From 509d73b27de54f6f16b1f77745ffe451c1cde0ea Mon Sep 17 00:00:00 2001 From: PP Date: Tue, 13 Jun 2023 18:08:45 +0800 Subject: [PATCH 001/232] merge branch v3.8.0-aot (#15421) * PR1: add explicit function return type (#15311) * PR4: add explicit function return type (#15314) * [ci skip][AUTO]: Automated code generating update: 8843bfe54cd3f8e6f84432948716c8d130ecb233 (#15314) (#15357) Co-authored-by: cocos-robot * add function return type * fix version checking * fix return type --------- Co-authored-by: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Co-authored-by: cocos-robot --- .eslintrc.yaml | 4 + cocos/2d/assembler/graphics/helper.ts | 8 +- cocos/2d/assembler/graphics/webgl/earcut.ts | 56 +-- .../graphics/webgl/graphics-assembler.ts | 4 +- cocos/2d/assembler/graphics/webgl/impl.ts | 34 +- cocos/2d/assembler/label/bmfontUtils.ts | 20 +- cocos/2d/assembler/label/font-utils.ts | 40 +-- cocos/2d/assembler/label/letter.ts | 7 +- cocos/2d/assembler/label/text-layout.ts | 2 +- cocos/2d/assembler/label/text-output-data.ts | 4 +- cocos/2d/assembler/label/text-processing.ts | 86 ++--- cocos/2d/assembler/label/text-style.ts | 2 +- cocos/2d/assembler/label/ttfUtils.ts | 20 +- cocos/2d/assembler/sprite/radial-filled.ts | 12 +- cocos/2d/assembler/sprite/tiled.ts | 2 +- cocos/2d/assembler/utils.ts | 4 +- cocos/2d/assets/bitmap-font.ts | 14 +- cocos/2d/assets/sprite-atlas.ts | 9 +- cocos/2d/assets/sprite-frame.ts | 112 +++--- cocos/2d/assets/ttf-font.ts | 11 +- cocos/2d/components/graphics.ts | 64 ++-- cocos/2d/components/label-outline.ts | 8 +- cocos/2d/components/label-shadow.ts | 10 +- cocos/2d/components/label.ts | 76 ++-- cocos/2d/components/mask.ts | 74 ++-- cocos/2d/components/rich-text.ts | 88 ++--- cocos/2d/components/sprite.ts | 50 +-- cocos/2d/components/ui-mesh-renderer.ts | 38 +- cocos/2d/components/ui-opacity.ts | 10 +- cocos/2d/components/ui-static-batch.ts | 13 +- cocos/2d/event/pointer-event-dispatcher.ts | 16 +- cocos/2d/framework/canvas.ts | 20 +- cocos/2d/framework/deprecated.ts | 21 +- cocos/2d/framework/render-root-2d.ts | 6 +- cocos/2d/framework/sprite-renderer.ts | 32 +- cocos/2d/framework/ui-component.ts | 16 +- cocos/2d/framework/ui-renderer-manager.ts | 8 +- cocos/2d/framework/ui-renderer.ts | 75 ++-- cocos/2d/framework/ui-transform.ts | 64 ++-- cocos/2d/renderer/batcher-2d.ts | 88 ++--- cocos/2d/renderer/buffer-accessor.ts | 16 +- cocos/2d/renderer/draw-batch.ts | 16 +- cocos/2d/renderer/mesh-buffer.ts | 44 +-- cocos/2d/renderer/render-data.ts | 109 +++--- cocos/2d/renderer/render-draw-info.ts | 54 +-- cocos/2d/renderer/render-entity.ts | 36 +- cocos/2d/renderer/static-vb-accessor.ts | 20 +- cocos/2d/renderer/stencil-manager.ts | 39 ++- cocos/2d/renderer/vertex-format.ts | 4 +- cocos/2d/utils/dynamic-atlas/atlas-manager.ts | 34 +- cocos/2d/utils/dynamic-atlas/atlas.ts | 18 +- cocos/2d/utils/font-loader.ts | 10 +- cocos/2d/utils/html-text-parser.ts | 14 +- cocos/2d/utils/text-utils.ts | 36 +- cocos/3d/assets/mesh.ts | 104 +++--- cocos/3d/assets/morph-rendering.ts | 89 +++-- cocos/3d/assets/skeleton.ts | 12 +- cocos/3d/framework/mesh-renderer.ts | 145 ++++---- cocos/3d/lights/deprecated.ts | 8 +- .../3d/lights/directional-light-component.ts | 42 +-- cocos/3d/lights/light-component.ts | 35 +- cocos/3d/lights/point-light-component.ts | 8 +- .../ranged-directional-light-component.ts | 4 +- cocos/3d/lights/sphere-light-component.ts | 10 +- cocos/3d/lights/spot-light-component.ts | 20 +- cocos/3d/lod/lodgroup-component.ts | 39 ++- cocos/3d/misc/batch-utils.ts | 4 +- cocos/3d/misc/buffer-blob.ts | 8 +- cocos/3d/misc/buffer.ts | 8 +- cocos/3d/misc/create-mesh.ts | 8 +- cocos/3d/misc/ppm.ts | 2 +- cocos/3d/misc/read-mesh.ts | 2 +- cocos/3d/models/baked-skinning-model.ts | 18 +- cocos/3d/models/morph-model.ts | 12 +- cocos/3d/models/skinning-model.ts | 26 +- .../reflection-probe-component.ts | 40 +-- .../reflection-probe-manager.ts | 56 +-- .../skeletal-animation/data-pool-manager.ts | 6 +- .../skeletal-animation-blending.ts | 45 +-- .../skeletal-animation-data-hub.ts | 2 +- .../skeletal-animation-state.ts | 10 +- .../skeletal-animation-utils.ts | 33 +- .../skeletal-animation/skeletal-animation.ts | 44 +-- .../skinned-mesh-batch-renderer.ts | 35 +- .../skinned-mesh-renderer.ts | 22 +- cocos/animation/animation-clip.ts | 157 +++++---- cocos/animation/animation-component.ts | 52 +-- cocos/animation/animation-curve.ts | 34 +- cocos/animation/animation-manager.ts | 20 +- cocos/animation/animation-state.ts | 76 ++-- cocos/animation/core/pose-allocator.ts | 12 +- cocos/animation/core/pose-heap-allocator.ts | 18 +- cocos/animation/core/pose.ts | 39 ++- .../core/shared-stack-based-allocator.ts | 36 +- cocos/animation/core/transform-array.ts | 38 +- cocos/animation/core/transform.ts | 40 +-- cocos/animation/cross-fade.ts | 20 +- cocos/animation/cubic-spline-value.ts | 10 +- .../embedded-animation-clip-player.ts | 2 +- .../embedded-particle-system-player.ts | 2 +- .../embedded-player/embedded-player.ts | 4 +- cocos/animation/event/event-emitter.ts | 2 +- .../exotic-animation/exotic-animation.ts | 80 ++--- cocos/animation/global-animation-manager.ts | 2 +- cocos/animation/legacy-clip-data.ts | 34 +- .../marionette/animation-controller.ts | 38 +- .../animation-graph-animation-clip-binding.ts | 32 +- .../marionette/animation-graph-context.ts | 118 +++---- .../marionette/animation-graph-variant.ts | 16 +- cocos/animation/marionette/animation-graph.ts | 80 ++--- cocos/animation/marionette/animation-mask.ts | 10 +- .../marionette/event/event-binding.ts | 6 +- cocos/animation/marionette/graph-debug.ts | 2 +- cocos/animation/marionette/graph-eval.ts | 26 +- .../marionette/motion/animation-blend-1d.ts | 10 +- .../marionette/motion/animation-blend-2d.ts | 18 +- .../motion/animation-blend-direct.ts | 12 +- .../marionette/motion/animation-blend.ts | 20 +- cocos/animation/marionette/motion/blend-1d.ts | 2 +- cocos/animation/marionette/motion/blend-2d.ts | 14 +- .../marionette/motion/clip-motion.ts | 18 +- cocos/animation/marionette/motion/motion.ts | 2 +- cocos/animation/marionette/ownership.ts | 6 +- cocos/animation/marionette/parametric.ts | 8 +- .../marionette/pose-graph/decorator/input.ts | 2 +- .../marionette/pose-graph/decorator/node.ts | 10 +- .../pose-graph/default-top-level-pose-node.ts | 18 +- .../foundation/authoring/input-authoring.ts | 22 +- .../foundation/authoring/node-authoring.ts | 2 +- .../pose-graph/foundation/node-shell.ts | 22 +- .../marionette/pose-graph/instantiation.ts | 29 +- .../motion-sync/runtime-motion-sync.ts | 8 +- .../marionette/pose-graph/op/index.ts | 1 - .../marionette/pose-graph/pose-graph.ts | 10 +- .../marionette/pose-graph/pose-node.ts | 8 +- .../pose-graph/pose-nodes/additively-blend.ts | 8 +- .../pose-graph/pose-nodes/apply-transform.ts | 28 +- .../pose-nodes/blend-in-proportion.ts | 6 +- .../pose-nodes/blend-two-pose-base.ts | 6 +- .../choose-pose/choose-pose-base.ts | 16 +- .../choose-pose/choose-pose-by-boolean.ts | 11 +- .../choose-pose/choose-pose-by-index.ts | 7 +- .../pose-graph/pose-nodes/copy-transform.ts | 6 +- .../pose-nodes/ik/solve-two-bone-ik.ts | 20 +- .../pose-nodes/ik/two-bone-ik-debugger.ts | 6 +- .../pose-nodes/ik/two-bone-ik-solver.ts | 14 +- .../pose-nodes/intensity-specification.ts | 8 +- .../pose-graph/pose-nodes/modify-pose-base.ts | 26 +- .../pose-graph/pose-nodes/play-motion.ts | 13 +- .../play-or-sample-motion-pose-node-shared.ts | 9 +- .../pose-graph/pose-nodes/sample-motion.ts | 4 +- .../pose-nodes/set-auxiliary-curve.ts | 6 +- .../pose-graph/pose-nodes/state-machine.ts | 11 +- .../pose-graph/pose-nodes/use-stashed-pose.ts | 12 +- .../marionette/pose-graph/pure-value-node.ts | 6 +- .../pure-value-nodes/get-variable.ts | 4 +- .../pose-graph/stash/runtime-stash.ts | 22 +- .../animation/marionette/pose-graph/utils.ts | 2 +- .../condition/binary-condition.ts | 6 +- .../binding/auxiliary-curve-binding.ts | 4 +- .../state-machine/condition/binding/editor.ts | 6 +- .../binding/state-motion-time-binding.ts | 2 +- .../condition/binding/state-weight-binding.ts | 2 +- .../condition/binding/variable-binding.ts | 2 +- .../condition/trigger-condition.ts | 4 +- .../condition/unary-condition.ts | 12 +- .../marionette/state-machine/motion-state.ts | 4 +- .../state-machine/state-machine-component.ts | 4 +- .../state-machine/state-machine-eval.ts | 146 ++++---- .../marionette/state-machine/state.ts | 10 +- cocos/animation/marionette/variable/basic.ts | 4 +- .../marionette/variable/primitive-variable.ts | 6 +- .../marionette/variable/quat-variable.ts | 6 +- .../marionette/variable/trigger-variable.ts | 8 +- .../marionette/variable/vec3-variable.ts | 6 +- cocos/animation/playable.ts | 28 +- cocos/animation/pose-output.ts | 4 +- cocos/animation/skeletal-animation-utils.ts | 6 +- cocos/animation/target-path.ts | 5 +- cocos/animation/tracks/array-track.ts | 14 +- cocos/animation/tracks/color-track.ts | 8 +- cocos/animation/tracks/object-track.ts | 2 +- cocos/animation/tracks/quat-track.ts | 8 +- cocos/animation/tracks/real-track.ts | 2 +- cocos/animation/tracks/size-track.ts | 8 +- cocos/animation/tracks/track.ts | 64 ++-- cocos/animation/tracks/untyped-track.ts | 10 +- cocos/animation/tracks/utils.ts | 2 +- cocos/animation/tracks/vector-track.ts | 20 +- cocos/animation/transform-utils.ts | 4 +- cocos/animation/types.ts | 2 +- .../value-proxy-factories/morph-weights.ts | 12 +- .../value-proxy-factories/uniform.ts | 8 +- cocos/animation/wrap.ts | 2 +- cocos/asset/asset-manager/asset-manager.ts | 40 +-- cocos/asset/asset-manager/builtin-res-mgr.ts | 18 +- cocos/asset/asset-manager/bundle.ts | 30 +- cocos/asset/asset-manager/cache.ts | 2 +- cocos/asset/asset-manager/config.ts | 26 +- cocos/asset/asset-manager/depend-util.ts | 6 +- cocos/asset/asset-manager/deprecated.ts | 96 +++--- .../asset/asset-manager/download-dom-image.ts | 4 +- cocos/asset/asset-manager/download-file.ts | 10 +- cocos/asset/asset-manager/download-script.ts | 4 +- cocos/asset/asset-manager/downloader.ts | 58 ++-- .../asset-manager/editor-path-replace.ts | 16 +- cocos/asset/asset-manager/factory.ts | 16 +- cocos/asset/asset-manager/fetch.ts | 12 +- cocos/asset/asset-manager/helper.ts | 4 +- cocos/asset/asset-manager/load.ts | 22 +- cocos/asset/asset-manager/pack-manager.ts | 10 +- cocos/asset/asset-manager/parser.ts | 24 +- cocos/asset/asset-manager/preprocess.ts | 2 +- cocos/asset/asset-manager/release-manager.ts | 24 +- cocos/asset/asset-manager/task.ts | 4 +- cocos/asset/asset-manager/url-transformer.ts | 12 +- cocos/asset/asset-manager/utilities.ts | 28 +- cocos/asset/assets/asset.ts | 28 +- cocos/asset/assets/buffer-asset.ts | 6 +- cocos/asset/assets/deprecation.ts | 3 +- cocos/asset/assets/effect-asset.ts | 22 +- cocos/asset/assets/image-asset.ts | 48 +-- cocos/asset/assets/material.ts | 50 +-- cocos/asset/assets/render-texture.ts | 20 +- cocos/asset/assets/rendering-sub-mesh.ts | 30 +- cocos/asset/assets/scene-asset.ts | 4 +- cocos/asset/assets/simple-texture.ts | 38 +- cocos/asset/assets/text-asset.ts | 2 +- cocos/asset/assets/texture-2d.ts | 41 ++- cocos/asset/assets/texture-base.ts | 28 +- cocos/asset/assets/texture-cube.ts | 46 +-- cocos/audio/audio-clip.ts | 37 +- cocos/audio/audio-downloader.ts | 4 +- cocos/audio/audio-manager.ts | 22 +- cocos/audio/audio-source.ts | 52 +-- cocos/core/algorithm/binary-search.ts | 6 +- cocos/core/algorithm/easing.ts | 70 ++-- cocos/core/algorithm/move.ts | 2 +- cocos/core/algorithm/murmurhash2_gc.ts | 4 +- cocos/core/algorithm/partition.ts | 2 +- cocos/core/curves/bezier.ts | 8 +- cocos/core/curves/curve.ts | 32 +- cocos/core/curves/gradient.ts | 20 +- cocos/core/curves/keyframe-curve.ts | 26 +- cocos/core/curves/object-curve.ts | 2 +- cocos/core/curves/quat-curve.ts | 8 +- cocos/core/curves/solve-cubic.ts | 4 +- cocos/core/data/class.ts | 36 +- cocos/core/data/decorators/editable.ts | 12 +- cocos/core/data/decorators/property.ts | 12 +- cocos/core/data/decorators/serializable.ts | 6 +- cocos/core/data/decorators/utils.ts | 14 +- cocos/core/data/editor-extendable.ts | 12 +- cocos/core/data/garbage-collection.ts | 12 +- cocos/core/data/gc-object.ts | 2 +- cocos/core/data/object.ts | 20 +- cocos/core/data/utils/asserts.ts | 2 +- cocos/core/data/utils/attribute.ts | 14 +- .../data/utils/compact-value-type-array.ts | 11 +- cocos/core/data/utils/compiler.ts | 4 +- cocos/core/data/utils/preprocess-class.ts | 26 +- cocos/core/data/utils/requiring-frame.ts | 8 +- cocos/core/deprecated.ts | 2 +- cocos/core/effect-settings.ts | 4 +- cocos/core/event/async-delegate.ts | 8 +- cocos/core/event/callbacks-invoker.ts | 34 +- cocos/core/event/event-target-factory.ts | 2 +- cocos/core/event/eventify.ts | 4 +- cocos/core/geometry/aabb.ts | 20 +- cocos/core/geometry/capsule.ts | 8 +- cocos/core/geometry/curve.ts | 24 +- cocos/core/geometry/deprecated-3.0.0.ts | 2 +- cocos/core/geometry/distance.ts | 6 +- cocos/core/geometry/frustum.ts | 18 +- cocos/core/geometry/geometry-native-ext.ts | 10 +- cocos/core/geometry/intersect.ts | 64 ++-- cocos/core/geometry/line.ts | 16 +- cocos/core/geometry/obb.ts | 16 +- cocos/core/geometry/plane.ts | 24 +- cocos/core/geometry/ray.ts | 4 +- cocos/core/geometry/sphere.ts | 24 +- cocos/core/geometry/spline.ts | 34 +- cocos/core/geometry/triangle.ts | 2 +- cocos/core/global-exports.ts | 2 +- cocos/core/legacy.ts | 2 +- cocos/core/math/affine-transform.ts | 22 +- cocos/core/math/bits.ts | 38 +- cocos/core/math/color.ts | 88 ++--- cocos/core/math/deprecated.ts | 2 +- cocos/core/math/mat3.ts | 82 ++--- cocos/core/math/mat4.ts | 132 +++---- cocos/core/math/math-base.ts | 2 +- cocos/core/math/math-native-ext.ts | 12 +- cocos/core/math/quat.ts | 102 +++--- cocos/core/math/rect.ts | 52 +-- cocos/core/math/size.ts | 24 +- cocos/core/math/utils.ts | 40 +-- cocos/core/math/vec2.ts | 126 +++---- cocos/core/math/vec3.ts | 154 ++++----- cocos/core/math/vec4.ts | 124 +++---- cocos/core/memop/cached-array.ts | 16 +- cocos/core/memop/pool.ts | 8 +- cocos/core/memop/recycle-pool.ts | 16 +- cocos/core/memop/scalable-container.ts | 10 +- cocos/core/platform/debug.ts | 52 +-- cocos/core/platform/screen.ts | 24 +- cocos/core/platform/sys.ts | 16 +- cocos/core/platform/visible-rect.ts | 2 +- cocos/core/scheduler.ts | 70 ++-- cocos/core/settings.ts | 16 +- cocos/core/system.ts | 10 +- cocos/core/utils/array.ts | 18 +- .../core/utils/coordinates-converts-utils.ts | 6 +- cocos/core/utils/decode-uuid.ts | 4 +- cocos/core/utils/id-generator.ts | 2 +- cocos/core/utils/internal.ts | 18 +- cocos/core/utils/js-typed.ts | 70 ++-- cocos/core/utils/jsb-utils.ts | 10 +- cocos/core/utils/misc.ts | 24 +- cocos/core/utils/mutable-forward-iterator.ts | 12 +- cocos/core/utils/path.ts | 8 +- cocos/core/utils/pool.ts | 6 +- cocos/core/utils/x-deprecated.ts | 58 ++-- cocos/core/value-types/bitmask.ts | 10 +- cocos/core/value-types/enum.ts | 8 +- cocos/core/value-types/value-type.ts | 6 +- cocos/dragon-bones/ArmatureCache.ts | 46 +-- cocos/dragon-bones/ArmatureDisplay.ts | 130 +++---- cocos/dragon-bones/ArmatureSystem.ts | 14 +- cocos/dragon-bones/AttachUtil.ts | 8 +- cocos/dragon-bones/CCArmatureDisplay.ts | 26 +- cocos/dragon-bones/CCFactory.ts | 28 +- cocos/dragon-bones/CCSlot.ts | 42 +-- cocos/dragon-bones/CCTextureData.ts | 12 +- cocos/dragon-bones/DragonBonesAsset.ts | 16 +- cocos/dragon-bones/DragonBonesAtlasAsset.ts | 12 +- cocos/dragon-bones/assembler/simple.ts | 18 +- cocos/game/deprecated.ts | 6 +- cocos/game/director.ts | 74 ++-- cocos/game/game.ts | 142 ++++---- cocos/game/splash-screen.ts | 38 +- cocos/gfx/base/define.ts | 114 +++--- cocos/gfx/base/descriptor-set-layout.ts | 6 +- cocos/gfx/base/descriptor-set.ts | 14 +- cocos/gfx/base/device.ts | 6 +- cocos/gfx/base/input-assembler.ts | 14 +- cocos/gfx/base/pipeline-layout.ts | 2 +- cocos/gfx/base/pipeline-sub-state.ts | 30 +- cocos/gfx/base/render-pass.ts | 2 +- cocos/gfx/base/shader.ts | 6 +- cocos/gfx/base/states/buffer-barrier.ts | 2 +- cocos/gfx/base/states/general-barrier.ts | 2 +- cocos/gfx/base/states/sampler.ts | 6 +- cocos/gfx/base/states/texture-barrier.ts | 2 +- cocos/gfx/base/swapchain.ts | 10 +- cocos/gfx/device-manager.ts | 10 +- cocos/gfx/empty/empty-buffer.ts | 8 +- cocos/gfx/empty/empty-command-buffer.ts | 44 +-- .../gfx/empty/empty-descriptor-set-layout.ts | 4 +- cocos/gfx/empty/empty-descriptor-set.ts | 6 +- cocos/gfx/empty/empty-device.ts | 18 +- cocos/gfx/empty/empty-framebuffer.ts | 4 +- cocos/gfx/empty/empty-input-assembler.ts | 4 +- cocos/gfx/empty/empty-pipeline-layout.ts | 4 +- cocos/gfx/empty/empty-pipeline-state.ts | 6 +- cocos/gfx/empty/empty-queue.ts | 6 +- cocos/gfx/empty/empty-render-pass.ts | 4 +- cocos/gfx/empty/empty-shader.ts | 4 +- cocos/gfx/empty/empty-swapchain.ts | 4 +- cocos/gfx/empty/empty-texture.ts | 8 +- cocos/gfx/webgl/webgl-buffer.ts | 8 +- cocos/gfx/webgl/webgl-command-allocator.ts | 10 +- cocos/gfx/webgl/webgl-command-buffer.ts | 46 +-- cocos/gfx/webgl/webgl-commands.ts | 60 ++-- cocos/gfx/webgl/webgl-define.ts | 4 +- .../gfx/webgl/webgl-descriptor-set-layout.ts | 6 +- cocos/gfx/webgl/webgl-descriptor-set.ts | 6 +- cocos/gfx/webgl/webgl-device.ts | 37 +- cocos/gfx/webgl/webgl-framebuffer.ts | 8 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 14 +- cocos/gfx/webgl/webgl-input-assembler.ts | 4 +- cocos/gfx/webgl/webgl-pipeline-layout.ts | 6 +- cocos/gfx/webgl/webgl-pipeline-state.ts | 6 +- .../gfx/webgl/webgl-primary-command-buffer.ts | 16 +- cocos/gfx/webgl/webgl-queue.ts | 8 +- cocos/gfx/webgl/webgl-render-pass.ts | 4 +- cocos/gfx/webgl/webgl-shader.ts | 4 +- cocos/gfx/webgl/webgl-state-cache.ts | 2 +- cocos/gfx/webgl/webgl-swapchain.ts | 14 +- cocos/gfx/webgl/webgl-texture.ts | 8 +- cocos/gfx/webgl2/states/webgl2-sampler.ts | 2 +- cocos/gfx/webgl2/webgl2-buffer.ts | 8 +- cocos/gfx/webgl2/webgl2-command-allocator.ts | 10 +- cocos/gfx/webgl2/webgl2-command-buffer.ts | 46 +-- cocos/gfx/webgl2/webgl2-commands.ts | 72 ++-- cocos/gfx/webgl2/webgl2-define.ts | 4 +- .../webgl2/webgl2-descriptor-set-layout.ts | 6 +- cocos/gfx/webgl2/webgl2-descriptor-set.ts | 6 +- cocos/gfx/webgl2/webgl2-device.ts | 37 +- cocos/gfx/webgl2/webgl2-framebuffer.ts | 8 +- cocos/gfx/webgl2/webgl2-gpu-objects.ts | 12 +- cocos/gfx/webgl2/webgl2-input-assembler.ts | 4 +- cocos/gfx/webgl2/webgl2-pipeline-layout.ts | 6 +- cocos/gfx/webgl2/webgl2-pipeline-state.ts | 6 +- .../webgl2/webgl2-primary-command-buffer.ts | 16 +- cocos/gfx/webgl2/webgl2-queue.ts | 8 +- cocos/gfx/webgl2/webgl2-render-pass.ts | 4 +- cocos/gfx/webgl2/webgl2-shader.ts | 4 +- cocos/gfx/webgl2/webgl2-state-cache.ts | 2 +- cocos/gfx/webgl2/webgl2-swapchain.ts | 14 +- cocos/gfx/webgl2/webgl2-texture.ts | 8 +- cocos/gi/light-probe/auto-placement.ts | 6 +- cocos/gi/light-probe/delaunay.ts | 48 +-- cocos/gi/light-probe/light-probe-group.ts | 12 +- cocos/gi/light-probe/light-probe.ts | 38 +- cocos/gi/light-probe/polynomial-solver.ts | 4 +- cocos/gi/light-probe/sh.ts | 26 +- cocos/input/input.ts | 76 ++-- cocos/input/system-event.ts | 32 +- cocos/input/types/event/event-keyboard.ts | 2 +- cocos/input/types/event/event-mouse.ts | 44 +-- cocos/input/types/event/event-touch.ts | 34 +- cocos/input/types/event/event.ts | 10 +- cocos/input/types/touch.ts | 40 +-- cocos/misc/camera-component.ts | 79 ++--- cocos/misc/intersect.ts | 18 +- cocos/misc/missing-script.ts | 4 +- cocos/misc/model-renderer.ts | 14 +- cocos/misc/renderer.ts | 14 +- cocos/native-binding/decorators.ts | 2 +- .../particle-2d/motion-streak-2d-assembler.ts | 22 +- cocos/particle-2d/motion-streak-2d.ts | 32 +- cocos/particle-2d/particle-simulator-2d.ts | 20 +- cocos/particle-2d/particle-system-2d.ts | 78 +++-- cocos/particle-2d/png-reader.ts | 20 +- cocos/particle-2d/tiff-reader.ts | 34 +- cocos/particle/animator/color-overtime.ts | 4 +- cocos/particle/animator/curve-range.ts | 28 +- cocos/particle/animator/force-overtime.ts | 6 +- cocos/particle/animator/gradient-range.ts | 12 +- .../animator/limit-velocity-overtime.ts | 8 +- cocos/particle/animator/noise-module.ts | 32 +- cocos/particle/animator/rotation-overtime.ts | 8 +- cocos/particle/animator/size-overtime.ts | 4 +- cocos/particle/animator/texture-animation.ts | 18 +- cocos/particle/animator/velocity-overtime.ts | 6 +- cocos/particle/billboard.ts | 20 +- cocos/particle/burst.ts | 10 +- cocos/particle/emitter/shape-module.ts | 34 +- cocos/particle/line.ts | 30 +- cocos/particle/models/line-model.ts | 12 +- cocos/particle/models/particle-batch-model.ts | 56 +-- cocos/particle/noise.ts | 20 +- cocos/particle/particle-culler.ts | 26 +- cocos/particle/particle-general-function.ts | 26 +- cocos/particle/particle-system.ts | 128 +++---- cocos/particle/particle-utils.ts | 14 +- cocos/particle/particle.ts | 6 +- .../renderer/particle-system-renderer-base.ts | 28 +- .../renderer/particle-system-renderer-cpu.ts | 68 ++-- .../renderer/particle-system-renderer-data.ts | 30 +- .../renderer/particle-system-renderer-gpu.ts | 50 +-- cocos/particle/renderer/trail.ts | 60 ++-- .../physics-2d/box2d/joints/distance-joint.ts | 4 +- cocos/physics-2d/box2d/joints/fixed-joint.ts | 6 +- cocos/physics-2d/box2d/joints/hinge-joint.ts | 16 +- cocos/physics-2d/box2d/joints/joint-2d.ts | 20 +- cocos/physics-2d/box2d/joints/mouse-joint.ts | 24 +- .../physics-2d/box2d/joints/relative-joint.ts | 12 +- cocos/physics-2d/box2d/joints/slider-joint.ts | 16 +- cocos/physics-2d/box2d/joints/spring-joint.ts | 8 +- cocos/physics-2d/box2d/joints/wheel-joint.ts | 12 +- cocos/physics-2d/box2d/physics-contact.ts | 32 +- cocos/physics-2d/box2d/physics-world.ts | 26 +- .../platform/physics-aabb-query-callback.ts | 8 +- .../platform/physics-contact-listener.ts | 16 +- .../box2d/platform/physics-debug-draw.ts | 28 +- .../platform/physics-ray-cast-callback.ts | 12 +- cocos/physics-2d/box2d/rigid-body.ts | 74 ++-- cocos/physics-2d/box2d/shapes/box-shape-2d.ts | 2 +- .../box2d/shapes/circle-shape-2d.ts | 6 +- .../box2d/shapes/polygon-shape-2d.ts | 2 +- cocos/physics-2d/box2d/shapes/shape-2d.ts | 28 +- cocos/physics-2d/builtin/builtin-contact.ts | 4 +- cocos/physics-2d/builtin/builtin-world.ts | 30 +- .../physics-2d/builtin/shapes/box-shape-2d.ts | 6 +- .../builtin/shapes/circle-shape-2d.ts | 8 +- .../builtin/shapes/polygon-shape-2d.ts | 6 +- cocos/physics-2d/builtin/shapes/shape-2d.ts | 24 +- .../components/colliders/box-collider-2d.ts | 2 +- .../colliders/circle-collider-2d.ts | 2 +- .../components/colliders/collider-2d.ts | 24 +- .../colliders/polygon-collider-2d.ts | 2 +- .../components/joints/distance-joint-2d.ts | 4 +- .../framework/components/joints/joint-2d.ts | 14 +- .../components/joints/mouse-joint-2d.ts | 4 +- .../components/joints/spring-joint-2d.ts | 8 +- .../framework/components/rigid-body-2d.ts | 30 +- .../physics-2d/framework/physics-selector.ts | 10 +- cocos/physics-2d/framework/physics-system.ts | 35 +- .../framework/utils/polygon-partition.ts | 20 +- .../framework/utils/polygon-separator.ts | 34 +- .../bullet/bullet-bvh-triangle-mesh-shape.ts | 4 +- cocos/physics/bullet/bullet-cache.ts | 8 +- cocos/physics/bullet/bullet-env.ts | 4 +- cocos/physics/bullet/bullet-rigid-body.ts | 38 +- cocos/physics/bullet/bullet-shared-body.ts | 66 ++-- cocos/physics/bullet/bullet-utils.ts | 4 +- cocos/physics/bullet/bullet-world.ts | 32 +- .../bullet-character-controller.ts | 14 +- .../bullet-configurable-constraint.ts | 6 +- .../bullet/constraints/bullet-constraint.ts | 4 +- .../constraints/bullet-fixed-constraint.ts | 8 +- .../constraints/bullet-hinge-constraint.ts | 10 +- .../constraints/bullet-p2p-constraint.ts | 4 +- cocos/physics/bullet/instantiated.ts | 10 +- .../physics/bullet/shapes/bullet-box-shape.ts | 12 +- .../bullet/shapes/bullet-capsule-shape.ts | 14 +- .../bullet/shapes/bullet-cone-shape.ts | 16 +- .../bullet/shapes/bullet-cylinder-shape.ts | 14 +- .../bullet/shapes/bullet-plane-shape.ts | 10 +- cocos/physics/bullet/shapes/bullet-shape.ts | 38 +- .../bullet/shapes/bullet-simplex-shape.ts | 12 +- .../bullet/shapes/bullet-sphere-shape.ts | 12 +- .../bullet/shapes/bullet-terrain-shape.ts | 8 +- .../bullet/shapes/bullet-trimesh-shape.ts | 10 +- cocos/physics/cannon/cannon-rigid-body.ts | 48 +-- cocos/physics/cannon/cannon-shared-body.ts | 22 +- cocos/physics/cannon/cannon-util.ts | 6 +- cocos/physics/cannon/cannon-world.ts | 20 +- .../cannon/constraints/cannon-constraint.ts | 16 +- .../constraints/cannon-hinge-constraint.ts | 10 +- .../constraints/cannon-lock-constraint.ts | 2 +- .../cannon-point-to-point-constraint.ts | 10 +- .../physics/cannon/shapes/cannon-box-shape.ts | 8 +- .../cannon/shapes/cannon-cone-shape.ts | 14 +- .../cannon/shapes/cannon-cylinder-shape.ts | 14 +- .../cannon/shapes/cannon-plane-shape.ts | 12 +- cocos/physics/cannon/shapes/cannon-shape.ts | 40 +-- .../cannon/shapes/cannon-simplex-shape.ts | 16 +- .../cannon/shapes/cannon-sphere-shape.ts | 8 +- .../cannon/shapes/cannon-terrain-shape.ts | 14 +- .../cannon/shapes/cannon-trimesh-shape.ts | 48 +-- cocos/physics/cocos/builtin-rigid-body.ts | 38 +- cocos/physics/cocos/builtin-shared-body.ts | 12 +- cocos/physics/cocos/builtin-world.ts | 14 +- .../physics/cocos/shapes/builtin-box-shape.ts | 10 +- .../cocos/shapes/builtin-capsule-shape.ts | 14 +- cocos/physics/cocos/shapes/builtin-shape.ts | 32 +- .../cocos/shapes/builtin-sphere-shape.ts | 10 +- .../framework/assets/physics-material.ts | 12 +- .../box-character-controller.ts | 6 +- .../capsule-character-controller.ts | 4 +- .../character-controller.ts | 32 +- .../components/colliders/box-collider.ts | 4 +- .../components/colliders/capsule-collider.ts | 16 +- .../components/colliders/collider.ts | 40 +-- .../components/colliders/cone-collider.ts | 8 +- .../components/colliders/cylinder-collider.ts | 8 +- .../components/colliders/mesh-collider.ts | 8 +- .../components/colliders/plane-collider.ts | 8 +- .../components/colliders/simplex-collider.ts | 16 +- .../components/colliders/sphere-collider.ts | 4 +- .../components/colliders/terrain-collider.ts | 6 +- .../framework/components/constant-force.ts | 14 +- .../constraints/configurable-constraint.ts | 84 ++--- .../components/constraints/constraint.ts | 10 +- .../constraints/point-to-point-constraint.ts | 4 +- .../framework/components/rigid-body.ts | 62 ++-- cocos/physics/framework/physics-ray-result.ts | 8 +- cocos/physics/framework/physics-selector.ts | 16 +- cocos/physics/framework/physics-system.ts | 56 +-- .../physx-character-controller.ts | 14 +- .../physx/joints/physx-configurable-joint.ts | 24 +- .../physics/physx/joints/physx-fixed-joint.ts | 6 +- cocos/physics/physx/joints/physx-joint.ts | 6 +- .../physx/joints/physx-revolute-joint.ts | 6 +- .../physx/joints/physx-spherical-joint.ts | 4 +- cocos/physics/physx/physx-adapter.ts | 72 ++-- cocos/physics/physx/physx-rigid-body.ts | 2 +- cocos/physics/physx/physx-shared-body.ts | 20 +- cocos/physics/physx/physx-world.ts | 6 +- cocos/physics/physx/shapes/physx-shape.ts | 12 +- .../physx/shapes/physx-sphere-shape.ts | 8 +- .../physx/shapes/physx-terrain-shape.ts | 16 +- .../physx/shapes/physx-trimesh-shape.ts | 12 +- cocos/physics/utils/array-collision-matrix.ts | 6 +- cocos/physics/utils/tuple-dictionary.ts | 6 +- cocos/physics/utils/util.ts | 8 +- cocos/primitive/box.ts | 2 +- cocos/primitive/capsule.ts | 8 +- cocos/primitive/cylinder.ts | 4 +- cocos/primitive/primitive.ts | 2 +- cocos/primitive/torus.ts | 2 +- cocos/primitive/transform.ts | 6 +- cocos/primitive/utils.ts | 10 +- cocos/profiler/counter.ts | 10 +- cocos/profiler/perf-counter.ts | 8 +- cocos/profiler/profiler.ts | 28 +- cocos/render-scene/config.ts | 6 +- cocos/render-scene/core/material-instance.ts | 10 +- cocos/render-scene/core/memory-pools.ts | 4 +- cocos/render-scene/core/native-pools.ts | 8 +- cocos/render-scene/core/pass-instance.ts | 12 +- cocos/render-scene/core/pass.ts | 18 +- cocos/render-scene/core/program-lib.jsb.ts | 2 +- cocos/render-scene/core/program-lib.ts | 60 ++-- cocos/render-scene/core/program-utils.ts | 36 +- cocos/render-scene/core/render-scene.ts | 102 +++--- cocos/render-scene/core/render-window.ts | 22 +- .../render-scene/core/texture-buffer-pool.ts | 20 +- cocos/render-scene/scene/ambient.ts | 2 +- cocos/render-scene/scene/camera.ts | 91 ++--- cocos/render-scene/scene/directional-light.ts | 44 +-- cocos/render-scene/scene/fog.ts | 42 +-- cocos/render-scene/scene/light.ts | 22 +- cocos/render-scene/scene/lod-group.ts | 26 +- cocos/render-scene/scene/model.ts | 108 +++--- cocos/render-scene/scene/octree.ts | 2 +- cocos/render-scene/scene/point-light.ts | 10 +- .../scene/ranged-directional-light.ts | 8 +- cocos/render-scene/scene/reflection-probe.ts | 74 ++-- cocos/render-scene/scene/shadows.ts | 10 +- cocos/render-scene/scene/skin.ts | 2 +- cocos/render-scene/scene/skybox.ts | 26 +- cocos/render-scene/scene/sphere-light.ts | 10 +- cocos/render-scene/scene/spot-light.ts | 27 +- cocos/render-scene/scene/submodel.ts | 18 +- cocos/render-scene/utils.ts | 4 +- cocos/rendering/custom/builtin-pipelines.ts | 8 +- cocos/rendering/custom/compiler.ts | 82 ++--- cocos/rendering/custom/custom-pipeline.ts | 12 +- cocos/rendering/custom/debug.ts | 52 +-- cocos/rendering/custom/define.ts | 130 +++---- cocos/rendering/custom/executor.ts | 324 +++++++++--------- cocos/rendering/custom/graph.ts | 14 +- cocos/rendering/custom/index.ts | 8 +- cocos/rendering/custom/layout-graph-utils.ts | 66 ++-- cocos/rendering/custom/layout-graph.ts | 74 ++-- cocos/rendering/custom/pipeline-define.ts | 46 +-- cocos/rendering/custom/render-graph.ts | 12 +- cocos/rendering/custom/serialization.ts | 20 +- cocos/rendering/custom/types.ts | 48 +-- cocos/rendering/custom/utils.ts | 10 +- cocos/rendering/custom/web-pipeline.ts | 132 +++---- cocos/rendering/custom/web-program-library.ts | 32 +- cocos/rendering/custom/web-scene.ts | 14 +- cocos/rendering/debug-view.ts | 16 +- cocos/rendering/deferred/bloom-stage.ts | 14 +- .../deferred/deferred-pipeline-scene-data.ts | 24 +- cocos/rendering/deferred/deferred-pipeline.ts | 16 +- cocos/rendering/deferred/gbuffer-stage.ts | 6 +- cocos/rendering/deferred/lighting-stage.ts | 10 +- cocos/rendering/deferred/main-flow.ts | 6 +- cocos/rendering/deferred/postprocess-stage.ts | 6 +- cocos/rendering/define.ts | 18 +- cocos/rendering/forward/forward-flow.ts | 6 +- cocos/rendering/forward/forward-pipeline.ts | 8 +- cocos/rendering/forward/forward-stage.ts | 10 +- cocos/rendering/geometry-renderer.ts | 66 ++-- .../global-descriptor-set-manager.ts | 24 +- cocos/rendering/index.jsb.ts | 10 +- cocos/rendering/index.ts | 2 +- cocos/rendering/instanced-buffer.ts | 8 +- cocos/rendering/pass-phase.ts | 4 +- cocos/rendering/pipeline-funcs.ts | 8 +- cocos/rendering/pipeline-scene-data.ts | 26 +- cocos/rendering/pipeline-state-manager.ts | 2 +- cocos/rendering/pipeline-ubo.ts | 28 +- cocos/rendering/planar-shadow-queue.ts | 6 +- .../post-process/components/blit-screen.ts | 10 +- .../post-process/components/bloom.ts | 6 +- .../post-process/components/color-grading.ts | 4 +- .../rendering/post-process/components/fsr.ts | 2 +- .../rendering/post-process/components/hbao.ts | 10 +- .../components/post-process-setting.ts | 6 +- .../post-process/components/post-process.ts | 12 +- .../post-process/passes/base-pass.ts | 16 +- .../post-process/passes/blit-screen-pass.ts | 6 +- .../post-process/passes/bloom-pass.ts | 4 +- .../post-process/passes/color-grading-pass.ts | 4 +- .../post-process/passes/forward-final-pass.ts | 2 +- .../post-process/passes/forward-pass.ts | 6 +- .../passes/forward-transparency-pass.ts | 4 +- .../forward-transparency-simple-pass.ts | 4 +- .../rendering/post-process/passes/fsr-pass.ts | 4 +- .../post-process/passes/fxaa-pass.ts | 2 +- .../post-process/passes/hbao-pass.ts | 28 +- .../post-process/passes/setting-pass.ts | 6 +- .../post-process/passes/skin-pass.ts | 24 +- .../rendering/post-process/passes/taa-pass.ts | 10 +- .../post-process/passes/tone-mapping-pass.ts | 2 +- .../post-process/post-process-builder.ts | 34 +- .../post-process/utils/pass-context.ts | 22 +- .../reflection-probe/reflection-probe-flow.ts | 8 +- .../reflection-probe-stage.ts | 10 +- .../rendering/render-additive-light-queue.ts | 28 +- cocos/rendering/render-flow.ts | 6 +- cocos/rendering/render-instanced-queue.ts | 8 +- cocos/rendering/render-pipeline.ts | 62 ++-- cocos/rendering/render-queue.ts | 18 +- .../render-reflection-probe-queue.ts | 10 +- .../render-shadow-map-batched-queue.ts | 8 +- cocos/rendering/render-stage.ts | 8 +- cocos/rendering/scene-culling.ts | 12 +- cocos/rendering/shadow/csm-layers.ts | 52 +-- cocos/rendering/shadow/shadow-flow.ts | 14 +- cocos/rendering/shadow/shadow-stage.ts | 10 +- cocos/rendering/ui-phase.ts | 4 +- cocos/root.ts | 48 +-- cocos/scene-graph/component-event-handler.ts | 12 +- cocos/scene-graph/component-scheduler.ts | 70 ++-- cocos/scene-graph/component.ts | 38 +- cocos/scene-graph/deprecated.ts | 29 +- cocos/scene-graph/layers.ts | 6 +- cocos/scene-graph/node-activator.ts | 42 +-- cocos/scene-graph/node-dev.ts | 14 +- cocos/scene-graph/node-event-processor.ts | 52 +-- cocos/scene-graph/node-ui-properties.ts | 14 +- cocos/scene-graph/node.ts | 142 ++++---- cocos/scene-graph/prefab/prefab-info.ts | 12 +- cocos/scene-graph/prefab/prefab.ts | 8 +- cocos/scene-graph/prefab/utils.ts | 22 +- cocos/scene-graph/scene-globals.ts | 116 +++---- cocos/scene-graph/scene.ts | 22 +- cocos/serialization/ccon.ts | 27 +- cocos/serialization/deserialize-dynamic.ts | 52 +-- cocos/serialization/deserialize.ts | 64 ++-- cocos/serialization/instantiate-jit.ts | 38 +- cocos/serialization/instantiate.ts | 10 +- cocos/serialization/report-missing-class.ts | 2 +- cocos/sorting/sorting-layers.ts | 6 +- cocos/sorting/sorting.ts | 8 +- cocos/spine/assembler/simple.ts | 9 +- cocos/spine/attach-util.ts | 8 +- cocos/spine/lib/instantiated.ts | 8 +- cocos/spine/lib/spine-core.d.ts | 12 +- cocos/spine/lib/spine-define.ts | 146 ++++---- cocos/spine/skeleton-cache.ts | 26 +- cocos/spine/skeleton-data.ts | 18 +- cocos/spine/skeleton-system.ts | 10 +- cocos/spine/skeleton.ts | 143 ++++---- cocos/spine/track-entry-listeners.ts | 2 +- cocos/spine/vertex-effect-delegate.ts | 10 +- cocos/terrain/height-field.ts | 8 +- cocos/terrain/terrain-asset.ts | 74 ++-- cocos/terrain/terrain-lod.ts | 20 +- cocos/terrain/terrain.ts | 242 ++++++------- cocos/tiledmap/assembler/simple.ts | 10 +- cocos/tiledmap/tiled-layer.ts | 129 ++++--- cocos/tiledmap/tiled-map.ts | 46 +-- cocos/tiledmap/tiled-object-group.ts | 20 +- cocos/tiledmap/tiled-tile.ts | 12 +- cocos/tiledmap/tiled-types.ts | 10 +- cocos/tiledmap/tiled-utils.ts | 2 +- cocos/tiledmap/tmx-xml-parser.ts | 104 +++--- cocos/tween/actions/action-instant.ts | 46 +-- cocos/tween/actions/action-interval.ts | 104 +++--- cocos/tween/actions/action-manager.ts | 38 +- cocos/tween/actions/action.ts | 42 +-- cocos/tween/set-action.ts | 6 +- cocos/tween/tween-action.ts | 12 +- cocos/tween/tween-system.ts | 4 +- cocos/tween/tween.ts | 22 +- cocos/ui/block-input-events.ts | 6 +- cocos/ui/button.ts | 90 ++--- cocos/ui/editbox/edit-box-impl-base.ts | 22 +- cocos/ui/editbox/edit-box-impl.ts | 64 ++-- cocos/ui/editbox/edit-box.ts | 94 ++--- cocos/ui/editbox/tabIndexUtil.ts | 8 +- cocos/ui/layout.ts | 104 +++--- cocos/ui/page-view-indicator.ts | 18 +- cocos/ui/page-view.ts | 76 ++-- cocos/ui/progress-bar.ts | 14 +- cocos/ui/safe-area.ts | 6 +- cocos/ui/scroll-bar.ts | 44 +-- cocos/ui/scroll-view.ts | 164 ++++----- cocos/ui/slider.ts | 40 +-- cocos/ui/sub-context-view.ts | 28 +- cocos/ui/toggle-container.ts | 14 +- cocos/ui/toggle.ts | 20 +- cocos/ui/ui-coordinate-tracker.ts | 14 +- cocos/ui/view.ts | 70 ++-- cocos/ui/widget-manager.ts | 22 +- cocos/ui/widget.ts | 118 ++++--- cocos/video/video-downloader.ts | 8 +- cocos/video/video-player-impl-web.ts | 52 +-- cocos/video/video-player-impl.ts | 53 +-- cocos/video/video-player.ts | 68 ++-- cocos/web-view/web-view-impl-manager.ts | 2 +- cocos/web-view/web-view-impl-web.ts | 22 +- cocos/web-view/web-view-impl.ts | 17 +- cocos/web-view/web-view.ts | 28 +- exports/physics-cannon.ts | 4 +- extensions/ccpool/node-pool.ts | 6 +- external/compression/gzip.d.ts | 6 +- package-lock.json | 2 +- package.json | 2 +- pal/audio/audio-buffer-manager.ts | 6 +- pal/audio/audio-timer.ts | 18 +- pal/audio/minigame/player-minigame.ts | 44 +-- pal/audio/minigame/player-web.ts | 28 +- pal/audio/minigame/player.ts | 18 +- pal/audio/native/player.ts | 24 +- pal/audio/operation-queue.ts | 2 +- pal/audio/type.ts | 4 +- pal/audio/web/player-dom.ts | 34 +- pal/audio/web/player-web.ts | 60 ++-- pal/audio/web/player.ts | 18 +- pal/env/native/env.ts | 4 +- pal/env/web/env.ts | 2 +- pal/input/minigame/accelerometer-input.ts | 14 +- pal/input/minigame/gamepad-input.ts | 134 ++++---- pal/input/minigame/handheld-input.ts | 12 +- pal/input/minigame/handle-input.ts | 112 +++--- pal/input/minigame/hmd-input.ts | 28 +- pal/input/minigame/keyboard-input.ts | 6 +- pal/input/minigame/mouse-input.ts | 8 +- pal/input/minigame/touch-input.ts | 6 +- pal/input/native/accelerometer-input.ts | 10 +- pal/input/native/gamepad-input.ts | 148 ++++---- pal/input/native/handheld-input.ts | 18 +- pal/input/native/handle-input.ts | 122 +++---- pal/input/native/hmd-input.ts | 34 +- pal/input/native/keyboard-input.ts | 14 +- pal/input/native/mouse-input.ts | 18 +- pal/input/native/touch-input.ts | 6 +- pal/input/touch-manager.ts | 6 +- pal/input/web/accelerometer-input.ts | 14 +- pal/input/web/gamepad-input.ts | 154 ++++----- pal/input/web/handheld-input.ts | 12 +- pal/input/web/handle-input.ts | 112 +++--- pal/input/web/hmd-input.ts | 36 +- pal/input/web/keyboard-input.ts | 14 +- pal/input/web/mouse-input.ts | 20 +- pal/input/web/touch-input.ts | 6 +- pal/minigame/alipay.ts | 20 +- pal/minigame/baidu.ts | 8 +- pal/minigame/bytedance.ts | 12 +- pal/minigame/runtime.ts | 10 +- pal/minigame/taobao.ts | 24 +- pal/minigame/taobao_minigame.ts | 24 +- pal/minigame/wechat.ts | 18 +- pal/minigame/wechat_mini_program.ts | 22 +- pal/minigame/xiaomi.ts | 20 +- pal/pacer/pacer-minigame.ts | 2 +- pal/pacer/pacer-native.ts | 2 +- pal/pacer/pacer-web.ts | 8 +- pal/screen-adapter/minigame/screen-adapter.ts | 8 +- pal/screen-adapter/native/screen-adapter.ts | 14 +- pal/screen-adapter/web/screen-adapter.ts | 34 +- pal/system-info/minigame/system-info.ts | 18 +- pal/system-info/native/system-info.ts | 16 +- pal/system-info/web/system-info.ts | 14 +- pal/utils.ts | 8 +- 855 files changed, 10398 insertions(+), 10220 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index bb227c333ee..b3b7303f203 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -112,6 +112,9 @@ rules: # TODO: this is just too much work '@typescript-eslint/explicit-module-boundary-types': off + # NOTE: We don't want to rely on TS automatic type inference + '@typescript-eslint/no-inferrable-types': off + # TODO: sadly we still rely heavily on legacyCC '@typescript-eslint/no-unsafe-assignment': off '@typescript-eslint/no-unsafe-call': off @@ -143,3 +146,4 @@ rules: # Prefer the interface style. '@typescript-eslint/consistent-type-definitions': [error, interface] + '@typescript-eslint/explicit-function-return-type': [error] diff --git a/cocos/2d/assembler/graphics/helper.ts b/cocos/2d/assembler/graphics/helper.ts index cfa60109431..a73f5edb0bb 100644 --- a/cocos/2d/assembler/graphics/helper.ts +++ b/cocos/2d/assembler/graphics/helper.ts @@ -35,7 +35,7 @@ const sign = Math.sign; const KAPPA90 = 0.5522847493; -export function arc (ctx: Impl, cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean) { +export function arc (ctx: Impl, cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean): void { counterclockwise = counterclockwise || false; let a = 0; @@ -97,7 +97,7 @@ export function arc (ctx: Impl, cx: number, cy: number, r: number, startAngle: n } } -export function ellipse (ctx: Impl, cx: number, cy: number, rx: number, ry: number) { +export function ellipse (ctx: Impl, cx: number, cy: number, rx: number, ry: number): void { ctx.moveTo(cx - rx, cy); ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry); ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy); @@ -106,7 +106,7 @@ export function ellipse (ctx: Impl, cx: number, cy: number, rx: number, ry: numb ctx.close(); } -export function roundRect (ctx: Impl, x: number, y: number, w: number, h: number, r: number) { +export function roundRect (ctx: Impl, x: number, y: number, w: number, h: number, r: number): void { if (r < 0.1) { ctx.rect(x, y, w, h); } else { @@ -132,7 +132,7 @@ export function tesselateBezier ( x3: number, y3: number, x4: number, y4: number, level: number, type: number, -) { +): void { let x12 = 0; let y12 = 0; let x23 = 0; diff --git a/cocos/2d/assembler/graphics/webgl/earcut.ts b/cocos/2d/assembler/graphics/webgl/earcut.ts index bb865e70559..d8dc495c9f6 100644 --- a/cocos/2d/assembler/graphics/webgl/earcut.ts +++ b/cocos/2d/assembler/graphics/webgl/earcut.ts @@ -52,7 +52,7 @@ class Aim { } // create a circular doubly linked list from polygon points in the specified winding order -function linkedList (datas: number[], start: number, end: number, dim: number, clockwise: boolean) { +function linkedList (datas: number[], start: number, end: number, dim: number, clockwise: boolean): Aim | null { let i = 0; let last: Aim | null = null; @@ -75,7 +75,7 @@ function linkedList (datas: number[], start: number, end: number, dim: number, c } // eliminate colinear or duplicate points -function filterPoints (start: Aim | null, end: Aim | null = null) { +function filterPoints (start: Aim | null, end: Aim | null = null): Aim | null { if (!start) { return start; } @@ -105,7 +105,7 @@ function filterPoints (start: Aim | null, end: Aim | null = null) { } // main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked (ear: Aim | null, triangles: number[], dim: number, minX: number, minY: number, size: number, pass = 0) { +function earcutLinked (ear: Aim | null, triangles: number[], dim: number, minX: number, minY: number, size: number, pass = 0): void { if (!ear) { return; } @@ -163,7 +163,7 @@ function earcutLinked (ear: Aim | null, triangles: number[], dim: number, minX: } // check whether a polygon node forms a valid ear with adjacent nodes -function isEar (ear: Aim) { +function isEar (ear: Aim): boolean { const a = ear.prev!; const b = ear; const c = ear.next!; @@ -182,7 +182,7 @@ function isEar (ear: Aim) { return true; } -function isEarHashed (ear: Aim, minX: number, minY: number, size) { +function isEarHashed (ear: Aim, minX: number, minY: number, size): boolean { const a = ear.prev!; const b = ear; const c = ear.next!; @@ -226,7 +226,7 @@ function isEarHashed (ear: Aim, minX: number, minY: number, size) { } // go through all polygon nodes and cure small local self-intersections -function cureLocalIntersections (start: Aim, triangles: number[], dim: number) { +function cureLocalIntersections (start: Aim, triangles: number[], dim: number): Aim { let p = start; do { const a = p.prev!; @@ -250,7 +250,7 @@ function cureLocalIntersections (start: Aim, triangles: number[], dim: number) { } // try splitting polygon into two and triangulate them independently -function splitEarcut (start: Aim | null, triangles: number[], dim: number, minX: number, minY: number, size: number) { +function splitEarcut (start: Aim | null, triangles: number[], dim: number, minX: number, minY: number, size: number): void { // look for a valid diagonal that divides the polygon into two let a = start!; do { @@ -276,7 +276,7 @@ function splitEarcut (start: Aim | null, triangles: number[], dim: number, minX: } // link every hole into the outer loop, producing a single-ring polygon without holes -function eliminateHoles (datas: number[], holeIndices: number[], outerNode: Aim | null, dim: number) { +function eliminateHoles (datas: number[], holeIndices: number[], outerNode: Aim | null, dim: number): Aim | null { const queue: Aim[] = []; let i = 0; let len = 0; @@ -313,12 +313,12 @@ function eliminateHoles (datas: number[], holeIndices: number[], outerNode: Aim return outerNode; } -function compareX (a, b) { +function compareX (a, b): number { return a.x - b.x; } // find a bridge between vertices that connects hole with an outer ring and and link it -function eliminateHole (hole: Aim, outerNode: Aim | null) { +function eliminateHole (hole: Aim, outerNode: Aim | null): void { outerNode = findHoleBridge(hole, outerNode!); if (outerNode) { const b = splitPolygon(outerNode, hole); @@ -327,7 +327,7 @@ function eliminateHole (hole: Aim, outerNode: Aim | null) { } // David Eberly's algorithm for finding a bridge between hole and outer polygon -function findHoleBridge (hole: Aim, outerNode: Aim) { +function findHoleBridge (hole: Aim, outerNode: Aim): Aim | null { let p = outerNode; const hx = hole.x; const hy = hole.y; @@ -389,7 +389,7 @@ function findHoleBridge (hole: Aim, outerNode: Aim) { } // interlink polygon nodes in z-order -function indexCurve (start: Aim, minX: number, minY: number, size: number) { +function indexCurve (start: Aim, minX: number, minY: number, size: number): void { let p = start; do { if (p.z === null) { @@ -409,7 +409,7 @@ function indexCurve (start: Aim, minX: number, minY: number, size: number) { // Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html -function sortLinked (list: Aim | null) { +function sortLinked (list: Aim | null): Aim | null { let i = 0; let p: Aim | null = null; let q: Aim | null = null; @@ -474,7 +474,7 @@ function sortLinked (list: Aim | null) { } // z-order of a point given coords and size of the data bounding box -function zOrder (x: number, y: number, minX: number, minY: number, size: number) { +function zOrder (x: number, y: number, minX: number, minY: number, size: number): number { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) / size; y = 32767 * (y - minY) / size; @@ -493,7 +493,7 @@ function zOrder (x: number, y: number, minX: number, minY: number, size: number) } // find the leftmost node of a polygon ring -function getLeftmost (start: Aim) { +function getLeftmost (start: Aim): Aim { let p = start; let leftmost = start; do { @@ -508,30 +508,30 @@ function getLeftmost (start: Aim) { } // check if a point lies within a convex triangle -function pointInTriangle (ax: number, ay: number, bx: number, by: number, cx: number, cy: number, px: number, py: number) { +function pointInTriangle (ax: number, ay: number, bx: number, by: number, cx: number, cy: number, px: number, py: number): boolean { return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; } // check if a diagonal between two polygon nodes is valid (lies in polygon interior) -function isValidDiagonal (a: Aim, b: Aim) { +function isValidDiagonal (a: Aim, b: Aim): boolean { return a.next!.i !== b.i && a.prev!.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); } // signed area of a triangle -function area (p: Aim, q: Aim, r: Aim) { +function area (p: Aim, q: Aim, r: Aim): number { return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); } // check if two points are equal -function equals (p1: Aim, p2: Aim) { +function equals (p1: Aim, p2: Aim): boolean { return p1.x === p2.x && p1.y === p2.y; } // check if two segments intersect -function intersects (p1: Aim, q1: Aim, p2: Aim, q2: Aim) { +function intersects (p1: Aim, q1: Aim, p2: Aim, q2: Aim): boolean { if ((equals(p1, q1) && equals(p2, q2)) || (equals(p1, q2) && equals(p2, q1))) { return true; @@ -542,7 +542,7 @@ function intersects (p1: Aim, q1: Aim, p2: Aim, q2: Aim) { } // check if a polygon diagonal intersects any polygon segments -function intersectsPolygon (a: Aim, b: Aim) { +function intersectsPolygon (a: Aim, b: Aim): boolean { let p = a; do { if (p.i !== a.i && p.next!.i !== a.i && p.i !== b.i && p.next!.i !== b.i @@ -554,14 +554,14 @@ function intersectsPolygon (a: Aim, b: Aim) { } // check if a polygon diagonal is locally inside the polygon -function locallyInside (a: Aim, b: Aim) { +function locallyInside (a: Aim, b: Aim): boolean { return area(a.prev!, a, a.next!) < 0 ? area(a, b, a.next!) >= 0 && area(a, a.prev!, b) >= 0 : area(a, b, a.prev!) < 0 || area(a, a.next!, b) < 0; } // check if the middle point of a polygon diagonal is inside the polygon -function middleInside (a: Aim, b: Aim) { +function middleInside (a: Aim, b: Aim): boolean { let p = a; let inside = false; const px = (a.x + b.x) / 2; @@ -578,7 +578,7 @@ function middleInside (a: Aim, b: Aim) { // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring -function splitPolygon (a: Aim, b: Aim) { +function splitPolygon (a: Aim, b: Aim): Aim { const a2 = new Aim(a.i, a.x, a.y); const b2 = new Aim(b.i, b.x, b.y); const an = a.next!; @@ -600,7 +600,7 @@ function splitPolygon (a: Aim, b: Aim) { } // create a node and optionally link it with previous one (in a circular doubly linked list) -function insertNode (i: number, x: number, y: number, last: Aim | null) { +function insertNode (i: number, x: number, y: number, last: Aim | null): Aim { const p = new Aim(i, x, y); if (!last) { @@ -616,7 +616,7 @@ function insertNode (i: number, x: number, y: number, last: Aim | null) { return p; } -function removeNode (p: Aim) { +function removeNode (p: Aim): void { p.next!.prev = p.prev; p.prev!.next = p.next; @@ -629,7 +629,7 @@ function removeNode (p: Aim) { } } -function signedArea (datas: number[], start: number, end: number, dim: number) { +function signedArea (datas: number[], start: number, end: number, dim: number): number { let sum = 0; for (let i = start, j = end - dim; i < end; i += dim) { sum += (datas[j] - datas[i]) * (datas[i + 1] + datas[j + 1]); @@ -638,7 +638,7 @@ function signedArea (datas: number[], start: number, end: number, dim: number) { return sum; } -export function earcut (datas: number[], holeIndices: number[] | null, dim: number) { +export function earcut (datas: number[], holeIndices: number[] | null, dim: number): number[] { dim = dim || 3; const hasHoles = holeIndices ? holeIndices.length : 0; diff --git a/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts b/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts index 24795ee5c0b..b913a277403 100644 --- a/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts @@ -54,12 +54,12 @@ for (let i = 0; i < 4; i++) { vec3_temps.push(new Vec3()); } -function curveDivs (r: number, arc: number, tol: number) { +function curveDivs (r: number, arc: number, tol: number): number { const da = acos(r / (r + tol)) * 2.0; return max(2, ceil(arc / da)); } -function clamp (v: number, minNum: number, maxNum: number) { +function clamp (v: number, minNum: number, maxNum: number): number { if (v < minNum) { return minNum; } else if (v > maxNum) { diff --git a/cocos/2d/assembler/graphics/webgl/impl.ts b/cocos/2d/assembler/graphics/webgl/impl.ts index 4052e890a7e..af9880ea228 100644 --- a/cocos/2d/assembler/graphics/webgl/impl.ts +++ b/cocos/2d/assembler/graphics/webgl/impl.ts @@ -38,7 +38,7 @@ export class Point extends Vec2 { public flags = 0; public len = 0; - public reset () { + public reset (): void { this.dx = 0; this.dy = 0; this.dmx = 0; @@ -54,7 +54,7 @@ export class Path { public complex = true; public points: Point[] = []; - public reset () { + public reset (): void { this.closed = false; this.bevel = 0; this.complex = true; @@ -92,7 +92,7 @@ export class Impl { this._comp = comp; } - public moveTo (x: number, y: number) { + public moveTo (x: number, y: number): void { if (this.updatePathOffset) { this.pathOffset = this.pathLength; this.updatePathOffset = false; @@ -105,14 +105,14 @@ export class Impl { this._commandY = y; } - public lineTo (x: number, y: number) { + public lineTo (x: number, y: number): void { this.addPoint(x, y, PointFlags.PT_CORNER); this._commandX = x; this._commandY = y; } - public bezierCurveTo (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) { + public bezierCurveTo (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): void { const path = this._curPath!; const last = path.points[path.points.length - 1]; if (!last) { @@ -130,27 +130,27 @@ export class Impl { this._commandY = y; } - public quadraticCurveTo (cx: number, cy: number, x: number, y: number) { + public quadraticCurveTo (cx: number, cy: number, x: number, y: number): void { const x0 = this._commandX; const y0 = this._commandY; this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y); } - public arc (cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean) { + public arc (cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean): void { arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); } - public ellipse (cx: number, cy: number, rx: number, ry: number) { + public ellipse (cx: number, cy: number, rx: number, ry: number): void { ellipse(this, cx, cy, rx, ry); this._curPath!.complex = false; } - public circle (cx: number, cy: number, r: number) { + public circle (cx: number, cy: number, r: number): void { ellipse(this, cx, cy, r, r); this._curPath!.complex = false; } - public rect (x: number, y: number, w: number, h: number) { + public rect (x: number, y: number, w: number, h: number): void { this.moveTo(x, y); this.lineTo(x + w, y); this.lineTo(x + w, y + h); @@ -160,12 +160,12 @@ export class Impl { this._curPath!.complex = false; } - public roundRect (x: number, y: number, w: number, h: number, r: number) { + public roundRect (x: number, y: number, w: number, h: number, r: number): void { roundRect(this, x, y, w, h, r); this._curPath!.complex = false; } - public clear () { + public clear (): void { this.pathLength = 0; this.pathOffset = 0; this.pointsOffset = 0; @@ -188,11 +188,11 @@ export class Impl { this._renderDataList.length = 0; } - public close () { + public close (): void { this._curPath!.closed = true; } - public requestRenderData () { + public requestRenderData (): MeshRenderData { const renderData = MeshRenderData.add(); this._renderDataList.push(renderData); if (JSB) { @@ -207,7 +207,7 @@ export class Impl { return renderData; } - public getRenderDataList () { + public getRenderDataList (): MeshRenderData[] { if (this._renderDataList.length === 0) { this.requestRenderData(); } @@ -215,7 +215,7 @@ export class Impl { return this._renderDataList; } - public addPoint (x: number, y: number, flags: PointFlags) { + public addPoint (x: number, y: number, flags: PointFlags): void { const path = this._curPath; if (!path) { return; @@ -239,7 +239,7 @@ export class Impl { pathPoints.push(pt); } - private _addPath () { + private _addPath (): Path { const offset = this.pathLength; let path = this.paths[offset]; diff --git a/cocos/2d/assembler/label/bmfontUtils.ts b/cocos/2d/assembler/label/bmfontUtils.ts index 10c3d15e746..09735a7d9b3 100644 --- a/cocos/2d/assembler/label/bmfontUtils.ts +++ b/cocos/2d/assembler/label/bmfontUtils.ts @@ -50,7 +50,7 @@ export const bmfontUtils = { updateProcessingData (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData, - comp: Label, trans: UITransform) { + comp: Label, trans: UITransform): void { style.fontSize = comp.fontSize; style.actualFontSize = comp.fontSize; style.originFontSize = _fntConfig ? _fntConfig.fontSize : comp.fontSize; @@ -88,7 +88,7 @@ export const bmfontUtils = { style.color.set(comp.color); }, - updateRenderData (comp: Label) { + updateRenderData (comp: Label): void { if (!comp.renderData) { return; } @@ -150,7 +150,7 @@ export const bmfontUtils = { } }, - updateUVs (label: Label) { + updateUVs (label: Label): void { const renderData = label.renderData!; const vData = renderData.chunk.vb; const vertexCount = renderData.vertexCount; @@ -164,7 +164,7 @@ export const bmfontUtils = { } }, - updateColor (label: Label) { + updateColor (label: Label): void { if (JSB) { const renderData = label.renderData!; const vertexCount = renderData.vertexCount; @@ -187,7 +187,7 @@ export const bmfontUtils = { } }, - resetRenderData (comp: Label) { + resetRenderData (comp: Label): void { const renderData = comp.renderData!; renderData.dataLength = 0; renderData.resize(0, 0); @@ -195,7 +195,7 @@ export const bmfontUtils = { // callBack function generateVertexData (style: TextStyle, outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData, offset: number, - spriteFrame: SpriteFrame, rect: Rect, rotated: boolean, x: number, y: number) { + spriteFrame: SpriteFrame, rect: Rect, rotated: boolean, x: number, y: number): void { const dataOffset = offset; const scale = style.bmfontScale; @@ -250,7 +250,7 @@ export const bmfontUtils = { dataList[dataOffset + 3].y = y; }, - _updateFontFamily (comp) { + _updateFontFamily (comp): void { const fontAsset = comp.font; _spriteFrame = fontAsset.spriteFrame; _fntConfig = fontAsset.fntConfig; @@ -267,20 +267,20 @@ export const bmfontUtils = { // TODO update material and uv }, - _updateLabelInfo (comp) { + _updateLabelInfo (comp): void { // clear shareLabelInfo.hash = ''; shareLabelInfo.margin = 0; }, - _resetProperties () { + _resetProperties (): void { _fntConfig = null; _spriteFrame = null; shareLabelInfo.hash = ''; shareLabelInfo.margin = 0; }, - createQuadIndices (indexCount) { + createQuadIndices (indexCount): void { if (indexCount % 6 !== 0) { console.error('illegal index count!'); return; diff --git a/cocos/2d/assembler/label/font-utils.ts b/cocos/2d/assembler/label/font-utils.ts index 1034240d05f..caa946b3a3a 100644 --- a/cocos/2d/assembler/label/font-utils.ts +++ b/cocos/2d/assembler/label/font-utils.ts @@ -46,7 +46,7 @@ export class CanvasPool { return _canvasPool; } public pool: ISharedLabelData[] = []; - public get () { + public get (): ISharedLabelData { let data = this.pool.pop(); if (!data) { @@ -61,7 +61,7 @@ export class CanvasPool { return data; } - public put (canvas: ISharedLabelData) { + public put (canvas: ISharedLabelData): void { if (this.pool.length >= macro.MAX_LABEL_CANVAS_POOL_SIZE) { return; } @@ -136,18 +136,18 @@ class LetterTexture { this.hash = `${char.charCodeAt(0)}${labelInfo.hash}`; } - public updateRenderData () { + public updateRenderData (): void { this._updateProperties(); this._updateTexture(); } - public destroy () { + public destroy (): void { this.image = null; // Label._canvasPool.put(this._data); CanvasPool.getInstance().put(this.data as ISharedLabelData); } - private _updateProperties () { + private _updateProperties (): void { this.data = CanvasPool.getInstance().get(); this.canvas = this.data.canvas; this.context = this.data.context; @@ -176,7 +176,7 @@ class LetterTexture { this.image.reset(this.canvas); } - private _updateTexture () { + private _updateTexture (): void { if (!this.context || !this.canvas) { return; } @@ -228,7 +228,7 @@ export class LetterRenderTexture extends Texture2D { * @param [height] * @param [string] */ - public initWithSize (width: number, height: number, format: number = PixelFormat.RGBA8888) { + public initWithSize (width: number, height: number, format: number = PixelFormat.RGBA8888): void { this.reset({ width, height, @@ -243,7 +243,7 @@ export class LetterRenderTexture extends Texture2D { * @param {Number} x * @param {Number} y */ - public drawTextureAt (image: ImageAsset, x: number, y: number) { + public drawTextureAt (image: ImageAsset, x: number, y: number): void { const gfxTexture = this.getGFXTexture(); if (!image || !gfxTexture) { return; @@ -265,11 +265,11 @@ export class LetterRenderTexture extends Texture2D { } export class LetterAtlas { - get width () { + get width (): number { return this._width; } - get height () { + get height (): number { return this._height; } @@ -293,7 +293,7 @@ export class LetterAtlas { director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); } - public insertLetterTexture (letterTexture: LetterTexture) { + public insertLetterTexture (letterTexture: LetterTexture): FontLetterDefinition | null { const texture = letterTexture.image; const device = director.root!.device; if (!texture || !this.fontDefDictionary || !device) { @@ -344,7 +344,7 @@ export class LetterAtlas { return letterDefinition; } - public update () { + public update (): void { if (!this._dirty) { return; } @@ -352,7 +352,7 @@ export class LetterAtlas { this._dirty = false; } - public reset () { + public reset (): void { this._x = space; this._y = space; this._nextY = space; @@ -370,7 +370,7 @@ export class LetterAtlas { this.fontDefDictionary.clear(); } - public destroy () { + public destroy (): void { this.reset(); if (this.fontDefDictionary) { this.fontDefDictionary.texture.destroy(); @@ -378,15 +378,15 @@ export class LetterAtlas { } } - getTexture () { + getTexture (): any { return this.fontDefDictionary.getTexture(); } - public beforeSceneLoad () { + public beforeSceneLoad (): void { this.clearAllCache(); } - public clearAllCache () { + public clearAllCache (): void { this.destroy(); const texture = new LetterRenderTexture(); @@ -395,11 +395,11 @@ export class LetterAtlas { this.fontDefDictionary.texture = texture; } - public getLetter (key: string) { + public getLetter (key: string): any { return this.fontDefDictionary.letterDefinitions[key]; } - public getLetterDefinitionForChar (char: string, labelInfo: ILabelInfo) { + public getLetterDefinitionForChar (char: string, labelInfo: ILabelInfo): any { const hash = char.charCodeAt(0) + labelInfo.hash; let letter = this.fontDefDictionary.letterDefinitions[hash]; if (!letter) { @@ -445,7 +445,7 @@ export const shareLabelInfo: IShareLabelInfo = { fontScale: 1, }; -export function computeHash (labelInfo) { +export function computeHash (labelInfo): string { const hashData = ''; const color = labelInfo.color.toHEX(); let out = ''; diff --git a/cocos/2d/assembler/label/letter.ts b/cocos/2d/assembler/label/letter.ts index c9edf579524..24388e2dd5b 100644 --- a/cocos/2d/assembler/label/letter.ts +++ b/cocos/2d/assembler/label/letter.ts @@ -28,6 +28,7 @@ import { IBatcher } from '../../renderer/i-batcher'; import { Label } from '../../components/label'; import { fillMeshVertices3D } from '../utils'; import { letterFont } from './letter-font'; +import type { RenderData } from '../../renderer/render-data'; const tempColor = new Color(255, 255, 255, 255); @@ -36,13 +37,13 @@ const tempColor = new Color(255, 255, 255, 255); * 可通过 `UI.letter` 获取该组装器。 */ export const letter = { - createData (comp: Label) { + createData (comp: Label): RenderData { const renderData = comp.requestRenderData(); renderData.resize(0, 0); return renderData; }, - fillBuffers (comp: Label, renderer: IBatcher) { + fillBuffers (comp: Label, renderer: IBatcher): void { if (!comp.renderData) { return; } @@ -53,7 +54,7 @@ export const letter = { fillMeshVertices3D(node, renderer, comp.renderData, tempColor); }, - updateColor (label: Label) { + updateColor (label: Label): void { if (JSB) { const renderData = label.renderData!; const vertexCount = renderData.vertexCount; diff --git a/cocos/2d/assembler/label/text-layout.ts b/cocos/2d/assembler/label/text-layout.ts index 7e5648ecce8..ddfc04be438 100644 --- a/cocos/2d/assembler/label/text-layout.ts +++ b/cocos/2d/assembler/label/text-layout.ts @@ -56,7 +56,7 @@ export class TextLayout { public textDesiredHeight = 0; public linesWidth: number[] = []; - public reset () { + public reset (): void { this.horizontalAlign = 0; this.verticalAlign = 0; this.wrapping = true; diff --git a/cocos/2d/assembler/label/text-output-data.ts b/cocos/2d/assembler/label/text-output-data.ts index 98caa9a1054..30086182eb3 100644 --- a/cocos/2d/assembler/label/text-output-data.ts +++ b/cocos/2d/assembler/label/text-output-data.ts @@ -43,7 +43,7 @@ export class TextOutputLayoutData { public startPosition = Vec2.ZERO.clone(); // ttf - public reset () { + public reset (): void { this.parsedString.length = 0; this.nodeContentSize.set(0, 0); this.canvasSize.set(); @@ -63,7 +63,7 @@ export class TextOutputRenderData { public uiTransAnchorX = 0.5; // both public uiTransAnchorY = 0.5; // both - public reset () { + public reset (): void { this.quadCount = 0; this.vertexBuffer.length = 0; this.texture = null; diff --git a/cocos/2d/assembler/label/text-processing.ts b/cocos/2d/assembler/label/text-processing.ts index eea427c951f..7e7d0c84f1b 100644 --- a/cocos/2d/assembler/label/text-processing.ts +++ b/cocos/2d/assembler/label/text-processing.ts @@ -80,13 +80,13 @@ export class TextProcessing { this._context = this._canvasData.context; } - public destroy () { + public destroy (): void { CanvasPool.getInstance().put(this._canvasData!); this._lettersInfo.length = 0; } public processingString (isBmFont: boolean, style: TextStyle, layout: TextLayout, - outputLayoutData: TextOutputLayoutData, inputString: string, out?: string[]) { + outputLayoutData: TextOutputLayoutData, inputString: string, out?: string[]): void { if (!isBmFont) { this._updatePaddingRect(style, outputLayoutData); this._calculateLabelFont(style, layout, outputLayoutData, inputString); @@ -109,7 +109,7 @@ export class TextProcessing { } public generateRenderInfo (isBmFont: boolean, style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, - outputRenderData: TextOutputRenderData, inputString: string, callback: AnyFunction) { + outputRenderData: TextOutputRenderData, inputString: string, callback: AnyFunction): void { if (!isBmFont) { this._updateLabelDimensions(style, layout, outputLayoutData); this._updateTexture(style, layout, outputLayoutData, outputRenderData); @@ -120,7 +120,7 @@ export class TextProcessing { } } - public setCanvasUsed (canvas: HTMLCanvasElement, content: CanvasRenderingContext2D | null) { + public setCanvasUsed (canvas: HTMLCanvasElement, content: CanvasRenderingContext2D | null): void { this._canvas = canvas; this._context = content; } @@ -139,7 +139,7 @@ export class TextProcessing { private _maxFontSize = 100; private _fontScale = 1; - private _getStyleFontScale (fontSize: number, fontScale: number, canvasWidth: number, canvasHeight: number) { + private _getStyleFontScale (fontSize: number, fontScale: number, canvasWidth: number, canvasHeight: number): number { let scale = fontScale; if (scale * fontSize > this._maxFontSize && fontSize < this._maxFontSize) { // Font size limit scale = this._maxFontSize / fontSize; @@ -154,7 +154,7 @@ export class TextProcessing { } private _calculateLabelFont (style: TextStyle, layout: TextLayout, - outputLayoutData: TextOutputLayoutData, inputString: string) { + outputLayoutData: TextOutputLayoutData, inputString: string): void { if (!this._context) { return; } @@ -210,7 +210,7 @@ export class TextProcessing { } // can cache - private _getFontDesc (fontSize: number, fontFamily: string, isBold: boolean, isItalic: boolean) { + private _getFontDesc (fontSize: number, fontFamily: string, isBold: boolean, isItalic: boolean): string { let fontDesc = `${fontSize.toString()}px `; fontDesc += fontFamily; if (isBold) { @@ -225,7 +225,7 @@ export class TextProcessing { } // can cache - private _getLineHeight (lineHeight: number, fontSize: number, drawFontsize: number) { + private _getLineHeight (lineHeight: number, fontSize: number, drawFontsize: number): number { let nodeSpacingY = lineHeight; if (nodeSpacingY === 0) { nodeSpacingY = fontSize; @@ -236,7 +236,7 @@ export class TextProcessing { return nodeSpacingY | 0; } - private _calculateShrinkFont (paragraphedStrings: string[], style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _calculateShrinkFont (paragraphedStrings: string[], style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData): void { if (!this._context) return; let _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic); this._context.font = _fontDesc; @@ -317,7 +317,7 @@ export class TextProcessing { style.fontDesc = _fontDesc; } - private _calculateWrapText (paragraphedStrings: string[], style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _calculateWrapText (paragraphedStrings: string[], style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData): void { if (!layout.wrapping || !this._context) return; let _splitStrings: string[] = []; @@ -336,11 +336,11 @@ export class TextProcessing { style.fontDesc = _fontDesc; } - private _measureText (ctx: CanvasRenderingContext2D, fontDesc) { - return (string: string) => safeMeasureText(ctx, string, fontDesc); + private _measureText (ctx: CanvasRenderingContext2D, fontDesc): (str: string) => number { + return (str: string): number => safeMeasureText(ctx, str, fontDesc); } - private _calculateParagraphLength (paragraphedStrings: string[], ctx: CanvasRenderingContext2D, fontDesc: string) { + private _calculateParagraphLength (paragraphedStrings: string[], ctx: CanvasRenderingContext2D, fontDesc: string): number[] { const paragraphLength: number[] = []; for (const para of paragraphedStrings) { @@ -351,7 +351,7 @@ export class TextProcessing { return paragraphLength; } - private _updatePaddingRect (style: TextStyle, outputLayoutData: TextOutputLayoutData) { + private _updatePaddingRect (style: TextStyle, outputLayoutData: TextOutputLayoutData): void { let top = 0; let bottom = 0; let left = 0; let right = 0; let outlineWidth = 0; outputLayoutData.contentSizeExtend.width = outputLayoutData.contentSizeExtend.height = 0; @@ -385,7 +385,7 @@ export class TextProcessing { // -------------------- Render Processing Part -------------------------- - private _updateLabelDimensions (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _updateLabelDimensions (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData): void { outputLayoutData.canvasSize.width = Math.min(outputLayoutData.canvasSize.width, MAX_SIZE); outputLayoutData.canvasSize.height = Math.min(outputLayoutData.canvasSize.height, MAX_SIZE); @@ -400,7 +400,7 @@ export class TextProcessing { this._context!.textBaseline = 'alphabetic'; } - private _calculateFillTextStartPosition (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _calculateFillTextStartPosition (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData): void { let labelX = 0; if (layout.horizontalAlign === HorizontalTextAlignment.RIGHT) { labelX = outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width; @@ -431,7 +431,7 @@ export class TextProcessing { outputLayoutData.startPosition.set(labelX + outputLayoutData.canvasPadding.x, firstLinelabelY + outputLayoutData.canvasPadding.y); } - private _updateTexture (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData) { + private _updateTexture (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData): void { if (!this._context || !this._canvas) { return; } @@ -440,7 +440,7 @@ export class TextProcessing { this._context.clearRect(0, 0, this._canvas.width, this._canvas.height); this._context.font = style.fontDesc.replace( /(\d+)(\.\d+)?(px|em|rem|pt)/g, - (w, m: string, n: string, u: string) => (+m * fontScale + (+n || 0) * fontScale).toString() + u, + (w, m: string, n: string, u: string): string => (+m * fontScale + (+n || 0) * fontScale).toString() + u, ); this._calculateFillTextStartPosition(style, layout, outputLayoutData); @@ -479,7 +479,7 @@ export class TextProcessing { this._uploadTexture(outputRenderData); } - private _uploadTexture (outputRenderData: TextOutputRenderData) { + private _uploadTexture (outputRenderData: TextOutputRenderData): void { if (outputRenderData.texture && this._canvas) { let tex: Texture2D; if (outputRenderData.texture instanceof SpriteFrame) { @@ -513,7 +513,7 @@ export class TextProcessing { } } - private _drawTextEffect (startPosition: Vec2, lineHeight: number, style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _drawTextEffect (startPosition: Vec2, lineHeight: number, style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData): void { if (!style.hasShadow && !style.isOutlined && !style.isUnderline) return; const isMultiple = outputLayoutData.parsedString.length > 1 && style.hasShadow; @@ -564,12 +564,12 @@ export class TextProcessing { } } - private _setupOutline (style: TextStyle) { + private _setupOutline (style: TextStyle): void { this._context!.strokeStyle = `rgba(${style.outlineColor.r}, ${style.outlineColor.g}, ${style.outlineColor.b}, ${style.outlineColor.a / 255})`; this._context!.lineWidth = style.outlineWidth * 2 * this._fontScale; } - private _setupShadow (style: TextStyle) { + private _setupShadow (style: TextStyle): void { const fontScale = this._fontScale; this._context!.shadowColor = `rgba(${style.shadowColor.r}, ${style.shadowColor.g}, ${style.shadowColor.b}, ${style.shadowColor.a / 255})`; this._context!.shadowBlur = style.shadowBlur * fontScale; @@ -580,7 +580,7 @@ export class TextProcessing { // -------------------- Render Processing Part -------------------------- private generateVertexData (isBmFont: boolean, style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, - outputRenderData: TextOutputRenderData, inputString: string, callback: AnyFunction) { + outputRenderData: TextOutputRenderData, inputString: string, callback: AnyFunction): void { if (!isBmFont) { this.updateQuatCount(outputRenderData); // update vbBuffer count callback(style, outputLayoutData, outputRenderData); @@ -589,7 +589,7 @@ export class TextProcessing { } } - private updateQuatCount (outputRenderData: TextOutputRenderData) { + private updateQuatCount (outputRenderData: TextOutputRenderData): void { const data: IRenderData[] = outputRenderData.vertexBuffer; const count = outputRenderData.quadCount; if (data.length !== count) { @@ -611,7 +611,7 @@ export class TextProcessing { // -------------------- Canvas Mode Part --------------------------- // -------------------- Multiple Quad Mode Part -------------------- - private _setupBMFontOverflowMetrics (layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _setupBMFontOverflowMetrics (layout: TextLayout, outputLayoutData: TextOutputLayoutData): void { let newWidth = outputLayoutData.nodeContentSize.width; let newHeight = outputLayoutData.nodeContentSize.height; @@ -631,11 +631,11 @@ export class TextProcessing { layout.maxLineWidth = newWidth; } - private _updateFontScale (style: TextStyle) { + private _updateFontScale (style: TextStyle): void { style.bmfontScale = style.actualFontSize / (style.originFontSize * this._fontScale); } - private _computeHorizontalKerningForText (style: TextStyle, layout: TextLayout, inputString: string) { + private _computeHorizontalKerningForText (style: TextStyle, layout: TextLayout, inputString: string): void { const string = inputString; const stringLen = string.length; if (!style.fntConfig) return; // for char @@ -660,7 +660,7 @@ export class TextProcessing { } } - private _alignText (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, inputString: string) { + private _alignText (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, inputString: string): void { this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen); // shrink @@ -675,7 +675,7 @@ export class TextProcessing { this._parsedString(outputLayoutData, inputString); } - private _parsedString (outputLayoutData: TextOutputLayoutData, inputString: string) { + private _parsedString (outputLayoutData: TextOutputLayoutData, inputString: string): void { let _splitStrings: string[] = []; let textFragment = ''; @@ -695,7 +695,7 @@ export class TextProcessing { } private _multilineTextWrap (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, - inputString: string, nextTokenFunc: (arg0: TextStyle, arg1: TextLayout, arg2: string, arg3: number, arg4: number) => number) { + inputString: string, nextTokenFunc: (arg0: TextStyle, arg1: TextLayout, arg2: string, arg3: number, arg4: number) => number): boolean { layout.linesWidth.length = 0; const _string = inputString; @@ -834,7 +834,7 @@ export class TextProcessing { return true; } - private _recordPlaceholderInfo (letterIndex: number, char: string) { + private _recordPlaceholderInfo (letterIndex: number, char: string): void { if (letterIndex >= this._lettersInfo.length) { const tmpInfo = new LetterInfo(); this._lettersInfo.push(tmpInfo); @@ -845,7 +845,7 @@ export class TextProcessing { this._lettersInfo[letterIndex].valid = false; } - private _recordLetterInfo (letterPosition: Vec2, character: string, letterIndex: number, lineIndex: number) { + private _recordLetterInfo (letterPosition: Vec2, character: string, letterIndex: number, lineIndex: number): void { if (letterIndex >= this._lettersInfo.length) { const tmpInfo = new LetterInfo(); this._lettersInfo.push(tmpInfo); @@ -862,7 +862,7 @@ export class TextProcessing { this._lettersInfo[letterIndex].y = letterPosition.y; } - private _getFirstWordLen (style: TextStyle, layout: TextLayout, text: string, startIndex: number, textLen: number) { + private _getFirstWordLen (style: TextStyle, layout: TextLayout, text: string, startIndex: number, textLen: number): number { let character = text.charAt(startIndex); if (isUnicodeCJK(character) || character === '\n' @@ -903,7 +903,7 @@ export class TextProcessing { return len; } - private _computeAlignmentOffset (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _computeAlignmentOffset (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData): void { layout.linesOffsetX.length = 0; layout.letterOffsetY = 0; @@ -942,12 +942,12 @@ export class TextProcessing { } } - private _getFontScale (style: TextStyle, layout: TextLayout) { + private _getFontScale (style: TextStyle, layout: TextLayout): number { return layout.overFlow === Overflow.SHRINK ? style.bmfontScale : 1; } private _isVerticalClamp (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, - inputString: string, process: TextProcessing) { + inputString: string, process: TextProcessing): boolean { if (layout.textDesiredHeight > outputLayoutData.nodeContentSize.height) { return true; } else { @@ -956,7 +956,7 @@ export class TextProcessing { } private _isHorizontalClamp (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, - inputString: string, process: TextProcessing) { + inputString: string, process: TextProcessing): boolean { let letterClamp = false; const _string = inputString; for (let ctr = 0, l = _string.length; ctr < l; ++ctr) { @@ -989,7 +989,7 @@ export class TextProcessing { return letterClamp; } - private _isHorizontalNeedShrink (layout: TextLayout, outputLayoutData: TextOutputLayoutData) { + private _isHorizontalNeedShrink (layout: TextLayout, outputLayoutData: TextOutputLayoutData): boolean { let wordWidth = 0; for (let ctr = 0, l = layout.linesWidth.length; ctr < l; ++ctr) { wordWidth = layout.linesWidth[ctr]; @@ -1000,7 +1000,7 @@ export class TextProcessing { private _shrinkLabelToContentSize (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, inputString: string, lambda: (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, - inputString: string, process: TextProcessing) => boolean) { + inputString: string, process: TextProcessing) => boolean): void { const fontSize = style.actualFontSize; let left = 0; @@ -1032,7 +1032,7 @@ export class TextProcessing { } } - private _scaleFontSizeDown (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, inputString: string, fontSize: number) { + private _scaleFontSizeDown (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, inputString: string, fontSize: number): void { let shouldUpdateContent = true; if (!fontSize) { fontSize = 0.1; @@ -1047,7 +1047,7 @@ export class TextProcessing { } private _updateQuads (style: TextStyle, layout: TextLayout, outputLayoutData: TextOutputLayoutData, - outputRenderData: TextOutputRenderData, inputString: string, callback) { + outputRenderData: TextOutputRenderData, inputString: string, callback): boolean { const texture = style.spriteFrame ? style.spriteFrame.texture : shareLabelInfo.fontAtlas!.getTexture(); const appX = outputRenderData.uiTransAnchorX * outputLayoutData.nodeContentSize.width; @@ -1106,7 +1106,7 @@ export class TextProcessing { return ret; } - private _isHorizontalClamped (layout: TextLayout, outputLayoutData: TextOutputLayoutData, px: number, lineIndex: number) { + private _isHorizontalClamped (layout: TextLayout, outputLayoutData: TextOutputLayoutData, px: number, lineIndex: number): boolean { const wordWidth = layout.linesWidth[lineIndex]; const letterOverClamp = (px > outputLayoutData.nodeContentSize.width || px < 0); @@ -1117,7 +1117,7 @@ export class TextProcessing { } } - private _determineRect (style: TextStyle) { + private _determineRect (style: TextStyle): boolean { const _spriteFrame = style.spriteFrame; if (!_spriteFrame) return false; // for char mode const isRotated = _spriteFrame.isRotated(); diff --git a/cocos/2d/assembler/label/text-style.ts b/cocos/2d/assembler/label/text-style.ts index 4f5032fcff2..590f4c03842 100644 --- a/cocos/2d/assembler/label/text-style.ts +++ b/cocos/2d/assembler/label/text-style.ts @@ -70,7 +70,7 @@ export class TextStyle { public fontScale = 1; - public reset () { + public reset (): void { this.isBold = false; this.isItalic = false; this.isUnderline = false; diff --git a/cocos/2d/assembler/label/ttfUtils.ts b/cocos/2d/assembler/label/ttfUtils.ts index 4d292d090ef..b8375ca84c9 100644 --- a/cocos/2d/assembler/label/ttfUtils.ts +++ b/cocos/2d/assembler/label/ttfUtils.ts @@ -36,7 +36,7 @@ const Overflow = Label.Overflow; export const ttfUtils = { updateProcessingData (style: TextStyle, layout: TextLayout, - outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData, comp: Label, trans: UITransform) { + outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData, comp: Label, trans: UITransform): void { // font info // both style.isSystemFontUsed = comp.useSystemFont; style.fontSize = comp.fontSize; @@ -95,19 +95,19 @@ export const ttfUtils = { layout.verticalAlign = comp.verticalAlign; // render Only }, - getAssemblerData () { + getAssemblerData (): ISharedLabelData { const sharedLabelData = Label._canvasPool.get(); sharedLabelData.canvas.width = sharedLabelData.canvas.height = 1; return sharedLabelData; }, - resetAssemblerData (assemblerData: ISharedLabelData) { + resetAssemblerData (assemblerData: ISharedLabelData): void { if (assemblerData) { Label._canvasPool.put(assemblerData); } }, - updateRenderData (comp: Label) { + updateRenderData (comp: Label): void { if (!comp.renderData) { return; } if (comp.renderData.vertDirty) { @@ -154,7 +154,7 @@ export const ttfUtils = { }, // callBack function - generateVertexData (style: TextStyle, outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData) { + generateVertexData (style: TextStyle, outputLayoutData: TextOutputLayoutData, outputRenderData: TextOutputRenderData): void { const data = outputRenderData.vertexBuffer; const width = outputLayoutData.canvasSize.width; @@ -172,13 +172,13 @@ export const ttfUtils = { data[3].y = height - appY; // t }, - updateVertexData (comp: Label) { + updateVertexData (comp: Label): void { }, - updateUVs (comp: Label) { + updateUVs (comp: Label): void { }, - _updateFontFamily (comp: Label) { + _updateFontFamily (comp: Label): string { let _fontFamily = ''; if (!comp.useSystemFont) { if (comp.font) { @@ -192,14 +192,14 @@ export const ttfUtils = { return _fontFamily; }, - _calDynamicAtlas (comp: Label, outputLayoutData: TextOutputLayoutData) { + _calDynamicAtlas (comp: Label, outputLayoutData: TextOutputLayoutData): void { if (comp.cacheMode !== Label.CacheMode.BITMAP || outputLayoutData.canvasSize.width <= 0 || outputLayoutData.canvasSize.height <= 0) return; const frame = comp.ttfSpriteFrame!; dynamicAtlasManager.packToDynamicAtlas(comp, frame); // TODO update material and uv }, - _resetDynamicAtlas (comp: Label) { + _resetDynamicAtlas (comp: Label): void { if (comp.cacheMode !== Label.CacheMode.BITMAP) return; const frame = comp.ttfSpriteFrame!; dynamicAtlasManager.deleteAtlasSpriteFrame(frame); diff --git a/cocos/2d/assembler/sprite/radial-filled.ts b/cocos/2d/assembler/sprite/radial-filled.ts index e0830329585..c7d0685e5c1 100644 --- a/cocos/2d/assembler/sprite/radial-filled.ts +++ b/cocos/2d/assembler/sprite/radial-filled.ts @@ -45,7 +45,7 @@ const _center = new Vec2(); const _triangles: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; let QUAD_INDICES; -function _calcIntersectedPoints (left, right, bottom, top, center: Vec2, angle, intersectPoints: Vec2[]) { +function _calcIntersectedPoints (left, right, bottom, top, center: Vec2, angle, intersectPoints: Vec2[]): void { // left bottom, right, top let sinAngle = Math.sin(angle); sinAngle = Math.abs(sinAngle) > EPSILON ? sinAngle : 0; @@ -85,7 +85,7 @@ function _calcIntersectedPoints (left, right, bottom, top, center: Vec2, angle, } } -function _calculateVertices (sprite: Sprite) { +function _calculateVertices (sprite: Sprite): void { const uiTrans = sprite.node._uiProps.uiTransformComp!; const width = uiTrans.width; const height = uiTrans.height; @@ -130,7 +130,7 @@ function _calculateVertices (sprite: Sprite) { } } -function _calculateUVs (spriteFrame: SpriteFrame) { +function _calculateUVs (spriteFrame: SpriteFrame): void { const atlasWidth = spriteFrame.width; const atlasHeight = spriteFrame.height; const textureRect = spriteFrame.getRect(); @@ -166,7 +166,7 @@ function _calculateUVs (spriteFrame: SpriteFrame) { } } -function _getVertAngle (start: Vec2, end: Vec2) { +function _getVertAngle (start: Vec2, end: Vec2): number { const placementX = end.x - start.x; const placementY = end.y - start.y; @@ -188,7 +188,7 @@ function _getVertAngle (start: Vec2, end: Vec2) { } } -function _generateTriangle (dataList: IRenderData[], offset: number, vert0: Vec2, vert1: Vec2, vert2: Vec2) { +function _generateTriangle (dataList: IRenderData[], offset: number, vert0: Vec2, vert1: Vec2, vert2: Vec2): void { const vertices = _vertices; const v0x = vertices[0]; const v0y = vertices[1]; @@ -217,7 +217,7 @@ function _generateTriangle (dataList: IRenderData[], offset: number, vert0: Vec2 _generateUV(progressX, progressY, dataList, offset + 2); } -function _generateUV (progressX: number, progressY: number, data: IRenderData[], offset: number) { +function _generateUV (progressX: number, progressY: number, data: IRenderData[], offset: number): void { const uvs = _uvs; const px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX; const px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX; diff --git a/cocos/2d/assembler/sprite/tiled.ts b/cocos/2d/assembler/sprite/tiled.ts index 9177576fa11..502ebb5fe4f 100644 --- a/cocos/2d/assembler/sprite/tiled.ts +++ b/cocos/2d/assembler/sprite/tiled.ts @@ -45,7 +45,7 @@ let tempRenderDataLength = 0; const tempRenderData: IRenderData[] = []; let QUAD_INDICES; -function has9SlicedOffsetVertexCount (spriteFrame: SpriteFrame) { +function has9SlicedOffsetVertexCount (spriteFrame: SpriteFrame): number { if (spriteFrame) { if (spriteFrame.insetTop > 0 || spriteFrame.insetBottom > 0 diff --git a/cocos/2d/assembler/utils.ts b/cocos/2d/assembler/utils.ts index af17bbd4eca..b087b993c4d 100644 --- a/cocos/2d/assembler/utils.ts +++ b/cocos/2d/assembler/utils.ts @@ -30,7 +30,7 @@ import { FormatInfos } from '../../gfx'; const m = new Mat4(); -export function fillMeshVertices3D (node: Node, renderer: IBatcher, renderData: RenderData, color: Color) { +export function fillMeshVertices3D (node: Node, renderer: IBatcher, renderData: RenderData, color: Color): void { const chunk = renderData.chunk; const dataList = renderData.data; const vData = chunk.vb; @@ -71,7 +71,7 @@ export function fillMeshVertices3D (node: Node, renderer: IBatcher, renderData: meshBuffer.setDirty(); } -export function updateOpacity (renderData: RenderData, opacity: number) { +export function updateOpacity (renderData: RenderData, opacity: number): void { const vfmt = renderData.vertexFormat; const vb = renderData.chunk.vb; let attr; let format; let stride; diff --git a/cocos/2d/assets/bitmap-font.ts b/cocos/2d/assets/bitmap-font.ts index f83bbae5514..04ab0ee7982 100644 --- a/cocos/2d/assets/bitmap-font.ts +++ b/cocos/2d/assets/bitmap-font.ts @@ -57,11 +57,11 @@ export class FontAtlas { this.texture = texture; } - public addLetterDefinitions (letter, letterDefinition) { + public addLetterDefinitions (letter, letterDefinition): void { this.letterDefinitions[letter] = letterDefinition; } - public cloneLetterDefinition () { + public cloneLetterDefinition (): ILetterDefinition { const copyLetterDefinitions: ILetterDefinition = {}; for (const key of Object.keys(this.letterDefinitions)) { const value = new FontLetterDefinition(); @@ -71,15 +71,15 @@ export class FontAtlas { return copyLetterDefinitions; } - public getTexture () { + public getTexture (): any { return this.texture; } - public getLetter (key) { + public getLetter (key): any { return this.letterDefinitions[key]; } - public getLetterDefinitionForChar (char, labelInfo?) { + public getLetterDefinitionForChar (char, labelInfo?): any { const key = char.charCodeAt(0); const hasKey = this.letterDefinitions.hasOwnProperty(key); let letter; @@ -91,7 +91,7 @@ export class FontAtlas { return letter; } - public clear () { + public clear (): void { this.letterDefinitions = {}; } } @@ -137,7 +137,7 @@ export class BitmapFont extends Font { */ public declare fontDefDictionary: FontAtlas; - onLoaded () { + onLoaded (): void { const spriteFrame = this.spriteFrame; if (!this.fontDefDictionary && spriteFrame) { this.fontDefDictionary = new FontAtlas(spriteFrame.texture); diff --git a/cocos/2d/assets/sprite-atlas.ts b/cocos/2d/assets/sprite-atlas.ts index b77ac7cac31..75af3306541 100644 --- a/cocos/2d/assets/sprite-atlas.ts +++ b/cocos/2d/assets/sprite-atlas.ts @@ -28,6 +28,7 @@ import { ccclass, serializable, editable } from 'cc.decorator'; import { Asset } from '../../asset/assets'; import { SpriteFrame } from './sprite-frame'; import { cclegacy, js } from '../../core'; +import type { TextureBase } from '../../asset/assets/texture-base'; interface ISpriteAtlasSerializeData{ name: string; @@ -59,7 +60,7 @@ export class SpriteAtlas extends Asset { * @zh 获取精灵图集的贴图。 * @returns @en The texture2d asset. @zh 二维贴图资源。 */ - public getTexture () { + public getTexture (): TextureBase | null { const keys = Object.keys(this.spriteFrames); if (keys.length > 0) { const spriteFrame = this.spriteFrames[keys[0]]; @@ -76,7 +77,7 @@ export class SpriteAtlas extends Asset { * @param key @en The SpriteFrame name. @zh 精灵名字。 * @returns @en The SpriteFrame asset. @zh 精灵资源。 */ - public getSpriteFrame (key: string) { + public getSpriteFrame (key: string): SpriteFrame | null { const sf = this.spriteFrames[key]; if (!sf) { return null; @@ -92,7 +93,7 @@ export class SpriteAtlas extends Asset { * @zh 获取精灵图集所有精灵。 * @returns @en All sprite frames. @zh 所有的精灵资源。 */ - public getSpriteFrames () { + public getSpriteFrames (): (SpriteFrame | null)[] { const frames: Array = []; const spriteFrames = this.spriteFrames; @@ -129,7 +130,7 @@ export class SpriteAtlas extends Asset { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _deserialize (serializeData: any, handle: any) { + public _deserialize (serializeData: any, handle: any): void { const data = serializeData as ISpriteAtlasSerializeData; this._name = data.name; const frames = data.spriteFrames; diff --git a/cocos/2d/assets/sprite-frame.ts b/cocos/2d/assets/sprite-frame.ts index 6d841fce3c9..abc7d4194f3 100644 --- a/cocos/2d/assets/sprite-frame.ts +++ b/cocos/2d/assets/sprite-frame.ts @@ -35,7 +35,7 @@ import { Texture2D } from '../../asset/assets/texture-2d'; import { dynamicAtlasManager } from '../utils/dynamic-atlas/atlas-manager'; import { Mesh } from '../../3d/assets/mesh'; import { createMesh } from '../../3d/misc'; -import { Attribute, AttributeName, Format, PrimitiveMode } from '../../gfx'; +import { Attribute, AttributeName, Format, PrimitiveMode, Sampler, SamplerInfo, Texture } from '../../gfx'; import { ccwindow } from '../../core/global-exports'; const INSET_LEFT = 0; @@ -249,7 +249,7 @@ export class SpriteFrame extends Asset { * @zh 图像资源或图像原始图像源,图像原始图像源支持 HTMLCanvasElement HTMLImageElement IMemoryImageSource 三种资源。 * @returns @en SpriteFrame asset. @zh 精灵资源。 */ - public static createWithImage (imageSourceOrImageAsset: ImageSource | ImageAsset) { + public static createWithImage (imageSourceOrImageAsset: ImageSource | ImageAsset): SpriteFrame { const img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset); const tex = new Texture2D(); tex.image = img; @@ -269,7 +269,7 @@ export class SpriteFrame extends Asset { * @en Top border distance of sliced 9 rect. * @zh 九宫格内部矩形顶部边框距离 SpriteFrame 矩形的距离。 */ - get insetTop () { + get insetTop (): number { return this._capInsets[INSET_TOP]; } @@ -288,7 +288,7 @@ export class SpriteFrame extends Asset { * @en Bottom border distance of sliced 9 rect. * @zh 九宫格内部矩形底部边框距离 SpriteFrame 矩形的距离。 */ - get insetBottom () { + get insetBottom (): number { return this._capInsets[INSET_BOTTOM]; } @@ -307,7 +307,7 @@ export class SpriteFrame extends Asset { * @en Left border distance of sliced 9 rect. * @zh 九宫格内部矩形左边框距离 SpriteFrame 矩形的距离。 */ - get insetLeft () { + get insetLeft (): number { return this._capInsets[INSET_LEFT]; } @@ -326,7 +326,7 @@ export class SpriteFrame extends Asset { * @en Right border distance of sliced 9 rect. * @zh 九宫格内部矩形右边框距离 SpriteFrame 矩形的距离。 */ - get insetRight () { + get insetRight (): number { return this._capInsets[INSET_RIGHT]; } @@ -347,7 +347,7 @@ export class SpriteFrame extends Asset { * @zh 获取 SpriteFrame 的纹理矩形区域。 * 如果是一个 atlas 的贴图,则为当前贴图的实际剔除透明像素区域。 */ - get rect () { + get rect (): Rect { return this._rect; } @@ -367,7 +367,7 @@ export class SpriteFrame extends Asset { * @en The original size before trimmed. * @zh 修剪前的原始大小。 */ - get originalSize () { + get originalSize (): Size { return this._originalSize; } @@ -390,7 +390,7 @@ export class SpriteFrame extends Asset { * @zh 精灵帧偏移量。 * 在图集中的精灵帧可能会被剔除透明像素以获得更高的空间利用李,剔除后的矩形尺寸比剪裁前更小,偏移量指的是从原始矩形的中心到剪裁后的矩形中心的距离。 */ - get offset () { + get offset (): Vec2 { return this._offset; } @@ -403,7 +403,7 @@ export class SpriteFrame extends Asset { * @en Whether the content of sprite frame is rotated. * @zh 是否旋转。 */ - get rotated () { + get rotated (): boolean { return this._rotated; } @@ -422,7 +422,7 @@ export class SpriteFrame extends Asset { * @en The texture of the sprite frame, could be `TextureBase`. * @zh 贴图对象资源,可以是 `TextureBase` 类型。 */ - get texture () { + get texture (): TextureBase { return this._texture; } @@ -443,7 +443,7 @@ export class SpriteFrame extends Asset { * @en The uuid of the atlas asset, if exists. * @zh 图集资源的 uuid。 */ - get atlasUuid () { + get atlasUuid (): string { return this._atlasUuid; } @@ -455,7 +455,7 @@ export class SpriteFrame extends Asset { * @en The pixel width of the sprite frame. * @zh 精灵帧的像素宽度。 */ - get width () { + get width (): number { return this._texture.width; } @@ -463,7 +463,7 @@ export class SpriteFrame extends Asset { * @en The pixel height of the sprite frame. * @zh 精灵帧的像素高度。 */ - get height () { + get height (): number { return this._texture.height; } @@ -486,7 +486,7 @@ export class SpriteFrame extends Asset { * @en Whether flip the uv in X direction. * @zh 沿 X 轴方向, 翻转 UV。 */ - get flipUVX () { + get flipUVX (): boolean { return this._isFlipUVX; } @@ -499,7 +499,7 @@ export class SpriteFrame extends Asset { * @en Whether flip the uv in Y direction. * @zh 沿 Y 轴方向, 翻转 UV。 */ - get flipUVY () { + get flipUVY (): boolean { return this._isFlipUVY; } @@ -512,7 +512,7 @@ export class SpriteFrame extends Asset { * @en Sets whether sprite can be packed into dynamic atlas. * @zh 设置精灵是否允许参与自动合图。 */ - get packable () { + get packable (): boolean { return this._packable; } set packable (value: boolean) { @@ -523,7 +523,11 @@ export class SpriteFrame extends Asset { * @en Original information before packed to dynamic atlas, includes texture, width, height. It's null before being packed to dynamic atlas. * @zh 精灵自动合图之前的原始 texture 和宽高信息。在参与自动合图之前此值为 null。 */ - get original () { + get original (): { + _texture: TextureBase; + _x: number; + _y: number; + } | null { return this._original; } @@ -531,7 +535,7 @@ export class SpriteFrame extends Asset { * @en Number of pixels corresponding to unit size in world space (pixels per unit). * @zh 世界空间中的单位大小对应的像素数量(像素每单位)。 */ - get pixelsToUnit () { + get pixelsToUnit (): number { return this._pixelsToUnit; } @@ -539,7 +543,7 @@ export class SpriteFrame extends Asset { * @en Local origin position when generating the mesh. * @zh 生成 mesh 时本地坐标原点位置。 */ - get pivot () { + get pivot (): Vec2 { return this._pivot; } @@ -547,14 +551,14 @@ export class SpriteFrame extends Asset { * @en mesh information, you should call the [[ensureMeshData]] function before using it. * @zh mesh 信息,你应该在使用它之前调用 [[ensureMeshData]] 函数来确保其可用。 */ - get mesh () { + get mesh (): Mesh | null { return this._mesh; } /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get trimmedBorder () { + get trimmedBorder (): Vec4 { return this._trimmedBorder; } @@ -652,7 +656,7 @@ export class SpriteFrame extends Asset { * * @deprecated since v3.3, Useless Code. */ - public textureLoaded () { + public textureLoaded (): boolean { return !!this.texture; } @@ -663,7 +667,7 @@ export class SpriteFrame extends Asset { * 获取 SpriteFrame 是否旋转。 * @deprecated since v1.2, please use [[rotated]] instead. */ - public isRotated () { + public isRotated (): boolean { return this._rotated; } @@ -675,7 +679,7 @@ export class SpriteFrame extends Asset { * @param rotated @en rotated. @zh 是否旋转。 * @deprecated since v1.2, please use [[rotated]] instead. */ - public setRotated (rotated: boolean) { + public setRotated (rotated: boolean): void { this.rotated = rotated; } @@ -688,7 +692,7 @@ export class SpriteFrame extends Asset { * @returns @en The rect. @zh 矩形区域。 * @deprecated since v1.2, please use [[rect]]. */ - public getRect (out?: Rect) { + public getRect (out?: Rect): Rect { if (out) { out.set(this._rect); return out; @@ -703,7 +707,7 @@ export class SpriteFrame extends Asset { * @param rect @en The new rect. @zh 想要设置的 rect。 * @deprecated since v1.2, please use [[rect]]. */ - public setRect (rect: Rect) { + public setRect (rect: Rect): void { this.rect = rect; } @@ -714,7 +718,7 @@ export class SpriteFrame extends Asset { * @returns @en The original size. @zh 原始大小。 * @deprecated since v1.2, please use [[originalSize]]. */ - public getOriginalSize (out?: Size) { + public getOriginalSize (out?: Size): Size { if (out) { out.set(this._originalSize); return out; @@ -729,7 +733,7 @@ export class SpriteFrame extends Asset { * @param size @en The new original size. @zh 新设置的原始大小。 * @deprecated since v1.2, please use [[originalSize]]. */ - public setOriginalSize (size: Size) { + public setOriginalSize (size: Size): void { this.originalSize = size; } @@ -740,7 +744,7 @@ export class SpriteFrame extends Asset { * @returns @en The offset object. @zh 偏移量。 * @deprecated since v1.2, please use [[offset]] */ - public getOffset (out?: Vec2) { + public getOffset (out?: Vec2): Vec2 { if (out) { out.set(this._offset); return out; @@ -755,7 +759,7 @@ export class SpriteFrame extends Asset { * @param offset @en The new offset. @zh 新设置的偏移量。 * @deprecated since v1.2, please use [[offset]] */ - public setOffset (offset: Vec2) { + public setOffset (offset: Vec2): void { this.offset = offset; } @@ -764,7 +768,7 @@ export class SpriteFrame extends Asset { * @zh 获取渲染贴图的 GFX 资源。 * @returns @en Gfx Texture resource. @zh GFX 贴图资源。 */ - public getGFXTexture () { + public getGFXTexture (): Texture | null { return this._texture.getGFXTexture(); } @@ -773,7 +777,7 @@ export class SpriteFrame extends Asset { * @zh 贴图资源的采样器。 * @returns @en The GFX sampler resource. @zh GFX贴图采样器。 */ - public getGFXSampler () { + public getGFXSampler (): Sampler { return this._texture.getGFXSampler(); } @@ -782,7 +786,7 @@ export class SpriteFrame extends Asset { * @zh 贴图资源的哈希值。 * @returns @en Texture`s hash. @zh 贴图哈希值。 */ - public getHash () { + public getHash (): number { return this._texture.getHash(); } @@ -791,7 +795,7 @@ export class SpriteFrame extends Asset { * @zh 贴图资源的采样器哈希值。 * @returns @en Sampler`s hash. @zh 采样器哈希值。 */ - public getSamplerInfo () { + public getSamplerInfo (): Readonly { return this._texture.getSamplerInfo(); } @@ -801,7 +805,7 @@ export class SpriteFrame extends Asset { * @param info @en SpriteFrame initialization information. @zh SpriteFrame 初始化信息。 * @param clearData @en Clear Data before initialization. @zh 是否在初始化前清空原有数据。 */ - public reset (info?: ISpriteFrameInitInfo, clearData = false) { + public reset (info?: ISpriteFrameInitInfo, clearData = false): void { let calUV = false; if (clearData) { this._originalSize.set(0, 0); @@ -872,7 +876,7 @@ export class SpriteFrame extends Asset { * @param texture @en Texture resources for sprite frame. @zh SpriteFrame 的贴图资源。 * @returns @en Out of the texture boundary or not. @zh 矩形区域是否越界。 */ - public checkRect (texture: TextureBase) { + public checkRect (texture: TextureBase): boolean { const rect = this._rect; let maxX = rect.x; let maxY = rect.y; @@ -897,7 +901,7 @@ export class SpriteFrame extends Asset { return true; } - private _calcTrimmedBorder () { + private _calcTrimmedBorder (): void { const ow = this._originalSize.width; const oh = this._originalSize.height; const rw = this._rect.width; @@ -918,14 +922,14 @@ export class SpriteFrame extends Asset { * @en Make sure the mesh is available, you should call it before using the mesh. * @zh 确保 mesh 可用,你应该在使用 mesh 之前调用它。 */ - public ensureMeshData () { + public ensureMeshData (): void { if (this._mesh) return; // If SpriteFrame from load, we need init vertices when use mesh this._initVertices(); this._createMesh(); } - public destroy () { + public destroy (): boolean { if (this._packable && dynamicAtlasManager) { dynamicAtlasManager.deleteAtlasSpriteFrame(this); } @@ -936,7 +940,7 @@ export class SpriteFrame extends Asset { * Calculate UV for sliced * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _calculateSlicedUV () { + public _calculateSlicedUV (): void { const rect = this._rect; // const texture = this._getCalculateTarget()!; const tex = this.texture; @@ -1002,7 +1006,7 @@ export class SpriteFrame extends Asset { * Calculate UV * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _calculateUV () { + public _calculateUV (): void { const rect = this._rect; const uv = this.uv; const unbiasUV = this.unbiasUV; @@ -1226,7 +1230,7 @@ export class SpriteFrame extends Asset { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _setDynamicAtlasFrame (frame) { + public _setDynamicAtlasFrame (frame): void { if (!frame) return; this._original = { @@ -1244,7 +1248,7 @@ export class SpriteFrame extends Asset { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _resetDynamicAtlasFrame () { + public _resetDynamicAtlasFrame (): void { if (!this._original) return; this._rect.x = this._original._x; this._rect.y = this._original._y; @@ -1256,7 +1260,7 @@ export class SpriteFrame extends Asset { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _checkPackable () { + public _checkPackable (): void { const dynamicAtlas = dynamicAtlasManager; if (!dynamicAtlas) return; const texture = this._texture; @@ -1338,7 +1342,7 @@ export class SpriteFrame extends Asset { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _deserialize (serializeData: any, handle: any) { + public _deserialize (serializeData: any, handle: any): void { const data = serializeData as ISpriteFramesSerializeData; const rect = data.rect; if (rect) { @@ -1440,7 +1444,7 @@ export class SpriteFrame extends Asset { return sp; } - protected _refreshTexture (texture: TextureBase) { + protected _refreshTexture (texture: TextureBase): void { this._texture = texture; const tex = this._texture; const config: ISpriteFrameInitInfo = {}; @@ -1474,7 +1478,7 @@ export class SpriteFrame extends Asset { * @zh 加载完成回调。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public onLoaded () { + public onLoaded (): void { this._calcTrimmedBorder(); } @@ -1484,7 +1488,7 @@ export class SpriteFrame extends Asset { * @param uuid @en Asset uuid. @zh 资源 uuid。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); const texture = new Texture2D(); texture.initDefault(); @@ -1498,11 +1502,11 @@ export class SpriteFrame extends Asset { * @returns @en validate or not. @zh 是否有效。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public validate () { + public validate (): boolean { return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0; } - protected _initVertices () { + protected _initVertices (): void { if (!this.vertices) { this.vertices = { rawPosition: [], @@ -1584,7 +1588,7 @@ export class SpriteFrame extends Asset { } // Combine vertex information, unit information, anchor points, extrude and even customOutline to generate the actual vertices used - protected _updateMeshVertices () { + protected _updateMeshVertices (): void { // Start generating the Geometry information to generate the mesh temp_matrix.identity(); const units = 1 / this._pixelsToUnit; @@ -1605,7 +1609,7 @@ export class SpriteFrame extends Asset { Vec3.transformMat4(this._maxPos, vertices.maxPos, temp_matrix); } - protected _createMesh () { + protected _createMesh (): void { this._mesh = createMesh({ primitiveMode: PrimitiveMode.TRIANGLE_LIST, positions: this.vertices!.positions, @@ -1627,7 +1631,7 @@ export class SpriteFrame extends Asset { }); } - protected _updateMesh () { + protected _updateMesh (): void { if (this._mesh) { this._mesh.destroy(); } diff --git a/cocos/2d/assets/ttf-font.ts b/cocos/2d/assets/ttf-font.ts index f5ca236d547..fe0ef179365 100644 --- a/cocos/2d/assets/ttf-font.ts +++ b/cocos/2d/assets/ttf-font.ts @@ -44,7 +44,7 @@ export class TTFFont extends Font { */ @override @string - get _nativeAsset () { + get _nativeAsset (): string | null { return this._fontFamily; } set _nativeAsset (value) { @@ -55,7 +55,12 @@ export class TTFFont extends Font { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override - get _nativeDep () { + get _nativeDep (): { + uuid: string; + __nativeName__: string; + ext: string; + __isNative__: boolean; + } { return { uuid: this._uuid, __nativeName__: this._native, ext: path.extname(this._native), __isNative__: true }; } @@ -65,7 +70,7 @@ export class TTFFont extends Font { * @param uuid @en Asset uuid. @zh 资源 uuid。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { this._fontFamily = 'Arial'; super.initDefault(uuid); } diff --git a/cocos/2d/components/graphics.ts b/cocos/2d/components/graphics.ts index e36d97e8f0a..1f4fb1c8e32 100644 --- a/cocos/2d/components/graphics.ts +++ b/cocos/2d/components/graphics.ts @@ -69,7 +69,7 @@ export class Graphics extends UIRenderer { */ @editable @tooltip('i18n:graphics.lineWidth') - get lineWidth () { + get lineWidth (): number { return this._lineWidth; } set lineWidth (value) { @@ -90,7 +90,7 @@ export class Graphics extends UIRenderer { */ @type(LineJoin) @tooltip('i18n:graphics.lineJoin') - get lineJoin () { + get lineJoin (): LineJoin { return this._lineJoin; } @@ -112,7 +112,7 @@ export class Graphics extends UIRenderer { */ @type(LineCap) @tooltip('i18n:graphics.lineCap') - get lineCap () { + get lineCap (): LineCap { return this._lineCap; } @@ -177,7 +177,7 @@ export class Graphics extends UIRenderer { * 设置斜接面限制比例。 */ @tooltip('i18n:graphics.miterLimit') - get miterLimit () { + get miterLimit (): number { return this._miterLimit; } @@ -188,7 +188,7 @@ export class Graphics extends UIRenderer { @override @visible(false) - get color () { + get color (): Color { return this._color; } @@ -230,7 +230,7 @@ export class Graphics extends UIRenderer { /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get graphicsNativeProxy () { + get graphicsNativeProxy (): NativeUIModelProxy { return this._graphicsNativeProxy; } @@ -243,13 +243,13 @@ export class Graphics extends UIRenderer { } } - public onRestore () { + public onRestore (): void { if (!this.impl) { this._flushAssembler(); } } - public onLoad () { + public onLoad (): void { super.onLoad(); if (JSB) { this._graphicsNativeProxy.initModel(this.node); @@ -261,12 +261,12 @@ export class Graphics extends UIRenderer { this._flushAssembler(); } - public onEnable () { + public onEnable (): void { super.onEnable(); this._updateMtlForGraphics(); } - public onDestroy () { + public onDestroy (): void { this._sceneGetter = null; if (JSB) { this._graphicsNativeProxy.destroy(); @@ -307,7 +307,7 @@ export class Graphics extends UIRenderer { * @param y @en The y-axis coordinate of the target position. * @zh 目标位置的 y 轴坐标。 */ - public moveTo (x: number, y: number) { + public moveTo (x: number, y: number): void { if (!this.impl) { return; } @@ -327,7 +327,7 @@ export class Graphics extends UIRenderer { * @param y @en The x-axis coordinate of the target position. * @zh 目标位置的 y 轴坐标。 */ - public lineTo (x: number, y: number) { + public lineTo (x: number, y: number): void { if (!this.impl) { return; } @@ -355,7 +355,7 @@ export class Graphics extends UIRenderer { * @param y @en The y-axis coordinate of the last control point. * @zh 最后一个控制点的 y 轴坐标。 */ - public bezierCurveTo (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) { + public bezierCurveTo (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): void { if (!this.impl) { return; } @@ -379,7 +379,7 @@ export class Graphics extends UIRenderer { * @param y @en The y-axis coordinates of the endpoint control point. * @zh 终点控制点的 x 轴坐标。 */ - public quadraticCurveTo (cx: number, cy: number, x: number, y: number) { + public quadraticCurveTo (cx: number, cy: number, x: number, y: number): void { if (!this.impl) { return; } @@ -408,7 +408,7 @@ export class Graphics extends UIRenderer { * @param counterclockwise @en If true, draws counterclockwise between the two angles. Default is clockwise. * @zh 如果为真,在两个角度之间逆时针绘制。默认顺时针。 */ - public arc (cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean) { + public arc (cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean): void { if (!this.impl) { return; } @@ -432,7 +432,7 @@ export class Graphics extends UIRenderer { * @param ry @en The radius of the y-axis of the ellipse. * @zh 椭圆 y 轴半径。 */ - public ellipse (cx: number, cy: number, rx: number, ry: number) { + public ellipse (cx: number, cy: number, rx: number, ry: number): void { if (!this.impl) { return; } @@ -454,7 +454,7 @@ export class Graphics extends UIRenderer { * @param r @en Radius. * @zh 圆半径。 */ - public circle (cx: number, cy: number, r: number) { + public circle (cx: number, cy: number, r: number): void { if (!this.impl) { return; } @@ -478,7 +478,7 @@ export class Graphics extends UIRenderer { * @param h @en The height of the rectangle. * @zh 矩形高度。 */ - public rect (x: number, y: number, w: number, h: number) { + public rect (x: number, y: number, w: number, h: number): void { if (!this.impl) { return; } @@ -504,7 +504,7 @@ export class Graphics extends UIRenderer { * @param r @en Radius of rectangular rounded corners. * @zh 矩形圆角半径。 */ - public roundRect (x: number, y: number, w: number, h: number, r: number) { + public roundRect (x: number, y: number, w: number, h: number, r: number): void { if (!this.impl) { return; } @@ -528,7 +528,7 @@ export class Graphics extends UIRenderer { * @param h @en The height of the rectangle. * @zh 矩形高度。 */ - public fillRect (x, y, w, h) { + public fillRect (x, y, w, h): void { this.rect(x, y, w, h); this.fill(); } @@ -540,7 +540,7 @@ export class Graphics extends UIRenderer { * @zh * 擦除之前绘制的所有内容的方法。 */ - public clear () { + public clear (): void { if (!this.impl) { return; } @@ -567,7 +567,7 @@ export class Graphics extends UIRenderer { * @zh * 将笔点返回到当前路径起始点的。它尝试从当前点到起始点绘制一条直线。 */ - public close () { + public close (): void { if (!this.impl) { return; } @@ -582,7 +582,7 @@ export class Graphics extends UIRenderer { * @zh * 根据当前的画线样式,绘制当前或已经存在的路径。 */ - public stroke () { + public stroke (): void { if (!this._assembler) { this._flushAssembler(); } @@ -599,7 +599,7 @@ export class Graphics extends UIRenderer { * @zh * 根据当前的画线样式,填充当前或已经存在的路径。 */ - public fill () { + public fill (): void { if (!this._assembler) { this._flushAssembler(); } @@ -609,7 +609,7 @@ export class Graphics extends UIRenderer { (this._assembler as IAssembler).fill!(this); } - private _updateMtlForGraphics () { + private _updateMtlForGraphics (): void { let mat; if (this._customMaterial) { mat = this.getMaterialInstance(0); @@ -624,7 +624,7 @@ export class Graphics extends UIRenderer { /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public activeSubModel (idx: number) { + public activeSubModel (idx: number): void { if (!this.model) { warnID(4500, this.node.name); return; @@ -653,7 +653,7 @@ export class Graphics extends UIRenderer { } } - protected _uploadData () { + protected _uploadData (): void { const impl = this.impl; if (!impl) { return; @@ -685,7 +685,7 @@ export class Graphics extends UIRenderer { this._isNeedUploadData = false; } - protected _render (render: IBatcher) { + protected _render (render: IBatcher): void { if (this._isNeedUploadData) { if (this.impl) { const renderDataList = this.impl.getRenderDataList(); @@ -702,7 +702,7 @@ export class Graphics extends UIRenderer { render.commitModel(this, this.model, this.getMaterialInstance(0)); } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = Graphics.Assembler.getAssembler(this); if (this._assembler !== assembler) { @@ -710,7 +710,7 @@ export class Graphics extends UIRenderer { } } - protected _canRender () { + protected _canRender (): boolean { if (!super._canRender()) { return false; } @@ -725,7 +725,7 @@ export class Graphics extends UIRenderer { /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public updateRenderer () { + public updateRenderer (): void { super.updateRenderer(); if (JSB) { if (this._isNeedUploadData) { @@ -742,7 +742,7 @@ export class Graphics extends UIRenderer { } } - protected createRenderEntity () { + protected createRenderEntity (): RenderEntity { return new RenderEntity(RenderEntityType.DYNAMIC); } } diff --git a/cocos/2d/components/label-outline.ts b/cocos/2d/components/label-outline.ts index d90473ad87b..ba50ae80fa8 100644 --- a/cocos/2d/components/label-outline.ts +++ b/cocos/2d/components/label-outline.ts @@ -98,7 +98,7 @@ export class LabelOutline extends Component { * ``` */ @tooltip('i18n:labelOutline.width') - get width () { + get width (): number { return this._width; } @@ -111,15 +111,15 @@ export class LabelOutline extends Component { this._updateRenderData(); } - public onEnable () { + public onEnable (): void { this._updateRenderData(); } - public onDisable () { + public onDisable (): void { this._updateRenderData(); } - protected _updateRenderData () { + protected _updateRenderData (): void { const label = this.node.getComponent(Label); if (label) { label.updateRenderData(true); diff --git a/cocos/2d/components/label-shadow.ts b/cocos/2d/components/label-shadow.ts index f8308c1fc63..bab05719cbd 100644 --- a/cocos/2d/components/label-shadow.ts +++ b/cocos/2d/components/label-shadow.ts @@ -94,7 +94,7 @@ export class LabelShadow extends Component { * ``` */ @tooltip('i18n:labelShadow.offset') - get offset () { + get offset (): Vec2 { return this._offset; } @@ -116,7 +116,7 @@ export class LabelShadow extends Component { * ``` */ @tooltip('i18n:labelShadow.blur') - get blur () { + get blur (): number { return this._blur; } @@ -125,15 +125,15 @@ export class LabelShadow extends Component { this._updateRenderData(); } - public onEnable () { + public onEnable (): void { this._updateRenderData(); } - public onDisable () { + public onDisable (): void { this._updateRenderData(); } - protected _updateRenderData () { + protected _updateRenderData (): void { const label = this.node.getComponent(Label); if (label) { label.updateRenderData(true); diff --git a/cocos/2d/components/label.ts b/cocos/2d/components/label.ts index 7248eb880f8..6274761ca3a 100644 --- a/cocos/2d/components/label.ts +++ b/cocos/2d/components/label.ts @@ -214,7 +214,7 @@ export class Label extends UIRenderer { @displayOrder(4) @tooltip('i18n:label.string') @multiline - get string () { + get string (): string { return this._string; } set string (value) { @@ -242,7 +242,7 @@ export class Label extends UIRenderer { @type(HorizontalTextAlignment) @displayOrder(5) @tooltip('i18n:label.horizontal_align') - get horizontalAlign () { + get horizontalAlign (): HorizontalTextAlignment { return this._horizontalAlign; } set horizontalAlign (value) { @@ -264,7 +264,7 @@ export class Label extends UIRenderer { @type(VerticalTextAlignment) @displayOrder(6) @tooltip('i18n:label.vertical_align') - get verticalAlign () { + get verticalAlign (): VerticalTextAlignment { return this._verticalAlign; } set verticalAlign (value) { @@ -283,7 +283,7 @@ export class Label extends UIRenderer { * @zh * SHRINK 模式下面文本实际渲染的字体大小。 */ - get actualFontSize () { + get actualFontSize (): number { return this._actualFontSize; } set actualFontSize (value) { @@ -299,7 +299,7 @@ export class Label extends UIRenderer { */ @displayOrder(7) @tooltip('i18n:label.font_size') - get fontSize () { + get fontSize (): number { return this._fontSize; } set fontSize (value) { @@ -320,7 +320,7 @@ export class Label extends UIRenderer { */ @displayOrder(8) @tooltip('i18n:label.line_height') - get lineHeight () { + get lineHeight (): number { return this._lineHeight; } set lineHeight (value) { @@ -344,7 +344,7 @@ export class Label extends UIRenderer { }) @displayOrder(9) @tooltip('i18n:label.spacing_x') - get spacingX () { + get spacingX (): number { return this._spacingX; } set spacingX (value) { @@ -366,7 +366,7 @@ export class Label extends UIRenderer { @type(Overflow) @displayOrder(10) @tooltip('i18n:label.overflow') - get overflow () { + get overflow (): Overflow { return this._overflow; } set overflow (value) { @@ -387,7 +387,7 @@ export class Label extends UIRenderer { */ @displayOrder(11) @tooltip('i18n:label.wrap') - get enableWrapText () { + get enableWrapText (): boolean { return this._enableWrapText; } set enableWrapText (value) { @@ -408,7 +408,7 @@ export class Label extends UIRenderer { */ @displayOrder(12) @tooltip('i18n:label.system_font') - get useSystemFont () { + get useSystemFont (): boolean { return this._isSystemFontUsed; } set useSystemFont (value) { @@ -444,7 +444,7 @@ export class Label extends UIRenderer { @displayOrder(13) @visible(function (this: Label) { return this._isSystemFontUsed; }) @tooltip('i18n:label.font_family') - get fontFamily () { + get fontFamily (): string { return this._fontFamily; } set fontFamily (value) { @@ -467,7 +467,7 @@ export class Label extends UIRenderer { @displayOrder(13) @visible(function (this: Label) { return !this._isSystemFontUsed; }) @tooltip('i18n:label.font') - get font () { + get font (): Font | null { // return this._N$file; return this._font; } @@ -504,7 +504,7 @@ export class Label extends UIRenderer { @type(CacheMode) @displayOrder(14) @tooltip('i18n:label.cache_mode') - get cacheMode () { + get cacheMode (): CacheMode { return this._cacheMode; } set cacheMode (value) { @@ -532,7 +532,7 @@ export class Label extends UIRenderer { */ @displayOrder(15) @tooltip('i18n:label.font_bold') - get isBold () { + get isBold (): boolean { return this._isBold; } set isBold (value) { @@ -553,7 +553,7 @@ export class Label extends UIRenderer { */ @displayOrder(16) @tooltip('i18n:label.font_italic') - get isItalic () { + get isItalic (): boolean { return this._isItalic; } set isItalic (value) { @@ -574,7 +574,7 @@ export class Label extends UIRenderer { */ @displayOrder(17) @tooltip('i18n:label.font_underline') - get isUnderline () { + get isUnderline (): boolean { return this._isUnderline; } set isUnderline (value) { @@ -594,7 +594,7 @@ export class Label extends UIRenderer { @editable @displayOrder(18) @tooltip('i18n:label.underline_height') - public get underlineHeight () { + public get underlineHeight (): number { return this._underlineHeight; } public set underlineHeight (value) { @@ -606,28 +606,28 @@ export class Label extends UIRenderer { /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get spriteFrame () { + get spriteFrame (): SpriteFrame | LetterRenderTexture | null { return this._texture; } /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get ttfSpriteFrame () { + get ttfSpriteFrame (): SpriteFrame | null { return this._ttfSpriteFrame; } /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get assemblerData () { + get assemblerData (): ISharedLabelData | null { return this._assemblerData; } /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get fontAtlas () { + get fontAtlas (): FontAtlas | null { return this._fontAtlas; } @@ -638,7 +638,7 @@ export class Label extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - get _bmFontOriginalSize () { + get _bmFontOriginalSize (): number { if (this._font instanceof BitmapFont) { return this._font.fontSize; } else { @@ -649,25 +649,25 @@ export class Label extends UIRenderer { /** * @engineInternal */ - get textStyle () { + get textStyle (): TextStyle { return this._textStyle!; } /** * @engineInternal */ - get textLayout () { + get textLayout (): TextLayout { return this._textLayout!; } /** * @engineInternal */ - get textRenderData () { + get textRenderData (): TextOutputRenderData { return this._textRenderData!; } /** * @engineInternal */ - get textLayoutData () { + get textLayoutData (): TextOutputLayoutData { return this._textLayoutData!; } @@ -726,7 +726,7 @@ export class Label extends UIRenderer { /** * @engineInternal */ - get contentWidth () { + get contentWidth (): number { return this._contentWidth; } @@ -750,7 +750,7 @@ export class Label extends UIRenderer { this._textRenderData = new TextOutputRenderData(); } - public onEnable () { + public onEnable (): void { super.onEnable(); // TODO: Hack for barbarians @@ -765,7 +765,7 @@ export class Label extends UIRenderer { this._applyFontTexture(); } - public onDestroy () { + public onDestroy (): void { if (this._assembler && this._assembler.resetAssemblerData) { this._assembler.resetAssemblerData(this._assemblerData!); } @@ -801,7 +801,7 @@ export class Label extends UIRenderer { * @zh 更新渲染相关数据。 * @param force @en Whether to force an immediate update. @zh 是否立马强制更新渲染数据。 */ - public updateRenderData (force = false) { + public updateRenderData (force = false): void { if (force) { this._flushAssembler(); // Hack: Fixed the bug that richText wants to get the label length by _measureText, @@ -814,12 +814,12 @@ export class Label extends UIRenderer { } } - protected _render (render: IBatcher) { + protected _render (render: IBatcher): void { render.commitComp(this, this.renderData, this._texture, this._assembler!, null); } // Cannot use the base class methods directly because BMFont and CHAR cannot be updated in assambler with just color. - protected _updateColor () { + protected _updateColor (): void { super._updateColor(); this.markForUpdateRenderData(); } @@ -827,7 +827,7 @@ export class Label extends UIRenderer { /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setEntityColor (color: Color) { + public setEntityColor (color: Color): void { if (JSB) { if (this._font instanceof BitmapFont) { this._renderEntity.color = color; @@ -838,7 +838,7 @@ export class Label extends UIRenderer { } } - protected _canRender () { + protected _canRender (): boolean { if (!super._canRender() || !this._string) { return false; } @@ -855,7 +855,7 @@ export class Label extends UIRenderer { return true; } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = Label.Assembler.getAssembler(this); if (this._assembler !== assembler) { @@ -876,7 +876,7 @@ export class Label extends UIRenderer { } } - protected _applyFontTexture () { + protected _applyFontTexture (): void { this.markForUpdateRenderData(); const font = this._font; if (font instanceof BitmapFont) { @@ -912,7 +912,7 @@ export class Label extends UIRenderer { } } - protected changeMaterialForDefine () { + protected changeMaterialForDefine (): void { if (!this._texture) { return; } @@ -936,7 +936,7 @@ export class Label extends UIRenderer { /** * @engineInternal */ - public _updateBlendFunc () { + public _updateBlendFunc (): void { // override for BYTEDANCE if (BYTEDANCE) { // need to fix ttf font black border at the sdk verion lower than 2.0.0 diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index 19ff7976b48..afaf7dfb44a 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -33,13 +33,15 @@ import { NodeEventProcessor } from '../../scene-graph/node-event-processor'; import { MaskMode } from '../renderer/render-entity'; import { Sprite } from './sprite'; import { NodeEventType, Component } from '../../scene-graph'; +import type { SpriteFrame } from '../assets'; +import type { Material } from '../../asset/assets'; const _worldMatrix = new Mat4(); const _vec2_temp = new Vec2(); const _mat4_temp = new Mat4(); const _circlePoints: Vec3[] = []; -function _calculateCircle (center: Vec3, radius: Vec3, segments: number) { +function _calculateCircle (center: Vec3, radius: Vec3, segments: number): Vec3[] { _circlePoints.length = 0; const anglePerStep = Math.PI * 2 / segments; for (let step = 0; step < segments; ++step) { @@ -122,7 +124,7 @@ export class Mask extends Component { */ @type(MaskType) @tooltip('i18n:mask.type') - get type () { + get type (): MaskType { return this._type; } @@ -166,7 +168,7 @@ export class Mask extends Component { */ @displayOrder(14) @tooltip('i18n:mask.inverted') - get inverted () { + get inverted (): boolean { return this._inverted; } @@ -190,7 +192,7 @@ export class Mask extends Component { @visible(function (this: Mask) { return this.type === MaskType.GRAPHICS_ELLIPSE; }) - get segments () { + get segments (): number { return this._segments; } @@ -211,7 +213,7 @@ export class Mask extends Component { * 遮罩所需要的贴图。 * @deprecated since v3.6.1 */ - get spriteFrame () { + get spriteFrame (): SpriteFrame | null { if (this._sprite) { return this._sprite.spriteFrame; } @@ -239,12 +241,12 @@ export class Mask extends Component { * 该数值 0 ~ 1 之间的浮点数,默认值为 0.1 * 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容 */ - @visible(function (this: Mask) { + @visible(function (this: Mask): boolean { return this.type === MaskType.SPRITE_STENCIL; }) @range([0, 1, 0.1]) @slide - get alphaThreshold () { + get alphaThreshold (): number { return this._alphaThreshold; } @@ -264,7 +266,7 @@ export class Mask extends Component { * @en Rendering component for providing stencil buffer information. * @zh 用于提供 stencil buffer 信息的渲染组件。 */ - get subComp () { + get subComp (): Sprite | Graphics | null { return this._graphics || this._sprite; } @@ -285,7 +287,7 @@ export class Mask extends Component { protected _stencilStage: Stage = Stage.DISABLED; - public onLoad () { + public onLoad (): void { this._changeRenderType(); if (JSB) { @@ -295,7 +297,7 @@ export class Mask extends Component { } } - public onEnable () { + public onEnable (): void { this._changeRenderType();// Maybe useless,a protect,may effect custom setting this._updateGraphics(); this._enableRender(); @@ -303,18 +305,18 @@ export class Mask extends Component { this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); } - public onRestore () { + public onRestore (): void { this._changeRenderType(); this._updateGraphics(); } - public onDisable () { + public onDisable (): void { this._disableRender(); this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this); this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); } - public onDestroy () { + public onDestroy (): void { this._removeMaskNode(); } @@ -323,7 +325,7 @@ export class Mask extends Component { * @zh 世界空间中的点击测试。 * @param worldPt @en point in World Space. @zh 世界空间中的点击点。 */ - public isHit (worldPt: Vec2) { + public isHit (worldPt: Vec2): boolean { const uiTrans = this.node._uiProps.uiTransformComp!; const size = uiTrans.contentSize; const w = size.width; @@ -355,11 +357,11 @@ export class Mask extends Component { return result; } - protected _nodeStateChange (type: TransformBit) { + protected _nodeStateChange (type: TransformBit): void { this._updateGraphics(); } - private _changeRenderType () { + private _changeRenderType (): void { const isGraphics = (this._type !== MaskType.SPRITE_STENCIL); if (isGraphics) { this._createGraphics(); @@ -368,7 +370,7 @@ export class Mask extends Component { } } - protected _createSprite () { + protected _createSprite (): void { if (!this._sprite) { let sprite = this._sprite = this.node.getComponent(Sprite); if (!sprite) { @@ -382,7 +384,7 @@ export class Mask extends Component { this._sprite!.updateMaterial(); } - protected _createGraphics () { + protected _createGraphics (): void { if (!this._graphics) { let graphics = this._graphics = this.node.getComponent(Graphics); if (!graphics) { @@ -397,7 +399,7 @@ export class Mask extends Component { this._graphics!.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; } - protected _updateGraphics () { + protected _updateGraphics (): void { if (!this._graphics || (this._type !== MaskType.GRAPHICS_RECT && this._type !== MaskType.GRAPHICS_ELLIPSE)) { return; } @@ -432,13 +434,13 @@ export class Mask extends Component { graphics.fill(); } - protected _enableRender () { + protected _enableRender (): void { if (this.subComp) { this.subComp.enabled = true; } } - protected _disableRender () { + protected _disableRender (): void { if (this.subComp) { this.subComp.stencilStage = Stage.DISABLED; this.subComp.updateMaterial(); @@ -448,7 +450,7 @@ export class Mask extends Component { } } - protected _removeMaskNode () { + protected _removeMaskNode (): void { if (this._sprite) { this._sprite.destroy(); this._sprite = null; @@ -463,7 +465,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - get customMaterial () { + get customMaterial (): Material | null { warnID(9007); if (this.subComp) { return this.subComp.customMaterial; @@ -479,7 +481,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - get color () { + get color (): Color | null { warnID(9007); if (this.subComp) { return this.subComp.color; @@ -495,7 +497,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public markForUpdateRenderData (enable = true) { + public markForUpdateRenderData (enable = true): void { warnID(9007); if (this.subComp) { this.subComp.markForUpdateRenderData(enable); @@ -504,20 +506,20 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public requestRenderData (any) { + public requestRenderData (any): void { warnID(9007); } /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public destroyRenderData () { + public destroyRenderData (): void { warnID(9007); } /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public updateRenderer () { + public updateRenderer (): void { warnID(9007); if (this.subComp) { this.subComp.updateRenderer(); @@ -527,19 +529,19 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public fillBuffers (render: any) { + public fillBuffers (render: any): void { warnID(9007); } /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public postUpdateAssembler (render: any) { + public postUpdateAssembler (render: any): void { warnID(9007); } /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public setNodeDirty () { + public setNodeDirty (): void { warnID(9007); if (this.subComp) { this.subComp.setNodeDirty(); @@ -548,7 +550,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public setTextureDirty () { + public setTextureDirty (): void { warnID(9007); if (this.subComp) { this.subComp.setTextureDirty(); @@ -557,7 +559,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - get sharedMaterial () { + get sharedMaterial (): Material | null { warnID(9007); if (this.subComp) { return this.subComp.sharedMaterial; @@ -567,7 +569,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - get sharedMaterials () { + get sharedMaterials (): (Material | null)[] | null { warnID(9007); if (this.subComp) { return this.subComp.sharedMaterials; @@ -625,7 +627,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public setMaterial (material: any, index: number) { + public setMaterial (material: any, index: number): void { warnID(9007); if (this.subComp) { this.subComp.setMaterial(material, index); @@ -644,7 +646,7 @@ export class Mask extends Component { /** * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation */ - public setMaterialInstance (matInst: any, index: number) { + public setMaterialInstance (matInst: any, index: number): void { warnID(9007); if (this.subComp) { this.subComp.setMaterialInstance(matInst, index); diff --git a/cocos/2d/components/rich-text.ts b/cocos/2d/components/rich-text.ts index 6ee65a2ef43..385f5cb2647 100644 --- a/cocos/2d/components/rich-text.ts +++ b/cocos/2d/components/rich-text.ts @@ -84,7 +84,7 @@ function createSegment (type: string): ISegment { }; } -function getSegmentByPool (type: string, content: string | SpriteFrame) { +function getSegmentByPool (type: string, content: string | SpriteFrame): ISegment | null { let seg; if (type === RichTextChildName) { seg = labelPool._get(); @@ -156,7 +156,7 @@ export class RichText extends Component { */ @multiline @tooltip('i18n:richtext.string') - get string () { + get string (): string { return this._string; } set string (value) { @@ -177,7 +177,7 @@ export class RichText extends Component { */ @type(HorizontalTextAlignment) @tooltip('i18n:richtext.horizontal_align') - get horizontalAlign () { + get horizontalAlign (): HorizontalTextAlignment { return this._horizontalAlign; } @@ -200,7 +200,7 @@ export class RichText extends Component { */ @type(VerticalTextAlignment) @tooltip('i18n:richtext.vertical_align') - get verticalAlign () { + get verticalAlign (): VerticalTextAlignment { return this._verticalAlign; } @@ -222,7 +222,7 @@ export class RichText extends Component { * 富文本字体大小。 */ @tooltip('i18n:richtext.font_size') - get fontSize () { + get fontSize (): number { return this._fontSize; } @@ -244,7 +244,7 @@ export class RichText extends Component { * 富文本定制系统字体。 */ @tooltip('i18n:richtext.font_family') - get fontFamily () { + get fontFamily (): string { return this._fontFamily; } set fontFamily (value: string) { @@ -263,7 +263,7 @@ export class RichText extends Component { */ @type(Font) @tooltip('i18n:richtext.font') - get font () { + get font (): TTFFont | null { return this._font; } set font (value) { @@ -293,7 +293,7 @@ export class RichText extends Component { */ @tooltip('i18n:richtext.use_system_font') @displayOrder(12) - get useSystemFont () { + get useSystemFont (): boolean { return this._isSystemFontUsed; } set useSystemFont (value: boolean) { @@ -324,7 +324,7 @@ export class RichText extends Component { */ @type(CacheMode) @tooltip('i18n:richtext.cache_mode') - get cacheMode () { + get cacheMode (): CacheMode { return this._cacheMode; } set cacheMode (value: CacheMode) { @@ -343,7 +343,7 @@ export class RichText extends Component { * 富文本的最大宽度。 */ @tooltip('i18n:richtext.max_width') - get maxWidth () { + get maxWidth (): number { return this._maxWidth; } @@ -365,7 +365,7 @@ export class RichText extends Component { * 富文本行高。 */ @tooltip('i18n:richtext.line_height') - get lineHeight () { + get lineHeight (): number { return this._lineHeight; } @@ -388,7 +388,7 @@ export class RichText extends Component { */ @type(SpriteAtlas) @tooltip('i18n:richtext.image_atlas') - get imageAtlas () { + get imageAtlas (): SpriteAtlas | null { return this._imageAtlas; } @@ -411,7 +411,7 @@ export class RichText extends Component { * 选中此选项后,RichText 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点。 */ @tooltip('i18n:richtext.handleTouchEvent') - get handleTouchEvent () { + get handleTouchEvent (): boolean { return this._handleTouchEvent; } @@ -490,12 +490,12 @@ export class RichText extends Component { this._updateRichTextStatus = this._updateRichText; } - public onLoad () { + public onLoad (): void { this.node.on(NodeEventType.LAYER_CHANGED, this._applyLayer, this); this.node.on(NodeEventType.ANCHOR_CHANGED, this._updateRichTextPosition, this); } - public onEnable () { + public onEnable (): void { if (this.handleTouchEvent) { this._addEventListeners(); } @@ -504,7 +504,7 @@ export class RichText extends Component { this._activateChildren(true); } - public onDisable () { + public onDisable (): void { if (this.handleTouchEvent) { this._removeEventListeners(); } @@ -512,7 +512,7 @@ export class RichText extends Component { this._activateChildren(false); } - public onRestore () { + public onRestore (): void { if (!EDITOR) { return; } @@ -527,7 +527,7 @@ export class RichText extends Component { } } - public onDestroy () { + public onDestroy (): void { for (const seg of this._segments) { seg.node.removeFromParent(); if (seg.type === RichTextChildName) { @@ -541,15 +541,15 @@ export class RichText extends Component { this.node.off(NodeEventType.LAYER_CHANGED, this._applyLayer, this); } - protected _addEventListeners () { + protected _addEventListeners (): void { this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this); } - protected _removeEventListeners () { + protected _removeEventListeners (): void { this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this); } - protected _updateLabelSegmentTextAttributes () { + protected _updateLabelSegmentTextAttributes (): void { this._segments.forEach((item) => { this._applyTextAttribute(item); }); @@ -563,7 +563,7 @@ export class RichText extends Component { return getSegmentByPool(RichTextChildImageName, spriteFrame)!; } - protected _onTTFLoaded () { + protected _onTTFLoaded (): void { if (this._font instanceof TTFFont) { this._layoutDirty = true; this._updateRichText(); @@ -576,7 +576,7 @@ export class RichText extends Component { /** * @engineInternal */ - protected splitLongStringApproximatelyIn2048 (text: string, styleIndex: number) { + protected splitLongStringApproximatelyIn2048 (text: string, styleIndex: number): string[] { const approxSize = text.length * this.fontSize; const partStringArr: string[] = []; // avoid that many short richtext still execute _calculateSize so that performance is low @@ -607,7 +607,7 @@ export class RichText extends Component { /** * @engineInternal */ - protected splitLongStringOver2048 (text: string, styleIndex: number) { + protected splitLongStringOver2048 (text: string, styleIndex: number): string[] { const partStringArr: string[] = []; const longStr = text; @@ -713,8 +713,8 @@ export class RichText extends Component { return partStringArr; } - protected _measureText (styleIndex: number, string?: string) { - const func = (s: string) => { + protected _measureText (styleIndex: number, string?: string): number | ((s: string) => number) { + const func = (s: string): number => { const width = this._calculateSize(_tempSize, styleIndex, s).x; return width; }; @@ -728,7 +728,7 @@ export class RichText extends Component { /** * @engineInternal */ - protected _calculateSize (out: Vec2, styleIndex: number, s: string) { + protected _calculateSize (out: Vec2, styleIndex: number, s: string): Vec2 { let label: ISegment; if (this._labelSegmentsCache.length === 0) { label = this._createFontLabel(s); @@ -744,7 +744,7 @@ export class RichText extends Component { return out; } - protected _onTouchEnded (event: EventTouch) { + protected _onTouchEnded (event: EventTouch): void { const components = this.node.getComponents(Component); for (const seg of this._segments) { @@ -762,7 +762,7 @@ export class RichText extends Component { } } - protected _containsTouchLocation (label: ISegment, point: Vec2) { + protected _containsTouchLocation (label: ISegment, point: Vec2): boolean { const comp = label.node.getComponent(UITransform); if (!comp) { return false; @@ -772,7 +772,7 @@ export class RichText extends Component { return myRect.contains(point); } - protected _resetState () { + protected _resetState (): void { const children = this.node.children; for (let i = children.length - 1; i >= 0; i--) { @@ -806,7 +806,7 @@ export class RichText extends Component { this._layoutDirty = true; } - protected _activateChildren (active) { + protected _activateChildren (active): void { for (let i = this.node.children.length - 1; i >= 0; i--) { const child = this.node.children[i]; if (child.name === RichTextChildName || child.name === RichTextChildImageName) { @@ -815,7 +815,7 @@ export class RichText extends Component { } } - protected _addLabelSegment (stringToken: string, styleIndex: number) { + protected _addLabelSegment (stringToken: string, styleIndex: number): ISegment { let labelSegment: ISegment; if (this._labelSegmentsCache.length === 0) { labelSegment = this._createFontLabel(stringToken); @@ -845,7 +845,7 @@ export class RichText extends Component { return labelSegment; } - protected _updateRichTextWithMaxWidth (labelString: string, labelWidth: number, styleIndex: number) { + protected _updateRichTextWithMaxWidth (labelString: string, labelWidth: number, styleIndex: number): void { let fragmentWidth = labelWidth; let labelSegment: ISegment; @@ -890,17 +890,17 @@ export class RichText extends Component { } } - protected _isLastComponentCR (stringToken) { + protected _isLastComponentCR (stringToken): boolean { return stringToken.length - 1 === stringToken.lastIndexOf('\n'); } - protected _updateLineInfo () { + protected _updateLineInfo (): void { this._linesWidth.push(this._lineOffsetX); this._lineOffsetX = 0; this._lineCount++; } - protected _needsUpdateTextLayout (newTextArray: IHtmlTextParserResultObj[]) { + protected _needsUpdateTextLayout (newTextArray: IHtmlTextParserResultObj[]): boolean { if (this._layoutDirty || !this._textArray || !newTextArray) { return true; } @@ -946,7 +946,7 @@ export class RichText extends Component { return false; } - protected _addRichTextImageElement (richTextElement: IHtmlTextParserResultObj) { + protected _addRichTextImageElement (richTextElement: IHtmlTextParserResultObj): void { if (!richTextElement.style) { return; } @@ -1023,7 +1023,7 @@ export class RichText extends Component { } } - protected _updateRichText () { + protected _updateRichText (): void { if (!this.enabledInHierarchy) { return; } @@ -1115,7 +1115,7 @@ export class RichText extends Component { this._layoutDirty = false; } - protected _getFirstWordLen (text: string, startIndex: number, textLen: number) { + protected _getFirstWordLen (text: string, startIndex: number, textLen: number): number { let character = text.charAt(startIndex); if (isUnicodeCJK(character) || isUnicodeSpace(character)) { return 1; @@ -1134,7 +1134,7 @@ export class RichText extends Component { return len; } - protected _updateRichTextPosition () { + protected _updateRichTextPosition (): void { let nextTokenX = 0; let nextLineIndex = 1; const totalLineCount = this._lineCount; @@ -1215,7 +1215,7 @@ export class RichText extends Component { } } - protected _convertLiteralColorValue (color: string) { + protected _convertLiteralColorValue (color: string): Color { const colorValue = color.toUpperCase(); if (Color[colorValue]) { const colorUse: Color = Color[colorValue]; @@ -1226,7 +1226,7 @@ export class RichText extends Component { } } - protected _applyTextAttribute (labelSeg: ISegment) { + protected _applyTextAttribute (labelSeg: ISegment): void { const label = labelSeg.node.getComponent(Label); if (!label) { return; @@ -1285,13 +1285,13 @@ export class RichText extends Component { label.updateRenderData(true); } - protected _applyLayer () { + protected _applyLayer (): void { for (const seg of this._segments) { seg.node.layer = this.node.layer; } } - protected _resetLabelState (label: Label) { + protected _resetLabelState (label: Label): void { label.fontSize = this._fontSize; label.color = Color.WHITE; label.isBold = false; diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 3a71536264f..4af575e7e5d 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -177,7 +177,7 @@ export class Sprite extends UIRenderer { @type(SpriteAtlas) @displayOrder(4) @tooltip('i18n:sprite.atlas') - get spriteAtlas () { + get spriteAtlas (): SpriteAtlas | null { return this._atlas; } set spriteAtlas (value) { @@ -197,7 +197,7 @@ export class Sprite extends UIRenderer { @type(SpriteFrame) @displayOrder(5) @tooltip('i18n:sprite.sprite_frame') - get spriteFrame () { + get spriteFrame (): SpriteFrame | null { return this._spriteFrame; } set spriteFrame (value) { @@ -230,7 +230,7 @@ export class Sprite extends UIRenderer { @type(SpriteType) @displayOrder(6) @tooltip('i18n:sprite.type') - get type () { + get type (): SpriteType { return this._type; } set type (value: SpriteType) { @@ -256,7 +256,7 @@ export class Sprite extends UIRenderer { @type(FillType) @displayOrder(6) @tooltip('i18n:sprite.fill_type') - get fillType () { + get fillType (): FillType { return this._fillType; } set fillType (value: FillType) { @@ -287,7 +287,7 @@ export class Sprite extends UIRenderer { */ @displayOrder(6) @tooltip('i18n:sprite.fill_center') - get fillCenter () { + get fillCenter (): Vec2 { return this._fillCenter; } set fillCenter (value) { @@ -314,7 +314,7 @@ export class Sprite extends UIRenderer { @range([0, 1, 0.1]) @displayOrder(6) @tooltip('i18n:sprite.fill_start') - get fillStart () { + get fillStart (): number { return this._fillStart; } @@ -342,7 +342,7 @@ export class Sprite extends UIRenderer { @range([-1, 1, 0.1]) @displayOrder(6) @tooltip('i18n:sprite.fill_range') - get fillRange () { + get fillRange (): number { return this._fillRange; } set fillRange (value) { @@ -370,7 +370,7 @@ export class Sprite extends UIRenderer { }) @displayOrder(8) @tooltip('i18n:sprite.trim') - get trim () { + get trim (): boolean { return this._isTrimmedMode; } @@ -393,7 +393,7 @@ export class Sprite extends UIRenderer { @editable @displayOrder(5) @tooltip('i18n:sprite.gray_scale') - get grayscale () { + get grayscale (): boolean { return this._useGrayscale; } set grayscale (value) { @@ -421,7 +421,7 @@ export class Sprite extends UIRenderer { @type(SizeMode) @displayOrder(5) @tooltip('i18n:sprite.size_mode') - get sizeMode () { + get sizeMode (): SizeMode { return this._sizeMode; } set sizeMode (value) { @@ -477,7 +477,7 @@ export class Sprite extends UIRenderer { @serializable protected _atlas: SpriteAtlas | null = null; - public __preload () { + public __preload (): void { this.changeMaterialForDefine(); super.__preload(); @@ -487,7 +487,7 @@ export class Sprite extends UIRenderer { } } - public onEnable () { + public onEnable (): void { super.onEnable(); // Force update uv, material define, active material, etc @@ -501,14 +501,14 @@ export class Sprite extends UIRenderer { } } - public onDisable () { + public onDisable (): void { super.onDisable(); if (this._spriteFrame && this._type === SpriteType.SLICED) { this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); } } - public onDestroy () { + public onDestroy (): void { if (EDITOR) { this.node.off(NodeEventType.SIZE_CHANGED, this._resized, this); } @@ -524,7 +524,7 @@ export class Sprite extends UIRenderer { * 选取使用精灵图集中的其他精灵。 * @param name @en Name of the spriteFrame to switch. @zh 要切换的 spriteFrame 名字。 */ - public changeSpriteFrameFromAtlas (name: string) { + public changeSpriteFrameFromAtlas (name: string): void { if (!this._atlas) { console.warn('SpriteAtlas is null.'); return; @@ -536,7 +536,7 @@ export class Sprite extends UIRenderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public changeMaterialForDefine () { + public changeMaterialForDefine (): void { let texture; const lastInstanceMaterialType = this._instanceMaterialType; if (this._spriteFrame) { @@ -562,7 +562,7 @@ export class Sprite extends UIRenderer { } } - protected _updateBuiltinMaterial () { + protected _updateBuiltinMaterial (): Material { let mat = super._updateBuiltinMaterial(); if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) { const defines = { SAMPLE_FROM_RT: true, ...mat.passes[0].defines }; @@ -576,11 +576,11 @@ export class Sprite extends UIRenderer { return mat; } - protected _render (render: IBatcher) { + protected _render (render: IBatcher): void { render.commitComp(this, this.renderData, this._spriteFrame, this._assembler, null); } - protected _canRender () { + protected _canRender (): boolean { if (!super._canRender()) { return false; } @@ -593,7 +593,7 @@ export class Sprite extends UIRenderer { return true; } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = Sprite.Assembler.getAssembler(this); if (this._assembler !== assembler) { @@ -623,7 +623,7 @@ export class Sprite extends UIRenderer { } } - private _applySpriteSize () { + private _applySpriteSize (): void { if (this._spriteFrame) { if (BUILD || !this._spriteFrame.isDefault) { if (SizeMode.RAW === this._sizeMode) { @@ -637,7 +637,7 @@ export class Sprite extends UIRenderer { } } - private _resized () { + private _resized (): void { if (!EDITOR) { return; } @@ -662,7 +662,7 @@ export class Sprite extends UIRenderer { } } - private _activateMaterial () { + private _activateMaterial (): void { const spriteFrame = this._spriteFrame; const material = this.getRenderMaterial(0); if (spriteFrame) { @@ -676,13 +676,13 @@ export class Sprite extends UIRenderer { } } - private _updateUVs () { + private _updateUVs (): void { if (this._assembler) { this._assembler.updateUVs(this); } } - private _applySpriteFrame (oldFrame: SpriteFrame | null) { + private _applySpriteFrame (oldFrame: SpriteFrame | null): void { const spriteFrame = this._spriteFrame; if (oldFrame && this._type === SpriteType.SLICED) { diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index 90a9fbaaded..a2ffa25cd24 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -66,7 +66,7 @@ export class UIMeshRenderer extends Component { * @en Get the model component on this node * @zh 获取同节点的 model 组件 */ - public get modelComponent () { + public get modelComponent (): ModelRenderer | null { return this._modelComponent; } @@ -78,21 +78,21 @@ export class UIMeshRenderer extends Component { public _dirtyVersion = -1; public _internalId = -1; - public __preload () { + public __preload (): void { this.node._uiProps.uiComp = this; } - onEnable () { + onEnable (): void { uiRendererManager.addRenderer(this); this.markForUpdateRenderData(); } - onDisable () { + onDisable (): void { uiRendererManager.removeRenderer(this); this.renderEntity.enabled = this._canRender(); } - public onLoad () { + public onLoad (): void { if (!this.node._uiProps.uiTransformComp) { this.node.addComponent('cc.UITransform'); } @@ -108,7 +108,7 @@ export class UIMeshRenderer extends Component { this.renderEntity.setNode(this.node); } - public onDestroy () { + public onDestroy (): void { this.renderEntity.setNode(null); if (this.node._uiProps.uiComp === this) { this.node._uiProps.uiComp = null; @@ -130,7 +130,7 @@ export class UIMeshRenderer extends Component { * 注意:不要手动调用该函数,除非你理解整个流程。 * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public _render (render: IBatcher) { + public _render (render: IBatcher): boolean { if (this._modelComponent) { const models = this._modelComponent._collectModels(); this._modelComponent._detachFromScene(); @@ -148,7 +148,7 @@ export class UIMeshRenderer extends Component { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public fillBuffers (render: IBatcher) { + public fillBuffers (render: IBatcher): void { if (this.enabled) { this._render(render); } @@ -158,7 +158,7 @@ export class UIMeshRenderer extends Component { * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ // Native updateAssembler - public updateRenderer () { + public updateRenderer (): void { if (JSB) { this.renderEntity.enabled = this._canRender(); if (this._modelComponent) { @@ -176,7 +176,7 @@ export class UIMeshRenderer extends Component { } } - private _uploadRenderData (index) { + private _uploadRenderData (index): void { if (JSB) { const renderData = MeshRenderData.add(); // TODO: here we weirdly use UIMeshRenderer as UIRenderer @@ -199,10 +199,10 @@ export class UIMeshRenderer extends Component { * 它可能会组装额外的渲染数据到顶点数据缓冲区,也可能只是重置一些渲染状态。 * 注意:不要手动调用该函数,除非你理解整个流程。 */ - public postUpdateAssembler (render: IBatcher) { + public postUpdateAssembler (render: IBatcher): void { } - public update () { + public update (): void { if (JSB) { if (this._modelComponent) { this.markForUpdateRenderData(); @@ -211,7 +211,7 @@ export class UIMeshRenderer extends Component { this._fitUIRenderQueue(); } - private _fitUIRenderQueue () { + private _fitUIRenderQueue (): void { if (!this._modelComponent) { return; } @@ -238,7 +238,7 @@ export class UIMeshRenderer extends Component { * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ // interface - public markForUpdateRenderData (enable = true) { + public markForUpdateRenderData (enable = true): void { uiRendererManager.markDirtyRenderer(this); } @@ -250,23 +250,23 @@ export class UIMeshRenderer extends Component { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setNodeDirty () { + public setNodeDirty (): void { } /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setTextureDirty () { + public setTextureDirty (): void { } - protected _canRender () { + protected _canRender (): boolean { return (this.enabled && this._modelComponent !== null); } /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - get renderEntity () { + get renderEntity (): RenderEntity { if (DEBUG) { assert(this._renderEntity, 'this._renderEntity should not be invalid'); } @@ -277,7 +277,7 @@ export class UIMeshRenderer extends Component { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - get renderData () { + get renderData (): RenderData | null { return this._renderData; } } diff --git a/cocos/2d/components/ui-opacity.ts b/cocos/2d/components/ui-opacity.ts index 96a36be5a83..625fd1a5584 100644 --- a/cocos/2d/components/ui-opacity.ts +++ b/cocos/2d/components/ui-opacity.ts @@ -54,7 +54,7 @@ export class UIOpacity extends Component { */ @editable @tooltip('i18n:UIOpacity.opacity') - get opacity () { + get opacity (): number { return this._opacity; } @@ -69,7 +69,7 @@ export class UIOpacity extends Component { this.setEntityLocalOpacityDirtyRecursively(true); } - private setEntityLocalOpacityDirtyRecursively (dirty: boolean) { + private setEntityLocalOpacityDirtyRecursively (dirty: boolean): void { if (JSB) { // const render = this.node._uiProps.uiComp as UIRenderer; // if (render) { @@ -82,7 +82,7 @@ export class UIOpacity extends Component { } // for UIOpacity - public static setEntityLocalOpacityDirtyRecursively (node: Node, dirty: boolean, interruptParentOpacity: number) { + public static setEntityLocalOpacityDirtyRecursively (node: Node, dirty: boolean, interruptParentOpacity: number): void { if (!node.isValid) { // Since children might be destroyed before the parent, // we should add protecting condition when executing recursion downwards. @@ -116,12 +116,12 @@ export class UIOpacity extends Component { @serializable protected _opacity = 255; - public onEnable () { + public onEnable (): void { this.node._uiProps.localOpacity = this._opacity / 255; this.setEntityLocalOpacityDirtyRecursively(true); } - public onDisable () { + public onDisable (): void { this.node._uiProps.localOpacity = 1; this.setEntityLocalOpacityDirtyRecursively(true); } diff --git a/cocos/2d/components/ui-static-batch.ts b/cocos/2d/components/ui-static-batch.ts index 987a3c363dc..191776eaa39 100644 --- a/cocos/2d/components/ui-static-batch.ts +++ b/cocos/2d/components/ui-static-batch.ts @@ -29,6 +29,7 @@ import { DrawBatch2D } from '../renderer/draw-batch'; import { Color, warnID } from '../../core'; import { StaticVBAccessor } from '../renderer/static-vb-accessor'; import { director } from '../../game'; +import type { Batcher2D } from '../renderer/batcher-2d'; /** * @en @@ -68,7 +69,7 @@ export class UIStaticBatch extends UIRenderer { this._color.set(value); } - get drawBatchList () { + get drawBatchList (): DrawBatch2D[] { return this._uiDrawBatchList; } @@ -77,7 +78,7 @@ export class UIStaticBatch extends UIRenderer { protected _dirty = true; private _uiDrawBatchList: DrawBatch2D[] = []; - public postUpdateAssembler (render: IBatcher) { + public postUpdateAssembler (render: IBatcher): void { // if (this._dirty) { // this._dirty = false; // this._init = true; @@ -98,7 +99,7 @@ export class UIStaticBatch extends UIRenderer { * 重新采集数据标记,会在当前帧的渲染阶段重新采集渲染数据,下一帧开始将会使用固定数据进行渲染。 * 注意:尽量不要频繁调用此接口,因为会清空原先存储的 ia 数据重新采集,会有一定内存损耗。 */ - public markAsDirty () { + public markAsDirty (): void { // this.node._static = false; // this._dirty = true; @@ -109,14 +110,14 @@ export class UIStaticBatch extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _requireDrawBatch () { + public _requireDrawBatch (): DrawBatch2D { const batch = new DrawBatch2D(); batch.isStatic = true; this._uiDrawBatchList.push(batch); return batch; } - protected _clearData () { + protected _clearData (): void { if (this._bufferAccessor) { this._bufferAccessor.reset(); @@ -131,7 +132,7 @@ export class UIStaticBatch extends UIRenderer { this._init = false; } - protected _getBatcher () { + protected _getBatcher (): Batcher2D | null { if (director.root && director.root.batcher2D) { return director.root.batcher2D; } diff --git a/cocos/2d/event/pointer-event-dispatcher.ts b/cocos/2d/event/pointer-event-dispatcher.ts index 83e35b33d05..516d5cb58ab 100644 --- a/cocos/2d/event/pointer-event-dispatcher.ts +++ b/cocos/2d/event/pointer-event-dispatcher.ts @@ -70,7 +70,7 @@ class PointerEventDispatcher implements IEventDispatcher { return true; } - public addPointerEventProcessor (pointerEventProcessor: NodeEventProcessor) { + public addPointerEventProcessor (pointerEventProcessor: NodeEventProcessor): void { if (this._inDispatchCount === 0) { if (!this._pointerEventProcessorList.includes(pointerEventProcessor)) { this._pointerEventProcessorList.push(pointerEventProcessor); @@ -82,7 +82,7 @@ class PointerEventDispatcher implements IEventDispatcher { js.array.remove(this._processorListToRemove, pointerEventProcessor); } - public removePointerEventProcessor (pointerEventProcessor: NodeEventProcessor) { + public removePointerEventProcessor (pointerEventProcessor: NodeEventProcessor): void { if (this._inDispatchCount === 0) { js.array.remove(this._pointerEventProcessorList, pointerEventProcessor); this._isListDirty = true; @@ -92,7 +92,7 @@ class PointerEventDispatcher implements IEventDispatcher { js.array.remove(this._processorListToAdd, pointerEventProcessor); } - public dispatchEventMouse (eventMouse: EventMouse) { + public dispatchEventMouse (eventMouse: EventMouse): boolean { this._inDispatchCount++; this._sortPointerEventProcessorList(); const pointerEventProcessorList = this._pointerEventProcessorList; @@ -116,7 +116,7 @@ class PointerEventDispatcher implements IEventDispatcher { return dispatchToNextEventDispatcher; } - public dispatchEventTouch (eventTouch: EventTouch) { + public dispatchEventTouch (eventTouch: EventTouch): boolean { this._inDispatchCount++; this._sortPointerEventProcessorList(); const pointerEventProcessorList = this._pointerEventProcessorList; @@ -159,7 +159,7 @@ class PointerEventDispatcher implements IEventDispatcher { return dispatchToNextEventDispatcher; } - private _updatePointerEventProcessorList () { + private _updatePointerEventProcessorList (): void { const listToAdd = this._processorListToAdd; const addLength = listToAdd.length; for (let i = 0; i < addLength; ++i) { @@ -175,7 +175,7 @@ class PointerEventDispatcher implements IEventDispatcher { listToRemove.length = 0; } - private _sortPointerEventProcessorList () { + private _sortPointerEventProcessorList (): void { if (!this._isListDirty) { return; } @@ -193,7 +193,7 @@ class PointerEventDispatcher implements IEventDispatcher { this._isListDirty = false; } - private _sortByPriority (p1: NodeEventProcessor, p2: NodeEventProcessor) { + private _sortByPriority (p1: NodeEventProcessor, p2: NodeEventProcessor): number { const node1: Node = p1.node; const node2: Node = p2.node; if (!p2 || !node2 || !node2.activeInHierarchy || !node2._uiProps.uiTransformComp) { @@ -226,7 +226,7 @@ class PointerEventDispatcher implements IEventDispatcher { return ex ? priority1 - priority2 : priority2 - priority1; } - private _markListDirty () { + private _markListDirty (): void { this._isListDirty = true; } } diff --git a/cocos/2d/framework/canvas.ts b/cocos/2d/framework/canvas.ts index c37be72094d..a4aef03ff73 100644 --- a/cocos/2d/framework/canvas.ts +++ b/cocos/2d/framework/canvas.ts @@ -73,7 +73,7 @@ export class Canvas extends RenderRoot2D { * * @deprecated since v3.0, please use [[Camera.priority]] to control overlapping between cameras. */ - get renderMode () { + get renderMode (): number { return this._renderMode; } set renderMode (val) { @@ -90,7 +90,7 @@ export class Canvas extends RenderRoot2D { */ @type(Camera) @tooltip('i18n:canvas.camera') - get cameraComponent () { + get cameraComponent (): Camera | null { return this._cameraComponent; } @@ -107,7 +107,7 @@ export class Canvas extends RenderRoot2D { * @zh 是否使用屏幕对齐画布 */ @tooltip('i18n:canvas.align') - get alignCanvasWithScreen () { + get alignCanvasWithScreen (): boolean { return this._alignCanvasWithScreen; } @@ -134,7 +134,7 @@ export class Canvas extends RenderRoot2D { this._thisOnCameraResized = this._onResizeCamera.bind(this); if (EDITOR) { - this._fitDesignResolution = () => { + this._fitDesignResolution = (): void => { // TODO: support paddings of locked widget this.node.getPosition(this._pos); const nodeSize = view.getDesignResolutionSize(); @@ -154,7 +154,7 @@ export class Canvas extends RenderRoot2D { } } - public __preload () { + public __preload (): void { // Stretch to matched size during the scene initialization const widget = this.getComponent('cc.Widget') as unknown as Widget; if (widget) { @@ -186,21 +186,21 @@ export class Canvas extends RenderRoot2D { } } - public onEnable () { + public onEnable (): void { super.onEnable(); if (!EDITOR && this._cameraComponent) { this._cameraComponent.node.on(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); } } - public onDisable () { + public onDisable (): void { super.onDisable(); if (this._cameraComponent) { this._cameraComponent.node.off(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); } } - public onDestroy () { + public onDestroy (): void { super.onDestroy(); if (EDITOR) { @@ -210,7 +210,7 @@ export class Canvas extends RenderRoot2D { } } - protected _onResizeCamera () { + protected _onResizeCamera (): void { if (this._cameraComponent && this._alignCanvasWithScreen) { if (this._cameraComponent.targetTexture) { this._cameraComponent.orthoHeight = visibleRect.height / 2; @@ -224,7 +224,7 @@ export class Canvas extends RenderRoot2D { } } - private _getViewPriority () { + private _getViewPriority (): number { if (this._cameraComponent) { let priority = this.cameraComponent?.priority as number; priority = this._renderMode === RenderMode.OVERLAY ? priority | 1 << 30 : priority & ~(1 << 30); diff --git a/cocos/2d/framework/deprecated.ts b/cocos/2d/framework/deprecated.ts index db1d3608143..cc39a163fbd 100644 --- a/cocos/2d/framework/deprecated.ts +++ b/cocos/2d/framework/deprecated.ts @@ -30,6 +30,7 @@ import { UIRenderer } from './ui-renderer'; import { Canvas } from './canvas'; import type { RenderTexture } from '../../asset/assets/render-texture'; import type { ClearFlagBit } from '../../gfx/base/define'; +import type { Camera } from '../../render-scene/scene'; removeProperty(UIComponent.prototype, 'UIComponent', [ { @@ -44,54 +45,54 @@ replaceProperty(Canvas.prototype, 'Canvas.prototype', [ { name: 'camera', newName: 'cameraComponent.camera', - customGetter (this: Canvas) { + customGetter (this: Canvas): Camera | undefined { return this._cameraComponent?.camera; }, }, { name: 'clearFlag', newName: 'cameraComponent.clearFlags', - customGetter (this: Canvas) { + customGetter (this: Canvas): ClearFlagBit | 0 { return this._cameraComponent ? this._cameraComponent.clearFlags : 0; }, - customSetter (this: Canvas, val: ClearFlagBit) { + customSetter (this: Canvas, val: ClearFlagBit): void { if (this._cameraComponent) this._cameraComponent.clearFlags = val; }, }, { name: 'color', newName: 'cameraComponent.clearColor', - customGetter (this: Canvas) { + customGetter (this: Canvas): Readonly { return this._cameraComponent ? this._cameraComponent.clearColor : Color.BLACK; }, - customSetter (this: Canvas, val: Readonly) { + customSetter (this: Canvas, val: Readonly): void { if (this._cameraComponent) this._cameraComponent.clearColor = val; }, }, { name: 'priority', newName: 'cameraComponent.priority', - customGetter (this: Canvas) { + customGetter (this: Canvas): number { return this._cameraComponent ? this._cameraComponent.priority : 0; }, - customSetter (this: Canvas, val: number) { + customSetter (this: Canvas, val: number): void { if (this._cameraComponent) this._cameraComponent.priority = val; }, }, { name: 'targetTexture', newName: 'cameraComponent.targetTexture', - customGetter (this: Canvas) { + customGetter (this: Canvas): RenderTexture | null { return this._cameraComponent ? this._cameraComponent.targetTexture : null; }, - customSetter (this: Canvas, value: RenderTexture) { + customSetter (this: Canvas, value: RenderTexture): void { if (this._cameraComponent) this._cameraComponent.targetTexture = value; }, }, { name: 'visibility', newName: 'cameraComponent.visibility', - customGetter (this: Canvas) { + customGetter (this: Canvas): number { return this._cameraComponent ? this._cameraComponent.visibility : 0; }, }, diff --git a/cocos/2d/framework/render-root-2d.ts b/cocos/2d/framework/render-root-2d.ts index faacc9441c4..ba672f2ad71 100644 --- a/cocos/2d/framework/render-root-2d.ts +++ b/cocos/2d/framework/render-root-2d.ts @@ -39,15 +39,15 @@ import { UITransform } from './ui-transform'; @disallowMultiple @executeInEditMode export class RenderRoot2D extends Component { - public onEnable () { + public onEnable (): void { cclegacy.director.root!.batcher2D.addScreen(this); } - public onDisable () { + public onDisable (): void { cclegacy.director.root!.batcher2D.removeScreen(this); } - public onDestroy () { + public onDestroy (): void { cclegacy.director.root!.batcher2D.removeScreen(this); } } diff --git a/cocos/2d/framework/sprite-renderer.ts b/cocos/2d/framework/sprite-renderer.ts index fadc96c5fe2..9e7b7b4125c 100644 --- a/cocos/2d/framework/sprite-renderer.ts +++ b/cocos/2d/framework/sprite-renderer.ts @@ -54,7 +54,7 @@ export class SpriteRenderer extends ModelRenderer { * @zh 该组件应渲染的 spriteFrame。 */ @type(SpriteFrame) - get spriteFrame () { + get spriteFrame (): SpriteFrame | null { return this._spriteFrame; } @@ -81,7 +81,7 @@ export class SpriteRenderer extends ModelRenderer { * @en Rendering model of the component. * @zh 该组件的渲染模型。 */ - get model () { + get model (): Model | null { return this._model; } @@ -101,7 +101,7 @@ export class SpriteRenderer extends ModelRenderer { private _model: Model | null = null; - public onLoad () { + public onLoad (): void { if (this._spriteFrame) { if (!this._spriteFrame.mesh) { this._spriteFrame.ensureMeshData(); @@ -111,14 +111,14 @@ export class SpriteRenderer extends ModelRenderer { this._updateModels(); } - public onRestore () { + public onRestore (): void { this._updateModels(); if (this.enabledInHierarchy) { this._attachToScene(); } } - public onEnable () { + public onEnable (): void { super.onEnable(); if (!this._model) { this._updateModels(); @@ -126,13 +126,13 @@ export class SpriteRenderer extends ModelRenderer { this._attachToScene(); } - public onDisable () { + public onDisable (): void { if (this._model) { this._detachFromScene(); } } - public onDestroy () { + public onDestroy (): void { if (this._model) { cclegacy.director.root.destroyModel(this._model); this._model = null; @@ -140,7 +140,7 @@ export class SpriteRenderer extends ModelRenderer { } } - protected _updateModels () { + protected _updateModels (): void { if (!this._spriteFrame) { return; } @@ -162,7 +162,7 @@ export class SpriteRenderer extends ModelRenderer { } } - protected _createModel () { + protected _createModel (): void { const model = this._model = (cclegacy.director.root as Root).createModel(Model); model.visFlags = this.visibility; model.node = model.transform = this.node; @@ -170,7 +170,7 @@ export class SpriteRenderer extends ModelRenderer { this._models.push(this._model); } - protected _updateModelParams () { + protected _updateModelParams (): void { if (!this._spriteFrame || !this._model) { return; } this._spriteFrame.ensureMeshData(); const mesh = this._spriteFrame.mesh!; @@ -193,12 +193,12 @@ export class SpriteRenderer extends ModelRenderer { this._model.enabled = true; } - protected _getBuiltinMaterial () { + protected _getBuiltinMaterial (): Material { // classic ugly pink indicating missing material return builtinResMgr.get('missing-material'); } - protected _onMaterialModified (idx: number, material: Material | null) { + protected _onMaterialModified (idx: number, material: Material | null): void { super._onMaterialModified(idx, material); if (!this._spriteFrame || !this._model || !this._model.inited) { return; @@ -209,13 +209,13 @@ export class SpriteRenderer extends ModelRenderer { /** * @engineInternal */ - public _onRebuildPSO (idx: number, material: Material) { + public _onRebuildPSO (idx: number, material: Material): void { if (!this._model || !this._model.inited) { return; } this._model.setSubModelMaterial(idx, material); this._onUpdateLocalDescriptorSet(); } - protected _onUpdateLocalDescriptorSet () { + protected _onUpdateLocalDescriptorSet (): void { if (!this._spriteFrame || !this._model || !this._model.inited) { return; } @@ -233,7 +233,7 @@ export class SpriteRenderer extends ModelRenderer { } } - protected _attachToScene () { + protected _attachToScene (): void { if (!this.node.scene || !this._model) { return; } @@ -247,7 +247,7 @@ export class SpriteRenderer extends ModelRenderer { /** * @engineInternal */ - public _detachFromScene () { + public _detachFromScene (): void { if (this._model && this._model.scene) { this._model.scene.removeModel(this._model); } diff --git a/cocos/2d/framework/ui-component.ts b/cocos/2d/framework/ui-component.ts index 758695ea885..bfc2d30d271 100644 --- a/cocos/2d/framework/ui-component.ts +++ b/cocos/2d/framework/ui-component.ts @@ -44,21 +44,21 @@ import { Stage } from '../renderer/stencil-manager'; export class UIComponent extends Component { protected _lastParent: Node | null = null; - public __preload () { + public __preload (): void { // TODO: UIComponent should not be assigned to UIMeshRenderer | UIRenderer @holycanvas // workaround: mark this as any // issue: https://github.com/cocos/cocos-engine/issues/14637 (this as any).node._uiProps.uiComp = this; } - public onEnable () { + public onEnable (): void { } - public onDisable () { + public onDisable (): void { } - public onDestroy () { + public onDestroy (): void { // TODO: UIComponent should not be assigned to UIMeshRenderer | UIRenderer @holycanvas // workaround: mark this as any // issue: https://github.com/cocos/cocos-engine/issues/14637 @@ -76,13 +76,13 @@ export class UIComponent extends Component { * 注意:不要手动调用该函数,除非你理解整个流程。 * @deprecated since v3.4.1, please use [[UIRenderer]] instead. */ - public postUpdateAssembler (render: IBatcher) { + public postUpdateAssembler (render: IBatcher): void { } /** * @deprecated since v3.4.1, please use [[UIRenderer]] instead. */ - public markForUpdateRenderData (enable = true) { + public markForUpdateRenderData (enable = true): void { } /** @@ -93,12 +93,12 @@ export class UIComponent extends Component { /** * @deprecated since v3.4.1, please use [[UIRenderer]] instead. */ - public setNodeDirty () { + public setNodeDirty (): void { } /** * @deprecated since v3.4.1, please use [[UIRenderer]] instead. */ - public setTextureDirty () { + public setTextureDirty (): void { } } diff --git a/cocos/2d/framework/ui-renderer-manager.ts b/cocos/2d/framework/ui-renderer-manager.ts index 3971749e97a..c9627ca129f 100644 --- a/cocos/2d/framework/ui-renderer-manager.ts +++ b/cocos/2d/framework/ui-renderer-manager.ts @@ -31,14 +31,14 @@ export class UIRendererManager { private _allRenderers: (UIRenderer | UIMeshRenderer)[] = []; private _dirtyRenderers: (UIRenderer | UIMeshRenderer)[] = []; private _dirtyVersion = 0; - public addRenderer (uiRenderer: UIRenderer | UIMeshRenderer) { + public addRenderer (uiRenderer: UIRenderer | UIMeshRenderer): void { if (uiRenderer._internalId === -1) { uiRenderer._internalId = this._allRenderers.length; this._allRenderers.push(uiRenderer); } } - public removeRenderer (uiRenderer: UIRenderer | UIMeshRenderer) { + public removeRenderer (uiRenderer: UIRenderer | UIMeshRenderer): void { if (uiRenderer._internalId !== -1) { if (DEBUG) { assert(this._allRenderers[uiRenderer._internalId] === uiRenderer); @@ -54,14 +54,14 @@ export class UIRendererManager { } } - public markDirtyRenderer (uiRenderer: UIRenderer | UIMeshRenderer) { + public markDirtyRenderer (uiRenderer: UIRenderer | UIMeshRenderer): void { if (uiRenderer._dirtyVersion !== this._dirtyVersion && uiRenderer._internalId !== -1) { this._dirtyRenderers.push(uiRenderer); uiRenderer._dirtyVersion = this._dirtyVersion; } } - public updateAllDirtyRenderers () { + public updateAllDirtyRenderers (): void { const length = this._dirtyRenderers.length; const dirtyRenderers = this._dirtyRenderers; for (let i = 0; i < length; i++) { diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index f19e13caad4..32a7b11ac33 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -44,6 +44,7 @@ import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; import { uiRendererManager } from './ui-renderer-manager'; import { RenderDrawInfoType } from '../renderer/render-draw-info'; import { director } from '../../game'; +import type { Batcher2D } from '../renderer/batcher-2d'; // hack ccenum(BlendFactor); @@ -142,7 +143,7 @@ export class UIRenderer extends Renderer { @override @visible(false) - get sharedMaterials () { + get sharedMaterials (): (Material | null)[] { // if we don't create an array copy, the editor will modify the original array directly. return EDITOR && this._materials.slice() || this._materials; } @@ -170,7 +171,7 @@ export class UIRenderer extends Renderer { @tooltip('i18n:UIRenderer.customMaterial') @displayName('CustomMaterial') @disallowAnimation - get customMaterial () { + get customMaterial (): Material | null { return this._customMaterial; } @@ -204,21 +205,21 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - get renderData () { + get renderData (): RenderData | null { return this._renderData; } /** * As can not set setter internal individually, so add setRenderData(); * @engineInternal */ - setRenderData (renderData: RenderData | null) { + setRenderData (renderData: RenderData | null): void { this._renderData = renderData; } /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - get useVertexOpacity () { + get useVertexOpacity (): boolean { return this._useVertexOpacity; } @@ -281,14 +282,14 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - get batcher () { + get batcher (): Batcher2D { return director.root!.batcher2D; } /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - get renderEntity () { + get renderEntity (): RenderEntity { if (DEBUG) { assert(this._renderEntity, 'this._renderEntity should not be invalid'); } @@ -303,18 +304,18 @@ export class UIRenderer extends Renderer { protected _lastParent: Node | null = null; - public onLoad () { + public onLoad (): void { this._renderEntity.setNode(this.node); } - public __preload () { + public __preload (): void { this.node._uiProps.uiComp = this; if (this._flushAssembler) { this._flushAssembler(); } } - public onEnable () { + public onEnable (): void { this.node.on(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this); this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); this.node.on(NodeEventType.PARENT_CHANGED, this._colorDirty, this); @@ -325,13 +326,13 @@ export class UIRenderer extends Renderer { } // For Redo, Undo - public onRestore () { + public onRestore (): void { this.updateMaterial(); // restore render data this.markForUpdateRenderData(); } - public onDisable () { + public onDisable (): void { this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this); this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this); @@ -340,7 +341,7 @@ export class UIRenderer extends Renderer { this._renderEntity.enabled = false; } - public onDestroy () { + public onDestroy (): void { this._renderEntity.setNode(null); if (this.node._uiProps.uiComp === this) { this.node._uiProps.uiComp = null; @@ -359,7 +360,7 @@ export class UIRenderer extends Renderer { * @zh 标记当前组件的渲染数据为已修改状态,这样渲染数据才会重新计算。 * @param enable Marked necessary to update or not */ - public markForUpdateRenderData (enable = true) { + public markForUpdateRenderData (enable = true): void { if (enable) { const renderData = this._renderData; if (renderData) { @@ -374,7 +375,7 @@ export class UIRenderer extends Renderer { * @zh 请求新的渲染数据对象。 * @return @en The new render data. @zh 新的渲染数据。 */ - public requestRenderData (drawInfoType = RenderDrawInfoType.COMP) { + public requestRenderData (drawInfoType = RenderDrawInfoType.COMP): RenderData { const data = RenderData.add(); data.initRenderDrawInfo(this, drawInfoType); this._renderData = data; @@ -385,7 +386,7 @@ export class UIRenderer extends Renderer { * @en Destroy current render data. * @zh 销毁当前渲染数据。 */ - public destroyRenderData () { + public destroyRenderData (): void { if (!this._renderData) { return; } @@ -397,7 +398,7 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public updateRenderer () { + public updateRenderer (): void { if (this._assembler) { this._assembler.updateRenderData(this); } @@ -408,7 +409,7 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public fillBuffers (render: IBatcher) { + public fillBuffers (render: IBatcher): void { if (this._renderFlag) { this._render(render); } @@ -422,17 +423,17 @@ export class UIRenderer extends Renderer { * 它可能会组装额外的渲染数据到顶点数据缓冲区,也可能只是重置一些渲染状态。 * 注意:不要手动调用该函数,除非你理解整个流程。 */ - public postUpdateAssembler (render: IBatcher) { + public postUpdateAssembler (render: IBatcher): void { if (this._postAssembler && this._renderFlag) { this._postRender(render); } } - protected _render (render: IBatcher) { } + protected _render (render: IBatcher): void { } - protected _postRender (render: IBatcher) { } + protected _postRender (render: IBatcher): void { } - protected _canRender () { + protected _canRender (): boolean { if (DEBUG) { assert(this.isValid, 'this component should not be invalid!'); } @@ -441,12 +442,12 @@ export class UIRenderer extends Renderer { && this._color.a > 0; } - protected _postCanRender () { } + protected _postCanRender (): void { } /** * @engineInternal */ - public updateMaterial () { + public updateMaterial (): void { if (this._customMaterial) { if (this.getSharedMaterial(0) !== this._customMaterial) { this.setMaterial(this._customMaterial, 0); @@ -461,7 +462,7 @@ export class UIRenderer extends Renderer { this._updateBlendFunc(); } - protected _updateColor () { + protected _updateColor (): void { this.node._uiProps.colorDirty = true; this.setEntityColorDirty(true); this.setEntityColor(this._color); @@ -486,7 +487,7 @@ export class UIRenderer extends Renderer { * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ // for common - public static setEntityColorDirtyRecursively (node: Node, dirty: boolean) { + public static setEntityColorDirtyRecursively (node: Node, dirty: boolean): void { const render = node._uiProps.uiComp as UIRenderer; if (render && render.color) { // exclude UIMeshRenderer which has not color render._renderEntity.colorDirty = dirty; @@ -496,7 +497,7 @@ export class UIRenderer extends Renderer { } } - private setEntityColorDirty (dirty: boolean) { + private setEntityColorDirty (dirty: boolean): void { if (JSB) { UIRenderer.setEntityColorDirtyRecursively(this.node, dirty); } @@ -505,7 +506,7 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setEntityColor (color: Color) { + public setEntityColor (color: Color): void { if (JSB) { this._renderEntity.color = color; } @@ -514,7 +515,7 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setEntityOpacity (opacity: number) { + public setEntityOpacity (opacity: number): void { if (JSB) { this._renderEntity.localOpacity = opacity; } @@ -523,7 +524,7 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setEntityEnabled (enabled: boolean) { + public setEntityEnabled (enabled: boolean): void { if (JSB) { this._renderEntity.enabled = enabled; } @@ -532,7 +533,7 @@ export class UIRenderer extends Renderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateBlendFunc () { + public _updateBlendFunc (): void { // todo: Not only Pass[0].target[0] let target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0]; this._dstBlendFactorCache = target.blendDst; @@ -552,7 +553,7 @@ export class UIRenderer extends Renderer { } // pos, rot, scale changed - protected _nodeStateChange (transformType: TransformBit) { + protected _nodeStateChange (transformType: TransformBit): void { if (this._renderData) { this.markForUpdateRenderData(); } @@ -566,12 +567,12 @@ export class UIRenderer extends Renderer { } } - protected _colorDirty () { + protected _colorDirty (): void { this.node._uiProps.colorDirty = true; this.setEntityColorDirty(true); } - protected _onMaterialModified (idx: number, material: Material | null) { + protected _onMaterialModified (idx: number, material: Material | null): void { if (this._renderData) { this.markForUpdateRenderData(); this._renderData.passDirty = true; @@ -606,7 +607,7 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setNodeDirty () { + public setNodeDirty (): void { if (this._renderData) { this._renderData.nodeDirty = true; } @@ -615,7 +616,7 @@ export class UIRenderer extends Renderer { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setTextureDirty () { + public setTextureDirty (): void { if (this._renderData) { this._renderData.textureDirty = true; } @@ -623,7 +624,7 @@ export class UIRenderer extends Renderer { // RenderEntity // it should be overwritten by inherited classes - protected createRenderEntity () { + protected createRenderEntity (): RenderEntity { return new RenderEntity(RenderEntityType.STATIC); } } diff --git a/cocos/2d/framework/ui-transform.ts b/cocos/2d/framework/ui-transform.ts index e40a121a06f..797270dece6 100644 --- a/cocos/2d/framework/ui-transform.ts +++ b/cocos/2d/framework/ui-transform.ts @@ -88,7 +88,7 @@ export class UITransform extends Component { * @zh * 组件宽度。 */ - get width () { + get width (): number { return this._contentSize.width; } @@ -114,7 +114,7 @@ export class UITransform extends Component { * @zh * 组件高度。 */ - get height () { + get height (): number { return this._contentSize.height; } @@ -165,7 +165,7 @@ export class UITransform extends Component { * @zh * 锚点位置的 X 坐标。 */ - get anchorX () { + get anchorX (): number { return this._anchorPoint.x; } @@ -186,7 +186,7 @@ export class UITransform extends Component { * @zh * 锚点位置的 Y 坐标。 */ - get anchorY () { + get anchorY (): number { return this._anchorPoint.y; } @@ -209,7 +209,7 @@ export class UITransform extends Component { * 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。 * @deprecated Since v3.1 */ - get priority () { + get priority (): number { return this._priority; } @@ -236,7 +236,7 @@ export class UITransform extends Component { * @zh 查找被渲染相机的可见性掩码。 * @deprecated since v3.0 */ - get visibility () { + get visibility (): number { const camera = director.root!.batcher2D.getFirstRenderCamera(this.node); return camera ? camera.visibility : 0; } @@ -245,7 +245,7 @@ export class UITransform extends Component { * @en Get the priority of the rendering camera * @zh 查找被渲染相机的渲染优先级。 */ - get cameraPriority () { + get cameraPriority (): number { const camera = director.root!.batcher2D.getFirstRenderCamera(this.node); return camera ? camera.priority : 0; } @@ -257,26 +257,26 @@ export class UITransform extends Component { @serializable protected _anchorPoint = new Vec2(0.5, 0.5); - public __preload () { + public __preload (): void { this.node._uiProps.uiTransformComp = this; } - public onLoad () { + public onLoad (): void { if (this.node.parent) { UITransform.insertChangeMap(this.node.parent); } } - public onEnable () { + public onEnable (): void { this.node.on(NodeEventType.PARENT_CHANGED, this._parentChanged, this); this._markRenderDataDirty(); } - public onDisable () { + public onDisable (): void { this.node.off(NodeEventType.PARENT_CHANGED, this._parentChanged, this); } - public onDestroy () { + public onDestroy (): void { this.node._uiProps.uiTransformComp = null; } @@ -313,7 +313,7 @@ export class UITransform extends Component { */ public setContentSize(width: number, height: number): void; - public setContentSize (size: Size | number, height?: number) { + public setContentSize (size: Size | number, height?: number): void { const locContentSize = this._contentSize; let locWidth: number; let locHeight: number; @@ -375,7 +375,7 @@ export class UITransform extends Component { * node.setAnchorPoint(1, 1); * ``` */ - public setAnchorPoint (point: Vec2 | Readonly | number, y?: number) { + public setAnchorPoint (point: Vec2 | Readonly | number, y?: number): void { const locAnchorPoint = this._anchorPoint; if (y === undefined) { point = point as Vec2; @@ -406,7 +406,7 @@ export class UITransform extends Component { * @param uiPoint point in UI Space. * @deprecated since v3.5.0, please use `uiTransform.hitTest(screenPoint: Vec2)` instead. */ - public isHit (uiPoint: Vec2) { + public isHit (uiPoint: Vec2): boolean { const w = this._contentSize.width; const h = this._contentSize.height; const v2WorldPt = _vec2a; @@ -453,7 +453,7 @@ export class UITransform extends Component { * * @param screenPoint @en point in Screen Space. @zh 屏幕坐标中的点。 */ - public hitTest (screenPoint: Vec2, windowId = 0) { + public hitTest (screenPoint: Vec2, windowId = 0): boolean { const w = this._contentSize.width; const h = this._contentSize.height; const v3WorldPt = _vec3a; @@ -493,7 +493,7 @@ export class UITransform extends Component { return false; } - private _maskTest (pointInWorldSpace: Vec2) { + private _maskTest (pointInWorldSpace: Vec2): boolean { const maskList = this.node?.eventProcessor?.maskList as IMask[] | undefined; if (maskList) { let parent: Node | null = this.node; @@ -543,7 +543,7 @@ export class UITransform extends Component { * const newVec3 = uiTransform.convertToNodeSpaceAR(cc.v3(100, 100, 0)); * ``` */ - public convertToNodeSpaceAR (worldPoint: Vec3, out?: Vec3) { + public convertToNodeSpaceAR (worldPoint: Vec3, out?: Vec3): Vec3 { this.node.getWorldMatrix(_worldMatrix); Mat4.invert(_mat4_temp, _worldMatrix); if (!out) { @@ -571,7 +571,7 @@ export class UITransform extends Component { * const newVec3 = uiTransform.convertToWorldSpaceAR(3(100, 100, 0)); * ``` */ - public convertToWorldSpaceAR (nodePoint: Vec3, out?: Vec3) { + public convertToWorldSpaceAR (nodePoint: Vec3, out?: Vec3): Vec3 { this.node.getWorldMatrix(_worldMatrix); if (!out) { out = new Vec3(); @@ -597,7 +597,7 @@ export class UITransform extends Component { * const boundingBox = uiTransform.getBoundingBox(); * ``` */ - public getBoundingBox () { + public getBoundingBox (): Rect { const rect = new Rect(); this._selfBoundingBox(rect); Mat4.fromSRT(_matrix, this.node.rotation, this.node.position, this.node.scale); @@ -618,7 +618,7 @@ export class UITransform extends Component { * const newRect = uiTransform.getBoundingBoxToWorld(); * ``` */ - public getBoundingBoxToWorld () { + public getBoundingBoxToWorld (): Rect { const rect = new Rect(); const locChildren = this.node.children; for (let i = 0; i < locChildren.length; ++i) { @@ -665,7 +665,7 @@ export class UITransform extends Component { * @returns @en The minimum bounding box containing the current bounding box and its child nodes. * @zh 包含当前节点包围盒及其子节点包围盒的最小包围盒。 */ - public getBoundingBoxTo (targetMat: Mat4) { + public getBoundingBoxTo (targetMat: Mat4): Rect { const rect = new Rect(); const locChildren = this.node.children; Mat4.invert(_mat4_temp, targetMat); @@ -711,7 +711,7 @@ export class UITransform extends Component { * @param out @en The out object of aabb bounding box of the node in world space. @zh 输出节点在世界空间下的 aabb 包围盒。 * @returns @en The aabb bounding box of the node in world space. @zh 节点在世界空间下的 aabb 包围盒。 */ - public getComputeAABB (out?: geometry.AABB) { + public getComputeAABB (out?: geometry.AABB): geometry.AABB { const width = this._contentSize.width; const height = this._contentSize.height; _rect.set( @@ -735,7 +735,7 @@ export class UITransform extends Component { } } - protected _selfBoundingBox (out: Rect) { + protected _selfBoundingBox (out: Rect): Rect { const width = this._contentSize.width; const height = this._contentSize.height; out.set( @@ -747,7 +747,7 @@ export class UITransform extends Component { return out; } - protected _parentChanged (node: Node) { + protected _parentChanged (node: Node): void { if (this.node.getComponent('cc.RenderRoot2D')) { return; } @@ -757,7 +757,7 @@ export class UITransform extends Component { } } - private _markRenderDataDirty () { + private _markRenderDataDirty (): void { const uiComp = this.node._uiProps.uiComp; if (uiComp) { uiComp.markForUpdateRenderData(); @@ -766,17 +766,17 @@ export class UITransform extends Component { private static priorityChangeNodeMap = new Map(); - private static insertChangeMap (node: Node) { + private static insertChangeMap (node: Node): void { const key = node.uuid; if (!UITransform.priorityChangeNodeMap.has(key)) { UITransform.priorityChangeNodeMap.set(key, node); } } - private static _sortChildrenSibling (node) { + private static _sortChildrenSibling (node): void { const siblings = node.children; if (siblings) { - siblings.sort((a: Node, b: Node) => { + siblings.sort((a: Node, b: Node): number => { const aComp = a._uiProps.uiTransformComp; const bComp = b._uiProps.uiTransformComp; const ca = aComp ? aComp._priority : 0; @@ -792,8 +792,8 @@ export class UITransform extends Component { * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. * @engineInternal */ - public static _sortSiblings () { - UITransform.priorityChangeNodeMap.forEach((node, ID) => { + public static _sortSiblings (): void { + UITransform.priorityChangeNodeMap.forEach((node, ID): void => { UITransform._sortChildrenSibling(node); node._updateSiblingIndex(); node.emit('childrenSiblingOrderChanged'); @@ -805,7 +805,7 @@ export class UITransform extends Component { * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. * @engineInternal */ - public static _cleanChangeMap () { + public static _cleanChangeMap (): void { UITransform.priorityChangeNodeMap.clear(); } } diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index 97f3d84a599..13e7126ec76 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -62,14 +62,14 @@ export class Batcher2D implements IBatcher { return this._nativeObj; } - get currBufferAccessor () { + get currBufferAccessor (): StaticVBAccessor { if (this._staticVBBuffer) return this._staticVBBuffer; // create if not set this._staticVBBuffer = this.switchBufferAccessor(); return this._staticVBBuffer; } - get batches () { + get batches (): CachedArray { return this._batches; } @@ -132,11 +132,11 @@ export class Batcher2D implements IBatcher { this._drawBatchPool = new Pool(() => new DrawBatch2D(), 128, (obj) => obj.destroy(this)); } - public initialize () { + public initialize (): boolean { return true; } - public destroy () { + public destroy (): void { for (let i = 0; i < this._batches.length; i++) { if (this._batches.array[i]) { this._batches.array[i].destroy(this); @@ -166,7 +166,7 @@ export class Batcher2D implements IBatcher { } } - private syncRootNodesToNative () { + private syncRootNodesToNative (): void { if (JSB) { const rootNodes: Node[] = []; for (const screen of this._screens) { @@ -186,7 +186,7 @@ export class Batcher2D implements IBatcher { * @param comp @en The render root of 2d. * @zh 2d 渲染入口组件。 */ - public addScreen (comp: RenderRoot2D) { + public addScreen (comp: RenderRoot2D): void { this._screens.push(comp); this._screens.sort(this._screenSort); if (JSB) { @@ -201,7 +201,7 @@ export class Batcher2D implements IBatcher { * @param comp @en The target to removed. * @zh 被移除的屏幕。 */ - public removeScreen (comp: RenderRoot2D) { + public removeScreen (comp: RenderRoot2D): void { const idx = this._screens.indexOf(comp); if (idx === -1) { return; @@ -212,7 +212,7 @@ export class Batcher2D implements IBatcher { } } - public sortScreens () { + public sortScreens (): void { this._screens.sort(this._screenSort); if (JSB) { this.syncRootNodesToNative(); @@ -232,7 +232,7 @@ export class Batcher2D implements IBatcher { return null; } - public update () { + public update (): void { if (JSB) { return; } @@ -272,7 +272,7 @@ export class Batcher2D implements IBatcher { } } - public uploadBuffers () { + public uploadBuffers (): void { if (JSB) { this._nativeObj.uploadBuffers(); } else if (this._batches.length > 0) { @@ -290,7 +290,7 @@ export class Batcher2D implements IBatcher { } } - public reset () { + public reset (): void { if (JSB) { this._nativeObj.reset(); } else { @@ -334,7 +334,7 @@ export class Batcher2D implements IBatcher { * @en Switch the mesh buffer for corresponding vertex layout if necessary. * @param attributes use VertexFormat.vfmtPosUvColor by default */ - public switchBufferAccessor (attributes: Attribute[] = vfmtPosUvColor) { + public switchBufferAccessor (attributes: Attribute[] = vfmtPosUvColor): StaticVBAccessor { const strideBytes = attributes === vfmtPosUvColor ? 36 /* 9x4 */ : getAttributeStride(attributes); // If current accessor not compatible with the requested attributes if (!this._staticVBBuffer || (this._staticVBBuffer.vertexFormatBytes) !== strideBytes) { @@ -350,11 +350,11 @@ export class Batcher2D implements IBatcher { return this._staticVBBuffer; } - public registerBufferAccessor (key: number, accessor: StaticVBAccessor) { + public registerBufferAccessor (key: number, accessor: StaticVBAccessor): void { this._bufferAccessors.set(key, accessor); } - public updateBuffer (attributes: Attribute[], bid: number) { + public updateBuffer (attributes: Attribute[], bid: number): void { const accessor = this.switchBufferAccessor(attributes); // If accessor changed, then current bid will be reset to -1, this check will pass too if (this._currBID !== bid) { @@ -379,7 +379,7 @@ export class Batcher2D implements IBatcher { * @param assembler - The assembler for the current component, could be null * @param transform - Node type transform, if passed, then batcher will consider it's using model matrix, could be null */ - public commitComp (comp: UIRenderer, renderData: BaseRenderData|null, frame: TextureBase|SpriteFrame|null, assembler, transform: Node|null) { + public commitComp (comp: UIRenderer, renderData: BaseRenderData|null, frame: TextureBase|SpriteFrame|null, assembler, transform: Node|null): void { let dataHash = 0; let mat; let bufferID = -1; @@ -444,7 +444,7 @@ export class Batcher2D implements IBatcher { * @param [transform] - The related node transform if the render data is based on node's local coordinates * @deprecated since v3.6.2, please use [[commitMiddleware]] instead */ - public commitIA (renderComp: UIRenderer, ia: InputAssembler, tex?: TextureBase, mat?: Material, transform?: Node) { + public commitIA (renderComp: UIRenderer, ia: InputAssembler, tex?: TextureBase, mat?: Material, transform?: Node): void { // if the last comp is spriteComp, previous comps should be batched. if (this._currMaterial !== this._emptyMaterial) { this.autoMergeBatches(this._currComponent!); @@ -491,7 +491,7 @@ export class Batcher2D implements IBatcher { * @param enableBatch - component support multi draw batch or not */ public commitMiddleware (comp: UIRenderer, meshBuffer: MeshBuffer, indexOffset: number, - indexCount: number, tex: TextureBase, mat: Material, enableBatch: boolean) { + indexCount: number, tex: TextureBase, mat: Material, enableBatch: boolean): void { // check if need merge draw batch const texture = tex.getGFXTexture(); if (enableBatch && this._middlewareEnableBatch && this._middlewareBuffer === meshBuffer @@ -536,7 +536,7 @@ export class Batcher2D implements IBatcher { * @param model - The committed model * @param mat - The material used, could be null */ - public commitModel (comp: UIMeshRenderer | UIRenderer, model: Model | null, mat: Material | null) { + public commitModel (comp: UIMeshRenderer | UIRenderer, model: Model | null, mat: Material | null): void { // if the last comp is spriteComp, previous comps should be batched. if (this._currMaterial !== this._emptyMaterial) { this.autoMergeBatches(this._currComponent!); @@ -579,13 +579,13 @@ export class Batcher2D implements IBatcher { } } - public setupStaticBatch (staticComp: UIStaticBatch, bufferAccessor: StaticVBAccessor) { + public setupStaticBatch (staticComp: UIStaticBatch, bufferAccessor: StaticVBAccessor): void { this.finishMergeBatches(); this._staticVBBuffer = bufferAccessor; this.currStaticRoot = staticComp; } - public endStaticBatch () { + public endStaticBatch (): void { this.finishMergeBatches(); this.currStaticRoot = null; // Clear linear buffer to switch to the correct internal accessor @@ -603,7 +603,7 @@ export class Batcher2D implements IBatcher { * @param comp @en The UIStaticBatch component. * @zh 静态组件 */ - public commitStaticBatch (comp: UIStaticBatch) { + public commitStaticBatch (comp: UIStaticBatch): void { this._batches.concat(comp.drawBatchList); this.finishMergeBatches(); } @@ -615,7 +615,7 @@ export class Batcher2D implements IBatcher { * @zh * 根据合批条件,结束一段渲染数据并提交。 */ - public autoMergeBatches (renderComp?: UIRenderer) { + public autoMergeBatches (renderComp?: UIRenderer): void { if (this._currIsMiddleware) { this.mergeBatchesForMiddleware(renderComp!); return; @@ -682,7 +682,7 @@ export class Batcher2D implements IBatcher { this._batches.push(curDrawBatch); } - private mergeBatchesForMiddleware (renderComp: UIRenderer) { + private mergeBatchesForMiddleware (renderComp: UIRenderer): void { let depthStencil; let dssHash = 0; renderComp.stencilStage = StencilManager.sharedManager!.stage; @@ -724,7 +724,7 @@ export class Batcher2D implements IBatcher { * @param sprite @en Sprite frame of current batch. * @zh 当前批次的精灵帧。 */ - public forceMergeBatches (material: Material, frame: TextureBase | SpriteFrame | null, renderComp: UIRenderer) { + public forceMergeBatches (material: Material, frame: TextureBase | SpriteFrame | null, renderComp: UIRenderer): void { this._currMaterial = material; if (frame) { @@ -741,7 +741,7 @@ export class Batcher2D implements IBatcher { this.autoMergeBatches(renderComp); } - public resetRenderStates () { + public resetRenderStates (): void { this._currMaterial = this._emptyMaterial; this._currRenderData = null; this._currTexture = null; @@ -759,7 +759,7 @@ export class Batcher2D implements IBatcher { * @zh * 强制合并上一个批次的数据,开启新一轮合批。 */ - public finishMergeBatches () { + public finishMergeBatches (): void { this.autoMergeBatches(); this.resetRenderStates(); } @@ -771,11 +771,11 @@ export class Batcher2D implements IBatcher { * @zh * 强制刷新材质。 */ - public flushMaterial (mat: Material) { + public flushMaterial (mat: Material): void { this._currMaterial = mat; } - public walk (node: Node, level = 0) { + public walk (node: Node, level = 0): void { if (!node.activeInHierarchy) { return; } @@ -844,12 +844,12 @@ export class Batcher2D implements IBatcher { level += 1; } - private _screenSort (a: RenderRoot2D, b: RenderRoot2D) { + private _screenSort (a: RenderRoot2D, b: RenderRoot2D): number { return a.node.getSiblingIndex() - b.node.getSiblingIndex(); } // TODO: Not a good way to do the job - private _releaseDescriptorSetCache (textureHash, sampler = null!) { + private _releaseDescriptorSetCache (textureHash, sampler = null!): void { if (JSB) { this._nativeObj.releaseDescriptorSetCache(textureHash, sampler); } else { @@ -858,7 +858,7 @@ export class Batcher2D implements IBatcher { } // Mask use - private _createClearModel () { + private _createClearModel (): void { if (!this._maskClearModel) { this._maskClearMtl = builtinResMgr.get('default-clear-stencil'); @@ -890,7 +890,7 @@ export class Batcher2D implements IBatcher { } } - private _insertMaskBatch (comp: UIRenderer | UIMeshRenderer) { + private _insertMaskBatch (comp: UIRenderer | UIMeshRenderer): void { this.autoMergeBatches(this._currComponent!); this.resetRenderStates(); this._createClearModel(); @@ -933,7 +933,7 @@ export class Batcher2D implements IBatcher { } //sync mesh buffer to naive - public syncMeshBuffersToNative (accId: number, buffers: MeshBuffer[]) { + public syncMeshBuffersToNative (accId: number, buffers: MeshBuffer[]): void { if (JSB) { const nativeBuffers = buffers.map((buf) => buf.nativeObj); this._nativeObj.syncMeshBuffersToNative(accId, nativeBuffers); @@ -965,7 +965,7 @@ class LocalDescriptorSet { )); } - public initialize (batch) { + public initialize (batch): void { const device = deviceManager.gfxDevice; this._transform = batch.useLocalData; this._textureHash = batch.textureHash; @@ -980,24 +980,24 @@ class LocalDescriptorSet { this._transformUpdate = true; } - public updateTransform (transform: Node) { + public updateTransform (transform: Node): void { if (transform === this._transform) return; this._transform = transform; this._transformUpdate = true; this.uploadLocalData(); } - public equals (transform, textureHash, samplerHash) { + public equals (transform, textureHash, samplerHash): boolean { return this._transform === transform && this._textureHash === textureHash && this._samplerHash === samplerHash; } - public reset () { + public reset (): void { this._transform = null; this._textureHash = 0; this._samplerHash = 0; } - public destroy () { + public destroy (): void { if (this._localBuffer) { this._localBuffer.destroy(); this._localBuffer = null; @@ -1011,11 +1011,11 @@ class LocalDescriptorSet { this._localData = null; } - public isValid () { + public isValid (): boolean | null { return this._transform && this._transform.isValid; } - public uploadLocalData () { + public uploadLocalData (): void { const node = this._transform!; if (node.hasChangedFlags || node.isTransformDirty()) { node.updateWorldTransform(); @@ -1087,7 +1087,7 @@ class DescriptorSetCache { } } - public update () { + public update (): void { const caches = this._localDescriptorSetCache; const length = caches.length; if (length === 0) { return; } @@ -1110,7 +1110,7 @@ class DescriptorSetCache { } } - public reset () { + public reset (): void { const caches = this._localDescriptorSetCache; const length = caches.length; for (let i = 0; i < length; i++) { @@ -1120,7 +1120,7 @@ class DescriptorSetCache { this._localDescriptorSetCache.length = 0; } - public releaseDescriptorSetCache (textureHash) { + public releaseDescriptorSetCache (textureHash): void { const key = this._dsCacheHashByTexture.get(textureHash); if (key && this._descriptorSetCache.has(key)) { this._descriptorSetCache.get(key)!.destroy(); @@ -1129,7 +1129,7 @@ class DescriptorSetCache { } } - public destroy () { + public destroy (): void { for (const value of this._descriptorSetCache.values()) { value.destroy(); } diff --git a/cocos/2d/renderer/buffer-accessor.ts b/cocos/2d/renderer/buffer-accessor.ts index 8ef1612a51e..60247570aff 100644 --- a/cocos/2d/renderer/buffer-accessor.ts +++ b/cocos/2d/renderer/buffer-accessor.ts @@ -28,8 +28,8 @@ import { getAttributeStride } from './vertex-format'; export class BufferAccessor { public get attributes (): Readonly { return this._attributes; } - public get vertexFormatBytes () { return this._vertexFormatBytes; } - public get floatsPerVertex () { return this._floatsPerVertex; } + public get vertexFormatBytes (): number { return this._vertexFormatBytes; } + public get floatsPerVertex (): number { return this._floatsPerVertex; } protected _device: Device = null! protected _attributes: Attribute[] = null!; @@ -45,12 +45,12 @@ export class BufferAccessor { this._vertexFormatBytes = this._floatsPerVertex * Float32Array.BYTES_PER_ELEMENT; } - public initialize () {} - public reset () {} - public request (vertexCount = 4, indexCount = 6) {} - public appendBuffers (vertices: Float32Array, indices: Uint16Array) {} - public uploadBuffers () {} - public destroy () { + public initialize (): void {} + public reset (): void {} + public request (vertexCount = 4, indexCount = 6): void {} + public appendBuffers (vertices: Float32Array, indices: Uint16Array): void {} + public uploadBuffers (): void {} + public destroy (): void { this._attributes.length = 0; } } diff --git a/cocos/2d/renderer/draw-batch.ts b/cocos/2d/renderer/draw-batch.ts index 42f6c6f7260..2cadbd5c412 100644 --- a/cocos/2d/renderer/draw-batch.ts +++ b/cocos/2d/renderer/draw-batch.ts @@ -33,7 +33,7 @@ import { IBatcher } from './i-batcher'; const UI_VIS_FLAG = Layers.Enum.NONE | Layers.Enum.UI_3D; export class DrawBatch2D { - public get inputAssembler () { + public get inputAssembler (): InputAssembler | null { return this._inputAssembler; } @@ -41,7 +41,7 @@ export class DrawBatch2D { this._inputAssembler = ia; } - public get descriptorSet () { + public get descriptorSet (): DescriptorSet | null { return this._descriptorSet; } @@ -49,18 +49,18 @@ export class DrawBatch2D { this._descriptorSet = ds; } - public get visFlags () { + public get visFlags (): number { return this._visFlags; } public set visFlags (vis) { this._visFlags = vis; } - get passes () { + get passes (): Pass[] { return this._passes; } - public get shaders () { + public get shaders (): Shader[] { return this._shaders; } @@ -81,11 +81,11 @@ export class DrawBatch2D { private _descriptorSet: DescriptorSet | null = null; //private declare _nativeObj: any; - public destroy (ui: IBatcher) { + public destroy (ui: IBatcher): void { this._passes = []; } - public clear () { + public clear (): void { // this.bufferBatch = null; this._inputAssembler = null; this._descriptorSet = null; @@ -102,7 +102,7 @@ export class DrawBatch2D { } // object version - public fillPasses (mat: Material | null, dss, dssHash, patches) { + public fillPasses (mat: Material | null, dss, dssHash, patches): void { if (mat) { const passes = mat.passes; if (!passes) { return; } diff --git a/cocos/2d/renderer/mesh-buffer.ts b/cocos/2d/renderer/mesh-buffer.ts index 1cd8c67d608..1cfac55efda 100644 --- a/cocos/2d/renderer/mesh-buffer.ts +++ b/cocos/2d/renderer/mesh-buffer.ts @@ -55,13 +55,13 @@ export class MeshBuffer { * @zh buffer 的顶点属性。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get attributes () { return this._attributes; } + get attributes (): Attribute[] { return this._attributes; } /** * @en Number of bytes in vertex format. * @zh 顶点格式的字节数。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get vertexFormatBytes () { return this._vertexFormatBytes; } + get vertexFormatBytes (): number { return this._vertexFormatBytes; } protected _byteOffset = 0; /** @@ -69,7 +69,7 @@ export class MeshBuffer { * @zh 字节偏移量。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get byteOffset () { + get byteOffset (): number { return this._byteOffset; } set byteOffset (val: number) { @@ -85,7 +85,7 @@ export class MeshBuffer { * @zh 顶点数偏移。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get vertexOffset () { + get vertexOffset (): number { return this._vertexOffset; } set vertexOffset (val: number) { @@ -101,7 +101,7 @@ export class MeshBuffer { * @zh 索引偏移。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get indexOffset () { + get indexOffset (): number { return this._indexOffset; } set indexOffset (val: number) { @@ -117,7 +117,7 @@ export class MeshBuffer { * @zh 脏标记。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get dirty () { + get dirty (): boolean { return this._dirty; } set dirty (val: boolean) { @@ -133,7 +133,7 @@ export class MeshBuffer { * @zh 每顶点的浮点数长度。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get floatsPerVertex () { + get floatsPerVertex (): number { return this._floatsPerVertex; } set floatsPerVertex (val: number) { @@ -146,7 +146,7 @@ export class MeshBuffer { * @zh 顶点数据。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get vData () { + get vData (): Float32Array { return this._vData; } set vData (val: Float32Array) { @@ -163,7 +163,7 @@ export class MeshBuffer { * @zh 索引数据。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get iData () { + get iData (): Uint16Array { return this._iData; } set iData (val: Uint16Array) { @@ -190,7 +190,7 @@ export class MeshBuffer { * @zh 原生对象。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get nativeObj () { + get nativeObj (): NativeUIMeshBuffer { return this._nativeObj; } @@ -201,7 +201,7 @@ export class MeshBuffer { * @zh 原生共享缓冲。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get sharedBuffer () { + get sharedBuffer (): Uint32Array { return this._sharedBuffer; } @@ -210,7 +210,7 @@ export class MeshBuffer { * @zh 初始化原生共享缓冲。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public initSharedBuffer () { + public initSharedBuffer (): void { if (JSB) { this._sharedBuffer = new Uint32Array(MeshBufferSharedBufferView.count); } @@ -221,7 +221,7 @@ export class MeshBuffer { * @zh 同步原生共享缓冲。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public syncSharedBufferToNative () { + public syncSharedBufferToNative (): void { if (JSB) { this._nativeObj.syncSharedBufferToNative(this._sharedBuffer); } @@ -244,7 +244,7 @@ export class MeshBuffer { * @param iCount @en The indices count. @zh 索引数量。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public initialize (device: Device, attrs: Attribute[], vFloatCount: number, iCount: number) { + public initialize (device: Device, attrs: Attribute[], vFloatCount: number, iCount: number): void { this._initVDataCount = vFloatCount; this._initIDataCount = iCount; this._attributes = attrs; @@ -269,12 +269,12 @@ export class MeshBuffer { * @zh 重置状态。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public reset () { + public reset (): void { this._nextFreeIAHandle = 0; this.dirty = false; } - public destroy () { + public destroy (): void { this.reset(); this._attributes = null!; this._iaInfo = null!; @@ -300,7 +300,7 @@ export class MeshBuffer { * @zh 设置脏标签。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public setDirty () { + public setDirty (): void { this.dirty = true; } @@ -308,7 +308,7 @@ export class MeshBuffer { * @deprecated since v3.4.0, please use BufferAccessor's request * @see [[BufferAccessor.request]] */ - public request (vertexCount: number, indexCount: number) { + public request (vertexCount: number, indexCount: number): boolean { warnID(9002); return false; } @@ -318,7 +318,7 @@ export class MeshBuffer { * @zh 请求可用的输入汇集器。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public requireFreeIA (device: Device) { + public requireFreeIA (device: Device): InputAssembler { if (this._iaPool.length <= this._nextFreeIAHandle) { this._iaPool.push(this.createNewIA(device)); } @@ -331,7 +331,7 @@ export class MeshBuffer { * @zh 回收输入汇集器。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public recycleIA (ia: InputAssembler) { + public recycleIA (ia: InputAssembler): void { const pool = this._iaPool; for (let i = 0; i < this._nextFreeIAHandle; ++i) { if (ia === pool[i].ia) { @@ -349,7 +349,7 @@ export class MeshBuffer { * @zh 检查可分配余量。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public checkCapacity (vertexCount: number, indexCount: number) { + public checkCapacity (vertexCount: number, indexCount: number): boolean { const maxVertex = (this.vertexOffset + vertexCount) * this._floatsPerVertex; const maxIndex = this.indexOffset + indexCount; if (maxVertex > this._initVDataCount || maxIndex > this._initIDataCount) { @@ -363,7 +363,7 @@ export class MeshBuffer { * @zh 上传更新缓冲内容。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public uploadBuffers () { + public uploadBuffers (): void { if (this.byteOffset === 0 || !this._dirty) { return; } diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index 14464d2068d..3f4fc8c1582 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -35,6 +35,7 @@ import { Buffer, BufferInfo, BufferUsageBit, Device, Attribute, InputAssembler, import { RenderDrawInfo, RenderDrawInfoType } from './render-draw-info'; import { Batcher2D } from './batcher-2d'; import { RenderEntity, RenderEntityType } from './render-entity'; +import type { MeshBuffer } from './mesh-buffer'; /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. @@ -65,23 +66,23 @@ const _pool: RecyclePool = null!; * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export class BaseRenderData { - get vertexCount () { + get vertexCount (): number { return this._vc; } - get indexCount () { + get indexCount (): number { return this._ic; } - get stride () { + get stride (): number { return this._floatStride << 2; } - get floatStride () { + get floatStride (): number { return this._floatStride; } - get vertexFormat () { + get vertexFormat (): Attribute[] { return this._vertexFormat; } - get drawInfoType () { + get drawInfoType (): RenderDrawInfoType { return this._drawInfoType; } set drawInfoType (type: RenderDrawInfoType) { @@ -95,12 +96,12 @@ export class BaseRenderData { // entity for native protected _renderDrawInfo: RenderDrawInfo = null!; - public get renderDrawInfo () { + public get renderDrawInfo (): RenderDrawInfo { return this._renderDrawInfo; } protected _material: Material | null = null; - get material () { + get material (): Material | null { return this._material!; } set material (val: Material | null) { @@ -111,7 +112,7 @@ export class BaseRenderData { } protected _dataHash = 0; - get dataHash () { + get dataHash (): number { return this._dataHash; } set dataHash (val: number) { @@ -129,13 +130,13 @@ export class BaseRenderData { protected _vertexFormat = vfmtPosUvColor; protected _drawInfoType :RenderDrawInfoType = RenderDrawInfoType.COMP; protected _multiOwner = false; - get multiOwner () { return this._multiOwner; } + get multiOwner (): boolean { return this._multiOwner; } set multiOwner (val) { this._multiOwner = val; } protected _batcher: Batcher2D | null = null; - get batcher () { + get batcher (): Batcher2D { if (!this._batcher) { this._batcher = director.root!.batcher2D; } @@ -147,12 +148,12 @@ export class BaseRenderData { this._vertexFormat = vertexFormat; } - public isValid () { + public isValid (): false | StaticVBAccessor { return this._ic > 0 && this.chunk.vertexAccessor; } // it should be invoked at where a render data is allocated. - public initRenderDrawInfo (comp: UIRenderer, drawInfoType: RenderDrawInfoType = RenderDrawInfoType.COMP) { + public initRenderDrawInfo (comp: UIRenderer, drawInfoType: RenderDrawInfoType = RenderDrawInfoType.COMP): void { if (JSB) { const renderEntity: RenderEntity = comp.renderEntity; @@ -178,7 +179,7 @@ export class BaseRenderData { } } - public removeRenderDrawInfo (comp: UIRenderer) { + public removeRenderDrawInfo (comp: UIRenderer): void { if (JSB) { const renderEntity: RenderEntity = comp.renderEntity; if (renderEntity.renderEntityType === RenderEntityType.DYNAMIC) { @@ -189,7 +190,7 @@ export class BaseRenderData { } } - protected setRenderDrawInfoAttributes () { + protected setRenderDrawInfoAttributes (): void { if (JSB) { if (!this._renderDrawInfo) { return; @@ -221,7 +222,7 @@ export class BaseRenderData { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export class RenderData extends BaseRenderData { - public static add (vertexFormat = vfmtPosUvColor, accessor?: StaticVBAccessor) { + public static add (vertexFormat = vfmtPosUvColor, accessor?: StaticVBAccessor): RenderData { const rd = new RenderData(vertexFormat, accessor); if (!accessor) { const batcher = director.root!.batcher2D; @@ -231,7 +232,7 @@ export class RenderData extends BaseRenderData { return rd; } - public static remove (data: RenderData) { + public static remove (data: RenderData): void { // const idx = _pool.data.indexOf(data); // if (idx === -1) { // return; @@ -242,7 +243,7 @@ export class RenderData extends BaseRenderData { // _pool.removeAt(idx); } - get dataLength () { + get dataLength (): number { return this._data.length; } @@ -266,12 +267,12 @@ export class RenderData extends BaseRenderData { this.syncRender2dBuffer(); } - get data () { + get data ():IRenderData[] { return this._data; } public _vertDirty = true; - get vertDirty () { + get vertDirty (): boolean { return this._vertDirty; } set vertDirty (val: boolean) { @@ -282,7 +283,7 @@ export class RenderData extends BaseRenderData { } protected _textureHash = 0; - get textureHash () { + get textureHash (): number { return this._textureHash; } set textureHash (val: number) { @@ -303,7 +304,7 @@ export class RenderData extends BaseRenderData { } } } - public get frame () { + public get frame (): SpriteFrame | TextureBase | null { return this._frame; } public layer = 0; @@ -320,7 +321,7 @@ export class RenderData extends BaseRenderData { private _height = 0; private _frame: SpriteFrame | TextureBase | null = null; protected _accessor: StaticVBAccessor = null!; - get accessor () { return this._accessor; } + get accessor (): StaticVBAccessor { return this._accessor; } public vertexRow = 1; public vertexCol = 1; @@ -333,7 +334,7 @@ export class RenderData extends BaseRenderData { this._accessor = accessor; } - public resize (vertexCount: number, indexCount: number) { + public resize (vertexCount: number, indexCount: number): void { if (vertexCount === this._vc && indexCount === this._ic && this.chunk) return; this._vc = vertexCount; this._ic = indexCount; @@ -361,7 +362,7 @@ export class RenderData extends BaseRenderData { } } - protected setRenderDrawInfoAttributes () { + protected setRenderDrawInfoAttributes (): void { if (JSB) { if (!this._renderDrawInfo) { return; @@ -375,7 +376,7 @@ export class RenderData extends BaseRenderData { /** * @internal */ - public fillDrawInfoAttributes (drawInfo: RenderDrawInfo) { + public fillDrawInfoAttributes (drawInfo: RenderDrawInfo): void { if (JSB) { if (!drawInfo) { return; @@ -397,7 +398,7 @@ export class RenderData extends BaseRenderData { } // Initial advance render data for native - protected syncRender2dBuffer () { + protected syncRender2dBuffer (): void { if (JSB && this.multiOwner === false) { if (!this._renderDrawInfo) { return; @@ -408,7 +409,7 @@ export class RenderData extends BaseRenderData { } } - public resizeAndCopy (vertexCount: number, indexCount: number) { + public resizeAndCopy (vertexCount: number, indexCount: number): void { if (vertexCount === this._vc && indexCount === this._ic && this.chunk) return; this._vc = vertexCount; this._ic = indexCount; @@ -423,7 +424,7 @@ export class RenderData extends BaseRenderData { this.updateHash(); } - public getMeshBuffer () { + public getMeshBuffer (): MeshBuffer | null { if (this.chunk && this._accessor) { return this._accessor.getMeshBuffer(this.chunk.bufferId); } else { @@ -431,33 +432,33 @@ export class RenderData extends BaseRenderData { } } - public updateNode (comp: UIRenderer) { + public updateNode (comp: UIRenderer): void { this.layer = comp.node.layer; this.nodeDirty = false; this.hashDirty = true; } - public updatePass (comp: UIRenderer) { + public updatePass (comp: UIRenderer): void { this.material = comp.getRenderMaterial(0)!; this.passDirty = false; this.hashDirty = true; } - public updateTexture (frame: SpriteFrame | TextureBase) { + public updateTexture (frame: SpriteFrame | TextureBase): void { this.frame = frame; this.textureHash = frame.getHash(); this.textureDirty = false; this.hashDirty = true; } - public updateHash () { + public updateHash (): void { const bid = this.chunk ? this.chunk.bufferId : -1; const hashString = `${bid}${this.layer} ${this.textureHash}`; this.dataHash = murmurhash2_32_gc(hashString, 666); this.hashDirty = false; } - public updateRenderData (comp: UIRenderer, frame: SpriteFrame | TextureBase) { + public updateRenderData (comp: UIRenderer, frame: SpriteFrame | TextureBase): void { if (this.passDirty) { this.material = comp.getRenderMaterial(0)!; this.passDirty = false; @@ -505,7 +506,7 @@ export class RenderData extends BaseRenderData { } } - public updateSizeNPivot (width: number, height: number, pivotX: number, pivotY: number) { + public updateSizeNPivot (width: number, height: number, pivotX: number, pivotY: number): void { if (width !== this._width || height !== this._height || pivotX !== this._pivotX @@ -518,7 +519,7 @@ export class RenderData extends BaseRenderData { } } - public clear () { + public clear (): void { this.resize(0, 0); this._data.length = 0; this._pivotX = 0; @@ -553,7 +554,7 @@ export class RenderData extends BaseRenderData { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export class MeshRenderData extends BaseRenderData { - public static add (vertexFormat = vfmtPosUvColor) { + public static add (vertexFormat = vfmtPosUvColor): MeshRenderData { // const rd = _meshDataPool.add(); const rd = new MeshRenderData(); rd._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : (getAttributeStride(vertexFormat) >> 2); @@ -561,7 +562,7 @@ export class MeshRenderData extends BaseRenderData { return rd; } - public static remove (data: MeshRenderData) { + public static remove (data: MeshRenderData): void { // const idx = _meshDataPool.data.indexOf(data); // if (idx === -1) { // return; @@ -577,14 +578,14 @@ export class MeshRenderData extends BaseRenderData { * @deprecated */ set formatByte (value: number) { } - get formatByte () { return this.stride; } + get formatByte (): number { return this.stride; } - get floatStride () { return this._floatStride; } + get floatStride (): number { return this._floatStride; } /** * Index of Float32Array: vData */ - get vDataOffset () { return this._byteLength >>> 2; } + get vDataOffset (): number { return this._byteLength >>> 2; } public _isMeshBuffer = true; public vData: Float32Array; @@ -624,7 +625,7 @@ export class MeshRenderData extends BaseRenderData { this.iData = new Uint16Array(256 * 6); } - public request (vertexCount: number, indexCount: number) { + public request (vertexCount: number, indexCount: number): boolean { const byteOffset = this._byteLength + vertexCount * this.stride; const succeed = this.reserve(vertexCount, indexCount); if (!succeed) return false; @@ -636,7 +637,7 @@ export class MeshRenderData extends BaseRenderData { return true; } - public reserve (vertexCount: number, indexCount: number) { + public reserve (vertexCount: number, indexCount: number): boolean { const newVBytes = this._byteLength + vertexCount * this.stride; const newICount = this.indexCount + indexCount; @@ -664,7 +665,7 @@ export class MeshRenderData extends BaseRenderData { // overload // Resize buffer and IA range - public resize (vertexCount: number, indexCount: number) { + public resize (vertexCount: number, indexCount: number): void { const byteLength = vertexCount * this.stride; assertIsTrue(vertexCount >= 0 && indexCount >= 0 && byteLength <= this.vData.byteLength && indexCount <= this.iData.length); this._vc = vertexCount; @@ -674,7 +675,7 @@ export class MeshRenderData extends BaseRenderData { } // Only resize IA range - public updateRange (vertOffset: number, vertexCount: number, indexOffset: number, indexCount: number) { + public updateRange (vertOffset: number, vertexCount: number, indexOffset: number, indexCount: number): void { assertIsTrue(vertexCount >= 0 && indexCount >= 0 && vertexCount <= this._vc && indexCount <= this._ic); this.vertexStart = vertOffset; this.indexStart = indexOffset; @@ -682,7 +683,7 @@ export class MeshRenderData extends BaseRenderData { this.indexRange = indexCount; } - public requestIA (device: Device) { + public requestIA (device: Device): InputAssembler { this._initIAInfo(device); const ia = this._iaPool!.add(); ia.firstIndex = this.indexStart; @@ -690,7 +691,7 @@ export class MeshRenderData extends BaseRenderData { return ia; } - public uploadBuffers () { + public uploadBuffers (): void { if (this._byteLength === 0 || !this._vertexBuffers[0] || !this._indexBuffer) { return; } @@ -712,13 +713,13 @@ export class MeshRenderData extends BaseRenderData { this._indexBuffer.update(indicesData); } - public freeIAPool () { + public freeIAPool (): void { if (this._iaPool) { this._iaPool.reset(); } } - public reset () { + public reset (): void { this._vc = 0; this._ic = 0; this._byteLength = 0; @@ -732,7 +733,7 @@ export class MeshRenderData extends BaseRenderData { this.freeIAPool(); } - public clear () { + public clear (): void { this.reset(); if (this._iaPool) { this._iaPool.destroy(); @@ -746,7 +747,7 @@ export class MeshRenderData extends BaseRenderData { this.iData = new Uint16Array(256 * 6); } - protected _initIAInfo (device: Device) { + protected _initIAInfo (device: Device): void { if (!this._iaInfo) { const vbStride = this.stride; const vbs = this._vertexBuffers; @@ -772,7 +773,7 @@ export class MeshRenderData extends BaseRenderData { } } - protected _reallocBuffer (vCount, iCount) { + protected _reallocBuffer (vCount, iCount): void { // copy old data const oldVData = this.vData; this.vData = new Float32Array(vCount); @@ -786,7 +787,7 @@ export class MeshRenderData extends BaseRenderData { } } - public setRenderDrawInfoAttributes () { + public setRenderDrawInfoAttributes (): void { if (JSB) { if (!this._renderDrawInfo) { return; @@ -806,7 +807,7 @@ export class MeshRenderData extends BaseRenderData { } // only for particle2d - public particleInitRenderDrawInfo (entity: RenderEntity) { + public particleInitRenderDrawInfo (entity: RenderEntity): void { if (JSB) { if (entity.renderEntityType === RenderEntityType.STATIC) { if (!this._renderDrawInfo) { diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index f118dcd6d4d..01e1a34552b 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -103,15 +103,15 @@ export class RenderDrawInfo { this._uint32SharedBuffer = new Uint32Array(attrSharedBuffer, offset, AttrUInt32ArrayView.Count); } - get nativeObj () { + get nativeObj (): NativeRenderDrawInfo { return this._nativeObj; } - get render2dBuffer () { + get render2dBuffer (): Float32Array { return this._render2dBuffer; } - private init (nativeDrawInfo?: NativeRenderDrawInfo) { + private init (nativeDrawInfo?: NativeRenderDrawInfo): void { if (JSB) { if (nativeDrawInfo) { this._nativeObj = nativeDrawInfo; @@ -122,14 +122,14 @@ export class RenderDrawInfo { } } - public clear () { + public clear (): void { this._bufferId = 0; this._vertexOffset = 0; this._indexOffset = 0; this._vertDirty = false; } - public setAccId (accId) { + public setAccId (accId): void { if (JSB) { if (this._accId !== accId) { this._uint16SharedBuffer[AttrUInt16ArrayView.AccessorID] = accId; @@ -138,7 +138,7 @@ export class RenderDrawInfo { this._accId = accId; } - public setBufferId (bufferId) { + public setBufferId (bufferId): void { if (JSB) { if (this._bufferId !== bufferId) { this._uint16SharedBuffer[AttrUInt16ArrayView.BufferID] = bufferId; @@ -148,7 +148,7 @@ export class RenderDrawInfo { this._bufferId = bufferId; } - public setAccAndBuffer (accId, bufferId) { + public setAccAndBuffer (accId, bufferId): void { if (JSB) { if (this._accId !== accId || this._bufferId !== bufferId) { this._uint16SharedBuffer[AttrUInt16ArrayView.AccessorID] = accId; @@ -160,79 +160,79 @@ export class RenderDrawInfo { this._accId = accId; } - public setVertexOffset (vertexOffset) { + public setVertexOffset (vertexOffset): void { this._vertexOffset = vertexOffset; if (JSB) { this._uint32SharedBuffer[AttrUInt32ArrayView.VertexOffset] = vertexOffset; } } - public setIndexOffset (indexOffset) { + public setIndexOffset (indexOffset): void { this._indexOffset = indexOffset; if (JSB) { this._uint32SharedBuffer[AttrUInt32ArrayView.IndexOffset] = indexOffset; } } - public setVB (vbBuffer: Float32Array) { + public setVB (vbBuffer: Float32Array): void { if (JSB) { this._nativeObj.vbBuffer = vbBuffer; } } - public setIB (ibBuffer: Uint16Array) { + public setIB (ibBuffer: Uint16Array): void { if (JSB) { this._nativeObj.ibBuffer = ibBuffer; } } - public setVData (vDataBuffer: ArrayBufferLike) { + public setVData (vDataBuffer: ArrayBufferLike): void { if (JSB) { this._nativeObj.vDataBuffer = vDataBuffer; } } - public setIData (iDataBuffer: ArrayBufferLike) { + public setIData (iDataBuffer: ArrayBufferLike): void { if (JSB) { this._nativeObj.iDataBuffer = iDataBuffer; } } - public setVBCount (vbCount) { + public setVBCount (vbCount): void { if (JSB) { this._uint32SharedBuffer[AttrUInt32ArrayView.VBCount] = vbCount; } this._vbCount = vbCount; } - public setIBCount (ibCount) { + public setIBCount (ibCount): void { if (JSB) { this._uint32SharedBuffer[AttrUInt32ArrayView.IBCount] = ibCount; } } - public setVertDirty (val: boolean) { + public setVertDirty (val: boolean): void { if (JSB) { this._uint8SharedBuffer[AttrUInt8ArrayView.VertDirty] = val ? 1 : 0; } this._vertDirty = val; } - public setDataHash (dataHash: number) { + public setDataHash (dataHash: number): void { if (JSB) { this._uint32SharedBuffer[AttrUInt32ArrayView.DataHash] = dataHash; } this._dataHash = dataHash; } - public setIsMeshBuffer (isMeshBuffer: boolean) { + public setIsMeshBuffer (isMeshBuffer: boolean): void { if (JSB) { this._uint8SharedBuffer[AttrUInt8ArrayView.IsMeshBuffer] = isMeshBuffer ? 1 : 0; } this._isMeshBuffer = isMeshBuffer; } - public setMaterial (material: Material) { + public setMaterial (material: Material): void { if (JSB) { if (this._material !== material) { this._nativeObj.material = material; @@ -241,7 +241,7 @@ export class RenderDrawInfo { this._material = material; } - public setTexture (texture: Texture | null) { + public setTexture (texture: Texture | null): void { if (JSB) { if (this._texture !== texture) { this._nativeObj.texture = texture; @@ -250,7 +250,7 @@ export class RenderDrawInfo { this._texture = texture; } - public setSampler (sampler: Sampler | null) { + public setSampler (sampler: Sampler | null): void { if (JSB) { if (this._sampler !== sampler) { this._nativeObj.sampler = sampler; @@ -259,7 +259,7 @@ export class RenderDrawInfo { this._sampler = sampler; } - public setModel (model: Model) { + public setModel (model: Model): void { if (JSB) { if (this._model !== model) { this._nativeObj.model = model; @@ -267,7 +267,7 @@ export class RenderDrawInfo { } } - public setDrawInfoType (drawInfoType: RenderDrawInfoType) { + public setDrawInfoType (drawInfoType: RenderDrawInfoType): void { if (JSB) { if (this._drawInfoType !== drawInfoType) { this._uint8SharedBuffer[AttrUInt8ArrayView.DrawInfoType] = drawInfoType; @@ -276,7 +276,7 @@ export class RenderDrawInfo { this._drawInfoType = drawInfoType; } - public setSubNode (node : Node) { + public setSubNode (node : Node): void { if (JSB) { if (this._subNode !== node) { this._nativeObj.subNode = node; @@ -285,21 +285,21 @@ export class RenderDrawInfo { this._subNode = node; } - public setStride (stride: number) { + public setStride (stride: number): void { if (JSB) { this._uint8SharedBuffer[AttrUInt8ArrayView.Stride] = stride; } this._stride = stride; } - public initRender2dBuffer () { + public initRender2dBuffer (): void { if (JSB) { this._render2dBuffer = new Float32Array(this._vbCount * this._stride); this._nativeObj.setRender2dBufferToNative(this._render2dBuffer); } } - public fillRender2dBuffer (vertexDataArr: IRenderData[]) { + public fillRender2dBuffer (vertexDataArr: IRenderData[]): void { if (JSB) { const fillLength = Math.min(this._vbCount, vertexDataArr.length); let bufferOffset = 0; diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index d59200c0cc5..8bd35121b4c 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -80,15 +80,15 @@ export class RenderEntity { protected declare _boolSharedBuffer: Uint8Array; private declare _nativeObj: NativeRenderEntity; - get nativeObj () { + get nativeObj (): NativeRenderEntity { return this._nativeObj; } - get renderDrawInfoArr () { + get renderDrawInfoArr (): RenderDrawInfo[] { return this._dynamicDrawInfoArr; } - get renderEntityType () { + get renderEntityType (): RenderEntityType { return this._renderEntityType; } // set renderEntityType (val:RenderEntityType) { @@ -96,7 +96,7 @@ export class RenderEntity { // } protected _color: Color = Color.WHITE; - get color () { + get color (): Color { return this._color; } set color (val: Color) { @@ -110,7 +110,7 @@ export class RenderEntity { } protected _localOpacity = 255; - get localOpacity () { + get localOpacity (): number { return this._localOpacity; } set localOpacity (val: number) { @@ -121,7 +121,7 @@ export class RenderEntity { } protected _colorDirty = true; - get colorDirty () { + get colorDirty (): boolean { return this._colorDirty; } set colorDirty (val: boolean) { @@ -132,7 +132,7 @@ export class RenderEntity { } protected _enabled = false; - get enabled () { + get enabled (): boolean { return this._enabled; } set enabled (val: boolean) { @@ -152,7 +152,7 @@ export class RenderEntity { } } - public addDynamicRenderDrawInfo (renderDrawInfo: RenderDrawInfo | null) { + public addDynamicRenderDrawInfo (renderDrawInfo: RenderDrawInfo | null): void { if (JSB) { if (renderDrawInfo) { this._dynamicDrawInfoArr.push(renderDrawInfo); @@ -161,27 +161,27 @@ export class RenderEntity { } } - public removeDynamicRenderDrawInfo () { + public removeDynamicRenderDrawInfo (): void { if (JSB) { this._dynamicDrawInfoArr.pop(); this._nativeObj.removeDynamicRenderDrawInfo(); } } - public clearDynamicRenderDrawInfos () { + public clearDynamicRenderDrawInfos (): void { if (JSB) { this._dynamicDrawInfoArr.length = 0; this._nativeObj.clearDynamicRenderDrawInfos(); } } - public clearStaticRenderDrawInfos () { + public clearStaticRenderDrawInfos (): void { if (JSB) { this._nativeObj.clearStaticRenderDrawInfos(); } } - public setDynamicRenderDrawInfo (renderDrawInfo: RenderDrawInfo | null, index: number) { + public setDynamicRenderDrawInfo (renderDrawInfo: RenderDrawInfo | null, index: number): void { if (JSB) { if (renderDrawInfo) { if (this._dynamicDrawInfoArr.length < index + 1) { @@ -195,7 +195,7 @@ export class RenderEntity { } } - public setMaskMode (mode: MaskMode) { + public setMaskMode (mode: MaskMode): void { if (JSB) { this._uint8SharedBuffer[RenderEntityUInt8SharedBufferView.maskMode] = mode; } @@ -211,7 +211,7 @@ export class RenderEntity { return null; } - setNode (node: Node | null) { + setNode (node: Node | null): void { if (JSB) { if (this._node !== node) { this._nativeObj.node = node; @@ -220,7 +220,7 @@ export class RenderEntity { this._node = node; } - setRenderTransform (renderTransform: Node | null) { + setRenderTransform (renderTransform: Node | null): void { if (JSB) { if (this._renderTransform !== renderTransform) { this._nativeObj.renderTransform = renderTransform; @@ -229,7 +229,7 @@ export class RenderEntity { this._renderTransform = renderTransform; } - setStencilStage (stage: Stage) { + setStencilStage (stage: Stage): void { if (JSB) { if (this._stencilStage !== stage) { this._nativeObj.stencilStage = stage; @@ -238,14 +238,14 @@ export class RenderEntity { this._stencilStage = stage; } - setUseLocal (useLocal: boolean) { + setUseLocal (useLocal: boolean): void { if (JSB) { this._boolSharedBuffer[RenderEntityBoolSharedBufferView.useLocal] = useLocal ? 1 : 0; } this._useLocal = useLocal; } - private initSharedBuffer () { + private initSharedBuffer (): void { if (JSB) { //this._sharedBuffer = new Float32Array(RenderEntitySharedBufferView.count); const buffer = this._nativeObj.getEntitySharedBufferForJS(); diff --git a/cocos/2d/renderer/static-vb-accessor.ts b/cocos/2d/renderer/static-vb-accessor.ts index 9a759f22848..d3a5fd49815 100644 --- a/cocos/2d/renderer/static-vb-accessor.ts +++ b/cocos/2d/renderer/static-vb-accessor.ts @@ -61,7 +61,7 @@ export class StaticVBChunk { assertIsTrue(meshBuffer === vertexAccessor.getMeshBuffer(bufferId)); } - setIndexBuffer (indices: ArrayLike) { + setIndexBuffer (indices: ArrayLike): void { if (JSB) { // 放到原生 assertIsTrue(indices.length === this.ib.length); @@ -81,7 +81,7 @@ export class StaticVBAccessor extends BufferAccessor { private _vCount = 0; private _iCount = 0; private _id = 0; - get id () { return this._id; } + get id (): number { return this._id; } public constructor (device: Device, attributes: Attribute[], vCount?: number, iCount?: number) { super(device, attributes); @@ -92,7 +92,7 @@ export class StaticVBAccessor extends BufferAccessor { this._allocateBuffer(); } - public destroy () { + public destroy (): void { // Destroy mesh buffers and reuse free entries for (let i = 0; i < this._buffers.length; ++i) { this._buffers[i].destroy(); @@ -106,7 +106,7 @@ export class StaticVBAccessor extends BufferAccessor { super.destroy(); } - public reset () { + public reset (): void { for (let i = 0; i < this._buffers.length; ++i) { const buffer = this._buffers[i]; // Reset index buffer @@ -127,7 +127,7 @@ export class StaticVBAccessor extends BufferAccessor { return this._buffers[bid]; } - public uploadBuffers () { + public uploadBuffers (): void { for (let i = 0; i < this._buffers.length; ++i) { const firstEntry = this._freeLists[i][0]; const buffer = this._buffers[i]; @@ -139,7 +139,7 @@ export class StaticVBAccessor extends BufferAccessor { } } - public appendIndices (bufferId: number, indices: Uint16Array) { + public appendIndices (bufferId: number, indices: Uint16Array): void { const buf = this._buffers[bufferId]; const iCount = indices.length; if (iCount) { @@ -157,7 +157,7 @@ export class StaticVBAccessor extends BufferAccessor { } } - public allocateChunk (vertexCount: number, indexCount: number) { + public allocateChunk (vertexCount: number, indexCount: number): StaticVBChunk | null { const byteLength = vertexCount * this.vertexFormatBytes; let buf: MeshBuffer = null!; let freeList: IFreeEntry[]; let bid = 0; let eid = -1; let entry: IFreeEntry | null = null; @@ -200,7 +200,7 @@ export class StaticVBAccessor extends BufferAccessor { } } - public recycleChunk (chunk: StaticVBChunk) { + public recycleChunk (chunk: StaticVBChunk): void { const freeList = this._freeLists[chunk.bufferId]; const buf = this._buffers[chunk.bufferId]; let offset = chunk.vertexOffset * this.vertexFormatBytes; @@ -269,7 +269,7 @@ export class StaticVBAccessor extends BufferAccessor { } } - private _allocateChunkFromEntry (bid: number, eid: number, entry: IFreeEntry, bytes: number) { + private _allocateChunkFromEntry (bid: number, eid: number, entry: IFreeEntry, bytes: number): void { const remaining = entry.length - bytes; const offset = entry.offset + bytes; const buf = this._buffers[bid]; @@ -287,7 +287,7 @@ export class StaticVBAccessor extends BufferAccessor { } } - private _allocateBuffer () { + private _allocateBuffer (): number { // Validate length of buffer array assertID(this._buffers.length === this._freeLists.length, 9003); diff --git a/cocos/2d/renderer/stencil-manager.ts b/cocos/2d/renderer/stencil-manager.ts index 8434fbf52cc..69445e62581 100644 --- a/cocos/2d/renderer/stencil-manager.ts +++ b/cocos/2d/renderer/stencil-manager.ts @@ -91,7 +91,7 @@ export class StencilManager { * @zh 模板缓冲阶段。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get stage () { + get stage (): Stage { return this._stage; } set stage (val: Stage) { @@ -103,7 +103,16 @@ export class StencilManager { * @zh 模板缓冲样式。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - get pattern () { + get pattern (): { + stencilTest: boolean; + func: ComparisonFunc; + stencilMask: number; + writeMask: number; + failOp: StencilOp; + zFailOp: StencilOp; + passOp: StencilOp; + ref: number; + } { return this._stencilPattern; } @@ -112,7 +121,7 @@ export class StencilManager { * @zh 添加mask嵌套。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public pushMask (mask: any) { + public pushMask (mask: any): void { this._maskStack.push(mask); } @@ -121,7 +130,7 @@ export class StencilManager { * @zh 清空模板状态。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public clear (comp: UIRenderer | UIMeshRenderer) { + public clear (comp: UIRenderer | UIMeshRenderer): Stage { const isInverted = (comp.stencilStage !== Stage.ENTER_LEVEL); return isInverted ? Stage.CLEAR_INVERTED : Stage.CLEAR; } @@ -131,7 +140,7 @@ export class StencilManager { * @zh 开启模板状态。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public enableMask () { + public enableMask (): void { this.stage = Stage.ENABLED; } @@ -140,7 +149,7 @@ export class StencilManager { * @zh 退出模板状态。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public exitMask () { + public exitMask (): void { if (this._maskStack.length === 0) { // cc.errorID(9001); return; @@ -158,7 +167,7 @@ export class StencilManager { * @zh 获取写入模板缓冲的位数。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public getWriteMask () { + public getWriteMask (): number { return 1 << (this._maskStack.length - 1); } @@ -167,11 +176,11 @@ export class StencilManager { * @zh 获取退出时模板缓冲的位数。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public getExitWriteMask () { + public getExitWriteMask (): number { return 1 << this._maskStack.length; } - private getStencilRef () { + private getStencilRef (): number { let result = 0; for (let i = 0; i < this._maskStack.length; ++i) { result += (0x00000001 << i); @@ -184,7 +193,7 @@ export class StencilManager { * @zh 获取mask嵌套数量。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public getMaskStackSize () { + public getMaskStackSize (): number { return this._maskStack.length; } @@ -193,13 +202,13 @@ export class StencilManager { * @zh 重置模板状态。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public reset () { + public reset (): void { // reset stack and stage this._maskStack.length = 0; this.stage = Stage.DISABLED; } - public destroy () { + public destroy (): void { this.stencilStateMap.forEach((value, key) => { value.destroy(); }); @@ -214,7 +223,7 @@ export class StencilManager { * @zh 获取模板状态。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public getStencilStage (stage: Stage, mat?: Material) { + public getStencilStage (stage: Stage, mat?: Material): DepthStencilState { let key = 0; let depthTest = false; let depthWrite = false; @@ -269,12 +278,12 @@ export class StencilManager { * @zh 获取模板状态的哈希值。 * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public getStencilHash (stage: Stage) { + public getStencilHash (stage: Stage): number { return (stage << 8) | this._maskStack.length; } // Notice: Only children node in Mask need use this.stage - private setStateFromStage (stage) { + private setStateFromStage (stage): void { const pattern = this._stencilPattern; if (stage === Stage.DISABLED) { pattern.stencilTest = false; diff --git a/cocos/2d/renderer/vertex-format.ts b/cocos/2d/renderer/vertex-format.ts index b2b30689a70..3d8cdefa08c 100644 --- a/cocos/2d/renderer/vertex-format.ts +++ b/cocos/2d/renderer/vertex-format.ts @@ -122,7 +122,7 @@ export const vfmtPosUvTwoColor4B = [ * @param attrs All attributes of the vertex format * @returns Total components count */ -export function getComponentPerVertex (attrs: Attribute[]) { +export function getComponentPerVertex (attrs: Attribute[]): number { let count = 0; for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; @@ -139,7 +139,7 @@ export function getComponentPerVertex (attrs: Attribute[]) { * @param attrs All attributes of the vertex format * @returns Total stride */ -export function getAttributeStride (attrs: Attribute[]) { +export function getAttributeStride (attrs: Attribute[]): number { let count = 0; for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; diff --git a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts index 4622dcb0b66..3fc28ec8533 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts @@ -25,7 +25,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { System, macro, js, cclegacy } from '../../../core'; import { Filter } from '../../../asset/assets/asset-enum'; -import { Atlas } from './atlas'; +import { Atlas, DynamicAtlasTexture } from './atlas'; import { director } from '../../../game'; /** @@ -59,7 +59,7 @@ export class DynamicAtlasManager extends System { * @zh * 开启或关闭动态图集。 */ - get enabled () { + get enabled (): boolean { return this._enabled; } set enabled (value) { @@ -83,7 +83,7 @@ export class DynamicAtlasManager extends System { * @zh * 可以创建的最大图集数量。 */ - get maxAtlasCount () { + get maxAtlasCount (): number { return this._maxAtlasCount; } set maxAtlasCount (value) { @@ -97,7 +97,7 @@ export class DynamicAtlasManager extends System { * @zh * 获取当前已经创建的图集数量。 */ - get atlasCount () { + get atlasCount (): number { return this._atlases.length; } @@ -108,7 +108,7 @@ export class DynamicAtlasManager extends System { * @zh * 是否开启 textureBleeding。 */ - get textureBleeding () { + get textureBleeding (): boolean { return this._textureBleeding; } set textureBleeding (enable) { @@ -122,7 +122,7 @@ export class DynamicAtlasManager extends System { * @zh * 创建的图集的宽高。 */ - get textureSize () { + get textureSize (): number { return this._textureSize; } set textureSize (value) { @@ -136,14 +136,14 @@ export class DynamicAtlasManager extends System { * @zh * 可以添加进图集的图片的最大尺寸。 */ - get maxFrameSize () { + get maxFrameSize (): number { return this._maxFrameSize; } set maxFrameSize (value) { this._maxFrameSize = value; } - private newAtlas () { + private newAtlas (): Atlas { let atlas = this._atlases[++this._atlasIndex]; if (!atlas) { atlas = new Atlas(this._textureSize, this._textureSize); @@ -152,14 +152,14 @@ export class DynamicAtlasManager extends System { return atlas; } - private beforeSceneLoad () { + private beforeSceneLoad (): void { this.reset(); } /** * @internal */ - public init () { + public init (): void { this.enabled = !macro.CLEANUP_IMAGE_CACHE; } @@ -173,7 +173,11 @@ export class DynamicAtlasManager extends System { * @method insertSpriteFrame * @param spriteFrame the sprite frame that will be inserted in the atlas. */ - public insertSpriteFrame (spriteFrame) { + public insertSpriteFrame (spriteFrame): { + x: number; + y: number; + texture: DynamicAtlasTexture; + } | null { if (EDITOR_NOT_IN_PREVIEW) return null; if (!this._enabled || this._atlasIndex === this._maxAtlasCount || !spriteFrame || spriteFrame._original) return null; @@ -208,7 +212,7 @@ export class DynamicAtlasManager extends System { * * @method reset */ - public reset () { + public reset (): void { for (let i = 0, l = this._atlases.length; i < l; i++) { this._atlases[i].destroy(); } @@ -226,7 +230,7 @@ export class DynamicAtlasManager extends System { * @method deleteAtlasSpriteFrame * @param spriteFrame the sprite frame that will be removed from the atlas. */ - public deleteAtlasSpriteFrame (spriteFrame) { + public deleteAtlasSpriteFrame (spriteFrame): void { if (!spriteFrame._original) return; let atlas; @@ -248,7 +252,7 @@ export class DynamicAtlasManager extends System { * @method deleteAtlasTexture * @param texture the texture that will be removed from the atlas. */ - public deleteAtlasTexture (texture) { + public deleteAtlasTexture (texture): void { if (texture) { for (let i = this._atlases.length - 1; i >= 0; i--) { this._atlases[i].deleteInnerTexture(texture); @@ -272,7 +276,7 @@ export class DynamicAtlasManager extends System { * @method packToDynamicAtlas * @param frame the sprite frame that will be packed in the dynamic atlas. */ - public packToDynamicAtlas (comp, frame) { + public packToDynamicAtlas (comp, frame): void { if (EDITOR_NOT_IN_PREVIEW || !this._enabled) return; if (frame && !frame._original && frame.packable && frame.texture && frame.texture.width > 0 && frame.texture.height > 0) { diff --git a/cocos/2d/utils/dynamic-atlas/atlas.ts b/cocos/2d/utils/dynamic-atlas/atlas.ts index dd8542545dc..cb1deade823 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas.ts @@ -70,7 +70,11 @@ export class Atlas { * @method insertSpriteFrame * @param spriteFrame the sprite frame that will be inserted in the atlas. */ - public insertSpriteFrame (spriteFrame: SpriteFrame) { + public insertSpriteFrame (spriteFrame: SpriteFrame): { + x: number; + y: number; + texture: DynamicAtlasTexture; + } | null { const rect = spriteFrame.rect; // Todo:No renderTexture const texture = spriteFrame.texture as Texture2D; @@ -151,7 +155,7 @@ export class Atlas { * @method deleteAtlasTexture * @param texture the texture that will be removed from the atlas. */ - public deleteInnerTexture (texture: Texture2D) { + public deleteInnerTexture (texture: Texture2D): void { if (texture && this._innerTextureInfos[texture.getId()]) { delete this._innerTextureInfos[texture.getId()]; this._count--; @@ -167,7 +171,7 @@ export class Atlas { * * @method isEmpty */ - public isEmpty () { + public isEmpty (): boolean { return this._count <= 0; } @@ -180,7 +184,7 @@ export class Atlas { * * @method reset */ - public reset () { + public reset (): void { this._x = space; this._y = space; this._nexty = space; @@ -206,7 +210,7 @@ export class Atlas { * * @method destroy */ - public destroy () { + public destroy (): void { this.reset(); this._texture.destroy(); } @@ -222,7 +226,7 @@ export class DynamicAtlasTexture extends Texture2D { * * @method initWithSize */ - public initWithSize (width: number, height: number, format: number = PixelFormat.RGBA8888) { + public initWithSize (width: number, height: number, format: number = PixelFormat.RGBA8888): void { this.reset({ width, height, @@ -242,7 +246,7 @@ export class DynamicAtlasTexture extends Texture2D { * @param {Number} x * @param {Number} y */ - public drawTextureAt (image: ImageAsset, x: number, y: number) { + public drawTextureAt (image: ImageAsset, x: number, y: number): void { const gfxTexture = this.getGFXTexture(); if (!image || !gfxTexture) { return; diff --git a/cocos/2d/utils/font-loader.ts b/cocos/2d/utils/font-loader.ts index 579de5d42fe..5ede5e34ca5 100644 --- a/cocos/2d/utils/font-loader.ts +++ b/cocos/2d/utils/font-loader.ts @@ -50,7 +50,7 @@ const _loadingFonts: IFontLoadHandle[] = []; const _timeout = 3000; // Refer to https://github.com/typekit/webfontloader/blob/master/src/core/fontwatcher.js -const useNativeCheck = (() => { +const useNativeCheck = ((): () => boolean => { let nativeCheck: boolean; return (): boolean => { if (nativeCheck === undefined) { @@ -74,7 +74,7 @@ const useNativeCheck = (() => { }; })(); -function checkFontLoaded () { +function checkFontLoaded (): void { let allFontsLoaded = true; const now = Date.now(); @@ -111,7 +111,7 @@ function checkFontLoaded () { // refer to https://github.com/typekit/webfontloader/blob/master/src/core/nativefontwatchrunner.js function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Error | null, data?: any | null) => void)): void { const loader = new Promise((resolve, reject) => { - const check = () => { + const check = (): void => { const now = Date.now(); if (now - start >= _timeout) { @@ -150,7 +150,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Er }); } -export function loadFont (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) { +export function loadFont (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { const fontFamilyName = getFontFamily(url); // Already loaded fonts if (_fontFaces[fontFamilyName]) { @@ -227,7 +227,7 @@ export function getFontFamily (fontHandle: string): string { return fontFamilyName; } -function createFont (id: string, data: string, options: Record, onComplete: ((err: Error | null, data?: TTFFont | null) => void)) { +function createFont (id: string, data: string, options: Record, onComplete: ((err: Error | null, data?: TTFFont | null) => void)): void { const out = new TTFFont(); out._nativeUrl = id; out._nativeAsset = data; diff --git a/cocos/2d/utils/html-text-parser.ts b/cocos/2d/utils/html-text-parser.ts index 6b781c3b494..2062c28f1c1 100644 --- a/cocos/2d/utils/html-text-parser.ts +++ b/cocos/2d/utils/html-text-parser.ts @@ -82,7 +82,7 @@ export class HtmlTextParser { this._specialSymbolArray.push([/'/g, '\'']); } - public parse (htmlString: string) { + public parse (htmlString: string): IHtmlTextParserResultObj[] { this._resultObjectArray.length = 0; this._stack.length = 0; @@ -124,7 +124,7 @@ export class HtmlTextParser { return this._resultObjectArray; } - private _attributeToObject (attribute: string) { + private _attributeToObject (attribute: string): IHtmlTextParserStack { attribute = attribute.trim(); const obj: IHtmlTextParserStack = {}; @@ -322,7 +322,7 @@ export class HtmlTextParser { } // find the right part of the first pair of following quotations. - private getRightQuotationIndex (remainingArgument: string) { + private getRightQuotationIndex (remainingArgument: string): number { let leftQuot = -1; let rightQuot = -1; // Skip a pair of quotations for avoiding spaces in image name are detected. @@ -342,7 +342,7 @@ export class HtmlTextParser { return rightQuot; } - private _processEventHandler (eventString: string) { + private _processEventHandler (eventString: string): Record { const obj = {}; let index = 0; let isValidTag = false; @@ -389,7 +389,7 @@ export class HtmlTextParser { return obj; } - private _addToStack (attribute: string) { + private _addToStack (attribute: string): void { const obj = this._attributeToObject(attribute); if (this._stack.length === 0) { @@ -409,7 +409,7 @@ export class HtmlTextParser { } } - private _processResult (value: string) { + private _processResult (value: string): void { if (value.length === 0) { return; } @@ -422,7 +422,7 @@ export class HtmlTextParser { } } - private _escapeSpecialSymbol (str: string) { + private _escapeSpecialSymbol (str: string): string { for (const symbolArr of this._specialSymbolArray) { const key = symbolArr[0]; const value = symbolArr[1]; diff --git a/cocos/2d/utils/text-utils.ts b/cocos/2d/utils/text-utils.ts index 625eb3869d4..b2e37614358 100644 --- a/cocos/2d/utils/text-utils.ts +++ b/cocos/2d/utils/text-utils.ts @@ -50,7 +50,7 @@ if (RUNTIME_BASED) { } } export const MIDDLE_RATIO = (BASELINE_RATIO + 1) / 2 - BASELINE_RATIO; -export function getBaselineOffset () { +export function getBaselineOffset (): number { return _BASELINE_OFFSET; } @@ -64,7 +64,7 @@ interface ICacheNode { } const pool = new js.Pool(2); -pool.get = function () { +pool.get = function (): ICacheNode { return this._get() || { key: '', value: 0, @@ -84,7 +84,7 @@ export class LRUCache { this.limit = size; } - public moveToHead (node) { + public moveToHead (node): void { node.next = this.head; node.prev = null; if (this.head) this.head.prev = node; @@ -94,7 +94,7 @@ export class LRUCache { this.datas[node.key] = node; } - public put (key, value) { + public put (key, value): void { const node = pool.get(); node!.key = key; node!.value = value; @@ -112,7 +112,7 @@ export class LRUCache { this.moveToHead(node); } - public remove (node) { + public remove (node): void { if (node.prev) { node.prev.next = node.next; } else { @@ -127,7 +127,7 @@ export class LRUCache { this.count--; } - public get (key) { + public get (key): number | null { const node = this.datas[key]; if (node) { this.remove(node); @@ -137,18 +137,18 @@ export class LRUCache { return null; } - public clear () { + public clear (): void { this.count = 0; this.datas = {}; this.head = null; this.tail = null; } - public has (key) { + public has (key): boolean { return !!this.datas[key]; } - public delete (key) { + public delete (key): void { const node = this.datas[key]; this.remove(node); } @@ -171,7 +171,7 @@ const lowSurrogateRex = /[\uDC00-\uDFFF]/; /** * @deprecated since v3.7.2, this is an engine private interface that will be removed in the future. */ -export function isUnicodeCJK (ch: string) { +export function isUnicodeCJK (ch: string): boolean { const __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/; const __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g; const __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/; @@ -182,7 +182,7 @@ export function isUnicodeCJK (ch: string) { * @deprecated since v3.7.2, this is an engine private interface that will be removed in the future. */ // Checking whether the character is a whitespace -export function isUnicodeSpace (ch: string) { +export function isUnicodeSpace (ch: string): boolean { const chCode = ch.charCodeAt(0); return ((chCode >= 9 && chCode <= 13) || chCode === 32 @@ -199,7 +199,7 @@ export function isUnicodeSpace (ch: string) { /** * @deprecated since v3.7.2, this is an engine private interface that will be removed in the future. */ -export function safeMeasureText (ctx: CanvasRenderingContext2D, string: string, desc?: string) { +export function safeMeasureText (ctx: CanvasRenderingContext2D, string: string, desc?: string): number { const font = desc || ctx.font; const key = `${font}\uD83C\uDFAE${string}`; const cache = measureCache.get(key); @@ -223,7 +223,7 @@ export function safeMeasureText (ctx: CanvasRenderingContext2D, string: string, // _safeSubstring(a, 0, 4) === '😉🚗' // _safeSubstring(a, 1, 2) === _safeSubstring(a, 1, 3) === '😉' // _safeSubstring(a, 2, 3) === _safeSubstring(a, 2, 4) === '🚗' -function _safeSubstring (targetString, startIndex, endIndex?) { +function _safeSubstring (targetString, startIndex, endIndex?): string { let newStartIndex = startIndex; let newEndIndex = endIndex; const startChar = targetString[startIndex]; @@ -248,33 +248,33 @@ function _safeSubstring (targetString, startIndex, endIndex?) { /** * @engineInternal */ -export function isEnglishWordPartAtFirst (stringToken: string) { +export function isEnglishWordPartAtFirst (stringToken: string): boolean { return FIRST_ENGLISH_REG.test(stringToken); } /** * @engineInternal */ -export function isEnglishWordPartAtLast (stringToken: string) { +export function isEnglishWordPartAtLast (stringToken: string): boolean { return LAST_ENGLISH_REG.test(stringToken); } /** * @engineInternal */ -export function getEnglishWordPartAtFirst (stringToken: string) { +export function getEnglishWordPartAtFirst (stringToken: string): RegExpExecArray | null { const result = FIRST_ENGLISH_REG.exec(stringToken); return result; } /** * @engineInternal */ -export function getEnglishWordPartAtLast (stringToken: string) { +export function getEnglishWordPartAtLast (stringToken: string): RegExpExecArray | null { const result = LAST_ENGLISH_REG.exec(stringToken); return result; } /** * @deprecated since v3.7.2, this is an engine private interface that will be removed in the future. */ -export function fragmentText (stringToken: string, allWidth: number, maxWidth: number, measureText: (string: string) => number) { +export function fragmentText (stringToken: string, allWidth: number, maxWidth: number, measureText: (string: string) => number): string[] { // check the first character const wrappedWords: string[] = []; // fast return if strArr is empty diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 9341dda232f..39b823bb07a 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -36,7 +36,7 @@ import { import { Morph } from './morph'; import { MorphRendering, createMorphRendering } from './morph-rendering'; -function getIndexStrideCtor (stride: number) { +function getIndexStrideCtor (stride: number): Uint8ArrayConstructor | Uint16ArrayConstructor | Uint32ArrayConstructor { switch (stride) { case 1: return Uint8Array; case 2: return Uint16Array; @@ -244,7 +244,7 @@ export class Mesh extends Asset { * @zh 此网格的子网格数量。 * @deprecated Please use [[renderingSubMeshes.length]] instead */ - get subMeshCount () { + get subMeshCount (): number { const renderingMesh = this.renderingSubMeshes; return renderingMesh ? renderingMesh.length : 0; } @@ -271,7 +271,7 @@ export class Mesh extends Asset { * @en The struct of the mesh * @zh 此网格的结构。 */ - get struct () { + get struct (): Mesh.IStruct { return this._struct; } @@ -279,7 +279,7 @@ export class Mesh extends Asset { * @en The actual data of the mesh * @zh 此网格的数据。 */ - get data () { + get data (): Uint8Array { return this._data; } @@ -287,7 +287,7 @@ export class Mesh extends Asset { * @en The hash of the mesh * @zh 此网格的哈希值。 */ - get hash () { + get hash (): number { // 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; @@ -297,7 +297,7 @@ export class Mesh extends Asset { * @en The index of the joint buffer of all sub meshes in the joint map buffers * @zh 所有子网格的关节索引集合 */ - get jointBufferIndices () { + get jointBufferIndices (): number[] { if (this._jointBufferIndices) { return this._jointBufferIndices; } return this._jointBufferIndices = this._struct.primitives.map((p) => p.jointMapIndex || 0); } @@ -306,7 +306,7 @@ export class Mesh extends Asset { * @en The sub meshes for rendering. Mesh could be split into different sub meshes for rendering. * @zh 此网格创建的渲染网格。 */ - public get renderingSubMeshes () { + public get renderingSubMeshes (): RenderingSubMesh[] { this.initialize(); return this._renderingSubMeshes!; } @@ -349,7 +349,7 @@ export class Mesh extends Asset { * @en complete loading callback * @zh 加载完成回调 */ - public onLoaded () { + public onLoaded (): void { this.initialize(); } @@ -357,7 +357,7 @@ export class Mesh extends Asset { * @en mesh init * @zh 网格初始化函数 */ - public initialize () { + public initialize (): void { if (this._initialized) { return; } @@ -505,7 +505,7 @@ export class Mesh extends Asset { * @param primitiveIndex @en sub mesh index @zh 子网格索引 * @param dynamicGeometry @en sub mesh geometry data @zh 子网格几何数据 */ - public updateSubMesh (primitiveIndex: number, dynamicGeometry: IDynamicGeometry) { + public updateSubMesh (primitiveIndex: number, dynamicGeometry: IDynamicGeometry): void { if (!this._struct.dynamic) { warnID(14200); return; @@ -622,7 +622,7 @@ export class Mesh extends Asset { * @en Destroy the mesh and release all related GPU resources * @zh 销毁此网格,并释放它占有的所有 GPU 资源。 */ - public destroy () { + public destroy (): boolean { this.destroyRenderingMesh(); return super.destroy(); } @@ -631,7 +631,7 @@ export class Mesh extends Asset { * @en Release all related GPU resources * @zh 释放此网格占有的所有 GPU 资源。 */ - public destroyRenderingMesh () { + public destroyRenderingMesh (): void { if (this._renderingSubMeshes) { for (let i = 0; i < this._renderingSubMeshes.length; i++) { this._renderingSubMeshes[i].destroy(); @@ -649,7 +649,7 @@ export class Mesh extends Asset { * @param data @en The new data @zh 新数据 * @deprecated Will be removed in v3.0.0, please use [[reset]] instead */ - public assign (struct: Mesh.IStruct, data: Uint8Array) { + public assign (struct: Mesh.IStruct, data: Uint8Array): void { this.reset({ struct, data, @@ -661,7 +661,7 @@ export class Mesh extends Asset { * @zh 重置此网格。 * @param info @en Mesh creation information including struct and data @zh 网格创建信息,包含结构及数据 */ - public reset (info: Mesh.ICreateInfo) { + public reset (info: Mesh.ICreateInfo): void { this.destroyRenderingMesh(); this._struct = info.struct; this._data = info.data; @@ -674,7 +674,7 @@ export class Mesh extends Asset { * @param skeleton @en skeleton data @zh 骨骼信息 * @param skeleton @en skeleton data @zh 骨骼信息 */ - public getBoneSpaceBounds (skeleton: Skeleton) { + public getBoneSpaceBounds (skeleton: Skeleton): (geometry.AABB | null)[] { if (this._boneSpaceBounds.has(skeleton.hash)) { return this._boneSpaceBounds.get(skeleton.hash)!; } @@ -1034,7 +1034,7 @@ export class Mesh extends Asset { * - 要么都需要索引绘制,要么都不需要索引绘制。 * @param mesh @en The other mesh to be validated @zh 待验证的网格 */ - public validateMergingMesh (mesh: Mesh) { + public validateMergingMesh (mesh: Mesh): boolean { // dynamic mesh is not allowed to merge. if (this._struct.dynamic || mesh._struct.dynamic) { return false; @@ -1141,7 +1141,7 @@ export class Mesh extends Asset { * @param offset @en The offset of the first attribute in the target buffer @zh 第一个属性在目标缓冲区的偏移 * @returns @en false if failed to access attribute, true otherwise @zh 是否成功拷贝 */ - public copyAttribute (primitiveIndex: number, attributeName: AttributeName, buffer: ArrayBuffer, stride: number, offset: number) { + public copyAttribute (primitiveIndex: number, attributeName: AttributeName, buffer: ArrayBuffer, stride: number, offset: number): boolean { let written = false; this._accessAttribute(primitiveIndex, attributeName, (vertexBundle, iAttribute) => { const vertexCount = vertexBundle.view.count; @@ -1191,7 +1191,7 @@ export class Mesh extends Asset { * @returns @en Return null if not found or can't read, otherwise, will create a large enough typed array to contain all indices data, * the array type will use the corresponding stride size. @zh 读取失败返回 null,否则返回索引数据 */ - public readIndices (primitiveIndex: number) { + public readIndices (primitiveIndex: number): Uint8Array | Uint16Array | Uint32Array | null { if (primitiveIndex >= this._struct.primitives.length) { return null; } @@ -1250,7 +1250,7 @@ export class Mesh extends Asset { primitiveIndex: number, attributeName: AttributeName, accessor: (vertexBundle: Mesh.IVertexBundle, iAttribute: number) => void, - ) { + ): void { if (primitiveIndex >= this._struct.primitives.length) { return; } @@ -1286,7 +1286,7 @@ export class Mesh extends Asset { * @zh 默认初始化 * @param uuid @en asset uuid @zh 资源 uuid */ - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); this.reset({ struct: { @@ -1314,17 +1314,17 @@ export class Mesh extends Asset { * @zh 获取此网格的数据是否可被存取 * @return @en whether the data of this mesh could be accessed (read or wrote) @zh 此网格的数据是否可被存取 */ - public get allowDataAccess () { + public get allowDataAccess (): boolean { return this._allowDataAccess; } - private releaseData () { + private releaseData (): void { this._data = globalEmptyMeshBuffer; } } cclegacy.Mesh = Mesh; -function getOffset (attributes: Attribute[], attributeIndex: number) { +function getOffset (attributes: Attribute[], attributeIndex: number): number { let result = 0; for (let i = 0; i < attributeIndex; ++i) { const attribute = attributes[i]; @@ -1335,54 +1335,54 @@ function getOffset (attributes: Attribute[], attributeIndex: number) { const { isLittleEndian } = sys; -function getComponentByteLength (format: Format) { +function getComponentByteLength (format: Format): number { const info = FormatInfos[format]; return info.size / info.count; } -function getReader (dataView: DataView, format: Format) { +function getReader (dataView: DataView, format: Format): ((offset: number) => number) | null { const info = FormatInfos[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); + case 1: return (offset: number): number => dataView.getUint8(offset); + case 2: return (offset: number): number => dataView.getUint16(offset, isLittleEndian); + case 4: return (offset: number): number => dataView.getUint32(offset, isLittleEndian); default: } 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 1: return (offset: number): number => dataView.getInt8(offset); + case 2: return (offset: number): number => dataView.getInt16(offset, isLittleEndian); + case 4: return (offset: number): number => dataView.getInt32(offset, isLittleEndian); default: } 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 1: return (offset: number): number => dataView.getInt8(offset); + case 2: return (offset: number): number => dataView.getInt16(offset, isLittleEndian); + case 4: return (offset: number): number => dataView.getInt32(offset, isLittleEndian); default: } 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); + case 1: return (offset: number): number => dataView.getUint8(offset); + case 2: return (offset: number): number => dataView.getUint16(offset, isLittleEndian); + case 4: return (offset: number): number => dataView.getUint32(offset, isLittleEndian); default: } break; } case FormatType.FLOAT: { - return (offset: number) => dataView.getFloat32(offset, isLittleEndian); + return (offset: number): number => dataView.getFloat32(offset, isLittleEndian); } default: } @@ -1390,49 +1390,49 @@ function getReader (dataView: DataView, format: Format) { return null; } -function getWriter (dataView: DataView, format: Format) { +function getWriter (dataView: DataView, format: Format): ((offset: number, value: number) => void) | null { const info = FormatInfos[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); + case 1: return (offset: number, value: number): void => dataView.setUint8(offset, value); + case 2: return (offset: number, value: number): void => dataView.setUint16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number): void => dataView.setUint32(offset, value, isLittleEndian); default: } 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 1: return (offset: number, value: number): void => dataView.setInt8(offset, value); + case 2: return (offset: number, value: number): void => dataView.setInt16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number): void => dataView.setInt32(offset, value, isLittleEndian); default: } 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 1: return (offset: number, value: number): void => dataView.setInt8(offset, value); + case 2: return (offset: number, value: number): void => dataView.setInt16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number): void => dataView.setInt32(offset, value, isLittleEndian); default: } 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); + case 1: return (offset: number, value: number): void => dataView.setUint8(offset, value); + case 2: return (offset: number, value: number): void => dataView.setUint16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number): void => dataView.setUint32(offset, value, isLittleEndian); default: } break; } case FormatType.FLOAT: { - return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian); + return (offset: number, value: number): void => dataView.setFloat32(offset, value, isLittleEndian); } default: } diff --git a/cocos/3d/assets/morph-rendering.ts b/cocos/3d/assets/morph-rendering.ts index 73e16027077..22dde772058 100644 --- a/cocos/3d/assets/morph-rendering.ts +++ b/cocos/3d/assets/morph-rendering.ts @@ -23,7 +23,7 @@ */ import { - AttributeName, Buffer, BufferUsageBit, Device, MemoryUsageBit, DescriptorSet, BufferInfo, FormatFeatureBit, Format, + AttributeName, Buffer, BufferUsageBit, Device, MemoryUsageBit, DescriptorSet, BufferInfo, FormatFeatureBit, Format, Texture, Sampler, } from '../../gfx'; import { Mesh } from './mesh'; import { Texture2D } from '../../asset/assets/texture-2d'; @@ -142,11 +142,11 @@ export class StdMorphRendering implements MorphRendering { subMeshInstances[iSubMesh] = this._subMeshRenderings[iSubMesh]?.createInstance() ?? null; } return { - setWeights (subMeshIndex: number, weights: number[]) { + setWeights (subMeshIndex: number, weights: number[]): void { subMeshInstances[subMeshIndex]?.setWeights(weights); }, - requiredPatches: (subMeshIndex: number) => { + requiredPatches: (subMeshIndex: number): IMacroPatch[] | null => { assertIsNonNullable(this._mesh.struct.morph); const subMeshMorph = this._mesh.struct.morph.subMeshMorphs[subMeshIndex]; const subMeshRenderingInstance = subMeshInstances[subMeshIndex]; @@ -171,11 +171,11 @@ export class StdMorphRendering implements MorphRendering { return patches; }, - adaptPipelineState: (subMeshIndex: number, descriptorSet: DescriptorSet) => { + adaptPipelineState: (subMeshIndex: number, descriptorSet: DescriptorSet): void => { subMeshInstances[subMeshIndex]?.adaptPipelineState(descriptorSet); }, - destroy: () => { + destroy: (): void => { for (const subMeshInstance of subMeshInstances) { subMeshInstance?.destroy(); } @@ -288,26 +288,31 @@ class GpuComputing implements SubMeshMorphRendering { }); } - public destroy () { + public destroy (): void { for (const attribute of this._attributes) { attribute.morphTexture.destroy(); } } - public createInstance () { + public createInstance (): { + setWeights: (weights: number[]) => void; + requiredPatches: () => IMacroPatch[]; + adaptPipelineState: (descriptorSet: DescriptorSet) => void; + destroy: () => void; + } { const morphUniforms = new MorphUniforms(this._gfxDevice, this._subMeshMorph.targets.length); morphUniforms.setMorphTextureInfo(this._textureInfo.width, this._textureInfo.height); morphUniforms.setVerticesCount(this._verticesCount); morphUniforms.commit(); return { - setWeights: (weights: number[]) => { + setWeights: (weights: number[]): void => { morphUniforms.setWeights(weights); morphUniforms.commit(); }, requiredPatches: (): IMacroPatch[] => [{ name: 'CC_MORPH_TARGET_USE_TEXTURE', value: true }], - adaptPipelineState: (descriptorSet: DescriptorSet) => { + adaptPipelineState: (descriptorSet: DescriptorSet): void => { for (const attribute of this._attributes) { let binding: number | undefined; switch (attribute.name) { @@ -326,7 +331,7 @@ class GpuComputing implements SubMeshMorphRendering { descriptorSet.update(); }, - destroy: () => { + destroy: (): void => { }, }; @@ -367,11 +372,16 @@ class CpuComputing implements SubMeshMorphRendering { /** * DO NOT use this field. */ - get data () { + get data (): { + name: string; + targets: { + displacements: Float32Array; + }[]; + }[] { return this._attributes; } - public createInstance () { + public createInstance (): CpuComputingRenderingInstance { return new CpuComputingRenderingInstance( this, this._attributes[0].targets[0].displacements.length / 3, @@ -404,7 +414,7 @@ class CpuComputingRenderingInstance implements SubMeshMorphRenderingInstance { }); } - public setWeights (weights: number[]) { + public setWeights (weights: number[]): void { for (let iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) { const myAttribute = this._attributes[iAttribute]; const valueView = myAttribute.morphTexture.valueView; @@ -440,7 +450,7 @@ class CpuComputingRenderingInstance implements SubMeshMorphRenderingInstance { ]; } - public adaptPipelineState (descriptorSet: DescriptorSet) { + public adaptPipelineState (descriptorSet: DescriptorSet): void { for (const attribute of this._attributes) { const attributeName = attribute.attributeName; let binding: number | undefined; @@ -460,7 +470,7 @@ class CpuComputingRenderingInstance implements SubMeshMorphRenderingInstance { descriptorSet.update(); } - public destroy () { + public destroy (): void { this._morphUniforms.destroy(); for (let iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) { const myAttribute = this._attributes[iAttribute]; @@ -488,36 +498,46 @@ class MorphUniforms { )); } - public destroy () { + public destroy (): void { this._remoteBuffer.destroy(); } - public get buffer () { + public get buffer (): Buffer { return this._remoteBuffer; } - public setWeights (weights: number[]) { + public setWeights (weights: number[]): void { assertIsTrue(weights.length === this._targetCount); for (let iWeight = 0; iWeight < weights.length; ++iWeight) { this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_WEIGHTS + 4 * iWeight, weights[iWeight], cclegacy.sys.isLittleEndian); } } - public setMorphTextureInfo (width: number, height: number) { + public setMorphTextureInfo (width: number, height: number): void { this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH, width, cclegacy.sys.isLittleEndian); this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT, height, cclegacy.sys.isLittleEndian); } - public setVerticesCount (count: number) { + public setVerticesCount (count: number): void { this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_VERTICES_COUNT, count, cclegacy.sys.isLittleEndian); } - public commit () { + public commit (): void { this._remoteBuffer.update(this._localBuffer.buffer); } } -function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number) { +function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number): { + width: number; + height: number; + create: () => { + readonly texture: Texture; + readonly sampler: Sampler; + readonly valueView: Float32Array; + destroy(): void; + updatePixels(): void; + }; +} { const hasFeatureFloatTexture = gfxDevice.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE; let pixelRequired: number; @@ -542,7 +562,13 @@ function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number) { return { width, height, - create: () => { + create: (): { + readonly texture: Texture; + readonly sampler: Sampler; + readonly valueView: Float32Array; + destroy(): void; + updatePixels(): void; + } => { const arrayBuffer = new ArrayBuffer(width * height * pixelBytes); const valueView = new Float32Array(arrayBuffer); const updateView = UpdateViewConstructor === Float32Array ? valueView : new UpdateViewConstructor(arrayBuffer); @@ -566,28 +592,28 @@ function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number) { /** * Gets the GFX texture. */ - get texture () { + get texture (): Texture { return textureAsset.getGFXTexture()!; }, /** * Gets the GFX sampler. */ - get sampler () { + get sampler (): Sampler { return sampler; }, /** * Value view. */ - get valueView () { + get valueView (): Float32Array { return valueView; }, /** * Destroy the texture. Release its GPU resources. */ - destroy () { + destroy (): void { textureAsset.destroy(); // Samplers allocated from `samplerLib` are not required and // should not be destroyed. @@ -597,7 +623,7 @@ function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number) { /** * Update the pixels content to `valueView`. */ - updatePixels () { + updatePixels (): void { textureAsset.uploadData(updateView); }, }; @@ -611,7 +637,7 @@ type MorphTexture = ReturnType['crea * When use vertex-texture-fetch technique, we do need `gl_vertexId` when we sample per-vertex data. * WebGL 1.0 does not have `gl_vertexId`; WebGL 2.0, however, does. */ -function enableVertexId (mesh: Mesh, subMeshIndex: number, gfxDevice: Device) { +function enableVertexId (mesh: Mesh, subMeshIndex: number, gfxDevice: Device): void { mesh.renderingSubMeshes[subMeshIndex].enableVertexIdChannel(gfxDevice); } @@ -623,7 +649,10 @@ function enableVertexId (mesh: Mesh, subMeshIndex: number, gfxDevice: Device) { * - the width is ensured to be multiple of 4. * @param nPixels Least pixel capacity. */ -function bestSizeToHavePixels (nPixels: number) { +function bestSizeToHavePixels (nPixels: number): { + width: number; + height: number; +} { if (nPixels < 5) { nPixels = 5; } diff --git a/cocos/3d/assets/skeleton.ts b/cocos/3d/assets/skeleton.ts index e3018244098..1a610f9d723 100644 --- a/cocos/3d/assets/skeleton.ts +++ b/cocos/3d/assets/skeleton.ts @@ -48,7 +48,7 @@ export class Skeleton extends Asset { * @en The path of all bones, the length always equals the length of [[bindposes]] * @zh 所有关节的路径。该数组的长度始终与 [[bindposes]] 的长度相同。 */ - get joints () { + get joints (): string[] { return this._joints; } @@ -60,7 +60,7 @@ export class Skeleton extends Asset { * @en The bind poses matrix of all bones, the length always equals the length of [[joints]] * @zh 所有关节的绑定姿势矩阵。该数组的长度始终与 [[joints]] 的长度相同。 */ - get bindposes () { + get bindposes (): Mat4[] { return this._bindposes; } @@ -72,7 +72,7 @@ export class Skeleton extends Asset { * @en Gets the inverse bind poses matrix * @zh 获取反向绑定姿势矩阵 */ - get inverseBindposes () { + get inverseBindposes (): Mat4[] { if (!this._invBindposes) { this._invBindposes = []; for (let i = 0; i < this._bindposes.length; i++) { @@ -88,7 +88,7 @@ export class Skeleton extends Asset { * @en Gets the hash of the skeleton asset * @zh 获取骨骼资源的哈希值 */ - get hash () { + get hash (): number { // hashes should already be computed offline, but if not, make one if (!this._hash) { let str = ''; @@ -105,7 +105,7 @@ export class Skeleton extends Asset { return this._hash; } - public destroy () { + public destroy (): boolean { (cclegacy.director.root?.dataPoolManager as DataPoolManager)?.releaseSkeleton(this); return super.destroy(); } @@ -115,7 +115,7 @@ export class Skeleton extends Asset { * @zh 检查当前骨骼对象是否是有效的,取决于它是否包含关节路径和绑定姿势数据。 * @returns @en Whether the skeleton is valid or not @zh 此骨骼是否有效 */ - public validate () { + public validate (): boolean { return this.joints.length > 0 && this.bindposes.length > 0; } } diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index 1cba94e26ce..c9b847fe8ba 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -42,6 +42,7 @@ import { ReflectionProbeType } from '../reflection-probe/reflection-probe-enum'; import { getPhaseID } from '../../rendering/pass-phase'; import { SubModel } from '../../render-scene/scene'; import { isEnableEffect } from '../../rendering/define'; +import type { Model } from '../../render-scene/scene'; const { property, ccclass, help, executeInEditMode, executionOrder, menu, tooltip, visible, type, formerlySerializedAs, serializable, editable, disallowAnimation } = _decorator; @@ -153,7 +154,7 @@ class ModelBakeSettings extends EventTarget { */ @group({ id: 'LightMap', name: 'LightMapSettings', displayOrder: 0 }) @editable - get bakeable () { + get bakeable (): boolean { return this._bakeable; } @@ -167,7 +168,7 @@ class ModelBakeSettings extends EventTarget { */ @group({ id: 'LightMap', name: 'LightMapSettings' }) @editable - get castShadow () { + get castShadow (): boolean { return this._castShadow; } @@ -181,7 +182,7 @@ class ModelBakeSettings extends EventTarget { */ @group({ id: 'LightMap', name: 'LightMapSettings' }) @editable - get receiveShadow () { + get receiveShadow (): boolean { return this._receiveShadow; } @@ -197,7 +198,7 @@ class ModelBakeSettings extends EventTarget { @editable @type(CCInteger) @range([0, 1024]) - get lightmapSize () { + get lightmapSize (): number { return this._lightmapSize; } @@ -212,7 +213,7 @@ class ModelBakeSettings extends EventTarget { @group({ id: 'LightProbe', name: 'LightProbeSettings', displayOrder: 1 }) @editable @type(CCBoolean) - get useLightProbe () { + get useLightProbe (): boolean { return this._useLightProbe; } @@ -228,7 +229,7 @@ class ModelBakeSettings extends EventTarget { @group({ id: 'LightProbe', name: 'LightProbeSettings' }) @editable @type(CCBoolean) - get bakeToLightProbe () { + get bakeToLightProbe (): boolean { return this._bakeToLightProbe; } @@ -242,7 +243,7 @@ class ModelBakeSettings extends EventTarget { */ @group({ id: 'ReflectionProbe', name: 'ReflectionProbeSettings', displayOrder: 2 }) @type(Enum(ReflectionProbeType)) - get reflectionProbe () { + get reflectionProbe (): ReflectionProbeType { return this._reflectionProbeType; } @@ -257,7 +258,7 @@ class ModelBakeSettings extends EventTarget { */ @group({ id: 'ReflectionProbe', name: 'ReflectionProbeSettings' }) @type(CCBoolean) - get bakeToReflectionProbe () { + get bakeToReflectionProbe (): boolean { return this._bakeToReflectionProbe; } @@ -340,7 +341,7 @@ export class MeshRenderer extends ModelRenderer { @tooltip('i18n:model.shadow_bias') @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings', displayOrder: 2 }) @disallowAnimation - get shadowBias () { + get shadowBias (): number { return this._shadowBias; } @@ -358,7 +359,7 @@ export class MeshRenderer extends ModelRenderer { @tooltip('i18n:model.shadow_normal_bias') @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings' }) @disallowAnimation - get shadowNormalBias () { + get shadowNormalBias (): number { return this._shadowNormalBias; } @@ -377,7 +378,7 @@ export class MeshRenderer extends ModelRenderer { @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings' }) @disallowAnimation @visible(false) - get shadowCastingMode () { + get shadowCastingMode (): number { return this._shadowCastingMode; } @@ -402,7 +403,7 @@ export class MeshRenderer extends ModelRenderer { * @zh 是否接收平行光光照。 * @param visibility @en direction light visibility. @zh 方向光的可见性。 */ - public onUpdateReceiveDirLight (visibility: number, forceClose = false) { + public onUpdateReceiveDirLight (visibility: number, forceClose = false): void { if (!this._model) { return; } if (forceClose) { this._model.receiveDirLight = false; @@ -422,7 +423,7 @@ export class MeshRenderer extends ModelRenderer { */ @type(ModelShadowReceivingMode) @visible(false) - get receiveShadow () { + get receiveShadow (): number { return this._shadowReceivingMode; } set receiveShadow (val) { @@ -434,7 +435,7 @@ export class MeshRenderer extends ModelRenderer { @tooltip('i18n:model.shadow_receiving_model') @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings' }) @disallowAnimation - get receiveShadowForInspector () { + get receiveShadowForInspector (): boolean { return this._shadowReceivingMode === ModelShadowReceivingMode.ON; } set receiveShadowForInspector (val: boolean) { @@ -451,7 +452,7 @@ export class MeshRenderer extends ModelRenderer { @type(Mesh) @displayOrder(1) @tooltip('i18n:model.mesh') - get mesh () { + get mesh (): Mesh | null { return this._mesh; } @@ -477,7 +478,7 @@ export class MeshRenderer extends ModelRenderer { * @en Gets the model in [[RenderScene]]. * @zh 获取渲染场景 [[RenderScene]] 中对应的模型。 */ - get model () { + get model (): Model | null { return this._model; } @@ -494,7 +495,7 @@ export class MeshRenderer extends ModelRenderer { ); }) @disallowAnimation - get enableMorph () { + get enableMorph (): boolean { return this._enableMorph; } @@ -509,7 +510,7 @@ export class MeshRenderer extends ModelRenderer { @type(CCBoolean) @tooltip('i18n:model.standard_skin_model') @disallowAnimation - get isGlobalStandardSkinObject () { + get isGlobalStandardSkinObject (): boolean { return this._enabledGlobalStandardSkinObject; } @@ -521,7 +522,7 @@ export class MeshRenderer extends ModelRenderer { /** * @engineInternal */ - public clearGlobalStandardSkinObjectFlag () { + public clearGlobalStandardSkinObjectFlag (): void { this._enabledGlobalStandardSkinObject = false; } @@ -546,7 +547,7 @@ export class MeshRenderer extends ModelRenderer { } } - public onLoad () { + public onLoad (): void { if (this._mesh) { this._mesh.initialize(); } if (!this._validateShapeWeights()) { this._initSubMeshShapesWeights(); @@ -565,7 +566,7 @@ export class MeshRenderer extends ModelRenderer { } // Redo, Undo, Prefab restore, etc. - public onRestore () { + public onRestore (): void { this._updateModels(); if (this.enabledInHierarchy) { this._attachToScene(); @@ -581,7 +582,7 @@ export class MeshRenderer extends ModelRenderer { this._updateStandardSkin(); } - public onEnable () { + public onEnable (): void { super.onEnable(); this.node.on(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this); this.node.on(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this); @@ -607,7 +608,7 @@ export class MeshRenderer extends ModelRenderer { this._attachToScene(); } - public onDisable () { + public onDisable (): void { if (this._model) { this._detachFromScene(); } @@ -618,7 +619,7 @@ export class MeshRenderer extends ModelRenderer { this.bakeSettings.off(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this); } - public onDestroy () { + public onDestroy (): void { if (this._model) { cclegacy.director.root.destroyModel(this._model); this._model = null; @@ -629,7 +630,7 @@ export class MeshRenderer extends ModelRenderer { } } - public onGeometryChanged () { + public onGeometryChanged (): void { if (this._model && this._mesh) { const meshStruct = this._mesh.struct; this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition); @@ -645,7 +646,7 @@ export class MeshRenderer extends ModelRenderer { * @param shapeIndex Index to the morph target of the sub mesh. * @returns The weight. */ - public getWeight (subMeshIndex: number, shapeIndex: number) { + public getWeight (subMeshIndex: number, shapeIndex: number): number { const { _subMeshShapesWeights: subMeshShapesWeights } = this; assertIsTrue(subMeshIndex < subMeshShapesWeights.length); const shapeWeights = this._subMeshShapesWeights[subMeshIndex]; @@ -663,7 +664,7 @@ export class MeshRenderer extends ModelRenderer { * @param weights The weights. * @param subMeshIndex Index to the sub mesh. */ - public setWeights (weights: number[], subMeshIndex: number) { + public setWeights (weights: number[], subMeshIndex: number): void { const { _subMeshShapesWeights: subMeshShapesWeights } = this; if (subMeshIndex >= subMeshShapesWeights.length) { return; @@ -688,7 +689,7 @@ export class MeshRenderer extends ModelRenderer { * @param subMeshIndex Index to the sub mesh. * @param shapeIndex Index to the shape of the sub mesh. */ - public setWeight (weight: number, subMeshIndex: number, shapeIndex: number) { + public setWeight (weight: number, subMeshIndex: number, shapeIndex: number): void { const { _subMeshShapesWeights: subMeshShapesWeights } = this; if (subMeshIndex >= subMeshShapesWeights.length) { return; @@ -701,7 +702,7 @@ export class MeshRenderer extends ModelRenderer { this._uploadSubMeshShapesWeights(subMeshIndex); } - public setInstancedAttribute (name: string, value: ArrayLike) { + public setInstancedAttribute (name: string, value: ArrayLike): void { if (!this.model) { return; } @@ -726,7 +727,7 @@ export class MeshRenderer extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateLightmap (lightmap: Texture2D|null, uOff: number, vOff: number, scale: number, lum: number) { + public _updateLightmap (lightmap: Texture2D|null, uOff: number, vOff: number, scale: number, lum: number): void { this.bakeSettings.texture = lightmap; this.bakeSettings.uvParam.x = uOff; this.bakeSettings.uvParam.y = vOff; @@ -745,7 +746,7 @@ export class MeshRenderer extends ModelRenderer { * @param cubeMap baked cubemap. * @param useDefaultTexture if the reflection probe has not been baked, is the skybox used instead. */ - public updateProbeCubemap (cubeMap: TextureCube | null) { + public updateProbeCubemap (cubeMap: TextureCube | null): void { if (this.bakeSettings.probeCubemap && this.bakeSettings.probeCubemap === cubeMap) { return; } @@ -762,7 +763,7 @@ export class MeshRenderer extends ModelRenderer { * Updat cubemap baked with reflection probes for blending. * @param cubeMap baked cubemap. */ - public updateProbeBlendCubemap (cubeMap: TextureCube | null) { + public updateProbeBlendCubemap (cubeMap: TextureCube | null): void { if (this.bakeSettings.probeBlendCubemap && this.bakeSettings.probeBlendCubemap === cubeMap) { return; } @@ -779,7 +780,7 @@ export class MeshRenderer extends ModelRenderer { * Update the reflection rendering texture. * @param planarMap render texture. */ - public updateProbePlanarMap (planarMap: Texture | null) { + public updateProbePlanarMap (planarMap: Texture | null): void { if (this.bakeSettings.probePlanarmap === planarMap) { return; } @@ -796,7 +797,7 @@ export class MeshRenderer extends ModelRenderer { * Update the data mapping of the reflection probe. * @param dataMap data mapping with data saved all reflection probe data. */ - public updateReflectionProbeDataMap (dataMap: Texture2D | null) { + public updateReflectionProbeDataMap (dataMap: Texture2D | null): void { this._reflectionProbeDataMap = dataMap; if (this.model !== null) { this.model.updateReflectionProbeDataMap(dataMap); @@ -810,7 +811,7 @@ export class MeshRenderer extends ModelRenderer { * Update the id of the reflection probe. * @param probeId probe id. */ - public updateReflectionProbeId (probeId: number) { + public updateReflectionProbeId (probeId: number): void { this._reflectionProbeId = probeId; if (this.model) { this.model.reflectionProbeId = probeId; @@ -825,7 +826,7 @@ export class MeshRenderer extends ModelRenderer { * Update the id of the reflection probe used for blending. * @param blendProbeId probe id of blend. */ - public updateReflectionProbeBlendId (blendProbeId: number) { + public updateReflectionProbeBlendId (blendProbeId: number): void { this._reflectionProbeBlendId = blendProbeId; if (this.model) { this.model.reflectionProbeBlendId = blendProbeId; @@ -840,7 +841,7 @@ export class MeshRenderer extends ModelRenderer { * Update blending weight. * @param weight blending weight. */ - public updateReflectionProbeBlendWeight (weight: number) { + public updateReflectionProbeBlendWeight (weight: number): void { this._reflectionProbeBlendWeight = weight; if (this.model) { this.model.reflectionProbeBlendWeight = weight; @@ -848,7 +849,7 @@ export class MeshRenderer extends ModelRenderer { this._onUpdateLocalReflectionProbeData(); } - protected _updateReflectionProbeTexture () { + protected _updateReflectionProbeTexture (): void { if (!this.model) return; const bakeSettings = this.bakeSettings; @@ -878,7 +879,7 @@ export class MeshRenderer extends ModelRenderer { } } - protected _updateModels () { + protected _updateModels (): void { if (!this.enabledInHierarchy) { return; } @@ -911,7 +912,7 @@ export class MeshRenderer extends ModelRenderer { } } - protected _updateReceiveDirLight () { + protected _updateReceiveDirLight (): void { if (!this._model) { return; } const scene = this.node.scene; if (!scene || !scene.renderScene) { return; } @@ -937,7 +938,7 @@ export class MeshRenderer extends ModelRenderer { } } - protected _createModel () { + protected _createModel (): void { const preferMorphOverPlain = !!this._morphInstance; // Note we only change to use `MorphModel` if // we are required to render morph and the `this._modelType` is exactly the basic `Model`. @@ -957,7 +958,7 @@ export class MeshRenderer extends ModelRenderer { } } - protected _attachToScene () { + protected _attachToScene (): void { if (!this.node.scene || !this._model) { return; } @@ -971,13 +972,13 @@ export class MeshRenderer extends ModelRenderer { /** * @engineInternal */ - public _detachFromScene () { + public _detachFromScene (): void { if (this._model && this._model.scene) { this._model.scene.removeModel(this._model); } } - protected _updateModelParams () { + protected _updateModelParams (): void { if (!this._mesh || !this._model) { return; } this.node.hasChangedFlags |= TransformBit.POSITION; this._model.transform.hasChangedFlags |= TransformBit.POSITION; @@ -999,7 +1000,7 @@ export class MeshRenderer extends ModelRenderer { this._model.enabled = true; } - protected _onUpdateLightingmap () { + protected _onUpdateLightingmap (): void { if (this.model !== null) { this.model.updateLightingmap(this.bakeSettings.texture, this.bakeSettings.uvParam); } @@ -1012,7 +1013,7 @@ export class MeshRenderer extends ModelRenderer { ]); } - protected _onUpdateLocalShadowBiasAndProbeId () { + protected _onUpdateLocalShadowBiasAndProbeId (): void { if (this.model !== null) { this.model.updateLocalShadowBias(); this.model.updateReflectionProbeId(); @@ -1026,7 +1027,7 @@ export class MeshRenderer extends ModelRenderer { ]); } - protected _onUpdateLocalReflectionProbeData () { + protected _onUpdateLocalReflectionProbeData (): void { if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) { @@ -1043,13 +1044,13 @@ export class MeshRenderer extends ModelRenderer { } } - protected _onUpdateReflectionProbeDataMap () { + protected _onUpdateReflectionProbeDataMap (): void { if (this.model !== null) { this.model.updateReflectionProbeDataMap(this._reflectionProbeDataMap); } } - protected _onMaterialModified (idx: number, material: Material | null) { + protected _onMaterialModified (idx: number, material: Material | null): void { if (!this._model || !this._model.inited) { return; } this._onRebuildPSO(idx, material || this._getBuiltinMaterial()); this._updateStandardSkin(); @@ -1058,7 +1059,7 @@ export class MeshRenderer extends ModelRenderer { /** * @engineInternal */ - public _onRebuildPSO (idx: number, material: Material) { + public _onRebuildPSO (idx: number, material: Material): void { if (!this._model || !this._model.inited) { return; } this._model.isDynamicBatching = this._isBatchingEnabled(); this._model.setSubModelMaterial(idx, material); @@ -1069,10 +1070,10 @@ export class MeshRenderer extends ModelRenderer { this._onUpdateLocalReflectionProbeData(); } - protected _onMeshChanged (old: Mesh | null) { + protected _onMeshChanged (old: Mesh | null): void { } - protected _clearMaterials () { + protected _clearMaterials (): void { if (!this._model) { return; } const subModels = this._model.subModels; for (let i = 0; i < subModels.length; ++i) { @@ -1080,27 +1081,27 @@ export class MeshRenderer extends ModelRenderer { } } - protected _getBuiltinMaterial () { + protected _getBuiltinMaterial (): Material { // classic ugly pink indicating missing material return builtinResMgr.get('missing-material'); } - protected _onVisibilityChange (val: number) { + protected _onVisibilityChange (val: number): void { if (!this._model) { return; } this._model.visFlags = val; } - protected _updateShadowBias () { + protected _updateShadowBias (): void { if (!this._model) { return; } this._model.shadowBias = this._shadowBias; } - protected _updateShadowNormalBias () { + protected _updateShadowNormalBias (): void { if (!this._model) { return; } this._model.shadowNormalBias = this._shadowNormalBias; } - protected _updateCastShadow () { + protected _updateCastShadow (): void { if (!this._model) { return; } if (this._shadowCastingMode === ModelShadowCastingMode.OFF) { this._model.castShadow = false; @@ -1113,7 +1114,7 @@ export class MeshRenderer extends ModelRenderer { } } - protected _updateReceiveShadow () { + protected _updateReceiveShadow (): void { if (!this._model) { return; } if (this._shadowReceivingMode === ModelShadowReceivingMode.OFF) { this._model.receiveShadow = false; @@ -1122,20 +1123,20 @@ export class MeshRenderer extends ModelRenderer { } } - protected onMobilityChanged () { + protected onMobilityChanged (): void { this._updateUseLightProbe(); this._updateReceiveDirLight(); } - protected onLightProbeBakingChanged () { + protected onLightProbeBakingChanged (): void { this._updateReceiveDirLight(); } - protected onUseLightProbeChanged () { + protected onUseLightProbeChanged (): void { this._updateUseLightProbe(); } - protected onReflectionProbeChanged () { + protected onReflectionProbeChanged (): void { this._updateUseReflectionProbe(); this._onUpdateLocalShadowBiasAndProbeId(); if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP @@ -1153,11 +1154,11 @@ export class MeshRenderer extends ModelRenderer { } } - protected onBakeToReflectionProbeChanged () { + protected onBakeToReflectionProbeChanged (): void { this._updateBakeToReflectionProbe(); } - protected _updateUseLightProbe () { + protected _updateUseLightProbe (): void { if (!this._model) { return; } const node = this.node; if (this._mesh && node && node.mobility === MobilityMode.Movable && this.bakeSettings.useLightProbe) { @@ -1167,7 +1168,7 @@ export class MeshRenderer extends ModelRenderer { } } - protected _isBatchingEnabled () { + protected _isBatchingEnabled (): boolean { for (let i = 0; i < this._materials.length; ++i) { const mat = this._materials[i]; if (!mat) { continue; } @@ -1179,18 +1180,18 @@ export class MeshRenderer extends ModelRenderer { return false; } - protected _updateUseReflectionProbe () { + protected _updateUseReflectionProbe (): void { if (!this._model) return; this._model.reflectionProbeType = this.bakeSettings.reflectionProbe; this._updateReflectionProbeTexture(); } - protected _updateBakeToReflectionProbe () { + protected _updateBakeToReflectionProbe (): void { if (!this._model) { return; } this._model.bakeToReflectionProbe = this.bakeSettings.bakeToReflectionProbe; } - private _watchMorphInMesh () { + private _watchMorphInMesh (): void { if (this._morphInstance) { this._morphInstance.destroy(); this._morphInstance = null; @@ -1217,7 +1218,7 @@ export class MeshRenderer extends ModelRenderer { } } - private _initSubMeshShapesWeights () { + private _initSubMeshShapesWeights (): void { const { _mesh: mesh } = this; this._subMeshShapesWeights.length = 0; @@ -1246,7 +1247,7 @@ export class MeshRenderer extends ModelRenderer { }); } - private _validateShapeWeights () { + private _validateShapeWeights (): boolean { const { _mesh: mesh, _subMeshShapesWeights: subMeshShapesWeights, @@ -1266,11 +1267,11 @@ export class MeshRenderer extends ModelRenderer { ); } - private _uploadSubMeshShapesWeights (subMeshIndex: number) { + private _uploadSubMeshShapesWeights (subMeshIndex: number): void { this._morphInstance?.setWeights(subMeshIndex, this._subMeshShapesWeights[subMeshIndex]); } - private _updateStandardSkin () { + private _updateStandardSkin (): void { const pipelineSceneData = (cclegacy.director.root as Root).pipeline.pipelineSceneData; if (this._enabledGlobalStandardSkinObject) { pipelineSceneData.standardSkinModel = this; diff --git a/cocos/3d/lights/deprecated.ts b/cocos/3d/lights/deprecated.ts index 04635276ee1..70fcfb9af29 100644 --- a/cocos/3d/lights/deprecated.ts +++ b/cocos/3d/lights/deprecated.ts @@ -61,10 +61,10 @@ replaceProperty(SpotLight.prototype, 'SpotLight.prototype', [ { name: 'luminousPower', newName: 'luminousFlux', - customGetter (this: SpotLight) { + customGetter (this: SpotLight): number { return this.luminousFlux; }, - customSetter (this: SpotLight, value: number) { + customSetter (this: SpotLight, value: number): void { this.luminousFlux = value; }, }, @@ -74,10 +74,10 @@ replaceProperty(SphereLight.prototype, 'SphereLight.prototype', [ { name: 'luminousPower', newName: 'luminousFlux', - customGetter (this: SpotLight) { + customGetter (this: SpotLight): number { return this.luminousFlux; }, - customSetter (this: SpotLight, value: number) { + customSetter (this: SpotLight, value: number): void { this.luminousFlux = value; }, }, diff --git a/cocos/3d/lights/directional-light-component.ts b/cocos/3d/lights/directional-light-component.ts index aace7848688..6f7f00e26dd 100644 --- a/cocos/3d/lights/directional-light-component.ts +++ b/cocos/3d/lights/directional-light-component.ts @@ -99,7 +99,7 @@ export class DirectionalLight extends Light { @editable @rangeMin(0) @type(CCInteger) - get illuminance () { + get illuminance (): number { const isHDR = (cclegacy.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._illuminanceHDR; @@ -128,7 +128,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 1 } }) @editable @type(CCBoolean) - get shadowEnabled () { + get shadowEnabled (): boolean { return this._shadowEnabled; } set shadowEnabled (val) { @@ -148,7 +148,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 5 } }) @editable @type(PCFType) - get shadowPcf () { + get shadowPcf (): number { return this._shadowPcf; } set shadowPcf (val) { @@ -168,7 +168,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 6 } }) @editable @type(CCFloat) - get shadowBias () { + get shadowBias (): number { return this._shadowBias; } set shadowBias (val) { @@ -188,7 +188,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 7 } }) @editable @type(CCFloat) - get shadowNormalBias () { + get shadowNormalBias (): number { return this._shadowNormalBias; } set shadowNormalBias (val) { @@ -210,7 +210,7 @@ export class DirectionalLight extends Light { @range([0.0, 1.0, 0.01]) @slide @type(CCFloat) - get shadowSaturation () { + get shadowSaturation (): number { return this._shadowSaturation; } set shadowSaturation (val) { @@ -237,7 +237,7 @@ export class DirectionalLight extends Light { @range([0.0, 2000.0, 0.1]) @slide @type(CCFloat) - get shadowDistance () { + get shadowDistance (): number { return this._shadowDistance; } set shadowDistance (val) { @@ -266,7 +266,7 @@ export class DirectionalLight extends Light { @range([0.0, 2000.0, 1.0]) @slide @type(CCFloat) - get shadowInvisibleOcclusionRange () { + get shadowInvisibleOcclusionRange (): number { return this._shadowInvisibleOcclusionRange; } set shadowInvisibleOcclusionRange (val) { @@ -285,7 +285,7 @@ export class DirectionalLight extends Light { @editable @tooltip('CSM Level') @type(CSMLevel) - get csmLevel () { + get csmLevel (): number { return this._csmLevel; } set csmLevel (val) { @@ -310,7 +310,7 @@ export class DirectionalLight extends Light { @editable @tooltip('enable CSM') @type(CCBoolean) - get enableCSM () { + get enableCSM (): boolean { return this._csmLevel > CSMLevel.LEVEL_1; } set enableCSM (val) { @@ -332,7 +332,7 @@ export class DirectionalLight extends Light { @range([0.0, 1.0, 0.01]) @slide @type(CCFloat) - get csmLayerLambda () { + get csmLayerLambda (): number { return this._csmLayerLambda; } set csmLayerLambda (val) { @@ -353,7 +353,7 @@ export class DirectionalLight extends Light { @editable @tooltip('CSM Performance Optimization Mode') @type(CSMOptimizationMode) - get csmOptimizationMode () { + get csmOptimizationMode (): number { return this._csmOptimizationMode; } set csmOptimizationMode (val) { @@ -373,7 +373,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 14 } }) @editable @type(CCBoolean) - get shadowFixedArea () { + get shadowFixedArea (): boolean { return this._shadowFixedArea; } set shadowFixedArea (val) { @@ -396,7 +396,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 15 } }) @editable @type(CCFloat) - get shadowNear () { + get shadowNear (): number { return this._shadowNear; } set shadowNear (val) { @@ -419,7 +419,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 16 } }) @editable @type(CCFloat) - get shadowFar () { + get shadowFar (): number { return this._shadowFar; } set shadowFar (val) { @@ -441,7 +441,7 @@ export class DirectionalLight extends Light { }) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 17 } }) @type(CCFloat) - get shadowOrthoSize () { + get shadowOrthoSize (): number { return this._shadowOrthoSize; } set shadowOrthoSize (val) { @@ -464,7 +464,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 19 } }) @editable @type(CCBoolean) - get csmAdvancedOptions () { + get csmAdvancedOptions (): boolean { return this._csmAdvancedOptions; } set csmAdvancedOptions (val) { @@ -485,7 +485,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 20 } }) @editable @type(CCBoolean) - get csmLayersTransition () { + get csmLayersTransition (): boolean { return this._csmLayersTransition; } set csmLayersTransition (val) { @@ -509,7 +509,7 @@ export class DirectionalLight extends Light { @range([0.0, 0.1, 0.01]) @slide @type(CCFloat) - get csmTransitionRange () { + get csmTransitionRange (): number { return this._csmTransitionRange; } set csmTransitionRange (val) { @@ -531,7 +531,7 @@ export class DirectionalLight extends Light { } } - protected _createLight () { + protected _createLight (): void { super._createLight(); this._type = scene.LightType.DIRECTIONAL; if (this._light) { @@ -558,7 +558,7 @@ export class DirectionalLight extends Light { } } - protected _onUpdateReceiveDirLight () { + protected _onUpdateReceiveDirLight (): void { if (!this._light) { return; } diff --git a/cocos/3d/lights/light-component.ts b/cocos/3d/lights/light-component.ts index d9ea8268f63..f2262f162c0 100644 --- a/cocos/3d/lights/light-component.ts +++ b/cocos/3d/lights/light-component.ts @@ -30,6 +30,7 @@ import { scene } from '../../render-scene'; import { Root } from '../../root'; import { CAMERA_DEFAULT_MASK } from '../../rendering/define'; import { Layers } from '../../scene-graph/layers'; +import type { LightType } from '../../render-scene/scene'; const _color_tmp = new Vec3(); @@ -60,7 +61,7 @@ class StaticLightSettings { * @zh 是否只在编辑器里生效。 */ @editable - get editorOnly () { + get editorOnly (): boolean { return this._editorOnly; } set editorOnly (val) { @@ -71,7 +72,7 @@ class StaticLightSettings { * @en Whether the light is baked * @zh 光源是否被烘焙 */ - get baked () { + get baked (): boolean { return this._baked; } @@ -84,7 +85,7 @@ class StaticLightSettings { * @zh 光源在烘焙时是否投射阴影。 */ @editable - get castShadow () { + get castShadow (): boolean { return this._castShadow; } @@ -155,7 +156,7 @@ export class Light extends Component { * 是否启用光源色温。 */ @tooltip('i18n:lights.use_color_temperature') - get useColorTemperature () { + get useColorTemperature (): boolean { return this._useColorTemperature; } set useColorTemperature (enable) { @@ -172,7 +173,7 @@ export class Light extends Component { @slide @range([1000, 15000, 1]) @tooltip('i18n:lights.color_temperature') - get colorTemperature () { + get colorTemperature (): number { return this._colorTemperature; } @@ -189,7 +190,7 @@ export class Light extends Component { */ @type(StaticLightSettings) @displayOrder(50) - get staticSettings () { + get staticSettings (): StaticLightSettings { return this._staticSettings; } @@ -201,7 +202,7 @@ export class Light extends Component { * @en The light type. * @zh 光源类型。 */ - get type () { + get type (): LightType { return this._type; } @@ -209,7 +210,7 @@ export class Light extends Component { * @en Whether the light is baked * @zh 光源是否被烘焙 */ - get baked () { + get baked (): boolean { return this.staticSettings.baked; } @@ -241,23 +242,23 @@ export class Light extends Component { this._lightType = scene.Light; } - public onLoad () { + public onLoad (): void { this._createLight(); } - public onEnable () { + public onEnable (): void { this._attachToScene(); } - public onDisable () { + public onDisable (): void { this._detachFromScene(); } - public onDestroy () { + public onDestroy (): void { this._destroyLight(); } - protected _createLight () { + protected _createLight (): void { if (!this._light) { this._light = (cclegacy.director.root as Root).createLight(this._lightType); } @@ -269,14 +270,14 @@ export class Light extends Component { this._light.visibility = this.visibility; } - protected _destroyLight () { + protected _destroyLight (): void { if (this._light) { cclegacy.director.root.recycleLight(this._light); this._light = null; } } - protected _attachToScene () { + protected _attachToScene (): void { this._detachFromScene(); if (this._light && !this._light.scene && this.node.scene) { const renderScene = this._getRenderScene(); @@ -303,7 +304,7 @@ export class Light extends Component { } } - protected _detachFromScene () { + protected _detachFromScene (): void { if (this._light && this._light.scene) { const renderScene = this._light.scene; switch (this._type) { @@ -329,5 +330,5 @@ export class Light extends Component { } } - protected _onUpdateReceiveDirLight () {} + protected _onUpdateReceiveDirLight (): void {} } diff --git a/cocos/3d/lights/point-light-component.ts b/cocos/3d/lights/point-light-component.ts index 66e800ac9fc..a7c501894bc 100644 --- a/cocos/3d/lights/point-light-component.ts +++ b/cocos/3d/lights/point-light-component.ts @@ -57,7 +57,7 @@ export class PointLight extends Light { @editable @rangeMin(0) @type(CCInteger) - get luminousFlux () { + get luminousFlux (): number { const isHDR = cclegacy.director.root.pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._luminanceHDR * scene.nt2lm(1.0); @@ -88,7 +88,7 @@ export class PointLight extends Light { @editable @rangeMin(0) @type(CCInteger) - get luminance () { + get luminance (): number { const isHDR = cclegacy.director.root.pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._luminanceHDR; @@ -134,7 +134,7 @@ export class PointLight extends Light { @editable @rangeMin(0) @type(CCFloat) - get range () { + get range (): number { return this._range; } set range (val) { @@ -147,7 +147,7 @@ export class PointLight extends Light { this._lightType = scene.PointLight; } - protected _createLight () { + protected _createLight (): void { super._createLight(); this._type = LightType.POINT; this.range = this._range; diff --git a/cocos/3d/lights/ranged-directional-light-component.ts b/cocos/3d/lights/ranged-directional-light-component.ts index 6dce3be6cf4..75f3b39947e 100644 --- a/cocos/3d/lights/ranged-directional-light-component.ts +++ b/cocos/3d/lights/ranged-directional-light-component.ts @@ -49,7 +49,7 @@ export class RangedDirectionalLight extends Light { @editable @rangeMin(0) @type(CCInteger) - get illuminance () { + get illuminance (): number { const isHDR = cclegacy.director.root.pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._illuminanceHDR; @@ -73,7 +73,7 @@ export class RangedDirectionalLight extends Light { this._lightType = scene.RangedDirectionalLight; } - protected _createLight () { + protected _createLight (): void { super._createLight(); this._type = LightType.RANGED_DIRECTIONAL; if (this._light) { diff --git a/cocos/3d/lights/sphere-light-component.ts b/cocos/3d/lights/sphere-light-component.ts index da52d616ada..2c04fbc0d39 100644 --- a/cocos/3d/lights/sphere-light-component.ts +++ b/cocos/3d/lights/sphere-light-component.ts @@ -61,7 +61,7 @@ export class SphereLight extends Light { @editable @rangeMin(0) @type(CCInteger) - get luminousFlux () { + get luminousFlux (): number { const isHDR = (cclegacy.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._luminanceHDR * scene.nt2lm(this._size); @@ -91,7 +91,7 @@ export class SphereLight extends Light { @editable @rangeMin(0) @type(CCInteger) - get luminance () { + get luminance (): number { const isHDR = (cclegacy.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._luminanceHDR; @@ -138,7 +138,7 @@ export class SphereLight extends Light { @slide @range([0.0, 10.0, 0.001]) @type(CCFloat) - get size () { + get size (): number { return this._size; } set size (val) { @@ -156,7 +156,7 @@ export class SphereLight extends Light { @editable @rangeMin(0) @type(CCFloat) - get range () { + get range (): number { return this._range; } set range (val) { @@ -169,7 +169,7 @@ export class SphereLight extends Light { this._lightType = scene.SphereLight; } - protected _createLight () { + protected _createLight (): void { super._createLight(); this._type = scene.LightType.SPHERE; this.size = this._size; diff --git a/cocos/3d/lights/spot-light-component.ts b/cocos/3d/lights/spot-light-component.ts index fe48c0fdb15..86b43573030 100644 --- a/cocos/3d/lights/spot-light-component.ts +++ b/cocos/3d/lights/spot-light-component.ts @@ -75,7 +75,7 @@ export class SpotLight extends Light { */ @tooltip('i18n:lights.luminous_flux') @displayOrder(-1) - get luminousFlux () { + get luminousFlux (): number { const isHDR = (cclegacy.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._luminanceHDR * scene.nt2lm(this._size); @@ -103,7 +103,7 @@ export class SpotLight extends Light { */ @tooltip('i18n:lights.luminance') @displayOrder(-1) - get luminance () { + get luminance (): number { const isHDR = (cclegacy.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._luminanceHDR; @@ -149,7 +149,7 @@ export class SpotLight extends Light { @slide @range([0.0, 10.0, 0.001]) @type(CCFloat) - get size () { + get size (): number { return this._size; } @@ -165,7 +165,7 @@ export class SpotLight extends Light { * 光源范围。 */ @tooltip('i18n:lights.range') - get range () { + get range (): number { return this._range; } @@ -183,7 +183,7 @@ export class SpotLight extends Light { @slide @range([2, 180, 1]) @tooltip('The spot light cone angle') - get spotAngle () { + get spotAngle (): number { return this._spotAngle; } @@ -201,7 +201,7 @@ export class SpotLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 1 } }) @editable @type(CCBoolean) - get shadowEnabled () { + get shadowEnabled (): boolean { return this._shadowEnabled; } set shadowEnabled (val) { @@ -220,7 +220,7 @@ export class SpotLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 2 } }) @editable @type(PCFType) - get shadowPcf () { + get shadowPcf (): number { return this._shadowPcf; } set shadowPcf (val) { @@ -239,7 +239,7 @@ export class SpotLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 3 } }) @editable @type(CCFloat) - get shadowBias () { + get shadowBias (): number { return this._shadowBias; } set shadowBias (val) { @@ -258,7 +258,7 @@ export class SpotLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 4 } }) @editable @type(CCFloat) - get shadowNormalBias () { + get shadowNormalBias (): number { return this._shadowNormalBias; } set shadowNormalBias (val) { @@ -273,7 +273,7 @@ export class SpotLight extends Light { this._lightType = scene.SpotLight; } - protected _createLight () { + protected _createLight (): void { super._createLight(); this._type = scene.LightType.SPOT; this.size = this._size; diff --git a/cocos/3d/lod/lodgroup-component.ts b/cocos/3d/lod/lodgroup-component.ts index 9ea6817560e..81aa29c3258 100644 --- a/cocos/3d/lod/lodgroup-component.ts +++ b/cocos/3d/lod/lodgroup-component.ts @@ -30,6 +30,7 @@ import { MeshRenderer } from '../framework/mesh-renderer'; import { Mesh } from '../assets/mesh'; import { scene } from '../../render-scene'; import { NodeEventType } from '../../scene-graph/node-event'; +import type { LODData } from '../../render-scene/scene'; // Ratio of objects occupying the screen const DEFAULT_SCREEN_OCCUPATION: number[] = [0.25, 0.125, 0.01]; @@ -136,7 +137,7 @@ export class LOD { * @engineInternal * @en Get internal LOD object. */ - get lodData () { return this._LODData; } + get lodData (): LODData { return this._LODData; } /** * @engineInternal @@ -202,7 +203,7 @@ export class LOD { * @zh 更新指定索引处的 [[MeshRenderer]] * @param index @en Value range from 0 to _renderers's length @zh 取值范围是 [0, _renderers数组长度] */ - public setRenderer (index: number, renderer: MeshRenderer) { + public setRenderer (index: number, renderer: MeshRenderer): void { if (index < 0 || index >= this.rendererCount) { console.error('setRenderer to LOD error, index out of range'); return; @@ -279,7 +280,7 @@ export class LODGroup extends Component { * @en Get current AABB's size. * @zh 获取当前包围盒的大小 */ - get objectSize () { return this._objectSize; } + get objectSize (): number { return this._objectSize; } /** * @en Get LOD array config. @@ -314,9 +315,9 @@ export class LODGroup extends Component { /** * @engineInternal */ - get lodGroup () { return this._lodGroup; } + get lodGroup (): scene.LODGroup { return this._lodGroup; } - private onLodModelAddedCallback () { + private onLodModelAddedCallback (): void { if (this.objectSize === 0) { this.recalculateBounds(); } @@ -412,7 +413,7 @@ export class LODGroup extends Component { * @param index, update lod at specified index. * @param lod, the updated lod. */ - public setLOD (index: number, lod: LOD) { + public setLOD (index: number, lod: LOD): void { if (index < 0 || index >= this.lodCount) { console.warn('setLOD error, index out of range'); return; @@ -427,7 +428,7 @@ export class LODGroup extends Component { * @en Recalculate the bounding box, and the interface will recalculate the localBoundaryCenter and objectSize * @zh 重新计算包围盒,该接口会更新 localBoundaryCenter 和 objectSize */ - public recalculateBounds () { + public recalculateBounds (): void { function getTransformedBoundary (c: /* center */Vec3, e: /*extents*/Vec3, transform: Mat4): [Vec3, Vec3] { let minPos: Vec3; let maxPos: Vec3; @@ -515,7 +516,7 @@ export class LODGroup extends Component { * @en reset current objectSize to 1, and recalculate screenUsagePercentage. * @zh 重置 objectSize 的大小为1,该接口会重新计算 screenUsagePercentage */ - public resetObjectSize () { + public resetObjectSize (): void { if (this.objectSize === 1.0) return; if (this.objectSize === 0) { @@ -541,11 +542,11 @@ export class LODGroup extends Component { * @en Force LOD level to use. * lodLevel @en The LOD level to use. Passing lodLevel < 0 will return to standard LOD processing. @zh 要使用的LOD层级,为负数时使用标准的处理流程 */ - public forceLOD (lodLevel: number) { + public forceLOD (lodLevel: number): void { this.lodGroup.lockLODLevels(lodLevel < 0 ? [] : [lodLevel]); } - onLoad () { + onLoad (): void { this._lodGroup.node = this.node; // objectSize maybe initialized from deserialize this._lodGroup.objectSize = this._objectSize; @@ -557,13 +558,13 @@ export class LODGroup extends Component { this._constructLOD(); } - _onRemove (comp: Component) { + _onRemove (comp: Component): void { if (comp === this) { this.onDisable(); } } - private _constructLOD () { + private _constructLOD (): void { // generate default lod for lodGroup if (this.lodCount < 1) { const size = DEFAULT_SCREEN_OCCUPATION.length; @@ -574,14 +575,14 @@ export class LODGroup extends Component { } // Redo, Undo, Prefab restore, etc. - onRestore () { + onRestore (): void { this._constructLOD(); if (this.enabledInHierarchy) { this._attachToScene(); } } - onEnable () { + onEnable (): void { this._attachToScene(); if (this.objectSize === 0) { this.recalculateBounds(); @@ -606,11 +607,11 @@ export class LODGroup extends Component { } } - onDisable () { + onDisable (): void { this._detachFromScene(); } - private _attachToScene () { + private _attachToScene (): void { if (this.node && this.node.scene) { const renderScene = this._getRenderScene(); if (this._lodGroup.scene) { @@ -620,20 +621,20 @@ export class LODGroup extends Component { } } - private _detachFromScene () { + private _detachFromScene (): void { if (this._lodGroup.scene) { this._lodGroup.scene.removeLODGroup(this._lodGroup); } } /** * @engineInternal */ - private _emitChangeNode (node: Node) { + private _emitChangeNode (node: Node): void { if (EDITOR) { EditorExtends.Node.emit('change', node.uuid, node); } } - private _updateDataToScene () { + private _updateDataToScene (): void { this._detachFromScene(); this._attachToScene(); } diff --git a/cocos/3d/misc/batch-utils.ts b/cocos/3d/misc/batch-utils.ts index 778838be018..379a90aa273 100644 --- a/cocos/3d/misc/batch-utils.ts +++ b/cocos/3d/misc/batch-utils.ts @@ -62,7 +62,7 @@ export class BatchingUtility { * @param staticModelRoot root of all the static models to be batched * @param batchedRoot the target output node */ - public static batchStaticModel (staticModelRoot: Node, batchedRoot: Node) { + public static batchStaticModel (staticModelRoot: Node, batchedRoot: Node): boolean { const models = staticModelRoot.getComponentsInChildren(MeshRenderer); if (models.length < 2) { console.error('the number of static models to batch is less than 2,it needn\'t batch.'); @@ -105,7 +105,7 @@ export class BatchingUtility { * @param staticModelRoot root of all the static models to be batched * @param batchedRoot the target output node */ - public static unbatchStaticModel (staticModelRoot: Node, batchedRoot: Node) { + public static unbatchStaticModel (staticModelRoot: Node, batchedRoot: Node): boolean { const models = staticModelRoot.getComponentsInChildren(MeshRenderer); for (let i = 0; i < models.length; i++) { const comp = models[i]; diff --git a/cocos/3d/misc/buffer-blob.ts b/cocos/3d/misc/buffer-blob.ts index ecc97efe581..d873d3c6eff 100644 --- a/cocos/3d/misc/buffer-blob.ts +++ b/cocos/3d/misc/buffer-blob.ts @@ -26,7 +26,7 @@ export class BufferBlob { private _arrayBufferOrPaddings: Array = []; private _length = 0; - public setNextAlignment (align: number) { + public setNextAlignment (align: number): void { if (align !== 0) { const remainder = this._length % align; if (remainder !== 0) { @@ -37,18 +37,18 @@ export class BufferBlob { } } - public addBuffer (arrayBuffer: ArrayBuffer) { + public addBuffer (arrayBuffer: ArrayBuffer): number { const result = this._length; this._arrayBufferOrPaddings.push(arrayBuffer); this._length += arrayBuffer.byteLength; return result; } - public getLength () { + public getLength (): number { return this._length; } - public getCombined () { + public getCombined (): ArrayBufferLike { const result = new Uint8Array(this._length); let counter = 0; this._arrayBufferOrPaddings.forEach((arrayBufferOrPadding) => { diff --git a/cocos/3d/misc/buffer.ts b/cocos/3d/misc/buffer.ts index c1d83bcfd54..80d8dfc5211 100644 --- a/cocos/3d/misc/buffer.ts +++ b/cocos/3d/misc/buffer.ts @@ -34,14 +34,14 @@ const _typeMap: Record = { [FormatType.FLOAT]: 'Float', default: 'Uint', }; -function _getDataViewType (info: FormatInfo) { +function _getDataViewType (info: FormatInfo): string { const type = _typeMap[info.type] || _typeMap.default; const bytes = info.size / info.count * 8; return `${type}${bytes}`; } // default params bahaves just like on an plain, compact Float32Array -export function writeBuffer (target: DataView, data: number[], format: Format = Format.R32F, offset = 0, stride = 0) { +export function writeBuffer (target: DataView, data: number[], format: Format = Format.R32F, offset = 0, stride = 0): void { const info = FormatInfos[format]; if (!stride) { stride = info.size; } const writer = `set${_getDataViewType(info)}`; @@ -60,7 +60,7 @@ export function writeBuffer (target: DataView, data: number[], format: Format = export function readBuffer ( target: DataView, format: Format = Format.R32F, offset = 0, length: number = target.byteLength - offset, stride = 0, out: number[] = [], -) { +): number[] { const info = FormatInfos[format]; if (!stride) { stride = info.size; } const reader = `get${_getDataViewType(info)}`; @@ -80,7 +80,7 @@ export function readBuffer ( export function mapBuffer ( target: DataView, callback: (cur: number, idx: number, view: DataView) => number, format: Format = Format.R32F, offset = 0, length: number = target.byteLength - offset, stride = 0, out?: DataView, -) { +): DataView { if (!out) { out = new DataView(target.buffer.slice(target.byteOffset, target.byteOffset + target.byteLength)); } const info = FormatInfos[format]; if (!stride) { stride = info.size; } diff --git a/cocos/3d/misc/create-mesh.ts b/cocos/3d/misc/create-mesh.ts index 3e59d58258a..dc1352344d8 100644 --- a/cocos/3d/misc/create-mesh.ts +++ b/cocos/3d/misc/create-mesh.ts @@ -41,7 +41,7 @@ const v3_1 = new Vec3(); /** * @deprecated */ -export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMeshOptions) { +export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMeshOptions): Mesh { options = options || {}; // Collect attributes and calculate length of result vertex buffer. const attributes: Attribute[] = []; @@ -276,7 +276,7 @@ function getPadding (length: number, align: number): number { return 0; } -function createDynamicMesh (primitiveIndex: number, geometry: IDynamicGeometry, out?: Mesh, options?: ICreateDynamicMeshOptions) { +function createDynamicMesh (primitiveIndex: number, geometry: IDynamicGeometry, out?: Mesh, options?: ICreateDynamicMeshOptions): Mesh { options = options || { maxSubMeshes: 1, maxSubMeshVertices: 1024, maxSubMeshIndices: 1024 }; const attributes: Attribute[] = []; @@ -418,7 +418,7 @@ export class MeshUtils { * @param options @en options of creating @zh 创建选项 * @return @en The created static mesh, which is same as out @zh 新创建的静态网格,同 out 参数 */ - static createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMeshOptions) { + static createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMeshOptions): Mesh { return createMesh(geometry, out, options); } @@ -431,7 +431,7 @@ export class MeshUtils { * @param options @en options of creating @zh 创建选项 * @return @en The created dynamic mesh, which is same as out @zh 新创建的动态网格,同 out 参数 */ - static createDynamicMesh (primitiveIndex: number, geometry: IDynamicGeometry, out?: Mesh, options?: ICreateDynamicMeshOptions) { + static createDynamicMesh (primitiveIndex: number, geometry: IDynamicGeometry, out?: Mesh, options?: ICreateDynamicMeshOptions): Mesh { return createDynamicMesh(primitiveIndex, geometry, out, options); } } diff --git a/cocos/3d/misc/ppm.ts b/cocos/3d/misc/ppm.ts index 64c19d8490a..778c5536fcb 100644 --- a/cocos/3d/misc/ppm.ts +++ b/cocos/3d/misc/ppm.ts @@ -31,6 +31,6 @@ * @param w width * @param h height */ -export function toPPM (buffer: Uint8Array, w: number, h: number) { +export function toPPM (buffer: Uint8Array, w: number, h: number): string { return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; } diff --git a/cocos/3d/misc/read-mesh.ts b/cocos/3d/misc/read-mesh.ts index e6d45c728cd..1badd79f7fe 100644 --- a/cocos/3d/misc/read-mesh.ts +++ b/cocos/3d/misc/read-mesh.ts @@ -34,7 +34,7 @@ enum _keyMap { colors = AttributeName.ATTR_COLOR, } -export function readMesh (mesh: Mesh, iPrimitive = 0) { +export function readMesh (mesh: Mesh, iPrimitive = 0): IGeometry { const out: IGeometry = { positions: [] }; const dataView = new DataView(mesh.data.buffer, mesh.data.byteOffset, mesh.data.byteLength); const struct = mesh.struct; diff --git a/cocos/3d/models/baked-skinning-model.ts b/cocos/3d/models/baked-skinning-model.ts index de66a5b0f7a..d0cd13740da 100644 --- a/cocos/3d/models/baked-skinning-model.ts +++ b/cocos/3d/models/baked-skinning-model.ts @@ -79,7 +79,7 @@ export class BakedSkinningModel extends MorphModel { this._jointsMedium = { buffer: null, jointTextureInfo, animInfo, texture: null, boundsInfo: null }; } - public destroy () { + public destroy (): void { this.uploadedAnim = undefined; // uninitialized this._jointsMedium.boundsInfo = null; if (this._jointsMedium.buffer) { @@ -91,7 +91,7 @@ export class BakedSkinningModel extends MorphModel { } // Override - public bindSkeleton (skeleton: Skeleton | null = null, skinningRoot: Node | null = null, mesh: Mesh | null = null) { + public bindSkeleton (skeleton: Skeleton | null = null, skinningRoot: Node | null = null, mesh: Mesh | null = null): void { this._skeleton = skeleton; this._mesh = mesh; if (!skeleton || !skinningRoot || !mesh) { return; } @@ -109,7 +109,7 @@ export class BakedSkinningModel extends MorphModel { } // Override - public updateTransform (stamp: number) { + public updateTransform (stamp: number): void { super.updateTransform(stamp); if (!this.uploadedAnim) { return; } @@ -123,7 +123,7 @@ export class BakedSkinningModel extends MorphModel { } // Override, update fid buffer only when visible - public updateUBOs (stamp: number) { + public updateUBOs (stamp: number): boolean { super.updateUBOs(stamp); const info = this._jointsMedium.animInfo; @@ -161,7 +161,7 @@ export class BakedSkinningModel extends MorphModel { * @param anim @en The animation clip to be uploaded to the joint texture. @zh 需要上传到骨骼贴图上的动画片段。 * @returns void */ - public uploadAnimation (anim: AnimationClip | null) { + public uploadAnimation (anim: AnimationClip | null): void { if (!this._skeleton || !this._mesh || this.uploadedAnim === anim) { return; } this.uploadedAnim = anim; const resMgr = this._dataPoolManager; @@ -178,7 +178,7 @@ export class BakedSkinningModel extends MorphModel { this._applyJointTexture(texture); } - protected _applyJointTexture (texture: IJointTextureHandle | null = null) { + protected _applyJointTexture (texture: IJointTextureHandle | null = null): void { const oldTex = this._jointsMedium.texture; if (oldTex && oldTex !== texture) { this._dataPoolManager.jointTexturePool.releaseHandle(oldTex); } this._jointsMedium.texture = texture; @@ -198,7 +198,7 @@ export class BakedSkinningModel extends MorphModel { } } - protected _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet) { + protected _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet): void { super._updateLocalDescriptors(submodelIdx, descriptorSet); const { buffer, texture, animInfo } = this._jointsMedium; descriptorSet.bindBuffer(UBOSkinningTexture.BINDING, buffer!); @@ -210,13 +210,13 @@ export class BakedSkinningModel extends MorphModel { } } - protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel) { + protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel): void { super._updateInstancedAttributes(attributes, subModel); this._instAnimInfoIdx = subModel.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO); this.updateInstancedJointTextureInfo(); } - private updateInstancedJointTextureInfo () { + private updateInstancedJointTextureInfo (): void { const { jointTextureInfo, animInfo } = this._jointsMedium; const idx = this._instAnimInfoIdx; for (let i = 0; i < this._subModels.length; i++) { diff --git a/cocos/3d/models/morph-model.ts b/cocos/3d/models/morph-model.ts index c6bdc8bde47..77ed65e07a8 100644 --- a/cocos/3d/models/morph-model.ts +++ b/cocos/3d/models/morph-model.ts @@ -64,7 +64,7 @@ export class MorphModel extends Model { * @param subMeshData @en The sub mesh data to be set @zh 需要设置的子网格 * @param mat sub material */ - public initSubModel (subModelIndex: number, subMeshData: RenderingSubMesh, material: Material) { + public initSubModel (subModelIndex: number, subMeshData: RenderingSubMesh, material: Material): void { return super.initSubModel( subModelIndex, subMeshData, @@ -72,7 +72,7 @@ export class MorphModel extends Model { ); } - public destroy () { + public destroy (): void { super.destroy(); this._morphRenderingInstance = null; } @@ -84,7 +84,7 @@ export class MorphModel extends Model { * @param material @en The material to be set @zh 需要设置的材质 * @returns void */ - public setSubModelMaterial (subModelIndex: number, material: Material) { + public setSubModelMaterial (subModelIndex: number, material: Material): void { return super.setSubModelMaterial(subModelIndex, this._launderMaterial(material)); } @@ -92,11 +92,11 @@ export class MorphModel extends Model { * Sets morph rendering instance for the model, it's managed by the MeshRenderer * @internal */ - public setMorphRendering (morphRendering: MorphRenderingInstance) { + public setMorphRendering (morphRendering: MorphRenderingInstance): void { this._morphRenderingInstance = morphRendering; } - protected _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet) { + protected _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet): void { super._updateLocalDescriptors(submodelIdx, descriptorSet); if (this._morphRenderingInstance) { @@ -104,7 +104,7 @@ export class MorphModel extends Model { } } - private _launderMaterial (material: Material) { + private _launderMaterial (material: Material): Material { return material; // if (this._usedMaterials.has(material)) { // return new MaterialInstance({ diff --git a/cocos/3d/models/skinning-model.ts b/cocos/3d/models/skinning-model.ts index efda4f0276d..3ebd761b052 100644 --- a/cocos/3d/models/skinning-model.ts +++ b/cocos/3d/models/skinning-model.ts @@ -49,7 +49,7 @@ const texturePatches: IMacroPatch[] = [ { name: 'CC_USE_REAL_TIME_JOINT_TEXTURE', value: true }, ]; -function getRelevantBuffers (outIndices: number[], outBuffers: number[], jointMaps: number[][], targetJoint: number) { +function getRelevantBuffers (outIndices: number[], outBuffers: number[], jointMaps: number[][], targetJoint: number): void { for (let i = 0; i < jointMaps.length; i++) { const idxMap = jointMaps[i]; let index = -1; @@ -105,7 +105,7 @@ export class SkinningModel extends MorphModel { this.type = ModelType.SKINNING; } - public destroy () { + public destroy (): void { this.bindSkeleton(); if (this._buffers.length) { for (let i = 0; i < this._buffers.length; i++) { @@ -126,7 +126,7 @@ export class SkinningModel extends MorphModel { * @en Abstract function for [[BakedSkinningModel]], empty implementation. * @zh 由 [[BakedSkinningModel]] 继承的空函数。 */ - public uploadAnimation () {} + public uploadAnimation () : void {} /** * @en Bind the skeleton with its skinning root node and the mesh data. @@ -136,7 +136,7 @@ export class SkinningModel extends MorphModel { * @param mesh @en The mesh @zh 蒙皮网格 * @returns void */ - public bindSkeleton (skeleton: Skeleton | null = null, skinningRoot: Node | null = null, mesh: Mesh | null = null) { + public bindSkeleton (skeleton: Skeleton | null = null, skinningRoot: Node | null = null, mesh: Mesh | null = null): void { for (let i = 0; i < this._joints.length; i++) { deleteTransform(this._joints[i].target); } @@ -168,7 +168,7 @@ export class SkinningModel extends MorphModel { * @zh 更新模型的世界矩阵和包围盒 * @param stamp @en The update time stamp @zh 更新的时间戳 */ - public updateTransform (stamp: number) { + public updateTransform (stamp: number): void { const root = this.transform; if (root.hasChangedFlags || root.isTransformDirty()) { root.updateWorldTransform(); @@ -199,7 +199,7 @@ export class SkinningModel extends MorphModel { * @param stamp @en The update time stamp @zh 更新的时间戳 * @returns @en successful or not @zh 更新是否成功 */ - public updateUBOs (stamp: number) { + public updateUBOs (stamp: number): boolean { super.updateUBOs(stamp); for (let i = 0; i < this._joints.length; i++) { const { indices, buffers, transform, bindpose } = this._joints[i]; @@ -225,7 +225,7 @@ export class SkinningModel extends MorphModel { * @param subMeshData @en The sub mesh data @zh 子网格数据 * @param mat @en The material @zh 子模型材质 */ - public initSubModel (idx: number, subMeshData: RenderingSubMesh, mat: Material) { + public initSubModel (idx: number, subMeshData: RenderingSubMesh, mat: Material): void { const original = subMeshData.vertexBuffers; const iaInfo = subMeshData.iaInfo; iaInfo.vertexBuffers = subMeshData.jointMappedBuffers; @@ -249,7 +249,7 @@ export class SkinningModel extends MorphModel { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet) { + public _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet): void { super._updateLocalDescriptors(submodelIdx, descriptorSet); const idx = this._bufferIndices![submodelIdx]; if (this._realTimeTextureMode) { @@ -260,7 +260,7 @@ export class SkinningModel extends MorphModel { } } - protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel) { + protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel): void { const pass = subModel.passes[0]; if (pass.batchingScheme !== BatchingSchemes.NONE) { // TODO(holycanvas): #9203 better to print the complete path instead of only the current node @@ -269,7 +269,7 @@ export class SkinningModel extends MorphModel { super._updateInstancedAttributes(attributes, subModel); } - private _ensureEnoughBuffers (count: number) { + private _ensureEnoughBuffers (count: number): void { if (this._buffers.length) { for (let i = 0; i < this._buffers.length; i++) { this._buffers[i].destroy(); @@ -298,7 +298,7 @@ export class SkinningModel extends MorphModel { } } - private _initRealTimeJointTexture () { + private _initRealTimeJointTexture (): void { if (this._realTimeJointTexture._textures.length) { this._realTimeJointTexture._textures.forEach((tex) => { tex.destroy(); @@ -340,7 +340,7 @@ export class SkinningModel extends MorphModel { } } - private _bindRealTimeJointTexture (idx: number, descriptorSet: DescriptorSet) { + private _bindRealTimeJointTexture (idx: number, descriptorSet: DescriptorSet): void { if (!this._realTimeTextureMode) return; const jointTexture = this._realTimeJointTexture._textures[idx]; if (jointTexture) { @@ -351,7 +351,7 @@ export class SkinningModel extends MorphModel { } } - private _updateRealTimeJointTextureBuffer () { + private _updateRealTimeJointTextureBuffer (): void { if (!this._realTimeTextureMode) return; const textures = this._realTimeJointTexture._textures; const buffers = this._realTimeJointTexture._buffers; diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index eb24ff03c03..ec66ef564b2 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -118,7 +118,7 @@ export class ReflectionProbe extends Component { } } @type(Vec3) - get size () { + get size (): Vec3 { return this._size; } @@ -163,7 +163,7 @@ export class ReflectionProbe extends Component { this.size = this._size; } } - get probeType () { + get probeType (): number { return this._probeType; } @@ -178,7 +178,7 @@ export class ReflectionProbe extends Component { this.probe.resolution = value; } - get resolution () { + get resolution (): number { return this._resolution; } @@ -191,7 +191,7 @@ export class ReflectionProbe extends Component { this._clearFlag = value; this.probe.clearFlag = this._clearFlag; } - get clearFlag () { + get clearFlag (): number { return this._clearFlag; } @@ -205,7 +205,7 @@ export class ReflectionProbe extends Component { this._backgroundColor = val; this.probe.backgroundColor = this._backgroundColor; } - get backgroundColor () { + get backgroundColor (): Color { return this._backgroundColor; } @@ -215,7 +215,7 @@ export class ReflectionProbe extends Component { */ @type(Layers.BitMask) @tooltip('i18n:camera.visibility') - get visibility () { + get visibility (): number { return this._visibility; } set visibility (val) { @@ -240,7 +240,7 @@ export class ReflectionProbe extends Component { } } } - get sourceCamera () { + get sourceCamera (): Camera { return this._sourceCamera!; } @@ -251,7 +251,7 @@ export class ReflectionProbe extends Component { @visible(function (this: ReflectionProbe) { return this.probeType === ProbeType.CUBE; }) @type(CCBoolean) @tooltip('i18n:reflection_probe.fastBake') - get fastBake () { + get fastBake (): boolean { return this._fastBake; } @@ -265,11 +265,11 @@ export class ReflectionProbe extends Component { ReflectionProbeManager.probeManager.onUpdateProbes(true); } - get cubemap () { + get cubemap (): TextureCube | null { return this._cubemap; } - get probe () { + get probe (): scene.ReflectionProbe { return this._probe!; } @@ -287,7 +287,7 @@ export class ReflectionProbe extends Component { } } - get previewSphere () { + get previewSphere (): Node | null { return this._previewSphere!; } @@ -305,16 +305,16 @@ export class ReflectionProbe extends Component { } } - get previewPlane () { + get previewPlane (): Node { return this._previewPlane!; } - public onLoad () { + public onLoad (): void { this._createProbe(); ReflectionProbeManager.probeManager.registerEvent(); } - onEnable () { + onEnable (): void { if (this._probe) { const probe = ReflectionProbeManager.probeManager.getProbeById(this._probeId); if (probe !== null && probe !== this._probe) { @@ -326,14 +326,14 @@ export class ReflectionProbe extends Component { this._probe.enable(); } } - onDisable () { + onDisable (): void { if (this._probe) { ReflectionProbeManager.probeManager.unregister(this._probe); this._probe.disable(); } } - public start () { + public start (): void { if (this._sourceCamera && this.probeType === ProbeType.PLANAR) { this.probe.renderPlanarReflection(this.sourceCamera.camera); ReflectionProbeManager.probeManager.filterModelsForPlanarReflection(); @@ -341,13 +341,13 @@ export class ReflectionProbe extends Component { ReflectionProbeManager.probeManager.updateProbeData(); } - public onDestroy () { + public onDestroy (): void { if (this.probe) { this.probe.destroy(); } } - public update (dt: number) { + public update (dt: number): void { if (!this.probe) return; if (EDITOR_NOT_IN_PREVIEW) { if (this.probeType === ProbeType.PLANAR) { @@ -384,13 +384,13 @@ export class ReflectionProbe extends Component { * @en Clear the baked cubemap. * @zh 清除烘焙的cubemap */ - public clearBakedCubemap () { + public clearBakedCubemap (): void { this.cubemap = null; ReflectionProbeManager.probeManager.updateBakedCubemap(this.probe); ReflectionProbeManager.probeManager.updatePreviewSphere(this.probe); } - private _createProbe () { + private _createProbe (): void { if (this._probeId === -1 || ReflectionProbeManager.probeManager.exists(this._probeId)) { this._probeId = ReflectionProbeManager.probeManager.getNewReflectionProbeId(); } diff --git a/cocos/3d/reflection-probe/reflection-probe-manager.ts b/cocos/3d/reflection-probe/reflection-probe-manager.ts index 610933a7f71..9b114aff0f4 100644 --- a/cocos/3d/reflection-probe/reflection-probe-manager.ts +++ b/cocos/3d/reflection-probe/reflection-probe-manager.ts @@ -65,11 +65,11 @@ export class ReflectionProbeManager { set updateForRuntime (val: boolean) { this._updateForRuntime = val; } - get updateForRuntime () { + get updateForRuntime (): boolean { return this._updateForRuntime; } - public registerEvent () { + public registerEvent (): void { if (!this._registeredEvent) { cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_UPDATE, this.onUpdateProbes, this); this._registeredEvent = true; @@ -79,7 +79,7 @@ export class ReflectionProbeManager { * @en refresh all reflection probe * @zh 刷新所有反射探针 */ - public onUpdateProbes (forceUpdate = false) { + public onUpdateProbes (forceUpdate = false): void { if (!EDITOR && !this._updateForRuntime) return; if (this._probes.length === 0) return; const scene = cclegacy.director.getScene(); @@ -100,7 +100,7 @@ export class ReflectionProbeManager { } } - public filterModelsForPlanarReflection () { + public filterModelsForPlanarReflection (): void { if (this._probes.length === 0) return; const scene = cclegacy.director.getScene(); if (!scene || !scene.renderScene) { @@ -116,7 +116,7 @@ export class ReflectionProbeManager { } } - public clearPlanarReflectionMap (probe: ReflectionProbe) { + public clearPlanarReflectionMap (probe: ReflectionProbe): void { for (const entry of this._usePlanarModels.entries()) { if (entry[1] === probe) { this._updatePlanarMapOfModel(entry[0], null, null); @@ -124,7 +124,7 @@ export class ReflectionProbeManager { } } - public register (probe: ReflectionProbe) { + public register (probe: ReflectionProbe): void { const index = this._probes.indexOf(probe); if (index === -1) { this._probes.push(probe); @@ -132,7 +132,7 @@ export class ReflectionProbeManager { } } - public unregister (probe: ReflectionProbe) { + public unregister (probe: ReflectionProbe): void { for (let i = 0; i < this._probes.length; i++) { if (this._probes[i] === probe) { const del = this._probes.splice(i, 1); @@ -155,7 +155,7 @@ export class ReflectionProbeManager { return false; } - public getNewReflectionProbeId () { + public getNewReflectionProbeId (): number { let probeId = 0; // eslint-disable-next-line no-constant-condition while (true) { @@ -180,11 +180,11 @@ export class ReflectionProbeManager { return null; } - public clearAll () { + public clearAll (): void { this._probes = []; } - public getProbeByCamera (camera: Camera) { + public getProbeByCamera (camera: Camera): ReflectionProbe | null { for (let i = 0; i < this._probes.length; i++) { if (this._probes[i].camera === camera) { return this._probes[i]; @@ -198,7 +198,7 @@ export class ReflectionProbeManager { * @zh 更新反射探针捕获的cubemap * @param probe update the texture for this probe */ - public updateBakedCubemap (probe: ReflectionProbe) { + public updateBakedCubemap (probe: ReflectionProbe): void { const models = this._getModelsByProbe(probe); if (!probe.cubemap) return; for (let i = 0; i < models.length; i++) { @@ -221,7 +221,7 @@ export class ReflectionProbeManager { * @zh 更新反射探针渲染的平面反射贴图 * @param probe update the texture for this probe */ - public updatePlanarMap (probe: ReflectionProbe, texture: Texture | null) { + public updatePlanarMap (probe: ReflectionProbe, texture: Texture | null): void { if (!probe.node || !probe.node.scene) return; const models = this._getModelsByProbe(probe); for (let i = 0; i < models.length; i++) { @@ -241,7 +241,7 @@ export class ReflectionProbeManager { * @param probe update the model for reflection probe * @engineInternal */ - public updateUsePlanarModels (model: Model) { + public updateUsePlanarModels (model: Model): void { if (!model.node || !model.worldBounds || model.reflectionProbeType !== ReflectionProbeType.PLANAR_REFLECTION) return; for (let i = 0; i < this._probes.length; i++) { const probe = this._probes[i]; @@ -277,7 +277,7 @@ export class ReflectionProbeManager { * @param model update the model for reflection probe * @engineInternal */ - public updateUseCubeModels (model: Model) { + public updateUseCubeModels (model: Model): void { if (model.node && model.worldBounds && ((model.node.layer & REFLECTION_PROBE_DEFAULT_MASK))) { model.updateWorldBound(); const nearest = this._getNearestProbe(model); @@ -309,7 +309,7 @@ export class ReflectionProbeManager { * @en Update the preview sphere of the Reflection Probe cube mode. * @zh 更新反射探针cube模式的预览球 */ - public updatePreviewSphere (probe: ReflectionProbe) { + public updatePreviewSphere (probe: ReflectionProbe): void { if (!probe || !probe.previewSphere) return; const meshRender = probe.previewSphere.getComponent(MeshRenderer); if (meshRender) { @@ -322,7 +322,7 @@ export class ReflectionProbeManager { * @en Update the preview plane of the Reflection Probe planar mode. * @zh 更新反射探针预览平面 */ - public updatePreviewPlane (probe: ReflectionProbe) { + public updatePreviewPlane (probe: ReflectionProbe): void { if (!probe || !probe.previewPlane) return; const meshRender = probe.previewPlane.getComponent(MeshRenderer); if (meshRender) { @@ -336,7 +336,7 @@ export class ReflectionProbeManager { * @en Update reflection probe data of model bind. * @zh 更新模型绑定的反射探针数据。 */ - public updateProbeData () { + public updateProbeData (): void { if (this._probes.length === 0) return; const maxId = this.getMaxProbeId(); const height = maxId + 1; @@ -416,7 +416,7 @@ export class ReflectionProbeManager { * @en get max value of probe id. * @zh 获取反射探针id的最大值。 */ - public getMaxProbeId () { + public getMaxProbeId (): number { if (this._probes.length === 0) { return -1; } @@ -430,7 +430,7 @@ export class ReflectionProbeManager { * @en Get the reflection probe used by the model. * @zh 获取模型使用的反射探针。 */ - public getUsedReflectionProbe (model: Model, planarReflection: boolean) { + public getUsedReflectionProbe (model: Model, planarReflection: boolean): ReflectionProbe | null | undefined { if (planarReflection) { if (this._usePlanarModels.has(model)) { return this._usePlanarModels.get(model); @@ -488,7 +488,7 @@ export class ReflectionProbeManager { return temp.length > 1 ? temp[1] : null; } - private _getModelsByProbe (probe: ReflectionProbe) { + private _getModelsByProbe (probe: ReflectionProbe): Model[] { const models: Model[] = []; let useModels = this._useCubeModels; if (probe.probeType === ProbeType.PLANAR) { @@ -502,7 +502,7 @@ export class ReflectionProbeManager { return models; } - private _removeDependentModels (probe: ReflectionProbe) { + private _removeDependentModels (probe: ReflectionProbe): void { for (const key of this._useCubeModels.keys()) { const p = this._useCubeModels.get(key); if (p !== undefined && p === probe) { @@ -519,7 +519,7 @@ export class ReflectionProbeManager { } } - private _updateCubemapOfModel (model: Model, probe: ReflectionProbe | null) { + private _updateCubemapOfModel (model: Model, probe: ReflectionProbe | null): void { const node = model.node; if (!node) { return; @@ -539,7 +539,7 @@ export class ReflectionProbeManager { } } } - private _updatePlanarMapOfModel (model: Model, texture: Texture | null, probe: ReflectionProbe | null) { + private _updatePlanarMapOfModel (model: Model, texture: Texture | null, probe: ReflectionProbe | null): void { const meshRender = model.node.getComponent(MeshRenderer); if (meshRender) { meshRender.updateProbePlanarMap(texture); @@ -551,7 +551,7 @@ export class ReflectionProbeManager { } } } - private _isUsedBlending (model: Model) { + private _isUsedBlending (model: Model): boolean { if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES || model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) { return true; @@ -559,7 +559,7 @@ export class ReflectionProbeManager { return false; } - private _updateBlendProbeInfo (model: Model, probe: ReflectionProbe) { + private _updateBlendProbeInfo (model: Model, probe: ReflectionProbe): void { const node = model.node; if (!node) { return; @@ -581,7 +581,7 @@ export class ReflectionProbeManager { } } - private _updateBlendCubemap (model: Model, probe: ReflectionProbe) { + private _updateBlendCubemap (model: Model, probe: ReflectionProbe): void { const node = model.node; if (!node) { return; @@ -595,7 +595,7 @@ export class ReflectionProbeManager { } } - private _calculateBlendWeight (model: Model, probe: ReflectionProbe, blendProbe: ReflectionProbe | null) { + private _calculateBlendWeight (model: Model, probe: ReflectionProbe, blendProbe: ReflectionProbe | null): number { if (blendProbe) { const d1 = Vec3.distance(model.node.worldPosition, probe.node.worldPosition); const d2 = Vec3.distance(model.node.worldPosition, blendProbe.node.worldPosition); @@ -609,7 +609,7 @@ export class ReflectionProbeManager { return 0.0; } - private _calculateBlendOfSkybox (aabb1: AABB | null, aabb2: AABB) { + private _calculateBlendOfSkybox (aabb1: AABB | null, aabb2: AABB): number { if (!aabb1) return 1.0; const aMin = new Vec3(); const aMax = new Vec3(); diff --git a/cocos/3d/skeletal-animation/data-pool-manager.ts b/cocos/3d/skeletal-animation/data-pool-manager.ts index 15f8fd616a2..8ed1381a22d 100644 --- a/cocos/3d/skeletal-animation/data-pool-manager.ts +++ b/cocos/3d/skeletal-animation/data-pool-manager.ts @@ -37,15 +37,15 @@ export class DataPoolManager { this.jointAnimationInfo = new JointAnimationInfo(device); } - public releaseSkeleton (skeleton: Skeleton) { + public releaseSkeleton (skeleton: Skeleton): void { this.jointTexturePool.releaseSkeleton(skeleton); } - public releaseAnimationClip (clip: AnimationClip) { + public releaseAnimationClip (clip: AnimationClip): void { this.jointTexturePool.releaseAnimationClip(clip); } - public clear () { + public clear (): void { this.jointTexturePool.clear(); this.jointAnimationInfo.clear(); } diff --git a/cocos/3d/skeletal-animation/skeletal-animation-blending.ts b/cocos/3d/skeletal-animation/skeletal-animation-blending.ts index 91905448d26..89151362004 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-blending.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-blending.ts @@ -48,12 +48,13 @@ export abstract class BlendStateBuffer< ); } - public destroyWriter

(writer: BlendStateWriter

) { + public destroyWriter

(writer: BlendStateWriter

): void { const internal = writer as BlendStateWriterInternal

; this.deRef(internal.node, internal.property); } - public ref

(node: Node, property: P) { + public ref

(node: Node, property: P): PropertyBlendStateTypeMap, PropertyBlendState>[P] + { let nodeBlendState = this._nodeBlendStates.get(node); if (!nodeBlendState) { nodeBlendState = this.createNodeBlendState(); @@ -63,7 +64,7 @@ export abstract class BlendStateBuffer< return propertyBlendState as PropertyBlendStateTypeMap, PropertyBlendState>[P]; } - public deRef (node: Node, property: BlendingPropertyName) { + public deRef (node: Node, property: BlendingPropertyName): void { const nodeBlendState = this._nodeBlendStates.get(node); if (!nodeBlendState) { return; @@ -74,8 +75,8 @@ export abstract class BlendStateBuffer< } } - public apply () { - this._nodeBlendStates.forEach((nodeBlendState, node) => { + public apply (): void { + this._nodeBlendStates.forEach((nodeBlendState, node): void => { nodeBlendState.apply(node); }); } @@ -106,19 +107,19 @@ class BlendStateWriterInternal

implements Runtim ) { } - get node () { + get node (): Node { return this._node; } - get property () { + get property (): P { return this._property; } - public getValue () { + public getValue (): Node[P] { return this._node[this._property]; } - public setValue (value: PropertyBlendStateTypeMap, PropertyBlendState>[P]['result']) { + public setValue (value: PropertyBlendStateTypeMap, PropertyBlendState>[P]['result']): void { const { _propertyBlendState: propertyBlendState, _host: host, @@ -162,7 +163,7 @@ class LegacyVec3PropertyBlendState implements PropertyBlendState { public result = new Vec3(); - public blend (value: Readonly, weight: number) { + public blend (value: Readonly, weight: number): void { this.accumulatedWeight = mixAveragedVec3( this.result, this.result, @@ -172,7 +173,7 @@ class LegacyVec3PropertyBlendState implements PropertyBlendState { ); } - public reset () { + public reset (): void { this.accumulatedWeight = 0.0; Vec3.zero(this.result); } @@ -185,7 +186,7 @@ class LegacyQuatPropertyBlendState implements PropertyBlendState { public result = new Quat(); - public blend (value: Readonly, weight: number) { + public blend (value: Readonly, weight: number): void { this.accumulatedWeight = mixAveragedQuat( this.result, this.result, @@ -195,14 +196,14 @@ class LegacyQuatPropertyBlendState implements PropertyBlendState { ); } - public reset () { + public reset (): void { this.accumulatedWeight = 0.0; Quat.identity(this.result); } } abstract class NodeBlendState, TQuatPropertyBlendState extends PropertyBlendState> { - get empty () { + get empty (): boolean { const { _properties: properties } = this; return !properties.position && !properties.rotation @@ -230,7 +231,7 @@ abstract class NodeBlendState[P]; } - public deRefProperty (property: BlendingPropertyName) { + public deRefProperty (property: BlendingPropertyName): void { const { _properties: properties } = this; const propertyBlendState = properties[property]; @@ -246,7 +247,7 @@ abstract class NodeBlendState { - public apply (node: Node) { + public apply (node: Node): void { const { _properties: { position, scale, rotation, eulerAngles } } = this; if (position && position.accumulatedWeight) { @@ -337,22 +338,22 @@ class LegacyNodeBlendState extends NodeBlendState) { + protected _createVec3BlendState (_currentValue: Readonly): LegacyVec3PropertyBlendState { return new LegacyVec3PropertyBlendState(); } - protected _createQuatBlendState (_currentValue: Readonly) { + protected _createQuatBlendState (_currentValue: Readonly): LegacyQuatPropertyBlendState { return new LegacyQuatPropertyBlendState(); } } export class LegacyBlendStateBuffer extends BlendStateBuffer { - protected createNodeBlendState () { + protected createNodeBlendState (): LegacyNodeBlendState { return new LegacyNodeBlendState(); } } -function mixAveragedVec3 (result: Vec3, previous: Readonly, accumulatedWeight: number, input: Readonly, weight: number) { +function mixAveragedVec3 (result: Vec3, previous: Readonly, accumulatedWeight: number, input: Readonly, weight: number): number { const newSum = accumulatedWeight + weight; if (weight === 1.0 && !accumulatedWeight) { Vec3.copy(result, input); @@ -363,7 +364,7 @@ function mixAveragedVec3 (result: Vec3, previous: Readonly, accumulatedWei return newSum; } -function mixAveragedQuat (result: Quat, previous: Readonly, accumulatedWeight: number, input: Readonly, weight: number) { +function mixAveragedQuat (result: Quat, previous: Readonly, accumulatedWeight: number, input: Readonly, weight: number): number { const newSum = accumulatedWeight + weight; if (weight === 1.0 && !accumulatedWeight) { Quat.copy(result, input); diff --git a/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts b/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts index 20d5f119ff6..142097a926e 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts @@ -50,7 +50,7 @@ export class SkelAnimDataHub { return data; } - public static destroy (clip: AnimationClip) { + public static destroy (clip: AnimationClip): void { SkelAnimDataHub.pool.delete(clip); } diff --git a/cocos/3d/skeletal-animation/skeletal-animation-state.ts b/cocos/3d/skeletal-animation/skeletal-animation-state.ts index 463188cd86c..ae2c7778406 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-state.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-state.ts @@ -69,7 +69,7 @@ export class SkeletalAnimationState extends AnimationState { this._animInfoMgr = cclegacy.director.root.dataPoolManager.jointAnimationInfo; } - public initialize (root: Node) { + public initialize (root: Node): void { if (this._curveLoaded) { return; } this._parent = root.getComponent('cc.SkeletalAnimation') as SkeletalAnimation; const baked = this._parent.useBakedAnimation; @@ -83,7 +83,7 @@ export class SkeletalAnimationState extends AnimationState { this.setUseBaked(baked); } - protected onPlay () { + protected onPlay (): void { super.onPlay(); const baked = this._parent!.useBakedAnimation; if (baked) { @@ -98,7 +98,7 @@ export class SkeletalAnimationState extends AnimationState { /** * @internal This method only friends to `SkeletalAnimation`. */ - public setUseBaked (useBaked: boolean) { + public setUseBaked (useBaked: boolean): void { if (useBaked) { this._sampleCurves = this._sampleCurvesBaked; this.duration = this._bakedDuration; @@ -119,7 +119,7 @@ export class SkeletalAnimationState extends AnimationState { * @param sockets @en The sockets need update @zh 需要重建的挂点列表 * @returns void */ - public rebuildSocketCurves (sockets: Socket[]) { + public rebuildSocketCurves (sockets: Socket[]): void { this._sockets.length = 0; if (!this._targetNode) { return; } const root = this._targetNode; @@ -169,7 +169,7 @@ export class SkeletalAnimationState extends AnimationState { } } - private _sampleCurvesBaked (time: number) { + private _sampleCurvesBaked (time: number): void { const ratio = time / this.duration; const info = this._animInfo!; const clip = this.clip; diff --git a/cocos/3d/skeletal-animation/skeletal-animation-utils.ts b/cocos/3d/skeletal-animation/skeletal-animation-utils.ts index d9a41f0757d..88dff5312f4 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-utils.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-utils.ts @@ -48,7 +48,7 @@ export function selectJointsMediumFormat (device: Device): Format { } // Linear Blending Skinning -function uploadJointDataLBS (out: Float32Array, base: number, mat: Readonly, firstBone: boolean) { +function uploadJointDataLBS (out: Float32Array, base: number, mat: Readonly, firstBone: boolean): void { out[base + 0] = mat.m00; out[base + 1] = mat.m01; out[base + 2] = mat.m02; @@ -70,7 +70,7 @@ const qt_1 = new Quat(); const v3_2 = new Vec3(); // Dual Quaternion Skinning -function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) { +function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean): void { 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); } @@ -91,7 +91,7 @@ function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBo out[base + 10] = v3_2.z; } -function roundUpTextureSize (targetLength: number, formatSize: number) { +function roundUpTextureSize (targetLength: number, formatSize: number): number { const formatScale = 4 / Math.sqrt(formatSize); return Math.ceil(Math.max(MINIMUM_JOINT_TEXTURE_SIZE * formatScale, targetLength) / 12) * 12; } @@ -156,7 +156,7 @@ export class JointTexturePool { private _chunkIdxMap = new Map(); // hash -> chunkIdx - get pixelsPerJoint () { + get pixelsPerJoint (): number { return this._pixelsPerJoint; } @@ -171,12 +171,12 @@ export class JointTexturePool { this._customPool.initialize({ format, roundUpFn: roundUpTextureSize }); } - public clear () { + public clear (): void { this._pool.destroy(); this._textureBuffers.clear(); } - public registerCustomTextureLayouts (layouts: ICustomJointTextureLayout[]) { + public registerCustomTextureLayouts (layouts: ICustomJointTextureLayout[]): void { for (let i = 0; i < layouts.length; i++) { const layout = layouts[i]; let textureLength = layout.textureLength; @@ -202,7 +202,7 @@ export class JointTexturePool { * @zh * 获取默认姿势的骨骼贴图。 */ - public getDefaultPoseTexture (skeleton: Skeleton, mesh: Mesh, skinningRoot: Node) { + public getDefaultPoseTexture (skeleton: Skeleton, mesh: Mesh, skinningRoot: Node): IJointTextureHandle | null { const hash = skeleton.hash ^ 0; // may not equal to skeleton.hash let texture: IJointTextureHandle | null = this._textureBuffers.get(hash) || null; if (texture && texture.bounds.has(mesh.hash)) { texture.refCount++; return texture; } @@ -260,7 +260,7 @@ export class JointTexturePool { * @zh * 获取指定动画片段的骨骼贴图。 */ - public getSequencePoseTexture (skeleton: Skeleton, clip: AnimationClip, mesh: Mesh, skinningRoot: Node) { + public getSequencePoseTexture (skeleton: Skeleton, clip: AnimationClip, mesh: Mesh, skinningRoot: Node): IJointTextureHandle | null { const hash = skeleton.hash ^ clip.hash; let texture: IJointTextureHandle | null = this._textureBuffers.get(hash) || null; if (texture && texture.bounds.has(mesh.hash)) { texture.refCount++; return texture; } @@ -333,7 +333,7 @@ export class JointTexturePool { return texture; } - public releaseHandle (handle: IJointTextureHandle) { + public releaseHandle (handle: IJointTextureHandle): void { if (handle.refCount > 0) { handle.refCount--; } if (!handle.refCount && handle.readyToBeDeleted) { const hash = handle.skeletonHash ^ handle.clipHash; @@ -345,7 +345,7 @@ export class JointTexturePool { } } - public releaseSkeleton (skeleton: Skeleton) { + public releaseSkeleton (skeleton: Skeleton): void { const it = this._textureBuffers.values(); let res = it.next(); while (!res.done) { @@ -363,7 +363,7 @@ export class JointTexturePool { } } - public releaseAnimationClip (clip: AnimationClip) { + public releaseAnimationClip (clip: AnimationClip): void { const it = this._textureBuffers.values(); let res = it.next(); while (!res.done) { @@ -381,7 +381,8 @@ export class JointTexturePool { } } - private _createAnimInfos (skeleton: Skeleton, clip: AnimationClip, skinningRoot: Node) { + private _createAnimInfos (skeleton: Skeleton, clip: AnimationClip, skinningRoot: Node): IInternalJointAnimInfo[] + { const animInfos: IInternalJointAnimInfo[] = []; const { joints, bindposes } = skeleton; const jointCount = joints.length; @@ -465,7 +466,7 @@ export class JointAnimationInfo { this._device = device; } - public getData (nodeID = '-1') { + public getData (nodeID = '-1'): IAnimInfo { const res = this._pool.get(nodeID); if (res) { return res; } const buffer = this._device.createBuffer(new BufferInfo( @@ -482,14 +483,14 @@ export class JointAnimationInfo { return info; } - public destroy (nodeID: string) { + public destroy (nodeID: string): void { const info = this._pool.get(nodeID); if (!info) { return; } info.buffer.destroy(); this._pool.delete(nodeID); } - public switchClip (info: IAnimInfo, clip: AnimationClip | null) { + public switchClip (info: IAnimInfo, clip: AnimationClip | null): IAnimInfo { info.currentClip = clip; info.data[0] = 0; // reset default frame 0 info.buffer.update(info.data); @@ -500,7 +501,7 @@ export class JointAnimationInfo { return info; } - public clear () { + public clear (): void { for (const info of this._pool.values()) { info.buffer.destroy(); } diff --git a/cocos/3d/skeletal-animation/skeletal-animation.ts b/cocos/3d/skeletal-animation/skeletal-animation.ts index f9a71ec4e68..62f980eb51c 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation.ts @@ -69,7 +69,7 @@ js.setClassAlias(Socket, 'cc.SkeletalAnimationComponent.Socket'); const m4_1 = new Mat4(); const m4_2 = new Mat4(); -function collectRecursively (node: Node, prefix = '', out: string[] = []) { +function collectRecursively (node: Node, prefix = '', out: string[] = []): string[] { for (let i = 0; i < node.children.length; i++) { const child = node.children[i]; if (!child) { continue; } @@ -108,7 +108,7 @@ export class SkeletalAnimation extends Animation { */ @type([Socket]) @tooltip('i18n:animation.sockets') - get sockets () { + get sockets (): Socket[] { return this._sockets; } @@ -132,7 +132,7 @@ export class SkeletalAnimation extends Animation { * 运行时动态修改此选项会在播放下一条动画片段时生效。 */ @tooltip('i18n:animation.use_baked_animation') - get useBakedAnimation () { + get useBakedAnimation (): boolean { return this._useBakedAnimation; } @@ -162,7 +162,7 @@ export class SkeletalAnimation extends Animation { @type([Socket]) protected _sockets: Socket[] = []; - public onLoad () { + public onLoad (): void { super.onLoad(); // Actively search for potential users and notify them that an animation is usable. const comps = this.node.getComponentsInChildren(SkinnedMeshRenderer); @@ -174,30 +174,30 @@ export class SkeletalAnimation extends Animation { } } - public onDestroy () { + public onDestroy (): void { super.onDestroy(); (cclegacy.director.root.dataPoolManager as DataPoolManager).jointAnimationInfo.destroy(this.node.uuid); getGlobalAnimationManager().removeSockets(this.node, this._sockets); this._removeAllUsers(); } - public onEnable () { + public onEnable (): void { super.onEnable(); this._currentBakedState?.resume(); } - public onDisable () { + public onDisable (): void { super.onDisable(); this._currentBakedState?.pause(); } - public start () { + public start (): void { this.sockets = this._sockets; this.useBakedAnimation = this._useBakedAnimation; super.start(); } - public pause () { + public pause (): void { if (!this._useBakedAnimation) { super.pause(); } else { @@ -205,7 +205,7 @@ export class SkeletalAnimation extends Animation { } } - public resume () { + public resume (): void { if (!this._useBakedAnimation) { super.resume(); } else { @@ -213,7 +213,7 @@ export class SkeletalAnimation extends Animation { } } - public stop () { + public stop (): void { if (!this._useBakedAnimation) { super.stop(); } else if (this._currentBakedState) { @@ -227,9 +227,9 @@ export class SkeletalAnimation extends Animation { * @zh 获取所有挂点的骨骼路径 * @returns @en All socket paths @zh 所有挂点的骨骼路径 */ - public querySockets () { + public querySockets (): string[] { const animPaths = (this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).joints).sort() - .reduce((acc, cur) => (cur.startsWith(`${acc[acc.length - 1]}/`) ? acc : (acc.push(cur), acc)), [] as string[])) || []; + .reduce((acc, cur): string[] => (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++) { @@ -246,7 +246,7 @@ export class SkeletalAnimation extends Animation { * @en Rebuild animations to synchronize immediately all sockets to their target node. * @zh 重建动画并立即同步所有挂点的转换矩阵到它们的目标节点上。 */ - public rebuildSocketAnimations () { + public rebuildSocketAnimations (): void { for (const socket of this._sockets) { const joint = this.node.getChildByPath(socket.path); const { target } = socket; @@ -272,7 +272,7 @@ export class SkeletalAnimation extends Animation { * @param path @en Path of the target joint. @zh 此挂点的骨骼路径。 * @returns @en The target node of the socket. @zh 挂点的目标节点 */ - public createSocket (path: string) { + public createSocket (path: string): Node | null { const socket = this._sockets.find((s) => s.path === path); if (socket) { return socket.target; } const joint = this.node.getChildByPath(path); @@ -287,7 +287,7 @@ export class SkeletalAnimation extends Animation { /** * @internal This method only friends to skinned mesh renderer. */ - public notifySkinnedMeshAdded (skinnedMeshRenderer: SkinnedMeshRenderer) { + public notifySkinnedMeshAdded (skinnedMeshRenderer: SkinnedMeshRenderer): void { const { _useBakedAnimation: useBakedAnimation } = this; const formerBound = skinnedMeshRenderer.associatedAnimation; if (formerBound) { @@ -307,7 +307,7 @@ export class SkeletalAnimation extends Animation { /** * @internal This method only friends to skinned mesh renderer. */ - public notifySkinnedMeshRemoved (skinnedMeshRenderer: SkinnedMeshRenderer) { + public notifySkinnedMeshRemoved (skinnedMeshRenderer: SkinnedMeshRenderer): void { assertIsTrue(skinnedMeshRenderer.associatedAnimation === this || skinnedMeshRenderer.associatedAnimation === null); skinnedMeshRenderer.setUseBakedAnimation(false); skinnedMeshRenderer.associatedAnimation = null; @@ -318,21 +318,21 @@ export class SkeletalAnimation extends Animation { * Get all users. * @internal This method only friends to the skeleton animation state. */ - public getUsers () { + public getUsers (): Set { return this._users; } - protected _createState (clip: AnimationClip, name?: string) { + protected _createState (clip: AnimationClip, name?: string): SkeletalAnimationState { return new SkeletalAnimationState(clip, name); } - protected _doCreateState (clip: AnimationClip, name: string) { + protected _doCreateState (clip: AnimationClip, name: string): SkeletalAnimationState { const state = super._doCreateState(clip, name) as SkeletalAnimationState; state.rebuildSocketCurves(this._sockets); return state; } - protected doPlayOrCrossFade (state: AnimationState, duration: number) { + protected doPlayOrCrossFade (state: AnimationState, duration: number): void { if (this._useBakedAnimation) { if (this._currentBakedState) { this._currentBakedState.stop(); @@ -349,7 +349,7 @@ export class SkeletalAnimation extends Animation { private _currentBakedState: SkeletalAnimationState | null = null; - private _removeAllUsers () { + private _removeAllUsers (): void { Array.from(this._users).forEach((user) => { this.notifySkinnedMeshRemoved(user); }); diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts index bf8f4a08bb2..78d86ac86b2 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts @@ -37,7 +37,7 @@ import { AttributeName, FormatInfos, Format, Type, Attribute, BufferTextureCopy import { mapBuffer, readBuffer, writeBuffer } from '../misc/buffer'; import { SkinnedMeshRenderer } from './skinned-mesh-renderer'; -const repeat = (n: number) => n - Math.floor(n); +const repeat = (n: number): number => n - Math.floor(n); const batch_id: Attribute = new Attribute(AttributeName.ATTR_BATCH_ID, Format.R32F); const batch_uv: Attribute = new Attribute(AttributeName.ATTR_BATCH_UV, Format.RG32F); const batch_extras_size = FormatInfos[batch_id.format].size + FormatInfos[batch_uv.format].size; @@ -88,7 +88,7 @@ export class SkinnedMeshUnit { Vec2.copy(this._offset, offset); } - get offset () { + get offset (): Vec2 { return this._offset; } @@ -101,7 +101,7 @@ export class SkinnedMeshUnit { Vec2.copy(this._size, size); } - get size () { + get size (): Vec2 { return this._size; } @@ -118,7 +118,8 @@ export class SkinnedMeshUnit { if (comp.skinningRoot) { getWorldTransformUntilRoot(comp.node, comp.skinningRoot, this._localTransform); } } - get copyFrom () { + get copyFrom (): SkinnedMeshRenderer | null + { return null; } } @@ -172,7 +173,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { @override @visible(false) - get mesh () { + get mesh (): Mesh | null { return super.mesh; } @@ -182,7 +183,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { @override @visible(false) - get skeleton () { + get skeleton (): Skeleton | null { return super.skeleton; } @@ -190,12 +191,12 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { super.skeleton = val; } - public onLoad () { + public onLoad (): void { super.onLoad(); this.cook(); } - public onDestroy () { + public onDestroy (): void { for (const tex in this._textures) { this._textures[tex].destroy(); } @@ -210,18 +211,18 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onMaterialModified (idx: number, material: Material | null) { + public _onMaterialModified (idx: number, material: Material | null): void { this.cookMaterials(); super._onMaterialModified(idx, this.getMaterialInstance(idx)); } - public cook () { + public cook (): void { this.cookMaterials(); this.cookSkeletons(); this.cookMeshes(); } - public cookMaterials () { + public cookMaterials (): void { if (!this._batchMaterial) { this._batchMaterial = this.getSharedMaterial(0); } @@ -258,7 +259,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { } } - public cookSkeletons () { + public cookSkeletons (): void { if (!this._skinningRoot) { console.warn('no skinning root specified!'); return; } // merge joints accordingly const joints: string[] = []; @@ -299,7 +300,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { this.skeleton = skeleton; } - public cookMeshes () { + public cookMeshes (): void { let isValid = false; for (let u = 0; u < this.units.length; u++) { const unit = this.units[u]; @@ -452,7 +453,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { this._updateModels(); } - protected cookTextures (target: Texture2D, prop: string, passIdx: number) { + protected cookTextures (target: Texture2D, prop: string, passIdx: number): void { const texImages: TexImageSource[] = []; const texImageRegions: BufferTextureCopy[] = []; const texBuffers: ArrayBufferView[] = []; @@ -483,7 +484,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { if (texImages.length > 0) { device.copyTexImagesToTexture(texImages, gfxTex, texImageRegions); } } - protected createTexture (prop: string) { + protected createTexture (prop: string): Texture2D { const tex = new Texture2D(); tex.setFilters(Filter.LINEAR, Filter.LINEAR); tex.setMipFilter(Filter.NEAREST); @@ -496,7 +497,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { return tex; } - protected resizeAtlases () { + protected resizeAtlases (): void { for (const prop in this._textures) { const tex = this._textures[prop]; tex.reset({ @@ -507,7 +508,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { } } - private _createUnitMesh (unitIdx: number, mesh: Mesh) { + private _createUnitMesh (unitIdx: number, mesh: Mesh): Mesh { // add batch ID to this temp mesh // first, update bookkeeping const newMeshStruct: Mesh.IStruct = JSON.parse(JSON.stringify(mesh.struct)); diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts index 53fc8c2fb88..ef6a78cc522 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts @@ -59,7 +59,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { * @zh 骨骼资源。 */ @type(Skeleton) - get skeleton () { + get skeleton (): Skeleton | null { return this._skeleton; } @@ -75,7 +75,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { */ @type(Node) @tooltip('i18n:model.skinning_root') - get skinningRoot () { + get skinningRoot (): Node | null { return this._skinningRoot; } @@ -86,7 +86,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { this._update(); } - get model () { + get model (): SkinningModel | BakedSkinningModel | null { return this._model as SkinningModel | BakedSkinningModel | null; } @@ -101,12 +101,12 @@ export class SkinnedMeshRenderer extends MeshRenderer { this._modelType = BakedSkinningModel; } - public onLoad () { + public onLoad (): void { super.onLoad(); this._tryBindAnimation(); } - public onDestroy () { + public onDestroy (): void { if (this.associatedAnimation) { this.associatedAnimation.notifySkinnedMeshRemoved(this); assertIsTrue(this.associatedAnimation === null); @@ -115,7 +115,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { super.onDestroy(); } - public uploadAnimation (clip: AnimationClip | null) { + public uploadAnimation (clip: AnimationClip | null): void { this._clip = clip; if (this.model && this.model.uploadAnimation) { this.model.uploadAnimation(clip); @@ -126,7 +126,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { * Set if bake mode should be used. * @internal This method only friends to skeletal animation component. */ - public setUseBakedAnimation (val = true, force = false) { + public setUseBakedAnimation (val = true, force = false): void { const modelType = val ? BakedSkinningModel : SkinningModel; if (!force && this._modelType === modelType) { return; } this._modelType = modelType; @@ -144,19 +144,19 @@ export class SkinnedMeshRenderer extends MeshRenderer { } } - public setMaterial (material: Material | null, index: number) { + public setMaterial (material: Material | null, index: number): void { super.setMaterial(material, index); if (this._modelType === SkinningModel) { this.getMaterialInstance(index); } } - protected _updateModelParams () { + protected _updateModelParams (): void { this._update(); // should bind skeleton before super create pso super._updateModelParams(); } - private _tryBindAnimation () { + private _tryBindAnimation (): void { const { _skinningRoot: skinningRoot } = this; if (!skinningRoot) { return; @@ -181,7 +181,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { } } - private _update () { + private _update (): void { if (this.model) { this.model.bindSkeleton(this._skeleton, this._skinningRoot, this._mesh); if (this.model.uploadAnimation) { this.model.uploadAnimation(this._clip); } diff --git a/cocos/animation/animation-clip.ts b/cocos/animation/animation-clip.ts index a40293ef47d..3854de50d4b 100644 --- a/cocos/animation/animation-clip.ts +++ b/cocos/animation/animation-clip.ts @@ -109,7 +109,7 @@ export class AnimationClip extends Asset { * const clip = AnimationClip.createWithSpriteFrames(spriteFrames, 10); * ``` */ - public static createWithSpriteFrames (spriteFrames: SpriteFrame[], sample: number) { + public static createWithSpriteFrames (spriteFrames: SpriteFrame[], sample: number): AnimationClip { const clip = new AnimationClip(); clip.sample = sample || clip.sample; clip.duration = spriteFrames.length / clip.sample; @@ -156,7 +156,7 @@ export class AnimationClip extends Asset { * @zh 动画的周期。 * @en Animation duration. */ - get duration () { + get duration (): number { return this._duration; } @@ -170,7 +170,7 @@ export class AnimationClip extends Asset { * @zh * 获取此动画中的轨道数量。 */ - get tracksCount () { + get tracksCount (): number { return this._tracks.length; } @@ -184,7 +184,7 @@ export class AnimationClip extends Asset { return this._tracks; } - get hash () { + get hash (): number { // hashes should already be computed offline, but if not, make one if (this._hash) { return this._hash; } // Only hash exotic animations(including skeletal animations imported from model file). @@ -197,7 +197,8 @@ export class AnimationClip extends Asset { * @zh 动画包含的事件数据。 * @en Associated event data. */ - get events () { + get events (): AnimationClip.IEvent[] + { return this._events; } @@ -231,7 +232,7 @@ export class AnimationClip extends Asset { }; } - get [exoticAnimationTag] () { + get [exoticAnimationTag] (): ExoticAnimation | null { return this._exoticAnimation; } @@ -243,7 +244,7 @@ export class AnimationClip extends Asset { * Gets if this animation clip contains additive animation. * @experimental */ - get isAdditive_experimental () { + get isAdditive_experimental (): boolean { return this._additiveSettings.enabled; } @@ -251,11 +252,11 @@ export class AnimationClip extends Asset { * Accesses the additive animation settings. * @internal */ - get [additiveSettingsTag] () { + get [additiveSettingsTag] (): AdditiveSettings { return this._additiveSettings; } - public onLoaded () { + public onLoaded (): void { this.frameRate = this.sample; this.events = this._events; } @@ -267,7 +268,7 @@ export class AnimationClip extends Asset { * 获取此动画所有轨道占据的时间范围。 * @returns The time range. */ - public range () { + public range (): Range { const range: Range = { min: Infinity, max: -Infinity }; const { _tracks: tracks } = this; const nTracks = tracks.length; @@ -288,7 +289,7 @@ export class AnimationClip extends Asset { * @param index Index to the track. * @returns The track. */ - public getTrack (index: number) { + public getTrack (index: number): Track { return this._tracks[index]; } @@ -300,7 +301,7 @@ export class AnimationClip extends Asset { * @param track The track. * @returns Index to the track. */ - public addTrack (track: Track) { + public addTrack (track: Track): number { const index = this._tracks.length; this._tracks.push(track); return index; @@ -313,7 +314,7 @@ export class AnimationClip extends Asset { * 移除此动画中的指定轨道。 * @param index Index to the track. */ - public removeTrack (index: number) { + public removeTrack (index: number): void { this._tracks.splice(index, 1); } @@ -323,7 +324,7 @@ export class AnimationClip extends Asset { * @zh * 移除此动画的所有轨道。 */ - public clearTracks () { + public clearTracks (): void { this._tracks.length = 0; } @@ -331,7 +332,7 @@ export class AnimationClip extends Asset { * Returns if this clip has any event. * @internal Do not use this in your code. */ - public containsAnyEvent () { + public containsAnyEvent (): boolean { return this._events.length !== 0; } @@ -340,7 +341,7 @@ export class AnimationClip extends Asset { * @param targetNode Target node used to fire events. * @internal Do not use this in your code. */ - public createEventEvaluator (targetNode: Node) { + public createEventEvaluator (targetNode: Node): EventEvaluator { return new EventEvaluator( targetNode, this._runtimeEvents.ratios, @@ -353,7 +354,7 @@ export class AnimationClip extends Asset { * Returns if this clip has any embedded player. * @internal Do not use this in your code. */ - public containsAnyEmbeddedPlayer () { + public containsAnyEmbeddedPlayer (): boolean { return this._embeddedPlayers.length !== 0; } @@ -362,7 +363,7 @@ export class AnimationClip extends Asset { * @param targetNode Target node. * @internal Do not use this in your code. */ - public createEmbeddedPlayerEvaluator (targetNode: Node) { + public createEmbeddedPlayerEvaluator (targetNode: Node): EmbeddedPlayerEvaluation { return new EmbeddedPlayerEvaluation( this._embeddedPlayers, targetNode, @@ -375,7 +376,7 @@ export class AnimationClip extends Asset { * @returns The evaluator. * @internal Do not use this in your code. */ - public createEvaluator (context: AnimationClipEvalContext) { + public createEvaluator (context: AnimationClipEvalContext): AnimationClipEvaluation { const { target, } = context; @@ -407,7 +408,7 @@ export class AnimationClip extends Asset { return this._createEvalWithBinder(target, binder, context.rootMotion); } - public destroy () { + public destroy (): boolean { if (cclegacy.director.root?.dataPoolManager) { (cclegacy.director.root.dataPoolManager).releaseAnimationClip(this); } @@ -495,7 +496,7 @@ export class AnimationClip extends Asset { * @param refine How to decide the type on specified path. * @internal DO NOT USE THIS IN YOUR CODE. */ - public upgradeUntypedTracks (refine: UntypedTrackRefine) { + public upgradeUntypedTracks (refine: UntypedTrackRefine): void { const newTracks: Track[] = []; const removals: Track[] = []; const { _tracks: tracks } = this; @@ -521,7 +522,7 @@ export class AnimationClip extends Asset { /** * @internal Export for test. */ - public [searchForRootBonePathSymbol] () { + public [searchForRootBonePathSymbol] (): string { return this._searchForRootBonePath(); } @@ -535,7 +536,7 @@ export class AnimationClip extends Asset { * @en Frame keys referenced by curves. * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ - get keys () { + get keys (): number[][] { return this._getLegacyData().keys; } @@ -549,7 +550,7 @@ export class AnimationClip extends Asset { * @en Curves this animation contains. * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ - get curves () { + get curves (): legacy.LegacyClipCurve[] { this._legacyDataDirty = true; return this._getLegacyData().curves; } @@ -561,7 +562,7 @@ export class AnimationClip extends Asset { /** * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ - get commonTargets () { + get commonTargets (): legacy.LegacyCommonTarget[] { return this._getLegacyData().commonTargets; } @@ -577,14 +578,14 @@ export class AnimationClip extends Asset { * 此动画的数据。 * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ - get data () { + get data (): Uint8Array | null { return this._getLegacyData().data; } /** * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ - public getPropertyCurves () { + public getPropertyCurves (): readonly legacy.LegacyRuntimeCurve[] { return this._getLegacyData().getPropertyCurves(); } @@ -603,7 +604,7 @@ export class AnimationClip extends Asset { * You should call this function after you changed the `events` data to take effect. * @deprecated Since V3.3. Please Assign to `this.events`. */ - public updateEventDatas () { + public updateEventDatas (): void { this.events = this._events; } @@ -612,7 +613,7 @@ export class AnimationClip extends Asset { * @en Returns if this animation contains event data. * @protected */ - public hasEvents () { + public hasEvents (): boolean { return this.events.length !== 0; } @@ -622,7 +623,7 @@ export class AnimationClip extends Asset { * DO NOT use it in your code since it might be removed for the future at any time. * @internal Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ - public syncLegacyData () { + public syncLegacyData (): void { if (this._legacyData) { this._fromLegacy(this._legacyData); this._legacyData = undefined; @@ -634,7 +635,7 @@ export class AnimationClip extends Asset { /** * @internal */ - get [embeddedPlayerCountTag] () { + get [embeddedPlayerCountTag] (): number { return this._embeddedPlayers.length; } @@ -648,14 +649,14 @@ export class AnimationClip extends Asset { /** * @internal */ - public [addEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer) { + public [addEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer): void { this._embeddedPlayers.push(embeddedPlayer); } /** * @internal */ - public [removeEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer) { + public [removeEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer): void { const iEmbeddedPlayer = this._embeddedPlayers.indexOf(embeddedPlayer); if (iEmbeddedPlayer >= 0) { this._embeddedPlayers.splice(iEmbeddedPlayer, 1); @@ -665,7 +666,7 @@ export class AnimationClip extends Asset { /** * @internal */ - public [clearEmbeddedPlayersTag] () { + public [clearEmbeddedPlayersTag] (): void { this._embeddedPlayers.length = 0; } @@ -673,7 +674,7 @@ export class AnimationClip extends Asset { * @zh 获取此动画剪辑中的辅助曲线数量。 * @en Gets the count of auxiliary curves within this animation clip. */ - public get auxiliaryCurveCount_experimental () { + public get auxiliaryCurveCount_experimental (): number { return this._auxiliaryCurveEntries.length; } @@ -689,7 +690,7 @@ export class AnimationClip extends Asset { * @zh 返回此动画剪辑中是否存在指定的辅助曲线。 * @en Returns if the specified auxiliary curve exists in this animation clip. */ - public hasAuxiliaryCurve_experimental (name: string) { + public hasAuxiliaryCurve_experimental (name: string): boolean { return !!this._findAuxiliaryCurveEntry(name); } @@ -717,7 +718,7 @@ export class AnimationClip extends Asset { * @returns @zh 指定的辅助曲线。@en The specified auxiliary curve. * @experimental */ - public getAuxiliaryCurve_experimental (name: string) { + public getAuxiliaryCurve_experimental (name: string): RealCurve { const entry = this._findAuxiliaryCurveEntry(name); assertIsTrue(entry); return entry.curve; @@ -729,7 +730,7 @@ export class AnimationClip extends Asset { * @param name @zh 要重命名的辅助曲线的名称。@en Name of the auxiliary curve to rename. * @param newName @zh 新名称。@en New name. */ - public renameAuxiliaryCurve_experimental (name: string, newName: string) { + public renameAuxiliaryCurve_experimental (name: string, newName: string): void { const entry = this._findAuxiliaryCurveEntry(name); if (entry) { entry.name = newName; @@ -742,14 +743,14 @@ export class AnimationClip extends Asset { * @param name @zh 辅助曲线的名称。@en The auxiliary curve's name. * @experimental */ - public removeAuxiliaryCurve_experimental (name: string) { + public removeAuxiliaryCurve_experimental (name: string): void { removeIf(this._auxiliaryCurveEntries, (entry) => entry.name === name); } /** * @internal */ - public _trySyncLegacyData () { + public _trySyncLegacyData (): void { if (this._legacyDataDirty) { this._legacyDataDirty = false; this.syncLegacyData(); @@ -794,7 +795,7 @@ export class AnimationClip extends Asset { eventGroups: [], }; - private _createEvalWithBinder (target: unknown, binder: Binder, rootMotionOptions: RootMotionOptions | undefined) { + private _createEvalWithBinder (target: unknown, binder: Binder, rootMotionOptions: RootMotionOptions | undefined): AnimationClipEvaluation { if (this._legacyDataDirty) { this._legacyDataDirty = false; this.syncLegacyData(); @@ -865,7 +866,7 @@ export class AnimationClip extends Asset { target: unknown, rootMotionOptions: RootMotionOptions, rootMotionTrackExcludes: Track[], - ) { + ): RootMotionEvaluation | undefined { if (!(target instanceof Node)) { errorID(3920); return undefined; @@ -919,7 +920,7 @@ export class AnimationClip extends Asset { return rootMotionEvaluation; } - private _searchForRootBonePath () { + private _searchForRootBonePath (): string { const paths = this._tracks.map((track) => { const trsPath = track[trackBindingTag].parseTrsPath(); if (trsPath) { @@ -960,7 +961,7 @@ export class AnimationClip extends Asset { return highestPathsAreSame ? firstPath.path : ''; } - private _getLegacyData () { + private _getLegacyData (): legacy.AnimationClipLegacyData { if (!this._legacyData) { this._legacyData = this._toLegacy(); } @@ -979,7 +980,7 @@ export class AnimationClip extends Asset { return legacyClipData; } - private _fromLegacy (legacyData: legacy.AnimationClipLegacyData) { + private _fromLegacy (legacyData: legacy.AnimationClipLegacyData): void { const newTracks = legacyData.toTracks(); const nNewTracks = newTracks.length; for (let iNewTrack = 0; iNewTrack < nNewTracks; ++iNewTrack) { @@ -987,7 +988,7 @@ export class AnimationClip extends Asset { } } - private _collectAnimatedJoints () { + private _collectAnimatedJoints (): string[] { const joints = new Set(); const { _tracks: tracks } = this; @@ -1011,7 +1012,7 @@ export class AnimationClip extends Asset { return Array.from(joints); } - private _findAuxiliaryCurveEntry (name: string) { + private _findAuxiliaryCurveEntry (name: string): AuxiliaryCurveEntry | undefined { return this._auxiliaryCurveEntries.find((entry) => entry.name === name); } } @@ -1041,7 +1042,7 @@ class TrackEvalStatus { this._trackEval = trackEval; } - public evaluate (time: number) { + public evaluate (time: number): void { const { _binding: binding, _trackEval: trackEval } = this; const defaultValue = binding.getValue && trackEval.requiresDefault ? binding.getValue() as TValue extends unknown ? unknown : Readonly @@ -1105,7 +1106,7 @@ class EmbeddedPlayerEvaluation { ); } - public destroy () { + public destroy (): void { const { _embeddedPlayerEvaluationInfos: embeddedPlayerEvaluationInfos, } = this; @@ -1121,7 +1122,7 @@ class EmbeddedPlayerEvaluation { * @param time The time([0, clipDuration]). * @param iterations The iterations the evaluation occurred. Should be integral. */ - public evaluate (time: number, iterations: number) { + public evaluate (time: number, iterations: number): void { assertIsTrue(Number.isInteger(iterations)); const { _embeddedPlayers: embeddedPlayers, @@ -1157,7 +1158,7 @@ class EmbeddedPlayerEvaluation { } } - public notifyHostSpeedChanged (speed: number) { + public notifyHostSpeedChanged (speed: number): void { // Transmit the speed to embedded players that want a reconciled speed. const { _embeddedPlayers: embeddedPlayers, @@ -1181,7 +1182,7 @@ class EmbeddedPlayerEvaluation { * Notifies that the host has ran into **playing** state. * @param time The time where host ran into playing state. */ - public notifyHostPlay (time: number) { + public notifyHostPlay (time: number): void { // Host has switched to "playing", this can be happened when: // - Previous state is "stopped": we must have stopped all embedded players. // - Is pausing: we need to resume all embedded players. @@ -1217,7 +1218,7 @@ class EmbeddedPlayerEvaluation { /** * Notifies that the host has ran into **pause** state. */ - public notifyHostPause (time: number) { + public notifyHostPause (time: number): void { // Host is paused, simply transmit this to embedded players. const { _embeddedPlayers: embeddedPlayers, @@ -1240,7 +1241,7 @@ class EmbeddedPlayerEvaluation { /** * Notifies that the host has ran into **stopped** state. */ - public notifyHostStop () { + public notifyHostStop (): void { // Now that host is stopped, we stop all embedded players' playing // regardless of their progresses. const { @@ -1286,7 +1287,7 @@ class AnimationClipEvaluation { * Evaluates this animation. * @param time The time. */ - public evaluate (time: number) { + public evaluate (time: number): void { const { _trackEvalStatues: trackEvalStatuses, _exoticAnimationEvaluator: exoticAnimationEvaluator, @@ -1307,7 +1308,7 @@ class AnimationClipEvaluation { * @param startTime Start time. * @param endTime End time. */ - public evaluateRootMotion (time: number, motionLength: number) { + public evaluateRootMotion (time: number, motionLength: number): void { const { _rootMotionEvaluation: rootMotionEvaluation } = this; if (rootMotionEvaluation) { rootMotionEvaluation.evaluate(time, motionLength); @@ -1325,7 +1326,7 @@ class BoneTransform { public rotation = new Quat(); public eulerAngles = new Vec3(); - public getTransform (out: Mat4) { + public getTransform (out: Mat4): void { Mat4.fromRTS(out, this.rotation, this.position, this.scale); } } @@ -1345,7 +1346,7 @@ class BoneGlobalTransform extends BoneTransform { return this._transform; } - public invalidate () { + public invalidate (): void { this._dirty = true; } @@ -1365,7 +1366,7 @@ class RootMotionEvaluation { } - public evaluate (time: number, motionLength: number) { + public evaluate (time: number, motionLength: number): void { const motionTransform = this._calcMotionTransform(time, motionLength, this._motionTransformCache); const { @@ -1387,7 +1388,7 @@ class RootMotionEvaluation { rootBone.setScale(scaleMotion); } - private _calcMotionTransform (time: number, motionLength: number, outTransform: Mat4) { + private _calcMotionTransform (time: number, motionLength: number, outTransform: Mat4): Mat4 { const { _duration: duration } = this; const remainLength = duration - time; assertIsTrue(remainLength >= 0); @@ -1398,7 +1399,7 @@ class RootMotionEvaluation { } else { Mat4.identity(outTransform); - const accumulateMotionTransform = (from: Mat4, to: Mat4) => { + const accumulateMotionTransform = (from: Mat4, to: Mat4): void => { relativeTransform(motionTransformCache, from, to); Mat4.multiply(outTransform, outTransform, motionTransformCache); }; @@ -1425,7 +1426,7 @@ class RootMotionEvaluation { return outTransform; } - private _evaluateAt (time: number, outTransform: Mat4) { + private _evaluateAt (time: number, outTransform: Mat4): Mat4 { const { _trackEvalStatuses: trackEvalStatuses, } = this; @@ -1449,36 +1450,40 @@ class RootMotionEvaluation { private _scaleMotionCache = new Vec3(); } -function relativeTransform (out: Mat4, from: Mat4, to: Mat4) { - Mat4.invert(out, from); +function relativeTransform (out: Mat4, from: Mat4, to: Mat4): void { +Mat4.invert(out, from); Mat4.multiply(out, to, out); } -function createBoneTransformBinding (boneTransform: BoneTransform, property: TrsTrackPath[1]) { +function createBoneTransformBinding (boneTransform: BoneTransform, property: TrsTrackPath[1]): { + setValue(value: Vec3): void; +} | { + setValue(value: Quat): void; +} | undefined { switch (property) { default: return undefined; case 'position': return { - setValue (value: Vec3) { + setValue (value: Vec3): void { Vec3.copy(boneTransform.position, value); }, }; case 'rotation': return { - setValue (value: Quat) { + setValue (value: Quat): void { Quat.copy(boneTransform.rotation, value); }, }; case 'scale': return { - setValue (value: Vec3) { + setValue (value: Vec3): void { Vec3.copy(boneTransform.scale, value); }, }; case 'eulerAngles': return { - setValue (value: Vec3) { + setValue (value: Vec3): void { Vec3.copy(boneTransform.eulerAngles, value); }, }; @@ -1508,11 +1513,11 @@ class EventEvaluator { } - public setWrapMode (wrapMode: WrapMode) { + public setWrapMode (wrapMode: WrapMode): void { this._wrapMode = wrapMode; } - public ignore (ratio: number, direction: number) { + public ignore (ratio: number, direction: number): void { this._ignoreIndex = InvalidIndex; this._sampled = false; @@ -1529,7 +1534,7 @@ class EventEvaluator { } } - public sample (ratio: number, direction: number, iterations: number) { + public sample (ratio: number, direction: number, iterations: number): void { const length = this._eventGroups.length; let eventIndex = getEventGroupIndexAtRatio(ratio, this._ratios); if (eventIndex < 0) { @@ -1609,7 +1614,7 @@ class EventEvaluator { private _ignoreIndex = InvalidIndex; private _sampled = false; - private _doFire (eventIndex: number, delay: boolean) { + private _doFire (eventIndex: number, delay: boolean): void { if (delay) { getGlobalAnimationManager().pushDelayEvent(this._checkAndFire, this, [eventIndex]); } else { @@ -1617,7 +1622,7 @@ class EventEvaluator { } } - private _checkAndFire (eventIndex: number) { + private _checkAndFire (eventIndex: number): void { if (!this._targetNode || !this._targetNode.isValid) { return; } @@ -1636,14 +1641,14 @@ class EventEvaluator { } } -function wrapIterations (iterations: number) { +function wrapIterations (iterations: number): number { if (iterations - (iterations | 0) === 0) { iterations -= 1; } return iterations | 0; } -function getEventGroupIndexAtRatio (ratio: number, ratios: readonly number[]) { +function getEventGroupIndexAtRatio (ratio: number, ratios: readonly number[]): number { const result = binarySearchEpsilon(ratios, ratio); return result; } diff --git a/cocos/animation/animation-component.ts b/cocos/animation/animation-component.ts index 823d4789302..0c1045fc680 100644 --- a/cocos/animation/animation-component.ts +++ b/cocos/animation/animation-component.ts @@ -61,7 +61,7 @@ export class Animation extends Eventify(Component) { */ @type([AnimationClip]) @tooltip('i18n:animation.clips') - get clips () { + get clips (): (AnimationClip | null)[] { return this._clips; } @@ -104,7 +104,7 @@ export class Animation extends Eventify(Component) { */ @type(AnimationClip) @tooltip('i18n:animation.default_clip') - get defaultClip () { + get defaultClip (): AnimationClip | null { return this._defaultClip; } @@ -161,7 +161,7 @@ export class Animation extends Eventify(Component) { */ private _hasBeenPlayed = false; - public onLoad () { + public onLoad (): void { this.clips = this._clips; for (const stateName in this._nameToState) { const state = this._nameToState[stateName]; @@ -169,21 +169,21 @@ export class Animation extends Eventify(Component) { } } - public start () { + public start (): void { if (!EDITOR_NOT_IN_PREVIEW && (this.playOnLoad && !this._hasBeenPlayed) && this._defaultClip) { this.crossFade(this._defaultClip.name, 0); } } - public onEnable () { + public onEnable (): void { this._crossFade.resume(); } - public onDisable () { + public onDisable (): void { this._crossFade.pause(); } - public onDestroy () { + public onDestroy (): void { this._crossFade.stop(); for (const name in this._nameToState) { const state = this._nameToState[name]; @@ -199,7 +199,7 @@ export class Animation extends Eventify(Component) { * 立即切换到指定动画状态。 * @param name The name of the animation to be played, if absent, the default clip will be played */ - public play (name?: string) { + public play (name?: string): void { this._hasBeenPlayed = true; if (!name) { if (!this._defaultClip) { @@ -218,7 +218,7 @@ export class Animation extends Eventify(Component) { * @param name The name of the animation to switch to * @param duration The duration of the cross fade, default value is 0.3s */ - public crossFade (name: string, duration = 0.3) { + public crossFade (name: string, duration = 0.3): void { this._hasBeenPlayed = true; const state = this._nameToState[name]; if (state) { @@ -232,7 +232,7 @@ export class Animation extends Eventify(Component) { * @zh * 暂停所有动画状态,并暂停所有切换。 */ - public pause () { + public pause (): void { this._crossFade.pause(); } @@ -242,7 +242,7 @@ export class Animation extends Eventify(Component) { * @zh * 恢复所有动画状态,并恢复所有切换。 */ - public resume () { + public resume (): void { this._crossFade.resume(); } @@ -252,7 +252,7 @@ export class Animation extends Eventify(Component) { * @zh * 停止所有动画状态,并停止所有切换。 */ - public stop () { + public stop (): void { this._crossFade.stop(); } @@ -264,7 +264,7 @@ export class Animation extends Eventify(Component) { * @param name The name of the animation * @returns If no animation found, return null, otherwise the correspond animation state is returned */ - public getState (name: string) { + public getState (name: string): AnimationState { const state = this._nameToState[name]; if (state && !state.curveLoaded) { state.initialize(this.node); @@ -283,7 +283,7 @@ export class Animation extends Eventify(Component) { * @param name The animation state name, if absent, the default clip's name will be used * @returns The animation state created */ - public createState (clip: AnimationClip, name?: string) { + public createState (clip: AnimationClip, name?: string): AnimationState { name = name || clip.name; this.removeState(name); @@ -297,7 +297,7 @@ export class Animation extends Eventify(Component) { * 停止并移除指定的动画状态。 * @param name The name of the animation state */ - public removeState (name: string) { + public removeState (name: string): void { const state = this._nameToState[name]; if (state) { state.allowLastFrameEvent(false); @@ -334,7 +334,7 @@ export class Animation extends Eventify(Component) { * 但是如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。这时候如果 clip 是 defaultClip,defaultClip 将会被重置为 null。
* @param force - If force is true, then will always remove the clip and any animation states based on it. */ - public removeClip (clip: AnimationClip, force?: boolean) { + public removeClip (clip: AnimationClip, force?: boolean): void { let removalState: AnimationState | undefined; for (const name in this._nameToState) { const state = this._nameToState[name]; @@ -390,7 +390,7 @@ export class Animation extends Eventify(Component) { * animation.on('play', this.onPlay, this); * ``` */ - public on void> (type: EventType, callback: TFunction, thisArg?: any, once?: boolean) { + public on void> (type: EventType, callback: TFunction, thisArg?: any, once?: boolean): TFunction { const ret = super.on(type, callback, thisArg, once); if (type === EventType.LASTFRAME) { this._syncAllowLastFrameEvent(); @@ -398,7 +398,7 @@ export class Animation extends Eventify(Component) { return ret; } - public once void> (type: EventType, callback: TFunction, thisArg?: any) { + public once void> (type: EventType, callback: TFunction, thisArg?: any): TFunction { const ret = super.once(type, callback, thisArg); if (type === EventType.LASTFRAME) { this._syncAllowLastFrameEvent(); @@ -420,7 +420,7 @@ export class Animation extends Eventify(Component) { * animation.off('play', this.onPlay, this); * ``` */ - public off (type: EventType, callback?: (...any) => void, thisArg?: any) { + public off (type: EventType, callback?: (...any) => void, thisArg?: any): void { super.off(type, callback, thisArg); if (type === EventType.LASTFRAME) { this._syncDisallowLastFrameEvent(); @@ -430,14 +430,14 @@ export class Animation extends Eventify(Component) { /** * @internal */ - protected _createState (clip: AnimationClip, name?: string) { + protected _createState (clip: AnimationClip, name?: string): AnimationState { return new AnimationState(clip, name); } /** * @internal */ - protected _doCreateState (clip: AnimationClip, name: string) { + protected _doCreateState (clip: AnimationClip, name: string): AnimationState { const state = this._createState(clip, name); state._setEventTarget(this); state.allowLastFrameEvent(this.hasEventListener(EventType.LASTFRAME)); @@ -451,12 +451,12 @@ export class Animation extends Eventify(Component) { /** * @internal This method only friends to skeletal animation component. */ - protected doPlayOrCrossFade (state: AnimationState, duration: number) { + protected doPlayOrCrossFade (state: AnimationState, duration: number): void { this._crossFade.play(); this._crossFade.crossFade(state, duration); } - private _removeStateOfAutomaticClip (clip: AnimationClip) { + private _removeStateOfAutomaticClip (clip: AnimationClip): void { for (const name in this._nameToState) { const state = this._nameToState[name]; if (equalClips(clip, state.clip)) { @@ -466,7 +466,7 @@ export class Animation extends Eventify(Component) { } } - private _syncAllowLastFrameEvent () { + private _syncAllowLastFrameEvent (): void { if (this.hasEventListener(EventType.LASTFRAME)) { for (const stateName in this._nameToState) { this._nameToState[stateName].allowLastFrameEvent(true); @@ -474,7 +474,7 @@ export class Animation extends Eventify(Component) { } } - private _syncDisallowLastFrameEvent () { + private _syncDisallowLastFrameEvent (): void { if (!this.hasEventListener(EventType.LASTFRAME)) { for (const stateName in this._nameToState) { this._nameToState[stateName].allowLastFrameEvent(false); @@ -489,7 +489,7 @@ export declare namespace Animation { export type EventType = EventType_; } -function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) { +function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null): string | boolean { if (clip1 === clip2) { return true; } diff --git a/cocos/animation/animation-curve.ts b/cocos/animation/animation-curve.ts index 6af8613a7d9..b1c4aaa2edd 100644 --- a/cocos/animation/animation-curve.ts +++ b/cocos/animation/animation-curve.ts @@ -53,7 +53,7 @@ export class RatioSampler { this._findRatio = canOptimize ? quickFindIndex : binarySearchEpsilon; } - public sample (ratio: number) { + public sample (ratio: number): number { return this._findRatio(this.ratios, ratio); } } @@ -69,7 +69,7 @@ cclegacy.RatioSampler = RatioSampler; export class AnimCurve { public static Linear = null; - public static Bezier (controlPoints: number[]) { + public static Bezier (controlPoints: number[]): BezierControlPoints { return controlPoints as BezierControlPoints; } @@ -97,7 +97,7 @@ export class AnimCurve { // Install values. this._values = propertyCurveData.values; - const getCurveType = (easingMethod: legacy.LegacyEasingMethod) => { + const getCurveType = (easingMethod: legacy.LegacyEasingMethod): legacy.LegacyEasingMethod | null => { if (typeof easingMethod === 'string') { return easingMethod; } else if (Array.isArray(easingMethod)) { @@ -139,11 +139,11 @@ export class AnimCurve { } } - public hasLerp () { + public hasLerp (): boolean { return !!this._lerp; } - public valueAt (index: number) { + public valueAt (index: number): any { if (this._array === undefined) { const value = this._values[index]; if (value && value.getNoLerp) { @@ -162,7 +162,7 @@ export class AnimCurve { } } - public valueBetween (ratio: number, from: number, fromRatio: number, to: number, toRatio: number) { + public valueBetween (ratio: number, from: number, fromRatio: number, to: number, toRatio: number): any { if (this._lerp) { const type = this.types ? this.types[from] : this.type; const dRatio = (toRatio - fromRatio); @@ -198,14 +198,14 @@ export class AnimCurve { } } - public empty () { + public empty (): boolean { return this._values.length === 0; } /** * Returns if this curve only yields constants. */ - public constant () { + public constant (): boolean { return this._values.length === 1; } } @@ -218,7 +218,7 @@ export class EventInfo { * @param func event function * @param params event params */ - public add (func: string, params: any[]) { + public add (func: string, params: any[]): void { this.events.push({ func: func || '', params: params || [], @@ -236,7 +236,7 @@ export class EventInfo { * @param sampler @zh 采样器。@en The sampler. * @param ratio @zh 采样比率。@en Sample ratio([0, 1]). */ -export function sampleAnimationCurve (curve: AnimCurve, sampler: RatioSampler, ratio: number) { +export function sampleAnimationCurve (curve: AnimCurve, sampler: RatioSampler, ratio: number): any { let index = sampler.sample(ratio); if (index < 0) { index = ~index; @@ -266,7 +266,7 @@ cclegacy.sampleAnimationCurve = sampleAnimationCurve; * If it's string, then ratio will be computed with cc.easing function * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ -export function computeRatioByType (ratio: number, type: legacy.LegacyEasingMethod) { +export function computeRatioByType (ratio: number, type: legacy.LegacyEasingMethod): number { if (typeof type === 'string') { const func = easing[type]; if (func) { @@ -285,7 +285,7 @@ export function computeRatioByType (ratio: number, type: legacy.LegacyEasingMeth /** * Use this function if intervals between frames are same. */ -function quickFindIndex (ratios: number[], ratio: number) { +function quickFindIndex (ratios: number[], ratio: number): number { const length = ratios.length - 1; if (length === 0) { return 0; } @@ -312,10 +312,10 @@ function quickFindIndex (ratios: number[], ratio: number) { return ~(floorIndex + 1); } -const selectLerpFx = (() => { - function makeValueTypeLerpFx (constructor: Constructor) { +const selectLerpFx = ((): (value: any) => legacy.LegacyLerpFunction | undefined => { + function makeValueTypeLerpFx (constructor: Constructor): (from: T, to: T, ratio: number) => T { const tempValue = new constructor(); - return (from: T, to: T, ratio: number) => { + return (from: T, to: T, ratio: number): T => { // TODO: `ValueType` class doesn't define lerp method // please fix the type @Leslie Leigh // Tracking issue: https://github.com/cocos/cocos-engine/issues/14640 @@ -329,9 +329,9 @@ const selectLerpFx = (() => { return from.lerp(to, t, dt); } - function makeQuatSlerpFx () { + function makeQuatSlerpFx (): (from: Quat, to: Quat, t: number, dt: number) => Quat { const tempValue = new Quat(); - return (from: Quat, to: Quat, t: number, dt: number) => Quat.slerp(tempValue, from, to, t); + return (from: Quat, to: Quat, t: number, dt: number): Quat => Quat.slerp(tempValue, from, to, t); } return (value: any): legacy.LegacyLerpFunction | undefined => { diff --git a/cocos/animation/animation-manager.ts b/cocos/animation/animation-manager.ts index 3e929dd6978..eb1f32e28e5 100644 --- a/cocos/animation/animation-manager.ts +++ b/cocos/animation/animation-manager.ts @@ -54,14 +54,14 @@ export class AnimationManager extends System { private _blendStateBuffer: LegacyBlendStateBuffer = new LegacyBlendStateBuffer(); private _sockets: ISocketData[] = []; - public addCrossFade (crossFade: CrossFade) { + public addCrossFade (crossFade: CrossFade): void { const index = this._crossFades.array.indexOf(crossFade); if (index === -1) { this._crossFades.push(crossFade); } } - public removeCrossFade (crossFade: CrossFade) { + public removeCrossFade (crossFade: CrossFade): void { const index = this._crossFades.array.indexOf(crossFade); if (index >= 0) { this._crossFades.fastRemoveAt(index); @@ -70,7 +70,7 @@ export class AnimationManager extends System { } } - public update (dt: number) { + public update (dt: number): void { const { _delayEvents, _crossFades: crossFadesIter, _sockets } = this; { // Update cross fades @@ -104,18 +104,18 @@ export class AnimationManager extends System { _delayEvents.length = 0; } - public destruct () { + public destruct (): void { } - public addAnimation (anim: AnimationState) { + public addAnimation (anim: AnimationState): void { const index = this._anims.array.indexOf(anim); if (index === -1) { this._anims.push(anim); } } - public removeAnimation (anim: AnimationState) { + public removeAnimation (anim: AnimationState): void { const index = this._anims.array.indexOf(anim); if (index >= 0) { this._anims.fastRemoveAt(index); @@ -124,7 +124,7 @@ export class AnimationManager extends System { } } - public pushDelayEvent (fn: (...args: any[]) => void, thisArg: any, args: any[]) { + public pushDelayEvent (fn: (...args: any[]) => void, thisArg: any, args: any[]): void { this._delayEvents.push({ fn, thisArg, @@ -132,7 +132,7 @@ export class AnimationManager extends System { }); } - public addSockets (root: Node, sockets: Socket[]) { + public addSockets (root: Node, sockets: Socket[]): void { for (let i = 0; i < sockets.length; ++i) { const socket = sockets[i]; if (this._sockets.find((s) => s.target === socket.target)) { continue; } @@ -144,7 +144,7 @@ export class AnimationManager extends System { } } - public removeSockets (root: Node, sockets: Socket[]) { + public removeSockets (root: Node, sockets: Socket[]): void { for (let i = 0; i < sockets.length; ++i) { const socketToRemove = sockets[i]; for (let j = 0; j < this._sockets.length; ++j) { @@ -160,7 +160,7 @@ export class AnimationManager extends System { } } -director.on(Director.EVENT_INIT, () => { +director.on(Director.EVENT_INIT, (): void => { const animationManager = new AnimationManager(); director.registerSystem(AnimationManager.ID, animationManager, System.Priority.HIGH); }); diff --git a/cocos/animation/animation-state.ts b/cocos/animation/animation-state.ts index 7c69d1326e6..31ca4d8ac7f 100644 --- a/cocos/animation/animation-state.ts +++ b/cocos/animation/animation-state.ts @@ -87,7 +87,7 @@ export class AnimationState extends Playable { * @en The clip that is being played by this animation state. * @zh 此动画状态正在播放的剪辑。 */ - get clip () { + get clip (): AnimationClip { return this._clip; } @@ -95,11 +95,11 @@ export class AnimationState extends Playable { * @en The name of the playing animation. * @zh 动画的名字。 */ - get name () { + get name (): string { return this._name; } - get length () { + get length (): number { return this.duration; } @@ -112,7 +112,7 @@ export class AnimationState extends Playable { * 需要注意的是,动态修改 wrapMode 时,会重置 time 以及 repeatCount。 * @default: WrapMode.Normal */ - get wrapMode () { + get wrapMode (): WrapMode { return this._wrapMode; } @@ -144,7 +144,7 @@ export class AnimationState extends Playable { * * @default 1 */ - get repeatCount () { + get repeatCount (): number { return this._repeatCount; } @@ -166,7 +166,7 @@ export class AnimationState extends Playable { * @zh 延迟多少秒播放。 * @default 0 */ - get delay () { + get delay (): number { return this._delay; } @@ -215,7 +215,7 @@ export class AnimationState extends Playable { * @zh 播放速率。 * @default: 1.0 */ - get speed () { + get speed (): number { return this._speed; } @@ -235,7 +235,7 @@ export class AnimationState extends Playable { * @en Gets the time progress, in seconds. * @zh 获取动画的时间进度,单位为秒。 */ - get current () { + get current (): number { return this.getWrappedInfo(this.time).time; } @@ -243,7 +243,7 @@ export class AnimationState extends Playable { * @en Gets the playback ratio. * @zh 获取动画播放的比例时间。 */ - get ratio () { + get ratio (): number { return this.duration === 0.0 ? 0.0 : this.current / this.duration; } @@ -253,7 +253,7 @@ export class AnimationState extends Playable { * @zh * 此动画状态的权重。 */ - get weight () { + get weight (): number { return this._weight; } @@ -327,11 +327,11 @@ export class AnimationState extends Playable { /** * This method is used for internal purpose only. */ - get curveLoaded () { + get curveLoaded (): boolean { return this._curveLoaded; } - public initialize (root: Node, blendStateBuffer?: BlendStateBuffer, mask?: AnimationMask) { + public initialize (root: Node, blendStateBuffer?: BlendStateBuffer, mask?: AnimationMask): void { if (this._curveLoaded) { return; } this._curveLoaded = true; if (this._poseOutput) { @@ -391,7 +391,7 @@ export class AnimationState extends Playable { } } - public destroy () { + public destroy (): void { if (!this.isMotionless) { getGlobalAnimationManager().removeAnimation(this); } @@ -407,7 +407,7 @@ export class AnimationState extends Playable { * @deprecated Since V1.1.1, animation states were no longer defined as event targets. * To process animation events, use `Animation` instead. */ - public emit (...args: any[]) { + public emit (...args: any[]): void { getGlobalAnimationManager().pushDelayEvent(this._emit, this, args); } @@ -416,7 +416,7 @@ export class AnimationState extends Playable { * To process animation events, use `Animation` instead. */ // eslint-disable-next-line @typescript-eslint/ban-types - public on (type: string, callback: Function, target?: any) { + public on (type: string, callback: Function, target?: any): void | null { if (this._target && this._target.isValid) { return this._target.on(type, callback, target); } else { @@ -429,7 +429,7 @@ export class AnimationState extends Playable { * To process animation events, use `Animation` instead. */ // eslint-disable-next-line @typescript-eslint/ban-types - public once (type: string, callback: Function, target?: any) { + public once (type: string, callback: Function, target?: any): void | null { if (this._target && this._target.isValid) { return this._target.once(type, callback, target); } else { @@ -442,7 +442,7 @@ export class AnimationState extends Playable { * To process animation events, use `Animation` instead. */ // eslint-disable-next-line @typescript-eslint/ban-types - public off (type: string, callback: Function, target?: any) { + public off (type: string, callback: Function, target?: any): void { if (this._target && this._target.isValid) { this._target.off(type, callback, target); } @@ -457,7 +457,7 @@ export class AnimationState extends Playable { * @param allowed True if the last frame events may be triggered. * This method is only used for internal purpose only. */ - public allowLastFrameEvent (allowed: boolean) { + public allowLastFrameEvent (allowed: boolean): void { this._allowLastFrame = allowed; } @@ -465,11 +465,11 @@ export class AnimationState extends Playable { * This method is used for internal purpose only. * @internal */ - public _setEventTarget (target) { + public _setEventTarget (target): void { this._target = target; } - public setTime (time: number) { + public setTime (time: number): void { this._currentFramePlayed = false; this.time = time || 0.0; @@ -479,7 +479,7 @@ export class AnimationState extends Playable { } } - public update (delta: number) { + public update (delta: number): void { // calculate delay time if (this._delayTime > 0.0) { @@ -502,7 +502,7 @@ export class AnimationState extends Playable { this._process(); } - public sample () { + public sample (): WrappedInfo { const info = this.getWrappedInfo(this.time, this._wrappedInfo); this._sampleCurves(info.time); if (!EDITOR_NOT_IN_PREVIEW) { @@ -512,7 +512,7 @@ export class AnimationState extends Playable { return info; } - protected onPlay () { + protected onPlay (): void { this.setTime(this._getPlaybackStart()); this._delayTime = this._delay; this._onReplayOrResume(); @@ -520,7 +520,7 @@ export class AnimationState extends Playable { this._clipEmbeddedPlayerEval?.notifyHostPlay(this.current); } - protected onStop () { + protected onStop (): void { if (!this.isPaused) { this._onPauseOrStop(); } @@ -528,13 +528,13 @@ export class AnimationState extends Playable { this._clipEmbeddedPlayerEval?.notifyHostStop(); } - protected onResume () { + protected onResume (): void { this._onReplayOrResume(); this.emit(EventType.RESUME, this); this._clipEmbeddedPlayerEval?.notifyHostPlay(this.current); } - protected onPause () { + protected onPause (): void { this._onPauseOrStop(); this.emit(EventType.PAUSE, this); this._clipEmbeddedPlayerEval?.notifyHostPause(this.current); @@ -543,7 +543,7 @@ export class AnimationState extends Playable { /** * @internal */ - protected _sampleCurves (time: number) { + protected _sampleCurves (time: number): void { const { _poseOutput: poseOutput, _clipEval: clipEval } = this; if (poseOutput) { poseOutput.weight = this.weight; @@ -553,7 +553,7 @@ export class AnimationState extends Playable { } } - private _process () { + private _process (): void { if (this._useSimpleProcess) { this.simpleProcess(); } else { @@ -561,7 +561,7 @@ export class AnimationState extends Playable { } } - private process () { + private process (): void { // sample const info = this.sample(); @@ -586,7 +586,7 @@ export class AnimationState extends Playable { } } - private simpleProcess () { + private simpleProcess (): void { const playbackStart = this._playbackRange.min; const playbackDuration = this._playbackDuration; @@ -624,7 +624,7 @@ export class AnimationState extends Playable { } } - private _needReverse (currentIterations: number) { + private _needReverse (currentIterations: number): boolean { const wrapMode = this.wrapMode; let needReverse = false; @@ -645,7 +645,7 @@ export class AnimationState extends Playable { return needReverse; } - private getWrappedInfo (time: number, info?: WrappedInfo) { + private getWrappedInfo (time: number, info?: WrappedInfo): WrappedInfo { info = info || new WrappedInfo(); const { @@ -715,11 +715,11 @@ export class AnimationState extends Playable { return info; } - private _getPlaybackStart () { + private _getPlaybackStart (): number { return this._playbackRange.min; } - private _sampleEvents (wrapInfo: WrappedInfo) { + private _sampleEvents (wrapInfo: WrappedInfo): void { this._clipEventEval?.sample( wrapInfo.ratio, wrapInfo.direction, @@ -727,24 +727,24 @@ export class AnimationState extends Playable { ); } - private _sampleEmbeddedPlayers (wrapInfo: WrappedInfo) { + private _sampleEmbeddedPlayers (wrapInfo: WrappedInfo): void { this._clipEmbeddedPlayerEval?.evaluate( wrapInfo.time, Math.trunc(wrapInfo.iterations), ); } - private _emit (type, state) { + private _emit (type, state): void { if (this._target && this._target.isValid) { this._target.emit(type, type, state); } } - private _onReplayOrResume () { + private _onReplayOrResume (): void { getGlobalAnimationManager().addAnimation(this); } - private _onPauseOrStop () { + private _onPauseOrStop (): void { getGlobalAnimationManager().removeAnimation(this); } } diff --git a/cocos/animation/core/pose-allocator.ts b/cocos/animation/core/pose-allocator.ts index c615d083f80..8d68bd1adf8 100644 --- a/cocos/animation/core/pose-allocator.ts +++ b/cocos/animation/core/pose-allocator.ts @@ -17,7 +17,7 @@ export class PoseStackAllocator { this._memoryAllocator = globalPosePageMemoryAllocatorManager.createAllocator(poseBytes); } - public destroy () { + public destroy (): void { assertIsTrue(this._allocatedCount === 0, `Can not destroy the allocator since it's not empty.`); for (let iPose = 0; iPose < this._poses.length; ++iPose) { @@ -29,7 +29,7 @@ export class PoseStackAllocator { return this._memoryAllocator.destroy(); } - public get allocatedCount () { + public get allocatedCount (): number { return this._allocatedCount; } @@ -51,7 +51,7 @@ export class PoseStackAllocator { return pose; } - public pop () { + public pop (): void { assertIsTrue(this._allocatedCount > 0, `PoseStackAllocator: push/pop does not match.`); --this._allocatedCount; @@ -65,7 +65,7 @@ export class PoseStackAllocator { // This does not cause big problem since all pose allocators share the same stack memory. } - get top () { + get top (): Pose { assertIsTrue(this._allocatedCount > 0); return this._poses[this._allocatedCount - 1]; } @@ -80,7 +80,7 @@ export class PoseStackAllocator { private _memoryAllocator: SharedStackBasedAllocator; - private _allocateNewPose () { + private _allocateNewPose (): void { const slice = this._memoryAllocator.push(); const transformsByteLength = TransformArray.BYTES_PER_ELEMENT * this._transformCount; const baseOffset = slice.byteOffset; @@ -95,7 +95,7 @@ function calculateRequiredBytes ( transformCount: number, auxiliaryCurveCount: number, capacity: number, -) { +): number { return (TransformArray.BYTES_PER_ELEMENT * transformCount + Float64Array.BYTES_PER_ELEMENT * auxiliaryCurveCount) * capacity; } diff --git a/cocos/animation/core/pose-heap-allocator.ts b/cocos/animation/core/pose-heap-allocator.ts index d02337590de..74e1a30aae2 100644 --- a/cocos/animation/core/pose-heap-allocator.ts +++ b/cocos/animation/core/pose-heap-allocator.ts @@ -23,7 +23,7 @@ export class PoseHeapAllocator { this._metaValueCount = metaValueCount; } - public get allocatedCount () { + public get allocatedCount (): number { return this._allocatedCount; } @@ -59,7 +59,7 @@ export class PoseHeapAllocator { return pose; } - public destroyPose (pose: Pose) { + public destroyPose (pose: Pose): void { assertIsTrue(isPagedPose(pose)); const { _pages: pages } = this; const nPages = pages.length; @@ -104,7 +104,7 @@ export class PoseHeapAllocator { } class AllocationInfo { - get pageIndex () { + get pageIndex (): number { return this._id >> POSE_INDEX_BITS; } @@ -113,7 +113,7 @@ class AllocationInfo { this._id |= (value << POSE_INDEX_BITS); } - get poseIndex () { + get poseIndex (): number { return this._id & POSE_INDEX_MASK; } @@ -141,11 +141,11 @@ class PosePage { this._freeCount = _capacity; } - get capacity () { + get capacity (): number { return this._capacity; } - get freeCount () { + get freeCount (): number { return this._freeCount; } @@ -164,7 +164,7 @@ class PosePage { return pose; } - public deallocate (pose: PagedPose) { + public deallocate (pose: PagedPose): void { const { _poses: poses } = this; const poseIndex = pose[allocationInfoTag].poseIndex; assertIsTrue(poseIndex >= 0 && poseIndex < poses.length); @@ -183,7 +183,7 @@ class PosePage { private _freeCount = 0; - private _createPose (index: number) { + private _createPose (index: number): PagedPose { const transformsByteLength = TransformArray.BYTES_PER_ELEMENT * this._transformCount; const baseOffset = (transformsByteLength + Float64Array.BYTES_PER_ELEMENT * this._metaValueCount) * index; @@ -195,7 +195,7 @@ class PosePage { } } -function findRightmostSetBit (bits: number) { +function findRightmostSetBit (bits: number): number { // Math.log(2) === -Infinity return bits === 0 ? Infinity : Math.log2(bits & -bits); } diff --git a/cocos/animation/core/pose.ts b/cocos/animation/core/pose.ts index 40bc94158b6..1142005be6e 100644 --- a/cocos/animation/core/pose.ts +++ b/cocos/animation/core/pose.ts @@ -22,7 +22,7 @@ export class Pose { /** * @internal */ - public static _create (transforms: TransformArray, auxiliaryCurves: Float64Array) { + public static _create (transforms: TransformArray, auxiliaryCurves: Float64Array): Pose { return new Pose(transforms, auxiliaryCurves); } } @@ -50,7 +50,7 @@ export class TransformFilter { this._involvedTransforms = new Uint16Array(involvedTransforms); } - get involvedTransforms () { + get involvedTransforms (): Readonly { return this._involvedTransforms as Readonly; } @@ -92,7 +92,7 @@ export class TransformFilter { private declare _involvedTransforms: Uint16Array; } -export function blendPoseInto (target: Pose, source: Readonly, alpha: number, transformFilter: TransformFilter | undefined = undefined) { +export function blendPoseInto (target: Pose, source: Readonly, alpha: number, transformFilter: TransformFilter | undefined = undefined): void { blendTransformsInto(target.transforms, source.transforms, alpha, transformFilter); blendAuxiliaryCurvesInto(target.auxiliaryCurves, source.auxiliaryCurves, alpha); } @@ -102,7 +102,7 @@ export function blendTransformsInto ( source: Readonly, alpha: number, transformFilter: TransformFilter | undefined = undefined, -) { +): void { const nTransforms = target.length; assertIsTrue(nTransforms === target.length); if (alpha === 0) { @@ -130,7 +130,7 @@ export function blendTransformsInto ( } } -function copyTransformsWithFilter (target: TransformArray, source: Readonly, filter: TransformFilter) { +function copyTransformsWithFilter (target: TransformArray, source: Readonly, filter: TransformFilter): void { const nTransforms = target.length; assertIsTrue(nTransforms === target.length); // TODO: cannot use for-of statement for Readonly ArrayBuffer on TS 4.2 for OH platform, wait for they upgrade TS version. @@ -141,10 +141,11 @@ function copyTransformsWithFilter (target: TransformArray, source: Readonly { +type BlendIntoTransformArrayAtFunc = (target: TransformArray, source: Readonly, alpha: number, transformIndex: number) => void; +const blendIntoTransformArrayAt = ((): BlendIntoTransformArrayAtFunc => { const cacheTransformSource = new Transform(); const cacheTransformTarget = new Transform(); - return (target: TransformArray, source: Readonly, alpha: number, transformIndex: number) => { + return (target: TransformArray, source: Readonly, alpha: number, transformIndex: number): void => { const transformTarget = target.getTransform(transformIndex, cacheTransformTarget); const transformSource = source.getTransform(transformIndex, cacheTransformSource); Transform.lerp(transformTarget, transformTarget, transformSource, alpha); @@ -152,7 +153,7 @@ const blendIntoTransformArrayAt = (() => { }; })(); -export function blendAuxiliaryCurvesInto (target: Float64Array, source: Readonly, alpha: number) { +export function blendAuxiliaryCurvesInto (target: Float64Array, source: Readonly, alpha: number): void { const nValues = source.length; assertIsTrue(nValues === target.length); for (let iValue = 0; iValue < nValues; ++iValue) { @@ -160,15 +161,16 @@ export function blendAuxiliaryCurvesInto (target: Float64Array, source: Readonly } } -export function calculateDeltaPose (target: Pose, base: Pose) { +export function calculateDeltaPose (target: Pose, base: Pose): void { calculateDeltaTransforms(target.transforms, base.transforms); calculateDeltaAuxiliaryCurves(target.auxiliaryCurves, base.auxiliaryCurves); } -const calculateDeltaTransformArrayAt = (() => { +type CalculateDeltaTransformArrayAtFunc = (target: TransformArray, base: Readonly, transformIndex: number) => void; +const calculateDeltaTransformArrayAt = ((): CalculateDeltaTransformArrayAtFunc => { const cacheTransformBase = new Transform(); const cacheTransformTarget = new Transform(); - return (target: TransformArray, base: Readonly, transformIndex: number) => { + return (target: TransformArray, base: Readonly, transformIndex: number): void => { const baseTransform = base.getTransform(transformIndex, cacheTransformBase); const targetTransform = target.getTransform(transformIndex, cacheTransformTarget); __calculateDeltaTransform(targetTransform, targetTransform, baseTransform); @@ -176,7 +178,7 @@ const calculateDeltaTransformArrayAt = (() => { }; })(); -export function calculateDeltaTransforms (target: TransformArray, base: TransformArray) { +export function calculateDeltaTransforms (target: TransformArray, base: TransformArray): void { const nTransforms = target.length; assertIsTrue(nTransforms === base.length); for (let iTransform = 0; iTransform < nTransforms; ++iTransform) { @@ -184,7 +186,7 @@ export function calculateDeltaTransforms (target: TransformArray, base: Transfor } } -export function calculateDeltaAuxiliaryCurves (target: Float64Array, base: Float64Array) { +export function calculateDeltaAuxiliaryCurves (target: Float64Array, base: Float64Array): void { const nAuxiliaryCurves = target.length; assertIsTrue(nAuxiliaryCurves === base.length); for (let i = 0; i < target.length; ++i) { @@ -192,15 +194,16 @@ export function calculateDeltaAuxiliaryCurves (target: Float64Array, base: Float } } -export function applyDeltaPose (target: Pose, base: Pose, alpha: number, transformFilter: TransformFilter | undefined = undefined) { +export function applyDeltaPose (target: Pose, base: Pose, alpha: number, transformFilter: TransformFilter | undefined = undefined): void { applyDeltaTransforms(target.transforms, base.transforms, alpha, transformFilter); applyDeltaAuxiliaryCurves(target.auxiliaryCurves, base.auxiliaryCurves, alpha); } -const applyDeltaTransformArrayAt = (() => { +type ApplyDeltaTransformArrayAtFunc = (target: TransformArray, delta: Readonly, alpha: number, transformIndex: number) => void; +const applyDeltaTransformArrayAt = ((): ApplyDeltaTransformArrayAtFunc => { const cacheTransformDelta = new Transform(); const cacheTransformTarget = new Transform(); - return (target: TransformArray, delta: Readonly, alpha: number, transformIndex: number) => { + return (target: TransformArray, delta: Readonly, alpha: number, transformIndex: number): void => { const deltaTransform = delta.getTransform(transformIndex, cacheTransformDelta); const targetTransform = target.getTransform(transformIndex, cacheTransformTarget); __applyDeltaTransform(targetTransform, targetTransform, deltaTransform, alpha); @@ -210,7 +213,7 @@ const applyDeltaTransformArrayAt = (() => { export function applyDeltaTransforms ( target: TransformArray, delta: TransformArray, alpha: number, transformFilter: TransformFilter | undefined = undefined, -) { +): void { const nTransforms = target.length; assertIsTrue(nTransforms === delta.length); if (!transformFilter) { @@ -227,7 +230,7 @@ export function applyDeltaTransforms ( } } -export function applyDeltaAuxiliaryCurves (target: Float64Array, delta: Float64Array, alpha: number) { +export function applyDeltaAuxiliaryCurves (target: Float64Array, delta: Float64Array, alpha: number): void { const nAuxiliaryCurves = target.length; assertIsTrue(nAuxiliaryCurves === delta.length); for (let i = 0; i < target.length; ++i) { diff --git a/cocos/animation/core/shared-stack-based-allocator.ts b/cocos/animation/core/shared-stack-based-allocator.ts index 857e935bc17..b14ad668dd6 100644 --- a/cocos/animation/core/shared-stack-based-allocator.ts +++ b/cocos/animation/core/shared-stack-based-allocator.ts @@ -19,29 +19,29 @@ class PagedStack { constructor (private _manager: SharedStackBasedAllocatorManager, private _pageSize: number) { } - get pageSize () { + get pageSize (): number { return this._pageSize; } - get debugLocking () { + get debugLocking (): boolean { return this._locking; } - public get allocatorCount () { + public get allocatorCount (): number { return this._allocatorCount; } - public debugLock () { + public debugLock (): void { assertIsTrue(!this._locking, `The memory is locking.`); this._locking = true; } - public debugUnlock () { + public debugUnlock (): void { assertIsTrue(this._locking, `Wrong execution logic: the memory is not locking.`); this._locking = false; } - public getPageMemory (index: number) { + public getPageMemory (index: number): ArrayBuffer { assertIsTrue(index >= 0 && index < this._pages.length, `Page index out of range`); return this._pages[index].buffer; } @@ -62,7 +62,7 @@ class PagedStack { return page; } - public popPage (allocator: SharedStackBasedAllocator) { + public popPage (allocator: SharedStackBasedAllocator): void { const allocatorPageCount = allocator[allocatorPageCountTag]; assertIsTrue(allocatorPageCount > 0); const allocatorLastPageIndex = allocatorPageCount - 1; @@ -80,13 +80,13 @@ class PagedStack { } } - public createAllocator (sliceSize: number) { + public createAllocator (sliceSize: number): SharedStackBasedAllocator { const allocator = new SharedStackBasedAllocator(this, sliceSize); ++this._allocatorCount; return allocator; } - public destroyAllocator (allocator: SharedStackBasedAllocator) { + public destroyAllocator (allocator: SharedStackBasedAllocator): void { // Decrease use count of all pages used by the allocator. const allocatorPageCount = allocator[allocatorPageCountTag]; for (let iPage = 0; iPage < allocatorPageCount; ++iPage) { @@ -109,7 +109,7 @@ class PagedStack { private _pages: SharedMemoryPage[] = []; private _allocatorCount = 0; - private _pushNewPage () { + private _pushNewPage (): void { const newPage = new SharedMemoryPage(this._pageSize); this._pages.push(newPage); } @@ -140,22 +140,22 @@ class SharedStackBasedAllocator { this._slicesPerPage = slicesPerPage; } - public get isEmpty () { + public get isEmpty (): boolean { return this._slices.length === 0; } - public destroy () { + public destroy (): void { assertIsTrue(this._slices.length === 0, `Can not destroy the allocator since it's not empty.`); assertIsTrue(!this._resource.debugLocking, `Can not destroy the allocator since it's locking.`); this._resource.destroyAllocator(this); } - public debugLock () { + public debugLock (): void { this._resource.debugLock(); } - public debugUnlock () { + public debugUnlock (): void { this._resource.debugUnlock(); } @@ -202,7 +202,7 @@ class SharedStackBasedAllocator { return newSlice; } - public pop () { + public pop (): void { const { _slices: slices, _slicesPerPage: slicesPerPage, @@ -241,7 +241,7 @@ export class SharedStackBasedAllocatorManager { assertIsTrue(_thresholds.every((v, i, arr) => i === 0 || v > arr[i - 1])); } - public get isEmpty () { + public get isEmpty (): boolean { return this._stacks.size === 0; } @@ -262,7 +262,7 @@ export class SharedStackBasedAllocatorManager { return stack.createAllocator(allocationPageSize); } - public [onStackPurgedTag] (stack: PagedStack) { + public [onStackPurgedTag] (stack: PagedStack): void { let stackFound = false; for (const [k, v] of this._stacks) { if (v === stack) { @@ -278,7 +278,7 @@ export class SharedStackBasedAllocatorManager { private _stacks = new Map(); - private _selectStackPageSize (allocationPageSize: number) { + private _selectStackPageSize (allocationPageSize: number): number { let thresholdIndex = binarySearchEpsilon(this._thresholds, allocationPageSize); let stackPageSize = allocationPageSize; if (thresholdIndex >= 0) { diff --git a/cocos/animation/core/transform-array.ts b/cocos/animation/core/transform-array.ts index 8b3e815d7a9..607b21a841a 100644 --- a/cocos/animation/core/transform-array.ts +++ b/cocos/animation/core/transform-array.ts @@ -14,7 +14,7 @@ const SCALE_OFFSET = ROTATION_OFFSET + 4; * Array-buffer-based transform array. */ export class TransformArray { - public static get BYTES_PER_ELEMENT () { + public static get BYTES_PER_ELEMENT (): number { return TRANSFORM_STRIDE_IN_BYTES; } @@ -36,23 +36,23 @@ export class TransformArray { } } - get buffer () { + get buffer (): ArrayBufferLike { return this._data.buffer; } - get byteLength () { + get byteLength (): number { return this._data.byteLength; } - get byteOffset () { + get byteOffset (): number { return this._data.byteOffset; } - get length () { + get length (): number { return this._data.length / TRANSFORM_STRIDE_IN_FLOATS; } - public getTransform (index: number, out: Transform) { + public getTransform (index: number, out: Transform): Transform { const { _data: data, } = this; @@ -68,7 +68,7 @@ export class TransformArray { return out; } - public getPosition (index: number, out: Vec3) { + public getPosition (index: number, out: Vec3): Vec3 { const { _data: data, } = this; @@ -77,7 +77,7 @@ export class TransformArray { return out; } - public getRotation (index: number, out: Quat) { + public getRotation (index: number, out: Quat): Quat { const { _data: data, } = this; @@ -86,7 +86,7 @@ export class TransformArray { return out; } - public getScale (index: number, out: Vec3) { + public getScale (index: number, out: Vec3): Vec3 { const { _data: data, } = this; @@ -95,7 +95,7 @@ export class TransformArray { return out; } - public setTransform (index: number, value: Readonly) { + public setTransform (index: number, value: Readonly): void { const { _data: data, } = this; @@ -110,7 +110,7 @@ export class TransformArray { Vec3.toArray(data, scale, baseOffset + SCALE_OFFSET); } - public setPosition (index: number, value: Readonly) { + public setPosition (index: number, value: Readonly): void { const { _data: data, } = this; @@ -118,7 +118,7 @@ export class TransformArray { Vec3.toArray(data, value, baseOffset); } - public setRotation (index: number, value: Readonly) { + public setRotation (index: number, value: Readonly): void { const { _data: data, } = this; @@ -126,7 +126,7 @@ export class TransformArray { Quat.toArray(data, value, baseOffset + ROTATION_OFFSET); } - public setScale (index: number, value: Readonly) { + public setScale (index: number, value: Readonly): void { const { _data: data, } = this; @@ -138,7 +138,7 @@ export class TransformArray { * Same algorithm as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/copyWithin * except for the the operating objects are transforms. */ - public copyWithin (target: number, start: number, end?: number) { + public copyWithin (target: number, start: number, end?: number): void { this._data.copyWithin( target * TRANSFORM_STRIDE_IN_FLOATS, start * TRANSFORM_STRIDE_IN_FLOATS, @@ -150,7 +150,7 @@ export class TransformArray { * Same algorithm as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/fill * except for the the operating objects are transforms. */ - public fill (value: Readonly, start?: number, end?: number) { + public fill (value: Readonly, start?: number, end?: number): void { const { length } = this; start ??= 0; end ??= length; @@ -166,7 +166,7 @@ export class TransformArray { /** * Same as `this.fill(Transform.ZERO, start, end)`. */ - public fillZero (start?: number, end?: number) { + public fillZero (start?: number, end?: number): void { this._data.fill( 0.0, typeof start === 'number' ? start * TRANSFORM_STRIDE_IN_FLOATS : undefined, @@ -180,7 +180,7 @@ export class TransformArray { * - the the operating objects are transforms, * - plain array is not allowed. */ - public set (transformArray: Readonly, targetOffset?: number) { + public set (transformArray: Readonly, targetOffset?: number): void { this._data.set( (transformArray as TransformArray)._data, typeof targetOffset === 'number' ? targetOffset * TRANSFORM_STRIDE_IN_FLOATS : undefined, @@ -191,7 +191,7 @@ export class TransformArray { * Same algorithm as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice * except for the the operating objects are transforms. */ - public slice (start?: number, end?: number) { + public slice (start?: number, end?: number): TransformArray { const dataSliced = this._data.slice( typeof start === 'number' ? start * TRANSFORM_STRIDE_IN_FLOATS : undefined, typeof end === 'number' ? end * TRANSFORM_STRIDE_IN_FLOATS : undefined, @@ -209,7 +209,7 @@ export class TransformArray { source: Readonly, sourceOffset: number, size: number, - ) { + ): void { const sizeInFloats = TRANSFORM_STRIDE_IN_FLOATS * size; const targetFloats = this._data; diff --git a/cocos/animation/core/transform.ts b/cocos/animation/core/transform.ts index 5f331b72dcb..fc05acd3851 100644 --- a/cocos/animation/core/transform.ts +++ b/cocos/animation/core/transform.ts @@ -14,7 +14,7 @@ type ReadonlyTransform = Transform; export class Transform { public static IDENTITY = Object.freeze(new Transform()); - public static ZERO = Object.freeze((() => { + public static ZERO = Object.freeze(((): Transform => { const transform = new Transform(); Vec3.copy(transform._position, Vec3.ZERO); Quat.set(transform._rotation, 0.0, 0.0, 0.0, 0.0); @@ -46,39 +46,39 @@ export class Transform { Vec3.copy(this._scale, value); } - public static clone (src: ReadonlyTransform) { + public static clone (src: ReadonlyTransform): Transform { const transform = new Transform(); Transform.copy(transform, src); return transform; } - public static setIdentity (out: Transform) { + public static setIdentity (out: Transform): Transform { Vec3.copy(out._position, Vec3.ZERO); Quat.copy(out._rotation, Quat.IDENTITY); Vec3.copy(out._scale, Vec3.ONE); return out; } - public static copy (out: Transform, src: ReadonlyTransform) { + public static copy (out: Transform, src: ReadonlyTransform): Transform { Vec3.copy(out._position, src._position); Quat.copy(out._rotation, src._rotation); Vec3.copy(out._scale, src._scale); return out; } - public static equals (a: ReadonlyTransform, b: ReadonlyTransform, epsilon?: number) { + public static equals (a: ReadonlyTransform, b: ReadonlyTransform, epsilon?: number): boolean { return Vec3.equals(a._position, b._position, epsilon) && Quat.equals(a._rotation, b._rotation, epsilon) && Vec3.equals(a._scale, b._scale, epsilon); } - public static strictEquals (a: ReadonlyTransform, b: ReadonlyTransform) { + public static strictEquals (a: ReadonlyTransform, b: ReadonlyTransform):boolean { return Vec3.strictEquals(a._position, b._position) && Quat.strictEquals(a._rotation, b._rotation) && Vec3.strictEquals(a._scale, b._scale); } - public static lerp (out: Transform, from: ReadonlyTransform, to: ReadonlyTransform, t: number) { + public static lerp (out: Transform, from: ReadonlyTransform, to: ReadonlyTransform, t: number): Transform { if (t === 0.0) { return Transform.copy(out, from); } @@ -104,7 +104,7 @@ export class Transform { * - The scale should be uniformed, ie. all components should be the same. * - Each component of the scale shall be non-negative. */ - public static multiply (out: Transform, second: ReadonlyTransform, first: ReadonlyTransform) { + public static multiply (out: Transform, second: ReadonlyTransform, first: ReadonlyTransform): Transform { // May reference to https://zhuanlan.zhihu.com/p/119066087 // for the reason about restrictions on uniform scales. @@ -138,10 +138,10 @@ export class Transform { * * Same restriction is applied to this method like `Transform.multiply`. */ - public static calculateRelative = (() => { + public static calculateRelative = ((): (out: Transform, first: ReadonlyTransform, second: ReadonlyTransform) => Transform => { const cacheInvRotation = new Quat(); const cacheInvScale = new Vec3(); - return (out: Transform, first: ReadonlyTransform, second: ReadonlyTransform) => { + return (out: Transform, first: ReadonlyTransform, second: ReadonlyTransform): Transform => { const invSecondRotation = Quat.invert(cacheInvRotation, second._rotation); const invScale = invScaleOrZero(cacheInvScale, second._scale, EPSILON); @@ -163,7 +163,7 @@ export class Transform { * @param out Out transform. * @param transform Transform to invert. */ - public static invert (out: Transform, transform: ReadonlyTransform) { + public static invert (out: Transform, transform: ReadonlyTransform): Transform { const { _rotation: invRotation, _scale: invScale, @@ -199,7 +199,7 @@ export class Transform { return out; } - public static fromMatrix (out: Transform, matrix: Readonly) { + public static fromMatrix (out: Transform, matrix: Readonly): Transform { Mat4.toSRT( matrix, out._rotation, @@ -209,7 +209,7 @@ export class Transform { return out; } - public static toMatrix (out: Mat4, transform: ReadonlyTransform) { + public static toMatrix (out: Mat4, transform: ReadonlyTransform): Mat4 { return Mat4.fromSRT( out, transform._rotation, @@ -228,7 +228,7 @@ export class Transform { /** * Invert each component of scale if it isn't close to zero, or set it to zero otherwise. */ -function invScaleOrZero (out: Vec3, scale: Readonly, epsilon: number) { +function invScaleOrZero (out: Vec3, scale: Readonly, epsilon: number): Vec3 { const { x, y, z } = scale; return Vec3.set( out, @@ -238,16 +238,16 @@ function invScaleOrZero (out: Vec3, scale: Readonly, epsilon: number) { ); } -export function __calculateDeltaTransform (out: Transform, target: Readonly, base: Readonly) { +export function __calculateDeltaTransform (out: Transform, target: Readonly, base: Readonly): Transform { Vec3.subtract(out.position, target.position, base.position); deltaQuat(out.rotation, base.rotation, target.rotation); Vec3.subtract(out.scale, target.scale, base.scale); return out; } -export const __applyDeltaTransform = (() => { +export const __applyDeltaTransform = ((): (out: Transform, base: Readonly, delta: Readonly, alpha: number) => Transform => { const cacheQuat = new Quat(); - return (out: Transform, base: Readonly, delta: Readonly, alpha: number) => { + return (out: Transform, base: Readonly, delta: Readonly, alpha: number): Transform => { Vec3.scaleAndAdd(out.position, base.position, delta.position, alpha); const weightedDeltaRotation = Quat.slerp(cacheQuat, Quat.IDENTITY, delta.rotation, alpha); Quat.multiply(out.rotation, weightedDeltaRotation, base.rotation); @@ -262,15 +262,15 @@ export const __applyDeltaTransform = (() => { * @param from * @param to */ -const deltaQuat = (() => { +const deltaQuat = ((): (out: Quat, from: Quat, to: Quat) => Quat => { const quatMultiInvInverseCache = new Quat(); - return (out: Quat, from: Quat, to: Quat) => { + return (out: Quat, from: Quat, to: Quat): Quat => { const fromInv = Quat.invert(quatMultiInvInverseCache, from); return Quat.multiply(out, to, fromInv); }; })(); -export const ZERO_DELTA_TRANSFORM = Object.freeze((() => { +export const ZERO_DELTA_TRANSFORM = Object.freeze(((): Transform => { const transform = new Transform(); transform.position = Vec3.ZERO; transform.rotation = Quat.IDENTITY; diff --git a/cocos/animation/cross-fade.ts b/cocos/animation/cross-fade.ts index 0276134c3ef..fb315a4ee7a 100644 --- a/cocos/animation/cross-fade.ts +++ b/cocos/animation/cross-fade.ts @@ -55,7 +55,7 @@ export class CrossFade extends Playable { this._scheduler = scheduler ?? getGlobalAnimationManager(); } - public update (deltaTime: number) { + public update (deltaTime: number): void { if (this.isMotionless) { return; } @@ -82,7 +82,7 @@ export class CrossFade extends Playable { * @param state 指定的动画状态。 * @param duration 切换时间。 */ - public crossFade (state: AnimationState | null, duration: number) { + public crossFade (state: AnimationState | null, duration: number): void { if (this._managedStates.length === 0) { // If we are cross fade from a "initial" pose, // we do not use the duration. @@ -116,7 +116,7 @@ export class CrossFade extends Playable { } } - public clear () { + public clear (): void { for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; if (state) { @@ -127,7 +127,7 @@ export class CrossFade extends Playable { this._fadings.length = 0; } - protected onPlay () { + protected onPlay (): void { super.onPlay(); this._scheduleThis(); } @@ -135,7 +135,7 @@ export class CrossFade extends Playable { /** * 停止我们淡入淡出的所有动画状态并停止淡入淡出。 */ - protected onPause () { + protected onPause (): void { super.onPause(); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; @@ -149,7 +149,7 @@ export class CrossFade extends Playable { /** * 恢复我们淡入淡出的所有动画状态并继续淡入淡出。 */ - protected onResume () { + protected onResume (): void { super.onResume(); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; @@ -163,12 +163,12 @@ export class CrossFade extends Playable { /** * 停止所有淡入淡出的动画状态。 */ - protected onStop () { + protected onStop (): void { super.onStop(); this.clear(); } - private _calculateWeights (deltaTime: number) { + private _calculateWeights (deltaTime: number): void { const managedStates = this._managedStates; const fadings = this._fadings; @@ -217,14 +217,14 @@ export class CrossFade extends Playable { } } - private _scheduleThis () { + private _scheduleThis (): void { if (!this._scheduled) { this._scheduler.addCrossFade(this); this._scheduled = true; } } - private _unscheduleThis () { + private _unscheduleThis (): void { if (this._scheduled) { this._scheduler.removeCrossFade(this); this._scheduled = false; diff --git a/cocos/animation/cubic-spline-value.ts b/cocos/animation/cubic-spline-value.ts index 9de508f8ebb..b1f496031ef 100644 --- a/cocos/animation/cubic-spline-value.ts +++ b/cocos/animation/cubic-spline-value.ts @@ -65,7 +65,7 @@ function makeCubicSplineValueConstructor ( this.outTangent = outTangent || new ConstructorX(); } - public lerp (to: CubicSplineValueClass, t: number, dt: number) { + public lerp (to: CubicSplineValueClass, t: number, dt: number):T { const p0 = this.dataPoint; const p1 = to.dataPoint; // dt => t_k+1 - t_k @@ -84,7 +84,7 @@ function makeCubicSplineValueConstructor ( return tempValue; } - public getNoLerp () { + public getNoLerp (): T { return this.dataPoint; } } @@ -93,7 +93,7 @@ function makeCubicSplineValueConstructor ( // Tracking issue: https://github.com/cocos/cocos-engine/issues/14640 if (ConstructorX as any === Quat) { const lerp = CubicSplineValueClass.prototype.lerp; - CubicSplineValueClass.prototype.lerp = function (this: CubicSplineValueClass, to: CubicSplineValueClass, t: number, dt: number) { + CubicSplineValueClass.prototype.lerp = function (this: CubicSplineValueClass, to: CubicSplineValueClass, t: number, dt: number): Quat { const result = lerp.call(this, to, t, dt) as Quat; Quat.normalize(result, result); return result; @@ -166,7 +166,7 @@ export class CubicSplineNumberValue implements ICubicSplineValue { this.outTangent = outTangent; } - public lerp (to: CubicSplineNumberValue, t: number, dt: number) { + public lerp (to: CubicSplineNumberValue, t: number, dt: number): number { const p0 = this.dataPoint; const p1 = to.dataPoint; // dt => t_k+1 - t_k @@ -181,7 +181,7 @@ export class CubicSplineNumberValue implements ICubicSplineValue { return p0 * f_0 + m0 * f_1 + p1 * f_2 + m1 * f_3; } - public getNoLerp () { + public getNoLerp (): number { return this.dataPoint; } } diff --git a/cocos/animation/embedded-player/embedded-animation-clip-player.ts b/cocos/animation/embedded-player/embedded-animation-clip-player.ts index 8129163ea66..0f86bd4a49e 100644 --- a/cocos/animation/embedded-player/embedded-animation-clip-player.ts +++ b/cocos/animation/embedded-player/embedded-animation-clip-player.ts @@ -56,7 +56,7 @@ export class EmbeddedAnimationClipPlayable extends EmbeddedPlayable { @serializable public clip: AnimationClip | null = null; - public instantiate (root: Node) { + public instantiate (root: Node): EmbeddedAnimationClipPlayableState | null { const { clip, path } = this; if (!clip) { return null; diff --git a/cocos/animation/embedded-player/embedded-particle-system-player.ts b/cocos/animation/embedded-player/embedded-particle-system-player.ts index 95c064d3c30..f0777e35745 100644 --- a/cocos/animation/embedded-player/embedded-particle-system-player.ts +++ b/cocos/animation/embedded-player/embedded-particle-system-player.ts @@ -46,7 +46,7 @@ export class EmbeddedParticleSystemPlayable extends EmbeddedPlayable { @serializable public path = ''; - public instantiate (root: Node) { + public instantiate (root: Node): EmbeddedParticleSystemPlayableState | null { const node = root.getChildByPath(this.path); if (!node) { warn(`Hierarchy path ${this.path} does not exists.`); diff --git a/cocos/animation/embedded-player/embedded-player.ts b/cocos/animation/embedded-player/embedded-player.ts index b82766acd2c..e9ff0e6a5b4 100644 --- a/cocos/animation/embedded-player/embedded-player.ts +++ b/cocos/animation/embedded-player/embedded-player.ts @@ -89,7 +89,7 @@ export abstract class EmbeddedPlayableState { * @en * Indicates if this player can be adjusted to any time. */ - public get randomAccess () { + public get randomAccess (): boolean { return this._randomAccess; } @@ -134,7 +134,7 @@ export abstract class EmbeddedPlayableState { */ public abstract setSpeed(speed: number): void; - public setTime (_time: number) { + public setTime (_time: number): void { } private declare _randomAccess: boolean; diff --git a/cocos/animation/event/event-emitter.ts b/cocos/animation/event/event-emitter.ts index 80229220469..583895e75a6 100644 --- a/cocos/animation/event/event-emitter.ts +++ b/cocos/animation/event/event-emitter.ts @@ -8,7 +8,7 @@ import { Node } from '../../scene-graph'; * @param methodName The method name to invoke. * @param args The arguments passed to the method. */ -export function invokeComponentMethodsEngagedInAnimationEvent (node: Node, methodName: string, ...args: unknown[]) { +export function invokeComponentMethodsEngagedInAnimationEvent (node: Node, methodName: string, ...args: unknown[]): void { const components = node.components; const nComponents = components.length; for (let iComponent = 0; iComponent < nComponents; ++iComponent) { diff --git a/cocos/animation/exotic-animation/exotic-animation.ts b/cocos/animation/exotic-animation/exotic-animation.ts index ada988a09ff..5d8433f91b6 100644 --- a/cocos/animation/exotic-animation/exotic-animation.ts +++ b/cocos/animation/exotic-animation/exotic-animation.ts @@ -49,25 +49,25 @@ function throwIfSplitMethodIsNotValid (): never { */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticAnimation`) export class ExoticAnimation { - public createEvaluator (binder: Binder) { + public createEvaluator (binder: Binder): ExoticTrsAnimationEvaluator { return new ExoticTrsAnimationEvaluator(this._nodeAnimations, binder); } - public createEvaluatorForAnimationGraph (context: AnimationClipGraphBindingContext) { + public createEvaluatorForAnimationGraph (context: AnimationClipGraphBindingContext): ExoticTrsAGEvaluation { return new ExoticTrsAGEvaluation(this._nodeAnimations, context); } - public addNodeAnimation (path: string) { + public addNodeAnimation (path: string): ExoticNodeAnimation { const nodeAnimation = new ExoticNodeAnimation(path); this._nodeAnimations.push(nodeAnimation); return nodeAnimation; } - public collectAnimatedJoints () { + public collectAnimatedJoints (): string[] { return Array.from(new Set(this._nodeAnimations.map(({ path }) => path))); } - public split (from: number, to: number) { + public split (from: number, to: number): ExoticAnimation { if (!SPLIT_METHOD_ENABLED) { return throwIfSplitMethodIsNotValid(); } @@ -82,7 +82,7 @@ export class ExoticAnimation { /** * @internal */ - public toHashString () { + public toHashString (): string { return this._nodeAnimations.map((nodeAnimation) => nodeAnimation.toHashString()).join('\n'); } @@ -96,19 +96,19 @@ class ExoticNodeAnimation { this._path = path; } - public createPosition (times: FloatArray, values: FloatArray) { + public createPosition (times: FloatArray, values: FloatArray): void { this._position = new ExoticTrack(times, new ExoticVec3TrackValues(values)); } - public createRotation (times: FloatArray, values: FloatArray) { + public createRotation (times: FloatArray, values: FloatArray): void { this._rotation = new ExoticTrack(times, new ExoticQuatTrackValues(values)); } - public createScale (times: FloatArray, values: FloatArray) { + public createScale (times: FloatArray, values: FloatArray): void { this._scale = new ExoticTrack(times, new ExoticVec3TrackValues(values)); } - public createEvaluator (binder: Binder) { + public createEvaluator (binder: Binder): ExoticNodeAnimationEvaluator { return new ExoticNodeAnimationEvaluator( this._path, this._position, @@ -118,7 +118,7 @@ class ExoticNodeAnimation { ); } - public createEvaluatorForAnimationGraph (context: AnimationClipGraphBindingContext) { + public createEvaluatorForAnimationGraph (context: AnimationClipGraphBindingContext): ExoticNodeAnimationAGEvaluation | null { const transformHandle = context.bindTransform(this._path); if (!transformHandle) { return null; @@ -131,7 +131,7 @@ class ExoticNodeAnimation { ); } - public split (from: number, to: number, splitInfoCache: SplitInfo) { + public split (from: number, to: number, splitInfoCache: SplitInfo): ExoticNodeAnimation { if (!SPLIT_METHOD_ENABLED) { return throwIfSplitMethodIsNotValid(); } @@ -154,7 +154,7 @@ class ExoticNodeAnimation { return newAnimation; } - get path () { + get path (): string { return this._path; } @@ -186,7 +186,7 @@ function floatToHashString (value: number): string { return value.toPrecision(2); } -function floatArrayToHashString (values: FloatArray) { +function floatArrayToHashString (values: FloatArray): string { return (values).map((v: number) => Number.parseFloat(floatToHashString(v))).join(' '); } @@ -212,13 +212,13 @@ class ExoticVectorLikeTrackValues { this._isQuantized = false; } - get precision () { + get precision (): FloatPrecision { return this._isQuantized ? (this._values as QuantizedFloatArray).originalPrecision : getFloatArrayPrecision(this._values as FloatArray); } - public quantize (type: QuantizationType) { + public quantize (type: QuantizationType): void { assertIsTrue(!this._isQuantized); this._values = quantize(this._values as FloatArray, type); this._isQuantized = true; @@ -245,7 +245,7 @@ class ExoticVectorLikeTrackValues { @ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticVec3TrackValues`) class ExoticVec3TrackValues extends ExoticVectorLikeTrackValues implements ExoticTrackValues { - public static imitate (values: FloatArray, model: ExoticVec3TrackValues) { + public static imitate (values: FloatArray, model: ExoticVec3TrackValues): ExoticVec3TrackValues { const trackValues = new ExoticVec3TrackValues(values); if (model._isQuantized) { trackValues.quantize((model._values as QuantizedFloatArray).quantizationType); @@ -290,7 +290,7 @@ class ExoticVec3TrackValues extends ExoticVectorLikeTrackValues implements Exoti @ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticQuatTrackValues`) class ExoticQuatTrackValues extends ExoticVectorLikeTrackValues implements ExoticTrackValues { - public static imitate (values: FloatArray, model: ExoticQuatTrackValues) { + public static imitate (values: FloatArray, model: ExoticQuatTrackValues): ExoticQuatTrackValues { const trackValues = new ExoticQuatTrackValues(values); if (model._isQuantized) { trackValues.quantize((model._values as QuantizedFloatArray).quantizationType); @@ -359,7 +359,7 @@ type ExoticVec3Track = ExoticTrack; type ExoticQuatTrack = ExoticTrack; -function splitVec3Track (track: ExoticVec3Track, from: number, to: number, splitInfoCache: SplitInfo) { +function splitVec3Track (track: ExoticVec3Track, from: number, to: number, splitInfoCache: SplitInfo): ExoticTrack { const { times, values } = split( track.times, track.values, @@ -377,7 +377,7 @@ function splitVec3Track (track: ExoticVec3Track, from: number, to: number, split ); } -function splitQuatTrack (track: ExoticQuatTrack, from: number, to: number, splitInfoCache: SplitInfo) { +function splitQuatTrack (track: ExoticQuatTrack, from: number, to: number, splitInfoCache: SplitInfo): ExoticTrack { const { times, values } = split( track.times, track.values, @@ -442,7 +442,7 @@ function split ( const resultValue = new ValueConstructor(); const newTimes: FloatArray = new TimeArrayConstructor(nNewKeyframes); const newValues: FloatArray = new ValueArrayConstructor(components * nNewKeyframes); - const doLerp = (index: number, ratio: number, outputIndex: number) => { + const doLerp = (index: number, ratio: number, outputIndex: number): void => { assertIsTrue(index < times.length - 1); const iPrevious = index; const iNext = index + 1; @@ -492,7 +492,7 @@ class SplitInfo { this._reset(); } - public get keyframesCount () { + public get keyframesCount (): number { const { preLerpIndex, directKeyframesBegin, @@ -505,7 +505,7 @@ class SplitInfo { + (postLerpIndex < 0 ? 0 : 1); } - public calculate (times: ArrayLike, from: number, to: number) { + public calculate (times: ArrayLike, from: number, to: number): void { this._reset(); if (from > to) { @@ -573,7 +573,7 @@ class SplitInfo { } } - private _reset () { + private _reset (): void { this.preLerpIndex = -1; this.preLerpRatio = 0.0; this.directKeyframesBegin = 0; @@ -583,7 +583,7 @@ class SplitInfo { } } -function binarySearchRatio (values: ArrayLike, value: number) { +function binarySearchRatio (values: ArrayLike, value: number): { index: number; ratio: number; } { const nValues = values.length; assertIsTrue(values.length !== 0); let resultIndex = 0; @@ -608,7 +608,7 @@ class ExoticTrsAnimationEvaluator { this._nodeEvaluations = nodeAnimations.map((nodeAnimation) => nodeAnimation.createEvaluator(binder)); } - public evaluate (time: number) { + public evaluate (time: number): void { this._nodeEvaluations.forEach((nodeEvaluator) => { nodeEvaluator.evaluate(time); }); @@ -642,7 +642,7 @@ class ExoticNodeAnimationEvaluator { } } - public evaluate (time: number) { + public evaluate (time: number): void { if (this._position) { const value = this._position.evaluator.evaluate(time); this._position.runtimeBinding.setValue(value); @@ -671,7 +671,7 @@ class ExoticTrackEvaluator { this._resultValue = new ValueConstructor(); } - public evaluate (time: number) { + public evaluate (time: number): TValue { const { _times: times, _values: values, @@ -729,7 +729,7 @@ export class ExoticTrsAGEvaluation { ).filter((x) => !!x) as ExoticNodeAnimationAGEvaluation[]; } - public destroy () { + public destroy (): void { const { _nodeEvaluations: nodeEvaluations } = this; const nNodeEvaluations = nodeEvaluations.length; for (let iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) { @@ -737,7 +737,7 @@ export class ExoticTrsAGEvaluation { } } - public evaluate (time: number, pose: Pose) { + public evaluate (time: number, pose: Pose): void { const { _nodeEvaluations: nodeEvaluations } = this; const nNodeEvaluations = nodeEvaluations.length; for (let iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) { @@ -767,11 +767,11 @@ class ExoticNodeAnimationAGEvaluation { } } - public destroy () { + public destroy (): void { this._transformHandle.destroy(); } - public evaluate (time: number, pose: Pose) { + public evaluate (time: number, pose: Pose): void { const { _transformHandle: { index: transformIndex, @@ -810,7 +810,7 @@ interface InputSampleResult { ratio: number; } -function sampleInput (values: FloatArray, time: number, result: InputSampleResult) { +function sampleInput (values: FloatArray, time: number, result: InputSampleResult): InputSampleResult { const nFrames = values.length; assertIsTrue(nFrames !== 0); @@ -866,7 +866,7 @@ enum FloatPrecision { FLOAT_64, } -function getFloatArrayPrecision (array: FloatArray) { +function getFloatArrayPrecision (array: FloatArray): FloatPrecision { switch (array.BYTES_PER_ELEMENT) { default: assertIsTrue(false); @@ -878,7 +878,7 @@ function getFloatArrayPrecision (array: FloatArray) { } } -function getFloatArrayConstructorWithPrecision (precision: FloatPrecision) { +function getFloatArrayConstructorWithPrecision (precision: FloatPrecision): Float32ArrayConstructor | Float64ArrayConstructor { switch (precision) { default: assertIsTrue(false); @@ -931,7 +931,7 @@ class QuantizedFloatArray { } } -function quantize (values: FloatArray, type: QuantizationType) { +function quantize (values: FloatArray, type: QuantizationType): QuantizedFloatArray { const TypedArrayViewConstructor = QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP[type]; const MAX = 1 << TypedArrayViewConstructor.BYTES_PER_ELEMENT; let min = Number.POSITIVE_INFINITY; @@ -946,7 +946,7 @@ function quantize (values: FloatArray, type: QuantizationType) { return new QuantizedFloatArray(getFloatArrayPrecision(values), normalized, extent, min); } -function indexQuantized (quantized: QuantizedFloatArray, index: number) { +function indexQuantized (quantized: QuantizedFloatArray, index: number): number { const quantizedValue = quantized.values[index]; const MAX_VALUE = 1 << quantized.values.BYTES_PER_ELEMENT; return quantizedValue / MAX_VALUE * quantized.extent + quantized.min; @@ -959,7 +959,7 @@ function createExoticTrackEvaluationRecord ( path: string, property: 'position' | 'scale' | 'rotation', binder: Binder, -) { +): ExoticTrackEvaluationRecord | null { const trackBinding = new TrackBinding(); trackBinding.path = new TrackPath().toHierarchy(path).toProperty(property); const runtimeBinding = binder(trackBinding); @@ -973,7 +973,7 @@ function createExoticTrackEvaluationRecord ( } as ExoticTrackEvaluationRecord; } -function loadVec3FromQuantized (values: QuantizedFloatArray, index: number, out: Vec3) { +function loadVec3FromQuantized (values: QuantizedFloatArray, index: number, out: Vec3): void { Vec3.set( out, indexQuantized(values, 3 * index + 0), @@ -982,7 +982,7 @@ function loadVec3FromQuantized (values: QuantizedFloatArray, index: number, out: ); } -function loadQuatFromQuantized (values: QuantizedFloatArray, index: number, out: Quat) { +function loadQuatFromQuantized (values: QuantizedFloatArray, index: number, out: Quat): void { Quat.set( out, indexQuantized(values, 4 * index + 0), diff --git a/cocos/animation/global-animation-manager.ts b/cocos/animation/global-animation-manager.ts index 839d834bc43..14f80fa981e 100644 --- a/cocos/animation/global-animation-manager.ts +++ b/cocos/animation/global-animation-manager.ts @@ -25,7 +25,7 @@ import { cclegacy } from '../core'; import type { AnimationManager } from './animation-manager'; -export function getGlobalAnimationManager () { +export function getGlobalAnimationManager (): AnimationManager { const animationManager = cclegacy.director.getAnimationManager() as AnimationManager; return animationManager; } diff --git a/cocos/animation/legacy-clip-data.ts b/cocos/animation/legacy-clip-data.ts index 48d2efd7df4..51f5af42cbe 100644 --- a/cocos/animation/legacy-clip-data.ts +++ b/cocos/animation/legacy-clip-data.ts @@ -154,7 +154,7 @@ export class AnimationClipLegacyData { this._duration = duration; } - get keys () { + get keys (): number[][] { return this._keys; } @@ -162,7 +162,7 @@ export class AnimationClipLegacyData { this._keys = value; } - get curves () { + get curves (): LegacyClipCurve[] { return this._curves; } @@ -171,7 +171,7 @@ export class AnimationClipLegacyData { delete this._runtimeCurves; } - get commonTargets () { + get commonTargets (): LegacyCommonTarget[] { return this._commonTargets; } @@ -182,7 +182,7 @@ export class AnimationClipLegacyData { /** * 此动画的数据。 */ - get data () { + get data (): Uint8Array | null { return this._data; } @@ -193,7 +193,7 @@ export class AnimationClipLegacyData { return this._runtimeCurves!; } - public toTracks () { + public toTracks (): Track[] { const newTracks: Track[] = []; const { @@ -202,7 +202,7 @@ export class AnimationClipLegacyData { commonTargets: legacyCommonTargets, } = this; - const convertTrackPath = (track: Track, modifiers: TargetPath[], valueAdapter: IValueProxyFactory | undefined) => { + const convertTrackPath = (track: Track, modifiers: TargetPath[], valueAdapter: IValueProxyFactory | undefined): void => { const trackPath = new TrackPath(); for (const modifier of modifiers) { if (typeof modifier === 'string') { @@ -245,7 +245,7 @@ export class AnimationClipLegacyData { assertIsTrue(typeof legacyCurveData._arrayLength !== 'number' || typeof firstValue === 'number'); const legacyEasingMethodConverter = new LegacyEasingMethodConverter(legacyCurveData, times.length); - const installPathAndSetter = (track: Track) => { + const installPathAndSetter = (track: Track): void => { convertTrackPath(track, legacyCurve.modifiers, legacyCurve.valueAdapter); }; @@ -267,7 +267,7 @@ export class AnimationClipLegacyData { legacyCommonTargetCurve = curve; } - const convertCurve = () => { + const convertCurve = (): void => { if (typeof firstValue === 'number') { if (!legacyValues.every((value) => typeof value === 'number')) { warnID(3934); @@ -455,7 +455,7 @@ export class AnimationClipLegacyData { private _duration: number; - protected _createPropertyCurves () { + protected _createPropertyCurves (): void { this._ratioSamplers = this._keys.map( (keys) => new RatioSampler( keys.map( @@ -518,11 +518,11 @@ class LegacyEasingMethodConverter { } } - get nil () { + get nil (): boolean { return !this._easingMethods || this._easingMethods.every((easingMethod) => easingMethod === null || easingMethod === undefined); } - public convert (curve: RealCurve) { + public convert (curve: RealCurve): void { const { _easingMethods: easingMethods } = this; if (!easingMethods) { return; @@ -562,7 +562,7 @@ class LegacyEasingMethodConverter { } } - public convertQuatCurve (curve: QuatCurve) { + public convertQuatCurve (curve: QuatCurve): void { const { _easingMethods: easingMethods } = this; if (!easingMethods) { return; @@ -605,7 +605,7 @@ function applyLegacyEasingMethodName ( easingMethodName: LegacyEasingMethodName, curve: RealCurve, keyframeIndex: number, -) { +): void { assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1); assertIsTrue(easingMethodName in easingMethodNameMap); const keyframeValue = curve.getKeyframeValue(keyframeIndex); @@ -622,7 +622,7 @@ function applyLegacyEasingMethodNameIntoQuatCurve ( easingMethodName: LegacyEasingMethodName, curve: QuatCurve, keyframeIndex: number, -) { +): void { assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1); assertIsTrue(easingMethodName in easingMethodNameMap); const keyframeValue = curve.getKeyframeValue(keyframeIndex); @@ -694,7 +694,7 @@ export function timeBezierToTangents ( previousKeyframe: RealKeyframeValue, nextTime: number, nextKeyframe: RealKeyframeValue, -) { +): void { const [p1X, p1Y, p2X, p2Y] = timeBezierPoints; const { value: previousValue } = previousKeyframe; const { value: nextValue } = nextKeyframe; @@ -720,7 +720,7 @@ export function timeBezierToTangents ( nextKeyframe.leftTangentWeight = nextTangentWeight; } -function ensureLeftTangentWeightMode (tangentWeightMode: TangentWeightMode) { +function ensureLeftTangentWeightMode (tangentWeightMode: TangentWeightMode): TangentWeightMode { if (tangentWeightMode === TangentWeightMode.NONE) { return TangentWeightMode.LEFT; } else if (tangentWeightMode === TangentWeightMode.RIGHT) { @@ -730,7 +730,7 @@ function ensureLeftTangentWeightMode (tangentWeightMode: TangentWeightMode) { } } -function ensureRightTangentWeightMode (tangentWeightMode: TangentWeightMode) { +function ensureRightTangentWeightMode (tangentWeightMode: TangentWeightMode): TangentWeightMode { if (tangentWeightMode === TangentWeightMode.NONE) { return TangentWeightMode.RIGHT; } else if (tangentWeightMode === TangentWeightMode.LEFT) { diff --git a/cocos/animation/marionette/animation-controller.ts b/cocos/animation/marionette/animation-controller.ts index f451efc9813..12a3e1e0ff2 100644 --- a/cocos/animation/marionette/animation-controller.ts +++ b/cocos/animation/marionette/animation-controller.ts @@ -29,7 +29,7 @@ import type { AnimationGraphRunTime } from './animation-graph'; import { EventTarget, _decorator, assertIsNonNullable, assertIsTrue, warn } from '../../core'; import { AnimationGraphEval } from './graph-eval'; import type { MotionStateStatus, TransitionStatus, ClipStatus } from './state-machine/state-machine-eval'; -import { PrimitiveValue, Value } from './variable'; +import { PrimitiveValue, Value, VariableType } from './variable'; import { AnimationGraphVariant, AnimationGraphVariantRunTime } from './animation-graph-variant'; import { AnimationGraphLike } from './animation-graph-like'; import type { ReadonlyClipOverrideMap } from './clip-overriding'; @@ -64,7 +64,7 @@ export class AnimationController extends Component { */ @type(AnimationGraphLike) @editable - public get graph () { + public get graph (): AnimationGraphRunTime | AnimationGraphVariantRunTime | null { return this._graph; } @@ -83,11 +83,11 @@ export class AnimationController extends Component { * @en Gets the count of layers in the animation graph. * If no animation graph is specified, 0 is returned. */ - public get layerCount () { + public get layerCount (): number { return this._graphEval?.layerCount ?? 0; } - public __preload () { + public __preload (): void { const { graph } = this; if (graph) { let originalGraph: AnimationGraph; @@ -112,11 +112,11 @@ export class AnimationController extends Component { } } - public onDestroy () { + public onDestroy (): void { this._graphEval?.destroy(); } - public update (deltaTime: number) { + public update (deltaTime: number): void { this._graphEval?.update(deltaTime); } @@ -131,7 +131,9 @@ export class AnimationController extends Component { * } * ``` */ - public getVariables () { + public getVariables (): Iterable]> { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.getVariables(); @@ -149,7 +151,7 @@ export class AnimationController extends Component { * animationController.setValue('attack', true); * ``` */ - public setValue (name: string, value: PrimitiveValue) { + public setValue (name: string, value: PrimitiveValue): void { return this.setValue_experimental(name, value); } @@ -166,7 +168,7 @@ export class AnimationController extends Component { * ``` * @experimental */ - public setValue_experimental (name: string, value: Value) { + public setValue_experimental (name: string, value: Value): void { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); graphEval.setValue(name, value); @@ -210,7 +212,7 @@ export class AnimationController extends Component { * @returns @en The running status of the current state. `null` is returned if current state is not a motion state. * @zh 当前的状态运作状态对象。如果当前的状态不是动作状态,则返回 `null`。 */ - public getCurrentStateStatus (layer: number) { + public getCurrentStateStatus (layer: number): Readonly | null { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.getCurrentStateStatus(layer); @@ -224,7 +226,7 @@ export class AnimationController extends Component { * An empty iterable is returned if current state is not a motion state. * @zh 到动画剪辑运作状态的迭代器。若当前状态不是动画状态,则返回一个空的迭代器。 */ - public getCurrentClipStatuses (layer: number) { + public getCurrentClipStatuses (layer: number): Iterable> { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.getCurrentClipStatuses(layer); @@ -237,7 +239,7 @@ export class AnimationController extends Component { * @returns @en Current transition status. `null` is returned in case of no transition. * @zh 当前正在进行的过渡,若没有进行任何过渡,则返回 `null`。 */ - public getCurrentTransition (layer: number) { + public getCurrentTransition (layer: number): Readonly | null { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.getCurrentTransition(layer); @@ -250,7 +252,7 @@ export class AnimationController extends Component { * @returns @en The running status of the next state. `null` is returned in case of no transition or if next state is not a motion state. * @zh 下一状态运作状态对象,若未在进行过渡或下一状态不是动画状态,则返回 `null`。 */ - public getNextStateStatus (layer: number) { + public getNextStateStatus (layer: number): Readonly | null { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.getNextStateStatus(layer); @@ -264,7 +266,7 @@ export class AnimationController extends Component { * An empty iterable is returned in case of no transition or next state is not a motion state. * @zh 到下一状态上包含的动画剪辑运作状态的迭代器,若未在进行过渡或下一状态不是动画状态,则返回一个空的迭代器。 */ - public getNextClipStatuses (layer: number) { + public getNextClipStatuses (layer: number): Iterable> { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.getNextClipStatuses(layer); @@ -275,7 +277,7 @@ export class AnimationController extends Component { * @en Gets the weight of specified layer. * @param layer @en Index of the layer. @zh 层级索引。 */ - public getLayerWeight (layer: number) { + public getLayerWeight (layer: number): number { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.getLayerWeight(layer); @@ -286,7 +288,7 @@ export class AnimationController extends Component { * @en Sets the weight of specified layer. * @param layer @en Index of the layer. @zh 层级索引。 */ - public setLayerWeight (layer: number, weight: number) { + public setLayerWeight (layer: number, weight: number): void { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); return graphEval.setLayerWeight(layer, weight); @@ -314,7 +316,7 @@ export class AnimationController extends Component { * TODO * @experimental */ - public overrideClips_experimental (overrides: ReadonlyClipOverrideMap) { + public overrideClips_experimental (overrides: ReadonlyClipOverrideMap): void { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); graphEval.overrideClips(overrides); @@ -329,7 +331,7 @@ export class AnimationController extends Component { * or 0 if specified adjoint curve does not exist or if the animation graph is null. * @experimental */ - public getAuxiliaryCurveValue_experimental (curveName: string) { + public getAuxiliaryCurveValue_experimental (curveName: string): number { const { _graphEval: graphEval } = this; if (!graphEval) { return 0.0; diff --git a/cocos/animation/marionette/animation-graph-animation-clip-binding.ts b/cocos/animation/marionette/animation-graph-animation-clip-binding.ts index 03f0f151559..298a61777a5 100644 --- a/cocos/animation/marionette/animation-graph-animation-clip-binding.ts +++ b/cocos/animation/marionette/animation-graph-animation-clip-binding.ts @@ -95,7 +95,7 @@ class PoseBindingBase { /** * Releases the held transform handle. */ - public destroy () { + public destroy (): void { this._transformHandle.destroy(); } @@ -113,7 +113,7 @@ class PosePositionBinding extends PoseBindingBase implements PoseBinding { pose.transforms.setPosition(this._transformHandle.index, value); } - public getValue (pose: Pose) { + public getValue (pose: Pose): Readonly { return pose.transforms.getPosition(this._transformHandle.index, CACHE_VEC3_GET_VALUE) as Readonly; } } @@ -126,7 +126,7 @@ class PoseRotationBinding extends PoseBindingBase implements PoseBinding { pose.transforms.setRotation(this._transformHandle.index, value); } - public getValue (pose: Pose) { + public getValue (pose: Pose): Readonly { return pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE) as Readonly; } } @@ -140,7 +140,7 @@ class PoseEulerAnglesBinding extends PoseBindingBase implements PoseBinding { const q = pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE) as Readonly; return Quat.toEuler(CACHE_VEC3_GET_VALUE, q) as Readonly; } @@ -156,7 +156,7 @@ class PoseScaleBinding extends PoseBindingBase implements PoseBinding { pose.transforms.setScale(this._transformHandle.index, value); } - public getValue (pose: Pose) { + public getValue (pose: Pose): Readonly { return pose.transforms.getScale(this._transformHandle.index, CACHE_VEC3_GET_VALUE) as Readonly; } } @@ -174,7 +174,7 @@ class AuxiliaryCurveBinding implements PoseBinding { pose.auxiliaryCurves[this._handle.index] = value; } - public getValue (pose: Pose) { + public getValue (pose: Pose): number { return pose.auxiliaryCurves[this._handle.index]; } } @@ -213,11 +213,11 @@ class AGTrackEvaluation { this._trackSampler = trackEvaluation; } - public destroy () { + public destroy (): void { this._binding.destroy(); } - public evaluate (time: number, pose: Pose) { + public evaluate (time: number, pose: Pose): void { const { _trackSampler: trackSampler, _binding: binding } = this; const defaultValue = /* binding.getValue && */trackSampler.requiresDefault ? binding.getValue(pose) as TValue extends unknown ? unknown : TValue @@ -230,7 +230,7 @@ class AGTrackEvaluation { private _trackSampler: TrackEval; } -function bindTrackAG (animationClip: AnimationClip, track: Track, bindContext: AnimationClipGraphBindingContext) { +function bindTrackAG (animationClip: AnimationClip, track: Track, bindContext: AnimationClipGraphBindingContext): PoseBinding | undefined { const trackBinding = track[trackBindingTag]; const trackTarget = createRuntimeBindingAG(trackBinding, bindContext); if (DEBUG && !trackTarget) { @@ -247,7 +247,7 @@ function bindTrackAG (animationClip: AnimationClip, track: Track, bindContext: A return trackTarget ?? undefined; } -function createRuntimeBindingAG (track: TrackBinding, bindContext: AnimationClipGraphBindingContext) { +function createRuntimeBindingAG (track: TrackBinding, bindContext: AnimationClipGraphBindingContext): PoseBinding | null | undefined { const { origin, } = bindContext; @@ -266,7 +266,7 @@ function createRuntimeBindingAG (track: TrackBinding, bindContext: AnimationClip } if (resultTarget instanceof Node && isTrsPropertyName(lastPropertyKey)) { - const transformPath = (() => { + const transformPath = ((): string | undefined => { const segments = [] as string[]; let node: Node | null = resultTarget; for (; node && node !== origin; node = node.parent) { @@ -303,7 +303,7 @@ class AuxiliaryCurveEvaluation { * @param time The time. * @param context The evaluation context. */ - public evaluate (time: number, context: AnimationClipGraphEvaluationContext) { + public evaluate (time: number, context: AnimationClipGraphEvaluationContext): void { const { _curve: curve, _binding: binding, @@ -398,7 +398,7 @@ class AnimationClipAGEvaluationRegular implements AnimationClipAGEvaluation { this._auxiliaryCurveEvaluations = auxiliaryCurveEvaluations; } - public destroy () { + public destroy (): void { this._exoticAnimationEvaluation?.destroy(); const { @@ -410,7 +410,7 @@ class AnimationClipAGEvaluationRegular implements AnimationClipAGEvaluation { } } - public evaluate (time: number, context: AnimationGraphEvaluationContext) { + public evaluate (time: number, context: AnimationGraphEvaluationContext): Pose { const { _trackEvaluations: trackEvaluations, _exoticAnimationEvaluation: exoticAnimationEvaluation, @@ -455,7 +455,7 @@ class AnimationClipAGEvaluationAdditive implements AnimationClipAGEvaluation { } } - public destroy () { + public destroy (): void { this._clipEval.destroy(); this._refClipEval?.destroy(); } @@ -465,7 +465,7 @@ class AnimationClipAGEvaluationAdditive implements AnimationClipAGEvaluation { * @param time The time. * @param context The evaluation context. */ - public evaluate (time: number, context: AnimationGraphEvaluationContext) { + public evaluate (time: number, context: AnimationGraphEvaluationContext): Pose { // Evaluate this clip. const pose = this._clipEval.evaluate(time, context); diff --git a/cocos/animation/marionette/animation-graph-context.ts b/cocos/animation/marionette/animation-graph-context.ts index 14cd791ce15..a2aef79cda2 100644 --- a/cocos/animation/marionette/animation-graph-context.ts +++ b/cocos/animation/marionette/animation-graph-context.ts @@ -79,14 +79,14 @@ export class AnimationGraphBindingContext { * The origin node is the origin from where the animation target start to resolve. * It's now definitely the node hosting the running animation controller component. */ - get origin () { + get origin (): Node { return this._origin; } /** * The animation controller component currently running the animation graph. */ - get controller () { + get controller (): AnimationController { return this._controller; } @@ -94,18 +94,18 @@ export class AnimationGraphBindingContext { * A free function to reset specified trigger. * @internal This function should only be accessed by the builtin state machine. */ - get triggerResetter () { + get triggerResetter (): TriggerResetter { return this._triggerResetter; } - get clipOverrides () { + get clipOverrides (): ReadonlyClipOverrideMap | undefined { return this._clipOverrides; } /** * Returns if current context expects to have an additive pose. */ - get additive () { + get additive (): boolean { const { _additiveFlagStack: additiveFlagStack } = this; return additiveFlagStack[additiveFlagStack.length - 1]; } @@ -134,7 +134,7 @@ export class AnimationGraphBindingContext { return boneNode.children.map((childNode) => childNode.name); } - public getParentBoneNameByName (bone: string) { + public getParentBoneNameByName (bone: string): string | null | undefined { const boneNode = findBoneByNameRecursively(this._origin, bone); if (!boneNode) { return null; @@ -158,7 +158,7 @@ export class AnimationGraphBindingContext { * Pushes the `additive` flag. A later `_popAdditiveFlag` is required to pop the change. * @internal */ - public _pushAdditiveFlag (additive: boolean) { + public _pushAdditiveFlag (additive: boolean): void { this._additiveFlagStack.push(additive); } @@ -166,13 +166,13 @@ export class AnimationGraphBindingContext { * Undo last `_pushAdditiveFlag`. * @internal */ - public _popAdditiveFlag () { + public _popAdditiveFlag (): void { assertIsTrue(this._additiveFlagStack.length > 1); this._additiveFlagStack.pop(); } /** @internal */ - public _integrityCheck () { + public _integrityCheck (): boolean { return this._additiveFlagStack.length === 1; } @@ -192,7 +192,7 @@ export class AnimationGraphBindingContext { public _setLayerWideContextProperties ( stashView: RuntimeStashView, motionSyncManager: RuntimeMotionSyncManager, - ) { + ): void { assertIsTrue(!this._isLayerWideContextPropertiesSet); this._isLayerWideContextPropertiesSet = true; this._stashView = stashView; @@ -202,7 +202,7 @@ export class AnimationGraphBindingContext { /** * @internal */ - public _unsetLayerWideContextProperties () { + public _unsetLayerWideContextProperties (): void { assertIsTrue(this._isLayerWideContextPropertiesSet); this._isLayerWideContextPropertiesSet = false; this._stashView = undefined; @@ -212,7 +212,7 @@ export class AnimationGraphBindingContext { /** * @internal */ - public _setClipOverrides (clipOverrides: ReadonlyClipOverrideMap | undefined) { + public _setClipOverrides (clipOverrides: ReadonlyClipOverrideMap | undefined): void { this._clipOverrides = clipOverrides; } @@ -232,7 +232,7 @@ export class AnimationGraphBindingContext { private _motionSyncManager: RuntimeMotionSyncManager | undefined; private _clipOverrides: ReadonlyClipOverrideMap | undefined = undefined; - private _resetTrigger (triggerName: string) { + private _resetTrigger (triggerName: string): void { const varInstance = this._varRegistry[triggerName]; if (!varInstance) { return; @@ -244,19 +244,19 @@ export class AnimationGraphBindingContext { const cacheTransform = new Transform(); export class AuxiliaryCurveRegistry { - public names () { + public names (): IterableIterator { return this._namedCurves.keys(); } - public has (name: string) { + public has (name: string): boolean { return this._namedCurves.has(name); } - public get (name: string) { + public get (name: string): number { return this._namedCurves.get(name) ?? 0.0; } - public set (name: string, value: number) { + public set (name: string, value: number): void { this._namedCurves.set(name, value); } @@ -280,7 +280,7 @@ export enum LayoutChangeFlag { AUXILIARY_CURVE_COUNT = 4, } -const checkBindStatus = (bindStarted = false): MethodDecorator => (_, _propertyKey, descriptor: TypedPropertyDescriptor) => { +const checkBindStatus = (bindStarted = false): MethodDecorator => (_, _propertyKey, descriptor: TypedPropertyDescriptor): void => { if (!DEBUG) { return; } @@ -288,7 +288,7 @@ const checkBindStatus = (bindStarted = false): MethodDecorator => (_, _propertyK const vendor = descriptor.value; if (vendor) { // eslint-disable-next-line func-names - descriptor.value = function (this: { readonly _bindStarted: boolean }, ...args: unknown[]) { + descriptor.value = function (this: { readonly _bindStarted: boolean }, ...args: unknown[]): any { assertIsTrue(this._bindStarted === bindStarted, bindStarted ? `The operation is invalid since bind has not been started.` @@ -308,11 +308,11 @@ export class AnimationGraphPoseLayoutMaintainer { this._auxiliaryCurveRegistry = auxiliaryCurveRegistry; } - get transformCount () { + get transformCount (): number { return this._transformRecords.length; } - get auxiliaryCurveCount () { + get auxiliaryCurveCount (): number { return this._auxiliaryCurveRecords.length; } @@ -321,7 +321,7 @@ export class AnimationGraphPoseLayoutMaintainer { } @checkBindStatus(true) - public getOrCreateTransformBinding (node: Node) { + public getOrCreateTransformBinding (node: Node): TransformHandleInternal | null { const { _origin: origin, } = this; @@ -375,7 +375,7 @@ export class AnimationGraphPoseLayoutMaintainer { } @checkBindStatus(true) - private _getOrCreateTransformBinding (node: Node) { + private _getOrCreateTransformBinding (node: Node): TransformHandleInternal { const { _transformRecords: transformRecords } = this; const transformIndex = transformRecords.findIndex((transformRecord) => transformRecord.node === node); @@ -411,7 +411,7 @@ export class AnimationGraphPoseLayoutMaintainer { } @checkBindStatus(true) - public getOrCreateAuxiliaryCurveBinding (name: string) { + public getOrCreateAuxiliaryCurveBinding (name: string): AuxiliaryCurveHandleInternal { const { _auxiliaryCurveRecords: auxiliaryCurveRecords } = this; const auxiliaryCurveIndex = auxiliaryCurveRecords.findIndex((record) => record.name === name); @@ -430,7 +430,7 @@ export class AnimationGraphPoseLayoutMaintainer { } } - public createEvaluationContext () { + public createEvaluationContext (): AnimationGraphEvaluationContext { assertIsTrue(!this._bindStarted); return new AnimationGraphEvaluationContext( this.transformCount, @@ -440,12 +440,12 @@ export class AnimationGraphPoseLayoutMaintainer { ); } - public resetPoseStashAllocator (allocator: DeferredPoseStashAllocator) { + public resetPoseStashAllocator (allocator: DeferredPoseStashAllocator): void { assertIsTrue(!this._bindStarted); allocator._reset(this.transformCount, this.auxiliaryCurveCount); } - public createTransformFilter (mask: Readonly) { + public createTransformFilter (mask: Readonly): TransformFilter { const { _origin: origin } = this; const involvedTransformIndices: number[] = []; for (const { node, handle } of this._transformRecords) { @@ -462,7 +462,7 @@ export class AnimationGraphPoseLayoutMaintainer { const poseFilter = new TransformFilter(involvedTransformIndices); return poseFilter; - function countPath (from: Node, to: Node) { + function countPath (from: Node, to: Node): string | undefined { const path: string[] = []; for (let node: Node | null = to; node; node = node.parent) { if (node === from) { @@ -475,7 +475,7 @@ export class AnimationGraphPoseLayoutMaintainer { } } - public fetchDefaultTransforms (transforms: TransformArray) { + public fetchDefaultTransforms (transforms: TransformArray): void { const nTransforms = this._transformRecords.length; assertIsTrue(transforms.length === nTransforms); for (let iTransform = 0; iTransform < nTransforms; ++iTransform) { @@ -484,7 +484,7 @@ export class AnimationGraphPoseLayoutMaintainer { } } - public apply (pose: Pose) { + public apply (pose: Pose): void { const { transforms, auxiliaryCurves, @@ -514,7 +514,7 @@ export class AnimationGraphPoseLayoutMaintainer { * @engineInternal */ @checkBindStatus(true) - public _destroyTransformHandle (index: number) { + public _destroyTransformHandle (index: number): void { assertIsTrue(index >= 0 && index < this._transformRecords.length, `Invalid transform handle.`); const record = this._transformRecords[index]; assertIsTrue(record.refCount > 0, `Something work wrong: refCount mismatch.`); @@ -525,7 +525,7 @@ export class AnimationGraphPoseLayoutMaintainer { * @engineInternal */ @checkBindStatus(true) - public _destroyAuxiliaryCurveHandle (index: number) { + public _destroyAuxiliaryCurveHandle (index: number): void { assertIsTrue(index >= 0 && index < this._auxiliaryCurveRecords.length, `Invalid auxiliary value handle.`); const record = this._auxiliaryCurveRecords[index]; assertIsTrue(record.refCount > 0, `Something work wrong: refCount mismatch.`); @@ -533,14 +533,14 @@ export class AnimationGraphPoseLayoutMaintainer { } @checkBindStatus(false) - public startBind () { + public startBind (): void { this._bindStarted = true; this._transformCountBeforeBind = this._transformRecords.length; this._auxiliaryCurveCountBeforeBind = this._auxiliaryCurveRecords.length; } @checkBindStatus(true) - public endBind () { + public endBind (): number { const { _transformRecords: transformRecords, _auxiliaryCurveRecords: auxiliaryCurveRecords, @@ -682,7 +682,7 @@ class AuxiliaryCurveRecord implements AnimationRecord> (records: TRecord[]) { +function trimRecords> (records: TRecord[]): void { const nUsedRecords = partition(records, (record) => { assertIsTrue(record.refCount >= 0); return record.refCount > 0; @@ -717,7 +717,7 @@ export class AnimationGraphSettleContext { /** * Gets the number of transforms in pose. */ - public get transformCount () { + public get transformCount (): number { return this._layoutMaintainer.transformCount; } @@ -757,7 +757,7 @@ class AnimationGraphEvaluationContext { this[defaultTransformsTag] = new TransformArray(transformCount); } - public destroy () { + public destroy (): void { this._poseAllocator.destroy(); } @@ -766,15 +766,15 @@ class AnimationGraphEvaluationContext { */ public readonly [defaultTransformsTag]: TransformArray; - public get allocatedPoseCount () { + public get allocatedPoseCount (): number { return this._poseAllocator.allocatedCount; } - get parentTable () { + get parentTable (): readonly number[] { return this._parentTable; } - public pushDefaultedPose () { + public pushDefaultedPose (): Pose { const pose = this._poseAllocator.push(); pose.transforms.set(this[defaultTransformsTag]); pose._poseTransformSpace = PoseTransformSpace.LOCAL; @@ -782,13 +782,13 @@ class AnimationGraphEvaluationContext { return pose; } - public pushDefaultedPoseInComponentSpace () { + public pushDefaultedPoseInComponentSpace (): Pose { const pose = this.pushDefaultedPose(); this._poseTransformsSpaceLocalToComponent(pose); return pose; } - public pushZeroDeltaPose () { + public pushZeroDeltaPose (): Pose { const pose = this._poseAllocator.push(); pose.transforms.fill(ZERO_DELTA_TRANSFORM); pose._poseTransformSpace = PoseTransformSpace.LOCAL; @@ -796,7 +796,7 @@ class AnimationGraphEvaluationContext { return pose; } - public pushDuplicatedPose (src: Pose) { + public pushDuplicatedPose (src: Pose): Pose { const pose = this._poseAllocator.push(); pose.transforms.set(src.transforms); pose._poseTransformSpace = src._poseTransformSpace; @@ -804,26 +804,26 @@ class AnimationGraphEvaluationContext { return pose; } - public popPose () { + public popPose (): void { this._poseAllocator.pop(); } /** * @internal */ - public get _stackSize_debugging () { + public get _stackSize_debugging (): number { return this._poseAllocator.allocatedCount; } /** * @internal */ - public _isStackTopPose_debugging (pose: Pose) { + public _isStackTopPose_debugging (pose: Pose): boolean { return pose === this._poseAllocator.top; } /** @internal */ - public _poseTransformsSpaceLocalToComponent (pose: Pose) { + public _poseTransformsSpaceLocalToComponent (pose: Pose): void { const { transforms } = pose; const { length: nTransforms } = transforms; for (let iTransform = 0; iTransform < nTransforms; ++iTransform) { @@ -841,7 +841,7 @@ class AnimationGraphEvaluationContext { } /** @internal */ - public _poseTransformsSpaceComponentToLocal (pose: Pose) { + public _poseTransformsSpaceComponentToLocal (pose: Pose): void { const { transforms } = pose; const { length: nTransforms } = transforms; for (let iTransform = nTransforms - 1; iTransform >= 0; --iTransform) { @@ -863,7 +863,7 @@ class AnimationGraphEvaluationContext { outTransformSpace: TransformSpace, pose: Pose, poseTransformIndex: number, - ) { + ): Transform { const poseSpace = pose._poseTransformSpace; switch (outTransformSpace) { default: @@ -929,7 +929,7 @@ class AnimationGraphEvaluationContext { transformSpace: TransformSpace, pose: Pose, poseTransformIndex: number, - ) { + ): Transform { const poseSpace = pose._poseTransformSpace; switch (transformSpace) { @@ -992,7 +992,7 @@ class AnimationGraphEvaluationContext { private _cacheComponentToWorldTransform = new Transform(); - private _getComponentToWorldTransform () { + private _getComponentToWorldTransform (): Transform { const result = this._cacheComponentToWorldTransform; const componentNode = this._componentNode; result.position = componentNode.worldPosition; @@ -1001,7 +1001,7 @@ class AnimationGraphEvaluationContext { return result; } - private _getLocalToComponentTransform (out: Transform, pose: Pose, transformIndex: number) { + private _getLocalToComponentTransform (out: Transform, pose: Pose, transformIndex: number): Transform { const { _parentTable: parentTable } = this; Transform.setIdentity(out); @@ -1013,7 +1013,7 @@ class AnimationGraphEvaluationContext { return out; } - private _getLocalToWorldTransform (out: Transform, pose: Pose, transformIndex: number) { + private _getLocalToWorldTransform (out: Transform, pose: Pose, transformIndex: number): Transform { this._getLocalToComponentTransform(out, pose, transformIndex); Transform.multiply(out, this._getComponentToWorldTransform(), out); return out; @@ -1038,7 +1038,7 @@ class TransformHandleInternal implements TransformHandle { public index = -1; - public destroy () { + public destroy (): void { this._host._destroyTransformHandle(this.index); } @@ -1055,7 +1055,7 @@ class AuxiliaryCurveHandleInternal implements AuxiliaryCurveHandle { public index = -1; - public destroy () { + public destroy (): void { this._host._destroyAuxiliaryCurveHandle(this.index); } @@ -1094,7 +1094,7 @@ export class AnimationGraphUpdateContextGenerator { public generate ( deltaTime: number, indicativeWeight: number, - ) { + ): AnimationGraphUpdateContext { this._context.deltaTime = deltaTime; this._context.indicativeWeight = indicativeWeight; return this._context as AnimationGraphUpdateContext; @@ -1110,7 +1110,7 @@ export class AnimationGraphUpdateContextGenerator { public forkSubWeight ( base: AnimationGraphUpdateContext, subWeight: number, - ) { + ): void { this._context.deltaTime = base.deltaTime; this._context.indicativeWeight = base.indicativeWeight * subWeight; } @@ -1127,13 +1127,13 @@ interface ReusableUpdateContext extends AnimationGraphUpdateContext { } export class DeferredPoseStashAllocator implements PoseStashAllocator { - get allocatedPoseCount () { + get allocatedPoseCount (): number { assertIsTrue(this._allocator); return this._allocator.allocatedCount; } /** @internal */ - public _reset (transformCount: number, auxiliaryCurveCount: number) { + public _reset (transformCount: number, auxiliaryCurveCount: number): void { this._allocator = new PoseHeapAllocator(transformCount, auxiliaryCurveCount); } diff --git a/cocos/animation/marionette/animation-graph-variant.ts b/cocos/animation/marionette/animation-graph-variant.ts index 7913f480aca..ccbbc2797c3 100644 --- a/cocos/animation/marionette/animation-graph-variant.ts +++ b/cocos/animation/marionette/animation-graph-variant.ts @@ -58,7 +58,7 @@ export class AnimationGraphVariant extends AnimationGraphLike implements Animati @type(AnimationGraph) @editable - get original () { + get original (): AnimationGraph | null { return this._graph; } @@ -79,24 +79,24 @@ export class AnimationGraphVariant extends AnimationGraphLike implements Animati @ccclass(`${CLASS_NAME_PREFIX_ANIM}ClipOverrideMap`) class ClipOverrideMap implements ReadonlyClipOverrideMap { - get size () { + get size (): number { return this._entries.length; } - public [Symbol.iterator] () { + public [Symbol.iterator] (): IterableIterator { return this._entries[Symbol.iterator](); } - public has (original: AnimationClip) { + public has (original: AnimationClip): boolean { return !!this._entries.find(({ original: o }) => o === original); } - public get (original: AnimationClip) { + public get (original: AnimationClip): AnimationClip | undefined { const entry = this._entries.find(({ original: o }) => o === original); return entry?.substitution; } - public set (original: AnimationClip, substitution: AnimationClip) { + public set (original: AnimationClip, substitution: AnimationClip): void { const entry = this._entries.find(({ original: o }) => o === original); if (entry) { entry.substitution = substitution; @@ -108,11 +108,11 @@ class ClipOverrideMap implements ReadonlyClipOverrideMap { } } - public delete (original: AnimationClip) { + public delete (original: AnimationClip): void { removeIf(this._entries, ({ original: o }) => o === original); } - public clear () { + public clear (): void { this._entries.length = 0; } diff --git a/cocos/animation/marionette/animation-graph.ts b/cocos/animation/marionette/animation-graph.ts index 280fae88875..f2175568392 100644 --- a/cocos/animation/marionette/animation-graph.ts +++ b/cocos/animation/marionette/animation-graph.ts @@ -73,7 +73,7 @@ class Transition extends EditorExtendable implements OwnedBy, Tran } } - public copyTo (that: Transition) { + public copyTo (that: Transition): void { that.conditions = this.conditions.map((condition) => condition.clone()); } @@ -124,7 +124,7 @@ class DurationalTransition extends Transition { @editable public endEventBinding = new AnimationGraphEventBinding(); - public copyTo (that: DurationalTransition) { + public copyTo (that: DurationalTransition): void { super.copyTo(that); that.destinationStart = this.destinationStart; that.relativeDestinationStart = this.relativeDestinationStart; @@ -154,7 +154,7 @@ class AnimationTransition extends DurationalTransition { @serializable public exitConditionEnabled = true; - get exitCondition () { + get exitCondition (): number { return this._exitCondition; } @@ -163,7 +163,7 @@ class AnimationTransition extends DurationalTransition { this._exitCondition = value; } - public copyTo (that: AnimationTransition) { + public copyTo (that: AnimationTransition): void { super.copyTo(that); that.duration = this.duration; that.relativeDuration = this.relativeDuration; @@ -199,7 +199,7 @@ export class EmptyStateTransition extends DurationalTransition { @serializable public duration = 0.3; - public copyTo (that: EmptyStateTransition) { + public copyTo (that: EmptyStateTransition): void { super.copyTo(that); that.duration = this.duration; } @@ -232,11 +232,11 @@ class ProceduralPoseState extends State { * // TODO: HACK * @internal */ - public __callOnAfterDeserializeRecursive () { + public __callOnAfterDeserializeRecursive (): void { this.graph.__callOnAfterDeserializeRecursive(); } - public copyTo (that: MotionState) { + public copyTo (that: MotionState): ProceduralPoseState { super.copyTo(that); this.transitionInEventBinding.copyTo(that.transitionInEventBinding); this.transitionOutEventBinding.copyTo(that.transitionOutEventBinding); @@ -258,7 +258,7 @@ class ProceduralPoseTransition extends DurationalTransition { @serializable public duration = 0.3; - public copyTo (that: ProceduralPoseTransition) { + public copyTo (that: ProceduralPoseTransition): void { super.copyTo(that); that.duration = this.duration; } @@ -296,7 +296,7 @@ export class StateMachine extends EditorExtendable { * // TODO: HACK * @internal */ - public __callOnAfterDeserializeRecursive () { + public __callOnAfterDeserializeRecursive (): void { this[onAfterDeserializedTag](); const nStates = this._states.length; for (let iState = 0; iState < nStates; ++iState) { @@ -322,7 +322,7 @@ export class StateMachine extends EditorExtendable { this._anyState.name = 'Any'; } - public [onAfterDeserializedTag] () { + public [onAfterDeserializedTag] (): void { this._states.forEach((state) => own(state, this)); this._transitions.forEach((transition) => { transition.from[outgoingsSymbol].push(transition); @@ -330,28 +330,28 @@ export class StateMachine extends EditorExtendable { }); } - public get allowEmptyStates () { + public get allowEmptyStates (): boolean { return this._allowEmptyStates; } /** * The entry state. */ - get entryState () { + get entryState (): State { return this._entryState; } /** * The exit state. */ - get exitState () { + get exitState (): State { return this._exitState; } /** * The any state. */ - get anyState () { + get anyState (): State { return this._anyState; } @@ -426,7 +426,7 @@ export class StateMachine extends EditorExtendable { * Adds an empty state into this state machine. * @returns The newly created empty state. */ - public addEmpty () { + public addEmpty (): EmptyState { if (!this._allowEmptyStates) { throw new Error(`Empty states are now allowed in this state machine.`); } @@ -438,7 +438,7 @@ export class StateMachine extends EditorExtendable { * @en Adds an pose state into this state machine. * @returns @zh 新创建的姿势状态。 @en The newly created pose state. */ - public addProceduralPoseState () { + public addProceduralPoseState (): ProceduralPoseState { return this._addState(new ProceduralPoseState()); } @@ -446,7 +446,7 @@ export class StateMachine extends EditorExtendable { * Removes specified state from this state machine. * @param state The state to remove. */ - public remove (state: State) { + public remove (state: State): void { assertsOwnedBy(state, this); if (state === this.entryState @@ -526,7 +526,7 @@ export class StateMachine extends EditorExtendable { return transition; } - public disconnect (from: State, to: State) { + public disconnect (from: State, to: State): void { assertsOwnedBy(from, this); assertsOwnedBy(to, this); @@ -553,7 +553,7 @@ export class StateMachine extends EditorExtendable { } } - public removeTransition (removal: Transition) { + public removeTransition (removal: Transition): void { assertIsTrue( js.array.remove(this._transitions, removal), ); @@ -566,7 +566,7 @@ export class StateMachine extends EditorExtendable { markAsDangling(removal); } - public eraseOutgoings (from: State) { + public eraseOutgoings (from: State): void { assertsOwnedBy(from, this); const oTransitions = from[outgoingsSymbol]; @@ -584,7 +584,7 @@ export class StateMachine extends EditorExtendable { oTransitions.length = 0; } - public eraseIncomings (to: State) { + public eraseIncomings (to: State): void { assertsOwnedBy(to, this); const iTransitions = to[incomingsSymbol]; @@ -602,7 +602,7 @@ export class StateMachine extends EditorExtendable { iTransitions.length = 0; } - public eraseTransitionsIncludes (state: State) { + public eraseTransitionsIncludes (state: State): void { this.eraseIncomings(state); this.eraseOutgoings(state); } @@ -635,7 +635,7 @@ export class StateMachine extends EditorExtendable { * @param adjusting @en The transition to adjust the priority. @zh 需要调整优先级的过渡。 * @param diff @en Indicates how to adjust the priority. @zh 指示如何调整优先级。 */ - public adjustTransitionPriority (adjusting: Transition, diff: number) { + public adjustTransitionPriority (adjusting: Transition, diff: number): void { const { from } = adjusting; if (diff === 0) { return; @@ -677,7 +677,7 @@ export class StateMachine extends EditorExtendable { } } - public copyTo (that: StateMachine) { + public copyTo (that: StateMachine): void { // Clear that first const thatStatesOld = that._states.filter((state) => { switch (state) { @@ -749,13 +749,13 @@ export class StateMachine extends EditorExtendable { } } - public clone () { + public clone (): StateMachine { const that = new StateMachine(this._allowEmptyStates); this.copyTo(that); return that; } - private _addState (state: T) { + private _addState (state: T): T { own(state, this); this._states.push(state); return state; @@ -769,11 +769,11 @@ export class SubStateMachine extends InteractiveState { this._stateMachine = new StateMachine(allowEmptyStates); } - get stateMachine () { + get stateMachine (): StateMachine { return this._stateMachine; } - public copyTo (that: SubStateMachine) { + public copyTo (that: SubStateMachine): void { super.copyTo(that); this._stateMachine.copyTo(that._stateMachine); } @@ -813,7 +813,7 @@ export class Layer implements OwnedBy { * // TODO: HACK * @internal */ - public __callOnAfterDeserializeRecursive () { + public __callOnAfterDeserializeRecursive (): void { this.stateMachine._allowEmptyStates = true; this.stateMachine.__callOnAfterDeserializeRecursive(); for (const stashId in this._stashes) { @@ -830,15 +830,15 @@ export class Layer implements OwnedBy { return this._stashes[id]; } - public addStash (id: string) { + public addStash (id: string): PoseGraphStash { return this._stashes[id] = new PoseGraphStash(); } - public removeStash (id: string) { + public removeStash (id: string): void { delete this._stashes[id]; } - public renameStash (id: string, newId: string) { + public renameStash (id: string, newId: string): void { this._stashes = renameObjectProperty(this._stashes, id, newId); } @@ -849,7 +849,7 @@ export class Layer implements OwnedBy { this._stateMachine = new StateMachine(true); } - get stateMachine () { + get stateMachine (): StateMachine { return this._stateMachine; } @@ -889,7 +889,7 @@ export class AnimationGraph extends AnimationGraphLike implements AnimationGraph super(); } - onLoaded () { + onLoaded (): void { const { _layers: layers } = this; const nLayers = layers.length; for (let iLayer = 0; iLayer < nLayers; ++iLayer) { @@ -909,7 +909,7 @@ export class AnimationGraph extends AnimationGraphLike implements AnimationGraph * Adds a layer. * @returns The new layer. */ - public addLayer () { + public addLayer (): Layer { const layer = new Layer(); this._layers.push(layer); return layer; @@ -919,7 +919,7 @@ export class AnimationGraph extends AnimationGraphLike implements AnimationGraph * Removes a layer. * @param index Index to the layer to remove. */ - public removeLayer (index: number) { + public removeLayer (index: number): void { js.array.removeAt(this._layers, index); } @@ -928,7 +928,7 @@ export class AnimationGraph extends AnimationGraphLike implements AnimationGraph * @param index * @param newIndex */ - public moveLayer (index: number, newIndex: number) { + public moveLayer (index: number, newIndex: number): void { shift(this._layers, index, newIndex); } @@ -940,13 +940,13 @@ export class AnimationGraph extends AnimationGraphLike implements AnimationGraph */ public addVariable ( name: string, type: TVariableType, initialValue?: VariableTypeValueTypeMap[TVariableType], - ) { + ): VariableDescription { const variable = createVariable(type, initialValue); this._variables[name] = variable; return variable; } - public removeVariable (name: string) { + public removeVariable (name: string): void { delete this._variables[name]; } @@ -965,7 +965,7 @@ export class AnimationGraph extends AnimationGraphLike implements AnimationGraph * @param name @zh 要重命名的变量的名字。 @en The name of the variable to be renamed. * @param newName @zh 新的名字。 @en New name. */ - public renameVariable (name: string, newName: string) { + public renameVariable (name: string, newName: string): void { this._variables = renameObjectProperty(this._variables, name, newName); } } diff --git a/cocos/animation/marionette/animation-mask.ts b/cocos/animation/marionette/animation-mask.ts index 8f4157ecfe4..76884ff0ffd 100644 --- a/cocos/animation/marionette/animation-mask.ts +++ b/cocos/animation/marionette/animation-mask.ts @@ -72,7 +72,7 @@ export class AnimationMask extends Asset { * @param path @zh 关节的路径。 @en The joint's path. * @param enabled @zh 是否启用该关节。 @en Whether to enable the joint. */ - public addJoint (path: string, enabled: boolean) { + public addJoint (path: string, enabled: boolean): void { this.removeJoint(path); const info = new JointMask(); info.path = path; @@ -80,15 +80,15 @@ export class AnimationMask extends Asset { this._jointMasks.push(info); } - public removeJoint (removal: string) { + public removeJoint (removal: string): void { js.array.removeIf(this._jointMasks, ({ path }) => path === removal); } - public clear () { + public clear (): void { this._jointMasks.length = 0; } - public filterDisabledNodes (root: Node) { + public filterDisabledNodes (root: Node): Set { const { _jointMasks: jointMasks } = this; const nJointMasks = jointMasks.length; const disabledNodes = new Set(); @@ -105,7 +105,7 @@ export class AnimationMask extends Asset { return disabledNodes; } - public isExcluded (path: string) { + public isExcluded (path: string): boolean { return !(this._jointMasks.find(({ path: p }) => p === path)?.enabled ?? true); } } diff --git a/cocos/animation/marionette/event/event-binding.ts b/cocos/animation/marionette/event/event-binding.ts index 1d811c75391..f3a7fdca156 100644 --- a/cocos/animation/marionette/event/event-binding.ts +++ b/cocos/animation/marionette/event/event-binding.ts @@ -22,11 +22,11 @@ export class AnimationGraphEventBinding { * @zh 获取该绑定是否绑定了任何事件。 * @en Tells if there's any event bound to this binding. */ - get isBound () { + get isBound (): boolean { return !!this.methodName; } - public emit (origin: Node) { + public emit (origin: Node): void { if (!this.methodName) { return; } @@ -34,7 +34,7 @@ export class AnimationGraphEventBinding { invokeComponentMethodsEngagedInAnimationEvent(origin, this.methodName); } - public copyTo (that: AnimationGraphEventBinding) { + public copyTo (that: AnimationGraphEventBinding): AnimationGraphEventBinding { that.methodName = this.methodName; return this; } diff --git a/cocos/animation/marionette/graph-debug.ts b/cocos/animation/marionette/graph-debug.ts index 61d3e723a06..4b80a90b4c8 100644 --- a/cocos/animation/marionette/graph-debug.ts +++ b/cocos/animation/marionette/graph-debug.ts @@ -30,7 +30,7 @@ export const RUNTIME_ID_ENABLED = EDITOR; export type RuntimeID = number; -export function getMotionRuntimeID (motion: Motion) { +export function getMotionRuntimeID (motion: Motion): number | undefined { return (motion[editorExtrasTag] as undefined | { id?: RuntimeID })?.id; } diff --git a/cocos/animation/marionette/graph-eval.ts b/cocos/animation/marionette/graph-eval.ts index 06c38cd2662..52558d27d7f 100644 --- a/cocos/animation/marionette/graph-eval.ts +++ b/cocos/animation/marionette/graph-eval.ts @@ -105,11 +105,11 @@ export class AnimationGraphEval { this._initializeContexts(); } - public destroy () { + public destroy (): void { this._evaluationContext.destroy(); } - public _destroyAfterException_debugging () { + public _destroyAfterException_debugging (): void { const stackSize = this._evaluationContext._stackSize_debugging; if (stackSize !== 0) { // Should only caused by exception. for (let i = 0; i < stackSize; ++i) { @@ -120,11 +120,11 @@ export class AnimationGraphEval { this._evaluationContext.destroy(); } - public get layerCount () { + public get layerCount (): number { return this._rootPoseNode.layerCount; } - public update (deltaTime: number) { + public update (deltaTime: number): void { const { _evaluationContext: evaluationContext, _poseLayoutMaintainer: poseLayoutMaintainer, @@ -189,7 +189,7 @@ export class AnimationGraphEval { return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getNextClipStatuses(); } - public getValue (name: string) { + public getValue (name: string): Value | undefined { const varInstance = this._varInstances[name]; if (!varInstance) { return undefined; @@ -198,7 +198,7 @@ export class AnimationGraphEval { } } - public setValue (name: string, value: Value) { + public setValue (name: string, value: Value): void { const varInstance = this._varInstances[name]; if (!varInstance) { return; @@ -206,15 +206,15 @@ export class AnimationGraphEval { varInstance.value = value; } - public getLayerWeight (layerIndex: number) { + public getLayerWeight (layerIndex: number): number { return this._rootPoseNode.getLayerWeight(layerIndex); } - public setLayerWeight (layerIndex: number, weight: number) { + public setLayerWeight (layerIndex: number, weight: number): void { this._rootPoseNode.setLayerWeight(layerIndex, weight); } - public overrideClips (overrides: ReadonlyClipOverrideMap) { + public overrideClips (overrides: ReadonlyClipOverrideMap): void { const { _poseLayoutMaintainer: poseLayoutMaintainer, } = this; @@ -226,7 +226,7 @@ export class AnimationGraphEval { this._updateAfterPossiblePoseLayoutChange(); } - public getAuxiliaryCurveValue (curveName: string) { + public getAuxiliaryCurveValue (curveName: string): number { return this._auxiliaryCurveRegistry.get(curveName); } @@ -245,7 +245,7 @@ export class AnimationGraphEval { private declare _poseStashAllocator: DeferredPoseStashAllocator; private _rootUpdateContextGenerator = new AnimationGraphUpdateContextGenerator(); - private _initializeContexts () { + private _initializeContexts (): void { const { _poseLayoutMaintainer: poseLayoutMaintainer, } = this; @@ -265,7 +265,7 @@ export class AnimationGraphEval { poseLayoutMaintainer.resetPoseStashAllocator(this._poseStashAllocator); } - private _updateAfterPossiblePoseLayoutChange () { + private _updateAfterPossiblePoseLayoutChange (): void { const { _poseLayoutMaintainer: poseLayoutMaintainer, } = this; @@ -302,7 +302,7 @@ export class AnimationGraphEval { } } - private _createOrUpdateTransformFilters () { + private _createOrUpdateTransformFilters (): void { this._rootPoseNode.settle(this._settleContext); } } diff --git a/cocos/animation/marionette/motion/animation-blend-1d.ts b/cocos/animation/marionette/motion/animation-blend-1d.ts index d7e6fb8857b..27499753ad7 100644 --- a/cocos/animation/marionette/motion/animation-blend-1d.ts +++ b/cocos/animation/marionette/motion/animation-blend-1d.ts @@ -38,13 +38,13 @@ class AnimationBlend1DItem extends AnimationBlendItem { @serializable public threshold = 0.0; - public clone () { + public clone (): AnimationBlend1DItem { const that = new AnimationBlend1DItem(); this._copyTo(that); return that; } - protected _copyTo (that: AnimationBlend1DItem) { + protected _copyTo (that: AnimationBlend1DItem): AnimationBlend1DItem { super._copyTo(that); that.threshold = this.threshold; return that; @@ -70,7 +70,7 @@ export class AnimationBlend1D extends AnimationBlend { .sort(({ threshold: lhs }, { threshold: rhs }) => lhs - rhs); } - public clone () { + public clone (): AnimationBlend1D { const that = new AnimationBlend1D(); this.copyTo(that); that._items = this._items.map((item) => item.clone()); @@ -82,7 +82,7 @@ export class AnimationBlend1D extends AnimationBlend { context: AnimationGraphBindingContext, clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, - ) { + ): any { const evaluation = new AnimationBlend1DEval( context, clipOverrides, ignoreEmbeddedPlayers, this, this._items, this._items.map(({ threshold }) => threshold), 0.0, @@ -118,7 +118,7 @@ class AnimationBlend1DEval extends AnimationBlendEval { this.doEval(); } - protected eval (weights: number[], [value]: readonly [number]) { + protected eval (weights: number[], [value]: readonly [number]): void { blend1D(weights, this._thresholds, value); } } diff --git a/cocos/animation/marionette/motion/animation-blend-2d.ts b/cocos/animation/marionette/motion/animation-blend-2d.ts index debd06fd38b..b4ce6ab9a16 100644 --- a/cocos/animation/marionette/motion/animation-blend-2d.ts +++ b/cocos/animation/marionette/motion/animation-blend-2d.ts @@ -46,13 +46,13 @@ class AnimationBlend2DItem extends AnimationBlendItem { @serializable public threshold = new Vec2(); - public clone () { + public clone (): AnimationBlend2DItem { const that = new AnimationBlend2DItem(); this._copyTo(that); return that; } - protected _copyTo (that: AnimationBlend2DItem) { + protected _copyTo (that: AnimationBlend2DItem): AnimationBlend2DItem { super._copyTo(that); Vec2.copy(that.threshold, this.threshold); return that; @@ -66,7 +66,7 @@ export class AnimationBlend2D extends AnimationBlend { public static Item = AnimationBlend2DItem; @editable - public get algorithm () { + public get algorithm (): Algorithm { return this._algorithm; } @@ -100,11 +100,11 @@ export class AnimationBlend2D extends AnimationBlend { * // TODO: HACK * @internal */ - __callOnAfterDeserializeRecursive () { + __callOnAfterDeserializeRecursive (): void { this._tryReconstructPolarSpaceInterpolator(); } - public clone () { + public clone (): AnimationBlend2D { const that = new AnimationBlend2D(); this.copyTo(that); that._items = this._items.map((item) => item?.clone() ?? null); @@ -118,7 +118,7 @@ export class AnimationBlend2D extends AnimationBlend { context: AnimationGraphBindingContext, clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, - ) { + ): AnimationBlendEval { const { algorithm } = this; let evaluation: AnimationBlendEval; switch (algorithm) { @@ -178,7 +178,7 @@ export class AnimationBlend2D extends AnimationBlend { private _polarSpaceGBI: PolarSpaceGradientBandInterpolator2D | undefined = undefined; - private _tryReconstructPolarSpaceInterpolator () { + private _tryReconstructPolarSpaceInterpolator (): void { if (this._algorithm === Algorithm.FREEFORM_DIRECTIONAL) { this._polarSpaceGBI = new PolarSpaceGradientBandInterpolator2D(this._items.map((item) => item.threshold)); } else { @@ -214,7 +214,7 @@ class AnimationBlend2DEval extends AnimationBlendEval { this.doEval(); } - protected eval (weights: number[], [x, y]: [number, number]) { + protected eval (weights: number[], [x, y]: [number, number]): void { Vec2.set(this._value, x, y); weights.fill(0); switch (this._algorithm) { @@ -248,7 +248,7 @@ class PolarSpaceGradientBandBlend2DEval extends AnimationBlendEval { this.doEval(); } - protected eval (weights: number[], [x, y]: [number, number]) { + protected eval (weights: number[], [x, y]: [number, number]): void { Vec2.set(this._value, x, y); weights.fill(0); this._interpolator.interpolate(weights, this._value); diff --git a/cocos/animation/marionette/motion/animation-blend-direct.ts b/cocos/animation/marionette/motion/animation-blend-direct.ts index fd334c025d3..0a59f8d8f3e 100644 --- a/cocos/animation/marionette/motion/animation-blend-direct.ts +++ b/cocos/animation/marionette/motion/animation-blend-direct.ts @@ -37,13 +37,13 @@ class AnimationBlendDirectItem extends AnimationBlendItem { @serializable public weight = new BindableNumber(0.0); - public clone () { + public clone (): AnimationBlendDirectItem { const that = new AnimationBlendDirectItem(); this._copyTo(that); return that; } - protected _copyTo (that: AnimationBlendDirectItem) { + protected _copyTo (that: AnimationBlendDirectItem): AnimationBlendDirectItem { super._copyTo(that); that.weight = this.weight; return that; @@ -57,7 +57,7 @@ export class AnimationBlendDirect extends AnimationBlend { @serializable private _items: AnimationBlendDirectItem[] = []; - get items () { + get items (): AnimationBlendDirectItem[] { return this._items; } @@ -65,7 +65,7 @@ export class AnimationBlendDirect extends AnimationBlend { this._items = Array.from(value); } - public clone () { + public clone (): AnimationBlendDirect { const that = new AnimationBlendDirect(); this.copyTo(that); that._items = this._items.map((item) => item?.clone() ?? null); @@ -76,7 +76,7 @@ export class AnimationBlendDirect extends AnimationBlend { context: AnimationGraphBindingContext, clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, - ) { + ): AnimationBlendDirectEval { const myEval: AnimationBlendDirectEval = new AnimationBlendDirectEval( context, clipOverrides, @@ -111,7 +111,7 @@ class AnimationBlendDirectEval extends AnimationBlendEval { this.doEval(); } - protected eval (weights: number[], inputs: readonly number[]) { + protected eval (weights: number[], inputs: readonly number[]): void { const nChildren = weights.length; for (let iChild = 0; iChild < nChildren; ++iChild) { weights[iChild] = inputs[iChild]; diff --git a/cocos/animation/marionette/motion/animation-blend.ts b/cocos/animation/marionette/motion/animation-blend.ts index c7d99d41bf4..fa39971e69f 100644 --- a/cocos/animation/marionette/motion/animation-blend.ts +++ b/cocos/animation/marionette/motion/animation-blend.ts @@ -50,13 +50,13 @@ export class AnimationBlendItem { @serializable public motion: Motion | null = null; - public clone () { + public clone (): AnimationBlendItem { const that = new AnimationBlendItem(); this._copyTo(that); return that; } - protected _copyTo (that: AnimationBlendItem) { + protected _copyTo (that: AnimationBlendItem): AnimationBlendItem { that.motion = this.motion?.clone() ?? null; return that; } @@ -67,7 +67,7 @@ export abstract class AnimationBlend extends Motion { @serializable name = ''; - public copyTo (that: AnimationBlend) { + public copyTo (that: AnimationBlend): void { that.name = this.name; that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this); } @@ -103,7 +103,7 @@ export class AnimationBlendEval implements MotionEval { ); } - get childCount () { + get childCount (): number { return this._weights.length; } @@ -111,11 +111,11 @@ export class AnimationBlendEval implements MotionEval { return this._weights[childIndex]; } - public getChildMotionEval (childIndex: number) { + public getChildMotionEval (childIndex: number): MotionEval | null { return this._childEvaluators[childIndex]; } - get duration () { + get duration (): number { let uniformDuration = 0.0; for (let iChild = 0; iChild < this._childEvaluators.length; ++iChild) { uniformDuration += (this._childEvaluators[iChild]?.duration ?? 0.0) * this._weights[iChild]; @@ -129,7 +129,7 @@ export class AnimationBlendEval implements MotionEval { let iChild = 0; let currentChildIterator: Iterator | undefined; return { - next () { + next (): IteratorResult { // eslint-disable-next-line no-constant-condition while (true) { if (currentChildIterator) { @@ -186,16 +186,16 @@ export class AnimationBlendEval implements MotionEval { } } - public setInput (value: number, index: number) { + public setInput (value: number, index: number): void { this._inputs[index] = value; this.doEval(); } - protected doEval () { + protected doEval (): void { this.eval(this._weights, this._inputs); } - protected eval (_weights: number[], _inputs: readonly number[]) { + protected eval (_weights: number[], _inputs: readonly number[]): void { } } diff --git a/cocos/animation/marionette/motion/blend-1d.ts b/cocos/animation/marionette/motion/blend-1d.ts index 9a1fca0ffe4..d5d973a78d9 100644 --- a/cocos/animation/marionette/motion/blend-1d.ts +++ b/cocos/animation/marionette/motion/blend-1d.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -export function blend1D (weights: number[], thresholds: readonly number[], value: number) { +export function blend1D (weights: number[], thresholds: readonly number[], value: number): void { weights.fill(0.0); if (thresholds.length === 0) { // Do nothing diff --git a/cocos/animation/marionette/motion/blend-2d.ts b/cocos/animation/marionette/motion/blend-2d.ts index c1ec747cc80..194798008b5 100644 --- a/cocos/animation/marionette/motion/blend-2d.ts +++ b/cocos/animation/marionette/motion/blend-2d.ts @@ -30,12 +30,12 @@ import { approx, assertIsTrue, Vec2, Vec3 } from '../../../core'; * @param samples Every samples' parameter. * @param input Input parameter. */ -export const blendSimpleDirectional = (() => { +export const blendSimpleDirectional = ((): (weights: number[], samples: readonly Vec2[], input: Readonly) => void => { const CACHE_NORMALIZED_SAMPLE = new Vec2(); const CACHE_BARYCENTRIC_SOLUTIONS: EquationResolutions = { wA: 0, wB: 0 }; - return function blendSimpleDirectional (weights: number[], samples: readonly Vec2[], input: Readonly) { + return function blendSimpleDirectional (weights: number[], samples: readonly Vec2[], input: Readonly): void { assertIsTrue(weights.length === samples.length); if (samples.length === 0) { @@ -191,11 +191,11 @@ const _DEV_NOTE = false; * @param thresholds * @param value */ -export function sampleFreeformCartesian (weights: number[], thresholds: readonly Vec2[], value: Readonly) { +export function sampleFreeformCartesian (weights: number[], thresholds: readonly Vec2[], value: Readonly): void { sampleFreeform(weights, thresholds, value, getGradientBandCartesianCoords); } -function sampleFreeform (weights: number[], samples: readonly Vec2[], value: Readonly, getGradientBandCoords: GetGradientBandCoords) { +function sampleFreeform (weights: number[], samples: readonly Vec2[], value: Readonly, getGradientBandCoords: GetGradientBandCoords): void { weights.fill(0.0); const pIpInput = new Vec2(0, 0); const pIJ = new Vec2(0, 0); @@ -244,7 +244,7 @@ function solveBarycentric ( b: Readonly, p: Readonly, resolutions: EquationResolutions, -) { +): EquationResolutions { // Let P = p - 0, A = a - 0, B = b - 0, // wA = (P x B) / (A x B) // wB = (P x A) / (B x A) @@ -323,7 +323,7 @@ export class PolarSpaceGradientBandInterpolator2D { this._cacheVIXAngles = new Float32Array(nExamples); } - public interpolate (weights: number[], input: Readonly) { + public interpolate (weights: number[], input: Readonly): void { const { _exampleDirections: exampleDirections, _exampleMagnitudes: exampleMagnitudes, @@ -454,7 +454,7 @@ export class PolarSpaceGradientBandInterpolator2D { private declare _cacheVIXAngles: Float32Array; } -function signedAngle (v1: Readonly, v2: Readonly) { +function signedAngle (v1: Readonly, v2: Readonly): number { const angle = Vec2.angle(v1, v2); const determinate = v1.x * v2.y - v1.y * v2.x; return determinate < 0 ? -angle : angle; diff --git a/cocos/animation/marionette/motion/clip-motion.ts b/cocos/animation/marionette/motion/clip-motion.ts index 7b0eb746ba2..6350625326c 100644 --- a/cocos/animation/marionette/motion/clip-motion.ts +++ b/cocos/animation/marionette/motion/clip-motion.ts @@ -50,7 +50,7 @@ export class ClipMotion extends Motion { context: AnimationGraphBindingContext, overrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, - ) { + ): ClipMotionEval | null { if (!this.clip) { return null; } @@ -61,7 +61,7 @@ export class ClipMotion extends Motion { return clipMotionEval; } - public clone () { + public clone (): ClipMotion { const that = new ClipMotion(); that.clip = this.clip; that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this); @@ -91,7 +91,7 @@ class ClipMotionEval implements MotionEval { this._setClip(overriding, context); } - get duration () { + get duration (): number { return this._duration; } @@ -99,10 +99,10 @@ class ClipMotionEval implements MotionEval { return new ClipMotionPort(this); } - public getClipStatuses (baseWeight: number): Iterator { + public getClipStatuses (baseWeight: number): Iterator { let got = false; return { - next: () => { + next: (): IteratorResult => { if (got) { return { done: true, @@ -112,18 +112,20 @@ class ClipMotionEval implements MotionEval { got = true; return { done: false, + // TODO: `__DEBUG_ID__` does not exist on ClipStatus, please fix it @Leslie Leigh + // tracking issue: https://github.com/cocos/cocos-engine/issues/15307 value: { __DEBUG_ID__: this.__DEBUG__ID__, clip: this._clip, weight: baseWeight, - }, + } as any, }; } }, }; } - public [evaluatePortTag] (progress: number, context: AnimationGraphEvaluationContext) { + public [evaluatePortTag] (progress: number, context: AnimationGraphEvaluationContext): Pose { const { _duration: duration, _clip: { duration: clipDuration }, @@ -177,7 +179,7 @@ class ClipMotionEval implements MotionEval { private _duration = 0.0; private _ignoreEmbeddedPlayers: boolean; - private _setClip (clip: AnimationClip, context: AnimationGraphBindingContext) { + private _setClip (clip: AnimationClip, context: AnimationGraphBindingContext): void { this._clipEval?.destroy(); if (this._clipEmbeddedPlayerEval) { this._clipEmbeddedPlayerEval.destroy(); diff --git a/cocos/animation/marionette/motion/motion.ts b/cocos/animation/marionette/motion/motion.ts index f8d78718687..e7f487dd72f 100644 --- a/cocos/animation/marionette/motion/motion.ts +++ b/cocos/animation/marionette/motion/motion.ts @@ -79,7 +79,7 @@ export abstract class Motion extends EditorExtendable { * // TODO: HACK * @internal */ - __callOnAfterDeserializeRecursive () { } + __callOnAfterDeserializeRecursive (): void { } } export interface MotionPort { diff --git a/cocos/animation/marionette/ownership.ts b/cocos/animation/marionette/ownership.ts index 390b0a34c3b..e768ba8d718 100644 --- a/cocos/animation/marionette/ownership.ts +++ b/cocos/animation/marionette/ownership.ts @@ -31,17 +31,17 @@ export interface OwnedBy { [ownerSymbol]: T | undefined; } -export function assertsOwnedBy (mastered: OwnedBy, owner: T) { +export function assertsOwnedBy (mastered: OwnedBy, owner: T): void { assertIsTrue(mastered[ownerSymbol] === owner); } -export function own (mastered: OwnedBy, owner: T) { +export function own (mastered: OwnedBy, owner: T): void { if (DEBUG) { mastered[ownerSymbol] = owner; } } -export function markAsDangling (mastered: OwnedBy) { +export function markAsDangling (mastered: OwnedBy): void { if (DEBUG) { mastered[ownerSymbol] = undefined; } diff --git a/cocos/animation/marionette/parametric.ts b/cocos/animation/marionette/parametric.ts index f4e12c75233..7be23156882 100644 --- a/cocos/animation/marionette/parametric.ts +++ b/cocos/animation/marionette/parametric.ts @@ -130,7 +130,7 @@ export function bindNumericOr ( callback: BindCallback, thisArg: TThis, ...args: TArgs -) { +): number | TValue { const { variable, value, @@ -167,19 +167,19 @@ export function validateVariableExistence (varInstance: VarInstance | undefined, } } -export function validateVariableType (type: VariableType, expected: VariableType, name: string) { +export function validateVariableType (type: VariableType, expected: VariableType, name: string): void { if (type !== expected) { throw new VariableTypeMismatchedError(name, 'number'); } } -export function validateVariableTypeNumeric (type: VariableType, name: string) { +export function validateVariableTypeNumeric (type: VariableType, name: string): void { if (type !== VariableType.FLOAT && type !== VariableType.INTEGER) { throw new VariableTypeMismatchedError(name, 'number or integer'); } } -export function validateVariableTypeTriggerLike (type: VariableType, name: string) { +export function validateVariableTypeTriggerLike (type: VariableType, name: string): void { if (type !== VariableType.TRIGGER) { throw new VariableTypeMismatchedError(name, 'trigger'); } diff --git a/cocos/animation/marionette/pose-graph/decorator/input.ts b/cocos/animation/marionette/pose-graph/decorator/input.ts index 9ee44060d9b..38e2f2135af 100644 --- a/cocos/animation/marionette/pose-graph/decorator/input.ts +++ b/cocos/animation/marionette/pose-graph/decorator/input.ts @@ -37,7 +37,7 @@ export type { PoseGraphNodeInputMappingOptions }; * Otherwise, each element of the property will be mapped as an input. */ export function input (options: PoseGraphNodeInputMappingOptions): PropertyDecorator { - return (target, propertyKey) => { + return (target, propertyKey): void => { if (typeof propertyKey !== 'string') { error(`@input can be only applied to string-named fields.`); return; diff --git a/cocos/animation/marionette/pose-graph/decorator/node.ts b/cocos/animation/marionette/pose-graph/decorator/node.ts index 87b184155c7..856e22e9fd7 100644 --- a/cocos/animation/marionette/pose-graph/decorator/node.ts +++ b/cocos/animation/marionette/pose-graph/decorator/node.ts @@ -17,7 +17,7 @@ export type { } from '../foundation/authoring/node-authoring'; function makeNodeEditorMetadataModifier (edit: (metadata: PoseGraphNodeEditorMetadata) => void): ClassDecorator { - return (target) => { + return (target): void => { if (!checkDecoratingClass(target)) { return; } @@ -26,21 +26,21 @@ function makeNodeEditorMetadataModifier (edit: (metadata: PoseGraphNodeEditorMet }; } -export const poseGraphNodeCategory = (category: string) => makeNodeEditorMetadataModifier((metadata) => { +export const poseGraphNodeCategory = (category: string): ClassDecorator => makeNodeEditorMetadataModifier((metadata): void => { metadata.category = category; }); -export const poseGraphCreateNodeFactory = (factory: PoseGraphCreateNodeFactory) => makeNodeEditorMetadataModifier((metadata) => { +export const poseGraphCreateNodeFactory = (factory: PoseGraphCreateNodeFactory): ClassDecorator => makeNodeEditorMetadataModifier((metadata): void => { metadata.factory = factory; }); -export const poseGraphNodeHide = (hide = true) => makeNodeEditorMetadataModifier((metadata) => { +export const poseGraphNodeHide = (hide = true): ClassDecorator => makeNodeEditorMetadataModifier((metadata): void => { metadata.hide = hide; }); export const poseGraphNodeAppearance = ( appearance: Readonly, -) => makeNodeEditorMetadataModifier((metadata) => { +): ClassDecorator => makeNodeEditorMetadataModifier((metadata): void => { Object.assign(metadata.appearance ??= {}, appearance); }); diff --git a/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts b/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts index 05643fc7aa6..47396c48a76 100644 --- a/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts +++ b/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts @@ -33,7 +33,7 @@ export class DefaultTopLevelPoseNode extends PoseNode { this._layerRecords = layerEvaluationRecords; } - get layerCount () { + get layerCount (): number { return this._layerRecords.length; } @@ -55,21 +55,21 @@ export class DefaultTopLevelPoseNode extends PoseNode { } } - public getLayerWeight (layerIndex: number) { + public getLayerWeight (layerIndex: number): number { assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, `Invalid layer index`); return this._layerRecords[layerIndex].weight; } - public setLayerWeight (layerIndex: number, weight: number) { + public setLayerWeight (layerIndex: number, weight: number): void { assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, `Invalid layer index`); this._layerRecords[layerIndex].weight = weight; } - public getLayerTopLevelStateMachineEvaluation (layerIndex: number) { + public getLayerTopLevelStateMachineEvaluation (layerIndex: number): TopLevelStateMachineEvaluation { return this._layerRecords[layerIndex].stateMachineEvaluation; } - public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext) { + public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { const { _layerRecords: layerRecords } = this; const nLayers = layerRecords.length; for (let iLayer = 0; iLayer < nLayers; ++iLayer) { @@ -152,11 +152,11 @@ class LayerEvaluationRecord { bindingContext._unsetLayerWideContextProperties(); } - get stateMachineEvaluation () { + get stateMachineEvaluation (): TopLevelStateMachineEvaluation { return this._topLevelStateMachineEval; } - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { if (this._mask) { this.transformFilter = context.createTransformFilter(this._mask); } @@ -168,13 +168,13 @@ class LayerEvaluationRecord { this._topLevelStateMachineEval.settle(context); } - public update (context: AnimationGraphUpdateContext) { + public update (context: AnimationGraphUpdateContext): void { this.stateMachineEvaluation.update(context); this._motionSyncManager.sync(); } - public postEvaluate () { + public postEvaluate (): void { // Reset stash resources. this._stashManager.reset(); } diff --git a/cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts b/cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts index ea4c1c119d1..d3511889abe 100644 --- a/cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts +++ b/cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts @@ -129,7 +129,7 @@ class PoseGraphNodeInputManager { constructor: Constructor, propertyKey: string, options: PoseGraphNodeInputMappingOptions, - ) { + ): void { let classInputRecord = this._classInputMap.get(constructor); if (!classInputRecord) { classInputRecord = { @@ -161,7 +161,7 @@ class PoseGraphNodeInputManager { public getInputKeys (object: PoseGraphNode): readonly PoseGraphInputKey[] { const result: PoseGraphInputKey[] = []; - const getInputKeysRecurse = (constructor: null | Constructor) => { + const getInputKeysRecurse = (constructor: null | Constructor): void => { if (!constructor) { return; } @@ -189,7 +189,7 @@ class PoseGraphNodeInputManager { return result; } - public isPoseInput (object: PoseGraphNode, key: PoseGraphInputKey) { + public isPoseInput (object: PoseGraphNode, key: PoseGraphInputKey): boolean { const [propertyKey] = key; const propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey); if (!propertyInputRecord) { @@ -225,7 +225,7 @@ class PoseGraphNodeInputManager { }; } - public hasInput (object: PoseGraphNode, key: PoseGraphInputKey) { + public hasInput (object: PoseGraphNode, key: PoseGraphInputKey): boolean { const [propertyKey, elementIndex = -1] = key; const record = this._getPropertyNodeInputRecord(object.constructor, propertyKey); if (!record) { @@ -262,7 +262,7 @@ class PoseGraphNodeInputManager { return result; } - public deleteInput (graph: PoseGraph, node: PoseGraphNode, key: PoseGraphInputKey) { + public deleteInput (graph: PoseGraph, node: PoseGraphNode, key: PoseGraphInputKey): void { const [ propertyKey, elementIndex = -1, @@ -300,7 +300,7 @@ class PoseGraphNodeInputManager { deletePoseGraphNodeArrayElement(graph, node, key); } - public insertInput (graph: PoseGraph, node: PoseGraphNode, insertId: PoseGraphNodeInputInsertId) { + public insertInput (graph: PoseGraph, node: PoseGraphNode, insertId: PoseGraphNodeInputInsertId): void { const propertyKey = insertId; const propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey); if (!propertyInputRecord) { @@ -364,7 +364,7 @@ class PoseGraphNodeInputManager { syncGroup: ArrayPropertySyncGroup, expectedOriginalSyncLength: number, insertHint: number, - ) { + ): void { for (let iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) { const syncedPropertyKey = syncGroup.members[iGroupMember]; const syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey); @@ -391,7 +391,7 @@ class PoseGraphNodeInputManager { syncGroup: ArrayPropertySyncGroup, expectedOriginalSyncLength: number, index: number, - ) { + ): void { for (let iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) { const syncedPropertyKey = syncGroup.members[iGroupMember]; const syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey); @@ -408,7 +408,7 @@ class PoseGraphNodeInputManager { } } -function insertPoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, inputKey: PoseGraphInputKey, value: unknown) { +function insertPoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, inputKey: PoseGraphInputKey, value: unknown): void { const shell = graph.getShell(node); if (!shell) { throw new OperationOnFreestandingNodeError(node); @@ -430,7 +430,7 @@ function insertPoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, false); } -function deletePoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, inputKey: PoseGraphInputKey) { +function deletePoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, inputKey: PoseGraphInputKey): void { const shell = graph.getShell(node); if (!shell) { throw new OperationOnFreestandingNodeError(node); @@ -458,7 +458,7 @@ function deletePoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, true); } -function createDefaultInputValueByType (type: PoseGraphType) { +function createDefaultInputValueByType (type: PoseGraphType): false | 0 | Vec3 | Quat | null { switch (type) { default: assertIsTrue(false); diff --git a/cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts b/cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts index 7595449a7e0..910f3a0f94f 100644 --- a/cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts +++ b/cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts @@ -85,7 +85,7 @@ export function getPoseGraphNodeEditorMetadata ( return nodeEditorMetadataMap.get(classConstructor); } -export function getOrCreateNodeEditorMetadata (constructor: Constructor) { +export function getOrCreateNodeEditorMetadata (constructor: Constructor): PoseGraphNodeEditorMetadata { const existing = nodeEditorMetadataMap.get(constructor); if (existing) { return existing; diff --git a/cocos/animation/marionette/pose-graph/foundation/node-shell.ts b/cocos/animation/marionette/pose-graph/foundation/node-shell.ts index 385f55059fe..947a3a72074 100644 --- a/cocos/animation/marionette/pose-graph/foundation/node-shell.ts +++ b/cocos/animation/marionette/pose-graph/foundation/node-shell.ts @@ -38,7 +38,7 @@ export class PoseGraphNodeShell extends EditorExtendable { * Gets all bindings on this node. * @returns @zh 绑定对象数组。 @en The binding objects array. */ - public getBindings () { + public getBindings (): PoseGraphNodeInputBinding[] { return this._bindings; } @@ -55,7 +55,7 @@ export class PoseGraphNodeShell extends EditorExtendable { * @en A binding is keyed by the 3-element tuple: input path, producer node and producer output index. * Redundantly adding a binding takes no effect. */ - public addBinding (inputPath: NodeInputPath, producer: PoseGraphNode, outputIndex: number) { + public addBinding (inputPath: NodeInputPath, producer: PoseGraphNode, outputIndex: number): void { this._emplaceBinding(new PoseGraphNodeInputBinding( inputPath, producer, @@ -70,7 +70,7 @@ export class PoseGraphNodeShell extends EditorExtendable { * Deletes the binding on specified input. * @param inputPath @zh 要解绑的输入的路径。 @en Path of the input to unbind. */ - public deleteBinding (inputPath: NodeInputPath) { + public deleteBinding (inputPath: NodeInputPath): void { const index = this._findBindingIndex(inputPath); if (index >= 0) { this._bindings.splice(index, 1); @@ -91,7 +91,7 @@ export class PoseGraphNodeShell extends EditorExtendable { * @param forward @en 替换的方向。`true` 表示向前替换,反之向后。 * @en Substitution direction. `true` means substitute in forward, backward otherwise. */ - public moveArrayElementBindingForward (propertyKey: string, firstIndex: number, forward: boolean) { + public moveArrayElementBindingForward (propertyKey: string, firstIndex: number, forward: boolean): void { // TODO: this method has worse performance! const { _bindings: bindings } = this; @@ -125,7 +125,7 @@ export class PoseGraphNodeShell extends EditorExtendable { * Deletes all the bindings bound to specified producer. * @param producer @zh 生产方结点。 @en The producer node. */ - public deleteBindingTo (producer: PoseGraphNode) { + public deleteBindingTo (producer: PoseGraphNode): void { const { _bindings: bindings } = this; for (let iBinding = 0; iBinding < bindings.length; // Note: array length might vary @@ -153,13 +153,13 @@ export class PoseGraphNodeShell extends EditorExtendable { @serializable private _bindings: PoseGraphNodeInputBinding[] = []; - private _findBindingIndex (inputPath: NodeInputPath) { + private _findBindingIndex (inputPath: NodeInputPath): number { return this._bindings.findIndex( (searchElement) => isEqualNodeInputPath(searchElement.inputPath, inputPath), ); } - private _emplaceBinding (binding: PoseGraphNodeInputBinding) { + private _emplaceBinding (binding: PoseGraphNodeInputBinding): void { const index = this._bindings.findIndex( (searchElement) => isEqualNodeInputPath(searchElement.inputPath, binding.inputPath), ); @@ -171,7 +171,7 @@ export class PoseGraphNodeShell extends EditorExtendable { } } -function isEqualNodeInputPath (lhs: NodeInputPath, rhs: NodeInputPath) { +function isEqualNodeInputPath (lhs: NodeInputPath, rhs: NodeInputPath): boolean { const [lhsPropertyKey, lhsElementIndex] = lhs; const [rhsPropertyKey, rhsElementIndex] = rhs; return lhsPropertyKey === rhsPropertyKey && lhsElementIndex === rhsElementIndex; @@ -197,7 +197,7 @@ class PoseGraphNodeInputBinding { * @zh 消费方结点的输入路径。 * @en Input path of consumer node. */ - get inputPath () { + get inputPath (): NodeInputPath { return this._inputPath; } @@ -205,7 +205,7 @@ class PoseGraphNodeInputBinding { * @zh 生产方结点。 * @en The producer node. */ - get producer () { + get producer (): PoseGraphNode { return this._producer; } @@ -213,7 +213,7 @@ class PoseGraphNodeInputBinding { * @zh 生产方结点的输出索引。 * @en The producer node's output index. */ - get outputIndex () { + get outputIndex (): number { return this._outputIndex; } diff --git a/cocos/animation/marionette/pose-graph/instantiation.ts b/cocos/animation/marionette/pose-graph/instantiation.ts index 32e32a6cb84..ff33b011e1f 100644 --- a/cocos/animation/marionette/pose-graph/instantiation.ts +++ b/cocos/animation/marionette/pose-graph/instantiation.ts @@ -13,6 +13,7 @@ import { AnimationGraphBindingContext, AnimationGraphSettleContext, AnimationGraphUpdateContext, AnimationGraphEvaluationContext, } from '../animation-graph-context'; +import type { Pose } from '../../core/pose'; type EvaluatableNode = PoseNode | PureValueNode; @@ -28,27 +29,27 @@ class InstantiatedPoseGraph { } - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { this._rootPoseNode?.bind(context); } - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { this._rootPoseNode?.settle(context); } - public reenter () { + public reenter (): void { this._rootPoseNode?.reenter(); } - public update (context: AnimationGraphUpdateContext) { + public update (context: AnimationGraphUpdateContext): void { this._rootPoseNode?.update(context); } - public evaluate (context: AnimationGraphEvaluationContext) { + public evaluate (context: AnimationGraphEvaluationContext): Pose | null { return this._rootPoseNode?.evaluate(context, PoseTransformSpaceRequirement.LOCAL) ?? null; } - public countMotionTime () { + public countMotionTime (): number { const { _countingPlayMotionNodes: playMotionNodes } = this; if (!playMotionNodes) { if (DEBUG) { @@ -239,23 +240,23 @@ class RuntimePVNodeEvaluation { this._outputs = new Array(_node.outputCount); } - get node () { + get node (): PureValueNode { return this._node; } - public get outputCount () { + public get outputCount (): number { return this._outputs.length; } - public getDefaultOutput () { + public getDefaultOutput (): unknown { return this.getOutput(0); } - public getOutput (outputIndex: number) { + public getOutput (outputIndex: number): unknown { return this._outputs[outputIndex]; } - public evaluate () { + public evaluate (): void { const { _node: node, _dependency: dependency, @@ -276,7 +277,7 @@ function linkPoseNode ( consumerInputPath: NodeInputPath, producerNode: PoseNode, producerOutputIndex: number, -) { +): void { const [consumerPropertyKey, consumerElementIndex = -1] = consumerInputPath; if (!(consumerPropertyKey in consumerNode)) { // Invalid binding. @@ -341,7 +342,7 @@ class RuntimePVNodePlainPropertyBinding implements RuntimePVNodePropertyBinding ) { } - public evaluate () { + public evaluate (): void { this._producerRecord.evaluate(); this._consumerNode[this._consumerPropertyKey] = this._producerRecord.getOutput(this._producerOutputIndex); } @@ -357,7 +358,7 @@ class RuntimePVNodeArrayElementPropertyBinding implements RuntimePVNodePropertyB ) { } - public evaluate () { + public evaluate (): void { this._producerRecord.evaluate(); this._consumerNode[this._consumerPropertyKey][this._consumerElementIndex] = this._producerRecord.getOutput(this._producerOutputIndex); } diff --git a/cocos/animation/marionette/pose-graph/motion-sync/runtime-motion-sync.ts b/cocos/animation/marionette/pose-graph/motion-sync/runtime-motion-sync.ts index 717f3cbb8ef..e23653c257f 100644 --- a/cocos/animation/marionette/pose-graph/motion-sync/runtime-motion-sync.ts +++ b/cocos/animation/marionette/pose-graph/motion-sync/runtime-motion-sync.ts @@ -15,7 +15,7 @@ export class RuntimeMotionSyncManager { return group.addMember(); } - public sync () { + public sync (): void { for (const group of this._groups) { group.sync(); } @@ -34,7 +34,7 @@ class Group { return record; } - public sync () { + public sync (): void { const { _records: records, } = this; @@ -110,7 +110,7 @@ class RuntimeMotionSyncRecordImpl implements RuntimeMotionSyncRecord { this.normalizedTime = normalizedTime; } - public notifyUpdate (normalizedDeltaTime: number, weight: number) { + public notifyUpdate (normalizedDeltaTime: number, weight: number): void { this.normalizedTime += normalizedDeltaTime; // Note: we're allowing update multiple times. The first update becomes "activate". if (this.active) { @@ -121,7 +121,7 @@ class RuntimeMotionSyncRecordImpl implements RuntimeMotionSyncRecord { } } - public reset () { + public reset (): void { this.active = false; this.weight = 0.0; } diff --git a/cocos/animation/marionette/pose-graph/op/index.ts b/cocos/animation/marionette/pose-graph/op/index.ts index 14ed09279d5..ac5d3bd16f3 100644 --- a/cocos/animation/marionette/pose-graph/op/index.ts +++ b/cocos/animation/marionette/pose-graph/op/index.ts @@ -1,4 +1,3 @@ - import * as poseGraphOp from './internal'; export { poseGraphOp }; diff --git a/cocos/animation/marionette/pose-graph/pose-graph.ts b/cocos/animation/marionette/pose-graph/pose-graph.ts index 4d31a3a23fc..09063f6f57c 100644 --- a/cocos/animation/marionette/pose-graph/pose-graph.ts +++ b/cocos/animation/marionette/pose-graph/pose-graph.ts @@ -23,7 +23,7 @@ export class PoseGraph extends EditorExtendable { * @zh 姿势图的输出结点。 * @en The pose graph's output node. */ - public get outputNode () { + public get outputNode (): PoseGraphOutputNode { return this._outputNode; } @@ -31,7 +31,7 @@ export class PoseGraph extends EditorExtendable { * // TODO: HACK * @internal */ - public __callOnAfterDeserializeRecursive () { + public __callOnAfterDeserializeRecursive (): void { assertIsTrue(this._nodes.length === this._shells.length); for (let iNode = 0; iNode < this._nodes.length; ++iNode) { const node = this._nodes[iNode]; @@ -61,7 +61,7 @@ export class PoseGraph extends EditorExtendable { * @en Note, the node to add should be "freestanding", * means it should not been already in any graph. Otherwise, an exception would be thrown. */ - public addNode (node: TNode) { + public addNode (node: TNode): TNode { if (this._shellMap.has(node)) { throw new AddNonFreestandingNodeError(node); } @@ -82,7 +82,7 @@ export class PoseGraph extends EditorExtendable { * @en If the removal node is not within graph or is the output node of graph, * this method takes no effect. */ - public removeNode (removal: PoseGraphNode) { + public removeNode (removal: PoseGraphNode): void { if (removal === this._outputNode) { error(`Can not remove the output node.`); return; @@ -114,7 +114,7 @@ export class PoseGraph extends EditorExtendable { * Gets the specified node's shell in pose graph. * @internal */ - public getShell (node: PoseGraphNode) { + public getShell (node: PoseGraphNode): PoseGraphNodeShell | undefined { return this._shellMap.get(node); } diff --git a/cocos/animation/marionette/pose-graph/pose-node.ts b/cocos/animation/marionette/pose-graph/pose-node.ts index cee5b587dc3..4dd82a19c29 100644 --- a/cocos/animation/marionette/pose-graph/pose-node.ts +++ b/cocos/animation/marionette/pose-graph/pose-node.ts @@ -71,7 +71,7 @@ export abstract class PoseNode extends PoseGraphNode { * * @note Subclasses shall not override this method and should override `doUpdate` instead. */ - public update (context: AnimationGraphUpdateContext) { + public update (context: AnimationGraphUpdateContext): void { this._dependencyEvaluation?.evaluate(); this.doUpdate(context); } @@ -84,7 +84,7 @@ export abstract class PoseNode extends PoseGraphNode { * * @note Subclasses shall not override this method and should override `doEvaluate` instead. */ - public evaluate (context: AnimationGraphEvaluationContext, poseTransformSpaceRequirement: PoseTransformSpaceRequirement) { + public evaluate (context: AnimationGraphEvaluationContext, poseTransformSpaceRequirement: PoseTransformSpaceRequirement): Pose { let stackSizeBefore!: number; if (POSE_NODE_EVALUATION_STACK_ORDER_DEBUG_ENABLED) { stackSizeBefore = context._stackSize_debugging; @@ -128,7 +128,7 @@ export abstract class PoseNode extends PoseGraphNode { return pose; } - public static evaluateDefaultPose (context: AnimationGraphEvaluationContext, poseTransformSpaceRequirement: PoseTransformSpaceRequirement) { + public static evaluateDefaultPose (context: AnimationGraphEvaluationContext, poseTransformSpaceRequirement: PoseTransformSpaceRequirement): Pose { switch (poseTransformSpaceRequirement) { default: assertIsTrue(false); @@ -142,7 +142,7 @@ export abstract class PoseNode extends PoseGraphNode { } /** @internal */ - public _setDependencyEvaluation (dependency: PoseNodeDependencyEvaluation) { + public _setDependencyEvaluation (dependency: PoseNodeDependencyEvaluation): void { this._dependencyEvaluation = dependency; } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts b/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts index 500f98c48e5..77cffebd07f 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts @@ -1,5 +1,5 @@ import { ccclass, serializable } from '../../../../core/data/decorators'; -import { applyDeltaPose } from '../../../core/pose'; +import { Pose, applyDeltaPose } from '../../../core/pose'; import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; import { poseGraphNodeAppearance, poseGraphNodeCategory } from '../decorator/node'; import { POSE_GRAPH_NODE_MENU_PREFIX_POSE_BLEND } from './menu-common'; @@ -31,7 +31,7 @@ export class PoseNodeAdditivelyBlend extends PoseNode { @input({ type: PoseGraphType.FLOAT }) public ratio = 1.0; - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { this.basePose?.bind(context); context._pushAdditiveFlag(true); this.additivePose?.bind(context); @@ -43,7 +43,7 @@ export class PoseNodeAdditivelyBlend extends PoseNode { this.additivePose?.settle(context); } - public reenter () { + public reenter (): void { this.basePose?.reenter(); this.additivePose?.reenter(); } @@ -53,7 +53,7 @@ export class PoseNodeAdditivelyBlend extends PoseNode { this.additivePose?.update(context); } - public doEvaluate (context: AnimationGraphEvaluationContext) { + public doEvaluate (context: AnimationGraphEvaluationContext): Pose { const basePose = this.basePose?.evaluate(context, PoseTransformSpaceRequirement.LOCAL) ?? context.pushDefaultedPose(); if (!this.additivePose) { return basePose; diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts b/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts index 6425f6b69fd..6ba4f5524cc 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts @@ -71,7 +71,7 @@ export class PoseNodeApplyTransform extends PoseNodeModifyPoseBase { public transformSpace: TransformSpace = TransformSpace.WORLD; @input({ type: PoseGraphType.FLOAT }) - public get intensityValue () { + public get intensityValue (): number { return this.intensity.value; } @@ -79,7 +79,7 @@ export class PoseNodeApplyTransform extends PoseNodeModifyPoseBase { this.intensity.value = value; } - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { const { node: nodeName, } = this; @@ -101,11 +101,11 @@ export class PoseNodeApplyTransform extends PoseNodeModifyPoseBase { this.intensity.bind(context); } - protected getPoseTransformSpaceRequirement () { + protected getPoseTransformSpaceRequirement (): PoseTransformSpaceRequirement { return PoseTransformSpaceRequirement.NO; } - protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose, modificationQueue: TransformModificationQueue) { + protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose, modificationQueue: TransformModificationQueue): Pose { const { _transformHandle: transformHandle, } = this; @@ -190,7 +190,10 @@ export class PoseNodeApplyTransform extends PoseNodeModifyPoseBase { const { replace: replacePosition, add: addPosition, -} = (() => { +} = ((): { + replace: (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) => void, + add: (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) => void, +} => { const cacheInput = new Vec3(); const cacheResult = new Vec3(); @@ -199,7 +202,7 @@ const { add, }; - function replace (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) { + function replace (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean): void { if (fullIntensity) { transform.position = value; } else { @@ -209,7 +212,7 @@ const { } } - function add (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) { + function add (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean): void { const result = cacheResult; if (fullIntensity) { Vec3.copy(result, value); @@ -224,7 +227,10 @@ const { const { replace: replaceRotation, add: addRotation, -} = (() => { +} = ((): { + replace: (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) => void, + add: (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) => void, +} => { const cacheInput = new Quat(); const cacheResult = new Quat(); @@ -233,7 +239,7 @@ const { add, }; - function replace (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) { + function replace (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean): void { if (fullIntensity) { transform.rotation = value; } else { @@ -243,7 +249,7 @@ const { } } - function add (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean) { + function add (transform: Transform, value: Readonly, intensity: number, fullIntensity: boolean): void { const inputRotation = Quat.copy(cacheInput, transform.rotation); const resultRotation = cacheResult; if (fullIntensity) { @@ -257,7 +263,7 @@ const { })(); if (EDITOR) { - PoseNodeApplyTransform.prototype.getTitle = function getTitle (this: PoseNodeApplyTransform) { + PoseNodeApplyTransform.prototype.getTitle = function getTitle (this: PoseNodeApplyTransform): string | [string, Record] | undefined { if (this.node) { return [`ENGINE.classes.${CLASS_NAME_PREFIX_ANIM}PoseNodeApplyTransform.title`, { nodeName: this.node }]; } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts b/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts index 5bcc6c2e5f7..ed84d2a146e 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts @@ -31,7 +31,7 @@ export class PoseNodeBlendInProportion extends PoseNode { }) public readonly proportions: number[] = []; - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { for (const pose of this.poses) { pose?.bind(context); } @@ -43,7 +43,7 @@ export class PoseNodeBlendInProportion extends PoseNode { } } - public reenter () { + public reenter (): void { for (const pose of this.poses) { pose?.reenter(); } @@ -67,7 +67,7 @@ export class PoseNodeBlendInProportion extends PoseNode { } } - public doEvaluate (context: AnimationGraphEvaluationContext) { + public doEvaluate (context: AnimationGraphEvaluationContext): Pose { const nInputPoses = this.poses.length; let sumWeight = 0.0; let finalPose: Pose | null = null; diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts b/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts index b18f8ed58ab..e87ce7e4b8e 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts @@ -24,7 +24,7 @@ export abstract class PoseNodeBlendTwoPoseBase extends PoseNode { @input({ type: PoseGraphType.FLOAT }) ratio = 1.0; - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { this.pose0?.bind(context); this.pose1?.bind(context); } @@ -34,7 +34,7 @@ export abstract class PoseNodeBlendTwoPoseBase extends PoseNode { this.pose1?.settle(context); } - public reenter () { + public reenter (): void { this.pose0?.reenter(); this.pose1?.reenter(); } @@ -62,7 +62,7 @@ export abstract class PoseNodeBlendTwoPoseBase extends PoseNode { } } - public doEvaluate (context: AnimationGraphEvaluationContext) { + public doEvaluate (context: AnimationGraphEvaluationContext): Pose { const spaceRequirement = PoseTransformSpaceRequirement.LOCAL; if (!this.pose0 || !this.pose1) { return PoseNodeBlendTwoPoseBase.evaluateDefaultPose(context, spaceRequirement); diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-base.ts b/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-base.ts index 3aba4a3fedc..7308d4f19a0 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-base.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-base.ts @@ -23,7 +23,7 @@ export abstract class PoseNodeChoosePoseBase extends PoseNode { this._fadeInDurations.fill(0.0); } - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { for (const pose of this._poses) { pose?.bind(context); } @@ -37,7 +37,7 @@ export abstract class PoseNodeChoosePoseBase extends PoseNode { } } - public reenter () { + public reenter (): void { for (const pose of this._poses) { pose?.reenter(); } @@ -81,7 +81,7 @@ export abstract class PoseNodeChoosePoseBase extends PoseNode { } } - public doEvaluate (context: AnimationGraphEvaluationContext) { + public doEvaluate (context: AnimationGraphEvaluationContext): Pose { const { _poses: poses, _evaluationRecord: evaluationRecord, @@ -130,7 +130,7 @@ export abstract class PoseNodeChoosePoseBase extends PoseNode { @serializable protected _fadeInDurations: number[] = []; - protected getChosenIndex () { + protected getChosenIndex (): number { return 0; } @@ -144,7 +144,7 @@ class EvaluationRecord { itemCount: number, initialChosenIndex: number, ) { - const items = Array.from({ length: itemCount }, () => new ItemEvaluationRecord()); + const items = Array.from({ length: itemCount }, (): ItemEvaluationRecord => new ItemEvaluationRecord()); if (initialChosenIndex >= 0 && initialChosenIndex < itemCount) { items[initialChosenIndex].selfSourceWeight = 1.0; items[initialChosenIndex].selfTargetWeight = 1.0; @@ -157,11 +157,11 @@ class EvaluationRecord { return this._items; } - public allWeightsAreZero () { + public allWeightsAreZero (): boolean { return this._chosenPoseIndex < 0; } - public update (deltaTime: number, newChoseIndex: number, fadeInDurations: readonly number[]) { + public update (deltaTime: number, newChoseIndex: number, fadeInDurations: readonly number[]): void { assertIsTrue(deltaTime >= 0.0); this._checkAlternation(newChoseIndex, fadeInDurations); @@ -218,7 +218,7 @@ class EvaluationRecord { private _blendingDuration = 0.0; - private _checkAlternation (newChoseIndex: number, fadeInDurations: readonly number[]) { + private _checkAlternation (newChoseIndex: number, fadeInDurations: readonly number[]): void { const { _items: items, _chosenPoseIndex: oldChoseIndex, diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-boolean.ts b/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-boolean.ts index 7dd293604d4..f95e6e1e4ac 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-boolean.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-boolean.ts @@ -5,6 +5,7 @@ import { poseGraphNodeAppearance, poseGraphNodeCategory } from '../../decorator/ import { POSE_GRAPH_NODE_MENU_PREFIX_CHOOSE } from './menu'; import { PoseNodeChoosePoseBase } from './choose-pose-base'; import { PoseGraphType } from '../../foundation/type-system'; +import type { PoseNode } from '../../pose-node'; @ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseNodeChoosePoseByBoolean`) @poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_CHOOSE) @@ -15,7 +16,7 @@ export class PoseNodeChoosePoseByBoolean extends PoseNodeChoosePoseBase { } @input({ type: PoseGraphType.POSE }) - public get truePose () { + public get truePose (): PoseNode | null { return this._poses[0]; } public set truePose (value) { @@ -23,7 +24,7 @@ export class PoseNodeChoosePoseByBoolean extends PoseNodeChoosePoseBase { } @input({ type: PoseGraphType.POSE }) - public get falsePose () { + public get falsePose (): PoseNode | null { return this._poses[1]; } public set falsePose (value) { @@ -31,7 +32,7 @@ export class PoseNodeChoosePoseByBoolean extends PoseNodeChoosePoseBase { } @input({ type: PoseGraphType.FLOAT }) - public get trueFadeInDuration () { + public get trueFadeInDuration (): number { return this._fadeInDurations[0]; } public set trueFadeInDuration (value) { @@ -39,7 +40,7 @@ export class PoseNodeChoosePoseByBoolean extends PoseNodeChoosePoseBase { } @input({ type: PoseGraphType.FLOAT }) - public get falseFadeInDuration () { + public get falseFadeInDuration (): number { return this._fadeInDurations[1]; } public set falseFadeInDuration (value) { @@ -50,7 +51,7 @@ export class PoseNodeChoosePoseByBoolean extends PoseNodeChoosePoseBase { @input({ type: PoseGraphType.BOOLEAN }) public choice = true; - protected getChosenIndex () { + protected getChosenIndex (): number { return this.choice ? 0 : 1; } } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-index.ts b/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-index.ts index 62e0f3c8d8e..36b672f2d6e 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-index.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/choose-pose/choose-pose-by-index.ts @@ -6,6 +6,7 @@ import { poseGraphNodeAppearance, poseGraphNodeCategory } from '../../decorator/ import { POSE_GRAPH_NODE_MENU_PREFIX_CHOOSE } from './menu'; import { PoseNodeChoosePoseBase } from './choose-pose-base'; import { PoseGraphType } from '../../foundation/type-system'; +import type { PoseNode } from '../../pose-node'; @ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseNodeChoosePoseByIndex`) @poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_CHOOSE) @@ -15,7 +16,7 @@ export class PoseNodeChoosePoseByIndex extends PoseNodeChoosePoseBase { type: PoseGraphType.POSE, arraySyncGroup: 'choose-item', }) - get poses () { + get poses (): (PoseNode | null)[] { return this._poses; } @@ -28,7 +29,7 @@ export class PoseNodeChoosePoseByIndex extends PoseNodeChoosePoseBase { arraySyncGroup: 'choose-item', arraySyncGroupFollower: true, }) - get fadeInDurations () { + get fadeInDurations (): number[] { return this._fadeInDurations; } @@ -40,7 +41,7 @@ export class PoseNodeChoosePoseByIndex extends PoseNodeChoosePoseBase { @input({ type: PoseGraphType.INTEGER }) public choice = 0; - protected getChosenIndex () { + protected getChosenIndex (): number { return this.choice; } } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/copy-transform.ts b/cocos/animation/marionette/pose-graph/pose-nodes/copy-transform.ts index 1b9c0117e80..08d6da946e2 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/copy-transform.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/copy-transform.ts @@ -58,7 +58,7 @@ export class PoseNodeCopyTransform extends PoseNodeModifyPoseBase { ); } - protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose) { + protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose): void { const { _workspace: workspace, } = this; @@ -73,7 +73,7 @@ export class PoseNodeCopyTransform extends PoseNodeModifyPoseBase { inputPose.transforms.setTransform(targetTransformIndex, transform); } - protected getPoseTransformSpaceRequirement () { + protected getPoseTransformSpaceRequirement (): PoseTransformSpaceRequirement { return this.space === CopySpace.COMPONENT ? PoseTransformSpaceRequirement.COMPONENT : PoseTransformSpaceRequirement.LOCAL; } @@ -89,7 +89,7 @@ class Workspace { } if (EDITOR) { - PoseNodeCopyTransform.prototype.getTitle = function getTitle (this: PoseNodeCopyTransform) { + PoseNodeCopyTransform.prototype.getTitle = function getTitle (this: PoseNodeCopyTransform): string | [string, Record] | undefined { if (this.sourceNodeName && this.targetNodeName) { return [`ENGINE.classes.${CLASS_NAME_PREFIX_ANIM}PoseNodeCopyTransform.title`, { sourceNodeName: this.sourceNodeName, diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/ik/solve-two-bone-ik.ts b/cocos/animation/marionette/pose-graph/pose-nodes/ik/solve-two-bone-ik.ts index abc41354843..f0d1825b05f 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/ik/solve-two-bone-ik.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/ik/solve-two-bone-ik.ts @@ -6,13 +6,13 @@ import { debugTwoBoneIKDraw } from './two-bone-ik-debugger'; const SANITY_CHECK_ENABLED = DEBUG; class TwoBoneIKPositionSanityChecker { - public reset (a: Readonly, b: Readonly, c: Readonly) { + public reset (a: Readonly, b: Readonly, c: Readonly): void { Vec3.copy(this._a, a); this._dAB = Vec3.distance(a, b); this._dBC = Vec3.distance(b, c); } - public check (_a: Readonly, _b: Readonly, _c: Readonly) { + public check (_a: Readonly, _b: Readonly, _c: Readonly): boolean { const CHECK_EPSILON = 1e-3; const dAB = Vec3.distance(_a, _b); const dBC = Vec3.distance(_b, _c); @@ -48,13 +48,13 @@ class TwoBoneIKPositionSanityChecker { * @param target 末端关节要抵达的目标位置(世界空间)。 * @param hint 中间关节的提示位置(世界空间),用于决定中间关节的朝向。 */ -export const solveTwoBoneIK = (() => { +export const solveTwoBoneIK = ((): (root: Transform, middle: Transform, end: Transform, target: Vec3, middlePositionHint?: Vec3, debugKey?: unknown | undefined) => void => { const cacheQuat = new Quat(); const cacheHint = new Vec3(); const cacheBSolved = new Vec3(); const cacheCSolved = new Vec3(); - const calculateRotationBetweenRays = (() => { + const calculateRotationBetweenRays = ((): (out: Quat, sourceOrigin: Readonly, sourceDestination: Readonly, targetOrigin: Readonly, targetDestination: Readonly) => Quat => { const cacheVec3_1 = new Vec3(); const cacheVec3_2 = new Vec3(); return ( @@ -62,7 +62,7 @@ export const solveTwoBoneIK = (() => { sourceOrigin: Readonly, sourceDestination: Readonly, targetOrigin: Readonly, targetDestination: Readonly, // eslint-disable-next-line arrow-body-style - ) => { + ): Quat => { return Quat.rotationTo( out, Vec3.subtract(cacheVec3_1, sourceDestination, sourceOrigin).normalize(), @@ -78,7 +78,7 @@ export const solveTwoBoneIK = (() => { target: Vec3, middlePositionHint?: Vec3, debugKey?: unknown | undefined, - ) => { + ): void => { const hint = Vec3.copy(cacheHint, middlePositionHint ?? middle.position); const pA = root.position; @@ -125,7 +125,7 @@ export const solveTwoBoneIK = (() => { }; })(); -export const solveTwoBoneIKPositions = (() => { +export const solveTwoBoneIKPositions = ((): (a: Readonly, b: Readonly, c: Readonly, target: Readonly, middleTarget: Readonly, bSolved: Vec3, cSolved: Vec3) => void => { const cacheDirAT = new Vec3(); const cacheDirAB = new Vec3(); const cacheDirHeightLine = new Vec3(); @@ -141,11 +141,11 @@ export const solveTwoBoneIKPositions = (() => { middleTarget: Readonly, bSolved: Vec3, cSolved: Vec3, - ) => { + ): void => { const sanityCheck = cacheSanityChecker - ? (() => { + ? ((): () => boolean => { cacheSanityChecker?.reset(a, b, c); - return () => cacheSanityChecker.check(a, bSolved, cSolved); + return (): boolean => cacheSanityChecker.check(a, bSolved, cSolved); })() : undefined; diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-debugger.ts b/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-debugger.ts index 9772ed55548..96c6d07c713 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-debugger.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-debugger.ts @@ -12,7 +12,7 @@ export class TwoBoneIKDebugger { legacyCC.director.getScene().addChild(node); const meshRenderer = node.addComponent(MeshRenderer); - meshRenderer.material = (() => { + meshRenderer.material = ((): Material => { const material = new Material(); material.reset({ effectName: 'builtin-unlit', @@ -30,7 +30,7 @@ export class TwoBoneIKDebugger { this._meshRenderer = meshRenderer; } - public draw (a: Readonly, b: Readonly, c: Readonly) { + public draw (a: Readonly, b: Readonly, c: Readonly): void { const color1 = Color.RED; const color2 = Color.BLUE; const positions: number[] = [ @@ -63,7 +63,7 @@ const debuggerMap = new WeakMap(); export function debugTwoBoneIKDraw ( key: unknown, a: Readonly, b: Readonly, c: Readonly, -) { +): void { if (typeof key !== 'object' || !key) { return; } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts b/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts index 7b9709db09a..566ca523610 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts @@ -68,14 +68,14 @@ class TargetSpecification { @visible(function visible(this: TargetSpecification) { return this.type === TargetSpecificationType.BONE; }) public targetBone = ''; - public bind (context: AnimationGraphBindingContext, sourceBoneHandle: TransformHandle) { + public bind (context: AnimationGraphBindingContext, sourceBoneHandle: TransformHandle): void { this._sourceBoneHandle = sourceBoneHandle; if (this.type === TargetSpecificationType.BONE && this.targetBone) { this._targetBoneHandle = context.bindTransformByName(this.targetBone) ?? undefined; } } - public evaluate (outTargetPosition: Vec3, pose: Pose, context: AnimationGraphEvaluationContext) { + public evaluate (outTargetPosition: Vec3, pose: Pose, context: AnimationGraphEvaluationContext): Vec3 { assertIsTrue(this._sourceBoneHandle); if (this._targetBoneHandle) { pose.transforms.getPosition(this._targetBoneHandle.index, outTargetPosition); @@ -115,7 +115,7 @@ export class PoseNodeTwoBoneIKSolver extends PoseNodeModifyPoseBase { public readonly endEffectorTarget = new TargetSpecification(TargetSpecificationType.VALUE); @input({ type: PoseGraphType.VEC3 }) - get endEffectorTargetPosition () { + get endEffectorTargetPosition (): Vec3 { return this.endEffectorTarget.targetPosition; } @@ -128,7 +128,7 @@ export class PoseNodeTwoBoneIKSolver extends PoseNodeModifyPoseBase { public readonly poleTarget = new TargetSpecification(TargetSpecificationType.NONE); @input({ type: PoseGraphType.VEC3 }) - get poleTargetPosition () { + get poleTargetPosition (): Vec3 { return this.poleTarget.targetPosition; } @@ -164,11 +164,11 @@ export class PoseNodeTwoBoneIKSolver extends PoseNodeModifyPoseBase { } } - protected getPoseTransformSpaceRequirement () { + protected getPoseTransformSpaceRequirement (): PoseTransformSpaceRequirement { return PoseTransformSpaceRequirement.COMPONENT; } - protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose, modificationQueue: TransformModificationQueue) { + protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose, modificationQueue: TransformModificationQueue): void { const { _workspace: workspace, } = this; @@ -210,7 +210,7 @@ export class PoseNodeTwoBoneIKSolver extends PoseNodeModifyPoseBase { } if (EDITOR) { - PoseNodeTwoBoneIKSolver.prototype.getTitle = function getTitle (this: PoseNodeTwoBoneIKSolver) { + PoseNodeTwoBoneIKSolver.prototype.getTitle = function getTitle (this: PoseNodeTwoBoneIKSolver): string | [string, Record] | undefined { if (this.endEffectorBoneName) { return [`ENGINE.classes.${CLASS_NAME_PREFIX_ANIM}PoseNodeTwoBoneIKSolver.title`, { endEffectorBoneName: this.endEffectorBoneName, diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts b/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts index 556ff3b86f8..36a779ba580 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts @@ -21,22 +21,22 @@ export class IntensitySpecification { @serializable @editable - @visible(function visible (this: IntensitySpecification) { return this.type === IntensityType.VALUE; }) + @visible(function visible (this: IntensitySpecification): boolean { return this.type === IntensityType.VALUE; }) public value = 1.0; @serializable @editable - @visible(function visible (this: IntensitySpecification) { return this.type === IntensityType.AUXILIARY_CURVE; }) + @visible(function visible (this: IntensitySpecification): boolean { return this.type === IntensityType.AUXILIARY_CURVE; }) public auxiliaryCurveName = ''; - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { if (this.type === IntensityType.AUXILIARY_CURVE && this.auxiliaryCurveName) { const handle = context.bindAuxiliaryCurve(this.auxiliaryCurveName); this._handle = handle; } } - public evaluate (pose: Readonly) { + public evaluate (pose: Readonly): number { if (this.type === IntensityType.AUXILIARY_CURVE && this._handle) { const value = pose.auxiliaryCurves[this._handle.index]; return value; diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/modify-pose-base.ts b/cocos/animation/marionette/pose-graph/pose-nodes/modify-pose-base.ts index c5dde074adb..adc048af352 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/modify-pose-base.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/modify-pose-base.ts @@ -17,12 +17,12 @@ export abstract class PoseNodeModifyPoseBase extends PoseNode { @input({ type: PoseGraphType.POSE }) public pose: PoseNode | null = null; - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { this.pose?.settle(context); this._spaceFlagTable = new PoseTransformSpaceFlagTable(context.transformCount); } - public reenter () { + public reenter (): void { this.pose?.reenter(); } @@ -30,7 +30,7 @@ export abstract class PoseNodeModifyPoseBase extends PoseNode { this.pose?.bind(context); } - protected doUpdate (context: AnimationGraphUpdateContext) { + protected doUpdate (context: AnimationGraphUpdateContext): void { this.pose?.update(context); } @@ -69,15 +69,15 @@ class TransformModification { export type { TransformModification }; class TransformModificationQueue { - get length () { + get length (): number { return this._array.length; } - get array () { + get array (): TransformModification[] { return this._array.array; } - public push (transformIndex: number, transform: Transform) { + public push (transformIndex: number, transform: Transform): void { if (DEBUG) { assertIsTrue(transformIndex > this._debugLastTransformIndex, `Unexpected transform modification order`); this._debugLastTransformIndex = transformIndex; @@ -88,7 +88,7 @@ class TransformModificationQueue { this._array.push(mod); } - public clear () { + public clear (): void { const length = this._array.length; for (let iMod = 0; iMod < length; ++iMod) { const mod = this._array.get(iMod); @@ -101,7 +101,7 @@ class TransformModificationQueue { } } - private _pool: Pool = new Pool(() => new TransformModification(), 3); + private _pool: Pool = new Pool((): TransformModification => new TransformModification(), 3); private _array = new CachedArray(3); private _debugLastTransformIndex = -1; } @@ -116,7 +116,7 @@ class PoseTransformSpaceFlagTable { /** * Set all transforms' flags to false. */ - public clear () { + public clear (): void { this._transformFlags.fill(false); } @@ -125,7 +125,7 @@ class PoseTransformSpaceFlagTable { * @param transformIndex Transform index. * @returns True if the transform's flag is set to true. */ - public test (transformIndex: number) { + public test (transformIndex: number): boolean { return this._transformFlags[transformIndex]; } @@ -133,7 +133,7 @@ class PoseTransformSpaceFlagTable { * Sets the transform's flag to true. * @param transformIndex Transform index. */ - public set (transformIndex: number) { + public set (transformIndex: number): void { this._transformFlags[transformIndex] = true; } @@ -141,7 +141,7 @@ class PoseTransformSpaceFlagTable { * Sets the transform's flag to false. * @param transformIndex Transform index. */ - public unset (transformIndex: number) { + public unset (transformIndex: number): void { this._transformFlags[transformIndex] = false; } @@ -156,7 +156,7 @@ function applyTransformModificationQueue ( pose: Pose, queue: TransformModificationQueue, spaceFlagTable: PoseTransformSpaceFlagTable, -) { +): void { const nMods = queue.length; if (nMods === 0) { return; diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts b/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts index 54334f51590..a93d7606d64 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts @@ -16,6 +16,7 @@ import { AnimationGraphBindingContext, AnimationGraphEvaluationContext, AnimationGraphSettleContext, AnimationGraphUpdateContext, } from '../../animation-graph-context'; import { clamp01 } from '../../../../core'; +import type { Pose } from '../../../core/pose'; const ZERO_DURATION_THRESHOLD = 1e-5; @@ -51,18 +52,18 @@ export class PoseNodePlayMotion extends PoseNode { /** * The weight of this node indicated in last update. */ - get lastIndicativeWeight () { + get lastIndicativeWeight (): number { return this._workspace?.lastIndicativeWeight ?? 0.0; } /** * Normalized time elapsed on specified motion. */ - get elapsedMotionTime () { + get elapsedMotionTime (): number { return this._workspace?.normalizedTime ?? 0.0; } - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { const { motion } = this; if (!motion) { return; @@ -81,7 +82,7 @@ export class PoseNodePlayMotion extends PoseNode { } - public reenter () { + public reenter (): void { if (this._workspace) { const { _runtimeSyncRecord: runtimeSyncRecord, @@ -121,7 +122,7 @@ export class PoseNodePlayMotion extends PoseNode { } } - public doEvaluate (context: AnimationGraphEvaluationContext) { + public doEvaluate (context: AnimationGraphEvaluationContext): Pose { if (!this._workspace) { return context.pushDefaultedPose(); } else { @@ -149,7 +150,7 @@ class Workspace { } if (EDITOR) { - PoseNodePlayMotion.prototype.getTitle = function getTitle (this: PoseNodePlayMotion) { + PoseNodePlayMotion.prototype.getTitle = function getTitle (this: PoseNodePlayMotion): string | [string, Record] | undefined { return getTileBase(`ENGINE.classes.${CLASS_NAME_PREFIX_ANIM}PoseNodePlayMotion.title`, this.motion); }; diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/play-or-sample-motion-pose-node-shared.ts b/cocos/animation/marionette/pose-graph/pose-nodes/play-or-sample-motion-pose-node-shared.ts index a4a913a0357..c39942f9486 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/play-or-sample-motion-pose-node-shared.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/play-or-sample-motion-pose-node-shared.ts @@ -1,8 +1,9 @@ import { ClipMotion, AnimationBlend, AnimationBlend1D, AnimationBlend2D } from '../../motion'; import { Motion } from '../../motion/motion'; import { EnterNodeInfo } from '../foundation/authoring/enter-node-info'; -import { PoseGraphCreateNodeFactory } from '../decorator/node'; +import { PoseGraphCreateNodeEntry, PoseGraphCreateNodeFactory } from '../decorator/node'; import { PoseNode } from '../pose-node'; +import type { PoseGraphNode } from '../foundation/pose-graph-node'; export {}; @@ -26,7 +27,7 @@ export function makeCreateNodeFactory ( create_: (motion: Motion | null) => PoseNode, ): PoseGraphCreateNodeFactory { return { - listEntries: (context) => [{ + listEntries: (context): Iterable> => [{ arg: { type: 'clip-motion' }, menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_clip_motion', }, { @@ -36,7 +37,7 @@ export function makeCreateNodeFactory ( arg: { type: 'animation-blend-2d' }, menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_animation_blend_2d', }], - create: (arg) => { + create: (arg): PoseGraphNode => { let motion: Motion | null = null; switch (arg.type) { case 'clip-motion': motion = new ClipMotion(); break; @@ -49,7 +50,7 @@ export function makeCreateNodeFactory ( }; } -export function getTileBase (titleI18nKey: string, motion: Motion | null) { +export function getTileBase (titleI18nKey: string, motion: Motion | null): [string, Record] | undefined { let motionName = ''; if (motion instanceof ClipMotion) { if (!motion.clip) { diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts b/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts index 60699b3de6c..7e8fb921505 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts @@ -38,7 +38,7 @@ export class PoseNodeSampleMotion extends PoseNode { @editable public useNormalizedTime = false; - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { const { motion } = this; if (!motion) { return; @@ -84,7 +84,7 @@ class SampleMotionWorkspace { } if (EDITOR) { - PoseNodeSampleMotion.prototype.getTitle = function getTitle (this: PoseNodeSampleMotion) { + PoseNodeSampleMotion.prototype.getTitle = function getTitle (this: PoseNodeSampleMotion): string | [string, Record] | undefined { return getTileBase(`ENGINE.classes.${CLASS_NAME_PREFIX_ANIM}PoseNodeSampleMotion.title`, this.motion); }; diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/set-auxiliary-curve.ts b/cocos/animation/marionette/pose-graph/pose-nodes/set-auxiliary-curve.ts index 2db438991a7..d25822d5b0e 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/set-auxiliary-curve.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/set-auxiliary-curve.ts @@ -46,11 +46,11 @@ export class PoseNodeSetAuxiliaryCurve extends PoseNodeModifyPoseBase { } } - protected getPoseTransformSpaceRequirement () { + protected getPoseTransformSpaceRequirement (): PoseTransformSpaceRequirement { return PoseTransformSpaceRequirement.NO; } - protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose) { + protected modifyPose (context: AnimationGraphEvaluationContext, inputPose: Pose): void { const { _handle: handle, } = this; @@ -74,7 +74,7 @@ export class PoseNodeSetAuxiliaryCurve extends PoseNodeModifyPoseBase { } if (EDITOR) { - PoseNodeSetAuxiliaryCurve.prototype.getTitle = function getTitle (this: PoseNodeSetAuxiliaryCurve) { + PoseNodeSetAuxiliaryCurve.prototype.getTitle = function getTitle (this: PoseNodeSetAuxiliaryCurve): string | [string, Record] | undefined { if (!this.curveName) { return undefined; } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts b/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts index 994ecbe4e43..bd88711ab4d 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts @@ -12,6 +12,7 @@ import { StateMachine } from '../../animation-graph'; import { TopLevelStateMachineEvaluation } from '../../state-machine/state-machine-eval'; import { poseGraphNodeAppearance, poseGraphNodeCategory } from '../decorator/node'; import { POSE_GRAPH_NODE_MENU_PREFIX_POSE } from './menu-common'; +import type { EnterNodeInfo } from '../foundation/authoring/enter-node-info'; @ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseNodeStateMachine`) @poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE) @@ -30,7 +31,7 @@ export class PoseNodeStateMachine extends PoseNode { * // TODO: HACK * @internal */ - public __callOnAfterDeserializeRecursive () { + public __callOnAfterDeserializeRecursive (): void { this.stateMachine._allowEmptyStates = false; this.stateMachine.__callOnAfterDeserializeRecursive(); } @@ -45,11 +46,11 @@ export class PoseNodeStateMachine extends PoseNode { ); } - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { this._stateMachineEval?.settle(context); } - public reenter () { + public reenter (): void { this._stateMachineEval?.reenter(); } @@ -72,14 +73,14 @@ export class PoseNodeStateMachine extends PoseNode { } if (EDITOR) { - PoseNodeStateMachine.prototype.getTitle = function getTitle (this: PoseNodeStateMachine) { + PoseNodeStateMachine.prototype.getTitle = function getTitle (this: PoseNodeStateMachine): string | [string, Record] | undefined { if (this.name) { return this.name; } return undefined; }; - PoseNodeStateMachine.prototype.getEnterInfo = function getEnterInfo (this: PoseNodeStateMachine) { + PoseNodeStateMachine.prototype.getEnterInfo = function getEnterInfo (this: PoseNodeStateMachine): EnterNodeInfo | undefined { return { type: 'state-machine', target: this.stateMachine, diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/use-stashed-pose.ts b/cocos/animation/marionette/pose-graph/pose-nodes/use-stashed-pose.ts index e53e020a003..345bcb1f179 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/use-stashed-pose.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/use-stashed-pose.ts @@ -7,6 +7,8 @@ import { POSE_GRAPH_NODE_MENU_PREFIX_POSE } from './menu-common'; import { RuntimeStash } from '../stash/runtime-stash'; import { PoseNode } from '../pose-node'; import { AnimationGraphBindingContext, AnimationGraphEvaluationContext, AnimationGraphSettleContext, AnimationGraphUpdateContext } from '../../animation-graph-context'; +import type { Pose } from '../../../core/pose'; +import type { EnterNodeInfo } from '../foundation/authoring/enter-node-info'; const createNodeFactory: PoseGraphCreateNodeFactory = { // eslint-disable-next-line arrow-body-style @@ -36,7 +38,7 @@ export class PoseNodeUseStashedPose extends PoseNode { @editable public stashName = ''; - public bind (context: AnimationGraphBindingContext) { + public bind (context: AnimationGraphBindingContext): void { const { stashName, } = this; @@ -53,7 +55,7 @@ export class PoseNodeUseStashedPose extends PoseNode { public settle (context: AnimationGraphSettleContext): void { } - public reenter () { + public reenter (): void { this._runtimeStash?.reenter(); } @@ -61,7 +63,7 @@ export class PoseNodeUseStashedPose extends PoseNode { this._runtimeStash?.requestUpdate(context); } - protected doEvaluate (context: AnimationGraphEvaluationContext) { + protected doEvaluate (context: AnimationGraphEvaluationContext): Pose { return this._runtimeStash?.evaluate(context) ?? context.pushDefaultedPose(); } @@ -69,14 +71,14 @@ export class PoseNodeUseStashedPose extends PoseNode { } if (EDITOR) { - PoseNodeUseStashedPose.prototype.getTitle = function getTitle (this: PoseNodeUseStashedPose) { + PoseNodeUseStashedPose.prototype.getTitle = function getTitle (this: PoseNodeUseStashedPose): [string, { stashName: string; }] | undefined { if (this.stashName) { return [`ENGINE.classes.${CLASS_NAME_PREFIX_ANIM}PoseNodeUseStashedPose.title`, { stashName: this.stashName }]; } return undefined; }; - PoseNodeUseStashedPose.prototype.getEnterInfo = function getTitle (this: PoseNodeUseStashedPose) { + PoseNodeUseStashedPose.prototype.getEnterInfo = function getTitle (this: PoseNodeUseStashedPose): EnterNodeInfo | undefined { return { type: 'stash', stashName: this.stashName, diff --git a/cocos/animation/marionette/pose-graph/pure-value-node.ts b/cocos/animation/marionette/pose-graph/pure-value-node.ts index bc665140070..6adc20e04fd 100644 --- a/cocos/animation/marionette/pose-graph/pure-value-node.ts +++ b/cocos/animation/marionette/pose-graph/pure-value-node.ts @@ -17,15 +17,15 @@ export abstract class PureValueNode extends PoseGraphNode { this._outputTypes = outputTypes; } - get outputCount () { + get outputCount (): number { return this._outputTypes.length; } - public getOutputType (outputIndex: number) { + public getOutputType (outputIndex: number):PoseGraphType { return this._outputTypes[outputIndex]; } - public link (context: PureValueNodeLinkContext) { + public link (context: PureValueNodeLinkContext): void { } private _outputTypes: readonly PoseGraphType[] = []; diff --git a/cocos/animation/marionette/pose-graph/pure-value-nodes/get-variable.ts b/cocos/animation/marionette/pose-graph/pure-value-nodes/get-variable.ts index 3aee19f2379..64236c50013 100644 --- a/cocos/animation/marionette/pose-graph/pure-value-nodes/get-variable.ts +++ b/cocos/animation/marionette/pose-graph/pure-value-nodes/get-variable.ts @@ -87,7 +87,7 @@ export abstract class PVNodeGetVariableBase extends SingleOutputPVNode { @serializable public variableName = ''; - link (context: PureValueNodeLinkContext) { + link (context: PureValueNodeLinkContext): void { this._varInstance = context.getVar(this.variableName); } @@ -95,7 +95,7 @@ export abstract class PVNodeGetVariableBase extends SingleOutputPVNode { } if (EDITOR) { - PVNodeGetVariableBase.prototype.getTitle = function getTitle (this: PVNodeGetVariableBase) { + PVNodeGetVariableBase.prototype.getTitle = function getTitle (this: PVNodeGetVariableBase): [string, { variableName: string; }] | undefined { if (!this.variableName) { return undefined; } diff --git a/cocos/animation/marionette/pose-graph/stash/runtime-stash.ts b/cocos/animation/marionette/pose-graph/stash/runtime-stash.ts index 64ab0d560f5..2c35fcba815 100644 --- a/cocos/animation/marionette/pose-graph/stash/runtime-stash.ts +++ b/cocos/animation/marionette/pose-graph/stash/runtime-stash.ts @@ -148,7 +148,7 @@ class RuntimeStashRecord implements RuntimeStash { ) { } - public set (stash: PoseGraphStash, context: AnimationGraphBindingContext) { + public set (stash: PoseGraphStash, context: AnimationGraphBindingContext): void { assertIsTrue(this._state === StashRecordState.UNINITIALIZED, `The stash has already been set.`); const instantiatedPoseGraph = instantiatePoseGraph(stash.graph, context); instantiatedPoseGraph.bind(context); @@ -156,7 +156,7 @@ class RuntimeStashRecord implements RuntimeStash { this._state = StashRecordState.UNSETTLED; } - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { assertIsTrue( this._state === StashRecordState.UNSETTLED // First time settle || this._state === StashRecordState.SETTLED, // Resettle @@ -166,7 +166,7 @@ class RuntimeStashRecord implements RuntimeStash { this._state = StashRecordState.SETTLED; } - public reset () { + public reset (): void { switch (this._state) { case StashRecordState.SETTLED: // Happen when the stash was not reentered till now. case StashRecordState.OUTDATED: // Happen when the stash keeps outdated. @@ -191,7 +191,7 @@ class RuntimeStashRecord implements RuntimeStash { } } - public reenter () { + public reenter (): void { switch (this._state) { default: assertIsTrue(false as boolean, `Unexpected stash state ${this._state} when reenter().`); @@ -209,7 +209,7 @@ class RuntimeStashRecord implements RuntimeStash { } } - public requestUpdate (context: AnimationGraphUpdateContext) { + public requestUpdate (context: AnimationGraphUpdateContext): void { const { deltaTime } = context; assertIsTrue( this._state === StashRecordState.OUTDATED @@ -251,7 +251,7 @@ class RuntimeStashRecord implements RuntimeStash { this._state = StashRecordState.UPDATED; } - public evaluate (context: AnimationGraphEvaluationContext) { + public evaluate (context: AnimationGraphEvaluationContext): Pose | null { switch (this._state) { default: assertIsTrue(false as boolean, `Unexpected stash state ${this._state} when evaluate().`); @@ -306,7 +306,7 @@ export class RuntimeStashManager implements RuntimeStashView { this._allocator = allocator; } - public bindStash (id: string) { + public bindStash (id: string): RuntimeStash { return this._stashEvaluations[id] as RuntimeStash; } @@ -314,23 +314,23 @@ export class RuntimeStashManager implements RuntimeStashView { return this._stashEvaluations[id]; } - public addStash (id: string) { + public addStash (id: string): void { this._stashEvaluations[id] = new RuntimeStashRecord(this._allocator); } - public setStash (id: string, stash: PoseGraphStash, context: AnimationGraphBindingContext) { + public setStash (id: string, stash: PoseGraphStash, context: AnimationGraphBindingContext): void { assertIsTrue(id in this._stashEvaluations); this._stashEvaluations[id].set(stash, context); } - public reset () { + public reset (): void { for (const stashId in this._stashEvaluations) { const record = this._stashEvaluations[stashId]; record.reset(); } } - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { for (const stashId in this._stashEvaluations) { const record = this._stashEvaluations[stashId]; record.settle(context); diff --git a/cocos/animation/marionette/pose-graph/utils.ts b/cocos/animation/marionette/pose-graph/utils.ts index fe3c2403993..94d94d83e1d 100644 --- a/cocos/animation/marionette/pose-graph/utils.ts +++ b/cocos/animation/marionette/pose-graph/utils.ts @@ -3,6 +3,6 @@ * @param weight The weight. * @returns True if it can be treated as 0. */ -export function isIgnorableWeight (weight: number) { +export function isIgnorableWeight (weight: number): boolean { return weight < 1e-5; } diff --git a/cocos/animation/marionette/state-machine/condition/binary-condition.ts b/cocos/animation/marionette/state-machine/condition/binary-condition.ts index f68469d60c1..d1e1eb62533 100644 --- a/cocos/animation/marionette/state-machine/condition/binary-condition.ts +++ b/cocos/animation/marionette/state-machine/condition/binary-condition.ts @@ -71,7 +71,7 @@ export class BinaryCondition implements Condition { @serializable public rhs = 0.0; - public clone () { + public clone (): BinaryCondition { const that = new BinaryCondition(); that.operator = this.operator; that.lhs = this.lhs; @@ -80,7 +80,7 @@ export class BinaryCondition implements Condition { return that; } - public [createEval] (context: ConditionBindingContext) { + public [createEval] (context: ConditionBindingContext): BinaryConditionEval { const lhsBindingEvaluation = this.lhsBinding?.bind(context); const binaryConditionEval = new BinaryConditionEval( @@ -112,7 +112,7 @@ class BinaryConditionEval implements ConditionEval { /** * Evaluates this condition. */ - public eval (context: ConditionEvaluationContext) { + public eval (context: ConditionEvaluationContext): boolean { const lhsValue = this._lhsBindingEvaluation?.evaluate(context) ?? this._lhsValue; const rhsValue = this._rhsValue; diff --git a/cocos/animation/marionette/state-machine/condition/binding/auxiliary-curve-binding.ts b/cocos/animation/marionette/state-machine/condition/binding/auxiliary-curve-binding.ts index 49f2a080332..e5e49174cd4 100644 --- a/cocos/animation/marionette/state-machine/condition/binding/auxiliary-curve-binding.ts +++ b/cocos/animation/marionette/state-machine/condition/binding/auxiliary-curve-binding.ts @@ -26,7 +26,7 @@ export class TCAuxiliaryCurveBinding extends TCBinding @serializable public curveName = ''; - public getValueType () { + public getValueType (): TCBindingValueType.FLOAT { return TCBindingValueType.FLOAT as const; } @@ -42,7 +42,7 @@ class TCAuxiliaryCurveBindingEvaluation implements TCBindingEvaluation { private _curveName: string, ) { } - public evaluate () { + public evaluate (): number { return this._view.get(this._curveName); } } diff --git a/cocos/animation/marionette/state-machine/condition/binding/editor.ts b/cocos/animation/marionette/state-machine/condition/binding/editor.ts index 42fb5ffd575..b294fbf3b4d 100644 --- a/cocos/animation/marionette/state-machine/condition/binding/editor.ts +++ b/cocos/animation/marionette/state-machine/condition/binding/editor.ts @@ -37,7 +37,7 @@ export interface TCBindingTypeInfo { const tcnBindingTypeInfoMap = new WeakMap>, TCBindingTypeInfo>(); // eslint-disable-next-line @typescript-eslint/ban-types -function getOrCreateTCBindingTypeInfo (target: TFunction) { +function getOrCreateTCBindingTypeInfo (target: TFunction): TCBindingTypeInfo { assertIsTrue( js.isChildClassOf(target, TCBinding), `This method can only be applied to subclasses of TCBinding`, @@ -51,7 +51,7 @@ function getOrCreateTCBindingTypeInfo (target: TFun return info; } -export const provide = (...valueTypes: readonly TCBindingValueType[]): ClassDecorator => (!EDITOR ? () => {} : (target) => { +export const provide = (...valueTypes: readonly TCBindingValueType[]): ClassDecorator => (!EDITOR ? (): void => {} : (target): void => { const info = getOrCreateTCBindingTypeInfo(target); info.provisions = valueTypes.slice(); }); @@ -70,7 +70,7 @@ export enum TCBindingTransitionSourceFilter { WEIGHTED = MOTION | POSE | EMPTY, } -export const support = (transitionSourceFilter: TCBindingTransitionSourceFilter): ClassDecorator => (!EDITOR ? () => {} : (target) => { +export const support = (transitionSourceFilter: TCBindingTransitionSourceFilter): ClassDecorator => (!EDITOR ? (): void => {} : (target): void => { const info = getOrCreateTCBindingTypeInfo(target); info.transitionSourceFilter = transitionSourceFilter; }); diff --git a/cocos/animation/marionette/state-machine/condition/binding/state-motion-time-binding.ts b/cocos/animation/marionette/state-machine/condition/binding/state-motion-time-binding.ts index 05b90bd58de..a0dea995d84 100644 --- a/cocos/animation/marionette/state-machine/condition/binding/state-motion-time-binding.ts +++ b/cocos/animation/marionette/state-machine/condition/binding/state-motion-time-binding.ts @@ -20,7 +20,7 @@ const { ccclass } = _decorator; @provide(TCBindingValueType.FLOAT) @support(TCBindingTransitionSourceFilter.POSE) export class TCStateMotionTimeBinding extends TCBinding { - public getValueType () { + public getValueType (): TCBindingValueType.FLOAT { return TCBindingValueType.FLOAT as const; } diff --git a/cocos/animation/marionette/state-machine/condition/binding/state-weight-binding.ts b/cocos/animation/marionette/state-machine/condition/binding/state-weight-binding.ts index d15e77fb8f1..142f153e60d 100644 --- a/cocos/animation/marionette/state-machine/condition/binding/state-weight-binding.ts +++ b/cocos/animation/marionette/state-machine/condition/binding/state-weight-binding.ts @@ -17,7 +17,7 @@ const { ccclass } = _decorator; @provide(TCBindingValueType.FLOAT) @support(TCBindingTransitionSourceFilter.WEIGHTED) export class TCStateWeightBinding extends TCBinding { - public getValueType () { + public getValueType (): TCBindingValueType.FLOAT { return TCBindingValueType.FLOAT as const; } diff --git a/cocos/animation/marionette/state-machine/condition/binding/variable-binding.ts b/cocos/animation/marionette/state-machine/condition/binding/variable-binding.ts index f8f63c9be37..ef80c561411 100644 --- a/cocos/animation/marionette/state-machine/condition/binding/variable-binding.ts +++ b/cocos/animation/marionette/state-machine/condition/binding/variable-binding.ts @@ -47,7 +47,7 @@ export class TCVariableBinding extends TC class TCVariableBindingEvaluation implements TCBindingEvaluation { constructor (private _varInstance: VarInstance) { } - public evaluate () { + public evaluate (): number { return this._varInstance.value as number; } } diff --git a/cocos/animation/marionette/state-machine/condition/trigger-condition.ts b/cocos/animation/marionette/state-machine/condition/trigger-condition.ts index 74927c052e9..cd704fc6b0b 100644 --- a/cocos/animation/marionette/state-machine/condition/trigger-condition.ts +++ b/cocos/animation/marionette/state-machine/condition/trigger-condition.ts @@ -31,7 +31,7 @@ export class TriggerCondition implements Condition { @serializable public trigger = ''; - public clone () { + public clone (): TriggerCondition { const that = new TriggerCondition(); that.trigger = this.trigger; return that; @@ -56,7 +56,7 @@ class TriggerConditionEval implements ConditionEval { this._triggered = triggered; } - public setTrigger (trigger: boolean) { + public setTrigger (trigger: boolean): void { this._triggered = trigger; } diff --git a/cocos/animation/marionette/state-machine/condition/unary-condition.ts b/cocos/animation/marionette/state-machine/condition/unary-condition.ts index 3aa5562c6a4..499d28f2c58 100644 --- a/cocos/animation/marionette/state-machine/condition/unary-condition.ts +++ b/cocos/animation/marionette/state-machine/condition/unary-condition.ts @@ -41,14 +41,14 @@ export class UnaryCondition implements Condition { @serializable public operand = new BindableBoolean(); - public clone () { + public clone (): UnaryCondition { const that = new UnaryCondition(); that.operator = this.operator; that.operand = this.operand.clone(); return that; } - public [createEval] (context: ConditionBindingContext) { + public [createEval] (context: ConditionBindingContext): UnaryConditionEval { const { operator, operand } = this; const evaluation = new UnaryConditionEval(operator, false); const value = bindOr( @@ -78,11 +78,11 @@ class UnaryConditionEval implements ConditionEval { this._eval(); } - public reset (value: boolean) { + public reset (value: boolean): void { this.setOperand(value); } - public setOperand (value: boolean) { + public setOperand (value: boolean): void { this._operand = value; this._eval(); } @@ -90,11 +90,11 @@ class UnaryConditionEval implements ConditionEval { /** * Evaluates this condition. */ - public eval () { + public eval (): boolean { return this._result; } - private _eval () { + private _eval (): void { const { _operand: operand } = this; switch (this._operator) { default: diff --git a/cocos/animation/marionette/state-machine/motion-state.ts b/cocos/animation/marionette/state-machine/motion-state.ts index b86fbae0d4d..4ee65276a7b 100644 --- a/cocos/animation/marionette/state-machine/motion-state.ts +++ b/cocos/animation/marionette/state-machine/motion-state.ts @@ -66,11 +66,11 @@ export class MotionState extends InteractiveState { * // TODO: HACK * @internal */ - __callOnAfterDeserializeRecursive () { + __callOnAfterDeserializeRecursive (): void { this.motion?.__callOnAfterDeserializeRecursive(); } - public copyTo (that: MotionState) { + public copyTo (that: MotionState): MotionState { super.copyTo(that); that.motion = this.motion?.clone() ?? null; that.speed = this.speed; diff --git a/cocos/animation/marionette/state-machine/state-machine-component.ts b/cocos/animation/marionette/state-machine/state-machine-component.ts index ee0e3c12ec1..bf37465d443 100644 --- a/cocos/animation/marionette/state-machine/state-machine-component.ts +++ b/cocos/animation/marionette/state-machine/state-machine-component.ts @@ -75,7 +75,7 @@ export class StateMachineComponent { * 在刚刚进入状态机时调用。 * @param controller The animation controller it within. */ - public onStateMachineEnter (controller: AnimationController) { + public onStateMachineEnter (controller: AnimationController): void { // Can be overrode } @@ -86,7 +86,7 @@ export class StateMachineComponent { * 在即将退出状态机时调用。 * @param controller The animation controller it within. */ - public onStateMachineExit (controller: AnimationController) { + public onStateMachineExit (controller: AnimationController): void { // Can be overrode } } diff --git a/cocos/animation/marionette/state-machine/state-machine-eval.ts b/cocos/animation/marionette/state-machine/state-machine-eval.ts index f4eae03bffb..933f04410dd 100644 --- a/cocos/animation/marionette/state-machine/state-machine-eval.ts +++ b/cocos/animation/marionette/state-machine/state-machine-eval.ts @@ -141,11 +141,11 @@ class TopLevelStateMachineEvaluation { /** * Indicates if this layer's top level graph reached its exit. */ - get exited () { + get exited (): boolean { return this._currentNode === this._topLevelExit; } - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { const { _proceduralPoseStates: proceduralPoseStates } = this; const nProceduralPoseStates = proceduralPoseStates.length; for (let iState = 0; iState < nProceduralPoseStates; ++iState) { @@ -154,7 +154,7 @@ class TopLevelStateMachineEvaluation { } } - public reenter () { + public reenter (): void { // Known problem: no callbacks are triggered. for (const transition of this._activatedTransitions) { @@ -168,7 +168,7 @@ class TopLevelStateMachineEvaluation { this._currentNode = this._topLevelEntry; } - public update (context: AnimationGraphUpdateContext) { + public update (context: AnimationGraphUpdateContext): void { assertIsTrue(!this.exited); this._loopMatchTransitions(); @@ -252,7 +252,7 @@ class TopLevelStateMachineEvaluation { } } - public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext) { + public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { const { _motionStates: motionStates } = this; const nMotionStates = motionStates.length; for (let iMotionState = 0; iMotionState < nMotionStates; ++iMotionState) { @@ -453,7 +453,7 @@ class TopLevelStateMachineEvaluation { * Loop match transitions util no match, * or util `MAX_TRANSITIONS_PER_FRAME` is reached(in case of circular transition formed or too long transition path). */ - private _loopMatchTransitions () { + private _loopMatchTransitions (): void { const { _pendingTransitionPath: pendingTransitionPath, _activatedTransitions: activatedTransitions, @@ -514,7 +514,7 @@ class TopLevelStateMachineEvaluation { pendingTransitionPath.length = 0; } - private _resetStateTickFlagsAndWeights () { + private _resetStateTickFlagsAndWeights (): void { const { _currentNode: currentNode, _activatedTransitions: activatedTransitions, @@ -527,7 +527,7 @@ class TopLevelStateMachineEvaluation { } } - private _commitStateUpdates (parentContext: AnimationGraphUpdateContext) { + private _commitStateUpdates (parentContext: AnimationGraphUpdateContext): void { const { _currentNode: currentNode, _activatedTransitions: activatedTransitions, @@ -545,7 +545,7 @@ class TopLevelStateMachineEvaluation { } } - private _commitStateUpdate (state: NodeEval, parentContext: AnimationGraphUpdateContext) { + private _commitStateUpdate (state: NodeEval, parentContext: AnimationGraphUpdateContext): void { const { _updateContextGenerator: updateContextGenerator, } = this; @@ -625,7 +625,7 @@ class TopLevelStateMachineEvaluation { return finalPose; } - private _pushNullishPose (context: AnimationGraphEvaluationContext) { + private _pushNullishPose (context: AnimationGraphEvaluationContext): Pose { return this._additive ? context.pushZeroDeltaPose() : context.pushDefaultedPose(); @@ -660,7 +660,7 @@ class TopLevelStateMachineEvaluation { * - to determinate the starting state machine from where the any states are matched; * - so we can solve transitions' relative durations. */ - private _matchAnyScoped (realNode: VMSMInternalState | ProceduralPoseStateEval) { + private _matchAnyScoped (realNode: VMSMInternalState | ProceduralPoseStateEval): TransitionEval | null { for (let ancestor: StateMachineInfo | null = realNode.stateMachine; ancestor !== null; ancestor = ancestor.parent) { @@ -684,7 +684,7 @@ class TopLevelStateMachineEvaluation { */ private _matchTransition ( node: NodeEval, realNode: NodeEval, - ) { + ): TransitionEval | null { assertIsTrue(node === realNode || node.kind === NodeKind.any); const { _conditionEvaluationContext: conditionEvaluationContext } = this; @@ -752,7 +752,7 @@ class TopLevelStateMachineEvaluation { private _activateTransition ( prefix: readonly TransitionEval[], lastTransition: TransitionEval, - ) { + ): void { const destinationState = lastTransition.to; assertIsTrue(isRealState(destinationState)); @@ -803,7 +803,7 @@ class TopLevelStateMachineEvaluation { * @param deltaTime Time piece. * @returns */ - private _updateActivatedTransitions (deltaTime: number) { + private _updateActivatedTransitions (deltaTime: number): void { const { _activatedTransitions: activatedTransitions, } = this; @@ -852,7 +852,7 @@ class TopLevelStateMachineEvaluation { * Drops the transitions from `0` to `lastTransitionIndex` in `this._activatedTransitions`. * @note This methods may modifies the length of `this._activatedTransitions`. */ - private _dropActivatedTransitions (lastTransitionIndex: number) { + private _dropActivatedTransitions (lastTransitionIndex: number): void { const { _activatedTransitions: activatedTransition, _activatedTransitionPool: activatedTransitionPool, @@ -916,7 +916,7 @@ class TopLevelStateMachineEvaluation { this._currentNode = newCurrentState; } - private _resetTriggersOnTransition (transition: TransitionEval) { + private _resetTriggersOnTransition (transition: TransitionEval): void { const { triggers } = transition; if (triggers) { const nTriggers = triggers.length; @@ -927,12 +927,12 @@ class TopLevelStateMachineEvaluation { } } - private _resetTrigger (name: string) { + private _resetTrigger (name: string): void { const { _triggerReset: triggerResetFn } = this; triggerResetFn(name); } - private _callEnterMethods (node: NodeEval) { + private _callEnterMethods (node: NodeEval): void { const { _controller: controller } = this; switch (node.kind) { default: @@ -947,7 +947,7 @@ class TopLevelStateMachineEvaluation { } } - private _callExitMethods (node: NodeEval) { + private _callExitMethods (node: NodeEval): void { const { _controller: controller } = this; switch (node.kind) { default: @@ -962,7 +962,7 @@ class TopLevelStateMachineEvaluation { } } - private _emit (eventBinding: AnimationGraphEventBinding) { + private _emit (eventBinding: AnimationGraphEventBinding): void { eventBinding.emit(this._controller.node); } } @@ -1026,7 +1026,7 @@ export class StateEval { /** * The absolute weight of this state. */ - get absoluteWeight () { + get absoluteWeight (): number { return this._absoluteWeight; } @@ -1035,22 +1035,22 @@ export class StateEval { * - If the state is activated as current state, the count increased. * - If the state is activated as a transition destination, the count increased. */ - get activeReferenceCount () { + get activeReferenceCount (): number { return this._activeReferenceCount; } - public setPrefix_debug (prefix: string) { + public setPrefix_debug (prefix: string): void { this.__DEBUG_ID__ = `${prefix}${this.name}`; } - public addTransition (transition: TransitionEval) { + public addTransition (transition: TransitionEval): void { this.outgoingTransitions.push(transition); } /** * Increases an active reference. */ - public increaseActiveReference () { + public increaseActiveReference (): void { if (this._activeReferenceCount === 0) { this._absoluteWeight = 0.0; this._tickFlags = 0; @@ -1061,31 +1061,31 @@ export class StateEval { /** * Decrease an active reference. */ - public decreaseActiveReference () { + public decreaseActiveReference (): void { if (DEBUG) { this._checkActivated(); } --this._activeReferenceCount; } - public resetTickFlagsAndWeight () { + public resetTickFlagsAndWeight (): void { this._checkActivated(); this._absoluteWeight = 0.0; this._tickFlags = 0; } - public increaseAbsoluteWeight (weight: number) { + public increaseAbsoluteWeight (weight: number): void { this._absoluteWeight += weight; } - public testTickFlag (flag: StateTickFlag) { + public testTickFlag (flag: StateTickFlag): boolean { if (DEBUG) { this._checkActivated(); } return !!(this._tickFlags & flag); } - public setTickFlag (flag: StateTickFlag) { + public setTickFlag (flag: StateTickFlag): void { if (DEBUG) { this._checkActivated(); } @@ -1097,7 +1097,7 @@ export class StateEval { private _tickFlags = 0; private _absoluteWeight = 0.0; - private _checkActivated () { + private _checkActivated (): void { assertIsTrue(this._activeReferenceCount > 0, `The state has not been activated`); } } @@ -1145,23 +1145,23 @@ class InstantiatedComponents { this._components = node.instantiateComponents(); } - public callMotionStateEnterMethods (controller: AnimationController, status: Readonly) { + public callMotionStateEnterMethods (controller: AnimationController, status: Readonly): void { this._callMotionStateCallbackIfNonDefault('onMotionStateEnter', controller, status); } - public callMotionStateUpdateMethods (controller: AnimationController, status: Readonly) { + public callMotionStateUpdateMethods (controller: AnimationController, status: Readonly): void { this._callMotionStateCallbackIfNonDefault('onMotionStateUpdate', controller, status); } - public callMotionStateExitMethods (controller: AnimationController, status: Readonly) { + public callMotionStateExitMethods (controller: AnimationController, status: Readonly): void { this._callMotionStateCallbackIfNonDefault('onMotionStateExit', controller, status); } - public callStateMachineEnterMethods (controller: AnimationController) { + public callStateMachineEnterMethods (controller: AnimationController): void { this._callStateMachineCallbackIfNonDefault('onStateMachineEnter', controller); } - public callStateMachineExitMethods (controller: AnimationController) { + public callStateMachineExitMethods (controller: AnimationController): void { this._callStateMachineCallbackIfNonDefault('onStateMachineExit', controller); } @@ -1173,7 +1173,7 @@ class InstantiatedComponents { methodName: TMethodName, controller: AnimationController, status: MotionStateStatus, - ) { + ): void { const { _components: components } = this; const nComponents = components.length; for (let iComponent = 0; iComponent < nComponents; ++iComponent) { @@ -1189,7 +1189,7 @@ class InstantiatedComponents { > ( methodName: TMethodName, controller: AnimationController, - ) { + ): void { const { _components: components } = this; const nComponents = components.length; for (let iComponent = 0; iComponent < nComponents; ++iComponent) { @@ -1245,19 +1245,19 @@ class VMSMEval { public declare components: InstantiatedComponents; - get duration () { + get duration (): number { return this._source?.duration ?? 0.0; } - get speed () { + get speed (): number { return this._speed; } - get entry () { + get entry (): VMSMInternalState { return this._publicState; } - get stateMachine () { + get stateMachine (): StateMachineInfo { return this._stateMachine; } @@ -1267,12 +1267,12 @@ class VMSMEval { this._privateState.stateMachine = value; } - public setPrefix_debug (prefix: string) { + public setPrefix_debug (prefix: string): void { this._publicState.setPrefix_debug(prefix); this._privateState.setPrefix_debug(prefix); } - public addTransition (transition: Readonly) { + public addTransition (transition: Readonly): void { // If the transition is a self transition, // copy the transition but modify it so that it point to the private state. if (transition.to === this._publicState) { @@ -1292,12 +1292,12 @@ class VMSMEval { return emptyClipStatusesIterable; } else { return { - [Symbol.iterator]: () => source.getClipStatuses(baseWeight), + [Symbol.iterator]: (): Iterator => source.getClipStatuses(baseWeight), }; } } - public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext) { + public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { this._source?.overrideClips(overrides, context); } @@ -1309,7 +1309,7 @@ class VMSMEval { private declare _stateMachine: StateMachineInfo; private declare _debugId: string; - private _setSpeedMultiplier (value: number) { + private _setSpeedMultiplier (value: number): void { this._speed = this._baseSpeed * value; } } @@ -1327,27 +1327,27 @@ class VMSMInternalState extends EventifiedStateEval { this._port = port; } - get duration () { + get duration (): number { return this._container.duration; } - get components () { + get components (): InstantiatedComponents { return this._container.components; } - get normalizedTime () { + get normalizedTime (): number { return this._progress; } - get time () { + get time (): number { return this._progress * this._container.duration; } - public reenter (initialTimeNormalized: number) { + public reenter (initialTimeNormalized: number): void { this._progress = initialTimeNormalized; } - public getStatus () { + public getStatus (): MotionStateStatus { const { _statusCache: stateStatus } = this; if (DEBUG) { stateStatus.__DEBUG_ID__ = this.name; @@ -1360,7 +1360,7 @@ class VMSMInternalState extends EventifiedStateEval { return this._container.getClipStatuses(baseWeight); } - public update (deltaTime: number, controller: AnimationController) { + public update (deltaTime: number, controller: AnimationController): void { this._progress = calcProgressUpdate( this._progress, this.duration, @@ -1369,7 +1369,7 @@ class VMSMInternalState extends EventifiedStateEval { this._container.components.callMotionStateUpdateMethods(controller, this.getStatus()); } - public evaluate (context: AnimationGraphEvaluationContext) { + public evaluate (context: AnimationGraphEvaluationContext): Pose | null { return this._port?.evaluate(this._progress, context) ?? null; } @@ -1379,7 +1379,7 @@ class VMSMInternalState extends EventifiedStateEval { private readonly _statusCache: MotionStateStatus = createStateStatusCache(); } -function calcProgressUpdate (currentProgress: number, duration: number, deltaTime: number) { +function calcProgressUpdate (currentProgress: number, duration: number, deltaTime: number): number { if (duration === 0.0) { // TODO? return 0.0; @@ -1388,7 +1388,7 @@ function calcProgressUpdate (currentProgress: number, duration: number, deltaTim return progress; } -function normalizeProgress (progress: number) { +function normalizeProgress (progress: number): number { const signedFrac = progress - Math.trunc(progress); return signedFrac >= 0.0 ? signedFrac : (1.0 + signedFrac); } @@ -1428,30 +1428,30 @@ class ProceduralPoseStateEval extends EventifiedStateEval { this._statusCache.progress = 0.0; } - public settle (context: AnimationGraphSettleContext) { + public settle (context: AnimationGraphSettleContext): void { this._instantiatedPoseGraph.settle(context); } - public reenter () { + public reenter (): void { this._statusCache.progress = 0.0; this._instantiatedPoseGraph.reenter(); } - public update (context: AnimationGraphUpdateContext) { + public update (context: AnimationGraphUpdateContext): void { this._elapsedTime += context.deltaTime; this._instantiatedPoseGraph.update(context); } - public evaluate (context: AnimationGraphEvaluationContext) { + public evaluate (context: AnimationGraphEvaluationContext): Pose | null { return this._instantiatedPoseGraph.evaluate(context) ?? null; } - public getStatus () { + public getStatus (): MotionStateStatus { this._statusCache.progress = normalizeProgress(this._elapsedTime); return this._statusCache; } - public countMotionTime () { + public countMotionTime (): number { return this._instantiatedPoseGraph.countMotionTime(); } @@ -1488,7 +1488,7 @@ interface TransitionEval { } class ConditionEvaluationContextImpl implements ConditionEvaluationContext { - public set (sourceState: NodeEval) { + public set (sourceState: NodeEval): void { this._sourceState = sourceState; if (isRealState(sourceState)) { assertIsTrue(sourceState.activeReferenceCount); @@ -1499,14 +1499,14 @@ class ConditionEvaluationContextImpl implements ConditionEvaluationContext { } } - public unset () { + public unset (): void { this._sourceState = undefined; this.sourceStateWeight = 0.0; } public sourceStateWeight = 0.0; - public get sourceStateMotionTimeNormalized () { + public get sourceStateMotionTimeNormalized (): number { const { _sourceState: sourceState } = this; assertIsTrue( sourceState @@ -1544,15 +1544,15 @@ class ActivatedTransition { public declare destination: RealState; - get done () { + get done (): boolean { return approx(this.normalizedElapsedTime, 1.0, 1e-6); } - public getAbsoluteDuration (baseDurationState: NodeEval) { + public getAbsoluteDuration (baseDurationState: NodeEval): number { return this._getAbsoluteDurationUnscaled(baseDurationState) * this._durationMultiplier; } - public update (deltaTime: number, fromState: NodeEval) { + public update (deltaTime: number, fromState: NodeEval): void { // If the transitions is not starting with a concrete state. // We can directly finish the transition. if (!isRealState(fromState)) { @@ -1575,10 +1575,10 @@ class ActivatedTransition { } } - public static createPool (initialCapacity: number) { + public static createPool (initialCapacity: number): Pool { const destructor = !DEBUG ? undefined - : (transitionInstance: ActivatedTransition) => { + : (transitionInstance: ActivatedTransition): void => { transitionInstance.normalizedElapsedTime = Number.NaN; }; @@ -1594,7 +1594,7 @@ class ActivatedTransition { public reset ( prefix: readonly TransitionEval[], lastTransition: TransitionEval, - ) { + ): void { const destinationState = lastTransition.to; assertIsTrue(isRealState(destinationState)); @@ -1631,7 +1631,7 @@ class ActivatedTransition { private _durationMultiplier = 1.0; - private _getAbsoluteDurationUnscaled (baseDurationState: NodeEval) { + private _getAbsoluteDurationUnscaled (baseDurationState: NodeEval): number { assertIsTrue(this.path.length !== 0); const { duration, diff --git a/cocos/animation/marionette/state-machine/state.ts b/cocos/animation/marionette/state-machine/state.ts index 0b560fb09c0..e9cc61beaca 100644 --- a/cocos/animation/marionette/state-machine/state.ts +++ b/cocos/animation/marionette/state-machine/state.ts @@ -51,7 +51,7 @@ export class State extends EditorExtendable implements OwnedBy (constructor: StateMachineComponentConstructor) { + public addComponent (constructor: StateMachineComponentConstructor): T { const component = new constructor(); this._components.push(component); return component; } - public removeComponent (component: StateMachineComponent) { + public removeComponent (component: StateMachineComponent): void { js.array.remove(this._components, component); } public instantiateComponents (): StateMachineComponent[] { - const instantiatedComponents = this._components.map((component) => { + const instantiatedComponents = this._components.map((component): StateMachineComponent => { const instantiated = instantiate(component) as unknown as StateMachineComponent; return instantiated; }); return instantiatedComponents; } - public copyTo (that: InteractiveState) { + public copyTo (that: InteractiveState): void { super.copyTo(that); that._components = this.instantiateComponents(); } diff --git a/cocos/animation/marionette/variable/basic.ts b/cocos/animation/marionette/variable/basic.ts index f1d3d0c16e0..30ffb69bd21 100644 --- a/cocos/animation/marionette/variable/basic.ts +++ b/cocos/animation/marionette/variable/basic.ts @@ -105,7 +105,7 @@ export abstract class VarInstanceBase { fn: (this: TThis, value: T, ...args: ExtraArgs) => void, thisArg: TThis, ...args: ExtraArgs - ) { + ): Value { this._refs.push({ fn: fn as (this: unknown, value: unknown, ...args: unknown[]) => void, thisArg, @@ -114,7 +114,7 @@ export abstract class VarInstanceBase { return this.getValue(); } - get value () { + get value (): Value { return this.getValue(); } diff --git a/cocos/animation/marionette/variable/primitive-variable.ts b/cocos/animation/marionette/variable/primitive-variable.ts index 145e7dfd9ad..8a166bc0077 100644 --- a/cocos/animation/marionette/variable/primitive-variable.ts +++ b/cocos/animation/marionette/variable/primitive-variable.ts @@ -37,11 +37,11 @@ export class PlainVariable { } } - get type () { + get type (): PlainVariableType { return this._type; } - get value () { + get value (): Value { return this._value; } @@ -64,7 +64,7 @@ export class PlainVariable { this._value = value; } - public [createInstanceTag] () { + public [createInstanceTag] (): VarInstancePrimitive { return new VarInstancePrimitive(this._type, this._value); } } diff --git a/cocos/animation/marionette/variable/quat-variable.ts b/cocos/animation/marionette/variable/quat-variable.ts index db4b62240aa..9fbb271de15 100644 --- a/cocos/animation/marionette/variable/quat-variable.ts +++ b/cocos/animation/marionette/variable/quat-variable.ts @@ -4,11 +4,11 @@ import { assertIsTrue, Quat } from '../../../core'; @ccclass('cc.animation.QuatVariable') export class QuatVariable implements BasicVariableDescription { - get type () { + get type (): VariableType.QUAT_experimental { return VariableType.QUAT_experimental as const; } - get value () { + get value (): Readonly { return this._value as Readonly; } @@ -16,7 +16,7 @@ export class QuatVariable implements BasicVariableDescription { - get type () { + get type (): VariableType.TRIGGER { return VariableType.TRIGGER as const; } - get value () { + get value (): boolean { return !!((this._flags & TRIGGER_VARIABLE_FLAG_VALUE_MASK) >> TRIGGER_VARIABLE_FLAG_VALUE_START); } @@ -52,7 +52,7 @@ export class TriggerVariable implements BasicVariableDescription> TRIGGER_VARIABLE_FLAG_RESET_MODE_START); } @@ -63,7 +63,7 @@ export class TriggerVariable implements BasicVariableDescription { - get type () { + get type (): VariableType.VEC3_experimental { return VariableType.VEC3_experimental as const; } - get value () { + get value (): Readonly { return this._value as Readonly; } @@ -16,7 +16,7 @@ export class Vec3Variable implements BasicVariableDescription { const writer = this._pose.createWriter(node, property, this, constants); this._blendStateWriters.push(writer); return writer; diff --git a/cocos/animation/skeletal-animation-utils.ts b/cocos/animation/skeletal-animation-utils.ts index 3f137e84dde..219f1b33e1e 100644 --- a/cocos/animation/skeletal-animation-utils.ts +++ b/cocos/animation/skeletal-animation-utils.ts @@ -36,7 +36,7 @@ export interface IJointTransform { parent: IJointTransform | null; } -export function getWorldMatrix (transform: IJointTransform | null, stamp: number) { +export function getWorldMatrix (transform: IJointTransform | null, stamp: number): Readonly { let i = 0; let res = Mat4.IDENTITY; while (transform) { @@ -59,7 +59,7 @@ export function getWorldMatrix (transform: IJointTransform | null, stamp: number return res; } -export function getTransform (node: Node, root: Node) { +export function getTransform (node: Node, root: Node): IJointTransform | null { let joint: IJointTransform | null = null; let i = 0; while (node !== root) { @@ -85,7 +85,7 @@ export function getTransform (node: Node, root: Node) { return joint; } -export function deleteTransform (node: Node) { +export function deleteTransform (node: Node): void { let transform = pool.get(node.uuid) || null; while (transform) { pool.delete(transform.node.uuid); diff --git a/cocos/animation/target-path.ts b/cocos/animation/target-path.ts index daa64ec7623..18e9e30191c 100644 --- a/cocos/animation/target-path.ts +++ b/cocos/animation/target-path.ts @@ -25,6 +25,7 @@ import { ccclass, serializable } from 'cc.decorator'; import { Node } from '../scene-graph/node'; import { warnID } from '../core'; +import type { Component } from '../scene-graph'; /** * @deprecated Since V3.3, use [[TrackPath]] instead. @@ -78,7 +79,7 @@ export class HierarchyPath implements ICustomTargetPath { this.path = path || ''; } - public get (target: Node) { + public get (target: Node): Node | null { if (!(target instanceof Node)) { warnID(3925); return null; @@ -104,7 +105,7 @@ export class ComponentPath implements ICustomTargetPath { this.component = component || ''; } - public get (target: Node) { + public get (target: Node): Component | null { if (!(target instanceof Node)) { warnID(3927); return null; diff --git a/cocos/animation/tracks/array-track.ts b/cocos/animation/tracks/array-track.ts index db5f401bbe9..bf9619220bc 100644 --- a/cocos/animation/tracks/array-track.ts +++ b/cocos/animation/tracks/array-track.ts @@ -45,7 +45,7 @@ export class RealArrayTrack extends Track { * @zh 此轨道产生的数组元素的数量。 * 当你增加数量时,会增加新的空实数通道;当你减少数量时,最后几个指定数量的通道会被移除。 */ - get elementCount () { + get elementCount (): number { return this._channels.length; } @@ -57,7 +57,7 @@ export class RealArrayTrack extends Track { } else if (value > nChannels) { this._channels.push( ...Array.from({ length: value - nChannels }, - () => new Channel(new RealCurve())), + (): Channel => new Channel(new RealCurve())), ); } } @@ -66,15 +66,15 @@ export class RealArrayTrack extends Track { * @en The channels of the track. * @zh 返回此轨道的所有通道的数组。 */ - public channels () { + public channels (): RealChannel[] { return this._channels; } /** * @internal */ - public [createEvalSymbol] () { - return new RealArrayTrackEval(this._channels.map(({ curve }) => curve)); + public [createEvalSymbol] (): RealArrayTrackEval { + return new RealArrayTrackEval(this._channels.map(({ curve }): RealCurve => curve)); } @serializable @@ -88,11 +88,11 @@ export class RealArrayTrackEval implements TrackEval { this._result = new Array(_curves.length).fill(0.0); } - public get requiresDefault () { + public get requiresDefault (): boolean { return false; } - public evaluate (time: number) { + public evaluate (time: number): number[] { const { _result: result, } = this; diff --git a/cocos/animation/tracks/color-track.ts b/cocos/animation/tracks/color-track.ts index b0ce404a6b3..7d5ee0eb81a 100644 --- a/cocos/animation/tracks/color-track.ts +++ b/cocos/animation/tracks/color-track.ts @@ -54,14 +54,14 @@ export class ColorTrack extends Track { * @returns An readonly four length array in which * the element at n denotes the channel of n-th(in order of RGBA) color component(in form of integer within 0-255). */ - public channels () { + public channels (): [RealChannel, RealChannel, RealChannel, RealChannel] { return this._channels; } /** * @internal */ - public [createEvalSymbol] () { + public [createEvalSymbol] (): ColorTrackEval { return new ColorTrackEval( maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), @@ -84,11 +84,11 @@ export class ColorTrackEval implements TrackEval { } - public get requiresDefault () { + public get requiresDefault (): boolean { return !this._x || !this._y || !this._z || !this._w; } - public evaluate (time: number, defaultValue?: Color) { + public evaluate (time: number, defaultValue?: Color): Color { if (defaultValue) { Color.copy(this._result, defaultValue); } diff --git a/cocos/animation/tracks/object-track.ts b/cocos/animation/tracks/object-track.ts index 5d895d2a23e..81731d7b6f7 100644 --- a/cocos/animation/tracks/object-track.ts +++ b/cocos/animation/tracks/object-track.ts @@ -38,7 +38,7 @@ export class ObjectTrack extends SingleChannelTrack> { /** * @internal */ - protected createCurve () { + protected createCurve (): ObjectCurve { return new ObjectCurve(); } } diff --git a/cocos/animation/tracks/quat-track.ts b/cocos/animation/tracks/quat-track.ts index b354b7fe8ee..6ec7085f7da 100644 --- a/cocos/animation/tracks/quat-track.ts +++ b/cocos/animation/tracks/quat-track.ts @@ -38,14 +38,14 @@ export class QuatTrack extends SingleChannelTrack { /** * @internal */ - protected createCurve () { + protected createCurve (): QuatCurve { return new QuatCurve(); } /** * @internal */ - public [createEvalSymbol] () { + public [createEvalSymbol] (): QuatTrackEval { return new QuatTrackEval(this.channels()[0].curve); } } @@ -55,11 +55,11 @@ export class QuatTrackEval implements TrackEval { } - public get requiresDefault () { + public get requiresDefault (): boolean { return false; } - public evaluate (time: number) { + public evaluate (time: number): Quat { this._curve.evaluate(time, this._result); return this._result; } diff --git a/cocos/animation/tracks/real-track.ts b/cocos/animation/tracks/real-track.ts index 82ad7db530a..933f08896ae 100644 --- a/cocos/animation/tracks/real-track.ts +++ b/cocos/animation/tracks/real-track.ts @@ -38,7 +38,7 @@ export class RealTrack extends SingleChannelTrack { /** * @internal */ - protected createCurve () { + protected createCurve (): RealCurve { return new RealCurve(); } } diff --git a/cocos/animation/tracks/size-track.ts b/cocos/animation/tracks/size-track.ts index bf102665ee3..04c16b70767 100644 --- a/cocos/animation/tracks/size-track.ts +++ b/cocos/animation/tracks/size-track.ts @@ -54,14 +54,14 @@ export class SizeTrack extends Track { * @returns An readonly array in which * the first element is the width channel and the second element is the height channel. */ - public channels () { + public channels (): [RealChannel, RealChannel] { return this._channels; } /** * @internal */ - public [createEvalSymbol] () { + public [createEvalSymbol] (): SizeTrackEval { return new SizeTrackEval( maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), @@ -80,11 +80,11 @@ export class SizeTrackEval implements TrackEval { } - public get requiresDefault () { + public get requiresDefault (): boolean { return !this._width || !this._height; } - public evaluate (time: number, defaultValue?: Readonly) { + public evaluate (time: number, defaultValue?: Readonly): Size { if (defaultValue) { this._result.x = defaultValue.x; this._result.y = defaultValue.y; diff --git a/cocos/animation/tracks/track.ts b/cocos/animation/tracks/track.ts index 13e3efb1267..c518ed5e528 100644 --- a/cocos/animation/tracks/track.ts +++ b/cocos/animation/tracks/track.ts @@ -62,7 +62,7 @@ class TrackPath { * @en The length of the path. * @zh 此路径的段数。 */ - get length () { + get length (): number { return this._paths.length; } @@ -72,7 +72,7 @@ class TrackPath { * @param name The property's name. * @returns `this` */ - public toProperty (name: string) { + public toProperty (name: string): TrackPath { this._paths.push(name); return this; } @@ -83,7 +83,7 @@ class TrackPath { * @param index The element's index. * @returns `this` */ - public toElement (index: number) { + public toElement (index: number): TrackPath { this._paths.push(index); return this; } @@ -94,7 +94,7 @@ class TrackPath { * @param nodePath Path to the children. * @returns `this` */ - public toHierarchy (nodePath: string) { + public toHierarchy (nodePath: string): TrackPath { this._paths.push(new HierarchyPath(nodePath)); return this; } @@ -105,7 +105,7 @@ class TrackPath { * @param constructor @en The constructor of the component. @zh 组件的构造函数。 * @returns `this` */ - public toComponent (constructor: Constructor | string) { + public toComponent (constructor: Constructor | string): TrackPath { const path = new ComponentPath(typeof constructor === 'string' ? constructor : js.getClassName(constructor)); this._paths.push(path); return this; @@ -114,7 +114,7 @@ class TrackPath { /** * @internal Reserved for backward compatibility. DO NOT USE IT IN YOUR CODE. */ - public toCustomized (resolver: CustomizedTrackPathResolver) { + public toCustomized (resolver: CustomizedTrackPathResolver): TrackPath { this._paths.push(resolver); return this; } @@ -125,8 +125,8 @@ class TrackPath { * @param trackPaths Paths to append. * @returns `this`. */ - public append (...trackPaths: TrackPath[]) { - const paths = this._paths.concat(...trackPaths.map((trackPath) => trackPath._paths)); + public append (...trackPaths: TrackPath[]): TrackPath { + const paths = this._paths.concat(...trackPaths.map((trackPath): TargetPath[] => trackPath._paths)); this._paths = paths; return this; } @@ -137,7 +137,7 @@ class TrackPath { * @param index Index to the segment。 * @returns The judgement result. */ - public isPropertyAt (index: number) { + public isPropertyAt (index: number): boolean { return typeof (this._paths[index]) === 'string'; } @@ -157,7 +157,7 @@ class TrackPath { * @param index Index to the segment。 * @returns The judgement result. */ - public isElementAt (index: number) { + public isElementAt (index: number): boolean { return typeof this._paths[index] === 'number'; } @@ -177,7 +177,7 @@ class TrackPath { * @param index Index to the segment。 * @returns The judgement result. */ - public isHierarchyAt (index: number) { + public isHierarchyAt (index: number): boolean { return this._paths[index] instanceof HierarchyPath; } @@ -187,7 +187,7 @@ class TrackPath { * @param index Index to the segment。 * @returns The hierarchy path. */ - public parseHierarchyAt (index: number) { + public parseHierarchyAt (index: number): string { assertIsTrue(this.isHierarchyAt(index)); return (this._paths[index] as HierarchyPath).path; } @@ -198,7 +198,7 @@ class TrackPath { * @param index Index to the segment。 * @returns The judgement result. */ - public isComponentAt (index: number) { + public isComponentAt (index: number): boolean { return this._paths[index] instanceof ComponentPath; } @@ -208,7 +208,7 @@ class TrackPath { * @param index Index to the segment。 * @returns The component path. */ - public parseComponentAt (index: number) { + public parseComponentAt (index: number): string { assertIsTrue(this.isComponentAt(index)); return (this._paths[index] as ComponentPath).component; } @@ -220,7 +220,7 @@ class TrackPath { * @param endIndex End index to the segment. Default to the last segment. * @returns The new path. */ - public slice (beginIndex?: number, endIndex?: number) { + public slice (beginIndex?: number, endIndex?: number): TrackPath { const trackPath = new TrackPath(); trackPath._paths = this._paths.slice(beginIndex, endIndex); return trackPath; @@ -229,7 +229,7 @@ class TrackPath { /** * @internal */ - public trace (object: unknown, beginIndex?: number, endIndex?: number) { + public trace (object: unknown, beginIndex?: number, endIndex?: number): unknown { beginIndex ??= 0; endIndex ??= this._paths.length; return this[normalizedFollowTag](object, beginIndex, endIndex); @@ -238,7 +238,7 @@ class TrackPath { /** * @internal */ - public [parseTrsPathTag] () { + public [parseTrsPathTag] (): { node: string; property: "position" | "scale" | "rotation" | "eulerAngles"; } | null { const { _paths: paths } = this; const nPaths = paths.length; @@ -284,7 +284,7 @@ class TrackPath { /** * @internal */ - public [normalizedFollowTag] (root: unknown, beginIndex: number, endIndex: number) { + public [normalizedFollowTag] (root: unknown, beginIndex: number, endIndex: number): unknown { const { _paths: paths } = this; let result = root; for (let iPath = beginIndex; iPath < endIndex; ++iPath) { @@ -331,7 +331,7 @@ export class TrackBinding { private static _animationFunctions = new WeakMap>(); - public parseTrsPath () { + public parseTrsPath (): { node: string; property: "position" | "scale" | "rotation" | "eulerAngles"; } | null { if (this.proxy) { return null; } else { @@ -339,7 +339,7 @@ export class TrackBinding { } } - public createRuntimeBinding (target: unknown, poseOutput: PoseOutput | undefined, isConstant: boolean) { + public createRuntimeBinding (target: unknown, poseOutput: PoseOutput | undefined, isConstant: boolean): RuntimeBinding | { target: any; setValue: any; getValue: any; } | null { const { path, proxy } = this; const nPaths = path.length; const iLastPath = nPaths - 1; @@ -376,10 +376,10 @@ export class TrackBinding { setValue = accessor.setValue; getValue = accessor.getValue; } else { - setValue = (value: unknown) => { + setValue = (value: unknown): void => { resultTarget[lastPropertyKey] = value; }; - getValue = () => resultTarget[lastPropertyKey] as unknown; + getValue = (): unknown => resultTarget[lastPropertyKey] as unknown; } return { target: resultTarget, @@ -399,20 +399,20 @@ export class TrackBinding { return null; } const binding: RuntimeBinding = { - setValue: (value) => { + setValue: (value): void => { runtimeProxy.set(value); }, }; const proxyGet = runtimeProxy.get; if (proxyGet) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return - binding.getValue = () => proxyGet.call(runtimeProxy); + binding.getValue = (): any => proxyGet.call(runtimeProxy); } return binding; } } - public isMaskedOff (mask: AnimationMask) { + public isMaskedOff (mask: AnimationMask): boolean { const trsPath = this.parseTrsPath(); if (!trsPath) { return false; @@ -454,7 +454,7 @@ export abstract class Track { * @en Track path. * @zh 轨道路径。 */ - get path () { + get path (): Readonly { return this._binding.path; } @@ -466,7 +466,7 @@ export abstract class Track { * @en Value proxy for the target. * @zh 目标的值代理。 */ - get proxy () { + get proxy (): IValueProxyFactory | undefined { return this._binding.proxy; } @@ -477,7 +477,7 @@ export abstract class Track { /** * @internal */ - get [trackBindingTag] () { + get [trackBindingTag] (): TrackBinding { return this._binding; } @@ -552,7 +552,7 @@ export class Channel { * @en The curve within the channel. * @zh 通道中的曲线。 */ - get curve () { + get curve (): T { return this._curve; } @@ -579,7 +579,7 @@ export abstract class SingleChannelTrack extends Track { * @en The channel within the track. * @zh 轨道包含的通道。 */ - get channel () { + get channel (): Channel { return this._channel; } @@ -610,11 +610,11 @@ class SingleChannelTrackEval implements TrackEval constructor (private _curve: TCurve) { } - public get requiresDefault () { + public get requiresDefault (): boolean { return false; } - public evaluate (time: number) { + public evaluate (time: number): unknown { return this._curve.evaluate(time); } } diff --git a/cocos/animation/tracks/untyped-track.ts b/cocos/animation/tracks/untyped-track.ts index 16a0f666dea..29ecce4cf54 100644 --- a/cocos/animation/tracks/untyped-track.ts +++ b/cocos/animation/tracks/untyped-track.ts @@ -46,7 +46,7 @@ export class UntypedTrack extends Track { @serializable private _channels: UntypedTrackChannel[] = []; - public channels () { + public channels (): UntypedTrackChannel[] { return this._channels; } @@ -57,8 +57,8 @@ export class UntypedTrack extends Track { /** * @internal */ - public createLegacyEval (hintValue?: unknown) { - const trySearchCurve = (property: string) => this._channels.find((channel) => channel.property === property)?.curve; + public createLegacyEval (hintValue?: unknown): Vec2TrackEval | Vec3TrackEval | Vec4TrackEval | ColorTrackEval | SizeTrackEval { + const trySearchCurve = (property: string): RealCurve | undefined => this._channels.find((channel): boolean => channel.property === property)?.curve; switch (true) { default: throw new Error(getError(3931)); @@ -104,8 +104,8 @@ export class UntypedTrack extends Track { } public upgrade (refine: UntypedTrackRefine): Track | null { - const trySearchChannel = (property: string, outChannel: RealChannel) => { - const untypedChannel = this.channels().find((channel) => channel.property === property); + const trySearchChannel = (property: string, outChannel: RealChannel): void => { + const untypedChannel = this.channels().find((channel): boolean => channel.property === property); if (untypedChannel) { outChannel.name = untypedChannel.name; outChannel.curve.assignSorted( diff --git a/cocos/animation/tracks/utils.ts b/cocos/animation/tracks/utils.ts index 7e9a43f0644..e9d65b56e5d 100644 --- a/cocos/animation/tracks/utils.ts +++ b/cocos/animation/tracks/utils.ts @@ -24,7 +24,7 @@ import type { Curve } from './track'; -export function maskIfEmpty (curve: T) { +export function maskIfEmpty (curve: T): T | undefined { return curve.keyFramesCount === 0 ? undefined : curve; } diff --git a/cocos/animation/tracks/vector-track.ts b/cocos/animation/tracks/vector-track.ts index f8dfe9997aa..fa71b8263bf 100644 --- a/cocos/animation/tracks/vector-track.ts +++ b/cocos/animation/tracks/vector-track.ts @@ -52,7 +52,7 @@ export class VectorTrack extends Track { * @en Gets or sets the count of components(dimension) available while evaluating of this track. * @zh 获取或设置此轨道在求值时有效的分量数(维度)。 */ - get componentsCount () { + get componentsCount (): number { return this._nComponents; } @@ -66,14 +66,14 @@ export class VectorTrack extends Track { * @returns An readonly four length array in which * the element at n denotes the channel of n-th vector component. */ - public channels () { + public channels (): [RealChannel, RealChannel, RealChannel, RealChannel] { return this._channels; } /** * @internal */ - public [createEvalSymbol] () { + public [createEvalSymbol] (): Vec2TrackEval | Vec3TrackEval | Vec4TrackEval { switch (this._nComponents) { default: case 2: @@ -101,7 +101,7 @@ export class VectorTrack extends Track { private _channels: [RealChannel, RealChannel, RealChannel, RealChannel]; @serializable - private _nComponents: 2 | 3 | 4 = 4; + private _nComponents: number = 4; } export class Vec2TrackEval implements TrackEval { @@ -109,11 +109,11 @@ export class Vec2TrackEval implements TrackEval { } - public get requiresDefault () { + public get requiresDefault (): boolean { return !this._x || !this._y; } - public evaluate (time: number, defaultValue?: Readonly) { + public evaluate (time: number, defaultValue?: Readonly): Vec2 { if (defaultValue) { Vec2.copy(this._result, defaultValue); } @@ -136,11 +136,11 @@ export class Vec3TrackEval implements TrackEval { } - public get requiresDefault () { + public get requiresDefault (): boolean { return !this._x || !this._y || !this._z; } - public evaluate (time: number, defaultValue?: Readonly) { + public evaluate (time: number, defaultValue?: Readonly): Vec3 { if (defaultValue) { Vec3.copy(this._result, defaultValue); } @@ -171,11 +171,11 @@ export class Vec4TrackEval implements TrackEval { } - public get requiresDefault () { + public get requiresDefault (): boolean { return !this._x || !this._y || !this._z || !this._w; } - public evaluate (time: number, defaultValue?: Readonly) { + public evaluate (time: number, defaultValue?: Readonly): Vec4 { if (defaultValue) { Vec4.copy(this._result, defaultValue); } diff --git a/cocos/animation/transform-utils.ts b/cocos/animation/transform-utils.ts index 7b9b7bf065b..12252f55161 100644 --- a/cocos/animation/transform-utils.ts +++ b/cocos/animation/transform-utils.ts @@ -30,7 +30,7 @@ const m4_1 = new Mat4(); /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ -export function getPathFromRoot (target: Node | null, root: Node) { +export function getPathFromRoot (target: Node | null, root: Node): string { let node: Node | null = target; let path = ''; while (node !== null && node !== root) { @@ -43,7 +43,7 @@ export function getPathFromRoot (target: Node | null, root: Node) { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ -export function getWorldTransformUntilRoot (target: Node, root: Node, outMatrix: Mat4) { +export function getWorldTransformUntilRoot (target: Node, root: Node, outMatrix: Mat4): Mat4 { Mat4.identity(outMatrix); while (target !== root) { Mat4.fromRTS(m4_1, target.rotation, target.position, target.scale); diff --git a/cocos/animation/types.ts b/cocos/animation/types.ts index 2310e766098..2ec8815bc27 100644 --- a/cocos/animation/types.ts +++ b/cocos/animation/types.ts @@ -83,7 +83,7 @@ export class WrappedInfo { } } - public set (info: WrappedInfo) { + public set (info: WrappedInfo): void { this.ratio = info.ratio; this.time = info.time; this.direction = info.direction; diff --git a/cocos/animation/value-proxy-factories/morph-weights.ts b/cocos/animation/value-proxy-factories/morph-weights.ts index 783b8933e78..ae1f5e6d488 100644 --- a/cocos/animation/value-proxy-factories/morph-weights.ts +++ b/cocos/animation/value-proxy-factories/morph-weights.ts @@ -48,9 +48,9 @@ export class MorphWeightValueProxy implements IValueProxyFactory { @serializable public shapeIndex = 0; - public forTarget (target: MeshRenderer) { + public forTarget (target: MeshRenderer): { set: (value: number) => void; } { return { - set: (value: number) => { + set: (value: number): void => { target.setWeight(value, this.subMeshIndex, this.shapeIndex); }, }; @@ -72,9 +72,9 @@ export class MorphWeightsValueProxy implements IValueProxyFactory { @serializable public subMeshIndex = 0; - public forTarget (target: MeshRenderer) { + public forTarget (target: MeshRenderer): { set: (value: number[]) => void; } { return { - set: (value: number[]) => { + set: (value: number[]): void => { target.setWeights(value, this.subMeshIndex); }, }; @@ -89,9 +89,9 @@ export class MorphWeightsValueProxy implements IValueProxyFactory { */ @ccclass('cc.animation.MorphWeightsAllValueProxy') export class MorphWeightsAllValueProxy implements IValueProxyFactory { - public forTarget (target: MeshRenderer) { + public forTarget (target: MeshRenderer): { set: (value: number[]) => void; } { return { - set: (value: number[]) => { + set: (value: number[]): void => { const nSubMeshes = target.mesh?.struct.primitives.length ?? 0; for (let iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) { target.setWeights(value, iSubMesh); diff --git a/cocos/animation/value-proxy-factories/uniform.ts b/cocos/animation/value-proxy-factories/uniform.ts index 50c366d9cbe..779560b0db4 100644 --- a/cocos/animation/value-proxy-factories/uniform.ts +++ b/cocos/animation/value-proxy-factories/uniform.ts @@ -106,13 +106,13 @@ export class UniformProxyFactory implements IValueProxyFactory { } if (isUniformArray(pass, uniformName)) { return { - set: (value: any) => { + set: (value: any): void => { pass.setUniformArray(realHandle, value); }, }; } return { - set: (value: any) => { + set: (value: any): void => { pass.setUniform(realHandle, value); }, }; @@ -126,7 +126,7 @@ export class UniformProxyFactory implements IValueProxyFactory { dftTex = builtinResMgr.get('default-texture'); } return { - set: (value: TextureBase | SpriteFrame) => { + set: (value: TextureBase | SpriteFrame): void => { if (!value) { value = dftTex; } const texture = value.getGFXTexture(); if (!texture || !texture.width || !texture.height) { return; } @@ -140,7 +140,7 @@ export class UniformProxyFactory implements IValueProxyFactory { } } -function isUniformArray (pass: Pass, name: string) { +function isUniformArray (pass: Pass, name: string): boolean { for (const block of pass.shaderInfo.blocks) { for (const uniform of block.members) { if (uniform.name === name) { diff --git a/cocos/animation/wrap.ts b/cocos/animation/wrap.ts index f079b878355..27df6ec27f5 100644 --- a/cocos/animation/wrap.ts +++ b/cocos/animation/wrap.ts @@ -65,7 +65,7 @@ export function wrap ( return info; } -function isReverseIteration (wrapMode: WrapMode, currentIterations: number) { +function isReverseIteration (wrapMode: WrapMode, currentIterations: number): boolean { let needReverse = false; if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) { const isEnd = currentIterations - (currentIterations | 0) === 0; diff --git a/cocos/asset/asset-manager/asset-manager.ts b/cocos/asset/asset-manager/asset-manager.ts index 61f7016840e..56455b0986a 100644 --- a/cocos/asset/asset-manager/asset-manager.ts +++ b/cocos/asset/asset-manager/asset-manager.ts @@ -314,7 +314,7 @@ export class AssetManager { * @zh * [[AssetManager]] 的全局单例,你可以直接通过 [[assetManager]] 访问。 */ - static get instance () { + static get instance (): AssetManager { if (!this._instance) { this._instance = new AssetManager(); } @@ -358,7 +358,7 @@ export class AssetManager { * @internal * @engineInternal */ - public onAssetMissing (func: (parentAsset: Asset, owner: any, propName: string, uuid: string) => void, target?: any) { + public onAssetMissing (func: (parentAsset: Asset, owner: any, propName: string, uuid: string) => void, target?: any): void { this._eventTarget.on(EVENT_ASSET_MISSING, func, target); } @@ -372,7 +372,7 @@ export class AssetManager { * @internal * @engineInternal */ - public offAssetMissing (func: (parentAsset: Asset, owner: any, propName: string, uuid: string) => void, target?: any) { + public offAssetMissing (func: (parentAsset: Asset, owner: any, propName: string, uuid: string) => void, target?: any): void { this._eventTarget.off(EVENT_ASSET_MISSING, func, target); } @@ -388,7 +388,7 @@ export class AssetManager { * @internal * @engineInternal */ - public dispatchAssetMissing (parentAsset: Asset, owner: any, propName: string, uuid: string) { + public dispatchAssetMissing (parentAsset: Asset, owner: any, propName: string, uuid: string): void { this._eventTarget.emit(EVENT_ASSET_MISSING, parentAsset, owner, propName, uuid); } @@ -403,7 +403,7 @@ export class AssetManager { * @param options @en The configuration of asset manager. @zh 资源管理器的配置选项。 * @internal */ - public init (options: IAssetManagerOptions = {}) { + public init (options: IAssetManagerOptions = {}): void { const server = options.server || settings.querySettings(Settings.Category.ASSETS, 'server') || ''; const bundleVers = options.bundleVers || settings.querySettings(Settings.Category.ASSETS, 'bundleVers') || {}; const remoteBundles = options.remoteBundles || settings.querySettings(Settings.Category.ASSETS, 'remoteBundles') || []; @@ -465,7 +465,7 @@ export class AssetManager { * @param bundle @en The bundle to be removed. @zh 准备移除的 Bundle。 * */ - public removeBundle (bundle: Bundle) { + public removeBundle (bundle: Bundle): void { bundle._destroy(); bundles.remove(bundle.name); } @@ -531,7 +531,7 @@ export class AssetManager { options?: { [key: string]: any, preset?: string } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: any) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: any) => void) | null, onComplete?: ((err: Error | null, data: any) => void) | null, - ) { + ): void { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete); opts.preset = opts.preset || 'default'; requests = Array.isArray(requests) ? requests.slice() : requests; @@ -581,7 +581,7 @@ export class AssetManager { options?: { [key: string]: any, preset?: string } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null, - ) { + ): void { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete); opts.preset = opts.preset || 'preload'; requests = Array.isArray(requests) ? requests.slice() : requests; @@ -619,7 +619,7 @@ export class AssetManager { */ public loadRemote (url: string, options: { [k: string]: any, ext?: string } | null, onComplete?: ((err: Error | null, data: T) => void) | null): void; public loadRemote (url: string, onComplete?: ((err: Error | null, data: T) => void) | null): void; - public loadRemote (url: string, options?: { [k: string]: any, ext?: string } | ((err: Error | null, data: T) => void) | null, onComplete?: ((err: Error | null, data: T) => void) | null) { + public loadRemote (url: string, options?: { [k: string]: any, ext?: string } | ((err: Error | null, data: T) => void) | null, onComplete?: ((err: Error | null, data: T) => void) | null): void { const { options: opts, onComplete: onComp } = parseParameters<((err: Error | null, data: T) => void)>(options, undefined, onComplete); if (!opts.reloadAsset && this.assets.has(url)) { @@ -629,12 +629,12 @@ export class AssetManager { opts.__isNative__ = true; opts.preset = opts.preset || 'remote'; - this.loadAny({ url }, opts, null, (err, data) => { + this.loadAny({ url }, opts, null, (err, data): void => { if (err) { error(err.message, err.stack); if (onComp) { onComp(err, data); } } else { - factory.create(url, data, opts.ext || path.extname(url), opts, (p1, p2) => { + factory.create(url, data, opts.ext || path.extname(url), opts, (p1, p2): void => { if (onComp) { onComp(p1, p2 as T); } }); } @@ -677,7 +677,7 @@ export class AssetManager { */ public loadBundle (nameOrUrl: string, options: { [k: string]: any, version?: string } | null, onComplete?: ((err: Error | null, data: Bundle) => void) | null): void; public loadBundle (nameOrUrl: string, onComplete?: ((err: Error | null, data: Bundle) => void) | null): void; - public loadBundle (nameOrUrl: string, options?: { [k: string]: any, version?: string } | ((err: Error | null, data: Bundle) => void) | null, onComplete?: ((err: Error | null, data: Bundle) => void) | null) { + public loadBundle (nameOrUrl: string, options?: { [k: string]: any, version?: string } | ((err: Error | null, data: Bundle) => void) | null, onComplete?: ((err: Error | null, data: Bundle) => void) | null): void { const { options: opts, onComplete: onComp } = parseParameters<((err: Error | null, data: Bundle) => void)>(options, undefined, onComplete); const bundleName = path.basename(nameOrUrl); @@ -690,12 +690,12 @@ export class AssetManager { opts.preset = opts.preset || 'bundle'; opts.ext = 'bundle'; opts.__isNative__ = true; - this.loadAny({ url: nameOrUrl }, opts, null, (err, data) => { + this.loadAny({ url: nameOrUrl }, opts, null, (err, data): void => { if (err) { error(err.message, err.stack); if (onComp) { onComp(err, data); } } else { - factory.create(nameOrUrl, data, 'bundle', opts, (p1, p2) => { + factory.create(nameOrUrl, data, 'bundle', opts, (p1, p2): void => { if (onComp) { onComp(p1, p2 as Bundle); } }); } @@ -736,8 +736,8 @@ export class AssetManager { * @engineInternal * */ - public releaseUnusedAssets () { - assets.forEach((asset) => { + public releaseUnusedAssets (): void { + assets.forEach((asset): void => { releaseManager.tryRelease(asset); }); } @@ -750,8 +750,8 @@ export class AssetManager { * 释放所有资源。详细信息请参考 [[releaseAsset]]。 * */ - public releaseAll () { - assets.forEach((asset) => { + public releaseAll (): void { + assets.forEach((asset): void => { releaseManager.tryRelease(asset, true); }); } @@ -776,7 +776,7 @@ export class AssetManager { options?: { [key: string]: any, assetId?: string } | ((err: Error | null, data: T) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T) => void) | null, onComplete?: ((err: Error | null, data: T) => void) | null, - ) { + ): void { if (BUILD) { throw new Error('Only valid in Editor'); } const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err: Error | null, data: T) => void)>(options, onProgress, onComplete); @@ -791,7 +791,7 @@ export class AssetManager { input: [item], onProgress: onProg, options: opts, - onComplete: asyncify((err, data: T) => { + onComplete: asyncify((err, data: T): void => { if (!err) { if (!opts.assetId) { data._uuid = ''; diff --git a/cocos/asset/asset-manager/builtin-res-mgr.ts b/cocos/asset/asset-manager/builtin-res-mgr.ts index b24284e03b3..4ce58cdd83b 100644 --- a/cocos/asset/asset-manager/builtin-res-mgr.ts +++ b/cocos/asset/asset-manager/builtin-res-mgr.ts @@ -40,7 +40,7 @@ export class BuiltinResMgr { protected _materialsToBeCompiled: Material[] = []; // this should be called after renderer initialized - public init () { + public init (): void { const resources = this._resources; const len = 2; const numChannels = 4; @@ -302,32 +302,32 @@ export class BuiltinResMgr { } } - public addAsset (key: string, asset: Asset) { + public addAsset (key: string, asset: Asset): void { this._resources[key] = asset; } - public get (uuid: string) { + public get (uuid: string): T { return this._resources[uuid] as T; } /** * @internal */ - public loadBuiltinAssets () { + public loadBuiltinAssets (): Promise { const builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets'); if (TEST || !builtinAssets) return Promise.resolve(); const resources = this._resources; - return new Promise((resolve, reject) => { - assetManager.loadBundle(BuiltinBundleName.INTERNAL, (err, bundle) => { + return new Promise((resolve, reject): void => { + assetManager.loadBundle(BuiltinBundleName.INTERNAL, (err, bundle): void => { if (err) { reject(err); return; } - assetManager.loadAny(builtinAssets, (err, assets) => { + assetManager.loadAny(builtinAssets, (err, assets): void => { if (err) { reject(err); } else { - assets.forEach((asset) => { + assets.forEach((asset): void => { resources[asset.name] = asset; // In Editor, no need to ignore asset destroy, we use auto gc to handle destroy if (!EDITOR_NOT_IN_PREVIEW) { releaseManager.addIgnoredAsset(asset); } @@ -342,7 +342,7 @@ export class BuiltinResMgr { }); } - public compileBuiltinMaterial () { + public compileBuiltinMaterial (): void { // NOTE: Builtin material should be compiled again after the render pipeline setup for (let i = 0; i < this._materialsToBeCompiled.length; ++i) { const mat = this._materialsToBeCompiled[i]; diff --git a/cocos/asset/asset-manager/bundle.ts b/cocos/asset/asset-manager/bundle.ts index 4d7cc9d2e1f..149adc0e376 100644 --- a/cocos/asset/asset-manager/bundle.ts +++ b/cocos/asset/asset-manager/bundle.ts @@ -175,7 +175,7 @@ export default class Bundle { * @deprecate Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. * */ - public init (options: IConfigOption) { + public init (options: IConfigOption): void { this._config.init(options); bundles.add(options.name, this); } @@ -241,7 +241,7 @@ export default class Bundle { type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T|T[]) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T|T[]) => void) | null, onComplete?: ((err: Error | null, data: T|T[]) => void) | null, - ) { + ): void { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); const options = { __requestType__: RequestType.PATH, type: _type, bundle: this.name, __outputAsArray__: Array.isArray(paths) }; cclegacy.assetManager.loadAny(paths, options, onProg, onComp); @@ -305,7 +305,7 @@ export default class Bundle { type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void) | null, onComplete?: ((err: Error | null, data: RequestItem[]) => void) | null, - ) { + ): void { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); cclegacy.assetManager.preloadAny(paths, { __requestType__: RequestType.PATH, type: _type, bundle: this.name }, onProg, onComp); } @@ -361,7 +361,7 @@ export default class Bundle { type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T[]) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: T[]) => void) | null, onComplete?: ((err: Error | null, data: T[]) => void) | null, - ) { + ): void { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); cclegacy.assetManager.loadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name, __outputAsArray__: true }, onProg, onComp); } @@ -418,7 +418,7 @@ export default class Bundle { type?: Constructor | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void)| null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: RequestItem[]) => void)| null, onComplete?: ((err: Error | null, data: RequestItem[]) => void)| null, - ) { + ): void { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); cclegacy.assetManager.preloadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name }, onProg, onComp); } @@ -459,12 +459,12 @@ export default class Bundle { options?: { [key: string]: any, preset?: 'string' } | ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: SceneAsset) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err: Error | null, data: SceneAsset) => void) | null, onComplete?: ((err: Error | null, data: SceneAsset) => void) | null, - ) { + ): void { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err: Error | null, data: SceneAsset) => void)>(options, onProgress, onComplete); opts.preset = opts.preset || 'scene'; opts.bundle = this.name; - cclegacy.assetManager.loadAny({ scene: sceneName }, opts, onProg, (err, sceneAsset) => { + cclegacy.assetManager.loadAny({ scene: sceneName }, opts, onProg, (err, sceneAsset): void => { if (err) { error(err.message, err.stack); } else if (sceneAsset.scene) { @@ -518,11 +518,11 @@ export default class Bundle { options?: { [key: string]: any, preset?: 'string' } | ((finished: number, total: number, item: RequestItem) => void) | ((err?: Error | null) => void) | null, onProgress?: ((finished: number, total: number, item: RequestItem) => void) | ((err?: Error | null) => void) | null, onComplete?: ((err?: Error | null) => void) | null, - ) { + ): void { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<((err?: Error | null) => void)>(options, onProgress, onComplete); opts.bundle = this.name; - cclegacy.assetManager.preloadAny({ scene: sceneName }, opts, onProg, (err) => { + cclegacy.assetManager.preloadAny({ scene: sceneName }, opts, onProg, (err): void => { if (err) { errorID(1210, sceneName, err.message); } @@ -585,7 +585,7 @@ export default class Bundle { * bundle1.release('misc/character/cocos'); * */ - public release (path: string, type?: Constructor | null) { + public release (path: string, type?: Constructor | null): void { const asset = this.get(path, type); if (asset) { releaseManager.tryRelease(asset, true); @@ -605,8 +605,8 @@ export default class Bundle { * * @engineInternal */ - public releaseUnusedAssets () { - assets.forEach((asset) => { + public releaseUnusedAssets (): void { + assets.forEach((asset): void => { const info = this.getAssetInfo(asset._uuid); if (info && !info.redirect) { releaseManager.tryRelease(asset); @@ -625,8 +625,8 @@ export default class Bundle { * // release all asset within bundle1 * bundle1.releaseAll(); */ - public releaseAll () { - assets.forEach((asset) => { + public releaseAll (): void { + assets.forEach((asset): void => { const info = this.getAssetInfo(asset._uuid); if (info && !info.redirect) { releaseManager.tryRelease(asset, true); @@ -637,7 +637,7 @@ export default class Bundle { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _destroy () { + public _destroy (): void { this._config.destroy(); } } diff --git a/cocos/asset/asset-manager/cache.ts b/cocos/asset/asset-manager/cache.ts index baccd29440e..c655aef3ff6 100644 --- a/cocos/asset/asset-manager/cache.ts +++ b/cocos/asset/asset-manager/cache.ts @@ -139,7 +139,7 @@ export default class Cache implements ICache { /** * @engineInternal */ - public get map () { + public get map (): Record | null { return this._map; } protected _map: Record | null = null; diff --git a/cocos/asset/asset-manager/config.ts b/cocos/asset/asset-manager/config.ts index cfc482d770d..1a4a0899332 100644 --- a/cocos/asset/asset-manager/config.ts +++ b/cocos/asset/asset-manager/config.ts @@ -146,7 +146,7 @@ const isMatchByWord = (path: string, test: string): boolean => { return true; }; -const processOptions = (options: IConfigOption) => { +const processOptions = (options: IConfigOption): void => { if (EDITOR_NOT_IN_PREVIEW || TEST) { return; } let uuids = options.uuids; const paths = options.paths; @@ -217,7 +217,7 @@ const processOptions = (options: IConfigOption) => { if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) { continue; } - options.extensionMap[ext].forEach((uuid, index) => { + options.extensionMap[ext].forEach((uuid, index): void => { options.extensionMap[ext][index] = uuids[uuid] || uuid; }); } @@ -241,7 +241,7 @@ export default class Config { public paths = new Cache(); - public init (options: IConfigOption) { + public init (options: IConfigOption): void { processOptions(options); this.importBase = options.importBase || ''; @@ -260,7 +260,7 @@ export default class Config { if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) { continue; } - options.extensionMap[ext].forEach((uuid) => { + options.extensionMap[ext].forEach((uuid): void => { const assetInfo = this.assetInfos.get(uuid); if (assetInfo) { assetInfo.extension = ext; @@ -297,7 +297,7 @@ export default class Config { } const infos = out || []; - this.paths.forEach((items, p) => { + this.paths.forEach((items, p): void => { if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) { for (let i = 0, l = items.length; i < l; i++) { const entry = items[i]; @@ -323,17 +323,17 @@ export default class Config { name = `/${name}`; } // search scene - const info = this.scenes.find((val, key) => key.endsWith(name)); + const info = this.scenes.find((val, key): boolean => key.endsWith(name)); return info; } - public destroy () { + public destroy (): void { this.paths.destroy(); this.scenes.destroy(); this.assetInfos.destroy(); } - private _initUuid (uuidList: string[]) { + private _initUuid (uuidList: string[]): void { if (!uuidList) { return; } @@ -344,7 +344,7 @@ export default class Config { } } - private _initPath (pathList: Record) { + private _initPath (pathList: Record): void { if (!pathList) { return; } const paths = this.paths; paths.clear(); @@ -369,7 +369,7 @@ export default class Config { } } - private _initScene (sceneList: Record) { + private _initScene (sceneList: Record): void { if (!sceneList) { return; } const scenes = this.scenes; scenes.clear(); @@ -382,7 +382,7 @@ export default class Config { } } - private _initPackage (packageList: Record) { + private _initPackage (packageList: Record): void { if (!packageList) { return; } const assetInfos = this.assetInfos; for (const packUuid in packageList) { @@ -407,7 +407,7 @@ export default class Config { } } - private _initVersion (versions: { import?: string[], native?: string[] }) { + private _initVersion (versions: { import?: string[], native?: string[] }): void { if (!versions) { return; } const assetInfos = this.assetInfos; let entries = versions.import; @@ -428,7 +428,7 @@ export default class Config { } } - private _initRedirect (redirect: string[]) { + private _initRedirect (redirect: string[]): void { if (!redirect) { return; } const assetInfos = this.assetInfos; for (let i = 0, l = redirect.length; i < l; i += 2) { diff --git a/cocos/asset/asset-manager/depend-util.ts b/cocos/asset/asset-manager/depend-util.ts index 79050f4700b..8f826676aea 100644 --- a/cocos/asset/asset-manager/depend-util.ts +++ b/cocos/asset/asset-manager/depend-util.ts @@ -58,7 +58,7 @@ export class DependUtil { * @en Global singleton for [[DependUtil]]. You can access it via [[AssetManager.dependUtil]]. * @zh [[DependUtil]] 的全局单例. 你可以通过 [[AssetManager.dependUtil]] 访问. */ - static get instance () { + static get instance (): DependUtil { if (!this._instance) { this._instance = new DependUtil(); } @@ -150,7 +150,7 @@ export class DependUtil { /** * @engineInternal */ - public remove (uuid: string) { + public remove (uuid: string): void { this._depends.remove(uuid); } @@ -234,7 +234,7 @@ export class DependUtil { private _parseDepsFromJson (json: any[]): string[] { const depends = parseUuidDependencies(json); - depends.forEach((uuid, index) => depends[index] = decodeUuid(uuid)); + depends.forEach((uuid, index): string => depends[index] = decodeUuid(uuid)); return depends; } diff --git a/cocos/asset/asset-manager/deprecated.ts b/cocos/asset/asset-manager/deprecated.ts index f2401e4de87..ed29f8cee5a 100644 --- a/cocos/asset/asset-manager/deprecated.ts +++ b/cocos/asset/asset-manager/deprecated.ts @@ -29,9 +29,9 @@ import Cache from './cache'; import assetManager, { AssetManager } from './asset-manager'; import { resources } from './bundle'; import dependUtil from './depend-util'; -import downloader from './downloader'; +import downloader, { Downloader } from './downloader'; import { getUuidFromURL, transform } from './helper'; -import parser from './parser'; +import parser, { Parser } from './parser'; import { releaseManager } from './release-manager'; import { assets, BuiltinBundleName, bundles } from './shared'; import { parseLoadResArgs, setDefaultProgressCallback } from './utilities'; @@ -41,13 +41,13 @@ import RequestItem from './request-item'; const ImageFmts = ['.png', '.jpg', '.bmp', '.jpeg', '.gif', '.ico', '.tiff', '.webp', '.image', '.pvr', '.pkm', '.astc']; const AudioFmts = ['.mp3', '.ogg', '.wav', '.m4a']; -function GetTrue () { return true; } +function GetTrue (): boolean { return true; } const md5Pipe = { transformURL (url: string): string { const uuid = getUuidFromURL(url); if (!uuid) { return url; } - const bundle = bundles.find((b) => !!b.getAssetInfo(uuid)); + const bundle = bundles.find((b): boolean => !!b.getAssetInfo(uuid)); if (!bundle) { return url; } let hashValue = ''; const info = bundle.getAssetInfo(uuid); @@ -66,7 +66,7 @@ const md5Pipe = { const basename = path.basename(url); url = `${dirname}.${hashValue}/${basename}`; } else { - url = url.replace(/.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,})/, (match, uuid) => `${match}.${hashValue}`); + url = url.replace(/.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,})/, (match, uuid): string => `${match}.${hashValue}`); } return url; @@ -111,7 +111,7 @@ export class CCLoader { return assets.map!; } else { const map = {}; - assets.forEach((val, key) => { + assets.forEach((val, key): void => { map[key] = val; }); return map; @@ -148,7 +148,7 @@ export class CCLoader { * @param completeCallback - Callback invoked when all resources loaded * @deprecated since v3.0, loader.load is deprecated, please use assetManager.loadRemote instead */ - public load (res: string|string[]|Record, progressCallback?: ((...args) => void)|null, completeCallback?: ((...args) => void)|null) { + public load (res: string|string[]|Record, progressCallback?: ((...args) => void)|null, completeCallback?: ((...args) => void)|null): void { if (completeCallback === undefined) { if (progressCallback !== undefined) { completeCallback = progressCallback; @@ -173,7 +173,7 @@ export class CCLoader { } const images: any[] = []; const audios: any[] = []; - assetManager.loadAny(requests, null, (finish, total, item) => { + assetManager.loadAny(requests, null, (finish, total, item): void => { if (item.content) { if (ImageFmts.includes(item.ext)) { images.push(item.content); @@ -182,7 +182,7 @@ export class CCLoader { } } if (progressCallback) { progressCallback(finish, total, item); } - }, (err, native) => { + }, (err, native): void => { let out: any = null; if (!err) { native = Array.isArray(native) ? native : [native]; @@ -192,11 +192,11 @@ export class CCLoader { let asset = item; const url = (requests[i] as Record).url; if (images.includes(asset)) { - factory.create(url, item, '.png', {}, (err, image) => { + factory.create(url, item, '.png', {}, (err, image): void => { asset = native[i] = image; }); } else if (audios.includes(asset)) { - factory.create(url, item, '.mp3', {}, (err, audio) => { + factory.create(url, item, '.mp3', {}, (err, audio): void => { asset = native[i] = audio; }); } @@ -205,7 +205,7 @@ export class CCLoader { } if (native.length > 1) { const map = Object.create(null); - native.forEach((asset) => { + native.forEach((asset): void => { map[asset._uuid] = asset; }); out = { isCompleted: GetTrue, _map: map }; @@ -235,7 +235,7 @@ export class CCLoader { * @return {Object} * @deprecated since v3.0 loader.getItem is deprecated, please use assetManager.assets.get instead */ - public getItem (id) { + public getItem (id): { content: Asset | null | undefined; } | null { return assetManager.assets.has(id) ? { content: assetManager.assets.get(id) } : null; } @@ -286,26 +286,26 @@ export class CCLoader { type: Constructor, progressCallback: LoadProgressCallback, completeCallback: LoadCompleteCallback, - ); + ): any; public loadRes ( url: string, type: Constructor, completeCallback: LoadCompleteCallback, - ); + ): any; public loadRes ( url: string, progressCallback: LoadProgressCallback, completeCallback: LoadCompleteCallback, - ); + ): any; public loadRes ( url: string, completeCallback: LoadCompleteCallback, - ); + ): any; public loadRes ( url: string, type?: Constructor | LoadCompleteCallback | LoadProgressCallback, progressCallback?: LoadProgressCallback | LoadCompleteCallback, completeCallback?: LoadCompleteCallback, - ) { + ): any { const { type: _type, onProgress, onComplete } = this._parseLoadResArgs(type as any, progressCallback as LoadProgressCallback, completeCallback as LoadCompleteCallback); @@ -354,11 +354,11 @@ export class CCLoader { type?: Constructor, progressCallback?: LoadProgressCallback, completeCallback?: LoadCompleteCallback, - ) { + ): void { const { type: _type, onProgress, onComplete } = this._parseLoadResArgs>(type as any, progressCallback as LoadProgressCallback, completeCallback as LoadCompleteCallback); - urls.forEach((url, i) => { + urls.forEach((url, i): void => { const extname = path.extname(url); if (extname && !resources.getInfoWithPath(url, _type)) { // strip extname @@ -421,35 +421,35 @@ export class CCLoader { type: Constructor, progressCallback: LoadProgressCallback, completeCallback: LoadDirCompleteCallback, - ); + ): any; public loadResDir ( url: string, type: Constructor, completeCallback: LoadDirCompleteCallback, - ); + ): any; public loadResDir ( url: string, progressCallback: LoadProgressCallback, completeCallback: LoadDirCompleteCallback, - ); + ): any; public loadResDir ( url: string, completeCallback: LoadDirCompleteCallback, - ); + ): any; public loadResDir ( url: string, type?: Constructor | LoadProgressCallback | LoadDirCompleteCallback, progressCallback?: LoadProgressCallback | LoadDirCompleteCallback, completeCallback?: LoadDirCompleteCallback, - ) { + ): any { const { type: _type, onProgress, onComplete } = this._parseLoadResArgs>(type as any, progressCallback as LoadProgressCallback, completeCallback as LoadDirCompleteCallback); - resources.loadDir(url, _type, onProgress, (err, out) => { + resources.loadDir(url, _type, onProgress, (err, out): void => { let urls: string[] = []; if (!err) { const infos = resources.getDirWithPath(url, _type); - urls = infos.map((info) => info.path); + urls = infos.map((info): string => info.path); } if (onComplete) { onComplete(err, out, urls); } }); @@ -532,7 +532,9 @@ export class CCLoader { * * @deprecated since v3.0 loader.md5Pipe is deprecated, assetLoader and md5Pipe were merged into assetManager.transformPipeline */ - public get md5Pipe () { + public get md5Pipe (): { + transformURL(url: string): string; + } { return md5Pipe; } @@ -548,7 +550,7 @@ export class CCLoader { * * @deprecated since v3.0 loader.downloader is deprecated, please use assetManager.downloader instead */ - get downloader () { + get downloader (): Downloader { return downloader; } @@ -564,7 +566,7 @@ export class CCLoader { * * @deprecated since v3.0 loader.loader is deprecated, please use assetManager.parser instead */ - get loader () { + get loader (): Parser { return assetManager.parser; } @@ -581,11 +583,11 @@ export class CCLoader { * @param extMap Handlers for corresponding type in a map * @deprecated since v3.0 loader.addDownloadHandlers is deprecated, please use assetManager.downloader.register instead */ - public addDownloadHandlers (extMap: Record void)) => void>) { + public addDownloadHandlers (extMap: Record void)) => void>): void { const handler = Object.create(null); for (const type in extMap) { const func = extMap[type]; - handler[`.${type}`] = (url, options, onComplete) => { + handler[`.${type}`] = (url, options, onComplete): void => { func({ url }, onComplete); }; } @@ -605,11 +607,11 @@ export class CCLoader { * @param extMap Handlers for corresponding type in a map * @deprecated since v3.0 loader.addLoadHandlers is deprecated, please use assetManager.parser.register instead */ - public addLoadHandlers (extMap: Record void)) => void>) { + public addLoadHandlers (extMap: Record void)) => void>): void { const handler = Object.create(null); for (const type in extMap) { const func = extMap[type]; - handler[`.${type}`] = (file, options, onComplete) => { + handler[`.${type}`] = (file, options, onComplete): void => { func({ content: file }, onComplete); }; } @@ -652,7 +654,7 @@ export class CCLoader { * @param asset Asset or assets to be released * @deprecated since v3.0 loader.release is deprecated, please use assetManager.releaseAsset instead */ - public release (asset: Asset|string|Array) { + public release (asset: Asset|string|Array): void { if (Array.isArray(asset)) { for (let i = 0; i < asset.length; i++) { let key = asset[i]; @@ -672,7 +674,7 @@ export class CCLoader { * * @deprecated since v3.0 loader.releaseAsset is deprecated, please use assetManager.releaseAsset instead */ - public releaseAsset (asset: Asset) { + public releaseAsset (asset: Asset): void { assetManager.releaseAsset(asset); } @@ -684,7 +686,7 @@ export class CCLoader { * * @deprecated since v3.0 loader.releaseRes is deprecated, please use assetManager.releaseRes instead */ - public releaseRes (res: string, type?: Constructor) { + public releaseRes (res: string, type?: Constructor): void { resources.release(res, type); } @@ -695,7 +697,7 @@ export class CCLoader { * * @deprecated since v3.0 loader.releaseAll is deprecated, please use assetManager.releaseAll instead */ - public releaseAll () { + public releaseAll (): void { assetManager.releaseAll(); assets.clear(); } @@ -749,7 +751,7 @@ export class CCLoader { * * @deprecated since v3.0 loader.setAutoRelease is deprecated, if you want to prevent some asset from auto releasing, please use Asset.addRef instead */ - public setAutoRelease (asset: Asset|string, autoRelease: boolean) { + public setAutoRelease (asset: Asset|string, autoRelease: boolean): void { if (typeof asset === 'object') { asset = asset._uuid; } this._autoReleaseSetting[asset] = !!autoRelease; } @@ -786,7 +788,7 @@ export class CCLoader { * @param autoRelease - Whether to release automatically during scene switch * @deprecated loader.setAutoReleaseRecursively is deprecated, if you want to prevent some asset from auto releasing, please use Asset.addRef instead */ - public setAutoReleaseRecursively (asset: Asset|string, autoRelease: boolean) { + public setAutoReleaseRecursively (asset: Asset|string, autoRelease: boolean): void { if (typeof asset === 'object') { asset = asset._uuid; } autoRelease = !!autoRelease; this._autoReleaseSetting[asset] = autoRelease; @@ -844,7 +846,7 @@ export const AssetLibrary = { * @param {String} [options.packedAssets] - packed assets (only used in runtime) * @deprecated AssetLibrary.init is deprecated, please use assetManager.init instead */ - init (options: Record) { + init (options: Record): void { options.importBase = options.libraryPath; options.nativeBase = BUILD ? options.rawAssetsBase : options.libraryPath; assetManager.init(options); @@ -879,7 +881,7 @@ export const AssetLibrary = { * @param {Asset} options.existingAsset - 加载现有资源,此参数仅在编辑器中可用。 * @deprecated since v3.0 AssetLibrary.loadAsset is deprecated, please use assetManager.loadAny instead */ - loadAsset (uuid: string, callback: ((err: Error | null, data?: any | null) => void), options?) { + loadAsset (uuid: string, callback: ((err: Error | null, data?: any | null) => void), options?): void { assetManager.loadAny(uuid, callback); }, }; @@ -904,7 +906,7 @@ replaceProperty(url, 'url', [ name: 'raw', targetName: 'Asset.prototype', newName: 'nativeUrl', - customFunction: (url: string) => { + customFunction: (url: string): string => { if (url.startsWith('resources/')) { return transform({ path: path.changeExtname(url.substr(10)), @@ -949,12 +951,12 @@ replaceProperty(cclegacy, 'cc', [ name: 'loader', newName: 'assetManager', logTimes: 1, - customGetter: () => loader, + customGetter: (): CCLoader => loader, }, { name: 'AssetLibrary', newName: 'assetManager', logTimes: 1, - customGetter: () => AssetLibrary, + customGetter: (): typeof AssetLibrary => AssetLibrary, }, { name: 'Pipeline', target: AssetManager, @@ -966,7 +968,7 @@ replaceProperty(cclegacy, 'cc', [ targetName: 'assetManager', newName: 'utils', logTimes: 1, - customGetter: () => url, + customGetter: (): Record => url, }, ]); @@ -985,7 +987,7 @@ replaceProperty(macro, 'macro', [ ]); const _autoRelease = releaseManager._autoRelease; -releaseManager._autoRelease = function (oldScene, newScene, persistNodes) { +releaseManager._autoRelease = function (oldScene, newScene, persistNodes): void { _autoRelease.call(releaseManager, oldScene, newScene, persistNodes); const releaseSettings = loader._autoReleaseSetting; const keys = Object.keys(releaseSettings); diff --git a/cocos/asset/asset-manager/download-dom-image.ts b/cocos/asset/asset-manager/download-dom-image.ts index d8025f159cb..f9d235bf554 100644 --- a/cocos/asset/asset-manager/download-dom-image.ts +++ b/cocos/asset/asset-manager/download-dom-image.ts @@ -39,13 +39,13 @@ export default function downloadDomImage ( img.crossOrigin = 'anonymous'; } - function loadCallback () { + function loadCallback (): void { img.removeEventListener('load', loadCallback); img.removeEventListener('error', errorCallback); if (onComplete) { onComplete(null, img); } } - function errorCallback () { + function errorCallback (): void { img.removeEventListener('load', loadCallback); img.removeEventListener('error', errorCallback); if (onComplete) { onComplete(new Error(getError(4930, url))); } diff --git a/cocos/asset/asset-manager/download-file.ts b/cocos/asset/asset-manager/download-file.ts index a03fbcc9784..e331b6ebbd6 100644 --- a/cocos/asset/asset-manager/download-file.ts +++ b/cocos/asset/asset-manager/download-file.ts @@ -46,29 +46,29 @@ export default function downloadFile ( } } - xhr.onload = () => { + xhr.onload = (): void => { if (xhr.status === 200 || xhr.status === 0) { if (onComplete) { onComplete(null, xhr.response); } } else if (onComplete) { onComplete(new Error(`${errInfo}${xhr.status}(no response)`)); } }; if (onProgress) { - xhr.onprogress = (e) => { + xhr.onprogress = (e): void => { if (e.lengthComputable) { onProgress(e.loaded, e.total); } }; } - xhr.onerror = () => { + xhr.onerror = (): void => { if (onComplete) { onComplete(new Error(`${errInfo}${xhr.status}(error)`)); } }; - xhr.ontimeout = () => { + xhr.ontimeout = (): void => { if (onComplete) { onComplete(new Error(`${errInfo}${xhr.status}(time out)`)); } }; - xhr.onabort = () => { + xhr.onabort = (): void => { if (onComplete) { onComplete(new Error(`${errInfo}${xhr.status}(abort)`)); } }; diff --git a/cocos/asset/asset-manager/download-script.ts b/cocos/asset/asset-manager/download-script.ts index 728f723c62c..e3027cc79f5 100644 --- a/cocos/asset/asset-manager/download-script.ts +++ b/cocos/asset/asset-manager/download-script.ts @@ -48,7 +48,7 @@ export default function downloadScript ( script.async = options.scriptAsyncLoading || false; script.src = url; - function loadHandler () { + function loadHandler (): void { script.parentNode!.removeChild(script); script.removeEventListener('load', loadHandler, false); script.removeEventListener('error', errorHandler, false); @@ -56,7 +56,7 @@ export default function downloadScript ( if (onComplete) { onComplete(null); } } - function errorHandler () { + function errorHandler (): void { script.parentNode!.removeChild(script); script.removeEventListener('load', loadHandler, false); script.removeEventListener('error', errorHandler, false); diff --git a/cocos/asset/asset-manager/downloader.ts b/cocos/asset/asset-manager/downloader.ts index e110cc084cd..d763e639e84 100644 --- a/cocos/asset/asset-manager/downloader.ts +++ b/cocos/asset/asset-manager/downloader.ts @@ -46,36 +46,36 @@ interface IDownloadRequest { const REGEX = /^(?:\w+:\/\/|\.+\/).+/; -const downloadImage = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { +const downloadImage = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { // if createImageBitmap is valid, we can transform blob to ImageBitmap. Otherwise, just use HTMLImageElement to load const func = sys.hasFeature(sys.Feature.IMAGE_BITMAP) && cclegacy.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage; func(url, options, onComplete); }; -const downloadBlob = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { +const downloadBlob = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { options.xhrResponseType = 'blob'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadJson = (url: string, options: Record, onComplete: ((err: Error | null, data?: Record | null) => void)) => { +const downloadJson = (url: string, options: Record, onComplete: ((err: Error | null, data?: Record | null) => void)): void => { options.xhrResponseType = 'json'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadArrayBuffer = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { +const downloadArrayBuffer = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { options.xhrResponseType = 'arraybuffer'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadCCON = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)) => { - downloadJson(url, options, (err, json) => { +const downloadCCON = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)): void => { + downloadJson(url, options, (err, json): void => { if (err) { onComplete(err); return; } const cconPreface = parseCCONJson(json); - const chunkPromises = Promise.all(cconPreface.chunks.map((chunk) => new Promise((resolve, reject) => { - downloadArrayBuffer(`${path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => { + const chunkPromises = Promise.all(cconPreface.chunks.map((chunk): Promise => new Promise((resolve, reject): void => { + downloadArrayBuffer(`${path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer): void => { if (err) { reject(err); } else { @@ -83,17 +83,17 @@ const downloadCCON = (url: string, options: Record, onComplete: ((e } }); }))); - chunkPromises.then((chunks) => { + chunkPromises.then((chunks): void => { const ccon = new CCON(cconPreface.document, chunks); onComplete(null, ccon); - }).catch((err) => { + }).catch((err): void => { onComplete(err); }); }); }; -const downloadCCONB = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)) => { - downloadArrayBuffer(url, options, (err, arrayBuffer: ArrayBuffer) => { +const downloadCCONB = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)): void => { + downloadArrayBuffer(url, options, (err, arrayBuffer: ArrayBuffer): void => { if (err) { onComplete(err); return; @@ -107,12 +107,12 @@ const downloadCCONB = (url: string, options: Record, onComplete: (( }); }; -const downloadText = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { +const downloadText = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { options.xhrResponseType = 'text'; downloadFile(url, options, options.onFileProgress, onComplete); }; -const downloadBundle = (nameOrUrl: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => { +const downloadBundle = (nameOrUrl: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { const bundleName = path.basename(nameOrUrl); let url = nameOrUrl; if (!REGEX.test(url)) { @@ -127,7 +127,7 @@ const downloadBundle = (nameOrUrl: string, options: Record, onCompl const config = `${url}/config.${version ? `${version}.` : ''}json`; let out: IConfigOption | null = null; let error: Error | null = null; - downloadJson(config, options, (err, response) => { + downloadJson(config, options, (err, response): void => { error = err || error; out = response as IConfigOption; if (out) { out.base = `${url}/`; } @@ -137,7 +137,7 @@ const downloadBundle = (nameOrUrl: string, options: Record, onCompl }); const jspath = `${url}/index.${version ? `${version}.` : ''}js`; - downloadScript(jspath, options, (err) => { + downloadScript(jspath, options, (err): void => { error = err || error; if (++count === 2) { onComplete(error, out); @@ -159,7 +159,7 @@ export class Downloader { * @en Global singleton for [[Downloader]]. You can access it via [[AssetManager.downloader]]. * @zh [[Downloader]] 的全局单例. 你可以通过 [[AssetManager.downloader]] 访问. */ - public static get instance () { + public static get instance (): Downloader { if (!Downloader._instance) { Downloader._instance = new Downloader(); } @@ -193,7 +193,7 @@ export class Downloader { * 远程服务器地址。 * */ - public get remoteServerAddress () { + public get remoteServerAddress (): string { return this._remoteServerAddress; } @@ -328,7 +328,7 @@ export class Downloader { /** * @engineInternal */ - public init (remoteServerAddress = '', bundleVers: Record = {}, remoteBundles: string[] = []) { + public init (remoteServerAddress = '', bundleVers: Record = {}, remoteBundles: string[] = []): void { this._downloading.clear(); this._queue.length = 0; this._remoteServerAddress = remoteServerAddress; @@ -365,7 +365,7 @@ export class Downloader { public register ( type: string | Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>, handler?: (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void, - ) { + ): void { if (typeof type === 'object') { js.mixin(this._downloaders, type); } else { @@ -408,7 +408,7 @@ export class Downloader { const downloadCallbacks = this._downloading.get(id); if (downloadCallbacks) { downloadCallbacks.push(onComplete); - const request = this._queue.find((x) => x.id === id); + const request = this._queue.find((x): boolean => x.id === id); if (!request) { return; } const priority: number = options.priority || 0; if (request.priority < priority) { @@ -424,7 +424,7 @@ export class Downloader { const maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame : this.maxRequestsPerFrame; const handler = this._downloaders[type] || this._downloaders.default; - const process: RetryFunction = (index, callback) => { + const process: RetryFunction = (index, callback): void => { if (index === 0) { this._downloading.add(id, [onComplete]); } @@ -437,7 +437,7 @@ export class Downloader { // refresh this._updateTime(); - const done: ((err: Error | null, data?: any | null) => void) = (err, data) => { + const done: ((err: Error | null, data?: any | null) => void) = (err, data): void => { // when finish downloading, update _totalNum this._totalNum--; this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame); @@ -458,7 +458,7 @@ export class Downloader { }; // when retry finished, invoke callbacks - const finale = (err, result) => { + const finale = (err, result): void => { if (!err) { files.add(id, result); } const callbacks = this._downloading.remove(id) as ((err: Error | null, data?: any | null) => void)[]; for (let i = 0, l = callbacks.length; i < l; i++) { @@ -478,13 +478,13 @@ export class Downloader { * * @deprecated loader.downloader.loadSubpackage is deprecated, please use AssetManager.loadBundle instead. */ - public loadSubpackage (name: string, completeCallback?: ((err?: Error | null) => void)) { + public loadSubpackage (name: string, completeCallback?: ((err?: Error | null) => void)): void { cclegacy.assetManager.loadBundle(name, null, completeCallback); } private constructor () {} - private _updateTime () { + private _updateTime (): void { const now = performance.now(); // use deltaTime as interval const deltaTime = cclegacy.game.deltaTime; @@ -496,12 +496,12 @@ export class Downloader { } // handle the rest request in next period - private _handleQueue (maxConcurrency: number, maxRequestsPerFrame: number) { + private _handleQueue (maxConcurrency: number, maxRequestsPerFrame: number): void { this._checkNextPeriod = false; this._updateTime(); while (this._queue.length > 0 && this._totalNum < maxConcurrency && this._totalNumThisPeriod < maxRequestsPerFrame) { if (this._queueDirty) { - this._queue.sort((a, b) => a.priority - b.priority); + this._queue.sort((a, b): number => a.priority - b.priority); this._queueDirty = false; } const request = this._queue.pop(); @@ -516,7 +516,7 @@ export class Downloader { this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame); } - private _handleQueueInNextFrame (maxConcurrency: number, maxRequestsPerFrame: number) { + private _handleQueueInNextFrame (maxConcurrency: number, maxRequestsPerFrame: number): void { if (!this._checkNextPeriod && this._queue.length > 0) { misc.callInNextTick(this._handleQueue.bind(this), maxConcurrency, maxRequestsPerFrame); this._checkNextPeriod = true; diff --git a/cocos/asset/asset-manager/editor-path-replace.ts b/cocos/asset/asset-manager/editor-path-replace.ts index f1fe2b3cf98..ae5172088b4 100644 --- a/cocos/asset/asset-manager/editor-path-replace.ts +++ b/cocos/asset/asset-manager/editor-path-replace.ts @@ -30,9 +30,9 @@ declare const Editor: any; if ((EDITOR || PREVIEW) && !TEST) { const cache: {[uuid: string]: string | null} = {}; const resolveMap: { [uuid: string]: Function[] } = {}; - const replaceExtension = (task: Task, done) => { + const replaceExtension = (task: Task, done): void => { task.output = task.input; - (async () => { + (async (): Promise => { for (let i = 0; i < task.input.length; i++) { const item = task.input[i]; if (!item.uuid || item.isNative) { continue; } @@ -46,17 +46,17 @@ if ((EDITOR || PREVIEW) && !TEST) { continue; } } - })().then(() => { + })().then((): void => { done(null, null); - }).catch((reason) => { + }).catch((reason): void => { done(reason, null); }); }; - const fetchText = (url) => new Promise((resolve, reject) => { + const fetchText = (url): Promise => new Promise((resolve, reject): void => { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); - xhr.onload = () => { + xhr.onload = (): void => { if (xhr.status !== 200) { reject(); return; @@ -71,7 +71,7 @@ if ((EDITOR || PREVIEW) && !TEST) { if (cache[uuid] !== null) { return cache[uuid] as string; } - return new Promise((resolve) => { + return new Promise((resolve): void => { resolveMap[uuid] = resolveMap[uuid] || []; resolveMap[uuid].push(resolve); }); @@ -94,7 +94,7 @@ if ((EDITOR || PREVIEW) && !TEST) { } cache[uuid] = text; if (resolveMap[uuid]) { - resolveMap[uuid].forEach((func) => func(text)); + resolveMap[uuid].forEach((func): any => func(text)); resolveMap[uuid] = []; } return text; diff --git a/cocos/asset/asset-manager/factory.ts b/cocos/asset/asset-manager/factory.ts index 3d1cd620c52..9f8bb8fcab2 100644 --- a/cocos/asset/asset-manager/factory.ts +++ b/cocos/asset/asset-manager/factory.ts @@ -39,7 +39,7 @@ import { js } from '../../core'; export type CreateHandler = (id: string, data: any, options: Record, onComplete: ((err: Error | null, data?: Asset | Bundle | null) => void)) => void; -function createImageAsset (id: string, data: HTMLImageElement, options: Record, onComplete: ((err: Error | null, data?: ImageAsset | null) => void)) { +function createImageAsset (id: string, data: HTMLImageElement, options: Record, onComplete: ((err: Error | null, data?: ImageAsset | null) => void)): void { let out: ImageAsset | null = null; let err: Error | null = null; try { @@ -52,33 +52,33 @@ function createImageAsset (id: string, data: HTMLImageElement, options: Record, options: Record, onComplete: ((err: Error | null, data?: JsonAsset | null) => void)) { +function createJsonAsset (id: string, data: Record, options: Record, onComplete: ((err: Error | null, data?: JsonAsset | null) => void)): void { const out = new JsonAsset(); out.json = data; onComplete(null, out); } -function createTextAsset (id: string, data: string, options: Record, onComplete: ((err: Error | null, data?: TextAsset | null) => void)) { +function createTextAsset (id: string, data: string, options: Record, onComplete: ((err: Error | null, data?: TextAsset | null) => void)): void { const out = new TextAsset(); out.text = data; onComplete(null, out); } -function createBufferAsset (id: string, data: ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: BufferAsset | null) => void)) { +function createBufferAsset (id: string, data: ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: BufferAsset | null) => void)): void { const out = new BufferAsset(); out._nativeUrl = id; out._nativeAsset = data; onComplete(null, out); } -function createAsset (id: string, data: any, options: Record, onComplete: ((err: Error | null, data?: Asset | null) => void)) { +function createAsset (id: string, data: any, options: Record, onComplete: ((err: Error | null, data?: Asset | null) => void)): void { const out = new Asset(); out._nativeUrl = id; out._nativeAsset = data; onComplete(null, out); } -function createBundle (id: string, data: IConfigOption, options: Record, onComplete: ((err: Error | null, data?: Bundle | null) => void)) { +function createBundle (id: string, data: IConfigOption, options: Record, onComplete: ((err: Error | null, data?: Bundle | null) => void)): void { let bundle = bundles.get(data.name); if (!bundle) { bundle = data.name === BuiltinBundleName.RESOURCES ? resources : new Bundle(); @@ -87,7 +87,7 @@ function createBundle (id: string, data: IConfigOption, options: Record { + import(`virtual:///prerequisite-imports/${bundle.name}`).then((): void => { onComplete(null, bundle); }).catch(onComplete); } else { @@ -160,7 +160,7 @@ export class Factory { } this._creating.add(id, [onComplete]); - handler(id, data, options, (err, result) => { + handler(id, data, options, (err, result): void => { if (!err && result instanceof Asset) { result._uuid = id; cache(id, result, options.cacheAsset); diff --git a/cocos/asset/asset-manager/fetch.ts b/cocos/asset/asset-manager/fetch.ts index e325c1947e9..57e41fed200 100644 --- a/cocos/asset/asset-manager/fetch.ts +++ b/cocos/asset/asset-manager/fetch.ts @@ -30,7 +30,7 @@ import { assets, fetchPipeline } from './shared'; import Task from './task'; import { clear, forEach, getDepends } from './utilities'; -export default function fetch (task: Task, done: ((err?: Error | null) => void)) { +export default function fetch (task: Task, done: ((err?: Error | null) => void)): void { let firstTask = false; if (!task.progress) { task.progress = { finish: 0, total: task.input.length, canInvoke: true }; @@ -44,7 +44,7 @@ export default function fetch (task: Task, done: ((err?: Error | null) => void)) task.output = []; - forEach(task.input as RequestItem[], (item, cb) => { + forEach(task.input as RequestItem[], (item, cb): void => { if (!item.isNative && assets.has(item.uuid)) { const asset = assets.get(item.uuid); item.content = asset!.addRef(); @@ -56,7 +56,7 @@ export default function fetch (task: Task, done: ((err?: Error | null) => void)) return; } - packManager.load(item, task.options, (err, data) => { + packManager.load(item, task.options, (err, data): void => { if (err) { if (!task.isFinished) { if (!cclegacy.assetManager.force || firstTask) { @@ -84,7 +84,7 @@ export default function fetch (task: Task, done: ((err?: Error | null) => void)) } cb(); }); - }, () => { + }, (): void => { if (task.isFinished) { clear(task, true); task.dispatch('error'); @@ -98,7 +98,7 @@ export default function fetch (task: Task, done: ((err?: Error | null) => void)) options, onProgress: task.onProgress, onError: Task.prototype.recycle, - onComplete: (err) => { + onComplete: (err): void => { if (!err) { task.output.push(...subTask.output); subTask.recycle(); @@ -115,7 +115,7 @@ export default function fetch (task: Task, done: ((err?: Error | null) => void)) }); } -function decreaseRef (task: Task) { +function decreaseRef (task: Task): void { const output = task.output as RequestItem[]; for (let i = 0, l = output.length; i < l; i++) { if (output[i].content) { diff --git a/cocos/asset/asset-manager/helper.ts b/cocos/asset/asset-manager/helper.ts index a12991b2c89..4f5ec26c6cd 100644 --- a/cocos/asset/asset-manager/helper.ts +++ b/cocos/asset/asset-manager/helper.ts @@ -80,7 +80,7 @@ export function getUrlWithUuid (uuid: string, options?: { [k: string]: any, isNa if (options!.nativeExt) { options!.ext = options!.nativeExt; } - const bundle = bundles.find((b) => !!b.getAssetInfo(uuid)); + const bundle = bundles.find((b): boolean => !!b.getAssetInfo(uuid)); if (bundle) { options!.bundle = bundle.name; } @@ -99,7 +99,7 @@ export function getUrlWithUuid (uuid: string, options?: { [k: string]: any, isNa * @returns @en Whether or not the asset is a SceneAsset. @zh 此资源是否是场景资源。 * */ -export function isScene (asset) { +export function isScene (asset): boolean { return !!asset && (asset instanceof cclegacy.SceneAsset || asset instanceof cclegacy.Scene); } diff --git a/cocos/asset/asset-manager/load.ts b/cocos/asset/asset-manager/load.ts index 898bcfebe26..8e7c27b655d 100644 --- a/cocos/asset/asset-manager/load.ts +++ b/cocos/asset/asset-manager/load.ts @@ -46,7 +46,7 @@ interface ILoadingRequest { callbacks: Array<{ done: ((err?: Error | null) => void); item: RequestItem }>; } -export default function load (task: Task, done: ((err?: Error | null) => void)) { +export default function load (task: Task, done: ((err?: Error | null) => void)): void { let firstTask = false; if (!task.progress) { task.progress = { finish: 0, total: task.input.length, canInvoke: true }; @@ -59,13 +59,13 @@ export default function load (task: Task, done: ((err?: Error | null) => void)) task.output = []; - forEach(task.input as RequestItem[], (item, cb) => { + forEach(task.input as RequestItem[], (item, cb): void => { const subTask = Task.create({ input: item, onProgress: task.onProgress, options, progress, - onComplete: (err, result) => { + onComplete: (err, result): void => { if (err && !task.isFinished) { if (!cclegacy.assetManager.force || firstTask) { if (BUILD) { @@ -84,7 +84,7 @@ export default function load (task: Task, done: ((err?: Error | null) => void)) }); loadOneAssetPipeline.async(subTask); - }, () => { + }, (): void => { options!.__exclude__ = null; if (task.isFinished) { @@ -101,7 +101,7 @@ export default function load (task: Task, done: ((err?: Error | null) => void)) const loadOneAssetPipeline = new Pipeline('loadOneAsset', [ - function fetch (task, done) { + function fetch (task, done): void { const item = task.output = task.input as RequestItem; const { options, isNative, uuid, file } = item; const { reloadAsset } = options; @@ -111,20 +111,20 @@ const loadOneAssetPipeline = new Pipeline('loadOneAsset', [ return; } - packManager.load(item, task.options, (err, data) => { + packManager.load(item, task.options, (err, data): void => { item.file = data; done(err); }); }, - function parse (task, done) { + function parse (task, done): void { const item: RequestItem = task.output = task.input; const progress: IProgress = task.progress; const exclude: Record = task.options!.__exclude__; const { id, file, options } = item; if (item.isNative) { - parser.parse(id, file, item.ext, options, (err, asset) => { + parser.parse(id, file, item.ext, options, (err, asset): void => { if (err) { done(err); return; @@ -161,7 +161,7 @@ const loadOneAssetPipeline = new Pipeline('loadOneAsset', [ done(); } else { options.__uuid__ = uuid; - parser.parse(id, file, 'import', options, (err, asset: Asset) => { + parser.parse(id, file, 'import', options, (err, asset: Asset): void => { if (err) { done(err); return; @@ -173,7 +173,7 @@ const loadOneAssetPipeline = new Pipeline('loadOneAsset', [ }, ]); -function loadDepends (task: Task, asset: Asset, done: ((err?: Error | null) => void)) { +function loadDepends (task: Task, asset: Asset, done: ((err?: Error | null) => void)): void { const { input: item, progress } = task; const { uuid, id, options, config } = item as RequestItem; const { cacheAsset } = options; @@ -196,7 +196,7 @@ function loadDepends (task: Task, asset: Asset, done: ((err?: Error | null) => v onProgress: task.onProgress, onError: Task.prototype.recycle, progress, - onComplete: (err) => { + onComplete: (err): void => { if (asset.decRef) { asset.decRef(false); } diff --git a/cocos/asset/asset-manager/pack-manager.ts b/cocos/asset/asset-manager/pack-manager.ts index cf3676d8d93..ae4275b2073 100644 --- a/cocos/asset/asset-manager/pack-manager.ts +++ b/cocos/asset/asset-manager/pack-manager.ts @@ -113,7 +113,7 @@ export class PackManager { onComplete(err, out); } - public init () { + public init (): void { this._loading.clear(); } @@ -140,7 +140,7 @@ export class PackManager { */ public register (type: string, handler: Unpacker): void; public register (map: Record): void; - public register (type: string | Record, handler?: Unpacker) { + public register (type: string | Record, handler?: Unpacker): void { if (typeof type === 'object') { js.mixin(this._unpackers, type); } else { @@ -215,7 +215,7 @@ export class PackManager { const packs = item.info.packs; // find a loading package - let pack = packs.find((val) => this._loading.has(val.uuid)); + let pack = packs.find((val): boolean => this._loading.has(val.uuid)); if (pack) { this._loading.get(pack.uuid)!.push({ onComplete, id: item.id }); @@ -229,13 +229,13 @@ export class PackManager { // find the url of pack const url = transform(pack.uuid, { ext: pack.ext, bundle: item.config!.name }) as string; - downloader.download(pack.uuid, url, pack.ext, item.options, (err, data) => { + downloader.download(pack.uuid, url, pack.ext, item.options, (err, data): void => { files.remove(pack!.uuid); if (err) { error(err.message, err.stack); } // unpack package - this.unpack(pack!.packedUuids, data, pack!.ext, item.options, (err2, result) => { + this.unpack(pack!.packedUuids, data, pack!.ext, item.options, (err2, result): void => { if (!err2) { for (const id in result) { files.add(id, result[id]); diff --git a/cocos/asset/asset-manager/parser.ts b/cocos/asset/asset-manager/parser.ts index 4982f766cb3..5a156500e95 100644 --- a/cocos/asset/asset-manager/parser.ts +++ b/cocos/asset/asset-manager/parser.ts @@ -69,7 +69,7 @@ export class Parser { private static _instance: Parser; - public static get instance () { + public static get instance (): Parser { if (!this._instance) { this._instance = new Parser(); } @@ -80,14 +80,14 @@ export class Parser { /** * @engineInternal */ - public parseImage (file: HTMLImageElement | Blob, options: Record, onComplete: ((err: Error | null, data?: HTMLImageElement | ImageBitmap | null) => void)) { + public parseImage (file: HTMLImageElement | Blob, options: Record, onComplete: ((err: Error | null, data?: HTMLImageElement | ImageBitmap | null) => void)): void { if (file instanceof HTMLImageElement) { onComplete(null, file); return; } - createImageBitmap(file, { premultiplyAlpha: 'none' }).then((result) => { + createImageBitmap(file, { premultiplyAlpha: 'none' }).then((result): void => { onComplete(null, result); - }, (err) => { + }, (err): void => { onComplete(err, null); }); } @@ -95,7 +95,7 @@ export class Parser { /** * @engineInternal */ - public parsePVRTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) { + public parsePVRTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)): void { let err: Error | null = null; let out: IMemoryImageSource | null = null; try { @@ -110,7 +110,7 @@ export class Parser { /** * @engineInternal */ - public parsePKMTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) { + public parsePKMTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)): void { let err: Error | null = null; let out: IMemoryImageSource | null = null; try { @@ -125,7 +125,7 @@ export class Parser { /** * @engineInternal */ - public parseASTCTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)) { + public parseASTCTex (file: ArrayBuffer | ArrayBufferView, options: Record, onComplete: ((err: Error | null, data?: IMemoryImageSource | null) => void)): void { let err: Error | null = null; let out: IMemoryImageSource | null = null; try { @@ -140,7 +140,7 @@ export class Parser { /** * @engineInternal */ - public parsePlist (file: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) { + public parsePlist (file: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { let err: Error | null = null; const result = plistParser.parse(file); if (!result) { err = new Error('parse failed'); } @@ -150,7 +150,7 @@ export class Parser { /** * @engineInternal */ - public parseImport (file: Record | CCON, options: Record, onComplete: ((err: Error | null, data?: Asset | null) => void)) { + public parseImport (file: Record | CCON, options: Record, onComplete: ((err: Error | null, data?: Asset | null) => void)): void { if (!file) { onComplete(new Error(`The json file of asset ${options.__uuid__ as string} is empty or missing`)); return; @@ -168,7 +168,7 @@ export class Parser { /** * @engineInternal */ - public init () { + public init (): void { this._parsing.clear(); } @@ -198,7 +198,7 @@ export class Parser { public register ( type: string | Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>, handler?: (file: any, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void, - ) { + ): void { if (typeof type === 'object') { js.mixin(this._parsers, type); } else { @@ -246,7 +246,7 @@ export class Parser { } this._parsing.add(id, [onComplete]); - parseHandler(file, options, (err, data) => { + parseHandler(file, options, (err, data): void => { if (err) { files.remove(id); } else if (!isScene(data)) { diff --git a/cocos/asset/asset-manager/preprocess.ts b/cocos/asset/asset-manager/preprocess.ts index b402a109892..ecc1e1bed3e 100644 --- a/cocos/asset/asset-manager/preprocess.ts +++ b/cocos/asset/asset-manager/preprocess.ts @@ -25,7 +25,7 @@ import { RequestType, transformPipeline } from './shared'; import Task from './task'; -export default function preprocess (task: Task, done: ((err?: Error | null) => void)) { +export default function preprocess (task: Task, done: ((err?: Error | null) => void)): void { const options = task.options; const subOptions = Object.create(null); const leftOptions = Object.create(null); diff --git a/cocos/asset/asset-manager/release-manager.ts b/cocos/asset/asset-manager/release-manager.ts index 418e148e8ec..121af14ae55 100644 --- a/cocos/asset/asset-manager/release-manager.ts +++ b/cocos/asset/asset-manager/release-manager.ts @@ -30,7 +30,7 @@ import Cache from './cache'; import dependUtil from './depend-util'; import { assets, references } from './shared'; -function visitAsset (asset: Asset, deps: string[]) { +function visitAsset (asset: Asset, deps: string[]): void { // Skip assets generated programmatically or by user (e.g. label texture) if (!asset._uuid) { return; @@ -38,7 +38,7 @@ function visitAsset (asset: Asset, deps: string[]) { deps.push(asset._uuid); } -function visitComponent (comp: any, deps: string[]) { +function visitComponent (comp: any, deps: string[]): void { const props = Object.getOwnPropertyNames(comp); for (let i = 0; i < props.length; i++) { const propName = props[i]; @@ -67,7 +67,7 @@ function visitComponent (comp: any, deps: string[]) { } } -function visitNode (node: any, deps: string[]) { +function visitNode (node: any, deps: string[]): void { for (let i = 0; i < node._components.length; i++) { visitComponent(node._components[i], deps); } @@ -76,7 +76,7 @@ function visitNode (node: any, deps: string[]) { } } -function descendOpRef (asset: Asset, refs: Record, exclude: string[], op: number) { +function descendOpRef (asset: Asset, refs: Record, exclude: string[], op: number): void { exclude.push(asset._uuid); const depends = dependUtil.getDeps(asset._uuid); for (let i = 0, l = depends.length; i < l; i++) { @@ -118,7 +118,7 @@ class ReleaseManager { private _eventListener = false; private _dontDestroyAssets: string[] = []; - public addIgnoredAsset (asset: Asset) { + public addIgnoredAsset (asset: Asset): void { this._dontDestroyAssets.push(asset._uuid); } @@ -130,7 +130,7 @@ class ReleaseManager { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _addPersistNodeRef (node: Node) { + public _addPersistNodeRef (node: Node): void { const deps = []; visitNode(node, deps); for (let i = 0, l = deps.length; i < l; i++) { @@ -145,7 +145,7 @@ class ReleaseManager { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _removePersistNodeRef (node: Node) { + public _removePersistNodeRef (node: Node): void { if (!this._persistNodeDeps.has(node.uuid)) { return; } const deps = this._persistNodeDeps.get(node.uuid) as string[]; @@ -162,7 +162,7 @@ class ReleaseManager { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _autoRelease (oldScene: Scene, newScene: Scene, persistNodes: Record) { + public _autoRelease (oldScene: Scene, newScene: Scene, persistNodes: Record): void { if (oldScene) { const childs = dependUtil.getDeps(oldScene.uuid); for (let i = 0, l = childs.length; i < l; i++) { @@ -220,15 +220,15 @@ class ReleaseManager { } } - private _freeAssets () { + private _freeAssets (): void { this._eventListener = false; - this._toDelete.forEach((asset) => { + this._toDelete.forEach((asset): void => { this._free(asset); }); this._toDelete.clear(); } - private _free (asset: Asset, force = false) { + private _free (asset: Asset, force = false): void { const uuid = asset._uuid; this._toDelete.remove(uuid); @@ -263,7 +263,7 @@ class ReleaseManager { if (dependant && dependant.length === 0) { references!.remove(uuid); } - references!.forEach((dependance, key) => { + references!.forEach((dependance, key): void => { for (let i = dependance.length - 1; i >= 0; i--) { if (dependance[i][0].deref() === asset) { js.array.fastRemoveAt(dependance, i); diff --git a/cocos/asset/asset-manager/task.ts b/cocos/asset/asset-manager/task.ts index 8c6032f8dd0..e69dcce68f2 100644 --- a/cocos/asset/asset-manager/task.ts +++ b/cocos/asset/asset-manager/task.ts @@ -176,7 +176,7 @@ export default class Task { /** * @deprecated Typo. Since v3.7, please use [[Task.isFinished]] instead. */ - public get isFinish () { + public get isFinish (): boolean { return this.isFinished; } @@ -250,7 +250,7 @@ export default class Task { * task.set({input: ['test'], onComplete: (err, result) => console.log(err), onProgress: (finish, total) => console.log(finish / total)}); * */ - public set (options: ITaskOption = Object.create(null)) { + public set (options: ITaskOption = Object.create(null)): void { this.onComplete = options.onComplete || null; this.onProgress = options.onProgress || null; this.onError = options.onError || null; diff --git a/cocos/asset/asset-manager/url-transformer.ts b/cocos/asset/asset-manager/url-transformer.ts index 9de1437fc1c..a37beee47ec 100644 --- a/cocos/asset/asset-manager/url-transformer.ts +++ b/cocos/asset/asset-manager/url-transformer.ts @@ -32,7 +32,7 @@ import Task from './task'; const infos: IAddressableInfo[] = []; -export function parse (task: Task) { +export function parse (task: Task): null { const options = task.options; const input = Array.isArray(task.input) ? task.input : [task.input]; @@ -57,7 +57,7 @@ export function parse (task: Task) { case RequestType.UUID: { const uuid = out.uuid = decodeUuid(item.uuid); if (!item.bundle) { - const bundle = bundles.find((bundle) => !!bundle.getAssetInfo(uuid)); + const bundle = bundles.find((bundle): boolean => !!bundle.getAssetInfo(uuid)); item.bundle = (bundle && bundle.name); } if (bundles.has(item.bundle)) { @@ -113,7 +113,7 @@ export function parse (task: Task) { break; case RequestType.SCENE: if (!item.bundle) { - const bundle = bundles.find((bundle) => !!bundle.getSceneInfo(item.scene)); + const bundle = bundles.find((bundle): boolean => !!bundle.getSceneInfo(item.scene)); item.bundle = bundle && bundle.name; } if (bundles.has(item.bundle)) { @@ -155,7 +155,7 @@ export function parse (task: Task) { return null; } -export function replaceOverrideAsset (task: Task) { +export function replaceOverrideAsset (task: Task): void { const input = task.output = task.input; for (let i = 0; i < input.length; i++) { const item = input[i] as RequestItem; @@ -167,7 +167,7 @@ export function replaceOverrideAsset (task: Task) { item.ext = item.isNative ? item.ext : '.json'; continue; } - const bundle = bundles.find((bundle) => !!bundle.getAssetInfo(uuid)); + const bundle = bundles.find((bundle): boolean => !!bundle.getAssetInfo(uuid)); if (bundle) { item.overrideUuid = uuid; let config = bundle.config; @@ -187,7 +187,7 @@ export function replaceOverrideAsset (task: Task) { } } -export function combine (task: Task) { +export function combine (task: Task): any { const input = task.output = task.input; for (let i = 0; i < input.length; i++) { const item = input[i] as RequestItem; diff --git a/cocos/asset/asset-manager/utilities.ts b/cocos/asset/asset-manager/utilities.ts index 15bda1f876f..11196aa66d8 100644 --- a/cocos/asset/asset-manager/utilities.ts +++ b/cocos/asset/asset-manager/utilities.ts @@ -39,11 +39,11 @@ declare class WeakRef { constructor (obj: any); } -export function setDefaultProgressCallback (onProgress: (finished: number, total: number, item: RequestItem) => void) { +export function setDefaultProgressCallback (onProgress: (finished: number, total: number, item: RequestItem) => void): void { defaultProgressCallback = onProgress; } -export function clear (task: Task, clearRef: boolean) { +export function clear (task: Task, clearRef: boolean): void { for (let i = 0, l = task.input.length; i < l; i++) { const item = task.input[i] as RequestItem; if (clearRef) { @@ -69,15 +69,15 @@ export function urlAppendTimestamp (url: string, append: boolean): string { export type RetryFunction = (times: number, done: ((err: Error | null, data?: any | null) => void)) => void; -export function retry (process: RetryFunction, times: number, wait: number, onComplete: ((err: Error | null, data?: any | null) => void), index = 0) { - process(index, (err, result) => { +export function retry (process: RetryFunction, times: number, wait: number, onComplete: ((err: Error | null, data?: any | null) => void), index = 0): void { + process(index, (err, result): void => { index++; if (!err || index > times) { if (onComplete) { onComplete(err, result); } } else { - setTimeout(() => { + setTimeout((): void => { retry(process, times, wait, onComplete, index); }, wait); } @@ -106,7 +106,7 @@ export function getDepends (uuid: string, data: Asset | Record, exc } } -export function cache (id: string, asset: Asset, cacheAsset?: boolean) { +export function cache (id: string, asset: Asset, cacheAsset?: boolean): void { if (!asset) { return; } cacheAsset = cacheAsset !== undefined ? cacheAsset : cclegacy.assetManager.cacheAsset; if (!isScene(asset) && cacheAsset && !asset.isDefault) { @@ -114,7 +114,7 @@ export function cache (id: string, asset: Asset, cacheAsset?: boolean) { } } -export function setProperties (uuid: string, asset: Asset, assetsMap: Record) { +export function setProperties (uuid: string, asset: Asset, assetsMap: Record): boolean { let missingAsset = false; const depends = dependMap.get(asset); if (depends) { @@ -171,7 +171,7 @@ export function setProperties (uuid: string, asset: Asset, assetsMap: Record = (item: T, done: ((err?: Error | null) => void)) => void; -export function forEach (array: T[], process: ForEachFunction, onComplete: (errs: Error[]) => void) { +export function forEach (array: T[], process: ForEachFunction, onComplete: (errs: Error[]) => void): void { let count = 0; const errs: Error[] = []; const length = array.length; if (length === 0 && onComplete) { onComplete(errs); } - const cb = (err) => { + const cb = (err): void => { if (err) { errs.push(err); } @@ -297,16 +297,16 @@ export function checkCircleReference (owner: string, uuid: string, map: Record void) | null): (p1?: any, p2?: any) => void { - return (p1, p2) => { + return (p1, p2): void => { if (!cb) { return; } const refs: Asset[] = []; if (Array.isArray(p2)) { - p2.forEach((x) => x instanceof Asset && refs.push(x.addRef())); + p2.forEach((x): number | boolean => x instanceof Asset && refs.push(x.addRef())); } else if (p2 instanceof Asset) { refs.push(p2.addRef()); } - misc.callInNextTick(() => { - refs.forEach((x) => x.decRef(false)); + misc.callInNextTick((): void => { + refs.forEach((x): Asset => x.decRef(false)); cb(p1, p2); }); }; diff --git a/cocos/asset/assets/asset.ts b/cocos/asset/assets/asset.ts index 97e93cb6488..364d736be30 100644 --- a/cocos/asset/assets/asset.ts +++ b/cocos/asset/assets/asset.ts @@ -60,7 +60,7 @@ export class Asset extends Eventify(CCObject) { * @param {String} data * @return {Asset} */ - public static deserialize (data) { + public static deserialize (data): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return cclegacy.deserialize(data); } @@ -129,7 +129,7 @@ export class Asset extends Eventify(CCObject) { * 返回该资源对应的目标平台资源的 URL,如果此资源没有原生依赖将返回一个空字符串。 * @readOnly */ - get nativeUrl () { + get nativeUrl (): string { if (!this._nativeUrl) { if (!this._native) return ''; const name = this._native; @@ -156,7 +156,7 @@ export class Asset extends Eventify(CCObject) { * @zh * 资源的 UUID。 */ - get uuid () { + get uuid (): string { return this._uuid; } @@ -164,7 +164,7 @@ export class Asset extends Eventify(CCObject) { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future, please use `nativeAsset` instead. */ @property - get _nativeAsset () { + get _nativeAsset (): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this._file; } @@ -181,7 +181,7 @@ export class Asset extends Eventify(CCObject) { * 此资源的基础资源(如果有)。 此属性可用于访问与资源相关的其他详细信息或功能。
* 如果`_native`可用,则此属性将由加载器初始化。 */ - public get nativeAsset () { + public get nativeAsset (): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this._file; } @@ -225,7 +225,7 @@ export class Asset extends Eventify(CCObject) { * @method toString * @returns @en String representation of this asset. @zh 此资源的字符串表示。 */ - public toString () { + public toString (): string { return this.nativeUrl; } @@ -237,7 +237,7 @@ export class Asset extends Eventify(CCObject) { * @returns {String} * @private */ - public serialize () { } + public serialize (): void { } /** * @en @@ -250,7 +250,7 @@ export class Asset extends Eventify(CCObject) { * @param inLibrary * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _setRawAsset (filename: string, inLibrary = true) { + public _setRawAsset (filename: string, inLibrary = true): void { if (inLibrary !== false) { this._native = filename || ''; } else { @@ -279,7 +279,11 @@ export class Asset extends Eventify(CCObject) { * * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ - public get _nativeDep () { + public get _nativeDep (): { + __isNative__: boolean; + uuid: string; + ext: string; + } | undefined { if (this._native) { return { __isNative__: true, uuid: this._uuid, ext: this._native }; } @@ -342,7 +346,7 @@ export class Asset extends Eventify(CCObject) { * * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ - public onLoaded () {} + public onLoaded (): void {} /** * @en @@ -353,7 +357,7 @@ export class Asset extends Eventify(CCObject) { * * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { if (uuid) { this._uuid = uuid; } this.isDefault = true; } @@ -379,7 +383,7 @@ export class Asset extends Eventify(CCObject) { * @zh * 销毁此资源以及其内部数据。 */ - public destroy () { + public destroy (): boolean { debug(getError(12101, this._uuid)); return super.destroy(); } diff --git a/cocos/asset/assets/buffer-asset.ts b/cocos/asset/assets/buffer-asset.ts index c22ac469ba8..f091bfa8391 100644 --- a/cocos/asset/assets/buffer-asset.ts +++ b/cocos/asset/assets/buffer-asset.ts @@ -41,7 +41,7 @@ export class BufferAsset extends Asset { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override - get _nativeAsset () { + get _nativeAsset (): ArrayBuffer | ArrayBufferView { return this._buffer as ArrayBuffer; } set _nativeAsset (bin: ArrayBufferView | ArrayBuffer) { @@ -57,12 +57,12 @@ export class BufferAsset extends Asset { * @en Get the ArrayBuffer data of this asset. * @returns @en The ArrayBuffer. @zh 缓冲数据。 */ - public buffer () { + public buffer (): ArrayBuffer { assertIsNonNullable(this._buffer); return this._buffer; } - public validate () { + public validate (): boolean { return !!this._buffer; } } diff --git a/cocos/asset/assets/deprecation.ts b/cocos/asset/assets/deprecation.ts index ddb08d1e201..5ddcb843a59 100644 --- a/cocos/asset/assets/deprecation.ts +++ b/cocos/asset/assets/deprecation.ts @@ -25,6 +25,7 @@ import { removeProperty, replaceProperty } from '../../core'; import { TextureBase } from './texture-base'; import { RenderTexture } from './render-texture'; +import type { RenderWindow } from '../../render-scene/core/render-window'; removeProperty(TextureBase.prototype, 'TextureBase.prototype', [ { @@ -41,7 +42,7 @@ removeProperty(TextureBase.prototype, 'TextureBase.prototype', [ replaceProperty(RenderTexture.prototype, 'RenderTexture.prototype', [ { name: 'getGFXWindow', - customFunction (this: RenderTexture) { + customFunction (this: RenderTexture): RenderWindow | null { return this.window; }, }, diff --git a/cocos/asset/assets/effect-asset.ts b/cocos/asset/assets/effect-asset.ts index dd2f2860ce5..94f95d9ddf9 100644 --- a/cocos/asset/assets/effect-asset.ts +++ b/cocos/asset/assets/effect-asset.ts @@ -26,7 +26,7 @@ import { ccclass, serializable, editable, editorOnly } from 'cc.decorator'; import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { Root } from '../../root'; import { BlendState, DepthStencilState, RasterizerState, - DynamicStateFlags, PrimitiveMode, ShaderStageFlags, Type, Uniform, MemoryAccess, Format, deviceManager, ShaderInfo } from '../../gfx'; + DynamicStateFlags, PrimitiveMode, ShaderStageFlags, Type, Uniform, MemoryAccess, Format, deviceManager, ShaderInfo, Shader } from '../../gfx'; import { RenderPassStage } from '../../rendering/define'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { programLib } from '../../render-scene/core/program-lib'; @@ -221,7 +221,7 @@ export class EffectAsset extends Asset { * * @param asset @en The effect asset to be registered. @zh 待注册的 effect asset。 */ - public static register (asset: EffectAsset) { + public static register (asset: EffectAsset): void { EffectAsset._effects[asset.name] = asset; EffectAsset._layoutValid = false; } @@ -232,7 +232,7 @@ export class EffectAsset extends Asset { * * @param asset - @en The effect asset to be removed. @zh 待移除的 effect asset。 */ - public static remove (asset: EffectAsset | string) { + public static remove (asset: EffectAsset | string): void { if (typeof asset !== 'string') { if (EffectAsset._effects[asset.name] && EffectAsset._effects[asset.name] === asset) { delete EffectAsset._effects[asset.name]; @@ -255,7 +255,7 @@ export class EffectAsset extends Asset { * @param name - @en The name of effect you want to get. @zh 想要获取的 effect 的名字。 * @returns @en The effect. @zh 你查询的 effect. */ - public static get (name: string) { + public static get (name: string): EffectAsset | null { if (EffectAsset._effects[name]) { return EffectAsset._effects[name]; } for (const n in EffectAsset._effects) { if (EffectAsset._effects[n]._uuid === name) { @@ -273,7 +273,7 @@ export class EffectAsset extends Asset { * @zh 获取所有已注册的 effect 资源。 * @returns @en All registered effects. @zh 所有已注册的 effect 资源。 */ - public static getAll () { return EffectAsset._effects; } + public static getAll (): Record { return EffectAsset._effects; } /** * @engineInternal @@ -329,7 +329,7 @@ export class EffectAsset extends Asset { * @en The loaded callback which should be invoked by the [[AssetManager]], will automatically register the effect. * @zh 通过 [[AssetManager]] 加载完成时的回调,将自动注册 effect 资源。 */ - public onLoaded () { + public onLoaded (): void { if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { addEffectDefaultProperties(this); (cclegacy.rendering.programLib as ProgramLibrary).addEffect(this); @@ -343,7 +343,7 @@ export class EffectAsset extends Asset { /** * @engineInternal */ - protected _precompile () { + protected _precompile (): void { if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { (cclegacy.rendering.programLib as ProgramLibrary).precompileEffect(deviceManager.gfxDevice, this); return; @@ -357,17 +357,17 @@ export class EffectAsset extends Asset { } const defines = getCombinationDefines(combination); defines.forEach( - (defines) => programLib.getGFXShader(deviceManager.gfxDevice, shader.name, defines, root.pipeline), + (defines): Shader => programLib.getGFXShader(deviceManager.gfxDevice, shader.name, defines, root.pipeline), ); } } - public destroy () { + public destroy (): boolean { EffectAsset.remove(this); return super.destroy(); } - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); const effect = EffectAsset.get('builtin-unlit'); this.name = 'builtin-unlit'; @@ -376,7 +376,7 @@ export class EffectAsset extends Asset { this.techniques = effect!.techniques; } - public validate () { + public validate (): boolean { return this.techniques.length > 0 && this.shaders.length > 0; } } diff --git a/cocos/asset/assets/image-asset.ts b/cocos/asset/assets/image-asset.ts index 77fb065f482..980446ab10a 100644 --- a/cocos/asset/assets/image-asset.ts +++ b/cocos/asset/assets/image-asset.ts @@ -94,7 +94,7 @@ const ASTC_HEADER_SIZE_X_BEGIN = 7; const ASTC_HEADER_SIZE_Y_BEGIN = 10; const ASTC_HEADER_SIZE_Z_BEGIN = 13; -function getASTCFormat (xdim, ydim) { +function getASTCFormat (xdim, ydim): PixelFormat { if (xdim === 4) { return PixelFormat.RGBA_ASTC_4x4; } if (xdim === 5) { @@ -130,7 +130,7 @@ function getASTCFormat (xdim, ydim) { return PixelFormat.RGBA_ASTC_12x12; } -function readBEUint16 (header, offset: number) { +function readBEUint16 (header, offset: number): number { return (header[offset] << 8) | header[offset + 1]; } @@ -157,7 +157,7 @@ function isImageBitmap (imageSource: any): imageSource is ImageBitmap { return !!(sys.hasFeature(sys.Feature.IMAGE_BITMAP) && imageSource instanceof ImageBitmap); } -function fetchImageSource (imageSource: ImageSource) { +function fetchImageSource (imageSource: ImageSource): HTMLCanvasElement | HTMLImageElement | ImageBitmap | ArrayBufferView | null { return '_data' in imageSource ? imageSource._data : imageSource; } @@ -205,7 +205,7 @@ export class ImageAsset extends Asset { * @param files @zh 压缩纹理数组。 @en Compressed Texture Arrays. * @returns out @zh 合并后的压缩纹理数据。 @en Merged compressed texture data. */ - public static mergeCompressedTextureMips (files: ArrayBuffer[] | ArrayBufferView[]) { + public static mergeCompressedTextureMips (files: ArrayBuffer[] | ArrayBufferView[]): Uint8Array { let out = new Uint8Array(0); let err: Error | null = null; @@ -257,7 +257,7 @@ export class ImageAsset extends Asset { * @param type 压缩纹理类型。 * @engineInternal */ - public static parseCompressedTextures (file: ArrayBuffer | ArrayBufferView, type: number) { + public static parseCompressedTextures (file: ArrayBuffer | ArrayBufferView, type: number): IMemoryImageSource { const out: IMemoryImageSource = { _data: new Uint8Array(0), _compressed: true, @@ -306,7 +306,7 @@ export class ImageAsset extends Asset { * @engineInternal */ public static parseCompressedTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, - beginOffset: number, endOffset: number, type: number, out: IMemoryImageSource) { + beginOffset: number, endOffset: number, type: number, out: IMemoryImageSource): void { switch (type) { case compressType.PVR: ImageAsset.parsePVRTexture(file, levelIndex, beginOffset, endOffset, out); @@ -332,7 +332,7 @@ export class ImageAsset extends Asset { * @engineInternal */ public static parsePVRTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, - beginOffset: number, endOffset: number, out: IMemoryImageSource) { + beginOffset: number, endOffset: number, out: IMemoryImageSource): void { const buffer = file instanceof ArrayBuffer ? file : file.buffer; // Get a view of the arrayBuffer that represents the DDS header. const header = new Int32Array(buffer, beginOffset, PVR_HEADER_LENGTH); @@ -384,7 +384,7 @@ export class ImageAsset extends Asset { * @engineInternal */ public static parsePKMTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, - beginOffset: number, endOffset: number, out: IMemoryImageSource) { + beginOffset: number, endOffset: number, out: IMemoryImageSource): void { const buffer = file instanceof ArrayBuffer ? file : file.buffer; const header = new Uint8Array(buffer, beginOffset, ETC_PKM_HEADER_LENGTH); const format = readBEUint16(header, ETC_PKM_FORMAT_OFFSET); @@ -418,7 +418,7 @@ export class ImageAsset extends Asset { * @engineInternal */ public static parseASTCTexture (file: ArrayBuffer | ArrayBufferView, levelIndex: number, - beginOffset: number, endOffset: number, out: IMemoryImageSource) { + beginOffset: number, endOffset: number, out: IMemoryImageSource): void { const buffer = file instanceof ArrayBuffer ? file : file.buffer; const header = new Uint8Array(buffer, beginOffset, ASTC_HEADER_LENGTH); @@ -521,7 +521,7 @@ export class ImageAsset extends Asset { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override - get _nativeAsset () { + get _nativeAsset (): any { // Maybe returned to pool in webgl. return this._nativeData; } @@ -538,7 +538,7 @@ export class ImageAsset extends Asset { * @en Image data. * @zh 此图像资源的图像数据。 */ - get data () { + get data (): ArrayBufferView | HTMLCanvasElement | HTMLImageElement | ImageBitmap | null { if (isNativeImage(this._nativeData)) { return this._nativeData; } @@ -550,7 +550,7 @@ export class ImageAsset extends Asset { * @en The pixel width of the image. * @zh 此图像资源的像素宽度。 */ - get width () { + get width (): number { return this._nativeData.width || this._width; } @@ -558,7 +558,7 @@ export class ImageAsset extends Asset { * @en The pixel height of the image. * @zh 此图像资源的像素高度。 */ - get height () { + get height (): number { return this._nativeData.height || this._height; } @@ -566,7 +566,7 @@ export class ImageAsset extends Asset { * @en The pixel format of the image. * @zh 此图像资源的像素格式。 */ - get format () { + get format (): PixelFormat { return this._format; } @@ -574,7 +574,7 @@ export class ImageAsset extends Asset { * @en Whether the image is in compressed texture format. * @zh 此图像资源是否为压缩像素格式。 */ - get isCompressed () { + get isCompressed (): boolean { return (this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12) || (this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1); } @@ -593,7 +593,7 @@ export class ImageAsset extends Asset { * @zh 此图像资源的原始图像源的 URL。当原始图像元不是 HTML 文件时可能为空。 * @deprecated Please use [[nativeUrl]] */ - get url () { + get url (): string { return this.nativeUrl; } @@ -635,7 +635,7 @@ export class ImageAsset extends Asset { * @zh 重置此图像资源使用的原始图像源。 * @param data @en The new source. @zh 新的图片数据源。 */ - public reset (data: ImageSource) { + public reset (data: ImageSource): void { if (isImageBitmap(data)) { this._nativeData = data; } else if (!(data instanceof HTMLElement)) { @@ -647,7 +647,7 @@ export class ImageAsset extends Asset { } } - public destroy () { + public destroy (): boolean { if (this.data && this.data instanceof HTMLImageElement) { this.data.src = ''; this._setRawAsset(''); @@ -668,7 +668,11 @@ export class ImageAsset extends Asset { * @engineInternal */ // eslint-disable-next-line consistent-return - public _serialize () { + public _serialize (): string | { + fmt: string; + w: number; + h: number; + } | undefined { if (EDITOR || TEST) { let targetExtensions = this._exportedExts; if (!targetExtensions && this._native) { @@ -696,7 +700,7 @@ export class ImageAsset extends Asset { /** * @engineInternal */ - public _deserialize (data: any) { + public _deserialize (data: any): void { let fmtStr = ''; if (typeof data === 'string') { fmtStr = data; @@ -751,7 +755,7 @@ export class ImageAsset extends Asset { private static _sharedPlaceHolderCanvas: HTMLCanvasElement | null = null; - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); if (!ImageAsset._sharedPlaceHolderCanvas) { const canvas = ccwindow.document.createElement('canvas'); @@ -766,7 +770,7 @@ export class ImageAsset extends Asset { } } - public validate () { + public validate (): boolean { return !!this.data; } } diff --git a/cocos/asset/assets/material.ts b/cocos/asset/assets/material.ts index af61de7d5ac..8bdd53715ba 100644 --- a/cocos/asset/assets/material.ts +++ b/cocos/asset/assets/material.ts @@ -90,7 +90,7 @@ export class Material extends Asset { * @zh 获取一个材质的哈希值 * @param material */ - public static getHash (material: Material) { + public static getHash (material: Material): number { let hash = 0; for (const pass of material.passes) { hash ^= pass.hash; @@ -146,7 +146,7 @@ export class Material extends Asset { * @en The current [[EffectAsset]]. * @zh 当前使用的 [[EffectAsset]] 资源。 */ - get effectAsset () { + get effectAsset (): EffectAsset | null { return this._effectAsset; } @@ -154,7 +154,7 @@ export class Material extends Asset { * @en Name of the current [[EffectAsset]]. * @zh 当前使用的 [[EffectAsset]] 资源名。 */ - get effectName () { + get effectName (): string { return this._effectAsset ? this._effectAsset.name : ''; } @@ -162,7 +162,7 @@ export class Material extends Asset { * @en The current technique index. * @zh 当前的 technique 索引。 */ - get technique () { + get technique (): number { return this._techIdx; } @@ -170,7 +170,7 @@ export class Material extends Asset { * @en The passes defined in this material. * @zh 当前正在使用的 pass 数组。 */ - get passes () { + get passes (): Pass[] { return this._passes; } @@ -178,7 +178,7 @@ export class Material extends Asset { * @en The hash value of this material. * @zh 材质的 hash。 */ - get hash () { + get hash (): number { return this._hash; } @@ -203,7 +203,7 @@ export class Material extends Asset { * @zh 根据所给信息初始化这个材质,初始化正常结束后材质即可立即用于渲染。 * @param info @en Material description info. @zh 材质描述信息 */ - public initialize (info: IMaterialInfo) { + public initialize (info: IMaterialInfo): void { if (this._passes.length) { warnID(12005); return; @@ -222,7 +222,7 @@ export class Material extends Asset { * * @param info @en Material description info. @zh 材质描述信息。 */ - public reset (info: IMaterialInfo) { // to be consistent with other assets + public reset (info: IMaterialInfo): void { // to be consistent with other assets this.initialize(info); } @@ -238,7 +238,7 @@ export class Material extends Asset { * 如需修改现有材质,请创建一个新材质,
* 调用 copy 函数传入需要的 overrides 并赋给目标组件。 */ - public destroy () { + public destroy (): boolean { this._doDestroy(); return super.destroy(); } @@ -249,7 +249,7 @@ export class Material extends Asset { * @param overrides @en The shader macro override values. @zh 宏的覆盖值,用于编译不同 Shader 变体。 * @param passIdx @en The pass to apply to. Will apply to all passes if not specified. @zh 要重编的 pass 索引,如果没有指定,则重编所有 pass。 */ - public recompileShaders (overrides: MacroRecord, passIdx?: number) { + public recompileShaders (overrides: MacroRecord, passIdx?: number): void { console.warn(`Shaders in material asset '${this.name}' cannot be modified at runtime, please instantiate the material first.`); } @@ -259,7 +259,7 @@ export class Material extends Asset { * @param overrides The pipeline state override values. * @param passIdx The pass to apply to. Will apply to all passes if not specified. */ - public overridePipelineStates (overrides: PassOverrides, passIdx?: number) { + public overridePipelineStates (overrides: PassOverrides, passIdx?: number): void { console.warn(`Pipeline states in material asset '${this.name}' cannot be modified at runtime, please instantiate the material first.`); } @@ -267,7 +267,7 @@ export class Material extends Asset { * @en Callback function after material is loaded in [[AssetManager]]. Initialize the resources automatically. * @zh 通过 [[AssetManager]] 加载完成时的回调,将自动初始化材质资源。 */ - public onLoaded () { + public onLoaded (): void { this._update(); } @@ -276,7 +276,7 @@ export class Material extends Asset { * @zh 重置材质的所有 uniform 参数数据为 [[EffectAsset]] 中的默认初始值。 * @param clearPasses @en Whether to clear the rendering data too. @zh 是否同时清空渲染数据。 */ - public resetUniforms (clearPasses = true) { + public resetUniforms (clearPasses = true): void { this._props.length = this._passes.length; for (let i = 0; i < this._props.length; i++) { this._props[i] = {}; } if (!clearPasses) { return; } @@ -299,7 +299,7 @@ export class Material extends Asset { * @en The pass to apply to. Will apply to all passes if not specified. * @zh 设置此属性的 pass 索引,如果没有指定,则会设置此属性到所有 pass 上。 */ - public setProperty (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number) { + public setProperty (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number): void { let success = false; if (passIdx === undefined) { // try set property for all applicable passes const passes = this._passes; @@ -361,7 +361,7 @@ export class Material extends Asset { * @param mat @en The material to be copied. @zh 需要拷贝的原始材质。 * @param overrides @en The overriding states on top of the original material. @zh 需要在原始材质上覆盖的状态。 */ - public copy (mat: Material, overrides?: IMaterialInfo) { + public copy (mat: Material, overrides?: IMaterialInfo): void { this._techIdx = mat._techIdx; this._props.length = mat._props.length; for (let i = 0; i < mat._props.length; i++) { @@ -383,7 +383,7 @@ export class Material extends Asset { /** * @engineInternal */ - protected _fillInfo (info: IMaterialInfo) { + protected _fillInfo (info: IMaterialInfo): void { if (info.technique !== undefined) { this._techIdx = info.technique; } if (info.effectAsset) { this._effectAsset = info.effectAsset; @@ -397,7 +397,7 @@ export class Material extends Asset { /** * @engineInternal */ - protected _prepareInfo (patch: Record | Record[], cur: Record[]) { + protected _prepareInfo (patch: Record | Record[], cur: Record[]): void { 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; @@ -411,7 +411,7 @@ export class Material extends Asset { /** * @engineInternal */ - protected _createPasses () { + protected _createPasses (): Pass[] { const tech = this._effectAsset!.techniques[this._techIdx || 0]; if (!tech) { return []; } const passNum = tech.passes.length; @@ -438,14 +438,14 @@ export class Material extends Asset { /** * @engineInternal */ - protected _update (keepProps = true) { + protected _update (keepProps = true): void { if (this._effectAsset) { this._passes = this._createPasses(); // handle property values const totalPasses = this._effectAsset.techniques[this._techIdx].passes.length; this._props.length = totalPasses; if (keepProps) { - this._passes.forEach((pass, i) => { + this._passes.forEach((pass, i): void => { let props = this._props[i]; if (!props) { props = this._props[i] = {}; } if (pass.propertyIndex !== undefined) { @@ -465,7 +465,7 @@ export class Material extends Asset { /** * @engineInternal */ - protected _uploadProperty (pass: Pass, name: string, val: MaterialPropertyFull | MaterialPropertyFull[]) { + protected _uploadProperty (pass: Pass, name: string, val: MaterialPropertyFull | MaterialPropertyFull[]): boolean { const handle = pass.getHandle(name); if (!handle) { return false; } const type = Pass.getTypeFromHandle(handle); @@ -498,7 +498,7 @@ export class Material extends Asset { /** * @engineInternal */ - protected _bindTexture (pass: Pass, handle: number, val: MaterialPropertyFull, index?: number) { + protected _bindTexture (pass: Pass, handle: number, val: MaterialPropertyFull, index?: number): void { const binding = Pass.getBindingFromHandle(handle); if (val instanceof Texture) { pass.bindTexture(binding, val, index); @@ -516,7 +516,7 @@ export class Material extends Asset { /** * @engineInternal */ - protected _doDestroy () { + protected _doDestroy (): void { if (this._passes && this._passes.length) { for (const pass of this._passes) { pass.destroy(); @@ -525,7 +525,7 @@ export class Material extends Asset { this._passes.length = 0; } - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); this.initialize({ effectName: 'builtin-unlit', @@ -535,7 +535,7 @@ export class Material extends Asset { this.setProperty('mainColor', new Color('#ff00ff')); } - public validate () { + public validate (): boolean { return !!this._effectAsset && !this._effectAsset.isDefault && this.passes.length > 0; } } diff --git a/cocos/asset/assets/render-texture.ts b/cocos/asset/assets/render-texture.ts index 9ca06bf965f..96fa07d314f 100644 --- a/cocos/asset/assets/render-texture.ts +++ b/cocos/asset/assets/render-texture.ts @@ -66,7 +66,7 @@ export class RenderTexture extends TextureBase { * @en The render window for the render pipeline, it's created internally and cannot be modified. * @zh 渲染管线所使用的渲染窗口,内部逻辑创建,无法被修改。 */ - get window () { + get window (): RenderWindow | null { return this._window; } @@ -75,7 +75,7 @@ export class RenderTexture extends TextureBase { * @zh 初始化渲染贴图。设置渲染贴图的名称、尺寸、渲染通道信息。 * @param info @en The create info of render texture. @zh 渲染贴图的创建信息。 */ - public initialize (info: IRenderTextureCreateInfo) { + public initialize (info: IRenderTextureCreateInfo): void { this._name = info.name || ''; this._width = info.width; this._height = info.height; @@ -87,7 +87,7 @@ export class RenderTexture extends TextureBase { * @zh 重新初始化渲染贴图。用户可以更改渲染贴图的名称、尺寸、渲染通道信息。 * @param info @en The create info of render texture. @zh 渲染贴图的创建信息。 */ - public reset (info: IRenderTextureCreateInfo) { // to be consistent with other assets + public reset (info: IRenderTextureCreateInfo): void { // to be consistent with other assets this.initialize(info); } @@ -95,7 +95,7 @@ export class RenderTexture extends TextureBase { * @en Destroy the render texture. * @zh 销毁渲染贴图。 */ - public destroy () { + public destroy (): boolean { if (this._window) { const root = cclegacy.director.root as Root; root?.destroyWindow(this._window); @@ -111,7 +111,7 @@ export class RenderTexture extends TextureBase { * @param width @en The pixel width to resize to, the range is from 1 to 2048. @zh 需要调整到的像素宽度,范围为 1-2048。 * @param height @en The pixel height to resize to, the range is from 1 to 2048. @zh 需要调整到的像素高度,范围为 1-2048。 */ - public resize (width: number, height: number) { + public resize (width: number, height: number): void { this._width = Math.floor(clamp(width, 1, 2048)); this._height = Math.floor(clamp(height, 1, 2048)); if (this._window) { @@ -133,7 +133,7 @@ export class RenderTexture extends TextureBase { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _deserialize (serializedData: any, handle: any) { + public _deserialize (serializedData: any, handle: any): void { const data = serializedData; this._width = data.w; this._height = data.h; @@ -155,7 +155,7 @@ export class RenderTexture extends TextureBase { * @en Callback function after render texture is loaded in [[AssetManager]]. Initialize the render texture. * @zh 通过 [[AssetManager]] 加载完成时的回调,初始化渲染贴图。 */ - public onLoaded () { + public onLoaded (): void { this._initWindow(); } @@ -165,7 +165,7 @@ export class RenderTexture extends TextureBase { * @param info @en The create info of render texture. @zh 渲染贴图的创建信息。 * @engineInternal */ - protected _initWindow (info?: IRenderTextureCreateInfo) { + protected _initWindow (info?: IRenderTextureCreateInfo): void { const root = cclegacy.director.root as Root; _windowInfo.title = this._name; @@ -195,7 +195,7 @@ export class RenderTexture extends TextureBase { * @param uuid @en asset uuid. @zh 资源 uuid。 * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); this._width = this._height = 1; this._initWindow(); @@ -206,7 +206,7 @@ export class RenderTexture extends TextureBase { * @zh 验证渲染贴图的正确性。 * @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances. */ - public validate () { + public validate (): boolean { return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048; } diff --git a/cocos/asset/assets/rendering-sub-mesh.ts b/cocos/asset/assets/rendering-sub-mesh.ts index d0aec9626b4..a648dc6a3ea 100644 --- a/cocos/asset/assets/rendering-sub-mesh.ts +++ b/cocos/asset/assets/rendering-sub-mesh.ts @@ -152,31 +152,31 @@ export class RenderingSubMesh { * @en All vertex attributes used by the sub mesh. * @zh 所有顶点属性。 */ - get attributes () { return this._attributes; } + get attributes (): Attribute[] { return this._attributes; } /** * @en All vertex buffers used by the sub mesh. * @zh 使用的所有顶点缓冲区。 */ - get vertexBuffers () { return this._vertexBuffers; } + get vertexBuffers (): Buffer[] { return this._vertexBuffers; } /** * @en Index buffer used by the sub mesh. * @zh 使用的索引缓冲区,若未使用则无需指定。 */ - get indexBuffer () { return this._indexBuffer; } + get indexBuffer (): Buffer | null { return this._indexBuffer; } /** * @en Indirect buffer used by the sub mesh. * @zh 间接绘制缓冲区。 */ - get indirectBuffer () { return this._indirectBuffer; } + get indirectBuffer (): Buffer | null { return this._indirectBuffer; } /** * @en Primitive mode used by the sub mesh. * @zh 图元类型。 */ - get primitiveMode () { return this._primitiveMode; } + get primitiveMode (): PrimitiveMode { return this._primitiveMode; } /** * @en The geometric info of the sub mesh, used for raycast. @@ -197,7 +197,7 @@ export class RenderingSubMesh { 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): boolean => element.name === AttributeName.ATTR_POSITION); if (pAttri) { const conut = FormatInfos[pAttri.format].count; if (conut === 2) { @@ -231,7 +231,7 @@ export class RenderingSubMesh { * @en Invalidate the geometric info of the sub mesh after geometry changed. * @zh 网格更新后,设置(用于射线检测的)几何信息为无效,需要重新计算。 */ - public invalidateGeometricInfo () { this._geometricInfo = undefined; } + public invalidateGeometricInfo (): void { this._geometricInfo = undefined; } /** * @en the draw range. @@ -249,13 +249,13 @@ export class RenderingSubMesh { * @en Flatted vertex buffers. * @zh 扁平化的顶点缓冲区。 */ - get flatBuffers () { return this._flatBuffers; } + get flatBuffers (): IFlatBuffer[] { return this._flatBuffers; } /** * @en generate flatted vertex buffers. * @zh 生成扁平化的顶点缓冲区。 */ - public genFlatBuffers () { + public genFlatBuffers (): void { if (this._flatBuffers.length || !this.mesh || this.subMeshIdx === undefined) { return; } const { mesh } = this; @@ -295,7 +295,7 @@ export class RenderingSubMesh { * @en The vertex buffer for joint after mapping. * @zh 骨骼索引按映射表处理后的顶点缓冲。 */ - get jointMappedBuffers () { + get jointMappedBuffers (): Buffer[] { if (this._jointMappedBuffers) { return this._jointMappedBuffers; } const buffers: Buffer[] = this._jointMappedBuffers = []; const indices: number[] = this._jointMappedBufferIndices = []; @@ -324,7 +324,7 @@ export class RenderingSubMesh { const data = new Uint8Array(this.mesh.data.buffer, bundle.view.offset, bundle.view.length); const dataView = new DataView(data.slice().buffer); const idxMap = struct.jointMaps[prim.jointMapIndex]; - mapBuffer(dataView, (cur) => idxMap.indexOf(cur), jointFormat, jointOffset, + mapBuffer(dataView, (cur): number => idxMap.indexOf(cur), jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView); const buffer = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, @@ -347,13 +347,13 @@ export class RenderingSubMesh { * @en The input assembler info. * @zh 输入汇集器信息。 */ - get iaInfo () { return this._iaInfo; } + get iaInfo (): InputAssemblerInfo { return this._iaInfo; } /** * @en Destroys sub mesh. * @zh 销毁子网格。 */ - public destroy () { + public destroy (): void { for (let i = 0; i < this.vertexBuffers.length; i++) { this.vertexBuffers[i].destroy(); } @@ -386,7 +386,7 @@ export class RenderingSubMesh { * 一旦你调用此函数, 顶点属性永久被添加, 后续调用无效果。 * @param device @en Device used to create related rendering resources @zh 用于创建相关渲染资源的设备对象 */ - public enableVertexIdChannel (device: Device) { + public enableVertexIdChannel (device: Device): void { if (this._vertexIdChannel) { return; } @@ -407,7 +407,7 @@ export class RenderingSubMesh { }; } - private _allocVertexIdBuffer (device: Device) { + private _allocVertexIdBuffer (device: Device): Buffer { 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. diff --git a/cocos/asset/assets/scene-asset.ts b/cocos/asset/assets/scene-asset.ts index 967f4a57100..183d1723e3f 100644 --- a/cocos/asset/assets/scene-asset.ts +++ b/cocos/asset/assets/scene-asset.ts @@ -43,12 +43,12 @@ export class SceneAsset extends Asset { @serializable public scene: Scene | null = null; - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); this.scene = new Scene('New Scene'); } - public validate () { + public validate (): boolean { return !!this.scene; } } diff --git a/cocos/asset/assets/simple-texture.ts b/cocos/asset/assets/simple-texture.ts index dfef7d0295f..9d902b38896 100644 --- a/cocos/asset/assets/simple-texture.ts +++ b/cocos/asset/assets/simple-texture.ts @@ -36,15 +36,15 @@ const _regions: BufferTextureCopy[] = [new BufferTextureCopy()]; export type PresumedGFXTextureInfo = Pick; export type PresumedGFXTextureViewInfo = Pick; -function getMipLevel (width: number, height: number) { +function getMipLevel (width: number, height: number): number { let size = Math.max(width, height); let level = 0; while (size) { size >>= 1; level++; } return level; } -function isPOT (n: number) { return n && (n & (n - 1)) === 0; } -function canGenerateMipmap (device: Device, w: number, h: number) { +function isPOT (n: number): boolean | 0 { return n && (n & (n - 1)) === 0; } +function canGenerateMipmap (device: Device, w: number, h: number): boolean | 0 { const needCheckPOT = device.gfxAPI === API.WEBGL; if (needCheckPOT) { return isPOT(w) && isPOT(h); } return true; @@ -85,7 +85,7 @@ export class SimpleTexture extends TextureBase { * @en The mipmap level of the texture. * @zh 贴图中的 Mipmap 层级数量。 */ - get mipmapLevel () { + get mipmapLevel (): number { return this._mipmapLevel; } @@ -94,11 +94,11 @@ export class SimpleTexture extends TextureBase { * @zh 获取此贴图底层的 GFX 贴图对象。 * @return @en The low level gfx texture. @zh 底层的 GFX 贴图。 */ - public getGFXTexture () { + public getGFXTexture (): Texture | null { return this._gfxTextureView; } - public destroy () { + public destroy (): boolean { this._tryDestroyTextureView(); this._tryDestroyTexture(); return super.destroy(); @@ -108,7 +108,7 @@ export class SimpleTexture extends TextureBase { * @en Update the level 0 mipmap image. * @zh 更新 0 级 Mipmap。 */ - public updateImage () { + public updateImage (): void { this.updateMipmaps(0); } @@ -119,7 +119,7 @@ export class SimpleTexture extends TextureBase { * @param firstLevel @en First level to be updated. @zh 更新指定层的 mipmap。 * @param count @en Mipmap level count to be updated。 @zh 指定要更新层的数量。 */ - public updateMipmaps (firstLevel = 0, count?: number) { + public updateMipmaps (firstLevel = 0, count?: number): void { } @@ -140,7 +140,7 @@ export class SimpleTexture extends TextureBase { * @param level @en Mipmap level to upload the image to. @zh 要上传的 mipmap 层级。 * @param arrayIndex @en The array index. @zh 要上传的数组索引。 */ - public uploadData (source: HTMLCanvasElement | HTMLImageElement | ArrayBufferView | ImageBitmap, level = 0, arrayIndex = 0) { + public uploadData (source: HTMLCanvasElement | HTMLImageElement | ArrayBufferView | ImageBitmap, level = 0, arrayIndex = 0): void { if (!this._gfxTexture || this._mipmapLevel <= level) { return; } @@ -175,7 +175,7 @@ export class SimpleTexture extends TextureBase { /** * @engineInternal */ - protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) { + protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number): void { const data = image.data; if (!data) { return; @@ -196,14 +196,14 @@ export class SimpleTexture extends TextureBase { /** * @engineInternal */ - protected _checkTextureLoaded () { + protected _checkTextureLoaded (): void { this._textureReady(); } /** * @engineInternal */ - protected _textureReady () { + protected _textureReady (): void { this.loaded = true; this.emit('load'); } @@ -218,14 +218,14 @@ export class SimpleTexture extends TextureBase { * @engineInternal * */ - protected _setMipmapLevel (value: number) { + protected _setMipmapLevel (value: number): void { this._mipmapLevel = value < 1 ? 1 : value; } /** * @engineInternal */ - protected _setMipRange (baseLevel: number, maxLevel: number) { + protected _setMipRange (baseLevel: number, maxLevel: number): void { this._baseLevel = baseLevel < 1 ? 0 : baseLevel; this._maxLevel = maxLevel < 1 ? 0 : maxLevel; } @@ -236,7 +236,7 @@ export class SimpleTexture extends TextureBase { * @param baseLevel @en The base mipmap level. @zh 最低 mipmap 等级。 * @param maxLevel @en The maximum mipmap level. @zh 最高 mipmap 等级。 */ - public setMipRange (baseLevel: number, maxLevel: number) { + public setMipRange (baseLevel: number, maxLevel: number): void { assertID(baseLevel <= maxLevel, 3124); this._setMipRange(baseLevel, maxLevel); @@ -275,7 +275,7 @@ export class SimpleTexture extends TextureBase { /** * @engineInternal */ - protected _tryReset () { + protected _tryReset (): void { this._tryDestroyTextureView(); this._tryDestroyTexture(); if (this._mipmapLevel === 0) { @@ -300,7 +300,7 @@ export class SimpleTexture extends TextureBase { /** * @engineInternal */ - protected _createTexture (device: Device) { + protected _createTexture (device: Device): void { if (this._width === 0 || this._height === 0) { return; } let flags = TextureFlagBit.NONE; if (this._mipFilter !== Filter.NONE && canGenerateMipmap(device, this._width, this._height)) { @@ -350,7 +350,7 @@ export class SimpleTexture extends TextureBase { /** * @engineInternal */ - protected _tryDestroyTexture () { + protected _tryDestroyTexture (): void { if (this._gfxTexture) { this._gfxTexture.destroy(); this._gfxTexture = null; @@ -360,7 +360,7 @@ export class SimpleTexture extends TextureBase { /** * @engineInternal */ - protected _tryDestroyTextureView () { + protected _tryDestroyTextureView (): void { if (this._gfxTextureView) { this._gfxTextureView.destroy(); this._gfxTextureView = null; diff --git a/cocos/asset/assets/text-asset.ts b/cocos/asset/assets/text-asset.ts index c3f1631a05a..93b5b60af3e 100644 --- a/cocos/asset/assets/text-asset.ts +++ b/cocos/asset/assets/text-asset.ts @@ -41,7 +41,7 @@ export class TextAsset extends Asset { @editable public text = ''; - public toString () { + public toString (): string { return this.text; } } diff --git a/cocos/asset/assets/texture-2d.ts b/cocos/asset/assets/texture-2d.ts index fc2fa6e7791..e795d6da063 100644 --- a/cocos/asset/assets/texture-2d.ts +++ b/cocos/asset/assets/texture-2d.ts @@ -89,7 +89,7 @@ export class Texture2D extends SimpleTexture { * @zh 所有层级 Mipmap,注意,这里不包含自动生成的 Mipmap。 * 当设置 Mipmap 时,贴图的尺寸以及像素格式可能会改变。 */ - get mipmaps () { + get mipmaps (): ImageAsset[] { return this._mipmaps; } set mipmaps (value) { @@ -114,7 +114,7 @@ export class Texture2D extends SimpleTexture { /** * TODO: See: cocos/cocos-engine#15305 */ - private _setMipmapParams (value: ImageAsset[]) { + private _setMipmapParams (value: ImageAsset[]): void { this._generatedMipmaps = value; this._setMipmapLevel(this._generatedMipmaps.length); if (this._generatedMipmaps.length > 0) { @@ -150,7 +150,7 @@ export class Texture2D extends SimpleTexture { * 注意,`this.image = img` 等价于 `this.mipmaps = [img]`, * 也就是说,通过 `this.image` 设置 0 级 Mipmap 时将隐式地清除之前的所有 Mipmap。 */ - get image () { + get image (): ImageAsset | null { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; } @@ -169,11 +169,11 @@ export class Texture2D extends SimpleTexture { /** * @engineInternal */ - public initialize () { + public initialize (): void { this.mipmaps = this._mipmaps; } - public onLoaded () { + public onLoaded (): void { this.initialize(); } @@ -184,7 +184,7 @@ export class Texture2D extends SimpleTexture { * mipmap 图像的数据不会自动更新到贴图中,你必须显式调用 [[uploadData]] 来上传贴图数据。 * @param info @en The create information. @zh 创建贴图的相关信息。 */ - public reset (info: ITexture2DCreateInfo) { + public reset (info: ITexture2DCreateInfo): void { this._width = info.width; this._height = info.height; this._setGFXFormat(info.format); @@ -209,7 +209,7 @@ export class Texture2D extends SimpleTexture { * @param maxLevel Mipmap maximum level * @deprecated since v1.0 please use [[reset]] instead */ - public create (width: number, height: number, format = PixelFormat.RGBA8888, mipmapLevel = 1, baseLevel = 0, maxLevel = 1000) { + public create (width: number, height: number, format = PixelFormat.RGBA8888, mipmapLevel = 1, baseLevel = 0, maxLevel = 1000): void { this.reset({ width, height, @@ -220,11 +220,11 @@ export class Texture2D extends SimpleTexture { }); } - public toString () { + public toString (): string { return this._mipmaps.length !== 0 ? this._mipmaps[0].url : ''; } - public updateMipmaps (firstLevel = 0, count?: number) { + public updateMipmaps (firstLevel = 0, count?: number): void { if (firstLevel >= this._generatedMipmaps.length) { return; } @@ -246,7 +246,7 @@ export class Texture2D extends SimpleTexture { * @returns @en HTMLElement or `null`. @zh HTML 元素或者 null。 * @deprecated Please use [[ImageAsset.data]] instead */ - public getHtmlElementObj () { + public getHtmlElementObj (): HTMLCanvasElement | HTMLImageElement | null { return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data : null; } @@ -254,7 +254,7 @@ export class Texture2D extends SimpleTexture { * @en Destroy the current 2d texture, clear up all mipmap levels and the related GPU resources. * @zh 销毁此贴图,清空所有 Mipmap 并释放占用的 GPU 资源。 */ - public destroy () { + public destroy (): boolean { this._mipmaps = []; this._generatedMipmaps = []; return super.destroy(); @@ -265,7 +265,7 @@ export class Texture2D extends SimpleTexture { * @zh 返回此贴图的描述。 * @returns @en The description. @zh 贴图的描述信息。 */ - public description () { + public description (): string { const url = this._mipmaps[0] ? this._mipmaps[0].url : ''; return ``; } @@ -275,14 +275,17 @@ export class Texture2D extends SimpleTexture { * @zh 释放占用的 GPU 资源。 * @deprecated please use [[destroy]] instead. */ - public releaseTexture () { + public releaseTexture (): void { this.destroy(); } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _serialize (ctxForExporting: any) { + public _serialize (ctxForExporting: any): { + base: any; + mipmaps: (string | null)[]; + } | null { if (EDITOR || TEST) { return { base: super._serialize(ctxForExporting), @@ -304,7 +307,7 @@ export class Texture2D extends SimpleTexture { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _deserialize (serializedData: any, handle: any) { + public _deserialize (serializedData: any, handle: any): void { const data = serializedData as ITexture2DSerializeData; super._deserialize(data.base, handle); @@ -323,7 +326,7 @@ export class Texture2D extends SimpleTexture { /** * @engineInternal */ - protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo) { + protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo): TextureInfo { const texInfo = new TextureInfo(TextureType.TEX2D); texInfo.width = this._width; texInfo.height = this._height; @@ -334,21 +337,21 @@ export class Texture2D extends SimpleTexture { /** * @engineInternal */ - protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo) { + protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo): TextureViewInfo { const texViewInfo = new TextureViewInfo(); texViewInfo.type = TextureType.TEX2D; Object.assign(texViewInfo, presumed); return texViewInfo; } - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); const imageAsset = new ImageAsset(); imageAsset.initDefault(); this.image = imageAsset; } - public validate () { + public validate (): boolean { return this.mipmaps && this.mipmaps.length !== 0; } } diff --git a/cocos/asset/assets/texture-base.ts b/cocos/asset/assets/texture-base.ts index f941d6a167b..d45d4be8b2c 100644 --- a/cocos/asset/assets/texture-base.ts +++ b/cocos/asset/assets/texture-base.ts @@ -160,7 +160,7 @@ export class TextureBase extends Asset { * @zh 获取标识符。 * @returns @en The id of this texture. @zh 此贴图的 id。 */ - public getId () { + public getId (): string { return this._id; } @@ -169,7 +169,7 @@ export class TextureBase extends Asset { * @zh 获取像素格式。 * @returns @en The pixel format. @zh 像素格式。 */ - public getPixelFormat () { + public getPixelFormat (): PixelFormat { return this._format; } @@ -178,7 +178,7 @@ export class TextureBase extends Asset { * @zh 获取各向异性。 * @returns @en The anisotropy. @zh 各项异性值。 */ - public getAnisotropy () { + public getAnisotropy (): number { return this._anisotropy; } @@ -191,7 +191,7 @@ export class TextureBase extends Asset { * @param wrapT @en T(V) coordinate wrap mode. @zh T(V) 坐标系缠绕模式. * @param wrapR @en R(W) coordinate wrap mode. @zh R(W) 坐标系缠绕模式. */ - public setWrapMode (wrapS: WrapMode, wrapT: WrapMode, wrapR?: WrapMode) { + public setWrapMode (wrapS: WrapMode, wrapT: WrapMode, wrapR?: WrapMode): void { if (wrapR === undefined) wrapR = wrapS; // wrap modes should be as consistent as possible for performance this._wrapS = wrapS; @@ -212,7 +212,7 @@ export class TextureBase extends Asset { * @param minFilter @en Filter mode for scale down. @zh 贴图缩小时使用的过滤模式。 * @param magFilter @en Filter mode for scale up. @zh 贴图放大时使用的过滤模式。 */ - public setFilters (minFilter: Filter, magFilter: Filter) { + public setFilters (minFilter: Filter, magFilter: Filter): void { this._minFilter = minFilter; this._samplerInfo.minFilter = minFilter as unknown as GFXFilter; this._magFilter = magFilter; @@ -228,7 +228,7 @@ export class TextureBase extends Asset { * @zh 设置此贴图的多层 mip 过滤算法。 * @param mipFilter @en Filter mode for multiple mip level. @zh 多层 mip 过滤模式。 */ - public setMipFilter (mipFilter: Filter) { + public setMipFilter (mipFilter: Filter): void { this._mipFilter = mipFilter; this._samplerInfo.mipFilter = mipFilter as unknown as GFXFilter; @@ -242,7 +242,7 @@ export class TextureBase extends Asset { * @zh 设置此贴图的各向异性。 * @param anisotropy @en The anisotropy to be set. @zh 待设置的各向异性数值。 */ - public setAnisotropy (anisotropy: number) { + public setAnisotropy (anisotropy: number): void { this._anisotropy = anisotropy; this._samplerInfo.maxAnisotropy = anisotropy; @@ -255,7 +255,7 @@ export class TextureBase extends Asset { * @en Destroy the current texture, clear up the related GPU resources. * @zh 销毁此贴图,并释放占用的 GPU 资源。 */ - public destroy () { + public destroy (): boolean { const destroyed = super.destroy(); if (destroyed && cclegacy.director.root?.batcher2D) { cclegacy.director.root.batcher2D._releaseDescriptorSetCache(this._textureHash); @@ -267,7 +267,7 @@ export class TextureBase extends Asset { * @en Gets the texture hash. * @zh 获取此贴图的哈希值。 */ - public getHash () { + public getHash (): number { return this._textureHash; } @@ -292,7 +292,7 @@ export class TextureBase extends Asset { * @en Gets the sampler resource for the texture * @zh 获取此贴图底层的 GFX 采样信息。 */ - public getGFXSampler () { + public getGFXSampler (): Sampler { if (!this._gfxSampler) { if (this._gfxDevice) { this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo); @@ -320,7 +320,7 @@ export class TextureBase extends Asset { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _deserialize (serializedData: any, handle: any) { + public _deserialize (serializedData: any, handle: any): void { const data = serializedData as string; const fields = data.split(','); fields.unshift(''); @@ -340,15 +340,15 @@ export class TextureBase extends Asset { return deviceManager.gfxDevice; } - protected _getGFXFormat () { + protected _getGFXFormat (): Format { return this._getGFXPixelFormat(this._format); } - protected _setGFXFormat (format?: PixelFormat) { + protected _setGFXFormat (format?: PixelFormat): void { this._format = format === undefined ? PixelFormat.RGBA8888 : format; } - protected _getGFXPixelFormat (format: PixelFormat) { + protected _getGFXPixelFormat (format: PixelFormat): Format { if (format === PixelFormat.RGBA_ETC1) { format = PixelFormat.RGB_ETC1; } else if (format === PixelFormat.RGB_A_PVRTC_4BPPV1) { diff --git a/cocos/asset/assets/texture-cube.ts b/cocos/asset/assets/texture-cube.ts index ffed22ecab4..7e38085de24 100644 --- a/cocos/asset/assets/texture-cube.ts +++ b/cocos/asset/assets/texture-cube.ts @@ -134,7 +134,7 @@ export class TextureCube extends SimpleTexture { * @zh 所有层级 Mipmap,注意,这里不包含自动生成的 Mipmap。 * 当设置 Mipmap 时,贴图的尺寸以及像素格式可能会改变。 */ - get mipmaps () { + get mipmaps (): ITextureCubeMipmap[] { return this._mipmaps; } @@ -174,7 +174,7 @@ export class TextureCube extends SimpleTexture { cubeMaps.push(cubeMap); } } else if (value.length > 1) { - value.forEach((mipmap) => { + value.forEach((mipmap): void => { const cubeMap: ITextureCubeMipmap = { front: mipmap.front.extractMipmap0(), back: mipmap.back.extractMipmap0(), @@ -190,7 +190,7 @@ export class TextureCube extends SimpleTexture { this._setMipmapParams(cubeMaps); } - private _setMipmapParams (value: ITextureCubeMipmap[]) { + private _setMipmapParams (value: ITextureCubeMipmap[]): void { this._generatedMipmaps = value; this._setMipmapLevel(this._generatedMipmaps.length); if (this._generatedMipmaps.length > 0) { @@ -203,8 +203,8 @@ export class TextureCube extends SimpleTexture { baseLevel: this._baseLevel, maxLevel: this._maxLevel, }); - this._generatedMipmaps.forEach((mipmap, level) => { - _forEachFace(mipmap, (face, faceIndex) => { + this._generatedMipmaps.forEach((mipmap, level): void => { + _forEachFace(mipmap, (face, faceIndex): void => { this._assignImage(face, level, faceIndex); }); }); @@ -264,7 +264,7 @@ export class TextureCube extends SimpleTexture { for (let j = 0; j < layout.length; j++) { const layoutInfo = layout[j]; - _forEachFace(faceAtlas, (face, faceIndex) => { + _forEachFace(faceAtlas, (face, faceIndex): void => { ctx.clearRect(0, 0, imageAtlasAsset.width, imageAtlasAsset.height); const drawImg = face.data as HTMLImageElement; // NOTE: on OH platform, drawImage only supports ImageBitmap and PixelMap type, so we mark drawImg as any. @@ -283,7 +283,7 @@ export class TextureCube extends SimpleTexture { } } - get mipmapAtlas () { + get mipmapAtlas (): ITextureCubeMipmapAtlas | null { return this._mipmapAtlas; } @@ -303,7 +303,7 @@ export class TextureCube extends SimpleTexture { * 注意,`this.image = img` 等价于 `this.mipmaps = [img]`, * 也就是说,通过 `this.image` 设置 0 级 Mipmap 时将隐式地清除之前的所有 Mipmap。 */ - get image () { + get image (): ITextureCubeMipmap | null { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; } @@ -331,7 +331,7 @@ export class TextureCube extends SimpleTexture { * ``` */ - public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) { + public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube): TextureCube { const mipmaps: ITextureCubeMipmap[] = []; const nMipmaps = textures.length / 6; for (let i = 0; i < nMipmaps; i++) { @@ -358,7 +358,7 @@ export class TextureCube extends SimpleTexture { private _generatedMipmaps: ITextureCubeMipmap[] = []; - public onLoaded () { + public onLoaded (): void { if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { this.mipmapAtlas = this._mipmapAtlas; } else { @@ -373,7 +373,7 @@ export class TextureCube extends SimpleTexture { * mipmap 图像的数据不会自动更新到贴图中,你必须显式调用 [[uploadData]] 来上传贴图数据。 * @param info @en The create information. @zh 创建贴图的相关信息。 */ - public reset (info: ITextureCubeCreateInfo) { + public reset (info: ITextureCubeCreateInfo): void { this._width = info.width; this._height = info.height; this._setGFXFormat(info.format); @@ -392,7 +392,7 @@ export class TextureCube extends SimpleTexture { * @param firstLevel @en First level to be updated. @zh 更新指定层的 mipmap。 * @param count @en Mipmap level count to be updated。 @zh 指定要更新层的数量。 */ - public updateMipmaps (firstLevel = 0, count?: number) { + public updateMipmaps (firstLevel = 0, count?: number): void { if (firstLevel >= this._generatedMipmaps.length) { return; } @@ -404,7 +404,7 @@ export class TextureCube extends SimpleTexture { for (let i = 0; i < nUpdate; ++i) { const level = firstLevel + i; - _forEachFace(this._generatedMipmaps[level], (face, faceIndex) => { + _forEachFace(this._generatedMipmaps[level], (face, faceIndex): void => { this._assignImage(face, level, faceIndex); }); } @@ -414,7 +414,7 @@ export class TextureCube extends SimpleTexture { * @en Destroys this texture, clear all mipmaps and release GPU resources * @zh 销毁此贴图,清空所有 Mipmap 并释放占用的 GPU 资源。 */ - public destroy () { + public destroy (): boolean { this._mipmaps = []; this._generatedMipmaps = []; this._mipmapAtlas = null; @@ -426,7 +426,7 @@ export class TextureCube extends SimpleTexture { * @zh 释放占用的 GPU 资源。 * @deprecated please use [[destroy]] instead */ - public releaseTexture () { + public releaseTexture (): void { this.destroy(); } @@ -492,7 +492,7 @@ export class TextureCube extends SimpleTexture { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) { + public _deserialize (serializedData: ITextureCubeSerializeData, handle: any): void { const data = serializedData; super._deserialize(data.base, handle); this.isRGBE = data.rgbe; @@ -552,7 +552,7 @@ export class TextureCube extends SimpleTexture { return texInfo; } - protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo) { + protected _getGfxTextureViewCreateInfo (presumed: PresumedGFXTextureViewInfo): TextureViewInfo { const texViewInfo = new TextureViewInfo(); texViewInfo.type = TextureType.CUBE; texViewInfo.baseLayer = 0; @@ -561,7 +561,7 @@ export class TextureCube extends SimpleTexture { return texViewInfo; } - protected _uploadAtlas () { + protected _uploadAtlas (): void { const layout = this._mipmapAtlas!.layout; const mip0Layout = layout[0]; this.reset({ @@ -571,7 +571,7 @@ export class TextureCube extends SimpleTexture { mipmapLevel: layout.length, }); - _forEachFace(this._mipmapAtlas!.atlas, (face, faceIndex) => { + _forEachFace(this._mipmapAtlas!.atlas, (face, faceIndex): void => { const tex = new Texture2D(); tex.image = face; tex.reset({ @@ -605,7 +605,7 @@ export class TextureCube extends SimpleTexture { }); } - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); const imageAsset = new ImageAsset(); @@ -620,7 +620,7 @@ export class TextureCube extends SimpleTexture { }]; } - public validate () { + public validate (): boolean { if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { if (this.mipmapAtlas === null || this.mipmapAtlas.layout.length === 0) { return false; @@ -628,7 +628,7 @@ export class TextureCube extends SimpleTexture { const atlas = this.mipmapAtlas.atlas; return !!(atlas.top && atlas.bottom && atlas.front && atlas.back && atlas.left && atlas.right); } else { - return this._mipmaps.length !== 0 && !this._mipmaps.find((x) => !(x.top && x.bottom && x.front && x.back && x.left && x.right)); + return this._mipmaps.length !== 0 && !this._mipmaps.find((x): boolean => !(x.top && x.bottom && x.front && x.back && x.left && x.right)); } } } @@ -662,7 +662,7 @@ interface ITextureCubeSerializeData { * @param {Mipmap} mipmap * @param {(face: ImageAsset) => void} callback */ -function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void) { +function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void): void { callback(mipmap.front, FaceIndex.front); callback(mipmap.back, FaceIndex.back); callback(mipmap.left, FaceIndex.left); diff --git a/cocos/audio/audio-clip.ts b/cocos/audio/audio-clip.ts index 8fef1f5d4a2..25431eb3972 100644 --- a/cocos/audio/audio-clip.ts +++ b/cocos/audio/audio-clip.ts @@ -84,7 +84,7 @@ export class AudioClip extends Asset { this._duration = 0; } } - get _nativeAsset () { + get _nativeAsset (): AudioMeta | null { return this._meta; } @@ -92,7 +92,12 @@ export class AudioClip extends Asset { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override - get _nativeDep () { + get _nativeDep (): { + uuid: string; + audioLoadMode: AudioType; + ext: string; + __isNative__: boolean; + } { return { uuid: this._uuid, audioLoadMode: this.loadMode, @@ -101,15 +106,15 @@ export class AudioClip extends Asset { }; } - get loadMode () { + get loadMode (): AudioType { return this._loadMode; } - public validate () { + public validate (): boolean { return !!this._meta; } - public getDuration () { + public getDuration (): number { // Dynamicly loaded audioClip._duration is 0 if (this._duration) { return this._duration; @@ -121,42 +126,42 @@ export class AudioClip extends Asset { /** * @deprecated since v3.1.0, please use AudioSource.prototype.state instead. */ - public get state () { + public get state (): AudioState { return this._player ? this._player.state : AudioState.INIT; } /** * @deprecated since v3.1.0, please use AudioSource.prototype.getCurrentTime() instead. */ - public getCurrentTime () { + public getCurrentTime (): number { return this._player ? this._player.currentTime : 0; } /** * @deprecated since v3.1.0, please use AudioSource.prototype.getVolume() instead. */ - public getVolume () { + public getVolume (): number { return this._player ? this._player.volume : 0; } /** * @deprecated since v3.1.0, please use AudioSource.prototype.getLoop() instead. */ - public getLoop () { + public getLoop (): boolean { return this._player ? this._player.loop : false; } /** * @deprecated since v3.1.0, please use AudioSource.prototype.setCurrentTime() instead. */ - public setCurrentTime (time: number) { + public setCurrentTime (time: number): void { this._player?.seek(time).catch((e) => {}); } /** * @deprecated since v3.1.0, please use AudioSource.prototype.setVolume() instead. */ - public setVolume (volume: number) { + public setVolume (volume: number): void { if (this._player) { this._player.volume = volume; } @@ -165,7 +170,7 @@ export class AudioClip extends Asset { /** * @deprecated since v3.1.0, please use AudioSource.prototype.setLoop() instead. */ - public setLoop (loop: boolean) { + public setLoop (loop: boolean): void { if (this._player) { this._player.loop = loop; } @@ -174,28 +179,28 @@ export class AudioClip extends Asset { /** * @deprecated since v3.1.0, please use AudioSource.prototype.play() instead. */ - public play () { + public play (): void { this._player?.play().catch((e) => {}); } /** * @deprecated since v3.1.0, please use AudioSource.prototype.pause() instead. */ - public pause () { + public pause (): void { this._player?.pause().catch((e) => {}); } /** * @deprecated since v3.1.0, please use AudioSource.prototype.stop() instead. */ - public stop () { + public stop (): void { this._player?.stop().catch((e) => {}); } /** * @deprecated since v3.1.0, please use AudioSource.prototype.playOneShot() instead. */ - public playOneShot (volume = 1) { + public playOneShot (volume = 1): void { if (this._nativeAsset) { AudioPlayer.loadOneShotAudio(this._nativeAsset.url, volume).then((oneShotAudio) => { oneShotAudio.play(); diff --git a/cocos/audio/audio-downloader.ts b/cocos/audio/audio-downloader.ts index bfd1438fb32..06906f22326 100644 --- a/cocos/audio/audio-downloader.ts +++ b/cocos/audio/audio-downloader.ts @@ -28,7 +28,7 @@ import { AudioClip, AudioMeta } from './audio-clip'; import downloader from '../asset/asset-manager/downloader'; import factory from '../asset/asset-manager/factory'; -export function loadAudioPlayer (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) { +export function loadAudioPlayer (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { AudioPlayer.load(url, { audioLoadMode: options.audioLoadMode, }).then((player) => { @@ -47,7 +47,7 @@ export function loadAudioPlayer (url: string, options: Record, onCo function createAudioClip (id: string, data: AudioMeta, options: Record, - onComplete: ((err: Error | null, data?: AudioClip | null) => void)) { + onComplete: ((err: Error | null, data?: AudioClip | null) => void)): void { const out = new AudioClip(); out._nativeUrl = id; out._nativeAsset = data; diff --git a/cocos/audio/audio-manager.ts b/cocos/audio/audio-manager.ts index ae576417701..1db9a09b026 100644 --- a/cocos/audio/audio-manager.ts +++ b/cocos/audio/audio-manager.ts @@ -35,7 +35,7 @@ export class AudioManager { private _oneShotAudioInfoList: AudioInfo[] = []; private _audioPlayerInfoList: AudioInfo[] = []; - private _findIndex (audioInfoList: AudioInfo[], audio: ManagedAudio) { + private _findIndex (audioInfoList: AudioInfo[], audio: ManagedAudio): number { return audioInfoList.findIndex((item) => item.audio === audio); } @@ -52,7 +52,7 @@ export class AudioManager { }); return true; } - public addPlaying (audio: ManagedAudio) { + public addPlaying (audio: ManagedAudio): void { if (audio instanceof AudioPlayer) { this._tryAddPlaying(this._audioPlayerInfoList, audio); } else { @@ -68,7 +68,7 @@ export class AudioManager { js.array.fastRemoveAt(audioInfoList, idx); return true; } - public removePlaying (audio: ManagedAudio) { + public removePlaying (audio: ManagedAudio): void { if (audio instanceof AudioPlayer) { this._tryRemovePlaying(this._audioPlayerInfoList, audio); } else { @@ -76,7 +76,7 @@ export class AudioManager { } } - public discardOnePlayingIfNeeded () { + public discardOnePlayingIfNeeded (): void { if (this._audioPlayerInfoList.length + this._oneShotAudioInfoList.length < AudioPlayer.maxAudioChannel) { return; } @@ -102,19 +102,19 @@ export class AudioManager { } } - public pause () { - this._oneShotAudioInfoList.forEach((info) => { + public pause (): void { + this._oneShotAudioInfoList.forEach((info): void => { info.audio.stop(); }); - this._audioPlayerInfoList.forEach((info) => { - info.audio.pause().catch((e) => {}); + this._audioPlayerInfoList.forEach((info): void => { + info.audio.pause().catch((e): void => {}); }); } - public resume () { + public resume (): void { // onShotAudio can not be resumed - this._audioPlayerInfoList.forEach((info) => { - info.audio.play().catch((e) => {}); + this._audioPlayerInfoList.forEach((info): void => { + info.audio.play().catch((e): void => {}); }); } } diff --git a/cocos/audio/audio-source.ts b/cocos/audio/audio-source.ts index 98d1f3271dd..7f966341c8b 100644 --- a/cocos/audio/audio-source.ts +++ b/cocos/audio/audio-source.ts @@ -49,7 +49,7 @@ enum AudioSourceEventType { @help('i18n:cc.AudioSource') @menu('Audio/AudioSource') export class AudioSource extends Component { - static get maxAudioChannel () { + static get maxAudioChannel (): number { return AudioPlayer.maxAudioChannel; } public static AudioState = AudioState; @@ -75,7 +75,7 @@ export class AudioSource extends Component { private _lastSetClip: AudioClip | null = null; - private _resetPlayer () { + private _resetPlayer (): void { if (this._player) { audioManager.removePlaying(this._player); this._player.offEnded(); @@ -100,10 +100,10 @@ export class AudioSource extends Component { this._clip = val; this._syncPlayer(); } - get clip () { + get clip (): AudioClip | null { return this._clip; } - private _syncPlayer () { + private _syncPlayer (): void { const clip = this._clip; if (this._lastSetClip === clip) { return; @@ -163,7 +163,7 @@ export class AudioSource extends Component { this._loop = val; this._player && (this._player.loop = val); } - get loop () { + get loop (): boolean { return this._loop; } @@ -182,7 +182,7 @@ export class AudioSource extends Component { set playOnAwake (val) { this._playOnAwake = val; } - get playOnAwake () { + get playOnAwake (): boolean { return this._playOnAwake; } @@ -206,22 +206,22 @@ export class AudioSource extends Component { this._volume = val; } } - get volume () { + get volume (): number { return this._volume; } - public onLoad () { + public onLoad (): void { this._syncPlayer(); } - public onEnable () { + public onEnable (): void { // audio source component may be played before if (this._playOnAwake && !this.playing) { this.play(); } } - public onDisable () { + public onDisable (): void { const rootNode = this._getRootNode(); if (rootNode?._persistNode) { return; @@ -229,7 +229,7 @@ export class AudioSource extends Component { this.pause(); } - public onDestroy () { + public onDestroy (): void { this.stop(); this._player?.destroy(); this._player = null; @@ -327,7 +327,7 @@ export class AudioSource extends Component { * - 在 TOUCH_END 或者 MOUSE_UP 的事件回调里播放音频。 * - 直接播放音频,引擎会在下一次发生用户交互时自动播放。 */ - public play () { + public play (): void { if (!this._isLoaded && this.clip) { this._operationsBeforeLoading.push('play'); return; @@ -350,7 +350,7 @@ export class AudioSource extends Component { * @zh * 暂停播放。 */ - public pause () { + public pause (): void { if (!this._isLoaded && this.clip) { this._operationsBeforeLoading.push('pause'); return; @@ -367,7 +367,7 @@ export class AudioSource extends Component { * @zh * 停止播放。 */ - public stop () { + public stop (): void { if (!this._isLoaded && this.clip) { this._operationsBeforeLoading.push('stop'); return; @@ -386,7 +386,7 @@ export class AudioSource extends Component { * @param clip The audio clip to be played. * @param volumeScale volume scaling factor wrt. current value. */ - public playOneShot (clip: AudioClip, volumeScale = 1) { + public playOneShot (clip: AudioClip, volumeScale = 1): void { if (!clip._nativeAsset) { console.error('Invalid audio clip'); return; @@ -395,26 +395,26 @@ export class AudioSource extends Component { audioLoadMode: clip.loadMode, }).then((oneShotAudio) => { audioManager.discardOnePlayingIfNeeded(); - oneShotAudio.onPlay = () => { + oneShotAudio.onPlay = (): void => { audioManager.addPlaying(oneShotAudio); }; - oneShotAudio.onEnd = () => { + oneShotAudio.onEnd = (): void => { audioManager.removePlaying(oneShotAudio); }; oneShotAudio.play(); - }).catch((e) => {}); + }).catch((e): void => {}); } - protected _syncStates () { + protected _syncStates (): void { if (!this._player) { return; } - this._player.seek(this._cachedCurrentTime).then(() => { + this._player.seek(this._cachedCurrentTime).then((): void => { if (this._player) { this._player.loop = this._loop; this._player.volume = this._volume; - this._operationsBeforeLoading.forEach((opName) => { this[opName]?.(); }); + this._operationsBeforeLoading.forEach((opName): void => { this[opName]?.(); }); this._operationsBeforeLoading.length = 0; } - }).catch((e) => {}); + }).catch((e): void => {}); } /** @@ -428,7 +428,7 @@ export class AudioSource extends Component { if (Number.isNaN(num)) { console.warn('illegal audio time!'); return; } num = clamp(num, 0, this.duration); this._cachedCurrentTime = num; - this._player?.seek(this._cachedCurrentTime).catch((e) => {}); + this._player?.seek(this._cachedCurrentTime).catch((e): void => {}); } /** @@ -437,7 +437,7 @@ export class AudioSource extends Component { * @zh * 以秒为单位获取当前播放时间。 */ - get currentTime () { + get currentTime (): number { return this._player ? this._player.currentTime : this._cachedCurrentTime; } @@ -447,7 +447,7 @@ export class AudioSource extends Component { * @zh * 获取以秒为单位的音频总时长。 */ - get duration () { + get duration (): number { return this._clip?.getDuration() ?? (this._player ? this._player.duration : 0); } @@ -467,7 +467,7 @@ export class AudioSource extends Component { * @zh * 当前音频是否正在播放? */ - get playing () { + get playing (): boolean { return this.state === AudioSource.AudioState.PLAYING; } } diff --git a/cocos/core/algorithm/binary-search.ts b/cocos/core/algorithm/binary-search.ts index bad62deeea1..b39f1e61fd2 100644 --- a/cocos/core/algorithm/binary-search.ts +++ b/cocos/core/algorithm/binary-search.ts @@ -32,7 +32,7 @@ * returns the complement of array's length if no element is greater than the element to be searched or the array is empty. * @engineInternal */ -export function binarySearch (array: number[], value: number) { +export function binarySearch (array: number[], value: number): number { return binarySearchEpsilon(array, value, 0); } @@ -46,7 +46,7 @@ export function binarySearch (array: number[], value: number) { * returns the complement of array's length if no element is greater than the element to be searched or the array is empty. * @engineInternal */ -export function binarySearchEpsilon (array: Readonly>, value: number, EPSILON = 1e-6) { +export function binarySearchEpsilon (array: Readonly>, value: number, EPSILON = 1e-6): number { let low = 0; let high = array.length - 1; let middle = high >>> 1; @@ -73,7 +73,7 @@ export function binarySearchEpsilon (array: Readonly>, value: * returns the complement of array's length if no element is greater than the searching element or the array is empty. * @engineInternal */ -export function binarySearchBy (array: T[], value: U, lessThan: (lhs: T, rhs: U) => number) { +export function binarySearchBy (array: T[], value: U, lessThan: (lhs: T, rhs: U) => number): number { let low = 0; let high = array.length - 1; let middle = high >>> 1; diff --git a/cocos/core/algorithm/easing.ts b/cocos/core/algorithm/easing.ts index 60ed26f4bfa..84394a6ecbc 100644 --- a/cocos/core/algorithm/easing.ts +++ b/cocos/core/algorithm/easing.ts @@ -28,7 +28,7 @@ * @en Not any easing effect. * @zh 没有任何缓动效果。 */ -export function constant () { +export function constant (): number { return 0; } @@ -37,7 +37,7 @@ export function constant () { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 线性函数,`f(k) = k`。返回值和输入值一一对应。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function linear (k: number) { +export function linear (k: number): number { return k; } @@ -46,7 +46,7 @@ export function linear (k: number) { * at which point it stops abruptly. Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 一个二次方的函数,f(k) = k * k。插值开始时很慢,然后逐渐加快,直到结束,并突然停止。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quadIn (k: number) { +export function quadIn (k: number): number { return k * k; } @@ -55,7 +55,7 @@ export function quadIn (k: number) { * [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 一个二次方的函数,f(k) = k * (2-k)。插值开始时很突然,然后在接近尾声时逐渐减慢。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quadOut (k: number) { +export function quadOut (k: number): number { return k * (2 - k); } @@ -64,7 +64,7 @@ export function quadOut (k: number) { * [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) graphic feature. * @zh 插值开始时很慢,接着加快,然后在接近尾声时减慢。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quadInOut (k: number) { +export function quadInOut (k: number): number { k *= 2; if (k < 1) { return 0.5 * k * k; @@ -76,7 +76,7 @@ export function quadInOut (k: number) { * @en Starts slowly and accelerates. Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 启动慢,加速快。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function cubicIn (k: number) { +export function cubicIn (k: number): number { return k * k * k; } @@ -85,7 +85,7 @@ export function cubicIn (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 起动迅速,减速慢。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function cubicOut (k: number) { +export function cubicOut (k: number): number { return --k * k * k + 1; } @@ -94,7 +94,7 @@ export function cubicOut (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 在开始时加速动画,在结束时减慢动画的速度。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function cubicInOut (k: number) { +export function cubicInOut (k: number): number { k *= 2; if (k < 1) { return 0.5 * k * k * k; @@ -106,7 +106,7 @@ export function cubicInOut (k: number) { * @en Starts slowly and accelerates. Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 启动慢,加速快。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quartIn (k: number) { +export function quartIn (k: number): number { return k * k * k * k; } @@ -115,7 +115,7 @@ export function quartIn (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 起动迅速,减速慢。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quartOut (k: number) { +export function quartOut (k: number): number { return 1 - (--k * k * k * k); } @@ -124,7 +124,7 @@ export function quartOut (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 在开始时加速动画,在结束时减慢动画的速度。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quartInOut (k: number) { +export function quartInOut (k: number): number { k *= 2; if (k < 1) { return 0.5 * k * k * k * k; @@ -136,7 +136,7 @@ export function quartInOut (k: number) { * @en Starts slowly and accelerates. Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 启动慢,加速快。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quintIn (k: number) { +export function quintIn (k: number): number { return k * k * k * k * k; } @@ -145,7 +145,7 @@ export function quintIn (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 起动迅速,减速慢。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quintOut (k: number) { +export function quintOut (k: number): number { return --k * k * k * k * k + 1; } @@ -154,7 +154,7 @@ export function quintOut (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 在开始时加速动画,在结束时减慢动画的速度。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function quintInOut (k: number) { +export function quintInOut (k: number): number { k *= 2; if (k < 1) { return 0.5 * k * k * k * k * k; @@ -167,7 +167,7 @@ export function quintInOut (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 平滑地加速动画。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function sineIn (k: number) { +export function sineIn (k: number): number { if (k === 1) { return 1; } @@ -179,7 +179,7 @@ export function sineIn (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 平滑地使动画降速。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function sineOut (k: number) { +export function sineOut (k: number): number { return Math.sin(k * Math.PI / 2); } @@ -188,7 +188,7 @@ export function sineOut (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 在开始时平滑地加速动画,在结束时平滑地减速动画。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function sineInOut (k: number) { +export function sineInOut (k: number): number { return 0.5 * (1 - Math.cos(Math.PI * k)); } @@ -196,7 +196,7 @@ export function sineInOut (k: number) { * @en Starts slowly and accelerates. Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 启动慢,加速快。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function expoIn (k: number) { +export function expoIn (k: number): number { return k === 0 ? 0 : Math.pow(1024, k - 1); } @@ -205,7 +205,7 @@ export function expoIn (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 起动迅速,减速慢。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function expoOut (k: number) { +export function expoOut (k: number): number { return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); } @@ -214,7 +214,7 @@ export function expoOut (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 在开始时加速动画,在结束时减慢动画的速度。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function expoInOut (k: number) { +export function expoInOut (k: number): number { if (k === 0) { return 0; } @@ -232,7 +232,7 @@ export function expoInOut (k: number) { * @en Starts slowly and accelerates. Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 启动慢,加速快。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function circIn (k: number) { +export function circIn (k: number): number { return 1 - Math.sqrt(1 - k * k); } @@ -241,7 +241,7 @@ export function circIn (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 起动迅速,减速慢。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function circOut (k: number) { +export function circOut (k: number): number { return Math.sqrt(1 - (--k * k)); } @@ -250,7 +250,7 @@ export function circOut (k: number) { * Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 在开始时加速动画,在结束时减慢动画的速度。具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function circInOut (k: number) { +export function circInOut (k: number): number { k *= 2; if (k < 1) { return -0.5 * (Math.sqrt(1 - k * k) - 1); @@ -262,7 +262,7 @@ export function circInOut (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function elasticIn (k: number) { +export function elasticIn (k: number): number { let s; let a = 0.1; const p = 0.4; @@ -285,7 +285,7 @@ export function elasticIn (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function elasticOut (k: number) { +export function elasticOut (k: number): number { let s; let a = 0.1; const p = 0.4; @@ -308,7 +308,7 @@ export function elasticOut (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function elasticInOut (k: number) { +export function elasticInOut (k: number): number { let s; let a = 0.1; const p = 0.4; @@ -336,7 +336,7 @@ export function elasticInOut (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function backIn (k: number) { +export function backIn (k: number): number { if (k === 1) { return 1; } @@ -348,7 +348,7 @@ export function backIn (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function backOut (k: number) { +export function backOut (k: number): number { if (k === 0) { return 0; } @@ -360,7 +360,7 @@ export function backOut (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function backInOut (k: number) { +export function backInOut (k: number): number { const s = 1.70158 * 1.525; k *= 2; if (k < 1) { @@ -369,7 +369,7 @@ export function backInOut (k: number) { return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); } -export function bounceIn (k: number) { +export function bounceIn (k: number): number { return 1 - bounceOut(1 - k); } @@ -377,7 +377,7 @@ export function bounceIn (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function bounceOut (k: number) { +export function bounceOut (k: number): number { if (k < (1 / 2.75)) { return 7.5625 * k * k; } else if (k < (2 / 2.75)) { @@ -393,7 +393,7 @@ export function bounceOut (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function bounceInOut (k: number) { +export function bounceInOut (k: number): number { if (k < 0.5) { return bounceIn(k * 2) * 0.5; } @@ -404,7 +404,7 @@ export function bounceInOut (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function smooth (k: number) { +export function smooth (k: number): number { if (k <= 0) { return 0; } @@ -418,7 +418,7 @@ export function smooth (k: number) { * @en Refer to [this doc](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html) for graphic feature. * @zh 具体效果可以参考[该文档](https://docs.cocos.com/creator/manual/zh/tween/tween-function.html)。 */ -export function fade (k: number) { +export function fade (k: number): number { if (k <= 0) { return 0; } @@ -489,7 +489,7 @@ export const backOutIn = _makeOutIn(backIn, backOut); export const bounceOutIn = _makeOutIn(bounceIn, bounceOut); function _makeOutIn (fnIn: (k: number) => number, fnOut: (k: number) => number) { - return (k: number) => { + return (k: number): number => { if (k < 0.5) { return fnOut(k * 2) / 2; } diff --git a/cocos/core/algorithm/move.ts b/cocos/core/algorithm/move.ts index 89267bd2f54..d171b939007 100644 --- a/cocos/core/algorithm/move.ts +++ b/cocos/core/algorithm/move.ts @@ -35,7 +35,7 @@ import { assertsArrayIndex } from '../data/utils/asserts'; * @returns @en The input array. @zh 输入的数组。 * @engineInternal */ -export function shift (array: T[], first: number, last: number) { +export function shift (array: T[], first: number, last: number): T[] { assertsArrayIndex(array, first); assertsArrayIndex(array, last); if (first === last) { diff --git a/cocos/core/algorithm/murmurhash2_gc.ts b/cocos/core/algorithm/murmurhash2_gc.ts index 3ac32fc8ad7..a2a2c8ecc34 100644 --- a/cocos/core/algorithm/murmurhash2_gc.ts +++ b/cocos/core/algorithm/murmurhash2_gc.ts @@ -36,7 +36,7 @@ */ const getUint8ForString = String.prototype.charCodeAt; -function getUint8ForArray (this: Uint8Array, idx: number) { return this[idx]; } +function getUint8ForArray (this: Uint8Array, idx: number): number { return this[idx]; } /** * @en JS Implementation of MurmurHash2. Original implementation is http://github.com/garycourt/murmurhash-js. @@ -45,7 +45,7 @@ function getUint8ForArray (this: Uint8Array, idx: number) { return this[idx]; } * @param seed @en Hash seed. Should be a positive integer. @zh 哈希种子。必须是个正整数。 * @returns @en 32-bit positive integer hash. @zh 32位正整数哈希值。 */ -export function murmurhash2_32_gc (input: string | Uint8Array, seed: number) { +export function murmurhash2_32_gc (input: string | Uint8Array, seed: number): number { let l = input.length; let h = seed ^ l; let i = 0; diff --git a/cocos/core/algorithm/partition.ts b/cocos/core/algorithm/partition.ts index 4f0efe6502c..87d5f591978 100644 --- a/cocos/core/algorithm/partition.ts +++ b/cocos/core/algorithm/partition.ts @@ -47,7 +47,7 @@ * log(array.slice(nFirstGroupElements)); // [7, 1, 3] * ``` */ -export function partition (array: T[], predicate: (element: T, index: number, array: T[]) => boolean) { +export function partition (array: T[], predicate: (element: T, index: number, array: T[]) => boolean): number { const nElements = array.length; // Finds the first element to be placed into second group(predicate to false). diff --git a/cocos/core/curves/bezier.ts b/cocos/core/curves/bezier.ts index 0e75dda1eaf..8aebb3dec68 100644 --- a/cocos/core/curves/bezier.ts +++ b/cocos/core/curves/bezier.ts @@ -26,7 +26,7 @@ import { legacyCC } from '../global-exports'; export type BezierControlPoints = [ number, number, number, number ]; -export function bezier (C1: number, C2: number, C3: number, C4: number, t: number) { +export function bezier (C1: number, C2: number, C3: number, C4: number, t: number): number { const t1 = 1 - t; return t1 * (t1 * (C1 + (C2 * 3 - C1) * t) + C3 * 3 * t * t) + C4 * t * t * t; } @@ -41,7 +41,7 @@ const pi = Math.PI; const tau = 2 * pi; const sqrt = Math.sqrt; -function crt (v: number) { +function crt (v: number): number { if (v < 0) { return -Math.pow(-v, 1 / 3); } else { @@ -51,7 +51,7 @@ function crt (v: number) { // Modified from http://jsbin.com/yibipofeqi/1/edit, optimized for animations. // The origin Cardano's algorithm is based on http://www.trans4mind.com/personal_development/mathematics/polynomials/cubicAlgebra.htm -function cardano (curve: BezierControlPoints, x: number) { +function cardano (curve: BezierControlPoints, x: number): any { // align curve with the intersecting line: // var line = {p1: {x: x, y: 0}, p2: {x: x, y: 1}}; // var aligned = align(curve, line); @@ -155,7 +155,7 @@ function cardano (curve: BezierControlPoints, x: number) { } } -export function bezierByTime (controlPoints: BezierControlPoints, x: number) { +export function bezierByTime (controlPoints: BezierControlPoints, x: number): number { const percent = cardano(controlPoints, x); // t const p1y = controlPoints[1]; // b const p2y = controlPoints[3]; // c diff --git a/cocos/core/curves/curve.ts b/cocos/core/curves/curve.ts index b66317a9f14..9e2b511014b 100644 --- a/cocos/core/curves/curve.ts +++ b/cocos/core/curves/curve.ts @@ -207,7 +207,7 @@ export type { RealKeyframeValue }; */ type RealKeyframeValueParameters = number | Partial; -function createRealKeyframeValue (params: RealKeyframeValueParameters) { +function createRealKeyframeValue (params: RealKeyframeValueParameters): RealKeyframeValue { const realKeyframeValue = new RealKeyframeValue(); if (typeof params === 'number') { realKeyframeValue.value = params; @@ -452,7 +452,7 @@ export class RealCurve extends KeyframeCurve { public assignSorted ( times: Iterable<[number, RealKeyframeValueParameters]> | readonly number[], values?: readonly RealKeyframeValueParameters[], - ) { + ): void { if (values !== undefined) { assertIsTrue(Array.isArray(times)); this.setKeyframes( @@ -476,18 +476,18 @@ export class RealCurve extends KeyframeCurve { * @param tolerance The tolerance. * @returns Whether it is constant. */ - public isConstant (tolerance: number) { + public isConstant (tolerance: number): boolean { if (this._values.length <= 1) { return true; } const firstVal = this._values[0].value; - return this._values.every((frame) => approx(frame.value, firstVal, tolerance)); + return this._values.every((frame): boolean => approx(frame.value, firstVal, tolerance)); } /** * @internal */ - public [serializeTag] (output: SerializationOutput, context: SerializationContext) { + public [serializeTag] (output: SerializationOutput, context: SerializationContext): void { if (!context.toCCON) { output.writeThis(); return; @@ -537,7 +537,7 @@ export class RealCurve extends KeyframeCurve { /** * @internal */ - public [deserializeTag] (input: SerializationInput, context: DeserializationContext) { + public [deserializeTag] (input: SerializationInput, context: DeserializationContext): void { if (!context.fromCCON) { input.readThis(); return; @@ -634,7 +634,7 @@ const REAL_KEY_FRAME_VALUE_MAX_SIZE = KEY_FRAME_VALUE_FLAGS_BYTES + RIGHT_TANGENT_WEIGHT_BYTES + 0; -function saveRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeValue, offset: number) { +function saveRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeValue, offset: number): number { let flags = 0; let currentOffset = offset; @@ -699,7 +699,7 @@ function saveRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeV return currentOffset; } -function loadRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeValue, offset: number) { +function loadRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeValue, offset: number): number { let currentOffset = offset; const flags = dataView.getUint32(currentOffset, true); @@ -744,11 +744,11 @@ function loadRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeV return currentOffset; } -function wrapRepeat (time: number, prevTime: number, nextTime: number) { +function wrapRepeat (time: number, prevTime: number, nextTime: number): number { return prevTime + repeat(time - prevTime, nextTime - prevTime); } -function wrapPingPong (time: number, prevTime: number, nextTime: number) { +function wrapPingPong (time: number, prevTime: number, nextTime: number): number { return prevTime + pingPong(time - prevTime, nextTime - prevTime); } @@ -758,7 +758,7 @@ function linearTrend ( nextTime: number, nextValue: number, time: number, -) { +): number { const slope = (nextValue - prevValue) / (nextTime - prevTime); return prevValue + (time - prevTime) * slope; } @@ -769,7 +769,7 @@ function evalBetweenTwoKeyFrames ( nextTime: number, nextValue: RealKeyframeValue, ratio: number, -) { +): number { const dt = nextTime - prevTime; switch (prevValue.interpolationMode) { default: @@ -860,15 +860,15 @@ function evalBetweenTwoKeyFrames ( } } -function isLeftTangentWeightEnabled (tangentWeightMode: TangentWeightMode) { +function isLeftTangentWeightEnabled (tangentWeightMode: TangentWeightMode): boolean { return (tangentWeightMode & TangentWeightMode.LEFT) !== 0; } -function isRightTangentWeightEnabled (tangentWeightMode: TangentWeightMode) { +function isRightTangentWeightEnabled (tangentWeightMode: TangentWeightMode): boolean { return (tangentWeightMode & TangentWeightMode.RIGHT) !== 0; } -function bezierInterpolate (p0: number, p1: number, p2: number, p3: number, t: number) { +function bezierInterpolate (p0: number, p1: number, p2: number, p3: number, t: number): number { const u = 1 - t; const coeff0 = u * u * u; const coeff1 = 3 * u * u * t; @@ -877,7 +877,7 @@ function bezierInterpolate (p0: number, p1: number, p2: number, p3: number, t: n return coeff0 * p0 + coeff1 * p1 + coeff2 * p2 + coeff3 * p3; } -function getParamFromCubicSolution (solutions: readonly [number, number, number], solutionsCount: number, x: number) { +function getParamFromCubicSolution (solutions: readonly [number, number, number], solutionsCount: number, x: number): number { let param = x; if (solutionsCount === 1) { param = solutions[0]; diff --git a/cocos/core/curves/gradient.ts b/cocos/core/curves/gradient.ts index a21074001fc..9ad938e15de 100644 --- a/cocos/core/curves/gradient.ts +++ b/cocos/core/curves/gradient.ts @@ -112,7 +112,7 @@ export class Gradient { * @param colorKeys @en Array of color keys @zh 颜色关键帧列表 * @param alphaKeys @en Array of alpha keys @zh 透明度关键帧列表 */ - public setKeys (colorKeys: ColorKey[], alphaKeys: AlphaKey[]) { + public setKeys (colorKeys: ColorKey[], alphaKeys: AlphaKey[]): void { this.colorKeys = colorKeys; this.alphaKeys = alphaKeys; } @@ -121,12 +121,12 @@ export class Gradient { * @en Sort color keys and alpha keys. * @zh 对颜色和透明度的关键帧进行排序。 */ - public sortKeys () { + public sortKeys (): void { if (this.colorKeys.length > 1) { - this.colorKeys.sort((a, b) => a.time - b.time); + this.colorKeys.sort((a, b): number => a.time - b.time); } if (this.alphaKeys.length > 1) { - this.alphaKeys.sort((a, b) => a.time - b.time); + this.alphaKeys.sort((a, b): number => a.time - b.time); } } @@ -138,7 +138,7 @@ export class Gradient { * * @deprecated since v3.8 please use [[evaluateFast]] instead. */ - public evaluate (time: number) { + public evaluate (time: number): Color { return this.evaluateFast(new Color(), time); } @@ -149,7 +149,7 @@ export class Gradient { * @param time @en Normalized time to interpolate. @zh 用于插值的归一化时间。 * @returns @en Interpolated color value. @zh 插值过后的颜色值。 */ - public evaluateFast (out: Color, time: number) { + public evaluateFast (out: Color, time: number): Color { this.getRGB(out, time); out._set_a_unsafe(this.getAlpha(time)!); return out; @@ -161,7 +161,7 @@ export class Gradient { * @returns @en Randomized color. @zh 随机生成的颜色。 * @deprecated since v3.8 please use [[getRandomColor]] instead. */ - public randomColor () { + public randomColor (): Color { return this.getRandomColor(new Color()); } @@ -171,7 +171,7 @@ export class Gradient { * @param out @en Randomized color. @zh 随机生成的颜色。 * @returns @en Randomized color. @zh 随机生成的颜色。 */ - public getRandomColor (out: Color) { + public getRandomColor (out: Color): Color { const c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)]; const a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)]; out.set(c.color); @@ -179,7 +179,7 @@ export class Gradient { return out; } - private getRGB (out: Color, time: number) { + private getRGB (out: Color, time: number): Color { const colorKeys = this.colorKeys; const length = colorKeys.length; if (length > 1) { @@ -214,7 +214,7 @@ export class Gradient { return out; } - private getAlpha (time: number) { + private getAlpha (time: number): number { const basicAlpha = 0; // default alpha is 0 const alphaKeys = this.alphaKeys; const length = alphaKeys.length; diff --git a/cocos/core/curves/keyframe-curve.ts b/cocos/core/curves/keyframe-curve.ts index 23d1e093ceb..ff60d57a1cf 100644 --- a/cocos/core/curves/keyframe-curve.ts +++ b/cocos/core/curves/keyframe-curve.ts @@ -43,7 +43,7 @@ export class KeyframeCurve implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable IteratorResult> } { let index = 0; return { next: (): IteratorResult> => { @@ -168,7 +168,7 @@ export class KeyframeCurve implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable | readonly number[], values?: readonly TKeyframeValue[]) { + public assignSorted (times: Iterable<[number, TKeyframeValue]> | readonly number[], values?: readonly TKeyframeValue[]): void { if (values !== undefined) { assertIsTrue(Array.isArray(times)); this.setKeyframes( @@ -240,23 +240,23 @@ export class KeyframeCurve implements CurveBase, Iterable index === 0 || value > array[index - 1] || approx(value, array[index - 1], 1e-6), diff --git a/cocos/core/curves/object-curve.ts b/cocos/core/curves/object-curve.ts index c501a80518d..79f5da99057 100644 --- a/cocos/core/curves/object-curve.ts +++ b/cocos/core/curves/object-curve.ts @@ -30,7 +30,7 @@ export type ObjectCurveKeyframe = T; @ccclass('cc.ObjectCurve') export class ObjectCurve extends KeyframeCurve> { - public evaluate (time: number) { + public evaluate (time: number): T { const iSearch = this.searchKeyframe(time); if (iSearch >= 0) { return this._values[iSearch]; diff --git a/cocos/core/curves/quat-curve.ts b/cocos/core/curves/quat-curve.ts index fde7c9cf1a6..3ca14a93a7e 100644 --- a/cocos/core/curves/quat-curve.ts +++ b/cocos/core/curves/quat-curve.ts @@ -128,7 +128,7 @@ export type { QuatKeyframeValue }; */ type QuatKeyframeValueParameters = Partial; -function createQuatKeyframeValue (params: QuatKeyframeValueParameters) { +function createQuatKeyframeValue (params: QuatKeyframeValueParameters): QuatKeyframeValue { return new QuatKeyframeValue(params); } @@ -279,7 +279,7 @@ export class QuatCurve extends KeyframeCurve { public assignSorted ( times: Iterable<[number, QuatKeyframeValueParameters]> | readonly number[], values?: readonly QuatKeyframeValueParameters[], - ) { + ): void { if (values !== undefined) { assertIsTrue(Array.isArray(times)); this.setKeyframes( @@ -298,7 +298,7 @@ export class QuatCurve extends KeyframeCurve { /** * @internal */ - public [serializeTag] (output: SerializationOutput, context: SerializationContext) { + public [serializeTag] (output: SerializationOutput, context: SerializationContext): void { if (!context.toCCON) { output.writeThis(); return; @@ -394,7 +394,7 @@ export class QuatCurve extends KeyframeCurve { /** * @internal */ - public [deserializeTag] (input: SerializationInput, context: DeserializationContext) { + public [deserializeTag] (input: SerializationInput, context: DeserializationContext): void { if (!context.fromCCON) { input.readThis(); return; diff --git a/cocos/core/curves/solve-cubic.ts b/cocos/core/curves/solve-cubic.ts index 5a4174d738c..3d402883e3d 100644 --- a/cocos/core/curves/solve-cubic.ts +++ b/cocos/core/curves/solve-cubic.ts @@ -29,7 +29,7 @@ * The equation is formed from coeff0 + coeff1 * x + coeff2 * x^2 + coeff3 * x^3 = 0. * Modified from https://github.com/erich666/GraphicsGems/blob/master/gems/Roots3And4.c . */ -export function solveCubic (coeff0: number, coeff1: number, coeff2: number, coeff3: number, solutions: [number, number, number]) { +export function solveCubic (coeff0: number, coeff1: number, coeff2: number, coeff3: number, solutions: [number, number, number]): number { // normal form: x^3 + Ax^2 + Bx + C = 0 const a = coeff2 / coeff3; const b = coeff1 / coeff3; @@ -82,6 +82,6 @@ export function solveCubic (coeff0: number, coeff1: number, coeff2: number, coef const EQN_EPS = 1e-9; -function isZero (x: number) { +function isZero (x: number): boolean { return x > -EQN_EPS && x < EQN_EPS; } diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index 1b75451a5d3..4d230d13bfd 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -50,14 +50,14 @@ export const ENUM_TAG = 'Enum'; */ export const BITMASK_TAG = 'BitMask'; -function pushUnique (array, item) { +function pushUnique (array, item): void { if (array.indexOf(item) < 0) { array.push(item); } } // both getter and prop must register the name into `__props__` array -function appendProp (cls, name) { +function appendProp (cls, name): void { if (DEV) { // if (!IDENTIFIER_RE.test(name)) { // error('The property name "' + name + '" is not compliant with JavaScript naming standards'); @@ -71,7 +71,7 @@ function appendProp (cls, name) { pushUnique(cls.__props__, name); } -function defineProp (cls, className, propName, val) { +function defineProp (cls, className, propName, val): void { if (DEV) { // check base prototype to avoid name collision if (CCClass.getInheritanceChain(cls) @@ -93,7 +93,7 @@ function defineProp (cls, className, propName, val) { } } -function defineGetSet (cls, name, propName, val) { +function defineGetSet (cls, name, propName, val): void { const getter = val.get; const setter = val.set; @@ -122,7 +122,7 @@ function defineGetSet (cls, name, propName, val) { } } -function getDefault (defaultVal) { +function getDefault (defaultVal): any { if (typeof defaultVal === 'function') { if (EDITOR) { try { @@ -138,7 +138,7 @@ function getDefault (defaultVal) { return defaultVal; } -function doDefine (className, baseClass, options) { +function doDefine (className, baseClass, options): any { const ctor = options.ctor; if (DEV) { @@ -159,7 +159,7 @@ function doDefine (className, baseClass, options) { return ctor; } -function define (className, baseClass, options) { +function define (className, baseClass, options): any { const Component = legacyCC.Component; const frame = RF.peek(); @@ -222,7 +222,7 @@ function define (className, baseClass, options) { return cls; } -function getNewValueTypeCodeJit (value) { +function getNewValueTypeCodeJit (value): string { const clsName = js.getClassName(value); const type = value.constructor; let res = `new ${clsName}(`; @@ -245,7 +245,7 @@ function getNewValueTypeCodeJit (value) { // convert a normal string including newlines, quotes and Unicode characters into a string literal // ready to use in JavaScript source -function escapeForJS (s) { +function escapeForJS (s): string { return JSON.stringify(s) // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify .replace(/\u2028/g, '\\u2028') @@ -255,7 +255,7 @@ function escapeForJS (s) { // simple test variable name const IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/; -function declareProperties (cls, className, properties, baseClass) { +function declareProperties (cls, className, properties, baseClass): void { cls.__props__ = []; if (baseClass && baseClass.__props__) { @@ -286,7 +286,7 @@ export function CCClass (options: { ctor: TFunction; properties?: any; editor?: any; -}) { +}): any { let name = options.name; const base = options.extends/* || CCObject */; @@ -343,7 +343,7 @@ CCClass._isCCClass = function isCCClass (constructor): boolean { // @param {Object} serializableFields // @private // -CCClass.fastDefine = function (className, constructor, serializableFields) { +CCClass.fastDefine = function (className, constructor, serializableFields): void { js.setClassName(className, constructor); const props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields); const attrs = attributeUtils.getClassAttrs(constructor); @@ -364,7 +364,7 @@ CCClass.attr = attributeUtils.attr; * @engineInternal */ // eslint-disable-next-line @typescript-eslint/ban-types -export function isCCClassOrFastDefined (constructor: Constructor) { +export function isCCClassOrFastDefined (constructor: Constructor): boolean { // eslint-disable-next-line no-prototype-builtins, @typescript-eslint/no-unsafe-return return constructor?.hasOwnProperty?.('__values__'); } @@ -375,7 +375,7 @@ CCClass.isCCClassOrFastDefined = isCCClassOrFastDefined; * Return all super classes. * @param constructor The Constructor. */ -function getInheritanceChain (constructor) { +function getInheritanceChain (constructor): any[] { const chain: any[] = []; for (; ;) { constructor = getSuper(constructor); @@ -415,12 +415,12 @@ interface AttributesRecord { default?: unknown; } -function parseAttributes (constructor: Function, attributes: PropertyStash, className: string, propertyName: string, usedInGetter) { +function parseAttributes (constructor: Function, attributes: PropertyStash, className: string, propertyName: string, usedInGetter): void { const ERR_Type = DEV ? 'The %s of %s must be type %s' : ''; let attrs: IParsedAttribute | null = null; let propertyNamePrefix = ''; - function initAttrs () { + function initAttrs (): any { propertyNamePrefix = propertyName + DELIMETER; return attrs = attributeUtils.getClassAttrs(constructor); } @@ -483,7 +483,7 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas // warnID(3654, className, propertyName); } - const parseSimpleAttribute = (attributeName: keyof IAcceptableAttributes, expectType: string) => { + const parseSimpleAttribute = (attributeName: keyof IAcceptableAttributes, expectType: string): void => { if (attributeName in attributes) { const val = attributes[attributeName]; if (typeof val === expectType) { @@ -591,7 +591,7 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas parseSimpleAttribute('step', 'number'); } -CCClass.isArray = function (defaultVal) { +CCClass.isArray = function (defaultVal): boolean { defaultVal = getDefault(defaultVal); return Array.isArray(defaultVal); }; diff --git a/cocos/core/data/decorators/editable.ts b/cocos/core/data/decorators/editable.ts index 858487ef1b0..75ab976b2f0 100644 --- a/cocos/core/data/decorators/editable.ts +++ b/cocos/core/data/decorators/editable.ts @@ -151,7 +151,7 @@ export const help: (url: string) => ClassDecorator = DEV ? makeEditorClassDecora */ export const editable: LegacyPropertyDecorator = !DEV ? emptyDecorator - : (target, propertyKey, descriptorOrInitializer) => { + : (target, propertyKey, descriptorOrInitializer): void => { const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer); setImplicitVisible(propertyStash); }; @@ -326,7 +326,7 @@ export const multiline: LegacyPropertyDecorator = !DEV */ export const disallowAnimation: LegacyPropertyDecorator = !DEV ? emptyDecorator - : (target, propertyKey, descriptorOrInitializer) => { + : (target, propertyKey, descriptorOrInitializer): void => { const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer); propertyStash.animatable = false; }; @@ -343,7 +343,7 @@ function setPropertyStashWithImplicitVisible ( key: TKey, value: NonNullable, ): LegacyPropertyDecorator { - return (target, propertyKey, descriptorOrInitializer) => { + return (target, propertyKey, descriptorOrInitializer): void => { const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer); propertyStash[key] = value; setImplicitVisible(propertyStash); @@ -353,21 +353,21 @@ function setPropertyStashWithImplicitVisible ( function setPropertyStashVar1WithImplicitVisible ( key: TKey, ) { - return (value: NonNullable): LegacyPropertyDecorator => (target, propertyKey, descriptorOrInitializer) => { + return (value: NonNullable): LegacyPropertyDecorator => (target, propertyKey, descriptorOrInitializer): void => { const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer); propertyStash[key] = value; setImplicitVisible(propertyStash); }; } -function setImplicitVisible (propertyStash: PropertyStash) { +function setImplicitVisible (propertyStash: PropertyStash): void { propertyStash.__internalFlags |= PropertyStashInternalFlag.IMPLICIT_VISIBLE; } function setPropertyStashWithImplicitI18n ( key: TKey, ) { - return (value: NonNullable): LegacyPropertyDecorator => (target, propertyKey, descriptorOrInitializer) => { + return (value: NonNullable): LegacyPropertyDecorator => (target, propertyKey, descriptorOrInitializer): void => { const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer); const prefix = 'i18n:'; if (value.startsWith(prefix)) { diff --git a/cocos/core/data/decorators/property.ts b/cocos/core/data/decorators/property.ts index 1cd5a051aef..7647adcd758 100644 --- a/cocos/core/data/decorators/property.ts +++ b/cocos/core/data/decorators/property.ts @@ -68,13 +68,13 @@ export function property ( target?: Parameters[0] | PropertyType, propertyKey?: Parameters[1], descriptorOrInitializer?: Parameters[2], -) { +): LegacyPropertyDecorator | undefined { let options: IPropertyOptions | PropertyType | null = null; function normalized ( target: Parameters[0], propertyKey: Parameters[1], descriptorOrInitializer: Parameters[2], - ) { + ): void { const classStash = getOrCreateClassStash(target); const propertyStash = getOrCreateEmptyPropertyStash( target, @@ -108,7 +108,7 @@ export function property ( } } -function getDefaultFromInitializer (initializer: Initializer) { +function getDefaultFromInitializer (initializer: Initializer): unknown { let value: unknown; try { value = initializer(); @@ -126,7 +126,7 @@ function getDefaultFromInitializer (initializer: Initializer) { } } -function extractActualDefaultValues (classConstructor: new () => unknown) { +function extractActualDefaultValues (classConstructor: new () => unknown): unknown { let dummyObj: unknown; try { // eslint-disable-next-line new-cap @@ -192,7 +192,7 @@ function mergePropertyOptions ( propertyKey: Parameters[1], options, descriptorOrInitializer: Parameters[2] | undefined, -) { +): void { let fullOptions; const isGetset = descriptorOrInitializer && typeof descriptorOrInitializer !== 'function' && (descriptorOrInitializer.get || descriptorOrInitializer.set); @@ -246,7 +246,7 @@ function setDefaultValue ( classConstructor: new () => T, propertyKey: PropertyKey, descriptorOrInitializer: BabelPropertyDecoratorDescriptor | Initializer | undefined | null, -) { +): void { if (descriptorOrInitializer !== undefined) { if (typeof descriptorOrInitializer === 'function') { propertyStash.default = getDefaultFromInitializer(descriptorOrInitializer); diff --git a/cocos/core/data/decorators/serializable.ts b/cocos/core/data/decorators/serializable.ts index 93f522f4659..7cb4dd0a8ab 100644 --- a/cocos/core/data/decorators/serializable.ts +++ b/cocos/core/data/decorators/serializable.ts @@ -46,7 +46,7 @@ export const serializable: LegacyPropertyDecorator = (target, propertyKey, descr * @engineInternal */ export function formerlySerializedAs (name: string): LegacyPropertyDecorator { - return (target, propertyKey, descriptorOrInitializer) => { + return (target, propertyKey, descriptorOrInitializer): void => { const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer); propertyStash.formerlySerializedAs = name; setImplicitSerializable(propertyStash); @@ -65,7 +65,7 @@ export const editorOnly: LegacyPropertyDecorator = (target, propertyKey, descrip setImplicitSerializable(propertyStash); }; -function setImplicitSerializable (propertyStash: PropertyStash) { +function setImplicitSerializable (propertyStash: PropertyStash): void { propertyStash.__internalFlags |= PropertyStashInternalFlag.IMPLICIT_SERIALIZABLE; } @@ -122,7 +122,7 @@ function setImplicitSerializable (propertyStash: PropertyStash) { export const uniquelyReferenced: ClassDecorator = !WITH_SERIALIZATION ? emptyDecorator // eslint-disable-next-line func-names, @typescript-eslint/ban-types - : function uniquelyReferenced (constructor: TFunction) { + : function uniquelyReferenced (constructor: TFunction): void { const metadata = getOrCreateSerializationMetadata(constructor); metadata.uniquelyReferenced = true; }; diff --git a/cocos/core/data/decorators/utils.ts b/cocos/core/data/decorators/utils.ts index e9d19b71207..ee22d90f91f 100644 --- a/cocos/core/data/decorators/utils.ts +++ b/cocos/core/data/decorators/utils.ts @@ -58,7 +58,7 @@ export const emptyDecorator: ClassDecorator & LegacyPropertyDecorator = () => {} * @zh * 一个忽略所有参数并且返回 `emptyDecorator` 的函数。 */ -export const emptyDecoratorFn = () => emptyDecorator; +export const emptyDecoratorFn = (): ClassDecorator & LegacyPropertyDecorator => emptyDecorator; /** * @en @@ -96,14 +96,14 @@ export function makeSmartClassDecorator ( // If no parameter specified return decorate(target); } else { - return function (constructor: TFunction) { + return function (constructor: TFunction): void | Function { return decorate(constructor, target); }; } } } -function writeEditorClassProperty (constructor: AnyFunction, propertyName: string, value: TValue) { +function writeEditorClassProperty (constructor: AnyFunction, propertyName: string, value: TValue): void { const cache = getClassCache(constructor, propertyName); if (cache) { const proto = getSubDict(cache, 'proto'); @@ -121,7 +121,7 @@ function writeEditorClassProperty (constructor: AnyFunction, propertyNam * @param propertyName The editor property. */ export function makeEditorClassDecoratorFn (propertyName: string): (value: TValue) => ClassDecorator { - return (value: TValue) => (constructor: TFunction) => { + return (value: TValue) => (constructor: TFunction): void => { writeEditorClassProperty(constructor, propertyName, value); }; } @@ -138,8 +138,8 @@ export function makeEditorClassDecoratorFn (propertyName: string): (valu * - 如果该装饰器是以一个参数的形式,即 `@x(arg0)` 的形式调用的,该属性将被设置为传入的参数值。 * @param propertyName The editor property. */ -export function makeSmartEditorClassDecorator (propertyName: string, defaultValue: TValue) { - return makeSmartClassDecorator((constructor, decoratedValue?: TValue) => { +export function makeSmartEditorClassDecorator (propertyName: string, defaultValue: TValue): ClassDecorator & ((arg?: TValue | undefined) => ClassDecorator) { + return makeSmartClassDecorator((constructor, decoratedValue?: TValue): void => { writeEditorClassProperty(constructor, propertyName, (defaultValue !== undefined) ? defaultValue : decoratedValue); }); } @@ -147,7 +147,7 @@ export function makeSmartEditorClassDecorator (propertyName: string, def // caches for class construction export const CACHE_KEY = '__ccclassCache__'; -export function getClassCache (ctor, decoratorName?) { +export function getClassCache (ctor, decoratorName?): any { if (DEV && CCClass._isCCClass(ctor)) { error('`@%s` should be used after @ccclass for class "%s"', decoratorName, getClassName(ctor)); return null; diff --git a/cocos/core/data/editor-extendable.ts b/cocos/core/data/editor-extendable.ts index 38a8cf6f59b..f5605ea9c0b 100644 --- a/cocos/core/data/editor-extendable.ts +++ b/cocos/core/data/editor-extendable.ts @@ -39,7 +39,7 @@ import { assertIsTrue } from './utils/asserts'; * @param className Assign an optional cc class name. If the base class is not cc class, this param is required. * @returns The mixin class. */ -export function EditorExtendableMixin (Base: new (...args: any[]) => T, className?: string) { +export function EditorExtendableMixin (Base: new (...args: any[]) => T, className?: string): new (...args: any[]) => EditorExtendableObject { return editorExtendableInternal(Base); } @@ -57,12 +57,12 @@ export type EditorExtendable = InstanceType; // So we have to use its literal value below. assertIsTrue(editorExtrasTag === '__editorExtras__', 'editorExtrasTag needs to be updated.'); -// eslint-disable-next-line @typescript-eslint/ban-types -function editorExtendableInternal (Base?: (new (...args: any[]) => T), className?: string) { - type ResultType = new (...args: any[]) => (T & EditorExtendableObject); +type ResultType = new (...args: any[]) => (T & EditorExtendableObject); +// eslint-disable-next-line @typescript-eslint/ban-types +function editorExtendableInternal (Base?: (new (...args: any[]) => T), className?: string): new (...args: any[]) => EditorExtendableObject { if (!EDITOR) { - return (Base ?? Empty) as unknown as ResultType; + return (Base ?? Empty) as unknown as ResultType; } let name: string; @@ -98,5 +98,5 @@ function editorExtendableInternal (Base?: (new (...args: any[]) => T), classN EditorExtendable = C; } - return EditorExtendable as unknown as ResultType; + return EditorExtendable as unknown as ResultType; } diff --git a/cocos/core/data/garbage-collection.ts b/cocos/core/data/garbage-collection.ts index 7aa70e75af9..d2de7650448 100644 --- a/cocos/core/data/garbage-collection.ts +++ b/cocos/core/data/garbage-collection.ts @@ -38,7 +38,7 @@ class GarbageCollectionManager { if (EDITOR && this._finalizationRegistry) { const token = {}; const proxy = new Proxy(gcObject, { - get (target, property, receiver) { + get (target, property, receiver): unknown { if (property === targetSymbol) { return target; } @@ -46,13 +46,13 @@ class GarbageCollectionManager { if (typeof val === 'function' && property !== 'constructor') { const original = val; // NOTE: fix error - 'this' implicitly has type 'any' because it does not have a type annotation. - val = function newFunc (this: any) { + val = function newFunc (this: any): unknown { return original.apply(this[targetSymbol], arguments) as unknown; }; } return val as unknown; }, - set (target, prop, value, receiver) { + set (target, prop, value, receiver): true { target[prop] = value; return true; }, @@ -65,10 +65,10 @@ class GarbageCollectionManager { } } - public init () { + public init (): void { } - private finalizationRegistryCallback (token: any) { + private finalizationRegistryCallback (token: any): void { const gcObject = this._gcObjects.get(token); if (gcObject) { this._gcObjects.delete(token); @@ -77,7 +77,7 @@ class GarbageCollectionManager { this._finalizationRegistry!.unregister(token); } - public destroy () { + public destroy (): void { } } diff --git a/cocos/core/data/gc-object.ts b/cocos/core/data/gc-object.ts index dd73447291f..845cf662a43 100644 --- a/cocos/core/data/gc-object.ts +++ b/cocos/core/data/gc-object.ts @@ -29,5 +29,5 @@ export class GCObject { return garbageCollectionManager.registerGCObject(this); } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.ts index ce13531ff00..0554698907e 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -71,7 +71,7 @@ const AllHideMasks = DontSave | EditorOnly | LockedInEditor | HideInHierarchy; const objectsToDestroy: any = []; let deferredDestroyTimer: number | null = null; -function compileDestruct (obj, ctor) { +function compileDestruct (obj, ctor): Function { const shouldSkipId = obj instanceof legacyCC.Node || obj instanceof legacyCC.Component; const idToSkip = shouldSkipId ? '_id' : null; @@ -148,7 +148,7 @@ function compileDestruct (obj, ctor) { // eslint-disable-next-line @typescript-eslint/no-implied-eval,no-new-func return Function('o', func); } else { - return (o) => { + return (o): void => { for (const _key in propsToReset) { o[_key] = propsToReset[_key]; } @@ -164,7 +164,7 @@ function compileDestruct (obj, ctor) { * @private */ class CCObject implements EditorExtendableObject { - public static _deferredDestroy () { + public static _deferredDestroy (): void { const deleteCount = objectsToDestroy.length; for (let i = 0; i < deleteCount; ++i) { const obj = objectsToDestroy[i]; @@ -226,7 +226,7 @@ class CCObject implements EditorExtendableObject { * obj.name = "New Obj"; * ``` */ - get name () { + get name (): string { return this._name; } set name (value) { @@ -241,7 +241,7 @@ class CCObject implements EditorExtendableObject { const flags = hideFlags & CCObject.Flags.AllHideMasks; this._objFlags = (this._objFlags & ~CCObject.Flags.AllHideMasks) | flags; } - public get hideFlags () { + public get hideFlags (): CCObject.Flags { return this._objFlags & CCObject.Flags.AllHideMasks; } @@ -345,7 +345,7 @@ class CCObject implements EditorExtendableObject { * } * ``` */ - public _destruct () { + public _destruct (): void { const ctor: any = this.constructor; let destruct = ctor.__destruct__; if (!destruct) { @@ -358,7 +358,7 @@ class CCObject implements EditorExtendableObject { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _destroyImmediate () { + public _destroyImmediate (): void { if (this._objFlags & Destroyed) { errorID(5000); return; @@ -414,7 +414,7 @@ if (EDITOR || TEST) { * TODO: this is a dynamic inject method, should be define in class * issue: https://github.com/cocos/cocos-engine/issues/14643 */ - (prototype as any).realDestroyInEditor = function () { + (prototype as any).realDestroyInEditor = function (): void { if (!(this._objFlags & Destroyed)) { warnID(5001); return; @@ -620,7 +620,7 @@ declare namespace CCObject { * @return @en Whether it is a CCObject boolean value. @zh 是否为CCObject的布尔值。 * @engineInternal */ -export function isCCObject (object: any) { +export function isCCObject (object: any): boolean { return object instanceof CCObject; } @@ -653,7 +653,7 @@ export function isCCObject (object: any) { * log(isValid(node)); // false, destroyed in the end of last frame * ``` */ -export function isValid (value: any, strictMode?: boolean) { +export function isValid (value: any, strictMode?: boolean): boolean { if (typeof value === 'object') { return !!value && !(value._objFlags & (strictMode ? (Destroyed | ToDestroy) : Destroyed)); } else { diff --git a/cocos/core/data/utils/asserts.ts b/cocos/core/data/utils/asserts.ts index b85f31229d9..8a878e7c1f2 100644 --- a/cocos/core/data/utils/asserts.ts +++ b/cocos/core/data/utils/asserts.ts @@ -52,6 +52,6 @@ export function assertIsTrue (expr: unknown, message?: string): asserts expr { * Assets that the index is valid. * @engineInternal */ -export function assertsArrayIndex (array: T[], index: number) { +export function assertsArrayIndex (array: T[], index: number): void { assertIsTrue(index >= 0 && index < array.length, `Array index ${index} out of bounds: [0, ${array.length})`); } diff --git a/cocos/core/data/utils/attribute.ts b/cocos/core/data/utils/attribute.ts index 5316d4196ec..de9c7f55219 100644 --- a/cocos/core/data/utils/attribute.ts +++ b/cocos/core/data/utils/attribute.ts @@ -31,7 +31,7 @@ import { legacyCC } from '../../global-exports'; export const DELIMETER = '$_$'; -export function createAttrsSingle (owner: Object, superAttrs?: any) { +export function createAttrsSingle (owner: Object, superAttrs?: any): any { const attrs = superAttrs ? Object.create(superAttrs) : {}; value(owner, '__attrs__', attrs); return attrs; @@ -40,7 +40,7 @@ export function createAttrsSingle (owner: Object, superAttrs?: any) { /** * @param subclass Should not have '__attrs__'. */ -export function createAttrs (subclass: any) { +export function createAttrs (subclass: any): any { if (typeof subclass !== 'function') { // attributes only in instance const instance = subclass; @@ -86,11 +86,11 @@ export function attr (constructor: any, propertyName: string): { [attributeName: /** * Returns a read-only meta-object. */ -export function getClassAttrs (constructor: any) { +export function getClassAttrs (constructor: any): any { return (constructor.hasOwnProperty('__attrs__') && constructor.__attrs__) || createAttrs(constructor); } -export function setClassAttr (ctor, propName, key, value) { +export function setClassAttr (ctor, propName, key, value): void { getClassAttrs(ctor)[propName + DELIMETER + key] = value; } @@ -104,7 +104,7 @@ export class PrimitiveType { this.default = defaultValue; } - public toString () { + public toString (): string { return this.name; } } @@ -205,7 +205,7 @@ legacyCC.CCString = CCString; // Ensures the type matches its default value export function getTypeChecker_ET (type: string, attributeName: string) { - return function (constructor: Function, mainPropertyName: string) { + return function (constructor: Function, mainPropertyName: string): void { const propInfo = `"${getClassName(constructor)}.${mainPropertyName}"`; const mainPropAttrs = attr(constructor, mainPropertyName); let mainPropAttrsType = mainPropAttrs.type; @@ -257,7 +257,7 @@ export function getTypeChecker_ET (type: string, attributeName: string) { // Ensures the type matches its default value export function getObjTypeChecker_ET (typeCtor) { - return function (classCtor, mainPropName) { + return function (classCtor, mainPropName): void { getTypeChecker_ET('Object', 'type')(classCtor, mainPropName); // check ValueType const defaultDef = getClassAttrs(classCtor)[`${mainPropName + DELIMETER}default`]; diff --git a/cocos/core/data/utils/compact-value-type-array.ts b/cocos/core/data/utils/compact-value-type-array.ts index 54f41685fc1..7ef55c50be1 100644 --- a/cocos/core/data/utils/compact-value-type-array.ts +++ b/cocos/core/data/utils/compact-value-type-array.ts @@ -44,11 +44,14 @@ const elementTypeBits = 3; export type StorageUnitElementType = number; -export function combineStorageUnitElementType (unit: StorageUnit, elementType: ElementType) { +export function combineStorageUnitElementType (unit: StorageUnit, elementType: ElementType): number { return (elementType << elementTypeBits) + unit; } -export function extractStorageUnitElementType (combined: StorageUnitElementType) { +export function extractStorageUnitElementType (combined: StorageUnitElementType): { + storageUnit: number; + elementType: number; +} { return { storageUnit: ~(-1 << elementTypeBits) & combined, elementType: combined >> elementTypeBits, @@ -139,11 +142,11 @@ export class CompactValueTypeArray { } } -function getElementTraits (elementType: ElementType) { +function getElementTraits (elementType: ElementType): CompactTraits { return BuiltinElementTypeTraits[elementType]; } -function getStorageConstructor (unit: StorageUnit) { +function getStorageConstructor (unit: StorageUnit): TypedArrayConstructor { switch (unit) { case StorageUnit.Uint8: return Uint8Array; diff --git a/cocos/core/data/utils/compiler.ts b/cocos/core/data/utils/compiler.ts index 36013d8aa76..566c4204037 100644 --- a/cocos/core/data/utils/compiler.ts +++ b/cocos/core/data/utils/compiler.ts @@ -25,7 +25,7 @@ import { DEV } from 'internal:constants'; -function deepFlatten (strList, array) { +function deepFlatten (strList, array): void { for (const item of array) { if (Array.isArray(item)) { deepFlatten(strList, item); @@ -43,7 +43,7 @@ function deepFlatten (strList, array) { * * @engineInternal */ -export function flattenCodeArray (array) { +export function flattenCodeArray (array): string { const separator = DEV ? '\n' : ''; const strList = []; deepFlatten(strList, array); diff --git a/cocos/core/data/utils/preprocess-class.ts b/cocos/core/data/utils/preprocess-class.ts index 13a0cd82d79..b326e484a52 100644 --- a/cocos/core/data/utils/preprocess-class.ts +++ b/cocos/core/data/utils/preprocess-class.ts @@ -41,7 +41,7 @@ const SerializableAttrs = { /** * 预处理 notify 等扩展属性 */ -function parseNotify (val, propName, notify, properties) { +function parseNotify (val, propName, notify, properties): void { if (val.get || val.set) { if (DEV) { warnID(5500); @@ -53,10 +53,10 @@ function parseNotify (val, propName, notify, properties) { // (以 _ 开头将自动设置property 为 visible: false) const newKey = `_N$${propName}`; - val.get = function () { + val.get = function (): any { return this[newKey]; }; - val.set = function (value) { + val.set = function (value): void { const oldValue = this[newKey]; this[newKey] = value; notify.call(this, oldValue); @@ -80,7 +80,7 @@ function parseNotify (val, propName, notify, properties) { } } -function parseType (val, type, className, propName) { +function parseType (val, type, className, propName): void { const STATIC_CHECK = (EDITOR && DEV) || TEST; if (Array.isArray(type)) { @@ -142,7 +142,7 @@ function parseType (val, type, className, propName) { } } -function getBaseClassWherePropertyDefined_DEV (propName, cls) { +function getBaseClassWherePropertyDefined_DEV (propName, cls): any { if (DEV) { let res; for (; cls && cls.__props__ && cls.__props__.indexOf(propName) !== -1; cls = cls.$super) { @@ -155,7 +155,11 @@ function getBaseClassWherePropertyDefined_DEV (propName, cls) { } } -function _wrapOptions (isGetset: boolean, _default, type?: Function | Function[] | PrimitiveType) { +function _wrapOptions (isGetset: boolean, _default, type?: Function | Function[] | PrimitiveType): { + default?: any; + _short?: boolean | undefined; + type?: any; +} { const res: { default?: any, _short?: boolean, @@ -167,7 +171,11 @@ function _wrapOptions (isGetset: boolean, _default, type?: Function | Function[] return res; } -export function getFullFormOfProperty (options, isGetset) { +export function getFullFormOfProperty (options, isGetset): { + default?: any; + _short?: boolean | undefined; + type?: any; +} | null { const isLiteral = options && options.constructor === Object; if (!isLiteral) { if (Array.isArray(options) && options.length > 0) { @@ -184,7 +192,7 @@ export function getFullFormOfProperty (options, isGetset) { return null; } -export function preprocessAttrs (properties, className, cls) { +export function preprocessAttrs (properties, className, cls): void { for (const propName in properties) { let val = properties[propName]; const fullForm = getFullFormOfProperty(val, false); @@ -226,7 +234,7 @@ export function preprocessAttrs (properties, className, cls) { } const CALL_SUPER_DESTROY_REG_DEV = /\b\._super\b|destroy.*\.call\s*\(\s*\w+\s*[,|)]/; -export function doValidateMethodWithProps_DEV (func, funcName, className, cls, base) { +export function doValidateMethodWithProps_DEV (func, funcName, className, cls, base): false | undefined { if (cls.__props__ && cls.__props__.indexOf(funcName) >= 0) { // find class that defines this method as a property const baseClassName = js.getClassName(getBaseClassWherePropertyDefined_DEV(funcName, cls)); diff --git a/cocos/core/data/utils/requiring-frame.ts b/cocos/core/data/utils/requiring-frame.ts index 98dff14dbf1..826486db54e 100644 --- a/cocos/core/data/utils/requiring-frame.ts +++ b/cocos/core/data/utils/requiring-frame.ts @@ -31,7 +31,7 @@ import { legacyCC } from '../../global-exports'; */ let requiringFrames: any = []; // the requiring frame infos -export function push (module, uuid: string, script, importMeta?) { +export function push (module, uuid: string, script, importMeta?): void { if (script === undefined) { script = uuid; uuid = ''; @@ -46,7 +46,7 @@ export function push (module, uuid: string, script, importMeta?) { }); } -export function pop () { +export function pop (): void { const frameInfo = requiringFrames.pop(); // check exports const module = frameInfo.module; @@ -61,7 +61,7 @@ export function pop () { } } -export function peek () { +export function peek (): any { return requiringFrames[requiringFrames.length - 1]; } @@ -72,7 +72,7 @@ legacyCC._RF = { }; if (EDITOR) { - legacyCC._RF.reset = () => { + legacyCC._RF.reset = (): void => { requiringFrames = []; }; } diff --git a/cocos/core/deprecated.ts b/cocos/core/deprecated.ts index bf9f6451ed3..c6c6c4f5798 100644 --- a/cocos/core/deprecated.ts +++ b/cocos/core/deprecated.ts @@ -204,7 +204,7 @@ replaceProperty(Scheduler, 'Scheduler', [ { name: 'PRIORITY_SYSTEM', newName: 'System.Priority.SCHEDULER', - customGetter () { + customGetter (): number { return System.Priority.SCHEDULER; }, }, diff --git a/cocos/core/effect-settings.ts b/cocos/core/effect-settings.ts index 11843fb0a3b..580fb5b0074 100644 --- a/cocos/core/effect-settings.ts +++ b/cocos/core/effect-settings.ts @@ -45,11 +45,11 @@ export class EffectSettings { const xhr = new XMLHttpRequest(); xhr.open('GET', path); xhr.responseType = 'arraybuffer'; - xhr.onload = () => { + xhr.onload = (): void => { this._data = xhr.response; resolve(); }; - xhr.onerror = () => { + xhr.onerror = (): void => { reject(new Error('request effect settings failed!')); }; xhr.send(null); diff --git a/cocos/core/event/async-delegate.ts b/cocos/core/event/async-delegate.ts index 3bc2e2990a2..f1d31bd1567 100644 --- a/cocos/core/event/async-delegate.ts +++ b/cocos/core/event/async-delegate.ts @@ -60,7 +60,7 @@ export class AsyncDelegate (Promise | void) = * @en The callback to add, and will be invoked when this delegate is dispatching. * @zh 要添加的回调,并将在该委托调度时被调用。 */ - public add (callback: T) { + public add (callback: T): void { if (!this._delegates.includes(callback)) { this._delegates.push(callback); } @@ -75,7 +75,7 @@ export class AsyncDelegate (Promise | void) = * @param callback @en The callback to query. @zh 要查询的回调函数。 * @returns @en Whether the callback has been added. @zh 是否已经添加了回调。 */ - public hasListener (callback: T) { + public hasListener (callback: T): boolean { return this._delegates.includes(callback); } @@ -88,7 +88,7 @@ export class AsyncDelegate (Promise | void) = * * @param callback @en The callback to remove. @zh 要移除的某个回调。 */ - public remove (callback: T) { + public remove (callback: T): void { array.fastRemove(this._delegates, callback); } @@ -102,7 +102,7 @@ export class AsyncDelegate (Promise | void) = * @param args @en The parameters to be transferred to callback. @zh 传递给回调函数的参数。 * @returns @en The promise awaiting all async callback resolved. @zh 等待所有异步回调结束的 Promise 对象。 */ - public dispatch (...args: Parameters) { + public dispatch (...args: Parameters): Promise { return Promise.all(this._delegates.map((func) => func(...arguments)).filter(Boolean)); } } diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index 573f75b5b96..34a0e1876ad 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -31,26 +31,26 @@ import { legacyCC } from '../global-exports'; const fastRemoveAt = array.fastRemoveAt; -function empty () { } +function empty (): void { } class CallbackInfo { public callback: AnyFunction = empty; public target: unknown | undefined = undefined; public once = false; - public set (callback: AnyFunction, target?: unknown, once?: boolean) { + public set (callback: AnyFunction, target?: unknown, once?: boolean): void { this.callback = callback || empty; this.target = target; this.once = !!once; } - public reset () { + public reset (): void { this.target = undefined; this.callback = empty; this.once = false; } - public check () { + public check (): boolean { // Validation if (isCCObject(this.target) && !isValid(this.target, true)) { return false; @@ -76,7 +76,7 @@ export class CallbackList { * * @param cb - The callback to be removed */ - public removeByCallback (cb: AnyFunction) { + public removeByCallback (cb: AnyFunction): void { for (let i = 0; i < this.callbackInfos.length; ++i) { const info = this.callbackInfos[i]; if (info && info.callback === cb) { @@ -92,7 +92,7 @@ export class CallbackList { * @en Remove the event listeners with the given target from the list * @param target */ - public removeByTarget (target: unknown) { + public removeByTarget (target: unknown): void { for (let i = 0; i < this.callbackInfos.length; ++i) { const info = this.callbackInfos[i]; if (info && info.target === target) { @@ -109,7 +109,7 @@ export class CallbackList { * @en Remove the event listener at the given index * @param index */ - public cancel (index: number) { + public cancel (index: number): void { const info = this.callbackInfos[index]; if (info) { info.reset(); @@ -127,7 +127,7 @@ export class CallbackList { * @zh 注销所有事件。 * @en Cancel all event listeners */ - public cancelAll () { + public cancelAll (): void { for (let i = 0; i < this.callbackInfos.length; i++) { const info = this.callbackInfos[i]; if (info) { @@ -143,7 +143,7 @@ export class CallbackList { * @zh 立即删除所有取消的回调。(在移除过程中会更加紧凑的排列数组) * @en Delete all canceled callbacks and compact array */ - public purgeCanceled () { + public purgeCanceled (): void { for (let i = this.callbackInfos.length - 1; i >= 0; --i) { const info = this.callbackInfos[i]; if (!info) { @@ -157,7 +157,7 @@ export class CallbackList { * @zh 清除并重置所有数据。 * @en Clear all data */ - public clear () { + public clear (): void { this.cancelAll(); this.callbackInfos.length = 0; this.isInvoking = false; @@ -195,7 +195,7 @@ export class CallbacksInvoker { * @param target - Callback callee * @param once - Whether invoke the callback only once (and remove it) */ - public on (key: EventTypeClass, callback: AnyFunction, target?: unknown, once?: boolean) { + public on (key: EventTypeClass, callback: AnyFunction, target?: unknown, once?: boolean): AnyFunction { if (!this.hasEventListener(key, callback, target)) { let list = this._callbackTable[key]; if (!list) { @@ -215,7 +215,7 @@ export class CallbacksInvoker { * @param callback - Callback function when event triggered * @param target - Callback callee */ - public hasEventListener (key: EventTypeClass, callback?: AnyFunction, target?: unknown) { + public hasEventListener (key: EventTypeClass, callback?: AnyFunction, target?: unknown): boolean { const list = this._callbackTable && this._callbackTable[key]; if (!list) { return false; @@ -251,7 +251,7 @@ export class CallbacksInvoker { * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target * @param keyOrTarget - The event type or target with which the listeners will be removed */ - public removeAll (keyOrTarget: EventTypeClass | unknown) { + public removeAll (keyOrTarget: EventTypeClass | unknown): void { const type = typeof keyOrTarget; if (type === 'string' || type === 'number') { // remove by key @@ -291,7 +291,7 @@ export class CallbacksInvoker { * @param callback - The callback function of the event listener, if absent all event listeners for the given type will be removed * @param target - The callback callee of the event listener */ - public off (key: EventTypeClass, callback?: AnyFunction, target?: unknown) { + public off (key: EventTypeClass, callback?: AnyFunction, target?: unknown): void { const list = this._callbackTable && this._callbackTable[key]; if (list) { const infos = list.callbackInfos; @@ -320,7 +320,7 @@ export class CallbacksInvoker { * @param arg3 - The fourth argument to be passed to the callback * @param arg4 - The fifth argument to be passed to the callback */ - public emit (key: EventTypeClass, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) { + public emit (key: EventTypeClass, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void { const list: CallbackList = this._callbackTable && this._callbackTable[key]!; if (list) { const rootInvoker = !list.isInvoking; @@ -360,7 +360,7 @@ export class CallbacksInvoker { /** * 移除所有回调。 */ - public clear () { + public clear (): void { for (const key in this._callbackTable) { const list = this._callbackTable[key]; if (list) { @@ -374,7 +374,7 @@ export class CallbacksInvoker { /** * @engineInternal */ - public _registerOffCallback (cb: () => void) { + public _registerOffCallback (cb: () => void): void { this._offCallback = cb; } } diff --git a/cocos/core/event/event-target-factory.ts b/cocos/core/event/event-target-factory.ts index 5f15399ffcc..c25e9fe854b 100644 --- a/cocos/core/event/event-target-factory.ts +++ b/cocos/core/event/event-target-factory.ts @@ -28,7 +28,7 @@ import { EventTarget } from './event-target'; * * @engineInternal */ -export function applyMixins (derivedCtor: any, baseCtors: any[]) { +export function applyMixins (derivedCtor: any, baseCtors: any[]): void { baseCtors.forEach((baseCtor) => { Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => { if (name !== 'constructor') { diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts index 4ec8ff82abc..220203b228a 100644 --- a/cocos/core/event/eventify.ts +++ b/cocos/core/event/eventify.ts @@ -153,11 +153,11 @@ export function Eventify (base: Constructor): Constructor void> (type: EventType, callback: Callback, target?: any) { + public once void> (type: EventType, callback: Callback, target?: any): Callback { return this.on(type, callback, target, true) as Callback; } - public targetOff (typeOrTarget: any) { + public targetOff (typeOrTarget: any): void { this.removeAll(typeOrTarget); } } diff --git a/cocos/core/geometry/aabb.ts b/cocos/core/geometry/aabb.ts index 8c05c908ac7..9af5f66330d 100644 --- a/cocos/core/geometry/aabb.ts +++ b/cocos/core/geometry/aabb.ts @@ -35,7 +35,7 @@ const _v3_tmp4 = new Vec3(); const _m3_tmp = new Mat3(); // https://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/ -const transform_extent_m4 = (out: Vec3, extent: Vec3, m4: Mat4 | Readonly) => { +const transform_extent_m4 = (out: Vec3, extent: Vec3, m4: Mat4 | Readonly): void => { _m3_tmp.m00 = Math.abs(m4.m00); _m3_tmp.m01 = Math.abs(m4.m01); _m3_tmp.m02 = Math.abs(m4.m02); _m3_tmp.m03 = Math.abs(m4.m04); _m3_tmp.m04 = Math.abs(m4.m05); _m3_tmp.m05 = Math.abs(m4.m06); _m3_tmp.m06 = Math.abs(m4.m08); _m3_tmp.m07 = Math.abs(m4.m09); _m3_tmp.m08 = Math.abs(m4.m10); @@ -65,7 +65,7 @@ export class AABB { * @param hl @zh AABB 长度的一半。 @en Half the length of the AABB. * @returns @zh 返回新创建的 AABB 实例。 @en A new instance of AABB. */ - public static create (px?: number, py?: number, pz?: number, hw?: number, hh?: number, hl?: number) { + public static create (px?: number, py?: number, pz?: number, hw?: number, hh?: number, hl?: number): AABB { return new AABB(px, py, pz, hw, hh, hl); } @@ -77,7 +77,7 @@ export class AABB { * @param a @zh 克隆的目标。 @en The target object to be cloned. * @returns @zh 克隆出的 AABB 实例。@en The cloned AABB instance. */ - public static clone (a: AABB | Readonly) { + public static clone (a: AABB | Readonly): AABB { return new AABB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z); } @@ -165,7 +165,7 @@ export class AABB { * @param a @zh 输入的 AABB,只读参数。 @en The input AABB,it's readonly. * @returns @zh 接受操作的包围球 `out` 的引用. @en The reference to the first parameter `out`. */ - public static toBoundingSphere (out: Sphere, a: AABB | Readonly) { + public static toBoundingSphere (out: Sphere, a: AABB | Readonly): Sphere { out.center.set(a.center); out.radius = a.halfExtents.length(); return out; @@ -209,7 +209,7 @@ export class AABB { * @zh * 获取此形状的类型。 */ - get type () { + get type (): number { return this._type; } @@ -229,7 +229,7 @@ export class AABB { * @param minPos @zh 存放此 AABB 最小点的向量。 @en The minimum position of the AABB to be stored to. * @param maxPos @zh 存放此 AABB 最大点的向量。 @en The maximum position of the AABB to be stored to. */ - public getBoundary (minPos: IVec3Like, maxPos: IVec3Like) { + public getBoundary (minPos: IVec3Like, maxPos: IVec3Like): void { Vec3.subtract(minPos, this.center, this.halfExtents); Vec3.add(maxPos, this.center, this.halfExtents); } @@ -245,7 +245,7 @@ export class AABB { * @param scale @zh 变换的缩放部分。 @en 3d-vector scale. * @param out @zh 存储结果的 AABB。 @en The output AABB. */ - public transform (m: Mat4, pos: Vec3 | null, rot: Quat | null, scale: Vec3 | null, out: AABB) { + public transform (m: Mat4, pos: Vec3 | null, rot: Quat | null, scale: Vec3 | null, out: AABB): void { Vec3.transformMat4(out.center, this.center, m); transform_extent_m4(out.halfExtents, this.halfExtents, m); } @@ -278,7 +278,7 @@ export class AABB { * @zh 合并一个顶点到当前 AABB 中。 * @param point @zh 3D 世界中某一个位置的顶点。 @en A point in 3D space. */ - public mergePoint (point: IVec3) { + public mergePoint (point: IVec3): void { // _v3_tmp is min pos // _v3_tmp2 is max pos this.getBoundary(_v3_tmp, _v3_tmp2); @@ -300,7 +300,7 @@ export class AABB { * @zh 合并一系列顶点到当前 AABB 中。 * @param points @zh 3D 世界中的顶点列表。 @en A list of points in 3D space. */ - public mergePoints (points: IVec3[]) { + public mergePoints (points: IVec3[]): void { if (points.length < 1) { return; } for (let i = 0; i < points.length; i++) { this.mergePoint(points[i]); @@ -312,7 +312,7 @@ export class AABB { * @zh 合并一个截头锥体的所有顶点到此 AABB 中。 * @param frustum @zh 输入的截头锥体 @en The frustum object. */ - public mergeFrustum (frustum: Frustum | Readonly) { + public mergeFrustum (frustum: Frustum | Readonly): void { this.mergePoints(frustum.vertices); } } diff --git a/cocos/core/geometry/capsule.ts b/cocos/core/geometry/capsule.ts index 0e3b4f2cf6a..a40028ef946 100644 --- a/cocos/core/geometry/capsule.ts +++ b/cocos/core/geometry/capsule.ts @@ -39,7 +39,7 @@ export class Capsule { * @zh * 获取此形状的类型,值固定为 `enums.SHAPE_CAPSULE`。 */ - get type () { + get type (): number { return this._type; } @@ -124,7 +124,7 @@ export class Capsule { * @zh * 使用 4x4 矩阵和 RTS 变换此胶囊体。 */ - transform (m: Mat4, pos: IVec3Like, rot: IQuatLike, scale: IVec3Like, out: Capsule) { + transform (m: Mat4, pos: IVec3Like, rot: IQuatLike, scale: IVec3Like, out: Capsule): void { const ws = scale; const s = absMaxComponent(ws as Vec3); out.radius = this.radius * Math.abs(s); @@ -145,7 +145,7 @@ export class Capsule { * @zh * 更新缓存。 */ - updateCache () { + updateCache (): void { this.updateLocalCenter(); Vec3.transformQuat(this.ellipseCenter0, this.ellipseCenter0, this.rotation); Vec3.transformQuat(this.ellipseCenter1, this.ellipseCenter1, this.rotation); @@ -159,7 +159,7 @@ export class Capsule { * @zh * 更新中心点信息。 */ - updateLocalCenter () { + updateLocalCenter (): void { const halfHeight = this.halfHeight; const axis = this.axis; switch (axis) { diff --git a/cocos/core/geometry/curve.ts b/cocos/core/geometry/curve.ts index 85df56ac5d0..9580e510722 100644 --- a/cocos/core/geometry/curve.ts +++ b/cocos/core/geometry/curve.ts @@ -82,7 +82,7 @@ export class OptimizedKey { this.coefficient = new Float32Array(4); } - public evaluate (T: number) { + public evaluate (T: number): number { const t = T - this.time; return evalOptCurve(t, this.coefficient); } @@ -91,7 +91,7 @@ export class OptimizedKey { /** * @engineInternal */ -export function evalOptCurve (t: number, coefs: Float32Array | number[]) { +export function evalOptCurve (t: number, coefs: Float32Array | number[]): number { return (t * (t * (t * coefs[0] + coefs[1]) + coefs[2])) + coefs[3]; } @@ -120,7 +120,7 @@ export class AnimationCurve { * For internal usage only. * @internal */ - get _internalCurve () { + get _internalCurve (): RealCurve { return this._curve; } @@ -130,7 +130,7 @@ export class AnimationCurve { * @zh * 曲线的关键帧。 */ - get keyFrames () { + get keyFrames (): Keyframe[] { return Array.from(this._curve.keyframes()).map(([time, value]) => { const legacyKeyframe = new Keyframe(); legacyKeyframe.time = time; @@ -159,7 +159,7 @@ export class AnimationCurve { * @zh * 当采样时间超出左端时采用的循环模式[[AnimationClip.WrapMode]]。 */ - get preWrapMode () { + get preWrapMode (): WrapModeMask { return toLegacyWrapMode(this._curve.preExtrapolation); } @@ -173,7 +173,7 @@ export class AnimationCurve { * @zh * 当采样时间超出右端时采用的循环模式[[AnimationClip.WrapMode]]。 */ - get postWrapMode () { + get postWrapMode (): WrapModeMask { return toLegacyWrapMode(this._curve.postExtrapolation); } @@ -220,7 +220,7 @@ export class AnimationCurve { * 添加一个关键帧。 * @param keyFrame @en A keyframe. @zh 关键帧。 */ - public addKey (keyFrame: Keyframe | null) { + public addKey (keyFrame: Keyframe | null): void { if (!keyFrame) { this._curve.clear(); } else { @@ -237,7 +237,7 @@ export class AnimationCurve { * @ignore * @param time */ - public evaluate_slow (time: number) { + public evaluate_slow (time: number): number { return this._curve.evaluate(time); } @@ -248,7 +248,7 @@ export class AnimationCurve { * 计算给定时间点的曲线插值。 * @param time @en The time. @zh 时间。 */ - public evaluate (time: number) { + public evaluate (time: number): number { const { cachedKey, _curve: curve } = this; const nKeyframes = curve.keyFramesCount; const lastKeyframeIndex = nKeyframes - 1; @@ -283,7 +283,7 @@ export class AnimationCurve { * @param leftIndex * @param rightIndex */ - public calcOptimizedKey (optKey: OptimizedKey, leftIndex: number, rightIndex: number) { + public calcOptimizedKey (optKey: OptimizedKey, leftIndex: number, rightIndex: number): void { const lhsTime = this._curve.getKeyframeTime(leftIndex); const rhsTime = this._curve.getKeyframeTime(rightIndex); const { value: lhsValue, leftTangent: lhsOutTangent } = this._curve.getKeyframeValue(leftIndex); @@ -309,7 +309,7 @@ export class AnimationCurve { * @param optKey * @param t */ - private findIndex (optKey: OptimizedKey, t: number) { + private findIndex (optKey: OptimizedKey, t: number): number { const { _curve: curve } = this; const nKeyframes = curve.keyFramesCount; const cachedIndex = optKey.index; @@ -388,7 +388,7 @@ function toLegacyWrapMode (extrapolationMode: ExtrapolationMode): WrapModeMask { * Same as but more effective than `new LegacyCurve()._internalCurve`. * @engineInternal */ -export function constructLegacyCurveAndConvert () { +export function constructLegacyCurveAndConvert (): RealCurve { const curve = new RealCurve(); curve.assignSorted([ [0.0, { interpolationMode: RealInterpolationMode.CUBIC, value: 1.0 }], diff --git a/cocos/core/geometry/deprecated-3.0.0.ts b/cocos/core/geometry/deprecated-3.0.0.ts index 759153c4e04..fd3b9a7b434 100644 --- a/cocos/core/geometry/deprecated-3.0.0.ts +++ b/cocos/core/geometry/deprecated-3.0.0.ts @@ -170,7 +170,7 @@ replaceProperty(intersect, 'intersect', [ }, ]); -function deprecatedClassMessage (oldClassName: string, newClassName) { +function deprecatedClassMessage (oldClassName: string, newClassName): void { console.warn(`${oldClassName} is deprecated, please use ${newClassName} instead.`); } diff --git a/cocos/core/geometry/distance.ts b/cocos/core/geometry/distance.ts index ce1b8d360f7..3495695c412 100644 --- a/cocos/core/geometry/distance.ts +++ b/cocos/core/geometry/distance.ts @@ -45,7 +45,7 @@ const e = new Array(3); * @param plane @en The target plane. @zh 目标平面。 * @returns @en The distance between the point and the plane. @zh 点和平面之间的距离。 */ -export function point_plane (point: Vec3, plane_: Plane) { +export function point_plane (point: Vec3, plane_: Plane): number { return Vec3.dot(plane_.n, point) - plane_.d; } @@ -59,7 +59,7 @@ export function point_plane (point: Vec3, plane_: Plane) { * @param plane @en The target plane. @zh 平面。 * @returns @en The result of the closest point, same as the `out` parameter. @zh 存储最近点的向量,与 `out` 参数为同一个对象。 */ -export function pt_point_plane (out: Vec3, point: Vec3, plane_: Plane) { +export function pt_point_plane (out: Vec3, point: Vec3, plane_: Plane): Vec3 { const t = point_plane(point, plane_); return Vec3.subtract(out, point, Vec3.multiplyScalar(out, plane_.n, t)); } @@ -148,7 +148,7 @@ export function pt_point_obb (out: Vec3, point: Vec3, obb_: OBB): Vec3 { * @param linePointA @en Point A on the line. @zh 线上的某点 A。 * @param linePointB @en Point B on the line. @zh 线上的某点 B。 */ -export function pt_point_line (out: Vec3, point: Vec3, linePointA: Vec3, linePointB: Vec3) { +export function pt_point_line (out: Vec3, point: Vec3, linePointA: Vec3, linePointB: Vec3): void { Vec3.subtract(X, linePointA, linePointB); const dir = X.clone(); const dirSquaredLength = Vec3.lengthSqr(dir); diff --git a/cocos/core/geometry/frustum.ts b/cocos/core/geometry/frustum.ts index 3c55b818d9e..72d6a27eba9 100644 --- a/cocos/core/geometry/frustum.ts +++ b/cocos/core/geometry/frustum.ts @@ -59,7 +59,7 @@ export class Frustum { * @param transform @en The transform matrix of the frustum. @zh 正交视锥体的变换矩阵。 * @returns @en The result frustum, same as the `out` parameter. @zh 存储结果的视锥体,与 `out` 参数为同一个对象。 */ - public static createOrthographic (out: Frustum, width: number, height: number, near: number, far: number, transform: Mat4) { + public static createOrthographic (out: Frustum, width: number, height: number, near: number, far: number, transform: Mat4): void { const halfWidth = width / 2; const halfHeight = height / 2; Vec3.set(_temp_v3, halfWidth, halfHeight, -near); @@ -95,7 +95,7 @@ export class Frustum { * * @deprecated since v3.8.0, please use [[createOrthographic]] instead. */ - public static createOrtho (out: Frustum, width: number, height: number, near: number, far: number, transform: Mat4) { + public static createOrtho (out: Frustum, width: number, height: number, near: number, far: number, transform: Mat4): void { return Frustum.createOrthographic(out, width, height, near, far, transform); } @@ -109,7 +109,7 @@ export class Frustum { * @param transform @en The transform matrix. @zh 变换矩阵。 * @returns @en The result frustum, same as the `out` parameter. @zh 存储结果的视锥体,与 `out` 参数为同一个对象。 */ - public static createPerspective (out: Frustum, aspect: number, fov: number, near: number, far: number, transform: Mat4) { + public static createPerspective (out: Frustum, aspect: number, fov: number, near: number, far: number, transform: Mat4): void { const h = Math.tan(fov * 0.5); const w = h * aspect; _nearTemp.set(near * w, near * h, near); @@ -178,7 +178,7 @@ export class Frustum { * * @deprecated since v3.8.0, please use [[createPerspective]] instead. */ - public split (start: number, end: number, aspect: number, fov: number, m: Mat4) { + public split (start: number, end: number, aspect: number, fov: number, m: Mat4): void { return Frustum.createPerspective(this, aspect, fov, start, end, m); } @@ -244,7 +244,7 @@ export class Frustum { * 获取形状的类型。值可能为 `enums.SHAPE_FRUSTUM_ACCURATE` 或 `enums.SHAPE_FRUSTUM`。 * @readonly */ - get type () { + get type (): number { return this._type; } @@ -287,7 +287,7 @@ export class Frustum { * @param m @en The view-projection matrix. @zh 视图投影矩阵。 * @param inv @en The inverse view-projection matrix. @zh 视图投影逆矩阵。 */ - public update (m: Mat4, inv: Mat4) { + public update (m: Mat4, inv: Mat4): void { // RTR4, ch. 22.14.1, p. 983 // extract frustum planes from view-proj matrix. @@ -331,7 +331,7 @@ export class Frustum { * 变换此视锥体。 * @param mat @en The transform matrix. @zh 变换矩阵。 */ - public transform (mat: Mat4) { + public transform (mat: Mat4): void { for (let i = 0; i < 8; i++) { Vec3.transformMat4(this.vertices[i], this.vertices[i], mat); } @@ -342,7 +342,7 @@ export class Frustum { * @en Makes the frustum empty, all vertices will be zero values. * @zh 置空此视锥体,所有顶点将被赋值为 0。 */ - public zero () { + public zero (): void { // reset to initial state for (let i = 0; i < 8; i++) { this.vertices[i].set(0.0, 0.0, 0.0); @@ -356,7 +356,7 @@ export class Frustum { * @en Updates all six planes of the frustum. * @zh 更新视锥体的所有面数据。 */ - public updatePlanes () { + public updatePlanes (): void { // left plane Plane.fromPoints(this.planes[0], this.vertices[1], this.vertices[6], this.vertices[5]); // right plane diff --git a/cocos/core/geometry/geometry-native-ext.ts b/cocos/core/geometry/geometry-native-ext.ts index fc623b71597..c54f7ad8fdf 100644 --- a/cocos/core/geometry/geometry-native-ext.ts +++ b/cocos/core/geometry/geometry-native-ext.ts @@ -34,7 +34,7 @@ import { Frustum } from './frustum'; /** * cache jsb attributes in js, reduce cross language invokations. */ -function cacheProperty (ctor: Constructor, property: string) { +function cacheProperty (ctor: Constructor, property: string): void { const propDesc = Object.getOwnPropertyDescriptor(ctor.prototype, property); const propCacheKey = `_$cache_${property}`; const propRealKey = `_$_${property}`; @@ -59,9 +59,9 @@ function cacheProperty (ctor: Constructor, property: string) { /** * cache native object's `underlyingData()` result in __data */ -function cacheUnderlyingData (ctor: Constructor) { +function cacheUnderlyingData (ctor: Constructor): void { // eslint-disable-next-line func-names - ctor.prototype._arraybuffer = function () { + ctor.prototype._arraybuffer = function (): ArrayBuffer { if (!this.__data) { this.__data = this.underlyingData(); } @@ -83,7 +83,7 @@ interface FieldDesc { /** * define accessor for attr, read/write directly to the underlyingData as Float32Array[1] */ -const defineAttrFloat = (kls: Constructor, attr: string) => { +const defineAttrFloat = (kls: Constructor, attr: string): void => { // __nativeFields__ is defined in jsb_geometry_manual.cpp const desc: FieldDesc = (kls as any).__nativeFields__[attr]; const cacheKey = `_$_${attr}`; @@ -113,7 +113,7 @@ const defineAttrFloat = (kls: Constructor, attr: string) => { /** * define accessor for attr, read/write directly to the underlyingData as Int32Array[1] */ -const defineAttrInt = (kls: Constructor, attr: string) => { +const defineAttrInt = (kls: Constructor, attr: string): void => { // __nativeFields__ is defined in jsb_geometry_manual.cpp const desc: FieldDesc = (kls as any).__nativeFields__[attr]; if (!desc) { diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index 61de26b3fcc..157b6578dfa 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -71,14 +71,14 @@ const rayPlane = (function () { * @param doubleSided @zh 要测试的三角形是否为双面。 @en Indicates whether the triangle to test is double sided. * @returns @zh 0 或 非 0,0 表示没有相交。@en 0 or not 0, 0 indicates there is no intersection. */ -const rayTriangle = (function () { +const rayTriangle = (function (): (ray: Ray, triangle: Triangle, doubleSided?: boolean) => number { const ab = new Vec3(0, 0, 0); const ac = new Vec3(0, 0, 0); const pvec = new Vec3(0, 0, 0); const tvec = new Vec3(0, 0, 0); const qvec = new Vec3(0, 0, 0); - return function (ray: Ray, triangle: Triangle, doubleSided?: boolean) { + return function (ray: Ray, triangle: Triangle, doubleSided?: boolean): number { Vec3.subtract(ab, triangle.b, triangle.a); Vec3.subtract(ac, triangle.c, triangle.a); @@ -116,7 +116,7 @@ const rayTriangle = (function () { * @param sphere @zh 要测试的球。 @en The sphere to test. * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value. */ -const raySphere = (function () { +const raySphere = (function (): (ray: Ray, sphere: Sphere) => number { const e = new Vec3(0, 0, 0); return function (ray: Ray, sphere: Sphere): number { const r = sphere.radius; @@ -147,7 +147,7 @@ const raySphere = (function () { * @param aabb @zh 要测试的 AABB。 @en The aabb to test. * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value. */ -const rayAABB = (function () { +const rayAABB = (function (): (ray: Ray, aabb: AABB) => number { const min = new Vec3(); const max = new Vec3(); return function (ray: Ray, aabb: AABB): number { @@ -157,7 +157,7 @@ const rayAABB = (function () { }; }()); -function rayAABB2 (ray: Ray, min: IVec3Like, max: IVec3Like) { +function rayAABB2 (ray: Ray, min: IVec3Like, max: IVec3Like): number { const o = ray.o; const d = ray.d; const ix = 1 / d.x; const iy = 1 / d.y; const iz = 1 / d.z; const t1 = (min.x - o.x) * ix; @@ -181,7 +181,7 @@ function rayAABB2 (ray: Ray, min: IVec3Like, max: IVec3Like) { * @param obb @zh 要测试的 OBB。 @en The OBB to test. * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value. */ -const rayOBB = (function () { +const rayOBB = (function (): (ray: Ray, obb: OBB) => number { let center = new Vec3(); let o = new Vec3(); let d = new Vec3(); @@ -261,7 +261,7 @@ const rayOBB = (function () { * @param capsule @zh 要测试的胶囊体。 @en The capsule to test. * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value. */ -const rayCapsule = (function () { +const rayCapsule = (function (): (ray: Ray, capsule: Capsule) => number { const v3_0 = new Vec3(); const v3_1 = new Vec3(); const v3_2 = new Vec3(); @@ -270,7 +270,7 @@ const rayCapsule = (function () { const v3_5 = new Vec3(); const v3_6 = new Vec3(); const sphere_0 = new Sphere(); - return function (ray: Ray, capsule: Capsule) { + return function (ray: Ray, capsule: Capsule): number { const A = capsule.ellipseCenter0; const B = capsule.ellipseCenter1; const BA = Vec3.subtract(v3_1, B, A); @@ -348,7 +348,7 @@ const rayCapsule = (function () { * @param plane @zh 要测试的平面。 @en The plane to test. * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value. */ -const linePlane = (function () { +const linePlane = (function (): (line: Line, plane: Plane) => number { const ab = new Vec3(0, 0, 0); return function (line: Line, plane: Plane): number { @@ -369,7 +369,7 @@ const linePlane = (function () { * @param outPt @zh 可选,相交点 @en Optional out param, indicates the intersection point. * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value. */ -const lineTriangle = (function () { +const lineTriangle = (function (): (line: Line, triangle: Triangle, outPt?: Vec3) => number { const ab = new Vec3(0, 0, 0); const ac = new Vec3(0, 0, 0); const qp = new Vec3(0, 0, 0); @@ -499,12 +499,12 @@ function lineSphere (line: Line, sphere: Sphere): number { * @param aabb2 @zh 轴对齐包围盒2 @en aabb 2 to test * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ -const aabbWithAABB = (function () { +const aabbWithAABB = (function (): (aabb1: AABB, aabb2: AABB) => boolean { const aMin = new Vec3(); const aMax = new Vec3(); const bMin = new Vec3(); const bMax = new Vec3(); - return function (aabb1: AABB, aabb2: AABB) { + return function (aabb1: AABB, aabb2: AABB): boolean { Vec3.subtract(aMin, aabb1.center, aabb1.halfExtents); Vec3.add(aMax, aabb1.center, aabb1.halfExtents); Vec3.subtract(bMin, aabb2.center, aabb2.halfExtents); @@ -515,7 +515,7 @@ const aabbWithAABB = (function () { }; }()); -function getAABBVertices (min: Vec3, max: Vec3, out: Vec3[]) { +function getAABBVertices (min: Vec3, max: Vec3, out: Vec3[]): void { Vec3.set(out[0], min.x, max.y, max.z); Vec3.set(out[1], min.x, max.y, min.z); Vec3.set(out[2], min.x, min.y, max.z); @@ -526,7 +526,7 @@ function getAABBVertices (min: Vec3, max: Vec3, out: Vec3[]) { Vec3.set(out[7], max.x, min.y, min.z); } -function getOBBVertices (c: Vec3, e: Vec3, a1: Vec3, a2: Vec3, a3: Vec3, out: Vec3[]) { +function getOBBVertices (c: Vec3, e: Vec3, a1: Vec3, a2: Vec3, a3: Vec3, out: Vec3[]): void { Vec3.set(out[0], c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z, @@ -561,7 +561,7 @@ function getOBBVertices (c: Vec3, e: Vec3, a1: Vec3, a2: Vec3, a3: Vec3, out: Ve c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z); } -function getInterval (vertices: any[] | Vec3[], axis: Vec3) { +function getInterval (vertices: any[] | Vec3[], axis: Vec3): number[] { let min = Vec3.dot(axis, vertices[0]); let max = min; for (let i = 1; i < 8; ++i) { const projection = Vec3.dot(axis, vertices[i]); @@ -580,7 +580,7 @@ function getInterval (vertices: any[] | Vec3[], axis: Vec3) { * @param obb @zh OBB @en The OBB to test * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ -const aabbWithOBB = (function () { +const aabbWithOBB = (function (): (aabb: AABB, obb: OBB) => number { const test = new Array(15); for (let i = 0; i < 15; i++) { test[i] = new Vec3(0, 0, 0); @@ -690,7 +690,7 @@ const aabbFrustumCompletelyInside = function (aabb: AABB, frustum: Readonly number { const tmp = new Array(8); let out1 = 0; let out2 = 0; for (let i = 0; i < tmp.length; i++) { @@ -739,7 +739,7 @@ const aabbFrustumAccurate = (function () { * @param point @zh 参与测试的点。 @en The point to test. * @returns @zh 是否相交 @en The value indicates if there is an intersection. */ -const obbPoint = (function () { +const obbPoint = (function (): (obb: OBB, point: Vec3) => boolean { const tmp = new Vec3(0, 0, 0); const m3 = new Mat3(); const lessThan = function (a: Vec3, b: Vec3): boolean { return Math.abs(a.x) < b.x && Math.abs(a.y) < b.y && Math.abs(a.z) < b.z; }; return function (obb: OBB, point: Vec3): boolean { @@ -758,8 +758,8 @@ const obbPoint = (function () { * @param plane @zh 平面 @en The plane to test * @returns @zh 检测结果, 包含为 -1, 不包含为 0, 相交为 1 @en Test result, inside(back) = -1, outside(front) = 0, intersect = 1 */ -const obbPlane = (function () { - const absDot = function (n: Vec3, x: number, y: number, z: number) { +const obbPlane = (function (): (obb: OBB, plane: Plane) => number { + const absDot = function (n: Vec3, x: number, y: number, z: number): number { return Math.abs(n.x * x + n.y * y + n.z * z); }; return function (obb: OBB, plane: Plane): number { @@ -803,7 +803,7 @@ const obbFrustum = function (obb: OBB, frustum: Frustum): number { * @param frustum @zh 锥台 @en The frustum to test * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ -const obbFrustumAccurate = (function () { +const obbFrustumAccurate = (function (): (obb: OBB, frustum: Frustum) => number { const tmp = new Array(8); let dist = 0; let out1 = 0; let out2 = 0; for (let i = 0; i < tmp.length; i++) { @@ -858,7 +858,7 @@ const obbFrustumAccurate = (function () { * @param obb2 @zh OBB2 @en Obb 2 to test * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ -const obbWithOBB = (function () { +const obbWithOBB = (function (): (obb1: OBB, obb2: OBB) => number { const test = new Array(15); for (let i = 0; i < 15; i++) { test[i] = new Vec3(0, 0, 0); @@ -910,7 +910,7 @@ const obbWithOBB = (function () { * @param capsule @zh 胶囊体 @en The capsule to test. * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value. */ -const obbCapsule = (function () { +const obbCapsule = (function (): (obb: OBB, capsule: Capsule) => boolean | 1 | 0 { const sphere_0 = new Sphere(); const v3_0 = new Vec3(); const v3_1 = new Vec3(); @@ -919,7 +919,7 @@ const obbCapsule = (function () { for (let i = 0; i < 8; i++) { v3_verts8[i] = new Vec3(); } const v3_axis8 = new Array(8); for (let i = 0; i < 8; i++) { v3_axis8[i] = new Vec3(); } - return function (obb: OBB, capsule: Capsule) { + return function (obb: OBB, capsule: Capsule): boolean | 1 | 0 { const h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1); if (h === 0) { sphere_0.radius = capsule.radius; @@ -1012,7 +1012,7 @@ const sphereFrustum = function (sphere: Sphere, frustum: Frustum): number { * @param frustum @zh 锥台 @en The frustum to test * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ -const sphereFrustumAccurate = (function () { +const sphereFrustumAccurate = (function (): (sphere: Sphere, frustum: Frustum) => number { const pt = new Vec3(0, 0, 0); const map = [1, -1, 1, -1, 1, -1]; return function (sphere: Sphere, frustum: Frustum): number { for (let i = 0; i < 6; i++) { @@ -1059,7 +1059,7 @@ const sphereWithSphere = function (sphere0: Sphere, sphere1: Sphere): boolean { * @param aabb @zh 轴对齐包围盒 @en The aabb to test * @returns @zh 是否发生碰撞 @en true or false which indicates if there is an intersection */ -const sphereAABB = (function () { +const sphereAABB = (function (): (sphere: Sphere, aabb: AABB) => boolean { const pt = new Vec3(); return function (sphere: Sphere, aabb: AABB): boolean { distance.pt_point_aabb(pt, sphere.center, aabb); @@ -1076,7 +1076,7 @@ const sphereAABB = (function () { * @param obb @zh 参与测试的 OBB。 @en The OBB to test. * @returns @zh 是否发生碰撞。 @en true or false which indicates if there is an intersection. */ -const sphereOBB = (function () { +const sphereOBB = (function (): (sphere: Sphere, obb: OBB) => boolean { const pt = new Vec3(); return function (sphere: Sphere, obb: OBB): boolean { distance.pt_point_obb(pt, sphere.center, obb); @@ -1093,10 +1093,10 @@ const sphereOBB = (function () { * @param capsule @zh 参与测试的胶囊体。 @en The capsule to test. * @returns @zh 是否发生碰撞。 @en true or false which indicates if there is an intersection. */ -const sphereCapsule = (function () { +const sphereCapsule = (function (): (sphere: Sphere, capsule: Capsule) => boolean { const v3_0 = new Vec3(); const v3_1 = new Vec3(); - return function (sphere: Sphere, capsule: Capsule) { + return function (sphere: Sphere, capsule: Capsule): boolean { const r = sphere.radius + capsule.radius; const squaredR = r * r; const h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1); @@ -1128,14 +1128,14 @@ const sphereCapsule = (function () { * @param capsuleB @zh 要测试的胶囊体 B。 @en The capsule B to test. * @returns @zh 如果相交,返回 true,否则返回 false。 @en true if there is an intersection, otherwise returns false. */ -const capsuleWithCapsule = (function () { +const capsuleWithCapsule = (function (): (capsuleA: Capsule, capsuleB: Capsule) => boolean { const v3_0 = new Vec3(); const v3_1 = new Vec3(); const v3_2 = new Vec3(); const v3_3 = new Vec3(); const v3_4 = new Vec3(); const v3_5 = new Vec3(); - return function capsuleWithCapsule (capsuleA: Capsule, capsuleB: Capsule) { + return function capsuleWithCapsule (capsuleA: Capsule, capsuleB: Capsule): boolean { const u = Vec3.subtract(v3_0, capsuleA.ellipseCenter1, capsuleA.ellipseCenter0); const v = Vec3.subtract(v3_1, capsuleB.ellipseCenter1, capsuleB.ellipseCenter0); const w = Vec3.subtract(v3_2, capsuleA.ellipseCenter0, capsuleB.ellipseCenter0); @@ -1265,7 +1265,7 @@ const intersect = { * @param outPt @en A 3d point to store the intersection point result, only part of the geometries support this. * @zh 可选,用于保存相交点的输出对象。(注:仅部分形状的检测带有这个返回值) */ - resolve (g1: any, g2: any, outPt = null) { + resolve (g1: any, g2: any, outPt = null): number { const type1 = g1._type; const type2 = g2._type; const resolver = this[type1 | type2] as (...args: any) => number; return type1 < type2 ? resolver(g1, g2, outPt) : resolver(g2, g1, outPt); diff --git a/cocos/core/geometry/line.ts b/cocos/core/geometry/line.ts index 260ed44d996..7e2f1b0c1c7 100644 --- a/cocos/core/geometry/line.ts +++ b/cocos/core/geometry/line.ts @@ -45,7 +45,7 @@ export class Line { * @param ez @en the z coordinate of the end position. @zh 终点的 z 坐标。 * @returns @en The created line. @zh 创建的直线。 */ - public static create (sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) { + public static create (sx: number, sy: number, sz: number, ex: number, ey: number, ez: number): Line { return new Line(sx, sy, sz, ex, ey, ez); } @@ -57,7 +57,7 @@ export class Line { * @param a @en The line to clone from. @zh 克隆的来源 Line 对象。 * @returns @en The cloned line. @zh 克隆出的新 Line 对象。 */ - public static clone (a: Line) { + public static clone (a: Line): Line { return new Line( a.s.x, a.s.y, a.s.z, a.e.x, a.e.y, a.e.z, @@ -73,7 +73,7 @@ export class Line { * @param a @en The line to copy from. @zh 从这个 Line 对象拷贝信息。 * @returns @en The `out` parameter. @zh 传入的 `out` 对象。 */ - public static copy (out: Line, a: Line) { + public static copy (out: Line, a: Line): Line { Vec3.copy(out.s, a.s); Vec3.copy(out.e, a.e); @@ -90,7 +90,7 @@ export class Line { * @param end @en The end point. @zh 终点。 * @returns @en The `out` parameter. @zh 传入的 out 对象。 */ - public static fromPoints (out: Line, start: Vec3, end: Vec3) { + public static fromPoints (out: Line, start: Vec3, end: Vec3): Line { Vec3.copy(out.s, start); Vec3.copy(out.e, end); return out; @@ -110,7 +110,7 @@ export class Line { * @param ez @en the z coordinate of the end position. @zh 终点的 z 坐标。 * @returns @en The `out` parameter. @zh 传入的 `out` 对象。 */ - public static set (out: Line, sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) { + public static set (out: Line, sx: number, sy: number, sz: number, ex: number, ey: number, ez: number): Line { out.s.x = sx; out.s.y = sy; out.s.z = sz; @@ -127,7 +127,7 @@ export class Line { * @param a @en The line to calculate length. @zh 用于计算长度的线段。 * @returns @en The length of the given line. @zh 线段的长度。 */ - public static len (a: Line) { + public static len (a: Line): number { return Vec3.distance(a.s, a.e); } @@ -147,7 +147,7 @@ export class Line { * @en Gets the type of the shape. Always returns `enums.SHAPE_LINE`. * @zh 获取形状的类型,总是返回 `enums.SHAPE_LINE`。 */ - get type () { + get type (): number { return this._type; } @@ -174,7 +174,7 @@ export class Line { * @zh 计算线段的长度。 * @returns @en The length of the line. @zh 线段的长度。 */ - public length () { + public length (): number { return Vec3.distance(this.s, this.e); } } diff --git a/cocos/core/geometry/obb.ts b/cocos/core/geometry/obb.ts index 0995ce86270..a450042d88d 100644 --- a/cocos/core/geometry/obb.ts +++ b/cocos/core/geometry/obb.ts @@ -30,7 +30,7 @@ const _v3_tmp2 = new Vec3(); const _m3_tmp = new Mat3(); // https://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/ -const transform_extent_m3 = (out: Vec3, extent: Vec3, m3: Mat3) => { +const transform_extent_m3 = (out: Vec3, extent: Vec3, m3: Mat3): void => { _m3_tmp.m00 = Math.abs(m3.m00); _m3_tmp.m01 = Math.abs(m3.m01); _m3_tmp.m02 = Math.abs(m3.m02); _m3_tmp.m03 = Math.abs(m3.m03); _m3_tmp.m04 = Math.abs(m3.m04); _m3_tmp.m05 = Math.abs(m3.m05); _m3_tmp.m06 = Math.abs(m3.m06); _m3_tmp.m07 = Math.abs(m3.m07); _m3_tmp.m08 = Math.abs(m3.m08); @@ -73,7 +73,7 @@ export class OBB { ox_1: number, ox_2: number, ox_3: number, oy_1: number, oy_2: number, oy_3: number, oz_1: number, oz_2: number, oz_3: number, - ) { + ): OBB { return new OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); } @@ -85,7 +85,7 @@ export class OBB { * @param a @zh 克隆的目标。 @en The input OBB. * @returns @zh The cloned OBB instance. @en 克隆出的新对象。 */ - public static clone (a: OBB) { + public static clone (a: OBB): OBB { return new OBB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, a.orientation.m00, a.orientation.m01, a.orientation.m02, @@ -194,7 +194,7 @@ export class OBB { * @zh * 获取形状的类型,固定返回 `enums.SHAPE_OBB`。 */ - get type () { + get type (): number { return this._type; } @@ -236,7 +236,7 @@ export class OBB { * @param minPos @zh 此 OBB 的最小点。 @en The out minimum position of the OBB. * @param maxPos @zh 此 OBB 的最大点。 @en The out maximum position of the OBB. */ - public getBoundary (minPos: Vec3, maxPos: Vec3) { + public getBoundary (minPos: Vec3, maxPos: Vec3): void { transform_extent_m3(_v3_tmp, this.halfExtents, this.orientation); Vec3.subtract(minPos, this.center, _v3_tmp); Vec3.add(maxPos, this.center, _v3_tmp); @@ -254,7 +254,7 @@ export class OBB { * @param out @zh 变换结果的目标 OBB。 @en The output OBB. * @note @zh 此方法不会修改当前 OBB 的数据。 @en This method will not modify the data of current OBB. */ - public transform (m: Mat4, pos: Vec3, rot: Quat, scale: Vec3, out: OBB) { + public transform (m: Mat4, pos: Vec3, rot: Quat, scale: Vec3, out: OBB): void { Vec3.transformMat4(out.center, this.center, m); // parent shape doesn't contain rotations for now Mat3.fromQuat(out.orientation, rot); @@ -271,7 +271,7 @@ export class OBB { * @param out @zh 变换的目标。 @en The output OBB. * @note @zh 此方法不会修改当前 OBB 的数据。 @en This method will not modify the data of current OBB. */ - public translateAndRotate (m: Mat4, rot: Quat, out: OBB) { + public translateAndRotate (m: Mat4, rot: Quat, out: OBB): void { Vec3.transformMat4(out.center, this.center, m); // parent shape doesn't contain rotations for now Mat3.fromQuat(out.orientation, rot); @@ -286,7 +286,7 @@ export class OBB { * @param out @zh 缩放的目标。 @en The output OBB. * @note @zh 此方法不会修改当前 OBB 的数据。 @en This method will not modify the data of current OBB. */ - public setScale (scale: Vec3, out: OBB) { + public setScale (scale: Vec3, out: OBB): void { Vec3.multiply(out.halfExtents, this.halfExtents, scale); } } diff --git a/cocos/core/geometry/plane.ts b/cocos/core/geometry/plane.ts index 7b40b15816e..32bc73cdc7d 100644 --- a/cocos/core/geometry/plane.ts +++ b/cocos/core/geometry/plane.ts @@ -52,7 +52,7 @@ export class Plane { * @param d @en The distance between normal vector and the origin. @zh 与原点的距离。 * @returns @en The created plane object. @zh 新创建的平面。 */ - public static create (nx: number, ny: number, nz: number, d: number) { + public static create (nx: number, ny: number, nz: number, d: number): Plane { return new Plane(nx, ny, nz, d); } @@ -64,7 +64,7 @@ export class Plane { * @param p @en The Plane object to be cloned from. @zh 克隆的来源平面对象。 * @returns @en The cloned Plane object @zh 克隆出的平面对象。 */ - public static clone (p: Plane) { + public static clone (p: Plane): Plane { return new Plane(p.n.x, p.n.y, p.n.z, p.d); } @@ -77,7 +77,7 @@ export class Plane { * @param p @en The source of replication. @zh 复制的来源。 * @returns @en The object to be operated on. @zh 接受操作的对象。 */ - public static copy (out: Plane, p: Plane) { + public static copy (out: Plane, p: Plane): Plane { Vec3.copy(out.n, p.n); out.d = p.d; @@ -95,7 +95,7 @@ export class Plane { * @param c @en The point c. @zh 点 c。 * @returns @en The Plane object to be operated on, same as `out` parameter. @zh 接受操作的对象,与 `out` 相同。 */ - public static fromPoints (out: Plane, a: Vec3, b: Vec3, c: Vec3) { + public static fromPoints (out: Plane, a: Vec3, b: Vec3, c: Vec3): Plane { Vec3.subtract(v1, b, a); Vec3.subtract(v2, c, a); @@ -117,7 +117,7 @@ export class Plane { * @param d @en The distance between normal vector and the origin. @zh 与原点的距离。 * @returns @en The object to be operated on, same as the `out` parameter. @zh 接受操作的对象,与 `out` 参数相同。 */ - public static set (out: Plane, nx: number, ny: number, nz: number, d: number) { + public static set (out: Plane, nx: number, ny: number, nz: number, d: number): Plane { out.n.x = nx; out.n.y = ny; out.n.z = nz; @@ -136,7 +136,7 @@ export class Plane { * @param point @en A point in the plane. @zh 平面上的一点。 * @returns @en The object to be operated on, same as the `out` parameter. @zh 接受操作的对象,与 `out` 参数相同。 */ - public static fromNormalAndPoint (out: Plane, normal: Vec3, point: Vec3) { + public static fromNormalAndPoint (out: Plane, normal: Vec3, point: Vec3): Plane { Vec3.copy(out.n, normal); out.d = Vec3.dot(normal, point); @@ -152,7 +152,7 @@ export class Plane { * @param a @en Source data for the operation. @zh 操作的源数据。 * @returns @en The object to be operated on, sames as the `out` parameter. @zh 接受操作的对象,与 `out` 相同。 */ - public static normalize (out: Plane, a: Plane) { + public static normalize (out: Plane, a: Plane): Plane { const len = a.n.length(); Vec3.normalize(out.n, a.n); if (len > 0) { @@ -183,19 +183,19 @@ export class Plane { * @zh * 获取形状的类型,值为 `enums.SHAPE_PLANE`。 */ - get type () { + get type (): number { return this._type; } // compatibility with vector interfaces set x (val) { this.n.x = val; } - get x () { return this.n.x; } + get x (): number { return this.n.x; } set y (val) { this.n.y = val; } - get y () { return this.n.y; } + get y (): number { return this.n.y; } set z (val) { this.n.z = val; } - get z () { return this.n.z; } + get z (): number { return this.n.z; } set w (val) { this.d = val; } - get w () { return this.d; } + get w (): number { return this.d; } protected declare readonly _type: number; diff --git a/cocos/core/geometry/ray.ts b/cocos/core/geometry/ray.ts index d22c31957f2..3b90498c489 100644 --- a/cocos/core/geometry/ray.ts +++ b/cocos/core/geometry/ray.ts @@ -145,7 +145,7 @@ export class Ray { * @zh * 获取形状的类型,其值为`enums.SHAPE_RAY`。 */ - get type () { + get type (): number { return this._type; } @@ -178,7 +178,7 @@ export class Ray { * @param out @en Another point on the ray. @zh 射线上的另一点。 * @param distance @en The given distance. @zh 给定的距离。 */ - public computeHit (out: IVec3Like, distance: number) { + public computeHit (out: IVec3Like, distance: number): void { Vec3.normalize(out, this.d); Vec3.scaleAndAdd(out, this.o, out, distance); } diff --git a/cocos/core/geometry/sphere.ts b/cocos/core/geometry/sphere.ts index 21819892337..08e951de227 100644 --- a/cocos/core/geometry/sphere.ts +++ b/cocos/core/geometry/sphere.ts @@ -30,7 +30,7 @@ const _v3_tmp = new Vec3(); const _offset = new Vec3(); const _min = new Vec3(); const _max = new Vec3(); -function maxComponent (v: Vec3) { return Math.max(Math.max(v.x, v.y), v.z); } +function maxComponent (v: Vec3): number { return Math.max(Math.max(v.x, v.y), v.z); } /** * @en @@ -158,7 +158,7 @@ export class Sphere { * @zh * 获取球的类型,固定返回 `enums.SHAPE_SPHERE`。 */ - get type () { + get type (): number { return this._type; } @@ -180,7 +180,7 @@ export class Sphere { this._radius = r; } - public destroy () { + public destroy (): void { } /** @@ -190,7 +190,7 @@ export class Sphere { * 克隆一个球实例。 * @returns @en The cloned sphere instance. @zh 克隆的球实例。 */ - public clone () { + public clone (): Sphere { return Sphere.clone(this); } @@ -201,7 +201,7 @@ export class Sphere { * 复制一个球的值到当前球实例中。 * @param a @en The sphere to copy from. @zh 拷贝的目标。 */ - public copy (a: Sphere) { + public copy (a: Sphere): Sphere { return Sphere.copy(this, a); } @@ -213,7 +213,7 @@ export class Sphere { * @param minPos @en The point with maximum coordinates of the sphere. @zh 当前球实例的最小点。 * @param maxPos @en The point with minimum coordinates of the sphere. @zh 当前球实例的最大点。 */ - public getBoundary (minPos: Vec3, maxPos: Vec3) { + public getBoundary (minPos: Vec3, maxPos: Vec3): void { Vec3.set(minPos, this.center.x - this.radius, this.center.y - this.radius, this.center.z - this.radius); Vec3.set(maxPos, this.center.x + this.radius, this.center.y + this.radius, this.center.z + this.radius); } @@ -229,7 +229,7 @@ export class Sphere { * @param scale @en The scale part of the transform. @zh 变换的缩放部分。 * @param out @en The sphere which the transform will be applied to. @zh 变换的目标。 */ - public transform (m: Mat4, pos: Vec3, rot: Quat, scale: Vec3, out: Sphere) { + public transform (m: Mat4, pos: Vec3, rot: Quat, scale: Vec3, out: Sphere): void { Vec3.transformMat4(out.center, this.center, m); out.radius = this.radius * maxComponent(scale); } @@ -243,7 +243,7 @@ export class Sphere { * @param rot @en The rotation part of the transform. @zh 变换的旋转部分。 * @param out @en The sphere which the transform will be applied to. @zh 变换的目标。 */ - public translateAndRotate (m: Mat4, rot: Quat, out: Sphere) { + public translateAndRotate (m: Mat4, rot: Quat, out: Sphere): void { Vec3.transformMat4(out.center, this.center, m); } @@ -255,7 +255,7 @@ export class Sphere { * @param scale @en The scale value. @zh 缩放值。 * @param out @en The sphere which the scale will be applied to. @zh 缩放的目标。 */ - public setScale (scale: Vec3, out: Sphere) { + public setScale (scale: Vec3, out: Sphere): void { out.radius = this.radius * maxComponent(scale); } @@ -264,7 +264,7 @@ export class Sphere { * @zh 合并一个点到当前球实例中。 * @param point @en The point to be merged to this sphere. @zh 要合并到当前球实例的点。 */ - public mergePoint (point: Vec3) { + public mergePoint (point: Vec3): void { // if sphere.radius Less than 0, // Set this point as anchor, // And set radius to 0. @@ -289,7 +289,7 @@ export class Sphere { * @zh 合并一些点到当前球实例中。 * @param points @en The points to be merged to this sphere. @zh 要合并到当前球实例的点列表。 */ - public mergePoints (points: Vec3[]) { + public mergePoints (points: Vec3[]): void { const length = points.length; if (length < 1) return; @@ -306,7 +306,7 @@ export class Sphere { * @zh 合并一个 AABB 到当前球实例中。 * @param a @en The AABB instance to be merged to this sphere. @zh 要合并到当前球实例的 AABB 实例。 */ - public mergeAABB (a: AABB) { + public mergeAABB (a: AABB): void { a.getBoundary(_min, _max); this.mergePoint(_min); diff --git a/cocos/core/geometry/spline.ts b/cocos/core/geometry/spline.ts index 5ac549e486f..876d4a0141c 100644 --- a/cocos/core/geometry/spline.ts +++ b/cocos/core/geometry/spline.ts @@ -111,7 +111,7 @@ export class Spline { * @param knots @en The knots to create the Spline instance. @zh 用于创建 Spline 实例的结点列表。 * @returns @en The created Spline instance. @zh 创建出的 Spline 实例。 */ - public static create (mode: SplineMode, knots: Vec3[] = []) { + public static create (mode: SplineMode, knots: Vec3[] = []): Spline { return new Spline(mode, knots); } @@ -123,7 +123,7 @@ export class Spline { * @param s @en The Spline instance to be cloned. @zh 用于克隆的 Spline 实例。 * @returns @en The cloned Spline instance. @zh 克隆出的 Spline 实例。 */ - public static clone (s: Spline) { + public static clone (s: Spline): Spline { return new Spline(s.mode, s.knots); } @@ -136,7 +136,7 @@ export class Spline { * @param s @en The source Spline instance to copy from. @zh 拷贝源 Spline 实例。 * @returns @en The target Spline instance to copy to, same as the `out` parameter. @zh 拷贝目标 Spline 实例,值与 `out` 参数相同。 */ - public static copy (out: Spline, s: Spline) { + public static copy (out: Spline, s: Spline): Spline { out._mode = s.mode; out._knots.length = 0; @@ -155,7 +155,7 @@ export class Spline { * @zh * 获取此 Spline 的类型,固定返回 `enums.SHAPE_SPLINE` */ - get type () { + get type (): number { return this._type; } @@ -165,7 +165,7 @@ export class Spline { * @zh * 获取当前 Spline 实例的模式。 */ - get mode () { + get mode (): SplineMode { return this._mode; } @@ -187,7 +187,7 @@ export class Spline { * @param mode @en The mode to be set to this Spline instance. @zh 要设置到当前 Spline 实例的模式。 * @param knots @en The knots to be set to this spline instance. @zh 要设置到当前 Spline 实例的结点列表。 */ - public setModeAndKnots (mode: SplineMode, knots: Vec3[]) { + public setModeAndKnots (mode: SplineMode, knots: Vec3[]): void { this._mode = mode; this._knots.length = 0; @@ -202,7 +202,7 @@ export class Spline { * @zh * 清空当前 Spline 实例的所有结点。 */ - public clearKnots () { + public clearKnots (): void { this._knots.length = 0; } @@ -213,7 +213,7 @@ export class Spline { * 获取当前 Spline 实例的结点数量。 * @returns @en The knot count of this Spline instance. @zh 当前 Spline 实例的结点数量。 */ - public getKnotCount () { + public getKnotCount (): number { return this._knots.length; } @@ -224,7 +224,7 @@ export class Spline { * 给当前 Spline 实例添加一个结点。 * @param knot @en The knot to add to this Spline instance. @zh 要添加到当前 Spline 实例的结点。 */ - public addKnot (knot: Vec3) { + public addKnot (knot: Vec3): void { this._knots.push(new Vec3(knot)); } @@ -236,7 +236,7 @@ export class Spline { * @param index @en The position of this Spline instance to be inserted. @zh 要插入到此 Spline 实例的位置。 * @param knot @en The knot to be inserted. @zh 要插入的结点。 */ - public insertKnot (index: number, knot: Vec3) { + public insertKnot (index: number, knot: Vec3): void { const item = new Vec3(knot); if (index >= this._knots.length) { this._knots.push(item); @@ -253,7 +253,7 @@ export class Spline { * 移除当前 Spline 实例的指定位置的一个结点。 * @param index */ - public removeKnot (index: number) { + public removeKnot (index: number): void { assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); this._knots.splice(index, 1); @@ -267,7 +267,7 @@ export class Spline { * @param index @en The specified position of this Spline instance. @zh 要设置结点的指定位置。 * @param knot @en The knot to be set to the specified position. @zh 要设置的结点。 */ - public setKnot (index: number, knot: Vec3) { + public setKnot (index: number, knot: Vec3): void { assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); this._knots[index].set(knot); @@ -296,7 +296,7 @@ export class Spline { * @param index @en The knot index of this Spline instance, default value is the whole curve. @zh 当前 Spline 实例的某个结点索引,默认值为整条曲线。 * @returns @en The point matches the input `t` factor and `index`. @zh 满足输入 `t` 参数和 `index` 参数的点。 */ - public getPoint (t: number, index: number = SPLINE_WHOLE_INDEX) { + public getPoint (t: number, index: number = SPLINE_WHOLE_INDEX): Vec3 { t = clamp(t, 0.0, 1.0); const segments = this.getSegments(); @@ -362,7 +362,7 @@ export class Spline { return points; } - private getSegments () { + private getSegments (): number { const count = this._knots.length; switch (this._mode) { case SplineMode.LINEAR: @@ -385,7 +385,7 @@ export class Spline { } } - private static calcLinear (v0: Vec3, v1: Vec3, t: number) { + private static calcLinear (v0: Vec3, v1: Vec3, t: number): Vec3 { const result = new Vec3(); Vec3.multiplyScalar(_v0, v0, (1.0 - t)); Vec3.multiplyScalar(_v1, v1, t); @@ -394,7 +394,7 @@ export class Spline { return result; } - private static calcBezier (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number) { + private static calcBezier (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number): Vec3 { const result = new Vec3(); const s = 1.0 - t; Vec3.multiplyScalar(_v0, v0, s * s * s); @@ -407,7 +407,7 @@ export class Spline { return result; } - private static calcCatmullRom (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number) { + private static calcCatmullRom (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number): Vec3 { const result = new Vec3(); const t2 = t * t; const t3 = t2 * t; diff --git a/cocos/core/geometry/triangle.ts b/cocos/core/geometry/triangle.ts index e04d56b85ab..80520afbec4 100644 --- a/cocos/core/geometry/triangle.ts +++ b/cocos/core/geometry/triangle.ts @@ -172,7 +172,7 @@ export class Triangle { * @zh * 获取此三角形的类型,固定返回 `enums.SHAPE_TRIANGLE`。 */ - get type () { + get type (): number { return this._type; } diff --git a/cocos/core/global-exports.ts b/cocos/core/global-exports.ts index b07273cc111..e002b91eee6 100644 --- a/cocos/core/global-exports.ts +++ b/cocos/core/global-exports.ts @@ -46,7 +46,7 @@ if (DEV) { legacyCC._Test = {}; } -const engineVersion = '3.8.0'; +const engineVersion = '3.8.1'; /** * @en diff --git a/cocos/core/legacy.ts b/cocos/core/legacy.ts index 107482b4824..5572f0beb39 100644 --- a/cocos/core/legacy.ts +++ b/cocos/core/legacy.ts @@ -49,7 +49,7 @@ legacyCC.path = { changeBasename, _normalize, stripSep, - get sep () { + get sep (): string { return getSeperator(); }, }; diff --git a/cocos/core/math/affine-transform.ts b/cocos/core/math/affine-transform.ts index e190046271e..00b86bf96fa 100644 --- a/cocos/core/math/affine-transform.ts +++ b/cocos/core/math/affine-transform.ts @@ -40,7 +40,7 @@ export class AffineTransform { * @en Create an identity transformation matrix. * @zh 创建单位二维仿射变换矩阵,它不进行任何变换。 */ - public static identity () { + public static identity (): AffineTransform { return new AffineTransform(); } @@ -49,7 +49,7 @@ export class AffineTransform { * @zh 克隆指定的二维仿射变换矩阵。 * @param affineTransform Specified `AffineTransform` objects */ - public static clone (affineTransform: AffineTransform) { + public static clone (affineTransform: AffineTransform): AffineTransform { return new AffineTransform( affineTransform.a, affineTransform.b, affineTransform.c, affineTransform.d, @@ -65,7 +65,7 @@ export class AffineTransform { * @param t1 The first transform object. * @param t2 The transform object to concatenate. */ - public static concat (out: AffineTransform, t1: AffineTransform, t2: AffineTransform) { + public static concat (out: AffineTransform, t1: AffineTransform, t2: AffineTransform): void { const a = t1.a; const b = t1.b; const c = t1.c; @@ -86,7 +86,7 @@ export class AffineTransform { * @param out Out object to store the invert result * @param t the input `AffineTransform` object */ - public static invert (out: AffineTransform, t: AffineTransform) { + public static invert (out: AffineTransform, t: AffineTransform): void { const determinant = 1 / (t.a * t.d - t.b * t.c); out.a = determinant * t.d; out.b = -determinant * t.b; @@ -102,7 +102,7 @@ export class AffineTransform { * @param out The output matrix to store the result * @param mat transform matrix. */ - public static fromMat4 (out: AffineTransform, mat: Mat4) { + public static fromMat4 (out: AffineTransform, mat: Mat4): void { out.a = mat.m00; out.b = mat.m01; out.c = mat.m04; @@ -118,7 +118,7 @@ export class AffineTransform { * @param point Vector to apply transform. * @param t transform matrix. */ - public static transformVec2 (out: Vec2, point: Vec2, t: AffineTransform); + public static transformVec2 (out: Vec2, point: Vec2, t: AffineTransform): any; /** * @en Apply the `AffineTransform` on a 2D vector. @@ -128,9 +128,9 @@ export class AffineTransform { * @param y y to apply transform. * @param t transform matrix. */ - public static transformVec2 (out: Vec2, x: number, y: number, t: AffineTransform); + public static transformVec2 (out: Vec2, x: number, y: number, t: AffineTransform): any; - public static transformVec2 (out: Vec2, point: Vec2 | number, transOrY: AffineTransform | number, t?: AffineTransform) { + public static transformVec2 (out: Vec2, point: Vec2 | number, transOrY: AffineTransform | number, t?: AffineTransform): any { let x: number; let y: number; if (!t) { @@ -152,7 +152,7 @@ export class AffineTransform { * @param size The size to apply transform. * @param t transform matrix. */ - public static transformSize (out: Size, size: Size, t: AffineTransform) { + public static transformSize (out: Size, size: Size, t: AffineTransform): void { out.width = t.a * size.width + t.c * size.height; out.height = t.b * size.width + t.d * size.height; } @@ -164,7 +164,7 @@ export class AffineTransform { * @param rect The rect object to apply transform. * @param t transform matrix. */ - public static transformRect (out: Rect, rect: Rect, t: AffineTransform) { + public static transformRect (out: Rect, rect: Rect, t: AffineTransform): void { const or = rect.x + rect.width; const ot = rect.y + rect.height; const lbx = t.a * rect.x + t.c * rect.y + t.tx; @@ -200,7 +200,7 @@ export class AffineTransform { * @param anAffineTransform transform matrix. */ public static transformObb (out_bl: Vec2, out_tl: Vec2, out_tr: Vec2, out_br: Vec2, rect: Rect, - anAffineTransform: AffineTransform, flipY = true) { + anAffineTransform: AffineTransform, flipY = true): void { const tx = anAffineTransform.a * rect.x + anAffineTransform.c * rect.y + anAffineTransform.tx; const ty = anAffineTransform.b * rect.x + anAffineTransform.d * rect.y + anAffineTransform.ty; const xa = anAffineTransform.a * rect.width; diff --git a/cocos/core/math/bits.ts b/cocos/core/math/bits.ts index ecdc24c3f6b..73e8af6b37d 100644 --- a/cocos/core/math/bits.ts +++ b/cocos/core/math/bits.ts @@ -57,7 +57,7 @@ export const INT_MIN = -1 << (INT_BITS - 1); * @en Returns -1, 0, +1 depending on sign of x. * @zh 根据x的符号返回 -1,0,+1。 */ -export function sign (v: number) { +export function sign (v: number): number { return ((v > 0) as unknown as number) - ((v < 0) as unknown as number); } @@ -65,7 +65,7 @@ export function sign (v: number) { * @en Computes absolute value of integer. * @zh 计算整数的绝对值。 */ -export function abs (v: number) { +export function abs (v: number): number { const mask = v >> (INT_BITS - 1); return (v ^ mask) - mask; } @@ -74,7 +74,7 @@ export function abs (v: number) { * @en Computes minimum of integers x and y. * @zh 计算整数x和y中的最小值。 */ -export function min (x: number, y: number) { +export function min (x: number, y: number): number { return y ^ ((x ^ y) & -(x < y)); } @@ -82,7 +82,7 @@ export function min (x: number, y: number) { * @en Computes maximum of integers x and y. * @zh 计算整数x和y中的最大值。 */ -export function max (x: number, y: number) { +export function max (x: number, y: number): number { return x ^ ((x ^ y) & -(x < y)); } @@ -90,7 +90,7 @@ export function max (x: number, y: number) { * @en Checks if a number is a power of two. * @zh 检查一个数字是否是2的幂。 */ -export function isPow2 (v: number) { +export function isPow2 (v: number): boolean { return !(v & (v - 1)) && (!!v); } @@ -98,7 +98,7 @@ export function isPow2 (v: number) { * @en Computes log base 2 of v. * @zh 计算以 2 为底的 v 的对数。 */ -export function log2 (v: number) { +export function log2 (v: number): number { let r: number; let shift: number; r = ((v > 0xFFFF) as unknown as number) << 4; v >>>= r; @@ -112,7 +112,7 @@ export function log2 (v: number) { * @en Computes log base 10 of v. * @zh 计算以 10 为底的 v 的对数。 */ -export function log10 (v: number) { +export function log10 (v: number): number { return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; @@ -122,7 +122,7 @@ export function log10 (v: number) { * @en Counts number of bits. * @zh 计算传入数字二进制表示中 1 的数量。 */ -export function popCount (v: number) { +export function popCount (v: number): number { v -= ((v >>> 1) & 0x55555555); v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; @@ -132,7 +132,7 @@ export function popCount (v: number) { * @en Counts number of trailing zeros. * @zh 计算传入数字二进制表示尾随零的数量。 */ -export function countTrailingZeros (v: number) { +export function countTrailingZeros (v: number): number { let c = 32; v &= -v; if (v) { c--; } @@ -148,7 +148,7 @@ export function countTrailingZeros (v: number) { * @en Rounds to next power of 2. * @zh 计算大于等于v的最小的二的整数次幂的数字。 */ -export function nextPow2 (v: number) { +export function nextPow2 (v: number): number { --v; v |= v >>> 1; v |= v >>> 2; @@ -162,7 +162,7 @@ export function nextPow2 (v: number) { * @en Rounds down to previous power of 2. * @zh 计算小于等于v的最小的二的整数次幂的数字。 */ -export function prevPow2 (v: number) { +export function prevPow2 (v: number): number { v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; @@ -175,7 +175,7 @@ export function prevPow2 (v: number) { * @en Computes parity of word. * @zh 奇偶校验。 */ -export function parity (v: number) { +export function parity (v: number): number { v ^= v >>> 16; v ^= v >>> 8; v ^= v >>> 4; @@ -185,7 +185,7 @@ export function parity (v: number) { const REVERSE_TABLE: number[] = new Array(256); -((tab: number[]) => { +((tab: number[]): void => { for (let i = 0; i < 256; ++i) { let v = i; let r = i; @@ -203,7 +203,7 @@ const REVERSE_TABLE: number[] = new Array(256); * @en Reverse bits in a 32 bit word. * @zh 翻转 32 位二进制数字。 */ -export function reverse (v: number) { +export function reverse (v: number): number { return (REVERSE_TABLE[v & 0xff] << 24) | (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) @@ -214,7 +214,7 @@ export function reverse (v: number) { * @en Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes. * @zh 将两个 16 位数字按位交错编码。有利于在快速四叉树中使用。 */ -export function interleave2 (x: number, y: number) { +export function interleave2 (x: number, y: number): number { x &= 0xFFFF; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; @@ -234,7 +234,7 @@ export function interleave2 (x: number, y: number) { * @en Extracts the nth interleaved component. * @zh 提取第 n 个交错分量。 */ -export function deinterleave2 (v: number, n: number) { +export function deinterleave2 (v: number, n: number): number { v = (v >>> n) & 0x55555555; v = (v | (v >>> 1)) & 0x33333333; v = (v | (v >>> 2)) & 0x0F0F0F0F; @@ -247,7 +247,7 @@ export function deinterleave2 (v: number, n: number) { * @en Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes. * @zh 将三个数字按位交错编码,每个数字占十位。有利于在八叉树中使用。 */ -export function interleave3 (x: number, y: number, z: number) { +export function interleave3 (x: number, y: number, z: number): number { x &= 0x3FF; x = (x | (x << 16)) & 4278190335; x = (x | (x << 8)) & 251719695; @@ -274,7 +274,7 @@ export function interleave3 (x: number, y: number, z: number) { * @en Extracts nth interleaved component of a 3-tuple. * @zh 提取三个数字中的第n个交错分量。 */ -export function deinterleave3 (v: number, n: number) { +export function deinterleave3 (v: number, n: number): number { v = (v >>> n) & 1227133513; v = (v | (v >>> 2)) & 3272356035; v = (v | (v >>> 4)) & 251719695; @@ -287,7 +287,7 @@ export function deinterleave3 (v: number, n: number) { * @en Compute the lexicographically next bit permutation * @zh 计算下一组字典序的比特排列 */ -export function nextCombination (v: number) { +export function nextCombination (v: number): number { const t = v | (v - 1); return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); } diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index 995c3561d93..63d28b2335b 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -56,7 +56,7 @@ export class Color extends ValueType { * @en Copy content of a color into another and save the results to out color. * @zh 获得指定颜色的拷贝 */ - public static clone (a: Out) { + public static clone (a: Out): Color { const out = new Color(); if (a._val) { out._val = a._val; @@ -70,7 +70,7 @@ export class Color extends ValueType { * @en Clone a color and save the results to out color. * @zh 复制目标颜色 */ - public static copy (out: Out, a: Out) { + public static copy (out: Out, a: Out): Out { out.r = a.r; out.g = a.g; out.b = a.b; @@ -82,7 +82,7 @@ export class Color extends ValueType { * @en Set the components of a color to the given values and save the results to out color. * @zh 设置颜色值 */ - public static set (out: Out, r: number, g: number, b: number, a: number) { + public static set (out: Out, r: number, g: number, b: number, a: number): Out { out.r = r; out.g = g; out.b = b; @@ -128,7 +128,7 @@ export class Color extends ValueType { * @en Converts the hexadecimal formal color into rgb formal and save the results to out color. * @zh 从十六进制颜色字符串中读入颜色到 out 中 */ - public static fromHEX (out: Out, hexString: string) { + public static fromHEX (out: Out, hexString: string): Out { hexString = (hexString.indexOf('#') === 0) ? hexString.substring(1) : hexString; out.r = parseInt(hexString.substr(0, 2), 16) || 0; out.g = parseInt(hexString.substr(2, 2), 16) || 0; @@ -143,7 +143,7 @@ export class Color extends ValueType { * @en Add two colors by components. And save the results to out color. * @zh 逐通道颜色加法 */ - public static add (out: Out, a: Out, b: Out) { + public static add (out: Out, a: Out, b: Out): Out { out.r = a.r + b.r; out.g = a.g + b.g; out.b = a.b + b.b; @@ -155,7 +155,7 @@ export class Color extends ValueType { * @en Subtract each components of color b from each components of color a. And save the results to out color. * @zh 逐通道颜色减法 */ - public static subtract (out: Out, a: Out, b: Out) { + public static subtract (out: Out, a: Out, b: Out): Out { out.r = a.r - b.r; out.g = a.g - b.g; out.b = a.b - b.b; @@ -167,7 +167,7 @@ export class Color extends ValueType { * @en Multiply each components of two colors. And save the results to out color. * @zh 逐通道颜色乘法 */ - public static multiply (out: Out, a: Out, b: Out) { + public static multiply (out: Out, a: Out, b: Out): Out { out.r = a.r * b.r; out.g = a.g * b.g; out.b = a.b * b.b; @@ -179,7 +179,7 @@ export class Color extends ValueType { * @en Divide each components of color a by each components of color b. And save the results to out color. * @zh 逐通道颜色除法 */ - public static divide (out: Out, a: Out, b: Out) { + public static divide (out: Out, a: Out, b: Out): Out { out.r = a.r / b.r; out.g = a.g / b.g; out.b = a.b / b.b; @@ -191,7 +191,7 @@ export class Color extends ValueType { * @en Multiply all channels in a color with the given scale factor, and save the results to out color. * @zh 全通道统一缩放颜色 */ - public static scale (out: Out, a: Out, b: number) { + public static scale (out: Out, a: Out, b: number): Out { out.r = a.r * b; out.g = a.g * b; out.b = a.b * b; @@ -203,7 +203,7 @@ export class Color extends ValueType { * @en Performs a linear interpolation between two colors. * @zh 逐通道颜色线性插值:A + t * (B - A) */ - public static lerp (out: Out, from: Out, to: Out, ratio: number) { + public static lerp (out: Out, from: Out, to: Out, ratio: number): Out { let r = from.r; let g = from.g; let b = from.b; @@ -221,7 +221,7 @@ export class Color extends ValueType { * @zh 颜色转数组 * @param ofs Array Start Offset */ - public static toArray> (out: Out, a: IColorLike, ofs = 0) { + public static toArray> (out: Out, a: IColorLike, ofs = 0): Out { const scale = (a instanceof Color || a.a > 1) ? 1 / 255 : 1; out[ofs + 0] = a.r * scale; out[ofs + 1] = a.g * scale; @@ -235,7 +235,7 @@ export class Color extends ValueType { * @zh 数组转颜色 * @param ofs Array Start Offset */ - public static fromArray (arr: IWritableArrayLike, out: Out, ofs = 0) { + public static fromArray (arr: IWritableArrayLike, out: Out, ofs = 0): Out { out.r = arr[ofs + 0] * 255; out.g = arr[ofs + 1] * 255; out.b = arr[ofs + 2] * 255; @@ -252,7 +252,7 @@ export class Color extends ValueType { * @param uint32 @en The unsigned 32 bit integer @zh 32 位无符号整数 * @returns @en The `out` object @zh `out` 对象 */ - public static fromUint32 (out: Out, uint32: number) { + public static fromUint32 (out: Out, uint32: number): Out { out._val = uint32; return out; } @@ -273,7 +273,7 @@ export class Color extends ValueType { * @en Check whether the two given colors are identical * @zh 颜色等价判断 */ - public static strictEquals (a: Out, b: Out) { + public static strictEquals (a: Out, b: Out): boolean { return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; } @@ -281,7 +281,7 @@ export class Color extends ValueType { * @en Check whether the two given colors are approximately equivalent. Difference of each channel is smaller that the epsilon. * @zh 排除浮点数误差的颜色近似等价判断 */ - public static equals (a: Out, b: Out, epsilon = EPSILON) { + public static equals (a: Out, b: Out, epsilon = EPSILON): boolean { const hasInf = Math.abs(a.r) === Infinity || Math.abs(a.g) === Infinity || Math.abs(a.b) === Infinity || Math.abs(a.a) === Infinity; return !hasInf && (Math.abs(a.r - b.r) <= epsilon * Math.max(1.0, Math.abs(a.r), Math.abs(b.r)) && Math.abs(a.g - b.g) <= epsilon * Math.max(1.0, Math.abs(a.g), Math.abs(b.g)) @@ -293,7 +293,7 @@ export class Color extends ValueType { * @en Convert the given color to a hex color value. And save the results to out color. * @zh 获取指定颜色的整型数据表示 */ - public static hex (a: Out) { + public static hex (a: Out): number { return ((a.r * 255) << 24 | (a.g * 255) << 16 | (a.b * 255) << 8 | a.a * 255) >>> 0; } @@ -301,7 +301,7 @@ export class Color extends ValueType { * @en Get or set red channel value. * @zh 获取或设置当前颜色的 Red 通道。 */ - get r () { + get r (): number { return this._val & 0x000000ff; } @@ -314,7 +314,7 @@ export class Color extends ValueType { * @en Get or set green channel value. * @zh 获取或设置当前颜色的 Green 通道。 */ - get g () { + get g (): number { return (this._val & 0x0000ff00) >> 8; } @@ -327,7 +327,7 @@ export class Color extends ValueType { * @en Get or set blue channel value. * @zh 获取或设置当前颜色的 Blue 通道。 */ - get b () { + get b (): number { return (this._val & 0x00ff0000) >> 16; } @@ -339,7 +339,7 @@ export class Color extends ValueType { /** @en Get or set alpha channel value. * @zh 获取或设置当前颜色的透明度通道。 */ - get a () { + get a (): number { return (this._val & 0xff000000) >>> 24; } @@ -349,13 +349,13 @@ export class Color extends ValueType { } // compatibility with vector interfaces - get x () { return this.r * toFloat; } + get x (): number { return this.r * toFloat; } set x (value) { this.r = value * 255; } - get y () { return this.g * toFloat; } + get y (): number { return this.g * toFloat; } set y (value) { this.g = value * 255; } - get z () { return this.b * toFloat; } + get z (): number { return this.b * toFloat; } set z (value) { this.b = value * 255; } - get w () { return this.a * toFloat; } + get w (): number { return this.a * toFloat; } set w (value) { this.a = value * 255; } /** @@ -403,7 +403,7 @@ export class Color extends ValueType { * @en Clone a new color from the current color. * @zh 克隆当前颜色。 */ - public clone () { + public clone (): Color { const ret = new Color(); ret._val = this._val; return ret; @@ -415,7 +415,7 @@ export class Color extends ValueType { * @param other Specified color * @returns Returns `true` when all channels of both colours are equal; otherwise returns `false`. */ - public equals (other: Color) { + public equals (other: Color): boolean { return other && this._val === other._val; } @@ -425,7 +425,7 @@ export class Color extends ValueType { * @param to Target color * @param ratio The interpolation coefficient.The range is [0,1]. */ - public lerp (to: Color, ratio: number) { + public lerp (to: Color, ratio: number): Color { let r = this.r; let g = this.g; let b = this.b; @@ -443,7 +443,7 @@ export class Color extends ValueType { * @zh 返回当前颜色的字符串表示。 * @returns A string representation of the current color. */ - public toString () { + public toString (): string { return `rgba(${this.r.toFixed()}, ${this.g.toFixed()}, ${this.b.toFixed()}, ${this.a.toFixed()})`; } @@ -462,7 +462,7 @@ export class Color extends ValueType { * color.toCSS("#rrggbb"); // "#000000"; * ``` */ - public toCSS (opt: ('rgba' | 'rgb' | '#rrggbb' | '#rrggbbaa') = 'rgba') { + public toCSS (opt: ('rgba' | 'rgb' | '#rrggbb' | '#rrggbbaa') = 'rgba'): string { if (opt === 'rgba') { return `rgba(${this.r},${this.g},${this.b},${(this.a * toFloat).toFixed(2)})`; } else if (opt === 'rgb') { @@ -481,7 +481,7 @@ export class Color extends ValueType { * @param hexString the hex string * @returns `this` */ - public fromHEX (hexString: string) { + public fromHEX (hexString: string): Color { hexString = (hexString.indexOf('#') === 0) ? hexString.substring(1) : hexString; const r = parseInt(hexString.substr(0, 2), 16) || 0; const g = parseInt(hexString.substr(2, 2), 16) || 0; @@ -507,7 +507,7 @@ export class Color extends ValueType { * color.toHEX("#rrggbb"); // "ff0e00" * ``` */ - public toHEX (fmt: '#rgb' | '#rrggbb' | '#rrggbbaa' = '#rrggbb') { + public toHEX (fmt: '#rgb' | '#rrggbb' | '#rrggbbaa' = '#rrggbb'): string { const prefix = '0'; // #rrggbb const hex = [ @@ -536,7 +536,7 @@ export class Color extends ValueType { * color.toRGBValue(); * ``` */ - public toRGBValue () { + public toRGBValue (): number { return this._val & 0x00ffffff; } @@ -553,7 +553,7 @@ export class Color extends ValueType { * color.fromHSV(0, 0, 1); // Color {r: 255, g: 255, b: 255, a: 255}; * ``` */ - public fromHSV (h: number, s: number, v: number) { + public fromHSV (h: number, s: number, v: number): Color { let r = 0; let g = 0; let b = 0; @@ -628,7 +628,7 @@ export class Color extends ValueType { * color.toHSV(); // {h: 0.1533864541832669, s: 0.9843137254901961, v: 1} * ``` */ - public toHSV () { + public toHSV (): { h: number; s: number; v: number; } { const r = this.r * toFloat; const g = this.g * toFloat; const b = this.b * toFloat; @@ -692,7 +692,7 @@ export class Color extends ValueType { * @zh 将当前颜色乘以与指定颜色 * @param other The specified color. */ - public multiply (other: Color) { + public multiply (other: Color): Color { const r = ((this._val & 0x000000ff) * other.r) >> 8; const g = ((this._val & 0x0000ff00) * other.g) >> 8; const b = ((this._val & 0x00ff0000) * other.b) >> 8; @@ -704,7 +704,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_r_unsafe (red) { + public _set_r_unsafe (red): Color { this._val = ((this._val & 0xffffff00) | red) >>> 0; return this; } @@ -712,7 +712,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_g_unsafe (green) { + public _set_g_unsafe (green): Color { this._val = ((this._val & 0xffff00ff) | (green << 8)) >>> 0; return this; } @@ -720,7 +720,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_b_unsafe (blue) { + public _set_b_unsafe (blue): Color { this._val = ((this._val & 0xff00ffff) | (blue << 16)) >>> 0; return this; } @@ -728,7 +728,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_a_unsafe (alpha) { + public _set_a_unsafe (alpha): Color { this._val = ((this._val & 0x00ffffff) | (alpha << 24)) >>> 0; return this; } @@ -740,7 +740,7 @@ legacyCC.Color = Color; export function color (other: Color | string): Color; export function color (r?: number, g?: number, b?: number, a?: number): Color; -export function color (r?: number | Color | string, g?: number, b?: number, a?: number) { +export function color (r?: number | Color | string, g?: number, b?: number, a?: number): Color { return new Color(r as any, g, b, a); } @@ -780,7 +780,7 @@ export function linearToSrgb8Bit (x: number): number { let SRGB_8BIT_TO_LINEAR: Array = []; for (let i = 0; i < 256; i++) { SRGB_8BIT_TO_LINEAR.push(srgbToLinear(i / 255.0)); } -export function clampVec3 (val: Vec3, min: Vec3, max: Vec3) { +export function clampVec3 (val: Vec3, min: Vec3, max: Vec3): Vec3 { if (min > max) { const temp = min; min = max; @@ -789,7 +789,7 @@ export function clampVec3 (val: Vec3, min: Vec3, max: Vec3) { return val < min ? min : val > max ? max : val; } -export function floorVec3 (val: Vec3) { +export function floorVec3 (val: Vec3): Vec3 { const temp = val.clone(); temp.x = Math.floor(val.x); temp.y = Math.floor(val.y); @@ -797,7 +797,7 @@ export function floorVec3 (val: Vec3) { return temp; } -export function stepVec3 (a: Vec3, b: Vec3) { +export function stepVec3 (a: Vec3, b: Vec3): Vec3 { if (a < b) { return b; } else { @@ -810,7 +810,7 @@ export function stepVec3 (a: Vec3, b: Vec3) { * @zh 三通道rgb颜色pack成四通道rbge格式 * @param rgb Vec3 */ -export function packRGBE (rgb: Vec3) { +export function packRGBE (rgb: Vec3): Vec4 { const maxComp = Math.max(Math.max(rgb.x, rgb.y), rgb.z); let e = 128.0; if (maxComp > 0.0001) { diff --git a/cocos/core/math/deprecated.ts b/cocos/core/math/deprecated.ts index 611ee945755..8c5df205bf4 100644 --- a/cocos/core/math/deprecated.ts +++ b/cocos/core/math/deprecated.ts @@ -360,7 +360,7 @@ replaceProperty(Color, 'Color', [ { name: 'fromHex', newName: 'fromHEX', - customFunction (...args: any) { + customFunction (...args: any): any { const arg1 = args[1].toString(16); return legacyCC.Color.fromHEX(args[0], arg1); }, diff --git a/cocos/core/math/mat3.ts b/cocos/core/math/mat3.ts index 91cecfc901f..1f9a3b7e0d3 100644 --- a/cocos/core/math/mat3.ts +++ b/cocos/core/math/mat3.ts @@ -42,7 +42,7 @@ export class Mat3 extends ValueType { * @en Clone a matrix and save the results to out matrix * @zh 获得指定矩阵的拷贝 */ - public static clone (a: Out) { + public static clone (a: Out): Mat3 { return new Mat3( a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, @@ -54,7 +54,7 @@ export class Mat3 extends ValueType { * @en Copy content of a matrix into another and save the results to out matrix * @zh 复制目标矩阵 */ - public static copy (out: Out, a: Out) { + public static copy (out: Out, a: Out): Out { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; @@ -76,7 +76,7 @@ export class Mat3 extends ValueType { m00: number, m01: number, m02: number, m03: number, m04: number, m05: number, m06: number, m07: number, m08: number, - ) { + ): Out { out.m00 = m00; out.m01 = m01; out.m02 = m02; out.m03 = m03; out.m04 = m04; out.m05 = m05; out.m06 = m06; out.m07 = m07; out.m08 = m08; @@ -87,7 +87,7 @@ export class Mat3 extends ValueType { * @en Reset the out matrix to an identity matrix * @zh 将目标赋值为单位矩阵 */ - public static identity (out: Out) { + public static identity (out: Out): Out { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -104,7 +104,7 @@ export class Mat3 extends ValueType { * @en Transposes a matrix and save the results to out matrix * @zh 转置矩阵 */ - public static transpose (out: Out, a: Out) { + public static transpose (out: Out, a: Out): Out { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { const a01 = a.m01; @@ -135,7 +135,7 @@ export class Mat3 extends ValueType { * @en Inverts a matrix. When matrix is not invertible the matrix will be set to zeros. * @zh 矩阵求逆,注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ - public static invert (out: Out, a: Out) { + public static invert (out: Out, a: Out): Out { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a10 = a.m03; const a11 = a.m04; const a12 = a.m05; const a20 = a.m06; const a21 = a.m07; const a22 = a.m08; @@ -171,7 +171,7 @@ export class Mat3 extends ValueType { * @en Calculates the determinant of a matrix * @zh 矩阵行列式 */ - public static determinant (a: Out) { + public static determinant (a: Out): number { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a10 = a.m03; const a11 = a.m04; const a12 = a.m05; const a20 = a.m06; const a21 = a.m07; const a22 = a.m08; @@ -183,7 +183,7 @@ export class Mat3 extends ValueType { * @en Multiply two matrices explicitly and save the results to out matrix: a * b * @zh 矩阵乘法:a * b */ - public static multiply (out: Out, a: Out, b: Out) { + public static multiply (out: Out, a: Out, b: Out): Out { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a10 = a.m03; const a11 = a.m04; const a12 = a.m05; const a20 = a.m06; const a21 = a.m07; const a22 = a.m08; @@ -210,7 +210,7 @@ export class Mat3 extends ValueType { * @en Take the first third order of the fourth order matrix and multiply by the third order matrix: a * b * @zh 取四阶矩阵的前三阶,与三阶矩阵相乘:a * b */ - public static multiplyMat4 (out: Out, a: Out, b: IMat4Like) { + public static multiplyMat4 (out: Out, a: Out, b: IMat4Like): Out { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a10 = a.m03; const a11 = a.m04; const a12 = a.m05; const a20 = a.m06; const a21 = a.m07; const a22 = a.m08; @@ -240,7 +240,7 @@ export class Mat3 extends ValueType { /** * @deprecated since v3.8.0, the function name is misleading, please use translate instead. */ - public static transform (out: Out, a: Out, v: VecLike) { + public static transform (out: Out, a: Out, v: VecLike): void { this.translate(out, a, v); } @@ -248,7 +248,7 @@ export class Mat3 extends ValueType { * @en Multiply a matrix with a translation vector given by a translation offset, first translate, then transform:a * T(v). * @zh 在给定矩阵变换基础上加入位移变换,先位移,再变换,即a * T(v)。 */ - public static translate (out: Out, a: Out, v: VecLike) { + public static translate (out: Out, a: Out, v: VecLike): Out { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a10 = a.m03; const a11 = a.m04; const a12 = a.m05; const a20 = a.m06; const a21 = a.m07; const a22 = a.m08; @@ -272,7 +272,7 @@ export class Mat3 extends ValueType { * @en Multiply a matrix with a scale matrix given by a scale vector and save the results to out matrix, first scale, then transform:a * S(v). * @zh 在给定矩阵变换基础上加入新缩放变换,先缩放,再变换,即a * S(v)。 */ - public static scale (out: Out, a: Out, v: VecLike) { + public static scale (out: Out, a: Out, v: VecLike): Out { const x = v.x; const y = v.y; out.m00 = x * a.m00; @@ -294,7 +294,7 @@ export class Mat3 extends ValueType { * @zh 在给定矩阵变换基础上加入新旋转变换,先旋转,再变换,即a * R(rad)。 * @param rad radian of rotation */ - public static rotate (out: Out, a: Out, rad: number) { + public static rotate (out: Out, a: Out, rad: number): Out { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a10 = a.m03; const a11 = a.m04; const a12 = a.m05; const a20 = a.m06; const a21 = a.m07; const a22 = a.m08; @@ -320,7 +320,7 @@ export class Mat3 extends ValueType { * @en Copies the first third order matrix of a fourth order matrix to the out third order matrix * @zh 取四阶矩阵的前三阶 */ - public static fromMat4 (out: Out, a: IMat4Like) { + public static fromMat4 (out: Out, a: IMat4Like): Out { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; @@ -339,7 +339,7 @@ export class Mat3 extends ValueType { * @param view The view direction, it`s must be normalized. * @param up The view up direction, it`s must be normalized, default value is (0, 1, 0). */ - public static fromViewUp (out: Out, view: VecLike, up?: Vec3) { + public static fromViewUp (out: Out, view: VecLike, up?: Vec3): Out { if (Vec3.lengthSqr(view) < EPSILON * EPSILON) { Mat3.identity(out); return out; @@ -368,7 +368,7 @@ export class Mat3 extends ValueType { * @en Sets the given matrix with a translation vector and save the results to out matrix * @zh 计算位移矩阵 */ - public static fromTranslation (out: Out, v: VecLike) { + public static fromTranslation (out: Out, v: VecLike): Out { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -385,7 +385,7 @@ export class Mat3 extends ValueType { * @en Sets the given matrix with a scale vector and save the results to out matrix * @zh 计算缩放矩阵 */ - public static fromScaling (out: Out, v: VecLike) { + public static fromScaling (out: Out, v: VecLike): Out { out.m00 = v.x; out.m01 = 0; out.m02 = 0; @@ -404,7 +404,7 @@ export class Mat3 extends ValueType { * @en Sets the given matrix with a given angle and save the results to out matrix * @zh 计算旋转矩阵 */ - public static fromRotation (out: Out, rad: number) { + public static fromRotation (out: Out, rad: number): Out { const s = Math.sin(rad); const c = Math.cos(rad); out.m00 = c; @@ -425,7 +425,7 @@ export class Mat3 extends ValueType { * @en Sets the given matrix with the given quaternion and save the results to out matrix * @zh 根据四元数旋转信息计算矩阵 */ - public static fromQuat (out: Out, q: IQuatLike) { + public static fromQuat (out: Out, q: IQuatLike): Out { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -463,7 +463,7 @@ export class Mat3 extends ValueType { * @en Calculates the upper-left 3x3 matrix of a 4x4 matrix's inverse transpose * @zh 计算指定四维矩阵的逆转置三维矩阵 */ - public static inverseTransposeMat4 (out: Out, a: IMat4Like) { + public static inverseTransposeMat4 (out: Out, a: IMat4Like): Out | null { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; @@ -510,7 +510,7 @@ export class Mat3 extends ValueType { * @zh 矩阵转数组 * @param ofs Array Start Offset */ - public static toArray > (out: Out, m: IMat3Like, ofs = 0) { + public static toArray > (out: Out, m: IMat3Like, ofs = 0): Out { out[ofs + 0] = m.m00; out[ofs + 1] = m.m01; out[ofs + 2] = m.m02; @@ -528,7 +528,7 @@ export class Mat3 extends ValueType { * @zh 数组转矩阵 * @param ofs Array Start Offset */ - public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0) { + public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0): Out { out.m00 = arr[ofs + 0]; out.m01 = arr[ofs + 1]; out.m02 = arr[ofs + 2]; @@ -545,7 +545,7 @@ export class Mat3 extends ValueType { * @en Adds two matrices and save the results to out matrix * @zh 逐元素矩阵加法 */ - public static add (out: Out, a: Out, b: Out) { + public static add (out: Out, a: Out, b: Out): Out { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; @@ -562,7 +562,7 @@ export class Mat3 extends ValueType { * @en Subtracts matrix b from matrix a and save the results to out matrix * @zh 逐元素矩阵减法 */ - public static subtract (out: Out, a: Out, b: Out) { + public static subtract (out: Out, a: Out, b: Out): Out { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; @@ -579,7 +579,7 @@ export class Mat3 extends ValueType { * @en Multiply each element of a matrix by a scalar number and save the results to out matrix * @zh 矩阵标量乘法 */ - public static multiplyScalar (out: Out, a: Out, b: number) { + public static multiplyScalar (out: Out, a: Out, b: number): Out { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; @@ -596,7 +596,7 @@ export class Mat3 extends ValueType { * @en Adds two matrices after multiplying each element of the second operand by a scalar number. And save the results to out matrix. * @zh 逐元素矩阵标量乘加: A + B * scale */ - public static multiplyScalarAndAdd (out: Out, a: Out, b: Out, scale: number) { + public static multiplyScalarAndAdd (out: Out, a: Out, b: Out, scale: number): Out { out.m00 = b.m00 * scale + a.m00; out.m01 = b.m01 * scale + a.m01; out.m02 = b.m02 * scale + a.m02; @@ -613,7 +613,7 @@ export class Mat3 extends ValueType { * @en Returns whether the specified matrices are equal. * @zh 矩阵等价判断 */ - public static strictEquals (a: Out, b: Out) { + public static strictEquals (a: Out, b: Out): boolean { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08; @@ -623,7 +623,7 @@ export class Mat3 extends ValueType { * @en Returns whether the specified matrices are approximately equal. * @zh 排除浮点数误差的矩阵近似等价判断 */ - public static equals (a: Out, b: Out, epsilon = EPSILON) { + public static equals (a: Out, b: Out, epsilon = EPSILON): boolean { return ( Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) @@ -761,7 +761,7 @@ export class Mat3 extends ValueType { * @en Clone a new matrix from the current matrix. * @zh 克隆当前矩阵。 */ - public clone () { + public clone (): Mat3 { const t = this; return new Mat3( t.m00, t.m01, t.m02, @@ -789,7 +789,7 @@ export class Mat3 extends ValueType { public set (m00: number | Mat3 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, - m06 = 0, m07 = 0, m08 = 1) { + m06 = 0, m07 = 0, m08 = 1): Mat3 { 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; @@ -840,7 +840,7 @@ export class Mat3 extends ValueType { * @zh 返回当前矩阵的字符串表示。 * @return The string representation of this matrix */ - public toString () { + public toString (): string { const t = this; return `[\n${ t.m00}, ${t.m01}, ${t.m02},\n${ @@ -854,7 +854,7 @@ export class Mat3 extends ValueType { * @zh 将当前矩阵设为单位矩阵。 * @return `this` */ - public identity () { + public identity (): Mat3 { this.m00 = 1; this.m01 = 0; this.m02 = 0; @@ -871,7 +871,7 @@ export class Mat3 extends ValueType { * @en Transposes the current matrix. * @zh 计算当前矩阵的转置矩阵。 */ - public transpose () { + public transpose (): Mat3 { const a01 = this.m01; const a02 = this.m02; const a12 = this.m05; this.m01 = this.m03; this.m02 = this.m06; @@ -886,7 +886,7 @@ export class Mat3 extends ValueType { * @en Inverts the current matrix. When matrix is not invertible the matrix will be set to zeros. * @zh 计算当前矩阵的逆矩阵。注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ - public invert () { + public invert (): Mat3 { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a10 = this.m03; const a11 = this.m04; const a12 = this.m05; const a20 = this.m06; const a21 = this.m07; const a22 = this.m08; @@ -934,7 +934,7 @@ export class Mat3 extends ValueType { * @zh 矩阵加法。将当前矩阵与指定矩阵的相加,结果返回给当前矩阵。 * @param mat the second operand */ - public add (mat: Mat3) { + public add (mat: Mat3): Mat3 { this.m00 += mat.m00; this.m01 += mat.m01; this.m02 += mat.m02; @@ -952,7 +952,7 @@ export class Mat3 extends ValueType { * @zh 计算矩阵减法。将当前矩阵减去指定矩阵的结果赋值给当前矩阵。 * @param mat the second operand */ - public subtract (mat: Mat3) { + public subtract (mat: Mat3): Mat3 { this.m00 -= mat.m00; this.m01 -= mat.m01; this.m02 -= mat.m02; @@ -970,7 +970,7 @@ export class Mat3 extends ValueType { * @zh 矩阵乘法。将当前矩阵左乘指定矩阵的结果赋值给当前矩阵。 * @param mat the second operand */ - public multiply (mat: Mat3) { + public multiply (mat: Mat3): Mat3 { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a10 = this.m03; const a11 = this.m04; const a12 = this.m05; const a20 = this.m06; const a21 = this.m07; const a22 = this.m08; @@ -998,7 +998,7 @@ export class Mat3 extends ValueType { * @zh 矩阵数乘。将当前矩阵与指定标量的数乘结果赋值给当前矩阵。 * @param scalar amount to scale the matrix's elements by */ - public multiplyScalar (scalar: number) { + public multiplyScalar (scalar: number): Mat3 { this.m00 *= scalar; this.m01 *= scalar; this.m02 *= scalar; @@ -1016,7 +1016,7 @@ export class Mat3 extends ValueType { * @zh 将当前矩阵左乘缩放矩阵的结果赋值给当前矩阵,缩放矩阵由各个轴的缩放给出,即M * S(vec)。 * @param vec vector to scale by */ - public scale (vec: Vec3) { + public scale (vec: Vec3): Mat3 { const x = vec.x; const y = vec.y; this.m00 = x * this.m00; @@ -1038,7 +1038,7 @@ export class Mat3 extends ValueType { * @zh 将当前矩阵左乘旋转矩阵的结果赋值给当前矩阵,旋转矩阵由旋转轴和旋转角度给出,即M * R(rad)。 * @param rad radian of rotation */ - public rotate (rad: number) { + public rotate (rad: number): Mat3 { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a10 = this.m03; const a11 = this.m04; const a12 = this.m05; const a20 = this.m06; const a21 = this.m07; const a22 = this.m08; @@ -1066,7 +1066,7 @@ export class Mat3 extends ValueType { * @param q The quaternion. * @returns this */ - public fromQuat (q: Quat) { + public fromQuat (q: Quat): Mat3 { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; diff --git a/cocos/core/math/mat4.ts b/cocos/core/math/mat4.ts index b90d2c16bc7..067a3219bf3 100644 --- a/cocos/core/math/mat4.ts +++ b/cocos/core/math/mat4.ts @@ -53,7 +53,7 @@ export class Mat4 extends ValueType { * @en Clone a matrix and save the results to out matrix * @zh 获得指定矩阵的拷贝 */ - public static clone (a: IMat4Like) { + public static clone (a: IMat4Like): Mat4 { return new Mat4( a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, @@ -66,7 +66,7 @@ export class Mat4 extends ValueType { * @en Copy a matrix into the out matrix * @zh 复制目标矩阵 */ - public static copy (out: Out, a: Out) { + public static copy (out: Out, a: Out): Out { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; @@ -115,7 +115,7 @@ export class Mat4 extends ValueType { m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number, - ) { + ): Out { out.m00 = m00; out.m01 = m01; out.m02 = m02; out.m03 = m03; out.m04 = m10; out.m05 = m11; out.m06 = m12; out.m07 = m13; out.m08 = m20; out.m09 = m21; out.m10 = m22; out.m11 = m23; @@ -127,7 +127,7 @@ export class Mat4 extends ValueType { * @en return an identity matrix. * @zh 将目标赋值为单位矩阵 */ - public static identity (out: Out) { + public static identity (out: Out): Out { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -151,7 +151,7 @@ export class Mat4 extends ValueType { * @en Transposes a matrix and save the results to out matrix * @zh 转置矩阵 */ - public static transpose (out: Out, a: Out) { + public static transpose (out: Out, a: Out): Out { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a12 = a.m06; const a13 = a.m07; const a23 = a.m11; @@ -192,7 +192,7 @@ export class Mat4 extends ValueType { * @en Inverts a matrix. When matrix is not invertible the matrix will be set to zeros. * @zh 矩阵求逆,注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ - public static invert (out: Out, a: Out) { + public static invert (out: Out, a: Out): Out { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; @@ -280,7 +280,7 @@ export class Mat4 extends ValueType { * @param b The second operand * @returns out matrix */ - public static multiply (out: Out, a: Out, b: Out) { + public static multiply (out: Out, a: Out, b: Out): Out { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; @@ -321,7 +321,7 @@ export class Mat4 extends ValueType { * @param a The matrix to translate * @param v The vector to translate with */ - public static transform (out: Out, a: Out, v: VecLike) { + public static transform (out: Out, a: Out, v: VecLike): Out { const x = v.x; const y = v.y; const z = v.z; if (a === out) { out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12; @@ -355,7 +355,7 @@ export class Mat4 extends ValueType { * @param v The vector to translate with * @deprecated Since 3.8.0, please use [[transform]] instead */ - public static translate (out: Out, a: Out, v: VecLike) { + public static translate (out: Out, a: Out, v: VecLike): Out { if (a === out) { out.m12 += v.x; out.m13 += v.y; @@ -377,7 +377,7 @@ export class Mat4 extends ValueType { * the scale is applied before the matrix, i.e. (out = a * S) * @zh 在给定矩阵变换基础上加入新缩放变换,并将结果保存到 out 矩阵中,缩放变换将应用在矩阵变换之前,即 (out = a * S) */ - public static scale (out: Out, a: Out, v: VecLike) { + public static scale (out: Out, a: Out, v: VecLike): Out { const x = v.x; const y = v.y; const z = v.z; out.m00 = a.m00 * x; out.m01 = a.m01 * x; @@ -405,7 +405,7 @@ export class Mat4 extends ValueType { * @param rad Angle of rotation (in radians) * @param axis axis of rotation */ - public static rotate (out: Out, a: Out, rad: number, axis: VecLike) { + public static rotate (out: Out, a: Out, rad: number, axis: VecLike): Out | null { let x = axis.x; let y = axis.y; let z = axis.z; let len = Math.sqrt(x * x + y * y + z * z); @@ -465,7 +465,7 @@ export class Mat4 extends ValueType { * @zh 在给定矩阵变换基础上加入绕 X 轴的旋转变换, 并将结果保存到 out 矩阵中,旋转变换将应用在矩阵变换之前,即 (out = a * R) * @param rad Angle of rotation (in radians) */ - public static rotateX (out: Out, a: Out, rad: number) { + public static rotateX (out: Out, a: Out, rad: number): Out { const s = Math.sin(rad); const c = Math.cos(rad); const a10 = a.m04; @@ -506,7 +506,7 @@ export class Mat4 extends ValueType { * @zh 在给定矩阵变换基础上加入绕 Y 轴的旋转变换 * @param rad Angle of rotation (in radians) */ - public static rotateY (out: Out, a: Out, rad: number) { + public static rotateY (out: Out, a: Out, rad: number): Out { // ref: https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle const s = Math.sin(rad); @@ -549,7 +549,7 @@ export class Mat4 extends ValueType { * @zh 在给定矩阵变换基础上加入绕 Z 轴的旋转变换 * @param rad Angle of rotation (in radians) */ - public static rotateZ (out: Out, a: Out, rad: number) { + public static rotateZ (out: Out, a: Out, rad: number): Out { // ref: https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle const s = Math.sin(rad); @@ -592,7 +592,7 @@ export class Mat4 extends ValueType { * @en Sets the out matrix with a translation vector * @zh 计算位移矩阵 */ - public static fromTranslation (out: Out, v: VecLike) { + public static fromTranslation (out: Out, v: VecLike): Out { out.m00 = 1; out.m01 = 0; out.m02 = 0; @@ -616,7 +616,7 @@ export class Mat4 extends ValueType { * @en Sets the out matrix with a scale vector * @zh 计算缩放矩阵 */ - public static fromScaling (out: Out, v: VecLike) { + public static fromScaling (out: Out, v: VecLike): Out { out.m00 = v.x; out.m01 = 0; out.m02 = 0; @@ -640,7 +640,7 @@ export class Mat4 extends ValueType { * @en Sets the out matrix with rotation angle * @zh 计算旋转矩阵 */ - public static fromRotation (out: Out, rad: number, axis: VecLike) { + public static fromRotation (out: Out, rad: number, axis: VecLike): Out | null { let x = axis.x; let y = axis.y; let z = axis.z; let len = Math.sqrt(x * x + y * y + z * z); @@ -681,7 +681,7 @@ export class Mat4 extends ValueType { * @en Calculates the matrix representing a rotation around the X axis * @zh 计算绕 X 轴的旋转矩阵 */ - public static fromXRotation (out: Out, rad: number) { + public static fromXRotation (out: Out, rad: number): Out { const s = Math.sin(rad); const c = Math.cos(rad); // Perform axis-specific matrix multiplication @@ -708,7 +708,7 @@ export class Mat4 extends ValueType { * @en Calculates the matrix representing a rotation around the Y axis * @zh 计算绕 Y 轴的旋转矩阵 */ - public static fromYRotation (out: Out, rad: number) { + public static fromYRotation (out: Out, rad: number): Out { const s = Math.sin(rad); const c = Math.cos(rad); // Perform axis-specific matrix multiplication @@ -735,7 +735,7 @@ export class Mat4 extends ValueType { * @en Calculates the matrix representing a rotation around the Z axis * @zh 计算绕 Z 轴的旋转矩阵 */ - public static fromZRotation (out: Out, rad: number) { + public static fromZRotation (out: Out, rad: number): Out { const s = Math.sin(rad); const c = Math.cos(rad); // Perform axis-specific matrix multiplication @@ -763,7 +763,7 @@ export class Mat4 extends ValueType { * The order is rotation then translation. * @zh 根据旋转和位移信息计算矩阵 */ - public static fromRT (out: Out, q: Quat, v: VecLike) { + public static fromRT (out: Out, q: Quat, v: VecLike): Out { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -805,7 +805,7 @@ export class Mat4 extends ValueType { * @en Extracts the translation from the matrix, assuming it's composed in order of scale, rotation, translation * @zh 提取矩阵的位移信息, 默认矩阵中的变换以 S->R->T 的顺序应用 */ - public static getTranslation (out: VecLike, mat: InType) { + public static getTranslation (out: VecLike, mat: InType): VecLike { out.x = mat.m12; out.y = mat.m13; out.z = mat.m14; @@ -817,7 +817,7 @@ export class Mat4 extends ValueType { * @en Extracts the scale vector from the matrix, assuming it's composed in order of scale, rotation, translation * @zh 提取矩阵的缩放信息, 默认矩阵中的变换以 S->R->T 的顺序应用 */ - public static getScaling (out: VecLike, mat: InType) { + public static getScaling (out: VecLike, mat: InType): VecLike { const m00 = m3_1.m00 = mat.m00; const m01 = m3_1.m01 = mat.m01; const m02 = m3_1.m02 = mat.m02; @@ -839,7 +839,7 @@ export class Mat4 extends ValueType { * @en Extracts the rotation from the matrix, assuming it's composed in order of scale, rotation, translation * @zh 提取矩阵的旋转信息, 默认输入矩阵不含有缩放信息,如考虑缩放应使用 `toRTS` 函数。 */ - public static getRotation (out: Quat, mat: InType) { + public static getRotation (out: Quat, mat: InType): Quat { const trace = mat.m00 + mat.m05 + mat.m10; let S = 0; @@ -883,7 +883,7 @@ export class Mat4 extends ValueType { * * @deprecated Since 3.8.0, please use toSRT instead */ - public static toRTS (m: InType, q: Quat | null, v: VecLike | null, s: VecLike | null) { + public static toRTS (m: InType, q: Quat | null, v: VecLike | null, s: VecLike | null): void { const sx = Vec3.set(v3_1, m.m00, m.m01, m.m02).length(); const sy = Vec3.set(v3_1, m.m04, m.m05, m.m06).length(); const sz = Vec3.set(v3_1, m.m08, m.m09, m.m10).length(); @@ -926,7 +926,7 @@ export class Mat4 extends ValueType { * @param v The corresponding translate vector * @param s The corresponding scaling vector */ - public static toSRT (m: InType, q: Quat | null, v: VecLike | null, s: VecLike | null) { + public static toSRT (m: InType, q: Quat | null, v: VecLike | null, s: VecLike | null): void { const sx = Vec3.set(v3_1, m.m00, m.m01, m.m02).length(); const sy = Vec3.set(v3_1, m.m04, m.m05, m.m06).length(); const sz = Vec3.set(v3_1, m.m08, m.m09, m.m10).length(); @@ -979,7 +979,7 @@ export class Mat4 extends ValueType { * @zh 根据旋转、位移、缩放信息计算矩阵,以 S->R->T 的顺序应用 * @deprecated Since 3.8.0, please use [[fromSRT]] instead. */ - public static fromRTS (out: Out, q: Quat, v: VecLike, s: VecLike) { + public static fromRTS (out: Out, q: Quat, v: VecLike, s: VecLike): Out { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -1027,7 +1027,7 @@ export class Mat4 extends ValueType { * @param s Scaling vector * @returns The receiving matrix */ - public static fromSRT (out: Out, q: Quat, v: VecLike, s: VecLike) { + public static fromSRT (out: Out, q: Quat, v: VecLike, s: VecLike): Out { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -1075,7 +1075,7 @@ export class Mat4 extends ValueType { * @param o transformation Center * @deprecated Please use [[fromSRTOrigin]] instead. */ - public static fromRTSOrigin (out: Out, q: Quat, v: VecLike, s: VecLike, o: VecLike) { + public static fromRTSOrigin (out: Out, q: Quat, v: VecLike, s: VecLike, o: VecLike): Out { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -1129,7 +1129,7 @@ export class Mat4 extends ValueType { * @param o transformation Center * @returns The receiving matrix */ - public static fromSRTOrigin (out: Out, q: Quat, v: VecLike, s: VecLike, o: VecLike) { + public static fromSRTOrigin (out: Out, q: Quat, v: VecLike, s: VecLike, o: VecLike): Out { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -1177,7 +1177,7 @@ export class Mat4 extends ValueType { * @en Sets the out matrix with the given quaternion * @zh 根据指定的旋转信息计算矩阵 */ - public static fromQuat (out: Out, q: Quat) { + public static fromQuat (out: Out, q: Quat): Out { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -1229,7 +1229,7 @@ export class Mat4 extends ValueType { * * @return The receiving matrix. */ - public static frustum (out: Out, left: number, right: number, bottom: number, top: number, near: number, far: number) { + public static frustum (out: Out, left: number, right: number, bottom: number, top: number, near: number, far: number): Out { const rl = 1 / (right - left); const tb = 1 / (top - bottom); const nf = 1 / (near - far); @@ -1271,7 +1271,7 @@ export class Mat4 extends ValueType { public static perspective ( out: Out, fov: number, aspect: number, near: number, far: number, isFOVY = true, minClipZ = -1, projectionSignY = 1, orientation = 0, - ) { + ): Out { const f = 1.0 / Math.tan(fov / 2); const nf = 1 / (near - far); @@ -1317,7 +1317,7 @@ export class Mat4 extends ValueType { public static ortho ( out: Out, left: number, right: number, bottom: number, top: number, near: number, far: number, minClipZ = -1, projectionSignY = 1, orientation = 0, - ) { + ): Out { const lr = 1 / (left - right); const bt = 1 / (bottom - top) * projectionSignY; const nf = 1 / (near - far); @@ -1359,7 +1359,7 @@ export class Mat4 extends ValueType { * @param up The vector describing the up direction. * @return The receiving matrix. */ - public static lookAt (out: Out, eye: VecLike, center: VecLike, up: VecLike) { + public static lookAt (out: Out, eye: VecLike, center: VecLike, up: VecLike): Out { const eyex = eye.x; const eyey = eye.y; const eyez = eye.z; @@ -1417,7 +1417,7 @@ export class Mat4 extends ValueType { * * @deprecated This function is too complicated, and should be split into several functions. */ - public static inverseTranspose (out: Out, a: Out) { + public static inverseTranspose (out: Out, a: Out): Out | null { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; @@ -1472,7 +1472,7 @@ export class Mat4 extends ValueType { * @zh 矩阵转数组 * @param ofs Array Start Offset */ - public static toArray> (out: Out, m: IMat4Like, ofs = 0) { + public static toArray> (out: Out, m: IMat4Like, ofs = 0): Out { out[ofs + 0] = m.m00; out[ofs + 1] = m.m01; out[ofs + 2] = m.m02; @@ -1497,7 +1497,7 @@ export class Mat4 extends ValueType { * @zh 数组转矩阵 * @param ofs Array Start Offset */ - public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0) { + public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0): Out { out.m00 = arr[ofs + 0]; out.m01 = arr[ofs + 1]; out.m02 = arr[ofs + 2]; @@ -1521,7 +1521,7 @@ export class Mat4 extends ValueType { * @en Adds two matrices and save the results to out matrix * @zh 逐元素矩阵加法 */ - public static add (out: Out, a: Out, b: Out) { + public static add (out: Out, a: Out, b: Out): Out { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; @@ -1545,7 +1545,7 @@ export class Mat4 extends ValueType { * @en Subtracts matrix b from matrix a and save the results to out matrix * @zh 逐元素矩阵减法 */ - public static subtract (out: Out, a: Out, b: Out) { + public static subtract (out: Out, a: Out, b: Out): Out { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; @@ -1569,7 +1569,7 @@ export class Mat4 extends ValueType { * @en Multiply each element of a matrix by a scalar number and save the results to out matrix * @zh 矩阵标量乘法 */ - public static multiplyScalar (out: Out, a: Out, b: number) { + public static multiplyScalar (out: Out, a: Out, b: number): Out { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; @@ -1593,7 +1593,7 @@ export class Mat4 extends ValueType { * @en Adds two matrices after multiplying each element of the second operand by a scalar number. And save the results to out matrix. * @zh 逐元素矩阵标量乘加: A + B * scale */ - public static multiplyScalarAndAdd (out: Out, a: Out, b: Out, scale: number) { + public static multiplyScalarAndAdd (out: Out, a: Out, b: Out, scale: number): Out { out.m00 = a.m00 + (b.m00 * scale); out.m01 = a.m01 + (b.m01 * scale); out.m02 = a.m02 + (b.m02 * scale); @@ -1617,7 +1617,7 @@ export class Mat4 extends ValueType { * @en Returns whether the specified matrices are equal. * @zh 矩阵等价判断 */ - public static strictEquals (a: InType, b: InType) { + public static strictEquals (a: InType, b: InType): boolean { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 @@ -1633,7 +1633,7 @@ export class Mat4 extends ValueType { * @param epsilon The tolerance value. * @return */ - public static equals (a: InType, b: InType, epsilon = EPSILON) { + public static equals (a: InType, b: InType, epsilon = EPSILON): boolean { // TAOCP vol.2, 3rd ed., s.4.2.4, p.213-225 // defines a 'close enough' relationship between u and v that scales for magnitude return ( @@ -1792,7 +1792,7 @@ export class Mat4 extends ValueType { * @en Clone a new matrix from the current matrix. * @zh 克隆当前矩阵。 */ - public clone () { + public clone (): Mat4 { return new Mat4( this.m00, this.m01, this.m02, this.m03, this.m04, this.m05, this.m06, this.m07, @@ -1824,7 +1824,7 @@ export class Mat4 extends ValueType { public set (m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 0, m05 = 1, m06 = 0, m07 = 0, m08 = 0, m09 = 0, m10 = 1, m11 = 0, - m12 = 0, m13 = 0, m14 = 0, m15 = 1) { + m12 = 0, m13 = 0, m14 = 0, m15 = 1): Mat4 { if (typeof m00 === 'object') { this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; this.m04 = m00.m04; this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; @@ -1902,7 +1902,7 @@ export class Mat4 extends ValueType { * @zh 返回当前矩阵的字符串表示。 * @return 当前矩阵的字符串表示。 */ - public toString () { + public toString (): string { return `[\n${ this.m00}, ${this.m01}, ${this.m02}, ${this.m03},\n${ this.m04}, ${this.m05}, ${this.m06}, ${this.m07},\n${ @@ -1916,7 +1916,7 @@ export class Mat4 extends ValueType { * @zh 将当前矩阵设为单位矩阵。 * @return `this` */ - public identity () { + public identity (): Mat4 { this.m00 = 1; this.m01 = 0; this.m02 = 0; @@ -1941,7 +1941,7 @@ export class Mat4 extends ValueType { * @zh 将当前矩阵设为 0矩阵。 * @return `this` */ - public zero () { + public zero (): Mat4 { this.m00 = 0; this.m01 = 0; this.m02 = 0; @@ -1965,7 +1965,7 @@ export class Mat4 extends ValueType { * @en Transposes the current matrix. * @zh 计算当前矩阵的转置矩阵。 */ - public transpose () { + public transpose (): Mat4 { const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a12 = this.m06; const a13 = this.m07; const a23 = this.m11; this.m01 = this.m04; this.m02 = this.m08; @@ -1986,7 +1986,7 @@ export class Mat4 extends ValueType { * @en Inverts the current matrix. When matrix is not invertible the matrix will be set to zeros. * @zh 计算当前矩阵的逆矩阵。注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ - public invert () { + public invert (): Mat4 { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; @@ -2067,7 +2067,7 @@ export class Mat4 extends ValueType { * @zh 矩阵加法。将当前矩阵与指定矩阵的相加,结果返回给当前矩阵。 * @param mat the second operand */ - public add (mat: Mat4) { + public add (mat: Mat4): Mat4 { this.m00 += mat.m00; this.m01 += mat.m01; this.m02 += mat.m02; @@ -2092,7 +2092,7 @@ export class Mat4 extends ValueType { * @zh 计算矩阵减法。将当前矩阵减去指定矩阵的结果赋值给当前矩阵。 * @param mat the second operand */ - public subtract (mat: Mat4) { + public subtract (mat: Mat4): Mat4 { this.m00 -= mat.m00; this.m01 -= mat.m01; this.m02 -= mat.m02; @@ -2117,7 +2117,7 @@ export class Mat4 extends ValueType { * @zh 矩阵乘法。将当前矩阵左乘指定矩阵的结果赋值给当前矩阵。 * @param mat the second operand */ - public multiply (mat: Mat4) { + public multiply (mat: Mat4): Mat4 { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; @@ -2155,7 +2155,7 @@ export class Mat4 extends ValueType { * @zh 矩阵数乘。将当前矩阵与指定标量的数乘结果赋值给当前矩阵。 * @param scalar amount to scale the matrix's elements by */ - public multiplyScalar (scalar: number) { + public multiplyScalar (scalar: number): Mat4 { this.m00 *= scalar; this.m01 *= scalar; this.m02 *= scalar; @@ -2182,7 +2182,7 @@ export class Mat4 extends ValueType { * * @deprecated since v3.0, please use [[transform]] instead */ - public translate (vec: Vec3) { + public translate (vec: Vec3): Mat4 { this.m12 += vec.x; this.m13 += vec.y; this.m14 += vec.z; @@ -2194,7 +2194,7 @@ export class Mat4 extends ValueType { * @zh 将当前矩阵左乘位移矩阵的结果赋值给当前矩阵,位移矩阵由各个轴的位移给出。 * @param vec vector to translate by */ - public transform (vec: Vec3) { + public transform (vec: Vec3): Mat4 { const { x, y, z } = vec; const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; @@ -2213,7 +2213,7 @@ export class Mat4 extends ValueType { * @zh 将当前矩阵左乘缩放矩阵的结果赋值给当前矩阵,缩放矩阵由各个轴的缩放给出。 * @param vec vector to scale by */ - public scale (vec: Vec3) { + public scale (vec: Vec3): Mat4 { const x = vec.x; const y = vec.y; const z = vec.z; this.m00 *= x; this.m01 *= x; @@ -2236,7 +2236,7 @@ export class Mat4 extends ValueType { * @param rad Angle of rotation (in radians) * @param axis Axis of rotation */ - public rotate (rad: number, axis: Vec3) { + public rotate (rad: number, axis: Vec3): Mat4 | null { let x = axis.x; let y = axis.y; let z = axis.z; let len = Math.sqrt(x * x + y * y + z * z); @@ -2285,7 +2285,7 @@ export class Mat4 extends ValueType { * @zh 从当前矩阵中计算出位移变换的部分,并以各个轴上位移的形式赋值给输出向量。 * @param out Vector to receive translation component. */ - public getTranslation (out: Vec3) { + public getTranslation (out: Vec3): Vec3 { out.x = this.m12; out.y = this.m13; out.z = this.m14; @@ -2298,7 +2298,7 @@ export class Mat4 extends ValueType { * @zh 从当前矩阵中计算出缩放变换的部分,并以各个轴上缩放的形式赋值给输出向量。 * @param out Vector to receive scale component */ - public getScale (out: Vec3) { + public getScale (out: Vec3): Vec3 { const m00 = m3_1.m00 = this.m00; const m01 = m3_1.m01 = this.m01; const m02 = m3_1.m02 = this.m02; @@ -2321,7 +2321,7 @@ export class Mat4 extends ValueType { * @zh 从当前矩阵中计算出旋转变换的部分,并以四元数的形式赋值给输出四元数。 * @param out Vector to receive rotation component */ - public getRotation (out: Quat) { + public getRotation (out: Quat): Quat { // Extract rotation matrix first const sx = Vec3.set(v3_1, this.m00, this.m01, this.m02).length(); const sy = Vec3.set(v3_1, this.m04, this.m05, this.m06).length(); @@ -2355,7 +2355,7 @@ export class Mat4 extends ValueType { * * @deprecated Since 3.8.0, please use [[fromSRT]] instead */ - public fromRTS (q: Quat, v: Vec3, s: Vec3) { + public fromRTS (q: Quat, v: Vec3, s: Vec3): Mat4 { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -2402,7 +2402,7 @@ export class Mat4 extends ValueType { * @param s Scaling vector * @return `this` */ - public fromSRT (q: Quat, v: Vec3, s: Vec3) { + public fromSRT (q: Quat, v: Vec3, s: Vec3): Mat4 { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -2447,7 +2447,7 @@ export class Mat4 extends ValueType { * @param q Rotation quaternion * @return `this` */ - public fromQuat (q: Quat) { + public fromQuat (q: Quat): Mat4 { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; @@ -2522,7 +2522,7 @@ export function mat4 ( m10?, m11?, m12?, m13?, m20?, m21?, m22?, m23?, m30?, m31?, m32?, m33?, -) { +): Mat4 { return new Mat4(m00 as any, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); } diff --git a/cocos/core/math/math-base.ts b/cocos/core/math/math-base.ts index 5e9afc2eb7c..8c7da18a3be 100644 --- a/cocos/core/math/math-base.ts +++ b/cocos/core/math/math-base.ts @@ -29,7 +29,7 @@ import { FloatArray } from './type-define'; export const MATH_FLOAT_ARRAY = JSB ? Float32Array : Float64Array; export class MathBase extends ValueType { - public static createFloatArray (size: number) { + public static createFloatArray (size: number): Float64Array | Float32Array { return new MATH_FLOAT_ARRAY(size); } diff --git a/cocos/core/math/math-native-ext.ts b/cocos/core/math/math-native-ext.ts index 381ba9a0a59..3a8031479ab 100644 --- a/cocos/core/math/math-native-ext.ts +++ b/cocos/core/math/math-native-ext.ts @@ -29,15 +29,15 @@ import { Vec4 } from './vec4'; import { Quat } from './quat'; import { Color } from './color'; -const defineAttr = (proto, name, offset) => { +const defineAttr = (proto, name, offset): void => { Object.defineProperty(proto, name, { configurable: true, enumerable: true, - get () { + get (): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this._data()[offset]; }, - set (v: number) { + set (v: number): void { this._data()[offset] = v; }, }); @@ -55,8 +55,8 @@ export enum MathType { COLOR, } -function extendType (proto: any, parentProto: any, typ: MathType) { - proto._data = function () { +function extendType (proto: any, parentProto: any, typ: MathType): void { + proto._data = function (): Float32Array { if (!this.__data) { this.__data = new Float32Array(this.underlyingData()); } @@ -66,7 +66,7 @@ function extendType (proto: any, parentProto: any, typ: MathType) { Object.defineProperty(proto, 'type', { configurable: true, enumerable: true, writable: false, value: typ }); } -function inheritCCClass (ctor: Constructor, parentCtor: Constructor) { +function inheritCCClass (ctor: Constructor, parentCtor: Constructor): void { for (const attrName of ['__cid__', '__classname__']) { Object.defineProperty(ctor.prototype, attrName, { value: parentCtor.prototype[attrName], diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index f28cfc6e079..0cc92175ef1 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -41,7 +41,7 @@ export class Quat extends ValueType { * @en Obtain a copy of the given quaternion * @zh 获得指定四元数的拷贝 */ - public static clone (a: Out) { + public static clone (a: Out): Quat { return new Quat(a.x, a.y, a.z, a.w); } @@ -49,7 +49,7 @@ export class Quat extends ValueType { * @en Copy the given quaternion to the out quaternion * @zh 复制目标四元数 */ - public static copy (out: Out, a: QuatLike) { + public static copy (out: Out, a: QuatLike): Out { out.x = a.x; out.y = a.y; out.z = a.z; @@ -61,7 +61,7 @@ export class Quat extends ValueType { * @en Sets the out quaternion with values of each component * @zh 设置四元数值 */ - public static set (out: Out, x: number, y: number, z: number, w: number) { + public static set (out: Out, x: number, y: number, z: number, w: number): Out { out.x = x; out.y = y; out.z = z; @@ -73,7 +73,7 @@ export class Quat extends ValueType { * @en Sets the out quaternion to an identity quaternion * @zh 将目标赋值为单位四元数 */ - public static identity (out: Out) { + public static identity (out: Out): Out { out.x = 0; out.y = 0; out.z = 0; @@ -85,7 +85,7 @@ export class Quat extends ValueType { * @en Sets the out quaternion with the shortest path orientation between two vectors, considering both vectors normalized * @zh 设置四元数为两向量间的最短路径旋转,默认两向量都已归一化 */ - public static rotationTo (out: Out, a: VecLike, b: VecLike) { + public static rotationTo (out: Out, a: VecLike, b: VecLike): Out { const dot = Vec3.dot(a, b); if (dot < -0.999999) { Vec3.cross(v3_1, Vec3.UNIT_X, a); @@ -118,7 +118,7 @@ export class Quat extends ValueType { * @param q input quaternion * @return radian of rotation */ - public static getAxisAngle (outAxis: VecLike, q: Out) { + public static getAxisAngle (outAxis: VecLike, q: Out): number { const rad = Math.acos(q.w) * 2.0; const s = Math.sin(rad / 2.0); if (s !== 0.0) { @@ -138,7 +138,7 @@ export class Quat extends ValueType { * @en Quaternion multiplication and save the results to out quaternion, that is a * b. * @zh 四元数乘法,即a * b。 */ - public static multiply (out: Out, a: QuatLike_1, b: QuatLike_2) { + public static multiply (out: Out, a: QuatLike_1, b: QuatLike_2): Out { const x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y; const y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z; const z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x; @@ -154,7 +154,7 @@ export class Quat extends ValueType { * @en Quaternion scalar multiplication and save the results to out quaternion * @zh 四元数标量乘法 */ - public static multiplyScalar (out: Out, a: Out, b: number) { + public static multiplyScalar (out: Out, a: Out, b: number): Out { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; @@ -166,7 +166,7 @@ export class Quat extends ValueType { * @en Quaternion multiplication and addition: A + B * scale * @zh 四元数乘加:A + B * scale */ - public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number) { + public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number): Out { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale; @@ -179,7 +179,7 @@ export class Quat extends ValueType { * @zh 绕 X 轴旋转指定四元数 * @param rad radian of rotation */ - public static rotateX (out: Out, a: Out, rad: number) { + public static rotateX (out: Out, a: Out, rad: number): Out { rad *= 0.5; const bx = Math.sin(rad); @@ -198,7 +198,7 @@ export class Quat extends ValueType { * @zh 绕 Y 轴旋转指定四元数 * @param rad radian of rotation */ - public static rotateY (out: Out, a: Out, rad: number) { + public static rotateY (out: Out, a: Out, rad: number): Out { rad *= 0.5; const by = Math.sin(rad); @@ -217,7 +217,7 @@ export class Quat extends ValueType { * @zh 绕 Z 轴旋转指定四元数 * @param rad radian of rotation */ - public static rotateZ (out: Out, a: Out, rad: number) { + public static rotateZ (out: Out, a: Out, rad: number): Out { rad *= 0.5; const bz = Math.sin(rad); @@ -237,7 +237,7 @@ export class Quat extends ValueType { * @param axis axis of rotation, normalized by default * @param rad radian of rotation */ - public static rotateAround (out: Out, rot: Out, axis: VecLike, rad: number) { + public static rotateAround (out: Out, rot: Out, axis: VecLike, rad: number): Out { // get inv-axis (local to rot) Quat.invert(qt_1, rot); Vec3.transformQuat(v3_1, axis, qt_1); @@ -253,7 +253,7 @@ export class Quat extends ValueType { * @param axis axis of rotation * @param rad radian of rotation */ - public static rotateAroundLocal (out: Out, rot: Out, axis: VecLike, rad: number) { + public static rotateAroundLocal (out: Out, rot: Out, axis: VecLike, rad: number): Out { Quat.fromAxisAngle(qt_1, axis, rad); Quat.multiply(out, rot, qt_1); return out; @@ -263,7 +263,7 @@ export class Quat extends ValueType { * @en Calculates the w component with xyz components, considering the given quaternion normalized * @zh 根据 xyz 分量计算 w 分量,默认已归一化 */ - public static calculateW (out: Out, a: Out) { + public static calculateW (out: Out, a: Out): Out { out.x = a.x; out.y = a.y; out.z = a.z; @@ -275,7 +275,7 @@ export class Quat extends ValueType { * @en Quaternion dot product (scalar product) * @zh 四元数点积(数量积) */ - public static dot (a: Out, b: Out) { + public static dot (a: Out, b: Out): number { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } @@ -283,7 +283,7 @@ export class Quat extends ValueType { * @en Element by element linear interpolation: A + t * (B - A) * @zh 逐元素线性插值: A + t * (B - A) */ - public static lerp (out: Out, a: Out, b: Out, t: number) { + public static lerp (out: Out, a: Out, b: Out, t: number): Out { out.x = a.x + t * (b.x - a.x); out.y = a.y + t * (b.y - a.y); out.z = a.z + t * (b.z - a.z); @@ -296,7 +296,7 @@ export class Quat extends ValueType { * @zh 四元数球面插值 */ public static slerp - (out: Out, a: QuatLike_1, b: QuatLike_2, t: number) { + (out: Out, a: QuatLike_1, b: QuatLike_2, t: number): Out { // benchmarks: // http://jsperf.com/quaternion-slerp-implementations @@ -350,7 +350,7 @@ export class Quat extends ValueType { * @param t interpolation amount, in the range [0-1], between the two inputs * @returns out */ - public static sqlerp (out: Out, a: Out, b: Out, c: Out, d: Out, t: number) { + public static sqlerp (out: Out, a: Out, b: Out, c: Out, d: Out, t: number): Out { Quat.slerp(qt_1, a, d, t); Quat.slerp(qt_2, b, c, t); Quat.slerp(out, qt_1, qt_2, 2 * t * (1 - t)); @@ -361,7 +361,7 @@ export class Quat extends ValueType { * @en Sets the inverse of the given quaternion to out quaternion * @zh 四元数求逆 */ - public static invert (out: Out, a: QuatLike) { + public static invert (out: Out, a: QuatLike): Out { const dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; const invDot = dot ? 1.0 / dot : 0; @@ -378,7 +378,7 @@ export class Quat extends ValueType { * @en Conjugating a quaternion, it's equivalent to the inverse of the unit quaternion, but more efficient * @zh 求共轭四元数,对单位四元数与求逆等价,但更高效 */ - public static conjugate (out: Out, a: Out) { + public static conjugate (out: Out, a: Out): Out { out.x = -a.x; out.y = -a.y; out.z = -a.z; @@ -390,7 +390,7 @@ export class Quat extends ValueType { * @en Calculates the length of the quaternion * @zh 求四元数长度 */ - public static len (a: Out) { + public static len (a: Out): number { return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); } @@ -398,7 +398,7 @@ export class Quat extends ValueType { * @en Calculates the squared length of the quaternion * @zh 求四元数长度平方 */ - public static lengthSqr (a: Out) { + public static lengthSqr (a: Out): number { return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; } @@ -406,7 +406,7 @@ export class Quat extends ValueType { * @en Normalize the given quaternion, returns a zero quaternion if input is a zero quaternion. * @zh 归一化四元数,输入零四元数将会返回零四元数。 */ - public static normalize (out: Out, a: Out) { + public static normalize (out: Out, a: Out): Out { let len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; if (len > 0) { len = 1 / Math.sqrt(len); @@ -427,7 +427,7 @@ export class Quat extends ValueType { * @en Calculated the quaternion represents the given coordinates, considering all given vectors are normalized and mutually perpendicular * @zh 根据本地坐标轴朝向计算四元数,默认三向量都已归一化且相互垂直 */ - public static fromAxes (out: Out, xAxis: VecLike, yAxis: VecLike, zAxis: VecLike) { + public static fromAxes (out: Out, xAxis: VecLike, yAxis: VecLike, zAxis: VecLike): Out { Mat3.set(m3_1, xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, @@ -441,7 +441,7 @@ export class Quat extends ValueType { * @param view The view direction, it`s must be normalized. * @param up The view up direction, it`s must be normalized, default value is (0, 1, 0). */ - public static fromViewUp (out: Out, view: VecLike, up?: Vec3) { + public static fromViewUp (out: Out, view: VecLike, up?: Vec3): Out { Mat3.fromViewUp(m3_1, view, up); return Quat.normalize(out, Quat.fromMat3(out, m3_1)); } @@ -450,7 +450,7 @@ export class Quat extends ValueType { * @en Calculates the quaternion from a given rotary shaft and a radian rotation around it. * @zh 根据旋转轴和旋转弧度计算四元数 */ - public static fromAxisAngle (out: Out, axis: VecLike, rad: number) { + public static fromAxisAngle (out: Out, axis: VecLike, rad: number): Out { rad *= 0.5; const s = Math.sin(rad); out.x = s * axis.x; @@ -464,7 +464,7 @@ export class Quat extends ValueType { * @en Calculates the quaternion with the three-dimensional transform matrix, considering no scale included in the matrix * @zh 根据三维矩阵信息计算四元数,默认输入矩阵不含有缩放信息 */ - public static fromMat3 (out: Out, m: Mat3) { + public static fromMat3 (out: Out, m: Mat3): Out { const { m00, m03: m01, m06: m02, m01: m10, m04: m11, m07: m12, @@ -510,7 +510,7 @@ export class Quat extends ValueType { * @en Calculates the quaternion with Euler angles, the rotation order is YZX, first rotate around Y, then around Z, and finally around X. * @zh 根据欧拉角信息计算四元数,旋转顺序为 YZX,即先绕Y旋转,再绕Z,最后绕X旋转。 */ - public static fromEuler (out: Out, x: number, y: number, z: number) { + public static fromEuler (out: Out, x: number, y: number, z: number): Out { x *= halfToRad; y *= halfToRad; z *= halfToRad; @@ -537,7 +537,7 @@ export class Quat extends ValueType { * @param out Output quaternion * @param z Angle to rotate around Z axis in degrees. */ - public static fromAngleZ (out: Out, z: number) { + public static fromAngleZ (out: Out, z: number): Out { z *= halfToRad; out.x = out.y = 0; out.z = Math.sin(z); @@ -549,7 +549,7 @@ export class Quat extends ValueType { * @en This returns the X-axis vector of the quaternion * @zh 返回定义此四元数的坐标系 X 轴向量 */ - public static toAxisX (out: IVec3Like, q: IQuatLike) { + public static toAxisX (out: IVec3Like, q: IQuatLike): IVec3Like { const fy = 2.0 * q.y; const fz = 2.0 * q.z; out.x = 1.0 - fy * q.y - fz * q.z; @@ -563,7 +563,7 @@ export class Quat extends ValueType { * @en This returns the Y-axis vector of the quaternion * @zh 返回定义此四元数的坐标系 Y 轴向量 */ - public static toAxisY (out: IVec3Like, q: IQuatLike) { + public static toAxisY (out: IVec3Like, q: IQuatLike): IVec3Like { const fx = 2.0 * q.x; const fy = 2.0 * q.y; const fz = 2.0 * q.z; @@ -578,7 +578,7 @@ export class Quat extends ValueType { * @en This returns the Z-axis vector of the quaternion * @zh 返回定义此四元数的坐标系 Z 轴向量 */ - public static toAxisZ (out: IVec3Like, q: IQuatLike) { + public static toAxisZ (out: IVec3Like, q: IQuatLike): IVec3Like { const fx = 2.0 * q.x; const fy = 2.0 * q.y; const fz = 2.0 * q.z; @@ -595,7 +595,7 @@ export class Quat extends ValueType { * @zh 根据四元数计算欧拉角,返回角度 x, y 在 [-180, 180] 区间内, z 默认在 [-90, 90] 区间内,旋转顺序为 YZX,即先绕Y旋转,再绕Z,最后绕X旋转。 * @param outerZ change z value range to [-180, -90] U [90, 180] */ - public static toEuler (out: IVec3Like, q: IQuatLike, outerZ?: boolean) { + public static toEuler (out: IVec3Like, q: IQuatLike, outerZ?: boolean): IVec3Like { const { x, y, z, w } = q; let bank = 0; let heading = 0; @@ -631,7 +631,7 @@ export class Quat extends ValueType { * the rotation order is YXZ, first rotate around Y, then around X, and finally around Z. * @zh 根据四元数计算欧拉角,返回角度 yz 在 [-180, 180], x 在 [-90, 90],旋转顺序为 YXZ,即先绕Y旋转,再绕X,最后绕Z旋转。 */ - public static toEulerInYXZOrder (out: Vec3, q: IQuatLike) { + public static toEulerInYXZOrder (out: Vec3, q: IQuatLike): void { Mat3.fromQuat(m3_1, q); Mat3.toEuler(m3_1, out); out.x = toDegree(out.x); @@ -644,7 +644,7 @@ export class Quat extends ValueType { * @zh 四元数转数组 * @param ofs Array Start Offset */ - public static toArray> (out: Out, q: IQuatLike, ofs = 0) { + public static toArray> (out: Out, q: IQuatLike, ofs = 0): Out { out[ofs + 0] = q.x; out[ofs + 1] = q.y; out[ofs + 2] = q.z; @@ -657,7 +657,7 @@ export class Quat extends ValueType { * @zh 数组转四元数 * @param ofs Array Start Offset */ - public static fromArray (out: IQuatLike, arr: IWritableArrayLike, ofs = 0) { + public static fromArray (out: IQuatLike, arr: IWritableArrayLike, ofs = 0): IQuatLike { out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; out.z = arr[ofs + 2]; @@ -669,7 +669,7 @@ export class Quat extends ValueType { * @en Check whether two quaternions are equal * @zh 四元数等价判断 */ - public static strictEquals (a: IQuatLike, b: IQuatLike) { + public static strictEquals (a: IQuatLike, b: IQuatLike): boolean { return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; } @@ -677,7 +677,7 @@ export class Quat extends ValueType { * @en Check whether two quaternions are approximately equal * @zh 排除浮点数误差的四元数近似等价判断 */ - public static equals (a: IQuatLike, b: IQuatLike, epsilon = EPSILON) { + public static equals (a: IQuatLike, b: IQuatLike, epsilon = EPSILON): boolean { return (Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) @@ -691,7 +691,7 @@ export class Quat extends ValueType { * @param b The second unit quaternion * @returns Angle between the two quaternions in radians */ - public static angle (a: IQuatLike, b: IQuatLike) { + public static angle (a: IQuatLike, b: IQuatLike): number { const dot = Math.min(Math.abs(Quat.dot(a, b)), 1.0); return Math.acos(dot) * 2.0; } @@ -704,7 +704,7 @@ export class Quat extends ValueType { * @param maxStep The maximum angle of rotation in degrees * @returns new unit quaternion generated during rotation */ - public static rotateTowards (out: IQuatLike, from: IQuatLike, to: IQuatLike, maxStep: number) { + public static rotateTowards (out: IQuatLike, from: IQuatLike, to: IQuatLike, maxStep: number): IQuatLike { const angle = Quat.angle(from, to); if (angle === 0) { out.x = to.x; @@ -765,7 +765,7 @@ export class Quat extends ValueType { * @en clone the current Quat * @zh 克隆当前四元数。 */ - public clone () { + public clone (): Quat { return new Quat(this.x, this.y, this.z, this.w); } @@ -784,7 +784,7 @@ export class Quat extends ValueType { */ public set (x?: number, y?: number, z?: number, w?: number): Quat; - public set (x?: number | Quat, y?: number, z?: number, w?: number) { + public set (x?: number | Quat, y?: number, z?: number, w?: number): Quat { if (typeof x === 'object') { this.x = x.x; this.y = x.y; @@ -806,7 +806,7 @@ export class Quat extends ValueType { * @param epsilon The error allowed. It`s should be a non-negative number. * @returns Returns `true' when the components of the two quaternions are equal within the specified error range; otherwise, returns `false'. */ - public equals (other: Quat, epsilon = EPSILON) { + public equals (other: Quat, epsilon = EPSILON): boolean { return (Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) @@ -819,7 +819,7 @@ export class Quat extends ValueType { * @param other Comparative quaternion * @returns Returns `true' when the components of the two quaternions are equal within the specified error range; otherwise, returns `false'. */ - public strictEquals (other: Quat) { + public strictEquals (other: Quat): boolean { return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; } @@ -828,7 +828,7 @@ export class Quat extends ValueType { * @zh 将当前四元数转化为欧拉角(x-y-z)并赋值给输出向量。 * @param out the output vector */ - public getEulerAngles (out: Vec3) { + public getEulerAngles (out: Vec3): IVec3Like { return Quat.toEuler(out, this); } @@ -838,7 +838,7 @@ export class Quat extends ValueType { * @param to The target quaternion * @param ratio The interpolation coefficient. The range is [0,1]. */ - public lerp (to: Quat, ratio: number) { + public lerp (to: Quat, ratio: number): Quat { this.x += ratio * (to.x - this.x); this.y += ratio * (to.y - this.y); this.z += ratio * (to.z - this.z); @@ -852,7 +852,7 @@ export class Quat extends ValueType { * @param to The target quaternion * @param ratio The interpolation coefficient. The range is [0,1]. */ - public slerp (to: Quat, ratio: number) { + public slerp (to: Quat, ratio: number): Quat { return Quat.slerp(this, this, to, ratio); } @@ -860,7 +860,7 @@ export class Quat extends ValueType { * @en Calculates the length of the quaternion * @zh 求四元数长度 */ - public length () { + public length (): number { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); } @@ -868,7 +868,7 @@ export class Quat extends ValueType { * @en Calculates the squared length of the quaternion * @zh 求四元数长度平方 */ - public lengthSqr () { + public lengthSqr (): number { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; } } @@ -885,7 +885,7 @@ legacyCC.Quat = Quat; export function quat (other: Quat): Quat; export function quat (x?: number, y?: number, z?: number, w?: number): Quat; -export function quat (x: number | Quat = 0, y = 0, z = 0, w = 1) { +export function quat (x: number | Quat = 0, y = 0, z = 0, w = 1): Quat { return new Quat(x as any, y, z, w); } diff --git a/cocos/core/math/rect.ts b/cocos/core/math/rect.ts index e738b20ca07..03061e18a20 100644 --- a/cocos/core/math/rect.ts +++ b/cocos/core/math/rect.ts @@ -49,7 +49,7 @@ export class Rect extends ValueType { * @param v2 Specified point 2. * @returns Target rectangle. */ - public static fromMinMax (out: Out, v1: VecLike, v2: VecLike) { + public static fromMinMax (out: Out, v1: VecLike, v2: VecLike): Out { const minX = Math.min(v1.x, v2.x); const minY = Math.min(v1.y, v2.y); const maxX = Math.max(v1.x, v2.x); @@ -70,7 +70,7 @@ export class Rect extends ValueType { * @param to Target rect. * @param ratio The interpolation coefficient.The range is [0,1]. */ - public static lerp (out: Out, from: Out, to: Out, ratio: number) { + public static lerp (out: Out, from: Out, to: Out, ratio: number): Out { const x = from.x; const y = from.y; const w = from.width; @@ -90,7 +90,7 @@ export class Rect extends ValueType { * @param one One of the specify Rect. * @param other Another of the specify Rect. */ - public static intersection (out: Out, one: Out, other: Out) { + public static intersection (out: Out, one: Out, other: Out): Out { const axMin = one.x; const ayMin = one.y; const axMax = one.x + one.width; @@ -114,7 +114,7 @@ export class Rect extends ValueType { * @param one One of the specify Rect. * @param other Another of the specify Rect. */ - public static union (out: Out, one: Out, other: Out) { + public static union (out: Out, one: Out, other: Out): Out { const x = one.x; const y = one.y; const w = one.width; @@ -138,7 +138,7 @@ export class Rect extends ValueType { * @param b The second rect to be compared. * @returns Returns `true' when the minimum and maximum values of both rectangles are equal, respectively; otherwise, returns `false'. */ - public static equals (a: InType, b: InType) { + public static equals (a: InType, b: InType): boolean { return a.x === b.x && a.y === b.y && a.width === b.width @@ -149,7 +149,7 @@ export class Rect extends ValueType { * @en The minimum x value. * @zh 获取或设置矩形在 x 轴上的最小值。 */ - get xMin () { + get xMin (): number { return this.x; } @@ -162,7 +162,7 @@ export class Rect extends ValueType { * @en The minimum y value. * @zh 获取或设置矩形在 y 轴上的最小值。 */ - get yMin () { + get yMin (): number { return this.y; } @@ -175,7 +175,7 @@ export class Rect extends ValueType { * @en The maximum x value. * @zh 获取或设置矩形在 x 轴上的最大值。 */ - get xMax () { + get xMax (): number { return this.x + this.width; } @@ -187,7 +187,7 @@ export class Rect extends ValueType { * @en The maximum y value. * @zh 获取或设置矩形在 y 轴上的最大值。 */ - get yMax () { + get yMax (): number { return this.y + this.height; } @@ -199,7 +199,7 @@ export class Rect extends ValueType { * @en The position of the center of the rectangle. * @zh 获取或设置矩形中心点的坐标。 */ - get center () { + get center (): Vec2 { return new Vec2(this.x + this.width * 0.5, this.y + this.height * 0.5); } @@ -213,7 +213,7 @@ export class Rect extends ValueType { * @en Returns a new [[Vec2]] object representing the position of the rectangle * @zh 获取或设置矩形的 x 和 y 坐标。 */ - get origin () { + get origin (): Vec2 { return new Vec2(this.x, this.y); } @@ -226,7 +226,7 @@ export class Rect extends ValueType { * @en Returns a new [[Size]] object represents the width and height of the rectangle * @zh 获取或设置矩形的尺寸。 */ - get size () { + get size (): Size { return new Size(this.width, this.height); } @@ -237,9 +237,9 @@ export class Rect extends ValueType { // compatibility with vector interfaces set z (val) { this.width = val; } - get z () { return this.width; } + get z (): number { return this.width; } set w (val) { this.height = val; } - get w () { return this.height; } + get w (): number { return this.height; } /** * @en The minimum x value. @@ -301,7 +301,7 @@ export class Rect extends ValueType { * @en clone the current Rect. * @zh 克隆当前矩形。 */ - public clone () { + public clone (): Rect { return new Rect(this.x, this.y, this.width, this.height); } @@ -311,7 +311,7 @@ export class Rect extends ValueType { * @param other Specified Rect. * @returns `this` */ - public set (other: Rect); + public set (other: Rect): any; /** * @en Set the value of each component of the current Rect. @@ -322,9 +322,9 @@ export class Rect extends ValueType { * @param height The height parameter of the specified rectangle * @returns `this` */ - public set (x?: number, y?: number, width?: number, height?: number); + public set (x?: number, y?: number, width?: number, height?: number): any; - public set (x?: Rect | number, y?: number, width?: number, height?: number) { + public set (x?: Rect | number, y?: number, width?: number, height?: number): any { if (typeof x === 'object') { this.x = x.x; this.y = x.y; @@ -345,7 +345,7 @@ export class Rect extends ValueType { * @param other Specified rectangles. * @returns Returns `true' when the minimum and maximum values of both rectangles are equal, respectively; otherwise, returns `false'. */ - public equals (other: Rect) { + public equals (other: Rect): boolean { return this.x === other.x && this.y === other.y && this.width === other.width @@ -358,7 +358,7 @@ export class Rect extends ValueType { * @param to Target Rect. * @param ratio The interpolation coefficient.The range is [0,1]. */ - public lerp (to: Rect, ratio: number) { + public lerp (to: Rect, ratio: number): Rect { const x = this.x; const y = this.y; const w = this.width; @@ -376,7 +376,7 @@ export class Rect extends ValueType { * @zh 返回当前矩形的字符串表示。 * @returns The information of the current rect in string */ - public toString () { + public toString (): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.width.toFixed(2)}, ${this.height.toFixed(2)})`; } @@ -386,7 +386,7 @@ export class Rect extends ValueType { * @param other Specified rectangles. * @returns If intersected, return `true', otherwise return `false'. */ - public intersects (other: Rect) { + public intersects (other: Rect): boolean { const maxax = this.x + this.width; const maxay = this.y + this.height; const maxbx = other.x + other.width; @@ -400,7 +400,7 @@ export class Rect extends ValueType { * @param point Specified point. * @returns The specified point is included in the rectangle and returns `true', otherwise it returns `false'. */ - public contains (point: Vec2) { + public contains (point: Vec2): boolean { return (this.x <= point.x && this.x + this.width >= point.x && this.y <= point.y @@ -413,7 +413,7 @@ export class Rect extends ValueType { * @param other Specified rectangles. * @returns Returns `true' if all the points of the specified rectangle are included in the current rectangle, `false' otherwise. */ - public containsRect (other: Rect) { + public containsRect (other: Rect): boolean { return (this.x <= other.x && this.x + this.width >= other.x + other.width && this.y <= other.y @@ -429,7 +429,7 @@ export class Rect extends ValueType { * 并将如此构成的新矩形。 * @param matrix The matrix4 */ - public transformMat4 (mat: Mat4) { + public transformMat4 (mat: Mat4): Rect { const ol = this.x; const ob = this.y; const or = ol + this.width; @@ -468,7 +468,7 @@ export class Rect extends ValueType { * @param out_rb The right bottom point * @param out_rt The right top point */ - public transformMat4ToPoints (mat: Mat4, out_lb: Vec2, out_lt: Vec2, out_rt: Vec2, out_rb: Vec2) { + public transformMat4ToPoints (mat: Mat4, out_lb: Vec2, out_lt: Vec2, out_rt: Vec2, out_rb: Vec2): void { const ol = this.x; const ob = this.y; const or = ol + this.width; diff --git a/cocos/core/math/size.ts b/cocos/core/math/size.ts index b427a9ba5ee..07332665816 100644 --- a/cocos/core/math/size.ts +++ b/cocos/core/math/size.ts @@ -45,7 +45,7 @@ export class Size extends ValueType { * @param ratio The interpolation coefficient.The range is [0,1]. * @returns A vector consisting of linear interpolation of the width and height of the current size to the width and height of the target size at a specified interpolation ratio, respectively. */ - public static lerp (out: Out, from: Out, to: Out, ratio: number) { + public static lerp (out: Out, from: Out, to: Out, ratio: number): Out { out.width = from.width + (to.width - from.width) * ratio; out.height = from.height + (to.height - from.height) * ratio; return out; @@ -58,16 +58,16 @@ export class Size extends ValueType { * @param b Size b. * @returns Returns `true' when both dimensions are equal in width and height; otherwise returns `false'. */ - public static equals (a: InType, b: InType) { + public static equals (a: InType, b: InType): boolean { return a.width === b.width && a.height === b.height; } // compatibility with vector interfaces set x (val) { this.width = val; } - get x () { return this.width; } + get x (): number { return this.width; } set y (val) { this.height = val; } - get y () { return this.height; } + get y (): number { return this.height; } public declare width: number; @@ -103,7 +103,7 @@ export class Size extends ValueType { * @en clone the current `Size`. * @zh 克隆当前尺寸。 */ - public clone () { + public clone (): Size { return new Size(this.width, this.height); } @@ -113,7 +113,7 @@ export class Size extends ValueType { * @param other Specified Size. * @returns `this` */ - public set (other: Size); + public set (other: Size): any; /** * @en Set the value of each component of the current `Size`. @@ -122,9 +122,9 @@ export class Size extends ValueType { * @param height Specified height * @returns `this` */ - public set (width?: number, height?: number); + public set (width?: number, height?: number): any; - public set (width?: Size | number, height?: number) { + public set (width?: Size | number, height?: number): any { if (typeof width === 'object') { this.height = width.height; this.width = width.width; @@ -141,7 +141,7 @@ export class Size extends ValueType { * @param other Specified Size * @returns Returns `true' when both dimensions are equal in width and height; otherwise returns `false'. */ - public equals (other: Size) { + public equals (other: Size): boolean { return this.width === other.width && this.height === other.height; } @@ -152,7 +152,7 @@ export class Size extends ValueType { * @param to Target Size. * @param ratio The interpolation coefficient.The range is [0,1]. */ - public lerp (to: Size, ratio: number) { + public lerp (to: Size, ratio: number): Size { this.width += (to.width - this.width) * ratio; this.height += (to.height - this.height) * ratio; return this; @@ -163,7 +163,7 @@ export class Size extends ValueType { * @zh 返回当前尺寸的字符串表示。 * @returns The information of the current size in string */ - public toString () { + public toString (): string { return `(${this.width.toFixed(2)}, ${this.height.toFixed(2)})`; } } @@ -187,7 +187,7 @@ export function size (other: Size): Size; */ export function size (width?: number, height?: number): Size; -export function size (width: Size | number = 0, height = 0) { +export function size (width: Size | number = 0, height = 0): Size { return new Size(width as any, height); } diff --git a/cocos/core/math/utils.ts b/cocos/core/math/utils.ts index 0b9c06cf006..0af2c7d624a 100644 --- a/cocos/core/math/utils.ts +++ b/cocos/core/math/utils.ts @@ -46,7 +46,7 @@ export const EPSILON = 0.000001; * @param b The second number to test. * @return True if the numbers are approximately equal, false otherwise. */ -export function equals (a: number, b: number) { +export function equals (a: number, b: number): boolean { return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); } @@ -58,7 +58,7 @@ export function equals (a: number, b: number) { * @param maxDiff Maximum difference. * @return True if the numbers are approximately equal, false otherwise. */ -export function approx (a: number, b: number, maxDiff?: number) { +export function approx (a: number, b: number, maxDiff?: number): boolean { maxDiff = maxDiff || EPSILON; return Math.abs(a - b) <= maxDiff; } @@ -70,7 +70,7 @@ export function approx (a: number, b: number, maxDiff?: number) { * @param min * @param max */ -export function clamp (val: number, min: number, max: number) { +export function clamp (val: number, min: number, max: number): number { if (min > max) { const temp = min; min = max; @@ -85,7 +85,7 @@ export function clamp (val: number, min: number, max: number) { * @zh 将值限制在0和1之间。 * @param val */ -export function clamp01 (val: number) { +export function clamp01 (val: number): number { return val < 0 ? 0 : val > 1 ? 1 : val; } @@ -96,7 +96,7 @@ export function clamp01 (val: number) { * @param to - The ending number. * @param ratio - The interpolation coefficient, t should be in the range [0, 1]. */ -export function lerp (from: number, to: number, ratio: number) { +export function lerp (from: number, to: number, ratio: number): number { return from + (to - from) * ratio; } @@ -105,7 +105,7 @@ export function lerp (from: number, to: number, ratio: number) { * @zh 把角度换算成弧度。 * @param {Number} a Angle in Degrees */ -export function toRadian (a: number) { +export function toRadian (a: number): number { return a * _d2r; } @@ -114,7 +114,7 @@ export function toRadian (a: number) { * @zh 把弧度换算成角度。 * @param {Number} a Angle in Radian */ -export function toDegree (a: number) { +export function toDegree (a: number): number { return a * _r2d; } @@ -131,7 +131,7 @@ export const random = Math.random; * @param max * @return The random number. */ -export function randomRange (min: number, max: number) { +export function randomRange (min: number, max: number): number { return Math.random() * (max - min) + min; } @@ -142,7 +142,7 @@ export function randomRange (min: number, max: number) { * @param max * @return The random integer. */ -export function randomRangeInt (min: number, max: number) { +export function randomRangeInt (min: number, max: number): number { return Math.floor(randomRange(min, max)); } @@ -155,7 +155,7 @@ export function randomRangeInt (min: number, max: number) { * @param seed The random seed. * @return The pseudo random. */ -export function pseudoRandom (seed: number) { +export function pseudoRandom (seed: number): number { seed = (seed * 9301 + 49297) % 233280; return seed / 233280.0; } @@ -171,7 +171,7 @@ export function pseudoRandom (seed: number) { * @param max * @return The random number. */ -export function pseudoRandomRange (seed: number, min: number, max: number) { +export function pseudoRandomRange (seed: number, min: number, max: number): number { return pseudoRandom(seed) * (max - min) + min; } @@ -183,7 +183,7 @@ export function pseudoRandomRange (seed: number, min: number, max: number) { * @param max * @return The random integer. */ -export function pseudoRandomRangeInt (seed: number, min: number, max: number) { +export function pseudoRandomRangeInt (seed: number, min: number, max: number): number { return Math.floor(pseudoRandomRange(seed, min, max)); } @@ -196,7 +196,7 @@ export function pseudoRandomRangeInt (seed: number, min: number, max: number) { * @param val * @return The the next power of two. */ -export function nextPow2 (val: number) { +export function nextPow2 (val: number): number { return bits.nextPow2(val); } @@ -207,7 +207,7 @@ export function nextPow2 (val: number) { * @param length Time of one cycle. * @return The Time wrapped in the first cycle. */ -export function repeat (t: number, length: number) { +export function repeat (t: number, length: number): number { return t - Math.floor(t / length) * length; } @@ -221,7 +221,7 @@ export function repeat (t: number, length: number) { * @param length Time of one cycle. * @return The time wrapped in the first cycle. */ -export function pingPong (t: number, length: number) { +export function pingPong (t: number, length: number): number { t = repeat(t, length * 2); t = length - Math.abs(t - length); return t; @@ -235,7 +235,7 @@ export function pingPong (t: number, length: number) { * @param value Given value. * @return The ratio between [from, to]. */ -export function inverseLerp (from: number, to: number, value: number) { +export function inverseLerp (from: number, to: number, value: number): number { return (value - from) / (to - from); } @@ -245,7 +245,7 @@ export function inverseLerp (from: number, to: number, value: number) { * @param v vec3 like value * @returns max absolute component */ -export function absMaxComponent (v: IVec3Like) { +export function absMaxComponent (v: IVec3Like): number { if (Math.abs(v.x) > Math.abs(v.y)) { if (Math.abs(v.x) > Math.abs(v.z)) { return v.x; @@ -265,7 +265,7 @@ export function absMaxComponent (v: IVec3Like) { * @param a number * @param b number */ -export function absMax (a: number, b: number) { +export function absMax (a: number, b: number): number { if (Math.abs(a) > Math.abs(b)) { return a; } else { @@ -281,8 +281,8 @@ export function absMax (a: number, b: number) { * @param prototype Inherit the prototype chain of the ValueType class * @param attrs List of attributes that need to be enumerated */ -export function enumerableProps (prototype: ValueType, attrs: string[]) { - attrs.forEach((key) => { +export function enumerableProps (prototype: ValueType, attrs: string[]): void { + attrs.forEach((key): void => { Object.defineProperty(prototype, key, { enumerable: true }); }); } diff --git a/cocos/core/math/vec2.ts b/cocos/core/math/vec2.ts index 9acd0c13903..b3d9aa33150 100644 --- a/cocos/core/math/vec2.ts +++ b/cocos/core/math/vec2.ts @@ -47,7 +47,7 @@ export class Vec2 extends ValueType { * @en Obtains a clone of the given vector object * @zh 获得指定向量的拷贝 */ - public static clone (a: Out) { + public static clone (a: Out): Vec2 { return new Vec2(a.x, a.y); } @@ -55,7 +55,7 @@ export class Vec2 extends ValueType { * @en Copy the target vector and save the results to out vector object * @zh 复制目标向量 */ - public static copy (out: Out, a: Out) { + public static copy (out: Out, a: Out): Out { out.x = a.x; out.y = a.y; return out; @@ -65,7 +65,7 @@ export class Vec2 extends ValueType { * @en Sets the out vector with the given x and y values * @zh 设置向量值 */ - public static set (out: Out, x: number, y: number) { + public static set (out: Out, x: number, y: number): Out { out.x = x; out.y = y; return out; @@ -75,7 +75,7 @@ export class Vec2 extends ValueType { * @en Element-wise vector addition and save the results to out vector object * @zh 逐元素向量加法 */ - public static add (out: Out, a: Out, b: Out) { + public static add (out: Out, a: Out, b: Out): Out { out.x = a.x + b.x; out.y = a.y + b.y; return out; @@ -85,7 +85,7 @@ export class Vec2 extends ValueType { * @en Element-wise vector subtraction and save the results to out vector object * @zh 逐元素向量减法 */ - public static subtract (out: Out, a: Out, b: Out) { + public static subtract (out: Out, a: Out, b: Out): Out { out.x = a.x - b.x; out.y = a.y - b.y; return out; @@ -95,7 +95,7 @@ export class Vec2 extends ValueType { * @en Element-wise vector multiplication and save the results to out vector object * @zh 逐元素向量乘法 */ - public static multiply (out: Out, a: Out, b: Out) { + public static multiply (out: Out, a: Out, b: Out): Out { out.x = a.x * b.x; out.y = a.y * b.y; return out; @@ -105,7 +105,7 @@ export class Vec2 extends ValueType { * @en Element-wise vector division and save the results to out vector object * @zh 逐元素向量除法 */ - public static divide (out: Out, a: Out, b: Out) { + public static divide (out: Out, a: Out, b: Out): Out { out.x = a.x / b.x; out.y = a.y / b.y; return out; @@ -115,7 +115,7 @@ export class Vec2 extends ValueType { * @en Rounds up by elements of the vector and save the results to out vector object * @zh 逐元素向量向上取整 */ - public static ceil (out: Out, a: Out) { + public static ceil (out: Out, a: Out): Out { out.x = Math.ceil(a.x); out.y = Math.ceil(a.y); return out; @@ -125,7 +125,7 @@ export class Vec2 extends ValueType { * @en Element-wise rounds down of the current vector and save the results to the out vector * @zh 逐元素向量向下取整 */ - public static floor (out: Out, a: Out) { + public static floor (out: Out, a: Out): Out { out.x = Math.floor(a.x); out.y = Math.floor(a.y); return out; @@ -135,7 +135,7 @@ export class Vec2 extends ValueType { * @en Calculates element-wise minimum values and save to the out vector * @zh 逐元素向量最小值 */ - public static min (out: Out, a: Out, b: Out) { + public static min (out: Out, a: Out, b: Out): Out { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); return out; @@ -145,7 +145,7 @@ export class Vec2 extends ValueType { * @en Calculates element-wise maximum values and save to the out vector * @zh 逐元素向量最大值 */ - public static max (out: Out, a: Out, b: Out) { + public static max (out: Out, a: Out, b: Out): Out { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); return out; @@ -155,7 +155,7 @@ export class Vec2 extends ValueType { * @en Calculates element-wise round results and save to the out vector * @zh 逐元素向量四舍五入取整 */ - public static round (out: Out, a: Out) { + public static round (out: Out, a: Out): Out { out.x = Math.round(a.x); out.y = Math.round(a.y); return out; @@ -165,7 +165,7 @@ export class Vec2 extends ValueType { * @en Vector scalar multiplication and save the results to out vector object * @zh 向量标量乘法 */ - public static multiplyScalar (out: Out, a: Out, b: number) { + public static multiplyScalar (out: Out, a: Out, b: number): Out { out.x = a.x * b; out.y = a.y * b; return out; @@ -175,7 +175,7 @@ export class Vec2 extends ValueType { * @en Element-wise multiplication and addition with the equation: a + b * scale * @zh 逐元素向量乘加: A + B * scale */ - public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number) { + public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number): Out { out.x = a.x + (b.x * scale); out.y = a.y + (b.y * scale); return out; @@ -185,7 +185,7 @@ export class Vec2 extends ValueType { * @en Calculates the euclidean distance of two vectors * @zh 求两向量的欧氏距离 */ - public static distance (a: Out, b: Out) { + public static distance (a: Out, b: Out): number { const x = b.x - a.x; const y = b.y - a.y; return Math.sqrt(x * x + y * y); @@ -195,7 +195,7 @@ export class Vec2 extends ValueType { * @en Calculates the squared euclidean distance of two vectors * @zh 求两向量的欧氏距离平方 */ - public static squaredDistance (a: Out, b: Out) { + public static squaredDistance (a: Out, b: Out): number { const x = b.x - a.x; const y = b.y - a.y; return x * x + y * y; @@ -205,7 +205,7 @@ export class Vec2 extends ValueType { * @en Calculates the length of the vector * @zh 求向量长度 */ - public static len (a: Out) { + public static len (a: Out): number { const x = a.x; const y = a.y; return Math.sqrt(x * x + y * y); @@ -215,7 +215,7 @@ export class Vec2 extends ValueType { * @en Calculates the squared length of the vector * @zh 求向量长度平方 */ - public static lengthSqr (a: Out) { + public static lengthSqr (a: Out): number { const x = a.x; const y = a.y; return x * x + y * y; @@ -225,7 +225,7 @@ export class Vec2 extends ValueType { * @en Sets each element to its negative value * @zh 逐元素向量取负 */ - public static negate (out: Out, a: Out) { + public static negate (out: Out, a: Out): Out { out.x = -a.x; out.y = -a.y; return out; @@ -235,7 +235,7 @@ export class Vec2 extends ValueType { * @en Sets each element to its inverse value, zero value will become Infinity * @zh 逐元素向量取倒数,接近 0 时返回 Infinity */ - public static inverse (out: Out, a: Out) { + public static inverse (out: Out, a: Out): Out { out.x = 1.0 / a.x; out.y = 1.0 / a.y; return out; @@ -245,7 +245,7 @@ export class Vec2 extends ValueType { * @en Sets each element to its inverse value, zero value will remain zero * @zh 逐元素向量取倒数,接近 0 时返回 0 */ - public static inverseSafe (out: Out, a: Out) { + public static inverseSafe (out: Out, a: Out): Out { const x = a.x; const y = a.y; @@ -268,7 +268,7 @@ export class Vec2 extends ValueType { * @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector. * @zh 归一化向量,输入零向量将会返回零向量。 */ - public static normalize (out: Out, a: Vec2Like) { + public static normalize (out: Out, a: Vec2Like): Out { const x = a.x; const y = a.y; let len = x * x + y * y; @@ -287,7 +287,7 @@ export class Vec2 extends ValueType { * @en Calculates the dot product of the vector * @zh 向量点积(数量积) */ - public static dot (a: Out, b: Out) { + public static dot (a: Out, b: Out): number { return a.x * b.x + a.y * b.y; } @@ -321,7 +321,7 @@ export class Vec2 extends ValueType { * @en Calculates the linear interpolation between two vectors with a given ratio: A + t * (B - A) * @zh 逐元素向量线性插值: A + t * (B - A) */ - public static lerp (out: Out, a: Out, b: Out, t: number) { + public static lerp (out: Out, a: Out, b: Out, t: number): Out { const x = a.x; const y = a.y; out.x = x + t * (b.x - x); @@ -334,7 +334,7 @@ export class Vec2 extends ValueType { * @zh 生成一个在单位圆上均匀分布的随机向量 * @param scale vector length */ - public static random (out: Out, scale?: number) { + public static random (out: Out, scale?: number): Out { scale = scale || 1.0; const r = random() * 2.0 * Math.PI; out.x = Math.cos(r) * scale; @@ -346,7 +346,7 @@ export class Vec2 extends ValueType { * @en Vector and third order matrix multiplication, will complete the vector with a third value as one * @zh 向量与三维矩阵乘法,默认向量第三位为 1。 */ - public static transformMat3 (out: Out, a: Out, m: IMat3Like) { + public static transformMat3 (out: Out, a: Out, m: IMat3Like): Out { const x = a.x; const y = a.y; out.x = m.m00 * x + m.m03 * y + m.m06; @@ -358,7 +358,7 @@ export class Vec2 extends ValueType { * @en Vector and third order matrix multiplication, will complete the vector with a third and a fourth element as one * @zh 向量与四维矩阵乘法,默认向量第三位为 0,第四位为 1。 */ - public static transformMat4 (out: Out, a: Out, m: IMat4Like) { + public static transformMat4 (out: Out, a: Out, m: IMat4Like): Out { const x = a.x; const y = a.y; out.x = m.m00 * x + m.m04 * y + m.m12; @@ -370,7 +370,7 @@ export class Vec2 extends ValueType { * @en Gets the string representation of the given vector * @zh 返回向量的字符串表示 */ - public static str (a: Out) { + public static str (a: Out): string { return `Vec2(${a.x}, ${a.y})`; } @@ -379,7 +379,7 @@ export class Vec2 extends ValueType { * @zh 向量转数组 * @param ofs Array Start Offset */ - public static toArray > (out: Out, v: IVec2Like, ofs = 0) { + public static toArray > (out: Out, v: IVec2Like, ofs = 0): Out { out[ofs + 0] = v.x; out[ofs + 1] = v.y; return out; @@ -390,7 +390,7 @@ export class Vec2 extends ValueType { * @zh 数组转向量 * @param ofs Array Start Offset */ - public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0) { + public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0): Out { out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; return out; @@ -400,7 +400,7 @@ export class Vec2 extends ValueType { * @en Check the equality of the two given vectors * @zh 向量等价判断 */ - public static strictEquals (a: Out, b: Out) { + public static strictEquals (a: Out, b: Out): boolean { return a.x === b.x && a.y === b.y; } @@ -408,7 +408,7 @@ export class Vec2 extends ValueType { * @en Check whether the two given vectors are approximately equivalent * @zh 排除浮点数误差的向量近似等价判断 */ - public static equals (a: Out, b: Out, epsilon = EPSILON) { + public static equals (a: Out, b: Out, epsilon = EPSILON): boolean { return ( Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) @@ -421,7 +421,7 @@ export class Vec2 extends ValueType { * @en Calculates the radian angle between two vectors, returns zero if either vector is a zero vector. * @zh 求两向量夹角弧度,任意一个向量是零向量则返回零。 */ - public static angle (a: Out, b: Out) { + public static angle (a: Out, b: Out): number { const magSqr1 = a.x * a.x + a.y * a.y; const magSqr2 = b.x * b.x + b.y * b.y; @@ -466,7 +466,7 @@ export class Vec2 extends ValueType { * @en clone a Vec2 value * @zh 克隆当前向量。 */ - public clone () { + public clone (): Vec2 { return new Vec2(this.x, this.y); } @@ -487,7 +487,7 @@ export class Vec2 extends ValueType { */ public set (x?: number, y?: number): Vec2; - public set (x?: number | Vec2, y?: number) { + public set (x?: number | Vec2, y?: number): Vec2 { if (typeof x === 'object') { this.x = x.x; this.y = x.y; @@ -505,7 +505,7 @@ export class Vec2 extends ValueType { * @param epsilon The error allowed. It`s should be a non-negative number. * @return Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public equals (other: Vec2, epsilon = EPSILON) { + public equals (other: Vec2, epsilon = EPSILON): boolean { return ( Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) @@ -522,7 +522,7 @@ export class Vec2 extends ValueType { * @param epsilon The error allowed. It`s should be a non-negative number. * @return Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public equals2f (x: number, y: number, epsilon = EPSILON) { + public equals2f (x: number, y: number, epsilon = EPSILON): boolean { return ( Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) @@ -537,7 +537,7 @@ export class Vec2 extends ValueType { * @param other specified vector * @return Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public strictEquals (other: Vec2) { + public strictEquals (other: Vec2): boolean { return other && this.x === other.x && this.y === other.y; } @@ -548,7 +548,7 @@ export class Vec2 extends ValueType { * @param y The y value of specified vector * @return Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public strictEquals2f (x: number, y: number) { + public strictEquals2f (x: number, y: number): boolean { return this.x === x && this.y === y; } @@ -557,7 +557,7 @@ export class Vec2 extends ValueType { * @zh 返回当前向量的字符串表示。 * @returns The string with vector information */ - public toString () { + public toString (): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)})`; } @@ -567,7 +567,7 @@ export class Vec2 extends ValueType { * @param to Target vector * @param ratio The interpolation coefficient.The range is [0,1]. */ - public lerp (to: Vec2, ratio: number) { + public lerp (to: Vec2, ratio: number): Vec2 { const x = this.x; const y = this.y; this.x = x + ratio * (to.x - x); @@ -582,7 +582,7 @@ export class Vec2 extends ValueType { * @param maxInclusive Maximum value allowed * @return `this` */ - public clampf (minInclusive: Vec2, maxInclusive: Vec2) { + public clampf (minInclusive: Vec2, maxInclusive: Vec2): Vec2 { this.x = clamp(this.x, minInclusive.x, maxInclusive.x); this.y = clamp(this.y, minInclusive.y, maxInclusive.y); return this; @@ -593,7 +593,7 @@ export class Vec2 extends ValueType { * @zh 向量加法。将当前向量与指定向量的相加 * @param other specified vector */ - public add (other: Vec2) { + public add (other: Vec2): Vec2 { this.x += other.x; this.y += other.y; return this; @@ -605,7 +605,7 @@ export class Vec2 extends ValueType { * @param x The x value of specified vector * @param y The y value of specified vector */ - public add2f (x: number, y: number) { + public add2f (x: number, y: number): Vec2 { this.x += x; this.y += y; return this; @@ -616,7 +616,7 @@ export class Vec2 extends ValueType { * @zh 向量减法。将当前向量减去指定向量 * @param other specified vector */ - public subtract (other: Vec2) { + public subtract (other: Vec2): Vec2 { this.x -= other.x; this.y -= other.y; return this; @@ -628,7 +628,7 @@ export class Vec2 extends ValueType { * @param x The x value of specified vector * @param y The y value of specified vector */ - public subtract2f (x: number, y: number) { + public subtract2f (x: number, y: number): Vec2 { this.x -= x; this.y -= y; return this; @@ -639,7 +639,7 @@ export class Vec2 extends ValueType { * @zh 向量数乘。将当前向量数乘指定标量 * @param scalar scalar number */ - public multiplyScalar (scalar: number) { + public multiplyScalar (scalar: number): Vec2 { if (typeof scalar === 'object') { console.warn('should use Vec2.multiply for vector * vector operation'); } this.x *= scalar; this.y *= scalar; @@ -651,7 +651,7 @@ export class Vec2 extends ValueType { * @zh 向量乘法。将当前向量乘以与指定向量的结果赋值给当前向量。 * @param other specified vector */ - public multiply (other: Vec2) { + public multiply (other: Vec2): Vec2 { if (typeof other !== 'object') { console.warn('should use Vec2.scale for vector * scalar operation'); } this.x *= other.x; this.y *= other.y; @@ -664,7 +664,7 @@ export class Vec2 extends ValueType { * @param x The x value of specified vector * @param y The y value of specified vector */ - public multiply2f (x: number, y: number) { + public multiply2f (x: number, y: number): Vec2 { this.x *= x; this.y *= y; return this; @@ -675,7 +675,7 @@ export class Vec2 extends ValueType { * @zh 向量逐元素相除。将当前向量与指定分量的向量相除的结果赋值给当前向量。 * @param other specified vector */ - public divide (other: Vec2) { + public divide (other: Vec2): Vec2 { this.x /= other.x; this.y /= other.y; return this; @@ -687,7 +687,7 @@ export class Vec2 extends ValueType { * @param x The x value of specified vector * @param y The y value of specified vector */ - public divide2f (x: number, y: number) { + public divide2f (x: number, y: number): Vec2 { this.x /= x; this.y /= y; return this; @@ -697,7 +697,7 @@ export class Vec2 extends ValueType { * @en Sets each component of this vector with its negative value * @zh 将当前向量的各个分量取反 */ - public negative () { + public negative (): Vec2 { this.x = -this.x; this.y = -this.y; return this; @@ -709,7 +709,7 @@ export class Vec2 extends ValueType { * @param other specified vector * @return The result of calculates the dot product with another vector */ - public dot (other: Vec2) { + public dot (other: Vec2): number { return this.x * other.x + this.y * other.y; } @@ -722,7 +722,7 @@ export class Vec2 extends ValueType { /** * @deprecated since v3.8.0, There is no physical meaning. */ - public cross (other: Vec2) { + public cross (other: Vec2): number { return this.x * other.y - this.y * other.x; } @@ -731,7 +731,7 @@ export class Vec2 extends ValueType { * @zh 计算向量的长度(模)。 * @return Length of vector */ - public length () { + public length (): number { return Math.sqrt(this.x * this.x + this.y * this.y); } @@ -740,7 +740,7 @@ export class Vec2 extends ValueType { * @zh 计算向量长度(模)的平方。 * @return the squared length of this vector */ - public lengthSqr () { + public lengthSqr (): number { return this.x * this.x + this.y * this.y; } @@ -748,7 +748,7 @@ export class Vec2 extends ValueType { * @en Normalize the current vector. * @zh 将当前向量归一化。 */ - public normalize () { + public normalize (): Vec2 { const x = this.x; const y = this.y; let len = x * x + y * y; @@ -766,7 +766,7 @@ export class Vec2 extends ValueType { * @param other specified vector. * @return The angle between the current vector and the specified vector. */ - public angle (other: Vec2) { + public angle (other: Vec2): number { const magSqr1 = this.lengthSqr(); const magSqr2 = other.lengthSqr(); @@ -787,7 +787,7 @@ export class Vec2 extends ValueType { * @param other specified vector * @return The signed angle between the current vector and the specified vector (in radians); if there is a zero vector in the current vector and the specified vector, 0 is returned. */ - public signAngle (other: Vec2) { + public signAngle (other: Vec2): number { const angle = this.angle(other); return this.cross(other) < 0 ? -angle : angle; } @@ -797,7 +797,7 @@ export class Vec2 extends ValueType { * @zh 将当前向量进行旋转,逆时针为正方向。 * @param radians radians of rotation. */ - public rotate (radians: number) { + public rotate (radians: number): Vec2 { const x = this.x; const y = this.y; @@ -813,7 +813,7 @@ export class Vec2 extends ValueType { * @zh 计算当前向量在指定向量上的投影向量。 * @param other specified vector */ - public project (other: Vec2) { + public project (other: Vec2): Vec2 { const scalar = this.dot(other) / other.dot(other); this.x = other.x * scalar; this.y = other.y * scalar; @@ -826,7 +826,7 @@ export class Vec2 extends ValueType { * 应用四维矩阵变换到当前矩阵
* @param matrix matrix to transform with */ - public transformMat4 (matrix: Mat4) { + public transformMat4 (matrix: Mat4): Vec2 { const x = this.x; const y = this.y; this.x = matrix.m00 * x + matrix.m04 * y + matrix.m12; @@ -841,7 +841,7 @@ legacyCC.Vec2 = Vec2; export function v2 (other: Vec2): Vec2; export function v2 (x?: number, y?: number): Vec2; -export function v2 (x?: number | Vec2, y?: number) { +export function v2 (x?: number | Vec2, y?: number): Vec2 { return new Vec2(x as any, y); } diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index 28fead35cb7..a82d05dfa0e 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -49,7 +49,7 @@ export class Vec3 extends ValueType { * @en return a Vec3 object with x = 0, y = 0, z = 0. * @zh 将目标赋值为零向量 */ - public static zero (out: Out) { + public static zero (out: Out): Out { out.x = 0; out.y = 0; out.z = 0; @@ -60,7 +60,7 @@ export class Vec3 extends ValueType { * @en Obtains a clone of the given vector object * @zh 获得指定向量的拷贝 */ - public static clone (a: Out) { + public static clone (a: Out): Vec3 { return new Vec3(a.x, a.y, a.z); } @@ -68,7 +68,7 @@ export class Vec3 extends ValueType { * @en Copy the target vector and save the results to out vector object * @zh 复制目标向量 */ - public static copy (out: Out, a: Vec3Like) { + public static copy (out: Out, a: Vec3Like): Out { out.x = a.x; out.y = a.y; out.z = a.z; @@ -79,7 +79,7 @@ export class Vec3 extends ValueType { * @en Sets the out vector with the given x, y and z values * @zh 设置向量值 */ - public static set (out: Out, x: number, y: number, z: number) { + public static set (out: Out, x: number, y: number, z: number): Out { out.x = x; out.y = y; out.z = z; @@ -90,7 +90,7 @@ export class Vec3 extends ValueType { * @en Element-wise vector addition and save the results to out vector object * @zh 逐元素向量加法 */ - public static add (out: Out, a: IVec3Like, b: IVec3Like) { + public static add (out: Out, a: IVec3Like, b: IVec3Like): Out { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; @@ -101,7 +101,7 @@ export class Vec3 extends ValueType { * @en Element-wise vector subtraction and save the results to out vector object * @zh 逐元素向量减法 */ - public static subtract (out: Out, a: IVec3Like, b: IVec3Like) { + public static subtract (out: Out, a: IVec3Like, b: IVec3Like): Out { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; @@ -112,7 +112,7 @@ export class Vec3 extends ValueType { * @en Element-wise vector multiplication and save the results to out vector object * @zh 逐元素向量乘法 (分量积) */ - public static multiply (out: Out, a: IVec3Like, b: IVec3Like) { + public static multiply (out: Out, a: IVec3Like, b: IVec3Like): Out { out.x = a.x * b.x; out.y = a.y * b.y; out.z = a.z * b.z; @@ -123,7 +123,7 @@ export class Vec3 extends ValueType { * @en Element-wise vector division and save the results to out vector object * @zh 逐元素向量除法 */ - public static divide (out: Out, a: IVec3Like, b: IVec3Like) { + public static divide (out: Out, a: IVec3Like, b: IVec3Like): Out { out.x = a.x / b.x; out.y = a.y / b.y; out.z = a.z / b.z; @@ -134,7 +134,7 @@ export class Vec3 extends ValueType { * @en Rounds up by elements of the vector and save the results to out vector object * @zh 逐元素向量向上取整 */ - public static ceil (out: Out, a: IVec3Like) { + public static ceil (out: Out, a: IVec3Like): Out { out.x = Math.ceil(a.x); out.y = Math.ceil(a.y); out.z = Math.ceil(a.z); @@ -145,7 +145,7 @@ export class Vec3 extends ValueType { * @en Element-wise rounds down of the current vector and save the results to the out vector * @zh 逐元素向量向下取整 */ - public static floor (out: Out, a: IVec3Like) { + public static floor (out: Out, a: IVec3Like): Out { out.x = Math.floor(a.x); out.y = Math.floor(a.y); out.z = Math.floor(a.z); @@ -156,7 +156,7 @@ export class Vec3 extends ValueType { * @en Calculates element-wise minimum values and save to the out vector * @zh 逐元素向量最小值 */ - public static min (out: Out, a: IVec3Like, b: IVec3Like) { + public static min (out: Out, a: IVec3Like, b: IVec3Like): Out { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); out.z = Math.min(a.z, b.z); @@ -167,7 +167,7 @@ export class Vec3 extends ValueType { * @en Calculates element-wise maximum values and save to the out vector * @zh 逐元素向量最大值 */ - public static max (out: Out, a: IVec3Like, b: IVec3Like) { + public static max (out: Out, a: IVec3Like, b: IVec3Like): Out { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); out.z = Math.max(a.z, b.z); @@ -178,7 +178,7 @@ export class Vec3 extends ValueType { * @en Calculates element-wise round results and save to the out vector * @zh 逐元素向量四舍五入取整 */ - public static round (out: Out, a: IVec3Like) { + public static round (out: Out, a: IVec3Like): Out { out.x = Math.round(a.x); out.y = Math.round(a.y); out.z = Math.round(a.z); @@ -189,7 +189,7 @@ export class Vec3 extends ValueType { * @en Vector scalar multiplication and save the results to out vector object * @zh 向量标量乘法 */ - public static multiplyScalar (out: Out, a: Vec3Like, b: number) { + public static multiplyScalar (out: Out, a: Vec3Like, b: number): Out { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; @@ -200,7 +200,7 @@ export class Vec3 extends ValueType { * @en Element-wise multiplication and addition with the equation: a + b * scale * @zh 逐元素向量乘加: A + B * scale */ - public static scaleAndAdd (out: Out, a: IVec3Like, b: IVec3Like, scale: number) { + public static scaleAndAdd (out: Out, a: IVec3Like, b: IVec3Like, scale: number): Out { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale; @@ -211,7 +211,7 @@ export class Vec3 extends ValueType { * @en Calculates the euclidean distance of two vectors * @zh 求两向量的欧氏距离 */ - public static distance (a: IVec3Like, b: IVec3Like) { + public static distance (a: IVec3Like, b: IVec3Like): number { const x = b.x - a.x; const y = b.y - a.y; const z = b.z - a.z; @@ -222,7 +222,7 @@ export class Vec3 extends ValueType { * @en Calculates the squared euclidean distance of two vectors * @zh 求两向量的欧氏距离平方 */ - public static squaredDistance (a: IVec3Like, b: IVec3Like) { + public static squaredDistance (a: IVec3Like, b: IVec3Like): number { const x = b.x - a.x; const y = b.y - a.y; const z = b.z - a.z; @@ -233,7 +233,7 @@ export class Vec3 extends ValueType { * @en Calculates the length of the vector * @zh 求向量长度 */ - public static len (a: IVec3Like) { + public static len (a: IVec3Like): number { const x = a.x; const y = a.y; const z = a.z; @@ -244,7 +244,7 @@ export class Vec3 extends ValueType { * @en Calculates the squared length of the vector * @zh 求向量长度平方 */ - public static lengthSqr (a: IVec3Like) { + public static lengthSqr (a: IVec3Like): number { const x = a.x; const y = a.y; const z = a.z; @@ -255,7 +255,7 @@ export class Vec3 extends ValueType { * @en Sets each element to its negative value * @zh 逐元素向量取负 */ - public static negate (out: Out, a: IVec3Like) { + public static negate (out: Out, a: IVec3Like): Out { out.x = -a.x; out.y = -a.y; out.z = -a.z; @@ -266,7 +266,7 @@ export class Vec3 extends ValueType { * @en Sets each element to its inverse value, zero value will become Infinity * @zh 逐元素向量取倒数,接近 0 时返回 Infinity */ - public static invert (out: Out, a: IVec3Like) { + public static invert (out: Out, a: IVec3Like): Out { out.x = 1.0 / a.x; out.y = 1.0 / a.y; out.z = 1.0 / a.z; @@ -277,7 +277,7 @@ export class Vec3 extends ValueType { * @en Sets each element to its inverse value, zero value will remain zero * @zh 逐元素向量取倒数,接近 0 时返回 0 */ - public static invertSafe (out: Out, a: IVec3Like) { + public static invertSafe (out: Out, a: IVec3Like): Out { const x = a.x; const y = a.y; const z = a.z; @@ -307,7 +307,7 @@ export class Vec3 extends ValueType { * @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector. * @zh 归一化向量,输入零向量将会返回零向量。 */ - public static normalize (out: Out, a: IVec3Like) { + public static normalize (out: Out, a: IVec3Like): Out { const x = a.x; const y = a.y; const z = a.z; @@ -330,7 +330,7 @@ export class Vec3 extends ValueType { * @en Calculates the dot product of the vector * @zh 向量点积(数量积) */ - public static dot (a: Out, b: IVec3Like) { + public static dot (a: Out, b: IVec3Like): number { return a.x * b.x + a.y * b.y + a.z * b.z; } @@ -338,7 +338,7 @@ export class Vec3 extends ValueType { * @en Calculates the cross product of the vector * @zh 向量叉积(向量积) */ - public static cross (out: Out, a: IVec3Like, b: IVec3Like) { + public static cross (out: Out, a: IVec3Like, b: IVec3Like): Out { const { x: ax, y: ay, z: az } = a; const { x: bx, y: by, z: bz } = b; out.x = ay * bz - az * by; @@ -351,7 +351,7 @@ export class Vec3 extends ValueType { * @en Calculates the linear interpolation between two vectors with a given ratio: A + t * (B - A) * @zh 逐元素向量线性插值: A + t * (B - A) */ - public static lerp (out: Out, a: IVec3Like, b: IVec3Like, t: number) { + public static lerp (out: Out, a: IVec3Like, b: IVec3Like, t: number): Out { out.x = a.x + t * (b.x - a.x); out.y = a.y + t * (b.y - a.y); out.z = a.z + t * (b.z - a.z); @@ -388,11 +388,11 @@ export class Vec3 extends ValueType { * from normalized `from` to normalized `to`, * then scaled by linear interpolation of lengths from `from` to `to`. */ - public static slerp= (() => { + public static slerp= ((): (out: Out, from: Readonly, to: Readonly, t: number) => Out => { const cacheV1 = new Vec3(); const cacheV2 = new Vec3(); const cacheV3 = new Vec3(); - return (out: Out, from: Readonly, to: Readonly, t: number) => { + return (out: Out, from: Readonly, to: Readonly, t: number): Out => { const EPSILON = 1e-5; const lenFrom = Vec3.len(from); const lenTo = Vec3.len(to); @@ -434,7 +434,7 @@ export class Vec3 extends ValueType { * @zh 生成一个在单位球体上均匀分布的随机向量 * @param scale vector length */ - public static random (out: Out, scale?: number) { + public static random (out: Out, scale?: number): Out { scale = scale || 1.0; const phi = random() * 2.0 * Math.PI; @@ -451,7 +451,7 @@ export class Vec3 extends ValueType { * @en Vector and fourth order matrix multiplication, will complete the vector with a fourth value as one * @zh 向量与四维矩阵乘法,默认向量第四位为 1。 */ - public static transformMat4 (out: Out, a: IVec3Like, m: IMat4Like) { + public static transformMat4 (out: Out, a: IVec3Like, m: IMat4Like): Out { const x = a.x; const y = a.y; const z = a.z; @@ -467,7 +467,7 @@ export class Vec3 extends ValueType { * @en Vector and fourth order matrix multiplication, will complete the vector with a fourth element as one * @zh 向量与四维矩阵乘法,默认向量第四位为 0。 */ - public static transformMat4Normal (out: Out, a: IVec3Like, m: IMat4Like) { + public static transformMat4Normal (out: Out, a: IVec3Like, m: IMat4Like): Out { const x = a.x; const y = a.y; const z = a.z; @@ -483,7 +483,7 @@ export class Vec3 extends ValueType { * @en Vector and third order matrix multiplication * @zh 向量与三维矩阵乘法 */ - public static transformMat3 (out: Out, a: IVec3Like, m: IMat3Like) { + public static transformMat3 (out: Out, a: IVec3Like, m: IMat3Like): Out { const x = a.x; const y = a.y; const z = a.z; @@ -497,7 +497,7 @@ export class Vec3 extends ValueType { * @en Affine transformation vector * @zh 向量仿射变换 */ - public static transformAffine (out: Out, v: IVec3Like, m: IMat4Like) { + public static transformAffine (out: Out, v: IVec3Like, m: IMat4Like): Out { const x = v.x; const y = v.y; const z = v.z; @@ -511,7 +511,7 @@ export class Vec3 extends ValueType { * @en Vector quaternion multiplication: q*a*q^{-1}. * @zh 向量四元数乘法:q*a*q^{-1}。 */ - public static transformQuat (out: Out, a: IVec3Like, q: IQuatLike) { + public static transformQuat (out: Out, a: IVec3Like, q: IQuatLike): Out { // benchmarks: http://jsperf.com/quaternion-transform-Vec3-implementations // calculate quat * vec @@ -531,7 +531,7 @@ export class Vec3 extends ValueType { * @en Transforms the current vector with given scale, rotation and translation in order * @zh 以缩放 -> 旋转 -> 平移顺序变换向量 */ - public static transformRTS (out: Out, a: IVec3Like, r: IQuatLike, t: IVec3Like, s: IVec3Like) { + public static transformRTS (out: Out, a: IVec3Like, r: IQuatLike, t: IVec3Like, s: IVec3Like): Out { const x = a.x * s.x; const y = a.y * s.y; const z = a.z * s.z; @@ -549,7 +549,7 @@ export class Vec3 extends ValueType { * @en Transforms the current vector with given scale, rotation and translation in reverse order * @zh 以平移 -> 旋转 -> 缩放顺序逆变换向量 */ - public static transformInverseRTS (out: Out, a: IVec3Like, r: IQuatLike, t: IVec3Like, s: IVec3Like) { + public static transformInverseRTS (out: Out, a: IVec3Like, r: IQuatLike, t: IVec3Like, s: IVec3Like): Out { const x = a.x - t.x; const y = a.y - t.y; const z = a.z - t.z; @@ -570,7 +570,7 @@ export class Vec3 extends ValueType { * @param o center of rotation * @param a radiance of rotation */ - public static rotateX (out: Out, v: IVec3Like, o: IVec3Like, a: number) { + public static rotateX (out: Out, v: IVec3Like, o: IVec3Like, a: number): Out { // Translate point to the origin const x = v.x - o.x; const y = v.y - o.y; @@ -598,7 +598,7 @@ export class Vec3 extends ValueType { * @param o center of rotation * @param a radiance of rotation */ - public static rotateY (out: Out, v: IVec3Like, o: IVec3Like, a: number) { + public static rotateY (out: Out, v: IVec3Like, o: IVec3Like, a: number): Out { // Translate point to the origin const x = v.x - o.x; const y = v.y - o.y; @@ -626,7 +626,7 @@ export class Vec3 extends ValueType { * @param o center of rotation * @param a radiance of rotation */ - public static rotateZ (out: Out, v: IVec3Like, o: IVec3Like, a: number) { + public static rotateZ (out: Out, v: IVec3Like, o: IVec3Like, a: number): Out { // Translate point to the origin const x = v.x - o.x; const y = v.y - o.y; @@ -655,7 +655,7 @@ export class Vec3 extends ValueType { * @param n axis of rotation * @param a radiance of rotation */ - public static rotateN (out: Out, v: IVec3Like, o: IVec3Like, n: IVec3Like, a: number) { + public static rotateN (out: Out, v: IVec3Like, o: IVec3Like, n: IVec3Like, a: number): Out { // Translate point to the origin const x = v.x - o.x; const y = v.y - o.y; @@ -685,7 +685,7 @@ export class Vec3 extends ValueType { * @zh 向量转数组 * @param ofs Array Start Offset */ - public static toArray > (out: Out, v: IVec3Like, ofs = 0) { + public static toArray > (out: Out, v: IVec3Like, ofs = 0): Out { out[ofs + 0] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; @@ -698,7 +698,7 @@ export class Vec3 extends ValueType { * @zh 数组转向量 * @param ofs Array Start Offset */ - public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0) { + public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0): Out { out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; out.z = arr[ofs + 2]; @@ -709,7 +709,7 @@ export class Vec3 extends ValueType { * @en Check the equality of the two given vectors * @zh 向量等价判断 */ - public static strictEquals (a: IVec3Like, b: IVec3Like) { + public static strictEquals (a: IVec3Like, b: IVec3Like): boolean { return a.x === b.x && a.y === b.y && a.z === b.z; } @@ -717,7 +717,7 @@ export class Vec3 extends ValueType { * @en Check whether the two given vectors are approximately equivalent * @zh 排除浮点数误差的向量近似等价判断 */ - public static equals (a: IVec3Like, b: IVec3Like, epsilon = EPSILON) { + public static equals (a: IVec3Like, b: IVec3Like, epsilon = EPSILON): boolean { const { x: a0, y: a1, z: a2 } = a; const { x: b0, y: b1, z: b2 } = b; return ( @@ -734,7 +734,7 @@ export class Vec3 extends ValueType { * @en Calculates the radian angle between two vectors * @zh 求两向量夹角弧度 */ - public static angle (a: IVec3Like, b: IVec3Like) { + public static angle (a: IVec3Like, b: IVec3Like): number { const magSqr1 = a.x * a.x + a.y * a.y + a.z * a.z; const magSqr2 = b.x * b.x + b.y * b.y + b.z * b.z; @@ -754,7 +754,7 @@ export class Vec3 extends ValueType { * @param a projection vector * @param n the normal line of specified plane */ - public static projectOnPlane (out: Out, a: IVec3Like, n: IVec3Like) { + public static projectOnPlane (out: Out, a: IVec3Like, n: IVec3Like): Out { return Vec3.subtract(out, a, Vec3.project(out, a, n)); } @@ -764,7 +764,7 @@ export class Vec3 extends ValueType { * @param a projection vector * @param b target vector */ - public static project (out: Out, a: IVec3Like, b: IVec3Like) { + public static project (out: Out, a: IVec3Like, b: IVec3Like): Out { const sqrLen = Vec3.lengthSqr(b); if (sqrLen < 0.000001) { return Vec3.set(out, 0, 0, 0); @@ -780,7 +780,7 @@ export class Vec3 extends ValueType { * @param target target position * @param maxStep maximum moving distance */ - public static moveTowards (out: Out, current: IVec3Like, target: IVec3Like, maxStep: number) { + public static moveTowards (out: Out, current: IVec3Like, target: IVec3Like, maxStep: number): Out { const deltaX = target.x - current.x; const deltaY = target.y - current.y; const deltaZ = target.z - current.z; @@ -840,7 +840,7 @@ export class Vec3 extends ValueType { * @en clone a Vec3 value * @zh 克隆当前向量。 */ - public clone () { + public clone (): Vec3 { return new Vec3(this.x, this.y, this.z); } @@ -862,7 +862,7 @@ export class Vec3 extends ValueType { */ public set (x?: number, y?: number, z?: number): Vec3; - public set (x?: number | Vec3, y?: number, z?: number) { + public set (x?: number | Vec3, y?: number, z?: number): Vec3 { if (typeof x === 'object') { this.x = x.x; this.y = x.y; @@ -882,7 +882,7 @@ export class Vec3 extends ValueType { * @param epsilon The error allowed. It`s should be a non-negative number. * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public equals (other: Vec3, epsilon = EPSILON) { + public equals (other: Vec3, epsilon = EPSILON): boolean { return ( Math.abs(this.x - other.x) <= epsilon && Math.abs(this.y - other.y) <= epsilon @@ -899,7 +899,7 @@ export class Vec3 extends ValueType { * @param epsilon The error allowed. It`s should be a non-negative number. * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public equals3f (x: number, y: number, z: number, epsilon = EPSILON) { + public equals3f (x: number, y: number, z: number, epsilon = EPSILON): boolean { return ( Math.abs(this.x - x) <= epsilon && Math.abs(this.y - y) <= epsilon @@ -913,7 +913,7 @@ export class Vec3 extends ValueType { * @param other specified vector * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public strictEquals (other: Vec3) { + public strictEquals (other: Vec3): boolean { return this.x === other.x && this.y === other.y && this.z === other.z; } @@ -925,7 +925,7 @@ export class Vec3 extends ValueType { * @param z The z value of specified vector * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public strictEquals3f (x: number, y: number, z: number) { + public strictEquals3f (x: number, y: number, z: number): boolean { return this.x === x && this.y === y && this.z === z; } @@ -934,7 +934,7 @@ export class Vec3 extends ValueType { * @zh 返回当前向量的字符串表示。 * @returns The string with vector information */ - public toString () { + public toString (): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)})`; } @@ -944,7 +944,7 @@ export class Vec3 extends ValueType { * @param to Target vector * @param ratio The interpolation coefficient.The range is [0,1]. */ - public lerp (to: Vec3, ratio: number) { + public lerp (to: Vec3, ratio: number): Vec3 { this.x += ratio * (to.x - this.x); this.y += ratio * (to.y - this.y); this.z += ratio * (to.z - this.z); @@ -956,7 +956,7 @@ export class Vec3 extends ValueType { * @zh 向量加法。将当前向量与指定向量的相加 * @param other specified vector */ - public add (other: Vec3) { + public add (other: Vec3): Vec3 { this.x += other.x; this.y += other.y; this.z += other.z; @@ -970,7 +970,7 @@ export class Vec3 extends ValueType { * @param y The y value of specified vector * @param z The z value of specified vector */ - public add3f (x: number, y: number, z: number) { + public add3f (x: number, y: number, z: number): Vec3 { this.x += x; this.y += y; this.z += z; @@ -982,7 +982,7 @@ export class Vec3 extends ValueType { * @zh 向量减法。将当前向量减去指定向量的结果。 * @param other specified vector */ - public subtract (other: Vec3) { + public subtract (other: Vec3): Vec3 { this.x -= other.x; this.y -= other.y; this.z -= other.z; @@ -996,7 +996,7 @@ export class Vec3 extends ValueType { * @param y The y value of specified vector * @param z The z value of specified vector */ - public subtract3f (x: number, y: number, z: number) { + public subtract3f (x: number, y: number, z: number): Vec3 { this.x -= x; this.y -= y; this.z -= z; @@ -1008,7 +1008,7 @@ export class Vec3 extends ValueType { * @zh 向量数乘。将当前向量数乘指定标量 * @param scalar scalar number */ - public multiplyScalar (scalar: number) { + public multiplyScalar (scalar: number): Vec3 { if (typeof scalar === 'object') { console.warn('should use Vec3.multiply for vector * vector operation'); } this.x *= scalar; this.y *= scalar; @@ -1021,7 +1021,7 @@ export class Vec3 extends ValueType { * @zh 向量乘法。将当前向量乘以与指定向量的结果赋值给当前向量。 * @param other specified vector */ - public multiply (other: Vec3) { + public multiply (other: Vec3): Vec3 { if (typeof other !== 'object') { console.warn('should use Vec3.scale for vector * scalar operation'); } this.x *= other.x; this.y *= other.y; @@ -1036,7 +1036,7 @@ export class Vec3 extends ValueType { * @param y The y value of specified vector * @param z The z value of specified vector */ - public multiply3f (x: number, y: number, z: number) { + public multiply3f (x: number, y: number, z: number): Vec3 { this.x *= x; this.y *= y; this.z *= z; @@ -1048,7 +1048,7 @@ export class Vec3 extends ValueType { * @zh 向量逐元素相除。将当前向量与指定分量的向量相除的结果赋值给当前向量。 * @param other specified vector */ - public divide (other: Vec3) { + public divide (other: Vec3): Vec3 { this.x /= other.x; this.y /= other.y; this.z /= other.z; @@ -1062,7 +1062,7 @@ export class Vec3 extends ValueType { * @param y The y value of specified vector * @param z The z value of specified vector */ - public divide3f (x: number, y: number, z: number) { + public divide3f (x: number, y: number, z: number): Vec3 { this.x /= x; this.y /= y; this.z /= z; @@ -1073,7 +1073,7 @@ export class Vec3 extends ValueType { * @en Sets each component of this vector with its negative value * @zh 将当前向量的各个分量取反 */ - public negative () { + public negative (): Vec3 { this.x = -this.x; this.y = -this.y; this.z = -this.z; @@ -1087,7 +1087,7 @@ export class Vec3 extends ValueType { * @param maxInclusive Maximum value allowed * @returns `this` */ - public clampf (minInclusive: Vec3, maxInclusive: Vec3) { + public clampf (minInclusive: Vec3, maxInclusive: Vec3): Vec3 { this.x = clamp(this.x, minInclusive.x, maxInclusive.x); this.y = clamp(this.y, minInclusive.y, maxInclusive.y); this.z = clamp(this.z, minInclusive.z, maxInclusive.z); @@ -1100,7 +1100,7 @@ export class Vec3 extends ValueType { * @param other specified vector * @returns The result of calculates the dot product with another vector */ - public dot (other: Vec3) { + public dot (other: Vec3): number { return this.x * other.x + this.y * other.y + this.z * other.z; } @@ -1109,7 +1109,7 @@ export class Vec3 extends ValueType { * @zh 向量叉乘。将当前向量左叉乘指定向量 * @param other specified vector */ - public cross (other: Vec3) { + public cross (other: Vec3): Vec3 { const { x: ax, y: ay, z: az } = this; const { x: bx, y: by, z: bz } = other; @@ -1124,7 +1124,7 @@ export class Vec3 extends ValueType { * @zh 计算向量的长度(模)。 * @returns Length of vector */ - public length () { + public length (): number { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } @@ -1133,7 +1133,7 @@ export class Vec3 extends ValueType { * @zh 计算向量长度(模)的平方。 * @returns the squared length of this vector */ - public lengthSqr () { + public lengthSqr (): number { return this.x * this.x + this.y * this.y + this.z * this.z; } @@ -1141,7 +1141,7 @@ export class Vec3 extends ValueType { * @en Normalize the current vector. * @zh 将当前向量归一化 */ - public normalize () { + public normalize (): Vec3 { const x = this.x; const y = this.y; const z = this.z; @@ -1162,7 +1162,7 @@ export class Vec3 extends ValueType { * @zh 将当前向量视为 w 分量为 1 的四维向量,应用四维矩阵变换到当前矩阵 * @param matrix matrix to transform with */ - public transformMat4 (matrix: Mat4) { + public transformMat4 (matrix: Mat4): Vec3 { const x = this.x; const y = this.y; const z = this.z; @@ -1181,14 +1181,14 @@ legacyCC.Vec3 = Vec3; export function v3 (other: Vec3): Vec3; export function v3 (x?: number, y?: number, z?: number): Vec3; -export function v3 (x?: number | Vec3, y?: number, z?: number) { +export function v3 (x?: number | Vec3, y?: number, z?: number): Vec3 { return new Vec3(x as any, y, z); } /** * Chooses an arbitrary unit vector that is perpendicular to input. */ -function chooseAnyPerpendicular (out: Vec3, v: Readonly) { +function chooseAnyPerpendicular (out: Vec3, v: Readonly): Vec3 { const { x, y, z } = v; // 1. Drop the component with minimal magnitude. // 2. Negate one of the remain components. @@ -1209,10 +1209,10 @@ function chooseAnyPerpendicular (out: Vec3, v: Readonly) { /** * Rotates `input` around `axis` for `angle` radians. */ -const rotateAxisAngle = (() => { +const rotateAxisAngle = ((): (out: Vec3, input: Readonly, axis: Readonly, angle: number) => Vec3 => { // TODO: can this cause v8 hidden class problem? const cacheQ = { x: 0.0, y: 0.0, z: 0.0, w: 0.0 }; - return (out: Vec3, input: Readonly, axis: Readonly, angle: number) => { + return (out: Vec3, input: Readonly, axis: Readonly, angle: number): Vec3 => { // This should be equivalent to `Quat.fromAxisAngle(cacheQ, axis, angle)`. // Here we duplicate the code to avoid circular reference. diff --git a/cocos/core/math/vec4.ts b/cocos/core/math/vec4.ts index f16e43da70f..6146b721fd3 100644 --- a/cocos/core/math/vec4.ts +++ b/cocos/core/math/vec4.ts @@ -47,7 +47,7 @@ export class Vec4 extends ValueType { * @en Obtains a clone of the given vector object * @zh 获得指定向量的拷贝 */ - public static clone (a: Out) { + public static clone (a: Out): Vec4 { return new Vec4(a.x, a.y, a.z, a.w); } @@ -55,7 +55,7 @@ export class Vec4 extends ValueType { * @en Copy the target vector and save the results to out vector object * @zh 复制目标向量 */ - public static copy (out: Out, a: Out) { + public static copy (out: Out, a: Out): Out { out.x = a.x; out.y = a.y; out.z = a.z; @@ -67,7 +67,7 @@ export class Vec4 extends ValueType { * @en Sets the out vector with the given x, y, z and w values * @zh 设置向量值 */ - public static set (out: Out, x: number, y: number, z: number, w: number) { + public static set (out: Out, x: number, y: number, z: number, w: number): Out { out.x = x; out.y = y; out.z = z; @@ -81,7 +81,7 @@ export class Vec4 extends ValueType { * @param out * @param color */ - public static fromColor (out: Out, color: IColorLike) { + public static fromColor (out: Out, color: IColorLike): Out { out.x = color.r; out.y = color.g; out.z = color.b; @@ -93,7 +93,7 @@ export class Vec4 extends ValueType { * @en The angle between two vectors * @zh 两个向量之间的夹角 */ - public static angle (a: Out, b: Out) { + public static angle (a: Out, b: Out): number { // use atan2 to get the sign of the angle correctly const dx = (a.y * b.z - a.z * b.y); const dy = (a.z * b.x - a.x * b.z); @@ -107,7 +107,7 @@ export class Vec4 extends ValueType { * @en Element-wise vector addition and save the results to out vector object * @zh 逐元素向量加法 */ - public static add (out: Out, a: Out, b: Out) { + public static add (out: Out, a: Out, b: Out): Out { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; @@ -119,7 +119,7 @@ export class Vec4 extends ValueType { * @en Element-wise vector subtraction and save the results to out vector object * @zh 逐元素向量减法 */ - public static subtract (out: Out, a: Out, b: Out) { + public static subtract (out: Out, a: Out, b: Out): Out { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; @@ -131,7 +131,7 @@ export class Vec4 extends ValueType { * @en Element-wise vector multiplication and save the results to out vector object * @zh 逐元素向量乘法 */ - public static multiply (out: Out, a: Out, b: Out) { + public static multiply (out: Out, a: Out, b: Out): Out { out.x = a.x * b.x; out.y = a.y * b.y; out.z = a.z * b.z; @@ -143,7 +143,7 @@ export class Vec4 extends ValueType { * @en Element-wise vector division and save the results to out vector object * @zh 逐元素向量除法 */ - public static divide (out: Out, a: Out, b: Out) { + public static divide (out: Out, a: Out, b: Out): Out { out.x = a.x / b.x; out.y = a.y / b.y; out.z = a.z / b.z; @@ -155,7 +155,7 @@ export class Vec4 extends ValueType { * @en Rounds up by elements of the vector and save the results to out vector object * @zh 逐元素向量向上取整 */ - public static ceil (out: Out, a: Out) { + public static ceil (out: Out, a: Out): Out { out.x = Math.ceil(a.x); out.y = Math.ceil(a.y); out.z = Math.ceil(a.z); @@ -167,7 +167,7 @@ export class Vec4 extends ValueType { * @en Element-wise rounds down of the current vector and save the results to the out vector * @zh 逐元素向量向下取整 */ - public static floor (out: Out, a: Out) { + public static floor (out: Out, a: Out): Out { out.x = Math.floor(a.x); out.y = Math.floor(a.y); out.z = Math.floor(a.z); @@ -179,7 +179,7 @@ export class Vec4 extends ValueType { * @en Calculates the minimum values by elements of the vector and save the results to the out vector * @zh 逐元素向量最小值 */ - public static min (out: Out, a: Out, b: Out) { + public static min (out: Out, a: Out, b: Out): Out { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); out.z = Math.min(a.z, b.z); @@ -191,7 +191,7 @@ export class Vec4 extends ValueType { * @en Calculates the maximum values by elements of the vector and save the results to the out vector * @zh 逐元素向量最大值 */ - public static max (out: Out, a: Out, b: Out) { + public static max (out: Out, a: Out, b: Out): Out { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); out.z = Math.max(a.z, b.z); @@ -203,7 +203,7 @@ export class Vec4 extends ValueType { * @en Calculates element-wise round results and save to the out vector * @zh 逐元素向量四舍五入取整 */ - public static round (out: Out, a: Out) { + public static round (out: Out, a: Out): Out { out.x = Math.round(a.x); out.y = Math.round(a.y); out.z = Math.round(a.z); @@ -215,7 +215,7 @@ export class Vec4 extends ValueType { * @en Vector scalar multiplication and save the results to out vector object * @zh 向量标量乘法 */ - public static multiplyScalar (out: Out, a: Out, b: number) { + public static multiplyScalar (out: Out, a: Out, b: number): Out { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; @@ -227,7 +227,7 @@ export class Vec4 extends ValueType { * @en Element-wise multiplication and addition with the equation: a + b * scale * @zh 逐元素向量乘加: A + B * scale */ - public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number) { + public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number): Out { out.x = a.x + (b.x * scale); out.y = a.y + (b.y * scale); out.z = a.z + (b.z * scale); @@ -239,7 +239,7 @@ export class Vec4 extends ValueType { * @en Calculates the euclidean distance of two vectors * @zh 求两向量的欧氏距离 */ - public static distance (a: Out, b: Out) { + public static distance (a: Out, b: Out): number { const x = b.x - a.x; const y = b.y - a.y; const z = b.z - a.z; @@ -251,7 +251,7 @@ export class Vec4 extends ValueType { * @en Calculates the squared euclidean distance of two vectors * @zh 求两向量的欧氏距离平方 */ - public static squaredDistance (a: Out, b: Out) { + public static squaredDistance (a: Out, b: Out): number { const x = b.x - a.x; const y = b.y - a.y; const z = b.z - a.z; @@ -263,7 +263,7 @@ export class Vec4 extends ValueType { * @en Calculates the length of the vector * @zh 求向量长度 */ - public static len (a: Out) { + public static len (a: Out): number { const x = a.x; const y = a.y; const z = a.z; @@ -275,7 +275,7 @@ export class Vec4 extends ValueType { * @en Calculates the squared length of the vector * @zh 求向量长度平方 */ - public static lengthSqr (a: Out) { + public static lengthSqr (a: Out): number { const x = a.x; const y = a.y; const z = a.z; @@ -287,7 +287,7 @@ export class Vec4 extends ValueType { * @en Sets each element to its negative value * @zh 逐元素向量取负 */ - public static negate (out: Out, a: Out) { + public static negate (out: Out, a: Out): Out { out.x = -a.x; out.y = -a.y; out.z = -a.z; @@ -299,7 +299,7 @@ export class Vec4 extends ValueType { * @en Sets each element to its inverse value, zero value will become Infinity * @zh 逐元素向量取倒数,接近 0 时返回 Infinity */ - public static inverse (out: Out, a: Out) { + public static inverse (out: Out, a: Out): Out { out.x = 1.0 / a.x; out.y = 1.0 / a.y; out.z = 1.0 / a.z; @@ -311,7 +311,7 @@ export class Vec4 extends ValueType { * @en Sets each element to its inverse value, zero value will remain zero * @zh 逐元素向量取倒数,接近 0 时返回 0 */ - public static inverseSafe (out: Out, a: Out) { + public static inverseSafe (out: Out, a: Out): Out { const x = a.x; const y = a.y; const z = a.z; @@ -348,7 +348,7 @@ export class Vec4 extends ValueType { * @en Sets the normalized vector to the out vector, returns a zero vector if input is a zero vector. * @zh 归一化向量,输入零向量将会返回零向量。 */ - public static normalize (out: Out, a: Out) { + public static normalize (out: Out, a: Out): Out { const x = a.x; const y = a.y; const z = a.z; @@ -373,7 +373,7 @@ export class Vec4 extends ValueType { * @en Calculates the dot product of the vector * @zh 向量点积(数量积) */ - public static dot (a: Out, b: Out) { + public static dot (a: Out, b: Out): number { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } @@ -381,7 +381,7 @@ export class Vec4 extends ValueType { * @en Calculates the linear interpolation between two vectors with a given ratio * @zh 逐元素向量线性插值: A + t * (B - A) */ - public static lerp (out: Out, a: Out, b: Out, t: number) { + public static lerp (out: Out, a: Out, b: Out, t: number): Out { out.x = a.x + t * (b.x - a.x); out.y = a.y + t * (b.y - a.y); out.z = a.z + t * (b.z - a.z); @@ -393,7 +393,7 @@ export class Vec4 extends ValueType { * @en Scales all ell elements of this vector by the specified scalar value * @zh 逐元素向量缩放 */ - public static scale (out: Out, a: Out, b: number) { + public static scale (out: Out, a: Out, b: number): Out { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; @@ -406,7 +406,7 @@ export class Vec4 extends ValueType { * @zh 生成一个在单位球体上均匀分布的随机向量 * @param scale vector length */ - public static random (out: Out, scale?: number) { + public static random (out: Out, scale?: number): Out { scale = scale || 1.0; const phi = random() * 2.0 * Math.PI; @@ -424,7 +424,7 @@ export class Vec4 extends ValueType { * @en Vector and fourth order matrix multiplication * @zh 向量与四维矩阵乘法 */ - public static transformMat4 (out: Out, a: Out, m: MatLike) { + public static transformMat4 (out: Out, a: Out, m: MatLike): Out { const x = a.x; const y = a.y; const z = a.z; @@ -441,7 +441,7 @@ export class Vec4 extends ValueType { * @zh 向量仿射变换 */ public static transformAffine - (out: Out, v: VecLike, m: MatLike) { + (out: Out, v: VecLike, m: MatLike): Out { const x = v.x; const y = v.y; const z = v.z; @@ -457,7 +457,7 @@ export class Vec4 extends ValueType { * @en Vector quaternion multiplication * @zh 向量四元数乘法 */ - public static transformQuat (out: Out, a: Out, q: QuatLike) { + public static transformQuat (out: Out, a: Out, q: QuatLike): Out { // qpq^{-1} https://en.wikipedia.org/wiki/Quaternion#Hamilton_product const { x, y, z } = a; @@ -485,7 +485,7 @@ export class Vec4 extends ValueType { * @zh 向量转数组 * @param ofs Array Start Offset */ - public static toArray > (out: Out, v: IVec4Like, ofs = 0) { + public static toArray > (out: Out, v: IVec4Like, ofs = 0): Out { out[ofs + 0] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; @@ -498,7 +498,7 @@ export class Vec4 extends ValueType { * @zh 数组转向量 * @param ofs Array Start Offset */ - public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0) { + public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0): Out { out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; out.z = arr[ofs + 2]; @@ -510,7 +510,7 @@ export class Vec4 extends ValueType { * @en Check the equality of the two given vectors * @zh 向量等价判断 */ - public static strictEquals (a: Out, b: Out) { + public static strictEquals (a: Out, b: Out): boolean { return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; } @@ -518,7 +518,7 @@ export class Vec4 extends ValueType { * @en Check whether the two given vectors are approximately equivalent * @zh 排除浮点数误差的向量近似等价判断 */ - public static equals (a: Out, b: Out, epsilon = EPSILON) { + public static equals (a: Out, b: Out, epsilon = EPSILON): boolean { // relative epsilon comparison with small number guard: // https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ const hasInf = Math.abs(a.x) === Infinity || Math.abs(a.y) === Infinity || Math.abs(a.z) === Infinity || Math.abs(a.w) === Infinity @@ -576,7 +576,7 @@ export class Vec4 extends ValueType { * @en clone the current Vec4 value. * @zh 克隆当前向量。 */ - public clone () { + public clone (): Vec4 { return new Vec4(this.x, this.y, this.z, this.w); } @@ -599,7 +599,7 @@ export class Vec4 extends ValueType { */ public set (x?: number, y?: number, z?: number, w?: number): Vec4; - public set (x?: number | Vec4, y?: number, z?: number, w?: number) { + public set (x?: number | Vec4, y?: number, z?: number, w?: number): Vec4 { if (typeof x === 'object') { this.x = x.x; this.y = x.y; @@ -621,7 +621,7 @@ export class Vec4 extends ValueType { * @param epsilon The error allowed. It`s should be a non-negative number. * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public equals (other: Vec4, epsilon = EPSILON) { + public equals (other: Vec4, epsilon = EPSILON): boolean { return (Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) @@ -638,7 +638,7 @@ export class Vec4 extends ValueType { * @param epsilon The error allowed. It`s should be a non-negative number. * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public equals4f (x: number, y: number, z: number, w: number, epsilon = EPSILON) { + public equals4f (x: number, y: number, z: number, w: number, epsilon = EPSILON): boolean { return (Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y)) && Math.abs(this.z - z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(z)) @@ -651,7 +651,7 @@ export class Vec4 extends ValueType { * @param other specified vector * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public strictEquals (other: Vec4) { + public strictEquals (other: Vec4): boolean { return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; } @@ -664,7 +664,7 @@ export class Vec4 extends ValueType { * @param w The w value of specified vector * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ - public strictEquals4f (x: number, y: number, z: number, w: number) { + public strictEquals4f (x: number, y: number, z: number, w: number): boolean { return this.x === x && this.y === y && this.z === z && this.w === w; } @@ -674,7 +674,7 @@ export class Vec4 extends ValueType { * @param to Target vector * @param ratio The interpolation coefficient.The range is [0,1]. */ - public lerp (to: Vec4, ratio: number) { + public lerp (to: Vec4, ratio: number): Vec4 { const x = this.x; const y = this.y; const z = this.z; @@ -691,7 +691,7 @@ export class Vec4 extends ValueType { * @zh 返回当前向量的字符串表示。 * @returns The string with vector information */ - public toString () { + public toString (): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)}, ${this.w.toFixed(2)})`; } @@ -702,7 +702,7 @@ export class Vec4 extends ValueType { * @param maxInclusive Maximum value allowed * @returns `this` */ - public clampf (minInclusive: Vec4, maxInclusive: Vec4) { + public clampf (minInclusive: Vec4, maxInclusive: Vec4): Vec4 { this.x = clamp(this.x, minInclusive.x, maxInclusive.x); this.y = clamp(this.y, minInclusive.y, maxInclusive.y); this.z = clamp(this.z, minInclusive.z, maxInclusive.z); @@ -715,7 +715,7 @@ export class Vec4 extends ValueType { * @zh 向量加法。将当前向量与指定向量的相加 * @param other specified vector */ - public add (other: Vec4) { + public add (other: Vec4): Vec4 { this.x += other.x; this.y += other.y; this.z += other.z; @@ -731,7 +731,7 @@ export class Vec4 extends ValueType { * @param z The z value of specified vector * @param w The w value of specified vector */ - public add4f (x: number, y: number, z: number, w: number) { + public add4f (x: number, y: number, z: number, w: number): Vec4 { this.x += x; this.y += y; this.z += z; @@ -744,7 +744,7 @@ export class Vec4 extends ValueType { * @zh 向量减法。将当前向量减去指定向量 * @param other specified vector */ - public subtract (other: Vec4) { + public subtract (other: Vec4): Vec4 { this.x -= other.x; this.y -= other.y; this.z -= other.z; @@ -760,7 +760,7 @@ export class Vec4 extends ValueType { * @param z The z value of specified vector * @param w The w value of specified vector */ - public subtract4f (x: number, y: number, z: number, w: number) { + public subtract4f (x: number, y: number, z: number, w: number): Vec4 { this.x -= x; this.y -= y; this.z -= z; @@ -773,7 +773,7 @@ export class Vec4 extends ValueType { * @zh 向量数乘。将当前向量数乘指定标量 * @param scalar scalar number */ - public multiplyScalar (scalar: number) { + public multiplyScalar (scalar: number): Vec4 { if (typeof scalar === 'object') { console.warn('should use Vec4.multiply for vector * vector operation'); } this.x *= scalar; this.y *= scalar; @@ -787,7 +787,7 @@ export class Vec4 extends ValueType { * @zh 向量乘法。将当前向量乘以指定向量 * @param other specified vector */ - public multiply (other: Vec4) { + public multiply (other: Vec4): Vec4 { if (typeof other !== 'object') { console.warn('should use Vec4.scale for vector * scalar operation'); } this.x *= other.x; this.y *= other.y; @@ -804,7 +804,7 @@ export class Vec4 extends ValueType { * @param z The z value of specified vector * @param w The w value of specified vector */ - public multiply4f (x: number, y: number, z: number, w: number) { + public multiply4f (x: number, y: number, z: number, w: number): Vec4 { this.x *= x; this.y *= y; this.z *= z; @@ -817,7 +817,7 @@ export class Vec4 extends ValueType { * @zh 向量逐元素相除。将当前向量与指定分量的向量相除的结果赋值给当前向量。 * @param other specified vector */ - public divide (other: Vec4) { + public divide (other: Vec4): Vec4 { this.x /= other.x; this.y /= other.y; this.z /= other.z; @@ -833,7 +833,7 @@ export class Vec4 extends ValueType { * @param z The z value of specified vector * @param w The w value of specified vector */ - public divide4f (x: number, y: number, z: number, w: number) { + public divide4f (x: number, y: number, z: number, w: number): Vec4 { this.x /= x; this.y /= y; this.z /= z; @@ -845,7 +845,7 @@ export class Vec4 extends ValueType { * @en Sets each component of this vector with its negative value * @zh 将当前向量的各个分量取反 */ - public negative () { + public negative (): Vec4 { this.x = -this.x; this.y = -this.y; this.z = -this.z; @@ -859,7 +859,7 @@ export class Vec4 extends ValueType { * @param other specified vector * @returns 当前向量与指定向量点乘的结果。 */ - public dot (vector: Vec4) { + public dot (vector: Vec4): number { return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w; } @@ -870,7 +870,7 @@ export class Vec4 extends ValueType { * * @deprecated since v3.8 cross product only defined in 3D space, use [[Vec3.cross]] instead. */ - public cross (vector: Vec4) { + public cross (vector: Vec4): Vec4 { const { x: ax, y: ay, z: az } = this; const { x: bx, y: by, z: bz } = vector; @@ -885,7 +885,7 @@ export class Vec4 extends ValueType { * @zh 计算向量的长度(模)。 * @returns Length of vector */ - public length () { + public length (): number { const x = this.x; const y = this.y; const z = this.z; @@ -898,7 +898,7 @@ export class Vec4 extends ValueType { * @zh 计算向量长度(模)的平方。 * @returns the squared length of this vector */ - public lengthSqr () { + public lengthSqr (): number { const x = this.x; const y = this.y; const z = this.z; @@ -910,7 +910,7 @@ export class Vec4 extends ValueType { * @en Normalize the current vector. * @zh 将当前向量归一化 */ - public normalize () { + public normalize (): Vec4 { const x = this.x; const y = this.y; const z = this.z; @@ -930,7 +930,7 @@ export class Vec4 extends ValueType { * @en Scales the current vector by a scalar number. * @zh 向量数乘。 */ - public scale (scalar: number) { + public scale (scalar: number): Vec4 { this.x *= scalar; this.y *= scalar; this.z *= scalar; @@ -943,7 +943,7 @@ export class Vec4 extends ValueType { * @zh 应用四维矩阵变换到当前矩阵 * @param matrix matrix to transform with */ - public transformMat4 (matrix: Mat4) { + public transformMat4 (matrix: Mat4): Vec4 { const x = this.x; const y = this.y; const z = this.z; @@ -962,7 +962,7 @@ legacyCC.Vec4 = Vec4; export function v4 (other: Vec4): Vec4; export function v4 (x?: number, y?: number, z?: number, w?: number): Vec4; -export function v4 (x?: number | Vec4, y?: number, z?: number, w?: number) { +export function v4 (x?: number | Vec4, y?: number, z?: number, w?: number): Vec4 { return new Vec4(x as any, y, z, w); } diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index 83f7a815d38..ead1ef38d06 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -76,7 +76,7 @@ export class CachedArray extends ScalableContainer { * 向数组末尾添加一个元素。 * @param item @en The item to be added. @zh 被添加到数组的元素。 */ - public push (item: T) { + public push (item: T): void { this.array[this.length++] = item; } @@ -111,7 +111,7 @@ export class CachedArray extends ScalableContainer { * @zh * 清空数组所有元素。[[length]] 会被设为 0,但内部数组的实际长度不变 */ - public clear () { + public clear (): void { this.length = 0; } @@ -121,7 +121,7 @@ export class CachedArray extends ScalableContainer { * @zh * 销毁数组。[[length]] 会被设为 0,并且清空内部数组。 */ - public destroy () { + public destroy (): void { this.length = 0; this.array.length = 0; super.destroy(); @@ -131,7 +131,7 @@ export class CachedArray extends ScalableContainer { * @en Requests the removal of unused capacity. * @zh 尝试释放多余的内存。 */ - public tryShrink () { + public tryShrink (): void { if (this.array.length >> 2 > this.length) { this.array.length = Math.max(this._initSize, this.array.length >> 1); } @@ -144,7 +144,7 @@ export class CachedArray extends ScalableContainer { * @zh * 使用构造函数传入的 [[compareFn]] 排序所有现有元素。如果没有传入比较函数,将按照 ASCII 升序排序。 */ - public sort () { + public sort (): void { this.array.length = this.length; this.array.sort(this._compareFn); } @@ -156,7 +156,7 @@ export class CachedArray extends ScalableContainer { * 添加一个指定数组中的所有元素到当前数组末尾。 * @param array @en The given array to be appended. @zh 被添加的数组。 */ - public concat (array: T[]) { + public concat (array: T[]): void { for (let i = 0; i < array.length; ++i) { this.array[this.length++] = array[i]; } @@ -169,7 +169,7 @@ export class CachedArray extends ScalableContainer { * not effect. * @zh 希望被删除的索引。如果索引超出 [0, length),将没有效果。 */ - public fastRemove (idx: number) { + public fastRemove (idx: number): void { if (idx >= this.length || idx < 0) { return; } @@ -184,7 +184,7 @@ export class CachedArray extends ScalableContainer { * @returns The index to the first element that compares equal to val. If no elements match, returns -1. * @zh 第一个和 val 相等的元素的索引。如果没找到,将返回 -1。 */ - public indexOf (val: T) { + public indexOf (val: T): number { for (let i = 0, len = this.length; i < len; ++i) { if (this.array[i] === val) { return i; diff --git a/cocos/core/memop/pool.ts b/cocos/core/memop/pool.ts index 991becb542d..a0a6f505a68 100644 --- a/cocos/core/memop/pool.ts +++ b/cocos/core/memop/pool.ts @@ -86,7 +86,7 @@ export class Pool extends ScalableContainer { * @param obj @en The object to be put back into the pool. * @zh 放回对象池中的对象。 */ - public free (obj: T) { + public free (obj: T): void { this._freePool[++this._nextAvail] = obj; } @@ -96,7 +96,7 @@ export class Pool extends ScalableContainer { * @param objs @en An array of objects to be put back into the pool. * @zh 放回对象池中的一组对象。 */ - public freeArray (objs: T[]) { + public freeArray (objs: T[]): void { this._freePool.length = this._nextAvail + 1; Array.prototype.push.apply(this._freePool, objs); this._nextAvail += objs.length; @@ -106,7 +106,7 @@ export class Pool extends ScalableContainer { * @en Try to shrink the object pool to reduce memory usage. * @zh 尝试缩容对象池,以释放内存。 */ - public tryShrink () { + public tryShrink (): void { if (this._nextAvail >> 1 > this._elementsPerBatch) { if (this._dtor) { for (let i = this._nextAvail >> 1; i <= this._nextAvail; i++) { @@ -122,7 +122,7 @@ export class Pool extends ScalableContainer { * @en Destroy all elements and clear the pool. * @zh 释放对象池中所有资源并清空缓存池。 */ - public destroy () { + public destroy (): void { const dtor = arguments.length > 0 ? arguments[0] : null; if (dtor) { warnID(14100); } const readDtor = dtor || this._dtor; diff --git a/cocos/core/memop/recycle-pool.ts b/cocos/core/memop/recycle-pool.ts index da32ea8b98b..ec1aa1a83b7 100644 --- a/cocos/core/memop/recycle-pool.ts +++ b/cocos/core/memop/recycle-pool.ts @@ -65,7 +65,7 @@ export class RecyclePool extends ScalableContainer { * @en The length of the object pool. * @zh 对象池大小。 */ - get length () { + get length (): number { return this._count; } @@ -73,7 +73,7 @@ export class RecyclePool extends ScalableContainer { * @en The underlying array of all pool elements. * @zh 实际对象池数组。 */ - get data () { + get data (): T[] { return this._data; } @@ -81,7 +81,7 @@ export class RecyclePool extends ScalableContainer { * @en Resets the object pool. Only changes the length to 0. * @zh 清空对象池。目前仅仅会设置尺寸为 0。 */ - public reset () { + public reset (): void { this._count = 0; } @@ -90,7 +90,7 @@ export class RecyclePool extends ScalableContainer { * @zh 设置对象池大小,并填充新的元素。 * @param size @en The new size of the pool. @zh 新的对象池大小。 */ - public resize (size: number) { + public resize (size: number): void { if (size > this._data.length) { for (let i = this._data.length; i < size; ++i) { this._data[i] = this._fn(); @@ -102,7 +102,7 @@ export class RecyclePool extends ScalableContainer { * @en Expand the array size to 2 times the original size, and fills with new created elements. * @zh 扩充对象池容量,会自动扩充尺寸到原来的 2 倍,并填充新的元素。 */ - public add () { + public add (): T { if (this._count >= this._data.length) { this.resize(this._data.length << 1); } @@ -114,7 +114,7 @@ export class RecyclePool extends ScalableContainer { * @en Destroy the object pool. Please don't use it any more after it is destroyed. * @zh 销毁对象池。销毁后不能继续使用。 */ - public destroy () { + public destroy (): void { if (this._dtor) { for (let i = 0; i < this._data.length; i++) { this._dtor(this._data[i]); @@ -129,7 +129,7 @@ export class RecyclePool extends ScalableContainer { * @en Try to shrink the object pool to free memory. * @zh 尝试回收没用的对象,释放内存。 */ - public tryShrink () { + public tryShrink (): void { if (this._data.length >> 2 > this._count) { const length = Math.max(this._initSize, this._data.length >> 1); if (this._dtor) { @@ -146,7 +146,7 @@ export class RecyclePool extends ScalableContainer { * @zh 移除对象池中指定索引的元素,会减小池子尺寸。 * @param idx @en The index of the element to remove. @zh 被移除的元素的索引。 */ - public removeAt (idx: number) { + public removeAt (idx: number): void { if (idx >= this._count) { return; } diff --git a/cocos/core/memop/scalable-container.ts b/cocos/core/memop/scalable-container.ts index 44e9c3451d0..63a8ef89055 100644 --- a/cocos/core/memop/scalable-container.ts +++ b/cocos/core/memop/scalable-container.ts @@ -34,7 +34,7 @@ export abstract class ScalableContainer { abstract tryShrink (): void; - destroy () { + destroy (): void { scalableContainerManager.removeContainer(this); } } @@ -55,7 +55,7 @@ class ScalableContainerManager { * @en Add a ScalableContainer. Will add the same ScalableContainer instance once. * @param pool @en The ScalableContainer to add. */ - addContainer (pool: ScalableContainer) { + addContainer (pool: ScalableContainer): void { if (pool._poolHandle !== -1) return; pool._poolHandle = this._pools.length; this._pools.push(pool); @@ -65,7 +65,7 @@ class ScalableContainerManager { * @en Remove a ScalableContainer. * @param pool @en The ScalableContainer to remove. */ - removeContainer (pool: ScalableContainer) { + removeContainer (pool: ScalableContainer): void { if (pool._poolHandle === -1) return; this._pools[this._pools.length - 1]._poolHandle = pool._poolHandle; fastRemoveAt(this._pools, pool._poolHandle); @@ -75,7 +75,7 @@ class ScalableContainerManager { /** * @en Try to shrink all managed ScalableContainers. */ - tryShrink () { + tryShrink (): void { for (let i = 0; i < this._pools.length; i++) { this._pools[i].tryShrink(); } @@ -85,7 +85,7 @@ class ScalableContainerManager { * @en An update function invoked every frame. * @param dt @en Delta time of frame interval in secondes. */ - update (dt: number) { + update (dt: number): void { this._lastShrinkPassed += dt; if (this._lastShrinkPassed > this.shrinkTimeSpan) { this.tryShrink(); diff --git a/cocos/core/platform/debug.ts b/cocos/core/platform/debug.ts index 4a07d7a6a35..7d56a958265 100644 --- a/cocos/core/platform/debug.ts +++ b/cocos/core/platform/debug.ts @@ -40,7 +40,7 @@ let ccWarn = ccLog; let ccError = ccLog; -let ccAssert = (condition: any, message?: any, ...optionalParams: any[]) => { +let ccAssert = (condition: any, message?: any, ...optionalParams: any[]): void => { if (!condition) { console.log(`ASSERT: ${formatString(message, ...optionalParams)}`); } @@ -54,7 +54,7 @@ let ccDebug = ccLog; * @param message @zh 包含零个或多个需要替换的JavaScript字符串。@en JavaScript objects to replace substitution strings in msg. * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. */ -function formatString (message?: any, ...optionalParams: any[]) { +function formatString (message?: any, ...optionalParams: any[]): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return legacyCC.js.formatStr.apply(null, [message].concat(optionalParams)); } @@ -65,7 +65,7 @@ function formatString (message?: any, ...optionalParams: any[]) { * @param message @zh 包含零个或多个需要替换的JavaScript字符串。@en JavaScript objects to replace substitution strings in msg. * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. */ -export function log (message?: any, ...optionalParams: any[]) { +export function log (message?: any, ...optionalParams: any[]): void { return ccLog(message, ...optionalParams); } @@ -82,7 +82,7 @@ export function log (message?: any, ...optionalParams: any[]) { * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. * This gives you additional control over the format of the output. */ -export function warn (message?: any, ...optionalParams: any[]) { +export function warn (message?: any, ...optionalParams: any[]): void { return ccWarn(message, ...optionalParams); } @@ -99,7 +99,7 @@ export function warn (message?: any, ...optionalParams: any[]) { * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. * This gives you additional control over the format of the output. */ -export function error (message?: any, ...optionalParams: any[]) { +export function error (message?: any, ...optionalParams: any[]): void { return ccError(message, ...optionalParams); } @@ -122,16 +122,16 @@ export function assert (value: any, message?: string, ...optionalParams: any[]): * @zh 输出一条“调试”日志等级的消息。 * @param data @zh 输出的消息对象。 @en The output message object. */ -export function debug (...data: any[]) { +export function debug (...data: any[]): void { return ccDebug(...data); } /** * @engineInternal */ -export function _resetDebugSetting (mode: DebugMode) { +export function _resetDebugSetting (mode: DebugMode): void { // reset - ccLog = ccWarn = ccError = ccAssert = ccDebug = () => { + ccLog = ccWarn = ccError = ccAssert = ccDebug = (): void => { }; if (mode === DebugMode.NONE) { @@ -140,7 +140,7 @@ export function _resetDebugSetting (mode: DebugMode) { if (mode > DebugMode.ERROR) { // Log to web page. - const logToWebPage = (msg: string) => { + const logToWebPage = (msg: string): void => { if (!legacyCC.game.canvas) { return; } @@ -175,21 +175,21 @@ export function _resetDebugSetting (mode: DebugMode) { logList.scrollTop = logList.scrollHeight; }; - ccError = (message?: any, ...optionalParams: any[]) => { + ccError = (message?: any, ...optionalParams: any[]): void => { logToWebPage(`ERROR : ${formatString(message, ...optionalParams)}`); }; - ccAssert = (condition: any, message?: any, ...optionalParams: any[]) => { + ccAssert = (condition: any, message?: any, ...optionalParams: any[]): void => { if (!condition) { logToWebPage(`ASSERT: ${formatString(message, ...optionalParams)}`); } }; if (mode !== DebugMode.ERROR_FOR_WEB_PAGE) { - ccWarn = (message?: any, ...optionalParams: any[]) => { + ccWarn = (message?: any, ...optionalParams: any[]): void => { logToWebPage(`WARN : ${formatString(message, ...optionalParams)}`); }; } if (mode === DebugMode.INFO_FOR_WEB_PAGE) { - ccLog = (message?: any, ...optionalParams: any[]) => { + ccLog = (message?: any, ...optionalParams: any[]): void => { logToWebPage(formatString(message, ...optionalParams)); }; } @@ -208,9 +208,9 @@ export function _resetDebugSetting (mode: DebugMode) { // use bind to avoid pollute call stacks ccError = console.error.bind(console); } else { - ccError = JSB ? console.error : (message?: any, ...optionalParams: any[]) => console.error.apply(console, [message, ...optionalParams]); + ccError = JSB ? console.error : (message?: any, ...optionalParams: any[]): any => console.error.apply(console, [message, ...optionalParams]); } - ccAssert = (condition: any, message?: any, ...optionalParams: any[]) => { + ccAssert = (condition: any, message?: any, ...optionalParams: any[]): void => { if (!condition) { const errorText = formatString(message, ...optionalParams); if (DEV) { @@ -230,7 +230,7 @@ export function _resetDebugSetting (mode: DebugMode) { // use bind to avoid pollute call stacks ccWarn = console.warn.bind(console); } else { - ccWarn = JSB ? console.warn : (message?: any, ...optionalParams: any[]) => console.warn.apply(console, [message, ...optionalParams]); + ccWarn = JSB ? console.warn : (message?: any, ...optionalParams: any[]): any => console.warn.apply(console, [message, ...optionalParams]); } } @@ -243,19 +243,19 @@ export function _resetDebugSetting (mode: DebugMode) { // use bind to avoid pollute call stacks ccLog = console.log.bind(console); } else { - ccLog = (message?: any, ...optionalParams: any[]) => console.log.apply(console, [message, ...optionalParams]); + ccLog = (message?: any, ...optionalParams: any[]): any => console.log.apply(console, [message, ...optionalParams]); } } if (mode <= DebugMode.VERBOSE) { if (typeof console.debug === 'function') { const vendorDebug = console.debug.bind(console); - ccDebug = (...data: any[]) => vendorDebug(...data); + ccDebug = (...data: any[]): any => vendorDebug(...data); } } } -export function _throw (error_: any) { +export function _throw (error_: any): any { if (EDITOR) { return error(error_); } else { @@ -269,8 +269,8 @@ export function _throw (error_: any) { } } -function getTypedFormatter (type: 'Log' | 'Warning' | 'Error' | 'Assert') { - return (id: number, ...args: any[]) => { +function getTypedFormatter (type: 'Log' | 'Warning' | 'Error' | 'Assert'): (id: number, ...args: any[]) => any { + return (id: number, ...args: any[]): any => { const msg = DEBUG ? (debugInfos[id] || 'unknown id') : `${type} ${id}, please go to ${ERROR_MAP_URL}#${id} to see details.`; if (args.length === 0) { return msg; @@ -281,22 +281,22 @@ function getTypedFormatter (type: 'Log' | 'Warning' | 'Error' | 'Assert') { } const logFormatter = getTypedFormatter('Log'); -export function logID (id: number, ...optionalParams: any[]) { +export function logID (id: number, ...optionalParams: any[]): void { log(logFormatter(id, ...optionalParams)); } const warnFormatter = getTypedFormatter('Warning'); -export function warnID (id: number, ...optionalParams: any[]) { +export function warnID (id: number, ...optionalParams: any[]): void { warn(warnFormatter(id, ...optionalParams)); } const errorFormatter = getTypedFormatter('Error'); -export function errorID (id: number, ...optionalParams: any[]) { +export function errorID (id: number, ...optionalParams: any[]): void { error(errorFormatter(id, ...optionalParams)); } const assertFormatter = getTypedFormatter('Assert'); -export function assertID (condition: any, id: number, ...optionalParams: any[]) { +export function assertID (condition: any, id: number, ...optionalParams: any[]): void { if (condition) { return; } @@ -383,7 +383,7 @@ export function isDisplayStats (): boolean { * @zh 设置是否在左下角显示 FPS 和部分调试。 * @deprecated @zh 从v3.6开始不再支持,请使用 profiler.showStats。@en Since v3.6, Please use profiler.showStats instead. */ -export function setDisplayStats (displayStats: boolean) { +export function setDisplayStats (displayStats: boolean): void { if (legacyCC.profiler) { displayStats ? legacyCC.profiler.showStats() : legacyCC.profiler.hideStats(); } diff --git a/cocos/core/platform/screen.ts b/cocos/core/platform/screen.ts index 71a5e798268..0cfb92be0e6 100644 --- a/cocos/core/platform/screen.ts +++ b/cocos/core/platform/screen.ts @@ -39,11 +39,11 @@ class Screen { /** * @internal */ - public init () { + public init (): void { const exactFitScreen = settings.querySettings(Settings.Category.SCREEN, 'exactFitScreen') ?? true; const orientation = settings.querySettings(Settings.Category.SCREEN, 'orientation') ?? 'auto'; const isHeadlessMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode') === 3; - screenAdapter.init({ exactFitScreen, configOrientation: orientation, isHeadlessMode }, () => { + screenAdapter.init({ exactFitScreen, configOrientation: orientation, isHeadlessMode }, (): void => { const director = legacyCC.director; if (!director.root?.pipeline) { warnID(1220); @@ -60,7 +60,7 @@ class Screen { * @zh 当前显示设备的物理像素分辨率与 CSS 像素分辨率之比。 * 注意:出于性能考虑,引擎在一些平台会限制 DPR 的最高值,这个属性返回的是引擎限制后的 DPR。 */ - public get devicePixelRatio () { + public get devicePixelRatio (): number { return screenAdapter.devicePixelRatio; } @@ -90,7 +90,7 @@ class Screen { * * @readonly */ - public get resolution () { + public get resolution (): Size { return screenAdapter.resolution; } @@ -154,9 +154,9 @@ class Screen { if (arguments.length > 0) { warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise'); } - return screenAdapter.requestFullScreen().then(() => { + return screenAdapter.requestFullScreen().then((): void => { onFullScreenChange?.call(document); // this case is only used on Web platforms, which is deprecated since v3.3.0 - }).catch((err) => { + }).catch((err): void => { console.error(err); onFullScreenError?.call(document); // this case is only used on Web platforms, which is deprecated since v3.3.0 }); @@ -179,15 +179,15 @@ class Screen { * * @deprecated since v3.3, please use screen.requestFullScreen() instead. */ - public autoFullScreen (element: HTMLElement, onFullScreenChange: (this: Document, ev: any) => any) { - this.requestFullScreen(element, onFullScreenChange)?.catch((e) => {}); + public autoFullScreen (element: HTMLElement, onFullScreenChange: (this: Document, ev: any) => any): void { + this.requestFullScreen(element, onFullScreenChange)?.catch((e): void => {}); } /** * @param element * @deprecated since v3.3 */ - public disableAutoFullScreen (element) { + public disableAutoFullScreen (element): void { // DO NOTHING } @@ -198,7 +198,7 @@ class Screen { * @zh * 注册screen事件回调。 */ - public on (type: PalScreenEvent, callback: any, target?: any) { + public on (type: PalScreenEvent, callback: any, target?: any): void { screenAdapter.on(type, callback, target); } @@ -208,7 +208,7 @@ class Screen { * @zh * 注册单次的screen事件回调。 */ - public once (type: PalScreenEvent, callback?: any, target?: any) { + public once (type: PalScreenEvent, callback?: any, target?: any): void { screenAdapter.once(type, callback, target); } @@ -218,7 +218,7 @@ class Screen { * @zh * 取消注册screen事件回调。 */ - public off (type: PalScreenEvent, callback?: any, target?: any) { + public off (type: PalScreenEvent, callback?: any, target?: any): void { screenAdapter.off(type, callback, target); } } diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index 299b9905d09..8c475705488 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -239,7 +239,7 @@ export const sys = { * @en Forces the garbage collection, only available in native platforms. * @zh 强制进行 JS 内存垃圾回收,尽在原生平台有效。 */ - garbageCollect () { + garbageCollect (): void { systemInfo.triggerGC(); }, @@ -268,7 +268,7 @@ export const sys = { * @en Dump systemInfo informations. * @zh 在控制台打印当前的主要系统信息。 */ - dump () { + dump (): void { let str = ''; str += `isMobile : ${this.isMobile}\r\n`; str += `language : ${this.language}\r\n`; @@ -292,7 +292,7 @@ export const sys = { * @zh 尝试打开一个 web 页面,并非在所有平台都有效。 * @param url @zh 访问的链接。 @en Visited links. */ - openURL (url) { + openURL (url): void { systemInfo.openURL(url); }, @@ -301,8 +301,8 @@ export const sys = { */ init (): Promise { return Promise.resolve() - .then(() => systemInfo.init()) - .then(() => { + .then((): any => systemInfo.init()) + .then((): void => { try { let localStorage: Storage | null = sys.localStorage = window.localStorage; localStorage.setItem('storage', ''); @@ -336,7 +336,7 @@ export const sys = { * @en Get the current time in milliseconds. * @zh 获取当前时间(毫秒为单位)。 */ - now () { + now (): number { return systemInfo.now(); }, @@ -345,7 +345,7 @@ export const sys = { * @zh 重启JS虚拟机,仅仅在原生平台有效。 * @private */ - restartVM () { + restartVM (): void { systemInfo.restartJSVM(); }, @@ -360,7 +360,7 @@ export const sys = { * @method getSafeAreaRect * @return {Rect} */ - getSafeAreaRect () { + getSafeAreaRect (): Rect { const locView = legacyCC.view; const edge = screenAdapter.safeAreaEdge; const windowSize = screenAdapter.windowSize; diff --git a/cocos/core/platform/visible-rect.ts b/cocos/core/platform/visible-rect.ts index dc56a446dbe..57e4b5dfb0e 100644 --- a/cocos/core/platform/visible-rect.ts +++ b/cocos/core/platform/visible-rect.ts @@ -105,7 +105,7 @@ export const visibleRect = { * @param visibleRect_ @zh 当前视图的实际可见区域。@en The actual visible area of the current view. * @NOTE: @zh 必须是有效的区域。例如区域大小不能为负数。@en It must be a valid region. For example, the region size cannot be negative. */ - init (visibleRect_: Rect) { + init (visibleRect_: Rect): void { const w = this.width = visibleRect_.width; const h = this.height = visibleRect_.height; const l = visibleRect_.x; diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index 479c47c378a..253de0f9455 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -45,7 +45,7 @@ export interface ISchedulable { * @class ListEntry */ class ListEntry { - public static get = (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean) => { + public static get = (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean): ListEntry => { let result = ListEntry._listEntries.pop(); if (result) { result.target = target; @@ -58,7 +58,7 @@ class ListEntry { return result; } - public static put = (entry: ListEntry | any) => { + public static put = (entry: ListEntry | any): void => { if (ListEntry._listEntries.length < MAX_POOL_SIZE) { entry.target = null; ListEntry._listEntries.push(entry); @@ -106,7 +106,7 @@ class ListEntry { * @param callback @en The callback function. @zh 所回调的函数。 */ class HashUpdateEntry { - public static get = (list: any, entry: ListEntry, target: ISchedulable, callback: any) => { + public static get = (list: any, entry: ListEntry, target: ISchedulable, callback: any): HashUpdateEntry => { let result = HashUpdateEntry._hashUpdateEntries.pop(); if (result) { result.list = list; @@ -119,7 +119,7 @@ class HashUpdateEntry { return result; } - public static put = (entry: HashUpdateEntry | any) => { + public static put = (entry: HashUpdateEntry | any): void => { if (HashUpdateEntry._hashUpdateEntries.length < MAX_POOL_SIZE) { entry.list = entry.entry = entry.target = entry.callback = null; HashUpdateEntry._hashUpdateEntries.push(entry); @@ -152,7 +152,7 @@ class HashUpdateEntry { * @param paused */ 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): HashTimerEntry => { let result = HashTimerEntry._hashTimerEntries.pop(); if (result) { result.timers = timers; @@ -167,7 +167,7 @@ class HashTimerEntry { return result; } - public static put = (entry: HashTimerEntry | any) => { + public static put = (entry: HashTimerEntry | any): void => { if (HashTimerEntry._hashTimerEntries.length < MAX_POOL_SIZE) { entry.timers = entry.target = entry.currentTimer = null; HashTimerEntry._hashTimerEntries.push(entry); @@ -198,8 +198,8 @@ class HashTimerEntry { */ class CallbackTimer { public static _timers: CallbackTimer[] = []; - public static get = () => CallbackTimer._timers.pop() || new CallbackTimer() - public static put = (timer: CallbackTimer | any) => { + public static get = (): CallbackTimer => CallbackTimer._timers.pop() || new CallbackTimer() + public static put = (timer: CallbackTimer | any): void => { if (CallbackTimer._timers.length < MAX_POOL_SIZE && !timer._lock) { timer._scheduler = timer._target = timer._callback = null; CallbackTimer._timers.push(timer); @@ -232,7 +232,7 @@ class CallbackTimer { this._target = null; } - public initWithCallback (scheduler: any, callback: any, target: ISchedulable, seconds: number, repeat: number, delay: number) { + public initWithCallback (scheduler: any, callback: any, target: ISchedulable, seconds: number, repeat: number, delay: number): boolean { this._lock = false; this._scheduler = scheduler; this._target = target; @@ -253,14 +253,14 @@ class CallbackTimer { * @en returns interval of timer in seconds. * @zh 返回计时器的时间间隔, 以秒为单位。 */ - public getInterval () { + public getInterval (): number { return this._interval; } /** * @en Set interval in seconds. * @zh 以秒为单位设置时间间隔。 */ - public setInterval (interval) { + public setInterval (interval): void { this._interval = interval; } @@ -271,7 +271,7 @@ class CallbackTimer { * @en delta time. The unit is seconds. * @zh 更新间隔时间, 单位是秒。 */ - public update (dt: number) { + public update (dt: number): void { if (this._elapsed === -1) { this._elapsed = 0; this._timesExecuted = 0; @@ -305,11 +305,11 @@ class CallbackTimer { } } - public getCallback () { + public getCallback (): ((dt?: number | undefined) => void) | undefined { return this._callback; } - public trigger () { + public trigger (): void { if (this._target && this._callback) { this._lock = true; this._callback.call(this._target, this._elapsed); @@ -317,7 +317,7 @@ class CallbackTimer { } } - public cancel () { + public cancel (): void { // override this._scheduler.unschedule(this._callback, this._target); } @@ -365,7 +365,7 @@ export class Scheduler extends System { * @en The target to enable, which type is ISchedulable. * @zh 所作用的对象。类型为ISchedulable。 */ - public static enableForTarget (target: ISchedulable) { + public static enableForTarget (target: ISchedulable): void { let found = false; if (target.uuid) { found = true; @@ -410,7 +410,7 @@ export class Scheduler extends System { * 注意:它影响该 Scheduler 下管理的所有定时器。 * @param timeScale */ - public setTimeScale (timeScale) { + public setTimeScale (timeScale): void { this._timeScale = timeScale; } @@ -429,7 +429,7 @@ export class Scheduler extends System { * @en delta time. The unit is seconds. * @zh 更新间隔时间, 单位是秒。 */ - public update (dt) { + public update (dt): void { this._updateHashLocked = true; if (this._timeScale !== 1) { dt *= this._timeScale; @@ -544,7 +544,7 @@ export class Scheduler extends System { * @zh 如果 paused 值为 true,那么直到 resume 被调用才开始计时。 * @param paused */ - public schedule (callback: (dt?: number) => void, target: ISchedulable, interval: number, repeat?: number, delay?: number, paused?: boolean) { + public schedule (callback: (dt?: number) => void, target: ISchedulable, interval: number, repeat?: number, delay?: number, paused?: boolean): void { if (typeof callback !== 'function') { warnID(1514); const tmp = callback; @@ -615,7 +615,7 @@ export class Scheduler extends System { * @param paused * @en Whether is paused. @zh 是否被暂停。 */ - public scheduleUpdate (target: ISchedulable, priority: number, paused: boolean) { + public scheduleUpdate (target: ISchedulable, priority: number, paused: boolean): void { const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); @@ -668,7 +668,7 @@ export class Scheduler extends System { * @param callback @en The callback to be unscheduled @zh 被取消调度的回调。 * @param target @en The target bound to the callback. @zh 回调所绑定的目标对象。 */ - public unschedule (callback, target: ISchedulable) { + public unschedule (callback, target: ISchedulable): void { // callback, target // explicity handle nil arguments when removing an object @@ -715,7 +715,7 @@ export class Scheduler extends System { * @zh 取消指定对象的 update 定时器。 * @param target The target to be unscheduled. */ - public unscheduleUpdate (target: ISchedulable) { + public unscheduleUpdate (target: ISchedulable): void { if (!target) { return; } @@ -742,7 +742,7 @@ export class Scheduler extends System { * @zh 取消指定对象的所有定时器,包括 update 定时器。 * @param target The target to be unscheduled. */ - public unscheduleAllForTarget (target) { + public unscheduleAllForTarget (target): void { // explicit nullptr handling if (!target) { return; @@ -785,7 +785,7 @@ export class Scheduler extends System { * 取消所有对象的所有定时器,包括系统定时器。 * 不要调用此函数,除非你确定你在做什么。 */ - public unscheduleAll () { + public unscheduleAll (): void { this.unscheduleAllWithMinPriority(System.Priority.SCHEDULER); } @@ -802,7 +802,7 @@ export class Scheduler extends System { * @zh 要取消调度的选择器的最低优先级。 * 这意味着,所有优先级高于 minPriority 的选择器将被取消调度。 */ - public unscheduleAllWithMinPriority (minPriority: number) { + public unscheduleAllWithMinPriority (minPriority: number): void { // Custom Selectors let i; let element; @@ -900,7 +900,7 @@ export class Scheduler extends System { * 暂停所有对象的所有定时器。 * 不要调用这个方法,除非你知道你正在做什么。 */ - public pauseAllTargets () { + public pauseAllTargets (): ISchedulable[] { return this.pauseAllTargetsWithMinPriority(System.Priority.SCHEDULER); } @@ -913,7 +913,7 @@ export class Scheduler extends System { * 你应该只暂停优先级的值大于 PRIORITY_NON_SYSTEM_MIN 的定时器。 * @param minPriority @en the minimum priority. @zn 最小优先级。 */ - public pauseAllTargetsWithMinPriority (minPriority: number) { + public pauseAllTargetsWithMinPriority (minPriority: number): ISchedulable[] { const idsWithSelectors: ISchedulable[] = []; let element: HashTimerEntry; @@ -974,7 +974,7 @@ export class Scheduler extends System { * 这个函数是 pauseAllCallbacks 的逆操作。 * @param targetsToResume */ - public resumeTargets (targetsToResume) { + public resumeTargets (targetsToResume): void { if (!targetsToResume) { return; } @@ -995,7 +995,7 @@ export class Scheduler extends System { * 如果指定的对象没有定时器,什么也不会发生。 * @param target */ - public pauseTarget (target: ISchedulable) { + public pauseTarget (target: ISchedulable): void { assertID(target, 1503); const targetId = target.uuid || target.id; if (!targetId) { @@ -1027,7 +1027,7 @@ export class Scheduler extends System { * 如果指定的对象没有定时器,什么也不会发生。 * @param target */ - public resumeTarget (target: ISchedulable) { + public resumeTarget (target: ISchedulable): void { assertID(target, 1504); const targetId = target.uuid || target.id; if (!targetId) { @@ -1053,7 +1053,7 @@ export class Scheduler extends System { * @zh 返回指定对象的定时器是否处于暂停状态。 * @param target */ - public isTargetPaused (target: ISchedulable) { + public isTargetPaused (target: ISchedulable): boolean { assertID(target, 1505); const targetId = target.uuid || target.id; if (!targetId) { @@ -1074,7 +1074,7 @@ export class Scheduler extends System { } // -----------------------private method---------------------- - private _removeHashElement (element) { + private _removeHashElement (element): void { const targetId = element.target.uuid || element.target.id; delete this._hashForTimers[targetId]; const arr = this._arrayForTimers; @@ -1087,7 +1087,7 @@ export class Scheduler extends System { HashTimerEntry.put(element); } - private _removeUpdateFromHash (entry) { + private _removeUpdateFromHash (entry): void { const targetId = entry.target.uuid || entry.target.id; const element = this._hashForUpdates[targetId]; if (element) { @@ -1107,7 +1107,7 @@ export class Scheduler extends System { } } - private _priorityIn (ppList, listElement, priority) { + private _priorityIn (ppList, listElement, priority): void { for (let i = 0; i < ppList.length; i++) { if (priority < ppList[i].priority) { ppList.splice(i, 0, listElement); @@ -1117,7 +1117,7 @@ export class Scheduler extends System { ppList.push(listElement); } - private _appendIn (ppList, listElement) { + private _appendIn (ppList, listElement): void { ppList.push(listElement); } } diff --git a/cocos/core/settings.ts b/cocos/core/settings.ts index 0b9dcada283..91cd9eaa09d 100644 --- a/cocos/core/settings.ts +++ b/cocos/core/settings.ts @@ -77,21 +77,21 @@ export class Settings { if (!path) return Promise.resolve(); if (window.oh) { - return new Promise((resolve, reject) => { + return new Promise((resolve, reject): void => { // TODO: to support a virtual module of settings. // For now, we use a system module context to dynamically import the relative path of module. const settingsModule = '../settings.js'; - import(settingsModule).then((res) => { + import(settingsModule).then((res): void => { this._settings = res.default; resolve(); - }).catch((e) => reject(e)); + }).catch((e): void => reject(e)); }); } - return new Promise((resolve, reject) => { + return new Promise((resolve, reject): void => { if (!HTML5 && !path.startsWith('http')) { // TODO: readJsonSync not working on Taobao IDE if (TAOBAO || TAOBAO_MINIGAME) { - globalThis.fsUtils.readJson(path, (err, result) => { + globalThis.fsUtils.readJson(path, (err, result): void => { if (err) { reject(err); return; @@ -112,11 +112,11 @@ export class Settings { const xhr = new XMLHttpRequest(); xhr.open('GET', path); xhr.responseType = 'text'; - xhr.onload = () => { + xhr.onload = (): void => { this._settings = JSON.parse(xhr.response); resolve(); }; - xhr.onerror = () => { + xhr.onerror = (): void => { reject(new Error('request settings failed!')); }; xhr.send(null); @@ -142,7 +142,7 @@ export class Settings { * console.log(settings.querySettings(Settings.Category.ASSETS, 'server')); // print http://www.test.com * ``` */ - overrideSettings (category: Category | string, name: string, value: T) { + overrideSettings (category: Category | string, name: string, value: T): void { if (!(category in this._override)) { this._override[category] = {}; } diff --git a/cocos/core/system.ts b/cocos/core/system.ts index 741ed750a91..bda71b2c35d 100644 --- a/cocos/core/system.ts +++ b/cocos/core/system.ts @@ -61,7 +61,7 @@ export class System implements ISchedulable { * @param a System a * @param b System b */ - public static sortByPriority (a:System, b:System) { + public static sortByPriority (a:System, b:System): number { if (a._priority < b._priority) { return 1; } else if (a._priority > b.priority) { @@ -75,19 +75,19 @@ export class System implements ISchedulable { * @en Init the system, will be invoked by [[Director]] when registered, should be implemented if needed. * @zh 系统初始化函数,会在注册时被 [[Director]] 调用,如果需要的话应该由子类实现 */ - init () {} + init (): void {} /** * @en Update function of the system, it will be invoked between all components update phase and late update phase. * @zh 系统的帧更新函数,它会在所有组件的 update 和 lateUpdate 之间被调用 * @param dt Delta time after the last frame */ - update (dt: number) {} + update (dt: number): void {} /** * @en Post update function of the system, it will be invoked after all components late update phase and before the rendering process. * @zh 系统的帧后处理函数,它会在所有组件的 lateUpdate 之后以及渲染之前被调用 * @param dt Delta time after the last frame */ - postUpdate (dt: number) {} + postUpdate (dt: number): void {} - destroy () {} + destroy (): void {} } diff --git a/cocos/core/utils/array.ts b/cocos/core/utils/array.ts index 01d7c75cbfb..c01f4605919 100644 --- a/cocos/core/utils/array.ts +++ b/cocos/core/utils/array.ts @@ -34,7 +34,7 @@ export { default as MutableForwardIterator } from './mutable-forward-iterator'; * @param array @zh 被操作的数组。@en The array to be operated. * @param index @zh 待移除元素的索引。@en The index of the element to be removed. */ -export function removeAt (array: T[], index: number) { +export function removeAt (array: T[], index: number): void { array.splice(index, 1); } @@ -48,7 +48,7 @@ export function removeAt (array: T[], index: number) { * @param array @zh 被操作的数组。@en The array to be operated. * @param index @zh 待移除元素的索引。@en The index of the element to be removed. */ -export function fastRemoveAt (array: T[], index: number) { +export function fastRemoveAt (array: T[], index: number): void { const length = array.length; if (index < 0 || index >= length) { return; @@ -66,7 +66,7 @@ export function fastRemoveAt (array: T[], index: number) { * @param array @zh 被操作的数组。@en The array to be operated. * @param value @zh 待移除元素。@en The value to be removed. */ -export function remove (array: T[], value: T) { +export function remove (array: T[], value: T): boolean { const index = array.indexOf(value); if (index >= 0) { removeAt(array, index); @@ -87,7 +87,7 @@ export function remove (array: T[], value: T) { * @param array @zh 被操作的数组。@en The array to be operated. * @param value @zh 待移除元素。@en The value to be removed. */ -export function fastRemove (array: T[], value: T) { +export function fastRemove (array: T[], value: T): void { const index = array.indexOf(value); if (index >= 0) { array[index] = array[array.length - 1]; @@ -103,7 +103,7 @@ export function fastRemove (array: T[], value: T) { * @param array @zh 被操作的数组。@en The array to be operated. * @param predicate @zh 一元谓词,如果要元素的话,需要返回 true。@en unary predicate which returns true if the element should be removed. */ -export function removeIf (array: T[], predicate: (value: T) => boolean) { +export function removeIf (array: T[], predicate: (value: T) => boolean): T | undefined { const index = array.findIndex(predicate); if (index >= 0) { const value = array[index]; @@ -144,7 +144,7 @@ export function verifyType (array: any[], type: T): array is * @param removals @zh 所有待移除的元素。此数组的每个元素所对应的首个源数组的元素都会被移除。 * @en The values to be removed. If a value appears multiple times in the array, only the first math element will be removed. */ -export function removeArray (array: T[], removals: T[]) { +export function removeArray (array: T[], removals: T[]): void { for (let i = 0, l = removals.length; i < l; i++) { remove(array, removals[i]); } @@ -160,7 +160,7 @@ export function removeArray (array: T[], removals: T[]) { * @param index @zh 插入的索引。@en The index to insert at. * @returns @zh 传入的 `array`。@en The passed in `array`. */ -export function appendObjectsAt (array: T[], objects: T[], index: number) { +export function appendObjectsAt (array: T[], objects: T[], index: number): T[] { array.splice.apply(array, [index, 0, ...objects]); return array; } @@ -174,7 +174,7 @@ export function appendObjectsAt (array: T[], objects: T[], index: number) { * @param value @zh 用来查询的值 @en The value used to check for. * @returns @zh true 如果包含该元素,否则返回 false。@en true if contains the value, false else. */ -export function contains (array: T[], value: T) { +export function contains (array: T[], value: T): boolean { return array.indexOf(value) >= 0; } @@ -186,7 +186,7 @@ export function contains (array: T[], value: T) { * @param array @zh 用来拷贝的数组。@en The array to be copied from. * @returns @zh 数组的副本。@en A new array has the same values as `array`. */ -export function copy (array: T[]) { +export function copy (array: T[]): T[] { const len = array.length; const cloned = new Array(len); for (let i = 0; i < len; i += 1) { diff --git a/cocos/core/utils/coordinates-converts-utils.ts b/cocos/core/utils/coordinates-converts-utils.ts index 0ccd3fce0cc..55479ef3612 100644 --- a/cocos/core/utils/coordinates-converts-utils.ts +++ b/cocos/core/utils/coordinates-converts-utils.ts @@ -41,7 +41,7 @@ const _vec3 = new Vec3(); * @param uiNode @en The UI node. @zh UI 节点。 * @param out @en The output local position in UI @zh 返回 UI 节点局部坐标。 */ -export function WorldNode3DToLocalNodeUI (mainCamera: Camera, wpos: Vec3, uiNode: Node, out?: Vec3) { +export function WorldNode3DToLocalNodeUI (mainCamera: Camera, wpos: Vec3, uiNode: Node, out?: Vec3): Vec3 { if (!out) { out = new Vec3(); } @@ -62,7 +62,7 @@ export function WorldNode3DToLocalNodeUI (mainCamera: Camera, wpos: Vec3, uiNode * @param wpos @en The world space location. @zh 世界空间位置。 * @param out @en The output world position in UI @zh 返回 UI 空间世界坐标。 */ -export function WorldNode3DToWorldNodeUI (mainCamera: Camera, wpos: Vec3, out?: Vec3) { +export function WorldNode3DToWorldNodeUI (mainCamera: Camera, wpos: Vec3, out?: Vec3): Vec3 { if (!out) { out = new Vec3(); } @@ -91,7 +91,7 @@ replaceProperty(legacyCC.pipelineUtils, 'cc.pipelineUtils', [ name: 'WorldNode3DToLocalNodeUI', newName: 'convertToUINode', targetName: 'cc.Camera.prototype', - customFunction (...args: any[]) { + customFunction (...args: any[]): any { const camera = args[0] as Camera; const out = args[3] || _vec3; camera.convertToUINode(args[1], args[2], out); diff --git a/cocos/core/utils/decode-uuid.ts b/cocos/core/utils/decode-uuid.ts index 0b270679e63..d9cf49989f9 100644 --- a/cocos/core/utils/decode-uuid.ts +++ b/cocos/core/utils/decode-uuid.ts @@ -33,7 +33,7 @@ const HexChars = '0123456789abcdef'.split(''); const _t = ['', '', '', '']; const UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t); -const Indices = UuidTemplate.map((x, i) => (x === '-' ? NaN : i)).filter(Number.isFinite); +const Indices = UuidTemplate.map((x, i): number => (x === '-' ? NaN : i)).filter(Number.isFinite); /** * @en @@ -51,7 +51,7 @@ const Indices = UuidTemplate.map((x, i) => (x === '-' ? NaN : i)).filter(Number. * const originalUuid = decodeUuid(uuid); // fc991dd7-0033-4b80-9d41-c8a86a702e59 * ``` */ -export default function decodeUuid (base64: string) { +export default function decodeUuid (base64: string): string { const strs = base64.split(separator); const uuid = strs[0]; if (uuid.length !== 22) { diff --git a/cocos/core/utils/id-generator.ts b/cocos/core/utils/id-generator.ts index 07761d7e6aa..9ce23f757b8 100644 --- a/cocos/core/utils/id-generator.ts +++ b/cocos/core/utils/id-generator.ts @@ -76,7 +76,7 @@ export class IDGenerator { * @returns @en The unique id. It has the form `prefix+id`, for example `scene55`, `scene` is `prefix`, `55` is `id`. * @zh 唯一的 id。它的形式是 `prefix+id`,比如 `scene55`,`scene` 是 prefix,`55` 是 `id`。 */ - public getNewId () { + public getNewId (): string { if (EDITOR && (this.prefix === 'Node.' || this.prefix === 'Comp.')) { return EditorExtends.UuidUtils.uuid(); } diff --git a/cocos/core/utils/internal.ts b/cocos/core/utils/internal.ts index 5d89da84be2..4835fdeacc0 100644 --- a/cocos/core/utils/internal.ts +++ b/cocos/core/utils/internal.ts @@ -84,20 +84,20 @@ export function renameObjectProperty> ( const result = {} as T; if (typeof originalPropertyKey === 'symbol') { - (Object.entries(object)).forEach(([k, v]) => { + (Object.entries(object)).forEach(([k, v]): void => { result[k as keyof T] = v; }); - Object.getOwnPropertySymbols(object).forEach((k) => { + Object.getOwnPropertySymbols(object).forEach((k): void => { if (!propertyIsEnumerable.call(object, k)) { return; } result[k === originalPropertyKey ? newPropertyKey : k as keyof T] = object[k as keyof T]; }); } else { - Object.entries(object).forEach(([k, v]) => { + Object.entries(object).forEach(([k, v]): void => { result[k === originalPropertyKey ? newPropertyKey : k as keyof T] = v; }); - Object.getOwnPropertySymbols(object).forEach((k) => { + Object.getOwnPropertySymbols(object).forEach((k): void => { if (!propertyIsEnumerable.call(object, k)) { return; } @@ -176,7 +176,7 @@ export const createInstanceofProxy = ((): CreateInstanceofProxySignature => { // To guarantee we won't suffer from platform issue, we do check here. let isSymbolHasInstanceAvailable = false; try { - class Array1 { static [Symbol.hasInstance] (instance: unknown) { return Array.isArray(instance); } } + class Array1 { static [Symbol.hasInstance] (instance: unknown): boolean { return Array.isArray(instance); } } isSymbolHasInstanceAvailable = ([] instanceof Array1); } catch { isSymbolHasInstanceAvailable = false; @@ -184,17 +184,17 @@ export const createInstanceofProxy = ((): CreateInstanceofProxySignature => { // If `Symbol.hasInstance` is not available, fallback to return the original constructor. if (!isSymbolHasInstanceAvailable) { - return (constructor) => constructor; + return (constructor): any => constructor; } // Otherwise, proxy it. - return (constructor) => { - function InstanceOfProxy () { + return (constructor): any => { + function InstanceOfProxy (): void { throw new Error(`This function can not be called as a constructor.`); } Object.defineProperty(InstanceOfProxy, Symbol.hasInstance, { - value (instance: unknown) { + value (instance: unknown): boolean { return instance instanceof constructor; }, }); diff --git a/cocos/core/utils/js-typed.ts b/cocos/core/utils/js-typed.ts index 69ef0bf5dea..f3eef862203 100644 --- a/cocos/core/utils/js-typed.ts +++ b/cocos/core/utils/js-typed.ts @@ -49,7 +49,7 @@ const classIdTag = '__cid__'; * isNumber(obj); // returns true * ``` */ -export function isNumber (object: any) { +export function isNumber (object: any): boolean { return typeof object === 'number' || object instanceof Number; } @@ -70,7 +70,7 @@ export function isNumber (object: any) { * isString(obj); // returns true * ``` */ -export function isString (object: any) { +export function isString (object: any): boolean { return typeof object === 'string' || object instanceof String; } @@ -84,7 +84,7 @@ export function isString (object: any) { * @returns @en True if it is not an empty object or not an object, false else. * @zh 如果不是空对象或者不是一个对象,返回 `true`;否则返回 `false`。 */ -export function isEmptyObject (obj: any) { +export function isEmptyObject (obj: any): boolean { for (const key in obj) { return false; } @@ -102,14 +102,14 @@ export function isEmptyObject (obj: any) { * @param writable @en If the property is writable. @zh 属性是否可写。 * @param enumerable @en If the property is enumerable. @zh 属性是否可枚举。 */ -export const value = (() => { +export const value = ((): (object: Record, propertyName: string, value_: any, writable?: boolean, enumerable?: boolean) => void => { const descriptor: PropertyDescriptor = { value: undefined, enumerable: false, writable: false, configurable: true, }; - return (object: Record, propertyName: string, value_: any, writable?: boolean, enumerable?: boolean) => { + return (object: Record, propertyName: string, value_: any, writable?: boolean, enumerable?: boolean): void => { descriptor.value = value_; descriptor.writable = writable; descriptor.enumerable = enumerable; @@ -128,13 +128,13 @@ export const value = (() => { * @param enumerable @en If the property is enumerable. @zh 属性是否可列举。 * @param configurable @en If the property is configurable. @zh 属性是否可配置。 */ -export const getset = (() => { +export const getset = ((): (object: Record, propertyName: string, getter: Getter, setter?: Setter | boolean, enumerable?: boolean, configurable?: boolean) => void => { const descriptor: PropertyDescriptor = { get: undefined, set: undefined, enumerable: false, }; - return (object: Record, propertyName: string, getter: Getter, setter?: Setter | boolean, enumerable = false, configurable = false) => { + return (object: Record, propertyName: string, getter: Getter, setter?: Setter | boolean, enumerable = false, configurable = false): void => { if (typeof setter === 'boolean') { console.log('Set `setter` to boolean is deprecated. Please don not use like this again.'); enumerable = setter; @@ -160,13 +160,13 @@ export const getset = (() => { * @param enumerable @en If the property is enumerable. @zh 属性是否可列举。 * @param configurable @en If the property is configurable. @zh 属性是否可配置。 */ -export const get = (() => { +export const get = ((): (object: Record, propertyName: string, getter: Getter, enumerable?: boolean, configurable?: boolean) => void => { const descriptor: PropertyDescriptor = { get: undefined, enumerable: false, configurable: false, }; - return (object: Record, propertyName: string, getter: Getter, enumerable?: boolean, configurable?: boolean) => { + return (object: Record, propertyName: string, getter: Getter, enumerable?: boolean, configurable?: boolean): void => { descriptor.get = getter; descriptor.enumerable = enumerable; descriptor.configurable = configurable; @@ -184,13 +184,13 @@ export const get = (() => { * @param enumerable @en If the property is enumerable. @zh 属性是否可列举。 * @param configurable @en If the property is configurable. @zh 属性是否可配置。 */ -export const set = (() => { +export const set = ((): (object: Record, propertyName: string, setter: Setter, enumerable?: boolean, configurable?: boolean) => void => { const descriptor: PropertyDescriptor = { set: undefined, enumerable: false, configurable: false, }; - return (object: Record, propertyName: string, setter: Setter, enumerable?: boolean, configurable?: boolean) => { + return (object: Record, propertyName: string, setter: Setter, enumerable?: boolean, configurable?: boolean): void => { descriptor.set = setter; descriptor.enumerable = enumerable; descriptor.configurable = configurable; @@ -286,17 +286,17 @@ export function getClassName (objOrCtor: any): string { * @zh 新的属性名。可以直接传属性名或者是 `类名.属性名` 的形式。 * @param writable @en Whether the property is writable. Default is false. @zh 该属性是否可写。默认不可写。 */ -export function obsolete (object: any, obsoleted: string, newExpr: string, writable?: boolean) { +export function obsolete (object: any, obsoleted: string, newExpr: string, writable?: boolean): void { const extractPropName = /([^.]+)$/; const oldProp = extractPropName.exec(obsoleted)![0]; const newProp = extractPropName.exec(newExpr)![0]; - function getter (this: any) { + function getter (this: any): unknown { if (DEV) { warnID(5400, obsoleted, newExpr); } return this[newProp] as unknown; } - function setter (this: any, value_: any) { + function setter (this: any, value_: any): void { if (DEV) { warnID(5401, obsoleted, newExpr); } @@ -321,7 +321,7 @@ export function obsolete (object: any, obsoleted: string, newExpr: string, writa * @param props @en The property names to deprecate. @zh 被废弃的一组属性名。 * @param writable @en Whether these properties are writable. @zh 被废弃的属性是否可写。 */ -export function obsoletes (obj, objName, props, writable) { +export function obsoletes (obj, objName, props, writable): void { for (const obsoleted in props) { const newName = props[obsoleted]; obsolete(obj, `${objName}.${obsoleted}`, newName, writable); @@ -381,7 +381,7 @@ export function formatStr (msg: string, ...subst: any[]): string { * @returns @en An Array that contains all arguments except the first one. * @zh 新的参数数组,该数组不包含第一个参数。 */ -export function shiftArguments () { +export function shiftArguments (): any[] { const len = arguments.length - 1; const args = new Array(len); for (let i = 0; i < len; ++i) { @@ -411,7 +411,7 @@ export function getPropertyDescriptor (object: any, propertyName: string): Prope return null; } -function _copyProp (name: string, source: any, target: any) { +function _copyProp (name: string, source: any, target: any): void { const pd = getPropertyDescriptor(source, name); if (pd) { Object.defineProperty(target, name, pd); @@ -425,7 +425,7 @@ function _copyProp (name: string, source: any, target: any) { * @param target @en Target object to copy to. @zh 拷贝到目标对象。 * @param excepts @en Properties are not copied. @zh 不拷贝到属性。 */ -export function copyAllProperties (source: any, target: any, excepts: Array) { +export function copyAllProperties (source: any, target: any, excepts: Array): void { const propertyNames: Array = Object.getOwnPropertyNames(source); for (let i = 0, len = propertyNames.length; i < len; ++i) { const propertyName: string = propertyNames[i]; @@ -445,7 +445,7 @@ export function copyAllProperties (source: any, target: any, excepts: Array, ...sources: any[]) { +export function addon (object?: Record, ...sources: any[]): Record { object = object || {}; for (const source of sources) { if (source) { @@ -471,7 +471,7 @@ export function addon (object?: Record, ...sources: any[]) * @return @en The passing `object` or a new object if passing object is not valid. * @zh 传入的对象。如果传入的对象无效或者没传入,将返回一个新对象。 */ -export function mixin (object?: Record, ...sources: any[]) { +export function mixin (object?: Record, ...sources: any[]): Record { object = object || {}; for (const source of sources) { if (source) { @@ -497,7 +497,7 @@ export function mixin (object?: Record, ...sources: any[]) * @returns @en Passed in `cls`. @zh 传入的 `cls`。 */ // eslint-disable-next-line @typescript-eslint/ban-types -export function extend (cls: Function, base: Function) { +export function extend (cls: Function, base: Function): Function | undefined { if (DEV) { if (!base) { errorID(5404); @@ -532,7 +532,7 @@ export function extend (cls: Function, base: Function) { * @returns @en Super class. @zh 父类。 */ // eslint-disable-next-line @typescript-eslint/ban-types -export function getSuper (constructor: Function) { +export function getSuper (constructor: Function): any { const proto = constructor.prototype; // bound function do not have prototype const dunderProto = proto && Object.getPrototypeOf(proto); // eslint-disable-next-line @typescript-eslint/no-unsafe-return @@ -550,7 +550,7 @@ export function getSuper (constructor: Function) { */ export function isChildClassOf(subclass: unknown, superclass: T): subclass is T; export function isChildClassOf(subclass: unknown, superclass: unknown): boolean; -export function isChildClassOf (subclass: unknown, superclass: unknown) { +export function isChildClassOf (subclass: unknown, superclass: unknown): boolean { if (subclass && superclass) { if (typeof subclass !== 'function') { return false; @@ -584,13 +584,13 @@ export function isChildClassOf (subclass: unknown, superclass: unknown) { * @param object @en The object to remove enumerable properties from. * @zh 要删除可枚举属性的对象。 */ -export function clear (object: Record) { +export function clear (object: Record): void { for (const key of Object.keys(object)) { delete object[key]; } } -function isTempClassId (id) { +function isTempClassId (id): boolean { return typeof id !== 'string' || id.startsWith(tempCIDGenerator.prefix); } @@ -604,8 +604,8 @@ export const _idToClass: Record = createMap(true); */ export const _nameToClass: Record = createMap(true); -function setup (tag: string, table: Record, allowExist: boolean) { - return function (id: string, constructor: Constructor) { +function setup (tag: string, table: Record, allowExist: boolean): (id: string, constructor: Constructor) => void { + return function (id: string, constructor: Constructor): void { // deregister old // eslint-disable-next-line no-prototype-builtins if (constructor.prototype.hasOwnProperty(tag)) { @@ -654,7 +654,7 @@ const doSetClassName = setup('__classname__', _nameToClass, true); * @param className @en Class name to register. @zh 注册的类名。 * @param constructor @en Constructor to register. @zh 注册的构造函数。 */ -export function setClassName (className: string, constructor: Constructor) { +export function setClassName (className: string, constructor: Constructor): void { doSetClassName(className, constructor); // auto set class id // eslint-disable-next-line no-prototype-builtins @@ -678,7 +678,7 @@ export function setClassName (className: string, constructor: Constructor) { * @param alias @en Alias to set. The name shall not have been set as class name or alias of another class. * @zh 类的别名。别名不能重复,也不能是已有类的名字。 */ -export function setClassAlias (target: Constructor, alias: string) { +export function setClassAlias (target: Constructor, alias: string): void { const nameRegistry = _nameToClass[alias]; const idRegistry = _idToClass[alias]; let ok = true; @@ -714,7 +714,7 @@ export function setClassAlias (target: Constructor, alias: string) { * @param ...constructor @en The classes to unregister. @zh 取消注册的类型列表。 */ // eslint-disable-next-line @typescript-eslint/ban-types -export function unregisterClass (...constructors: Function[]) { +export function unregisterClass (...constructors: Function[]): void { for (const constructor of constructors) { const p = constructor.prototype; const classId = p[classIdTag]; @@ -744,7 +744,7 @@ export function unregisterClass (...constructors: Function[]) { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. * Please use `getClassById()` instead. */ -export function _getClassById (classId) { +export function _getClassById (classId): Constructor { return getClassById(classId); } @@ -754,7 +754,7 @@ export function _getClassById (classId) { * @param classId @en The class id used to get class. @zh 获取类的 id。 * @returns @en The constructor of the registered class. @zh 注册的类构造函数。 */ -export function getClassById (classId) { +export function getClassById (classId): Constructor { return _idToClass[classId]; } @@ -766,7 +766,7 @@ export function getClassById (classId) { * @param classname @en The class name used to get class. @zh 获取类的类名。 * @returns @en The constructor of the registered class. @zh 注册的类构造函数。 */ -export function getClassByName (classname) { +export function getClassByName (classname): Constructor { return _nameToClass[classname]; } @@ -781,7 +781,7 @@ export function getClassByName (classname) { * @deprecated since v3.5.0. this is an engine private interface that will be removed in the future. * Please use `getClassId()` instead. */ -export function _getClassId (obj, allowTempId?: boolean) { +export function _getClassId (obj, allowTempId?: boolean): string { return getClassId(obj, allowTempId); } @@ -796,7 +796,7 @@ export function _getClassId (obj, allowTempId?: boolean) { * @returns @en Class id if found, empty string else. * @zh 找到的类标识。如果没找到的话,返回空字符串。 */ -export function getClassId (obj, allowTempId?: boolean) { +export function getClassId (obj, allowTempId?: boolean): string { allowTempId = (typeof allowTempId !== 'undefined' ? allowTempId : true); let res; diff --git a/cocos/core/utils/jsb-utils.ts b/cocos/core/utils/jsb-utils.ts index ecc078b2c12..efab2acf672 100644 --- a/cocos/core/utils/jsb-utils.ts +++ b/cocos/core/utils/jsb-utils.ts @@ -111,7 +111,7 @@ import type { Node } from '../../scene-graph'; // TODO: we mark node as type of any, because the properties we access are only implemented on native. @dumganhar // issue: https://github.com/cocos/cocos-engine/issues/14644 // export function syncNodeValues (node: Node) { -export function syncNodeValues (node: any) { +export function syncNodeValues (node: any): void { const lpos = node._lpos; node.setPositionForJS(lpos.x, lpos.y, lpos.z); @@ -125,7 +125,7 @@ export function syncNodeValues (node: any) { node.setRotationFromEulerForJS(euler.x, euler.y, euler.z); } -export function updateChildrenForDeserialize (node: Node) { +export function updateChildrenForDeserialize (node: Node): void { if (!node) { return; } @@ -177,12 +177,12 @@ export function updateChildrenForDeserialize (node: Node) { // node._isChildrenRedefined = true; // } type EventType = string | number; -export function ExtraEventMethods () {} +export function ExtraEventMethods (): void {} -ExtraEventMethods.prototype.once = function once void> (type: EventType, callback: Callback, target?: any) { +ExtraEventMethods.prototype.once = function once void> (type: EventType, callback: Callback, target?: any): Callback { return this.on(type, callback, target, true) as Callback; }; -ExtraEventMethods.prototype.targetOff = function targetOff (typeOrTarget: any) { +ExtraEventMethods.prototype.targetOff = function targetOff (typeOrTarget: any): void { this.removeAll(typeOrTarget); }; diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index 81b28b250dd..359d14edf6b 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -51,8 +51,8 @@ export const BASE64_VALUES = values; * have different names. So a property getter and setter occupy two positions in `diffNameGetSets`. * @engineInternal */ -export function propertyDefine (ctor, sameNameGetSets, diffNameGetSets) { - function define (np, propName, getter, setter) { +export function propertyDefine (ctor, sameNameGetSets, diffNameGetSets): void { + function define (np, propName, getter, setter): void { const pd = Object.getOwnPropertyDescriptor(np, propName); if (pd) { if (pd.get) { np[getter] = pd.get; } @@ -90,7 +90,7 @@ export function propertyDefine (ctor, sameNameGetSets, diffNameGetSets) { * @param pushFront @en Whether to put new value in front of the vector if key exists. * @zh 如果关键字已经存在,是否把新插入的值放到数组第一个位置。 */ -export function pushToMap (map, key, value, pushFront) { +export function pushToMap (map, key, value, pushFront): void { const exists = map[key]; if (exists) { if (Array.isArray(exists)) { @@ -117,7 +117,7 @@ export function pushToMap (map, key, value, pushFront) { * @returns @en True if otherNode is contained in refNode, false if not. * @zh 如果 refNode 包含 otherNode,返回 true;否则返回 false。 */ -export function contains (refNode, otherNode) { +export function contains (refNode, otherNode): boolean { if (typeof refNode.contains === 'function') { return refNode.contains(otherNode) as boolean; } else if (typeof refNode.compareDocumentPosition === 'function') { @@ -143,7 +143,7 @@ export function contains (refNode, otherNode) { * @returns @en True if node is a DOM node, false else. * @zh 如果 DOM 节点,返回 true;否则返回 false。 */ -export function isDomNode (node) { +export function isDomNode (node): boolean { if (typeof window === 'object' && typeof Node === 'function') { // If "TypeError: Right-hand side of 'instanceof' is not callback" is thrown, // it should because window.Node was overwritten. @@ -162,9 +162,9 @@ export function isDomNode (node) { * @param p1 @en The first parameter passed to `callback`. @zh 传给回调函数的第一个参数。 * @param p2 @en The seconde parameter passed to `callback`. @zh 传给回调函数的第二个参数。 */ -export function callInNextTick (callback, p1?: any, p2?: any) { +export function callInNextTick (callback, p1?: any, p2?: any): void { if (callback) { - setTimeoutRAF(() => { + setTimeoutRAF((): void => { callback(p1, p2); }, 0); } @@ -179,7 +179,7 @@ export function callInNextTick (callback, p1?: any, p2?: any) { * @returns @en A new function that will invoke `functionName` with try catch. * @zh 使用 try catch 机制调用 `functionName` 的新函数. */ -export function tryCatchFunctor_EDITOR (funcName) { +export function tryCatchFunctor_EDITOR (funcName): AnyFunction { // eslint-disable-next-line @typescript-eslint/no-implied-eval return Function('target', `${'try {\n' @@ -197,7 +197,7 @@ export function tryCatchFunctor_EDITOR (funcName) { * @returns @en True if it is an empty object. False if it is not an empty object, not Object type, null or undefined. * @ 如果是空对象,返回 true。如果不是空对象,不是Object类型,空或未定义,则为假。 */ -export function isPlainEmptyObj_DEV (obj) { +export function isPlainEmptyObj_DEV (obj): boolean { if (!obj || obj.constructor !== Object) { return false; } @@ -222,7 +222,7 @@ export function isPlainEmptyObj_DEV (obj) { * var v2 = clampf(-1, 0, 20); // 0; * var v3 = clampf(10, 0, 20); // 10; */ -export function clampf (value: number, min_inclusive: number, max_inclusive: number) { +export function clampf (value: number, min_inclusive: number, max_inclusive: number): number { if (min_inclusive > max_inclusive) { const temp = min_inclusive; min_inclusive = max_inclusive; @@ -237,7 +237,7 @@ export function clampf (value: number, min_inclusive: number, max_inclusive: num * @param angle @en The degree to convert. @zh 角度。 * @returns @en The radian. @zh 弧度。 */ -export function degreesToRadians (angle: number) { +export function degreesToRadians (angle: number): number { return angle * macro.RAD; } @@ -247,7 +247,7 @@ export function degreesToRadians (angle: number) { * @param angle @en The radian to convert. @zh 弧度。 * @returns @en The degree. @zh 角度。 */ -export function radiansToDegrees (angle) { +export function radiansToDegrees (angle): number { return angle * macro.DEG; } diff --git a/cocos/core/utils/mutable-forward-iterator.ts b/cocos/core/utils/mutable-forward-iterator.ts index 0201f8e7f03..fb8b1da14f4 100644 --- a/cocos/core/utils/mutable-forward-iterator.ts +++ b/cocos/core/utils/mutable-forward-iterator.ts @@ -42,7 +42,7 @@ export default class MutableForwardIterator { constructor (public array: T[]) { } - get length () { + get length (): number { return this.array.length; } @@ -53,14 +53,14 @@ export default class MutableForwardIterator { } } - public remove (value: T) { + public remove (value: T): void { const index = this.array.indexOf(value); if (index >= 0) { this.removeAt(index); } } - public removeAt (i: number) { + public removeAt (i: number): void { this.array.splice(i, 1); if (i <= this.i) { @@ -68,14 +68,14 @@ export default class MutableForwardIterator { } } - public fastRemove (value: T) { + public fastRemove (value: T): void { const index = this.array.indexOf(value); if (index >= 0) { this.fastRemoveAt(index); } } - public fastRemoveAt (i: number) { + public fastRemoveAt (i: number): void { const array = this.array; array[i] = array[array.length - 1]; --array.length; @@ -85,7 +85,7 @@ export default class MutableForwardIterator { } } - public push (item: T) { + public push (item: T): void { this.array.push(item); } } diff --git a/cocos/core/utils/path.ts b/cocos/core/utils/path.ts index 964a33d0213..985404ff83f 100644 --- a/cocos/core/utils/path.ts +++ b/cocos/core/utils/path.ts @@ -80,7 +80,7 @@ export function mainFileName (fileName: string): string { * @returns @en The file name. @zh 文件名。 * @example {@link cocos/core/utils/CCPath/basename.js} */ -export function basename (path: string, extName?: string) { +export function basename (path: string, extName?: string): string { const index = path.indexOf('?'); if (index > 0) { path = path.substring(0, index); @@ -158,7 +158,7 @@ export function changeBasename (path: string, newBaseName: string, keepExt?: boo } // todo make public after verification -export function _normalize (url) { +export function _normalize (url): any { let oldUrl = url = String(url); // removing all ../ @@ -176,7 +176,7 @@ export function _normalize (url) { * @returns @en A new file path without last file separator. * @zh 路径最后分隔符的新路径。 */ -export function stripSep (path: string) { +export function stripSep (path: string): string { return path.replace(/[\/\\]$/, ''); } @@ -186,6 +186,6 @@ export function stripSep (path: string) { * @zh 获取不同平台的文件分割符。类 unix 系统是 `/`,windows 系统是 `\`。 * @returns @en File separator. @zh 文件分割符。 */ -export function getSeperator () { +export function getSeperator (): string { return systemInfo.os === OS.WINDOWS ? '\\' : '/'; } diff --git a/cocos/core/utils/pool.ts b/cocos/core/utils/pool.ts index a0c8d71df4b..6715d282ccf 100644 --- a/cocos/core/utils/pool.ts +++ b/cocos/core/utils/pool.ts @@ -138,7 +138,7 @@ export class Pool { * @zh 获取的对象。如果对象池中没有对象,返回 null。 * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _get () { + public _get (): T | null { if (this.count > 0) { --this.count; const cache = this._pool[this.count]; @@ -152,7 +152,7 @@ export class Pool { * @en Put an object into the pool. * @zh 向对象池返还一个不再需要的对象。 */ - public put (obj: T) { + public put (obj: T): void { const pool = this._pool; if (this.count < pool.length) { if (this._cleanup && this._cleanup(obj) === false) { @@ -169,7 +169,7 @@ export class Pool { * @param length @en New pool size. * @zh 新对象池大小。 */ - public resize (length: number) { + public resize (length: number): void { if (length >= 0) { this._pool.length = length; if (this.count > length) { diff --git a/cocos/core/utils/x-deprecated.ts b/cocos/core/utils/x-deprecated.ts index 648155327ad..e41125b347a 100644 --- a/cocos/core/utils/x-deprecated.ts +++ b/cocos/core/utils/x-deprecated.ts @@ -112,7 +112,7 @@ interface IMeessageItem { let messageID = 0; const messageMap: Map = new Map(); -replacePropertyLog = (n: string, dp: string, n2: string, newp: string, f: Function, id: number, s: string) => { +replacePropertyLog = (n: string, dp: string, n2: string, newp: string, f: Function, id: number, s: string): void => { const item = messageMap.get(id); if (item && item.logTimes > item.count) { f(`'%s' is deprecated, please use '%s' instead. ${s}`, `${n}.${dp}`, `${n2}.${newp}`); @@ -120,10 +120,10 @@ replacePropertyLog = (n: string, dp: string, n2: string, newp: string, f: Functi } }; -replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) => { +replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]): void => { if (owner == null) return; - properties.forEach((item: IReplacement) => { + properties.forEach((item: IReplacement): void => { const id = messageID++; messageMap.set(id, { id, count: 0, logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes }); const target = item.target != null ? item.target : owner; @@ -132,7 +132,7 @@ replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) const sameTarget = target === owner; const suggest = item.suggest ? `(${item.suggest})` : ''; if (item.customFunction != null) { - owner[item.name] = function (this: any) { + owner[item.name] = function (this: any): any { replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest); return item.customFunction!.call(this, ...arguments); }; @@ -141,11 +141,11 @@ replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) const hasGetter = item.customGetter != null; if (hasSetter && hasGetter) { Object.defineProperty(owner, item.name, { - get (this) { + get (this): any { replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest); return item.customGetter!.call(this); }, - set (this, v: any) { + set (this, v: any): void { replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest); item.customSetter!.call(this, v); }, @@ -153,7 +153,7 @@ replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) }); } else if (hasSetter) { Object.defineProperty(owner, item.name, { - set (this, v: any) { + set (this, v: any): void { replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest); item.customSetter!.call(this, v); }, @@ -161,7 +161,7 @@ replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) }); } else if (hasGetter) { Object.defineProperty(owner, item.name, { - get (this) { + get (this): any { replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest); return item.customGetter!.call(this); }, @@ -170,11 +170,11 @@ replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) } } else { Object.defineProperty(owner, item.name, { - get (this) { + get (this): any { replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest); return sameTarget ? this[newName] : target[newName]; }, - set (this, v: any) { + set (this, v: any): void { replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest); if (sameTarget) { this[newName] = v; @@ -188,7 +188,7 @@ replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) }); }; -removePropertyLog = (n: string, dp: string, f: Function, id: number, s: string) => { +removePropertyLog = (n: string, dp: string, f: Function, id: number, s: string): void => { const item = messageMap.get(id); if (item && item.logTimes > item.count) { f(`'%s' has been removed. ${s}`, `${n}.${dp}`); @@ -196,18 +196,18 @@ removePropertyLog = (n: string, dp: string, f: Function, id: number, s: string) } }; -removeProperty = (owner: object, ownerName: string, properties: IRemoveItem[]) => { +removeProperty = (owner: object, ownerName: string, properties: IRemoveItem[]): void => { if (owner == null) return; - properties.forEach((item: IRemoveItem) => { + properties.forEach((item: IRemoveItem): void => { const id = messageID++; messageMap.set(id, { id, count: 0, logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes }); const suggest = item.suggest ? `(${item.suggest})` : ''; Object.defineProperty(owner, item.name, { - get (this) { + get (this): void { return removePropertyLog(ownerName, item.name, error, id, suggest); }, - set (this) { + set (this): void { removePropertyLog(ownerName, item.name, error, id, suggest); }, enumerable: false, @@ -215,7 +215,7 @@ removeProperty = (owner: object, ownerName: string, properties: IRemoveItem[]) = }); }; -markAsWarningLog = (n: string, dp: string, f: Function, id: number, s: string) => { +markAsWarningLog = (n: string, dp: string, f: Function, id: number, s: string): void => { const item = messageMap.get(id); if (item && item.logTimes > item.count) { f(`'%s' is deprecated. ${s}`, `${n}.${dp}`); @@ -223,20 +223,20 @@ markAsWarningLog = (n: string, dp: string, f: Function, id: number, s: string) = } }; -markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]) => { +markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]): void => { if (owner == null) return; - const _defaultGetSet = (d: PropertyDescriptor, n: string, dp: string, f: Function, id: number, s: string) => { + const _defaultGetSet = (d: PropertyDescriptor, n: string, dp: string, f: Function, id: number, s: string): void => { if (d.get) { const oldGet = d.get; - d.get = function (this) { + d.get = function (this): any { markAsWarningLog(n, dp, f, id, s); return oldGet.call(this); }; } if (d.set) { const oldSet = d.set; - d.set = function (this, v: any) { + d.set = function (this, v: any): void { markAsWarningLog(n, dp, f, id, s); oldSet.call(this, v); }; @@ -244,7 +244,7 @@ markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]) => { Object.defineProperty(owner, dp, d); }; - properties.forEach((item: IMarkItem) => { + properties.forEach((item: IMarkItem): void => { const deprecatedProp = item.name; const descriptor = Object.getOwnPropertyDescriptor(owner, deprecatedProp); if (!descriptor || !descriptor.configurable) { return; } @@ -254,7 +254,7 @@ markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]) => { if (typeof descriptor.value !== 'undefined') { if (typeof descriptor.value === 'function') { const oldValue = descriptor.value as Function; - owner[deprecatedProp] = function (this) { + owner[deprecatedProp] = function (this): any { markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest); return oldValue.call(this, ...arguments); }; @@ -262,14 +262,14 @@ markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]) => { let oldValue = descriptor.value; Object.defineProperty(owner, deprecatedProp, { configurable: true, - get () { + get (): any { markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest); return oldValue; }, }); if (descriptor.writable) { Object.defineProperty(owner, deprecatedProp, { - set (value) { + set (value): void { markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest); oldValue = value; }, @@ -330,14 +330,14 @@ const topLevelDeprecateList: TopLevelDeprecateList = { * ``` * @engineInternal */ -export function deprecateModuleExportedName (deprecateList: TopLevelDeprecateList) { +export function deprecateModuleExportedName (deprecateList: TopLevelDeprecateList): void { for (let deprecateName in deprecateList) { const deprecateInfo = deprecateList[deprecateName]; topLevelDeprecateList[deprecateName] = deprecateInfo; } } -function _checkObsoleteByName (checkName: string) { +function _checkObsoleteByName (checkName: string): void { const deprecateInfo = topLevelDeprecateList[checkName]; if (!deprecateInfo) { return; @@ -367,7 +367,7 @@ function _checkObsoleteByName (checkName: string) { * ``` * @engineInternal */ -export function __checkObsolete__ (checkList: string[]) { +export function __checkObsolete__ (checkList: string[]): void { for (let checkName of checkList) { _checkObsoleteByName(checkName); } @@ -385,13 +385,13 @@ let _cachedProxy; * ``` * @engineInternal */ -export function __checkObsoleteInNamespace__ (ccNamespace: object) { +export function __checkObsoleteInNamespace__ (ccNamespace: object): any { if (!_cachedProxy) { if (typeof Proxy === 'undefined') { _cachedProxy = {}; } else { _cachedProxy = new Proxy(ccNamespace, { - get (target, name, receiver) { + get (target, name, receiver): any { // NOTE: for now we use tsc version 4.3.5, which has not supported symbol as index. _checkObsoleteByName(name as string); return Reflect.get(target, name, receiver); diff --git a/cocos/core/value-types/bitmask.ts b/cocos/core/value-types/bitmask.ts index 50385421d67..61db17e9a95 100644 --- a/cocos/core/value-types/bitmask.ts +++ b/cocos/core/value-types/bitmask.ts @@ -95,14 +95,14 @@ export function BitMask (obj: T): T { * @returns @en True if it is a BitMask, false else. * @zh 如果是 BitMask,返回 true;否则返回 false。 */ -BitMask.isBitMask = (BitMaskType) => BitMaskType && BitMaskType.hasOwnProperty('__bitmask__'); +BitMask.isBitMask = (BitMaskType): any => BitMaskType && BitMaskType.hasOwnProperty('__bitmask__'); /** * * @param BitMaskDef * @returns @en A sorted array with integer values. @zh 存储整型属性值的数组。该数组已排序。 */ -BitMask.getList = (BitMaskDef) => { +BitMask.getList = (BitMaskDef): any => { if (BitMaskDef.__bitmask__) { return BitMaskDef.__bitmask__; } @@ -119,7 +119,7 @@ BitMask.getList = (BitMaskDef) => { * @param BitMaskDef * @returns @en A sorted array with integer values. @zh 存储整型属性值的数组。该数组已排序。 */ -BitMask.update = (BitMaskDef) => { +BitMask.update = (BitMaskDef): any => { if (!Array.isArray(BitMaskDef.__bitmask__)) { BitMaskDef.__bitmask__ = []; } @@ -133,7 +133,7 @@ BitMask.update = (BitMaskDef) => { bitList.push({ name, value: v }); } } - bitList.sort((a, b) => a.value - b.value); + bitList.sort((a, b): number => a.value - b.value); return bitList; }; @@ -144,7 +144,7 @@ BitMask.update = (BitMaskDef) => { * @param bitmaskx @en An object to make BitMask type. @zh 要标记为 BitMask 类型的对象。 * @returns @en The passed in object. @zh 传入的对象。 */ -export function ccbitmask (bitmaskx) { +export function ccbitmask (bitmaskx): void { if ('__bitmask__' in bitmaskx) { return; } diff --git a/cocos/core/value-types/enum.ts b/cocos/core/value-types/enum.ts index a2efa4dc1e2..6e4e5aa169e 100644 --- a/cocos/core/value-types/enum.ts +++ b/cocos/core/value-types/enum.ts @@ -113,7 +113,7 @@ interface EnumExtras { * Determines if the object is an enum type. * @param enumType @en The object to judge. @zh 需要判断的对象。 */ -Enum.isEnum = (enumType: EnumT) => enumType && enumType.hasOwnProperty('__enums__'); +Enum.isEnum = (enumType: EnumT): boolean => enumType && enumType.hasOwnProperty('__enums__'); function assertIsEnum (enumType: EnumT): asserts enumType is EnumT & EnumExtras { assertIsTrue(enumType.hasOwnProperty('__enums__')); @@ -149,7 +149,7 @@ function updateList (enumType: EnumT): readonly Enum.Enumerato enums.push({ name, value: v }); } } - enums.sort((a, b) => a.value - b.value); + enums.sort((a, b): number => a.value - b.value); enumType.__enums__ = enums; return enums; } @@ -159,7 +159,7 @@ function updateList (enumType: EnumT): readonly Enum.Enumerato * @param enumType @en The enum type defined from [[Enum]] @zh 从[[Enum]]定义的枚举类型。 * @param compareFn @en Function used to determine the order of the elements. @zh 用于确定元素顺序的函数。 */ -Enum.sortList = (enumType: EnumT, compareFn: (a, b) => number) => { +Enum.sortList = (enumType: EnumT, compareFn: (a, b) => number): void => { assertIsEnum(enumType); if (!Array.isArray(enumType.__enums__)) { return; @@ -189,7 +189,7 @@ if (DEV) { * @en enumType An enum type, eg, a kind of type with similar semantic defined by TypeScript. * @zh 枚举类型,例如 TypeScript 中定义的类型。 */ -export function ccenum (enumType: EnumT) { +export function ccenum (enumType: EnumT): void { if (!('__enums__' in enumType)) { value(enumType, '__enums__', null, true); } diff --git a/cocos/core/value-types/value-type.ts b/cocos/core/value-types/value-type.ts index 93b023626f5..15473af19e8 100644 --- a/cocos/core/value-types/value-type.ts +++ b/cocos/core/value-types/value-type.ts @@ -60,7 +60,7 @@ export class ValueType { * @param other @en The other object @zh 指定值。 * @returns @en `true` if equal, otherwise returns `false` @zh 如果相等,则返回 `true`,否则返回 `false`。 */ - public equals (other: this) { + public equals (other: this): boolean { // errorID(100, js.getClassName(this) + '.equals'); return false; } @@ -74,7 +74,7 @@ export class ValueType { * 本方法的基类版本简单地返回 `this`,派生类**必须**重写本方法。 * @param other @en The other object. @zh 指定值。 */ - public set (other: this) { + public set (other: this): void { errorID(100, `${js.getClassName(this)}.set`); } @@ -87,7 +87,7 @@ export class ValueType { * 本方法的基类版本返回空字符串。 * @returns @en The string representation of the current value. @zh 当前值的字符串表示。 */ - public toString () { + public toString (): string { return `${''}`; } } diff --git a/cocos/dragon-bones/ArmatureCache.ts b/cocos/dragon-bones/ArmatureCache.ts index 1924015233c..dada8e53dca 100644 --- a/cocos/dragon-bones/ArmatureCache.ts +++ b/cocos/dragon-bones/ArmatureCache.ts @@ -129,7 +129,7 @@ export class AnimationCache { * @param armatureInfo @en Armature info. @zh 龙骨信息。 * @param animationName @en Animation name. @zh 动画名称。 */ - init (armatureInfo: ArmatureInfo, animationName: string) { + init (armatureInfo: ArmatureInfo, animationName: string): void { this._inited = true; this._armatureInfo = armatureInfo; this._animationName = animationName; @@ -139,7 +139,7 @@ export class AnimationCache { * @en Clears all animation frames cached. * @zh 清除所有缓存动画帧。 */ - clear () { + clear (): void { this._inited = false; for (let i = 0, n = this.frames.length; i < n; i++) { const frame = this.frames[i]!; @@ -151,7 +151,7 @@ export class AnimationCache { * @en Start to play cached frames. * @zh 开始播放缓存动画帧。 */ - begin () { + begin (): void { if (!this._invalid) return; const armatureInfo = this._armatureInfo!; @@ -177,7 +177,7 @@ export class AnimationCache { * @en Complete to play cached frames. * @zh 完成播放缓存动画帧。 */ - end () { + end (): void { if (!this._needToUpdate()) { this._armatureInfo!.curAnimationCache = null; this.frames.length = this._frameIdx + 1; @@ -187,7 +187,7 @@ export class AnimationCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _needToUpdate (toFrameIdx?: number) { + _needToUpdate (toFrameIdx?: number): boolean { const armatureInfo = this._armatureInfo!; const armature = armatureInfo.armature; const animation = armature.animation; @@ -200,7 +200,7 @@ export class AnimationCache { * @zh 更新动画到指定帧序列。 * @param toFrameIdx @en Frame index. @zh 帧序列。 */ - updateToFrame (toFrameIdx?: number) { + updateToFrame (toFrameIdx?: number): void { if (!this._inited) return; this.begin(); @@ -226,7 +226,7 @@ export class AnimationCache { * @returns @en True means has been initialized, false means not. * @zh True 表示已初始化完成,false 表示还没初始化。 */ - isInited () { + isInited (): boolean { return this._inited; } /** @@ -235,14 +235,14 @@ export class AnimationCache { * @returns @zh True means invalid, false means valid. * @en True 表示当前数据为无效状态,false 表示当前数据有效。 */ - isInvalid () { + isInvalid (): boolean { return this._invalid; } /** * @en Mark all cached frames as invalid. * @zh 将所有缓存帧标记为无效的。 */ - invalidAllFrame () { + invalidAllFrame (): void { this.isCompleted = false; this._invalid = true; } @@ -250,7 +250,7 @@ export class AnimationCache { * @en Update all cached frames. * @zh 更新所有缓存帧。 */ - updateAllFrame () { + updateAllFrame (): void { this.invalidAllFrame(); this.updateToFrame(); } @@ -258,7 +258,7 @@ export class AnimationCache { * @en Enable attached information. * @zh 启用挂载附着信息。 */ - enableCacheAttachedInfo () { + enableCacheAttachedInfo (): void { if (!this._enableCacheAttachedInfo) { this._enableCacheAttachedInfo = true; this.invalidAllFrame(); @@ -270,7 +270,7 @@ export class AnimationCache { * @param armature @en Armature. @zh 指定骨架。 * @param index @en Frame index. @zh 帧序列。 */ - updateFrame (armature, index) { + updateFrame (armature, index): void { _vfOffset = 0; _boneInfoOffset = 0; _indexOffset = 0; @@ -363,7 +363,7 @@ export class AnimationCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _traverseArmature (armature: Armature, parentOpacity) { + _traverseArmature (armature: Armature, parentOpacity): void { const colors = this._tempColors!; const segments = this._tempSegments!; const boneInfos = this._tempBoneInfos!; @@ -495,7 +495,7 @@ export class ArmatureCache { * @en Enable private cache mode. * @zh 启用私有缓存模式。 */ - enablePrivateMode () { + enablePrivateMode (): void { this._privateMode = true; } @@ -503,7 +503,7 @@ export class ArmatureCache { * @en If using private cache mode, all cached data will be destroyed when corresponding dragonbone nodes are destroyed. * @zh 如果为私有缓存模式,cache 数据将随组件一起销毁。 */ - dispose () { + dispose (): void { for (const key in this._armatureCache) { const armatureInfo = this._armatureCache[key]; if (armatureInfo) { @@ -517,7 +517,7 @@ export class ArmatureCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _removeArmature (armatureKey: string) { + _removeArmature (armatureKey: string): void { const armatureInfo = this._armatureCache[armatureKey]; const animationsCache = armatureInfo.animationsCache; for (const aniKey in animationsCache) { @@ -537,7 +537,7 @@ export class ArmatureCache { * @en When dragonbones assets be destroy, remove armature from dragonbones cache. * @zh 当 dragonbones assets 销毁时,从 cache 中移除骨架。 */ - resetArmature (uuid: string) { + resetArmature (uuid: string): void { for (const armatureKey in this._armatureCache) { if (armatureKey.indexOf(uuid) === -1) continue; this._removeArmature(armatureKey); @@ -546,7 +546,7 @@ export class ArmatureCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - getArmatureCache (armatureName: string, armatureKey: string, atlasUUID: string) { + getArmatureCache (armatureName: string, armatureKey: string, atlasUUID: string): Armature | null { const armatureInfo = this._armatureCache[armatureKey]; let armature: Armature; if (!armatureInfo) { @@ -576,7 +576,7 @@ export class ArmatureCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - getAnimationCache (armatureKey, animationName) { + getAnimationCache (armatureKey, animationName): AnimationCache | null { const armatureInfo = this._armatureCache[armatureKey]; if (!armatureInfo) return null; @@ -586,7 +586,7 @@ export class ArmatureCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - initAnimationCache (armatureKey: string, animationName: string) { + initAnimationCache (armatureKey: string, animationName: string): AnimationCache | null { if (!animationName) return null; const armatureInfo = this._armatureCache[armatureKey]; @@ -616,7 +616,7 @@ export class ArmatureCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - invalidAnimationCache (armatureKey: string) { + invalidAnimationCache (armatureKey: string): void { const armatureInfo = this._armatureCache[armatureKey]; const armature = armatureInfo && armatureInfo.armature; if (!armature) return; @@ -630,7 +630,7 @@ export class ArmatureCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - updateAnimationCache (armatureKey: string, animationName: string) { + updateAnimationCache (armatureKey: string, animationName: string): void { if (animationName) { const animationCache = this.initAnimationCache(armatureKey, animationName); if (!animationCache) return; @@ -650,7 +650,7 @@ export class ArmatureCache { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - static canCache (armature: Armature) { + static canCache (armature: Armature): boolean { const slots = armature._slots; for (let i = 0, l = slots.length; i < l; i++) { const slot = slots[i]; diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index 39eb59a262a..20899375b91 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -23,7 +23,7 @@ */ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; -import { Armature, Bone, EventObject } from '@cocos/dragonbones-js'; +import { Armature, Bone, EventObject, AnimationState } from '@cocos/dragonbones-js'; import { UIRenderer } from '../2d/framework/ui-renderer'; import { CCClass, Color, Enum, ccenum, errorID, RecyclePool, js, CCObject, EventTarget, cclegacy, _decorator } from '../core'; import { BlendFactor } from '../gfx'; @@ -94,7 +94,7 @@ ccenum(AnimationCacheMode); const { ccclass, serializable, editable, type, help, menu, tooltip, visible, displayName, override, displayOrder, executeInEditMode } = _decorator; -function setEnumAttr (obj, propName, enumDef) { +function setEnumAttr (obj, propName, enumDef): void { CCClass.Attr.setClassAttr(obj, propName, 'type', 'Enum'); CCClass.Attr.setClassAttr(obj, propName, 'enumList', Enum.getList(enumDef)); } @@ -202,7 +202,7 @@ export class ArmatureDisplay extends UIRenderer { @editable @type(DragonBonesAsset) @tooltip('i18n:COMPONENT.dragon_bones.dragon_bones_asset') - get dragonAsset () { + get dragonAsset (): DragonBonesAsset | null { return this._dragonAsset; } set dragonAsset (value) { @@ -225,7 +225,7 @@ export class ArmatureDisplay extends UIRenderer { @editable @type(DragonBonesAtlasAsset) @tooltip('i18n:COMPONENT.dragon_bones.dragon_bones_atlas_asset') - get dragonAtlasAsset () { return this._dragonAtlasAsset; } + get dragonAtlasAsset (): DragonBonesAtlasAsset | null { return this._dragonAtlasAsset; } set dragonAtlasAsset (value) { this._dragonAtlasAsset = value; this._parseDragonAtlasAsset(); @@ -238,7 +238,7 @@ export class ArmatureDisplay extends UIRenderer { * @property {String} armatureName */ @visible(false) - get armatureName () { return this._armatureName; } + get armatureName (): string { return this._armatureName; } set armatureName (name) { this._armatureName = name; const animNames = this.getAnimationNames(this._armatureName); @@ -269,7 +269,7 @@ export class ArmatureDisplay extends UIRenderer { * @property {String} animationName */ @visible(false) - get animationName () { + get animationName (): string { return this._animationName; } set animationName (value) { @@ -283,7 +283,7 @@ export class ArmatureDisplay extends UIRenderer { @editable @type(DefaultArmaturesEnum) @tooltip('i18n:COMPONENT.dragon_bones.armature_name') - get _defaultArmatureIndex () { + get _defaultArmatureIndex (): DefaultArmaturesEnum { return this._defaultArmatureIndexValue; } set _defaultArmatureIndex (value) { @@ -317,7 +317,7 @@ export class ArmatureDisplay extends UIRenderer { @type(DefaultAnimsEnum) @displayName('Animation') @tooltip('i18n:COMPONENT.dragon_bones.animation_name') - get _animationIndex () { + get _animationIndex (): DefaultAnimsEnum { return this._animationIndexValue; } set _animationIndex (value) { @@ -351,7 +351,7 @@ export class ArmatureDisplay extends UIRenderer { @editable @displayName('Animation Cache Mode') @tooltip('i18n:COMPONENT.dragon_bones.animation_cache_mode') - get _defaultCacheMode () { return this._defaultCacheModeValue; } + get _defaultCacheMode (): AnimationCacheMode { return this._defaultCacheModeValue; } set _defaultCacheMode (value) { this._defaultCacheModeValue = value; @@ -373,7 +373,7 @@ export class ArmatureDisplay extends UIRenderer { @editable @tooltip('i18n:COMPONENT.dragon_bones.time_scale') @serializable - get timeScale () { return this._timeScale; } + get timeScale (): number { return this._timeScale; } set timeScale (value) { this._timeScale = value; @@ -421,7 +421,7 @@ export class ArmatureDisplay extends UIRenderer { */ @tooltip('i18n:COMPONENT.dragon_bones.debug_bones') @editable - get debugBones () { return this._debugBones; } + get debugBones (): boolean { return this._debugBones; } set debugBones (value) { this._debugBones = value; this._updateDebugDraw(); @@ -436,7 +436,7 @@ export class ArmatureDisplay extends UIRenderer { */ @tooltip('i18n:COMPONENT.dragon_bones.enabled_batch') @editable - get enableBatch () { return this._enableBatch; } + get enableBatch (): boolean { return this._enableBatch; } set enableBatch (value) { if (value !== this._enableBatch) { this._enableBatch = value; @@ -471,7 +471,7 @@ export class ArmatureDisplay extends UIRenderer { * transformation with bones. * @zh 获取 socket nodes,socket nodes 被注册到组件上,可以随骨骼做同步运动变换。 */ - get socketNodes () { return this._socketNodes; } + get socketNodes (): Map { return this._socketNodes; } /** * @en The armature is the core of the skeletal animation system. * @zh 骨架是骨骼动画系统的核心。 @@ -486,7 +486,7 @@ export class ArmatureDisplay extends UIRenderer { * @en Draw call list. * @zh Draw call 列表。 */ - get drawList () { return this._drawList; } + get drawList (): RecyclePool { return this._drawList; } @serializable protected _defaultArmatureIndexValue: DefaultArmaturesEnum = DefaultArmaturesEnum.default; /** @@ -570,7 +570,7 @@ export class ArmatureDisplay extends UIRenderer { protected _displayProxy: CCArmatureDisplay | null = null; protected _drawIdx = 0; - protected _drawList = new RecyclePool(() => ({ + protected _drawList = new RecyclePool((): ArmatureDisplayDrawData => ({ material: null, texture: null, indexOffset: 0, @@ -598,7 +598,7 @@ export class ArmatureDisplay extends UIRenderer { private _inited; private _drawInfoList: RenderDrawInfo[] = []; - private requestDrawInfo (idx: number) { + private requestDrawInfo (idx: number): RenderDrawInfo { if (!this._drawInfoList[idx]) { this._drawInfoList[idx] = new RenderDrawInfo(); } @@ -624,18 +624,18 @@ export class ArmatureDisplay extends UIRenderer { * @en Initializes _factory from CCFactory, if golbal factory not exists, will create a new one. * @zh 初始化变量 _factory,如果全局工厂实例不存在将新创建一个工厂实列对象。 */ - initFactory () { + initFactory (): void { this._factory = CCFactory.getInstance(); } - onLoad () { + onLoad (): void { super.onLoad(); } /** * @engineInternal */ - public _requestDrawData (material: Material, texture: Texture2D, indexOffset: number, indexCount: number) { + public _requestDrawData (material: Material, texture: Texture2D, indexOffset: number, indexCount: number): ArmatureDisplayDrawData { const draw = this._drawList.add(); draw.material = material; draw.texture = texture; @@ -649,7 +649,7 @@ export class ArmatureDisplay extends UIRenderer { * @zh * 销毁渲染数据,一般在重新生成渲染数据时或销毁组件时调用。 */ - public destroyRenderData () { + public destroyRenderData (): void { this._drawList.reset(); super.destroyRenderData(); } @@ -703,7 +703,7 @@ export class ArmatureDisplay extends UIRenderer { @type(Material) @displayOrder(0) @displayName('CustomMaterial') - get customMaterial () { + get customMaterial (): Material | null { return this._customMaterial; } set customMaterial (val) { @@ -715,7 +715,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal */ - public updateMaterial () { + public updateMaterial (): void { let mat; if (this._customMaterial) mat = this._customMaterial; else mat = this._updateBuiltinMaterial(); @@ -723,7 +723,7 @@ export class ArmatureDisplay extends UIRenderer { this._cleanMaterialCache(); } - protected _render (batcher: Batcher2D) { + protected _render (batcher: Batcher2D): void { let indicesCount = 0; if (this.renderData && this._drawList) { const rd = this.renderData; @@ -746,7 +746,7 @@ export class ArmatureDisplay extends UIRenderer { } } - __preload () { + __preload (): void { super.__preload(); this._init(); } @@ -754,7 +754,7 @@ export class ArmatureDisplay extends UIRenderer { * @en Initialize asset data and internal data within the component. * @zh 初始化资产数据以及组件内部数据。 */ - _init () { + _init (): void { if (EDITOR_NOT_IN_PREVIEW) { const Flags = CCObject.Flags; this._objFlags |= (Flags.IsAnchorLocked | Flags.IsSizeLocked); @@ -796,7 +796,7 @@ export class ArmatureDisplay extends UIRenderer { * let needChangeSlot = needChangeArmature.armature().getSlot("changeSlotName"); * factory.replaceSlotDisplay(toChangeArmature.getArmatureKey(), "armatureName", "slotName", "displayName", needChangeSlot); */ - getArmatureKey () { + getArmatureKey (): string { return this._armatureKey; } @@ -815,7 +815,7 @@ export class ArmatureDisplay extends UIRenderer { * @example * armatureDisplay.setAnimationCacheMode(dragonBones.ArmatureDisplay.AnimationCacheMode.SHARED_CACHE); */ - setAnimationCacheMode (cacheMode: AnimationCacheMode) { + setAnimationCacheMode (cacheMode: AnimationCacheMode): void { if (this._preCacheMode !== cacheMode) { this._cacheMode = cacheMode; this._buildArmature(); @@ -836,7 +836,7 @@ export class ArmatureDisplay extends UIRenderer { * @zh True 代表动画使用 SHARED_CACHE 或 PRIVATE_CACHE 模式。 * False 代表动画使用 REALTIME 模式。 */ - isAnimationCached () { + isAnimationCached (): boolean { if (EDITOR_NOT_IN_PREVIEW) return false; return this._cacheMode !== AnimationCacheMode.REALTIME; } @@ -845,7 +845,7 @@ export class ArmatureDisplay extends UIRenderer { * Instance of ArmatureDisplay will be added into ArmatureSystem. * @zh 组件状态变为可用时调用。ArmatureDisplay 实例将被添加到 ArmatureSystem。 */ - onEnable () { + onEnable (): void { super.onEnable(); // If cache mode is cache, no need to update by dragonbones library. if (this._armature && !this.isAnimationCached()) { @@ -859,7 +859,7 @@ export class ArmatureDisplay extends UIRenderer { * Instance of ArmatureDisplay will be removed from ArmatureSystem. * @zh 组件状态变为不可用时调用。ArmatureDisplay 实例将被从 ArmatureSystem 移除。 */ - onDisable () { + onDisable (): void { super.onDisable(); // If cache mode is cache, no need to update by dragonbones library. if (this._armature && !this.isAnimationCached()) { @@ -870,7 +870,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _emitCacheCompleteEvent () { + _emitCacheCompleteEvent (): void { // Animation loop complete, the event diffrent from dragonbones inner event, // It has no event object. this._eventTarget.emit(EventObject.LOOP_COMPLETE); @@ -884,7 +884,7 @@ export class ArmatureDisplay extends UIRenderer { * @zh 更新动画序列。 * @param dt @en Delta time, unit is second. @zh 时间差,单位为秒。 */ - updateAnimation (dt) { + updateAnimation (dt): void { this.markForUpdateRenderData(); if (!this.isAnimationCached()) return; if (!this._frameCache) return; @@ -964,8 +964,8 @@ export class ArmatureDisplay extends UIRenderer { * @en Destroy component, release resource. * @zh 销毁组件时调用,释放相关资源。 */ - onDestroy () { - this._materialInstances = this._materialInstances.filter((instance) => !!instance); + onDestroy (): void { + this._materialInstances = this._materialInstances.filter((instance): boolean => !!instance); this._inited = false; if (!EDITOR_NOT_IN_PREVIEW) { @@ -991,7 +991,7 @@ export class ArmatureDisplay extends UIRenderer { * @en Update the debugging component show. * @zh 更新调试 Graphic 组件的显示。 */ - _updateDebugDraw () { + _updateDebugDraw (): void { if (this.debugBones) { if (!this._debugDraw) { const debugDrawNode = new Node('DEBUG_DRAW_NODE'); @@ -1013,7 +1013,7 @@ export class ArmatureDisplay extends UIRenderer { * @en Update related data due to batching settings. * @zh 更新由于合批设置导致的相关数据。 */ - protected _updateBatch () { + protected _updateBatch (): void { this._cleanMaterialCache(); this.markForUpdateRenderData(); } @@ -1021,7 +1021,7 @@ export class ArmatureDisplay extends UIRenderer { * @en Building data of armature. * @zh 构建骨架数据。 */ - _buildArmature () { + _buildArmature (): void { if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) return; // Switch Asset or Atlas or cacheMode will rebuild armature. @@ -1099,7 +1099,7 @@ export class ArmatureDisplay extends UIRenderer { * @en Gets sockets binding on this component. * @zh 获取绑定在本组件上的socket。 */ - public querySockets () { + public querySockets (): string[] { if (!this._armature) { return []; } @@ -1114,7 +1114,7 @@ export class ArmatureDisplay extends UIRenderer { * @zh 查询 Socket 路径。 * @param name @en Slot name or Bone name. @zh 插槽或骨骼名称。 */ - public querySocketPathByName (name: string) { + public querySocketPathByName (name: string): string[] { const ret: string[] = []; for (const key of this._cachedSockets.keys()) { if (key.endsWith(name)) { @@ -1127,7 +1127,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _parseDragonAtlasAsset () { + _parseDragonAtlasAsset (): void { if (this.dragonAtlasAsset) { this.dragonAtlasAsset.init(this._factory!); } @@ -1135,7 +1135,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _refresh () { + _refresh (): void { this._buildArmature(); this._indexBoneSockets(); if (EDITOR_NOT_IN_PREVIEW) { @@ -1150,7 +1150,7 @@ export class ArmatureDisplay extends UIRenderer { private _cacheModeEnum: any; // EDITOR - _updateCacheModeEnum () { + _updateCacheModeEnum (): void { this._cacheModeEnum = Enum({}); if (this._armature) { Object.assign(this._cacheModeEnum, AnimationCacheMode); @@ -1164,7 +1164,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _updateAnimEnum () { + _updateAnimEnum (): void { let animEnum; if (this.dragonAsset) { animEnum = this.dragonAsset.getAnimsEnum(this.armatureName); @@ -1183,7 +1183,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _updateArmatureEnum () { + _updateArmatureEnum (): void { let armatureEnum; if (this.dragonAsset) { armatureEnum = this.dragonAsset.getArmatureEnum(); @@ -1200,7 +1200,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - _indexBoneSockets () { + _indexBoneSockets (): void { if (!this._armature) { return; } @@ -1219,7 +1219,7 @@ export class ArmatureDisplay extends UIRenderer { (bone as any).path = name; return name; }; - const walkArmature = (prefix: string, armature: Armature) => { + const walkArmature = (prefix: string, armature: Armature): void => { const bones = armature.getBones(); const boneToName = new Map(); for (let i = 0; i < bones.length; i++) { @@ -1257,7 +1257,7 @@ export class ArmatureDisplay extends UIRenderer { * 0 为无限循环播放。 * >0 为动画的重复次数。 */ - playAnimation (animName: string, playTimes?: number) { + playAnimation (animName: string, playTimes?: number): AnimationState | null { this.playTimes = (playTimes === undefined) ? -1 : playTimes; this.animationName = animName; @@ -1295,7 +1295,7 @@ export class ArmatureDisplay extends UIRenderer { * @method updateAnimationCache * @param animName @en Animation's name. @zh 动画名称。 */ - updateAnimationCache (animName: string) { + updateAnimationCache (animName: string): void { if (!this.isAnimationCached()) return; this._armatureCache!.updateAnimationCache(this._armatureKey, animName); } @@ -1307,7 +1307,7 @@ export class ArmatureDisplay extends UIRenderer { * 使动画缓存失效,之后会在每帧重新计算。 * @method invalidAnimationCache */ - invalidAnimationCache () { + invalidAnimationCache (): void { if (!this.isAnimationCached()) return; this._armatureCache!.invalidAnimationCache(this._armatureKey); } @@ -1320,7 +1320,7 @@ export class ArmatureDisplay extends UIRenderer { * @method getArmatureNames * @returns @en Return an array of armature names. @zh 返回 armature 名称数组。 */ - getArmatureNames () { + getArmatureNames (): string[] { const dragonBonesData = this._factory!.getDragonBonesData(this._armatureKey); return (dragonBonesData && dragonBonesData.armatureNames) || []; } @@ -1335,7 +1335,7 @@ export class ArmatureDisplay extends UIRenderer { * @returns @en Return an array of all animation names. * @zh 返回包含所有动画名称的数组。 */ - getAnimationNames (armatureName: string) { + getAnimationNames (armatureName: string): string[] { const ret: string[] = []; const dragonBonesData = this._factory!.getDragonBonesData(this._armatureKey); if (dragonBonesData) { @@ -1365,7 +1365,7 @@ export class ArmatureDisplay extends UIRenderer { * @param target @en The target (this object) to invoke the callback, can be null. * @zh 调用回调函数的对象,可以为 null。 */ - on (eventType: string, listener, target) { + on (eventType: string, listener, target): void { this.addEventListener(eventType, listener, target); } @@ -1382,7 +1382,7 @@ export class ArmatureDisplay extends UIRenderer { * @param target @en The target (this object) to invoke the callback, can be null. * @zh 调用回调函数的对象,可以为 null。 */ - off (eventType: string, listener, target) { + off (eventType: string, listener, target): void { this.removeEventListener(eventType, listener, target); } @@ -1399,7 +1399,7 @@ export class ArmatureDisplay extends UIRenderer { * @param target @en The target (this object) to invoke the callback, can be null. * @zh 调用回调函数的对象,可以为 null。 */ - once (eventType: string, listener, target) { + once (eventType: string, listener, target): void { this._eventTarget.once(eventType, listener, target); } @@ -1416,7 +1416,7 @@ export class ArmatureDisplay extends UIRenderer { * @param target @en The target (this object) to invoke the callback, can be null. * @zh 调用回调函数的对象,可以为 null。 */ - addEventListener (eventType, listener, target) { + addEventListener (eventType, listener, target): void { this._eventTarget.on(eventType, listener, target); } @@ -1431,7 +1431,7 @@ export class ArmatureDisplay extends UIRenderer { * @param target @en The target (this object) to invoke the callback, can be null. * @zh 调用回调函数的对象,可以为 null。 */ - removeEventListener (eventType, listener, target) { + removeEventListener (eventType, listener, target): void { this._eventTarget.off(eventType, listener, target); } @@ -1445,7 +1445,7 @@ export class ArmatureDisplay extends UIRenderer { * @returns @en Return a new ArmatureDisplay component. * @zh 返回一个新创建的 ArmatureDisplay 组件。 */ - buildArmature (armatureName: string, node?: Node) { + buildArmature (armatureName: string, node?: Node): ArmatureDisplay { return this._factory!.createArmatureNode(this, armatureName, node); } @@ -1457,11 +1457,11 @@ export class ArmatureDisplay extends UIRenderer { * @method armature * @returns @en Return the armature object. @zh 返回 armature 对象。 */ - armature () { + armature (): Armature | null { return this._armature; } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = ArmatureDisplay.Assembler.getAssembler(this); if (this._assembler !== assembler) { this._assembler = assembler; @@ -1477,7 +1477,7 @@ export class ArmatureDisplay extends UIRenderer { } } - protected _updateSocketBindings () { + protected _updateSocketBindings (): void { if (!this._armature) return; this._socketNodes.clear(); for (let i = 0, l = this._sockets.length; i < l; i++) { @@ -1494,7 +1494,7 @@ export class ArmatureDisplay extends UIRenderer { } } - private _verifySockets (sockets: DragonBoneSocket[]) { + private _verifySockets (sockets: DragonBoneSocket[]): void { for (let i = 0, l = sockets.length; i < l; i++) { const target = sockets[i].target; if (target) { @@ -1506,14 +1506,14 @@ export class ArmatureDisplay extends UIRenderer { } } - private _cleanMaterialCache () { + private _cleanMaterialCache (): void { for (const val in this._materialCache) { this._materialCache[val].destroy(); } this._materialCache = {}; } - protected createRenderEntity () { + protected createRenderEntity (): RenderEntity { const renderEntity = new RenderEntity(RenderEntityType.DYNAMIC); renderEntity.setUseLocal(false); return renderEntity; @@ -1522,7 +1522,7 @@ export class ArmatureDisplay extends UIRenderer { * @en Sets flag for update render data. * @zh 标记组件渲染数据更新。 */ - public markForUpdateRenderData (enable = true) { + public markForUpdateRenderData (enable = true): void { super.markForUpdateRenderData(enable); if (this._debugDraw) { this._debugDraw.markForUpdateRenderData(enable); @@ -1532,7 +1532,7 @@ export class ArmatureDisplay extends UIRenderer { /** * @engineInternal since v3.7.2 this is an engine private function. */ - public syncAttachedNode () { + public syncAttachedNode (): void { // sync attached node matrix this.attachUtil._syncAttachedNode(); } diff --git a/cocos/dragon-bones/ArmatureSystem.ts b/cocos/dragon-bones/ArmatureSystem.ts index 8dbdf304c25..b019f5a4ce0 100644 --- a/cocos/dragon-bones/ArmatureSystem.ts +++ b/cocos/dragon-bones/ArmatureSystem.ts @@ -46,7 +46,7 @@ export class ArmatureSystem extends System { * @en Gets the instance of the ArmatureSystem system. * @zh 获取 Dragonbones Armature 系统的单例。 */ - public static getInstance () { + public static getInstance (): ArmatureSystem { if (!ArmatureSystem._instance) { ArmatureSystem._instance = new ArmatureSystem(); director.registerSystem(ArmatureSystem.ID, ArmatureSystem._instance, System.Priority.HIGH); @@ -59,7 +59,7 @@ export class ArmatureSystem extends System { * @en Add the ArmatureDisplay components into ArmatureSystem system. * @zh 将龙骨组件添加到系统中。 */ - public add (armature: ArmatureDisplay | null) { + public add (armature: ArmatureDisplay | null): void { if (!armature) return; if (!this._armatures.has(armature)) { this._armatures.add(armature); @@ -69,7 +69,7 @@ export class ArmatureSystem extends System { * @en Remove the ArmatureDisplay components from ArmatureSystem system. * @zh 将龙骨组件从系统移除。 */ - public remove (armature: ArmatureDisplay | null) { + public remove (armature: ArmatureDisplay | null): void { if (!armature) return; if (this._armatures.has(armature)) { this._armatures.delete(armature); @@ -79,11 +79,11 @@ export class ArmatureSystem extends System { * @en Trigger animation update of Armature objects. * @zh 触发更新龙骨动画。 */ - postUpdate (dt: number) { + postUpdate (dt: number): void { if (!this._armatures) { return; } - this._armatures.forEach((armature) => { + this._armatures.forEach((armature): void => { armature.updateAnimation(dt); armature.syncAttachedNode(); }); @@ -94,11 +94,11 @@ export class ArmatureSystem extends System { * @zh * 触发标记更新所有龙骨组件的渲染数据。 */ - public prepareRenderData () { + public prepareRenderData (): void { if (!this._armatures) { return; } - this._armatures.forEach((armature) => { + this._armatures.forEach((armature): void => { armature.markForUpdateRenderData(); }); } diff --git a/cocos/dragon-bones/AttachUtil.ts b/cocos/dragon-bones/AttachUtil.ts index 73dcb416a54..d804aa1021b 100644 --- a/cocos/dragon-bones/AttachUtil.ts +++ b/cocos/dragon-bones/AttachUtil.ts @@ -54,7 +54,7 @@ export class AttachUtil { * @en Initializes parameters. * @zh 初始化参数设置。 */ - init (armatureDisplay: ArmatureDisplay) { + init (armatureDisplay: ArmatureDisplay): void { this._inited = true; this._armature = armatureDisplay._armature; this._armatureNode = armatureDisplay.node; @@ -64,7 +64,7 @@ export class AttachUtil { * @en Resets parameter values. * @zh 重置参数设置。 */ - reset () { + reset (): void { this._inited = false; this._armature = null; this._armatureNode = null; @@ -74,7 +74,7 @@ export class AttachUtil { * @en Synchronize transformation of nodes attached to bones. * @zh 同步变换附着在骨骼上节点。 */ - _syncAttachedNode () { + _syncAttachedNode (): void { if (!this._inited) return; const rootMatrix = this._armatureNode!.worldMatrix; @@ -88,7 +88,7 @@ export class AttachUtil { const sockets = this._armatureDisplay!.sockets; const socketNodes = this._armatureDisplay!.socketNodes; - const matrixHandle = (node: Node, boneMat: Matrix) => { + const matrixHandle = (node: Node, boneMat: Matrix): void => { const tm = _tempMat4; tm.m00 = boneMat.a; tm.m01 = boneMat.b; diff --git a/cocos/dragon-bones/CCArmatureDisplay.ts b/cocos/dragon-bones/CCArmatureDisplay.ts index 6877df40744..d4987a860db 100644 --- a/cocos/dragon-bones/CCArmatureDisplay.ts +++ b/cocos/dragon-bones/CCArmatureDisplay.ts @@ -42,7 +42,7 @@ export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { * @en Return this. * @zh 返回自身。 */ - get node () { return this; } + get node (): CCArmatureDisplay { return this; } /** * @deprecated This variable will be removed in the future. */ @@ -98,7 +98,7 @@ export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { * @en Sets EventTarget object. * @zh 设置事件目标。 */ - setEventTarget (eventTarget: EventTarget) { + setEventTarget (eventTarget: EventTarget): void { this._eventTarget = eventTarget; } /** @@ -122,7 +122,7 @@ export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { * @en Convert pos to parent slot coordination. * @zh 将坐标转换到父插槽的坐标系下。 */ - convertToRootSpace (pos: Vec3) { + convertToRootSpace (pos: Vec3): Vec3 { const slot = this._armature!._parent as CCSlot; if (!slot) { return pos; @@ -139,7 +139,7 @@ export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { * @en Convert pos to world coordination. * @zh 将坐标转换到世界坐标系下。 */ - convertToWorldSpace (point: Vec3) { + convertToWorldSpace (point: Vec3): Vec3 | undefined { const newPos = this.convertToRootSpace(point); const ccNode = this.getRootNode(); return ccNode?._uiProps.uiTransformComp?.convertToWorldSpaceAR(newPos); @@ -148,7 +148,7 @@ export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { * @en Get the node of root ArmatureDisplay component in. * @zh 获取顶层 ArmatureDisplay 组件所在的 node。 */ - getRootNode () { + getRootNode (): Node | null { const rootDisplay = this.getRootDisplay(); return rootDisplay && rootDisplay._ccNode; } @@ -158,21 +158,21 @@ export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { * @zh 初始时设置骨架。 */ // dragonbones api - dbInit (armature: Armature | null) { + dbInit (armature: Armature | null): void { this._armature = armature; } /** * @en Clears Armature object. * @zh 清除骨架对象。 */ - dbClear () { + dbClear (): void { this._armature = null; } /** * @en Trigger ArmatureDisplay component to update render data. * @zh 触发 ArmatureDisplay 组件更新渲染数据。 */ - dbUpdate () { + dbUpdate (): void { if (this._ccComponent) { this._ccComponent.markForUpdateRenderData(); } @@ -181,23 +181,23 @@ export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { * @engineInternal Since v3.7.2. * @deprecated This variable will be removed in the future. */ - advanceTimeBySelf (on: boolean | number) { + advanceTimeBySelf (on: boolean | number): void { this.shouldAdvanced = !!on; } - hasDBEventListener (type) { + hasDBEventListener (type): boolean { return this._eventTarget.hasEventListener(type); } - addDBEventListener (type: string, listener, target) { + addDBEventListener (type: string, listener, target): void { this._eventTarget.on(type, listener, target); } - removeDBEventListener (type: string, listener, target) { + removeDBEventListener (type: string, listener, target): void { this._eventTarget.off(type, listener, target); } - dispatchDBEvent (type: string, eventObject) { + dispatchDBEvent (type: string, eventObject): void { this._eventTarget.emit(type, eventObject); } } diff --git a/cocos/dragon-bones/CCFactory.ts b/cocos/dragon-bones/CCFactory.ts index 0fb44d7805f..dfe8a6f9d7d 100644 --- a/cocos/dragon-bones/CCFactory.ts +++ b/cocos/dragon-bones/CCFactory.ts @@ -23,7 +23,7 @@ */ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; -import { Armature, BaseObject, Animation, BaseFactory, DragonBones } from '@cocos/dragonbones-js'; +import { Armature, BaseObject, Animation, BaseFactory, DragonBones, DragonBonesData, DisplayData } from '@cocos/dragonbones-js'; import { ISchedulable, Scheduler, System, _decorator } from '../core'; import { CCTextureAtlasData } from './CCTextureData'; import { TextureBase } from '../asset/assets/texture-base'; @@ -62,7 +62,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @example * let factory = CCFactory.getInstance(); */ - static getInstance () { + static getInstance (): CCFactory { if (!CCFactory._factory) { CCFactory._factory = new CCFactory(); } @@ -99,7 +99,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @en Sets CCFactory object null when Restart game. * @zh 重启时需将工厂实例置空。 */ - onRestart () { + onRestart (): void { CCFactory._factory = null; } @@ -107,7 +107,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @en Initialize update schedule. * @zh 初始化更新计划。 */ - initUpdate (dt?: number) { + initUpdate (dt?: number): void { // director.getScheduler().enableForTarget(this); Scheduler.enableForTarget(this); director.getScheduler().scheduleUpdate(this, System.Priority.HIGH, false); @@ -116,7 +116,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @en Trigger ArmatureDisplay components to update animation and render data. * @zh 触发 ArmatureDisplay 组件更新动画和渲染数据。 */ - update (dt: number) { + update (dt: number): void { if (EDITOR_NOT_IN_PREVIEW) return; this._dragonBones.advanceTime(dt); } @@ -124,7 +124,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @en Parser raw data to DragonBonesData. * @zh 从 raw data 解析出 DragonBonesData 数据。 */ - getDragonBonesDataByRawData (rawData: any) { + getDragonBonesDataByRawData (rawData: any): DragonBonesData | null { const dataParser = rawData instanceof ArrayBuffer ? BaseFactory._binaryParser : this._dataParser; return dataParser.parseDragonBonesData(rawData, 1.0); } @@ -133,7 +133,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @zh 创建骨架的显示数据。 */ // Build new armature with a new display. - buildArmatureDisplay (armatureName: string, dragonBonesName?: string, skinName?: string, textureAtlasName?: string) { + buildArmatureDisplay (armatureName: string, dragonBonesName?: string, skinName?: string, textureAtlasName?: string): DisplayData | null { const armature = this.buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName); return armature ? armature._display : null; } @@ -145,7 +145,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @en Create a new node with Dragonbones component. * @zh 创建一个附带龙骨组件的 node 节点。 */ - createArmatureNode (comp: ArmatureDisplay, armatureName: string, node?: Node) { + createArmatureNode (comp: ArmatureDisplay, armatureName: string, node?: Node): ArmatureDisplay { node = node || new Node(); let display = node.getComponent('dragonBones.ArmatureDisplay') as ArmatureDisplay; if (!display) { @@ -162,7 +162,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { return display; } - _buildTextureAtlasData (textureAtlasData: null | CCTextureAtlasData, textureAtlas?: TextureBase) { + _buildTextureAtlasData (textureAtlasData: null | CCTextureAtlasData, textureAtlas?: TextureBase): CCTextureAtlasData { if (textureAtlasData) { textureAtlasData.renderTexture = textureAtlas!; } else { @@ -171,7 +171,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { return textureAtlasData; } - _sortSlots () { + _sortSlots (): void { const slots = this._slots!; const sortedSlots: CCSlot[] = []; for (let i = 0, l = slots.length; i < l; i++) { @@ -191,7 +191,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { } this._slots = sortedSlots; } - _buildArmature (dataPackage) { + _buildArmature (dataPackage): Armature { const armature = BaseObject.borrowObject(Armature); armature._skinData = dataPackage.skin; @@ -211,7 +211,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { return armature; } - _buildSlot (dataPackage, slotData, displays) { + _buildSlot (dataPackage, slotData, displays): CCSlot { const slot = BaseObject.borrowObject(CCSlot); const display = slot; slot.init(slotData, displays, display, display); @@ -221,7 +221,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @en Gets DragonBonesData object by UUID. * @zh 通过 UUID 获取 DragonBonesData object。 */ - getDragonBonesDataByUUID (uuid) { + getDragonBonesDataByUUID (uuid): DragonBonesData | null { for (const name in this._dragonBonesDataMap) { if (name.indexOf(uuid) !== -1) { return this._dragonBonesDataMap[name]; @@ -233,7 +233,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { * @en Remove DragonBonesData object from cache by UUID. * @zh 通过 UUID 从缓存移除 DragonBonesData object。 */ - removeDragonBonesDataByUUID (uuid: string, disposeData?: boolean) { + removeDragonBonesDataByUUID (uuid: string, disposeData?: boolean): void { if (disposeData === undefined) { disposeData = true; } for (const name in this._dragonBonesDataMap) { if (name.indexOf(uuid) === -1) continue; diff --git a/cocos/dragon-bones/CCSlot.ts b/cocos/dragon-bones/CCSlot.ts index 4cfe6abd905..94f905998e1 100644 --- a/cocos/dragon-bones/CCSlot.ts +++ b/cocos/dragon-bones/CCSlot.ts @@ -36,7 +36,7 @@ const { ccclass } = _decorator; */ @ccclass('dragonBones.CCSlot') export class CCSlot extends Slot { - static toString () { + static toString (): string { return '[class dragonBones.CCSlot]'; } @@ -94,7 +94,7 @@ export class CCSlot extends Slot { * @returns @en A texture instance if _textureData is not null, otherwise returns null. * @zh 若 _textureData 为 null,将返回 null。 */ - getTexture () { + getTexture (): Texture2D | null { if (this._textureData) { const sp = (this._textureData as any).spriteFrame; const tex = sp.texture as Texture2D; @@ -106,7 +106,7 @@ export class CCSlot extends Slot { * @en Calculates world matrix of slot. * @zh 计算插槽世界矩阵。 */ - calculWorldMatrix () { + calculWorldMatrix (): void { const parent = this._armature._parent as CCSlot; if (parent) { this._mulMat(this._worldMatrix, parent._worldMatrix, this._matrix); @@ -120,7 +120,7 @@ export class CCSlot extends Slot { * @en Resets slot data and state. * @zh 重置插槽数据和状态。 */ - _onClear () { + _onClear (): void { super._onClear(); this._localVertices.length = 0; this._indices.length = 0; @@ -134,32 +134,32 @@ export class CCSlot extends Slot { * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _onUpdateDisplay () { + _onUpdateDisplay (): void { } /** * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _initDisplay (value) { + _initDisplay (value): void { } /** * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _addDisplay () { + _addDisplay (): void { this._visible = true; } /** * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _replaceDisplay (value) { + _replaceDisplay (value): void { } /** * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _removeDisplay () { + _removeDisplay (): void { this._visible = false; } @@ -167,20 +167,20 @@ export class CCSlot extends Slot { * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _disposeDisplay (object) { + _disposeDisplay (object): void { } /** * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _updateVisible () { + _updateVisible (): void { this._visible = this.parent.visible; } /** * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _updateGlueMesh () { + _updateGlueMesh (): void { } @@ -188,13 +188,13 @@ export class CCSlot extends Slot { * just for adapt to dragonbones api,no need to do any thing * @deprecated Since v3.7.2, this interface that will be removed in the future. */ - _updateZOrder () { + _updateZOrder (): void { } /** * @en Update the color blending mode of the slot. * @zh 更新插槽的颜色混合模式。 */ - _updateBlendMode () { + _updateBlendMode (): void { if (this._childArmature) { const childSlots = this._childArmature.getSlots(); for (let i = 0, l = childSlots.length; i < l; i++) { @@ -208,7 +208,7 @@ export class CCSlot extends Slot { * @en Update the color of the slot. * @zh 更新插槽的颜色。 */ - _updateColor () { + _updateColor (): void { const c = this._color; c.r = this._colorTransform.redMultiplier * 255; c.g = this._colorTransform.greenMultiplier * 255; @@ -219,7 +219,7 @@ export class CCSlot extends Slot { * @en Update one frame of slot vertex data. * @zh 更新一帧插槽顶点数据。 */ - _updateFrame () { + _updateFrame (): void { this._indices.length = 0; const indices = this._indices; const localVertices = this._localVertices; @@ -325,7 +325,7 @@ export class CCSlot extends Slot { * @en Update mesh data of slot. * @zh 更新槽点的网格数据。 */ - _updateMesh () { + _updateMesh (): void { const scale = this._armature._armatureData.scale; const deformVertices = this._deformVertices.vertices; const bones = this._deformVertices.bones; @@ -412,7 +412,7 @@ export class CCSlot extends Slot { * @en Reset current matrix to identity matrix. * @zh 重置当前矩阵为单位矩阵。 */ - _identityTransform () { + _identityTransform (): void { const m = this._matrix; m.m00 = 1.0; m.m01 = 0.0; @@ -426,7 +426,7 @@ export class CCSlot extends Slot { * @en Update transform of slot. * @zh 更新插槽的变换。 */ - _updateTransform () { + _updateTransform (): void { const m = this._matrix; m.m00 = this.globalTransformMatrix.a; m.m01 = this.globalTransformMatrix.b; @@ -446,7 +446,7 @@ export class CCSlot extends Slot { * @en Update world matrix of slot. * @zh 更新插槽的世界矩阵。 */ - updateWorldMatrix () { + updateWorldMatrix (): void { if (!this._armature) return; const parentSlot = this._armature._parent as CCSlot; @@ -470,7 +470,7 @@ export class CCSlot extends Slot { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - /* protected */ _mulMat (out: Mat4, a: Readonly, b: Readonly) { + /* protected */ _mulMat (out: Mat4, a: Readonly, b: Readonly): void { const aa = a.m00; const ab = a.m01; const ac = a.m04; const ad = a.m05; const atx = a.m12; const aty = a.m13; const ba = b.m00; const bb = b.m01; const bc = b.m04; const bd = b.m05; const btx = b.m12; const bty = b.m13; if (ab !== 0 || ac !== 0) { diff --git a/cocos/dragon-bones/CCTextureData.ts b/cocos/dragon-bones/CCTextureData.ts index f48a221c2b4..efc072123fc 100644 --- a/cocos/dragon-bones/CCTextureData.ts +++ b/cocos/dragon-bones/CCTextureData.ts @@ -39,7 +39,7 @@ export class CCTextureAtlasData extends TextureAtlasData { * @en The texture used for rendering. * @zh 实际用于渲染显示的纹理对象。 */ - get renderTexture () { + get renderTexture (): TextureBase | null { return this._renderTexture; } @@ -78,21 +78,21 @@ export class CCTextureAtlasData extends TextureAtlasData { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - static toString () { + static toString (): string { return '[class dragonBones.CCTextureAtlasData]'; } /** * @en Create texture data, get data from the object pool. * @zh 创建纹理数据,从对象池获取。 */ - createTexture () { + createTexture (): CCTextureData { return BaseObject.borrowObject(CCTextureData); } /** * @en Clear associated texture resources. * @zh 清除关联的纹理。 */ - _onClear () { + _onClear (): void { super._onClear(); this.renderTexture = null; } @@ -111,14 +111,14 @@ export class CCTextureData extends TextureData { /** * @engineInternal Since v3.7.2 this is an engine private function. */ - static toString () { + static toString (): string { return '[class dragonBones.CCTextureData]'; } /** * @en Clear SpriteFrame assets. * @zh 清除关联的SpriteFrame 资源。 */ - _onClear () { + _onClear (): void { super._onClear(); this.spriteFrame = null; } diff --git a/cocos/dragon-bones/DragonBonesAsset.ts b/cocos/dragon-bones/DragonBonesAsset.ts index a01d8e8ddf0..420280ee59b 100644 --- a/cocos/dragon-bones/DragonBonesAsset.ts +++ b/cocos/dragon-bones/DragonBonesAsset.ts @@ -49,7 +49,7 @@ export class DragonBonesAsset extends Asset { @serializable protected _dragonBonesJson = ''; - get dragonBonesJson () { + get dragonBonesJson (): string { return this._dragonBonesJson; } @@ -64,14 +64,14 @@ export class DragonBonesAsset extends Asset { private _armaturesEnum: any = null; - constructctor () { + constructctor (): void { this.reset(); } /** * @en Create a new node with Dragonbones component. * @zh 创建一个附带龙骨组件的 node 节点。 */ - createNode (callback: (err: Error | null, node: Node) => void) { + createNode (callback: (err: Error | null, node: Node) => void): void { const node = new Node(this.name); const armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay') as any; armatureDisplay.dragonAsset = this; @@ -82,7 +82,7 @@ export class DragonBonesAsset extends Asset { * @en Reset DragonBonesAsset data and state. * @zh 重置 DragonBonesAsset 数据和状态。 */ - reset () { + reset (): void { this._clear(); if (EDITOR_NOT_IN_PREVIEW) { this._armaturesEnum = null; @@ -95,7 +95,7 @@ export class DragonBonesAsset extends Asset { * @zh 全局的 CCFactory 对象。 * @param atlasUUID @en Atlas uuid. @zh Atlas uuid。 */ - init (factory?: CCFactory, atlasUUID?: string) { + init (factory?: CCFactory, atlasUUID?: string): string { this._factory = factory || CCFactory.getInstance(); if (!this._dragonBonesJsonData && this.dragonBonesJson) { @@ -152,7 +152,7 @@ export class DragonBonesAsset extends Asset { /** * @engineInternal Since v3.7.2, this is an engine private function. */ - public getAnimsEnum (armatureName: string) { + public getAnimsEnum (armatureName: string): { '': number; } | null { this.init(); const dragonBonesData = this._factory!.getDragonBonesDataByUUID(this._uuid); if (dragonBonesData) { @@ -179,12 +179,12 @@ export class DragonBonesAsset extends Asset { * @en Destroy DragonBonesAsset data. * @zh 销毁 DragonBonesAsset 资产数据。 */ - public destroy () { + public destroy (): boolean { this._clear(); return super.destroy(); } - protected _clear () { + protected _clear (): void { if (this._factory) { ArmatureCache.sharedCache.resetArmature(this._uuid); this._factory.removeDragonBonesDataByUUID(this._uuid, true); diff --git a/cocos/dragon-bones/DragonBonesAtlasAsset.ts b/cocos/dragon-bones/DragonBonesAtlasAsset.ts index ccd27e5bca4..fa72c13ff21 100644 --- a/cocos/dragon-bones/DragonBonesAtlasAsset.ts +++ b/cocos/dragon-bones/DragonBonesAtlasAsset.ts @@ -51,7 +51,7 @@ export class DragonBonesAtlasAsset extends Asset { */ @serializable _atlasJson = ''; - get atlasJson () { + get atlasJson (): string { return this._atlasJson; } set atlasJson (value) { @@ -83,7 +83,7 @@ export class DragonBonesAtlasAsset extends Asset { * @zh 2D 纹理。 * @property {Texture2D} texture */ - get texture () { + get texture (): Texture2D | null { return this._texture; } set texture (value) { @@ -101,7 +101,7 @@ export class DragonBonesAtlasAsset extends Asset { * @en Create a new node with Dragonbones component. * @zh 创建一个附带龙骨组件的 node 节点。 */ - createNode (callback: (error: Error | null, node: Node) => void) { + createNode (callback: (error: Error | null, node: Node) => void): void { const node = new Node(this.name); const armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay') as ArmatureDisplay; armatureDisplay.dragonAtlasAsset = this; @@ -114,7 +114,7 @@ export class DragonBonesAtlasAsset extends Asset { * TextureAtlasData instance, and cache it to the factory. * @zh 图集资源初始化。将原始贴图集数据和贴图集对象解析为 TextureAtlasData 实例,并缓存到工厂中。 */ - init (factory: CCFactory) { + init (factory: CCFactory): void { this._factory = factory; if (!this._atlasJsonData) { @@ -135,12 +135,12 @@ export class DragonBonesAtlasAsset extends Asset { * @en Destroy altas assets. * @zh 销毁图集资源。 */ - destroy () { + destroy (): boolean { this._clear(); return super.destroy(); } - protected _clear () { + protected _clear (): void { if (JSB) return; if (this._factory) { ArmatureCache.sharedCache.resetArmature(this._uuid); diff --git a/cocos/dragon-bones/assembler/simple.ts b/cocos/dragon-bones/assembler/simple.ts index 2a70595a455..5d579e472df 100644 --- a/cocos/dragon-bones/assembler/simple.ts +++ b/cocos/dragon-bones/assembler/simple.ts @@ -83,7 +83,7 @@ const _slotMat = new Mat4(); let _currentMaterial: MaterialInstance | null = null; let _currentTexture: Texture2D | null = null; -function _getSlotMaterial (tex: TextureBase | null, blendMode: BlendMode) { +function _getSlotMaterial (tex: TextureBase | null, blendMode: BlendMode): MaterialInstance | null { if (!tex) return null; let src: BlendFactor; @@ -110,7 +110,7 @@ function _getSlotMaterial (tex: TextureBase | null, blendMode: BlendMode) { return _comp!.getMaterialForBlend(src, dst); } -function _handleColor (color: {r: number, g: number, b: number, a: number}, parentOpacity: number) { +function _handleColor (color: {r: number, g: number, b: number, a: number}, parentOpacity: number): void { const _a = color.a * parentOpacity * _nodeA; const _multiply = _premultipliedAlpha ? _a / 255.0 : 1.0; const _r = color.r * _nodeR * _multiply / 255.0; @@ -131,7 +131,7 @@ let _accessor: StaticVBAccessor = null!; export const simple: IAssembler = { accessor: _accessor, vCount: 32767, - ensureAccessor () { + ensureAccessor (): StaticVBAccessor { if (!_accessor) { const device = director.root!.device; const batcher = director.root!.batcher2D; @@ -143,7 +143,7 @@ export const simple: IAssembler = { return this.accessor as StaticVBAccessor; }, - createData (comp: ArmatureDisplay) { + createData (comp: ArmatureDisplay): RenderData { let rd = comp.renderData; if (!rd) { this.ensureAccessor() as StaticVBAccessor; @@ -170,7 +170,7 @@ export const simple: IAssembler = { return rd; }, - updateRenderData (comp: ArmatureDisplay, batcher: Batcher2D) { + updateRenderData (comp: ArmatureDisplay, batcher: Batcher2D): void { _comp = comp; const armature = comp._armature; if (armature) { @@ -178,13 +178,13 @@ export const simple: IAssembler = { } }, - updateColor (comp: ArmatureDisplay) { + updateColor (comp: ArmatureDisplay): void { if (!comp) return; _comp = comp; _comp.markForUpdateRenderData(); }, }; -function realTimeTraverse (armature: Armature, parentOpacity: number, worldMat?: Mat4) { +function realTimeTraverse (armature: Armature, parentOpacity: number, worldMat?: Mat4): void { const rd = _renderData!; _vbuf = rd.chunk.vb; _ibuf = rd.indices!; @@ -311,7 +311,7 @@ function realTimeTraverse (armature: Armature, parentOpacity: number, worldMat?: } } -function cacheTraverse (frame: ArmatureFrame | null, parentMat?: Mat4) { +function cacheTraverse (frame: ArmatureFrame | null, parentMat?: Mat4): void { if (!frame) return; const segments = frame.segments; if (segments.length === 0) return; @@ -406,7 +406,7 @@ function cacheTraverse (frame: ArmatureFrame | null, parentMat?: Mat4) { } } -function updateComponentRenderData (comp: ArmatureDisplay, batcher: Batcher2D) { +function updateComponentRenderData (comp: ArmatureDisplay, batcher: Batcher2D): void { // comp.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; const armature = comp._armature; diff --git a/cocos/game/deprecated.ts b/cocos/game/deprecated.ts index be18b48f9b9..aa520d7d363 100644 --- a/cocos/game/deprecated.ts +++ b/cocos/game/deprecated.ts @@ -93,7 +93,7 @@ replaceProperty(director, 'director', [ name: '_getSceneUuid', targetName: 'assetManager.main', newName: 'getSceneInfo', - customFunction: (sceneName) => { + customFunction: (sceneName): string | undefined => { if (assetManager.main) { return assetManager.main.getSceneInfo(sceneName)?.uuid; } @@ -118,10 +118,10 @@ replaceProperty(game, 'game', [ name: '_sceneInfos', targetName: 'assetManager.main', newName: 'getSceneInfo', - customGetter: () => { + customGetter: (): ISceneInfo[] => { const scenes: ISceneInfo[] = []; if (assetManager.main) { - assetManager.main.config.scenes.forEach((val) => { + assetManager.main.config.scenes.forEach((val): void => { scenes.push(val); }); } diff --git a/cocos/game/director.ts b/cocos/game/director.ts index c8e9fdcc4b0..8f6b250a707 100644 --- a/cocos/game/director.ts +++ b/cocos/game/director.ts @@ -225,14 +225,14 @@ export class Director extends EventTarget { * @zh 计算从上一帧到现在的时间间隔,结果保存在私有属性中 * @deprecated since v3.3.0 no need to use it anymore */ - public calculateDeltaTime (now) {} + public calculateDeltaTime (now): void {} /** * @en End the life of director in the next frame * @zh 执行完当前帧后停止 director 的执行 */ - public end () { - this.once(Director.EVENT_END_FRAME, () => { + public end (): void { + this.once(Director.EVENT_END_FRAME, (): void => { this.purgeDirector(); }); } @@ -245,7 +245,7 @@ export class Director extends EventTarget { * @zh 暂停正在运行的场景,该暂停只会停止游戏逻辑执行,但是不会停止渲染和 UI 响应。
* 如果想要更彻底得暂停游戏,包含渲染,音频和事件,请使用 `game.pause` 。 */ - public pause () { + public pause (): void { if (this._paused) { return; } @@ -258,7 +258,7 @@ export class Director extends EventTarget { * @zh 清除 `director` 本身,包括停止所有的计时器,
* 移除所有的事件监听器,清理并退出当前运行的场景,停止所有动画,清理缓存数据。 */ - public purgeDirector () { + public purgeDirector (): void { // cleanup scheduler this._scheduler.unscheduleAll(); this._compScheduler.unscheduleAll(); @@ -282,7 +282,7 @@ export class Director extends EventTarget { * @en Reset the director, can be used to restart the director after purge * @zh 重置此 Director,可用于在清除后重启 Director。 */ - public reset () { + public reset (): void { this.purgeDirector(); for (const id in this._persistRootNodes) { @@ -306,7 +306,7 @@ export class Director extends EventTarget { * @param onBeforeLoadScene - The function invoked at the scene before loading. * @param onLaunched - The function invoked at the scene after launch. */ - public runSceneImmediate (scene: Scene | SceneAsset, onBeforeLoadScene?: Director.OnBeforeLoadScene, onLaunched?: Director.OnSceneLaunched) { + public runSceneImmediate (scene: Scene | SceneAsset, onBeforeLoadScene?: Director.OnBeforeLoadScene, onLaunched?: Director.OnSceneLaunched): void { if (scene instanceof SceneAsset) scene = scene.scene!; assertID(scene instanceof Scene, 1216); @@ -321,7 +321,7 @@ export class Director extends EventTarget { if (BUILD && DEBUG) { console.time('AttachPersist'); } - const persistNodeList = Object.keys(this._persistRootNodes).map((x) => this._persistRootNodes[x] as Node); + const persistNodeList = Object.keys(this._persistRootNodes).map((x): Node => this._persistRootNodes[x] as Node); for (let i = 0; i < persistNodeList.length; i++) { const node = persistNodeList[i]; node.emit(Node.EventType.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene); @@ -404,13 +404,13 @@ export class Director extends EventTarget { * @param onLaunched - The function invoked at the scene after launch. * @private */ - public runScene (scene: Scene | SceneAsset, onBeforeLoadScene?: Director.OnBeforeLoadScene, onLaunched?: Director.OnSceneLaunched) { + public runScene (scene: Scene | SceneAsset, onBeforeLoadScene?: Director.OnBeforeLoadScene, onLaunched?: Director.OnSceneLaunched): void { if (scene instanceof SceneAsset) scene = scene.scene!; assertID(scene, 1205); assertID(scene instanceof Scene, 1216); // Delay run / replace scene to the end of the frame - this.once(Director.EVENT_END_FRAME, () => { + this.once(Director.EVENT_END_FRAME, (): void => { this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched); }); } @@ -423,17 +423,17 @@ export class Director extends EventTarget { * @param onLaunched - callback, will be called after scene launched. * @return if error, return false */ - public loadScene (sceneName: string, onLaunched?: Director.OnSceneLaunched, onUnloaded?: Director.OnUnload) { + public loadScene (sceneName: string, onLaunched?: Director.OnSceneLaunched, onUnloaded?: Director.OnUnload): boolean { if (this._loadingScene) { warnID(1208, sceneName, this._loadingScene); return false; } - const bundle = assetManager.bundles.find((bundle) => !!bundle.getSceneInfo(sceneName)); + const bundle = assetManager.bundles.find((bundle): boolean => !!bundle.getSceneInfo(sceneName)); if (bundle) { this.emit(Director.EVENT_BEFORE_SCENE_LOADING, sceneName); this._loadingScene = sceneName; console.time(`LoadScene ${sceneName}`); - bundle.loadScene(sceneName, (err, scene) => { + bundle.loadScene(sceneName, (err, scene): void => { console.timeEnd(`LoadScene ${sceneName}`); this._loadingScene = ''; if (err) { @@ -485,8 +485,8 @@ export class Director extends EventTarget { sceneName: string, onProgress?: Director.OnLoadSceneProgress | Director.OnSceneLoaded, onLoaded?: Director.OnSceneLoaded, - ) { - const bundle = assetManager.bundles.find((bundle) => !!bundle.getSceneInfo(sceneName)); + ): void { + const bundle = assetManager.bundles.find((bundle): boolean => !!bundle.getSceneInfo(sceneName)); if (bundle) { // NOTE: the similar function signatures but defined as deferent function types. bundle.preloadScene(sceneName, null, onProgress as (finished: number, total: number, item: any) => void, @@ -504,14 +504,14 @@ export class Director extends EventTarget { * @en Resume game logic execution after pause, if the current scene is not paused, nothing will happen. * @zh 恢复暂停场景的游戏逻辑,如果当前场景没有暂停将没任何事情发生。 */ - public resume () { + public resume (): void { if (!this._paused) { return; } this._paused = false; } - get root () { + get root (): Root | null { return this._root; } @@ -534,7 +534,7 @@ export class Director extends EventTarget { * @zh 获取上一帧的增量时间。 * @deprecated since v3.3.0, please use game.deltaTime instead */ - public getDeltaTime () { + public getDeltaTime (): number { return cclegacy.game.deltaTime as number; } @@ -543,7 +543,7 @@ export class Director extends EventTarget { * @zh 获取从游戏开始到现在总共经过的时间,单位为 ms * @deprecated since v3.3.0, please use game.totalTime instead */ - public getTotalTime () { + public getTotalTime (): number { return cclegacy.game.totalTime as number; } @@ -552,7 +552,7 @@ export class Director extends EventTarget { * @zh 获取当前帧的时间。 * @deprecated since v3.3.0, please use game.frameStartTime instead */ - public getCurrentTime () { + public getCurrentTime (): number { return cclegacy.game.frameStartTime as number; } @@ -560,7 +560,7 @@ export class Director extends EventTarget { * @en Returns how many frames were called since the director started. * @zh 获取 director 启动以来游戏运行的总帧数。 */ - public getTotalFrames () { + public getTotalFrames (): number { return this._totalFrames; } @@ -568,7 +568,7 @@ export class Director extends EventTarget { * @en Returns whether or not the Director is paused. * @zh 是否处于暂停状态。 */ - public isPaused () { + public isPaused (): boolean { return this._paused; } @@ -576,7 +576,7 @@ export class Director extends EventTarget { * @en Returns the scheduler associated with this director. * @zh 获取和 director 相关联的调度器。 */ - public getScheduler () { + public getScheduler (): Scheduler { return this._scheduler; } @@ -584,7 +584,7 @@ export class Director extends EventTarget { * @en Sets the scheduler associated with this director. * @zh 设置和 director 相关联的调度器。 */ - public setScheduler (scheduler: Scheduler) { + public setScheduler (scheduler: Scheduler): void { if (this._scheduler !== scheduler) { this.unregisterSystem(this._scheduler); this._scheduler = scheduler; @@ -596,14 +596,14 @@ export class Director extends EventTarget { * @en Register a system. * @zh 注册一个系统。 */ - public registerSystem (name: string, sys: System, priority: number) { + public registerSystem (name: string, sys: System, priority: number): void { sys.id = name; sys.priority = priority; this._systems.push(sys); this._systems.sort(System.sortByPriority); } - public unregisterSystem (sys: System) { + public unregisterSystem (sys: System): void { js.array.fastRemove(this._systems, sys); this._systems.sort(System.sortByPriority); } @@ -612,8 +612,8 @@ export class Director extends EventTarget { * @en get a system. * @zh 获取一个 system。 */ - public getSystem (name: string) { - return this._systems.find((sys) => sys.id === name); + public getSystem (name: string): System | undefined { + return this._systems.find((sys): boolean => sys.id === name); } /** @@ -630,7 +630,7 @@ export class Director extends EventTarget { * @en Starts the director * @zh 开始执行游戏逻辑 */ - public startAnimation () { + public startAnimation (): void { this._invalid = false; } @@ -638,7 +638,7 @@ export class Director extends EventTarget { * @en Stops the director * @zh 停止执行游戏逻辑,每帧渲染会继续执行 */ - public stopAnimation () { + public stopAnimation (): void { this._invalid = true; } @@ -647,7 +647,7 @@ export class Director extends EventTarget { * @zh 运行主循环 * @deprecated Since v3.6, please use [tick] instead */ - public mainLoop (now: number) { + public mainLoop (now: number): void { let dt; if (EDITOR_NOT_IN_PREVIEW || TEST) { dt = now; @@ -662,7 +662,7 @@ export class Director extends EventTarget { * @zh 运行主循环 * @param dt Delta time in seconds */ - public tick (dt: number) { + public tick (dt: number): void { if (!this._invalid) { this.emit(Director.EVENT_BEGIN_FRAME); if (!EDITOR_NOT_IN_PREVIEW) { @@ -706,7 +706,7 @@ export class Director extends EventTarget { } } - private buildRenderPipeline () { + private buildRenderPipeline (): void { if (this._root) { this._root.customPipeline.beginSetup(); const builder = cclegacy.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME); @@ -715,7 +715,7 @@ export class Director extends EventTarget { } } - private setupRenderPipelineBuilder () { + private setupRenderPipelineBuilder (): void { if (macro.CUSTOM_PIPELINE_NAME !== '' && cclegacy.rendering && this._root && this._root.usesCustomPipeline) { this.on(Director.EVENT_BEFORE_RENDER, this.buildRenderPipeline, this); } @@ -724,7 +724,7 @@ export class Director extends EventTarget { /** * @internal */ - public init () { + public init (): void { this._totalFrames = 0; this._paused = false; // Scheduler @@ -752,7 +752,7 @@ export class Director extends EventTarget { * 目标节点必须位于为层级的根节点,否则无效。 * @param node - The node to be made persistent */ - public addPersistRootNode (node: Node) { + public addPersistRootNode (node: Node): void { if (!Node.isNode(node) || !node.uuid) { warnID(3800); return; @@ -785,7 +785,7 @@ export class Director extends EventTarget { * @zh 取消常驻根节点。 * @param node - The node to be removed from persistent node list */ - public removePersistRootNode (node: Node) { + public removePersistRootNode (node: Node): void { const id = node.uuid || ''; if (node === this._persistRootNodes[id]) { delete this._persistRootNodes[id]; diff --git a/cocos/game/game.ts b/cocos/game/game.ts index 4061e9b8921..5f3eac8149d 100644 --- a/cocos/game/game.ts +++ b/cocos/game/game.ts @@ -391,7 +391,7 @@ export class Game extends EventTarget { * @en Indicates whether the engine and the renderer has been initialized * @zh 引擎和渲染器是否以完成初始化 */ - public get inited () { + public get inited (): boolean { return this._inited; } @@ -399,7 +399,7 @@ export class Game extends EventTarget { * @en Expected frame rate of the game. * @zh 游戏的设定帧率。 */ - public get frameRate () { + public get frameRate (): string | number { return this._frameRate; } public set frameRate (frameRate: number | string) { @@ -426,7 +426,7 @@ export class Game extends EventTarget { * @en The total passed time since game start, unit: ms * @zh 获取从游戏开始到现在总共经过的时间,以毫秒为单位 */ - public get totalTime () { + public get totalTime (): number { return performance.now() - this._initTime; } @@ -434,7 +434,7 @@ export class Game extends EventTarget { * @en The start time of the current frame in milliseconds. * @zh 获取当前帧开始的时间(以 ms 为单位)。 */ - public get frameStartTime () { + public get frameStartTime (): number { return this._startTime; } @@ -519,7 +519,7 @@ export class Game extends EventTarget { * @zh 设置游戏帧率。 * @deprecated since v3.3.0 please use [[game.frameRate]] */ - public setFrameRate (frameRate: number | string) { + public setFrameRate (frameRate: number | string): void { this.frameRate = frameRate; } @@ -537,7 +537,7 @@ export class Game extends EventTarget { * @en Run the game frame by frame with a fixed delta time correspond to frame rate. * @zh 以固定帧间隔执行一帧游戏循环,帧间隔与设定的帧率匹配。 */ - public step () { + public step (): void { director.tick(this._calculateDT(true)); } @@ -545,7 +545,7 @@ export class Game extends EventTarget { * @en Called by the engine to pause the game. * @zh 提供给引擎调用暂停游戏接口。 */ - private pauseByEngine () { + private pauseByEngine (): void { if (this._paused) { return; } this._pausedByEngine = true; this.pause(); @@ -555,7 +555,7 @@ export class Game extends EventTarget { * @en Resume paused game by engine call. * @zh 提供给引擎调用恢复暂停游戏接口。 */ - private resumeByEngine () { + private resumeByEngine (): void { if (this._pausedByEngine) { this.resume(); this._pausedByEngine = false; @@ -577,7 +577,7 @@ export class Game extends EventTarget { * * 这点和只暂停游戏逻辑的 `director.pause()` 不同。 */ - public pause () { + public pause (): void { if (this._paused) { return; } this._paused = true; this._pacer?.stop(); @@ -589,7 +589,7 @@ export class Game extends EventTarget { * game logic execution, rendering process, event manager, background music and all audio effects.
* @zh 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。 */ - public resume () { + public resume (): void { if (!this._paused) { return; } input._clearEvents(); this._paused = false; @@ -610,8 +610,8 @@ export class Game extends EventTarget { * @zh 重新开始游戏 */ public restart (): Promise { - const endFramePromise = new Promise((resolve) => { director.once(Director.EVENT_END_FRAME, () => resolve()); }); - return endFramePromise.then(() => { + const endFramePromise = new Promise((resolve): void => { director.once(Director.EVENT_END_FRAME, (): void => resolve()); }); + return endFramePromise.then((): void => { director.reset(); cclegacy.Object._deferredDestroy(); this.pause(); @@ -626,7 +626,7 @@ export class Game extends EventTarget { * @en End game, it will close the game window * @zh 退出游戏 */ - public end () { + public end (): void { systemInfo.close(); } @@ -708,28 +708,28 @@ export class Game extends EventTarget { * -GameInitedEvent * @param config - Pass configuration object */ - public init (config: IGameConfig) { + public init (config: IGameConfig): Promise { this._compatibleWithOldParams(config); // DONT change the order unless you know what's you doing return Promise.resolve() // #region Base - .then(() => { + .then((): Promise => { this.emit(Game.EVENT_PRE_BASE_INIT); return this.onPreBaseInitDelegate.dispatch(); }) - .then(() => { + .then((): void => { if (DEBUG) { console.time('Init Base'); } const debugMode = config.debugMode || DebugMode.NONE; _resetDebugSetting(debugMode); }) - .then(() => sys.init()) - .then(() => { + .then((): Promise => sys.init()) + .then((): void => { this._initEvents(); }) - .then(() => settings.init(config.settingsPath, config.overrideSettings)) - .then(() => { + .then((): Promise => settings.init(config.settingsPath, config.overrideSettings)) + .then((): Promise => { if (DEBUG) { console.timeEnd('Init Base'); } @@ -738,11 +738,11 @@ export class Game extends EventTarget { }) // #endregion Base // #region Infrastructure - .then(() => { + .then((): Promise => { this.emit(Game.EVENT_PRE_INFRASTRUCTURE_INIT); return this.onPreInfrastructureInitDelegate.dispatch(); }) - .then(() => { + .then((): void => { if (DEBUG) { console.time('Init Infrastructure'); } @@ -768,18 +768,18 @@ export class Game extends EventTarget { console.timeEnd('Init Infrastructure'); } }) - .then(() => { + .then((): Promise => { this.emit(Game.EVENT_POST_INFRASTRUCTURE_INIT); return this.onPostInfrastructureInitDelegate.dispatch(); }) // #endregion Infrastructure // #region Subsystem - .then(() => { + .then((): Promise => { this.emit(Game.EVENT_PRE_SUBSYSTEM_INIT); return this.onPreSubsystemInitDelegate.dispatch(); }) - .then(() => effectSettings.init(settings.querySettings(Settings.Category.RENDERING, 'effectSettingsPath') as string)) - .then(() => { + .then((): Promise => effectSettings.init(settings.querySettings(Settings.Category.RENDERING, 'effectSettingsPath') as string)) + .then((): void => { // initialize custom render pipeline if (!cclegacy.rendering || !cclegacy.rendering.enableEffectImport) { return; @@ -796,60 +796,60 @@ export class Game extends EventTarget { } cclegacy.rendering.init(deviceManager.gfxDevice, data); }) - .then(() => { + .then((): Promise => { if (DEBUG) { console.time('Init SubSystem'); } director.init(); return builtinResMgr.loadBuiltinAssets(); }) - .then(() => { + .then((): Promise => { if (DEBUG) { console.timeEnd('Init SubSystem'); } this.emit(Game.EVENT_POST_SUBSYSTEM_INIT); return this.onPostSubsystemInitDelegate.dispatch(); }) - .then(() => { + .then((): void => { console.log(`Cocos Creator v${VERSION}`); this.emit(Game.EVENT_ENGINE_INITED); this._engineInited = true; }) // #endregion Subsystem // #region Project - .then(() => { + .then((): Promise => { this.emit(Game.EVENT_PRE_PROJECT_INIT); return this.onPreProjectInitDelegate.dispatch(); }) - .then(() => { + .then((): Promise => { if (DEBUG) { console.time('Init Project'); } const jsList = settings.querySettings(Settings.Category.PLUGINS, 'jsList'); let promise = Promise.resolve(); if (jsList) { - jsList.forEach((jsListFile) => { - promise = promise.then(() => loadJsFile(`${PREVIEW ? 'plugins' : 'src'}/${jsListFile}`)); + jsList.forEach((jsListFile): void => { + promise = promise.then((): any => loadJsFile(`${PREVIEW ? 'plugins' : 'src'}/${jsListFile}`)); }); } return promise; }) - .then(() => { + .then((): Promise => { const scriptPackages = settings.querySettings(Settings.Category.SCRIPTING, 'scriptPackages'); if (scriptPackages) { - return Promise.all(scriptPackages.map((pack) => import(pack))); + return Promise.all(scriptPackages.map((pack): Promise => import(pack))); } return Promise.resolve([]); }) - .then(() => this._loadProjectBundles()) - .then(() => this._loadCCEScripts()) - .then(() => this._setupRenderPipeline()) - .then(() => this._loadPreloadAssets()) - .then(() => { + .then((): Promise => this._loadProjectBundles()) + .then((): Promise => this._loadCCEScripts()) + .then((): void | Promise => this._setupRenderPipeline()) + .then((): Promise => this._loadPreloadAssets()) + .then((): Promise => { builtinResMgr.compileBuiltinMaterial(); return SplashScreen.instance.init(); }) - .then(() => { + .then((): Promise => { if (DEBUG) { console.timeEnd('Init Project'); } @@ -857,13 +857,13 @@ export class Game extends EventTarget { return this.onPostProjectInitDelegate.dispatch(); }) // #endregion Project - .then(() => { + .then((): void => { this._inited = true; this._safeEmit(Game.EVENT_GAME_INITED); }); } - private _initXR () { + private _initXR (): void { if (typeof globalThis.__globalXR === 'undefined') { globalThis.__globalXR = {}; } @@ -881,7 +881,7 @@ export class Game extends EventTarget { } } - private _compatibleWithOldParams (config: IGameConfig) { + private _compatibleWithOldParams (config: IGameConfig): void { const overrideSettings = config.overrideSettings = config.overrideSettings || {}; if ('showFPS' in config) { overrideSettings.profiling = overrideSettings.profiling || {}; @@ -921,11 +921,11 @@ export class Game extends EventTarget { } } - private _loadPreloadAssets () { + private _loadPreloadAssets (): Promise { const preloadAssets = settings.querySettings(Settings.Category.ASSETS, 'preloadAssets'); if (!preloadAssets) return Promise.resolve([]); - return Promise.all(preloadAssets.map((uuid) => new Promise((resolve, reject) => { - assetManager.loadAny(uuid, (err) => { + return Promise.all(preloadAssets.map((uuid): Promise => new Promise((resolve, reject): void => { + assetManager.loadAny(uuid, (err): void => { if (err) { reject(err); return; @@ -938,12 +938,12 @@ export class Game extends EventTarget { /** * @internal only for browser preview */ - private _loadCCEScripts () { - return new Promise((resolve, reject) => { + private _loadCCEScripts (): Promise { + return new Promise((resolve, reject): void => { // Since there is no script in the bundle during preview, we need to load the user's script in the following way if (PREVIEW && !TEST && !EDITOR && !NATIVE) { const bundneName = 'cce:/internal/x/prerequisite-imports'; - import(bundneName).then(() => resolve(), (reason) => reject(reason)); + import(bundneName).then((): void => resolve(), (reason): void => reject(reason)); } else { resolve(); } @@ -953,13 +953,13 @@ export class Game extends EventTarget { /** * @internal only for game-view */ - public _loadProjectBundles () { + public _loadProjectBundles (): Promise { const preloadBundles = settings.querySettings<{ bundle: string, version: string }[]>(Settings.Category.ASSETS, 'preloadBundles'); if (!preloadBundles) return Promise.resolve([]); - return Promise.all(preloadBundles.map(({ bundle, version }) => new Promise((resolve, reject) => { + return Promise.all(preloadBundles.map(({ bundle, version }): Promise => new Promise((resolve, reject): void => { const opts: Record = {}; if (version) opts.version = version; - assetManager.loadBundle(bundle, opts, (err) => { + assetManager.loadBundle(bundle, opts, (err): void => { if (err) { reject(err); return; @@ -974,7 +974,7 @@ export class Game extends EventTarget { * @zh 运行游戏,并且指定引擎配置和 onStart 的回调。 * @param onStart - function to be executed after game initialized */ - public run (onStart?: Game.OnStart) { + public run (onStart?: Game.OnStart): void { if (onStart) { this.onStart = onStart; } @@ -986,7 +986,7 @@ export class Game extends EventTarget { // @Methods - private _calculateDT (useFixedDeltaTime: boolean) { + private _calculateDT (useFixedDeltaTime: boolean): number { this._useFixedDeltaTime = useFixedDeltaTime; if (useFixedDeltaTime) { @@ -1003,7 +1003,7 @@ export class Game extends EventTarget { return this._deltaTime; } - private _updateCallback () { + private _updateCallback (): void { if (!this._inited) return; if (!SplashScreen.instance.isFinished) { SplashScreen.instance.update(this._calculateDT(false)); @@ -1012,7 +1012,7 @@ export class Game extends EventTarget { const launchScene = settings.querySettings(Settings.Category.LAUNCH, 'launchScene'); if (launchScene) { // load scene - director.loadScene(launchScene, () => { + director.loadScene(launchScene, (): void => { console.log(`Success to load scene: ${launchScene}`); this._initTime = performance.now(); director.startAnimation(); @@ -1028,7 +1028,7 @@ export class Game extends EventTarget { } } - private initPacer () { + private initPacer (): void { const frameRate = settings.querySettings(Settings.Category.SCREEN, 'frameRate') ?? 60; assert(typeof frameRate === 'number'); this._pacer = new Pacer(); @@ -1036,23 +1036,23 @@ export class Game extends EventTarget { this.frameRate = frameRate; } - private _initEvents () { + private _initEvents (): void { systemInfo.on('show', this._onShow, this); systemInfo.on('hide', this._onHide, this); systemInfo.on('close', this._onClose, this); } - private _onHide () { + private _onHide (): void { this.emit(Game.EVENT_HIDE); this.pauseByEngine(); } - private _onShow () { + private _onShow (): void { this.emit(Game.EVENT_SHOW); this.resumeByEngine(); } - private _onClose () { + private _onClose (): void { this.emit(Game.EVENT_CLOSE); // TODO : Release Resources. systemInfo.exit(); @@ -1069,7 +1069,7 @@ export class Game extends EventTarget { * @param node - The node to be made persistent * @deprecated Since v3.6.0, please use director.addPersistRootNode instead. */ - public addPersistRootNode (node: Node) { + public addPersistRootNode (node: Node): void { director.addPersistRootNode(node); } @@ -1079,7 +1079,7 @@ export class Game extends EventTarget { * @param node - The node to be removed from persistent node list * @deprecated Since v3.6.0, please use director.removePersistRootNode instead. */ - public removePersistRootNode (node: Node) { + public removePersistRootNode (node: Node): void { director.removePersistRootNode(node); } @@ -1093,25 +1093,25 @@ export class Game extends EventTarget { return director.isPersistRootNode(node); } - private _setupRenderPipeline () { + private _setupRenderPipeline (): void | Promise { const renderPipeline = settings.querySettings(Settings.Category.RENDERING, 'renderPipeline'); if (!renderPipeline) { return this._setRenderPipeline(); } - return new Promise((resolve, reject) => { - assetManager.loadAny(renderPipeline, (err, asset) => ((err || !(asset instanceof RenderPipeline)) + return new Promise((resolve, reject): void => { + assetManager.loadAny(renderPipeline, (err, asset): void => ((err || !(asset instanceof RenderPipeline)) ? reject(err) : resolve(asset))); - }).then((asset) => { + }).then((asset): void => { this._setRenderPipeline(asset); - }).catch((reason) => { + }).catch((reason): void => { warn(reason); warn(`Failed load render pipeline: ${renderPipeline}, engine failed to initialize, will fallback to default pipeline`); this._setRenderPipeline(); }); } - private _setRenderPipeline (rppl?: RenderPipeline) { + private _setRenderPipeline (rppl?: RenderPipeline): void { if (!director.root!.setRenderPipeline(rppl)) { this._setRenderPipeline(); } @@ -1120,7 +1120,7 @@ export class Game extends EventTarget { this._safeEmit(Game.EVENT_RENDERER_INITED); } - private _safeEmit (event) { + private _safeEmit (event): void { if (EDITOR) { try { this.emit(event); diff --git a/cocos/game/splash-screen.ts b/cocos/game/splash-screen.ts index 6ba7261726d..fb85f3f1c59 100644 --- a/cocos/game/splash-screen.ts +++ b/cocos/game/splash-screen.ts @@ -99,7 +99,7 @@ export class SplashScreen { private scaleSize = 1; - public get isFinished () { + public get isFinished (): boolean { return this._curTime >= this.settings.totalTime; } @@ -107,11 +107,11 @@ export class SplashScreen { this._curTime = val; } - get curTime () { + get curTime (): number { return this._curTime; } - public init (): Promise | undefined { + public init (): Promise { this.settings = { displayRatio: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'displayRatio') ?? 0.4, totalTime: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'totalTime') ?? 3000, @@ -134,24 +134,24 @@ export class SplashScreen { this.initLayout(); this.initWaterMark(); - const bgPromise = new Promise((resolve, reject) => { + const bgPromise = new Promise((resolve, reject): void => { this.bgImage = new ccwindow.Image(); - this.bgImage.onload = () => { + this.bgImage.onload = (): void => { this.initBG(); resolve(); }; - this.bgImage.onerror = () => { + this.bgImage.onerror = (): void => { reject(); }; this.bgImage.src = this.settings.bgBase64; }); - const logoPromise = new Promise((resolve, reject) => { + const logoPromise = new Promise((resolve, reject): void => { this.logoImage = new ccwindow.Image(); - this.logoImage.onload = () => { + this.logoImage.onload = (): void => { this.initLogo(); resolve(); }; - this.logoImage.onerror = () => { + this.logoImage.onerror = (): void => { reject(); }; this.logoImage.src = this.settings.base64src; @@ -161,7 +161,7 @@ export class SplashScreen { return Promise.resolve([]); } - private preInit () { + private preInit (): void { this.clearColors = [new Color(0, 0, 0, 255)]; // clean to black const { device, swapchain } = this; this.renderArea = new Rect(0, 0, swapchain.width, swapchain.height); @@ -202,7 +202,7 @@ export class SplashScreen { this.isMobile = sys.isMobile; } - private initLayout () { + private initLayout (): void { if (this.isMobile) { this.bgWidth = 812; this.bgHeight = 375; @@ -231,7 +231,7 @@ export class SplashScreen { this.initScale(); } - private initScale () { + private initScale (): void { const dw = this.swapchain.width; const dh = this.swapchain.height; let desiredWidth = this.isMobile ? 375 : 1080; let desiredHeight = this.isMobile ? 812 : 1920; @@ -247,7 +247,7 @@ export class SplashScreen { } } - public update (deltaTime: number) { + public update (deltaTime: number): void { const settings = this.settings; const { device, swapchain } = this; Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, @@ -308,7 +308,7 @@ export class SplashScreen { this.frame(); } - private initBG () { + private initBG (): void { const device = this.device; this.bgMat = new Material(); @@ -343,7 +343,7 @@ export class SplashScreen { device.copyTexImagesToTexture([this.bgImage], this.bgTexture, [region]); } - private initLogo () { + private initLogo (): void { const device = this.device; this.logoMat = new Material(); @@ -387,7 +387,7 @@ export class SplashScreen { } } - private initWaterMark () { + private initWaterMark (): void { // create texture from image const watermarkImg = ccwindow.document.createElement('canvas'); watermarkImg.height = this.textHeight * this.scaleSize; @@ -419,7 +419,7 @@ export class SplashScreen { pass.descriptorSet.update(); } - private frame () { + private frame (): void { const { device, swapchain } = this; if (!sys.isXR || xr.entry.isRenderAllowable()) { @@ -508,7 +508,7 @@ export class SplashScreen { } } - private destroy () { + private destroy (): void { this.device = null!; this.swapchain = null!; this.clearColors = null!; @@ -548,7 +548,7 @@ export class SplashScreen { private static _ins?: SplashScreen; - public static get instance () { + public static get instance (): SplashScreen { if (!SplashScreen._ins) { SplashScreen._ins = new SplashScreen(); } diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 87ec5bd34c3..21b6de0effe 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -37,7 +37,7 @@ import { GCObject } from '../../core'; interface ICopyable { copy (info: ICopyable): ICopyable; } -const deepCopy = (target: T[], source: T[], Ctor: Constructor) => { +const deepCopy = (target: T[], source: T[], Ctor: Constructor): void => { for (let i = 0; i < source.length; ++i) { if (target.length <= i) target.push(new Ctor()); target[i].copy(source[i]); @@ -715,7 +715,7 @@ export class Size { public z: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Size { this.x = info.x; this.y = info.y; this.z = info.z; @@ -753,7 +753,7 @@ export class DeviceCaps { public clipSpaceSignY: number = 1, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DeviceCaps { this.maxVertexAttributes = info.maxVertexAttributes; this.maxVertexUniformVectors = info.maxVertexUniformVectors; this.maxFragmentUniformVectors = info.maxFragmentUniformVectors; @@ -789,7 +789,7 @@ export class DeviceOptions { public enableBarrierDeduce: boolean = true, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DeviceOptions { this.enableBarrierDeduce = info.enableBarrierDeduce; return this; } @@ -804,7 +804,7 @@ export class Offset { public z: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Offset { this.x = info.x; this.y = info.y; this.z = info.z; @@ -822,7 +822,7 @@ export class Rect { public height: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Rect { this.x = info.x; this.y = info.y; this.width = info.width; @@ -840,7 +840,7 @@ export class Extent { public depth: number = 1, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Extent { this.width = info.width; this.height = info.height; this.depth = info.depth; @@ -857,7 +857,7 @@ export class TextureSubresLayers { public layerCount: number = 1, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): TextureSubresLayers { this.mipLevel = info.mipLevel; this.baseArrayLayer = info.baseArrayLayer; this.layerCount = info.layerCount; @@ -875,7 +875,7 @@ export class TextureSubresRange { public layerCount: number = 1, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): TextureSubresRange { this.baseMipLevel = info.baseMipLevel; this.levelCount = info.levelCount; this.baseArrayLayer = info.baseArrayLayer; @@ -895,7 +895,7 @@ export class TextureCopy { public extent: Extent = new Extent(), ) {} - public copy (info: Readonly) { + public copy (info: Readonly): TextureCopy { this.srcSubres.copy(info.srcSubres); this.srcOffset.copy(info.srcOffset); this.dstSubres.copy(info.dstSubres); @@ -917,7 +917,7 @@ export class TextureBlit { public dstExtent: Extent = new Extent(), ) {} - public copy (info: Readonly) { + public copy (info: Readonly): TextureBlit { this.srcSubres.copy(info.srcSubres); this.srcOffset.copy(info.srcOffset); this.srcExtent.copy(info.srcExtent); @@ -940,7 +940,7 @@ export class BufferTextureCopy { public texSubres: TextureSubresLayers = new TextureSubresLayers(), ) {} - public copy (info: Readonly) { + public copy (info: Readonly): BufferTextureCopy { this.buffOffset = info.buffOffset; this.buffStride = info.buffStride; this.buffTexHeight = info.buffTexHeight; @@ -963,7 +963,7 @@ export class Viewport { public maxDepth: number = 1, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Viewport { this.left = info.left; this.top = info.top; this.width = info.width; @@ -984,7 +984,7 @@ export class Color { public w: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Color { this.x = info.x; this.y = info.y; this.z = info.z; @@ -1007,7 +1007,7 @@ export class BindingMappingInfo { public setIndices: number[] = [0], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): BindingMappingInfo { this.maxBlockCounts = info.maxBlockCounts.slice(); this.maxSamplerTextureCounts = info.maxSamplerTextureCounts.slice(); this.maxSamplerCounts = info.maxSamplerCounts.slice(); @@ -1031,7 +1031,7 @@ export class SwapchainInfo { public height: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): SwapchainInfo { this.windowId = info.windowId; this.windowHandle = info.windowHandle; this.vsyncMode = info.vsyncMode; @@ -1048,7 +1048,7 @@ export class DeviceInfo { public bindingMappingInfo: BindingMappingInfo = new BindingMappingInfo(), ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DeviceInfo { this.bindingMappingInfo.copy(info.bindingMappingInfo); return this; } @@ -1065,7 +1065,7 @@ export class BufferInfo { public flags: BufferFlags = BufferFlagBit.NONE, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): BufferInfo { this.usage = info.usage; this.memUsage = info.memUsage; this.size = info.size; @@ -1084,7 +1084,7 @@ export class BufferViewInfo { public range: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): BufferViewInfo { this.buffer = info.buffer; this.offset = info.offset; this.range = info.range; @@ -1105,7 +1105,7 @@ export class DrawInfo { public firstInstance: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DrawInfo { this.vertexCount = info.vertexCount; this.firstVertex = info.firstVertex; this.indexCount = info.indexCount; @@ -1128,7 +1128,7 @@ export class DispatchInfo { public indirectOffset: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DispatchInfo { this.groupCountX = info.groupCountX; this.groupCountY = info.groupCountY; this.groupCountZ = info.groupCountZ; @@ -1145,7 +1145,7 @@ export class IndirectBuffer { public drawInfos: DrawInfo[] = [], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): IndirectBuffer { deepCopy(this.drawInfos, info.drawInfos, DrawInfo); return this; } @@ -1168,7 +1168,7 @@ export class TextureInfo { public externalRes: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): TextureInfo { this.type = info.type; this.usage = info.usage; this.format = info.format; @@ -1197,7 +1197,7 @@ export class TextureViewInfo { public layerCount: number = 1, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): TextureViewInfo { this.texture = info.texture; this.type = info.type; this.format = info.format; @@ -1223,7 +1223,7 @@ export class SamplerInfo { public cmpFunc: ComparisonFunc = ComparisonFunc.ALWAYS, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): SamplerInfo { this.minFilter = info.minFilter; this.magFilter = info.magFilter; this.mipFilter = info.mipFilter; @@ -1245,7 +1245,7 @@ export class Uniform { public count: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Uniform { this.name = info.name; this.type = info.type; this.count = info.count; @@ -1265,7 +1265,7 @@ export class UniformBlock { public flattened: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): UniformBlock { this.set = info.set; this.binding = info.binding; this.name = info.name; @@ -1288,7 +1288,7 @@ export class UniformSamplerTexture { public flattened: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): UniformSamplerTexture { this.set = info.set; this.binding = info.binding; this.name = info.name; @@ -1310,7 +1310,7 @@ export class UniformSampler { public flattened: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): UniformSampler { this.set = info.set; this.binding = info.binding; this.name = info.name; @@ -1332,7 +1332,7 @@ export class UniformTexture { public flattened: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): UniformTexture { this.set = info.set; this.binding = info.binding; this.name = info.name; @@ -1356,7 +1356,7 @@ export class UniformStorageImage { public flattened: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): UniformStorageImage { this.set = info.set; this.binding = info.binding; this.name = info.name; @@ -1380,7 +1380,7 @@ export class UniformStorageBuffer { public flattened: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): UniformStorageBuffer { this.set = info.set; this.binding = info.binding; this.name = info.name; @@ -1402,7 +1402,7 @@ export class UniformInputAttachment { public flattened: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): UniformInputAttachment { this.set = info.set; this.binding = info.binding; this.name = info.name; @@ -1420,7 +1420,7 @@ export class ShaderStage { public source: string = '', ) {} - public copy (info: Readonly) { + public copy (info: Readonly): ShaderStage { this.stage = info.stage; this.source = info.source; return this; @@ -1439,7 +1439,7 @@ export class Attribute { public location: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): Attribute { this.name = info.name; this.format = info.format; this.isNormalized = info.isNormalized; @@ -1466,7 +1466,7 @@ export class ShaderInfo { public subpassInputs: UniformInputAttachment[] = [], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): ShaderInfo { this.name = info.name; deepCopy(this.stages, info.stages, ShaderStage); deepCopy(this.attributes, info.attributes, Attribute); @@ -1491,7 +1491,7 @@ export class InputAssemblerInfo { public indirectBuffer: Buffer | null = null, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): InputAssemblerInfo { deepCopy(this.attributes, info.attributes, Attribute); this.vertexBuffers = info.vertexBuffers.slice(); this.indexBuffer = info.indexBuffer; @@ -1511,7 +1511,7 @@ export class ColorAttachment { public barrier: GeneralBarrier = null!, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): ColorAttachment { this.format = info.format; this.sampleCount = info.sampleCount; this.loadOp = info.loadOp; @@ -1534,7 +1534,7 @@ export class DepthStencilAttachment { public barrier: GeneralBarrier = null!, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DepthStencilAttachment { this.format = info.format; this.sampleCount = info.sampleCount; this.depthLoadOp = info.depthLoadOp; @@ -1560,7 +1560,7 @@ export class SubpassInfo { public stencilResolveMode: ResolveMode = ResolveMode.NONE, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): SubpassInfo { this.inputs = info.inputs.slice(); this.colors = info.colors.slice(); this.resolves = info.resolves.slice(); @@ -1584,7 +1584,7 @@ export class SubpassDependency { public nextAccesses: AccessFlags[] = [AccessFlagBit.NONE], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): SubpassDependency { this.srcSubpass = info.srcSubpass; this.dstSubpass = info.dstSubpass; this.generalBarrier = info.generalBarrier; @@ -1604,7 +1604,7 @@ export class RenderPassInfo { public dependencies: SubpassDependency[] = [], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): RenderPassInfo { deepCopy(this.colorAttachments, info.colorAttachments, ColorAttachment); this.depthStencilAttachment.copy(info.depthStencilAttachment); deepCopy(this.subpasses, info.subpasses, SubpassInfo); @@ -1622,7 +1622,7 @@ export class GeneralBarrierInfo { public type: BarrierType = BarrierType.FULL, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): GeneralBarrierInfo { this.prevAccesses = info.prevAccesses; this.nextAccesses = info.nextAccesses; this.type = info.type; @@ -1646,7 +1646,7 @@ export class TextureBarrierInfo { public dstQueue: Queue | null = null, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): TextureBarrierInfo { this.prevAccesses = info.prevAccesses; this.nextAccesses = info.nextAccesses; this.type = info.type; @@ -1675,7 +1675,7 @@ export class BufferBarrierInfo { public dstQueue: Queue | null = null, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): BufferBarrierInfo { this.prevAccesses = info.prevAccesses; this.nextAccesses = info.nextAccesses; this.type = info.type; @@ -1697,7 +1697,7 @@ export class FramebufferInfo { public depthStencilTexture: Texture | null = null, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): FramebufferInfo { this.renderPass = info.renderPass; this.colorTextures = info.colorTextures.slice(); this.depthStencilTexture = info.depthStencilTexture; @@ -1716,7 +1716,7 @@ export class DescriptorSetLayoutBinding { public immutableSamplers: Sampler[] = [], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DescriptorSetLayoutBinding { this.binding = info.binding; this.descriptorType = info.descriptorType; this.count = info.count; @@ -1733,7 +1733,7 @@ export class DescriptorSetLayoutInfo { public bindings: DescriptorSetLayoutBinding[] = [], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DescriptorSetLayoutInfo { deepCopy(this.bindings, info.bindings, DescriptorSetLayoutBinding); return this; } @@ -1746,7 +1746,7 @@ export class DescriptorSetInfo { public layout: DescriptorSetLayout = null!, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DescriptorSetInfo { this.layout = info.layout; return this; } @@ -1759,7 +1759,7 @@ export class PipelineLayoutInfo { public setLayouts: DescriptorSetLayout[] = [], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): PipelineLayoutInfo { this.setLayouts = info.setLayouts.slice(); return this; } @@ -1772,7 +1772,7 @@ export class InputState { public attributes: Attribute[] = [], ) {} - public copy (info: Readonly) { + public copy (info: Readonly): InputState { deepCopy(this.attributes, info.attributes, Attribute); return this; } @@ -1786,7 +1786,7 @@ export class CommandBufferInfo { public type: CommandBufferType = CommandBufferType.PRIMARY, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): CommandBufferInfo { this.queue = info.queue; this.type = info.type; return this; @@ -1800,7 +1800,7 @@ export class QueueInfo { public type: QueueType = QueueType.GRAPHICS, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): QueueInfo { this.type = info.type; return this; } @@ -1815,7 +1815,7 @@ export class QueryPoolInfo { public forceWait: boolean = true, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): QueryPoolInfo { this.type = info.type; this.maxQueryObjects = info.maxQueryObjects; this.forceWait = info.forceWait; @@ -1846,7 +1846,7 @@ export class MemoryStatus { public textureSize: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): MemoryStatus { this.bufferSize = info.bufferSize; this.textureSize = info.textureSize; return this; @@ -1862,7 +1862,7 @@ export class DynamicStencilStates { public reference: number = 0, ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DynamicStencilStates { this.writeMask = info.writeMask; this.compareMask = info.compareMask; this.reference = info.reference; @@ -1887,7 +1887,7 @@ export class DynamicStates { public stencilStatesBack: DynamicStencilStates = new DynamicStencilStates(), ) {} - public copy (info: Readonly) { + public copy (info: Readonly): DynamicStates { this.viewport.copy(info.viewport); this.scissor.copy(info.scissor); this.blendConstant.copy(info.blendConstant); diff --git a/cocos/gfx/base/descriptor-set-layout.ts b/cocos/gfx/base/descriptor-set-layout.ts index 0258a7b54db..46eb21613a3 100644 --- a/cocos/gfx/base/descriptor-set-layout.ts +++ b/cocos/gfx/base/descriptor-set-layout.ts @@ -29,15 +29,15 @@ import { GFXObject, ObjectType, DescriptorSetLayoutBinding, DescriptorSetLayoutI * @zh GFX 描述符集布局。 */ export abstract class DescriptorSetLayout extends GFXObject { - get bindings () { + get bindings (): DescriptorSetLayoutBinding[] { return this._bindings; } - get bindingIndices () { + get bindingIndices (): number[] { return this._bindingIndices; } - get descriptorIndices () { + get descriptorIndices (): number[] { return this._descriptorIndices; } diff --git a/cocos/gfx/base/descriptor-set.ts b/cocos/gfx/base/descriptor-set.ts index 4afea6d4ca7..b29c0f4073e 100644 --- a/cocos/gfx/base/descriptor-set.ts +++ b/cocos/gfx/base/descriptor-set.ts @@ -33,7 +33,7 @@ import { GFXObject, ObjectType, DescriptorSetInfo, DESCRIPTOR_BUFFER_TYPE, DESCR * @zh GFX 描述符集组。 */ export abstract class DescriptorSet extends GFXObject { - get layout () { + get layout (): DescriptorSetLayout { return this._layout!; } @@ -60,7 +60,7 @@ export abstract class DescriptorSet extends GFXObject { * @param binding The target binding. * @param buffer The buffer to be bound. */ - public bindBuffer (binding: number, buffer: Buffer, index = 0) { + public bindBuffer (binding: number, buffer: Buffer, index = 0): void { const bindingIndex = this._layout!.bindingIndices[binding]; const info = this._layout!.bindings[bindingIndex]; if (!info) { return; } if (info.descriptorType & DESCRIPTOR_BUFFER_TYPE) { @@ -78,7 +78,7 @@ export abstract class DescriptorSet extends GFXObject { * @param binding The target binding. * @param sampler The sampler to be bound. */ - public bindSampler (binding: number, sampler: Sampler, index = 0) { + public bindSampler (binding: number, sampler: Sampler, index = 0): void { const bindingIndex = this._layout!.bindingIndices[binding]; const info = this._layout!.bindings[bindingIndex]; if (!info) { return; } if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) { @@ -96,7 +96,7 @@ export abstract class DescriptorSet extends GFXObject { * @param binding The target binding. * @param texture The texture to be bound. */ - public bindTexture (binding: number, texture: Texture, index = 0, flags?: AccessFlags) { + public bindTexture (binding: number, texture: Texture, index = 0, flags?: AccessFlags): void { const bindingIndex = this._layout!.bindingIndices[binding]; const info = this._layout!.bindings[bindingIndex]; if (!info) { return; } if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) { @@ -113,7 +113,7 @@ export abstract class DescriptorSet extends GFXObject { * @zh 获取当前指定绑定位置上的缓冲。 * @param binding The target binding. */ - public getBuffer (binding: number, index = 0) { + public getBuffer (binding: number, index = 0): Buffer { const descriptorIndex = this._layout!.descriptorIndices[binding]; return this._buffers[descriptorIndex + index]; } @@ -123,7 +123,7 @@ export abstract class DescriptorSet extends GFXObject { * @zh 获取当前指定绑定位置上的采样器。 * @param binding The target binding. */ - public getSampler (binding: number, index = 0) { + public getSampler (binding: number, index = 0): Sampler { const descriptorIndex = this._layout!.descriptorIndices[binding]; return this._samplers[descriptorIndex + index]; } @@ -133,7 +133,7 @@ export abstract class DescriptorSet extends GFXObject { * @zh 获取当前指定绑定位置上的贴图。 * @param binding The target binding. */ - public getTexture (binding: number, index = 0) { + public getTexture (binding: number, index = 0): Texture { const descriptorIndex = this._layout!.descriptorIndices[binding]; return this._textures[descriptorIndex + index]; } diff --git a/cocos/gfx/base/device.ts b/cocos/gfx/base/device.ts index cb6c1541d20..e0272538b24 100644 --- a/cocos/gfx/base/device.ts +++ b/cocos/gfx/base/device.ts @@ -137,7 +137,7 @@ export abstract class Device { * @en Current device binding mappings. * @zh 当前设备的绑定槽位映射关系。 */ - get bindingMappingInfo () { + get bindingMappingInfo (): BindingMappingInfo { return this._bindingMappingInfo; } @@ -358,7 +358,7 @@ export abstract class Device { * @zh 是否开启自动GFX内部barrier推导,web无影响。 * @param format The GFX format to be queried. */ - public enableAutoBarrier (en: boolean) {} + public enableAutoBarrier (en: boolean): void {} } export class DefaultResource { @@ -435,7 +435,7 @@ export class DefaultResource { } } - public getTexture (type: TextureType) { + public getTexture (type: TextureType): Texture | null { switch (type) { case TextureType.TEX2D: return this._texture2D; case TextureType.TEX3D: return this._texture3D; diff --git a/cocos/gfx/base/input-assembler.ts b/cocos/gfx/base/input-assembler.ts index 66ca33015c3..84312b9aa3b 100644 --- a/cocos/gfx/base/input-assembler.ts +++ b/cocos/gfx/base/input-assembler.ts @@ -78,7 +78,7 @@ export abstract class InputAssembler extends GFXObject { set vertexCount (count: number) { this._drawInfo.vertexCount = count; } - get vertexCount () { + get vertexCount (): number { return this._drawInfo.vertexCount; } @@ -89,7 +89,7 @@ export abstract class InputAssembler extends GFXObject { set firstVertex (first: number) { this._drawInfo.firstVertex = first; } - get firstVertex () { + get firstVertex (): number { return this._drawInfo.firstVertex; } @@ -100,7 +100,7 @@ export abstract class InputAssembler extends GFXObject { set indexCount (count: number) { this._drawInfo.indexCount = count; } - get indexCount () { + get indexCount (): number { return this._drawInfo.indexCount; } @@ -111,7 +111,7 @@ export abstract class InputAssembler extends GFXObject { set firstIndex (first: number) { this._drawInfo.firstIndex = first; } - get firstIndex () { + get firstIndex (): number { return this._drawInfo.firstIndex; } @@ -122,7 +122,7 @@ export abstract class InputAssembler extends GFXObject { set vertexOffset (offset: number) { this._drawInfo.vertexOffset = offset; } - get vertexOffset () { + get vertexOffset (): number { return this._drawInfo.vertexOffset; } @@ -133,7 +133,7 @@ export abstract class InputAssembler extends GFXObject { set instanceCount (count: number) { this._drawInfo.instanceCount = count; } - get instanceCount () { + get instanceCount (): number { return this._drawInfo.instanceCount; } @@ -144,7 +144,7 @@ export abstract class InputAssembler extends GFXObject { set firstInstance (first: number) { this._drawInfo.firstInstance = first; } - get firstInstance () { + get firstInstance (): number { return this._drawInfo.firstInstance; } diff --git a/cocos/gfx/base/pipeline-layout.ts b/cocos/gfx/base/pipeline-layout.ts index 4e29fc9bc48..677c4ac96d1 100644 --- a/cocos/gfx/base/pipeline-layout.ts +++ b/cocos/gfx/base/pipeline-layout.ts @@ -30,7 +30,7 @@ import { GFXObject, ObjectType, PipelineLayoutInfo } from './define'; * @zh GFX 管线布局。 */ export abstract class PipelineLayout extends GFXObject { - get setLayouts () { + get setLayouts (): DescriptorSetLayout[] { return this._setLayouts; } diff --git a/cocos/gfx/base/pipeline-sub-state.ts b/cocos/gfx/base/pipeline-sub-state.ts index 7607a43c808..3edc42d90c3 100644 --- a/cocos/gfx/base/pipeline-sub-state.ts +++ b/cocos/gfx/base/pipeline-sub-state.ts @@ -42,7 +42,7 @@ import { 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 - get native () { + get native (): RasterizerState { return this; } @@ -61,7 +61,7 @@ export class RasterizerState { public lineWidth: number = 1.0, ) {} - public reset () { + public reset (): void { this.isDiscard = false; this.polygonMode = PolygonMode.FILL; this.shadeModel = ShadeModel.GOURAND; @@ -76,11 +76,11 @@ export class RasterizerState { this.lineWidth = 1.0; } - public assign (rs: RasterizerState) { + public assign (rs: RasterizerState): void { Object.assign(this, rs); } - public destroy () {} + public destroy (): void {} } /** @@ -90,7 +90,7 @@ export class RasterizerState { 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 - get native () { + get native (): DepthStencilState { return this; } constructor ( @@ -115,7 +115,7 @@ export class DepthStencilState { public stencilRefBack: number = 1, ) {} - public reset () { + public reset (): void { this.depthTest = true; this.depthWrite = true; this.depthFunc = ComparisonFunc.LESS; @@ -137,11 +137,11 @@ export class DepthStencilState { this.stencilRefBack = 1; } - public assign (dss: DepthStencilState) { + public assign (dss: DepthStencilState): void { Object.assign(this, dss); } - public destroy () {} + public destroy (): void {} } /** @@ -162,7 +162,7 @@ export class BlendTarget { public blendColorMask: ColorMask = ColorMask.ALL, ) {} - public reset () { + public reset (): void { this.blend = false; this.blendSrc = BlendFactor.ONE; this.blendDst = BlendFactor.ZERO; @@ -173,11 +173,11 @@ export class BlendTarget { this.blendColorMask = ColorMask.ALL; } - public assign (target: BlendTarget) { + public assign (target: BlendTarget): void { Object.assign(this, target); } - public destroy () {} + public destroy (): void {} } /** @@ -187,7 +187,7 @@ export class BlendTarget { 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 - get native () { + get native (): BlendState { return this; } @@ -206,7 +206,7 @@ export class BlendState { * @param index The index to set target. * @param target The target to be set. */ - public setTarget (index: number, target: BlendTarget) { + public setTarget (index: number, target: BlendTarget): void { let tg = this.targets[index]; if (!tg) { tg = this.targets[index] = new BlendTarget(); @@ -214,7 +214,7 @@ export class BlendState { Object.assign(tg, target); } - public reset () { + public reset (): void { this.isA2C = false; this.isIndepend = false; this.blendColor.x = 0; @@ -225,5 +225,5 @@ export class BlendState { this.targets[0].reset(); } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/base/render-pass.ts b/cocos/gfx/base/render-pass.ts index c40f303d707..857c591c97f 100644 --- a/cocos/gfx/base/render-pass.ts +++ b/cocos/gfx/base/render-pass.ts @@ -45,7 +45,7 @@ export abstract class RenderPass extends GFXObject { get colorAttachments () : Readonly { return this._colorInfos; } get depthStencilAttachment () : Readonly | null { return this._depthStencilInfo; } get subPasses () : Readonly { return this._subpasses; } - get hash () { return this._hash; } + get hash (): number { return this._hash; } constructor () { super(ObjectType.RENDER_PASS); diff --git a/cocos/gfx/base/shader.ts b/cocos/gfx/base/shader.ts index e66622196a4..64b99ec041f 100644 --- a/cocos/gfx/base/shader.ts +++ b/cocos/gfx/base/shader.ts @@ -33,15 +33,15 @@ export abstract class Shader extends GFXObject { return this._name; } - get attributes () { + get attributes (): Attribute[] { return this._attributes; } - get blocks () { + get blocks (): UniformBlock[] { return this._blocks; } - get samplers () { + get samplers (): UniformSampler[] { return this._samplers; } diff --git a/cocos/gfx/base/states/buffer-barrier.ts b/cocos/gfx/base/states/buffer-barrier.ts index c3fd997c6f1..3304a78ce27 100644 --- a/cocos/gfx/base/states/buffer-barrier.ts +++ b/cocos/gfx/base/states/buffer-barrier.ts @@ -42,7 +42,7 @@ export class BufferBarrier extends GFXObject { this._hash = hash; } - static computeHash (info: Readonly) { + static computeHash (info: Readonly): number { let res = `${info.prevAccesses} ${info.nextAccesses}`; res += info.type; res += info.offset; diff --git a/cocos/gfx/base/states/general-barrier.ts b/cocos/gfx/base/states/general-barrier.ts index 78e77860339..a271b06d8a6 100644 --- a/cocos/gfx/base/states/general-barrier.ts +++ b/cocos/gfx/base/states/general-barrier.ts @@ -42,7 +42,7 @@ export class GeneralBarrier extends GFXObject { this._hash = hash; } - static computeHash (info: Readonly) { + static computeHash (info: Readonly): number { return murmurhash2_32_gc(`${info.prevAccesses} ${info.nextAccesses} ${info.type}`, 666); } } diff --git a/cocos/gfx/base/states/sampler.ts b/cocos/gfx/base/states/sampler.ts index 3ac8865af95..7dee689f6ed 100644 --- a/cocos/gfx/base/states/sampler.ts +++ b/cocos/gfx/base/states/sampler.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { GFXObject, ObjectType, SamplerInfo } from '../define'; +import { Filter, GFXObject, ObjectType, SamplerInfo } from '../define'; /** * @en GFX sampler. @@ -41,7 +41,7 @@ export class Sampler extends GFXObject { this._hash = hash; } - static computeHash (info: Readonly) { + static computeHash (info: Readonly): Filter { let hash = info.minFilter; hash |= (info.magFilter << 2); hash |= (info.mipFilter << 4); @@ -53,7 +53,7 @@ export class Sampler extends GFXObject { return hash; } - static unpackFromHash (hash: number) { + static unpackFromHash (hash: number): SamplerInfo { const info = new SamplerInfo(); info.minFilter = (hash & ((1 << 2) - 1)) >> 0; info.magFilter = (hash & ((1 << 2) - 1)) >> 2; diff --git a/cocos/gfx/base/states/texture-barrier.ts b/cocos/gfx/base/states/texture-barrier.ts index a00765d1743..b4d754ab365 100644 --- a/cocos/gfx/base/states/texture-barrier.ts +++ b/cocos/gfx/base/states/texture-barrier.ts @@ -42,7 +42,7 @@ export class TextureBarrier extends GFXObject { this._hash = hash; } - static computeHash (info: Readonly) { + static computeHash (info: Readonly): number { let res = `${info.prevAccesses} ${info.nextAccesses}`; res += info.type; res += info.baseMipLevel; diff --git a/cocos/gfx/base/swapchain.ts b/cocos/gfx/base/swapchain.ts index 829c8009044..1be61edf23a 100644 --- a/cocos/gfx/base/swapchain.ts +++ b/cocos/gfx/base/swapchain.ts @@ -34,7 +34,7 @@ export abstract class Swapchain extends GFXObject { * @en The color texture of this swapchain. * @zh 当前交换链的颜色缓冲。 */ - get colorTexture () { + get colorTexture (): Texture { return this._colorTexture; } @@ -42,7 +42,7 @@ export abstract class Swapchain extends GFXObject { * @en The depth stencil texture of this swapchain. * @zh 当前交换链的深度模板缓冲。 */ - get depthStencilTexture () { + get depthStencilTexture (): Texture { return this._depthStencilTexture; } @@ -50,15 +50,15 @@ export abstract class Swapchain extends GFXObject { * @en The surface transform to be applied in projection matrices. * @zh 需要在投影矩阵中应用的表面变换。 */ - get surfaceTransform () { + get surfaceTransform (): SurfaceTransform { return this._transform; } - get width () { + get width (): number { return this._colorTexture.width; } - get height () { + get height (): number { return this._colorTexture.height; } diff --git a/cocos/gfx/device-manager.ts b/cocos/gfx/device-manager.ts index 4aab0d17aba..2db9c1c60aa 100644 --- a/cocos/gfx/device-manager.ts +++ b/cocos/gfx/device-manager.ts @@ -92,15 +92,15 @@ export class DeviceManager { private _swapchain!: Swapchain; private _renderType: RenderType = RenderType.UNKNOWN; - public get gfxDevice () { + public get gfxDevice (): Device { return this._gfxDevice; } - public get swapchain () { + public get swapchain (): Swapchain { return this._swapchain; } - public init (canvas: HTMLCanvasElement | null, bindingMappingInfo: BindingMappingInfo) { + public init (canvas: HTMLCanvasElement | null, bindingMappingInfo: BindingMappingInfo): void { // Avoid setup to be called twice. if (this.initialized) { return; } const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode'); @@ -156,10 +156,10 @@ export class DeviceManager { return; } - if (this._canvas) { this._canvas.oncontextmenu = () => false; } + if (this._canvas) { this._canvas.oncontextmenu = (): boolean => false; } } - private _initSwapchain () { + private _initSwapchain (): void { const swapchainInfo = new SwapchainInfo(1, this._canvas!); const windowSize = screen.windowSize; swapchainInfo.width = windowSize.width; diff --git a/cocos/gfx/empty/empty-buffer.ts b/cocos/gfx/empty/empty-buffer.ts index 009c3c0d08f..798d3a77b1d 100644 --- a/cocos/gfx/empty/empty-buffer.ts +++ b/cocos/gfx/empty/empty-buffer.ts @@ -26,7 +26,7 @@ import { BufferSource, BufferInfo, BufferViewInfo } from '../base/define'; import { Buffer } from '../base/buffer'; export class EmptyBuffer extends Buffer { - public initialize (info: Readonly | Readonly) { + public initialize (info: Readonly | Readonly): void { if ('buffer' in info) { // buffer view this._isBufferView = true; @@ -46,7 +46,7 @@ export class EmptyBuffer extends Buffer { this._flags = info.flags; } } - public destroy () {} - public resize (size: number) {} - public update (buffer: Readonly, size?: number) {} + public destroy (): void {} + public resize (size: number): void {} + public update (buffer: Readonly, size?: number): void {} } diff --git a/cocos/gfx/empty/empty-command-buffer.ts b/cocos/gfx/empty/empty-command-buffer.ts index 770544f5943..b3de2aadc95 100644 --- a/cocos/gfx/empty/empty-command-buffer.ts +++ b/cocos/gfx/empty/empty-command-buffer.ts @@ -38,34 +38,34 @@ import { StencilFace, BufferSource, CommandBufferInfo, BufferTextureCopy, Color, } from '../base/define'; export class EmptyCommandBuffer extends CommandBuffer { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._type = info.type; this._queue = info.queue; } - public destroy () {} - public begin (renderPass?: RenderPass, subpass = 0, frameBuffer?: Framebuffer) {} - public end () {} + public destroy (): void {} + public begin (renderPass?: RenderPass, subpass = 0, frameBuffer?: Framebuffer): void {} + public end (): void {} public beginRenderPass (renderPass: RenderPass, framebuffer: Framebuffer, renderArea: Readonly, - clearColors: Readonly, clearDepth: number, clearStencil: number) {} - public endRenderPass () {} - public bindPipelineState (pipelineState: PipelineState) {} - public bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: Readonly) {} - public bindInputAssembler (inputAssembler: InputAssembler) {} - public setViewport (viewport: Readonly) {} - public setScissor (scissor: Readonly) {} - public setLineWidth (lineWidth: number) {} - public setDepthBias (depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number) {} - public setBlendConstants (blendConstants: Readonly) {} - public setDepthBound (minDepthBounds: number, maxDepthBounds: number) {} - public setStencilWriteMask (face: StencilFace, writeMask: number) {} - public setStencilCompareMask (face: StencilFace, reference: number, compareMask: number) {} - public draw (infoOrAssembler: Readonly | Readonly) {} - public updateBuffer (buffer: Buffer, data: Readonly, size?: number) {} - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) {} - public execute (cmdBuffs: Readonly, count: number) {} + clearColors: Readonly, clearDepth: number, clearStencil: number): void {} + public endRenderPass (): void {} + public bindPipelineState (pipelineState: PipelineState): void {} + public bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: Readonly): void {} + public bindInputAssembler (inputAssembler: InputAssembler): void {} + public setViewport (viewport: Readonly): void {} + public setScissor (scissor: Readonly): void {} + public setLineWidth (lineWidth: number): void {} + public setDepthBias (depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number): void {} + public setBlendConstants (blendConstants: Readonly): void {} + public setDepthBound (minDepthBounds: number, maxDepthBounds: number): void {} + public setStencilWriteMask (face: StencilFace, writeMask: number): void {} + public setStencilCompareMask (face: StencilFace, reference: number, compareMask: number): void {} + public draw (infoOrAssembler: Readonly | Readonly): void {} + public updateBuffer (buffer: Buffer, data: Readonly, size?: number): void {} + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void {} + public execute (cmdBuffs: Readonly, count: number): void {} public pipelineBarrier (GeneralBarrier: Readonly, bufferBarriers?: Readonly, buffers?: Readonly, textureBarriers?: Readonly, - textures?: Readonly) {} + textures?: Readonly): void {} public blitTexture (srcTexture: Readonly, dstTexture: Texture, regions: Readonly, filter: Filter): void {} } diff --git a/cocos/gfx/empty/empty-descriptor-set-layout.ts b/cocos/gfx/empty/empty-descriptor-set-layout.ts index 7e59e095c93..3e6c96b2923 100644 --- a/cocos/gfx/empty/empty-descriptor-set-layout.ts +++ b/cocos/gfx/empty/empty-descriptor-set-layout.ts @@ -26,8 +26,8 @@ import { DescriptorSetLayoutInfo } from '../base/define'; import { DescriptorSetLayout } from '../base/descriptor-set-layout'; export class EmptyDescriptorSetLayout extends DescriptorSetLayout { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { Array.prototype.push.apply(this._bindings, info.bindings); } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/empty/empty-descriptor-set.ts b/cocos/gfx/empty/empty-descriptor-set.ts index b75a15f31c8..4f39ec49961 100644 --- a/cocos/gfx/empty/empty-descriptor-set.ts +++ b/cocos/gfx/empty/empty-descriptor-set.ts @@ -26,9 +26,9 @@ import { DescriptorSet } from '../base/descriptor-set'; import { DescriptorSetInfo } from '../base/define'; export class EmptyDescriptorSet extends DescriptorSet { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._layout = info.layout; } - public destroy () {} - public update () {} + public destroy (): void {} + public update (): void {} } diff --git a/cocos/gfx/empty/empty-device.ts b/cocos/gfx/empty/empty-device.ts index 8958073ebda..b0465f8de61 100644 --- a/cocos/gfx/empty/empty-device.ts +++ b/cocos/gfx/empty/empty-device.ts @@ -91,9 +91,9 @@ export class EmptyDevice extends Device { this._swapchain = null; } - public flushCommands (cmdBuffs: Readonly) {} - public acquire (swapchains: Readonly) {} - public present () {} + public flushCommands (cmdBuffs: Readonly): void {} + public acquire (swapchains: Readonly): void {} + public present (): void {} public createCommandBuffer (info: Readonly): CommandBuffer { const cmdBuff = new EmptyCommandBuffer(); @@ -186,7 +186,7 @@ export class EmptyDevice extends Device { return [this._swapchain as Swapchain]; } - public getGeneralBarrier (info: Readonly) { + public getGeneralBarrier (info: Readonly): GeneralBarrier { const hash = GeneralBarrier.computeHash(info); if (!this._generalBarrierss.has(hash)) { this._generalBarrierss.set(hash, new GeneralBarrier(info, hash)); @@ -194,7 +194,7 @@ export class EmptyDevice extends Device { return this._generalBarrierss.get(hash)!; } - public getTextureBarrier (info: Readonly) { + public getTextureBarrier (info: Readonly): TextureBarrier { const hash = TextureBarrier.computeHash(info); if (!this._textureBarriers.has(hash)) { this._textureBarriers.set(hash, new TextureBarrier(info, hash)); @@ -202,7 +202,7 @@ export class EmptyDevice extends Device { return this._textureBarriers.get(hash)!; } - public getBufferBarrier (info: Readonly) { + public getBufferBarrier (info: Readonly): BufferBarrier { const hash = BufferBarrier.computeHash(info); if (!this._bufferBarriers.has(hash)) { this._bufferBarriers.set(hash, new BufferBarrier(info, hash)); @@ -210,9 +210,9 @@ export class EmptyDevice extends Device { return this._bufferBarriers.get(hash)!; } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) {} - public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly) {} - public copyTexImagesToTexture (texImages: Readonly, texture: Texture, regions: Readonly) {} + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void {} + public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly): void {} + public copyTexImagesToTexture (texImages: Readonly, texture: Texture, regions: Readonly): void {} } cclegacy.EmptyDevice = EmptyDevice; diff --git a/cocos/gfx/empty/empty-framebuffer.ts b/cocos/gfx/empty/empty-framebuffer.ts index bc9d01ec872..da61ec0f129 100644 --- a/cocos/gfx/empty/empty-framebuffer.ts +++ b/cocos/gfx/empty/empty-framebuffer.ts @@ -26,10 +26,10 @@ import { FramebufferInfo } from '../base/define'; import { Framebuffer } from '../base/framebuffer'; export class EmptyFramebuffer extends Framebuffer { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._renderPass = info.renderPass; this._colorTextures = info.colorTextures || []; this._depthStencilTexture = info.depthStencilTexture || null; } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/empty/empty-input-assembler.ts b/cocos/gfx/empty/empty-input-assembler.ts index b266c176ffe..3d9df167a46 100644 --- a/cocos/gfx/empty/empty-input-assembler.ts +++ b/cocos/gfx/empty/empty-input-assembler.ts @@ -26,7 +26,7 @@ import { InputAssemblerInfo } from '../base/define'; import { InputAssembler } from '../base/input-assembler'; export class EmptyInputAssembler extends InputAssembler { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._attributes = info.attributes; this._attributesHash = this.computeAttributesHash(); this._vertexBuffers = info.vertexBuffers; @@ -42,5 +42,5 @@ export class EmptyInputAssembler extends InputAssembler { this._drawInfo.vertexOffset = 0; } } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/empty/empty-pipeline-layout.ts b/cocos/gfx/empty/empty-pipeline-layout.ts index 709d509a72a..93eda468e2a 100644 --- a/cocos/gfx/empty/empty-pipeline-layout.ts +++ b/cocos/gfx/empty/empty-pipeline-layout.ts @@ -26,8 +26,8 @@ import { PipelineLayout } from '../base/pipeline-layout'; import { PipelineLayoutInfo } from '../base/define'; export class EmptyPipelineLayout extends PipelineLayout { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { Array.prototype.push.apply(this._setLayouts, info.setLayouts); } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/empty/empty-pipeline-state.ts b/cocos/gfx/empty/empty-pipeline-state.ts index 43329304023..8f32ccf4716 100644 --- a/cocos/gfx/empty/empty-pipeline-state.ts +++ b/cocos/gfx/empty/empty-pipeline-state.ts @@ -25,7 +25,7 @@ import { PipelineState, PipelineStateInfo } from '../base/pipeline-state'; export class EmptyPipelineState extends PipelineState { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._primitive = info.primitive; this._shader = info.shader; this._pipelineLayout = info.pipelineLayout; @@ -34,7 +34,7 @@ export class EmptyPipelineState extends PipelineState { const bsInfo = info.blendState; const { targets } = bsInfo; if (targets) { - targets.forEach((t, i) => { + targets.forEach((t, i): void => { bs.setTarget(i, t); }); } @@ -49,5 +49,5 @@ export class EmptyPipelineState extends PipelineState { this._renderPass = info.renderPass; this._dynamicStates = info.dynamicStates; } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/empty/empty-queue.ts b/cocos/gfx/empty/empty-queue.ts index bcf8fee8c3f..cee42522c64 100644 --- a/cocos/gfx/empty/empty-queue.ts +++ b/cocos/gfx/empty/empty-queue.ts @@ -27,9 +27,9 @@ import { CommandBuffer } from '../base/command-buffer'; import { Queue } from '../base/queue'; export class EmptyQueue extends Queue { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._type = info.type; } - public destroy () {} - public submit (cmdBuffs: Readonly) {} + public destroy (): void {} + public submit (cmdBuffs: Readonly): void {} } diff --git a/cocos/gfx/empty/empty-render-pass.ts b/cocos/gfx/empty/empty-render-pass.ts index fb0bfd341fe..c7b4b500609 100644 --- a/cocos/gfx/empty/empty-render-pass.ts +++ b/cocos/gfx/empty/empty-render-pass.ts @@ -26,11 +26,11 @@ import { RenderPassInfo } from '../base/define'; import { RenderPass } from '../base/render-pass'; export class EmptyRenderPass extends RenderPass { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._colorInfos = info.colorAttachments; this._depthStencilInfo = info.depthStencilAttachment; this._subpasses = info.subpasses; this._hash = this.computeHash(); } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/empty/empty-shader.ts b/cocos/gfx/empty/empty-shader.ts index 4c626f96087..3df59be25aa 100644 --- a/cocos/gfx/empty/empty-shader.ts +++ b/cocos/gfx/empty/empty-shader.ts @@ -27,8 +27,8 @@ import { ShaderInfo } from '../base/define'; import { Shader } from '../base/shader'; export class EmptyShader extends Shader { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { debug(`Shader '${info.name}' compilation succeeded.`); } - public destroy () {} + public destroy (): void {} } diff --git a/cocos/gfx/empty/empty-swapchain.ts b/cocos/gfx/empty/empty-swapchain.ts index c2e3d717ef6..b3cc0e84475 100644 --- a/cocos/gfx/empty/empty-swapchain.ts +++ b/cocos/gfx/empty/empty-swapchain.ts @@ -27,7 +27,7 @@ import { Swapchain } from '../base/swapchain'; import { EmptyTexture } from './empty-texture'; export class EmptySwapchain extends Swapchain { - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._colorTexture = new EmptyTexture(); this._colorTexture.initAsSwapchainTexture({ swapchain: this, @@ -45,5 +45,5 @@ export class EmptySwapchain extends Swapchain { }); } public destroy (): void {} - public resize (width: number, height: number, surfaceTransform: SurfaceTransform) {} + public resize (width: number, height: number, surfaceTransform: SurfaceTransform): void {} } diff --git a/cocos/gfx/empty/empty-texture.ts b/cocos/gfx/empty/empty-texture.ts index 077738dd883..6b1eb316c68 100644 --- a/cocos/gfx/empty/empty-texture.ts +++ b/cocos/gfx/empty/empty-texture.ts @@ -26,7 +26,7 @@ import { TextureInfo, TextureViewInfo, ISwapchainTextureInfo, FormatSurfaceSize, import { Texture } from '../base/texture'; export class EmptyTexture extends Texture { - public initialize (info: Readonly | Readonly, isSwapchainTexture?: boolean) { + public initialize (info: Readonly | Readonly, isSwapchainTexture?: boolean): void { let texInfo = info as Readonly; if ('texture' in info) { @@ -49,18 +49,18 @@ export class EmptyTexture extends Texture { this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount; } - public destroy () {} + public destroy (): void {} public getGLTextureHandle (): number { return 0; } - public resize (width: number, height: number) { + public resize (width: number, height: number): void { this._info.width = width; this._info.height = height; } /** * @engineInternal */ - public initAsSwapchainTexture (info: ISwapchainTextureInfo) {} + public initAsSwapchainTexture (info: ISwapchainTextureInfo): void {} } diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 8a9f598b5ae..9f6c308dc61 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -47,7 +47,7 @@ export class WebGLBuffer extends Buffer { private _gpuBufferView: IWebGLGPUBufferView | null = null; private _uniformBuffer: Uint8Array | null = null; - public initialize (info: Readonly | Readonly) { + public initialize (info: Readonly | Readonly): void { if ('buffer' in info) { // buffer view this._isBufferView = true; @@ -98,7 +98,7 @@ export class WebGLBuffer extends Buffer { } } - public destroy () { + public destroy (): void { if (this._gpuBuffer) { WebGLCmdFuncDestroyBuffer(WebGLDeviceManager.instance, this._gpuBuffer); WebGLDeviceManager.instance.memoryStatus.bufferSize -= this._size; @@ -110,7 +110,7 @@ export class WebGLBuffer extends Buffer { } } - public resize (size: number) { + public resize (size: number): void { if (this._isBufferView) { console.warn('cannot resize buffer views!'); return; @@ -140,7 +140,7 @@ export class WebGLBuffer extends Buffer { } } - public update (buffer: Readonly, size?: number) { + public update (buffer: Readonly, size?: number): void { if (this._isBufferView) { console.warn('cannot update through buffer views!'); return; diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 97ad1bf0ba2..85b49b7c59d 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -78,13 +78,13 @@ export class WebGLCommandPool { return cmd; } - public free (cmd: T) { + public free (cmd: T): void { if (--cmd.refCount === 0) { this._freeCmds.push(cmd); } } - public freeCmds (cmds: CachedArray) { + public freeCmds (cmds: CachedArray): void { // return ; for (let i = 0; i < cmds.length; ++i) { if (--cmds.array[i].refCount === 0) { @@ -93,7 +93,7 @@ export class WebGLCommandPool { } } - public release () { + public release (): void { for (let i = 0; i < this._freeCmds.length; ++i) { const cmd = this._freeCmds.array[i]; cmd.clear(); @@ -120,7 +120,7 @@ export class WebGLCommandAllocator { this.blitTextureCmdPool = new WebGLCommandPool(WebGLCmdBlitTexture, 1); } - public clearCmds (cmdPackage: WebGLCmdPackage) { + public clearCmds (cmdPackage: WebGLCmdPackage): void { if (cmdPackage.beginRenderPassCmds.length) { this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds); cmdPackage.beginRenderPassCmds.clear(); @@ -154,7 +154,7 @@ export class WebGLCommandAllocator { cmdPackage.cmds.clear(); } - public releaseCmds () { + public releaseCmds (): void { this.beginRenderPassCmdPool.release(); this.bindStatesCmdPool.release(); this.drawCmdPool.release(); diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 7cb4a1d8383..f4868493ec3 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -60,7 +60,7 @@ export class WebGLCommandBuffer extends CommandBuffer { protected _curDynamicStates: DynamicStates = new DynamicStates(); protected _isStateInvalied = false; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._type = info.type; this._queue = info.queue; @@ -70,11 +70,11 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public destroy () { + public destroy (): void { this._cmdAllocator.clearCmds(this.cmdPackage); } - public begin (renderPass?: RenderPass, subpass = 0, frameBuffer?: Framebuffer) { + public begin (renderPass?: RenderPass, subpass = 0, frameBuffer?: Framebuffer): void { this._cmdAllocator.clearCmds(this.cmdPackage); this._curGPUPipelineState = null; this._curGPUInputAssembler = null; @@ -84,7 +84,7 @@ export class WebGLCommandBuffer extends CommandBuffer { this._numTris = 0; } - public end () { + public end (): void { if (this._isStateInvalied) { this.bindStates(); } @@ -99,7 +99,7 @@ export class WebGLCommandBuffer extends CommandBuffer { clearColors: Readonly, clearDepth: number, clearStencil: number, - ) { + ): void { const cmd = this._cmdAllocator.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); cmd.gpuRenderPass = (renderPass as WebGLRenderPass).gpuRenderPass; cmd.gpuFramebuffer = (framebuffer as WebGLFramebuffer).gpuFramebuffer; @@ -117,11 +117,11 @@ export class WebGLCommandBuffer extends CommandBuffer { this._isInRenderPass = true; } - public endRenderPass () { + public endRenderPass (): void { this._isInRenderPass = false; } - public bindPipelineState (pipelineState: PipelineState) { + public bindPipelineState (pipelineState: PipelineState): void { const gpuPipelineState = (pipelineState as WebGLPipelineState).gpuPipelineState; if (gpuPipelineState !== this._curGPUPipelineState) { this._curGPUPipelineState = gpuPipelineState; @@ -129,7 +129,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: Readonly) { + public bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: Readonly): void { const gpuDescriptorSet = (descriptorSet as WebGLDescriptorSet).gpuDescriptorSet; if (gpuDescriptorSet !== this._curGPUDescriptorSets[set]) { this._curGPUDescriptorSets[set] = gpuDescriptorSet; @@ -146,13 +146,13 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public bindInputAssembler (inputAssembler: InputAssembler) { + public bindInputAssembler (inputAssembler: InputAssembler): void { const gpuInputAssembler = (inputAssembler as WebGLInputAssembler).gpuInputAssembler; this._curGPUInputAssembler = gpuInputAssembler; this._isStateInvalied = true; } - public setViewport (viewport: Readonly) { + public setViewport (viewport: Readonly): void { const cache = this._curDynamicStates.viewport; if (cache.left !== viewport.left || cache.top !== viewport.top @@ -170,7 +170,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public setScissor (scissor: Readonly) { + public setScissor (scissor: Readonly): void { const cache = this._curDynamicStates.scissor; if (cache.x !== scissor.x || cache.y !== scissor.y @@ -184,14 +184,14 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public setLineWidth (lineWidth: number) { + public setLineWidth (lineWidth: number): void { if (this._curDynamicStates.lineWidth !== lineWidth) { this._curDynamicStates.lineWidth = lineWidth; this._isStateInvalied = true; } } - public setDepthBias (depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number) { + public setDepthBias (depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number): void { const cache = this._curDynamicStates; if (cache.depthBiasConstant !== depthBiasConstantFactor || cache.depthBiasClamp !== depthBiasClamp @@ -203,7 +203,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public setBlendConstants (blendConstants: Readonly) { + public setBlendConstants (blendConstants: Readonly): void { const cache = this._curDynamicStates.blendConstant; if (cache.x !== blendConstants.x || cache.y !== blendConstants.y @@ -214,7 +214,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public setDepthBound (minDepthBounds: number, maxDepthBounds: number) { + public setDepthBound (minDepthBounds: number, maxDepthBounds: number): void { const cache = this._curDynamicStates; if (cache.depthMinBounds !== minDepthBounds || cache.depthMaxBounds !== maxDepthBounds) { @@ -224,7 +224,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public setStencilWriteMask (face: StencilFace, writeMask: number) { + public setStencilWriteMask (face: StencilFace, writeMask: number): void { const front = this._curDynamicStates.stencilStatesFront; const back = this._curDynamicStates.stencilStatesBack; if (face & StencilFace.FRONT) { @@ -241,7 +241,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public setStencilCompareMask (face: StencilFace, reference: number, compareMask: number) { + public setStencilCompareMask (face: StencilFace, reference: number, compareMask: number): void { const front = this._curDynamicStates.stencilStatesFront; const back = this._curDynamicStates.stencilStatesBack; if (face & StencilFace.FRONT) { @@ -262,7 +262,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public draw (infoOrAssembler: Readonly | Readonly) { + public draw (infoOrAssembler: Readonly | Readonly): void { if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass || this._type === CommandBufferType.SECONDARY) { if (this._isStateInvalied) { @@ -299,7 +299,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public updateBuffer (buffer: Buffer, data: Readonly, size?: number) { + public updateBuffer (buffer: Buffer, data: Readonly, size?: number): void { if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) { const gpuBuffer = (buffer as WebGLBuffer).gpuBuffer; @@ -335,7 +335,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void { if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) { const gpuTexture = (texture as WebGLTexture).gpuTexture; @@ -357,7 +357,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public execute (cmdBuffs: Readonly, count: number) { + public execute (cmdBuffs: Readonly, count: number): void { for (let i = 0; i < count; ++i) { const webGLCmdBuff = cmdBuffs[i] as WebGLCommandBuffer; @@ -408,9 +408,9 @@ export class WebGLCommandBuffer extends CommandBuffer { public pipelineBarrier (GeneralBarrier: Readonly, bufferBarriers?: Readonly, buffers?: Readonly, textureBarriers?: Readonly, - textures?: Readonly) {} + textures?: Readonly): void {} - protected bindStates () { + protected bindStates (): void { const bindStatesCmd = this._cmdAllocator.bindStatesCmdPool.alloc(WebGLCmdBindStates); if (bindStatesCmd) { diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 17343c3a0a6..9c4f73c093c 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -294,7 +294,7 @@ function GFXTypeToWebGLType (type: Type, gl: WebGLRenderingContext): GLenum { } } -function GFXTypeToTypedArrayCtor (type: Type) { +function GFXTypeToTypedArrayCtor (type: Type): Int32ArrayConstructor | Float32ArrayConstructor { switch (type) { case Type.BOOL: case Type.BOOL2: @@ -469,7 +469,7 @@ export class WebGLCmdBeginRenderPass extends WebGLCmdObject { super(WebGLCmd.BEGIN_RENDER_PASS); } - public clear () { + public clear (): void { this.gpuFramebuffer = null; this.clearColors.length = 0; } @@ -486,7 +486,7 @@ export class WebGLCmdBindStates extends WebGLCmdObject { super(WebGLCmd.BIND_STATES); } - public clear () { + public clear (): void { this.gpuPipelineState = null; this.gpuDescriptorSets.length = 0; this.gpuInputAssembler = null; @@ -501,7 +501,7 @@ export class WebGLCmdDraw extends WebGLCmdObject { super(WebGLCmd.DRAW); } - public clear () { + public clear (): void { } } @@ -515,7 +515,7 @@ export class WebGLCmdUpdateBuffer extends WebGLCmdObject { super(WebGLCmd.UPDATE_BUFFER); } - public clear () { + public clear (): void { this.gpuBuffer = null; this.buffer = null; } @@ -530,7 +530,7 @@ export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { super(WebGLCmd.COPY_BUFFER_TO_TEXTURE); } - public clear () { + public clear (): void { this.gpuTexture = null; this.buffers.length = 0; this.regions.length = 0; @@ -547,7 +547,7 @@ export class WebGLCmdBlitTexture extends WebGLCmdObject { super(WebGLCmd.BLIT_TEXTURE); } - public clear () { + public clear (): void { this.srcTexture = null; this.dstTexture = null; this.regions.length = 0; @@ -563,7 +563,7 @@ export class WebGLCmdPackage { public copyBufferToTextureCmds: CachedArray = new CachedArray(1); public blitTextureCmds: CachedArray = new CachedArray(1); - public clearCmds (allocator: WebGLCommandAllocator) { + public clearCmds (allocator: WebGLCommandAllocator): void { if (this.beginRenderPassCmds.length) { allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds); this.beginRenderPassCmds.clear(); @@ -598,7 +598,7 @@ export class WebGLCmdPackage { } } -export function WebGLCmdFuncCreateBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer) { +export function WebGLCmdFuncCreateBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer): void { const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; @@ -670,7 +670,7 @@ export function WebGLCmdFuncCreateBuffer (device: WebGLDevice, gpuBuffer: IWebGL } } -export function WebGLCmdFuncDestroyBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer) { +export function WebGLCmdFuncDestroyBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer): void { const { gl } = device; const cache = device.stateCache; @@ -710,7 +710,7 @@ export function WebGLCmdFuncDestroyBuffer (device: WebGLDevice, gpuBuffer: IWebG } } -export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer) { +export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer): void { const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; @@ -770,7 +770,7 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL } export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer, buffer: Readonly, - offset: number, size: number) { + offset: number, size: number): void { if (gpuBuffer.usage & BufferUsageBit.UNIFORM) { if (ArrayBuffer.isView(buffer)) { gpuBuffer.vf32!.set(buffer as Float32Array, offset / Float32Array.BYTES_PER_ELEMENT); @@ -833,7 +833,7 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGL } } -export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture) { +export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture): void { const { gl } = device; gpuTexture.glFormat = gpuTexture.glInternalFmt = GFXFormatToWebGLFormat(gpuTexture.format, gl); @@ -974,7 +974,7 @@ export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWeb } } -export function WebGLCmdFuncDestroyTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture) { +export function WebGLCmdFuncDestroyTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture): void { const { gl } = device; if (gpuTexture.glTexture) { const glTexUnits = device.stateCache.glTexUnits; @@ -1003,7 +1003,7 @@ export function WebGLCmdFuncDestroyTexture (device: WebGLDevice, gpuTexture: IWe } } -export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture) { +export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture): void { if (!gpuTexture.size) return; const { gl } = device; @@ -1101,7 +1101,7 @@ export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWeb } } -export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuffer: IWebGLGPUFramebuffer) { +export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuffer: IWebGLGPUFramebuffer): void { for (let i = 0; i < gpuFramebuffer.gpuColorTextures.length; ++i) { const tex = gpuFramebuffer.gpuColorTextures[i]; if (tex.isSwapchainTexture) { @@ -1203,7 +1203,7 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuff } } -export function WebGLCmdFuncDestroyFramebuffer (device: WebGLDevice, gpuFramebuffer: IWebGLGPUFramebuffer) { +export function WebGLCmdFuncDestroyFramebuffer (device: WebGLDevice, gpuFramebuffer: IWebGLGPUFramebuffer): void { if (gpuFramebuffer.glFramebuffer) { device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer); if (device.stateCache.glFramebuffer === gpuFramebuffer.glFramebuffer) { @@ -1214,7 +1214,7 @@ export function WebGLCmdFuncDestroyFramebuffer (device: WebGLDevice, gpuFramebuf } } -export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGLGPUShader) { +export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGLGPUShader): void { const { gl } = device; for (let k = 0; k < gpuShader.gpuStages.length; k++) { @@ -1249,7 +1249,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { console.error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); - console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, () => `\n${lineNumber++} `)); + console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); console.error(gl.getShaderInfoLog(gpuStage.glShader)); for (let l = 0; l < gpuShader.gpuStages.length; l++) { @@ -1563,7 +1563,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL gpuShader.glSamplerTextures = glActiveSamplers; } -export function WebGLCmdFuncDestroyShader (device: WebGLDevice, gpuShader: IWebGLGPUShader) { +export function WebGLCmdFuncDestroyShader (device: WebGLDevice, gpuShader: IWebGLGPUShader): void { if (gpuShader.glProgram) { const { gl } = device; if (!device.extensions.destroyShadersImmediately) { @@ -1585,7 +1585,7 @@ export function WebGLCmdFuncDestroyShader (device: WebGLDevice, gpuShader: IWebG } } -export function WebGLCmdFuncCreateInputAssember (device: WebGLDevice, gpuInputAssembler: IWebGLGPUInputAssembler) { +export function WebGLCmdFuncCreateInputAssember (device: WebGLDevice, gpuInputAssembler: IWebGLGPUInputAssembler): void { const { gl } = device; gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length); @@ -1619,7 +1619,7 @@ export function WebGLCmdFuncCreateInputAssember (device: WebGLDevice, gpuInputAs } } -export function WebGLCmdFuncDestroyInputAssembler (device: WebGLDevice, gpuInputAssembler: IWebGLGPUInputAssembler) { +export function WebGLCmdFuncDestroyInputAssembler (device: WebGLDevice, gpuInputAssembler: IWebGLGPUInputAssembler): void { const it = gpuInputAssembler.glVAOs.values(); let res = it.next(); const OES_vertex_array_object = device.extensions.OES_vertex_array_object!; @@ -1656,7 +1656,7 @@ export function WebGLCmdFuncBeginRenderPass ( clearColors: Readonly, clearDepth: number, clearStencil: number, -) { +): void { const { gl } = device; const cache = device.stateCache; let clears: GLbitfield = 0; @@ -1826,7 +1826,7 @@ export function WebGLCmdFuncBindStates ( gpuDescriptorSets: Readonly, dynamicOffsets: Readonly, dynamicStates: Readonly, -) { +): void { const { gl } = device; const cache = device.stateCache; const gpuShader = gpuPipelineState && gpuPipelineState.gpuShader; @@ -2560,7 +2560,7 @@ export function WebGLCmdFuncBindStates ( } // update dynamic states } -export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: Readonly) { +export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: Readonly): void { const { gl } = device; const { ANGLE_instanced_arrays: ia, WEBGL_multi_draw: md } = device.extensions; const { gpuInputAssembler, glPrimitive } = gfxStateCache; @@ -2642,7 +2642,7 @@ export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: Readonly(WebGLCmd.COUNT); -export function WebGLCmdFuncExecuteCmds (device: WebGLDevice, cmdPackage: WebGLCmdPackage) { +export function WebGLCmdFuncExecuteCmds (device: WebGLDevice, cmdPackage: WebGLCmdPackage): void { cmdIds.fill(0); for (let i = 0; i < cmdPackage.cmds.length; ++i) { @@ -2699,7 +2699,7 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( texImages: Readonly, gpuTexture: IWebGLGPUTexture, regions: Readonly, -) { +): void { const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { @@ -2787,7 +2787,7 @@ export function WebGLCmdFuncCopyBuffersToTexture ( buffers: Readonly, gpuTexture: IWebGLGPUTexture, regions: Readonly, -) { +): void { const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { @@ -2920,7 +2920,7 @@ export function WebGLCmdFuncCopyTextureToBuffers ( gpuTexture: IWebGLGPUTexture, buffers: Readonly, regions: Readonly, -) { +): void { const { gl } = device; const cache = device.stateCache; @@ -2954,7 +2954,7 @@ export function WebGLCmdFuncCopyTextureToBuffers ( } export function WebGLCmdFuncBlitTexture (device: WebGLDevice, - srcTexture: Readonly, dstTexture: IWebGLGPUTexture, regions: Readonly, filter: Filter) { + srcTexture: Readonly, dstTexture: IWebGLGPUTexture, regions: Readonly, filter: Filter): void { // logic different from native, because framebuffer map is not implemented in webgl device.blitManager.draw(srcTexture, dstTexture, regions as TextureBlit[], filter); } diff --git a/cocos/gfx/webgl/webgl-define.ts b/cocos/gfx/webgl/webgl-define.ts index 1e7caf0f129..39db595f0da 100644 --- a/cocos/gfx/webgl/webgl-define.ts +++ b/cocos/gfx/webgl/webgl-define.ts @@ -133,10 +133,10 @@ export interface IWebGLExtensions { // put the global instance here so that we won't have circular dependencies export class WebGLDeviceManager { - static get instance () { + static get instance (): WebGLDevice { return WebGLDeviceManager._instance!; } - static setInstance (instance: WebGLDevice) { + static setInstance (instance: WebGLDevice): void { WebGLDeviceManager._instance = instance; } private static _instance: WebGLDevice | null = null; diff --git a/cocos/gfx/webgl/webgl-descriptor-set-layout.ts b/cocos/gfx/webgl/webgl-descriptor-set-layout.ts index 8ec72b9118a..4649272f507 100644 --- a/cocos/gfx/webgl/webgl-descriptor-set-layout.ts +++ b/cocos/gfx/webgl/webgl-descriptor-set-layout.ts @@ -27,11 +27,11 @@ import { DescriptorSetLayout } from '../base/descriptor-set-layout'; import { IWebGLGPUDescriptorSetLayout } from './webgl-gpu-objects'; export class WebGLDescriptorSetLayout extends DescriptorSetLayout { - get gpuDescriptorSetLayout () { return this._gpuDescriptorSetLayout!; } + get gpuDescriptorSetLayout (): IWebGLGPUDescriptorSetLayout { return this._gpuDescriptorSetLayout!; } private _gpuDescriptorSetLayout: IWebGLGPUDescriptorSetLayout | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { Array.prototype.push.apply(this._bindings, info.bindings); let descriptorCount = 0; let maxBinding = -1; @@ -69,7 +69,7 @@ export class WebGLDescriptorSetLayout extends DescriptorSetLayout { }; } - public destroy () { + public destroy (): void { this._bindings.length = 0; } } diff --git a/cocos/gfx/webgl/webgl-descriptor-set.ts b/cocos/gfx/webgl/webgl-descriptor-set.ts index 38d6679a3cf..a9bc21122b3 100644 --- a/cocos/gfx/webgl/webgl-descriptor-set.ts +++ b/cocos/gfx/webgl/webgl-descriptor-set.ts @@ -37,7 +37,7 @@ export class WebGLDescriptorSet extends DescriptorSet { private _gpuDescriptorSet: IWebGLGPUDescriptorSet | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._layout = info.layout; const { bindings, descriptorIndices, descriptorCount } = (info.layout as WebGLDescriptorSetLayout).gpuDescriptorSetLayout; @@ -61,12 +61,12 @@ export class WebGLDescriptorSet extends DescriptorSet { } } - public destroy () { + public destroy (): void { this._layout = null; this._gpuDescriptorSet = null; } - public update () { + public update (): void { if (this._isDirty && this._gpuDescriptorSet) { const descriptors = this._gpuDescriptorSet.gpuDescriptors; for (let i = 0; i < descriptors.length; ++i) { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 440d08a16b5..6367e870c88 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -64,26 +64,27 @@ import { BufferBarrier } from '../base/states/buffer-barrier'; import { debug } from '../../core'; import { Swapchain } from '../base/swapchain'; import { IWebGLExtensions, WebGLDeviceManager } from './webgl-define'; -import { IWebGLBindingMapping } from './webgl-gpu-objects'; +import { IWebGLBindingMapping, IWebGLBlitManager } from './webgl-gpu-objects'; +import type { WebGLStateCache } from './webgl-state-cache'; export class WebGLDevice extends Device { - get gl () { + get gl (): WebGLRenderingContext { return this._context!; } - get extensions () { + get extensions (): IWebGLExtensions { return this._swapchain!.extensions; } - get stateCache () { + get stateCache (): WebGLStateCache { return this._swapchain!.stateCache; } - get nullTex2D () { + get nullTex2D (): WebGLTexture { return this._swapchain!.nullTex2D; } - get nullTexCube () { + get nullTexCube (): WebGLTexture { return this._swapchain!.nullTexCube; } @@ -91,11 +92,11 @@ export class WebGLDevice extends Device { return this._textureExclusive; } - get bindingMappings () { + get bindingMappings (): IWebGLBindingMapping { return this._bindingMappings!; } - get blitManager () { + get blitManager (): IWebGLBlitManager { return this._swapchain!.blitManager; } @@ -243,11 +244,11 @@ export class WebGLDevice extends Device { this._swapchain = null; } - public flushCommands (cmdBuffs: CommandBuffer[]) {} + public flushCommands (cmdBuffs: CommandBuffer[]): void {} - public acquire (swapchains: Swapchain[]) {} + public acquire (swapchains: Swapchain[]): void {} - public present () { + public present (): void { const queue = (this._queue as WebGLQueue); this._numDrawCalls = queue.numDrawCalls; this._numInstances = queue.numInstances; @@ -255,7 +256,7 @@ export class WebGLDevice extends Device { queue.clear(); } - protected initFormatFeatures (exts: IWebGLExtensions) { + protected initFormatFeatures (exts: IWebGLExtensions): void { this._formatFeatures.fill(FormatFeatureBit.NONE); this._textureExclusive.fill(true); @@ -509,7 +510,7 @@ export class WebGLDevice extends Device { return [this._swapchain as Swapchain]; } - public getGeneralBarrier (info: Readonly) { + public getGeneralBarrier (info: Readonly): GeneralBarrier { const hash = GeneralBarrier.computeHash(info); if (!this._generalBarrierss.has(hash)) { this._generalBarrierss.set(hash, new GeneralBarrier(info, hash)); @@ -517,7 +518,7 @@ export class WebGLDevice extends Device { return this._generalBarrierss.get(hash)!; } - public getTextureBarrier (info: Readonly) { + public getTextureBarrier (info: Readonly): TextureBarrier { const hash = TextureBarrier.computeHash(info); if (!this._textureBarriers.has(hash)) { this._textureBarriers.set(hash, new TextureBarrier(info, hash)); @@ -525,7 +526,7 @@ export class WebGLDevice extends Device { return this._textureBarriers.get(hash)!; } - public getBufferBarrier (info: Readonly) { + public getBufferBarrier (info: Readonly): BufferBarrier { const hash = BufferBarrier.computeHash(info); if (!this._bufferBarriers.has(hash)) { this._bufferBarriers.set(hash, new BufferBarrier(info, hash)); @@ -533,7 +534,7 @@ export class WebGLDevice extends Device { return this._bufferBarriers.get(hash)!; } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void { WebGLCmdFuncCopyBuffersToTexture( this, buffers as ArrayBufferView[], @@ -542,7 +543,7 @@ export class WebGLDevice extends Device { ); } - public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly) { + public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly): void { WebGLCmdFuncCopyTextureToBuffers( this, (texture as WebGLTexture).gpuTexture, @@ -555,7 +556,7 @@ export class WebGLDevice extends Device { texImages: Readonly, texture: Texture, regions: Readonly, - ) { + ): void { WebGLCmdFuncCopyTexImagesToTexture( this, texImages, diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts index 287fd3ca0d3..e60aa0b3691 100644 --- a/cocos/gfx/webgl/webgl-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -38,7 +38,7 @@ export class WebGLFramebuffer extends Framebuffer { private _gpuFramebuffer: IWebGLGPUFramebuffer | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._renderPass = info.renderPass; this._colorTextures = info.colorTextures || []; this._depthStencilTexture = info.depthStencilTexture || null; @@ -68,13 +68,13 @@ export class WebGLFramebuffer extends Framebuffer { gpuDepthStencilTexture, glFramebuffer: null, isOffscreen: true, - get width () { + get width (): number { return this.isOffscreen ? width : this.gpuColorTextures[0].width; }, set width (val) { width = val; }, - get height () { + get height (): number { return this.isOffscreen ? height : this.gpuColorTextures[0].height; }, set height (val) { @@ -86,7 +86,7 @@ export class WebGLFramebuffer extends Framebuffer { WebGLCmdFuncCreateFramebuffer(WebGLDeviceManager.instance, this._gpuFramebuffer); } - public destroy () { + public destroy (): void { if (this._gpuFramebuffer) { WebGLCmdFuncDestroyFramebuffer(WebGLDeviceManager.instance, this._gpuFramebuffer); this._gpuFramebuffer = null; diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index e8d6e563b18..8abff6d139d 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -58,13 +58,13 @@ export class WebGLIndirectDrawInfos { this.byteOffsets = new Int32Array(this._capacity); } - public clearDraws () { + public clearDraws (): void { this.drawCount = 0; this.drawByIndex = false; this.instancedDraw = false; } - public setDrawInfo (idx: number, info: Readonly) { + public setDrawInfo (idx: number, info: Readonly): void { this._ensureCapacity(idx); this.drawByIndex = info.indexCount > 0; this.instancedDraw = !!info.instanceCount; @@ -80,7 +80,7 @@ export class WebGLIndirectDrawInfos { this.instances[idx] = Math.max(1, info.instanceCount); } - private _ensureCapacity (target: number) { + private _ensureCapacity (target: number): void { if (this._capacity > target) return; this._capacity = nextPow2(target); @@ -498,7 +498,7 @@ export class IWebGLBlitManager { this._glFramebuffer = WebGLDeviceManager.instance.gl.createFramebuffer(); } - public destroy () { + public destroy (): void { if (this._glFramebuffer) { WebGLDeviceManager.instance.gl.deleteFramebuffer(this._glFramebuffer); this._glFramebuffer = null; @@ -519,7 +519,7 @@ export class IWebGLBlitManager { } } - public draw (gpuTextureSrc: IWebGLGPUTexture, gpuTextureDst: IWebGLGPUTexture, regions: TextureBlit[], filter: Filter) { + public draw (gpuTextureSrc: IWebGLGPUTexture, gpuTextureDst: IWebGLGPUTexture, regions: TextureBlit[], filter: Filter): void { const device = WebGLDeviceManager.instance; const { gl } = device; const stateCache = device.stateCache; @@ -545,8 +545,8 @@ export class IWebGLBlitManager { attachment = gl.DEPTH_ATTACHMENT; } - const regionIndices = regions.map((_, i) => i); - regionIndices.sort((a, b) => regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel); + const regionIndices = regions.map((_, i): number => i); + regionIndices.sort((a, b): number => regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel); if (stateCache.glFramebuffer !== this._glFramebuffer) { device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, this._glFramebuffer); diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index 61f41e570f5..58a188c6a4e 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -36,7 +36,7 @@ export class WebGLInputAssembler extends InputAssembler { private _gpuInputAssembler: IWebGLGPUInputAssembler | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { if (info.vertexBuffers.length === 0) { console.error('InputAssemblerInfo.vertexBuffers is null.'); return; @@ -104,7 +104,7 @@ export class WebGLInputAssembler extends InputAssembler { WebGLCmdFuncCreateInputAssember(WebGLDeviceManager.instance, this._gpuInputAssembler); } - public destroy () { + public destroy (): void { const device = WebGLDeviceManager.instance; if (this._gpuInputAssembler && device.extensions.useVAO) { WebGLCmdFuncDestroyInputAssembler(device, this._gpuInputAssembler); diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts index 56f904a9fda..64053a6d70a 100644 --- a/cocos/gfx/webgl/webgl-pipeline-layout.ts +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -28,11 +28,11 @@ import { WebGLDescriptorSetLayout } from './webgl-descriptor-set-layout'; import { PipelineLayoutInfo } from '../base/define'; export class WebGLPipelineLayout extends PipelineLayout { - get gpuPipelineLayout () { return this._gpuPipelineLayout!; } + get gpuPipelineLayout (): IWebGLGPUPipelineLayout { return this._gpuPipelineLayout!; } private _gpuPipelineLayout: IWebGLGPUPipelineLayout | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { Array.prototype.push.apply(this._setLayouts, info.setLayouts); const dynamicOffsetIndices: number[][] = []; @@ -63,7 +63,7 @@ export class WebGLPipelineLayout extends PipelineLayout { }; } - public destroy () { + public destroy (): void { this._setLayouts.length = 0; } } diff --git a/cocos/gfx/webgl/webgl-pipeline-state.ts b/cocos/gfx/webgl/webgl-pipeline-state.ts index 63701a9b104..6460f7f9502 100644 --- a/cocos/gfx/webgl/webgl-pipeline-state.ts +++ b/cocos/gfx/webgl/webgl-pipeline-state.ts @@ -53,7 +53,7 @@ export class WebGLPipelineState extends PipelineState { private _gpuPipelineState: IWebGLGPUPipelineState | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._primitive = info.primitive; this._shader = info.shader; this._pipelineLayout = info.pipelineLayout; @@ -62,7 +62,7 @@ export class WebGLPipelineState extends PipelineState { const bsInfo = info.blendState; const { targets } = bsInfo; if (targets) { - targets.forEach((t, i) => { + targets.forEach((t, i): void => { bs.setTarget(i, t); }); } @@ -96,7 +96,7 @@ export class WebGLPipelineState extends PipelineState { }; } - public destroy () { + public destroy (): void { this._gpuPipelineState = null; } } diff --git a/cocos/gfx/webgl/webgl-primary-command-buffer.ts b/cocos/gfx/webgl/webgl-primary-command-buffer.ts index e6f34ad3c91..792defd0fc7 100644 --- a/cocos/gfx/webgl/webgl-primary-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-primary-command-buffer.ts @@ -47,7 +47,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { clearColors: Readonly, clearDepth: number, clearStencil: number, - ) { + ): void { WebGLCmdFuncBeginRenderPass( WebGLDeviceManager.instance, (renderPass as WebGLRenderPass).gpuRenderPass, @@ -57,7 +57,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { this._isInRenderPass = true; } - public draw (infoOrAssembler: DrawInfo | InputAssembler) { + public draw (infoOrAssembler: DrawInfo | InputAssembler): void { if (this._isInRenderPass) { if (this._isStateInvalied) { this.bindStates(); @@ -90,7 +90,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { } } - public setViewport (viewport: Readonly) { + public setViewport (viewport: Readonly): void { const { stateCache: cache, gl } = WebGLDeviceManager.instance; if (cache.viewport.left !== viewport.left @@ -106,7 +106,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { } } - public setScissor (scissor: Readonly) { + public setScissor (scissor: Readonly): void { const { stateCache: cache, gl } = WebGLDeviceManager.instance; if (cache.scissorRect.x !== scissor.x @@ -122,7 +122,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { } } - public updateBuffer (buffer: Buffer, data: Readonly, size?: number) { + public updateBuffer (buffer: Buffer, data: Readonly, size?: number): void { if (!this._isInRenderPass) { const gpuBuffer = (buffer as WebGLBuffer).gpuBuffer; if (gpuBuffer) { @@ -142,7 +142,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { } } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void { if (!this._isInRenderPass) { const gpuTexture = (texture as WebGLTexture).gpuTexture; if (gpuTexture) { @@ -153,7 +153,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { } } - public execute (cmdBuffs: Readonly, count: number) { + public execute (cmdBuffs: Readonly, count: number): void { for (let i = 0; i < count; ++i) { // actually they are secondary buffers, the cast here is only for type checking const webGLCmdBuff = cmdBuffs[i] as WebGLPrimaryCommandBuffer; @@ -164,7 +164,7 @@ export class WebGLPrimaryCommandBuffer extends WebGLCommandBuffer { } } - protected bindStates () { + protected bindStates (): void { WebGLCmdFuncBindStates(WebGLDeviceManager.instance, this._curGPUPipelineState, this._curGPUInputAssembler, this._curGPUDescriptorSets, this._curDynamicOffsets, this._curDynamicStates); this._isStateInvalied = false; diff --git a/cocos/gfx/webgl/webgl-queue.ts b/cocos/gfx/webgl/webgl-queue.ts index 1cbccb4aa4e..f5e5e4b1868 100644 --- a/cocos/gfx/webgl/webgl-queue.ts +++ b/cocos/gfx/webgl/webgl-queue.ts @@ -31,14 +31,14 @@ export class WebGLQueue extends Queue { public numInstances = 0; public numTris = 0; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._type = info.type; } - public destroy () { + public destroy (): void { } - public submit (cmdBuffs: Readonly) { + public submit (cmdBuffs: Readonly): void { const len = cmdBuffs.length; for (let i = 0; i < len; i++) { const cmdBuff = cmdBuffs[i]; @@ -49,7 +49,7 @@ export class WebGLQueue extends Queue { } } - public clear () { + public clear (): void { this.numDrawCalls = 0; this.numInstances = 0; this.numTris = 0; diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts index 328d5cf97ca..f612634e620 100644 --- a/cocos/gfx/webgl/webgl-render-pass.ts +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -33,7 +33,7 @@ export class WebGLRenderPass extends RenderPass { private _gpuRenderPass: IWebGLGPURenderPass | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._colorInfos = info.colorAttachments; this._depthStencilInfo = info.depthStencilAttachment; this._subpasses = info.subpasses; @@ -46,7 +46,7 @@ export class WebGLRenderPass extends RenderPass { this._hash = this.computeHash(); } - public destroy () { + public destroy (): void { this._gpuRenderPass = null; } } diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/gfx/webgl/webgl-shader.ts index e7d5ed07798..29e89c77630 100644 --- a/cocos/gfx/webgl/webgl-shader.ts +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -38,7 +38,7 @@ export class WebGLShader extends Shader { private _gpuShader: IWebGLGPUShader | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._name = info.name; this._stages = info.stages; this._attributes = info.attributes; @@ -69,7 +69,7 @@ export class WebGLShader extends Shader { } } - public destroy () { + public destroy (): void { if (this._gpuShader) { WebGLCmdFuncDestroyShader(WebGLDeviceManager.instance, this._gpuShader); this._gpuShader = null; diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index c5a52cd6474..7114526a19d 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -47,7 +47,7 @@ export class WebGLStateCache { public glCurrentAttribLocs: boolean[] = []; public texUnitCacheMap: Record = {}; - initialize (texUnit: number, vertexAttributes: number) { + initialize (texUnit: number, vertexAttributes: number): void { for (let i = 0; i < texUnit; ++i) this.glTexUnits.push({ glTexture: null }); this.glEnabledAttribLocs.length = vertexAttributes; diff --git a/cocos/gfx/webgl/webgl-swapchain.ts b/cocos/gfx/webgl/webgl-swapchain.ts index 7c3b1ff4607..5d84c51ad3a 100644 --- a/cocos/gfx/webgl/webgl-swapchain.ts +++ b/cocos/gfx/webgl/webgl-swapchain.ts @@ -37,7 +37,7 @@ import { IWebGLBlitManager } from './webgl-gpu-objects'; const eventWebGLContextLost = 'webglcontextlost'; -function initStates (gl: WebGLRenderingContext) { +function initStates (gl: WebGLRenderingContext): void { gl.activeTexture(gl.TEXTURE0); gl.pixelStorei(gl.PACK_ALIGNMENT, 1); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); @@ -88,7 +88,7 @@ function getExtension (gl: WebGLRenderingContext, ext: string): any { return null; } -export function getExtensions (gl: WebGLRenderingContext) { +export function getExtensions (gl: WebGLRenderingContext): IWebGLExtensions { const res: IWebGLExtensions = { EXT_texture_filter_anisotropic: getExtension(gl, 'EXT_texture_filter_anisotropic'), EXT_blend_minmax: getExtension(gl, 'EXT_blend_minmax'), @@ -215,11 +215,11 @@ export function getContext (canvas: HTMLCanvasElement): WebGLRenderingContext | } export class WebGLSwapchain extends Swapchain { - get extensions () { + get extensions (): IWebGLExtensions { return this._extensions as IWebGLExtensions; } - get blitManager () { + get blitManager (): IWebGLBlitManager { return this._blitManager!; } @@ -233,7 +233,7 @@ export class WebGLSwapchain extends Swapchain { private _extensions: IWebGLExtensions | null = null; private _blitManager: IWebGLBlitManager | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._canvas = info.windowHandle; this._webGLContextLostHandler = this._onWebGLContextLost.bind(this); @@ -341,7 +341,7 @@ export class WebGLSwapchain extends Swapchain { this._canvas = null; } - public resize (width: number, height: number, surfaceTransform: SurfaceTransform) { + public resize (width: number, height: number, surfaceTransform: SurfaceTransform): void { if (this._colorTexture.width !== width || this._colorTexture.height !== height) { debug(`Resizing swapchain: ${width}x${height}`); this._canvas!.width = width; @@ -351,7 +351,7 @@ export class WebGLSwapchain extends Swapchain { } } - private _onWebGLContextLost (event: Event) { + private _onWebGLContextLost (event: Event): void { warnID(11000); warn(event); // 2020.9.3: `preventDefault` is not available on some platforms diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index 2ecb6c6c3b8..ef16fbd24ee 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -40,7 +40,7 @@ export class WebGLTexture extends Texture { private _gpuTexture: IWebGLGPUTexture | null = null; private _lodLevel = 0; - public initialize (info: Readonly | Readonly, isSwapchainTexture?: boolean) { + public initialize (info: Readonly | Readonly, isSwapchainTexture?: boolean): void { let texInfo = info as Readonly; const viewInfo = info as Readonly; @@ -104,7 +104,7 @@ export class WebGLTexture extends Texture { } } - public destroy () { + public destroy (): void { if (!this._isTextureView && this._gpuTexture) { WebGLCmdFuncDestroyTexture(WebGLDeviceManager.instance, this._gpuTexture); WebGLDeviceManager.instance.memoryStatus.textureSize -= this._size; @@ -127,7 +127,7 @@ export class WebGLTexture extends Texture { return 0; } - public resize (width: number, height: number) { + public resize (width: number, height: number): void { if (this._info.width === width && this._info.height === height) { return; } @@ -162,7 +162,7 @@ export class WebGLTexture extends Texture { /** * @engineInternal */ - public initAsSwapchainTexture (info: Readonly) { + public initAsSwapchainTexture (info: Readonly): void { const texInfo = new TextureInfo(); texInfo.format = info.format; texInfo.usage = FormatInfos[info.format].hasDepth ? TextureUsageBit.DEPTH_STENCIL_ATTACHMENT : TextureUsageBit.COLOR_ATTACHMENT; diff --git a/cocos/gfx/webgl2/states/webgl2-sampler.ts b/cocos/gfx/webgl2/states/webgl2-sampler.ts index 4c75f7960af..f1af1ca9bfc 100644 --- a/cocos/gfx/webgl2/states/webgl2-sampler.ts +++ b/cocos/gfx/webgl2/states/webgl2-sampler.ts @@ -78,7 +78,7 @@ export class WebGL2Sampler extends Sampler { WebGL2CmdFuncPrepareSamplerInfo(WebGL2DeviceManager.instance, this._gpuSampler); } - destroy () { + destroy (): void { if (this._gpuSampler) { WebGL2CmdFuncDestroySampler(WebGL2DeviceManager.instance, this._gpuSampler); this._gpuSampler = null; diff --git a/cocos/gfx/webgl2/webgl2-buffer.ts b/cocos/gfx/webgl2/webgl2-buffer.ts index 6353ed5d42f..a9f868dd156 100644 --- a/cocos/gfx/webgl2/webgl2-buffer.ts +++ b/cocos/gfx/webgl2/webgl2-buffer.ts @@ -40,7 +40,7 @@ export class WebGL2Buffer extends Buffer { private _gpuBuffer: IWebGL2GPUBuffer | null = null; - public initialize (info: Readonly | Readonly) { + public initialize (info: Readonly | Readonly): void { if ('buffer' in info) { // buffer view this._isBufferView = true; @@ -89,7 +89,7 @@ export class WebGL2Buffer extends Buffer { } } - public destroy () { + public destroy (): void { if (this._gpuBuffer) { if (!this._isBufferView) { WebGL2CmdFuncDestroyBuffer(WebGL2DeviceManager.instance, this._gpuBuffer); @@ -99,7 +99,7 @@ export class WebGL2Buffer extends Buffer { } } - public resize (size: number) { + public resize (size: number): void { if (this._isBufferView) { console.warn('cannot resize buffer views!'); return; @@ -121,7 +121,7 @@ export class WebGL2Buffer extends Buffer { } } - public update (buffer: Readonly, size?: number) { + public update (buffer: Readonly, size?: number): void { if (this._isBufferView) { console.warn('cannot update through buffer views!'); return; diff --git a/cocos/gfx/webgl2/webgl2-command-allocator.ts b/cocos/gfx/webgl2/webgl2-command-allocator.ts index 2a977eefd4a..e5bb408adc5 100644 --- a/cocos/gfx/webgl2/webgl2-command-allocator.ts +++ b/cocos/gfx/webgl2/webgl2-command-allocator.ts @@ -78,13 +78,13 @@ export class WebGL2CommandPool { return cmd; } - public free (cmd: T) { + public free (cmd: T): void { if (--cmd.refCount === 0) { this._freeCmds.push(cmd); } } - public freeCmds (cmds: CachedArray) { + public freeCmds (cmds: CachedArray): void { // return ; for (let i = 0; i < cmds.length; ++i) { if (--cmds.array[i].refCount === 0) { @@ -93,7 +93,7 @@ export class WebGL2CommandPool { } } - public release () { + public release (): void { for (let i = 0; i < this._freeCmds.length; ++i) { const cmd = this._freeCmds.array[i]; cmd.clear(); @@ -120,7 +120,7 @@ export class WebGL2CommandAllocator { this.blitTextureCmdPool = new WebGL2CommandPool(WebGL2CmdBlitTexture, 1); } - public clearCmds (cmdPackage: WebGL2CmdPackage) { + public clearCmds (cmdPackage: WebGL2CmdPackage): void { if (cmdPackage.beginRenderPassCmds.length) { this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds); cmdPackage.beginRenderPassCmds.clear(); @@ -154,7 +154,7 @@ export class WebGL2CommandAllocator { cmdPackage.cmds.clear(); } - public releaseCmds () { + public releaseCmds (): void { this.beginRenderPassCmdPool.release(); this.bindStatesCmdPool.release(); this.drawCmdPool.release(); diff --git a/cocos/gfx/webgl2/webgl2-command-buffer.ts b/cocos/gfx/webgl2/webgl2-command-buffer.ts index 39698b185fa..c4810681b6f 100644 --- a/cocos/gfx/webgl2/webgl2-command-buffer.ts +++ b/cocos/gfx/webgl2/webgl2-command-buffer.ts @@ -73,7 +73,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { protected _curDynamicStates: DynamicStates = new DynamicStates(); protected _isStateInvalied = false; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._type = info.type; this._queue = info.queue; @@ -83,11 +83,11 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public destroy () { + public destroy (): void { this._cmdAllocator.clearCmds(this.cmdPackage); } - public begin (renderPass?: RenderPass, subpass = 0, frameBuffer?: Framebuffer) { + public begin (renderPass?: RenderPass, subpass = 0, frameBuffer?: Framebuffer): void { this._cmdAllocator.clearCmds(this.cmdPackage); this._curGPUPipelineState = null; this._curGPUInputAssembler = null; @@ -97,7 +97,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { this._numTris = 0; } - public end () { + public end (): void { if (this._isStateInvalied) { this.bindStates(); } @@ -112,7 +112,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { clearColors: Readonly, clearDepth: number, clearStencil: number, - ) { + ): void { const cmd = this._cmdAllocator.beginRenderPassCmdPool.alloc(WebGL2CmdBeginRenderPass); cmd.gpuRenderPass = (renderPass as WebGL2RenderPass).gpuRenderPass; cmd.gpuFramebuffer = (framebuffer as WebGL2Framebuffer).gpuFramebuffer; @@ -129,11 +129,11 @@ export class WebGL2CommandBuffer extends CommandBuffer { this._isInRenderPass = true; } - public endRenderPass () { + public endRenderPass (): void { this._isInRenderPass = false; } - public bindPipelineState (pipelineState: PipelineState) { + public bindPipelineState (pipelineState: PipelineState): void { const gpuPipelineState = (pipelineState as WebGL2PipelineState).gpuPipelineState; if (gpuPipelineState !== this._curGPUPipelineState) { this._curGPUPipelineState = gpuPipelineState; @@ -141,7 +141,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: Readonly) { + public bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: Readonly): void { const gpuDescriptorSets = (descriptorSet as WebGL2DescriptorSet).gpuDescriptorSet; if (gpuDescriptorSets !== this._curGPUDescriptorSets[set]) { this._curGPUDescriptorSets[set] = gpuDescriptorSets; @@ -158,13 +158,13 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public bindInputAssembler (inputAssembler: InputAssembler) { + public bindInputAssembler (inputAssembler: InputAssembler): void { const gpuInputAssembler = (inputAssembler as WebGL2InputAssembler).gpuInputAssembler; this._curGPUInputAssembler = gpuInputAssembler; this._isStateInvalied = true; } - public setViewport (viewport: Readonly) { + public setViewport (viewport: Readonly): void { const cache = this._curDynamicStates.viewport; if (cache.left !== viewport.left || cache.top !== viewport.top @@ -182,7 +182,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public setScissor (scissor: Readonly) { + public setScissor (scissor: Readonly): void { const cache = this._curDynamicStates.scissor; if (cache.x !== scissor.x || cache.y !== scissor.y @@ -196,14 +196,14 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public setLineWidth (lineWidth: number) { + public setLineWidth (lineWidth: number): void { if (this._curDynamicStates.lineWidth !== lineWidth) { this._curDynamicStates.lineWidth = lineWidth; this._isStateInvalied = true; } } - public setDepthBias (depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number) { + public setDepthBias (depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number): void { const cache = this._curDynamicStates; if (cache.depthBiasConstant !== depthBiasConstantFactor || cache.depthBiasClamp !== depthBiasClamp @@ -215,7 +215,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public setBlendConstants (blendConstants: Color) { + public setBlendConstants (blendConstants: Color): void { const cache = this._curDynamicStates.blendConstant; if (cache.x !== blendConstants.x || cache.y !== blendConstants.y @@ -226,7 +226,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public setDepthBound (minDepthBounds: number, maxDepthBounds: number) { + public setDepthBound (minDepthBounds: number, maxDepthBounds: number): void { const cache = this._curDynamicStates; if (cache.depthMinBounds !== minDepthBounds || cache.depthMaxBounds !== maxDepthBounds) { @@ -236,7 +236,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public setStencilWriteMask (face: StencilFace, writeMask: number) { + public setStencilWriteMask (face: StencilFace, writeMask: number): void { const front = this._curDynamicStates.stencilStatesFront; const back = this._curDynamicStates.stencilStatesBack; if (face & StencilFace.FRONT) { @@ -253,7 +253,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public setStencilCompareMask (face: StencilFace, reference: number, compareMask: number) { + public setStencilCompareMask (face: StencilFace, reference: number, compareMask: number): void { const front = this._curDynamicStates.stencilStatesFront; const back = this._curDynamicStates.stencilStatesBack; if (face & StencilFace.FRONT) { @@ -274,7 +274,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public draw (infoOrAssembler: Readonly | Readonly) { + public draw (infoOrAssembler: Readonly | Readonly): void { if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass || this._type === CommandBufferType.SECONDARY) { if (this._isStateInvalied) { @@ -311,7 +311,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public updateBuffer (buffer: Buffer, data: Readonly, size?: number) { + public updateBuffer (buffer: Buffer, data: Readonly, size?: number): void { if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) { const gpuBuffer = (buffer as WebGL2Buffer).gpuBuffer; @@ -346,7 +346,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void { if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) { const gpuTexture = (texture as WebGL2Texture).gpuTexture; @@ -366,7 +366,7 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public execute (cmdBuffs: Readonly, count: number) { + public execute (cmdBuffs: Readonly, count: number): void { for (let i = 0; i < count; ++i) { const webGL2CmdBuff = cmdBuffs[i] as WebGL2CommandBuffer; @@ -417,9 +417,9 @@ export class WebGL2CommandBuffer extends CommandBuffer { public pipelineBarrier (GeneralBarrier: Readonly, bufferBarriers?: Readonly, buffers?: Readonly, textureBarriers?: Readonly, - textures?: Readonly) {} + textures?: Readonly): void {} - protected bindStates () { + protected bindStates (): void { const bindStatesCmd = this._cmdAllocator.bindStatesCmdPool.alloc(WebGL2CmdBindStates); bindStatesCmd.gpuPipelineState = this._curGPUPipelineState; Array.prototype.push.apply(bindStatesCmd.gpuDescriptorSets, this._curGPUDescriptorSets); diff --git a/cocos/gfx/webgl2/webgl2-commands.ts b/cocos/gfx/webgl2/webgl2-commands.ts index 85405ec8b48..136a6eebfd7 100644 --- a/cocos/gfx/webgl2/webgl2-commands.ts +++ b/cocos/gfx/webgl2/webgl2-commands.ts @@ -648,7 +648,7 @@ export class WebGL2CmdBeginRenderPass extends WebGL2CmdObject { super(WebGL2Cmd.BEGIN_RENDER_PASS); } - public clear () { + public clear (): void { this.gpuFramebuffer = null; this.clearColors.length = 0; } @@ -665,7 +665,7 @@ export class WebGL2CmdBindStates extends WebGL2CmdObject { super(WebGL2Cmd.BIND_STATES); } - public clear () { + public clear (): void { this.gpuPipelineState = null; this.gpuInputAssembler = null; this.gpuDescriptorSets.length = 0; @@ -680,7 +680,7 @@ export class WebGL2CmdDraw extends WebGL2CmdObject { super(WebGL2Cmd.DRAW); } - public clear () { + public clear (): void { } } @@ -694,7 +694,7 @@ export class WebGL2CmdUpdateBuffer extends WebGL2CmdObject { super(WebGL2Cmd.UPDATE_BUFFER); } - public clear () { + public clear (): void { this.gpuBuffer = null; this.buffer = null; } @@ -709,7 +709,7 @@ export class WebGL2CmdCopyBufferToTexture extends WebGL2CmdObject { super(WebGL2Cmd.COPY_BUFFER_TO_TEXTURE); } - public clear () { + public clear (): void { this.gpuTexture = null; this.buffers.length = 0; this.regions.length = 0; @@ -726,7 +726,7 @@ export class WebGL2CmdBlitTexture extends WebGL2CmdObject { super(WebGL2Cmd.BLIT_TEXTURE); } - public clear () { + public clear (): void { this.srcTexture = null; this.dstTexture = null; this.regions.length = 0; @@ -742,7 +742,7 @@ export class WebGL2CmdPackage { public copyBufferToTextureCmds: CachedArray = new CachedArray(1); public blitTextureCmds: CachedArray = new CachedArray(1); - public clearCmds (allocator: WebGL2CommandAllocator) { + public clearCmds (allocator: WebGL2CommandAllocator): void { if (this.beginRenderPassCmds.length) { allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds); this.beginRenderPassCmds.clear(); @@ -777,7 +777,7 @@ export class WebGL2CmdPackage { } } -export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer) { +export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer): void { const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; @@ -860,7 +860,7 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWeb } } -export function WebGL2CmdFuncDestroyBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer) { +export function WebGL2CmdFuncDestroyBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer): void { const { gl } = device; const cache = device.stateCache; @@ -904,7 +904,7 @@ export function WebGL2CmdFuncDestroyBuffer (device: WebGL2Device, gpuBuffer: IWe } } -export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer) { +export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer): void { const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; @@ -968,7 +968,7 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb } export function WebGL2CmdFuncUpdateBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer, buffer: Readonly, - offset: number, size: number) { + offset: number, size: number): void { if (gpuBuffer.usage & BufferUsageBit.INDIRECT) { gpuBuffer.indirects.clearDraws(); const drawInfos = (buffer as IndirectBuffer).drawInfos; @@ -1043,7 +1043,7 @@ export function WebGL2CmdFuncUpdateBuffer (device: WebGL2Device, gpuBuffer: IWeb } } -export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture) { +export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture): void { const { gl } = device; gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl); @@ -1206,7 +1206,7 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW } } -export function WebGL2CmdFuncDestroyTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture) { +export function WebGL2CmdFuncDestroyTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture): void { const { gl } = device; if (gpuTexture.glTexture) { const glTexUnits = device.stateCache.glTexUnits; @@ -1235,7 +1235,7 @@ export function WebGL2CmdFuncDestroyTexture (device: WebGL2Device, gpuTexture: I } } -export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture) { +export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture): void { if (!gpuTexture.size) return; const { gl } = device; @@ -1394,7 +1394,7 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW } } -export function WebGL2CmdFuncPrepareSamplerInfo (device: WebGL2Device, gpuSampler: IWebGL2GPUSampler) { +export function WebGL2CmdFuncPrepareSamplerInfo (device: WebGL2Device, gpuSampler: IWebGL2GPUSampler): void { const { gl } = device; if (gpuSampler.minFilter === Filter.LINEAR || gpuSampler.minFilter === Filter.ANISOTROPIC) { @@ -1424,7 +1424,7 @@ export function WebGL2CmdFuncPrepareSamplerInfo (device: WebGL2Device, gpuSample gpuSampler.glWrapR = WebGLWraps[gpuSampler.addressW]; } -export function WebGL2CmdFuncDestroySampler (device: WebGL2Device, gpuSampler: IWebGL2GPUSampler) { +export function WebGL2CmdFuncDestroySampler (device: WebGL2Device, gpuSampler: IWebGL2GPUSampler): void { const { gl } = device; const it = gpuSampler.glSamplers.values(); const res = it.next(); @@ -1444,7 +1444,7 @@ export function WebGL2CmdFuncDestroySampler (device: WebGL2Device, gpuSampler: I gpuSampler.glSamplers.clear(); } -export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebuffer: IWebGL2GPUFramebuffer) { +export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebuffer: IWebGL2GPUFramebuffer): void { for (let i = 0; i < gpuFramebuffer.gpuColorViews.length; ++i) { const tex = gpuFramebuffer.gpuColorViews[i].gpuTexture; if (tex.isSwapchainTexture) { @@ -1546,7 +1546,7 @@ export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebu } } -export function WebGL2CmdFuncDestroyFramebuffer (device: WebGL2Device, gpuFramebuffer: IWebGL2GPUFramebuffer) { +export function WebGL2CmdFuncDestroyFramebuffer (device: WebGL2Device, gpuFramebuffer: IWebGL2GPUFramebuffer): void { if (gpuFramebuffer.glFramebuffer) { device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer); if (device.stateCache.glFramebuffer === gpuFramebuffer.glFramebuffer) { @@ -1557,7 +1557,7 @@ export function WebGL2CmdFuncDestroyFramebuffer (device: WebGL2Device, gpuFrameb } } -export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWebGL2GPUShader) { +export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWebGL2GPUShader): void { const { gl } = device; for (let k = 0; k < gpuShader.gpuStages.length; k++) { @@ -1592,7 +1592,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { console.error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); - console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, () => `\n${lineNumber++} `)); + console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); console.error(gl.getShaderInfoLog(gpuStage.glShader)); for (let l = 0; l < gpuShader.gpuStages.length; l++) { @@ -1854,7 +1854,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb gpuShader.glSamplerTextures = glActiveSamplers; } -export function WebGL2CmdFuncDestroyShader (device: WebGL2Device, gpuShader: IWebGL2GPUShader) { +export function WebGL2CmdFuncDestroyShader (device: WebGL2Device, gpuShader: IWebGL2GPUShader): void { if (gpuShader.glProgram) { device.gl.deleteProgram(gpuShader.glProgram); if (device.stateCache.glProgram === gpuShader.glProgram) { @@ -1865,7 +1865,7 @@ export function WebGL2CmdFuncDestroyShader (device: WebGL2Device, gpuShader: IWe } } -export function WebGL2CmdFuncCreateInputAssember (device: WebGL2Device, gpuInputAssembler: IWebGL2GPUInputAssembler) { +export function WebGL2CmdFuncCreateInputAssember (device: WebGL2Device, gpuInputAssembler: IWebGL2GPUInputAssembler): void { const { gl } = device; gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length); @@ -1900,7 +1900,7 @@ export function WebGL2CmdFuncCreateInputAssember (device: WebGL2Device, gpuInput } } -export function WebGL2CmdFuncDestroyInputAssembler (device: WebGL2Device, gpuInputAssembler: IWebGL2GPUInputAssembler) { +export function WebGL2CmdFuncDestroyInputAssembler (device: WebGL2Device, gpuInputAssembler: IWebGL2GPUInputAssembler): void { const it = gpuInputAssembler.glVAOs.values(); let res = it.next(); const { gl } = device; @@ -1938,7 +1938,7 @@ export function WebGL2CmdFuncBeginRenderPass ( clearColors: Readonly, clearDepth: number, clearStencil: number, -) { +): void { const { gl } = device; const cache = device.stateCache; @@ -2104,7 +2104,7 @@ export function WebGL2CmdFuncBindStates ( gpuDescriptorSets: Readonly, dynamicOffsets: Readonly, dynamicStates: Readonly, -) { +): void { const { gl } = device; const cache = device.stateCache; const gpuShader = gpuPipelineState && gpuPipelineState.gpuShader; @@ -2622,7 +2622,7 @@ export function WebGL2CmdFuncBindStates ( } // update dynamic states } -export function WebGL2CmdFuncDraw (device: WebGL2Device, drawInfo: Readonly) { +export function WebGL2CmdFuncDraw (device: WebGL2Device, drawInfo: Readonly): void { const { gl } = device; const { gpuInputAssembler, glPrimitive } = gfxStateCache; const md = device.extensions.WEBGL_multi_draw; @@ -2704,7 +2704,7 @@ export function WebGL2CmdFuncDraw (device: WebGL2Device, drawInfo: Readonly(WebGL2Cmd.COUNT); -export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebGL2CmdPackage) { +export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebGL2CmdPackage): void { cmdIds.fill(0); for (let i = 0; i < cmdPackage.cmds.length; ++i) { @@ -2756,7 +2756,7 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebG } // for } -function toUseTexImage2D (texImages: Readonly, regions: Readonly) { +function toUseTexImage2D (texImages: Readonly, regions: Readonly): boolean { if (texImages.length > 1 || regions.length > 1) return false; const isVideoElement = texImages[0] instanceof HTMLVideoElement; if (isVideoElement) { @@ -2775,7 +2775,7 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( texImages: Readonly, gpuTexture: IWebGL2GPUTexture, regions: Readonly, -) { +): void { const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { @@ -2865,7 +2865,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( buffers: Readonly, gpuTexture: IWebGL2GPUTexture, regions: Readonly, -) { +): void { const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { @@ -3100,7 +3100,7 @@ export function WebGL2CmdFuncCopyTextureToBuffers ( gpuTexture: IWebGL2GPUTexture, buffers: Readonly, regions: Readonly, -) { +): void { const { gl } = device; const cache = device.stateCache; @@ -3140,7 +3140,7 @@ export function WebGL2CmdFuncBlitFramebuffer ( srcRect: Readonly, dstRect: Readonly, filter: Filter, -) { +): void { const { gl } = device; if (device.stateCache.glReadFramebuffer !== src.glFramebuffer) { @@ -3184,7 +3184,7 @@ export function WebGL2CmdFuncBlitTexture ( dst: IWebGL2GPUTexture, regions: Readonly, filter: Filter, -) { +): void { const { gl } = device; const cache = device.stateCache; const blitManager = device.blitManager; @@ -3203,7 +3203,7 @@ export function WebGL2CmdFuncBlitTexture ( let srcMip = regions[0].srcSubres.mipLevel; let dstMip = regions[0].dstSubres.mipLevel; - const blitInfo = (formatInfo: FormatInfo) => { + const blitInfo = (formatInfo: FormatInfo): { mask: number; attachment: number; } => { let mask = 0; let attachment = gl.COLOR_ATTACHMENT0; @@ -3227,8 +3227,8 @@ export function WebGL2CmdFuncBlitTexture ( return { mask, attachment }; }; - const regionIndices = regions.map((_, i) => i); - regionIndices.sort((a, b) => regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel); + const regionIndices = regions.map((_, i): number => i); + regionIndices.sort((a, b): number => regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel); const { mask: srcMask, attachment: srcAttachment } = blitInfo(FormatInfos[src.format]); const { mask: dstMask, attachment: dstAttachment } = blitInfo(FormatInfos[dst.format]); diff --git a/cocos/gfx/webgl2/webgl2-define.ts b/cocos/gfx/webgl2/webgl2-define.ts index 6bfe1593457..771aaf03719 100644 --- a/cocos/gfx/webgl2/webgl2-define.ts +++ b/cocos/gfx/webgl2/webgl2-define.ts @@ -106,10 +106,10 @@ export interface IWebGL2Extensions { // put the global instance here so that we won't have circular dependencies export class WebGL2DeviceManager { - static get instance () { + static get instance (): WebGL2Device { return WebGL2DeviceManager._instance!; } - static setInstance (instance: WebGL2Device) { + static setInstance (instance: WebGL2Device): void { WebGL2DeviceManager._instance = instance; } private static _instance: WebGL2Device | null = null; diff --git a/cocos/gfx/webgl2/webgl2-descriptor-set-layout.ts b/cocos/gfx/webgl2/webgl2-descriptor-set-layout.ts index 66af8f60504..b3de7a73d29 100644 --- a/cocos/gfx/webgl2/webgl2-descriptor-set-layout.ts +++ b/cocos/gfx/webgl2/webgl2-descriptor-set-layout.ts @@ -27,11 +27,11 @@ import { DescriptorSetLayout } from '../base/descriptor-set-layout'; import { IWebGL2GPUDescriptorSetLayout } from './webgl2-gpu-objects'; export class WebGL2DescriptorSetLayout extends DescriptorSetLayout { - get gpuDescriptorSetLayout () { return this._gpuDescriptorSetLayout!; } + get gpuDescriptorSetLayout (): IWebGL2GPUDescriptorSetLayout { return this._gpuDescriptorSetLayout!; } private _gpuDescriptorSetLayout: IWebGL2GPUDescriptorSetLayout | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { Array.prototype.push.apply(this._bindings, info.bindings); let descriptorCount = 0; let maxBinding = -1; @@ -69,7 +69,7 @@ export class WebGL2DescriptorSetLayout extends DescriptorSetLayout { }; } - public destroy () { + public destroy (): void { this._bindings.length = 0; } } diff --git a/cocos/gfx/webgl2/webgl2-descriptor-set.ts b/cocos/gfx/webgl2/webgl2-descriptor-set.ts index 65cd99a2341..2fa4a5b3481 100644 --- a/cocos/gfx/webgl2/webgl2-descriptor-set.ts +++ b/cocos/gfx/webgl2/webgl2-descriptor-set.ts @@ -37,7 +37,7 @@ export class WebGL2DescriptorSet extends DescriptorSet { private _gpuDescriptorSet: IWebGL2GPUDescriptorSet | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._layout = info.layout; const { bindings, descriptorIndices, descriptorCount } = (info.layout as WebGL2DescriptorSetLayout).gpuDescriptorSetLayout; @@ -61,12 +61,12 @@ export class WebGL2DescriptorSet extends DescriptorSet { } } - public destroy () { + public destroy (): void { this._layout = null; this._gpuDescriptorSet = null; } - public update () { + public update (): void { if (this._isDirty && this._gpuDescriptorSet) { const descriptors = this._gpuDescriptorSet.gpuDescriptors; for (let i = 0; i < descriptors.length; ++i) { diff --git a/cocos/gfx/webgl2/webgl2-device.ts b/cocos/gfx/webgl2/webgl2-device.ts index c346230e5f4..c46c3e65395 100644 --- a/cocos/gfx/webgl2/webgl2-device.ts +++ b/cocos/gfx/webgl2/webgl2-device.ts @@ -65,27 +65,28 @@ import { BufferBarrier } from '../base/states/buffer-barrier'; import { debug, sys } from '../../core'; import { Swapchain } from '../base/swapchain'; import { IWebGL2Extensions, WebGL2DeviceManager } from './webgl2-define'; -import { IWebGL2BindingMapping } from './webgl2-gpu-objects'; +import { IWebGL2BindingMapping, IWebGL2BlitManager } from './webgl2-gpu-objects'; import { BrowserType, OS } from '../../../pal/system-info/enum-type'; +import type { WebGL2StateCache } from './webgl2-state-cache'; export class WebGL2Device extends Device { - get gl () { + get gl (): WebGL2RenderingContext { return this._context!; } - get extensions () { + get extensions (): IWebGL2Extensions { return this._swapchain!.extensions; } - get stateCache () { + get stateCache (): WebGL2StateCache { return this._swapchain!.stateCache; } - get nullTex2D () { + get nullTex2D (): WebGL2Texture { return this._swapchain!.nullTex2D; } - get nullTexCube () { + get nullTexCube (): WebGL2Texture { return this._swapchain!.nullTexCube; } @@ -93,11 +94,11 @@ export class WebGL2Device extends Device { return this._textureExclusive; } - get bindingMappings () { + get bindingMappings (): IWebGL2BindingMapping { return this._bindingMappings!; } - get blitManager () { + get blitManager (): IWebGL2BlitManager | null { return this._swapchain!.blitManager; } @@ -253,11 +254,11 @@ export class WebGL2Device extends Device { this._swapchain = null; } - public flushCommands (cmdBuffs: Readonly) {} + public flushCommands (cmdBuffs: Readonly): void {} - public acquire (swapchains: Readonly) {} + public acquire (swapchains: Readonly): void {} - public present () { + public present (): void { const queue = (this._queue as WebGL2Queue); this._numDrawCalls = queue.numDrawCalls; this._numInstances = queue.numInstances; @@ -265,7 +266,7 @@ export class WebGL2Device extends Device { queue.clear(); } - protected initFormatFeatures (exts: IWebGL2Extensions) { + protected initFormatFeatures (exts: IWebGL2Extensions): void { this._formatFeatures.fill(FormatFeatureBit.NONE); this._textureExclusive.fill(true); @@ -576,7 +577,7 @@ export class WebGL2Device extends Device { return [this._swapchain as Swapchain]; } - public getGeneralBarrier (info: Readonly) { + public getGeneralBarrier (info: Readonly): GeneralBarrier { const hash = GeneralBarrier.computeHash(info); if (!this._generalBarrierss.has(hash)) { this._generalBarrierss.set(hash, new GeneralBarrier(info, hash)); @@ -584,7 +585,7 @@ export class WebGL2Device extends Device { return this._generalBarrierss.get(hash)!; } - public getTextureBarrier (info: Readonly) { + public getTextureBarrier (info: Readonly): TextureBarrier { const hash = TextureBarrier.computeHash(info); if (!this._textureBarriers.has(hash)) { this._textureBarriers.set(hash, new TextureBarrier(info, hash)); @@ -592,7 +593,7 @@ export class WebGL2Device extends Device { return this._textureBarriers.get(hash)!; } - public getBufferBarrier (info: Readonly) { + public getBufferBarrier (info: Readonly): BufferBarrier { const hash = BufferBarrier.computeHash(info); if (!this._bufferBarriers.has(hash)) { this._bufferBarriers.set(hash, new BufferBarrier(info, hash)); @@ -600,7 +601,7 @@ export class WebGL2Device extends Device { return this._bufferBarriers.get(hash)!; } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void { WebGL2CmdFuncCopyBuffersToTexture( this, buffers, @@ -609,7 +610,7 @@ export class WebGL2Device extends Device { ); } - public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly) { + public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly): void { WebGL2CmdFuncCopyTextureToBuffers( this, (texture as WebGL2Texture).gpuTexture, @@ -622,7 +623,7 @@ export class WebGL2Device extends Device { texImages: Readonly, texture: Texture, regions: Readonly, - ) { + ): void { WebGL2CmdFuncCopyTexImagesToTexture( this, texImages, diff --git a/cocos/gfx/webgl2/webgl2-framebuffer.ts b/cocos/gfx/webgl2/webgl2-framebuffer.ts index 596a3295bbf..8ee609cb4b5 100644 --- a/cocos/gfx/webgl2/webgl2-framebuffer.ts +++ b/cocos/gfx/webgl2/webgl2-framebuffer.ts @@ -37,7 +37,7 @@ export class WebGL2Framebuffer extends Framebuffer { private _gpuFramebuffer: IWebGL2GPUFramebuffer | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._renderPass = info.renderPass; this._colorTextures = info.colorTextures || []; this._depthStencilTexture = info.depthStencilTexture || null; @@ -63,7 +63,7 @@ export class WebGL2Framebuffer extends Framebuffer { gpuDepthStencilView, glFramebuffer: null, isOffscreen: true, - get width () { + get width (): number { if (this.isOffscreen) { return width; } else if (this.gpuColorViews.length > 0) { @@ -75,7 +75,7 @@ export class WebGL2Framebuffer extends Framebuffer { set width (val) { width = val; }, - get height () { + get height (): number { if (this.isOffscreen) { return width; } else if (this.gpuColorViews.length > 0) { @@ -92,7 +92,7 @@ export class WebGL2Framebuffer extends Framebuffer { WebGL2CmdFuncCreateFramebuffer(WebGL2DeviceManager.instance, this._gpuFramebuffer); } - public destroy () { + public destroy (): void { if (this._gpuFramebuffer) { WebGL2CmdFuncDestroyFramebuffer(WebGL2DeviceManager.instance, this._gpuFramebuffer); this._gpuFramebuffer = null; diff --git a/cocos/gfx/webgl2/webgl2-gpu-objects.ts b/cocos/gfx/webgl2/webgl2-gpu-objects.ts index 2bd64282424..1cdec040420 100644 --- a/cocos/gfx/webgl2/webgl2-gpu-objects.ts +++ b/cocos/gfx/webgl2/webgl2-gpu-objects.ts @@ -52,13 +52,13 @@ export class WebGL2IndirectDrawInfos { this.byteOffsets = new Int32Array(this._capacity); } - public clearDraws () { + public clearDraws (): void { this.drawCount = 0; this.drawByIndex = false; this.instancedDraw = false; } - public setDrawInfo (idx: number, info: Readonly) { + public setDrawInfo (idx: number, info: Readonly): void { this._ensureCapacity(idx); this.drawByIndex = info.indexCount > 0; this.instancedDraw = !!info.instanceCount; @@ -74,7 +74,7 @@ export class WebGL2IndirectDrawInfos { this.instances[idx] = Math.max(1, info.instanceCount); } - private _ensureCapacity (target: number) { + private _ensureCapacity (target: number): void { if (this._capacity > target) return; this._capacity = nextPow2(target); @@ -326,11 +326,11 @@ export class IWebGL2BlitManager { private _srcFramebuffer: WebGLFramebuffer | null; private _dstFramebuffer: WebGLFramebuffer | null; - get srcFramebuffer () { + get srcFramebuffer (): WebGLFramebuffer | null { return this._srcFramebuffer; } - get dstFramebuffer () { + get dstFramebuffer (): WebGLFramebuffer | null { return this._dstFramebuffer; } @@ -340,7 +340,7 @@ export class IWebGL2BlitManager { this._dstFramebuffer = gl.createFramebuffer(); } - destroy () { + destroy (): void { const { gl } = WebGL2DeviceManager.instance; gl.deleteFramebuffer(this._srcFramebuffer); gl.deleteFramebuffer(this._dstFramebuffer); diff --git a/cocos/gfx/webgl2/webgl2-input-assembler.ts b/cocos/gfx/webgl2/webgl2-input-assembler.ts index bb066d39365..ec1e5566d9f 100644 --- a/cocos/gfx/webgl2/webgl2-input-assembler.ts +++ b/cocos/gfx/webgl2/webgl2-input-assembler.ts @@ -36,7 +36,7 @@ export class WebGL2InputAssembler extends InputAssembler { private _gpuInputAssembler: IWebGL2GPUInputAssembler | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { if (info.vertexBuffers.length === 0) { console.error('InputAssemblerInfo.vertexBuffers is null.'); return; @@ -104,7 +104,7 @@ export class WebGL2InputAssembler extends InputAssembler { WebGL2CmdFuncCreateInputAssember(WebGL2DeviceManager.instance, this._gpuInputAssembler); } - public destroy () { + public destroy (): void { const device = WebGL2DeviceManager.instance; if (this._gpuInputAssembler && device.extensions.useVAO) { WebGL2CmdFuncDestroyInputAssembler(device, this._gpuInputAssembler); diff --git a/cocos/gfx/webgl2/webgl2-pipeline-layout.ts b/cocos/gfx/webgl2/webgl2-pipeline-layout.ts index 4e21412ba02..43cbc9c36b3 100644 --- a/cocos/gfx/webgl2/webgl2-pipeline-layout.ts +++ b/cocos/gfx/webgl2/webgl2-pipeline-layout.ts @@ -28,11 +28,11 @@ import { WebGL2DescriptorSetLayout } from './webgl2-descriptor-set-layout'; import { PipelineLayoutInfo } from '../base/define'; export class WebGL2PipelineLayout extends PipelineLayout { - get gpuPipelineLayout () { return this._gpuPipelineLayout!; } + get gpuPipelineLayout (): IWebGL2GPUPipelineLayout { return this._gpuPipelineLayout!; } private _gpuPipelineLayout: IWebGL2GPUPipelineLayout | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { Array.prototype.push.apply(this._setLayouts, info.setLayouts); const dynamicOffsetIndices: number[][] = []; @@ -63,7 +63,7 @@ export class WebGL2PipelineLayout extends PipelineLayout { }; } - public destroy () { + public destroy (): void { this._setLayouts.length = 0; } } diff --git a/cocos/gfx/webgl2/webgl2-pipeline-state.ts b/cocos/gfx/webgl2/webgl2-pipeline-state.ts index d4175e81136..94bd74f7162 100644 --- a/cocos/gfx/webgl2/webgl2-pipeline-state.ts +++ b/cocos/gfx/webgl2/webgl2-pipeline-state.ts @@ -53,7 +53,7 @@ export class WebGL2PipelineState extends PipelineState { private _gpuPipelineState: IWebGL2GPUPipelineState | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._primitive = info.primitive; this._shader = info.shader; this._pipelineLayout = info.pipelineLayout; @@ -62,7 +62,7 @@ export class WebGL2PipelineState extends PipelineState { const bsInfo = info.blendState; const { targets } = bsInfo; if (targets) { - targets.forEach((t, i) => { + targets.forEach((t, i): void => { bs.setTarget(i, t); }); } @@ -96,7 +96,7 @@ export class WebGL2PipelineState extends PipelineState { }; } - public destroy () { + public destroy (): void { this._gpuPipelineState = null; } } diff --git a/cocos/gfx/webgl2/webgl2-primary-command-buffer.ts b/cocos/gfx/webgl2/webgl2-primary-command-buffer.ts index d6b5db5e443..1866ed39133 100644 --- a/cocos/gfx/webgl2/webgl2-primary-command-buffer.ts +++ b/cocos/gfx/webgl2/webgl2-primary-command-buffer.ts @@ -47,7 +47,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { clearColors: Readonly, clearDepth: number, clearStencil: number, - ) { + ): void { WebGL2CmdFuncBeginRenderPass( WebGL2DeviceManager.instance, (renderPass as WebGL2RenderPass).gpuRenderPass, @@ -57,7 +57,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { this._isInRenderPass = true; } - public draw (infoOrAssembler: Readonly | Readonly) { + public draw (infoOrAssembler: Readonly | Readonly): void { if (this._isInRenderPass) { if (this._isStateInvalied) { this.bindStates(); @@ -90,7 +90,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { } } - public setViewport (viewport: Readonly) { + public setViewport (viewport: Readonly): void { const { stateCache: cache, gl } = WebGL2DeviceManager.instance; if (cache.viewport.left !== viewport.left @@ -106,7 +106,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { } } - public setScissor (scissor: Readonly) { + public setScissor (scissor: Readonly): void { const { stateCache: cache, gl } = WebGL2DeviceManager.instance; if (cache.scissorRect.x !== scissor.x @@ -122,7 +122,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { } } - public updateBuffer (buffer: Buffer, data: Readonly, size?: number) { + public updateBuffer (buffer: Buffer, data: Readonly, size?: number): void { if (!this._isInRenderPass) { const gpuBuffer = (buffer as WebGL2Buffer).gpuBuffer; if (gpuBuffer) { @@ -142,7 +142,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { } } - public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly): void { if (!this._isInRenderPass) { const gpuTexture = (texture as WebGL2Texture).gpuTexture; if (gpuTexture) { @@ -153,7 +153,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { } } - public execute (cmdBuffs: Readonly, count: number) { + public execute (cmdBuffs: Readonly, count: number): void { for (let i = 0; i < count; ++i) { // actually they are secondary buffers, the cast here is only for type checking const webGL2CmdBuff = cmdBuffs[i] as WebGL2PrimaryCommandBuffer; @@ -164,7 +164,7 @@ export class WebGL2PrimaryCommandBuffer extends WebGL2CommandBuffer { } } - protected bindStates () { + protected bindStates (): void { WebGL2CmdFuncBindStates(WebGL2DeviceManager.instance, this._curGPUPipelineState, this._curGPUInputAssembler, this._curGPUDescriptorSets, this._curDynamicOffsets, this._curDynamicStates); this._isStateInvalied = false; diff --git a/cocos/gfx/webgl2/webgl2-queue.ts b/cocos/gfx/webgl2/webgl2-queue.ts index 117d8cc8af7..6f1d95731c4 100644 --- a/cocos/gfx/webgl2/webgl2-queue.ts +++ b/cocos/gfx/webgl2/webgl2-queue.ts @@ -32,14 +32,14 @@ export class WebGL2Queue extends Queue { public numInstances = 0; public numTris = 0; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._type = info.type; } - public destroy () { + public destroy (): void { } - public submit (cmdBuffs: Readonly) { + public submit (cmdBuffs: Readonly): void { for (let i = 0; i < cmdBuffs.length; i++) { const cmdBuff = cmdBuffs[i] as WebGL2CommandBuffer; // WebGL2CmdFuncExecuteCmds(this._device as WebGL2Device, cmdBuff.cmdPackage); // opted out @@ -49,7 +49,7 @@ export class WebGL2Queue extends Queue { } } - public clear () { + public clear (): void { this.numDrawCalls = 0; this.numInstances = 0; this.numTris = 0; diff --git a/cocos/gfx/webgl2/webgl2-render-pass.ts b/cocos/gfx/webgl2/webgl2-render-pass.ts index c307a5fab12..b52ea442d78 100644 --- a/cocos/gfx/webgl2/webgl2-render-pass.ts +++ b/cocos/gfx/webgl2/webgl2-render-pass.ts @@ -33,7 +33,7 @@ export class WebGL2RenderPass extends RenderPass { private _gpuRenderPass: IWebGL2GPURenderPass | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._colorInfos = info.colorAttachments; this._depthStencilInfo = info.depthStencilAttachment; this._subpasses = info.subpasses; @@ -46,7 +46,7 @@ export class WebGL2RenderPass extends RenderPass { this._hash = this.computeHash(); } - public destroy () { + public destroy (): void { this._gpuRenderPass = null; } } diff --git a/cocos/gfx/webgl2/webgl2-shader.ts b/cocos/gfx/webgl2/webgl2-shader.ts index 94f92ccb1a3..485384dbe70 100644 --- a/cocos/gfx/webgl2/webgl2-shader.ts +++ b/cocos/gfx/webgl2/webgl2-shader.ts @@ -38,7 +38,7 @@ export class WebGL2Shader extends Shader { private _gpuShader: IWebGL2GPUShader | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._name = info.name; this._stages = info.stages; this._attributes = info.attributes; @@ -69,7 +69,7 @@ export class WebGL2Shader extends Shader { } } - public destroy () { + public destroy (): void { if (this._gpuShader) { WebGL2CmdFuncDestroyShader(WebGL2DeviceManager.instance, this._gpuShader); this._gpuShader = null; diff --git a/cocos/gfx/webgl2/webgl2-state-cache.ts b/cocos/gfx/webgl2/webgl2-state-cache.ts index 37ee443dcc1..8653e2e52ec 100644 --- a/cocos/gfx/webgl2/webgl2-state-cache.ts +++ b/cocos/gfx/webgl2/webgl2-state-cache.ts @@ -52,7 +52,7 @@ export class WebGL2StateCache { public glCurrentAttribLocs: boolean[] = []; public texUnitCacheMap: Record = {}; - initialize (texUnit: number, bufferBindings: number, vertexAttributes: number) { + initialize (texUnit: number, bufferBindings: number, vertexAttributes: number): void { for (let i = 0; i < texUnit; ++i) this.glTexUnits.push({ glTexture: null }); this.glSamplerUnits.length = texUnit; diff --git a/cocos/gfx/webgl2/webgl2-swapchain.ts b/cocos/gfx/webgl2/webgl2-swapchain.ts index 83b9ff4329c..6b499933e56 100644 --- a/cocos/gfx/webgl2/webgl2-swapchain.ts +++ b/cocos/gfx/webgl2/webgl2-swapchain.ts @@ -36,7 +36,7 @@ import { IWebGL2BlitManager } from './webgl2-gpu-objects'; const eventWebGLContextLost = 'webglcontextlost'; -function initStates (gl: WebGL2RenderingContext) { +function initStates (gl: WebGL2RenderingContext): void { gl.activeTexture(gl.TEXTURE0); gl.pixelStorei(gl.PACK_ALIGNMENT, 1); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); @@ -85,7 +85,7 @@ function getExtension (gl: WebGL2RenderingContext, ext: string): any { return null; } -export function getExtensions (gl: WebGL2RenderingContext) { +export function getExtensions (gl: WebGL2RenderingContext): IWebGL2Extensions { const res: IWebGL2Extensions = { EXT_texture_filter_anisotropic: getExtension(gl, 'EXT_texture_filter_anisotropic'), EXT_color_buffer_half_float: getExtension(gl, 'EXT_color_buffer_half_float'), @@ -156,11 +156,11 @@ export function getContext (canvas: HTMLCanvasElement): WebGL2RenderingContext | } export class WebGL2Swapchain extends Swapchain { - get extensions () { + get extensions (): IWebGL2Extensions { return this._extensions as IWebGL2Extensions; } - get blitManager () { + get blitManager (): IWebGL2BlitManager | null { return this._blitManager; } @@ -173,7 +173,7 @@ export class WebGL2Swapchain extends Swapchain { private _extensions: IWebGL2Extensions | null = null; private _blitManager: IWebGL2BlitManager | null = null; - public initialize (info: Readonly) { + public initialize (info: Readonly): void { this._canvas = info.windowHandle; this._webGL2ContextLostHandler = this._onWebGLContextLost.bind(this); @@ -279,7 +279,7 @@ export class WebGL2Swapchain extends Swapchain { this._canvas = null; } - public resize (width: number, height: number, surfaceTransform: SurfaceTransform) { + public resize (width: number, height: number, surfaceTransform: SurfaceTransform): void { if (this._colorTexture.width !== width || this._colorTexture.height !== height) { debug(`Resizing swapchain: ${width}x${height}`); this._canvas!.width = width; @@ -289,7 +289,7 @@ export class WebGL2Swapchain extends Swapchain { } } - private _onWebGLContextLost (event: Event) { + private _onWebGLContextLost (event: Event): void { warnID(11000); warn(event); // 2020.9.3: `preventDefault` is not available on some platforms diff --git a/cocos/gfx/webgl2/webgl2-texture.ts b/cocos/gfx/webgl2/webgl2-texture.ts index 71bae836b70..824e3c2af70 100644 --- a/cocos/gfx/webgl2/webgl2-texture.ts +++ b/cocos/gfx/webgl2/webgl2-texture.ts @@ -43,7 +43,7 @@ export class WebGL2Texture extends Texture { return this._gpuTextureView!; } - public initialize (info: Readonly | Readonly, isSwapchainTexture?: boolean) { + public initialize (info: Readonly | Readonly, isSwapchainTexture?: boolean): void { let texInfo = info as Readonly; const viewInfo = info as Readonly; @@ -127,7 +127,7 @@ export class WebGL2Texture extends Texture { } } - public destroy () { + public destroy (): void { if (!this._isTextureView && this._gpuTexture) { WebGL2CmdFuncDestroyTexture(WebGL2DeviceManager.instance, this._gpuTexture); WebGL2DeviceManager.instance.memoryStatus.textureSize -= this._size; @@ -150,7 +150,7 @@ export class WebGL2Texture extends Texture { return 0; } - public resize (width: number, height: number) { + public resize (width: number, height: number): void { if (this._info.width === width && this._info.height === height) { return; } @@ -184,7 +184,7 @@ export class WebGL2Texture extends Texture { /** * @engineInternal */ - public initAsSwapchainTexture (info: Readonly) { + public initAsSwapchainTexture (info: Readonly): void { const texInfo = new TextureInfo(); texInfo.format = info.format; texInfo.usage = FormatInfos[info.format].hasDepth ? TextureUsageBit.DEPTH_STENCIL_ATTACHMENT : TextureUsageBit.COLOR_ATTACHMENT; diff --git a/cocos/gi/light-probe/auto-placement.ts b/cocos/gi/light-probe/auto-placement.ts index c728c0d39e8..16ff013e518 100644 --- a/cocos/gi/light-probe/auto-placement.ts +++ b/cocos/gi/light-probe/auto-placement.ts @@ -39,7 +39,7 @@ export interface PlacementInfo { } export class AutoPlacement { - public static generate (info: PlacementInfo) { + public static generate (info: PlacementInfo): Vec3[] { switch (info.method) { case PlaceMethod.UNIFORM: return this.doGenerateUniform(info); @@ -50,7 +50,7 @@ export class AutoPlacement { } } - private static doGenerateUniform (info: PlacementInfo) { + private static doGenerateUniform (info: PlacementInfo): Vec3[] { if (info.nProbesX < 2 || info.nProbesY < 2 || info.nProbesZ < 2) { return []; } @@ -79,7 +79,7 @@ export class AutoPlacement { return probes; } - private static doGenerateAdaptive (info: PlacementInfo) { + private static doGenerateAdaptive (info: PlacementInfo): Vec3[] { // TODO return this.doGenerateUniform(info); } diff --git a/cocos/gi/light-probe/delaunay.ts b/cocos/gi/light-probe/delaunay.ts index e82235e195f..b5aeb976bd6 100644 --- a/cocos/gi/light-probe/delaunay.ts +++ b/cocos/gi/light-probe/delaunay.ts @@ -72,7 +72,7 @@ class Edge { } } - public set (tet: number, i: number, v0: number, v1: number) { + public set (tet: number, i: number, v0: number, v1: number): void { this.tetrahedron = tet; this.index = i; @@ -85,7 +85,7 @@ class Edge { } } - public isSame (other: Edge) { + public isSame (other: Edge): boolean { return (this.vertex0 === other.vertex0 && this.vertex1 === other.vertex1); } } @@ -143,7 +143,7 @@ class Triangle { } } - public set (tet: number, i: number, v0: number, v1: number, v2: number, v3: number) { + public set (tet: number, i: number, v0: number, v1: number, v2: number, v3: number): void { this.invalid = false; this.isOuterFace = true; @@ -181,7 +181,7 @@ class Triangle { } } - public isSame (other: Triangle) { + public isSame (other: Triangle): boolean { return (this.vertex0 === other.vertex0 && this.vertex1 === other.vertex1 && this.vertex2 === other.vertex2); } } @@ -193,7 +193,7 @@ export class CircumSphere { @serializable public radiusSquared = 0.0; - public init (p0: Vec3, p1: Vec3, p2: Vec3, p3: Vec3) { + public init (p0: Vec3, p1: Vec3, p2: Vec3, p3: Vec3): void { // calculate circumsphere of 4 points in R^3 space. _mat.set( p1.x - p0.x, p1.y - p0.y, p1.z - p0.z, @@ -258,20 +258,20 @@ export class Tetrahedron { } } - public isInCircumSphere (point: Vec3) { + public isInCircumSphere (point: Vec3): boolean { return Vec3.squaredDistance(point, this.sphere.center) < this.sphere.radiusSquared - EPSILON; } - public contain (vertexIndex: number) { + public contain (vertexIndex: number): boolean { return (this.vertex0 === vertexIndex || this.vertex1 === vertexIndex || this.vertex2 === vertexIndex || this.vertex3 === vertexIndex); } - public isInnerTetrahedron () { + public isInnerTetrahedron (): boolean { return this.vertex3 >= 0; } - public isOuterCell () { + public isOuterCell (): boolean { return this.vertex3 < 0; // -1 or -2 } } @@ -287,7 +287,7 @@ export class Delaunay { this._probes = probes; } - public build () { + public build (): Tetrahedron[] { this.reset(); this.tetrahedralize(); this.computeAdjacency(); @@ -296,7 +296,7 @@ export class Delaunay { return this._tetrahedrons; } - private reset () { + private reset (): void { this._tetrahedrons.length = 0; this._triangles.length = 0; this._edges.length = 0; @@ -305,7 +305,7 @@ export class Delaunay { /** * Bowyer-Watson algorithm */ - private tetrahedralize () { + private tetrahedralize (): void { // get probe count first const probeCount = this._probes.length; @@ -317,7 +317,7 @@ export class Delaunay { } // remove all tetrahedrons which contain the super tetrahedron's vertices - this._tetrahedrons = this._tetrahedrons.filter((tetrahedron) => { + this._tetrahedrons = this._tetrahedrons.filter((tetrahedron): boolean => { const vertexIndex = probeCount; const isSuperTetrahedron = ( tetrahedron.contain(vertexIndex) @@ -334,7 +334,7 @@ export class Delaunay { this.reorder(center); } - private initTetrahedron () { + private initTetrahedron (): Vec3 { const minPos = new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); const maxPos = new Vec3(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE); @@ -374,7 +374,7 @@ export class Delaunay { return center; } - private addTriangle (index: number, tet: number, i: number, v0: number, v1: number, v2: number, v3: number) { + private addTriangle (index: number, tet: number, i: number, v0: number, v1: number, v2: number, v3: number): void { if (index < this._triangles.length) { this._triangles[index].set(tet, i, v0, v1, v2, v3); } else { @@ -382,7 +382,7 @@ export class Delaunay { } } - private addEdge (index: number, tet: number, i: number, v0: number, v1: number) { + private addEdge (index: number, tet: number, i: number, v0: number, v1: number): void { if (index < this._edges.length) { this._edges[index].set(tet, i, v0, v1); } else { @@ -390,7 +390,7 @@ export class Delaunay { } } - private addProbe (vertexIndex: number) { + private addProbe (vertexIndex: number): void { const probe = this._probes[vertexIndex]; const position = probe.position; @@ -423,7 +423,7 @@ export class Delaunay { } // remove containing tetrahedron - this._tetrahedrons = this._tetrahedrons.filter((tetrahedron) => !tetrahedron.invalid); + this._tetrahedrons = this._tetrahedrons.filter((tetrahedron): boolean => !tetrahedron.invalid); for (let i = 0; i < triangleIndex; i++) { const triangle = this._triangles[i]; @@ -433,12 +433,12 @@ export class Delaunay { } } - private reorder (center: Vec3) { + private reorder (center: Vec3): void { // The tetrahedron in the middle is placed at the front of the vector - this._tetrahedrons.sort((a, b) => Vec3.squaredDistance(a.sphere.center, center) - Vec3.squaredDistance(b.sphere.center, center)); + this._tetrahedrons.sort((a, b): number => Vec3.squaredDistance(a.sphere.center, center) - Vec3.squaredDistance(b.sphere.center, center)); } - private computeAdjacency () { + private computeAdjacency (): void { const normal = new Vec3(0.0, 0.0, 0.0); const edge1 = new Vec3(0.0, 0.0, 0.0); const edge2 = new Vec3(0.0, 0.0, 0.0); @@ -534,7 +534,7 @@ export class Delaunay { } } - private computeMatrices () { + private computeMatrices (): void { for (let i = 0; i < this._tetrahedrons.length; i++) { const tetrahedron = this._tetrahedrons[i]; @@ -546,7 +546,7 @@ export class Delaunay { } } - private computeTetrahedronMatrix (tetrahedron: Tetrahedron) { + private computeTetrahedronMatrix (tetrahedron: Tetrahedron): void { const p0 = this._probes[tetrahedron.vertex0].position; const p1 = this._probes[tetrahedron.vertex1].position; const p2 = this._probes[tetrahedron.vertex2].position; @@ -561,7 +561,7 @@ export class Delaunay { tetrahedron.matrix.transpose(); } - private computeOuterCellMatrix (tetrahedron: Tetrahedron) { + private computeOuterCellMatrix (tetrahedron: Tetrahedron): void { const v: Vec3[] = []; const p: Vec3[] = []; diff --git a/cocos/gi/light-probe/light-probe-group.ts b/cocos/gi/light-probe/light-probe-group.ts index adc5adfd6f3..4da0e6bbad3 100644 --- a/cocos/gi/light-probe/light-probe-group.ts +++ b/cocos/gi/light-probe/light-probe-group.ts @@ -85,7 +85,7 @@ export class LightProbeGroup extends Component { @type(PlaceMethod) @tooltip('i18n:light_probe_group.method') @displayName('Generating Method') - get method () { + get method (): number { return this._method; } // Support this feature later. @@ -157,7 +157,7 @@ export class LightProbeGroup extends Component { this._nProbesZ = val; } - public onLoad () { + public onLoad (): void { if (!EDITOR) { return; } @@ -172,7 +172,7 @@ export class LightProbeGroup extends Component { } } - public onEnable () { + public onEnable (): void { if (!EDITOR) { return; } @@ -187,7 +187,7 @@ export class LightProbeGroup extends Component { } } - public onDisable () { + public onDisable (): void { if (!EDITOR) { return; } @@ -202,7 +202,7 @@ export class LightProbeGroup extends Component { } } - public generateLightProbes () { + public generateLightProbes (): void { if (!this.node) { return; } @@ -219,7 +219,7 @@ export class LightProbeGroup extends Component { this.onProbeChanged(); } - public onProbeChanged (updateTet = true, emitEvent = true) { + public onProbeChanged (updateTet = true, emitEvent = true): void { this.node.scene.globals.lightProbeInfo.syncData(this.node, this.probes); this.node.scene.globals.lightProbeInfo.update(updateTet); diff --git a/cocos/gi/light-probe/light-probe.ts b/cocos/gi/light-probe/light-probe.ts index 159f2d5bc3c..585f2408a7b 100644 --- a/cocos/gi/light-probe/light-probe.ts +++ b/cocos/gi/light-probe/light-probe.ts @@ -48,24 +48,24 @@ const _vp2 = new Vec3(0.0, 0.0, 0.0); @ccclass('cc.LightProbesData') export class LightProbesData { - public get probes () { + public get probes (): Vertex[] { return this._probes; } - public get tetrahedrons () { + public get tetrahedrons (): Tetrahedron[] { return this._tetrahedrons; } - public empty () { + public empty (): boolean { return this._probes.length === 0 || this._tetrahedrons.length === 0; } - public reset () { + public reset (): void { this._probes.length = 0; this._tetrahedrons.length = 0; } - public updateProbes (points: Vec3[]) { + public updateProbes (points: Vec3[]): void { this._probes.length = 0; const pointCount = points.length; @@ -74,12 +74,12 @@ export class LightProbesData { } } - public updateTetrahedrons () { + public updateTetrahedrons (): void { const delaunay = new Delaunay(this._probes); this._tetrahedrons = delaunay.build(); } - public getInterpolationSHCoefficients (tetIndex: number, weights: Vec4, coefficients: Vec3[]) { + public getInterpolationSHCoefficients (tetIndex: number, weights: Vec4, coefficients: Vec3[]): boolean { if (!this.hasCoefficients()) { return false; } @@ -112,7 +112,7 @@ export class LightProbesData { return true; } - public getInterpolationWeights (position: Vec3, tetIndex: number, weights: Vec4) { + public getInterpolationWeights (position: Vec3, tetIndex: number, weights: Vec4): number { const tetrahedronCount = this._tetrahedrons.length; if (tetIndex < 0 || tetIndex >= tetrahedronCount) { tetIndex = 0; @@ -150,11 +150,11 @@ export class LightProbesData { return tetIndex; } - public hasCoefficients () { + public hasCoefficients (): boolean { return !this.empty() && this._probes[0].coefficients.length !== 0; } - private static getTriangleBarycentricCoord (p0: Vec3, p1: Vec3, p2: Vec3, position: Vec3) { + private static getTriangleBarycentricCoord (p0: Vec3, p1: Vec3, p2: Vec3, position: Vec3): Vec3 { Vec3.subtract(_v1, p1, p0); Vec3.subtract(_v2, p2, p0); Vec3.cross(_normal, _v1, _v2); @@ -182,7 +182,7 @@ export class LightProbesData { return new Vec3(alpha, beta, 1.0 - alpha - beta); } - private getBarycentricCoord (position: Vec3, tetrahedron: Tetrahedron, weights: Vec4) { + private getBarycentricCoord (position: Vec3, tetrahedron: Tetrahedron, weights: Vec4): void { if (tetrahedron.vertex3 >= 0) { this.getTetrahedronBarycentricCoord(position, tetrahedron, weights); } else { @@ -190,7 +190,7 @@ export class LightProbesData { } } - private getTetrahedronBarycentricCoord (position: Vec3, tetrahedron: Tetrahedron, weights: Vec4) { + private getTetrahedronBarycentricCoord (position: Vec3, tetrahedron: Tetrahedron, weights: Vec4): void { const result = new Vec3(0.0, 0.0, 0.0); Vec3.subtract(result, position, this._probes[tetrahedron.vertex3].position); Vec3.transformMat3(result, result, tetrahedron.matrix); @@ -198,7 +198,7 @@ export class LightProbesData { weights.set(result.x, result.y, result.z, 1.0 - result.x - result.y - result.z); } - private getOuterCellBarycentricCoord (position: Vec3, tetrahedron: Tetrahedron, weights: Vec4) { + private getOuterCellBarycentricCoord (position: Vec3, tetrahedron: Tetrahedron, weights: Vec4): void { const p0 = this._probes[tetrahedron.vertex0].position; const p1 = this._probes[tetrahedron.vertex1].position; const p2 = this._probes[tetrahedron.vertex2].position; @@ -287,7 +287,7 @@ export class LightProbes { set reduceRinging (val: number) { this._reduceRinging = val; } - get reduceRinging () { + get reduceRinging (): number { return this._reduceRinging; } @@ -298,7 +298,7 @@ export class LightProbes { set showProbe (val: boolean) { this._showProbe = val; } - get showProbe () { + get showProbe (): boolean { return this._showProbe; } @@ -309,7 +309,7 @@ export class LightProbes { set showWireframe (val: boolean) { this._showWireframe = val; } - get showWireframe () { + get showWireframe (): boolean { return this._showWireframe; } @@ -320,7 +320,7 @@ export class LightProbes { set showConvex (val: boolean) { this._showConvex = val; } - get showConvex () { + get showConvex (): boolean { return this._showConvex; } @@ -356,7 +356,7 @@ export class LightProbes { protected _data: LightProbesData | null = null; protected _lightProbeSphereVolume = 1.0; - public initialize (info: LightProbeInfo) { + public initialize (info: LightProbeInfo): void { this._giScale = info.giScale; this._giSamples = info.giSamples; this._bounces = info.bounces; @@ -368,7 +368,7 @@ export class LightProbes { this._lightProbeSphereVolume = info.lightProbeSphereVolume; } - public empty () { + public empty (): boolean { if (!this._data) { return true; } diff --git a/cocos/gi/light-probe/polynomial-solver.ts b/cocos/gi/light-probe/polynomial-solver.ts index 0882de614c9..7b288613957 100644 --- a/cocos/gi/light-probe/polynomial-solver.ts +++ b/cocos/gi/light-probe/polynomial-solver.ts @@ -27,7 +27,7 @@ export class PolynomialSolver { * solve quadratic equation: b * t^2 + c * t + d = 0 * return the unique real positive root */ - public static getQuadraticUniqueRoot (b: number, c: number, d: number) { + public static getQuadraticUniqueRoot (b: number, c: number, d: number): number { // quadratic case if (b !== 0.0) { // the discriminant should be 0 @@ -47,7 +47,7 @@ export class PolynomialSolver { * solve cubic equation: t^3 + b * t^2 + c * t + d = 0 * return the unique real positive root */ - public static getCubicUniqueRoot (b: number, c: number, d: number) { + public static getCubicUniqueRoot (b: number, c: number, d: number): number { const roots: number[] = []; // let x = y - b / 3, convert equation to: y^3 + 3 * p * y + 2 * q = 0 diff --git a/cocos/gi/light-probe/sh.ts b/cocos/gi/light-probe/sh.ts index 28e90d9d1af..6ac5d872339 100644 --- a/cocos/gi/light-probe/sh.ts +++ b/cocos/gi/light-probe/sh.ts @@ -30,7 +30,7 @@ export class LightProbeSampler { /** * generate one sample from sphere uniformly */ - public static uniformSampleSphere (u1: number, u2: number) { + public static uniformSampleSphere (u1: number, u2: number): Vec3 { const z = 1.0 - 2.0 * u1; const r = Math.sqrt(Math.max(0.0, 1.0 - z * z)); const phi = 2.0 * Math.PI * u2; @@ -44,7 +44,7 @@ export class LightProbeSampler { /** * generate ucount1 * ucount2 samples from sphere uniformly */ - public static uniformSampleSphereAll (sampleCount: number) { + public static uniformSampleSphereAll (sampleCount: number): Vec3[] { assertIsTrue(sampleCount > 0); const uCount1 = Math.floor(Math.sqrt(sampleCount)); @@ -70,7 +70,7 @@ export class LightProbeSampler { /** * probability density function of uniform distribution on spherical surface */ - public static uniformSpherePdf () { return 1.0 / (4.0 * Math.PI); } + public static uniformSpherePdf (): number { return 1.0 / (4.0 * Math.PI); } } /** @@ -108,7 +108,7 @@ export class SH { /** * update ubo data by coefficients */ - public static updateUBOData (data: Float32Array, offset: number, coefficients: Vec3[]) { + public static updateUBOData (data: Float32Array, offset: number, coefficients: Vec3[]): void { // cc_sh_linear_const_r data[offset++] = coefficients[3].x * this.basisOverPI[3]; data[offset++] = coefficients[1].x * this.basisOverPI[1]; @@ -155,7 +155,7 @@ export class SH { /** * recreate a function from sh coefficients, which is same as SHEvaluate in shader */ - public static shaderEvaluate (normal: Vec3, coefficients: Vec3[]) { + public static shaderEvaluate (normal: Vec3, coefficients: Vec3[]): Vec3 { const linearConstR = new Vec4( coefficients[3].x * this.basisOverPI[3], coefficients[1].x * this.basisOverPI[1], @@ -227,7 +227,7 @@ export class SH { /** * recreate a function from sh coefficients */ - public static evaluate (sample: Vec3, coefficients: Vec3[]) { + public static evaluate (sample: Vec3, coefficients: Vec3[]): Vec3 { const result = new Vec3(0.0, 0.0, 0.0); const size = coefficients.length; @@ -242,7 +242,7 @@ export class SH { /** * project a function to sh coefficients */ - public static project (samples: Vec3[], values: Vec3[]) { + public static project (samples: Vec3[], values: Vec3[]): Vec3[] { assertIsTrue(samples.length > 0 && samples.length === values.length); // integral using Monte Carlo method @@ -269,7 +269,7 @@ export class SH { /** * calculate irradiance's sh coefficients from radiance's sh coefficients directly */ - public static convolveCosine (radianceCoefficients: Vec3[]) { + public static convolveCosine (radianceCoefficients: Vec3[]): Vec3[] { const cosTheta: number[] = [0.8862268925, 1.0233267546, 0.4954159260]; const irradianceCoefficients: Vec3[] = []; @@ -289,21 +289,21 @@ export class SH { /** * return basis function count */ - public static getBasisCount () { + public static getBasisCount (): number { return SH_BASIS_COUNT; } /** * evaluate from a basis function */ - public static evaluateBasis (index: number, sample: Vec3) { + public static evaluateBasis (index: number, sample: Vec3): number { assertIsTrue(index < this.getBasisCount()); const func = this.basisFunctions[index]; return func(sample); } - public static reduceRinging (coefficients: Vec3[], lambda: number) { + public static reduceRinging (coefficients: Vec3[], lambda: number): void { if (lambda === 0.0) { return; } @@ -317,11 +317,11 @@ export class SH { } } - private static lambda (l: number) { + private static lambda (l: number): number { return Math.sqrt((4.0 * Math.PI) / (2.0 * l + 1.0)); } - private static toIndex (l: number, m: number) { + private static toIndex (l: number, m: number): number { return l * l + l + m; } } diff --git a/cocos/input/input.ts b/cocos/input/input.ts index 2cd766d8b51..8729daaa838 100644 --- a/cocos/input/input.ts +++ b/cocos/input/input.ts @@ -160,28 +160,28 @@ export class Input { /** * This should be a private method, but it's exposed for Editor Only. */ - private _dispatchMouseDownEvent (nativeMouseEvent: any) { this._mouseInput.dispatchMouseDownEvent?.(nativeMouseEvent); } + private _dispatchMouseDownEvent (nativeMouseEvent: any): void { this._mouseInput.dispatchMouseDownEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ - private _dispatchMouseMoveEvent (nativeMouseEvent: any) { this._mouseInput.dispatchMouseMoveEvent?.(nativeMouseEvent); } + private _dispatchMouseMoveEvent (nativeMouseEvent: any): void { this._mouseInput.dispatchMouseMoveEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ - private _dispatchMouseUpEvent (nativeMouseEvent: any) { this._mouseInput.dispatchMouseUpEvent?.(nativeMouseEvent); } + private _dispatchMouseUpEvent (nativeMouseEvent: any): void { this._mouseInput.dispatchMouseUpEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ - private _dispatchMouseScrollEvent (nativeMouseEvent: any) { this._mouseInput.dispatchScrollEvent?.(nativeMouseEvent); } + private _dispatchMouseScrollEvent (nativeMouseEvent: any): void { this._mouseInput.dispatchScrollEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ - private _dispatchKeyboardDownEvent (nativeKeyboardEvent: any) { this._keyboardInput.dispatchKeyboardDownEvent?.(nativeKeyboardEvent); } + private _dispatchKeyboardDownEvent (nativeKeyboardEvent: any): void { this._keyboardInput.dispatchKeyboardDownEvent?.(nativeKeyboardEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ - private _dispatchKeyboardUpEvent (nativeKeyboardEvent: any) { this._keyboardInput.dispatchKeyboardUpEvent?.(nativeKeyboardEvent); } + private _dispatchKeyboardUpEvent (nativeKeyboardEvent: any): void { this._keyboardInput.dispatchKeyboardUpEvent?.(nativeKeyboardEvent); } /** * @en @@ -193,7 +193,7 @@ export class Input { * @param callback - The event listener's callback * @param target - The event listener's target and callee */ - public on (eventType: K, callback: InputEventMap[K], target?: any) { + public on (eventType: K, callback: InputEventMap[K], target?: any): InputEventMap[K] { this._eventTarget.on(eventType, callback, target); return callback; } @@ -208,7 +208,7 @@ export class Input { * @param callback - The event listener's callback * @param target - The event listener's target and callee */ - public once (eventType: K, callback: InputEventMap[K], target?: any) { + public once (eventType: K, callback: InputEventMap[K], target?: any): InputEventMap[K] { this._eventTarget.once(eventType, callback, target); return callback; } @@ -223,7 +223,7 @@ export class Input { * @param callback - The event listener's callback * @param target - The event listener's target and callee */ - public off (eventType: K, callback?: InputEventMap[K], target?: any) { + public off (eventType: K, callback?: InputEventMap[K], target?: any): void { if (EDITOR_NOT_IN_PREVIEW) { return; } @@ -236,7 +236,7 @@ export class Input { * @zh * 是否启用加速度计事件。 */ - public setAccelerometerEnabled (isEnable: boolean) { + public setAccelerometerEnabled (isEnable: boolean): void { if (EDITOR_NOT_IN_PREVIEW) { return; } @@ -261,7 +261,7 @@ export class Input { this._accelerometerInput.setInterval(intervalInMileSeconds); } - private _simulateEventTouch (eventMouse: EventMouse) { + private _simulateEventTouch (eventMouse: EventMouse): void { const eventType = pointerEventTypeMap[eventMouse.type]; const touchID = 0; const touch = touchManager.getTouch(touchID, eventMouse.getLocationX(), eventMouse.getLocationY()); @@ -281,12 +281,12 @@ export class Input { /** * @engineInternal */ - public _registerEventDispatcher (eventDispatcher: IEventDispatcher) { + public _registerEventDispatcher (eventDispatcher: IEventDispatcher): void { this._eventDispatcherList.push(eventDispatcher); - this._eventDispatcherList.sort((a, b) => b.priority - a.priority); + this._eventDispatcherList.sort((a, b): number => b.priority - a.priority); } - private _emitEvent (event: Event) { + private _emitEvent (event: Event): void { const length = this._eventDispatcherList.length; for (let i = 0; i < length; ++i) { const dispatcher = this._eventDispatcherList[i]; @@ -301,76 +301,76 @@ export class Input { } } - private _registerEvent () { + private _registerEvent (): void { if (sys.hasFeature(sys.Feature.INPUT_TOUCH)) { const eventTouchList = this._eventTouchList; - this._touchInput.on(InputEventType.TOUCH_START, (event) => { this._dispatchOrPushEventTouch(event, eventTouchList); }); - this._touchInput.on(InputEventType.TOUCH_MOVE, (event) => { this._dispatchOrPushEventTouch(event, eventTouchList); }); - this._touchInput.on(InputEventType.TOUCH_END, (event) => { this._dispatchOrPushEventTouch(event, eventTouchList); }); - this._touchInput.on(InputEventType.TOUCH_CANCEL, (event) => { this._dispatchOrPushEventTouch(event, eventTouchList); }); + this._touchInput.on(InputEventType.TOUCH_START, (event): void => { this._dispatchOrPushEventTouch(event, eventTouchList); }); + this._touchInput.on(InputEventType.TOUCH_MOVE, (event): void => { this._dispatchOrPushEventTouch(event, eventTouchList); }); + this._touchInput.on(InputEventType.TOUCH_END, (event): void => { this._dispatchOrPushEventTouch(event, eventTouchList); }); + this._touchInput.on(InputEventType.TOUCH_CANCEL, (event): void => { this._dispatchOrPushEventTouch(event, eventTouchList); }); } if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) { const eventMouseList = this._eventMouseList; - this._mouseInput.on(InputEventType.MOUSE_DOWN, (event) => { + this._mouseInput.on(InputEventType.MOUSE_DOWN, (event): void => { this._needSimulateTouchMoveEvent = true; this._simulateEventTouch(event); this._dispatchOrPushEvent(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_MOVE, (event) => { + this._mouseInput.on(InputEventType.MOUSE_MOVE, (event): void => { if (this._needSimulateTouchMoveEvent) { this._simulateEventTouch(event); } this._dispatchOrPushEvent(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_UP, (event) => { + this._mouseInput.on(InputEventType.MOUSE_UP, (event): void => { this._needSimulateTouchMoveEvent = false; this._simulateEventTouch(event); this._dispatchOrPushEvent(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_WHEEL, (event) => { this._dispatchOrPushEvent(event, eventMouseList); }); + this._mouseInput.on(InputEventType.MOUSE_WHEEL, (event): void => { this._dispatchOrPushEvent(event, eventMouseList); }); } if (sys.hasFeature(sys.Feature.EVENT_KEYBOARD)) { const eventKeyboardList = this._eventKeyboardList; - this._keyboardInput.on(InputEventType.KEY_DOWN, (event) => { this._dispatchOrPushEvent(event, eventKeyboardList); }); - this._keyboardInput.on(InputEventType.KEY_PRESSING, (event) => { this._dispatchOrPushEvent(event, eventKeyboardList); }); - this._keyboardInput.on(InputEventType.KEY_UP, (event) => { this._dispatchOrPushEvent(event, eventKeyboardList); }); + this._keyboardInput.on(InputEventType.KEY_DOWN, (event): void => { this._dispatchOrPushEvent(event, eventKeyboardList); }); + this._keyboardInput.on(InputEventType.KEY_PRESSING, (event): void => { this._dispatchOrPushEvent(event, eventKeyboardList); }); + this._keyboardInput.on(InputEventType.KEY_UP, (event): void => { this._dispatchOrPushEvent(event, eventKeyboardList); }); } if (sys.hasFeature(sys.Feature.EVENT_ACCELEROMETER)) { const eventAccelerationList = this._eventAccelerationList; - this._accelerometerInput.on(InputEventType.DEVICEMOTION, (event) => { this._dispatchOrPushEvent(event, eventAccelerationList); }); + this._accelerometerInput.on(InputEventType.DEVICEMOTION, (event): void => { this._dispatchOrPushEvent(event, eventAccelerationList); }); } if (sys.hasFeature(sys.Feature.EVENT_GAMEPAD)) { const eventGamepadList = this._eventGamepadList; - GamepadInputDevice._on(InputEventType.GAMEPAD_CHANGE, (event) => { this._dispatchOrPushEvent(event, eventGamepadList); }); - GamepadInputDevice._on(InputEventType.GAMEPAD_INPUT, (event) => { this._dispatchOrPushEvent(event, eventGamepadList); }); - GamepadInputDevice._on(InputEventType.HANDLE_POSE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventGamepadList); }); + GamepadInputDevice._on(InputEventType.GAMEPAD_CHANGE, (event): void => { this._dispatchOrPushEvent(event, eventGamepadList); }); + GamepadInputDevice._on(InputEventType.GAMEPAD_INPUT, (event): void => { this._dispatchOrPushEvent(event, eventGamepadList); }); + GamepadInputDevice._on(InputEventType.HANDLE_POSE_INPUT, (event): void => { this._dispatchOrPushEvent(event, eventGamepadList); }); } if (sys.hasFeature(sys.Feature.EVENT_HANDLE)) { const eventHandleList = this._eventHandleList; - this._handleInput._on(InputEventType.HANDLE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventHandleList); }); - this._handleInput._on(InputEventType.HANDLE_POSE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventHandleList); }); + this._handleInput._on(InputEventType.HANDLE_INPUT, (event): void => { this._dispatchOrPushEvent(event, eventHandleList); }); + this._handleInput._on(InputEventType.HANDLE_POSE_INPUT, (event): void => { this._dispatchOrPushEvent(event, eventHandleList); }); } if (sys.hasFeature(sys.Feature.EVENT_HMD)) { const eventHMDList = this._eventHMDList; - this._hmdInput._on(InputEventType.HMD_POSE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventHMDList); }); + this._hmdInput._on(InputEventType.HMD_POSE_INPUT, (event): void => { this._dispatchOrPushEvent(event, eventHMDList); }); } if (sys.hasFeature(sys.Feature.EVENT_HANDHELD)) { const eventHandheldList = this._eventHandheldList; - this._handheldInput._on(InputEventType.HANDHELD_POSE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventHandheldList); }); + this._handheldInput._on(InputEventType.HANDHELD_POSE_INPUT, (event): void => { this._dispatchOrPushEvent(event, eventHandheldList); }); } } /** * @engineInternal */ - public _clearEvents () { + public _clearEvents (): void { this._eventMouseList.length = 0; this._eventTouchList.length = 0; this._eventKeyboardList.length = 0; @@ -380,7 +380,7 @@ export class Input { this._eventHMDList.length = 0; } - private _dispatchOrPushEvent (event: Event, eventList: Event[]) { + private _dispatchOrPushEvent (event: Event, eventList: Event[]): void { if (this._dispatchImmediately) { this._emitEvent(event); } else { @@ -388,7 +388,7 @@ export class Input { } } - private _dispatchOrPushEventTouch (eventTouch: EventTouch, touchEventList: EventTouch[]) { + private _dispatchOrPushEventTouch (eventTouch: EventTouch, touchEventList: EventTouch[]): void { if (this._dispatchImmediately) { const touches = eventTouch.getTouches(); const touchesLength = touches.length; @@ -405,7 +405,7 @@ export class Input { /** * @engineInternal */ - public _frameDispatchEvents () { + public _frameDispatchEvents (): void { const eventHMDList = this._eventHMDList; // TODO: culling event queue for (let i = 0, length = eventHMDList.length; i < length; ++i) { diff --git a/cocos/input/system-event.ts b/cocos/input/system-event.ts index 15a8a482b9f..b4ecaa76026 100644 --- a/cocos/input/system-event.ts +++ b/cocos/input/system-event.ts @@ -74,21 +74,21 @@ export class SystemEvent extends EventTarget { constructor () { super(); - input.on(InputEventType.MOUSE_DOWN, (e) => { this.emit(SystemEventType.MOUSE_DOWN, e); }); - input.on(InputEventType.MOUSE_MOVE, (e) => { this.emit(SystemEventType.MOUSE_MOVE, e); }); - input.on(InputEventType.MOUSE_UP, (e) => { this.emit(SystemEventType.MOUSE_UP, e); }); - input.on(InputEventType.MOUSE_WHEEL, (e) => { this.emit(SystemEventType.MOUSE_WHEEL, e); }); + input.on(InputEventType.MOUSE_DOWN, (e): void => { this.emit(SystemEventType.MOUSE_DOWN, e); }); + input.on(InputEventType.MOUSE_MOVE, (e): void => { this.emit(SystemEventType.MOUSE_MOVE, e); }); + input.on(InputEventType.MOUSE_UP, (e): void => { this.emit(SystemEventType.MOUSE_UP, e); }); + input.on(InputEventType.MOUSE_WHEEL, (e): void => { this.emit(SystemEventType.MOUSE_WHEEL, e); }); - input.on(InputEventType.TOUCH_START, (e) => { this.emit(SystemEventType.TOUCH_START, e.touch, e); }); - input.on(InputEventType.TOUCH_MOVE, (e) => { this.emit(SystemEventType.TOUCH_MOVE, e.touch, e); }); - input.on(InputEventType.TOUCH_END, (e) => { this.emit(SystemEventType.TOUCH_END, e.touch, e); }); - input.on(InputEventType.TOUCH_CANCEL, (e) => { this.emit(SystemEventType.TOUCH_CANCEL, e.touch, e); }); + input.on(InputEventType.TOUCH_START, (e): void => { this.emit(SystemEventType.TOUCH_START, e.touch, e); }); + input.on(InputEventType.TOUCH_MOVE, (e): void => { this.emit(SystemEventType.TOUCH_MOVE, e.touch, e); }); + input.on(InputEventType.TOUCH_END, (e): void => { this.emit(SystemEventType.TOUCH_END, e.touch, e); }); + input.on(InputEventType.TOUCH_CANCEL, (e): void => { this.emit(SystemEventType.TOUCH_CANCEL, e.touch, e); }); - input.on(InputEventType.KEY_DOWN, (e) => { this.emit(SystemEventType.KEY_DOWN, e); }); - input.on(InputEventType.KEY_PRESSING, (e) => { this.emit(SystemEventType.KEY_DOWN, e); }); - input.on(InputEventType.KEY_UP, (e) => { this.emit(SystemEventType.KEY_UP, e); }); + input.on(InputEventType.KEY_DOWN, (e): void => { this.emit(SystemEventType.KEY_DOWN, e); }); + input.on(InputEventType.KEY_PRESSING, (e): void => { this.emit(SystemEventType.KEY_DOWN, e); }); + input.on(InputEventType.KEY_UP, (e): void => { this.emit(SystemEventType.KEY_UP, e); }); - input.on(InputEventType.DEVICEMOTION, (e) => { this.emit(SystemEventType.DEVICEMOTION, e); }); + input.on(InputEventType.DEVICEMOTION, (e): void => { this.emit(SystemEventType.DEVICEMOTION, e); }); } /** * @en @@ -97,7 +97,7 @@ export class SystemEvent extends EventTarget { * @zh * 是否启用加速度计事件。 */ - public setAccelerometerEnabled (isEnabled: boolean) { + public setAccelerometerEnabled (isEnabled: boolean): void { input.setAccelerometerEnabled(isEnabled); } @@ -108,7 +108,7 @@ export class SystemEvent extends EventTarget { * @zh * 设置加速度计间隔值。 */ - public setAccelerometerInterval (interval: number) { + public setAccelerometerInterval (interval: number): void { input.setAccelerometerInterval(interval); } @@ -123,7 +123,7 @@ export class SystemEvent extends EventTarget { * @param target - The event listener's target and callee * @param once - Register the event listener once */ - public on void>(type: string, callback: TFunction, target?: unknown, once?: boolean) { + public on void>(type: string, callback: TFunction, target?: unknown, once?: boolean): TFunction { super.on(type, callback, target, once); return callback; } @@ -139,7 +139,7 @@ export class SystemEvent extends EventTarget { * @param callback - The callback to remove. * @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed */ - public off (type: K, callback?: SystemEventMap[K], target?: any) { + public off (type: K, callback?: SystemEventMap[K], target?: any): void { super.off(type, callback, target); } } diff --git a/cocos/input/types/event/event-keyboard.ts b/cocos/input/types/event/event-keyboard.ts index 8003b8af63e..cb8d8964e36 100644 --- a/cocos/input/types/event/event-keyboard.ts +++ b/cocos/input/types/event/event-keyboard.ts @@ -59,7 +59,7 @@ export class EventKeyboard extends Event { * @en Indicates whether the current key is being pressed * @zh 表示当前按键是否正在被按下 */ - public get isPressed () { + public get isPressed (): boolean { return this._isPressed; } diff --git a/cocos/input/types/event/event-mouse.ts b/cocos/input/types/event/event-mouse.ts index 67b0657f086..bbeef3a1e4e 100644 --- a/cocos/input/types/event/event-mouse.ts +++ b/cocos/input/types/event/event-mouse.ts @@ -124,7 +124,7 @@ export class EventMouse extends Event { * * @deprecated since v3.3, please use EventMouse.prototype.type instead. */ - public get eventType () { + public get eventType (): string { return this._eventType; } @@ -162,7 +162,7 @@ export class EventMouse extends Event { * @param scrollX - The scroll value on x axis * @param scrollY - The scroll value on y axis */ - public setScrollData (scrollX: number, scrollY: number) { + public setScrollData (scrollX: number, scrollY: number): void { this._scrollX = scrollX; this._scrollY = scrollY; } @@ -171,7 +171,7 @@ export class EventMouse extends Event { * @en Returns the scroll value on x axis. * @zh 获取鼠标滚动的 X 轴距离,只有滚动时才有效。 */ - public getScrollX () { + public getScrollX (): number { return this._scrollX; } @@ -179,7 +179,7 @@ export class EventMouse extends Event { * @en Returns the scroll value on y axis. * @zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 */ - public getScrollY () { + public getScrollY (): number { return this._scrollY; } @@ -189,7 +189,7 @@ export class EventMouse extends Event { * @param x - The location on x axis * @param y - The location on y axis */ - public setLocation (x: number, y: number) { + public setLocation (x: number, y: number): void { this._x = x; this._y = y; } @@ -199,7 +199,7 @@ export class EventMouse extends Event { * @zh 获取鼠标相对于左下角位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getLocation (out?: Vec2) { + public getLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -213,7 +213,7 @@ export class EventMouse extends Event { * @zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getLocationInView (out?: Vec2) { + public getLocationInView (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -227,7 +227,7 @@ export class EventMouse extends Event { * @zh 获取当前事件在 UI 窗口内的坐标位置,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUILocation (out?: Vec2) { + public getUILocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -242,7 +242,7 @@ export class EventMouse extends Event { * @zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getPreviousLocation (out?: Vec2) { + public getPreviousLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -256,7 +256,7 @@ export class EventMouse extends Event { * @zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUIPreviousLocation (out?: Vec2) { + public getUIPreviousLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -271,7 +271,7 @@ export class EventMouse extends Event { * @zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getDelta (out?: Vec2) { + public getDelta (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -284,7 +284,7 @@ export class EventMouse extends Event { * @en Returns the X axis delta distance from the previous location to current location. * @zh 获取鼠标距离上一次事件移动的 X 轴距离。 */ - public getDeltaX () { + public getDeltaX (): number { return this._x - this._prevX; } @@ -292,7 +292,7 @@ export class EventMouse extends Event { * @en Returns the Y axis delta distance from the previous location to current location. * @zh 获取鼠标距离上一次事件移动的 Y 轴距离。 */ - public getDeltaY () { + public getDeltaY (): number { return this._y - this._prevY; } @@ -301,7 +301,7 @@ export class EventMouse extends Event { * @zh 获取鼠标距离上一次事件移动在 UI 坐标系下的距离对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUIDelta (out?: Vec2) { + public getUIDelta (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -314,7 +314,7 @@ export class EventMouse extends Event { * @en Returns the X axis delta distance from the previous location to current location in the UI coordinates. * @zh 获取鼠标距离上一次事件移动在 UI 坐标系下的 X 轴距离。 */ - public getUIDeltaX () { + public getUIDeltaX (): number { return (this._x - this._prevX) / cclegacy.view.getScaleX(); } @@ -322,7 +322,7 @@ export class EventMouse extends Event { * @en Returns the Y axis delta distance from the previous location to current location in the UI coordinates. * @zh 获取鼠标距离上一次事件移动在 UI 坐标系下的 Y 轴距离。 */ - public getUIDeltaY () { + public getUIDeltaY (): number { return (this._y - this._prevY) / cclegacy.view.getScaleY(); } @@ -331,7 +331,7 @@ export class EventMouse extends Event { * @zh 设置鼠标按键。 * @param button - The button code */ - public setButton (button: number) { + public setButton (button: number): void { this._button = button; } @@ -339,7 +339,7 @@ export class EventMouse extends Event { * @en Returns mouse button code. * @zh 获取鼠标按键。 */ - public getButton () { + public getButton (): number { return this._button; } @@ -347,7 +347,7 @@ export class EventMouse extends Event { * @en Returns location data on X axis. * @zh 获取鼠标当前 X 轴位置。 */ - public getLocationX () { + public getLocationX (): number { return this._x; } @@ -355,7 +355,7 @@ export class EventMouse extends Event { * @en Returns location data on Y axis. * @zh 获取鼠标当前 Y 轴位置。 */ - public getLocationY () { + public getLocationY (): number { return this._y; } @@ -363,7 +363,7 @@ export class EventMouse extends Event { * @en Returns location data on X axis. * @zh 获取鼠标当前 X 轴位置。 */ - public getUILocationX () { + public getUILocationX (): number { const viewport = cclegacy.view.getViewportRect(); return (this._x - viewport.x) / cclegacy.view.getScaleX(); } @@ -372,7 +372,7 @@ export class EventMouse extends Event { * @en Returns location data on Y axis. * @zh 获取鼠标当前 Y 轴位置。 */ - public getUILocationY () { + public getUILocationY (): number { const viewport = cclegacy.view.getViewportRect(); return (this._y - viewport.y) / cclegacy.view.getScaleY(); } diff --git a/cocos/input/types/event/event-touch.ts b/cocos/input/types/event/event-touch.ts index ae2bd45b543..a1a647534c9 100644 --- a/cocos/input/types/event/event-touch.ts +++ b/cocos/input/types/event/event-touch.ts @@ -98,7 +98,7 @@ export class EventTouch extends Event { * * @deprecated since v3.3, please use EventTouch.prototype.type instead. */ - public getEventCode () { + public getEventCode (): string { return this._eventCode; } @@ -108,7 +108,7 @@ export class EventTouch extends Event { * 注意:第一根手指按下不动,接着按第二根手指,这时候触点信息就只有变动的这根手指(第二根手指)的信息。 * 如果需要获取全部手指的信息,请使用 `getAllTouches`。 */ - public getTouches () { + public getTouches (): Touch[] { return this._touches; } @@ -117,7 +117,7 @@ export class EventTouch extends Event { * @zh 获取所有触摸点的列表。 * 注意:如果手指行为是 touch end,这个时候列表是没有该手指信息的。如需知道该手指信息,可通过 `getTouches` 获取识别。 */ - public getAllTouches () { + public getAllTouches (): Touch[] { return this._allTouches; } @@ -127,7 +127,7 @@ export class EventTouch extends Event { * @param x - The current touch location on the x axis * @param y - The current touch location on the y axis */ - public setLocation (x: number, y: number) { + public setLocation (x: number, y: number): void { if (this.touch) { this.touch.setTouchInfo(this.touch.getID(), x, y); } @@ -138,7 +138,7 @@ export class EventTouch extends Event { * @zh 获取触点位置。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getLocation (out?: Vec2) { + public getLocation (out?: Vec2): Vec2 { return this.touch ? this.touch.getLocation(out) : new Vec2(); } @@ -147,7 +147,7 @@ export class EventTouch extends Event { * @zh 获取 UI 坐标系下的触点位置。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUILocation (out?: Vec2) { + public getUILocation (out?: Vec2): Vec2 { return this.touch ? this.touch.getUILocation(out) : new Vec2(); } @@ -156,7 +156,7 @@ export class EventTouch extends Event { * @zh 获取当前触点在游戏窗口中的位置。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getLocationInView (out?: Vec2) { + public getLocationInView (out?: Vec2): Vec2 { return this.touch ? this.touch.getLocationInView(out) : new Vec2(); } @@ -165,7 +165,7 @@ export class EventTouch extends Event { * @zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getPreviousLocation (out?: Vec2) { + public getPreviousLocation (out?: Vec2): Vec2 { return this.touch ? this.touch.getPreviousLocation(out) : new Vec2(); } @@ -174,7 +174,7 @@ export class EventTouch extends Event { * @zh 获取触点落下时的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getStartLocation (out?: Vec2) { + public getStartLocation (out?: Vec2): Vec2 { return this.touch ? this.touch.getStartLocation(out) : new Vec2(); } @@ -183,7 +183,7 @@ export class EventTouch extends Event { * @zh 获取触点落下时的 UI 世界下位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUIStartLocation (out?: Vec2) { + public getUIStartLocation (out?: Vec2): Vec2 { return this.touch ? this.touch.getUIStartLocation(out) : new Vec2(); } @@ -191,7 +191,7 @@ export class EventTouch extends Event { * @en Returns the id of the current touch point. * @zh 获取触点的标识 ID,可以用来在多点触摸中跟踪触点。 */ - public getID () { + public getID (): number | null { return this.touch ? this.touch.getID() : null; } @@ -200,7 +200,7 @@ export class EventTouch extends Event { * @zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getDelta (out?: Vec2) { + public getDelta (out?: Vec2): Vec2 { return this.touch ? this.touch.getDelta(out) : new Vec2(); } @@ -209,7 +209,7 @@ export class EventTouch extends Event { * @zh 获取触点距离上一次事件 UI 世界下移动的距离对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUIDelta (out?: Vec2) { + public getUIDelta (out?: Vec2): Vec2 { return this.touch ? this.touch.getUIDelta(out) : new Vec2(); } @@ -217,7 +217,7 @@ export class EventTouch extends Event { * @en Returns the X axis delta distance from the previous location to current location. * @zh 获取触点距离上一次事件移动的 x 轴距离。 */ - public getDeltaX () { + public getDeltaX (): number { return this.touch ? this.touch.getDelta(_vec2).x : 0; } @@ -225,7 +225,7 @@ export class EventTouch extends Event { * @en Returns the Y axis delta distance from the previous location to current location. * @zh 获取触点距离上一次事件移动的 y 轴距离。 */ - public getDeltaY () { + public getDeltaY (): number { return this.touch ? this.touch.getDelta(_vec2).y : 0; } @@ -233,7 +233,7 @@ export class EventTouch extends Event { * @en Returns location X axis data. * @zh 获取当前触点 X 轴位置。 */ - public getLocationX () { + public getLocationX (): number { return this.touch ? this.touch.getLocationX() : 0; } @@ -241,7 +241,7 @@ export class EventTouch extends Event { * @en Returns location Y axis data. * @zh 获取当前触点 Y 轴位置。 */ - public getLocationY () { + public getLocationY (): number { return this.touch ? this.touch.getLocationY() : 0; } } diff --git a/cocos/input/types/event/event.ts b/cocos/input/types/event/event.ts index 6fc215ebda2..47f827af748 100644 --- a/cocos/input/types/event/event.ts +++ b/cocos/input/types/event/event.ts @@ -214,7 +214,7 @@ export class Event { * @zh * 重置事件对象以便在对象池中存储。 */ - public unuse () { + public unuse (): void { this.type = Event.NO_TYPE; this.target = null; this.currentTarget = null; @@ -231,7 +231,7 @@ export class Event { * @param type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit" * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not */ - public reuse (type: SystemEventTypeUnion, bubbles?: boolean) { + public reuse (type: SystemEventTypeUnion, bubbles?: boolean): void { this.type = type; this.bubbles = bubbles || false; } @@ -260,7 +260,7 @@ export class Event { * @zh * 检查该事件是否已经停止传递。 */ - public isStopped () { + public isStopped (): boolean { return this.propagationStopped || this.propagationImmediateStopped; } @@ -273,7 +273,7 @@ export class Event { * 获取当前目标节点 * @returns - The target with which the event associates. */ - public getCurrentTarget () { + public getCurrentTarget (): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this.currentTarget; } @@ -284,7 +284,7 @@ export class Event { * @zh * 获取事件类型。 */ - public getType () { + public getType (): string { return this.type; } } diff --git a/cocos/input/types/touch.ts b/cocos/input/types/touch.ts index e79daaaf351..1be58d480e2 100644 --- a/cocos/input/types/touch.ts +++ b/cocos/input/types/touch.ts @@ -38,7 +38,7 @@ export class Touch { private _startPoint: Vec2 = new Vec2(); private _startPointCaptured = false; - get lastModified () { + get lastModified (): number { return this._lastModified; } @@ -56,7 +56,7 @@ export class Touch { * @zh 获取当前触点位置。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getLocation (out?: Vec2) { + public getLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -69,7 +69,7 @@ export class Touch { * @en Returns X axis location value. * @zh 获取当前触点 X 轴位置。 */ - public getLocationX () { + public getLocationX (): number { return this._point.x; } @@ -77,7 +77,7 @@ export class Touch { * @en Returns Y axis location value. * @zh 获取当前触点 Y 轴位置。 */ - public getLocationY () { + public getLocationY (): number { return this._point.y; } @@ -86,7 +86,7 @@ export class Touch { * @zh 获取当前触点在 UI 坐标系中的位置。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUILocation (out?: Vec2) { + public getUILocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -100,7 +100,7 @@ export class Touch { * @en Returns X axis location value in UI coordinates. * @zh 获取当前触点在 UI 坐标系中 X 轴位置。 */ - public getUILocationX () { + public getUILocationX (): number { const viewport = cclegacy.view.getViewportRect(); return (this._point.x - viewport.x) / cclegacy.view.getScaleX(); } @@ -109,7 +109,7 @@ export class Touch { * @en Returns Y axis location value in UI coordinates. * @zh 获取当前触点在 UI 坐标系中 Y 轴位置。 */ - public getUILocationY () { + public getUILocationY (): number { const viewport = cclegacy.view.getViewportRect(); return (this._point.y - viewport.y) / cclegacy.view.getScaleY(); } @@ -119,7 +119,7 @@ export class Touch { * @zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getPreviousLocation (out?: Vec2) { + public getPreviousLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -133,7 +133,7 @@ export class Touch { * @zh 获取触点在上一次事件时在 UI 坐标系中的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUIPreviousLocation (out?: Vec2) { + public getUIPreviousLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -148,7 +148,7 @@ export class Touch { * @zh 获取触点落下时的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getStartLocation (out?: Vec2) { + public getStartLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -162,7 +162,7 @@ export class Touch { * @zh 获取触点落下时在 UI 坐标系中的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUIStartLocation (out?: Vec2) { + public getUIStartLocation (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -177,7 +177,7 @@ export class Touch { * @zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getDelta (out?: Vec2) { + public getDelta (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -192,7 +192,7 @@ export class Touch { * @zh 获取触点距离上一次事件移动在 UI 坐标系中的距离对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getUIDelta (out?: Vec2) { + public getUIDelta (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -209,7 +209,7 @@ export class Touch { * @zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getLocationInView (out?: Vec2) { + public getLocationInView (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -223,7 +223,7 @@ export class Touch { * @zh 获取触点在上一次事件时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getPreviousLocationInView (out?: Vec2) { + public getPreviousLocationInView (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -237,7 +237,7 @@ export class Touch { * @zh 获取触点落下时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 * @param out - Pass the out object to avoid object creation, very good practice */ - public getStartLocationInView (out?: Vec2) { + public getStartLocationInView (out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -250,7 +250,7 @@ export class Touch { * @en Returns the id of the touch point. * @zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 */ - public getID () { + public getID (): number { return this._id; } @@ -261,7 +261,7 @@ export class Touch { * @param x - x position of the touch point * @param y - y position of the touch point */ - public setTouchInfo (id = 0, x?: number, y?: number) { + public setTouchInfo (id = 0, x?: number, y?: number): void { this._prevPoint = this._point; this._point = new Vec2(x || 0, y || 0); this._id = id; @@ -287,7 +287,7 @@ export class Touch { */ public setPoint (x: number, y: number): void; - public setPoint (x: number | Vec2, y?: number) { + public setPoint (x: number | Vec2, y?: number): void { if (typeof x === 'object') { this._point.x = x.x; this._point.y = x.y; @@ -313,7 +313,7 @@ export class Touch { */ public setPrevPoint (x: number, y: number): void; - public setPrevPoint (x: number | Vec2, y?: number) { + public setPrevPoint (x: number | Vec2, y?: number): void { if (typeof x === 'object') { this._prevPoint = new Vec2(x.x, x.y); } else { diff --git a/cocos/misc/camera-component.ts b/cocos/misc/camera-component.ts index 9fb15a769ba..068f2b07979 100644 --- a/cocos/misc/camera-component.ts +++ b/cocos/misc/camera-component.ts @@ -40,6 +40,7 @@ import { RenderWindow } from '../render-scene/core/render-window'; import { ClearFlagBit } from '../gfx'; import { PostProcess } from '../rendering/post-process/components/post-process'; import { property } from '../core/data/class-decorator'; +import type { Ray } from '../core/geometry'; const _temp_vec3_1 = new Vec3(); @@ -186,7 +187,7 @@ export class Camera extends Component { * @en The render camera representation. * @zh 渲染场景中的相机对象。 */ - get camera () { + get camera (): scene.Camera { return this._camera!; } @@ -197,7 +198,7 @@ export class Camera extends Component { @displayOrder(0) @range([0, 65535, 1]) @tooltip('i18n:camera.priority') - get priority () { + get priority (): number { return this._priority; } @@ -215,7 +216,7 @@ export class Camera extends Component { @type(Layers.BitMask) @displayOrder(1) @tooltip('i18n:camera.visibility') - get visibility () { + get visibility (): number { return this._visibility; } @@ -233,7 +234,7 @@ export class Camera extends Component { @type(ClearFlag) @displayOrder(2) @tooltip('i18n:camera.clear_flags') - get clearFlags () { + get clearFlags (): ClearFlagBit { return this._clearFlags; } @@ -266,7 +267,7 @@ export class Camera extends Component { */ @displayOrder(4) @tooltip('i18n:camera.depth') - get clearDepth () { + get clearDepth (): number { return this._depth; } @@ -281,7 +282,7 @@ export class Camera extends Component { */ @displayOrder(5) @tooltip('i18n:camera.stencil') - get clearStencil () { + get clearStencil (): number { return this._stencil; } @@ -297,7 +298,7 @@ export class Camera extends Component { @type(ProjectionType) @displayOrder(6) @tooltip('i18n:camera.projection') - get projection () { + get projection (): CameraProjection { return this._projection; } @@ -312,11 +313,11 @@ export class Camera extends Component { */ @type(FOVAxis) @displayOrder(7) - @visible(function (this: Camera) { + @visible(function (this: Camera): boolean { return this._projection === ProjectionType.PERSPECTIVE; }) @tooltip('i18n:camera.fov_axis') - get fovAxis () { + get fovAxis (): CameraFOVAxis { return this._fovAxis; } @@ -334,12 +335,12 @@ export class Camera extends Component { * @zh 相机的视角大小。 */ @displayOrder(8) - @visible(function (this: Camera) { + @visible(function (this: Camera): boolean { return this._projection === ProjectionType.PERSPECTIVE; }) @range([1, 180, 1]) @tooltip('i18n:camera.fov') - get fov () { + get fov (): number { return this._fov; } @@ -353,12 +354,12 @@ export class Camera extends Component { * @zh 正交模式下的相机视角高度。 */ @displayOrder(9) - @visible(function (this: Camera) { + @visible(function (this: Camera): boolean { return this._projection === ProjectionType.ORTHO; }) @rangeMin(1) @tooltip('i18n:camera.ortho_height') - get orthoHeight () { + get orthoHeight (): number { return this._orthoHeight; } @@ -374,7 +375,7 @@ export class Camera extends Component { @displayOrder(10) @rangeMin(0) @tooltip('i18n:camera.near') - get near () { + get near (): number { return this._near; } @@ -390,7 +391,7 @@ export class Camera extends Component { @displayOrder(11) @rangeMin(0) @tooltip('i18n:camera.far') - get far () { + get far (): number { return this._far; } @@ -406,7 +407,7 @@ export class Camera extends Component { @type(Aperture) @displayOrder(12) @tooltip('i18n:camera.aperture') - get aperture () { + get aperture (): CameraAperture { return this._aperture; } @@ -422,7 +423,7 @@ export class Camera extends Component { @type(Shutter) @displayOrder(13) @tooltip('i18n:camera.shutter') - get shutter () { + get shutter (): CameraShutter { return this._shutter; } @@ -438,7 +439,7 @@ export class Camera extends Component { @type(ISO) @displayOrder(14) @tooltip('i18n:camera.ISO') - get iso () { + get iso (): CameraISO { return this._iso; } @@ -453,7 +454,7 @@ export class Camera extends Component { */ @displayOrder(15) @tooltip('i18n:camera.rect') - get rect () { + get rect (): Rect { return this._rect; } @@ -469,7 +470,7 @@ export class Camera extends Component { @type(RenderTexture) @displayOrder(16) @tooltip('i18n:camera.target_texture') - get targetTexture () { + get targetTexture (): RenderTexture | null { return this._targetTexture; } @@ -491,7 +492,7 @@ export class Camera extends Component { } @property - get usePostProcess () { + get usePostProcess (): boolean { return this._usePostProcess; } set usePostProcess (v) { @@ -502,7 +503,7 @@ export class Camera extends Component { } @type(PostProcess) - get postProcess () { + get postProcess (): PostProcess | null { return this._postProcess; } set postProcess (v) { @@ -517,7 +518,7 @@ export class Camera extends Component { * set to 1 to keep the same with the canvas size. * @zh 相机内部缓冲尺寸的缩放值, 1 为与 canvas 尺寸相同。 */ - get screenScale () { + get screenScale (): number { return this._screenScale; } @@ -529,7 +530,7 @@ export class Camera extends Component { /** * @internal */ - get inEditorMode () { + get inEditorMode (): boolean { return this._inEditorMode; } @@ -544,7 +545,7 @@ export class Camera extends Component { /** * @internal */ - get cameraType () { + get cameraType (): CameraType { return this._cameraType; } @@ -561,7 +562,7 @@ export class Camera extends Component { /** * @internal */ - get trackingType () { + get trackingType (): TrackingType { return this._trackingType; } @@ -575,24 +576,24 @@ export class Camera extends Component { } } - public onLoad () { + public onLoad (): void { this._createCamera(); } - public onEnable () { + public onEnable (): void { this.node.hasChangedFlags |= TransformBit.POSITION; // trigger camera matrix update if (this._camera) { this._attachToScene(); } } - public onDisable () { + public onDisable (): void { if (this._camera) { this._detachFromScene(); } } - public onDestroy () { + public onDestroy (): void { if (this._camera) { this._camera.destroy(); this._camera = null; @@ -611,7 +612,7 @@ export class Camera extends Component { * @param out The output ray object. * @returns Return the output ray object. */ - public screenPointToRay (x: number, y: number, out?: geometry.Ray) { + public screenPointToRay (x: number, y: number, out?: geometry.Ray): Ray { if (!out) { out = geometry.Ray.create(); } if (this._camera) { this._camera.screenPointToRay(out, x, y); } return out; @@ -624,7 +625,7 @@ export class Camera extends Component { * @param out The output position in screen space coordinates. * @returns Return the output position object. */ - public worldToScreen (worldPos: Vec3 | Readonly, out?: Vec3) { + public worldToScreen (worldPos: Vec3 | Readonly, out?: Vec3): Vec3 { if (!out) { out = new Vec3(); } if (this._camera) { this._camera.worldToScreen(out, worldPos); } return out; @@ -637,7 +638,7 @@ export class Camera extends Component { * @param out The output position in world space coordinates * @returns Return the output position object. */ - public screenToWorld (screenPos: Vec3, out?: Vec3) { + public screenToWorld (screenPos: Vec3, out?: Vec3): Vec3 { if (!out) { out = this.node.getWorldPosition(); } if (this._camera) { this._camera.screenToWorld(out, screenPos); } return out; @@ -657,7 +658,7 @@ export class Camera extends Component { * uiNode.position = out; * ``` */ - public convertToUINode (wpos: Vec3 | Readonly, uiNode: Node, out?: Vec3) { + public convertToUINode (wpos: Vec3 | Readonly, uiNode: Node, out?: Vec3): Vec3 { if (!out) { out = new Vec3(); } @@ -681,7 +682,7 @@ export class Camera extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _createCamera () { + public _createCamera (): void { if (!this._camera) { this._camera = (cclegacy.director.root).createCamera(); this._camera!.initialize({ @@ -716,7 +717,7 @@ export class Camera extends Component { this._updateTargetTexture(); } - protected _attachToScene () { + protected _attachToScene (): void { if (!this.node.scene || !this._camera) { return; } @@ -727,13 +728,13 @@ export class Camera extends Component { rs.addCamera(this._camera); } - protected _detachFromScene () { + protected _detachFromScene (): void { if (this._camera && this._camera.scene) { this._camera.scene.removeCamera(this._camera); } } - protected _checkTargetTextureEvent (old: RenderTexture | null) { + protected _checkTargetTextureEvent (old: RenderTexture | null): void { if (old) { old.off('resize'); } @@ -747,7 +748,7 @@ export class Camera extends Component { } } - protected _updateTargetTexture () { + protected _updateTargetTexture (): void { if (!this._camera) { return; } diff --git a/cocos/misc/intersect.ts b/cocos/misc/intersect.ts index c5c72da77c7..6de8f869260 100644 --- a/cocos/misc/intersect.ts +++ b/cocos/misc/intersect.ts @@ -35,7 +35,7 @@ import { scene } from '../render-scene'; // FIXME(minggo): rayAABB2 is also implemented in core/geometry/intersects.ts, but it is not exported. // And i don't think should export this function, so copy the implementation here. -function rayAABB2 (ray: geometry.Ray, min: IVec3Like, max: IVec3Like) { +function rayAABB2 (ray: geometry.Ray, min: IVec3Like, max: IVec3Like): number { const o = ray.o; const d = ray.d; const ix = 1 / d.x; const iy = 1 / d.y; const iz = 1 / d.z; const t1 = (min.x - o.x) * ix; @@ -60,12 +60,12 @@ function rayAABB2 (ray: geometry.Ray, min: IVec3Like, max: IVec3Like) { * @param options @zh 额外选项 @en Optional params * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ -const raySubMesh = (function () { +const raySubMesh = (function (): (ray: geometry.Ray, submesh: RenderingSubMesh, options?: geometry.IRaySubMeshOptions) => number { const tri = geometry.Triangle.create(); const deOpt: geometry.IRaySubMeshOptions = { distance: Infinity, doubleSided: false, mode: geometry.ERaycastMode.ANY }; let minDis = 0; - const fillResult = (m: geometry.ERaycastMode, d: number, i0: number, i1: number, i2: number, r?: geometry.IRaySubMeshResult[]) => { + const fillResult = (m: geometry.ERaycastMode, d: number, i0: number, i1: number, i2: number, r?: geometry.IRaySubMeshResult[]): void => { if (m === geometry.ERaycastMode.CLOSEST) { if (minDis > d || minDis === 0) { minDis = d; @@ -83,7 +83,7 @@ const raySubMesh = (function () { } }; - const narrowphase = (vb: Float32Array, ib: IBArray, pm: PrimitiveMode, ray: geometry.Ray, opt: geometry.IRaySubMeshOptions) => { + const narrowphase = (vb: Float32Array, ib: IBArray, pm: PrimitiveMode, ray: geometry.Ray, opt: geometry.IRaySubMeshOptions): number => { if (pm === PrimitiveMode.TRIANGLE_LIST) { const cnt = ib.length; for (let j = 0; j < cnt; j += 3) { @@ -131,7 +131,7 @@ const raySubMesh = (function () { } return minDis; }; - return function (ray: geometry.Ray, submesh: RenderingSubMesh, options?: geometry.IRaySubMeshOptions) { + return function (ray: geometry.Ray, submesh: RenderingSubMesh, options?: geometry.IRaySubMeshOptions): number { minDis = 0; if (submesh.geometricInfo.positions.length === 0) return minDis; const opt = options === undefined ? deOpt : options; @@ -156,10 +156,10 @@ const raySubMesh = (function () { * @param options @zh 可选参数 @en Optional param * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ -const rayMesh = (function () { +const rayMesh = (function (): (ray: geometry.Ray, mesh: Mesh, options?: geometry.IRayMeshOptions) => number { let minDis = 0; const deOpt: geometry.IRayMeshOptions = { distance: Infinity, doubleSided: false, mode: geometry.ERaycastMode.ANY }; - return function (ray: geometry.Ray, mesh: Mesh, options?: geometry.IRayMeshOptions) { + return function (ray: geometry.Ray, mesh: Mesh, options?: geometry.IRayMeshOptions): number { minDis = 0; const opt = options === undefined ? deOpt : options; const length = mesh.renderingSubMeshes.length; @@ -205,12 +205,12 @@ const rayMesh = (function () { * @param options @zh 可选参数 @en Optional param * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ -const rayModel = (function () { +const rayModel = (function (): (r: geometry.Ray, model: scene.Model, options?: geometry.IRayModelOptions) => number { let minDis = 0; const deOpt: geometry.IRayModelOptions = { distance: Infinity, doubleSided: false, mode: geometry.ERaycastMode.ANY }; const modelRay = new geometry.Ray(); const m4 = new Mat4(); - return function (r: geometry.Ray, model: scene.Model, options?: geometry.IRayModelOptions) { + return function (r: geometry.Ray, model: scene.Model, options?: geometry.IRayModelOptions): number { minDis = 0; const opt = options === undefined ? deOpt : options; const wb = model.worldBounds; diff --git a/cocos/misc/missing-script.ts b/cocos/misc/missing-script.ts index 7f83263f208..3b36c747e49 100644 --- a/cocos/misc/missing-script.ts +++ b/cocos/misc/missing-script.ts @@ -50,7 +50,7 @@ export class MissingScript extends Component { * @param {string} id * @return {function} constructor */ - public static safeFindClass (id: string) { + public static safeFindClass (id: string): Constructor | undefined { const cls = js.getClassById(id); if (cls) { return cls; @@ -72,7 +72,7 @@ export class MissingScript extends Component { super(); } - public onLoad () { + public onLoad (): void { warnID(4600, this.node.name); } } diff --git a/cocos/misc/model-renderer.ts b/cocos/misc/model-renderer.ts index c5f7201be57..92fcbc81644 100644 --- a/cocos/misc/model-renderer.ts +++ b/cocos/misc/model-renderer.ts @@ -58,7 +58,7 @@ export class ModelRenderer extends Renderer { * @en The visibility which will be applied to the committed models. * @zh 应用于所有提交渲染的 Model 的可见性 */ - get visibility () { + get visibility (): number { return this._visFlags; } @@ -71,7 +71,7 @@ export class ModelRenderer extends Renderer { * @en The priority which will be applied to the committed models.(Valid only in transparent queues) * @zh 应用于所有提交渲染的 Model 的排序优先级(只在半透明渲染队列中起效) */ - get priority () { + get priority (): number { return this._priority; } @@ -95,23 +95,23 @@ export class ModelRenderer extends Renderer { return this._models; } - protected onEnable () { + protected onEnable (): void { this._updatePriority(); } - protected _attachToScene () { + protected _attachToScene (): void { } /** * @engineInternal */ - public _detachFromScene () { + public _detachFromScene (): void { } - protected _onVisibilityChange (val) { + protected _onVisibilityChange (val): void { } - protected _updatePriority () { + protected _updatePriority (): void { if (this._models.length > 0) { for (let i = 0; i < this._models.length; i++) { this._models[i].priority = this._priority; diff --git a/cocos/misc/renderer.ts b/cocos/misc/renderer.ts index 94600d2434e..8f5c9dc8e58 100644 --- a/cocos/misc/renderer.ts +++ b/cocos/misc/renderer.ts @@ -59,7 +59,7 @@ export class Renderer extends Component { * @en Get the default shared material * @zh 获取默认的共享材质 */ - get sharedMaterial () { + get sharedMaterial (): Material |null { return this.getSharedMaterial(0); } @@ -70,7 +70,7 @@ export class Renderer extends Component { @type(Material) @displayOrder(0) @displayName('Materials') - get sharedMaterials () { + get sharedMaterials (): (Material | null)[] { // if we don't create an array copy, the editor will modify the original array directly. return (EDITOR && this._materials.slice()) || this._materials; } @@ -161,7 +161,7 @@ export class Renderer extends Component { * new material instance will be created automatically if the sub-model is already using one. * @zh 设置指定子模型的 sharedMaterial,如果对应位置有材质实例则会创建一个对应的材质实例。 */ - public setMaterial (material: Material | null, index: number) { + public setMaterial (material: Material | null, index: number): void { if (material && material instanceof MaterialInstance) { console.error('Can\'t set a material instance to a sharedMaterial slot'); } @@ -201,7 +201,7 @@ export class Renderer extends Component { * @en Set the material instance of the specified sub-model. * @zh 获取指定子模型的材质实例。 */ - public setMaterialInstance (matInst: Material | MaterialInstance | null, index: number) { + public setMaterialInstance (matInst: Material | MaterialInstance | null, index: number): void { if (typeof matInst === 'number') { warnID(12007); const temp: any = matInst; @@ -236,15 +236,15 @@ export class Renderer extends Component { return this._materialInstances[index] || this._materials[index]; } - protected _onMaterialModified (index: number, material: Material | null) { + protected _onMaterialModified (index: number, material: Material | null): void { } /** * @engineInternal */ - public _onRebuildPSO (index: number, material: Material | null) { + public _onRebuildPSO (index: number, material: Material | null): void { } - protected _clearMaterials () { + protected _clearMaterials (): void { } } diff --git a/cocos/native-binding/decorators.ts b/cocos/native-binding/decorators.ts index 1c62d158a57..6630254fddd 100644 --- a/cocos/native-binding/decorators.ts +++ b/cocos/native-binding/decorators.ts @@ -1021,7 +1021,7 @@ export function patch_cc_SkyboxInfo(ctx: cc_SkyboxInfo_Context_Args, apply = def apply(() => { $.type(TextureCube)(SkyboxInfo.prototype, 'diffuseMap', diffuseMapDescriptor); }, 'type', 'diffuseMap'); apply(() => { $$.readOnly(SkyboxInfo.prototype, 'diffuseMap', diffuseMapDescriptor); }, 'readOnly', 'diffuseMap'); apply(() => { $.editable(SkyboxInfo.prototype, 'diffuseMap', diffuseMapDescriptor); }, 'editable', 'diffuseMap'); - apply(() => { $.visible(function (this: SkyboxInfo) { + apply(() => { $.visible(function (this: SkyboxInfo): boolean { if (this.useIBL && this.applyDiffuseMap) { return true; } diff --git a/cocos/particle-2d/motion-streak-2d-assembler.ts b/cocos/particle-2d/motion-streak-2d-assembler.ts index 6867787b48b..160eaaaec11 100644 --- a/cocos/particle-2d/motion-streak-2d-assembler.ts +++ b/cocos/particle-2d/motion-streak-2d-assembler.ts @@ -36,14 +36,14 @@ const _normal = new Vec2(); const _vec2 = new Vec2(); let QUAD_INDICES; -function normal (out:Vec2, dir:Vec2) { +function normal (out:Vec2, dir:Vec2): Vec2 { // get perpendicular out.x = -dir.y; out.y = dir.x; return out; } -function computeMiter (miter, lineA, lineB, halfThick, maxMultiple) { +function computeMiter (miter, lineA, lineB, halfThick, maxMultiple): number { // get tangent line lineA.add(lineB, _tangent); _tangent.normalize(); @@ -63,14 +63,14 @@ function computeMiter (miter, lineA, lineB, halfThick, maxMultiple) { } export const MotionStreakAssembler: IAssembler = { - createData (comp: MotionStreak) { + createData (comp: MotionStreak): RenderData { const renderData = comp.requestRenderData(); renderData.dataLength = 4; renderData.resize(16, (16 - 2) * 3); return renderData; }, - update (comp: MotionStreak, dt: number) { + update (comp: MotionStreak, dt: number): void { const stroke = comp.stroke / 2; const node = comp.node; @@ -189,7 +189,7 @@ export const MotionStreakAssembler: IAssembler = { } }, - updateWorldVertexAllData (comp: MotionStreak) { + updateWorldVertexAllData (comp: MotionStreak): void { const renderData = comp.renderData!; const stride = renderData.floatStride; const dataList = renderData.data; @@ -205,7 +205,7 @@ export const MotionStreakAssembler: IAssembler = { } }, - createQuadIndices (comp, indexCount) { + createQuadIndices (comp, indexCount): void { const renderData = comp.renderData!; const chunk = renderData.chunk; const vid = 0; @@ -224,7 +224,7 @@ export const MotionStreakAssembler: IAssembler = { } }, - updateRenderDataCache (comp: MotionStreak, renderData: RenderData) { + updateRenderDataCache (comp: MotionStreak, renderData: RenderData): void { if (renderData.passDirty) { renderData.updatePass(comp); } @@ -240,7 +240,7 @@ export const MotionStreakAssembler: IAssembler = { } }, - updateRenderData (comp: MotionStreak) { + updateRenderData (comp: MotionStreak): void { if (JSB) { // A dirty hack // The world matrix was updated in advance and needs to be avoided at the cpp level @@ -250,10 +250,10 @@ export const MotionStreakAssembler: IAssembler = { } }, - updateColor (comp: MotionStreak) { + updateColor (comp: MotionStreak): void { }, - fillBuffers (comp: MotionStreak, renderer: IBatcher) { + fillBuffers (comp: MotionStreak, renderer: IBatcher): void { const renderData = comp.renderData!; const chunk = renderData.chunk; const dataList = renderData.data; @@ -296,7 +296,7 @@ export const MotionStreakAssembler: IAssembler = { }; export const MotionStreakAssemblerManager: IAssemblerManager = { - getAssembler (comp: MotionStreak) { + getAssembler (comp: MotionStreak): IAssembler { return MotionStreakAssembler; }, }; diff --git a/cocos/particle-2d/motion-streak-2d.ts b/cocos/particle-2d/motion-streak-2d.ts index 52be61d282d..e63ba96557d 100644 --- a/cocos/particle-2d/motion-streak-2d.ts +++ b/cocos/particle-2d/motion-streak-2d.ts @@ -41,12 +41,12 @@ class Point { if (dir) this.dir.set(dir); } - public setPoint (x, y) { + public setPoint (x, y): void { this.point.x = x; this.point.y = y; } - public setDir (x, y) { + public setDir (x, y): void { this.dir.x = x; this.dir.y = y; } @@ -76,7 +76,7 @@ export class MotionStreak extends UIRenderer { * @zh 在编辑器模式下预览拖尾效果。 */ @editable - public get preview () { + public get preview (): boolean { return this._preview; } @@ -91,7 +91,7 @@ export class MotionStreak extends UIRenderer { * motionStreak.fadeTime = 3; */ @editable - public get fadeTime () { + public get fadeTime (): number { return this._fadeTime; } @@ -106,7 +106,7 @@ export class MotionStreak extends UIRenderer { * motionStreak.minSeg = 3; */ @editable - public get minSeg () { + public get minSeg (): number { return this._minSeg; } public set minSeg (val) { @@ -119,7 +119,7 @@ export class MotionStreak extends UIRenderer { * motionStreak.stroke = 64; */ @editable - public get stroke () { + public get stroke (): number { return this._stroke; } public set stroke (val) { @@ -133,7 +133,7 @@ export class MotionStreak extends UIRenderer { * motionStreak.texture = newTexture; */ @type(Texture2D) - public get texture () { + public get texture (): Texture2D | null { return this._texture; } @@ -149,14 +149,14 @@ export class MotionStreak extends UIRenderer { * motionStreak.fastMode = true; */ @editable - public get fastMode () { + public get fastMode (): boolean { return this._fastMode; } public set fastMode (val: boolean) { this._fastMode = val; } - public get points () { + public get points (): Point[] { return this._points; } @@ -174,12 +174,12 @@ export class MotionStreak extends UIRenderer { private _fastMode = false; private _points: Point[] = []; - public onEnable () { + public onEnable (): void { super.onEnable(); this.reset(); } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = MotionStreak.Assembler.getAssembler(this); if (this._assembler !== assembler) { @@ -195,13 +195,13 @@ export class MotionStreak extends UIRenderer { } } - public onFocusInEditor () { + public onFocusInEditor (): void { if (this._preview) { this.reset(); } } - public onLostFocusInEditor () { + public onLostFocusInEditor (): void { if (this._preview) { this.reset(); } @@ -214,12 +214,12 @@ export class MotionStreak extends UIRenderer { * // Remove all living segments of the ribbon. * myMotionStreak.reset(); */ - public reset () { + public reset (): void { this._points.length = 0; if (this._renderData) this._renderData.clear(); } - public lateUpdate (dt) { + public lateUpdate (dt): void { if (EDITOR_NOT_IN_PREVIEW && !this._preview) return; if (this._assembler) this._assembler.update(this, dt); } @@ -227,7 +227,7 @@ export class MotionStreak extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _render (render: IBatcher) { + public _render (render: IBatcher): void { render.commitComp(this, this._renderData, this._texture, this._assembler, null); } } diff --git a/cocos/particle-2d/particle-simulator-2d.ts b/cocos/particle-2d/particle-simulator-2d.ts index 73d92f70f0c..2902322ea8a 100644 --- a/cocos/particle-2d/particle-simulator-2d.ts +++ b/cocos/particle-2d/particle-simulator-2d.ts @@ -37,7 +37,7 @@ const _tpc = new Vec2(); const formatBytes = getComponentPerVertex(vfmtPosUvColor); // In the Free mode to get emit real rotation in the world coordinate. -function getWorldRotation (node) { +function getWorldRotation (node): number { let rotation = 0; let tempNode = node; while (tempNode) { @@ -76,7 +76,7 @@ class ParticlePool extends js.Pool { } } -const pool = new ParticlePool((par: Particle) => { +const pool = new ParticlePool((par: Particle): void => { par.pos.set(ZERO_VEC2); par.startPos.set(ZERO_VEC2); par.color._val = 0xFF000000; @@ -124,14 +124,14 @@ export class Simulator { this._worldRotation = 0; } - public stop () { + public stop (): void { this.active = false; this.readyToPlay = false; this.elapsed = this.sys.duration; this.emitCounter = 0; } - public reset () { + public reset (): void { this.active = true; this.readyToPlay = true; this.elapsed = 0; @@ -142,7 +142,7 @@ export class Simulator { particles.length = 0; } - public emitParticle (pos) { + public emitParticle (pos): void { const psys = this.sys; const particle = pool.get(); this.particles.push(particle); @@ -230,7 +230,7 @@ export class Simulator { } } - public updateUVs (force?: boolean) { + public updateUVs (force?: boolean): void { const renderData = this.renderData; if (renderData && this.sys._renderSpriteFrame) { const vbuf = renderData.vData; @@ -253,7 +253,7 @@ export class Simulator { } } - public updateParticleBuffer (particle, pos, buffer, offset: number) { + public updateParticleBuffer (particle, pos, buffer, offset: number): void { const vbuf = buffer.vData; // const uintbuf = buffer._uintVData; @@ -319,7 +319,7 @@ export class Simulator { Color.toArray(vbuf, particle.color, offset + 32); } - public step (dt) { + public step (dt): void { const assembler = this.sys.assembler!; const psys = this.sys; const node = psys.node; @@ -468,7 +468,7 @@ export class Simulator { } } - requestData (vertexCount: number, indexCount: number) { + requestData (vertexCount: number, indexCount: number): void { let offset = this.renderData.indexCount; this.renderData.request(vertexCount, indexCount); const count = this.renderData.indexCount / 6; @@ -484,7 +484,7 @@ export class Simulator { } } - public initDrawInfo () { + public initDrawInfo (): void { const renderData = this.renderData; renderData.setRenderDrawInfoAttributes(); } diff --git a/cocos/particle-2d/particle-system-2d.ts b/cocos/particle-2d/particle-system-2d.ts index d3bfa5906a1..153d83816f5 100644 --- a/cocos/particle-2d/particle-system-2d.ts +++ b/cocos/particle-2d/particle-system-2d.ts @@ -42,6 +42,8 @@ import { IBatcher } from '../2d/renderer/i-batcher'; import { assetManager, builtinResMgr } from '../asset/asset-manager'; import { PositionType, EmitterMode, DURATION_INFINITY, START_RADIUS_EQUAL_TO_END_RADIUS, START_SIZE_EQUAL_TO_END_SIZE } from './define'; import { ccwindow } from '../core/global-exports'; +import type { IAssembler } from '../2d'; +import type { TextureBase } from '../asset/assets/texture-base'; /** * Image formats @@ -105,7 +107,7 @@ export enum ImageFormat { UNKNOWN, } -export function getImageFormatByData (imgData) { +export function getImageFormatByData (imgData): ImageFormat { // if it is a png file buffer. if (imgData.length > 8 && imgData[0] === 0x89 && imgData[1] === 0x50 @@ -182,7 +184,7 @@ export class ParticleSystem2D extends UIRenderer { @editable @displayOrder(6) @tooltip('i18n:particle_system.custom') - public get custom () { + public get custom (): boolean { return this._custom; } public set custom (value) { @@ -252,7 +254,7 @@ export class ParticleSystem2D extends UIRenderer { * @zh 当前播放的粒子数量。 * @readonly */ - public get particleCount () { + public get particleCount (): number { return this._simulator.particles.length; } @@ -262,7 +264,7 @@ export class ParticleSystem2D extends UIRenderer { */ @editable @tooltip('i18n:particle_system.totalParticles') - public get totalParticles () { + public get totalParticles (): number { return this._totalParticles; } public set totalParticles (value: number) { @@ -312,7 +314,7 @@ export class ParticleSystem2D extends UIRenderer { */ @editable @tooltip('i18n:particle_system.startColor') - public get startColor () { + public get startColor (): Color { return this._startColor; } @@ -341,7 +343,7 @@ export class ParticleSystem2D extends UIRenderer { } @override - @visible(() => false) + @visible((): boolean => false) set color (value) { } @@ -495,7 +497,7 @@ export class ParticleSystem2D extends UIRenderer { */ @type(PositionType) @tooltip('i18n:particle_system.positionType') - public get positionType () { + public get positionType (): number { return this._positionType; } @@ -512,7 +514,7 @@ export class ParticleSystem2D extends UIRenderer { @editable @displayOrder(2) @tooltip('i18n:particle_system.preview') - public get preview () { + public get preview (): boolean { return this._preview; } @@ -665,7 +667,7 @@ export class ParticleSystem2D extends UIRenderer { * @en Indicate whether the system simulation have stopped. * @zh 指示粒子播放是否完毕。 */ - public get stopped () { + public get stopped (): boolean { return this._stopped; } @@ -674,11 +676,11 @@ export class ParticleSystem2D extends UIRenderer { * @zh 是否激活粒子。 * @readonly */ - public get active () { + public get active (): boolean { return this._simulator.active; } - public get assembler () { + public get assembler (): IAssembler | null { return this._assembler; } public aspectRatio = 1; @@ -750,13 +752,13 @@ export class ParticleSystem2D extends UIRenderer { this._useFile = false; } - public onEnable () { + public onEnable (): void { super.onEnable(); this._updateMaterial(); this._updatePositionType(); } - public onDestroy () { + public onDestroy (): void { super.onDestroy(); if (this.autoRemoveOnFinish) { @@ -771,14 +773,14 @@ export class ParticleSystem2D extends UIRenderer { } } - private initProperties () { + private initProperties (): void { this._previewTimer = null; this._focused = false; this.aspectRatio = 1; this._simulator = new Simulator(this); } - public onFocusInEditor () { + public onFocusInEditor (): void { this._focused = true; const components = getParticleComponents(this.node); for (let i = 0; i < components.length; ++i) { @@ -786,7 +788,7 @@ export class ParticleSystem2D extends UIRenderer { } } - public onLostFocusInEditor () { + public onLostFocusInEditor (): void { this._focused = false; const components = getParticleComponents(this.node); for (let i = 0; i < components.length; ++i) { @@ -794,13 +796,13 @@ export class ParticleSystem2D extends UIRenderer { } } - private _startPreview () { + private _startPreview (): void { if (this._preview) { this.resetSystem(); } } - private _stopPreview () { + private _stopPreview (): void { if (this._preview) { this.resetSystem(); this.stopSystem(); @@ -810,7 +812,7 @@ export class ParticleSystem2D extends UIRenderer { } } - public __preload () { + public __preload (): void { super.__preload(); if (this._custom && this.spriteFrame && !this._renderSpriteFrame) { @@ -834,7 +836,7 @@ export class ParticleSystem2D extends UIRenderer { } } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = ParticleSystem2D.Assembler.getAssembler(this); if (this._assembler !== assembler) { @@ -847,7 +849,7 @@ export class ParticleSystem2D extends UIRenderer { } } - protected lateUpdate (dt) { + protected lateUpdate (dt): void { if (!this._simulator.finished) { this._simulator.step(dt); } @@ -860,7 +862,7 @@ export class ParticleSystem2D extends UIRenderer { * @zh 添加一个粒子到发射器中。 * @return {Boolean} */ - public addParticle () { + public addParticle (): void { // Not implemented } @@ -871,7 +873,7 @@ export class ParticleSystem2D extends UIRenderer { * // stop particle system. * myParticleSystem.stopSystem(); */ - public stopSystem () { + public stopSystem (): void { this._stopped = true; this._simulator.stop(); } @@ -883,7 +885,7 @@ export class ParticleSystem2D extends UIRenderer { * // play particle system. * myParticleSystem.resetSystem(); */ - public resetSystem () { + public resetSystem (): void { this._stopped = false; this._simulator.reset(); this.markForUpdateRenderData(); @@ -894,14 +896,14 @@ export class ParticleSystem2D extends UIRenderer { * @zh 发射器中粒子是否大于等于设置的总粒子数量。 * @return {Boolean} */ - public isFull () { + public isFull (): boolean { return (this.particleCount >= this.totalParticles); } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _applyFile () { + public _applyFile (): void { const file = this._file; if (file) { if (!file) { @@ -933,10 +935,10 @@ export class ParticleSystem2D extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _initTextureWithDictionary (dict: any) { + public _initTextureWithDictionary (dict: any): boolean { if (dict.spriteFrameUuid) { const spriteFrameUuid = dict.spriteFrameUuid; - assetManager.loadAny(spriteFrameUuid, (err: Error, spriteFrame: SpriteFrame) => { + assetManager.loadAny(spriteFrameUuid, (err: Error, spriteFrame: SpriteFrame): void => { if (err) { dict.spriteFrameUuid = undefined; this._initTextureWithDictionary(dict); @@ -950,7 +952,7 @@ export class ParticleSystem2D extends UIRenderer { const imgPath = path.changeBasename(this._plistFile, dict.textureFileName || ''); if (dict.textureFileName) { // Try to get the texture from the cache - assetManager.loadRemote(imgPath, (err: Error | null, imageAsset: ImageAsset) => { + assetManager.loadRemote(imgPath, (err: Error | null, imageAsset: ImageAsset): void => { if (err) { dict.textureFileName = undefined; this._initTextureWithDictionary(dict); @@ -1021,7 +1023,7 @@ export class ParticleSystem2D extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _initWithDictionary (dict: any) { + public _initWithDictionary (dict: any): boolean { this._useFile = true; this.totalParticles = parseInt(dict.maxParticles || 0); @@ -1137,7 +1139,7 @@ export class ParticleSystem2D extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _syncAspect () { + public _syncAspect (): void { if (this._renderSpriteFrame) { const frameRect = this._renderSpriteFrame.rect; this.aspectRatio = frameRect.width / frameRect.height; @@ -1147,7 +1149,7 @@ export class ParticleSystem2D extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _applySpriteFrame () { + public _applySpriteFrame (): void { this._renderSpriteFrame = this._renderSpriteFrame || this._spriteFrame; if (this._renderSpriteFrame) { if (this._renderSpriteFrame.texture) { @@ -1167,14 +1169,14 @@ export class ParticleSystem2D extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _getTexture () { + public _getTexture (): TextureBase | null { return (this._renderSpriteFrame && this._renderSpriteFrame.texture); } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateMaterial () { + public _updateMaterial (): void { if (this._customMaterial) { this.setMaterial(this._customMaterial, 0); const target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0]; @@ -1191,7 +1193,7 @@ export class ParticleSystem2D extends UIRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _finishedSimulation () { + public _finishedSimulation (): void { if (EDITOR_NOT_IN_PREVIEW) { if (this._preview && this._focused && !this.active /* && !cc.engine.isPlaying */) { this.resetSystem(); @@ -1206,11 +1208,11 @@ export class ParticleSystem2D extends UIRenderer { } } - protected _canRender () { + protected _canRender (): boolean { return super._canRender() && !this._stopped && this._renderSpriteFrame !== null && this._renderSpriteFrame !== undefined; } - protected _render (render: IBatcher) { + protected _render (render: IBatcher): void { if (this._positionType === PositionType.RELATIVE) { render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, this.node.parent); } else if (this.positionType === PositionType.GROUPED) { @@ -1220,7 +1222,7 @@ export class ParticleSystem2D extends UIRenderer { } } - protected _updatePositionType () { + protected _updatePositionType (): void { if (this._positionType === PositionType.RELATIVE) { this._renderEntity.setRenderTransform(this.node.parent); this._renderEntity.setUseLocal(true); diff --git a/cocos/particle-2d/png-reader.ts b/cocos/particle-2d/png-reader.ts index 6276ef42298..3f12e22b515 100644 --- a/cocos/particle-2d/png-reader.ts +++ b/cocos/particle-2d/png-reader.ts @@ -67,7 +67,7 @@ export class PNGReader { while (true) { chunkSize = this.readUInt32(); - const section = ((() => { + const section = (((): any[] => { const _results: any[] = []; for (i = _i = 0; _i < 4; i = ++_i) { _results.push(String.fromCharCode(this.data[this.pos++])); @@ -152,7 +152,7 @@ export class PNGReader { if (frame) { this.animation.frames.push(frame); } - this.colors = (() => { + this.colors = ((): number | undefined => { switch (this.colorType) { case 0: case 3: @@ -167,7 +167,7 @@ export class PNGReader { this.hasAlphaChannel = _ref === 4 || _ref === 6; const colors = this.colors + (this.hasAlphaChannel ? 1 : 0); this.pixelBitlength = this.bits * colors; - this.colorSpace = (() => { + this.colorSpace = ((): string | undefined => { switch (this.colors) { case 1: return 'DeviceGray'; @@ -189,7 +189,7 @@ export class PNGReader { } } - public read (bytes) { + public read (bytes): any[] { let i = 0; let _i = 0; const _results: any[] = []; for (i = _i = 0; bytes >= 0 ? _i < bytes : _i > bytes; i = bytes >= 0 ? ++_i : --_i) { @@ -198,7 +198,7 @@ export class PNGReader { return _results; } - public readUInt32 () { + public readUInt32 (): number { const b1 = this.data[this.pos++] << 24; const b2 = this.data[this.pos++] << 16; const b3 = this.data[this.pos++] << 8; @@ -206,13 +206,13 @@ export class PNGReader { return b1 | b2 | b3 | b4; } - public readUInt16 () { + public readUInt16 (): number { const b1 = this.data[this.pos++] << 8; const b2 = this.data[this.pos++]; return b1 | b2; } - public decodePixels (data) { + public decodePixels (data): Uint8Array { if (data == null) { data = this.imgData; } @@ -292,7 +292,7 @@ export class PNGReader { return pixels; } - public copyToImageData (imageData, pixels) { + public copyToImageData (imageData, pixels): void { let alpha = this.hasAlphaChannel; let palette: any; let colors = this.colors; @@ -327,7 +327,7 @@ export class PNGReader { } } - decodePalette () { + decodePalette (): Uint8Array { const palette = this.palette; const transparency = this.transparency.indexed || []; const ret = new Uint8Array((transparency.length || 0) + palette.length); @@ -344,7 +344,7 @@ export class PNGReader { return ret; } - render (canvas) { + render (canvas): any { canvas.width = this.width; canvas.height = this.height; const ctx = canvas.getContext('2d'); diff --git a/cocos/particle-2d/tiff-reader.ts b/cocos/particle-2d/tiff-reader.ts index bf4eec4127c..d7ad92efb7e 100644 --- a/cocos/particle-2d/tiff-reader.ts +++ b/cocos/particle-2d/tiff-reader.ts @@ -56,22 +56,22 @@ export class TiffReader { constructor () { } - public getUint8 (offset) { + public getUint8 (offset): any { return this._tiffData[offset]; } - public getUint16 (offset) { + public getUint16 (offset): number { if (this._littleEndian) return (this._tiffData[offset + 1] << 8) | (this._tiffData[offset]); else return (this._tiffData[offset] << 8) | (this._tiffData[offset + 1]); } - public getUint32 (offset) { + public getUint32 (offset): number { const a = this._tiffData; if (this._littleEndian) return (a[offset + 3] << 24) | (a[offset + 2] << 16) | (a[offset + 1] << 8) | (a[offset]); else return (a[offset] << 24) | (a[offset + 1] << 16) | (a[offset + 2] << 8) | (a[offset + 3]); } - public checkLittleEndian () { + public checkLittleEndian (): boolean { const BOM = this.getUint16(0); if (BOM === 0x4949) { @@ -86,7 +86,7 @@ export class TiffReader { return this._littleEndian; } - public hasTowel () { + public hasTowel (): boolean { // Check for towel. if (this.getUint16(2) !== 42) { throw RangeError(getError(6020)); @@ -95,7 +95,7 @@ export class TiffReader { return true; } - public getFieldTypeName (fieldType) { + public getFieldTypeName (fieldType): any { const typeNames = fieldTypeNames; if (fieldType in typeNames) { return typeNames[fieldType]; @@ -103,7 +103,7 @@ export class TiffReader { return null; } - public getFieldTagName (fieldTag) { + public getFieldTagName (fieldTag): any { const tagNames = fieldTagNames; if (fieldTag in tagNames) { @@ -114,7 +114,7 @@ export class TiffReader { } } - public getFieldTypeLength (fieldTypeName) { + public getFieldTypeLength (fieldTypeName): number { if (['BYTE', 'ASCII', 'SBYTE', 'UNDEFINED'].indexOf(fieldTypeName) !== -1) { return 1; } else if (['SHORT', 'SSHORT'].indexOf(fieldTypeName) !== -1) { @@ -128,7 +128,7 @@ export class TiffReader { return 0; } - public getFieldValues (fieldTagName, fieldTypeName, typeCount, valueOffset) { + public getFieldValues (fieldTagName, fieldTypeName, typeCount, valueOffset): any[] { const fieldValues: any[] = []; const fieldTypeLength = this.getFieldTypeLength(fieldTypeName); const fieldValueSize = fieldTypeLength * typeCount; @@ -156,14 +156,14 @@ export class TiffReader { } if (fieldTypeName === 'ASCII') { - fieldValues.forEach((e, i, a) => { + fieldValues.forEach((e, i, a): void => { a[i] = String.fromCharCode(e); }); } return fieldValues; } - public getBytes (numBytes, offset) { + public getBytes (numBytes, offset): any { if (numBytes <= 0) { logID(8001); } else if (numBytes <= 1) { @@ -181,7 +181,7 @@ export class TiffReader { return 0; } - getBits (numBits, byteOffset, bitOffset) { + getBits (numBits, byteOffset, bitOffset): { bits: number; byteOffset: any; bitOffset: number; } { bitOffset = bitOffset || 0; const extraBytes = Math.floor(bitOffset / 8); const newByteOffset = byteOffset + extraBytes; @@ -212,7 +212,7 @@ export class TiffReader { }; } - parseFileDirectory (offset) { + parseFileDirectory (offset): void { const numDirEntries = this.getUint16(offset); const tiffFields: IFile[] = []; let i = 0; @@ -239,7 +239,7 @@ export class TiffReader { } } - clampColorSample (colorSample, bitsPerSample) { + clampColorSample (colorSample, bitsPerSample): number { const multiplier = Math.pow(2, 8 - bitsPerSample); return Math.floor((colorSample * multiplier) + (multiplier - 1)); @@ -251,7 +251,7 @@ export class TiffReader { * @param {HTMLCanvasElement} canvas * @returns {*} */ - parseTIFF (tiffData, canvas) { + parseTIFF (tiffData, canvas): any { canvas = canvas || ccwindow.document.createElement('canvas'); this._tiffData = tiffData; @@ -287,7 +287,7 @@ export class TiffReader { let bitsPerPixel = 0; let hasBytesPerPixel = false; - fileDirectory.BitsPerSample.values.forEach((bitsPerSample, i, bitsPerSampleValues) => { + fileDirectory.BitsPerSample.values.forEach((bitsPerSample, i, bitsPerSampleValues): void => { sampleProperties[i] = { bitsPerSample, hasBytesPerSample: false, @@ -536,7 +536,7 @@ export class TiffReader { } // Invert samples. - pixelSamples.forEach((sample, index, samples) => { + pixelSamples.forEach((sample, index, samples): void => { samples[index] = invertValue - sample; }); diff --git a/cocos/particle/animator/color-overtime.ts b/cocos/particle/animator/color-overtime.ts index b14aa8b8d95..e267b39c86c 100644 --- a/cocos/particle/animator/color-overtime.ts +++ b/cocos/particle/animator/color-overtime.ts @@ -46,7 +46,7 @@ export default class ColorOvertimeModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -73,7 +73,7 @@ export default class ColorOvertimeModule extends ParticleModuleBase { * @param particle @en Particle to animate. @zh 模块需要更新的粒子。 * @internal */ - public animate (particle: Particle) { + public animate (particle: Particle): void { particle.color.set(particle.startColor); const rand = isGradientTwoValues(this.color) ? pseudoRandom(particle.randomSeed + COLOR_OVERTIME_RAND_OFFSET) : 0; particle.color.multiply(this.color.evaluate(1.0 - particle.remainingLifetime / particle.startLifetime, rand)); diff --git a/cocos/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts index 59b4bce7409..acffa79b818 100644 --- a/cocos/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -100,7 +100,7 @@ export default class CurveRange { break; } } - get mode () { + get mode (): number { return this._mode; } /** @@ -126,7 +126,7 @@ export default class CurveRange { * @zh 当 mode 为 Curve 时,使用的曲线。 * @deprecated Since V3.3. Use `spline` instead. */ - get curve () { + get curve (): geometry.AnimationCurve { return this._curve ??= new geometry.AnimationCurve(this.spline); } @@ -140,7 +140,7 @@ export default class CurveRange { * @zh 当 mode 为 TwoCurves 时,使用的曲线下限。 * @deprecated Since V3.3. Use `splineMin` instead. */ - get curveMin () { + get curveMin (): geometry.AnimationCurve { return this._curveMin ??= new geometry.AnimationCurve(this.splineMin); } @@ -154,7 +154,7 @@ export default class CurveRange { * @zh 当 mode 为 TwoCurves 时,使用的曲线上限。 * @deprecated Since V3.3. Use `splineMax` instead. */ - get curveMax () { + get curveMax (): geometry.AnimationCurve { return this._curveMax ??= new geometry.AnimationCurve(this.splineMax); } @@ -212,7 +212,7 @@ export default class CurveRange { * @zh 当模式为双曲线或双常数时,使用的插值比例,通常粒子系统会传入一个随机数以获得一个随机结果。 * @returns @en Curve value. @zh 曲线的值。 */ - public evaluate (time: number, rndRatio: number) { + public evaluate (time: number, rndRatio: number): number { switch (this._mode) { default: case Mode.Constant: @@ -262,7 +262,7 @@ export default class CurveRange { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBeforeSerialize (props) { + public _onBeforeSerialize (props): readonly ["mode", "constant", "multiplier"] | readonly ["mode", "spline", "multiplier"] | readonly ["mode", "splineMin", "splineMax", "multiplier"] | readonly ["mode", "constantMin", "constantMax", "multiplier"] { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return SerializableTable[this._mode]; } @@ -300,7 +300,7 @@ setClassAttr(CurveRange, 'spline', 'type', 'Object'); setClassAttr(CurveRange, 'spline', 'ctor', RealCurve); setClassAttr(CurveRange, 'spline', 'visible', true); -function evaluateCurve (cr: CurveRange, time: number, index: number) { +function evaluateCurve (cr: CurveRange, time: number, index: number): number { switch (cr.mode) { case Mode.Constant: return cr.constant; @@ -315,7 +315,7 @@ function evaluateCurve (cr: CurveRange, time: number, index: number) { } } -function evaluateHeight (cr: CurveRange) { +function evaluateHeight (cr: CurveRange): number { switch (cr.mode) { case Mode.TwoConstants: return 2; @@ -326,7 +326,7 @@ function evaluateHeight (cr: CurveRange) { } } -function packTexture (data, width, height) { +function packTexture (data, width, height): Texture2D { const image = new ImageAsset({ width, height, @@ -356,7 +356,7 @@ function updateTexture (tex: Texture2D | null, data, width, height): Texture2D { return tex; } -export function packCurveRangeZ (tex: Texture2D | null, data: Float32Array | null, samples: number, cr: CurveRange, discrete?: boolean) { +export function packCurveRangeZ (tex: Texture2D | null, data: Float32Array | null, samples: number, cr: CurveRange, discrete?: boolean): { texture: Texture2D; texdata: Float32Array; } { const height = evaluateHeight(cr); const len = samples * height * 4; if (data === null || data.length !== len) { @@ -383,7 +383,7 @@ export function packCurveRangeZ (tex: Texture2D | null, data: Float32Array | nul } return { texture: updateTexture(tex, data, samples, height), texdata: data }; } -export function packCurveRangeN (tex: Texture2D | null, data: Float32Array | null, samples: number, cr: CurveRange, discrete?: boolean) { +export function packCurveRangeN (tex: Texture2D | null, data: Float32Array | null, samples: number, cr: CurveRange, discrete?: boolean): { texture: Texture2D; texdata: Float32Array; } { const height = evaluateHeight(cr); const len = samples * height * 4; if (data === null || data.length !== len) { @@ -413,7 +413,7 @@ export function packCurveRangeN (tex: Texture2D | null, data: Float32Array | nul } // eslint-disable-next-line max-len -export function packCurveRangeXY (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, discrete?: boolean) { +export function packCurveRangeXY (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, discrete?: boolean): { texture: Texture2D; texdata: Float32Array; } { const height = Math.max(evaluateHeight(x), evaluateHeight(y)); const len = samples * height * 4; if (data === null || data.length !== len) { @@ -443,7 +443,7 @@ export function packCurveRangeXY (tex: Texture2D | null, data: Float32Array | nu } // eslint-disable-next-line max-len -export function packCurveRangeXYZ (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, z: CurveRange, discrete?: boolean) { +export function packCurveRangeXYZ (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, z: CurveRange, discrete?: boolean): { texture: Texture2D; texdata: Float32Array; } { const height = Math.max(evaluateHeight(x), evaluateHeight(y), evaluateHeight(z)); const len = samples * height * 4; if (data === null || data.length !== len) { @@ -473,7 +473,7 @@ export function packCurveRangeXYZ (tex: Texture2D | null, data: Float32Array | n } // eslint-disable-next-line max-len -export function packCurveRangeXYZW (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, z: CurveRange, w: CurveRange, discrete?: boolean) { +export function packCurveRangeXYZW (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, z: CurveRange, w: CurveRange, discrete?: boolean): { texture: Texture2D; texdata: Float32Array; } { const height = Math.max(evaluateHeight(x), evaluateHeight(y), evaluateHeight(z), evaluateHeight(w)); const len = samples * height * 4; if (data === null || data.length !== len) { diff --git a/cocos/particle/animator/force-overtime.ts b/cocos/particle/animator/force-overtime.ts index 91d5fd875fa..44aea52ff9d 100644 --- a/cocos/particle/animator/force-overtime.ts +++ b/cocos/particle/animator/force-overtime.ts @@ -51,7 +51,7 @@ export default class ForceOvertimeModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -123,7 +123,7 @@ export default class ForceOvertimeModule extends ParticleModuleBase { * @param worldTransform @en Particle system world transform. @zh 粒子系统的世界变换矩阵。 * @internal */ - public update (space, worldTransform) { + public update (space, worldTransform): void { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } @@ -134,7 +134,7 @@ export default class ForceOvertimeModule extends ParticleModuleBase { * @param dt @en Update interval time. @zh 粒子系统更新的间隔时间。 * @internal */ - public animate (p: Particle, dt) { + public animate (p: Particle, dt): void { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randX = isCurveTwoValues(this.x) ? pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET) : 0; const randY = isCurveTwoValues(this.y) ? pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET) : 0; diff --git a/cocos/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts index 73615cda496..ac0305cb144 100644 --- a/cocos/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -79,7 +79,7 @@ export default class GradientRange { * @zh 使用的渐变色类型 参考 [[Mode]]。 */ @type(Mode) - get mode () { + get mode (): number { return this._mode; } @@ -162,7 +162,7 @@ export default class GradientRange { * @zh 当模式为双色或双渐变色时,使用的插值比例,通常粒子系统会传入一个随机数以获得一个随机结果。 * @returns @en Gradient value. @zh 颜色渐变曲线的值。 */ - public evaluate (time: number, rndRatio: number) { + public evaluate (time: number, rndRatio: number): Color { switch (this._mode) { case Mode.Color: return this.color; @@ -184,12 +184,12 @@ export default class GradientRange { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBeforeSerialize (props: any) { + public _onBeforeSerialize (props: any): any { return SerializableTable[this._mode]; } } -function evaluateGradient (gr: GradientRange, time: number, index: number) { +function evaluateGradient (gr: GradientRange, time: number, index: number): Color { switch (gr.mode) { case Mode.Color: return gr.color; @@ -205,7 +205,7 @@ function evaluateGradient (gr: GradientRange, time: number, index: number) { return gr.color; } } -function evaluateHeight (gr: GradientRange) { +function evaluateHeight (gr: GradientRange): number { switch (gr.mode) { case Mode.TwoColors: return 2; @@ -215,7 +215,7 @@ function evaluateHeight (gr: GradientRange) { return 1; } } -export function packGradientRange (tex: Texture2D | null, data: Uint8Array | null, samples: number, gr: GradientRange) { +export function packGradientRange (tex: Texture2D | null, data: Uint8Array | null, samples: number, gr: GradientRange): { texture: Texture2D; texdata: Uint8Array; } { const height = evaluateHeight(gr); const len = samples * height * 4; if (data === null || data.length !== len) { diff --git a/cocos/particle/animator/limit-velocity-overtime.ts b/cocos/particle/animator/limit-velocity-overtime.ts index f7d7f6f0129..1423e643ee8 100644 --- a/cocos/particle/animator/limit-velocity-overtime.ts +++ b/cocos/particle/animator/limit-velocity-overtime.ts @@ -53,7 +53,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -166,7 +166,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { * @param worldTransform @en Particle system world transform @zh 粒子系统的世界变换矩阵 * @internal */ - public update (space: number, worldTransform: Mat4) { + public update (space: number, worldTransform: Mat4): void { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } @@ -177,7 +177,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 * @internal */ - public animate (p: Particle, dt: number) { + public animate (p: Particle, dt: number): void { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const dampedVel = _temp_v3; if (this.separateAxes) { @@ -206,7 +206,7 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { } } -function dampenBeyondLimit (vel: number, limit: number, dampen: number) { +function dampenBeyondLimit (vel: number, limit: number, dampen: number): number { const sgn = Math.sign(vel); let abs = Math.abs(vel); if (abs > limit) { diff --git a/cocos/particle/animator/noise-module.ts b/cocos/particle/animator/noise-module.ts index cfce15415a2..b4106e54f90 100644 --- a/cocos/particle/animator/noise-module.ts +++ b/cocos/particle/animator/noise-module.ts @@ -43,7 +43,7 @@ export class NoiseModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -62,7 +62,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 100]) @displayOrder(16) @slide - get strengthX () { + get strengthX (): number { return this._strengthX; } set strengthX (value: number) { @@ -79,7 +79,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 100]) @displayOrder(16) @slide - get strengthY () { + get strengthY (): number { return this._strengthY; } set strengthY (value: number) { @@ -96,7 +96,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 100]) @displayOrder(16) @slide - get strengthZ () { + get strengthZ (): number { return this._strengthZ; } set strengthZ (value: number) { @@ -113,7 +113,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 100]) @slide @displayOrder(16) - get noiseSpeedX () { + get noiseSpeedX (): number { return this._noiseSpeedX; } set noiseSpeedX (value: number) { @@ -130,7 +130,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 100]) @displayOrder(16) @slide - get noiseSpeedY () { + get noiseSpeedY (): number { return this._noiseSpeedY; } set noiseSpeedY (value: number) { @@ -147,7 +147,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 100]) @displayOrder(16) @slide - get noiseSpeedZ () { + get noiseSpeedZ (): number { return this._noiseSpeedZ; } set noiseSpeedZ (value: number) { @@ -164,7 +164,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 100, 0.1]) @displayOrder(16) @slide - get noiseFrequency () { + get noiseFrequency (): number { return this._noiseFrequency; } set noiseFrequency (value: number) { @@ -182,7 +182,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 1, 0.1]) @displayOrder(16) @slide - get remapX () { + get remapX (): number { return this._remapX; } set remapX (value: number) { @@ -200,7 +200,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 1, 0.1]) @displayOrder(16) @slide - get remapY () { + get remapY (): number { return this._remapY; } set remapY (value: number) { @@ -218,7 +218,7 @@ export class NoiseModule extends ParticleModuleBase { @range([0, 1, 0.1]) @displayOrder(16) @slide - get remapZ () { + get remapZ (): number { return this._remapZ; } set remapZ (value: number) { @@ -235,7 +235,7 @@ export class NoiseModule extends ParticleModuleBase { @range([1, 4, 1]) @displayOrder(16) @slide - get octaves () { + get octaves (): number { return this._octaves; } set octaves (value: number) { @@ -253,7 +253,7 @@ export class NoiseModule extends ParticleModuleBase { @type(CCFloat) @range([0, 1, 0.1]) @displayOrder(16) - get octaveMultiplier () { + get octaveMultiplier (): number { return this._octaveMultiplier; } set octaveMultiplier (value: number) { @@ -271,7 +271,7 @@ export class NoiseModule extends ParticleModuleBase { @type(CCFloat) @range([1, 4, 0.1]) @displayOrder(16) - get octaveScale () { + get octaveScale (): number { return this._octaveScale; } set octaveScale (value: number) { @@ -293,7 +293,7 @@ export class NoiseModule extends ParticleModuleBase { * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 * @internal */ - public animate (particle: Particle, dt: number) { + public animate (particle: Particle, dt: number): void { this.noise.setTime(particle.particleSystem.time); this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ); this.noise.setFrequency(this.noiseFrequency); @@ -319,7 +319,7 @@ export class NoiseModule extends ParticleModuleBase { * @param width @en Texture width @zh 噪声图宽度 * @param height @en Texture height @zh 噪声图高度 */ - public getNoisePreview (out: number[], ps, width: number, height: number) { + public getNoisePreview (out: number[], ps, width: number, height: number): void { this.noise.setTime(ps.time); this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ); this.noise.setFrequency(this.noiseFrequency); diff --git a/cocos/particle/animator/rotation-overtime.ts b/cocos/particle/animator/rotation-overtime.ts index 474b388d1d2..e1f1a29ae89 100644 --- a/cocos/particle/animator/rotation-overtime.ts +++ b/cocos/particle/animator/rotation-overtime.ts @@ -51,7 +51,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -71,7 +71,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { */ @displayOrder(1) @tooltip('i18n:rotationOvertimeModule.separateAxes') - get separateAxes () { + get separateAxes (): boolean { return this._separateAxes; } @@ -121,7 +121,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { private _quatRot: Quat = new Quat(); private _otherEuler: Vec3 = new Vec3(); - private _processRotation (p: Particle, r2d: number) { + private _processRotation (p: Particle, r2d: number): void { // Same as the particle-vs-legacy.chunk glsl statemants const renderMode = p.particleSystem.processor.getInfo().renderMode; if (renderMode !== RenderMode.Mesh) { @@ -143,7 +143,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 * @internal */ - public animate (p: Particle, dt: number) { + public animate (p: Particle, dt: number): void { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randZ = isCurveTwoValues(this.z) ? pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET) : 0; const renderMode = p.particleSystem.processor.getInfo().renderMode; diff --git a/cocos/particle/animator/size-overtime.ts b/cocos/particle/animator/size-overtime.ts index ced2a24b73d..ab94d480c6b 100644 --- a/cocos/particle/animator/size-overtime.ts +++ b/cocos/particle/animator/size-overtime.ts @@ -50,7 +50,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -127,7 +127,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 * @internal */ - public animate (particle: Particle, dt: number) { + public animate (particle: Particle, dt: number): void { if (!this.separateAxes) { const rand = isCurveTwoValues(this.size) ? pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET) : 0; Vec3.multiplyScalar(particle.size, particle.startSize, diff --git a/cocos/particle/animator/texture-animation.ts b/cocos/particle/animator/texture-animation.ts index aa5f1696d70..a08dd4f5b05 100644 --- a/cocos/particle/animator/texture-animation.ts +++ b/cocos/particle/animator/texture-animation.ts @@ -89,7 +89,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - get enable () { + get enable (): boolean { return this._enable; } @@ -111,7 +111,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { @type(Mode) @displayOrder(1) @tooltip('i18n:textureAnimationModule.mode') - get mode () { + get mode (): number { return this._mode; } @@ -127,7 +127,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { */ @displayOrder(2) @tooltip('i18n:textureAnimationModule.numTilesX') - get numTilesX () { + get numTilesX (): number { return this._numTilesX; } @@ -144,7 +144,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { */ @displayOrder(3) @tooltip('i18n:textureAnimationModule.numTilesY') - get numTilesY () { + get numTilesY (): number { return this._numTilesY; } @@ -202,7 +202,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { /** * @ignore */ - get flipU () { + get flipU (): number { return this._flipU; } @@ -213,7 +213,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { @serializable private _flipV = 0; - get flipV () { + get flipV (): number { return this._flipV; } @@ -224,7 +224,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { @serializable private _uvChannelMask = -1; - get uvChannelMask () { + get uvChannelMask (): number { return this._uvChannelMask; } @@ -262,7 +262,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { * @param p @en Particle to set start row. @zh 设置初始行属性的粒子。 * @internal */ - public init (p: Particle) { + public init (p: Particle): void { p.startRow = Math.floor(Math.random() * this.numTilesY); } @@ -273,7 +273,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { * @param dt @en Update interval time. @zh 粒子系统更新的间隔时间。 * @internal */ - public animate (p: Particle, dt: number) { + public animate (p: Particle, dt: number): void { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randStart = isCurveTwoValues(this.startFrame) ? pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET) : 0; const randFrame = isCurveTwoValues(this.frameOverTime) ? pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET) : 0; diff --git a/cocos/particle/animator/velocity-overtime.ts b/cocos/particle/animator/velocity-overtime.ts index 9d3103a970f..05b73ba362f 100644 --- a/cocos/particle/animator/velocity-overtime.ts +++ b/cocos/particle/animator/velocity-overtime.ts @@ -54,7 +54,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -134,7 +134,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { * @param worldTransform @en Particle system world transform @zh 粒子系统的世界变换矩阵 * @internal */ - public update (space: number, worldTransform: Mat4) { + public update (space: number, worldTransform: Mat4): void { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } @@ -145,7 +145,7 @@ export default class VelocityOvertimeModule extends ParticleModuleBase { * @param dt @en Update interval time @zh 粒子系统更新的间隔时间 * @internal */ - public animate (p: Particle, dt: number) { + public animate (p: Particle, dt: number): void { const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; const randX = isCurveTwoValues(this.x) ? pseudoRandom(p.randomSeed ^ VELOCITY_X_OVERTIME_RAND_OFFSET) : 0; const randY = isCurveTwoValues(this.y) ? pseudoRandom(p.randomSeed ^ VELOCITY_Y_OVERTIME_RAND_OFFSET) : 0; diff --git a/cocos/particle/billboard.ts b/cocos/particle/billboard.ts index 46384bc78e0..1e703d7fbde 100644 --- a/cocos/particle/billboard.ts +++ b/cocos/particle/billboard.ts @@ -45,7 +45,7 @@ export class Billboard extends Component { */ @type(Texture2D) @tooltip('i18n:billboard.texture') - get texture () { + get texture (): null { return this._texture; } @@ -63,7 +63,7 @@ export class Billboard extends Component { * @zh 高度。 */ @tooltip('i18n:billboard.height') - get height () { + get height (): number { return this._height; } @@ -82,7 +82,7 @@ export class Billboard extends Component { * @zh 宽度。 */ @tooltip('i18n:billboard.width') - public get width () { + public get width (): number { return this._width; } @@ -101,7 +101,7 @@ export class Billboard extends Component { * @zh billboard绕中心点旋转的角度 */ @tooltip('i18n:billboard.rotation') - public get rotation () { + public get rotation (): number { return Math.round(toDegree(this._rotation) * 100) / 100; } @@ -125,11 +125,11 @@ export class Billboard extends Component { super(); } - public onLoad () { + public onLoad (): void { this.createModel(); } - public onEnable () { + public onEnable (): void { this.attachToScene(); this._model!.enabled = true; this.width = this._width; @@ -138,11 +138,11 @@ export class Billboard extends Component { this.texture = this.texture; } - public onDisable () { + public onDisable (): void { this.detachFromScene(); } - private attachToScene () { + private attachToScene (): void { if (this._model && this.node && this.node.scene) { if (this._model.scene) { this.detachFromScene(); @@ -151,13 +151,13 @@ export class Billboard extends Component { } } - private detachFromScene () { + private detachFromScene (): void { if (this._model && this._model.scene) { this._model.scene.removeModel(this._model); } } - private createModel () { + private createModel (): void { this._mesh = createMesh({ primitiveMode: PrimitiveMode.TRIANGLE_LIST, positions: [0, 0, 0, diff --git a/cocos/particle/burst.ts b/cocos/particle/burst.ts index 83fe0c666d2..16cf1fb0c06 100644 --- a/cocos/particle/burst.ts +++ b/cocos/particle/burst.ts @@ -42,7 +42,7 @@ export default class Burst { * @zh 粒子系统开始运行到触发此次 Brust 的时间。 */ @editable - get time () { + get time (): number { return this._time; } @@ -59,7 +59,7 @@ export default class Burst { * @zh Burst 的触发次数。 */ @editable - get repeatCount () { + get repeatCount (): number { return this._repeatCount; } @@ -100,7 +100,7 @@ export default class Burst { * @param dt @en Update interval time. @zh 粒子系统更新的间隔时间。 * @internal */ - public update (psys, dt: number) { + public update (psys, dt: number): void { if (this._remainingCount === 0) { this._remainingCount = this._repeatCount; this._curTime = this._time; @@ -121,7 +121,7 @@ export default class Burst { * @en Reset remaining burst count and burst time to zero. * @zh 重置触发时间和留存的触发次数为零。 */ - public reset () { + public reset (): void { this._remainingCount = 0; this._curTime = 0.0; } @@ -132,7 +132,7 @@ export default class Burst { * @param psys @en Particle system to burst. @zh 要触发的粒子系统。 * @returns @en burst max particle count. @zh 一次最多触发的粒子个数。 */ - public getMaxCount (psys) { + public getMaxCount (psys): number { return this.count.getMax() * Math.min(Math.ceil(psys.duration / this.repeatInterval), this.repeatCount); } } diff --git a/cocos/particle/emitter/shape-module.ts b/cocos/particle/emitter/shape-module.ts index 26afbad8243..2f96b9cc77a 100644 --- a/cocos/particle/emitter/shape-module.ts +++ b/cocos/particle/emitter/shape-module.ts @@ -66,7 +66,7 @@ export default class ShapeModule { */ @displayOrder(13) @tooltip('i18n:shapeModule.position') - get position () { + get position (): Vec3 { return this._position; } set position (val) { @@ -80,7 +80,7 @@ export default class ShapeModule { */ @displayOrder(14) @tooltip('i18n:shapeModule.rotation') - get rotation () { + get rotation (): Vec3 { return this._rotation; } set rotation (val) { @@ -94,7 +94,7 @@ export default class ShapeModule { */ @displayOrder(15) @tooltip('i18n:shapeModule.scale') - get scale () { + get scale (): Vec3 { return this._scale; } set scale (val) { @@ -113,7 +113,7 @@ export default class ShapeModule { const enumName = getShapeTypeEnumName(this.shapeType); return subset.includes(enumName); }) - get arc () { + get arc (): number { return toDegree(this._arc); } @@ -134,7 +134,7 @@ export default class ShapeModule { const enumName = getShapeTypeEnumName(this.shapeType); return subset.includes(enumName); }) - get angle () { + get angle (): number { return Math.round(toDegree(this._angle) * 100) / 100; } @@ -149,7 +149,7 @@ export default class ShapeModule { * @zh 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -170,7 +170,7 @@ export default class ShapeModule { @type(ShapeType) @tooltip('i18n:shapeModule.shapeType') - public get shapeType () { + public get shapeType (): number { return this._shapeType; } @@ -394,7 +394,7 @@ export default class ShapeModule { * @param ps @en Emit shape applied to which Particle system. @zh 使用发射形状的粒子系统。 * @internal */ - public onInit (ps: ParticleSystem) { + public onInit (ps: ParticleSystem): void { this.particleSystem = ps; this.constructMat(); this.lastTime = this.particleSystem._time; @@ -406,7 +406,7 @@ export default class ShapeModule { * @param p @en Particle emitted. @zh 发射出来的粒子。 * @internal */ - public emit (p) { + public emit (p): void { switch (this.shapeType) { case ShapeType.Box: boxEmit(this.emitFrom, this.boxThickness, p.position, p.velocity); @@ -440,12 +440,12 @@ export default class ShapeModule { this.lastTime = this.particleSystem._time; } - private constructMat () { + private constructMat (): void { Quat.fromEuler(this.quat, this._rotation.x, this._rotation.y, this._rotation.z); Mat4.fromRTS(this.mat, this.quat, this._position, this._scale); } - private generateArcAngle () { + private generateArcAngle (): number { if (this.arcMode === ArcMode.Random) { return randomRange(0, this._arc); } @@ -465,7 +465,7 @@ export default class ShapeModule { } } -function sphereEmit (emitFrom, radius, radiusThickness, pos, dir) { +function sphereEmit (emitFrom, radius, radiusThickness, pos, dir): void { switch (emitFrom) { case EmitLocation.Volume: randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); @@ -481,7 +481,7 @@ function sphereEmit (emitFrom, radius, radiusThickness, pos, dir) { } } -function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) { +function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir): void { switch (emitFrom) { case EmitLocation.Volume: randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); @@ -503,7 +503,7 @@ function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) { } } -function coneEmit (emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) { +function coneEmit (emitFrom, radius, radiusThickness, theta, angle, length, pos, dir): void { switch (emitFrom) { case EmitLocation.Base: randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); @@ -533,7 +533,7 @@ function coneEmit (emitFrom, radius, radiusThickness, theta, angle, length, pos, } } -function boxEmit (emitFrom, boxThickness, pos, dir) { +function boxEmit (emitFrom, boxThickness, pos, dir): void { switch (emitFrom) { case EmitLocation.Volume: randomPointInCube(pos, _unitBoxExtent); @@ -563,12 +563,12 @@ function boxEmit (emitFrom, boxThickness, pos, dir) { Vec3.copy(dir, particleEmitZAxis); } -function circleEmit (radius, radiusThickness, theta, pos, dir) { +function circleEmit (radius, radiusThickness, theta, pos, dir): void { randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); Vec3.normalize(dir, pos); } -function applyBoxThickness (pos, thickness) { +function applyBoxThickness (pos, thickness): void { if (thickness.x > 0) { pos[0] += 0.5 * randomRange(-thickness.x, thickness.x); pos[0] = clamp(pos[0], -0.5, 0.5); diff --git a/cocos/particle/line.ts b/cocos/particle/line.ts index 5a923161fb2..7524a2abf94 100644 --- a/cocos/particle/line.ts +++ b/cocos/particle/line.ts @@ -50,7 +50,7 @@ export class Line extends ModelRenderer { @type(Texture2D) @displayOrder(0) @tooltip('i18n:line.texture') - get texture () { + get texture (): null { return this._texture; } @@ -68,7 +68,7 @@ export class Line extends ModelRenderer { @displayOrder(1) @tooltip('i18n:line.material') @displayName('Material') - get lineMaterial () { + get lineMaterial (): Material | null { return this.getSharedMaterial(0); } @@ -79,7 +79,7 @@ export class Line extends ModelRenderer { @override @visible(false) @serializable - get sharedMaterials () { + get sharedMaterials (): (Material | null)[] { return super.sharedMaterials; } @@ -96,7 +96,7 @@ export class Line extends ModelRenderer { */ @displayOrder(1) @tooltip('i18n:line.worldSpace') - get worldSpace () { + get worldSpace (): boolean { return this._worldSpace; } @@ -122,7 +122,7 @@ export class Line extends ModelRenderer { @type([Vec3]) @displayOrder(2) @tooltip('i18n:line.positions') - get positions () { + get positions (): Vec3[] { return this._positions; } @@ -142,7 +142,7 @@ export class Line extends ModelRenderer { @range([0, 1]) @displayOrder(3) @tooltip('i18n:line.width') - get width () { + get width (): CurveRange { return this._width; } @@ -164,7 +164,7 @@ export class Line extends ModelRenderer { @type(GradientRange) @displayOrder(6) @tooltip('i18n:line.color') - get color () { + get color (): GradientRange { return this._color; } @@ -191,7 +191,7 @@ export class Line extends ModelRenderer { @type(Vec2) @displayOrder(4) @tooltip('i18n:line.tile') - get tile () { + get tile (): Vec2 { return this._tile; } @@ -210,7 +210,7 @@ export class Line extends ModelRenderer { @type(Vec2) @displayOrder(5) @tooltip('i18n:line.offset') - get offset () { + get offset (): Vec2 { return this._offset; } @@ -227,7 +227,7 @@ export class Line extends ModelRenderer { super(); } - public onLoad () { + public onLoad (): void { const model = cclegacy.director.root.createModel(LineModel); if (this._models.length === 0) { this._models.push(model); @@ -252,7 +252,7 @@ export class Line extends ModelRenderer { model.setCapacity(100); } - public onEnable () { + public onEnable (): void { super.onEnable(); if (this._models.length === 0 || !this._models[0]) { return; @@ -265,13 +265,13 @@ export class Line extends ModelRenderer { lineModel.addLineVertexData(this._positions, this.width, this.color); } - public onDisable () { + public onDisable (): void { if (this._models.length > 0 && this._models[0]) { this._detachFromScene(); } } - protected _attachToScene () { + protected _attachToScene (): void { super._attachToScene(); if (this._models.length > 0 && this._models[0] && this.node && this.node.scene) { const lineModel = this._models[0]; @@ -285,7 +285,7 @@ export class Line extends ModelRenderer { /** * @engineInternal */ - public _detachFromScene () { + public _detachFromScene (): void { super._detachFromScene(); if (this._models.length > 0 && this._models[0]) { const lineModel = this._models[0]; @@ -295,7 +295,7 @@ export class Line extends ModelRenderer { } } - protected _onMaterialModified (index: number, material: Material | null) { + protected _onMaterialModified (index: number, material: Material | null): void { super._onMaterialModified(index, material); const matIns = this.getMaterialInstance(0); if (matIns) { diff --git a/cocos/particle/models/line-model.ts b/cocos/particle/models/line-model.ts index 26a973ba05b..4b35293766e 100644 --- a/cocos/particle/models/line-model.ts +++ b/cocos/particle/models/line-model.ts @@ -65,12 +65,12 @@ export class LineModel extends scene.Model { this._capacity = 100; } - public setCapacity (capacity: number) { + public setCapacity (capacity: number): void { this._capacity = capacity; this.createBuffer(); } - public createBuffer () { + public createBuffer (): void { this._vertSize = 0; for (const a of _vertex_attrs) { (a as any).offset = this._vertSize; @@ -82,7 +82,7 @@ export class LineModel extends scene.Model { this._vdataUint32 = new Uint32Array(this._vBuffer); } - public updateMaterial (mat: Material) { + public updateMaterial (mat: Material): void { this._material = mat; super.setSubModelMaterial(0, mat); } @@ -131,7 +131,7 @@ export class LineModel extends scene.Model { return vBuffer; } - public addLineVertexData (positions: Vec3[], width: CurveRange, color: GradientRange) { + public addLineVertexData (positions: Vec3[], width: CurveRange, color: GradientRange): void { if (positions.length > 1) { let offset = 0; Vec3.subtract(_temp_v1, positions[1], positions[0]); @@ -212,7 +212,7 @@ export class LineModel extends scene.Model { this.updateIA(Math.max(0, positions.length - 1)); } - public updateIA (count: number) { + public updateIA (count: number): void { const ia = this._subModels[0].inputAssembler; ia.vertexBuffers[0].update(this._vdataF32!); ia.firstIndex = 0; @@ -220,7 +220,7 @@ export class LineModel extends scene.Model { ia.vertexCount = this._iaVertCount; } - private destroySubMeshData () { + private destroySubMeshData (): void { if (this._subMeshData) { this._subMeshData.destroy(); this._subMeshData = null; diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index 82c53fa6bbc..6e79584eba7 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -101,7 +101,7 @@ export default class ParticleBatchModel extends scene.Model { this._mesh = null; } - public setCapacity (capacity: number) { + public setCapacity (capacity: number): void { const capChanged = this._capacity !== capacity; this._capacity = capacity; if (this._subMeshData && capChanged) { @@ -109,7 +109,7 @@ export default class ParticleBatchModel extends scene.Model { } } - public setVertexAttributes (mesh: Mesh | null, attrs: Attribute[]) { + public setVertexAttributes (mesh: Mesh | null, attrs: Attribute[]): void { if (!this._useInstance) { if (this._mesh === mesh && this._vertAttrs === attrs) { return; @@ -129,7 +129,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private setVertexAttributesIns (mesh: Mesh | null, attrs: Attribute[]) { + private setVertexAttributesIns (mesh: Mesh | null, attrs: Attribute[]): void { if (this._mesh === mesh && this._vertAttrs === attrs) { return; } @@ -169,9 +169,9 @@ export default class ParticleBatchModel extends scene.Model { )); const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._capacity * this._vertCount); if (this._mesh && this._capacity > 0) { - let vOffset = (this._vertAttrs![this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD)] as any).offset; + let vOffset = (this._vertAttrs![this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD)] as any).offset; this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSize, vOffset); // copy mesh uv to ATTR_TEX_COORD - let vIdx = this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD3); + let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3); vOffset = (this._vertAttrs![vIdx++] as any).offset; this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSize, vOffset); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; @@ -247,7 +247,7 @@ export default class ParticleBatchModel extends scene.Model { return vBuffer; } - private createSubMeshDataInsStatic () { + private createSubMeshDataInsStatic (): void { this._vertCount = 4; this._indexCount = 6; if (this._mesh) { @@ -264,10 +264,10 @@ export default class ParticleBatchModel extends scene.Model { const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSizeStatic * this._vertCount); if (this._mesh) { - let vIdx = this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD); // find ATTR_TEX_COORD index + let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD); // find ATTR_TEX_COORD index let vOffset = (this._vertAttrs![vIdx] as any).offset; // find ATTR_TEX_COORD offset this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh uv to ATTR_TEX_COORD - vIdx = this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD3); // find ATTR_TEX_COORD3 index + vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3); // find ATTR_TEX_COORD3 index vOffset = (this._vertAttrs![vIdx++] as any).offset; // find ATTR_TEX_COORD3 offset this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; @@ -315,17 +315,17 @@ export default class ParticleBatchModel extends scene.Model { this._insBuffers.push(vertexBuffer); } - private createInsSubmesh () { + private createInsSubmesh (): void { this._subMeshData = new RenderingSubMesh(this._insBuffers, this._vertAttrs!, PrimitiveMode.TRIANGLE_LIST, this._insIndices); this.initSubModel(0, this._subMeshData, this._material!); } - public updateMaterial (mat: Material) { + public updateMaterial (mat: Material): void { this._material = mat; this.setSubModelMaterial(0, mat); } - public addParticleVertexData (index: number, pvdata: any[]) { + public addParticleVertexData (index: number, pvdata: any[]): void { if (!this._useInstance) { if (!this._mesh) { let offset: number = index * this._vertAttrsFloatCount; @@ -371,7 +371,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private addParticleVertexDataIns (index: number, pvdata: any[]) { + private addParticleVertexDataIns (index: number, pvdata: any[]): void { let offset: number = index * this._vertAttrsFloatCount; if (!this._mesh) { this._vdataF32![offset++] = pvdata[0].x; // position @@ -411,7 +411,7 @@ export default class ParticleBatchModel extends scene.Model { } } - public addGPUParticleVertexData (p: Particle, num: number, time:number) { + public addGPUParticleVertexData (p: Particle, num: number, time:number): void { if (!this._useInstance) { let offset = num * this._vertAttrsFloatCount * this._vertCount; for (let i = 0; i < this._vertCount; i++) { @@ -450,7 +450,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private addGPUParticleVertexDataIns (p: Particle, num: number, time:number) { + private addGPUParticleVertexDataIns (p: Particle, num: number, time:number): void { let offset = num * this._vertAttrsFloatCount; let idx = offset; this._vdataF32![idx++] = p.position.x; @@ -482,7 +482,7 @@ export default class ParticleBatchModel extends scene.Model { offset += this._vertAttrsFloatCount; } - public updateGPUParticles (num: number, time: number, dt: number) { + public updateGPUParticles (num: number, time: number, dt: number): number { if (!this._useInstance) { const pSize = this._vertAttrsFloatCount * this._vertCount; let pBaseIndex = 0; @@ -508,7 +508,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private updateGPUParticlesIns (num: number, time: number, dt: number) { + private updateGPUParticlesIns (num: number, time: number, dt: number): number { const pSize = this._vertAttrsFloatCount; let pBaseIndex = 0; let startTime = 0; @@ -530,19 +530,19 @@ export default class ParticleBatchModel extends scene.Model { return num; } - public constructAttributeIndex () { + public constructAttributeIndex (): void { if (!this._vertAttrs) { return; } - let vIdx = this._vertAttrs.findIndex((val) => val.name === 'a_position_starttime'); + let vIdx = this._vertAttrs.findIndex((val): boolean => val.name === 'a_position_starttime'); let vOffset = (this._vertAttrs[vIdx] as any).offset; this._startTimeOffset = vOffset / 4 + 3; - vIdx = this._vertAttrs.findIndex((val) => val.name === 'a_dir_life'); + vIdx = this._vertAttrs.findIndex((val): boolean => val.name === 'a_dir_life'); vOffset = (this._vertAttrs[vIdx] as any).offset; this._lifeTimeOffset = vOffset / 4 + 3; } - public updateIA (count: number) { + public updateIA (count: number): void { if (!this._useInstance) { if (count <= 0) { return; @@ -557,7 +557,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private updateIAIns (count: number) { + private updateIAIns (count: number): void { if (count <= 0) { return; } @@ -570,7 +570,7 @@ export default class ParticleBatchModel extends scene.Model { ia.vertexCount = this._iaVertCount; } - public clear () { + public clear (): void { if (!this._useInstance) { this._subModels[0].inputAssembler.indexCount = 0; } else { @@ -578,16 +578,16 @@ export default class ParticleBatchModel extends scene.Model { } } - private clearIns () { + private clearIns (): void { this._subModels[0].inputAssembler.instanceCount = 0; } - public destroy () { + public destroy (): void { super.destroy(); this.doDestroy(); } - public doDestroy () { + public doDestroy (): void { this._vBuffer = null; this._vdataF32 = null; this._vdataUint32 = null; @@ -601,7 +601,7 @@ export default class ParticleBatchModel extends scene.Model { this.destroySubMeshData(); } - private rebuild () { + private rebuild (): void { if (!this._useInstance) { this._vBuffer = this.createSubMeshData(); this._vdataF32 = new Float32Array(this._vBuffer); @@ -611,7 +611,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private rebuildIns () { + private rebuildIns (): void { this._vBuffer = this.createSubMeshDataInsDynamic(); this._vdataF32 = new Float32Array(this._vBuffer); this._vdataUint32 = new Uint32Array(this._vBuffer); @@ -621,7 +621,7 @@ export default class ParticleBatchModel extends scene.Model { this.createInsSubmesh(); } - private destroySubMeshData () { + private destroySubMeshData (): void { if (this._subMeshData) { this._subMeshData.destroy(); this._subMeshData = null; diff --git a/cocos/particle/noise.ts b/cocos/particle/noise.ts index fd42921d23c..ff9c780acbc 100644 --- a/cocos/particle/noise.ts +++ b/cocos/particle/noise.ts @@ -126,7 +126,7 @@ export class ParticleNoise { * @param y @en Y axis roll speed. @zh Y 轴滚动速度。 * @param z @en Z axis roll speed. @zh Z 轴滚动速度。 */ - public setSpeed (x, y, z) { + public setSpeed (x, y, z): void { this.noiseSpeed.set(x, y, z); } @@ -135,7 +135,7 @@ export class ParticleNoise { * @zh 设置生成的噪声频率。 * @param f @en Noise texture frequency. @zh 噪声频率。 */ - public setFrequency (f) { + public setFrequency (f): void { this.noiseFrequency = f; } @@ -147,7 +147,7 @@ export class ParticleNoise { * @param z @en Z value transformed. @zh Z 轴上噪声值的偏移。 * @deprecated since v3.6.0 */ - public setAbs (x, y, z) { + public setAbs (x, y, z): void { this.noiseAbs.set(x, y, z); } @@ -158,7 +158,7 @@ export class ParticleNoise { * @param y @en Noise amplititude on Y axis. @zh Y 轴上的噪声强度。 * @param z @en Noise amplititude on Z axis. @zh Z 轴上的噪声强度。 */ - public setAmplititude (x, y, z) { + public setAmplititude (x, y, z): void { this.noiseAmplitude.set(x, y, z); } @@ -169,7 +169,7 @@ export class ParticleNoise { * @param y @en For each additional noise layer, reduce the strength by this proportion. @zh 每一层的噪声强度衰减比例。 * @param z @en For each additional noise layer, adjust the frequency by this multiplier. @zh 对于每个附加的噪声层,按此乘数调整频率。 */ - public setOctaves (x, y, z) { + public setOctaves (x, y, z): void { this.octaves.set(x, y, z); } @@ -178,7 +178,7 @@ export class ParticleNoise { * @zh 设置更新间隔时间。 * @param t @en Update interval time. @zh 更新的间隔时间。 */ - public setTime (t) { + public setTime (t): void { this.dt = t; } @@ -187,7 +187,7 @@ export class ParticleNoise { * @zh 设置噪声纹理的采样点。 * @param p @en Sample point of noise texture. @zh 噪声纹理采样点。 */ - public setSamplePoint (p: Vec3) { + public setSamplePoint (p: Vec3): void { this.point.set(p); } @@ -220,7 +220,7 @@ export class ParticleNoise { return sum / range; } - private getNoiseMix (out: Vec2, point: Vec3, time: number, offSpeed: Vec3, noiseFrequency: number, octaves: Vec3) { + private getNoiseMix (out: Vec2, point: Vec3, time: number, offSpeed: Vec3, noiseFrequency: number, octaves: Vec3): void { out.x = this.getNoise(point.x, point.y, point.z, time, offSpeed, noiseFrequency, octaves); out.y = this.getNoise(point.y, point.z, point.x, time, offSpeed, noiseFrequency, octaves); } @@ -229,7 +229,7 @@ export class ParticleNoise { * @en Sample pixel from noise texture. * @zh 从噪声纹理采样像素。 */ - public getNoiseParticle () { + public getNoiseParticle (): void { this.accSpeed.set(this.noiseSpeed.x * this.dt, this.noiseSpeed.y * this.dt, this.noiseSpeed.z * this.dt); const axisOffset = 1000.0; @@ -250,7 +250,7 @@ export class ParticleNoise { * @param width @en Texture width. @zh 纹理宽度。 * @param height @en Texture height. @zh 纹理高度。 */ - public getPreview (out: number[], width: number, height: number) { + public getPreview (out: number[], width: number, height: number): void { for (let h = 0; h < height; ++h) { for (let w = 0; w < width; ++w) { const sampx = (w - width * 0.5) / width + this.noiseSpeed.x * this.dt; diff --git a/cocos/particle/particle-culler.ts b/cocos/particle/particle-culler.ts index 4022dd20d6c..8132f71dbb8 100644 --- a/cocos/particle/particle-culler.ts +++ b/cocos/particle/particle-culler.ts @@ -73,12 +73,12 @@ export class ParticleCuller { this._initModuleList(); } - private _updateBoundingNode () { + private _updateBoundingNode (): void { this._nodeSize.set(this.maxPos.x - this.minPos.x, this.maxPos.y - this.minPos.y, this.maxPos.z - this.minPos.z); this._nodePos.set(this.minPos.x + this._nodeSize.x * 0.5, this.minPos.y + this._nodeSize.y * 0.5, this.minPos.z + this._nodeSize.z * 0.5); } - public setBoundingBoxSize (halfExt: Vec3) { + public setBoundingBoxSize (halfExt: Vec3): void { this.maxPos.x = this._nodePos.x + halfExt.x; this.maxPos.y = this._nodePos.y + halfExt.y; this.maxPos.z = this._nodePos.z + halfExt.z; @@ -88,7 +88,7 @@ export class ParticleCuller { this._updateBoundingNode(); } - public setBoundingBoxCenter (px: number, py: number, pz: number) { + public setBoundingBoxCenter (px: number, py: number, pz: number): void { this.maxPos.x = px + this._nodeSize.x * 0.5; this.maxPos.y = py + this._nodeSize.y * 0.5; this.maxPos.z = pz + this._nodeSize.z * 0.5; @@ -98,8 +98,8 @@ export class ParticleCuller { this._updateBoundingNode(); } - private _initModuleList () { - _anim_module.forEach((val) => { + private _initModuleList (): void { + _anim_module.forEach((val): void => { const pm = this._particleSystem[val]; if (pm && pm.enable) { if (pm.needUpdate) { @@ -122,7 +122,7 @@ export class ParticleCuller { } } - private _emit (count: number, dt: number, particleLst: Particle[]) { + private _emit (count: number, dt: number, particleLst: Particle[]): void { const ps = this._particleSystem; const node = this._node; const loopDelta = (ps.time % ps.duration) / ps.duration; // loop delta value @@ -183,7 +183,7 @@ export class ParticleCuller { } } - private _updateParticles (dt: number, particleLst: Particle[]) { + private _updateParticles (dt: number, particleLst: Particle[]): void { const ps = this._particleSystem; ps.node.getWorldMatrix(_node_mat); @@ -198,7 +198,7 @@ export class ParticleCuller { break; } - this._updateList.forEach((value: IParticleModule, key: string) => { + this._updateList.forEach((value: IParticleModule, key: string): void => { value.update(ps.simulationSpace, _node_mat); }); @@ -246,7 +246,7 @@ export class ParticleCuller { Vec3.copy(p.ultimateVelocity, p.velocity); - this._runAnimateList.forEach((value) => { + this._runAnimateList.forEach((value): void => { value.animate(p, dt); }); @@ -254,7 +254,7 @@ export class ParticleCuller { } } - private _calculateBounding (isInit: boolean) { + private _calculateBounding (isInit: boolean): void { const size: Vec3 = new Vec3(); const position: Vec3 = new Vec3(); const subPos: Vec3 = new Vec3(); @@ -292,7 +292,7 @@ export class ParticleCuller { } } - public calculatePositions () { + public calculatePositions (): void { this._emit(this._particleSystem.capacity, 0, this._particlesAll); const rand = isCurveTwoValues(this._particleSystem.startLifetime) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 0; this._updateParticles(0, this._particlesAll); @@ -302,11 +302,11 @@ export class ParticleCuller { this._updateBoundingNode(); } - public clear () { + public clear (): void { this._particlesAll.length = 0; } - public destroy () { + public destroy (): void { } } diff --git a/cocos/particle/particle-general-function.ts b/cocos/particle/particle-general-function.ts index d7c8004b5db..2da01912f18 100644 --- a/cocos/particle/particle-general-function.ts +++ b/cocos/particle/particle-general-function.ts @@ -29,7 +29,7 @@ import { Space } from './enum'; export const particleEmitZAxis = new Vec3(0, 0, -1); -export function calculateTransform (systemSpace: number, moduleSpace: number, worldTransform: Mat4, outQuat: Quat) { +export function calculateTransform (systemSpace: number, moduleSpace: number, worldTransform: Mat4, outQuat: Quat): boolean { if (moduleSpace !== systemSpace) { if (systemSpace === Space.World) { Mat4.getRotation(outQuat, worldTransform); @@ -44,18 +44,18 @@ export function calculateTransform (systemSpace: number, moduleSpace: number, wo } } -export function fixedAngleUnitVector2 (out: Vec2 | Vec3, theta: number) { +export function fixedAngleUnitVector2 (out: Vec2 | Vec3, theta: number): void { Vec2.set(out, Math.cos(theta), Math.sin(theta)); } -export function randomUnitVector2 (out: Vec2 | Vec3) { +export function randomUnitVector2 (out: Vec2 | Vec3): void { const a = randomRange(0, 2 * Math.PI); const x = Math.cos(a); const y = Math.sin(a); Vec2.set(out, x, y); } -export function randomUnitVector (out: Vec3) { +export function randomUnitVector (out: Vec3): void { const z = randomRange(-1, 1); const a = randomRange(0, 2 * Math.PI); const r = Math.sqrt(1 - z * z); @@ -64,42 +64,42 @@ export function randomUnitVector (out: Vec3) { Vec3.set(out, x, y, z); } -export function randomPointInUnitSphere (out: Vec3) { +export function randomPointInUnitSphere (out: Vec3): void { randomUnitVector(out); Vec3.multiplyScalar(out, out, random()); } -export function randomPointBetweenSphere (out: Vec3, minRadius: number, maxRadius: number) { +export function randomPointBetweenSphere (out: Vec3, minRadius: number, maxRadius: number): void { randomUnitVector(out); Vec3.multiplyScalar(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointInUnitCircle (out: Vec3) { +export function randomPointInUnitCircle (out: Vec3): void { randomUnitVector2(out); out.z = 0; Vec3.multiplyScalar(out, out, random()); } -export function randomPointBetweenCircle (out: Vec3, minRadius: number, maxRadius: number) { +export function randomPointBetweenCircle (out: Vec3, minRadius: number, maxRadius: number): void { randomUnitVector2(out); out.z = 0; Vec3.multiplyScalar(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointBetweenCircleAtFixedAngle (out: Vec3, minRadius: number, maxRadius: number, theta: number) { +export function randomPointBetweenCircleAtFixedAngle (out: Vec3, minRadius: number, maxRadius: number, theta: number): void { fixedAngleUnitVector2(out, theta); out.z = 0; Vec3.multiplyScalar(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointInCube (out: Vec3, extents: Vec3) { +export function randomPointInCube (out: Vec3, extents: Vec3): void { Vec3.set(out, randomRange(-extents.x, extents.x), randomRange(-extents.y, extents.y), randomRange(-extents.z, extents.z)); } -export function randomPointBetweenCube (out: Vec3, minBox: Vec3, maxBox: Vec3) { +export function randomPointBetweenCube (out: Vec3, minBox: Vec3, maxBox: Vec3): void { const subscript = ['x', 'y', 'z']; const edge = randomRangeInt(0, 3); for (let i = 0; i < 3; i++) { @@ -117,7 +117,7 @@ export function randomPointBetweenCube (out: Vec3, minBox: Vec3, maxBox: Vec3) { } // Fisher–Yates shuffle -export function randomSortArray (arr: any[]) { +export function randomSortArray (arr: any[]): void { for (let i = 0; i < arr.length; i++) { const transpose = i + randomRangeInt(0, arr.length - i); const val = arr[transpose]; @@ -126,7 +126,7 @@ export function randomSortArray (arr: any[]) { } } -export function randomSign () { +export function randomSign (): number { let sgn = randomRange(-1, 1); if (sgn === 0) { sgn++; diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index 67c75d698c8..c374a753227 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -80,7 +80,7 @@ export class ParticleSystem extends ModelRenderer { @range([0, Number.POSITIVE_INFINITY, 1]) @displayOrder(1) @tooltip('i18n:particle_system.capacity') - public get capacity () { + public get capacity (): number { return this._capacity; } @@ -255,7 +255,7 @@ export class ParticleSystem extends ModelRenderer { */ @displayOrder(3) @tooltip('i18n:particle_system.prewarm') - get prewarm () { + get prewarm (): boolean { return this._prewarm; } @@ -274,7 +274,7 @@ export class ParticleSystem extends ModelRenderer { @serializable @displayOrder(4) @tooltip('i18n:particle_system.simulationSpace') - get simulationSpace () { + get simulationSpace (): number { return this._simulationSpace; } @@ -367,7 +367,7 @@ export class ParticleSystem extends ModelRenderer { } } - get renderCulling () { + get renderCulling (): boolean { return this._renderCulling; } @@ -381,7 +381,7 @@ export class ParticleSystem extends ModelRenderer { @type(CullingMode) @displayOrder(17) @tooltip('i18n:particle_system.cullingMode') - get cullingMode () { + get cullingMode (): number { return this._cullingMode; } @@ -405,7 +405,7 @@ export class ParticleSystem extends ModelRenderer { @type(CCFloat) @displayOrder(17) @tooltip('i18n:particle_system.aabbHalfX') - get aabbHalfX () { + get aabbHalfX (): number { const res = this.getBoundingX(); if (res) { return res; @@ -428,7 +428,7 @@ export class ParticleSystem extends ModelRenderer { @type(CCFloat) @displayOrder(17) @tooltip('i18n:particle_system.aabbHalfY') - get aabbHalfY () { + get aabbHalfY (): number { const res = this.getBoundingY(); if (res) { return res; @@ -451,7 +451,7 @@ export class ParticleSystem extends ModelRenderer { @type(CCFloat) @displayOrder(17) @tooltip('i18n:particle_system.aabbHalfZ') - get aabbHalfZ () { + get aabbHalfZ (): number { const res = this.getBoundingZ(); if (res) { return res; @@ -473,7 +473,7 @@ export class ParticleSystem extends ModelRenderer { */ @displayOrder(28) @tooltip('i18n:particle_system.dataCulling') - get dataCulling () { + get dataCulling (): boolean { return this._dataCulling; } @@ -489,7 +489,7 @@ export class ParticleSystem extends ModelRenderer { @visible(false) @serializable @displayName('Materials') - get sharedMaterials () { + get sharedMaterials (): any { // if we don't create an array copy, the editor will modify the original array directly. // eslint-disable-next-line @typescript-eslint/no-unsafe-return return superMaterials.get!.call(this); @@ -510,7 +510,7 @@ export class ParticleSystem extends ModelRenderer { @type(ColorOverLifetimeModule) @displayOrder(23) @tooltip('i18n:particle_system.colorOverLifetimeModule') - public get colorOverLifetimeModule () { + public get colorOverLifetimeModule (): ColorOverLifetimeModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._colorOverLifetimeModule) { this._colorOverLifetimeModule = new ColorOverLifetimeModule(); @@ -535,7 +535,7 @@ export class ParticleSystem extends ModelRenderer { @type(ShapeModule) @displayOrder(17) @tooltip('i18n:particle_system.shapeModule') - public get shapeModule () { + public get shapeModule (): ShapeModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._shapeModule) { this._shapeModule = new ShapeModule(); @@ -560,7 +560,7 @@ export class ParticleSystem extends ModelRenderer { @type(SizeOvertimeModule) @displayOrder(21) @tooltip('i18n:particle_system.sizeOvertimeModule') - public get sizeOvertimeModule () { + public get sizeOvertimeModule (): SizeOvertimeModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._sizeOvertimeModule) { this._sizeOvertimeModule = new SizeOvertimeModule(); @@ -585,7 +585,7 @@ export class ParticleSystem extends ModelRenderer { @type(VelocityOvertimeModule) @displayOrder(18) @tooltip('i18n:particle_system.velocityOvertimeModule') - public get velocityOvertimeModule () { + public get velocityOvertimeModule (): VelocityOvertimeModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._velocityOvertimeModule) { this._velocityOvertimeModule = new VelocityOvertimeModule(); @@ -610,7 +610,7 @@ export class ParticleSystem extends ModelRenderer { @type(ForceOvertimeModule) @displayOrder(19) @tooltip('i18n:particle_system.forceOvertimeModule') - public get forceOvertimeModule () { + public get forceOvertimeModule (): ForceOvertimeModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._forceOvertimeModule) { this._forceOvertimeModule = new ForceOvertimeModule(); @@ -636,7 +636,7 @@ export class ParticleSystem extends ModelRenderer { @type(LimitVelocityOvertimeModule) @displayOrder(20) @tooltip('i18n:particle_system.limitVelocityOvertimeModule') - public get limitVelocityOvertimeModule () { + public get limitVelocityOvertimeModule (): LimitVelocityOvertimeModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._limitVelocityOvertimeModule) { this._limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); @@ -661,7 +661,7 @@ export class ParticleSystem extends ModelRenderer { @type(RotationOvertimeModule) @displayOrder(22) @tooltip('i18n:particle_system.rotationOvertimeModule') - public get rotationOvertimeModule () { + public get rotationOvertimeModule (): RotationOvertimeModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._rotationOvertimeModule) { this._rotationOvertimeModule = new RotationOvertimeModule(); @@ -686,7 +686,7 @@ export class ParticleSystem extends ModelRenderer { @type(TextureAnimationModule) @displayOrder(24) @tooltip('i18n:particle_system.textureAnimationModule') - public get textureAnimationModule () { + public get textureAnimationModule (): TextureAnimationModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._textureAnimationModule) { this._textureAnimationModule = new TextureAnimationModule(); @@ -715,7 +715,7 @@ export class ParticleSystem extends ModelRenderer { @type(NoiseModule) @displayOrder(24) @tooltip('i18n:particle_system.noiseModule') - public get noiseModule () { + public get noiseModule (): NoiseModule | null { if (EDITOR) { if (!this._noiseModule) { this._noiseModule = new NoiseModule(); @@ -740,7 +740,7 @@ export class ParticleSystem extends ModelRenderer { @type(TrailModule) @displayOrder(25) @tooltip('i18n:particle_system.trailModule') - public get trailModule () { + public get trailModule (): TrailModule | null { if (EDITOR_NOT_IN_PREVIEW) { if (!this._trailModule) { this._trailModule = new TrailModule(); @@ -846,11 +846,11 @@ export class ParticleSystem extends ModelRenderer { this._subEmitters = []; // array of { emitter: ParticleSystem, type: 'birth', 'collision' or 'death'} } - public onFocusInEditor () { + public onFocusInEditor (): void { this.renderer.create(this); } - public onLoad () { + public onLoad (): void { // HACK, TODO this.renderer.onInit(this); if (this._shapeModule) this._shapeModule.onInit(this); @@ -866,7 +866,7 @@ export class ParticleSystem extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onMaterialModified (index: number, material: Material) { + public _onMaterialModified (index: number, material: Material): void { if (this.processor !== null) { this.processor.onMaterialModified(index, material); } @@ -875,7 +875,7 @@ export class ParticleSystem extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onRebuildPSO (index: number, material: Material) { + public _onRebuildPSO (index: number, material: Material): void { this.processor.onRebuildPSO(index, material); } @@ -891,7 +891,7 @@ export class ParticleSystem extends ModelRenderer { return this._models; } - protected _attachToScene () { + protected _attachToScene (): void { this.processor.attachToScene(); if (this._trailModule && this._trailModule.enable) { this._trailModule._attachToScene(); @@ -901,7 +901,7 @@ export class ParticleSystem extends ModelRenderer { /** * @engineInternal */ - public _detachFromScene () { + public _detachFromScene (): void { this.processor.detachFromScene(); if (this._trailModule && this._trailModule.enable) { this._trailModule._detachFromScene(); @@ -920,7 +920,7 @@ export class ParticleSystem extends ModelRenderer { * @en Bind module to particle processor. * @zh 把模块绑定到粒子更新函数上。 */ - private bindModule () { + private bindModule (): void { if (this._colorOverLifetimeModule) this._colorOverLifetimeModule.bindTarget(this.processor); if (this._sizeOvertimeModule) this._sizeOvertimeModule.bindTarget(this.processor); if (this._rotationOvertimeModule) this._rotationOvertimeModule.bindTarget(this.processor); @@ -940,7 +940,7 @@ export class ParticleSystem extends ModelRenderer { * @en Play particle system. * @zh 播放粒子效果。 */ - public play () { + public play (): void { if (this._needToRestart) { this.reset(); this._needToRestart = false; @@ -979,7 +979,7 @@ export class ParticleSystem extends ModelRenderer { * @en Pause particle system. * @zh 暂停播放粒子效果。 */ - public pause () { + public pause (): void { if (this._isStopped) { console.warn('pause(): particle system is already stopped.'); return; @@ -995,7 +995,7 @@ export class ParticleSystem extends ModelRenderer { * @zh 停止发射粒子。 * @en Stop emitting particles. */ - public stopEmitting () { + public stopEmitting (): void { this._isEmitting = false; this._needToRestart = true; } @@ -1004,7 +1004,7 @@ export class ParticleSystem extends ModelRenderer { * @en Stop particle system. * @zh 停止播放粒子。 */ - public stop () { + public stop (): void { if (this._isPlaying || this._isPaused) { this.clear(); } @@ -1026,7 +1026,7 @@ export class ParticleSystem extends ModelRenderer { this.reset(); } - private reset () { + private reset (): void { this._time = 0.0; this._emitRateTimeCounter = 0.0; this._emitRateDistanceCounter = 0.0; @@ -1041,7 +1041,7 @@ export class ParticleSystem extends ModelRenderer { * @en remove all particles from current particle system. * @zh 将所有粒子从粒子系统中清除。 */ - public clear () { + public clear (): void { if (this.enabledInHierarchy) { this.processor.clear(); if (this._trailModule) this._trailModule.clear(); @@ -1053,7 +1053,7 @@ export class ParticleSystem extends ModelRenderer { * @en Get current particle capacity. * @zh 获取当前粒子数量。 */ - public getParticleCount () { + public getParticleCount (): number { if (this.processor) { return this.processor.getParticleCount(); } else { @@ -1064,18 +1064,18 @@ export class ParticleSystem extends ModelRenderer { /** * @ignore */ - public setCustomData1 (x, y) { + public setCustomData1 (x, y): void { Vec2.set(this._customData1, x, y); } /** * @ignore */ - public setCustomData2 (x, y) { + public setCustomData2 (x, y): void { Vec2.set(this._customData2, x, y); } - protected onDestroy () { + protected onDestroy (): void { this.stop(); if (this.processor.getModel()?.scene) { this.processor.detachFromScene(); @@ -1094,7 +1094,7 @@ export class ParticleSystem extends ModelRenderer { } } - protected onEnable () { + protected onEnable (): void { super.onEnable(); cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); if (this.playOnAwake && !EDITOR_NOT_IN_PREVIEW) { @@ -1103,7 +1103,7 @@ export class ParticleSystem extends ModelRenderer { this.processor.onEnable(); if (this._trailModule) this._trailModule.onEnable(); } - protected onDisable () { + protected onDisable (): void { cclegacy.director.off(cclegacy.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); this.processor.onDisable(); if (this._trailModule) this._trailModule.onDisable(); @@ -1117,7 +1117,7 @@ export class ParticleSystem extends ModelRenderer { } } - private _calculateBounding (forceRefresh: boolean) { + private _calculateBounding (forceRefresh: boolean): void { if (this._boundingBox) { if (!this._culler) { this._culler = new ParticleCuller(this); @@ -1151,7 +1151,7 @@ export class ParticleSystem extends ModelRenderer { } } - protected update (dt: number) { + protected update (dt: number): void { const scaledDeltaTime = dt * this.simulationSpeed; if (!this.renderCulling) { @@ -1286,7 +1286,7 @@ export class ParticleSystem extends ModelRenderer { } } - protected beforeRender () { + protected beforeRender (): void { if (this.getParticleCount() <= 0) { if (this.processor.getModel()?.scene) { this.processor.detachFromScene(); @@ -1311,13 +1311,13 @@ export class ParticleSystem extends ModelRenderer { } } - protected _onVisibilityChange (val) { + protected _onVisibilityChange (val): void { if (this.processor.model) { this.processor.model.visFlags = val; } } - private emit (count: number, dt: number) { + private emit (count: number, dt: number): void { const loopDelta = (this._time % this.duration) / this.duration; // loop delta value // refresh particle node position to update emit position @@ -1399,7 +1399,7 @@ export class ParticleSystem extends ModelRenderer { } // initialize particle system as though it had already completed a full cycle. - private _prewarmSystem () { + private _prewarmSystem (): void { this.startDelay.mode = Mode.Constant; // clear startDelay. this.startDelay.constant = 0; const dt = 1.0; // should use varying value? @@ -1413,7 +1413,7 @@ export class ParticleSystem extends ModelRenderer { } // internal function - private _emit (dt) { + private _emit (dt): void { // emit particles. const startDelay = this.startDelay.evaluate(0, 1)!; if (this._time > startDelay) { @@ -1458,40 +1458,40 @@ export class ParticleSystem extends ModelRenderer { } } - private _resetPosition () { + private _resetPosition (): void { this.node.getWorldPosition(this._oldWPos); Vec3.copy(this._curWPos, this._oldWPos); } - private addSubEmitter (subEmitter) { + private addSubEmitter (subEmitter): void { this._subEmitters.push(subEmitter); } - private removeSubEmitter (idx) { + private removeSubEmitter (idx): void { this._subEmitters.splice(this._subEmitters.indexOf(idx), 1); } - private addBurst (burst) { + private addBurst (burst): void { this.bursts.push(burst); } - private removeBurst (idx) { + private removeBurst (idx): void { this.bursts.splice(this.bursts.indexOf(idx), 1); } - private getBoundingX () { + private getBoundingX (): number { return this._aabbHalfX; } - private getBoundingY () { + private getBoundingY (): number { return this._aabbHalfY; } - private getBoundingZ () { + private getBoundingZ (): number { return this._aabbHalfZ; } - private setBoundingX (value: number) { + private setBoundingX (value: number): void { if (this._boundingBox && this._culler) { this._boundingBox.halfExtents.x = value; this._culler.setBoundingBoxSize(this._boundingBox.halfExtents); @@ -1499,7 +1499,7 @@ export class ParticleSystem extends ModelRenderer { } } - private setBoundingY (value: number) { + private setBoundingY (value: number): void { if (this._boundingBox && this._culler) { this._boundingBox.halfExtents.y = value; this._culler.setBoundingBoxSize(this._boundingBox.halfExtents); @@ -1507,7 +1507,7 @@ export class ParticleSystem extends ModelRenderer { } } - private setBoundingZ (value: number) { + private setBoundingZ (value: number): void { if (this._boundingBox && this._culler) { this._boundingBox.halfExtents.z = value; this._culler.setBoundingBoxSize(this._boundingBox.halfExtents); @@ -1518,7 +1518,7 @@ export class ParticleSystem extends ModelRenderer { /** * @ignore */ - get isPlaying () { + get isPlaying (): boolean { return this._isPlaying; } @@ -1526,7 +1526,7 @@ export class ParticleSystem extends ModelRenderer { * @en Query particle system is paused or not. * @zh 获取粒子系统当前是否已经暂停运行。 */ - get isPaused () { + get isPaused (): boolean { return this._isPaused; } @@ -1534,7 +1534,7 @@ export class ParticleSystem extends ModelRenderer { * @en Query particle system is stopped or not. * @zh 获取粒子系统当前是否已经停止。 */ - get isStopped () { + get isStopped (): boolean { return this._isStopped; } @@ -1542,7 +1542,7 @@ export class ParticleSystem extends ModelRenderer { * @en Query particle system is emitting or not. * @zh 获取粒子系统当前是否还在发射。 */ - get isEmitting () { + get isEmitting (): boolean { return this._isEmitting; } @@ -1550,16 +1550,16 @@ export class ParticleSystem extends ModelRenderer { * @en Query particle system simulation time. * @zh 获取粒子系统运行时间。 */ - get time () { + get time (): number { return this._time; } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBeforeSerialize (props) { + public _onBeforeSerialize (props): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return this.dataCulling ? props.filter((p) => !PARTICLE_MODULE_PROPERTY.includes(p) || (this[p] && this[p].enable)) : props; + return this.dataCulling ? props.filter((p): any => !PARTICLE_MODULE_PROPERTY.includes(p) || (this[p] && this[p].enable)) : props; } /** diff --git a/cocos/particle/particle-utils.ts b/cocos/particle/particle-utils.ts index e2781a74b94..195982550b4 100644 --- a/cocos/particle/particle-utils.ts +++ b/cocos/particle/particle-utils.ts @@ -39,14 +39,14 @@ export class ParticleUtils { * @en Instantiate particle system from prefab. * @zh 从 prefab 实例化粒子系统。 */ - public static instantiate (prefab) { + public static instantiate (prefab): CCObject { if (!this.registeredSceneEvent) { director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.onSceneUnload, this); this.registeredSceneEvent = true; } if (!this.particleSystemPool.has(prefab._uuid)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return - this.particleSystemPool.set(prefab._uuid, new Pool(() => instantiate(prefab) || new Node(), 1, (prefab) => prefab.destroy())); + this.particleSystemPool.set(prefab._uuid, new Pool((): any => instantiate(prefab) || new Node(), 1, (prefab): boolean => prefab.destroy())); } return this.particleSystemPool.get(prefab._uuid)!.alloc(); } @@ -56,7 +56,7 @@ export class ParticleUtils { * @zh 销毁创建出来的粒子系统prefab。 * @param prefab @en Particle system prefab to destroy. @zh 要销毁的粒子系统prefab。 */ - public static destroy (prefab) { + public static destroy (prefab): void { if (this.particleSystemPool.has(prefab._prefab.asset._uuid)) { this.stop(prefab); this.particleSystemPool.get(prefab._prefab.asset._uuid)!.free(prefab); @@ -68,7 +68,7 @@ export class ParticleUtils { * @zh 播放粒子系统。 * @param rootNode @en Root node contains the particle system. @zh 包含粒子系统的根节点。 */ - public static play (rootNode: Node) { + public static play (rootNode: Node): void { for (const ps of rootNode.getComponentsInChildren(ParticleSystem)) { (ps).play(); } @@ -79,7 +79,7 @@ export class ParticleUtils { * @zh 停止播放粒子系统。 * @param rootNode @en Root node contains the particle system. @zh 包含粒子系统的根节点。 */ - public static stop (rootNode: Node) { + public static stop (rootNode: Node): void { for (const ps of rootNode.getComponentsInChildren(ParticleSystem)) { (ps).stop(); } @@ -88,8 +88,8 @@ export class ParticleUtils { private static particleSystemPool: Map> = new Map>(); private static registeredSceneEvent = false; - private static onSceneUnload () { - this.particleSystemPool.forEach((value) => value.destroy()); + private static onSceneUnload (): void { + this.particleSystemPool.forEach((value): void => value.destroy()); this.particleSystemPool.clear(); } } diff --git a/cocos/particle/particle.ts b/cocos/particle/particle.ts index 0a3e6b9f04c..713443f378f 100644 --- a/cocos/particle/particle.ts +++ b/cocos/particle/particle.ts @@ -90,7 +90,7 @@ export class Particle { this.startRow = 0; } - public reset () { + public reset (): void { this.rotation.set(0, 0, 0); this.startEuler.set(0, 0, 0); this.startRotation.set(0, 0, 0, 1); @@ -151,11 +151,11 @@ export abstract class ParticleModuleBase implements IParticleModule { public needUpdate = false; public needAnimate = true; - public bindTarget (target: ParticleSystemRendererBase) { + public bindTarget (target: ParticleSystemRendererBase): void { this.target = target; } - public update (space: number, trans: Mat4) {} + public update (space: number, trans: Mat4): void {} public abstract name: string; public abstract animate (p: Particle, dt?: number): void; } diff --git a/cocos/particle/renderer/particle-system-renderer-base.ts b/cocos/particle/renderer/particle-system-renderer-base.ts index fe7351fc216..d8e287843b4 100644 --- a/cocos/particle/renderer/particle-system-renderer-base.ts +++ b/cocos/particle/renderer/particle-system-renderer-base.ts @@ -37,7 +37,7 @@ export abstract class ParticleSystemRendererBase { /** * @engineInternal */ - public get model () { + public get model (): ParticleBatchModel | null { return this._model; } protected _model: ParticleBatchModel | null = null; @@ -58,15 +58,15 @@ export abstract class ParticleSystemRendererBase { return this._useInstance; } - public getInfo () { + public getInfo (): ParticleSystemRenderer { return this._renderInfo!; } - public onInit (ps: Component) { + public onInit (ps: Component): void { this._particleSystem = ps; } - public onEnable () { + public onEnable (): void { if (!this._particleSystem) { return; } @@ -77,18 +77,18 @@ export abstract class ParticleSystemRendererBase { } } - public onDisable () { + public onDisable (): void { this.detachFromScene(); } - public onDestroy () { + public onDestroy (): void { if (this._model) { cclegacy.director.root.destroyModel(this._model); this._model = null; } } - public attachToScene () { + public attachToScene (): void { if (this._model) { if (this._model.scene) { this.detachFromScene(); @@ -97,28 +97,28 @@ export abstract class ParticleSystemRendererBase { } } - public detachFromScene () { + public detachFromScene (): void { if (this._model && this._model.scene) { this._model.scene.removeModel(this._model); } } - public setVertexAttributes () { + public setVertexAttributes (): void { if (this._model) { this.updateVertexAttrib(); this._model.setVertexAttributes(this._renderInfo!.renderMode === RenderMode.Mesh ? this._renderInfo!.mesh : null, this._vertAttrs); } } - public clear () { + public clear (): void { if (this._model) this._model.enabled = false; } - public getModel () { + public getModel (): ParticleBatchModel | null { return this._model; } - protected _initModel () { + protected _initModel (): void { if (!this._model) { this._model = cclegacy.director.root.createModel(ParticleBatchModel); this._model!.setCapacity(this._particleSystem.capacity); @@ -126,8 +126,8 @@ export abstract class ParticleSystemRendererBase { } } - public updateTrailMaterial () {} - public getDefaultTrailMaterial () { return null; } + public updateTrailMaterial (): void {} + public getDefaultTrailMaterial (): null { return null; } public abstract getParticleCount () : number; public abstract getFreeParticle (): Particle | null; public abstract onMaterialModified (index: number, material: Material) : void; diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index 68f99a8231a..677758a9c69 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -180,10 +180,10 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas }; } - public onInit (ps: Component) { + public onInit (ps: Component): void { super.onInit(ps); - this._particles = new RecyclePool(() => new Particle(this), 16); + this._particles = new RecyclePool((): Particle => new Particle(this), 16); this._setVertexAttrib(); this._setFillFunc(); this._initModuleList(); @@ -194,7 +194,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._inited = true; } - public clear () { + public clear (): void { super.clear(); this._particles!.reset(); if (this._particleSystem._trailModule) { @@ -204,7 +204,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._model!.enabled = false; } - public updateRenderMode () { + public updateRenderMode (): void { this._setVertexAttrib(); this._setFillFunc(); this.updateMaterialParams(); @@ -227,11 +227,11 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas return this._defaultTrailMat; } - public setNewParticle (p: Particle) { + public setNewParticle (p: Particle): void { } - private _initModuleList () { - _anim_module.forEach((val) => { + private _initModuleList (): void { + _anim_module.forEach((val): void => { const pm = this._particleSystem[val]; if (pm && pm.enable) { if (pm.needUpdate) { @@ -254,7 +254,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - public enableModule (name: string, val: boolean, pm: IParticleModule) { + public enableModule (name: string, val: boolean, pm: IParticleModule): void { if (val) { if (pm.needUpdate) { this._updateList[pm.name] = pm; @@ -279,7 +279,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this.updateMaterialParams(); } - public updateAlignSpace (space) { + public updateAlignSpace (space): void { this._alignSpace = space; } @@ -287,13 +287,13 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas return this._defaultMat; } - public updateRotation (pass: Pass | null) { + public updateRotation (pass: Pass | null): void { if (pass) { this.doUpdateRotation(pass); } } - private doUpdateRotation (pass) { + private doUpdateRotation (pass): void { const mode = this._renderInfo!.renderMode; if (mode !== RenderMode.Mesh && this._alignSpace === AlignmentSpace.View) { return; @@ -324,13 +324,13 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas pass.setUniform(this._uNodeRotHandle, _node_rot); } - public updateScale (pass: Pass | null) { + public updateScale (pass: Pass | null): void { if (pass) { this.doUpdateScale(pass); } } - private doUpdateScale (pass) { + private doUpdateScale (pass): void { switch (this._particleSystem.scaleSpace) { case Space.Local: this._particleSystem.node.getScale(this._node_scale); @@ -346,7 +346,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private noise: ParticleNoise = new ParticleNoise(); - public updateParticles (dt: number) { + public updateParticles (dt: number): number { const ps = this._particleSystem; if (!ps) { return this._particles!.length; @@ -357,7 +357,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this.doUpdateScale(pass); this.doUpdateRotation(pass); - this._updateList.forEach((value: IParticleModule, key: string) => { + this._updateList.forEach((value: IParticleModule, key: string): void => { value.update(ps._simulationSpace, _tempWorldTrans); }); @@ -423,7 +423,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } Vec3.copy(p.ultimateVelocity, p.velocity); - this._runAnimateList.forEach((value) => { + this._runAnimateList.forEach((value): void => { value.animate(p, dt); }); @@ -437,8 +437,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas return this._particles!.length; } - public getNoisePreview (out: number[], width: number, height: number) { - this._runAnimateList.forEach((value) => { + public getNoisePreview (out: number[], width: number, height: number): void { + this._runAnimateList.forEach((value): void => { if (value.name === PARTICLE_MODULE_NAME.NOISE) { const m = value as NoiseModule; m.getNoisePreview(out, this._particleSystem, width, height); @@ -447,7 +447,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } // internal function - public updateRenderData () { + public updateRenderData (): void { // update vertex buffer let idx = 0; for (let i = 0; i < this._particles!.length; ++i) { @@ -462,7 +462,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - public beforeRender () { + public beforeRender (): void { // because we use index buffer, per particle index count = 6. this._model!.updateIA(this._particles!.length); } @@ -471,7 +471,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas return this._particles!.length; } - public onMaterialModified (index: number, material: Material) { + public onMaterialModified (index: number, material: Material): void { if (!this._inited) { return; } @@ -483,7 +483,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - public onRebuildPSO (index: number, material: Material) { + public onRebuildPSO (index: number, material: Material): void { if (this._model && index === 0) { this._model.setSubModelMaterial(0, material); } @@ -493,7 +493,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - private _setFillFunc () { + private _setFillFunc (): void { if (this._renderInfo!.renderMode === RenderMode.Mesh) { this._fillDataFunc = this._fillMeshData; } else if (this._renderInfo!.renderMode === RenderMode.StrecthedBillboard) { @@ -503,7 +503,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - private _fillMeshData (p: Particle, idx: number, fi: number) { + private _fillMeshData (p: Particle, idx: number, fi: number): void { const i = idx / 4; this._attrs[0] = p.position; _tempAttribUV.z = fi; @@ -514,7 +514,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._model!.addParticleVertexData(i, this._attrs); } - private _fillStrecthedData (p: Particle, idx: number, fi: number) { + private _fillStrecthedData (p: Particle, idx: number, fi: number): void { if (!this._useInstance) { for (let j = 0; j < 4; ++j) { // four verts per particle. this._attrs[0] = p.position; @@ -534,7 +534,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - private _fillStrecthedDataIns (p: Particle, idx: number, fi: number) { + private _fillStrecthedDataIns (p: Particle, idx: number, fi: number): void { const i = idx / 4; this._attrs[0] = p.position; _tempAttribUV.z = fi; @@ -546,7 +546,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._model!.addParticleVertexData(i, this._attrs); } - private _fillNormalData (p: Particle, idx: number, fi: number) { + private _fillNormalData (p: Particle, idx: number, fi: number): void { if (!this._useInstance) { for (let j = 0; j < 4; ++j) { // four verts per particle. this._attrs[0] = p.position; @@ -565,7 +565,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - private _fillNormalDataIns (p: Particle, idx: number, fi: number) { + private _fillNormalDataIns (p: Particle, idx: number, fi: number): void { const i = idx / 4; this._attrs[0] = p.position; _tempAttribUV.z = fi; @@ -577,7 +577,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._model!.addParticleVertexData(i, this._attrs); } - public updateVertexAttrib () { + public updateVertexAttrib (): void { if (this._renderInfo!.renderMode !== RenderMode.Mesh) { return; } @@ -599,7 +599,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - private _setVertexAttrib () { + private _setVertexAttrib (): void { if (!this._useInstance) { switch (this._renderInfo!.renderMode) { case RenderMode.StrecthedBillboard: @@ -616,7 +616,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - private _setVertexAttribIns () { + private _setVertexAttribIns (): void { switch (this._renderInfo!.renderMode) { case RenderMode.StrecthedBillboard: this._vertAttrs = _vertex_attrs_stretch_ins.slice(); @@ -629,7 +629,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - public updateMaterialParams () { + public updateMaterialParams (): void { if (!this._particleSystem) { return; } @@ -703,7 +703,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - public updateTrailMaterial () { + public updateTrailMaterial (): void { if (!this._particleSystem) { return; } @@ -731,7 +731,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - public setUseInstance (value: boolean) { + public setUseInstance (value: boolean): void { if (this._useInstance === value) { return; } diff --git a/cocos/particle/renderer/particle-system-renderer-data.ts b/cocos/particle/renderer/particle-system-renderer-data.ts index 54644d00900..5f3ca4e0b29 100644 --- a/cocos/particle/renderer/particle-system-renderer-data.ts +++ b/cocos/particle/renderer/particle-system-renderer-data.ts @@ -32,7 +32,7 @@ import { director } from '../../game/director'; import { Device, Format, FormatFeatureBit } from '../../gfx'; import { errorID, warnID, cclegacy } from '../../core'; -function isSupportGPUParticle () { +function isSupportGPUParticle (): boolean { const device: Device = director.root!.device; if (device.capabilities.maxVertexTextureUnits >= 8 && (device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE))) { @@ -51,7 +51,7 @@ export default class ParticleSystemRenderer { @type(RenderMode) @displayOrder(0) @tooltip('i18n:particleSystemRenderer.renderMode') - public get renderMode () { + public get renderMode (): number { return this._renderMode; } @@ -70,7 +70,7 @@ export default class ParticleSystemRenderer { */ @displayOrder(1) @tooltip('i18n:particleSystemRenderer.velocityScale') - public get velocityScale () { + public get velocityScale (): number { return this._velocityScale; } @@ -87,7 +87,7 @@ export default class ParticleSystemRenderer { */ @displayOrder(2) @tooltip('i18n:particleSystemRenderer.lengthScale') - public get lengthScale () { + public get lengthScale (): number { return this._lengthScale; } @@ -118,7 +118,7 @@ export default class ParticleSystemRenderer { @type(Mesh) @displayOrder(7) @tooltip('i18n:particleSystemRenderer.mesh') - public get mesh () { + public get mesh (): Mesh | null { return this._mesh; } @@ -137,7 +137,7 @@ export default class ParticleSystemRenderer { @disallowAnimation @visible(false) @tooltip('i18n:particleSystemRenderer.particleMaterial') - public get particleMaterial () { + public get particleMaterial (): Material | null { if (!this._particleSystem) { return null; } @@ -158,7 +158,7 @@ export default class ParticleSystemRenderer { @displayOrder(8) @disallowAnimation @visible(function (this: ParticleSystemRenderer): boolean { return !this._useGPU; }) - public get cpuMaterial () { + public get cpuMaterial (): Material | null { return this._cpuMaterial; } @@ -187,7 +187,7 @@ export default class ParticleSystemRenderer { @displayOrder(8) @disallowAnimation @visible(function (this: ParticleSystemRenderer): boolean { return this._useGPU; }) - public get gpuMaterial () { + public get gpuMaterial (): Material | null { return this._gpuMaterial; } @@ -217,7 +217,7 @@ export default class ParticleSystemRenderer { @disallowAnimation @visible(function (this: ParticleSystemRenderer): boolean { return !this._useGPU; }) @tooltip('i18n:particleSystemRenderer.trailMaterial') - public get trailMaterial () { + public get trailMaterial (): Material | null { if (!this._particleSystem) { return null; } @@ -233,7 +233,7 @@ export default class ParticleSystemRenderer { @serializable private _mainTexture: Texture2D | null = null; - public get mainTexture () { + public get mainTexture (): Texture2D | null { return this._mainTexture; } @@ -246,7 +246,7 @@ export default class ParticleSystemRenderer { @displayOrder(10) @tooltip('i18n:particleSystemRenderer.useGPU') - public get useGPU () { + public get useGPU (): boolean { return this._useGPU; } @@ -271,7 +271,7 @@ export default class ParticleSystemRenderer { @type(AlignmentSpace) @displayOrder(10) @tooltip('i18n:particle_system.alignSpace') - public get alignSpace () { + public get alignSpace (): number { return this._alignSpace; } @@ -287,7 +287,7 @@ export default class ParticleSystemRenderer { private _particleSystem: any = null!; // ParticleSystem - create (ps) { + create (ps): void { // if particle system is null we run the old routine // else if particle system is not null we do nothing if (this._particleSystem === null) { @@ -297,7 +297,7 @@ export default class ParticleSystemRenderer { } } - onInit (ps) { + onInit (ps): void { this.create(ps); const useGPU = this._useGPU && isSupportGPUParticle(); if (!this._particleSystem.processor) { @@ -318,7 +318,7 @@ export default class ParticleSystemRenderer { } } - private _switchProcessor () { + private _switchProcessor (): void { if (!this._particleSystem) { return; } diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index e07ea885b59..894fc246ab8 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -176,7 +176,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._particleNum = 0; } - public onInit (ps: Component) { + public onInit (ps: Component): void { super.onInit(ps); this._setVertexAttrib(); this._initModel(); @@ -185,24 +185,24 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._inited = true; } - public updateRenderMode () { + public updateRenderMode (): void { this._setVertexAttrib(); this.updateMaterialParams(); this.setVertexAttributes(); } - public setVertexAttributes () { + public setVertexAttributes (): void { super.setVertexAttributes(); this._model!.constructAttributeIndex(); } - public clear () { + public clear (): void { super.clear(); this._particleNum = 0; this.updateRenderData(); } - public onDestroy () { + public onDestroy (): void { super.onDestroy(); if (this._forceTexture) this._forceTexture.destroy(); if (this._velocityTexture) this._velocityTexture.destroy(); @@ -218,7 +218,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._animData = null; } - public enableModule (name: string, val: boolean, pm: IParticleModule) { + public enableModule (name: string, val: boolean, pm: IParticleModule): void { const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat; if (!mat) { return; @@ -238,7 +238,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas return this._tempParticle; } - public setNewParticle (p: Particle) { + public setNewParticle (p: Particle): void { this._model!.addGPUParticleVertexData(p, this._particleNum, this._particleSystem._time); this._particleNum++; } @@ -247,13 +247,13 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas return this._defaultMat; } - public updateRotation (pass: Pass | null) { + public updateRotation (pass: Pass | null): void { if (pass) { this.doUpdateRotation(pass); } } - private doUpdateRotation (pass) { + private doUpdateRotation (pass): void { const mode = this._renderInfo!.renderMode; if (mode !== RenderMode.Mesh && this._alignSpace === AlignmentSpace.View) { return; @@ -284,13 +284,13 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas pass.setUniform(this._uNodeRotHandle, _node_rot); } - public updateScale (pass: Pass | null) { + public updateScale (pass: Pass | null): void { if (pass) { this.doUpdateScale(pass); } } - private doUpdateScale (pass) { + private doUpdateScale (pass): void { switch (this._particleSystem.scaleSpace) { case Space.Local: this._particleSystem.node.getScale(this._node_scale); @@ -304,7 +304,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas pass.setUniform(pass.getHandle('scale'), this._node_scale); } - public updateParticles (dt: number) { + public updateParticles (dt: number): number { if (EDITOR_NOT_IN_PREVIEW) { const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat; @@ -329,19 +329,19 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // internal function - public updateRenderData () { + public updateRenderData (): void { } - public beforeRender () { + public beforeRender (): void { // update vertex buffer this._model!.updateIA(this._particleNum); } - public updateAlignSpace (space) { + public updateAlignSpace (space): void { this._alignSpace = space; } - public updateShaderUniform (dt: number) { + public updateShaderUniform (dt: number): void { const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat; if (!mat) { return; @@ -358,7 +358,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this.doUpdateRotation(pass); } - public initShaderUniform (mat: Material) { + public initShaderUniform (mat: Material): void { const pass = mat.passes[0]; this._uTimeHandle = pass.getHandle('u_timeDelta'); @@ -500,20 +500,20 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas return this._particleNum; } - public onMaterialModified (index: number, material: Material) { + public onMaterialModified (index: number, material: Material): void { if (!this._inited) { return; } this.updateMaterialParams(); } - public onRebuildPSO (index: number, material: Material) { + public onRebuildPSO (index: number, material: Material): void { if (this._model && index === 0) { this._model.setSubModelMaterial(0, material); } } - public updateVertexAttrib () { + public updateVertexAttrib (): void { if (this._renderInfo!.renderMode !== RenderMode.Mesh) { return; } @@ -535,7 +535,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } } - private _setVertexAttrib () { + private _setVertexAttrib (): void { if (!this._useInstance) { switch (this._renderInfo!.renderMode) { case RenderMode.StrecthedBillboard: @@ -552,7 +552,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } } - private _setVertexAttribIns () { + private _setVertexAttribIns (): void { switch (this._renderInfo!.renderMode) { case RenderMode.StrecthedBillboard: this._vertAttrs = _gpu_vert_attr_ins.slice(); @@ -565,7 +565,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } } - public updateMaterialParams () { + public updateMaterialParams (): void { if (!this._particleSystem) { return; } @@ -632,7 +632,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } } - public setUseInstance (value: boolean) { + public setUseInstance (value: boolean): void { if (this._useInstance === value) { return; } @@ -644,7 +644,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this.updateRenderMode(); } - public getNoisePreview (out: number[], width: number, height: number) { + public getNoisePreview (out: number[], width: number, height: number): void { } } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index dfd600592de..3dad5a3d748 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -81,7 +81,7 @@ class TrailSegment { } } - public getElement (idx: number) { + public getElement (idx: number): ITrailElement | null { if (this.start === -1) { return null; } @@ -121,7 +121,7 @@ class TrailSegment { } // eslint-disable-next-line max-len - public iterateElement (target: TrailModule, f: (target: TrailModule, e: ITrailElement, p: Particle, dt: number) => boolean, p: Particle, dt: number) { + public iterateElement (target: TrailModule, f: (target: TrailModule, e: ITrailElement, p: Particle, dt: number) => boolean, p: Particle, dt: number): void { const end = this.start >= this.end ? this.end + this.trailElements.length : this.end; for (let i = this.start; i < end; i++) { if (f(target, this.trailElements[i % this.trailElements.length], p, dt)) { @@ -135,7 +135,7 @@ class TrailSegment { } } - public count () { + public count (): number { if (this.start < this.end) { return this.end - this.start; } else { @@ -143,7 +143,7 @@ class TrailSegment { } } - public clear () { + public clear (): void { this.start = -1; this.end = -1; } @@ -166,7 +166,7 @@ export default class TrailModule { * 是否启用。 */ @displayOrder(0) - public get enable () { + public get enable (): boolean { return this._enable; } @@ -227,7 +227,7 @@ export default class TrailModule { */ @displayOrder(5) @tooltip('i18n:trailSegment.minParticleDistance') - public get minParticleDistance () { + public get minParticleDistance (): number { return this._minParticleDistance; } @@ -239,7 +239,7 @@ export default class TrailModule { @type(Space) @displayOrder(6) @tooltip('i18n:trailSegment.space') - public get space () { + public get space (): number { return this._space; } @@ -303,7 +303,7 @@ export default class TrailModule { * @zh 获取拖尾模型 * @return Model of this trail and type is scene.Model */ - public getModel () { + public getModel (): scene.Model | null { return this._trailModel; } @@ -338,7 +338,7 @@ export default class TrailModule { /** * @engineInternal */ - public get inited () { + public get inited (): boolean { return this._inited; } private _inited: boolean; @@ -361,7 +361,7 @@ export default class TrailModule { this._inited = false; } - public onInit (ps) { + public onInit (ps): void { this._particleSystem = ps; this.minParticleDistance = this._minParticleDistance; let burstCount = 0; @@ -376,18 +376,18 @@ export default class TrailModule { warnID(6036); } this._trailNum = Math.ceil(psTime * Math.ceil(this.lifeTime.getMax()) * 60 * (psRate * duration + burstCount)); - this._trailSegments = new Pool(() => new TrailSegment(10), Math.ceil(psRate * duration), (obj: TrailSegment) => obj.trailElements.length = 0); + this._trailSegments = new Pool((): TrailSegment => new TrailSegment(10), Math.ceil(psRate * duration), (obj: TrailSegment): number => obj.trailElements.length = 0); if (this._enable) { this.enable = this._enable; } this._inited = true; } - public onEnable () { + public onEnable (): void { this._attachToScene(); } - public onDisable () { + public onDisable (): void { this._particleTrail.clear(); this._detachFromScene(); } @@ -395,7 +395,7 @@ export default class TrailModule { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _attachToScene () { + public _attachToScene (): void { if (this._trailModel) { if (this._trailModel.scene) { this._detachFromScene(); @@ -407,13 +407,13 @@ export default class TrailModule { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _detachFromScene () { + public _detachFromScene (): void { if (this._trailModel && this._trailModel.scene) { this._trailModel.scene.removeModel(this._trailModel); } } - public destroy () { + public destroy (): void { this.destroySubMeshData(); if (this._trailModel) { director.root!.destroyModel(this._trailModel); @@ -425,13 +425,13 @@ export default class TrailModule { } } - public play () { + public play (): void { if (this._trailModel && this._enable) { this._trailModel.enabled = true; } } - public clear () { + public clear (): void { if (this.enable) { const trailIter = this._particleTrail.values(); let trail = trailIter.next(); @@ -445,7 +445,7 @@ export default class TrailModule { } } - public updateMaterial () { + public updateMaterial (): void { if (this._particleSystem) { this._material = this._particleSystem.getMaterialInstance(1) || this._particleSystem.processor._defaultTrailMat; if (this._trailModel) { @@ -454,7 +454,7 @@ export default class TrailModule { } } - public update () { + public update (): void { this._trailLifetime = this.lifeTime.evaluate(this._particleSystem._time, 1)!; if (this.space === Space.World && this._particleSystem._simulationSpace === Space.Local) { this._needTransform = true; @@ -465,7 +465,7 @@ export default class TrailModule { } } - public animate (p: Particle, scaledDt: number) { + public animate (p: Particle, scaledDt: number): void { if (!this._trailSegments) { return; } @@ -535,7 +535,7 @@ export default class TrailModule { } } - public removeParticle (p: Particle) { + public removeParticle (p: Particle): void { const trail = this._particleTrail.get(p); if (trail && this._trailSegments) { trail.clear(); @@ -544,7 +544,7 @@ export default class TrailModule { } } - public updateRenderData () { + public updateRenderData (): void { this.vbOffset = 0; this.ibOffset = 0; for (const p of this._particleTrail.keys()) { @@ -626,7 +626,7 @@ export default class TrailModule { } } - public updateIA (count: number) { + public updateIA (count: number): void { const subModels = this._trailModel && this._trailModel.subModels; if (subModels && subModels.length > 0) { const subModel = subModels[0]; @@ -638,11 +638,11 @@ export default class TrailModule { } } - public beforeRender () { + public beforeRender (): void { this.updateIA(this.ibOffset); } - private _createModel () { + private _createModel (): void { if (this._trailModel) { return; } @@ -650,7 +650,7 @@ export default class TrailModule { this._trailModel = cclegacy.director.root.createModel(scene.Model); } - private rebuild () { + private rebuild (): void { const device: Device = director.root!.device; const vertexBuffer = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, @@ -703,7 +703,7 @@ export default class TrailModule { } private _fillVertexBuffer (trailSeg: ITrailElement, colorModifer: Color, indexOffset: number, - xTexCoord: number, trailEleIdx: number, indexSet: number) { + xTexCoord: number, trailEleIdx: number, indexSet: number): void { this._vbF32![this.vbOffset++] = trailSeg.position.x; this._vbF32![this.vbOffset++] = trailSeg.position.y; this._vbF32![this.vbOffset++] = trailSeg.position.z; @@ -748,7 +748,7 @@ export default class TrailModule { } } - private _checkDirectionReverse (currElement: ITrailElement, prevElement: ITrailElement) { + private _checkDirectionReverse (currElement: ITrailElement, prevElement: ITrailElement): void { if (Vec3.dot(currElement.velocity, prevElement.velocity) < DIRECTION_THRESHOLD) { currElement.direction = 1 - prevElement.direction; } else { @@ -756,7 +756,7 @@ export default class TrailModule { } } - private destroySubMeshData () { + private destroySubMeshData (): void { if (this._subMeshData) { this._subMeshData.destroy(); this._subMeshData = null; diff --git a/cocos/physics-2d/box2d/joints/distance-joint.ts b/cocos/physics-2d/box2d/joints/distance-joint.ts index 92d4e36b913..a35b3ceec7e 100644 --- a/cocos/physics-2d/box2d/joints/distance-joint.ts +++ b/cocos/physics-2d/box2d/joints/distance-joint.ts @@ -29,13 +29,13 @@ import { DistanceJoint2D } from '../../framework'; import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; export class b2DistanceJoint extends b2Joint implements IDistanceJoint { - setMaxLength (v: number) { + setMaxLength (v: number): void { if (this._b2joint) { (this._b2joint as b2.RopeJoint).SetMaxLength(v); } } - _createJointDef () { + _createJointDef (): any { const comp = this._jointComp as DistanceJoint2D; const def = new b2.RopeJointDef(); def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO); diff --git a/cocos/physics-2d/box2d/joints/fixed-joint.ts b/cocos/physics-2d/box2d/joints/fixed-joint.ts index 155da9db813..b42cb968b82 100644 --- a/cocos/physics-2d/box2d/joints/fixed-joint.ts +++ b/cocos/physics-2d/box2d/joints/fixed-joint.ts @@ -29,18 +29,18 @@ import { FixedJoint2D } from '../../framework'; import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; export class b2FixedJoint extends b2Joint implements IFixedJoint { - setFrequency (v: number) { + setFrequency (v: number): void { if (this._b2joint) { (this._b2joint as b2.WeldJoint).SetFrequency(v); } } - setDampingRatio (v: number) { + setDampingRatio (v: number): void { if (this._b2joint) { (this._b2joint as b2.WeldJoint).SetDampingRatio(v); } } - _createJointDef () { + _createJointDef (): any { const comp = this._jointComp as FixedJoint2D; const def = new b2.WeldJointDef(); def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO); diff --git a/cocos/physics-2d/box2d/joints/hinge-joint.ts b/cocos/physics-2d/box2d/joints/hinge-joint.ts index 6b0f0a70ff2..ab66f2e02c1 100644 --- a/cocos/physics-2d/box2d/joints/hinge-joint.ts +++ b/cocos/physics-2d/box2d/joints/hinge-joint.ts @@ -30,18 +30,18 @@ import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; import { toRadian } from '../../../core'; export class b2HingeJoint extends b2Joint implements IHingeJoint { - enableLimit (v: boolean) { + enableLimit (v: boolean): void { if (this._b2joint) { (this._b2joint as b2.RevoluteJoint).EnableLimit(v); } } - setLowerAngle (v: number) { + setLowerAngle (v: number): void { this.updateLimits(); } - setUpperAngle (v: number) { + setUpperAngle (v: number): void { this.updateLimits(); } - updateLimits () { + updateLimits (): void { if (this._b2joint) { const comp = this._jointComp as HingeJoint2D; (this._b2joint as b2.RevoluteJoint).SetLimits(toRadian(comp.lowerAngle), toRadian(comp.upperAngle)); @@ -49,23 +49,23 @@ export class b2HingeJoint extends b2Joint implements IHingeJoint { } // motor - enableMotor (v: boolean) { + enableMotor (v: boolean): void { if (this._b2joint) { (this._b2joint as b2.RevoluteJoint).EnableMotor(v); } } - setMaxMotorTorque (v: number) { + setMaxMotorTorque (v: number): void { if (this._b2joint) { (this._b2joint as b2.RevoluteJoint).SetMaxMotorTorque(v); } } - setMotorSpeed (v: number) { + setMotorSpeed (v: number): void { if (this._b2joint) { (this._b2joint as b2.RevoluteJoint).SetMotorSpeed(v); } } - _createJointDef () { + _createJointDef (): any { const comp = this._jointComp as HingeJoint2D; const def = new b2.RevoluteJointDef(); def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO); diff --git a/cocos/physics-2d/box2d/joints/joint-2d.ts b/cocos/physics-2d/box2d/joints/joint-2d.ts index f222947671b..8aa60b35467 100644 --- a/cocos/physics-2d/box2d/joints/joint-2d.ts +++ b/cocos/physics-2d/box2d/joints/joint-2d.ts @@ -29,13 +29,13 @@ import { b2PhysicsWorld } from '../physics-world'; import { Vec2 } from '../../../core'; export class b2Joint implements IJoint2D { - get impl () { + get impl (): b2.Joint | null { return this._b2joint; } - get comp () { + get comp (): Joint2D | null { return this._jointComp; } - get body () { + get body (): RigidBody2D | null { return this._body; } @@ -45,24 +45,24 @@ export class b2Joint implements IJoint2D { private _inited = false; - initialize (comp: Joint2D) { + initialize (comp: Joint2D): void { this._jointComp = comp; } - onEnable () { + onEnable (): void { PhysicsSystem2D.instance._callAfterStep(this, this._init); } - onDisable () { + onDisable (): void { PhysicsSystem2D.instance._callAfterStep(this, this._destroy); } // need init after body and connected body init - start () { + start (): void { PhysicsSystem2D.instance._callAfterStep(this, this._init); } - _init () { + _init (): void { if (this._inited) return; const comp = this._jointComp!; @@ -98,7 +98,7 @@ export class b2Joint implements IJoint2D { this._inited = true; } - _destroy () { + _destroy (): void { if (!this._inited) return; (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).impl.DestroyJoint(this._b2joint!); @@ -111,7 +111,7 @@ export class b2Joint implements IJoint2D { return null; } - isValid () { + isValid (): Joint2D | null { return this._b2joint && this._body && this._body.impl && this._jointComp; } } diff --git a/cocos/physics-2d/box2d/joints/mouse-joint.ts b/cocos/physics-2d/box2d/joints/mouse-joint.ts index 2811aab97e0..b4a50af7c55 100644 --- a/cocos/physics-2d/box2d/joints/mouse-joint.ts +++ b/cocos/physics-2d/box2d/joints/mouse-joint.ts @@ -39,30 +39,30 @@ export class b2MouseJoint extends b2Joint implements IMouseJoint { _touchPoint = new Vec2(); _isTouched = false; - setTarget (v: IVec2Like) { + setTarget (v: IVec2Like): void { if (this._b2joint) { tempB2Vec2.x = v.x / PHYSICS_2D_PTM_RATIO; tempB2Vec2.y = v.y / PHYSICS_2D_PTM_RATIO; (this._b2joint as b2.MouseJoint).SetTarget(tempB2Vec2); } } - setDampingRatio (v: number) { + setDampingRatio (v: number): void { if (this._b2joint) { (this._b2joint as b2.MouseJoint).SetDampingRatio(v); } } - setFrequency (v: number) { + setFrequency (v: number): void { if (this._b2joint) { (this._b2joint as b2.MouseJoint).SetFrequency(v); } } - setMaxForce (v: number) { + setMaxForce (v: number): void { if (this._b2joint) { (this._b2joint as b2.MouseJoint).SetMaxForce(v); } } - _createJointDef () { + _createJointDef (): any { const def = new b2.MouseJointDef(); const comp = this._jointComp as MouseJoint2D; def.target.Set(this._touchPoint.x / PHYSICS_2D_PTM_RATIO, this._touchPoint.y / PHYSICS_2D_PTM_RATIO); @@ -72,7 +72,7 @@ export class b2MouseJoint extends b2Joint implements IMouseJoint { return def; } - initialize (comp: Joint2D) { + initialize (comp: Joint2D): void { super.initialize(comp); const canvas = find('Canvas'); @@ -84,13 +84,13 @@ export class b2MouseJoint extends b2Joint implements IMouseJoint { } } - onEnable () { + onEnable (): void { } - start () { + start (): void { } - onTouchBegan (event: Touch) { + onTouchBegan (event: Touch): void { this._isTouched = true; const target = this._touchPoint.set(event.getUILocation()); @@ -111,16 +111,16 @@ export class b2MouseJoint extends b2Joint implements IMouseJoint { this.setTarget(target); } - onTouchMove (event: Touch) { + onTouchMove (event: Touch): void { this._touchPoint = event.getUILocation(); } - onTouchEnd (event: Touch) { + onTouchEnd (event: Touch): void { this._destroy(); this._isTouched = false; } - update () { + update (): void { if (!this._isTouched || !this.isValid()) { return; } diff --git a/cocos/physics-2d/box2d/joints/relative-joint.ts b/cocos/physics-2d/box2d/joints/relative-joint.ts index 4817e0f2496..510cc125a1e 100644 --- a/cocos/physics-2d/box2d/joints/relative-joint.ts +++ b/cocos/physics-2d/box2d/joints/relative-joint.ts @@ -30,33 +30,33 @@ import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; import { toRadian } from '../../../core'; export class b2RelativeJoint extends b2Joint implements IRelativeJoint { - setMaxForce (v: number) { + setMaxForce (v: number): void { if (this._b2joint) { (this._b2joint as b2.MotorJoint).SetMaxForce(v); } } - setAngularOffset (v: number) { + setAngularOffset (v: number): void { if (this._b2joint) { (this._b2joint as b2.MotorJoint).SetAngularOffset(toRadian(v)); } } - setLinearOffset (v: Vec2) { + setLinearOffset (v: Vec2): void { if (this._b2joint) { (this._b2joint as b2.MotorJoint).SetLinearOffset(new b2.Vec2(v.x / PHYSICS_2D_PTM_RATIO, v.y / PHYSICS_2D_PTM_RATIO)); } } - setCorrectionFactor (v: number) { + setCorrectionFactor (v: number): void { if (this._b2joint) { (this._b2joint as b2.MotorJoint).m_correctionFactor = v; } } - setMaxTorque (v: number) { + setMaxTorque (v: number): void { if (this._b2joint) { (this._b2joint as b2.MotorJoint).SetMaxTorque(v); } } - _createJointDef () { + _createJointDef (): any { const comp = this._jointComp as RelativeJoint2D; const def = new b2.MotorJointDef(); def.linearOffset.Set(comp.linearOffset.x / PHYSICS_2D_PTM_RATIO, comp.linearOffset.y / PHYSICS_2D_PTM_RATIO); diff --git a/cocos/physics-2d/box2d/joints/slider-joint.ts b/cocos/physics-2d/box2d/joints/slider-joint.ts index 5b713e42825..7de7655c977 100644 --- a/cocos/physics-2d/box2d/joints/slider-joint.ts +++ b/cocos/physics-2d/box2d/joints/slider-joint.ts @@ -31,18 +31,18 @@ import { toRadian } from '../../../core'; export class b2SliderJoint extends b2Joint implements ISliderJoint { // limit - enableLimit (v: boolean) { + enableLimit (v: boolean): void { if (this._b2joint) { (this._b2joint as b2.PrismaticJoint).EnableLimit(v); } } - setLowerLimit (v: number) { + setLowerLimit (v: number): void { this.updateLimits(); } - setUpperLimit (v: number) { + setUpperLimit (v: number): void { this.updateLimits(); } - updateLimits () { + updateLimits (): void { if (this._b2joint) { const comp = this._jointComp as SliderJoint2D; (this._b2joint as b2.PrismaticJoint).SetLimits(comp.lowerLimit / PHYSICS_2D_PTM_RATIO, comp.upperLimit / PHYSICS_2D_PTM_RATIO); @@ -50,23 +50,23 @@ export class b2SliderJoint extends b2Joint implements ISliderJoint { } // motor - enableMotor (v: boolean) { + enableMotor (v: boolean): void { if (this._b2joint) { (this._b2joint as b2.PrismaticJoint).EnableMotor(v); } } - setMaxMotorForce (v: number) { + setMaxMotorForce (v: number): void { if (this._b2joint) { (this._b2joint as b2.PrismaticJoint).SetMaxMotorForce(v); } } - setMotorSpeed (v: number) { + setMotorSpeed (v: number): void { if (this._b2joint) { (this._b2joint as b2.PrismaticJoint).SetMotorSpeed(v); } } - _createJointDef () { + _createJointDef (): any { const comp = this._jointComp as SliderJoint2D; const def = new b2.PrismaticJointDef(); def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO); diff --git a/cocos/physics-2d/box2d/joints/spring-joint.ts b/cocos/physics-2d/box2d/joints/spring-joint.ts index 61ee071e8fb..00ce8588797 100644 --- a/cocos/physics-2d/box2d/joints/spring-joint.ts +++ b/cocos/physics-2d/box2d/joints/spring-joint.ts @@ -29,23 +29,23 @@ import { SpringJoint2D } from '../../framework'; import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; export class b2SpringJoint extends b2Joint implements ISpringJoint { - setDampingRatio (v: number) { + setDampingRatio (v: number): void { if (this._b2joint) { (this._b2joint as b2.DistanceJoint).SetDampingRatio(v); } } - setFrequency (v: number) { + setFrequency (v: number): void { if (this._b2joint) { (this._b2joint as b2.DistanceJoint).SetFrequency(v); } } - setDistance (v: number) { + setDistance (v: number): void { if (this._b2joint) { (this._b2joint as b2.DistanceJoint).SetLength(v); } } - _createJointDef () { + _createJointDef (): any { const comp = this._jointComp as SpringJoint2D; const def = new b2.DistanceJointDef(); def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO); diff --git a/cocos/physics-2d/box2d/joints/wheel-joint.ts b/cocos/physics-2d/box2d/joints/wheel-joint.ts index ea33ea50674..6c8a951503b 100644 --- a/cocos/physics-2d/box2d/joints/wheel-joint.ts +++ b/cocos/physics-2d/box2d/joints/wheel-joint.ts @@ -30,35 +30,35 @@ import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; import { toRadian } from '../../../core'; export class b2WheelJoint extends b2Joint implements IWheelJoint { - setDampingRatio (v: number) { + setDampingRatio (v: number): void { if (this._b2joint) { (this._b2joint as b2.WheelJoint).SetSpringDampingRatio(v); } } - setFrequency (v: number) { + setFrequency (v: number): void { if (this._b2joint) { (this._b2joint as b2.WheelJoint).SetSpringFrequencyHz(v); } } // motor - enableMotor (v: boolean) { + enableMotor (v: boolean): void { if (this._b2joint) { (this._b2joint as b2.WheelJoint).EnableMotor(v); } } - setMaxMotorTorque (v: number) { + setMaxMotorTorque (v: number): void { if (this._b2joint) { (this._b2joint as b2.WheelJoint).SetMaxMotorTorque(v); } } - setMotorSpeed (v: number) { + setMotorSpeed (v: number): void { if (this._b2joint) { (this._b2joint as b2.WheelJoint).SetMotorSpeed(v); } } - _createJointDef () { + _createJointDef (): any { const comp = this._jointComp as WheelJoint2D; const def = new b2.WheelJointDef(); def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO); diff --git a/cocos/physics-2d/box2d/physics-contact.ts b/cocos/physics-2d/box2d/physics-contact.ts index 9c145f7ec9f..3d41710bb08 100644 --- a/cocos/physics-2d/box2d/physics-contact.ts +++ b/cocos/physics-2d/box2d/physics-contact.ts @@ -82,11 +82,11 @@ export class PhysicsContact implements IPhysics2DContact { private _inverted = false; private _b2contact: b2Contact | null = null; - _setImpulse (impulse: b2.ContactImpulse | null) { + _setImpulse (impulse: b2.ContactImpulse | null): void { this._impulse = impulse; } - private init (b2contact) { + private init (b2contact): void { this.colliderA = (b2contact.m_fixtureA.m_userData as b2Shape2D).collider; this.colliderB = (b2contact.m_fixtureB.m_userData as b2Shape2D).collider; this.disabled = false; @@ -98,7 +98,7 @@ export class PhysicsContact implements IPhysics2DContact { this._b2contact = b2contact; } - reset () { + reset (): void { this.setTangentSpeed(0); this.resetFriction(); this.resetRestitution(); @@ -110,7 +110,7 @@ export class PhysicsContact implements IPhysics2DContact { this._b2contact = null; } - getWorldManifold () { + getWorldManifold (): IPhysics2DWorldManifold { const points = worldmanifold.points; const separations = worldmanifold.separations; const normal = worldmanifold.normal; @@ -142,7 +142,7 @@ export class PhysicsContact implements IPhysics2DContact { return worldmanifold; } - getManifold () { + getManifold (): { type: number; localPoint: Vec2; localNormal: Vec2; points: ManifoldPoint[]; } { const points = manifold.points; const localNormal = manifold.localNormal; const localPoint = manifold.localPoint; @@ -176,7 +176,7 @@ export class PhysicsContact implements IPhysics2DContact { return manifold; } - getImpulse () { + getImpulse (): IPhysics2DImpulse | null { const b2impulse = this._impulse; if (!b2impulse) return null; @@ -193,43 +193,43 @@ export class PhysicsContact implements IPhysics2DContact { return impulse; } - setEnabled (value) { + setEnabled (value): void { this._b2contact!.SetEnabled(value); } - isTouching () { + isTouching (): boolean { return this._b2contact!.IsTouching(); } - setTangentSpeed (value) { + setTangentSpeed (value): void { this._b2contact!.SetTangentSpeed(value); } - getTangentSpeed () { + getTangentSpeed (): number { return this._b2contact!.GetTangentSpeed(); } - setFriction (value) { + setFriction (value): void { this._b2contact!.SetFriction(value); } - getFriction () { + getFriction (): number { return this._b2contact!.GetFriction(); } - resetFriction () { + resetFriction (): void { return this._b2contact!.ResetFriction(); } - setRestitution (value) { + setRestitution (value): void { this._b2contact!.SetRestitution(value); } - getRestitution () { + getRestitution (): number { return this._b2contact!.GetRestitution(); } - resetRestitution () { + resetRestitution (): void { return this._b2contact!.ResetRestitution(); } } diff --git a/cocos/physics-2d/box2d/physics-world.ts b/cocos/physics-2d/box2d/physics-world.ts index 87965d93511..5650c1a9314 100644 --- a/cocos/physics-2d/box2d/physics-world.ts +++ b/cocos/physics-2d/box2d/physics-world.ts @@ -61,11 +61,11 @@ export class b2PhysicsWorld implements IPhysicsWorld { protected _aabbQueryCallback: PhysicsAABBQueryCallback; protected _raycastQueryCallback: PhysicsRayCastCallback; - get impl () { + get impl (): b2.World { return this._world; } - get groundBodyImpl () { + get groundBodyImpl (): b2.Body { return this._physicsGroundBody; } @@ -86,7 +86,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { _b2DebugDrawer: b2.Draw | null = null; _debugDrawFlags = 0; - get debugDrawFlags () { + get debugDrawFlags (): number { return this._debugDrawFlags; } set debugDrawFlags (v) { @@ -101,7 +101,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { this._debugDrawFlags = v; } - _checkDebugDrawValid () { + _checkDebugDrawValid (): void { if (EDITOR_NOT_IN_PREVIEW) return; if (!this._debugGraphics || !this._debugGraphics.isValid) { let canvas = find('Canvas'); @@ -139,15 +139,15 @@ export class b2PhysicsWorld implements IPhysicsWorld { } } - setGravity (v: IVec2Like) { + setGravity (v: IVec2Like): void { this._world.SetGravity(v as b2.Vec2); } - setAllowSleep (v: boolean) { + setAllowSleep (v: boolean): void { this._world.SetAllowSleeping(true); } - step (deltaTime: number, velocityIterations = 10, positionIterations = 10) { + step (deltaTime: number, velocityIterations = 10, positionIterations = 10): void { const animatedBodies = this._animatedBodies; for (let i = 0, l = animatedBodies.length; i < l; i++) { animatedBodies[i].animate(deltaTime); @@ -219,7 +219,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { return []; } - syncPhysicsToScene () { + syncPhysicsToScene (): void { const bodies = this._bodies; for (let i = 0, l = bodies.length; i < l; i++) { const body = bodies[i]; @@ -244,14 +244,14 @@ export class b2PhysicsWorld implements IPhysicsWorld { node.setWorldRotationFromEuler(0, 0, angle); } } - syncSceneToPhysics () { + syncSceneToPhysics (): void { const bodies = this._bodies; for (let i = 0; i < bodies.length; i++) { bodies[i].syncSceneToPhysics(); } } - addBody (body: b2RigidBody2D) { + addBody (body: b2RigidBody2D): void { const bodies = this._bodies; if (bodies.includes(body)) { return; @@ -305,7 +305,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { this._bodies.push(body); } - removeBody (body: b2RigidBody2D) { + removeBody (body: b2RigidBody2D): void { if (!this._bodies.includes(body)) { return; } @@ -368,7 +368,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { return testResults; } - drawDebug () { + drawDebug (): void { this._checkDebugDrawValid(); if (!this._debugGraphics) { @@ -378,7 +378,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { this._world.DrawDebugData(); } - finalizeContactEvent () { + finalizeContactEvent (): void { this._contactListener.finalizeContactEvent(); } } diff --git a/cocos/physics-2d/box2d/platform/physics-aabb-query-callback.ts b/cocos/physics-2d/box2d/platform/physics-aabb-query-callback.ts index f06bd06ddc1..050a068fc57 100644 --- a/cocos/physics-2d/box2d/platform/physics-aabb-query-callback.ts +++ b/cocos/physics-2d/box2d/platform/physics-aabb-query-callback.ts @@ -30,7 +30,7 @@ export class PhysicsAABBQueryCallback extends b2.QueryCallback { _isPoint = false; _fixtures: b2.Fixture[] = []; - init (point?: Vec2) { + init (point?: Vec2): void { if (point) { this._isPoint = true; this._point.x = point.x; @@ -42,7 +42,7 @@ export class PhysicsAABBQueryCallback extends b2.QueryCallback { this._fixtures.length = 0; } - ReportFixture (fixture: b2.Fixture) { + ReportFixture (fixture: b2.Fixture): boolean { if (this._isPoint) { if (fixture.TestPoint(this._point)) { this._fixtures.push(fixture); @@ -55,11 +55,11 @@ export class PhysicsAABBQueryCallback extends b2.QueryCallback { return true; } - getFixture () { + getFixture (): any { return this._fixtures[0]; } - getFixtures () { + getFixtures (): any[] { return this._fixtures; } } diff --git a/cocos/physics-2d/box2d/platform/physics-contact-listener.ts b/cocos/physics-2d/box2d/platform/physics-contact-listener.ts index 55a6f573483..613dc465991 100644 --- a/cocos/physics-2d/box2d/platform/physics-contact-listener.ts +++ b/cocos/physics-2d/box2d/platform/physics-contact-listener.ts @@ -40,7 +40,7 @@ import { b2Shape2D } from '../shapes/shape-2d'; export class PhysicsContactListener extends b2.ContactListener { static readonly _contactMap = new Map(); - private getContactKey (contact: b2.Contact) { + private getContactKey (contact: b2.Contact): string { const colliderA = (contact.m_fixtureA.m_userData as b2Shape2D).collider; const colliderB = (contact.m_fixtureB.m_userData as b2Shape2D).collider; let key = colliderA.uuid + colliderB.uuid; @@ -50,7 +50,7 @@ export class PhysicsContactListener extends b2.ContactListener { return key; } - BeginContact (contact: b2.Contact) { + BeginContact (contact: b2.Contact): void { const key = this.getContactKey(contact); if (PhysicsContactListener._contactMap.has(key)) { @@ -72,7 +72,7 @@ export class PhysicsContactListener extends b2.ContactListener { } } - EndContact (contact: b2.Contact) { + EndContact (contact: b2.Contact): void { const key = this.getContactKey(contact); const retContact = PhysicsContactListener._contactMap.get(key); @@ -86,14 +86,14 @@ export class PhysicsContactListener extends b2.ContactListener { } } - PreSolve (contact: b2.Contact, oldManifold: b2.Manifold) { + PreSolve (contact: b2.Contact, oldManifold: b2.Manifold): void { } - PostSolve (contact: b2.Contact, impulse: b2.ContactImpulse) { + PostSolve (contact: b2.Contact, impulse: b2.ContactImpulse): void { } - public finalizeContactEvent () { - PhysicsContactListener._contactMap.forEach((contact: PhysicsContact, key: string) => { + public finalizeContactEvent (): void { + PhysicsContactListener._contactMap.forEach((contact: PhysicsContact, key: string): void => { //console.log('forEach', key, collision); // emit collision event @@ -119,7 +119,7 @@ export class PhysicsContactListener extends b2.ContactListener { }); } - private emit (contactType, contact: PhysicsContact) { + private emit (contactType, contact: PhysicsContact): void { const colliderA = contact.colliderA; const colliderB = contact.colliderB; if (!colliderA || !colliderB) { diff --git a/cocos/physics-2d/box2d/platform/physics-debug-draw.ts b/cocos/physics-2d/box2d/platform/physics-debug-draw.ts index b9ed99e180e..937a39457e9 100644 --- a/cocos/physics-2d/box2d/platform/physics-debug-draw.ts +++ b/cocos/physics-2d/box2d/platform/physics-debug-draw.ts @@ -44,7 +44,7 @@ export class PhysicsDebugDraw extends b2.Draw { this._drawer = drawer; } - _DrawPolygon (vertices, vertexCount) { + _DrawPolygon (vertices, vertexCount): void { const drawer = this._drawer!; for (let i = 0; i < vertexCount; i++) { @@ -60,37 +60,37 @@ export class PhysicsDebugDraw extends b2.Draw { drawer.close(); } - DrawPolygon (vertices, vertexCount, color) { + DrawPolygon (vertices, vertexCount, color): void { this._applyStrokeColor(color); this._DrawPolygon(vertices, vertexCount); this._drawer!.stroke(); } - DrawSolidPolygon (vertices, vertexCount, color) { + DrawSolidPolygon (vertices, vertexCount, color): void { this._applyFillColor(color); this._DrawPolygon(vertices, vertexCount); this._drawer!.fill(); this._drawer!.stroke(); } - _DrawCircle (center: b2.Vec2, radius: number) { + _DrawCircle (center: b2.Vec2, radius: number): void { const p = this._xf.p; this._drawer!.circle((center.x + p.x) * PHYSICS_2D_PTM_RATIO, (center.y + p.y) * PHYSICS_2D_PTM_RATIO, radius * PHYSICS_2D_PTM_RATIO); } - DrawCircle (center: b2.Vec2, radius: number, color) { + DrawCircle (center: b2.Vec2, radius: number, color): void { this._applyStrokeColor(color); this._DrawCircle(center, radius); this._drawer!.stroke(); } - DrawSolidCircle (center: b2.Vec2, radius: number, axis, color) { + DrawSolidCircle (center: b2.Vec2, radius: number, axis, color): void { this._applyFillColor(color); this._DrawCircle(center, radius); this._drawer!.fill(); } - DrawSegment (p1: b2.Vec2, p2: b2.Vec2, color) { + DrawSegment (p1: b2.Vec2, p2: b2.Vec2, color): void { const drawer = this._drawer!; if (p1.x === p2.x && p1.y === p2.y) { @@ -108,7 +108,7 @@ export class PhysicsDebugDraw extends b2.Draw { drawer.stroke(); } - DrawTransform (xf: b2.Transform) { + DrawTransform (xf: b2.Transform): void { const drawer = this._drawer!; drawer.strokeColor = RED_COLOR; @@ -136,13 +136,13 @@ export class PhysicsDebugDraw extends b2.Draw { drawer.stroke(); } - DrawPoint (center, radius, color) { + DrawPoint (center, radius, color): void { } - DrawParticles () { + DrawParticles (): void { } - _applyStrokeColor (color) { + _applyStrokeColor (color): void { this._drawer!.strokeColor = _tmp_color.set( color.r * 255, color.g * 255, @@ -151,7 +151,7 @@ export class PhysicsDebugDraw extends b2.Draw { ); } - _applyFillColor (color) { + _applyFillColor (color): void { this._drawer!.fillColor = _tmp_color.set( color.r * 255, color.g * 255, @@ -160,11 +160,11 @@ export class PhysicsDebugDraw extends b2.Draw { ); } - PushTransform (xf) { + PushTransform (xf): void { this._xf = xf; } - PopTransform () { + PopTransform (): void { this._xf = this._dxf; } } diff --git a/cocos/physics-2d/box2d/platform/physics-ray-cast-callback.ts b/cocos/physics-2d/box2d/platform/physics-ray-cast-callback.ts index 7d6b2c9d34a..7f7e5ec6b09 100644 --- a/cocos/physics-2d/box2d/platform/physics-ray-cast-callback.ts +++ b/cocos/physics-2d/box2d/platform/physics-ray-cast-callback.ts @@ -35,7 +35,7 @@ export class PhysicsRayCastCallback extends b2.RayCastCallback { _mask = 0xffffffff; - init (type: ERaycast2DType, mask: number) { + init (type: ERaycast2DType, mask: number): void { this._type = type; this._mask = mask; this._fixtures.length = 0; @@ -44,7 +44,7 @@ export class PhysicsRayCastCallback extends b2.RayCastCallback { this._fractions.length = 0; } - ReportFixture (fixture: b2.Fixture, point, normal, fraction) { + ReportFixture (fixture: b2.Fixture, point, normal, fraction): any { if ((fixture.GetFilterData().categoryBits & this._mask) === 0) { return 0; } @@ -71,19 +71,19 @@ export class PhysicsRayCastCallback extends b2.RayCastCallback { return fraction; } - getFixtures () { + getFixtures (): any[] { return this._fixtures; } - getPoints () { + getPoints (): Vec2[] { return this._points; } - getNormals () { + getNormals (): Vec2[] { return this._normals; } - getFractions () { + getFractions (): number[] { return this._fractions; } } diff --git a/cocos/physics-2d/box2d/rigid-body.ts b/cocos/physics-2d/box2d/rigid-body.ts index 8d3ec48fcdb..e99c8b24496 100644 --- a/cocos/physics-2d/box2d/rigid-body.ts +++ b/cocos/physics-2d/box2d/rigid-body.ts @@ -39,20 +39,20 @@ const tempVec3 = new Vec3(); const tempVec2_1 = new b2.Vec2(); export class b2RigidBody2D implements IRigidBody2D { - get impl () { + get impl (): b2.Body | null { return this._body; } set _imp (v: b2.Body | null) { this._body = v; } - get rigidBody () { + get rigidBody (): RigidBody2D { return this._rigidBody; } - get isAwake () { + get isAwake (): boolean { return this._body!.IsAwake(); } - get isSleeping () { + get isSleeping (): boolean { return !(this._body!.IsAwake()); } @@ -64,25 +64,25 @@ export class b2RigidBody2D implements IRigidBody2D { private _inited = false; - initialize (com: RigidBody2D) { + initialize (com: RigidBody2D): void { this._rigidBody = com; PhysicsSystem2D.instance._callAfterStep(this, this._init); } - onDestroy () { + onDestroy (): void { PhysicsSystem2D.instance._callAfterStep(this, this._destroy); } - onEnable () { + onEnable (): void { this.setActive(true); } - onDisable () { + onDisable (): void { this.setActive(false); } - nodeTransformChanged (type) { + nodeTransformChanged (type): void { if (PhysicsSystem2D.instance.stepping) { return; } @@ -101,7 +101,7 @@ export class b2RigidBody2D implements IRigidBody2D { } } - _init () { + _init (): void { if (this._inited) { return; } @@ -112,7 +112,7 @@ export class b2RigidBody2D implements IRigidBody2D { this._inited = true; } - _destroy () { + _destroy (): void { if (!this._inited) return; (PhysicsSystem2D.instance.physicsWorld as b2PhysicsWorld).removeBody(this); @@ -120,7 +120,7 @@ export class b2RigidBody2D implements IRigidBody2D { this._inited = false; } - animate (dt: number) { + animate (dt: number): void { const b2body = this._body; if (!b2body) return; const b2Pos = b2body.GetPosition(); @@ -149,12 +149,12 @@ export class b2RigidBody2D implements IRigidBody2D { b2body.SetAngularVelocity(angularVelocity); } - syncSceneToPhysics () { + syncSceneToPhysics (): void { const dirty = this._rigidBody.node.hasChangedFlags; if (dirty) { this.nodeTransformChanged(dirty); } } - syncPositionToPhysics (enableAnimated = false) { + syncPositionToPhysics (enableAnimated = false): void { const b2body = this._body; if (!b2body) return; @@ -178,7 +178,7 @@ export class b2RigidBody2D implements IRigidBody2D { } } - syncRotationToPhysics (enableAnimated = false) { + syncRotationToPhysics (enableAnimated = false): void { const b2body = this._body; if (!b2body) return; @@ -195,7 +195,7 @@ export class b2RigidBody2D implements IRigidBody2D { } } - resetVelocity () { + resetVelocity (): void { const b2body = this._body; if (!b2body) return; @@ -206,40 +206,40 @@ export class b2RigidBody2D implements IRigidBody2D { b2body.SetAngularVelocity(0); } - setType (v: ERigidBody2DType) { + setType (v: ERigidBody2DType): void { this._body!.SetType(v as number); } - setLinearDamping (v: number) { + setLinearDamping (v: number): void { this._body!.SetLinearDamping(v); } - setAngularDamping (v: number) { + setAngularDamping (v: number): void { this._body!.SetAngularDamping(v); } - setGravityScale (v: number) { + setGravityScale (v: number): void { this._body!.SetGravityScale(v); } - setFixedRotation (v: boolean) { + setFixedRotation (v: boolean): void { this._body!.SetFixedRotation(v); } - setAllowSleep (v: boolean) { + setAllowSleep (v: boolean): void { this._body!.SetSleepingAllowed(v); } - isActive () { + isActive (): any { return this._body!.IsActive(); } - setActive (v: boolean) { + setActive (v: boolean): void { this._body!.SetActive(v); } - wakeUp () { + wakeUp (): void { this._body!.SetAwake(true); } - sleep () { + sleep (): void { this._body!.SetAwake(false); } - getMass () { + getMass (): any { return this._body!.GetMass(); } - setLinearVelocity (v: IVec2Like) { + setLinearVelocity (v: IVec2Like): void { this._body!.SetLinearVelocity(v as b2.Vec2); } getLinearVelocity (out: Out): Out { @@ -255,10 +255,10 @@ export class b2RigidBody2D implements IRigidBody2D { out.y *= PHYSICS_2D_PTM_RATIO; return out; } - setAngularVelocity (v: number) { + setAngularVelocity (v: number): void { this._body!.SetAngularVelocity(v); } - getAngularVelocity () { + getAngularVelocity (): number { return toDegree(this._body!.GetAngularVelocity()); } @@ -311,43 +311,43 @@ export class b2RigidBody2D implements IRigidBody2D { return out; } - getInertia () { + getInertia (): any { return this._body!.GetInertia(); } - applyForce (force: IVec2Like, point: IVec2Like, wake: boolean) { + applyForce (force: IVec2Like, point: IVec2Like, wake: boolean): void { if (this._body) { tempVec2_1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO); this._body.ApplyForce(force as b2.Vec2, tempVec2_1, wake); } } - applyForceToCenter (force: IVec2Like, wake: boolean) { + applyForceToCenter (force: IVec2Like, wake: boolean): void { if (this._body) { this._body.ApplyForceToCenter(force as b2.Vec2, wake); } } - applyTorque (torque: number, wake: boolean) { + applyTorque (torque: number, wake: boolean): void { if (this._body) { this._body.ApplyTorque(torque, wake); } } - applyLinearImpulse (impulse: IVec2Like, point: IVec2Like, wake: boolean) { + applyLinearImpulse (impulse: IVec2Like, point: IVec2Like, wake: boolean): void { if (this._body) { tempVec2_1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO); this._body.ApplyLinearImpulse(impulse as b2.Vec2, tempVec2_1, wake); } } - applyLinearImpulseToCenter (impulse: IVec2Like, wake: boolean) { + applyLinearImpulseToCenter (impulse: IVec2Like, wake: boolean): void { if (this._body) { this._body.ApplyLinearImpulse(impulse as b2.Vec2, this._body.GetPosition(), wake); } } - applyAngularImpulse (impulse: number, wake: boolean) { + applyAngularImpulse (impulse: number, wake: boolean): void { if (this._body) { this._body.ApplyAngularImpulse(impulse, wake); } diff --git a/cocos/physics-2d/box2d/shapes/box-shape-2d.ts b/cocos/physics-2d/box2d/shapes/box-shape-2d.ts index b2bef265a60..f12c85c9fe3 100644 --- a/cocos/physics-2d/box2d/shapes/box-shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/box-shape-2d.ts @@ -54,7 +54,7 @@ export class b2BoxShape extends b2Shape2D implements IBoxShape { return wps; } - _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number) { + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] { scaleX = Math.abs(scaleX); scaleY = Math.abs(scaleY); diff --git a/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts b/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts index 1c453ba3cbf..8079ce3eb24 100644 --- a/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/circle-shape-2d.ts @@ -30,17 +30,17 @@ import { ICircleShape } from '../../spec/i-physics-shape'; import { Vec2 } from '../../../core'; export class b2CircleShape extends b2Shape2D implements ICircleShape { - get worldRadius () { + get worldRadius (): number { return (this._shapes[0] as b2.CircleShape).m_radius * PHYSICS_2D_PTM_RATIO; } _worldPosition = new Vec2(); - get worldPosition () { + get worldPosition (): Vec2 { const p = (this._shapes[0] as b2.CircleShape).m_p; return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO); } - _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number) { + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] { scaleX = Math.abs(scaleX); scaleY = Math.abs(scaleY); diff --git a/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts b/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts index 6a9a4e4b4a7..ba04cec60a8 100644 --- a/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/polygon-shape-2d.ts @@ -49,7 +49,7 @@ export class b2PolygonShape extends b2Shape2D implements IPolygonShape { return this._worldPoints; } - _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number) { + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] { const shapes: b2.PolygonShape[] = []; const comp = this.collider as PolygonCollider2D; diff --git a/cocos/physics-2d/box2d/shapes/shape-2d.ts b/cocos/physics-2d/box2d/shapes/shape-2d.ts index 91bd0b4463c..284ece6ec24 100644 --- a/cocos/physics-2d/box2d/shapes/shape-2d.ts +++ b/cocos/physics-2d/box2d/shapes/shape-2d.ts @@ -32,7 +32,7 @@ import { PhysicsGroup } from '../../../physics/framework/physics-enum'; const tempFilter = new b2.Filter(); -function getFilter (shape: b2Shape2D) { +function getFilter (shape: b2Shape2D): any { const comp = shape.collider; if (comp.body) { tempFilter.categoryBits = comp.group === PhysicsGroup.DEFAULT ? comp.body.group : comp.group; @@ -54,41 +54,41 @@ export class b2Shape2D implements IBaseShape { private _rect = new Rect(); - get impl () { + get impl (): b2.Shape[] { return this._shapes; } - get collider () { + get collider (): Collider2D { return this._collider!; } - initialize (comp: Collider2D) { + initialize (comp: Collider2D): void { this._collider = comp; } - onLoad () { + onLoad (): void { } - onEnable () { + onEnable (): void { PhysicsSystem2D.instance._callAfterStep(this, this._init); } - onDisable () { + onDisable (): void { PhysicsSystem2D.instance._callAfterStep(this, this._destroy); } - start () { + start (): void { } - onGroupChanged () { + onGroupChanged (): void { const filter = getFilter(this); - this._fixtures.forEach((f) => { + this._fixtures.forEach((f): void => { f.SetFilterData(filter); }); } - apply () { + apply (): void { this._destroy(); if (this.collider.enabledInHierarchy) { this._init(); @@ -133,7 +133,7 @@ export class b2Shape2D implements IBaseShape { return r; } - getFixtureIndex (fixture: b2.Fixture) { + getFixtureIndex (fixture: b2.Fixture): number { return this._fixtures.indexOf(fixture); } @@ -142,7 +142,7 @@ export class b2Shape2D implements IBaseShape { return []; } - _init () { + _init (): void { if (this._inited) return; const comp = this.collider; @@ -187,7 +187,7 @@ export class b2Shape2D implements IBaseShape { this._inited = true; } - _destroy () { + _destroy (): void { if (!this._inited) return; const fixtures = this._fixtures; diff --git a/cocos/physics-2d/builtin/builtin-contact.ts b/cocos/physics-2d/builtin/builtin-contact.ts index ef245830db5..c13335e7b31 100644 --- a/cocos/physics-2d/builtin/builtin-contact.ts +++ b/cocos/physics-2d/builtin/builtin-contact.ts @@ -65,7 +65,7 @@ export class BuiltinContact { } } - test () { + test (): boolean { const s1 = this.shape1!; const s2 = this.shape2!; @@ -92,7 +92,7 @@ export class BuiltinContact { return false; } - updateState () { + updateState (): string { const result = this.test(); let type = Contact2DType.None; diff --git a/cocos/physics-2d/builtin/builtin-world.ts b/cocos/physics-2d/builtin/builtin-world.ts index 7a7dc177f15..533ee749f07 100644 --- a/cocos/physics-2d/builtin/builtin-world.ts +++ b/cocos/physics-2d/builtin/builtin-world.ts @@ -46,14 +46,14 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { private _debugGraphics: Graphics | null = null; private _debugDrawFlags = 0; - get debugDrawFlags () { + get debugDrawFlags (): number { return this._debugDrawFlags; } set debugDrawFlags (v) { this._debugDrawFlags = v; } - shouldCollide (c1: BuiltinShape2D, c2: BuiltinShape2D) { + shouldCollide (c1: BuiltinShape2D, c2: BuiltinShape2D): number | boolean { const collider1 = c1.collider; const collider2 = c2.collider; const collisionMatrix = PhysicsSystem2D.instance.collisionMatrix; return (collider1 !== collider2) @@ -62,7 +62,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { && (collisionMatrix[collider2.group] & collider1.group); } - addShape (shape: BuiltinShape2D) { + addShape (shape: BuiltinShape2D): void { const shapes = this._shapes; const index = shapes.indexOf(shape); if (index === -1) { @@ -80,7 +80,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { } } - removeShape (shape: BuiltinShape2D) { + removeShape (shape: BuiltinShape2D): void { const shapes = this._shapes; const index = shapes.indexOf(shape); if (index >= 0) { @@ -106,14 +106,14 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { shape._contacts.length = 0; } - updateShapeGroup (shape: BuiltinShape2D) { + updateShapeGroup (shape: BuiltinShape2D): void { this.removeShape(shape); if (shape.collider.enabledInHierarchy) { this.addShape(shape); } } - step (deltaTime: number, velocityIterations = 10, positionIterations = 10) { + step (deltaTime: number, velocityIterations = 10, positionIterations = 10): void { // update collider const shapes = this._shapes; for (let i = 0, l = shapes.length; i < l; i++) { @@ -140,7 +140,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { } } - drawDebug () { + drawDebug (): void { if (!this._debugDrawFlags) { return; } @@ -191,7 +191,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { } } - private _emitCollide (contact: BuiltinContact, collisionType?: string) { + private _emitCollide (contact: BuiltinContact, collisionType?: string): void { collisionType = collisionType || contact.type; const c1 = contact.shape1!.collider; @@ -202,7 +202,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { c2.emit(collisionType, c2, c1); } - private _checkDebugDrawValid () { + private _checkDebugDrawValid (): void { if (EDITOR_NOT_IN_PREVIEW) return; if (!this._debugGraphics || !this._debugGraphics.isValid) { let canvas = find('Canvas'); @@ -257,17 +257,17 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { } // empty implements - impl () { + impl (): any { return null; } - setGravity () { } - setAllowSleep () { } - syncPhysicsToScene () { } - syncSceneToPhysics () { } + setGravity (): void { } + setAllowSleep (): void { } + syncPhysicsToScene (): void { } + syncSceneToPhysics (): void { } raycast (p1: IVec2Like, p2: IVec2Like, type: ERaycast2DType): RaycastResult2D[] { return []; } - finalizeContactEvent () { + finalizeContactEvent (): void { } } diff --git a/cocos/physics-2d/builtin/shapes/box-shape-2d.ts b/cocos/physics-2d/builtin/shapes/box-shape-2d.ts index 715cf87f5d2..8b725ceae4b 100644 --- a/cocos/physics-2d/builtin/shapes/box-shape-2d.ts +++ b/cocos/physics-2d/builtin/shapes/box-shape-2d.ts @@ -33,7 +33,7 @@ export class BuiltinBoxShape extends BuiltinShape2D { return this._worldPoints; } - update () { + update (): void { const aabb = this._worldAabb; const collider = this.collider as BoxCollider2D; @@ -62,13 +62,13 @@ export class BuiltinBoxShape extends BuiltinShape2D { aabb.height = maxy - miny; } - containsPoint (p: Vec2) { + containsPoint (p: Vec2): boolean { if (!this.worldAABB.contains(p)) { return false; } return Intersection2D.pointInPolygon(p, this.worldPoints); } - intersectsRect (rect: Rect) { + intersectsRect (rect: Rect): boolean { if (!this.worldAABB.intersects(rect)) { return false; } diff --git a/cocos/physics-2d/builtin/shapes/circle-shape-2d.ts b/cocos/physics-2d/builtin/shapes/circle-shape-2d.ts index 0de30a2dedf..da3e25e05c2 100644 --- a/cocos/physics-2d/builtin/shapes/circle-shape-2d.ts +++ b/cocos/physics-2d/builtin/shapes/circle-shape-2d.ts @@ -37,11 +37,11 @@ export class BuiltinCircleShape extends BuiltinShape2D { } private _worldRadius = 0; - get worldRadius () { + get worldRadius (): number { return this._worldRadius; } - update () { + update (): void { const aabb = this._worldAabb; const collider = this.collider as CircleCollider2D; @@ -69,14 +69,14 @@ export class BuiltinCircleShape extends BuiltinShape2D { aabb.height = d * 2; } - containsPoint (p: Vec2) { + containsPoint (p: Vec2): boolean { if (!this.worldAABB.contains(p)) { return false; } const dist = Vec2.subtract(tempVec2, p, this.worldPosition).length(); return dist < this.worldRadius; } - intersectsRect (rect: Rect) { + intersectsRect (rect: Rect): boolean { if (!this.worldAABB.intersects(rect)) { return false; } diff --git a/cocos/physics-2d/builtin/shapes/polygon-shape-2d.ts b/cocos/physics-2d/builtin/shapes/polygon-shape-2d.ts index 888ca092c00..915d7373cda 100644 --- a/cocos/physics-2d/builtin/shapes/polygon-shape-2d.ts +++ b/cocos/physics-2d/builtin/shapes/polygon-shape-2d.ts @@ -35,7 +35,7 @@ export class BuiltinPolygonShape extends BuiltinShape2D { return this._worldPoints; } - update () { + update (): void { const aabb = this._worldAabb; const collider = this.collider as PolygonCollider2D; @@ -76,13 +76,13 @@ export class BuiltinPolygonShape extends BuiltinShape2D { aabb.height = maxy - miny; } - containsPoint (p: Vec2) { + containsPoint (p: Vec2): boolean { if (!this.worldAABB.contains(p)) { return false; } return Intersection2D.pointInPolygon(p, this.worldPoints); } - intersectsRect (rect: Rect) { + intersectsRect (rect: Rect): boolean { if (!this.worldAABB.intersects(rect)) { return false; } diff --git a/cocos/physics-2d/builtin/shapes/shape-2d.ts b/cocos/physics-2d/builtin/shapes/shape-2d.ts index 29360faced5..cb8bc3368e8 100644 --- a/cocos/physics-2d/builtin/shapes/shape-2d.ts +++ b/cocos/physics-2d/builtin/shapes/shape-2d.ts @@ -35,58 +35,58 @@ export class BuiltinShape2D implements IBaseShape { //contacts contain this Shape public _contacts: BuiltinContact[] = []; - get impl () { + get impl (): null { return null; } - get collider () { + get collider (): Collider2D { return this._collider!; } - apply () { + apply (): void { } - initialize (comp: Collider2D) { + initialize (comp: Collider2D): void { this._collider = comp; } - onLoad () { + onLoad (): void { } - onEnable () { + onEnable (): void { (PhysicsSystem2D.instance.physicsWorld as BuiltinPhysicsWorld).addShape(this); } - onDisable () { + onDisable (): void { (PhysicsSystem2D.instance.physicsWorld as BuiltinPhysicsWorld).removeShape(this); } - start () { + start (): void { } - update () { + update (): void { } get worldAABB (): Readonly { return this._worldAabb; } - containsPoint (p: Vec2) { + containsPoint (p: Vec2): boolean { if (!this.worldAABB.contains(p)) { return false; } return true; } - intersectsRect (rect: Rect) { + intersectsRect (rect: Rect): boolean { if (!this.worldAABB.intersects(rect)) { return false; } return true; } - onGroupChanged () { + onGroupChanged (): void { (PhysicsSystem2D.instance.physicsWorld as BuiltinPhysicsWorld).updateShapeGroup(this); } } diff --git a/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts index f044fa0a196..9feeda73413 100644 --- a/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts @@ -43,7 +43,7 @@ export class BoxCollider2D extends Collider2D { */ @type(Size) @tooltip('i18n:physics2d.collider.size') - get size () { + get size (): Size { return this._size; } set size (v) { diff --git a/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts index 22699791e7f..4d8abd25649 100644 --- a/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts @@ -43,7 +43,7 @@ export class CircleCollider2D extends Collider2D { */ @type(CCFloat) @tooltip('i18n:physics2d.collider.radius') - get radius () { + get radius (): number { return this._radius; } set radius (v) { diff --git a/cocos/physics-2d/framework/components/colliders/collider-2d.ts b/cocos/physics-2d/framework/components/colliders/collider-2d.ts index 5f5b4105318..a314bff8a92 100644 --- a/cocos/physics-2d/framework/components/colliders/collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/collider-2d.ts @@ -73,7 +73,7 @@ export class Collider2D extends Eventify(Component) { */ @type(CCFloat) @tooltip('i18n:physics2d.collider.density') - get density () { + get density (): number { return this._density; } set density (v) { @@ -88,7 +88,7 @@ export class Collider2D extends Eventify(Component) { */ @type(CCBoolean) @tooltip('i18n:physics2d.collider.sensor') - get sensor () { + get sensor (): boolean { return this._sensor; } set sensor (v) { @@ -103,7 +103,7 @@ export class Collider2D extends Eventify(Component) { */ @type(CCFloat) @tooltip('i18n:physics2d.collider.friction') - get friction () { + get friction (): number { return this._friction; } set friction (v) { @@ -118,7 +118,7 @@ export class Collider2D extends Eventify(Component) { */ @type(CCFloat) @tooltip('i18n:physics2d.collider.restitution') - get restitution () { + get restitution (): number { return this._restitution; } set restitution (v) { @@ -130,7 +130,7 @@ export class Collider2D extends Eventify(Component) { */ @type(Vec2) @tooltip('i18n:physics2d.collider.offset') - get offset () { + get offset (): Vec2 { return this._offset; } set offset (v) { @@ -143,11 +143,11 @@ export class Collider2D extends Eventify(Component) { * @zh * 碰撞体会在初始化时查找节点上是否存在刚体,如果查找成功则赋值到这个属性上。 */ - get body () { + get body (): RigidBody2D | null { return this._body; } - get impl () { + get impl (): IBaseShape | null { return this._shape; } @@ -155,7 +155,7 @@ export class Collider2D extends Eventify(Component) { /// COMPONENT LIFECYCLE /// - protected onLoad () { + protected onLoad (): void { if (!EDITOR_NOT_IN_PREVIEW) { this._shape = createShape(this.TYPE); this._shape.initialize(this); @@ -168,19 +168,19 @@ export class Collider2D extends Eventify(Component) { } } - protected onEnable () { + protected onEnable (): void { if (this._shape) { this._shape.onEnable!(); } } - protected onDisable () { + protected onDisable (): void { if (this._shape && this._shape.onDisable) { this._shape.onDisable(); } } - protected onDestroy () { + protected onDestroy (): void { if (this._shape && this._shape.onDestroy) { this._shape.onDestroy(); } @@ -192,7 +192,7 @@ export class Collider2D extends Eventify(Component) { * @zh * 如果物理引擎是 box2d, 需要调用此函数来应用当前 collider 中的修改,调用此函数会重新生成 box2d 的夹具。 */ - apply () { + apply (): void { if (this._shape && this._shape.apply) { this._shape.apply(); } diff --git a/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts index 3a6385178e4..ff7a735d7f6 100644 --- a/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts @@ -48,7 +48,7 @@ export class PolygonCollider2D extends Collider2D { */ @type([Vec2]) @tooltip('i18n:physics2d.collider.points') - get points () { + get points (): Vec2[] { return this._points; } set points (v) { diff --git a/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts b/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts index 625bc0c2538..9ae6d5f968b 100644 --- a/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts @@ -44,7 +44,7 @@ export class DistanceJoint2D extends Joint2D { */ @type(CCFloat) @tooltip('i18n:physics2d.joint.maxLength') - get maxLength () { + get maxLength (): number { if (this._autoCalcDistance) { if (this.connectedBody) { return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition); @@ -69,7 +69,7 @@ export class DistanceJoint2D extends Joint2D { */ @type(CCBoolean) @tooltip('i18n:physics2d.joint.autoCalcDistance') - get autoCalcDistance () { + get autoCalcDistance (): boolean { return this._autoCalcDistance; } set autoCalcDistance (v) { diff --git a/cocos/physics-2d/framework/components/joints/joint-2d.ts b/cocos/physics-2d/framework/components/joints/joint-2d.ts index 78922c09101..57e2d0285a0 100644 --- a/cocos/physics-2d/framework/components/joints/joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/joint-2d.ts @@ -82,11 +82,11 @@ export class Joint2D extends Component { * 关节所绑定的刚体组件。 */ _body: RigidBody2D | null = null - get body () { + get body (): RigidBody2D | null { return this._body; } - get impl () { + get impl (): IJoint2D | null { return this._joint; } @@ -100,7 +100,7 @@ export class Joint2D extends Component { */ TYPE = EJoint2DType.None; - protected onLoad () { + protected onLoad (): void { if (!EDITOR_NOT_IN_PREVIEW) { this._joint = createJoint(this.TYPE); this._joint.initialize(this); @@ -109,25 +109,25 @@ export class Joint2D extends Component { } } - protected onEnable () { + protected onEnable (): void { if (this._joint && this._joint.onEnable) { this._joint.onEnable(); } } - protected onDisable () { + protected onDisable (): void { if (this._joint && this._joint.onDisable) { this._joint.onDisable(); } } - protected start () { + protected start (): void { if (this._joint && this._joint.start) { this._joint.start(); } } - protected onDestroy () { + protected onDestroy (): void { if (this._joint && this._joint.onDestroy) { this._joint.onDestroy(); } diff --git a/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts b/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts index 0ed1424f3f4..4798b1175cc 100644 --- a/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts @@ -36,7 +36,7 @@ const { ccclass, menu, property } = _decorator; export class MouseJoint2D extends Joint2D { TYPE = EJoint2DType.MOUSE; - get target () { + get target (): Vec2 { return this._target; } set target (v) { @@ -100,7 +100,7 @@ export class MouseJoint2D extends Joint2D { } } - update (dt) { + update (dt): void { this._joint!.update!(dt); } diff --git a/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts b/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts index 232bdcef97a..63e87f1e558 100644 --- a/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts @@ -44,7 +44,7 @@ export class SpringJoint2D extends Joint2D { */ @type(CCFloat) @tooltip('i18n:physics2d.joint.frequency') - get frequency () { + get frequency (): number { return this._frequency; } set frequency (v) { @@ -62,7 +62,7 @@ export class SpringJoint2D extends Joint2D { */ @type(CCFloat) @tooltip('i18n:physics2d.joint.dampingRatio') - get dampingRatio () { + get dampingRatio (): number { return this._dampingRatio; } set dampingRatio (v) { @@ -80,7 +80,7 @@ export class SpringJoint2D extends Joint2D { */ @type(CCFloat) @tooltip('i18n:physics2d.joint.distance') - get distance () { + get distance (): number { if (this._autoCalcDistance) { if (this.connectedBody) { return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition); @@ -105,7 +105,7 @@ export class SpringJoint2D extends Joint2D { */ @type(CCBoolean) @tooltip('i18n:physics2d.joint.autoCalcDistance') - get autoCalcDistance () { + get autoCalcDistance (): boolean { return this._autoCalcDistance; } set autoCalcDistance (v) { diff --git a/cocos/physics-2d/framework/components/rigid-body-2d.ts b/cocos/physics-2d/framework/components/rigid-body-2d.ts index 6e10906e9fe..13c5bfeaeb4 100644 --- a/cocos/physics-2d/framework/components/rigid-body-2d.ts +++ b/cocos/physics-2d/framework/components/rigid-body-2d.ts @@ -283,7 +283,7 @@ export class RigidBody2D extends Component { * @zh * 获取刚体是否正在休眠。 */ - isAwake () { + isAwake (): boolean { if (this._body) { return this._body.isAwake; } @@ -297,7 +297,7 @@ export class RigidBody2D extends Component { * @zh * 唤醒刚体。 */ - wakeUp () { + wakeUp (): void { if (this._body) { this._body.wakeUp(); } @@ -309,7 +309,7 @@ export class RigidBody2D extends Component { * @zh * 休眠刚体。 */ - sleep () { + sleep (): void { if (this._body) { this._body.sleep(); } @@ -339,7 +339,7 @@ export class RigidBody2D extends Component { * @param point @en the world position. @zh 世界坐标系下的力的作用点。 * @param wake @en also wake up the body. @zh 唤醒刚体。 */ - applyForce (force: Vec2, point: Vec2, wake: boolean) { + applyForce (force: Vec2, point: Vec2, wake: boolean): void { if (this._body) { this._body.applyForce(force, point, wake); } @@ -353,7 +353,7 @@ export class RigidBody2D extends Component { * @param force @en the world force vector. @zh 世界坐标系下的力。 * @param wake @en also wake up the body. @zh 唤醒刚体。 */ - applyForceToCenter (force: Vec2, wake: boolean) { + applyForceToCenter (force: Vec2, wake: boolean): void { if (this._body) { this._body.applyForceToCenter(force, wake); } @@ -367,7 +367,7 @@ export class RigidBody2D extends Component { * @param torque @en about the z-axis (out of the screen), usually in N-m. @zh 扭矩 N-m。 * @param wake @en also wake up the body @zh 唤醒刚体。 */ - applyTorque (torque: number, wake: boolean) { + applyTorque (torque: number, wake: boolean): void { if (this._body) { this._body.applyTorque(torque, wake); } @@ -385,7 +385,7 @@ export class RigidBody2D extends Component { * @param point @en the world position. @zh 世界坐标系下的作用点。 * @param wake @en also wake up the body. @zh 唤醒刚体。 */ - applyLinearImpulse (impulse: Vec2, point: Vec2, wake: boolean) { + applyLinearImpulse (impulse: Vec2, point: Vec2, wake: boolean): void { if (this._body) { this._body.applyLinearImpulse(impulse, point, wake); } @@ -399,7 +399,7 @@ export class RigidBody2D extends Component { * @param impulse @en the world impulse vector, usually in N-seconds or kg-m/s. @zh 冲量 N-seconds 或者 kg-m/s。 * @param wake @en also wake up the body @zh 唤醒刚体。 */ - applyLinearImpulseToCenter (impulse: Vec2, wake: boolean) { + applyLinearImpulseToCenter (impulse: Vec2, wake: boolean): void { if (this._body) { this._body.applyLinearImpulseToCenter(impulse, wake); } @@ -413,7 +413,7 @@ export class RigidBody2D extends Component { * @param impulse @en the angular impulse in units of kg*m*m/s. @zh 角冲量 kg*m*m/s。 * @param wake @en also wake up the body. @zh 唤醒刚体。 */ - applyAngularImpulse (impulse: number, wake: boolean) { + applyAngularImpulse (impulse: number, wake: boolean): void { if (this._body) { this._body.applyAngularImpulse(impulse, wake); } @@ -531,7 +531,7 @@ export class RigidBody2D extends Component { * @zh * 获取刚体本地坐标系下原点的旋转惯性。 */ - getInertia () { + getInertia (): number { if (this._body) { this._body.getInertia(); } @@ -539,33 +539,33 @@ export class RigidBody2D extends Component { } /// COMPONENT LIFECYCLE /// - protected onLoad () { + protected onLoad (): void { if (!EDITOR_NOT_IN_PREVIEW) { this._body = createRigidBody(); this._body.initialize(this); } } - protected onEnable () { + protected onEnable (): void { if (this._body) { this._body.onEnable!(); } } - protected onDisable () { + protected onDisable (): void { if (this._body) { this._body.onDisable!(); } } - protected onDestroy () { + protected onDestroy (): void { if (this._body) { this._body.onDestroy!(); } } private _body: IRigidBody2D | null = null; - get impl () { + get impl (): IRigidBody2D | null { return this._body; } diff --git a/cocos/physics-2d/framework/physics-selector.ts b/cocos/physics-2d/framework/physics-selector.ts index efee4c03763..3af13810d8a 100644 --- a/cocos/physics-2d/framework/physics-selector.ts +++ b/cocos/physics-2d/framework/physics-selector.ts @@ -118,7 +118,7 @@ function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void { } } -function switchTo (id: IPhysicsEngineId) { +function switchTo (id: IPhysicsEngineId): void { //if (!selector.runInEditor) return; const mutableSelector = selector as Mutable; if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) { @@ -151,7 +151,7 @@ export const selector: IPhysicsSelector = { runInEditor: !EDITOR, }; -const FUNC = (...v: any) => 0 as any; +const FUNC = (...v: any): any => 0 as any; const ENTIRE_WORLD: IPhysicsWorld = { impl: null, debugDrawFlags: 0, @@ -167,7 +167,7 @@ const ENTIRE_WORLD: IPhysicsWorld = { finalizeContactEvent: FUNC, }; -export function checkPhysicsModule (obj: any) { +export function checkPhysicsModule (obj: any): boolean { if (DEBUG && !TEST && !EDITOR_NOT_IN_PREVIEW && obj == null) { errorID(9600); return true; @@ -269,7 +269,7 @@ export function createShape (type: ECollider2DType): IBaseShape { return CREATE_COLLIDER_PROXY[type](); } -function initColliderProxy () { +function initColliderProxy (): void { if (CREATE_COLLIDER_PROXY.INITED) return; CREATE_COLLIDER_PROXY.INITED = true; @@ -324,7 +324,7 @@ export function createJoint (type: EJoint2DType): IJoint2D { return CREATE_JOINT_PROXY[type](); } -function initJointProxy () { +function initJointProxy (): void { if (CREATE_JOINT_PROXY.INITED) return; CREATE_JOINT_PROXY.INITED = true; diff --git a/cocos/physics-2d/framework/physics-system.ts b/cocos/physics-2d/framework/physics-system.ts index 89b9260d9bf..433d41759b0 100644 --- a/cocos/physics-2d/framework/physics-system.ts +++ b/cocos/physics-2d/framework/physics-system.ts @@ -32,6 +32,7 @@ import { CollisionMatrix } from '../../physics/framework/collision-matrix'; import { ERaycast2DType, RaycastResult2D, PHYSICS_2D_PTM_RATIO, PhysicsGroup, Contact2DType } from './physics-types'; import { Collider2D } from './components/colliders/collider-2d'; import { director, Director } from '../../game'; +import type { IPhysicsWorld } from '../spec/i-physics-world'; let instance: PhysicsSystem2D | null = null; cclegacy.internal.PhysicsGroup2D = PhysicsGroup; @@ -88,7 +89,7 @@ export class PhysicsSystem2D extends Eventify(System) { * @zh * 获取或设置每帧模拟的最大子步数。 */ - get maxSubSteps () { + get maxSubSteps (): number { return this._maxSubSteps; } @@ -102,7 +103,7 @@ export class PhysicsSystem2D extends Eventify(System) { * @zh * 获取或设置每步模拟消耗的固定时间。 */ - get fixedTimeStep () { + get fixedTimeStep (): number { return this._fixedTimeStep; } @@ -116,7 +117,7 @@ export class PhysicsSystem2D extends Eventify(System) { * @zh * 获取或设置是否自动模拟。 */ - get autoSimulation () { + get autoSimulation (): boolean { return this._autoSimulation; } @@ -124,7 +125,7 @@ export class PhysicsSystem2D extends Eventify(System) { this._autoSimulation = value; } - get debugDrawFlags () { + get debugDrawFlags (): number { return this.physicsWorld.debugDrawFlags; } set debugDrawFlags (v) { @@ -152,7 +153,7 @@ export class PhysicsSystem2D extends Eventify(System) { * @zh * 获取物理世界的封装对象,通过它你可以访问到实际的底层对象。 */ - public get physicsWorld () { + public get physicsWorld (): IPhysicsWorld { return selector.physicsWorld!; } @@ -164,15 +165,15 @@ export class PhysicsSystem2D extends Eventify(System) { */ static readonly ID = 'PHYSICS_2D'; - static get PHYSICS_NONE () { + static get PHYSICS_NONE (): boolean { return !selector.id; } - static get PHYSICS_BUILTIN () { + static get PHYSICS_BUILTIN (): boolean { return selector.id === 'builtin'; } - static get PHYSICS_BOX2D () { + static get PHYSICS_BOX2D (): boolean { return selector.id === 'box2d'; } @@ -182,7 +183,7 @@ export class PhysicsSystem2D extends Eventify(System) { * @zh * 获取预定义的物理分组。 */ - public static get PhysicsGroup () { + public static get PhysicsGroup (): typeof PhysicsGroup { return PhysicsGroup; } @@ -218,7 +219,7 @@ export class PhysicsSystem2D extends Eventify(System) { private _delayEvents: DelayEvent[] = []; - get stepping () { + get stepping (): boolean { return this._steping; } @@ -247,7 +248,7 @@ export class PhysicsSystem2D extends Eventify(System) { if (collisionGroups) { const cg = collisionGroups; if (cg instanceof Array) { - cg.forEach((v) => { PhysicsGroup[v.name] = 1 << v.index; }); + cg.forEach((v): void => { PhysicsGroup[v.name] = 1 << v.index; }); Enum.update(PhysicsGroup); } } @@ -266,7 +267,7 @@ export class PhysicsSystem2D extends Eventify(System) { * 执行一次物理系统的模拟,目前将在每帧自动执行一次。 * @param deltaTime @en time step. @zh 与上一次执行相差的时间,目前为每帧消耗时间。 */ - postUpdate (deltaTime: number) { + postUpdate (deltaTime: number): void { if (!this._enable) { return; } @@ -311,7 +312,7 @@ export class PhysicsSystem2D extends Eventify(System) { } // eslint-disable-next-line @typescript-eslint/ban-types - _callAfterStep (target: object, func: Function) { + _callAfterStep (target: object, func: Function): void { if (this._steping) { this._delayEvents.push({ target, @@ -328,7 +329,7 @@ export class PhysicsSystem2D extends Eventify(System) { * @zh * 重置时间累积总量为给定值。 */ - resetAccumulator (time = 0) { + resetAccumulator (time = 0): void { this._accumulator = time; } @@ -339,7 +340,7 @@ export class PhysicsSystem2D extends Eventify(System) { * 执行物理世界的模拟步进。 * @param fixedTimeStep */ - step (fixedTimeStep: number) { + step (fixedTimeStep: number): void { this.physicsWorld.step(fixedTimeStep, this.velocityIterations, this.positionIterations); } @@ -384,8 +385,8 @@ export class PhysicsSystem2D extends Eventify(System) { } } -function initPhysicsSystem () { +function initPhysicsSystem (): void { director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, System.Priority.LOW); } -director.once(Director.EVENT_INIT, () => { initPhysicsSystem(); }); +director.once(Director.EVENT_INIT, (): void => { initPhysicsSystem(); }); diff --git a/cocos/physics-2d/framework/utils/polygon-partition.ts b/cocos/physics-2d/framework/utils/polygon-partition.ts index 0017946be71..625900b1b70 100644 --- a/cocos/physics-2d/framework/utils/polygon-partition.ts +++ b/cocos/physics-2d/framework/utils/polygon-partition.ts @@ -35,7 +35,7 @@ import { IVec2Like } from '../../../core'; * @param polygon @en one polygon. @zh 一个多边形。 * @return @en polygon array. @zh 多边形数组。 */ -export function ConvexPartition (polygon: IVec2Like[]) { +export function ConvexPartition (polygon: IVec2Like[]): IVec2Like[][] | null { // We force it to CCW as it is a precondition in this algorithm. ForceCounterClockWise(polygon); @@ -114,20 +114,20 @@ class Vertex { } // Signed area. -function area (a: IVec2Like, b: IVec2Like, c: IVec2Like) { +function area (a: IVec2Like, b: IVec2Like, c: IVec2Like): number { return (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y); } // Whether corner of a counterclockwise polygon is convex. -function isConvex (p1: IVec2Like, p2: IVec2Like, p3: IVec2Like) { +function isConvex (p1: IVec2Like, p2: IVec2Like, p3: IVec2Like): boolean { return area(p1, p2, p3) < 0; } -function equals (a: IVec2Like, b: IVec2Like) { +function equals (a: IVec2Like, b: IVec2Like): boolean { return a.x === b.x && a.y === b.y; } -function isClockwise (polygon: IVec2Like[]) { +function isClockwise (polygon: IVec2Like[]): boolean { let sum = 0; for (let i = 0, len = polygon.length; i < len; ++i) { const p1 = polygon[i]; @@ -138,13 +138,13 @@ function isClockwise (polygon: IVec2Like[]) { } // Forces counter clock wise order. -function ForceCounterClockWise (vertices: IVec2Like[]) { +function ForceCounterClockWise (vertices: IVec2Like[]): void { if (isClockwise(vertices)) { vertices.reverse(); } } -function updateVertex (vertex: Vertex, vertices: Vertex[]) { +function updateVertex (vertex: Vertex, vertices: Vertex[]): void { if (!vertex.shouldUpdate) { return; } @@ -206,7 +206,7 @@ function updateVertex (vertex: Vertex, vertices: Vertex[]) { } } -function removeCollinearOrDuplicate (start: Vertex) { +function removeCollinearOrDuplicate (start: Vertex): void { for (let curr = start, end = start; ;) { if (equals(curr.point!, curr.next!.point!) || area(curr.prev!.point!, curr.point!, curr.next!.point!) === 0) { @@ -229,7 +229,7 @@ function removeCollinearOrDuplicate (start: Vertex) { } // Triangulation by ear clipping. -function Triangulate (polygon: IVec2Like[]) { +function Triangulate (polygon: IVec2Like[]): IVec2Like[][] | null { ForceCounterClockWise(polygon); if (polygon.length < 4) { @@ -255,7 +255,7 @@ function Triangulate (polygon: IVec2Like[]) { vertex.prev = vertices[(i + len - 1) % len]; vertex.next = vertices[(i + 1) % len]; } - vertices.forEach((vertex) => updateVertex(vertex, vertices)); + vertices.forEach((vertex): void => updateVertex(vertex, vertices)); for (let i = 0; i < len - 3; ++i) { let ear; // find the most extruded ear diff --git a/cocos/physics-2d/framework/utils/polygon-separator.ts b/cocos/physics-2d/framework/utils/polygon-separator.ts index 2522dbd698f..3dbd5daf081 100644 --- a/cocos/physics-2d/framework/utils/polygon-separator.ts +++ b/cocos/physics-2d/framework/utils/polygon-separator.ts @@ -39,12 +39,12 @@ import { IVec2Like, Vec2 } from '../../../core'; /// For more information about this algorithm, see http://mnbayazit.com/406/bayazit /// -function At (i: number, vertices: IVec2Like[]) { +function At (i: number, vertices: IVec2Like[]): IVec2Like { const s = vertices.length; return vertices[i < 0 ? s - (-i % s) : i % s]; } -function Copy (i: number, j: number, vertices: IVec2Like[]) { +function Copy (i: number, j: number, vertices: IVec2Like[]): IVec2Like[] { const p: IVec2Like[] = []; while (j < i) j += vertices.length; // p.reserve(j - i + 1); @@ -64,7 +64,7 @@ function Copy (i: number, j: number, vertices: IVec2Like[]) { * @param polygon @en one polygon. @zh 一个多边形。 * @return @en polygon array. @zh 多边形数组。 */ -export function ConvexPartition (vertices: IVec2Like[]) { +export function ConvexPartition (vertices: IVec2Like[]): IVec2Like[][] { // We force it to CCW as it is a precondition in this algorithm. ForceCounterClockWise(vertices); @@ -168,7 +168,7 @@ export function ConvexPartition (vertices: IVec2Like[]) { return list; } -function CanSee (i, j, vertices) { +function CanSee (i, j, vertices): boolean { if (Reflex(i, vertices)) { if (LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices)) && RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices))) return false; @@ -193,11 +193,11 @@ function CanSee (i, j, vertices) { } // precondition: ccw -function Reflex (i: number, vertices: IVec2Like[]) { +function Reflex (i: number, vertices: IVec2Like[]): boolean { return Right(i, vertices); } -function Right (a: number | IVec2Like, b: IVec2Like | IVec2Like[], c?: IVec2Like) { +function Right (a: number | IVec2Like, b: IVec2Like | IVec2Like[], c?: IVec2Like): boolean { if (typeof c === 'undefined') { const i = a as number; const vertices = b as IVec2Like[]; @@ -215,32 +215,32 @@ function Right (a: number | IVec2Like, b: IVec2Like | IVec2Like[], c?: IVec2Like return Area(a as IVec2Like, b as IVec2Like, c) < 0; } -function Left (a: IVec2Like, b: IVec2Like, c: IVec2Like) { +function Left (a: IVec2Like, b: IVec2Like, c: IVec2Like): boolean { return Area(a, b, c) > 0; } -function LeftOn (a: IVec2Like, b: IVec2Like, c: IVec2Like) { +function LeftOn (a: IVec2Like, b: IVec2Like, c: IVec2Like): boolean { return Area(a, b, c) >= 0; } -function RightOn (a: IVec2Like, b: IVec2Like, c: IVec2Like) { +function RightOn (a: IVec2Like, b: IVec2Like, c: IVec2Like): boolean { return Area(a, b, c) <= 0; } -function SquareDist (a: IVec2Like, b: IVec2Like) { +function SquareDist (a: IVec2Like, b: IVec2Like): number { const dx = b.x - a.x; const dy = b.y - a.y; return dx * dx + dy * dy; } // forces counter clock wise order. -export function ForceCounterClockWise (vertices) { +export function ForceCounterClockWise (vertices): void { if (!IsCounterClockWise(vertices)) { vertices.reverse(); } } -export function IsCounterClockWise (vertices) { +export function IsCounterClockWise (vertices): boolean { // We just return true for lines if (vertices.length < 3) return true; @@ -248,7 +248,7 @@ export function IsCounterClockWise (vertices) { } // gets the signed area. -function GetSignedArea (vertices) { +function GetSignedArea (vertices): number { let i; let area = 0; @@ -262,7 +262,7 @@ function GetSignedArea (vertices) { } // From Mark Bayazit's convex decomposition algorithm -function LineIntersect (p1, p2, q1, q2) { +function LineIntersect (p1, p2, q1, q2): Vec2 { const i = new Vec2(); const a1 = p2.y - p1.y; const b1 = p1.x - p2.x; @@ -282,7 +282,7 @@ function LineIntersect (p1, p2, q1, q2) { // from Eric Jordan's convex decomposition library, it checks if the lines a0->a1 and b0->b1 cross. // if they do, intersectionPovar will be filled with the povar of crossing. Grazing lines should not return true. -function LineIntersect2 (a0, a1, b0, b1, intersectionPoint) { +function LineIntersect2 (a0, a1, b0, b1, intersectionPoint): boolean { if (a0 == b0 || a0 == b1 || a1 == b0 || a1 == b1) return false; const x1 = a0.x; @@ -318,11 +318,11 @@ function LineIntersect2 (a0, a1, b0, b1, intersectionPoint) { return false; } -function FloatEquals (value1, value2) { +function FloatEquals (value1, value2): boolean { return Math.abs(value1 - value2) <= 10e-7; } // returns a positive number if c is to the left of the line going from a to b. Positive number if povar is left, negative if povar is right, and 0 if points are collinear. -function Area (a: IVec2Like, b: IVec2Like, c: IVec2Like) { +function Area (a: IVec2Like, b: IVec2Like, c: IVec2Like): number { return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y); } diff --git a/cocos/physics/bullet/bullet-bvh-triangle-mesh-shape.ts b/cocos/physics/bullet/bullet-bvh-triangle-mesh-shape.ts index bb2805268dc..07bf68d24d6 100644 --- a/cocos/physics/bullet/bullet-bvh-triangle-mesh-shape.ts +++ b/cocos/physics/bullet/bullet-bvh-triangle-mesh-shape.ts @@ -29,7 +29,7 @@ import { cocos2BulletTriMesh } from './bullet-utils'; export class BulletBvhTriangleMeshShape { private static readonly BulletBvhTriangleMeshShapeMap = new Map(); - public static getBulletBvhTriangleMeshShape (key: number, mesh: Mesh) { + public static getBulletBvhTriangleMeshShape (key: number, mesh: Mesh): BulletBvhTriangleMeshShape { let newBulletBvhTriangleMeshShape!: BulletBvhTriangleMeshShape; if (BulletBvhTriangleMeshShape.BulletBvhTriangleMeshShapeMap.has(key)) { //can be improved newBulletBvhTriangleMeshShape = BulletBvhTriangleMeshShape.BulletBvhTriangleMeshShapeMap.get(key)!; @@ -60,7 +60,7 @@ export class BulletBvhTriangleMeshShape { this.bulletBvhTriangleMeshShapePtr = bt.BvhTriangleMeshShape_new(this.btTriangleMeshPtr, true, true); } - private destroy () { + private destroy (): void { if (this.bulletBvhTriangleMeshShapePtr) { bt._safe_delete(EBulletType.EBulletTypeCollisionShape, this.bulletBvhTriangleMeshShapePtr); } diff --git a/cocos/physics/bullet/bullet-cache.ts b/cocos/physics/bullet/bullet-cache.ts index 21e8d57cd46..3d9e0f9b3f1 100644 --- a/cocos/physics/bullet/bullet-cache.ts +++ b/cocos/physics/bullet/bullet-cache.ts @@ -43,19 +43,19 @@ export const CollisionEventObject = { export class BulletCache { private static _instance: BulletCache; - static get instance () { + static get instance (): BulletCache { if (BulletCache._instance == null) BulletCache._instance = new BulletCache(); return BulletCache._instance; } static readonly ROOT: { [x: number]: Record } = {}; - static setWrapper (impl: Bullet.ptr, type: string, wrap: any) { + static setWrapper (impl: Bullet.ptr, type: string, wrap: any): void { if (!this.ROOT[type]) this.ROOT[type] = {}; this.ROOT[type][impl] = wrap; } - static delWrapper (impl: Bullet.ptr, type: string) { + static delWrapper (impl: Bullet.ptr, type: string): void { delete this.ROOT[type][impl]; } @@ -63,7 +63,7 @@ export class BulletCache { return this.ROOT[type][ptr] as T; } - static isNotEmptyShape (ptr: Bullet.ptr) { return ptr !== bt.EmptyShape_static(); } + static isNotEmptyShape (ptr: Bullet.ptr): boolean { return ptr !== bt.EmptyShape_static(); } readonly BT_TRANSFORM_0 = bt.Transform_new(); readonly BT_TRANSFORM_1 = bt.Transform_new(); diff --git a/cocos/physics/bullet/bullet-env.ts b/cocos/physics/bullet/bullet-env.ts index d640ce70f0a..096a0fe310f 100644 --- a/cocos/physics/bullet/bullet-env.ts +++ b/cocos/physics/bullet/bullet-env.ts @@ -34,12 +34,12 @@ export const memorySize = pageSize * pageCount; // 16 MiB // The import function used in c++ code, same as DLL Import export const importFunc = { - syncPhysicsToGraphics (id: number) { + syncPhysicsToGraphics (id: number): void { const bt = globalThis.Bullet; const body = bt.CACHE.getWrapper(id, bt.BODY_CACHE_NAME); body.syncPhysicsToGraphics(); }, - onShapeHitExt (hit: number, controller: number) { + onShapeHitExt (hit: number, controller: number): void { const bt = globalThis.Bullet; const cct = bt.CACHE.getWrapper(controller, bt.CCT_CACHE_NAME); cct.onShapeHitExt(hit); diff --git a/cocos/physics/bullet/bullet-rigid-body.ts b/cocos/physics/bullet/bullet-rigid-body.ts index aaa6f04c41b..5b5c84bed64 100644 --- a/cocos/physics/bullet/bullet-rigid-body.ts +++ b/cocos/physics/bullet/bullet-rigid-body.ts @@ -53,26 +53,26 @@ export class BulletRigidBody implements IRigidBody { return state === btCollisionObjectStates.ISLAND_SLEEPING; } - setMass (value: number) { + setMass (value: number): void { if (!this._rigidBody.isDynamic) return; bt.RigidBody_setMass(this.impl, value); this._wakeUpIfSleep(); this._sharedBody.dirty |= EBtSharedBodyDirty.BODY_RE_ADD; } - setType (v: ERigidBodyType) { + setType (v: ERigidBodyType): void { this._sharedBody.setType(v); } - setLinearDamping (value: number) { + setLinearDamping (value: number): void { bt.RigidBody_setDamping(this.impl, this._rigidBody.linearDamping, this._rigidBody.angularDamping); } - setAngularDamping (value: number) { + setAngularDamping (value: number): void { bt.RigidBody_setDamping(this.impl, this._rigidBody.linearDamping, this._rigidBody.angularDamping); } - useGravity (value: boolean) { + useGravity (value: boolean): void { if (!this._rigidBody.isDynamic) return; let m_rigidBodyFlag = bt.RigidBody_getFlags(this.impl); if (value) { @@ -86,27 +86,27 @@ export class BulletRigidBody implements IRigidBody { this._sharedBody.dirty |= EBtSharedBodyDirty.BODY_RE_ADD; } - useCCD (value: boolean) { + useCCD (value: boolean): void { bt.CollisionObject_setCcdMotionThreshold(this.impl, value ? 0.01 : 0); bt.CollisionObject_setCcdSweptSphereRadius(this.impl, value ? 0.1 : 0); this._isUsingCCD = value; } - isUsingCCD () { + isUsingCCD (): boolean { return this._isUsingCCD; } - setLinearFactor (v: IVec3Like) { + setLinearFactor (v: IVec3Like): void { bt.RigidBody_setLinearFactor(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, v)); this._wakeUpIfSleep(); } - setAngularFactor (v: IVec3Like) { + setAngularFactor (v: IVec3Like): void { bt.RigidBody_setAngularFactor(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, v)); this._wakeUpIfSleep(); } - setAllowSleep (v: boolean) { + setAllowSleep (v: boolean): void { if (!this._rigidBody.isDynamic) return; if (v) { bt.CollisionObject_forceActivationState(this.impl, btCollisionObjectStates.ACTIVE_TAG); @@ -119,10 +119,10 @@ export class BulletRigidBody implements IRigidBody { private static idCounter = 0; readonly id: number; - get impl () { return this._sharedBody.body; } - get rigidBody () { return this._rigidBody; } - get sharedBody () { return this._sharedBody; } - get isEnabled () { return this._isEnabled; } + get impl (): number { return this._sharedBody.body; } + get rigidBody (): RigidBody { return this._rigidBody; } + get sharedBody (): BulletSharedBody { return this._sharedBody; } + get isEnabled (): boolean { return this._isEnabled; } private _isEnabled = false; private _isUsingCCD = false; @@ -148,13 +148,13 @@ export class BulletRigidBody implements IRigidBody { /** LIFECYCLE */ - initialize (com: RigidBody) { + initialize (com: RigidBody): void { this._rigidBody = com; this._sharedBody = (PhysicsSystem.instance.physicsWorld as BulletWorld).getSharedBody(this._rigidBody.node, this); this._sharedBody.reference = true; } - onEnable () { + onEnable (): void { this._isEnabled = true; this.setMass(this._rigidBody.mass); this.setAllowSleep(this._rigidBody.allowSleep); @@ -166,12 +166,12 @@ export class BulletRigidBody implements IRigidBody { this._sharedBody.bodyEnabled = true; } - onDisable () { + onDisable (): void { this._isEnabled = false; this._sharedBody.bodyEnabled = false; } - onDestroy () { + onDestroy (): void { this._sharedBody.reference = false; (this._rigidBody as any) = null; (this._sharedBody as any) = null; @@ -316,7 +316,7 @@ export class BulletRigidBody implements IRigidBody { this._sharedBody.collisionFilterMask &= ~v; } - protected _wakeUpIfSleep () { + protected _wakeUpIfSleep (): void { if (!this.isAwake) { bt.CollisionObject_activate(this.impl, true); } } } diff --git a/cocos/physics/bullet/bullet-shared-body.ts b/cocos/physics/bullet/bullet-shared-body.ts index 3bddc758a6f..9e852dc7754 100644 --- a/cocos/physics/bullet/bullet-shared-body.ts +++ b/cocos/physics/bullet/bullet-shared-body.ts @@ -50,7 +50,7 @@ export class BulletSharedBody { private static idCounter = 0; private static readonly sharedBodesMap = new Map(); - static getSharedBody (node: Node, wrappedWorld: BulletWorld, wrappedBody?: BulletRigidBody) { + static getSharedBody (node: Node, wrappedWorld: BulletWorld, wrappedBody?: BulletRigidBody): BulletSharedBody { const key = node.uuid; let newSB!: BulletSharedBody; if (BulletSharedBody.sharedBodesMap.has(key)) { @@ -73,27 +73,27 @@ export class BulletSharedBody { return newSB; } - get wrappedBody () { + get wrappedBody (): BulletRigidBody | null { return this._wrappedBody; } - get bodyCompoundShape () { + get bodyCompoundShape (): number { return this.bodyStruct.compound; } - get ghostCompoundShape () { + get ghostCompoundShape (): number { return this.ghostStruct.compound; } - get body () { + get body (): number { return this.bodyStruct.body; } - get ghost () { + get ghost (): number { return this.ghostStruct.ghost; } - get collisionFilterGroup () { return this._collisionFilterGroup; } + get collisionFilterGroup (): number { return this._collisionFilterGroup; } set collisionFilterGroup (v: number) { if (v !== this._collisionFilterGroup) { this._collisionFilterGroup = v; @@ -102,7 +102,7 @@ export class BulletSharedBody { } } - get collisionFilterMask () { return this._collisionFilterMask; } + get collisionFilterMask (): number { return this._collisionFilterMask; } set collisionFilterMask (v: number) { if (v !== this._collisionFilterMask) { this._collisionFilterMask = v; @@ -111,12 +111,12 @@ export class BulletSharedBody { } } - get bodyStruct () { + get bodyStruct (): IBulletBodyStruct { this._instantiateBodyStruct(); return this._bodyStruct; } - get ghostStruct () { + get ghostStruct (): IBulletGhostStruct { this._instantiateGhostStruct(); return this._ghostStruct; } @@ -198,7 +198,7 @@ export class BulletSharedBody { this.node = node; } - private _instantiateBodyStruct () { + private _instantiateBodyStruct (): void { if (this._bodyStruct) return; let mass = 0; if (this._wrappedBody && this._wrappedBody.rigidBody.enabled && this._wrappedBody.rigidBody.isDynamic) { @@ -223,7 +223,7 @@ export class BulletSharedBody { if (this._wrappedBody) this.setBodyType(this._wrappedBody.rigidBody.type); } - private _instantiateGhostStruct () { + private _instantiateGhostStruct (): void { if (this._ghostStruct) return; const ghost = bt.CollisionObject_new(); const ghostShape = bt.ccCompoundShape_new(); @@ -234,12 +234,12 @@ export class BulletSharedBody { if (this._wrappedBody) this.setGhostType(this._wrappedBody.rigidBody.type); } - setType (v: ERigidBodyType) { + setType (v: ERigidBodyType): void { this.setBodyType(v); this.setGhostType(v); } - setBodyType (v: ERigidBodyType) { + setBodyType (v: ERigidBodyType): void { if (this._bodyStruct && this._wrappedBody) { const body = this._bodyStruct.body; const wrap = this._wrappedBody; @@ -277,7 +277,7 @@ export class BulletSharedBody { } } - setGhostType (v: ERigidBodyType) { + setGhostType (v: ERigidBodyType): void { if (this._ghostStruct) { const ghost = this._ghostStruct.ghost; let m_gcf = bt.CollisionObject_getCollisionFlags(ghost); @@ -301,8 +301,8 @@ export class BulletSharedBody { } } - addShape (v: BulletShape, isTrigger: boolean) { - function switchShape (that: BulletSharedBody, shape: Bullet.ptr) { + addShape (v: BulletShape, isTrigger: boolean): void { + function switchShape (that: BulletSharedBody, shape: Bullet.ptr): void { bt.CollisionObject_setCollisionShape(that.body, shape); that.dirty |= EBtSharedBodyDirty.BODY_RE_ADD; if (that._wrappedBody && that._wrappedBody.isEnabled) { @@ -341,7 +341,7 @@ export class BulletSharedBody { } } - removeShape (v: BulletShape, isTrigger: boolean) { + removeShape (v: BulletShape, isTrigger: boolean): void { if (isTrigger) { const index = this.ghostStruct.wrappedShapes.indexOf(v); if (index >= 0) { @@ -365,7 +365,7 @@ export class BulletSharedBody { } } - addJoint (v: BulletConstraint, type: 0 | 1) { + addJoint (v: BulletConstraint, type: 0 | 1): void { if (type) { const i = this.wrappedJoints1.indexOf(v); if (i < 0) this.wrappedJoints1.push(v); @@ -375,7 +375,7 @@ export class BulletSharedBody { } } - removeJoint (v: BulletConstraint, type: 0 | 1) { + removeJoint (v: BulletConstraint, type: 0 | 1): void { if (type) { const i = this.wrappedJoints1.indexOf(v); if (i >= 0) js.array.fastRemoveAt(this.wrappedJoints1, i); @@ -385,7 +385,7 @@ export class BulletSharedBody { } } - updateDirty () { + updateDirty (): void { if (this.dirty) { if (this.bodyIndex >= 0 && this.dirty & EBtSharedBodyDirty.BODY_RE_ADD) this.updateBodyByReAdd(); if (this.ghostIndex >= 0 && this.dirty & EBtSharedBodyDirty.GHOST_RE_ADD) this.updateGhostByReAdd(); @@ -393,7 +393,7 @@ export class BulletSharedBody { } } - syncSceneToPhysics () { + syncSceneToPhysics (): void { if (this.node.hasChangedFlags) { const bt_quat = BulletCache.instance.BT_QUAT_0; const bt_transform = bt.CollisionObject_getWorldTransform(this.body); @@ -413,12 +413,12 @@ export class BulletSharedBody { } } - syncPhysicsToScene () { + syncPhysicsToScene (): void { if (bt.CollisionObject_isStaticOrKinematicObject(this.body)) return; this.syncPhysicsToGraphics(); } - syncPhysicsToGraphics () { + syncPhysicsToGraphics (): void { if (this.isBodySleeping()) return; const bt_quat = BulletCache.instance.BT_QUAT_0; const bt_transform = BulletCache.instance.BT_TRANSFORM_0; @@ -436,7 +436,7 @@ export class BulletSharedBody { } } - syncSceneToGhost () { + syncSceneToGhost (): void { if (this.node.hasChangedFlags) { const bt_quat = BulletCache.instance.BT_QUAT_0; const bt_transform = bt.CollisionObject_getWorldTransform(this.ghost); @@ -448,7 +448,7 @@ export class BulletSharedBody { } } - syncInitialBody () { + syncInitialBody (): void { const bt_quat = BulletCache.instance.BT_QUAT_0; const bt_transform = bt.CollisionObject_getWorldTransform(this.body); cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition); @@ -458,7 +458,7 @@ export class BulletSharedBody { bt.CollisionObject_activate(this.body); } - syncInitialGhost () { + syncInitialGhost (): void { const bt_quat = BulletCache.instance.BT_QUAT_0; const bt_transform = bt.CollisionObject_getWorldTransform(this.ghost); cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition); @@ -468,7 +468,7 @@ export class BulletSharedBody { bt.CollisionObject_activate(this.body); } - syncBodyScale () { + syncBodyScale (): void { for (let i = 0; i < this.bodyStruct.wrappedShapes.length; i++) { this.bodyStruct.wrappedShapes[i].updateScale(); } @@ -480,7 +480,7 @@ export class BulletSharedBody { } } - syncGhostScale () { + syncGhostScale (): void { for (let i = 0; i < this.ghostStruct.wrappedShapes.length; i++) { this.ghostStruct.wrappedShapes[i].updateScale(); } @@ -489,7 +489,7 @@ export class BulletSharedBody { /** * see: https://pybullet.org/Bullet/phpBB3/viewtopic.php?f=9&t=5312&p=19094&hilit=how+to+change+group+mask#p19097 */ - updateBodyByReAdd () { + updateBodyByReAdd (): void { if (this.bodyIndex >= 0) { this.wrappedWorld.removeSharedBody(this); this.bodyIndex = this.wrappedWorld.bodies.length; @@ -497,7 +497,7 @@ export class BulletSharedBody { } } - updateGhostByReAdd () { + updateGhostByReAdd (): void { if (this.ghostIndex >= 0) { this.wrappedWorld.removeGhostObject(this); this.ghostIndex = this.wrappedWorld.ghosts.length; @@ -505,7 +505,7 @@ export class BulletSharedBody { } } - private destroy () { + private destroy (): void { BulletSharedBody.sharedBodesMap.delete(this.node.uuid); (this.node as any) = null; (this.wrappedWorld as any) = null; @@ -526,7 +526,7 @@ export class BulletSharedBody { } } - private isBodySleeping () { + private isBodySleeping (): boolean { return bt.CollisionObject_getActivationState(this.body) === btCollisionObjectStates.ISLAND_SLEEPING; } } diff --git a/cocos/physics/bullet/bullet-utils.ts b/cocos/physics/bullet/bullet-utils.ts index d4d27d3b1b2..28625f031f3 100644 --- a/cocos/physics/bullet/bullet-utils.ts +++ b/cocos/physics/bullet/bullet-utils.ts @@ -106,10 +106,10 @@ export function cocos2BulletTriMesh (out: Bullet.ptr, mesh: Mesh): any { return out; } -export function force2Impulse (force: number, dt: number) { +export function force2Impulse (force: number, dt: number): number { return force * dt; } -export function impulse2Force (impulse: number, dt: number) { +export function impulse2Force (impulse: number, dt: number): number { return impulse / dt; } diff --git a/cocos/physics/bullet/bullet-world.ts b/cocos/physics/bullet/bullet-world.ts index a2238445991..f10a5f454a2 100644 --- a/cocos/physics/bullet/bullet-world.ts +++ b/cocos/physics/bullet/bullet-world.ts @@ -45,17 +45,17 @@ const v3_1 = CC_V3_1; const v3_2 = CC_V3_2; const emitHit = new CharacterControllerContact(); export class BulletWorld implements IPhysicsWorld { - setDefaultMaterial (v: PhysicsMaterial) { } + setDefaultMaterial (v: PhysicsMaterial): void { } - setAllowSleep (v: boolean) { + setAllowSleep (v: boolean): void { bt.ccDiscreteDynamicsWorld_setAllowSleep(this._world, v); } - setGravity (gravity: IVec3Like) { + setGravity (gravity: IVec3Like): void { bt.DynamicsWorld_setGravity(this._world, cocos2BulletVec3(BulletCache.instance.BT_V3_0, gravity)); } - updateNeedEmitEvents (v: boolean) { + updateNeedEmitEvents (v: boolean): void { if (!this.ghosts) return; // return if destroyed if (v) { this._needEmitEvents = true; @@ -87,7 +87,7 @@ export class BulletWorld implements IPhysicsWorld { } } - updateNeedEmitCCTEvents (force: boolean) { + updateNeedEmitCCTEvents (force: boolean): void { if (!this.ccts) return; // return if already been removed from bullet world if (force) { this._needEmitCCTEvents = true; @@ -105,7 +105,7 @@ export class BulletWorld implements IPhysicsWorld { } } - get impl () { + get impl (): Bullet.ptr { return this._world; } @@ -158,7 +158,7 @@ export class BulletWorld implements IPhysicsWorld { contactsPool.length = 0; } - step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep = 0) { + step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep = 0): void { if (!this.bodies.length && !this.ghosts.length && !this.ccts.length) return; if (timeSinceLastCalled === undefined) timeSinceLastCalled = deltaTime; bt.DynamicsWorld_stepSimulation(this._world, timeSinceLastCalled, maxSubStep, deltaTime); @@ -374,11 +374,11 @@ export class BulletWorld implements IPhysicsWorld { return false; } - getSharedBody (node: Node, wrappedBody?: BulletRigidBody) { + getSharedBody (node: Node, wrappedBody?: BulletRigidBody): BulletSharedBody { return BulletSharedBody.getSharedBody(node, this, wrappedBody); } - addSharedBody (sharedBody: BulletSharedBody) { + addSharedBody (sharedBody: BulletSharedBody): void { const i = this.bodies.indexOf(sharedBody); if (i < 0) { this.bodies.push(sharedBody); @@ -386,7 +386,7 @@ export class BulletWorld implements IPhysicsWorld { } } - removeSharedBody (sharedBody: BulletSharedBody) { + removeSharedBody (sharedBody: BulletSharedBody): void { const i = this.bodies.indexOf(sharedBody); if (i >= 0) { js.array.fastRemoveAt(this.bodies, i); @@ -394,7 +394,7 @@ export class BulletWorld implements IPhysicsWorld { } } - addGhostObject (sharedBody: BulletSharedBody) { + addGhostObject (sharedBody: BulletSharedBody): void { const i = this.ghosts.indexOf(sharedBody); if (i < 0) { this.ghosts.push(sharedBody); @@ -402,7 +402,7 @@ export class BulletWorld implements IPhysicsWorld { } } - removeGhostObject (sharedBody: BulletSharedBody) { + removeGhostObject (sharedBody: BulletSharedBody): void { const i = this.ghosts.indexOf(sharedBody); if (i >= 0) { js.array.fastRemoveAt(this.ghosts, i); @@ -430,7 +430,7 @@ export class BulletWorld implements IPhysicsWorld { } } - addConstraint (constraint: BulletConstraint) { + addConstraint (constraint: BulletConstraint): void { const i = this.constraints.indexOf(constraint); if (i < 0) { this.constraints.push(constraint); @@ -439,7 +439,7 @@ export class BulletWorld implements IPhysicsWorld { } } - removeConstraint (constraint: BulletConstraint) { + removeConstraint (constraint: BulletConstraint): void { const i = this.constraints.indexOf(constraint); if (i >= 0) { this.constraints.splice(i, 1); @@ -448,7 +448,7 @@ export class BulletWorld implements IPhysicsWorld { } } - emitEvents () { + emitEvents (): void { this._needSyncAfterEvents = false; if (this._needEmitEvents) { @@ -605,7 +605,7 @@ export class BulletWorld implements IPhysicsWorld { } } - gatherConatactData () { + gatherConatactData (): void { const numManifolds = bt.Dispatcher_getNumManifolds(this._dispatcher); for (let i = 0; i < numManifolds; i++) { const manifold = bt.Dispatcher_getManifoldByIndexInternal(this._dispatcher, i);//btPersistentManifold diff --git a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts index e4c52a04f81..19135648145 100644 --- a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts +++ b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts @@ -81,7 +81,7 @@ export abstract class BulletCharacterController implements IBaseCharacterControl } } - setWrapper () { + setWrapper (): void { BulletCache.setWrapper(this._impl, bt.CCT_CACHE_NAME, this); } @@ -172,16 +172,16 @@ export abstract class BulletCharacterController implements IBaseCharacterControl this._comp.node.setWorldPosition(v3_0); } - syncScale () { + syncScale (): void { this.updateScale(); } - get scaledCenter () { + get scaledCenter (): Vec3 { Vec3.multiply(v3_1, this._comp.center, this._comp.node.worldScale); return v3_1; } - move (movement: IVec3Like, minDist: number, elapsedTime: number) { + move (movement: IVec3Like, minDist: number, elapsedTime: number): void { if (!this._isEnabled) { return; } const movementBT = BulletCache.instance.BT_V3_0; bt.Vec3_set(movementBT, movement.x, movement.y, movement.z); @@ -230,12 +230,12 @@ export abstract class BulletCharacterController implements IBaseCharacterControl this._dirty = true; } - updateEventListener () { + updateEventListener (): void { this.wrappedWorld.updateNeedEmitCCTEvents(this.characterController.needCollisionEvent); } // update group and mask by re-adding cct to physics world - updateDirty () { + updateDirty (): void { if (this._dirty) { (PhysicsSystem.instance.physicsWorld as BulletWorld).removeCCT(this); (PhysicsSystem.instance.physicsWorld as BulletWorld).addCCT(this); @@ -243,7 +243,7 @@ export abstract class BulletCharacterController implements IBaseCharacterControl } } - onShapeHitExt (hit: number) { + onShapeHitExt (hit: number): void { const shapePtr = bt.ControllerShapeHit_getHitShape(hit); const bulletWorld = (PhysicsSystem.instance.physicsWorld as BulletWorld); //use characterController impl and shape impl pair as key diff --git a/cocos/physics/bullet/constraints/bullet-configurable-constraint.ts b/cocos/physics/bullet/constraints/bullet-configurable-constraint.ts index ed9182edbeb..9bcc11ee483 100644 --- a/cocos/physics/bullet/constraints/bullet-configurable-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-configurable-constraint.ts @@ -184,7 +184,7 @@ export class BulletConfigurableConstraint extends BulletConstraint implements IC } } - _updateMotorTargetAndVelocity (index: number) { + _updateMotorTargetAndVelocity (index: number): void { let mode = EDriverMode.DISABLED; let axis = 0; let target = 0; @@ -305,7 +305,7 @@ export class BulletConfigurableConstraint extends BulletConstraint implements IC return this._com as ConfigurableConstraint; } - onComponentSet () { + onComponentSet (): void { const cb = this.constraint.connectedBody; const bodyA = (this._rigidBody.body as BulletRigidBody).impl; const bodyB = (cb && (cb.body as BulletRigidBody).impl) || bt.TypedConstraint_getFixedBody(); @@ -362,7 +362,7 @@ export class BulletConfigurableConstraint extends BulletConstraint implements IC this.updateFrames(); } - updateFrames () { + updateFrames (): void { const cs = this.constraint; const node = cs.node; const v3_0 = CC_V3_0; diff --git a/cocos/physics/bullet/constraints/bullet-constraint.ts b/cocos/physics/bullet/constraints/bullet-constraint.ts index b061ff9a2b4..4676a79fdfd 100644 --- a/cocos/physics/bullet/constraints/bullet-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-constraint.ts @@ -66,7 +66,7 @@ export abstract class BulletConstraint implements IBaseConstraint { } } - get impl () { + get impl (): number { return this._impl; } @@ -83,7 +83,7 @@ export abstract class BulletConstraint implements IBaseConstraint { protected _connectedBody: RigidBody | null = null; protected _collided = false; - updateByReAdd () { + updateByReAdd (): void { if (this._rigidBody && this.index >= 0) { const sb = (this._rigidBody.body as BulletRigidBody).sharedBody; sb.wrappedWorld.removeConstraint(this); diff --git a/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts b/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts index 3c8b550b66d..afdc2567432 100644 --- a/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-fixed-constraint.ts @@ -45,7 +45,7 @@ export class BulletFixedConstraint extends BulletConstraint implements IFixedCon return this._com as FixedConstraint; } - onComponentSet () { + onComponentSet (): void { const cb = this.constraint.connectedBody; const bodyA = (this._rigidBody.body as BulletRigidBody).impl; const bodyB = cb ? (cb.body as BulletRigidBody).impl : bt.TypedConstraint_getFixedBody(); @@ -57,7 +57,7 @@ export class BulletFixedConstraint extends BulletConstraint implements IFixedCon this.updateFrames(); } - updateFrames () { + updateFrames (): void { const cb = this.constraint.connectedBody; const bodyA = (this._rigidBody.body as BulletRigidBody).sharedBody; @@ -94,11 +94,11 @@ export class BulletFixedConstraint extends BulletConstraint implements IFixedCon bt.FixedConstraint_setFrames(this._impl, trans0, trans1); } - updateScale0 () { + updateScale0 (): void { this.updateFrames(); } - updateScale1 () { + updateScale1 (): void { this.updateFrames(); } } diff --git a/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts b/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts index b33a0c3d23d..b11fde4a362 100644 --- a/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts @@ -42,7 +42,7 @@ export class BulletHingeConstraint extends BulletConstraint implements IHingeCon this.updateFrames(); } - setAxis (v: IVec3Like) { + setAxis (v: IVec3Like): void { this.updateFrames(); } @@ -87,7 +87,7 @@ export class BulletHingeConstraint extends BulletConstraint implements IHingeCon return this._com as HingeConstraint; } - onComponentSet () { + onComponentSet (): void { const cb = this.constraint.connectedBody; const bodyA = (this._rigidBody.body as BulletRigidBody).impl; const bodyB = cb ? (cb.body as BulletRigidBody).impl : bt.TypedConstraint_getFixedBody(); @@ -104,7 +104,7 @@ export class BulletHingeConstraint extends BulletConstraint implements IHingeCon this.updateFrames(); } - updateFrames () { + updateFrames (): void { const cs = this.constraint; const node = cs.node; const v3_0 = CC_V3_0; @@ -145,11 +145,11 @@ export class BulletHingeConstraint extends BulletConstraint implements IHingeCon bt.HingeConstraint_setFrames(this._impl, trans0, trans1); } - updateScale0 () { + updateScale0 (): void { this.updateFrames(); } - updateScale1 () { + updateScale1 (): void { this.updateFrames(); } } diff --git a/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts b/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts index 6ece8df7956..248e4125c09 100644 --- a/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts @@ -74,11 +74,11 @@ export class BulletP2PConstraint extends BulletConstraint implements IPointToPoi this.setPivotB(this.constraint.pivotB); } - updateScale0 () { + updateScale0 (): void { this.setPivotA(this.constraint.pivotA); } - updateScale1 () { + updateScale1 (): void { this.setPivotB(this.constraint.pivotB); } } diff --git a/cocos/physics/bullet/instantiated.ts b/cocos/physics/bullet/instantiated.ts index 3f3d9b16c10..4faeb8030a7 100644 --- a/cocos/physics/bullet/instantiated.ts +++ b/cocos/physics/bullet/instantiated.ts @@ -69,7 +69,7 @@ globalThis.Bullet = bt; bt.BODY_CACHE_NAME = 'body'; bt.CCT_CACHE_NAME = 'cct'; -function initWasm (wasmUrl: string, importObject: WebAssembly.Imports) { +function initWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { console.debug('[Physics][Bullet]: Using wasm Bullet libs.'); return instantiateWasm(wasmUrl, importObject).then((results) => { const btInstance = results.instance.exports as Bullet.instance; @@ -77,7 +77,7 @@ function initWasm (wasmUrl: string, importObject: WebAssembly.Imports) { }); } -function initAsm (resolve) { +function initAsm (resolve): void { console.debug('[Physics][Bullet]: Using asmjs Bullet libs.'); const env: any = importFunc; const wasmMemory: any = {}; @@ -89,7 +89,7 @@ function initAsm (resolve) { } function getImportObject (): WebAssembly.Imports { - const infoReport = (msg: any) => { console.info(msg); }; + const infoReport = (msg: any): void => { console.info(msg); }; const memory = new WebAssembly.Memory({ initial: pageCount }); const importObject = { cc: importFunc, @@ -113,9 +113,9 @@ if (!FORCE_BANNING_BULLET_WASM) { } } -export function waitForAmmoInstantiation () { +export function waitForAmmoInstantiation (): Promise { return new Promise((resolve) => { - const errorReport = (msg: any) => { console.error(msg); }; + const errorReport = (msg: any): void => { console.error(msg); }; if (FORCE_BANNING_BULLET_WASM) { initAsm(resolve); } else if (WASM_SUPPORT_MODE === WebAssemblySupportMode.MAYBE_SUPPORT) { diff --git a/cocos/physics/bullet/shapes/bullet-box-shape.ts b/cocos/physics/bullet/shapes/bullet-box-shape.ts index 7b9e4f462e3..f6dca66e9b3 100644 --- a/cocos/physics/bullet/shapes/bullet-box-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-box-shape.ts @@ -33,32 +33,32 @@ import { BulletCache } from '../bullet-cache'; import { bt } from '../instantiated'; export class BulletBoxShape extends BulletShape implements IBoxShape { - updateSize () { + updateSize (): void { const hf = BulletCache.instance.BT_V3_0; cocos2BulletVec3(hf, this.getMinUnscaledHalfExtents(VEC3_0)); bt.BoxShape_setUnscaledHalfExtents(this.impl, hf); this.updateCompoundTransform(); } - get collider () { + get collider (): BoxCollider { return this._collider as BoxCollider; } - onComponentSet () { + onComponentSet (): void { const hf = BulletCache.instance.BT_V3_0; cocos2BulletVec3(hf, this.getMinUnscaledHalfExtents(VEC3_0)); this._impl = bt.BoxShape_new(hf); this.updateScale(); } - updateScale () { + updateScale (): void { super.updateScale(); const bt_v3 = BulletCache.instance.BT_V3_0; bt.CollisionShape_setLocalScaling(this._impl, cocos2BulletVec3(bt_v3, this.getMinScale(VEC3_0))); this.updateCompoundTransform(); } - getMinUnscaledHalfExtents (out: Vec3) { + getMinUnscaledHalfExtents (out: Vec3): Vec3 { const size = this.collider.size; const ws = absolute(VEC3_0.set(this._collider.node.worldScale)); const minVolumeSize = PhysicsSystem.instance.minVolumeSize; @@ -70,7 +70,7 @@ export class BulletBoxShape extends BulletShape implements IBoxShape { return out; } - getMinScale (out: Vec3) { + getMinScale (out: Vec3): Vec3 { const size = this.collider.size; const ws = absolute(VEC3_0.set(this._collider.node.worldScale)); const minVolumeSize = PhysicsSystem.instance.minVolumeSize; diff --git a/cocos/physics/bullet/shapes/bullet-capsule-shape.ts b/cocos/physics/bullet/shapes/bullet-capsule-shape.ts index b2fe17e8911..8635b83618e 100644 --- a/cocos/physics/bullet/shapes/bullet-capsule-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-capsule-shape.ts @@ -29,7 +29,7 @@ import { ICapsuleShape } from '../../spec/i-physics-shape'; import { bt } from '../instantiated'; export class BulletCapsuleShape extends BulletShape implements ICapsuleShape { - setCylinderHeight (v: number) { + setCylinderHeight (v: number): void { this.updateProperties( this.collider.radius, this.collider.cylinderHeight, @@ -38,7 +38,7 @@ export class BulletCapsuleShape extends BulletShape implements ICapsuleShape { ); } - setDirection (v: number) { + setDirection (v: number): void { this.updateProperties( this.collider.radius, this.collider.cylinderHeight, @@ -47,7 +47,7 @@ export class BulletCapsuleShape extends BulletShape implements ICapsuleShape { ); } - setRadius (v: number) { + setRadius (v: number): void { this.updateProperties( this.collider.radius, this.collider.cylinderHeight, @@ -56,21 +56,21 @@ export class BulletCapsuleShape extends BulletShape implements ICapsuleShape { ); } - get collider () { + get collider (): CapsuleCollider { return this._collider as CapsuleCollider; } - onComponentSet () { + onComponentSet (): void { this._impl = bt.CapsuleShape_new(0.5, 1); this.setRadius(this.collider.radius); } - updateScale () { + updateScale (): void { super.updateScale(); this.setRadius(this.collider.radius); } - updateProperties (radius: number, height: number, direction: number, scale: IVec3Like) { + updateProperties (radius: number, height: number, direction: number, scale: IVec3Like): void { const ws = scale; const upAxis = direction; let wr: number; let halfH: number; diff --git a/cocos/physics/bullet/shapes/bullet-cone-shape.ts b/cocos/physics/bullet/shapes/bullet-cone-shape.ts index 73de1a3cc57..ab7ce0a0e57 100644 --- a/cocos/physics/bullet/shapes/bullet-cone-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-cone-shape.ts @@ -30,7 +30,7 @@ import { bt } from '../instantiated'; import { BulletCache } from '../bullet-cache'; export class BulletConeShape extends BulletShape implements ICylinderShape { - setHeight (v: number) { + setHeight (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -39,7 +39,7 @@ export class BulletConeShape extends BulletShape implements ICylinderShape { ); } - setDirection (v: number) { + setDirection (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -48,7 +48,7 @@ export class BulletConeShape extends BulletShape implements ICylinderShape { ); } - setRadius (v: number) { + setRadius (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -57,25 +57,25 @@ export class BulletConeShape extends BulletShape implements ICylinderShape { ); } - get impl () { + get impl (): number { return this._impl; } - get collider () { + get collider (): ConeCollider { return this._collider as ConeCollider; } - onComponentSet () { + onComponentSet (): void { this._impl = bt.ConeShape_new(0.5, 1); this.setRadius(this.collider.radius); } - updateScale () { + updateScale (): void { super.updateScale(); this.setRadius(this.collider.radius); } - updateProperties (radius: number, height: number, direction: number, scale: IVec3Like) { + updateProperties (radius: number, height: number, direction: number, scale: IVec3Like): void { const ws = scale; const upAxis = direction; let wr: number; let wh: number; diff --git a/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts b/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts index 2a03fbef3f1..1aa8913b270 100644 --- a/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts @@ -30,7 +30,7 @@ import { BulletCache } from '../bullet-cache'; import { bt } from '../instantiated'; export class BulletCylinderShape extends BulletShape implements ICylinderShape { - setHeight (v: number) { + setHeight (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -39,7 +39,7 @@ export class BulletCylinderShape extends BulletShape implements ICylinderShape { ); } - setDirection (v: number) { + setDirection (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -48,7 +48,7 @@ export class BulletCylinderShape extends BulletShape implements ICylinderShape { ); } - setRadius (v: number) { + setRadius (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -57,23 +57,23 @@ export class BulletCylinderShape extends BulletShape implements ICylinderShape { ); } - get collider () { + get collider (): CylinderCollider { return this._collider as CylinderCollider; } - onComponentSet () { + onComponentSet (): void { const bt_v3 = BulletCache.instance.BT_V3_0; bt.Vec3_set(bt_v3, 0.5, 1, 0.5); this._impl = bt.CylinderShape_new(bt_v3); this.setRadius(this.collider.radius); } - updateScale () { + updateScale (): void { super.updateScale(); this.setRadius(this.collider.radius); } - updateProperties (radius: number, height: number, direction: number, scale: IVec3Like) { + updateProperties (radius: number, height: number, direction: number, scale: IVec3Like): void { const ws = scale; const upAxis = direction; let wr: number; let wh: number; diff --git a/cocos/physics/bullet/shapes/bullet-plane-shape.ts b/cocos/physics/bullet/shapes/bullet-plane-shape.ts index f16739ed99c..8c1bf9a8534 100644 --- a/cocos/physics/bullet/shapes/bullet-plane-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-plane-shape.ts @@ -31,17 +31,17 @@ import { BulletCache } from '../bullet-cache'; import { bt } from '../instantiated'; export class BulletPlaneShape extends BulletShape implements IPlaneShape { - setNormal (v: IVec3Like) { + setNormal (v: IVec3Like): void { cocos2BulletVec3(bt.StaticPlaneShape_getPlaneNormal(this.impl), v); this.updateCompoundTransform(); } - setConstant (v: number) { + setConstant (v: number): void { bt.StaticPlaneShape_setPlaneConstant(this.impl, v); this.updateCompoundTransform(); } - updateScale () { + updateScale (): void { super.updateScale(); const bt_v3 = BulletCache.instance.BT_V3_0; cocos2BulletVec3(bt_v3, this._collider.node.worldScale); @@ -49,11 +49,11 @@ export class BulletPlaneShape extends BulletShape implements IPlaneShape { this.updateCompoundTransform(); } - get collider () { + get collider (): PlaneCollider { return this._collider as PlaneCollider; } - onComponentSet () { + onComponentSet (): void { const normal = BulletCache.instance.BT_V3_0; cocos2BulletVec3(normal, this.collider.normal); this._impl = bt.StaticPlaneShape_new(normal, this.collider.constant); diff --git a/cocos/physics/bullet/shapes/bullet-shape.ts b/cocos/physics/bullet/shapes/bullet-shape.ts index fc81046fb72..0989df94de7 100644 --- a/cocos/physics/bullet/shapes/bullet-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-shape.ts @@ -23,7 +23,7 @@ */ import { Vec3, IVec3Like, geometry } from '../../../core'; -import { Collider, PhysicsMaterial, PhysicsSystem } from '../../../../exports/physics-framework'; +import { Collider, PhysicsMaterial, PhysicsSystem, RigidBody } from '../../../../exports/physics-framework'; import { BulletWorld } from '../bullet-world'; import { EBtSharedBodyDirty } from '../bullet-enum'; import { cocos2BulletQuat, cocos2BulletVec3 } from '../bullet-utils'; @@ -40,7 +40,7 @@ export abstract class BulletShape implements IBaseShape { this._sharedBody.wrappedWorld.updateNeedEmitEvents(this.collider.needCollisionEvent || this.collider.needTriggerEvent); } - setMaterial (v: PhysicsMaterial | null) { + setMaterial (v: PhysicsMaterial | null): void { const v1 = (v == null) ? PhysicsSystem.instance.defaultMaterial : v; if (!this._isTrigger && this._isEnabled) { if (this._compound) { @@ -54,14 +54,14 @@ export abstract class BulletShape implements IBaseShape { } } - setCenter (v: IVec3Like) { + setCenter (v: IVec3Like): void { Vec3.copy(v3_0, v); v3_0.multiply(this._collider.node.worldScale); cocos2BulletVec3(bt.Transform_getOrigin(this.transform), v3_0); this.updateCompoundTransform(); } - setAsTrigger (v: boolean) { + setAsTrigger (v: boolean): void { if (this._isTrigger === v) return; if (this._isEnabled) { @@ -71,12 +71,12 @@ export abstract class BulletShape implements IBaseShape { this._isTrigger = v; } - get attachedRigidBody () { + get attachedRigidBody (): RigidBody | null { if (this._sharedBody.wrappedBody) return this._sharedBody.wrappedBody.rigidBody; return null; } - get impl () { return this._impl; } + get impl (): number { return this._impl; } get collider (): Collider { return this._collider; } get sharedBody (): BulletSharedBody { return this._sharedBody; } @@ -93,7 +93,7 @@ export abstract class BulletShape implements IBaseShape { protected _collider!: Collider; protected _sharedBody!: BulletSharedBody; - getAABB (v: geometry.AABB) { + getAABB (v: geometry.AABB): void { const bt_transform = BulletCache.instance.BT_TRANSFORM_0; bt.Transform_setIdentity(bt_transform); bt.Transform_setRotation(bt_transform, cocos2BulletQuat(BulletCache.instance.BT_QUAT_0, this._collider.node.worldRotation)); @@ -106,12 +106,12 @@ export abstract class BulletShape implements IBaseShape { Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center); } - getBoundingSphere (v: geometry.Sphere) { + getBoundingSphere (v: geometry.Sphere): void { v.radius = bt.CollisionShape_getLocalBoundingSphere(this._impl); Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center); } - initialize (com: Collider) { + initialize (com: Collider): void { this._collider = com; this._isInitialized = true; this._sharedBody = (PhysicsSystem.instance.physicsWorld as BulletWorld).getSharedBody(this._collider.node); @@ -120,7 +120,7 @@ export abstract class BulletShape implements IBaseShape { this.setWrapper(); } - setWrapper () { + setWrapper (): void { if (BulletCache.isNotEmptyShape(this._impl)) { bt.CollisionShape_setUserPointer(this._impl, this._impl); BulletCache.setWrapper(this._impl, BulletShape.TYPE, this); @@ -130,24 +130,24 @@ export abstract class BulletShape implements IBaseShape { // virtual protected abstract onComponentSet(): void; - onLoad () { + onLoad (): void { this.setCenter(this._collider.center); this.setAsTrigger(this._collider.isTrigger); } - onEnable () { + onEnable (): void { this._isEnabled = true; this._sharedBody.addShape(this, this._isTrigger); this.setMaterial(this.collider.sharedMaterial); } - onDisable () { + onDisable (): void { this._isEnabled = false; this._sharedBody.removeShape(this, this._isTrigger); } - onDestroy () { + onDestroy (): void { this._sharedBody.reference = false; (this._collider as any) = null; bt._safe_delete(this.quat, EBulletType.EBulletTypeQuat); @@ -159,7 +159,7 @@ export abstract class BulletShape implements IBaseShape { } } - updateByReAdd () { + updateByReAdd (): void { if (this._isEnabled) { this._sharedBody.removeShape(this, this._isTrigger); this._sharedBody.addShape(this, this._isTrigger); @@ -198,17 +198,17 @@ export abstract class BulletShape implements IBaseShape { this._sharedBody.collisionFilterMask &= ~v; } - setCompound (compound: Bullet.ptr) { + setCompound (compound: Bullet.ptr): void { if (this._compound) bt.CompoundShape_removeChildShape(this._compound, this._impl); if (compound) bt.CompoundShape_addChildShape(compound, this.transform, this._impl); this._compound = compound; } - updateScale () { + updateScale (): void { this.setCenter(this._collider.center); } - updateCompoundTransform () { + updateCompoundTransform (): void { if (this._compound) { bt.CompoundShape_updateChildTransform(this._compound, this._impl, this.transform, true); } else if (this._isEnabled && !this._isTrigger) { @@ -218,7 +218,7 @@ export abstract class BulletShape implements IBaseShape { } } - needCompound () { + needCompound (): boolean { if (this._collider.type === EColliderType.TERRAIN) { return true; } if (this._collider.center.equals(Vec3.ZERO)) { return false; } return true; diff --git a/cocos/physics/bullet/shapes/bullet-simplex-shape.ts b/cocos/physics/bullet/shapes/bullet-simplex-shape.ts index 877f7c0e618..12e212910d3 100644 --- a/cocos/physics/bullet/shapes/bullet-simplex-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-simplex-shape.ts @@ -31,19 +31,19 @@ import { bt } from '../instantiated'; import { BulletCache } from '../bullet-cache'; export class BulletSimplexShape extends BulletShape implements ISimplexShape { - setShapeType (v: SimplexCollider.ESimplexType) { + setShapeType (v: SimplexCollider.ESimplexType): void { // TODO: } - setVertices (v: IVec3Like[]) { + setVertices (v: IVec3Like[]): void { // TODO: } - get collider () { + get collider (): SimplexCollider { return this._collider as SimplexCollider; } - protected onComponentSet () { + protected onComponentSet (): void { this._impl = bt.SimplexShape_new(); const length = this.collider.shapeType; const vertices = this.collider.vertices; @@ -54,12 +54,12 @@ export class BulletSimplexShape extends BulletShape implements ISimplexShape { bt.CollisionShape_setLocalScaling(this._impl, cocos2BulletVec3(bt_v3, this._collider.node.worldScale)); } - onLoad () { + onLoad (): void { super.onLoad(); this.collider.updateVertices(); } - updateScale () { + updateScale (): void { super.updateScale(); const bt_v3 = BulletCache.instance.BT_V3_0; bt.CollisionShape_setLocalScaling(this._impl, cocos2BulletVec3(bt_v3, this._collider.node.worldScale)); diff --git a/cocos/physics/bullet/shapes/bullet-sphere-shape.ts b/cocos/physics/bullet/shapes/bullet-sphere-shape.ts index f1d5c0c73c2..bf075dccca7 100644 --- a/cocos/physics/bullet/shapes/bullet-sphere-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-sphere-shape.ts @@ -31,21 +31,21 @@ import { bt } from '../instantiated'; import { absMaxComponent } from '../../../core'; export class BulletSphereShape extends BulletShape implements ISphereShape { - updateRadius () { + updateRadius (): void { bt.SphereShape_setUnscaledRadius(this.impl, this.getMinUnscaledRadius()); this.updateCompoundTransform(); } - get collider () { + get collider (): SphereCollider { return this._collider as SphereCollider; } - onComponentSet () { + onComponentSet (): void { this._impl = bt.SphereShape_new(this.getMinUnscaledRadius()); this.updateScale(); } - updateScale () { + updateScale (): void { super.updateScale(); const scale = this.getMinScale(); CC_V3_0.set(scale, scale, scale); @@ -54,14 +54,14 @@ export class BulletSphereShape extends BulletShape implements ISphereShape { this.updateCompoundTransform(); } - getMinUnscaledRadius () { + getMinUnscaledRadius (): number { const radius = this.collider.radius; const ws = Math.abs(absMaxComponent(this._collider.node.worldScale)); const minVolumeSize = PhysicsSystem.instance.minVolumeSize; return ws * radius < minVolumeSize ? minVolumeSize / ws : radius; } - getMinScale () { + getMinScale (): number { const radius = this.collider.radius; const ws = Math.abs(absMaxComponent(this._collider.node.worldScale)); const minVolumeSize = PhysicsSystem.instance.minVolumeSize; diff --git a/cocos/physics/bullet/shapes/bullet-terrain-shape.ts b/cocos/physics/bullet/shapes/bullet-terrain-shape.ts index 8d7b6002602..71b9674073c 100644 --- a/cocos/physics/bullet/shapes/bullet-terrain-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-terrain-shape.ts @@ -32,7 +32,7 @@ import { CC_V3_0, BulletCache } from '../bullet-cache'; import { bt } from '../instantiated'; export class BulletTerrainShape extends BulletShape implements ITerrainShape { - public get collider () { + public get collider (): TerrainCollider { return this._collider as TerrainCollider; } @@ -80,16 +80,16 @@ export class BulletTerrainShape extends BulletShape implements ITerrainShape { private _tileSize = 0; private _localOffset = new Vec3(); - onComponentSet () { + onComponentSet (): void { this.setTerrain(this.collider.terrain); } - onDestroy () { + onDestroy (): void { if (this._bufPtr) bt._free(this._bufPtr); super.onDestroy(); } - setCenter (v: IVec3Like) { + setCenter (v: IVec3Like): void { Vec3.copy(CC_V3_0, v); CC_V3_0.add(this._localOffset); // CC_V3_0.multiply(this._collider.node.worldScale); diff --git a/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts b/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts index 0fe6f75f4b0..8893c1fbffc 100644 --- a/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts @@ -34,11 +34,11 @@ import { BulletBvhTriangleMeshShape } from '../bullet-bvh-triangle-mesh-shape'; export class BulletTrimeshShape extends BulletShape implements ITrimeshShape { private btBVHMeshShape; - public get collider () { + public get collider (): MeshCollider { return this._collider as MeshCollider; } - setMesh (v: Mesh | null) { + setMesh (v: Mesh | null): void { if (!this._isInitialized) return; if (this._impl && BulletCache.isNotEmptyShape(this._impl)) { @@ -69,11 +69,11 @@ export class BulletTrimeshShape extends BulletShape implements ITrimeshShape { private refBtTriangleMesh: Bullet.ptr = 0; - onComponentSet () { + onComponentSet (): void { this.setMesh(this.collider.mesh); } - onDestroy () { + onDestroy (): void { if (this.collider.convex) { if (this.refBtTriangleMesh) { bt._safe_delete(this.refBtTriangleMesh, EBulletType.EBulletTypeTriangleMesh); @@ -84,7 +84,7 @@ export class BulletTrimeshShape extends BulletShape implements ITrimeshShape { super.onDestroy(); } - updateScale () { + updateScale (): void { super.updateScale(); const bt_v3 = BulletCache.instance.BT_V3_0; cocos2BulletVec3(bt_v3, this._collider.node.worldScale); diff --git a/cocos/physics/cannon/cannon-rigid-body.ts b/cocos/physics/cannon/cannon-rigid-body.ts index 4f04ec8fddf..a484fbc3732 100644 --- a/cocos/physics/cannon/cannon-rigid-body.ts +++ b/cocos/physics/cannon/cannon-rigid-body.ts @@ -51,20 +51,20 @@ export class CannonRigidBody implements IRigidBody { return this.impl.isSleeping(); } - setAllowSleep (v: boolean) { + setAllowSleep (v: boolean): void { if (this.impl.type !== CANNON.Body.DYNAMIC) return; this.impl.allowSleep = v; this._wakeUpIfSleep(); } - setMass (value: number) { + setMass (value: number): void { if (this.impl.type !== CANNON.Body.DYNAMIC) return; this.impl.mass = value; this.impl.updateMassProperties(); this._wakeUpIfSleep(); } - setType (v: ERigidBodyType) { + setType (v: ERigidBodyType): void { switch (v) { case ERigidBodyType.DYNAMIC: this.impl.type = CANNON.Body.DYNAMIC; @@ -89,33 +89,33 @@ export class CannonRigidBody implements IRigidBody { } } - setLinearDamping (value: number) { + setLinearDamping (value: number): void { this.impl.linearDamping = value; } - setAngularDamping (value: number) { + setAngularDamping (value: number): void { this.impl.angularDamping = value; } - useGravity (value: boolean) { + useGravity (value: boolean): void { this.impl.useGravity = value; this._wakeUpIfSleep(); } - useCCD (value:boolean) { + useCCD (value:boolean): void { this.impl.ccdSpeedThreshold = value ? 0.01 : -1; } - isUsingCCD () { + isUsingCCD (): boolean { return this.impl.ccdSpeedThreshold !== -1; } - setLinearFactor (value: IVec3Like) { + setLinearFactor (value: IVec3Like): void { Vec3.copy(this.impl.linearFactor, value); this._wakeUpIfSleep(); } - setAngularFactor (value: IVec3Like) { + setAngularFactor (value: IVec3Like): void { Vec3.copy(this.impl.angularFactor, value); const fixR = Vec3.equals(this.impl.angularFactor, Vec3.ZERO); if (fixR !== this.impl.fixedRotation) { @@ -125,19 +125,19 @@ export class CannonRigidBody implements IRigidBody { this._wakeUpIfSleep(); } - get impl () { + get impl (): CANNON.Body { return this._sharedBody.body; } - get rigidBody () { + get rigidBody (): RigidBody { return this._rigidBody; } - get sharedBody () { + get sharedBody (): CannonSharedBody { return this._sharedBody; } - get isEnabled () { + get isEnabled (): boolean { return this._isEnabled; } @@ -148,17 +148,17 @@ export class CannonRigidBody implements IRigidBody { /** LIFECYCLE */ - initialize (com: RigidBody) { + initialize (com: RigidBody): void { this._rigidBody = com; this._sharedBody = (PhysicsSystem.instance.physicsWorld as CannonWorld).getSharedBody(this._rigidBody.node, this); this._sharedBody.reference = true; this._sharedBody.wrappedBody = this; } - onLoad () { + onLoad (): void { } - onEnable () { + onEnable (): void { this._isEnabled = true; this.setType(this._rigidBody.type); this.setMass(this._rigidBody.mass); @@ -171,12 +171,12 @@ export class CannonRigidBody implements IRigidBody { this._sharedBody.enabled = true; } - onDisable () { + onDisable (): void { this._isEnabled = false; this._sharedBody.enabled = false; } - onDestroy () { + onDestroy (): void { this._sharedBody.reference = false; (this._rigidBody as any) = null; (this._sharedBody as any) = null; @@ -207,12 +207,12 @@ export class CannonRigidBody implements IRigidBody { return this.impl.sleep(); } - setSleepThreshold (v: number) { + setSleepThreshold (v: number): void { this.impl.sleepSpeedLimit = v; this._wakeUpIfSleep(); } - getSleepThreshold () { + getSleepThreshold (): any { return this.impl.sleepSpeedLimit; } @@ -236,14 +236,14 @@ export class CannonRigidBody implements IRigidBody { Vec3.copy(this.impl.angularVelocity, value); } - applyForce (force: Vec3, worldPoint?: Vec3) { + applyForce (force: Vec3, worldPoint?: Vec3): void { this._sharedBody.syncSceneToPhysics(); this._wakeUpIfSleep(); if (worldPoint == null) worldPoint = Vec3.ZERO as Vec3; this.impl.applyForce(Vec3.copy(v3_cannon0, force), Vec3.copy(v3_cannon1, worldPoint)); } - applyImpulse (impulse: Vec3, worldPoint?: Vec3) { + applyImpulse (impulse: Vec3, worldPoint?: Vec3): void { this._sharedBody.syncSceneToPhysics(); this._wakeUpIfSleep(); if (worldPoint == null) worldPoint = Vec3.ZERO as Vec3; @@ -318,7 +318,7 @@ export class CannonRigidBody implements IRigidBody { this._wakeUpIfSleep(); } - protected _wakeUpIfSleep () { + protected _wakeUpIfSleep (): void { if (!this.impl.isAwake()) this.impl.wakeUp(); } } diff --git a/cocos/physics/cannon/cannon-shared-body.ts b/cocos/physics/cannon/cannon-shared-body.ts index 40aa339013d..e4d478ae310 100644 --- a/cocos/physics/cannon/cannon-shared-body.ts +++ b/cocos/physics/cannon/cannon-shared-body.ts @@ -55,7 +55,7 @@ const CollisionEventObject = { export class CannonSharedBody { private static readonly sharedBodesMap = new Map(); - static getSharedBody (node: Node, wrappedWorld: CannonWorld, wrappedBody?: CannonRigidBody) { + static getSharedBody (node: Node, wrappedWorld: CannonWorld, wrappedBody?: CannonRigidBody): CannonSharedBody { const key = node.uuid; let newSB: CannonSharedBody; if (CannonSharedBody.sharedBodesMap.has(key)) { @@ -135,7 +135,7 @@ export class CannonSharedBody { this.body.addEventListener('cc-collide', this.onCollidedListener); } - addShape (v: CannonShape) { + addShape (v: CannonShape): void { const index = this.wrappedShapes.indexOf(v); if (index < 0) { const index = this.body.shapes.length; @@ -150,7 +150,7 @@ export class CannonSharedBody { } } - removeShape (v: CannonShape) { + removeShape (v: CannonShape): void { const index = this.wrappedShapes.indexOf(v); if (index >= 0) { js.array.fastRemoveAt(this.wrappedShapes, index); @@ -160,7 +160,7 @@ export class CannonSharedBody { } } - addJoint (v: CannonConstraint, type: 0 | 1) { + addJoint (v: CannonConstraint, type: 0 | 1): void { if (type) { const i = this.wrappedJoints1.indexOf(v); if (i < 0) this.wrappedJoints1.push(v); @@ -170,7 +170,7 @@ export class CannonSharedBody { } } - removeJoint (v: CannonConstraint, type: 0 | 1) { + removeJoint (v: CannonConstraint, type: 0 | 1): void { if (type) { const i = this.wrappedJoints1.indexOf(v); if (i >= 0) js.array.fastRemoveAt(this.wrappedJoints1, i); @@ -180,7 +180,7 @@ export class CannonSharedBody { } } - syncSceneToPhysics () { + syncSceneToPhysics (): void { const node = this.node; const body = this.body; if (node.hasChangedFlags) { @@ -192,7 +192,7 @@ export class CannonSharedBody { } } - syncPhysicsToScene () { + syncPhysicsToScene (): void { const n = this.node; const b = this.body; if (b.type === ERigidBodyType.DYNAMIC) { @@ -205,7 +205,7 @@ export class CannonSharedBody { } } - syncInitial () { + syncInitial (): void { const n = this.node; const b = this.body; Vec3.copy(b.position, n.worldPosition); @@ -217,7 +217,7 @@ export class CannonSharedBody { if (b.isSleeping()) b.wakeUp(); } - syncScale () { + syncScale (): void { for (let i = 0; i < this.wrappedShapes.length; i++) { this.wrappedShapes[i].setScale(this.node.worldScale); } @@ -230,7 +230,7 @@ export class CannonSharedBody { commitShapeUpdates(this.body); } - private destroy () { + private destroy (): void { setWrap(this.body, null); this.body.removeEventListener('cc-collide', this.onCollidedListener); CannonSharedBody.sharedBodesMap.delete(this.node.uuid); @@ -244,7 +244,7 @@ export class CannonSharedBody { (this.onCollidedListener as any) = null; } - private onCollided (event: CANNON.ICollisionEvent) { + private onCollided (event: CANNON.ICollisionEvent): void { CollisionEventObject.type = event.event; const self = getWrap(event.selfShape); const other = getWrap(event.otherShape); diff --git a/cocos/physics/cannon/cannon-util.ts b/cocos/physics/cannon/cannon-util.ts index 29d8f42d105..742e7d325e1 100644 --- a/cocos/physics/cannon/cannon-util.ts +++ b/cocos/physics/cannon/cannon-util.ts @@ -28,14 +28,14 @@ import { IBaseShape } from '../spec/i-physics-shape'; import { PhysicsRayResult } from '../framework'; import { IRaycastOptions } from '../spec/i-physics-world'; -export function toCannonRaycastOptions (out: CANNON.IRaycastOptions, options: IRaycastOptions) { +export function toCannonRaycastOptions (out: CANNON.IRaycastOptions, options: IRaycastOptions): void { out.checkCollisionResponse = !options.queryTrigger; out.collisionFilterGroup = -1; out.collisionFilterMask = options.mask; // out.skipBackfaces = true; } -export function fillRaycastResult (result: PhysicsRayResult, cannonResult: CANNON.RaycastResult) { +export function fillRaycastResult (result: PhysicsRayResult, cannonResult: CANNON.RaycastResult): void { result._assign( cannonResult.hitPointWorld, cannonResult.distance, @@ -44,7 +44,7 @@ export function fillRaycastResult (result: PhysicsRayResult, cannonResult: CANNO ); } -export function commitShapeUpdates (body: CANNON.Body) { +export function commitShapeUpdates (body: CANNON.Body): void { body.aabbNeedsUpdate = true; body.updateMassProperties(); body.updateBoundingRadius(); diff --git a/cocos/physics/cannon/cannon-world.ts b/cocos/physics/cannon/cannon-world.ts index 3d830d56fdf..03b271d7aed 100644 --- a/cocos/physics/cannon/cannon-world.ts +++ b/cocos/physics/cannon/cannon-world.ts @@ -34,11 +34,11 @@ import { CannonRigidBody } from './cannon-rigid-body'; import { Node } from '../../scene-graph'; export class CannonWorld implements IPhysicsWorld { - get impl () { + get impl (): CANNON.World { return this._world; } - setDefaultMaterial (mat: PhysicsMaterial) { + setDefaultMaterial (mat: PhysicsMaterial): void { this._world.defaultMaterial.friction = mat.friction; this._world.defaultMaterial.restitution = mat.restitution; if (CannonShape.idToMaterial[mat.id] != null) { @@ -46,11 +46,11 @@ export class CannonWorld implements IPhysicsWorld { } } - setAllowSleep (v: boolean) { + setAllowSleep (v: boolean): void { this._world.allowSleep = v; } - setGravity (gravity: IVec3Like) { + setGravity (gravity: IVec3Like): void { Vec3.copy(this._world.gravity, gravity); } @@ -133,7 +133,7 @@ export class CannonWorld implements IPhysicsWorld { this.syncSceneToPhysics(); } - step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep?: number) { + step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep?: number): void { if (this.bodies.length === 0) return; this._world.step(deltaTime, timeSinceLastCalled, maxSubStep); @@ -168,7 +168,7 @@ export class CannonWorld implements IPhysicsWorld { return CannonSharedBody.getSharedBody(node, this, wrappedBody); } - addSharedBody (sharedBody: CannonSharedBody) { + addSharedBody (sharedBody: CannonSharedBody): void { const i = this.bodies.indexOf(sharedBody); if (i < 0) { this.bodies.push(sharedBody); @@ -176,7 +176,7 @@ export class CannonWorld implements IPhysicsWorld { } } - removeSharedBody (sharedBody: CannonSharedBody) { + removeSharedBody (sharedBody: CannonSharedBody): void { const i = this.bodies.indexOf(sharedBody); if (i >= 0) { js.array.fastRemoveAt(this.bodies, i); @@ -188,7 +188,7 @@ export class CannonWorld implements IPhysicsWorld { // this._cannonWorld.addContactMaterial(contactMaterial._getImpl()); // } - addConstraint (constraint: CannonConstraint) { + addConstraint (constraint: CannonConstraint): void { const i = this.constraints.indexOf(constraint); if (i < 0) { this.constraints.push(constraint); @@ -196,7 +196,7 @@ export class CannonWorld implements IPhysicsWorld { } } - removeConstraint (constraint: CannonConstraint) { + removeConstraint (constraint: CannonConstraint): void { const i = this.constraints.indexOf(constraint); if (i >= 0) { js.array.fastRemoveAt(this.constraints, i); @@ -207,7 +207,7 @@ export class CannonWorld implements IPhysicsWorld { const from = new CANNON.Vec3(); const to = new CANNON.Vec3(); -function setupFromAndTo (worldRay: geometry.Ray, distance: number) { +function setupFromAndTo (worldRay: geometry.Ray, distance: number): void { Vec3.copy(from, worldRay.o); worldRay.computeHit(to, distance); } diff --git a/cocos/physics/cannon/constraints/cannon-constraint.ts b/cocos/physics/cannon/constraints/cannon-constraint.ts index b3d121ebe99..13a2caa8857 100644 --- a/cocos/physics/cannon/constraints/cannon-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-constraint.ts @@ -70,8 +70,8 @@ export class CannonConstraint implements IBaseConstraint { this._impl.collideConnected = v; } - get impl () { return this._impl; } - get constraint () { return this._com; } + get impl (): CANNON.Constraint { return this._impl; } + get constraint (): Constraint { return this._com; } protected _impl!: CANNON.Constraint; protected _com!: Constraint; @@ -88,13 +88,13 @@ export class CannonConstraint implements IBaseConstraint { } // virtual - protected onComponentSet () { } + protected onComponentSet (): void { } // virtual - updateScale0 () { } - updateScale1 () { } + updateScale0 (): void { } + updateScale1 (): void { } - onEnable () { + onEnable (): void { const sb = (this._rigidBody.body as CannonRigidBody).sharedBody; sb.wrappedWorld.addConstraint(this); sb.addJoint(this, 0); @@ -105,7 +105,7 @@ export class CannonConstraint implements IBaseConstraint { } } - onDisable () { + onDisable (): void { const sb = (this._rigidBody.body as CannonRigidBody).sharedBody; sb.wrappedWorld.removeConstraint(this); sb.removeJoint(this, 0); @@ -116,7 +116,7 @@ export class CannonConstraint implements IBaseConstraint { } } - onDestroy () { + onDestroy (): void { delete (CANNON.World as any).idToConstraintMap[this._impl.id]; (this._com as any) = null; (this._rigidBody as any) = null; diff --git a/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts b/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts index 057be382b8c..8e36fe127dc 100644 --- a/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts @@ -33,11 +33,11 @@ const v3_0 = new Vec3(); const quat_0 = new Quat(); export class CannonHingeConstraint extends CannonConstraint implements IHingeConstraint { - public get impl () { + public get impl (): CANNON.HingeConstraint { return this._impl as CANNON.HingeConstraint; } - public get constraint () { + public get constraint (): HingeConstraint { return this._com as HingeConstraint; } @@ -101,7 +101,7 @@ export class CannonHingeConstraint extends CannonConstraint implements IHingeCon warnID(9613); } - onComponentSet () { + onComponentSet (): void { const bodyA = (this._rigidBody.body as CannonRigidBody).impl; const cb = this.constraint.connectedBody; let bodyB: CANNON.Body = (CANNON.World as any).staticBody; @@ -114,11 +114,11 @@ export class CannonHingeConstraint extends CannonConstraint implements IHingeCon this.setAxis(this.constraint.axis); } - updateScale0 () { + updateScale0 (): void { this.setPivotA(this.constraint.pivotA); } - updateScale1 () { + updateScale1 (): void { this.setPivotB(this.constraint.pivotB); } } diff --git a/cocos/physics/cannon/constraints/cannon-lock-constraint.ts b/cocos/physics/cannon/constraints/cannon-lock-constraint.ts index ac827839ccd..c5edcd8dd3b 100644 --- a/cocos/physics/cannon/constraints/cannon-lock-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-lock-constraint.ts @@ -40,7 +40,7 @@ export class CannonLockConstraint extends CannonConstraint implements IFixedCons // not supported } - public get impl () { + public get impl (): CANNON.LockConstraint { return this._impl as CANNON.LockConstraint; } diff --git a/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts b/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts index 7b3d9b55b8c..5b7e784e024 100644 --- a/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts @@ -32,11 +32,11 @@ import { CannonRigidBody } from '../cannon-rigid-body'; const v3_0 = new Vec3(); export class CannonPointToPointConstraint extends CannonConstraint implements IPointToPointConstraint { - public get impl () { + public get impl (): CANNON.PointToPointConstraint { return this._impl as CANNON.PointToPointConstraint; } - public get constraint () { + public get constraint (): PointToPointConstraint { return this._com as PointToPointConstraint; } @@ -60,7 +60,7 @@ export class CannonPointToPointConstraint extends CannonConstraint implements IP } } - onComponentSet () { + onComponentSet (): void { const bodyA = (this._rigidBody.body as CannonRigidBody).impl; const cb = this.constraint.connectedBody; let bodyB: CANNON.Body = (CANNON.World as any).staticBody; @@ -72,11 +72,11 @@ export class CannonPointToPointConstraint extends CannonConstraint implements IP this.setPivotB(this.constraint.pivotB); } - updateScale0 () { + updateScale0 (): void { this.setPivotA(this.constraint.pivotA); } - updateScale1 () { + updateScale1 (): void { this.setPivotB(this.constraint.pivotB); } } diff --git a/cocos/physics/cannon/shapes/cannon-box-shape.ts b/cocos/physics/cannon/shapes/cannon-box-shape.ts index 461d131ea87..023ed776c75 100644 --- a/cocos/physics/cannon/shapes/cannon-box-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-box-shape.ts @@ -31,11 +31,11 @@ import { BoxCollider, PhysicsSystem } from '../../../../exports/physics-framewor import { absolute, VEC3_0 } from '../../utils/util'; export class CannonBoxShape extends CannonShape implements IBoxShape { - public get collider () { + public get collider (): BoxCollider { return this._collider as BoxCollider; } - public get impl () { + public get impl (): CANNON.Box { return this._shape as CANNON.Box; } @@ -46,7 +46,7 @@ export class CannonBoxShape extends CannonShape implements IBoxShape { this._shape = new CANNON.Box(this.halfExtent.clone()); } - updateSize () { + updateSize (): void { Vec3.multiplyScalar(this.halfExtent, this.collider.size, 0.5); const ws = absolute(VEC3_0.set(this.collider.node.worldScale)); const x = this.halfExtent.x * ws.x; @@ -62,7 +62,7 @@ export class CannonBoxShape extends CannonShape implements IBoxShape { } } - onLoad () { + onLoad (): void { super.onLoad(); this.updateSize(); } diff --git a/cocos/physics/cannon/shapes/cannon-cone-shape.ts b/cocos/physics/cannon/shapes/cannon-cone-shape.ts index 9c6a078829b..ad2ca71e8e7 100644 --- a/cocos/physics/cannon/shapes/cannon-cone-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-cone-shape.ts @@ -34,15 +34,15 @@ const v3_0 = new Vec3(); const v3_1 = new Vec3(); export class CannonConeShape extends CannonShape implements IConeShape { - get collider () { + get collider (): ConeCollider { return this._collider as ConeCollider; } - get impl () { + get impl (): CANNON.Cylinder { return this._shape as CANNON.Cylinder; } - setRadius (v: number) { + setRadius (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -54,7 +54,7 @@ export class CannonConeShape extends CannonShape implements IConeShape { if (this._index !== -1) commitShapeUpdates(this._body); } - setHeight (v: number) { + setHeight (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -66,7 +66,7 @@ export class CannonConeShape extends CannonShape implements IConeShape { if (this._index !== -1) commitShapeUpdates(this._body); } - setDirection (v: number) { + setDirection (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -83,7 +83,7 @@ export class CannonConeShape extends CannonShape implements IConeShape { this._shape = new CANNON.Cylinder(0, radius, height, (CANNON as any).CC_CONFIG.numSegmentsCone, direction === EAxisDirection.Y_AXIS); } - onLoad () { + onLoad (): void { super.onLoad(); this.setRadius(this.collider.radius); } @@ -93,7 +93,7 @@ export class CannonConeShape extends CannonShape implements IConeShape { this.setRadius(this.collider.radius); } - updateProperties (radius: number, height: number, numSegments: number, direction: number, scale: IVec3Like) { + updateProperties (radius: number, height: number, numSegments: number, direction: number, scale: IVec3Like): void { let wh = height; let wr = radius; const cos = Math.cos; diff --git a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts index 22f27b2eb59..5f4f1ac913d 100644 --- a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts @@ -31,15 +31,15 @@ import { EAxisDirection } from '../../framework/physics-enum'; import { commitShapeUpdates } from '../cannon-util'; export class CannonCylinderShape extends CannonShape implements ICylinderShape { - get collider () { + get collider (): CylinderCollider { return this._collider as CylinderCollider; } - get impl () { + get impl (): CANNON.Cylinder { return this._shape as CANNON.Cylinder; } - setRadius (v: number) { + setRadius (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -51,7 +51,7 @@ export class CannonCylinderShape extends CannonShape implements ICylinderShape { if (this._index !== -1) commitShapeUpdates(this._body); } - setHeight (v: number) { + setHeight (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -63,7 +63,7 @@ export class CannonCylinderShape extends CannonShape implements ICylinderShape { if (this._index !== -1) commitShapeUpdates(this._body); } - setDirection (v: number) { + setDirection (v: number): void { this.updateProperties( this.collider.radius, this.collider.height, @@ -80,7 +80,7 @@ export class CannonCylinderShape extends CannonShape implements ICylinderShape { this._shape = new CANNON.Cylinder(radius, radius, height, (CANNON as any).CC_CONFIG.numSegmentsCylinder, direction === EAxisDirection.Y_AXIS); } - onLoad () { + onLoad (): void { super.onLoad(); this.setRadius(this.collider.radius); } @@ -90,7 +90,7 @@ export class CannonCylinderShape extends CannonShape implements ICylinderShape { this.setRadius(this.collider.radius); } - updateProperties (radius: number, height: number, numSegments: number, direction: number, scale: IVec3Like) { + updateProperties (radius: number, height: number, numSegments: number, direction: number, scale: IVec3Like): void { let wh = height; let wr = radius; const cos = Math.cos; diff --git a/cocos/physics/cannon/shapes/cannon-plane-shape.ts b/cocos/physics/cannon/shapes/cannon-plane-shape.ts index 66c94a8bad6..246d2684a4c 100644 --- a/cocos/physics/cannon/shapes/cannon-plane-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-plane-shape.ts @@ -30,11 +30,11 @@ import { IPlaneShape } from '../../spec/i-physics-shape'; import { PlaneCollider } from '../../../../exports/physics-framework'; export class CannonPlaneShape extends CannonShape implements IPlaneShape { - public get collider () { + public get collider (): PlaneCollider { return this._collider as PlaneCollider; } - public get impl () { + public get impl (): CANNON.Plane { return this._shape as CANNON.Plane; } @@ -43,24 +43,24 @@ export class CannonPlaneShape extends CannonShape implements IPlaneShape { this._shape = new CANNON.Plane(); } - setNormal (v: IVec3Like) { + setNormal (v: IVec3Like): void { Quat.rotationTo(this._orient, Vec3.UNIT_Z, v); if (this._index !== -1) { commitShapeUpdates(this._body); } } - setConstant (v: number) { + setConstant (v: number): void { Vec3.scaleAndAdd(this._offset, this._collider.center, this.collider.normal, v); } - onLoad () { + onLoad (): void { super.onLoad(); this.setConstant(this.collider.constant); this.setNormal(this.collider.normal); } - _setCenter (v: IVec3Like) { + _setCenter (v: IVec3Like): void { super._setCenter(v); this.setConstant(this.collider.constant); } diff --git a/cocos/physics/cannon/shapes/cannon-shape.ts b/cocos/physics/cannon/shapes/cannon-shape.ts index 5bcf26b3557..f89b69c50f1 100644 --- a/cocos/physics/cannon/shapes/cannon-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-shape.ts @@ -48,18 +48,18 @@ export class CannonShape implements IBaseShape { static readonly idToMaterial = {}; - get impl () { return this._shape; } + get impl (): CANNON.Shape { return this._shape; } - get collider () { return this._collider; } + get collider (): Collider { return this._collider; } - get attachedRigidBody () { + get attachedRigidBody (): RigidBody | null { if (this._sharedBody.wrappedBody) { return this._sharedBody.wrappedBody.rigidBody; } return null; } get sharedBody (): CannonSharedBody { return this._sharedBody; } - setMaterial (mat: PhysicsMaterial | null) { + setMaterial (mat: PhysicsMaterial | null): void { const mat1 = (mat == null) ? PhysicsSystem.instance.defaultMaterial : mat; if (CannonShape.idToMaterial[mat1.id] == null) { @@ -74,21 +74,21 @@ export class CannonShape implements IBaseShape { (smat as any).correctInelastic = smat.restitution === 0 ? coef : 0; } - setAsTrigger (v: boolean) { + setAsTrigger (v: boolean): void { this._shape.collisionResponse = !v; if (this._index >= 0) { this._body.updateHasTrigger(); } } - setCenter (v: IVec3Like) { + setCenter (v: IVec3Like): void { this._setCenter(v); if (this._index >= 0) { commitShapeUpdates(this._body); } } - setAttachedBody (v: RigidBody | null) { + setAttachedBody (v: RigidBody | null): void { if (v) { if (this._sharedBody) { if (this._sharedBody.wrappedBody === v.body) return; @@ -107,7 +107,7 @@ export class CannonShape implements IBaseShape { } } - getAABB (v: geometry.AABB) { + getAABB (v: geometry.AABB): void { Quat.copy(cannonQuat_0, this._collider.node.worldRotation); (this._shape as any).calculateWorldAABB(CANNON.Vec3.ZERO, cannonQuat_0, cannonVec3_0, cannonVec3_1); Vec3.subtract(v.halfExtents, cannonVec3_1, cannonVec3_0); @@ -115,7 +115,7 @@ export class CannonShape implements IBaseShape { Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center); } - getBoundingSphere (v: geometry.Sphere) { + getBoundingSphere (v: geometry.Sphere): void { v.radius = this._shape.boundingSphereRadius; Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center); } @@ -132,7 +132,7 @@ export class CannonShape implements IBaseShape { /** LIFECYCLE */ - initialize (comp: Collider) { + initialize (comp: Collider): void { this._collider = comp; this._isBinding = true; this._sharedBody = (PhysicsSystem.instance.physicsWorld as CannonWorld).getSharedBody(this._collider.node); @@ -143,25 +143,25 @@ export class CannonShape implements IBaseShape { } // virtual - protected onComponentSet () { } + protected onComponentSet (): void { } - onLoad () { + onLoad (): void { this.setMaterial(this._collider.sharedMaterial); this.setCenter(this._collider.center); this.setAsTrigger(this._collider.isTrigger); } - onEnable () { + onEnable (): void { this._sharedBody.addShape(this); this._sharedBody.enabled = true; } - onDisable () { + onDisable (): void { this._sharedBody.removeShape(this); this._sharedBody.enabled = false; } - onDestroy () { + onDestroy (): void { this._sharedBody.reference = false; this._shape.removeEventListener('cc-trigger', this.onTriggerListener); delete (CANNON.World as any).idToShapeMap[this._shape.id]; @@ -221,29 +221,29 @@ export class CannonShape implements IBaseShape { * size handle by child class * @param scale */ - setScale (scale: IVec3Like) { + setScale (scale: IVec3Like): void { this._setCenter(this._collider.center); } - setIndex (index: number) { + setIndex (index: number): void { this._index = index; } - setOffsetAndOrient (offset: CANNON.Vec3, orient: CANNON.Quaternion) { + setOffsetAndOrient (offset: CANNON.Vec3, orient: CANNON.Quaternion): void { Vec3.copy(offset, this._offset); Quat.copy(orient, this._orient); this._offset = offset; this._orient = orient; } - protected _setCenter (v: IVec3Like) { + protected _setCenter (v: IVec3Like): void { const lpos = this._offset as IVec3Like; Vec3.subtract(lpos, this._sharedBody.node.worldPosition, this._collider.node.worldPosition); Vec3.add(lpos, lpos, v); Vec3.multiply(lpos, lpos, this._collider.node.worldScale); } - protected _onTrigger (event: CANNON.ITriggeredEvent) { + protected _onTrigger (event: CANNON.ITriggeredEvent): void { TriggerEventObject.type = event.event; const self = getWrap(event.selfShape); const other = getWrap(event.otherShape); diff --git a/cocos/physics/cannon/shapes/cannon-simplex-shape.ts b/cocos/physics/cannon/shapes/cannon-simplex-shape.ts index f4b2d43b3e7..67363cd8253 100644 --- a/cocos/physics/cannon/shapes/cannon-simplex-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-simplex-shape.ts @@ -31,13 +31,13 @@ import { ISimplexShape } from '../../spec/i-physics-shape'; import { SimplexCollider } from '../../../../exports/physics-framework'; export class CannonSimplexShape extends CannonShape implements ISimplexShape { - setShapeType (v: SimplexCollider.ESimplexType) { + setShapeType (v: SimplexCollider.ESimplexType): void { if (this._isBinding) { // TODO: change the type after init } } - setVertices (v: IVec3Like[]) { + setVertices (v: IVec3Like[]): void { const length = this.vertices.length; if (length === 4) { const ws = this._collider.node.worldScale; @@ -57,17 +57,17 @@ export class CannonSimplexShape extends CannonShape implements ISimplexShape { } } - get collider () { + get collider (): SimplexCollider { return this._collider as SimplexCollider; } - get impl () { + get impl (): CANNON.Particle | CANNON.ConvexPolyhedron { return this._shape as CANNON.Particle | CANNON.ConvexPolyhedron; } readonly vertices: CANNON.Vec3[] = []; - protected onComponentSet () { + protected onComponentSet (): void { const type = this.collider.shapeType; if (type === SimplexCollider.ESimplexType.TETRAHEDRON) { for (let i = 0; i < 4; i++) { @@ -82,7 +82,7 @@ export class CannonSimplexShape extends CannonShape implements ISimplexShape { } } - onLoad () { + onLoad (): void { super.onLoad(); this.collider.updateVertices(); } @@ -93,14 +93,14 @@ export class CannonSimplexShape extends CannonShape implements ISimplexShape { } } -const createTetra = (function () { +const createTetra = (function (): (verts: CANNON.Vec3[]) => CANNON.ConvexPolyhedron { const faces = [ [0, 3, 2], // -x [0, 1, 3], // -y [0, 2, 1], // -z [1, 2, 3], // +xyz ]; - return function (verts: CANNON.Vec3[]) { + return function (verts: CANNON.Vec3[]): CANNON.ConvexPolyhedron { return new CANNON.ConvexPolyhedron(verts, faces); }; }()); diff --git a/cocos/physics/cannon/shapes/cannon-sphere-shape.ts b/cocos/physics/cannon/shapes/cannon-sphere-shape.ts index f482e160ef4..c15baa816ad 100644 --- a/cocos/physics/cannon/shapes/cannon-sphere-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-sphere-shape.ts @@ -30,15 +30,15 @@ import { ISphereShape } from '../../spec/i-physics-shape'; import { PhysicsSystem, SphereCollider } from '../../../../exports/physics-framework'; export class CannonSphereShape extends CannonShape implements ISphereShape { - get collider () { + get collider (): SphereCollider { return this._collider as SphereCollider; } - get impl () { + get impl (): CANNON.Sphere { return this._shape as CANNON.Sphere; } - updateRadius () { + updateRadius (): void { const max = Math.abs(absMaxComponent(this.collider.node.worldScale)); this.impl.radius = clamp(this.collider.radius * Math.abs(max), PhysicsSystem.instance.minVolumeSize, Number.MAX_VALUE); this.impl.updateBoundingSphereRadius(); @@ -52,7 +52,7 @@ export class CannonSphereShape extends CannonShape implements ISphereShape { this._shape = new CANNON.Sphere(radius); } - onLoad () { + onLoad (): void { super.onLoad(); this.updateRadius(); } diff --git a/cocos/physics/cannon/shapes/cannon-terrain-shape.ts b/cocos/physics/cannon/shapes/cannon-terrain-shape.ts index 98b4be71364..0b43792aefe 100644 --- a/cocos/physics/cannon/shapes/cannon-terrain-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-terrain-shape.ts @@ -34,7 +34,7 @@ const CANNON_AABB_LOCAL = new CANNON.AABB(); const CANNON_AABB = new CANNON.AABB(); const CANNON_TRANSFORM = new CANNON.Transform(); // eslint-disable-next-line func-names -CANNON.Heightfield.prototype.calculateWorldAABB = function (pos: CANNON.Vec3, quat: CANNON.Quaternion, min: CANNON.Vec3, max: CANNON.Vec3) { +CANNON.Heightfield.prototype.calculateWorldAABB = function (pos: CANNON.Vec3, quat: CANNON.Quaternion, min: CANNON.Vec3, max: CANNON.Vec3): void { const frame = CANNON_TRANSFORM; const result = CANNON_AABB; Vec3.copy(frame.position, pos); @@ -49,11 +49,11 @@ CANNON.Heightfield.prototype.calculateWorldAABB = function (pos: CANNON.Vec3, qu }; export class CannonTerrainShape extends CannonShape implements ITerrainShape { - get collider () { + get collider (): TerrainCollider { return this._collider as TerrainCollider; } - get impl () { + get impl (): CANNON.Heightfield { return this._shape as CANNON.Heightfield; } @@ -96,7 +96,7 @@ export class CannonTerrainShape extends CannonShape implements ITerrainShape { this._terrainID = ''; } - protected onComponentSet () { + protected onComponentSet (): void { const terrain = this.collider.terrain; if (terrain) { const sizeI = terrain.getVertexCountI(); @@ -114,12 +114,12 @@ export class CannonTerrainShape extends CannonShape implements ITerrainShape { this._shape = new CANNON.Heightfield(this.data, this.options); } - onLoad () { + onLoad (): void { super.onLoad(); this.setTerrain(this.collider.terrain); } - updateProperties (data: number[][], elementSize: number) { + updateProperties (data: number[][], elementSize: number): void { const impl = this.impl; impl.data = data; impl.elementSize = elementSize; @@ -133,7 +133,7 @@ export class CannonTerrainShape extends CannonShape implements ITerrainShape { } // override - protected _setCenter (v: IVec3Like) { + protected _setCenter (v: IVec3Like): void { const terrain = this.collider.terrain; if (terrain) { Quat.fromEuler(this._orient, -90, 0, 0); diff --git a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts index d425c66aa75..8804ff3cfa4 100644 --- a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts @@ -3,23 +3,23 @@ https://www.cocos.com/ - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. */ import CANNON from '@cocos/cannon'; @@ -33,15 +33,15 @@ import { commitShapeUpdates } from '../cannon-util'; const v3_cannon0 = new CANNON.Vec3(); export class CannonTrimeshShape extends CannonShape implements ITrimeshShape { - get collider () { + get collider (): MeshCollider { return this._collider as MeshCollider; } - get impl () { + get impl (): CANNON.Trimesh { return this._shape as CANNON.Trimesh; } - setMesh (v: Mesh | null) { + setMesh (v: Mesh | null): void { if (!this._isBinding) return; const mesh = v; @@ -62,22 +62,22 @@ export class CannonTrimeshShape extends CannonShape implements ITrimeshShape { } } - protected onComponentSet () { + protected onComponentSet (): void { this.setMesh(this.collider.mesh); } - onLoad () { + onLoad (): void { super.onLoad(); this.setMesh(this.collider.mesh); } - setScale (scale: Vec3) { + setScale (scale: Vec3): void { super.setScale(scale); Vec3.copy(v3_cannon0, scale); this.impl.setScale(v3_cannon0); } - updateProperties (vertices: Float32Array, indices: Uint16Array) { + updateProperties (vertices: Float32Array, indices: Uint16Array): void { this.impl.vertices = new Float32Array(vertices); this.impl.indices = new Int16Array(indices); this.impl.normals = new Float32Array(indices.length); diff --git a/cocos/physics/cocos/builtin-rigid-body.ts b/cocos/physics/cocos/builtin-rigid-body.ts index 5ac14431fcd..7a9d99c0119 100644 --- a/cocos/physics/cocos/builtin-rigid-body.ts +++ b/cocos/physics/cocos/builtin-rigid-body.ts @@ -29,13 +29,13 @@ import { BuiltinSharedBody } from './builtin-shared-body'; import { BuiltInWorld } from './builtin-world'; export class BuiltinRigidBody implements IRigidBody { - get impl () { return this; } - get isAwake () { return true; } - get isSleepy () { return false; } - get isSleeping () { return false; } + get impl (): BuiltinRigidBody { return this; } + get isAwake (): boolean { return true; } + get isSleepy (): boolean { return false; } + get isSleeping (): boolean { return false; } - get rigidBody () { return this._rigidBody; } - get sharedBody () { return this._sharedBody; } + get rigidBody (): RigidBody { return this._rigidBody; } + get sharedBody (): BuiltinSharedBody { return this._sharedBody; } private _rigidBody!: RigidBody; protected _sharedBody!: BuiltinSharedBody; @@ -46,30 +46,30 @@ export class BuiltinRigidBody implements IRigidBody { this._sharedBody.reference = true; } - onEnable () { + onEnable (): void { this._sharedBody.enabled = true; } - onDisable () { + onDisable (): void { this._sharedBody.enabled = false; } - onDestroy () { + onDestroy (): void { this._sharedBody.reference = false; (this._rigidBody as any) = null; (this._sharedBody as any) = null; } - setMass (v: number) { } - setType (v: ERigidBodyType) { } - setLinearDamping (v: number) { } - setAngularDamping (v: number) { } - useGravity (v: boolean) { } - useCCD (v: boolean) { } - isUsingCCD () { return false; } - setLinearFactor (v: IVec3Like) { } - setAngularFactor (v: IVec3Like) { } - setAllowSleep (v: boolean) { } + setMass (v: number): void { } + setType (v: ERigidBodyType): void { } + setLinearDamping (v: number): void { } + setAngularDamping (v: number): void { } + useGravity (v: boolean): void { } + useCCD (v: boolean): void { } + isUsingCCD (): boolean { return false; } + setLinearFactor (v: IVec3Like): void { } + setAngularFactor (v: IVec3Like): void { } + setAllowSleep (v: boolean): void { } wakeUp (): void { } sleep (): void { } clearState (): void { } diff --git a/cocos/physics/cocos/builtin-shared-body.ts b/cocos/physics/cocos/builtin-shared-body.ts index 8a192bc1c04..2ee2067aff4 100644 --- a/cocos/physics/cocos/builtin-shared-body.ts +++ b/cocos/physics/cocos/builtin-shared-body.ts @@ -42,7 +42,7 @@ const quat_0 = new Quat(); export class BuiltinSharedBody extends BuiltinObject { private static readonly sharedBodesMap = new Map(); - static getSharedBody (node: Node, wrappedWorld: BuiltInWorld, wrappedBody?: BuiltinRigidBody) { + static getSharedBody (node: Node, wrappedWorld: BuiltInWorld, wrappedBody?: BuiltinRigidBody): BuiltinSharedBody { const key = node.uuid; let newSB: BuiltinSharedBody; if (BuiltinSharedBody.sharedBodesMap.has(key)) { @@ -65,7 +65,7 @@ export class BuiltinSharedBody extends BuiltinObject { return newSB; } - get id () { + get id (): number { return this._id; } @@ -115,7 +115,7 @@ export class BuiltinSharedBody extends BuiltinObject { this.world = world; } - intersects (body: BuiltinSharedBody) { + intersects (body: BuiltinSharedBody): void { for (let i = 0; i < this.shapes.length; i++) { const shapeA = this.shapes[i]; for (let j = 0; j < body.shapes.length; j++) { @@ -144,7 +144,7 @@ export class BuiltinSharedBody extends BuiltinObject { } } - syncSceneToPhysics () { + syncSceneToPhysics (): void { if (this.node.hasChangedFlags) { this.node.getWorldMatrix(m4_0); v3_0.set(this.node.worldPosition); @@ -156,7 +156,7 @@ export class BuiltinSharedBody extends BuiltinObject { } } - syncInitial () { + syncInitial (): void { this.node.getWorldMatrix(m4_0); v3_0.set(this.node.worldPosition); quat_0.set(this.node.worldRotation); @@ -166,7 +166,7 @@ export class BuiltinSharedBody extends BuiltinObject { } } - private destroy () { + private destroy (): void { BuiltinSharedBody.sharedBodesMap.delete(this.node.uuid); (this.node as any) = null; (this.world as any) = null; diff --git a/cocos/physics/cocos/builtin-world.ts b/cocos/physics/cocos/builtin-world.ts index 5433afc4675..304cea733a2 100644 --- a/cocos/physics/cocos/builtin-world.ts +++ b/cocos/physics/cocos/builtin-world.ts @@ -84,10 +84,10 @@ export class BuiltInWorld implements IPhysicsWorld { return false; } - setGravity (v: IVec3Like) { } - setAllowSleep (v: boolean) { } - setDefaultMaterial (v: PhysicsMaterial) { } - get impl () { return this; } + setGravity (v: IVec3Like): void { } + setAllowSleep (v: boolean): void { } + setDefaultMaterial (v: PhysicsMaterial): void { } + get impl (): BuiltInWorld { return this; } shapeArr: BuiltinShape[] = []; readonly bodies: BuiltinSharedBody[] = []; @@ -187,21 +187,21 @@ export class BuiltInWorld implements IPhysicsWorld { return BuiltinSharedBody.getSharedBody(node, this, wrappedBody); } - addSharedBody (body: BuiltinSharedBody) { + addSharedBody (body: BuiltinSharedBody): void { const index = this.bodies.indexOf(body); if (index < 0) { this.bodies.push(body); } } - removeSharedBody (body: BuiltinSharedBody) { + removeSharedBody (body: BuiltinSharedBody): void { const index = this.bodies.indexOf(body); if (index >= 0) { js.array.fastRemoveAt(this.bodies, index); } } - private emitTriggerEvent () { + private emitTriggerEvent (): void { let shapeA: BuiltinShape; let shapeB: BuiltinShape; for (let i = 0; i < this.shapeArr.length; i += 2) { diff --git a/cocos/physics/cocos/shapes/builtin-box-shape.ts b/cocos/physics/cocos/shapes/builtin-box-shape.ts index 41ae4830c3d..5c868652725 100644 --- a/cocos/physics/cocos/shapes/builtin-box-shape.ts +++ b/cocos/physics/cocos/shapes/builtin-box-shape.ts @@ -28,15 +28,15 @@ import { IBoxShape } from '../../spec/i-physics-shape'; import { BoxCollider } from '../../../../exports/physics-framework'; export class BuiltinBoxShape extends BuiltinShape implements IBoxShape { - get localObb () { + get localObb (): geometry.OBB { return this._localShape as geometry.OBB; } - get worldObb () { + get worldObb (): geometry.OBB { return this._worldShape as geometry.OBB; } - get collider () { + get collider (): BoxCollider { return this._collider as BoxCollider; } @@ -46,12 +46,12 @@ export class BuiltinBoxShape extends BuiltinShape implements IBoxShape { this._worldShape = new geometry.OBB(); } - updateSize () { + updateSize (): void { Vec3.multiplyScalar(this.localObb.halfExtents, this.collider.size, 0.5); Vec3.multiply(this.worldObb.halfExtents, this.localObb.halfExtents, this.collider.node.worldScale); } - onLoad () { + onLoad (): void { super.onLoad(); this.updateSize(); } diff --git a/cocos/physics/cocos/shapes/builtin-capsule-shape.ts b/cocos/physics/cocos/shapes/builtin-capsule-shape.ts index 36e5dce08e6..c687c5eeea5 100644 --- a/cocos/physics/cocos/shapes/builtin-capsule-shape.ts +++ b/cocos/physics/cocos/shapes/builtin-capsule-shape.ts @@ -28,15 +28,15 @@ import { geometry } from '../../../core'; import { EAxisDirection, CapsuleCollider } from '../../framework'; export class BuiltinCapsuleShape extends BuiltinShape implements ICapsuleShape { - get localCapsule () { + get localCapsule (): geometry.Capsule { return this._localShape as geometry.Capsule; } - get worldCapsule () { + get worldCapsule (): geometry.Capsule { return this._worldShape as geometry.Capsule; } - get collider () { + get collider (): CapsuleCollider { return this._collider as CapsuleCollider; } @@ -48,7 +48,7 @@ export class BuiltinCapsuleShape extends BuiltinShape implements ICapsuleShape { this._worldShape = new geometry.Capsule(radius, h, direction); } - setRadius (v: number) { + setRadius (v: number): void { this.localCapsule.radius = v; this.transform( this._sharedBody.node.worldMatrix, @@ -58,7 +58,7 @@ export class BuiltinCapsuleShape extends BuiltinShape implements ICapsuleShape { ); } - setCylinderHeight (v: number) { + setCylinderHeight (v: number): void { this.localCapsule.halfHeight = v / 2; this.localCapsule.updateCache(); @@ -70,7 +70,7 @@ export class BuiltinCapsuleShape extends BuiltinShape implements ICapsuleShape { ); } - setDirection (v: EAxisDirection) { + setDirection (v: EAxisDirection): void { this.localCapsule.axis = v; this.localCapsule.updateCache(); @@ -85,7 +85,7 @@ export class BuiltinCapsuleShape extends BuiltinShape implements ICapsuleShape { ); } - onLoad () { + onLoad (): void { super.onLoad(); this.setRadius(this.collider.radius); this.setDirection(this.collider.direction); diff --git a/cocos/physics/cocos/shapes/builtin-shape.ts b/cocos/physics/cocos/shapes/builtin-shape.ts index e4b672535e0..f8708f16a23 100644 --- a/cocos/physics/cocos/shapes/builtin-shape.ts +++ b/cocos/physics/cocos/shapes/builtin-shape.ts @@ -30,34 +30,34 @@ import { IBaseShape } from '../../spec/i-physics-shape'; import { BuiltInWorld } from '../builtin-world'; export class BuiltinShape implements IBaseShape { - getAABB (v: geometry.AABB) { } - getBoundingSphere (v: geometry.Sphere) { } + getAABB (v: geometry.AABB): void { } + getBoundingSphere (v: geometry.Sphere): void { } updateEventListener (): void { } - setMaterial (v: PhysicsMaterial | null) { } - setAsTrigger (v: boolean) { } + setMaterial (v: PhysicsMaterial | null): void { } + setAsTrigger (v: boolean): void { } get attachedRigidBody (): RigidBody | null { return null; } - setCenter (v: IVec3Like) { + setCenter (v: IVec3Like): void { Vec3.copy(this._localShape.center, v); } - get localShape () { + get localShape (): IBuiltinShape { return this._localShape; } - get worldShape () { + get worldShape (): IBuiltinShape { return this._worldShape; } - get impl () { + get impl (): IBuiltinShape { return this._worldShape; } - get sharedBody () { + get sharedBody (): BuiltinSharedBody { return this._sharedBody; } - get collider () { + get collider (): Collider { return this._collider; } @@ -70,34 +70,34 @@ export class BuiltinShape implements IBaseShape { protected _localShape!: IBuiltinShape; protected _worldShape!: IBuiltinShape; - initialize (comp: Collider) { + initialize (comp: Collider): void { this._collider = comp; this._sharedBody = (PhysicsSystem.instance.physicsWorld as BuiltInWorld).getSharedBody(this._collider.node); this._sharedBody.reference = true; } - onLoad () { + onLoad (): void { this.setCenter(this._collider.center); } - onEnable () { + onEnable (): void { this._sharedBody.addShape(this); this._sharedBody.enabled = true; } - onDisable () { + onDisable (): void { this._sharedBody.removeShape(this); this._sharedBody.enabled = false; } - onDestroy () { + onDestroy (): void { this._sharedBody.reference = false; (this._collider as any) = null; (this._localShape as any) = null; (this._worldShape as any) = null; } - transform (m: Mat4 | Readonly, pos: Vec3 | Readonly, rot: Quat | Readonly, scale: Vec3 | Readonly) { + transform (m: Mat4 | Readonly, pos: Vec3 | Readonly, rot: Quat | Readonly, scale: Vec3 | Readonly): void { this._localShape.transform(m, pos, rot, scale, this._worldShape); } diff --git a/cocos/physics/cocos/shapes/builtin-sphere-shape.ts b/cocos/physics/cocos/shapes/builtin-sphere-shape.ts index 0be5941017d..45a82ff5e1f 100644 --- a/cocos/physics/cocos/shapes/builtin-sphere-shape.ts +++ b/cocos/physics/cocos/shapes/builtin-sphere-shape.ts @@ -29,21 +29,21 @@ import { maxComponent } from '../../utils/util'; import { SphereCollider } from '../../../../exports/physics-framework'; export class BuiltinSphereShape extends BuiltinShape implements ISphereShape { - updateRadius () { + updateRadius (): void { this.localSphere.radius = this.collider.radius; const s = maxComponent(this.collider.node.worldScale); this.worldSphere.radius = this.localSphere.radius * s; } - get localSphere () { + get localSphere (): geometry.Sphere { return this._localShape as geometry.Sphere; } - get worldSphere () { + get worldSphere (): geometry.Sphere { return this._worldShape as geometry.Sphere; } - get collider () { + get collider (): SphereCollider { return this._collider as SphereCollider; } @@ -53,7 +53,7 @@ export class BuiltinSphereShape extends BuiltinShape implements ISphereShape { this._worldShape = new geometry.Sphere(0, 0, 0, radius); } - onLoad () { + onLoad (): void { super.onLoad(); this.updateRadius(); } diff --git a/cocos/physics/framework/assets/physics-material.ts b/cocos/physics/framework/assets/physics-material.ts index 216dcd3eb95..fb48fbf6bbb 100644 --- a/cocos/physics/framework/assets/physics-material.ts +++ b/cocos/physics/framework/assets/physics-material.ts @@ -62,7 +62,7 @@ export class PhysicsMaterial extends Asset { @editable @type(CCFloat) @tooltip('i18n:physics3d.material.friction') - get friction () { + get friction (): number { return this._friction; } @@ -82,7 +82,7 @@ export class PhysicsMaterial extends Asset { @editable @type(CCFloat) @tooltip('i18n:physics3d.material.rollingFriction') - get rollingFriction () { + get rollingFriction (): number { return this._rollingFriction; } @@ -102,7 +102,7 @@ export class PhysicsMaterial extends Asset { @editable @type(CCFloat) @tooltip('i18n:physics3d.material.spinningFriction') - get spinningFriction () { + get spinningFriction (): number { return this._spinningFriction; } @@ -122,7 +122,7 @@ export class PhysicsMaterial extends Asset { @editable @type(CCFloat) @tooltip('i18n:physics3d.material.restitution') - get restitution () { + get restitution (): number { return this._restitution; } @@ -161,7 +161,7 @@ export class PhysicsMaterial extends Asset { * @zh * 克隆。 */ - public clone () { + public clone (): PhysicsMaterial { const c = new PhysicsMaterial(); c._friction = this._friction; c._restitution = this._restitution; @@ -198,7 +198,7 @@ export class PhysicsMaterial extends Asset { * @param spinningFriction * @param restitution */ - public setValues (friction: number, rollingFriction: number, spinningFriction: number, restitution: number) { + public setValues (friction: number, rollingFriction: number, spinningFriction: number, restitution: number): void { const emitUpdate = this._friction !== friction || this._rollingFriction !== rollingFriction || this._spinningFriction !== spinningFriction || this._restitution !== restitution; this._friction = friction; diff --git a/cocos/physics/framework/components/character-controllers/box-character-controller.ts b/cocos/physics/framework/components/character-controllers/box-character-controller.ts index 700926639d4..88b21a3ccd1 100644 --- a/cocos/physics/framework/components/character-controllers/box-character-controller.ts +++ b/cocos/physics/framework/components/character-controllers/box-character-controller.ts @@ -62,7 +62,7 @@ export class BoxCharacterController extends CharacterController { */ @tooltip('i18n:physics3d.character_controller.boxHalfHeight') @type(CCFloat) - public get halfHeight () { + public get halfHeight (): number { return this._halfHeight; } @@ -82,7 +82,7 @@ export class BoxCharacterController extends CharacterController { */ @tooltip('i18n:physics3d.character_controller.boxHalfSideExtent') @type(CCFloat) - public get halfSideExtent () { + public get halfSideExtent (): number { return this._halfSideExtent; } @@ -102,7 +102,7 @@ export class BoxCharacterController extends CharacterController { */ @tooltip('i18n:physics3d.character_controller.boxHalfForwardExtent') @type(CCFloat) - public get halfForwardExtent () { + public get halfForwardExtent (): number { return this._halfForwardExtent; } diff --git a/cocos/physics/framework/components/character-controllers/capsule-character-controller.ts b/cocos/physics/framework/components/character-controllers/capsule-character-controller.ts index ab204a1c3c5..447161853b4 100644 --- a/cocos/physics/framework/components/character-controllers/capsule-character-controller.ts +++ b/cocos/physics/framework/components/character-controllers/capsule-character-controller.ts @@ -62,7 +62,7 @@ export class CapsuleCharacterController extends CharacterController { */ @tooltip('i18n:physics3d.character_controller.capsuleRadius') @type(CCFloat) - public get radius () { + public get radius (): number { return this._radius; } @@ -83,7 +83,7 @@ export class CapsuleCharacterController extends CharacterController { */ @tooltip('i18n:physics3d.character_controller.capsuleHeight') @type(CCFloat) - public get height () { + public get height (): number { return this._height; } diff --git a/cocos/physics/framework/components/character-controllers/character-controller.ts b/cocos/physics/framework/components/character-controllers/character-controller.ts index d6cb769b74e..eeb13cd5a8f 100644 --- a/cocos/physics/framework/components/character-controllers/character-controller.ts +++ b/cocos/physics/framework/components/character-controllers/character-controller.ts @@ -81,7 +81,7 @@ export class CharacterController extends Eventify(Component) { */ @tooltip('i18n:physics3d.character_controller.minMoveDistance') @type(CCFloat) - public get minMoveDistance () { + public get minMoveDistance (): number { return this._minMoveDistance; } @@ -98,7 +98,7 @@ export class CharacterController extends Eventify(Component) { */ @tooltip('i18n:physics3d.character_controller.stepOffset') @type(CCFloat) - public get stepOffset () { + public get stepOffset (): number { return this._stepOffset; } @@ -118,7 +118,7 @@ export class CharacterController extends Eventify(Component) { */ @tooltip('i18n:physics3d.character_controller.slopeLimit') @type(CCFloat) - public get slopeLimit () { + public get slopeLimit (): number { return this._slopeLimit; } @@ -139,7 +139,7 @@ export class CharacterController extends Eventify(Component) { */ @tooltip('i18n:physics3d.character_controller.contactOffset') @type(CCFloat) - public get contactOffset () { + public get contactOffset (): number { return this._contactOffset; } @@ -265,26 +265,26 @@ export class CharacterController extends Eventify(Component) { /// COMPONENT LIFECYCLE /// - protected onLoad () { + protected onLoad (): void { if (!selector.runInEditor) return; this._cct = createCharacterController(this.type); this._initialized = this._cct.initialize(this); this._cct.onLoad!(); } - protected onEnable () { + protected onEnable (): void { if (this._cct) { this._cct.onEnable!(); } } - protected onDisable () { + protected onDisable (): void { if (this._cct) { this._cct.onDisable!(); } } - protected onDestroy () { + protected onDestroy (): void { if (this._cct) { this._needCollisionEvent = false; this._cct.updateEventListener(); @@ -380,7 +380,7 @@ export class CharacterController extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public off (type: CharacterCollisionEventType, callback?: (...any) => void, target?) { + public off (type: CharacterCollisionEventType, callback?: (...any) => void, target?): void { super.off(type, callback, target); this._updateNeedEvent(); } @@ -433,7 +433,7 @@ export class CharacterController extends Eventify(Component) { * 添加分组值,可填要加入的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ - public addGroup (v: number) { + public addGroup (v: number): void { if (this._isInitialized) this._cct!.addGroup(v); } @@ -444,7 +444,7 @@ export class CharacterController extends Eventify(Component) { * 减去分组值,可填要移除的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ - public removeGroup (v: number) { + public removeGroup (v: number): void { if (this._isInitialized) this._cct!.removeGroup(v); } @@ -467,7 +467,7 @@ export class CharacterController extends Eventify(Component) { * 设置掩码值。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public setMask (v: number) { + public setMask (v: number): void { if (this._isInitialized) this._cct!.setMask(v); } @@ -478,7 +478,7 @@ export class CharacterController extends Eventify(Component) { * 添加掩码值,可填入需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public addMask (v: number) { + public addMask (v: number): void { if (this._isInitialized) this._cct!.addMask(v); } @@ -489,15 +489,15 @@ export class CharacterController extends Eventify(Component) { * 减去掩码值,可填入不需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public removeMask (v: number) { + public removeMask (v: number): void { if (this._isInitialized) this._cct!.removeMask(v); } - public get needCollisionEvent () { + public get needCollisionEvent (): boolean { return this._needCollisionEvent; } - private _updateNeedEvent (type?: string) { + private _updateNeedEvent (type?: string): void { if (this.isValid) { if (type !== undefined) { if (type === 'onControllerColliderHit') { diff --git a/cocos/physics/framework/components/colliders/box-collider.ts b/cocos/physics/framework/components/colliders/box-collider.ts index ec2ed63f2ec..b513e1f6ae7 100644 --- a/cocos/physics/framework/components/colliders/box-collider.ts +++ b/cocos/physics/framework/components/colliders/box-collider.ts @@ -58,7 +58,7 @@ export class BoxCollider extends Collider { */ @type(Vec3) @tooltip('i18n:physics3d.collider.box_size') - public get size () { + public get size (): Vec3 { return this._size; } @@ -77,7 +77,7 @@ export class BoxCollider extends Collider { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - public get shape () { + public get shape (): IBoxShape { return this._shape as IBoxShape; } diff --git a/cocos/physics/framework/components/colliders/capsule-collider.ts b/cocos/physics/framework/components/colliders/capsule-collider.ts index 8b1d82585df..662a4d8f875 100644 --- a/cocos/physics/framework/components/colliders/capsule-collider.ts +++ b/cocos/physics/framework/components/colliders/capsule-collider.ts @@ -56,7 +56,7 @@ export class CapsuleCollider extends Collider { * 获取或设置胶囊体在本地坐标系下的球半径。 */ @tooltip('i18n:physics3d.collider.capsule_radius') - public get radius () { + public get radius (): number { return this._radius; } @@ -75,7 +75,7 @@ export class CapsuleCollider extends Collider { * 获取或设置在本地坐标系下的胶囊体上圆柱体的高度。 */ @tooltip('i18n:physics3d.collider.capsule_cylinderHeight') - public get cylinderHeight () { + public get cylinderHeight (): number { return this._cylinderHeight; } @@ -95,7 +95,7 @@ export class CapsuleCollider extends Collider { */ @type(EAxisDirection) @tooltip('i18n:physics3d.collider.capsule_direction') - public get direction () { + public get direction (): EAxisDirection { return this._direction; } @@ -115,7 +115,7 @@ export class CapsuleCollider extends Collider { * @zh * 获取或设置在本地坐标系下胶囊体的高度,最小值为球的直径。 */ - public get height () { + public get height (): number { return this._radius * 2 + this._cylinderHeight; } @@ -131,7 +131,7 @@ export class CapsuleCollider extends Collider { * @zh * 获取胶囊体在世界坐标系下相应胶囊体朝向上的高度,只读属性。 */ - public get worldHeight () { + public get worldHeight (): number { return this._radius * 2 * this._getRadiusScale() + this._cylinderHeight * this._getHeightScale(); } @@ -141,7 +141,7 @@ export class CapsuleCollider extends Collider { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - public get shape () { + public get shape (): ICapsuleShape { return this._shape as ICapsuleShape; } @@ -160,7 +160,7 @@ export class CapsuleCollider extends Collider { super(EColliderType.CAPSULE); } - private _getRadiusScale () { + private _getRadiusScale (): number { if (this.node == null) return 1; const ws = this.node.worldScale; if (this._direction === EAxisDirection.Y_AXIS) return Math.abs(absMax(ws.x, ws.z)); @@ -168,7 +168,7 @@ export class CapsuleCollider extends Collider { return Math.abs(absMax(ws.x, ws.y)); } - private _getHeightScale () { + private _getHeightScale (): number { if (this.node == null) return 1; const ws = this.node.worldScale; if (this._direction === EAxisDirection.Y_AXIS) return Math.abs(ws.y); diff --git a/cocos/physics/framework/components/colliders/collider.ts b/cocos/physics/framework/components/colliders/collider.ts index 27ad7ca1bd3..2c8ef0ce264 100644 --- a/cocos/physics/framework/components/colliders/collider.ts +++ b/cocos/physics/framework/components/colliders/collider.ts @@ -86,7 +86,7 @@ export class Collider extends Eventify(Component) { @displayName('Material') @displayOrder(-1) @tooltip('i18n:physics3d.collider.sharedMaterial') - public get sharedMaterial () { + public get sharedMaterial (): PhysicsMaterial | null { return this._material; } @@ -104,7 +104,7 @@ export class Collider extends Eventify(Component) { * @zh * 获取或设置此碰撞器的物理材质,共享状态下获取将会生成新的实例。 */ - public get material () { + public get material (): PhysicsMaterial | null { if (this._isSharedMaterial && this._material) { this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this); this._material = this._material.clone(); @@ -144,7 +144,7 @@ export class Collider extends Eventify(Component) { */ @displayOrder(0) @tooltip('i18n:physics3d.collider.isTrigger') - public get isTrigger () { + public get isTrigger (): boolean { return this._isTrigger; } @@ -164,7 +164,7 @@ export class Collider extends Eventify(Component) { @type(Vec3) @displayOrder(1) @tooltip('i18n:physics3d.collider.center') - public get center () { + public get center (): Vec3 { return this._center; } @@ -181,7 +181,7 @@ export class Collider extends Eventify(Component) { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - public get shape () { + public get shape (): IBaseShape | null { return this._shape; } @@ -197,11 +197,11 @@ export class Collider extends Eventify(Component) { return this._boundingSphere; } - public get needTriggerEvent () { + public get needTriggerEvent (): boolean { return this._needTriggerEvent; } - public get needCollisionEvent () { + public get needCollisionEvent (): boolean { return this._needCollisionEvent; } @@ -263,7 +263,7 @@ export class Collider extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public off (type: TriggerEventType | CollisionEventType, callback?: (...any) => void, target?) { + public off (type: TriggerEventType | CollisionEventType, callback?: (...any) => void, target?): void { super.off(type, callback, target); this._updateNeedEvent(); } @@ -291,7 +291,7 @@ export class Collider extends Eventify(Component) { * 移除所有指定目标或类型的注册事件。 * @param typeOrTarget - The event type or target. */ - public removeAll (typeOrTarget: TriggerEventType | CollisionEventType | Record) { + public removeAll (typeOrTarget: TriggerEventType | CollisionEventType | Record): void { super.removeAll(typeOrTarget); this._updateNeedEvent(); } @@ -332,7 +332,7 @@ export class Collider extends Eventify(Component) { * 添加分组值,可填要加入的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ - public addGroup (v: number) { + public addGroup (v: number): void { if (this._isInitialized) { this._shape!.addGroup(v); } @@ -345,7 +345,7 @@ export class Collider extends Eventify(Component) { * 减去分组值,可填要移除的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ - public removeGroup (v: number) { + public removeGroup (v: number): void { if (this._isInitialized) { this._shape!.removeGroup(v); } @@ -372,7 +372,7 @@ export class Collider extends Eventify(Component) { * 设置掩码值。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public setMask (v: number) { + public setMask (v: number): void { if (this._isInitialized) { this._shape!.setMask(v); } @@ -385,7 +385,7 @@ export class Collider extends Eventify(Component) { * 添加掩码值,可填入需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public addMask (v: number) { + public addMask (v: number): void { if (this._isInitialized) { this._shape!.addMask(v); } @@ -398,7 +398,7 @@ export class Collider extends Eventify(Component) { * 减去掩码值,可填入不需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public removeMask (v: number) { + public removeMask (v: number): void { if (this._isInitialized) { this._shape!.removeMask(v); } @@ -406,7 +406,7 @@ export class Collider extends Eventify(Component) { /// COMPONENT LIFECYCLE /// - protected onLoad () { + protected onLoad (): void { if (!selector.runInEditor) return; this.sharedMaterial = this._material; @@ -415,19 +415,19 @@ export class Collider extends Eventify(Component) { this._shape.onLoad!(); } - protected onEnable () { + protected onEnable (): void { if (this._shape) { this._shape.onEnable!(); } } - protected onDisable () { + protected onDisable (): void { if (this._shape) { this._shape.onDisable!(); } } - protected onDestroy () { + protected onDestroy (): void { if (this._shape) { this._needTriggerEvent = false; this._needCollisionEvent = false; @@ -438,11 +438,11 @@ export class Collider extends Eventify(Component) { if (this._boundingSphere) this._boundingSphere.destroy(); } - private _updateMaterial () { + private _updateMaterial (): void { if (this._shape) this._shape.setMaterial(this._material); } - private _updateNeedEvent (type?: string) { + private _updateNeedEvent (type?: string): void { if (this.isValid) { if (type !== undefined) { if (type === 'onCollisionEnter' || type === 'onCollisionStay' || type === 'onCollisionExit') { diff --git a/cocos/physics/framework/components/colliders/cone-collider.ts b/cocos/physics/framework/components/colliders/cone-collider.ts index 9489b3e91fd..bcd450b2122 100644 --- a/cocos/physics/framework/components/colliders/cone-collider.ts +++ b/cocos/physics/framework/components/colliders/cone-collider.ts @@ -55,7 +55,7 @@ export class ConeCollider extends Collider { * 获取或设置圆锥体上圆面半径。 */ @tooltip('i18n:physics3d.collider.cone_radius') - public get radius () { + public get radius (): number { return this._radius; } @@ -74,7 +74,7 @@ export class ConeCollider extends Collider { * 获取或设置圆锥体在相应轴向的高度。 */ @tooltip('i18n:physics3d.collider.cone_height') - public get height () { + public get height (): number { return this._height; } @@ -95,7 +95,7 @@ export class ConeCollider extends Collider { */ @type(EAxisDirection) @tooltip('i18n:physics3d.collider.cone_direction') - public get direction () { + public get direction (): EAxisDirection { return this._direction; } @@ -108,7 +108,7 @@ export class ConeCollider extends Collider { } } - public get shape () { + public get shape (): IConeShape { return this._shape as IConeShape; } diff --git a/cocos/physics/framework/components/colliders/cylinder-collider.ts b/cocos/physics/framework/components/colliders/cylinder-collider.ts index 072b60fc2a4..5ba80c5ab50 100644 --- a/cocos/physics/framework/components/colliders/cylinder-collider.ts +++ b/cocos/physics/framework/components/colliders/cylinder-collider.ts @@ -55,7 +55,7 @@ export class CylinderCollider extends Collider { * 获取或设置圆柱体上圆面半径。 */ @tooltip('i18n:physics3d.collider.cylinder_radius') - public get radius () { + public get radius (): number { return this._radius; } @@ -74,7 +74,7 @@ export class CylinderCollider extends Collider { * 获取或设置圆柱体在相应轴向的高度。 */ @tooltip('i18n:physics3d.collider.cylinder_height') - public get height () { + public get height (): number { return this._height; } @@ -94,7 +94,7 @@ export class CylinderCollider extends Collider { */ @type(EAxisDirection) @tooltip('i18n:physics3d.collider.cylinder_direction') - public get direction () { + public get direction (): EAxisDirection { return this._direction; } @@ -107,7 +107,7 @@ export class CylinderCollider extends Collider { } } - public get shape () { + public get shape (): ICylinderShape { return this._shape as ICylinderShape; } diff --git a/cocos/physics/framework/components/colliders/mesh-collider.ts b/cocos/physics/framework/components/colliders/mesh-collider.ts index a0bcabca9c5..e2b4dd912ba 100644 --- a/cocos/physics/framework/components/colliders/mesh-collider.ts +++ b/cocos/physics/framework/components/colliders/mesh-collider.ts @@ -60,7 +60,7 @@ export class MeshCollider extends Collider { */ @type(Mesh) @tooltip('i18n:physics3d.collider.mesh_mesh') - get mesh () { + get mesh (): Mesh | null { return this._mesh; } @@ -78,7 +78,7 @@ export class MeshCollider extends Collider { */ @editable @tooltip('i18n:physics3d.collider.mesh_convex') - get convex () { + get convex (): boolean { return this._convex; } @@ -95,11 +95,11 @@ export class MeshCollider extends Collider { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - get shape () { + get shape (): ITrimeshShape { return this._shape as ITrimeshShape; } - protected onEnable () { + protected onEnable (): void { super.onEnable(); if (this.node) { diff --git a/cocos/physics/framework/components/colliders/plane-collider.ts b/cocos/physics/framework/components/colliders/plane-collider.ts index 21d9c1cf6f8..7a9203e07de 100644 --- a/cocos/physics/framework/components/colliders/plane-collider.ts +++ b/cocos/physics/framework/components/colliders/plane-collider.ts @@ -59,7 +59,7 @@ export class PlaneCollider extends Collider { */ @type(Vec3) @tooltip('i18n:physics3d.collider.plane_normal') - public get normal () { + public get normal (): Vec3 { return this._normal; } @@ -79,7 +79,7 @@ export class PlaneCollider extends Collider { */ @editable @tooltip('i18n:physics3d.collider.plane_constant') - public get constant () { + public get constant (): number { return this._constant; } @@ -97,11 +97,11 @@ export class PlaneCollider extends Collider { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - public get shape () { + public get shape (): IPlaneShape { return this._shape as IPlaneShape; } - protected onEnable () { + protected onEnable (): void { super.onEnable(); if (this.node) { diff --git a/cocos/physics/framework/components/colliders/simplex-collider.ts b/cocos/physics/framework/components/colliders/simplex-collider.ts index 66b5e6b5e66..ed49b3e6c96 100644 --- a/cocos/physics/framework/components/colliders/simplex-collider.ts +++ b/cocos/physics/framework/components/colliders/simplex-collider.ts @@ -57,7 +57,7 @@ export class SimplexCollider extends Collider { @type(ESimplexType) @tooltip('i18n:physics3d.collider.simplex_shapeType') - get shapeType () { + get shapeType (): ESimplexType { return this._shapeType; } @@ -70,7 +70,7 @@ export class SimplexCollider extends Collider { @editable @tooltip('i18n:physics3d.collider.simplex_vertex0') - get vertex0 () { + get vertex0 (): IVec3Like { return this._vertices[0]; } @@ -81,7 +81,7 @@ export class SimplexCollider extends Collider { @visible(function (this: SimplexCollider) { return this._shapeType > 1; }) @tooltip('i18n:physics3d.collider.simplex_vertex1') - get vertex1 () { + get vertex1 (): IVec3Like { return this._vertices[1]; } @@ -92,7 +92,7 @@ export class SimplexCollider extends Collider { @visible(function (this: SimplexCollider) { return this._shapeType > 2; }) @tooltip('i18n:physics3d.collider.simplex_vertex2') - get vertex2 () { + get vertex2 (): IVec3Like { return this._vertices[2]; } @@ -103,7 +103,7 @@ export class SimplexCollider extends Collider { @visible(function (this: SimplexCollider) { return this._shapeType > 3; }) @tooltip('i18n:physics3d.collider.simplex_vertex3') - get vertex3 () { + get vertex3 (): IVec3Like { return this._vertices[3]; } @@ -118,11 +118,11 @@ export class SimplexCollider extends Collider { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - public get shape () { + public get shape (): ISimplexShape { return this._shape as ISimplexShape; } - get vertices () { + get vertices (): IVec3Like[] { return this._vertices; } @@ -143,7 +143,7 @@ export class SimplexCollider extends Collider { super(EColliderType.SIMPLEX); } - updateVertices () { + updateVertices (): void { if (this._shape) { this.shape.setVertices(this._vertices); } diff --git a/cocos/physics/framework/components/colliders/sphere-collider.ts b/cocos/physics/framework/components/colliders/sphere-collider.ts index e4895bc94b2..5dec566117b 100644 --- a/cocos/physics/framework/components/colliders/sphere-collider.ts +++ b/cocos/physics/framework/components/colliders/sphere-collider.ts @@ -54,7 +54,7 @@ export class SphereCollider extends Collider { * 获取或设置球的半径。 */ @tooltip('i18n:physics3d.collider.sphere_radius') - public get radius () { + public get radius (): number { return this._radius; } @@ -72,7 +72,7 @@ export class SphereCollider extends Collider { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - public get shape () { + public get shape (): ISphereShape { return this._shape as ISphereShape; } diff --git a/cocos/physics/framework/components/colliders/terrain-collider.ts b/cocos/physics/framework/components/colliders/terrain-collider.ts index 0388cec1f2a..0d511c45295 100644 --- a/cocos/physics/framework/components/colliders/terrain-collider.ts +++ b/cocos/physics/framework/components/colliders/terrain-collider.ts @@ -60,7 +60,7 @@ export class TerrainCollider extends Collider { */ @type(TerrainAsset) @tooltip('i18n:physics3d.collider.terrain_terrain') - get terrain () { + get terrain (): ITerrainAsset | null { return this._terrain; } @@ -75,11 +75,11 @@ export class TerrainCollider extends Collider { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - get shape () { + get shape (): ITerrainShape { return this._shape as ITerrainShape; } - protected onEnable () { + protected onEnable (): void { super.onEnable(); if (this.node) { diff --git a/cocos/physics/framework/components/constant-force.ts b/cocos/physics/framework/components/constant-force.ts index e9c7821a064..bdb174239b6 100644 --- a/cocos/physics/framework/components/constant-force.ts +++ b/cocos/physics/framework/components/constant-force.ts @@ -75,7 +75,7 @@ export class ConstantForce extends Component { */ @displayOrder(0) @tooltip('i18n:physics3d.constant_force.force') - public get force () { + public get force (): Vec3 { return this._force; } @@ -92,7 +92,7 @@ export class ConstantForce extends Component { */ @displayOrder(1) @tooltip('i18n:physics3d.constant_force.localForce') - public get localForce () { + public get localForce (): Vec3 { return this._localForce; } @@ -109,7 +109,7 @@ export class ConstantForce extends Component { */ @displayOrder(2) @tooltip('i18n:physics3d.constant_force.torque') - public get torque () { + public get torque (): Vec3 { return this._torque; } @@ -126,7 +126,7 @@ export class ConstantForce extends Component { */ @displayOrder(3) @tooltip('i18n:physics3d.constant_force.localTorque') - public get localTorque () { + public get localTorque (): Vec3 { return this._localTorque; } @@ -135,7 +135,7 @@ export class ConstantForce extends Component { this._maskUpdate(this._localTorque, 8); } - public onLoad () { + public onLoad (): void { this._rigidBody = this.node.getComponent(RigidBody); this._maskUpdate(this._force, 1); this._maskUpdate(this._localForce, 2); @@ -143,7 +143,7 @@ export class ConstantForce extends Component { this._maskUpdate(this._localTorque, 8); } - public lateUpdate (dt: number) { + public lateUpdate (dt: number): void { if (!EDITOR_NOT_IN_PREVIEW) { if (this._rigidBody != null && this._mask !== 0) { if (this._mask & 1) this._rigidBody.applyForce(this._force); @@ -154,7 +154,7 @@ export class ConstantForce extends Component { } } - private _maskUpdate (t: Vec3, m: number) { + private _maskUpdate (t: Vec3, m: number): void { if (t.strictEquals(Vec3.ZERO)) { this._mask &= ~m; } else { diff --git a/cocos/physics/framework/components/constraints/configurable-constraint.ts b/cocos/physics/framework/components/constraints/configurable-constraint.ts index e239336a230..1fa3f4245dd 100644 --- a/cocos/physics/framework/components/constraints/configurable-constraint.ts +++ b/cocos/physics/framework/components/constraints/configurable-constraint.ts @@ -43,7 +43,7 @@ import { IConfigurableConstraint } from '../../../spec/i-physics-constraint'; export class LinearLimitSettings { @type(EConstraintMode) @tooltip('i18n:physics3d.constraint.linearLimit.xMotion') - get xMotion () { + get xMotion (): EConstraintMode { return this._xMotion; } set xMotion (v: EConstraintMode) { @@ -55,7 +55,7 @@ export class LinearLimitSettings { @type(EConstraintMode) @tooltip('i18n:physics3d.constraint.linearLimit.yMotion') - get yMotion () { + get yMotion (): EConstraintMode { return this._yMotion; } set yMotion (v: EConstraintMode) { @@ -67,7 +67,7 @@ export class LinearLimitSettings { @type(EConstraintMode) @tooltip('i18n:physics3d.constraint.linearLimit.zMotion') - get zMotion () { + get zMotion (): EConstraintMode { return this._zMotion; } set zMotion (v: EConstraintMode) { @@ -79,7 +79,7 @@ export class LinearLimitSettings { @type(Vec3) @tooltip('i18n:physics3d.constraint.linearLimit.upper') - get upper () { + get upper (): Vec3 { return this._upper; } set upper (v: Vec3) { @@ -94,7 +94,7 @@ export class LinearLimitSettings { @type(Vec3) @tooltip('i18n:physics3d.constraint.linearLimit.lower') - get lower () { + get lower (): Vec3 { return this._lower; } set lower (v: Vec3) { @@ -109,7 +109,7 @@ export class LinearLimitSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.linearLimit.restitution') - get restitution () { + get restitution (): number { return this._bounciness; } set restitution (v: number) { @@ -122,7 +122,7 @@ export class LinearLimitSettings { @type(CCBoolean) @tooltip('i18n:physics3d.constraint.linearLimit.enableSoftConstraint') @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) - get enableSoftConstraint () { + get enableSoftConstraint (): boolean { return this._enableSoftConstraint; } set enableSoftConstraint (v: boolean) { @@ -135,7 +135,7 @@ export class LinearLimitSettings { @type(CCFloat) @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) @tooltip('i18n:physics3d.constraint.linearLimit.stiffness') - get stiffness () { + get stiffness (): number { return this._stiffness; } set stiffness (v: number) { @@ -148,7 +148,7 @@ export class LinearLimitSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.linearLimit.damping') @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) - get damping () { + get damping (): number { return this._damping; } set damping (v: number) { @@ -194,7 +194,7 @@ export class LinearLimitSettings { export class AngularLimitSettings { @type(EConstraintMode) @tooltip('i18n:physics3d.constraint.angularLimit.twistMotion') - get twistMotion () { + get twistMotion (): EConstraintMode { return this._twistMotion; } set twistMotion (v: EConstraintMode) { @@ -205,7 +205,7 @@ export class AngularLimitSettings { } @type(EConstraintMode) @tooltip('i18n:physics3d.constraint.angularLimit.swingMotion1') - get swingMotion1 () { + get swingMotion1 (): EConstraintMode { return this._swing1Motion; } set swingMotion1 (v: EConstraintMode) { @@ -216,7 +216,7 @@ export class AngularLimitSettings { } @type(EConstraintMode) @tooltip('i18n:physics3d.constraint.angularLimit.swingMotion2') - get swingMotion2 () { + get swingMotion2 (): EConstraintMode { return this._swing2Motion; } set swingMotion2 (v: EConstraintMode) { @@ -228,7 +228,7 @@ export class AngularLimitSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.angularLimit.twistExtent') - get twistExtent () { + get twistExtent (): number { return this._twistExtent; } set twistExtent (v: number) { @@ -240,7 +240,7 @@ export class AngularLimitSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.angularLimit.swingExtent1') - get swingExtent1 () { + get swingExtent1 (): number { return this._swingExtent1; } set swingExtent1 (v: number) { @@ -252,7 +252,7 @@ export class AngularLimitSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.angularLimit.swingExtent2') - get swingExtent2 () { + get swingExtent2 (): number { return this._swingExtent2; } set swingExtent2 (v: number) { @@ -264,7 +264,7 @@ export class AngularLimitSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.angularLimit.twistRestitution') - get twistRestitution () { + get twistRestitution (): number { return this._twistBounciness; } set twistRestitution (v: number) { @@ -276,7 +276,7 @@ export class AngularLimitSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.angularLimit.swingRestitution') - get swingRestitution () { + get swingRestitution (): number { return this._swingBounciness; } set swingRestitution (v: number) { @@ -289,7 +289,7 @@ export class AngularLimitSettings { @type(CCBoolean) @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) @tooltip('i18n:physics3d.constraint.angularLimit.enableSoftConstraintTwist') - get enableSoftConstraintTwist () { + get enableSoftConstraintTwist (): boolean { return this._enableSoftConstraintTwist; } set enableSoftConstraintTwist (v: boolean) { @@ -302,7 +302,7 @@ export class AngularLimitSettings { @type(CCFloat) @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) @tooltip('i18n:physics3d.constraint.angularLimit.twistStiffness') - get twistStiffness () { + get twistStiffness (): number { return this._twistStiffness; } set twistStiffness (v: number) { @@ -315,7 +315,7 @@ export class AngularLimitSettings { @type(CCFloat) @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) @tooltip('i18n:physics3d.constraint.angularLimit.twistDamping') - get twistDamping () { + get twistDamping (): number { return this._twistDamping; } set twistDamping (v: number) { @@ -328,7 +328,7 @@ export class AngularLimitSettings { @type(CCBoolean) @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) @tooltip('i18n:physics3d.constraint.angularLimit.enableSoftConstraintSwing') - get enableSoftConstraintSwing () { + get enableSoftConstraintSwing (): boolean { return this._enableSoftConstraintSwing; } set enableSoftConstraintSwing (v: boolean) { @@ -341,7 +341,7 @@ export class AngularLimitSettings { @type(CCFloat) @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) @tooltip('i18n:physics3d.constraint.angularLimit.swingStiffness') - get swingStiffness () { + get swingStiffness (): number { return this._swingStiffness; } set swingStiffness (v: number) { @@ -354,7 +354,7 @@ export class AngularLimitSettings { @type(CCFloat) @group({ id: 'SoftConstraint', name: 'SoftConstraintSettings' }) @tooltip('i18n:physics3d.constraint.angularLimit.swingDamping') - get swingDamping () { + get swingDamping (): number { return this._swingDamping; } set swingDamping (v: number) { @@ -413,7 +413,7 @@ export class AngularLimitSettings { export class LinearDriverSettings { @type(EDriverMode) @tooltip('i18n:physics3d.constraint.linearDriver.xMode') - get xDrive () { + get xDrive (): EDriverMode { return this._xDrive; } set xDrive (v: EDriverMode) { @@ -425,7 +425,7 @@ export class LinearDriverSettings { @type(EDriverMode) @tooltip('i18n:physics3d.constraint.linearDriver.yMode') - get yDrive () { + get yDrive (): EDriverMode { return this._yDrive; } set yDrive (v: EDriverMode) { @@ -437,7 +437,7 @@ export class LinearDriverSettings { @type(EDriverMode) @tooltip('i18n:physics3d.constraint.linearDriver.zMode') - get zDrive () { + get zDrive (): EDriverMode { return this._zDrive; } set zDrive (v: EDriverMode) { @@ -449,7 +449,7 @@ export class LinearDriverSettings { @type(Vec3) @tooltip('i18n:physics3d.constraint.linearDriver.targetPosition') - get targetPosition () { + get targetPosition (): Vec3 { return this._target; } set targetPosition (v: Vec3) { @@ -461,7 +461,7 @@ export class LinearDriverSettings { @type(Vec3) @tooltip('i18n:physics3d.constraint.linearDriver.targetVelocity') - get targetVelocity () { + get targetVelocity (): Vec3 { return this._velocity; } set targetVelocity (v: Vec3) { @@ -473,7 +473,7 @@ export class LinearDriverSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.linearDriver.strength') - get strength () { + get strength (): number { return this._strength; } set strength (v) { @@ -515,7 +515,7 @@ export class LinearDriverSettings { export class AngularDriverSettings { @type(EDriverMode) @tooltip('i18n:physics3d.constraint.angularDriver.twistMode') - get twistDrive () { + get twistDrive (): EDriverMode { return this._twistDrive; } set twistDrive (v: EDriverMode) { @@ -527,7 +527,7 @@ export class AngularDriverSettings { @type(EDriverMode) @tooltip('i18n:physics3d.constraint.angularDriver.swingMode1') - get swingDrive1 () { + get swingDrive1 (): EDriverMode { return this._swingDrive1; } set swingDrive1 (v: EDriverMode) { @@ -539,7 +539,7 @@ export class AngularDriverSettings { @type(EDriverMode) @tooltip('i18n:physics3d.constraint.angularDriver.swingMode2') - get swingDrive2 () { + get swingDrive2 (): EDriverMode { return this._swingDrive2; } set swingDrive2 (v: EDriverMode) { @@ -551,7 +551,7 @@ export class AngularDriverSettings { @type(Vec3) @tooltip('i18n:physics3d.constraint.angularDriver.targetOrientation') - get targetOrientation () { + get targetOrientation (): Vec3 { return this._targetOrientation; } set targetOrientation (v) { @@ -563,7 +563,7 @@ export class AngularDriverSettings { @type(Vec3) @tooltip('i18n:physics3d.constraint.angularDriver.targetAngularVelocity') - get targetVelocity () { + get targetVelocity (): Vec3 { return this._targetVelocity; } set targetVelocity (v) { @@ -575,7 +575,7 @@ export class AngularDriverSettings { @type(CCFloat) @tooltip('i18n:physics3d.constraint.angularDriver.strength') - get strength () { + get strength (): number { return this._strength; } set strength (v) { @@ -716,7 +716,7 @@ export class ConfigurableConstraint extends Constraint { */ @type(CCFloat) @tooltip('i18n:physics3d.constraint.breakForce') - get breakForce () { + get breakForce (): number { return this._breakForce; } set breakForce (v) { @@ -734,7 +734,7 @@ export class ConfigurableConstraint extends Constraint { */ @type(CCFloat) @tooltip('i18n:physics3d.constraint.breakTorque') - get breakTorque () { + get breakTorque (): number { return this._breakTorque; } set breakTorque (v) { @@ -752,7 +752,7 @@ export class ConfigurableConstraint extends Constraint { */ @type(LinearLimitSettings) @tooltip('i18n:physics3d.constraint.linearLimit') - get linearLimitSettings () { + get linearLimitSettings (): LinearLimitSettings { return this._linearLimitSettings; } set linearLimitSettings (v) { @@ -782,7 +782,7 @@ export class ConfigurableConstraint extends Constraint { */ @type(AngularLimitSettings) @tooltip('i18n:physics3d.constraint.angularLimit') - get angularLimitSettings () { + get angularLimitSettings (): AngularLimitSettings { return this._angularLimitSettings; } set angularLimitSettings (v) { @@ -812,7 +812,7 @@ export class ConfigurableConstraint extends Constraint { */ @type(LinearDriverSettings) @tooltip('i18n:physics3d.constraint.linearDrive') - get linearDriverSettings () { + get linearDriverSettings (): LinearDriverSettings { return this._linearDriverSettings; } set linearDriverSettings (v) { @@ -836,7 +836,7 @@ export class ConfigurableConstraint extends Constraint { */ @type(AngularDriverSettings) @tooltip('i18n:physics3d.constraint.angularDrive') - get angularDriverSettings () { + get angularDriverSettings (): AngularDriverSettings { return this._angularDriverSettings; } set angularDriverSettings (v) { @@ -901,7 +901,7 @@ export class ConfigurableConstraint extends Constraint { this._angularDriverSettings = new AngularDriverSettings(this.constraint); } - onLoad () { + onLoad (): void { super.onLoad(); if (!EDITOR_NOT_IN_PREVIEW) { this.linearLimitSettings.impl = this.constraint; diff --git a/cocos/physics/framework/components/constraints/constraint.ts b/cocos/physics/framework/components/constraints/constraint.ts index 75613d6cf81..2ccd7c3c134 100644 --- a/cocos/physics/framework/components/constraints/constraint.ts +++ b/cocos/physics/framework/components/constraints/constraint.ts @@ -91,7 +91,7 @@ export class Constraint extends Eventify(Component) { */ @displayOrder(0) @tooltip('i18n:physics3d.constraint.enableCollision') - get enableCollision () { + get enableCollision (): boolean { return this._enableCollision; } @@ -127,25 +127,25 @@ export class Constraint extends Eventify(Component) { /// COMPONENT LIFECYCLE /// - protected onLoad () { + protected onLoad (): void { if (!selector.runInEditor) return; this._constraint = createConstraint(this.TYPE); this._constraint.initialize(this); } - protected onEnable () { + protected onEnable (): void { if (this._constraint) { this._constraint.onEnable!(); } } - protected onDisable () { + protected onDisable (): void { if (this._constraint) { this._constraint.onDisable!(); } } - protected onDestroy () { + protected onDestroy (): void { if (this._constraint) { this._constraint.onDestroy!(); } diff --git a/cocos/physics/framework/components/constraints/point-to-point-constraint.ts b/cocos/physics/framework/components/constraints/point-to-point-constraint.ts index 20646409406..4346f30a41d 100644 --- a/cocos/physics/framework/components/constraints/point-to-point-constraint.ts +++ b/cocos/physics/framework/components/constraints/point-to-point-constraint.ts @@ -48,7 +48,7 @@ export class PointToPointConstraint extends Constraint { */ @type(Vec3) @tooltip('i18n:physics3d.constraint.pivotA') - get pivotA () { + get pivotA (): IVec3Like { return this._pivotA; } @@ -67,7 +67,7 @@ export class PointToPointConstraint extends Constraint { */ @type(Vec3) @tooltip('i18n:physics3d.constraint.pivotB') - get pivotB () { + get pivotB (): IVec3Like { return this._pivotB; } diff --git a/cocos/physics/framework/components/rigid-body.ts b/cocos/physics/framework/components/rigid-body.ts index 4125815e402..9ba7bc50f40 100644 --- a/cocos/physics/framework/components/rigid-body.ts +++ b/cocos/physics/framework/components/rigid-body.ts @@ -118,7 +118,7 @@ export class RigidBody extends Component { @visible(isDynamicBody) @displayOrder(0) @tooltip('i18n:physics3d.rigidbody.mass') - public get mass () { + public get mass (): number { return this._mass; } @@ -157,7 +157,7 @@ export class RigidBody extends Component { @visible(isDynamicBody) @displayOrder(1) @tooltip('i18n:physics3d.rigidbody.linearDamping') - public get linearDamping () { + public get linearDamping (): number { return this._linearDamping; } @@ -176,7 +176,7 @@ export class RigidBody extends Component { @visible(isDynamicBody) @displayOrder(2) @tooltip('i18n:physics3d.rigidbody.angularDamping') - public get angularDamping () { + public get angularDamping (): number { return this._angularDamping; } @@ -195,7 +195,7 @@ export class RigidBody extends Component { @visible(isDynamicBody) @displayOrder(4) @tooltip('i18n:physics3d.rigidbody.useGravity') - public get useGravity () { + public get useGravity (): boolean { return this._useGravity; } @@ -213,7 +213,7 @@ export class RigidBody extends Component { @visible(isDynamicBody) @displayOrder(6) @tooltip('i18n:physics3d.rigidbody.linearFactor') - public get linearFactor () { + public get linearFactor (): Vec3 { return this._linearFactor; } @@ -233,7 +233,7 @@ export class RigidBody extends Component { @visible(isDynamicBody) @displayOrder(7) @tooltip('i18n:physics3d.rigidbody.angularFactor') - public get angularFactor () { + public get angularFactor (): Vec3 { return this._angularFactor; } @@ -351,7 +351,7 @@ export class RigidBody extends Component { * @zh * 获取或设置刚体是否是运动态类型的(将由用户来控制运动)。 */ - public get isKinematic () { + public get isKinematic (): boolean { return this._type === ERigidBodyType.KINEMATIC; } @@ -366,7 +366,7 @@ export class RigidBody extends Component { * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ - public get body () { + public get body (): IRigidBody | null { return this._body; } @@ -409,21 +409,21 @@ export class RigidBody extends Component { /// COMPONENT LIFECYCLE /// - protected onLoad () { + protected onLoad (): void { if (!selector.runInEditor) return; this._body = createRigidBody(); this._body.initialize(this); } - protected onEnable () { + protected onEnable (): void { if (this._body) this._body.onEnable!(); } - protected onDisable () { + protected onDisable (): void { if (this._body) this._body.onDisable!(); } - protected onDestroy () { + protected onDestroy (): void { if (this._body) this._body.onDestroy!(); } @@ -437,7 +437,7 @@ export class RigidBody extends Component { * @param force @zh 作用力 @en The force applied * @param relativePoint @zh 作用点,相对于刚体的质心 @en The point to apply the force on, relative to the center of mass of the rigid body */ - public applyForce (force: Vec3, relativePoint?: Vec3) { + public applyForce (force: Vec3, relativePoint?: Vec3): void { if (this._isInitialized) this._body!.applyForce(force, relativePoint); } @@ -449,7 +449,7 @@ export class RigidBody extends Component { * @param force @zh 作用力 @en The force applied * @param localPoint @zh 作用点 @en The point to apply the force on */ - public applyLocalForce (force: Vec3, localPoint?: Vec3) { + public applyLocalForce (force: Vec3, localPoint?: Vec3): void { if (this._isInitialized) this._body!.applyLocalForce(force, localPoint); } @@ -461,7 +461,7 @@ export class RigidBody extends Component { * @param impulse @zh 冲量 @en The impulse applied * @param relativePoint @zh 作用点,相对于刚体的中心点 @en The point to apply the impulse, relative to the center of mass of the rigid body */ - public applyImpulse (impulse: Vec3, relativePoint?: Vec3) { + public applyImpulse (impulse: Vec3, relativePoint?: Vec3): void { if (this._isInitialized) this._body!.applyImpulse(impulse, relativePoint); } @@ -473,7 +473,7 @@ export class RigidBody extends Component { * @param impulse @zh 冲量 @en The impulse applied * @param localPoint @zh 作用点 @en The point to apply the impulse */ - public applyLocalImpulse (impulse: Vec3, localPoint?: Vec3) { + public applyLocalImpulse (impulse: Vec3, localPoint?: Vec3): void { if (this._isInitialized) this._body!.applyLocalImpulse(impulse, localPoint); } @@ -484,7 +484,7 @@ export class RigidBody extends Component { * 在世界空间中,对刚体施加扭矩。 * @param torque @zh 扭矩 @en The torque applied */ - public applyTorque (torque: Vec3) { + public applyTorque (torque: Vec3): void { if (this._isInitialized) this._body!.applyTorque(torque); } @@ -495,7 +495,7 @@ export class RigidBody extends Component { * In local space, torque is applied to the rigid body. * @param torque @zh 扭矩 @en The torque applied */ - public applyLocalTorque (torque: Vec3) { + public applyLocalTorque (torque: Vec3): void { if (this._isInitialized) this._body!.applyLocalTorque(torque); } @@ -505,7 +505,7 @@ export class RigidBody extends Component { * @zh * 唤醒刚体。 */ - public wakeUp () { + public wakeUp (): void { if (this._isInitialized) this._body!.wakeUp(); } @@ -515,7 +515,7 @@ export class RigidBody extends Component { * @zh * 休眠刚体。 */ - public sleep () { + public sleep (): void { if (this._isInitialized) this._body!.sleep(); } @@ -525,7 +525,7 @@ export class RigidBody extends Component { * @zh * 清除刚体受到的力和速度。 */ - public clearState () { + public clearState (): void { if (this._isInitialized) this._body!.clearState(); } @@ -535,7 +535,7 @@ export class RigidBody extends Component { * @zh * 清除刚体受到的力。 */ - public clearForces () { + public clearForces (): void { if (this._isInitialized) this._body!.clearForces(); } @@ -545,7 +545,7 @@ export class RigidBody extends Component { * @zh * 清除刚体的速度。 */ - public clearVelocity () { + public clearVelocity (): void { if (this._isInitialized) this._body!.clearVelocity(); } @@ -556,7 +556,7 @@ export class RigidBody extends Component { * 获取线性速度。 * @param out @zh 速度向量 @en The velocity vector */ - public getLinearVelocity (out: Vec3) { + public getLinearVelocity (out: Vec3): void { if (this._isInitialized) this._body!.getLinearVelocity(out); } @@ -578,7 +578,7 @@ export class RigidBody extends Component { * 获取旋转速度。 * @param out @zh 角速度向量 @en The angular velocity vector */ - public getAngularVelocity (out: Vec3) { + public getAngularVelocity (out: Vec3): void { if (this._isInitialized) this._body!.getAngularVelocity(out); } @@ -625,7 +625,7 @@ export class RigidBody extends Component { * 添加分组值,可填要加入的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ - public addGroup (v: number) { + public addGroup (v: number): void { if (this._isInitialized) this._body!.addGroup(v); } @@ -636,7 +636,7 @@ export class RigidBody extends Component { * 减去分组值,可填要移除的 group。 * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ - public removeGroup (v: number) { + public removeGroup (v: number): void { if (this._isInitialized) this._body!.removeGroup(v); } @@ -659,7 +659,7 @@ export class RigidBody extends Component { * 设置掩码值。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public setMask (v: number) { + public setMask (v: number): void { if (this._isInitialized) this._body!.setMask(v); } @@ -670,7 +670,7 @@ export class RigidBody extends Component { * 添加掩码值,可填入需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public addMask (v: number) { + public addMask (v: number): void { if (this._isInitialized) this._body!.addMask(v); } @@ -681,12 +681,12 @@ export class RigidBody extends Component { * 减去掩码值,可填入不需要检查的 group。 * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ - public removeMask (v: number) { + public removeMask (v: number): void { if (this._isInitialized) this._body!.removeMask(v); } } -function isDynamicBody (this: RigidBody) { return this.isDynamic; } +function isDynamicBody (this: RigidBody): boolean { return this.isDynamic; } export namespace RigidBody { export type Type = EnumAlias; diff --git a/cocos/physics/framework/physics-ray-result.ts b/cocos/physics/framework/physics-ray-result.ts index 374055979f2..4c2d4b02fb6 100644 --- a/cocos/physics/framework/physics-ray-result.ts +++ b/cocos/physics/framework/physics-ray-result.ts @@ -85,7 +85,7 @@ export class PhysicsRayResult { * * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _assign (hitPoint: IVec3Like, distance: number, collider: Collider, hitNormal: IVec3Like) { + public _assign (hitPoint: IVec3Like, distance: number, collider: Collider, hitNormal: IVec3Like): void { Vec3.copy(this._hitPoint, hitPoint); Vec3.copy(this._hitNormal, hitNormal); this._distance = distance; @@ -98,7 +98,7 @@ export class PhysicsRayResult { * @zh * 克隆。 */ - public clone () { + public clone (): PhysicsRayResult { const c = new PhysicsRayResult(); Vec3.copy(c._hitPoint, this._hitPoint); Vec3.copy(c._hitNormal, this._hitNormal); @@ -134,7 +134,7 @@ export class PhysicsLineStripCastResult extends PhysicsRayResult { * 设置射线,此方法由引擎内部使用,请勿在外部脚本调用。 * @engineInternal */ - public _assign (hitPoint: IVec3Like, distance: number, collider: Collider, hitNormal: IVec3Like, id = 0) { + public _assign (hitPoint: IVec3Like, distance: number, collider: Collider, hitNormal: IVec3Like, id = 0): void { super._assign(hitPoint, distance, collider, hitNormal); this._id = id; } @@ -145,7 +145,7 @@ export class PhysicsLineStripCastResult extends PhysicsRayResult { * @zh * 克隆。 */ - public clone () { + public clone (): PhysicsLineStripCastResult { const c = new PhysicsLineStripCastResult(); Vec3.copy(c._hitPoint, this._hitPoint); Vec3.copy(c._hitNormal, this._hitNormal); diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 3e803b2c7e2..b7041aa82f0 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -118,7 +118,7 @@ interface IPhysicsSelector { [x: string]: any, } -function updateLegacyMacro (id: string) { +function updateLegacyMacro (id: string): void { cclegacy._global.CC_PHYSICS_BUILTIN = id === 'builtin'; cclegacy._global.CC_PHYSICS_CANNON = id === 'cannon.js'; cclegacy._global.CC_PHYSICS_AMMO = id === 'bullet'; @@ -142,7 +142,7 @@ export interface IWorldInitData { } let worldInitData: IWorldInitData | null; -function switchTo (id: IPhysicsEngineId) { +function switchTo (id: IPhysicsEngineId): void { if (!selector.runInEditor) return; const mutableSelector = selector as Mutable; if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) { @@ -181,7 +181,7 @@ export const selector: IPhysicsSelector = { runInEditor: !EDITOR, }; -export function constructDefaultWorld (data: IWorldInitData) { +export function constructDefaultWorld (data: IWorldInitData): void { if (!worldInitData) worldInitData = data; if (!selector.runInEditor) return; if (!selector.physicsWorld) { @@ -195,7 +195,7 @@ export function constructDefaultWorld (data: IWorldInitData) { /// Utility Function For Create Wrapper Entity /// -const FUNC = (...v: any) => 0 as any; +const FUNC = (...v: any): any => 0 as any; const ENTIRE_WORLD: IPhysicsWorld = { impl: null, setGravity: FUNC, @@ -240,7 +240,7 @@ enum ECheckType { CapsuleCharacterController, } -function check (obj: any, type: ECheckType) { +function check (obj: any, type: ECheckType): boolean { if (obj == null) { if (selector.id) { warn(`${selector.id} physics does not support ${ECheckType[type]}`); @@ -361,7 +361,7 @@ export function createShape (type: EColliderType): IBaseShape { return CREATE_COLLIDER_PROXY[type](); } -function initColliderProxy () { +function initColliderProxy (): void { if (CREATE_COLLIDER_PROXY.INITED) return; CREATE_COLLIDER_PROXY.INITED = true; @@ -467,7 +467,7 @@ export function createConstraint (type: EConstraintType): IBaseConstraint { return CREATE_CONSTRAINT_PROXY[type](); } -function initConstraintProxy () { +function initConstraintProxy (): void { if (CREATE_CONSTRAINT_PROXY.INITED) return; CREATE_CONSTRAINT_PROXY.INITED = true; @@ -539,7 +539,7 @@ export function createCharacterController (type: ECharacterControllerType): IEnt return CREATE_CHARACTER_CONTROLLER_PROXY[type](); } -function initCharacterControllerProxy () { +function initCharacterControllerProxy (): void { if (CREATE_CHARACTER_CONTROLLER_PROXY.INITED) return; CREATE_CHARACTER_CONTROLLER_PROXY.INITED = true; diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index d07698b2219..ae6668b9642 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -24,7 +24,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { Vec3, RecyclePool, Enum, System, cclegacy, Settings, settings, geometry, warn, IQuatLike, IVec3Like } from '../../core'; -import { IRaycastOptions } from '../spec/i-physics-world'; +import { IPhysicsWorld, IRaycastOptions } from '../spec/i-physics-world'; import { director, Director, game } from '../../game'; import { PhysicsMaterial } from './assets/physics-material'; import { PhysicsRayResult, PhysicsLineStripCastResult } from './physics-ray-result'; @@ -44,23 +44,23 @@ cclegacy.internal.PhysicsGroup = PhysicsGroup; * 物理系统。 */ export class PhysicsSystem extends System implements IWorldInitData { - public static get PHYSICS_NONE () { + public static get PHYSICS_NONE (): boolean { return !selector.id; } - public static get PHYSICS_BUILTIN () { + public static get PHYSICS_BUILTIN (): boolean { return selector.id === 'builtin'; } - public static get PHYSICS_CANNON () { + public static get PHYSICS_CANNON (): boolean { return selector.id === 'cannon.js'; } - public static get PHYSICS_BULLET () { + public static get PHYSICS_BULLET (): boolean { return selector.id === 'bullet'; } - public static get PHYSICS_PHYSX () { + public static get PHYSICS_PHYSX (): boolean { return selector.id === 'physx'; } @@ -78,7 +78,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 获取预定义的物理分组。 */ - public static get PhysicsGroup () { + public static get PhysicsGroup (): typeof PhysicsGroup { return PhysicsGroup; } @@ -129,7 +129,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 获取或设置每帧模拟的最大子步数。 */ - public get maxSubSteps () { + public get maxSubSteps (): number { return this._maxSubSteps; } @@ -143,7 +143,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 获取或设置每步模拟消耗的固定时间(以 s 为单位)。 */ - public get fixedTimeStep () { + public get fixedTimeStep (): number { return this._fixedTimeStep; } @@ -188,7 +188,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 获取或设置是否自动模拟。 */ - public get autoSimulation () { + public get autoSimulation (): boolean { return this._autoSimulation; } @@ -212,7 +212,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 设置默认物理材质。 */ - public setDefaultPhysicsMaterial (material: PhysicsMaterial) { + public setDefaultPhysicsMaterial (material: PhysicsMaterial): void { this._material = material; this.physicsWorld.setDefaultMaterial(this._material); this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this); @@ -233,13 +233,13 @@ export class PhysicsSystem extends System implements IWorldInitData { this.setDefaultPhysicsMaterial(builtinMaterial); return Promise.resolve(); } else { //use user customized default physics material - return new Promise((resolve, reject) => { - assetManager.loadAny(userMaterial, (err, asset) => ((err || !(asset instanceof PhysicsMaterial)) + return new Promise((resolve, reject): void => { + assetManager.loadAny(userMaterial, (err, asset): void => ((err || !(asset instanceof PhysicsMaterial)) ? reject(err) : resolve(asset))); - }).then((asset) => { + }).then((asset): void => { this.setDefaultPhysicsMaterial(asset); - }).catch((reason) => { + }).catch((reason): void => { warn(reason); warn(`Failed to load user customized default physics material: ${userMaterial}, will fallback to built-in default physics material`); this.setDefaultPhysicsMaterial(builtinMaterial); @@ -253,7 +253,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 获取物理世界的封装对象,通过它你可以访问到实际的底层对象。 */ - public get physicsWorld () { + public get physicsWorld (): IPhysicsWorld { return selector.physicsWorld!; } @@ -341,14 +341,14 @@ export class PhysicsSystem extends System implements IWorldInitData { maxDistance: 10000000, } - private readonly raycastResultPool = new RecyclePool(() => new PhysicsRayResult(), 1); - private readonly sweepResultPool = new RecyclePool(() => new PhysicsRayResult(), 1); + private readonly raycastResultPool = new RecyclePool((): PhysicsRayResult => new PhysicsRayResult(), 1); + private readonly sweepResultPool = new RecyclePool((): PhysicsRayResult => new PhysicsRayResult(), 1); private constructor () { super(); } - postUpdate (deltaTime: number) { + postUpdate (deltaTime: number): void { if (EDITOR_NOT_IN_PREVIEW && !this._executeInEditMode && !selector.runInEditor) return; if (!this.physicsWorld) return; @@ -385,7 +385,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 重置物理配置。 */ - resetConfiguration (config?: IPhysicsConfig) { + resetConfiguration (config?: IPhysicsConfig): void { const allowSleep = config ? config.allowSleep : settings.querySettings(Settings.Category.PHYSICS, 'allowSleep'); if (typeof allowSleep === 'boolean') this._allowSleep = allowSleep; const fixedTimeStep = config ? config.fixedTimeStep : settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep'); @@ -410,7 +410,7 @@ export class PhysicsSystem extends System implements IWorldInitData { if (collisionGroups) { const cg = collisionGroups; if (cg instanceof Array) { - cg.forEach((v) => { PhysicsGroup[v.name] = 1 << v.index; }); + cg.forEach((v): void => { PhysicsGroup[v.name] = 1 << v.index; }); Enum.update(PhysicsGroup); } } @@ -427,7 +427,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 重置时间累积总量为给定值。 */ - resetAccumulator (time = 0) { + resetAccumulator (time = 0): void { this._accumulator = time; } @@ -438,7 +438,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * 执行物理世界的模拟步进。 * @param fixedTimeStep */ - step (fixedTimeStep: number, deltaTime?: number, maxSubSteps?: number) { + step (fixedTimeStep: number, deltaTime?: number, maxSubSteps?: number): void { if (this.physicsWorld) this.physicsWorld.step(fixedTimeStep, deltaTime, maxSubSteps); } @@ -448,7 +448,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 同步场景世界的变化信息到物理世界中。 */ - syncSceneToPhysics () { + syncSceneToPhysics (): void { if (this.physicsWorld) this.physicsWorld.syncSceneToPhysics(); } @@ -458,7 +458,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * @zh * 触发`trigger`和`collision`事件。 */ - emitEvents () { + emitEvents (): void { if (this.physicsWorld) this.physicsWorld.emitEvents(); } @@ -752,7 +752,7 @@ export class PhysicsSystem extends System implements IWorldInitData { this.raycastOptions, this.sweepCastClosestResult); } - private _updateMaterial () { + private _updateMaterial (): void { if (this.physicsWorld) this.physicsWorld.setDefaultMaterial(this._material); } @@ -764,7 +764,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * 构造并注册系统单例。 * 预先加载模块的情况下,会自动执行。 */ - static constructAndRegister () { + static constructAndRegister (): void { const enabled = settings.querySettings(Settings.Category.PHYSICS, 'enabled') ?? true; if (!enabled) { return; } if (!PhysicsSystem._instance) { @@ -784,4 +784,4 @@ export class PhysicsSystem extends System implements IWorldInitData { * By registering the initialization event, the system can be automatically * constructed and registered when the module is pre-loaded */ -director.once(Director.EVENT_INIT, () => { PhysicsSystem.constructAndRegister(); }); +director.once(Director.EVENT_INIT, (): void => { PhysicsSystem.constructAndRegister(); }); diff --git a/cocos/physics/physx/character-controllers/physx-character-controller.ts b/cocos/physics/physx/character-controllers/physx-character-controller.ts index 841c6558e93..da7d3e9d703 100644 --- a/cocos/physics/physx/character-controllers/physx-character-controller.ts +++ b/cocos/physics/physx/character-controllers/physx-character-controller.ts @@ -52,12 +52,12 @@ export class PhysXCharacterController implements IBaseCharacterController { } get characterController (): CharacterController { return this._comp; } - get filterData () { + get filterData (): any { /* eslint-disable @typescript-eslint/no-unsafe-return */ return this._filterData; } - get queryFilterCB () { + get queryFilterCB (): any { /* eslint-disable @typescript-eslint/no-unsafe-return */ return this._queryFilterCB; } @@ -189,11 +189,11 @@ export class PhysXCharacterController implements IBaseCharacterController { this._comp.node.setWorldPosition(v3_0); } - syncScale () { + syncScale (): void { this.updateScale(); } - get scaledCenter () { + get scaledCenter (): Vec3 { Vec3.multiply(v3_1, this._comp.center, this._comp.node.worldScale); return v3_1; } @@ -225,7 +225,7 @@ export class PhysXCharacterController implements IBaseCharacterController { }, }; - move (movement: IVec3Like, minDist: number, elapsedTime: number) { + move (movement: IVec3Like, minDist: number, elapsedTime: number): void { if (!this._isEnabled) { return; } (PhysicsSystem.instance.physicsWorld as PhysXWorld).controllerManager.setOverlapRecoveryModule(this._overlapRecovery); this._pxCollisionFlags = this._impl.move(movement, minDist, elapsedTime, this.filterData, this.queryFilterCB); @@ -275,11 +275,11 @@ export class PhysXCharacterController implements IBaseCharacterController { this.updateFilterData(); } - updateEventListener () { + updateEventListener (): void { this.updateFilterData(); } - updateFilterData () { + updateFilterData (): void { if (!this._impl) return; // this._impl.setQueryFilterData(filterData);//set inside move() this._impl.setSimulationFilterData(this.filterData); diff --git a/cocos/physics/physx/joints/physx-configurable-joint.ts b/cocos/physics/physx/joints/physx-configurable-joint.ts index 8e04691b42c..fcedd4401e1 100644 --- a/cocos/physics/physx/joints/physx-configurable-joint.ts +++ b/cocos/physics/physx/joints/physx-configurable-joint.ts @@ -37,7 +37,7 @@ const CC_QUAT_0 = new Quat(); const CC_QUAT_1 = new Quat(); const CC_MAT4_0 = new Mat4(); -function getConstraintFlag (v: EConstraintMode) { +function getConstraintFlag (v: EConstraintMode): any { switch (v) { case EConstraintMode.FREE: return PX.D6Motion.eFREE; case EConstraintMode.LIMITED: return PX.D6Motion.eLIMITED; @@ -48,14 +48,14 @@ function getConstraintFlag (v: EConstraintMode) { } export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableConstraint { - protected _setLinearLimit () { + protected _setLinearLimit (): void { const linearLimit = this.constraint.linearLimitSettings; const limitPairX = PhysXConfigurableJoint._linearLimitX; const limitPairY = PhysXConfigurableJoint._linearLimitY; const limitPairZ = PhysXConfigurableJoint._linearLimitZ; - const setLimitPair = (limitPair: any) => { + const setLimitPair = (limitPair: any): void => { if (linearLimit.enableSoftConstraint) { limitPair.stiffness = linearLimit.stiffness; limitPair.damping = linearLimit.damping; @@ -93,7 +93,7 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC } } - protected _setSwingLimit () { + protected _setSwingLimit (): void { const angularLimit = this.constraint.angularLimitSettings; const limitCone = PhysXConfigurableJoint._swingLimit; @@ -121,7 +121,7 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC } } - protected _setTwistLimit () { + protected _setTwistLimit (): void { const angularLimit = this.constraint.angularLimitSettings; const limitPair = PhysXConfigurableJoint._twistLimit; @@ -144,14 +144,14 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC } } - protected _updateDrive (idx: number) { + protected _updateDrive (idx: number): void { let axis = PX.D6Axis.eX; let driveMode = EDriverMode.DISABLED; const com = this.constraint; const ld = com.linearDriverSettings; const ad = com.angularDriverSettings; - const getSwingDriveMode = () => { + const getSwingDriveMode = (): EDriverMode => { const ad = this.constraint.angularDriverSettings; if (ad.swingDrive1 === EDriverMode.INDUCTION || ad.swingDrive2 === EDriverMode.INDUCTION) { return EDriverMode.INDUCTION; @@ -189,7 +189,7 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC this._impl.setDrive(axis, drive); } - protected _updateDriveTarget () { + protected _updateDriveTarget (): void { const linearTarget = this.constraint.linearDriverSettings.targetPosition; const angularTarget = this.constraint.angularDriverSettings.targetOrientation; const quat = Quat.fromEuler(CC_QUAT_0, angularTarget.x, angularTarget.y, angularTarget.z); @@ -197,7 +197,7 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC this._impl.setDrivePosition(_pxtrans, true); } - protected _updateDriveVelocity () { + protected _updateDriveVelocity (): void { const linearVelocity = this.constraint.linearDriverSettings.targetVelocity; const angularVelocity = this.constraint.angularDriverSettings.targetVelocity; const lv = Vec3.set(CC_V3_0, linearVelocity.x, linearVelocity.y, linearVelocity.z); @@ -205,7 +205,7 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC this._impl.setDriveVelocity(lv, av, true); } - protected _updateDriveSettings () { + protected _updateDriveSettings (): void { this._updateDrive(0); this._updateDrive(1); this._updateDrive(2); @@ -361,7 +361,7 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC this.updateFrames(); } - updateFrames () { + updateFrames (): void { const cs = this.constraint; const node = cs.node; const pos = _trans.translation; @@ -426,7 +426,7 @@ export class PhysXConfigurableJoint extends PhysXJoint implements IConfigurableC private static _drive_swing1: any= null; private static _drive_swing2: any= null; private static _drive: any[] = []; - private static _initCache () { + private static _initCache (): void { if (!PhysXConfigurableJoint._jointToleranceScale) { PhysXConfigurableJoint._jointToleranceScale = PhysXInstance.physics.getTolerancesScale(); PhysXConfigurableJoint._linearLimitX = new PX.PxJointLinearLimitPair(PhysXConfigurableJoint._jointToleranceScale, 0, 0); diff --git a/cocos/physics/physx/joints/physx-fixed-joint.ts b/cocos/physics/physx/joints/physx-fixed-joint.ts index 58a27b4d14d..1609e81cf11 100644 --- a/cocos/physics/physx/joints/physx-fixed-joint.ts +++ b/cocos/physics/physx/joints/physx-fixed-joint.ts @@ -61,7 +61,7 @@ export class PhysXFixedJoint extends PhysXJoint implements IFixedConstraint { this.updateFrame(); } - updateFrame () { + updateFrame (): void { const bodyA = (this._rigidBody.body as PhysXRigidBody).sharedBody; const cb = this.constraint.connectedBody; @@ -83,11 +83,11 @@ export class PhysXFixedJoint extends PhysXJoint implements IFixedConstraint { } } - updateScale0 () { + updateScale0 (): void { this.updateFrame(); } - updateScale1 () { + updateScale1 (): void { this.updateFrame(); } } diff --git a/cocos/physics/physx/joints/physx-joint.ts b/cocos/physics/physx/joints/physx-joint.ts index bc55b1911cd..86a5dd5a691 100644 --- a/cocos/physics/physx/joints/physx-joint.ts +++ b/cocos/physics/physx/joints/physx-joint.ts @@ -74,7 +74,7 @@ export class PhysXJoint implements IBaseConstraint { } get impl (): any { return this._impl; } - get constraint () { return this._com; } + get constraint (): Constraint { return this._com; } protected _impl!: any; protected _com!: Constraint; @@ -96,8 +96,8 @@ export class PhysXJoint implements IBaseConstraint { protected onComponentSet (): void { } // virtual - updateScale0 () { } - updateScale1 () { } + updateScale0 (): void { } + updateScale1 (): void { } onEnable (): void { const sb = (this._rigidBody.body as PhysXRigidBody).sharedBody; diff --git a/cocos/physics/physx/joints/physx-revolute-joint.ts b/cocos/physics/physx/joints/physx-revolute-joint.ts index 042193f730d..4099c72b52e 100644 --- a/cocos/physics/physx/joints/physx-revolute-joint.ts +++ b/cocos/physics/physx/joints/physx-revolute-joint.ts @@ -115,7 +115,7 @@ export class PhysXRevoluteJoint extends PhysXJoint implements IHingeConstraint { this.updateFrames(); } - updateFrames () { + updateFrames (): void { const cs = this.constraint; const cb = cs.connectedBody; const pos = _trans.translation; @@ -163,11 +163,11 @@ export class PhysXRevoluteJoint extends PhysXJoint implements IHingeConstraint { this._impl.setLocalPose(1, getTempTransform(pos, quat_0)); } - updateScale0 () { + updateScale0 (): void { this.updateFrames(); } - updateScale1 () { + updateScale1 (): void { this.updateFrames(); } } diff --git a/cocos/physics/physx/joints/physx-spherical-joint.ts b/cocos/physics/physx/joints/physx-spherical-joint.ts index 9edaa6642d3..cba277046cd 100644 --- a/cocos/physics/physx/joints/physx-spherical-joint.ts +++ b/cocos/physics/physx/joints/physx-spherical-joint.ts @@ -68,11 +68,11 @@ export class PhysXSphericalJoint extends PhysXJoint implements IPointToPointCons this.setPivotB(this.constraint.pivotB); } - updateScale0 () { + updateScale0 (): void { this.setPivotA(this.constraint.pivotA); } - updateScale1 () { + updateScale1 (): void { this.setPivotB(this.constraint.pivotB); } } diff --git a/cocos/physics/physx/physx-adapter.ts b/cocos/physics/physx/physx-adapter.ts index 105f6258a73..0ef51b2e365 100644 --- a/cocos/physics/physx/physx-adapter.ts +++ b/cocos/physics/physx/physx-adapter.ts @@ -57,7 +57,7 @@ const USE_EXTERNAL_PHYSX = !!globalThis.PHYSX; // Init physx libs when engine init. game.onPostInfrastructureInitDelegate.add(InitPhysXLibs); -export function InitPhysXLibs () { +export function InitPhysXLibs (): any { if (USE_BYTEDANCE) { if (!EDITOR && !TEST) console.debug('[PHYSICS]:', `Use PhysX Libs in BYTEDANCE.`); Object.assign(PX, globalThis.nativePhysX); @@ -80,48 +80,48 @@ export function InitPhysXLibs () { } } -function initASM () { +function initASM (): any { globalThis.PhysX = globalThis.PHYSX ? globalThis.PHYSX : asmFactory; if (globalThis.PhysX != null) { - return globalThis.PhysX().then((Instance: any) => { + return globalThis.PhysX().then((Instance: any): void => { if (!EDITOR && !TEST) console.debug('[PHYSICS]:', `${USE_EXTERNAL_PHYSX ? 'External' : 'Internal'} PhysX asm libs loaded.`); initAdaptWrapper(Instance); initConfigAndCacheObject(Instance); Object.assign(PX, Instance); - }, (reason: any) => { console.error('[PHYSICS]:', `PhysX asm load failed: ${reason}`); }); + }, (reason: any): void => { console.error('[PHYSICS]:', `PhysX asm load failed: ${reason}`); }); } else { if (!EDITOR && !TEST) console.error('[PHYSICS]:', 'Failed to load PhysX js libs, package may be not found.'); - return new Promise((resolve, reject) => { + return new Promise((resolve, reject): void => { resolve(); }); } } -function initWASM () { +function initWASM (): any { globalThis.PhysX = globalThis.PHYSX ? globalThis.PHYSX : wasmFactory; if (globalThis.PhysX != null) { return globalThis.PhysX({ instantiateWasm (importObject: WebAssembly.Imports, - receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void) { - return instantiateWasm(PhysXWasmUrl, importObject).then((result: any) => { + receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void): any { + return instantiateWasm(PhysXWasmUrl, importObject).then((result: any): void => { receiveInstance(result.instance, result.module); }); }, - }).then((Instance: any) => { + }).then((Instance: any): void => { if (!EDITOR && !TEST) console.debug('[PHYSICS]:', `${USE_EXTERNAL_PHYSX ? 'External' : 'Internal'} PhysX wasm libs loaded.`); initAdaptWrapper(Instance); initConfigAndCacheObject(Instance); Object.assign(PX, Instance); - }, (reason: any) => { console.error('[PHYSICS]:', `PhysX wasm load failed: ${reason}`); }); + }, (reason: any): void => { console.error('[PHYSICS]:', `PhysX wasm load failed: ${reason}`); }); } else { if (!EDITOR && !TEST) console.error('[PHYSICS]:', 'Failed to load PhysX wasm libs, package may be not found.'); - return new Promise((resolve, reject) => { + return new Promise((resolve, reject): void => { resolve(); }); } } -function initConfigAndCacheObject (PX: any) { +function initConfigAndCacheObject (PX: any): void { globalThis.PhysX = PX; PX.EPSILON = 1e-3; PX.MULTI_THREAD = false; @@ -133,7 +133,7 @@ function initConfigAndCacheObject (PX: any) { PX.TERRAIN_STATIC = {}; } -function initAdaptWrapper (obj: any) { +function initAdaptWrapper (obj: any): void { obj.VECTOR_MAT = new obj.PxMaterialVector(); obj.MeshScale = obj.PxMeshScale; obj.ShapeFlag = obj.PxShapeFlag; @@ -181,7 +181,7 @@ type IPxTransformExt = { [x in keyof typeof _trans]: typeof _trans[x]; } & export const _pxtrans = _trans as unknown as IPxTransformExt; -export function addReference (shape: PhysXShape, impl: any) { +export function addReference (shape: PhysXShape, impl: any): void { if (!impl) return; if (USE_BYTEDANCE) { PX.IMPL_PTR[shape.id] = shape; @@ -191,7 +191,7 @@ export function addReference (shape: PhysXShape, impl: any) { } } -export function removeReference (shape: PhysXShape, impl: any) { +export function removeReference (shape: PhysXShape, impl: any): void { if (!impl) return; if (USE_BYTEDANCE) { PX.IMPL_PTR[shape.id] = null; @@ -229,7 +229,7 @@ export function getJsTransform (pos: IVec3Like, quat: IQuatLike): any { return _trans; } -export function addActorToScene (scene: any, actor: any) { +export function addActorToScene (scene: any, actor: any): void { if (USE_BYTEDANCE) { scene.addActor(actor); } else { @@ -278,7 +278,7 @@ export function physXEqualsCocosQuat (trans: any, q: IQuatLike): boolean { return Quat.equals(rot, q, PX.EPSILON); } -export function applyImpulse (isGlobal: boolean, impl: any, vec: IVec3Like, rp: IVec3Like) { +export function applyImpulse (isGlobal: boolean, impl: any, vec: IVec3Like, rp: IVec3Like): void { if (isGlobal) { if (USE_BYTEDANCE) { PX.RigidBodyExt.applyImpulse(impl, vec, rp); @@ -292,7 +292,7 @@ export function applyImpulse (isGlobal: boolean, impl: any, vec: IVec3Like, rp: } } -export function applyForce (isGlobal: boolean, impl: any, vec: IVec3Like, rp: IVec3Like) { +export function applyForce (isGlobal: boolean, impl: any, vec: IVec3Like, rp: IVec3Like): void { if (isGlobal) { if (USE_BYTEDANCE) { PX.RigidBodyExt.applyForce(impl, vec, rp); @@ -306,7 +306,7 @@ export function applyForce (isGlobal: boolean, impl: any, vec: IVec3Like, rp: IV } } -export function applyTorqueForce (impl: any, vec: IVec3Like) { +export function applyTorqueForce (impl: any, vec: IVec3Like): void { if (USE_BYTEDANCE) { impl.addTorque(vec, PX.ForceMode.eFORCE, true); } else { @@ -325,7 +325,7 @@ export function getShapeFlags (isTrigger: boolean): any { return new PX.PxShapeFlags(flag); } -export function getShapeWorldBounds (shape: any, actor: any, i = 1.01, out: geometry.AABB) { +export function getShapeWorldBounds (shape: any, actor: any, i = 1.01, out: geometry.AABB): void { if (USE_BYTEDANCE) { const b3 = PX.RigidActorExt.getWorldBounds(shape, actor, i); geometry.AABB.fromPoints(out, b3.minimum, b3.maximum); @@ -335,7 +335,7 @@ export function getShapeWorldBounds (shape: any, actor: any, i = 1.01, out: geom } } -export function getShapeMaterials (pxMtl: any) { +export function getShapeMaterials (pxMtl: any): any { if (USE_BYTEDANCE) { return [pxMtl]; } @@ -387,7 +387,7 @@ export function createConvexMesh (_buffer: Float32Array | number[], cooking: any // eTIGHT_BOUNDS = (1<<0) convex // eDOUBLE_SIDED = (1<<1) trimesh -export function createMeshGeometryFlags (flags: number, isConvex: boolean) { +export function createMeshGeometryFlags (flags: number, isConvex: boolean): any { if (USE_BYTEDANCE) { return flags; } @@ -468,7 +468,7 @@ export function createBV34TriangleMesh (vertices: number[], indices: Uint32Array return cooking.createTriangleMesh(meshDesc); } -export function createHeightField (terrain: any, heightScale: number, cooking: any, physics: any) { +export function createHeightField (terrain: any, heightScale: number, cooking: any, physics: any): any { const sizeI = terrain.getVertexCountI(); const sizeJ = terrain.getVertexCountJ(); if (USE_BYTEDANCE) { @@ -499,7 +499,7 @@ export function createHeightField (terrain: any, heightScale: number, cooking: a return cooking.createHeightFieldExt(sizeI, sizeJ, samples, physics); } -export function createHeightFieldGeometry (hf: any, flags: number, hs: number, xs: number, zs: number) { +export function createHeightFieldGeometry (hf: any, flags: number, hs: number, xs: number, zs: number): any { if (USE_BYTEDANCE) { return new PX.HeightFieldGeometry(hf, hs, xs, zs); } @@ -507,7 +507,7 @@ export function createHeightFieldGeometry (hf: any, flags: number, hs: number, x hs, xs, zs); } -export function simulateScene (scene: any, deltaTime: number) { +export function simulateScene (scene: any, deltaTime: number): void { if (USE_BYTEDANCE) { scene.simulate(deltaTime); } else { @@ -662,7 +662,7 @@ export function sweepClosest (world: PhysXWorld, worldRay: geometry.Ray, geometr return false; } -export function initializeWorld (world: any) { +export function initializeWorld (world: any): void { if (USE_BYTEDANCE) { // construct PhysX instance object only once if (!PhysXInstance.physics) { @@ -734,7 +734,7 @@ export function initializeWorld (world: any) { * ui32 internalFaceIndex1, * totoal = 48 */ -export function getContactPosition (pxContactOrOffset: any, out: IVec3Like, buf: any) { +export function getContactPosition (pxContactOrOffset: any, out: IVec3Like, buf: any): void { if (USE_BYTEDANCE) { Vec3.fromArray(out, new Float32Array(buf, pxContactOrOffset, 3)); } else { @@ -742,7 +742,7 @@ export function getContactPosition (pxContactOrOffset: any, out: IVec3Like, buf: } } -export function getContactNormal (pxContactOrOffset: any, out: IVec3Like, buf: any) { +export function getContactNormal (pxContactOrOffset: any, out: IVec3Like, buf: any): void { if (USE_BYTEDANCE) { Vec3.fromArray(out, new Float32Array(buf, (pxContactOrOffset as number) + 12, 3)); } else { @@ -750,7 +750,7 @@ export function getContactNormal (pxContactOrOffset: any, out: IVec3Like, buf: a } } -export function getContactDataOrByteOffset (index: number, offset: number) { +export function getContactDataOrByteOffset (index: number, offset: number): any { if (USE_BYTEDANCE) { return index * 40 + offset; } else { @@ -761,7 +761,7 @@ export function getContactDataOrByteOffset (index: number, offset: number) { } } -export function gatherEvents (world: PhysXWorld) { +export function gatherEvents (world: PhysXWorld): void { if (USE_BYTEDANCE) { // contact const contactBuf = world.scene.getContactData() as ArrayBuffer; @@ -833,7 +833,7 @@ export function gatherEvents (world: PhysXWorld) { } } -export function syncNoneStaticToSceneIfWaking (actor: any, node: Node) { +export function syncNoneStaticToSceneIfWaking (actor: any, node: Node): void { if (USE_BYTEDANCE) { const transform = actor.getGlobalPoseIfWaking(); if (!transform) return; @@ -851,7 +851,7 @@ interface IPhysicsConfigEXT extends IPhysicsConfig { physX: { epsilon: number, multiThread: boolean, subThreadCount: number, } } -function initConfigForByteDance () { +function initConfigForByteDance (): void { const physX = settings.querySettings(Settings.Category.PHYSICS, 'physX'); if (physX) { const { epsilon, multiThread, subThreadCount } = physX; @@ -862,9 +862,9 @@ function initConfigForByteDance () { } // hack for multi thread mode, should be refactor in future -function hackForMultiThread () { +function hackForMultiThread (): void { if (USE_BYTEDANCE && PX.MULTI_THREAD) { - PhysicsSystem.prototype.postUpdate = function postUpdate (deltaTime: number) { + PhysicsSystem.prototype.postUpdate = function postUpdate (deltaTime: number): void { const sys = this as any; if (!sys._enable) { sys.physicsWorld.syncSceneToPhysics(); @@ -882,7 +882,7 @@ function hackForMultiThread () { }; // eslint-disable-next-line no-inner-declarations - function lastUpdate (sys: any) { + function lastUpdate (sys: any): void { if (!sys._enable) return; if (sys._autoSimulation) { @@ -896,7 +896,7 @@ function hackForMultiThread () { } } - director.on(Director.EVENT_END_FRAME, () => { + director.on(Director.EVENT_END_FRAME, (): void => { if (!director.isPaused()) { lastUpdate(PhysicsSystem.instance); } diff --git a/cocos/physics/physx/physx-rigid-body.ts b/cocos/physics/physx/physx-rigid-body.ts index 8e78a30fd88..ccc9353763d 100644 --- a/cocos/physics/physx/physx-rigid-body.ts +++ b/cocos/physics/physx/physx-rigid-body.ts @@ -116,7 +116,7 @@ export class PhysXRigidBody implements IRigidBody { this._isUsingCCD = v; } - isUsingCCD () { return this._isUsingCCD; } + isUsingCCD (): boolean { return this._isUsingCCD; } setLinearFactor (v: IVec3Like): void { if (this.isStatic) return; diff --git a/cocos/physics/physx/physx-shared-body.ts b/cocos/physics/physx/physx-shared-body.ts index 97d32e4297c..cae1a5e9c44 100644 --- a/cocos/physics/physx/physx-shared-body.ts +++ b/cocos/physics/physx/physx-shared-body.ts @@ -75,8 +75,8 @@ export class PhysXSharedBody { get isKinematic (): boolean { return this._isKinematic; } get isDynamic (): boolean { return !this._isStatic && !this._isKinematic; } get wrappedBody (): PhysXRigidBody | null { return this._wrappedBody; } - get filterData () { return this._filterData; } - get isInScene () { return this._index !== -1; } + get filterData (): any { return this._filterData; } + get isInScene (): boolean { return this._index !== -1; } get impl (): any { this._initActor(); return this.isStatic ? this._staticActor : this._dynamicActor; @@ -145,14 +145,14 @@ export class PhysXSharedBody { if (st !== this._isStatic) { this._switchActor(st); } } - private _initStaticActor () { + private _initStaticActor (): void { if (this._staticActor) return; const t = getTempTransform(this.node.worldPosition, this.node.worldRotation); this._staticActor = PhysXInstance.physics.createRigidStatic(t); if (this._staticActor.$$) PX.IMPL_PTR[this._staticActor.$$.ptr] = this; } - private _initDynamicActor () { + private _initDynamicActor (): void { if (this._dynamicActor) return; const t = getTempTransform(this.node.worldPosition, this.node.worldRotation); this._dynamicActor = PhysXInstance.physics.createRigidDynamic(t); @@ -176,7 +176,7 @@ export class PhysXSharedBody { } } - private _switchActor (isStaticBefore: boolean) { + private _switchActor (isStaticBefore: boolean): void { if (!this._staticActor || !this._dynamicActor) return; const a0 = isStaticBefore ? this._staticActor : this._dynamicActor; const a1 = !isStaticBefore ? this._staticActor : this._dynamicActor; @@ -220,7 +220,7 @@ export class PhysXSharedBody { } } - addJoint (v: PhysXJoint, type: 0 | 1) { + addJoint (v: PhysXJoint, type: 0 | 1): void { if (type) { const i = this.wrappedJoints1.indexOf(v); if (i < 0) this.wrappedJoints1.push(v); @@ -230,7 +230,7 @@ export class PhysXSharedBody { } } - removeJoint (v: PhysXJoint, type: 0 | 1) { + removeJoint (v: PhysXJoint, type: 0 | 1): void { if (type) { const i = this.wrappedJoints1.indexOf(v); if (i >= 0) js.array.fastRemoveAt(this.wrappedJoints1, i); @@ -240,13 +240,13 @@ export class PhysXSharedBody { } } - setLinearDamping (linDamp: number) { + setLinearDamping (linDamp: number): void { if (!this._dynamicActor) return; const dt = PhysicsSystem.instance.fixedTimeStep; this._dynamicActor.setLinearDamping((1 - (1 - linDamp) ** dt) / dt); } - setAngularDamping (angDamp: number) { + setAngularDamping (angDamp: number): void { if (!this._dynamicActor) return; const dt = PhysicsSystem.instance.fixedTimeStep; this._dynamicActor.setAngularDamping((1 - (1 - angDamp) ** dt) / dt); @@ -316,7 +316,7 @@ export class PhysXSharedBody { syncNoneStaticToSceneIfWaking(this._dynamicActor, this.node); } - syncScale () { + syncScale (): void { for (let i = 0; i < this.wrappedShapes.length; i++) { this.wrappedShapes[i].updateScale(); } diff --git a/cocos/physics/physx/physx-world.ts b/cocos/physics/physx/physx-world.ts index 68b038b2496..fcf089f324e 100644 --- a/cocos/physics/physx/physx-world.ts +++ b/cocos/physics/physx/physx-world.ts @@ -93,14 +93,14 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { } } - private _simulate (dt: number) { + private _simulate (dt: number): void { if (!this._isNeedFetch) { simulateScene(this.scene, dt); this._isNeedFetch = true; } } - private _fetchResults () { + private _fetchResults (): void { if (this._isNeedFetch) { this.scene.fetchResults(true); this._isNeedFetch = false; @@ -353,7 +353,7 @@ const PhysXCallback = { } }, - emitTriggerEvent () { + emitTriggerEvent (): void { let len = triggerEventEndDic.getLength(); while (len--) { const key = triggerEventEndDic.getKeyByIndex(len); diff --git a/cocos/physics/physx/shapes/physx-shape.ts b/cocos/physics/physx/shapes/physx-shape.ts index 004f0ca38fe..79bf1521f5a 100644 --- a/cocos/physics/physx/shapes/physx-shape.ts +++ b/cocos/physics/physx/shapes/physx-shape.ts @@ -208,7 +208,7 @@ export class PhysXShape implements IBaseShape { this._sharedBody.removeMask(v); } - updateFilterData (filterData: any) { + updateFilterData (filterData: any): void { this._word3 = EFilterDataWord3.DETECT_CONTACT_CCD; if (this._collider.needTriggerEvent) { this._word3 |= EFilterDataWord3.DETECT_TRIGGER_EVENT; @@ -221,11 +221,11 @@ export class PhysXShape implements IBaseShape { this.setFilerData(filterData); } - updateEventListener () { + updateEventListener (): void { if (this._sharedBody) this.updateFilterData(this._sharedBody.filterData); } - updateByReAdd () { + updateByReAdd (): void { if (this._isEnabled) { this.removeFromBody(); this.addToBody(); @@ -233,18 +233,18 @@ export class PhysXShape implements IBaseShape { } // virtual - setFilerData (filterData: any) { + setFilerData (filterData: any): void { this._impl.setQueryFilterData(filterData); this._impl.setSimulationFilterData(filterData); } // virtual - addToBody () { + addToBody (): void { this._sharedBody.addShape(this); } // virtual - removeFromBody () { + removeFromBody (): void { this._sharedBody.removeShape(this); } } diff --git a/cocos/physics/physx/shapes/physx-sphere-shape.ts b/cocos/physics/physx/shapes/physx-sphere-shape.ts index d7e99de1164..8c492487436 100644 --- a/cocos/physics/physx/shapes/physx-sphere-shape.ts +++ b/cocos/physics/physx/shapes/physx-sphere-shape.ts @@ -43,23 +43,23 @@ export class PhysXSphereShape extends PhysXShape implements ISphereShape { this.updateScale(); } - get collider () { + get collider (): SphereCollider { return this._collider as SphereCollider; } - onComponentSet () { + onComponentSet (): void { this.updateGeometry(); const pxmat = this.getSharedMaterial(this.collider.sharedMaterial); this._impl = PhysXInstance.physics.createShape(PhysXSphereShape.SPHERE_GEOMETRY, pxmat, true, this._flags); } - updateScale () { + updateScale (): void { this.updateGeometry(); this._impl.setGeometry(PhysXSphereShape.SPHERE_GEOMETRY); this.setCenter(this._collider.center); } - updateGeometry () { + updateGeometry (): void { const co = this.collider; const maxSp = Math.abs(absMaxComponent(this.collider.node.worldScale)); PhysXSphereShape.SPHERE_GEOMETRY.setRadius(Math.max(0.0001, co.radius * maxSp)); diff --git a/cocos/physics/physx/shapes/physx-terrain-shape.ts b/cocos/physics/physx/shapes/physx-terrain-shape.ts index f25ee0a81d7..e662b7d93a8 100644 --- a/cocos/physics/physx/shapes/physx-terrain-shape.ts +++ b/cocos/physics/physx/shapes/physx-terrain-shape.ts @@ -53,15 +53,15 @@ export class PhysXTerrainShape extends PhysXShape implements ITerrainShape { } } - get collider () { + get collider (): TerrainCollider { return this._collider as TerrainCollider; } - onComponentSet () { + onComponentSet (): void { this.setTerrain(this.collider.terrain); } - updateScale () { + updateScale (): void { this.setCenter(this._collider.center); } @@ -71,23 +71,23 @@ export class PhysXTerrainShape extends PhysXShape implements ITerrainShape { if (this._impl) this._impl.setLocalPose(getTempTransform(v, this._rotation)); } - setMaterial (v: PhysicsMaterial | null) { + setMaterial (v: PhysicsMaterial | null): void { if (this._impl) super.setMaterial(v); } - setAsTrigger (v: boolean) { + setAsTrigger (v: boolean): void { if (this._impl) super.setAsTrigger(v); } - setFilerData (v: any) { + setFilerData (v: any): void { if (this._impl) super.setFilerData(v); } - addToBody () { + addToBody (): void { if (this._impl) super.addToBody(); } - removeFromBody () { + removeFromBody (): void { if (this._impl) super.removeFromBody(); } } diff --git a/cocos/physics/physx/shapes/physx-trimesh-shape.ts b/cocos/physics/physx/shapes/physx-trimesh-shape.ts index d4437a9060e..77841f09846 100644 --- a/cocos/physics/physx/shapes/physx-trimesh-shape.ts +++ b/cocos/physics/physx/shapes/physx-trimesh-shape.ts @@ -99,27 +99,27 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape { /* override */ - setMaterial (v: PhysicsMaterial | null) { + setMaterial (v: PhysicsMaterial | null): void { if (this._impl) super.setMaterial(v); } - setCenter (v: IVec3Like) { + setCenter (v: IVec3Like): void { if (this._impl) super.setCenter(v); } - setAsTrigger (v: boolean) { + setAsTrigger (v: boolean): void { if (this._impl) super.setAsTrigger(v); } - setFilerData (v: any) { + setFilerData (v: any): void { if (this._impl) super.setFilerData(v); } - addToBody () { + addToBody (): void { if (this._impl) super.addToBody(); } - removeFromBody () { + removeFromBody (): void { if (this._impl) super.removeFromBody(); } } diff --git a/cocos/physics/utils/array-collision-matrix.ts b/cocos/physics/utils/array-collision-matrix.ts index 9123f67aaec..d77cc89f02a 100644 --- a/cocos/physics/utils/array-collision-matrix.ts +++ b/cocos/physics/utils/array-collision-matrix.ts @@ -56,7 +56,7 @@ export class ArrayCollisionMatrix { * @param {Number} j * @param {boolean} value */ - public set (i: number, j: number, value: boolean) { + public set (i: number, j: number, value: boolean): void { if (j > i) { const temp = j; j = i; @@ -69,7 +69,7 @@ export class ArrayCollisionMatrix { * Sets all elements to zero * @method reset */ - public reset () { + public reset (): void { this.matrix.length = 0; } @@ -77,7 +77,7 @@ export class ArrayCollisionMatrix { * Sets the max number of objects * @param {Number} n */ - public setNumObjects (n: number) { + public setNumObjects (n: number): void { this.matrix.length = n * (n - 1) >> 1; } } diff --git a/cocos/physics/utils/tuple-dictionary.ts b/cocos/physics/utils/tuple-dictionary.ts index d308a8fb7bb..72a9ba0e5f3 100644 --- a/cocos/physics/utils/tuple-dictionary.ts +++ b/cocos/physics/utils/tuple-dictionary.ts @@ -87,14 +87,14 @@ export class TupleDictionary { /** * @method reset */ - public reset () { + public reset (): void { this.data = { keys: [] }; } /** * @method getLength */ - public getLength () { + public getLength (): number { return this.data.keys.length; } @@ -102,7 +102,7 @@ export class TupleDictionary { * @method getKeyByIndex * @param {number} index */ - public getKeyByIndex (index: number) { + public getKeyByIndex (index: number): string { return this.data.keys[index]; } diff --git a/cocos/physics/utils/util.ts b/cocos/physics/utils/util.ts index bda38e84363..ad8e0135a9a 100644 --- a/cocos/physics/utils/util.ts +++ b/cocos/physics/utils/util.ts @@ -31,15 +31,15 @@ interface IWrapped { __cc_wrapper__: T; } -export function setWrap (object: any, wrapper: Wrapper) { +export function setWrap (object: any, wrapper: Wrapper): void { (object as IWrapped).__cc_wrapper__ = wrapper; } -export function getWrap (object: any) { +export function getWrap (object: any): Wrapper { return (object as IWrapped).__cc_wrapper__; } -export function maxComponent (v: IVec3Like) { +export function maxComponent (v: IVec3Like): number { return Math.max(v.x, Math.max(v.y, v.z)); } @@ -86,7 +86,7 @@ export function shrinkPositions (buffer: Float32Array | number[]): number[] { return pos; } -export function absolute (v: Vec3) { +export function absolute (v: Vec3): Vec3 { v.x = Math.abs(v.x); v.y = Math.abs(v.y); v.z = Math.abs(v.z); diff --git a/cocos/primitive/box.ts b/cocos/primitive/box.ts index 4cdf7668e0c..59688467b0b 100644 --- a/cocos/primitive/box.ts +++ b/cocos/primitive/box.ts @@ -146,7 +146,7 @@ export default function box (options?: IBoxOptions): IGeometry { const maxPos = new Vec3(hw, hh, hl); const boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl); - function _buildPlane (side: number, uSegments: number, vSegments: number) { + function _buildPlane (side: number, uSegments: number, vSegments: number): void { let u: number; let v: number; let ix: number; diff --git a/cocos/primitive/capsule.ts b/cocos/primitive/capsule.ts index 0f04ab78be8..33fb65a0963 100644 --- a/cocos/primitive/capsule.ts +++ b/cocos/primitive/capsule.ts @@ -49,7 +49,7 @@ const temp2 = new Vec3(0, 0, 0); * @param radiusBottom @zh 底部半径。@en The radius of bottom sphere * @param opts @zh 胶囊体参数选项。@en The optional creation parameters of the capsule */ -export default function capsule (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts: RecursivePartial = {}) { +export default function capsule (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts: RecursivePartial = {}): { positions: number[]; normals: number[]; uvs: number[]; indices: number[]; minPos: Vec3; maxPos: Vec3; boundingRadius: number; } { const torsoHeight = height - radiusTop - radiusBottom; const sides = opts.sides || 32; const heightSegments = opts.heightSegments || 32; @@ -98,7 +98,7 @@ export default function capsule (radiusTop = 0.5, radiusBottom = 0.5, height = 2 // internal fucntions // ======================= - function generateTorso () { + function generateTorso (): void { // this will be used to calculate the normal const slope = (radiusTop - radiusBottom) / torsoHeight; @@ -162,7 +162,7 @@ export default function capsule (radiusTop = 0.5, radiusBottom = 0.5, height = 2 } } - function generateBottom () { + function generateBottom (): void { for (let lat = 0; lat <= bottomSegments; ++lat) { const theta = lat * Math.PI / bottomSegments / 2; const sinTheta = Math.sin(theta); @@ -199,7 +199,7 @@ export default function capsule (radiusTop = 0.5, radiusBottom = 0.5, height = 2 } } - function generateTop () { + function generateTop (): void { for (let lat = 0; lat <= topSegments; ++lat) { const theta = lat * Math.PI / topSegments / 2 + Math.PI / 2; const sinTheta = Math.sin(theta); diff --git a/cocos/primitive/cylinder.ts b/cocos/primitive/cylinder.ts index ae9a6fffe7c..57fadfc4fff 100644 --- a/cocos/primitive/cylinder.ts +++ b/cocos/primitive/cylinder.ts @@ -120,7 +120,7 @@ export default function cylinder (radiusTop = 0.5, radiusBottom = 0.5, height = // internal fucntions // ======================= - function generateTorso () { + function generateTorso (): void { const indexArray: number[][] = []; // this will be used to calculate the normal @@ -190,7 +190,7 @@ export default function cylinder (radiusTop = 0.5, radiusBottom = 0.5, height = } } - function generateCap (top) { + function generateCap (top): void { const radius = top ? radiusTop : radiusBottom; const sign = top ? 1 : -1; diff --git a/cocos/primitive/primitive.ts b/cocos/primitive/primitive.ts index 0fd0ac9f49f..9455de24558 100644 --- a/cocos/primitive/primitive.ts +++ b/cocos/primitive/primitive.ts @@ -80,7 +80,7 @@ export class Primitive extends Mesh { * @zh * 根据`type`和`info`构建相应的网格。 */ - public onLoaded () { + public onLoaded (): void { createMesh(primitives[PrimitiveType[this.type].toLowerCase()](this.info), this); } } diff --git a/cocos/primitive/torus.ts b/cocos/primitive/torus.ts index b3628fe80a7..45f9e939bc0 100644 --- a/cocos/primitive/torus.ts +++ b/cocos/primitive/torus.ts @@ -46,7 +46,7 @@ interface ITorusOptions extends IGeometryOptions { * @param tube @zh 管形大小。@en The radius of tube * @param opts @zh 参数选项。@en The optional creation parameters of the torus */ -export default function torus (radius = 0.4, tube = 0.1, opts: RecursivePartial = {}) { +export default function torus (radius = 0.4, tube = 0.1, opts: RecursivePartial = {}): { positions: number[]; normals: number[]; uvs: number[]; indices: number[]; minPos: Vec3; maxPos: Vec3; boundingRadius: number; } { const radialSegments = opts.radialSegments || 32; const tubularSegments = opts.tubularSegments || 32; const arc = opts.arc || 2.0 * Math.PI; diff --git a/cocos/primitive/transform.ts b/cocos/primitive/transform.ts index 17ff15e8fa4..9930b196670 100644 --- a/cocos/primitive/transform.ts +++ b/cocos/primitive/transform.ts @@ -33,7 +33,7 @@ import { IGeometry } from './define'; * @param geometry @zh 几何体信息。@en The geometry to be translated * @param offset @zh 偏移量。@en The translation */ -export function translate (geometry: IGeometry, offset: { x?: number; y?: number; z?: number; }) { +export function translate (geometry: IGeometry, offset: { x?: number; y?: number; z?: number; }): IGeometry { const x = offset.x || 0; const y = offset.y || 0; const z = offset.z || 0; @@ -67,7 +67,7 @@ export function translate (geometry: IGeometry, offset: { x?: number; y?: number * @param geometry @zh 几何体信息。 @en The geometry to be scaled * @param value @zh 缩放量。@en The scaling size */ -export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: number }) { +export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: number }): IGeometry { const x = value.x ?? 1.0; const y = value.y ?? 1.0; const z = value.z ?? 1.0; @@ -119,7 +119,7 @@ export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: * 将几何体转换为线框模式,仅支持三角形拓扑的几何体。 * @param geometry @zh 几何体信息。@en The geometry to be converted to wireframe */ -export function wireframed (geometry: IGeometry) { +export function wireframed (geometry: IGeometry): IGeometry { const { indices } = geometry; if (!indices) { return geometry; diff --git a/cocos/primitive/utils.ts b/cocos/primitive/utils.ts index 181e6e069fc..9814dc3699a 100644 --- a/cocos/primitive/utils.ts +++ b/cocos/primitive/utils.ts @@ -28,7 +28,7 @@ import { IGeometry } from './define'; /** * @deprecated */ -export function wireframe (indices: number[]) { +export function wireframe (indices: number[]): number[] { const offsets = [[0, 1], [1, 2], [2, 0]]; const lines: number[] = []; const lineIDs = {}; @@ -53,7 +53,7 @@ export function wireframe (indices: number[]) { /** * @deprecated */ -export function invWinding (indices: number[]) { +export function invWinding (indices: number[]): number[] { const newIB: number[] = []; for (let i = 0; i < indices.length; i += 3) { newIB.push(indices[i], indices[i + 2], indices[i + 1]); @@ -64,7 +64,7 @@ export function invWinding (indices: number[]) { /** * @deprecated */ -export function toWavefrontOBJ (primitive: IGeometry, scale = 1) { +export function toWavefrontOBJ (primitive: IGeometry, scale = 1): string { if (!primitive.indices || !primitive.uvs || !primitive.normals @@ -75,7 +75,7 @@ export function toWavefrontOBJ (primitive: IGeometry, scale = 1) { const t = primitive.uvs; const n = primitive.normals; const IB = primitive.indices; - const V = (i) => `${IB[i] + 1}/${IB[i] + 1}/${IB[i] + 1}`; + const V = (i): string => `${IB[i] + 1}/${IB[i] + 1}/${IB[i] + 1}`; let content = ''; for (let i = 0; i < v.length; i += 3) { content += `v ${v[i] * scale} ${v[i + 1] * scale} ${v[i + 2] * scale}\n`; @@ -95,7 +95,7 @@ export function toWavefrontOBJ (primitive: IGeometry, scale = 1) { /** * @deprecated */ -export function normals (positions: number[], nms: number[], length = 1) { +export function normals (positions: number[], nms: number[], length = 1): number[] { const verts: number[] = new Array(2 * positions.length); for (let i = 0; i < positions.length / 3; ++i) { diff --git a/cocos/profiler/counter.ts b/cocos/profiler/counter.ts index 461f44992dc..56f7156749b 100644 --- a/cocos/profiler/counter.ts +++ b/cocos/profiler/counter.ts @@ -35,7 +35,7 @@ export interface ICounterOption { } export class Counter { - get value () { + get value (): number { return this._value; } @@ -58,24 +58,24 @@ export class Counter { this._accumStart = now; } - public sample (now: number) { + public sample (now: number): void { this._average(this._value, now); } - public human () { + public human (): number { const { average, isInteger } = this._opts; const v = average ? this._averageValue : this._value; return isInteger ? Math.round(v) : Math.round(v * 100) / 100; } - public alarm () { + public alarm (): boolean | number | undefined { return ( (this._opts.below && this._value < this._opts.below) || (this._opts.over && this._value > this._opts.over) ); } - protected _average (v: number, now = 0) { + protected _average (v: number, now = 0): void { if (this._opts.average) { this._accumValue += v; ++this._accumSamples; diff --git a/cocos/profiler/perf-counter.ts b/cocos/profiler/perf-counter.ts index d6597d21406..1e791251e26 100644 --- a/cocos/profiler/perf-counter.ts +++ b/cocos/profiler/perf-counter.ts @@ -32,14 +32,14 @@ export class PerfCounter extends Counter { super(id, opts, now); this._time = now; } - public start (now = 0) { + public start (now = 0): void { this._time = now; // DISABLE: long time running will cause performance drop down // window.performance.mark(this._idstart); } - public end (now = 0) { + public end (now = 0): void { this._value = now - this._time; // DISABLE: long time running will cause performance drop down @@ -49,12 +49,12 @@ export class PerfCounter extends Counter { this._average(this._value); } - public tick () { + public tick (): void { this.end(); this.start(); } - public frame (now: number) { + public frame (now: number): void { const t = now; const e = t - this._time; this._total++; diff --git a/cocos/profiler/profiler.ts b/cocos/profiler/profiler.ts index 6f17acfd1e1..c22b6896851 100644 --- a/cocos/profiler/profiler.ts +++ b/cocos/profiler/profiler.ts @@ -135,7 +135,7 @@ export class Profiler extends System { } } - init () { + init (): void { const showFPS = !!settings.querySettings(Settings.Category.PROFILING, 'showFPS'); if (showFPS) { this.showStats(); @@ -144,11 +144,11 @@ export class Profiler extends System { } } - public isShowingStats () { + public isShowingStats (): boolean { return this._showFPS; } - public hideStats () { + public hideStats (): void { if (this._showFPS) { if (this._rootNode) { this._rootNode.active = false; @@ -167,7 +167,7 @@ export class Profiler extends System { } } - public showStats () { + public showStats (): void { if (!this._showFPS) { if (!this._device) { const root = cclegacy.director.root as Root; @@ -199,7 +199,7 @@ export class Profiler extends System { } } - public generateCanvas () { + public generateCanvas (): void { if (this._canvasDone) { return; } @@ -231,7 +231,7 @@ export class Profiler extends System { this._region.texExtent.height = textureHeight; } - public generateStats () { + public generateStats (): void { if (this._statsDone || !this._ctx || !this._canvas) { return; } @@ -263,7 +263,7 @@ export class Profiler extends System { this._device!.copyTexImagesToTexture(this._canvasArr, this._texture!, this._regionArr); } - public generateNode () { + public generateNode (): void { if (this._rootNode && this._rootNode.isValid) { return; } @@ -340,7 +340,7 @@ export class Profiler extends System { this._inited = true; } - public beforeUpdate () { + public beforeUpdate (): void { if (!this._stats) { return; } @@ -350,7 +350,7 @@ export class Profiler extends System { (this._stats.logic.counter as PerfCounter).start(now); } - public afterUpdate () { + public afterUpdate (): void { if (!this._stats) { return; } @@ -363,7 +363,7 @@ export class Profiler extends System { } } - public beforePhysics () { + public beforePhysics (): void { if (!this._stats) { return; } @@ -372,7 +372,7 @@ export class Profiler extends System { (this._stats.physics.counter as PerfCounter).start(now); } - public afterPhysics () { + public afterPhysics (): void { if (!this._stats) { return; } @@ -381,7 +381,7 @@ export class Profiler extends System { (this._stats.physics.counter as PerfCounter).end(now); } - public beforeDraw () { + public beforeDraw (): void { if (!this._stats || !this._inited) { return; } @@ -412,7 +412,7 @@ export class Profiler extends System { (this._stats.render.counter as PerfCounter).start(now); } - public afterRender () { + public afterRender (): void { if (!this._stats || !this._inited) { return; } @@ -421,7 +421,7 @@ export class Profiler extends System { (this._stats.present.counter as PerfCounter).start(now); } - public afterPresent () { + public afterPresent (): void { if (!this._stats || !this._inited) { return; } diff --git a/cocos/render-scene/config.ts b/cocos/render-scene/config.ts index 0ea358ca99a..e219c44defb 100644 --- a/cocos/render-scene/config.ts +++ b/cocos/render-scene/config.ts @@ -26,7 +26,7 @@ let _stageOffset = 0; const _name2stageID = {}; export default { - addStage (name) { + addStage (name): void { // already added if (_name2stageID[name] !== undefined) { return; @@ -38,7 +38,7 @@ export default { _stageOffset += 1; }, - stageID (name) { + stageID (name): any { const id = _name2stageID[name]; if (id === undefined) { return -1; @@ -46,7 +46,7 @@ export default { return id; }, - stageIDs (nameList) { + stageIDs (nameList): number { let key = 0; for (const name of nameList) { const id = _name2stageID[name]; diff --git a/cocos/render-scene/core/material-instance.ts b/cocos/render-scene/core/material-instance.ts index 45057eeeb06..36e48acb64c 100644 --- a/cocos/render-scene/core/material-instance.ts +++ b/cocos/render-scene/core/material-instance.ts @@ -39,11 +39,11 @@ export interface IMaterialInstanceInfo { * 材质实例,当有材质修改需求时,根据材质资源创建的,可任意定制的实例。 */ export class MaterialInstance extends Material { - get parent () { + get parent (): Material { return this._parent; } - get owner () { + get owner (): Renderer | null { return this._owner; } @@ -89,19 +89,19 @@ export class MaterialInstance extends Material { } } - public destroy () { + public destroy (): boolean { this._doDestroy(); return true; } - public onPassStateChange (dontNotify: boolean) { + public onPassStateChange (dontNotify: boolean): void { this._hash = Material.getHash(this); if (!dontNotify && this._owner) { this._owner._onRebuildPSO(this._subModelIdx, this); } } - protected _createPasses () { + protected _createPasses (): PassInstance[] { const passes: PassInstance[] = []; const parentPasses = this._parent.passes; if (!parentPasses) { return passes; } diff --git a/cocos/render-scene/core/memory-pools.ts b/cocos/render-scene/core/memory-pools.ts index 74f15db6cb2..c4c17024b13 100644 --- a/cocos/render-scene/core/memory-pools.ts +++ b/cocos/render-scene/core/memory-pools.ts @@ -25,7 +25,7 @@ import { DEBUG } from 'internal:constants'; import { NativeBufferPool } from './native-pools'; -const contains = (a: number[], t: number) => { +const contains = (a: number[], t: number): boolean => { for (let i = 0; i < a.length; ++i) { if (a[i] === t) return true; } @@ -166,7 +166,7 @@ class BufferPool

implements IMemor return view.subarray(index, index + count); } - public free (handle: IHandle

) { + public free (handle: IHandle

): void { const chunk = (this._chunkMask & handle as unknown as number) >> this._entryBits; const entry = this._entryMask & handle as unknown as number; if (DEBUG && (!handle || chunk < 0 || chunk >= this._freeLists.length diff --git a/cocos/render-scene/core/native-pools.ts b/cocos/render-scene/core/native-pools.ts index 3d3b9de1b7d..2b5a9656b9d 100644 --- a/cocos/render-scene/core/native-pools.ts +++ b/cocos/render-scene/core/native-pools.ts @@ -28,16 +28,16 @@ export class NativeBufferPool { constructor (dataType: number, entryBits: number, stride: number) { this._chunkSize = stride * (1 << entryBits); } - public allocateNewChunk () { return new ArrayBuffer(this._chunkSize); } + public allocateNewChunk (): ArrayBuffer { return new ArrayBuffer(this._chunkSize); } } export class NativeObjectPool { constructor (dataType: number, array: T[]) {} - public bind (index: number, obj: T) {} + public bind (index: number, obj: T): void {} } export class NativeBufferAllocator { constructor (poolType: number) {} - public alloc (index: number, bytes: number) { return new ArrayBuffer(bytes); } - public free (index: number) {} + public alloc (index: number, bytes: number): ArrayBuffer { return new ArrayBuffer(bytes); } + public free (index: number): void {} } diff --git a/cocos/render-scene/core/pass-instance.ts b/cocos/render-scene/core/pass-instance.ts index d353e27f29e..580f8af414f 100644 --- a/cocos/render-scene/core/pass-instance.ts +++ b/cocos/render-scene/core/pass-instance.ts @@ -36,7 +36,7 @@ export class PassInstance extends Pass { * @en The parent pass * @zh 相关联的原始 Pass */ - get parent () { return this._parent; } + get parent (): Pass { return this._parent; } private _parent: Pass; @@ -86,7 +86,7 @@ export class PassInstance extends Pass { this._onStateChange(); } - public tryCompile (defineOverrides?: MacroRecord) { + public tryCompile (defineOverrides?: MacroRecord): boolean { if (defineOverrides) { if (!overrideMacros(this._defines, defineOverrides)) { return false; @@ -101,7 +101,7 @@ export class PassInstance extends Pass { * @en Prepare to change states of the pass and do not notify the material to rebuild the pipeline state object * @zh 开始静默修改 Pass 相关状态,不会通知材质去重新构建管线状态对象。 */ - public beginChangeStatesSilently () { + public beginChangeStatesSilently (): void { this._dontNotify = true; } @@ -109,16 +109,16 @@ export class PassInstance extends Pass { * @en End the silent states changing process, all state changes will be notified. * @zh 结束静默状态修改,所有修改将会开始通知材质。 */ - public endChangeStatesSilently () { + public endChangeStatesSilently (): void { this._dontNotify = false; } - protected _syncBatchingScheme () { + protected _syncBatchingScheme (): void { this._defines.USE_INSTANCING = false; this._batchingScheme = BatchingSchemes.NONE; } - protected _onStateChange () { + protected _onStateChange (): void { this._hash = Pass.getPassHash(this); this._owner.onPassStateChange(this._dontNotify); } diff --git a/cocos/render-scene/core/pass.ts b/cocos/render-scene/core/pass.ts index 475454605a3..2f598c3063f 100644 --- a/cocos/render-scene/core/pass.ts +++ b/cocos/render-scene/core/pass.ts @@ -129,7 +129,7 @@ export class Pass { const bsInfo = info.blendState; const { targets } = bsInfo; if (targets) { - targets.forEach((t, i) => { + targets.forEach((t, i): void => { bs.setTarget(i, t as BlendTarget); }); } @@ -367,7 +367,7 @@ export class Pass { this._descriptorSet.update(); } - public getInstancedBuffer (extraKey = 0) { + public getInstancedBuffer (extraKey = 0): InstancedBuffer { return this._instancedBuffers[extraKey] || (this._instancedBuffers[extraKey] = new InstancedBuffer(this)); } @@ -655,7 +655,7 @@ export class Pass { Object.assign(directHandleMap, indirectHandleMap); } - private _buildUniformBlocks (device: Device, blocks: EffectAsset.IBlockInfo[], blockSizes: number[]) { + private _buildUniformBlocks (device: Device, blocks: EffectAsset.IBlockInfo[], blockSizes: number[]): void { const alignment = device.capabilities.uboOffsetAlignment; const startOffsets: number[] = []; let lastSize = 0; let lastOffset = 0; @@ -690,7 +690,7 @@ export class Pass { } } - private _buildMaterialUniformBlocks (device: Device, blocks: UniformBlock[], blockSizes: number[]) { + private _buildMaterialUniformBlocks (device: Device, blocks: UniformBlock[], blockSizes: number[]): void { const alignment = device.capabilities.uboOffsetAlignment; const startOffsets: number[] = []; let lastSize = 0; let lastOffset = 0; @@ -748,7 +748,7 @@ export class Pass { } } - private _getBlockView (type: Type, binding: number) { + private _getBlockView (type: Type, binding: number): Int32Array | Float32Array { return type < Type.FLOAT ? this._blocksInt[binding] : this._blocks[binding]; } @@ -756,7 +756,7 @@ export class Pass { * @engineInternal * Only for UI */ - public _initPassFromTarget (target: Pass, dss: DepthStencilState, hashFactor: number) { + public _initPassFromTarget (target: Pass, dss: DepthStencilState, hashFactor: number): void { this._priority = target.priority; this._stage = target.stage; this._phase = target.phase; @@ -795,7 +795,7 @@ export class Pass { /** * @engineInternal */ - public _updatePassHash () { + public _updatePassHash (): void { this._hash = Pass.getPassHash(this); } @@ -825,14 +825,14 @@ export class Pass { * @engineInternal * Currently, can not just mark setter as engine internal, so change to a function. */ - setRootBufferDirty (val: boolean) { this._rootBufferDirty = val; } + setRootBufferDirty (val: boolean): void { this._rootBufferDirty = val; } // states get priority (): RenderPriority { return this._priority; } /** * @engineInternal * Currently, can not just mark setter as engine internal, so change to a function. */ - setPriority (val: RenderPriority) { this._priority = val; } + setPriority (val: RenderPriority): void { this._priority = val; } get primitive (): PrimitiveMode { return this._primitive; } get stage (): RenderPassStage { return this._stage; } get phase (): number { return this._phase; } diff --git a/cocos/render-scene/core/program-lib.jsb.ts b/cocos/render-scene/core/program-lib.jsb.ts index 60d1652df23..a909e2a9d96 100644 --- a/cocos/render-scene/core/program-lib.jsb.ts +++ b/cocos/render-scene/core/program-lib.jsb.ts @@ -48,7 +48,7 @@ export interface IProgramInfo extends EffectAsset.IShaderInfo { uber: boolean; // macro number exceeds default limits, will fallback to string hash } -export function getDeviceShaderVersion (device) { +export function getDeviceShaderVersion (device): string { switch (device.gfxAPI) { case API.GLES2: case API.WEBGL: return 'glsl1'; diff --git a/cocos/render-scene/core/program-lib.ts b/cocos/render-scene/core/program-lib.ts index 96ad1457505..9c8095ca7d3 100644 --- a/cocos/render-scene/core/program-lib.ts +++ b/cocos/render-scene/core/program-lib.ts @@ -66,13 +66,13 @@ export interface IProgramInfo extends EffectAsset.IShaderInfo { function insertBuiltinBindings ( tmpl: IProgramInfo, tmplInfo: ITemplateInfo, source: IDescriptorSetLayoutInfo, type: 'locals' | 'globals', outBindings?: DescriptorSetLayoutBinding[], -) { +): void { const target = tmpl.builtins[type]; const tempBlocks: UniformBlock[] = []; for (let i = 0; i < target.blocks.length; i++) { const b = target.blocks[i]; const info = source.layouts[b.name] as UniformBlock | undefined; - const binding = info && source.bindings.find((bd) => bd.binding === info.binding); + const binding = info && source.bindings.find((bd): boolean => bd.binding === info.binding); if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_BUFFER_TYPE)) { console.warn(`builtin UBO '${b.name}' not available!`); continue; @@ -85,7 +85,7 @@ function insertBuiltinBindings ( for (let i = 0; i < target.samplerTextures.length; i++) { const s = target.samplerTextures[i]; const info = source.layouts[s.name] as UniformSamplerTexture; - const binding = info && source.bindings.find((bd) => bd.binding === info.binding); + const binding = info && source.bindings.find((bd): boolean => bd.binding === info.binding); if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_SAMPLER_TYPE)) { console.warn(`builtin samplerTexture '${s.name}' not available!`); continue; @@ -94,11 +94,11 @@ function insertBuiltinBindings ( if (outBindings && !outBindings.includes(binding)) outBindings.push(binding); } Array.prototype.unshift.apply(tmplInfo.shaderInfo.samplerTextures, tempSamplerTextures); - if (outBindings) outBindings.sort((a, b) => a.binding - b.binding); + if (outBindings) outBindings.sort((a, b): number => a.binding - b.binding); } // find those location which won't be affected by defines, and replace by ascending order of existing slot if location > 15 -function findDefineIndependent (source: string, tmpl: IProgramInfo, attrMap: Map, locSet: Set) { +function findDefineIndependent (source: string, tmpl: IProgramInfo, attrMap: Map, locSet: Set): string { const locExistingRegStr = `layout\\(location = (\\d+)\\)\\s+in.*?\\s(\\w+)[;,\\)]`; const locExistingReg = new RegExp(locExistingRegStr, 'g'); let locExistingRes = locExistingReg.exec(source); @@ -108,9 +108,9 @@ function findDefineIndependent (source: string, tmpl: IProgramInfo, attrMap: Map // v_normal while (locExistingRes) { const attrName = locExistingRes[2]; - const attrInfo = tmpl.attributes.find((ele) => ele.name === attrName); + const attrInfo = tmpl.attributes.find((ele): boolean => ele.name === attrName); // no define required. - const preExisted = attrInfo?.defines.length === 0 || attrInfo?.defines.every((ele) => ele === ''); + const preExisted = attrInfo?.defines.length === 0 || attrInfo?.defines.every((ele): boolean => ele === ''); if (preExisted) { let loc = parseInt(locExistingRes[1]); if (loc > 15) { @@ -140,7 +140,7 @@ function replaceVertexMutableLocation ( inOrOut: string, attrMap: Map, locSet: Set = new Set(), -) { +): string { const locHolderRegStr = `layout\\(location = ([^\\)]+)\\)\\s+${inOrOut}.*?\\s(\\w+)[;,\\)]`; const locHolderReg = new RegExp(locHolderRegStr, 'g'); @@ -152,7 +152,7 @@ function replaceVertexMutableLocation ( while (locHolder) { const attrName = locHolder[2]; if (!attrMap.has(attrName)) { - const attrInfo = tmpl.attributes.find((ele) => ele.name === attrName); + const attrInfo = tmpl.attributes.find((ele): boolean => ele.name === attrName); let active = true; let location = 0; // only vertexshader input is checked @@ -162,10 +162,10 @@ function replaceVertexMutableLocation ( // macroInfo stores value of defines // '!CC_USE_XXX' starts with a '!' is inverse condition. // all defines satisfied? - active = !!attrInfo?.defines.every((defStrIn) => { + active = !!attrInfo?.defines.every((defStrIn): boolean => { const inverseCond = defStrIn.startsWith('!'); const defStr = inverseCond ? defStrIn.slice(1) : defStrIn; - const v = macroInfo.find((ele) => ele.name === defStr); + const v = macroInfo.find((ele): boolean => ele.name === defStr); let res = !!v; if (v) { res = !(v.value === '0' || v.value === 'false' || v.value === 'FALSE'); @@ -181,9 +181,9 @@ function replaceVertexMutableLocation ( const evalStr = lastIfRes[1]; const evalORElements = evalStr.split('||'); // simple grammar, no parenthesses support yet. - const evalRes = evalORElements.some((eleOrTestStr) => { + const evalRes = evalORElements.some((eleOrTestStr): boolean => { const evalANDElements = eleOrTestStr.split('&&'); - return evalANDElements.every((eleAndTestStr) => { + return evalANDElements.every((eleAndTestStr): boolean => { let evalEleRes = true; if (eleAndTestStr.includes('==')) { const opVars = eleAndTestStr.split('=='); @@ -235,7 +235,7 @@ function replaceFragmentLocation ( source: string, inOrOut: string, attrMap: Map, -) { +): string { let code = source; const locHolderRegStr = `layout\\(location = ([^\\)]+)\\)\\s+${inOrOut}.*?\\s(\\w+)[;,\\)]`; const locHolderReg = new RegExp(locHolderRegStr, 'g'); @@ -269,7 +269,7 @@ export function flattenShaderLocation ( macroInfo: IMacroInfo[], shaderStage, attrMap: Map, -) { +): string { let code = source; if (shaderStage === 'vert') { const locSet = new Set(); @@ -290,7 +290,7 @@ function processShaderInfo ( tmpl: IProgramInfo, macroInfo: IMacroInfo[], shaderInfo, -) { +): void { // during configuring vertex state when make a pipelinestate // webgpu request max location of vertex attribute should not be greater than 15 // shader source comes from offline effect-compiler can't have sense what macro is activate @@ -320,7 +320,7 @@ export class ProgramLib { protected _cache: Record = {}; protected _templateInfos: Record = {}; - public register (effect: EffectAsset) { + public register (effect: EffectAsset): void { for (let i = 0; i < effect.shaders.length; i++) { const tmpl = this.define(effect.shaders[i]); tmpl.effectName = effect.name; @@ -341,7 +341,7 @@ export class ProgramLib { * @en Register the shader template with the given info * @zh 注册 shader 模板。 */ - public define (shader: EffectAsset.IShaderInfo) { + public define (shader: EffectAsset.IShaderInfo): IProgramInfo { const curTmpl = this._templates[shader.name]; if (curTmpl && curTmpl.hash === shader.hash) { return curTmpl; } const tmpl = ({ ...shader }) as IProgramInfo; @@ -363,7 +363,7 @@ export class ProgramLib { tmplInfo.bindings.push(new DescriptorSetLayoutBinding(block.binding, DescriptorType.UNIFORM_BUFFER, 1, block.stageFlags)); tmplInfo.shaderInfo.blocks.push(new UniformBlock(SetIndex.MATERIAL, block.binding, block.name, - block.members.map((m) => new Uniform(m.name, m.type, m.count)), 1)); // effect compiler guarantees block count = 1 + block.members.map((m): Uniform => new Uniform(m.name, m.type, m.count)), 1)); // effect compiler guarantees block count = 1 } for (let i = 0; i < tmpl.samplerTextures.length; i++) { const samplerTexture = tmpl.samplerTextures[i]; @@ -436,7 +436,7 @@ export class ProgramLib { * @zh 通过名字获取 Shader 模板 * @param name Target shader name */ - public getTemplate (name: string) { + public getTemplate (name: string): IProgramInfo { return this._templates[name]; } @@ -445,7 +445,7 @@ export class ProgramLib { * @zh 通过名字获取 Shader 模版信息 * @param name Target shader name */ - public getTemplateInfo (name: string) { + public getTemplateInfo (name: string): ITemplateInfo { const hash = this._templates[name].hash; return this._templateInfos[hash]; } @@ -455,7 +455,7 @@ export class ProgramLib { * @zh 通过名字获取 Shader 模板相关联的管线布局 * @param name Target shader name */ - public getDescriptorSetLayout (device: Device, name: string, isLocal = false) { + public getDescriptorSetLayout (device: Device, name: string, isLocal = false): DescriptorSetLayout { const tmpl = this._templates[name]; const tmplInfo = this._templateInfos[tmpl.hash]; if (!tmplInfo.setLayouts.length) { @@ -474,7 +474,7 @@ export class ProgramLib { * 当前是否有已注册的指定名字的 shader * @param name Target shader name */ - public hasProgram (name: string) { + public hasProgram (name: string): boolean { return this._templates[name] !== undefined; } @@ -484,7 +484,7 @@ export class ProgramLib { * @param name Target shader name * @param defines The combination of preprocess macros */ - public getKey (name: string, defines: MacroRecord) { + public getKey (name: string, defines: MacroRecord): string { const tmpl = this._templates[name]; return getVariantKey(tmpl, defines); } @@ -494,14 +494,14 @@ export class ProgramLib { * @zh 销毁所有完全满足指定预处理宏特征的 shader 实例。 * @param defines The preprocess macros as filter */ - public destroyShaderByDefines (defines: MacroRecord) { + public destroyShaderByDefines (defines: MacroRecord): void { const names = Object.keys(defines); if (!names.length) { return; } - const regexes = names.map((cur) => { + const regexes = names.map((cur): RegExp => { let val = defines[cur]; if (typeof val === 'boolean') { val = val ? '1' : '0'; } return new RegExp(`${cur}${val}`); }); - const keys = Object.keys(this._cache).filter((k) => regexes.every((re) => re.test(this._cache[k].name))); + const keys = Object.keys(this._cache).filter((k): boolean => regexes.every((re): boolean => re.test(this._cache[k].name))); for (let i = 0; i < keys.length; i++) { const k = keys[i]; const prog = this._cache[k]; @@ -519,7 +519,7 @@ export class ProgramLib { * @param pipeline The [[RenderPipeline]] which owns the render command * @param key The shader cache key, if already known */ - public getGFXShader (device: Device, name: string, defines: MacroRecord, pipeline: PipelineRuntime, key?: string) { + public getGFXShader (device: Device, name: string, defines: MacroRecord, pipeline: PipelineRuntime, key?: string): Shader { Object.assign(defines, pipeline.macros); if (!key) key = this.getKey(name, defines); const res = this._cache[key]; @@ -536,7 +536,7 @@ export class ProgramLib { const macroArray = prepareDefines(defines, tmpl.defines); const prefix = pipeline.constantMacros + tmpl.constantMacros - + macroArray.reduce((acc, cur) => `${acc}#define ${cur.name} ${cur.value}\n`, ''); + + macroArray.reduce((acc, cur): string => `${acc}#define ${cur.name} ${cur.value}\n`, ''); let src = tmpl.glsl3; const deviceShaderVersion = getDeviceShaderVersion(device); @@ -565,7 +565,7 @@ export class ProgramLib { } } -export function getDeviceShaderVersion (device: Device) { +export function getDeviceShaderVersion (device: Device): string { switch (device.gfxAPI) { case API.GLES2: case API.WEBGL: return 'glsl1'; diff --git a/cocos/render-scene/core/program-utils.ts b/cocos/render-scene/core/program-utils.ts index 5132b7f8e32..080e2b7bfcd 100644 --- a/cocos/render-scene/core/program-utils.ts +++ b/cocos/render-scene/core/program-utils.ts @@ -34,7 +34,7 @@ export interface IMacroInfo { isDefault: boolean; } -function mapDefine (info: EffectAsset.IDefineInfo, def: number | string | boolean) { +function mapDefine (info: EffectAsset.IDefineInfo, def: number | string | boolean): string { switch (info.type) { case 'boolean': return typeof def === 'number' ? def.toString() : (def ? '1' : '0'); case 'string': return def !== undefined ? def as string : info.options![0]; @@ -45,7 +45,7 @@ function mapDefine (info: EffectAsset.IDefineInfo, def: number | string | boolea } } -export function prepareDefines (defs: MacroRecord, tDefs: EffectAsset.IDefineInfo[]) { +export function prepareDefines (defs: MacroRecord, tDefs: EffectAsset.IDefineInfo[]): IMacroInfo[] { const macros: IMacroInfo[] = []; for (let i = 0; i < tDefs.length; i++) { const tmpl = tDefs[i]; @@ -58,11 +58,11 @@ export function prepareDefines (defs: MacroRecord, tDefs: EffectAsset.IDefineInf return macros; } -export function getShaderInstanceName (name: string, macros: IMacroInfo[]) { - return name + macros.reduce((acc, cur) => (cur.isDefault ? acc : `${acc}|${cur.name}${cur.value}`), ''); +export function getShaderInstanceName (name: string, macros: IMacroInfo[]): string { + return name + macros.reduce((acc, cur): string => (cur.isDefault ? acc : `${acc}|${cur.name}${cur.value}`), ''); } -function dependencyCheck (dependencies: string[], defines: MacroRecord) { +function dependencyCheck (dependencies: string[], defines: MacroRecord): boolean { for (let i = 0; i < dependencies.length; i++) { const d = dependencies[i]; if (d[0] === '!') { // negative dependency @@ -74,7 +74,7 @@ function dependencyCheck (dependencies: string[], defines: MacroRecord) { return true; } -export function getActiveAttributes (tmpl: IProgramInfo, gfxAttributes: Attribute[], defines: MacroRecord) { +export function getActiveAttributes (tmpl: IProgramInfo, gfxAttributes: Attribute[], defines: MacroRecord): Attribute[] { const out: Attribute[] = []; const attributes = tmpl.attributes; for (let i = 0; i < attributes.length; i++) { @@ -84,7 +84,7 @@ export function getActiveAttributes (tmpl: IProgramInfo, gfxAttributes: Attribut return out; } -export function getVariantKey (programInfo: IProgramInfo, defines: MacroRecord) { +export function getVariantKey (programInfo: IProgramInfo, defines: MacroRecord): string { const tmplDefs = programInfo.defines; if (programInfo.uber) { let key = ''; @@ -122,7 +122,7 @@ defaultUniformCounts.set('cc_lightSizeRangeAngle', UBOForwardLight.LIGHTS_PER_PA defaultUniformCounts.set('cc_lightDir', UBOForwardLight.LIGHTS_PER_PASS); defaultUniformCounts.set('cc_lightBoundingSizeVS', UBOForwardLight.LIGHTS_PER_PASS); -function getUniformSize (prevSize: number, m: Uniform) { +function getUniformSize (prevSize: number, m: Uniform): number { if (m.count) { return prevSize + GetTypeSize(m.type) * m.count; } else { @@ -135,11 +135,11 @@ function getUniformSize (prevSize: number, m: Uniform) { return prevSize; } -export function getSize (blockMembers: Uniform[]) { +export function getSize (blockMembers: Uniform[]): number { return blockMembers.reduce(getUniformSize, 0); } -export function genHandles (tmpl: EffectAsset.IShaderInfo | ShaderInfo) { +export function genHandles (tmpl: EffectAsset.IShaderInfo | ShaderInfo): Record { const handleMap: Record = {}; // block member handles for (let i = 0; i < tmpl.blocks.length; i++) { @@ -160,11 +160,11 @@ export function genHandles (tmpl: EffectAsset.IShaderInfo | ShaderInfo) { return handleMap; } -function getBitCount (cnt: number) { +function getBitCount (cnt: number): number { return Math.ceil(Math.log2(Math.max(cnt, 2))); } -export function populateMacros (tmpl: IProgramInfo) { +export function populateMacros (tmpl: IProgramInfo): void { // calculate option mask offset let offset = 0; for (let i = 0; i < tmpl.defines.length; i++) { @@ -173,12 +173,12 @@ export function populateMacros (tmpl: IProgramInfo) { if (def.type === 'number') { const range = def.range!; cnt = getBitCount(range[1] - range[0] + 1); // inclusive on both ends - def._map = (value: number) => value - range[0]; + def._map = (value: number): number => value - range[0]; } else if (def.type === 'string') { cnt = getBitCount(def.options!.length); - def._map = (value: any) => Math.max(0, def.options!.findIndex((s) => s === value)); + def._map = (value: any): number => Math.max(0, def.options!.findIndex((s): boolean => s === value)); } else if (def.type === 'boolean') { - def._map = (value: any) => (value ? 1 : 0); + def._map = (value: any): number => (value ? 1 : 0); } def._offset = offset; offset += cnt; @@ -191,8 +191,8 @@ export function populateMacros (tmpl: IProgramInfo) { } } -export function getCombinationDefines (combination: EffectAsset.IPreCompileInfo) { - const defines = Object.keys(combination).reduce((out, name) => out.reduce((acc, cur) => { +export function getCombinationDefines (combination: EffectAsset.IPreCompileInfo): Record[] { + const defines = Object.keys(combination).reduce((out, name): Record[] => out.reduce((acc, cur): Record[] => { const choices = combination[name]; for (let i = 0; i < choices.length; ++i) { const defines = { ...cur }; @@ -204,7 +204,7 @@ export function getCombinationDefines (combination: EffectAsset.IPreCompileInfo) return defines; } -export function addEffectDefaultProperties (effect: EffectAsset) { +export function addEffectDefaultProperties (effect: EffectAsset): void { for (let i = 0; i < effect.techniques.length; i++) { const tech = effect.techniques[i]; for (let j = 0; j < tech.passes.length; j++) { diff --git a/cocos/render-scene/core/render-scene.ts b/cocos/render-scene/core/render-scene.ts index 97165374dec..0ffabd7091d 100644 --- a/cocos/render-scene/core/render-scene.ts +++ b/cocos/render-scene/core/render-scene.ts @@ -141,7 +141,7 @@ export class RenderScene { * @en All active 2d draw batches of the render scene. * @zh 渲染场景管理的所有 2D 渲染批次对象。 */ - get batches () { + get batches (): DrawBatch2D[] { return this._batches; } @@ -171,7 +171,7 @@ export class RenderScene { * Register the creation function of the render scene to root. * @internal */ - public static registerCreateFunc (root: Root) { + public static registerCreateFunc (root: Root): void { root._createSceneFun = (_root: Root): RenderScene => new RenderScene(_root); } @@ -196,7 +196,7 @@ export class RenderScene { * @param stamp The update time stamp * @returns void */ - public update (stamp: number) { + public update (stamp: number): void { const mainLight = this._mainLight; if (mainLight) { mainLight.update(); @@ -242,7 +242,7 @@ export class RenderScene { * @en Destroy the render scene, dangerous, please do not invoke manually. * @zh 销毁渲染场景,请不要手动销毁,会造成未知行为。 */ - public destroy () { + public destroy (): void { this.removeCameras(); this.removeSphereLights(); this.removeSpotLights(); @@ -252,7 +252,7 @@ export class RenderScene { this._lodStateCache.clearCache(); } - public isCulledByLod (camera: Camera, model: Model) { + public isCulledByLod (camera: Camera, model: Model): boolean { return this._lodStateCache.isLodModelCulled(camera, model); } @@ -260,7 +260,7 @@ export class RenderScene { * @en Attach a camera to the render scene * @zh 向渲染场景挂载一个相机 */ - public addCamera (cam: Camera) { + public addCamera (cam: Camera): void { cam.attachToScene(this); this._cameras.push(cam); this._lodStateCache.addCamera(cam); @@ -270,7 +270,7 @@ export class RenderScene { * @en Detach a camera to the render scene * @zh 从渲染场景移除一个相机 */ - public removeCamera (camera: Camera) { + public removeCamera (camera: Camera): void { for (let i = 0; i < this._cameras.length; ++i) { if (this._cameras[i] === camera) { this._cameras.splice(i, 1); @@ -285,7 +285,7 @@ export class RenderScene { * @en Detach all cameras to the render scene * @zh 从渲染场景移除所有相机 */ - public removeCameras () { + public removeCameras (): void { for (const camera of this._cameras) { camera.detachFromScene(); this._lodStateCache.removeCamera(camera); @@ -298,7 +298,7 @@ export class RenderScene { * @zh 给渲染场景设置主光源 * @param dl The main directional light source */ - public setMainLight (dl: DirectionalLight | null) { + public setMainLight (dl: DirectionalLight | null): void { this._mainLight = dl; if (this._mainLight) this._mainLight.activate(); } @@ -308,7 +308,7 @@ export class RenderScene { * @zh 从渲染场景移除主光源 * @param dl The main directional light source, if it's not the actual main light, nothing happens. */ - public unsetMainLight (dl: DirectionalLight) { + public unsetMainLight (dl: DirectionalLight): void { if (this._mainLight === dl) { const dlList = this._directionalLights; if (dlList.length) { @@ -327,7 +327,7 @@ export class RenderScene { * @zh 增加一个方向光源,场景中只会有一个方向光是起效的,并且会作为主光源。 * @param dl The directional light. */ - public addDirectionalLight (dl: DirectionalLight) { + public addDirectionalLight (dl: DirectionalLight): void { dl.attachToScene(this); this._directionalLights.push(dl); } @@ -337,7 +337,7 @@ export class RenderScene { * @zh 删除一个方向光源。 * @param dl The directional light. */ - public removeDirectionalLight (dl: DirectionalLight) { + public removeDirectionalLight (dl: DirectionalLight): void { for (let i = 0; i < this._directionalLights.length; ++i) { if (this._directionalLights[i] === dl) { dl.detachFromScene(); @@ -352,7 +352,7 @@ export class RenderScene { * @zh 增加一个球面光源。 * @param pl The sphere light. */ - public addSphereLight (pl: SphereLight) { + public addSphereLight (pl: SphereLight): void { pl.attachToScene(this); this._sphereLights.push(pl); } @@ -362,7 +362,7 @@ export class RenderScene { * @zh 删除一个球面光源。 * @param pl The sphere light. */ - public removeSphereLight (pl: SphereLight) { + public removeSphereLight (pl: SphereLight): void { for (let i = 0; i < this._sphereLights.length; ++i) { if (this._sphereLights[i] === pl) { pl.detachFromScene(); @@ -378,7 +378,7 @@ export class RenderScene { * @zh 增加一个聚光灯光源。 * @param sl The spot light. */ - public addSpotLight (sl: SpotLight) { + public addSpotLight (sl: SpotLight): void { sl.attachToScene(this); this._spotLights.push(sl); } @@ -388,7 +388,7 @@ export class RenderScene { * @zh 删除一个聚光灯光源。 * @param sl The spot light. */ - public removeSpotLight (sl: SpotLight) { + public removeSpotLight (sl: SpotLight): void { for (let i = 0; i < this._spotLights.length; ++i) { if (this._spotLights[i] === sl) { sl.detachFromScene(); @@ -403,7 +403,7 @@ export class RenderScene { * @en Remove all sphere light sources. * @zh 删除所有球面光源。 */ - public removeSphereLights () { + public removeSphereLights (): void { for (let i = 0; i < this._sphereLights.length; ++i) { this._sphereLights[i].detachFromScene(); } @@ -414,7 +414,7 @@ export class RenderScene { * @en Remove all spot light sources. * @zh 删除所有聚光灯光源。 */ - public removeSpotLights () { + public removeSpotLights (): void { for (let i = 0; i < this._spotLights.length; ++i) { this._spotLights[i].detachFromScene(); } @@ -426,7 +426,7 @@ export class RenderScene { * @zh 增加一个点光源。 * @param pl @en The point light. @zh 点光源。 */ - public addPointLight (pl: PointLight) { + public addPointLight (pl: PointLight): void { pl.attachToScene(this); this._pointLights.push(pl); } @@ -436,7 +436,7 @@ export class RenderScene { * @zh 删除一个点光源。 * @param pl @en The point light. @zh 点光源。 */ - public removePointLight (pl: PointLight) { + public removePointLight (pl: PointLight): void { for (let i = 0; i < this._pointLights.length; ++i) { if (this._pointLights[i] === pl) { pl.detachFromScene(); @@ -450,7 +450,7 @@ export class RenderScene { * @en Remove all point light sources. * @zh 删除所有点光源。 */ - public removePointLights () { + public removePointLights (): void { for (let i = 0; i < this._pointLights.length; ++i) { this._pointLights[i].detachFromScene(); } @@ -462,7 +462,7 @@ export class RenderScene { * @zh 增加一个范围平行光源。 * @param l @en The ranged directional light. @zh 范围平行光。 */ - public addRangedDirLight (l: RangedDirectionalLight) { + public addRangedDirLight (l: RangedDirectionalLight): void { l.attachToScene(this); this._rangedDirLights.push(l); } @@ -472,7 +472,7 @@ export class RenderScene { * @zh 删除一个范围平行光源。 * @param l @en The ranged directional light. @zh 范围平行光。 */ - public removeRangedDirLight (l: RangedDirectionalLight) { + public removeRangedDirLight (l: RangedDirectionalLight): void { for (let i = 0; i < this._rangedDirLights.length; ++i) { if (this._rangedDirLights[i] === l) { l.detachFromScene(); @@ -486,7 +486,7 @@ export class RenderScene { * @en Remove all ranged directional light sources. * @zh 删除所有范围平行光源。 */ - public removeRangedDirLights () { + public removeRangedDirLights (): void { for (let i = 0; i < this._rangedDirLights.length; ++i) { this._rangedDirLights[i].detachFromScene(); } @@ -498,7 +498,7 @@ export class RenderScene { * @zh 增加一个模型,渲染场景上挂载的所有模型都会被提交渲染。 * @param m The model. */ - public addModel (m: Model) { + public addModel (m: Model): void { m.attachToScene(this); this._models.push(m); } @@ -508,7 +508,7 @@ export class RenderScene { * @zh 删除一个模型,移除的模型将不再被提交渲染。 * @param m The model. */ - public removeModel (model: Model) { + public removeModel (model: Model): void { for (let i = 0; i < this._models.length; ++i) { if (this._models[i] === model) { this._lodStateCache.removeModel(model); @@ -524,7 +524,7 @@ export class RenderScene { * @en Remove all models. * @zh 删除所有模型。 */ - public removeModels () { + public removeModels (): void { for (const m of this._models) { this._lodStateCache.removeModel(m); m.detachFromScene(); @@ -540,7 +540,7 @@ export class RenderScene { * @internal * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ - public addBatch (batch: DrawBatch2D) { + public addBatch (batch: DrawBatch2D): void { this._batches.push(batch); } @@ -551,7 +551,7 @@ export class RenderScene { * @internal * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ - public removeBatch (batch: DrawBatch2D) { + public removeBatch (batch: DrawBatch2D): void { for (let i = 0; i < this._batches.length; ++i) { if (this._batches[i] === batch) { this._batches.splice(i, 1); @@ -566,7 +566,7 @@ export class RenderScene { * @internal * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ - public removeBatches () { + public removeBatches (): void { this._batches.length = 0; } @@ -576,7 +576,7 @@ export class RenderScene { * @zh 增加一个LOD 组,渲染场景上挂载的所有LOD 组都会被提交渲染。 * @param lodGroup the LOD group */ - addLODGroup (lodGroup: LODGroup) { + addLODGroup (lodGroup: LODGroup): void { this._lodGroups.push(lodGroup); lodGroup.attachToScene(this); this._lodStateCache.addLodGroup(lodGroup); @@ -588,7 +588,7 @@ export class RenderScene { * @zh 删除一个LOD 组,移除的LOD 组将不再被提交渲染。 * @param lodGroup the LOD group */ - removeLODGroup (lodGroup: LODGroup) { + removeLODGroup (lodGroup: LODGroup): void { const index = this._lodGroups.indexOf(lodGroup); if (index >= 0) { this._lodGroups.splice(index, 1); @@ -602,7 +602,7 @@ export class RenderScene { * @en Remove all LOD groups. * @zh 删除所有LOD 组。 */ - removeLODGroups () { + removeLODGroups (): void { for (const group of this._lodGroups) { this._lodStateCache.removeLodGroup(group); } @@ -613,7 +613,7 @@ export class RenderScene { * @en Notify all models that the global pipeline state have been updated so that they can update their render data and states. * @zh 通知所有模型全局管线状态已更新,需要更新自身状态。 */ - public onGlobalPipelineStateChanged () { + public onGlobalPipelineStateChanged (): void { for (const m of this._models) { m.onGlobalPipelineStateChanged(); } @@ -649,7 +649,7 @@ class LodStateCache { this._renderScene = scene; } - addCamera (camera: Camera) { + addCamera (camera: Camera): void { const needRegisterChanged = false; for (const lodGroup of this._renderScene.lodGroups) { const layer = lodGroup.node.layer; @@ -662,13 +662,13 @@ class LodStateCache { } } - removeCamera (camera: Camera) { + removeCamera (camera: Camera): void { if (this._lodStateInCamera.has(camera)) { this._lodStateInCamera.delete(camera); } } - addLodGroup (lodGroup: LODGroup) { + addLodGroup (lodGroup: LODGroup): void { this._newAddedLodGroupVec.push(lodGroup); for (const camera of this._renderScene.cameras) { @@ -682,7 +682,7 @@ class LodStateCache { } } - removeLodGroup (lodGroup: LODGroup) { + removeLodGroup (lodGroup: LODGroup): void { for (let index = 0; index < lodGroup.lodCount; index++) { const lod = lodGroup.lodDataArray[index]; for (const model of lod.models) { @@ -695,14 +695,14 @@ class LodStateCache { this._levelModels.delete(lodGroup); } - removeModel (model: Model) { + removeModel (model: Model): void { if (this._modelsInLODGroup.has(model)) { this._modelsInLODGroup.delete(model); } } // Update list of visible cameras on _modelsInLODGroup and update lod usage level under specified camera. - updateLodState () { + updateLodState (): void { // insert vecAddedLodGroup's model into modelsByAnyLODGroup for (const addedLodGroup of this._newAddedLodGroupVec) { let levelModels = this._levelModels.get(addedLodGroup); @@ -756,8 +756,8 @@ class LodStateCache { const lodModels = this._levelModels.get(lodGroup); if (lodModels) { - lodModels.forEach((vecArray, index) => { - vecArray.forEach((model) => { + lodModels.forEach((vecArray, index): void => { + vecArray.forEach((model): void => { const modelInfo = this._modelsInLODGroup.get(model); if (modelInfo) { modelInfo.clear(); @@ -768,7 +768,7 @@ class LodStateCache { for (const visibleIndex of lodLevels) { const vecModels = lodModels.get(visibleIndex); if (vecModels) { - vecModels.forEach((model) => { + vecModels.forEach((model): void => { const modelInfo = this._modelsInLODGroup.get(model); if (modelInfo && model.node && model.node.active) { for (const visibleCamera of this._lodStateInCamera) { @@ -819,8 +819,8 @@ class LodStateCache { if (lodGroup.isLockLevelChanged()) { lodGroup.resetLockChangeFlag(); - lodModels.forEach((vecArray, index) => { - vecArray.forEach((model) => { + lodModels.forEach((vecArray, index): void => { + vecArray.forEach((model): void => { const modelInfo = this._modelsInLODGroup.get(model); if (modelInfo) { modelInfo.clear(); @@ -829,12 +829,12 @@ class LodStateCache { }); hasUpdated = true; } else if (hasUpdated) { - this._lodStateInCamera.forEach((lodState, camera) => { + this._lodStateInCamera.forEach((lodState, camera): void => { const lodInfo = lodState.get(lodGroup); if (lodInfo && lodInfo.usedLevel !== lodInfo.lastUsedLevel) { const vecModels = lodModels.get(lodInfo.lastUsedLevel); if (vecModels) { - vecModels.forEach((model) => { + vecModels.forEach((model): void => { const modelInfo = this._modelsInLODGroup.get(model); if (modelInfo) { modelInfo.clear(); @@ -846,13 +846,13 @@ class LodStateCache { } if (hasUpdated) { - this._lodStateInCamera.forEach((lodState, camera) => { + this._lodStateInCamera.forEach((lodState, camera): void => { const lodInfo = lodState.get(lodGroup); if (lodInfo) { const usedLevel = lodInfo.usedLevel; const vecModels = lodModels.get(usedLevel); if (vecModels) { - vecModels.forEach((model) => { + vecModels.forEach((model): void => { const modelInfo = this._modelsInLODGroup.get(model); if (modelInfo && model.node && model.node.active) { modelInfo.set(camera, true); @@ -866,7 +866,7 @@ class LodStateCache { } } - isLodModelCulled (camera: Camera, model: Model) { + isLodModelCulled (camera: Camera, model: Model): boolean { const modelInfo = this._modelsInLODGroup.get(model); if (!modelInfo) { return false; @@ -875,7 +875,7 @@ class LodStateCache { return !modelInfo.has(camera); } - clearCache () { + clearCache (): void { this._levelModels.clear(); this._modelsInLODGroup.clear(); this._lodStateInCamera.clear(); diff --git a/cocos/render-scene/core/render-window.ts b/cocos/render-scene/core/render-window.ts index b59384d6574..24f81164daf 100644 --- a/cocos/render-scene/core/render-window.ts +++ b/cocos/render-scene/core/render-window.ts @@ -75,7 +75,7 @@ export class RenderWindow { * @en Get the swapchain for this window, if there is one * @zh 如果存在的话,获取此窗口的交换链 */ - get swapchain () { + get swapchain (): Swapchain { return this._swapchain; } @@ -87,7 +87,7 @@ export class RenderWindow { return this._framebuffer!; } - get cameras () { + get cameras (): Camera[] { return this._cameras; } @@ -107,7 +107,7 @@ export class RenderWindow { /** * @private */ - public static registerCreateFunc (root: Root) { + public static registerCreateFunc (root: Root): void { root._createWindowFun = (_root: Root): RenderWindow => new RenderWindow(_root); } @@ -167,7 +167,7 @@ export class RenderWindow { return true; } - public destroy () { + public destroy (): void { this.clearCameras(); if (this._framebuffer) { @@ -196,7 +196,7 @@ export class RenderWindow { * @param width The new width. * @param height The new height. */ - public resize (width: number, height: number) { + public resize (width: number, height: number): void { if (this._swapchain) { this._swapchain.resize(width, height, orientationMap[screenAdapter.orientation]); this._width = this._swapchain.width; @@ -232,7 +232,7 @@ export class RenderWindow { * @param cameras @en The output cameras list, should be empty before invoke this function * @zh 输出相机列表参数,传入时应该为空 */ - public extractRenderCameras (cameras: Camera[]) { + public extractRenderCameras (cameras: Camera[]): void { for (let j = 0; j < this._cameras.length; j++) { const camera = this._cameras[j]; if (camera.enabled) { @@ -247,7 +247,7 @@ export class RenderWindow { * @zh 添加渲染相机 * @param camera @en The camera to attach @zh 要挂载的相机 */ - public attachCamera (camera: Camera) { + public attachCamera (camera: Camera): void { for (let i = 0; i < this._cameras.length; i++) { if (this._cameras[i] === camera) { return; @@ -262,7 +262,7 @@ export class RenderWindow { * @zh 移除场景中的渲染相机 * @param camera @en The camera to detach @zh 要移除的相机 */ - public detachCamera (camera: Camera) { + public detachCamera (camera: Camera): void { for (let i = 0; i < this._cameras.length; ++i) { if (this._cameras[i] === camera) { this._cameras.splice(i, 1); @@ -275,7 +275,7 @@ export class RenderWindow { * @en Clear all attached cameras * @zh 清空全部渲染相机 */ - public clearCameras () { + public clearCameras (): void { this._cameras.length = 0; } @@ -283,7 +283,7 @@ export class RenderWindow { * @en Sort all attached cameras with priority * @zh 按照优先级对所有挂载的相机排序 */ - public sortCameras () { - this._cameras.sort((a: Camera, b: Camera) => a.priority - b.priority); + public sortCameras (): void { + this._cameras.sort((a: Camera, b: Camera): number => a.priority - b.priority); } } diff --git a/cocos/render-scene/core/texture-buffer-pool.ts b/cocos/render-scene/core/texture-buffer-pool.ts index ceb76399405..f17259266b1 100644 --- a/cocos/render-scene/core/texture-buffer-pool.ts +++ b/cocos/render-scene/core/texture-buffer-pool.ts @@ -58,7 +58,7 @@ export interface ITextureBufferPoolInfo { roundUpFn?: (size: number, formatSize: number) => number; // given a target size, how will the actual texture size round up? } -function roundUp (n: number, alignment: number) { +function roundUp (n: number, alignment: number): number { return Math.ceil(n / alignment) * alignment; } @@ -81,7 +81,7 @@ export class TextureBufferPool { this._device = device; } - public initialize (info: ITextureBufferPoolInfo) { + public initialize (info: ITextureBufferPoolInfo): void { const formatInfo = FormatInfos[info.format]; this._format = info.format; this._formatSize = formatInfo.size; @@ -92,7 +92,7 @@ export class TextureBufferPool { if (info.inOrderFree) { this.alloc = this._McDonaldAlloc; } } - public destroy () { + public destroy (): void { for (let i = 0; i < this._chunkCount; ++i) { const chunk = this._chunks[i]; chunk.texture.destroy(); @@ -101,7 +101,7 @@ export class TextureBufferPool { this._handles.length = 0; } - public alloc (size: number, chunkIdx?: number) { + public alloc (size: number, chunkIdx?: number): ITextureBufferHandle { size = roundUp(size, this._alignment); let index = -1; @@ -148,7 +148,7 @@ export class TextureBufferPool { return texHandle; } - public free (handle: ITextureBufferHandle) { + public free (handle: ITextureBufferHandle): void { for (let i = 0; i < this._handles.length; ++i) { if (this._handles[i] === handle) { this._chunks[handle.chunkIdx].end = handle.end; @@ -158,7 +158,7 @@ export class TextureBufferPool { } } - public createChunk (length: number) { + public createChunk (length: number): number { const texSize = length * length * this._formatSize; debug(`TextureBufferPool: Allocate chunk ${this._chunkCount}, size: ${texSize}, format: ${this._format}`); @@ -181,7 +181,7 @@ export class TextureBufferPool { return this._chunkCount++; } - public update (handle: ITextureBufferHandle, buffer: ArrayBuffer) { + public update (handle: ITextureBufferHandle, buffer: ArrayBuffer): void { const buffers: ArrayBufferView[] = []; const regions: BufferTextureCopy[] = []; const start = handle.start / this._formatSize; @@ -243,7 +243,7 @@ export class TextureBufferPool { this._device.copyBuffersToTexture(buffers, handle.texture, regions); } - private _findAvailableSpace (size: number, chunkIdx: number) { + private _findAvailableSpace (size: number, chunkIdx: number): number { const chunk = this._chunks[chunkIdx]; let isFound = false; let start = chunk.start; @@ -251,7 +251,7 @@ export class TextureBufferPool { isFound = true; } else { start = 0; // try to find from head again - const handles = this._handles.filter((h) => h.chunkIdx === chunkIdx).sort((a, b) => a.start - b.start); + const handles = this._handles.filter((h): boolean => h.chunkIdx === chunkIdx).sort((a, b): number => a.start - b.start); for (let i = 0; i < handles.length; i++) { const handle = handles[i]; if ((start + size) <= handle.start) { @@ -268,7 +268,7 @@ export class TextureBufferPool { } // [McDonald 12] Efficient Buffer Management - private _McDonaldAlloc (size: number) { + private _McDonaldAlloc (size: number): ITextureBufferHandle { size = roundUp(size, this._alignment); for (let i = 0; i < this._chunkCount; ++i) { diff --git a/cocos/render-scene/scene/ambient.ts b/cocos/render-scene/scene/ambient.ts index 389c056218b..9faf273aca2 100644 --- a/cocos/render-scene/scene/ambient.ts +++ b/cocos/render-scene/scene/ambient.ts @@ -127,7 +127,7 @@ export class Ambient { protected _enabled = false; - public initialize (ambientInfo: AmbientInfo) { + public initialize (ambientInfo: AmbientInfo): void { // Init HDR/LDR from serialized data on load this._skyColorHDR = ambientInfo.skyColorHDR; this._groundAlbedoHDR.set(ambientInfo.groundAlbedoHDR); diff --git a/cocos/render-scene/scene/camera.ts b/cocos/render-scene/scene/camera.ts index 436b512375d..96fc0ff967f 100644 --- a/cocos/render-scene/scene/camera.ts +++ b/cocos/render-scene/scene/camera.ts @@ -30,6 +30,7 @@ import { RenderScene } from '../core/render-scene'; import { RenderWindow } from '../core/render-window'; import { GeometryRenderer } from '../../rendering/geometry-renderer'; import { PostProcess } from '../../rendering/post-process/components/post-process'; +import type { Frustum } from '../../core/geometry'; /** * @en The enumeration type for the fixed axis of the camera. @@ -402,7 +403,7 @@ export class Camera { * @en This exposure value corresponding to default standard camera exposure parameters. * @zh 默认相机的曝光值。 */ - public static get standardExposureValue () { + public static get standardExposureValue (): number { return 1.0 / 38400.0; } @@ -410,7 +411,7 @@ export class Camera { * @en The luminance unit scale used by area lights. * @zh 默认局部光源使用的亮度单位缩放。 */ - public static get standardLightMeterScale () { + public static get standardLightMeterScale (): number { return 10000.0; } @@ -418,7 +419,7 @@ export class Camera { * @en The name of the camera * @zh 相机的名称 */ - get name () { + get name (): string | null { return this._name; } @@ -426,7 +427,7 @@ export class Camera { * @en The render scene to which the camera is attached * @zh 相机所挂载的场景 */ - get scene () { + get scene (): RenderScene | null { return this._scene; } @@ -437,7 +438,7 @@ export class Camera { set node (val: Node) { this._node = val; } - get node () { + get node (): Node { return this._node!; } @@ -445,7 +446,7 @@ export class Camera { * @en The unique ID of system window which the camera will render to. * @zh 相机关联的渲染窗口ID */ - get systemWindowId () { + get systemWindowId (): number { return this._windowId; } @@ -456,7 +457,7 @@ export class Camera { set window (val) { this._window = val; } - get window () { + get window (): RenderWindow { return this._window!; } @@ -467,7 +468,7 @@ export class Camera { set enabled (val) { this._enabled = val; } - get enabled () { + get enabled (): boolean { return this._enabled; } @@ -498,7 +499,7 @@ export class Camera { * @en The width of the camera's view size * @zh 相机的视图宽度 */ - get width () { + get width (): number { return this._width; } @@ -506,7 +507,7 @@ export class Camera { * @en The height of the camera's view size * @zh 相机的视图高度 */ - get height () { + get height (): number { return this._height; } @@ -517,7 +518,7 @@ export class Camera { set position (val) { this._position = val; } - get position () { + get position (): Vec3 { return this._position; } @@ -528,7 +529,7 @@ export class Camera { set forward (val) { this._forward = val; } - get forward () { + get forward (): Vec3 { return this._forward; } @@ -624,7 +625,7 @@ export class Camera { this._clearColor.z = val.z; this._clearColor.w = val.w; } - get clearColor () { + get clearColor (): IVec4Like { return this._clearColor as IVec4Like; } @@ -658,7 +659,7 @@ export class Camera { this._proj = val; this._isProjDirty = true; } - get projectionType () { + get projectionType (): CameraProjection { return this._proj; } @@ -666,7 +667,7 @@ export class Camera { * @en The aspect ratio of the camera * @zh 相机视图的长宽比 */ - get aspect () { + get aspect (): number { return this._aspect; } @@ -678,7 +679,7 @@ export class Camera { this._orthoHeight = val; this._isProjDirty = true; } - get orthoHeight () { + get orthoHeight (): number { return this._orthoHeight; } @@ -690,7 +691,7 @@ export class Camera { this._fovAxis = axis; this._isProjDirty = true; } - get fovAxis () { + get fovAxis (): CameraFOVAxis { return this._fovAxis; } @@ -702,7 +703,7 @@ export class Camera { this._fov = fov; this._isProjDirty = true; } - get fov () { + get fov (): number { return this._fov; } @@ -714,7 +715,7 @@ export class Camera { this._nearClip = nearClip; this._isProjDirty = true; } - get nearClip () { + get nearClip (): number { return this._nearClip; } @@ -726,7 +727,7 @@ export class Camera { this._farClip = farClip; this._isProjDirty = true; } - get farClip () { + get farClip (): number { return this._farClip; } @@ -734,7 +735,7 @@ export class Camera { * @en The viewport rect of the camera, pre-rotated (i.e. always in identity/portrait mode) if possible. * @zh 相机的视口矩形,如果设备允许的话,这个视口会永远保持竖屏状态,由渲染流程保障旋转的正确。 */ - get viewport () { + get viewport (): Rect { return this._viewport; } set viewport (val) { @@ -749,7 +750,7 @@ export class Camera { set frustum (val) { this._frustum = val; } - get frustum () { + get frustum (): Frustum { return this._frustum; } @@ -757,7 +758,7 @@ export class Camera { * @en The view matrix of the camera * @zh 相机的视图矩阵 */ - get matView () { + get matView (): Mat4 { return this._matView; } @@ -765,7 +766,7 @@ export class Camera { * @en The projection matrix of the camera * @zh 相机的投影矩阵 */ - get matProj () { + get matProj (): Mat4 { return this._matProj; } @@ -773,7 +774,7 @@ export class Camera { * @en The inverse of the projection matrix of the camera * @zh 相机的逆投影矩阵 */ - get matProjInv () { + get matProjInv (): Mat4 { return this._matProjInv; } @@ -781,7 +782,7 @@ export class Camera { * @en The view projection matrix of the camera * @zh 相机的视图投影矩阵 */ - get matViewProj () { + get matViewProj (): Mat4 { return this._matViewProj; } @@ -789,7 +790,7 @@ export class Camera { * @en The inverse of the view projection matrix of the camera * @zh 相机的逆视图投影矩阵 */ - get matViewProjInv () { + get matViewProjInv (): Mat4 { return this._matViewProjInv; } @@ -874,7 +875,7 @@ export class Camera { } } - private _updateAspect (oriented = true) { + private _updateAspect (oriented = true): void { this._aspect = (this.window.width * this._viewport.width) / (this.window.height * this._viewport.height); // window size/viewport is pre-rotated, but aspect should be oriented to acquire the correct projection if (oriented) { @@ -889,7 +890,7 @@ export class Camera { * @en Initialize the camera, normally you shouldn't invoke this function, it's managed automatically. * @zh 初始化相机,开发者通常不应该使用这个方法,初始化流程是自动管理的。 */ - public initialize (info: ICameraInfo) { + public initialize (info: ICameraInfo): void { if (info.usage !== undefined) { this._usage = info.usage; } else { @@ -919,7 +920,7 @@ export class Camera { * @en Destroy the camera, you shouldn't invoke this function, it's managed by the render scene. * @zh 销毁相机,开发者不应该使用这个方法,销毁流程是由 RenderScene 管理的。 */ - public destroy () { + public destroy (): void { this._node = null; this.detachFromScene(); if (this._window) { @@ -935,7 +936,7 @@ export class Camera { * @zh 将相机添加到相关的渲染场景中,以便可以被渲染器渲染。 * @param scene @en The render scene @zh 渲染场景 */ - public attachToScene (scene: RenderScene) { + public attachToScene (scene: RenderScene): void { this._enabled = true; this._scene = scene; } @@ -944,7 +945,7 @@ export class Camera { * @en Detach the camera from previously attached render scene. It will no longer be rendered. * @zh 将相机从之前设置的渲染场景移除,之后将不会再被渲染。 */ - public detachFromScene () { + public detachFromScene (): void { this._enabled = false; this._scene = null; } @@ -970,7 +971,7 @@ export class Camera { * @param width The width of the view size * @param height The height of the view size */ - public setFixedSize (width: number, height: number) { + public setFixedSize (width: number, height: number): void { this._width = width; this._height = height; this._updateAspect(); @@ -981,7 +982,7 @@ export class Camera { * Editor specific gizmo camera logic * @internal */ - public syncCameraEditor (camera) { + public syncCameraEditor (camera): void { if (EDITOR) { this.position = camera.position; this.forward = camera.forward; @@ -1053,7 +1054,7 @@ export class Camera { } } - get surfaceTransform () { + get surfaceTransform (): SurfaceTransform { return this._curTransform; } @@ -1061,7 +1062,7 @@ export class Camera { * @en Set the viewport in oriented space (equal to the actual screen rotation) * @zh 在目标朝向空间(实际屏幕朝向)内设置相机视口 */ - public setViewportInOrientedSpace (val: Rect) { + public setViewportInOrientedSpace (val: Rect): void { const { x, width, height } = val; const y = this._device.capabilities.screenSpaceSignY < 0 ? 1 - val.y - height : val.y; @@ -1108,7 +1109,7 @@ export class Camera { * @en create geometry renderer for this camera * @zh 创建这个摄像机的几何体渲染器 */ - public initGeometryRenderer () { + public initGeometryRenderer (): void { if (!this._geometryRenderer) { this._geometryRenderer = cclegacy.internal.GeometryRenderer ? new cclegacy.internal.GeometryRenderer() : null; this._geometryRenderer?.activate(this._device); @@ -1120,7 +1121,7 @@ export class Camera { * @zh 获取这个摄像机的几何体渲染器 * @returns @en return the geometry renderer @zh 返回几何体渲染器 */ - get geometryRenderer () { + get geometryRenderer (): GeometryRenderer | null { return this._geometryRenderer; } @@ -1153,7 +1154,7 @@ export class Camera { * @zh 修改相机的目标渲染窗口 * @param window The target render window, could be null */ - public changeTargetWindow (window: RenderWindow | null = null) { + public changeTargetWindow (window: RenderWindow | null = null): void { if (this._window) { this._window.detachCamera(this); } @@ -1174,7 +1175,7 @@ export class Camera { * @en Detach camera from the render window * @zh 将 camera 从渲染窗口移除 */ - public detachCamera () { + public detachCamera (): void { if (this._window) { this._window.detachCamera(this); } @@ -1310,7 +1311,7 @@ export class Camera { * @param height framebuffer height * @returns the resulting matrix */ - public worldMatrixToScreen (out: Mat4, worldMatrix: Mat4, width: number, height: number) { + public worldMatrixToScreen (out: Mat4, worldMatrix: Mat4, width: number, height: number): Mat4 { Mat4.multiply(out, this._matViewProj, worldMatrix); Mat4.multiply(out, correctionMatrices[this._curTransform], out); @@ -1330,7 +1331,7 @@ export class Camera { * @zh 计算并设置斜视锥体投影矩阵 * @param clipPlane clip plane in camera space */ - public calculateObliqueMat (viewSpacePlane: Vec4) { + public calculateObliqueMat (viewSpacePlane: Vec4): void { const clipFar = new Vec4(Math.sign(viewSpacePlane.x), Math.sign(viewSpacePlane.y), 1.0, 1.0); const viewFar = clipFar.transformMat4(this._matProjInv); @@ -1351,16 +1352,16 @@ export class Camera { * @zh 设置相机的曝光值 * @param ev100 */ - protected setExposure (ev100) { + protected setExposure (ev100): void { this._exposure = 0.833333 / (2.0 ** ev100); } - private updateExposure () { + private updateExposure (): void { const ev100 = Math.log2((this._apertureValue * this._apertureValue) / this._shutterValue * 100.0 / this._isoValue); this.setExposure(ev100); } - private setDefaultUsage () { + private setDefaultUsage (): void { if (EDITOR) { if (cclegacy.GAME_VIEW) { this._usage = CameraUsage.GAME_VIEW; diff --git a/cocos/render-scene/scene/directional-light.ts b/cocos/render-scene/scene/directional-light.ts index 1a38f93d91e..aecb1f7bdf5 100644 --- a/cocos/render-scene/scene/directional-light.ts +++ b/cocos/render-scene/scene/directional-light.ts @@ -100,7 +100,7 @@ export class DirectionalLight extends Light { * @en The illuminance of the light in HDR mode * @zh HDR 模式下光源的辐照度 */ - get illuminanceHDR () { + get illuminanceHDR (): number { return this._illuminanceHDR; } set illuminanceHDR (value: number) { @@ -111,7 +111,7 @@ export class DirectionalLight extends Light { * @en The illuminance of the light in LDR mode * @zh LDR 模式下光源的辐照度 */ - get illuminanceLDR () { + get illuminanceLDR (): number { return this._illuminanceLDR; } set illuminanceLDR (value: number) { @@ -122,7 +122,7 @@ export class DirectionalLight extends Light { * @en Whether activate shadow * @zh 是否启用阴影? */ - get shadowEnabled () { + get shadowEnabled (): boolean { return this._shadowEnabled; } set shadowEnabled (val) { @@ -134,7 +134,7 @@ export class DirectionalLight extends Light { * @en get or set shadow pcf. * @zh 获取或者设置阴影pcf等级。 */ - get shadowPcf () { + get shadowPcf (): number { return this._shadowPcf; } set shadowPcf (val) { @@ -146,7 +146,7 @@ export class DirectionalLight extends Light { * @en get or set shadow map sampler offset * @zh 获取或者设置阴影纹理偏移值 */ - get shadowBias () { + get shadowBias (): number { return this._shadowBias; } set shadowBias (val) { @@ -157,7 +157,7 @@ export class DirectionalLight extends Light { * @en get or set normal bias. * @zh 设置或者获取法线偏移。 */ - get shadowNormalBias () { + get shadowNormalBias (): number { return this._shadowNormalBias; } set shadowNormalBias (val: number) { @@ -168,7 +168,7 @@ export class DirectionalLight extends Light { * @en Shadow color saturation * @zh 阴影颜色饱和度 */ - get shadowSaturation () { + get shadowSaturation (): number { return this._shadowSaturation; } set shadowSaturation (val: number) { @@ -179,7 +179,7 @@ export class DirectionalLight extends Light { * @en get or set shadow camera far * @zh 获取或者设置潜在阴影产生的范围 */ - get shadowDistance () { + get shadowDistance (): number { return this._shadowDistance; } set shadowDistance (val) { @@ -190,7 +190,7 @@ export class DirectionalLight extends Light { * @en get or set shadow camera far * @zh 获取或者设置潜在阴影产生的范围 */ - get shadowInvisibleOcclusionRange () { + get shadowInvisibleOcclusionRange (): number { return this._shadowInvisibleOcclusionRange; } set shadowInvisibleOcclusionRange (val) { @@ -201,7 +201,7 @@ export class DirectionalLight extends Light { * @en get or set shadow CSM level * @zh 获取或者设置级联阴影层数 */ - get csmLevel () { + get csmLevel (): number { return this._csmLevel; } set csmLevel (val) { @@ -213,7 +213,7 @@ export class DirectionalLight extends Light { * @en is CSM need update * @zh 获取或者设置级联阴影是否需要更新 */ - get csmNeedUpdate () { + get csmNeedUpdate (): boolean { return this._csmNeedUpdate; } set csmNeedUpdate (val) { @@ -224,7 +224,7 @@ export class DirectionalLight extends Light { * @en get or set shadow CSM level ratio * @zh 获取或者设置级联阴影层数系数 */ - get csmLayerLambda () { + get csmLayerLambda (): number { return this._csmLayerLambda; } set csmLayerLambda (val) { @@ -235,7 +235,7 @@ export class DirectionalLight extends Light { * @en get or set shadow CSM performance optimization mode * @zh 获取或者设置级联阴影性能优化模式 */ - get csmOptimizationMode () { + get csmOptimizationMode (): number { return this._csmOptimizationMode; } set csmOptimizationMode (val) { @@ -246,7 +246,7 @@ export class DirectionalLight extends Light { * @en get or set fixed area shadow * @zh 是否是固定区域阴影 */ - get shadowFixedArea () { + get shadowFixedArea (): boolean { return this._shadowFixedArea; } set shadowFixedArea (val) { @@ -258,7 +258,7 @@ export class DirectionalLight extends Light { * @en The near clip plane of the shadow camera * @zh 获取或者设置阴影相机近裁剪面 */ - get shadowNear () { + get shadowNear (): number { return this._shadowNear; } set shadowNear (val) { @@ -269,7 +269,7 @@ export class DirectionalLight extends Light { * @en The far clip plane of the shadow camera * @zh 获取或者设置阴影相机远裁剪面 */ - get shadowFar () { + get shadowFar (): number { return this._shadowFar; } set shadowFar (val) { @@ -280,7 +280,7 @@ export class DirectionalLight extends Light { * @en get or set shadow camera orthoSize * @zh 获取或者设置阴影相机正交大小 */ - get shadowOrthoSize () { + get shadowOrthoSize (): number { return this._shadowOrthoSize; } set shadowOrthoSize (val) { @@ -291,7 +291,7 @@ export class DirectionalLight extends Light { * @en Enabled csm layers transition * @zh 是否启用级联阴影层级过渡? */ - get csmLayersTransition () { + get csmLayersTransition (): boolean { return this._csmLayersTransition; } set csmLayersTransition (val) { @@ -303,7 +303,7 @@ export class DirectionalLight extends Light { * @en get or set csm layers transition range * @zh 获取或者设置级联阴影层级过渡范围? */ - get csmTransitionRange () { + get csmTransitionRange (): number { return this._csmTransitionRange; } set csmTransitionRange (val) { @@ -315,7 +315,7 @@ export class DirectionalLight extends Light { this._type = LightType.DIRECTIONAL; } - public initialize () { + public initialize (): void { super.initialize(); this.illuminance = Ambient.SUN_ILLUM; @@ -326,7 +326,7 @@ export class DirectionalLight extends Light { * @en Update the direction * @zh 更新方向 */ - public update () { + public update (): void { if (this._node && this._node.hasChangedFlags) { this.direction = Vec3.transformQuat(_v3, _forward, this._node.worldRotation); } @@ -335,7 +335,7 @@ export class DirectionalLight extends Light { /** * @engineInternal */ - public activate () { + public activate (): void { const root = cclegacy.director.root; const pipeline = root.pipeline; if (this._shadowEnabled) { diff --git a/cocos/render-scene/scene/fog.ts b/cocos/render-scene/scene/fog.ts index be04c19d2d1..ed303ebb3cb 100644 --- a/cocos/render-scene/scene/fog.ts +++ b/cocos/render-scene/scene/fog.ts @@ -3,23 +3,23 @@ https://www.cocos.com/ - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. */ import { Enum, Color, Vec4, cclegacy } from '../../core'; @@ -120,7 +120,7 @@ export class Fog { SRGBToLinear(this._colorArray, _v4); } - get fogColor () { + get fogColor (): Color { return this._fogColor; } @@ -229,7 +229,7 @@ export class Fog { protected _fogRange = 1.2; protected _activated = false; - public initialize (fogInfo : FogInfo) { + public initialize (fogInfo : FogInfo): void { this._activated = false; this.fogColor = fogInfo.fogColor; this._enabled = fogInfo.enabled; @@ -243,12 +243,12 @@ export class Fog { this.fogRange = fogInfo.fogRange; } - public activate () { + public activate (): void { this._updatePipeline(); this._activated = true; } - protected _updatePipeline () { + protected _updatePipeline (): void { const root = cclegacy.director.root; const value = this.enabled ? this.type : FOG_TYPE_NONE; const accurateValue = this.accurate ? 1 : 0; diff --git a/cocos/render-scene/scene/light.ts b/cocos/render-scene/scene/light.ts index 1fdabf24e39..e3220a0094d 100644 --- a/cocos/render-scene/scene/light.ts +++ b/cocos/render-scene/scene/light.ts @@ -29,7 +29,7 @@ import { Node } from '../../scene-graph'; import { CAMERA_DEFAULT_MASK } from '../../rendering/define'; // Color temperature (in Kelvin) to RGB -export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { +export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number): void { if (kelvin < 1000.0) { kelvin = 1000.0; } else if (kelvin > 15000.0) { @@ -68,7 +68,7 @@ export enum LightType { UNKNOWN, } -export const nt2lm = (size: number) => 4 * Math.PI * Math.PI * size * size; +export const nt2lm = (size: number): number => 4 * Math.PI * Math.PI * size * size; /** * @en The abstract light class of the render scene @@ -79,7 +79,7 @@ export class Light { * @en Whether it's a baked light source, baked light will be ignored in real time lighting pass * @zh 是否是烘焙光源,烘焙光源会在实时光照计算中被忽略 */ - get baked () { + get baked (): boolean { return this._baked; } @@ -162,7 +162,7 @@ export class Light { * @en The node which owns the light source * @zh 光源归属的节点 */ - get node () { + get node (): Node | null { return this._node; } @@ -178,7 +178,7 @@ export class Light { * @en The name of the light source * @zh 光源的名字 */ - get name () { + get name (): string | null { return this._name; } @@ -190,7 +190,7 @@ export class Light { * @en The render scene which owns the current light * @zh 光源所属的渲染场景 */ - get scene () { + get scene (): RenderScene | null { return this._scene; } @@ -216,7 +216,7 @@ export class Light { protected _visibility = CAMERA_DEFAULT_MASK; - public initialize () { + public initialize (): void { this.color = new Vec3(1, 1, 1); this.colorTemperature = 6550.0; } @@ -226,7 +226,7 @@ export class Light { * @zh 将光源挂载到渲染场景上 * @param scene @en The render scene @zh 渲染场景 */ - public attachToScene (scene: RenderScene) { + public attachToScene (scene: RenderScene): void { this._scene = scene; } @@ -234,14 +234,14 @@ export class Light { * @en Detach the light from the render scene * @zh 将光源从渲染场景上移除 */ - public detachFromScene () { + public detachFromScene (): void { this._scene = null; } - public destroy () { + public destroy (): void { this._name = null; this._node = null; } - public update () {} + public update (): void {} } diff --git a/cocos/render-scene/scene/lod-group.ts b/cocos/render-scene/scene/lod-group.ts index 3a238597f20..4f09a8a7631 100644 --- a/cocos/render-scene/scene/lod-group.ts +++ b/cocos/render-scene/scene/lod-group.ts @@ -41,18 +41,18 @@ export class LODData { return this._models; } - public addModel (model: Model) { + public addModel (model: Model): void { this._models.splice(0, 0, model); } - public eraseModel (model: Model) { + public eraseModel (model: Model): void { const removeIndex = this._models.indexOf(model); if (removeIndex >= 0) { this._models.splice(removeIndex, 1); } } - public clearModels () { + public clearModels (): void { this._models.length = 0; } } @@ -96,24 +96,24 @@ export class LODGroup { get localBoundaryCenter (): Readonly { return this._localBoundaryCenter.clone(); } - get lodCount () { return this._lodDataArray.length; } + get lodCount (): number { return this._lodDataArray.length; } set objectSize (val: number) { this._objectSize = val; } - get objectSize () { return this._objectSize; } + get objectSize (): number { return this._objectSize; } get lodDataArray (): readonly LODData[] { return this._lodDataArray; } - attachToScene (scene: RenderScene) { + attachToScene (scene: RenderScene): void { this.scene = scene; } - detachFromScene () { + detachFromScene (): void { this.scene = null!; } - lockLODLevels (lockLev: number[]) { + lockLODLevels (lockLev: number[]): void { if (lockLev.length !== this._lockedLODLevelVec.length) { this._isLockLevelChanged = true; } else { @@ -133,7 +133,7 @@ export class LODGroup { return this._isLockLevelChanged; } - resetLockChangeFlag () { + resetLockChangeFlag (): void { this._isLockLevelChanged = false; } @@ -141,19 +141,19 @@ export class LODGroup { return this._lockedLODLevelVec; } - clearLODs () { + clearLODs (): void { this._lodDataArray.length = 0; } - insertLOD (index: number, lod: LODData) { + insertLOD (index: number, lod: LODData): void { this._lodDataArray.splice(index, 0, lod); } - updateLOD (index: number, lod: LODData) { + updateLOD (index: number, lod: LODData): void { this._lodDataArray[index] = lod; } - eraseLOD (index: number) { + eraseLOD (index: number): void { this._lodDataArray.splice(index, 1); } diff --git a/cocos/render-scene/scene/model.ts b/cocos/render-scene/scene/model.ts index d9baf293260..3cc86fb88f6 100644 --- a/cocos/render-scene/scene/model.ts +++ b/cocos/render-scene/scene/model.ts @@ -110,7 +110,7 @@ export class Model { * @en Sub models of the current model * @zh 获取所有子模型 */ - get subModels () { + get subModels (): SubModel[] { return this._subModels; } @@ -126,7 +126,7 @@ export class Model { * @en The axis-aligned bounding box of the model in the world space * @zh 获取世界空间包围盒 */ - get worldBounds () { + get worldBounds (): geometry.AABB | null { return this._worldBounds; } @@ -134,7 +134,7 @@ export class Model { * @en The axis-aligned bounding box of the model in the model space * @zh 获取模型空间包围盒 */ - get modelBounds () { + get modelBounds (): geometry.AABB | null { return this._modelBounds; } @@ -142,7 +142,7 @@ export class Model { * @en The ubo buffer of the model * @zh 获取模型的 ubo 缓冲 */ - get localBuffer () { + get localBuffer (): Buffer | null { return this._localBuffer; } @@ -150,7 +150,7 @@ export class Model { * @en The SH ubo buffer of the model * @zh 获取模型的球谐 ubo 缓冲 */ - get localSHBuffer () { + get localSHBuffer (): Buffer | null { return this._localSHBuffer; } @@ -158,7 +158,7 @@ export class Model { * @en The world bound ubo buffer * @zh 获取世界包围盒 ubo 缓冲 */ - get worldBoundBuffer () { + get worldBoundBuffer (): Buffer | null { return this._worldBoundBuffer; } @@ -166,7 +166,7 @@ export class Model { * @en The time stamp of last update * @zh 获取上次更新时间戳 */ - get updateStamp () { + get updateStamp (): number { return this._updateStamp; } @@ -174,7 +174,7 @@ export class Model { * @en Use LightProbe or not * @zh 光照探针开关 */ - get useLightProbe () { + get useLightProbe (): boolean { return this._useLightProbe; } @@ -187,7 +187,7 @@ export class Model { * @en located tetrahedron index * @zh 模型所处的四面体索引 */ - get tetrahedronIndex () { + get tetrahedronIndex (): number { return this._tetrahedronIndex; } @@ -199,7 +199,7 @@ export class Model { * @en Model level shadow bias * @zh 阴影偏移值 */ - get shadowBias () { + get shadowBias (): number { return this._shadowBias; } @@ -211,7 +211,7 @@ export class Model { * @en Model level shadow normal bias * @zh 阴影法线偏移值 */ - get shadowNormalBias () { + get shadowNormalBias (): number { return this._shadowNormalBias; } @@ -223,7 +223,7 @@ export class Model { * @en Whether the model should receive shadow * @zh 是否接收阴影 */ - get receiveShadow () { + get receiveShadow (): boolean { return this._receiveShadow; } @@ -236,7 +236,7 @@ export class Model { * @en Whether the model should cast shadow * @zh 是否投射阴影 */ - get castShadow () { + get castShadow (): boolean { return this._castShadow; } @@ -323,7 +323,7 @@ export class Model { * @en Whether the model can be render by the reflection probe * @zh 模型是否能被反射探针渲染 */ - get bakeToReflectionProbe () { + get bakeToReflectionProbe (): boolean { return this._bakeToReflectionProbe; } @@ -335,7 +335,7 @@ export class Model { * @en Reflection probe type * @zh 反射探针类型。 */ - get reflectionProbeType () { + get reflectionProbeType (): ReflectionProbeType { return this._reflectionProbeType; } @@ -352,7 +352,7 @@ export class Model { * @en sets or gets reflection probe id * @zh 设置或获取反射探针id。 */ - get reflectionProbeId () { + get reflectionProbeId (): number { return this._reflectionProbeId; } @@ -364,7 +364,7 @@ export class Model { * @en Sets or gets the reflection probe id for blend. * @zh 设置或获取用于混合的反射探针id。 */ - get reflectionProbeBlendId () { + get reflectionProbeBlendId (): number { return this._reflectionProbeBlendId; } @@ -376,7 +376,7 @@ export class Model { * @en Sets or gets the reflection probe blend weight. * @zh 设置或获取反射探针混合权重。 */ - get reflectionProbeBlendWeight () { + get reflectionProbeBlendWeight (): number { return this._reflectionProbeBlendWeight; } @@ -600,7 +600,7 @@ export class Model { * @en Initialize the model * @zh 初始化模型 */ - public initialize () { + public initialize (): void { if (this._inited) { return; } @@ -617,7 +617,7 @@ export class Model { * @en Destroy the model * @zh 销毁模型 */ - public destroy () { + public destroy (): void { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { this._subModels[i].destroy(); @@ -649,7 +649,7 @@ export class Model { * @zh 添加模型到渲染场景 [[renderer.RenderScene]] 中 * @param scene destination scene */ - public attachToScene (scene: RenderScene) { + public attachToScene (scene: RenderScene): void { this.scene = scene; this._localDataUpdated = true; } @@ -658,7 +658,7 @@ export class Model { * @en Detach the model from its render scene * @zh 移除场景中的模型 */ - public detachFromScene () { + public detachFromScene (): void { this.scene = null; } @@ -667,7 +667,7 @@ export class Model { * @zh 更新模型的变换 * @param stamp time stamp */ - public updateTransform (stamp: number) { + public updateTransform (stamp: number): void { const node = this.transform; if (node.hasChangedFlags || node.isTransformDirty()) { node.updateWorldTransform(); @@ -683,7 +683,7 @@ export class Model { * @en Update the model's world AABB * @zh 更新模型的世界空间包围盒 */ - public updateWorldBound () { + public updateWorldBound (): void { const node = this.transform; if (node !== null) { node.updateWorldTransform(); @@ -700,7 +700,7 @@ export class Model { * @zh 更新模型的 ubo * @param stamp time stamp */ - public updateUBOs (stamp: number) { + public updateUBOs (stamp: number): void { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { subModels[i].update(); @@ -735,11 +735,11 @@ export class Model { } } - public showTetrahedron () { + public showTetrahedron (): boolean { return this.isLightProbeAvailable(); } - private isLightProbeAvailable () { + private isLightProbeAvailable (): boolean { if (!this._useLightProbe) { return false; } @@ -756,7 +756,7 @@ export class Model { return true; } - private updateSHBuffer () { + private updateSHBuffer (): void { if (!this._localSHData) { return; } @@ -782,7 +782,7 @@ export class Model { * @en Clear the model's SH ubo * @zh 清除模型的球谐 ubo */ - public clearSHUBOs () { + public clearSHUBOs (): void { if (!this._localSHData) { return; } @@ -798,7 +798,7 @@ export class Model { * @en Update the model's SH ubo * @zh 更新模型的球谐 ubo */ - public updateSHUBOs () { + public updateSHUBOs (): void { if (!this.isLightProbeAvailable()) { return; } @@ -834,7 +834,7 @@ export class Model { * @param minPos min position of the AABB * @param maxPos max position of the AABB */ - public createBoundingShape (minPos?: Vec3, maxPos?: Vec3) { + public createBoundingShape (minPos?: Vec3, maxPos?: Vec3): void { if (!minPos || !maxPos) { return; } if (!this._modelBounds) { this._modelBounds = geometry.AABB.create(); } if (!this._worldBounds) { this._worldBounds = geometry.AABB.create(); } @@ -842,7 +842,7 @@ export class Model { geometry.AABB.copy(this._worldBounds, this._modelBounds); } - private _createSubModel () { + private _createSubModel (): SubModel { return new SubModel(); } @@ -853,7 +853,7 @@ export class Model { * @param subMeshData sub mesh * @param mat sub material */ - public initSubModel (idx: number, subMeshData: RenderingSubMesh, mat: Material) { + public initSubModel (idx: number, subMeshData: RenderingSubMesh, mat: Material): void { this.initialize(); if (this._subModels[idx] == null) { @@ -872,7 +872,7 @@ export class Model { * @param idx sub model's index * @param subMesh sub mesh */ - public setSubModelMesh (idx: number, subMesh: RenderingSubMesh) { + public setSubModelMesh (idx: number, subMesh: RenderingSubMesh): void { if (!this._subModels[idx]) { return; } this._subModels[idx].subMesh = subMesh; } @@ -883,7 +883,7 @@ export class Model { * @param idx sub model's index * @param mat sub material */ - public setSubModelMaterial (idx: number, mat: Material) { + public setSubModelMaterial (idx: number, mat: Material): void { if (!this._subModels[idx]) { return; } this._subModels[idx].passes = mat.passes; this._updateAttributesAndBinding(idx); @@ -893,7 +893,7 @@ export class Model { * @en Pipeline changed callback * @zh 管线更新回调 */ - public onGlobalPipelineStateChanged () { + public onGlobalPipelineStateChanged (): void { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { subModels[i].onPipelineStateChanged(); @@ -904,14 +904,14 @@ export class Model { * @en Shader macro changed callback * @zh Shader 宏更新回调 */ - public onMacroPatchesStateChanged () { + public onMacroPatchesStateChanged (): void { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { subModels[i].onMacroPatchesStateChanged(this.getMacroPatches(i)); } } - public onGeometryChanged () { + public onGeometryChanged (): void { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { subModels[i].onGeometryChanged(); @@ -924,7 +924,7 @@ export class Model { * initialize lighting map info before model initializing * because the lighting map will influence the shader */ - public initLightingmap (texture: Texture2D | null, uvParam: Vec4) { + public initLightingmap (texture: Texture2D | null, uvParam: Vec4): void { this._lightmap = texture; this._lightmapUVParam = uvParam; } @@ -935,7 +935,7 @@ export class Model { * @param texture light map * @param uvParam uv coordinate */ - public updateLightingmap (texture: Texture2D | null, uvParam: Vec4) { + public updateLightingmap (texture: Texture2D | null, uvParam: Vec4): void { Vec4.toArray(this._localData, uvParam, UBOLocal.LIGHTINGMAP_UVPARAM); this._localDataUpdated = true; this._lightmap = texture; @@ -965,7 +965,7 @@ export class Model { * @zh 更新反射探针的立方体贴图 * @param texture probe cubemap */ - public updateReflectionProbeCubemap (texture: TextureCube | null) { + public updateReflectionProbeCubemap (texture: TextureCube | null): void { this._localDataUpdated = true; this.onMacroPatchesStateChanged(); @@ -993,7 +993,7 @@ export class Model { * @zh 更新用于blend的反射探针立方体贴图 * @param texture probe cubemap */ - public updateReflectionProbeBlendCubemap (texture: TextureCube | null) { + public updateReflectionProbeBlendCubemap (texture: TextureCube | null): void { this._localDataUpdated = true; this.onMacroPatchesStateChanged(); @@ -1021,7 +1021,7 @@ export class Model { * @zh 更新反射探针的平面反射贴图 * @param texture planar relflection map */ - public updateReflectionProbePlanarMap (texture: Texture | null) { + public updateReflectionProbePlanarMap (texture: Texture | null): void { this._localDataUpdated = true; this.onMacroPatchesStateChanged(); @@ -1054,7 +1054,7 @@ export class Model { * @zh 更新反射探针的数据贴图 * @param texture data map */ - public updateReflectionProbeDataMap (texture: Texture2D | null) { + public updateReflectionProbeDataMap (texture: Texture2D | null): void { this._localDataUpdated = true; this.onMacroPatchesStateChanged(); @@ -1079,7 +1079,7 @@ export class Model { * @en Update the shadow bias * @zh 更新阴影偏移 */ - public updateLocalShadowBias () { + public updateLocalShadowBias (): void { const sv = this._localData; sv[UBOLocal.LOCAL_SHADOW_BIAS + 0] = this._shadowBias; sv[UBOLocal.LOCAL_SHADOW_BIAS + 1] = this._shadowNormalBias; @@ -1090,7 +1090,7 @@ export class Model { * @en Update the id of reflection probe * @zh 更新物体使用哪个反射探针 */ - public updateReflectionProbeId () { + public updateReflectionProbeId (): void { const sv = this._localData; sv[UBOLocal.LOCAL_SHADOW_BIAS + 2] = this._reflectionProbeId; sv[UBOLocal.LOCAL_SHADOW_BIAS + 3] = this._reflectionProbeBlendId; @@ -1181,7 +1181,7 @@ export class Model { return patches; } - protected _updateAttributesAndBinding (subModelIndex: number) { + protected _updateAttributesAndBinding (subModelIndex: number): void { const subModel = this._subModels[subModelIndex]; if (!subModel) { return; } @@ -1214,12 +1214,12 @@ export class Model { // sub-classes can override the following functions if needed // for now no subModel level instancing attributes - protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel) { + protected _updateInstancedAttributes (attributes: Attribute[], subModel: SubModel): void { subModel.UpdateInstancedAttributes(attributes); this._localDataUpdated = true; } - protected _initLocalDescriptors (subModelIndex: number) { + protected _initLocalDescriptors (subModelIndex: number): void { if (!this._localBuffer) { this._localBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, @@ -1230,7 +1230,7 @@ export class Model { } } - protected _initLocalSHDescriptors (subModelIndex: number) { + protected _initLocalSHDescriptors (subModelIndex: number): void { if (!EDITOR && !this._useLightProbe) { return; } @@ -1249,7 +1249,7 @@ export class Model { } } - protected _initWorldBoundDescriptors (subModelIndex: number) { + protected _initWorldBoundDescriptors (subModelIndex: number): void { if (!this._worldBoundBuffer) { this._worldBoundBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, @@ -1260,15 +1260,15 @@ export class Model { } } - protected _updateLocalDescriptors (subModelIndex: number, descriptorSet: DescriptorSet) { + protected _updateLocalDescriptors (subModelIndex: number, descriptorSet: DescriptorSet): void { if (this._localBuffer) descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer); } - protected _updateLocalSHDescriptors (subModelIndex: number, descriptorSet: DescriptorSet) { + protected _updateLocalSHDescriptors (subModelIndex: number, descriptorSet: DescriptorSet): void { if (this._localSHBuffer) descriptorSet.bindBuffer(UBOSH.BINDING, this._localSHBuffer); } - protected _updateWorldBoundDescriptors (subModelIndex: number, descriptorSet: DescriptorSet) { + protected _updateWorldBoundDescriptors (subModelIndex: number, descriptorSet: DescriptorSet): void { if (this._worldBoundBuffer) descriptorSet.bindBuffer(UBOWorldBound.BINDING, this._worldBoundBuffer); } } diff --git a/cocos/render-scene/scene/octree.ts b/cocos/render-scene/scene/octree.ts index 8515e905b4f..783c0fadf91 100644 --- a/cocos/render-scene/scene/octree.ts +++ b/cocos/render-scene/scene/octree.ts @@ -80,7 +80,7 @@ export class Octree { protected _maxPos = new Vec3(0, 0, 0); protected _depth = 0; - public initialize (octreeInfo: OctreeInfo) { + public initialize (octreeInfo: OctreeInfo): void { this._enabled = octreeInfo.enabled; this._minPos = octreeInfo.minPos; this._maxPos = octreeInfo.maxPos; diff --git a/cocos/render-scene/scene/point-light.ts b/cocos/render-scene/scene/point-light.ts index b55a82d3119..37fbf127659 100644 --- a/cocos/render-scene/scene/point-light.ts +++ b/cocos/render-scene/scene/point-light.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { cclegacy, Vec3 } from '../../core'; +import { cclegacy, geometry, Vec3 } from '../../core'; import { AABB } from '../../core/geometry'; import { Light, LightType, nt2lm } from './light'; @@ -79,7 +79,7 @@ export class PointLight extends Light { * @en The luminance of the light source in HDR mode. * @zh HDR 模式下光源的亮度。 */ - get luminanceHDR () { + get luminanceHDR (): number { return this._luminanceHDR; } set luminanceHDR (value: number) { @@ -98,7 +98,7 @@ export class PointLight extends Light { * @en The AABB bounding box of the lighting area. * @zh 受光源影响范围的 AABB 包围盒。 */ - get aabb () { + get aabb (): geometry.AABB { return this._aabb; } @@ -116,7 +116,7 @@ export class PointLight extends Light { this._type = LightType.POINT; } - public initialize () { + public initialize (): void { super.initialize(); this.range = 1.0; @@ -128,7 +128,7 @@ export class PointLight extends Light { * @en Update the lighting area. * @zh 更新光源影响范围。 */ - public update () { + public update (): void { if (this._node && (this._node.hasChangedFlags || this._needUpdate)) { this._node.getWorldPosition(this._pos); const range = this._range; diff --git a/cocos/render-scene/scene/ranged-directional-light.ts b/cocos/render-scene/scene/ranged-directional-light.ts index 890c30154c7..121e6fb7d37 100644 --- a/cocos/render-scene/scene/ranged-directional-light.ts +++ b/cocos/render-scene/scene/ranged-directional-light.ts @@ -96,7 +96,7 @@ export class RangedDirectionalLight extends Light { * @en The illuminance of the light in HDR mode * @zh HDR 模式下光源的辐照度 */ - get illuminanceHDR () { + get illuminanceHDR (): number { return this._illuminanceHDR; } set illuminanceHDR (value: number) { @@ -107,7 +107,7 @@ export class RangedDirectionalLight extends Light { * @en The illuminance of the light in LDR mode * @zh LDR 模式下光源的辐照度 */ - get illuminanceLDR () { + get illuminanceLDR (): number { return this._illuminanceLDR; } set illuminanceLDR (value: number) { @@ -119,7 +119,7 @@ export class RangedDirectionalLight extends Light { this._type = LightType.RANGED_DIRECTIONAL; } - public initialize () { + public initialize (): void { super.initialize(); this.illuminance = Ambient.SUN_ILLUM; @@ -129,7 +129,7 @@ export class RangedDirectionalLight extends Light { * @en Update * @zh 更新 */ - public update () { + public update (): void { if (this._node && this._node.hasChangedFlags) { this._node.getWorldPosition(this._pos); this._node.getWorldScale(this._scale); diff --git a/cocos/render-scene/scene/reflection-probe.ts b/cocos/render-scene/scene/reflection-probe.ts index d363b7e1653..ea7a32e481c 100644 --- a/cocos/render-scene/scene/reflection-probe.ts +++ b/cocos/render-scene/scene/reflection-probe.ts @@ -128,11 +128,11 @@ export class ReflectionProbe { set probeType (value: number) { this._probeType = value; } - get probeType () { + get probeType (): number { return this._probeType; } - get resolution () { + get resolution (): number { return this._resolution; } @@ -142,7 +142,7 @@ export class ReflectionProbe { */ set resolution (value: number) { if (value !== this._resolution) { - this.bakedCubeTextures.forEach((rt, idx) => { + this.bakedCubeTextures.forEach((rt, idx): void => { rt.resize(value, value); }); } @@ -157,7 +157,7 @@ export class ReflectionProbe { this._clearFlag = value; this.camera.clearFlag = this._clearFlag; } - get clearFlag () { + get clearFlag (): number { return this._clearFlag; } @@ -169,14 +169,14 @@ export class ReflectionProbe { this._backgroundColor = val; this.camera.clearColor = this._backgroundColor; } - get backgroundColor () { + get backgroundColor (): Color { return this._backgroundColor; } /** * @en Visibility mask, declaring a set of node layers that will be visible to this camera. * @zh 可见性掩码,声明在当前相机中可见的节点层级集合。 */ - get visibility () { + get visibility (): number { return this._visibility; } set visibility (val) { @@ -194,7 +194,7 @@ export class ReflectionProbe { const pos = this.node.getWorldPosition(); geometry.AABB.set(this._boundingBox!, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); } - get size () { + get size (): Vec3 { return this._size; } @@ -202,7 +202,7 @@ export class ReflectionProbe { this._cubemap = val; } - get cubemap () { + get cubemap (): TextureCube | null { return this._cubemap!; } @@ -210,11 +210,11 @@ export class ReflectionProbe { * @en The node of the probe. * @zh probe绑定的节点 */ - get node () { + get node (): Node { return this._node!; } - get camera () { + get camera (): Camera { return this._camera!; } @@ -226,25 +226,25 @@ export class ReflectionProbe { this._needRefresh = value; } - get needRefresh () { + get needRefresh (): boolean { return this._needRefresh; } set needRender (value: boolean) { this._needRender = value; } - get needRender () { + get needRender (): boolean { return this._needRender; } - get boundingBox () { + get boundingBox (): geometry.AABB | null { return this._boundingBox; } set cameraNode (node: Node) { this._cameraNode = node; } - get cameraNode () { + get cameraNode (): Node { return this._cameraNode!; } @@ -257,7 +257,7 @@ export class ReflectionProbe { this._previewSphere = val; } - get previewSphere () { + get previewSphere (): Node | null { return this._previewSphere!; } @@ -269,7 +269,7 @@ export class ReflectionProbe { this._previewPlane = val; } - get previewPlane () { + get previewPlane (): Node { return this._previewPlane!; } @@ -277,7 +277,7 @@ export class ReflectionProbe { this._probeId = id; } - public initialize (node: Node, cameraNode: Node) { + public initialize (node: Node, cameraNode: Node): void { this._node = node; this._cameraNode = cameraNode; const pos = this.node.getWorldPosition(); @@ -285,7 +285,7 @@ export class ReflectionProbe { this._createCamera(cameraNode); } - public initBakedTextures () { + public initBakedTextures (): void { if (this.bakedCubeTextures.length === 0) { for (let i = 0; i < 6; i++) { const renderTexture = this._createTargetTexture(this._resolution, this._resolution); @@ -294,7 +294,7 @@ export class ReflectionProbe { } } - public captureCubemap () { + public captureCubemap (): void { this.initBakedTextures(); this._resetCameraParams(); this._needRender = true; @@ -305,7 +305,7 @@ export class ReflectionProbe { * @zh 渲染实时平面反射贴图 * @param sourceCamera render planar reflection for this camera */ - public renderPlanarReflection (sourceCamera: Camera) { + public renderPlanarReflection (sourceCamera: Camera): void { if (!sourceCamera) return; if (!this.realtimePlanarTexture) { const canvasSize = cclegacy.view.getDesignResolutionSize(); @@ -317,7 +317,7 @@ export class ReflectionProbe { this._needRender = true; } - public switchProbeType (type: number, sourceCamera: Camera | null) { + public switchProbeType (type: number, sourceCamera: Camera | null): void { if (type === ProbeType.CUBE) { this._needRender = false; } else if (sourceCamera !== null) { @@ -325,11 +325,11 @@ export class ReflectionProbe { } } - public getProbeId () { + public getProbeId (): number { return this._probeId; } - public updateProbeId (id) { + public updateProbeId (id): void { this._probeId = id; } @@ -341,15 +341,15 @@ export class ReflectionProbe { } } - public isFinishedRendering () { + public isFinishedRendering (): boolean { return true; } - public validate () { + public validate (): boolean { return this.cubemap !== null; } - public destroy () { + public destroy (): void { if (this._camera) { this._camera.destroy(); this._camera = null; @@ -364,17 +364,17 @@ export class ReflectionProbe { this.realtimePlanarTexture = null; } } - public enable () { + public enable (): void { } - public disable () { + public disable (): void { } - public updateCameraDir (faceIdx: number) { + public updateCameraDir (faceIdx: number): void { this.cameraNode.setRotationFromEuler(cameraDir[faceIdx]); this.camera.update(true); } - public updateBoundingBox () { + public updateBoundingBox (): void { if (this.node) { this.node.updateWorldTransform(); const pos = this.node.getWorldPosition(); @@ -382,7 +382,7 @@ export class ReflectionProbe { } } - public hasFrameBuffer (framebuffer: Framebuffer) { + public hasFrameBuffer (framebuffer: Framebuffer): boolean { if (this.probeType === ProbeType.PLANAR) { if (!this.realtimePlanarTexture) return false; if (this.realtimePlanarTexture.window?.framebuffer === framebuffer) { @@ -405,7 +405,7 @@ export class ReflectionProbe { return true; } - private _syncCameraParams (camera: Camera) { + private _syncCameraParams (camera: Camera): void { this.camera.projectionType = camera.projectionType; this.camera.orthoHeight = camera.orthoHeight; this.camera.nearClip = camera.nearClip; @@ -418,7 +418,7 @@ export class ReflectionProbe { this.camera.resize(camera.width, camera.height); } - private _createCamera (cameraNode: Node) { + private _createCamera (cameraNode: Node): Camera | null { const root = cclegacy.director.root; if (!this._camera) { this._camera = (cclegacy.director.root).createCamera(); @@ -451,7 +451,7 @@ export class ReflectionProbe { return this._camera; } - private _resetCameraParams () { + private _resetCameraParams (): void { this.camera.projectionType = CameraProjection.PERSPECTIVE; this.camera.orthoHeight = 10; this.camera.nearClip = 1; @@ -469,13 +469,13 @@ export class ReflectionProbe { this.camera.update(true); } - private _createTargetTexture (width: number, height: number) { + private _createTargetTexture (width: number, height: number): RenderTexture { const rt = new RenderTexture(); rt.reset({ width, height }); return rt; } - private _transformReflectionCamera (sourceCamera: Camera) { + private _transformReflectionCamera (sourceCamera: Camera): void { const offset = Vec3.dot(this.node.worldPosition, this.node.up); this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset); this.cameraNode.worldPosition = this._cameraWorldPos; @@ -501,7 +501,7 @@ export class ReflectionProbe { this.camera.calculateObliqueMat(viewSpaceProbe); } - private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number) { + private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 { const n = Vec3.clone(normal); n.normalize(); const dist = Vec3.dot(n, point) - offset; diff --git a/cocos/render-scene/scene/shadows.ts b/cocos/render-scene/scene/shadows.ts index 51afd895d72..0b7bce976d9 100644 --- a/cocos/render-scene/scene/shadows.ts +++ b/cocos/render-scene/scene/shadows.ts @@ -293,7 +293,7 @@ export class Shadows { * @en The transform matrix of the light source * @zh 光源的变换矩阵 */ - public get matLight () { + public get matLight (): Mat4 { return this._matLight; } @@ -369,7 +369,7 @@ export class Shadows { return passes.length > 0 ? passes[0].getShaderVariant(patches) : null; } - public initialize (shadowsInfo: ShadowsInfo) { + public initialize (shadowsInfo: ShadowsInfo): void { this._enabled = shadowsInfo.enabled; this._type = this.enabled ? shadowsInfo.type : SHADOW_TYPE_NONE; @@ -383,7 +383,7 @@ export class Shadows { } } - public activate () { + public activate (): void { if (this._enabled) { if (this.type === ShadowType.Planar) { this._updatePlanarInfo(); @@ -401,7 +401,7 @@ export class Shadows { } } - protected _updatePlanarInfo () { + protected _updatePlanarInfo (): void { if (!this._material) { this._material = new Material(); this._material.initialize({ effectName: 'pipeline/planar-shadow' }); @@ -416,7 +416,7 @@ export class Shadows { root.onGlobalPipelineStateChanged(); } - public destroy () { + public destroy (): void { if (this._material) { this._material.destroy(); } diff --git a/cocos/render-scene/scene/skin.ts b/cocos/render-scene/scene/skin.ts index 43014d8e53c..3b96ec5d63b 100644 --- a/cocos/render-scene/scene/skin.ts +++ b/cocos/render-scene/scene/skin.ts @@ -68,7 +68,7 @@ export class Skin { protected _blurRadius = 0.01; protected _sssIntensity = 3.0; - public initialize (skinInfo: SkinInfo) { + public initialize (skinInfo: SkinInfo): void { this._enabled = skinInfo.enabled; this._blurRadius = skinInfo.blurRadius; this._sssIntensity = skinInfo.sssIntensity; diff --git a/cocos/render-scene/scene/skybox.ts b/cocos/render-scene/scene/skybox.ts index 4b33751ba6f..2d8b6da60f7 100644 --- a/cocos/render-scene/scene/skybox.ts +++ b/cocos/render-scene/scene/skybox.ts @@ -209,7 +209,7 @@ export class Skybox { } } - get editableMaterial () { + get editableMaterial (): MaterialInstance | null { return this._editableMaterial; } @@ -230,7 +230,7 @@ export class Skybox { protected _reflectionLDR: TextureCube | null = null; protected _rotationAngle = 0; - public initialize (skyboxInfo: SkyboxInfo) { + public initialize (skyboxInfo: SkyboxInfo): void { this._activated = false; this._enabled = skyboxInfo.enabled; this._useIBL = skyboxInfo.useIBL; @@ -244,7 +244,7 @@ export class Skybox { * @param envmapHDR @en Environment map for HDR mode @zh HDR 模式下的环境贴图 * @param envmapLDR @en Environment map for LDR mode @zh LDR 模式下的环境贴图 */ - public setEnvMaps (envmapHDR: TextureCube | null, envmapLDR: TextureCube | null) { + public setEnvMaps (envmapHDR: TextureCube | null, envmapLDR: TextureCube | null): void { this._envmapHDR = envmapHDR; this._envmapLDR = envmapLDR; @@ -258,7 +258,7 @@ export class Skybox { * @param diffuseMapHDR @en Diffuse map for HDR mode @zh HDR 模式下的漫反射贴图 * @param diffuseMapLDR @en Diffuse map for LDR mode @zh LDR 模式下的漫反射贴图 */ - public setDiffuseMaps (diffuseMapHDR: TextureCube | null, diffuseMapLDR: TextureCube | null) { + public setDiffuseMaps (diffuseMapHDR: TextureCube | null, diffuseMapLDR: TextureCube | null): void { this._diffuseMapHDR = diffuseMapHDR; this._diffuseMapLDR = diffuseMapLDR; this._updateGlobalBinding(); @@ -270,7 +270,7 @@ export class Skybox { * @zh 设置自定义的天空盒材质 * @param skyboxMat @en Skybox material @zh 天空盒材质 */ - public setSkyboxMaterial (skyboxMat: Material | null) { + public setSkyboxMaterial (skyboxMat: Material | null): void { if (skyboxMat) { this._editableMaterial = new MaterialInstance({ parent: skyboxMat }); this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); @@ -286,7 +286,7 @@ export class Skybox { * @param reflectionHDR @en Reflection convolution map for HDR mode @zh HDR 模式下的反射卷积图 * @param reflectionLDR @en Reflection convolution map for LDR mode @zh LDR 模式下的反射卷积图 */ - public setReflectionMaps (reflectionHDR: TextureCube | null, reflectionLDR: TextureCube | null) { + public setReflectionMaps (reflectionHDR: TextureCube | null, reflectionLDR: TextureCube | null): void { this._reflectionHDR = reflectionHDR; this._reflectionLDR = reflectionLDR; this._updateGlobalBinding(); @@ -298,20 +298,20 @@ export class Skybox { * @zh 设置天空盒旋转角度 * @param angle @en rotation angle @zh 旋转角度 */ - public setRotationAngle (angle: number) { + public setRotationAngle (angle: number): void { this._rotationAngle = angle; } - public getRotationAngle () { + public getRotationAngle (): number { return this._rotationAngle; } - public updateMaterialRenderInfo () { + public updateMaterialRenderInfo (): void { this._updateGlobalBinding(); this._updatePipeline(); } - public activate () { + public activate (): void { const pipeline = cclegacy.director.root.pipeline; this._globalDSManager = pipeline.globalDSManager; this._default = builtinResMgr.get('default-cube-texture'); @@ -360,7 +360,7 @@ export class Skybox { this._activated = true; } - protected _updatePipeline () { + protected _updatePipeline (): void { const root = cclegacy.director.root as Root; const pipeline = root.pipeline; @@ -397,7 +397,7 @@ export class Skybox { } } - protected _updateGlobalBinding () { + protected _updateGlobalBinding (): void { if (this._globalDSManager) { const device = deviceManager.gfxDevice; if (this.reflectionMap) { @@ -427,7 +427,7 @@ export class Skybox { } } - protected _updateSubModes () { + protected _updateSubModes (): void { if (this._model) { const subModels = this._model.subModels; for (let i = 0; i < subModels.length; i++) { diff --git a/cocos/render-scene/scene/sphere-light.ts b/cocos/render-scene/scene/sphere-light.ts index 41c95e37917..22f7bb52c7e 100644 --- a/cocos/render-scene/scene/sphere-light.ts +++ b/cocos/render-scene/scene/sphere-light.ts @@ -35,7 +35,7 @@ export class SphereLight extends Light { * @en The world position of the light source * @zh 光源中心点的世界坐标 */ - get position () { + get position (): Vec3 { return this._pos; } @@ -90,7 +90,7 @@ export class SphereLight extends Light { * @en The luminance of the light source in HDR mode * @zh HDR 模式下光源的亮度 */ - get luminanceHDR () { + get luminanceHDR (): number { return this._luminanceHDR; } set luminanceHDR (value: number) { @@ -109,7 +109,7 @@ export class SphereLight extends Light { * @en The AABB bounding box of the lighting area * @zh 受光源影响范围的 AABB 包围盒 */ - get aabb () { + get aabb (): geometry.AABB { return this._aabb; } @@ -128,7 +128,7 @@ export class SphereLight extends Light { this._type = LightType.SPHERE; } - public initialize () { + public initialize (): void { super.initialize(); const size = 0.15; @@ -142,7 +142,7 @@ export class SphereLight extends Light { * @en Update the lighting area * @zh 更新光源影响范围 */ - public update () { + public update (): void { if (this._node && (this._node.hasChangedFlags || this._needUpdate)) { this._node.getWorldPosition(this._pos); const range = this._range; diff --git a/cocos/render-scene/scene/spot-light.ts b/cocos/render-scene/scene/spot-light.ts index 1c6b9498dc6..21cb28177cf 100644 --- a/cocos/render-scene/scene/spot-light.ts +++ b/cocos/render-scene/scene/spot-light.ts @@ -23,6 +23,7 @@ */ import { Mat4, Quat, Vec3, geometry, cclegacy } from '../../core'; +import type { Frustum } from '../../core/geometry'; import { Light, LightType, nt2lm } from './light'; import { PCFType } from './shadows'; @@ -74,7 +75,7 @@ export class SpotLight extends Light { * @en The world position of the light source * @zh 光源的世界坐标 */ - get position () { + get position (): Vec3 { return this._pos; } @@ -129,7 +130,7 @@ export class SpotLight extends Light { * @en The luminance of the light source in HDR mode * @zh HDR 模式下光源的亮度 */ - get luminanceHDR () { + get luminanceHDR (): number { return this._luminanceHDR; } set luminanceHDR (value: number) { @@ -140,7 +141,7 @@ export class SpotLight extends Light { * @en The luminance of the light source in LDR mode * @zh LDR 模式下光源的亮度 */ - get luminanceLDR () { + get luminanceLDR (): number { return this._luminanceLDR; } set luminanceLDR (value: number) { @@ -163,7 +164,7 @@ export class SpotLight extends Light { * 由于这种不一致性,请不要使用这个属性。 * @internal */ - get spotAngle () { + get spotAngle (): number { return this._spotAngle; } set spotAngle (val: number) { @@ -177,11 +178,11 @@ export class SpotLight extends Light { * @en The cone angle of the lighting area * @zh 聚光灯锥角 */ - get angle () { + get angle (): number { return this._angle; } - get aabb () { + get aabb (): geometry.AABB { return this._aabb; } @@ -189,7 +190,7 @@ export class SpotLight extends Light { * @en The frustum of the lighting area * @zh 受光源影响范围的截椎体 */ - get frustum () { + get frustum (): Frustum { return this._frustum; } @@ -197,7 +198,7 @@ export class SpotLight extends Light { * @en Whether shadow casting is enabled * @zh 是否启用阴影? */ - get shadowEnabled () { + get shadowEnabled (): boolean { return this._shadowEnabled; } set shadowEnabled (val) { @@ -208,7 +209,7 @@ export class SpotLight extends Light { * @en The pcf level of the shadow generation. * @zh 获取或者设置阴影 pcf 等级。 */ - get shadowPcf () { + get shadowPcf (): number { return this._shadowPcf; } set shadowPcf (val) { @@ -219,7 +220,7 @@ export class SpotLight extends Light { * @en The depth offset of shadow to avoid moire pattern artifacts * @zh 阴影的深度偏移, 可以减弱跨像素导致的条纹状失真 */ - get shadowBias () { + get shadowBias (): number { return this._shadowBias; } set shadowBias (val) { @@ -230,7 +231,7 @@ export class SpotLight extends Light { * @en The normal bias of the shadow map. * @zh 设置或者获取法线偏移。 */ - get shadowNormalBias () { + get shadowNormalBias (): number { return this._shadowNormalBias; } set shadowNormalBias (val: number) { @@ -245,7 +246,7 @@ export class SpotLight extends Light { this._type = LightType.SPOT; } - public initialize () { + public initialize (): void { super.initialize(); const size = 0.15; @@ -256,7 +257,7 @@ export class SpotLight extends Light { this._dir.set(new Vec3(1.0, -1.0, -1.0)); } - public update () { + public update (): void { if (this._node && (this._node.hasChangedFlags || this._needUpdate)) { this._node.getWorldPosition(this._pos); Vec3.transformQuat(this._dir, _forward, this._node.getWorldRotation(_qt)); diff --git a/cocos/render-scene/scene/submodel.ts b/cocos/render-scene/scene/submodel.ts index 7015ad92d88..f2533ed7c26 100644 --- a/cocos/render-scene/scene/submodel.ts +++ b/cocos/render-scene/scene/submodel.ts @@ -167,7 +167,7 @@ export class SubModel { * @en The instance attribute block, access by sub model * @zh 硬件实例化属性,通过子模型访问 */ - get instancedAttributeBlock () { + get instancedAttributeBlock (): IInstancedAttributeBlock { return this._instancedAttributeBlock; } @@ -178,7 +178,7 @@ export class SubModel { set instancedWorldMatrixIndex (val: number) { this._instancedWorldMatrixIndex = val; } - get instancedWorldMatrixIndex () { + get instancedWorldMatrixIndex (): number { return this._instancedWorldMatrixIndex; } @@ -189,7 +189,7 @@ export class SubModel { set instancedSHIndex (val: number) { this._instancedSHIndex = val; } - get instancedSHIndex () { + get instancedSHIndex (): number { return this._instancedSHIndex; } @@ -200,7 +200,7 @@ export class SubModel { set useReflectionProbeType (val) { this._useReflectionProbeType = val; } - get useReflectionProbeType () { + get useReflectionProbeType (): number { return this._useReflectionProbeType; } @@ -383,7 +383,7 @@ export class SubModel { // to invoke getter/setter function for wasm object if (this._inputAssembler && drawInfo) { const dirtyDrawInfo = this._inputAssembler.drawInfo; - Object.keys(drawInfo).forEach((key) => { + Object.keys(drawInfo).forEach((key): void => { dirtyDrawInfo[key] = drawInfo[key]; }); this._inputAssembler.drawInfo = dirtyDrawInfo; @@ -399,7 +399,7 @@ export class SubModel { /** * @internal */ - public getInstancedAttributeIndex (name: string) { + public getInstancedAttributeIndex (name: string): number { const { attributes } = this.instancedAttributeBlock; for (let i = 0; i < attributes.length; i++) { if (attributes[i].name === name) { return i; } @@ -416,7 +416,7 @@ export class SubModel { /** * @internal */ - public updateInstancedWorldMatrix (mat: Mat4, idx: number) { + public updateInstancedWorldMatrix (mat: Mat4, idx: number): void { const attrs = this.instancedAttributeBlock.views; const v1 = attrs[idx]; const v2 = attrs[idx + 1]; @@ -435,7 +435,7 @@ export class SubModel { /** * @internal */ - public updateInstancedSH (data: Float32Array, idx: number) { + public updateInstancedSH (data: Float32Array, idx: number): void { const attrs = this.instancedAttributeBlock.views; const count = (UBOSH.SH_QUADRATIC_R_OFFSET - UBOSH.SH_LINEAR_CONST_R_OFFSET) / 4; let offset = 0; @@ -456,7 +456,7 @@ export class SubModel { /** * @internal */ - public UpdateInstancedAttributes (attributes: Attribute[]) { + public UpdateInstancedAttributes (attributes: Attribute[]): void { // initialize subModelWorldMatrixIndex this.instancedWorldMatrixIndex = -1; this.instancedSHIndex = -1; diff --git a/cocos/render-scene/utils.ts b/cocos/render-scene/utils.ts index 8c9b9fd62e9..7ed32973f1a 100644 --- a/cocos/render-scene/utils.ts +++ b/cocos/render-scene/utils.ts @@ -22,10 +22,10 @@ THE SOFTWARE. */ -import { Attribute, Buffer, BufferInfo, Device, InputAssemblerInfo, AttributeName, BufferUsageBit, Format, MemoryUsageBit } from '../gfx'; +import { Attribute, Buffer, BufferInfo, Device, InputAssemblerInfo, AttributeName, BufferUsageBit, Format, MemoryUsageBit, InputAssembler } from '../gfx'; import { IGeometry } from '../primitive/define'; -export function createIA (device: Device, data: IGeometry) { +export function createIA (device: Device, data: IGeometry): InputAssembler | null { if (!data.positions) { console.error('The data must have positions field'); return null; diff --git a/cocos/rendering/custom/builtin-pipelines.ts b/cocos/rendering/custom/builtin-pipelines.ts index 27353767c44..10216b63b21 100644 --- a/cocos/rendering/custom/builtin-pipelines.ts +++ b/cocos/rendering/custom/builtin-pipelines.ts @@ -47,11 +47,11 @@ export class ForwardPipelineBuilder implements PipelineBuilder { } } } - private initResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + private initResource (ppl: BasicPipeline, cameraInfo: CameraInfo): void { setupForwardRes(ppl, cameraInfo); if (EDITOR) setupReflectionProbeRes(ppl, cameraInfo); } - private updateResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + private updateResource (ppl: BasicPipeline, cameraInfo: CameraInfo): void { updateForwardRes(ppl, cameraInfo); if (EDITOR) updateReflectionProbeRes(ppl, cameraInfo); } @@ -85,7 +85,7 @@ export class DeferredPipelineBuilder implements PipelineBuilder { setupUIPass(ppl, info); } } - private initResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + private initResource (ppl: BasicPipeline, cameraInfo: CameraInfo): void { if (EDITOR) { setupForwardRes(ppl, cameraInfo); return; @@ -98,7 +98,7 @@ export class DeferredPipelineBuilder implements PipelineBuilder { setupUIRes(ppl, cameraInfo); } } - private updateResource (ppl: BasicPipeline, cameraInfo: CameraInfo) { + private updateResource (ppl: BasicPipeline, cameraInfo: CameraInfo): void { if (EDITOR) { updateForwardRes(ppl, cameraInfo); return; diff --git a/cocos/rendering/custom/compiler.ts b/cocos/rendering/custom/compiler.ts index d2ba1512fdf..d19d8e0459e 100644 --- a/cocos/rendering/custom/compiler.ts +++ b/cocos/rendering/custom/compiler.ts @@ -35,16 +35,16 @@ import { AccessType, RasterView, ComputeView, ResourceResidency, SceneFlags } fr let hashCode = 0; -function hashCombine (hash) { +function hashCombine (hash): void { hashCode ^= (hash >>> 0) + 0x9e3779b9 + (hashCode << 6) + (hashCode >> 2); } -function hashCombineNum (val: number) { +function hashCombineNum (val: number): void { const hash = 5381; hashCombine((hash * 33) ^ val); } -function hashCombineStr (str: string) { +function hashCombineStr (str: string): void { // DJB2 HASH let hash = 5381; for (let i = 0; i < str.length; i++) { @@ -52,7 +52,7 @@ function hashCombineStr (str: string) { } hashCombine(hash); } -function genHashValue (pass: RasterPass) { +function genHashValue (pass: RasterPass): void { hashCode = 0; for (const [name, raster] of pass.rasterViews) { hashCombineStr('raster'); @@ -136,7 +136,7 @@ class PassVisitor implements RenderGraphVisitor { return !!this.context.renderGraph.tryGetBlit(u); } - private _useResourceInfo (input: string, raster: RasterView) { + private _useResourceInfo (input: string, raster: RasterView): void { if (!DEBUG) { return; } @@ -187,7 +187,7 @@ class PassVisitor implements RenderGraphVisitor { } } - private _fetchValidPass () { + private _fetchValidPass (): void { const rg = this.context.renderGraph; const resContext = this.context.resourceContext; if (!DEBUG && rg.getValid(this.passID)) { @@ -266,7 +266,7 @@ class PassVisitor implements RenderGraphVisitor { this.sceneID = id; } } - rasterPass (pass: RasterPass) { + rasterPass (pass: RasterPass): void { // const rg = this.context.renderGraph; // Since the pass is valid, there is no need to continue traversing. // if (rg.getValid(this.passID)) { @@ -274,11 +274,11 @@ class PassVisitor implements RenderGraphVisitor { // } this._currPass = pass; } - rasterSubpass (value: RasterSubpass) {} - computeSubpass (value: ComputeSubpass) {} - compute (value: ComputePass) {} - resolve (value: ResolvePass) {} - copy (value: CopyPass) { + rasterSubpass (value: RasterSubpass): void {} + computeSubpass (value: ComputeSubpass): void {} + compute (value: ComputePass): void {} + resolve (value: ResolvePass): void {} + copy (value: CopyPass): void { const rg = context.renderGraph; if (rg.getValid(this.passID)) { return; @@ -299,18 +299,18 @@ class PassVisitor implements RenderGraphVisitor { } } } - move (value: MovePass) {} - raytrace (value: RaytracePass) {} - queue (value: RenderQueue) {} - scene (value: SceneData) { + move (value: MovePass): void {} + raytrace (value: RaytracePass): void {} + queue (value: RenderQueue): void {} + scene (value: SceneData): void { this._fetchValidPass(); } - blit (value: Blit) { + blit (value: Blit): void { this._fetchValidPass(); } - dispatch (value: Dispatch) {} - clear (value: ClearView[]) {} - viewport (value: Viewport) {} + dispatch (value: Dispatch): void {} + clear (value: ClearView[]): void {} + viewport (value: Viewport): void {} } class PassManagerVisitor extends DefaultVisitor { @@ -323,7 +323,7 @@ class PassManagerVisitor extends DefaultVisitor { this._resId = value; this._colorMap.colors.length = context.renderGraph.numVertices(); } - get resId () { + get resId (): number { return this._resId; } constructor (context: CompilerContext, resId: number) { @@ -333,9 +333,9 @@ class PassManagerVisitor extends DefaultVisitor { this._graphView = new ReferenceGraphView(context.renderGraph); this._colorMap = new VectorGraphColorMap(context.renderGraph.numVertices()); } - get graphView () { return this._graphView; } - get colorMap () { return this._colorMap; } - discoverVertex (u: number, gv: ReferenceGraphView) { + get graphView (): ReferenceGraphView { return this._graphView; } + get colorMap (): VectorGraphColorMap { return this._colorMap; } + discoverVertex (u: number, gv: ReferenceGraphView): void { const g = gv.g; this._passVisitor.applyID(u, this.resId); g.visitVertex(this._passVisitor, u); @@ -349,19 +349,19 @@ class ResourceVisitor implements ResourceGraphVisitor { constructor (context: CompilerContext) { this._context = context; } - managedBuffer (value: ManagedBuffer) { + managedBuffer (value: ManagedBuffer): void { // noop } - managedTexture (value: ManagedTexture) { + managedTexture (value: ManagedTexture): void { // noop } - managed (value: ManagedResource) { + managed (value: ManagedResource): void { this.dependency(); } - persistentBuffer (value: Buffer) { + persistentBuffer (value: Buffer): void { } - dependency () { + dependency (): void { if (!this._passManagerVis) { this._passManagerVis = new PassManagerVisitor(this._context, this.resID); } else { @@ -370,18 +370,18 @@ class ResourceVisitor implements ResourceGraphVisitor { depthFirstSearch(this._passManagerVis.graphView, this._passManagerVis, this._passManagerVis.colorMap); } - persistentTexture (value: Texture) { + persistentTexture (value: Texture): void { this.dependency(); } - framebuffer (value: Framebuffer) { + framebuffer (value: Framebuffer): void { this.dependency(); } - swapchain (value: RenderSwapchain) { + swapchain (value: RenderSwapchain): void { this.dependency(); } - formatView (value: FormatView) { + formatView (value: FormatView): void { } - subresourceView (value: SubresourceView) { + subresourceView (value: SubresourceView): void { } } @@ -395,7 +395,7 @@ class CompilerContext { set (pipeline: BasicPipeline, resGraph: ResourceGraph, renderGraph: RenderGraph, - layoutGraph: LayoutGraphData) { + layoutGraph: LayoutGraphData): void { this.pipeline = pipeline; this.resourceGraph = resGraph; this.renderGraph = renderGraph; @@ -427,7 +427,7 @@ export class Compiler { context.set(this._pipeline, this._resourceGraph, renderGraph, this._layoutGraph); this._visitor = new ResourceManagerVisitor(context); } - compile (rg: RenderGraph) { + compile (rg: RenderGraph): void { context.set(this._pipeline, this._resourceGraph, rg, this._layoutGraph); context.pipeline.resourceUses.length = 0; this._visitor.colorMap.colors.length = context.resourceGraph.numVertices(); @@ -443,7 +443,7 @@ export class Compiler { continue; } - const min = rasterArr.reduce((prev, current) => (prev < current ? prev : current)); + const min = rasterArr.reduce((prev, current): number => (prev < current ? prev : current)); const firstRaster = use.rasters.get(min)!; switch (trait.residency) { case ResourceResidency.PERSISTENT: @@ -457,10 +457,10 @@ export class Compiler { break; } const computeArr: number[] = Array.from(use.computes.keys()); - const max = rasterArr.reduce((prev, current) => (prev > current ? prev : current)); + const max = rasterArr.reduce((prev, current): number => (prev > current ? prev : current)); let maxCompute = -1; if (computeArr.length) { - maxCompute = computeArr.reduce((prev, current) => (prev > current ? prev : current)); + maxCompute = computeArr.reduce((prev, current): number => (prev > current ? prev : current)); } if (max > maxCompute) { const lastRaster = use.rasters.get(max)!; @@ -487,8 +487,8 @@ export class ResourceManagerVisitor extends DefaultVisitor { this._resourceGraph = context.resourceGraph; this._resVisitor = new ResourceVisitor(context); } - get colorMap () { return this._colorMap; } - discoverVertex (u: number, gv: ResourceGraph) { + get colorMap (): VectorGraphColorMap { return this._colorMap; } + discoverVertex (u: number, gv: ResourceGraph): void { const traits = this._resourceGraph.getTraits(u); if (traits.residency === ResourceResidency.MANAGED || traits.residency === ResourceResidency.MEMORYLESS) { diff --git a/cocos/rendering/custom/custom-pipeline.ts b/cocos/rendering/custom/custom-pipeline.ts index 0b1f22d0ee4..993f71c6b50 100644 --- a/cocos/rendering/custom/custom-pipeline.ts +++ b/cocos/rendering/custom/custom-pipeline.ts @@ -113,7 +113,7 @@ class SceneInfo { this.pipelineSceneData = pipelineSceneData; this.shadows = pipelineSceneData.shadows; } - public reset () { + public reset (): void { this.punctualLights.length = 0; this.spotLights.length = 0; } @@ -148,7 +148,7 @@ export class TestPipelineBuilder implements PipelineBuilder { // implementation private prepareSceneInfo (scene: Readonly, frustum: geometry.Frustum, - sceneInfo: SceneInfo) { + sceneInfo: SceneInfo): void { // clear scene info sceneInfo.reset(); // spot lights @@ -223,7 +223,7 @@ export class TestPipelineBuilder implements PipelineBuilder { this._windows.set(camera.window, info); return info; } - private initGameCamera (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number) { + private initGameCamera (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number): void { const device = ppl.device; // Main Target ppl.addRenderWindow(`Color${id}`, Format.BGRA8, width, height, camera.window); @@ -242,7 +242,7 @@ export class TestPipelineBuilder implements PipelineBuilder { ppl.addDepthStencil(`SpotLightShadowDepth${id}2`, Format.DEPTH_STENCIL, shadowSize.x, shadowSize.y); ppl.addDepthStencil(`SpotLightShadowDepth${id}3`, Format.DEPTH_STENCIL, shadowSize.x, shadowSize.y); } - private updateGameCamera (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number) { + private updateGameCamera (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number): void { // Main Target ppl.updateRenderWindow(`Color${id}`, camera.window); ppl.updateDepthStencil(`DepthStencil${id}`, width, height); @@ -261,7 +261,7 @@ export class TestPipelineBuilder implements PipelineBuilder { } private buildForwardTiled (ppl: BasicPipeline, camera: Camera, id: number, width: number, height: number, - sceneInfo: SceneInfo) { + sceneInfo: SceneInfo): void { assert(this._tiled); assert(camera.scene !== null); // init @@ -314,7 +314,7 @@ export class TestPipelineBuilder implements PipelineBuilder { .addSceneOfCamera(camera, new LightInfo(), SceneFlags.BLEND); } } - private buildCascadedShadowMapPass (ppl: BasicPipeline, id: number, light: DirectionalLight, camera: Camera) { + private buildCascadedShadowMapPass (ppl: BasicPipeline, id: number, light: DirectionalLight, camera: Camera): void { const width = this._sceneInfo.shadows.size.x; const height = this._sceneInfo.shadows.size.y; const pass = ppl.addRenderPass(width, height, 'default'); diff --git a/cocos/rendering/custom/debug.ts b/cocos/rendering/custom/debug.ts index 4db3a53ba78..5f5703289ea 100644 --- a/cocos/rendering/custom/debug.ts +++ b/cocos/rendering/custom/debug.ts @@ -38,13 +38,13 @@ class PrePrintVisitor implements RenderGraphVisitor { constructor (g: RenderGraph) { this.g = g; } - clear (value: ClearView[]) { + clear (value: ClearView[]): void { // do nothing } - viewport (value: Viewport) { + viewport (value: Viewport): void { // do nothing } - rasterPass (value: RasterPass) { + rasterPass (value: RasterPass): void { oss += `${space}width = ${value.width}\n`; oss += `${space}height = ${value.height}\n`; for (const rasterView of value.rasterViews) { @@ -54,14 +54,14 @@ class PrePrintVisitor implements RenderGraphVisitor { oss += `${space}"${computeView[0]}": ComputeView[]\n`; } } - rasterSubpass(value: RasterSubpass) {} - computeSubpass(value: ComputeSubpass) {} - compute (value: ComputePass) { + rasterSubpass(value: RasterSubpass): void {} + computeSubpass(value: ComputeSubpass): void {} + compute (value: ComputePass): void { for (const computeView of value.computeViews) { oss += `${space}"${computeView[0]}": ComputeView[]\n`; } } - copy (value: CopyPass) { + copy (value: CopyPass): void { if (value.copyPairs.length === 1) { const pair = value.copyPairs[0]; oss += `${space}source = "${pair.source}"\n`; @@ -87,7 +87,7 @@ class PrePrintVisitor implements RenderGraphVisitor { oss += ']\n'; } } - move (value: MovePass) { + move (value: MovePass): void { if (value.movePairs.length === 1) { const pair = value.movePairs[0]; oss += `${space}source = "${pair.source}"\n`; @@ -113,15 +113,15 @@ class PrePrintVisitor implements RenderGraphVisitor { oss += ']\n'; } } - raytrace (value: RaytracePass) { + raytrace (value: RaytracePass): void { for (const computeView of value.computeViews) { oss += `${space}"${computeView[0]}": ComputeView[]\n`; } } - queue (value: RenderQueue) { + queue (value: RenderQueue): void { oss += `${space}hint = ${getQueueHintName(value.hint)}\n`; } - scene (value: SceneData) { + scene (value: SceneData): void { oss += `${space}scenes = [`; let i = 0; for (const scene of value.scenes) { @@ -132,8 +132,8 @@ class PrePrintVisitor implements RenderGraphVisitor { } oss += ']\n'; } - blit (value: Blit) {} - dispatch (value: Dispatch) { + blit (value: Blit): void {} + dispatch (value: Dispatch): void { oss += `${space}material = "${value.material?.name}"\n`; oss += `${space}passID = "${value.passID}"\n`; oss += `${space}groupX = ${value.threadGroupCountX}\n`; @@ -147,29 +147,29 @@ class PostPrintVisitor implements RenderGraphVisitor { constructor (g: RenderGraph) { this.g = g; } - clear (value: ClearView[]) { + clear (value: ClearView[]): void { // do nothing } - viewport (value: Viewport) { + viewport (value: Viewport): void { // do nothing } - rasterPass (value: RasterPass) { + rasterPass (value: RasterPass): void { // post raster pass } - rasterSubpass(value: RasterSubpass) {} - computeSubpass(value: ComputeSubpass) {} - compute (value: ComputePass) {} - copy (value: CopyPass) {} - move (value: MovePass) {} - raytrace (value: RaytracePass) {} - queue (value: RenderQueue) { + rasterSubpass(value: RasterSubpass): void {} + computeSubpass(value: ComputeSubpass): void {} + compute (value: ComputePass): void {} + copy (value: CopyPass): void {} + move (value: MovePass): void {} + raytrace (value: RaytracePass): void {} + queue (value: RenderQueue): void { // collect scene results } - scene (value: SceneData) { + scene (value: SceneData): void { // scene command list finished } - blit (value: Blit) {} - dispatch (value: Dispatch) {} + blit (value: Blit): void {} + dispatch (value: Dispatch): void {} g: RenderGraph; } diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 28e4eca2bca..0ce86e7345a 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -56,11 +56,11 @@ export enum AntiAliasing { FXAAHQ, } -export function getRTFormatBeforeToneMapping (ppl: BasicPipeline) { +export function getRTFormatBeforeToneMapping (ppl: BasicPipeline): Format { const useFloatOutput = ppl.getMacroBool('CC_USE_FLOAT_OUTPUT'); return ppl.pipelineSceneData.isHDR && useFloatOutput && supportsRGBA16HalfFloatTexture(ppl.device) ? Format.RGBA16F : Format.RGBA8; } -function forceEnableFloatOutput (ppl: BasicPipeline) { +function forceEnableFloatOutput (ppl: BasicPipeline): void { if (ppl.pipelineSceneData.isHDR && !ppl.getMacroBool('CC_USE_FLOAT_OUTPUT')) { const supportFloatOutput = supportsRGBA16HalfFloatTexture(ppl.device); ppl.setMacroBool('CC_USE_FLOAT_OUTPUT', supportFloatOutput); @@ -68,7 +68,7 @@ function forceEnableFloatOutput (ppl: BasicPipeline) { } } -export function validPunctualLightsCulling (pipeline: BasicPipeline, camera: Camera) { +export function validPunctualLightsCulling (pipeline: BasicPipeline, camera: Camera): void { const sceneData = pipeline.pipelineSceneData; const validPunctualLights = sceneData.validPunctualLights; validPunctualLights.length = 0; @@ -122,7 +122,7 @@ export function validPunctualLightsCulling (pipeline: BasicPipeline, camera: Cam const _cameras: Camera[] = []; -export function getCameraUniqueID (camera: Camera) { +export function getCameraUniqueID (camera: Camera): number { if (!_cameras.includes(camera)) { _cameras.push(camera); } @@ -193,7 +193,7 @@ export function getRenderArea (camera: Camera, width: number, height: number, li class FxaaData { declare fxaaMaterial: Material; - private _updateFxaaPass () { + private _updateFxaaPass (): void { if (!this.fxaaMaterial) return; const combinePass = this.fxaaMaterial.passes[0]; @@ -201,7 +201,7 @@ class FxaaData { combinePass.tryCompile(); combinePass.endChangeStatesSilently(); } - private _init () { + private _init (): void { if (this.fxaaMaterial) return; this.fxaaMaterial = new Material(); this.fxaaMaterial._uuid = 'builtin-fxaa-material'; @@ -216,7 +216,7 @@ class FxaaData { } } -export function buildCopyPass (ppl: BasicPipeline, inOuts: CopyPair[]) { +export function buildCopyPass (ppl: BasicPipeline, inOuts: CopyPair[]): void { ppl.addCopyPass(inOuts); } @@ -224,7 +224,7 @@ let fxaaData: FxaaData | null = null; export function buildFxaaPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): { rtName: string; dsName: string; } { if (!fxaaData) { fxaaData = new FxaaData(); } @@ -277,7 +277,7 @@ class BloomData { threshold = 0.1; iterations = 2; intensity = 0.8; - private _updateBloomPass () { + private _updateBloomPass (): void { if (!this.bloomMaterial) return; const prefilterPass = this.bloomMaterial.passes[BLOOM_PREFILTERPASS_INDEX]; @@ -302,7 +302,7 @@ class BloomData { combinePass.tryCompile(); combinePass.endChangeStatesSilently(); } - private _init () { + private _init (): void { if (this.bloomMaterial) return; this.bloomMaterial = new Material(); this.bloomMaterial._uuid = 'builtin-bloom-material'; @@ -322,7 +322,7 @@ export function buildBloomPass (camera: Camera, inputRT: string, threshold = 0.6, iterations = 2, - intensity = 2.0) { + intensity = 2.0): { rtName: string; dsName: string; } { if (!bloomData) { bloomData = new BloomData(); } @@ -453,7 +453,7 @@ export function buildBloomPass (camera: Camera, export class PostInfo { declare postMaterial: Material; antiAliasing: AntiAliasing = AntiAliasing.NONE; - private _init () { + private _init (): void { this.postMaterial = new Material(); this.postMaterial.name = 'builtin-post-process-material'; if (macro.ENABLE_ANTIALIAS_FXAA) { @@ -480,7 +480,7 @@ let postInfo: PostInfo; export function buildPostprocessPass (camera: Camera, ppl: BasicPipeline, - inputTex: string) { + inputTex: string): { rtName: string; dsName: string; } { if (!postInfo) { postInfo = new PostInfo(); } @@ -525,7 +525,7 @@ export function buildPostprocessPass (camera: Camera, export function buildForwardPass (camera: Camera, ppl: BasicPipeline, isOffScreen: boolean, - enabledAlpha = true) { + enabledAlpha = true): { rtName: string; dsName: string; } { if (EDITOR) { ppl.setMacroInt('CC_PIPELINE_TYPE', 0); } @@ -599,7 +599,7 @@ let shadowPass; export function buildShadowPass (passName: Readonly, ppl: BasicPipeline, camera: Camera, light: Light, level: number, - width: Readonly, height: Readonly) { + width: Readonly, height: Readonly): void { const fboW = width; const fboH = height; const area = getRenderArea(camera, width, height, light, level); @@ -629,7 +629,7 @@ export function buildShadowPass (passName: Readonly, } export function buildReflectionProbePasss (camera: Camera, - ppl: BasicPipeline) { + ppl: BasicPipeline): void { if (!cclegacy.internal.reflectionProbeManager) return; const probes = cclegacy.internal.reflectionProbeManager.getProbes(); if (probes.length === 0) return; @@ -650,7 +650,7 @@ export function buildReflectionProbePasss (camera: Camera, } export function buildReflectionProbePass (camera: Camera, - ppl: BasicPipeline, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number) { + ppl: BasicPipeline, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number): void { const cameraName = `Camera${faceIdx}`; const area = probe.renderArea(); const width = area.x; @@ -684,7 +684,7 @@ export class ShadowInfo { mainLightShadowNames = new Array(); spotLightShadowNames = new Array(); validLights: Light[] = []; - reset () { + reset (): void { this.shadowEnabled = false; this.mainLightShadowNames.length = 0; this.spotLightShadowNames.length = 0; @@ -753,7 +753,7 @@ export class GBufferInfo { } // deferred passes export function buildGBufferPass (camera: Camera, - ppl: BasicPipeline) { + ppl: BasicPipeline): GBufferInfo { const cameraID = getCameraUniqueID(camera); const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -804,7 +804,7 @@ export function buildGBufferPass (camera: Camera, export class LightingInfo { declare deferredLightingMaterial: Material; - private _init () { + private _init (): void { this.deferredLightingMaterial = new Material(); this.deferredLightingMaterial.name = 'builtin-deferred-material'; this.deferredLightingMaterial.initialize({ @@ -823,7 +823,7 @@ export class LightingInfo { let lightingInfo: LightingInfo; // deferred lighting pass -export function buildLightingPass (camera: Camera, ppl: BasicPipeline, gBuffer: GBufferInfo) { +export function buildLightingPass (camera: Camera, ppl: BasicPipeline, gBuffer: GBufferInfo): { rtName: string; dsName: string; } { if (!lightingInfo) { lightingInfo = new LightingInfo(); } @@ -902,7 +902,7 @@ function getClearFlags (attachment: AttachmentType, clearFlag: ClearFlagBit, loa } export function buildUIPass (camera: Camera, - ppl: BasicPipeline) { + ppl: BasicPipeline): void { const cameraID = getCameraUniqueID(camera); const cameraName = `Camera${cameraID}`; const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -937,7 +937,7 @@ export function buildUIPass (camera: Camera, } } -export function buildNativeForwardPass (camera: Camera, ppl: BasicPipeline) { +export function buildNativeForwardPass (camera: Camera, ppl: BasicPipeline): void { const cameraID = getCameraUniqueID(camera); const cameraName = `Camera${cameraID}`; const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -997,7 +997,7 @@ export function buildNativeForwardPass (camera: Camera, ppl: BasicPipeline) { forwardPass.showStatistics = true; } -export function buildNativeDeferredPipeline (camera: Camera, ppl: BasicPipeline) { +export function buildNativeDeferredPipeline (camera: Camera, ppl: BasicPipeline): void { const cameraID = getCameraUniqueID(camera); const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -1072,7 +1072,7 @@ export function buildNativeDeferredPipeline (camera: Camera, ppl: BasicPipeline) } } -export function updateCameraUBO (setter: any, camera: Readonly, ppl: Readonly) { +export function updateCameraUBO (setter: any, camera: Readonly, ppl: Readonly): void { const pipeline = cclegacy.director.root.pipeline; const sceneData = ppl.pipelineSceneData; const skybox = sceneData.skybox; @@ -1091,7 +1091,7 @@ export function updateCameraUBO (setter: any, camera: Readonly, ppl: Rea setter.setVec4('cc_exposure', new Vec4(camera.exposure, 1.0 / camera.exposure, sceneData.isHDR ? 1.0 : 0.0, 1.0 / Camera.standardExposureValue)); } -function bindDescValue (desc: DescriptorSet, binding: number, value) { +function bindDescValue (desc: DescriptorSet, binding: number, value): void { if (value instanceof Buffer) { desc.bindBuffer(binding, value); } else if (value instanceof Texture) { @@ -1101,7 +1101,7 @@ function bindDescValue (desc: DescriptorSet, binding: number, value) { } } -function bindGlobalDesc (desc: DescriptorSet, binding: number, value) { +function bindGlobalDesc (desc: DescriptorSet, binding: number, value): void { bindDescValue(desc, binding, value); } @@ -1118,7 +1118,7 @@ export function getDescBinding (descId, descData: DescriptorSetData): number { return -1; } -export function getDescBindingFromName (bindingName: string) { +export function getDescBindingFromName (bindingName: string): number { const pipeline = cclegacy.director.root.pipeline as WebPipeline; const layoutGraph = pipeline.layoutGraph; const vertIds = layoutGraph.vertices(); @@ -1143,7 +1143,7 @@ export function getDescBindingFromName (bindingName: string) { } const uniformMap: Map = new Map(); -function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = false) { +function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = false): void { const constants = data.constants; const samplers = data.samplers; const textures = data.textures; @@ -1192,7 +1192,7 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa } } const layouts: Map = new Map(); -export function getDescriptorSetDataFromLayout (layoutName: string) { +export function getDescriptorSetDataFromLayout (layoutName: string): DescriptorSetData | undefined { const descLayout = layouts.get(layoutName); if (descLayout) { return descLayout; @@ -1206,22 +1206,22 @@ export function getDescriptorSetDataFromLayout (layoutName: string) { return layoutData; } -export function getDescriptorSetDataFromLayoutId (id: number) { +export function getDescriptorSetDataFromLayoutId (id: number): DescriptorSetData | undefined { const webPip = cclegacy.director.root.pipeline as WebPipeline; const layout = webPip.layoutGraph.getLayout(id); const layoutData = layout.descriptorSets.get(UpdateFrequency.PER_PASS); return layoutData; } -export function initGlobalDescBinding (data: RenderData, layoutName = 'default') { +export function initGlobalDescBinding (data: RenderData, layoutName = 'default'): void { applyGlobalDescBinding(data, layoutName); } -export function updateGlobalDescBinding (data: RenderData, layoutName = 'default') { +export function updateGlobalDescBinding (data: RenderData, layoutName = 'default'): void { applyGlobalDescBinding(data, layoutName, true); } -export function mergeSrcToTargetDesc (fromDesc, toDesc, isForce = false) { +export function mergeSrcToTargetDesc (fromDesc, toDesc, isForce = false): number[] { fromDesc.update(); const fromGpuDesc = fromDesc.gpuDescriptorSet; const toGpuDesc = toDesc.gpuDescriptorSet; @@ -1270,7 +1270,7 @@ class SSSSBlurData { boundingBox = 0.4; ssssScale = 3.0; - get ssssStrength () { + get ssssStrength (): Vec3 { return this._v3SSSSStrength; } set ssssStrength (val: Vec3) { @@ -1278,7 +1278,7 @@ class SSSSBlurData { this._updateSampleCount(); } - get ssssFallOff () { + get ssssFallOff (): Vec3 { return this._v3SSSSFallOff; } set ssssFallOff (val: Vec3) { @@ -1286,7 +1286,7 @@ class SSSSBlurData { this._updateSampleCount(); } - get kernel () { + get kernel (): Vec4[] { return this._kernel; } @@ -1299,7 +1299,7 @@ class SSSSBlurData { * spreads the shape making it wider, while small falloffs make it * narrower. */ - private _gaussian (out: Vec3, variance: number, r: number) { + private _gaussian (out: Vec3, variance: number, r: number): void { const xx = r / (0.001 + this._v3SSSSFallOff.x); out.x = Math.exp((-(xx * xx)) / (2.0 * variance)) / (2.0 * 3.14 * variance); const yy = r / (0.001 + this._v3SSSSFallOff.y); @@ -1316,7 +1316,7 @@ class SSSSBlurData { * the profile. For example, it allows to create blue SSS gradients, which * could be useful in case of rendering blue creatures. */ - private _profile (out: Vec3, val: number) { + private _profile (out: Vec3, val: number): void { for (let i = 0; i < 5; i++) { this._gaussian(_vec3Temp2, _varianceArray[i], val); _vec3Temp2.multiplyScalar(_strengthParameterArray[i]); @@ -1324,7 +1324,7 @@ class SSSSBlurData { } } - private _updateSampleCount () { + private _updateSampleCount (): void { const strength = this._v3SSSSStrength; const nSamples = I_SAMPLES_COUNT; const range = nSamples > 20 ? 3.0 : 2.0; @@ -1387,7 +1387,7 @@ class SSSSBlurData { } } - private _updateBlurPass () { + private _updateBlurPass (): void { if (!this.ssssBlurMaterial) return; const copyInputDSPass = this.ssssBlurMaterial.passes[COPY_INPUT_DS_PASS_INDEX]; @@ -1404,7 +1404,7 @@ class SSSSBlurData { ssssBlurYPass.endChangeStatesSilently(); } - private _init () { + private _init (): void { if (this.ssssBlurMaterial) return; this.ssssBlurMaterial = new Material(); @@ -1427,7 +1427,7 @@ class SSSSBlurData { } let ssssBlurData: SSSSBlurData | null = null; -export function hasSkinObject (ppl: BasicPipeline) { +export function hasSkinObject (ppl: BasicPipeline): boolean { const sceneData = ppl.pipelineSceneData; return sceneData.skin.enabled && sceneData.standardSkinModel !== null; } @@ -1435,7 +1435,7 @@ export function hasSkinObject (ppl: BasicPipeline) { function _buildSSSSBlurPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): { rtName: string; dsName: string; } { const sceneData = ppl.pipelineSceneData; const skin = sceneData.skin; const standardSkinModel = sceneData.standardSkinModel; @@ -1602,7 +1602,7 @@ function _buildSSSSBlurPass (camera: Camera, class ToneMappingInfo { declare toneMappingMaterial: Material; - private _init () { + private _init (): void { this.toneMappingMaterial = new Material(); this.toneMappingMaterial.name = 'builtin-tone-mapping-material'; this.toneMappingMaterial.initialize({ @@ -1621,7 +1621,7 @@ let toneMappingInfo: ToneMappingInfo | null = null; export function buildToneMappingPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): { rtName: string; dsName: string; } { if (!ppl.pipelineSceneData.isHDR || !ppl.getMacroBool('CC_USE_FLOAT_OUTPUT')) return { rtName: inputRT, dsName: inputDS }; if (!toneMappingInfo) { toneMappingInfo = new ToneMappingInfo(); @@ -1684,7 +1684,7 @@ export function buildTransparencyPass (camera: Camera, ppl: BasicPipeline, inputRT: string, inputDS: string, - hasDeferredTransparencyObject: boolean) { + hasDeferredTransparencyObject: boolean): { rtName: string; dsName: string; } { if (hasDeferredTransparencyObject) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -1732,7 +1732,7 @@ export function buildTransparencyPass (camera: Camera, function _buildSpecularPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): { rtName: string; dsName: string; } { if (EDITOR) { ppl.setMacroInt('CC_PIPELINE_TYPE', 0); } @@ -1790,7 +1790,7 @@ function _buildSpecularPass (camera: Camera, export function buildSSSSPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): { rtName: string; dsName: string; } { if (hasSkinObject(ppl)) { forceEnableFloatOutput(ppl); const blurInfo = _buildSSSSBlurPass(camera, ppl, inputRT, inputDS); @@ -1806,19 +1806,19 @@ class HBAOParams { declare hbaoMaterial: Material; declare randomTexture: Texture2D; - get uvDepthToEyePosParams () { + get uvDepthToEyePosParams (): Vec4 { return this._uvDepthToEyePosParams; } - get radiusParam () { + get radiusParam (): Vec4 { return this._radiusParam; } - get miscParam () { + get miscParam (): Vec4 { return this._miscParam; } - get blurParam () { + get blurParam (): Vec4 { return this._blurParam; } @@ -1879,7 +1879,7 @@ class HBAOParams { 235, 100, 24, 255, 252, 36, 158, 255, 254, 20, 142, 255, 245, 135, 124, 255, 251, 43, 121, 255, 253, 31, 145, 255, 235, 98, 160, 255, 240, 146, 198, 255, ]; - private _init () { + private _init (): void { if (this.hbaoMaterial) return; this.hbaoMaterial = new Material(); this.hbaoMaterial.name = 'builtin-hbao-material'; @@ -1913,7 +1913,7 @@ class HBAOParams { this.hbaoMaterial.setProperty('RandomTex', this.randomTexture, 0); } - public update () { + public update (): void { // should be same value as shader const HALF_KERNEL_RADIUS = 4; const INV_LN2 = 1.44269504; @@ -1952,7 +1952,7 @@ const vec2 = new Vec2(); function _buildHBAOPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): { rtName: string; dsName: string; } { if (!_hbaoParams) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -2005,7 +2005,7 @@ function _buildHBAOBlurPass (camera: Camera, ppl: BasicPipeline, inputRT: string, inputDS: string, - isYPass: boolean) { + isYPass: boolean): { rtName: string; dsName: string; } { if (!_hbaoParams) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -2077,7 +2077,7 @@ function _buildHBAOCombinedPass (camera: Camera, ppl: BasicPipeline, inputRT: string, inputDS: string, - outputRT: string) { + outputRT: string): { rtName: string; dsName: string; } { if (!_hbaoParams) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -2136,7 +2136,7 @@ export function buildHBAOPasses (camera: Camera, blurSharpness = 3, aoSaturation = 1.0, aoStrength = 1.0, - needBlur = true) { + needBlur = true): { rtName: string; dsName: string; } { const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; const height = area.height; @@ -2196,7 +2196,7 @@ class ClusterLightData { dispatchY = 1; dispatchZ = 1; - private _initMaterial (id: string, effect: string) { + private _initMaterial (id: string, effect: string): Material { const mat = new Material(); mat.name = id; mat.initialize({ effectName: effect }); @@ -2206,7 +2206,7 @@ class ClusterLightData { return mat; } - private _init () { + private _init (): void { this.clusterBuildCS = this._initMaterial('builtin-cluster-build-cs-material', 'pipeline/cluster-build'); this.clusterLightCullingCS = this._initMaterial('builtin-cluster-culling-cs-material', 'pipeline/cluster-culling'); @@ -2222,7 +2222,7 @@ class ClusterLightData { let _clusterLightData: ClusterLightData | null = null; export function buildLightClusterBuildPass (camera: Camera, clusterData: ClusterLightData, - ppl: Pipeline) { + ppl: Pipeline): void { const cameraID = getCameraUniqueID(camera); const clusterBufferName = `clusterBuffer${cameraID}`; @@ -2247,7 +2247,7 @@ export function buildLightClusterBuildPass (camera: Camera, clusterData: Cluster } export function buildLightClusterCullingPass (camera: Camera, clusterData: ClusterLightData, - ppl: Pipeline) { + ppl: Pipeline): void { const cameraID = getCameraUniqueID(camera); const clusterBufferName = `clusterBuffer${cameraID}`; const clusterLightBufferName = `clusterLightBuffer${cameraID}`; @@ -2283,7 +2283,7 @@ export function buildLightClusterCullingPass (camera: Camera, clusterData: Clust clusterPass.setMat4('cc_matProjInv', camera.matProjInv); } -export function buildLightData (camera: Camera, pipeline: BasicPipeline) { +export function buildLightData (camera: Camera, pipeline: BasicPipeline): void { validPunctualLightsCulling(pipeline, camera); // build cluster light data @@ -2413,7 +2413,7 @@ export function buildLightData (camera: Camera, pipeline: BasicPipeline) { ppl.addUploadPass([uploadPair1, uploadPair2]); } -export function buildClusterPasses (camera: Camera, pipeline: BasicPipeline) { +export function buildClusterPasses (camera: Camera, pipeline: BasicPipeline): void { buildLightData(camera, pipeline); const ppl = (pipeline as Pipeline); diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index a65da10f866..d1a321a386e 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -73,33 +73,33 @@ class ResourceVisitor implements ResourceGraphVisitor { set resName (value: string) { this.name = value; } - createDeviceTex (value: Texture | Framebuffer | ManagedResource | RenderSwapchain) { + createDeviceTex (value: Texture | Framebuffer | ManagedResource | RenderSwapchain): void { const deviceTex = new DeviceTexture(this.name, value); context.deviceTextures.set(this.name, deviceTex); } - managed (value: ManagedResource) { + managed (value: ManagedResource): void { this.createDeviceTex(value); } - managedBuffer (value: ManagedBuffer) { + managedBuffer (value: ManagedBuffer): void { // noop } - managedTexture (value: ManagedTexture) { + managedTexture (value: ManagedTexture): void { // noop } - persistentBuffer (value: Buffer) { + persistentBuffer (value: Buffer): void { } - persistentTexture (value: Texture) { + persistentTexture (value: Texture): void { this.createDeviceTex(value); } - framebuffer (value: Framebuffer) { + framebuffer (value: Framebuffer): void { this.createDeviceTex(value); } - swapchain (value: RenderSwapchain) { + swapchain (value: RenderSwapchain): void { this.createDeviceTex(value); } - formatView (value: FormatView) { + formatView (value: FormatView): void { } - subresourceView (value: SubresourceView) { + subresourceView (value: SubresourceView): void { } } @@ -109,7 +109,7 @@ class DeviceResource { constructor (name: string) { this._name = name; } - get name () { return this._name; } + get name (): string { return this._name; } } class DeviceTexture extends DeviceResource { protected _texture: Texture | null = null; @@ -117,13 +117,13 @@ class DeviceTexture extends DeviceResource { protected _framebuffer: Framebuffer | null = null; protected _desc: ResourceDesc | null = null; protected _trait: ResourceTraits | null = null; - get texture () { return this._texture; } + get texture (): Texture | null { return this._texture; } set framebuffer (val: Framebuffer | null) { this._framebuffer = val; } - get framebuffer () { return this._framebuffer; } - get description () { return this._desc; } - get trait () { return this._trait; } - get swapchain () { return this._swapchain; } - private _setDesc (desc: ResourceDesc) { + get framebuffer (): Framebuffer | null { return this._framebuffer; } + get description (): ResourceDesc | null { return this._desc; } + get trait (): ResourceTraits | null { return this._trait; } + get swapchain (): Swapchain | null { return this._swapchain; } + private _setDesc (desc: ResourceDesc): void { if (!this._desc) { this._desc = new ResourceDesc(); } @@ -188,7 +188,7 @@ class DeviceTexture extends DeviceResource { )); } - release () { + release (): void { if (this.framebuffer) { this.framebuffer.destroy(); this._framebuffer = null; @@ -200,7 +200,7 @@ class DeviceTexture extends DeviceResource { } } -function isShadowMap (graphScene: GraphScene) { +function isShadowMap (graphScene: GraphScene): boolean | null { const pSceneData: PipelineSceneData = cclegacy.director.root.pipeline.pipelineSceneData; return pSceneData.shadows.enabled && pSceneData.shadows.type === ShadowType.ShadowMap @@ -226,10 +226,10 @@ class BlitDesc { private _lightVolumeBuffer: Buffer | null = null; private _lightMeterScale = 10000.0; private _lightBufferData!: Float32Array; - get screenQuad () { return this._screenQuad; } - get blit () { return this._blit; } + get screenQuad (): PipelineInputAssemblerData | null { return this._screenQuad; } + get blit (): Blit { return this._blit; } set blit (blit: Blit) { this._blit = blit; } - get stageDesc () { return this._stageDesc; } + get stageDesc (): DescriptorSet | undefined { return this._stageDesc; } constructor (blit: Blit, queue: DeviceRenderQueue) { this._blit = blit; this._queue = queue; @@ -241,12 +241,12 @@ class BlitDesc { protected _createQuadInputAssembler (): PipelineInputAssemblerData { return context.blit.pipelineIAData; } - createScreenQuad () { + createScreenQuad (): void { if (!this._screenQuad) { this._screenQuad = this._createQuadInputAssembler(); } } - private _gatherVolumeLights (camera: Camera) { + private _gatherVolumeLights (camera: Camera): void { if (!camera.scene) { return; } const pipeline = context.pipeline; const cmdBuff = context.commandBuffer; @@ -337,7 +337,7 @@ class BlitDesc { cmdBuff.updateBuffer(this._lightVolumeBuffer!, this._lightBufferData); } - update () { + update (): void { if (this.blit.sceneFlags & SceneFlags.VOLUMETRIC_LIGHTING && this.blit.camera && !this._isGatherLight) { this._gatherVolumeLights(this.blit.camera); @@ -350,12 +350,12 @@ class BlitDesc { } } - reset () { + reset (): void { this._isUpdate = false; this._isGatherLight = false; } - createStageDescriptor () { + createStageDescriptor (): void { const blit = this.blit; const pass = blit.material!.passes[blit.passID]; const device = context.device; @@ -410,14 +410,14 @@ class DeviceRenderQueue { private _blitDesc: BlitDesc | null = null; private _queueId = -1; set queueId (val) { this._queueId = val; } - get queueId () { return this._queueId; } + get queueId (): number { return this._queueId; } set isUpdateUBO (update: boolean) { this._isUpdateUBO = update; } - get isUpdateUBO () { return this._isUpdateUBO; } + get isUpdateUBO (): boolean { return this._isUpdateUBO; } set isUploadInstance (value: boolean) { this._isUploadInstance = value; } - get isUploadInstance () { return this._isUploadInstance; } + get isUploadInstance (): boolean { return this._isUploadInstance; } set isUploadBatched (value: boolean) { this._isUploadBatched = value; } - get isUploadBatched () { return this._isUploadBatched; } - init (devicePass: DeviceRenderPass, renderQueue: RenderQueue, id: number) { + get isUploadBatched (): boolean { return this._isUploadBatched; } + init (devicePass: DeviceRenderPass, renderQueue: RenderQueue, id: number): void { this.reset(); this._graphQueue = renderQueue; this.queueHint = renderQueue.hint; @@ -433,7 +433,7 @@ class DeviceRenderQueue { context.pipeline.pipelineSceneData); } } - createBlitDesc (blit: Blit) { + createBlitDesc (blit: Blit): void { if (!this._blitDesc) { this._blitDesc = new BlitDesc(blit, this); } @@ -448,21 +448,21 @@ class DeviceRenderQueue { this._preSceneTasks.push(this._transversal.preRenderPass(this._sceneVisitor)); this._sceneTasks.push(this._transversal.transverse(this._sceneVisitor)); } - reset () { + reset (): void { this._postSceneTasks.length = this._preSceneTasks.length = this._sceneTasks.length = 0; this._isUpdateUBO = false; this._isUploadInstance = false; this._isUploadBatched = false; this._blitDesc?.reset(); } - get graphQueue () { return this._graphQueue; } - get blitDesc () { return this._blitDesc; } - get sceneTasks () { return this._sceneTasks; } + get graphQueue (): RenderQueue { return this._graphQueue; } + get blitDesc (): BlitDesc | null { return this._blitDesc; } + get sceneTasks (): DeviceSceneTask[] { return this._sceneTasks; } set queueHint (value: QueueHint) { this._hint = value; } - get queueHint () { return this._hint; } - get devicePass () { return this._devicePass!; } - get preSceneTasks () { return this._preSceneTasks; } - preRecord () { + get queueHint (): QueueHint { return this._hint; } + get devicePass (): DeviceRenderPass { return this._devicePass!; } + get preSceneTasks (): DevicePreSceneTask[] { return this._preSceneTasks; } + preRecord (): void { for (const task of this._preSceneTasks) { task.start(); task.join(); @@ -470,7 +470,7 @@ class DeviceRenderQueue { } } - record () { + record (): void { if (this._descSetData && this._descSetData.descriptorSet) { context.commandBuffer .bindDescriptorSet(SetIndex.COUNT, this._descSetData.descriptorSet); @@ -482,7 +482,7 @@ class DeviceRenderQueue { } } - postRecord () { + postRecord (): void { for (const task of this._postSceneTasks) { task.start(); task.join(); @@ -501,7 +501,7 @@ class SubmitInfo { public shadowMap: Map = new Map(); public additiveLight: RenderAdditiveLightQueue | null = null; public reflectionProbe: RenderReflectionProbeQueue | null = null; - reset () { + reset (): void { this.instances.clear(); this.renderInstanceQueue.length = 0; this.opaqueList.length = 0; @@ -562,18 +562,18 @@ class RenderPassLayoutInfo { } } } - get descriptorSet () { return this._descriptorSet; } - get layoutID () { return this._layoutID; } - get stage () { return this._stage; } - get layout () { return this._layout; } + get descriptorSet (): DescriptorSet | null { return this._descriptorSet; } + get layoutID (): number { return this._layoutID; } + get stage (): RenderStageData | null { return this._stage; } + get layout (): PipelineLayoutData { return this._layout; } } class RasterPassInfo { protected _id!: number; protected _pass!: RasterPass; - get id () { return this._id; } - get pass () { return this._pass; } - private _copyPass (pass: RasterPass) { + get id (): number { return this._id; } + get pass (): RasterPass { return this._pass; } + private _copyPass (pass: RasterPass): void { const rasterPass = this._pass || new RasterPass(); rasterPass.width = pass.width; rasterPass.height = pass.height; @@ -618,7 +618,7 @@ class RasterPassInfo { } this._pass = rasterPass; } - applyInfo (id: number, pass: RasterPass) { + applyInfo (id: number, pass: RasterPass): void { this._id = id; this._copyPass(pass); } @@ -739,28 +739,28 @@ class DeviceRenderPass { } get layoutName (): string { return this._layoutName; } get passID (): number { return this._passID; } - get renderLayout () { return this._layout; } - get renderPass () { return this._renderPass; } - get framebuffer () { return this._framebuffer; } - get clearColor () { return this._clearColor; } - get clearDepth () { return this._clearDepth; } - get clearStencil () { return this._clearStencil; } - get deviceQueues () { return this._deviceQueues; } - get rasterPassInfo () { return this._rasterInfo; } - get viewport () { return this._viewport; } - visitResource (resName: string) { + get renderLayout (): RenderPassLayoutInfo | null { return this._layout; } + get renderPass (): RenderPass { return this._renderPass; } + get framebuffer (): Framebuffer { return this._framebuffer; } + get clearColor (): Color[] { return this._clearColor; } + get clearDepth (): number { return this._clearDepth; } + get clearStencil (): number { return this._clearStencil; } + get deviceQueues (): DeviceRenderQueue[] { return this._deviceQueues; } + get rasterPassInfo (): RasterPassInfo { return this._rasterInfo; } + get viewport (): Viewport | null { return this._viewport; } + visitResource (resName: string): void { const resourceGraph = context.resourceGraph; const vertId = resourceGraph.vertex(resName); resourceVisitor.resName = resName; resourceGraph.visitVertex(resourceVisitor, vertId); } - addQueue (queue: DeviceRenderQueue) { this._deviceQueues.push(queue); } - prePass () { + addQueue (queue: DeviceRenderQueue): void { this._deviceQueues.push(queue); } + prePass (): void { for (const queue of this._deviceQueues) { queue.preRecord(); } } - protected _applyRenderLayout (input: [string, ComputeView[]]) { + protected _applyRenderLayout (input: [string, ComputeView[]]): void { const stageName = context.renderGraph.getLayout(this.rasterPassInfo.id); if (stageName) { const layoutGraph = context.layoutGraph; @@ -770,7 +770,7 @@ class DeviceRenderPass { } } } - getGlobalDescData () { + getGlobalDescData (): DescriptorSetData { const stageId = context.layoutGraph.locateChild(context.layoutGraph.nullVertex(), 'default'); assert(stageId !== 0xFFFFFFFF); const layout = context.layoutGraph.getLayout(stageId); @@ -778,7 +778,7 @@ class DeviceRenderPass { return layoutData; } - protected _applyViewport (frameTex: Texture) { + protected _applyViewport (frameTex: Texture): void { this._viewport = null; const viewport = this._rasterInfo.pass.viewport; if (viewport.left !== 0 @@ -789,7 +789,7 @@ class DeviceRenderPass { } } - protected _showProfiler (rect: Rect) { + protected _showProfiler (rect: Rect): void { const profiler = context.pipeline.profiler!; if (!profiler || !profiler.enabled) { return; @@ -816,7 +816,7 @@ class DeviceRenderPass { } // record common buffer - record () { + record (): void { const tex = this.framebuffer.colorTextures[0]!; this._applyViewport(tex); const cmdBuff = context.commandBuffer; @@ -843,7 +843,7 @@ class DeviceRenderPass { cmdBuff.endRenderPass(); } - private _clear () { + private _clear (): void { for (const [cam, infoMap] of context.submitMap) { for (const [id, info] of infoMap) { info.additiveLight?.clear(); @@ -858,14 +858,14 @@ class DeviceRenderPass { } } - postPass () { + postPass (): void { this._clear(); // this.submitMap.clear(); for (const queue of this._deviceQueues) { queue.postRecord(); } } - resetResource (id: number, pass: RasterPass) { + resetResource (id: number, pass: RasterPass): void { this._rasterInfo.applyInfo(id, pass); this._deviceQueues.length = 0; let framebuffer: Framebuffer | null = null; @@ -937,7 +937,7 @@ class DeviceSceneTransversal extends WebSceneTransversal { this._camera = graphScene.scene ? graphScene.scene.camera : null; if (this._camera) this._scene = this._camera.scene!; } - get graphScene () { return this._graphScene; } + get graphScene (): GraphScene { return this._graphScene; } public preRenderPass (visitor: WebSceneVisitor): DevicePreSceneTask { if (!this._preSceneTask) { this._preSceneTask = new DevicePreSceneTask(this._currentQueue, this._graphScene, visitor); @@ -964,7 +964,7 @@ class GraphScene { blit: Blit | null = null; dispatch: Dispatch | null = null; sceneID = -1; - private _copyScene (scene: SceneData | null) { + private _copyScene (scene: SceneData | null): void { if (scene) { if (!this.scene) { this.scene = new SceneData(); @@ -978,7 +978,7 @@ class GraphScene { } this.scene = null; } - private _copyBlit (blit: Blit | null) { + private _copyBlit (blit: Blit | null): void { if (blit) { if (!this.blit) { this.blit = new Blit(blit.material, blit.passID, blit.sceneFlags, blit.camera); @@ -991,7 +991,7 @@ class GraphScene { } this.blit = null; } - init (scene, blit, sceneID) { + init (scene, blit, sceneID): void { this._copyScene(scene); this._copyBlit(blit); this.sceneID = sceneID; @@ -1011,7 +1011,7 @@ class DevicePreSceneTask extends WebSceneTask { this._renderPass = queue.devicePass.renderPass; this._cmdBuff = context.commandBuffer; } - apply (queue: DeviceRenderQueue, graphScene: GraphScene) { + apply (queue: DeviceRenderQueue, graphScene: GraphScene): void { this._currentQueue = queue; this._graphScene = graphScene; this._renderPass = queue.devicePass.renderPass; @@ -1022,9 +1022,9 @@ class DevicePreSceneTask extends WebSceneTask { this._camera = camera; } } - get graphScene () { return this._graphScene; } + get graphScene (): GraphScene { return this._graphScene; } - public start () { + public start (): void { if (this.graphScene.blit) { this._currentQueue.createBlitDesc(this.graphScene.blit); return; @@ -1118,7 +1118,7 @@ class DevicePreSceneTask extends WebSceneTask { if (sceneFlag & SceneFlags.TRANSPARENT_OBJECT) { this._submitInfo.transparentList.sort(this._transparentCompareFn); } } - protected _instancedSort () { + protected _instancedSort (): void { let it = this._submitInfo!.instances.values(); let res = it.next(); while (!res.done) { @@ -1137,7 +1137,7 @@ class DevicePreSceneTask extends WebSceneTask { } } - protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false) { + protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false): void { const subModel = ro.model.subModels[subModelIdx]; const pass = subModel.passes[passIdx]; const shader = subModel.shaders[passIdx]; @@ -1165,18 +1165,18 @@ class DevicePreSceneTask extends WebSceneTask { * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 */ - protected _opaqueCompareFn (a: RenderInfo, b: RenderInfo) { + protected _opaqueCompareFn (a: RenderInfo, b: RenderInfo): number { return (a.hash - b.hash) || (a.depth - b.depth) || (a.shaderId - b.shaderId); } /** * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 */ - protected _transparentCompareFn (a: RenderInfo, b: RenderInfo) { + protected _transparentCompareFn (a: RenderInfo, b: RenderInfo): number { return (a.priority - b.priority) || (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); } - private _uploadInstanceBuffers () { + private _uploadInstanceBuffers (): void { if (this._currentQueue.isUploadInstance) return; const it = this._submitInfo!.instances.values(); let res = it.next(); while (!res.done) { @@ -1186,13 +1186,13 @@ class DevicePreSceneTask extends WebSceneTask { this._currentQueue.isUploadInstance = true; } - protected _updateGlobal (data: RenderData) { + protected _updateGlobal (data: RenderData): void { const devicePass = this._currentQueue.devicePass; updateGlobalDescBinding(data, isEnableEffect() ? context.renderGraph.getLayout(devicePass.rasterPassInfo.id) : 'default'); if (!isEnableEffect()) context.pipeline.descriptorSet.update(); } - public submit () { + public submit (): void { if (this.graphScene.blit) { this._currentQueue.blitDesc!.update(); return; @@ -1216,7 +1216,7 @@ class DeviceSceneTask extends WebSceneTask { this._renderPass = this._currentQueue.devicePass.renderPass; this._graphScene = graphScene; } - apply (queue: DeviceRenderQueue, graphScene: GraphScene) { + apply (queue: DeviceRenderQueue, graphScene: GraphScene): void { this._currentQueue = queue; this._graphScene = graphScene; this._renderPass = queue.devicePass.renderPass; @@ -1226,9 +1226,9 @@ class DeviceSceneTask extends WebSceneTask { this._camera = camera; } } - get graphScene () { return this._graphScene; } - public start () {} - protected _recordRenderList (isTransparent: boolean) { + get graphScene (): GraphScene { return this._graphScene; } + public start (): void {} + protected _recordRenderList (isTransparent: boolean): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; const renderList = isTransparent ? currSubmitInfo.transparentList @@ -1247,10 +1247,10 @@ class DeviceSceneTask extends WebSceneTask { this.visitor.draw(inputAssembler); } } - protected _recordOpaqueList () { + protected _recordOpaqueList (): void { this._recordRenderList(false); } - protected _recordInstences () { + protected _recordInstences (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; const it = currSubmitInfo.renderInstanceQueue.length === 0 @@ -1281,7 +1281,7 @@ class DeviceSceneTask extends WebSceneTask { res = it.next(); } } - protected _recordUI () { + protected _recordUI (): void { const batches = this.camera!.scene!.batches; for (let i = 0; i < batches.length; i++) { const batch = batches[i]; @@ -1308,23 +1308,23 @@ class DeviceSceneTask extends WebSceneTask { } } } - protected _recordTransparentList () { + protected _recordTransparentList (): void { this._recordRenderList(true); } - protected _recordShadowMap () { + protected _recordShadowMap (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; currSubmitInfo.shadowMap.get(this.graphScene.sceneID)!.recordCommandBuffer(context.device, this._renderPass, context.commandBuffer); } - protected _recordReflectionProbe () { + protected _recordReflectionProbe (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; currSubmitInfo.reflectionProbe?.recordCommandBuffer(context.device, this._renderPass, context.commandBuffer); } - private _clearExtBlitDesc (desc, extResId: number[]) { + private _clearExtBlitDesc (desc, extResId: number[]): void { const toGpuDesc = desc.gpuDescriptorSet; for (let i = 0; i < extResId.length; i++) { const currDesc = toGpuDesc.gpuDescriptors[extResId[i]]; @@ -1339,7 +1339,7 @@ class DeviceSceneTask extends WebSceneTask { } } - private _recordBlit () { + private _recordBlit (): void { if (!this.graphScene.blit) { return; } const blit = this.graphScene.blit; @@ -1370,7 +1370,7 @@ class DeviceSceneTask extends WebSceneTask { // if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, globalDesc); } } - private _recordAdditiveLights () { + private _recordAdditiveLights (): void { const devicePass = this._currentQueue.devicePass; const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; @@ -1379,7 +1379,7 @@ class DeviceSceneTask extends WebSceneTask { context.commandBuffer); } - private _recordPlanarShadows () { + private _recordPlanarShadows (): void { const devicePass = this._currentQueue.devicePass; const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; @@ -1387,12 +1387,12 @@ class DeviceSceneTask extends WebSceneTask { this._renderPass, context.commandBuffer); } - protected _updateGlobal (data: RenderData) { + protected _updateGlobal (data: RenderData): void { const devicePass = this._currentQueue.devicePass; updateGlobalDescBinding(data, isEnableEffect() ? context.renderGraph.getLayout(devicePass.rasterPassInfo.id) : 'default'); if (!isEnableEffect()) context.pipeline.descriptorSet.update(); } - protected _setMainLightShadowTex (data: RenderData) { + protected _setMainLightShadowTex (data: RenderData): void { const graphScene = this.graphScene; if (graphScene.scene && graphScene.scene.camera) { const mainLight = graphScene.scene.camera.scene!.mainLight; @@ -1412,7 +1412,7 @@ class DeviceSceneTask extends WebSceneTask { } } } - protected _updateRenderData () { + protected _updateRenderData (): void { if (this._currentQueue.isUpdateUBO) return; const devicePass = this._currentQueue.devicePass; const rasterId = devicePass.rasterPassInfo.id; @@ -1431,7 +1431,7 @@ class DeviceSceneTask extends WebSceneTask { } this._currentQueue.isUpdateUBO = true; } - public submit () { + public submit (): void { const devicePass = this._currentQueue.devicePass; const queueViewport = this._currentQueue.viewport; this._updateRenderData(); @@ -1497,11 +1497,11 @@ class DevicePostSceneTask extends WebSceneTask {} class ExecutorPools { constructor (context: ExecutorContext) { - this.deviceQueuePool = new RecyclePool(() => new DeviceRenderQueue(), 16); - this.graphScenePool = new RecyclePool(() => new GraphScene(), 16); - this.rasterPassInfoPool = new RecyclePool(() => new RasterPassInfo(), 16); - this.reflectionProbe = new RecyclePool(() => new RenderReflectionProbeQueue(context.pipeline), 8); - this.passPool = new RecyclePool(() => ({ + this.deviceQueuePool = new RecyclePool((): DeviceRenderQueue => new DeviceRenderQueue(), 16); + this.graphScenePool = new RecyclePool((): GraphScene => new GraphScene(), 16); + this.rasterPassInfoPool = new RecyclePool((): RasterPassInfo => new RasterPassInfo(), 16); + this.reflectionProbe = new RecyclePool((): RenderReflectionProbeQueue => new RenderReflectionProbeQueue(context.pipeline), 8); + this.passPool = new RecyclePool((): { priority: number; hash: number; depth: number; shaderId: number; subModel: any; passIdx: number; } => ({ priority: 0, hash: 0, depth: 0, @@ -1510,25 +1510,25 @@ class ExecutorPools { passIdx: 0, }), 64); } - addPassInfo () { + addPassInfo (): IRenderPass { return this.passPool.add(); } - resetPassInfo () { + resetPassInfo (): void { this.passPool.reset(); } - addDeviceQueue () { + addDeviceQueue (): DeviceRenderQueue { return this.deviceQueuePool.add(); } - addGraphScene () { + addGraphScene (): GraphScene { return this.graphScenePool.add(); } - addReflectionProbe () { + addReflectionProbe (): RenderReflectionProbeQueue { return this.reflectionProbe.add(); } - addRasterPassInfo () { + addRasterPassInfo (): RasterPassInfo { return this.rasterPassInfoPool.add(); } - reset () { + reset (): void { this.deviceQueuePool.reset(); this.graphScenePool.reset(); this.reflectionProbe.reset(); @@ -1556,22 +1556,22 @@ class BlitInfo { private _deferredLitsBufView!: Buffer; private _localUBO!: Buffer; private _stageDescs: Map = new Map(); - get pipelineIAData () { + get pipelineIAData (): PipelineInputAssemblerData { return this._pipelineIAData; } - get deferredLitsBufView () { + get deferredLitsBufView (): Buffer { return this._deferredLitsBufView; } - get lightVolumeBuffer () { + get lightVolumeBuffer (): Buffer { return this._lightVolumeBuffer; } - get lightBufferData () { + get lightBufferData (): Float32Array { return this._lightBufferData; } - get stageDescs () { + get stageDescs (): Map { return this._stageDescs; } - get emptyLocalUBO () { + get emptyLocalUBO (): Buffer { return this._localUBO; } constructor (context: ExecutorContext) { @@ -1590,7 +1590,7 @@ class BlitInfo { )); } - resize (width, height) { + resize (width, height): void { if (width !== this._width || height !== this._height) { quadRect.y = quadRect.x = 0; quadRect.width = width; @@ -1600,7 +1600,7 @@ class BlitInfo { } } - private _createLightVolumes () { + private _createLightVolumes (): void { const device = this._context.root.device; let totalSize = Float32Array.BYTES_PER_ELEMENT * volLightAttrCount * 4 * UBODeferredLight.LIGHTS_PER_PASS; totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment; @@ -1746,14 +1746,14 @@ class ExecutorContext { this.pools = new ExecutorPools(this); this.blit = new BlitInfo(this); } - reset () { + reset (): void { this.pools.reset(); this.cullCamera = null; for (const infoMap of this.submitMap) { for (const info of infoMap[1]) info[1].reset(); } } - resize (width: number, height: number) { + resize (width: number, height: number): void { this.width = width; this.height = height; this.blit.resize(width, height); @@ -1799,11 +1799,11 @@ export class Executor { ); } - resize (width: number, height: number) { + resize (width: number, height: number): void { context.resize(width, height); } - private _removeDeviceResource () { + private _removeDeviceResource (): void { const pipeline: any = context.pipeline; const resourceUses = pipeline.resourceUses; const deletes: string[] = []; @@ -1826,7 +1826,7 @@ export class Executor { } } - execute (rg: RenderGraph) { + execute (rg: RenderGraph): void { context.renderGraph = rg; context.reset(); this._removeDeviceResource(); @@ -1838,7 +1838,7 @@ export class Executor { context.device.queue.submit([cmdBuff]); } - release () { + release (): void { context.devicePasses.clear(); for (const [k, v] of context.deviceTextures) { v.release(); @@ -1880,13 +1880,13 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { constructor () { super(); } - clear (value: ClearView[]) { + clear (value: ClearView[]): void { // do nothing } - viewport (value: Viewport) { + viewport (value: Viewport): void { // do nothing } - rasterPass (pass: RasterPass) { + rasterPass (pass: RasterPass): void { if (!this.rg.getValid(this.passID)) return; const devicePasses = context.devicePasses; const passHash = pass.hashValue; @@ -1900,14 +1900,14 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { this.currPass.resetResource(this.passID, pass); } } - rasterSubpass (value: RasterSubpass) {} - computeSubpass (value: ComputeSubpass) {} - compute (value: ComputePass) {} - resolve (value: ResolvePass) {} - copy (value: CopyPass) {} - move (value: MovePass) {} - raytrace (value: RaytracePass) {} - queue (value: RenderQueue) { + rasterSubpass (value: RasterSubpass): void {} + computeSubpass (value: ComputeSubpass): void {} + compute (value: ComputePass): void {} + resolve (value: ResolvePass): void {} + copy (value: CopyPass): void {} + move (value: MovePass): void {} + raytrace (value: RaytracePass): void {} + queue (value: RenderQueue): void { if (!this.rg.getValid(this.queueID)) return; const deviceQueue = context.pools.addDeviceQueue(); deviceQueue.init(this.currPass!, value, this.queueID); @@ -1922,32 +1922,32 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { } } } - scene (value: SceneData) { + scene (value: SceneData): void { if (!this.rg.getValid(this.sceneID)) return; const graphScene = context.pools.addGraphScene(); graphScene.init(value, null, this.sceneID); this.currQueue!.addSceneTask(graphScene); } - blit (value: Blit) { + blit (value: Blit): void { if (!this.rg.getValid(this.sceneID)) return; const graphScene = context.pools.addGraphScene(); graphScene.init(null, value, -1); this.currQueue!.addSceneTask(graphScene); } - dispatch (value: Dispatch) {} + dispatch (value: Dispatch): void {} } class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { constructor () { super(); } - clear (value: ClearView[]) { + clear (value: ClearView[]): void { // do nothing } - viewport (value: Viewport) { + viewport (value: Viewport): void { // do nothing } - rasterPass (pass: RasterPass) { + rasterPass (pass: RasterPass): void { const devicePasses = context.devicePasses; const passHash = pass.hashValue; const currPass = devicePasses.get(passHash); @@ -1957,21 +1957,21 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor this.currPass.record(); this.currPass.postPass(); } - rasterSubpass (value: RasterSubpass) {} - computeSubpass (value: ComputeSubpass) {} - resolve (value: ResolvePass) {} - compute (value: ComputePass) {} - copy (value: CopyPass) {} - move (value: MovePass) {} - raytrace (value: RaytracePass) {} - queue (value: RenderQueue) { + rasterSubpass (value: RasterSubpass): void {} + computeSubpass (value: ComputeSubpass): void {} + resolve (value: ResolvePass): void {} + compute (value: ComputePass): void {} + copy (value: CopyPass): void {} + move (value: MovePass): void {} + raytrace (value: RaytracePass): void {} + queue (value: RenderQueue): void { // collect scene results } - scene (value: SceneData) { + scene (value: SceneData): void { // scene command list finished } - blit (value: Blit) {} - dispatch (value: Dispatch) {} + blit (value: Blit): void {} + dispatch (value: Dispatch): void {} } export class RenderVisitor extends DefaultVisitor { @@ -1987,14 +1987,14 @@ export class RenderVisitor extends DefaultVisitor { this._colorMap = new VectorGraphColorMap(context.renderGraph.numVertices()); } - get graphView () { return this._graphView; } - get colorMap () { return this._colorMap; } - discoverVertex (u: number, gv: ReferenceGraphView) { + get graphView (): ReferenceGraphView { return this._graphView; } + get colorMap (): VectorGraphColorMap { return this._colorMap; } + discoverVertex (u: number, gv: ReferenceGraphView): void { const g = gv.g; this._preVisitor.applyID(u); g.visitVertex(this._preVisitor, u); } - finishVertex (v: number, gv: ReferenceGraphView) { + finishVertex (v: number, gv: ReferenceGraphView): void { const g = gv.g; g.visitVertex(this._postVisitor, v); } diff --git a/cocos/rendering/custom/graph.ts b/cocos/rendering/custom/graph.ts index d3113f99111..118364d5c02 100644 --- a/cocos/rendering/custom/graph.ts +++ b/cocos/rendering/custom/graph.ts @@ -135,7 +135,7 @@ export class OutEI implements IterableIterator { this.iterator = iterator; this.source = source; } - [Symbol.iterator] () { + [Symbol.iterator] (): OutEI { return this; } next (): IteratorResult { @@ -156,7 +156,7 @@ export class OutEPI implements IterableIterator { this.iterator = iterator; this.source = source; } - [Symbol.iterator] () { + [Symbol.iterator] (): OutEPI { return this; } next (): IteratorResult { @@ -183,7 +183,7 @@ export class InEI implements IterableIterator { this.iterator = iterator; this.source = source; } - [Symbol.iterator] () { + [Symbol.iterator] (): InEI { return this; } next (): IteratorResult { @@ -204,7 +204,7 @@ export class InEPI implements IterableIterator { this.iterator = iterator; this.source = source; } - [Symbol.iterator] () { + [Symbol.iterator] (): InEPI { return this; } next (): IteratorResult { @@ -262,7 +262,7 @@ export class AdjI implements IterableIterator { this.graph = graph; this.iterator = iterator; } - [Symbol.iterator] () { + [Symbol.iterator] (): AdjI { return this; } next (): IteratorResult { @@ -282,7 +282,7 @@ export class AdjPI implements IterableIterator { this.graph = graph; this.iterator = iterator; } - [Symbol.iterator] () { + [Symbol.iterator] (): AdjPI { return this; } next (): IteratorResult { @@ -749,7 +749,7 @@ implements IncidenceGraph, VertexListGraph { this.edge_parallel_category = parallel.allow; this.traversal_category = traversal.incidence | traversal.vertex_list; } - nullVertex () { + nullVertex (): vertex_descriptor | null { return this.g.nullVertex(); } edge (u: vertex_descriptor, v: vertex_descriptor): boolean { diff --git a/cocos/rendering/custom/index.ts b/cocos/rendering/custom/index.ts index fc86fff574f..47d16af5b4c 100644 --- a/cocos/rendering/custom/index.ts +++ b/cocos/rendering/custom/index.ts @@ -60,7 +60,7 @@ export function createCustomPipeline (): BasicPipeline { export const customPipelineBuilderMap = new Map(); -export function setCustomPipeline (name: string, builder: PipelineBuilder) { +export function setCustomPipeline (name: string, builder: PipelineBuilder): void { customPipelineBuilderMap.set(name, builder); } export function getCustomPipeline (name: string): PipelineBuilder { @@ -76,7 +76,7 @@ export function getCustomPipeline (name: string): PipelineBuilder { return builder; } -function addCustomBuiltinPipelines (map: Map) { +function addCustomBuiltinPipelines (map: Map): void { map.set('Forward', new ForwardPipelineBuilder()); map.set('Deferred', new DeferredPipelineBuilder()); map.set('Deprecated', new CustomPipelineBuilder()); @@ -84,7 +84,7 @@ function addCustomBuiltinPipelines (map: Map) { addCustomBuiltinPipelines(customPipelineBuilderMap); -export function init (device: Device, arrayBuffer: ArrayBuffer | null) { +export function init (device: Device, arrayBuffer: ArrayBuffer | null): void { if (arrayBuffer) { const readBinaryData = new BinaryInputArchive(arrayBuffer); loadLayoutGraphData(readBinaryData, defaultLayoutGraph); @@ -92,7 +92,7 @@ export function init (device: Device, arrayBuffer: ArrayBuffer | null) { initializeLayoutGraphData(device, defaultLayoutGraph); } -export function destroy () { +export function destroy (): void { terminateLayoutGraphData(defaultLayoutGraph); } diff --git a/cocos/rendering/custom/layout-graph-utils.ts b/cocos/rendering/custom/layout-graph-utils.ts index eb0fc7ec7d2..6787df02880 100644 --- a/cocos/rendering/custom/layout-graph-utils.ts +++ b/cocos/rendering/custom/layout-graph-utils.ts @@ -219,7 +219,7 @@ function getVisibilityName (stage: ShaderStageFlagBit): string { // print LayoutGraphData export class PrintVisitor extends DefaultVisitor { - discoverVertex (u: number, g: LayoutGraphData) { + discoverVertex (u: number, g: LayoutGraphData): void { const ppl: PipelineLayoutData = g.getLayout(u); const name: string = g._names[u]; const freq: UpdateFrequency = g._updateFrequencies[u]; @@ -232,11 +232,11 @@ export class PrintVisitor extends DefaultVisitor { this.space = indent(this.space); // eslint-disable-next-line no-loop-func - ppl.descriptorSets.forEach((value, key) => { + ppl.descriptorSets.forEach((value, key): void => { this.oss += `${this.space}DescriptorSet<${getUpdateFrequencyName(key)}> {\n`; this.space = indent(this.space); const uniformBlocks = value.descriptorSetLayoutData.uniformBlocks; - uniformBlocks.forEach((uniformBlock, attrNameID) => { + uniformBlocks.forEach((uniformBlock, attrNameID): void => { const name = g.valueNames[attrNameID]; this.oss += `${this.space}UniformBlock "${name}" {\n`; for (const u of uniformBlock.members) { @@ -281,7 +281,7 @@ export class PrintVisitor extends DefaultVisitor { this.oss += `${this.space}}\n`; }); } - finishVertex (v: number, g: LayoutGraphData) { + finishVertex (v: number, g: LayoutGraphData): void { this.space = unindent(this.space); this.oss += `${this.space}}\n`; } @@ -305,11 +305,11 @@ function convertDescriptorBlock (block: DescriptorBlock): DescriptorBlockFlatten // sort descriptors by name const descriptors = Array.from(block.descriptors).sort( - (a, b) => String(a[0]).localeCompare(b[0]), + (a, b): number => String(a[0]).localeCompare(b[0]), ); // flatten descriptors - descriptors.forEach((v: [string, Descriptor]) => { + descriptors.forEach((v: [string, Descriptor]): void => { const name: string = v[0]; const d = v[1]; flattened.descriptorNames.push(name); @@ -318,11 +318,11 @@ function convertDescriptorBlock (block: DescriptorBlock): DescriptorBlockFlatten // sort uniforms by name const uniformBlocks = Array.from(block.uniformBlocks).sort( - (a, b) => String(a[0]).localeCompare(b[0]), + (a, b): number => String(a[0]).localeCompare(b[0]), ); // flatten uniforms - uniformBlocks.forEach((v: [string, UniformBlock]) => { + uniformBlocks.forEach((v: [string, UniformBlock]): void => { const name = v[0]; const uniformBlock = v[1]; flattened.uniformBlockNames.push(name); @@ -337,7 +337,7 @@ function convertDescriptorBlock (block: DescriptorBlock): DescriptorBlockFlatten // cache of descriptor blocks class DescriptorCounter { - public addDescriptor (key: string, name: string, count: number) { + public addDescriptor (key: string, name: string, count: number): void { // key is DescriptorBlockIndex // name is Descriptor name // count is Descriptor count @@ -357,7 +357,7 @@ class DescriptorCounter { // print LayoutGraph (not LayoutGraphData) class LayoutGraphPrintVisitor extends DefaultVisitor { - discoverVertex (v: number, g: LayoutGraph) { + discoverVertex (v: number, g: LayoutGraph): void { const info: DescriptorDB = g.getDescriptors(v); const name = g.getName(v); @@ -376,10 +376,10 @@ class LayoutGraphPrintVisitor extends DefaultVisitor { this.space = indent(this.space); const sortedMap: Map = new Map( - Array.from(info.blocks).sort((a, b) => String(a[0]).localeCompare(b[0])), + Array.from(info.blocks).sort((a, b): number => String(a[0]).localeCompare(b[0])), ); - sortedMap.forEach((block: DescriptorBlock, key: string) => { + sortedMap.forEach((block: DescriptorBlock, key: string): void => { const index: DescriptorBlockIndex = JSON.parse(key); const flat = convertDescriptorBlock(block); this.oss += `${this.space}DescriptorBlock {\n`; @@ -402,7 +402,7 @@ class LayoutGraphPrintVisitor extends DefaultVisitor { this.oss += `${this.space}}\n`; }); } - finishVertex (v: number, g: LayoutGraphData) { + finishVertex (v: number, g: LayoutGraphData): void { this.space = unindent(this.space); this.oss += `${this.space}}\n`; } @@ -447,7 +447,7 @@ export class VisibilityIndex { // descriptors of same visibility export class VisibilityBlock { - public mergeVisibility (name: string, vis: ShaderStageFlagBit) { + public mergeVisibility (name: string, vis: ShaderStageFlagBit): void { // for each descriptor, merge visibility // rate must >= PER_PHASE const v0 = this.descriptors.get(name); @@ -517,7 +517,7 @@ export class VisibilityGraph { EffectAsset.ISamplerTextureInfo[] | EffectAsset.ITextureInfo[], db: VisibilityDB, - ) { + ): void { const blockIndex = new VisibilityIndex( rate, ParameterType.TABLE, @@ -528,7 +528,7 @@ export class VisibilityGraph { block.mergeVisibility(info.name, info.stageFlags); } } - public mergeEffect (asset: EffectAsset) { + public mergeEffect (asset: EffectAsset): void { for (const tech of asset.techniques) { for (const pass of tech.passes) { const programName = pass.program; @@ -666,7 +666,7 @@ export class LayoutGraphInfo { } return uniformBlock; } - private addDescriptor (block: DescriptorBlock, name: string, type = Type.UNKNOWN) { + private addDescriptor (block: DescriptorBlock, name: string, type = Type.UNKNOWN): void { const value = block.descriptors.get(name); if (value === undefined) { block.descriptors.set(name, new Descriptor(type)); @@ -689,7 +689,7 @@ export class LayoutGraphInfo { console.warn(`Uniform block ${name} is inconsistent in the same block`); } } - private buildBlocks (visDB: VisibilityDB, rate: UpdateFrequency, blocks: EffectAsset.IBlockInfo[], db: DescriptorDB, counter: DescriptorCounter) { + private buildBlocks (visDB: VisibilityDB, rate: UpdateFrequency, blocks: EffectAsset.IBlockInfo[], db: DescriptorDB, counter: DescriptorCounter): void { const visBlock = visDB.getBlock({ updateFrequency: rate, parameterType: ParameterType.TABLE, @@ -717,7 +717,7 @@ export class LayoutGraphInfo { rate: UpdateFrequency, infoArray: EffectAsset.IBufferInfo[], type: Type, db: DescriptorDB, counter: DescriptorCounter, - ) { + ): void { const visBlock = visDB.getBlock({ updateFrequency: rate, parameterType: ParameterType.TABLE, @@ -745,7 +745,7 @@ export class LayoutGraphInfo { order: DescriptorTypeOrder, infoArray: EffectAsset.ISamplerInfo[] | EffectAsset.IInputAttachmentInfo[], type: Type, db: DescriptorDB, counter: DescriptorCounter, - ) { + ): void { const visBlock = visDB.getBlock({ updateFrequency: rate, parameterType: ParameterType.TABLE, @@ -773,7 +773,7 @@ export class LayoutGraphInfo { order: DescriptorTypeOrder, infoArray: EffectAsset.IImageInfo[] | EffectAsset.ISamplerTextureInfo[] | EffectAsset.ITextureInfo[], db: DescriptorDB, counter: DescriptorCounter, - ) { + ): void { const visBlock = visDB.getBlock({ updateFrequency: rate, parameterType: ParameterType.TABLE, @@ -840,7 +840,7 @@ export class LayoutGraphInfo { } // update max capacity and debug info - counter.counter.forEach((v: number, key: string) => { + counter.counter.forEach((v: number, key: string): void => { const block = this.getDescriptorBlock(key, db); if (v > block.capacity) { block.capacity = Math.max(block.capacity, v); @@ -1027,7 +1027,7 @@ function sortDescriptorBlocks (lhs: [string, T], rhs: [string, T]): number { } // build LayoutGraphData -function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuilder2) { +function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuilder2): void { for (const v of graph.vertices()) { const db = graph.getDescriptors(v); let minLevel = UpdateFrequency.PER_INSTANCE; @@ -1083,7 +1083,7 @@ function buildLayoutGraphDataImpl (graph: LayoutGraph, builder: LayoutGraphBuild const flattenedBlocks = Array.from(db.blocks).sort(sortDescriptorBlocks); - flattenedBlocks.forEach((value: [string, DescriptorBlock]) => { + flattenedBlocks.forEach((value: [string, DescriptorBlock]): void => { const key = value[0]; const block = value[1]; const index: DescriptorBlockIndex = JSON.parse(key); @@ -1263,13 +1263,13 @@ class LayoutGraphBuilder2 { readonly lg: LayoutGraphData; } -export function buildLayoutGraphData (lg: LayoutGraph, lgData: LayoutGraphData) { +export function buildLayoutGraphData (lg: LayoutGraph, lgData: LayoutGraphData): void { const builder = new LayoutGraphBuilder2(lgData); buildLayoutGraphDataImpl(lg, builder); builder.compile(); } -function createDescriptorInfo (layoutData: DescriptorSetLayoutData, info: DescriptorSetLayoutInfo) { +function createDescriptorInfo (layoutData: DescriptorSetLayoutData, info: DescriptorSetLayoutInfo): void { for (let i = 0; i < layoutData.descriptorBlocks.length; ++i) { const block = layoutData.descriptorBlocks[i]; let slot = block.offset; @@ -1287,7 +1287,7 @@ function createDescriptorInfo (layoutData: DescriptorSetLayoutData, info: Descri } } -function createDescriptorSetLayout (device: Device | null, layoutData: DescriptorSetLayoutData) { +function createDescriptorSetLayout (device: Device | null, layoutData: DescriptorSetLayoutData): DescriptorSetLayout | null { const info: DescriptorSetLayoutInfo = new DescriptorSetLayoutInfo(); createDescriptorInfo(layoutData, info); @@ -1298,10 +1298,10 @@ function createDescriptorSetLayout (device: Device | null, layoutData: Descripto } } -export function createGfxDescriptorSetsAndPipelines (device: Device | null, g: LayoutGraphData) { +export function createGfxDescriptorSetsAndPipelines (device: Device | null, g: LayoutGraphData): void { for (let i = 0; i < g._layouts.length; ++i) { const ppl: PipelineLayoutData = g.getLayout(i); - ppl.descriptorSets.forEach((value, key) => { + ppl.descriptorSets.forEach((value, key): void => { const level = value; const layoutData = level.descriptorSetLayoutData; if (device) { @@ -1489,7 +1489,7 @@ let _emptyDescriptorSetLayout: DescriptorSetLayout; let _emptyPipelineLayout: PipelineLayout; function populatePipelineLayoutInfo (layout: PipelineLayoutData, - rate: UpdateFrequency, info: PipelineLayoutInfo) { + rate: UpdateFrequency, info: PipelineLayoutInfo): void { const set = layout.descriptorSets.get(rate); if (set && set.descriptorSetLayout) { info.setLayouts.push(set.descriptorSetLayout); @@ -1499,7 +1499,7 @@ function populatePipelineLayoutInfo (layout: PipelineLayoutData, } // initialize layout graph module -export function initializeLayoutGraphData (device: Device, lg: LayoutGraphData) { +export function initializeLayoutGraphData (device: Device, lg: LayoutGraphData): void { // create descriptor sets _emptyDescriptorSetLayout = device.createDescriptorSetLayout(new DescriptorSetLayoutInfo()); _emptyPipelineLayout = device.createPipelineLayout(new PipelineLayoutInfo()); @@ -1534,7 +1534,7 @@ export function initializeLayoutGraphData (device: Device, lg: LayoutGraphData) } // terminate layout graph module -export function terminateLayoutGraphData (lg: LayoutGraphData) { +export function terminateLayoutGraphData (lg: LayoutGraphData): void { for (const v of lg.vertices()) { const layoutData = lg.getLayout(v); for (const [_, set] of layoutData.descriptorSets) { @@ -1706,7 +1706,7 @@ export function getPerInstanceDescriptorSetLayoutData (lg: LayoutGraphData, return set.descriptorSetLayoutData; } -export function getBinding (layout: DescriptorSetLayoutData, nameID: number) { +export function getBinding (layout: DescriptorSetLayoutData, nameID: number): number { const binding = layout.bindingMap.get(nameID); if (binding === undefined) { return 0xFFFFFFFF; diff --git a/cocos/rendering/custom/layout-graph.ts b/cocos/rendering/custom/layout-graph.ts index 8d6ece7be93..9ec1346ce68 100644 --- a/cocos/rendering/custom/layout-graph.ts +++ b/cocos/rendering/custom/layout-graph.ts @@ -1067,7 +1067,7 @@ export class LayoutGraphData implements BidirectionalGraph getUpdate (v: number): UpdateFrequency { return this._updateFrequencies[v]; } - setUpdate (v: number, value: UpdateFrequency) { + setUpdate (v: number, value: UpdateFrequency): void { this._updateFrequencies[v] = value; } getLayout (v: number): PipelineLayoutData { @@ -1260,7 +1260,7 @@ export class LayoutGraphData implements BidirectionalGraph constantMacros = ''; } -export function saveDescriptorDB (ar: OutputArchive, v: DescriptorDB) { +export function saveDescriptorDB (ar: OutputArchive, v: DescriptorDB): void { ar.writeNumber(v.blocks.size); // Map for (const [k1, v1] of v.blocks) { saveDescriptorBlockIndex(ar, JSON.parse(k1)); @@ -1268,7 +1268,7 @@ export function saveDescriptorDB (ar: OutputArchive, v: DescriptorDB) { } } -export function loadDescriptorDB (ar: InputArchive, v: DescriptorDB) { +export function loadDescriptorDB (ar: InputArchive, v: DescriptorDB): void { let sz = 0; sz = ar.readNumber(); // Map for (let i1 = 0; i1 !== sz; ++i1) { @@ -1280,14 +1280,14 @@ export function loadDescriptorDB (ar: InputArchive, v: DescriptorDB) { } } -export function saveRenderPhase (ar: OutputArchive, v: RenderPhase) { +export function saveRenderPhase (ar: OutputArchive, v: RenderPhase): void { ar.writeNumber(v.shaders.size); // Set for (const v1 of v.shaders) { ar.writeString(v1); } } -export function loadRenderPhase (ar: InputArchive, v: RenderPhase) { +export function loadRenderPhase (ar: InputArchive, v: RenderPhase): void { let sz = 0; sz = ar.readNumber(); // Set for (let i1 = 0; i1 !== sz; ++i1) { @@ -1296,7 +1296,7 @@ export function loadRenderPhase (ar: InputArchive, v: RenderPhase) { } } -export function saveLayoutGraph (ar: OutputArchive, g: LayoutGraph) { +export function saveLayoutGraph (ar: OutputArchive, g: LayoutGraph): void { const numVertices = g.numVertices(); const numEdges = g.numEdges(); ar.writeNumber(numVertices); @@ -1335,7 +1335,7 @@ export function saveLayoutGraph (ar: OutputArchive, g: LayoutGraph) { } } -export function loadLayoutGraph (ar: InputArchive, g: LayoutGraph) { +export function loadLayoutGraph (ar: InputArchive, g: LayoutGraph): void { const numVertices = ar.readNumber(); const numEdges = ar.readNumber(); const numStages = ar.readNumber(); @@ -1364,21 +1364,21 @@ export function loadLayoutGraph (ar: InputArchive, g: LayoutGraph) { } } -export function saveUniformData (ar: OutputArchive, v: UniformData) { +export function saveUniformData (ar: OutputArchive, v: UniformData): void { ar.writeNumber(v.uniformID); ar.writeNumber(v.uniformType); ar.writeNumber(v.offset); ar.writeNumber(v.size); } -export function loadUniformData (ar: InputArchive, v: UniformData) { +export function loadUniformData (ar: InputArchive, v: UniformData): void { v.uniformID = ar.readNumber(); v.uniformType = ar.readNumber(); v.offset = ar.readNumber(); v.size = ar.readNumber(); } -export function saveUniformBlockData (ar: OutputArchive, v: UniformBlockData) { +export function saveUniformBlockData (ar: OutputArchive, v: UniformBlockData): void { ar.writeNumber(v.bufferSize); ar.writeNumber(v.uniforms.length); // UniformData[] for (const v1 of v.uniforms) { @@ -1386,7 +1386,7 @@ export function saveUniformBlockData (ar: OutputArchive, v: UniformBlockData) { } } -export function loadUniformBlockData (ar: InputArchive, v: UniformBlockData) { +export function loadUniformBlockData (ar: InputArchive, v: UniformBlockData): void { v.bufferSize = ar.readNumber(); let sz = 0; sz = ar.readNumber(); // UniformData[] @@ -1398,19 +1398,19 @@ export function loadUniformBlockData (ar: InputArchive, v: UniformBlockData) { } } -export function saveDescriptorData (ar: OutputArchive, v: DescriptorData) { +export function saveDescriptorData (ar: OutputArchive, v: DescriptorData): void { ar.writeNumber(v.descriptorID); ar.writeNumber(v.type); ar.writeNumber(v.count); } -export function loadDescriptorData (ar: InputArchive, v: DescriptorData) { +export function loadDescriptorData (ar: InputArchive, v: DescriptorData): void { v.descriptorID = ar.readNumber(); v.type = ar.readNumber(); v.count = ar.readNumber(); } -export function saveDescriptorBlockData (ar: OutputArchive, v: DescriptorBlockData) { +export function saveDescriptorBlockData (ar: OutputArchive, v: DescriptorBlockData): void { ar.writeNumber(v.type); ar.writeNumber(v.visibility); ar.writeNumber(v.offset); @@ -1421,7 +1421,7 @@ export function saveDescriptorBlockData (ar: OutputArchive, v: DescriptorBlockDa } } -export function loadDescriptorBlockData (ar: InputArchive, v: DescriptorBlockData) { +export function loadDescriptorBlockData (ar: InputArchive, v: DescriptorBlockData): void { v.type = ar.readNumber(); v.visibility = ar.readNumber(); v.offset = ar.readNumber(); @@ -1436,7 +1436,7 @@ export function loadDescriptorBlockData (ar: InputArchive, v: DescriptorBlockDat } } -export function saveDescriptorSetLayoutData (ar: OutputArchive, v: DescriptorSetLayoutData) { +export function saveDescriptorSetLayoutData (ar: OutputArchive, v: DescriptorSetLayoutData): void { ar.writeNumber(v.slot); ar.writeNumber(v.capacity); ar.writeNumber(v.uniformBlockCapacity); @@ -1457,7 +1457,7 @@ export function saveDescriptorSetLayoutData (ar: OutputArchive, v: DescriptorSet } } -export function loadDescriptorSetLayoutData (ar: InputArchive, v: DescriptorSetLayoutData) { +export function loadDescriptorSetLayoutData (ar: InputArchive, v: DescriptorSetLayoutData): void { v.slot = ar.readNumber(); v.capacity = ar.readNumber(); v.uniformBlockCapacity = ar.readNumber(); @@ -1485,21 +1485,21 @@ export function loadDescriptorSetLayoutData (ar: InputArchive, v: DescriptorSetL } } -export function saveDescriptorSetData (ar: OutputArchive, v: DescriptorSetData) { +export function saveDescriptorSetData (ar: OutputArchive, v: DescriptorSetData): void { saveDescriptorSetLayoutData(ar, v.descriptorSetLayoutData); saveDescriptorSetLayoutInfo(ar, v.descriptorSetLayoutInfo); // skip, v.descriptorSetLayout: DescriptorSetLayout // skip, v.descriptorSet: DescriptorSet } -export function loadDescriptorSetData (ar: InputArchive, v: DescriptorSetData) { +export function loadDescriptorSetData (ar: InputArchive, v: DescriptorSetData): void { loadDescriptorSetLayoutData(ar, v.descriptorSetLayoutData); loadDescriptorSetLayoutInfo(ar, v.descriptorSetLayoutInfo); // skip, v.descriptorSetLayout: DescriptorSetLayout // skip, v.descriptorSet: DescriptorSet } -export function savePipelineLayoutData (ar: OutputArchive, v: PipelineLayoutData) { +export function savePipelineLayoutData (ar: OutputArchive, v: PipelineLayoutData): void { ar.writeNumber(v.descriptorSets.size); // Map for (const [k1, v1] of v.descriptorSets) { ar.writeNumber(k1); @@ -1507,7 +1507,7 @@ export function savePipelineLayoutData (ar: OutputArchive, v: PipelineLayoutData } } -export function loadPipelineLayoutData (ar: InputArchive, v: PipelineLayoutData) { +export function loadPipelineLayoutData (ar: InputArchive, v: PipelineLayoutData): void { let sz = 0; sz = ar.readNumber(); // Map for (let i1 = 0; i1 !== sz; ++i1) { @@ -1518,7 +1518,7 @@ export function loadPipelineLayoutData (ar: InputArchive, v: PipelineLayoutData) } } -export function saveShaderBindingData (ar: OutputArchive, v: ShaderBindingData) { +export function saveShaderBindingData (ar: OutputArchive, v: ShaderBindingData): void { ar.writeNumber(v.descriptorBindings.size); // Map for (const [k1, v1] of v.descriptorBindings) { ar.writeNumber(k1); @@ -1526,7 +1526,7 @@ export function saveShaderBindingData (ar: OutputArchive, v: ShaderBindingData) } } -export function loadShaderBindingData (ar: InputArchive, v: ShaderBindingData) { +export function loadShaderBindingData (ar: InputArchive, v: ShaderBindingData): void { let sz = 0; sz = ar.readNumber(); // Map for (let i1 = 0; i1 !== sz; ++i1) { @@ -1536,7 +1536,7 @@ export function loadShaderBindingData (ar: InputArchive, v: ShaderBindingData) { } } -export function saveShaderLayoutData (ar: OutputArchive, v: ShaderLayoutData) { +export function saveShaderLayoutData (ar: OutputArchive, v: ShaderLayoutData): void { ar.writeNumber(v.layoutData.size); // Map for (const [k1, v1] of v.layoutData) { ar.writeNumber(k1); @@ -1549,7 +1549,7 @@ export function saveShaderLayoutData (ar: OutputArchive, v: ShaderLayoutData) { } } -export function loadShaderLayoutData (ar: InputArchive, v: ShaderLayoutData) { +export function loadShaderLayoutData (ar: InputArchive, v: ShaderLayoutData): void { let sz = 0; sz = ar.readNumber(); // Map for (let i1 = 0; i1 !== sz; ++i1) { @@ -1567,14 +1567,14 @@ export function loadShaderLayoutData (ar: InputArchive, v: ShaderLayoutData) { } } -export function saveTechniqueData (ar: OutputArchive, v: TechniqueData) { +export function saveTechniqueData (ar: OutputArchive, v: TechniqueData): void { ar.writeNumber(v.passes.length); // ShaderLayoutData[] for (const v1 of v.passes) { saveShaderLayoutData(ar, v1); } } -export function loadTechniqueData (ar: InputArchive, v: TechniqueData) { +export function loadTechniqueData (ar: InputArchive, v: TechniqueData): void { let sz = 0; sz = ar.readNumber(); // ShaderLayoutData[] v.passes.length = sz; @@ -1585,7 +1585,7 @@ export function loadTechniqueData (ar: InputArchive, v: TechniqueData) { } } -export function saveEffectData (ar: OutputArchive, v: EffectData) { +export function saveEffectData (ar: OutputArchive, v: EffectData): void { ar.writeNumber(v.techniques.size); // Map for (const [k1, v1] of v.techniques) { ar.writeString(k1); @@ -1593,7 +1593,7 @@ export function saveEffectData (ar: OutputArchive, v: EffectData) { } } -export function loadEffectData (ar: InputArchive, v: EffectData) { +export function loadEffectData (ar: InputArchive, v: EffectData): void { let sz = 0; sz = ar.readNumber(); // Map for (let i1 = 0; i1 !== sz; ++i1) { @@ -1604,17 +1604,17 @@ export function loadEffectData (ar: InputArchive, v: EffectData) { } } -export function saveShaderProgramData (ar: OutputArchive, v: ShaderProgramData) { +export function saveShaderProgramData (ar: OutputArchive, v: ShaderProgramData): void { savePipelineLayoutData(ar, v.layout); // skip, v.pipelineLayout: PipelineLayout } -export function loadShaderProgramData (ar: InputArchive, v: ShaderProgramData) { +export function loadShaderProgramData (ar: InputArchive, v: ShaderProgramData): void { loadPipelineLayoutData(ar, v.layout); // skip, v.pipelineLayout: PipelineLayout } -export function saveRenderStageData (ar: OutputArchive, v: RenderStageData) { +export function saveRenderStageData (ar: OutputArchive, v: RenderStageData): void { ar.writeNumber(v.descriptorVisibility.size); // Map for (const [k1, v1] of v.descriptorVisibility) { ar.writeNumber(k1); @@ -1622,7 +1622,7 @@ export function saveRenderStageData (ar: OutputArchive, v: RenderStageData) { } } -export function loadRenderStageData (ar: InputArchive, v: RenderStageData) { +export function loadRenderStageData (ar: InputArchive, v: RenderStageData): void { let sz = 0; sz = ar.readNumber(); // Map for (let i1 = 0; i1 !== sz; ++i1) { @@ -1632,7 +1632,7 @@ export function loadRenderStageData (ar: InputArchive, v: RenderStageData) { } } -export function saveRenderPhaseData (ar: OutputArchive, v: RenderPhaseData) { +export function saveRenderPhaseData (ar: OutputArchive, v: RenderPhaseData): void { ar.writeString(v.rootSignature); ar.writeNumber(v.shaderPrograms.length); // ShaderProgramData[] for (const v1 of v.shaderPrograms) { @@ -1646,7 +1646,7 @@ export function saveRenderPhaseData (ar: OutputArchive, v: RenderPhaseData) { // skip, v.pipelineLayout: PipelineLayout } -export function loadRenderPhaseData (ar: InputArchive, v: RenderPhaseData) { +export function loadRenderPhaseData (ar: InputArchive, v: RenderPhaseData): void { v.rootSignature = ar.readString(); let sz = 0; sz = ar.readNumber(); // ShaderProgramData[] @@ -1665,7 +1665,7 @@ export function loadRenderPhaseData (ar: InputArchive, v: RenderPhaseData) { // skip, v.pipelineLayout: PipelineLayout } -export function saveLayoutGraphData (ar: OutputArchive, g: LayoutGraphData) { +export function saveLayoutGraphData (ar: OutputArchive, g: LayoutGraphData): void { const numVertices = g.numVertices(); const numEdges = g.numEdges(); ar.writeNumber(numVertices); @@ -1729,7 +1729,7 @@ export function saveLayoutGraphData (ar: OutputArchive, g: LayoutGraphData) { } } -export function loadLayoutGraphData (ar: InputArchive, g: LayoutGraphData) { +export function loadLayoutGraphData (ar: InputArchive, g: LayoutGraphData): void { const numVertices = ar.readNumber(); const numEdges = ar.readNumber(); const numStages = ar.readNumber(); diff --git a/cocos/rendering/custom/pipeline-define.ts b/cocos/rendering/custom/pipeline-define.ts index 1db8f3c7489..339988d44b1 100644 --- a/cocos/rendering/custom/pipeline-define.ts +++ b/cocos/rendering/custom/pipeline-define.ts @@ -6,7 +6,7 @@ import { Camera, Light, LightType, ProbeType, ReflectionProbe, ShadowType } from import { supportsR32FloatTexture } from '../define'; import { AntiAliasing, GBufferInfo, getRTFormatBeforeToneMapping, LightingInfo, PostInfo, ShadowInfo, getLoadOpOfClearFlag, getRenderArea, updateCameraUBO, validPunctualLightsCulling } from './define'; -import { BasicPipeline } from './pipeline'; +import { BasicPipeline, BasicRenderPassBuilder } from './pipeline'; import { AttachmentType, LightInfo, QueueHint, ResourceResidency, SceneFlags } from './types'; import { SRGBToLinear, getProfilerCamera } from '../pipeline-funcs'; @@ -70,7 +70,7 @@ export function prepareResource (ppl: BasicPipeline, camera: Camera, return info; } -function buildShadowRes (ppl: BasicPipeline, name: string, width, height) { +function buildShadowRes (ppl: BasicPipeline, name: string, width, height): void { const fboW = width; const fboH = height; const shadowMapName = name; @@ -140,7 +140,7 @@ let shadowPass; function buildShadowPass (passName: Readonly, ppl: BasicPipeline, camera: Camera, light: Light, level: number, - width: Readonly, height: Readonly) { + width: Readonly, height: Readonly): void { const fboW = width; const fboH = height; const area = getRenderArea(camera, width, height, light, level); @@ -160,7 +160,7 @@ function buildShadowPass (passName: Readonly, SceneFlags.SHADOW_CASTER); queue.setViewport(new Viewport(area.x, area.y, area.width, area.height)); } -export function setupShadowPass (ppl: BasicPipeline, cameraInfo: CameraInfo) { +export function setupShadowPass (ppl: BasicPipeline, cameraInfo: CameraInfo): void { if (!shadowInfo.shadowEnabled) return; const camera = cameraInfo.camera; const shadows = ppl.pipelineSceneData.shadows; @@ -192,7 +192,7 @@ export function setupShadowPass (ppl: BasicPipeline, cameraInfo: CameraInfo) { } } -export function setupForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false) { +export function setupForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false): void { const camera = cameraInfo.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -207,7 +207,7 @@ export function setupForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, isO ppl.addDepthStencil(`ForwardDepthStencil${cameraInfo.id}`, Format.DEPTH_STENCIL, width, height); } -export function updateForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false) { +export function updateForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false): void { const camera = cameraInfo.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -221,7 +221,7 @@ export function updateForwardRes (ppl: BasicPipeline, cameraInfo: CameraInfo, is ppl.updateDepthStencil(`ForwardDepthStencil${cameraInfo.id}`, width, height); } -export function setupForwardPass (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false, enabledAlpha = true) { +export function setupForwardPass (ppl: BasicPipeline, cameraInfo: CameraInfo, isOffScreen = false, enabledAlpha = true): { rtName: string; dsName: string; } { if (EDITOR) { ppl.setMacroInt('CC_PIPELINE_TYPE', 0); } @@ -273,7 +273,7 @@ export function setupForwardPass (ppl: BasicPipeline, cameraInfo: CameraInfo, is return { rtName: `ForwardColor${cameraInfo.id}`, dsName: `ForwardDepthStencil${cameraInfo.id}` }; } -export function buildReflectionProbeRes (ppl: BasicPipeline, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number) { +export function buildReflectionProbeRes (ppl: BasicPipeline, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number): void { const area = probe.renderArea(); const width = area.x; const height = area.y; @@ -289,7 +289,7 @@ export function buildReflectionProbeRes (ppl: BasicPipeline, probe: ReflectionPr ppl.updateDepthStencil(probePassDSName, width, height); } -export function setupReflectionProbeRes (ppl: BasicPipeline, info: CameraInfo) { +export function setupReflectionProbeRes (ppl: BasicPipeline, info: CameraInfo): void { if (!cclegacy.internal.reflectionProbeManager) return; const probes = cclegacy.internal.reflectionProbeManager.getProbes(); if (probes.length === 0) return; @@ -311,7 +311,7 @@ export function setupReflectionProbeRes (ppl: BasicPipeline, info: CameraInfo) { export const updateReflectionProbeRes = setupReflectionProbeRes; -function buildReflectProbePass (ppl: BasicPipeline, info: CameraInfo, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number) { +function buildReflectProbePass (ppl: BasicPipeline, info: CameraInfo, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number): void { const area = probe.renderArea(); const width = area.x; const height = area.y; @@ -332,7 +332,7 @@ function buildReflectProbePass (ppl: BasicPipeline, info: CameraInfo, probe: Ref updateCameraUBO(passBuilder as unknown as any, probeCamera, ppl); } -export function setupReflectionProbePass (ppl: BasicPipeline, info: CameraInfo) { +export function setupReflectionProbePass (ppl: BasicPipeline, info: CameraInfo): void { if (!cclegacy.internal.reflectionProbeManager) return; const probes = cclegacy.internal.reflectionProbeManager.getProbes(); if (probes.length === 0) return; @@ -352,7 +352,7 @@ export function setupReflectionProbePass (ppl: BasicPipeline, info: CameraInfo) } } const gBufferInfo = new GBufferInfo(); -export function setupGBufferRes (ppl: BasicPipeline, info: CameraInfo) { +export function setupGBufferRes (ppl: BasicPipeline, info: CameraInfo): void { const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -372,7 +372,7 @@ export function setupGBufferRes (ppl: BasicPipeline, info: CameraInfo) { gBufferInfo.ds = gBufferPassDSName; } -export function updateGBufferRes (ppl: BasicPipeline, info: CameraInfo) { +export function updateGBufferRes (ppl: BasicPipeline, info: CameraInfo): void { const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -387,7 +387,7 @@ export function updateGBufferRes (ppl: BasicPipeline, info: CameraInfo) { ppl.updateDepthStencil(gBufferPassDSName, width, height); } -export function setupGBufferPass (ppl: BasicPipeline, info: CameraInfo) { +export function setupGBufferPass (ppl: BasicPipeline, info: CameraInfo): BasicRenderPassBuilder { const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -420,7 +420,7 @@ export function setupGBufferPass (ppl: BasicPipeline, info: CameraInfo) { return gBufferPass; } -export function setupLightingRes (ppl: BasicPipeline, info: CameraInfo) { +export function setupLightingRes (ppl: BasicPipeline, info: CameraInfo): void { setupShadowRes(ppl, info); const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -433,7 +433,7 @@ export function setupLightingRes (ppl: BasicPipeline, info: CameraInfo) { ppl.addDepthStencil(deferredLightingPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); } -export function updateLightingRes (ppl: BasicPipeline, info: CameraInfo) { +export function updateLightingRes (ppl: BasicPipeline, info: CameraInfo): void { updateShadowRes(ppl, info); const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -446,7 +446,7 @@ export function updateLightingRes (ppl: BasicPipeline, info: CameraInfo) { ppl.updateDepthStencil(deferredLightingPassDS, width, height); } let lightingInfo: LightingInfo; -export function setupLightingPass (ppl: BasicPipeline, info: CameraInfo) { +export function setupLightingPass (ppl: BasicPipeline, info: CameraInfo): { rtName: string; dsName: string; } { setupShadowPass(ppl, info); if (!lightingInfo) { lightingInfo = new LightingInfo(); @@ -495,7 +495,7 @@ export function setupLightingPass (ppl: BasicPipeline, info: CameraInfo) { return { rtName: deferredLightingPassRTName, dsName: deferredLightingPassDS }; } -export function setupPostprocessRes (ppl: BasicPipeline, info: CameraInfo) { +export function setupPostprocessRes (ppl: BasicPipeline, info: CameraInfo): void { const cameraID = info.id; const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -507,7 +507,7 @@ export function setupPostprocessRes (ppl: BasicPipeline, info: CameraInfo) { ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.EXTERNAL); } -export function updatePostprocessRes (ppl: BasicPipeline, info: CameraInfo) { +export function updatePostprocessRes (ppl: BasicPipeline, info: CameraInfo): void { const cameraID = info.id; const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -521,7 +521,7 @@ export function updatePostprocessRes (ppl: BasicPipeline, info: CameraInfo) { let postInfo: PostInfo; export function setupPostprocessPass (ppl: BasicPipeline, info: CameraInfo, - inputTex: string) { + inputTex: string): { rtName: string; dsName: string; } { if (!postInfo) { postInfo = new PostInfo(); } @@ -559,7 +559,7 @@ export function setupPostprocessPass (ppl: BasicPipeline, } export function setupUIRes (ppl: BasicPipeline, - info: CameraInfo) { + info: CameraInfo): void { const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -572,7 +572,7 @@ export function setupUIRes (ppl: BasicPipeline, } export function updateUIRes (ppl: BasicPipeline, - info: CameraInfo) { + info: CameraInfo): void { const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -585,7 +585,7 @@ export function updateUIRes (ppl: BasicPipeline, } export function setupUIPass (ppl: BasicPipeline, - info: CameraInfo) { + info: CameraInfo): void { const camera = info.camera; const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; diff --git a/cocos/rendering/custom/render-graph.ts b/cocos/rendering/custom/render-graph.ts index 40cac35bb06..5bc0d77a86d 100644 --- a/cocos/rendering/custom/render-graph.ts +++ b/cocos/rendering/custom/render-graph.ts @@ -386,7 +386,7 @@ export class SubpassGraph implements BidirectionalGraph getName (v: number): string { return this._names[v]; } - setName (v: number, value: string) { + setName (v: number, value: string): void { this._names[v] = value; } getSubpass (v: number): Subpass { @@ -792,7 +792,7 @@ export class ResourceGraph implements BidirectionalGraph { // UuidGraph const key = this._names[u]; this._valueIndex.delete(key); - this._valueIndex.forEach((v) => { + this._valueIndex.forEach((v): void => { if (v > u) { --v; } }); } @@ -926,7 +926,7 @@ export class ResourceGraph implements BidirectionalGraph getName (v: number): string { return this._names[v]; } - setName (v: number, value: string) { + setName (v: number, value: string): void { this._names[v] = value; } getDesc (v: number): ResourceDesc { @@ -1801,13 +1801,13 @@ export class RenderGraph implements BidirectionalGraph getName (v: number): string { return this._names[v]; } - setName (v: number, value: string) { + setName (v: number, value: string): void { this._names[v] = value; } getLayout (v: number): string { return this._layoutNodes[v]; } - setLayout (v: number, value: string) { + setLayout (v: number, value: string): void { this._layoutNodes[v] = value; } getData (v: number): RenderData { @@ -1816,7 +1816,7 @@ export class RenderGraph implements BidirectionalGraph getValid (v: number): boolean { return this._valid[v]; } - setValid (v: number, value: boolean) { + setValid (v: number, value: boolean): void { this._valid[v] = value; } //----------------------------------------------------------------- diff --git a/cocos/rendering/custom/serialization.ts b/cocos/rendering/custom/serialization.ts index 3fc092ed126..f9c61215bf6 100644 --- a/cocos/rendering/custom/serialization.ts +++ b/cocos/rendering/custom/serialization.ts @@ -25,33 +25,33 @@ import { OutputArchive, InputArchive } from './archive'; import { Color, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, Uniform, UniformBlock } from '../../gfx'; -export function saveColor (ar: OutputArchive, v: Color) { +export function saveColor (ar: OutputArchive, v: Color): void { ar.writeNumber(v.x); ar.writeNumber(v.y); ar.writeNumber(v.z); ar.writeNumber(v.w); } -export function loadColor (ar: InputArchive, v: Color) { +export function loadColor (ar: InputArchive, v: Color): void { v.x = ar.readNumber(); v.y = ar.readNumber(); v.z = ar.readNumber(); v.w = ar.readNumber(); } -export function saveUniform (ar: OutputArchive, v: Uniform) { +export function saveUniform (ar: OutputArchive, v: Uniform): void { ar.writeString(v.name); ar.writeNumber(v.type); ar.writeNumber(v.count); } -export function loadUniform (ar: InputArchive, v: Uniform) { +export function loadUniform (ar: InputArchive, v: Uniform): void { v.name = ar.readString(); v.type = ar.readNumber(); v.count = ar.readNumber(); } -export function saveUniformBlock (ar: OutputArchive, v: UniformBlock) { +export function saveUniformBlock (ar: OutputArchive, v: UniformBlock): void { ar.writeNumber(v.set); ar.writeNumber(v.binding); ar.writeString(v.name); @@ -62,7 +62,7 @@ export function saveUniformBlock (ar: OutputArchive, v: UniformBlock) { ar.writeNumber(v.count); } -export function loadUniformBlock (ar: InputArchive, v: UniformBlock) { +export function loadUniformBlock (ar: InputArchive, v: UniformBlock): void { v.set = ar.readNumber(); v.binding = ar.readNumber(); v.name = ar.readString(); @@ -77,7 +77,7 @@ export function loadUniformBlock (ar: InputArchive, v: UniformBlock) { v.count = ar.readNumber(); } -export function saveDescriptorSetLayoutBinding (ar: OutputArchive, v: DescriptorSetLayoutBinding) { +export function saveDescriptorSetLayoutBinding (ar: OutputArchive, v: DescriptorSetLayoutBinding): void { ar.writeNumber(v.binding); ar.writeNumber(v.descriptorType); ar.writeNumber(v.count); @@ -85,7 +85,7 @@ export function saveDescriptorSetLayoutBinding (ar: OutputArchive, v: Descriptor // skip immutableSamplers; } -export function loadDescriptorSetLayoutBinding (ar: InputArchive, v: DescriptorSetLayoutBinding) { +export function loadDescriptorSetLayoutBinding (ar: InputArchive, v: DescriptorSetLayoutBinding): void { v.binding = ar.readNumber(); v.descriptorType = ar.readNumber(); v.count = ar.readNumber(); @@ -93,14 +93,14 @@ export function loadDescriptorSetLayoutBinding (ar: InputArchive, v: DescriptorS // skip immutableSamplers; } -export function saveDescriptorSetLayoutInfo (ar: OutputArchive, v: DescriptorSetLayoutInfo) { +export function saveDescriptorSetLayoutInfo (ar: OutputArchive, v: DescriptorSetLayoutInfo): void { ar.writeNumber(v.bindings.length); for (const v1 of v.bindings) { saveDescriptorSetLayoutBinding(ar, v1); } } -export function loadDescriptorSetLayoutInfo (ar: InputArchive, v: DescriptorSetLayoutInfo) { +export function loadDescriptorSetLayoutInfo (ar: InputArchive, v: DescriptorSetLayoutInfo): void { const sz = ar.readNumber(); v.bindings.length = sz; for (let i = 0; i !== sz; ++i) { diff --git a/cocos/rendering/custom/types.ts b/cocos/rendering/custom/types.ts index 74348dd2ee7..9c0dfa31309 100644 --- a/cocos/rendering/custom/types.ts +++ b/cocos/rendering/custom/types.ts @@ -566,7 +566,7 @@ export class PipelineStatistics { numInstancingUniformBlocks = 0; } -export function saveRasterView (ar: OutputArchive, v: RasterView) { +export function saveRasterView (ar: OutputArchive, v: RasterView): void { ar.writeString(v.slotName); ar.writeString(v.slotName1); ar.writeNumber(v.accessType); @@ -579,7 +579,7 @@ export function saveRasterView (ar: OutputArchive, v: RasterView) { ar.writeNumber(v.shaderStageFlags); } -export function loadRasterView (ar: InputArchive, v: RasterView) { +export function loadRasterView (ar: InputArchive, v: RasterView): void { v.slotName = ar.readString(); v.slotName1 = ar.readString(); v.accessType = ar.readNumber(); @@ -592,21 +592,21 @@ export function loadRasterView (ar: InputArchive, v: RasterView) { v.shaderStageFlags = ar.readNumber(); } -export function saveClearValue (ar: OutputArchive, v: ClearValue) { +export function saveClearValue (ar: OutputArchive, v: ClearValue): void { ar.writeNumber(v.x); ar.writeNumber(v.y); ar.writeNumber(v.z); ar.writeNumber(v.w); } -export function loadClearValue (ar: InputArchive, v: ClearValue) { +export function loadClearValue (ar: InputArchive, v: ClearValue): void { v.x = ar.readNumber(); v.y = ar.readNumber(); v.z = ar.readNumber(); v.w = ar.readNumber(); } -export function saveComputeView (ar: OutputArchive, v: ComputeView) { +export function saveComputeView (ar: OutputArchive, v: ComputeView): void { ar.writeString(v.name); ar.writeNumber(v.accessType); ar.writeNumber(v.plane); @@ -616,7 +616,7 @@ export function saveComputeView (ar: OutputArchive, v: ComputeView) { ar.writeNumber(v.shaderStageFlags); } -export function loadComputeView (ar: InputArchive, v: ComputeView) { +export function loadComputeView (ar: InputArchive, v: ComputeView): void { v.name = ar.readString(); v.accessType = ar.readNumber(); v.plane = ar.readNumber(); @@ -626,27 +626,27 @@ export function loadComputeView (ar: InputArchive, v: ComputeView) { v.shaderStageFlags = ar.readNumber(); } -export function saveLightInfo (ar: OutputArchive, v: LightInfo) { +export function saveLightInfo (ar: OutputArchive, v: LightInfo): void { // skip, v.light: Light ar.writeNumber(v.level); } -export function loadLightInfo (ar: InputArchive, v: LightInfo) { +export function loadLightInfo (ar: InputArchive, v: LightInfo): void { // skip, v.light: Light v.level = ar.readNumber(); } -export function saveDescriptor (ar: OutputArchive, v: Descriptor) { +export function saveDescriptor (ar: OutputArchive, v: Descriptor): void { ar.writeNumber(v.type); ar.writeNumber(v.count); } -export function loadDescriptor (ar: InputArchive, v: Descriptor) { +export function loadDescriptor (ar: InputArchive, v: Descriptor): void { v.type = ar.readNumber(); v.count = ar.readNumber(); } -export function saveDescriptorBlock (ar: OutputArchive, v: DescriptorBlock) { +export function saveDescriptorBlock (ar: OutputArchive, v: DescriptorBlock): void { ar.writeNumber(v.descriptors.size); // Map for (const [k1, v1] of v.descriptors) { ar.writeString(k1); @@ -661,7 +661,7 @@ export function saveDescriptorBlock (ar: OutputArchive, v: DescriptorBlock) { ar.writeNumber(v.count); } -export function loadDescriptorBlock (ar: InputArchive, v: DescriptorBlock) { +export function loadDescriptorBlock (ar: InputArchive, v: DescriptorBlock): void { let sz = 0; sz = ar.readNumber(); // Map for (let i1 = 0; i1 !== sz; ++i1) { @@ -681,7 +681,7 @@ export function loadDescriptorBlock (ar: InputArchive, v: DescriptorBlock) { v.count = ar.readNumber(); } -export function saveDescriptorBlockFlattened (ar: OutputArchive, v: DescriptorBlockFlattened) { +export function saveDescriptorBlockFlattened (ar: OutputArchive, v: DescriptorBlockFlattened): void { ar.writeNumber(v.descriptorNames.length); // string[] for (const v1 of v.descriptorNames) { ar.writeString(v1); @@ -702,7 +702,7 @@ export function saveDescriptorBlockFlattened (ar: OutputArchive, v: DescriptorBl ar.writeNumber(v.count); } -export function loadDescriptorBlockFlattened (ar: InputArchive, v: DescriptorBlockFlattened) { +export function loadDescriptorBlockFlattened (ar: InputArchive, v: DescriptorBlockFlattened): void { let sz = 0; sz = ar.readNumber(); // string[] v.descriptorNames.length = sz; @@ -732,21 +732,21 @@ export function loadDescriptorBlockFlattened (ar: InputArchive, v: DescriptorBlo v.count = ar.readNumber(); } -export function saveDescriptorBlockIndex (ar: OutputArchive, v: DescriptorBlockIndex) { +export function saveDescriptorBlockIndex (ar: OutputArchive, v: DescriptorBlockIndex): void { ar.writeNumber(v.updateFrequency); ar.writeNumber(v.parameterType); ar.writeNumber(v.descriptorType); ar.writeNumber(v.visibility); } -export function loadDescriptorBlockIndex (ar: InputArchive, v: DescriptorBlockIndex) { +export function loadDescriptorBlockIndex (ar: InputArchive, v: DescriptorBlockIndex): void { v.updateFrequency = ar.readNumber(); v.parameterType = ar.readNumber(); v.descriptorType = ar.readNumber(); v.visibility = ar.readNumber(); } -export function saveResolvePair (ar: OutputArchive, v: ResolvePair) { +export function saveResolvePair (ar: OutputArchive, v: ResolvePair): void { ar.writeString(v.source); ar.writeString(v.target); ar.writeNumber(v.resolveFlags); @@ -754,7 +754,7 @@ export function saveResolvePair (ar: OutputArchive, v: ResolvePair) { ar.writeNumber(v.mode1); } -export function loadResolvePair (ar: InputArchive, v: ResolvePair) { +export function loadResolvePair (ar: InputArchive, v: ResolvePair): void { v.source = ar.readString(); v.target = ar.readString(); v.resolveFlags = ar.readNumber(); @@ -762,7 +762,7 @@ export function loadResolvePair (ar: InputArchive, v: ResolvePair) { v.mode1 = ar.readNumber(); } -export function saveCopyPair (ar: OutputArchive, v: CopyPair) { +export function saveCopyPair (ar: OutputArchive, v: CopyPair): void { ar.writeString(v.source); ar.writeString(v.target); ar.writeNumber(v.mipLevels); @@ -775,7 +775,7 @@ export function saveCopyPair (ar: OutputArchive, v: CopyPair) { ar.writeNumber(v.targetPlaneSlice); } -export function loadCopyPair (ar: InputArchive, v: CopyPair) { +export function loadCopyPair (ar: InputArchive, v: CopyPair): void { v.source = ar.readString(); v.target = ar.readString(); v.mipLevels = ar.readNumber(); @@ -788,7 +788,7 @@ export function loadCopyPair (ar: InputArchive, v: CopyPair) { v.targetPlaneSlice = ar.readNumber(); } -export function saveMovePair (ar: OutputArchive, v: MovePair) { +export function saveMovePair (ar: OutputArchive, v: MovePair): void { ar.writeString(v.source); ar.writeString(v.target); ar.writeNumber(v.mipLevels); @@ -798,7 +798,7 @@ export function saveMovePair (ar: OutputArchive, v: MovePair) { ar.writeNumber(v.targetPlaneSlice); } -export function loadMovePair (ar: InputArchive, v: MovePair) { +export function loadMovePair (ar: InputArchive, v: MovePair): void { v.source = ar.readString(); v.target = ar.readString(); v.mipLevels = ar.readNumber(); @@ -808,7 +808,7 @@ export function loadMovePair (ar: InputArchive, v: MovePair) { v.targetPlaneSlice = ar.readNumber(); } -export function savePipelineStatistics (ar: OutputArchive, v: PipelineStatistics) { +export function savePipelineStatistics (ar: OutputArchive, v: PipelineStatistics): void { ar.writeNumber(v.numRenderPasses); ar.writeNumber(v.numManagedTextures); ar.writeNumber(v.totalManagedTextures); @@ -822,7 +822,7 @@ export function savePipelineStatistics (ar: OutputArchive, v: PipelineStatistics ar.writeNumber(v.numInstancingUniformBlocks); } -export function loadPipelineStatistics (ar: InputArchive, v: PipelineStatistics) { +export function loadPipelineStatistics (ar: InputArchive, v: PipelineStatistics): void { v.numRenderPasses = ar.readNumber(); v.numManagedTextures = ar.readNumber(); v.totalManagedTextures = ar.readNumber(); diff --git a/cocos/rendering/custom/utils.ts b/cocos/rendering/custom/utils.ts index 3d4cab5c3ad..92e985d9731 100644 --- a/cocos/rendering/custom/utils.ts +++ b/cocos/rendering/custom/utils.ts @@ -40,11 +40,11 @@ export function isUICamera (camera: Camera): boolean { } // eslint-disable-next-line @typescript-eslint/no-unused-vars -export function replacer (key: unknown, value: unknown) { +export function replacer (key: unknown, value: unknown): unknown { if (value instanceof Map) { return { meta_t: 'Map', - value: Array.from(value.entries()).sort((a, b) => String(a[0]).localeCompare(b[0])), + value: Array.from(value.entries()).sort((a, b): number => String(a[0]).localeCompare(b[0])), }; } else if (value instanceof Set) { return { @@ -56,7 +56,7 @@ export function replacer (key: unknown, value: unknown) { } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars -export function reviver (key: unknown, value: any) { +export function reviver (key: unknown, value: any): any { if (typeof value === 'object' && value !== null) { if (value.meta_t === 'Map') { return new Map(value.value); @@ -68,11 +68,11 @@ export function reviver (key: unknown, value: any) { return value; } -export function stringify (data: unknown, space?: string | number | undefined) { +export function stringify (data: unknown, space?: string | number | undefined): string { return JSON.stringify(data, replacer, space); } -export function parse (text: string) { +export function parse (text: string): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return JSON.parse(text, reviver); } diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index eacb55b0c32..665bb1787aa 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -25,7 +25,7 @@ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; import { DEBUG } from 'internal:constants'; -import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo } from '../../gfx'; +import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo, UniformBlock } from '../../gfx'; import { Mat4, Quat, toRadian, Vec2, Vec3, Vec4, assert, macro, cclegacy } from '../../core'; import { AccessType, AttachmentType, ComputeView, CopyPair, LightInfo, LightingMode, MovePair, QueueHint, RasterView, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; import { Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedBuffer, ManagedResource, MovePass, RasterPass, RasterSubpass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData, Subpass } from './render-graph'; @@ -74,7 +74,7 @@ export class WebSetter { this._lg = lg; } - protected _copyToBuffer (target: any, offset: number, type: Type) { + protected _copyToBuffer (target: any, offset: number, type: Type): void { assert(offset !== -1); const arr = this.getCurrConstant(); switch (type) { @@ -99,16 +99,16 @@ export class WebSetter { } } - protected _applyCurrConstantBuffer (name: string, target: any, type: Type, idx = 0) { + protected _applyCurrConstantBuffer (name: string, target: any, type: Type, idx = 0): void { const offset = this.getUniformOffset(name, type, idx); this._copyToBuffer(target, offset, type); } - public hasUniform (offset: number) { + public hasUniform (offset: number): boolean { return offset !== -1; } - public getUniformOffset (name: string, type: Type, idx = 0) { + public getUniformOffset (name: string, type: Type, idx = 0): number { const currBlock = this._getCurrUniformBlock(); if (!currBlock) return -1; let offset = 0; @@ -130,7 +130,7 @@ export class WebSetter { return -1; } - protected _getCurrUniformBlock () { + protected _getCurrUniformBlock (): UniformBlock | undefined { const block: string = this._currBlock; const nodeId = this._lg.locateChild(0xFFFFFFFF, this._currStage); const ppl = this._lg.getLayout(nodeId); @@ -139,7 +139,7 @@ export class WebSetter { return layout.uniformBlocks.get(nameID); } - protected _getCurrDescriptorBlock (block: string) { + protected _getCurrDescriptorBlock (block: string): number { const nodeId = this._lg.locateChild(0xFFFFFFFF, this._currStage); const ppl = this._lg.getLayout(nodeId); const layout = ppl.descriptorSets.get(UpdateFrequency.PER_PASS)!.descriptorSetLayoutData; @@ -154,7 +154,7 @@ export class WebSetter { return -1; } - setCurrConstant (block: string, stage = 'default') { + setCurrConstant (block: string, stage = 'default'): boolean { this._currBlock = block; this._currStage = stage; const nameID: number = this._lg.attributeIndex.get(block)!; @@ -168,11 +168,11 @@ export class WebSetter { return true; } - getCurrConstant () { + getCurrConstant (): number[] { return this._currConstant; } - public addConstant (block: string, stage = 'default') { + public addConstant (block: string, stage = 'default'): boolean { this._currBlock = block; this._currStage = stage; const num = this._lg.attributeIndex.get(block)!; @@ -286,7 +286,7 @@ function setShadowUBOLightView (setter: WebSetter, camera: Camera, light: Light, level: number, - layout = 'default') { + layout = 'default'): void { const director = cclegacy.director; const pipeline = director.root.pipeline; const device = pipeline.device; @@ -440,7 +440,7 @@ function getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number return 0.0; } -function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'default') { +function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'default'): void { const director = cclegacy.director; const pipeline = director.root.pipeline; const device = pipeline.device; @@ -586,7 +586,7 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd function setCameraUBOValues (setter: WebSetter, camera: Readonly | null, cfg: Readonly, scene: Readonly, - layoutName = 'default') { + layoutName = 'default'): void { const director = cclegacy.director; const root = director.root; const pipeline = root.pipeline as WebPipeline; @@ -727,7 +727,7 @@ function setCameraUBOValues (setter: WebSetter, } } -function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Readonly, layout = 'default') { +function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Readonly, layout = 'default'): void { const skybox = cfg.skybox; const director = cclegacy.director; const root = director.root; @@ -789,14 +789,14 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild setArrayBuffer (name: string, arrayBuffer: ArrayBuffer): void { throw new Error('Method not implemented.'); } - get name () { + get name (): string { return this._renderGraph.getName(this._vertID); } set name (name: string) { this._renderGraph.setName(this._vertID, name); } - getLayoutName () { + getLayoutName (): string { const parId = this._renderGraph.getParent(this._vertID); const layoutName = isEnableEffect() ? this._renderGraph.getLayout(parId) : 'default'; return layoutName; @@ -855,7 +855,7 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild setTextureUBOView(this, null, this._pipeline); initGlobalDescBinding(this._data, layoutName); } - addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags = SceneFlags.NONE) { + addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags = SceneFlags.NONE): void { this._renderGraph.addVertex( RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, camera), 'CameraQuad', '', new RenderData(), false, this._vertID, @@ -872,13 +872,13 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild setTextureUBOView(this, camera, this._pipeline); initGlobalDescBinding(this._data, layoutName); } - clearRenderTarget (name: string, color: Color = new Color()) { + clearRenderTarget (name: string, color: Color = new Color()): void { this._renderGraph.addVertex( RenderGraphValue.Clear, [new ClearView(name, ClearFlagBit.COLOR, color)], 'ClearRenderTarget', '', new RenderData(), false, this._vertID, ); } - setViewport (viewport: Viewport) { + setViewport (viewport: Viewport): void { this._queue.viewport = new Viewport().copy(viewport); } addCustomCommand (customBehavior: string): void { @@ -911,13 +911,13 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB setArrayBuffer (name: string, arrayBuffer: ArrayBuffer): void { throw new Error('Method not implemented.'); } - get name () { + get name (): string { return this._renderGraph.getName(this._vertID); } set name (name: string) { this._renderGraph.setName(this._vertID, name); } - addRenderTarget (name: string, accessType: AccessType, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()) { + addRenderTarget (name: string, accessType: AccessType, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()): void { throw new Error('Method not implemented.'); } addDepthStencil (name: string, accessType: AccessType, depthSlotName = '', stencilSlotName = '', loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { @@ -986,10 +986,10 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void { throw new Error('Method not implemented.'); } - addRasterView (name: string, view: RasterView) { + addRasterView (name: string, view: RasterView): void { this._pass.rasterViews.set(name, view); } - addComputeView (name: string, view: ComputeView) { + addComputeView (name: string, view: ComputeView): void { if (DEBUG) { assert(view.name); assert(name && this._resourceGraph.contains(name)); @@ -1010,13 +1010,13 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu this._pass.versionName = name; this._pass.version = version; } - get name () { + get name (): string { return this._renderGraph.getName(this._vertID); } set name (name: string) { this._renderGraph.setName(this._vertID, name); } - addRenderTarget (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()) { + addRenderTarget (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()): void { if (DEBUG) { assert(name && this._resourceGraph.contains(name)); } @@ -1044,7 +1044,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu new Color(depth, stencil, 0, 0)); this._pass.rasterViews.set(name, view); } - private _addComputeResource (name: string, accessType: AccessType, slotName: string) { + private _addComputeResource (name: string, accessType: AccessType, slotName: string): void { const view = new ComputeView(slotName); view.accessType = accessType; if (DEBUG) { @@ -1085,7 +1085,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu const result = new WebRenderSubpassBuilder(data, this._renderGraph, this._layoutGraph, vertID, subpass, this._pipeline); return result; } - addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = 'default') { + addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = 'default'): WebRenderQueueBuilder { if (DEBUG) { const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); @@ -1098,7 +1098,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); } - addFullscreenQuad (material: Material, passID: number, sceneFlags = SceneFlags.NONE, name = 'FullscreenQuad') { + addFullscreenQuad (material: Material, passID: number, sceneFlags = SceneFlags.NONE, name = 'FullscreenQuad'): void { const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); const queueId = this._renderGraph.addVertex( RenderGraphValue.Queue, queue, @@ -1111,7 +1111,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu ); } - addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags: SceneFlags, name = 'CameraQuad') { + addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags: SceneFlags, name = 'CameraQuad'): void { const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); const queueId = this._renderGraph.addVertex( RenderGraphValue.Queue, queue, @@ -1151,7 +1151,7 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui setArrayBuffer (name: string, arrayBuffer: ArrayBuffer): void { throw new Error('Method not implemented.'); } - get name () { + get name (): string { return this._renderGraph.getName(this._vertID); } set name (name: string) { @@ -1164,7 +1164,7 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui material: Material | null = null, passID = 0, name = 'Dispatch', - ) { + ): void { this._renderGraph.addVertex( RenderGraphValue.Dispatch, new Dispatch(material, passID, threadGroupCountX, threadGroupCountY, threadGroupCountZ), @@ -1198,7 +1198,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild setArrayBuffer (name: string, arrayBuffer: ArrayBuffer): void { throw new Error('Method not implemented.'); } - get name () { + get name (): string { return this._renderGraph.getName(this._vertID); } set name (name: string) { @@ -1216,7 +1216,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild addMaterialTexture (resourceName: string, flags?: ShaderStageFlagBit | undefined): void { throw new Error('Method not implemented.'); } - addComputeView (name: string, view: ComputeView) { + addComputeView (name: string, view: ComputeView): void { if (DEBUG) { assert(name && this._resourceGraph.contains(name)); } @@ -1226,7 +1226,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild this._pass.computeViews.set(name, [view]); } } - addQueue (layoutName = 'default') { + addQueue (layoutName = 'default'): WebComputeQueueBuilder { if (DEBUG) { const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); @@ -1256,13 +1256,13 @@ export class WebMovePassBuilder { setCustomBehavior (name: string): void { throw new Error('Method not implemented.'); } - get name () { + get name (): string { return this._renderGraph.getName(this._vertID); } set name (name: string) { this._renderGraph.setName(this._vertID, name); } - addPair (pair: MovePair) { + addPair (pair: MovePair): void { this._pass.movePairs.push(pair); } private readonly _renderGraph: RenderGraph; @@ -1282,7 +1282,7 @@ export class WebCopyPassBuilder { setCustomBehavior (name: string): void { throw new Error('Method not implemented.'); } - get name () { + get name (): string { return this._renderGraph.getName(this._vertID); } set name (name: string) { @@ -1302,10 +1302,10 @@ export class WebPipeline implements BasicPipeline { constructor (layoutGraph: LayoutGraphData) { this._layoutGraph = layoutGraph; } - get type () { + get type (): PipelineType { return PipelineType.BASIC; } - get capabilities () { + get capabilities (): PipelineCapabilities { return new PipelineCapabilities(); } addCustomBuffer (name: string, info: BufferInfo, type: string): number { @@ -1400,7 +1400,7 @@ export class WebPipeline implements BasicPipeline { // TODO: implement resolve pass throw new Error('Method not implemented.'); } - public addCopyPass (copyPairs: CopyPair[]) { + public addCopyPass (copyPairs: CopyPair[]): void { // const renderData = new RenderData(); // const vertID = this._renderGraph!.addVertex( // RenderGraphValue.Copy, copyPass, 'copyPass', 'copy-pass', renderData, false, @@ -1424,7 +1424,7 @@ export class WebPipeline implements BasicPipeline { currRaster.addQueue(QueueHint.NONE).addFullscreenQuad(this._copyPassMat, 0, SceneFlags.NONE); } } - protected _generateConstantMacros (clusterEnabled: boolean) { + protected _generateConstantMacros (clusterEnabled: boolean): void { let str = ''; str += `#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE ${this._device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) ? 1 : 0}\n`; @@ -1439,14 +1439,14 @@ export class WebPipeline implements BasicPipeline { this._constantMacros = str; this._layoutGraph.constantMacros = this._constantMacros; } - public setCustomPipelineName (name: string) { + public setCustomPipelineName (name: string): void { this._customPipelineName = name; if (this._customPipelineName === 'Deferred') { this._usesDeferredPipeline = true; } } - public getGlobalDescriptorSetData () { + public getGlobalDescriptorSetData (): DescriptorSetData | undefined { const stageId = this.layoutGraph.locateChild(this.layoutGraph.nullVertex(), 'default'); assert(stageId !== 0xFFFFFFFF); const layout = this.layoutGraph.getLayout(stageId); @@ -1454,20 +1454,20 @@ export class WebPipeline implements BasicPipeline { return layoutData; } - private _initCombineSignY () { + private _initCombineSignY (): void { const device = this._device; this._combineSignY = (device.capabilities.screenSpaceSignY * 0.5 + 0.5) << 1 | (device.capabilities.clipSpaceSignY * 0.5 + 0.5); } - public getCombineSignY () { + public getCombineSignY (): number { return this._combineSignY; } - get globalDescriptorSetData () { + get globalDescriptorSetData (): DescriptorSetData { return this._globalDescSetData; } - private _compileMaterial () { + private _compileMaterial (): void { this._copyPassMat.initialize({ effectName: 'pipeline/copy-pass', }); @@ -1652,7 +1652,7 @@ export class WebPipeline implements BasicPipeline { new SamplerInfo(), ); } - addRenderTarget (name: string, format: Format, width: number, height: number, residency = ResourceResidency.MANAGED) { + addRenderTarget (name: string, format: Format, width: number, height: number, residency = ResourceResidency.MANAGED): number { const desc = new ResourceDesc(); desc.dimension = ResourceDimension.TEXTURE2D; desc.width = width; @@ -1671,7 +1671,7 @@ export class WebPipeline implements BasicPipeline { new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), ); } - addDepthStencil (name: string, format: Format, width: number, height: number, residency = ResourceResidency.MANAGED) { + addDepthStencil (name: string, format: Format, width: number, height: number, residency = ResourceResidency.MANAGED): number { const desc = new ResourceDesc(); desc.dimension = ResourceDimension.TEXTURE2D; desc.width = width; @@ -1689,7 +1689,7 @@ export class WebPipeline implements BasicPipeline { new SamplerInfo(Filter.POINT, Filter.POINT, Filter.NONE), ); } - addStorageTexture (name: string, format: Format, width: number, height: number, residency = ResourceResidency.MANAGED) { + addStorageTexture (name: string, format: Format, width: number, height: number, residency = ResourceResidency.MANAGED): number { const desc = new ResourceDesc(); desc.dimension = ResourceDimension.TEXTURE2D; desc.width = width; @@ -1707,7 +1707,7 @@ export class WebPipeline implements BasicPipeline { new SamplerInfo(Filter.POINT, Filter.POINT, Filter.NONE), ); } - addShadingRateTexture (name: string, width: number, height: number, residency = ResourceResidency.MANAGED) { + addShadingRateTexture (name: string, width: number, height: number, residency = ResourceResidency.MANAGED): number { const desc = new ResourceDesc(); desc.dimension = ResourceDimension.TEXTURE2D; desc.width = width; @@ -1726,18 +1726,18 @@ export class WebPipeline implements BasicPipeline { new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), ); } - beginFrame () { + beginFrame (): void { // noop } - update (camera: Camera) { + update (camera: Camera): void { // noop } - endFrame () { + endFrame (): void { // this._renderGraph = null; this.renderGraph?.clear(); } - compile () { + compile (): void { if (!this._renderGraph) { throw new Error('RenderGraph cannot be built without being created'); } @@ -1747,7 +1747,7 @@ export class WebPipeline implements BasicPipeline { this._compiler.compile(this._renderGraph); } - execute () { + execute (): void { if (!this._renderGraph) { throw new Error('Cannot run without creating rendergraph'); } @@ -1758,10 +1758,10 @@ export class WebPipeline implements BasicPipeline { this._executor.resize(this.width, this.height); this._executor.execute(this._renderGraph); } - protected _applySize (cameras: Camera[]) { + protected _applySize (cameras: Camera[]): void { let newWidth = this._width; let newHeight = this._height; - cameras.forEach((camera) => { + cameras.forEach((camera): void => { const window = camera.window; newWidth = Math.max(window.width, newWidth); newHeight = Math.max(window.height, newHeight); @@ -1777,9 +1777,9 @@ export class WebPipeline implements BasicPipeline { private _width = 0; private _height = 0; - get width () { return this._width; } - get height () { return this._height; } - render (cameras: Camera[]) { + get width (): number { return this._width; } + get height (): number { return this._height; } + render (cameras: Camera[]): void { if (cameras.length === 0) { return; } @@ -1828,21 +1828,21 @@ export class WebPipeline implements BasicPipeline { const setLayout = pplLayout.descriptorSets.get(freq)!; return setLayout.descriptorSetLayout!; } - get renderGraph () { + get renderGraph (): RenderGraph | null { return this._renderGraph; } - get resourceGraph () { + get resourceGraph (): ResourceGraph { return this._resourceGraph; } - get layoutGraph () { + get layoutGraph (): LayoutGraphData { return this._layoutGraph; } - get resourceUses () { + get resourceUses (): string[] { return this._resourceUses; } - protected _updateRasterPassConstants (setter: WebSetter, width: number, height: number, layoutName = 'default') { + protected _updateRasterPassConstants (setter: WebSetter, width: number, height: number, layoutName = 'default'): void { const director = cclegacy.director; const root = director.root; const shadingWidth = width; diff --git a/cocos/rendering/custom/web-program-library.ts b/cocos/rendering/custom/web-program-library.ts index 78f1c217e72..35b9f691675 100644 --- a/cocos/rendering/custom/web-program-library.ts +++ b/cocos/rendering/custom/web-program-library.ts @@ -50,7 +50,7 @@ function makeProgramInfo (effectName: string, shader: EffectAsset.IShaderInfo): } // overwrite IProgramInfo using gfx.ShaderInfo -function overwriteProgramBlockInfo (shaderInfo: ShaderInfo, programInfo: IProgramInfo) { +function overwriteProgramBlockInfo (shaderInfo: ShaderInfo, programInfo: IProgramInfo): void { const set = _setIndex[UpdateFrequency.PER_BATCH]; for (const block of programInfo.blocks) { let found = false; @@ -75,7 +75,7 @@ function populateGroupedShaderInfo ( layout: DescriptorSetLayoutData, descriptorInfo: EffectAsset.IDescriptorInfo, set: number, shaderInfo: ShaderInfo, blockSizes: number[], -) { +): void { for (const descriptorBlock of layout.descriptorBlocks) { const visibility = descriptorBlock.visibility; let binding = descriptorBlock.offset; @@ -89,7 +89,7 @@ function populateGroupedShaderInfo ( blockSizes.push(getSize(block.members)); shaderInfo.blocks.push( new UniformBlock(set, binding, block.name, - block.members.map((m) => new Uniform(m.name, m.type, m.count)), + block.members.map((m): Uniform => new Uniform(m.name, m.type, m.count)), 1), // count is always 1 for UniformBlock ); ++binding; @@ -175,7 +175,7 @@ function populateGroupedShaderInfo ( // add merged descriptor to gfx.ShaderInfo function populateMergedShaderInfo (valueNames: string[], layout: DescriptorSetLayoutData, - set: number, shaderInfo: ShaderInfo, blockSizes: number[]) { + set: number, shaderInfo: ShaderInfo, blockSizes: number[]): void { for (const descriptorBlock of layout.descriptorBlocks) { let binding = descriptorBlock.offset; switch (descriptorBlock.type) { @@ -189,7 +189,7 @@ function populateMergedShaderInfo (valueNames: string[], blockSizes.push(getSize(uniformBlock.members)); shaderInfo.blocks.push( new UniformBlock(set, binding, valueNames[block.descriptorID], - uniformBlock.members.map((m) => new Uniform(m.name, m.type, m.count)), + uniformBlock.members.map((m): Uniform => new Uniform(m.name, m.type, m.count)), 1), // count is always 1 for UniformBlock ); ++binding; @@ -263,12 +263,12 @@ function populateMergedShaderInfo (valueNames: string[], function populateShaderInfo ( descriptorInfo: EffectAsset.IDescriptorInfo, set: number, shaderInfo: ShaderInfo, blockSizes: number[], -) { +): void { for (let i = 0; i < descriptorInfo.blocks.length; i++) { const block = descriptorInfo.blocks[i]; blockSizes.push(getSize(block.members)); shaderInfo.blocks.push(new UniformBlock(set, block.binding, block.name, - block.members.map((m) => new Uniform(m.name, m.type, m.count)), 1)); // effect compiler guarantees block count = 1 + block.members.map((m): Uniform => new Uniform(m.name, m.type, m.count)), 1)); // effect compiler guarantees block count = 1 } for (let i = 0; i < descriptorInfo.samplerTextures.length; i++) { const samplerTexture = descriptorInfo.samplerTextures[i]; @@ -312,24 +312,24 @@ function populateShaderInfo ( function populateLocalShaderInfo ( target: EffectAsset.IDescriptorInfo, source: IDescriptorSetLayoutInfo, shaderInfo: ShaderInfo, blockSizes: number[], -) { +): void { const set = _setIndex[UpdateFrequency.PER_INSTANCE]; for (let i = 0; i < target.blocks.length; i++) { const block = target.blocks[i]; const info = source.layouts[block.name] as UniformBlock | undefined; - const binding = info && source.bindings.find((bd) => bd.binding === info.binding); + const binding = info && source.bindings.find((bd): boolean => bd.binding === info.binding); if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_BUFFER_TYPE)) { console.warn(`builtin UBO '${block.name}' not available!`); continue; } blockSizes.push(getSize(block.members)); shaderInfo.blocks.push(new UniformBlock(set, binding.binding, block.name, - block.members.map((m) => new Uniform(m.name, m.type, m.count)), 1)); // effect compiler guarantees block count = 1 + block.members.map((m): Uniform => new Uniform(m.name, m.type, m.count)), 1)); // effect compiler guarantees block count = 1 } for (let i = 0; i < target.samplerTextures.length; i++) { const samplerTexture = target.samplerTextures[i]; const info = source.layouts[samplerTexture.name] as UniformSamplerTexture; - const binding = info && source.bindings.find((bd) => bd.binding === info.binding); + const binding = info && source.bindings.find((bd): boolean => bd.binding === info.binding); if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_SAMPLER_TYPE)) { console.warn(`builtin samplerTexture '${samplerTexture.name}' not available!`); continue; @@ -363,7 +363,7 @@ function getIDescriptorSetLayoutInfoSamplerTextureCapacity (info: IDescriptorSet } function setFlattenedUniformBlockBinding (setOffsets: number[], - descriptors: UniformBlock[]) { + descriptors: UniformBlock[]): void { for (const d of descriptors) { d.flattened = setOffsets[d.set] + d.binding; } @@ -376,7 +376,7 @@ function setFlattenedSamplerTextureBinding (setOffsets: number[], | UniformTexture[] | UniformStorageBuffer[] | UniformStorageImage[] - | UniformInputAttachment[]) { + | UniformInputAttachment[]): void { for (const d of descriptors) { d.flattened = setOffsets[d.set] + d.binding - uniformBlockCapacities[d.set]; } @@ -386,7 +386,7 @@ function calculateFlattenedBinding ( descriptorSets: (DescriptorSetLayoutData | null)[], fixedInstanceDescriptorSetLayout: IDescriptorSetLayoutInfo | null, shaderInfo: ShaderInfo, -) { +): void { // Descriptors of UniformBlock starts from 0, and Descriptors of SamplerTexture starts from the end of UniformBlock. const uniformBlockCapacities = new Array(4); { @@ -584,7 +584,7 @@ function buildProgramData ( srcShaderInfo: EffectAsset.IShaderInfo, lg: LayoutGraphData, phase: RenderPhaseData, programData: ShaderProgramData, fixedLocal: boolean, -) { +): void { { const perBatch = makeDescriptorSetLayoutData(lg, UpdateFrequency.PER_BATCH, @@ -875,7 +875,7 @@ export class WebProgramLibrary implements ProgramLibrary { // prepare variant const macroArray = prepareDefines(defines, programInfo.defines); const prefix = this.layoutGraph.constantMacros + programInfo.constantMacros - + macroArray.reduce((acc, cur) => `${acc}#define ${cur.name} ${cur.value}\n`, ''); + + macroArray.reduce((acc, cur): string => `${acc}#define ${cur.name} ${cur.value}\n`, ''); let src = programInfo.glsl3; const deviceShaderVersion = getDeviceShaderVersion(device); diff --git a/cocos/rendering/custom/web-scene.ts b/cocos/rendering/custom/web-scene.ts index 13327c71001..7a4c6a6150f 100644 --- a/cocos/rendering/custom/web-scene.ts +++ b/cocos/rendering/custom/web-scene.ts @@ -24,7 +24,7 @@ import { Frustum, intersect } from '../../core/geometry'; import { Vec3 } from '../../core/math'; -import { RenderScene } from '../../render-scene'; +import { RenderScene, scene } from '../../render-scene'; import { Camera, Model, ShadowType, SKYBOX_FLAG } from '../../render-scene/scene'; import { IRenderObject, IRenderPass, UBOShadow } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; @@ -63,7 +63,7 @@ export class WebSceneTask implements SceneTask { return TaskType.SYNC; } - protected _getRenderObject (model: Model, camera: Camera) { + protected _getRenderObject (model: Model, camera: Camera): RenderObject { let depth = 0; if (model.node) { const _tempVec3 = new Vec3(); @@ -74,7 +74,7 @@ export class WebSceneTask implements SceneTask { return ro; } - protected _sceneCulling () { + protected _sceneCulling (): void { if (!this.camera) { return; } const scene = this.renderScene; const camera = this.camera; @@ -144,12 +144,12 @@ export class WebSceneTask implements SceneTask { public submit (): void { } - get camera () { return this._camera; } - get renderScene () { + get camera (): scene.Camera | null { return this._camera; } + get renderScene (): RenderScene | null { return this._scene; } - get visitor () { return this._visitor; } - get dirLightFrustum () { return this._dirLightFrustum; } + get visitor (): SceneVisitor { return this._visitor; } + get dirLightFrustum (): Frustum { return this._dirLightFrustum; } get sceneData (): PipelineSceneData { return this._sceneData; } protected _scene: RenderScene | null = null; protected _camera: Camera | null = null; diff --git a/cocos/rendering/debug-view.ts b/cocos/rendering/debug-view.ts index 76da7cb4716..395b37581b7 100644 --- a/cocos/rendering/debug-view.ts +++ b/cocos/rendering/debug-view.ts @@ -185,7 +185,7 @@ export class DebugView { * @zh 开关指定的渲染组合调试模式。 * @param Specified composite type, enable or disable. */ - public enableCompositeMode (val: DebugViewCompositeType, enable: boolean) { + public enableCompositeMode (val: DebugViewCompositeType, enable: boolean): void { this._enableCompositeMode(val, enable); this._updatePipeline(); } @@ -194,7 +194,7 @@ export class DebugView { * @en Toggle all rendering composite debug mode. * @zh 开关所有的渲染组合调试模式。 */ - public enableAllCompositeMode (enable: boolean) { + public enableAllCompositeMode (enable: boolean): void { this._enableAllCompositeMode(enable); this._updatePipeline(); } @@ -203,7 +203,7 @@ export class DebugView { * @en Get rendering debug view on / off state. * @zh 查询当前是否开启了渲染调试模式。 */ - public isEnabled () { + public isEnabled (): boolean { return this._getType() !== RenderingDebugViewType.NONE; } @@ -211,7 +211,7 @@ export class DebugView { * @en Disable all debug view modes, reset to standard rendering mode. * @zh 关闭所有的渲染调试模式,恢复到正常渲染。 */ - public reset () { + public reset (): void { this._activate(); this._updatePipeline(); } @@ -219,14 +219,14 @@ export class DebugView { /** * @internal */ - protected _activate () { + protected _activate (): void { this._singleMode = DebugViewSingleType.NONE; this._enableAllCompositeMode(true); this._lightingWithAlbedo = true; this._csmLayerColoration = false; } - protected _updatePipeline () { + protected _updatePipeline (): void { const root = cclegacy.director.root as Root; const pipeline = root.pipeline; @@ -238,7 +238,7 @@ export class DebugView { } } - private _enableCompositeMode (val: DebugViewCompositeType, enable: boolean) { + private _enableCompositeMode (val: DebugViewCompositeType, enable: boolean): void { if (enable) { this._compositeModeValue |= (1 << val); } else { @@ -246,7 +246,7 @@ export class DebugView { } } - private _enableAllCompositeMode (enable: boolean) { + private _enableAllCompositeMode (enable: boolean): void { for (let i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { if (enable) { this._compositeModeValue |= (1 << i); diff --git a/cocos/rendering/deferred/bloom-stage.ts b/cocos/rendering/deferred/bloom-stage.ts index 76c26acad4d..0b80a6b3550 100644 --- a/cocos/rendering/deferred/bloom-stage.ts +++ b/cocos/rendering/deferred/bloom-stage.ts @@ -85,16 +85,16 @@ export class BloomStage extends RenderStage { return true; } - public activate (pipeline: RenderPipeline, flow: RenderFlow) { + public activate (pipeline: RenderPipeline, flow: RenderFlow): void { super.activate(pipeline, flow); if (this._bloomMaterial) { (pipeline.pipelineSceneData as DeferredPipelineSceneData).bloomMaterial = this._bloomMaterial; } } - public destroy () { + public destroy (): void { } - public render (camera: Camera) { + public render (camera: Camera): void { const pipeline = this._pipeline; pipeline.generateBloomRenderData(); if (!camera.window?.swapchain && !pipeline.macros.CC_PIPELINE_TYPE) { @@ -127,7 +127,7 @@ export class BloomStage extends RenderStage { this._combinePass(camera, pipeline); } - private _prefilterPass (camera: Camera, pipeline: RenderPipeline) { + private _prefilterPass (camera: Camera, pipeline: RenderPipeline): void { pipeline.generateRenderArea(camera, this._renderArea); this._renderArea.width >>= 1; this._renderArea.height >>= 1; @@ -168,7 +168,7 @@ export class BloomStage extends RenderStage { cmdBuff.endRenderPass(); } - private _downsamplePass (camera: Camera, pipeline: RenderPipeline) { + private _downsamplePass (camera: Camera, pipeline: RenderPipeline): void { pipeline.generateRenderArea(camera, this._renderArea); this._renderArea.width >>= 1; this._renderArea.height >>= 1; @@ -216,7 +216,7 @@ export class BloomStage extends RenderStage { } } - private _upsamplePass (camera: Camera, pipeline: RenderPipeline) { + private _upsamplePass (camera: Camera, pipeline: RenderPipeline): void { const bloomData = pipeline.getPipelineRenderData().bloom!; pipeline.generateRenderArea(camera, this._renderArea); this._renderArea.width >>= this.iterations + 1; @@ -265,7 +265,7 @@ export class BloomStage extends RenderStage { } } - private _combinePass (camera: Camera, pipeline: RenderPipeline) { + private _combinePass (camera: Camera, pipeline: RenderPipeline): void { pipeline.generateRenderArea(camera, this._renderArea); const cmdBuff = pipeline.commandBuffers[0]; diff --git a/cocos/rendering/deferred/deferred-pipeline-scene-data.ts b/cocos/rendering/deferred/deferred-pipeline-scene-data.ts index 0c995b6b19e..18b655e5457 100644 --- a/cocos/rendering/deferred/deferred-pipeline-scene-data.ts +++ b/cocos/rendering/deferred/deferred-pipeline-scene-data.ts @@ -57,11 +57,11 @@ export class DeferredPipelineSceneData extends PipelineSceneData { } } - get antiAliasing () { + get antiAliasing (): AntiAliasing { return this._antiAliasing; } - public get bloomMaterial () { + public get bloomMaterial (): Material { return this._bloomMaterial; } @@ -72,7 +72,7 @@ export class DeferredPipelineSceneData extends PipelineSceneData { } protected declare _bloomMaterial: Material; - public get postprocessMaterial () { + public get postprocessMaterial (): Material { return this._postprocessMaterial; } @@ -83,11 +83,11 @@ export class DeferredPipelineSceneData extends PipelineSceneData { } protected declare _postprocessMaterial: Material; - public updatePipelineSceneData () { + public updatePipelineSceneData (): void { this.updatePipelinePassInfo(); } - private updateBloomPass () { + private updateBloomPass (): void { if (!this._bloomMaterial) return; const prefilterPass = this._bloomMaterial.passes[BLOOM_PREFILTERPASS_INDEX]; @@ -113,7 +113,7 @@ export class DeferredPipelineSceneData extends PipelineSceneData { combinePass.endChangeStatesSilently(); } - private updatePostProcessPass () { + private updatePostProcessPass (): void { if (!this.postprocessMaterial) return; const passPost = this.postprocessMaterial.passes[0]; @@ -122,7 +122,7 @@ export class DeferredPipelineSceneData extends PipelineSceneData { passPost.endChangeStatesSilently(); } - public initPipelinePassInfo () { + public initPipelinePassInfo (): void { // builtin deferred material const deferredMat = new Material(); deferredMat._uuid = 'builtin-deferred-material'; @@ -159,7 +159,7 @@ export class DeferredPipelineSceneData extends PipelineSceneData { this.updatePipelinePassInfo(); } - public get deferredLightingMaterial () { + public get deferredLightingMaterial (): Material { return this._deferredLightingMaterial; } @@ -172,23 +172,23 @@ export class DeferredPipelineSceneData extends PipelineSceneData { protected declare _deferredLightingMaterial: Material; protected declare _deferredPostMaterial: Material; - protected updatePipelinePassInfo () { + protected updatePipelinePassInfo (): void { this.updateBloomPass(); this.updatePostProcessPass(); this.updateDeferredPassInfo(); } - public activate (device: Device) { + public activate (device: Device): boolean { super.activate(device); this.initPipelinePassInfo(); return true; } - private updateDeferredPassInfo () { + private updateDeferredPassInfo (): void { this.updateDeferredLightPass(); } - private updateDeferredLightPass () { + private updateDeferredLightPass (): void { if (!this._deferredLightingMaterial) return; // It's temporary solution for main light shadowmap diff --git a/cocos/rendering/deferred/deferred-pipeline.ts b/cocos/rendering/deferred/deferred-pipeline.ts index 6d16109f253..eea6fe4fb8a 100644 --- a/cocos/rendering/deferred/deferred-pipeline.ts +++ b/cocos/rendering/deferred/deferred-pipeline.ts @@ -103,7 +103,7 @@ export class DeferredPipeline extends RenderPipeline { return true; } - public destroy () { + public destroy (): boolean { this._destroyUBOs(); this._destroyQuadInputAssembler(); this._destroyDeferredData(); @@ -120,7 +120,7 @@ export class DeferredPipeline extends RenderPipeline { return super.destroy(); } - public onGlobalPipelineStateChanged () { + public onGlobalPipelineStateChanged (): void { (this.pipelineSceneData as DeferredPipelineSceneData).updatePipelineSceneData(); } @@ -132,7 +132,7 @@ export class DeferredPipeline extends RenderPipeline { return this._pipelineRenderData as DeferredRenderData; } - private _activeRenderer (swapchain: Swapchain) { + private _activeRenderer (swapchain: Swapchain): boolean { const device = this.device; this._commandBuffers.push(device.commandBuffer); @@ -221,7 +221,7 @@ export class DeferredPipeline extends RenderPipeline { return true; } - private _destroyUBOs () { + private _destroyUBOs (): void { if (this._descriptorSet) { this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy(); this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy(); @@ -231,7 +231,7 @@ export class DeferredPipeline extends RenderPipeline { } } - private _destroyDeferredData () { + private _destroyDeferredData (): void { const deferredData = this._pipelineRenderData as DeferredRenderData; if (deferredData) { if (deferredData.gbufferFrameBuffer) deferredData.gbufferFrameBuffer.destroy(); @@ -254,7 +254,7 @@ export class DeferredPipeline extends RenderPipeline { this._pipelineRenderData = null; } - protected _ensureEnoughSize (cameras: Camera[]) { + protected _ensureEnoughSize (cameras: Camera[]): void { let newWidth = this._width; let newHeight = this._height; for (let i = 0; i < cameras.length; ++i) { @@ -270,7 +270,7 @@ export class DeferredPipeline extends RenderPipeline { } } - private _generateDeferredRenderData () { + private _generateDeferredRenderData (): void { const device = this.device; const data: DeferredRenderData = this._pipelineRenderData = new DeferredRenderData(); @@ -314,7 +314,7 @@ export class DeferredPipeline extends RenderPipeline { data.sampler = this.globalDSManager.pointSampler; // Listens when the attachment texture is scaled - this.on(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, (val: number) => { + this.on(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, (val: number): void => { data.sampler = val < 1 ? this.globalDSManager.pointSampler : this.globalDSManager.linearSampler; data.gbufferFrameBuffer = this.newFramebufferByRatio(data.gbufferFrameBuffer); data.gbufferFrameBuffer = this.newFramebufferByRatio(data.outputFrameBuffer); diff --git a/cocos/rendering/deferred/gbuffer-stage.ts b/cocos/rendering/deferred/gbuffer-stage.ts index 16bb54ad0b0..b3b4c2a65bb 100644 --- a/cocos/rendering/deferred/gbuffer-stage.ts +++ b/cocos/rendering/deferred/gbuffer-stage.ts @@ -91,17 +91,17 @@ export class GbufferStage extends RenderStage { return true; } - public activate (pipeline: DeferredPipeline, flow: MainFlow) { + public activate (pipeline: DeferredPipeline, flow: MainFlow): void { super.activate(pipeline, flow); for (let i = 0; i < this.renderQueues.length; i++) { this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]); } } - public destroy () { + public destroy (): void { } - public render (camera: Camera) { + public render (camera: Camera): void { this._instancedQueue.clear(); const pipeline = this._pipeline as DeferredPipeline; const device = pipeline.device; diff --git a/cocos/rendering/deferred/lighting-stage.ts b/cocos/rendering/deferred/lighting-stage.ts index 80ac8e96d88..ebb09a9efc7 100644 --- a/cocos/rendering/deferred/lighting-stage.ts +++ b/cocos/rendering/deferred/lighting-stage.ts @@ -98,7 +98,7 @@ export class LightingStage extends RenderStage { super.initialize(info); return true; } - public gatherLights (camera: Camera) { + public gatherLights (camera: Camera): void { const pipeline = this._pipeline as DeferredPipeline; const cmdBuff = pipeline.commandBuffers[0]; @@ -266,7 +266,7 @@ export class LightingStage extends RenderStage { cmdBuff.updateBuffer(this._deferredLitsBufs, this._lightBufferData); } - protected _createStageDescriptor (pass: Pass) { + protected _createStageDescriptor (pass: Pass): void { const device = this._pipeline.device; let totalSize = Float32Array.BYTES_PER_ELEMENT * 4 * 4 * this._maxDeferredLights; totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment; @@ -293,7 +293,7 @@ export class LightingStage extends RenderStage { this._descriptorSet.bindBuffer(UBOLocal.BINDING, _localUBO); } - public activate (pipeline: DeferredPipeline, flow: MainFlow) { + public activate (pipeline: DeferredPipeline, flow: MainFlow): void { super.activate(pipeline, flow); this._uiPhase.activate(pipeline); @@ -307,12 +307,12 @@ export class LightingStage extends RenderStage { if (this._deferredMaterial) { (pipeline.pipelineSceneData as DeferredPipelineSceneData).deferredLightingMaterial = this._deferredMaterial; } } - public destroy () { + public destroy (): void { this._deferredLitsBufs?.destroy(); this._deferredLitsBufs = null!; this._descriptorSet = null!; } - public render (camera: Camera) { + public render (camera: Camera): void { const pipeline = this._pipeline as DeferredPipeline; const device = pipeline.device; diff --git a/cocos/rendering/deferred/main-flow.ts b/cocos/rendering/deferred/main-flow.ts index 2ecdb081274..f49303c2141 100644 --- a/cocos/rendering/deferred/main-flow.ts +++ b/cocos/rendering/deferred/main-flow.ts @@ -73,15 +73,15 @@ export class MainFlow extends RenderFlow { return true; } - public activate (pipeline: RenderPipeline) { + public activate (pipeline: RenderPipeline): void { super.activate(pipeline); } - public render (camera: Camera) { + public render (camera: Camera): void { super.render(camera); } - public destroy () { + public destroy (): void { super.destroy(); } } diff --git a/cocos/rendering/deferred/postprocess-stage.ts b/cocos/rendering/deferred/postprocess-stage.ts index db7e20adf7a..fa7d0ac7347 100644 --- a/cocos/rendering/deferred/postprocess-stage.ts +++ b/cocos/rendering/deferred/postprocess-stage.ts @@ -78,15 +78,15 @@ export class PostProcessStage extends RenderStage { return true; } - public activate (pipeline: RenderPipeline, flow: RenderFlow) { + public activate (pipeline: RenderPipeline, flow: RenderFlow): void { super.activate(pipeline, flow); if (this._postProcessMaterial) { (pipeline.pipelineSceneData as DeferredPipelineSceneData).postprocessMaterial = this._postProcessMaterial; } this._uiPhase.activate(pipeline); } - public destroy () { + public destroy (): void { } - public render (camera: Camera) { + public render (camera: Camera): void { const pipeline = this._pipeline; const device = pipeline.device; const sceneData = pipeline.pipelineSceneData; diff --git a/cocos/rendering/define.ts b/cocos/rendering/define.ts index 3de8e04740d..5d0d24d6643 100644 --- a/cocos/rendering/define.ts +++ b/cocos/rendering/define.ts @@ -511,11 +511,11 @@ localDescriptorSetLayout.bindings[UBOSkinningAnimation.BINDING] = UBOSkinningAni export const INST_JOINT_ANIM_INFO = 'a_jointAnimInfo'; export class UBOSkinning { private static _jointUniformCapacity = 0; - public static get JOINT_UNIFORM_CAPACITY () { return UBOSkinning._jointUniformCapacity; } + public static get JOINT_UNIFORM_CAPACITY (): number { return UBOSkinning._jointUniformCapacity; } private static _count = 0; - public static get COUNT () { return UBOSkinning._count; } + public static get COUNT (): number { return UBOSkinning._count; } private static _size = 0; - public static get SIZE () { return UBOSkinning._size; } + public static get SIZE (): number { return UBOSkinning._size; } public static readonly NAME = 'CCSkinning'; public static readonly BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE; @@ -527,7 +527,7 @@ export class UBOSkinning { /** * @internal This method only used init UBOSkinning configure. */ - public static initLayout (capacity: number) { + public static initLayout (capacity: number): void { UBOSkinning._jointUniformCapacity = capacity; UBOSkinning._count = capacity * 12; UBOSkinning._size = UBOSkinning._count * 4; @@ -538,7 +538,7 @@ export class UBOSkinning { /** * @internal This method only used to init localDescriptorSetLayout.layouts[UBOSkinning.NAME] */ -export function localDescriptorSetLayout_ResizeMaxJoints (maxCount: number) { +export function localDescriptorSetLayout_ResizeMaxJoints (maxCount: number): void { UBOSkinning.initLayout(maxCount); localDescriptorSetLayout.layouts[UBOSkinning.NAME] = UBOSkinning.LAYOUT; localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR; @@ -772,7 +772,7 @@ export const MODEL_ALWAYS_MASK = Layers.Enum.ALL; * @en Does the device support single-channeled half float texture? (for both color attachment and sampling) * @zh 当前设备是否支持单通道半浮点贴图?(颜色输出和采样) */ -export function supportsR16HalfFloatTexture (device: Device) { +export function supportsR16HalfFloatTexture (device: Device): boolean { return (device.getFormatFeatures(Format.R16F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE); } @@ -781,7 +781,7 @@ export function supportsR16HalfFloatTexture (device: Device) { * @en Does the device support single-channeled float texture? (for both color attachment and sampling) * @zh 当前设备是否支持单通道浮点贴图?(颜色输出和采样) */ -export function supportsR32FloatTexture (device: Device) { +export function supportsR32FloatTexture (device: Device): boolean { return (device.getFormatFeatures(Format.R32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL); // wegl 1 Single-channel float type is not supported under webgl1, so it is excluded @@ -791,7 +791,7 @@ export function supportsR32FloatTexture (device: Device) { * @en Does the device support 4-channeled float texture? (for both color attachment and sampling) * @zh 当前设备是否支持4通道浮点贴图?(颜色输出和采样) */ -export function supportsRGBA16HalfFloatTexture (device: Device) { +export function supportsRGBA16HalfFloatTexture (device: Device): boolean { return (device.getFormatFeatures(Format.RGBA16F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL); // wegl 1 Single-channel float type is not supported under webgl1, so it is excluded @@ -801,7 +801,7 @@ export function supportsRGBA16HalfFloatTexture (device: Device) { * @en Does the device support 4-channeled float texture? (for both color attachment and sampling) * @zh 当前设备是否支持4通道浮点贴图?(颜色输出和采样) */ -export function supportsRGBA32FloatTexture (device: Device) { +export function supportsRGBA32FloatTexture (device: Device): boolean { return (device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL); // wegl 1 Single-channel float type is not supported under webgl1, so it is excluded diff --git a/cocos/rendering/forward/forward-flow.ts b/cocos/rendering/forward/forward-flow.ts index a31191e40ee..8a652c86d60 100644 --- a/cocos/rendering/forward/forward-flow.ts +++ b/cocos/rendering/forward/forward-flow.ts @@ -56,15 +56,15 @@ export class ForwardFlow extends RenderFlow { return true; } - public activate (pipeline: RenderPipeline) { + public activate (pipeline: RenderPipeline): void { super.activate(pipeline); } - public render (camera: Camera) { + public render (camera: Camera): void { super.render(camera); } - public destroy () { + public destroy (): void { super.destroy(); } } diff --git a/cocos/rendering/forward/forward-pipeline.ts b/cocos/rendering/forward/forward-pipeline.ts index 2491f05a75a..a8bdcaf1832 100644 --- a/cocos/rendering/forward/forward-pipeline.ts +++ b/cocos/rendering/forward/forward-pipeline.ts @@ -94,7 +94,7 @@ export class ForwardPipeline extends RenderPipeline { return true; } - protected _ensureEnoughSize (cameras: Camera[]) { + protected _ensureEnoughSize (cameras: Camera[]): void { let newWidth = this._width; let newHeight = this._height; for (let i = 0; i < cameras.length; ++i) { @@ -108,7 +108,7 @@ export class ForwardPipeline extends RenderPipeline { } } - public destroy () { + public destroy (): boolean { this._destroyUBOs(); this._destroyQuadInputAssembler(); const rpIter = this._renderPasses.values(); @@ -123,7 +123,7 @@ export class ForwardPipeline extends RenderPipeline { return super.destroy(); } - private _activeRenderer (swapchain: Swapchain) { + private _activeRenderer (swapchain: Swapchain): boolean { const device = this.device; this._commandBuffers.push(device.commandBuffer); @@ -138,7 +138,7 @@ export class ForwardPipeline extends RenderPipeline { return true; } - private _destroyUBOs () { + private _destroyUBOs (): void { if (this._descriptorSet) { this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy(); this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy(); diff --git a/cocos/rendering/forward/forward-stage.ts b/cocos/rendering/forward/forward-stage.ts index f7470ab5cc5..3a486735198 100644 --- a/cocos/rendering/forward/forward-stage.ts +++ b/cocos/rendering/forward/forward-stage.ts @@ -88,14 +88,14 @@ export class ForwardStage extends RenderStage { this._uiPhase = new UIPhase(); } - public addRenderInstancedQueue (queue: RenderInstancedQueue) { + public addRenderInstancedQueue (queue: RenderInstancedQueue): void { if (this.additiveInstanceQueues.includes(queue)) { return; } this.additiveInstanceQueues.push(queue); } - public removeRenderInstancedQueue (queue: RenderInstancedQueue) { + public removeRenderInstancedQueue (queue: RenderInstancedQueue): void { const index = this.additiveInstanceQueues.indexOf(queue); if (index > -1) { this.additiveInstanceQueues.splice(index, 1); @@ -110,7 +110,7 @@ export class ForwardStage extends RenderStage { return true; } - public activate (pipeline: ForwardPipeline, flow: ForwardFlow) { + public activate (pipeline: ForwardPipeline, flow: ForwardFlow): void { super.activate(pipeline, flow); for (let i = 0; i < this.renderQueues.length; i++) { this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]); @@ -121,10 +121,10 @@ export class ForwardStage extends RenderStage { this._uiPhase.activate(pipeline); } - public destroy () { + public destroy (): void { } - public render (camera: Camera) { + public render (camera: Camera): void { this._instancedQueue.clear(); const pipeline = this._pipeline as ForwardPipeline; const device = pipeline.device; diff --git a/cocos/rendering/geometry-renderer.ts b/cocos/rendering/geometry-renderer.ts index e48ebe40164..6b4eee1aaf9 100644 --- a/cocos/rendering/geometry-renderer.ts +++ b/cocos/rendering/geometry-renderer.ts @@ -88,7 +88,7 @@ class GeometryVertexBuffer { */ public _inputAssembler!: InputAssembler; - public init (device: Device, maxVertices: number, stride: number, attributes: Attribute[]) { + public init (device: Device, maxVertices: number, stride: number, attributes: Attribute[]): void { this._maxVertices = maxVertices; this._vertexCount = 0; this._stride = stride; @@ -98,11 +98,11 @@ class GeometryVertexBuffer { this._inputAssembler = device.createInputAssembler(new InputAssemblerInfo(attributes, [this._buffer], null)); } - public getCount () { return Math.min(this._vertexCount, this._maxVertices); } + public getCount (): number { return Math.min(this._vertexCount, this._maxVertices); } public empty (): boolean { return this._vertexCount === 0; } - public reset () { this._vertexCount = 0; } + public reset (): void { this._vertexCount = 0; } - public update () { + public update (): void { if (!this.empty()) { const count = this.getCount(); const size = count * this._stride; @@ -110,7 +110,7 @@ class GeometryVertexBuffer { } } - public destroy () { + public destroy (): void { if (this._inputAssembler) { this._inputAssembler.destroy(); } @@ -149,7 +149,7 @@ export class GeometryRenderer { this._buffers = new GeometryVertexBuffers(); } - public activate (device: Device, info?: IGeometryInfo) { + public activate (device: Device, info?: IGeometryInfo): void { this._device = device; const posColorAttributes: Attribute[] = [ @@ -176,7 +176,7 @@ export class GeometryRenderer { } } - public render (renderPass: RenderPass, cmdBuff: CommandBuffer, sceneData: PipelineSceneData) { + public render (renderPass: RenderPass, cmdBuff: CommandBuffer, sceneData: PipelineSceneData): void { const passes = sceneData.geometryRendererPasses; const shaders = sceneData.geometryRendererShaders; @@ -247,7 +247,7 @@ export class GeometryRenderer { this.reset(); } - public destroy () { + public destroy (): void { for (let i = 0; i < GEOMETRY_DEPTH_TYPE_COUNT; i++) { this._buffers.lines[i].destroy(); this._buffers.dashedLines[i].destroy(); @@ -255,7 +255,7 @@ export class GeometryRenderer { } } - public empty () { + public empty (): boolean { for (let i = 0; i < GEOMETRY_DEPTH_TYPE_COUNT; i++) { if (!this._buffers.lines[i].empty() || !this._buffers.dashedLines[i].empty() @@ -267,7 +267,7 @@ export class GeometryRenderer { return true; } - public update () { + public update (): void { for (let i = 0; i < GEOMETRY_DEPTH_TYPE_COUNT; i++) { this._buffers.lines[i].update(); this._buffers.dashedLines[i].update(); @@ -275,7 +275,7 @@ export class GeometryRenderer { } } - public reset () { + public reset (): void { for (let i = 0; i < GEOMETRY_DEPTH_TYPE_COUNT; i++) { this._buffers.lines[i].reset(); this._buffers.dashedLines[i].reset(); @@ -283,7 +283,7 @@ export class GeometryRenderer { } } - public addDashedLine (v0: Vec3, v1: Vec3, color: Color, depthTest = true) { + public addDashedLine (v0: Vec3, v1: Vec3, color: Color, depthTest = true): void { const dashedLines = this._buffers.dashedLines[depthTest ? 1 : 0]; if (dashedLines._vertexCount + GEOMETRY_VERTICES_PER_LINE > dashedLines._maxVertices) { warnID(12008); @@ -305,7 +305,7 @@ export class GeometryRenderer { dashedLines._vertexCount += GEOMETRY_VERTICES_PER_LINE; } - public addLine (v0: Vec3, v1: Vec3, color: Color, depthTest = true) { + public addLine (v0: Vec3, v1: Vec3, color: Color, depthTest = true): void { const lines = this._buffers.lines[depthTest ? 1 : 0]; if (lines._vertexCount + GEOMETRY_VERTICES_PER_LINE > lines._maxVertices) { warnID(12008); @@ -327,7 +327,7 @@ export class GeometryRenderer { lines._vertexCount += GEOMETRY_VERTICES_PER_LINE; } - public addTriangle (v0: Vec3, v1: Vec3, v2: Vec3, color: Color, wireframe = true, depthTest = true, unlit = false) { + public addTriangle (v0: Vec3, v1: Vec3, v2: Vec3, color: Color, wireframe = true, depthTest = true, unlit = false): void { if (wireframe) { this.addLine(v0, v1, color, depthTest); this.addLine(v1, v2, color, depthTest); @@ -377,7 +377,7 @@ export class GeometryRenderer { triangles._vertexCount += GEOMETRY_VERTICES_PER_TRIANGLE; } - public addQuad (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, color: Color, wireframe = true, depthTest = true, unlit = false) { + public addQuad (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, color: Color, wireframe = true, depthTest = true, unlit = false): void { /** * 3---2 * | | @@ -396,7 +396,7 @@ export class GeometryRenderer { } public addBoundingBox (aabb: geometry.AABB, color: Color, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform: Mat4 = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform: Mat4 = new Mat4()): void { /** * 2---3 * / / @@ -455,7 +455,7 @@ export class GeometryRenderer { } } - public addCross (position: Vec3, size: number, color: Color, depthTest = true) { + public addCross (position: Vec3, size: number, color: Color, depthTest = true): void { const halfSize = size * 0.5; const v0 = new Vec3(position.x - halfSize, position.y, position.z); @@ -471,7 +471,7 @@ export class GeometryRenderer { this.addLine(v0, v1, color, depthTest); } - public addFrustum (frustum: geometry.Frustum, color: Color, depthTest = true) { + public addFrustum (frustum: geometry.Frustum, color: Color, depthTest = true): void { const vertices = frustum.vertices; this.addLine(vertices[0], vertices[1], color, depthTest); @@ -491,7 +491,7 @@ export class GeometryRenderer { } public addCapsule (center: Vec3, radius: number, height: number, color: Color, segmentsU = 32, hemiSegmentsV = 8, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const deltaPhi = Math.PI * 2.0 / segmentsU; const deltaTheta = Math.PI / 2.0 / hemiSegmentsV; const bottomCenter = new Vec3(center.x, center.y - height / 2.0, center.z); @@ -552,7 +552,7 @@ export class GeometryRenderer { } public addCylinder (center: Vec3, radius: number, height: number, color: Color, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const deltaPhi = Math.PI * 2.0 / segments; const bottomCenter = new Vec3(center.x, center.y - height / 2.0, center.z); const topCenter = new Vec3(center.x, center.y + height / 2.0, center.z); @@ -588,7 +588,7 @@ export class GeometryRenderer { } public addCone (center: Vec3, radius: number, height: number, color: Color, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const deltaPhi = Math.PI * 2.0 / segments; const bottomCenter = new Vec3(center.x, center.y - height / 2.0, center.z); const topCenter = new Vec3(center.x, center.y + height / 2.0, center.z); @@ -615,7 +615,7 @@ export class GeometryRenderer { } } - public addCircle (center: Vec3, radius: number, color: Color, segments = 32, depthTest = true, useTransform = false, transform = new Mat4()) { + public addCircle (center: Vec3, radius: number, color: Color, segments = 32, depthTest = true, useTransform = false, transform = new Mat4()): void { const deltaPhi = Math.PI * 2.0 / segments; const points = new Array(); @@ -637,7 +637,7 @@ export class GeometryRenderer { } public addArc (center: Vec3, radius: number, color: Color, startAngle: number, endAngle: number, segments = 32, - depthTest = true, useTransform = false, transform = new Mat4()) { + depthTest = true, useTransform = false, transform = new Mat4()): void { const startRadian = toRadian(startAngle); const endRadian = toRadian(endAngle); const deltaPhi = (endRadian - startRadian) / segments; @@ -661,7 +661,7 @@ export class GeometryRenderer { } public addPolygon (center: Vec3, radius: number, color: Color, segments = 6, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { if (wireframe) { this.addCircle(center, radius, color, segments, depthTest, useTransform, transform); } else { @@ -670,7 +670,7 @@ export class GeometryRenderer { } public addDisc (center: Vec3, radius: number, color: Color, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const deltaPhi = Math.PI * 2.0 / segments; const points = new Array(); const newCenter = new Vec3(center); @@ -702,7 +702,7 @@ export class GeometryRenderer { } public addSector (center: Vec3, radius: number, color: Color, startAngle: number, endAngle: number, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const startRadian = toRadian(startAngle); const endRadian = toRadian(endAngle); const deltaPhi = (endRadian - startRadian) / segments; @@ -736,7 +736,7 @@ export class GeometryRenderer { } public addSphere (center: Vec3, radius: number, color: Color, segmentsU = 32, segmentsV = 16, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const deltaPhi = Math.PI * 2.0 / segmentsU; const deltaTheta = Math.PI / segmentsV; const points = new Array>(); @@ -778,7 +778,7 @@ export class GeometryRenderer { } public addTorus (center: Vec3, bigRadius: number, radius: number, color: Color, segmentsU = 32, segmentsV = 16, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const deltaPhi = Math.PI * 2.0 / segmentsU; const deltaTheta = Math.PI * 2.0 / segmentsV; const points = new Array>(); @@ -819,7 +819,7 @@ export class GeometryRenderer { } public addOctahedron (center: Vec3, radius: number, color: Color, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()) { + wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { const points = new Array(); points.push(new Vec3(radius + center.x, center.y, center.z)); @@ -863,7 +863,7 @@ export class GeometryRenderer { } public addBezier (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, color: Color, segments = 32, - depthTest = true, useTransform = false, transform = new Mat4()) { + depthTest = true, useTransform = false, transform = new Mat4()): void { const deltaT = 1.0 / segments; const points = new Array(); @@ -899,7 +899,7 @@ export class GeometryRenderer { } } - public addSpline (spline: geometry.Spline, color: Color, index = 0xffffffff, knotSize = 0.5, segments = 32, depthTest = true) { + public addSpline (spline: geometry.Spline, color: Color, index = 0xffffffff, knotSize = 0.5, segments = 32, depthTest = true): void { const numPoints = segments + 1; const points = spline.getPoints(numPoints, index); @@ -918,7 +918,7 @@ export class GeometryRenderer { } } - public addMesh (center: Vec3, vertices: Array, color: Color, depthTest = true, useTransform = false, transform = new Mat4()) { + public addMesh (center: Vec3, vertices: Array, color: Color, depthTest = true, useTransform = false, transform = new Mat4()): void { for (let i = 0; i < vertices.length; i += 3) { const v0 = new Vec3(center.x + vertices[i].x, center.y + vertices[i].y, center.z + vertices[i].z); const v1 = new Vec3(center.x + vertices[i + 1].x, center.y + vertices[i + 1].y, center.z + vertices[i + 1].z); @@ -937,7 +937,7 @@ export class GeometryRenderer { } public addIndexedMesh (center: Vec3, vertices: Array, indices: Array, color: Color, - depthTest = true, useTransform = false, transform = new Mat4()) { + depthTest = true, useTransform = false, transform = new Mat4()): void { for (let i = 0; i < indices.length; i += 3) { const v0 = new Vec3(center.x + vertices[indices[i]].x, center.y + vertices[indices[i]].y, center.z + vertices[indices[i]].z); const v1 = new Vec3(center.x + vertices[indices[i + 1]].x, center.y + vertices[indices[i + 1]].y, center.z + vertices[indices[i + 1]].z); diff --git a/cocos/rendering/global-descriptor-set-manager.ts b/cocos/rendering/global-descriptor-set-manager.ts index 810f4fe2b6e..aff3b5a0798 100644 --- a/cocos/rendering/global-descriptor-set-manager.ts +++ b/cocos/rendering/global-descriptor-set-manager.ts @@ -55,21 +55,21 @@ export class GlobalDSManager { private _linearSampler: Sampler; private _pointSampler: Sampler; - get descriptorSetMap () { + get descriptorSetMap (): Map { return this._descriptorSetMap; } // TODO: Future extensions of PCSS require search depth to compute the penumbra, which requires linear sampling - get linearSampler () { + get linearSampler (): Sampler { return this._linearSampler; } // TODO: For the use of hard and soft, point sampling is required - get pointSampler () { + get pointSampler (): Sampler { return this._pointSampler; } - get descriptorSetLayout () { + get descriptorSetLayout (): DescriptorSetLayout { return this._descriptorSetLayout; } @@ -78,7 +78,7 @@ export class GlobalDSManager { this._globalDescriptorSet = val; } - get globalDescriptorSet () { + get globalDescriptorSet (): DescriptorSet { return this._globalDescriptorSet; } @@ -94,7 +94,7 @@ export class GlobalDSManager { this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout)); } - regenLayout () { + regenLayout (): void { const layoutInfo = new DescriptorSetLayoutInfo(globalDescriptorSetLayout.bindings); this._descriptorSetLayout = this._device.createDescriptorSetLayout(layoutInfo); @@ -107,7 +107,7 @@ export class GlobalDSManager { * @param binding The target binding. * @param buffer The buffer to be bound. */ - public bindBuffer (binding: number, buffer: Buffer) { + public bindBuffer (binding: number, buffer: Buffer): void { this._globalDescriptorSet.bindBuffer(binding, buffer); const it = this._descriptorSetMap.values(); let res = it.next(); @@ -124,7 +124,7 @@ export class GlobalDSManager { * @param binding The target binding. * @param sampler The sampler to be bound. */ - public bindSampler (binding: number, sampler: Sampler) { + public bindSampler (binding: number, sampler: Sampler): void { this._globalDescriptorSet.bindSampler(binding, sampler); const it = this._descriptorSetMap.values(); let res = it.next(); @@ -141,7 +141,7 @@ export class GlobalDSManager { * @param binding The target binding. * @param texture The texture to be bound. */ - public bindTexture (binding: number, texture: Texture) { + public bindTexture (binding: number, texture: Texture): void { this._globalDescriptorSet.bindTexture(binding, texture); const it = this._descriptorSetMap.values(); let res = it.next(); @@ -156,7 +156,7 @@ export class GlobalDSManager { * @en Update all descriptorSet * @zh 更新所有的 descriptorSet */ - public update () { + public update (): void { this._globalDescriptorSet.update(); const it = this._descriptorSetMap.values(); let res = it.next(); @@ -173,7 +173,7 @@ export class GlobalDSManager { * @param idx Specify index creation * @return descriptorSet */ - public getOrCreateDescriptorSet (light: Light) { + public getOrCreateDescriptorSet (light: Light): DescriptorSet | undefined { const device = this._device; // The global descriptorSet is managed by the pipeline and binds the buffer @@ -205,7 +205,7 @@ export class GlobalDSManager { return this._descriptorSetMap.get(light); } - public destroy () { + public destroy (): void { this._descriptorSetLayout.destroy(); } } diff --git a/cocos/rendering/index.jsb.ts b/cocos/rendering/index.jsb.ts index 0247024c3fb..a6fe869819f 100644 --- a/cocos/rendering/index.jsb.ts +++ b/cocos/rendering/index.jsb.ts @@ -304,7 +304,7 @@ export class RenderQueueDesc { this.stages = []; } - public init() { + public init(): any { return new nr.RenderQueueDesc(this.isTransparent, this.sortMode, this.stages); } } @@ -441,14 +441,14 @@ class RenderTextureConfig { } -function proxyArrayAttributeImpl(proto: any, attr: string) { +function proxyArrayAttributeImpl(proto: any, attr: string): void { const proxyTarget = `_${attr}_target`; - let arrayProxy = (self, targetArrayAttr: string) => { + let arrayProxy = (self, targetArrayAttr: string): any => { return new Proxy(self[targetArrayAttr], { - get(targetArray, prop, receiver) { + get(targetArray, prop, receiver): any { return Reflect.get(targetArray, prop, receiver); }, - set(targetArray, prop, receiver) { + set(targetArray, prop, receiver): boolean { const ret = Reflect.set(targetArray, prop, receiver); self[targetArrayAttr] = targetArray; return ret; diff --git a/cocos/rendering/index.ts b/cocos/rendering/index.ts index d261599fb2d..68a0d0434a8 100644 --- a/cocos/rendering/index.ts +++ b/cocos/rendering/index.ts @@ -56,7 +56,7 @@ export { DebugView } from './debug-view'; export { ReflectionProbeFlow } from './reflection-probe/reflection-probe-flow'; export { ReflectionProbeStage } from './reflection-probe/reflection-probe-stage'; -export function createDefaultPipeline () { +export function createDefaultPipeline (): ForwardPipeline { const rppl = new ForwardPipeline(); rppl.initialize({ flows: [] }); return rppl; diff --git a/cocos/rendering/instanced-buffer.ts b/cocos/rendering/instanced-buffer.ts index bb593be00b4..7df49320153 100644 --- a/cocos/rendering/instanced-buffer.ts +++ b/cocos/rendering/instanced-buffer.ts @@ -59,7 +59,7 @@ export class InstancedBuffer { this.pass = pass; } - public destroy () { + public destroy (): void { for (let i = 0; i < this.instances.length; ++i) { const instance = this.instances[i]; instance.vb.destroy(); @@ -68,7 +68,7 @@ export class InstancedBuffer { this.instances.length = 0; } - public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null) { + public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null): void { const attrs = subModel.instancedAttributeBlock; const stride = attrs.buffer.length; if (!stride) { return; } // we assume per-instance attributes are always present @@ -152,7 +152,7 @@ export class InstancedBuffer { this.hasPendingModels = true; } - public uploadBuffers (cmdBuff: CommandBuffer) { + public uploadBuffers (cmdBuff: CommandBuffer): void { for (let i = 0; i < this.instances.length; ++i) { const instance = this.instances[i]; if (!instance.count) { continue; } @@ -161,7 +161,7 @@ export class InstancedBuffer { } } - public clear () { + public clear (): void { for (let i = 0; i < this.instances.length; ++i) { const instance = this.instances[i]; instance.count = 0; diff --git a/cocos/rendering/pass-phase.ts b/cocos/rendering/pass-phase.ts index 628eac3f23a..c60eb697166 100644 --- a/cocos/rendering/pass-phase.ts +++ b/cocos/rendering/pass-phase.ts @@ -22,10 +22,10 @@ THE SOFTWARE. */ -export const getPhaseID = (() => { +export const getPhaseID = ((): (phaseName: string | number) => number => { const phases: Map = new Map(); let phaseNum = 0; - return (phaseName: string | number) => { + return (phaseName: string | number): number => { if (typeof phaseName === 'number') { return phaseName; } if (!phases.has(phaseName)) { phases.set(phaseName, 1 << phaseNum); diff --git a/cocos/rendering/pipeline-funcs.ts b/cocos/rendering/pipeline-funcs.ts index b8792cbcebf..fa55e3739af 100644 --- a/cocos/rendering/pipeline-funcs.ts +++ b/cocos/rendering/pipeline-funcs.ts @@ -39,7 +39,7 @@ const profilerScissor = new Rect(); * @param out Output color object * @param gamma Gamma value in SRGB space */ -export function SRGBToLinear (out: IVec4Like, gamma: IVec4Like) { +export function SRGBToLinear (out: IVec4Like, gamma: IVec4Like): void { // out.x = Math.pow(gamma.x, 2.2); // out.y = Math.pow(gamma.y, 2.2); // out.z = Math.pow(gamma.z, 2.2); @@ -54,7 +54,7 @@ export function SRGBToLinear (out: IVec4Like, gamma: IVec4Like) { * @param out Output color object * @param linear Color value in linear space */ -export function LinearToSRGB (out: IVec4Like, linear: IVec4Like) { +export function LinearToSRGB (out: IVec4Like, linear: IVec4Like): void { // out.x = Math.pow(linear.x, 0.454545); // out.y = Math.pow(linear.y, 0.454545); // out.z = Math.pow(linear.z, 0.454545); @@ -69,7 +69,7 @@ export function getProfilerCamera (): Camera | null { return profilerCamera; } -export function decideProfilerCamera (cameras: Camera[]) { +export function decideProfilerCamera (cameras: Camera[]): void { for (let i = cameras.length - 1; i >= 0; --i) { const camera = cameras[i]; if (camera.window.swapchain) { @@ -80,7 +80,7 @@ export function decideProfilerCamera (cameras: Camera[]) { profilerCamera = null; } -export function renderProfiler (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer, profiler: Model | null, camera: Camera) { +export function renderProfiler (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer, profiler: Model | null, camera: Camera): void { if (isEnableEffect()) { return; } diff --git a/cocos/rendering/pipeline-scene-data.ts b/cocos/rendering/pipeline-scene-data.ts index 63a9898ed5b..68079117f29 100644 --- a/cocos/rendering/pipeline-scene-data.ts +++ b/cocos/rendering/pipeline-scene-data.ts @@ -47,14 +47,14 @@ export class PipelineSceneData { * @zh 是否开启 HDR。 * @readonly */ - public get isHDR () { + public get isHDR (): boolean { return this._isHDR; } public set isHDR (val: boolean) { this._isHDR = val; } - public get shadingScale () { + public get shadingScale (): number { return this._shadingScale; } @@ -62,7 +62,7 @@ export class PipelineSceneData { this._shadingScale = val; } - public get csmSupported () { + public get csmSupported (): boolean { return this._csmSupported; } public set csmSupported (val: boolean) { @@ -75,7 +75,7 @@ export class PipelineSceneData { * @zh 获取全局的4s标准模型 * @returns The model id */ - get standardSkinModel () { return this._standardSkinModel; } + get standardSkinModel (): MeshRenderer | null { return this._standardSkinModel; } /** * @engineInternal @@ -88,7 +88,7 @@ export class PipelineSceneData { this._standardSkinModel = val; } - get skinMaterialModel () { + get skinMaterialModel (): Model { return this._skinMaterialModel!; } set skinMaterialModel (val: Model) { @@ -135,7 +135,7 @@ export class PipelineSceneData { this._shadingScale = 1.0; } - public activate (device: Device) { + public activate (device: Device): boolean { this._device = device; this.initGeometryRendererMaterials(); @@ -144,7 +144,7 @@ export class PipelineSceneData { return true; } - public initGeometryRendererMaterials () { + public initGeometryRendererMaterials (): void { let offset = 0; for (let tech = 0; tech < GEOMETRY_RENDERER_TECHNIQUE_COUNT; tech++) { this._geometryRendererMaterials[tech] = new Material(); @@ -159,15 +159,15 @@ export class PipelineSceneData { } } - public get geometryRendererPasses () { + public get geometryRendererPasses (): Pass[] { return this._geometryRendererPasses; } - public get geometryRendererShaders () { + public get geometryRendererShaders (): Shader[] { return this._geometryRendererShaders; } - public initOcclusionQuery () { + public initOcclusionQuery (): void { if (!this._occlusionQueryInputAssembler) { this._occlusionQueryInputAssembler = this._createOcclusionQueryIA(); } @@ -191,10 +191,10 @@ export class PipelineSceneData { return null; } - public updatePipelineSceneData () { + public updatePipelineSceneData (): void { } - public destroy () { + public destroy (): void { this.shadows.destroy(); this.csmLayers.destroy(); this.validPunctualLights.length = 0; @@ -206,7 +206,7 @@ export class PipelineSceneData { this._occlusionQueryIndicesBuffer = null; } - private _createOcclusionQueryIA () { + private _createOcclusionQueryIA (): InputAssembler { // create vertex buffer const device = this._device; const vertices = new Float32Array([-1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1]); diff --git a/cocos/rendering/pipeline-state-manager.ts b/cocos/rendering/pipeline-state-manager.ts index afd645fbfdc..2df742117a1 100644 --- a/cocos/rendering/pipeline-state-manager.ts +++ b/cocos/rendering/pipeline-state-manager.ts @@ -29,7 +29,7 @@ export class PipelineStateManager { private static _PSOHashMap: Map = new Map(); // pass is only needed on TS. - static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler) { + static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState { const hash1 = pass.hash; const hash2 = renderPass.hash; const hash3 = ia.attributesHash; diff --git a/cocos/rendering/pipeline-ubo.ts b/cocos/rendering/pipeline-ubo.ts index b173fdc3a6f..a157f8073f1 100644 --- a/cocos/rendering/pipeline-ubo.ts +++ b/cocos/rendering/pipeline-ubo.ts @@ -46,7 +46,7 @@ const _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0); const _tempVec3 = new Vec3(); export class PipelineUBO { - public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { + public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array): void { const director = cclegacy.director; const root = director.root; const fv = bufferView; @@ -92,7 +92,7 @@ export class PipelineUBO { } public static updateCameraUBOView (pipeline: PipelineRuntime, bufferView: Float32Array, - camera: Camera) { + camera: Camera): void { const scene = camera.scene ? camera.scene : cclegacy.director.getScene().renderScene; const mainLight = scene.mainLight; const sceneData = pipeline.pipelineSceneData; @@ -208,7 +208,7 @@ export class PipelineUBO { return 0.0; } - public static updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: Float32Array) { + public static updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: Float32Array): void { Vec3.normalize(_tempVec3, shadowInfo.normal); shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; @@ -217,7 +217,7 @@ export class PipelineUBO { } public static updateShadowUBOView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, - csmBufferView: Float32Array, camera: Camera) { + csmBufferView: Float32Array, camera: Camera): void { const device = pipeline.device; const mainLight = camera.scene!.mainLight; const sceneData = pipeline.pipelineSceneData; @@ -315,7 +315,7 @@ export class PipelineUBO { } } - public static updateShadowUBOLightView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, light: Light, level: number) { + public static updateShadowUBOLightView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, light: Light, level: number): void { const device = pipeline.device; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; @@ -433,16 +433,16 @@ export class PipelineUBO { *| 2 | -1 | 1 | | *| 3 | 1 | 1 | GL-like | */ - public static getCombineSignY () { + public static getCombineSignY (): number { return PipelineUBO._combineSignY; } - private _initCombineSignY () { + private _initCombineSignY (): void { const device = this._device; PipelineUBO._combineSignY = (device.capabilities.screenSpaceSignY * 0.5 + 0.5) << 1 | (device.capabilities.clipSpaceSignY * 0.5 + 0.5); } - public activate (device: Device, pipeline: PipelineRuntime) { + public activate (device: Device, pipeline: PipelineRuntime): void { this._device = device; this._pipeline = pipeline; const ds = this._pipeline.descriptorSet; @@ -488,7 +488,7 @@ export class PipelineUBO { * @en Update all UBOs * @zh 更新全部 UBO。 */ - public updateGlobalUBO (window: RenderWindow) { + public updateGlobalUBO (window: RenderWindow): void { const globalDSManager = this._pipeline.globalDSManager; const ds = this._pipeline.descriptorSet; const cmdBuffer = this._pipeline.commandBuffers; @@ -500,7 +500,7 @@ export class PipelineUBO { globalDSManager.update(); } - public updateCameraUBO (camera: Camera) { + public updateCameraUBO (camera: Camera): void { const globalDSManager = this._pipeline.globalDSManager; const ds = this._pipeline.descriptorSet; const cmdBuffer = this._pipeline.commandBuffers; @@ -511,7 +511,7 @@ export class PipelineUBO { globalDSManager.update(); } - public updateShadowUBO (camera: Camera) { + public updateShadowUBO (camera: Camera): void { const sceneData = this._pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; if (!shadowInfo.enabled) return; @@ -531,7 +531,7 @@ export class PipelineUBO { cmdBuffer[0].updateBuffer(ds.getBuffer(csmBinding), this._csmUBO); } - public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0) { + public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0): void { PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light, level); globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); @@ -540,7 +540,7 @@ export class PipelineUBO { this._pipeline.commandBuffers[0].updateBuffer(globalDS.getBuffer(binding), this._shadowUBO); } - public updateShadowUBORange (offset: number, data: Mat4 | Color) { + public updateShadowUBORange (offset: number, data: Mat4 | Color): void { if (data instanceof Mat4) { Mat4.toArray(this._shadowUBO, data, offset); } else if (data instanceof Color) { @@ -548,6 +548,6 @@ export class PipelineUBO { } } - public destroy () { + public destroy (): void { } } diff --git a/cocos/rendering/planar-shadow-queue.ts b/cocos/rendering/planar-shadow-queue.ts index 1fcd4391944..8582458b1cd 100644 --- a/cocos/rendering/planar-shadow-queue.ts +++ b/cocos/rendering/planar-shadow-queue.ts @@ -67,7 +67,7 @@ export class PlanarShadowQueue { * @zh * 清除 planar-shadow 渲染队列数据 */ - public clear () { + public clear (): void { this._subModelArray.length = 0; this._shaderArray.length = 0; this._passArray.length = 0; @@ -75,7 +75,7 @@ export class PlanarShadowQueue { this._castModels.length = 0; } - public gatherShadowPasses (camera: Camera, cmdBuff: CommandBuffer) { + public gatherShadowPasses (camera: Camera, cmdBuff: CommandBuffer): void { this.clear(); const pipelineSceneData = this._pipeline.pipelineSceneData; const shadows = pipelineSceneData.shadows; @@ -136,7 +136,7 @@ export class PlanarShadowQueue { this._instancedQueue.uploadBuffers(cmdBuff); } - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { + public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void { const shadows = this._pipeline.pipelineSceneData.shadows; if (!shadows.enabled || shadows.type !== ShadowType.Planar) { return; } diff --git a/cocos/rendering/post-process/components/blit-screen.ts b/cocos/rendering/post-process/components/blit-screen.ts index d46b2a0ac21..38b1d9f9888 100644 --- a/cocos/rendering/post-process/components/blit-screen.ts +++ b/cocos/rendering/post-process/components/blit-screen.ts @@ -9,7 +9,7 @@ class BlitScreenMaterial { _material: Material | undefined; @property(Material) - get material () { + get material (): Material | undefined { return this._material; } set material (v) { @@ -28,7 +28,7 @@ export class BlitScreen extends PostProcessSetting { @property(Material) _activeMaterials: Material[] = [] @property({ type: Material, visible: false }) - get activeMaterials () { + get activeMaterials (): Material[] { return this._activeMaterials; } set activeMaterials (v) { @@ -39,7 +39,7 @@ export class BlitScreen extends PostProcessSetting { _materials: BlitScreenMaterial[] = [] @property(BlitScreenMaterial) - get materials () { + get materials (): BlitScreenMaterial[] { return this._materials; } set materials (v) { @@ -47,7 +47,7 @@ export class BlitScreen extends PostProcessSetting { this.updateActiveMateirals(); } - updateActiveMateirals () { + updateActiveMateirals (): void { const materials = this._materials; this._activeMaterials.length = 0; for (let i = 0; i < materials.length; i++) { @@ -58,7 +58,7 @@ export class BlitScreen extends PostProcessSetting { } } - onLoad () { + onLoad (): void { this.updateActiveMateirals(); } } diff --git a/cocos/rendering/post-process/components/bloom.ts b/cocos/rendering/post-process/components/bloom.ts index 39c9f9c1056..ff1a87290e8 100644 --- a/cocos/rendering/post-process/components/bloom.ts +++ b/cocos/rendering/post-process/components/bloom.ts @@ -19,7 +19,7 @@ export class Bloom extends PostProcessSetting { set threshold (value: number) { this._threshold = value; } - get threshold () { + get threshold (): number { return this._threshold; } @@ -29,7 +29,7 @@ export class Bloom extends PostProcessSetting { set iterations (value: number) { this._iterations = value; } - get iterations () { + get iterations (): number { return this._iterations; } @@ -38,7 +38,7 @@ export class Bloom extends PostProcessSetting { set intensity (value: number) { this._intensity = value; } - get intensity () { + get intensity (): number { return this._intensity; } } diff --git a/cocos/rendering/post-process/components/color-grading.ts b/cocos/rendering/post-process/components/color-grading.ts index 989e8a5659d..9ad8d331cd1 100644 --- a/cocos/rendering/post-process/components/color-grading.ts +++ b/cocos/rendering/post-process/components/color-grading.ts @@ -20,7 +20,7 @@ export class ColorGrading extends PostProcessSetting { set contribute (value: number) { this._contribute = value; } - get contribute () { + get contribute (): number { return this._contribute; } @@ -29,7 +29,7 @@ export class ColorGrading extends PostProcessSetting { set colorGradingMap (val: Texture2D) { this._colorGradingMap = val; } - get colorGradingMap () { + get colorGradingMap (): Texture2D { return this._colorGradingMap!; } } diff --git a/cocos/rendering/post-process/components/fsr.ts b/cocos/rendering/post-process/components/fsr.ts index d879e73bb58..307214b28eb 100644 --- a/cocos/rendering/post-process/components/fsr.ts +++ b/cocos/rendering/post-process/components/fsr.ts @@ -14,7 +14,7 @@ export class FSR extends PostProcessSetting { @slide @range([0.05, 1, 0.01]) @type(CCFloat) - get sharpness () { + get sharpness (): number { return this._sharpness; } set sharpness (v) { diff --git a/cocos/rendering/post-process/components/hbao.ts b/cocos/rendering/post-process/components/hbao.ts index e2bb5db4e6a..f4926be3ccb 100644 --- a/cocos/rendering/post-process/components/hbao.ts +++ b/cocos/rendering/post-process/components/hbao.ts @@ -51,7 +51,7 @@ export class HBAO extends PostProcessSetting { set radiusScale (value: number) { this._radiusScale = value; } - get radiusScale () { + get radiusScale (): number { return this._radiusScale; } @@ -64,7 +64,7 @@ export class HBAO extends PostProcessSetting { set angleBiasDegree (value: number) { this._angleBiasDegree = value; } - get angleBiasDegree () { + get angleBiasDegree (): number { return this._angleBiasDegree; } @@ -77,7 +77,7 @@ export class HBAO extends PostProcessSetting { set blurSharpness (value: number) { this._blurSharpness = value; } - get blurSharpness () { + get blurSharpness (): number { return this._blurSharpness; } @@ -89,7 +89,7 @@ export class HBAO extends PostProcessSetting { set aoSaturation (value: number) { this._aoSaturation = value; } - get aoSaturation () { + get aoSaturation (): number { return this._aoSaturation; } @@ -99,7 +99,7 @@ export class HBAO extends PostProcessSetting { set needBlur (value: boolean) { this._needBlur = value; } - get needBlur () { + get needBlur (): boolean { return this._needBlur; } } diff --git a/cocos/rendering/post-process/components/post-process-setting.ts b/cocos/rendering/post-process/components/post-process-setting.ts index f0e672e57d6..0e7cb12306e 100644 --- a/cocos/rendering/post-process/components/post-process-setting.ts +++ b/cocos/rendering/post-process/components/post-process-setting.ts @@ -7,18 +7,18 @@ import { PostProcess } from './post-process'; @executeInEditMode export class PostProcessSetting extends Component { static _default: PostProcessSetting | undefined - static get default () { + static get default (): PostProcessSetting { if (!this._default) { this._default = new this(); } return this._default; } - onEnable () { + onEnable (): void { const pp = this.getComponent(PostProcess); pp?.addSetting(this); } - onDisable () { + onDisable (): void { const pp = this.getComponent(PostProcess); pp?.removeSetting(this); } diff --git a/cocos/rendering/post-process/components/post-process.ts b/cocos/rendering/post-process/components/post-process.ts index 9c322c165b9..066d9dbd6c3 100644 --- a/cocos/rendering/post-process/components/post-process.ts +++ b/cocos/rendering/post-process/components/post-process.ts @@ -19,7 +19,7 @@ export class PostProcess extends Component { @slide @range([0.01, 1, 0.01]) @property - get shadingScale () { + get shadingScale (): number { return this._shadingScale; } set shadingScale (v) { @@ -36,21 +36,21 @@ export class PostProcess extends Component { settings: Map = new Map() - addSetting (setting: PostProcessSetting) { + addSetting (setting: PostProcessSetting): void { this.settings.set(setting.constructor as typeof PostProcessSetting, setting); } - removeSetting (setting: PostProcessSetting) { + removeSetting (setting: PostProcessSetting): void { this.settings.delete(setting.constructor as typeof PostProcessSetting); } - getSetting (ctor: typeof PostProcessSetting) { + getSetting (ctor: typeof PostProcessSetting): PostProcessSetting | undefined { return this.settings.get(ctor); } - onEnable () { + onEnable (): void { PostProcess.all.push(this); } - onDisable () { + onDisable (): void { const idx = PostProcess.all.indexOf(this); if (idx !== -1) { PostProcess.all.splice(idx, 1); diff --git a/cocos/rendering/post-process/passes/base-pass.ts b/cocos/rendering/post-process/passes/base-pass.ts index 7e9cdde18b8..2df04396bd7 100644 --- a/cocos/rendering/post-process/passes/base-pass.ts +++ b/cocos/rendering/post-process/passes/base-pass.ts @@ -11,11 +11,11 @@ import { cclegacy, macro } from '../../../core'; let _BasePassID = 0; -export function getRTFormatBeforeToneMapping (ppl: BasicPipeline) { +export function getRTFormatBeforeToneMapping (ppl: BasicPipeline): Format { const useFloatOutput = ppl.getMacroBool('CC_USE_FLOAT_OUTPUT'); return ppl.pipelineSceneData.isHDR && useFloatOutput && supportsRGBA16HalfFloatTexture(ppl.device) ? Format.RGBA16F : Format.RGBA8; } -export function forceEnableFloatOutput (ppl: PipelineRuntime) { +export function forceEnableFloatOutput (ppl: PipelineRuntime): boolean { let enabled = ppl.getMacroBool('CC_USE_FLOAT_OUTPUT'); if (ppl.pipelineSceneData.isHDR && !enabled) { const supportFloatOutput = supportsRGBA16HalfFloatTexture(ppl.device); @@ -27,7 +27,7 @@ export function forceEnableFloatOutput (ppl: PipelineRuntime) { return enabled; } -export function disablePostProcessForDebugView () { +export function disablePostProcessForDebugView (): boolean { const debugView = cclegacy.director.root.debugView; return debugView.singleMode as number > 0; } @@ -47,7 +47,7 @@ export abstract class BasePass { // private _materialMap: Map = new Map() _material: Material | undefined - get material () { + get material (): Material { const effectReloaded = false; // if (EDITOR && this._material) { // const effect = builtinResMgr.get(this.effectName); @@ -82,21 +82,21 @@ export abstract class BasePass { lastPass: BasePass | undefined; - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { const name = this.outputNames[index] + this.name; return `${name}_${this._id}_${getCameraUniqueID(camera)}`; } enableInAllEditorCamera = false; - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { return this.enable; } - renderProfiler (camera) { + renderProfiler (camera): void { if (passContext.isFinalCamera && !EDITOR) { passContext.pass!.showStatistics = true; } } - abstract render (camera: Camera, ppl: Pipeline); + abstract render (camera: Camera, ppl: Pipeline): any; } diff --git a/cocos/rendering/post-process/passes/blit-screen-pass.ts b/cocos/rendering/post-process/passes/blit-screen-pass.ts index fe9c53e1651..7b1ef32a2d0 100644 --- a/cocos/rendering/post-process/passes/blit-screen-pass.ts +++ b/cocos/rendering/post-process/passes/blit-screen-pass.ts @@ -13,18 +13,18 @@ import { BlitScreen } from '../components/blit-screen'; const outputNames = ['BlitScreenColor0', 'BlitScreenColor1']; export class BlitScreenPass extends SettingPass { - get setting () { return getSetting(BlitScreen); } + get setting (): BlitScreen { return getSetting(BlitScreen); } name = 'BlitScreenPass' effectName = 'pipeline/post-process/blit-screen'; outputName = outputNames[0] - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { return this.outputName; } - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { const enable = super.checkEnable(camera); const setting = this.setting; return enable && (setting.activeMaterials.length > 0); diff --git a/cocos/rendering/post-process/passes/bloom-pass.ts b/cocos/rendering/post-process/passes/bloom-pass.ts index c47ad409832..5c0c8fe470c 100644 --- a/cocos/rendering/post-process/passes/bloom-pass.ts +++ b/cocos/rendering/post-process/passes/bloom-pass.ts @@ -14,9 +14,9 @@ const BLOOM_DOWNSAMPLEPASS_INDEX = 1; const BLOOM_UPSAMPLEPASS_INDEX = BLOOM_DOWNSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM; const BLOOM_COMBINEPASS_INDEX = BLOOM_UPSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM; export class BloomPass extends SettingPass { - get setting () { return getSetting(Bloom); } + get setting (): Bloom { return getSetting(Bloom); } - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); if (disablePostProcessForDebugView()) { enable = false; diff --git a/cocos/rendering/post-process/passes/color-grading-pass.ts b/cocos/rendering/post-process/passes/color-grading-pass.ts index fa42412a1c7..fcbff1da807 100644 --- a/cocos/rendering/post-process/passes/color-grading-pass.ts +++ b/cocos/rendering/post-process/passes/color-grading-pass.ts @@ -10,9 +10,9 @@ import { ColorGrading } from '../components'; import { disablePostProcessForDebugView } from './base-pass'; export class ColorGradingPass extends SettingPass { - get setting () { return getSetting(ColorGrading); } + get setting (): ColorGrading { return getSetting(ColorGrading); } - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); if (disablePostProcessForDebugView()) { enable = false; diff --git a/cocos/rendering/post-process/passes/forward-final-pass.ts b/cocos/rendering/post-process/passes/forward-final-pass.ts index 9b4fdcffe86..06372f2c185 100644 --- a/cocos/rendering/post-process/passes/forward-final-pass.ts +++ b/cocos/rendering/post-process/passes/forward-final-pass.ts @@ -16,7 +16,7 @@ export class ForwardFinalPass extends BasePass { enableInAllEditorCamera = true; - public render (camera: Camera, ppl: Pipeline) { + public render (camera: Camera, ppl: Pipeline): void { if (!this.lastPass) { return; } diff --git a/cocos/rendering/post-process/passes/forward-pass.ts b/cocos/rendering/post-process/passes/forward-pass.ts index a6def0cf7b7..24c99bf8c9f 100644 --- a/cocos/rendering/post-process/passes/forward-pass.ts +++ b/cocos/rendering/post-process/passes/forward-pass.ts @@ -18,7 +18,7 @@ export class ForwardPass extends BasePass { enableInAllEditorCamera = true; depthBufferShadingScale = 1; - calcDepthSlot (camera: Camera) { + calcDepthSlot (camera: Camera): void { let canUsePrevDepth = !!passContext.depthSlotName; canUsePrevDepth = !(camera.clearFlag & ClearFlagBit.DEPTH_STENCIL); canUsePrevDepth = canUsePrevDepth && passContext.shadingScale === this.depthBufferShadingScale; @@ -30,7 +30,7 @@ export class ForwardPass extends BasePass { passContext.depthSlotName = super.slotName(camera, 1); } - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { if (index === 1) { return passContext.depthSlotName; } @@ -38,7 +38,7 @@ export class ForwardPass extends BasePass { return super.slotName(camera, index); } - public render (camera: Camera, ppl: Pipeline) { + public render (camera: Camera, ppl: Pipeline): void { passContext.clearFlag = ClearFlagBit.COLOR | (camera.clearFlag & ClearFlagBit.DEPTH_STENCIL); Vec4.set(passContext.clearColor, 0, 0, 0, 0); Vec4.set(passContext.clearDepthColor, camera.clearDepth, camera.clearStencil, 0, 0); diff --git a/cocos/rendering/post-process/passes/forward-transparency-pass.ts b/cocos/rendering/post-process/passes/forward-transparency-pass.ts index 64c4e375914..c6f82d2e108 100644 --- a/cocos/rendering/post-process/passes/forward-transparency-pass.ts +++ b/cocos/rendering/post-process/passes/forward-transparency-pass.ts @@ -37,11 +37,11 @@ export class ForwardTransparencyPass extends BasePass { enableInAllEditorCamera = true; depthBufferShadingScale = 1; - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { return this.lastPass!.slotName(camera, index); } - public render (camera: Camera, ppl: Pipeline) { + public render (camera: Camera, ppl: Pipeline): void { passContext.clearFlag = ClearFlagBit.NONE; const output = this.lastPass!.slotName(camera, 0); diff --git a/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts b/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts index ae4dce7500d..a6d6b6d702b 100644 --- a/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts +++ b/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts @@ -35,11 +35,11 @@ import { ShadowPass } from './shadow-pass'; export class ForwardTransparencySimplePass extends BasePass { name = 'ForwardTransparencySimplePass'; - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { return (passContext.forwardPass as ForwardPass)!.slotName(camera, index); } - public render (camera: Camera, ppl: Pipeline) { + public render (camera: Camera, ppl: Pipeline): void { const pass = passContext.pass!; pass.addQueue(QueueHint.RENDER_TRANSPARENT) .addSceneOfCamera(camera, diff --git a/cocos/rendering/post-process/passes/fsr-pass.ts b/cocos/rendering/post-process/passes/fsr-pass.ts index 223095ee0ec..97956e82797 100644 --- a/cocos/rendering/post-process/passes/fsr-pass.ts +++ b/cocos/rendering/post-process/passes/fsr-pass.ts @@ -11,13 +11,13 @@ import { getSetting, SettingPass } from './setting-pass'; import { game } from '../../../game'; export class FSRPass extends SettingPass { - get setting () { return getSetting(FSR); } + get setting (): FSR { return getSetting(FSR); } name = 'FSRPass' effectName = 'pipeline/post-process/fsr'; outputNames = ['FSRColor'] - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) { enable = false; diff --git a/cocos/rendering/post-process/passes/fxaa-pass.ts b/cocos/rendering/post-process/passes/fxaa-pass.ts index ce0e1364ca5..916b73f09d3 100644 --- a/cocos/rendering/post-process/passes/fxaa-pass.ts +++ b/cocos/rendering/post-process/passes/fxaa-pass.ts @@ -9,7 +9,7 @@ import { getSetting, SettingPass } from './setting-pass'; import { Fxaa } from '../components/fxaa'; export class FxaaPass extends SettingPass { - get setting () { return getSetting(Fxaa); } + get setting (): Fxaa { return getSetting(Fxaa); } name = 'FxaaPass' effectName = 'pipeline/post-process/fxaa-hq'; diff --git a/cocos/rendering/post-process/passes/hbao-pass.ts b/cocos/rendering/post-process/passes/hbao-pass.ts index 0901ea27d0e..1f83a051673 100644 --- a/cocos/rendering/post-process/passes/hbao-pass.ts +++ b/cocos/rendering/post-process/passes/hbao-pass.ts @@ -42,19 +42,19 @@ const vec2 = new Vec2(); class HBAOParams { declare randomTexture: Texture2D; - get uvDepthToEyePosParams () { + get uvDepthToEyePosParams (): Vec4 { return this._uvDepthToEyePosParams; } - get radiusParam () { + get radiusParam (): Vec4 { return this._radiusParam; } - get miscParam () { + get miscParam (): Vec4 { return this._miscParam; } - get blurParam () { + get blurParam (): Vec4 { return this._blurParam; } @@ -115,7 +115,7 @@ class HBAOParams { 235, 100, 24, 255, 252, 36, 158, 255, 254, 20, 142, 255, 245, 135, 124, 255, 251, 43, 121, 255, 253, 31, 145, 255, 235, 98, 160, 255, 240, 146, 198, 255, ]; - private _init () { + private _init (): void { const width = 4; const height = 4; const pixelFormat = Texture2D.PixelFormat.RGBA8888; @@ -140,7 +140,7 @@ class HBAOParams { } } - public update () { + public update (): void { // should be same value as shader const HALF_KERNEL_RADIUS = 4; const INV_LN2 = 1.44269504; @@ -183,13 +183,13 @@ export class HBAOPass extends SettingPass { private _initialize = false; private averageObjectSize = new Map(); - get setting () { return getSetting(HBAO); } + get setting (): HBAO { return getSetting(HBAO); } name = 'HBAOPass' effectName = 'pipeline/post-process/hbao'; outputNames = ['hbaoRTName', 'hbaoBluredRTName'] - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) { enable = false; @@ -197,7 +197,7 @@ export class HBAOPass extends SettingPass { return enable; } - public getSceneScale (camera: Camera) { + public getSceneScale (camera: Camera): number { let sceneScale = camera.nearClip; if (!this.averageObjectSize.has(camera.node.scene)) { this._calculateObjectSize(camera.node.scene, camera.visibility); @@ -263,7 +263,7 @@ export class HBAOPass extends SettingPass { this._renderHBAOCombinedPass(camera, hbaoCombinedInputRTName, inputRT); } - private _renderHBAOPass (camera: Camera, inputDS: string) { + private _renderHBAOPass (camera: Camera, inputDS: string): { rtName: string; dsName: string; } { const cameraID = getCameraUniqueID(camera); const passIdx = this.HBAO_PASS_INDEX; @@ -294,7 +294,7 @@ export class HBAOPass extends SettingPass { return { rtName: outputRT, dsName: inputDS }; } - private _renderHBAOBlurPass (camera: Camera, inputRT: string, inputDS: string, isYPass: boolean) { + private _renderHBAOBlurPass (camera: Camera, inputRT: string, inputDS: string, isYPass: boolean): { rtName: string; dsName: string; } { const cameraID = getCameraUniqueID(camera); passContext.clearBlack(); @@ -332,7 +332,7 @@ export class HBAOPass extends SettingPass { return { rtName: outputRT, dsName: inputDS }; } - private _renderHBAOCombinedPass (camera: Camera, inputRT: string, outputRT: string) { + private _renderHBAOCombinedPass (camera: Camera, inputRT: string, outputRT: string): void { const cameraID = getCameraUniqueID(camera); const passIdx = this.HBAO_COMBINED_PASS_INDEX; @@ -361,7 +361,7 @@ export class HBAOPass extends SettingPass { .version(); } - private _calculateObjectSize (scene: Scene, visibility: number) { + private _calculateObjectSize (scene: Scene, visibility: number): void { if (!scene || !scene.renderScene) { return; } @@ -383,7 +383,7 @@ export class HBAOPass extends SettingPass { } } - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { return this.lastPass!.slotName(camera, index); } } diff --git a/cocos/rendering/post-process/passes/setting-pass.ts b/cocos/rendering/post-process/passes/setting-pass.ts index 8e893c3b958..2e7b5326af8 100644 --- a/cocos/rendering/post-process/passes/setting-pass.ts +++ b/cocos/rendering/post-process/passes/setting-pass.ts @@ -3,7 +3,7 @@ import { PostProcessSetting } from '../components/post-process-setting'; import { passContext } from '../utils/pass-context'; import { BasePass } from './base-pass'; -export function getSetting (settingClass: new () => T) { +export function getSetting (settingClass: new () => T): T { const cls: typeof PostProcessSetting = settingClass as any; let setting = passContext.postProcess && passContext.postProcess.getSetting(cls) as T; if (!setting) { @@ -14,9 +14,9 @@ export function getSetting (settingClass: new () = export abstract class SettingPass extends BasePass { getSetting = getSetting - get setting () { return this.getSetting(PostProcessSetting); } + get setting (): PostProcessSetting { return this.getSetting(PostProcessSetting); } - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { const enable = super.checkEnable(camera); const setting = this.setting; return enable && !!setting && setting.enabledInHierarchy; diff --git a/cocos/rendering/post-process/passes/skin-pass.ts b/cocos/rendering/post-process/passes/skin-pass.ts index 41ee7e02e0f..7696004cb56 100644 --- a/cocos/rendering/post-process/passes/skin-pass.ts +++ b/cocos/rendering/post-process/passes/skin-pass.ts @@ -39,7 +39,7 @@ export const COPY_INPUT_DS_PASS_INDEX = 0; export const SSSS_BLUR_X_PASS_INDEX = 1; export const SSSS_BLUR_Y_PASS_INDEX = 2; -function hasSkinObject (ppl: PipelineRuntime) { +function hasSkinObject (ppl: PipelineRuntime): boolean { const sceneData = ppl.pipelineSceneData; return !!sceneData.skin && sceneData.skin.enabled && !!sceneData.skinMaterialModel; } @@ -55,7 +55,7 @@ export const EXPONENT = 2.0; export const I_SAMPLES_COUNT = 25; export class SSSSBlurData { - get ssssStrength () { + get ssssStrength (): Vec3 { return this._v3SSSSStrength; } set ssssStrength (val: Vec3) { @@ -63,7 +63,7 @@ export class SSSSBlurData { this._updateSampleCount(); } - get ssssFallOff () { + get ssssFallOff (): Vec3 { return this._v3SSSSFallOff; } set ssssFallOff (val: Vec3) { @@ -71,7 +71,7 @@ export class SSSSBlurData { this._updateSampleCount(); } - get kernel () { + get kernel (): Vec4[] { return this._kernel; } @@ -84,7 +84,7 @@ export class SSSSBlurData { * spreads the shape making it wider, while small falloffs make it * narrower. */ - private _gaussian (out: Vec3, variance: number, r: number) { + private _gaussian (out: Vec3, variance: number, r: number): void { const xx = r / (0.001 + this._v3SSSSFallOff.x); out.x = Math.exp((-(xx * xx)) / (2.0 * variance)) / (2.0 * 3.14 * variance); const yy = r / (0.001 + this._v3SSSSFallOff.y); @@ -101,7 +101,7 @@ export class SSSSBlurData { * the profile. For example, it allows to create blue SSS gradients, which * could be useful in case of rendering blue creatures. */ - private _profile (out: Vec3, val: number) { + private _profile (out: Vec3, val: number): void { for (let i = 0; i < 5; i++) { this._gaussian(_vec3Temp2, _varianceArray[i], val); _vec3Temp2.multiplyScalar(_strengthParameterArray[i]); @@ -109,7 +109,7 @@ export class SSSSBlurData { } } - private _updateSampleCount () { + private _updateSampleCount (): void { const strength = this._v3SSSSStrength; const nSamples = I_SAMPLES_COUNT; const range = nSamples > 20 ? 3.0 : 2.0; @@ -172,7 +172,7 @@ export class SSSSBlurData { } } - private _init () { + private _init (): void { for (let i = 0; i < I_SAMPLES_COUNT; i++) { this._kernel[i] = new Vec4(); } @@ -193,7 +193,7 @@ export class SkinPass extends SettingPass { private _activate = false; enableInAllEditorCamera = true; - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { const ppl = (cclegacy.director.root as Root).pipeline; let enable = hasSkinObject(ppl); if (enable) { @@ -223,7 +223,7 @@ export class SkinPass extends SettingPass { private _buildSSSSBlurPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): void { const cameraID = getCameraUniqueID(camera); const pipelineSceneData = ppl.pipelineSceneData; @@ -299,7 +299,7 @@ export class SkinPass extends SettingPass { private _buildSpecularPass (camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string) { + inputDS: string): void { const cameraID = getCameraUniqueID(camera); const layoutName = 'specular-pass'; const passName = `specular-pass${cameraID}`; @@ -338,7 +338,7 @@ export class SkinPass extends SettingPass { | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING); } - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { return this.lastPass!.slotName(camera, index); } } diff --git a/cocos/rendering/post-process/passes/taa-pass.ts b/cocos/rendering/post-process/passes/taa-pass.ts index 0b9451fd663..77973ff6a4c 100644 --- a/cocos/rendering/post-process/passes/taa-pass.ts +++ b/cocos/rendering/post-process/passes/taa-pass.ts @@ -79,7 +79,7 @@ const SampleOffsets = { }; export class TAAPass extends SettingPass { - get setting () { return getSetting(TAA); } + get setting (): TAA { return getSetting(TAA); } name = 'TAAPass' effectName = 'pipeline/post-process/taa'; @@ -94,7 +94,7 @@ export class TAAPass extends SettingPass { forceRender = true; dirty = false; - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) { enable = false; @@ -105,7 +105,7 @@ export class TAAPass extends SettingPass { return enable; } - slotName (camera: Camera, index = 0) { + slotName (camera: Camera, index = 0): string { if (!this.checkEnable(camera)) { return this.lastPass!.slotName(camera, index); } @@ -117,7 +117,7 @@ export class TAAPass extends SettingPass { return super.slotName(camera, (this.taaTextureIndex + 1) % 2); } - applyCameraJitter (camera: Camera) { + applyCameraJitter (camera: Camera): void { (camera as any)._isProjDirty = true; camera.update(true); @@ -130,7 +130,7 @@ export class TAAPass extends SettingPass { camera.frustum.update(camera.matViewProj, camera.matViewProjInv); } - updateSample () { + updateSample (): void { if (this.dirty || this.forceRender) { this.sampleIndex++; this.taaTextureIndex++; diff --git a/cocos/rendering/post-process/passes/tone-mapping-pass.ts b/cocos/rendering/post-process/passes/tone-mapping-pass.ts index 47b02c07495..f512298e77f 100644 --- a/cocos/rendering/post-process/passes/tone-mapping-pass.ts +++ b/cocos/rendering/post-process/passes/tone-mapping-pass.ts @@ -39,7 +39,7 @@ export class ToneMappingPass extends SettingPass { enableInAllEditorCamera = true; enable = true; - checkEnable (camera: Camera) { + checkEnable (camera: Camera): boolean { const ppl = (cclegacy.director.root as Root).pipeline; return ppl.getMacroBool('CC_USE_FLOAT_OUTPUT'); } diff --git a/cocos/rendering/post-process/post-process-builder.ts b/cocos/rendering/post-process/post-process-builder.ts index a6eb69d3963..f90f3b97550 100644 --- a/cocos/rendering/post-process/post-process-builder.ts +++ b/cocos/rendering/post-process/post-process-builder.ts @@ -29,7 +29,7 @@ export class PostProcessBuilder implements PipelineBuilder { this.init(); } - init () { + init (): void { const forward = new ForwardPass(); const forwardFinal = new ForwardFinalPass(); @@ -64,46 +64,46 @@ export class PostProcessBuilder implements PipelineBuilder { this.addPass(forwardFinal); } - getPass (passClass: typeof BasePass, pipelineName = 'forward') { + getPass (passClass: typeof BasePass, pipelineName = 'forward'): BasePass | undefined { const pp = this.pipelines.get(pipelineName); - return pp && pp.find((p) => p instanceof passClass); + return pp && pp.find((p): boolean => p instanceof passClass); } - addPass (pass: BasePass, pipelineName = 'forward') { + addPass (pass: BasePass, pipelineName = 'forward'): void { let pp = this.pipelines.get(pipelineName); if (!pp) { pp = []; this.pipelines.set(pipelineName, pp); } - const oldIdx = pp.findIndex((p) => p.name === pass.name); + const oldIdx = pp.findIndex((p): boolean => p.name === pass.name); if (oldIdx !== -1) { pp.splice(oldIdx, 1); } pp.push(pass); } - insertPass (pass: BasePass, passClass: typeof BasePass, pipelineName = 'forward') { + insertPass (pass: BasePass, passClass: typeof BasePass, pipelineName = 'forward'): void { const pp = this.pipelines.get(pipelineName); if (pp) { - const oldIdx = pp.findIndex((p) => p.name === pass.name); + const oldIdx = pp.findIndex((p): boolean => p.name === pass.name); if (oldIdx !== -1) { pp.splice(oldIdx, 1); } - const idx = pp.findIndex((p) => p instanceof passClass); + const idx = pp.findIndex((p): boolean => p instanceof passClass); if (idx !== -1) { pp.splice(idx + 1, 0, pass); } } } - private initEditor () { - director.root!.cameraList.forEach((cam) => { + private initEditor (): void { + director.root!.cameraList.forEach((cam): void => { if (cam.name === 'Editor Camera') { cam.usePostProcess = cam.projectionType === CameraProjection.PERSPECTIVE; } }); } - private applyPreviewCamera (camera: Camera) { + private applyPreviewCamera (camera: Camera): void { if (!camera.node.parent) return; const camComp = camera.node.parent.getComponent(CameraComponent); const oriCamera = camComp && camComp.camera; @@ -113,7 +113,7 @@ export class PostProcessBuilder implements PipelineBuilder { } } - private resortEditorCameras (cameras: Camera[]) { + private resortEditorCameras (cameras: Camera[]): Camera[] { const newCameras: Camera[] = []; for (let i = 0; i < cameras.length; i++) { const c = cameras[i]; @@ -132,7 +132,7 @@ export class PostProcessBuilder implements PipelineBuilder { return newCameras; } - setup (cameras: Camera[], ppl: Pipeline) { + setup (cameras: Camera[], ppl: Pipeline): void { if (EDITOR) { this.initEditor(); cameras = this.resortEditorCameras(cameras); @@ -177,7 +177,7 @@ export class PostProcessBuilder implements PipelineBuilder { } } - getCameraPipelineName (camera: Camera) { + getCameraPipelineName (camera: Camera): string { let pipelineName = camera.pipeline; if (!pipelineName && camera.usePostProcess) { pipelineName = 'forward'; @@ -187,19 +187,19 @@ export class PostProcessBuilder implements PipelineBuilder { return pipelineName; } - getCameraPasses (camera: Camera) { + getCameraPasses (camera: Camera): BasePass[] { const pipelineName = this.getCameraPipelineName(camera); return this.pipelines.get(pipelineName) || []; } - renderCamera (camera: Camera, ppl: Pipeline) { + renderCamera (camera: Camera, ppl: Pipeline): void { passContext.passPathName = `${getCameraUniqueID(camera)}`; passContext.camera = camera; passContext.updateViewPort(); const passes = this.getCameraPasses(camera); - const taaPass = passes.find((p) => p instanceof TAAPass) as TAAPass; + const taaPass = passes.find((p): boolean => p instanceof TAAPass) as TAAPass; if (taaPass && taaPass.checkEnable(camera)) { taaPass.applyCameraJitter(camera); taaPass.updateSample(); diff --git a/cocos/rendering/post-process/utils/pass-context.ts b/cocos/rendering/post-process/utils/pass-context.ts index 51ca3199780..ded31937286 100644 --- a/cocos/rendering/post-process/utils/pass-context.ts +++ b/cocos/rendering/post-process/utils/pass-context.ts @@ -37,22 +37,22 @@ export class PassContext { forwardPass: any = undefined; postProcess: PostProcess | undefined; - setClearFlag (clearFlag: ClearFlagBit) { + setClearFlag (clearFlag: ClearFlagBit): PassContext { this.clearFlag = clearFlag; return this; } - setClearColor (x: number, y: number, z: number, w: number) { + setClearColor (x: number, y: number, z: number, w: number): PassContext { Vec4.set(this.clearColor, x, y, z, w); return this; } - setClearDepthColor (x: number, y: number, z: number, w: number) { + setClearDepthColor (x: number, y: number, z: number, w: number): PassContext { Vec4.set(this.clearDepthColor, x, y, z, w); return this; } - version () { + version (): PassContext { if (!EDITOR) { this.passPathName += `_${this.pass!.name}_${this.layoutName}`; this.pass!.setVersion(this.passPathName, this.passVersion); @@ -60,12 +60,12 @@ export class PassContext { return this; } - clearBlack () { + clearBlack (): void { this.clearFlag = ClearFlagBit.COLOR; Vec4.set(passContext.clearColor, 0, 0, 0, 1); } - addRenderPass (layoutName: string, passName: string) { + addRenderPass (layoutName: string, passName: string): PassContext { const passViewport = this.passViewport; const pass = this.ppl!.addRenderPass(passViewport.width, passViewport.height, layoutName); @@ -81,7 +81,7 @@ export class PassContext { return this; } - updateViewPort () { + updateViewPort (): void { const camera = this.camera; if (!camera) { return; @@ -97,7 +97,7 @@ export class PassContext { area.width = Math.floor(area.width); area.height = Math.floor(area.height); } - updatePassViewPort (shadingScale = 1, offsetScale = 0) { + updatePassViewPort (shadingScale = 1, offsetScale = 0): PassContext { this.passViewport.width = this.viewport.width * shadingScale; this.passViewport.height = this.viewport.height * shadingScale; @@ -111,7 +111,7 @@ export class PassContext { // return this; // } - addRasterView (name: string, format: Format, offscreen = true, residency?: ResourceResidency) { + addRasterView (name: string, format: Format, offscreen = true, residency?: ResourceResidency): PassContext { const ppl = this.ppl; const camera = this.camera; const pass = this.pass; @@ -162,7 +162,7 @@ export class PassContext { } return this; } - setPassInput (inputName: string, shaderName: string) { + setPassInput (inputName: string, shaderName: string): PassContext { if (this.ppl!.containsResource(inputName)) { const computeView = new ComputeView(); computeView.name = shaderName; @@ -171,7 +171,7 @@ export class PassContext { return this; } - blitScreen (passIdx = 0) { + blitScreen (passIdx = 0): PassContext { this.pass!.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( this.camera!, this.material!, passIdx, SceneFlags.NONE, diff --git a/cocos/rendering/reflection-probe/reflection-probe-flow.ts b/cocos/rendering/reflection-probe/reflection-probe-flow.ts index 2c8351cf45a..20611207a19 100644 --- a/cocos/rendering/reflection-probe/reflection-probe-flow.ts +++ b/cocos/rendering/reflection-probe/reflection-probe-flow.ts @@ -53,11 +53,11 @@ export class ReflectionProbeFlow extends RenderFlow { return true; } - public activate (pipeline: RenderPipeline) { + public activate (pipeline: RenderPipeline): void { super.activate(pipeline); } - public render (camera: Camera) { + public render (camera: Camera): void { if (!cclegacy.internal.reflectionProbeManager) { return; } @@ -71,10 +71,10 @@ export class ReflectionProbeFlow extends RenderFlow { } } - public destroy () { + public destroy (): void { super.destroy(); } - private _renderStage (camera: Camera, probe: ReflectionProbe) { + private _renderStage (camera: Camera, probe: ReflectionProbe): void { for (let i = 0; i < this._stages.length; i++) { const probeStage = this._stages[i] as ReflectionProbeStage; if (probe.probeType === ProbeType.PLANAR) { diff --git a/cocos/rendering/reflection-probe/reflection-probe-stage.ts b/cocos/rendering/reflection-probe/reflection-probe-stage.ts index bd7be75715b..beacaacb375 100644 --- a/cocos/rendering/reflection-probe/reflection-probe-stage.ts +++ b/cocos/rendering/reflection-probe/reflection-probe-stage.ts @@ -64,17 +64,17 @@ export class ReflectionProbeStage extends RenderStage { * @param probe * @param frameBuffer */ - public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer) { + public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer): void { this._probe = probe; this._frameBuffer = frameBuffer; } - public destroy () { + public destroy (): void { this._frameBuffer = null; this._probeRenderQueue?.clear(); } - public clearFramebuffer (camera: Camera) { + public clearFramebuffer (camera: Camera): void { if (!this._frameBuffer) { return; } colors[0].w = camera.clearColor.w; @@ -95,7 +95,7 @@ export class ReflectionProbeStage extends RenderStage { cmdBuff.endRenderPass(); } - public render (camera: Camera) { + public render (camera: Camera): void { const pipeline = this._pipeline; const cmdBuff = pipeline.commandBuffers[0]; this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff); @@ -129,7 +129,7 @@ export class ReflectionProbeStage extends RenderStage { pipeline.pipelineUBO.updateCameraUBO(camera); } - public activate (pipeline: ForwardPipeline, flow: ReflectionProbeFlow) { + public activate (pipeline: ForwardPipeline, flow: ReflectionProbeFlow): void { super.activate(pipeline, flow); this._probeRenderQueue = new RenderReflectionProbeQueue(pipeline); } diff --git a/cocos/rendering/render-additive-light-queue.ts b/cocos/rendering/render-additive-light-queue.ts index 777210b494d..94b8e02841e 100644 --- a/cocos/rendering/render-additive-light-queue.ts +++ b/cocos/rendering/render-additive-light-queue.ts @@ -63,20 +63,20 @@ const _matShadowViewProj = new Mat4(); const _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5); const _tmpBoundingBox = new AABB(); -function cullSphereLight (light: SphereLight, model: Model) { +function cullSphereLight (light: SphereLight, model: Model): boolean { return !!(model.worldBounds && !geometry.intersect.aabbWithAABB(model.worldBounds, light.aabb)); } -function cullSpotLight (light: SpotLight, model: Model) { +function cullSpotLight (light: SpotLight, model: Model): boolean { return !!(model.worldBounds && (!geometry.intersect.aabbWithAABB(model.worldBounds, light.aabb) || !geometry.intersect.aabbFrustum(model.worldBounds, light.frustum))); } -function cullPointLight (light: PointLight, model: Model) { +function cullPointLight (light: PointLight, model: Model): boolean { return !!(model.worldBounds && !geometry.intersect.aabbWithAABB(model.worldBounds, light.aabb)); } -function cullRangedDirLight (light: RangedDirectionalLight, model: Model) { +function cullRangedDirLight (light: RangedDirectionalLight, model: Model): boolean { AABB.transform(_tmpBoundingBox, _rangedDirLightBoundingBox, light.node!.getWorldMatrix()); return !!(model.worldBounds && (!geometry.intersect.aabbWithAABB(model.worldBounds, _tmpBoundingBox))); @@ -85,7 +85,7 @@ function cullRangedDirLight (light: RangedDirectionalLight, model: Model) { const phaseName = 'forward-add'; let _phaseID = getPhaseID(phaseName); const _lightPassIndices: number[] = []; -function getLightPassIndices (subModels: SubModel[], lightPassIndices: number[], passLayout = 'default') { +function getLightPassIndices (subModels: SubModel[], lightPassIndices: number[], passLayout = 'default'): boolean { const r = cclegacy.rendering; if (isEnableEffect()) { _phaseID = r.getPhaseID(r.getPassID(passLayout), phaseName); @@ -146,7 +146,7 @@ export class RenderAdditiveLightQueue { this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount); } - public clear () { + public clear (): void { this._instancedQueues.forEach((instancedQueue) => { instancedQueue.clear(); }); @@ -164,7 +164,7 @@ export class RenderAdditiveLightQueue { this._instancedLightPassPool.lights.length = 0; } - public destroy () { + public destroy (): void { const descriptorSetMap = this._pipeline.globalDSManager.descriptorSetMap; const keys = descriptorSetMap.keys; @@ -182,7 +182,7 @@ export class RenderAdditiveLightQueue { } } - private _bindForwardAddLight (validPunctualLights, passLayout = 'default') { + private _bindForwardAddLight (validPunctualLights, passLayout = 'default'): void { const renderObjects = this._pipeline.pipelineSceneData.renderObjects; for (let i = 0; i < renderObjects.length; i++) { const ro = renderObjects[i]; @@ -215,7 +215,7 @@ export class RenderAdditiveLightQueue { } } - public gatherLightPasses (camera: Camera, cmdBuff: CommandBuffer, passLayout = 'default') { + public gatherLightPasses (camera: Camera, cmdBuff: CommandBuffer, passLayout = 'default'): void { this.clear(); const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights; @@ -239,7 +239,7 @@ export class RenderAdditiveLightQueue { }); } - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { + public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void { const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager; for (let j = 0; j < this._instancedQueues.length; ++j) { const light = this._instancedLightPassPool.lights[j]; @@ -273,7 +273,7 @@ export class RenderAdditiveLightQueue { } // light culling - protected _lightCulling (model: Model, validPunctualLights: Light[]) { + protected _lightCulling (model: Model, validPunctualLights: Light[]): void { let isCulled = false; for (let l = 0; l < validPunctualLights.length; l++) { const light = validPunctualLights[l]; @@ -299,7 +299,7 @@ export class RenderAdditiveLightQueue { } // add renderQueue - protected _addRenderQueue (pass: Pass, subModel: SubModel, model: Model, lightPassIdx: number) { + protected _addRenderQueue (pass: Pass, subModel: SubModel, model: Model, lightPassIdx: number): void { const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights; const { batchingScheme } = pass; @@ -336,7 +336,7 @@ export class RenderAdditiveLightQueue { } // update light DescriptorSet - protected _updateLightDescriptorSet (camera: Camera, cmdBuff: CommandBuffer) { + protected _updateLightDescriptorSet (camera: Camera, cmdBuff: CommandBuffer): void { const device = this._pipeline.device; const sceneData = this._pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; @@ -466,7 +466,7 @@ export class RenderAdditiveLightQueue { } } - protected _updateUBOs (camera: Camera, cmdBuff: CommandBuffer) { + protected _updateUBOs (camera: Camera, cmdBuff: CommandBuffer): void { const { exposure } = camera; const sceneData = this._pipeline.pipelineSceneData; const isHDR = sceneData.isHDR; diff --git a/cocos/rendering/render-flow.ts b/cocos/rendering/render-flow.ts index 84b50048155..7b27ed47472 100644 --- a/cocos/rendering/render-flow.ts +++ b/cocos/rendering/render-flow.ts @@ -122,7 +122,7 @@ export abstract class RenderFlow { * @zh 为指定的渲染管线开启当前渲染流程 * @param pipeline The render pipeline to activate this render flow */ - public activate (pipeline: RenderPipeline) { + public activate (pipeline: RenderPipeline): void { this._pipeline = pipeline; this._stages.sort((a, b) => a.priority - b.priority); @@ -136,7 +136,7 @@ export abstract class RenderFlow { * @zh 渲染函数,对指定的渲染视图按顺序执行所有渲染阶段。 * @param view Render view。 */ - public render (camera: Camera) { + public render (camera: Camera): void { for (let i = 0, len = this._stages.length; i < len; i++) { if (this._stages[i].enabled) this._stages[i].render(camera); } @@ -146,7 +146,7 @@ export abstract class RenderFlow { * @en Destroy function. * @zh 销毁函数。 */ - public destroy () { + public destroy (): void { for (let i = 0, len = this._stages.length; i < len; i++) { this._stages[i].destroy(); } diff --git a/cocos/rendering/render-instanced-queue.ts b/cocos/rendering/render-instanced-queue.ts index 036fb0e52de..c97467799c9 100644 --- a/cocos/rendering/render-instanced-queue.ts +++ b/cocos/rendering/render-instanced-queue.ts @@ -44,7 +44,7 @@ export class RenderInstancedQueue { * @en Clear the render queue * @zh 清空渲染队列。 */ - public clear () { + public clear (): void { const it = this.queue.values(); let res = it.next(); while (!res.done) { res.value.clear(); @@ -54,7 +54,7 @@ export class RenderInstancedQueue { this.queue.clear(); } - public sort () { + public sort (): void { let it = this.queue.values(); let res = it.next(); while (!res.done) { @@ -73,7 +73,7 @@ export class RenderInstancedQueue { } } - public uploadBuffers (cmdBuff: CommandBuffer) { + public uploadBuffers (cmdBuff: CommandBuffer): void { const it = this.queue.values(); let res = it.next(); while (!res.done) { if (res.value.hasPendingModels) res.value.uploadBuffers(cmdBuff); @@ -87,7 +87,7 @@ export class RenderInstancedQueue { * @param cmdBuff The command buffer to store the result */ public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer, - descriptorSet: DescriptorSet | null = null, dynamicOffsets?: Readonly) { + descriptorSet: DescriptorSet | null = null, dynamicOffsets?: Readonly): void { const it = this._renderQueue.length === 0 ? this.queue.values() : this._renderQueue[Symbol.iterator](); let res = it.next(); diff --git a/cocos/rendering/render-pipeline.ts b/cocos/rendering/render-pipeline.ts index 76e721d174d..bae3fbf16f6 100644 --- a/cocos/rendering/render-pipeline.ts +++ b/cocos/rendering/render-pipeline.ts @@ -29,7 +29,7 @@ import { Asset } from '../asset/assets/asset'; import { AccessFlagBit, Attribute, Buffer, BufferInfo, BufferUsageBit, ClearFlagBit, ClearFlags, ColorAttachment, CommandBuffer, DepthStencilAttachment, DescriptorSet, Device, Feature, Format, FormatFeatureBit, Framebuffer, FramebufferInfo, InputAssembler, InputAssemblerInfo, LoadOp, MemoryUsageBit, Rect, RenderPass, RenderPassInfo, Sampler, StoreOp, SurfaceTransform, Swapchain, - Texture, TextureInfo, TextureType, TextureUsageBit, Viewport, GeneralBarrierInfo, deviceManager, + Texture, TextureInfo, TextureType, TextureUsageBit, Viewport, GeneralBarrierInfo, deviceManager, DescriptorSetLayout, } from '../gfx'; import { MacroRecord } from '../render-scene/core/pass-utils'; import { RenderWindow } from '../render-scene/core/render-window'; @@ -92,7 +92,7 @@ export class PipelineInputAssemblerData { quadIA: InputAssembler|null = null; } -function hashFrameBuffer (fbo: Framebuffer) { +function hashFrameBuffer (fbo: Framebuffer): number { let hash = 666; for (const color of fbo.colorTextures) { const info = color?.info; @@ -188,7 +188,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * @zh 常量宏定义字符串,运行时全程不会改变,用于给 shader 传一些只和平台相关的参数。 * @readonly */ - get constantMacros () { + get constantMacros (): string { return this._constantMacros; } @@ -199,35 +199,35 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * @zh 当前的全局宏定义,用于控制如 IBL、雾效等模块。 * @readonly */ - get macros () { + get macros (): MacroRecord { return this._macros; } - get device () { + get device (): Device { return this._device; } - get globalDSManager () { + get globalDSManager (): GlobalDSManager { return this._globalDSManager; } - get descriptorSetLayout () { + get descriptorSetLayout (): DescriptorSetLayout { return this._globalDSManager.descriptorSetLayout; } - get descriptorSet () { + get descriptorSet (): DescriptorSet { return this._descriptorSet; } - get commandBuffers () { + get commandBuffers (): CommandBuffer[] { return this._commandBuffers; } - get pipelineUBO () { + get pipelineUBO (): PipelineUBO { return this._pipelineUBO; } - get pipelineSceneData () { + get pipelineSceneData (): PipelineSceneData { return this._pipelineSceneData; } @@ -235,14 +235,14 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi this._profiler = value; } - get profiler () { + get profiler (): Model | null { return this._profiler; } /** * @deprecated since v3.6, please use camera.geometryRenderer instead. */ - get geometryRenderer () { + get geometryRenderer (): GeometryRenderer | null { return this._geometryRenderer; } @@ -250,7 +250,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi this._clusterEnabled = value; } - get clusterEnabled () { + get clusterEnabled (): boolean { return this._clusterEnabled; } @@ -258,7 +258,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi this._bloomEnabled = value; } - get bloomEnabled () { + get bloomEnabled (): boolean { return this._bloomEnabled; } @@ -336,7 +336,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi return renderPass; } - public newFramebufferByRatio (dyingFramebuffer: Framebuffer) { + public newFramebufferByRatio (dyingFramebuffer: Framebuffer): Framebuffer { const sceneData = this.pipelineSceneData; const width = this._width * sceneData.shadingScale; const height = this._height * sceneData.shadingScale; @@ -363,7 +363,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * @param camera the camera * @returns */ - public generateRenderArea (camera: Camera, out: Rect) { + public generateRenderArea (camera: Camera, out: Rect): void { const vp = camera.viewport; const w = camera.window.width; const h = camera.window.height; @@ -395,7 +395,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi return out; } - public get shadingScale () { + public get shadingScale (): number { return this._pipelineSceneData.shadingScale; } @@ -467,14 +467,14 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi return true; } - protected _ensureEnoughSize (cameras: Camera[]) {} + protected _ensureEnoughSize (cameras: Camera[]): void {} /** * @en Render function, it basically run the render process of all flows in sequence for the given view. * @zh 渲染函数,对指定的渲染视图按顺序执行所有渲染流程。 * @param view Render view。 */ - public render (cameras: Camera[]) { + public render (cameras: Camera[]): void { if (cameras.length === 0) { return; } @@ -507,7 +507,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * @zh * 销毁四边形输入汇集器。 */ - protected _destroyQuadInputAssembler () { + protected _destroyQuadInputAssembler (): void { if (this._quadIB) { this._quadIB.destroy(); this._quadIB = null; @@ -534,7 +534,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi } } - protected _destroyBloomData () { + protected _destroyBloomData (): void { const bloom = this._pipelineRenderData!.bloom; if (bloom === null) return; @@ -673,7 +673,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi return inputAssemblerData; } - public updateQuadVertexData (renderArea: Rect, window: RenderWindow) { + public updateQuadVertexData (renderArea: Rect, window: RenderWindow): void { const cachedArea = this._lastUsedRenderArea; if (cachedArea.x === renderArea.x && cachedArea.y === renderArea.y @@ -716,11 +716,11 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi return super.destroy(); } - public onGlobalPipelineStateChanged () { + public onGlobalPipelineStateChanged (): void { // do nothing } - protected _generateConstantMacros () { + protected _generateConstantMacros (): void { let str = ''; str += `#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE ${this.device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) ? 1 : 0}\n`; @@ -737,7 +737,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi this._constantMacros = str; } - protected updateGeometryRenderer (cameras: Camera[]) { + protected updateGeometryRenderer (cameras: Camera[]): void { if (this._geometryRenderer) { return; } @@ -753,7 +753,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi } } - public generateBloomRenderData () { + public generateBloomRenderData (): void { if (this._pipelineRenderData!.bloom != null) return; const bloom = this._pipelineRenderData!.bloom = new BloomRenderData(); @@ -863,7 +863,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * @zh * 删除之前用同类型、回调、目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 */ - public off (type: PipelineEventType, callback?: any, target?: any) { + public off (type: PipelineEventType, callback?: any, target?: any): void { this._eventProcessor.off(type, callback, target); } @@ -873,7 +873,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * @param type - event type * @param args - Arguments when the event triggered */ - public emit (type: PipelineEventType, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) { + public emit (type: PipelineEventType, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void { this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4); } @@ -887,7 +887,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 * @param typeOrTarget - The target to be searched for all related listeners */ - public targetOff (typeOrTarget: any) { + public targetOff (typeOrTarget: any): void { this._eventProcessor.targetOff(typeOrTarget); } @@ -896,7 +896,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target * @param typeOrTarget - The event type or target with which the listeners will be removed */ - public removeAll (typeOrTarget: any) { + public removeAll (typeOrTarget: any): void { this._eventProcessor.removeAll(typeOrTarget); } diff --git a/cocos/rendering/render-queue.ts b/cocos/rendering/render-queue.ts index 41002f03b5f..16b214657de 100644 --- a/cocos/rendering/render-queue.ts +++ b/cocos/rendering/render-queue.ts @@ -33,7 +33,7 @@ import { getPhaseID } from './pass-phase'; * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 */ -export function opaqueCompareFn (a: IRenderPass, b: IRenderPass) { +export function opaqueCompareFn (a: IRenderPass, b: IRenderPass): number { return (a.hash - b.hash) || (a.depth - b.depth) || (a.shaderId - b.shaderId); } @@ -41,7 +41,7 @@ export function opaqueCompareFn (a: IRenderPass, b: IRenderPass) { * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 */ -export function transparentCompareFn (a: IRenderPass, b: IRenderPass) { +export function transparentCompareFn (a: IRenderPass, b: IRenderPass): number { return (a.priority - b.priority) || (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); } @@ -66,7 +66,7 @@ export class RenderQueue { */ constructor (desc: IRenderQueueDesc) { this._passDesc = desc; - this._passPool = new RecyclePool(() => ({ + this._passPool = new RecyclePool((): { priority: number; hash: number; depth: number; shaderId: number; subModel: any; passIdx: number; } => ({ priority: 0, hash: 0, depth: 0, @@ -81,7 +81,7 @@ export class RenderQueue { * @en Clear the render queue * @zh 清空渲染队列。 */ - public clear () { + public clear (): void { this.queue.clear(); this._passPool.reset(); } @@ -118,11 +118,11 @@ export class RenderQueue { * @en Sort the current queue * @zh 排序渲染队列。 */ - public sort () { + public sort (): void { this.queue.sort(); } - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { + public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void { for (let i = 0; i < this.queue.length; ++i) { const { subModel, passIdx } = this.queue.array[i]; const { inputAssembler } = subModel; @@ -138,7 +138,7 @@ export class RenderQueue { } } -export function convertRenderQueue (desc: RenderQueueDesc) { +export function convertRenderQueue (desc: RenderQueueDesc): RenderQueue { let phase = 0; for (let j = 0; j < desc.stages.length; j++) { phase |= getPhaseID(desc.stages[j]); @@ -167,7 +167,7 @@ export function convertRenderQueue (desc: RenderQueueDesc) { * @zh 清空指定的渲染队列 * @param rq The render queue */ -export function renderQueueClearFunc (rq: RenderQueue) { +export function renderQueueClearFunc (rq: RenderQueue): void { rq.clear(); } @@ -176,6 +176,6 @@ export function renderQueueClearFunc (rq: RenderQueue) { * @zh 对指定的渲染队列执行排序 * @param rq The render queue */ -export function renderQueueSortFunc (rq: RenderQueue) { +export function renderQueueSortFunc (rq: RenderQueue): void { rq.sort(); } diff --git a/cocos/rendering/render-reflection-probe-queue.ts b/cocos/rendering/render-reflection-probe-queue.ts index 67ef5eb8b31..725b4a4ec6f 100644 --- a/cocos/rendering/render-reflection-probe-queue.ts +++ b/cocos/rendering/render-reflection-probe-queue.ts @@ -85,7 +85,7 @@ export class RenderReflectionProbeQueue { this._pipeline = pipeline; this._instancedQueue = new RenderInstancedQueue(); } - public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer) { + public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer): void { this.clear(); const scene = camera.scene!; const sceneData = this._pipeline.pipelineSceneData; @@ -121,7 +121,7 @@ export class RenderReflectionProbeQueue { this._instancedQueue.uploadBuffers(cmdBuff); } - public clear () { + public clear (): void { this._subModelsArray.length = 0; this._shaderArray.length = 0; this._passArray.length = 0; @@ -129,7 +129,7 @@ export class RenderReflectionProbeQueue { this._rgbeSubModelsArray.length = 0; } - public add (model: Model) { + public add (model: Model): void { const subModels = model.subModels; for (let j = 0; j < subModels.length; j++) { const subModel = subModels[j]; @@ -179,7 +179,7 @@ export class RenderReflectionProbeQueue { * @zh * record CommandBuffer */ - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { + public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void { this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff); for (let i = 0; i < this._subModelsArray.length; ++i) { @@ -199,7 +199,7 @@ export class RenderReflectionProbeQueue { this.resetRGBEMacro(); this._instancedQueue.clear(); } - public resetRGBEMacro () { + public resetRGBEMacro (): void { for (let i = 0; i < this._rgbeSubModelsArray.length; i++) { this._patches = []; const subModel = this._rgbeSubModelsArray[i]; diff --git a/cocos/rendering/render-shadow-map-batched-queue.ts b/cocos/rendering/render-shadow-map-batched-queue.ts index 79dddbfaf70..1c1cb3b2cad 100644 --- a/cocos/rendering/render-shadow-map-batched-queue.ts +++ b/cocos/rendering/render-shadow-map-batched-queue.ts @@ -67,7 +67,7 @@ export class RenderShadowMapBatchedQueue { this._instancedQueue = new RenderInstancedQueue(); } - public gatherLightPasses (camera: Camera, light: Light, cmdBuff: CommandBuffer, level = 0) { + public gatherLightPasses (camera: Camera, light: Light, cmdBuff: CommandBuffer, level = 0): void { this.clear(); const sceneData = this._pipeline.pipelineSceneData; @@ -124,14 +124,14 @@ export class RenderShadowMapBatchedQueue { * @zh * clear light-Batched-Queue */ - public clear () { + public clear (): void { this._subModelsArray.length = 0; this._shaderArray.length = 0; this._passArray.length = 0; this._instancedQueue.clear(); } - public add (model: Model) { + public add (model: Model): void { const subModels = model.subModels; for (let j = 0; j < subModels.length; j++) { const subModel = subModels[j]; @@ -157,7 +157,7 @@ export class RenderShadowMapBatchedQueue { * @zh * record CommandBuffer */ - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { + public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void { this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff); for (let i = 0; i < this._subModelsArray.length; ++i) { diff --git a/cocos/rendering/render-stage.ts b/cocos/rendering/render-stage.ts index 843afb27806..46003ce956c 100644 --- a/cocos/rendering/render-stage.ts +++ b/cocos/rendering/render-stage.ts @@ -97,7 +97,7 @@ export abstract class RenderStage { public set enabled (val: boolean) { this._enabled = val; } - public get enabled () { + public get enabled (): boolean { return this._enabled; } @@ -128,7 +128,7 @@ export abstract class RenderStage { * @zh 为指定的渲染流程开启当前渲染阶段 * @param flow The render flow to activate this render stage */ - public activate (pipeline: RenderPipeline, flow: RenderFlow) { + public activate (pipeline: RenderPipeline, flow: RenderFlow): void { this._pipeline = pipeline; this._flow = flow; } @@ -137,14 +137,14 @@ export abstract class RenderStage { * @en Destroy function * @zh 销毁函数。 */ - public abstract destroy (); + public abstract destroy (): void; /** * @en Render function * @zh 渲染函数。 * @param view The render view */ - public abstract render (camera: Camera); + public abstract render (camera: Camera): void; } cclegacy.RenderStage = RenderStage; diff --git a/cocos/rendering/scene-culling.ts b/cocos/rendering/scene-culling.ts index 968f90a5bd1..419a0bda854 100644 --- a/cocos/rendering/scene-culling.ts +++ b/cocos/rendering/scene-culling.ts @@ -37,9 +37,9 @@ const _sphere = geometry.Sphere.create(0, 0, 0, 1); const _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5); const _tmpBoundingBox = new AABB(); -const roPool = new Pool(() => ({ model: null!, depth: 0 }), 128); +const roPool = new Pool((): IRenderObject => ({ model: null!, depth: 0 }), 128); -function getRenderObject (model: Model, camera: Camera) { +function getRenderObject (model: Model, camera: Camera): IRenderObject { let depth = 0; if (model.node) { Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position); @@ -51,7 +51,7 @@ function getRenderObject (model: Model, camera: Camera) { return ro; } -export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Camera) { +export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Camera): void { const sceneData = pipeline.pipelineSceneData; const validPunctualLights = sceneData.validPunctualLights; validPunctualLights.length = 0; @@ -105,7 +105,7 @@ export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Ca sceneData.validPunctualLights = validPunctualLights; } -export function shadowCulling (camera: Camera, sceneData: PipelineSceneData, layer: ShadowLayerVolume) { +export function shadowCulling (camera: Camera, sceneData: PipelineSceneData, layer: ShadowLayerVolume): void { const scene = camera.scene!; const mainLight = scene.mainLight!; const csmLayers = sceneData.csmLayers; @@ -148,7 +148,7 @@ export function shadowCulling (camera: Camera, sceneData: PipelineSceneData, lay } } -export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { +export function sceneCulling (pipeline: RenderPipeline, camera: Camera): void { const scene = camera.scene!; const mainLight = scene.mainLight; const sceneData = pipeline.pipelineSceneData; @@ -185,7 +185,7 @@ export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { const models = scene.models; const visibility = camera.visibility; - function enqueueRenderObject (model: Model) { + function enqueueRenderObject (model: Model): void { // filter model by view visibility if (model.enabled) { if (scene.isCulledByLod(camera, model)) { diff --git a/cocos/rendering/shadow/csm-layers.ts b/cocos/rendering/shadow/csm-layers.ts index 5294aaa0aed..fcf74e54312 100644 --- a/cocos/rendering/shadow/csm-layers.ts +++ b/cocos/rendering/shadow/csm-layers.ts @@ -72,34 +72,34 @@ export class ShadowLayerVolume { this._lightViewFrustum.accurate = true; } - get level () { return this._level; } + get level (): number { return this._level; } - get shadowObjects () { + get shadowObjects (): IRenderObject[] { return this._shadowObjects; } - get shadowCameraFar () { + get shadowCameraFar (): number { return this._shadowCameraFar; } set shadowCameraFar (val) { this._shadowCameraFar = val; } - get matShadowView () { + get matShadowView (): Mat4 { return this._matShadowView; } set matShadowView (val) { this._matShadowView = val; } - get matShadowProj () { + get matShadowProj (): Mat4 { return this._matShadowProj; } set matShadowProj (val) { this._matShadowProj = val; } - get matShadowViewProj () { + get matShadowViewProj (): Mat4 { return this._matShadowViewProj; } set matShadowViewProj (val) { @@ -122,23 +122,23 @@ export class ShadowLayerVolume { return this._castLightViewBoundingBox; } - public copyToValidFrustum (validFrustum: Readonly) { + public copyToValidFrustum (validFrustum: Readonly): void { Frustum.copy(this._validFrustum, validFrustum); } - public calculateValidFrustumOrtho (width: number, height: number, near: number, far: number, transform: Mat4) { + public calculateValidFrustumOrtho (width: number, height: number, near: number, far: number, transform: Mat4): void { Frustum.createOrtho(this._validFrustum, width, height, near, far, transform); } - public calculateSplitFrustum (camera: Camera, m: Mat4, start: number, end: number) { + public calculateSplitFrustum (camera: Camera, m: Mat4, start: number, end: number): void { this._splitFrustum.split(start, end, camera.aspect, camera.fov, m); } - public destroy () { + public destroy (): void { this._shadowObjects.length = 0; } - public createMatrix (dirLight: DirectionalLight, shadowMapWidth: number, onlyForCulling: boolean) { + public createMatrix (dirLight: DirectionalLight, shadowMapWidth: number, onlyForCulling: boolean): void { const device = cclegacy.director.root.device; const invisibleOcclusionRange = dirLight.shadowInvisibleOcclusionRange; Frustum.copy(this._lightViewFrustum, this._splitFrustum); @@ -224,32 +224,32 @@ export class CSMShadowLayer extends ShadowLayerVolume { this._calculateAtlas(level); } - get splitCameraNear () { + get splitCameraNear (): number { return this._splitCameraNear; } set splitCameraNear (val) { this._splitCameraNear = val; } - get splitCameraFar () { + get splitCameraFar (): number { return this._splitCameraFar; } set splitCameraFar (val) { this._splitCameraFar = val; } - get csmAtlas () { + get csmAtlas (): Vec4 { return this._csmAtlas; } set csmAtlas (val) { this._csmAtlas = val; } - public destroy () { + public destroy (): void { super.destroy(); } - private _calculateAtlas (level: number) { + private _calculateAtlas (level: number): void { const clipSpaceSignY = cclegacy.director.root.device.capabilities.clipSpaceSignY; const x = level % 2 - 0.5; const y = (0.5 - Math.floor(level / 2)) * clipSpaceSignY; @@ -272,19 +272,19 @@ export class CSMLayers { protected _specialLayer: ShadowLayerVolume = new ShadowLayerVolume(1); protected _shadowDistance = 0; - get castShadowObjects () { + get castShadowObjects (): IRenderObject[] { return this._castShadowObjects; } - get layerObjects () { + get layerObjects (): CachedArray { return this._layerObjects; } - get layers () { + get layers (): CSMShadowLayer[] { return this._layers; } - get specialLayer () { + get specialLayer (): ShadowLayerVolume { return this._specialLayer; } @@ -294,7 +294,7 @@ export class CSMLayers { } } - public update (sceneData: PipelineSceneData, camera: Camera) { + public update (sceneData: PipelineSceneData, camera: Camera): void { const scene = camera.scene!; const dirLight = scene.mainLight; if (dirLight === null) { return; } @@ -319,7 +319,7 @@ export class CSMLayers { } } - public destroy () { + public destroy (): void { this._castShadowObjects.length = 0; for (let i = 0; i < this._layers.length; i++) { this._layers[i].destroy(); @@ -327,7 +327,7 @@ export class CSMLayers { this._layers.length = 0; } - private _updateFixedArea (dirLight: DirectionalLight) { + private _updateFixedArea (dirLight: DirectionalLight): void { const device = cclegacy.director.root.device; const x = dirLight.shadowOrthoSize; const y = dirLight.shadowOrthoSize; @@ -345,7 +345,7 @@ export class CSMLayers { this._specialLayer.calculateValidFrustumOrtho(x * 2.0, y * 2.0, near, far, _matShadowTrans); } - private _splitFrustumLevels (dirLight: DirectionalLight) { + private _splitFrustumLevels (dirLight: DirectionalLight): void { const nd = 0.1; const fd = dirLight.shadowDistance; const ratio = fd / nd; @@ -368,7 +368,7 @@ export class CSMLayers { dirLight.csmNeedUpdate = false; } - private _calculateCSM (camera: Camera, dirLight: DirectionalLight, shadowInfo: Shadows) { + private _calculateCSM (camera: Camera, dirLight: DirectionalLight, shadowInfo: Shadows): void { const level = cclegacy.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; const shadowMapWidth = level > 1 ? shadowInfo.size.x * 0.5 : shadowInfo.size.x; @@ -395,7 +395,7 @@ export class CSMLayers { } } - private _getCameraWorldMatrix (out: Mat4, camera: Camera) { + private _getCameraWorldMatrix (out: Mat4, camera: Camera): void { if (!camera.node) { return; } const cameraNode = camera.node; diff --git a/cocos/rendering/shadow/shadow-flow.ts b/cocos/rendering/shadow/shadow-flow.ts index 8347ce105f7..daf017cf376 100644 --- a/cocos/rendering/shadow/shadow-flow.ts +++ b/cocos/rendering/shadow/shadow-flow.ts @@ -71,7 +71,7 @@ export class ShadowFlow extends RenderFlow { return true; } - public activate (pipeline: RenderPipeline) { + public activate (pipeline: RenderPipeline): void { super.activate(pipeline); // 0: SHADOWMAP_FLOAT, 1: SHADOWMAP_RGBE. @@ -102,7 +102,7 @@ export class ShadowFlow extends RenderFlow { pipeline.onGlobalPipelineStateChanged(); } - public render (camera: Camera) { + public render (camera: Camera): void { const pipeline = this._pipeline as ForwardPipeline; const shadowInfo = pipeline.pipelineSceneData.shadows; const csmLayers = pipeline.pipelineSceneData.csmLayers; @@ -165,7 +165,7 @@ export class ShadowFlow extends RenderFlow { _validLights.length = 0; } - public destroy () { + public destroy (): void { super.destroy(); if (this._pipeline) { const shadowFrameBufferMap = this._pipeline.pipelineSceneData.shadowFrameBufferMap; @@ -196,7 +196,7 @@ export class ShadowFlow extends RenderFlow { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _initShadowFrameBuffer (pipeline: RenderPipeline, light: Light, swapchain: Swapchain) { + public _initShadowFrameBuffer (pipeline: RenderPipeline, light: Light, swapchain: Swapchain): void { const { device } = pipeline; const shadows = pipeline.pipelineSceneData.shadows; const shadowMapSize = shadows.size; @@ -249,7 +249,7 @@ export class ShadowFlow extends RenderFlow { shadowFrameBufferMap.set(light, shadowFrameBuffer); } - private _renderStage (camera: Camera, light: Light, shadowFrameBuffer: Framebuffer, globalDS: DescriptorSet, level = 0) { + private _renderStage (camera: Camera, light: Light, shadowFrameBuffer: Framebuffer, globalDS: DescriptorSet, level = 0): void { for (let i = 0; i < this._stages.length; i++) { const shadowStage = this._stages[i] as ShadowStage; shadowStage.setUsage(globalDS, light, shadowFrameBuffer, level); @@ -257,7 +257,7 @@ export class ShadowFlow extends RenderFlow { } } - private clearShadowMap (validLights: Light[], camera: Camera) { + private clearShadowMap (validLights: Light[], camera: Camera): void { const pipeline = this._pipeline; const scene = pipeline.pipelineSceneData; @@ -292,7 +292,7 @@ export class ShadowFlow extends RenderFlow { } } - private resizeShadowMap () { + private resizeShadowMap (): void { const shadows = this._pipeline.pipelineSceneData.shadows; const shadowMapSize = shadows.size; const pipeline = this._pipeline; diff --git a/cocos/rendering/shadow/shadow-stage.ts b/cocos/rendering/shadow/shadow-stage.ts index 4f8d8b38bfd..edae01d16ac 100644 --- a/cocos/rendering/shadow/shadow-stage.ts +++ b/cocos/rendering/shadow/shadow-stage.ts @@ -58,7 +58,7 @@ export class ShadowStage extends RenderStage { * @param shadowFrameBuffer * @param level 层级 */ - public setUsage (globalDS: DescriptorSet, light: Light, shadowFrameBuffer: Framebuffer, level = 0) { + public setUsage (globalDS: DescriptorSet, light: Light, shadowFrameBuffer: Framebuffer, level = 0): void { this._globalDS = globalDS; this._light = light; this._shadowFrameBuffer = shadowFrameBuffer; @@ -73,7 +73,7 @@ export class ShadowStage extends RenderStage { private _level = 0; private _isShadowMapCleared = false; - public destroy () { + public destroy (): void { this._shadowFrameBuffer = null; this._globalDS = null; this._light = null; @@ -81,7 +81,7 @@ export class ShadowStage extends RenderStage { this._additiveShadowQueue?.clear(); } - public clearFramebuffer (camera: Camera) { + public clearFramebuffer (camera: Camera): void { if (!this._light || !this._shadowFrameBuffer || this._isShadowMapCleared) { return; } colors[0].w = camera.clearColor.w; @@ -104,7 +104,7 @@ export class ShadowStage extends RenderStage { this._isShadowMapCleared = true; } - public render (camera: Camera) { + public render (camera: Camera): void { const pipeline = this._pipeline; const pipelineSceneData = pipeline.pipelineSceneData; const shadowInfo = pipelineSceneData.shadows; @@ -161,7 +161,7 @@ export class ShadowStage extends RenderStage { this._isShadowMapCleared = false; } - public activate (pipeline: ForwardPipeline, flow: ShadowFlow) { + public activate (pipeline: ForwardPipeline, flow: ShadowFlow): void { super.activate(pipeline, flow); this._additiveShadowQueue = new RenderShadowMapBatchedQueue(pipeline); this._isShadowMapCleared = false; diff --git a/cocos/rendering/ui-phase.ts b/cocos/rendering/ui-phase.ts index 50a827ecdf7..43e223a5f61 100644 --- a/cocos/rendering/ui-phase.ts +++ b/cocos/rendering/ui-phase.ts @@ -38,11 +38,11 @@ export class UIPhase { if (isEnableEffect()) this._phaseID = r.getPhaseID(r.getPassID('default'), 'default'); } - public activate (pipeline: RenderPipeline) { + public activate (pipeline: RenderPipeline): void { this._pipeline = pipeline; } - public render (camera: Camera, renderPass: RenderPass) { + public render (camera: Camera, renderPass: RenderPass): void { const pipeline = this._pipeline; const device = pipeline.device; const cmdBuff = pipeline.commandBuffers[0]; diff --git a/cocos/root.ts b/cocos/root.ts index c8440c3d080..faedf50ceac 100644 --- a/cocos/root.ts +++ b/cocos/root.ts @@ -220,7 +220,7 @@ export class Root { /** * @internal */ - public get dataPoolManager () { + public get dataPoolManager (): DataPoolManager { return this._dataPoolMgr; } @@ -285,7 +285,7 @@ export class Root { RenderScene.registerCreateFunc(this); RenderWindow.registerCreateFunc(this); - this._cameraPool = new Pool(() => new Camera(this._device), 4, (cam) => cam.destroy()); + this._cameraPool = new Pool((): Camera => new Camera(this._device), 4, (cam): void => cam.destroy()); } /** @@ -293,7 +293,7 @@ export class Root { * @zh 初始化函数,用户不应该自己初始化 Root,它是由 [[Director]] 管理的。 * @param info Root initialization information */ - public initialize (info: IRootInfo) { + public initialize (info: IRootInfo): void { const swapchain: Swapchain = deviceManager.swapchain; const colorAttachment = new ColorAttachment(); colorAttachment.format = swapchain.colorTexture.format; @@ -320,7 +320,7 @@ export class Root { * @en Destroy the root, user shouldn't invoke this function, it will cause undefined behavior. * @zh 销毁 Root,用户不应该调用此方法,会造成未知行为。 */ - public destroy () { + public destroy (): void { this.destroyScenes(); if (this._pipeline) { @@ -350,7 +350,7 @@ export class Root { * @param height The new height of the window. * @param windowId The system window ID, optional for now. */ - public resize (width: number, height: number, windowId?: number) { + public resize (width: number, height: number, windowId?: number): void { for (const window of this._windows) { if (window.swapchain) { window.resize(width, height); @@ -440,7 +440,7 @@ export class Root { * @en Notify the pipeline and all scenes that the global pipeline state have been updated so that they can update their render data and states. * @zh 通知渲染管线和所有场景全局管线状态已更新,需要更新自身状态。 */ - public onGlobalPipelineStateChanged () { + public onGlobalPipelineStateChanged (): void { for (let i = 0; i < this._scenes.length; i++) { this._scenes[i].onGlobalPipelineStateChanged(); } @@ -453,7 +453,7 @@ export class Root { * @zh 激活指定窗口为当前窗口 [[curWindow]] * @param window The render window to be activated */ - public activeWindow (window: RenderWindow) { + public activeWindow (window: RenderWindow): void { this._curWindow = window; } @@ -461,7 +461,7 @@ export class Root { * @en Reset the time cumulated * @zh 重置累计时间 */ - public resetCumulativeTime () { + public resetCumulativeTime (): void { this._cumulativeTime = 0; } @@ -470,7 +470,7 @@ export class Root { * @zh 用于每帧执行渲染流程的入口函数 * @param deltaTime @en The delta time since last update. @zh 距离上一帧间隔时间 */ - public frameMove (deltaTime: number) { + public frameMove (deltaTime: number): void { this._frameTime = deltaTime; /* @@ -519,7 +519,7 @@ export class Root { * @zh 销毁指定的窗口 * @param window The render window to be destroyed */ - public destroyWindow (window: RenderWindow) { + public destroyWindow (window: RenderWindow): void { for (let i = 0; i < this._windows.length; ++i) { if (this._windows[i] === window) { window.destroy(); @@ -533,7 +533,7 @@ export class Root { * @en Destroy all render windows * @zh 销毁全部窗口 */ - public destroyWindows () { + public destroyWindows (): void { for (const window of this._windows) { window.destroy(); } @@ -557,7 +557,7 @@ export class Root { * @zh 销毁指定的渲染场景 * @param scene @en The render scene to be destroyed. @zh 要销毁的渲染场景 */ - public destroyScene (scene: RenderScene) { + public destroyScene (scene: RenderScene): void { for (let i = 0; i < this._scenes.length; ++i) { if (this._scenes[i] === scene) { scene.destroy(); @@ -571,7 +571,7 @@ export class Root { * @en Destroy all render scenes. * @zh 销毁全部场景。 */ - public destroyScenes () { + public destroyScenes (): void { for (const scene of this._scenes) { scene.destroy(); } @@ -587,7 +587,7 @@ export class Root { public createModel (ModelCtor: typeof Model): T { let p = this._modelPools.get(ModelCtor); if (!p) { - this._modelPools.set(ModelCtor, new Pool(() => new ModelCtor(), 10, (obj) => obj.destroy())); + this._modelPools.set(ModelCtor, new Pool((): Model => new ModelCtor(), 10, (obj): void => obj.destroy())); p = this._modelPools.get(ModelCtor)!; } const model = p.alloc() as T; @@ -600,7 +600,7 @@ export class Root { * @zh 销毁指定的模型 * @param m @en The model to be destroyed @zh 要销毁的模型 */ - public destroyModel (m: Model) { + public destroyModel (m: Model): void { const p = this._modelPools.get(m.constructor as Constructor); if (p) { p.free(m); @@ -631,7 +631,7 @@ export class Root { public createLight (LightCtor: new () => T): T { let l = this._lightPools.get(LightCtor); if (!l) { - this._lightPools.set(LightCtor, new Pool(() => new LightCtor(), 4, (obj) => obj.destroy())); + this._lightPools.set(LightCtor, new Pool((): T => new LightCtor(), 4, (obj): void => obj.destroy())); l = this._lightPools.get(LightCtor)!; } const light = l.alloc() as T; @@ -644,7 +644,7 @@ export class Root { * @zh 销毁指定的光源 * @param l @en The light to be destroyed @zh 要销毁的光源 */ - public destroyLight (l: Light) { + public destroyLight (l: Light): void { if (l.scene) { switch (l.type) { case LightType.DIRECTIONAL: @@ -674,7 +674,7 @@ export class Root { * @zh 回收指定的光源到对象池 * @param l @en The light to be recycled @zh 要回收的光源 */ - public recycleLight (l: Light) { + public recycleLight (l: Light): void { const p = this._lightPools.get(l.constructor as Constructor); if (p) { p.free(l); @@ -702,7 +702,7 @@ export class Root { } } - private _doWebXRFrameMove () { + private _doWebXRFrameMove (): void { const xr = globalThis.__globalXR; if (!xr) { return; @@ -768,7 +768,7 @@ export class Root { } } - private _frameMoveBegin () { + private _frameMoveBegin (): void { for (let i = 0; i < this._scenes.length; ++i) { this._scenes[i].removeBatches(); } @@ -776,7 +776,7 @@ export class Root { this._cameraList.length = 0; } - private _frameMoveProcess () { + private _frameMoveProcess (): void { const { director } = cclegacy; const windows = this._windows; const cameraList = this._cameraList; @@ -802,12 +802,12 @@ export class Root { } } - private _frameMoveEnd () { + private _frameMoveEnd (): void { const { director, Director } = cclegacy; const cameraList = this._cameraList; if (this._pipeline && cameraList.length > 0) { director.emit(Director.EVENT_BEFORE_COMMIT); - cameraList.sort((a: Camera, b: Camera) => a.priority - b.priority); + cameraList.sort((a: Camera, b: Camera): number => a.priority - b.priority); for (let i = 0; i < cameraList.length; ++i) { cameraList[i].geometryRenderer?.update(); @@ -821,7 +821,7 @@ export class Root { if (this._batcher) this._batcher.reset(); } - private _resizeMaxJointForDS () { + private _resizeMaxJointForDS (): void { const usedUBOVectorCount = (UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOLocal.COUNT + UBOWorldBound.COUNT) / 4; let maxJoints = Math.floor((deviceManager.gfxDevice.capabilities.maxVertexUniformVectors - usedUBOVectorCount) / 3); maxJoints = maxJoints < 256 ? maxJoints : 256; diff --git a/cocos/scene-graph/component-event-handler.ts b/cocos/scene-graph/component-event-handler.ts index 40e7883174f..99865f80245 100644 --- a/cocos/scene-graph/component-event-handler.ts +++ b/cocos/scene-graph/component-event-handler.ts @@ -60,7 +60,7 @@ export class EventHandler { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - get _componentName () { + get _componentName (): any { this._genCompIdIfNeeded(); return this._compId2Name(this._componentId); @@ -78,7 +78,7 @@ export class EventHandler { * @param events - The event list to be emitted * @param args - The callback arguments */ - public static emitEvents (events: EventHandler[], ...args: any[]) { + public static emitEvents (events: EventHandler[], ...args: any[]): void { for (let i = 0, l = events.length; i < l; i++) { const event = events[i]; if (!(event instanceof EventHandler)) { @@ -153,7 +153,7 @@ export class EventHandler { * eventHandler.emit(["param1", "param2", ....]); * ``` */ - public emit (params: any[]) { + public emit (params: any[]): void { const target = this.target; if (!legacyCC.isValid(target)) { return; } @@ -174,18 +174,18 @@ export class EventHandler { handler.apply(comp, params); } - private _compName2Id (compName) { + private _compName2Id (compName): any { const comp = legacyCC.js.getClassByName(compName); return legacyCC.js.getClassId(comp); } - private _compId2Name (compId) { + private _compId2Name (compId): any { const comp = legacyCC.js.getClassById(compId); return legacyCC.js.getClassName(comp); } // to be deprecated in the future - private _genCompIdIfNeeded () { + private _genCompIdIfNeeded (): void { if (!this._componentId) { this._componentName = this.component; this.component = ''; diff --git a/cocos/scene-graph/component-scheduler.ts b/cocos/scene-graph/component-scheduler.ts index d1089506fae..52e93d51f2f 100644 --- a/cocos/scene-graph/component-scheduler.ts +++ b/cocos/scene-graph/component-scheduler.ts @@ -39,7 +39,7 @@ const callerFunctor: any = EDITOR && tryCatchFunctor_EDITOR; const callOnEnableInTryCatch: any = EDITOR && callerFunctor('onEnable'); const callOnDisableInTryCatch: any = EDITOR && callerFunctor('onDisable'); -function sortedIndex (array, comp) { +function sortedIndex (array, comp): number { const order = comp.constructor._executionOrder; const id = comp._id; let l = 0; @@ -68,7 +68,7 @@ function sortedIndex (array, comp) { } // remove disabled and not invoked component from array -function stableRemoveInactive (iterator, flagToClear) { +function stableRemoveInactive (iterator, flagToClear): void { const array = iterator.array; let next = iterator.i + 1; while (next < array.length) { @@ -108,29 +108,29 @@ export class LifeCycleInvoker { } } -function compareOrder (a, b) { +function compareOrder (a, b): number { return a.constructor._executionOrder - b.constructor._executionOrder; } // for onLoad: sort once all components registered, invoke once export class OneOffInvoker extends LifeCycleInvoker { - public add (comp) { + public add (comp): void { const order = comp.constructor._executionOrder; (order === 0 ? this._zero : (order < 0 ? this._neg : this._pos)).array.push(comp); } - public remove (comp) { + public remove (comp): void { const order = comp.constructor._executionOrder; (order === 0 ? this._zero : (order < 0 ? this._neg : this._pos)).fastRemove(comp); } - public cancelInactive (flagToClear) { + public cancelInactive (flagToClear): void { stableRemoveInactive(this._zero, flagToClear); stableRemoveInactive(this._neg, flagToClear); stableRemoveInactive(this._pos, flagToClear); } - public invoke () { + public invoke (): void { const compsNeg = this._neg; if (compsNeg.array.length > 0) { compsNeg.array.sort(compareOrder); @@ -152,7 +152,7 @@ export class OneOffInvoker extends LifeCycleInvoker { // for update: sort every time new component registered, invoke many times class ReusableInvoker extends LifeCycleInvoker { - public add (comp) { + public add (comp): void { const order = comp.constructor._executionOrder; if (order === 0) { this._zero.array.push(comp); @@ -167,7 +167,7 @@ class ReusableInvoker extends LifeCycleInvoker { } } - public remove (comp) { + public remove (comp): void { const order = comp.constructor._executionOrder; if (order === 0) { this._zero.fastRemove(comp); @@ -180,7 +180,7 @@ class ReusableInvoker extends LifeCycleInvoker { } } - public invoke (dt) { + public invoke (dt): void { if (this._neg.array.length > 0) { this._invoke(this._neg, dt); } @@ -193,7 +193,7 @@ class ReusableInvoker extends LifeCycleInvoker { } } -function enableInEditor (comp) { +function enableInEditor (comp): void { if (!(comp._objFlags & IsEditorOnEnableCalled)) { legacyCC.engine.emit('component-enabled', comp.uuid); if (!legacyCC.GAME_VIEW) { @@ -203,7 +203,7 @@ function enableInEditor (comp) { } // return function to simply call each component with try catch protection -export function createInvokeImplJit (code: string, useDt?, ensureFlag?) { +export function createInvokeImplJit (code: string, useDt?, ensureFlag?): (iterator: any, dt: any) => void { // function (it) { // let a = it.array; // for (it.i = 0; it.i < a.length; ++it.i) { @@ -220,8 +220,8 @@ export function createInvokeImplJit (code: string, useDt?, ensureFlag?) { const singleInvoke = Function('c', 'dt', code); return createInvokeImpl(singleInvoke, fastPath, ensureFlag); } -export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?) { - return (iterator, dt) => { +export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?): (iterator: any, dt: any) => void { + return (iterator, dt): void => { try { fastPath(iterator, dt); } catch (e) { @@ -248,11 +248,11 @@ export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?) { const invokeStart = SUPPORT_JIT ? createInvokeImplJit(`c.start();c._objFlags|=${IsStartCalled}`, false, IsStartCalled) : createInvokeImpl( - (c) => { + (c): void => { c.start(); c._objFlags |= IsStartCalled; }, - (iterator) => { + (iterator): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { const comp = array[iterator.i]; @@ -265,10 +265,10 @@ const invokeStart = SUPPORT_JIT ? createInvokeImplJit(`c.start();c._objFlags|=${ const invokeUpdate = SUPPORT_JIT ? createInvokeImplJit('c.update(dt)', true) : createInvokeImpl( - (c, dt) => { + (c, dt): void => { c.update(dt); }, - (iterator, dt) => { + (iterator, dt): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].update(dt); @@ -278,10 +278,10 @@ const invokeUpdate = SUPPORT_JIT ? createInvokeImplJit('c.update(dt)', true) const invokeLateUpdate = SUPPORT_JIT ? createInvokeImplJit('c.lateUpdate(dt)', true) : createInvokeImpl( - (c, dt) => { + (c, dt): void => { c.lateUpdate(dt); }, - (iterator, dt) => { + (iterator, dt): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].lateUpdate(dt); @@ -289,7 +289,7 @@ const invokeLateUpdate = SUPPORT_JIT ? createInvokeImplJit('c.lateUpdate(dt)', t }, ); -export const invokeOnEnable = EDITOR ? (iterator) => { +export const invokeOnEnable = EDITOR ? (iterator): void => { const compScheduler = legacyCC.director._compScheduler; const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { @@ -302,7 +302,7 @@ export const invokeOnEnable = EDITOR ? (iterator) => { } } } -} : (iterator) => { +} : (iterator): void => { const compScheduler = legacyCC.director._compScheduler; const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { @@ -351,7 +351,7 @@ export class ComponentScheduler { * @en Cancel all future callbacks, including `start`, `update` and `lateUpdate` * @zh 取消所有未来的函数调度,包括 `start`,`update` 和 `lateUpdate` */ - public unscheduleAll () { + public unscheduleAll (): void { // invokers this.startInvoker = new OneOffInvoker(invokeStart); this.updateInvoker = new ReusableInvoker(invokeUpdate); @@ -364,7 +364,7 @@ export class ComponentScheduler { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onEnabled (comp) { + public _onEnabled (comp): void { legacyCC.director.getScheduler().resumeTarget(comp); comp._objFlags |= IsOnEnableCalled; @@ -379,7 +379,7 @@ export class ComponentScheduler { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onDisabled (comp) { + public _onDisabled (comp): void { legacyCC.director.getScheduler().pauseTarget(comp); comp._objFlags &= ~IsOnEnableCalled; @@ -408,7 +408,7 @@ export class ComponentScheduler { * @param comp The component to be enabled * @param invoker The invoker which is responsible to schedule the `onEnable` call */ - public enableComp (comp, invoker?) { + public enableComp (comp, invoker?): void { if (!(comp._objFlags & IsOnEnableCalled)) { if (comp.onEnable) { if (invoker) { @@ -432,7 +432,7 @@ export class ComponentScheduler { * @zh 禁用一个组件 * @param comp The component to be disabled */ - public disableComp (comp) { + public disableComp (comp): void { if (comp._objFlags & IsOnEnableCalled) { if (comp.onDisable) { comp.onDisable(); @@ -445,7 +445,7 @@ export class ComponentScheduler { * @en Process start phase for registered components * @zh 为当前注册的组件执行 start 阶段任务 */ - public startPhase () { + public startPhase (): void { // Start of this frame this._updating = true; @@ -475,7 +475,7 @@ export class ComponentScheduler { * @zh 为当前注册的组件执行 update 阶段任务 * @param dt @en Time passed after the last frame in seconds @zh 距离上一帧的时间,以秒计算 */ - public updatePhase (dt:number) { + public updatePhase (dt:number): void { this.updateInvoker.invoke(dt); } @@ -484,7 +484,7 @@ export class ComponentScheduler { * @zh 为当前注册的组件执行 late update 阶段任务 * @param dt @en Time passed after the last frame in seconds @zh 距离上一帧的时间,以秒计算 */ - public lateUpdatePhase (dt:number) { + public lateUpdatePhase (dt:number): void { this.lateUpdateInvoker.invoke(dt); // End of this frame @@ -497,14 +497,14 @@ export class ComponentScheduler { // Call new registered start schedule immediately since last time start phase calling in this frame // See cocos-creator/2d-tasks/issues/256 - private _startForNewComps () { + private _startForNewComps (): void { if (this._deferredComps.length > 0) { this._deferredSchedule(); this.startInvoker.invoke(); } } - private _scheduleImmediate (comp) { + private _scheduleImmediate (comp): void { if (typeof comp.start === 'function' && !(comp._objFlags & IsStartCalled)) { this.startInvoker.add(comp); } @@ -516,7 +516,7 @@ export class ComponentScheduler { } } - private _deferredSchedule () { + private _deferredSchedule (): void { const comps = this._deferredComps; for (let i = 0, len = comps.length; i < len; i++) { this._scheduleImmediate(comps[i]); @@ -526,7 +526,7 @@ export class ComponentScheduler { } if (EDITOR) { - ComponentScheduler.prototype.enableComp = function (comp, invoker) { + ComponentScheduler.prototype.enableComp = function (comp, invoker): void { if (legacyCC.GAME_VIEW || comp.constructor._executeInEditMode) { if (!(comp._objFlags & IsOnEnableCalled)) { if (comp.onEnable) { @@ -549,7 +549,7 @@ if (EDITOR) { enableInEditor(comp); }; - ComponentScheduler.prototype.disableComp = function (comp) { + ComponentScheduler.prototype.disableComp = function (comp): void { if (legacyCC.GAME_VIEW || comp.constructor._executeInEditMode) { if (comp._objFlags & IsOnEnableCalled) { if (comp.onDisable) { diff --git a/cocos/scene-graph/component.ts b/cocos/scene-graph/component.ts index 1c74739e54f..0a9c8ccb62e 100644 --- a/cocos/scene-graph/component.ts +++ b/cocos/scene-graph/component.ts @@ -58,7 +58,7 @@ const NullNode = null as unknown as Node; class Component extends CCObject { public static EventHandler = EventHandler; - get name () { + get name (): string { if (this._name) { return this._name; } @@ -88,7 +88,7 @@ class Component extends CCObject { * log(comp.uuid); * ``` */ - get uuid () { + get uuid (): string { return this._id; } @@ -99,7 +99,7 @@ class Component extends CCObject { @type(Script) @tooltip('i18n:INSPECTOR.component.script') @disallowAnimation - get __scriptAsset () { return null; } + get __scriptAsset (): null { return null; } /** * @en Indicates whether this component is enabled or not. @@ -112,7 +112,7 @@ class Component extends CCObject { * log(comp.enabled); * ``` */ - get enabled () { + get enabled (): boolean { return this._enabled; } set enabled (value) { @@ -139,7 +139,7 @@ class Component extends CCObject { * log(comp.enabledInHierarchy); * ``` */ - get enabledInHierarchy () { + get enabledInHierarchy (): boolean { return this._enabled && this.node && this.node.activeInHierarchy; } @@ -155,7 +155,7 @@ class Component extends CCObject { * * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - get _isOnLoadCalled () { + get _isOnLoadCalled (): number { return this._objFlags & IsOnLoadCalled; } @@ -233,7 +233,7 @@ class Component extends CCObject { */ public addComponent (className: string): Component | null; - public addComponent (typeOrClassName: any) { + public addComponent (typeOrClassName: any): Component { return this.node.addComponent(typeOrClassName); } @@ -270,7 +270,7 @@ class Component extends CCObject { */ public getComponent (className: string): Component | null; - public getComponent (typeOrClassName: any) { + public getComponent (typeOrClassName: any): Component | null { return this.node.getComponent(typeOrClassName); } @@ -297,7 +297,7 @@ class Component extends CCObject { */ public getComponents (className: string): Component[]; - public getComponents (typeOrClassName: any) { + public getComponents (typeOrClassName: any): Component[] { return this.node.getComponents(typeOrClassName); } @@ -324,7 +324,7 @@ class Component extends CCObject { */ public getComponentInChildren (className: string): Component | null; - public getComponentInChildren (typeOrClassName: any) { + public getComponentInChildren (typeOrClassName: any): Component | null { return this.node.getComponentInChildren(typeOrClassName); } @@ -351,13 +351,13 @@ class Component extends CCObject { */ public getComponentsInChildren (className: string): Component[]; - public getComponentsInChildren (typeOrClassName: any) { + public getComponentsInChildren (typeOrClassName: any): Component[] { return this.node.getComponentsInChildren(typeOrClassName); } // OVERRIDE - public destroy () { + public destroy (): boolean { if (EDITOR) { // TODO: `_getDependComponent` is an injected method. // issue: https://github.com/cocos/cocos-engine/issues/14643 @@ -380,7 +380,7 @@ class Component extends CCObject { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onPreDestroy () { + public _onPreDestroy (): void { // Schedules this.unscheduleAllCallbacks(); @@ -394,7 +394,7 @@ class Component extends CCObject { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _instantiate (cloned?: Component) { + public _instantiate (cloned?: Component): Component | undefined { if (!cloned) { cloned = legacyCC.instantiate._clone(this, this); } @@ -425,7 +425,7 @@ class Component extends CCObject { * this.schedule((dt) => void log(`time: ${dt}`), 1); * ``` */ - public schedule (callback, interval = 0, repeat: number = legacyCC.macro.REPEAT_FOREVER, delay = 0) { + public schedule (callback, interval = 0, repeat: number = legacyCC.macro.REPEAT_FOREVER, delay = 0): void { assertID(callback, 1619); interval = interval || 0; @@ -458,7 +458,7 @@ class Component extends CCObject { * this.scheduleOnce((dt) => void log(`time: ${dt}`), 2); * ``` */ - public scheduleOnce (callback, delay = 0) { + public scheduleOnce (callback, delay = 0): void { this.schedule(callback, 0, 0, delay); } @@ -471,7 +471,7 @@ class Component extends CCObject { * this.unschedule(_callback); * ``` */ - public unschedule (callback_fn) { + public unschedule (callback_fn): void { if (!callback_fn) { return; } @@ -487,7 +487,7 @@ class Component extends CCObject { * this.unscheduleAllCallbacks(); * ``` */ - public unscheduleAllCallbacks () { + public unscheduleAllCallbacks (): void { legacyCC.director.getScheduler().unscheduleAllForTarget(this); } @@ -687,7 +687,7 @@ if (EDITOR || TEST) { } // we make this non-enumerable, to prevent inherited by sub classes. -value(Component, '_registerEditorProps', (cls, props) => { +value(Component, '_registerEditorProps', (cls, props): void => { let reqComp = props.requireComponent; if (reqComp) { if (Array.isArray(reqComp)) { diff --git a/cocos/scene-graph/deprecated.ts b/cocos/scene-graph/deprecated.ts index 97d31533eb8..072166d3851 100644 --- a/cocos/scene-graph/deprecated.ts +++ b/cocos/scene-graph/deprecated.ts @@ -36,12 +36,13 @@ import { SceneGlobals } from './scene-globals'; import { SystemEventType } from '../input/types'; import { SystemEvent } from '../input'; import { NodeUIProperties } from './node-ui-properties'; +import type { NodeEventType } from './node-event'; replaceProperty(Node.prototype, 'Node', [ { name: 'childrenCount', newName: 'children.length', - customGetter (this: Node) { + customGetter (this: Node): number { return this.children.length; }, }, @@ -51,47 +52,47 @@ replaceProperty(Node.prototype, 'Node', [ { name: 'width', targetName: 'node.getComponent(UITransform)', - customGetter (this: Node) { + customGetter (this: Node): number { return this._uiProps.uiTransformComp!.width; }, - customSetter (this: Node, value: number) { + customSetter (this: Node, value: number): void { this._uiProps.uiTransformComp!.width = value; }, }, { name: 'height', targetName: 'node.getComponent(UITransform)', - customGetter (this: Node) { + customGetter (this: Node): number { return this._uiProps.uiTransformComp!.height; }, - customSetter (this: Node, value: number) { + customSetter (this: Node, value: number): void { this._uiProps.uiTransformComp!.height = value; }, }, { name: 'anchorX', targetName: 'node.getComponent(UITransform)', - customGetter (this: Node) { + customGetter (this: Node): number { return this._uiProps.uiTransformComp!.anchorX; }, - customSetter (this: Node, value: number) { + customSetter (this: Node, value: number): void { this._uiProps.uiTransformComp!.anchorX = value; }, }, { name: 'anchorY', targetName: 'node.getComponent(UITransform)', - customGetter (this: Node) { + customGetter (this: Node): number { return this._uiProps.uiTransformComp!.anchorY; }, - customSetter (this: Node, value: number) { + customSetter (this: Node, value: number): void { this._uiProps.uiTransformComp!.anchorY = value; }, }, { name: 'getAnchorPoint', targetName: 'node.getComponent(UITransform)', - customFunction (this: Node, out?: Vec2) { + customFunction (this: Node, out?: Vec2): Vec2 { if (!out) { out = new Vec2(); } @@ -102,7 +103,7 @@ replaceProperty(Node.prototype, 'Node', [ { name: 'setAnchorPoint', targetName: 'node.getComponent(UITransform)', - customFunction (this: Node, point: Vec2 | number, y?: number) { + customFunction (this: Node, point: Vec2 | number, y?: number): void { this._uiProps.uiTransformComp!.setAnchorPoint(point, y); }, }, @@ -121,7 +122,7 @@ replaceProperty(Node.prototype, 'Node', [ { name: 'setContentSize', targetName: 'node.getComponent(UITransform)', - customFunction (this: Node, size: Size | number, height?: number) { + customFunction (this: Node, size: Size | number, height?: number): void { if (typeof size === 'number') { this._uiProps.uiTransformComp!.setContentSize(size, height!); } else { @@ -316,7 +317,7 @@ export class PrivateNode extends Node { if (EDITOR) { // check components to avoid missing node reference serialied in previous version - PrivateNode.prototype._onBatchCreated = function onBatchCreated (this: PrivateNode, dontSyncChildPrefab: boolean) { + PrivateNode.prototype._onBatchCreated = function onBatchCreated (this: PrivateNode, dontSyncChildPrefab: boolean): void { for (const comp of this._components) { comp.node = this; } @@ -339,7 +340,7 @@ replaceProperty(SystemEventType, 'SystemEventType', [ 'NODE_DESTROYED', 'LAYER_CHANGED', 'SIBLING_ORDER_CHANGED', -].map((name: string) => ({ +].map((name: string): { name: string; target: typeof NodeEventType; targetName: string; } => ({ name, target: Node.EventType, targetName: 'Node.EventType', diff --git a/cocos/scene-graph/layers.ts b/cocos/scene-graph/layers.ts index b63696c0a46..c1ae357dec7 100644 --- a/cocos/scene-graph/layers.ts +++ b/cocos/scene-graph/layers.ts @@ -73,7 +73,7 @@ export class Layers { /** * @internal */ - public static init () { + public static init (): void { const userLayers = settings.querySettings(Settings.Category.ENGINE, 'customLayers'); if (!userLayers) return; for (let i = 0; i < userLayers.length; i++) { @@ -116,7 +116,7 @@ export class Layers { * @param name Layer's name * @param bitNum Layer's bit position */ - public static addLayer (name: string, bitNum: number) { + public static addLayer (name: string, bitNum: number): void { if (bitNum === undefined) { console.warn('bitNum can\'t be undefined'); return; @@ -141,7 +141,7 @@ export class Layers { * @zh 移除一个层,用户可编辑 0 - 19 位为用户自定义层 * @param bitNum Layer's bit position */ - public static deleteLayer (bitNum: number) { + public static deleteLayer (bitNum: number): void { if (bitNum > 19 || bitNum < 0) { console.warn('do not change buildin layers.'); return; diff --git a/cocos/scene-graph/node-activator.ts b/cocos/scene-graph/node-activator.ts index fa929cf1cb0..4afb383cb92 100644 --- a/cocos/scene-graph/node-activator.ts +++ b/cocos/scene-graph/node-activator.ts @@ -40,7 +40,7 @@ const IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled; const Deactivating = CCObject.Flags.Deactivating; const callPreloadInTryCatch: any = EDITOR && tryCatchFunctor_EDITOR('__preload'); -const callOnLoadInTryCatch: any = EDITOR && function (c) { +const callOnLoadInTryCatch: any = EDITOR && function (c): void { try { c.onLoad(); } catch (e) { @@ -55,16 +55,16 @@ const callOnLostFocusInTryCatch: any = EDITOR && tryCatchFunctor_EDITOR('onLostF // for __preload: used internally, no sort class UnsortedInvoker extends LifeCycleInvoker { - public add (comp) { + public add (comp): void { this._zero.array.push(comp); } - public remove (comp) { + public remove (comp): void { this._zero.fastRemove(comp); } - public cancelInactive (flagToClear) { + public cancelInactive (flagToClear): void { LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear); } - public invoke () { + public invoke (): void { this._invoke(this._zero); this._zero.array.length = 0; } @@ -72,8 +72,8 @@ class UnsortedInvoker extends LifeCycleInvoker { const invokePreload = SUPPORT_JIT ? createInvokeImplJit('c.__preload();') : createInvokeImpl( - (c) => { c.__preload(); }, - (iterator) => { + (c): void => { c.__preload(); }, + (iterator): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].__preload(); @@ -82,11 +82,11 @@ const invokePreload = SUPPORT_JIT ? createInvokeImplJit('c.__preload();') ); const invokeOnLoad = SUPPORT_JIT ? createInvokeImplJit(`c.onLoad();c._objFlags|=${IsOnLoadCalled}`, false, IsOnLoadCalled) : createInvokeImpl( - (c) => { + (c): void => { c.onLoad(); c._objFlags |= IsOnLoadCalled; }, - (iterator) => { + (iterator): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { const comp = array[iterator.i]; @@ -98,7 +98,7 @@ const invokeOnLoad = SUPPORT_JIT ? createInvokeImplJit(`c.onLoad();c._objFlags|= ); const activateTasksPool = new Pool(MAX_POOL_SIZE); -activateTasksPool.get = function getActivateTask () { +activateTasksPool.get = function getActivateTask (): any { const task: any = this._get() || { preload: new UnsortedInvoker(invokePreload), onLoad: new OneOffInvoker(invokeOnLoad), @@ -119,7 +119,7 @@ activateTasksPool.get = function getActivateTask () { return task; }; -function _componentCorrupted (node, comp, index) { +function _componentCorrupted (node, comp, index): void { errorID(3817, node.name, index); console.log('Corrupted component value:', comp); if (comp) { @@ -129,7 +129,7 @@ function _componentCorrupted (node, comp, index) { } } -function _onLoadInEditor (comp) { +function _onLoadInEditor (comp): void { if (comp.onLoad && !legacyCC.GAME_VIEW) { const focused = Editor.Selection.getLastSelected('node') === comp.node.uuid; if (focused) { @@ -158,7 +158,7 @@ export default class NodeActivator { * @en Reset all activation or des-activation tasks * @zh 重置所有激活或非激活任务 */ - public reset () { + public reset (): void { // a stack of node's activating tasks this._activatingStack = []; } @@ -169,7 +169,7 @@ export default class NodeActivator { * @param node Target node * @param active Which state to set the node to */ - public activateNode (node, active) { + public activateNode (node, active): void { if (active) { const task: any = activateTasksPool.get(); this._activatingStack.push(task); @@ -204,7 +204,7 @@ export default class NodeActivator { * @param onLoadInvoker The invoker for `onLoad` method, normally from [[ComponentScheduler]] * @param onEnableInvoker The invoker for `onEnable` method, normally from [[ComponentScheduler]] */ - public activateComp (comp, preloadInvoker?, onLoadInvoker?, onEnableInvoker?) { + public activateComp (comp, preloadInvoker?, onLoadInvoker?, onEnableInvoker?): void { if (!isValid(comp, true)) { // destroyed before activating return; @@ -249,7 +249,7 @@ export default class NodeActivator { * @zh 销毁一个组件 * @param comp Target component */ - public destroyComp (comp) { + public destroyComp (comp): void { // ensure onDisable called legacyCC.director._compScheduler.disableComp(comp); @@ -258,7 +258,7 @@ export default class NodeActivator { } } - protected _activateNodeRecursively (node, preloadInvoker, onLoadInvoker, onEnableInvoker) { + protected _activateNodeRecursively (node, preloadInvoker, onLoadInvoker, onEnableInvoker): void { if (node._objFlags & Deactivating) { // en: // Forbid reactive the same node during its deactivating procedure @@ -297,7 +297,7 @@ export default class NodeActivator { node._onPostActivated(true); } - protected _deactivateNodeRecursively (node) { + protected _deactivateNodeRecursively (node): void { if (DEV) { assert(!(node._objFlags & Deactivating), 'node should not deactivating'); // ensures _activeInHierarchy is always changing when Deactivating flagged @@ -340,7 +340,7 @@ export default class NodeActivator { } if (EDITOR) { - NodeActivator.prototype.activateComp = (comp, preloadInvoker, onLoadInvoker, onEnableInvoker) => { + NodeActivator.prototype.activateComp = (comp, preloadInvoker, onLoadInvoker, onEnableInvoker): void => { if (!isValid(comp, true)) { // destroyed before activating return; @@ -382,7 +382,7 @@ if (EDITOR) { } }; - NodeActivator.prototype.destroyComp = (comp) => { + NodeActivator.prototype.destroyComp = (comp): void => { // ensure onDisable called legacyCC.director._compScheduler.disableComp(comp); @@ -393,7 +393,7 @@ if (EDITOR) { } }; - NodeActivator.prototype.resetComp = (comp, didResetToDefault: boolean) => { + NodeActivator.prototype.resetComp = (comp, didResetToDefault: boolean): void => { if (comp.resetInEditor) { try { comp.resetInEditor(didResetToDefault); diff --git a/cocos/scene-graph/node-dev.ts b/cocos/scene-graph/node-dev.ts index ff9501be57b..cae8b7f732f 100644 --- a/cocos/scene-graph/node-dev.ts +++ b/cocos/scene-graph/node-dev.ts @@ -32,9 +32,9 @@ import { Component } from './component'; const Destroying = CCObject.Flags.Destroying; const IS_PREVIEW = !!legacyCC.GAME_VIEW; -export function nodePolyfill (Node) { +export function nodePolyfill (Node): void { if ((EDITOR && !IS_PREVIEW) || TEST) { - Node.prototype._onPreDestroy = function () { + Node.prototype._onPreDestroy = function (): boolean { const destroyByParent: boolean = this._onPreDestroyBase(); if (!destroyByParent) { // ensure this node can reattach to scene by undo system @@ -46,7 +46,7 @@ export function nodePolyfill (Node) { } if (EDITOR || TEST) { - Node.prototype._checkMultipleComp = function (ctor) { + Node.prototype._checkMultipleComp = function (ctor): boolean { const existing = this.getComponent(ctor._disallowMultiple); if (existing) { if (existing.constructor === ctor) { @@ -62,7 +62,7 @@ export function nodePolyfill (Node) { * @param {Component} depended * @return {Component[]} */ - Node.prototype._getDependComponent = function (depended) { + Node.prototype._getDependComponent = function (depended): Component[] { const dependant: Component[] = []; for (let i = 0; i < this._components.length; i++) { const comp = this._components[i]; @@ -89,7 +89,7 @@ export function nodePolyfill (Node) { * @param {Component} comp * @param {Number} index */ - Node.prototype._addComponentAt = function (comp, index) { + Node.prototype._addComponentAt = function (comp, index): void { if (this._objFlags & Destroying) { return error('isDestroying'); } @@ -136,7 +136,7 @@ export function nodePolyfill (Node) { return undefined; }; - Node.prototype.onRestore = function () { + Node.prototype.onRestore = function (): void { // check activity state const shouldActiveNow = this._active && !!(this._parent && this._parent._activeInHierarchy); if (this._activeInHierarchy !== shouldActiveNow) { @@ -145,7 +145,7 @@ export function nodePolyfill (Node) { }; Node.prototype._onRestoreBase = Node.prototype.onRestore; - Node.prototype._registerIfAttached = function (register) { + Node.prototype._registerIfAttached = function (register): void { if (!this._id) { console.warn(`Node(${this && this.name}}) is invalid or its data is corrupted.`); return; diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts index 61f215e1755..d01ba5fab22 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/scene-graph/node-event-processor.ts @@ -79,7 +79,7 @@ export class NodeEventProcessor { /** * Whether the node event is enabled */ - public get isEnabled () { + public get isEnabled (): boolean { return this._isEnabled; } @@ -106,7 +106,7 @@ export class NodeEventProcessor { /** * The owner of node event processor. */ - public get node () { + public get node (): Node { return this._node; } @@ -144,7 +144,7 @@ export class NodeEventProcessor { * @param recursive Recursively set the state or not * @returns void */ - public setEnabled (value: boolean, recursive = false) { + public setEnabled (value: boolean, recursive = false): void { if (this._isEnabled === value) { return; } @@ -204,7 +204,7 @@ export class NodeEventProcessor { } } - public on (type: NodeEventType, callback: AnyFunction, target?: unknown, useCapture?: boolean) { + public on (type: NodeEventType, callback: AnyFunction, target?: unknown, useCapture?: boolean): AnyFunction { this._tryEmittingAddEvent(type); useCapture = !!useCapture; let invoker: CallbacksInvoker; @@ -217,7 +217,7 @@ export class NodeEventProcessor { return callback; } - public once (type: NodeEventType, callback: AnyFunction, target?: unknown, useCapture?: boolean) { + public once (type: NodeEventType, callback: AnyFunction, target?: unknown, useCapture?: boolean): AnyFunction { this._tryEmittingAddEvent(type); useCapture = !!useCapture; let invoker: CallbacksInvoker; @@ -231,7 +231,7 @@ export class NodeEventProcessor { return callback; } - public off (type: NodeEventType, callback?: AnyFunction, target?: unknown, useCapture?: boolean) { + public off (type: NodeEventType, callback?: AnyFunction, target?: unknown, useCapture?: boolean): void { useCapture = !!useCapture; let invoker: CallbacksInvoker | null; if (useCapture) { @@ -242,7 +242,7 @@ export class NodeEventProcessor { invoker?.off(type, callback, target); } - public targetOff (target: unknown) { + public targetOff (target: unknown): void { this.capturingTarget?.removeAll(target); this.bubblingTarget?.removeAll(target); @@ -258,11 +258,11 @@ export class NodeEventProcessor { } } - public emit (type: SystemEventTypeUnion, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) { + public emit (type: SystemEventTypeUnion, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void { this.bubblingTarget?.emit(type, arg0, arg1, arg2, arg3, arg4); } - public dispatchEvent (event: Event) { + public dispatchEvent (event: Event): void { const owner = this.node; let target: Node; let i = 0; @@ -321,7 +321,7 @@ export class NodeEventProcessor { _cachedArray.length = 0; } - public hasEventListener (type: SystemEventTypeUnion, callback?: AnyFunction, target?: unknown) { + public hasEventListener (type: SystemEventTypeUnion, callback?: AnyFunction, target?: unknown): boolean { let has = false; if (this.bubblingTarget) { has = this.bubblingTarget.hasEventListener(type, callback, target); @@ -341,7 +341,7 @@ export class NodeEventProcessor { * @param type - 一个监听事件类型的字符串。 * @param array - 接收目标的数组。 */ - public getCapturingTargets (type: string, targets: Node[]) { + public getCapturingTargets (type: string, targets: Node[]): void { let parent = this._node.parent; while (parent) { if (parent.eventProcessor.capturingTarget?.hasEventListener(type)) { @@ -360,7 +360,7 @@ export class NodeEventProcessor { * @param type - 一个监听事件类型的字符串。 * @param array - 接收目标的数组。 */ - public getBubblingTargets (type: string, targets: Node[]) { + public getBubblingTargets (type: string, targets: Node[]): void { let parent = this._node.parent; while (parent) { if (parent.eventProcessor.bubblingTarget?.hasEventListener(type)) { @@ -370,11 +370,11 @@ export class NodeEventProcessor { } } - public onUpdatingSiblingIndex () { + public onUpdatingSiblingIndex (): void { NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY); } - private _searchComponentsInParent (ctor: Constructor | null) { + private _searchComponentsInParent (ctor: Constructor | null): IMask[] | null { const node = this.node; if (ctor) { let index = 0; @@ -401,21 +401,21 @@ export class NodeEventProcessor { return null; } - private _attachMask () { + private _attachMask (): void { this.maskList = this._searchComponentsInParent(NodeEventProcessor._maskComp); } - private _isTouchEvent (type: NodeEventType) { + private _isTouchEvent (type: NodeEventType): boolean { const index = _touchEvents.indexOf(type); return index !== -1; } - private _isMouseEvent (type: NodeEventType) { + private _isMouseEvent (type: NodeEventType): boolean { const index = _mouseEvents.indexOf(type); return index !== -1; } - private _hasTouchListeners () { + private _hasTouchListeners (): boolean { for (let i = 0; i < _touchEvents.length; ++i) { const eventType = _touchEvents[i]; if (this.hasEventListener(eventType)) { @@ -425,7 +425,7 @@ export class NodeEventProcessor { return false; } - private _hasMouseListeners () { + private _hasMouseListeners (): boolean { for (let i = 0; i < _mouseEvents.length; ++i) { const eventType = _mouseEvents[i]; if (this.hasEventListener(eventType)) { @@ -435,7 +435,7 @@ export class NodeEventProcessor { return false; } - private _hasPointerListeners () { + private _hasPointerListeners (): boolean { const has = this._hasTouchListeners(); if (has) { return true; @@ -443,7 +443,7 @@ export class NodeEventProcessor { return this._hasMouseListeners(); } - private _tryEmittingAddEvent (typeToAdd: NodeEventType) { + private _tryEmittingAddEvent (typeToAdd: NodeEventType): void { const isTouchEvent = this._isTouchEvent(typeToAdd); const isMouseEvent = this._isMouseEvent(typeToAdd); if (isTouchEvent) { @@ -594,7 +594,7 @@ export class NodeEventProcessor { /** * @engineInternal */ - public _handleEventTouch (eventTouch: EventTouch) { + public _handleEventTouch (eventTouch: EventTouch): boolean | void { switch (eventTouch.type) { case InputEventType.TOUCH_START: return this._handleTouchStart(eventTouch); @@ -609,7 +609,7 @@ export class NodeEventProcessor { } } - private _handleTouchStart (event: EventTouch) { + private _handleTouchStart (event: EventTouch): boolean { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return false; @@ -628,7 +628,7 @@ export class NodeEventProcessor { return false; } - private _handleTouchMove (event: EventTouch) { + private _handleTouchMove (event: EventTouch): boolean { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return false; @@ -641,7 +641,7 @@ export class NodeEventProcessor { return true; } - private _handleTouchEnd (event: EventTouch) { + private _handleTouchEnd (event: EventTouch): void { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return; @@ -660,7 +660,7 @@ export class NodeEventProcessor { this._dispatchingTouch = null; } - private _handleTouchCancel (event: EventTouch) { + private _handleTouchCancel (event: EventTouch): void { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return; diff --git a/cocos/scene-graph/node-ui-properties.ts b/cocos/scene-graph/node-ui-properties.ts index 265f8efcad1..6387f88f430 100644 --- a/cocos/scene-graph/node-ui-properties.ts +++ b/cocos/scene-graph/node-ui-properties.ts @@ -36,7 +36,7 @@ export class NodeUIProperties { * @en The UI transform component * @zh UI 变换组件 */ - get uiTransformComp () { + get uiTransformComp (): UITransform | null { if (!this._uiTransformComp) { this._uiTransformComp = this._node.getComponent('cc.UITransform') as UITransform; } @@ -51,7 +51,7 @@ export class NodeUIProperties { * @en The base UI component * @zh UI 基类组件 */ - get uiComp () { + get uiComp (): UIMeshRenderer | UIRenderer | null { return this._uiComp; } set uiComp (comp: UIMeshRenderer | UIRenderer | null) { @@ -73,15 +73,15 @@ export class NodeUIProperties { * NOTE: engineInternal tag cannot only mark opacity setter as internal. * @engineInternal */ - public setOpacity (v: number) { this._opacity = v; } - public get opacity () { return this._opacity; } + public setOpacity (v: number): void { this._opacity = v; } + public get opacity (): number { return this._opacity; } /** * @en The opacity of the UI node itself * @zh 本节点的 UI 透明度 */ private _localOpacity = 1; - get localOpacity () { return this._localOpacity; } + get localOpacity (): number { return this._localOpacity; } set localOpacity (val) { this._localOpacity = val; this.colorDirty = true; @@ -98,7 +98,7 @@ export class NodeUIProperties { /** * @deprecated since v3.4 */ - public applyOpacity (effectOpacity) { + public applyOpacity (effectOpacity): void { this._opacity = this._localOpacity * effectOpacity; } @@ -107,5 +107,5 @@ export class NodeUIProperties { * @zh 为结点树的透明度状态设置脏标签,不再有效果 * @deprecated since v3.4 */ - public static markOpacityTree (node, isDirty = true) {} + public static markOpacityTree (node, isDirty = true): void {} } diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index bb4e3685e94..2ea4eda34cf 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -37,7 +37,7 @@ import { Component } from './component'; import { property } from '../core/data/decorators/property'; import { CCObject, js } from '../core'; import type { Scene } from './scene'; -import { PrefabInfo } from './prefab/prefab-info'; +import { PrefabInfo, PrefabInstance } from './prefab/prefab-info'; import { NodeEventType } from './node-event'; import { Event } from '../input/types'; @@ -151,7 +151,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 主要用于编辑器的 uuid,在编辑器下可用于持久化存储,在项目构建之后将变成自增的 id。 * @readOnly */ - get uuid () { + get uuid (): string { return this._id; } @@ -178,7 +178,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @default true */ @editable - get active () { + get active (): boolean { return this._active; } set active (isActive: boolean) { @@ -201,7 +201,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 表示此节点是否在场景中激活。 */ @editable - get activeInHierarchy () { + get activeInHierarchy (): boolean { return this._activeInHierarchy; } @@ -210,7 +210,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 父节点 */ @editable - get parent () { + get parent (): Node | null { return this._parent; } set parent (value) { @@ -222,7 +222,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 此节点属于哪个场景。 * @readonly */ - get scene () { + get scene (): Scene { return this._scene; } @@ -233,7 +233,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * * @deprecated since v3.4.0 */ - get eventProcessor () { + get eventProcessor (): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this._eventProcessor; } @@ -258,7 +258,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @internal * @param node The node. */ - protected static _setScene (node: Node) { + protected static _setScene (node: Node): void { node._updateScene(); } @@ -284,7 +284,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { return null; } - protected static _findComponents (node: Node, constructor: Constructor | AbstractedConstructor, components: Component[]) { + protected static _findComponents (node: Node, constructor: Constructor | AbstractedConstructor, components: Component[]): void { const cls = constructor; const comps = node._components; // NOTE: internal rtti property @@ -323,7 +323,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { return null; } - protected static _findChildComponents (children: Node[], constructor, components) { + protected static _findChildComponents (children: Node[], constructor, components): void { for (let i = 0; i < children.length; ++i) { const node = children[i]; Node._findComponents(node, constructor, components); @@ -346,7 +346,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * NOTE: components getter is typeof ReadonlyArray * @engineInternal */ - public getWritableComponents () { return this._components; } + public getWritableComponents (): Component[] { return this._components; } @serializable protected _components: Component[] = []; @@ -396,7 +396,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * The derived `Scene` overrides this method to behavior differently. * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - protected _updateScene () { + protected _updateScene (): void { if (this._parent == null) { error('Node %s(%s) has not attached to a scene.', this.name, this.uuid); } else { @@ -418,7 +418,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * node.attr(attrs); * ``` */ - public attr (attrs: unknown) { + public attr (attrs: unknown): void { js.mixin(this, attrs); } @@ -426,7 +426,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Get parent of the node. * @zh 获取该节点的父节点。 */ - public getParent () { + public getParent (): Node | null { return this._parent; } @@ -435,7 +435,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * other logic. So add a new function that only modify _parent value. * @engineInternal */ - public modifyParent (parent: this | null) { + public modifyParent (parent: this | null): void { this._parent = parent; } @@ -445,7 +445,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @param value Parent node * @param keepWorldTransform Whether keep node's current world transform unchanged after this operation */ - public setParent (value: this | Scene | null, keepWorldTransform = false) { + public setParent (value: Node | null, keepWorldTransform = false): void { if (keepWorldTransform) { this.updateWorldTransform(); } if (this._parent === value) { @@ -591,7 +591,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * node.insertChild(child, 2); * ``` */ - public insertChild (child: Node, siblingIndex: number) { + public insertChild (child: Node, siblingIndex: number): void { child.setParent(this); child.setSiblingIndex(siblingIndex); } @@ -600,7 +600,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Get the sibling index of the current node in its parent's children array. * @zh 获取当前节点在父节点的 children 数组中的位置。 */ - public getSiblingIndex () { + public getSiblingIndex (): number { return this._siblingIndex; } @@ -608,7 +608,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Set the sibling index of the current node in its parent's children array. * @zh 设置当前节点在父节点的 children 数组中的位置。 */ - public setSiblingIndex (index: number) { + public setSiblingIndex (index: number): void { if (!this._parent) { return; } @@ -655,7 +655,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * }); * ``` */ - public walk (preFunc: (target: this) => void, postFunc?: (target: this) => void) { + public walk (preFunc: (target: this) => void, postFunc?: (target: this) => void): void { let index = 1; let children: this[] | null = null; let curr: this | null = null; @@ -747,7 +747,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * 从父节点中删除该节点。 * 如果这个节点是一个孤立节点,那么什么都不会发生。 */ - public removeFromParent () { + public removeFromParent (): void { if (this._parent) { this._parent.removeChild(this); } @@ -758,7 +758,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 移除节点中指定的子节点。 * @param child - The child node which will be removed. */ - public removeChild (child: this | Node) { + public removeChild (child: this | Node): void { if (this._children.indexOf(child as this) > -1) { // invoke the parent setter child.parent = null; @@ -769,7 +769,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Removes all children from the container. * @zh 移除节点所有的子节点。 */ - public removeAllChildren () { + public removeAllChildren (): void { // not using detachChild improves speed here const children = this._children; for (let i = children.length - 1; i >= 0; i--) { @@ -833,7 +833,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public getComponent(className: string): Component | null; - public getComponent (typeOrClassName: string | Constructor | AbstractedConstructor) { + public getComponent (typeOrClassName: string | Constructor | AbstractedConstructor): T | null { const constructor = getConstructor(typeOrClassName); if (constructor) { return Node._findComponent(this, constructor); @@ -855,7 +855,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public getComponents(className: string): Component[]; - public getComponents (typeOrClassName: string | Constructor | AbstractedConstructor) { + public getComponents (typeOrClassName: string | Constructor | AbstractedConstructor): Component[] { const constructor = getConstructor(typeOrClassName); const components: Component[] = []; if (constructor) { @@ -886,7 +886,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public getComponentInChildren(className: string): Component | null; - public getComponentInChildren (typeOrClassName: string | Constructor | AbstractedConstructor) { + public getComponentInChildren (typeOrClassName: string | Constructor | AbstractedConstructor): T | null { const constructor = getConstructor(typeOrClassName); if (constructor) { return Node._findChildComponent(this._children, constructor); @@ -916,7 +916,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public getComponentsInChildren(className: string): Component[]; - public getComponentsInChildren (typeOrClassName: string | Constructor | AbstractedConstructor) { + public getComponentsInChildren (typeOrClassName: string | Constructor | AbstractedConstructor): Component[] { const constructor = getConstructor(typeOrClassName); const components: Component[] = []; if (constructor) { @@ -950,7 +950,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public addComponent(className: string): Component; - public addComponent (typeOrClassName: string | Constructor) { + public addComponent (typeOrClassName: string | Constructor): T { if (EDITOR && (this._objFlags & Destroying)) { throw Error('isDestroying'); } @@ -1070,7 +1070,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public removeComponent(classNameOrInstance: string | Component): void; - public removeComponent (component: any) { + public removeComponent (component: any): void { if (!component) { errorID(3813); return; @@ -1125,7 +1125,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * node.on(NodeEventType.TOUCH_END, callback, this); * ``` */ - public on (type: string | NodeEventType, callback: AnyFunction, target?: unknown, useCapture: any = false) { + public on (type: string | NodeEventType, callback: AnyFunction, target?: unknown, useCapture: any = false): void { switch (type) { case NodeEventType.TRANSFORM_CHANGED: this._eventMask |= TRANSFORM_ON; @@ -1152,7 +1152,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * node.off(NodeEventType.TOUCH_START, callback, this.node); * ``` */ - public off (type: string, callback?: AnyFunction, target?: unknown, useCapture: any = false) { + public off (type: string, callback?: AnyFunction, target?: unknown, useCapture: any = false): void { this._eventProcessor.off(type, callback, target, useCapture); const hasListeners = this._eventProcessor.hasEventListener(type); @@ -1180,7 +1180,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * 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 */ - public once (type: string, callback: AnyFunction, target?: unknown, useCapture?: any) { + public once (type: string, callback: AnyFunction, target?: unknown, useCapture?: any): void { this._eventProcessor.once(type, callback, target, useCapture); } @@ -1201,7 +1201,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * eventTarget.emit('fire', message, emitter); * ``` */ - public emit (type: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) { + public emit (type: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void { this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4); } @@ -1212,7 +1212,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 分发事件到事件流中。 * @param event - The Event object that is dispatched into the event flow */ - public dispatchEvent (event: Event) { + public dispatchEvent (event: Event): void { this._eventProcessor.dispatchEvent(event); } @@ -1224,7 +1224,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @param target - The callback callee of the event listener * @return True if a callback of the specified type is registered; false otherwise. */ - public hasEventListener (type: string, callback?: AnyFunction, target?: unknown) { + public hasEventListener (type: string, callback?: AnyFunction, target?: unknown): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this._eventProcessor.hasEventListener(type, callback, target); } @@ -1234,7 +1234,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 移除目标上的所有注册事件。 * @param target - The target to be searched for all related callbacks */ - public targetOff (target: string | unknown) { + public targetOff (target: string | unknown): void { this._eventProcessor.targetOff(target); // Check for event mask reset if ((this._eventMask & TRANSFORM_ON) && !this._eventProcessor.hasEventListener(NodeEventType.TRANSFORM_CHANGED)) { @@ -1242,7 +1242,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { } } - public destroy () { + public destroy (): boolean { if (super.destroy()) { this.active = false; return true; @@ -1259,7 +1259,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * 销毁所有子节点,并释放所有它们对其它对象的引用。 * 实际销毁操作会延迟到当前帧渲染前执行。 */ - public destroyAllChildren () { + public destroyAllChildren (): void { const children = this._children; for (let i = 0; i < children.length; ++i) { children[i].destroy(); @@ -1270,7 +1270,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * Do remove component, only used internally. * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _removeComponent (component: Component) { + public _removeComponent (component: Component): void { if (!component) { errorID(3814); return; @@ -1293,7 +1293,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateSiblingIndex () { + public _updateSiblingIndex (): void { for (let i = 0; i < this._children.length; ++i) { this._children[i]._siblingIndex = i; } @@ -1301,7 +1301,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { this.emit(NodeEventType.SIBLING_ORDER_CHANGED); } - protected _instantiate (cloned, isSyncedNode) { + protected _instantiate (cloned, isSyncedNode): any { if (!cloned) { cloned = legacyCC.instantiate._clone(this, this); } @@ -1326,7 +1326,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { return cloned; } - protected _onHierarchyChangedBase (oldParent: this | null) { + protected _onHierarchyChangedBase (oldParent: this | null): void { const newParent = this._parent; if (this._persistNode && !(newParent instanceof legacyCC.Scene)) { legacyCC.game.removePersistRootNode(this); @@ -1361,7 +1361,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { } } - protected _onPreDestroyBase () { + protected _onPreDestroyBase (): boolean { // marked as destroying this._objFlags |= Destroying; @@ -1538,7 +1538,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof legacyCC.Scene)); } - protected _onPreDestroy () { + protected _onPreDestroy (): boolean { return this._onPreDestroyBase(); } @@ -1591,7 +1591,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { this.setRotationFromEuler(val.x, val.y, val.z); } - get eulerAngles () { + get eulerAngles (): Readonly { if (this._eulerDirty) { Quat.toEuler(this._euler, this._lrot); this._eulerDirty = false; @@ -1604,7 +1604,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 本地坐标系下的旋转,用欧拉角表示,但是限定在 z 轴上。 */ @editable - get angle () { + get angle (): number { return this._euler.z; } @@ -1721,7 +1721,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { this.emit(NodeEventType.MOBILITY_CHANGED); } - get mobility () { + get mobility (): number { return this._mobility; } @@ -1740,7 +1740,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { this.emit(NodeEventType.LAYER_CHANGED, this._layer); } - get layer () { + get layer (): number { return this._layer; } @@ -1750,7 +1750,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @engineInternal * @internal */ - get flagChangedVersion () { + get flagChangedVersion (): number { return this._flagChangeVersion; } @@ -1758,7 +1758,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Whether the node's transformation have changed during the current frame. * @zh 这个节点的空间变换信息在当前帧内是否有变过? */ - get hasChangedFlags () { + get hasChangedFlags (): number { return this._flagChangeVersion === globalFlagChangeVersion ? this._hasChangedFlags : 0; } @@ -1770,7 +1770,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { /** * @internal */ - public [serializeTag] (serializationOutput: SerializationOutput, context: SerializationContext) { + public [serializeTag] (serializationOutput: SerializationOutput, context: SerializationContext): void { if (!EDITOR) { serializationOutput.writeThis(); return; @@ -1778,17 +1778,17 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { // Detects if this node is mounted node of `PrefabInstance` // TODO: optimize - const isMountedChild = () => !!(this[editorExtrasTag] as any)?.mountedRoot; + const isMountedChild = (): boolean => !!(this[editorExtrasTag] as any)?.mountedRoot; // Returns if this node is under `PrefabInstance` // eslint-disable-next-line arrow-body-style - const isSyncPrefab = () => { + const isSyncPrefab = (): boolean | PrefabInstance | undefined => { // 1. Under `PrefabInstance`, but not mounted // 2. If the mounted node is a `PrefabInstance`, it's also a "sync prefab". return this._prefab?.root?._prefab?.instance && (this?._prefab?.instance || !isMountedChild()); }; - const canDiscardByPrefabRoot = () => !(context.customArguments[(reserveContentsForAllSyncablePrefabTag) as any] + const canDiscardByPrefabRoot = (): boolean => !(context.customArguments[(reserveContentsForAllSyncablePrefabTag) as any] || !isSyncPrefab() || context.root === this); if (canDiscardByPrefabRoot()) { @@ -1832,7 +1832,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onSetParent (oldParent: this | null, keepWorldTransform = false) { + public _onSetParent (oldParent: this | null, keepWorldTransform = false): void { if (this._parent) { if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) { this.walk(Node._setScene); @@ -1862,7 +1862,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { this.invalidateChildren(TransformBit.TRS); } - protected _onHierarchyChanged (oldParent: this | null) { + protected _onHierarchyChanged (oldParent: this | null): void { this.eventProcessor.reattach(); this._onHierarchyChangedBase(oldParent); } @@ -1870,7 +1870,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBatchCreated (dontSyncChildPrefab: boolean) { + public _onBatchCreated (dontSyncChildPrefab: boolean): void { this.hasChangedFlags = TransformBit.TRS; this._transformFlags |= TransformBit.TRS; const len = this._children.length; @@ -1883,7 +1883,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBeforeSerialize () { + public _onBeforeSerialize (): void { // eslint-disable-next-line @typescript-eslint/no-unused-expressions this.eulerAngles; // make sure we save the correct eulerAngles } @@ -1891,7 +1891,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onPostActivated (active: boolean) { + public _onPostActivated (active: boolean): void { if (active) { // activated this._eventProcessor.setEnabled(true); // in case transform updated during deactivated period @@ -1990,7 +1990,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh 递归标记节点世界变换为 dirty * @param dirtyBit The dirty bits to setup to children, can be composed with multiple dirty bits */ - public invalidateChildren (dirtyBit: TransformBit) { + public invalidateChildren (dirtyBit: TransformBit): void { let i = 0; let j = 0; let l = 0; @@ -2022,7 +2022,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Update the world transform information if outdated * @zh 更新节点的世界变换信息 */ - public updateWorldTransform () { + public updateWorldTransform (): void { if (!this._transformFlags) { return; } // we need to recursively iterate this // eslint-disable-next-line @typescript-eslint/no-this-alias @@ -2142,7 +2142,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public setRotation(x: number, y: number, z: number, w: number): void; - public setRotation (val: Readonly | number, y?: number, z?: number, w?: number) { + public setRotation (val: Readonly | number, y?: number, z?: number, w?: number): void { if (y === undefined || z === undefined || w === undefined) { Quat.copy(this._lrot, val as Readonly); } else { @@ -2220,7 +2220,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public setScale(x: number, y: number, z?: number): void; - public setScale (val: Readonly | number, y?: number, z?: number) { + public setScale (val: Readonly | number, y?: number, z?: number): void { if (y === undefined && z === undefined) { Vec3.copy(this._lscale, val as Vec3); } else if (z === undefined) { @@ -2254,7 +2254,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @param out The result point in local coordinate system will be stored in this vector * @param p A position in world coordinate system */ - public inverseTransformPoint (out: Vec3, p: Vec3) { + public inverseTransformPoint (out: Vec3, p: Vec3): Vec3 { Vec3.copy(out, p); // we need to recursively iterate this // eslint-disable-next-line @typescript-eslint/no-this-alias @@ -2287,7 +2287,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public setWorldPosition(x: number, y: number, z: number): void; - public setWorldPosition (val: Vec3 | number, y?: number, z?: number) { + public setWorldPosition (val: Vec3 | number, y?: number, z?: number): void { if (y === undefined || z === undefined) { Vec3.copy(this._pos, val as Vec3); } else { @@ -2344,7 +2344,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public setWorldRotation(x: number, y: number, z: number, w: number): void; - public setWorldRotation (val: Quat | number, y?: number, z?: number, w?: number) { + public setWorldRotation (val: Quat | number, y?: number, z?: number, w?: number): void { if (y === undefined || z === undefined || w === undefined) { Quat.copy(this._rot, val as Quat); } else { @@ -2417,7 +2417,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ public setWorldScale(x: number, y: number, z: number): void; - public setWorldScale (val: Vec3 | number, y?: number, z?: number) { + public setWorldScale (val: Vec3 | number, y?: number, z?: number): void { const parent = this._parent; if (parent) { this.updateWorldTransform(); @@ -2507,7 +2507,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @param pos The position * @param scale The scale */ - public setRTS (rot?: Quat | Vec3, pos?: Vec3, scale?: Vec3) { + public setRTS (rot?: Quat | Vec3, pos?: Vec3, scale?: Vec3): void { let dirtyBit: TransformBit = 0; if (rot) { dirtyBit |= TransformBit.ROTATION; @@ -2540,7 +2540,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Does the world transform information of this node need to be updated? * @zh 这个节点的空间变换信息是否需要更新? */ - public isTransformDirty () { + public isTransformDirty (): boolean { return this._transformFlags !== TransformBit.NONE; } @@ -2579,7 +2579,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh * 清除所有节点的脏标记。 */ - public static resetHasChangedFlags () { + public static resetHasChangedFlags (): void { globalFlagChangeVersion += 1; } @@ -2589,7 +2589,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @zh * 清除节点数组 */ - public static clearNodeArray () { + public static clearNodeArray (): void { if (Node.ClearFrame < Node.ClearRound && !EDITOR) { Node.ClearFrame++; } else { diff --git a/cocos/scene-graph/prefab/prefab-info.ts b/cocos/scene-graph/prefab/prefab-info.ts index 5377e45ac6d..f4427d7a04c 100644 --- a/cocos/scene-graph/prefab/prefab-info.ts +++ b/cocos/scene-graph/prefab/prefab-info.ts @@ -30,7 +30,7 @@ import { CCObject, CCString } from '../../core/data'; import { Component } from '../component'; import { Node } from '../node'; -function compareStringArray (array1: string[] | undefined, array2: string[] | undefined) { +function compareStringArray (array1: string[] | undefined, array2: string[] | undefined): boolean { if (!array1 || !array2) { return false; } @@ -90,7 +90,7 @@ export class PropertyOverrideInfo { public value: any; // eslint-disable-next-line consistent-return - public isTarget (localID: string[], propPath: string[]) { + public isTarget (localID: string[], propPath: string[]): boolean | undefined { if (EDITOR) { return compareStringArray(this.targetInfo?.localID, localID) && compareStringArray(this.propertyPath, propPath); @@ -108,7 +108,7 @@ export class MountedChildrenInfo { public nodes: Node[] = []; // eslint-disable-next-line consistent-return - public isTarget (localID: string[]) { + public isTarget (localID: string[]): boolean | undefined { if (EDITOR) { return compareStringArray(this.targetInfo?.localID, localID); } @@ -125,7 +125,7 @@ export class MountedComponentsInfo { public components: Component[] = []; // eslint-disable-next-line consistent-return - public isTarget (localID: string[]) { + public isTarget (localID: string[]): boolean | undefined { if (EDITOR) { return compareStringArray(this.targetInfo?.localID, localID); } @@ -176,7 +176,7 @@ export class PrefabInstance { public expanded = false; // eslint-disable-next-line consistent-return - public findPropertyOverride (localID: string[], propPath: string[]) { + public findPropertyOverride (localID: string[], propPath: string[]): Prefab._utils.PropertyOverrideInfo | null | undefined { if (EDITOR) { for (let i = 0; i < this.propertyOverrides.length; i++) { const propertyOverride = this.propertyOverrides[i]; @@ -188,7 +188,7 @@ export class PrefabInstance { } } - public removePropertyOverride (localID: string[], propPath: string[]) { + public removePropertyOverride (localID: string[], propPath: string[]): void { if (EDITOR) { for (let i = 0; i < this.propertyOverrides.length; i++) { const propertyOverride = this.propertyOverrides[i]; diff --git a/cocos/scene-graph/prefab/prefab.ts b/cocos/scene-graph/prefab/prefab.ts index 60baecd8040..05773443275 100644 --- a/cocos/scene-graph/prefab/prefab.ts +++ b/cocos/scene-graph/prefab/prefab.ts @@ -147,7 +147,7 @@ export class Prefab extends Asset { /** * @engineInternal */ - public _doInstantiate (rootToRedirect?: any) { + public _doInstantiate (rootToRedirect?: any): Node { if (!this.data._prefab) { // temp guard code warnID(3700); @@ -185,7 +185,7 @@ export class Prefab extends Asset { return node; } - public initDefault (uuid?: string) { + public initDefault (uuid?: string): void { super.initDefault(uuid); this.data = new Node(); this.data.name = '(Missing Node)'; @@ -195,11 +195,11 @@ export class Prefab extends Asset { this.data._prefab = prefabInfo; } - public validate () { + public validate (): boolean { return !!this.data; } - public onLoaded () { + public onLoaded (): void { const rootNode = this.data as Node; utils.expandNestedPrefabInstanceNode(rootNode); utils.applyTargetOverrides(rootNode); diff --git a/cocos/scene-graph/prefab/utils.ts b/cocos/scene-graph/prefab/utils.ts index 1099c68ac93..8e59d819bab 100644 --- a/cocos/scene-graph/prefab/utils.ts +++ b/cocos/scene-graph/prefab/utils.ts @@ -32,7 +32,7 @@ import { ValueType } from '../../core/value-types'; export * from './prefab-info'; -export function createNodeWithPrefab (node: Node) { +export function createNodeWithPrefab (node: Node): void { // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 const prefabInfo = (node as any)._prefab; @@ -99,7 +99,7 @@ export function createNodeWithPrefab (node: Node) { } // TODO: more efficient id->Node/Component map -export function generateTargetMap (node: Node, targetMap: any, isRoot: boolean) { +export function generateTargetMap (node: Node, targetMap: any, isRoot: boolean): void { if (!targetMap) { return; } @@ -139,7 +139,7 @@ export function generateTargetMap (node: Node, targetMap: any, isRoot: boolean) } } -export function getTarget (localID: string[], targetMap: any) { +export function getTarget (localID: string[], targetMap: any): Node | Component | null { if (!localID) { return null; } @@ -158,7 +158,7 @@ export function getTarget (localID: string[], targetMap: any) { return target; } -export function applyMountedChildren (node: Node, mountedChildren: MountedChildrenInfo[], targetMap: Record) { +export function applyMountedChildren (node: Node, mountedChildren: MountedChildrenInfo[], targetMap: Record): void { if (!mountedChildren) { return; } @@ -205,7 +205,7 @@ export function applyMountedChildren (node: Node, mountedChildren: MountedChildr } } -export function applyMountedComponents (node: Node, mountedComponents: MountedComponentsInfo[], targetMap: Record) { +export function applyMountedComponents (node: Node, mountedComponents: MountedComponentsInfo[], targetMap: Record): void { if (!mountedComponents) { return; } @@ -240,7 +240,7 @@ export function applyMountedComponents (node: Node, mountedComponents: MountedCo } } -export function applyRemovedComponents (node: Node, removedComponents: TargetInfo[], targetMap: Record) { +export function applyRemovedComponents (node: Node, removedComponents: TargetInfo[], targetMap: Record): void { if (!removedComponents) { return; } @@ -261,7 +261,7 @@ export function applyRemovedComponents (node: Node, removedComponents: TargetInf } } -export function applyPropertyOverrides (node: Node, propertyOverrides: PropertyOverrideInfo[], targetMap: Record) { +export function applyPropertyOverrides (node: Node, propertyOverrides: PropertyOverrideInfo[], targetMap: Record): void { if (propertyOverrides.length <= 0) { return; } @@ -319,7 +319,7 @@ export function applyPropertyOverrides (node: Node, propertyOverrides: PropertyO } } -export function applyTargetOverrides (node: Node) { +export function applyTargetOverrides (node: Node): void { // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 const targetOverrides = (node as any)._prefab?.targetOverrides; @@ -384,7 +384,7 @@ export function applyTargetOverrides (node: Node) { } } -export function expandPrefabInstanceNode (node: Node, recursively = false) { +export function expandPrefabInstanceNode (node: Node, recursively = false): void { // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 const prefabInfo = (node as any)._prefab; @@ -417,7 +417,7 @@ export function expandPrefabInstanceNode (node: Node, recursively = false) { } } -export function expandNestedPrefabInstanceNode (node: Node) { +export function expandNestedPrefabInstanceNode (node: Node): void { // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 const prefabInfo = (node as any)._prefab; @@ -434,7 +434,7 @@ export function expandNestedPrefabInstanceNode (node: Node) { } // make sure prefab instance's children id is fixed -export function applyNodeAndComponentId (prefabInstanceNode: Node, rootId: string) { +export function applyNodeAndComponentId (prefabInstanceNode: Node, rootId: string): void { const { components, children } = prefabInstanceNode; for (let i = 0; i < components.length; i++) { const comp = components[i]; diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index 635d5f77179..f063f3bc40a 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -53,7 +53,7 @@ const _col = new Color(); const _qt = new Quat(); // Normalize HDR color -const normalizeHDRColor = (color: Vec4) => { +const normalizeHDRColor = (color: Vec4): void => { const intensity = 1.0 / Math.max(Math.max(Math.max(color.x, color.y), color.z), 0.0001); if (intensity < 1.0) { color.x *= intensity; @@ -87,7 +87,7 @@ export class AmbientInfo { * @en Sky illuminance in HDR mode * @zh HDR 模式下的天空亮度 */ - get skyIllumHDR () { + get skyIllumHDR (): number { return this._skyIllumHDR; } @@ -111,7 +111,7 @@ export class AmbientInfo { * @en Sky illuminance in LDR mode * @zh LDR 模式下的天空亮度 */ - get skyIllumLDR () { + get skyIllumLDR (): number { return this._skyIllumLDR; } @@ -139,7 +139,7 @@ export class AmbientInfo { } if (this._resource) { this._resource.skyColor.set(_v4); } } - get skyLightingColor () { + get skyLightingColor (): Color { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; _v4.set(isHDR ? this._skyColorHDR : this._skyColorLDR); normalizeHDRColor(_v4); @@ -174,7 +174,7 @@ export class AmbientInfo { if (this._resource) { this._resource.skyIllum = val; } } - get skyIllum () { + get skyIllum (): number { if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { return this._skyIllumHDR; } else { @@ -206,7 +206,7 @@ export class AmbientInfo { } if (this._resource) { this._resource.groundAlbedo.set(_v4); } } - get groundLightingColor () { + get groundLightingColor (): Color { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; _v4.set(isHDR ? this._groundAlbedoHDR : this._groundAlbedoLDR); normalizeHDRColor(_v4); @@ -249,7 +249,7 @@ export class AmbientInfo { * @zh 在渲染场景中启用环境光照设置,不需要手动调用 * @param resource The ambient configuration object in the render scene */ - public activate (resource: Ambient) { + public activate (resource: Ambient): void { this._resource = resource; this._resource.initialize(this); } @@ -271,7 +271,7 @@ export class SkyboxInfo { this._resource.useDiffuseMap = val; } } - get applyDiffuseMap () { + get applyDiffuseMap (): boolean { if (EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION === this._envLightingType) { return true; } @@ -291,7 +291,7 @@ export class SkyboxInfo { this._resource.enabled = this._enabled; } } - get enabled () { + get enabled (): boolean { return this._enabled; } @@ -322,7 +322,7 @@ export class SkyboxInfo { this._envLightingType = val; } } - get envLightingType () { + get envLightingType (): number { return this._envLightingType; } /** @@ -334,7 +334,7 @@ export class SkyboxInfo { this._resource.useIBL = val; } } - get useIBL () { + get useIBL (): boolean { if (EnvironmentLightingType.HEMISPHERE_DIFFUSE !== this._envLightingType) { return true; } @@ -368,7 +368,7 @@ export class SkyboxInfo { this._resource.updateMaterialRenderInfo(); } } - get useHDR () { + get useHDR (): boolean { (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR = this._useHDR; return this._useHDR; } @@ -409,7 +409,7 @@ export class SkyboxInfo { this._resource.envmap = val; } } - get envmap () { + get envmap (): TextureCube | null { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._envmapHDR; @@ -430,7 +430,7 @@ export class SkyboxInfo { this._rotationAngle = val; if (this._resource) { this._resource.setRotationAngle(this._rotationAngle); } } - get rotationAngle () { + get rotationAngle (): number { return this._rotationAngle; } @@ -438,7 +438,7 @@ export class SkyboxInfo { * @en The optional diffusion convolution map used in tandem with IBL * @zh 使用的漫反射卷积图 */ - @visible(function (this: SkyboxInfo) { + @visible(function (this: SkyboxInfo): boolean { if (this.useIBL && this.applyDiffuseMap) { return true; } @@ -460,7 +460,7 @@ export class SkyboxInfo { this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); } } - get diffuseMap () { + get diffuseMap (): TextureCube | null { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._diffuseMapHDR; @@ -494,7 +494,7 @@ export class SkyboxInfo { this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); } } - get reflectionMap () { + get reflectionMap (): TextureCube | null { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._reflectionHDR; @@ -516,7 +516,7 @@ export class SkyboxInfo { this._resource.setSkyboxMaterial(this._editableMaterial); } } - get skyboxMaterial () { + get skyboxMaterial (): Material | null { return this._editableMaterial; } @@ -558,7 +558,7 @@ export class SkyboxInfo { * @zh 在渲染场景中启用天空盒设置,不需要手动调用 * @param resource The skybox configuration object in the render scene */ - public activate (resource: Skybox) { + public activate (resource: Skybox): void { this.envLightingType = this._envLightingType; this._resource = resource; this._resource.initialize(this); @@ -575,7 +575,7 @@ export class SkyboxInfo { * @zh 环境贴图发生变化时,会调用此函数更新场景。 * @param val environment map */ - public updateEnvMap (val: TextureCube) { + public updateEnvMap (val: TextureCube): void { if (!val) { this.applyDiffuseMap = false; this.useIBL = false; @@ -602,7 +602,7 @@ export class SkyboxInfo { * @en The pass to apply to. Will apply to all passes if not specified. * @zh 设置此属性的 pass 索引,如果没有指定,则会设置此属性到所有 pass 上。 */ - public setMaterialProperty (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number) { + public setMaterialProperty (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number): void { if (!this._resource) return; if (this._resource.enabled && this._resource.editableMaterial) { this._resource.editableMaterial.setProperty(name, val, passIdx); @@ -640,7 +640,7 @@ export class FogInfo { } } - get enabled () { + get enabled (): boolean { return this._enabled; } @@ -662,7 +662,7 @@ export class FogInfo { } } - get accurate () { + get accurate (): boolean { return this._accurate; } @@ -689,7 +689,7 @@ export class FogInfo { @type(FogType) @displayOrder(1) @tooltip('i18n:fog.type') - get type () { + get type (): number { return this._type; } @@ -709,7 +709,7 @@ export class FogInfo { @range([0, 1, 0.01]) @slide @tooltip('i18n:fog.fogDensity') - get fogDensity () { + get fogDensity (): number { return this._fogDensity; } @@ -726,7 +726,7 @@ export class FogInfo { @type(CCFloat) @rangeStep(0.01) @tooltip('i18n:fog.fogStart') - get fogStart () { + get fogStart (): number { return this._fogStart; } @@ -743,7 +743,7 @@ export class FogInfo { @type(CCFloat) @rangeStep(0.01) @tooltip('i18n:fog.fogEnd') - get fogEnd () { + get fogEnd (): number { return this._fogEnd; } @@ -761,7 +761,7 @@ export class FogInfo { @rangeMin(0.01) @rangeStep(0.01) @tooltip('i18n:fog.fogAtten') - get fogAtten () { + get fogAtten (): number { return this._fogAtten; } @@ -778,7 +778,7 @@ export class FogInfo { @type(CCFloat) @rangeStep(0.01) @tooltip('i18n:fog.fogTop') - get fogTop () { + get fogTop (): number { return this._fogTop; } @@ -795,7 +795,7 @@ export class FogInfo { @type(CCFloat) @rangeStep(0.01) @tooltip('i18n:fog.fogRange') - get fogRange () { + get fogRange (): number { return this._fogRange; } @@ -831,7 +831,7 @@ export class FogInfo { * @zh 在渲染场景中启用雾效设置,不需要手动调用 * @param resource The fog configuration object in the render scene */ - public activate (resource: Fog) { + public activate (resource: Fog): void { this._resource = resource; this._resource.initialize(this); this._resource.activate(); @@ -860,7 +860,7 @@ export class ShadowsInfo { } } } - get enabled () { + get enabled (): boolean { if (BAIDU) { if (this._type !== ShadowType.Planar) { this._enabled = false; @@ -880,7 +880,7 @@ export class ShadowsInfo { this._type = val; if (this._resource) { this._resource.type = val; } } - get type () { + get type (): number { return this._type; } @@ -924,7 +924,7 @@ export class ShadowsInfo { this._distance = val; if (this._resource) { this._resource.distance = val; } } - get planeHeight () { + get planeHeight (): number { return this._distance; } @@ -939,7 +939,7 @@ export class ShadowsInfo { this._maxReceived = val; if (this._resource) { this._resource.maxReceived = val; } } - get maxReceived () { + get maxReceived (): number { return this._maxReceived; } @@ -957,7 +957,7 @@ export class ShadowsInfo { this._resource.shadowMapDirty = true; } } - get shadowMapSize () { + get shadowMapSize (): number { return this._size.x; } @@ -983,7 +983,7 @@ export class ShadowsInfo { * @zh 根据指定节点的世界变换设置阴影接收平面的信息 * @param node The node for setting up the plane */ - public setPlaneFromNode (node: Node) { + public setPlaneFromNode (node: Node): void { node.getWorldRotation(_qt); this.planeDirection = Vec3.transformQuat(_v3, _up, _qt); node.getWorldPosition(_v3); @@ -995,7 +995,7 @@ export class ShadowsInfo { * @zh 在渲染场景中启用阴影设置,不需要手动调用 * @param resource The shadow configuration object in the render scene */ - public activate (resource: Shadows) { + public activate (resource: Shadows): void { this._resource = resource; this._resource.initialize(this); this._resource.activate(); @@ -1026,7 +1026,7 @@ export class OctreeInfo { this._resource.enabled = val; } } - get enabled () { + get enabled (): boolean { return this._enabled; } @@ -1042,7 +1042,7 @@ export class OctreeInfo { this._minPos = val; if (this._resource) { this._resource.minPos = val; } } - get minPos () { + get minPos (): Vec3 { return this._minPos; } @@ -1058,7 +1058,7 @@ export class OctreeInfo { this._maxPos = val; if (this._resource) { this._resource.maxPos = val; } } - get maxPos () { + get maxPos (): Vec3 { return this._maxPos; } @@ -1075,7 +1075,7 @@ export class OctreeInfo { this._depth = val; if (this._resource) { this._resource.depth = val; } } - get depth () { + get depth (): number { return this._depth; } @@ -1095,7 +1095,7 @@ export class OctreeInfo { * @zh 在渲染场景中启用八叉树设置,不需要手动调用 * @param resource The octree configuration object in the render scene */ - public activate (resource: Octree) { + public activate (resource: Octree): void { this._resource = resource; this._resource.initialize(this); } @@ -1122,7 +1122,7 @@ export class SkinInfo { this._resource.enabled = val; } } - get enabled () { + get enabled (): boolean { return this._enabled; } @@ -1140,7 +1140,7 @@ export class SkinInfo { this._blurRadius = val; if (this._resource) { this._resource.blurRadius = val; } } - get blurRadius () { + get blurRadius (): number { return this._blurRadius; } @@ -1157,7 +1157,7 @@ export class SkinInfo { this._sssIntensity = val; if (this._resource) { this._resource.sssIntensity = val; } } - get sssIntensity () { + get sssIntensity (): number { return this._sssIntensity; } @@ -1175,7 +1175,7 @@ export class SkinInfo { * @zh 在渲染场景中启用皮肤设置,不需要手动调用 * @param resource The skin configuration object in the render scene */ - public activate (resource: Skin) { + public activate (resource: Skin): void { this._resource = resource; this._resource.initialize(this); } @@ -1380,22 +1380,22 @@ export class LightProbeInfo { protected _scene: Scene | null = null; protected _resource: LightProbes | null = null; - public activate (scene: Scene, resource: LightProbes) { + public activate (scene: Scene, resource: LightProbes): void { this._scene = scene; this._resource = resource; this._resource.initialize(this); } - public onProbeBakeFinished () { + public onProbeBakeFinished (): void { this.onProbeBakingChanged(this._scene); } - public onProbeBakeCleared () { + public onProbeBakeCleared (): void { this.clearSHCoefficients(); this.onProbeBakingChanged(this._scene); } - private onProbeBakingChanged (node: Node | null) { + private onProbeBakingChanged (node: Node | null): void { if (!node) { return; } @@ -1408,7 +1408,7 @@ export class LightProbeInfo { } } - public clearSHCoefficients () { + public clearSHCoefficients (): void { if (!this._data) { return; } @@ -1456,7 +1456,7 @@ export class LightProbeInfo { return true; } - public syncData (node: Node, probes: Vec3[]) { + public syncData (node: Node, probes: Vec3[]): void { for (let i = 0; i < this._nodes.length; i++) { if (this._nodes[i].node === node) { this._nodes[i].probes = probes; @@ -1465,7 +1465,7 @@ export class LightProbeInfo { } } - public update (updateTet = true) { + public update (updateTet = true): void { if (!cclegacy.internal.LightProbesData) { return; } @@ -1509,7 +1509,7 @@ export class LightProbeInfo { } } - private clearAllSHUBOs () { + private clearAllSHUBOs (): void { if (!this._scene) { return; } @@ -1525,7 +1525,7 @@ export class LightProbeInfo { } } - private resetAllTetraIndices () { + private resetAllTetraIndices (): void { if (!this._scene) { return; } @@ -1581,7 +1581,7 @@ export class SceneGlobals { */ @editable @type(SkyboxInfo) - get skybox () { + get skybox (): SkyboxInfo { return this._skybox; } set skybox (value) { @@ -1638,7 +1638,7 @@ export class SceneGlobals { * @en Activate and initialize the global configurations of the scene, no need to invoke manually. * @zh 启用和初始化场景全局配置,不需要手动调用 */ - public activate (scene: Scene) { + public activate (scene: Scene): void { const sceneData = (legacyCC.director.root as Root).pipeline.pipelineSceneData; this.skybox.activate(sceneData.skybox); this.ambient.activate(sceneData.ambient); diff --git a/cocos/scene-graph/scene.ts b/cocos/scene-graph/scene.ts index b03a6e6930e..9afac73b272 100644 --- a/cocos/scene-graph/scene.ts +++ b/cocos/scene-graph/scene.ts @@ -47,12 +47,12 @@ export class Scene extends Node { * @en The renderer scene, normally user don't need to use it * @zh 渲染层场景,一般情况下用户不需要关心它 */ - get renderScene () { + get renderScene (): RenderScene | null { return this._renderScene; } @editable - get globals () { + get globals (): SceneGlobals { return this._globals; } @@ -81,7 +81,7 @@ export class Scene extends Node { protected _prefabSyncedInLiveReload = false; - protected _updateScene () { + protected _updateScene (): void { this._scene = this; } @@ -98,7 +98,7 @@ export class Scene extends Node { * @en Destroy the current scene and all its nodes, this action won't destroy related assets * @zh 销毁当前场景中的所有节点,这个操作不会销毁资源 */ - public destroy () { + public destroy (): boolean { const success = CCObject.prototype.destroy.call(this); if (success) { const children = this._children; @@ -129,19 +129,19 @@ export class Scene extends Node { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onHierarchyChanged () { } + public _onHierarchyChanged (): void { } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onPostActivated (active: boolean) { + public _onPostActivated (active: boolean): void { } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBatchCreated (dontSyncChildPrefab: boolean) { + public _onBatchCreated (dontSyncChildPrefab: boolean): void { const len = this._children.length; for (let i = 0; i < len; ++i) { this._children[i]._siblingIndex = i; @@ -155,16 +155,16 @@ export class Scene extends Node { * @zh * 参考 [[Node.updateWorldTransform]] */ - public updateWorldTransform () {} + public updateWorldTransform (): void {} // life-cycle call backs - protected _instantiate () { } + protected _instantiate (): void { } /** * @engineInternal */ - public _load () { + public _load (): void { if (!this._inited) { if (TEST) { assert(!this._activeInHierarchy, 'Should deactivate ActionManager by default'); @@ -182,7 +182,7 @@ export class Scene extends Node { /** * @engineInternal */ - public _activate (active = true) { + public _activate (active = true): void { if (EDITOR) { // register all nodes to editor // TODO: `_registerIfAttached` is injected property diff --git a/cocos/serialization/ccon.ts b/cocos/serialization/ccon.ts index a284dc0a396..735161c99a4 100644 --- a/cocos/serialization/ccon.ts +++ b/cocos/serialization/ccon.ts @@ -36,11 +36,11 @@ export class CCON { this._chunks = chunks; } - get document () { + get document (): unknown { return this._document; } - get chunks () { + get chunks (): Uint8Array[] { return this._chunks; } @@ -54,7 +54,7 @@ interface CCONPreface { chunks: string[]; } -export function encodeCCONJson (ccon: CCON, chunkURLs: string[]) { +export function encodeCCONJson (ccon: CCON, chunkURLs: string[]): unknown { return { version: VERSION, document: ccon.document, @@ -62,7 +62,10 @@ export function encodeCCONJson (ccon: CCON, chunkURLs: string[]) { } as unknown; } -export function parseCCONJson (json: unknown) { +export function parseCCONJson (json: unknown): { + chunks: string[]; + document: unknown; +} { const cconPreface = json as CCONPreface; return { @@ -71,7 +74,7 @@ export function parseCCONJson (json: unknown) { }; } -export function encodeCCONBinary (ccon: CCON) { +export function encodeCCONBinary (ccon: CCON): Uint8Array { const { document, chunks } = ccon; const jsonString = JSON.stringify(document); @@ -105,7 +108,7 @@ export function encodeCCONBinary (ccon: CCON) { } } -export function decodeCCONBinary (bytes: Uint8Array) { +export function decodeCCONBinary (bytes: Uint8Array): CCON { if (bytes.length < 16) { throw new InvalidCCONError(getError(13102)); } @@ -180,7 +183,7 @@ interface BufferConstructor { from(buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): Buffer; } -function encodeJson (input: string) { +function encodeJson (input: string): Uint8Array { if (typeof TextEncoder !== 'undefined') { return new TextEncoder().encode(input); } else if ('Buffer' in globalThis) { @@ -196,7 +199,7 @@ function encodeJson (input: string) { } } -function decodeJson (data: Uint8Array) { +function decodeJson (data: Uint8Array): string { if (typeof TextDecoder !== 'undefined') { return new TextDecoder().decode(data); } else if ('Buffer' in globalThis) { @@ -214,11 +217,11 @@ export class BufferBuilder { private _viewOrPaddings: (ArrayBufferView | number)[] = []; private _length = 0; - get byteLength () { + get byteLength (): number { return this._length; } - public alignAs (align: number) { + public alignAs (align: number): number { if (align !== 0) { const remainder = this._length % align; if (remainder !== 0) { @@ -231,14 +234,14 @@ export class BufferBuilder { return 0; } - public append (view: ArrayBufferView) { + public append (view: ArrayBufferView): number { const result = this._length; this._viewOrPaddings.push(view); this._length += view.byteLength; return result; } - public get () { + public get (): Uint8Array { const result = new Uint8Array(this._length); let counter = 0; this._viewOrPaddings.forEach((viewOrPadding) => { diff --git a/cocos/serialization/deserialize-dynamic.ts b/cocos/serialization/deserialize-dynamic.ts index 64cfbe46c12..19e1aeb5769 100644 --- a/cocos/serialization/deserialize-dynamic.ts +++ b/cocos/serialization/deserialize-dynamic.ts @@ -38,7 +38,7 @@ function compileObjectTypeJit ( accessorToSet: string, propNameLiteralToSet: string, assumeHavePropIfIsValue: boolean, -) { +): void { if (defaultValue instanceof cclegacy.ValueType) { // fast case if (!assumeHavePropIfIsValue) { @@ -191,7 +191,7 @@ function compileDeserializeNative (_self: _Deserializer, klass: CCClassConstruct let advancedPropsToRead = advancedProps; const advancedPropsValueType: any = []; - (() => { + ((): void => { const props: string[] = klass.__values__; shouldCopyRawData = props[props.length - 1] === '_$erialized'; @@ -238,7 +238,7 @@ function compileDeserializeNative (_self: _Deserializer, klass: CCClassConstruct } })(); - return (s, o, d, k) => { + return (s, o, d, k): void => { for (let i = 0; i < simpleProps.length; ++i) { const prop = d[simplePropsToRead[i]]; if (prop !== undefined) { @@ -362,7 +362,7 @@ class DeserializerPool extends js.Pool<_Deserializer> { reportMissingClass: ReportMissingClass, customEnv: unknown, ignoreEditorOnly: boolean | undefined, -) { +): _Deserializer { const cache = this._get(); if (cache) { cache.reset(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly); @@ -385,7 +385,7 @@ class _Deserializer { /** * @engineInternal */ - public get ignoreEditorOnly () { return this._ignoreEditorOnly; } + public get ignoreEditorOnly (): unknown { return this._ignoreEditorOnly; } private _ignoreEditorOnly: unknown; private declare _mainBinChunk: Uint8Array; private declare _serializedData: SerializedObject | SerializedObject[]; @@ -404,7 +404,7 @@ class _Deserializer { } } - public reset (result: Details, classFinder: ClassFinder, reportMissingClass: ReportMissingClass, customEnv: unknown, ignoreEditorOnly: unknown) { + public reset (result: Details, classFinder: ClassFinder, reportMissingClass: ReportMissingClass, customEnv: unknown, ignoreEditorOnly: unknown): void { this.result = result; this.customEnv = customEnv; this._classFinder = classFinder; @@ -415,7 +415,7 @@ class _Deserializer { } } - public clear () { + public clear (): void { this.result = null!; this.customEnv = null; this.deserializedList.length = 0; @@ -425,7 +425,7 @@ class _Deserializer { this._onDereferenced = null!; } - public deserialize (serializedData: SerializedData | CCON) { + public deserialize (serializedData: SerializedData | CCON): any { let fromCCON = false; let jsonObj: SerializedData; if (serializedData instanceof CCON) { @@ -471,7 +471,7 @@ class _Deserializer { globalIndex: number, owner?: Record | unknown[], propName?: string, - ) { + ): Record | null { switch (serialized.__type__) { case 'TypedArray': return this._deserializeTypedArrayView(serialized); @@ -489,11 +489,11 @@ class _Deserializer { } } - private _deserializeTypedArrayView (value: SerializedTypedArray) { + private _deserializeTypedArrayView (value: SerializedTypedArray): Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array { return globalThis[value.ctor].from(value.array); } - private _deserializeTypedArrayViewRef (value: SerializedTypedArrayRef) { + private _deserializeTypedArrayViewRef (value: SerializedTypedArrayRef): Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array { const { offset, length, ctor: constructorName } = value; const obj = new globalThis[constructorName]( this._mainBinChunk.buffer, @@ -503,7 +503,7 @@ class _Deserializer { return obj; } - private _deserializeArray (value: SerializedValue[]) { + private _deserializeArray (value: SerializedValue[]): unknown[] { const obj = new Array(value.length); let prop: unknown; for (let i = 0; i < value.length; i++) { @@ -521,7 +521,7 @@ class _Deserializer { return obj; } - private _deserializePlainObject (value: Record) { + private _deserializePlainObject (value: Record): Record { const obj = {}; this._fillPlainObject(obj, value); return obj; @@ -532,7 +532,7 @@ class _Deserializer { globalIndex: number, owner?: Record | unknown[], propName?: string, - ) { + ): Record | null { const type = value.__type__ as unknown as string; const klass = this._classFinder(type, value, owner, propName); @@ -544,7 +544,7 @@ class _Deserializer { return null; } - const createObject = (constructor: deserialize.SerializableClassConstructor) => { + const createObject = (constructor: deserialize.SerializableClassConstructor): Record => { // eslint-disable-next-line new-cap const obj = new constructor() as Record; if (globalIndex >= 0) { @@ -578,7 +578,7 @@ class _Deserializer { object: Record, constructor: deserialize.SerializableClassConstructor, skipCustomized = false, - ) { + ): void { if (!skipCustomized && (object as Partial)[deserializeTag]) { this._runCustomizedDeserialize( value, @@ -608,7 +608,7 @@ class _Deserializer { value: SerializedGeneralTypedObject, object: Record & CustomSerializable, constructor: deserialize.SerializableClassConstructor, - ) { + ): void { const serializationInput: SerializationInput = { readProperty: (name: string) => { const serializedField = value[name]; @@ -634,7 +634,7 @@ class _Deserializer { object[deserializeTag]!(serializationInput, this._context); } - private _deserializeFireClass (obj: Record, serialized: SerializedGeneralTypedObject, klass: CCClassConstructor) { + private _deserializeFireClass (obj: Record, serialized: SerializedGeneralTypedObject, klass: CCClassConstructor): void { let deserialize: CompiledDeserializeFn; // eslint-disable-next-line no-prototype-builtins if (klass.hasOwnProperty('__deserialize__')) { @@ -656,7 +656,7 @@ class _Deserializer { deserialize = function (deserializer: _Deserializer, object: Record, deserialized: Record, - constructor: AnyFunction) { + constructor: AnyFunction): void { rawDeserialize(deserializer, object, deserialized, constructor); if (!object._$erialized) { error(`Unable to stash previously serialized data. ${JSON.stringify(deserialized)}`); @@ -679,7 +679,7 @@ class _Deserializer { obj: Record | unknown[], serializedField: SerializedFieldObjectValue, propName: string, - ) { + ): boolean { const id = (serializedField as Partial).__id__; if (typeof id === 'number') { const field = this.deserializedList[id]; @@ -709,7 +709,7 @@ class _Deserializer { return false; } - private _deserializeObjectField (serializedField: SerializedFieldObjectValue) { + private _deserializeObjectField (serializedField: SerializedFieldObjectValue): Record | null { const id = (serializedField as Partial).__id__; if (typeof id === 'number') { const field = this.deserializedList[id]; @@ -735,7 +735,7 @@ class _Deserializer { /** * @engineInternal */ - public _fillPlainObject (instance: Record, serialized: Record) { + public _fillPlainObject (instance: Record, serialized: Record): void { for (const propName in serialized) { // eslint-disable-next-line no-prototype-builtins if (!serialized.hasOwnProperty(propName)) { @@ -765,7 +765,7 @@ class _Deserializer { instance: Record, serialized: SerializedGeneralTypedObject, klass: SerializableClassConstructor, - ) { + ): void { if (klass === cclegacy.Vec2) { type SerializedVec2 = { x?: number; y?: number; }; instance.x = (serialized as SerializedVec2).x || 0; @@ -830,7 +830,7 @@ export function deserializeDynamic (data: SerializedData | CCON, details: Detail createAssetRefs?: boolean; customEnv?: unknown; reportMissingClass?: ReportMissingClass; -}) { +}): any { options = options || {}; const classFinder = options.classFinder || js.getClassById; const createAssetRefs = options.createAssetRefs || sys.platform === Platform.EDITOR_CORE; @@ -865,9 +865,9 @@ export function deserializeDynamic (data: SerializedData | CCON, details: Detail return res; } -export function parseUuidDependenciesDynamic (serialized: unknown) { +export function parseUuidDependenciesDynamic (serialized: unknown): never[] { const depends = []; - const parseDependRecursively = (data: any, out: string[]) => { + const parseDependRecursively = (data: any, out: string[]): void => { if (!data || typeof data !== 'object' || typeof data.__id__ === 'number') { return; } const uuid = data.__uuid__; if (Array.isArray(data)) { diff --git a/cocos/serialization/deserialize.ts b/cocos/serialization/deserialize.ts index 2edc27f2dfd..05b6c7723a9 100644 --- a/cocos/serialization/deserialize.ts +++ b/cocos/serialization/deserialize.ts @@ -56,38 +56,38 @@ const BuiltinValueTypes: (typeof ValueType)[] = [ ]; // Used for Data.ValueTypeCreated. -function BuiltinValueTypeParsers_xyzw (obj: Vec4 | Quat, data: number[]) { +function BuiltinValueTypeParsers_xyzw (obj: Vec4 | Quat, data: number[]): void { obj.x = data[1]; obj.y = data[2]; obj.z = data[3]; obj.w = data[4]; } const BuiltinValueTypeSetters: ((obj: any, data: number[]) => void)[] = [ - (obj: Vec2, data: number[]) => { + (obj: Vec2, data: number[]): void => { obj.x = data[1]; obj.y = data[2]; }, - (obj: Vec3, data: number[]) => { + (obj: Vec3, data: number[]): void => { obj.x = data[1]; obj.y = data[2]; obj.z = data[3]; }, BuiltinValueTypeParsers_xyzw, // Vec4 BuiltinValueTypeParsers_xyzw, // Quat - (obj: Color, data: number[]) => { + (obj: Color, data: number[]): void => { obj._val = data[1]; }, - (obj: Size, data: number[]) => { + (obj: Size, data: number[]): void => { obj.width = data[1]; obj.height = data[2]; }, - (obj: Rect, data: number[]) => { + (obj: Rect, data: number[]): void => { obj.x = data[1]; obj.y = data[2]; obj.width = data[3]; obj.height = data[4]; }, - (obj: Mat4, data: number[]) => { + (obj: Mat4, data: number[]): void => { Mat4.fromArray(obj, data, 1); }, ]; @@ -566,7 +566,7 @@ export class Details { * @method init * @param {Object} data */ - init (data?: IFileData) { + init (data?: IFileData): void { if (FORCE_COMPILED || data) { this.uuidObjList = data![File.DependObjs]; this.uuidPropList = data![File.DependKeys]; @@ -586,7 +586,7 @@ export class Details { /** * @method reset */ - reset () { + reset (): void { if (FORCE_COMPILED) { this.uuidList = null; this.uuidObjList = null; @@ -610,14 +610,14 @@ export class Details { * @param {String} uuid */ // eslint-disable-next-line @typescript-eslint/ban-types - push (obj: object, propName: string, uuid: string, type?: string) { + push (obj: object, propName: string, uuid: string, type?: string): void { this.uuidObjList!.push(obj); this.uuidPropList!.push(propName); this.uuidList!.push(uuid); this.uuidTypeList.push(type || ''); } } -Details.pool.get = function () { +Details.pool.get = function (): Details { return this._get() || new Details(); }; if (EDITOR || TEST) { @@ -625,7 +625,7 @@ if (EDITOR || TEST) { type: Constructor; owner: Record; prop: string; - }) => any) { + }) => any): void { for (let i = 0, len = this.uuidList!.length; i < len; i++) { const obj = this.uuidObjList![i] as Record; const prop = this.uuidPropList![i] as string; @@ -673,7 +673,7 @@ export function dereference (refs: IRefs, instances: IFileData[File.Instances], // -function deserializeCCObject (data: IFileData, objectData: IClassObjectData) { +function deserializeCCObject (data: IFileData, objectData: IClassObjectData): Record { const mask = data[File.SharedMasks][objectData[OBJ_DATA_MASK]]; const clazz = mask[MASK_CLASS]; const ctor = clazz[CLASS_TYPE] as Exclude; @@ -707,7 +707,7 @@ function deserializeCCObject (data: IFileData, objectData: IClassObjectData) { return obj; } -function deserializeCustomCCObject (data: IFileData, ctor: Ctor, value: ICustomObjectDataContent) { +function deserializeCustomCCObject (data: IFileData, ctor: Ctor, value: ICustomObjectDataContent): ICustomClass { // eslint-disable-next-line new-cap const obj = new ctor(); if (obj._deserialize) { @@ -722,11 +722,11 @@ function deserializeCustomCCObject (data: IFileData, ctor: Ctor, v type ParseFunction = (data: IFileData, owner: any, key: string, value: T) => void; -function assignSimple (data: IFileData, owner: any, key: string, value: DataTypes[DataTypeID.SimpleType]) { +function assignSimple (data: IFileData, owner: any, key: string, value: DataTypes[DataTypeID.SimpleType]): void { owner[key] = value; } -function assignInstanceRef (data: IFileData, owner: any, key: string, value: InstanceBnotReverseIndex) { +function assignInstanceRef (data: IFileData, owner: any, key: string, value: InstanceBnotReverseIndex): void { if (value >= 0) { owner[key] = data[File.Instances][value]; } else { @@ -735,7 +735,7 @@ function assignInstanceRef (data: IFileData, owner: any, key: string, value: Ins } function genArrayParser (parser: ParseFunction): ParseFunction { - return (data: IFileData, owner: any, key: string, value: T[]) => { + return (data: IFileData, owner: any, key: string, value: T[]): void => { for (let i = 0; i < value.length; ++i) { parser(data, value, i as unknown as string, value[i]); } @@ -743,21 +743,21 @@ function genArrayParser (parser: ParseFunction): ParseFunction { }; } -function parseAssetRefByInnerObj (data: IFileData, owner: any, key: string, value: number) { +function parseAssetRefByInnerObj (data: IFileData, owner: any, key: string, value: number): void { owner[key] = null; data[File.DependObjs][value] = owner; } -function parseClass (data: IFileData, owner: any, key: string, value: IClassObjectData) { +function parseClass (data: IFileData, owner: any, key: string, value: IClassObjectData): void { owner[key] = deserializeCCObject(data, value); } -function parseCustomClass (data: IFileData, owner: any, key: string, value: ICustomObjectData) { +function parseCustomClass (data: IFileData, owner: any, key: string, value: ICustomObjectData): void { const ctor = data[File.SharedClasses][value[CUSTOM_OBJ_DATA_CLASS]] as CCClassConstructor; owner[key] = deserializeCustomCCObject(data, ctor, value[CUSTOM_OBJ_DATA_CONTENT]); } -function parseValueTypeCreated (data: IFileData, owner: any, key: string, value: IValueTypeData) { +function parseValueTypeCreated (data: IFileData, owner: any, key: string, value: IValueTypeData): void { /**BuiltinValueTypes index: Vec2=0, Vec3=1, Vec4=2, Quat=3, Color=4, Size=5, Rect=6, Mat4=7 The native layer type corresponding to the BuiltinValueTypes has not been exported exclude Color, so we need to set to native after value changed @@ -771,18 +771,18 @@ function parseValueTypeCreated (data: IFileData, owner: any, key: string, value: } } -function parseValueType (data: IFileData, owner: any, key: string, value: IValueTypeData) { +function parseValueType (data: IFileData, owner: any, key: string, value: IValueTypeData): void { const val: ValueType = new BuiltinValueTypes[value[VALUETYPE_SETTER]](); BuiltinValueTypeSetters[value[VALUETYPE_SETTER]](val, value); owner[key] = val; } -function parseTRS (data: IFileData, owner: any, key: string, value: ITRSData) { +function parseTRS (data: IFileData, owner: any, key: string, value: ITRSData): void { const typedArray = owner[key] as (Float32Array | Float64Array); typedArray.set(value); } -function parseDict (data: IFileData, owner: any, key: string, value: IDictData) { +function parseDict (data: IFileData, owner: any, key: string, value: IDictData): void { const dict = value[DICT_JSON_LAYOUT]; owner[key] = dict; for (let i = DICT_JSON_LAYOUT + 1; i < value.length; i += 3) { @@ -794,7 +794,7 @@ function parseDict (data: IFileData, owner: any, key: string, value: IDictData) } } -function parseArray (data: IFileData, owner: any, key: string, value: IArrayData) { +function parseArray (data: IFileData, owner: any, key: string, value: IArrayData): void { const array = value[ARRAY_ITEM_VALUES]; for (let i = 0; i < array.length; ++i) { const subValue = array[i]; @@ -901,13 +901,13 @@ function parseInstances (data: IFileData): RootInstanceIndex { // } // } -function getMissingClass (hasCustomFinder, type, reportMissingClass: deserialize.ReportMissingClass) { +function getMissingClass (hasCustomFinder, type, reportMissingClass: deserialize.ReportMissingClass): ObjectConstructor { if (!hasCustomFinder) { reportMissingClass(type); } return Object; } -function doLookupClass (classFinder, type: string, container: any[], index: number, silent: boolean, hasCustomFinder, reportMissingClass: deserialize.ReportMissingClass) { +function doLookupClass (classFinder, type: string, container: any[], index: number, silent: boolean, hasCustomFinder, reportMissingClass: deserialize.ReportMissingClass): void { let klass = classFinder(type); if (!klass) { // if (klass.__FSA__) { @@ -915,7 +915,7 @@ function doLookupClass (classFinder, type: string, container: any[], index: numb // } if (silent) { // generate a lazy proxy for ctor - container[index] = ((c, i, t) => function proxy () { + container[index] = ((c, i, t) => function proxy (): any { const actualClass = classFinder(t) || getMissingClass(hasCustomFinder, t, reportMissingClass); c[i] = actualClass; // eslint-disable-next-line @typescript-eslint/no-unsafe-return, new-cap @@ -929,7 +929,7 @@ function doLookupClass (classFinder, type: string, container: any[], index: numb container[index] = klass; } -function lookupClasses (data: IPackedFileData, silent: boolean, customFinder: ClassFinder | undefined, reportMissingClass: deserialize.ReportMissingClass) { +function lookupClasses (data: IPackedFileData, silent: boolean, customFinder: ClassFinder | undefined, reportMissingClass: deserialize.ReportMissingClass): void { const classFinder = customFinder || js.getClassById; const classes = data[File.SharedClasses]; for (let i = 0; i < classes.length; ++i) { @@ -948,7 +948,7 @@ function lookupClasses (data: IPackedFileData, silent: boolean, customFinder: Cl } } -function cacheMasks (data: IPackedFileData) { +function cacheMasks (data: IPackedFileData): void { const masks = data[File.SharedMasks]; if (masks) { const classes = data[File.SharedClasses]; @@ -959,7 +959,7 @@ function cacheMasks (data: IPackedFileData) { } } -function parseResult (data: IFileData) { +function parseResult (data: IFileData): void { const instances = data[File.Instances]; const sharedStrings = data[File.SharedStrings]; const dependSharedUuids = data[File.SharedUuids]; @@ -1142,7 +1142,7 @@ function getDependUuidList (json: IFileData): string[] { return json[File.DependUuidIndices].map((index) => sharedUuids[index]); } -export function parseUuidDependencies (serialized: unknown) { +export function parseUuidDependencies (serialized: unknown): string[] { // eslint-disable-next-line @typescript-eslint/ban-types if (!DEV || isCompiledJson(serialized as object)) { return getDependUuidList(serialized as IFileData); diff --git a/cocos/serialization/instantiate-jit.ts b/cocos/serialization/instantiate-jit.ts index fd7f1f87462..e2edc54e7fb 100644 --- a/cocos/serialization/instantiate-jit.ts +++ b/cocos/serialization/instantiate-jit.ts @@ -59,7 +59,7 @@ class Declaration { this.expression = expression; } - public toString () { + public toString (): string { return `${VAR + this.varName}=${this.expression};`; } } @@ -68,7 +68,7 @@ class Declaration { // -> 'var b = a = x'; // ('a =', 'x') // -> 'a = x'; -function mergeDeclaration (statement, expression) { +function mergeDeclaration (statement, expression): any { if (expression instanceof Declaration) { return new Declaration(expression.varName, statement + expression.expression); } else { @@ -83,7 +83,7 @@ function mergeDeclaration (statement, expression) { // -> 'var b = a = x;' // ('a', 'x') // -> 'a = x;' -function writeAssignment (codeArray, statement, expression) { +function writeAssignment (codeArray, statement, expression): void { if (Array.isArray(expression)) { expression[0] = mergeDeclaration(statement, expression[0]); codeArray.push(expression); @@ -109,10 +109,10 @@ class Assignments { this._exps = []; this._targetExp = targetExpression; } - public append (key, expression) { + public append (key, expression): void { this._exps.push([key, expression]); } - public writeCode (codeArray) { + public writeCode (codeArray): void { let targetVar; if (this._exps.length > 1) { codeArray.push(`${LOCAL_TEMP_OBJ}=${this._targetExp};`); @@ -135,7 +135,7 @@ Assignments.pool = new js.Pool((obj: any) => { obj._targetExp = null; }, 1); // HACK: here we've changed the signature of get method -(Assignments.pool.get as any) = function (this: any, targetExpression) { +(Assignments.pool.get as any) = function (this: any, targetExpression): Assignments { const cache: any = this._get() || new Assignments(); cache._targetExp = targetExpression; return cache as Assignments; @@ -143,7 +143,7 @@ Assignments.pool = new js.Pool((obj: any) => { // HELPER FUNCTIONS -function getPropAccessor (key) { +function getPropAccessor (key): string { return IDENTIFIER_RE.test(key) ? (`.${key}`) : (`[${escapeForJS(key)}]`); } @@ -234,7 +234,7 @@ class Parser { this.objsToClear_iN$t.length = 0; } - public getFuncModule (func, usedInNew?) { + public getFuncModule (func, usedInNew?): any { const clsName = js.getClassName(func); if (clsName) { const cache = this.funcModuleCache[clsName]; @@ -267,7 +267,7 @@ class Parser { return res; } - public getObjRef (obj) { + public getObjRef (obj): string { let index = this.objs.indexOf(obj); if (index < 0) { index = this.objs.length; @@ -276,7 +276,7 @@ class Parser { return `O[${index}]`; } - public setValueType (codeArray, defaultValue, srcValue, targetExpression) { + public setValueType (codeArray, defaultValue, srcValue, targetExpression): void { // HACK: here we've changed the signature of get method. const assignments: any = (Assignments.pool.get as any)(targetExpression); let fastDefinedProps = defaultValue.constructor.__props__; @@ -296,7 +296,7 @@ class Parser { Assignments.pool.put(assignments); } - public enumerateCCClass (codeArray, obj, klass) { + public enumerateCCClass (codeArray, obj, klass): void { const props = klass.__values__; const attrs = CCClass.Attr.getClassAttrs(klass); for (let p = 0; p < props.length; p++) { @@ -319,7 +319,7 @@ class Parser { } } - public instantiateArray (value) { + public instantiateArray (value): Declaration[] | '[]' { if (value.length === 0) { return '[]'; } @@ -343,7 +343,7 @@ class Parser { return codeArray; } - public instantiateTypedArray (value) { + public instantiateTypedArray (value): string | Declaration[] { const type = value.constructor.name; if (value.length === 0) { return `new ${type}`; @@ -369,7 +369,7 @@ class Parser { return codeArray; } - public enumerateField (obj, key, value) { + public enumerateField (obj, key, value): any { if (typeof value === 'object' && value) { const _iN$t = value._iN$t; if (_iN$t) { @@ -408,14 +408,14 @@ class Parser { } } - public setObjProp (codeArray, obj, key, value) { + public setObjProp (codeArray, obj, key, value): void { const statement = `${LOCAL_OBJ + getPropAccessor(key)}=`; const expression = this.enumerateField(obj, key, value); writeAssignment(codeArray, statement, expression); } // codeArray - the source code array for this object - public enumerateObject (codeArray, obj) { + public enumerateObject (codeArray, obj): void { const klass = obj.constructor; if (isCCClassOrFastDefined(klass)) { this.enumerateCCClass(codeArray, obj, klass); @@ -437,7 +437,7 @@ class Parser { } } - public instantiateObj (obj) { + public instantiateObj (obj): any { if (obj instanceof cclegacy.ValueType) { return CCClass.getNewValueTypeCode(obj); } @@ -500,7 +500,7 @@ class Parser { } } -export function equalsToDefault (def: any, value: any) { +export function equalsToDefault (def: any, value: any): boolean { if (typeof def === 'function') { try { def = def(); @@ -528,7 +528,7 @@ export function equalsToDefault (def: any, value: any) { return false; } -export function compile (node) { +export function compile (node): any { const root = (node instanceof cclegacy.Node) && node; const parser = new Parser(node, root); return parser.result; diff --git a/cocos/serialization/instantiate.ts b/cocos/serialization/instantiate.ts index 24301dab898..e453eb2b6ef 100644 --- a/cocos/serialization/instantiate.ts +++ b/cocos/serialization/instantiate.ts @@ -75,7 +75,7 @@ export function instantiate (prefab: Prefab): Node; */ export function instantiate (original: T): T; -export function instantiate (original: any, internalForce?: boolean) { +export function instantiate (original: any, internalForce?: boolean): any { if (!internalForce) { if (DEV) { if (typeof original !== 'object' || Array.isArray(original)) { @@ -132,7 +132,7 @@ export function instantiate (original: any, internalForce?: boolean) { * @return {Object} * @private */ -function doInstantiate (obj, parent?) { +function doInstantiate (obj, parent?): any { if (DEV) { if (Array.isArray(obj)) { throw new TypeError(getError(6904)); @@ -167,7 +167,7 @@ function doInstantiate (obj, parent?) { // @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array. -function enumerateCCClass (klass, obj, clone, parent) { +function enumerateCCClass (klass, obj, clone, parent): void { const props = klass.__values__; for (let p = 0; p < props.length; p++) { @@ -187,7 +187,7 @@ function enumerateCCClass (klass, obj, clone, parent) { } } -function enumerateObject (obj, clone, parent) { +function enumerateObject (obj, clone, parent): void { // 目前使用“_iN$t”这个特殊字段来存实例化后的对象,这样做主要是为了防止循环引用 // 注意,为了避免循环引用,所有新创建的实例,必须在赋值前被设为源对象的_iN$t js.value(obj, '_iN$t', clone, true); @@ -226,7 +226,7 @@ function enumerateObject (obj, clone, parent) { * @param {Object|Array} obj - the original non-nil object, typeof must be 'object' * @return {Object|Array} - the original non-nil object, typeof must be 'object' */ -function instantiateObj (obj, parent) { +function instantiateObj (obj, parent): any { if (obj instanceof ValueType) { return obj.clone(); } diff --git a/cocos/serialization/report-missing-class.ts b/cocos/serialization/report-missing-class.ts index f561104290b..ae312fc1bee 100644 --- a/cocos/serialization/report-missing-class.ts +++ b/cocos/serialization/report-missing-class.ts @@ -29,7 +29,7 @@ import { errorID } from '../core'; * * @engineInternal */ -export function reportMissingClass (id: string) { +export function reportMissingClass (id: string): void { if (EDITOR && EditorExtends.UuidUtils.isUuid(id)) { id = EditorExtends.UuidUtils.decompressUuid(id); errorID(5301, id); diff --git a/cocos/sorting/sorting-layers.ts b/cocos/sorting/sorting-layers.ts index 8991011441d..62a580af912 100644 --- a/cocos/sorting/sorting-layers.ts +++ b/cocos/sorting/sorting-layers.ts @@ -145,7 +145,7 @@ export class SortingLayers { /** * @engineInternal */ - public static init () { + public static init (): void { let sortingLayers = settings.querySettings>(Settings.Category.ENGINE, 'sortingLayers'); if (!sortingLayers || sortingLayers.length === 0) { sortingLayers = this.getBuiltinLayers(); @@ -178,7 +178,7 @@ export class SortingLayers { /** * @engineInternal */ - public static setLayer (layer, layerName, layerIndex) { + public static setLayer (layer, layerName, layerIndex): void { this.nameMap.set(layer, layerName); this.indexMap.set(layer, layerIndex); } @@ -186,7 +186,7 @@ export class SortingLayers { /** * @engineInternal */ - private static resetState () { + private static resetState (): void { const oldItem = Object.keys(SortingLayers.Enum); for (let i = 0; i < oldItem.length; i++) { delete SortingLayers.Enum[SortingLayers.Enum[oldItem[i]]]; diff --git a/cocos/sorting/sorting.ts b/cocos/sorting/sorting.ts index 399f0837618..a6516221c71 100644 --- a/cocos/sorting/sorting.ts +++ b/cocos/sorting/sorting.ts @@ -50,7 +50,7 @@ export class Sorting extends Component { */ @editable @type(SortingLayers.Enum) - get sortingLayer () { + get sortingLayer (): number { return this._sortingLayer; } set sortingLayer (val) { @@ -64,7 +64,7 @@ export class Sorting extends Component { * @en Model Renderer's order within a sorting layer. In the default sorting rule, smaller values are rendered first. */ @range([MIN_INT16, MAX_INT16, 1]) - get sortingOrder () { + get sortingOrder (): number { return this._sortingOrder; } set sortingOrder (val) { @@ -80,7 +80,7 @@ export class Sorting extends Component { private _modelRenderer: ModelRenderer | null = null; - protected __preload () { + protected __preload (): void { this._modelRenderer = this.getComponent('cc.ModelRenderer') as ModelRenderer; if (!this._modelRenderer) { warnID(16301, this.node.name); @@ -88,7 +88,7 @@ export class Sorting extends Component { this._updateSortingPriority(); } - protected _updateSortingPriority () { + protected _updateSortingPriority (): void { const sortingLayerValue = SortingLayers.getLayerIndex(this._sortingLayer); const sortingPriority = SortingLayers.getSortingPriority(sortingLayerValue, this._sortingOrder); if (this._modelRenderer && this._modelRenderer.isValid) { diff --git a/cocos/spine/assembler/simple.ts b/cocos/spine/assembler/simple.ts index 34b843c1c6b..1d02a0d5fec 100644 --- a/cocos/spine/assembler/simple.ts +++ b/cocos/spine/assembler/simple.ts @@ -34,6 +34,7 @@ import { legacyCC } from '../../core/global-exports'; import { RenderData } from '../../2d/renderer/render-data'; import { director } from '../../game'; import spine from '../lib/spine-core.js'; +import type { MaterialInstance } from '../../render-scene'; let _accessor: StaticVBAccessor = null!; let _tintAccessor: StaticVBAccessor = null!; @@ -44,7 +45,7 @@ let _useTint = false; const _byteStrideOneColor = getAttributeStride(vfmtPosUvColor4B); const _byteStrideTwoColor = getAttributeStride(vfmtPosUvTwoColor4B); -function _getSlotMaterial (blendMode: number, comp: Skeleton) { +function _getSlotMaterial (blendMode: number, comp: Skeleton): MaterialInstance { let src: BlendFactor; let dst: BlendFactor; switch (blendMode) { @@ -114,7 +115,7 @@ export const simple: IAssembler = { }, }; -function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { +function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D): void { _useTint = comp.useTint || comp.isAnimationCached(); if (comp.isAnimationCached()) { cacheTraverse(comp); @@ -126,7 +127,7 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { accessor.getMeshBuffer(rd.chunk.bufferId).setDirty(); } -function realTimeTraverse (comp: Skeleton) { +function realTimeTraverse (comp: Skeleton): void { _premultipliedAlpha = comp.premultipliedAlpha; const floatStride = (_useTint ? _byteStrideTwoColor : _byteStrideOneColor) / Float32Array.BYTES_PER_ELEMENT; @@ -174,7 +175,7 @@ function realTimeTraverse (comp: Skeleton) { } } -function cacheTraverse (comp: Skeleton) { +function cacheTraverse (comp: Skeleton): void { _premultipliedAlpha = comp.premultipliedAlpha; comp.drawList.reset(); diff --git a/cocos/spine/attach-util.ts b/cocos/spine/attach-util.ts index aacfacdcc1f..ce14f687145 100644 --- a/cocos/spine/attach-util.ts +++ b/cocos/spine/attach-util.ts @@ -47,21 +47,21 @@ export class AttachUtil { this._skeletonComp = null; } - init (skeletonComp: Skeleton) { + init (skeletonComp: Skeleton): void { this._inited = true; this._skeleton = skeletonComp._skeleton; this._skeletonNode = skeletonComp.node; this._skeletonComp = skeletonComp; } - reset () { + reset (): void { this._inited = false; this._skeleton = null; this._skeletonNode = null; this._skeletonComp = null; } - _syncAttachedNode () { + _syncAttachedNode (): void { if (!this._inited) return; const socketNodes = this._skeletonComp!.socketNodes; @@ -77,7 +77,7 @@ export class AttachUtil { if (!boneInfos || boneInfos.length < 1) return; - const matrixHandle = (node: Node, bone: any) => { + const matrixHandle = (node: Node, bone: any): void => { const tm = tempMat4; tm.m00 = bone.a; tm.m01 = bone.c; diff --git a/cocos/spine/lib/instantiated.ts b/cocos/spine/lib/instantiated.ts index 4c215cff725..71e4d648369 100644 --- a/cocos/spine/lib/instantiated.ts +++ b/cocos/spine/lib/instantiated.ts @@ -43,7 +43,7 @@ const MEMORYSIZE = PAGESIZE * PAGECOUNT; // 64 MiB const wasmInstance: SpineWasm.instance = {} as any; const registerList: any[] = []; /////////////////////////////////////////////////////////////////////////////////////////////////// -function initWasm (wasmUrl) { +function initWasm (wasmUrl): Promise { console.log('[Spine]: Using wasm libs.'); // eslint-disable-next-line @typescript-eslint/no-unsafe-return return wasmFactory({ @@ -61,7 +61,7 @@ function initWasm (wasmUrl) { }, (reason: any) => { console.error('[Spine]:', `Spine wasm load failed: ${reason}`); }); } -function initAsm (resolve) { +function initAsm (resolve): Promise { console.log('[Spine]: Using asmjs libs.'); const wasmMemory: any = {}; wasmMemory.buffer = new ArrayBuffer(MEMORYSIZE); @@ -76,10 +76,10 @@ function initAsm (resolve) { }); } -export function waitForSpineWasmInstantiation () { +export function waitForSpineWasmInstantiation (): Promise { console.log('[spine] waitForSpineWasmInstantiation'); return new Promise((resolve) => { - const errorReport = (msg: any) => { console.error(msg); }; + const errorReport = (msg: any): void => { console.error(msg); }; if (WASM_SUPPORT_MODE === WebAssemblySupportMode.MAYBE_SUPPORT) { if (sys.hasFeature(sys.Feature.WASM)) { initWasm(spineWasmUrl).then(resolve).catch(errorReport); diff --git a/cocos/spine/lib/spine-core.d.ts b/cocos/spine/lib/spine-core.d.ts index 12b6de44d8c..8e95c27cfae 100644 --- a/cocos/spine/lib/spine-core.d.ts +++ b/cocos/spine/lib/spine-core.d.ts @@ -1006,11 +1006,11 @@ declare namespace spine { static BLUE: Color; static MAGENTA: Color; constructor(r?: number, g?: number, b?: number, a?: number); - set(r: number, g: number, b: number, a: number): this; - setFromColor(c: Color): this; - setFromString(hex: string): this; - add(r: number, g: number, b: number, a: number): this; - clamp(): this; + set(r: number, g: number, b: number, a: number): Color; + setFromColor(c: Color): Color; + setFromString(hex: string): Color; + add(r: number, g: number, b: number, a: number): Color; + clamp(): Color; static rgba8888ToColor(color: Color, value: number): void; static rgb888ToColor(color: Color, value: number): void; } @@ -1074,7 +1074,7 @@ declare namespace spine { constructor(x?: number, y?: number); set(x: number, y: number): Vector2; length(): number; - normalize(): this; + normalize(): Vector2; } class TimeKeeper { maxDelta: number; diff --git a/cocos/spine/lib/spine-define.ts b/cocos/spine/lib/spine-define.ts index 1dad41a0afb..6bae8600935 100644 --- a/cocos/spine/lib/spine-define.ts +++ b/cocos/spine/lib/spine-define.ts @@ -25,9 +25,9 @@ import spine from './spine-core.js'; import { js } from '../../core'; -function overrideDefineArrayProp (prototype, getPropVector, name) { +function overrideDefineArrayProp (prototype, getPropVector, name): void { Object.defineProperty(prototype, name, { - get () { + get (): any[] { const array: any[] = []; const vectors = getPropVector.call(this); const count = vectors.size(); @@ -41,7 +41,7 @@ function overrideDefineArrayProp (prototype, getPropVector, name) { }); } -function overrideClass (wasm) { +function overrideClass (wasm): void { spine.wasmUtil = wasm.SpineWasmUtil; spine.wasmUtil.HEAPU8 = wasm.HEAPU8; spine.wasmUtil.spineWasmInit(); @@ -113,7 +113,7 @@ function overrideClass (wasm) { spine.SkeletonInstance = wasm.SkeletonInstance; } -function overrideProperty_BoneData () { +function overrideProperty_BoneData (): void { const prototype = spine.BoneData.prototype as any; const propertyPolyfills = [ { @@ -187,12 +187,12 @@ function overrideProperty_BoneData () { // getter: spine.BoneData.prototype.getProp_color, // }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_ConstraintData () { +function overrideProperty_ConstraintData (): void { const prototype = spine.ConstraintData.prototype as any; const propertyPolyfills = [ { @@ -213,12 +213,12 @@ function overrideProperty_ConstraintData () { setter: prototype.setSkinRequired, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_IkConstraintData () { +function overrideProperty_IkConstraintData (): void { const prototype = spine.IkConstraintData.prototype as any; const propertyPolyfills = [ { @@ -257,13 +257,13 @@ function overrideProperty_IkConstraintData () { getter: prototype.getSoftness, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); } -function overrideProperty_PathConstraintData () { +function overrideProperty_PathConstraintData (): void { const prototype = spine.PathConstraintData.prototype as any; const propertyPolyfills = [ { @@ -312,13 +312,13 @@ function overrideProperty_PathConstraintData () { getter: prototype.getTranslateMix, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); } -function overrideProperty_Event () { +function overrideProperty_Event (): void { const prototype = spine.Event.prototype as any; const propertyPolyfills = [ { @@ -357,12 +357,12 @@ function overrideProperty_Event () { getter: prototype.getBalance, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_EventData () { +function overrideProperty_EventData (): void { const prototype = spine.EventData.prototype as any; const propertyPolyfills = [ { @@ -401,12 +401,12 @@ function overrideProperty_EventData () { getter: prototype.getBalance, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_BoundingBoxAttachment () { +function overrideProperty_BoundingBoxAttachment (): void { const prototype = spine.BoundingBoxAttachment.prototype as any; const propertyPolyfills = [ { @@ -415,12 +415,12 @@ function overrideProperty_BoundingBoxAttachment () { getter: prototype.getName, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_ClippingAttachment () { +function overrideProperty_ClippingAttachment (): void { const prototype = spine.ClippingAttachment.prototype as any; const propertyPolyfills = [ { @@ -429,12 +429,12 @@ function overrideProperty_ClippingAttachment () { getter: prototype.getEndSlot, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_MeshAttachment () { +function overrideProperty_MeshAttachment (): void { const prototype = spine.MeshAttachment.prototype as any; const propertyPolyfills = [ { @@ -483,12 +483,12 @@ function overrideProperty_MeshAttachment () { getter: prototype.getEdges, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_PathAttachment () { +function overrideProperty_PathAttachment (): void { const prototype = spine.PathAttachment.prototype as any; const propertyPolyfills = [ { @@ -502,13 +502,13 @@ function overrideProperty_PathAttachment () { getter: prototype.getConstantSpeed, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getLengths, 'lengths'); } -function overrideProperty_PointAttachment () { +function overrideProperty_PointAttachment (): void { const prototype = spine.PointAttachment.prototype as any; const propertyPolyfills = [ { @@ -527,12 +527,12 @@ function overrideProperty_PointAttachment () { getter: prototype.getRotation, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_RegionAttachment () { +function overrideProperty_RegionAttachment (): void { const prototype = spine.RegionAttachment.prototype as any; const propertyPolyfills = [ { @@ -601,12 +601,12 @@ function overrideProperty_RegionAttachment () { getter: prototype.getUVs, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_TextureAtlas () { +function overrideProperty_TextureAtlas (): void { // const prototype = spine.TextureAtlas.prototype as any; // const propertyPolyfills = [ // { @@ -625,7 +625,7 @@ function overrideProperty_TextureAtlas () { // }); } -function overrideProperty_SlotData () { +function overrideProperty_SlotData (): void { const prototype = spine.SlotData.prototype as any; const propertyPolyfills = [ { @@ -659,12 +659,12 @@ function overrideProperty_SlotData () { getter: prototype.getBlendMode, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_IkConstraint () { +function overrideProperty_IkConstraint (): void { const prototype = spine.IkConstraint.prototype as any; const propertyPolyfills = [ { @@ -708,13 +708,13 @@ function overrideProperty_IkConstraint () { getter: prototype.getActive, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); } -function overrideProperty_PathConstraint () { +function overrideProperty_PathConstraint (): void { const prototype = spine.PathConstraint.prototype as any; const propertyPolyfills = [ { @@ -753,13 +753,13 @@ function overrideProperty_PathConstraint () { getter: prototype.getActive, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); } -function overrideProperty_TransformConstraintData () { +function overrideProperty_TransformConstraintData (): void { const prototype = spine.TransformConstraintData.prototype as any; const propertyPolyfills = [ { @@ -828,13 +828,13 @@ function overrideProperty_TransformConstraintData () { getter: prototype.getLocal, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); } -function overrideProperty_TransformConstraint () { +function overrideProperty_TransformConstraint (): void { const prototype = spine.TransformConstraint.prototype as any; const propertyPolyfills = [ { @@ -873,13 +873,13 @@ function overrideProperty_TransformConstraint () { getter: prototype.getActive, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); } -function overrideProperty_Bone () { +function overrideProperty_Bone (): void { const prototype = spine.Bone.prototype as any; const propertyPolyfills = [ { @@ -1008,12 +1008,12 @@ function overrideProperty_Bone () { getter: prototype.getActive, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_Slot () { +function overrideProperty_Slot (): void { const prototype = spine.Slot.prototype as any; const propertyPolyfills = [ { @@ -1042,12 +1042,12 @@ function overrideProperty_Slot () { getter: prototype.getDeform, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_Skin () { +function overrideProperty_Skin (): void { const prototype = spine.Skin.prototype as any; const propertyPolyfills = [ { @@ -1056,7 +1056,7 @@ function overrideProperty_Skin () { getter: prototype.getName, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); @@ -1064,7 +1064,7 @@ function overrideProperty_Skin () { overrideDefineArrayProp(prototype, prototype.getConstraints, 'constraints'); } -function overrideProperty_SkinEntry () { +function overrideProperty_SkinEntry (): void { const prototype = spine.SkinEntry.prototype as any; const propertyPolyfills = [ { @@ -1073,12 +1073,12 @@ function overrideProperty_SkinEntry () { getter: prototype.getAttachment, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_SkeletonClipping () { +function overrideProperty_SkeletonClipping (): void { const prototype = spine.SkeletonClipping.prototype as any; const propertyPolyfills = [ { @@ -1097,12 +1097,12 @@ function overrideProperty_SkeletonClipping () { getter: prototype.getUVs, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_SkeletonData () { +function overrideProperty_SkeletonData (): void { const prototype = spine.SkeletonData.prototype as any; const propertyPolyfills = [ { @@ -1161,7 +1161,7 @@ function overrideProperty_SkeletonData () { getter: prototype.getAudioPath, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); @@ -1175,7 +1175,7 @@ function overrideProperty_SkeletonData () { overrideDefineArrayProp(prototype, prototype.getPathConstraints, 'pathConstraints'); } -function overrideProperty_RotateTimeline () { +function overrideProperty_RotateTimeline (): void { const prototype = spine.RotateTimeline.prototype as any; const propertyPolyfills = [ { @@ -1184,13 +1184,13 @@ function overrideProperty_RotateTimeline () { getter: prototype.getBoneIndex, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); } -function overrideProperty_ColorTimeline () { +function overrideProperty_ColorTimeline (): void { const prototype = spine.ColorTimeline.prototype as any; const propertyPolyfills = [ { @@ -1199,13 +1199,13 @@ function overrideProperty_ColorTimeline () { getter: prototype.getSlotIndex, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); } -function overrideProperty_TwoColorTimeline () { +function overrideProperty_TwoColorTimeline (): void { const prototype = spine.TwoColorTimeline.prototype as any; const propertyPolyfills = [ { @@ -1214,12 +1214,12 @@ function overrideProperty_TwoColorTimeline () { getter: prototype.getSlotIndex, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_AttachmentTimeline () { +function overrideProperty_AttachmentTimeline (): void { const prototype = spine.AttachmentTimeline.prototype as any; const propertyPolyfills = [ { @@ -1233,13 +1233,13 @@ function overrideProperty_AttachmentTimeline () { getter: prototype.getAttachmentNames, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); } -function overrideProperty_DeformTimeline () { +function overrideProperty_DeformTimeline (): void { const prototype = spine.DeformTimeline.prototype as any; const propertyPolyfills = [ { @@ -1258,24 +1258,24 @@ function overrideProperty_DeformTimeline () { getter: prototype.getFrameVertices, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); } -function overrideProperty_EventTimeline () { +function overrideProperty_EventTimeline (): void { const prototype = spine.EventTimeline.prototype as any; overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); overrideDefineArrayProp(prototype, prototype.getEvents, 'events'); } -function overrideProperty_DrawOrderTimeline () { +function overrideProperty_DrawOrderTimeline (): void { const prototype = spine.DrawOrderTimeline.prototype as any; overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); } -function overrideProperty_TrackEntry () { +function overrideProperty_TrackEntry (): void { const prototype = spine.TrackEntry.prototype as any; const propertyPolyfills = [ { @@ -1384,12 +1384,12 @@ function overrideProperty_TrackEntry () { getter: prototype.getMixBlend, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_AnimationStateData () { +function overrideProperty_AnimationStateData (): void { const prototype = spine.AnimationStateData.prototype as any; const propertyPolyfills = [ { @@ -1403,12 +1403,12 @@ function overrideProperty_AnimationStateData () { getter: prototype.getSkeletonData, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_AnimationState () { +function overrideProperty_AnimationState (): void { const prototype = spine.AnimationState.prototype as any; const propertyPolyfills = [ { @@ -1422,14 +1422,14 @@ function overrideProperty_AnimationState () { getter: prototype.getTimeScale, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getTracks, 'tracks'); } -function overrideProperty_Animation () { +function overrideProperty_Animation (): void { const prototype = spine.Animation.prototype as any; const propertyPolyfills = [ { @@ -1448,12 +1448,12 @@ function overrideProperty_Animation () { getter: prototype.getDuration, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); } -function overrideProperty_Skeleton () { +function overrideProperty_Skeleton (): void { const prototype = spine.Skeleton.prototype as any; const propertyPolyfills = [ { @@ -1502,7 +1502,7 @@ function overrideProperty_Skeleton () { getter: prototype.getY, }, ]; - propertyPolyfills.forEach((prop) => { + propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); @@ -1514,7 +1514,7 @@ function overrideProperty_Skeleton () { overrideDefineArrayProp(prototype, prototype.getPathConstraints, 'pathConstraints'); } -export function overrideSpineDefine (wasm) { +export function overrideSpineDefine (wasm): void { overrideClass(wasm); overrideProperty_BoneData(); overrideProperty_ConstraintData(); diff --git a/cocos/spine/skeleton-cache.ts b/cocos/spine/skeleton-cache.ts index 1663d55be53..335c6a38e0d 100644 --- a/cocos/spine/skeleton-cache.ts +++ b/cocos/spine/skeleton-cache.ts @@ -79,18 +79,18 @@ export class AnimationCache { this._instance.setUseTint(_useTint); } - get skeleton () { + get skeleton (): spine.Skeleton { return this._skeleton; } - public setSkin (skinName: string) { + public setSkin (skinName: string): void { this._instance.setSkin(skinName); } - public setAnimation (animationName: string) { + public setAnimation (animationName: string): void { const animations = this._skeletonData.animations; let animation: spine.Animation | null = null; - animations.forEach((element) => { + animations.forEach((element): void => { if (element.name === animationName) { animation = element; } @@ -104,7 +104,7 @@ export class AnimationCache { this._instance.setAnimation(0, animationName, false); } - public updateToFrame (frameIdx: number) { + public updateToFrame (frameIdx: number): void { if (this._isCompleted) return; while (this._curIndex < frameIdx) { this._instance.updateAnimation(FrameTime); @@ -117,18 +117,18 @@ export class AnimationCache { } } - public getFrame (frameIdx: number) { + public getFrame (frameIdx: number): AnimationFrame { const index = frameIdx % this._maxFrameIdex; return this._frames[index]; } - public invalidAnimationFrames () { + public invalidAnimationFrames (): void { this._curIndex = -1; this._isCompleted = false; this._frames.length = 0; } - private updateRenderData (index: number, model: any) { + private updateRenderData (index: number, model: any): void { const vc = model.vCount; const ic = model.iCount; const floatStride = (_useTint ? _byteStrideTwoColor : _byteStrideOneColor) / Float32Array.BYTES_PER_ELEMENT; @@ -167,7 +167,7 @@ export class AnimationCache { const bones = this._skeleton.bones; const boneInfosArray: FrameBoneInfo[] = []; - bones.forEach((bone) => { + bones.forEach((bone): void => { const boneInfo = new FrameBoneInfo(); boneInfo.a = bone.a; boneInfo.b = bone.b; @@ -184,7 +184,7 @@ export class AnimationCache { }; } - public destory () { + public destory (): void { spine.wasmUtil.destroySpineInstance(this._instance); } } @@ -196,13 +196,13 @@ class SkeletonCache { this._animationPool = {}; } - public getAnimationCache (uuid: string, animationName: string) { + public getAnimationCache (uuid: string, animationName: string): AnimationCache { const poolKey = `${uuid}#${animationName}`; const animCache = this._animationPool[poolKey]; return animCache; } - public initAnimationCache (data: SkeletonData, animationName: string) { + public initAnimationCache (data: SkeletonData, animationName: string): AnimationCache { const uuid = data.uuid; const poolKey = `${uuid}#${animationName}`; const spData = data.getRuntimeData(); @@ -212,7 +212,7 @@ class SkeletonCache { return animCache; } - public destroyCachedAnimations (uuid?: string) { + public destroyCachedAnimations (uuid?: string): void { if (uuid) { const animationPool = this._animationPool; for (const key in animationPool) { diff --git a/cocos/spine/skeleton-data.ts b/cocos/spine/skeleton-data.ts index d1e83aba7a0..906ff92bce3 100644 --- a/cocos/spine/skeleton-data.ts +++ b/cocos/spine/skeleton-data.ts @@ -82,7 +82,7 @@ export class SkeletonData extends Asset { * @en An atlas text description. * @zh Atlas 文本描述。 */ - get atlasText () { + get atlasText (): string { return this._atlasText; } set atlasText (value) { @@ -158,7 +158,7 @@ export class SkeletonData extends Asset { * @internal * @deprecated Since v3.7.2, this is an engine private interface that will be removed in the future. */ - public createNode (callback: (err: Error|null, node: Node) => void) { + public createNode (callback: (err: Error|null, node: Node) => void): void { const node = new Node(this.name); const skeleton = node.addComponent('cc.Skeleton') as Skeleton; skeleton.skeletonData = this; @@ -169,7 +169,7 @@ export class SkeletonData extends Asset { * @en Resets skeleton data state. * @zh 重置数据。 */ - public reset () { + public reset (): void { this._skeletonCache = null; if (EDITOR_NOT_IN_PREVIEW) { this._skinsEnum = null; @@ -181,7 +181,7 @@ export class SkeletonData extends Asset { * @en Reset skeleton skin and animation enumeration. * @zh 重置皮肤和动画枚举。 */ - public resetEnums () { + public resetEnums (): void { if (EDITOR_NOT_IN_PREVIEW) { this._skinsEnum = null; this._animsEnum = null; @@ -229,7 +229,9 @@ export class SkeletonData extends Asset { /** * @internal Since v3.7.2, this is an engine private function, it only works in editor. */ - public getSkinsEnum () { + public getSkinsEnum (): { + [key: string]: number; + } | null { if (this._skinsEnum /* && Object.keys(this._skinsEnum).length > 0 */) { return this._skinsEnum; } @@ -248,7 +250,9 @@ export class SkeletonData extends Asset { /** * @internal Since v3.7.2, this is an engine private function, it only works in editor. */ - public getAnimsEnum () { + public getAnimsEnum (): { + [key: string]: number; + } | null { if (this._animsEnum && Object.keys(this._animsEnum).length > 1) { return this._animsEnum; } @@ -268,7 +272,7 @@ export class SkeletonData extends Asset { * @en Destroy skeleton data. * @zh 销毁 skeleton data。 */ - public destroy () { + public destroy (): boolean { SkeletonCache.sharedCache.destroyCachedAnimations(this._uuid); if (this._skeletonCache) { spine.wasmUtil.registerSpineSkeletonDataWithUUID(this._skeletonCache, this._uuid); diff --git a/cocos/spine/skeleton-system.ts b/cocos/spine/skeleton-system.ts index 94f2ad464c2..d629b72c66a 100644 --- a/cocos/spine/skeleton-system.ts +++ b/cocos/spine/skeleton-system.ts @@ -48,7 +48,7 @@ export class SkeletonSystem extends System { * @zh * 获取 Spine 骨骼系统的单例。 */ - public static getInstance () { + public static getInstance (): SkeletonSystem { if (!SkeletonSystem._instance) { SkeletonSystem._instance = new SkeletonSystem(); director.registerSystem(SkeletonSystem.ID, SkeletonSystem._instance, System.Priority.HIGH); @@ -58,21 +58,21 @@ export class SkeletonSystem extends System { private _skeletons = new Set(); - public add (skeleton: Skeleton | null) { + public add (skeleton: Skeleton | null): void { if (!skeleton) return; if (!this._skeletons.has(skeleton)) { this._skeletons.add(skeleton); } } - public remove (skeleton: Skeleton | null) { + public remove (skeleton: Skeleton | null): void { if (!skeleton) return; if (this._skeletons.has(skeleton)) { this._skeletons.delete(skeleton); } } - postUpdate (dt: number) { + postUpdate (dt: number): void { if (!this._skeletons) { return; } @@ -82,7 +82,7 @@ export class SkeletonSystem extends System { }); } - public prepareRenderData () { + public prepareRenderData (): void { if (!this._skeletons) { return; } diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index c57d0f1b335..8d7e93570c9 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -120,7 +120,7 @@ export interface SkeletonDrawData { indexCount: number; } -function setEnumAttr (obj, propName, enumDef) { +function setEnumAttr (obj, propName, enumDef): void { CCClass.Attr.setClassAttr(obj, propName, 'type', 'Enum'); CCClass.Attr.setClassAttr(obj, propName, 'enumList', Enum.getList(enumDef)); } @@ -227,7 +227,7 @@ export class Skeleton extends UIRenderer { // Animation name protected _animationName = ''; protected _skinName = ''; - protected _drawList = new RecyclePool(() => ({ + protected _drawList = new RecyclePool((): { material: any; indexOffset: number; indexCount: number; } => ({ material: null, indexOffset: 0, indexCount: 0, @@ -268,7 +268,7 @@ export class Skeleton extends UIRenderer { /** * @engineInternal Since v3.7.2, this is an engine private interface. */ - get drawList () { return this._drawList; } + get drawList (): RecyclePool { return this._drawList; } /** * @en @@ -284,7 +284,7 @@ export class Skeleton extends UIRenderer { @editable @type(SkeletonData) @displayName('SkeletonData') - get skeletonData () { + get skeletonData (): SkeletonData | null { return this._skeletonData; } set skeletonData (value: SkeletonData | null) { @@ -356,7 +356,7 @@ export class Skeleton extends UIRenderer { @displayName('Animation') @type(DefaultAnimsEnum) @tooltip('i18n:COMPONENT.skeleton.animation') - get _animationIndex () { + get _animationIndex (): number { const animationName = EDITOR_NOT_IN_PREVIEW ? this.defaultAnimation : this.animation; if (this.skeletonData) { if (animationName) { @@ -407,7 +407,7 @@ export class Skeleton extends UIRenderer { @tooltip('i18n:COMPONENT.skeleton.animation_cache_mode') @editable @type(AnimationCacheMode) - get defaultCacheMode () { + get defaultCacheMode (): AnimationCacheMode { return this._defaultCacheMode; } set defaultCacheMode (mode: AnimationCacheMode) { @@ -444,7 +444,7 @@ export class Skeleton extends UIRenderer { */ @tooltip('i18n:COMPONENT.skeleton.time_scale') @editable - get timeScale () { return this._timeScale; } + get timeScale (): number { return this._timeScale; } set timeScale (value) { if (value !== this._timeScale) { this._timeScale = value; @@ -456,7 +456,7 @@ export class Skeleton extends UIRenderer { */ @editable @tooltip('i18n:COMPONENT.skeleton.use_tint') - get useTint () { return this._useTint; } + get useTint (): boolean { return this._useTint; } set useTint (value) { if (value !== this._useTint) { this._useTint = value; @@ -471,7 +471,7 @@ export class Skeleton extends UIRenderer { */ @editable @tooltip('i18n:COMPONENT.skeleton.enabled_batch') - get enableBatch () { return this._enableBatch; } + get enableBatch (): boolean { return this._enableBatch; } set enableBatch (value) { if (value !== this._enableBatch) { this._enableBatch = value; @@ -505,7 +505,7 @@ export class Skeleton extends UIRenderer { */ @editable @tooltip('i18n:COMPONENT.skeleton.debug_slots') - get debugSlots () { return this._debugSlots; } + get debugSlots (): boolean { return this._debugSlots; } set debugSlots (v: boolean) { if (v !== this._debugSlots) { this._debugSlots = v; @@ -520,7 +520,7 @@ export class Skeleton extends UIRenderer { */ @editable @tooltip('i18n:COMPONENT.skeleton.debug_bones') - get debugBones () { return this._debugBones; } + get debugBones (): boolean { return this._debugBones; } set debugBones (v: boolean) { if (v !== this._debugBones) { this._debugBones = v; @@ -535,7 +535,7 @@ export class Skeleton extends UIRenderer { */ @editable @tooltip('i18n:COMPONENT.skeleton.debug_mesh') - get debugMesh () { return this._debugMesh; } + get debugMesh (): boolean { return this._debugMesh; } set debugMesh (value) { if (value !== this._debugMesh) { this._debugMesh = value; @@ -543,14 +543,13 @@ export class Skeleton extends UIRenderer { this.markForUpdateRenderData(); } } - get socketNodes () { return this._socketNodes; } + get socketNodes (): Map { return this._socketNodes; } /** * @en The name of current playing animation. * @zh 当前播放的动画名称。 * @property {String} animation */ - get animation (): string { return this._animationName; } @@ -570,7 +569,7 @@ export class Skeleton extends UIRenderer { @type(Material) @displayOrder(0) @displayName('CustomMaterial') - get customMaterial () { + get customMaterial (): Material | null { return this._customMaterial; } set customMaterial (val) { @@ -579,18 +578,18 @@ export class Skeleton extends UIRenderer { this.markForUpdateRenderData(); } - public __preload () { + public __preload (): void { super.__preload(); } - public onRestore () { + public onRestore (): void { } /** * @en Be called when component state becomes available. * @zh 组件状态变为可用时调用。 */ - public onEnable () { + public onEnable (): void { super.onEnable(); this._updateSkeletonData(); this._flushAssembler(); @@ -600,12 +599,12 @@ export class Skeleton extends UIRenderer { * @en Be called when component state becomes disabled. * @zh 组件状态变为禁用状态时调用。 */ - public onDisable () { + public onDisable (): void { super.onDisable(); SkeletonSystem.getInstance().remove(this); } - public onDestroy () { + public onDestroy (): void { this.destroyRenderData(); this._cleanMaterialCache(); if (!JSB) { @@ -617,14 +616,14 @@ export class Skeleton extends UIRenderer { * @en Clear animation and set to setup pose. * @zh 清除动画并还原到初始姿势。 */ - public clearAnimation () { + public clearAnimation (): void { if (!this.isAnimationCached()) { this.clearTrack(0); this.setToSetupPose(); } } - protected _updateSkeletonData () { + protected _updateSkeletonData (): void { const skeletonData = this._skeletonData; if (!skeletonData) { this._texture = null; @@ -659,7 +658,7 @@ export class Skeleton extends UIRenderer { * skins, etc) and animations but does not hold any state. @zh 骨架数据(SkeletonData)包含骨架信息(绑定pose的骨骼、槽位、绘制顺序、附件、 * 皮肤等)和动画, 但不保存任何状态。 */ - public setSkeletonData (skeletonData: spine.SkeletonData) { + public setSkeletonData (skeletonData: spine.SkeletonData): void { if (!EDITOR_NOT_IN_PREVIEW) { if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) { this._skeletonCache = SkeletonCache.sharedCache; @@ -688,7 +687,7 @@ export class Skeleton extends UIRenderer { * @param name @en The name of animation. @zh 动画名称。 * @param loop @en Use loop mode or not. @zh 是否使用循环播放模式。 */ - public setAnimation (trackIndex: number, name: string, loop?: boolean) { + public setAnimation (trackIndex: number, name: string, loop?: boolean): void { if (loop === undefined) loop = true; if (this.isAnimationCached()) { @@ -728,7 +727,7 @@ export class Skeleton extends UIRenderer { * * @param skinName @en The name of skin. @zh 皮肤名称。 */ - public setSkin (name: string) { + public setSkin (name: string): void { this._skinName = name; if (this.isAnimationCached()) { if (this._animCache) { @@ -744,7 +743,7 @@ export class Skeleton extends UIRenderer { * @zh 更新骨骼动画。 * @param dt @en delta time. @zh 时间差。 */ - public updateAnimation (dt: number) { + public updateAnimation (dt: number): void { if (EDITOR_NOT_IN_PREVIEW) return; if (this.paused) return; dt *= this._timeScale * timeScale; @@ -773,7 +772,7 @@ export class Skeleton extends UIRenderer { } } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = Skeleton.Assembler.getAssembler(this); if (this._assembler !== assembler) { this._assembler = assembler; @@ -785,7 +784,7 @@ export class Skeleton extends UIRenderer { } } - protected _render (batcher: Batcher2D) { + protected _render (batcher: Batcher2D): void { let indicesCount = 0; if (this.renderData && this._drawList) { const rd = this.renderData; @@ -810,7 +809,7 @@ export class Skeleton extends UIRenderer { /** * @internal */ - public requestDrawData (material: Material, indexOffset: number, indexCount: number) { + public requestDrawData (material: Material, indexOffset: number, indexCount: number): SkeletonDrawData { const draw = this._drawList.add(); draw.material = material; draw.indexOffset = indexOffset; @@ -825,7 +824,7 @@ export class Skeleton extends UIRenderer { /** * @engineInternal */ - public updateMaterial () { + public updateMaterial (): void { let mat; if (this._customMaterial) mat = this._customMaterial; else mat = this._updateBuiltinMaterial(); @@ -839,7 +838,7 @@ export class Skeleton extends UIRenderer { this.updateMaterial(); return this.material!; } - private _cleanMaterialCache () { + private _cleanMaterialCache (): void { for (const val in this._materialCache) { this._materialCache[val].destroy(); } @@ -887,7 +886,7 @@ export class Skeleton extends UIRenderer { } // update animation list for editor - protected _updateAnimEnum () { + protected _updateAnimEnum (): void { let animEnum; if (this.skeletonData) { animEnum = this.skeletonData.getAnimsEnum(); @@ -902,7 +901,7 @@ export class Skeleton extends UIRenderer { setEnumAttr(this, '_animationIndex', this._enumAnimations); } // update skin list for editor - protected _updateSkinEnum () { + protected _updateSkinEnum (): void { let skinEnum; if (this.skeletonData) { skinEnum = this.skeletonData.getSkinsEnum(); @@ -916,7 +915,7 @@ export class Skeleton extends UIRenderer { setEnumAttr(this, '_defaultSkinIndex', this._enumSkins); } - protected _refreshInspector () { + protected _refreshInspector (): void { if (EDITOR_NOT_IN_PREVIEW) { // update inspector this._updateAnimEnum(); @@ -930,12 +929,12 @@ export class Skeleton extends UIRenderer { * @en Call this method to destroy the rendering data. * @zh 调用该方法销毁渲染数据。 */ - public destroyRenderData () { + public destroyRenderData (): void { this._drawList.reset(); super.destroyRenderData(); } - protected createRenderEntity () { + protected createRenderEntity (): RenderEntity { const renderEntity = new RenderEntity(RenderEntityType.DYNAMIC); renderEntity.setUseLocal(true); return renderEntity; @@ -944,7 +943,7 @@ export class Skeleton extends UIRenderer { * @en Mark to re-update the rendering data, usually used to force refresh the display. * @zh 标记重新更新渲染数据,一般用于强制刷新显示。 */ - public markForUpdateRenderData (enable = true) { + public markForUpdateRenderData (enable = true): void { super.markForUpdateRenderData(enable); // if (this._debugRenderer) { // this._debugRenderer.markForUpdateRenderData(enable); @@ -954,7 +953,7 @@ export class Skeleton extends UIRenderer { /** * @engineInternal since v3.7.2 this is an engine private function. */ - public syncAttachedNode () { + public syncAttachedNode (): void { // sync attached node matrix this.attachUtil._syncAttachedNode(); } @@ -963,7 +962,7 @@ export class Skeleton extends UIRenderer { * @en Whether in cached mode. * @zh 当前是否处于缓存模式。 */ - public isAnimationCached () { + public isAnimationCached (): boolean { if (EDITOR_NOT_IN_PREVIEW) return false; return this._cacheMode !== AnimationCacheMode.REALTIME; } @@ -978,7 +977,7 @@ export class Skeleton extends UIRenderer { * @example * skeleton.setAnimationCacheMode(sp.Skeleton.AnimationCacheMode.SHARED_CACHE); */ - public setAnimationCacheMode (cacheMode: AnimationCacheMode) { + public setAnimationCacheMode (cacheMode: AnimationCacheMode): void { if (this._cacheMode !== cacheMode) { this._cacheMode = cacheMode; this._updateSkeletonData(); @@ -992,7 +991,7 @@ export class Skeleton extends UIRenderer { * @en Sets the bones and slots to the setup pose. * @zh 还原到起始动作。 */ - public setToSetupPose () { + public setToSetupPose (): void { if (this._skeleton) { this._skeleton.setToSetupPose(); } @@ -1006,7 +1005,7 @@ export class Skeleton extends UIRenderer { * 设置 bone 到起始动作。 * 使用 SkeletonData 中的 BoneData 列表中的值。 */ - public setBonesToSetupPose () { + public setBonesToSetupPose (): void { if (this._skeleton) { this._skeleton.setBonesToSetupPose(); } @@ -1020,7 +1019,7 @@ export class Skeleton extends UIRenderer { * 设置 slot 到起始动作。 * 使用 SkeletonData 中的 SlotData 列表中的值。 */ - public setSlotsToSetupPose () { + public setSlotsToSetupPose (): void { if (this._skeleton) { this._skeleton.setSlotsToSetupPose(); } @@ -1038,7 +1037,7 @@ export class Skeleton extends UIRenderer { * * @param boneName @en The name of bone. @zh 骨骼名称。 */ - public findBone (boneName: string) { + public findBone (boneName: string): spine.Bone | null { if (this._skeleton) { return this._skeleton.findBone(boneName); } @@ -1055,7 +1054,7 @@ export class Skeleton extends UIRenderer { * * @param slotName @en The name of slot. @zh 插槽名称。 */ - public findSlot (slotName: string) { + public findSlot (slotName: string): spine.Slot | null { if (this._skeleton) { return this._skeleton.findSlot(slotName); } @@ -1087,7 +1086,7 @@ export class Skeleton extends UIRenderer { * @en Clears all tracks of animation state. * @zh 清除所有 track 的动画状态。 */ - public clearTracks () { + public clearTracks (): void { if (this.isAnimationCached()) { warn('\'clearTracks\' interface can not be invoked in cached mode.'); } else if (this._state) { @@ -1101,7 +1100,7 @@ export class Skeleton extends UIRenderer { * @zh 清除出指定 track 的动画状态。 * @param trackIndex @en Index of track. @zh 动画通道索引。 */ - public clearTrack (trackIndex: number) { + public clearTrack (trackIndex: number): void { if (this.isAnimationCached()) { warn('\'clearTrack\' interface can not be invoked in cached mode.'); } else if (this._state) { @@ -1123,7 +1122,7 @@ export class Skeleton extends UIRenderer { * bone = spine.findBone('head'); * cc.log(bone.worldX); // return -23.12; */ - protected updateWorldTransform () { + protected updateWorldTransform (): void { if (!this.isAnimationCached()) return; if (this._skeleton) { @@ -1131,7 +1130,7 @@ export class Skeleton extends UIRenderer { } } - private _verifySockets (sockets: SpineSocket[]) { + private _verifySockets (sockets: SpineSocket[]): void { for (let i = 0, l = sockets.length; i < l; i++) { const target = sockets[i].target; if (target) { @@ -1142,7 +1141,7 @@ export class Skeleton extends UIRenderer { } } const uniqueSocketNode: Map = new Map(); - sockets.forEach((x: SpineSocket) => { + sockets.forEach((x: SpineSocket): void => { if (x.target) { if (uniqueSocketNode.get(x.target)) { console.error(`Target node ${x.target.name} has existed.`); @@ -1153,7 +1152,7 @@ export class Skeleton extends UIRenderer { }); } - protected _updateSocketBindings () { + protected _updateSocketBindings (): void { if (!this._skeleton) return; this._socketNodes.clear(); for (let i = 0, l = this._sockets.length; i < l; i++) { @@ -1175,7 +1174,7 @@ export class Skeleton extends UIRenderer { } this._cachedSockets.clear(); const bones = this._skeleton.bones; - const getBoneName = (bone: spine.Bone) => { + const getBoneName = (bone: spine.Bone): any => { if (bone.parent == null) return bone.data.name || ''; return `${getBoneName(bones[bone.parent.data.index]) as string}/${bone.data.name}`; }; @@ -1191,7 +1190,7 @@ export class Skeleton extends UIRenderer { * @zh 查询所有可以添加挂点的所有骨骼。 * @return String typed array of bones's path. */ - public querySockets () { + public querySockets (): string[] { if (!this._skeleton) { return []; } @@ -1206,7 +1205,7 @@ export class Skeleton extends UIRenderer { } // if change use tint mode, just clear material cache - protected _updateUseTint () { + protected _updateUseTint (): void { this._cleanMaterialCache(); this.destroyRenderData(); if (!JSB) { @@ -1221,16 +1220,16 @@ export class Skeleton extends UIRenderer { } // if change use batch mode, just clear material cache - protected _updateBatch () { + protected _updateBatch (): void { this._cleanMaterialCache(); this.markForUpdateRenderData(); } - protected _updateDebugDraw () { + protected _updateDebugDraw (): void { // TODO next } - private _updateUITransform () { + private _updateUITransform (): void { const uiTrans = this.node._uiProps.uiTransformComp!; const skeletonData = this._runtimeData; if (!skeletonData) { @@ -1248,7 +1247,7 @@ export class Skeleton extends UIRenderer { } } - protected _updateColor () { + protected _updateColor (): void { this.node._uiProps.colorDirty = true; const r = this._color.r / 255.0; const g = this._color.g / 255.0; @@ -1262,7 +1261,7 @@ export class Skeleton extends UIRenderer { * @zh 设置顶点特效动画代理。 * @param effectDelegate @en Vertex effect delegate. @zh 顶点特效代理。 */ - public setVertexEffectDelegate (effectDelegate: VertexEffectDelegate | null | undefined) { + public setVertexEffectDelegate (effectDelegate: VertexEffectDelegate | null | undefined): void { if (!effectDelegate) { this._instance.clearEffect(); return; @@ -1277,7 +1276,7 @@ export class Skeleton extends UIRenderer { } } - protected _ensureListener () { + protected _ensureListener (): void { if (!this._listener) { this._listener = new TrackEntryListeners(); } @@ -1288,7 +1287,7 @@ export class Skeleton extends UIRenderer { * @zh 用来设置开始播放动画的事件监听。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setStartListener (listener: TrackListener) { + public setStartListener (listener: TrackListener): void { this._ensureListener(); const listenerID = TrackEntryListeners.addListener(listener); this._instance.setListener(listenerID, spine.EventType.start); @@ -1300,7 +1299,7 @@ export class Skeleton extends UIRenderer { * @zh 用来设置动画被打断的事件监听。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setInterruptListener (listener: TrackListener) { + public setInterruptListener (listener: TrackListener): void { this._ensureListener(); const listenerID = TrackEntryListeners.addListener(listener); this._instance.setListener(listenerID, spine.EventType.interrupt); @@ -1312,7 +1311,7 @@ export class Skeleton extends UIRenderer { * @zh 用来设置动画播放完后的事件监听。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setEndListener (listener: TrackListener) { + public setEndListener (listener: TrackListener): void { this._ensureListener(); const listenerID = TrackEntryListeners.addListener(listener); this._instance.setListener(listenerID, spine.EventType.end); @@ -1324,7 +1323,7 @@ export class Skeleton extends UIRenderer { * @zh 用来设置动画将被销毁的事件监听。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setDisposeListener (listener: TrackListener) { + public setDisposeListener (listener: TrackListener): void { this._ensureListener(); const listenerID = TrackEntryListeners.addListener(listener); this._instance.setListener(listenerID, spine.EventType.dispose); @@ -1336,7 +1335,7 @@ export class Skeleton extends UIRenderer { * @zh 用来设置动画播放一次循环结束后的事件监听。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setCompleteListener (listener: TrackListener) { + public setCompleteListener (listener: TrackListener): void { this._ensureListener(); const listenerID = TrackEntryListeners.addListener(listener); this._instance.setListener(listenerID, spine.EventType.complete); @@ -1348,7 +1347,7 @@ export class Skeleton extends UIRenderer { * @zh 用来设置动画播放过程中帧事件的监听。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setEventListener (listener: TrackListener2) { + public setEventListener (listener: TrackListener2): void { this._ensureListener(); const listenerID = TrackEntryListeners.addListener(listener); this._instance.setListener(listenerID, spine.EventType.event); @@ -1361,7 +1360,7 @@ export class Skeleton extends UIRenderer { * @param entry @en Animation track entry. @zh Track entry。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setTrackStartListener (entry: spine.TrackEntry, listener: TrackListener) { + public setTrackStartListener (entry: spine.TrackEntry, listener: TrackListener): void { TrackEntryListeners.getListeners(entry).start = listener; } @@ -1371,7 +1370,7 @@ export class Skeleton extends UIRenderer { * @param entry * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setTrackInterruptListener (entry: spine.TrackEntry, listener: TrackListener) { + public setTrackInterruptListener (entry: spine.TrackEntry, listener: TrackListener): void { TrackEntryListeners.getListeners(entry).interrupt = listener; } @@ -1381,7 +1380,7 @@ export class Skeleton extends UIRenderer { * @param entry * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setTrackEndListener (entry: spine.TrackEntry, listener: TrackListener) { + public setTrackEndListener (entry: spine.TrackEntry, listener: TrackListener): void { TrackEntryListeners.getListeners(entry).end = listener; } @@ -1391,7 +1390,7 @@ export class Skeleton extends UIRenderer { * @param entry * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setTrackDisposeListener (entry: spine.TrackEntry, listener: TrackListener) { + public setTrackDisposeListener (entry: spine.TrackEntry, listener: TrackListener): void { TrackEntryListeners.getListeners(entry).dispose = listener; } @@ -1401,7 +1400,7 @@ export class Skeleton extends UIRenderer { * @param entry * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setTrackCompleteListener (entry: spine.TrackEntry, listener: TrackListener2) { + public setTrackCompleteListener (entry: spine.TrackEntry, listener: TrackListener2): void { // TODO // TrackEntryListeners.getListeners(entry).complete = function (trackEntry) { // const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); @@ -1415,7 +1414,7 @@ export class Skeleton extends UIRenderer { * @param entry * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ - public setTrackEventListener (entry: spine.TrackEntry, listener: TrackListener|TrackListener2) { + public setTrackEventListener (entry: spine.TrackEntry, listener: TrackListener|TrackListener2): void { TrackEntryListeners.getListeners(entry).event = listener; } } diff --git a/cocos/spine/track-entry-listeners.ts b/cocos/spine/track-entry-listeners.ts index 4acdcbcec1e..777f8ca00bf 100644 --- a/cocos/spine/track-entry-listeners.ts +++ b/cocos/spine/track-entry-listeners.ts @@ -38,7 +38,7 @@ export class TrackEntryListeners { complete?: ((entry: spine.TrackEntry) => void); event?: ((entry: spine.TrackEntry, event: spine.Event) => void); - static getListeners (entry: spine.TrackEntry) { + static getListeners (entry: spine.TrackEntry): spine.AnimationStateListener { if (!entry.listener) { entry.listener = new TrackEntryListeners() as any; } diff --git a/cocos/spine/vertex-effect-delegate.ts b/cocos/spine/vertex-effect-delegate.ts index d7443d09fae..1fd12ac1423 100644 --- a/cocos/spine/vertex-effect-delegate.ts +++ b/cocos/spine/vertex-effect-delegate.ts @@ -55,7 +55,7 @@ export class VertexEffectDelegate { * @en Clears vertex effect. * @zh 清空顶点特效。 */ - clear () { + clear (): void { this._vertexEffect = null!; this._interpolation = null!; this._effectType = 'none'; @@ -110,7 +110,7 @@ export class VertexEffectDelegate { * @method getJitterVertexEffect * @return {sp.spine.JitterEffect} */ - getJitterVertexEffect () { + getJitterVertexEffect (): spine.VertexEffect { return this._vertexEffect; } @@ -120,7 +120,7 @@ export class VertexEffectDelegate { * @method getSwirlVertexEffect * @return {sp.spine.SwirlEffect} */ - getSwirlVertexEffect () { + getSwirlVertexEffect (): spine.VertexEffect { return this._vertexEffect; } @@ -130,7 +130,7 @@ export class VertexEffectDelegate { * @method getVertexEffect * @return {sp.spine.JitterEffect|sp.spine.SwirlEffect} */ - getVertexEffect () { + getVertexEffect (): spine.VertexEffect { return this._vertexEffect; } @@ -140,7 +140,7 @@ export class VertexEffectDelegate { * @method getEffectType * @return {String} */ - getEffectType () { + getEffectType (): string { return this._effectType; } } diff --git a/cocos/terrain/height-field.ts b/cocos/terrain/height-field.ts index ba5b5488102..ea45efaef07 100644 --- a/cocos/terrain/height-field.ts +++ b/cocos/terrain/height-field.ts @@ -39,22 +39,22 @@ export class HeightField { } } - public set (i: number, j: number, value: number) { + public set (i: number, j: number, value: number): void { this.data[j * this.w + i] = value; } - public get (i: number, j: number) { + public get (i: number, j: number): number { return this.data[j * this.w + i]; } - public getClamp (i: number, j: number) { + public getClamp (i: number, j: number): number { i = clamp(i, 0, this.w - 1); j = clamp(j, 0, this.h - 1); return this.get(i, j); } - public getAt (x: number, y: number) { + public getAt (x: number, y: number): number { const fx = x; const fy = y; diff --git a/cocos/terrain/terrain-asset.ts b/cocos/terrain/terrain-asset.ts index 2a23b841097..0a1fa12f141 100644 --- a/cocos/terrain/terrain-asset.ts +++ b/cocos/terrain/terrain-asset.ts @@ -55,7 +55,7 @@ class TerrainBuffer { private _buffView: DataView = new DataView(this.buffer.buffer); private _seekPos = 0; - public reserve (size: number) { + public reserve (size: number): void { if (this.buffer.byteLength > size) { return; } @@ -74,35 +74,35 @@ class TerrainBuffer { this._buffView = new DataView(this.buffer.buffer); } - public assign (buff: Uint8Array) { + public assign (buff: Uint8Array): void { this.buffer = buff; this.length = buff.length; this._seekPos = buff.byteOffset; this._buffView = new DataView(buff.buffer); } - public writeInt8 (value: number) { + public writeInt8 (value: number): void { this.reserve(this.length + 1); this._buffView.setInt8(this.length, value); this.length += 1; } - public writeInt16 (value: number) { + public writeInt16 (value: number): void { this.reserve(this.length + 2); this._buffView.setInt16(this.length, value, true); this.length += 2; } - public writeInt32 (value: number) { + public writeInt32 (value: number): void { this.reserve(this.length + 4); this._buffView.setInt32(this.length, value, true); this.length += 4; } - public writeIntArray (value: number[]) { + public writeIntArray (value: number[]): void { this.reserve(this.length + 4 * value.length); for (let i = 0; i < value.length; ++i) { @@ -111,14 +111,14 @@ class TerrainBuffer { this.length += 4 * value.length; } - public writeFloat (value: number) { + public writeFloat (value: number): void { this.reserve(this.length + 4); this._buffView.setFloat32(this.length, value, true); this.length += 4; } - public writeFloatArray (value: number[]) { + public writeFloatArray (value: number[]): void { this.reserve(this.length + 4 * value.length); for (let i = 0; i < value.length; ++i) { @@ -127,14 +127,14 @@ class TerrainBuffer { this.length += 4 * value.length; } - public writeDouble (value: number) { + public writeDouble (value: number): void { this.reserve(this.length + 8); this._buffView.setFloat64(this.length, value, true); this.length += 8; } - public writeDoubleArray (value: number[]) { + public writeDoubleArray (value: number[]): void { this.reserve(this.length + 8 * value.length); for (let i = 0; i < value.length; ++i) { @@ -143,7 +143,7 @@ class TerrainBuffer { this.length += 8 * value.length; } - public writeString (value: string) { + public writeString (value: string): void { this.reserve(this.length + value.length + 4); this._buffView.setInt32(this.length, value.length, true); @@ -153,25 +153,25 @@ class TerrainBuffer { this.length += value.length + 4; } - public readInt8 () { + public readInt8 (): number { const value = this._buffView.getInt8(this._seekPos); this._seekPos += 1; return value; } - public readInt16 () { + public readInt16 (): number { const value = this._buffView.getInt16(this._seekPos, true); this._seekPos += 2; return value; } - public readInt () { + public readInt (): number { const value = this._buffView.getInt32(this._seekPos, true); this._seekPos += 4; return value; } - public readIntArray (value: number[]) { + public readIntArray (value: number[]): number[] { for (let i = 0; i < value.length; ++i) { value[i] = this._buffView.getInt32(this._seekPos + i * 4, true); } @@ -179,13 +179,13 @@ class TerrainBuffer { return value; } - public readFloat () { + public readFloat (): number { const value = this._buffView.getFloat32(this._seekPos, true); this._seekPos += 4; return value; } - public readFloatArray (value: number[]) { + public readFloatArray (value: number[]): number[] { for (let i = 0; i < value.length; ++i) { value[i] = this._buffView.getFloat32(this._seekPos + i * 4, true); } @@ -193,13 +193,13 @@ class TerrainBuffer { return value; } - public readDouble () { + public readDouble (): number { const value = this._buffView.getFloat64(this._seekPos, true); this._seekPos += 8; return value; } - public readDoubleArray (value: number[]) { + public readDoubleArray (value: number[]): number[] { for (let i = 0; i < value.length; ++i) { value[i] = this._buffView.getFloat64(this._seekPos + i * 4, true); } @@ -207,7 +207,7 @@ class TerrainBuffer { return value; } - public readString () { + public readString (): string { const length = this.readInt(); let value = ''; @@ -297,7 +297,7 @@ export class TerrainAsset extends Asset { * @en version * @zh 版本 */ - get version () { + get version (): number { return this._version; } @@ -309,7 +309,7 @@ export class TerrainAsset extends Asset { this._tileSize = value; } - get tileSize () { + get tileSize (): number { return this._tileSize; } @@ -321,7 +321,7 @@ export class TerrainAsset extends Asset { this._blockCount = value; } - get blockCount () { + get blockCount (): number[] { return this._blockCount; } @@ -333,7 +333,7 @@ export class TerrainAsset extends Asset { this._lightMapSize = value; } - get lightMapSize () { + get lightMapSize (): number { return this._lightMapSize; } @@ -345,7 +345,7 @@ export class TerrainAsset extends Asset { this._weightMapSize = value; } - get weightMapSize () { + get weightMapSize (): number { return this._weightMapSize; } @@ -357,7 +357,7 @@ export class TerrainAsset extends Asset { this._heights = value; } - get heights () { + get heights (): Uint16Array { return this._heights; } @@ -369,7 +369,7 @@ export class TerrainAsset extends Asset { this._normals = value; } - get normals () { + get normals (): Float32Array { return this._normals; } @@ -381,7 +381,7 @@ export class TerrainAsset extends Asset { this._weights = value; } - get weights () { + get weights (): Uint8Array { return this._weights; } @@ -393,7 +393,7 @@ export class TerrainAsset extends Asset { this._layerBuffer = value; } - get layerBuffer () { + get layerBuffer (): number[] { return this._layerBuffer; } @@ -405,11 +405,11 @@ export class TerrainAsset extends Asset { this._layerInfos = value; } - get layerInfos () { + get layerInfos (): TerrainLayerInfo[] { return this._layerInfos; } - get layerBinaryInfos () { + get layerBinaryInfos (): TerrainLayerBinaryInfo[] { return this._layerBinaryInfos; } @@ -420,7 +420,7 @@ export class TerrainAsset extends Asset { * @param yBlock block index y * @param layerId layer id */ - public getLayer (xBlock: number, yBlock: number, layerId: number) { + public getLayer (xBlock: number, yBlock: number, layerId: number): number { const blockId = yBlock * this.blockCount[0] + xBlock; const index = blockId * 4 + layerId; @@ -431,17 +431,17 @@ export class TerrainAsset extends Asset { return -1; } - public getHeight (i: number, j: number) { + public getHeight (i: number, j: number): number { const vertexCountX = this._blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1; return (this._heights[j * vertexCountX + i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY; } - public getVertexCountI () { + public getVertexCountI (): number { if (this._blockCount.length < 1) return 0; return this._blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1; } - public getVertexCountJ () { + public getVertexCountJ (): number { if (this._blockCount.length < 2) return 0; return this._blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1; } @@ -449,14 +449,14 @@ export class TerrainAsset extends Asset { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _setNativeData (_nativeData: Uint8Array) { + public _setNativeData (_nativeData: Uint8Array): void { this._data = _nativeData; } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _loadNativeData (_nativeData: Uint8Array) { + public _loadNativeData (_nativeData: Uint8Array): boolean { if (!_nativeData || _nativeData.length === 0) { return false; } diff --git a/cocos/terrain/terrain-lod.ts b/cocos/terrain/terrain-lod.ts index 45bb73f27f5..f0489aa14d4 100644 --- a/cocos/terrain/terrain-lod.ts +++ b/cocos/terrain/terrain-lod.ts @@ -38,7 +38,7 @@ export class TerrainLodKey { public west = 0; public east = 0; - public equals (rk: TerrainLodKey) { + public equals (rk: TerrainLodKey): boolean { return this.level === rk.level && this.north === rk.north && this.south === rk.south && this.west === rk.west && this.east === rk.east; } } @@ -57,7 +57,7 @@ export class TerrainIndexData { } export class TerrainLod { - public static mapIndex (i: number, j: number, k: number) { + public static mapIndex (i: number, j: number, k: number): number { return i * (TERRAIN_LOD_LEVELS * TERRAIN_LOD_LEVELS) + j * TERRAIN_LOD_LEVELS + k; } @@ -142,7 +142,7 @@ export class TerrainLod { } } - public getIndexData (k: TerrainLodKey) { + public getIndexData (k: TerrainLodKey): TerrainIndexData | null { for (let i = 0; i < this._indexMap.length; ++i) { if (this._indexMap[i].key.equals(k)) { return this._indexMap[i]; @@ -152,7 +152,7 @@ export class TerrainLod { return null; } - private _genBodyIndex (level: number) { + private _genBodyIndex (level: number): void { const step = 1 << level; let tiles = TERRAIN_LOD_TILES >> level; let start = 0; @@ -205,7 +205,7 @@ export class TerrainLod { this._bodyIndexPool[level].indices = indices; } - private _genConnecterIndexNorth (level: number, connecter: number) { + private _genConnecterIndexNorth (level: number, connecter: number): void { const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_NORTH_INDEX); if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { @@ -248,7 +248,7 @@ export class TerrainLod { this._connecterIndexPool[connecterIndex].indices = indices; } - private _genConnecterIndexSouth (level: number, connecter: number) { + private _genConnecterIndexSouth (level: number, connecter: number): void { const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_SOUTH_INDEX); if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { @@ -291,7 +291,7 @@ export class TerrainLod { this._connecterIndexPool[connecterIndex].indices = indices; } - private _genConnecterIndexWest (level: number, connecter: number) { + private _genConnecterIndexWest (level: number, connecter: number): void { const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_WEST_INDEX); if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { @@ -334,7 +334,7 @@ export class TerrainLod { this._connecterIndexPool[connecterIndex].indices = indices; } - private _genConnecterIndexEast (level: number, connecter: number) { + private _genConnecterIndexEast (level: number, connecter: number): void { const connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_EAST_INDEX); if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { @@ -377,11 +377,11 @@ export class TerrainLod { this._connecterIndexPool[connecterIndex].indices = indices; } - private _getConnenterIndex (i: number, j: number, k: number) { + private _getConnenterIndex (i: number, j: number, k: number): TerrainIndexPool { return this._connecterIndexPool[TerrainLod.mapIndex(i, j, k)]; } - private _genIndexData (k: TerrainLodKey) { + private _genIndexData (k: TerrainLodKey): TerrainIndexData | null { let data = this.getIndexData(k); if (data != null) { return data; diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index 4ecc661864f..66855790fda 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -40,7 +40,7 @@ import { Camera } from '../render-scene/scene/camera'; import { Root } from '../root'; import { HeightField } from './height-field'; import { legacyCC } from '../core/global-exports'; -import { TerrainLod, TerrainLodKey, TERRAIN_LOD_LEVELS, TERRAIN_LOD_MAX_DISTANCE } from './terrain-lod'; +import { TerrainLod, TerrainLodKey, TERRAIN_LOD_LEVELS, TERRAIN_LOD_MAX_DISTANCE, TerrainIndexData } from './terrain-lod'; import { TerrainAsset, TerrainLayerInfo, TERRAIN_HEIGHT_BASE, TERRAIN_HEIGHT_FACTORY, TERRAIN_BLOCK_TILE_COMPLEXITY, TERRAIN_BLOCK_VERTEX_SIZE, TERRAIN_BLOCK_VERTEX_COMPLEXITY, TERRAIN_MAX_LAYER_COUNT, TERRAIN_HEIGHT_FMIN, TERRAIN_HEIGHT_FMAX, TERRAIN_MAX_BLEND_LAYERS, TERRAIN_DATA_VERSION5 } from './terrain-asset'; @@ -93,7 +93,7 @@ export class TerrainInfo { * @en terrain size * @zh 地形大小 */ - public get size () { + public get size (): Size { const sz = new Size(0, 0); sz.width = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize; sz.height = this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize; @@ -104,7 +104,7 @@ export class TerrainInfo { * @en tile count * @zh 栅格数量 */ - public get tileCount () { + public get tileCount (): number[] { const _tileCount = [0, 0]; _tileCount[0] = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY; _tileCount[1] = this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY; @@ -115,7 +115,7 @@ export class TerrainInfo { * @en vertex count * @zh 顶点数量 */ - public get vertexCount () { + public get vertexCount (): number[] { const _vertexCount = this.tileCount; _vertexCount[0] += 1; _vertexCount[1] += 1; @@ -204,7 +204,7 @@ class TerrainRenderable extends ModelRenderer { */ public _lightmap: Texture2D|null = null; - public destroy () { + public destroy (): boolean { // this._invalidMaterial(); if (this._model != null) { legacyCC.director.root.destroyModel(this._model); @@ -217,7 +217,7 @@ class TerrainRenderable extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _destroyModel () { + public _destroyModel (): void { // this._invalidMaterial(); if (this._model != null) { legacyCC.director.root.destroyModel(this._model); @@ -233,7 +233,7 @@ class TerrainRenderable extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _invalidMaterial () { + public _invalidMaterial (): void { if (this._currentMaterial == null) { return; } @@ -250,7 +250,7 @@ class TerrainRenderable extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateMaterial (block: TerrainBlock, init: boolean) { + public _updateMaterial (block: TerrainBlock, init: boolean): boolean { if (this._meshData == null || this._model == null) { return false; } @@ -296,7 +296,7 @@ class TerrainRenderable extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateLightingmap (texture: Texture2D | null, uvParam: Vec4) { + public _updateLightingmap (texture: Texture2D | null, uvParam: Vec4): void { if (this._model == null) { return; } @@ -309,7 +309,7 @@ class TerrainRenderable extends ModelRenderer { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onMaterialModified (idx: number, mtl: Material|null) { + public _onMaterialModified (idx: number, mtl: Material|null): void { if (this._model == null) { return; } @@ -319,13 +319,13 @@ class TerrainRenderable extends ModelRenderer { /** * @engineInternal */ - public _onRebuildPSO (idx: number, material: Material) { + public _onRebuildPSO (idx: number, material: Material): void { if (this._model) { this._model.setSubModelMaterial(idx, material); } } - protected _clearMaterials () { + protected _clearMaterials (): void { if (this._model == null) { return; } @@ -333,7 +333,7 @@ class TerrainRenderable extends ModelRenderer { this._onMaterialModified(0, null); } - protected _onUpdateReceiveDirLight (visibility: number, forceClose = false) { + protected _onUpdateReceiveDirLight (visibility: number, forceClose = false): void { if (!this._model) { return; } if (forceClose) { this._model.receiveDirLight = false; @@ -347,7 +347,7 @@ class TerrainRenderable extends ModelRenderer { } } - protected _updateReceiveDirLight () { + protected _updateReceiveDirLight (): void { const scene = this.node.scene; if (!scene || !scene.renderScene) { return; } const mainLight = scene.renderScene.mainLight; @@ -361,7 +361,7 @@ class TerrainRenderable extends ModelRenderer { } } - private _getBuiltinMaterial () { + private _getBuiltinMaterial (): Material { return builtinResMgr.get('missing-material'); } } @@ -421,7 +421,7 @@ export class TerrainBlock { this._renderable = this._node.addComponent(TerrainRenderable); } - public build () { + public build (): void { const gfxDevice = director.root!.device; // vertex buffer @@ -469,7 +469,7 @@ export class TerrainBlock { } } - public rebuild () { + public rebuild (): void { this._updateHeight(); this._updateWeightMap(); @@ -477,7 +477,7 @@ export class TerrainBlock { this._updateMaterial(false); } - public destroy () { + public destroy (): void { this.visible = false; this._renderable._destroyModel(); @@ -489,7 +489,7 @@ export class TerrainBlock { } } - public update () { + public update (): void { this._updateMaterial(false); if (this.lightmap !== this._renderable._lightmap) { @@ -500,11 +500,11 @@ export class TerrainBlock { const usePBR = this._terrain.usePBR; // eslint-disable-next-line arrow-body-style - const getDetailTex = (layer: TerrainLayer|null) => { + const getDetailTex = (layer: TerrainLayer|null): Texture2D | null => { return layer !== null ? layer.detailMap : null; }; - const getNormalTex = (layer: TerrainLayer|null) => { + const getNormalTex = (layer: TerrainLayer|null): Texture2D | null => { let normalTex = layer !== null ? layer.normalMap : null; if (normalTex === null) { normalTex = legacyCC.builtinResMgr.get('normal-texture'); @@ -643,7 +643,7 @@ export class TerrainBlock { /** * @engineInternal */ - public _buildLodInfo () { + public _buildLodInfo (): void { const vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY); this._buildVertexData(vertexData); // update lod @@ -655,7 +655,7 @@ export class TerrainBlock { /** * @engineInternal */ - public _updateLevel (camPos: Vec3) { + public _updateLevel (camPos: Vec3): void { const maxLevel = TERRAIN_LOD_LEVELS - 1; const bbMin = new Vec3(); @@ -680,18 +680,18 @@ export class TerrainBlock { } } - public setBrushMaterial (mtl: Material|null) { + public setBrushMaterial (mtl: Material|null): void { if (this._renderable._brushMaterial !== mtl) { this._renderable._invalidMaterial(); this._renderable._brushMaterial = mtl; } } - public _getBrushMaterial () { + public _getBrushMaterial (): Material | null { return this._renderable ? this._renderable._brushMaterial : null; } - public _getBrushPass () { + public _getBrushPass (): Pass | null { return this._renderable ? this._renderable._brushPass : null; } @@ -699,7 +699,7 @@ export class TerrainBlock { * @en valid * @zh 是否有效 */ - get valid () { + get valid (): boolean { if (this._terrain === null) { return false; } @@ -718,7 +718,7 @@ export class TerrainBlock { * @en get current material * @zh 获得当前的材质 */ - get material () { + get material (): Material | null { return this._renderable ? this._renderable._currentMaterial : null; } @@ -726,7 +726,7 @@ export class TerrainBlock { * @en get layers * @zh 获得纹理层索引 */ - get layers () { + get layers (): number[] { return this._terrain.getBlockLayers(this._index[0], this._index[1]); } @@ -734,7 +734,7 @@ export class TerrainBlock { * @en get weight map * @zh 获得权重图 */ - get weightmap () { + get weightmap (): Texture2D | null { return this._weightMap; } @@ -742,7 +742,7 @@ export class TerrainBlock { * @en get light map * @zh 获得光照图 */ - get lightmap () { + get lightmap (): Texture2D | null { return this._lightmapInfo ? this._lightmapInfo.texture : null; } @@ -750,7 +750,7 @@ export class TerrainBlock { * @en get light map uv parameter * @zh 获得光照图纹理坐标参数 */ - get lightmapUVParam () { + get lightmapUVParam (): Vec4 { if (this._lightmapInfo != null) { return new Vec4(this._lightmapInfo.UOff, this._lightmapInfo.VOff, this._lightmapInfo.UScale, this._lightmapInfo.VScale); } @@ -777,7 +777,7 @@ export class TerrainBlock { } } - get visible () { + get visible (): boolean { if (this._renderable._model !== null) { return this._renderable._model.scene !== null; } @@ -789,7 +789,7 @@ export class TerrainBlock { * @en get terrain owner * @zh 获得地形对象 */ - public getTerrain () { + public getTerrain (): Terrain { return this._terrain; } @@ -797,7 +797,7 @@ export class TerrainBlock { * @en get index * @zh 获得地形索引 */ - public getIndex () { + public getIndex (): number[] { return this._index; } @@ -805,7 +805,7 @@ export class TerrainBlock { * @en get rect bound * @zh 获得地形矩形包围体 */ - public getRect () { + public getRect (): Rect { const rect = new Rect(); rect.x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY; rect.y = this._index[1] * TERRAIN_BLOCK_TILE_COMPLEXITY; @@ -819,7 +819,7 @@ export class TerrainBlock { * @en set layer * @zh 设置纹理层 */ - public setLayer (index: number, layerId: number) { + public setLayer (index: number, layerId: number): void { if (this.layers[index] !== layerId) { this._terrain.setBlockLayer(this._index[0], this._index[1], index, layerId); this._renderable._invalidMaterial(); @@ -831,7 +831,7 @@ export class TerrainBlock { * @en get layer * @zh 获得纹理层 */ - public getLayer (index: number) { + public getLayer (index: number): number { return this.layers[index]; } @@ -839,7 +839,7 @@ export class TerrainBlock { * @en get max layer index * @zh 获得最大纹理索引 */ - public getMaxLayer () { + public getMaxLayer (): number { if (this.layers[3] >= 0) { return 3; } @@ -869,11 +869,11 @@ export class TerrainBlock { }; } - public _invalidMaterial () { + public _invalidMaterial (): void { this._renderable._invalidMaterial(); } - public _updateMaterial (init: boolean) { + public _updateMaterial (init: boolean): void { if (this._renderable._updateMaterial(this, init)) { // Need set wrap mode clamp to border if (this.lightmap !== null) { @@ -884,7 +884,7 @@ export class TerrainBlock { } } - public _updateHeight () { + public _updateHeight (): void { if (this._renderable._meshData == null) { return; } @@ -902,7 +902,7 @@ export class TerrainBlock { this._updateIndexBuffer(); } - public _updateWeightMap () { + public _updateWeightMap (): void { const nlayers = this.getMaxLayer(); if (nlayers === 0) { @@ -943,7 +943,7 @@ export class TerrainBlock { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateLightmap (info: TerrainBlockLightmapInfo) { + public _updateLightmap (info: TerrainBlockLightmapInfo): void { this._lightmapInfo = info; this._invalidMaterial(); } @@ -951,7 +951,7 @@ export class TerrainBlock { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateLod () { + public _updateLod (): void { const key = new TerrainLodKey(); key.level = this._lodLevel; key.north = this._lodLevel; @@ -1002,7 +1002,7 @@ export class TerrainBlock { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _resetLod () { + public _resetLod (): void { const key = new TerrainLodKey(); key.level = 0; key.north = 0; @@ -1021,7 +1021,7 @@ export class TerrainBlock { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateIndexBuffer () { + public _updateIndexBuffer (): void { if (this._renderable._meshData === null) { return; } @@ -1042,19 +1042,19 @@ export class TerrainBlock { model.inputAssembler.indexCount = indexData.size; } - private _getHeight (x: number, y: number, verts: Float32Array) { + private _getHeight (x: number, y: number, verts: Float32Array): number { const idx = TERRAIN_BLOCK_VERTEX_COMPLEXITY * y + x; return verts[idx * TERRAIN_BLOCK_VERTEX_SIZE + 1]; } - private _updateLodBuffer (vertecs: Float32Array) { + private _updateLodBuffer (vertecs: Float32Array): void { this._lodLevel = 0; this._lodKey = new TerrainLodKey(); this._calcErrorMetrics(vertecs); this._calcLevelDistances(vertecs); } - private _calcErrorMetrics (vertecs: Float32Array) { + private _calcErrorMetrics (vertecs: Float32Array): void { this._errorMetrics[0] = 0; for (let i = 1; i < TERRAIN_LOD_LEVELS; ++i) { @@ -1066,7 +1066,7 @@ export class TerrainBlock { } } - private _calcErrorMetric (level: number, vertecs: Float32Array) { + private _calcErrorMetric (level: number, vertecs: Float32Array): number { let err = 0.0; const step = 1 << level; const xSectionVerts = TERRAIN_BLOCK_VERTEX_COMPLEXITY; @@ -1132,7 +1132,7 @@ export class TerrainBlock { return err; } - private _calcLevelDistances (vertecs: Float32Array) { + private _calcLevelDistances (vertecs: Float32Array): void { const pixelerr = 4; const resolution = 768; const c = 1.0 / (2 * pixelerr / resolution); @@ -1144,7 +1144,7 @@ export class TerrainBlock { } } - private _buildVertexData (vertexData: Float32Array) { + private _buildVertexData (vertexData: Float32Array): void { let index = 0; for (let j = 0; j < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++j) { for (let i = 0; i < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++i) { @@ -1165,7 +1165,7 @@ export class TerrainBlock { } } - private _buildBoundingBox () { + private _buildBoundingBox (): void { this._bbMin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._bbMax.set(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE); for (let j = 0; j < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++j) { @@ -1300,7 +1300,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public get _asset () { + public get _asset (): TerrainAsset | null { return this.__asset; } @@ -1321,7 +1321,7 @@ export class Terrain extends Component { } } - public get effectAsset () { + public get effectAsset (): EffectAsset | null { return this._effectAsset; } @@ -1330,7 +1330,7 @@ export class Terrain extends Component { * @zh 是否接受阴影 */ @editable - get receiveShadow () { + get receiveShadow (): boolean { return this._receiveShadow; } @@ -1346,7 +1346,7 @@ export class Terrain extends Component { * @zh 是否使用法线贴图 */ @editable - get useNormalMap () { + get useNormalMap (): boolean { return this._useNormalmap; } @@ -1362,7 +1362,7 @@ export class Terrain extends Component { * @zh 是否使用物理材质 */ @editable - get usePBR () { + get usePBR (): boolean { return this._usePBR; } @@ -1378,7 +1378,7 @@ export class Terrain extends Component { * @zh 是否允许lod */ @editable - get lodEnable () { + get lodEnable (): boolean { return this._lodEnable; } @@ -1421,7 +1421,7 @@ export class Terrain extends Component { * @zh Lod偏移距离 */ @editable - get LodBias () { + get LodBias (): number { return this._lodBias; } @@ -1433,7 +1433,7 @@ export class Terrain extends Component { * @en get terrain size * @zh 获得地形大小 */ - public get size () { + public get size (): Size { const sz = new Size(0, 0); sz.width = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize; sz.height = this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize; @@ -1444,7 +1444,7 @@ export class Terrain extends Component { * @en get tile size * @zh 获得栅格大小 */ - get tileSize () { + get tileSize (): number { return this._tileSize; } @@ -1452,7 +1452,7 @@ export class Terrain extends Component { * @en get tile count * @zh 获得栅格数量 */ - public get tileCount () { + public get tileCount (): number[] { return [this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY, this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY]; } @@ -1460,7 +1460,7 @@ export class Terrain extends Component { * @en get vertex count * @zh 获得顶点数量 */ - public get vertexCount () { + public get vertexCount (): number[] { const _vertexCount = this.tileCount; _vertexCount[0] += 1; _vertexCount[1] += 1; @@ -1472,7 +1472,7 @@ export class Terrain extends Component { * @en get block count * @zh 获得地形块数量 */ - get blockCount () { + get blockCount (): number[] { return this._blockCount; } @@ -1480,7 +1480,7 @@ export class Terrain extends Component { * @en get light map size * @zh 获得光照图大小 */ - get lightMapSize () { + get lightMapSize (): number { return this._lightMapSize; } @@ -1488,7 +1488,7 @@ export class Terrain extends Component { * @en get weight map size * @zh 获得权重图大小 */ - get weightMapSize () { + get weightMapSize (): number { return this._weightMapSize; } @@ -1496,7 +1496,7 @@ export class Terrain extends Component { * @en get height buffer * @zh 获得高度缓存 */ - get heights () { + get heights (): Uint16Array { return this._heights; } @@ -1504,7 +1504,7 @@ export class Terrain extends Component { * @en get weight buffer * @zh 获得权重缓存 */ - get weights () { + get weights (): Uint8Array { return this._weights; } @@ -1512,7 +1512,7 @@ export class Terrain extends Component { * @en check valid * @zh 检测是否有效 */ - get valid () { + get valid (): boolean { return this._blocks.length > 0; } @@ -1521,7 +1521,7 @@ export class Terrain extends Component { * @zh 获得地形信息 */ @type(TerrainInfo) - public get info () { + public get info (): TerrainInfo { const ti = new TerrainInfo(); ti.tileSize = this.tileSize; ti.blockCount[0] = this.blockCount[0]; @@ -1536,7 +1536,7 @@ export class Terrain extends Component { * @en build * @zh 构建地形 */ - public build (info: TerrainInfo) { + public build (info: TerrainInfo): void { this._tileSize = info.tileSize; this._blockCount[0] = info.blockCount[0]; this._blockCount[1] = info.blockCount[1]; @@ -1550,7 +1550,7 @@ export class Terrain extends Component { * @en rebuild * @zh 重建地形 */ - public rebuild (info: TerrainInfo) { + public rebuild (info: TerrainInfo): void { for (let i = 0; i < this._blocks.length; ++i) { this._blocks[i].destroy(); } @@ -1597,7 +1597,7 @@ export class Terrain extends Component { * @en import height field * @zh 导入高度图 */ - public importHeightField (hf: HeightField, heightScale: number) { + public importHeightField (hf: HeightField, heightScale: number): void { let index = 0; for (let j = 0; j < this.vertexCount[1]; ++j) { for (let i = 0; i < this.vertexCount[0]; ++i) { @@ -1622,7 +1622,7 @@ export class Terrain extends Component { * @en export height field * @zh 导出高度图 */ - public exportHeightField (hf: HeightField, heightScale: number) { + public exportHeightField (hf: HeightField, heightScale: number): void { let index = 0; for (let j = 0; j < hf.h; ++j) { for (let i = 0; i < hf.w; ++i) { @@ -1640,7 +1640,7 @@ export class Terrain extends Component { } } - public exportAsset () { + public exportAsset (): TerrainAsset { const asset = new TerrainAsset(); asset.tileSize = this.tileSize; @@ -1663,7 +1663,7 @@ export class Terrain extends Component { return asset; } - public exportLayerListToAsset (asset: TerrainAsset) { + public exportLayerListToAsset (asset: TerrainAsset): void { asset.layerInfos.length = 0; for (let i = 0; i < this._layerList.length; ++i) { const temp = this._layerList[i]; @@ -1680,7 +1680,7 @@ export class Terrain extends Component { } } - public getEffectAsset () { + public getEffectAsset (): EffectAsset { if (this._effectAsset === null) { return legacyCC.EffectAsset.get(TERRAIN_EFFECT_UUID) as EffectAsset; } @@ -1688,7 +1688,7 @@ export class Terrain extends Component { return this._effectAsset; } - public onEnable () { + public onEnable (): void { if (this._blocks.length === 0) { this._buildImp(); } @@ -1700,7 +1700,7 @@ export class Terrain extends Component { (legacyCC.director.root as Root).pipelineEvent.on(PipelineEventType.RENDER_CAMERA_BEGIN, this.onUpdateFromCamera, this); } - public onDisable () { + public onDisable (): void { (legacyCC.director.root as Root).pipelineEvent.off(PipelineEventType.RENDER_CAMERA_BEGIN, this.onUpdateFromCamera, this); for (let i = 0; i < this._blocks.length; ++i) { @@ -1708,7 +1708,7 @@ export class Terrain extends Component { } } - public onDestroy () { + public onDestroy (): void { for (let i = 0; i < this._blocks.length; ++i) { this._blocks[i].destroy(); } @@ -1726,12 +1726,12 @@ export class Terrain extends Component { } } - public onRestore () { + public onRestore (): void { this.onEnable(); this._buildImp(true); } - public update (deltaTime: number) { + public update (deltaTime: number): void { for (let i = 0; i < this._blocks.length; ++i) { this._blocks[i].update(); } @@ -1758,7 +1758,7 @@ export class Terrain extends Component { * @en add layer * @zh 添加纹理层 */ - public addLayer (layer: TerrainLayer) { + public addLayer (layer: TerrainLayer): number { for (let i = 0; i < this._layerList.length; ++i) { if (this._layerList[i] === null || (this._layerList[i] && this._layerList[i]?.detailMap === null)) { this._layerList[i] = layer; @@ -1776,7 +1776,7 @@ export class Terrain extends Component { * @en set layer * @zh 设置纹理层 */ - public setLayer (i: number, layer: TerrainLayer) { + public setLayer (i: number, layer: TerrainLayer): void { this._layerList[i] = layer; if (this._asset) { this.exportLayerListToAsset(this._asset); @@ -1787,7 +1787,7 @@ export class Terrain extends Component { * @en remove layer * @zh 移除纹理层 */ - public removeLayer (id: number) { + public removeLayer (id: number): void { this._layerList[id] = null; if (this._asset) { this.exportLayerListToAsset(this._asset); @@ -1798,7 +1798,7 @@ export class Terrain extends Component { * @en get layer * @zh 获得纹理层 */ - public getLayer (id: number) { + public getLayer (id: number): TerrainLayer | null { if (id === -1) { return null; } @@ -1810,7 +1810,7 @@ export class Terrain extends Component { * @en get position * @zh 获得地形上的位置 */ - public getPosition (i: number, j: number) { + public getPosition (i: number, j: number): Vec3 { const x = i * this._tileSize; const z = j * this._tileSize; const y = this.getHeight(i, j); @@ -1818,7 +1818,7 @@ export class Terrain extends Component { return new Vec3(x, y, z); } - public getHeightField () { + public getHeightField (): Uint16Array { return this._heights; } @@ -1826,7 +1826,7 @@ export class Terrain extends Component { * @en set height * @zh 设置地形上的高度 */ - public setHeight (i: number, j: number, h: number) { + public setHeight (i: number, j: number, h: number): void { h = clamp(h, TERRAIN_HEIGHT_FMIN, TERRAIN_HEIGHT_FMAX); this._heights[j * this.vertexCount[0] + i] = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY; } @@ -1835,7 +1835,7 @@ export class Terrain extends Component { * @en get height * @zh 获得地形上的高度 */ - public getHeight (i: number, j: number) { + public getHeight (i: number, j: number): number { return (this._heights[j * this.vertexCount[0] + i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY; } @@ -1843,7 +1843,7 @@ export class Terrain extends Component { * @en set height * @zh 设置高度 */ - public getHeightClamp (i: number, j: number) { + public getHeightClamp (i: number, j: number): number { i = clamp(i, 0, this.vertexCount[0] - 1); j = clamp(j, 0, this.vertexCount[1] - 1); @@ -1854,7 +1854,7 @@ export class Terrain extends Component { * @en get height by point * @zh 根据点的坐标获得高度 */ - public getHeightAt (x: number, y: number) { + public getHeightAt (x: number, y: number): number | null { const fx = x / this.tileSize; const fy = y / this.tileSize; @@ -1897,7 +1897,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _setNormal (i: number, j: number, n: Vec3) { + public _setNormal (i: number, j: number, n: Vec3): void { const index = j * this.vertexCount[0] + i; this._normals[index * 3 + 0] = n.x; @@ -1909,7 +1909,7 @@ export class Terrain extends Component { * @en get normal * @zh 获得法线 */ - public getNormal (i: number, j: number) { + public getNormal (i: number, j: number): Vec3 { const index = j * this.vertexCount[0] + i; const n = new Vec3(); @@ -1924,7 +1924,7 @@ export class Terrain extends Component { * @en get normal by point * @zh 根据点的坐标获得法线 */ - public getNormalAt (x: number, y: number) { + public getNormalAt (x: number, y: number): Vec3 | null { const fx = x / this.tileSize; const fy = y / this.tileSize; @@ -1977,7 +1977,7 @@ export class Terrain extends Component { * @en set weight * @zh 设置权重 */ - public setWeight (i: number, j: number, w: Vec4) { + public setWeight (i: number, j: number, w: Vec4): void { const index = j * this._weightMapSize * this._blockCount[0] + i; this._weights[index * 4 + 0] = w.x * 255; @@ -1990,7 +1990,7 @@ export class Terrain extends Component { * @en get weight * @zh 获得权重 */ - public getWeight (i: number, j: number) { + public getWeight (i: number, j: number): Vec4 { const index = j * this._weightMapSize * this._blockCount[0] + i; const w = new Vec4(); @@ -2006,7 +2006,7 @@ export class Terrain extends Component { * @en get normal by point * @zh 根据点的坐标获得权重 */ - public getWeightAt (x: number, y: number) { + public getWeightAt (x: number, y: number): Vec4 | null { const uWeigthComplexity = this.weightMapSize * this.blockCount[0]; const vWeigthComplexity = this.weightMapSize * this.blockCount[1]; if (uWeigthComplexity === 0 || vWeigthComplexity === 0) { @@ -2061,7 +2061,7 @@ export class Terrain extends Component { * @en get max weight layer by point * @zh 根据点的坐标获得权重最大的纹理层 */ - public getMaxWeightLayerAt (x: number, y: number) { + public getMaxWeightLayerAt (x: number, y: number): TerrainLayer | null { const uWeigthComplexity = this.weightMapSize * this.blockCount[0]; const vWeigthComplexity = this.weightMapSize * this.blockCount[1]; if (uWeigthComplexity === 0 || vWeigthComplexity === 0) { @@ -2102,7 +2102,7 @@ export class Terrain extends Component { * @en get block layers * @zh 获得地形块纹理层 */ - public getBlockLayers (i: number, j: number) { + public getBlockLayers (i: number, j: number): number[] { const layerIndex = (j * this._blockCount[0] + i) * TERRAIN_MAX_BLEND_LAYERS; return [ @@ -2117,7 +2117,7 @@ export class Terrain extends Component { * @en get block layer * @zh 获得地形块纹理层 */ - public getBlockLayer (i: number, j: number, index: number) { + public getBlockLayer (i: number, j: number, index: number): number { const layerIndex = (j * this._blockCount[0] + i) * TERRAIN_MAX_BLEND_LAYERS; return this._layerBuffer[layerIndex + index]; } @@ -2126,7 +2126,7 @@ export class Terrain extends Component { * @en set block layer * @zh 获得地形块层 */ - public setBlockLayer (i: number, j: number, index: number, layerId: number) { + public setBlockLayer (i: number, j: number, index: number, layerId: number): void { const layerIndex = (j * this._blockCount[0] + i) * TERRAIN_MAX_BLEND_LAYERS; this._layerBuffer[layerIndex + index] = layerId; } @@ -2135,7 +2135,7 @@ export class Terrain extends Component { * @en get block * @zh 获得地形块对象 */ - public getBlock (i: number, j: number) { + public getBlock (i: number, j: number): TerrainBlock { return this._blocks[j * this._blockCount[0] + i]; } @@ -2143,7 +2143,7 @@ export class Terrain extends Component { * @en get all blocks * @zh 获得地形块缓存 */ - public getBlocks () { + public getBlocks (): TerrainBlock[] { return this._blocks; } @@ -2155,7 +2155,7 @@ export class Terrain extends Component { * @param step ray step * @param worldSpace is world space */ - public rayCheck (start: Vec3, dir: Vec3, step: number, worldSpace = true) { + public rayCheck (start: Vec3, dir: Vec3, step: number, worldSpace = true): Vec3 | null { const MAX_COUNT = 2000; const trace = start; @@ -2210,7 +2210,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.1, this is an engine private interface that will be removed in the future. */ - public _createSharedIndexBuffer () { + public _createSharedIndexBuffer (): Buffer { // initialize shared index buffer const gfxDevice = deviceManager.gfxDevice; @@ -2259,7 +2259,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _getSharedIndexBuffer () { + public _getSharedIndexBuffer (): Buffer { if (this._sharedLodIndexBuffer !== null) { return this._sharedLodIndexBuffer; } @@ -2284,7 +2284,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _getIndexData (key: TerrainLodKey) { + public _getIndexData (key: TerrainLodKey): TerrainIndexData | null { if (this._sharedLodIndexBuffer !== null && this._lod !== null) { return this._lod.getIndexData(key); } @@ -2295,7 +2295,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _resetLightmap (enble: boolean) { + public _resetLightmap (enble: boolean): void { this._lightmapInfos.length = 0; if (enble) { for (let i = 0; i < this._blockCount[0] * this._blockCount[1]; ++i) { @@ -2307,7 +2307,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateLightmap (blockId: number, tex: Texture2D|null, uOff: number, vOff: number, uScale: number, vScale: number) { + public _updateLightmap (blockId: number, tex: Texture2D|null, uOff: number, vOff: number, uScale: number, vScale: number): void { if (tex) { // ensure the lightmap infos is initialized if (this._lightmapInfos.length == 0) { @@ -2330,7 +2330,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _getLightmapInfo (i: number, j: number) { + public _getLightmapInfo (i: number, j: number): TerrainBlockLightmapInfo | null { const index = j * this._blockCount[0] + i; return index < this._lightmapInfos.length ? this._lightmapInfos[index] : null; } @@ -2338,7 +2338,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _calcNormal (x: number, z: number) { + public _calcNormal (x: number, z: number): Vec3 { let flip = 1; const here = this.getPosition(x, z); let right: Vec3; @@ -2373,7 +2373,7 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _buildNormals () { + public _buildNormals (): void { let index = 0; for (let y = 0; y < this.vertexCount[1]; ++y) { for (let x = 0; x < this.vertexCount[0]; ++x) { @@ -2387,7 +2387,7 @@ export class Terrain extends Component { } } - private _buildImp (restore = false) { + private _buildImp (restore = false): void { if (this.valid) { return; } @@ -2503,7 +2503,7 @@ export class Terrain extends Component { } } - private _rebuildHeights (info: TerrainInfo) { + private _rebuildHeights (info: TerrainInfo): boolean { if (this.vertexCount[0] === info.vertexCount[0] && this.vertexCount[1] === info.vertexCount[1]) { return false; } @@ -2530,7 +2530,7 @@ export class Terrain extends Component { return true; } - private _rebuildLayerBuffer (info: TerrainInfo) { + private _rebuildLayerBuffer (info: TerrainInfo): boolean { if (this.blockCount[0] === info.blockCount[0] && this.blockCount[1] === info.blockCount[1]) { return false; } @@ -2559,7 +2559,7 @@ export class Terrain extends Component { return true; } - private _rebuildWeights (info: TerrainInfo) { + private _rebuildWeights (info: TerrainInfo): boolean { const oldWeightMapSize = this._weightMapSize; const oldWeightMapComplexityU = this._weightMapSize * this._blockCount[0]; const oldWeightMapComplexityV = this._weightMapSize * this._blockCount[1]; @@ -2584,7 +2584,7 @@ export class Terrain extends Component { const h = Math.min(info.blockCount[1], this._blockCount[1]); // get weight - const getOldWeight = (_i: number, _j: number, _weights: Uint8Array) => { + const getOldWeight = (_i: number, _j: number, _weights: Uint8Array): Vec4 => { const index = _j * oldWeightMapComplexityU + _i; const weight = new Vec4(); @@ -2597,7 +2597,7 @@ export class Terrain extends Component { }; // sample weight - const sampleOldWeight = (_x: number, _y: number, _xOff: number, _yOff: number, _weights: Uint8Array) => { + const sampleOldWeight = (_x: number, _y: number, _xOff: number, _yOff: number, _weights: Uint8Array): Vec4 => { const ix0 = Math.floor(_x); const iz0 = Math.floor(_y); const ix1 = Math.min(ix0 + 1, oldWeightMapSize - 1); diff --git a/cocos/tiledmap/assembler/simple.ts b/cocos/tiledmap/assembler/simple.ts index a6b5f1a8228..ab5269a6900 100644 --- a/cocos/tiledmap/assembler/simple.ts +++ b/cocos/tiledmap/assembler/simple.ts @@ -183,7 +183,7 @@ texture coordinate a c b d */ -function _flipTexture (inGrid: TiledGrid, gid: MixedGID) { +function _flipTexture (inGrid: TiledGrid, gid: MixedGID): void { if (inGrid._rotated) { // 2:b 1:a // 4:d 3:c @@ -246,7 +246,7 @@ texture coordinate b c d */ -function _flipDiamondTileTexture (inGrid: TiledGrid, gid: MixedGID) { +function _flipDiamondTileTexture (inGrid: TiledGrid, gid: MixedGID): void { if (inGrid._rotated) { // 2:b // 4:d 1:a @@ -301,7 +301,7 @@ function _flipDiamondTileTexture (inGrid: TiledGrid, gid: MixedGID) { } } -function packRenderData () { +function packRenderData (): void { if (_fillCount < 1 || !_curTexture) return; const vbCount = 4 * _fillCount; @@ -326,7 +326,7 @@ function packRenderData () { // rowMoveDir is -1 or 1, -1 means decrease, 1 means increase // colMoveDir is -1 or 1, -1 means decrease, 1 means increase function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: number, row: number }, - rowMoveDir: number, colMoveDir: number, comp: TiledLayer) { + rowMoveDir: number, colMoveDir: number, comp: TiledLayer): void { // show nothing if (rightTop.row < 0 || rightTop.col < 0) return; @@ -536,7 +536,7 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: } function fillByTiledNode (tiledNode: Node, color: Float32Array, vbuf: Float32Array, - left: number, right: number, top: number, bottom: number, diamondTile: boolean) { + left: number, right: number, top: number, bottom: number, diamondTile: boolean): void { const vertStep = 9; const vertStep2 = vertStep * 2; const vertStep3 = vertStep * 3; diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index c124f42888e..155b5ff4b28 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -101,11 +101,23 @@ export class TiledLayer extends UIRenderer { leftDown: { row: -1, col: -1 }, rightTop: { row: -1, col: -1 }, }; - get cullingRect () { return this._cullingRect; } + get cullingRect (): { + leftDown: { + row: number; + col: number; + }; + rightTop: { + row: number; + col: number; + }; + } { return this._cullingRect; } protected _cullingDirty = true; protected _rightTop = { row: -1, col: -1 }; - get rightTop () { return this._rightTop; } + get rightTop (): { + row: number; + col: number; + } { return this._rightTop; } protected _layerInfo: TMXLayerInfo | null = null; protected _mapInfo: TMXMapInfo | null = null; @@ -128,7 +140,7 @@ export class TiledLayer extends UIRenderer { protected _layerName = ''; protected _layerSize?: Size; - get layerSize () { return this._layerSize!; } + get layerSize (): Size { return this._layerSize!; } protected _minGID?: GID; protected _maxGID?: GID; @@ -173,12 +185,12 @@ export class TiledLayer extends UIRenderer { protected _cameraNode?: Node; - get tiledDataArray () { return this._tiledDataArray; } - get leftDownToCenterX () { return this._leftDownToCenterX; } - get leftDownToCenterY () { return this._leftDownToCenterY; } + get tiledDataArray (): TiledDataArray { return this._tiledDataArray; } + get leftDownToCenterX (): number { return this._leftDownToCenterX; } + get leftDownToCenterY (): number { return this._leftDownToCenterY; } private _drawInfoList: RenderDrawInfo[] = []; - private requestDrawInfo (idx: number) { + private requestDrawInfo (idx: number): RenderDrawInfo { if (!this._drawInfoList[idx]) { this._drawInfoList[idx] = new RenderDrawInfo(); this._drawInfoList[idx].setDrawInfoType(RenderDrawInfoType.MIDDLEWARE); @@ -190,11 +202,11 @@ export class TiledLayer extends UIRenderer { super(); } - public hasTiledNode () { + public hasTiledNode (): boolean { return this._hasTiledNodeGrid; } - public hasAnimation () { + public hasAnimation (): boolean { return this._hasAniGrid; } @@ -211,7 +223,7 @@ export class TiledLayer extends UIRenderer { this.markForUpdateRenderData(); } } - get enableCulling () { return this._enableCulling!; } + get enableCulling (): boolean { return this._enableCulling!; } /** * @en Adds user's node into layer. @@ -220,7 +232,7 @@ export class TiledLayer extends UIRenderer { * @param {cc.Node} node * @return {Boolean} */ - public addUserNode (node: Node) { + public addUserNode (node: Node): boolean { let dataComp = node.getComponent(TiledUserNodeData); if (dataComp) { warn('CCTiledLayer:addUserNode node has been added'); @@ -251,7 +263,7 @@ export class TiledLayer extends UIRenderer { * @param {cc.Node} node * @return {Boolean} */ - public removeUserNode (node: Node) { + public removeUserNode (node: Node): boolean { const dataComp = node.getComponent(TiledUserNodeData); if (!dataComp) { warn('CCTiledLayer:removeUserNode node is not exist'); @@ -274,30 +286,33 @@ export class TiledLayer extends UIRenderer { * @method destroyUserNode * @param {cc.Node} node */ - public destroyUserNode (node: Node) { + public destroyUserNode (node: Node): void { this.removeUserNode(node); node.destroy(); } // acording layer anchor point to calculate node layer pos - protected _nodeLocalPosToLayerPos (nodePos: IVec2Like, out: IVec2Like) { + protected _nodeLocalPosToLayerPos (nodePos: IVec2Like, out: IVec2Like): void { out.x = nodePos.x + this._leftDownToCenterX; out.y = nodePos.y + this._leftDownToCenterY; } - public getNodesByRowCol (row: number, col: number) { + public getNodesByRowCol (row: number, col: number): { + count: number; + list: (TiledUserNodeData | null)[]; + } | null | undefined { const rowData = this._userNodeGrid[row]; if (!rowData) return null; return rowData[col]; } - public getNodesCountByRow (row) { + public getNodesCountByRow (row): number { const rowData = this._userNodeGrid[row]; if (!rowData) return 0; return rowData.count; } - protected _updateAllUserNode () { + protected _updateAllUserNode (): void { this._userNodeGrid = {}; for (const dataId in this._userNodeMap) { const dataComp = this._userNodeMap[dataId]; @@ -308,7 +323,7 @@ export class TiledLayer extends UIRenderer { } } - protected _updateCullingOffsetByUserNode (node_: Node) { + protected _updateCullingOffsetByUserNode (node_: Node): void { const node = node_._uiProps.uiTransformComp!.contentSize; if (this._topOffset < node.height) { this._topOffset = node.height; @@ -324,7 +339,7 @@ export class TiledLayer extends UIRenderer { } } - protected _userNodeSizeChange () { + protected _userNodeSizeChange (): void { const dataComp: TiledUserNodeData = this as unknown as any; const node = dataComp.node; const self = dataComp._tiledLayer!; @@ -333,7 +348,7 @@ export class TiledLayer extends UIRenderer { self.markForUpdateRenderData(); } - protected _userNodePosChange () { + protected _userNodePosChange (): void { const dataComp: TiledUserNodeData = this as unknown as any; const node = dataComp.node; const self = dataComp._tiledLayer!; @@ -347,7 +362,7 @@ export class TiledLayer extends UIRenderer { self._addUserNodeToGrid(dataComp, _tempRowCol); } - protected _removeUserNodeFromGrid (dataComp: TiledUserNodeData) { + protected _removeUserNodeFromGrid (dataComp: TiledUserNodeData): void { const row = dataComp._row; const col = dataComp._col; const index = dataComp._index; @@ -371,7 +386,7 @@ export class TiledLayer extends UIRenderer { this.markForUpdateRenderData(); } - protected _limitInLayer (rowCol: { row: number, col: number }) { + protected _limitInLayer (rowCol: { row: number, col: number }): void { const row = rowCol.row; const col = rowCol.col; if (row < 0) rowCol.row = 0; @@ -380,7 +395,7 @@ export class TiledLayer extends UIRenderer { if (col > this._rightTop.col) rowCol.col = this._rightTop.col; } - protected _addUserNodeToGrid (dataComp: TiledUserNodeData, tempRowCol: { col: number, row: number }) { + protected _addUserNodeToGrid (dataComp: TiledUserNodeData, tempRowCol: { col: number, row: number }): void { const row = tempRowCol.row; const col = tempRowCol.col; const rowData = this._userNodeGrid[row] = this._userNodeGrid[row] || { count: 0 }; @@ -394,11 +409,11 @@ export class TiledLayer extends UIRenderer { this._userNodeDirty = true; } - public isUserNodeDirty () { + public isUserNodeDirty (): boolean { return this._userNodeDirty; } - public setUserNodeDirty (value) { + public setUserNodeDirty (value): void { this._userNodeDirty = value; } @@ -416,7 +431,7 @@ export class TiledLayer extends UIRenderer { return camera; } - protected _uninstallCamera () { + protected _uninstallCamera (): void { if (this._cameraNode) { this._cameraNode.off(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this); this._cameraNode.off(NodeEventType.SIZE_CHANGED, this.updateCulling, this); @@ -424,7 +439,7 @@ export class TiledLayer extends UIRenderer { } } - onEnable () { + onEnable (): void { super.onEnable(); this.node.on(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); this.node.on(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this); @@ -436,7 +451,7 @@ export class TiledLayer extends UIRenderer { this.scheduleOnce(this.updateCulling.bind(this)); } - onDisable () { + onDisable (): void { super.onDisable(); this.node.parent?.off(NodeEventType.SIZE_CHANGED, this.updateCulling, this); this.node.parent?.off(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this); @@ -446,7 +461,7 @@ export class TiledLayer extends UIRenderer { this._uninstallCamera(); } - protected _syncAnchorPoint () { + protected _syncAnchorPoint (): void { const node = this.node; const trans = node._uiProps.uiTransformComp!; const scale = node.getScale(); @@ -477,7 +492,7 @@ export class TiledLayer extends UIRenderer { * @example * tiledLayer.setLayerName("New Layer"); */ - public setLayerName (layerName: string) { + public setLayerName (layerName: string): void { this._layerName = layerName; } @@ -491,7 +506,7 @@ export class TiledLayer extends UIRenderer { * let property = tiledLayer.getProperty("info"); * cc.log(property); */ - public getProperty (propertyName: string) { + public getProperty (propertyName: string): string | number { return this._properties![propertyName]; } @@ -529,7 +544,7 @@ export class TiledLayer extends UIRenderer { return null; } - public isInvalidPosition (x: number, y: number) { + public isInvalidPosition (x: number, y: number): boolean { return x >= this._layerSize!.width || y >= this._layerSize!.height || x < 0 || y < 0; } @@ -624,7 +639,7 @@ export class TiledLayer extends UIRenderer { * @example * tiledLayer.setTilesGIDAt([1, 1, 1, 1], 10, 10, 2) */ - public setTilesGIDAt (gids: number[], beginCol: number, beginRow: number, totalCols: number) { + public setTilesGIDAt (gids: number[], beginCol: number, beginRow: number, totalCols: number): void { if (!gids || gids.length === 0 || totalCols <= 0) return; if (beginRow < 0) beginRow = 0; if (beginCol < 0) beginCol = 0; @@ -656,7 +671,7 @@ export class TiledLayer extends UIRenderer { * @example * tiledLayer.setTileGIDAt(1001, 10, 10, 1) */ - public setTileGIDAt (gid: MixedGID, x: number, y: number, flags?: number) { + public setTileGIDAt (gid: MixedGID, x: number, y: number, flags?: number): void { const ugid = ((gid as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0; x = Math.floor(x); @@ -737,7 +752,7 @@ export class TiledLayer extends UIRenderer { * @example * let tileGid = tiledLayer.getTileGIDAt(0, 0); */ - public getTileFlagsAt (x: number, y: number) { + public getTileFlagsAt (x: number, y: number): number | null { if (this.isInvalidPosition(x, y)) { throw new Error('TiledLayer.getTileFlagsAt: invalid position'); } @@ -753,7 +768,7 @@ export class TiledLayer extends UIRenderer { return ((tile & TileFlag.FLIPPED_ALL) >>> 0) as unknown as GIDFlags; } - public setCullingDirty (value: boolean) { + public setCullingDirty (value: boolean): void { this._cullingDirty = value; } @@ -873,7 +888,7 @@ export class TiledLayer extends UIRenderer { return result; } - public updateCulling () { + public updateCulling (): void { if (EDITOR_NOT_IN_PREVIEW) { this.enableCulling = false; } else if (this._enableCulling) { @@ -907,7 +922,7 @@ export class TiledLayer extends UIRenderer { * let orientation = tiledLayer.getLayerOrientation(); * cc.log("Layer Orientation: " + orientation); */ - public getLayerOrientation () { + public getLayerOrientation (): Orientation | null { return this._layerOrientation; } @@ -920,11 +935,11 @@ export class TiledLayer extends UIRenderer { * let properties = tiledLayer.getProperties(); * cc.log("Properties: " + properties); */ - public getProperties () { + public getProperties (): PropertiesInfo | undefined { return this._properties; } - protected _updateVertex (col: number, row: number) { + protected _updateVertex (col: number, row: number): void { const FLIPPED_MASK = TileFlag.FLIPPED_MASK; const vertices = this.vertices; @@ -1082,7 +1097,7 @@ export class TiledLayer extends UIRenderer { this._cullingDirty = true; } - protected _updateVertices () { + protected _updateVertices (): void { const vertices = this.vertices; vertices.length = 0; @@ -1131,7 +1146,7 @@ export class TiledLayer extends UIRenderer { * let tile = tiledLayer.getTiledTileAt(100, 100, true); * cc.log(tile); */ - public getTiledTileAt (x: number, y: number, forceCreate?: boolean) { + public getTiledTileAt (x: number, y: number, forceCreate?: boolean): TiledTile | null { if (this.isInvalidPosition(x, y)) { throw new Error('TiledLayer.getTiledTileAt: invalid position'); } @@ -1209,7 +1224,7 @@ export class TiledLayer extends UIRenderer { * @method getTextures * @return {Texture2D} */ - public getTextures () { + public getTextures (): SpriteFrame[] { return this._textures; } @@ -1219,7 +1234,7 @@ export class TiledLayer extends UIRenderer { * @method setTexture * @param {SpriteFrame} texture */ - public setTexture (texture: SpriteFrame) { + public setTexture (texture: SpriteFrame): void { this.setTextures([texture]); } @@ -1229,7 +1244,7 @@ export class TiledLayer extends UIRenderer { * @method setTexture * @param {SpriteFrame} textures */ - public setTextures (textures: SpriteFrame[]) { + public setTextures (textures: SpriteFrame[]): void { this._textures = textures; this.markForUpdateRenderData(); } @@ -1291,7 +1306,7 @@ export class TiledLayer extends UIRenderer { * @method setTileSet * @param {TMXTilesetInfo} tileset */ - public setTileSet (tileset: TMXTilesetInfo) { + public setTileSet (tileset: TMXTilesetInfo): void { this.setTileSets([tileset]); } @@ -1301,7 +1316,7 @@ export class TiledLayer extends UIRenderer { * @method setTileSets * @param {TMXTilesetInfo} tilesets */ - public setTileSets (tilesets: TMXTilesetInfo[]) { + public setTileSets (tilesets: TMXTilesetInfo[]): void { this._tilesets = tilesets; const textures: SpriteFrame[] = this._textures = []; const texGrids = this.texGrids!; @@ -1321,7 +1336,7 @@ export class TiledLayer extends UIRenderer { this._prepareToRender(); } - public init (layerInfo: TMXLayerInfo, mapInfo: TMXMapInfo, tilesets: TMXTilesetInfo[], textures: SpriteFrame[], texGrids: TiledTextureGrids) { + public init (layerInfo: TMXLayerInfo, mapInfo: TMXMapInfo, tilesets: TMXTilesetInfo[], textures: SpriteFrame[], texGrids: TiledTextureGrids): void { this._cullingDirty = true; this._layerInfo = layerInfo; this._mapInfo = mapInfo; @@ -1398,12 +1413,12 @@ export class TiledLayer extends UIRenderer { this._prepareToRender(); } - protected _prepareToRender () { + protected _prepareToRender (): void { this._updateVertices(); this._updateAllUserNode(); } - public requestTiledRenderData () { + public requestTiledRenderData (): TiledRenderData { const arr = this._tiledDataArray as any[]; while (arr.length > 0 && arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) { arr.pop(); @@ -1419,7 +1434,7 @@ export class TiledLayer extends UIRenderer { return (comb as TiledRenderData); } - public requestSubNodesData () { + public requestSubNodesData (): TiledSubNodeData { const arr = this._tiledDataArray as any[]; if (arr.length > 0) { if (arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) { @@ -1432,7 +1447,7 @@ export class TiledLayer extends UIRenderer { return comb; } - public destroyRenderData () { + public destroyRenderData (): void { this._tiledDataArray.forEach((rd) => { const renderData = (rd as TiledRenderData).renderData; if (renderData) RenderData.remove(renderData); @@ -1441,7 +1456,7 @@ export class TiledLayer extends UIRenderer { super.destroyRenderData(); } - protected _flushAssembler () { + protected _flushAssembler (): void { const assembler = TiledLayer.Assembler.getAssembler(this); if (this._assembler !== assembler) { this._assembler = assembler; @@ -1461,7 +1476,7 @@ export class TiledLayer extends UIRenderer { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _tiledDataArrayIdx = 0; - protected _render (ui: IBatcher) { + protected _render (ui: IBatcher): void { for (let i = 0; i < this._tiledDataArray.length; i++) { this._tiledDataArrayIdx = i; const m = this._tiledDataArray[i]; @@ -1481,11 +1496,11 @@ export class TiledLayer extends UIRenderer { this.node._static = true; } - protected createRenderEntity () { + protected createRenderEntity (): RenderEntity { return new RenderEntity(RenderEntityType.CROSSED); } - private fillIndicesBuffer (renderData: RenderData, drawInfo: RenderDrawInfo) { + private fillIndicesBuffer (renderData: RenderData, drawInfo: RenderDrawInfo): void { const iBuf = renderData.chunk.meshBuffer.iData; let indexOffset = renderData.chunk.meshBuffer.indexOffset; @@ -1506,7 +1521,7 @@ export class TiledLayer extends UIRenderer { drawInfo.setIBCount(quadCount * 6); } - public prepareDrawData () { + public prepareDrawData (): void { this._drawInfoList.length = 0; const entity = this.renderEntity; entity.clearDynamicRenderDrawInfos(); diff --git a/cocos/tiledmap/tiled-map.ts b/cocos/tiledmap/tiled-map.ts index 908bb0f4224..1c874976990 100644 --- a/cocos/tiledmap/tiled-map.ts +++ b/cocos/tiledmap/tiled-map.ts @@ -119,7 +119,7 @@ export class TiledMap extends Component { @serializable protected _enableCulling = true; @editable - get enableCulling () { + get enableCulling (): boolean { return this._enableCulling; } set enableCulling (value) { @@ -142,7 +142,7 @@ export class TiledMap extends Component { * let mapSize = tiledMap.getMapSize(); * cc.log("Map Size: " + mapSize); */ - getMapSize () { + getMapSize (): Size { return this._mapSize; } @@ -155,7 +155,7 @@ export class TiledMap extends Component { * let tileSize = tiledMap.getTileSize(); * cc.log("Tile Size: " + tileSize); */ - getTileSize () { + getTileSize (): Size { return this._tileSize; } @@ -168,7 +168,7 @@ export class TiledMap extends Component { * let mapOrientation = tiledMap.getMapOrientation(); * cc.log("Map Orientation: " + mapOrientation); */ - getMapOrientation () { + getMapOrientation (): Orientation { return this._mapOrientation; } @@ -183,7 +183,7 @@ export class TiledMap extends Component { * cc.log("obj: " + objGroups[i]); * } */ - getObjectGroups () { + getObjectGroups (): TiledObjectGroup[] { return this._groups; } @@ -197,7 +197,7 @@ export class TiledMap extends Component { * let group = titledMap.getObjectGroup("Players"); * cc.log("ObjectGroup: " + group); */ - getObjectGroup (groupName: string) { + getObjectGroup (groupName: string): TiledObjectGroup | null { const groups = this._groups; for (let i = 0, l = groups.length; i < l; i++) { const group = groups[i]; @@ -220,7 +220,7 @@ export class TiledMap extends Component { * cc.log("Properties: " + properties[i]); * } */ - getProperties () { + getProperties (): PropertiesInfo { return this._properties; } @@ -235,7 +235,7 @@ export class TiledMap extends Component { * cc.log("Layers: " + layers[i]); * } */ - getLayers () { + getLayers (): TiledLayer[] { return this._layers; } @@ -249,7 +249,7 @@ export class TiledMap extends Component { * let layer = titledMap.getLayer("Player"); * cc.log(layer); */ - getLayer (layerName) { + getLayer (layerName): TiledLayer | null { const layers = this._layers; for (let i = 0, l = layers.length; i < l; i++) { const layer = layers[i]; @@ -260,7 +260,7 @@ export class TiledMap extends Component { return null; } - protected _changeLayer (layerName, replaceLayer) { + protected _changeLayer (layerName, replaceLayer): void { const layers = this._layers; for (let i = 0, l = layers.length; i < l; i++) { const layer = layers[i]; @@ -281,7 +281,7 @@ export class TiledMap extends Component { * let property = titledMap.getProperty("info"); * cc.log("Property: " + property); */ - getProperty (propertyName: string) { + getProperty (propertyName: string): string | number { return this._properties[propertyName.toString()]; } @@ -295,11 +295,11 @@ export class TiledMap extends Component { * let properties = titledMap.getPropertiesForGID(GID); * cc.log("Properties: " + properties); */ - getPropertiesForGID (gid: GID) { + getPropertiesForGID (gid: GID): PropertiesInfo | undefined { return this._tileProperties.get(gid); } - __preload () { + __preload (): void { if (!this._tmxFile) { return; } @@ -309,15 +309,15 @@ export class TiledMap extends Component { } } - onEnable () { + onEnable (): void { this.node.on(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); } - onDisable () { + onDisable (): void { this.node.off(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); } - _applyFile () { + _applyFile (): void { const spriteFrames: SpriteFrame[] = []; const spriteFramesCache = {}; @@ -371,7 +371,7 @@ export class TiledMap extends Component { } } - _releaseMapInfo () { + _releaseMapInfo (): void { // remove the layers & object groups added before const layers = this._layers; for (let i = 0, l = layers.length; i < l; i++) { @@ -397,7 +397,7 @@ export class TiledMap extends Component { images.length = 0; } - _syncAnchorPoint () { + _syncAnchorPoint (): void { const anchor = this.node._uiProps.uiTransformComp!.anchorPoint; const leftTopX = this.node._uiProps.uiTransformComp!.width * anchor.x; const leftTopY = this.node._uiProps.uiTransformComp!.height * (1 - anchor.y); @@ -433,7 +433,7 @@ export class TiledMap extends Component { } } - _fillAniGrids (texGrids: TiledTextureGrids, animations: TiledAnimationType) { + _fillAniGrids (texGrids: TiledTextureGrids, animations: TiledAnimationType): void { for (const i of animations.keys()) { const animation = animations.get(i); if (!animation) continue; @@ -445,7 +445,7 @@ export class TiledMap extends Component { } } - _buildLayerAndGroup () { + _buildLayerAndGroup (): void { const tilesets = this._tilesets; const texGrids = this._texGrids; const animations = this._animations; @@ -567,7 +567,7 @@ export class TiledMap extends Component { this._syncAnchorPoint(); } - protected _buildWithMapInfo (mapInfo: TMXMapInfo) { + protected _buildWithMapInfo (mapInfo: TMXMapInfo): void { this._mapInfo = mapInfo; this._mapSize = mapInfo.getMapSize(); this._tileSize = mapInfo.getTileSize(); @@ -603,7 +603,7 @@ export class TiledMap extends Component { } } - doCleanupImageCache (texture) { + doCleanupImageCache (texture): void { if (texture._image instanceof HTMLImageElement) { texture._image.src = ''; if (JSB) texture._image.destroy(); @@ -613,7 +613,7 @@ export class TiledMap extends Component { texture._image = null; } - lateUpdate (dt: number) { + lateUpdate (dt: number): void { const animations = this._animations; const texGrids = this._texGrids; for (const aniGID of animations.keys()) { diff --git a/cocos/tiledmap/tiled-object-group.ts b/cocos/tiledmap/tiled-object-group.ts index 5929b53607e..e2a30164f93 100644 --- a/cocos/tiledmap/tiled-object-group.ts +++ b/cocos/tiledmap/tiled-object-group.ts @@ -49,7 +49,7 @@ export class TiledObjectGroup extends Component { protected _premultiplyAlpha = false; @type(CCBoolean) - get premultiplyAlpha () { + get premultiplyAlpha (): boolean { return this._premultiplyAlpha; } set premultiplyAlpha (value: boolean) { @@ -64,7 +64,7 @@ export class TiledObjectGroup extends Component { * @example * let offset = tMXObjectGroup.getPositionOffset(); */ - public getPositionOffset () { + public getPositionOffset (): Vec2 | undefined { return this._positionOffset; } @@ -76,7 +76,7 @@ export class TiledObjectGroup extends Component { * @example * let offset = tMXObjectGroup.getProperties(); */ - public getProperties () { + public getProperties (): PropertiesInfo | undefined { return this._properties; } @@ -88,7 +88,7 @@ export class TiledObjectGroup extends Component { * @example * let groupName = tMXObjectGroup.getGroupName; */ - public getGroupName () { + public getGroupName (): string | undefined { return this._groupName; } @@ -97,7 +97,7 @@ export class TiledObjectGroup extends Component { * @param {String} propertyName * @return {Object} */ - public getProperty (propertyName: { toString (): string } | string) { + public getProperty (propertyName: { toString (): string } | string): string | number { return this._properties![propertyName.toString()]; } @@ -112,7 +112,7 @@ export class TiledObjectGroup extends Component { * @example * let object = tMXObjectGroup.getObject("Group"); */ - public getObject (objectName: string) { + public getObject (objectName: string): TMXObject | null { for (let i = 0, len = this._objects.length; i < len; i++) { const obj = this._objects[i]; if (obj && obj.name === objectName) { @@ -131,7 +131,7 @@ export class TiledObjectGroup extends Component { * @example * let objects = tMXObjectGroup.getObjects(); */ - public getObjects () { + public getObjects (): TMXObject[] { return this._objects; } @@ -140,7 +140,7 @@ export class TiledObjectGroup extends Component { protected _mapInfo?: TMXMapInfo; protected _properties?: PropertiesInfo; protected _offset?: Vec2; - get offset () { return this._offset!; } + get offset (): Vec2 { return this._offset!; } protected _opacity?: number; protected _tintColor: Color | null = null; @@ -157,7 +157,7 @@ export class TiledObjectGroup extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _init (groupInfo: TMXObjectGroupInfo, mapInfo: TMXMapInfo, texGrids: TiledTextureGrids) { + public _init (groupInfo: TMXObjectGroupInfo, mapInfo: TMXMapInfo, texGrids: TiledTextureGrids): void { const FLIPPED_MASK = TileFlag.FLIPPED_MASK; const FLAG_HORIZONTAL = TileFlag.HORIZONTAL; const FLAG_VERTICAL = TileFlag.VERTICAL; @@ -387,7 +387,7 @@ export class TiledObjectGroup extends Component { } } - public update (dt: number) { + public update (dt: number): void { if (!this._hasAniObj) { return; } diff --git a/cocos/tiledmap/tiled-tile.ts b/cocos/tiledmap/tiled-tile.ts index 82cb6e19591..b1463935b71 100644 --- a/cocos/tiledmap/tiled-tile.ts +++ b/cocos/tiledmap/tiled-tile.ts @@ -86,7 +86,7 @@ export class TiledTile extends Component { * @default 0 */ @type(CCInteger) - get y () { + get y (): number { return this._y; } set y (value: number) { @@ -118,7 +118,7 @@ export class TiledTile extends Component { } } - onEnable () { + onEnable (): void { const parent = this.node.parent!; this._layer = parent.getComponent('cc.TiledLayer') as TiledLayer; this.node.on(NodeEventType.TRANSFORM_CHANGED, this._updatePosition, this); @@ -127,19 +127,19 @@ export class TiledTile extends Component { this.updateInfo(); } - onDisable () { + onDisable (): void { this._resetTile(); this.node.off(NodeEventType.TRANSFORM_CHANGED, this._updatePosition, this); this.node.off(NodeEventType.SIZE_CHANGED, this._updatePosition, this); } - private _resetTile () { + private _resetTile (): void { if (this._layer && this._layer.getTiledTileAt(this._x, this._y) === this) { this._layer.setTiledTileAt(this._x, this._y, null); } } - public updateInfo () { + public updateInfo (): void { if (!this._layer) return; const x = this._x; @@ -154,7 +154,7 @@ export class TiledTile extends Component { this._layer.markForUpdateRenderData(); } - private _updatePosition () { + private _updatePosition (): void { this._layer!.markForUpdateRenderData(); } } diff --git a/cocos/tiledmap/tiled-types.ts b/cocos/tiledmap/tiled-types.ts index 59e1f6e6b52..d87427b9fbf 100644 --- a/cocos/tiledmap/tiled-types.ts +++ b/cocos/tiledmap/tiled-types.ts @@ -378,7 +378,7 @@ export class TMXTilesetInfo { collection = false; - rectForGID (gid_: MixedGID | GID, result?: TiledGrid) { + rectForGID (gid_: MixedGID | GID, result?: TiledGrid): Rect | TiledGrid { const rect = result || new Rect(0, 0, 0, 0); rect.width = this._tileSize.width; rect.height = this._tileSize.height; @@ -427,7 +427,7 @@ export class TMXObjectGroupInfo { * Gets the Properties. * @return {Array} */ - getProperties () { + getProperties (): PropertiesInfo { return this.properties; } @@ -435,7 +435,7 @@ export class TMXObjectGroupInfo { * Set the Properties. * @param {object} value */ - setProperties (value: PropertiesInfo) { + setProperties (value: PropertiesInfo): void { this.properties = value; } } @@ -493,7 +493,7 @@ export class TMXLayerInfo { * Gets the Properties. * @return {Object} */ - getProperties () { + getProperties (): PropertiesInfo { return this.properties; } @@ -501,7 +501,7 @@ export class TMXLayerInfo { * Set the Properties. * @param {object} value */ - setProperties (value: PropertiesInfo) { + setProperties (value: PropertiesInfo): void { this.properties = value; } diff --git a/cocos/tiledmap/tiled-utils.ts b/cocos/tiledmap/tiled-utils.ts index 68b54a0e016..c32f0e36794 100644 --- a/cocos/tiledmap/tiled-utils.ts +++ b/cocos/tiledmap/tiled-utils.ts @@ -27,7 +27,7 @@ import { Texture2D } from '../asset/assets'; import { Rect } from '../core'; import { GID, TiledGrid, TiledTextureGrids, TMXTilesetInfo } from './tiled-types'; -export function fillTextureGrids (tileset: TMXTilesetInfo, texGrids: TiledTextureGrids, spFrame?: SpriteFrame) { +export function fillTextureGrids (tileset: TMXTilesetInfo, texGrids: TiledTextureGrids, spFrame?: SpriteFrame): void { const spf: SpriteFrame = spFrame || tileset.sourceImage!; const tex: Texture2D = spf.texture as Texture2D; diff --git a/cocos/tiledmap/tmx-xml-parser.ts b/cocos/tiledmap/tmx-xml-parser.ts index 93ade6d5bf5..8e551881dcd 100644 --- a/cocos/tiledmap/tmx-xml-parser.ts +++ b/cocos/tiledmap/tmx-xml-parser.ts @@ -183,9 +183,9 @@ export class TMXMapInfo { protected _objectGroups: TMXObjectGroupInfo[] = []; protected _allChildren: (TMXLayerInfo | TMXImageLayerInfo | TMXObjectGroupInfo)[] = []; protected _mapSize = new Size(0, 0); - get mapSize () { return this._mapSize; } + get mapSize (): Size { return this._mapSize; } protected _tileSize = new Size(0, 0); - get tileSize () { return this._tileSize; } + get tileSize (): Size { return this._tileSize; } protected _layers: TMXLayerInfo[] = []; protected _tilesets: TMXTilesetInfo[] = []; protected _imageLayers: TMXImageLayerInfo[] = []; @@ -212,7 +212,7 @@ export class TMXMapInfo { /* Gets Map orientation. * @return {Number} */ - getOrientation () { + getOrientation (): Orientation | null { return this.orientation; } @@ -220,14 +220,14 @@ export class TMXMapInfo { * Set the Map orientation. * @param {Number} value */ - setOrientation (value: Orientation) { + setOrientation (value: Orientation): void { this.orientation = value; } /** * Gets the staggerAxis of map. * @return {TiledMap.StaggerAxis} */ - getStaggerAxis () { + getStaggerAxis (): StaggerAxis | null { return this._staggerAxis; } @@ -235,7 +235,7 @@ export class TMXMapInfo { * Set the staggerAxis of map. * @param {TiledMap.StaggerAxis} value */ - setStaggerAxis (value: StaggerAxis) { + setStaggerAxis (value: StaggerAxis): void { this._staggerAxis = value; } @@ -243,7 +243,7 @@ export class TMXMapInfo { * Gets stagger index * @return {TiledMap.StaggerIndex} */ - getStaggerIndex () { + getStaggerIndex (): StaggerIndex | null { return this._staggerIndex; } @@ -251,7 +251,7 @@ export class TMXMapInfo { * Set the stagger index. * @param {TiledMap.StaggerIndex} value */ - setStaggerIndex (value) { + setStaggerIndex (value): void { this._staggerIndex = value; } @@ -259,7 +259,7 @@ export class TMXMapInfo { * Gets Hex side length. * @return {Number} */ - getHexSideLength () { + getHexSideLength (): number { return this._hexSideLength; } @@ -267,7 +267,7 @@ export class TMXMapInfo { * Set the Hex side length. * @param {Number} value */ - setHexSideLength (value: number) { + setHexSideLength (value: number): void { this._hexSideLength = value; } @@ -275,7 +275,7 @@ export class TMXMapInfo { * Map width & height * @return {Size} */ - getMapSize () { + getMapSize (): Size { return new Size(this._mapSize.width, this._mapSize.height); } @@ -283,19 +283,19 @@ export class TMXMapInfo { * Map width & height * @param {Size} value */ - setMapSize (value: Size) { + setMapSize (value: Size): void { this._mapSize.width = value.width; this._mapSize.height = value.height; } - get mapWidth () { + get mapWidth (): number { return this._mapSize.width; } set mapWidth (width: number) { this._mapSize.width = width; } - get mapHeight () { + get mapHeight (): number { return this._mapSize.height; } set mapHeight (height: number) { @@ -306,7 +306,7 @@ export class TMXMapInfo { * Tiles width & height * @return {Size} */ - getTileSize () { + getTileSize (): Size { return new Size(this._tileSize.width, this._tileSize.height); } @@ -314,12 +314,12 @@ export class TMXMapInfo { * Tiles width & height * @param {Size} value */ - setTileSize (value: Size) { + setTileSize (value: Size): void { this._tileSize.width = value.width; this._tileSize.height = value.height; } - get tileWidth () { + get tileWidth (): number { return this._tileSize.width; } @@ -330,7 +330,7 @@ export class TMXMapInfo { /** * Height of a tile */ - get tileHeight () { + get tileHeight (): number { return this._tileSize.height; } @@ -342,7 +342,7 @@ export class TMXMapInfo { * Layers * @return {Array} */ - getLayers () { + getLayers (): TMXLayerInfo[] { return this._layers; } @@ -350,7 +350,7 @@ export class TMXMapInfo { * Layers * @param {cc.TMXLayerInfo} value */ - setLayers (value: TMXLayerInfo) { + setLayers (value: TMXLayerInfo): void { this._allChildren.push(value); this._layers.push(value); } @@ -359,7 +359,7 @@ export class TMXMapInfo { * ImageLayers * @return {Array} */ - getImageLayers () { + getImageLayers (): TMXImageLayerInfo[] { return this._imageLayers; } @@ -367,7 +367,7 @@ export class TMXMapInfo { * ImageLayers * @param {cc.TMXImageLayerInfo} value */ - setImageLayers (value: TMXImageLayerInfo) { + setImageLayers (value: TMXImageLayerInfo): void { this._allChildren.push(value); this._imageLayers.push(value); } @@ -376,7 +376,7 @@ export class TMXMapInfo { * tilesets * @return {Array} */ - getTilesets () { + getTilesets (): TMXTilesetInfo[] { return this._tilesets; } @@ -384,7 +384,7 @@ export class TMXMapInfo { * tilesets * @param {cc.TMXTilesetInfo} value */ - setTilesets (value: TMXTilesetInfo) { + setTilesets (value: TMXTilesetInfo): void { this._tilesets.push(value); } @@ -392,7 +392,7 @@ export class TMXMapInfo { * ObjectGroups * @return {Array} */ - getObjectGroups () { + getObjectGroups (): TMXObjectGroupInfo[] { return this._objectGroups; } @@ -400,12 +400,12 @@ export class TMXMapInfo { * ObjectGroups * @param {cc.TMXObjectGroup} value */ - setObjectGroups (value: TMXObjectGroupInfo) { + setObjectGroups (value: TMXObjectGroupInfo): void { this._allChildren.push(value); this._objectGroups.push(value); } - getAllChildren () { + getAllChildren (): (TMXObjectGroupInfo | TMXLayerInfo | TMXImageLayerInfo)[] { return this._allChildren; } @@ -413,7 +413,7 @@ export class TMXMapInfo { * parent element * @return {Object} */ - getParentElement () { + getParentElement (): Record | null { return this.parentElement; } @@ -421,7 +421,7 @@ export class TMXMapInfo { * parent element * @param {Object} value */ - setParentElement (value) { + setParentElement (value): void { this.parentElement = value; } @@ -429,7 +429,7 @@ export class TMXMapInfo { * parent GID * @return {Number} */ - getParentGID () { + getParentGID (): number { return this.parentGID; } @@ -437,7 +437,7 @@ export class TMXMapInfo { * parent GID * @param {Number} value */ - setParentGID (value) { + setParentGID (value): void { this.parentGID = value; } @@ -445,7 +445,7 @@ export class TMXMapInfo { * Layer attribute * @return {Object} */ - getLayerAttribs () { + getLayerAttribs (): number { return this.layerAttrs; } @@ -453,7 +453,7 @@ export class TMXMapInfo { * Layer attribute * @param {Object} value */ - setLayerAttribs (value) { + setLayerAttribs (value): void { this.layerAttrs = value; } @@ -461,7 +461,7 @@ export class TMXMapInfo { * Is reading storing characters stream * @return {Boolean} */ - getStoringCharacters () { + getStoringCharacters (): boolean { return this.storingCharacters; } @@ -469,7 +469,7 @@ export class TMXMapInfo { * Is reading storing characters stream * @param {Boolean} value */ - setStoringCharacters (value) { + setStoringCharacters (value): void { this.storingCharacters = value; } @@ -477,7 +477,7 @@ export class TMXMapInfo { * Properties * @return {Array} */ - getProperties () { + getProperties (): PropertiesInfo { return this.properties; } @@ -485,7 +485,7 @@ export class TMXMapInfo { * Properties * @param {object} value */ - setProperties (value) { + setProperties (value): void { this.properties = value; } @@ -497,7 +497,7 @@ export class TMXMapInfo { * @return {Boolean} */ initWithXML (tmxString: string, tsxMap: { [key: string]: string }, spfTextureMap: { [key: string]: SpriteFrame }, - textureSizes: { [key: string]: Size }, imageLayerTextures: { [key: string]: SpriteFrame }) { + textureSizes: { [key: string]: Size }, imageLayerTextures: { [key: string]: SpriteFrame }): HTMLElement { this._tilesets.length = 0; this._layers.length = 0; this._imageLayers.length = 0; @@ -528,7 +528,7 @@ export class TMXMapInfo { * @param {Number} tilesetFirstGid * @return {Element} */ - parseXMLString (xmlStr: string, tilesetFirstGid?: number) { + parseXMLString (xmlStr: string, tilesetFirstGid?: number): HTMLElement { const parser = new SAXParser(); const mapXML: Document = parser.parse(xmlStr); let i: number; @@ -792,7 +792,7 @@ export class TMXMapInfo { || node.nodeType === 4; // cdata } - protected _parseImageLayer (selLayer: Element) { + protected _parseImageLayer (selLayer: Element): TMXImageLayerInfo | null { const datas = selLayer.getElementsByTagName('image'); if (!datas || datas.length === 0) return null; @@ -824,7 +824,7 @@ export class TMXMapInfo { return imageLayer; } - protected _parseLayer (selLayer: Element) { + protected _parseLayer (selLayer: Element): TMXLayerInfo | null { const data = selLayer.getElementsByTagName('data')[0]; const layer = new TMXLayerInfo(); @@ -898,7 +898,7 @@ export class TMXMapInfo { return layer; } - protected _parseObjectGroup (selGroup: Element) { + protected _parseObjectGroup (selGroup: Element): TMXObjectGroupInfo { const objectGroup = new TMXObjectGroupInfo(); objectGroup.name = selGroup.getAttribute('name') || ''; objectGroup.offset = new Vec2(parseFloat(selGroup.getAttribute('offsetx')!), parseFloat(selGroup.getAttribute('offsety')!)); @@ -1008,7 +1008,10 @@ export class TMXMapInfo { return objectGroup; } - protected _parsePointsString (pointsString?: string) { + protected _parsePointsString (pointsString?: string): { + x: number; + y: number; + }[] | null { if (!pointsString) return null; const points: { x: number, y: number }[] = []; @@ -1024,7 +1027,7 @@ export class TMXMapInfo { * Sets the tile animations. * @return {Object} */ - setTileAnimations (animations: TiledAnimationType) { + setTileAnimations (animations: TiledAnimationType): void { this._tileAnimations = animations; } @@ -1040,7 +1043,8 @@ export class TMXMapInfo { * Gets the tile properties. * @return {Object} */ - getTileProperties () { + getTileProperties (): Map + { return this._tileProperties; } @@ -1048,7 +1052,7 @@ export class TMXMapInfo { * Set the tile properties. * @param {Object} tileProperties */ - setTileProperties (tileProperties: Map) { + setTileProperties (tileProperties: Map): void { this._tileProperties = tileProperties; } @@ -1056,7 +1060,7 @@ export class TMXMapInfo { * Gets the currentString * @return {String} */ - getCurrentString () { + getCurrentString (): string | null { return this.currentString; } @@ -1064,18 +1068,18 @@ export class TMXMapInfo { * Set the currentString * @param {String} currentString */ - setCurrentString (currentString: string) { + setCurrentString (currentString: string): void { this.currentString = currentString; } - static getNameWithPostfix (name: string) { + static getNameWithPostfix (name: string): string { name = name.replace(/\\/g, '/'); const slashIndex = name.lastIndexOf('/') + 1; const strLen = name.length; return name.substring(slashIndex, strLen); } - static getShortName (name: string) { + static getShortName (name: string): string { name = name.replace(/\\/g, '/'); const slashIndex = name.lastIndexOf('/') + 1; let dotIndex = name.lastIndexOf('.'); diff --git a/cocos/tween/actions/action-instant.ts b/cocos/tween/actions/action-instant.ts index 3847be7b86b..075283d9f7d 100644 --- a/cocos/tween/actions/action-instant.ts +++ b/cocos/tween/actions/action-instant.ts @@ -36,15 +36,15 @@ import { Renderer } from '../../misc/renderer'; * @extends FiniteTimeAction */ export class ActionInstant extends FiniteTimeAction { - isDone () { + isDone (): boolean { return true; } - step (dt: any) { + step (dt: any): void { this.update(1); } - update (dt: number) { + update (dt: number): void { // nothing } @@ -59,7 +59,7 @@ export class ActionInstant extends FiniteTimeAction { return this.clone(); } - clone () { + clone (): ActionInstant { return new ActionInstant(); } } @@ -70,7 +70,7 @@ export class ActionInstant extends FiniteTimeAction { * @extends ActionInstant */ export class Show extends ActionInstant { - update (dt: any) { + update (dt: any): void { const _renderComps = this.target!.getComponentsInChildren(Renderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; @@ -78,11 +78,11 @@ export class Show extends ActionInstant { } } - reverse () { + reverse (): Hide { return new Hide(); } - clone () { + clone (): Show { return new Show(); } } @@ -106,7 +106,7 @@ export function show (): ActionInstant { * @extends ActionInstant */ export class Hide extends ActionInstant { - update (dt: any) { + update (dt: any): void { const _renderComps = this.target!.getComponentsInChildren(Renderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; @@ -114,11 +114,11 @@ export class Hide extends ActionInstant { } } - reverse () { + reverse (): Show { return new Show(); } - clone () { + clone (): Hide { return new Hide(); } } @@ -142,7 +142,7 @@ export function hide (): ActionInstant { * @extends ActionInstant */ export class ToggleVisibility extends ActionInstant { - update (dt: any) { + update (dt: any): void { const _renderComps = this.target!.getComponentsInChildren(Renderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; @@ -150,11 +150,11 @@ export class ToggleVisibility extends ActionInstant { } } - reverse () { + reverse (): ToggleVisibility { return new ToggleVisibility(); } - clone () { + clone (): ToggleVisibility { return new ToggleVisibility(); } } @@ -190,23 +190,23 @@ export class RemoveSelf extends ActionInstant { isNeedCleanUp !== undefined && this.init(isNeedCleanUp); } - update (dt: any) { + update (dt: any): void { this.target!.removeFromParent(); if (this._isNeedCleanUp) { this.target!.destroy(); } } - init (isNeedCleanUp: any) { + init (isNeedCleanUp: any): boolean { this._isNeedCleanUp = isNeedCleanUp; return true; } - reverse () { + reverse (): RemoveSelf { return new RemoveSelf(this._isNeedCleanUp); } - clone () { + clone (): RemoveSelf { return new RemoveSelf(this._isNeedCleanUp); } } @@ -265,7 +265,7 @@ export class CallFunc extends ActionInstant { * @param {*|Null} [data] data for function, it accepts all data types. * @return {Boolean} */ - initWithFunction (selector: any, selectorTarget?: any, data?: any) { + initWithFunction (selector: any, selectorTarget?: any, data?: any): boolean { if (selector) { this._function = selector; } @@ -281,13 +281,13 @@ export class CallFunc extends ActionInstant { /* * execute the function. */ - execute () { + execute (): void { if (this._function) { this._function.call(this._selectorTarget, this.target, this._data); } } - update (dt: any) { + update (dt: any): void { this.execute(); } @@ -295,7 +295,7 @@ export class CallFunc extends ActionInstant { * Get selectorTarget. * @return {object} */ - getTargetCallback () { + getTargetCallback (): null { return this._selectorTarget; } @@ -303,14 +303,14 @@ export class CallFunc extends ActionInstant { * Set selectorTarget. * @param {object} sel */ - setTargetCallback (sel: any) { + setTargetCallback (sel: any): void { if (sel !== this._selectorTarget) { if (this._selectorTarget) { this._selectorTarget = null; } this._selectorTarget = sel; } } - clone () { + clone (): CallFunc { const action = new CallFunc(); action.initWithFunction(this._function, this._selectorTarget, this._data); return action; diff --git a/cocos/tween/actions/action-interval.ts b/cocos/tween/actions/action-interval.ts index 5ef489ccf74..c1a6b1fe93d 100644 --- a/cocos/tween/actions/action-interval.ts +++ b/cocos/tween/actions/action-interval.ts @@ -68,7 +68,7 @@ export class ActionInterval extends FiniteTimeAction { * How many seconds had elapsed since the actions started to run. * @return {Number} */ - getElapsed () { + getElapsed (): number { return this._elapsed; } @@ -77,7 +77,7 @@ export class ActionInterval extends FiniteTimeAction { * @param {Number} d duration in seconds * @return {Boolean} */ - initWithDuration (d: number) { + initWithDuration (d: number): boolean { this._duration = (d === 0) ? macro.FLT_EPSILON : d; // prevent division by 0 // This comparison could be in step:, but it might decrease the performance @@ -87,11 +87,11 @@ export class ActionInterval extends FiniteTimeAction { return true; } - isDone () { + isDone (): boolean { return (this._elapsed >= this._duration); } - _cloneDecoration (action: ActionInterval) { + _cloneDecoration (action: ActionInterval): void { action._repeatForever = this._repeatForever; action._speed = this._speed; action._timesForRepeat = this._timesForRepeat; @@ -100,7 +100,7 @@ export class ActionInterval extends FiniteTimeAction { action._repeatMethod = this._repeatMethod; } - _reverseEaseList (action: ActionInterval) { + _reverseEaseList (action: ActionInterval): void { if (this._easeList) { action._easeList = []; for (let i = 0; i < this._easeList.length; i++) { @@ -109,7 +109,7 @@ export class ActionInterval extends FiniteTimeAction { } } - clone () { + clone (): ActionInterval { const action = new ActionInterval(this._duration); this._cloneDecoration(action); return action; @@ -132,7 +132,7 @@ export class ActionInterval extends FiniteTimeAction { return this; } - _computeEaseTime (dt: any) { + _computeEaseTime (dt: any): any { // var locList = this._easeList; // if ((!locList) || (locList.length === 0)) // return dt; @@ -141,7 +141,7 @@ export class ActionInterval extends FiniteTimeAction { return dt; } - step (dt: number) { + step (dt: number): void { if (this._firstTick) { this._firstTick = false; this._elapsed = 0; @@ -167,13 +167,13 @@ export class ActionInterval extends FiniteTimeAction { } } - startWithTarget (target: any) { + startWithTarget (target: any): void { Action.prototype.startWithTarget.call(this, target); this._elapsed = 0; this._firstTick = true; } - reverse () { + reverse (): ActionInterval { logID(1010); return this; } @@ -183,7 +183,7 @@ export class ActionInterval extends FiniteTimeAction { * @warning It should be overridden in subclass. * @param {Number} amp */ - setAmplitudeRate (amp: any) { + setAmplitudeRate (amp: any): void { // Abstract class needs implementation logID(1011); } @@ -193,7 +193,7 @@ export class ActionInterval extends FiniteTimeAction { * @warning It should be overridden in subclass. * @return {Number} 0 */ - getAmplitudeRate () { + getAmplitudeRate (): number { // Abstract class needs implementation logID(1012); return 0; @@ -285,7 +285,7 @@ export class ActionInterval extends FiniteTimeAction { * Runs actions sequentially, one after another. */ export class Sequence extends ActionInterval { - static _actionOneTwo = function (actionOne: ActionInterval, actionTwo: ActionInterval) { + static _actionOneTwo = function (actionOne: ActionInterval, actionTwo: ActionInterval): Sequence { const sequence = new Sequence(); sequence.initWithTwoActions(actionOne, actionTwo); return sequence; @@ -336,7 +336,7 @@ export class Sequence extends ActionInterval { * @param {FiniteTimeAction} actionTwo * @return {Boolean} */ - initWithTwoActions (actionOne: any, actionTwo: any) { + initWithTwoActions (actionOne: any, actionTwo: any): boolean { if (!actionOne || !actionTwo) { errorID(1025); return false; @@ -353,27 +353,27 @@ export class Sequence extends ActionInterval { return true; } - clone () { + clone (): any { const action = new Sequence(); this._cloneDecoration(action as any); action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone()); return action as any; } - startWithTarget (target: any) { + startWithTarget (target: any): void { ActionInterval.prototype.startWithTarget.call(this, target); this._split = this._actions[0]._duration / this._duration; this._split *= this._actions[0]._repeatMethod ? this._actions[0]._timesForRepeat : 1; this._last = -1; } - stop () { + stop (): void { // Issue #1305 if (this._last !== -1) this._actions[this._last].stop(); Action.prototype.stop.call(this); } - update (dt: number) { + update (dt: number): void { let new_t: number; let found = 0; const locSplit = this._split; const locActions = this._actions; @@ -423,7 +423,7 @@ export class Sequence extends ActionInterval { this._last = found; } - reverse () { + reverse (): any { const action = Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse()); this._cloneDecoration(action); this._reverseEaseList(action); @@ -501,7 +501,7 @@ export class Repeat extends ActionInterval { * @param {Number} times * @return {Boolean} */ - initWithAction (action: FiniteTimeAction, times: number) { + initWithAction (action: FiniteTimeAction, times: number): boolean { const duration = action._duration * times; if (this.initWithDuration(duration)) { @@ -517,26 +517,26 @@ export class Repeat extends ActionInterval { return false; } - clone () { + clone (): Repeat { const action = new Repeat(); this._cloneDecoration(action); action.initWithAction(this._innerAction!.clone(), this._times); return action; } - startWithTarget (target: any) { + startWithTarget (target: any): void { this._total = 0; this._nextDt = this._innerAction!._duration / this._duration; ActionInterval.prototype.startWithTarget.call(this, target); this._innerAction!.startWithTarget(target); } - stop () { + stop (): void { this._innerAction!.stop(); Action.prototype.stop.call(this); } - update (dt: number) { + update (dt: number): void { dt = this._computeEaseTime(dt); const locInnerAction = this._innerAction!; const locDuration = this._duration; @@ -574,11 +574,11 @@ export class Repeat extends ActionInterval { } } - isDone () { + isDone (): boolean { return this._total === this._times; } - reverse () { + reverse (): any { const action = new Repeat(this._innerAction!.reverse(), this._times); this._cloneDecoration(action); this._reverseEaseList(action); @@ -589,7 +589,7 @@ export class Repeat extends ActionInterval { * Set inner Action. * @param {FiniteTimeAction} action */ - setInnerAction (action: any) { + setInnerAction (action: any): void { if (this._innerAction !== action) { this._innerAction = action; } @@ -599,7 +599,7 @@ export class Repeat extends ActionInterval { * Get inner Action. * @return {FiniteTimeAction} */ - getInnerAction () { + getInnerAction (): FiniteTimeAction | null { return this._innerAction; } } @@ -642,7 +642,7 @@ export class RepeatForever extends ActionInterval { * @param {ActionInterval} action * @return {Boolean} */ - initWithAction (action: ActionInterval) { + initWithAction (action: ActionInterval): boolean { if (!action) { errorID(1026); return false; @@ -652,19 +652,19 @@ export class RepeatForever extends ActionInterval { return true; } - clone () { + clone (): RepeatForever { const action = new RepeatForever(); this._cloneDecoration(action); action.initWithAction(this._innerAction!.clone()); return action; } - startWithTarget (target: any) { + startWithTarget (target: any): void { ActionInterval.prototype.startWithTarget.call(this, target); this._innerAction!.startWithTarget(target); } - step (dt: any) { + step (dt: any): void { const locInnerAction = this._innerAction!; locInnerAction.step(dt); if (locInnerAction.isDone()) { @@ -677,11 +677,11 @@ export class RepeatForever extends ActionInterval { } } - isDone () { + isDone (): boolean { return false; } - reverse () { + reverse (): any { const action = new RepeatForever(this._innerAction!.reverse()); this._cloneDecoration(action); this._reverseEaseList(action); @@ -692,7 +692,7 @@ export class RepeatForever extends ActionInterval { * Set inner action. * @param {ActionInterval} action */ - setInnerAction (action: any) { + setInnerAction (action: any): void { if (this._innerAction !== action) { this._innerAction = action; } @@ -702,7 +702,7 @@ export class RepeatForever extends ActionInterval { * Get inner action. * @return {ActionInterval} */ - getInnerAction () { + getInnerAction (): ActionInstant | null { return this._innerAction; } } @@ -727,7 +727,7 @@ export function repeatForever (action?: ActionInterval): ActionInterval { * @extends ActionInterval */ export class Spawn extends ActionInterval { - static _actionOneTwo = function (action1: any, action2: any) { + static _actionOneTwo = function (action1: any, action2: any): Spawn { const pSpawn = new Spawn(); pSpawn.initWithTwoActions(action1, action2); return pSpawn; @@ -764,7 +764,7 @@ export class Spawn extends ActionInterval { * @param {FiniteTimeAction} action2 * @return {Boolean} */ - initWithTwoActions (action1: any, action2: any) { + initWithTwoActions (action1: any, action2: any): boolean { if (!action1 || !action2) { errorID(1027); return false; @@ -790,32 +790,32 @@ export class Spawn extends ActionInterval { return ret; } - clone () { + clone (): Spawn { const action = new Spawn(); this._cloneDecoration(action); action.initWithTwoActions(this._one!.clone(), this._two!.clone()); return action; } - startWithTarget (target: any) { + startWithTarget (target: any): void { ActionInterval.prototype.startWithTarget.call(this, target); this._one!.startWithTarget(target); this._two!.startWithTarget(target); } - stop () { + stop (): void { this._one!.stop(); this._two!.stop(); Action.prototype.stop.call(this); } - update (dt: any) { + update (dt: any): void { dt = this._computeEaseTime(dt); if (this._one) this._one.update(dt); if (this._two) this._two.update(dt); } - reverse () { + reverse (): any { const action = Spawn._actionOneTwo(this._one!.reverse(), this._two!.reverse()); this._cloneDecoration(action); this._reverseEaseList(action); @@ -855,16 +855,16 @@ export function spawn (/* Multiple Arguments */tempArray: any): FiniteTimeAction * @extends ActionInterval */ class DelayTime extends ActionInterval { - update (dt: any) { } + update (dt: any): void { } - reverse () { + reverse (): any { const action = new DelayTime(this._duration); this._cloneDecoration(action); this._reverseEaseList(action); return action as any; } - clone () { + clone (): DelayTime { const action = new DelayTime(); this._cloneDecoration(action); action.initWithDuration(this._duration); @@ -912,7 +912,7 @@ export class ReverseTime extends ActionInterval { * @param {FiniteTimeAction} action * @return {Boolean} */ - initWithAction (action: ActionInterval) { + initWithAction (action: ActionInterval): boolean { if (!action) { errorID(1028); return false; @@ -930,28 +930,28 @@ export class ReverseTime extends ActionInterval { return false; } - clone () { + clone (): ReverseTime { const action = new ReverseTime(); this._cloneDecoration(action); action.initWithAction(this._other!.clone()); return action; } - startWithTarget (target: any) { + startWithTarget (target: any): void { ActionInterval.prototype.startWithTarget.call(this, target); this._other!.startWithTarget(target); } - update (dt: number) { + update (dt: number): void { dt = this._computeEaseTime(dt); if (this._other) this._other.update(1 - dt); } - reverse () { + reverse (): any { return this._other!.clone() as any; } - stop () { + stop (): void { this._other!.stop(); Action.prototype.stop.call(this); } diff --git a/cocos/tween/actions/action-manager.ts b/cocos/tween/actions/action-manager.ts index 82eacd281fd..ca82dd928c9 100644 --- a/cocos/tween/actions/action-manager.ts +++ b/cocos/tween/actions/action-manager.ts @@ -72,14 +72,14 @@ export class ActionManager { private _currentTarget!: HashElement; private _elementPool: HashElement[] = []; - private _searchElementByTarget (arr: HashElement[], target: Record) { + private _searchElementByTarget (arr: HashElement[], target: Record): HashElement | null { for (let k = 0; k < arr.length; k++) { if (target === arr[k].target) return arr[k]; } return null; } - private _getElement (target: Record, paused: boolean) { + private _getElement (target: Record, paused: boolean): HashElement { let element = this._elementPool.pop(); if (!element) { element = new HashElement(); @@ -89,7 +89,7 @@ export class ActionManager { return element; } - private _putElement (element: HashElement) { + private _putElement (element: HashElement): void { element.actions.length = 0; element.actionIndex = 0; element.currentAction = null; @@ -117,7 +117,7 @@ export class ActionManager { * @param {object} target * @param {Boolean} paused */ - addAction (action: Action, target: Node, paused: boolean) { + addAction (action: Action, target: Node, paused: boolean): void { if (!action || !target) { errorID(1000); return; @@ -148,7 +148,7 @@ export class ActionManager { * @zh 移除所有对象的所有动作。 * @method removeAllActions */ - removeAllActions () { + removeAllActions (): void { const locTargets = this._arrayTargets; for (let i = 0; i < locTargets.length; i++) { const element = locTargets[i]; @@ -167,7 +167,7 @@ export class ActionManager { * @method removeAllActionsFromTarget * @param {Node} target */ - removeAllActionsFromTarget (target: Node) { + removeAllActionsFromTarget (target: Node): void { // explicit null handling if (target == null) return; const element = this._hashTargets.get(target); @@ -182,7 +182,7 @@ export class ActionManager { * @method removeAction * @param {Action} action */ - removeAction (action: Action) { + removeAction (action: Action): void { // explicit null handling if (action == null) return; const target = action.getOriginalTarget()!; @@ -203,7 +203,7 @@ export class ActionManager { /** * @internal */ - _removeActionByTag (tag: number, element: any, target?: Node) { + _removeActionByTag (tag: number, element: any, target?: Node): void { for (let i = 0, l = element.actions.length; i < l; ++i) { const action = element.actions[i]; if (action && action.getTag() === tag) { @@ -219,7 +219,7 @@ export class ActionManager { /** * @internal */ - _removeAllActionsByTag (tag: number, element: any, target?: Node) { + _removeAllActionsByTag (tag: number, element: any, target?: Node): void { for (let i = element.actions.length - 1; i >= 0; --i) { const action = element.actions[i]; if (action && action.getTag() === tag) { @@ -238,7 +238,7 @@ export class ActionManager { * @param {Number} tag * @param {Node} target */ - removeActionByTag (tag: number, target?: Node) { + removeActionByTag (tag: number, target?: Node): void { if (tag === Action.TAG_INVALID) logID(1002); const hashTargets = this._hashTargets; @@ -261,7 +261,7 @@ export class ActionManager { * @param {Number} tag * @param {Node} target */ - removeAllActionsByTag (tag: number, target?: Node) { + removeAllActionsByTag (tag: number, target?: Node): void { if (tag === Action.TAG_INVALID) logID(1002); const hashTargets = this._hashTargets; @@ -335,7 +335,7 @@ export class ActionManager { * @method pauseTarget * @param {Node} target */ - pauseTarget (target: Node) { + pauseTarget (target: Node): void { const element = this._hashTargets.get(target); if (element) element.paused = true; } @@ -345,7 +345,7 @@ export class ActionManager { * @method resumeTarget * @param {Node} target */ - resumeTarget (target: Node) { + resumeTarget (target: Node): void { const element = this._hashTargets.get(target); if (element) element.paused = false; } @@ -375,7 +375,7 @@ export class ActionManager { * @method resumeTargets * @param {Array} targetsToResume */ - resumeTargets (targetsToResume: Array) { + resumeTargets (targetsToResume: Array): void { if (!targetsToResume) return; for (let i = 0; i < targetsToResume.length; i++) { @@ -389,7 +389,7 @@ export class ActionManager { * @method pauseTargets * @param {Array} targetsToPause */ - pauseTargets (targetsToPause: Array) { + pauseTargets (targetsToPause: Array): void { if (!targetsToPause) return; for (let i = 0; i < targetsToPause.length; i++) { @@ -406,12 +406,12 @@ export class ActionManager { * 因为它使用 this,因此它不能是静态的。 * @method purgeSharedManager */ - purgeSharedManager () { + purgeSharedManager (): void { legacyCC.director.getScheduler().unscheduleUpdate(this); } // protected - private _removeActionAtIndex (index, element) { + private _removeActionAtIndex (index, element): void { const action = element.actions[index]; element.actions.splice(index, 1); @@ -424,7 +424,7 @@ export class ActionManager { } } - private _deleteHashElement (element) { + private _deleteHashElement (element): boolean { let ret = false; if (element && !element.lock) { if (this._hashTargets.get(element.target)) { @@ -449,7 +449,7 @@ export class ActionManager { * @method update * @param {Number} dt delta time in seconds */ - update (dt: number) { + update (dt: number): void { const locTargets = this._arrayTargets; let locCurrTarget; for (let elt = 0; elt < locTargets.length; elt++) { diff --git a/cocos/tween/actions/action.ts b/cocos/tween/actions/action.ts index 4da6f6c7756..065ae1bd2f9 100644 --- a/cocos/tween/actions/action.ts +++ b/cocos/tween/actions/action.ts @@ -75,23 +75,23 @@ export class Action { } // called before the action start. It will also set the target. - startWithTarget (target: any) { + startWithTarget (target: any): void { this.originalTarget = target; this.target = target; } // called after the action has finished. It will set the 'target' to nil. - stop () { + stop (): void { this.target = null; } // called every frame with it's delta time.
- step (dt: number) { + step (dt: number): void { logID(1006); } // Called once per frame. Time is the number of seconds of a frame interval. - update (dt: number) { + update (dt: number): void { logID(1007); } @@ -111,7 +111,7 @@ export class Action { * @method setTarget * @param {object} target */ - setTarget (target: Node) { + setTarget (target: Node): void { this.target = target; } @@ -128,7 +128,7 @@ export class Action { // Set the original target, since target can be nil. // Is the target that were used to run the action. // Unless you are doing something complex, like `ActionManager`, you should NOT call this method. - setOriginalTarget (originalTarget: any) { + setOriginalTarget (originalTarget: any): void { this.originalTarget = originalTarget; } @@ -148,7 +148,7 @@ export class Action { * @method setTag * @param {Number} tag */ - setTag (tag: number) { + setTag (tag: number): void { this.tag = tag; } @@ -171,12 +171,12 @@ export class Action { // Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB, // and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB. // This is a hack, and should be removed once JSB fixes the retain/release bug. - retain () { } + retain (): void { } // Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB, // and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB. // This is a hack, and should be removed once JSB fixes the retain/release bug. - release () { } + release (): void { } } /** @@ -211,7 +211,7 @@ export class FiniteTimeAction extends Action { * @method setDuration * @param {Number} duration */ - setDuration (duration: number) { + setDuration (duration: number): void { this._duration = duration; } @@ -252,7 +252,7 @@ export class Speed extends Action { * @method getSpeed * @return {Number} */ - getSpeed () { + getSpeed (): number { return this._speed; } @@ -261,7 +261,7 @@ export class Speed extends Action { * @method setSpeed * @param {Number} speed */ - setSpeed (speed: number) { + setSpeed (speed: number): void { this._speed = speed; } @@ -272,7 +272,7 @@ export class Speed extends Action { * @param {Number} speed * @return {Boolean} */ - initWithAction (action: Action, speed: number) { + initWithAction (action: Action, speed: number): boolean { if (!action) { errorID(1021); return false; @@ -283,31 +283,31 @@ export class Speed extends Action { return true; } - clone () { + clone (): Speed { const action = new Speed(); action.initWithAction(this._innerAction!.clone(), this._speed); return action; } - startWithTarget (target: any) { + startWithTarget (target: any): void { Action.prototype.startWithTarget.call(this, target); this._innerAction!.startWithTarget(target); } - stop () { + stop (): void { this._innerAction!.stop(); Action.prototype.stop.call(this); } - step (dt: number) { + step (dt: number): void { this._innerAction!.step(dt * this._speed); } - isDone () { + isDone (): boolean { return this._innerAction!.isDone(); } - reverse () { + reverse (): Speed { return new Speed(this._innerAction!.reverse()!, this._speed); } @@ -316,7 +316,7 @@ export class Speed extends Action { * @method setInnerAction * @param {ActionInterval} action */ - setInnerAction (action: any) { + setInnerAction (action: any): void { if (this._innerAction !== action) { this._innerAction = action; } @@ -327,7 +327,7 @@ export class Speed extends Action { * @method getInnerAction * @return {ActionInterval} */ - getInnerAction () { + getInnerAction (): Action | null { return this._innerAction; } } diff --git a/cocos/tween/set-action.ts b/cocos/tween/set-action.ts index 3adb5c77f39..7ad3ddd513d 100644 --- a/cocos/tween/set-action.ts +++ b/cocos/tween/set-action.ts @@ -34,14 +34,14 @@ export class SetAction extends ActionInstant { props !== undefined && this.init(props); } - init (props) { + init (props): boolean { for (const name in props) { this._props[name] = props[name]; } return true; } - update () { + update (): void { const props = this._props; const target = this.target; for (const name in props) { @@ -49,7 +49,7 @@ export class SetAction extends ActionInstant { } } - clone () { + clone (): SetAction { const action = new SetAction(); action.init(this._props); return action; diff --git a/cocos/tween/tween-action.ts b/cocos/tween/tween-action.ts index 5c47092a056..4a5c80120d6 100644 --- a/cocos/tween/tween-action.ts +++ b/cocos/tween/tween-action.ts @@ -28,7 +28,7 @@ import { ITweenOption } from './export-api'; import { VERSION } from '../core/global-exports'; /** adapter */ -function TweenEasingAdapter (easingName: string) { +function TweenEasingAdapter (easingName: string): string { const initialChar = easingName.charAt(0); if (/[A-Z]/.test(initialChar)) { easingName = easingName.replace(initialChar, initialChar.toLowerCase()); @@ -69,7 +69,7 @@ function TweenEasingAdapter (easingName: string) { } /** checker */ -function TweenOptionChecker (opts: ITweenOption) { +function TweenOptionChecker (opts: ITweenOption): void { const header = ' [Tween:] '; const message = ` option is not support in v + ${VERSION}`; const _opts = opts as unknown as any; @@ -158,13 +158,13 @@ export class TweenAction extends ActionInterval { this.initWithDuration(duration); } - clone () { + clone (): TweenAction { const action = new TweenAction(this._duration, this._originProps, this._opts); this._cloneDecoration(action); return action; } - startWithTarget (target: Record) { + startWithTarget (target: Record): void { ActionInterval.prototype.startWithTarget.call(this, target); const relative = !!this._opts.relative; @@ -199,7 +199,7 @@ export class TweenAction extends ActionInterval { if (this._opts.onStart) { this._opts.onStart(this.target); } } - update (t: number) { + update (t: number): void { const target = this.target; if (!target) return; @@ -238,7 +238,7 @@ export class TweenAction extends ActionInterval { if (t === 1 && opts.onComplete) { opts.onComplete(this.target); } } - progress (start: number, end: number, current: number, t: number) { + progress (start: number, end: number, current: number, t: number): number { return current = start + (end - start) * t; } } diff --git a/cocos/tween/tween-system.ts b/cocos/tween/tween-system.ts index 3b539fdab96..cf374619583 100644 --- a/cocos/tween/tween-system.ts +++ b/cocos/tween/tween-system.ts @@ -56,7 +56,7 @@ export class TweenSystem extends System { * @zh * 获取动作管理器。 */ - get ActionManager () { + get ActionManager (): ActionManager { return this.actionMgr; } @@ -69,7 +69,7 @@ export class TweenSystem extends System { * 此方法会在组件 update 之后自动执行。 * @param dt @en The delta time @zh 间隔时间 */ - update (dt: number) { + update (dt: number): void { if (!EDITOR_NOT_IN_PREVIEW || this._executeInEditMode) { this.actionMgr.update(dt); } diff --git a/cocos/tween/tween.ts b/cocos/tween/tween.ts index 29fb148f707..dfaca346899 100644 --- a/cocos/tween/tween.ts +++ b/cocos/tween/tween.ts @@ -26,7 +26,7 @@ import { TweenSystem } from './tween-system'; import { warn } from '../core'; import { ActionInterval, sequence, repeat, repeatForever, reverseTime, delayTime, spawn } from './actions/action-interval'; import { removeSelf, show, hide, callFunc } from './actions/action-instant'; -import { Action } from './actions/action'; +import { Action, FiniteTimeAction } from './actions/action'; import { ITweenOption } from './export-api'; import { TweenAction } from './tween-action'; import { SetAction } from './set-action'; @@ -70,7 +70,7 @@ export class Tween { * @method tag * @param tag @en The tag set for this tween @zh 为当前缓动设置的标签 */ - tag (tag: number) { + tag (tag: number): Tween { this._tag = tag; return this; } @@ -407,7 +407,7 @@ export class Tween { * @zh * 停止所有缓动 */ - static stopAll () { + static stopAll (): void { TweenSystem.instance.ActionManager.removeAllActions(); } /** @@ -417,7 +417,7 @@ export class Tween { * 停止所有指定标签的缓动 */ // eslint-disable-next-line @typescript-eslint/ban-types - static stopAllByTag (tag: number, target?: object) { + static stopAllByTag (tag: number, target?: object): void { TweenSystem.instance.ActionManager.removeAllActionsByTag(tag, target as any); } /** @@ -427,11 +427,11 @@ export class Tween { * 停止所有指定对象的缓动 */ // eslint-disable-next-line @typescript-eslint/ban-types - static stopAllByTarget (target?: object) { + static stopAllByTarget (target?: object): void { TweenSystem.instance.ActionManager.removeAllActionsFromTarget(target as any); } - private _union () { + private _union (): Action { const actions = this._actions; let action: Action; if (actions.length === 1) { @@ -443,13 +443,13 @@ export class Tween { return action; } - private _destroy () { + private _destroy (): void { this.stop(); } private static readonly _tmp_args: Tween[] | Action[] = []; - private static _wrappedSequence (...args: Action[] | Tween[]) { + private static _wrappedSequence (...args: Action[] | Tween[]): ActionInterval { const tmp_args = Tween._tmp_args; tmp_args.length = 0; for (let l = args.length, i = 0; i < l; i++) { @@ -462,7 +462,7 @@ export class Tween { return sequence.apply(sequence, tmp_args as any); } - private static _wrappedParallel (...args: Action[] | Tween[]) { + private static _wrappedParallel (...args: Action[] | Tween[]): FiniteTimeAction { const tmp_args = Tween._tmp_args; tmp_args.length = 0; for (let l = args.length, i = 0; i < l; i++) { @@ -491,7 +491,7 @@ legacyCC.Tween = Tween; * .by(1, {scale: new Vec3(-1, -1, -1)}, {easing: 'sineOutIn'}) * .start() */ -export function tween (target?: T) { +export function tween (target?: T): Tween { return new Tween(target); } legacyCC.tween = tween; @@ -503,7 +503,7 @@ legacyCC.tween = tween; * tweenUtil 是一个工具函数,帮助实例化 Tween 实例。 * @deprecated please use `tween` instead. */ -export function tweenUtil (target?: T) { +export function tweenUtil (target?: T): Tween { warn('tweenUtil\' is deprecated, please use \'tween\' instead '); return new Tween(target); } diff --git a/cocos/ui/block-input-events.ts b/cocos/ui/block-input-events.ts index 7321e501cd1..7c4ad89daab 100644 --- a/cocos/ui/block-input-events.ts +++ b/cocos/ui/block-input-events.ts @@ -32,7 +32,7 @@ const BlockEvents = [NodeEventType.TOUCH_START, NodeEventType.TOUCH_END, NodeEve NodeEventType.MOUSE_DOWN, NodeEventType.MOUSE_MOVE, NodeEventType.MOUSE_UP, NodeEventType.MOUSE_ENTER, NodeEventType.MOUSE_LEAVE, NodeEventType.MOUSE_WHEEL]; -function stopPropagation (event: Event) { +function stopPropagation (event: Event): void { event.propagationStopped = true; } @@ -49,7 +49,7 @@ function stopPropagation (event: Event) { @help('i18n:cc.BlockInputEvents') @menu('Event/BlockInputEvents') export class BlockInputEvents extends Component { - onEnable () { + onEnable (): void { for (let i = 0; i < BlockEvents.length; i++) { // supply the 'this' parameter so that the callback could be added and removed correctly, // even if the same component is added more than once to a Node. @@ -57,7 +57,7 @@ export class BlockInputEvents extends Component { } } - onDisable () { + onDisable (): void { for (let i = 0; i < BlockEvents.length; i++) { this.node.off(BlockEvents[i], stopPropagation, this); } diff --git a/cocos/ui/button.ts b/cocos/ui/button.ts index 9a7f94ef695..2411f97a860 100644 --- a/cocos/ui/button.ts +++ b/cocos/ui/button.ts @@ -192,7 +192,7 @@ export class Button extends Component { @type(Node) @displayOrder(0) @tooltip('i18n:button.target') - get target () { + get target (): Node { return this._target || this.node; } @@ -218,7 +218,7 @@ export class Button extends Component { */ @displayOrder(1) @tooltip('i18n:button.interactable') - get interactable () { + get interactable (): boolean { return this._interactable; } @@ -261,7 +261,7 @@ export class Button extends Component { @type(Transition) @displayOrder(2) @tooltip('i18n:button.transition') - get transition () { + get transition (): Transition { return this._transition; } @@ -382,7 +382,7 @@ export class Button extends Component { @rangeMax(10) @displayOrder(4) @tooltip('i18n:button.duration') - get duration () { + get duration (): number { return this._duration; } @@ -408,7 +408,7 @@ export class Button extends Component { */ @displayOrder(3) @tooltip('i18n:button.zoom_scale') - get zoomScale () { + get zoomScale (): number { return this._zoomScale; } @@ -431,7 +431,7 @@ export class Button extends Component { @type(SpriteFrame) @displayOrder(3) @tooltip('i18n:button.normal_sprite') - get normalSprite () { + get normalSprite (): SpriteFrame | null { return this._normalSprite; } @@ -459,7 +459,7 @@ export class Button extends Component { @type(SpriteFrame) @displayOrder(3) @tooltip('i18n:button.pressed_sprite') - get pressedSprite () { + get pressedSprite (): SpriteFrame | null { return this._pressedSprite; } @@ -482,7 +482,7 @@ export class Button extends Component { @type(SpriteFrame) @displayOrder(3) @tooltip('i18n:button.hover_sprite') - get hoverSprite () { + get hoverSprite (): SpriteFrame | null { return this._hoverSprite; } @@ -505,7 +505,7 @@ export class Button extends Component { @type(SpriteFrame) @displayOrder(3) @tooltip('i18n:button.disabled_sprite') - get disabledSprite () { + get disabledSprite (): SpriteFrame | null { return this._disabledSprite; } @@ -578,7 +578,7 @@ export class Button extends Component { private _sprite: Sprite | null = null; private _targetScale: Vec3 = new Vec3(); - public __preload () { + public __preload (): void { if (!this.target) { this.target = this.node; } @@ -592,7 +592,7 @@ export class Button extends Component { this._resetState(); } - public onEnable () { + public onEnable (): void { // check sprite frames // if (!EDITOR_NOT_IN_PREVIEW) { @@ -612,7 +612,7 @@ export class Button extends Component { } } - public onDisable () { + public onDisable (): void { this._resetState(); if (!EDITOR_NOT_IN_PREVIEW) { @@ -622,13 +622,13 @@ export class Button extends Component { } } - public onDestroy () { + public onDestroy (): void { if (this.target.isValid) { this._unregisterTargetEvent(this.target); } } - public update (dt: number) { + public update (dt: number): void { const target = this.target; if (this._transitionFinished || !target) { return; @@ -666,7 +666,7 @@ export class Button extends Component { } } - protected _resizeNodeToTargetNode () { + protected _resizeNodeToTargetNode (): void { if (!this.target) { return; } @@ -676,7 +676,7 @@ export class Button extends Component { } } - protected _resetState () { + protected _resetState (): void { this._pressed = false; this._hovered = false; // Restore button status @@ -696,7 +696,7 @@ export class Button extends Component { this._transitionFinished = true; } - protected _registerNodeEvent () { + protected _registerNodeEvent (): void { this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this); this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMove, this); this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this); @@ -711,7 +711,7 @@ export class Button extends Component { this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); } - protected _registerTargetEvent (target) { + protected _registerTargetEvent (target): void { if (EDITOR_NOT_IN_PREVIEW) { target.on(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onTargetSpriteFrameChanged, this); target.on(NodeEventType.COLOR_CHANGED, this._onTargetColorChanged, this); @@ -719,7 +719,7 @@ export class Button extends Component { target.on(NodeEventType.TRANSFORM_CHANGED, this._onTargetTransformChanged, this); } - protected _unregisterNodeEvent () { + protected _unregisterNodeEvent (): void { this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this); this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMove, this); this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this); @@ -734,7 +734,7 @@ export class Button extends Component { this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); } - protected _unregisterTargetEvent (target) { + protected _unregisterTargetEvent (target): void { if (EDITOR_NOT_IN_PREVIEW) { target.off(Sprite.EventType.SPRITE_FRAME_CHANGED); target.off(NodeEventType.COLOR_CHANGED); @@ -742,7 +742,7 @@ export class Button extends Component { target.off(NodeEventType.TRANSFORM_CHANGED); } - protected _getTargetSprite (target: Node | null) { + protected _getTargetSprite (target: Node | null): Sprite | null { let sprite: Sprite | null = null; if (target) { sprite = target.getComponent(Sprite); @@ -750,7 +750,7 @@ export class Button extends Component { return sprite; } - protected _applyTarget () { + protected _applyTarget (): void { if (this.target) { this._sprite = this._getTargetSprite(this.target); if (!this._originalScale) { @@ -761,13 +761,13 @@ export class Button extends Component { } } - private _onTargetSpriteFrameChanged (comp: Sprite) { + private _onTargetSpriteFrameChanged (comp: Sprite): void { if (this._transition === Transition.SPRITE) { this._setCurrentStateSpriteFrame(comp.spriteFrame); } } - private _setCurrentStateSpriteFrame (spriteFrame: SpriteFrame | null) { + private _setCurrentStateSpriteFrame (spriteFrame: SpriteFrame | null): void { if (!spriteFrame) { return; } @@ -789,13 +789,13 @@ export class Button extends Component { } } - private _onTargetColorChanged (color: Color) { + private _onTargetColorChanged (color: Color): void { if (this._transition === Transition.COLOR) { this._setCurrentStateColor(color); } } - private _setCurrentStateColor (color: Color) { + private _setCurrentStateColor (color: Color): void { switch (this._getButtonState()) { case State.NORMAL: this._normalColor = color; @@ -814,7 +814,7 @@ export class Button extends Component { } } - private _onTargetTransformChanged (transformBit: TransformBit) { + private _onTargetTransformChanged (transformBit: TransformBit): void { // update originalScale if ((transformBit & TransformBit.SCALE) && this._originalScale && this._transition === Transition.SCALE && this._transitionFinished) { @@ -823,7 +823,7 @@ export class Button extends Component { } // touch event handler - protected _onTouchBegan (event?: EventTouch) { + protected _onTouchBegan (event?: EventTouch): void { if (!this._interactable || !this.enabledInHierarchy) { return; } this._pressed = true; @@ -833,7 +833,7 @@ export class Button extends Component { } } - protected _onTouchMove (event?: EventTouch) { + protected _onTouchMove (event?: EventTouch): void { if (!this._interactable || !this.enabledInHierarchy || !this._pressed) { return; } // mobile phone will not emit _onMouseMoveOut, // so we have to do hit test when touch moving @@ -873,7 +873,7 @@ export class Button extends Component { } } - protected _onTouchEnded (event?: EventTouch) { + protected _onTouchEnded (event?: EventTouch): void { if (!this._interactable || !this.enabledInHierarchy) { return; } @@ -890,14 +890,14 @@ export class Button extends Component { } } - protected _onTouchCancel (event?: EventTouch) { + protected _onTouchCancel (event?: EventTouch): void { if (!this._interactable || !this.enabledInHierarchy) { return; } this._pressed = false; this._updateState(); } - protected _onMouseMoveIn (event?: EventMouse) { + protected _onMouseMoveIn (event?: EventMouse): void { if (this._pressed || !this.interactable || !this.enabledInHierarchy) { return; } if (this._transition === Transition.SPRITE && !this._hoverSprite) { return; } @@ -907,7 +907,7 @@ export class Button extends Component { } } - protected _onMouseMoveOut (event?: EventMouse) { + protected _onMouseMoveOut (event?: EventMouse): void { if (this._hovered) { this._hovered = false; this._updateState(); @@ -915,12 +915,12 @@ export class Button extends Component { } // state handler - protected _updateState () { + protected _updateState (): void { const state = this._getButtonState(); this._applyTransition(state); } - protected _getButtonState () { + protected _getButtonState (): string { let state = State.NORMAL; if (!this._interactable) { state = State.DISABLED; @@ -932,7 +932,7 @@ export class Button extends Component { return state.toString(); } - protected _updateColorTransition (state: string) { + protected _updateColorTransition (state: string): void { const color = this[`${state}Color`]; const renderComp = this.target?.getComponent(UIRenderer); @@ -950,14 +950,14 @@ export class Button extends Component { } } - protected _updateSpriteTransition (state: string) { + protected _updateSpriteTransition (state: string): void { const sprite = this[`${state}Sprite`]; if (this._sprite && sprite) { this._sprite.spriteFrame = sprite; } } - protected _updateScaleTransition (state: string) { + protected _updateScaleTransition (state: string): void { if (!this._interactable) { return; } @@ -969,7 +969,7 @@ export class Button extends Component { } } - protected _zoomUp () { + protected _zoomUp (): void { // skip before __preload() if (!this._originalScale) { return; @@ -980,7 +980,7 @@ export class Button extends Component { this._transitionFinished = false; } - protected _zoomBack () { + protected _zoomBack (): void { if (!this.target || !this._originalScale) { return; } @@ -990,7 +990,7 @@ export class Button extends Component { this._transitionFinished = false; } - protected _applyTransition (state: string) { + protected _applyTransition (state: string): void { const transition = this._transition; if (transition === Transition.COLOR) { this._updateColorTransition(state); @@ -1001,12 +1001,12 @@ export class Button extends Component { } } - private _xrHoverEnter () { + private _xrHoverEnter (): void { this._onMouseMoveIn(); this._updateState(); } - private _xrHoverExit () { + private _xrHoverExit (): void { this._onMouseMoveOut(); if (this._pressed) { this._pressed = false; @@ -1014,13 +1014,13 @@ export class Button extends Component { } } - private _xrClick () { + private _xrClick (): void { if (!this._interactable || !this.enabledInHierarchy) { return; } this._pressed = true; this._updateState(); } - private _xrUnClick () { + private _xrUnClick (): void { if (!this._interactable || !this.enabledInHierarchy) { return; } diff --git a/cocos/ui/editbox/edit-box-impl-base.ts b/cocos/ui/editbox/edit-box-impl-base.ts index 7d75bbd1919..7b742034370 100644 --- a/cocos/ui/editbox/edit-box-impl-base.ts +++ b/cocos/ui/editbox/edit-box-impl-base.ts @@ -37,27 +37,27 @@ export class EditBoxImplBase { */ public _delegate: EditBox | null = null; - public init (delegate: EditBox) {} + public init (delegate: EditBox): void {} - public onEnable () {} + public onEnable (): void {} - public update () { } + public update (): void { } - public onDisable () { + public onDisable (): void { if (this._editing) { this.endEditing(); } } - public clear () { + public clear (): void { this._delegate = null; } - public setTabIndex (index: number) {} + public setTabIndex (index: number): void {} - public setSize (width: number, height: number) {} + public setSize (width: number, height: number): void {} - public setFocus (value) { + public setFocus (value): void { if (value) { this.beginEditing(); } else { @@ -65,11 +65,11 @@ export class EditBoxImplBase { } } - public isFocused () { + public isFocused (): boolean { return this._editing; } - public beginEditing () {} + public beginEditing (): void {} - public endEditing () {} + public endEditing (): void {} } diff --git a/cocos/ui/editbox/edit-box-impl.ts b/cocos/ui/editbox/edit-box-impl.ts index 9fcc7b7a958..57138707eb0 100644 --- a/cocos/ui/editbox/edit-box-impl.ts +++ b/cocos/ui/editbox/edit-box-impl.ts @@ -103,7 +103,7 @@ export class EditBoxImpl extends EditBoxImplBase { private _placeholderStyleSheet: HTMLStyleElement | null = null; private _domId = `EditBoxId_${++_domCount}`; - public init (delegate: EditBox) { + public init (delegate: EditBox): void { if (!delegate) { return; } @@ -122,7 +122,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._addDomToGameContainer(); } - public clear () { + public clear (): void { this._removeEventListeners(); this._removeDomFromGameContainer(); @@ -136,16 +136,16 @@ export class EditBoxImpl extends EditBoxImplBase { this._delegate = null; } - public update () { + public update (): void { this._updateMatrix(); } - public setTabIndex (index: number) { + public setTabIndex (index: number): void { this._edTxt!.tabIndex = index; tabIndexUtil.resort(); } - public setSize (width: number, height: number) { + public setSize (width: number, height: number): void { const elem = this._edTxt; if (elem) { elem.style.width = `${width}px`; @@ -153,7 +153,7 @@ export class EditBoxImpl extends EditBoxImplBase { } } - public beginEditing () { + public beginEditing (): void { if (_currentEditBoxImpl && _currentEditBoxImpl !== this) { _currentEditBoxImpl.setFocus(false); } @@ -165,28 +165,28 @@ export class EditBoxImpl extends EditBoxImplBase { this._edTxt!.focus(); } - public endEditing () { + public endEditing (): void { this._edTxt!.blur(); } - private _createInput () { + private _createInput (): void { this._isTextArea = false; this._edTxt = ccdocument.createElement('input'); } - private _createTextArea () { + private _createTextArea (): void { this._isTextArea = true; this._edTxt = ccdocument.createElement('textarea'); } - private _addDomToGameContainer () { + private _addDomToGameContainer (): void { if (game.container && this._edTxt) { game.container.appendChild(this._edTxt); ccdocument.head.appendChild(this._placeholderStyleSheet!); } } - private _removeDomFromGameContainer () { + private _removeDomFromGameContainer (): void { const hasElem = contains(game.container, this._edTxt); if (hasElem && this._edTxt) { game.container!.removeChild(this._edTxt); @@ -200,7 +200,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._placeholderStyleSheet = null; } - private _showDom () { + private _showDom (): void { this._updateMaxLength(); this._updateInputType(); this._updateStyleSheet(); @@ -213,7 +213,7 @@ export class EditBoxImpl extends EditBoxImplBase { } } - private _hideDom () { + private _hideDom (): void { const elem = this._edTxt; if (elem && this._delegate) { elem.style.display = 'none'; @@ -224,7 +224,7 @@ export class EditBoxImpl extends EditBoxImplBase { } } - private _showDomOnMobile () { + private _showDomOnMobile (): void { if (sys.os !== OS.ANDROID && sys.os !== OS.OHOS) { return; } @@ -233,7 +233,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._adjustWindowScroll(); } - private _hideDomOnMobile () { + private _hideDomOnMobile (): void { if (sys.os === OS.ANDROID || sys.os === OS.OHOS) { screenAdapter.handleResizeEvent = true; } @@ -241,7 +241,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._scrollBackWindow(); } - private _adjustWindowScroll () { + private _adjustWindowScroll (): void { setTimeout(() => { if (ccwindow.scrollY < SCROLLY) { this._edTxt!.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth' }); @@ -249,7 +249,7 @@ export class EditBoxImpl extends EditBoxImplBase { }, DELAY_TIME); } - private _scrollBackWindow () { + private _scrollBackWindow (): void { setTimeout(() => { if (sys.browserType === BrowserType.WECHAT && sys.os === OS.IOS) { if (ccwindow.top) { @@ -263,7 +263,7 @@ export class EditBoxImpl extends EditBoxImplBase { }, DELAY_TIME); } - private _updateMatrix () { + private _updateMatrix (): void { if (!this._edTxt) { return; } @@ -322,7 +322,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; } - private _updateInputType () { + private _updateInputType (): void { const delegate = this._delegate; const inputMode = delegate!.inputMode; const inputFlag = delegate!.inputFlag; @@ -392,7 +392,7 @@ export class EditBoxImpl extends EditBoxImplBase { elem.style.textTransform = textTransform; } - private _updateMaxLength () { + private _updateMaxLength (): void { let maxLength = this._delegate!.maxLength; if (maxLength < 0) { maxLength = 65535; @@ -400,7 +400,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._edTxt!.maxLength = maxLength; } - private _initStyleSheet () { + private _initStyleSheet (): void { if (!this._edTxt) { return; } @@ -433,7 +433,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._placeholderStyleSheet = ccdocument.createElement('style'); } - private _updateStyleSheet () { + private _updateStyleSheet (): void { const delegate = this._delegate; const elem = this._edTxt; if (elem && delegate) { @@ -446,7 +446,7 @@ export class EditBoxImpl extends EditBoxImplBase { } } - private _updateTextLabel (textLabel) { + private _updateTextLabel (textLabel): void { if (!textLabel) { return; } @@ -496,7 +496,7 @@ export class EditBoxImpl extends EditBoxImplBase { } } - private _updatePlaceholderLabel (placeholderLabel) { + private _updatePlaceholderLabel (placeholderLabel): void { if (!placeholderLabel) { return; } @@ -553,7 +553,7 @@ export class EditBoxImpl extends EditBoxImplBase { } } - private _registerEventListeners () { + private _registerEventListeners (): void { if (!this._edTxt) { return; } @@ -562,16 +562,16 @@ export class EditBoxImpl extends EditBoxImplBase { let inputLock = false; const cbs = this.__eventListeners; - cbs.compositionStart = () => { + cbs.compositionStart = (): void => { inputLock = true; }; - cbs.compositionEnd = () => { + cbs.compositionEnd = (): void => { inputLock = false; this._delegate!._editBoxTextChanged(elem.value); }; - cbs.onInput = () => { + cbs.onInput = (): void => { if (inputLock) { return; } @@ -584,7 +584,7 @@ export class EditBoxImpl extends EditBoxImplBase { delegate!._editBoxTextChanged(elem.value); }; - cbs.onClick = () => { + cbs.onClick = (): void => { if (this._editing) { if (sys.isMobile) { this._adjustWindowScroll(); @@ -592,7 +592,7 @@ export class EditBoxImpl extends EditBoxImplBase { } }; - cbs.onKeydown = (e) => { + cbs.onKeydown = (e): void => { if (e.keyCode === KeyCode.ENTER) { e.propagationStopped = true; this._delegate!._editBoxEditingReturn(); @@ -608,7 +608,7 @@ export class EditBoxImpl extends EditBoxImplBase { } }; - cbs.onBlur = () => { + cbs.onBlur = (): void => { // on mobile, sometimes input element doesn't fire compositionend event if (sys.isMobile && inputLock) { cbs.compositionEnd(); @@ -626,7 +626,7 @@ export class EditBoxImpl extends EditBoxImplBase { elem.addEventListener('blur', cbs.onBlur); elem.addEventListener('touchstart', cbs.onClick); } - private _removeEventListeners () { + private _removeEventListeners (): void { if (!this._edTxt) { return; } diff --git a/cocos/ui/editbox/edit-box.ts b/cocos/ui/editbox/edit-box.ts index b34956a7bc9..c781ff0bb2c 100644 --- a/cocos/ui/editbox/edit-box.ts +++ b/cocos/ui/editbox/edit-box.ts @@ -43,11 +43,11 @@ import { XrKeyboardEventType, XrUIPressEventType } from '../../xr/event/xr-event const LEFT_PADDING = 2; -function capitalize (str: string) { +function capitalize (str: string): string { return str.replace(/(?:^|\s)\S/g, (a) => a.toUpperCase()); } -function capitalizeFirstLetter (str: string) { +function capitalizeFirstLetter (str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); } @@ -83,7 +83,7 @@ export class EditBox extends Component { */ @displayOrder(1) @tooltip('i18n:editbox.string') - get string () { + get string (): string { return this._string; } @@ -109,7 +109,7 @@ export class EditBox extends Component { */ @displayOrder(2) @tooltip('i18n:editbox.placeholder') - get placeholder () { + get placeholder (): string { if (!this._placeholderLabel) { return ''; } @@ -132,7 +132,7 @@ export class EditBox extends Component { @type(Label) @displayOrder(3) @tooltip('i18n:editbox.text_lable') - get textLabel () { + get textLabel (): Label | null { return this._textLabel; } @@ -156,7 +156,7 @@ export class EditBox extends Component { @type(Label) @displayOrder(4) @tooltip('i18n:editbox.placeholder_label') - get placeholderLabel () { + get placeholderLabel (): Label | null { return this._placeholderLabel; } @@ -180,7 +180,7 @@ export class EditBox extends Component { @type(SpriteFrame) @displayOrder(5) @tooltip('i18n:editbox.backgroundImage') - get backgroundImage () { + get backgroundImage (): SpriteFrame | null { return this._backgroundImage; } @@ -204,7 +204,7 @@ export class EditBox extends Component { @type(InputFlag) @displayOrder(6) @tooltip('i18n:editbox.input_flag') - get inputFlag () { + get inputFlag (): InputFlag { return this._inputFlag; } @@ -228,7 +228,7 @@ export class EditBox extends Component { @type(InputMode) @displayOrder(7) @tooltip('i18n:editbox.input_mode') - get inputMode () { + get inputMode (): InputMode { return this._inputMode; } @@ -252,7 +252,7 @@ export class EditBox extends Component { @type(KeyboardReturnType) @displayOrder(8) @tooltip('i18n:editbox.returnType') - get returnType () { + get returnType (): KeyboardReturnType { return this._returnType; } @@ -273,7 +273,7 @@ export class EditBox extends Component { */ @displayOrder(9) @tooltip('i18n:editbox.max_length') - get maxLength () { + get maxLength (): number { return this._maxLength; } set maxLength (value: number) { @@ -289,7 +289,7 @@ export class EditBox extends Component { */ @displayOrder(10) @tooltip('i18n:editbox.tab_index') - get tabIndex () { + get tabIndex (): number { return this._tabIndex; } @@ -408,11 +408,11 @@ export class EditBox extends Component { private _isLabelVisible = false; - public __preload () { + public __preload (): void { this._init(); } - public onEnable () { + public onEnable (): void { if (!EDITOR_NOT_IN_PREVIEW) { this._registerEvent(); } @@ -422,13 +422,13 @@ export class EditBox extends Component { } } - public update () { + public update (): void { if (this._impl) { this._impl.update(); } } - public onDisable () { + public onDisable (): void { if (!EDITOR_NOT_IN_PREVIEW) { this._unregisterEvent(); } @@ -438,7 +438,7 @@ export class EditBox extends Component { } } - public onDestroy () { + public onDestroy (): void { if (this._impl) { this._impl.clear(); } @@ -448,7 +448,7 @@ export class EditBox extends Component { * @en Let the EditBox get focus. * @zh 让当前 EditBox 获得焦点。 */ - public setFocus () { + public setFocus (): void { if (this._impl) { this._impl.setFocus(true); } @@ -458,7 +458,7 @@ export class EditBox extends Component { * @en Let the EditBox get focus. * @zh 让当前 EditBox 获得焦点。 */ - public focus () { + public focus (): void { if (this._impl) { this._impl.setFocus(true); } @@ -468,7 +468,7 @@ export class EditBox extends Component { * @en Let the EditBox lose focus. * @zh 让当前 EditBox 失去焦点。 */ - public blur () { + public blur (): void { if (this._impl) { this._impl.setFocus(false); } @@ -479,7 +479,7 @@ export class EditBox extends Component { * @zh 判断 EditBox 是否获得了焦点。 * Note: only available on Web at the moment. */ - public isFocused () { + public isFocused (): boolean { if (this._impl) { return this._impl.isFocused(); } @@ -489,7 +489,7 @@ export class EditBox extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _editBoxEditingDidBegan () { + public _editBoxEditingDidBegan (): void { ComponentEventHandler.emitEvents(this.editingDidBegan, this); this.node.emit(EventType.EDITING_DID_BEGAN, this); } @@ -500,7 +500,7 @@ export class EditBox extends Component { * If relevant platform returns desensitized content, it will be passed to developer by EventType.EDITING_DID_ENDED. * Now only ByteDance minigame platform */ - public _editBoxEditingDidEnded (text?: string) { + public _editBoxEditingDidEnded (text?: string): void { ComponentEventHandler.emitEvents(this.editingDidEnded, this); this.node.emit(EventType.EDITING_DID_ENDED, this, text); } @@ -508,7 +508,7 @@ export class EditBox extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _editBoxTextChanged (text: string) { + public _editBoxTextChanged (text: string): void { text = this._updateLabelStringStyle(text, true); this.string = text; ComponentEventHandler.emitEvents(this.textChanged, text, this); @@ -521,7 +521,7 @@ export class EditBox extends Component { * If relevant platform returns desensitized content, it will be passed to developer by EventType.EDITING_RETURN. * Now only ByteDance minigame platform */ - public _editBoxEditingReturn (text?: string) { + public _editBoxEditingReturn (text?: string): void { ComponentEventHandler.emitEvents(this.editingReturn, this); this.node.emit(EventType.EDITING_RETURN, this, text); } @@ -529,7 +529,7 @@ export class EditBox extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _showLabels () { + public _showLabels (): void { this._isLabelVisible = true; this._updateLabels(); } @@ -537,7 +537,7 @@ export class EditBox extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _hideLabels () { + public _hideLabels (): void { this._isLabelVisible = false; if (this._textLabel) { this._textLabel.node.active = false; @@ -547,22 +547,22 @@ export class EditBox extends Component { } } - protected _onTouchBegan (event: EventTouch) { + protected _onTouchBegan (event: EventTouch): void { event.propagationStopped = true; } - protected _onTouchCancel (event: EventTouch) { + protected _onTouchCancel (event: EventTouch): void { event.propagationStopped = true; } - protected _onTouchEnded (event: EventTouch) { + protected _onTouchEnded (event: EventTouch): void { if (this._impl) { this._impl.beginEditing(); } event.propagationStopped = true; } - protected _init () { + protected _init (): void { this._updatePlaceholderLabel(); this._updateTextLabel(); this._isLabelVisible = true; @@ -574,7 +574,7 @@ export class EditBox extends Component { this._syncSize(); } - protected _ensureBackgroundSprite () { + protected _ensureBackgroundSprite (): void { if (!this._background) { let background = this.node.getComponent(Sprite); if (!background) { @@ -590,7 +590,7 @@ export class EditBox extends Component { } } - protected _updateTextLabel () { + protected _updateTextLabel (): void { let textLabel = this._textLabel; // If textLabel doesn't exist, create one. @@ -617,7 +617,7 @@ export class EditBox extends Component { textLabel.string = this._updateLabelStringStyle(this._string); } - protected _updatePlaceholderLabel () { + protected _updatePlaceholderLabel (): void { let placeholderLabel = this._placeholderLabel; // If placeholderLabel doesn't exist, create one. @@ -643,7 +643,7 @@ export class EditBox extends Component { placeholderLabel.string = this.placeholder; } - protected _syncSize () { + protected _syncSize (): void { const trans = this.node._uiProps.uiTransformComp!; const size = trans.contentSize; @@ -659,7 +659,7 @@ export class EditBox extends Component { } } - protected _updateLabels () { + protected _updateLabels (): void { if (this._isLabelVisible) { const content = this._string; if (this._textLabel) { @@ -671,7 +671,7 @@ export class EditBox extends Component { } } - protected _updateString (text: string) { + protected _updateString (text: string): void { const textLabel = this._textLabel; // Not inited yet if (!textLabel) { @@ -688,7 +688,7 @@ export class EditBox extends Component { this._updateLabels(); } - protected _updateLabelStringStyle (text: string, ignorePassword = false) { + protected _updateLabelStringStyle (text: string, ignorePassword = false): string { const inputFlag = this._inputFlag; if (!ignorePassword && inputFlag === InputFlag.PASSWORD) { let passwordString = ''; @@ -708,7 +708,7 @@ export class EditBox extends Component { return text; } - protected _registerEvent () { + protected _registerEvent (): void { this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this); this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this); @@ -716,7 +716,7 @@ export class EditBox extends Component { this.node.on(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this); } - protected _unregisterEvent () { + protected _unregisterEvent (): void { this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this); this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this); @@ -724,24 +724,24 @@ export class EditBox extends Component { this.node.off(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this); } - private _onBackgroundSpriteFrameChanged () { + private _onBackgroundSpriteFrameChanged (): void { if (!this._background) { return; } this.backgroundImage = this._background.spriteFrame; } - private _registerBackgroundEvent () { + private _registerBackgroundEvent (): void { const node = this._background && this._background.node; node?.on(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this); } - private _unregisterBackgroundEvent () { + private _unregisterBackgroundEvent (): void { const node = this._background && this._background.node; node?.off(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this); } - protected _updateLabelPosition (size: Size) { + protected _updateLabelPosition (size: Size): void { const trans = this.node._uiProps.uiTransformComp!; const offX = -trans.anchorX * trans.width; const offY = -trans.anchorY * trans.height; @@ -765,7 +765,7 @@ export class EditBox extends Component { } } - protected _resizeChildNodes () { + protected _resizeChildNodes (): void { const trans = this.node._uiProps.uiTransformComp!; const textLabelNode = this._textLabel && this._textLabel.node; if (textLabelNode) { @@ -785,11 +785,11 @@ export class EditBox extends Component { this._syncSize(); } - protected _xrUnClick () { + protected _xrUnClick (): void { this.node.emit(EventType.XR_EDITING_DID_BEGAN, this._maxLength, this.string); } - protected _xrKeyBoardInput (str: string) { + protected _xrKeyBoardInput (str: string): void { this.string = str; } } diff --git a/cocos/ui/editbox/tabIndexUtil.ts b/cocos/ui/editbox/tabIndexUtil.ts index 525fc542ddd..0ab941fa9a9 100644 --- a/cocos/ui/editbox/tabIndexUtil.ts +++ b/cocos/ui/editbox/tabIndexUtil.ts @@ -27,7 +27,7 @@ import { EditBoxImpl } from './edit-box-impl'; export class tabIndexUtil { public static _tabIndexList: EditBoxImpl[] = []; - public static add (editBoxImpl: EditBoxImpl) { + public static add (editBoxImpl: EditBoxImpl): void { const list = this._tabIndexList; const index = list.indexOf(editBoxImpl); if (index === -1) { @@ -35,7 +35,7 @@ export class tabIndexUtil { } } - public static remove (editBoxImpl: EditBoxImpl) { + public static remove (editBoxImpl: EditBoxImpl): void { const list = this._tabIndexList; const index = list.indexOf(editBoxImpl); if (index !== -1) { @@ -43,11 +43,11 @@ export class tabIndexUtil { } } - public static resort () { + public static resort (): void { this._tabIndexList.sort((a: EditBoxImpl, b: EditBoxImpl) => a._delegate!.tabIndex - b._delegate!.tabIndex); } - public static next (editBoxImpl: EditBoxImpl) { + public static next (editBoxImpl: EditBoxImpl): void { const list = this._tabIndexList; const index = list.indexOf(editBoxImpl); editBoxImpl.setFocus(false); diff --git a/cocos/ui/layout.ts b/cocos/ui/layout.ts index b1f0d7978d4..88c64aec0c1 100644 --- a/cocos/ui/layout.ts +++ b/cocos/ui/layout.ts @@ -219,11 +219,11 @@ export class Layout extends Component { * @zh * 横向对齐。在 Type 为 Horizontal 时按同个方向固定起始位置排列。 */ - @visible(function (this: Layout) { + @visible(function (this: Layout): boolean { return this._layoutType === Type.HORIZONTAL; }) @tooltip('i18n:layout.align_horizontal') - get alignHorizontal () { + get alignHorizontal (): boolean { return this._isAlign; } @@ -243,11 +243,11 @@ export class Layout extends Component { * @zh * 纵向对齐。在 Type 为 Horizontal 或 Vertical 时按同个方向固定起始位置排列。 */ - @visible(function (this: Layout) { + @visible(function (this: Layout): boolean { return this._layoutType === Type.VERTICAL; }) @tooltip('i18n:layout.align_vertical') - get alignVertical () { + get alignVertical (): boolean { return this._isAlign; } @@ -270,7 +270,7 @@ export class Layout extends Component { @type(Type) @displayOrder(0) @tooltip('i18n:layout.layout_type') - get type () { + get type (): Type { return this._layoutType; } @@ -286,11 +286,11 @@ export class Layout extends Component { * 缩放模式。 */ @type(ResizeMode) - @visible(function (this: Layout) { + @visible(function (this: Layout): boolean { return this._layoutType !== Type.NONE; }) @tooltip('i18n:layout.resize_mode') - get resizeMode () { + get resizeMode (): ResizeMode { return this._resizeMode; } set resizeMode (value) { @@ -340,7 +340,7 @@ export class Layout extends Component { */ @type(AxisDirection) @tooltip('i18n:layout.start_axis') - get startAxis () { + get startAxis (): AxisDirection { return this._startAxis; } @@ -360,7 +360,7 @@ export class Layout extends Component { * 容器内左边距,只会在一个布局方向上生效。 */ @tooltip('i18n:layout.padding_left') - get paddingLeft () { + get paddingLeft (): number { return this._paddingLeft; } set paddingLeft (value) { @@ -380,7 +380,7 @@ export class Layout extends Component { * 容器内右边距,只会在一个布局方向上生效。 */ @tooltip('i18n:layout.padding_right') - get paddingRight () { + get paddingRight (): number { return this._paddingRight; } set paddingRight (value) { @@ -400,7 +400,7 @@ export class Layout extends Component { * 容器内上边距,只会在一个布局方向上生效。 */ @tooltip('i18n:layout.padding_top') - get paddingTop () { + get paddingTop (): number { return this._paddingTop; } set paddingTop (value) { @@ -420,7 +420,7 @@ export class Layout extends Component { * 容器内下边距,只会在一个布局方向上生效。 */ @tooltip('i18n:layout.padding_bottom') - get paddingBottom () { + get paddingBottom (): number { return this._paddingBottom; } set paddingBottom (value) { @@ -440,7 +440,7 @@ export class Layout extends Component { * 子节点之间的水平间距。 */ @tooltip('i18n:layout.space_x') - get spacingX () { + get spacingX (): number { return this._spacingX; } @@ -461,7 +461,7 @@ export class Layout extends Component { * 子节点之间的垂直间距。 */ @tooltip('i18n:layout.space_y') - get spacingY () { + get spacingY (): number { return this._spacingY; } @@ -484,7 +484,7 @@ export class Layout extends Component { */ @type(VerticalDirection) @tooltip('i18n:layout.vertical_direction') - get verticalDirection () { + get verticalDirection (): VerticalDirection { return this._verticalDirection; } @@ -507,7 +507,7 @@ export class Layout extends Component { */ @type(HorizontalDirection) @tooltip('i18n:layout.horizontal_direction') - get horizontalDirection () { + get horizontalDirection (): HorizontalDirection { return this._horizontalDirection; } @@ -527,7 +527,7 @@ export class Layout extends Component { * @zh * 容器内边距,该属性会在四个布局方向上生效。 */ - get padding () { + get padding (): number { return this._paddingLeft; } @@ -546,11 +546,11 @@ export class Layout extends Component { * 容器内布局约束。 */ @type(Constraint) - @visible(function (this: Layout) { + @visible(function (this: Layout): boolean { return this.type === Type.GRID; }) @tooltip('i18n:layout.constraint') - get constraint () { + get constraint (): Constraint { return this._constraint; } @@ -570,11 +570,11 @@ export class Layout extends Component { * @zh * 容器内布局约束使用的限定值。 */ - @visible(function (this: Layout) { + @visible(function (this: Layout): boolean { return this._constraint !== Constraint.NONE; }) @tooltip('i18n:layout.constraint_number') - get constraintNum () { + get constraintNum (): number { return this._constraintNum; } @@ -599,7 +599,7 @@ export class Layout extends Component { * 子节点缩放比例是否影响布局。 */ @tooltip('i18n:layout.affected_scale') - get affectedByScale () { + get affectedByScale (): boolean { return this._affectedByScale; } @@ -695,14 +695,14 @@ export class Layout extends Component { * log(childNode.x); // changed * ``` */ - public updateLayout (force = false) { + public updateLayout (force = false): void { if (this._layoutDirty || force) { this._doLayout(); this._layoutDirty = false; } } - protected onEnable () { + protected onEnable (): void { this._addEventListeners(); const trans = this.node._uiProps.uiTransformComp!; @@ -713,12 +713,12 @@ export class Layout extends Component { this._childrenChanged(); } - protected onDisable () { + protected onDisable (): void { this._usefulLayoutObj.length = 0; this._removeEventListeners(); } - protected _checkUsefulObj () { + protected _checkUsefulObj (): void { this._usefulLayoutObj.length = 0; const children = this.node.children; for (let i = 0; i < children.length; ++i) { @@ -730,7 +730,7 @@ export class Layout extends Component { } } - protected _addEventListeners () { + protected _addEventListeners (): void { director.on(Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.on(NodeEventType.SIZE_CHANGED, this._resized, this); this.node.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -741,7 +741,7 @@ export class Layout extends Component { this._addChildrenEventListeners(); } - protected _removeEventListeners () { + protected _removeEventListeners (): void { director.off(Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.off(NodeEventType.SIZE_CHANGED, this._resized, this); this.node.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -752,7 +752,7 @@ export class Layout extends Component { this._removeChildrenEventListeners(); } - protected _addChildrenEventListeners () { + protected _addChildrenEventListeners (): void { const children = this.node.children; for (let i = 0; i < children.length; ++i) { const child = children[i]; @@ -763,7 +763,7 @@ export class Layout extends Component { } } - protected _removeChildrenEventListeners () { + protected _removeChildrenEventListeners (): void { const children = this.node.children; for (let i = 0; i < children.length; ++i) { const child = children[i]; @@ -774,7 +774,7 @@ export class Layout extends Component { } } - protected _childAdded (child: Node) { + protected _childAdded (child: Node): void { child.on(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this); child.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -782,7 +782,7 @@ export class Layout extends Component { this._childrenChanged(); } - protected _childRemoved (child: Node) { + protected _childRemoved (child: Node): void { child.off(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this); child.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -790,12 +790,12 @@ export class Layout extends Component { this._childrenChanged(); } - protected _resized () { + protected _resized (): void { this._layoutSize.set(this.node._uiProps.uiTransformComp!.contentSize); this._doLayoutDirty(); } - protected _doLayoutHorizontally (baseWidth: number, rowBreak: boolean, fnPositionY: (...args: any[]) => number, applyChildren: boolean) { + protected _doLayoutHorizontally (baseWidth: number, rowBreak: boolean, fnPositionY: (...args: any[]) => number, applyChildren: boolean): number { const trans = this.node._uiProps.uiTransformComp!; const layoutAnchor = trans.anchorPoint; const limit = this._getFixedBreakingNum(); @@ -889,7 +889,7 @@ export class Layout extends Component { return containerResizeBoundary; } - protected _doLayoutVertically (baseHeight: number, columnBreak: boolean, fnPositionX: (...args: any[]) => number, applyChildren: boolean) { + protected _doLayoutVertically (baseHeight: number, columnBreak: boolean, fnPositionX: (...args: any[]) => number, applyChildren: boolean): number { const trans = this.node._uiProps.uiTransformComp!; const layoutAnchor = trans.anchorPoint; const limit = this._getFixedBreakingNum(); @@ -985,7 +985,7 @@ export class Layout extends Component { return containerResizeBoundary; } - protected _doLayoutGridAxisHorizontal (layoutAnchor: Vec2 | Readonly, layoutSize: Size) { + protected _doLayoutGridAxisHorizontal (layoutAnchor: Vec2 | Readonly, layoutSize: Size): void { const baseWidth = layoutSize.width; let sign = 1; @@ -997,7 +997,7 @@ export class Layout extends Component { paddingY = this._paddingTop; } - const fnPositionY = (child: Node, childTrans: UITransform, topOffset: number) => bottomBoundaryOfLayout + sign * (topOffset + (1 - childTrans.anchorY) * childTrans.height * this._getUsedScaleValue(child.scale.y) + paddingY); + const fnPositionY = (child: Node, childTrans: UITransform, topOffset: number): number => bottomBoundaryOfLayout + sign * (topOffset + (1 - childTrans.anchorY) * childTrans.height * this._getUsedScaleValue(child.scale.y) + paddingY); let newHeight = 0; if (this._resizeMode === ResizeMode.CONTAINER) { @@ -1018,7 +1018,7 @@ export class Layout extends Component { } } - protected _doLayoutGridAxisVertical (layoutAnchor: Vec2 | Readonly, layoutSize: Size) { + protected _doLayoutGridAxisVertical (layoutAnchor: Vec2 | Readonly, layoutSize: Size): void { const baseHeight = layoutSize.height; let sign = 1; @@ -1030,7 +1030,7 @@ export class Layout extends Component { paddingX = this._paddingRight; } - const fnPositionX = (child: Node, childTrans: UITransform, leftOffset: number) => leftBoundaryOfLayout + sign * (leftOffset + (1 - childTrans.anchorX) * childTrans.width * this._getUsedScaleValue(child.scale.x) + paddingX); + const fnPositionX = (child: Node, childTrans: UITransform, leftOffset: number): number => leftBoundaryOfLayout + sign * (leftOffset + (1 - childTrans.anchorX) * childTrans.width * this._getUsedScaleValue(child.scale.x) + paddingX); let newWidth = 0; if (this._resizeMode === ResizeMode.CONTAINER) { @@ -1051,7 +1051,7 @@ export class Layout extends Component { } } - protected _doLayoutGrid () { + protected _doLayoutGrid (): void { const trans = this.node._uiProps.uiTransformComp!; const layoutAnchor = trans.anchorPoint; const layoutSize = trans.contentSize; @@ -1063,7 +1063,7 @@ export class Layout extends Component { } } - protected _getHorizontalBaseWidth (horizontal = true) { + protected _getHorizontalBaseWidth (horizontal = true): number { const children = this._usefulLayoutObj; let baseSize = 0; const activeChildCount = children.length; @@ -1083,7 +1083,7 @@ export class Layout extends Component { return baseSize; } - protected _getVerticalBaseHeight () { + protected _getVerticalBaseHeight (): number { const children = this._usefulLayoutObj; let baseSize = 0; const activeChildCount = children.length; @@ -1103,7 +1103,7 @@ export class Layout extends Component { return baseSize; } - protected _doLayout () { + protected _doLayout (): void { if (!this._init || this._childrenDirty) { this._checkUsefulObj(); this._init = true; @@ -1113,7 +1113,7 @@ export class Layout extends Component { if (this._layoutType === Type.HORIZONTAL) { const newWidth = this._getHorizontalBaseWidth(); - const fnPositionY = (child: Node) => { + const fnPositionY = (child: Node): number => { const pos = this._isAlign ? Vec3.ZERO : child.position; return pos.y; }; @@ -1123,7 +1123,7 @@ export class Layout extends Component { } else if (this._layoutType === Type.VERTICAL) { const newHeight = this._getVerticalBaseHeight(); - const fnPositionX = (child: Node) => { + const fnPositionX = (child: Node): number => { const pos = this._isAlign ? Vec3.ZERO : child.position; return pos.x; }; @@ -1135,11 +1135,11 @@ export class Layout extends Component { } } - protected _getUsedScaleValue (value: number) { + protected _getUsedScaleValue (value: number): number { return this._affectedByScale ? Math.abs(value) : 1; } - protected _transformDirty (type: TransformBit) { + protected _transformDirty (type: TransformBit): void { if (!(type & TransformBit.SCALE) || !(type & TransformBit.POSITION) || !this._affectedByScale) { return; } @@ -1147,24 +1147,24 @@ export class Layout extends Component { this._doLayoutDirty(); } - protected _doLayoutDirty () { + protected _doLayoutDirty (): void { this._layoutDirty = true; } - protected _childrenChanged () { + protected _childrenChanged (): void { this._childrenDirty = true; this._doLayoutDirty(); } - protected _getPaddingH () { + protected _getPaddingH (): number { return this._paddingLeft + this._paddingRight; } - protected _getPaddingV () { + protected _getPaddingV (): number { return this._paddingTop + this._paddingBottom; } - protected _getFixedBreakingNum () { + protected _getFixedBreakingNum (): number { if (this._layoutType !== Type.GRID || this._constraint === Constraint.NONE || this._constraintNum <= 0) { return 0; } diff --git a/cocos/ui/page-view-indicator.ts b/cocos/ui/page-view-indicator.ts index 6ba3fd1f74f..c11fa514e81 100644 --- a/cocos/ui/page-view-indicator.ts +++ b/cocos/ui/page-view-indicator.ts @@ -82,7 +82,7 @@ export class PageViewIndicator extends Component { */ @type(SpriteFrame) @tooltip('i18n:pageview_indicator.spriteFrame') - get spriteFrame () { + get spriteFrame (): SpriteFrame | null { return this._spriteFrame; } @@ -104,7 +104,7 @@ export class PageViewIndicator extends Component { */ @type(Direction) @tooltip('i18n:pageview_indicator.direction') - get direction () { + get direction (): Direction { return this._direction; } @@ -124,7 +124,7 @@ export class PageViewIndicator extends Component { */ @type(Size) @tooltip('i18n:pageview_indicator.cell_size') - get cellSize () { + get cellSize (): Size { return this._cellSize; } @@ -162,7 +162,7 @@ export class PageViewIndicator extends Component { protected _pageView: PageView | null = null; protected _indicators: Node[] = []; - public onLoad () { + public onLoad (): void { this._updateLayout(); } @@ -175,7 +175,7 @@ export class PageViewIndicator extends Component { * * @param target @en The page view which is attached with this indicator. @zh 当前标记对象附着到的页面视图对象。 */ - public setPageView (target: PageView) { + public setPageView (target: PageView): void { this._pageView = target; this._refresh(); } @@ -183,7 +183,7 @@ export class PageViewIndicator extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _updateLayout () { + public _updateLayout (): void { this._layout = this.getComponent(Layout); if (!this._layout) { this._layout = this.addComponent(Layout); @@ -203,7 +203,7 @@ export class PageViewIndicator extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _createIndicator () { + public _createIndicator (): Node { const node = new Node(); node.layer = this.node.layer; const sprite = node.addComponent(Sprite); @@ -217,7 +217,7 @@ export class PageViewIndicator extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _changedState () { + public _changedState (): void { const indicators = this._indicators; if (indicators.length === 0 || !this._pageView) { return; } const idx = this._pageView.curPageIdx; @@ -245,7 +245,7 @@ export class PageViewIndicator extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _refresh () { + public _refresh (): void { if (!this._pageView) { return; } const indicators = this._indicators; const pages = this._pageView.getPages(); diff --git a/cocos/ui/page-view.ts b/cocos/ui/page-view.ts index 44aea64f713..30fbcacecc6 100644 --- a/cocos/ui/page-view.ts +++ b/cocos/ui/page-view.ts @@ -110,7 +110,7 @@ export class PageView extends ScrollView { */ @type(SizeMode) @tooltip('i18n:pageview.sizeMode') - get sizeMode () { + get sizeMode (): SizeMode { return this._sizeMode; } @@ -132,7 +132,7 @@ export class PageView extends ScrollView { */ @type(Direction) @tooltip('i18n:pageview.direction') - get direction () { + get direction (): Direction { return this._direction; } @@ -156,7 +156,7 @@ export class PageView extends ScrollView { @slide @range([0, 1, 0.01]) @tooltip('i18n:pageview.scrollThreshold') - get scrollThreshold () { + get scrollThreshold (): number { return this._scrollThreshold; } @@ -178,7 +178,7 @@ export class PageView extends ScrollView { @slide @range([0, 1, 0.01]) @tooltip('i18n:pageview.pageTurningEventTiming') - get pageTurningEventTiming () { + get pageTurningEventTiming (): number { return this._pageTurningEventTiming; } @@ -199,7 +199,7 @@ export class PageView extends ScrollView { */ @type(PageViewIndicator) @tooltip('i18n:pageview.indicator') - get indicator () { + get indicator (): PageViewIndicator | null { return this._indicator; } @@ -214,7 +214,7 @@ export class PageView extends ScrollView { } } - get curPageIdx () { + get curPageIdx (): number { return this._curPageIdx; } @@ -258,7 +258,7 @@ export class PageView extends ScrollView { @type(ScrollBar) @override @visible(false) - get verticalScrollBar () { + get verticalScrollBar (): ScrollBar | null { return super.verticalScrollBar; } @@ -275,7 +275,7 @@ export class PageView extends ScrollView { @type(ScrollBar) @override @visible(false) - get horizontalScrollBar () { + get horizontalScrollBar (): ScrollBar | null { return super.horizontalScrollBar; } @@ -368,7 +368,7 @@ export class PageView extends ScrollView { protected _touchBeganPosition = new Vec2(); protected _touchEndPosition = new Vec2(); - public onEnable () { + public onEnable (): void { super.onEnable(); this.node.on(NodeEventType.SIZE_CHANGED, this._updateAllPagesSize, this); if (!EDITOR_NOT_IN_PREVIEW) { @@ -376,7 +376,7 @@ export class PageView extends ScrollView { } } - public onDisable () { + public onDisable (): void { super.onDisable(); this.node.off(NodeEventType.SIZE_CHANGED, this._updateAllPagesSize, this); if (!EDITOR_NOT_IN_PREVIEW) { @@ -384,7 +384,7 @@ export class PageView extends ScrollView { } } - public onLoad () { + public onLoad (): void { this._initPages(); if (this.indicator) { this.indicator.setPageView(this); @@ -400,7 +400,7 @@ export class PageView extends ScrollView { * * @returns @en Current page index of this page view. @zh 当前页面索引。 */ - public getCurrentPageIndex () { + public getCurrentPageIndex (): number { return this._curPageIdx; } @@ -412,7 +412,7 @@ export class PageView extends ScrollView { * 设置当前页面索引。 * @param index @en The page index to scroll to. @zh 需要滚动到的页面索引。 */ - public setCurrentPageIndex (index: number) { + public setCurrentPageIndex (index: number): void { this.scrollToPage(index, 1); } @@ -425,7 +425,7 @@ export class PageView extends ScrollView { * * @returns @en return all pages of this page view. @zh 返回当前视图所有页面。 */ - public getPages () { + public getPages (): Node[] { return this._pages; } @@ -438,7 +438,7 @@ export class PageView extends ScrollView { * * @param page @en New page to add to this page view. @zh 新加入的视图。 */ - public addPage (page: Node) { + public addPage (page: Node): void { if (!page || this._pages.indexOf(page) !== -1 || !this.content) { return; } @@ -461,7 +461,7 @@ export class PageView extends ScrollView { * @param page @en New page to insert to this page view. @zh 新插入的视图。 * @param index @en The index of new page to be inserted. @zh 新插入视图的索引。 */ - public insertPage (page: Node, index: number) { + public insertPage (page: Node, index: number): void { if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) { return; } @@ -488,7 +488,7 @@ export class PageView extends ScrollView { * * @param page @en The page to be removed. @zh 将被移除的页面。 */ - public removePage (page: Node) { + public removePage (page: Node): void { if (!page || !this.content) { return; } const index = this._pages.indexOf(page); if (index === -1) { @@ -507,7 +507,7 @@ export class PageView extends ScrollView { * * @param index @en The index of the page to be removed. @zh 将被移除界面的页面下标。 */ - public removePageAtIndex (index: number) { + public removePageAtIndex (index: number): void { const pageList = this._pages; if (index < 0 || index >= pageList.length) { return; } const page = pageList[index]; @@ -524,7 +524,7 @@ export class PageView extends ScrollView { * @zh * 移除所有页面。 */ - public removeAllPages () { + public removeAllPages (): void { if (!this.content) { return; } const locPages = this._pages; for (let i = 0, len = locPages.length; i < len; i++) { @@ -544,7 +544,7 @@ export class PageView extends ScrollView { * @param idx @en The index of page to be scroll to. @zh 希望滚动到的页面下标。 * @param timeInSecond @en How long time to scroll to the page, in seconds. @zh 滚动到指定页面所需时间,单位:秒。 */ - public scrollToPage (idx: number, timeInSecond = 0.3) { + public scrollToPage (idx: number, timeInSecond = 0.3): void { if (idx < 0 || idx >= this._pages.length) { return; } @@ -557,12 +557,12 @@ export class PageView extends ScrollView { } // override the method of ScrollView - public getScrollEndedEventTiming () { + public getScrollEndedEventTiming (): number { return this.pageTurningEventTiming; } // 刷新页面视图 - protected _updatePageView () { + protected _updatePageView (): void { // 当页面数组变化时修改 content 大小 if (!this.content) { return; @@ -597,7 +597,7 @@ export class PageView extends ScrollView { } // 刷新所有页面的大小 - protected _updateAllPagesSize () { + protected _updateAllPagesSize (): void { const viewTrans = this.view; if (!this.content || !viewTrans) { return; @@ -613,7 +613,7 @@ export class PageView extends ScrollView { } } - protected _handleReleaseLogic () { + protected _handleReleaseLogic (): void { this._autoScrollToPage(); if (this._scrolling) { this._scrolling = false; @@ -623,36 +623,36 @@ export class PageView extends ScrollView { } } - protected _onTouchBegan (event: EventTouch, captureListeners: any) { + protected _onTouchBegan (event: EventTouch, captureListeners: any): void { event.touch!.getUILocation(_tempVec2); Vec2.set(this._touchBeganPosition, _tempVec2.x, _tempVec2.y); super._onTouchBegan(event, captureListeners); } - protected _onTouchMoved (event: EventTouch, captureListeners: any) { + protected _onTouchMoved (event: EventTouch, captureListeners: any): void { super._onTouchMoved(event, captureListeners); } - protected _onTouchEnded (event: EventTouch, captureListeners: any) { + protected _onTouchEnded (event: EventTouch, captureListeners: any): void { event.touch!.getUILocation(_tempVec2); Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y); super._onTouchEnded(event, captureListeners); } - protected _onTouchCancelled (event: EventTouch, captureListeners: any) { + protected _onTouchCancelled (event: EventTouch, captureListeners: any): void { event.touch!.getUILocation(_tempVec2); Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y); super._onTouchCancelled(event, captureListeners); } - protected _onMouseWheel () { } + protected _onMouseWheel (): void { } - protected _syncScrollDirection () { + protected _syncScrollDirection (): void { this.horizontal = this.direction === Direction.Horizontal; this.vertical = this.direction === Direction.Vertical; } - protected _syncSizeMode () { + protected _syncSizeMode (): void { const viewTrans = this.view; if (!this.content || !viewTrans) { return; } const layout = this.content.getComponent(Layout); @@ -673,7 +673,7 @@ export class PageView extends ScrollView { } // 初始化页面 - protected _initPages () { + protected _initPages (): void { if (!this.content) { return; } this._initContentPos = this.content.position as Vec3; const children = this.content.children; @@ -687,7 +687,7 @@ export class PageView extends ScrollView { this._updatePageView(); } - protected _dispatchPageTurningEvent () { + protected _dispatchPageTurningEvent (): void { if (this._lastPageIdx === this._curPageIdx) { return; } this._lastPageIdx = this._curPageIdx; ComponentEventHandler.emitEvents(this.pageEvents, this, EventType.PAGE_TURNING); @@ -695,7 +695,7 @@ export class PageView extends ScrollView { } // 快速滑动 - protected _isQuicklyScrollable (touchMoveVelocity: Vec3) { + protected _isQuicklyScrollable (touchMoveVelocity: Vec3): boolean { if (this.direction === Direction.Horizontal) { if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) { return true; @@ -709,7 +709,7 @@ export class PageView extends ScrollView { } // 通过 idx 获取偏移值数值 - protected _moveOffsetValue (idx: number) { + protected _moveOffsetValue (idx: number): Vec2 { const offset = new Vec2(); if (this._sizeMode === SizeMode.Free) { if (this.direction === Direction.Horizontal) { @@ -731,7 +731,7 @@ export class PageView extends ScrollView { return offset; } - protected _getDragDirection (moveOffset: Vec2) { + protected _getDragDirection (moveOffset: Vec2): number { if (this._direction === Direction.Horizontal) { if (moveOffset.x === 0) { return 0; @@ -749,7 +749,7 @@ export class PageView extends ScrollView { } // 是否超过自动滚动临界值 - protected _isScrollable (offset: Vec2, index: number, nextIndex: number) { + protected _isScrollable (offset: Vec2, index: number, nextIndex: number): boolean { if (this._sizeMode === SizeMode.Free) { let curPageCenter = 0; let nextPageCenter = 0; @@ -776,7 +776,7 @@ export class PageView extends ScrollView { return false; } - protected _autoScrollToPage () { + protected _autoScrollToPage (): void { const bounceBackStarted = this._startBounceBackIfNeeded(); if (bounceBackStarted) { const bounceBackAmount = this._getHowMuchOutOfBoundary(); diff --git a/cocos/ui/progress-bar.ts b/cocos/ui/progress-bar.ts index 02571362986..73f22fb9425 100644 --- a/cocos/ui/progress-bar.ts +++ b/cocos/ui/progress-bar.ts @@ -109,7 +109,7 @@ export class ProgressBar extends Component { */ @type(Sprite) @tooltip('i18n:progress.bar_sprite') - get barSprite () { + get barSprite (): Sprite | null { return this._barSprite; } @@ -131,7 +131,7 @@ export class ProgressBar extends Component { */ @type(Mode) @tooltip('i18n:progress.mode') - get mode () { + get mode (): Mode { return this._mode; } @@ -164,7 +164,7 @@ export class ProgressBar extends Component { * 进度条实际的总长度。 */ @tooltip('i18n:progress.total_length') - get totalLength () { + get totalLength (): number { return this._totalLength; } @@ -191,7 +191,7 @@ export class ProgressBar extends Component { @range([0, 1, 0.1]) @slide @tooltip('i18n:progress.progress') - get progress () { + get progress (): number { return this._progress; } @@ -212,7 +212,7 @@ export class ProgressBar extends Component { * 进度条是否进行反方向变化。 */ @tooltip('i18n:progress.reverse') - get reverse () { + get reverse (): boolean { return this._reverse; } @@ -240,7 +240,7 @@ export class ProgressBar extends Component { @serializable protected _reverse = false; - protected _initBarSprite () { + protected _initBarSprite (): void { if (this._barSprite) { const entity = this._barSprite.node; if (!entity) { return; } @@ -274,7 +274,7 @@ export class ProgressBar extends Component { } } - protected _updateBarStatus () { + protected _updateBarStatus (): void { if (this._barSprite) { const entity = this._barSprite.node; diff --git a/cocos/ui/safe-area.ts b/cocos/ui/safe-area.ts index a2f1f61c8da..ecb6646c1ee 100644 --- a/cocos/ui/safe-area.ts +++ b/cocos/ui/safe-area.ts @@ -58,14 +58,14 @@ import { view } from './view'; @menu('UI/SafeArea') @requireComponent(Widget) export class SafeArea extends Component { - public onEnable () { + public onEnable (): void { this.updateArea(); // IDEA: need to delay the callback on Native platform ? screenAdapter.on('window-resize', this.updateArea, this); screenAdapter.on('orientation-change', this.updateArea, this); } - public onDisable () { + public onDisable (): void { screenAdapter.off('window-resize', this.updateArea, this); screenAdapter.off('orientation-change', this.updateArea, this); } @@ -78,7 +78,7 @@ export class SafeArea extends Component { * let safeArea = this.node.addComponent(cc.SafeArea); * safeArea.updateArea(); */ - public updateArea () { + public updateArea (): void { // TODO Remove Widget dependencies in the future const widget = this.node.getComponent(Widget) as Widget; const uiTransComp = this.node.getComponent(UITransform) as UITransform; diff --git a/cocos/ui/scroll-bar.ts b/cocos/ui/scroll-bar.ts index d4a4f29aaa5..9ee14709b1a 100644 --- a/cocos/ui/scroll-bar.ts +++ b/cocos/ui/scroll-bar.ts @@ -94,7 +94,7 @@ export class ScrollBar extends Component { @type(Sprite) @displayOrder(0) @tooltip('i18n:scrollbar.handle') - get handle () { + get handle (): Sprite | null { return this._handle; } @@ -116,7 +116,7 @@ export class ScrollBar extends Component { @type(Direction) @displayOrder(1) @tooltip('i18n:scrollbar.direction') - get direction () { + get direction (): Direction { return this._direction; } @@ -138,7 +138,7 @@ export class ScrollBar extends Component { */ @displayOrder(2) @tooltip('i18n:scrollbar.auto_hide') - get enableAutoHide () { + get enableAutoHide (): boolean { return this._enableAutoHide; } @@ -164,7 +164,7 @@ export class ScrollBar extends Component { */ @displayOrder(3) @tooltip('i18n:scrollbar.auto_hide_time') - get autoHideTime () { + get autoHideTime (): number { return this._autoHideTime; } @@ -199,7 +199,7 @@ export class ScrollBar extends Component { * @zh * 滚动条隐藏。 */ - public hide () { + public hide (): void { this._autoHideRemainingTime = 0; this._setOpacity(0); } @@ -211,7 +211,7 @@ export class ScrollBar extends Component { * @zh * 滚动条显示。 */ - public show () { + public show (): void { this._autoHideRemainingTime = this._autoHideTime; // because scrollbar's onEnable is later than scrollView, its _opacity is be modified in onEnable. we should reset it. this._opacity = 255; @@ -227,7 +227,7 @@ export class ScrollBar extends Component { * * @param outOfBoundary @en Rolling displacement. @zh 滚动位移。 */ - public onScroll (outOfBoundary: Vec2 | Readonly) { + public onScroll (outOfBoundary: Vec2 | Readonly): void { if (!this._scrollView) { return; } @@ -293,18 +293,18 @@ export class ScrollBar extends Component { * * @param scrollView @en The scroll view which is attached with this scroll bar. @zh 当前滚动条附着的滚动视窗。 */ - public setScrollView (scrollView: ScrollView) { + public setScrollView (scrollView: ScrollView): void { this._scrollView = scrollView; } - public onTouchBegan () { + public onTouchBegan (): void { if (!this._enableAutoHide) { return; } this._touching = true; } - public onTouchEnded () { + public onTouchEnded (): void { if (!this._enableAutoHide) { return; } @@ -329,24 +329,24 @@ export class ScrollBar extends Component { this._autoHideRemainingTime = this._autoHideTime; } - protected onEnable () { + protected onEnable (): void { const renderComp = this.node.getComponent(Sprite); if (renderComp) { this._opacity = renderComp.color.a; } } - protected start () { + protected start (): void { if (this._enableAutoHide) { this._setOpacity(0); } } - protected update (dt) { + protected update (dt): void { this._processAutoHide(dt); } - protected _convertToScrollViewSpace (out: Vec2, content: Node) { + protected _convertToScrollViewSpace (out: Vec2, content: Node): void { const scrollTrans = this._scrollView && this._scrollView.node._uiProps.uiTransformComp; const contentTrans = content._uiProps.uiTransformComp; if (!scrollTrans || !contentTrans) { @@ -362,7 +362,7 @@ export class ScrollBar extends Component { } } - protected _setOpacity (opacity: number) { + protected _setOpacity (opacity: number): void { if (this._handle) { let renderComp = this.node.getComponent(Sprite); if (renderComp) { @@ -380,7 +380,7 @@ export class ScrollBar extends Component { } } - protected _updateHandlerPosition (position: Vec2) { + protected _updateHandlerPosition (position: Vec2): void { if (this._handle) { const oldPosition = _tempVec3; this._fixupHandlerPosition(oldPosition); @@ -389,7 +389,7 @@ export class ScrollBar extends Component { } } - protected _fixupHandlerPosition (out: Vec3) { + protected _fixupHandlerPosition (out: Vec3): void { const uiTrans = this.node._uiProps.uiTransformComp!; const barSize = uiTrans.contentSize; const barAnchor = uiTrans.anchorPoint; @@ -412,7 +412,7 @@ export class ScrollBar extends Component { this.handle!.node.setPosition(fixupPosition); } - protected _conditionalDisableScrollBar (contentSize: Size, scrollViewSize: Size) { + protected _conditionalDisableScrollBar (contentSize: Size, scrollViewSize: Size): boolean { if (contentSize.width <= scrollViewSize.width && this._direction === Direction.HORIZONTAL) { return true; } @@ -423,7 +423,7 @@ export class ScrollBar extends Component { return false; } - protected _calculateLength (contentMeasure: number, scrollViewMeasure: number, handleNodeMeasure: number, outOfBoundary: number) { + protected _calculateLength (contentMeasure: number, scrollViewMeasure: number, handleNodeMeasure: number, outOfBoundary: number): number { let denominatorValue = contentMeasure; if (outOfBoundary) { denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTING_SHORTER_FACTOR; @@ -441,7 +441,7 @@ export class ScrollBar extends Component { contentPosition: number, outOfBoundary: number, actualLenth: number, - ) { + ): void { let denominatorValue = contentMeasure - scrollViewMeasure; if (outOfBoundary) { denominatorValue += Math.abs(outOfBoundary); @@ -461,7 +461,7 @@ export class ScrollBar extends Component { } } - protected _updateLength (length: number) { + protected _updateLength (length: number): void { if (this._handle) { const handleNode = this._handle.node; const handleTrans = handleNode._uiProps.uiTransformComp!; @@ -479,7 +479,7 @@ export class ScrollBar extends Component { } } - protected _processAutoHide (deltaTime: number) { + protected _processAutoHide (deltaTime: number): void { if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) { return; } else if (this._touching) { diff --git a/cocos/ui/scroll-view.ts b/cocos/ui/scroll-view.ts index 3480ef86680..6087f46b427 100644 --- a/cocos/ui/scroll-view.ts +++ b/cocos/ui/scroll-view.ts @@ -51,12 +51,12 @@ const _tempVec3_1 = new Vec3(); const _tempVec2 = new Vec2(); const _tempVec2_1 = new Vec2(); -const quintEaseOut = (time: number) => { +const quintEaseOut = (time: number): number => { time -= 1; return (time * time * time * time * time + 1); }; -const getTimeInMilliseconds = () => { +const getTimeInMilliseconds = (): number => { const currentTime = new Date(); return currentTime.getMilliseconds(); }; @@ -275,7 +275,7 @@ export class ScrollView extends ViewGroup { @type(Node) @displayOrder(5) @tooltip('i18n:scrollview.content') - get content () { + get content (): Node | null { return this._content; } set content (value) { @@ -313,7 +313,7 @@ export class ScrollView extends ViewGroup { @type(ScrollBar) @displayOrder(0) @tooltip('i18n:scrollview.horizontal_bar') - get horizontalScrollBar () { + get horizontalScrollBar (): ScrollBar | null { if (this._horizontalScrollBar && !this._horizontalScrollBar.isValid) { errorID(4303, 'horizontal', this.node.name); } @@ -355,7 +355,7 @@ export class ScrollView extends ViewGroup { @type(ScrollBar) @displayOrder(1) @tooltip('i18n:scrollview.vertical_bar') - get verticalScrollBar () { + get verticalScrollBar (): ScrollBar | null { if (this._verticalScrollBar && !this._verticalScrollBar.isValid) { errorID(4303, 'vertical', this.node.name); } @@ -406,7 +406,7 @@ export class ScrollView extends ViewGroup { * @en The display view in the scroll view component. * @zh scroll view 组件中的显示区域。 */ - get view () { + get view (): UITransform | null { const parent = this._content && this._content.parent; if (!parent) { return null; @@ -470,7 +470,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToBottom(0.1); * ``` */ - public scrollToBottom (timeInSecond?: number, attenuated = true) { + public scrollToBottom (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: false, @@ -500,7 +500,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToTop(0.1); * ``` */ - public scrollToTop (timeInSecond?: number, attenuated = true) { + public scrollToTop (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 1), applyToHorizontal: false, @@ -530,7 +530,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToLeft(0.1); * ``` */ - public scrollToLeft (timeInSecond?: number, attenuated = true) { + public scrollToLeft (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: true, @@ -560,7 +560,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToRight(0.1); * ``` */ - public scrollToRight (timeInSecond?: number, attenuated = true) { + public scrollToRight (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 0), applyToHorizontal: true, @@ -590,7 +590,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToTopLeft(0.1); * ``` */ - public scrollToTopLeft (timeInSecond?: number, attenuated = true) { + public scrollToTopLeft (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 1), applyToHorizontal: true, @@ -620,7 +620,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToTopRight(0.1); * ``` */ - public scrollToTopRight (timeInSecond?: number, attenuated = true) { + public scrollToTopRight (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 1), applyToHorizontal: true, @@ -650,7 +650,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToBottomLeft(0.1); * ``` */ - public scrollToBottomLeft (timeInSecond?: number, attenuated = true) { + public scrollToBottomLeft (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: true, @@ -680,7 +680,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToBottomRight(0.1); * ``` */ - public scrollToBottomRight (timeInSecond?: number, attenuated = true) { + public scrollToBottomRight (timeInSecond?: number, attenuated = true): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 0), applyToHorizontal: true, @@ -714,7 +714,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToOffset(new Vec2(maxScrollOffset.x / 2, 0), 0.1); * ``` */ - public scrollToOffset (offset: Vec2, timeInSecond?: number, attenuated = true) { + public scrollToOffset (offset: Vec2, timeInSecond?: number, attenuated = true): void { const maxScrollOffset = this.getMaxScrollOffset(); const anchor = new Vec2(0, 0); @@ -743,7 +743,7 @@ export class ScrollView extends ViewGroup { * * @return @en Current rolling offset. @zh 当前滚动偏移量。 */ - public getScrollOffset () { + public getScrollOffset (): Vec2 { const topDelta = this._getContentTopBoundary() - this._topBoundary; const leftDelta = this._getContentLeftBoundary() - this._leftBoundary; @@ -759,7 +759,7 @@ export class ScrollView extends ViewGroup { * * @return @en Maximum scrollable offset. @zh 最大可滚动偏移量。 */ - public getMaxScrollOffset () { + public getMaxScrollOffset (): Vec2 { if (!this._content || !this.view) { return Vec2.ZERO; } @@ -790,7 +790,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToBottomRight(0.5, 0.1); * ``` */ - public scrollToPercentHorizontal (percent: number, timeInSecond: number, attenuated: boolean) { + public scrollToPercentHorizontal (percent: number, timeInSecond: number, attenuated: boolean): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(percent, 0), applyToHorizontal: true, @@ -826,7 +826,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollTo(new Vec2(1, 0), 0.1); * ``` */ - public scrollTo (anchor: Vec2, timeInSecond?: number, attenuated?: boolean) { + public scrollTo (anchor: Vec2, timeInSecond?: number, attenuated?: boolean): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(anchor), applyToHorizontal: true, @@ -857,7 +857,7 @@ export class ScrollView extends ViewGroup { * scrollView.scrollToPercentVertical(0.5, 0.1); * ``` */ - public scrollToPercentVertical (percent: number, timeInSecond?: number, attenuated?: boolean) { + public scrollToPercentVertical (percent: number, timeInSecond?: number, attenuated?: boolean): void { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, percent), applyToHorizontal: false, @@ -878,7 +878,7 @@ export class ScrollView extends ViewGroup { * @zh * 停止自动滚动, 调用此 API 可以让 ScrollView 立即停止滚动。 */ - public stopAutoScroll () { + public stopAutoScroll (): void { this._autoScrolling = false; this._autoScrollAccumulatedTime = this._autoScrollTotalTime; } @@ -893,11 +893,11 @@ export class ScrollView extends ViewGroup { * @param position @en Current content position. @zh 希望设置内容框体的位置。 * @deprecated Since 3.1.0, setContentPosition is deprecated, please use scrollToOffset instead. */ - public setContentPosition (position: Vec3) { + public setContentPosition (position: Vec3): void { this._setContentPosition(position); } - private _setContentPosition (position: Vec3) { + private _setContentPosition (position: Vec3): void { if (!this._content) { return; } @@ -920,7 +920,7 @@ export class ScrollView extends ViewGroup { * @returns @en current content position. @zh 当前视图内容的坐标点。 * @deprecated Since 3.1.0, getContentPosition is deprecated. */ - public getContentPosition () { + public getContentPosition (): Vec3 { return this._getContentPosition(); } @@ -942,7 +942,7 @@ export class ScrollView extends ViewGroup { * * @returns @en If or not the current scrolling view is being dragged. @zh 是否在拖拽当前滚动视图。 */ - public isScrolling () { + public isScrolling (): boolean { return this._scrolling; } @@ -955,7 +955,7 @@ export class ScrollView extends ViewGroup { * * @returns @en Whether the scrolling view is scrolling inertially. @zh 滚动视图是否在惯性滚动。 */ - public isAutoScrolling () { + public isAutoScrolling (): boolean { return this._autoScrolling; } @@ -964,11 +964,11 @@ export class ScrollView extends ViewGroup { * @zh 获得滚动结束的事件的最小精度时间。 * @returns @en Minimum time. @zh 最小时间。 */ - public getScrollEndedEventTiming () { + public getScrollEndedEventTiming (): number { return EPSILON; } - public start () { + public start (): void { this._calculateBoundary(); // Because widget component will adjust content position and scrollView position is correct after visit // So this event could make sure the content is on the correct position after loading. @@ -977,7 +977,7 @@ export class ScrollView extends ViewGroup { } } - public onEnable () { + public onEnable (): void { if (!EDITOR_NOT_IN_PREVIEW) { this._registerEvent(); if (this._content) { @@ -994,13 +994,13 @@ export class ScrollView extends ViewGroup { this._updateScrollBarState(); } - public update (dt: number) { + public update (dt: number): void { if (this._autoScrolling) { this._processAutoScrolling(dt); } } - public onDisable () { + public onDisable (): void { if (!EDITOR_NOT_IN_PREVIEW) { this._unregisterEvent(); if (this._content) { @@ -1017,7 +1017,7 @@ export class ScrollView extends ViewGroup { } // private methods - protected _registerEvent () { + protected _registerEvent (): void { this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this, true); this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this, true); @@ -1031,7 +1031,7 @@ export class ScrollView extends ViewGroup { input.on(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); } - protected _unregisterEvent () { + protected _unregisterEvent (): void { this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this, true); this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this, true); @@ -1044,7 +1044,7 @@ export class ScrollView extends ViewGroup { input.off(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); } - protected _onMouseWheel (event: EventMouse, captureListeners?: Node[]) { + protected _onMouseWheel (event: EventMouse, captureListeners?: Node[]): void { if (!this.enabledInHierarchy) { return; } @@ -1074,7 +1074,7 @@ export class ScrollView extends ViewGroup { this._stopPropagationIfTargetIsMe(event); } - protected _onTouchBegan (event: EventTouch, captureListeners?: Node[]) { + protected _onTouchBegan (event: EventTouch, captureListeners?: Node[]): void { if (!this.enabledInHierarchy || !this._content) { return; } if (this._hasNestedViewGroup(event, captureListeners)) { return; } @@ -1084,7 +1084,7 @@ export class ScrollView extends ViewGroup { this._stopPropagationIfTargetIsMe(event); } - protected _onTouchMoved (event: EventTouch, captureListeners?: Node[]) { + protected _onTouchMoved (event: EventTouch, captureListeners?: Node[]): void { if (!this.enabledInHierarchy || !this._content) { return; } if (this._hasNestedViewGroup(event, captureListeners)) { return; } @@ -1112,7 +1112,7 @@ export class ScrollView extends ViewGroup { this._stopPropagationIfTargetIsMe(event); } - protected _onTouchEnded (event: EventTouch, captureListeners?: Node[]) { + protected _onTouchEnded (event: EventTouch, captureListeners?: Node[]): void { if (!this.enabledInHierarchy || !this._content || !event) { return; } if (this._hasNestedViewGroup(event, captureListeners)) { return; } @@ -1128,7 +1128,7 @@ export class ScrollView extends ViewGroup { } } - protected _onTouchCancelled (event: EventTouch, captureListeners?: Node[]) { + protected _onTouchCancelled (event: EventTouch, captureListeners?: Node[]): void { if (!this.enabledInHierarchy || !this._content) { return; } if (this._hasNestedViewGroup(event, captureListeners)) { return; } @@ -1140,7 +1140,7 @@ export class ScrollView extends ViewGroup { this._stopPropagationIfTargetIsMe(event); } - protected _calculateBoundary () { + protected _calculateBoundary (): void { if (this._content && this.view) { // refresh content size const layout = this._content.getComponent(Layout); @@ -1162,7 +1162,7 @@ export class ScrollView extends ViewGroup { } } - protected _hasNestedViewGroup (event: Event, captureListeners?: Node[]) { + protected _hasNestedViewGroup (event: Event, captureListeners?: Node[]): boolean { if (!event || event.eventPhase !== Event.CAPTURING_PHASE) { return false; } @@ -1187,13 +1187,13 @@ export class ScrollView extends ViewGroup { return false; } - protected _startInertiaScroll (touchMoveVelocity: Vec3) { + protected _startInertiaScroll (touchMoveVelocity: Vec3): void { const inertiaTotalMovement = new Vec3(touchMoveVelocity); inertiaTotalMovement.multiplyScalar(MOVEMENT_FACTOR); this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); } - protected _calculateAttenuatedFactor (distance: number) { + protected _calculateAttenuatedFactor (distance: number): number { if (this.brake <= 0) { return (1 - this.brake); } @@ -1202,7 +1202,7 @@ export class ScrollView extends ViewGroup { return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008)); } - protected _startAttenuatingAutoScroll (deltaMove: Vec3, initialVelocity: Vec3) { + protected _startAttenuatingAutoScroll (deltaMove: Vec3, initialVelocity: Vec3): void { const targetDelta = deltaMove.clone(); targetDelta.normalize(); if (this._content && this.view) { @@ -1245,11 +1245,11 @@ export class ScrollView extends ViewGroup { this._startAutoScroll(targetDelta, time, true); } - protected _calculateAutoScrollTimeByInitialSpeed (initialSpeed: number) { + protected _calculateAutoScrollTimeByInitialSpeed (initialSpeed: number): number { return Math.sqrt(Math.sqrt(initialSpeed / 5)); } - protected _startAutoScroll (deltaMove: Vec3, timeInSecond: number, attenuated = false) { + protected _startAutoScroll (deltaMove: Vec3, timeInSecond: number, attenuated = false): void { const adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); this._autoScrolling = true; @@ -1268,7 +1268,7 @@ export class ScrollView extends ViewGroup { } } - protected _calculateTouchMoveVelocity () { + protected _calculateTouchMoveVelocity (): Vec3 { const out = new Vec3(); let totalTime = 0; totalTime = this._touchMoveTimeDeltas.reduce((a, b) => a + b, totalTime); @@ -1288,14 +1288,14 @@ export class ScrollView extends ViewGroup { return out; } - protected _flattenVectorByDirection (vector: Vec3) { + protected _flattenVectorByDirection (vector: Vec3): Vec3 { const result = vector; result.x = this.horizontal ? result.x : 0; result.y = this.vertical ? result.y : 0; return result; } - protected _moveContent (deltaMove: Vec3, canStartBounceBack?: boolean) { + protected _moveContent (deltaMove: Vec3, canStartBounceBack?: boolean): void { const adjustedMove = this._flattenVectorByDirection(deltaMove); _tempVec3.set(this._getContentPosition()); _tempVec3.add(adjustedMove); @@ -1310,7 +1310,7 @@ export class ScrollView extends ViewGroup { } } - protected _getContentLeftBoundary () { + protected _getContentLeftBoundary (): number { if (!this._content) { return -1; } @@ -1319,7 +1319,7 @@ export class ScrollView extends ViewGroup { return contentPos.x - uiTrans.anchorX * uiTrans.width; } - protected _getContentRightBoundary () { + protected _getContentRightBoundary (): number { if (!this._content) { return -1; } @@ -1327,7 +1327,7 @@ export class ScrollView extends ViewGroup { return this._getContentLeftBoundary() + uiTrans.width; } - protected _getContentTopBoundary () { + protected _getContentTopBoundary (): number { if (!this._content) { return -1; } @@ -1335,7 +1335,7 @@ export class ScrollView extends ViewGroup { return this._getContentBottomBoundary() + uiTrans.height; } - protected _getContentBottomBoundary () { + protected _getContentBottomBoundary (): number { if (!this._content) { return -1; } @@ -1344,7 +1344,7 @@ export class ScrollView extends ViewGroup { return contentPos.y - uiTrans.anchorY * uiTrans.height; } - protected _getHowMuchOutOfBoundary (addition?: Vec3) { + protected _getHowMuchOutOfBoundary (addition?: Vec3): Vec3 { addition = addition || new Vec3(); if (addition.equals(Vec3.ZERO, EPSILON) && !this._outOfBoundaryAmountDirty) { return this._outOfBoundaryAmount; @@ -1376,7 +1376,7 @@ export class ScrollView extends ViewGroup { return outOfBoundaryAmount; } - protected _updateScrollBar (outOfBoundary: Vec2 | Readonly) { + protected _updateScrollBar (outOfBoundary: Vec2 | Readonly): void { if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.onScroll(outOfBoundary); } @@ -1386,7 +1386,7 @@ export class ScrollView extends ViewGroup { } } - protected _onScrollBarTouchBegan () { + protected _onScrollBarTouchBegan (): void { if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.onTouchBegan(); } @@ -1396,7 +1396,7 @@ export class ScrollView extends ViewGroup { } } - protected _onScrollBarTouchEnded () { + protected _onScrollBarTouchEnded (): void { if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.onTouchEnded(); } @@ -1406,7 +1406,7 @@ export class ScrollView extends ViewGroup { } } - protected _dispatchEvent (event: string) { + protected _dispatchEvent (event: string): void { if (event === EventType.SCROLL_ENDED) { this._scrollEventEmitMask = 0; } else if (event === EventType.SCROLL_TO_TOP @@ -1425,7 +1425,7 @@ export class ScrollView extends ViewGroup { this.node.emit(event, this); } - protected _adjustContentOutOfBoundary () { + protected _adjustContentOutOfBoundary (): void { if (!this._content) { return; } @@ -1440,7 +1440,7 @@ export class ScrollView extends ViewGroup { } } - protected _hideScrollBar () { + protected _hideScrollBar (): void { if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { this._horizontalScrollBar.hide(); } @@ -1450,7 +1450,7 @@ export class ScrollView extends ViewGroup { } } - protected _updateScrollBarState () { + protected _updateScrollBarState (): void { if (!this._content || !this.view) { return; } @@ -1474,23 +1474,23 @@ export class ScrollView extends ViewGroup { } // This is for ScrollView as children of a Button - protected _stopPropagationIfTargetIsMe (event: Event) { + protected _stopPropagationIfTargetIsMe (event: Event): void { if (event.eventPhase === Event.AT_TARGET && event.target === this.node) { event.propagationStopped = true; } } - protected _processDeltaMove (deltaMove: Vec3) { + protected _processDeltaMove (deltaMove: Vec3): void { this._scrollChildren(deltaMove); this._gatherTouchMove(deltaMove); } - protected _handleMoveLogic (touch: Touch) { + protected _handleMoveLogic (touch: Touch): void { this._getLocalAxisAlignDelta(this._deltaPos, touch); this._processDeltaMove(this._deltaPos); } - protected _handleReleaseLogic (touch: Touch) { + protected _handleReleaseLogic (touch: Touch): void { this._getLocalAxisAlignDelta(this._deltaPos, touch); this._gatherTouchMove(this._deltaPos); this._processInertiaScroll(); @@ -1503,7 +1503,7 @@ export class ScrollView extends ViewGroup { } } - protected _getLocalAxisAlignDelta (out: Vec3, touch: Touch) { + protected _getLocalAxisAlignDelta (out: Vec3, touch: Touch): void { const uiTransformComp = this.node._uiProps.uiTransformComp; const vec = new Vec3(); @@ -1520,7 +1520,7 @@ export class ScrollView extends ViewGroup { out.set(vec); } - protected _scrollChildren (deltaMove: Vec3) { + protected _scrollChildren (deltaMove: Vec3): void { this._clampDelta(deltaMove); const realMove = deltaMove; @@ -1591,7 +1591,7 @@ export class ScrollView extends ViewGroup { } } - protected _handlePressLogic () { + protected _handlePressLogic (): void { if (this._autoScrolling) { this._dispatchEvent(EventType.SCROLL_ENDED); } @@ -1606,7 +1606,7 @@ export class ScrollView extends ViewGroup { this._onScrollBarTouchBegan(); } - protected _clampDelta (out: Vec3) { + protected _clampDelta (out: Vec3): void { if (this._content && this.view) { const scrollViewSize = this.view.contentSize; const uiTrans = this._content._uiProps.uiTransformComp!; @@ -1619,7 +1619,7 @@ export class ScrollView extends ViewGroup { } } - protected _gatherTouchMove (delta: Vec3) { + protected _gatherTouchMove (delta: Vec3): void { const clampDt = delta.clone(); this._clampDelta(clampDt); @@ -1635,7 +1635,7 @@ export class ScrollView extends ViewGroup { this._touchMovePreviousTimestamp = timeStamp; } - protected _startBounceBackIfNeeded () { + protected _startBounceBackIfNeeded (): boolean { if (!this.elastic) { return false; } @@ -1661,7 +1661,7 @@ export class ScrollView extends ViewGroup { return true; } - protected _processInertiaScroll () { + protected _processInertiaScroll (): void { const bounceBackStarted = this._startBounceBackIfNeeded(); if (!bounceBackStarted && this.inertia) { const touchMoveVelocity = this._calculateTouchMoveVelocity(); @@ -1673,12 +1673,12 @@ export class ScrollView extends ViewGroup { this._onScrollBarTouchEnded(); } - protected _isOutOfBoundary () { + protected _isOutOfBoundary (): boolean { const outOfBoundary = this._getHowMuchOutOfBoundary(); return !outOfBoundary.equals(Vec3.ZERO, EPSILON); } - protected _isNecessaryAutoScrollBrake () { + protected _isNecessaryAutoScrollBrake (): boolean { if (this._autoScrollBraking) { return true; } @@ -1697,7 +1697,7 @@ export class ScrollView extends ViewGroup { return false; } - protected _processAutoScrolling (dt) { + protected _processAutoScrolling (dt): void { const isAutoScrollBrake = this._isNecessaryAutoScrollBrake(); const brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1; this._autoScrollAccumulatedTime += dt * (1 / brakingFactor); @@ -1754,7 +1754,7 @@ export class ScrollView extends ViewGroup { } } - protected _checkMouseWheel (dt: number) { + protected _checkMouseWheel (dt: number): void { const currentOutOfBoundary = this._getHowMuchOutOfBoundary(); const maxElapsedTime = 0.1; @@ -1777,7 +1777,7 @@ export class ScrollView extends ViewGroup { } } - protected _calculateMovePercentDelta (options) { + protected _calculateMovePercentDelta (options): Vec3 { const anchor = options.anchor; const applyToHorizontal = options.applyToHorizontal; const applyToVertical = options.applyToVertical; @@ -1810,7 +1810,7 @@ export class ScrollView extends ViewGroup { return moveDelta; } - protected _moveContentToTopLeft (scrollViewSize: Size) { + protected _moveContentToTopLeft (scrollViewSize: Size): void { let bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDelta = -bottomDelta; const moveDelta = new Vec3(); @@ -1840,13 +1840,13 @@ export class ScrollView extends ViewGroup { this._adjustContentOutOfBoundary(); } - protected _scaleChanged (value: TransformBit) { + protected _scaleChanged (value: TransformBit): void { if (value === TransformBit.SCALE) { this._calculateBoundary(); } } - protected _xrHoverEnter (event: XrUIPressEvent) { + protected _xrHoverEnter (event: XrUIPressEvent): void { if (event.deviceType === DeviceType.Left) { this._hoverIn = XrhoverType.LEFT; } else if (event.deviceType === DeviceType.Right) { @@ -1854,11 +1854,11 @@ export class ScrollView extends ViewGroup { } } - protected _xrHoverExit (event: XrUIPressEvent) { + protected _xrHoverExit (event: XrUIPressEvent): void { this._hoverIn = XrhoverType.NONE; } - private _dispatchEventHandleInput (event: EventHandle | EventGamepad) { + private _dispatchEventHandleInput (event: EventHandle | EventGamepad): void { let handleInputDevice; if (event instanceof EventGamepad) { handleInputDevice = event.gamepad; @@ -1882,7 +1882,7 @@ export class ScrollView extends ViewGroup { } } - protected _xrThumbStickMove (event: Vec2) { + protected _xrThumbStickMove (event: Vec2): void { if (!this.enabledInHierarchy) { return; } diff --git a/cocos/ui/slider.ts b/cocos/ui/slider.ts index adb6f9d5426..69f53555198 100644 --- a/cocos/ui/slider.ts +++ b/cocos/ui/slider.ts @@ -87,7 +87,7 @@ export class Slider extends Component { */ @type(Sprite) @tooltip('i18n:slider.handle') - get handle () { + get handle (): Sprite | null { return this._handle; } @@ -111,7 +111,7 @@ export class Slider extends Component { */ @type(Direction) @tooltip('i18n:slider.direction') - get direction () { + get direction (): number { return this._direction; } @@ -134,7 +134,7 @@ export class Slider extends Component { @slide @range([0, 1, 0.01]) @tooltip('i18n:slider.progress') - get progress () { + get progress (): number { return this._progress; } @@ -173,13 +173,13 @@ export class Slider extends Component { private _handleLocalPos = new Vec3(); private _touchPos = new Vec3(); - public __preload () { + public __preload (): void { this._updateHandlePosition(); } // 注册事件 - public onEnable () { + public onEnable (): void { this._updateHandlePosition(); this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this); @@ -197,7 +197,7 @@ export class Slider extends Component { } } - public onDisable () { + public onDisable (): void { this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this); this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this); @@ -213,7 +213,7 @@ export class Slider extends Component { } } - protected _onHandleDragStart (event?: EventTouch) { + protected _onHandleDragStart (event?: EventTouch): void { if (!event || !this._handle || !this._handle.node._uiProps.uiTransformComp) { return; } @@ -227,7 +227,7 @@ export class Slider extends Component { event.propagationStopped = true; } - protected _onTouchBegan (event?: EventTouch) { + protected _onTouchBegan (event?: EventTouch): void { if (!this._handle || !event) { return; } @@ -240,7 +240,7 @@ export class Slider extends Component { event.propagationStopped = true; } - protected _onTouchMoved (event?: EventTouch) { + protected _onTouchMoved (event?: EventTouch): void { if (!this._dragging || !event) { return; } @@ -249,7 +249,7 @@ export class Slider extends Component { event.propagationStopped = true; } - protected _onTouchEnded (event?: EventTouch) { + protected _onTouchEnded (event?: EventTouch): void { this._dragging = false; this._touchHandle = false; this._offset = new Vec3(); @@ -259,24 +259,24 @@ export class Slider extends Component { } } - protected _onTouchCancelled (event?: EventTouch) { + protected _onTouchCancelled (event?: EventTouch): void { this._dragging = false; if (event) { event.propagationStopped = true; } } - protected _handleSliderLogic (touch: Touch | null) { + protected _handleSliderLogic (touch: Touch | null): void { this._updateProgress(touch); this._emitSlideEvent(); } - protected _emitSlideEvent () { + protected _emitSlideEvent (): void { EventHandler.emitEvents(this.slideEvents, this); this.node.emit('slide', this); } - protected _updateProgress (touch: Touch | null) { + protected _updateProgress (touch: Touch | null): void { if (!this._handle || !touch) { return; } @@ -292,7 +292,7 @@ export class Slider extends Component { } } - protected _updateHandlePosition () { + protected _updateHandlePosition (): void { if (!this._handle) { return; } @@ -307,7 +307,7 @@ export class Slider extends Component { this._handle.node.setPosition(this._handleLocalPos); } - private _changeLayout () { + private _changeLayout (): void { const uiTrans = this.node._uiProps.uiTransformComp!; const contentSize = uiTrans.contentSize; uiTrans.setContentSize(contentSize.height, contentSize.width); @@ -323,7 +323,7 @@ export class Slider extends Component { } } - protected _xrHandleProgress (point: Vec3) { + protected _xrHandleProgress (point: Vec3): void { if (!this._touchHandle) { const uiTrans = this.node._uiProps.uiTransformComp!; uiTrans.convertToNodeSpaceAR(point, _tempPos); @@ -335,7 +335,7 @@ export class Slider extends Component { } } - protected _xrClick (event: XrUIPressEvent) { + protected _xrClick (event: XrUIPressEvent): void { if (!this._handle) { return; } @@ -344,12 +344,12 @@ export class Slider extends Component { this._emitSlideEvent(); } - protected _xrUnClick () { + protected _xrUnClick (): void { this._dragging = false; this._touchHandle = false; } - protected _xrHoverStay (event: XrUIPressEvent) { + protected _xrHoverStay (event: XrUIPressEvent): void { if (!this._dragging) { return; } diff --git a/cocos/ui/sub-context-view.ts b/cocos/ui/sub-context-view.ts index 87ccc09f0e2..a67217ff2d1 100644 --- a/cocos/ui/sub-context-view.ts +++ b/cocos/ui/sub-context-view.ts @@ -77,7 +77,7 @@ export class SubContextView extends Component { * 注意:该属性在运行时是只读的,请在编辑器环境下配置好设计分辨率。 */ @tooltip('i18n:subContextView.design_size') - get designResolutionSize () { + get designResolutionSize (): Size { return this._designResolutionSize; } set designResolutionSize (value) { @@ -93,7 +93,7 @@ export class SubContextView extends Component { * @zh 设置开放数据域的渲染帧率。 */ @tooltip('i18n:subContextView.fps') - get fps () { + get fps (): number { return this._fps; } set fps (value) { @@ -127,7 +127,7 @@ export class SubContextView extends Component { this._texture = new Texture2D(); } - public onLoad () { + public onLoad (): void { if (minigame.getOpenDataContext) { this._updateInterval = 1000 / this._fps; this._openDataContext = minigame.getOpenDataContext(); @@ -140,15 +140,15 @@ export class SubContextView extends Component { } } - public onEnable () { + public onEnable (): void { this._registerNodeEvent(); } - public onDisable () { + public onDisable (): void { this._unregisterNodeEvent(); } - private _initSharedCanvas () { + private _initSharedCanvas (): void { if (this._openDataContext) { const sharedCanvas = this._openDataContext.canvas; let designWidth = this._designResolutionSize.width; @@ -170,7 +170,7 @@ export class SubContextView extends Component { } } - private _initContentNode () { + private _initContentNode (): void { if (this._openDataContext) { const sharedCanvas = this._openDataContext.canvas; @@ -196,7 +196,7 @@ export class SubContextView extends Component { } } - private _updateSubContextView () { + private _updateSubContextView (): void { if (!this._openDataContext) { return; } @@ -235,7 +235,7 @@ export class SubContextView extends Component { }); } - private _updateSubContextTexture () { + private _updateSubContextTexture (): void { const img = this._imageAsset; if (!img || !this._openDataContext) { return; @@ -254,23 +254,23 @@ export class SubContextView extends Component { this._texture.uploadData(sharedCanvas); } - private _registerNodeEvent () { + private _registerNodeEvent (): void { this.node.on(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this); this.node.on(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this); this.node.on(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this); } - private _unregisterNodeEvent () { + private _unregisterNodeEvent (): void { this.node.off(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this); this.node.off(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this); this.node.off(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this); } - private _updateContentLayer () { + private _updateContentLayer (): void { this._content.layer = this.node.layer; } - public update (dt?: number) { + public update (dt?: number): void { const calledUpdateManually = (dt === undefined); if (calledUpdateManually) { this._updateSubContextTexture(); @@ -284,7 +284,7 @@ export class SubContextView extends Component { } } - public onDestroy () { + public onDestroy (): void { this._content.destroy(); this._texture.destroy(); if (this._sprite) { this._sprite.destroy(); } diff --git a/cocos/ui/toggle-container.ts b/cocos/ui/toggle-container.ts index eed1e4eafe1..8ea5b30e0d2 100644 --- a/cocos/ui/toggle-container.ts +++ b/cocos/ui/toggle-container.ts @@ -58,7 +58,7 @@ export class ToggleContainer extends Component { * 如果这个设置为 true,那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。 */ @tooltip('i18n:toggle_group.allowSwitchOff') - get allowSwitchOff () { + get allowSwitchOff (): boolean { return this._allowSwitchOff; } @@ -95,22 +95,22 @@ export class ToggleContainer extends Component { }).filter(Boolean) as Toggle[]; } - public onEnable () { + public onEnable (): void { this.ensureValidState(); this.node.on(NodeEventType.CHILD_ADDED, this.ensureValidState, this); this.node.on(NodeEventType.CHILD_REMOVED, this.ensureValidState, this); } - public onDisable () { + public onDisable (): void { this.node.off(NodeEventType.CHILD_ADDED, this.ensureValidState, this); this.node.off(NodeEventType.CHILD_REMOVED, this.ensureValidState, this); } - public activeToggles () { + public activeToggles (): Toggle[] { return this.toggleItems.filter((x) => x.isChecked); } - public anyTogglesChecked () { + public anyTogglesChecked (): boolean { return !!this.toggleItems.find((x) => x.isChecked); } @@ -124,7 +124,7 @@ export class ToggleContainer extends Component { * @param toggle @en The toggle to be updated. @zh 需要被更新的切换键。 * @param emitEvent @en Whether events are needed to be emitted. @zh 是否需要触发事件。 */ - public notifyToggleCheck (toggle: Toggle, emitEvent = true) { + public notifyToggleCheck (toggle: Toggle, emitEvent = true): void { if (!this.enabledInHierarchy) { return; } for (let i = 0; i < this.toggleItems.length; i++) { @@ -148,7 +148,7 @@ export class ToggleContainer extends Component { * @en Ensure toggles state valid. * @zh 确保 toggles 状态有效。 */ - public ensureValidState () { + public ensureValidState (): void { const toggles = this.toggleItems; if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) { const toggle = toggles[0]!; diff --git a/cocos/ui/toggle.ts b/cocos/ui/toggle.ts index 8ab351d6fb2..34fc12008ae 100644 --- a/cocos/ui/toggle.ts +++ b/cocos/ui/toggle.ts @@ -61,7 +61,7 @@ export class Toggle extends Button { */ @displayOrder(1) @tooltip('i18n:toggle.isChecked') - get isChecked () { + get isChecked (): boolean { return this._isChecked; } @@ -79,7 +79,7 @@ export class Toggle extends Button { @type(Sprite) @displayOrder(1) @tooltip('i18n:toggle.checkMark') - get checkMark () { + get checkMark (): Sprite | null { return this._checkMark; } @@ -103,7 +103,7 @@ export class Toggle extends Button { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - get _toggleContainer () { + get _toggleContainer (): ToggleContainer | null { const parent = this.node.parent!; if (legacyCC.Node.isNode(parent)) { return parent.getComponent('cc.ToggleContainer') as ToggleContainer; @@ -133,11 +133,11 @@ export class Toggle extends Button { @serializable protected _checkMark: Sprite | null = null; - protected _internalToggle () { + protected _internalToggle (): void { this.isChecked = !this.isChecked; } - protected _set (value: boolean, emitEvent = true) { + protected _set (value: boolean, emitEvent = true): void { if (this._isChecked == value) return; this._isChecked = value; @@ -159,7 +159,7 @@ export class Toggle extends Button { /** * @deprecated since v3.7.0, this is an engine private interface that will be removed in the future. */ - public playEffect () { + public playEffect (): void { if (this._checkMark) { this._checkMark.node.active = this._isChecked; } @@ -174,11 +174,11 @@ export class Toggle extends Button { * * @param value @en Whether this toggle is pressed. @zh 是否被按下。 */ - public setIsCheckedWithoutNotify (value: boolean) { + public setIsCheckedWithoutNotify (value: boolean): void { this._set(value, false); } - public onEnable () { + public onEnable (): void { super.onEnable(); this.playEffect(); if (!EDITOR_NOT_IN_PREVIEW) { @@ -186,14 +186,14 @@ export class Toggle extends Button { } } - public onDisable () { + public onDisable (): void { super.onDisable(); if (!EDITOR_NOT_IN_PREVIEW) { this.node.off(Toggle.EventType.CLICK, this._internalToggle, this); } } - protected _emitToggleEvents () { + protected _emitToggleEvents (): void { this.node.emit(Toggle.EventType.TOGGLE, this); if (this.checkEvents) { ComponentEventHandler.emitEvents(this.checkEvents, this); diff --git a/cocos/ui/ui-coordinate-tracker.ts b/cocos/ui/ui-coordinate-tracker.ts index e0ce7d3d9c4..ca882264a36 100644 --- a/cocos/ui/ui-coordinate-tracker.ts +++ b/cocos/ui/ui-coordinate-tracker.ts @@ -50,7 +50,7 @@ export class UICoordinateTracker extends Component { */ @type(Node) @tooltip('i18n:UICoordinateTracker.target') - get target () { + get target (): Node | null { return this._target; } @@ -72,7 +72,7 @@ export class UICoordinateTracker extends Component { */ @type(Camera) @tooltip('i18n:UICoordinateTracker.camera') - get camera () { + get camera (): Camera | null { return this._camera; } @@ -93,7 +93,7 @@ export class UICoordinateTracker extends Component { * 是否是缩放映射。 */ @tooltip('i18n:UICoordinateTracker.use_scale') - get useScale () { + get useScale (): boolean { return this._useScale; } @@ -113,7 +113,7 @@ export class UICoordinateTracker extends Component { * 距相机多少距离为正常显示计算大小。 */ @tooltip('i18n:UICoordinateTracker.distance') - get distance () { + get distance (): number { return this._distance; } @@ -154,11 +154,11 @@ export class UICoordinateTracker extends Component { protected _lastWPos = new Vec3(); protected _lastCameraPos = new Vec3(); - public onEnable () { + public onEnable (): void { this._checkCanMove(); } - public update () { + public update (): void { const wPos = this.node.worldPosition; const camera = this._camera; if (!this._canMove || !camera || !camera.camera || (this._lastWPos.equals(wPos) && this._lastCameraPos.equals(camera.node.worldPosition))) { @@ -180,7 +180,7 @@ export class UICoordinateTracker extends Component { } } - protected _checkCanMove () { + protected _checkCanMove (): void { this._canMove = !!(this._camera && this._target); } } diff --git a/cocos/ui/view.ts b/cocos/ui/view.ts index 3aec7a9c079..09230bbf4d7 100644 --- a/cocos/ui/view.ts +++ b/cocos/ui/view.ts @@ -112,7 +112,7 @@ export class View extends Eventify(System) { } // Call init at the time Game.EVENT_ENGINE_INITED - public init () { + public init (): void { const windowSize = screen.windowSize; const w = windowSize.width; const h = windowSize.height; @@ -152,7 +152,7 @@ export class View extends Eventify(System) { * 仅在 Web 模式下有效。 * @param enabled - Whether enable automatic resize with browser's resize event */ - public resizeWithBrowserSize (enabled: boolean) { + public resizeWithBrowserSize (enabled: boolean): void { screenAdapter.handleResizeEvent = enabled; } @@ -170,7 +170,7 @@ export class View extends Eventify(System) { * * @deprecated since v3.8.0, please use [[screen.on]] to listen for events. */ - public setResizeCallback (callback: (() => void) | null) { + public setResizeCallback (callback: (() => void) | null): void { if (typeof callback === 'function' || callback == null) { this._resizeCallback = callback; } @@ -189,7 +189,7 @@ export class View extends Eventify(System) { * 这个方法不会对 native 部分产生任何影响,对于 native 而言,你需要在应用设置中的设置排版。 * @param orientation - Possible values: macro.ORIENTATION_LANDSCAPE | macro.ORIENTATION_PORTRAIT | macro.ORIENTATION_AUTO */ - public setOrientation (orientation: number) { + public setOrientation (orientation: number): void { screenAdapter.orientation = orientationMap[orientation]; } @@ -206,7 +206,7 @@ export class View extends Eventify(System) { * @param enabled - Enable automatic modification to "viewport" meta * @deprecated since v3.3 */ - public adjustViewportMeta (enabled: boolean) { + public adjustViewportMeta (enabled: boolean): void { // DO NOTHING } @@ -222,7 +222,7 @@ export class View extends Eventify(System) { * * @deprecated since v3.4.0 */ - public enableRetina (enabled: boolean) { + public enableRetina (enabled: boolean): void { this._retinaEnabled = !!enabled; } @@ -250,7 +250,7 @@ export class View extends Eventify(System) { * * @deprecated since v3.3, please use screen.requestFullScreen() instead. */ - public enableAutoFullScreen (enabled: boolean) { + public enableAutoFullScreen (enabled: boolean): void { if (enabled === this._autoFullScreen) { return; } @@ -285,7 +285,7 @@ export class View extends Eventify(System) { * * @deprecated since v3.4.0, setting size in CSS pixels is not recommended, please use screen.windowSize instead. */ - public setCanvasSize (width: number, height: number) { + public setCanvasSize (width: number, height: number): void { // set resolution scale to 1; screenAdapter.resolutionScale = 1; @@ -341,7 +341,7 @@ export class View extends Eventify(System) { * * @deprecated since v3.4.0, setting size in CSS pixels is not recommended, please use screen.windowSize instead. */ - public setFrameSize (width: number, height: number) { + public setFrameSize (width: number, height: number): void { const dpr = screenAdapter.devicePixelRatio; screen.windowSize = new Size(width * dpr, height * dpr); } @@ -389,7 +389,7 @@ export class View extends Eventify(System) { return this._resolutionPolicy; } - private _updateResolutionPolicy (resolutionPolicy: ResolutionPolicy|number) { + private _updateResolutionPolicy (resolutionPolicy: ResolutionPolicy|number): void { if (resolutionPolicy instanceof ResolutionPolicy) { this._resolutionPolicy = resolutionPolicy; } else { @@ -417,7 +417,7 @@ export class View extends Eventify(System) { * @zh 设置当前分辨率模式 * @see [[ResolutionPolicy]] */ - public setResolutionPolicy (resolutionPolicy: ResolutionPolicy|number) { + public setResolutionPolicy (resolutionPolicy: ResolutionPolicy|number): void { this._updateResolutionPolicy(resolutionPolicy); const designedResolution = view.getDesignResolutionSize(); view.setDesignResolutionSize(designedResolution.width, designedResolution.height, resolutionPolicy); @@ -437,7 +437,7 @@ export class View extends Eventify(System) { * @param height Design resolution height. * @param resolutionPolicy The resolution policy desired */ - public setDesignResolutionSize (width: number, height: number, resolutionPolicy: ResolutionPolicy|number) { + public setDesignResolutionSize (width: number, height: number, resolutionPolicy: ResolutionPolicy|number): void { // Defensive code if (!(width > 0 && height > 0)) { errorID(2200); @@ -512,7 +512,7 @@ export class View extends Eventify(System) { * * @deprecated since v3.6.0 */ - public setRealPixelResolution (width: number, height: number, resolutionPolicy: ResolutionPolicy|number) { + public setRealPixelResolution (width: number, height: number, resolutionPolicy: ResolutionPolicy|number): void { if (!JSB && !RUNTIME_BASED && !MINIGAME) { // Set body width to the exact pixel resolution document.documentElement.style.width = `${width}px`; @@ -583,13 +583,13 @@ export class View extends Eventify(System) { } // Convert location in Cocos screen coordinate to location in UI space - private _convertToUISpace (point) { + private _convertToUISpace (point): void { const viewport = this._viewportRect; point.x = (point.x - viewport.x) / this._scaleX; point.y = (point.y - viewport.y) / this._scaleY; } - private _updateAdaptResult (width: number, height: number, windowId?: number) { + private _updateAdaptResult (width: number, height: number, windowId?: number): void { // The default invalid windowId is 0 cclegacy.director.root.resize(width, height, (windowId === undefined || windowId === 0) ? 1 : windowId); // Frame size changed, do resize works @@ -633,7 +633,7 @@ class ContainerStrategy { * @zh 在应用策略之前的操作 * @param view - The target view */ - public preApply (_view: View) { + public preApply (_view: View): void { } /** @@ -642,7 +642,7 @@ class ContainerStrategy { * @param view * @param designedResolution */ - public apply (_view: View, designedResolution: Size) { + public apply (_view: View, designedResolution: Size): void { } /** @@ -651,11 +651,11 @@ class ContainerStrategy { * @zh 策略调用之后的操作 * @param view The target view */ - public postApply (_view: View) { + public postApply (_view: View): void { } - protected _setupCanvas () { + protected _setupCanvas (): void { // TODO: need to figure out why set width and height of canvas const locCanvas = cclegacy.game.canvas; if (locCanvas) { @@ -705,7 +705,7 @@ class ContentStrategy { * @zh 策略应用前的操作 * @param view - The target view */ - public preApply (_view: View) { + public preApply (_view: View): void { } /** @@ -724,7 +724,7 @@ class ContentStrategy { * @zh 策略调用之后的操作 * @param view - The target view */ - public postApply (_view: View) { + public postApply (_view: View): void { } /** @@ -749,7 +749,7 @@ class ContentStrategy { } } -(() => { +((): void => { // Container scale strategys /** * @class EqualToFrame @@ -757,7 +757,7 @@ class ContentStrategy { */ class EqualToFrame extends ContainerStrategy { public name = 'EqualToFrame'; - public apply (_view, designedResolution) { + public apply (_view, designedResolution): void { screenAdapter.isProportionalToFrame = false; this._setupCanvas(); } @@ -769,7 +769,7 @@ class ContentStrategy { */ class ProportionalToFrame extends ContainerStrategy { public name = 'ProportionalToFrame'; - public apply (_view, designedResolution) { + public apply (_view, designedResolution): void { screenAdapter.isProportionalToFrame = true; this._setupCanvas(); } @@ -783,7 +783,7 @@ class ContentStrategy { // Content scale strategys class ExactFit extends ContentStrategy { public name = 'ExactFit'; - public apply (_view: View, designedResolution: Size) { + public apply (_view: View, designedResolution: Size): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -796,7 +796,7 @@ class ContentStrategy { class ShowAll extends ContentStrategy { public name = 'ShowAll'; - public apply (_view, designedResolution) { + public apply (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -824,7 +824,7 @@ class ContentStrategy { class NoBorder extends ContentStrategy { public name = 'NoBorder'; - public apply (_view, designedResolution) { + public apply (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -852,7 +852,7 @@ class ContentStrategy { class FixedHeight extends ContentStrategy { public name = 'FixedHeight'; - public apply (_view, designedResolution) { + public apply (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -867,7 +867,7 @@ class ContentStrategy { class FixedWidth extends ContentStrategy { public name = 'FixedWidth'; - public apply (_view, designedResolution) { + public apply (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -969,7 +969,7 @@ export class ResolutionPolicy { this.setContentStrategy(contentStg); } - get canvasSize () { + get canvasSize (): Size { return screen.windowSize; } @@ -978,7 +978,7 @@ export class ResolutionPolicy { * @zh 策略应用前的操作 * @param _view The target view */ - public preApply (_view: View) { + public preApply (_view: View): void { this._contentStrategy!.preApply(_view); } @@ -991,7 +991,7 @@ export class ResolutionPolicy { * @param designedResolution - The user defined design resolution * @return An object contains the scale X/Y values and the viewport rect */ - public apply (_view: View, designedResolution: Size) { + public apply (_view: View, designedResolution: Size): AdaptResult { this._containerStrategy!.apply(_view, designedResolution); return this._contentStrategy!.apply(_view, designedResolution); } @@ -1001,7 +1001,7 @@ export class ResolutionPolicy { * @zh 策略应用之后的操作 * @param _view - The target view */ - public postApply (_view: View) { + public postApply (_view: View): void { this._contentStrategy!.postApply(_view); } @@ -1010,7 +1010,7 @@ export class ResolutionPolicy { * @zh 设置容器的适配策略 * @param containerStg The container strategy */ - public setContainerStrategy (containerStg: ContainerStrategy) { + public setContainerStrategy (containerStg: ContainerStrategy): void { if (containerStg instanceof ContainerStrategy) { this._containerStrategy = containerStg; } @@ -1021,7 +1021,7 @@ export class ResolutionPolicy { * @zh 设置内容的适配策略 * @param contentStg The content strategy */ - public setContentStrategy (contentStg: ContentStrategy) { + public setContentStrategy (contentStg: ContentStrategy): void { if (contentStg instanceof ContentStrategy) { this._contentStrategy = contentStg; } diff --git a/cocos/ui/widget-manager.ts b/cocos/ui/widget-manager.ts index ddd6b8aaa1d..9ea367517f1 100644 --- a/cocos/ui/widget-manager.ts +++ b/cocos/ui/widget-manager.ts @@ -42,7 +42,7 @@ const _tempVec2_1 = new Vec2(); const _tempVec2_2 = new Vec2(); // align to borders by adjusting node's position and size (ignore rotation) -function align (node: Node, widget: Widget) { +function align (node: Node, widget: Widget): void { // Hack: this flag use to ONCE mode if (widget._hadAlignOnce) return; if ((!EDITOR) && widget.alignMode === AlignMode.ONCE) { @@ -192,7 +192,7 @@ function align (node: Node, widget: Widget) { } // TODO: type is hack, Change to the type actually used (Node or BaseNode) when BaseNode complete -function visitNode (node: any) { +function visitNode (node: any): void { const widget = node.getComponent(Widget); if (widget && widget.enabled) { if (DEV) { @@ -217,7 +217,7 @@ function visitNode (node: any) { } // This function will be called on AFTER_SCENE_LAUNCH and AFTER_UPDATE -function refreshScene () { +function refreshScene (): void { const scene = director.getScene(); if (scene) { widgetManager.isAligning = true; @@ -248,7 +248,7 @@ function refreshScene () { const activeWidgets: Widget[] = []; // updateAlignment from scene to node recursively -function updateAlignment (node: Node) { +function updateAlignment (node: Node): void { const parent = node.parent; if (parent && Node.isNode(parent)) { updateAlignment(parent); @@ -277,7 +277,7 @@ export const widgetManager = cclegacy._widgetManager = { animatedSinceLastFrame: false, } : null, - init () { + init (): void { director.on(Director.EVENT_AFTER_SCENE_LAUNCH, refreshScene); director.on(Director.EVENT_AFTER_UPDATE, refreshScene); @@ -288,19 +288,19 @@ export const widgetManager = cclegacy._widgetManager = { screenAdapter.on('window-resize', thisOnResized); } }, - add (widget: Widget) { + add (widget: Widget): void { this._nodesOrderDirty = true; }, - remove (widget: Widget) { + remove (widget: Widget): void { this._activeWidgetsIterator.remove(widget); }, - onResized () { + onResized (): void { const scene = director.getScene(); if (scene) { this.refreshWidgetOnResized(scene); } }, - refreshWidgetOnResized (node: Node) { + refreshWidgetOnResized (node: Node): void { const widget = Node.isNode(node) && node.getComponent(Widget); if (widget && widget.enabled && ( widget.alignMode === AlignMode.ON_WINDOW_RESIZE || widget.alignMode === AlignMode.ALWAYS @@ -313,8 +313,8 @@ export const widgetManager = cclegacy._widgetManager = { this.refreshWidgetOnResized(child); } }, - updateOffsetsToStayPut (widget: Widget, e?: AlignFlags) { - function i (t: number, c: number) { + updateOffsetsToStayPut (widget: Widget, e?: AlignFlags): void { + function i (t: number, c: number): number { return Math.abs(t - c) > 1e-10 ? c : t; } const widgetNode = widget.node; diff --git a/cocos/ui/widget.ts b/cocos/ui/widget.ts index 7259fa5092c..eba312d279b 100644 --- a/cocos/ui/widget.ts +++ b/cocos/ui/widget.ts @@ -27,7 +27,7 @@ import { ccclass, help, executeInEditMode, executionOrder, menu, requireComponen import { EDITOR, DEV, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { Component } from '../scene-graph/component'; import { UITransform } from '../2d/framework/ui-transform'; -import { Size, Vec2, Vec3, visibleRect, ccenum, errorID, cclegacy } from '../core'; +import { Size, Vec2, Vec3, visibleRect, ccenum, errorID, cclegacy, Rect } from '../core'; import { View } from './view'; import { Scene } from '../scene-graph'; import { Node } from '../scene-graph/node'; @@ -37,7 +37,20 @@ import { NodeEventType } from '../scene-graph/node-event'; const _tempScale = new Vec2(); // returns a readonly size of the node -export function getReadonlyNodeSize (parent: Node | Scene) { +export function getReadonlyNodeSize (parent: Node | Scene): { + topLeft: any; + topRight: any; + top: any; + bottomLeft: any; + bottomRight: any; + bottom: any; + center: any; + left: any; + right: any; + width: number; + height: number; + init(visibleRect_: Rect): void; +} | Readonly { if (parent instanceof Scene) { if (EDITOR) { // const canvasComp = parent.getComponentInChildren(Canvas); @@ -56,7 +69,7 @@ export function getReadonlyNodeSize (parent: Node | Scene) { } } -export function computeInverseTransForTarget (widgetNode: Node, target: Node, out_inverseTranslate: Vec2, out_inverseScale: Vec2) { +export function computeInverseTransForTarget (widgetNode: Node, target: Node, out_inverseTranslate: Vec2, out_inverseScale: Vec2): void { if (widgetNode.parent) { _tempScale.set(widgetNode.parent.getScale().x, widgetNode.parent.getScale().y); } else { @@ -221,7 +234,7 @@ export class Widget extends Component { */ @type(Node) @tooltip('i18n:widget.target') - get target () { + get target (): Node | null { return this._target; } @@ -251,7 +264,7 @@ export class Widget extends Component { * 是否对齐上边。 */ @tooltip('i18n:widget.align_top') - get isAlignTop () { + get isAlignTop (): boolean { return (this._alignFlags & AlignFlags.TOP) > 0; } set isAlignTop (value) { @@ -267,7 +280,7 @@ export class Widget extends Component { * 是否对齐下边。 */ @tooltip('i18n:widget.align_bottom') - get isAlignBottom () { + get isAlignBottom (): boolean { return (this._alignFlags & AlignFlags.BOT) > 0; } set isAlignBottom (value) { @@ -283,7 +296,7 @@ export class Widget extends Component { * 是否对齐左边。 */ @tooltip('i18n:widget.align_left') - get isAlignLeft () { + get isAlignLeft (): boolean { return (this._alignFlags & AlignFlags.LEFT) > 0; } set isAlignLeft (value) { @@ -299,7 +312,7 @@ export class Widget extends Component { * 是否对齐右边。 */ @tooltip('i18n:widget.align_right') - get isAlignRight () { + get isAlignRight (): boolean { return (this._alignFlags & AlignFlags.RIGHT) > 0; } set isAlignRight (value) { @@ -315,7 +328,7 @@ export class Widget extends Component { * 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。 */ @tooltip('i18n:widget.align_h_center') - get isAlignVerticalCenter () { + get isAlignVerticalCenter (): boolean { return (this._alignFlags & AlignFlags.MID) > 0; } set isAlignVerticalCenter (value) { @@ -338,7 +351,7 @@ export class Widget extends Component { * 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。 */ @tooltip('i18n:widget.align_v_center') - get isAlignHorizontalCenter () { + get isAlignHorizontalCenter (): boolean { return (this._alignFlags & AlignFlags.CENTER) > 0; } set isAlignHorizontalCenter (value) { @@ -361,7 +374,7 @@ export class Widget extends Component { * 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸。此时节点的宽度(只读)。 */ @visible(false) - get isStretchWidth () { + get isStretchWidth (): boolean { return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT; } @@ -374,7 +387,7 @@ export class Widget extends Component { * 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度(只读)。 */ @visible(false) - get isStretchHeight () { + get isStretchHeight (): boolean { return (this._alignFlags & TOP_BOT) === TOP_BOT; } @@ -389,7 +402,7 @@ export class Widget extends Component { * 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。 */ @tooltip('i18n:widget.top') - get top () { + get top (): number { return this._top; } set top (value) { @@ -401,7 +414,7 @@ export class Widget extends Component { * @EditorOnly Not for user */ @editable - get editorTop () { + get editorTop (): number { return this._isAbsTop ? this._top : (this._top * 100); } set editorTop (value) { @@ -418,7 +431,7 @@ export class Widget extends Component { * 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。 */ @tooltip('i18n:widget.bottom') - get bottom () { + get bottom (): number { return this._bottom; } set bottom (value) { @@ -430,7 +443,7 @@ export class Widget extends Component { * @EditorOnly Not for user */ @editable - get editorBottom () { + get editorBottom (): number { return this._isAbsBottom ? this._bottom : (this._bottom * 100); } set editorBottom (value) { @@ -447,7 +460,7 @@ export class Widget extends Component { * 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。 */ @tooltip('i18n:widget.left') - get left () { + get left (): number { return this._left; } set left (value) { @@ -459,7 +472,7 @@ export class Widget extends Component { * @EditorOnly Not for user */ @editable - get editorLeft () { + get editorLeft (): number { return this._isAbsLeft ? this._left : (this._left * 100); } set editorLeft (value) { @@ -476,7 +489,7 @@ export class Widget extends Component { * 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。 */ @tooltip('i18n:widget.right') - get right () { + get right (): number { return this._right; } set right (value) { @@ -488,7 +501,7 @@ export class Widget extends Component { * @EditorOnly Not for user */ @editable - get editorRight () { + get editorRight (): number { return this._isAbsRight ? this._right : (this._right * 100); } set editorRight (value) { @@ -505,7 +518,7 @@ export class Widget extends Component { * 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。 */ @tooltip('i18n:widget.horizontal_center') - get horizontalCenter () { + get horizontalCenter (): number { return this._horizontalCenter; } set horizontalCenter (value) { @@ -517,7 +530,7 @@ export class Widget extends Component { * @EditorOnly Not for user */ @editable - get editorHorizontalCenter () { + get editorHorizontalCenter (): number { return this._isAbsHorizontalCenter ? this._horizontalCenter : (this._horizontalCenter * 100); } set editorHorizontalCenter (value) { @@ -534,7 +547,7 @@ export class Widget extends Component { * 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。 */ @tooltip('i18n:widget.vertical_center') - get verticalCenter () { + get verticalCenter (): number { return this._verticalCenter; } set verticalCenter (value) { @@ -546,7 +559,7 @@ export class Widget extends Component { * @EditorOnly Not for user */ @editable - get editorVerticalCenter () { + get editorVerticalCenter (): number { return this._isAbsVerticalCenter ? this._verticalCenter : (this._verticalCenter * 100); } set editorVerticalCenter (value) { @@ -562,7 +575,7 @@ export class Widget extends Component { * 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的比例(0 到 1)作为边距。 */ @editable - get isAbsoluteTop () { + get isAbsoluteTop (): boolean { return this._isAbsTop; } set isAbsoluteTop (value) { @@ -582,7 +595,7 @@ export class Widget extends Component { * 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的比例(0 到 1)作为边距。 */ @editable - get isAbsoluteBottom () { + get isAbsoluteBottom (): boolean { return this._isAbsBottom; } set isAbsoluteBottom (value) { @@ -602,7 +615,7 @@ export class Widget extends Component { * 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的比例(0 到 1)作为边距。 */ @editable - get isAbsoluteLeft () { + get isAbsoluteLeft (): boolean { return this._isAbsLeft; } set isAbsoluteLeft (value) { @@ -622,7 +635,7 @@ export class Widget extends Component { * 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的比例(0 到 1)作为边距。 */ @editable - get isAbsoluteRight () { + get isAbsoluteRight (): boolean { return this._isAbsRight; } set isAbsoluteRight (value) { @@ -642,7 +655,7 @@ export class Widget extends Component { * 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为比例(0 到 1)。 */ @editable - get isAbsoluteHorizontalCenter () { + get isAbsoluteHorizontalCenter (): boolean { return this._isAbsHorizontalCenter; } set isAbsoluteHorizontalCenter (value) { @@ -662,7 +675,7 @@ export class Widget extends Component { * 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为比例(0 到 1)。 */ @editable - get isAbsoluteVerticalCenter () { + get isAbsoluteVerticalCenter (): boolean { return this._isAbsVerticalCenter; } set isAbsoluteVerticalCenter (value) { @@ -689,7 +702,7 @@ export class Widget extends Component { */ @type(AlignMode) @tooltip('i18n:widget.align_mode') - get alignMode () { + get alignMode (): AlignMode { return this._alignMode; } set alignMode (value) { @@ -704,7 +717,7 @@ export class Widget extends Component { * Align flags. */ @editable - get alignFlags () { + get alignFlags (): number { return this._alignFlags; } set alignFlags (value) { @@ -792,14 +805,14 @@ export class Widget extends Component { * log(widget.node.y); // changed * ``` */ - public updateAlignment () { + public updateAlignment (): void { cclegacy._widgetManager.updateAlignment(this.node); } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _validateTargetInDEV () { + public _validateTargetInDEV (): void { if (!DEV) { return; } @@ -814,11 +827,11 @@ export class Widget extends Component { } } - public setDirty () { + public setDirty (): void { this._recursiveDirty(); } - public onEnable () { + public onEnable (): void { this.node.getPosition(this._lastPos); this._lastSize.set(this.node._uiProps.uiTransformComp!.contentSize); cclegacy._widgetManager.add(this); @@ -827,36 +840,36 @@ export class Widget extends Component { this._registerTargetEvents(); } - public onDisable () { + public onDisable (): void { cclegacy._widgetManager.remove(this); this._unregisterEvent(); this._unregisterTargetEvents(); } - public onDestroy () { + public onDestroy (): void { this._removeParentEvent(); } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _adjustWidgetToAllowMovingInEditor (eventType: TransformBit) {} + public _adjustWidgetToAllowMovingInEditor (eventType: TransformBit): void {} /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _adjustWidgetToAllowResizingInEditor () {} + public _adjustWidgetToAllowResizingInEditor (): void {} /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _adjustWidgetToAnchorChanged () { + public _adjustWidgetToAnchorChanged (): void { this.setDirty(); } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _adjustTargetToParentChanged (oldParent: Node) { + public _adjustTargetToParentChanged (oldParent: Node): void { if (oldParent) { this._unregisterOldParentEvents(oldParent); } @@ -866,7 +879,7 @@ export class Widget extends Component { this._setDirtyByMode(); } - protected _registerEvent () { + protected _registerEvent (): void { if (EDITOR_NOT_IN_PREVIEW) { this.node.on(NodeEventType.TRANSFORM_CHANGED, this._adjustWidgetToAllowMovingInEditor, this); this.node.on(NodeEventType.SIZE_CHANGED, this._adjustWidgetToAllowResizingInEditor, this); @@ -878,7 +891,7 @@ export class Widget extends Component { this.node.on(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this); } - protected _unregisterEvent () { + protected _unregisterEvent (): void { if (EDITOR_NOT_IN_PREVIEW) { this.node.off(NodeEventType.TRANSFORM_CHANGED, this._adjustWidgetToAllowMovingInEditor, this); this.node.off(NodeEventType.SIZE_CHANGED, this._adjustWidgetToAllowResizingInEditor, this); @@ -889,11 +902,11 @@ export class Widget extends Component { this.node.off(NodeEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this); } - protected _removeParentEvent () { + protected _removeParentEvent (): void { this.node.off(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this); } - protected _autoChangedValue (flag: AlignFlags, isAbs: boolean) { + protected _autoChangedValue (flag: AlignFlags, isAbs: boolean): void { const current = (this._alignFlags & flag) > 0; if (!current) { return; @@ -919,7 +932,7 @@ export class Widget extends Component { this._recursiveDirty(); } - protected _registerTargetEvents () { + protected _registerTargetEvents (): void { const target = this._target || this.node.parent; if (target) { if (target.getComponent(UITransform)) { @@ -930,7 +943,7 @@ export class Widget extends Component { } } - protected _unregisterTargetEvents () { + protected _unregisterTargetEvents (): void { const target = this._target || this.node.parent; if (target) { target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this); @@ -939,21 +952,20 @@ export class Widget extends Component { } } - protected _unregisterOldParentEvents (oldParent: Node) { + protected _unregisterOldParentEvents (oldParent: Node): void { const target = this._target || oldParent; if (target) { target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this); target.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this); } } - - protected _setDirtyByMode () { + protected _setDirtyByMode (): void { if (this.alignMode === AlignMode.ALWAYS || (EDITOR_NOT_IN_PREVIEW)) { this._recursiveDirty(); } } - private _setAlign (flag: AlignFlags, isAlign: boolean) { + private _setAlign (flag: AlignFlags, isAlign: boolean): void { const current = (this._alignFlags & flag) > 0; if (isAlign === current) { return; @@ -1006,7 +1018,7 @@ export class Widget extends Component { } } - private _recursiveDirty () { + private _recursiveDirty (): void { if (this._dirty) { return; } diff --git a/cocos/video/video-downloader.ts b/cocos/video/video-downloader.ts index 06c5b43e5e7..226a7d0064f 100644 --- a/cocos/video/video-downloader.ts +++ b/cocos/video/video-downloader.ts @@ -32,7 +32,7 @@ import { ccwindow } from '../core/global-exports'; const ccdocument = ccwindow.document; // eslint-disable-next-line consistent-return -export function downloadVideo (url: string, options: Record, onComplete: (err: Error | null, data?: any | null) => void) { +export function downloadVideo (url: string, options: Record, onComplete: (err: Error | null, data?: any | null) => void): void { const video = ccdocument.createElement('video'); const source = ccdocument.createElement('source'); video.appendChild(source); @@ -40,7 +40,7 @@ export function downloadVideo (url: string, options: Record, onComp const req = new XMLHttpRequest(); req.open('GET', url, true); req.responseType = 'blob'; - req.onload = function onload () { + req.onload = function onload (): void { if (this.status === 200 || this.status === 0) { source.src = URL.createObjectURL(this.response); onComplete(null, video); @@ -48,7 +48,7 @@ export function downloadVideo (url: string, options: Record, onComp onComplete(new Error(`${req.status}(no response)`)); } }; - req.onerror = function onerror () { + req.onerror = function onerror (): void { const message = `load video failure - ${url}`; log(message); onComplete(new Error(message)); @@ -56,7 +56,7 @@ export function downloadVideo (url: string, options: Record, onComp req.send(); } -function createVideoClip (id: string, data: HTMLVideoElement, options: Record, onComplete: (err: Error | null, data?: VideoClip | null) => void) { +function createVideoClip (id: string, data: HTMLVideoElement, options: Record, onComplete: (err: Error | null, data?: VideoClip | null) => void): void { const out = new VideoClip(); out._nativeUrl = id; out._nativeAsset = data; diff --git a/cocos/video/video-player-impl-web.ts b/cocos/video/video-player-impl-web.ts index 7fe29a72d66..ba548439843 100644 --- a/cocos/video/video-player-impl-web.ts +++ b/cocos/video/video-player-impl-web.ts @@ -50,15 +50,15 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { super(component); } - protected addListener (type: string, handler: (e: Event) => void) { + protected addListener (type: string, handler: (e: Event) => void): void { if (!this._video) { return; } this._eventList.set(type, handler); this._video.addEventListener(type, handler); } - protected removeAllListeners () { - this._eventList.forEach((handler, type) => { + protected removeAllListeners (): void { + this._eventList.forEach((handler, type): void => { if (!this._video) { return; } @@ -67,7 +67,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { this._eventList.clear(); } - public canPlay () { + public canPlay (): void { if (this.video) { const promise = this.video.play(); // the play API can only be initiated by user gesture. @@ -84,18 +84,18 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { } } - public pause () { + public pause (): void { if (this.video) { this.video.pause(); this._cachedCurrentTime = this.video.currentTime; } } - public resume () { + public resume (): void { this.play(); } - public stop () { + public stop (): void { if (this.video) { this._ignorePause = true; this.video.currentTime = 0; @@ -108,19 +108,19 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { } } - public syncClip (clip: any) { + public syncClip (clip: any): void { this.removeVideoPlayer(); if (!clip) { return; } this.createVideoPlayer(clip.nativeUrl); } - public syncURL (url: string) { + public syncURL (url: string): void { this.removeVideoPlayer(); if (!url) { return; } this.createVideoPlayer(url); } - public syncPlaybackRate (val: number) { + public syncPlaybackRate (val: number): void { if (sys.browserType === BrowserType.UC) { warn('playbackRate is not supported by the uc mobile browser.'); return; @@ -130,45 +130,45 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { } } - public syncVolume (val: number) { + public syncVolume (val: number): void { if (this.video) { this.video.volume = val; } } - public syncMute (enabled: boolean) { + public syncMute (enabled: boolean): void { if (this.video) { this.video.muted = enabled; } } - public syncLoop (enabled: boolean) { + public syncLoop (enabled: boolean): void { if (this.video) { this.video.loop = enabled; } } - public getDuration () { + public getDuration (): number { if (!this.video) { return 0; } return this.video.duration; } - public getCurrentTime () { + public getCurrentTime (): number { if (this.video) { return this.video.currentTime; } return -1; } - public seekTo (val: number) { + public seekTo (val: number): void { if (this.video) { this.video.currentTime = val; } } - canFullScreen (enabled: boolean) { + canFullScreen (enabled: boolean): void { // NOTE: below we visited some non-standard web interfaces to complement browser compatibility // we need to mark video as any type. const video = this._video as any; @@ -218,7 +218,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { } } - public syncStayOnBottom (enabled: boolean) { + public syncStayOnBottom (enabled: boolean): void { if (this._video) { this._video.style['z-index'] = enabled ? MIN_ZINDEX : 0; this._stayOnBottom = enabled; @@ -226,14 +226,14 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { this._dirty = true; } - public syncKeepAspectRatio (enabled: boolean) { + public syncKeepAspectRatio (enabled: boolean): void { this._keepAspectRatio = enabled; if (enabled && this._loadedMeta && this._video) { this.syncUITransform(this._video.videoWidth, this._video.videoHeight); } } - public removeVideoPlayer () { + public removeVideoPlayer (): void { const video = this._video; if (video) { if (contains(game.container, video)) { @@ -248,7 +248,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { this._video = null; } - public createVideoPlayer (url: string) { + public createVideoPlayer (url: string): void { const video = this._video = ccdocument.createElement('video'); video.className = 'cocosVideo'; video.style.visibility = 'hidden'; @@ -270,7 +270,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { source.src = url; } - protected _bindDomEvent () { + protected _bindDomEvent (): void { const video = this._video; this.addListener('loadedmetadata', this.onLoadedMetadata.bind(this)); this.addListener('canplay', this.onCanPlay.bind(this)); @@ -283,7 +283,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { this.addListener('error', this.onError.bind(this)); } - public onCanPlay (e: Event) { + public onCanPlay (e: Event): void { const video = e.target as HTMLVideoElement; if (this._loaded && video) { return; @@ -298,7 +298,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { } } - public enable () { + public enable (): void { if (this._video) { this._visible = true; if (this._video.style.visibility === 'visible') { @@ -308,7 +308,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { } } - public disable (noPause?: boolean) { + public disable (noPause?: boolean): void { if (this._video) { if (!noPause && this._playing) { this._video.pause(); @@ -321,7 +321,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { } } - public syncMatrix () { + public syncMatrix (): void { if (!this._video || !this._visible || !this._component) return; const camera = this.UICamera; diff --git a/cocos/video/video-player-impl.ts b/cocos/video/video-player-impl.ts index 33c00ffd305..ac921c4828f 100644 --- a/cocos/video/video-player-impl.ts +++ b/cocos/video/video-player-impl.ts @@ -29,6 +29,7 @@ import { EventType } from './video-player-enums'; import { error } from '../core/platform'; import { director } from '../game/director'; import { Node } from '../scene-graph'; +import type { Camera } from '../render-scene/scene'; export abstract class VideoPlayerImpl { protected _componentEventList: Map void> = new Map(); @@ -74,12 +75,12 @@ export abstract class VideoPlayerImpl { this._component = component; this._node = component.node; this._uiTrans = component.node.getComponent(UITransform); - this._onInterruptedBegin = () => { + this._onInterruptedBegin = (): void => { if (!this.video || this._state !== EventType.PLAYING) { return; } this.video.pause(); this._interrupted = true; }; - this._onInterruptedEnd = () => { + this._onInterruptedEnd = (): void => { if (!this._interrupted || !this.video) { return; } // eslint-disable-next-line @typescript-eslint/no-floating-promises this.video.play(); @@ -119,18 +120,18 @@ export abstract class VideoPlayerImpl { // get video player data public abstract getDuration(): number; public abstract getCurrentTime(): number; - public get fullScreenOnAwake () { return this._fullScreenOnAwake; } - public get loaded () { return this._loaded; } - public get componentEventList () { return this._componentEventList; } - public get video () { return this._video; } - public get state () { return this._state; } - public get isPlaying () { return this._playing; } - get UICamera () { + public get fullScreenOnAwake (): boolean { return this._fullScreenOnAwake; } + public get loaded (): boolean { return this._loaded; } + public get componentEventList (): Map void> { return this._componentEventList; } + public get video (): HTMLVideoElement | null { return this._video; } + public get state (): EventType { return this._state; } + public get isPlaying (): boolean { return this._playing; } + get UICamera (): Camera | null { return director.root!.batcher2D.getFirstRenderCamera(this._node!); } // video player event - public onLoadedMetadata (e: Event) { + public onLoadedMetadata (e: Event): void { this._loadedMeta = true; this._forceUpdate = true; if (this._visible) { @@ -147,21 +148,21 @@ export abstract class VideoPlayerImpl { this.delayedPlay(); } - public onCanPlay (e: Event) { + public onCanPlay (e: Event): void { this._loaded = true; this.dispatchEvent(EventType.READY_TO_PLAY); } - public onPlay (e: Event) { + public onPlay (e: Event): void { this._playing = true; this.dispatchEvent(EventType.PLAYING); } - public onPlaying (e: Event) { + public onPlaying (e: Event): void { this.dispatchEvent(EventType.PLAYING); } - public onPause (e: Event) { + public onPause (e: Event): void { if (this._ignorePause) { this._ignorePause = false; return; @@ -170,21 +171,21 @@ export abstract class VideoPlayerImpl { this.dispatchEvent(EventType.PAUSED); } - public onStoped (e: Event) { + public onStoped (e: Event): void { this._playing = false; this._ignorePause = false; this.dispatchEvent(EventType.STOPPED); } - public onEnded (e: Event) { + public onEnded (e: Event): void { this.dispatchEvent(EventType.COMPLETED); } - public onClick (e: Event) { + public onClick (e: Event): void { this.dispatchEvent(EventType.CLICKED); } - public onError (e: Event) { + public onError (e: Event): void { this.dispatchEvent(EventType.ERROR); const video = e.target as HTMLVideoElement; if (video && video.error) { @@ -193,7 +194,7 @@ export abstract class VideoPlayerImpl { } // - public play () { + public play (): void { if (this._loadedMeta || this._loaded) { this.canPlay(); } else { @@ -201,14 +202,14 @@ export abstract class VideoPlayerImpl { } } - public delayedPlay () { + public delayedPlay (): void { if (this._waitingPlay) { this.canPlay(); this._waitingPlay = false; } } - public syncFullScreenOnAwake (enabled: boolean) { + public syncFullScreenOnAwake (enabled: boolean): void { this._fullScreenOnAwake = enabled; if (this._loadedMeta || this._loaded) { this.canFullScreen(enabled); @@ -217,14 +218,14 @@ export abstract class VideoPlayerImpl { } } - public delayedFullScreen () { + public delayedFullScreen (): void { if (this._waitingFullscreen) { this.canFullScreen(this._fullScreenOnAwake); this._waitingFullscreen = false; } } - protected dispatchEvent (key) { + protected dispatchEvent (key): void { const callback = this._componentEventList.get(key); if (callback) { this._state = key; @@ -232,14 +233,14 @@ export abstract class VideoPlayerImpl { } } - protected syncUITransform (width, height) { + protected syncUITransform (width, height): void { if (this._uiTrans) { this._uiTrans.width = width; this._uiTrans.height = height; } } - protected syncCurrentTime () { + protected syncCurrentTime (): void { if (!this.video) { return; } @@ -249,7 +250,7 @@ export abstract class VideoPlayerImpl { } } - public destroy () { + public destroy (): void { this.removeVideoPlayer(); this._componentEventList.clear(); legacyCC.game.off(legacyCC.Game.EVENT_PAUSE, this._onInterruptedBegin); diff --git a/cocos/video/video-player.ts b/cocos/video/video-player.ts index 03a84a28224..bba9aa4cc9a 100644 --- a/cocos/video/video-player.ts +++ b/cocos/video/video-player.ts @@ -84,7 +84,7 @@ export class VideoPlayer extends Component { */ @type(ResourceType) @tooltip('i18n:videoplayer.resourceType') - get resourceType () { + get resourceType (): number { return this._resourceType; } set resourceType (val) { @@ -101,7 +101,7 @@ export class VideoPlayer extends Component { * 远程视频的 URL。 */ @tooltip('i18n:videoplayer.remoteURL') - get remoteURL () { + get remoteURL (): string { return this._remoteURL; } set remoteURL (val: string) { @@ -119,7 +119,7 @@ export class VideoPlayer extends Component { */ @type(VideoClip) @tooltip('i18n:videoplayer.clip') - get clip () { + get clip (): VideoClip | null { return this._clip; } set clip (val) { @@ -136,7 +136,7 @@ export class VideoPlayer extends Component { * 视频加载后是否自动开始播放。 */ @tooltip('i18n:videoplayer.playOnAwake') - get playOnAwake () { + get playOnAwake (): boolean { return this._playOnAwake; } set playOnAwake (value) { @@ -152,7 +152,7 @@ export class VideoPlayer extends Component { @slide @range([0.0, 10, 1.0]) @tooltip('i18n:videoplayer.playbackRate') - get playbackRate () { + get playbackRate (): number { return this._playbackRate; } set playbackRate (value: number) { @@ -171,7 +171,7 @@ export class VideoPlayer extends Component { @slide @range([0.0, 1.0, 0.1]) @tooltip('i18n:videoplayer.volume') - get volume () { + get volume (): number { return this._volume; } set volume (value: number) { @@ -188,7 +188,7 @@ export class VideoPlayer extends Component { * 是否静音视频。设置音量为0时是静音,取消静音是恢复原来的音量。 */ @tooltip('i18n:videoplayer.mute') - get mute () { + get mute (): boolean { return this._mute; } set mute (value) { @@ -205,7 +205,7 @@ export class VideoPlayer extends Component { * 视频是否应在结束时再次播放。 */ @tooltip('i18n:videoplayer.loop') - get loop () { + get loop (): boolean { return this._loop; } set loop (value) { @@ -222,7 +222,7 @@ export class VideoPlayer extends Component { * 是否保持视频原来的宽高比。 */ @tooltip('i18n:videoplayer.keepAspectRatio') - get keepAspectRatio () { + get keepAspectRatio (): boolean { return this._keepAspectRatio; } set keepAspectRatio (value) { @@ -241,7 +241,7 @@ export class VideoPlayer extends Component { * 是否全屏播放视频。 */ @tooltip('i18n:videoplayer.fullScreenOnAwake') - get fullScreenOnAwake () { + get fullScreenOnAwake (): boolean { if (!EDITOR_NOT_IN_PREVIEW) { if (this._impl) { this._fullScreenOnAwake = this._impl.fullScreenOnAwake; @@ -271,7 +271,7 @@ export class VideoPlayer extends Component { * 注意:该属性只有在 Web 平台上有效果。由于各浏览器的支持与限制,效果可能无法保证一致。 */ @tooltip('i18n:videoplayer.stayOnBottom') - get stayOnBottom () { + get stayOnBottom (): boolean { return this._stayOnBottom; } set stayOnBottom (value: boolean) { @@ -304,7 +304,7 @@ export class VideoPlayer extends Component { * @zh * 获取原始视频对象,一般用于用户定制。 */ - get nativeVideo () { + get nativeVideo (): HTMLVideoElement | null { return (this._impl && this._impl.video) || null; } @@ -314,7 +314,7 @@ export class VideoPlayer extends Component { * @zh * 获取当前视频播放的时间进度。 */ - get currentTime () { + get currentTime (): number { if (!this._impl) { return this._cachedCurrentTime; } return this._impl.getCurrentTime(); } @@ -340,7 +340,7 @@ export class VideoPlayer extends Component { * @zh * 获取以秒为单位的视频总时长。 */ - get duration () { + get duration (): number { if (!this._impl) { return 0; } return this._impl.getDuration(); } @@ -351,7 +351,7 @@ export class VideoPlayer extends Component { * @zh * 获取当前视频状态。 */ - get state () { + get state (): EventType { if (!this._impl) { return EventType.NONE; } return this._impl.state; } @@ -362,12 +362,12 @@ export class VideoPlayer extends Component { * @zh * 当前视频是否正在播放,返回值为布尔类型。 */ - get isPlaying () { + get isPlaying (): boolean { if (!this._impl) { return false; } return this._impl.isPlaying; } - protected syncSource () { + protected syncSource (): void { if (!this._impl) { return; } if (this._resourceType === ResourceType.REMOTE) { this._impl.syncURL(this._remoteURL); @@ -376,7 +376,7 @@ export class VideoPlayer extends Component { } } - public __preload () { + public __preload (): void { if (EDITOR_NOT_IN_PREVIEW) { return; } @@ -404,68 +404,68 @@ export class VideoPlayer extends Component { } } - public onEnable () { + public onEnable (): void { if (this._impl) { this._impl.enable(); } } - public onDisable () { + public onDisable (): void { if (this._impl) { this._impl.disable(); } } - public onDestroy () { + public onDestroy (): void { if (this._impl) { this._impl.destroy(); this._impl = null; } } - public update (dt: number) { + public update (dt: number): void { if (this._impl) { this._impl.syncMatrix(); } } - public onMetaLoaded () { + public onMetaLoaded (): void { ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.META_LOADED); this.node.emit('meta-loaded', this); } - public onReadyToPlay () { + public onReadyToPlay (): void { if (this._playOnAwake && !this.isPlaying) { this.play(); } ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.READY_TO_PLAY); this.node.emit(EventType.READY_TO_PLAY, this); } - public onPlaying () { + public onPlaying (): void { ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PLAYING); this.node.emit(EventType.PLAYING, this); } - public onPaused () { + public onPaused (): void { ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PAUSED); this.node.emit(EventType.PAUSED, this); } - public onStopped () { + public onStopped (): void { ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.STOPPED); this.node.emit(EventType.STOPPED, this); } - public onCompleted () { + public onCompleted (): void { ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.COMPLETED); this.node.emit(EventType.COMPLETED, this); } - public onError () { + public onError (): void { ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.ERROR); this.node.emit(EventType.ERROR, this); } - public onClicked () { + public onClicked (): void { ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.CLICKED); this.node.emit(EventType.CLICKED, this); } @@ -480,7 +480,7 @@ export class VideoPlayer extends Component { * 如果视频处于正在播放状态,将会重新开始播放视频。
* 如果视频处于暂停状态,则会继续播放视频。 */ - public play () { + public play (): void { if (this._impl) { this._impl.play(); } @@ -493,7 +493,7 @@ export class VideoPlayer extends Component { * @zh * 继续播放。如果一个视频播放被暂停播放了,调用这个接口可以继续播放。 */ - public resume () { + public resume (): void { if (this._impl) { this._impl.resume(); } @@ -505,7 +505,7 @@ export class VideoPlayer extends Component { * @zh * 暂停播放。 */ - public pause () { + public pause (): void { if (this._impl) { this._impl.pause(); } @@ -517,7 +517,7 @@ export class VideoPlayer extends Component { * @zh * 停止播放。 */ - public stop () { + public stop (): void { if (this._impl) { this._impl.stop(); } diff --git a/cocos/web-view/web-view-impl-manager.ts b/cocos/web-view/web-view-impl-manager.ts index 885ed6ae5ff..445aff22acd 100644 --- a/cocos/web-view/web-view-impl-manager.ts +++ b/cocos/web-view/web-view-impl-manager.ts @@ -27,7 +27,7 @@ import { WebViewImplWeb } from './web-view-impl-web'; export class WebViewImplManager { // default web - static getImpl (component) { + static getImpl (component): WebViewImplWeb { return new WebViewImplWeb(component); } } diff --git a/cocos/web-view/web-view-impl-web.ts b/cocos/web-view/web-view-impl-web.ts index 8e95e1f4dbb..a290677d4b8 100644 --- a/cocos/web-view/web-view-impl-web.ts +++ b/cocos/web-view/web-view-impl-web.ts @@ -40,11 +40,11 @@ export class WebViewImplWeb extends WebViewImpl { super(component); } - _bindDomEvent () { + _bindDomEvent (): void { if (!this.webview) { return; } - const onLoaded = (e: Event) => { + const onLoaded = (e: Event): void => { this._forceUpdate = true; this.dispatchEvent(EventType.LOADED); @@ -58,7 +58,7 @@ export class WebViewImplWeb extends WebViewImpl { this.webview.addEventListener('load', onLoaded); } - public loadURL (url: string) { + public loadURL (url: string): void { if (this.webview) { this.webview.src = url; // emit loading event @@ -66,7 +66,7 @@ export class WebViewImplWeb extends WebViewImpl { } } - public createWebView () { + public createWebView (): void { const wrapper = ccdocument.createElement('div'); this._wrapper = wrapper; wrapper.id = 'webview-wrapper'; @@ -89,7 +89,7 @@ export class WebViewImplWeb extends WebViewImpl { this._bindDomEvent(); } - public removeWebView () { + public removeWebView (): void { const wrapper = this._wrapper; if (contains(game.container, wrapper)) { game.container!.removeChild(wrapper); @@ -97,19 +97,19 @@ export class WebViewImplWeb extends WebViewImpl { this.reset(); } - public enable () { + public enable (): void { if (this._wrapper) { this._wrapper.style.visibility = 'visible'; } } - public disable () { + public disable (): void { if (this._wrapper) { this._wrapper.style.visibility = 'hidden'; } } - public evaluateJS (str: string) { + public evaluateJS (str: string): void { if (this.webview) { const win = this.webview.contentWindow; if (win) { @@ -123,15 +123,15 @@ export class WebViewImplWeb extends WebViewImpl { } } - public setOnJSCallback (callback: () => void) { + public setOnJSCallback (callback: () => void): void { warn('The platform does not support'); } - public setJavascriptInterfaceScheme (scheme: string) { + public setJavascriptInterfaceScheme (scheme: string): void { warn('The platform does not support'); } - public syncMatrix () { + public syncMatrix (): void { if (!this._wrapper || !this._uiTrans || !this._component || this._wrapper.style.visibility === 'hidden') return; const camera = this.UICamera; diff --git a/cocos/web-view/web-view-impl.ts b/cocos/web-view/web-view-impl.ts index 101f50974a3..85828f81347 100644 --- a/cocos/web-view/web-view-impl.ts +++ b/cocos/web-view/web-view-impl.ts @@ -28,6 +28,7 @@ import { EventType } from './web-view-enums'; import { UITransform } from '../2d/framework'; import { director } from '../game/director'; import { Node } from '../scene-graph'; +import type { Camera } from '../render-scene/scene'; export abstract class WebViewImpl { protected _componentEventList: Map void> = new Map(); @@ -59,7 +60,7 @@ export abstract class WebViewImpl { this.createWebView(); } - public reset () { + public reset (): void { this._wrapper = null; this._webview = null; this._loaded = false; @@ -86,15 +87,15 @@ export abstract class WebViewImpl { public abstract setOnJSCallback(callback: () => void): void; public abstract setJavascriptInterfaceScheme(scheme: string): void; - get loaded () { return this._loaded; } - get componentEventList () { return this._componentEventList; } - get webview () { return this._webview; } - get state () { return this._state; } - get UICamera () { + get loaded (): boolean { return this._loaded; } + get componentEventList (): Map void> { return this._componentEventList; } + get webview (): HTMLIFrameElement | null { return this._webview; } + get state (): EventType { return this._state; } + get UICamera (): Camera | null { return director.root!.batcher2D.getFirstRenderCamera(this._node!); } - protected dispatchEvent (key: EventType, ...args: any[any]) { + protected dispatchEvent (key: EventType, ...args: any[any]): void { const callback = this._componentEventList.get(key); if (callback) { this._state = key; @@ -102,7 +103,7 @@ export abstract class WebViewImpl { } } - public destroy () { + public destroy (): void { this.removeWebView(); this._wrapper = null; this._webview = null; diff --git a/cocos/web-view/web-view.ts b/cocos/web-view/web-view.ts index faabfb2b69c..68f7d978fc5 100644 --- a/cocos/web-view/web-view.ts +++ b/cocos/web-view/web-view.ts @@ -64,7 +64,7 @@ export class WebView extends Component { * 指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串。 */ @tooltip('i18n:webview.url') - get url () { + get url (): string { return this._url; } set url (val: string) { @@ -92,7 +92,7 @@ export class WebView extends Component { * @zh * 原始网页对象,用于用户定制。 */ - get nativeWebView () { + get nativeWebView (): HTMLIFrameElement | null { return (this._impl && this._impl.webview) || null; } @@ -102,7 +102,7 @@ export class WebView extends Component { * @zh * 获取当前网页视图状态。 */ - get state () { + get state (): EventType { if (!this._impl) { return EventType.NONE; } return this._impl.state; } @@ -119,7 +119,7 @@ export class WebView extends Component { * @method setJavascriptInterfaceScheme * @param {String} scheme */ - public setJavascriptInterfaceScheme (scheme: string) { + public setJavascriptInterfaceScheme (scheme: string): void { if (this._impl) { this._impl.setJavascriptInterfaceScheme(scheme); } @@ -138,7 +138,7 @@ export class WebView extends Component { * @method setOnJSCallback * @param {Function} callback */ - public setOnJSCallback (callback: () => void) { + public setOnJSCallback (callback: () => void): void { if (this._impl) { this._impl.setOnJSCallback(callback); } @@ -155,13 +155,13 @@ export class WebView extends Component { * @method evaluateJS * @param {String} str */ - public evaluateJS (str: string) { + public evaluateJS (str: string): void { if (this._impl) { this._impl.evaluateJS(str); } } - public __preload () { + public __preload (): void { if (EDITOR_NOT_IN_PREVIEW) { return; } @@ -173,41 +173,41 @@ export class WebView extends Component { this._impl.loadURL(this._url); } - onLoading () { + onLoading (): void { ComponentEventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING); this.node.emit(EventType.LOADING, this); } - onLoaded () { + onLoaded (): void { ComponentEventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED); this.node.emit(EventType.LOADED, this); } - onError (...args: any[any]) { + onError (...args: any[any]): void { ComponentEventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR, args); this.node.emit(EventType.ERROR, this, args); } - public onEnable () { + public onEnable (): void { if (this._impl) { this._impl.enable(); } } - public onDisable () { + public onDisable (): void { if (this._impl) { this._impl.disable(); } } - public onDestroy () { + public onDestroy (): void { if (this._impl) { this._impl.destroy(); this._impl = null; } } - public update (dt: number) { + public update (dt: number): void { if (this._impl) { this._impl.syncMatrix(); } diff --git a/exports/physics-cannon.ts b/exports/physics-cannon.ts index 5e3f43f27e8..7ea7834eec9 100644 --- a/exports/physics-cannon.ts +++ b/exports/physics-cannon.ts @@ -37,12 +37,12 @@ if (globalThis) globalThis.CANNON = CANNON; }; // overwrite -(CANNON as any).ArrayCollisionMatrix.prototype.reset = function reset () { +(CANNON as any).ArrayCollisionMatrix.prototype.reset = function reset (): void { for (const key in this.matrix) { delete this.matrix[key]; } }; -(CANNON.Ray as any).perBodyFilter = function (r: CANNON.Ray, b: CANNON.Body) { +(CANNON.Ray as any).perBodyFilter = function (r: CANNON.Ray, b: CANNON.Body): boolean { return ((r as any).collisionFilterMask & b.collisionFilterGroup) !== 0; }; diff --git a/extensions/ccpool/node-pool.ts b/extensions/ccpool/node-pool.ts index 7f98f23907e..221a6fc6a64 100644 --- a/extensions/ccpool/node-pool.ts +++ b/extensions/ccpool/node-pool.ts @@ -96,7 +96,7 @@ export class NodePool { * @en The current available size in the pool * @zh 获取当前缓冲池的可用对象数量 */ - public size () { + public size (): number { return this._pool.length; } @@ -104,7 +104,7 @@ export class NodePool { * @en Destroy all cached nodes in the pool * @zh 销毁对象池中缓存的所有节点 */ - public clear () { + public clear (): void { const count = this._pool.length; for (let i = 0; i < count; ++i) { this._pool[i].destroy(); @@ -124,7 +124,7 @@ export class NodePool { * const myNode = instantiate(this.template); * this.myPool.put(myNode); */ - public put (obj: Node) { + public put (obj: Node): void { if (obj && this._pool.indexOf(obj) === -1) { // Remove from parent, but don't cleanup obj.removeFromParent(); diff --git a/external/compression/gzip.d.ts b/external/compression/gzip.d.ts index 5f113c482b1..c9e1c8da94b 100644 --- a/external/compression/gzip.d.ts +++ b/external/compression/gzip.d.ts @@ -42,10 +42,10 @@ export declare class GZip { flushBuffer(): void; addBuffer(a: number): void; IsPat(): number; - Rec(): 0 | -1; - CreateTree(currentTree: any, numval: any, lengths: any, show: any): 0 | -1; + Rec(): number; + CreateTree(currentTree: any, numval: any, lengths: any, show: any): number; DecodeValue(currentTree: any): any; - DeflateLoop(): 1 | 0; + DeflateLoop(): number; unzipFile(name: string): string; nextFile(): void; skipdir(): number; diff --git a/package-lock.json b/package-lock.json index f16a5df723e..a39812198e8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "cocos-creator", - "version": "3.8.0", + "version": "3.8.1", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 6a6f69b1400..f85cadfaea6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cocos-creator", - "version": "3.8.0", + "version": "3.8.1", "description": "Cocos Creator is a cross-platform 2D & 3D game engine written in C++ and TypeScript, licensed under MIT.", "homepage": "http://www.cocos.com", "license": "MIT", diff --git a/pal/audio/audio-buffer-manager.ts b/pal/audio/audio-buffer-manager.ts index 30d08c24a6c..3e0ba1d2c3a 100644 --- a/pal/audio/audio-buffer-manager.ts +++ b/pal/audio/audio-buffer-manager.ts @@ -37,7 +37,7 @@ interface AudioBufferDataMap { class AudioBufferManager { private _audioBufferDataMap: AudioBufferDataMap = {}; - public addCache (url: string, audioBuffer: AudioBuffer) { + public addCache (url: string, audioBuffer: AudioBuffer): void { const audioBufferData = this._audioBufferDataMap[url]; if (audioBufferData) { console.warn(`Audio buffer ${url} has been cached`); @@ -49,7 +49,7 @@ class AudioBufferManager { }; } - public retainCache (url: string) { + public retainCache (url: string): void { const audioBufferData = this._audioBufferDataMap[url]; if (!audioBufferData) { console.warn(`Audio buffer cache ${url} has not been added.`); @@ -63,7 +63,7 @@ class AudioBufferManager { return audioBufferData?.audioBuffer; } - public tryReleasingCache (url: string) { + public tryReleasingCache (url: string): void { const audioBufferData = this._audioBufferDataMap[url]; if (!audioBufferData) { console.warn(`Audio buffer cache ${url} has not been added.`); diff --git a/pal/audio/audio-timer.ts b/pal/audio/audio-timer.ts index ccee4d84275..dac75ce4208 100644 --- a/pal/audio/audio-timer.ts +++ b/pal/audio/audio-timer.ts @@ -43,19 +43,19 @@ export default class AudioTimer { this._nativeAudio = nativeAudio; } - public destroy () { + public destroy (): void { // NOTE: 'undefined' is not assignable to type 'IDuration' this._nativeAudio = undefined as any; } - get duration () { + get duration (): number { return this._nativeAudio.duration; } /** * Get the current time of audio timer. */ - get currentTime () { + get currentTime (): number { if (this._isPaused) { return this._startOffset; } else { @@ -63,11 +63,11 @@ export default class AudioTimer { } } - private _now () { + private _now (): number { return performance.now() / 1000; } - private _calculateCurrentTime () { + private _calculateCurrentTime (): number { const timePassed = this._now() - this._startTime; const currentTime = this._startOffset + timePassed; if (currentTime >= this.duration) { @@ -82,7 +82,7 @@ export default class AudioTimer { * Start the audio timer. * Call this method when audio is played. */ - start () { + start (): void { this._isPaused = false; this._startTime = this._now(); } @@ -91,7 +91,7 @@ export default class AudioTimer { * Pause the audio timer. * Call this method when audio is paused or interrupted. */ - pause () { + pause (): void { if (this._isPaused) { return; } @@ -103,7 +103,7 @@ export default class AudioTimer { * Stop the audio timer. * Call this method when audio playing ended or audio is stopped. */ - stop () { + stop (): void { this._isPaused = true; this._startOffset = 0; } @@ -112,7 +112,7 @@ export default class AudioTimer { * Seek the audio timer. * Call this method when audio is seeked. */ - seek (time: number) { + seek (time: number): void { this._startTime = this._now(); this._startOffset = clamp(time, 0, this.duration); } diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index 5d5cbb7ea76..4df014dd367 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -35,7 +35,7 @@ import { Game, game } from '../../../cocos/game'; export class OneShotAudioMinigame { private _innerAudioContext: InnerAudioContext; private _onPlayCb?: () => void; - get onPlay () { + get onPlay (): (() => void) | undefined { return this._onPlayCb; } set onPlay (cb) { @@ -43,7 +43,7 @@ export class OneShotAudioMinigame { } private _onEndCb?: () => void; - get onEnd () { + get onEnd (): (() => void) | undefined { return this._onEndCb; } set onEnd (cb) { @@ -85,7 +85,7 @@ export class AudioPlayerMinigame implements OperationQueueable { private _onEnded: () => void; private _readyToHandleOnShow = false; - private _resetSeekCache () { + private _resetSeekCache (): void { this._cacheTime = 0; this._needSeek = false; this._seeking = false; @@ -107,7 +107,7 @@ export class AudioPlayerMinigame implements OperationQueueable { game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); const eventTarget = this._eventTarget; - this._onPlay = () => { + this._onPlay = (): void => { this._state = AudioState.PLAYING; eventTarget.emit(AudioEvent.PLAYED); if (this._needSeek) { @@ -115,7 +115,7 @@ export class AudioPlayerMinigame implements OperationQueueable { } }; innerAudioContext.onPlay(this._onPlay); - this._onPause = () => { + this._onPause = (): void => { this._state = AudioState.PAUSED; try { const currentTime = this._innerAudioContext.currentTime; @@ -128,7 +128,7 @@ export class AudioPlayerMinigame implements OperationQueueable { eventTarget.emit(AudioEvent.PAUSED); }; innerAudioContext.onPause(this._onPause); - this._onStop = () => { + this._onStop = (): void => { this._state = AudioState.STOPPED; // Reset all properties this._resetSeekCache(); @@ -139,7 +139,7 @@ export class AudioPlayerMinigame implements OperationQueueable { } }; innerAudioContext.onStop(this._onStop); - this._onSeeked = () => { + this._onSeeked = (): void => { eventTarget.emit(AudioEvent.SEEKED); this._seeking = false; if (this._needSeek) { @@ -158,14 +158,14 @@ export class AudioPlayerMinigame implements OperationQueueable { } }; innerAudioContext.onSeeked(this._onSeeked); - this._onEnded = () => { + this._onEnded = (): void => { this._state = AudioState.INIT; this._resetSeekCache(); eventTarget.emit(AudioEvent.ENDED); }; innerAudioContext.onEnded(this._onEnded); } - destroy () { + destroy (): void { game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); if (this._innerAudioContext) { @@ -179,7 +179,7 @@ export class AudioPlayerMinigame implements OperationQueueable { this._innerAudioContext = null as any; } } - private _onInterruptedBegin () { + private _onInterruptedBegin (): void { if (this._state === AudioState.PLAYING) { this.pause().then(() => { this._state = AudioState.INTERRUPTED; @@ -188,7 +188,7 @@ export class AudioPlayerMinigame implements OperationQueueable { }).catch((e) => {}); } } - private _onInterruptedEnd () { + private _onInterruptedEnd (): void { // We don't know whether onShow or resolve callback in pause promise is called at first. if (!this._readyToHandleOnShow) { this._eventTarget.once(AudioEvent.INTERRUPTION_BEGIN, this._onInterruptedEnd, this); @@ -201,14 +201,14 @@ export class AudioPlayerMinigame implements OperationQueueable { } this._readyToHandleOnShow = false; } - private _offEvent (eventName: string) { + private _offEvent (eventName: string): void { if (this[`_on${eventName}`]) { this._innerAudioContext[`off${eventName}`](this[`_on${eventName}`]); this[`_on${eventName}`] = null; } } - get src () { + get src (): string { return this._innerAudioContext ? this._innerAudioContext.src : ''; } get type (): AudioType { @@ -228,16 +228,16 @@ export class AudioPlayerMinigame implements OperationQueueable { clearEvent(); resolve(innerAudioContext); }, 8000); - function clearEvent () { + function clearEvent (): void { innerAudioContext.offCanplay(success); innerAudioContext.offError(fail); } - function success () { + function success (): void { clearEvent(); clearTimeout(timer); resolve(innerAudioContext); } - function fail (err) { + function fail (err): void { clearEvent(); clearTimeout(timer); console.error('failed to load innerAudioContext'); @@ -345,10 +345,10 @@ export class AudioPlayerMinigame implements OperationQueueable { }); } - onInterruptionBegin (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void) { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void) { this._eventTarget.off(AudioEvent.ENDED, cb); } + onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } + offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } + onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } + offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } + onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } + offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } } diff --git a/pal/audio/minigame/player-web.ts b/pal/audio/minigame/player-web.ts index f6bc3b2f6b7..5d972be780c 100644 --- a/pal/audio/minigame/player-web.ts +++ b/pal/audio/minigame/player-web.ts @@ -40,7 +40,7 @@ export class OneShotAudioWeb { private _onPlayCb?: () => void; private _url: string; - get onPlay () { + get onPlay (): (() => void) | undefined { return this._onPlayCb; } set onPlay (cb) { @@ -48,7 +48,7 @@ export class OneShotAudioWeb { } private _onEndCb?: () => void; - get onEnd () { + get onEnd (): (() => void) | undefined { return this._onEndCb; } set onEnd (cb) { @@ -71,7 +71,7 @@ export class OneShotAudioWeb { public play (): void { this._bufferSourceNode.start(); this.onPlay?.(); - this._bufferSourceNode.onended = () => { + this._bufferSourceNode.onended = (): void => { audioBufferManager.tryReleasingCache(this._url); this._onEndCb?.(); }; @@ -116,7 +116,7 @@ export class AudioPlayerWeb implements OperationQueueable { game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); } - destroy () { + destroy (): void { this._audioTimer.destroy(); if (this._audioBuffer) { // NOTE: need to release AudioBuffer instance @@ -126,7 +126,7 @@ export class AudioPlayerWeb implements OperationQueueable { game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); } - private _onInterruptedBegin () { + private _onInterruptedBegin (): void { if (this._state === AudioState.PLAYING) { this.pause().then(() => { this._state = AudioState.INTERRUPTED; @@ -135,7 +135,7 @@ export class AudioPlayerWeb implements OperationQueueable { }).catch((e) => {}); } } - private _onInterruptedEnd () { + private _onInterruptedEnd (): void { // We don't know whether onShow or resolve callback in pause promise is called at first. if (!this._readyToHandleOnShow) { this._eventTarget.once(AudioEvent.INTERRUPTION_BEGIN, this._onInterruptedEnd, this); @@ -264,7 +264,7 @@ export class AudioPlayerWeb implements OperationQueueable { this._state = AudioState.PLAYING; this._audioTimer.start(); - this._sourceNode.onended = () => { + this._sourceNode.onended = (): void => { this._audioTimer.stop(); this._eventTarget.emit(AudioEvent.ENDED); this._state = AudioState.INIT; @@ -273,7 +273,7 @@ export class AudioPlayerWeb implements OperationQueueable { }); } - private _stopSourceNode () { + private _stopSourceNode (): void { try { if (this._sourceNode) { this._sourceNode.onended = null; // stop will call ended callback @@ -307,10 +307,10 @@ export class AudioPlayerWeb implements OperationQueueable { return Promise.resolve(); } - onInterruptionBegin (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void) { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void) { this._eventTarget.off(AudioEvent.ENDED, cb); } + onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } + offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } + onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } + offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } + onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } + offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } } diff --git a/pal/audio/minigame/player.ts b/pal/audio/minigame/player.ts index 8bfb426202b..bd4c433b9cd 100644 --- a/pal/audio/minigame/player.ts +++ b/pal/audio/minigame/player.ts @@ -33,14 +33,14 @@ type AbstractAudioPlayer = AudioPlayerMinigame | AudioPlayerWeb; export class OneShotAudio { private _audio: AbstractOneShotAudio; - get onPlay () { + get onPlay (): (() => void) | undefined { return this._audio.onPlay; } set onPlay (v) { this._audio.onPlay = v; } - get onEnd () { + get onEnd (): (() => void) | undefined { return this._audio.onEnd; } set onEnd (v) { @@ -77,7 +77,7 @@ export class AudioPlayer { } }); } - destroy () { + destroy (): void { this._player.destroy(); } static loadNative (url: string, opts?: AudioLoadOptions): Promise { @@ -119,12 +119,12 @@ export class AudioPlayer { play (): Promise { return this._player.play(); } pause (): Promise { return this._player.pause(); } stop (): Promise { return this._player.stop(); } - onInterruptionBegin (cb: () => void) { this._player.onInterruptionBegin(cb); } - offInterruptionBegin (cb?: () => void) { this._player.offInterruptionBegin(cb); } - onInterruptionEnd (cb: () => void) { this._player.onInterruptionEnd(cb); } - offInterruptionEnd (cb?: () => void) { this._player.offInterruptionEnd(cb); } - onEnded (cb: () => void) { this._player.onEnded(cb); } - offEnded (cb?: () => void) { this._player.offEnded(cb); } + onInterruptionBegin (cb: () => void): void { this._player.onInterruptionBegin(cb); } + offInterruptionBegin (cb?: () => void): void { this._player.offInterruptionBegin(cb); } + onInterruptionEnd (cb: () => void): void { this._player.onInterruptionEnd(cb); } + offInterruptionEnd (cb?: () => void): void { this._player.offInterruptionEnd(cb); } + onEnded (cb: () => void): void { this._player.onEnded(cb); } + offEnded (cb?: () => void): void { this._player.offEnded(cb); } } // REMOVE_ME diff --git a/pal/audio/native/player.ts b/pal/audio/native/player.ts index 95bac930a9a..d7b20f746ea 100644 --- a/pal/audio/native/player.ts +++ b/pal/audio/native/player.ts @@ -70,7 +70,7 @@ export class OneShotAudio { private _url: string; private _volume: number; private _onPlayCb?: () => void; - get onPlay () { + get onPlay (): (() => void) | undefined { return this._onPlayCb; } set onPlay (cb) { @@ -78,7 +78,7 @@ export class OneShotAudio { } private _onEndCb?: () => void; - get onEnd () { + get onEnd (): (() => void) | undefined { return this._onEndCb; } set onEnd (cb) { @@ -135,14 +135,14 @@ export class AudioPlayer implements OperationQueueable { game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); } - destroy () { + destroy (): void { game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); if (--urlCount[this._url] <= 0) { audioEngine.uncache(this._url); } } - private _onInterruptedBegin () { + private _onInterruptedBegin (): void { if (this._state === AudioState.PLAYING) { this.pause().then(() => { this._state = AudioState.INTERRUPTED; @@ -150,7 +150,7 @@ export class AudioPlayer implements OperationQueueable { }).catch((e) => {}); } } - private _onInterruptedEnd () { + private _onInterruptedEnd (): void { if (this._state === AudioState.INTERRUPTED) { this.play().then(() => { this._eventTarget.emit(AudioEvent.INTERRUPTION_END); @@ -198,7 +198,7 @@ export class AudioPlayer implements OperationQueueable { return this._id !== INVALID_AUDIO_ID; } - get src () { + get src (): string { return this._url; } get type (): AudioType { @@ -331,12 +331,12 @@ export class AudioPlayer implements OperationQueueable { resolve(); }); } - onInterruptionBegin (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void) { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void) { this._eventTarget.off(AudioEvent.ENDED, cb); } + onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } + offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } + onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } + offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } + onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } + offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } } // REMOVE_ME diff --git a/pal/audio/operation-queue.ts b/pal/audio/operation-queue.ts index 61f4a11ca32..158b6ea694d 100644 --- a/pal/audio/operation-queue.ts +++ b/pal/audio/operation-queue.ts @@ -38,7 +38,7 @@ export interface OperationQueueable { } let operationId = 0; -function _tryCallingRecursively (target: T, opInfo: OperationInfo) { +function _tryCallingRecursively (target: T, opInfo: OperationInfo): void { if (opInfo.invoking) { return; } diff --git a/pal/audio/type.ts b/pal/audio/type.ts index 60f4e850531..0051b84d6da 100644 --- a/pal/audio/type.ts +++ b/pal/audio/type.ts @@ -74,11 +74,11 @@ export class AudioPCMDataView { } } - get length () { + get length (): number { return this._bufferView.length; } - public getData (offset: number) { + public getData (offset: number): number { return this._bufferView[offset] * this._normalizeFactor; } } diff --git a/pal/audio/web/player-dom.ts b/pal/audio/web/player-dom.ts index 94444e5b5f0..6db349bd9af 100644 --- a/pal/audio/web/player-dom.ts +++ b/pal/audio/web/player-dom.ts @@ -36,8 +36,8 @@ function ensurePlaying (domAudio: HTMLAudioElement): Promise { if (promise === undefined) { // Chrome50/Firefox53 below return resolve(); } - promise.then(resolve).catch(() => { - const onGesture = () => { + promise.then(resolve).catch((): void => { + const onGesture = (): void => { domAudio.play().then(() => { // HACK NOTE: if the user slide after touch start, the context cannot be resumed correctly. canvas?.removeEventListener('touchend', onGesture, { capture: true }); @@ -56,7 +56,7 @@ function ensurePlaying (domAudio: HTMLAudioElement): Promise { export class OneShotAudioDOM { private _domAudio: HTMLAudioElement; private _onPlayCb?: () => void; - get onPlay () { + get onPlay (): (() => void) | undefined { return this._onPlayCb; } set onPlay (cb) { @@ -64,7 +64,7 @@ export class OneShotAudioDOM { } private _onEndCb?: () => void; - get onEnd () { + get onEnd (): (() => void) | undefined { return this._onEndCb; } set onEnd (cb) { @@ -111,7 +111,7 @@ export class AudioPlayerDOM implements OperationQueueable { // event game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); - this._onEnded = () => { + this._onEnded = (): void => { this.seek(0).catch((e) => {}); this._state = AudioState.INIT; this._eventTarget.emit(AudioEvent.ENDED); @@ -119,7 +119,7 @@ export class AudioPlayerDOM implements OperationQueueable { this._domAudio.addEventListener('ended', this._onEnded); } - destroy () { + destroy (): void { game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); this._domAudio.removeEventListener('ended', this._onEnded); @@ -152,16 +152,16 @@ export class AudioPlayerDOM implements OperationQueueable { success(); } }, 8000); - const clearEvent = () => { + const clearEvent = (): void => { clearTimeout(timer); domAudio.removeEventListener(loadedEvent, success, false); domAudio.removeEventListener('error', failure, false); }; - const success = () => { + const success = (): void => { clearEvent(); resolve(domAudio); }; - const failure = () => { + const failure = (): void => { clearEvent(); const message = `load audio failure - ${url}`; reject(message); @@ -181,7 +181,7 @@ export class AudioPlayerDOM implements OperationQueueable { }); } - private _onInterruptedBegin () { + private _onInterruptedBegin (): void { if (this._state === AudioState.PLAYING) { this.pause().then(() => { this._state = AudioState.INTERRUPTED; @@ -189,7 +189,7 @@ export class AudioPlayerDOM implements OperationQueueable { }).catch((e) => {}); } } - private _onInterruptedEnd () { + private _onInterruptedEnd (): void { if (this._state === AudioState.INTERRUPTED) { this.play().then(() => { this._eventTarget.emit(AudioEvent.INTERRUPTION_END); @@ -268,10 +268,10 @@ export class AudioPlayerDOM implements OperationQueueable { }); } - onInterruptionBegin (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void) { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void) { this._eventTarget.off(AudioEvent.ENDED, cb); } + onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } + offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } + onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } + offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } + onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } + offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } } diff --git a/pal/audio/web/player-web.ts b/pal/audio/web/player-web.ts index 95cb3e2e26e..7b7a0bc1d5f 100644 --- a/pal/audio/web/player-web.ts +++ b/pal/audio/web/player-web.ts @@ -44,7 +44,7 @@ export class AudioContextAgent { constructor () { this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); this._eventTarget = new EventTarget(); - this._context.onstatechange = () => { + this._context.onstatechange = (): void => { if (this._context.state === 'running') { this._isRunning = true; this._eventTarget.emit(_contextRunningEvent); @@ -54,19 +54,19 @@ export class AudioContextAgent { }; } - get isRunning () { + get isRunning (): boolean { return this._isRunning; } - get currentTime () { + get currentTime (): number { return this._context.currentTime; } - public onceRunning (cb: (...args: any[]) => void, target?: any) { + public onceRunning (cb: (...args: any[]) => void, target?: any): void { this._eventTarget.once(_contextRunningEvent, cb, target); } - public offRunning (cb?: (...args: any[]) => void, target?: any) { + public offRunning (cb?: (...args: any[]) => void, target?: any): void { this._eventTarget.off(_contextRunningEvent, cb, target); } @@ -101,7 +101,7 @@ export class AudioContextAgent { // Force running audio context if state is not 'running', may be 'suspended' or 'interrupted'. const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement; // HACK NOTE: if the user slide after touch start, the context cannot be resumed correctly. - const onGesture = () => { + const onGesture = (): void => { context.resume().then(() => { canvas?.removeEventListener('touchend', onGesture, { capture: true }); canvas?.removeEventListener('mouseup', onGesture, { capture: true }); @@ -113,7 +113,7 @@ export class AudioContextAgent { }); } - public createBufferSource (audioBuffer?: AudioBuffer, loop?: boolean) { + public createBufferSource (audioBuffer?: AudioBuffer, loop?: boolean): AudioBufferSourceNode { const sourceBufferNode = this._context.createBufferSource(); if (audioBuffer !== undefined) { sourceBufferNode.buffer = audioBuffer; @@ -124,13 +124,13 @@ export class AudioContextAgent { return sourceBufferNode; } - public createGain (volume = 1) { + public createGain (volume = 1): GainNode { const gainNode = this._context.createGain(); this.setGainValue(gainNode, volume); return gainNode; } - public setGainValue (gain: GainNode, volume: number) { + public setGainValue (gain: GainNode, volume: number): void { if (gain.gain.setTargetAtTime) { try { gain.gain.setTargetAtTime(volume, this._context.currentTime, 0); @@ -143,7 +143,7 @@ export class AudioContextAgent { } } - public connectContext (audioNode: GainNode) { + public connectContext (audioNode: GainNode): void { if (!this._context) { return; } @@ -163,7 +163,7 @@ export class OneShotAudioWeb { private _currentTimer = 0; private _url: string; - get onPlay () { + get onPlay (): (() => void) | undefined { return this._onPlayCb; } set onPlay (cb) { @@ -171,7 +171,7 @@ export class OneShotAudioWeb { } private _onEndCb?: () => void; - get onEnd () { + get onEnd (): (() => void) | undefined { return this._onEndCb; } set onEnd (cb) { @@ -241,7 +241,7 @@ export class AudioPlayerWeb implements OperationQueueable { game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); } - destroy () { + destroy (): void { this._audioTimer.destroy(); if (this._audioBuffer) { // NOTE: need to release AudioBuffer instance @@ -272,7 +272,7 @@ export class AudioPlayerWeb implements OperationQueueable { xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; - xhr.onload = () => { + xhr.onload = (): void => { if (xhr.status === 200 || xhr.status === 0) { audioContextAgent!.decodeAudioData(xhr.response).then((decodedAudioBuffer) => { audioBufferManager.addCache(url, decodedAudioBuffer); @@ -282,9 +282,9 @@ export class AudioPlayerWeb implements OperationQueueable { reject(new Error(`${errInfo}${xhr.status}(no response)`)); } }; - xhr.onerror = () => { reject(new Error(`${errInfo}${xhr.status}(error)`)); }; - xhr.ontimeout = () => { reject(new Error(`${errInfo}${xhr.status}(time out)`)); }; - xhr.onabort = () => { reject(new Error(`${errInfo}${xhr.status}(abort)`)); }; + xhr.onerror = (): void => { reject(new Error(`${errInfo}${xhr.status}(error)`)); }; + xhr.ontimeout = (): void => { reject(new Error(`${errInfo}${xhr.status}(time out)`)); }; + xhr.onabort = (): void => { reject(new Error(`${errInfo}${xhr.status}(abort)`)); }; xhr.send(null); }); @@ -307,7 +307,7 @@ export class AudioPlayerWeb implements OperationQueueable { return new AudioPCMDataView(this._audioBuffer.getChannelData(channelIndex), 1); } - private _onInterruptedBegin () { + private _onInterruptedBegin (): void { if (this._state === AudioState.PLAYING) { this.pause().then(() => { this._state = AudioState.INTERRUPTED; @@ -315,7 +315,7 @@ export class AudioPlayerWeb implements OperationQueueable { }).catch((e) => {}); } } - private _onInterruptedEnd () { + private _onInterruptedEnd (): void { if (this._state === AudioState.INTERRUPTED) { this.play().then(() => { this._eventTarget.emit(AudioEvent.INTERRUPTION_END); @@ -355,7 +355,7 @@ export class AudioPlayerWeb implements OperationQueueable { get currentTime (): number { return this._audioTimer.currentTime; } - private offRunning () { + private offRunning (): void { if (this._runningCallback) { audioContextAgent!.offRunning(this._runningCallback); this._runningCallback = undefined; @@ -395,7 +395,7 @@ export class AudioPlayerWeb implements OperationQueueable { resolve(); } else { this.offRunning(); - this._runningCallback = () => { + this._runningCallback = (): void => { this._startSourceNode(); resolve(); }; @@ -409,7 +409,7 @@ export class AudioPlayerWeb implements OperationQueueable { }); } - private _startSourceNode () { + private _startSourceNode (): void { // one AudioBufferSourceNode can't start twice this._stopSourceNode(); this._sourceNode = audioContextAgent!.createBufferSource(this._audioBuffer, this.loop); @@ -421,7 +421,7 @@ export class AudioPlayerWeb implements OperationQueueable { /* still not supported by all platforms * this._sourceNode.onended = this._onEnded; /* doing it manually for now */ - const checkEnded = () => { + const checkEnded = (): void => { if (this.loop) { this._currentTimer = window.setTimeout(checkEnded, this._audioBuffer.duration * 1000); } else { // do ended @@ -434,7 +434,7 @@ export class AudioPlayerWeb implements OperationQueueable { this._currentTimer = window.setTimeout(checkEnded, (this._audioBuffer.duration - this._audioTimer.currentTime) * 1000); } - private _stopSourceNode () { + private _stopSourceNode (): void { try { if (this._sourceNode) { this._sourceNode.stop(); @@ -471,10 +471,10 @@ export class AudioPlayerWeb implements OperationQueueable { return Promise.resolve(); } - onInterruptionBegin (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void) { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void) { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void) { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void) { this._eventTarget.off(AudioEvent.ENDED, cb); } + onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } + offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } + onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } + offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } + onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } + offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } } diff --git a/pal/audio/web/player.ts b/pal/audio/web/player.ts index 2c24d01b76e..bc405ca5604 100644 --- a/pal/audio/web/player.ts +++ b/pal/audio/web/player.ts @@ -32,14 +32,14 @@ type AbstractAudioPlayer = AudioPlayerDOM | AudioPlayerWeb; export class OneShotAudio { private _audio: AbstractOneShotAudio; - get onPlay () { + get onPlay (): (() => void) | undefined { return this._audio.onPlay; } set onPlay (v) { this._audio.onPlay = v; } - get onEnd () { + get onEnd (): (() => void) | undefined { return this._audio.onEnd; } set onEnd (v) { @@ -77,7 +77,7 @@ export class AudioPlayer { } }); } - destroy () { + destroy (): void { this._player.destroy(); } static loadNative (url: string, opts?: AudioLoadOptions): Promise { @@ -121,10 +121,10 @@ export class AudioPlayer { play (): Promise { return this._player.play(); } pause (): Promise { return this._player.pause(); } stop (): Promise { return this._player.stop(); } - onInterruptionBegin (cb: () => void) { this._player.onInterruptionBegin(cb); } - offInterruptionBegin (cb?: () => void) { this._player.offInterruptionBegin(cb); } - onInterruptionEnd (cb: () => void) { this._player.onInterruptionEnd(cb); } - offInterruptionEnd (cb?: () => void) { this._player.offInterruptionEnd(cb); } - onEnded (cb: () => void) { this._player.onEnded(cb); } - offEnded (cb?: () => void) { this._player.offEnded(cb); } + onInterruptionBegin (cb: () => void): void { this._player.onInterruptionBegin(cb); } + offInterruptionBegin (cb?: () => void): void { this._player.offInterruptionBegin(cb); } + onInterruptionEnd (cb: () => void): void { this._player.onInterruptionEnd(cb); } + offInterruptionEnd (cb?: () => void): void { this._player.offInterruptionEnd(cb); } + onEnded (cb: () => void): void { this._player.onEnded(cb); } + offEnded (cb?: () => void): void { this._player.offEnded(cb); } } diff --git a/pal/env/native/env.ts b/pal/env/native/env.ts index 4ebb47a82bc..082671beb31 100644 --- a/pal/env/native/env.ts +++ b/pal/env/native/env.ts @@ -49,7 +49,7 @@ export function loadJsFile (path: string): Promise { return new Promise((resolve, reject) => { const sourceURL = window.location.href + path; const xhr = new XMLHttpRequest(); - xhr.onload = () => { + xhr.onload = (): void => { if (xhr.status !== 200) { reject(new Error(`load js file failed: ${sourceURL}, error status: ${xhr.status}`)); return; @@ -58,7 +58,7 @@ export function loadJsFile (path: string): Promise { window.eval(`${xhr.response as string}\n//# sourceURL=${sourceURL}`); resolve(); }; - xhr.onerror = () => { + xhr.onerror = (): void => { reject(new Error(`load js file failed: ${sourceURL}`)); }; xhr.open('GET', sourceURL, true); diff --git a/pal/env/web/env.ts b/pal/env/web/env.ts index 6b84f874b32..ff35915bbcb 100644 --- a/pal/env/web/env.ts +++ b/pal/env/web/env.ts @@ -33,7 +33,7 @@ export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElemen export function loadJsFile (path: string): Promise { return new Promise((resolve, reject) => { let err; - function windowErrorListener (evt) { + function windowErrorListener (evt): void { if (evt.filename === path) { err = evt.error; } diff --git a/pal/input/minigame/accelerometer-input.ts b/pal/input/minigame/accelerometer-input.ts index e575f68a43a..571d1463638 100644 --- a/pal/input/minigame/accelerometer-input.ts +++ b/pal/input/minigame/accelerometer-input.ts @@ -38,22 +38,22 @@ export class AccelerometerInputSource { this._didAccelerateFunc = this._didAccelerate.bind(this); } - private _registerEvent () { + private _registerEvent (): void { minigame.onAccelerometerChange(this._didAccelerateFunc); } - private _unregisterEvent () { + private _unregisterEvent (): void { minigame.offAccelerometerChange(this._didAccelerateFunc); } - private _didAccelerate (event: AccelerometerData) { + private _didAccelerate (event: AccelerometerData): void { const timestamp = performance.now(); const acceleration = new Acceleration(event.x, event.y, event.z, timestamp); const eventAcceleration = new EventAcceleration(acceleration); this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration); } - public start () { + public start (): void { this._registerEvent(); minigame.startAccelerometer({ interval: this._accelMode, @@ -62,7 +62,7 @@ export class AccelerometerInputSource { }, }); } - public stop () { + public stop (): void { minigame.stopAccelerometer({ success: () => { this._isStarted = false; @@ -73,7 +73,7 @@ export class AccelerometerInputSource { }); this._unregisterEvent(); } - public setInterval (intervalInMileseconds: number) { + public setInterval (intervalInMileseconds: number): void { // reference: https://developers.weixin.qq.com/minigame/dev/api/device/accelerometer/wx.startAccelerometer.html if (intervalInMileseconds >= 200) { this._accelMode = 'normal'; @@ -88,7 +88,7 @@ export class AccelerometerInputSource { this.start(); } } - public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any) { + public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/minigame/gamepad-input.ts b/pal/input/minigame/gamepad-input.ts index 25dc5a8553c..da83428709d 100644 --- a/pal/input/minigame/gamepad-input.ts +++ b/pal/input/minigame/gamepad-input.ts @@ -32,39 +32,39 @@ export class GamepadInputDevice { public static all: GamepadInputDevice[] = []; public static xr: (GamepadInputDevice | null) = null; - public get buttonNorth () { return this._buttonNorth; } - public get buttonEast () { return this._buttonEast; } - public get buttonWest () { return this._buttonWest; } - public get buttonSouth () { return this._buttonSouth; } - public get buttonL1 () { return this._buttonL1; } - public get buttonL2 () { return this._buttonL2; } - public get buttonL3 () { return this._buttonL3; } - public get buttonR1 () { return this._buttonR1; } - public get buttonR2 () { return this._buttonR2; } - public get buttonR3 () { return this._buttonR3; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth; } + public get buttonEast (): InputSourceButton { return this._buttonEast; } + public get buttonWest (): InputSourceButton { return this._buttonWest; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth; } + public get buttonL1 (): InputSourceButton { return this._buttonL1; } + public get buttonL2 (): InputSourceButton { return this._buttonL2; } + public get buttonL3 (): InputSourceButton { return this._buttonL3; } + public get buttonR1 (): InputSourceButton { return this._buttonR1; } + public get buttonR2 (): InputSourceButton { return this._buttonR2; } + public get buttonR3 (): InputSourceButton { return this._buttonR3; } // public get buttonTouchPad () { return this._buttonTouchPad; } // public get buttonHome () { return this._buttonHome; } - public get buttonShare () { return this._buttonShare; } - public get buttonOptions () { return this._buttonOptions; } - public get dpad () { return this._dpad; } - public get leftStick () { return this._leftStick; } - public get rightStick () { return this._rightStick; } - public get buttonStart () { return this._buttonStart; } - public get gripLeft () { return this._gripLeft; } - public get gripRight () { return this._gripRight; } - public get handLeftPosition () { return this._handLeftPosition; } - public get handLeftOrientation () { return this._handLeftOrientation; } - public get handRightPosition () { return this._handRightPosition; } - public get handRightOrientation () { return this._handRightOrientation; } - public get aimLeftPosition () { return this._aimLeftPosition; } - public get aimLeftOrientation () { return this._aimLeftOrientation; } - public get aimRightPosition () { return this._aimRightPosition; } - public get aimRightOrientation () { return this._aimRightOrientation; } - - public get deviceId () { + public get buttonShare (): InputSourceButton { return this._buttonShare; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions; } + public get dpad (): InputSourceDpad { return this._dpad; } + public get leftStick (): InputSourceStick { return this._leftStick; } + public get rightStick (): InputSourceStick { return this._rightStick; } + public get buttonStart (): InputSourceButton { return this._buttonStart; } + public get gripLeft (): InputSourceButton { return this._gripLeft; } + public get gripRight (): InputSourceButton { return this._gripRight; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } + + public get deviceId (): number { return this._deviceId; } - public get connected () { + public get connected (): boolean { return this._connected; } @@ -110,39 +110,39 @@ export class GamepadInputDevice { /** * @engineInternal */ - public static _init () { + public static _init (): void { // not supported } /** * @engineInternal */ - public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any) { + public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { GamepadInputDevice._eventTarget.on(eventType, cb, target); } - private _initInputSource () { + private _initInputSource (): void { this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = () => 0; + this._buttonNorth.getValue = (): number => 0; this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = () => 0; + this._buttonEast.getValue = (): number => 0; this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = () => 0; + this._buttonWest.getValue = (): number => 0; this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = () => 0; + this._buttonSouth.getValue = (): number => 0; this._buttonL1 = new InputSourceButton(); - this._buttonL1.getValue = () => 0; + this._buttonL1.getValue = (): number => 0; this._buttonL2 = new InputSourceButton(); - this._buttonL2.getValue = () => 0; + this._buttonL2.getValue = (): number => 0; this._buttonL3 = new InputSourceButton(); - this._buttonL3.getValue = () => 0; + this._buttonL3.getValue = (): number => 0; this._buttonR1 = new InputSourceButton(); - this._buttonR1.getValue = () => 0; + this._buttonR1.getValue = (): number => 0; this._buttonR2 = new InputSourceButton(); - this._buttonR2.getValue = () => 0; + this._buttonR2.getValue = (): number => 0; this._buttonR3 = new InputSourceButton(); - this._buttonR3.getValue = () => 0; + this._buttonR3.getValue = (): number => 0; // this._buttonTouchPad = new InputSourceButton(); // this._buttonTouchPad.getValue = () => 0; @@ -150,66 +150,66 @@ export class GamepadInputDevice { // this._buttonHome.getValue = () => 0; this._buttonShare = new InputSourceButton(); - this._buttonShare.getValue = () => 0; + this._buttonShare.getValue = (): number => 0; this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = () => 0; + this._buttonOptions.getValue = (): number => 0; const dpadUp = new InputSourceButton(); - dpadUp.getValue = () => 0; + dpadUp.getValue = (): number => 0; const dpadDown = new InputSourceButton(); - dpadDown.getValue = () => 0; + dpadDown.getValue = (): number => 0; const dpadLeft = new InputSourceButton(); - dpadLeft.getValue = () => 0; + dpadLeft.getValue = (): number => 0; const dpadRight = new InputSourceButton(); - dpadRight.getValue = () => 0; + dpadRight.getValue = (): number => 0; this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = () => 0; + leftStickUp.getValue = (): number => 0; const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = () => 0; + leftStickDown.getValue = (): number => 0; const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = () => 0; + leftStickLeft.getValue = (): number => 0; const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = () => 0; + leftStickRight.getValue = (): number => 0; this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = () => 0; + rightStickUp.getValue = (): number => 0; const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = () => 0; + rightStickDown.getValue = (): number => 0; const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = () => 0; + rightStickLeft.getValue = (): number => 0; const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = () => 0; + rightStickRight.getValue = (): number => 0; this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = () => 0; + this._buttonStart.getValue = (): number => 0; this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = () => 0; + this._gripLeft.getValue = (): number => 0; this._gripRight = new InputSourceButton(); - this._gripRight.getValue = () => 0; + this._gripRight.getValue = (): number => 0; this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = () => Vec3.ZERO; + this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = () => Quat.IDENTITY; + this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = () => Vec3.ZERO; + this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = () => Quat.IDENTITY; + this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = () => Vec3.ZERO; + this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = () => Quat.IDENTITY; + this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = () => Vec3.ZERO; + this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = () => Quat.IDENTITY; + this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/minigame/handheld-input.ts b/pal/input/minigame/handheld-input.ts index 4b265c2c6d3..76b069ce5ad 100644 --- a/pal/input/minigame/handheld-input.ts +++ b/pal/input/minigame/handheld-input.ts @@ -29,8 +29,8 @@ import { InputSourcePosition, InputSourceOrientation } from '../input-source'; import { Quat, Vec3 } from '../../../cocos/core/math'; export class HandheldInputDevice { - public get handheldPosition () { return this._handheldPosition; } - public get handheldOrientation () { return this._handheldOrientation; } + public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } + public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -44,14 +44,14 @@ export class HandheldInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HandheldCallback, target?: any) { + public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _initInputSource () { + private _initInputSource (): void { this._handheldPosition = new InputSourcePosition(); - this._handheldPosition.getValue = () => Vec3.ZERO; + this._handheldPosition.getValue = (): Readonly => Vec3.ZERO; this._handheldOrientation = new InputSourceOrientation(); - this._handheldOrientation.getValue = () => Quat.IDENTITY; + this._handheldOrientation.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/minigame/handle-input.ts b/pal/input/minigame/handle-input.ts index da9098ac137..d154220753a 100644 --- a/pal/input/minigame/handle-input.ts +++ b/pal/input/minigame/handle-input.ts @@ -29,30 +29,30 @@ import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOr import { Vec3, Quat } from '../../../cocos/core/math'; export class HandleInputDevice { - public get buttonNorth () { return this._buttonNorth; } - public get buttonEast () { return this._buttonEast; } - public get buttonWest () { return this._buttonWest; } - public get buttonSouth () { return this._buttonSouth; } - public get buttonTriggerLeft () { return this._buttonTriggerLeft; } - public get buttonTriggerRight () { return this._buttonTriggerRight; } - public get triggerLeft () { return this._triggerLeft; } - public get triggerRight () { return this._triggerRight; } - public get gripLeft () { return this._gripLeft; } - public get gripRight () { return this._gripRight; } - public get leftStick () { return this._leftStick; } - public get rightStick () { return this._rightStick; } - public get buttonLeftStick () { return this._buttonLeftStick; } - public get buttonRightStick () { return this._buttonRightStick; } - public get buttonOptions () { return this._buttonOptions; } - public get buttonStart () { return this._buttonStart; } - public get handLeftPosition () { return this._handLeftPosition; } - public get handLeftOrientation () { return this._handLeftOrientation; } - public get handRightPosition () { return this._handRightPosition; } - public get handRightOrientation () { return this._handRightOrientation; } - public get aimLeftPosition () { return this._aimLeftPosition; } - public get aimLeftOrientation () { return this._aimLeftOrientation; } - public get aimRightPosition () { return this._aimRightPosition; } - public get aimRightOrientation () { return this._aimRightOrientation; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth; } + public get buttonEast (): InputSourceButton { return this._buttonEast; } + public get buttonWest (): InputSourceButton { return this._buttonWest; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth; } + public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } + public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } + public get triggerLeft (): InputSourceButton { return this._triggerLeft; } + public get triggerRight (): InputSourceButton { return this._triggerRight; } + public get gripLeft (): InputSourceButton { return this._gripLeft; } + public get gripRight (): InputSourceButton { return this._gripRight; } + public get leftStick (): InputSourceStick { return this._leftStick; } + public get rightStick (): InputSourceStick { return this._rightStick; } + public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } + public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions; } + public get buttonStart (): InputSourceButton { return this._buttonStart; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -88,80 +88,80 @@ export class HandleInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HandleCallback, target?: any) { + public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _initInputSource () { + private _initInputSource (): void { this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = () => 0; + this._buttonNorth.getValue = (): number => 0; this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = () => 0; + this._buttonEast.getValue = (): number => 0; this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = () => 0; + this._buttonWest.getValue = (): number => 0; this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = () => 0; + this._buttonSouth.getValue = (): number => 0; this._buttonTriggerLeft = new InputSourceButton(); - this._buttonTriggerLeft.getValue = () => 0; + this._buttonTriggerLeft.getValue = (): number => 0; this._buttonTriggerRight = new InputSourceButton(); - this._buttonTriggerRight.getValue = () => 0; + this._buttonTriggerRight.getValue = (): number => 0; this._triggerLeft = new InputSourceButton(); - this._triggerLeft.getValue = () => 0; + this._triggerLeft.getValue = (): number => 0; this._triggerRight = new InputSourceButton(); - this._triggerRight.getValue = () => 0; + this._triggerRight.getValue = (): number => 0; this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = () => 0; + this._gripLeft.getValue = (): number => 0; this._gripRight = new InputSourceButton(); - this._gripRight.getValue = () => 0; + this._gripRight.getValue = (): number => 0; this._buttonLeftStick = new InputSourceButton(); - this._buttonLeftStick.getValue = () => 0; + this._buttonLeftStick.getValue = (): number => 0; const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = () => 0; + leftStickUp.getValue = (): number => 0; const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = () => 0; + leftStickDown.getValue = (): number => 0; const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = () => 0; + leftStickLeft.getValue = (): number => 0; const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = () => 0; + leftStickRight.getValue = (): number => 0; this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); this._buttonRightStick = new InputSourceButton(); - this._buttonRightStick.getValue = () => 0; + this._buttonRightStick.getValue = (): number => 0; const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = () => 0; + rightStickUp.getValue = (): number => 0; const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = () => 0; + rightStickDown.getValue = (): number => 0; const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = () => 0; + rightStickLeft.getValue = (): number => 0; const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = () => 0; + rightStickRight.getValue = (): number => 0; this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = () => 0; + this._buttonOptions.getValue = (): number => 0; this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = () => 0; + this._buttonStart.getValue = (): number => 0; this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = () => Vec3.ZERO; + this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = () => Quat.IDENTITY; + this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = () => Vec3.ZERO; + this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = () => Quat.IDENTITY; + this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = () => Vec3.ZERO; + this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = () => Quat.IDENTITY; + this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = () => Vec3.ZERO; + this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = () => Quat.IDENTITY; + this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/minigame/hmd-input.ts b/pal/input/minigame/hmd-input.ts index 997bd881bab..67e0eed1345 100644 --- a/pal/input/minigame/hmd-input.ts +++ b/pal/input/minigame/hmd-input.ts @@ -29,12 +29,12 @@ import { InputSourcePosition, InputSourceOrientation } from '../input-source'; import { Vec3, Quat } from '../../../cocos/core/math'; export class HMDInputDevice { - public get viewLeftPosition () { return this._viewLeftPosition; } - public get viewLeftOrientation () { return this._viewLeftOrientation; } - public get viewRightPosition () { return this._viewRightPosition; } - public get viewRightOrientation () { return this._viewRightOrientation; } - public get headMiddlePosition () { return this._headMiddlePosition; } - public get headMiddleOrientation () { return this._headMiddleOrientation; } + public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } + public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } + public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } + public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } + public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } + public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -52,24 +52,24 @@ export class HMDInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HMDCallback, target?: any) { + public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _initInputSource () { + private _initInputSource (): void { this._viewLeftPosition = new InputSourcePosition(); - this._viewLeftPosition.getValue = () => Vec3.ZERO; + this._viewLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._viewLeftOrientation = new InputSourceOrientation(); - this._viewLeftOrientation.getValue = () => Quat.IDENTITY; + this._viewLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._viewRightPosition = new InputSourcePosition(); - this._viewRightPosition.getValue = () => Vec3.ZERO; + this._viewRightPosition.getValue = (): Readonly => Vec3.ZERO; this._viewRightOrientation = new InputSourceOrientation(); - this._viewRightOrientation.getValue = () => Quat.IDENTITY; + this._viewRightOrientation.getValue = (): Readonly => Quat.IDENTITY; this._headMiddlePosition = new InputSourcePosition(); - this._headMiddlePosition.getValue = () => Vec3.ZERO; + this._headMiddlePosition.getValue = (): Readonly => Vec3.ZERO; this._headMiddleOrientation = new InputSourceOrientation(); - this._headMiddleOrientation.getValue = () => Quat.IDENTITY; + this._headMiddleOrientation.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/minigame/keyboard-input.ts b/pal/input/minigame/keyboard-input.ts index d615d1740fa..c78f15e7414 100644 --- a/pal/input/minigame/keyboard-input.ts +++ b/pal/input/minigame/keyboard-input.ts @@ -149,7 +149,7 @@ export class KeyboardInputSource { } } - private _registerEvent () { + private _registerEvent (): void { minigame.wx?.onKeyDown?.((res) => { const keyCode = getKeyCode(res.code); if (!this._keyStateMap[keyCode]) { @@ -169,13 +169,13 @@ export class KeyboardInputSource { }); } - private _getInputEvent (event: KeyboardEventData, eventType: InputEventType) { + private _getInputEvent (event: KeyboardEventData, eventType: InputEventType): EventKeyboard { const keyCode = getKeyCode(event.code); const eventKeyboard = new EventKeyboard(keyCode, eventType); return eventKeyboard; } - public on (eventType: InputEventType, callback: KeyboardCallback, target?: any) { + public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/minigame/mouse-input.ts b/pal/input/minigame/mouse-input.ts index e161dd01cb3..e05970b8572 100644 --- a/pal/input/minigame/mouse-input.ts +++ b/pal/input/minigame/mouse-input.ts @@ -51,7 +51,7 @@ export class MouseInputSource { return new Vec2(x, y); } - private _registerEvent () { + private _registerEvent (): void { minigame.wx?.onMouseDown?.(this._createCallback(InputEventType.MOUSE_DOWN)); minigame.wx?.onMouseMove?.(this._createCallback(InputEventType.MOUSE_MOVE)); minigame.wx?.onMouseUp?.(this._createCallback(InputEventType.MOUSE_UP)); @@ -59,7 +59,7 @@ export class MouseInputSource { } private _createCallback (eventType: InputEventType) { - return (event: MouseEventData) => { + return (event: MouseEventData): void => { const location = this._getLocation(event); let button = event.button; switch (eventType) { @@ -90,7 +90,7 @@ export class MouseInputSource { }; } - private _handleMouseWheel (event: MouseWheelEventData) { + private _handleMouseWheel (event: MouseWheelEventData): void { const eventType = InputEventType.MOUSE_WHEEL; const location = this._getLocation(event); const button = event.button; @@ -107,7 +107,7 @@ export class MouseInputSource { this._eventTarget.emit(InputEventType.MOUSE_WHEEL, eventMouse); } - public on (eventType: InputEventType, callback: MouseCallback, target?: any) { + public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/minigame/touch-input.ts b/pal/input/minigame/touch-input.ts index f58333d4aa0..cce9b4ecd7b 100644 --- a/pal/input/minigame/touch-input.ts +++ b/pal/input/minigame/touch-input.ts @@ -44,7 +44,7 @@ export class TouchInputSource { } } - private _registerEvent () { + private _registerEvent (): void { minigame.onTouchStart(this._createCallback(InputEventType.TOUCH_START)); minigame.onTouchMove(this._createCallback(InputEventType.TOUCH_MOVE)); minigame.onTouchEnd(this._createCallback(InputEventType.TOUCH_END)); @@ -52,7 +52,7 @@ export class TouchInputSource { } private _createCallback (eventType: InputEventType) { - return (event: any) => { + return (event: any): void => { const handleTouches: Touch[] = []; const windowSize = screenAdapter.windowSize; const dpr = screenAdapter.devicePixelRatio; @@ -87,7 +87,7 @@ export class TouchInputSource { return new Vec2(x, y); } - public on (eventType: InputEventType, callback: TouchCallback, target?: any) { + public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/native/accelerometer-input.ts b/pal/input/native/accelerometer-input.ts index e0a4d1c9d3f..5f42d58600d 100644 --- a/pal/input/native/accelerometer-input.ts +++ b/pal/input/native/accelerometer-input.ts @@ -43,7 +43,7 @@ export class AccelerometerInputSource { this._didAccelerateFunc = this._didAccelerate.bind(this); } - private _didAccelerate () { + private _didAccelerate (): void { const deviceMotionValue = jsb.device.getDeviceMotionValue(); let x = deviceMotionValue[3] * 0.1; let y = deviceMotionValue[4] * 0.1; @@ -74,7 +74,7 @@ export class AccelerometerInputSource { this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration); } - public start () { + public start (): void { if (this._intervalId) { clearInterval(this._intervalId); } @@ -83,7 +83,7 @@ export class AccelerometerInputSource { jsb.device.setAccelerometerEnabled(true); this._isEnabled = true; } - public stop () { + public stop (): void { if (this._intervalId) { clearInterval(this._intervalId); this._intervalId = undefined; @@ -91,7 +91,7 @@ export class AccelerometerInputSource { jsb.device.setAccelerometerEnabled(false); this._isEnabled = false; } - public setInterval (intervalInMileseconds: number) { + public setInterval (intervalInMileseconds: number): void { this._intervalInSeconds = intervalInMileseconds / 1000; jsb.device.setAccelerometerInterval(this._intervalInSeconds); if (this._isEnabled) { @@ -100,7 +100,7 @@ export class AccelerometerInputSource { jsb.device.setAccelerometerEnabled(true); } } - public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any) { + public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/native/gamepad-input.ts b/pal/input/native/gamepad-input.ts index 058380ee388..87f6c124f22 100644 --- a/pal/input/native/gamepad-input.ts +++ b/pal/input/native/gamepad-input.ts @@ -88,39 +88,39 @@ export class GamepadInputDevice { public static all: GamepadInputDevice[] = []; public static xr: (GamepadInputDevice | null) = null; - public get buttonNorth () { return this._buttonNorth; } - public get buttonEast () { return this._buttonEast; } - public get buttonWest () { return this._buttonWest; } - public get buttonSouth () { return this._buttonSouth; } - public get buttonL1 () { return this._buttonL1; } - public get buttonL2 () { return this._buttonL2; } - public get buttonL3 () { return this._buttonL3; } - public get buttonR1 () { return this._buttonR1; } - public get buttonR2 () { return this._buttonR2; } - public get buttonR3 () { return this._buttonR3; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth; } + public get buttonEast (): InputSourceButton { return this._buttonEast; } + public get buttonWest (): InputSourceButton { return this._buttonWest; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth; } + public get buttonL1 (): InputSourceButton { return this._buttonL1; } + public get buttonL2 (): InputSourceButton { return this._buttonL2; } + public get buttonL3 (): InputSourceButton { return this._buttonL3; } + public get buttonR1 (): InputSourceButton { return this._buttonR1; } + public get buttonR2 (): InputSourceButton { return this._buttonR2; } + public get buttonR3 (): InputSourceButton { return this._buttonR3; } // public get buttonTouchPad () { return this._buttonTouchPad; } // public get buttonHome () { return this._buttonHome; } - public get buttonShare () { return this._buttonShare; } - public get buttonOptions () { return this._buttonOptions; } - public get dpad () { return this._dpad; } - public get leftStick () { return this._leftStick; } - public get rightStick () { return this._rightStick; } - public get buttonStart () { return this._buttonStart; } - public get gripLeft () { return this._gripLeft; } - public get gripRight () { return this._gripRight; } - public get handLeftPosition () { return this._handLeftPosition; } - public get handLeftOrientation () { return this._handLeftOrientation; } - public get handRightPosition () { return this._handRightPosition; } - public get handRightOrientation () { return this._handRightOrientation; } - public get aimLeftPosition () { return this._aimLeftPosition; } - public get aimLeftOrientation () { return this._aimLeftOrientation; } - public get aimRightPosition () { return this._aimRightPosition; } - public get aimRightOrientation () { return this._aimRightOrientation; } - - public get deviceId () { + public get buttonShare (): InputSourceButton { return this._buttonShare; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions; } + public get dpad (): InputSourceDpad { return this._dpad; } + public get leftStick (): InputSourceStick { return this._leftStick; } + public get rightStick (): InputSourceStick { return this._rightStick; } + public get buttonStart (): InputSourceButton { return this._buttonStart; } + public get gripLeft (): InputSourceButton { return this._gripLeft; } + public get gripRight (): InputSourceButton { return this._gripRight; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } + + public get deviceId (): number { return this._deviceId; } - public get connected () { + public get connected (): boolean { return this._connected; } @@ -194,7 +194,7 @@ export class GamepadInputDevice { /** * @engineInternal */ - public static _init () { + public static _init (): void { if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) { return; } @@ -204,21 +204,21 @@ export class GamepadInputDevice { /** * @engineInternal */ - public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any) { + public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { GamepadInputDevice._eventTarget.on(eventType, cb, target); } - private static _removeInputDevice (id: number) { + private static _removeInputDevice (id: number): void { const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id); if (removeIndex === -1) { return; } js.array.fastRemoveAt(GamepadInputDevice.all, removeIndex); } - private static _getInputDevice (id: number) { + private static _getInputDevice (id: number): GamepadInputDevice | undefined { return GamepadInputDevice.all.find((device) => device.deviceId === id); } - private static _createInputDevice (id: number, connected: boolean) { + private static _createInputDevice (id: number, connected: boolean): GamepadInputDevice { const device = new GamepadInputDevice(id); device._connected = connected; GamepadInputDevice.all.push(device); @@ -233,8 +233,8 @@ export class GamepadInputDevice { return device; } - private static _registerEvent () { - jsb.onControllerInput = (infoList: jsb.ControllerInfo[]) => { + private static _registerEvent (): void { + jsb.onControllerInput = (infoList: jsb.ControllerInfo[]): void => { for (let i = 0; i < infoList.length; ++i) { const info = infoList[i]; const device = GamepadInputDevice._getOrCreateInputDevice(info.id, true); @@ -243,7 +243,7 @@ export class GamepadInputDevice { } }; - jsb.onControllerChange = (controllerIds) => { + jsb.onControllerChange = (controllerIds): void => { // check connecting for (let i = 0; i < controllerIds.length; ++i) { const id = controllerIds[i]; @@ -277,7 +277,7 @@ export class GamepadInputDevice { } } - private _updateNativeButtonState (info: jsb.ControllerInfo) { + private _updateNativeButtonState (info: jsb.ControllerInfo): void { const { buttonInfoList, axisInfoList } = info; for (let i = 0; i < buttonInfoList.length; ++i) { const buttonInfo = buttonInfoList[i]; @@ -333,28 +333,28 @@ export class GamepadInputDevice { } } - private _initInputSource () { + private _initInputSource (): void { this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = () => this._nativeButtonState[Button.BUTTON_NORTH]; + this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH]; this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = () => this._nativeButtonState[Button.BUTTON_EAST]; + this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST]; this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = () => this._nativeButtonState[Button.BUTTON_WEST]; + this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST]; this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = () => this._nativeButtonState[Button.BUTTON_SOUTH]; + this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH]; this._buttonL1 = new InputSourceButton(); - this._buttonL1.getValue = () => this._nativeButtonState[Button.BUTTON_L1]; + this._buttonL1.getValue = (): number => this._nativeButtonState[Button.BUTTON_L1]; this._buttonL2 = new InputSourceButton(); - this._buttonL2.getValue = () => this._nativeButtonState[Button.BUTTON_L2]; + this._buttonL2.getValue = (): number => this._nativeButtonState[Button.BUTTON_L2]; this._buttonL3 = new InputSourceButton(); - this._buttonL3.getValue = () => this._nativeButtonState[Button.BUTTON_L3]; + this._buttonL3.getValue = (): number => this._nativeButtonState[Button.BUTTON_L3]; this._buttonR1 = new InputSourceButton(); - this._buttonR1.getValue = () => this._nativeButtonState[Button.BUTTON_R1]; + this._buttonR1.getValue = (): number => this._nativeButtonState[Button.BUTTON_R1]; this._buttonR2 = new InputSourceButton(); - this._buttonR2.getValue = () => this._nativeButtonState[Button.BUTTON_R2]; + this._buttonR2.getValue = (): number => this._nativeButtonState[Button.BUTTON_R2]; this._buttonR3 = new InputSourceButton(); - this._buttonR3.getValue = () => this._nativeButtonState[Button.BUTTON_R3]; + this._buttonR3.getValue = (): number => this._nativeButtonState[Button.BUTTON_R3]; // this._buttonTouchPad = new InputSourceButton(); // this._buttonTouchPad.getValue = () => 0; // TODO: NX unavailable @@ -362,66 +362,66 @@ export class GamepadInputDevice { // this._buttonHome.getValue = () => 0; // TODO: NX unavailable this._buttonShare = new InputSourceButton(); - this._buttonShare.getValue = () => this._nativeButtonState[Button.NS_MINUS]; // TODO: NX only for now + this._buttonShare.getValue = (): number => this._nativeButtonState[Button.NS_MINUS]; // TODO: NX only for now this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = () => this._nativeButtonState[Button.NS_PLUS] || this._nativeButtonState[Button.ROKID_MENU]; + this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.NS_PLUS] || this._nativeButtonState[Button.ROKID_MENU]; const dpadUp = new InputSourceButton(); - dpadUp.getValue = () => this._nativeButtonState[Button.DPAD_UP]; + dpadUp.getValue = (): number => this._nativeButtonState[Button.DPAD_UP]; const dpadDown = new InputSourceButton(); - dpadDown.getValue = () => this._nativeButtonState[Button.DPAD_DOWN]; + dpadDown.getValue = (): number => this._nativeButtonState[Button.DPAD_DOWN]; const dpadLeft = new InputSourceButton(); - dpadLeft.getValue = () => this._nativeButtonState[Button.DPAD_LEFT]; + dpadLeft.getValue = (): number => this._nativeButtonState[Button.DPAD_LEFT]; const dpadRight = new InputSourceButton(); - dpadRight.getValue = () => this._nativeButtonState[Button.DPAD_RIGHT]; + dpadRight.getValue = (): number => this._nativeButtonState[Button.DPAD_RIGHT]; this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = () => this._nativeButtonState[Button.LEFT_STICK_UP]; + leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP]; const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = () => this._nativeButtonState[Button.LEFT_STICK_DOWN]; + leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN]; const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = () => this._nativeButtonState[Button.LEFT_STICK_LEFT]; + leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT]; const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = () => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; + leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_UP]; + rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP]; const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; + rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; + rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; + rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = () => this._nativeButtonState[Button.ROKID_START]; // TODO: Rokid only for now + this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START]; // TODO: Rokid only for now this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = () => 0; + this._gripLeft.getValue = (): number => 0; this._gripRight = new InputSourceButton(); - this._gripRight.getValue = () => 0; + this._gripRight.getValue = (): number => 0; this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = () => Vec3.ZERO; + this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = () => Quat.IDENTITY; + this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = () => Vec3.ZERO; + this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = () => Quat.IDENTITY; + this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = () => Vec3.ZERO; + this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = () => Quat.IDENTITY; + this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = () => Vec3.ZERO; + this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = () => Quat.IDENTITY; + this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/native/handheld-input.ts b/pal/input/native/handheld-input.ts index 4fdc6b06751..8c73b32f2ac 100644 --- a/pal/input/native/handheld-input.ts +++ b/pal/input/native/handheld-input.ts @@ -42,8 +42,8 @@ interface IPoseValue { type NativePoseState = Record export class HandheldInputDevice { - public get handheldPosition () { return this._handheldPosition; } - public get handheldOrientation () { return this._handheldOrientation; } + public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } + public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -59,8 +59,8 @@ export class HandheldInputDevice { this._registerEvent(); } - private _registerEvent () { - jsb.onHandheldPoseInput = (infoList: jsb.PoseInfo[]) => { + private _registerEvent (): void { + jsb.onHandheldPoseInput = (infoList: jsb.PoseInfo[]): void => { for (let i = 0; i < infoList.length; ++i) { const info = infoList[i]; this._updateNativePoseState(info); @@ -73,11 +73,11 @@ export class HandheldInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HandheldCallback, target?: any) { + public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _updateNativePoseState (info: jsb.PoseInfo) { + private _updateNativePoseState (info: jsb.PoseInfo): void { switch (info.code) { case 7: this._nativePoseState[Pose.AR_MOBILE] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; @@ -87,11 +87,11 @@ export class HandheldInputDevice { } } - private _initInputSource () { + private _initInputSource (): void { this._handheldPosition = new InputSourcePosition(); - this._handheldPosition.getValue = () => this._nativePoseState[Pose.AR_MOBILE].position; + this._handheldPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AR_MOBILE].position; this._handheldOrientation = new InputSourceOrientation(); - this._handheldOrientation.getValue = () => this._nativePoseState[Pose.AR_MOBILE].orientation; + this._handheldOrientation.getValue = (): Quat => this._nativePoseState[Pose.AR_MOBILE].orientation; } } diff --git a/pal/input/native/handle-input.ts b/pal/input/native/handle-input.ts index fed98fc4070..ebca8523ead 100644 --- a/pal/input/native/handle-input.ts +++ b/pal/input/native/handle-input.ts @@ -89,30 +89,30 @@ interface IAxisValue { } export class HandleInputDevice { - public get buttonNorth () { return this._buttonNorth; } - public get buttonEast () { return this._buttonEast; } - public get buttonWest () { return this._buttonWest; } - public get buttonSouth () { return this._buttonSouth; } - public get buttonTriggerLeft () { return this._buttonTriggerLeft; } - public get buttonTriggerRight () { return this._buttonTriggerRight; } - public get triggerLeft () { return this._triggerLeft; } - public get triggerRight () { return this._triggerRight; } - public get gripLeft () { return this._gripLeft; } - public get gripRight () { return this._gripRight; } - public get leftStick () { return this._leftStick; } - public get rightStick () { return this._rightStick; } - public get buttonLeftStick () { return this._buttonLeftStick; } - public get buttonRightStick () { return this._buttonRightStick; } - public get buttonOptions () { return this._buttonOptions; } - public get buttonStart () { return this._buttonStart; } - public get handLeftPosition () { return this._handLeftPosition; } - public get handLeftOrientation () { return this._handLeftOrientation; } - public get handRightPosition () { return this._handRightPosition; } - public get handRightOrientation () { return this._handRightOrientation; } - public get aimLeftPosition () { return this._aimLeftPosition; } - public get aimLeftOrientation () { return this._aimLeftOrientation; } - public get aimRightPosition () { return this._aimRightPosition; } - public get aimRightOrientation () { return this._aimRightOrientation; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth; } + public get buttonEast (): InputSourceButton { return this._buttonEast; } + public get buttonWest (): InputSourceButton { return this._buttonWest; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth; } + public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } + public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } + public get triggerLeft (): InputSourceButton { return this._triggerLeft; } + public get triggerRight (): InputSourceButton { return this._triggerRight; } + public get gripLeft (): InputSourceButton { return this._gripLeft; } + public get gripRight (): InputSourceButton { return this._gripRight; } + public get leftStick (): InputSourceStick { return this._leftStick; } + public get rightStick (): InputSourceStick { return this._rightStick; } + public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } + public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions; } + public get buttonStart (): InputSourceButton { return this._buttonStart; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -178,8 +178,8 @@ export class HandleInputDevice { this._registerEvent(); } - private _registerEvent () { - jsb.onHandleInput = (infoList: jsb.ControllerInfo[]) => { + private _registerEvent (): void { + jsb.onHandleInput = (infoList: jsb.ControllerInfo[]): void => { for (let i = 0; i < infoList.length; ++i) { const info = infoList[i]; this._updateNativeButtonState(info); @@ -187,7 +187,7 @@ export class HandleInputDevice { } }; - jsb.onHandlePoseInput = (infoList: jsb.PoseInfo[]) => { + jsb.onHandlePoseInput = (infoList: jsb.PoseInfo[]): void => { for (let i = 0; i < infoList.length; ++i) { const info = infoList[i]; this._updateNativePoseState(info); @@ -199,7 +199,7 @@ export class HandleInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HandleCallback, target?: any) { + public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } @@ -214,7 +214,7 @@ export class HandleInputDevice { } } - private _updateNativeButtonState (info: jsb.ControllerInfo) { + private _updateNativeButtonState (info: jsb.ControllerInfo): void { const { buttonInfoList, axisInfoList } = info; for (let i = 0; i < buttonInfoList.length; ++i) { const buttonInfo = buttonInfoList[i]; @@ -267,7 +267,7 @@ export class HandleInputDevice { } } - private _updateNativePoseState (info: jsb.PoseInfo) { + private _updateNativePoseState (info: jsb.PoseInfo): void { switch (info.code) { case 1: this._nativePoseState[Pose.HAND_LEFT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; @@ -286,76 +286,76 @@ export class HandleInputDevice { } } - private _initInputSource () { + private _initInputSource (): void { this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = () => this._nativeButtonState[Button.BUTTON_NORTH]; + this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH]; this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = () => this._nativeButtonState[Button.BUTTON_EAST]; + this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST]; this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = () => this._nativeButtonState[Button.BUTTON_WEST]; + this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST]; this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = () => this._nativeButtonState[Button.BUTTON_SOUTH]; + this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH]; this._buttonTriggerLeft = new InputSourceButton(); - this._buttonTriggerLeft.getValue = () => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT]; + this._buttonTriggerLeft.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT]; this._buttonTriggerRight = new InputSourceButton(); - this._buttonTriggerRight.getValue = () => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT]; + this._buttonTriggerRight.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT]; this._triggerLeft = new InputSourceButton(); - this._triggerLeft.getValue = () => this._nativeButtonState[Button.TRIGGER_LEFT]; + this._triggerLeft.getValue = (): number => this._nativeButtonState[Button.TRIGGER_LEFT]; this._triggerRight = new InputSourceButton(); - this._triggerRight.getValue = () => this._nativeButtonState[Button.TRIGGER_RIGHT]; + this._triggerRight.getValue = (): number => this._nativeButtonState[Button.TRIGGER_RIGHT]; this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = () => this._nativeButtonState[Button.GRIP_LEFT]; + this._gripLeft.getValue = (): number => this._nativeButtonState[Button.GRIP_LEFT]; this._gripRight = new InputSourceButton(); - this._gripRight.getValue = () => this._nativeButtonState[Button.GRIP_RIGHT]; + this._gripRight.getValue = (): number => this._nativeButtonState[Button.GRIP_RIGHT]; this._buttonLeftStick = new InputSourceButton(); - this._buttonLeftStick.getValue = () => this._nativeButtonState[Button.BUTTON_LEFT_STICK]; + this._buttonLeftStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_LEFT_STICK]; const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = () => this._nativeButtonState[Button.LEFT_STICK_UP]; + leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP]; const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = () => this._nativeButtonState[Button.LEFT_STICK_DOWN]; + leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN]; const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = () => this._nativeButtonState[Button.LEFT_STICK_LEFT]; + leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT]; const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = () => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; + leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); this._buttonRightStick = new InputSourceButton(); - this._buttonRightStick.getValue = () => this._nativeButtonState[Button.BUTTON_RIGHT_STICK]; + this._buttonRightStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_RIGHT_STICK]; const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_UP]; + rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP]; const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; + rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; + rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; + rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = () => this._nativeButtonState[Button.ROKID_MENU]; + this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.ROKID_MENU]; this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = () => this._nativeButtonState[Button.ROKID_START]; + this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START]; this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = () => this._nativePoseState[Pose.HAND_LEFT].position; + this._handLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.HAND_LEFT].position; this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = () => this._nativePoseState[Pose.HAND_LEFT].orientation; + this._handLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.HAND_LEFT].orientation; this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = () => this._nativePoseState[Pose.HAND_RIGHT].position; + this._handRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.HAND_RIGHT].position; this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = () => this._nativePoseState[Pose.HAND_RIGHT].orientation; + this._handRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.HAND_RIGHT].orientation; this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = () => this._nativePoseState[Pose.AIM_LEFT].position; + this._aimLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AIM_LEFT].position; this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = () => this._nativePoseState[Pose.AIM_LEFT].orientation; + this._aimLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.AIM_LEFT].orientation; this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = () => this._nativePoseState[Pose.AIM_RIGHT].position; + this._aimRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AIM_RIGHT].position; this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = () => this._nativePoseState[Pose.AIM_RIGHT].orientation; + this._aimRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.AIM_RIGHT].orientation; } } diff --git a/pal/input/native/hmd-input.ts b/pal/input/native/hmd-input.ts index 897114ab7f9..fb16ef72c74 100644 --- a/pal/input/native/hmd-input.ts +++ b/pal/input/native/hmd-input.ts @@ -44,12 +44,12 @@ interface IPoseValue { type NativePoseState = Record export class HMDInputDevice { - public get viewLeftPosition () { return this._viewLeftPosition; } - public get viewLeftOrientation () { return this._viewLeftOrientation; } - public get viewRightPosition () { return this._viewRightPosition; } - public get viewRightOrientation () { return this._viewRightOrientation; } - public get headMiddlePosition () { return this._headMiddlePosition; } - public get headMiddleOrientation () { return this._headMiddleOrientation; } + public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } + public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } + public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } + public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } + public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } + public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -71,8 +71,8 @@ export class HMDInputDevice { this._registerEvent(); } - private _registerEvent () { - jsb.onHMDPoseInput = (infoList: jsb.PoseInfo[]) => { + private _registerEvent (): void { + jsb.onHMDPoseInput = (infoList: jsb.PoseInfo[]): void => { for (let i = 0; i < infoList.length; ++i) { const info = infoList[i]; this._updateNativePoseState(info); @@ -84,11 +84,11 @@ export class HMDInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HMDCallback, target?: any) { + public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _updateNativePoseState (info: jsb.PoseInfo) { + private _updateNativePoseState (info: jsb.PoseInfo): void { switch (info.code) { case 0: this._nativePoseState[Pose.VIEW_LEFT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; @@ -104,20 +104,20 @@ export class HMDInputDevice { } } - private _initInputSource () { + private _initInputSource (): void { this._viewLeftPosition = new InputSourcePosition(); - this._viewLeftPosition.getValue = () => this._nativePoseState[Pose.VIEW_LEFT].position; + this._viewLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.VIEW_LEFT].position; this._viewLeftOrientation = new InputSourceOrientation(); - this._viewLeftOrientation.getValue = () => this._nativePoseState[Pose.VIEW_LEFT].orientation; + this._viewLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.VIEW_LEFT].orientation; this._viewRightPosition = new InputSourcePosition(); - this._viewRightPosition.getValue = () => this._nativePoseState[Pose.VIEW_RIGHT].position; + this._viewRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.VIEW_RIGHT].position; this._viewRightOrientation = new InputSourceOrientation(); - this._viewRightOrientation.getValue = () => this._nativePoseState[Pose.VIEW_RIGHT].orientation; + this._viewRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.VIEW_RIGHT].orientation; this._headMiddlePosition = new InputSourcePosition(); - this._headMiddlePosition.getValue = () => this._nativePoseState[Pose.HEAD_MIDDLE].position; + this._headMiddlePosition.getValue = (): Vec3 => this._nativePoseState[Pose.HEAD_MIDDLE].position; this._headMiddleOrientation = new InputSourceOrientation(); - this._headMiddleOrientation.getValue = () => this._nativePoseState[Pose.HEAD_MIDDLE].orientation; + this._headMiddleOrientation.getValue = (): Quat => this._nativePoseState[Pose.HEAD_MIDDLE].orientation; } } diff --git a/pal/input/native/keyboard-input.ts b/pal/input/native/keyboard-input.ts index ecdd6adb42f..c36375b7c6f 100644 --- a/pal/input/native/keyboard-input.ts +++ b/pal/input/native/keyboard-input.ts @@ -68,7 +68,7 @@ export class KeyboardInputSource { private _handleKeyboardUp: (event: jsb.KeyboardEvent) => void; constructor () { - this._handleKeyboardDown = (event: jsb.KeyboardEvent) => { + this._handleKeyboardDown = (event: jsb.KeyboardEvent): void => { const keyCode = getKeyCode(event); if (!this._keyStateMap[keyCode]) { const eventKeyDown = this._getInputEvent(event, InputEventType.KEY_DOWN); @@ -79,7 +79,7 @@ export class KeyboardInputSource { } this._keyStateMap[keyCode] = true; }; - this._handleKeyboardUp = (event: jsb.KeyboardEvent) => { + this._handleKeyboardUp = (event: jsb.KeyboardEvent): void => { const keyCode = getKeyCode(event); const eventKeyUp = this._getInputEvent(event, InputEventType.KEY_UP); this._keyStateMap[keyCode] = false; @@ -88,22 +88,22 @@ export class KeyboardInputSource { this._registerEvent(); } - public dispatchKeyboardDownEvent (nativeKeyboardEvent: jsb.KeyboardEvent) { this._handleKeyboardDown(nativeKeyboardEvent); } - public dispatchKeyboardUpEvent (nativeKeyboardEvent: jsb.KeyboardEvent) { this._handleKeyboardUp(nativeKeyboardEvent); } + public dispatchKeyboardDownEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { this._handleKeyboardDown(nativeKeyboardEvent); } + public dispatchKeyboardUpEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { this._handleKeyboardUp(nativeKeyboardEvent); } - private _registerEvent () { + private _registerEvent (): void { jsb.onKeyDown = this._handleKeyboardDown; jsb.onKeyUp = this._handleKeyboardUp; } - private _getInputEvent (event: jsb.KeyboardEvent, eventType: InputEventType) { + private _getInputEvent (event: jsb.KeyboardEvent, eventType: InputEventType): EventKeyboard { const keyCode = getKeyCode(event); const eventKeyboard = new EventKeyboard(keyCode, eventType); eventKeyboard.windowId = event.windowId; return eventKeyboard; } - public on (eventType: InputEventType, callback: KeyboardCallback, target?: any) { + public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/native/mouse-input.ts b/pal/input/native/mouse-input.ts index 1ccd64b5f7d..98237b4691c 100644 --- a/pal/input/native/mouse-input.ts +++ b/pal/input/native/mouse-input.ts @@ -53,10 +53,10 @@ export class MouseInputSource { this._windowManager = jsb.ISystemWindowManager.getInstance(); } - public dispatchMouseDownEvent (nativeMouseEvent: any) { this._handleMouseDown(nativeMouseEvent); } - public dispatchMouseMoveEvent (nativeMouseEvent: any) { this._handleMouseMove(nativeMouseEvent); } - public dispatchMouseUpEvent (nativeMouseEvent: any) { this._handleMouseUp(nativeMouseEvent); } - public dispatchScrollEvent (nativeMouseEvent: any) { this._boundedHandleMouseWheel(nativeMouseEvent); } + public dispatchMouseDownEvent (nativeMouseEvent: any): void { this._handleMouseDown(nativeMouseEvent); } + public dispatchMouseMoveEvent (nativeMouseEvent: any): void { this._handleMouseMove(nativeMouseEvent); } + public dispatchMouseUpEvent (nativeMouseEvent: any): void { this._handleMouseUp(nativeMouseEvent); } + public dispatchScrollEvent (nativeMouseEvent: any): void { this._boundedHandleMouseWheel(nativeMouseEvent); } private _getLocation (event: jsb.MouseEvent): Vec2 { const window = this._windowManager.getWindow(event.windowId); @@ -67,18 +67,18 @@ export class MouseInputSource { return new Vec2(x, y); } - private _registerEvent () { + private _registerEvent (): void { jsb.onMouseDown = this._handleMouseDown; jsb.onMouseMove = this._handleMouseMove; jsb.onMouseUp = this._handleMouseUp; jsb.onMouseWheel = this._boundedHandleMouseWheel; - jsb.onPointerlockChange = (value: boolean) => { + jsb.onPointerlockChange = (value: boolean): void => { this._pointLocked = value; }; } private _createCallback (eventType: InputEventType) { - return (mouseEvent: jsb.MouseEvent) => { + return (mouseEvent: jsb.MouseEvent): void => { const location = this._getLocation(mouseEvent); let button = mouseEvent.button; switch (eventType) { @@ -109,7 +109,7 @@ export class MouseInputSource { }; } - private _handleMouseWheel (mouseEvent: jsb.MouseWheelEvent) { + private _handleMouseWheel (mouseEvent: jsb.MouseWheelEvent): void { const eventType = InputEventType.MOUSE_WHEEL; const location = this._getLocation(mouseEvent); const button = mouseEvent.button; @@ -127,7 +127,7 @@ export class MouseInputSource { this._eventTarget.emit(eventType, eventMouse); } - public on (eventType: InputEventType, callback: MouseCallback, target?: any) { + public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/native/touch-input.ts b/pal/input/native/touch-input.ts index aeb1d539b8a..08fce870209 100644 --- a/pal/input/native/touch-input.ts +++ b/pal/input/native/touch-input.ts @@ -43,7 +43,7 @@ export class TouchInputSource { this._windowManager = jsb.ISystemWindowManager.getInstance(); } - private _registerEvent () { + private _registerEvent (): void { jsb.onTouchStart = this._createCallback(InputEventType.TOUCH_START); jsb.onTouchMove = this._createCallback(InputEventType.TOUCH_MOVE); jsb.onTouchEnd = this._createCallback(InputEventType.TOUCH_END); @@ -51,7 +51,7 @@ export class TouchInputSource { } private _createCallback (eventType: InputEventType) { - return (changedTouches: TouchList, windowId: number) => { + return (changedTouches: TouchList, windowId: number): void => { const handleTouches: Touch[] = []; const length = changedTouches.length; const windowSize = this._windowManager.getWindow(windowId).getViewSize(); @@ -87,7 +87,7 @@ export class TouchInputSource { return new Vec2(x, y); } - public on (eventType: InputEventType, callback: TouchCallback, target?: any) { + public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/touch-manager.ts b/pal/input/touch-manager.ts index 6585fd49237..6c4ec9a4bc2 100644 --- a/pal/input/touch-manager.ts +++ b/pal/input/touch-manager.ts @@ -87,7 +87,7 @@ class TouchManager { * @param touchID * @returns */ - public releaseTouch (touchID: number) { + public releaseTouch (touchID: number): void { if (!this._touchMap.has(touchID)) { return; } @@ -130,13 +130,13 @@ class TouchManager { * @param x The current location X * @param y The current location Y */ - private _updateTouch (touch: Touch, x: number, y: number) { + private _updateTouch (touch: Touch, x: number, y: number): void { touch.getLocation(tempVec2); touch.setPrevPoint(tempVec2); touch.setPoint(x, y); } - private _checkTouchMapSizeMoreThanMax (touchID: number) { + private _checkTouchMapSizeMoreThanMax (touchID: number): boolean { if (this._touchMap.has(touchID)) { return false; } diff --git a/pal/input/web/accelerometer-input.ts b/pal/input/web/accelerometer-input.ts index 04735a6f773..04a4d3cc1af 100644 --- a/pal/input/web/accelerometer-input.ts +++ b/pal/input/web/accelerometer-input.ts @@ -49,17 +49,17 @@ export class AccelerometerInputSource { this._didAccelerateFunc = this._didAccelerate.bind(this); } - private _registerEvent () { + private _registerEvent (): void { this._accelTimer = performance.now(); window.addEventListener(this._deviceEventName, this._didAccelerateFunc, false); } - private _unregisterEvent () { + private _unregisterEvent (): void { this._accelTimer = 0; window.removeEventListener(this._deviceEventName, this._didAccelerateFunc, false); } - private _didAccelerate (event: DeviceMotionEvent | DeviceOrientationEvent) { + private _didAccelerate (event: DeviceMotionEvent | DeviceOrientationEvent): void { const now = performance.now(); if (now - this._accelTimer < this._intervalInMileSeconds) { return; @@ -118,7 +118,7 @@ export class AccelerometerInputSource { this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration); } - public start () { + public start (): void { // for iOS 13+, safari if (window.DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function') { DeviceMotionEvent.requestPermission().then((response) => { @@ -130,13 +130,13 @@ export class AccelerometerInputSource { this._registerEvent(); } } - public stop () { + public stop (): void { this._unregisterEvent(); } - public setInterval (intervalInMileSeconds: number) { + public setInterval (intervalInMileSeconds: number): void { this._intervalInMileSeconds = intervalInMileSeconds; } - public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any) { + public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/input/web/gamepad-input.ts b/pal/input/web/gamepad-input.ts index 8b2a1b85d94..2b6f6561ccb 100644 --- a/pal/input/web/gamepad-input.ts +++ b/pal/input/web/gamepad-input.ts @@ -106,39 +106,39 @@ export class GamepadInputDevice { public static all: GamepadInputDevice[] = []; public static xr: (GamepadInputDevice | null) = null; - public get buttonNorth () { return this._buttonNorth; } - public get buttonEast () { return this._buttonEast; } - public get buttonWest () { return this._buttonWest; } - public get buttonSouth () { return this._buttonSouth; } - public get buttonL1 () { return this._buttonL1; } - public get buttonL2 () { return this._buttonL2; } - public get buttonL3 () { return this._buttonL3; } - public get buttonR1 () { return this._buttonR1; } - public get buttonR2 () { return this._buttonR2; } - public get buttonR3 () { return this._buttonR3; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth; } + public get buttonEast (): InputSourceButton { return this._buttonEast; } + public get buttonWest (): InputSourceButton { return this._buttonWest; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth; } + public get buttonL1 (): InputSourceButton { return this._buttonL1; } + public get buttonL2 (): InputSourceButton { return this._buttonL2; } + public get buttonL3 (): InputSourceButton { return this._buttonL3; } + public get buttonR1 (): InputSourceButton { return this._buttonR1; } + public get buttonR2 (): InputSourceButton { return this._buttonR2; } + public get buttonR3 (): InputSourceButton { return this._buttonR3; } // public get buttonTouchPad () { return this._buttonTouchPad; } // public get buttonHome () { return this._buttonHome; } - public get buttonShare () { return this._buttonShare; } - public get buttonOptions () { return this._buttonOptions; } - public get dpad () { return this._dpad; } - public get leftStick () { return this._leftStick; } - public get rightStick () { return this._rightStick; } - public get buttonStart () { return this._buttonStart; } - public get gripLeft () { return this._gripLeft; } - public get gripRight () { return this._gripRight; } - public get handLeftPosition () { return this._handLeftPosition; } - public get handLeftOrientation () { return this._handLeftOrientation; } - public get handRightPosition () { return this._handRightPosition; } - public get handRightOrientation () { return this._handRightOrientation; } - public get aimLeftPosition () { return this._aimLeftPosition; } - public get aimLeftOrientation () { return this._aimLeftOrientation; } - public get aimRightPosition () { return this._aimRightPosition; } - public get aimRightOrientation () { return this._aimRightOrientation; } - - public get deviceId () { + public get buttonShare (): InputSourceButton { return this._buttonShare; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions; } + public get dpad (): InputSourceDpad { return this._dpad; } + public get leftStick (): InputSourceStick { return this._leftStick; } + public get rightStick (): InputSourceStick { return this._rightStick; } + public get buttonStart (): InputSourceButton { return this._buttonStart; } + public get gripLeft (): InputSourceButton { return this._gripLeft; } + public get gripRight (): InputSourceButton { return this._gripRight; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } + + public get deviceId (): number { return this._deviceId; } - public get connected () { + public get connected (): boolean { return this._connected; } @@ -194,7 +194,7 @@ export class GamepadInputDevice { /** * @engineInternal */ - public static _init () { + public static _init (): void { if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) { return; } @@ -204,11 +204,11 @@ export class GamepadInputDevice { /** * @engineInternal */ - public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any) { + public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { GamepadInputDevice._eventTarget.on(eventType, cb, target); } - private static _removeInputDevice (id: number) { + private static _removeInputDevice (id: number): void { const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id); if (removeIndex === -1) { return; @@ -225,7 +225,7 @@ export class GamepadInputDevice { return device; } - private static _ensureDirectorDefined () { + private static _ensureDirectorDefined (): Promise { return new Promise((resolve) => { GamepadInputDevice._intervalId = setInterval(() => { if (legacyCC.director && legacyCC.Director) { @@ -237,7 +237,7 @@ export class GamepadInputDevice { }); } - private static _registerEvent () { + private static _registerEvent (): void { GamepadInputDevice._ensureDirectorDefined().then(() => { legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, GamepadInputDevice._scanGamepads); }).catch((e) => {}); @@ -254,7 +254,7 @@ export class GamepadInputDevice { }); } - private static _scanWebGamepads (devices: GamepadInputDevice[]) { + private static _scanWebGamepads (devices: GamepadInputDevice[]): void { const webGamepads = GamepadInputDevice._getWebGamePads(); if (!webGamepads) { return; @@ -301,7 +301,7 @@ export class GamepadInputDevice { GamepadInputDevice._cachedWebGamepads = webGamepads; } - private static _scanGamepads () { + private static _scanGamepads (): void { const devices: GamepadInputDevice[] = []; GamepadInputDevice._scanWebGamepads(devices); GamepadInputDevice._scanWebXRGamepads(devices); @@ -313,7 +313,7 @@ export class GamepadInputDevice { GamepadInputDevice._scanWebXRGamepadsPose(); } - private static _scanWebXRGamepads (devices: GamepadInputDevice[]) { + private static _scanWebXRGamepads (devices: GamepadInputDevice[]): void { const webxrGamepadMap = GamepadInputDevice._getWebXRGamepadMap(); if (!webxrGamepadMap) { // update cache @@ -363,7 +363,7 @@ export class GamepadInputDevice { GamepadInputDevice._cachedWebXRGamepadMap.set(XRRightHandedness, GamepadInputDevice._copyCacheGamepadValue(right)); } - private static checkGamepadChanged (currGamepad: (Gamepad | undefined), cachedGamepad: (IGamepadCacheInfo | undefined)) { + private static checkGamepadChanged (currGamepad: (Gamepad | undefined), cachedGamepad: (IGamepadCacheInfo | undefined)): boolean { if (!currGamepad && !cachedGamepad) { return false; } else if (!currGamepad || !cachedGamepad) { @@ -391,7 +391,7 @@ export class GamepadInputDevice { return false; } - private static _copyCacheGamepadValue (gamepad: Gamepad | undefined) { + private static _copyCacheGamepadValue (gamepad: Gamepad | undefined): IGamepadCacheInfo | undefined { if (!gamepad) { return undefined; } @@ -407,7 +407,7 @@ export class GamepadInputDevice { return cacheGamepad; } - private static _scanWebXRGamepadsPose () { + private static _scanWebXRGamepadsPose (): void { const infoList = globalThis.__globalXR?.webxrHandlePoseInfos as IPoseInfo[]; if (!infoList || !GamepadInputDevice.xr) { return; @@ -457,7 +457,7 @@ export class GamepadInputDevice { } } - private _updateWebPoseState (info: IPoseInfo) { + private _updateWebPoseState (info: IPoseInfo): void { if (info.code !== Pose.HAND_LEFT && info.code !== Pose.AIM_LEFT && info.code !== Pose.HAND_RIGHT && info.code !== Pose.AIM_RIGHT) { return; @@ -469,9 +469,9 @@ export class GamepadInputDevice { }; } - private _initInputSource () { + private _initInputSource (): void { this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = () => { + this._buttonNorth.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) { @@ -484,7 +484,7 @@ export class GamepadInputDevice { return 0; }; this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = () => { + this._buttonEast.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) { @@ -497,7 +497,7 @@ export class GamepadInputDevice { return 0; }; this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = () => { + this._buttonWest.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) { @@ -510,7 +510,7 @@ export class GamepadInputDevice { return 0; }; this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = () => { + this._buttonSouth.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) { @@ -524,13 +524,13 @@ export class GamepadInputDevice { }; this._buttonL1 = new InputSourceButton(); - this._buttonL1.getValue = () => { + this._buttonL1.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_L1].value; } return 0; }; this._buttonL2 = new InputSourceButton(); - this._buttonL2.getValue = () => { + this._buttonL2.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) { @@ -543,7 +543,7 @@ export class GamepadInputDevice { return 0; }; this._buttonL3 = new InputSourceButton(); - this._buttonL3.getValue = () => { + this._buttonL3.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad) { @@ -560,13 +560,13 @@ export class GamepadInputDevice { return 0; }; this._buttonR1 = new InputSourceButton(); - this._buttonR1.getValue = () => { + this._buttonR1.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_R1].value; } return 0; }; this._buttonR2 = new InputSourceButton(); - this._buttonR2.getValue = () => { + this._buttonR2.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) { @@ -579,7 +579,7 @@ export class GamepadInputDevice { return 0; }; this._buttonR3 = new InputSourceButton(); - this._buttonR3.getValue = () => { + this._buttonR3.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad) { @@ -609,38 +609,38 @@ export class GamepadInputDevice { // return 0; // }; this._buttonShare = new InputSourceButton(); - this._buttonShare.getValue = () => { + this._buttonShare.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_SHARE].value; } return 0; }; this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = () => { + this._buttonOptions.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_OPTIONS].value; } return 0; }; const dpadUp = new InputSourceButton(); - dpadUp.getValue = () => { + dpadUp.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_UP].value; } return 0; }; const dpadDown = new InputSourceButton(); - dpadDown.getValue = () => { + dpadDown.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_DOWN].value; } return 0; }; const dpadLeft = new InputSourceButton(); - dpadLeft.getValue = () => { + dpadLeft.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_LEFT].value; } return 0; }; const dpadRight = new InputSourceButton(); - dpadRight.getValue = () => { + dpadRight.getValue = (): number => { const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_RIGHT].value; } return 0; @@ -648,7 +648,7 @@ export class GamepadInputDevice { this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = () => { + leftStickUp.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad) { @@ -667,7 +667,7 @@ export class GamepadInputDevice { return 0; }; const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = () => { + leftStickDown.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad) { @@ -686,7 +686,7 @@ export class GamepadInputDevice { return 0; }; const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = () => { + leftStickLeft.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad) { @@ -705,7 +705,7 @@ export class GamepadInputDevice { return 0; }; const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = () => { + leftStickRight.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad) { @@ -726,7 +726,7 @@ export class GamepadInputDevice { this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = () => { + rightStickUp.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad) { @@ -745,7 +745,7 @@ export class GamepadInputDevice { return 0; }; const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = () => { + rightStickDown.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad) { @@ -764,7 +764,7 @@ export class GamepadInputDevice { return 0; }; const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = () => { + rightStickLeft.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad) { @@ -783,7 +783,7 @@ export class GamepadInputDevice { return 0; }; const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = () => { + rightStickRight.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad) { @@ -804,10 +804,10 @@ export class GamepadInputDevice { this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = () => 0; + this._buttonStart.getValue = (): number => 0; this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = () => { + this._gripLeft.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) { @@ -817,7 +817,7 @@ export class GamepadInputDevice { return 0; }; this._gripRight = new InputSourceButton(); - this._gripRight.getValue = () => { + this._gripRight.getValue = (): number => { if (this.deviceId === -1) { const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) { @@ -828,23 +828,23 @@ export class GamepadInputDevice { }; this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = () => this._webPoseState[Pose.HAND_LEFT].position; + this._handLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.HAND_LEFT].position; this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = () => this._webPoseState[Pose.HAND_LEFT].orientation; + this._handLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.HAND_LEFT].orientation; this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = () => this._webPoseState[Pose.HAND_RIGHT].position; + this._handRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.HAND_RIGHT].position; this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = () => this._webPoseState[Pose.HAND_RIGHT].orientation; + this._handRightOrientation.getValue = (): Quat => this._webPoseState[Pose.HAND_RIGHT].orientation; this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = () => this._webPoseState[Pose.AIM_LEFT].position; + this._aimLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.AIM_LEFT].position; this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = () => this._webPoseState[Pose.AIM_LEFT].orientation; + this._aimLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.AIM_LEFT].orientation; this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = () => this._webPoseState[Pose.AIM_RIGHT].position; + this._aimRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.AIM_RIGHT].position; this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = () => this._webPoseState[Pose.AIM_RIGHT].orientation; + this._aimRightOrientation.getValue = (): Quat => this._webPoseState[Pose.AIM_RIGHT].orientation; } } diff --git a/pal/input/web/handheld-input.ts b/pal/input/web/handheld-input.ts index bdfdf3bd565..0603dae3e2c 100644 --- a/pal/input/web/handheld-input.ts +++ b/pal/input/web/handheld-input.ts @@ -29,8 +29,8 @@ import { InputSourcePosition, InputSourceOrientation } from '../input-source'; import { Vec3, Quat } from '../../../cocos/core/math'; export class HandheldInputDevice { - public get handheldPosition () { return this._handheldPosition; } - public get handheldOrientation () { return this._handheldOrientation; } + public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } + public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -44,14 +44,14 @@ export class HandheldInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HandheldCallback, target?: any) { + public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _initInputSource () { + private _initInputSource (): void { this._handheldPosition = new InputSourcePosition(); - this._handheldPosition.getValue = () => Vec3.ZERO; + this._handheldPosition.getValue = (): Readonly => Vec3.ZERO; this._handheldOrientation = new InputSourceOrientation(); - this._handheldOrientation.getValue = () => Quat.IDENTITY; + this._handheldOrientation.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/web/handle-input.ts b/pal/input/web/handle-input.ts index 7d67bb6fd0b..d89608c3498 100644 --- a/pal/input/web/handle-input.ts +++ b/pal/input/web/handle-input.ts @@ -95,30 +95,30 @@ interface IAxisValue { type NativeButtonState = Record export class HandleInputDevice { - public get buttonNorth () { return this._buttonNorth; } - public get buttonEast () { return this._buttonEast; } - public get buttonWest () { return this._buttonWest; } - public get buttonSouth () { return this._buttonSouth; } - public get buttonTriggerLeft () { return this._buttonTriggerLeft; } - public get buttonTriggerRight () { return this._buttonTriggerRight; } - public get triggerLeft () { return this._triggerLeft; } - public get triggerRight () { return this._triggerRight; } - public get gripLeft () { return this._gripLeft; } - public get gripRight () { return this._gripRight; } - public get leftStick () { return this._leftStick; } - public get rightStick () { return this._rightStick; } - public get buttonLeftStick () { return this._buttonLeftStick; } - public get buttonRightStick () { return this._buttonRightStick; } - public get buttonOptions () { return this._buttonOptions; } - public get buttonStart () { return this._buttonStart; } - public get handLeftPosition () { return this._handLeftPosition; } - public get handLeftOrientation () { return this._handLeftOrientation; } - public get handRightPosition () { return this._handRightPosition; } - public get handRightOrientation () { return this._handRightOrientation; } - public get aimLeftPosition () { return this._aimLeftPosition; } - public get aimLeftOrientation () { return this._aimLeftOrientation; } - public get aimRightPosition () { return this._aimRightPosition; } - public get aimRightOrientation () { return this._aimRightOrientation; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth; } + public get buttonEast (): InputSourceButton { return this._buttonEast; } + public get buttonWest (): InputSourceButton { return this._buttonWest; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth; } + public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } + public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } + public get triggerLeft (): InputSourceButton { return this._triggerLeft; } + public get triggerRight (): InputSourceButton { return this._triggerRight; } + public get gripLeft (): InputSourceButton { return this._gripLeft; } + public get gripRight (): InputSourceButton { return this._gripRight; } + public get leftStick (): InputSourceStick { return this._leftStick; } + public get rightStick (): InputSourceStick { return this._rightStick; } + public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } + public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions; } + public get buttonStart (): InputSourceButton { return this._buttonStart; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } private _eventTarget: EventTarget = new EventTarget(); @@ -251,43 +251,43 @@ export class HandleInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HandleCallback, target?: any) { + public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _initInputSource () { + private _initInputSource (): void { this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = () => this._nativeButtonState[Button.BUTTON_NORTH]; + this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH]; this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = () => this._nativeButtonState[Button.BUTTON_EAST]; + this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST]; this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = () => this._nativeButtonState[Button.BUTTON_WEST]; + this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST]; this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = () => this._nativeButtonState[Button.BUTTON_SOUTH]; + this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH]; this._buttonTriggerLeft = new InputSourceButton(); - this._buttonTriggerLeft.getValue = () => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT]; + this._buttonTriggerLeft.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT]; this._buttonTriggerRight = new InputSourceButton(); - this._buttonTriggerRight.getValue = () => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT]; + this._buttonTriggerRight.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT]; this._triggerLeft = new InputSourceButton(); - this._triggerLeft.getValue = () => this._nativeButtonState[Button.TRIGGER_LEFT]; + this._triggerLeft.getValue = (): number => this._nativeButtonState[Button.TRIGGER_LEFT]; this._triggerRight = new InputSourceButton(); - this._triggerRight.getValue = () => this._nativeButtonState[Button.TRIGGER_RIGHT]; + this._triggerRight.getValue = (): number => this._nativeButtonState[Button.TRIGGER_RIGHT]; this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = () => this._nativeButtonState[Button.GRIP_LEFT]; + this._gripLeft.getValue = (): number => this._nativeButtonState[Button.GRIP_LEFT]; this._gripRight = new InputSourceButton(); - this._gripRight.getValue = () => this._nativeButtonState[Button.GRIP_RIGHT]; + this._gripRight.getValue = (): number => this._nativeButtonState[Button.GRIP_RIGHT]; this._buttonLeftStick = new InputSourceButton(); - this._buttonLeftStick.getValue = () => this._nativeButtonState[Button.BUTTON_LEFT_STICK]; + this._buttonLeftStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_LEFT_STICK]; const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = () => this._nativeButtonState[Button.LEFT_STICK_UP]; + leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP]; const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = () => this._nativeButtonState[Button.LEFT_STICK_DOWN]; + leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN]; const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = () => this._nativeButtonState[Button.LEFT_STICK_LEFT]; + leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT]; const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = () => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; + leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, @@ -296,15 +296,15 @@ export class HandleInputDevice { }); this._buttonRightStick = new InputSourceButton(); - this._buttonRightStick.getValue = () => this._nativeButtonState[Button.BUTTON_RIGHT_STICK]; + this._buttonRightStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_RIGHT_STICK]; const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_UP]; + rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP]; const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; + rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; + rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; + rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, @@ -313,28 +313,28 @@ export class HandleInputDevice { }); this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = () => this._nativeButtonState[Button.ROKID_MENU]; + this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.ROKID_MENU]; this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = () => this._nativeButtonState[Button.ROKID_START]; + this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START]; this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = () => Vec3.ZERO; + this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = () => Quat.IDENTITY; + this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = () => Vec3.ZERO; + this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = () => Quat.IDENTITY; + this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = () => Vec3.ZERO; + this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = () => Quat.IDENTITY; + this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = () => Vec3.ZERO; + this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = () => Quat.IDENTITY; + this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/web/hmd-input.ts b/pal/input/web/hmd-input.ts index 1897804ad6e..442815dc8a5 100644 --- a/pal/input/web/hmd-input.ts +++ b/pal/input/web/hmd-input.ts @@ -50,12 +50,12 @@ interface IPoseInfo { type WebPoseState = Record export class HMDInputDevice { - public get viewLeftPosition () { return this._viewLeftPosition; } - public get viewLeftOrientation () { return this._viewLeftOrientation; } - public get viewRightPosition () { return this._viewRightPosition; } - public get viewRightOrientation () { return this._viewRightOrientation; } - public get headMiddlePosition () { return this._headMiddlePosition; } - public get headMiddleOrientation () { return this._headMiddleOrientation; } + public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } + public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } + public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } + public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } + public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } + public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } private _eventTarget: EventTarget = new EventTarget(); private _intervalId = -1; @@ -78,7 +78,7 @@ export class HMDInputDevice { this._registerEvent(); } - private _ensureDirectorDefined () { + private _ensureDirectorDefined (): Promise { return new Promise((resolve) => { this._intervalId = setInterval(() => { if (legacyCC.director && legacyCC.Director) { @@ -90,13 +90,13 @@ export class HMDInputDevice { }); } - private _registerEvent () { + private _registerEvent (): void { this._ensureDirectorDefined().then(() => { legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, this._scanHmd, this); }).catch((e) => {}); } - private _scanHmd () { + private _scanHmd (): void { const infoList = globalThis.__globalXR?.webxrHmdPoseInfos as IPoseInfo[]; if (!infoList) { return; @@ -112,11 +112,11 @@ export class HMDInputDevice { /** * @engineInternal */ - public _on (eventType: InputEventType, callback: HMDCallback, target?: any) { + public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _updateWebPoseState (info: IPoseInfo) { + private _updateWebPoseState (info: IPoseInfo): void { if (info.code !== Pose.VIEW_LEFT && info.code !== Pose.VIEW_RIGHT && info.code !== Pose.HEAD_MIDDLE) { return; } @@ -127,20 +127,20 @@ export class HMDInputDevice { }; } - private _initInputSource () { + private _initInputSource (): void { this._viewLeftPosition = new InputSourcePosition(); - this._viewLeftPosition.getValue = () => this._webPoseState[Pose.VIEW_LEFT].position; + this._viewLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.VIEW_LEFT].position; this._viewLeftOrientation = new InputSourceOrientation(); - this._viewLeftOrientation.getValue = () => this._webPoseState[Pose.VIEW_LEFT].orientation; + this._viewLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.VIEW_LEFT].orientation; this._viewRightPosition = new InputSourcePosition(); - this._viewRightPosition.getValue = () => this._webPoseState[Pose.VIEW_RIGHT].position; + this._viewRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.VIEW_RIGHT].position; this._viewRightOrientation = new InputSourceOrientation(); - this._viewRightOrientation.getValue = () => this._webPoseState[Pose.VIEW_RIGHT].orientation; + this._viewRightOrientation.getValue = (): Quat => this._webPoseState[Pose.VIEW_RIGHT].orientation; this._headMiddlePosition = new InputSourcePosition(); - this._headMiddlePosition.getValue = () => this._webPoseState[Pose.HEAD_MIDDLE].position; + this._headMiddlePosition.getValue = (): Vec3 => this._webPoseState[Pose.HEAD_MIDDLE].position; this._headMiddleOrientation = new InputSourceOrientation(); - this._headMiddleOrientation.getValue = () => this._webPoseState[Pose.HEAD_MIDDLE].orientation; + this._headMiddleOrientation.getValue = (): Quat => this._webPoseState[Pose.HEAD_MIDDLE].orientation; } } diff --git a/pal/input/web/keyboard-input.ts b/pal/input/web/keyboard-input.ts index e023b2c0e57..b69c763af0a 100644 --- a/pal/input/web/keyboard-input.ts +++ b/pal/input/web/keyboard-input.ts @@ -39,26 +39,26 @@ export class KeyboardInputSource { this._registerEvent(); } - public dispatchKeyboardDownEvent (nativeKeyboardEvent: KeyboardEvent) { this._handleKeyboardDown(nativeKeyboardEvent); } - public dispatchKeyboardUpEvent (nativeKeyboardEvent: KeyboardEvent) { this._handleKeyboardUp(nativeKeyboardEvent); } + public dispatchKeyboardDownEvent (nativeKeyboardEvent: KeyboardEvent): void { this._handleKeyboardDown(nativeKeyboardEvent); } + public dispatchKeyboardUpEvent (nativeKeyboardEvent: KeyboardEvent): void { this._handleKeyboardUp(nativeKeyboardEvent); } - public on (eventType: InputEventType, callback: KeyboardCallback, target?: any) { + public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } - private _registerEvent () { + private _registerEvent (): void { const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement; canvas?.addEventListener('keydown', this._handleKeyboardDown.bind(this)); canvas?.addEventListener('keyup', this._handleKeyboardUp.bind(this)); } - private _getInputEvent (event: any, eventType: InputEventType) { + private _getInputEvent (event: any, eventType: InputEventType): EventKeyboard { const keyCode = getKeyCode(event.code); const eventKeyboard = new EventKeyboard(keyCode, eventType); return eventKeyboard; } - private _handleKeyboardDown (event: KeyboardEvent) { + private _handleKeyboardDown (event: KeyboardEvent): void { event.stopPropagation(); event.preventDefault(); if (!event.repeat) { @@ -70,7 +70,7 @@ export class KeyboardInputSource { } } - private _handleKeyboardUp (event: KeyboardEvent) { + private _handleKeyboardUp (event: KeyboardEvent): void { const inputEvent = this._getInputEvent(event, InputEventType.KEY_UP); event.stopPropagation(); event.preventDefault(); diff --git a/pal/input/web/mouse-input.ts b/pal/input/web/mouse-input.ts index 48f26675d15..f5948d28b69 100644 --- a/pal/input/web/mouse-input.ts +++ b/pal/input/web/mouse-input.ts @@ -60,12 +60,12 @@ export class MouseInputSource { } } - public dispatchMouseDownEvent (nativeMouseEvent: any) { this._handleMouseDown(nativeMouseEvent); } - public dispatchMouseMoveEvent (nativeMouseEvent: any) { this._handleMouseMove(nativeMouseEvent); } - public dispatchMouseUpEvent (nativeMouseEvent: any) { this._handleMouseUp(nativeMouseEvent); } - public dispatchScrollEvent (nativeMouseEvent: WheelEvent) { this._handleMouseWheel(nativeMouseEvent); } + public dispatchMouseDownEvent (nativeMouseEvent: any): void { this._handleMouseDown(nativeMouseEvent); } + public dispatchMouseMoveEvent (nativeMouseEvent: any): void { this._handleMouseMove(nativeMouseEvent); } + public dispatchMouseUpEvent (nativeMouseEvent: any): void { this._handleMouseUp(nativeMouseEvent); } + public dispatchScrollEvent (nativeMouseEvent: WheelEvent): void { this._handleMouseWheel(nativeMouseEvent); } - public on (eventType: InputEventType, callback: MouseCallback, target?: any) { + public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } @@ -88,7 +88,7 @@ export class MouseInputSource { return new Vec2(x, y); } - private _registerEvent () { + private _registerEvent (): void { // register mouse down event window.addEventListener('mousedown', () => { this._isPressed = true; @@ -108,8 +108,8 @@ export class MouseInputSource { } // To be removed in the future. - private _registerPointerLockEvent () { - const lockChangeAlert = () => { + private _registerPointerLockEvent (): void { + const lockChangeAlert = (): void => { const canvas = this._canvas; // NOTE: mozPointerLockElement is not a standard web interface if (document.pointerLockElement === canvas || (document as any).mozPointerLockElement === canvas) { @@ -127,7 +127,7 @@ export class MouseInputSource { } private _createCallback (eventType: InputEventType) { - return (mouseEvent: MouseEvent) => { + return (mouseEvent: MouseEvent): void => { const location = this._getLocation(mouseEvent); const { button, buttons } = mouseEvent; let targetButton = button; @@ -172,7 +172,7 @@ export class MouseInputSource { }; } - private _handleMouseWheel (mouseEvent: WheelEvent) { + private _handleMouseWheel (mouseEvent: WheelEvent): void { const eventType = InputEventType.MOUSE_WHEEL; const location = this._getLocation(mouseEvent); const button = mouseEvent.button; diff --git a/pal/input/web/touch-input.ts b/pal/input/web/touch-input.ts index 76eda012b1b..ae90109d852 100644 --- a/pal/input/web/touch-input.ts +++ b/pal/input/web/touch-input.ts @@ -51,7 +51,7 @@ export class TouchInputSource { } } - private _registerEvent () { + private _registerEvent (): void { // IDEA: need to register on window ? this._canvas?.addEventListener('touchstart', this._createCallback(InputEventType.TOUCH_START)); this._canvas?.addEventListener('touchmove', this._createCallback(InputEventType.TOUCH_MOVE)); @@ -60,7 +60,7 @@ export class TouchInputSource { } private _createCallback (eventType: InputEventType) { - return (event: TouchEvent) => { + return (event: TouchEvent): void => { const canvasRect = this._getCanvasRect(); const handleTouches: Touch[] = []; const length = event.changedTouches.length; @@ -123,7 +123,7 @@ export class TouchInputSource { return new Vec2(x, y); } - public on (eventType: InputEventType, callback: TouchCallback, target?: any) { + public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { this._eventTarget.on(eventType, callback, target); } } diff --git a/pal/minigame/alipay.ts b/pal/minigame/alipay.ts index e1094493a73..6f074d9ef52 100644 --- a/pal/minigame/alipay.ts +++ b/pal/minigame/alipay.ts @@ -56,22 +56,22 @@ Object.defineProperty(minigame, 'orientation', { // #region TouchEvent // my.onTouchStart register touch event listner on body // need to register on canvas -minigame.onTouchStart = function (cb) { +minigame.onTouchStart = function (cb): void { window.canvas.addEventListener('touchstart', (res) => { cb && cb(res); }); }; -minigame.onTouchMove = function (cb) { +minigame.onTouchMove = function (cb): void { window.canvas.addEventListener('touchmove', (res) => { cb && cb(res); }); }; -minigame.onTouchEnd = function (cb) { +minigame.onTouchEnd = function (cb): void { window.canvas.addEventListener('touchend', (res) => { cb && cb(res); }); }; -minigame.onTouchCancel = function (cb) { +minigame.onTouchCancel = function (cb): void { window.canvas.addEventListener('touchcancel', (res) => { cb && cb(res); }); @@ -91,11 +91,11 @@ minigame.createInnerAudioContext = function (): InnerAudioContext { // #region Accelerometer let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { minigame.offAccelerometerChange(); // onAccelerometerChange would start accelerometer // so we won't call this method here - _accelerometerCb = (res: any) => { + _accelerometerCb = (res: any): void => { let x = res.x; let y = res.y; if (minigame.isLandscape) { @@ -113,13 +113,13 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { cb(resClone); }; }; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { if (_accelerometerCb) { my.offAccelerometerChange(_accelerometerCb); _accelerometerCb = undefined; } }; -minigame.startAccelerometer = function (res: any) { +minigame.startAccelerometer = function (res: any): void { if (_accelerometerCb) { my.onAccelerometerChange(_accelerometerCb); } else { @@ -127,14 +127,14 @@ minigame.startAccelerometer = function (res: any) { console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on alipay platform'); } }; -minigame.stopAccelerometer = function (res: any) { +minigame.stopAccelerometer = function (res: any): void { // my.stopAccelerometer() is not implemented. minigame.offAccelerometerChange(); }; // #endregion Accelerometer // #region SafeArea -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { console.warn('getSafeArea is not supported on this platform'); const systemInfo = minigame.getSystemInfoSync(); return { diff --git a/pal/minigame/baidu.ts b/pal/minigame/baidu.ts index 2714cc0377d..81955833f15 100644 --- a/pal/minigame/baidu.ts +++ b/pal/minigame/baidu.ts @@ -55,11 +55,11 @@ Object.defineProperty(minigame, 'orientation', { // #region Accelerometer let _customAccelerometerCb: AccelerometerChangeCallback | undefined; let _innerAccelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { // swan.offAccelerometerChange() is not supported. // so we can only register AccelerometerChange callback, but can't unregister. if (!_innerAccelerometerCb) { - _innerAccelerometerCb = (res: any) => { + _innerAccelerometerCb = (res: any): void => { let x = res.x; let y = res.y; if (minigame.isLandscape) { @@ -82,7 +82,7 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { } _customAccelerometerCb = cb; }; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { // swan.offAccelerometerChange() is not supported. _customAccelerometerCb = undefined; }; @@ -96,7 +96,7 @@ minigame.createInnerAudioContext = createInnerAudioContextPolyfill(swan, { }); // #region SafeArea -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { console.warn('getSafeArea is not supported on this platform'); const systemInfo = minigame.getSystemInfoSync(); return { diff --git a/pal/minigame/bytedance.ts b/pal/minigame/bytedance.ts index 109245c2f95..b8148703f7c 100644 --- a/pal/minigame/bytedance.ts +++ b/pal/minigame/bytedance.ts @@ -38,7 +38,7 @@ minigame.tt.getAudioContext = tt.getAudioContext?.bind(tt); // #region SystemInfo let systemInfo = minigame.getSystemInfoSync(); -minigame.getSystemInfoSync = () => systemInfo; +minigame.getSystemInfoSync = (): SystemInfo => systemInfo; minigame.onWindowResize?.(() => { systemInfo = minigame.getSystemInfoSync(); }); @@ -64,11 +64,11 @@ Object.defineProperty(minigame, 'orientation', { // #region Accelerometer let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { minigame.offAccelerometerChange(); // onAccelerometerChange would start accelerometer // so we won't call this method here - _accelerometerCb = (res: any) => { + _accelerometerCb = (res: any): void => { let x = res.x; let y = res.y; if (minigame.isLandscape) { @@ -86,13 +86,13 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { cb(resClone); }; }; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { if (_accelerometerCb) { tt.offAccelerometerChange(_accelerometerCb); _accelerometerCb = undefined; } }; -minigame.startAccelerometer = function (res: any) { +minigame.startAccelerometer = function (res: any): void { if (_accelerometerCb) { tt.onAccelerometerChange(_accelerometerCb); } @@ -109,7 +109,7 @@ minigame.createInnerAudioContext = createInnerAudioContextPolyfill(tt, { // #region SafeArea // FIX_ME: wrong safe area when orientation is landscape left -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { const locSystemInfo = tt.getSystemInfoSync() as SystemInfo; let { top, left, right } = locSystemInfo.safeArea; const { bottom, width, height } = locSystemInfo.safeArea; diff --git a/pal/minigame/runtime.ts b/pal/minigame/runtime.ts index fc94fea28d0..3c2336b0c57 100644 --- a/pal/minigame/runtime.ts +++ b/pal/minigame/runtime.ts @@ -72,7 +72,7 @@ if (LINKSURE || COCOSPLAY) { // update cached system info cachedSystemInfo = ral.getSystemInfoSync() as SystemInfo; }); - minigame.getSystemInfoSync = function () { + minigame.getSystemInfoSync = function (): SystemInfo { return cachedSystemInfo; }; } @@ -82,9 +82,9 @@ if (LINKSURE || COCOSPLAY) { let _customAccelerometerCb: AccelerometerChangeCallback | undefined; let _innerAccelerometerCb: AccelerometerChangeCallback | undefined; let _needHandleAccelerometerCb = false; -minigame.onAccelerometerChange = function (cb) { +minigame.onAccelerometerChange = function (cb): void { if (!_innerAccelerometerCb) { - _innerAccelerometerCb = (res) => { + _innerAccelerometerCb = (res): void => { if (!_needHandleAccelerometerCb) { return; } @@ -108,7 +108,7 @@ minigame.onAccelerometerChange = function (cb) { _needHandleAccelerometerCb = true; _customAccelerometerCb = cb; }; -minigame.offAccelerometerChange = function (cb) { +minigame.offAccelerometerChange = function (cb): void { _needHandleAccelerometerCb = false; _customAccelerometerCb = undefined; }; @@ -132,7 +132,7 @@ if (COCOSPLAY) { } // #region SafeArea -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { const locSystemInfo = ral.getSystemInfoSync() as SystemInfo; if (locSystemInfo.safeArea) { return locSystemInfo.safeArea; diff --git a/pal/minigame/taobao.ts b/pal/minigame/taobao.ts index e2cb4929755..4c8948a3079 100644 --- a/pal/minigame/taobao.ts +++ b/pal/minigame/taobao.ts @@ -43,7 +43,7 @@ cloneObject(minigame, my); // #region SystemInfo const systemInfo = minigame.getSystemInfoSync(); systemInfo.language = languageMap[systemInfo.language] || systemInfo.language; -minigame.getSystemInfoSync = () => systemInfo; +minigame.getSystemInfoSync = (): SystemInfo => systemInfo; minigame.isDevTool = my.isIDE; @@ -74,7 +74,7 @@ Object.defineProperty(minigame, 'orientation', { }); // #endregion SystemInfo -function detectLandscapeSupport () { +function detectLandscapeSupport (): void { const locSysInfo = minigame.getSystemInfoSync(); if (typeof locSysInfo.deviceOrientation === 'string' && locSysInfo.deviceOrientation.startsWith('landscape')) { if (versionCompare(locSysInfo.version, '10.15.10') < 0) { @@ -102,7 +102,7 @@ minigame.createInnerAudioContext = function (): InnerAudioContext { // #region Audio // #region Font -minigame.loadFont = function (url) { +minigame.loadFont = function (url): string { // my.loadFont crash when url is not in user data path return 'Arial'; }; @@ -110,11 +110,11 @@ minigame.loadFont = function (url) { // #region Accelerometer let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { minigame.offAccelerometerChange(); // onAccelerometerChange would start accelerometer // so we won't call this method here - _accelerometerCb = (res: any) => { + _accelerometerCb = (res: any): void => { let x: number = res.x; let y: number = res.y; if (minigame.isLandscape) { @@ -131,13 +131,13 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { cb(resClone); }; }; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { if (_accelerometerCb) { my.offAccelerometerChange(_accelerometerCb); _accelerometerCb = undefined; } }; -minigame.startAccelerometer = function (res: any) { +minigame.startAccelerometer = function (res: any): void { if (_accelerometerCb) { my.onAccelerometerChange(_accelerometerCb); } else { @@ -145,7 +145,7 @@ minigame.startAccelerometer = function (res: any) { console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on taobao platform'); } }; -minigame.stopAccelerometer = function (res: any) { +minigame.stopAccelerometer = function (res: any): void { // my.stopAccelerometer() is not implemented. minigame.offAccelerometerChange(); }; @@ -153,7 +153,7 @@ minigame.stopAccelerometer = function (res: any) { // #region SafeArea // It should be a value that is not multiplied by dpr -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { const systemInfo = minigame.getSystemInfoSync(); if (typeof systemInfo.safeArea !== 'undefined') { return systemInfo.safeArea; @@ -177,7 +177,7 @@ if (!my.isIDE) { const locCanvas = $global.screencanvas; if (locCanvas) { const originalGetContext = locCanvas.getContext.bind(locCanvas); - locCanvas.getContext = function (name, param) { + locCanvas.getContext = function (name, param): any { if (typeof name === 'string' && typeof param === 'object' && name.startsWith('webgl')) { Object.assign(param, { enable_flip_y_after_read_pixels: false }); const gl = originalGetContext(name, param); @@ -192,7 +192,7 @@ if (!my.isIDE) { } let hasAdapter = false; -function adapterGL (gl) { +function adapterGL (gl): void { if (hasAdapter) { return; } hasAdapter = true; @@ -204,7 +204,7 @@ function adapterGL (gl) { // Android return value: undefined. iOS return value: {ID: -1}. if (my.getSystemInfoSync().platform.toLocaleLowerCase() === 'ios') { const originalGetUniformLocation = gl.getUniformLocation.bind(gl); - gl.getUniformLocation = function (program, name) { + gl.getUniformLocation = function (program, name): any { const glLoc = originalGetUniformLocation(program, name); if (glLoc && glLoc.ID === -1) { return undefined; diff --git a/pal/minigame/taobao_minigame.ts b/pal/minigame/taobao_minigame.ts index 1942d15899f..6e3a20a6f00 100644 --- a/pal/minigame/taobao_minigame.ts +++ b/pal/minigame/taobao_minigame.ts @@ -43,7 +43,7 @@ cloneObject(minigame, my); // #region SystemInfo const systemInfo = minigame.getSystemInfoSync(); systemInfo.language = languageMap[systemInfo.language] || systemInfo.language; -minigame.getSystemInfoSync = () => systemInfo; +minigame.getSystemInfoSync = (): SystemInfo => systemInfo; minigame.isDevTool = my.isIDE; @@ -75,7 +75,7 @@ Object.defineProperty(minigame, 'orientation', { // #endregion SystemInfo // eslint-disable-next-line func-names -function detectLandscapeSupport () { +function detectLandscapeSupport (): void { const locSysInfo = minigame.getSystemInfoSync(); if (typeof locSysInfo.deviceOrientation === 'string' && locSysInfo.deviceOrientation.startsWith('landscape')) { if (versionCompare(locSysInfo.version, '10.15.10') < 0) { @@ -105,7 +105,7 @@ minigame.createInnerAudioContext = function (): InnerAudioContext { // #region Font // eslint-disable-next-line func-names -minigame.loadFont = function (url) { +minigame.loadFont = function (url): string { // my.loadFont crash when url is not in user data path return 'Arial'; }; @@ -114,11 +114,11 @@ minigame.loadFont = function (url) { // #region Accelerometer let _accelerometerCb: AccelerometerChangeCallback | undefined; // eslint-disable-next-line func-names -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { minigame.offAccelerometerChange(); // onAccelerometerChange would start accelerometer // so we won't call this method here - _accelerometerCb = (res: any) => { + _accelerometerCb = (res: any): void => { let x: number = res.x; let y: number = res.y; if (minigame.isLandscape) { @@ -136,14 +136,14 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { }; }; // eslint-disable-next-line func-names -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { if (_accelerometerCb) { my.offAccelerometerChange(_accelerometerCb); _accelerometerCb = undefined; } }; // eslint-disable-next-line func-names -minigame.startAccelerometer = function (res: any) { +minigame.startAccelerometer = function (res: any): void { if (_accelerometerCb) { my.onAccelerometerChange(_accelerometerCb); } else { @@ -152,7 +152,7 @@ minigame.startAccelerometer = function (res: any) { } }; // eslint-disable-next-line func-names -minigame.stopAccelerometer = function (res: any) { +minigame.stopAccelerometer = function (res: any): void { // my.stopAccelerometer() is not implemented. minigame.offAccelerometerChange(); }; @@ -160,7 +160,7 @@ minigame.stopAccelerometer = function (res: any) { // #region SafeArea // It should be a value that is not multiplied by dpr -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): any { const systemInfo = my.getWindowInfoSync(); if (typeof systemInfo.safeArea !== 'undefined') { // eslint-disable-next-line @typescript-eslint/no-unsafe-return @@ -186,7 +186,7 @@ if (!my.isIDE) { if (locCanvas) { const originalGetContext = locCanvas.getContext.bind(locCanvas); // eslint-disable-next-line func-names - locCanvas.getContext = function (name, param) { + locCanvas.getContext = function (name, param): any { if (typeof name === 'string' && typeof param === 'object' && name.startsWith('webgl')) { Object.assign(param, { enable_flip_y_after_read_pixels: false }); const gl = originalGetContext(name, param); @@ -201,7 +201,7 @@ if (!my.isIDE) { } let hasAdapter = false; -function adapterGL (gl) { +function adapterGL (gl): void { if (hasAdapter) { return; } hasAdapter = true; @@ -214,7 +214,7 @@ function adapterGL (gl) { if (my.getSystemInfoSync().platform.toLocaleLowerCase() === 'ios') { const originalGetUniformLocation = gl.getUniformLocation.bind(gl); // eslint-disable-next-line func-names - gl.getUniformLocation = function (program, name) { + gl.getUniformLocation = function (program, name): any { const glLoc = originalGetUniformLocation(program, name); if (glLoc && glLoc.ID === -1) { return undefined; diff --git a/pal/minigame/wechat.ts b/pal/minigame/wechat.ts index f4408bd9d48..5049cf6163a 100644 --- a/pal/minigame/wechat.ts +++ b/pal/minigame/wechat.ts @@ -44,10 +44,10 @@ minigame.wx.onWheel = wx.onWheel?.bind(wx); // #region SystemInfo let _cachedSystemInfo: SystemInfo = wx.getSystemInfoSync(); -function testAndUpdateSystemInfoCache (testAmount: number, testInterval: number) { +function testAndUpdateSystemInfoCache (testAmount: number, testInterval: number): void { let successfullyTestTimes = 0; let intervalTimer: number | null = null; - function testCachedSystemInfo () { + function testCachedSystemInfo (): void { const currentSystemInfo = wx.getSystemInfoSync() as SystemInfo; if (_cachedSystemInfo.screenWidth === currentSystemInfo.screenWidth && _cachedSystemInfo.screenHeight === currentSystemInfo.screenHeight) { if (++successfullyTestTimes >= testAmount && intervalTimer !== null) { @@ -67,7 +67,7 @@ minigame.onWindowResize?.(() => { // update cached system info _cachedSystemInfo = wx.getSystemInfoSync() as SystemInfo; }); -minigame.getSystemInfoSync = function () { +minigame.getSystemInfoSync = function (): SystemInfo { return _cachedSystemInfo; }; @@ -106,11 +106,11 @@ Object.defineProperty(minigame, 'orientation', { // #region Accelerometer let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { minigame.offAccelerometerChange(); // onAccelerometerChange would start accelerometer // so we won't call this method here - _accelerometerCb = (res: any) => { + _accelerometerCb = (res: any): void => { let x = res.x; let y = res.y; if (minigame.isLandscape) { @@ -128,13 +128,13 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { cb(resClone); }; }; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { if (_accelerometerCb) { wx.offAccelerometerChange(_accelerometerCb); _accelerometerCb = undefined; } }; -minigame.startAccelerometer = function (res: any) { +minigame.startAccelerometer = function (res: any): void { if (_accelerometerCb) { wx.onAccelerometerChange(_accelerometerCb); } @@ -151,7 +151,7 @@ minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, { // #region SafeArea // FIX_ME: wrong safe area when orientation is landscape left -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { const locSystemInfo = wx.getSystemInfoSync() as SystemInfo; return locSystemInfo.safeArea; }; @@ -165,7 +165,7 @@ if (systemInfo.platform === 'windows' && versionCompare(systemInfo.SDKVersion, ' if (locCanvas) { const webglRC = locCanvas.getContext('webgl'); const originalUseProgram = webglRC.useProgram.bind(webglRC); - webglRC.useProgram = function (program) { + webglRC.useProgram = function (program): void { if (program) { originalUseProgram(program); } diff --git a/pal/minigame/wechat_mini_program.ts b/pal/minigame/wechat_mini_program.ts index ed8884d9dc5..8abf6e2d0c4 100644 --- a/pal/minigame/wechat_mini_program.ts +++ b/pal/minigame/wechat_mini_program.ts @@ -47,10 +47,10 @@ minigame.wx.onWheel = wx.onWheel?.bind(wx); // #region SystemInfo let _cachedSystemInfo: SystemInfo = wx.getSystemInfoSync(); // @ts-expect-error TODO: move into minigame.d.ts -minigame.testAndUpdateSystemInfoCache = function (testAmount: number, testInterval: number) { +minigame.testAndUpdateSystemInfoCache = function (testAmount: number, testInterval: number): void { let successfullyTestTimes = 0; let intervalTimer: number | null = null; - function testCachedSystemInfo () { + function testCachedSystemInfo (): void { const currentSystemInfo = wx.getSystemInfoSync() as SystemInfo; if (_cachedSystemInfo.screenWidth === currentSystemInfo.screenWidth && _cachedSystemInfo.screenHeight === currentSystemInfo.screenHeight) { if (++successfullyTestTimes >= testAmount && intervalTimer !== null) { @@ -66,11 +66,11 @@ minigame.testAndUpdateSystemInfoCache = function (testAmount: number, testInterv }; // @ts-expect-error TODO: update when view resize minigame.testAndUpdateSystemInfoCache(10, 500); -minigame.onWindowResize?.(() => { +minigame.onWindowResize?.((): void => { // update cached system info _cachedSystemInfo = wx.getSystemInfoSync() as SystemInfo; }); -minigame.getSystemInfoSync = function () { +minigame.getSystemInfoSync = function (): SystemInfo { return _cachedSystemInfo; }; @@ -109,11 +109,11 @@ Object.defineProperty(minigame, 'orientation', { // #region Accelerometer let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { minigame.offAccelerometerChange(); // onAccelerometerChange would start accelerometer // so we won't call this method here - _accelerometerCb = (res: any) => { + _accelerometerCb = (res: any): void => { let x = res.x; let y = res.y; if (minigame.isLandscape) { @@ -131,13 +131,13 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { cb(resClone); }; }; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { if (_accelerometerCb) { wx.offAccelerometerChange(_accelerometerCb); _accelerometerCb = undefined; } }; -minigame.startAccelerometer = function (res: any) { +minigame.startAccelerometer = function (res: any): void { if (_accelerometerCb) { wx.onAccelerometerChange(_accelerometerCb); } @@ -154,7 +154,7 @@ minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, { // #region SafeArea // FIX_ME: wrong safe area when orientation is landscape left -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { const locSystemInfo = wx.getSystemInfoSync() as SystemInfo; return locSystemInfo.safeArea; }; @@ -167,7 +167,7 @@ if (systemInfo.platform === 'windows' && versionCompare(systemInfo.SDKVersion, ' if (locCanvas) { const webglRC = locCanvas.getContext('webgl'); const originalUseProgram = webglRC.useProgram.bind(webglRC); - webglRC.useProgram = function (program) { + webglRC.useProgram = function (program): void { if (program) { originalUseProgram(program); } @@ -178,7 +178,7 @@ if (systemInfo.platform === 'windows' && versionCompare(systemInfo.SDKVersion, ' // HACK: adapt gl.texSubImage2D: gl.texSubImage2D do not support 2d canvas in wechat miniprogram const gl = getApp().GameGlobal.canvas.getContext('webgl'); const oldTexSubImage2D = gl.texSubImage2D; -gl.texSubImage2D = function (...args) { +gl.texSubImage2D = function (...args): void { if (args.length === 7) { const canvas = args[6]; if (typeof canvas.type !== 'undefined' && canvas.type === 'canvas') { diff --git a/pal/minigame/xiaomi.ts b/pal/minigame/xiaomi.ts index 712c12df6ac..9a07a7a7b46 100644 --- a/pal/minigame/xiaomi.ts +++ b/pal/minigame/xiaomi.ts @@ -54,16 +54,16 @@ Object.defineProperty(minigame, 'orientation', { // #endregion SystemInfo // #region TouchEvent -minigame.onTouchStart = function (cb) { +minigame.onTouchStart = function (cb): void { window.canvas.ontouchstart = cb; }; -minigame.onTouchMove = function (cb) { +minigame.onTouchMove = function (cb): void { window.canvas.ontouchmove = cb; }; -minigame.onTouchEnd = function (cb) { +minigame.onTouchEnd = function (cb): void { window.canvas.ontouchend = cb; }; -minigame.onTouchCancel = function (cb) { +minigame.onTouchCancel = function (cb): void { window.canvas.ontouchcancel = cb; }; // #endregion TouchEvent @@ -77,11 +77,11 @@ minigame.onTouchCancel = function (cb) { // #region Accelerometer let _customAccelerometerCb: AccelerometerChangeCallback | undefined; let _innerAccelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { +minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { // qg.offAccelerometerChange() is not supported. // so we can only register AccelerometerChange callback, but can't unregister. if (!_innerAccelerometerCb) { - _innerAccelerometerCb = (res: any) => { + _innerAccelerometerCb = (res: any): void => { let x = res.x; let y = res.y; if (minigame.isLandscape) { @@ -105,7 +105,7 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) { } _customAccelerometerCb = cb; }; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) { +minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { // qg.offAccelerometerChange() is not supported. _customAccelerometerCb = undefined; }; @@ -119,12 +119,12 @@ minigame.createInnerAudioContext = createInnerAudioContextPolyfill(qg, { onSeek: false, }); const originalCreateInnerAudioContext = minigame.createInnerAudioContext; -minigame.createInnerAudioContext = function () { +minigame.createInnerAudioContext = function (): InnerAudioContext { const audioContext = originalCreateInnerAudioContext.call(minigame); const originalStop = audioContext.stop; Object.defineProperty(audioContext, 'stop', { configurable: true, - value () { + value (): void { // NOTE: stop won't seek to 0 when audio is paused on Xiaomi platform. audioContext.seek(0); originalStop.call(audioContext); @@ -135,7 +135,7 @@ minigame.createInnerAudioContext = function () { // #endregion InnerAudioContext // #region SafeArea -minigame.getSafeArea = function () { +minigame.getSafeArea = function (): SafeArea { console.warn('getSafeArea is not supported on this platform'); const systemInfo = minigame.getSystemInfoSync(); return { diff --git a/pal/pacer/pacer-minigame.ts b/pal/pacer/pacer-minigame.ts index 63cb01fda94..841e014ec3e 100644 --- a/pal/pacer/pacer-minigame.ts +++ b/pal/pacer/pacer-minigame.ts @@ -32,7 +32,7 @@ export class Pacer { private _targetFrameRate = 60; private _isPlaying = false; constructor () { - this._updateCallback = () => { + this._updateCallback = (): void => { if (this._isPlaying) { this._rafHandle = requestAnimationFrame(this._updateCallback); } diff --git a/pal/pacer/pacer-native.ts b/pal/pacer/pacer-native.ts index e81b27b9c6e..15ef3c2b100 100644 --- a/pal/pacer/pacer-native.ts +++ b/pal/pacer/pacer-native.ts @@ -32,7 +32,7 @@ export class Pacer { private _isPlaying = false; private _updateCallback: () => void; constructor () { - this._updateCallback = () => { + this._updateCallback = (): void => { if (this._isPlaying) { this._rafHandle = requestAnimationFrame(this._updateCallback); } diff --git a/pal/pacer/pacer-web.ts b/pal/pacer/pacer-web.ts index 5ee0cf76f0a..b006fbcd329 100644 --- a/pal/pacer/pacer-web.ts +++ b/pal/pacer/pacer-web.ts @@ -85,7 +85,7 @@ export class Pacer { start (): void { if (this._isPlaying) return; - const updateCallback = () => { + const updateCallback = (): void => { if (this._isPlaying) { this._stHandle = this._stTime(updateCallback); } @@ -108,7 +108,7 @@ export class Pacer { this._frameCount = 0; } - _handleRAF = () => { + _handleRAF = (): void => { const elapseTime = performance.now() - this._startTime; const elapseFrame = Math.floor(elapseTime / this._frameTime); if (elapseFrame <= this._frameCount) { @@ -125,7 +125,7 @@ export class Pacer { } }; - private _stTime (callback: () => void) { + private _stTime (callback: () => void): number { if (EDITOR || this._rAF === undefined || globalThis.__globalXR?.isWebXR) { const currTime = performance.now(); const elapseTime = Math.max(0, currTime - this._startTime); @@ -136,7 +136,7 @@ export class Pacer { return this._rAF.call(window, this._handleRAF); } - private _ctTime (id: number | undefined) { + private _ctTime (id: number | undefined): void { if (EDITOR || this._cAF === undefined || globalThis.__globalXR?.isWebXR) { clearTimeout(id); } else if (id) { diff --git a/pal/screen-adapter/minigame/screen-adapter.ts b/pal/screen-adapter/minigame/screen-adapter.ts index e82975e389f..77d10f3bc57 100644 --- a/pal/screen-adapter/minigame/screen-adapter.ts +++ b/pal/screen-adapter/minigame/screen-adapter.ts @@ -65,7 +65,7 @@ class ScreenAdapter extends EventTarget { return false; } - public get devicePixelRatio () { + public get devicePixelRatio (): number { const sysInfo = minigame.getSystemInfoSync(); return sysInfo.pixelRatio; } @@ -90,12 +90,12 @@ class ScreenAdapter extends EventTarget { warnID(1221); } - public get resolution () { + public get resolution (): Size { const windowSize = this.windowSize; const resolutionScale = this.resolutionScale; return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale); } - public get resolutionScale () { + public get resolutionScale (): number { return this._resolutionScale; } public set resolutionScale (value: number) { @@ -163,7 +163,7 @@ class ScreenAdapter extends EventTarget { } } - public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void) { + public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer; this._cbToUpdateFrameBuffer(); } diff --git a/pal/screen-adapter/native/screen-adapter.ts b/pal/screen-adapter/native/screen-adapter.ts index 0ec2675d221..0e0056104e5 100644 --- a/pal/screen-adapter/native/screen-adapter.ts +++ b/pal/screen-adapter/native/screen-adapter.ts @@ -71,7 +71,7 @@ class ScreenAdapter extends EventTarget { return false; } - public get devicePixelRatio () { + public get devicePixelRatio (): number { return jsb.device.getDevicePixelRatio() || 1; } @@ -91,12 +91,12 @@ class ScreenAdapter extends EventTarget { console.warn('Setting window size is not supported yet.'); } - public get resolution () { + public get resolution (): Size { const windowSize = this.windowSize; const resolutionScale = this.resolutionScale; return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale); } - public get resolutionScale () { + public get resolutionScale (): number { return this._resolutionScale; } public set resolutionScale (v: number) { @@ -155,7 +155,7 @@ class ScreenAdapter extends EventTarget { this._registerEvent(); } - public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void) { + public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer; if (!EDITOR) { this._cbToUpdateFrameBuffer(); @@ -169,14 +169,14 @@ class ScreenAdapter extends EventTarget { return Promise.reject(new Error('exit fullscreen has not been supported yet on this platform.')); } - private _registerEvent () { - jsb.onResize = (event: jsb.WindowEvent) => { + private _registerEvent (): void { + jsb.onResize = (event: jsb.WindowEvent): void => { if (event.width === 0 || event.height === 0) return; // TODO: remove this function calling window.resize(event.width / this.devicePixelRatio, event.height / this.devicePixelRatio); this.emit('window-resize', event.width, event.height, event.windowId); }; - jsb.onOrientationChanged = (event) => { + jsb.onOrientationChanged = (event): void => { this.emit('orientation-change'); }; } diff --git a/pal/screen-adapter/web/screen-adapter.ts b/pal/screen-adapter/web/screen-adapter.ts index a34295a62f5..86590be5ddf 100644 --- a/pal/screen-adapter/web/screen-adapter.ts +++ b/pal/screen-adapter/web/screen-adapter.ts @@ -95,7 +95,7 @@ class ScreenAdapter extends EventTarget { return !!document[this._fn.fullscreenElement]; } - public get devicePixelRatio () { + public get devicePixelRatio (): number { // TODO: remove the down sampling operation in DPR after supporting resolutionScale return Math.min(window.devicePixelRatio ?? 1, 2); } @@ -115,12 +115,12 @@ class ScreenAdapter extends EventTarget { this._resizeFrame(this._convertToSizeInCssPixels(size)); } - public get resolution () { + public get resolution (): Size { const windowSize = this.windowSize; const resolutionScale = this.resolutionScale; return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale); } - public get resolutionScale () { + public get resolutionScale (): number { return this._resolutionScale; } public set resolutionScale (v: number) { @@ -227,7 +227,7 @@ class ScreenAdapter extends EventTarget { 'msfullscreenerror', ], ]; - private get _windowSizeInCssPixels () { + private get _windowSizeInCssPixels (): Size { if (TEST) { return new Size(window.innerWidth, window.innerHeight); } @@ -323,7 +323,7 @@ class ScreenAdapter extends EventTarget { this._registerEvent(); } - public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void) { + public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer; this.orientation = orientationMap[options.configOrientation]; this._exactFitScreen = options.exactFitScreen; @@ -369,33 +369,33 @@ class ScreenAdapter extends EventTarget { }); } - private _registerEvent () { - document.addEventListener(this._fn.fullscreenerror, () => { + private _registerEvent (): void { + document.addEventListener(this._fn.fullscreenerror, (): void => { this._onFullscreenError?.(); }); - window.addEventListener('resize', () => { + window.addEventListener('resize', (): void => { if (!this.handleResizeEvent) { return; } this._resizeFrame(); }); if (typeof window.matchMedia === 'function') { - const updateDPRChangeListener = () => { + const updateDPRChangeListener = (): void => { const dpr = window.devicePixelRatio; // NOTE: some browsers especially on iPhone doesn't support MediaQueryList - window.matchMedia(`(resolution: ${dpr}dppx)`)?.addEventListener?.('change', () => { + window.matchMedia(`(resolution: ${dpr}dppx)`)?.addEventListener?.('change', (): void => { this.emit('window-resize', this.windowSize.width, this.windowSize.height); updateDPRChangeListener(); }, { once: true }); }; updateDPRChangeListener(); } - window.addEventListener('orientationchange', () => { + window.addEventListener('orientationchange', (): void => { if (this._orientationChangeTimeoutId !== -1) { clearTimeout(this._orientationChangeTimeoutId); } - this._orientationChangeTimeoutId = setTimeout(() => { + this._orientationChangeTimeoutId = setTimeout((): void => { if (!this.handleResizeEvent) { return; } @@ -410,7 +410,7 @@ class ScreenAdapter extends EventTarget { this.emit('fullscreen-change', this.windowSize.width, this.windowSize.height); }); } - private _convertToSizeInCssPixels (size: Size) { + private _convertToSizeInCssPixels (size: Size): Size { const clonedSize = size.clone(); const dpr = this.devicePixelRatio; clonedSize.width /= dpr; @@ -422,7 +422,7 @@ class ScreenAdapter extends EventTarget { * The frame size may be from screen size or an external editor options by setting screen.windowSize. * @param sizeInCssPixels you need to specify this size when the windowType is SubFrame. */ - private _resizeFrame (sizeInCssPixels?: Size) { + private _resizeFrame (sizeInCssPixels?: Size): void { if (!this._gameFrame) { return; } @@ -462,7 +462,7 @@ class ScreenAdapter extends EventTarget { this._updateContainer(); } - private _getFullscreenTarget () { + private _getFullscreenTarget (): HTMLElement | undefined { const windowType = this._windowType; if (windowType === WindowType.Fullscreen) { return document[this._fn.fullscreenElement] as HTMLElement; @@ -496,7 +496,7 @@ class ScreenAdapter extends EventTarget { } }); } - private _updateFrameState () { + private _updateFrameState (): void { const orientation = this.orientation; const width = window.innerWidth; const height = window.innerHeight; @@ -504,7 +504,7 @@ class ScreenAdapter extends EventTarget { this.isFrameRotated = systemInfo.isMobile && ((isBrowserLandscape && orientation === Orientation.PORTRAIT) || (!isBrowserLandscape && orientation === Orientation.LANDSCAPE)); } - private _updateContainer () { + private _updateContainer (): void { if (!this._gameContainer) { warnID(9201); return; diff --git a/pal/system-info/minigame/system-info.ts b/pal/system-info/minigame/system-info.ts index 5bd516f8a51..9e25280f29d 100644 --- a/pal/system-info/minigame/system-info.ts +++ b/pal/system-info/minigame/system-info.ts @@ -86,7 +86,7 @@ class SystemInfo extends EventTarget { this.isBrowser = false; // init isLittleEndian - this.isLittleEndian = (() => { + this.isLittleEndian = ((): boolean => { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true); // Int16Array uses the platform's endianness. @@ -176,15 +176,15 @@ class SystemInfo extends EventTarget { } try { const img = document.createElement('img'); - const timer = setTimeout(() => { + const timer = setTimeout((): void => { resolve(false); }, 500); - img.onload = function onload () { + img.onload = function onload (): void { clearTimeout(timer); const result = (img.width > 0) && (img.height > 0); resolve(result); }; - img.onerror = function onerror (err) { + img.onerror = function onerror (err): void { clearTimeout(timer); if (DEBUG) { console.warn('Create Webp image failed, message: '.concat(err.toString())); @@ -198,16 +198,16 @@ class SystemInfo extends EventTarget { }); } - private _registerEvent () { - minigame.onHide(() => { + private _registerEvent (): void { + minigame.onHide((): void => { this.emit('hide'); }); - minigame.onShow(() => { + minigame.onShow((): void => { this.emit('show'); }); } - private _setFeature (feature: Feature, value: boolean) { + private _setFeature (feature: Feature, value: boolean): boolean { return this._featureMap[feature] = value; } @@ -243,7 +243,7 @@ class SystemInfo extends EventTarget { } } - public close () { + public close (): void { minigame.exitMiniProgram?.(); } } diff --git a/pal/system-info/native/system-info.ts b/pal/system-info/native/system-info.ts index e892819783d..4b2b4dfab2f 100644 --- a/pal/system-info/native/system-info.ts +++ b/pal/system-info/native/system-info.ts @@ -91,7 +91,7 @@ class SystemInfo extends EventTarget { this.isMobile = this.platform === Platform.ANDROID || this.platform === Platform.IOS || this.platform === Platform.OHOS || this.platform === Platform.OPENHARMONY; // init isLittleEndian - this.isLittleEndian = (() => { + this.isLittleEndian = ((): boolean => { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true); // Int16Array uses the platform's endianness. @@ -140,19 +140,19 @@ class SystemInfo extends EventTarget { this._registerEvent(); } - private _registerEvent () { - jsb.onPause = () => { + private _registerEvent (): void { + jsb.onPause = (): void => { this.emit('hide'); }; - jsb.onResume = () => { + jsb.onResume = (): void => { this.emit('show'); }; - jsb.onClose = () => { + jsb.onClose = (): void => { this.emit('close'); }; } - private _setFeature (feature: Feature, value: boolean) { + private _setFeature (feature: Feature, value: boolean): boolean { return this._featureMap[feature] = value; } @@ -184,11 +184,11 @@ class SystemInfo extends EventTarget { __restartVM(); } - public close () { + public close (): void { __close(); } - public exit () { + public exit (): void { __exit(); } } diff --git a/pal/system-info/web/system-info.ts b/pal/system-info/web/system-info.ts index 2c2b8423e68..138e1bc4cfe 100644 --- a/pal/system-info/web/system-info.ts +++ b/pal/system-info/web/system-info.ts @@ -69,7 +69,7 @@ class SystemInfo extends EventTarget { } // init isLittleEndian - this.isLittleEndian = (() => { + this.isLittleEndian = ((): boolean => { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true); // Int16Array uses the platform's endianness. @@ -199,7 +199,7 @@ class SystemInfo extends EventTarget { // NOTE: xr is not totally supported on web const supportXR = typeof (navigator as any).xr !== 'undefined'; // refer https://stackoverflow.com/questions/47879864/how-can-i-check-if-a-browser-supports-webassembly - const supportWasm = (() => { + const supportWasm = ((): boolean => { // NOTE: safari on iOS 15.4 and MacOS 15.4 has some wasm memory issue, can not use wasm for bullet const isSafari_15_4 = (this.os === OS.IOS || this.os === OS.OSX) && /(OS 15_4)|(Version\/15.4)/.test(window.navigator.userAgent); if (isSafari_15_4) { @@ -262,7 +262,7 @@ class SystemInfo extends EventTarget { return Promise.resolve(); } - private _registerEvent () { + private _registerEvent (): void { let hiddenPropName: string; if (typeof document.hidden !== 'undefined') { hiddenPropName = 'hidden'; @@ -277,14 +277,14 @@ class SystemInfo extends EventTarget { } let hidden = false; - const onHidden = () => { + const onHidden = (): void => { if (!hidden) { hidden = true; this.emit('hide'); } }; // In order to adapt the most of platforms the onshow API. - const onShown = (arg0?, arg1?, arg2?, arg3?, arg4?) => { + const onShown = (arg0?, arg1?, arg2?, arg3?, arg4?): void => { if (hidden) { hidden = false; this.emit('show', arg0, arg1, arg2, arg3, arg4); @@ -330,7 +330,7 @@ class SystemInfo extends EventTarget { } } - private _setFeature (feature: Feature, value: boolean) { + private _setFeature (feature: Feature, value: boolean): boolean { return this._featureMap[feature] = value; } @@ -373,7 +373,7 @@ class SystemInfo extends EventTarget { } } - public close () { + public close (): void { this.emit('close'); window.close(); } diff --git a/pal/utils.ts b/pal/utils.ts index 3d0c14e0ce6..95198ad2b46 100644 --- a/pal/utils.ts +++ b/pal/utils.ts @@ -29,7 +29,7 @@ import { EDITOR } from 'internal:constants'; * @param targetObject Usually it's specified as the minigame module. * @param originObj Original minigame environment such as `wx`, `swan` etc. */ -export function cloneObject (targetObject: any, originObj: any) { +export function cloneObject (targetObject: any, originObj: any): void { Object.keys(originObj).forEach((key) => { if (typeof originObj[key] === 'function') { targetObject[key] = originObj[key].bind(originObj); @@ -51,7 +51,7 @@ type InnerAudioContextPolyfillConfig = { * @returns A polyfilled createInnerAudioContext method. */ export function createInnerAudioContextPolyfill (minigameEnv: any, polyfillConfig: InnerAudioContextPolyfillConfig, isAsynchronous = false) { - return () => { + return (): InnerAudioContext => { const audioContext: InnerAudioContext = minigameEnv.createInnerAudioContext(); // add polyfill if onPlay method doesn't work this platform @@ -205,7 +205,7 @@ export function setTimeoutRAF (callback: (...args: any[]) => void, delay: number return setTimeout(callback, delay, ...args); } - const handleRAF = () => { + const handleRAF = (): void => { if (performance.now() - start < delay) { raf(handleRAF); } else { @@ -221,7 +221,7 @@ export function setTimeoutRAF (callback: (...args: any[]) => void, delay: number * @param id A numeric ID that represents the timer to be canceled. * @returns Nothing. */ -export function clearTimeoutRAF (id) { +export function clearTimeoutRAF (id): void { const caf = cancelAnimationFrame || window.cancelAnimationFrame || window.cancelRequestAnimationFrame From 8f0070d164869b36d4421101e6788f1f2d44b90f Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Tue, 13 Jun 2023 18:28:46 +0800 Subject: [PATCH 002/232] [ci skip][AUTO]: Automated code generating update: 5ea295c1664096367bac233df6b24b4c9522262b (#15421) (#15423) Co-authored-by: cocos-robot --- native/cocos/cocos-version.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/native/cocos/cocos-version.h b/native/cocos/cocos-version.h index b5de9b87801..fe63a574d6b 100644 --- a/native/cocos/cocos-version.h +++ b/native/cocos/cocos-version.h @@ -25,9 +25,9 @@ THE SOFTWARE. #define COCOS_MAJOR_VERSION 3 #define COCOS_MINJOR_VERSION 8 -#define COCOS_PATCH_VERSION 0 -#define COCOS_VERSION_STRING "3.8.0" +#define COCOS_PATCH_VERSION 1 +#define COCOS_VERSION_STRING "3.8.1" #define COCOS_VERSION_DEFINED 1 -#define COCOS_VERSION 30800 +#define COCOS_VERSION 30801 // #define COCOS_PRE_RELEASE "release" From b8a96f0080bf1bdd5053df273455cb6d59f82a3c Mon Sep 17 00:00:00 2001 From: PP Date: Wed, 14 Jun 2023 11:33:00 +0800 Subject: [PATCH 003/232] fix type in debug.ts (#15426) * fix type in debug.ts --- cocos/2d/components/ui-mesh-renderer.ts | 2 +- cocos/2d/framework/ui-renderer.ts | 2 +- cocos/animation/animation-clip.ts | 5 +- .../value-proxy-factories/uniform.ts | 4 +- .../asset-manager/editor-path-replace.ts | 2 +- cocos/core/data/class.ts | 5 +- cocos/core/data/decorators/property.ts | 6 +- cocos/core/platform/debug.ts | 98 ++++++++----------- cocos/core/scheduler.ts | 12 +-- cocos/core/utils/js-typed.ts | 26 +++-- cocos/game/director.ts | 2 +- .../platform/physics-contact-listener.ts | 2 +- cocos/render-scene/core/pass.ts | 2 +- cocos/rendering/custom/executor.ts | 2 +- cocos/rendering/custom/web-pipeline.ts | 18 ++-- cocos/scene-graph/component.ts | 2 +- cocos/tiledmap/tmx-xml-parser.ts | 5 +- 17 files changed, 97 insertions(+), 98 deletions(-) diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index a2ffa25cd24..9542a49abbd 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -268,7 +268,7 @@ export class UIMeshRenderer extends Component { */ get renderEntity (): RenderEntity { if (DEBUG) { - assert(this._renderEntity, 'this._renderEntity should not be invalid'); + assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid'); } return this._renderEntity; } diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 32a7b11ac33..440fedc6424 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -291,7 +291,7 @@ export class UIRenderer extends Renderer { */ get renderEntity (): RenderEntity { if (DEBUG) { - assert(this._renderEntity, 'this._renderEntity should not be invalid'); + assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid'); } return this._renderEntity; } diff --git a/cocos/animation/animation-clip.ts b/cocos/animation/animation-clip.ts index 3854de50d4b..2df73f911e3 100644 --- a/cocos/animation/animation-clip.ts +++ b/cocos/animation/animation-clip.ts @@ -197,8 +197,7 @@ export class AnimationClip extends Asset { * @zh 动画包含的事件数据。 * @en Associated event data. */ - get events (): AnimationClip.IEvent[] - { + get events (): AnimationClip.IEvent[] { return this._events; } @@ -399,7 +398,7 @@ export class AnimationClip extends Asset { warnID( 3937, this.name, - (context.target instanceof Node) ? context.target.name : context.target, + ((context.target instanceof Node) ? context.target.name : context.target) as string, ); } return trackTarget ?? undefined; diff --git a/cocos/animation/value-proxy-factories/uniform.ts b/cocos/animation/value-proxy-factories/uniform.ts index 779560b0db4..540d0e5969c 100644 --- a/cocos/animation/value-proxy-factories/uniform.ts +++ b/cocos/animation/value-proxy-factories/uniform.ts @@ -75,7 +75,7 @@ export class UniformProxyFactory implements IValueProxyFactory { public forTarget (target: unknown): IValueProxy | undefined { if (!(target instanceof Material)) { - warnID(3940, target); + warnID(3940, target as string); return undefined; } @@ -101,7 +101,7 @@ export class UniformProxyFactory implements IValueProxyFactory { if (type < Type.SAMPLER1D) { const realHandle = channelIndex === undefined ? handle : pass.getHandle(uniformName, channelIndex, Type.FLOAT); if (!realHandle) { - warnID(3943, target.name, passIndex, uniformName, channelIndex); + warnID(3943, target.name, passIndex, uniformName, channelIndex!); return undefined; } if (isUniformArray(pass, uniformName)) { diff --git a/cocos/asset/asset-manager/editor-path-replace.ts b/cocos/asset/asset-manager/editor-path-replace.ts index ae5172088b4..970b855315a 100644 --- a/cocos/asset/asset-manager/editor-path-replace.ts +++ b/cocos/asset/asset-manager/editor-path-replace.ts @@ -88,7 +88,7 @@ if ((EDITOR || PREVIEW) && !TEST) { let previewServer = ''; if (NATIVE) { previewServer = settings.querySettings(Settings.Category.PATH, 'previewServer') || ''; - assert(previewServer); + assert(Boolean(previewServer)); } text = await fetchText(`${previewServer}/query-extname/${uuid}`) as string; } diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index 4d230d13bfd..e10f10fa83d 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -75,6 +75,7 @@ function defineProp (cls, className, propName, val): void { if (DEV) { // check base prototype to avoid name collision if (CCClass.getInheritanceChain(cls) + // eslint-disable-next-line no-prototype-builtins .some((x) => x.prototype.hasOwnProperty(propName))) { errorID(3637, className, propName, className); return; @@ -277,7 +278,7 @@ function declareProperties (cls, className, properties, baseClass): void { } const attrs = attributeUtils.getClassAttrs(cls); - cls.__values__ = cls.__props__.filter((prop) => attrs[`${prop + DELIMETER}serializable`] !== false); + cls.__values__ = cls.__props__.filter((prop) => attrs[`${prop}${DELIMETER}serializable`] !== false); } export function CCClass (options: { @@ -310,7 +311,7 @@ export function CCClass (options: { if (js.isChildClassOf(base, legacyCC.Component)) { legacyCC.Component._registerEditorProps(cls, editor); } else if (DEV) { - warnID(3623, name); + warnID(3623, name!); } } diff --git a/cocos/core/data/decorators/property.ts b/cocos/core/data/decorators/property.ts index 7647adcd758..b42a34200d5 100644 --- a/cocos/core/data/decorators/property.ts +++ b/cocos/core/data/decorators/property.ts @@ -207,7 +207,7 @@ function mergePropertyOptions ( const errorProps = getSubDict(cache, 'errorProps'); if (!errorProps[(propertyKey as string)]) { errorProps[(propertyKey as string)] = true; - warnID(3655, propertyKey, getClassName(ctor), propertyKey, propertyKey); + warnID(3655, propertyKey as string, getClassName(ctor), propertyKey as string, propertyKey as string); } } if ((descriptorOrInitializer as BabelPropertyDecoratorDescriptor).get) { @@ -219,7 +219,7 @@ function mergePropertyOptions ( } else { // Target property is non-accessor if (DEV && (propertyRecord.get || propertyRecord.set)) { // Specify "accessor options" for non-accessor property is forbidden. - errorID(3655, propertyKey, getClassName(ctor), propertyKey, propertyKey); + errorID(3655, propertyKey as string, getClassName(ctor), propertyKey as string, propertyKey as string); return; } @@ -234,7 +234,7 @@ function mergePropertyOptions ( if ((EDITOR && !window.Build) || TEST) { // eslint-disable-next-line no-prototype-builtins if (!fullOptions && options && options.hasOwnProperty('default')) { - warnID(3653, propertyKey, getClassName(ctor)); + warnID(3653, propertyKey as string, getClassName(ctor)); } } } diff --git a/cocos/core/platform/debug.ts b/cocos/core/platform/debug.ts index 7d56a958265..24afa7496f8 100644 --- a/cocos/core/platform/debug.ts +++ b/cocos/core/platform/debug.ts @@ -22,7 +22,6 @@ THE SOFTWARE. */ -/* eslint-disable no-console */ import { EDITOR, JSB, DEV, DEBUG } from 'internal:constants'; import debugInfos from '../../../DebugInfos'; import { legacyCC, ccwindow } from '../global-exports'; @@ -31,6 +30,8 @@ const ccdocument = ccwindow.document; const ERROR_MAP_URL = 'https://github.com/cocos-creator/engine/blob/develop/EngineErrorMap.md'; +export type StringSubstitution = number | string; + // The html element displays log in web page (DebugMode.INFO_FOR_WEB_PAGE) let logList: HTMLTextAreaElement | null = null; @@ -40,7 +41,7 @@ let ccWarn = ccLog; let ccError = ccLog; -let ccAssert = (condition: any, message?: any, ...optionalParams: any[]): void => { +let ccAssert = (condition: boolean, message?: string, ...optionalParams: StringSubstitution[]): void => { if (!condition) { console.log(`ASSERT: ${formatString(message, ...optionalParams)}`); } @@ -49,58 +50,46 @@ let ccAssert = (condition: any, message?: any, ...optionalParams: any[]): void = let ccDebug = ccLog; /** - * @en Format a string. - * @zh 格式化字符串。 - * @param message @zh 包含零个或多个需要替换的JavaScript字符串。@en JavaScript objects to replace substitution strings in msg. - * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. + * Constructs a string from a sequence of js object arguments. */ -function formatString (message?: any, ...optionalParams: any[]): any { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return legacyCC.js.formatStr.apply(null, [message].concat(optionalParams)); +function formatString (...data: unknown[]): string { + return legacyCC.js.formatStr.apply(null, data) as string; } /** - * @en Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). This gives you additional control over the format of the output. - * @zh 输出一条消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。这为你提供了对输出格式的额外控制。 - * @param message @zh 包含零个或多个需要替换的JavaScript字符串。@en JavaScript objects to replace substitution strings in msg. - * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. + * @en Outputs a log message to the console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects. + * @zh 向控制台输出一条日志信息。这条信息可能是单个字符串(包括可选的替代字符串),也可能是一个或多个对象。 */ -export function log (message?: any, ...optionalParams: any[]): void { - return ccLog(message, ...optionalParams); +export function log (...data: unknown[]): void { + return ccLog(...data); } /** * @en - * Outputs a warning message to the Cocos Creator Console (editor) or Web Console (runtime). + * Outputs a warning message to the console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects. * - In Cocos Creator, warning is yellow. * - In Chrome, warning have a yellow warning icon with the message text. * @zh - * 输出警告消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。
+ * 向控制台输出一条警告信息。这条信息可能是单个字符串(包括可选的替代字符串),也可能是一个或多个对象。 * - 在 Cocos Creator 中,警告信息显示是黄色的。
* - 在 Chrome 中,警告信息有着黄色的图标以及黄色的消息文本。
- * @param message @zh 包含零个或多个需要替换的JavaScript字符串。@en JavaScript objects to replace substitution strings in msg. - * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. - * This gives you additional control over the format of the output. */ -export function warn (message?: any, ...optionalParams: any[]): void { - return ccWarn(message, ...optionalParams); +export function warn (...data: unknown[]): void { + return ccWarn(...data); } /** * @en - * Outputs an error message to the Cocos Creator Console (editor) or Web Console (runtime).
+ * Outputs an error message to the console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects. * - In Cocos Creator, error is red.
* - In Chrome, error have a red icon along with red message text.
* @zh - * 输出错误消息到 Cocos Creator 编辑器的 Console 或运行时页面端的 Console 中。
+ * 向控制台输出一条错误信息。这条信息可能是单个字符串(包括可选的替代字符串),也可能是一个或多个对象。 * - 在 Cocos Creator 中,错误信息显示是红色的。
* - 在 Chrome 中,错误信息有红色的图标以及红色的消息文本。
- * @param message @zh 包含零个或多个需要替换的JavaScript字符串。@en JavaScript objects to replace substitution strings in msg. - * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. - * This gives you additional control over the format of the output. */ -export function error (message?: any, ...optionalParams: any[]): void { - return ccError(message, ...optionalParams); +export function error (...data: unknown[]): void { + return ccError(...data); } /** @@ -108,13 +97,13 @@ export function error (message?: any, ...optionalParams: any[]): void { * Assert the condition and output error messages if the condition is not true. * @zh * 对检查测试条件进行检查,如果条件不为 true 则输出错误消息 - * @param value @zh 需要检查的条件。 @en The condition to check on. + * @param condition @zh 需要检查的条件。 @en The condition to check on. * @param message @zh 包含零个或多个需要替换的JavaScript字符串。@en JavaScript objects to replace substitution strings in msg. * @param optionalParams @zh 用来替换在message中需要替换的JavaScript对象。@en JavaScript objects with which to replace substitution strings within msg. * This gives you additional control over the format of the output. */ -export function assert (value: any, message?: string, ...optionalParams: any[]): asserts value { - return ccAssert(value, message, ...optionalParams); +export function assert (condition: boolean, message?: string, ...optionalParams: StringSubstitution[]): asserts condition { + return ccAssert(condition, message, ...optionalParams); } /** @@ -122,7 +111,7 @@ export function assert (value: any, message?: string, ...optionalParams: any[]): * @zh 输出一条“调试”日志等级的消息。 * @param data @zh 输出的消息对象。 @en The output message object. */ -export function debug (...data: any[]): void { +export function debug (...data: unknown[]): void { return ccDebug(...data); } @@ -175,22 +164,22 @@ export function _resetDebugSetting (mode: DebugMode): void { logList.scrollTop = logList.scrollHeight; }; - ccError = (message?: any, ...optionalParams: any[]): void => { - logToWebPage(`ERROR : ${formatString(message, ...optionalParams)}`); + ccError = (...data: unknown[]): void => { + logToWebPage(`ERROR : ${formatString(...data)}`); }; - ccAssert = (condition: any, message?: any, ...optionalParams: any[]): void => { + ccAssert = (condition: boolean, message?: unknown, ...optionalParams: unknown[]): void => { if (!condition) { logToWebPage(`ASSERT: ${formatString(message, ...optionalParams)}`); } }; if (mode !== DebugMode.ERROR_FOR_WEB_PAGE) { - ccWarn = (message?: any, ...optionalParams: any[]): void => { - logToWebPage(`WARN : ${formatString(message, ...optionalParams)}`); + ccWarn = (...data: unknown[]): void => { + logToWebPage(`WARN : ${formatString(...data)}`); }; } if (mode === DebugMode.INFO_FOR_WEB_PAGE) { - ccLog = (message?: any, ...optionalParams: any[]): void => { - logToWebPage(formatString(message, ...optionalParams)); + ccLog = (...data: unknown[]): void => { + logToWebPage(formatString(...data)); }; } } else if (console) { @@ -208,9 +197,9 @@ export function _resetDebugSetting (mode: DebugMode): void { // use bind to avoid pollute call stacks ccError = console.error.bind(console); } else { - ccError = JSB ? console.error : (message?: any, ...optionalParams: any[]): any => console.error.apply(console, [message, ...optionalParams]); + ccError = JSB ? console.error : (...data: unknown[]): void => console.error.apply(console, data); } - ccAssert = (condition: any, message?: any, ...optionalParams: any[]): void => { + ccAssert = (condition: boolean, message?: unknown, ...optionalParams: unknown[]): void => { if (!condition) { const errorText = formatString(message, ...optionalParams); if (DEV) { @@ -230,7 +219,7 @@ export function _resetDebugSetting (mode: DebugMode): void { // use bind to avoid pollute call stacks ccWarn = console.warn.bind(console); } else { - ccWarn = JSB ? console.warn : (message?: any, ...optionalParams: any[]): any => console.warn.apply(console, [message, ...optionalParams]); + ccWarn = JSB ? console.warn : (...data: unknown[]): void => console.warn.apply(console, data); } } @@ -243,14 +232,14 @@ export function _resetDebugSetting (mode: DebugMode): void { // use bind to avoid pollute call stacks ccLog = console.log.bind(console); } else { - ccLog = (message?: any, ...optionalParams: any[]): any => console.log.apply(console, [message, ...optionalParams]); + ccLog = (...data: unknown[]): void => console.log.apply(console, data); } } if (mode <= DebugMode.VERBOSE) { if (typeof console.debug === 'function') { const vendorDebug = console.debug.bind(console); - ccDebug = (...data: any[]): any => vendorDebug(...data); + ccDebug = (...data: unknown[]): any => vendorDebug(...data); } } } @@ -269,34 +258,33 @@ export function _throw (error_: any): any { } } -function getTypedFormatter (type: 'Log' | 'Warning' | 'Error' | 'Assert'): (id: number, ...args: any[]) => any { - return (id: number, ...args: any[]): any => { +function getTypedFormatter (type: 'Log' | 'Warning' | 'Error' | 'Assert'): (id: number, ...args: StringSubstitution[]) => string { + return (id: number, ...args: StringSubstitution[]): string => { const msg = DEBUG ? (debugInfos[id] || 'unknown id') : `${type} ${id}, please go to ${ERROR_MAP_URL}#${id} to see details.`; if (args.length === 0) { return msg; } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return return DEBUG ? formatString(msg, ...args) : `${msg} Arguments: ${args.join(', ')}`; }; } const logFormatter = getTypedFormatter('Log'); -export function logID (id: number, ...optionalParams: any[]): void { +export function logID (id: number, ...optionalParams: StringSubstitution[]): void { log(logFormatter(id, ...optionalParams)); } const warnFormatter = getTypedFormatter('Warning'); -export function warnID (id: number, ...optionalParams: any[]): void { +export function warnID (id: number, ...optionalParams: StringSubstitution[]): void { warn(warnFormatter(id, ...optionalParams)); } const errorFormatter = getTypedFormatter('Error'); -export function errorID (id: number, ...optionalParams: any[]): void { +export function errorID (id: number, ...optionalParams: StringSubstitution[]): void { error(errorFormatter(id, ...optionalParams)); } const assertFormatter = getTypedFormatter('Assert'); -export function assertID (condition: any, id: number, ...optionalParams: any[]): void { +export function assertID (condition: boolean, id: number, ...optionalParams: StringSubstitution[]): void { if (condition) { return; } @@ -363,8 +351,7 @@ export enum DebugMode { * @param errorId @zh 错误的ID。@en Error id. * @param param @zh 输出日志。@en Output log. */ -export function getError (errorId: number, ...param: any[]): string { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return +export function getError (errorId: number, ...param: StringSubstitution[]): string { return errorFormatter(errorId, ...param); } @@ -374,8 +361,7 @@ export function getError (errorId: number, ...param: any[]): string { * @deprecated @zh 从v3.6开始不再支持,请使用 profiler.isShowingStates。@en Since v3.6, Please use profiler.isShowingStates instead. */ export function isDisplayStats (): boolean { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return legacyCC.profiler ? legacyCC.profiler.isShowingStats() : false; + return legacyCC.profiler ? legacyCC.profiler.isShowingStats() as boolean : false; } /** diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index 253de0f9455..316de7300ef 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -559,7 +559,7 @@ export class Scheduler extends System { delay = 0; } - assertID(target, 1502); + assertID(Boolean(target), 1502); const targetId = target.uuid || target.id; if (!targetId) { @@ -863,8 +863,8 @@ export class Scheduler extends System { public isScheduled (callback, target: ISchedulable): boolean { // key, target // selector, target - assertID(callback, 1508); - assertID(target, 1509); + assertID(Boolean(callback), 1508); + assertID(Boolean(target), 1509); const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); @@ -996,7 +996,7 @@ export class Scheduler extends System { * @param target */ public pauseTarget (target: ISchedulable): void { - assertID(target, 1503); + assertID(Boolean(target), 1503); const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); @@ -1028,7 +1028,7 @@ export class Scheduler extends System { * @param target */ public resumeTarget (target: ISchedulable): void { - assertID(target, 1504); + assertID(Boolean(target), 1504); const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); @@ -1054,7 +1054,7 @@ export class Scheduler extends System { * @param target */ public isTargetPaused (target: ISchedulable): boolean { - assertID(target, 1505); + assertID(Boolean(target), 1505); const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); diff --git a/cocos/core/utils/js-typed.ts b/cocos/core/utils/js-typed.ts index f3eef862203..59d3adfb888 100644 --- a/cocos/core/utils/js-typed.ts +++ b/cocos/core/utils/js-typed.ts @@ -23,7 +23,7 @@ */ import { EDITOR, DEV, TEST } from 'internal:constants'; -import { warnID, error, errorID } from '../platform/debug'; +import { warnID, error, errorID, StringSubstitution } from '../platform/debug'; import { IDGenerator } from './id-generator'; const tempCIDGenerator = new IDGenerator('TmpCId.'); @@ -348,7 +348,21 @@ const REGEXP_STR = /%s/; * js.formatStr(a, b, c); * ``` */ -export function formatStr (msg: string, ...subst: any[]): string { +export function formatStr (msg: string, ...subst: StringSubstitution[]): string; +/** + * @en + * A string tool to constructs a string from an arbitrary sequence of js object arguments. + * @zh + * 根据任意 js 对象参数序列构造一个字符串。 + * @returns @en A new formatted string. @zh 格式化后的新字符串。 + * @example + * ``` + * import { js } from 'cc'; + * js.formatStr({}, null, undefined); // [object Object] null undefined + * ``` + */ +export function formatStr (...data: unknown[]): string; +export function formatStr (msg: unknown, ...subst: unknown[]): string { if (arguments.length === 0) { return ''; } @@ -360,9 +374,9 @@ export function formatStr (msg: string, ...subst: any[]): string { if (hasSubstitution) { for (const arg of subst) { const regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR; - if (regExpToTest.test(msg)) { + if (regExpToTest.test(msg as string)) { const notReplaceFunction = `${arg}`; - msg = msg.replace(regExpToTest, notReplaceFunction); + msg = (msg as string).replace(regExpToTest, notReplaceFunction); } else { msg += ` ${arg}`; } @@ -372,7 +386,7 @@ export function formatStr (msg: string, ...subst: any[]): string { msg += ` ${arg}`; } } - return msg; + return msg as string; } // see https://github.com/petkaantonov/bluebird/issues/1389 @@ -557,7 +571,7 @@ export function isChildClassOf (subclass: unknown, superclass: unknown): boolean } if (typeof superclass !== 'function') { if (DEV) { - warnID(3625, superclass); + warnID(3625, superclass as string); } return false; } diff --git a/cocos/game/director.ts b/cocos/game/director.ts index 8f6b250a707..6ce2669fd9d 100644 --- a/cocos/game/director.ts +++ b/cocos/game/director.ts @@ -406,7 +406,7 @@ export class Director extends EventTarget { */ public runScene (scene: Scene | SceneAsset, onBeforeLoadScene?: Director.OnBeforeLoadScene, onLaunched?: Director.OnSceneLaunched): void { if (scene instanceof SceneAsset) scene = scene.scene!; - assertID(scene, 1205); + assertID(Boolean(scene), 1205); assertID(scene instanceof Scene, 1216); // Delay run / replace scene to the end of the frame diff --git a/cocos/physics-2d/box2d/platform/physics-contact-listener.ts b/cocos/physics-2d/box2d/platform/physics-contact-listener.ts index 613dc465991..ba21adbb266 100644 --- a/cocos/physics-2d/box2d/platform/physics-contact-listener.ts +++ b/cocos/physics-2d/box2d/platform/physics-contact-listener.ts @@ -76,7 +76,7 @@ export class PhysicsContactListener extends b2.ContactListener { const key = this.getContactKey(contact); const retContact = PhysicsContactListener._contactMap.get(key); - assert(retContact); + assert(typeof retContact !== 'undefined'); retContact.ref--; //console.log(' collision--', key, 'current ref is:', retCollision.ref); diff --git a/cocos/render-scene/core/pass.ts b/cocos/render-scene/core/pass.ts index 2f598c3063f..5be25422065 100644 --- a/cocos/render-scene/core/pass.ts +++ b/cocos/render-scene/core/pass.ts @@ -269,7 +269,7 @@ export class Pass { const block = this._getBlockView(type, binding); if (DEBUG) { const validator = type2validator[type]; - assertID(validator && validator(value), 12011, binding, Type[type]); + assertID(Boolean(validator && validator(value)), 12011, binding, Type[type]); } type2writer[type](block, value, ofs); this._rootBufferDirty = true; diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index d1a321a386e..9257584bf80 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -1055,7 +1055,7 @@ class DevicePreSceneTask extends WebSceneTask { // shadowmap if (isShadowMap(this.graphScene)) { const scene = this.graphScene.scene!; - assert(scene.light.light); + assert(scene.light.light !== null); let shadowQueue = this._submitInfo.shadowMap.get(this.graphScene.sceneID); if (!shadowQueue) { shadowQueue = new RenderShadowMapBatchedQueue(context.pipeline); diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 665bb1787aa..0035a35706a 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -991,8 +991,8 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu } addComputeView (name: string, view: ComputeView): void { if (DEBUG) { - assert(view.name); - assert(name && this._resourceGraph.contains(name)); + assert(Boolean(view.name)); + assert(Boolean(name && this._resourceGraph.contains(name))); const descriptorName = view.name; const descriptorID = this._layoutGraph.attributeIndex.get(descriptorName); assert(descriptorID !== undefined); @@ -1018,7 +1018,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu } addRenderTarget (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()): void { if (DEBUG) { - assert(name && this._resourceGraph.contains(name)); + assert(Boolean(name && this._resourceGraph.contains(name))); } let clearFlag = ClearFlagBit.COLOR; if (loadOp === LoadOp.LOAD) { @@ -1034,7 +1034,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu } addDepthStencil (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { if (DEBUG) { - assert(name && this._resourceGraph.contains(name)); + assert(Boolean(name && this._resourceGraph.contains(name))); } const view = new RasterView('', AccessType.WRITE, AttachmentType.DEPTH_STENCIL, @@ -1048,8 +1048,8 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu const view = new ComputeView(slotName); view.accessType = accessType; if (DEBUG) { - assert(view.name); - assert(name && this._resourceGraph.contains(name)); + assert(Boolean(view.name)); + assert(Boolean(name && this._resourceGraph.contains(name))); const descriptorName = view.name; const descriptorID = this._layoutGraph.attributeIndex.get(descriptorName); assert(descriptorID !== undefined); @@ -1218,7 +1218,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild } addComputeView (name: string, view: ComputeView): void { if (DEBUG) { - assert(name && this._resourceGraph.contains(name)); + assert(Boolean(name && this._resourceGraph.contains(name))); } if (this._pass.computeViews.has(name)) { this._pass.computeViews.get(name)?.push(view); @@ -1795,8 +1795,8 @@ export class WebPipeline implements BasicPipeline { const stageId = this.layoutGraph.locateChild(this.layoutGraph.nullVertex(), layoutName); assert(stageId !== 0xFFFFFFFF); const layout = this.layoutGraph.getLayout(stageId); - assert(layout); - assert(layout.descriptorSets.get(UpdateFrequency.PER_PASS)); + assert(Boolean(layout)); + assert(Boolean(layout.descriptorSets.get(UpdateFrequency.PER_PASS))); } const name = 'Raster'; const pass = new RasterPass(); diff --git a/cocos/scene-graph/component.ts b/cocos/scene-graph/component.ts index 0a9c8ccb62e..7a359bc32de 100644 --- a/cocos/scene-graph/component.ts +++ b/cocos/scene-graph/component.ts @@ -426,7 +426,7 @@ class Component extends CCObject { * ``` */ public schedule (callback, interval = 0, repeat: number = legacyCC.macro.REPEAT_FOREVER, delay = 0): void { - assertID(callback, 1619); + assertID(Boolean(callback), 1619); interval = interval || 0; assertID(interval >= 0, 1620); diff --git a/cocos/tiledmap/tmx-xml-parser.ts b/cocos/tiledmap/tmx-xml-parser.ts index 8e551881dcd..79669a6b51a 100644 --- a/cocos/tiledmap/tmx-xml-parser.ts +++ b/cocos/tiledmap/tmx-xml-parser.ts @@ -817,7 +817,7 @@ export class TMXMapInfo { imageLayer.trans = strToColor(data.getAttribute('trans')!); if (!imageLayer.sourceImage) { - errorID(7221, source); + errorID(7221, source!); console.warn(`Please try asset type of ${source} to 'sprite-frame'`); return null; } @@ -1043,8 +1043,7 @@ export class TMXMapInfo { * Gets the tile properties. * @return {Object} */ - getTileProperties (): Map - { + getTileProperties (): Map { return this._tileProperties; } From 7e86eb0f95fbb8c31c4df07769a5a404437d18e7 Mon Sep 17 00:00:00 2001 From: PP Date: Wed, 14 Jun 2023 13:41:18 +0800 Subject: [PATCH 004/232] fix type in scheduler.ts (#15431) * fix type in scheduler.ts * fix CI * add dt type --- cocos/core/scheduler.ts | 257 ++++++++++++++++++++++++---------------- 1 file changed, 157 insertions(+), 100 deletions(-) diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index 316de7300ef..8863514bca8 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -36,6 +36,7 @@ const idGenerator = new IDGenerator('Scheduler'); export interface ISchedulable { id?: string; uuid?: string; + update? (dt: number): void; } // data structures @@ -45,7 +46,7 @@ export interface ISchedulable { * @class ListEntry */ class ListEntry { - public static get = (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean): ListEntry => { + public static get (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean): ListEntry { let result = ListEntry._listEntries.pop(); if (result) { result.target = target; @@ -58,7 +59,7 @@ class ListEntry { return result; } - public static put = (entry: ListEntry | any): void => { + public static put (entry: ListEntry): void { if (ListEntry._listEntries.length < MAX_POOL_SIZE) { entry.target = null; ListEntry._listEntries.push(entry); @@ -67,7 +68,7 @@ class ListEntry { private static _listEntries: ListEntry[] = []; - public target: ISchedulable; + public target: ISchedulable | null; public priority: number; public paused: boolean; public markedForDeletion: boolean; @@ -106,7 +107,7 @@ class ListEntry { * @param callback @en The callback function. @zh 所回调的函数。 */ class HashUpdateEntry { - public static get = (list: any, entry: ListEntry, target: ISchedulable, callback: any): HashUpdateEntry => { + public static get (list: ListEntry[], entry: ListEntry, target: ISchedulable, callback: AnyFunction | null): HashUpdateEntry { let result = HashUpdateEntry._hashUpdateEntries.pop(); if (result) { result.list = list; @@ -119,7 +120,7 @@ class HashUpdateEntry { return result; } - public static put = (entry: HashUpdateEntry | any): void => { + public static put (entry: HashUpdateEntry): void { if (HashUpdateEntry._hashUpdateEntries.length < MAX_POOL_SIZE) { entry.list = entry.entry = entry.target = entry.callback = null; HashUpdateEntry._hashUpdateEntries.push(entry); @@ -128,12 +129,12 @@ class HashUpdateEntry { private static _hashUpdateEntries: HashUpdateEntry[] = []; - public list: any; - public entry: ListEntry; - public target: ISchedulable; - public callback: any; + public list: ListEntry[] | null; + public entry: ListEntry | null; + public target: ISchedulable | null; + public callback: AnyFunction | null; - constructor (list: any, entry: ListEntry, target: ISchedulable, callback: any) { + constructor (list: ListEntry[], entry: ListEntry, target: ISchedulable, callback: AnyFunction | null) { this.list = list; this.entry = entry; this.target = target; @@ -152,7 +153,7 @@ class HashUpdateEntry { * @param paused */ class HashTimerEntry { - public static get = (timers: any, target: ISchedulable, timerIndex: number, currentTimer: any, currentTimerSalvaged: any, paused: any): HashTimerEntry => { + public static get (timers: CallbackTimer[] | null, target: ISchedulable, timerIndex: number, currentTimer: CallbackTimer | null, currentTimerSalvaged: boolean, paused: boolean): HashTimerEntry { let result = HashTimerEntry._hashTimerEntries.pop(); if (result) { result.timers = timers; @@ -167,7 +168,7 @@ class HashTimerEntry { return result; } - public static put = (entry: HashTimerEntry | any): void => { + public static put (entry: HashTimerEntry): void { if (HashTimerEntry._hashTimerEntries.length < MAX_POOL_SIZE) { entry.timers = entry.target = entry.currentTimer = null; HashTimerEntry._hashTimerEntries.push(entry); @@ -176,14 +177,14 @@ class HashTimerEntry { private static _hashTimerEntries: HashTimerEntry[] = []; - public timers: any; - public target: ISchedulable; + public timers: CallbackTimer[] | null; + public target: ISchedulable | null; public timerIndex: number; - public currentTimer: any; - public currentTimerSalvaged: any; - public paused: any; + public currentTimer: CallbackTimer | null; + public currentTimerSalvaged: boolean; + public paused: boolean; - constructor (timers: any, target: ISchedulable, timerIndex: number, currentTimer: any, currentTimerSalvaged: any, paused: any) { + constructor (timers: CallbackTimer[] | null, target: ISchedulable, timerIndex: number, currentTimer: CallbackTimer | null, currentTimerSalvaged: boolean, paused: boolean) { this.timers = timers; this.target = target; this.timerIndex = timerIndex; @@ -193,13 +194,15 @@ class HashTimerEntry { } } +type CallbackType = (dt?: number) => void; + /* * Light weight timer */ class CallbackTimer { public static _timers: CallbackTimer[] = []; - public static get = (): CallbackTimer => CallbackTimer._timers.pop() || new CallbackTimer() - public static put = (timer: CallbackTimer | any): void => { + public static get (): CallbackTimer { return CallbackTimer._timers.pop() || new CallbackTimer(); } + public static put (timer: CallbackTimer): void { if (CallbackTimer._timers.length < MAX_POOL_SIZE && !timer._lock) { timer._scheduler = timer._target = timer._callback = null; CallbackTimer._timers.push(timer); @@ -207,7 +210,7 @@ class CallbackTimer { } private _lock: boolean; - private _scheduler: any; + private _scheduler: Scheduler | null; private _elapsed: number; private _runForever: boolean; private _useDelay: boolean; @@ -216,7 +219,7 @@ class CallbackTimer { private _delay: number; private _interval: number; private _target: ISchedulable | null; - private _callback?: (dt?: number) => void; + private _callback?: CallbackType | null; constructor () { this._lock = false; @@ -232,7 +235,7 @@ class CallbackTimer { this._target = null; } - public initWithCallback (scheduler: any, callback: any, target: ISchedulable, seconds: number, repeat: number, delay: number): boolean { + public initWithCallback (scheduler: Scheduler, callback: CallbackType, target: ISchedulable, seconds: number, repeat: number, delay: number): boolean { this._lock = false; this._scheduler = scheduler; this._target = target; @@ -260,7 +263,7 @@ class CallbackTimer { * @en Set interval in seconds. * @zh 以秒为单位设置时间间隔。 */ - public setInterval (interval): void { + public setInterval (interval: number): void { this._interval = interval; } @@ -305,7 +308,7 @@ class CallbackTimer { } } - public getCallback (): ((dt?: number | undefined) => void) | undefined { + public getCallback (): CallbackType | null | undefined { return this._callback; } @@ -318,8 +321,9 @@ class CallbackTimer { } public cancel (): void { - // override - this._scheduler.unschedule(this._callback, this._target); + if (this._scheduler && this._callback && this._target) { + this._scheduler.unschedule(this._callback, this._target); + } } } @@ -346,15 +350,15 @@ export class Scheduler extends System { public static ID = 'scheduler'; private _timeScale: number; - private _updatesNegList: any[]; - private _updates0List: any[]; - private _updatesPosList: any[]; - private _hashForUpdates: any; - private _hashForTimers: any; - private _currentTarget: any; + private _updatesNegList: ListEntry[]; + private _updates0List: ListEntry[]; + private _updatesPosList: ListEntry[]; + private _hashForUpdates: Record; + private _hashForTimers: Record; + private _currentTarget: HashTimerEntry | null; private _currentTargetSalvaged: boolean; private _updateHashLocked: boolean; - private _arrayForTimers: any; + private _arrayForTimers: HashTimerEntry[]; /** * @en This method should be called for any target which needs to schedule tasks, and this method should be called before any scheduler API usage. @@ -383,8 +387,8 @@ export class Scheduler extends System { this._updatesNegList = []; // list of priority < 0 this._updates0List = []; // list of priority == 0 this._updatesPosList = []; // list of priority > 0 - this._hashForUpdates = createMap(true); // hash used to fetch quickly the list entries for pause, delete, etc - this._hashForTimers = createMap(true); // Used for "selectors with interval" + this._hashForUpdates = createMap(true) as Record; // hash used to fetch quickly the list entries for pause, delete, etc + this._hashForTimers = createMap(true) as Record; // Used for "selectors with interval" this._currentTarget = null; this._currentTargetSalvaged = false; this._updateHashLocked = false; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. @@ -410,7 +414,7 @@ export class Scheduler extends System { * 注意:它影响该 Scheduler 下管理的所有定时器。 * @param timeScale */ - public setTimeScale (timeScale): void { + public setTimeScale (timeScale: number): void { this._timeScale = timeScale; } @@ -429,47 +433,47 @@ export class Scheduler extends System { * @en delta time. The unit is seconds. * @zh 更新间隔时间, 单位是秒。 */ - public update (dt): void { + public update (dt: number): void { this._updateHashLocked = true; if (this._timeScale !== 1) { dt *= this._timeScale; } let i: number; - let list; + let list: ListEntry[]; let len: number; - let entry; + let entry: ListEntry; for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) { entry = list[i]; - if (!entry.paused && !entry.markedForDeletion) { - entry.target.update(dt); + if (!entry.paused && !entry.markedForDeletion && entry.target) { + entry.target.update?.(dt); } } for (i = 0, list = this._updates0List, len = list.length; i < len; i++) { entry = list[i]; - if (!entry.paused && !entry.markedForDeletion) { - entry.target.update(dt); + if (!entry.paused && !entry.markedForDeletion && entry.target) { + entry.target.update?.(dt); } } for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) { entry = list[i]; - if (!entry.paused && !entry.markedForDeletion) { - entry.target.update(dt); + if (!entry.paused && !entry.markedForDeletion && entry.target) { + entry.target.update?.(dt); } } // Iterate over all the custom selectors - let elt; + let elt: HashTimerEntry; const arr = this._arrayForTimers; for (i = 0; i < arr.length; i++) { - elt = arr[i] as HashTimerEntry; + elt = arr[i]; this._currentTarget = elt; this._currentTargetSalvaged = false; - if (!elt.paused) { + if (!elt.paused && elt.timers) { // The 'timers' array may change while inside this loop for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++(elt.timerIndex)) { elt.currentTimer = elt.timers[elt.timerIndex]; @@ -481,7 +485,7 @@ export class Scheduler extends System { } // only delete currentTarget if no actions were scheduled during the cycle (issue #481) - if (this._currentTargetSalvaged && this._currentTarget.timers.length === 0) { + if (this._currentTargetSalvaged && this._currentTarget.timers?.length === 0) { this._removeHashElement(this._currentTarget); --i; } @@ -544,12 +548,44 @@ export class Scheduler extends System { * @zh 如果 paused 值为 true,那么直到 resume 被调用才开始计时。 * @param paused */ - public schedule (callback: (dt?: number) => void, target: ISchedulable, interval: number, repeat?: number, delay?: number, paused?: boolean): void { - if (typeof callback !== 'function') { + public schedule (callback: CallbackType, target: ISchedulable, interval: number, repeat?: number, delay?: number, paused?: boolean): void; + /** + * @en The specified target. + * @zh 所指定的调用对象。 + * @param target + * @en Specify the callback to schedule a new timer. + * If the callback function is already scheduled, then only the interval parameter will be updated without re-scheduling it again. + * @zh 指定回调函数来规划一个新的定时器。 + * 如果回调函数已经被定时器使用,那么只会更新之前定时器的时间间隔参数,不会设置新的定时器。 + * @param callback + * @en The scheduled method will be called every 'interval' seconds. + * If 'interval' is 0, it will be called every frame, but if so, it recommended to use 'scheduleUpdateForTarget:' instead. + * @zh 当时间间隔达到指定值时,设置的回调函数将会被调用。 + * 如果 interval 值为 0,那么回调函数每一帧都会被调用,但如果是这样,建议使用 scheduleUpdateForTarget 代替。 + * @param interval + * @en repeat let the action be repeated repeat + 1 times, use `macro.REPEAT_FOREVER` to let the action run continuously. + * @zh repeat 值可以让定时器触发 repeat + 1 次,使用 `macro.REPEAT_FOREVER` 可以让定时器一直循环触发。 + * @param repeat + * @en delay is the amount of time the action will wait before it'll start. Unit: s. + * @zh delay 值指定延迟时间,定时器会在延迟指定的时间之后开始计时,单位: 秒。 + * @param delay + * @en If paused is YES, then it won't be called until it is resumed. + * @zh 如果 paused 值为 true,那么直到 resume 被调用才开始计时。 + * @param paused + * + * @deprecated since v3.8.0, please use `Scheduler.schedule(callback, target, interval)` instead. + */ + public schedule (target: ISchedulable, callback: CallbackType, interval: number, repeat?: number, delay?: number, paused?: boolean): void; + public schedule (callbackTmp: CallbackType | ISchedulable, targetTmp: ISchedulable | CallbackType, interval: number, repeat?: number, delay?: number, paused?: boolean): void { + let callback: CallbackType; + let target: ISchedulable; + if (typeof callbackTmp !== 'function') { warnID(1514); - const tmp = callback; - callback = target as any; - target = tmp; + callback = targetTmp as CallbackType; + target = callbackTmp; + } else { + callback = callbackTmp; + target = targetTmp as ISchedulable; } // selector, target, interval, repeat, delay, paused // selector, target, interval, paused @@ -566,33 +602,33 @@ export class Scheduler extends System { errorID(1510); return; } - let element = this._hashForTimers[targetId] as HashTimerEntry; + let element = this._hashForTimers[targetId]; if (!element) { // Is this the 1st element ? Then set the pause level to all the callback_fns of this target - element = HashTimerEntry.get(null, target, 0, null, null, paused); + element = HashTimerEntry.get(null, target, 0, null, false, Boolean(paused)); this._arrayForTimers.push(element); this._hashForTimers[targetId] = element; } else if (element.paused !== paused) { warnID(1511); } - let timer; + let timer: CallbackTimer; let i; if (element.timers == null) { element.timers = []; } else { for (i = 0; i < element.timers.length; ++i) { timer = element.timers[i]; - if (timer && callback === timer._callback) { + if (timer && callback === timer.getCallback()) { logID(1507, timer.getInterval(), interval); - timer._interval = interval; + timer.setInterval(interval); return; } } } timer = CallbackTimer.get(); - timer.initWithCallback(this, callback, target, interval, repeat, delay); + timer.initWithCallback(this, callback, target, interval, repeat ?? 0, delay ?? 0); element.timers.push(timer); if (this._currentTarget === element && this._currentTargetSalvaged) { @@ -609,7 +645,7 @@ export class Scheduler extends System { * update 定时器每一帧都会被触发,触发时自动调用指定对象的 "update" 函数。
* 优先级的值越低,定时器被触发的越早。 * @param target - * @en The target bound to the callback. @zh 回调所绑定的目标对象。 + * @en The target bound to the callback. @zh 回调所绑定的目标对象。 * @param priority * @en The priority. @zh 优先级。 * @param paused @@ -642,7 +678,7 @@ export class Scheduler extends System { } const listElement = ListEntry.get(target, priority, paused, false); - let ppList; + let ppList: ListEntry[]; // most of the updates are going to be 0, that's way there // is an special list for updates with priority 0 @@ -668,7 +704,7 @@ export class Scheduler extends System { * @param callback @en The callback to be unscheduled @zh 被取消调度的回调。 * @param target @en The target bound to the callback. @zh 回调所绑定的目标对象。 */ - public unschedule (callback, target: ISchedulable): void { + public unschedule (callback: AnyFunction, target: ISchedulable): void { // callback, target // explicity handle nil arguments when removing an object @@ -684,9 +720,12 @@ export class Scheduler extends System { const element = this._hashForTimers[targetId]; if (element) { const timers = element.timers; + if (!timers) { + return; + } for (let i = 0, li = timers.length; i < li; i++) { const timer = timers[i]; - if (callback === timer._callback) { + if (callback === timer.getCallback()) { if ((timer === element.currentTimer) && (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } @@ -726,7 +765,7 @@ export class Scheduler extends System { } const element = this._hashForUpdates[targetId]; - if (element) { + if (element?.entry) { if (this._updateHashLocked) { element.entry.markedForDeletion = true; } else { @@ -742,7 +781,7 @@ export class Scheduler extends System { * @zh 取消指定对象的所有定时器,包括 update 定时器。 * @param target The target to be unscheduled. */ - public unscheduleAllForTarget (target): void { + public unscheduleAllForTarget (target: ISchedulable): void { // explicit nullptr handling if (!target) { return; @@ -755,9 +794,9 @@ export class Scheduler extends System { // Custom Selectors const element = this._hashForTimers[targetId]; - if (element) { + if (element?.timers) { const timers = element.timers; - if (timers.indexOf(element.currentTimer) > -1 + if (element.currentTimer && timers.indexOf(element.currentTimer) > -1 && (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } @@ -804,22 +843,24 @@ export class Scheduler extends System { */ public unscheduleAllWithMinPriority (minPriority: number): void { // Custom Selectors - let i; - let element; + let i: number; + let element: HashTimerEntry; const arr = this._arrayForTimers; for (i = arr.length - 1; i >= 0; i--) { - element = arr[i] as HashTimerEntry; - this.unscheduleAllForTarget(element.target); + element = arr[i]; + if (element.target) { + this.unscheduleAllForTarget(element.target); + } } // Updates selectors - let entry; + let entry: ListEntry; let temp_length = 0; if (minPriority < 0) { for (i = 0; i < this._updatesNegList.length;) { temp_length = this._updatesNegList.length; entry = this._updatesNegList[i]; - if (entry && entry.priority >= minPriority) { + if (entry?.target && entry.priority >= minPriority) { this.unscheduleUpdate(entry.target); } if (temp_length === this._updatesNegList.length) { @@ -832,7 +873,7 @@ export class Scheduler extends System { for (i = 0; i < this._updates0List.length;) { temp_length = this._updates0List.length; entry = this._updates0List[i]; - if (entry) { + if (entry?.target) { this.unscheduleUpdate(entry.target); } if (temp_length === this._updates0List.length) { @@ -844,7 +885,7 @@ export class Scheduler extends System { for (i = 0; i < this._updatesPosList.length;) { temp_length = this._updatesPosList.length; entry = this._updatesPosList[i]; - if (entry && entry.priority >= minPriority) { + if (entry?.target && entry.priority >= minPriority) { this.unscheduleUpdate(entry.target); } if (temp_length === this._updatesPosList.length) { @@ -860,7 +901,7 @@ export class Scheduler extends System { * @param target @en The target of the callback. @zh 回调的目标对象。 * @returns @en True if the specified callback is invoked, false if not. @zh 返回true如果指定回调被调用, 否则返回false。 */ - public isScheduled (callback, target: ISchedulable): boolean { + public isScheduled (callback: AnyFunction, target: ISchedulable): boolean { // key, target // selector, target assertID(Boolean(callback), 1508); @@ -884,7 +925,7 @@ export class Scheduler extends System { for (let i = 0; i < timers.length; ++i) { const timer = timers[i]; - if (callback === timer._callback) { + if (callback === timer.getCallback()) { return true; } } @@ -923,17 +964,17 @@ export class Scheduler extends System { // Custom Selectors for (i = 0, li = locArrayForTimers.length; i < li; i++) { element = locArrayForTimers[i]; - if (element) { + if (element?.target) { element.paused = true; idsWithSelectors.push(element.target); } } - let entry; + let entry: ListEntry; if (minPriority < 0) { for (i = 0; i < this._updatesNegList.length; i++) { entry = this._updatesNegList[i]; - if (entry) { + if (entry?.target) { if (entry.priority >= minPriority) { entry.paused = true; idsWithSelectors.push(entry.target); @@ -945,7 +986,7 @@ export class Scheduler extends System { if (minPriority <= 0) { for (i = 0; i < this._updates0List.length; i++) { entry = this._updates0List[i]; - if (entry) { + if (entry?.target) { entry.paused = true; idsWithSelectors.push(entry.target); } @@ -954,7 +995,7 @@ export class Scheduler extends System { for (i = 0; i < this._updatesPosList.length; i++) { entry = this._updatesPosList[i]; - if (entry) { + if (entry?.target) { if (entry.priority >= minPriority) { entry.paused = true; idsWithSelectors.push(entry.target); @@ -974,7 +1015,7 @@ export class Scheduler extends System { * 这个函数是 pauseAllCallbacks 的逆操作。 * @param targetsToResume */ - public resumeTargets (targetsToResume): void { + public resumeTargets (targetsToResume: ISchedulable[]): void { if (!targetsToResume) { return; } @@ -1011,7 +1052,7 @@ export class Scheduler extends System { // update callback const elementUpdate = this._hashForUpdates[targetId]; - if (elementUpdate) { + if (elementUpdate?.entry) { elementUpdate.entry.paused = true; } } @@ -1043,7 +1084,7 @@ export class Scheduler extends System { // update callback const elementUpdate = this._hashForUpdates[targetId]; - if (elementUpdate) { + if (elementUpdate?.entry) { elementUpdate.entry.paused = false; } } @@ -1062,20 +1103,26 @@ export class Scheduler extends System { } // Custom selectors - const element = this._hashForTimers[targetId] as HashTimerEntry; + const element = this._hashForTimers[targetId]; if (element) { - return element.paused as boolean; + return element.paused; } const elementUpdate = this._hashForUpdates[targetId]; - if (elementUpdate) { - return elementUpdate.entry.paused as boolean; + if (elementUpdate?.entry) { + return elementUpdate.entry.paused; } return false; } // -----------------------private method---------------------- - private _removeHashElement (element): void { + private _removeHashElement (element: HashTimerEntry): void { + if (!element.target) { + return; + } const targetId = element.target.uuid || element.target.id; + if (typeof targetId === 'undefined') { + return; + } delete this._hashForTimers[targetId]; const arr = this._arrayForTimers; for (let i = 0, l = arr.length; i < l; i++) { @@ -1087,27 +1134,37 @@ export class Scheduler extends System { HashTimerEntry.put(element); } - private _removeUpdateFromHash (entry): void { + private _removeUpdateFromHash (entry: ListEntry): void { + if (!entry.target) { + return; + } const targetId = entry.target.uuid || entry.target.id; + if (typeof targetId === 'undefined') { + return; + } const element = this._hashForUpdates[targetId]; if (element) { // Remove list entry from list const list = element.list; const listEntry = element.entry; - for (let i = 0, l = list.length; i < l; i++) { - if (list[i] === listEntry) { - list.splice(i, 1); - break; + if (list) { + for (let i = 0, l = list.length; i < l; i++) { + if (list[i] === listEntry) { + list.splice(i, 1); + break; + } } } delete this._hashForUpdates[targetId]; - ListEntry.put(listEntry); + if (listEntry) { + ListEntry.put(listEntry); + } HashUpdateEntry.put(element); } } - private _priorityIn (ppList, listElement, priority): void { + private _priorityIn (ppList: ListEntry[], listElement: ListEntry, priority: number): void { for (let i = 0; i < ppList.length; i++) { if (priority < ppList[i].priority) { ppList.splice(i, 0, listElement); @@ -1117,7 +1174,7 @@ export class Scheduler extends System { ppList.push(listElement); } - private _appendIn (ppList, listElement): void { + private _appendIn (ppList: ListEntry[], listElement: ListEntry): void { ppList.push(listElement); } } From 6b171d2be4ee7fc6958ef511b5619c2bd84cf9db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 15 Jun 2023 11:17:47 +0800 Subject: [PATCH 005/232] Uniform the way to set a property's type as enum (#15440) * Uniform the way to set a property's type as enum * Update * Revert "Update" * License --- cocos/core/data/class.ts | 8 +++-- cocos/core/data/utils/attribute-internal.ts | 36 +++++++++++++++++++++ cocos/core/internal-index.ts | 2 ++ cocos/core/value-types/enum.ts | 2 ++ cocos/dragon-bones/ArmatureDisplay.ts | 18 ++++------- cocos/particle/animator/curve-range.ts | 6 ++-- cocos/spine/skeleton.ts | 12 +++---- 7 files changed, 60 insertions(+), 24 deletions(-) create mode 100644 cocos/core/data/utils/attribute-internal.ts diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index e10f10fa83d..bc66b0149fb 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -36,6 +36,7 @@ import * as RF from './utils/requiring-frame'; import { legacyCC } from '../global-exports'; import { PropertyStash, PropertyStashInternalFlag } from './class-stash'; +import { setPropertyEnumTypeOnAttrs } from './utils/attribute-internal'; const DELIMETER = attributeUtils.DELIMETER; const CCCLASS_TAG = '__ctors__'; // Still use this historical name to avoid unsynchronized version issue @@ -455,8 +456,11 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas // } else if (typeof type === 'object') { if (Enum.isEnum(type)) { - (attrs || initAttrs())[`${propertyNamePrefix}type`] = ENUM_TAG; - attrs![`${propertyNamePrefix}enumList`] = Enum.getList(type); + setPropertyEnumTypeOnAttrs( + attrs || initAttrs(), + propertyName, + type, + ); } else if (BitMask.isBitMask(type)) { (attrs || initAttrs())[`${propertyNamePrefix}type`] = BITMASK_TAG; attrs![`${propertyNamePrefix}bitmaskList`] = BitMask.getList(type); diff --git a/cocos/core/data/utils/attribute-internal.ts b/cocos/core/data/utils/attribute-internal.ts new file mode 100644 index 00000000000..306019d084c --- /dev/null +++ b/cocos/core/data/utils/attribute-internal.ts @@ -0,0 +1,36 @@ +/* + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { Enum, EnumType } from '../../value-types/enum'; +import { getClassAttrs, DELIMETER } from './attribute'; + +// eslint-disable-next-line @typescript-eslint/ban-types +export function setPropertyEnumType (objectOrConstructor: object, propertyName: string, enumType: EnumType): void { + setPropertyEnumTypeOnAttrs(getClassAttrs(objectOrConstructor), propertyName, enumType); +} + +export function setPropertyEnumTypeOnAttrs (attrs: Record, propertyName: string, enumType: EnumType): void { + attrs[`${propertyName}${DELIMETER}type`] = 'Enum'; + attrs[`${propertyName}${DELIMETER}enumList`] = Enum.getList(enumType); +} diff --git a/cocos/core/internal-index.ts b/cocos/core/internal-index.ts index 48ab60cf195..25bfb414cf8 100644 --- a/cocos/core/internal-index.ts +++ b/cocos/core/internal-index.ts @@ -41,6 +41,8 @@ export type { DeserializationContext } from './data/custom-serializable'; export * from './data/utils/asserts'; export * from './data/utils/compiler'; +export { setPropertyEnumType, setPropertyEnumTypeOnAttrs } from './data/utils/attribute-internal'; + export { ENUM_TAG, BITMASK_TAG } from './data/class'; export { isCCObject, isValid } from './data/object'; diff --git a/cocos/core/value-types/enum.ts b/cocos/core/value-types/enum.ts index 6e4e5aa169e..60b8264a1d2 100644 --- a/cocos/core/value-types/enum.ts +++ b/cocos/core/value-types/enum.ts @@ -29,6 +29,8 @@ import { legacyCC } from '../global-exports'; import { errorID } from '../platform/debug'; import { assertIsTrue } from '../data/utils/asserts'; +export type EnumType = Record; + /** * @en * Define an enum type.
diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index 20899375b91..2e70e6d9660 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -25,7 +25,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { Armature, Bone, EventObject, AnimationState } from '@cocos/dragonbones-js'; import { UIRenderer } from '../2d/framework/ui-renderer'; -import { CCClass, Color, Enum, ccenum, errorID, RecyclePool, js, CCObject, EventTarget, cclegacy, _decorator } from '../core'; +import { Color, Enum, ccenum, errorID, RecyclePool, js, CCObject, EventTarget, cclegacy, _decorator } from '../core'; import { BlendFactor } from '../gfx'; import { AnimationCache, ArmatureCache, ArmatureFrame } from './ArmatureCache'; import { AttachUtil } from './AttachUtil'; @@ -42,6 +42,7 @@ import { RenderDrawInfo } from '../2d/renderer/render-draw-info'; import { Material, Texture2D } from '../asset/assets'; import { Node } from '../scene-graph'; import { builtinResMgr } from '../asset/asset-manager'; +import { setPropertyEnumType } from '../core/internal-index'; enum DefaultArmaturesEnum { default = -1, @@ -94,11 +95,6 @@ ccenum(AnimationCacheMode); const { ccclass, serializable, editable, type, help, menu, tooltip, visible, displayName, override, displayOrder, executeInEditMode } = _decorator; -function setEnumAttr (obj, propName, enumDef): void { - CCClass.Attr.setClassAttr(obj, propName, 'type', 'Enum'); - CCClass.Attr.setClassAttr(obj, propName, 'enumList', Enum.getList(enumDef)); -} - /** * @en Struct that can store rendering data-related information. * @zh 用于存储渲染数据相关信息的结构体。 @@ -616,8 +612,8 @@ export class ArmatureDisplay extends UIRenderer { this._inited = false; this.attachUtil = new AttachUtil(); this.initFactory(); - setEnumAttr(this, '_animationIndex', this._enumAnimations); - setEnumAttr(this, '_defaultArmatureIndex', this._enumArmatures); + setPropertyEnumType(this, '_animationIndex', this._enumAnimations); + setPropertyEnumType(this, '_defaultArmatureIndex', this._enumArmatures); this._useVertexOpacity = true; } /** @@ -1157,7 +1153,7 @@ export class ArmatureDisplay extends UIRenderer { } else { Object.assign(this._cacheModeEnum, DefaultCacheMode); } - setEnumAttr(this, '_defaultCacheMode', this._cacheModeEnum); + setPropertyEnumType(this, '_defaultCacheMode', this._cacheModeEnum); } // update animation list for editor @@ -1176,7 +1172,7 @@ export class ArmatureDisplay extends UIRenderer { Object.assign(this._enumAnimations, animEnum || DefaultAnimsEnum); Enum.update(this._enumAnimations); // change enum - setEnumAttr(this, '_animationIndex', this._enumAnimations); + setPropertyEnumType(this, '_animationIndex', this._enumAnimations); } // update armature list for editor @@ -1195,7 +1191,7 @@ export class ArmatureDisplay extends UIRenderer { Object.assign(this._enumArmatures, armatureEnum || DefaultArmaturesEnum); Enum.update(this._enumArmatures); // change enum - setEnumAttr(this, '_defaultArmatureIndex', this._enumArmatures); + setPropertyEnumType(this, '_defaultArmatureIndex', this._enumArmatures); } /** * @engineInternal Since v3.7.2 this is an engine private function. diff --git a/cocos/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts index acffa79b818..9930acd2a23 100644 --- a/cocos/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -27,6 +27,7 @@ import { EDITOR } from 'internal:constants'; import { lerp, RealCurve, CCClass, geometry, Enum, approx, EPSILON } from '../../core'; import { PixelFormat, Filter, WrapMode } from '../../asset/assets/asset-enum'; import { Texture2D, ImageAsset } from '../../asset/assets'; +import { setPropertyEnumType } from '../../core/internal-index'; const setClassAttr = CCClass.Attr.setClassAttr; @@ -262,7 +263,7 @@ export default class CurveRange { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBeforeSerialize (props): readonly ["mode", "constant", "multiplier"] | readonly ["mode", "spline", "multiplier"] | readonly ["mode", "splineMin", "splineMax", "multiplier"] | readonly ["mode", "constantMin", "constantMax", "multiplier"] { + public _onBeforeSerialize (props): readonly ['mode', 'constant', 'multiplier'] | readonly ['mode', 'spline', 'multiplier'] | readonly ['mode', 'splineMin', 'splineMax', 'multiplier'] | readonly ['mode', 'constantMin', 'constantMax', 'multiplier'] { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return SerializableTable[this._mode]; } @@ -287,8 +288,7 @@ setClassAttr(CurveRange, 'multiplier', 'visible', true); setClassAttr(CurveRange, 'constantMax', 'visible', true); setClassAttr(CurveRange, 'constantMin', 'visible', true); setClassAttr(CurveRange, 'constant', 'visible', true); -setClassAttr(CurveRange, 'mode', 'type', 'Enum'); -setClassAttr(CurveRange, 'mode', 'enumList', Enum.getList(Mode)); +setPropertyEnumType(CurveRange, 'mode', Mode); setClassAttr(CurveRange, 'mode', 'visible', true); setClassAttr(CurveRange, 'splineMax', 'type', 'Object'); setClassAttr(CurveRange, 'splineMax', 'ctor', RealCurve); diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 8d7e93570c9..8a33cd56466 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -27,7 +27,7 @@ import { Material, Texture2D } from '../asset/assets'; import { errorID, warn } from '../core/platform/debug'; import { Enum, ccenum } from '../core/value-types/enum'; import { Component, Node } from '../scene-graph'; -import { CCBoolean, CCClass, CCFloat, CCObject, Color, Mat4, RecyclePool, js } from '../core'; +import { CCBoolean, CCFloat, CCObject, Color, Mat4, RecyclePool, js } from '../core'; import { SkeletonData } from './skeleton-data'; import { UIRenderer, UITransform } from '../2d'; import { Batcher2D } from '../2d/renderer/batcher-2d'; @@ -44,6 +44,7 @@ import spine from './lib/spine-core.js'; import { VertexEffectDelegate } from './vertex-effect-delegate'; import SkeletonCache, { AnimationCache, AnimationFrame } from './skeleton-cache'; import { TrackEntryListeners } from './track-entry-listeners'; +import { setPropertyEnumType } from '../core/internal-index'; const spineTag = SPINE_WASM; const CachedFrameTime = 1 / 60; @@ -120,11 +121,6 @@ export interface SkeletonDrawData { indexCount: number; } -function setEnumAttr (obj, propName, enumDef): void { - CCClass.Attr.setClassAttr(obj, propName, 'type', 'Enum'); - CCClass.Attr.setClassAttr(obj, propName, 'enumList', Enum.getList(enumDef)); -} - /** * @en * The Sockets attached to bones, synchronous transform with spine animation. @@ -898,7 +894,7 @@ export class Skeleton extends UIRenderer { this._enumAnimations = Enum({}); Object.assign(this._enumAnimations, animEnum); Enum.update(this._enumAnimations); - setEnumAttr(this, '_animationIndex', this._enumAnimations); + setPropertyEnumType(this, '_animationIndex', this._enumAnimations); } // update skin list for editor protected _updateSkinEnum (): void { @@ -912,7 +908,7 @@ export class Skeleton extends UIRenderer { this._enumSkins = Enum({}); Object.assign(this._enumSkins, skinEnum); Enum.update(this._enumSkins); - setEnumAttr(this, '_defaultSkinIndex', this._enumSkins); + setPropertyEnumType(this, '_defaultSkinIndex', this._enumSkins); } protected _refreshInspector (): void { From deb6614a3e09162da12562ca9224c0d4ead6447d Mon Sep 17 00:00:00 2001 From: PP Date: Thu, 15 Jun 2023 15:08:26 +0800 Subject: [PATCH 006/232] fix type in node-activator.ts && component-scheduler.ts (#15444) * fix type in node-activator.ts && component-scheduler.ts * fix native node interface * fix native ts build --- cocos/core/utils/misc.ts | 5 +- cocos/scene-graph/component-scheduler.ts | 109 +++++++----- cocos/scene-graph/component.ts | 86 +++++++--- cocos/scene-graph/node-activator.ts | 207 ++++++++++++----------- cocos/scene-graph/node.jsb.ts | 4 +- cocos/scene-graph/node.ts | 7 + 6 files changed, 256 insertions(+), 162 deletions(-) diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index 359d14edf6b..1f3d7694bbf 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -31,6 +31,7 @@ import { legacyCC } from '../global-exports'; import { warnID } from '../platform/debug'; import { macro } from '../platform/macro'; import { setTimeoutRAF } from '../../../pal/utils'; +import type { Component } from '../../scene-graph'; export const BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/; @@ -179,7 +180,7 @@ export function callInNextTick (callback, p1?: any, p2?: any): void { * @returns @en A new function that will invoke `functionName` with try catch. * @zh 使用 try catch 机制调用 `functionName` 的新函数. */ -export function tryCatchFunctor_EDITOR (funcName): AnyFunction { +export function tryCatchFunctor_EDITOR (funcName: string): (comp: Component) => void { // eslint-disable-next-line @typescript-eslint/no-implied-eval return Function('target', `${'try {\n' @@ -187,7 +188,7 @@ export function tryCatchFunctor_EDITOR (funcName): AnyFunction { + `}\n` + `catch (e) {\n` + ` cc._throw(e);\n` - + `}`); + + `}`) as (comp: Component) => void; } /** diff --git a/cocos/scene-graph/component-scheduler.ts b/cocos/scene-graph/component-scheduler.ts index 52e93d51f2f..3f2fe524d39 100644 --- a/cocos/scene-graph/component-scheduler.ts +++ b/cocos/scene-graph/component-scheduler.ts @@ -28,6 +28,7 @@ import { js } from '../core'; import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; import { legacyCC } from '../core/global-exports'; import { error, assert } from '../core/platform/debug'; +import type { Component } from './component'; const fastRemoveAt = js.array.fastRemoveAt; @@ -84,21 +85,41 @@ function stableRemoveInactive (iterator, flagToClear): void { } } +type InvokeFunc = (...args: unknown[]) => void; + // This class contains some queues used to invoke life-cycle methods by script execution order export class LifeCycleInvoker { public static stableRemoveInactive = stableRemoveInactive; + /** + * @engineInternal `_zero` is a protected property, we provide this public property for engine internal usage. + */ + public get zero (): js.array.MutableForwardIterator { + return this._zero; + } + /** + * @engineInternal `_neg` is a protected property, we provide this public property for engine internal usage. + */ + public get neg (): js.array.MutableForwardIterator { + return this._neg; + } + /** + * @engineInternal `_pos` is a protected property, we provide this public property for engine internal usage. + */ + public get pos (): js.array.MutableForwardIterator { + return this._pos; + } + // components which priority === 0 (default) protected _zero: js.array.MutableForwardIterator; + // components which priority < 0 protected _neg: js.array.MutableForwardIterator; + // components which priority > 0 protected _pos: js.array.MutableForwardIterator; - protected _invoke: any; - constructor (invokeFunc) { + protected _invoke: InvokeFunc; + constructor (invokeFunc: InvokeFunc) { const Iterator = js.array.MutableForwardIterator; - // components which priority === 0 (default) this._zero = new Iterator([]); - // components which priority < 0 this._neg = new Iterator([]); - // components which priority > 0 this._pos = new Iterator([]); if (TEST) { @@ -114,17 +135,17 @@ function compareOrder (a, b): number { // for onLoad: sort once all components registered, invoke once export class OneOffInvoker extends LifeCycleInvoker { - public add (comp): void { - const order = comp.constructor._executionOrder; + public add (comp: Component): void { + const order = (comp.constructor as typeof Component)._executionOrder; (order === 0 ? this._zero : (order < 0 ? this._neg : this._pos)).array.push(comp); } - public remove (comp): void { - const order = comp.constructor._executionOrder; + public remove (comp: Component): void { + const order = (comp.constructor as typeof Component)._executionOrder; (order === 0 ? this._zero : (order < 0 ? this._neg : this._pos)).fastRemove(comp); } - public cancelInactive (flagToClear): void { + public cancelInactive (flagToClear: number): void { stableRemoveInactive(this._zero, flagToClear); stableRemoveInactive(this._neg, flagToClear); stableRemoveInactive(this._pos, flagToClear); @@ -152,8 +173,8 @@ export class OneOffInvoker extends LifeCycleInvoker { // for update: sort every time new component registered, invoke many times class ReusableInvoker extends LifeCycleInvoker { - public add (comp): void { - const order = comp.constructor._executionOrder; + public add (comp: Component): void { + const order = (comp.constructor as typeof Component)._executionOrder; if (order === 0) { this._zero.array.push(comp); } else { @@ -167,8 +188,8 @@ class ReusableInvoker extends LifeCycleInvoker { } } - public remove (comp): void { - const order = comp.constructor._executionOrder; + public remove (comp: Component): void { + const order = (comp.constructor as typeof Component)._executionOrder; if (order === 0) { this._zero.fastRemove(comp); } else { @@ -180,7 +201,7 @@ class ReusableInvoker extends LifeCycleInvoker { } } - public invoke (dt): void { + public invoke (dt: number): void { if (this._neg.array.length > 0) { this._invoke(this._neg, dt); } @@ -221,7 +242,7 @@ export function createInvokeImplJit (code: string, useDt?, ensureFlag?): (iterat return createInvokeImpl(singleInvoke, fastPath, ensureFlag); } export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?): (iterator: any, dt: any) => void { - return (iterator, dt): void => { + return (iterator, dt: number): void => { try { fastPath(iterator, dt); } catch (e) { @@ -265,10 +286,10 @@ const invokeStart = SUPPORT_JIT ? createInvokeImplJit(`c.start();c._objFlags|=${ const invokeUpdate = SUPPORT_JIT ? createInvokeImplJit('c.update(dt)', true) : createInvokeImpl( - (c, dt): void => { + (c, dt: number): void => { c.update(dt); }, - (iterator, dt): void => { + (iterator, dt: number): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].update(dt); @@ -278,10 +299,10 @@ const invokeUpdate = SUPPORT_JIT ? createInvokeImplJit('c.update(dt)', true) const invokeLateUpdate = SUPPORT_JIT ? createInvokeImplJit('c.lateUpdate(dt)', true) : createInvokeImpl( - (c, dt): void => { + (c, dt: number): void => { c.lateUpdate(dt); }, - (iterator, dt): void => { + (iterator, dt: number): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].lateUpdate(dt); @@ -364,7 +385,7 @@ export class ComponentScheduler { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onEnabled (comp): void { + public _onEnabled (comp: Component): void { legacyCC.director.getScheduler().resumeTarget(comp); comp._objFlags |= IsOnEnableCalled; @@ -379,7 +400,7 @@ export class ComponentScheduler { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onDisabled (comp): void { + public _onDisabled (comp: Component): void { legacyCC.director.getScheduler().pauseTarget(comp); comp._objFlags &= ~IsOnEnableCalled; @@ -391,13 +412,13 @@ export class ComponentScheduler { } // unschedule - if (comp.start && !(comp._objFlags & IsStartCalled)) { + if (comp.internalStart && !(comp._objFlags & IsStartCalled)) { this.startInvoker.remove(comp); } - if (comp.update) { + if (comp.internalUpdate) { this.updateInvoker.remove(comp); } - if (comp.lateUpdate) { + if (comp.internalLateUpdate) { this.lateUpdateInvoker.remove(comp); } } @@ -408,16 +429,16 @@ export class ComponentScheduler { * @param comp The component to be enabled * @param invoker The invoker which is responsible to schedule the `onEnable` call */ - public enableComp (comp, invoker?): void { + public enableComp (comp: Component, invoker?: OneOffInvoker): void { if (!(comp._objFlags & IsOnEnableCalled)) { - if (comp.onEnable) { + if (comp.internalOnEnable) { if (invoker) { invoker.add(comp); return; } else { - comp.onEnable(); + comp.internalOnEnable(); - const deactivatedDuringOnEnable = !comp.node._activeInHierarchy; + const deactivatedDuringOnEnable = !comp.node.activeInHierarchy; if (deactivatedDuringOnEnable) { return; } @@ -432,10 +453,10 @@ export class ComponentScheduler { * @zh 禁用一个组件 * @param comp The component to be disabled */ - public disableComp (comp): void { + public disableComp (comp: Component): void { if (comp._objFlags & IsOnEnableCalled) { - if (comp.onDisable) { - comp.onDisable(); + if (comp.internalOnDisable) { + comp.internalOnDisable(); } this._onDisabled(comp); } @@ -475,7 +496,7 @@ export class ComponentScheduler { * @zh 为当前注册的组件执行 update 阶段任务 * @param dt @en Time passed after the last frame in seconds @zh 距离上一帧的时间,以秒计算 */ - public updatePhase (dt:number): void { + public updatePhase (dt: number): void { this.updateInvoker.invoke(dt); } @@ -484,7 +505,7 @@ export class ComponentScheduler { * @zh 为当前注册的组件执行 late update 阶段任务 * @param dt @en Time passed after the last frame in seconds @zh 距离上一帧的时间,以秒计算 */ - public lateUpdatePhase (dt:number): void { + public lateUpdatePhase (dt: number): void { this.lateUpdateInvoker.invoke(dt); // End of this frame @@ -504,14 +525,14 @@ export class ComponentScheduler { } } - private _scheduleImmediate (comp): void { - if (typeof comp.start === 'function' && !(comp._objFlags & IsStartCalled)) { + private _scheduleImmediate (comp: Component): void { + if (typeof comp.internalStart === 'function' && !(comp._objFlags & IsStartCalled)) { this.startInvoker.add(comp); } - if (typeof comp.update === 'function') { + if (typeof comp.internalUpdate === 'function') { this.updateInvoker.add(comp); } - if (typeof comp.lateUpdate === 'function') { + if (typeof comp.internalLateUpdate === 'function') { this.lateUpdateInvoker.add(comp); } } @@ -527,9 +548,10 @@ export class ComponentScheduler { if (EDITOR) { ComponentScheduler.prototype.enableComp = function (comp, invoker): void { - if (legacyCC.GAME_VIEW || comp.constructor._executeInEditMode) { + // NOTE: _executeInEditMode is dynamically injected on Editor environment + if (legacyCC.GAME_VIEW || (comp.constructor as any)._executeInEditMode) { if (!(comp._objFlags & IsOnEnableCalled)) { - if (comp.onEnable) { + if (comp.internalOnEnable) { if (invoker) { invoker.add(comp); enableInEditor(comp); @@ -537,7 +559,7 @@ if (EDITOR) { } else { callOnEnableInTryCatch(comp); - const deactivatedDuringOnEnable = !comp.node._activeInHierarchy; + const deactivatedDuringOnEnable = !comp.node.activeInHierarchy; if (deactivatedDuringOnEnable) { return; } @@ -550,9 +572,10 @@ if (EDITOR) { }; ComponentScheduler.prototype.disableComp = function (comp): void { - if (legacyCC.GAME_VIEW || comp.constructor._executeInEditMode) { + // NOTE: _executeInEditMode is dynamically injected on Editor environment + if (legacyCC.GAME_VIEW || (comp.constructor as any)._executeInEditMode) { if (comp._objFlags & IsOnEnableCalled) { - if (comp.onDisable) { + if (comp.internalOnDisable) { callOnDisableInTryCatch(comp); } this._onDisabled(comp); diff --git a/cocos/scene-graph/component.ts b/cocos/scene-graph/component.ts index 7a359bc32de..8c24860959c 100644 --- a/cocos/scene-graph/component.ts +++ b/cocos/scene-graph/component.ts @@ -58,6 +58,16 @@ const NullNode = null as unknown as Node; class Component extends CCObject { public static EventHandler = EventHandler; + /** + * @engineInternal + */ + public static _executionOrder: number = 0; + + /** + * @engineInternal + */ + public static _requireComponent: Constructor | null = null; + get name (): string { if (this._name) { return this._name; @@ -506,6 +516,13 @@ class Component extends CCObject { */ protected update? (dt: number): void; + /** + * @engineInternal `update` is a protected property, we provide this public property for engine internal usage. + */ + public get internalUpdate (): ((dt: number) => void) | undefined { + return this.update; + } + /** * @en LateUpdate is called every frame, if the Component is enabled.
* This is a lifecycle method. It may not be implemented in the super class.
@@ -516,6 +533,13 @@ class Component extends CCObject { */ protected lateUpdate? (dt: number): void; + /** + * @engineInternal `lateUpdate` is a protected property, we provide this public property for engine internal usage. + */ + public get internalLateUpdate (): ((dt: number) => void) | undefined { + return this.lateUpdate; + } + /** * @en `__preload` is called before every onLoad.
* It is used to initialize the builtin components internally,
@@ -529,6 +553,13 @@ class Component extends CCObject { */ protected __preload? (): void; + /** + * @engineInternal `__preload` is a protected property, we provide this public property for engine internal usage. + */ + public get internalPreload (): (() => void) | undefined { + return this.__preload; + } + /** * @en * When attaching to an active node or its node first activated.
@@ -541,6 +572,13 @@ class Component extends CCObject { */ protected onLoad? (): void; + /** + * @engineInternal `onLoad` is a protected property, we provide this public property for engine internal usage. + */ + public get internalOnLoad (): (() => void) | undefined { + return this.onLoad; + } + /** * @en * Called before all scripts' update if the Component is enabled the first time.
@@ -553,6 +591,13 @@ class Component extends CCObject { */ protected start? (): void; + /** + * @engineInternal `start` is a protected property, we provide this public property for engine internal usage. + */ + public get internalStart (): (() => void) | undefined { + return this.start; + } + /** * @en Called when this component becomes enabled and its node is active.
* This is a lifecycle method. It may not be implemented in the super class. @@ -562,6 +607,13 @@ class Component extends CCObject { */ protected onEnable? (): void; + /** + * @engineInternal `onEnable` is a protected property, we provide this public property for engine internal usage. + */ + public get internalOnEnable (): (() => void) | undefined { + return this.onEnable; + } + /** * @en Called when this component becomes disabled or its node becomes inactive.
* This is a lifecycle method. It may not be implemented in the super class. @@ -571,6 +623,13 @@ class Component extends CCObject { */ protected onDisable? (): void; + /** + * @engineInternal `onDisable` is a protected property, we provide this public property for engine internal usage. + */ + public get internalOnDisable (): (() => void) | undefined { + return this.onDisable; + } + /** * @en Called when this component will be destroyed.
* This is a lifecycle method. It may not be implemented in the super class.
@@ -580,6 +639,13 @@ class Component extends CCObject { */ protected onDestroy? (): void; + /** + * @engineInternal `onDestroy` is a protected property, we provide this public property for engine internal usage. + */ + public get internalOnDestroy (): (() => void) | undefined { + return this.onDestroy; + } + public onFocusInEditor? (): void; public onLostFocusInEditor? (): void; @@ -589,7 +655,7 @@ class Component extends CCObject { * This function is only called in editor.
* @zh 用来初始化组件或节点的一些属性,当该组件被第一次添加到节点上或用户点击了它的 Reset 菜单时调用。这个回调只会在编辑器下调用。 */ - public resetInEditor? (): void; + public resetInEditor? (didResetToDefault?: boolean): void; // VIRTUAL @@ -648,25 +714,7 @@ class Component extends CCObject { protected onRestore? (): void; } -// NOTE: here we access the protected properties in Component, so we need to mark it as type of any. -const proto = Component.prototype as any; -proto.update = undefined; -proto.lateUpdate = undefined; -proto.__preload = undefined; -proto.onLoad = undefined; -proto.start = undefined; -proto.onEnable = undefined; -proto.onDisable = undefined; -proto.onDestroy = undefined; -proto.onFocusInEditor = undefined; -proto.onLostFocusInEditor = undefined; -proto.resetInEditor = undefined; -proto._getLocalBounds = undefined; -proto.onRestore = undefined; // NOTE: these are all injected properties -(Component as any)._requireComponent = null; -(Component as any)._executionOrder = 0; - if (EDITOR || TEST) { // INHERITABLE STATIC MEMBERS (Component as any)._executeInEditMode = false; diff --git a/cocos/scene-graph/node-activator.ts b/cocos/scene-graph/node-activator.ts index 4afb383cb92..357a966057b 100644 --- a/cocos/scene-graph/node-activator.ts +++ b/cocos/scene-graph/node-activator.ts @@ -31,37 +31,26 @@ import { legacyCC } from '../core/global-exports'; import { assert, errorID, getError } from '../core/platform/debug'; import { NodeEventType } from './node-event'; import { assertIsTrue } from '../core/data/utils/asserts'; +import type { Component } from './component'; +import type { Node } from './node'; const MAX_POOL_SIZE = 4; const IsPreloadStarted = CCObject.Flags.IsPreloadStarted; const IsOnLoadStarted = CCObject.Flags.IsOnLoadStarted; const IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled; +const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; const Deactivating = CCObject.Flags.Deactivating; -const callPreloadInTryCatch: any = EDITOR && tryCatchFunctor_EDITOR('__preload'); -const callOnLoadInTryCatch: any = EDITOR && function (c): void { - try { - c.onLoad(); - } catch (e) { - legacyCC._throw(e); - } - c._objFlags |= IsOnLoadCalled; - _onLoadInEditor(c); -}; -const callOnDestroyInTryCatch: any = EDITOR && tryCatchFunctor_EDITOR('onDestroy'); -const callOnFocusInTryCatch: any = EDITOR && tryCatchFunctor_EDITOR('onFocusInEditor'); -const callOnLostFocusInTryCatch: any = EDITOR && tryCatchFunctor_EDITOR('onLostFocusInEditor'); - // for __preload: used internally, no sort class UnsortedInvoker extends LifeCycleInvoker { - public add (comp): void { + public add (comp: Component): void { this._zero.array.push(comp); } - public remove (comp): void { + public remove (comp: Component): void { this._zero.fastRemove(comp); } - public cancelInactive (flagToClear): void { + public cancelInactive (flagToClear: number): void { LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear); } public invoke (): void { @@ -72,73 +61,66 @@ class UnsortedInvoker extends LifeCycleInvoker { const invokePreload = SUPPORT_JIT ? createInvokeImplJit('c.__preload();') : createInvokeImpl( - (c): void => { c.__preload(); }, - (iterator): void => { + (c: Component): void => { c.internalPreload?.(); }, + (iterator: array.MutableForwardIterator): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - array[iterator.i].__preload(); + array[iterator.i].internalPreload?.(); } }, ); const invokeOnLoad = SUPPORT_JIT ? createInvokeImplJit(`c.onLoad();c._objFlags|=${IsOnLoadCalled}`, false, IsOnLoadCalled) : createInvokeImpl( - (c): void => { - c.onLoad(); + (c: Component): void => { + c.internalOnLoad?.(); c._objFlags |= IsOnLoadCalled; }, - (iterator): void => { + (iterator: array.MutableForwardIterator): void => { const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - const comp = array[iterator.i]; - comp.onLoad(); + const comp: Component = array[iterator.i]; + comp.internalOnLoad?.(); comp._objFlags |= IsOnLoadCalled; } }, IsOnLoadCalled, ); -const activateTasksPool = new Pool(MAX_POOL_SIZE); -activateTasksPool.get = function getActivateTask (): any { - const task: any = this._get() || { +interface ActivateTask { + preload: UnsortedInvoker; + onLoad: OneOffInvoker; + onEnable: OneOffInvoker; +} + +const activateTasksPool = new Pool(MAX_POOL_SIZE); +activateTasksPool.get = function getActivateTask (): ActivateTask { + const task = this._get() || { preload: new UnsortedInvoker(invokePreload), onLoad: new OneOffInvoker(invokeOnLoad), onEnable: new OneOffInvoker(invokeOnEnable), }; // reset index to -1 so we can skip invoked component in cancelInactive - task.preload._zero.i = -1; + task.preload.zero.i = -1; let invoker = task.onLoad; - invoker._zero.i = -1; - invoker._neg.i = -1; - invoker._pos.i = -1; + invoker.zero.i = -1; + invoker.neg.i = -1; + invoker.pos.i = -1; invoker = task.onEnable; - invoker._zero.i = -1; - invoker._neg.i = -1; - invoker._pos.i = -1; + invoker.zero.i = -1; + invoker.neg.i = -1; + invoker.pos.i = -1; return task; }; -function _componentCorrupted (node, comp, index): void { +function _componentCorrupted (node: Node, comp: Component, index: number): void { errorID(3817, node.name, index); console.log('Corrupted component value:', comp); if (comp) { node._removeComponent(comp); } else { - array.removeAt(node._components, index); - } -} - -function _onLoadInEditor (comp): void { - if (comp.onLoad && !legacyCC.GAME_VIEW) { - const focused = Editor.Selection.getLastSelected('node') === comp.node.uuid; - if (focused) { - if (comp.onFocusInEditor && callOnFocusInTryCatch) { - callOnFocusInTryCatch(comp); - } - } else if (comp.onLostFocusInEditor && callOnLostFocusInTryCatch) { - callOnLostFocusInTryCatch(comp); - } + array.removeAt(node.getWritableComponents(), index); } } @@ -147,8 +129,8 @@ function _onLoadInEditor (comp): void { * @zh 用于执行节点和组件的激活和停用操作的管理器。 */ export default class NodeActivator { - public resetComp: any; - protected _activatingStack!: any[]; + public resetComp?: ((comp: Component, didResetToDefault: boolean) => void); + protected _activatingStack!: ActivateTask[]; constructor () { this.reset(); @@ -169,18 +151,20 @@ export default class NodeActivator { * @param node Target node * @param active Which state to set the node to */ - public activateNode (node, active): void { + public activateNode (node: Node, active: boolean): void { if (active) { - const task: any = activateTasksPool.get(); - this._activatingStack.push(task); + const task = activateTasksPool.get(); + if (task) { + this._activatingStack.push(task); - this._activateNodeRecursively(node, task.preload, task.onLoad, task.onEnable); - task.preload.invoke(); - task.onLoad.invoke(); - task.onEnable.invoke(); + this._activateNodeRecursively(node, task.preload, task.onLoad, task.onEnable); + task.preload.invoke(); + task.onLoad.invoke(); + task.onEnable.invoke(); - this._activatingStack.pop(); - activateTasksPool.put(task); + this._activatingStack.pop(); + activateTasksPool.put(task); + } } else { this._deactivateNodeRecursively(node); @@ -190,7 +174,7 @@ export default class NodeActivator { for (const lastTask of stack) { lastTask.preload.cancelInactive(IsPreloadStarted); lastTask.onLoad.cancelInactive(IsOnLoadStarted); - lastTask.onEnable.cancelInactive(); + lastTask.onEnable.cancelInactive(IsOnEnableCalled); } } node.emit(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, node); @@ -204,28 +188,28 @@ export default class NodeActivator { * @param onLoadInvoker The invoker for `onLoad` method, normally from [[ComponentScheduler]] * @param onEnableInvoker The invoker for `onEnable` method, normally from [[ComponentScheduler]] */ - public activateComp (comp, preloadInvoker?, onLoadInvoker?, onEnableInvoker?): void { + public activateComp (comp: Component, preloadInvoker?: UnsortedInvoker, onLoadInvoker?: OneOffInvoker, onEnableInvoker?: OneOffInvoker): void { if (!isValid(comp, true)) { // destroyed before activating return; } if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; - if (comp.__preload) { + if (comp.internalPreload) { if (preloadInvoker) { preloadInvoker.add(comp); } else { - comp.__preload(); + comp.internalPreload(); } } } if (!(comp._objFlags & IsOnLoadStarted)) { comp._objFlags |= IsOnLoadStarted; - if (comp.onLoad) { + if (comp.internalOnLoad) { if (onLoadInvoker) { onLoadInvoker.add(comp); } else { - comp.onLoad(); + comp.internalOnLoad(); comp._objFlags |= IsOnLoadCalled; } } else { @@ -236,7 +220,7 @@ export default class NodeActivator { if (DEBUG) { assertIsTrue(comp.node, getError(3823, comp.uuid, comp.name)); } - const deactivatedOnLoading = !comp.node._activeInHierarchy; + const deactivatedOnLoading = !comp.node.activeInHierarchy; if (deactivatedOnLoading) { return; } @@ -249,16 +233,16 @@ export default class NodeActivator { * @zh 销毁一个组件 * @param comp Target component */ - public destroyComp (comp): void { + public destroyComp (comp: Component): void { // ensure onDisable called legacyCC.director._compScheduler.disableComp(comp); - if (comp.onDestroy && (comp._objFlags & IsOnLoadCalled)) { - comp.onDestroy(); + if (comp.internalOnDestroy && (comp._objFlags & IsOnLoadCalled)) { + comp.internalOnDestroy(); } } - protected _activateNodeRecursively (node, preloadInvoker, onLoadInvoker, onEnableInvoker): void { + protected _activateNodeRecursively (node: Node, preloadInvoker: UnsortedInvoker, onLoadInvoker: OneOffInvoker, onEnableInvoker: OneOffInvoker): void { if (node._objFlags & Deactivating) { // en: // Forbid reactive the same node during its deactivating procedure @@ -270,14 +254,14 @@ export default class NodeActivator { return; } - node._activeInHierarchy = true; + node._setActiveInHierarchy(true); // component maybe added during onEnable, and the onEnable of new component is already called // so we should record the origin length - let originCount = node._components.length; + let originCount = node.components.length; // activate components for (let i = 0; i < originCount; ++i) { - const component = node._components[i]; + const component = node.components[i]; if (component instanceof legacyCC.Component) { this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker); } else { @@ -288,45 +272,45 @@ export default class NodeActivator { } // activate children recursively - for (let i = 0, len = node._children.length; i < len; ++i) { - const child = node._children[i]; - if (child._active) { + for (let i = 0, len = node.children.length; i < len; ++i) { + const child = node.children[i]; + if (child.active) { this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker); } } node._onPostActivated(true); } - protected _deactivateNodeRecursively (node): void { + protected _deactivateNodeRecursively (node: Node): void { if (DEV) { assert(!(node._objFlags & Deactivating), 'node should not deactivating'); // ensures _activeInHierarchy is always changing when Deactivating flagged - assert(node._activeInHierarchy, 'node should not deactivated'); + assert(node.activeInHierarchy, 'node should not deactivated'); } node._objFlags |= Deactivating; - node._activeInHierarchy = false; + node._setActiveInHierarchy(false); // component maybe added during onEnable, and the onEnable of new component is already called // so we should record the origin length - const originCount = node._components.length; + const originCount = node.components.length; for (let c = 0; c < originCount; ++c) { - const component = node._components[c]; + const component = node.components[c]; if (component._enabled) { legacyCC.director._compScheduler.disableComp(component); - if (node._activeInHierarchy) { + if (node.activeInHierarchy) { // reactivated from root node._objFlags &= ~Deactivating; return; } } } - for (let i = 0, len = node._children.length; i < len; ++i) { - const child = node._children[i]; - if (child._activeInHierarchy) { + for (let i = 0, len = node.children.length; i < len; ++i) { + const child = node.children[i]; + if (child.activeInHierarchy) { this._deactivateNodeRecursively(child); - if (node._activeInHierarchy) { + if (node.activeInHierarchy) { // reactivated from root node._objFlags &= ~Deactivating; return; @@ -340,15 +324,43 @@ export default class NodeActivator { } if (EDITOR) { - NodeActivator.prototype.activateComp = (comp, preloadInvoker, onLoadInvoker, onEnableInvoker): void => { + const callPreloadInTryCatch = tryCatchFunctor_EDITOR('__preload'); + const callOnLoadInTryCatch = function (c: Component): void { + try { + c.internalOnLoad?.(); + } catch (e) { + legacyCC._throw(e); + } + c._objFlags |= IsOnLoadCalled; + _onLoadInEditor(c); + }; + const callOnDestroyInTryCatch = tryCatchFunctor_EDITOR('onDestroy'); + const callOnFocusInTryCatch = tryCatchFunctor_EDITOR('onFocusInEditor'); + const callOnLostFocusInTryCatch = tryCatchFunctor_EDITOR('onLostFocusInEditor'); + + const _onLoadInEditor = (comp: Component): void => { + if (comp.internalOnLoad && !legacyCC.GAME_VIEW) { + const focused = Editor.Selection.getLastSelected('node') === comp.node.uuid; + if (focused) { + if (comp.onFocusInEditor && callOnFocusInTryCatch) { + callOnFocusInTryCatch(comp); + } + } else if (comp.onLostFocusInEditor && callOnLostFocusInTryCatch) { + callOnLostFocusInTryCatch(comp); + } + } + }; + + NodeActivator.prototype.activateComp = (comp: Component, preloadInvoker: UnsortedInvoker, onLoadInvoker: OneOffInvoker, onEnableInvoker: OneOffInvoker): void => { if (!isValid(comp, true)) { // destroyed before activating return; } - if (legacyCC.GAME_VIEW || comp.constructor._executeInEditMode) { + // NOTE: _executeInEditMode is dynamically injected on Editor environment + if (legacyCC.GAME_VIEW || (comp.constructor as any)._executeInEditMode) { if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; - if (comp.__preload) { + if (comp.internalPreload) { if (preloadInvoker) { preloadInvoker.add(comp); } else if (callPreloadInTryCatch) { @@ -358,7 +370,7 @@ if (EDITOR) { } if (!(comp._objFlags & IsOnLoadStarted)) { comp._objFlags |= IsOnLoadStarted; - if (comp.onLoad) { + if (comp.internalOnLoad) { if (onLoadInvoker) { onLoadInvoker.add(comp); } else if (callOnLoadInTryCatch) { @@ -374,7 +386,7 @@ if (EDITOR) { if (DEBUG) { assertIsTrue(comp.node, getError(3823, comp.uuid, comp.name)); } - const deactivatedOnLoading = !comp.node._activeInHierarchy; + const deactivatedOnLoading = !comp.node.activeInHierarchy; if (deactivatedOnLoading) { return; } @@ -382,18 +394,19 @@ if (EDITOR) { } }; - NodeActivator.prototype.destroyComp = (comp): void => { + NodeActivator.prototype.destroyComp = (comp: Component): void => { // ensure onDisable called legacyCC.director._compScheduler.disableComp(comp); - if (comp.onDestroy && (comp._objFlags & IsOnLoadCalled)) { - if (legacyCC.GAME_VIEW || comp.constructor._executeInEditMode) { + if (comp.internalOnDestroy && (comp._objFlags & IsOnLoadCalled)) { + // NOTE: _executeInEditMode is dynamically injected on Editor environment + if (legacyCC.GAME_VIEW || (comp.constructor as any)._executeInEditMode) { callOnDestroyInTryCatch && callOnDestroyInTryCatch(comp); } } }; - NodeActivator.prototype.resetComp = (comp, didResetToDefault: boolean): void => { + NodeActivator.prototype.resetComp = (comp: Component, didResetToDefault: boolean): void => { if (comp.resetInEditor) { try { comp.resetInEditor(didResetToDefault); diff --git a/cocos/scene-graph/node.jsb.ts b/cocos/scene-graph/node.jsb.ts index 4c4cb2a629f..db1a53c5b5c 100644 --- a/cocos/scene-graph/node.jsb.ts +++ b/cocos/scene-graph/node.jsb.ts @@ -346,7 +346,9 @@ nodeProto.resumeSystemEvents = function resumeSystemEvents(recursive: boolean): this._eventProcessor.setEnabled(true, recursive); }; -nodeProto.getWritableComponents = function (this: JsbNode) { return this._components; } +nodeProto.getWritableComponents = function (this: JsbNode) { return this._components; }; + +nodeProto._setActiveInHierarchy = function (this: JsbNode, v: boolean) { return this._activeInHierarchy = v; }; nodeProto._removeComponent = function (component: Component) { if (!component) { diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 2ea4eda34cf..53feee0935c 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -196,6 +196,13 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { } } + /** + * @engineInternal please don't use this method. + */ + public _setActiveInHierarchy (v: boolean): void { + this._activeInHierarchy = v; + } + /** * @en Indicates whether this node is active in the scene. * @zh 表示此节点是否在场景中激活。 From 923f8ec83c6315eb330a05d14329c1b802c5b51f Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Thu, 15 Jun 2023 16:27:52 +0800 Subject: [PATCH 007/232] Repair the problem of invalid game.end on web platform and minigame platform. (#15434) * Repair the problem of invalid game.end on web platform and minigame platform --- pal/system-info/minigame/system-info.ts | 9 ++++++++- pal/system-info/web/system-info.ts | 5 ++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/pal/system-info/minigame/system-info.ts b/pal/system-info/minigame/system-info.ts index 9e25280f29d..bb8fa7f2964 100644 --- a/pal/system-info/minigame/system-info.ts +++ b/pal/system-info/minigame/system-info.ts @@ -243,9 +243,16 @@ class SystemInfo extends EventTarget { } } - public close (): void { + public exit (): void { minigame.exitMiniProgram?.(); } + + public close (): void { + // TODO(qgh):The minigame platform does not have an exit interface, + // so there is no need to send a close message to the engine to release resources. + // this.emit('close'); + this.exit(); + } } export const systemInfo = new SystemInfo(); diff --git a/pal/system-info/web/system-info.ts b/pal/system-info/web/system-info.ts index 138e1bc4cfe..044c99eafdf 100644 --- a/pal/system-info/web/system-info.ts +++ b/pal/system-info/web/system-info.ts @@ -373,9 +373,12 @@ class SystemInfo extends EventTarget { } } + public exit (): void { + window.close(); + } + public close (): void { this.emit('close'); - window.close(); } } From f9d7a408c1b1fe8ba6d016718ad03419bbb7fa61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Mon, 26 Jun 2023 09:47:50 +0800 Subject: [PATCH 008/232] Refactor native-pack-tool/windows run logic (#15523) --- .../native-pack-tool/source/base/default.ts | 5 +++++ .../native-pack-tool/source/platforms/ios.ts | 2 +- .../source/platforms/windows.ts | 18 ++---------------- templates/cmake/common.cmake | 2 +- 4 files changed, 9 insertions(+), 18 deletions(-) diff --git a/scripts/native-pack-tool/source/base/default.ts b/scripts/native-pack-tool/source/base/default.ts index bdbb75ecf99..3f9899653dc 100644 --- a/scripts/native-pack-tool/source/base/default.ts +++ b/scripts/native-pack-tool/source/base/default.ts @@ -368,6 +368,11 @@ export abstract class NativePackTool { return /^[0-9a-zA-Z_-]+$/.test(this.params.projectName) ? this.params.projectName : 'CocosGame'; } + protected getExcutableNameOrDefault(): string { + const en = this.params.executableName; + return en ? en : this.projectNameASCII(); + } + protected async excuteTemplateTask(tasks: CocosProjectTasks) { if (tasks.appendFile) { await Promise.all(tasks.appendFile.map((task) => { diff --git a/scripts/native-pack-tool/source/platforms/ios.ts b/scripts/native-pack-tool/source/platforms/ios.ts index 41400ced239..a2f69b5f2e5 100644 --- a/scripts/native-pack-tool/source/platforms/ios.ts +++ b/scripts/native-pack-tool/source/platforms/ios.ts @@ -225,7 +225,7 @@ export class IOSPackTool extends MacOSPackTool { } readBundleId(): string | null { - const prjName = this.params.projectName!; + const prjName = this.getExcutableNameOrDefault(); const cmakeTmpDir = fs.readdirSync(ps.join(this.paths.nativePrjDir, 'CMakeFiles')) .filter((x) => x.startsWith(prjName))[0]; diff --git a/scripts/native-pack-tool/source/platforms/windows.ts b/scripts/native-pack-tool/source/platforms/windows.ts index 6f5d1792032..7c7b1435215 100644 --- a/scripts/native-pack-tool/source/platforms/windows.ts +++ b/scripts/native-pack-tool/source/platforms/windows.ts @@ -137,22 +137,8 @@ export class WindowsPackTool extends NativePackTool { async run(): Promise { const executableDir = ps.join(this.paths.nativePrjDir, this.params.debug ? 'Debug' : 'Release') - let executableFile: string; - let targetFile: string; - if (this.params.executableName) { - executableFile = ps.join(executableDir, this.params.executableName + '.exe'); - targetFile = this.params.executableName; - } else { - if (/^[0-9a-zA-Z_-]+$/.test(this.params.projectName)) { - executableFile = ps.join(executableDir, this.params.projectName + '.exe'); - targetFile = this.params.projectName; - } else { - const executableFiles = ['CocosGame', this.params.projectName].map(x => ps.join(executableDir, x + '.exe')).filter(x => fs.existsSync(x)); - executableFile = executableFiles[0]; - targetFile = 'CocosGame'; - } - } - + const targetFile = this.getExcutableNameOrDefault(); + const executableFile = ps.join(executableDir, targetFile + '.exe'); if (!executableFile || !fs.existsSync(executableFile)) { throw new Error(`[windows run] '${targetFile}' is not found within ' + ${executableDir}!`); } diff --git a/templates/cmake/common.cmake b/templates/cmake/common.cmake index 5d5e733f9c0..3f506978b8a 100644 --- a/templates/cmake/common.cmake +++ b/templates/cmake/common.cmake @@ -133,7 +133,7 @@ macro(cc_common_after_target target_name) endif() target_compile_definitions(${target_name} PRIVATE - GAME_NAME="${APP_NAME}" + GAME_NAME="${CC_EXECUTABLE_NAME}" ) if(XXTEAKEY) target_compile_definitions(${target_name} PRIVATE From 495830614a55572ae4be280b85cfcd314f119d16 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Mon, 26 Jun 2023 17:13:36 +0800 Subject: [PATCH 009/232] fix mac editbox show bug when resize (#15533) --- native/cocos/ui/edit-box/EditBox-mac.mm | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/native/cocos/ui/edit-box/EditBox-mac.mm b/native/cocos/ui/edit-box/EditBox-mac.mm index 93ce3bf04f8..e9258a31135 100644 --- a/native/cocos/ui/edit-box/EditBox-mac.mm +++ b/native/cocos/ui/edit-box/EditBox-mac.mm @@ -27,6 +27,7 @@ of this software and associated engine source code (the "Software"), a limited, #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" +#include "engine/EngineEvents.h" #import @@ -149,6 +150,9 @@ - (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultA Implementation of global helper functions. ************************************************************************/ namespace { + +static cc::events::Resize::Listener resizeListener; + void getTextInputCallback() { if (!g_textInputCallback.isUndefined()) return; @@ -241,6 +245,10 @@ void init(const cc::EditBox::ShowInfo &showInfo) { initTextView(showInfo); else initTextField(showInfo); + + resizeListener.bind([&](int /*width*/, int /*height*/ , uint32_t /*windowId*/) { + cc::EditBox::complete(); + }); } } // namespace From 02716c4a8411014052a46e89695f54e92d331839 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Tue, 27 Jun 2023 10:41:12 +0800 Subject: [PATCH 010/232] Fix the memory leak caused by excessive simultaneous playback of sound effects on the mini game platform (#15541) * Fix the memory leak caused by excessive simultaneous playback of sound effects on the mini game platform. (cherry picked from commit 4616c2482f00ecedf01a714e25449a8682793e3e) (cherry picked from commit 2ee2a1609bb3927f1cb71a0d70cf0273ab0e37da) --- pal/audio/minigame/player-minigame.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index 4df014dd367..88e03a50be9 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -56,13 +56,18 @@ export class OneShotAudioMinigame { nativeAudio.onPlay(() => { this._onPlayCb?.(); }); - nativeAudio.onEnded(() => { - this._onEndCb?.(); - nativeAudio.destroy(); - // NOTE: Type 'null' is not assignable to type 'InnerAudioContext'. - this._innerAudioContext = null as any; - }); + const endCallback = (): void => { + if (this._innerAudioContext) { + this._onEndCb?.(); + nativeAudio.destroy(); + // NOTE: Type 'null' is not assignable to type 'InnerAudioContext'. + this._innerAudioContext = null as any; + } + }; + nativeAudio.onEnded(endCallback); + nativeAudio.onStop(endCallback);//OneShotAudio can not be reused. } + public play (): void { this._innerAudioContext.play(); } @@ -240,6 +245,7 @@ export class AudioPlayerMinigame implements OperationQueueable { function fail (err): void { clearEvent(); clearTimeout(timer); + // eslint-disable-next-line no-console console.error('failed to load innerAudioContext'); reject(new Error(err)); } From f148e66fab9f99327921c8a723c9d29a58a47a72 Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 27 Jun 2023 14:21:01 +0800 Subject: [PATCH 011/232] fix compiling error --- cocos/gfx/base/define.ts | 2 +- cocos/physics/bullet/instantiated.ts | 4 ++-- cocos/profiler/profiler.ts | 4 ++-- cocos/render-scene/scene/camera.ts | 2 +- cocos/rendering/custom/web-pipeline.ts | 2 +- cocos/rendering/pipeline-scene-data.ts | 4 ++-- cocos/rendering/post-process/passes/base-pass.ts | 2 +- cocos/spine/lib/instantiated.ts | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 253b35010f5..769ade2ff90 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -992,7 +992,7 @@ export class Color { return this; } - public set (x: number, y: number, z: number, w: number) { + public set (x: number, y: number, z: number, w: number): Color { this.x = x; this.y = y; this.z = z; diff --git a/cocos/physics/bullet/instantiated.ts b/cocos/physics/bullet/instantiated.ts index bec293a67f9..92997dce5f9 100644 --- a/cocos/physics/bullet/instantiated.ts +++ b/cocos/physics/bullet/instantiated.ts @@ -77,7 +77,7 @@ function initWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise< }); } -function initAsm (resolve): void { +function initAsm (resolve, reject): void { if (CULL_ASM_JS_MODULE) { reject(getError(4601)); return; @@ -93,7 +93,7 @@ function initAsm (resolve): void { } function getImportObject (): WebAssembly.Imports { - const infoReport = (msg: any) => { console.info(msg); }; + const infoReport = (msg: any): void => { console.info(msg); }; const memory = new WebAssembly.Memory({ initial: pageCount }); const importObject = { cc: importFunc, diff --git a/cocos/profiler/profiler.ts b/cocos/profiler/profiler.ts index 22ca638b3eb..6debc3d9953 100644 --- a/cocos/profiler/profiler.ts +++ b/cocos/profiler/profiler.ts @@ -143,7 +143,7 @@ export class Profiler extends System { /** * @deprecated We have removed this private interface in version 3.8, please use the public interface get stats instead. */ - public get _stats () { + public get _stats (): IProfilerState | null { warn('Profiler._stats is deprecated, please use Profiler.stats instead.'); return this._profilerStats; } @@ -152,7 +152,7 @@ export class Profiler extends System { * @zh 获取引擎运行性能状态 * @en Get engine performance status */ - public get stats () { + public get stats (): IProfilerState | null { return this._profilerStats; } diff --git a/cocos/render-scene/scene/camera.ts b/cocos/render-scene/scene/camera.ts index 9cc2f4c9e49..31171d10aca 100644 --- a/cocos/render-scene/scene/camera.ts +++ b/cocos/render-scene/scene/camera.ts @@ -1347,7 +1347,7 @@ export class Camera { this._matProj.m14 = m3.w; } - public getClipSpaceMinz () { + public getClipSpaceMinz (): number { return this._device.capabilities.clipSpaceMinZ; } diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 6cdcabab8de..ec05c6e9ee2 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -1201,7 +1201,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild addMaterialTexture (resourceName: string, flags?: ShaderStageFlagBit | undefined): void { throw new Error('Method not implemented.'); } - addQueue (layoutName = 'default') { + addQueue (layoutName = 'default'): WebComputeQueueBuilder { if (DEBUG) { const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); diff --git a/cocos/rendering/pipeline-scene-data.ts b/cocos/rendering/pipeline-scene-data.ts index 16cc78aac60..ccee5477714 100644 --- a/cocos/rendering/pipeline-scene-data.ts +++ b/cocos/rendering/pipeline-scene-data.ts @@ -73,7 +73,7 @@ export class PipelineSceneData { * @zh 获取全局的4s标准模型 * @returns The model id */ - get standardSkinModel (): MeshRenderer | null { return this._standardSkinModel; } + get standardSkinModel (): Model | null { return this._standardSkinModel; } set standardSkinModel (val: Model | null) { this._standardSkinModel = val; } @@ -84,7 +84,7 @@ export class PipelineSceneData { * @zh 设置一个全局的4s标准模型组件 * @returns The model id */ - get standardSkinMeshRenderer () { return this._standardSkinMeshRenderer; } + get standardSkinMeshRenderer (): MeshRenderer | null { return this._standardSkinMeshRenderer; } set standardSkinMeshRenderer (val: MeshRenderer | null) { if (this._standardSkinMeshRenderer && this._standardSkinMeshRenderer !== val) { this._standardSkinMeshRenderer.clearGlobalStandardSkinObjectFlag(); diff --git a/cocos/rendering/post-process/passes/base-pass.ts b/cocos/rendering/post-process/passes/base-pass.ts index 4bc969a482e..cef4cb7942d 100644 --- a/cocos/rendering/post-process/passes/base-pass.ts +++ b/cocos/rendering/post-process/passes/base-pass.ts @@ -41,7 +41,7 @@ export function disablePostProcessForDebugView (): boolean { return debugView.singleMode as number > 0; } -export function getShadowMapSampler () { +export function getShadowMapSampler (): Sampler | null { if (!_pointSampler) { const director = cclegacy.director; const pipeline = director.root.pipeline; diff --git a/cocos/spine/lib/instantiated.ts b/cocos/spine/lib/instantiated.ts index 21718b6d67d..8efa5057e6e 100644 --- a/cocos/spine/lib/instantiated.ts +++ b/cocos/spine/lib/instantiated.ts @@ -93,7 +93,7 @@ function initAsm (): Promise { } export function waitForSpineWasmInstantiation (): Promise { - const errorReport = (msg: any): void => { console.error(msg); }; + const errorReport = (msg: any): void => { error(msg); }; if (WASM_SUPPORT_MODE === WebAssemblySupportMode.MAYBE_SUPPORT) { if (sys.hasFeature(sys.Feature.WASM)) { return initWasm(spineWasmUrl).catch(errorReport); From 491c0cf68852100255201d3301a89321ce4008d9 Mon Sep 17 00:00:00 2001 From: PP Date: Tue, 27 Jun 2023 15:56:32 +0800 Subject: [PATCH 012/232] [AOT] fix type for AOT engine (#15526) * fix type * fix readonly fix readonly * fix get/set type * fix switch type * fix eslint * update * optimize type in state-machine-eval --- .../marionette/pose-graph/instantiation.ts | 4 +-- .../state-machine/state-machine-eval.ts | 19 +++++----- cocos/animation/marionette/variable/index.ts | 4 +-- .../marionette/variable/primitive-variable.ts | 2 +- .../character-controller.ts | 4 +-- cocos/serialization/deserialize-dynamic.ts | 36 +++++++++---------- 6 files changed, 34 insertions(+), 35 deletions(-) diff --git a/cocos/animation/marionette/pose-graph/instantiation.ts b/cocos/animation/marionette/pose-graph/instantiation.ts index ff33b011e1f..0b1db72ed13 100644 --- a/cocos/animation/marionette/pose-graph/instantiation.ts +++ b/cocos/animation/marionette/pose-graph/instantiation.ts @@ -125,9 +125,9 @@ export interface PoseNodeDependencyEvaluation { evaluate(): void; } -function instantiateNode ( +function instantiateNode ( graph: PoseGraph, - node: TNode, + node: EvaluatableNode, instantiationMap: Map, linkContext: PureValueNodeLinkContext, ): RuntimeNodeEvaluation { diff --git a/cocos/animation/marionette/state-machine/state-machine-eval.ts b/cocos/animation/marionette/state-machine/state-machine-eval.ts index 7a794dd1e8d..56114bff2a1 100644 --- a/cocos/animation/marionette/state-machine/state-machine-eval.ts +++ b/cocos/animation/marionette/state-machine/state-machine-eval.ts @@ -196,7 +196,7 @@ class TopLevelStateMachineEvaluation { } } - public getCurrentClipStatuses (): Iterable { + public getCurrentClipStatuses (): Iterable> { const { _currentNode: currentNode } = this; if (currentNode.kind === NodeKind.animation) { return currentNode.getClipStatuses(currentNode.absoluteWeight); @@ -237,7 +237,7 @@ class TopLevelStateMachineEvaluation { return null; } - public getNextClipStatuses (): Iterable { + public getNextClipStatuses (): Iterable> { const { _activatedTransitions: activatedTransitions } = this; if (activatedTransitions.length === 0) { return emptyClipStatusesIterable; @@ -986,20 +986,21 @@ function createStateStatusCache (): MotionStateStatus { }; } -const emptyClipStatusesIterator: Readonly> = Object.freeze({ - next (..._args: [] | [undefined]): IteratorResult { +type ReadonlyClipStatus = Readonly; +const emptyClipStatusesIterator: Iterator = { + next (..._args: [] | [undefined]): IteratorResult { return { done: true, value: undefined, }; }, -}); +}; -const emptyClipStatusesIterable: Iterable = Object.freeze({ +const emptyClipStatusesIterable: Iterable = { [Symbol.iterator] () { return emptyClipStatusesIterator; }, -}); +}; enum NodeKind { entry, exit, any, animation, @@ -1286,7 +1287,7 @@ class VMSMEval { this._privateState.addTransition(transition); } - public getClipStatuses (baseWeight: number): Iterable { + public getClipStatuses (baseWeight: number): Iterable> { const { _source: source } = this; if (!source) { return emptyClipStatusesIterable; @@ -1357,7 +1358,7 @@ class VMSMInternalState extends EventifiedStateEval { return stateStatus; } - public getClipStatuses (baseWeight: number): Iterable { + public getClipStatuses (baseWeight: number): Iterable> { return this._container.getClipStatuses(baseWeight); } diff --git a/cocos/animation/marionette/variable/index.ts b/cocos/animation/marionette/variable/index.ts index bbe24f1e327..4a7647a7e43 100644 --- a/cocos/animation/marionette/variable/index.ts +++ b/cocos/animation/marionette/variable/index.ts @@ -23,7 +23,7 @@ */ import { VariableType, VariableTypeValueTypeMap, VarInstanceBase } from './basic'; -import { PlainVariable } from './primitive-variable'; +import { PlainVariable, PlainVariableType } from './primitive-variable'; import { TriggerVariable } from './trigger-variable'; import { Vec3Variable } from './vec3-variable'; import { QuatVariable } from './quat-variable'; @@ -50,7 +50,7 @@ export function createVariable ( case VariableType.FLOAT: case VariableType.INTEGER: case VariableType.BOOLEAN: - variable = new PlainVariable(type); + variable = new PlainVariable(type as PlainVariableType); break; case VariableType.TRIGGER: variable = new TriggerVariable(); diff --git a/cocos/animation/marionette/variable/primitive-variable.ts b/cocos/animation/marionette/variable/primitive-variable.ts index 8a166bc0077..7bf833388e3 100644 --- a/cocos/animation/marionette/variable/primitive-variable.ts +++ b/cocos/animation/marionette/variable/primitive-variable.ts @@ -3,7 +3,7 @@ import { assertIsTrue } from '../../../core'; import { ccclass, serializable } from '../../../core/data/decorators'; import { BasicVariableDescription, VariableType, createInstanceTag, VarInstanceBase, Value } from './basic'; -type PlainVariableType = VariableType.FLOAT | VariableType.INTEGER | VariableType.BOOLEAN; +export type PlainVariableType = VariableType.FLOAT | VariableType.INTEGER | VariableType.BOOLEAN; @ccclass('cc.animation.PlainVariable') export class PlainVariable { diff --git a/cocos/physics/framework/components/character-controllers/character-controller.ts b/cocos/physics/framework/components/character-controllers/character-controller.ts index a48b16c4bda..3eb87599832 100644 --- a/cocos/physics/framework/components/character-controllers/character-controller.ts +++ b/cocos/physics/framework/components/character-controllers/character-controller.ts @@ -204,7 +204,7 @@ export class CharacterController extends Eventify(Component) { return this._center; } - public set center (value: Vec3) { + public set center (value: Readonly) { if (Vec3.equals(this._center, value)) return; Vec3.copy(this._center, value); // if (this._cct) { //update cct position @@ -313,7 +313,7 @@ export class CharacterController extends Eventify(Component) { * @zh * 设置中心的世界坐标。 */ - public set centerWorldPosition (value: Vec3) { + public set centerWorldPosition (value: Readonly) { if (this._isInitialized) this._cct!.setPosition(value); } diff --git a/cocos/serialization/deserialize-dynamic.ts b/cocos/serialization/deserialize-dynamic.ts index 19e1aeb5769..c8dcd8d27c6 100644 --- a/cocos/serialization/deserialize-dynamic.ts +++ b/cocos/serialization/deserialize-dynamic.ts @@ -85,12 +85,12 @@ type AttributeFormerlySerializedAs = `${AttributeName}${typeof POSTFIX_FORMERLY_ type AttributeDefault = `${AttributeName}${typeof POSTFIX_DEFAULT}`; type AttributeType = `${AttributeName}${typeof POSTFIX_TYPE}`; type AttributeEditorOnly = `${AttributeName}${typeof POSTFIX_EDITOR_ONLY}`; -type AttrResult = { +interface AttrResult { [K: string]: typeof K extends AttributeFormerlySerializedAs ? string : typeof K extends AttributeDefault ? unknown : typeof K extends AttributeType ? AnyFunction : typeof K extends AttributeEditorOnly ? boolean : never; -}; +} function compileDeserializeJIT (self: _Deserializer, klass: CCClassConstructor): CompiledDeserializeFn { const attrs: AttrResult = CCClass.Attr.getClassAttrs(klass); @@ -287,22 +287,22 @@ type TypedArrayViewConstructorName = | 'Uint32Array' | 'Int32Array' | 'Float32Array' | 'Float64Array'; -type SerializedTypedArray = { +interface SerializedTypedArray { __id__: never; __uuid__: never; __type__: 'TypedArray'; array: number[]; ctor: TypedArrayViewConstructorName; -}; +} -type SerializedTypedArrayRef = { +interface SerializedTypedArrayRef { __id__: never; __uuid__: never; __type__: 'TypedArrayRef'; ctor: TypedArrayViewConstructorName; offset: number; length: number; -}; +} type SerializedGeneralTypedObject = { __id__: never; @@ -310,18 +310,18 @@ type SerializedGeneralTypedObject = { __type__?: NotKnownTypeTag; } & Record; -type SerializedObjectReference = { +interface SerializedObjectReference { __type__: never; __uuid__: never; __id__: number; } -type SerializedUUIDReference = { +interface SerializedUUIDReference { __type__: never; __id__: never; __uuid__: string; __expectedType__: string; -}; +} type SerializedObject = SerializedTypedArray | SerializedTypedArrayRef | SerializedGeneralTypedObject; @@ -588,12 +588,10 @@ class _Deserializer { return; } - // cSpell:words Deserializable - - type ClassicCustomizedDeserializable = { _deserialize: (content: unknown, deserializer: _Deserializer) => void; }; + interface ClassicCustomizedDeserializable { _deserialize: (content: unknown, deserializer: _Deserializer) => void; } if ((object as Partial)._deserialize) { // TODO: content check? - (object as ClassicCustomizedDeserializable)._deserialize((value as unknown as { content: unknown }).content, this); + (object as Partial)._deserialize!((value as unknown as { content: unknown }).content, this); return; } @@ -767,18 +765,18 @@ class _Deserializer { klass: SerializableClassConstructor, ): void { if (klass === cclegacy.Vec2) { - type SerializedVec2 = { x?: number; y?: number; }; + interface SerializedVec2 { x?: number; y?: number; } instance.x = (serialized as SerializedVec2).x || 0; instance.y = (serialized as SerializedVec2).y || 0; return; } else if (klass === cclegacy.Vec3) { - type SerializedVec3 = { x?: number; y?: number; z?: number; }; + interface SerializedVec3 { x?: number; y?: number; z?: number; } instance.x = (serialized as SerializedVec3).x || 0; instance.y = (serialized as SerializedVec3).y || 0; instance.z = (serialized as SerializedVec3).z || 0; return; } else if (klass === cclegacy.Color) { - type SerializedColor = { r?: number; g?: number; b?: number; a?: number; }; + interface SerializedColor { r?: number; g?: number; b?: number; a?: number; } instance.r = (serialized as SerializedColor).r || 0; instance.g = (serialized as SerializedColor).g || 0; instance.b = (serialized as SerializedColor).b || 0; @@ -786,7 +784,7 @@ class _Deserializer { instance.a = (a === undefined ? 255 : a); return; } else if (klass === cclegacy.Size) { - type SerializedSize = { width?: number; height?: number; }; + interface SerializedSize { width?: number; height?: number; } instance.width = (serialized as SerializedSize).width || 0; instance.height = (serialized as SerializedSize).height || 0; return; @@ -865,8 +863,8 @@ export function deserializeDynamic (data: SerializedData | CCON, details: Detail return res; } -export function parseUuidDependenciesDynamic (serialized: unknown): never[] { - const depends = []; +export function parseUuidDependenciesDynamic (serialized: unknown): string[] { + const depends: string[] = []; const parseDependRecursively = (data: any, out: string[]): void => { if (!data || typeof data !== 'object' || typeof data.__id__ === 'number') { return; } const uuid = data.__uuid__; From 4c0f6649604183b07c778a9767e90d9b870ce5d0 Mon Sep 17 00:00:00 2001 From: PP Date: Wed, 28 Jun 2023 11:24:40 +0800 Subject: [PATCH 013/232] [AOT] add type for AOT engine (#15527) * fix object * fix action * fix type in instantiate.ts * fix type for NodeEventProcessor node_event_processor * fix type in input.ts * fix particle system * fix color type * fix CI * add tracking issue --- cocos/core/data/object.ts | 4 +- cocos/core/math/color.ts | 8 +- cocos/input/input.ts | 2 +- cocos/particle/models/particle-batch-model.ts | 5 +- cocos/particle/particle-system.ts | 2 +- .../renderer/particle-system-renderer-base.ts | 9 +- .../renderer/particle-system-renderer-cpu.ts | 76 +++++++++-------- .../renderer/particle-system-renderer-gpu.ts | 83 ++++++++++--------- cocos/scene-graph/node-event-processor.ts | 3 +- cocos/scene-graph/node.ts | 12 +-- cocos/serialization/instantiate.ts | 33 ++++---- cocos/tween/actions/action-manager.ts | 15 ++-- 12 files changed, 139 insertions(+), 113 deletions(-) diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.ts index 0554698907e..7d0bb9c22c2 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -68,7 +68,7 @@ const PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactiva // all the hideFlags const AllHideMasks = DontSave | EditorOnly | LockedInEditor | HideInHierarchy; -const objectsToDestroy: any = []; +const objectsToDestroy: CCObject[] = []; let deferredDestroyTimer: number | null = null; function compileDestruct (obj, ctor): Function { @@ -620,7 +620,7 @@ declare namespace CCObject { * @return @en Whether it is a CCObject boolean value. @zh 是否为CCObject的布尔值。 * @engineInternal */ -export function isCCObject (object: any): boolean { +export function isCCObject (object: any): object is CCObject { return object instanceof CCObject; } diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index 63d28b2335b..d5393128af5 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -704,7 +704,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_r_unsafe (red): Color { + public _set_r_unsafe (red: number): Color { this._val = ((this._val & 0xffffff00) | red) >>> 0; return this; } @@ -712,7 +712,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_g_unsafe (green): Color { + public _set_g_unsafe (green: number): Color { this._val = ((this._val & 0xffff00ff) | (green << 8)) >>> 0; return this; } @@ -720,7 +720,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_b_unsafe (blue): Color { + public _set_b_unsafe (blue: number): Color { this._val = ((this._val & 0xff00ffff) | (blue << 16)) >>> 0; return this; } @@ -728,7 +728,7 @@ export class Color extends ValueType { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _set_a_unsafe (alpha): Color { + public _set_a_unsafe (alpha: number): Color { this._val = ((this._val & 0x00ffffff) | (alpha << 24)) >>> 0; return this; } diff --git a/cocos/input/input.ts b/cocos/input/input.ts index 8729daaa838..4cf549caa09 100644 --- a/cocos/input/input.ts +++ b/cocos/input/input.ts @@ -62,7 +62,7 @@ class InputEventDispatcher implements IEventDispatcher { } } -const pointerEventTypeMap = { +const pointerEventTypeMap: Record = { [InputEventType.MOUSE_DOWN]: InputEventType.TOUCH_START, [InputEventType.MOUSE_MOVE]: InputEventType.TOUCH_MOVE, [InputEventType.MOUSE_UP]: InputEventType.TOUCH_END, diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index 6e79584eba7..33a611473d1 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -31,6 +31,7 @@ import { Color } from '../../core'; import { scene } from '../../render-scene'; import { Particle } from '../particle'; import { Material, RenderingSubMesh } from '../../asset/assets'; +import type { PVData } from '../renderer/particle-system-renderer-cpu'; const _uvs = [ 0, 0, // bottom-left @@ -325,7 +326,7 @@ export default class ParticleBatchModel extends scene.Model { this.setSubModelMaterial(0, mat); } - public addParticleVertexData (index: number, pvdata: any[]): void { + public addParticleVertexData (index: number, pvdata: PVData): void { if (!this._useInstance) { if (!this._mesh) { let offset: number = index * this._vertAttrsFloatCount; @@ -371,7 +372,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private addParticleVertexDataIns (index: number, pvdata: any[]): void { + private addParticleVertexDataIns (index: number, pvdata: PVData): void { let offset: number = index * this._vertAttrsFloatCount; if (!this._mesh) { this._vdataF32![offset++] = pvdata[0].x; // position diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index c572b77a671..bed02d38284 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -1413,7 +1413,7 @@ export class ParticleSystem extends ModelRenderer { } // internal function - private _emit (dt): void { + private _emit (dt: number): void { // emit particles. const startDelay = this.startDelay.evaluate(0, 1)!; if (this._time > startDelay) { diff --git a/cocos/particle/renderer/particle-system-renderer-base.ts b/cocos/particle/renderer/particle-system-renderer-base.ts index d8e287843b4..64e76702973 100644 --- a/cocos/particle/renderer/particle-system-renderer-base.ts +++ b/cocos/particle/renderer/particle-system-renderer-base.ts @@ -31,9 +31,10 @@ import { Particle, IParticleModule } from '../particle'; import { RenderMode } from '../enum'; import { cclegacy } from '../../core'; import { Pass } from '../../render-scene'; +import type { ParticleSystem } from '../particle-system'; export abstract class ParticleSystemRendererBase { - protected _particleSystem: any = null; + protected _particleSystem: ParticleSystem | null = null; /** * @engineInternal */ @@ -62,7 +63,7 @@ export abstract class ParticleSystemRendererBase { return this._renderInfo!; } - public onInit (ps: Component): void { + public onInit (ps: ParticleSystem): void { this._particleSystem = ps; } @@ -93,7 +94,7 @@ export abstract class ParticleSystemRendererBase { if (this._model.scene) { this.detachFromScene(); } - this._particleSystem._getRenderScene().addModel(this._model); + this._particleSystem?._getRenderScene().addModel(this._model); } } @@ -119,7 +120,7 @@ export abstract class ParticleSystemRendererBase { } protected _initModel (): void { - if (!this._model) { + if (!this._model && this._particleSystem) { this._model = cclegacy.director.root.createModel(ParticleBatchModel); this._model!.setCapacity(this._particleSystem.capacity); this._model!.visFlags = this._particleSystem.visibility; diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index 677758a9c69..1f80596eca1 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -24,7 +24,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { builtinResMgr } from '../../asset/asset-manager'; -import { Material } from '../../asset/assets'; +import { Material, Texture2D } from '../../asset/assets'; import { AttributeName, Format, Attribute, FormatInfos } from '../../gfx'; import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat, EPSILON, approx, RecyclePool } from '../../core'; import { MaterialInstance, IMaterialInstanceInfo } from '../../render-scene/core/material-instance'; @@ -38,6 +38,7 @@ import { Pass } from '../../render-scene'; import { ParticleNoise } from '../noise'; import { NoiseModule } from '../animator/noise-module'; import { isCurveTwoValues } from '../particle-general-function'; +import type { ParticleSystem } from '../particle-system'; const _tempAttribUV = new Vec3(); const _tempWorldTrans = new Mat4(); @@ -136,20 +137,24 @@ const _matInsInfo: IMaterialInstanceInfo = { subModelIdx: 0, }; +// TODO: we should not use this type, should use a uniform array type instead. +// Tracking issue: https://github.com/cocos/cocos-engine/issues/15553 +export type PVData = [Vec3, Vec3, Vec3, Vec3, number, Vec3 | null, null]; + export default class ParticleSystemRendererCPU extends ParticleSystemRendererBase { private _defines: MacroRecord; private _trailDefines: MacroRecord; private _frameTile_velLenScale: Vec4; private _tmp_velLenScale: Vec4; private _defaultMat: Material | null = null; - private _node_scale: Vec4; - private _attrs: any[]; - private _particles: RecyclePool | null = null; + private _node_scale: Vec3; + private _attrs: PVData; + private _particles: RecyclePool | null = null; private _defaultTrailMat: Material | null = null; private _updateList: Map = new Map(); private _animateList: Map = new Map(); private _runAnimateList: IParticleModule[] = new Array(); - private _fillDataFunc: any = null; + private _fillDataFunc: ((p: Particle, idx: number, fi: number) => void) | null = null; private _uScaleHandle = 0; private _uLenHandle = 0; private _uNodeRotHandle = 0; @@ -165,8 +170,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._frameTile_velLenScale = new Vec4(1, 1, 0, 0); this._tmp_velLenScale = this._frameTile_velLenScale.clone(); - this._node_scale = new Vec4(); - this._attrs = new Array(7); + this._node_scale = new Vec3(); + this._attrs = new Array(7) as PVData; this._defines = { CC_USE_WORLD_SPACE: true, CC_USE_BILLBOARD: true, @@ -180,7 +185,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas }; } - public onInit (ps: Component): void { + public onInit (ps: ParticleSystem): void { super.onInit(ps); this._particles = new RecyclePool((): Particle => new Particle(this), 16); @@ -197,7 +202,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas public clear (): void { super.clear(); this._particles!.reset(); - if (this._particleSystem._trailModule) { + if (this._particleSystem && this._particleSystem._trailModule) { this._particleSystem._trailModule.clear(); } this.updateRenderData(); @@ -217,10 +222,10 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } public getFreeParticle (): Particle | null { - if (this._particles!.length >= this._particleSystem.capacity) { + if (this._particleSystem && this._particles!.length >= this._particleSystem.capacity) { return null; } - return this._particles!.add() as Particle; + return this._particles!.add(); } public getDefaultTrailMaterial (): any { @@ -232,6 +237,9 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private _initModuleList (): void { _anim_module.forEach((val): void => { + if (!this._particleSystem) { + return; + } const pm = this._particleSystem[val]; if (pm && pm.enable) { if (pm.needUpdate) { @@ -293,25 +301,25 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } } - private doUpdateRotation (pass): void { + private doUpdateRotation (pass: Pass): void { const mode = this._renderInfo!.renderMode; if (mode !== RenderMode.Mesh && this._alignSpace === AlignmentSpace.View) { return; } if (this._alignSpace === AlignmentSpace.Local) { - this._particleSystem.node.getRotation(_node_rot); + this._particleSystem?.node.getRotation(_node_rot); } else if (this._alignSpace === AlignmentSpace.World) { - this._particleSystem.node.getWorldRotation(_node_rot); + this._particleSystem?.node.getWorldRotation(_node_rot); } else if (this._alignSpace === AlignmentSpace.View) { // Quat.fromEuler(_node_rot, 0.0, 0.0, 0.0); _node_rot.set(0.0, 0.0, 0.0, 1.0); - const cameraLst: Camera[]|undefined = this._particleSystem.node.scene.renderScene?.cameras; + const cameraLst: Camera[] | undefined = this._particleSystem?.node.scene.renderScene?.cameras; if (cameraLst !== undefined) { for (let i = 0; i < cameraLst?.length; ++i) { const camera: Camera = cameraLst[i]; // eslint-disable-next-line max-len - const checkCamera: boolean = !EDITOR_NOT_IN_PREVIEW ? (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer : camera.name === 'Editor Camera'; + const checkCamera: boolean = !EDITOR_NOT_IN_PREVIEW ? (camera.visibility & this._particleSystem!.node.layer) === this._particleSystem!.node.layer : camera.name === 'Editor Camera'; if (checkCamera) { Quat.fromViewUp(_node_rot, camera.forward); break; @@ -331,12 +339,12 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } private doUpdateScale (pass): void { - switch (this._particleSystem.scaleSpace) { + switch (this._particleSystem?.scaleSpace) { case Space.Local: - this._particleSystem.node.getScale(this._node_scale); + this._particleSystem?.node.getScale(this._node_scale); break; case Space.World: - this._particleSystem.node.getWorldScale(this._node_scale); + this._particleSystem?.node.getWorldScale(this._node_scale); break; default: break; @@ -358,13 +366,13 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this.doUpdateRotation(pass); this._updateList.forEach((value: IParticleModule, key: string): void => { - value.update(ps._simulationSpace, _tempWorldTrans); + value.update(ps.simulationSpace, _tempWorldTrans); }); const trailModule = ps._trailModule; const trailEnable = trailModule && trailModule.enable; if (trailEnable) { - trailModule.update(); + trailModule!.update(); } const useGravity = !ps.gravityModifier.isZero(); @@ -389,7 +397,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas if (p.remainingLifetime < 0.0) { if (trailEnable) { - trailModule.removeParticle(p); + trailModule!.removeParticle(p); } this._particles!.removeAt(i); --i; @@ -429,7 +437,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas Vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. if (trailEnable) { - trailModule.animate(p, dt); + trailModule!.animate(p, dt); } } @@ -453,12 +461,12 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas for (let i = 0; i < this._particles!.length; ++i) { const p = this._particles!.data[i]; let fi = 0; - const textureModule = this._particleSystem._textureAnimationModule; + const textureModule = this._particleSystem!._textureAnimationModule; if (textureModule && textureModule.enable) { fi = p.frameIndex; } idx = i * 4; - this._fillDataFunc(p, idx, fi); + this._fillDataFunc!(p, idx, fi); } } @@ -487,9 +495,10 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas if (this._model && index === 0) { this._model.setSubModelMaterial(0, material); } - const trailModule = this._particleSystem._trailModule; - if (trailModule && trailModule._trailModel && index === 1) { - trailModule._trailModel.setSubModelMaterial(0, material); + const trailModule = this._particleSystem!._trailModule; + const trailModel = trailModule?.getModel(); + if (trailModel && index === 1) { + trailModel.setSubModelMaterial(0, material); } } @@ -637,8 +646,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas const ps = this._particleSystem; const shareMaterial = ps.sharedMaterial; if (shareMaterial != null) { - const effectName = shareMaterial._effectAsset._name; - this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); + this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0) as Texture2D; } if (ps.sharedMaterial == null && this._defaultMat == null) { @@ -653,8 +661,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._defaultMat.setProperty('mainTexture', this._renderInfo!.mainTexture); } } - const mat: Material = ps.getMaterialInstance(0) || this._defaultMat; - if (ps._simulationSpace === Space.World) { + const mat: Material = ps.getMaterialInstance(0) || this._defaultMat!; + if (ps.simulationSpace === Space.World) { this._defines[CC_USE_WORLD_SPACE] = true; } else { this._defines[CC_USE_WORLD_SPACE] = false; @@ -715,7 +723,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } else { this._trailDefines[CC_USE_WORLD_SPACE] = false; } - let mat = ps.getMaterialInstance(1); + let mat: Material | null = ps.getMaterialInstance(1); if (mat === null && this._defaultTrailMat === null) { _matInsInfo.parent = builtinResMgr.get('default-trail-material'); _matInsInfo.owner = this._particleSystem; @@ -725,7 +733,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas _matInsInfo.owner = null!; _matInsInfo.subModelIdx = 0; } - mat = mat || this._defaultTrailMat; + mat = mat || this._defaultTrailMat!; mat.recompileShaders(this._trailDefines); trailModule.updateMaterial(); } diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index 894fc246ab8..10b06d9a1ba 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -37,6 +37,7 @@ import { Pass } from '../../render-scene/core/pass'; import { packCurveRangeXYZ, packCurveRangeZ, packCurveRangeXYZW, packCurveRangeN, packCurveRangeXY } from '../animator/curve-range'; import { ParticleSystemRendererBase } from './particle-system-renderer-base'; import { Camera } from '../../render-scene/scene/camera'; +import type { ParticleSystem } from '../particle-system'; const _tempWorldTrans = new Mat4(); const _tempVec4 = new Vec4(); @@ -133,7 +134,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas private _frameTile_velLenScale: Vec4; private _unifrom_velLenScale: Vec4; private _tmp_velLenScale: Vec4; - private _node_scale: Vec4; + private _node_scale: Vec3; protected _vertAttrs: Attribute[] = []; protected _defaultMat: Material | null = null; private _particleNum = 0; @@ -162,7 +163,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._frameTile_velLenScale = new Vec4(1, 1, 0, 0); this._unifrom_velLenScale = this._frameTile_velLenScale.clone(); this._tmp_velLenScale = this._frameTile_velLenScale.clone(); - this._node_scale = new Vec4(); + this._node_scale = new Vec3(); this._defines = { CC_USE_WORLD_SPACE: true, CC_USE_BILLBOARD: true, @@ -176,7 +177,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._particleNum = 0; } - public onInit (ps: Component): void { + public onInit (ps: ParticleSystem): void { super.onInit(ps); this._setVertexAttrib(); this._initModel(); @@ -219,7 +220,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } public enableModule (name: string, val: boolean, pm: IParticleModule): void { - const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat; + const mat: Material | null = this._particleSystem?.getMaterialInstance(0) || this._defaultMat; if (!mat) { return; } @@ -231,7 +232,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } public getFreeParticle (): Particle | null { - if (this._particleNum >= this._particleSystem._capacity) { + if (this._particleSystem && this._particleNum >= this._particleSystem?.capacity) { return null; } @@ -239,7 +240,10 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } public setNewParticle (p: Particle): void { - this._model!.addGPUParticleVertexData(p, this._particleNum, this._particleSystem._time); + if (!this._particleSystem) { + return; + } + this._model!.addGPUParticleVertexData(p, this._particleNum, this._particleSystem.time); this._particleNum++; } @@ -260,14 +264,14 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } if (this._alignSpace === AlignmentSpace.Local) { - this._particleSystem.node.getRotation(_node_rot); + this._particleSystem?.node.getRotation(_node_rot); } else if (this._alignSpace === AlignmentSpace.World) { - this._particleSystem.node.getWorldRotation(_node_rot); + this._particleSystem?.node.getWorldRotation(_node_rot); } else if (this._alignSpace === AlignmentSpace.View) { // Quat.fromEuler(_node_rot, 0.0, 0.0, 0.0); _node_rot.set(0.0, 0.0, 0.0, 1.0); - const cameraLst: Camera[]|undefined = this._particleSystem.node.scene.renderScene?.cameras; - if (cameraLst !== undefined) { + const cameraLst: Camera[] | undefined = this._particleSystem?.node.scene.renderScene?.cameras; + if (cameraLst !== undefined && this._particleSystem) { for (let i = 0; i < cameraLst?.length; ++i) { const camera: Camera = cameraLst[i]; // eslint-disable-next-line max-len @@ -291,7 +295,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } private doUpdateScale (pass): void { - switch (this._particleSystem.scaleSpace) { + switch (this._particleSystem?.scaleSpace) { case Space.Local: this._particleSystem.node.getScale(this._node_scale); break; @@ -305,6 +309,9 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } public updateParticles (dt: number): number { + if (!this._particleSystem) { + return this._particleNum; + } if (EDITOR_NOT_IN_PREVIEW) { const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat; @@ -322,7 +329,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this.initShaderUniform(mat!); } - this._particleNum = this._model!.updateGPUParticles(this._particleNum, this._particleSystem._time, dt); + this._particleNum = this._model!.updateGPUParticles(this._particleNum, this._particleSystem.time, dt); this.updateShaderUniform(dt); this._model!.enabled = this._particleNum > 0; return this._particleNum; @@ -342,13 +349,16 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } public updateShaderUniform (dt: number): void { + if (!this._particleSystem) { + return; + } const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat; if (!mat) { return; } const pass = mat.passes[0]; - _tempVec4.x = this._particleSystem._time; + _tempVec4.x = this._particleSystem.time; _tempVec4.y = dt; pass.setUniform(this._uTimeHandle, _tempVec4); @@ -373,11 +383,11 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas let enable = false; // force - const forceModule = this._particleSystem._forceOvertimeModule; + const forceModule = this._particleSystem?._forceOvertimeModule; enable = forceModule ? forceModule.enable : false; this._defines[FORCE_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - const packed = packCurveRangeXYZ(this._forceTexture, this._forceData, _sample_num, forceModule.x, forceModule.y, forceModule.z); + const packed = packCurveRangeXYZ(this._forceTexture, this._forceData, _sample_num, forceModule!.x, forceModule!.y, forceModule!.z); this._forceTexture = packed.texture; this._forceData = packed.texdata; const handle = pass.getHandle('force_over_time_tex0'); @@ -385,18 +395,18 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas pass.bindSampler(binding, this._forceTexture.getGFXSampler()!); pass.bindTexture(binding, this._forceTexture.getGFXTexture()!); const spaceHandle = pass.getHandle('u_force_space'); - pass.setUniform(spaceHandle, forceModule.space); + pass.setUniform(spaceHandle, forceModule!.space); const modeHandle = pass.getHandle('u_force_mode'); pass.setUniform(modeHandle, this._forceTexture.height); } // velocity - const velocityModule = this._particleSystem._velocityOvertimeModule; + const velocityModule = this._particleSystem?._velocityOvertimeModule; enable = velocityModule ? velocityModule.enable : false; this._defines[VELOCITY_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - const packed = packCurveRangeXYZW(this._velocityTexture, this._velocityData, _sample_num, velocityModule.x, velocityModule.y, - velocityModule.z, velocityModule.speedModifier); + const packed = packCurveRangeXYZW(this._velocityTexture, this._velocityData, _sample_num, velocityModule!.x, velocityModule!.y, + velocityModule!.z, velocityModule!.speedModifier); this._velocityTexture = packed.texture; this._velocityData = packed.texdata; const handle = pass.getHandle('velocity_over_time_tex0'); @@ -404,17 +414,17 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas pass.bindSampler(binding, this._velocityTexture.getGFXSampler()!); pass.bindTexture(binding, this._velocityTexture.getGFXTexture()!); const spaceHandle = pass.getHandle('u_velocity_space'); - pass.setUniform(spaceHandle, velocityModule.space); + pass.setUniform(spaceHandle, velocityModule!.space); const modeHandle = pass.getHandle('u_velocity_mode'); pass.setUniform(modeHandle, this._velocityTexture.height); } // color module - const colorModule = this._particleSystem._colorOverLifetimeModule; + const colorModule = this._particleSystem?._colorOverLifetimeModule; enable = colorModule ? colorModule.enable : false; this._defines[COLOR_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - const packed = packGradientRange(this._colorTexture, this._colorData, _sample_num, colorModule.color); + const packed = packGradientRange(this._colorTexture, this._colorData, _sample_num, colorModule!.color); this._colorTexture = packed.texture; this._colorData = packed.texdata; const handle = pass.getHandle('color_over_time_tex0'); @@ -426,16 +436,16 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // rotation module - const roationModule = this._particleSystem._rotationOvertimeModule; + const roationModule = this._particleSystem?._rotationOvertimeModule; enable = roationModule ? roationModule.enable : false; this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { let packed; - if (roationModule.separateAxes) { + if (roationModule!.separateAxes) { // eslint-disable-next-line max-len - packed = packCurveRangeXYZ(this._rotationTexture, this._rotationData, _sample_num, roationModule.x, roationModule.y, roationModule.z); + packed = packCurveRangeXYZ(this._rotationTexture, this._rotationData, _sample_num, roationModule!.x, roationModule!.y, roationModule!.z); } else { - packed = packCurveRangeZ(this._rotationTexture, this._rotationData, _sample_num, roationModule.z); + packed = packCurveRangeZ(this._rotationTexture, this._rotationData, _sample_num, roationModule!.z); } this._rotationTexture = packed.texture; this._rotationData = packed.texdata; @@ -450,15 +460,15 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // size module - const sizeModule = this._particleSystem._sizeOvertimeModule; + const sizeModule = this._particleSystem?._sizeOvertimeModule; enable = sizeModule ? sizeModule.enable : false; this._defines[SIZE_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { let packed; - if (sizeModule.separateAxes) { - packed = packCurveRangeXYZ(this._sizeTexture, this._sizeData, _sample_num, sizeModule.x, sizeModule.y, sizeModule.z, true); + if (sizeModule!.separateAxes) { + packed = packCurveRangeXYZ(this._sizeTexture, this._sizeData, _sample_num, sizeModule!.x, sizeModule!.y, sizeModule!.z, true); } else { - packed = packCurveRangeN(this._sizeTexture, this._sizeData, _sample_num, sizeModule.size, true); + packed = packCurveRangeN(this._sizeTexture, this._sizeData, _sample_num, sizeModule!.size, true); } this._sizeTexture = packed.texture; this._sizeData = packed.texdata; @@ -473,12 +483,12 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // texture module - const textureModule = this._particleSystem._textureAnimationModule; + const textureModule = this._particleSystem?._textureAnimationModule; enable = textureModule ? textureModule.enable : false; this._defines[TEXTURE_ANIMATION_MODULE_ENABLE] = enable; if (enable) { // eslint-disable-next-line max-len - const packed = packCurveRangeXY(this._animTexture, this._animData, _sample_num, textureModule.startFrame, textureModule.frameOverTime, true); + const packed = packCurveRangeXY(this._animTexture, this._animData, _sample_num, textureModule!.startFrame, textureModule!.frameOverTime, true); this._animTexture = packed.texture; this._animData = packed.texdata; const handle = pass.getHandle('texture_animation_tex0'); @@ -487,8 +497,8 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas pass.bindTexture(binding, this._animTexture.getGFXTexture()!); const infoHandle = pass.getHandle('u_anim_info'); _tempVec4.x = this._animTexture.height; - _tempVec4.y = textureModule.numTilesX * textureModule.numTilesY; - _tempVec4.z = textureModule.cycleCount; + _tempVec4.y = textureModule!.numTilesX * textureModule!.numTilesY; + _tempVec4.z = textureModule!.cycleCount; pass.setUniform(infoHandle, _tempVec4); } @@ -572,8 +582,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas const ps = this._particleSystem; const shareMaterial = ps.sharedMaterial; if (shareMaterial !== null) { - const effectName = shareMaterial._effectAsset._name; - this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); + this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0) as Texture2D; } if (ps.sharedMaterial == null && this._defaultMat == null) { @@ -592,7 +601,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas ps.node.getWorldMatrix(_tempWorldTrans); - if (ps._simulationSpace === Space.World) { + if (ps.simulationSpace === Space.World) { this._defines[CC_USE_WORLD_SPACE] = true; } else { this._defines[CC_USE_WORLD_SPACE] = false; diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts index d86e13a8048..b2f10963fdf 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/scene-graph/node-event-processor.ts @@ -158,8 +158,7 @@ export class NodeEventProcessor { if (recursive && children.length > 0) { for (let i = 0; i < children.length; ++i) { const child = children[i]; - // NOTE: for circular reference reason, eventProcessor is typeof any, so it's OK to mark child as any - (child as any)._eventProcessor.setEnabled(value, true); + child.eventProcessor.setEnabled(value, true); } } // When a node is dispatching touch events and the node is set to disabled, diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 53feee0935c..aa7607d4aa1 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -40,6 +40,7 @@ import type { Scene } from './scene'; import { PrefabInfo, PrefabInstance } from './prefab/prefab-info'; import { NodeEventType } from './node-event'; import { Event } from '../input/types'; +import type { NodeEventProcessor } from './node-event-processor'; const Destroying = CCObject.Flags.Destroying; const DontDestroy = CCObject.Flags.DontDestroy; @@ -240,8 +241,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * * @deprecated since v3.4.0 */ - get eventProcessor (): any { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return + get eventProcessor (): NodeEventProcessor { return this._eventProcessor; } @@ -376,7 +376,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { protected _name: string; - protected _eventProcessor: any = new legacyCC.NodeEventProcessor(this); + protected _eventProcessor: NodeEventProcessor = new (legacyCC.NodeEventProcessor as typeof NodeEventProcessor)(this); protected _eventMask = 0; protected _siblingIndex = 0; @@ -1140,7 +1140,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { default: break; } - this._eventProcessor.on(type, callback, target, useCapture); + this._eventProcessor.on(type as NodeEventType, callback, target, useCapture); } /** @@ -1160,7 +1160,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * ``` */ public off (type: string, callback?: AnyFunction, target?: unknown, useCapture: any = false): void { - this._eventProcessor.off(type, callback, target, useCapture); + this._eventProcessor.off(type as NodeEventType, callback, target, useCapture); const hasListeners = this._eventProcessor.hasEventListener(type); // All listener removed @@ -1188,7 +1188,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @param target - The target (this object) to invoke the callback, can be null */ public once (type: string, callback: AnyFunction, target?: unknown, useCapture?: any): void { - this._eventProcessor.once(type, callback, target, useCapture); + this._eventProcessor.once(type as NodeEventType, callback, target, useCapture); } /** diff --git a/cocos/serialization/instantiate.ts b/cocos/serialization/instantiate.ts index e453eb2b6ef..03c0afbff18 100644 --- a/cocos/serialization/instantiate.ts +++ b/cocos/serialization/instantiate.ts @@ -27,11 +27,12 @@ import { DEV, JSB } from 'internal:constants'; import { CCObject, isCCObject, js, ValueType, jsbUtils, isCCClassOrFastDefined, getError, warn, misc, cclegacy } from '../core'; import { Prefab } from '../scene-graph/prefab'; import { Node } from '../scene-graph/node'; +import { Component } from '../scene-graph/component'; const Destroyed = CCObject.Flags.Destroyed; const PersistentMask = CCObject.Flags.PersistentMask; -const objsToClearTmpVar: any = []; // used to reset _iN$t variable +const objsToClearTmpVar: any[] = []; // used to reset _iN$t variable /** * Invoke _instantiate method if supplied. @@ -41,6 +42,10 @@ const objsToClearTmpVar: any = []; // used to reset _iN$t variable */ type CustomInstantiation = (this: T, instantiated?: T) => T; +function hasImplementedInstantiate (original: any): original is { _instantiate (...args: unknown[]): unknown } { + return typeof original._instantiate === 'function'; +} + /** * @zh 从 Prefab 实例化出新节点。 * @en Instantiate a node from the Prefab. @@ -87,7 +92,7 @@ export function instantiate (original: any, internalForce?: boolean): any { if (!cclegacy.isValid(original)) { throw new TypeError(getError(6901)); } - if (original instanceof cclegacy.Component) { + if (original instanceof Component) { warn('Should not instantiate a single cc.Component directly, you must instantiate the entire node.'); } } @@ -96,7 +101,7 @@ export function instantiate (original: any, internalForce?: boolean): any { let clone; if (isCCObject(original)) { - if (original._instantiate) { + if (hasImplementedInstantiate(original)) { cclegacy.game._isCloning = true; clone = original._instantiate(null, true); cclegacy.game._isCloning = false; @@ -226,7 +231,7 @@ function enumerateObject (obj, clone, parent): void { * @param {Object|Array} obj - the original non-nil object, typeof must be 'object' * @return {Object|Array} - the original non-nil object, typeof must be 'object' */ -function instantiateObj (obj, parent): any { +function instantiateObj (obj: TypedArray | any[] | CCObject, parent: any): any { if (obj instanceof ValueType) { return obj.clone(); } @@ -235,10 +240,10 @@ function instantiateObj (obj, parent): any { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return obj; } - let clone; + let clone: any; if (ArrayBuffer.isView(obj)) { - const len = (obj as any).length; - clone = new ((obj as any).constructor)(len); + const len = obj.length; + clone = new (obj.constructor as TypedArrayConstructor)(len); // NOTE: unknown injected property `_iN$t` (obj as any)._iN$t = clone; objsToClearTmpVar.push(obj); @@ -269,22 +274,22 @@ function instantiateObj (obj, parent): any { return null; } - const ctor = obj.constructor; + const ctor = obj.constructor as Constructor; if (isCCClassOrFastDefined(ctor)) { if (parent) { - if (parent instanceof cclegacy.Component) { - if (obj instanceof cclegacy.Node || obj instanceof cclegacy.Component) { + if (parent instanceof Component) { + if (obj instanceof Node || obj instanceof Component) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return obj; } - } else if (parent instanceof cclegacy.Node) { - if (obj instanceof cclegacy.Node) { + } else if (parent instanceof Node) { + if (obj instanceof Node) { if (!obj.isChildOf(parent)) { // should not clone other nodes if not descendant // eslint-disable-next-line @typescript-eslint/no-unsafe-return return obj; } - } else if (obj instanceof cclegacy.Component) { + } else if (obj instanceof Component) { if (obj.node && !obj.node.isChildOf(parent)) { // should not clone other component if not descendant // eslint-disable-next-line @typescript-eslint/no-unsafe-return @@ -301,11 +306,9 @@ function instantiateObj (obj, parent): any { clone = Object.create(null); } else { // unknown type - // eslint-disable-next-line @typescript-eslint/no-unsafe-return return obj; } enumerateObject(obj, clone, parent); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return return clone; } diff --git a/cocos/tween/actions/action-manager.ts b/cocos/tween/actions/action-manager.ts index ca82dd928c9..738a6416bbc 100644 --- a/cocos/tween/actions/action-manager.ts +++ b/cocos/tween/actions/action-manager.ts @@ -30,6 +30,7 @@ import { Action } from './action'; import { Node } from '../../scene-graph'; import { legacyCC } from '../../core/global-exports'; import { isCCObject } from '../../core/data/object'; +import type { ActionInterval } from './action-interval'; let ID_COUNTER = 0; @@ -39,10 +40,10 @@ let ID_COUNTER = 0; * @private */ class HashElement { - actions = []; + actions: Action[] = []; target: Record | null = null; // ccobject actionIndex = 0; - currentAction = null; // CCAction + currentAction: Action | null = null; // CCAction paused = false; lock = false; } @@ -451,14 +452,14 @@ export class ActionManager { */ update (dt: number): void { const locTargets = this._arrayTargets; - let locCurrTarget; + let locCurrTarget: HashElement; for (let elt = 0; elt < locTargets.length; elt++) { this._currentTarget = locTargets[elt]; locCurrTarget = this._currentTarget; const target = locCurrTarget.target; if (isCCObject(target) && !target.isValid) { - this.removeAllActionsFromTarget(target); + this.removeAllActionsFromTarget(target as unknown as Node); elt--; continue; } @@ -471,7 +472,7 @@ export class ActionManager { if (!locCurrTarget.currentAction) continue; // use for speed - locCurrTarget.currentAction.step(dt * (locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1)); + locCurrTarget.currentAction.step(dt * (this._isActionInternal(locCurrTarget.currentAction) ? locCurrTarget.currentAction.getSpeed() : 1)); if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) { locCurrTarget.currentAction.stop(); @@ -493,4 +494,8 @@ export class ActionManager { } } } + + private _isActionInternal (action: any): action is ActionInterval { + return typeof action._speedMethod !== 'undefined'; + } } From a0e3037ae196083b779037458174d8633a7447f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 29 Jun 2023 11:05:39 +0800 Subject: [PATCH 014/232] Add test utils: vec3, quat equality matcher and pseudo random generator (#15547) * Add test utils: vec3 equality matcher and pseudo random generator * Add Quat jest matcher * Tweak * Update --- .../pose-nodes/blend-two-pose-shared.ts | 11 ++- .../value-type-asymmetric-matchers.ts | 36 +++++++++ tests/utils/random-seed.ts | 19 +++++ tests/utils/random.ts | 75 +++++++++++++++---- 4 files changed, 120 insertions(+), 21 deletions(-) create mode 100644 tests/utils/random-seed.ts diff --git a/tests/animation/new-gen-anim/pose-graph/pose-nodes/blend-two-pose-shared.ts b/tests/animation/new-gen-anim/pose-graph/pose-nodes/blend-two-pose-shared.ts index 1493872bc4d..1a5cfec0909 100644 --- a/tests/animation/new-gen-anim/pose-graph/pose-nodes/blend-two-pose-shared.ts +++ b/tests/animation/new-gen-anim/pose-graph/pose-nodes/blend-two-pose-shared.ts @@ -4,8 +4,7 @@ import { PoseGraphType } from "../../../../../cocos/animation/marionette/pose-gr import { poseGraphOp } from "../../../../../cocos/animation/marionette/pose-graph/op"; import { PoseNode } from "../../../../../cocos/animation/marionette/pose-graph/pose-node"; import { PVNodeGetVariableFloat } from "../../../../../cocos/animation/marionette/pose-graph/pure-value-nodes/get-variable"; -import { pseudoRandomRange } from "../../../../../exports/base"; -import { createPseudoRandomGenerator01 } from "../../../../utils/random"; +import { PseudoRandomGenerator } from "../../../../utils/random"; import { BlendTwoOperator } from "../../utils/abstract-operators"; import { AnimationGraphEvalMock } from "../../utils/eval-mock"; import { createAnimationGraph } from "../../utils/factory"; @@ -42,14 +41,14 @@ export function includeTestsFor_BlendTwoPoseLike_PoseNode { - const g = createPseudoRandomGenerator01(10086); + const g = new PseudoRandomGenerator(10086); const fixture = { - initial_ratio: g(), + initial_ratio: g.range01(), - blend_input_data_1: PoseData_1tr_1aux.generate(g), + blend_input_data_1: PoseData_1tr_1aux.generate(() => g.range01()), - blend_input_data_2: PoseData_1tr_1aux.generate(g), + blend_input_data_2: PoseData_1tr_1aux.generate(() => g.range01()), }; const fillPoseGraph = (poseGraph: PoseGraph) => { diff --git a/tests/utils/matchers/value-type-asymmetric-matchers.ts b/tests/utils/matchers/value-type-asymmetric-matchers.ts index d5300ee5289..957167cdd69 100644 --- a/tests/utils/matchers/value-type-asymmetric-matchers.ts +++ b/tests/utils/matchers/value-type-asymmetric-matchers.ts @@ -1,3 +1,6 @@ +import { Quat, Vec3 } from "../../../exports/base"; +import matchers from 'expect/build/matchers'; + export { }; // https://stackoverflow.com/a/53464807 @@ -18,10 +21,43 @@ expect.extend({ }, }); +expect.extend({ + toBeCloseToVec3(actual: unknown, expected: Readonly, numDigits = 5) { + return matchers.toStrictEqual.call( + this, + actual, + expect.objectContaining({ + x: expect.toBeAround(expected.x, numDigits), + y: expect.toBeAround(expected.y, numDigits), + z: expect.toBeAround(expected.z, numDigits), + }), + ); + }, + toBeCloseToQuat(actual: unknown, expected: Readonly, numDigits = 5) { + return matchers.toStrictEqual.call( + this, + actual, + expect.objectContaining({ + x: expect.toBeAround(expected.x, numDigits), + y: expect.toBeAround(expected.y, numDigits), + z: expect.toBeAround(expected.z, numDigits), + w: expect.toBeAround(expected.w, numDigits), + }), + ); + }, +}); + declare global { namespace jest { interface Expect { toBeAround(expected: number, numDigits?: number): any; + toBeCloseToVec3(expected: Readonly, numDigits?: number): any; + toBeCloseToQuat(expected: Readonly, numDigits?: number): any; + } + + interface Matchers { + toBeCloseToVec3: (expected: Readonly, numDigits?: number) => CustomMatcherResult; + toBeCloseToQuat: (expected: Readonly, numDigits?: number) => CustomMatcherResult; } } } \ No newline at end of file diff --git a/tests/utils/random-seed.ts b/tests/utils/random-seed.ts new file mode 100644 index 00000000000..4979e2dfb63 --- /dev/null +++ b/tests/utils/random-seed.ts @@ -0,0 +1,19 @@ +import crypto from 'crypto'; +import { VERSION } from '../../exports/base'; + +export const getMagicSeed = () => { + const text = `${VERSION}: ${expect.getState().currentTestName ?? ''}`; + const sha1 = textToSha1(text); + const seed = sha1ToSeed(sha1); + return seed; +}; + +function textToSha1(text: string) { + return crypto.createHash('sha1').update(text).digest('hex'); +} + +function sha1ToSeed(sha1: string) { + const bigInt = BigInt(`0x${sha1.slice(0, 7)}`); + const signed64 = BigInt.asIntN(64, bigInt); + return Number(signed64); +} \ No newline at end of file diff --git a/tests/utils/random.ts b/tests/utils/random.ts index 9f59d6b3cf6..562cfd04212 100644 --- a/tests/utils/random.ts +++ b/tests/utils/random.ts @@ -1,18 +1,63 @@ -import { pseudoRandomRange } from "../../exports/base"; - -/** - * Creates a function which can be called infinite times, each call instance will yield pseudo random number in [0, 1]; - * @param initialSeed The seed. - * @returns The generator. - */ -export function createPseudoRandomGenerator01(initialSeed: number) { - const g = (function *(): Generator { - for (let seed = initialSeed; ; ++seed) { - yield pseudoRandomRange(seed, 0, 1); +export class PseudoRandomGenerator { + constructor(initialSeed: number) { + this._seed = initialSeed; + } + + get defaultOrder() { return this._defaultOrder } + set defaultOrder(value) { this._defaultOrder = value; } + + /** Generates number in [min, max]. */ + public range(min: number, max: number) { + if (min > max) { + throw new Error(`min should not be greater than max.`); } - })(); + return min + (max - min) * this.range01(); + } + + /** Generates number in [0, 1]. */ + public range01() { + return mulberry32(this._seed++); + } + + /** Generates number in [-1, 1]. */ + public normalized() { + return this.range(-1, 1); + } + + /** + * Generates a finite number. + * @order The order(max mag). + */ + public finite(order=this._defaultOrder) { + return this.normalized() * order; + } + + /** + * Generates a positive number. + * @order The order(max mag). + */ + public positive(order=this._defaultOrder) { + return this.range01() * order + order * 1e-6; + } + + /** + * Generates a negative number. + * @order The order(max mag). + */ + public negative(order=this._defaultOrder) { + return this.range01() * -order - order * 1e-6; + } + + private _seed = 0; + private _defaultOrder = 1e3; +} + +export { getMagicSeed } from './random-seed'; - return () => { - return g.next().value; - }; +function mulberry32(a: number) { + // https://stackoverflow.com/a/47593316 + let t = a += 0x6D2B79F5; + t = Math.imul(t ^ t >>> 15, t | 1); + t ^= t + Math.imul(t ^ t >>> 7, t | 61); + return ((t ^ t >>> 14) >>> 0) / 4294967296; } \ No newline at end of file From 324e47589e5fc7b79e258623e0b62e9272ff42b9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 30 Jun 2023 11:32:04 +0800 Subject: [PATCH 015/232] Update swig to cocos-v1.1.5 to resolve function name of glue code for overloaded constructor (#15588) --- native/external-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external-config.json b/native/external-config.json index b8d24654fab..6a3e0232e4b 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.0-11" + "checkout": "v3.8.1-1" } } From 3921bd72a391e9741c52a3e3db4d8bb291b8dd22 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Fri, 30 Jun 2023 17:15:33 +0800 Subject: [PATCH 016/232] fix editbox scale bug when node rotate (#15591) --- cocos/ui/editbox/edit-box-impl.ts | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/cocos/ui/editbox/edit-box-impl.ts b/cocos/ui/editbox/edit-box-impl.ts index 57138707eb0..3d86051898e 100644 --- a/cocos/ui/editbox/edit-box-impl.ts +++ b/cocos/ui/editbox/edit-box-impl.ts @@ -279,10 +279,9 @@ export class EditBoxImpl extends EditBoxImplBase { const transform = node._uiProps.uiTransformComp; if (transform) { Vec3.set(_vec3, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3.z); + Mat4.transform(_matrix, _matrix, _vec3); } - Mat4.transform(_matrix, _matrix, _vec3); - if (!node._uiProps.uiTransformComp) { return; } @@ -290,7 +289,6 @@ export class EditBoxImpl extends EditBoxImplBase { const camera = director.root!.batcher2D.getFirstRenderCamera(node); if (!camera) return; - // camera.getWorldToCameraMatrix(_matrix_temp); camera.node.getWorldRT(_matrix_temp); const m12 = _matrix_temp.m12; const m13 = _matrix_temp.m13; @@ -298,22 +296,29 @@ export class EditBoxImpl extends EditBoxImplBase { _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13); _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13); - Mat4.multiply(_matrix_temp, _matrix_temp, _matrix); scaleX /= dpr; scaleY /= dpr; - const container = game.container; - const a = _matrix_temp.m00 * scaleX; - const b = _matrix.m01; - const c = _matrix.m04; - const d = _matrix_temp.m05 * scaleY; + Vec3.set(_vec3, scaleX, scaleY, 1); + Mat4.scale(_matrix_temp, _matrix_temp, _vec3); + const container = game.container; let offsetX = parseInt((container && container.style.paddingLeft) || '0'); offsetX += viewport.x / dpr; let offsetY = parseInt((container && container.style.paddingBottom) || '0'); offsetY += viewport.y / dpr; - const tx = _matrix_temp.m12 * scaleX + offsetX; - const ty = _matrix_temp.m13 * scaleY + offsetY; + _matrix_temp.m12 += offsetX; + _matrix_temp.m13 += offsetY; + + Mat4.multiply(_matrix_temp, _matrix_temp, _matrix); + + const a = _matrix_temp.m00; + const b = _matrix_temp.m01; + const c = _matrix_temp.m04; + const d = _matrix_temp.m05; + + const tx = _matrix_temp.m12; + const ty = _matrix_temp.m13; const matrix = `matrix(${a},${-b},${-c},${d},${tx},${-ty})`; this._edTxt.style.transform = matrix; From cf843a11026cc162ece35c2d63572fce6e1472c3 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Mon, 3 Jul 2023 10:18:40 +0800 Subject: [PATCH 017/232] support taa mask (#15592) support taa mask --- .../post-process/components/taa-mask.ts | 43 +++++++++++++++++++ .../rendering/post-process/passes/taa-pass.ts | 40 ++++++++++++++--- .../effects/pipeline/post-process/taa.effect | 7 +-- 3 files changed, 82 insertions(+), 8 deletions(-) create mode 100644 cocos/rendering/post-process/components/taa-mask.ts diff --git a/cocos/rendering/post-process/components/taa-mask.ts b/cocos/rendering/post-process/components/taa-mask.ts new file mode 100644 index 00000000000..8f257576696 --- /dev/null +++ b/cocos/rendering/post-process/components/taa-mask.ts @@ -0,0 +1,43 @@ +import { RenderTexture } from '../../../asset/assets'; +import { warn } from '../../../core'; +import { property } from '../../../core/data/class-decorator'; +import { ccclass, menu } from '../../../core/data/decorators'; +import { game } from '../../../game'; +import { Camera } from '../../../misc'; +import { Component } from '../../../scene-graph'; + +@ccclass('TAAMask') +@menu('PostProcess/TAAMask') +export class TAAMask extends Component { + @property(Camera) + maskCamera: Camera | undefined; + + _mask: RenderTexture | undefined; + + get mask () { + if (!this.maskCamera || !this.maskCamera.enabledInHierarchy) { + return undefined; + } + if (!this.enabledInHierarchy) { + return undefined; + } + + return this._mask; + } + + start () { + if (!this.maskCamera) { + warn('Can not find a Camera for TAAMask'); + return; + } + + const tex = new RenderTexture(); + tex.reset({ + width: game.canvas!.width, + height: game.canvas!.height, + }); + + this._mask = tex; + this.maskCamera.targetTexture = tex; + } +} diff --git a/cocos/rendering/post-process/passes/taa-pass.ts b/cocos/rendering/post-process/passes/taa-pass.ts index e228ae34869..8ac1904eefc 100644 --- a/cocos/rendering/post-process/passes/taa-pass.ts +++ b/cocos/rendering/post-process/passes/taa-pass.ts @@ -7,9 +7,13 @@ import { Pipeline } from '../../custom/pipeline'; import { ResourceResidency } from '../../custom/types'; import { getCameraUniqueID } from '../../custom/define'; import { TAA } from '../components/taa'; +import { TAAMask } from '../components/taa-mask'; import { passContext } from '../utils/pass-context'; import { disablePostProcessForDebugView } from './base-pass'; import { getSetting, SettingPass } from './setting-pass'; +import { builtinResMgr } from '../../../asset/asset-manager'; +import { Material, RenderTexture, Texture2D } from '../../../asset/assets'; +import { MaterialInstance } from '../../../render-scene'; const tempVec4 = new Vec4(); @@ -95,6 +99,8 @@ export class TAAPass extends SettingPass { forceRender = true; dirty = false; + taaMaskMaterial: Material | undefined; + checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) { @@ -156,8 +162,6 @@ export class TAAPass extends SettingPass { passContext.clearFlag = ClearFlagBit.COLOR; Vec4.set(passContext.clearColor, 0, 0, 0, 1); - passContext.material = this.material; - const firstRender = this.firstRender; if (firstRender) { this.prevMatViewProj.set(camera.matViewProj); @@ -170,11 +174,37 @@ export class TAAPass extends SettingPass { const width = passContext.passViewport.width; const height = passContext.passViewport.height; - this.material.setProperty('taaParams1', tempVec4.set(this.sampleOffset.x, this.sampleOffset.y, setting.feedback, 0)); - this.material.setProperty('taaTextureSize', tempVec4.set(1 / width, 1 / height, 1 / width, 1 / height)); - this.material.setProperty('taaPrevViewProj', this.prevMatViewProj); + let material: Material = this.material; + const taaMask = camera.node.getComponent(TAAMask); + let maskTex: Texture2D | RenderTexture | undefined; + if (taaMask! && taaMask.enabledInHierarchy) { + maskTex = taaMask.mask; + } + if (maskTex) { + if (!this.taaMaskMaterial) { + const mi = new MaterialInstance({ + parent: material, + }); + mi.recompileShaders({ + USE_TAA_MASK: !EDITOR, + }); + this.taaMaskMaterial = mi; + } + material = this.taaMaskMaterial; + material.setProperty('motionMaskTex', maskTex); + } else { + const black = builtinResMgr.get('black-texture'); + maskTex = black as Texture2D; + material.setProperty('motionMaskTex', maskTex); + } + + material.setProperty('taaParams1', tempVec4.set(this.sampleOffset.x, this.sampleOffset.y, setting.feedback, 0)); + material.setProperty('taaTextureSize', tempVec4.set(1 / width, 1 / height, 1 / width, 1 / height)); + material.setProperty('taaPrevViewProj', this.prevMatViewProj); this.prevMatViewProj.set(camera.matViewProj); + passContext.material = material; + // input output const input0 = this.lastPass!.slotName(camera, 0); let historyTexture = super.slotName(camera, this.taaTextureIndex % 2); diff --git a/editor/assets/effects/pipeline/post-process/taa.effect b/editor/assets/effects/pipeline/post-process/taa.effect index 1067e579cb9..b7ae1196e92 100644 --- a/editor/assets/effects/pipeline/post-process/taa.effect +++ b/editor/assets/effects/pipeline/post-process/taa.effect @@ -52,6 +52,10 @@ CCProgram fs %{ vec4 taaParams1; // xy: offset, z: feedback mat4 taaPrevViewProj; }; + + #pragma rate motionMaskTex + uniform highp sampler2D motionMaskTex; + #pragma rate inputTexture pass uniform sampler2D inputTexture; #pragma rate depthTex pass @@ -59,9 +63,6 @@ CCProgram fs %{ #pragma rate taaPrevTexture pass uniform sampler2D taaPrevTexture; - #pragma rate motionMaskTex - uniform highp sampler2D motionMaskTex; - // screen position (0-1) vec3 screen2WS(vec3 screenPos) { vec4 ndc = vec4(screenPos.xyz * 2. - 1.0, 1.0); From ea695c2ae1cdc3aad25b17e281da134d1f75049a Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Mon, 3 Jul 2023 13:38:13 +0800 Subject: [PATCH 018/232] Fix widget bug in the editor when scale is not 1 (#15545) * Fix widget bug in the editor when scale is not 1 * fix scale to 0 * change to approx --- cocos/ui/widget-manager.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/cocos/ui/widget-manager.ts b/cocos/ui/widget-manager.ts index 9ea367517f1..f07c233f2dc 100644 --- a/cocos/ui/widget-manager.ts +++ b/cocos/ui/widget-manager.ts @@ -26,7 +26,7 @@ import { EDITOR, DEV } from 'internal:constants'; import { screenAdapter } from 'pal/screen-adapter'; import { Director, director } from '../game/director'; -import { Vec2, Vec3, visibleRect, js, cclegacy } from '../core'; +import { Vec2, Vec3, visibleRect, js, cclegacy, approx, EPSILON } from '../core'; import { View } from './view'; import { Scene } from '../scene-graph'; import { Node } from '../scene-graph/node'; @@ -124,6 +124,11 @@ function align (node: Node, widget: Widget): void { } else { x = localRight + (anchorX - 1) * width; } + if (!approx(scaleX, 0, EPSILON)) { + width /= scaleX; + } else { + width = uiTrans.width; + } } widget._lastSize.width = width; @@ -182,6 +187,11 @@ function align (node: Node, widget: Widget): void { } else { y = localTop + (anchorY - 1) * height; } + if (!approx(scaleY, 0, EPSILON)) { + height /= scaleY; + } else { + height = uiTrans.height; + } } widget._lastSize.height = height; From 1d85b949254364ded63db76ca3ac8d6c156605fa Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Wed, 5 Jul 2023 11:20:24 +0800 Subject: [PATCH 019/232] All games, mini-programs, and runtime platforms with onWindowResize need to listen to it. (#15617) * All games, mini-programs, and runtime platforms with onWindowResize need to listen to it. --- pal/screen-adapter/minigame/screen-adapter.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/pal/screen-adapter/minigame/screen-adapter.ts b/pal/screen-adapter/minigame/screen-adapter.ts index 77d10f3bc57..f95deecca7e 100644 --- a/pal/screen-adapter/minigame/screen-adapter.ts +++ b/pal/screen-adapter/minigame/screen-adapter.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { ALIPAY, BAIDU, BYTEDANCE, COCOSPLAY, RUNTIME_BASED, VIVO, WECHAT, WECHAT_MINI_PROGRAM } from 'internal:constants'; +import { ALIPAY, BYTEDANCE, COCOSPLAY, VIVO } from 'internal:constants'; import { minigame } from 'pal/minigame'; import { ConfigOrientation, IScreenOptions, SafeAreaEdge } from 'pal/screen-adapter'; import { systemInfo } from 'pal/system-info'; @@ -155,12 +155,9 @@ class ScreenAdapter extends EventTarget { constructor () { super(); - // TODO: onResize or onOrientationChange is not supported well - if (WECHAT || WECHAT_MINI_PROGRAM || RUNTIME_BASED) { - minigame.onWindowResize?.(() => { - this.emit('window-resize', this.windowSize.width, this.windowSize.height); - }); - } + minigame.onWindowResize?.(() => { + this.emit('window-resize', this.windowSize.width, this.windowSize.height); + }); } public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { From b3eeaba86bcfb6347002f794ec68ddda077a39fe Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Thu, 6 Jul 2023 09:48:47 +0800 Subject: [PATCH 020/232] add constrain for wechat logo default ratio (#15627) * add constrain for wechat logo default ratio --- templates/wechatgame/first-screen.ejs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/templates/wechatgame/first-screen.ejs b/templates/wechatgame/first-screen.ejs index c172c69c2bb..1e25ee187fe 100644 --- a/templates/wechatgame/first-screen.ejs +++ b/templates/wechatgame/first-screen.ejs @@ -179,9 +179,10 @@ function initProgressVertexBuffer() { } function updateVertexBuffer() { - // the ratio value may be adjusted according to the expected image display effect - const widthRatio = image.width / canvas.width * 1.35 * displayRatio; - const heightRatio = image.height / canvas.height * 1.35 * displayRatio; + // By default, maintain aspect ratio by constraining display at 200px height + const defaultRatio = 200 / image.height; + const widthRatio = image.width / canvas.width * 1.35 * defaultRatio * displayRatio; + const heightRatio = image.height / canvas.height * 1.35 * defaultRatio * displayRatio; const heightOffset = 1/6; // canvas:(-1,1) -> (button, top); heightOffset = (5/12) * (-2) + 1 = 1/6 const vertices = new Float32Array([ widthRatio, heightOffset - heightRatio, 1.0, 1.0, From 083e3b284d1b0070f41fb6e330042ed3183b1510 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Thu, 6 Jul 2023 12:40:26 +0800 Subject: [PATCH 021/232] [fix] physx rigid body sleep issues (#15625) * [fix] physx rigid body sleep issues * tweaks --- cocos/physics/physx/physx-rigid-body.ts | 12 ++++++++---- native/cocos/physics/physx/PhysXRigidBody.cpp | 11 +++++++---- platforms/native/engine/jsb-physics.js | 1 + 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/cocos/physics/physx/physx-rigid-body.ts b/cocos/physics/physx/physx-rigid-body.ts index ccc9353763d..1213d620e89 100644 --- a/cocos/physics/physx/physx-rigid-body.ts +++ b/cocos/physics/physx/physx-rigid-body.ts @@ -62,6 +62,7 @@ export class PhysXRigidBody implements IRigidBody { this._rigidBody = v; this._sharedBody = (PhysicsSystem.instance.physicsWorld as PhysXWorld).getSharedBody(v.node, this); this._sharedBody.reference = true; + this.setSleepThreshold(PhysicsSystem.instance.sleepThreshold); } onEnable (): void { @@ -134,8 +135,7 @@ export class PhysXRigidBody implements IRigidBody { setAllowSleep (v: boolean): void { if (this.isStaticOrKinematic) return; - const st = this.impl.getSleepThreshold() as number; - const wc = v ? Math.max(0.0, st - 0.001) : st + 0xffffffff; + const wc = v ? 0.0001 : 0xffffffff; this.impl.setWakeCounter(wc); } @@ -167,12 +167,16 @@ export class PhysXRigidBody implements IRigidBody { setSleepThreshold (v: number): void { if (this.isStatic) return; - this.impl.setSleepThreshold(v); + //(approximated) mass-normalized kinetic energy + const ke = 0.5 * v * v; + this.impl.setSleepThreshold(ke); } getSleepThreshold (): number { if (this.isStatic) return 0; - return this.impl.getSleepThreshold(); + const ke = this.impl.getSleepThreshold(); + const v = Math.sqrt(2 * ke); + return v; } getLinearVelocity (out: IVec3Like): void { diff --git a/native/cocos/physics/physx/PhysXRigidBody.cpp b/native/cocos/physics/physx/PhysXRigidBody.cpp index 90e6725213c..0fe35d4ddf8 100644 --- a/native/cocos/physics/physx/PhysXRigidBody.cpp +++ b/native/cocos/physics/physx/PhysXRigidBody.cpp @@ -121,8 +121,7 @@ void PhysXRigidBody::setAngularFactor(float x, float y, float z) { void PhysXRigidBody::setAllowSleep(bool v) { if (!getSharedBody().isDynamic()) return; - PxReal st = getSharedBody().getImpl().rigidDynamic->getSleepThreshold(); - PxReal wc = v ? std::max(0.F, st - 0.001F) : FLT_MAX; + PxReal wc = v ? 0.0001F : FLT_MAX; getSharedBody().getImpl().rigidDynamic->setWakeCounter(wc); } @@ -153,11 +152,15 @@ void PhysXRigidBody::clearVelocity() { void PhysXRigidBody::setSleepThreshold(float v) { if (getSharedBody().isStatic()) return; - getSharedBody().getImpl().rigidDynamic->setSleepThreshold(v); + //(approximated) mass-normalized kinetic energy + float ke = 0.5F * v * v; + getSharedBody().getImpl().rigidDynamic->setSleepThreshold(ke); } float PhysXRigidBody::getSleepThreshold() { - return getSharedBody().getImpl().rigidDynamic->getSleepThreshold(); + float ke = getSharedBody().getImpl().rigidDynamic->getSleepThreshold(); + float v = sqrtf(2.F * ke); + return v; } cc::Vec3 PhysXRigidBody::getLinearVelocity() { diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index 31310609783..bd7beb5c0c2 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -428,6 +428,7 @@ class RigidBody { this._com = v; this._impl.initialize(v.node, v.type, v._group); bookNode(v.node); + this._impl.setSleepThreshold(cc.PhysicsSystem.instance.sleepThreshold); } onEnable () { From ff40e7402e4a911808690ce827e2493de7c4c434 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 6 Jul 2023 14:34:03 +0800 Subject: [PATCH 022/232] Tweak deserialization code (#15630) * Tweak deserialization code --- cocos/serialization/deserialize-dynamic.ts | 52 ++++++++++++---------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/cocos/serialization/deserialize-dynamic.ts b/cocos/serialization/deserialize-dynamic.ts index c8dcd8d27c6..9b26fd27be5 100644 --- a/cocos/serialization/deserialize-dynamic.ts +++ b/cocos/serialization/deserialize-dynamic.ts @@ -100,7 +100,7 @@ function compileDeserializeJIT (self: _Deserializer, klass: CCClassConstructor): CompiledDeserializeFn { - const fastMode = misc.BUILTIN_CLASSID_RE.test(js.getClassId(klass)); + const fastMode = canBeDeserializedInFastMode(klass); const shouldCopyId = js.isChildClassOf(klass, cclegacy.Node) || js.isChildClassOf(klass, cclegacy.Component); let shouldCopyRawData = false; @@ -206,18 +197,11 @@ function compileDeserializeNative (_self: _Deserializer, klass: CCClassConstruct // function undefined object(null) string boolean number const defaultValue = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]); const userType = attrs[propName + POSTFIX_TYPE] as AnyFunction | string | undefined; - let isPrimitiveType = false; + let isPrimitiveTypeInFastMode = false; if (fastMode && (defaultValue !== undefined || userType)) { - if (defaultValue === undefined) { - isPrimitiveType = userType instanceof CCClass.Attr.PrimitiveType || userType === ENUM_TAG || userType === BITMASK_TAG; - } else { - const defaultType = typeof defaultValue; - isPrimitiveType = defaultType === 'string' - || defaultType === 'number' - || defaultType === 'boolean'; - } + isPrimitiveTypeInFastMode = isPrimitivePropertyByDefaultOrType(defaultValue, userType); } - if (fastMode && isPrimitiveType) { + if (isPrimitiveTypeInFastMode) { if (propNameToRead !== propName && simplePropsToRead === simpleProps) { simplePropsToRead = simpleProps.slice(); } @@ -281,6 +265,28 @@ function compileDeserializeNative (_self: _Deserializer, klass: CCClassConstruct }; } +/** + * Tells if the class can be deserialized in "fast mode". + * In fast mode, deserialization of the class will go into an optimized way: + * each class property will be examined whether to be primitive according to their default value + * and type. Finally, all primitive properties would be together deserialized using simple assignment, + * without performing in-loop check. + */ +function canBeDeserializedInFastMode (klass: any): boolean { + return misc.BUILTIN_CLASSID_RE.test(js.getClassId(klass)); +} + +function isPrimitivePropertyByDefaultOrType (defaultValue: any, userType: any): boolean { + if (defaultValue === undefined) { + return userType instanceof CCClass.Attr.PrimitiveType || userType === ENUM_TAG || userType === BITMASK_TAG; + } else { + const defaultType = typeof defaultValue; + return defaultType === 'string' + || defaultType === 'number' + || defaultType === 'boolean'; + } +} + type TypedArrayViewConstructorName = | 'Uint8Array' | 'Int8Array' | 'Uint16Array' | 'Int16Array' From a3ee06e374a947fa8ff45e707fb5065c94dd811c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 6 Jul 2023 18:00:03 +0800 Subject: [PATCH 023/232] Optimize unit test; support overriding constants in per-test-suite (#15628) * Optimize unit test; support overriding constants in per-test-suite --- tests/init.ts | 21 +++++++++++-- tests/test-environment.ts | 31 +++++++++++++------ tests/utils/test-suite-config.test.ts | 8 +++++ .../test-suite-config.test.ts.config.json | 6 ++++ tests/utils/test-suite-config.ts | 14 +++++++++ 5 files changed, 67 insertions(+), 13 deletions(-) create mode 100644 tests/utils/test-suite-config.test.ts create mode 100644 tests/utils/test-suite-config.test.ts.config.json create mode 100644 tests/utils/test-suite-config.ts diff --git a/tests/init.ts b/tests/init.ts index 15d492a8966..6f321dca9f2 100644 --- a/tests/init.ts +++ b/tests/init.ts @@ -1,6 +1,18 @@ jest.mock( 'internal:constants', - () => jest.requireActual('./constants-for-test'), + () => { + const actual = jest.requireActual('./constants-for-test'); + const { getCurrentTestSuiteConfig } = jest.requireActual('./utils/test-suite-config') as + typeof import('./utils/test-suite-config'); + const config = getCurrentTestSuiteConfig(); + if (!config.constantOverrides) { + return actual; + } + return { + ...actual, + ...config.constantOverrides, + }; + }, { virtual: true, }, ); @@ -171,7 +183,8 @@ const config: IGameConfig = { } } } -globalThis.waitThis((async () => { + +async function bootstrap() { game.on(Game.EVENT_POST_SUBSYSTEM_INIT, () => { effects.forEach((e, effectIndex) => { const effect = Object.assign(new EffectAsset(), e); @@ -190,4 +203,6 @@ globalThis.waitThis((async () => { initBuiltinPhysicsMaterial(); await game.init(config); await game.run(); -})()); +} + +module.exports = bootstrap; diff --git a/tests/test-environment.ts b/tests/test-environment.ts index 1b8afc3cad6..07ad7b32714 100644 --- a/tests/test-environment.ts +++ b/tests/test-environment.ts @@ -1,25 +1,36 @@ import JSDOMEnvironment from 'jest-environment-jsdom'; +import fs from 'fs-extra'; +import type { TestSuiteConfig } from './utils/test-suite-config'; class Environment extends JSDOMEnvironment { constructor(...args: ConstructorParameters) { super(...args); - const promises = this._promises; - Object.defineProperty(this.global, 'waitThis', { - get: () => { - return (promise: Promise) => { - promises.push(promise); - }; - }, - }); + const [_, context] = args; + this._testPath = context.testPath; + + this.global.__cc_test__ = { + currentTestSuiteConfig: {}, + }; + this._readTestSuiteConfig(); } async setup(...args: Parameters) { await super.setup(...args); - await Promise.all(this._promises); } - private _promises: Promise[] = []; + private _testPath: string; + + private _readTestSuiteConfig() { + const configPath = `${this._testPath}.config.json`; + if (!fs.pathExistsSync(configPath)) { + return; + } + const config = fs.readJsonSync(configPath) as TestSuiteConfig; + this.global.__cc_test__ = { + currentTestSuiteConfig: config, + }; + } } export default Environment; \ No newline at end of file diff --git a/tests/utils/test-suite-config.test.ts b/tests/utils/test-suite-config.test.ts new file mode 100644 index 00000000000..37be32da23b --- /dev/null +++ b/tests/utils/test-suite-config.test.ts @@ -0,0 +1,8 @@ +/// + +import { SUPPORT_JIT, BUILD } from 'internal:constants'; + +test(`Constant overrides`, () => { + expect(SUPPORT_JIT).toBe(true); + expect(BUILD).toBe(true); +}); \ No newline at end of file diff --git a/tests/utils/test-suite-config.test.ts.config.json b/tests/utils/test-suite-config.test.ts.config.json new file mode 100644 index 00000000000..0b434439bd2 --- /dev/null +++ b/tests/utils/test-suite-config.test.ts.config.json @@ -0,0 +1,6 @@ +{ + "constantOverrides": { + "SUPPORT_JIT": true, + "BUILD": true + } +} \ No newline at end of file diff --git a/tests/utils/test-suite-config.ts b/tests/utils/test-suite-config.ts new file mode 100644 index 00000000000..2e1d3dbad4e --- /dev/null +++ b/tests/utils/test-suite-config.ts @@ -0,0 +1,14 @@ + +export interface TestSuiteConfig { + constantOverrides?: Record; +} + +declare global { + namespace __cc_test__ { + let currentTestSuiteConfig: TestSuiteConfig; + } +} + +export function getCurrentTestSuiteConfig() { + return __cc_test__.currentTestSuiteConfig; +} From 79bec572f9055373575e8576ae8a2f81e76e930a Mon Sep 17 00:00:00 2001 From: PP Date: Fri, 7 Jul 2023 16:06:58 +0800 Subject: [PATCH 024/232] [AOT] fix: crash when setting uniform of particle system (#15639) * [AOT] fix: crash when setting uniform of particle system * update note --- .../renderer/particle-system-renderer-cpu.ts | 14 +++++++++----- .../renderer/particle-system-renderer-gpu.ts | 14 +++++++++----- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index 1f80596eca1..524d9ba9805 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -26,7 +26,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { builtinResMgr } from '../../asset/asset-manager'; import { Material, Texture2D } from '../../asset/assets'; import { AttributeName, Format, Attribute, FormatInfos } from '../../gfx'; -import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat, EPSILON, approx, RecyclePool } from '../../core'; +import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat, EPSILON, approx, RecyclePool, warn } from '../../core'; import { MaterialInstance, IMaterialInstanceInfo } from '../../render-scene/core/material-instance'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { AlignmentSpace, RenderMode, Space } from '../enum'; @@ -40,6 +40,7 @@ import { NoiseModule } from '../animator/noise-module'; import { isCurveTwoValues } from '../particle-general-function'; import type { ParticleSystem } from '../particle-system'; +const _tempNodeScale = new Vec4(); const _tempAttribUV = new Vec3(); const _tempWorldTrans = new Mat4(); const _tempParentInverse = new Mat4(); @@ -339,17 +340,20 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } private doUpdateScale (pass): void { + const nodeScale = this._node_scale; switch (this._particleSystem?.scaleSpace) { case Space.Local: - this._particleSystem?.node.getScale(this._node_scale); + this._particleSystem?.node.getScale(nodeScale); break; case Space.World: - this._particleSystem?.node.getWorldScale(this._node_scale); + this._particleSystem?.node.getWorldScale(nodeScale); break; default: break; } - pass.setUniform(this._uScaleHandle, this._node_scale); + // NOTE: the `_node_scale` should be a Vec3, but we implement `scale` uniform property as a Vec4, + // here we pass a temperate Vec4 object to prevent creating Vec4 object every time we set uniform. + pass.setUniform(this._uScaleHandle, _tempNodeScale.set(nodeScale.x, nodeScale.y, nodeScale.z)); } private noise: ParticleNoise = new ParticleNoise(); @@ -688,7 +692,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } else if (renderMode === RenderMode.Mesh) { this._defines[CC_RENDER_MODE] = RENDER_MODE_MESH; } else { - console.warn(`particle system renderMode ${renderMode} not support.`); + warn(`particle system renderMode ${renderMode} not support.`); } const textureModule = ps._textureAnimationModule; if (textureModule && textureModule.enable) { diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index 10b06d9a1ba..a01785aec24 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -27,7 +27,7 @@ import { builtinResMgr } from '../../asset/asset-manager'; import { Material, Texture2D } from '../../asset/assets'; import { Component } from '../../scene-graph'; import { AttributeName, Format, Attribute, API, deviceManager, FormatInfos } from '../../gfx'; -import { Mat4, Vec2, Vec4, Quat, Vec3 } from '../../core'; +import { Mat4, Vec2, Vec4, Quat, Vec3, warn } from '../../core'; import { MaterialInstance, IMaterialInstanceInfo } from '../../render-scene/core/material-instance'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { AlignmentSpace, RenderMode, Space } from '../enum'; @@ -39,6 +39,7 @@ import { ParticleSystemRendererBase } from './particle-system-renderer-base'; import { Camera } from '../../render-scene/scene/camera'; import type { ParticleSystem } from '../particle-system'; +const _tempNodeScale = new Vec4(); const _tempWorldTrans = new Mat4(); const _tempVec4 = new Vec4(); const _world_rot = new Quat(); @@ -295,17 +296,20 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } private doUpdateScale (pass): void { + const nodeScale = this._node_scale; switch (this._particleSystem?.scaleSpace) { case Space.Local: - this._particleSystem.node.getScale(this._node_scale); + this._particleSystem.node.getScale(nodeScale); break; case Space.World: - this._particleSystem.node.getWorldScale(this._node_scale); + this._particleSystem.node.getWorldScale(nodeScale); break; default: break; } - pass.setUniform(pass.getHandle('scale'), this._node_scale); + // NOTE: the `_node_scale` should be a Vec3, but we implement `scale` uniform property as a Vec4, + // here we pass a temperate Vec4 object to prevent creating Vec4 object every time we set uniform. + pass.setUniform(pass.getHandle('scale'), _tempNodeScale.set(nodeScale.x, nodeScale.y, nodeScale.z)); } public updateParticles (dt: number): number { @@ -620,7 +624,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } else if (renderMode === RenderMode.Mesh) { this._defines[CC_RENDER_MODE] = RENDER_MODE_MESH; } else { - console.warn(`particle system renderMode ${renderMode} not support.`); + warn(`particle system renderMode ${renderMode} not support.`); } const textureModule = ps._textureAnimationModule; if (textureModule && textureModule.enable) { From cc35a6107521fae4441e8b4828654e43e2cc9739 Mon Sep 17 00:00:00 2001 From: PP Date: Mon, 10 Jul 2023 09:31:14 +0800 Subject: [PATCH 025/232] fix: crash on OH 4.0 (#15656) --- cocos/rendering/index.jsb.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/cocos/rendering/index.jsb.ts b/cocos/rendering/index.jsb.ts index 09a150ae3f2..f107345680b 100644 --- a/cocos/rendering/index.jsb.ts +++ b/cocos/rendering/index.jsb.ts @@ -25,6 +25,7 @@ declare const nr: any; declare const jsb: any; +import { OPEN_HARMONY } from 'internal:constants' import { ccenum, CCString, js } from '../core'; import * as pipeline from './define'; import { ccclass, serializable, editable, type } from '../core/data/class-decorator'; @@ -447,9 +448,11 @@ function proxyArrayAttributeImpl(proto: any, attr: string): void { let proxyArrayAttribute = proxyArrayAttributeImpl; -proxyArrayAttribute(RenderFlow.prototype, '_stages'); - -proxyArrayAttribute(RenderPipeline.prototype, '_flows'); +if (!OPEN_HARMONY) { + // WORKAROUND: the proxy array getLength crashed on OH platform + proxyArrayAttribute(RenderFlow.prototype, '_stages'); + proxyArrayAttribute(RenderPipeline.prototype, '_flows'); +} //-------------------- register types -------------------- From f608d9840e6ebb36cb73ab13dd79b9d108687d60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 10 Jul 2023 10:10:32 +0800 Subject: [PATCH 026/232] Prevent jest from transforming physics external module (#15653) --- jest.config.js | 1 + 1 file changed, 1 insertion(+) diff --git a/jest.config.js b/jest.config.js index 63dc9fdeaba..b354e77476d 100644 --- a/jest.config.js +++ b/jest.config.js @@ -14,6 +14,7 @@ module.exports = { // ignore everything in the node_modules EXCEPT for: // - @cocos/dragonbones-js 'node_modules/(?!(@cocos/dragonbones-js)/)', + 'native/external/emscripten/', ], setupFilesAfterEnv: [ "./tests/setup-after-env.ts", From 47694d591d02997b6f4147e66384e1d6dd5a6705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 10 Jul 2023 16:14:07 +0800 Subject: [PATCH 027/232] Animation: fix ExoticVectorLikeTrackValues field serialization (#15507) --- cocos/animation/exotic-animation/exotic-animation.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos/animation/exotic-animation/exotic-animation.ts b/cocos/animation/exotic-animation/exotic-animation.ts index 5d8433f91b6..96db72a57aa 100644 --- a/cocos/animation/exotic-animation/exotic-animation.ts +++ b/cocos/animation/exotic-animation/exotic-animation.ts @@ -209,7 +209,6 @@ type MayBeQuantized = FloatArray | QuantizedFloatArray; class ExoticVectorLikeTrackValues { constructor (values: FloatArray) { this._values = values; - this._isQuantized = false; } get precision (): FloatPrecision { @@ -240,7 +239,7 @@ class ExoticVectorLikeTrackValues { protected _values: MayBeQuantized; @serializable - protected _isQuantized: boolean; + protected _isQuantized = false; } @ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticVec3TrackValues`) From dd55b22ef8d1a1866c34257e409a2277cb20b00c Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Mon, 10 Jul 2023 18:17:35 +0800 Subject: [PATCH 028/232] fix wechat videoplayer pause&stop&play bug (#15668) * fix wechat videoplayer pause&stop&play bug --- .../minigame/platforms/wechat/wrapper/engine/VideoPlayer.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js b/platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js index a99009be010..74aec0f29f3 100644 --- a/platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js +++ b/platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js @@ -291,7 +291,11 @@ if (cc.internal.VideoPlayer) { let self = this; let video = this._video; if (!video || !this._visible) return; - + // HACK: this is to unify inconsistent behavior (on Android, video won't play from begin if called pause() before called stop(). + // but if called play() before stop(), video will play from begin.) of wechat official interface on Android & iOS. + if (!this._playing) { + video.play(); + } video.stop().then(function (res) { if (res.errMsg && !res.errMsg.includes('ok')) { console.error('failed to stop video player'); From 09f83b4d03cebb241fed081305d393ec3c52f1f0 Mon Sep 17 00:00:00 2001 From: Knox Date: Tue, 11 Jul 2023 16:16:36 +0800 Subject: [PATCH 029/232] Optimization of user warnings when checking "Use Baked Animation. (#15612) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 勾选use baked animation时的用户警告优化 * 更新 i18n --- editor/i18n/en/components.js | 5 +++ editor/i18n/zh/components.js | 5 +++ editor/inspector/components.js | 1 + .../components/skeletal-animation.js | 44 +++++++++++++++++++ 4 files changed, 55 insertions(+) create mode 100644 editor/inspector/components/skeletal-animation.js diff --git a/editor/i18n/en/components.js b/editor/i18n/en/components.js index 4f416c12844..6f2d6c36cc0 100644 --- a/editor/i18n/en/components.js +++ b/editor/i18n/en/components.js @@ -1,6 +1,11 @@ module.exports = { components: { add_component: 'Add Component', + + animation: { + use_baked_animation_tips: 'When a skeleton animation is pre-baked, its bones do not move in real-time. If you need to attach external nodes to specific bone joints, it is recommended to use Sockets System .', + }, + safe_area: { brief_help: 'This component is used to adjust the layout of current node to respect the safe area of a notched mobile device such as the iPhone X.' + diff --git a/editor/i18n/zh/components.js b/editor/i18n/zh/components.js index 1c4a299cfb5..c0b0768836e 100644 --- a/editor/i18n/zh/components.js +++ b/editor/i18n/zh/components.js @@ -1,6 +1,11 @@ module.exports = { components: { add_component: '添加组件', + + animation: { + use_baked_animation_tips: '使用预烘焙动画,骨骼在运行时不会实时移动,如需将某些外部节点挂到指定的骨骼关节上,请使用 Sockets 挂点系统。', + }, + safe_area: { brief_help: '该组件会将所在节点的布局适配到 iPhone X 等异形屏手机的安全区域内,通常用于 UI 交互区域的顶层节点。该组件将在真机上将自动生效,在编辑器下没有效果。', diff --git a/editor/inspector/components.js b/editor/inspector/components.js index 86992b073df..37fd3598924 100644 --- a/editor/inspector/components.js +++ b/editor/inspector/components.js @@ -12,6 +12,7 @@ module.exports = { 'cc.SafeArea': join(__dirname, './components/safe-area.js'), 'cc.ScrollView': join(__dirname, './components/scroll-view.js'), 'cc.SkinnedMeshBatchRenderer': join(__dirname, './components/batched-skinning-model.js'), + 'cc.SkeletalAnimation': join(__dirname, './components/skeletal-animation.js'), 'cc.SphereLight': join(__dirname, './components/sphere-light.js'), 'cc.SpotLight': join(__dirname, './components/spot-light.js'), 'cc.PointLight': join(__dirname, './components/point-light.js'), diff --git a/editor/inspector/components/skeletal-animation.js b/editor/inspector/components/skeletal-animation.js new file mode 100644 index 00000000000..b16843d80e9 --- /dev/null +++ b/editor/inspector/components/skeletal-animation.js @@ -0,0 +1,44 @@ +const { template, $, update } = require('./base'); + +exports.template = template; +exports.$ = $; +exports.update = update; + +exports.style = ` + .use_baked_animation_tips { + color: #707070; + } + .use_baked_animation_tips_hidden { + display: none; + } +`; + +function updateTipsState(parent, hidden) { + let tips = parent.getElementsByClassName('use_baked_animation_tips')[0]; + if (!tips) { + tips = document.createElement('ui-label'); + tips.value = `i18n:ENGINE.components.animation.use_baked_animation_tips`; + tips.classList.add('use_baked_animation_tips', 'use_baked_animation_tips_hidden'); + parent.appendChild(tips); + } + if (hidden) { + tips.classList.add('use_baked_animation_tips_hidden'); + } else { + tips.classList.remove('use_baked_animation_tips_hidden'); + } + return tips; +} + +exports.elements = { + useBakedAnimation: { + update(element, dump) { + updateTipsState(element, !dump.useBakedAnimation.value); + } + } +}; + +exports.ready = function() { + this.elements = exports.elements; +}; + +exports.close = function() {} From ddc19f1228198c1e0f1cf9d525e39eb408524096 Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Tue, 11 Jul 2023 18:38:34 +0800 Subject: [PATCH 030/232] Remove useless code (#15670) * remove unused data * refine --- cocos/2d/renderer/render-data.ts | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index 00c7f211c3c..1efde4633ab 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -256,7 +256,7 @@ export class RenderData extends BaseRenderData { this.syncRender2dBuffer(); } - get data ():IRenderData[] { + get data (): IRenderData[] { return this._data; } @@ -304,10 +304,6 @@ export class RenderData extends BaseRenderData { public hashDirty = true; private _data: IRenderData[] = []; - private _pivotX = 0; - private _pivotY = 0; - private _width = 0; - private _height = 0; private _frame: SpriteFrame | TextureBase | null = null; protected _accessor: StaticVBAccessor = null!; get accessor (): StaticVBAccessor { return this._accessor; } @@ -495,26 +491,9 @@ export class RenderData extends BaseRenderData { } } - public updateSizeNPivot (width: number, height: number, pivotX: number, pivotY: number): void { - if (width !== this._width - || height !== this._height - || pivotX !== this._pivotX - || pivotY !== this._pivotY) { - this._width = width; - this._height = height; - this._pivotX = pivotX; - this._pivotY = pivotY; - this.vertDirty = true; - } - } - public clear (): void { this.resize(0, 0); this._data.length = 0; - this._pivotX = 0; - this._pivotY = 0; - this._width = 0; - this._height = 0; this.indices = null; this.vertDirty = true; this.material = null; @@ -810,5 +789,3 @@ export class MeshRenderData extends BaseRenderData { } } } - -const _meshDataPool: RecyclePool = new RecyclePool(() => new MeshRenderData(), 32); From 3c963bb94f69222d28cf18850a15a38cebc6aed6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Wed, 12 Jul 2023 09:15:51 +0800 Subject: [PATCH 031/232] optimize inspector interface when edit node (#15679) * optimize inspector interface * move up or down component, keep its expand state --- editor/inspector/contributions/asset.css | 4 + editor/inspector/contributions/node.css | 224 +++++++++------- editor/inspector/contributions/node.js | 311 ++++++++++++----------- editor/inspector/utils/prop.js | 4 + 4 files changed, 303 insertions(+), 240 deletions(-) diff --git a/editor/inspector/contributions/asset.css b/editor/inspector/contributions/asset.css index 3fe39a8b9cb..b2f571b24f1 100644 --- a/editor/inspector/contributions/asset.css +++ b/editor/inspector/contributions/asset.css @@ -130,3 +130,7 @@ top: 0; z-index: 1; } + +:host([type="asset"][sub-type="unknown"]) { + display: none; +} diff --git a/editor/inspector/contributions/node.css b/editor/inspector/contributions/node.css index 512c63d5536..556c6af9bbd 100644 --- a/editor/inspector/contributions/node.css +++ b/editor/inspector/contributions/node.css @@ -4,11 +4,33 @@ overflow: hidden; } +:host([type="node"][sub-type='scene']) > .container > .body > .node, +:host([type="node"][sub-type='scene']) > .container > .body > .section-header, +:host([type="node"][sub-type='scene']) > .container > .body > .section-body, +:host([type="node"][sub-type='scene']) > .container > .body > .section-footer, +:host([type="node"][sub-type='scene']) > .container > .body > .section-missing, +:host([type="node"][sub-type='scene']) > .container > .body > .footer, +:host([type="node"][sub-type='scene']) > .container > .body > .section-asset { + display: none; +} + +:host([type="node"][sub-type='scene']) > .container > .body > .scene { + display: block; +} + +:host([type="node"][sub-type='node']) > .container > .body > .node { + display: block; +} + .container { flex: 1; display: flex; flex-direction: column; - overflow: auto; + overflow: hidden; +} + +.container[hidden] { + display: none; } .container[hoving] { @@ -16,196 +38,214 @@ outline-offset: -2px; } -.prefab { +.container > .header { + display: flex; + flex-direction: column; + border-bottom: solid 1px var(--color-normal-fill-emphasis); + margin-bottom: -1px; +} + +.container > .header > .prefab { display: flex; padding: 4px 4px 0 4px; } -.prefab[hidden] { +.container > .header > .prefab[hidden] { display: none; } -.prefab > ui-label { +.container > .header > .prefab > ui-label { flex: 1; color: var(--color-success-fill); } -.prefab > ui-button { +.container > .header > .prefab > ui-button { padding: 0 8px; margin-left: 4px; } -.prefab[missing] > ui-label { +.container > .header > .prefab[missing] > ui-label { color: var(--color-danger-fill); } -.header { - display: none; +.container > .header > .node { + display: flex; + flex: 1; margin: 4px 4px 4px 0; } -.header > .active { +.container > .header > .node > .active { width: 20px; } -.header > .name, -.component-header .name { +.container > .header > .node > .name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.scene { - display: none; - border-top: solid 1px var(--color-normal-border); +.container > .body { + flex: 1; + display: flex; + flex-direction: column; + overflow: auto; + padding-bottom: 8px; } -.scene ui-prop[ui-section-config], -.scene ui-section.config { - margin-top: 0; +.container > .body .component .component-header { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + margin-right: 2px; +} + +.container > .body .component .component-header .active { + margin-right: 4px; } -.scene ui-prop[ui-section-config] ui-section.config [slot="header"] { +.container > .body .component .component-header ui-drag-item { flex: 1; - justify-content: space-between; - margin-right: 2px; } -.scene .envmap .envmap-prop ui-prop { - margin-top: 0; - margin-left: 0; +.container > .body .component .component-header .name { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } -:host([type="node"][sub-type='scene']) > .container > .scene { - display: block; +.container > .body .component .component-header > .menu, +.container > .body .component .component-header > .link { + padding: 0 2px; } -:host([sub-type='scene']) > .container > .prefab, -:host([sub-type='scene']) > .container > .node, -:host([sub-type='scene']) > .container > .section-header, -:host([sub-type='scene']) > .container > .section-body, -:host([sub-type='scene']) > .container > .section-footer, -:host([sub-type='scene']) > .container > .section-missing, -:host([sub-type='scene']) > .container > .footer { - display: none; +.container > .body .component .component-header > .menu { + opacity: 0.8; } -.section-missing:not(:empty) { - margin-top: 10px; - border-top: 1px solid var(--color-normal-border); +.container > .body .component .component-header > .menu:hover { + opacity: 1; } -.section-missing > section { - display: flex; - padding: 0 10px; +.container > .body .component .component-header > .link { + display: none; } -.section-missing > section:hover { - background-color: var(--color-hover-fill-normal); +.container > .body .component .component-header > .link[value] { + display: inline-block; } -.section-missing .name { - flex: 1; - color: var(--color-normal-contrast-emphasis); +.container > .body .component ui-prop { + margin-top: 4px; } -.section-missing .name span { - text-decoration: line-through; +.container > .body .component ui-prop [slot='label'] { + overflow: hidden; + text-overflow: ellipsis; } -.section-missing > section > ui-icon { - margin: 0 0 0 10px; - cursor: pointer; +.container > .body > .scene { display: none; + border-top: solid 1px var(--color-normal-border); } -.section-missing > section:hover > ui-icon { - display: inline-block; +.container > .body > .scene ui-prop[ui-section-config], +.container > .body > .scene ui-section.config { + margin-top: 0; } -.section-missing > section > ui-icon:hover { - color: var(--color-focus-fill-weakest); +.container > .body > .scene ui-prop[ui-section-config]:last-child { + border-bottom: solid 1px var(--color-normal-fill-emphasis); } -.node .layer-content { - display: flex; +.container > .body > .scene ui-prop[ui-section-config] ui-section.config [slot="header"] { + flex: 1; + justify-content: space-between; + margin-right: 2px; } -.node .layer-content > .layer-select { - flex: 1; - margin: 0; +.container > .body > .scene .envmap .envmap-prop ui-prop { + margin-top: 0; + margin-left: 0; } -.node .layer-content > .layer-edit { - margin-left: 4px; +.container > .body > .scene > .skybox { + margin-top: 4px; } -:host([sub-type='node']) > .container > .node { - display: block; +.container > .body > .scene > .skybox > [slot="header"] { + justify-content: space-between; } -.component .component-header { - flex: 1; - min-width: 0; +.container > .body > .node .layer-content { display: flex; - align-items: center; - margin-right: 2px; } -.component .component-header ui-drag-item { +.container > .body > .node .layer-content > .layer-select { flex: 1; + margin: 0; } -.component .component-header > .menu, -.component .component-header > .link { - padding: 0 2px; +.container > .body > .node .layer-content > .layer-edit { + margin-left: 4px; } -.component .component-header > .menu { - opacity: 0.8; +.container > .body > .section-body ui-section.config:last-child { + border-bottom: solid 1px var(--color-normal-fill-emphasis); } -.component .component-header > .menu:hover { - opacity: 1; +.container > .body > .section-missing:not(:empty) { + margin-top: 10px; + border-top: 1px solid var(--color-normal-border); } -.component .component-header > .link { - display: none; +.container > .body > .section-missing > section { + display: flex; + padding: 0 10px; } -.component .component-header > .link[value] { - display: inline-block; +.container > .body > .section-missing > section:hover { + background-color: var(--color-hover-fill-normal); } -.scene .skybox, -.component ui-prop { - margin-top: 4px; +.container > .body > .section-missing .name { + flex: 1; + color: var(--color-normal-contrast-emphasis); } -.scene .skybox > [slot="header"] { - justify-content: space-between; +.container > .body > .section-missing .name span { + text-decoration: line-through; } -.component ui-prop [slot='label'] { - overflow: hidden; - text-overflow: ellipsis; +.container > .body > .section-missing > section > ui-icon { + margin: 0 0 0 10px; + cursor: pointer; + display: none; } -.footer { - display: none; +.container > .body > .section-missing > section:hover > ui-icon { + display: inline-block; +} + +.container > .body > .section-missing > section > ui-icon:hover { + color: var(--color-focus-fill-weakest); +} + +.container > .body > .footer { margin: 20px 0; text-align: center; } -.footer .add-component { +.container > .body > .footer .add-component { padding: 0 24px; } -.section-asset { +.container > .body > .section-asset { margin-bottom: 16px; } -.section-asset:empty { +.container > .body > .section-asset:empty { display: none; } diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index c4a16000369..fb0dbce8e80 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -312,162 +312,167 @@ exports.listeners = { exports.template = /* html*/` -

-
- - + + +
+ + +
-
- - - -
- Skybox - - - -
-
- - - - - - - - - - - - - - +
+
+ + + +
+ Skybox + + + +
+
+ + + + + + + + + + + + + + + + + + Reflection Convolution +
+ + + +
- - - Reflection Convolution -
- - - -
-
+
+
-
+ + + + +
+ + +
+ Node + + + + +
+ + + + + + + +
+ + Edit +
+
+
- - - - -
- -
- Node - - - - -
- - - - - - - -
- - Edit -
-
-
-
- -
-
- -
- - - -
- -
+
+
+ +
+ + + +
+ +
+
`; exports.style = fs.readFileSync(path.join(__dirname, './node.css'), 'utf8'); exports.$ = { container: '.container', - - prefab: '.prefab', - prefabUnlink: '.prefab > [role="unlink"]', - prefabLocal: '.prefab > [role="local"]', - prefabReset: '.prefab > [role="reset"]', - prefabSave: '.prefab > [role="save"]', - prefabEdit: '.prefab > [role="edit"]', - - header: '.header', - active: '.active', - name: '.name', - - scene: '.scene', - sceneRelease: '.scene > .release', - sceneAmbient: '.scene > .ambient', - sceneFog: '.scene > .fog', - sceneShadows: '.scene > .shadows', - sceneSkybox: '.scene > .skybox', - sceneSkyboxBefore: '.scene > .skybox > .before', - sceneSkyboxUseHDR: '.scene > .skybox .useHDR', - sceneSkyboxEnvmapHDR: '.scene > .skybox .envmapHDR', - sceneSkyboxEnvmapLDR: '.scene > .skybox .envmapLDR', - sceneSkyboxReflection: '.scene > .skybox .reflection', - sceneSkyboxReflectionLoading: '.scene > .skybox .reflection ui-loading', - sceneSkyboxReflectionBake: '.scene > .skybox .reflection .bake', - sceneSkyboxReflectionRemove: '.scene > .skybox .reflection .remove', - sceneSkyboxAfter: '.scene > .skybox > .after', - sceneOctree: '.scene > .octree', - sceneSkin: '.scene > .skin', - - node: '.node', - nodeHeader: '.node > header', - nodeSection: '.node-section', - nodeMenu: '.node > header > .menu', - nodeLink: '.node > header > .link', - - nodePosition: '.node > .position', - nodeRotation: '.node > .rotation', - nodeScale: '.node > .scale', - nodeMobility: '.node > .mobility', - nodeLayerSelect: '.node > .layer .layer-select', - nodeLayerButton: '.node > .layer .layer-edit', - - sectionBody: '.section-body', - sectionMissing: '.section-missing', - sectionAsset: '.section-asset', - - footer: '.footer', - componentAdd: '.footer .add-component', + header: '.container > .header', + body: '.container > .body', + + prefab: '.container > .header > .prefab', + prefabUnlink: '.container > .header > .prefab > [role="unlink"]', + prefabLocal: '.container > .header > .prefab > [role="local"]', + prefabReset: '.container > .header > .prefab > [role="reset"]', + prefabSave: '.container > .header > .prefab > [role="save"]', + prefabEdit: '.container > .header > .prefab > [role="edit"]', + + active: '.container > .header > .node > .active', + name: '.container > .header > .node > .name', + + scene: '.container > .body > .scene', + sceneRelease: '.container > .body > .scene > .release', + sceneAmbient: '.container > .body > .scene > .ambient', + sceneFog: '.container > .body > .scene > .fog', + sceneShadows: '.container > .body > .scene > .shadows', + sceneSkybox: '.container > .body > .scene > .skybox', + sceneSkyboxBefore: '.container > .body > .scene > .skybox > .before', + sceneSkyboxUseHDR: '.container > .body > .scene > .skybox .useHDR', + sceneSkyboxEnvmapHDR: '.container > .body > .scene > .skybox .envmapHDR', + sceneSkyboxEnvmapLDR: '.container > .body > .scene > .skybox .envmapLDR', + sceneSkyboxReflection: '.container > .body > .scene > .skybox .reflection', + sceneSkyboxReflectionLoading: '.container > .body > .scene > .skybox .reflection ui-loading', + sceneSkyboxReflectionBake: '.container > .body > .scene > .skybox .reflection .bake', + sceneSkyboxReflectionRemove: '.container > .body > .scene > .skybox .reflection .remove', + sceneSkyboxAfter: '.container > .body > .scene > .skybox > .after', + sceneOctree: '.container > .body > .scene > .octree', + sceneSkin: '.container > .body > .scene > .skin', + + node: '.container > .body > .node', + nodeHeader: '.container > .body > .node > .component-header', + nodeSection: '.container > .body > .node >.node-section', + nodeMenu: '.container > .body > .node > .component-header > .menu', + nodeLink: '.container > .body > .node > .component-header > .link', + + nodePosition: '.container > .body > .node > .position', + nodeRotation: '.container > .body > .node > .rotation', + nodeScale: '.container > .body > .node > .scale', + nodeMobility: '.container > .body > .node > .mobility', + nodeLayerSelect: '.container > .body > .node > .layer .layer-select', + nodeLayerButton: '.container > .body > .node > .layer .layer-edit', + + sectionBody: '.container > .body > .section-body', + sectionMissing: '.container > .body > .section-missing', + sectionAsset: '.container > .body > .section-asset', + + footer: '.container > .body > .footer', + componentAdd: '.container > .body > .footer .add-component', }; const Elements = { @@ -595,9 +600,7 @@ const Elements = { panel.assets = {}; if (panel.dump) { - panel.$.container.style.display = 'flex'; - panel.$.header.style.display = 'flex'; - panel.$.footer.style.display = 'block'; + panel.$.container.removeAttribute('hidden'); // 以第一个节点的类型,过滤多选的其他不同类型,比如 node 和 sceneNode 就不能混为多选编辑 const type = panel.dump.__type__; @@ -611,7 +614,7 @@ const Elements = { // 补充缺失的 dump 数据,如 path values 等,收集节点内的资源 utils.translationDump(panel.dump, panel.dumps.length > 1 ? panel.dumps : undefined, panel.assets); } else { - panel.$.container.style.display = 'none'; + panel.$.container.setAttribute('hidden', ''); } }, close() { @@ -740,6 +743,7 @@ const Elements = { } } else { panel.$.prefab.setAttribute('missing', ''); + panel.$.prefabEdit.setAttribute('disabled', ''); panel.$.prefabLocal.setAttribute('disabled', ''); panel.$.prefabReset.setAttribute('disabled', ''); panel.$.prefabSave.setAttribute('disabled', ''); @@ -1121,6 +1125,8 @@ const Elements = { async update() { const panel = this; + panel.componentCacheExpand = {}; + if (!panel.dump || panel.dump.isScene) { return; } @@ -1203,7 +1209,15 @@ const Elements = { const $section = document.createElement('ui-section'); $section.setAttribute('expand', ''); $section.setAttribute('class', 'component config'); - $section.setAttribute('cache-expand', `${component.path}:${component.type}`); + + let cacheExpandKey = `node-component:${component.type}`; + if (panel.componentCacheExpand[cacheExpandKey]) { + // when exist duplicated component, use uuid as key; + cacheExpandKey = `node-component:${component.value.uuid.value}`; + } + panel.componentCacheExpand[cacheExpandKey] = true; + $section.setAttribute('cache-expand', `${cacheExpandKey}`); + $section.innerHTML = `
@@ -1530,6 +1544,7 @@ const Elements = { materialPanel.injectionStyle(injectionStyle); materialPanel.setAttribute('src', panel.typeManager[materialPanelType]); materialPanel.setAttribute('type', materialPanelType); + materialPanel.setAttribute('sub-type', 'unknown'); materialPanel.setAttribute('uuid', materialUuid); materialPanel.panelObject.replaceContainerWithUISection({ diff --git a/editor/inspector/utils/prop.js b/editor/inspector/utils/prop.js index d939550f0f9..6a7a0ad9692 100644 --- a/editor/inspector/utils/prop.js +++ b/editor/inspector/utils/prop.js @@ -546,4 +546,8 @@ ui-prop[ui-section-config] + ui-section.config, ui-prop[ui-section-config] + ui-prop[ui-section-config], ui-section.config + ui-prop[ui-section-config], ui-section.config + ui-section.config { margin-top: 0; } + +ui-prop[ui-section-config]:last-child { + border-bottom: solid 1px var(--color-normal-fill-emphasis); +} `; From 57414e27c235d522f2d7c169c402301b510ea538 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Wed, 12 Jul 2023 09:58:47 +0800 Subject: [PATCH 032/232] fix videoPlayer puase seekTo bug (#15678) --- cocos/video/video-player-impl-web.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/video/video-player-impl-web.ts b/cocos/video/video-player-impl-web.ts index ba548439843..0df7831777a 100644 --- a/cocos/video/video-player-impl-web.ts +++ b/cocos/video/video-player-impl-web.ts @@ -165,6 +165,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { public seekTo (val: number): void { if (this.video) { this.video.currentTime = val; + this._cachedCurrentTime = this.video.currentTime; } } From 43b9fd4485b0d5ba5f1880a98a03850cc0f791a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 12 Jul 2023 11:20:25 +0800 Subject: [PATCH 033/232] PoseGraph: fix apply transform node (#15632) * Fix apply transform Tweak * Optimize --- .../marionette/animation-graph-context.ts | 14 +- .../pose-graph/pose-nodes/apply-transform.ts | 2 +- .../pose-nodes/apply-transform.test.ts | 454 ++++++++++++++++++ .../pose-graph/pose-transform-space.test.ts | 4 +- tests/animation/utils/transform-matcher.ts | 27 ++ 5 files changed, 494 insertions(+), 7 deletions(-) create mode 100644 tests/animation/new-gen-anim/pose-graph/pose-nodes/apply-transform.test.ts create mode 100644 tests/animation/utils/transform-matcher.ts diff --git a/cocos/animation/marionette/animation-graph-context.ts b/cocos/animation/marionette/animation-graph-context.ts index a2aef79cda2..2072fb19444 100644 --- a/cocos/animation/marionette/animation-graph-context.ts +++ b/cocos/animation/marionette/animation-graph-context.ts @@ -915,9 +915,12 @@ class AnimationGraphEvaluationContext { break; } case TransformSpace.LOCAL: { // Local -> * - const nodeComponentTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion); - const invNodeComponentTransform = Transform.invert(nodeComponentTransform, nodeComponentTransform); - Transform.multiply(transform, invNodeComponentTransform, transform); + // Bone_Local_Transform * result = input + // result = inv(Bone_Local_Transform) * input + assertIsTrue(poseSpace === PoseTransformSpace.COMPONENT || poseSpace === PoseTransformSpace.LOCAL); + const boneTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion); + const invBoneTransform = Transform.invert(boneTransform, boneTransform); + Transform.multiply(transform, invBoneTransform, transform); break; } } @@ -975,6 +978,9 @@ class AnimationGraphEvaluationContext { break; } case TransformSpace.LOCAL: { + assertIsTrue(poseSpace === PoseTransformSpace.COMPONENT || poseSpace === PoseTransformSpace.LOCAL); + // Bone_Local_Transform * result = input + // result = inv(Bone_Local_Transform) * input const currentTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion); Transform.multiply(transform, currentTransform, transform); break; @@ -1005,7 +1011,7 @@ class AnimationGraphEvaluationContext { const { _parentTable: parentTable } = this; Transform.setIdentity(out); - for (let iTransform = transformIndex; iTransform >= 0; iTransform = parentTable[iTransform]) { + for (let iTransform = parentTable[transformIndex]; iTransform >= 0; iTransform = parentTable[iTransform]) { const localTransform = pose.transforms.getTransform(iTransform, cacheTransform_spaceConversion); Transform.multiply(out, localTransform, out); } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts b/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts index 6ba4f5524cc..2909c1f2bcc 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts @@ -17,7 +17,7 @@ import { PoseGraphType } from '../foundation/type-system'; import { TransformSpace } from './transform-space'; import { Transform } from '../../../core/transform'; -enum TransformOperation { +export enum TransformOperation { LEAVE_UNCHANGED, REPLACE, diff --git a/tests/animation/new-gen-anim/pose-graph/pose-nodes/apply-transform.test.ts b/tests/animation/new-gen-anim/pose-graph/pose-nodes/apply-transform.test.ts new file mode 100644 index 00000000000..5861467dd15 --- /dev/null +++ b/tests/animation/new-gen-anim/pose-graph/pose-nodes/apply-transform.test.ts @@ -0,0 +1,454 @@ +import { Transform } from "../../../../../cocos/animation/core/transform"; +import { PoseGraph, poseGraphOp } from "../../../../../cocos/animation/marionette/asset-creation"; +import { PoseNodeApplyTransform, TransformOperation } from "../../../../../cocos/animation/marionette/pose-graph/pose-nodes/apply-transform"; +import { TransformSpace } from "../../../../../cocos/animation/marionette/pose-graph/pose-nodes/transform-space"; +import { Node, Quat, Vec3 } from "../../../../../exports/base"; +import { AnimationGraphEvalMock } from "../../utils/eval-mock"; +import { createAnimationGraph } from "../../utils/factory"; +import '../../../../utils/matchers/value-type-asymmetric-matchers'; +import '../../../utils/transform-matcher'; +import { getMagicSeed, PseudoRandomGenerator } from '../../../../utils/random'; +import { PoseNode, PoseTransformSpaceRequirement } from "../../../../../cocos/animation/marionette/pose-graph/pose-node"; +import { Pose } from "../../../../../cocos/animation/core/pose"; +import { AnimationGraphBindingContext, AnimationGraphSettleContext, AnimationGraphUpdateContext, AnimationGraphEvaluationContext } from "../../../../../cocos/animation/marionette/animation-graph-context"; +import { input } from "../../../../../cocos/animation/marionette/pose-graph/decorator/input"; +import { PoseGraphType } from "../../../../../cocos/animation/marionette/pose-graph/foundation/type-system"; +import { composeInputKeyInternally } from "../utils/misc"; + +describe(`PoseNodeApplyTransform`, () => { + describe(`Position`, () => { + const g = new PseudoRandomGenerator(getMagicSeed()); + + const SIMPLE_INPUTS = false; + + const fixture = SIMPLE_INPUTS + ? (() => { + return { + originTransform: createTransformFromPRS({ position: new Vec3(0.1, 0.2, 0.3) }), + parentLocalTransforms: [createTransformFromPRS({ position: new Vec3(1, 2, 3) })], + localTransform: createTransformFromPRS({ position: new Vec3(4, 5, 6) }), + positionValue: Vec3.ZERO, + intensityValue: 1.0, + }; + })() + : (() => { + return { + originTransform: generateRandomTransform(g), + parentLocalTransforms: [generateRandomTransform(g)], + localTransform: generateRandomTransform(g), + positionValue: new Vec3(g.finite(), g.finite(), g.finite()), + intensityValue: g.range01(), + }; + })(); + + describe(`Override`, () => { + const replacePositionInSpace = (space: TransformSpace) => { + const result = runPoseNodeApplyTransform( + fixture.originTransform, + fixture.parentLocalTransforms, + fixture.localTransform, + { + position: { + value: fixture.positionValue, + operation: TransformOperation.REPLACE, + }, + intensity: fixture.intensityValue, + transformSpace: space, + }, + ); + + return result; + }; + + test(`World`, () => { + const result = replacePositionInSpace(TransformSpace.WORLD); + expect(result.worldPosition).toBeCloseToVec3(Vec3.lerp( + new Vec3(), + multiplyTransforms( + fixture.originTransform, + ...fixture.parentLocalTransforms, + fixture.localTransform, + ).position, + fixture.positionValue, + fixture.intensityValue, + )); + }); + test(`Component`, () => { + const result = replacePositionInSpace(TransformSpace.COMPONENT); + expect(result.worldPosition).toBeCloseToVec3(multiplyTransforms( + fixture.originTransform, + createTransformFromPRS({ + position: Vec3.lerp( + new Vec3(), + multiplyTransforms( + ...fixture.parentLocalTransforms, + fixture.localTransform, + ).position, + fixture.positionValue, + fixture.intensityValue, + ), + }), + ).position); + }); + test(`Parent`, () => { + const result = replacePositionInSpace(TransformSpace.PARENT); + expect(result.worldPosition).toBeCloseToVec3(multiplyTransforms( + fixture.originTransform, + ...fixture.parentLocalTransforms, + createTransformFromPRS({ + position: Vec3.lerp( + new Vec3(), + fixture.localTransform.position, + fixture.positionValue, + fixture.intensityValue, + ), + rotation: fixture.localTransform.rotation, + scale: fixture.localTransform.scale, + }), + ).position); + }); + test(`Local`, () => { + const result = replacePositionInSpace(TransformSpace.LOCAL); + expect(result.worldPosition).toBeCloseToVec3(multiplyTransforms( + fixture.originTransform, + ...fixture.parentLocalTransforms, + fixture.localTransform, + createTransformFromPRS({ + position: Vec3.lerp( + new Vec3(), + Vec3.ZERO, + fixture.positionValue, + fixture.intensityValue, + ), + }), + ).position); + }); + }); + + describe(`Additive`, () => { + const addPositionInSpace = (space: TransformSpace) => { + const result = runPoseNodeApplyTransform( + fixture.originTransform, + fixture.parentLocalTransforms, + fixture.localTransform, + { + position: { + value: fixture.positionValue, + operation: TransformOperation.ADD, + }, + intensity: fixture.intensityValue, + transformSpace: space, + }, + ); + + return result; + }; + + test(`World`, () => { + const result = addPositionInSpace(TransformSpace.WORLD); + expect(result.worldPosition).toBeCloseToVec3(Vec3.scaleAndAdd( + new Vec3(), + multiplyTransforms( + fixture.originTransform, + ...fixture.parentLocalTransforms, + fixture.localTransform, + ).position, + fixture.positionValue, + fixture.intensityValue, + )); + }); + test(`Component`, () => { + const result = addPositionInSpace(TransformSpace.COMPONENT); + const inputComponentTransform = multiplyTransforms( + ...fixture.parentLocalTransforms, + fixture.localTransform, + ); + expect(result.worldPosition).toBeCloseToVec3( + multiplyTransforms( + fixture.originTransform, + createTransformFromPRS({ + position: Vec3.scaleAndAdd(new Vec3(), inputComponentTransform.position, fixture.positionValue, fixture.intensityValue), + rotation: inputComponentTransform.rotation, + scale: inputComponentTransform.scale, + }), + ).position, + ); + }); + test(`Parent`, () => { + const result = addPositionInSpace(TransformSpace.PARENT); + expect(result.worldPosition).toBeCloseToVec3(multiplyTransforms( + fixture.originTransform, + ...fixture.parentLocalTransforms, + createTransformFromPRS({ + position: Vec3.scaleAndAdd(new Vec3(), fixture.localTransform.position, fixture.positionValue, fixture.intensityValue), + rotation: fixture.localTransform.rotation, + scale: fixture.localTransform.scale, + }), + ).position); + }); + test(`Local`, () => { + const result = addPositionInSpace(TransformSpace.LOCAL); + expect(result.worldPosition).toBeCloseToVec3(multiplyTransforms( + fixture.originTransform, + ...fixture.parentLocalTransforms, + createTransformFromPRS({ + position: Vec3.scaleAndAdd(new Vec3(), + fixture.localTransform.position, + multiplyTransforms( + createTransformFromPRS({ rotation: fixture.localTransform.rotation, scale: fixture.localTransform.scale }), + createTransformFromPRS({ position: fixture.positionValue }) + ).position, + fixture.intensityValue, + ), + rotation: fixture.localTransform.rotation, + scale: fixture.localTransform.scale, + }), + ).position); + }); + }); + }); +}); + +interface NodeProps { + position?: { + value: Readonly; + operation: TransformOperation; + }; + rotation?: { + value: Readonly, + operation: TransformOperation, + }; + transformSpace: TransformSpace, + intensity: number; +} + +function runPoseNodeApplyTransform( + originTransform: Transform, + parentNodeLocalTransforms: Transform[], + localTransform: Transform, + nodeProps: NodeProps, +) { + const originNode = new Node(`Origin`); + setNodeLocalTransform(originNode, originTransform); + const parentNodes = parentNodeLocalTransforms.map((tr, index) => { + const node = new Node(`Parent-${index}`); + setNodeLocalTransform(node, tr); + return node; + }); + const applyingNode = new Node(`Applying`); + setNodeLocalTransform(applyingNode, localTransform); + const childNode = new Node(`Child`); + const childLocalTransform = new Transform(); + childLocalTransform.position = new Vec3(1, 2, 3); + childLocalTransform.rotation = Quat.fromEuler(new Quat(), 40, 50, 60); + childLocalTransform.scale = Vec3.multiplyScalar(new Vec3(), Vec3.ONE, 7); + setNodeLocalTransform(childNode, childLocalTransform); + parentNodes.forEach((n, i) => { + if (i === 0) { + n.parent = originNode; + } else { + n.parent = parentNodes[i - 1]; + } + }); + applyingNode.parent = parentNodes.length === 0 ? originNode : parentNodes[parentNodes.length - 1]; + childNode.parent = applyingNode; + + /** + * To cover all conversion case, we do create the applying node twice + * for same inputs but different space input pose(either a local space input pose or a component space input pose). + * They should have same effect so we end up having an "asserts equal" node. + */ + const createPoseGraph = (poseGraph: PoseGraph) => { + const inputNode1 = poseGraph.addNode(new ConvertAsLocalInput()); + const applyingNode1 = createApplyingPoseNode(); + const inputNode2 = poseGraph.addNode(new ConvertAsComponentInput()); + const applyingNode2 = createApplyingPoseNode(); + const assertsNode = poseGraph.addNode(new AssertsEqualAndOutput()); + + poseGraphOp.connectOutputNode(poseGraph, assertsNode); + poseGraphOp.connectNode(poseGraph, assertsNode, composeInputKeyInternally('lhs'), applyingNode1); + poseGraphOp.connectNode(poseGraph, assertsNode, composeInputKeyInternally('rhs'), applyingNode2); + poseGraphOp.connectNode(poseGraph, applyingNode1, composeInputKeyInternally('pose'), inputNode1); + poseGraphOp.connectNode(poseGraph, applyingNode2, composeInputKeyInternally('pose'), inputNode2); + + function createApplyingPoseNode() { + const applyNode = poseGraph.addNode(new PoseNodeApplyTransform()); + applyNode.node = applyingNode.name; + if (nodeProps.position) { + Vec3.copy(applyNode.position, nodeProps.position.value); + applyNode.positionOperation = nodeProps.position.operation; + } + if (nodeProps.rotation) { + Quat.copy(applyNode.rotation, nodeProps.rotation.value); + applyNode.rotationOperation = nodeProps.rotation.operation; + } + applyNode.transformSpace = nodeProps.transformSpace; + applyNode.intensityValue = nodeProps.intensity; + return applyNode; + } + }; + + const animationGraph = createAnimationGraph({ + layers: [{ + stateMachine: { + entryTransitions: [{ to: 'p' }], + states: { + 'p': { + type: 'procedural', + graph: createPoseGraph, + }, + }, + }, + }], + }); + + const evalMock = new AnimationGraphEvalMock(originNode, animationGraph); + evalMock.step(0.1); + + //#region Basic checks. + + // Parent transforms shall not be affected. + for (const [node, inputTransform] of [ + [originNode, originTransform] as const, + ...parentNodes.map((node, i) => [node, parentNodeLocalTransforms[i]] as const), + ]) { + expect(getNodeLocalTransform(node)).toEqualTransform(inputTransform); + } + + // Child local transforms shall not be affected. + expect(getNodeLocalTransform(childNode)).toEqualTransform(childLocalTransform); + + // Applying node's scale shall not change. + expect(applyingNode.scale).toBeCloseToVec3(localTransform.scale); + // If position operation is "leave unchanged", the applying node's position shall not change. + if (!nodeProps.position || nodeProps.position.operation === TransformOperation.LEAVE_UNCHANGED) { + expect(applyingNode.position).toBeCloseToVec3(localTransform.position); + } + // So does rotation. + if (!nodeProps.rotation || nodeProps.rotation.operation === TransformOperation.LEAVE_UNCHANGED) { + expect(applyingNode.rotation).toBeCloseToQuat(localTransform.rotation); + } + + //#endregion + + return { + worldPosition: applyingNode.worldPosition, + worldRotation: applyingNode.worldRotation, + }; +} + +function setNodeLocalTransform(node: Node, tr: Transform) { + node.position = tr.position; + node.rotation = tr.rotation; + node.scale = tr.scale; +} + +function getNodeLocalTransform(node: Node) { + const tr = new Transform(); + tr.position = node.position; + tr.rotation = node.rotation; + tr.scale = node.scale; + return tr; +} + +function getNodeWorldTransform(node: Node) { + const tr = new Transform(); + tr.position = node.worldPosition; + tr.rotation = node.worldRotation; + tr.scale = node.worldScale; + return tr; +} + +function multiplyTransforms( + ...transforms: readonly [...Transform[], Transform] +) { + const result = Transform.clone(transforms[transforms.length - 1]); + for (let i = transforms.length - 2; i >= 0; --i) { + Transform.multiply(result, transforms[i], result); + } + return result; +} + +function createTransformFromPRS(prs: { position?: Readonly; rotation?: Readonly; scale?: Readonly }) { + const tr = new Transform(); + if (prs.position) { + tr.position = prs.position; + } + if (prs.rotation) { + tr.rotation = prs.rotation; + } + if (prs.scale) { + tr.scale = prs.scale; + } + return tr; +} + +function generateRandomTransform(g: PseudoRandomGenerator) { + return createTransformFromPRS({ + position: new Vec3(g.finite(), g.finite(), g.finite()), + rotation: Quat.fromEuler(new Quat(), g.range(0, 360), g.range(0, 360), g.range(0, 360)), + scale: Vec3.multiplyScalar(new Vec3(), Vec3.ONE, g.positive()), + }); +} + +class ConvertAsLocalInput extends PoseNode { + public bind(context: AnimationGraphBindingContext): void { } + public settle(context: AnimationGraphSettleContext): void { } + public reenter(): void { } + protected doUpdate(context: AnimationGraphUpdateContext): void { } + protected doEvaluate(context: AnimationGraphEvaluationContext): Pose { + return context.pushDefaultedPose(); + } +} + +class ConvertAsComponentInput extends PoseNode { + public bind(context: AnimationGraphBindingContext): void { } + public settle(context: AnimationGraphSettleContext): void { } + public reenter(): void { } + protected doUpdate(context: AnimationGraphUpdateContext): void { } + protected doEvaluate(context: AnimationGraphEvaluationContext): Pose { + return context.pushDefaultedPoseInComponentSpace(); + } +} + +class AssertsEqualAndOutput extends PoseNode { + @input({ type: PoseGraphType.POSE }) + lhs: PoseNode | null = null; + + @input({ type: PoseGraphType.POSE }) + rhs: PoseNode | null = null; + + public bind(context: AnimationGraphBindingContext): void { + this.lhs?.bind(context); + this.rhs?.bind(context); + } + + public settle(context: AnimationGraphSettleContext): void { + this.lhs?.settle(context); + this.rhs?.settle(context); + } + + public reenter(): void { + this.lhs?.reenter(); + this.rhs?.reenter(); + } + + protected doUpdate(context: AnimationGraphUpdateContext): void { + this.lhs?.update(context); + this.rhs?.update(context); + } + + protected doEvaluate(context: AnimationGraphEvaluationContext): Pose { + const p1 = this.lhs!.evaluate(context, PoseTransformSpaceRequirement.LOCAL); + const p2 = this.rhs!.evaluate(context, PoseTransformSpaceRequirement.LOCAL); + const tr1 = new Transform(); + const tr2 = new Transform(); + for (let i = 0; i < p1.transforms.length; ++i) { + p1.transforms.getTransform(i, tr1); + p2.transforms.getTransform(i, tr2); + expect(tr1).toEqualTransform(tr2); + } + context.popPose(); + return p1; + } +} \ No newline at end of file diff --git a/tests/animation/new-gen-anim/pose-graph/pose-transform-space.test.ts b/tests/animation/new-gen-anim/pose-graph/pose-transform-space.test.ts index 5009af42742..f1856cc8fbf 100644 --- a/tests/animation/new-gen-anim/pose-graph/pose-transform-space.test.ts +++ b/tests/animation/new-gen-anim/pose-graph/pose-transform-space.test.ts @@ -106,7 +106,7 @@ describe(`Pose transform space`, () => { hierarchy.getComponentToWorldTransform(), // Component -> World hierarchy.computeComponentSpaceTransform( // Local -> Component localSpacePoseRecord, - nodeName, + hierarchy.getParentNodeName(nodeName), ), ); }], @@ -116,7 +116,7 @@ describe(`Pose transform space`, () => { [PoseTransformSpace.LOCAL, TransformSpace.COMPONENT, (hierarchy, localSpacePoseRecord, nodeName) => { return hierarchy.computeComponentSpaceTransform( localSpacePoseRecord, - nodeName, + hierarchy.getParentNodeName(nodeName), ); }], diff --git a/tests/animation/utils/transform-matcher.ts b/tests/animation/utils/transform-matcher.ts new file mode 100644 index 00000000000..11d725b1a73 --- /dev/null +++ b/tests/animation/utils/transform-matcher.ts @@ -0,0 +1,27 @@ +import matchers from 'expect/build/matchers'; +import '../../utils/matchers/value-type-asymmetric-matchers'; +import { Transform } from '../../../cocos/animation/core/transform'; + +expect.extend({ + toEqualTransform(actual: unknown, expected: Readonly, numDigits = 5) { + return matchers.toStrictEqual.call( + this, + actual, + expect.objectContaining({ + position: expect.toBeCloseToVec3(expected.position, numDigits), + rotation: expect.toBeCloseToQuat(expected.rotation, numDigits), + scale: expect.toBeCloseToVec3(expected.scale, numDigits), + }), + ); + }, +}); + +export { }; + +declare global { + namespace jest { + interface Matchers { + toEqualTransform: (expected: Readonly, numDigits?: number) => CustomMatcherResult; + } + } +} \ No newline at end of file From aa53a8b03edb69d53dd3342cf475b64529328052 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 12 Jul 2023 13:37:28 +0800 Subject: [PATCH 034/232] fixed #15688: [JSB] Assertion was triggered if bind an inner class whose parent is also an inner class (#15689) --- native/cocos/bindings/jswrapper/v8/Class.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/native/cocos/bindings/jswrapper/v8/Class.cpp b/native/cocos/bindings/jswrapper/v8/Class.cpp index 3eee7d0d09d..821a0b79bd2 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.cpp +++ b/native/cocos/bindings/jswrapper/v8/Class.cpp @@ -79,14 +79,14 @@ Class *Class::create(const ccstd::string &clsName, Object *parent, Object *paren Class *Class::create(const std::initializer_list &classPath, Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data) { se::AutoHandleScope scope; - se::Object *currentParent = parent; - se::Value tmp; + se::Value currentParent{parent}; for (auto i = 0; i < classPath.size() - 1; i++) { - bool ok = currentParent->getProperty(*(classPath.begin() + i), &tmp); + se::Value tmp; + bool ok = currentParent.toObject()->getProperty(*(classPath.begin() + i), &tmp); CC_ASSERT(ok); // class or namespace in path is not defined - currentParent = tmp.toObject(); + currentParent = tmp; } - return create(*(classPath.end() - 1), currentParent, parentProto, ctor, data); + return create(*(classPath.end() - 1), currentParent.toObject(), parentProto, ctor, data); } bool Class::init(const ccstd::string &clsName, Object *parent, Object *parentProto, v8::FunctionCallback ctor, void *data) { From 7465cf68221a28742d6b2e5c61561e5e952435a7 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Thu, 13 Jul 2023 09:52:45 +0800 Subject: [PATCH 035/232] Fix LOD can not work normally while node's active changed dynamically (#15641) * Fix LOD can not work normally while node's active changed dynamically --- cocos/3d/lod/lodgroup-component.ts | 22 +++++++++++++++++---- cocos/render-scene/scene/lod-group.ts | 2 +- cocos/rendering/lod-group-editor-utility.ts | 9 --------- cocos/scene-graph/node-activator.ts | 2 +- 4 files changed, 20 insertions(+), 15 deletions(-) diff --git a/cocos/3d/lod/lodgroup-component.ts b/cocos/3d/lod/lodgroup-component.ts index 81aa29c3258..c740e53a965 100644 --- a/cocos/3d/lod/lodgroup-component.ts +++ b/cocos/3d/lod/lodgroup-component.ts @@ -242,6 +242,8 @@ export class LODGroup extends Component { private _eventRegistered = false; + private _forceUsedLevels: number[] = []; + constructor () { super(); } @@ -543,7 +545,20 @@ export class LODGroup extends Component { * lodLevel @en The LOD level to use. Passing lodLevel < 0 will return to standard LOD processing. @zh 要使用的LOD层级,为负数时使用标准的处理流程 */ public forceLOD (lodLevel: number): void { - this.lodGroup.lockLODLevels(lodLevel < 0 ? [] : [lodLevel]); + this._forceUsedLevels = lodLevel < 0 ? [] : [lodLevel]; + this.lodGroup.lockLODLevels(this._forceUsedLevels); + } + + /** + * @en Force multi LOD level to use, This function is only called in editor.
+ * @zh 强制使用某几级的LOD,该接口只会在编辑器下调用。 + * lodIndexArray @en The LOD level array. Passing [] will return to standard LOD processing. @zh 要使用的LOD层级数组,传[]时将使用标准的处理流程。 + */ + public forceLODs (lodIndexArray: number[]): void { + if (EDITOR) { + this._forceUsedLevels = lodIndexArray.slice(); + this.lodGroup.lockLODLevels(this._forceUsedLevels); + } } onLoad (): void { @@ -587,6 +602,7 @@ export class LODGroup extends Component { if (this.objectSize === 0) { this.recalculateBounds(); } + this.lodGroup.lockLODLevels(this._forceUsedLevels); // cache lod for scene if (this.lodCount > 0 && this._lodGroup.lodCount < 1) { @@ -609,6 +625,7 @@ export class LODGroup extends Component { onDisable (): void { this._detachFromScene(); + this.lodGroup.lockLODLevels([]); } private _attachToScene (): void { @@ -625,9 +642,6 @@ export class LODGroup extends Component { if (this._lodGroup.scene) { this._lodGroup.scene.removeLODGroup(this._lodGroup); } } - /** - * @engineInternal - */ private _emitChangeNode (node: Node): void { if (EDITOR) { EditorExtends.Node.emit('change', node.uuid, node); diff --git a/cocos/render-scene/scene/lod-group.ts b/cocos/render-scene/scene/lod-group.ts index 4f09a8a7631..7304b3f4919 100644 --- a/cocos/render-scene/scene/lod-group.ts +++ b/cocos/render-scene/scene/lod-group.ts @@ -126,7 +126,7 @@ export class LODGroup { } } } - this._lockedLODLevelVec = lockLev; + this._lockedLODLevelVec = lockLev.slice(); } isLockLevelChanged (): boolean { diff --git a/cocos/rendering/lod-group-editor-utility.ts b/cocos/rendering/lod-group-editor-utility.ts index 78817d85f1b..259ce62260d 100644 --- a/cocos/rendering/lod-group-editor-utility.ts +++ b/cocos/rendering/lod-group-editor-utility.ts @@ -66,15 +66,6 @@ export class LODGroupEditorUtility { return this.distanceToRelativeHeight(camera, distance, this.getWorldSpaceSize(lodGroup)); } - /** - * @zh 强制使用某几级的LOD - * @en Force multi LOD level to use. - * lodIndexArray @en The LOD level array. Passing [] will return to standard LOD processing. @zh 要使用的LOD层级数组,传[]时将使用标准的处理流程。 - */ - static forceLODs (lodGroup: LODGroup, lodIndexArray: number[]) { - lodGroup.lodGroup.lockLODLevels(lodIndexArray); - } - private static distanceToRelativeHeight (camera: Camera, distance: number | undefined, size: number): number { if (camera.projectionType === CameraProjection.PERSPECTIVE) { assertIsTrue(typeof distance === 'number', 'distance must be present for perspective projection'); diff --git a/cocos/scene-graph/node-activator.ts b/cocos/scene-graph/node-activator.ts index 357a966057b..2807fcb2371 100644 --- a/cocos/scene-graph/node-activator.ts +++ b/cocos/scene-graph/node-activator.ts @@ -129,7 +129,7 @@ function _componentCorrupted (node: Node, comp: Component, index: number): void * @zh 用于执行节点和组件的激活和停用操作的管理器。 */ export default class NodeActivator { - public resetComp?: ((comp: Component, didResetToDefault: boolean) => void); + public declare resetComp?: ((comp: Component, didResetToDefault: boolean) => void); protected _activatingStack!: ActivateTask[]; constructor () { From b826a43a034cb3859af1d2f9263bcfbf9a4ae5a0 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Thu, 13 Jul 2023 10:33:58 +0800 Subject: [PATCH 036/232] fix videoPlayer change Source related bug (#15695) --- cocos/video/video-player.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/cocos/video/video-player.ts b/cocos/video/video-player.ts index bba9aa4cc9a..f441585075e 100644 --- a/cocos/video/video-player.ts +++ b/cocos/video/video-player.ts @@ -374,14 +374,8 @@ export class VideoPlayer extends Component { } else { this._impl.syncClip(this._clip); } - } + this._cachedCurrentTime = 0; - public __preload (): void { - if (EDITOR_NOT_IN_PREVIEW) { - return; - } - this._impl = VideoPlayerImplManager.getImpl(this); - this.syncSource(); this._impl.syncLoop(this._loop); this._impl.syncVolume(this._volume); this._impl.syncMute(this._mute); @@ -390,7 +384,15 @@ export class VideoPlayer extends Component { this._impl.syncStayOnBottom(this._stayOnBottom); this._impl.syncKeepAspectRatio(this._keepAspectRatio); this._impl.syncFullScreenOnAwake(this._fullScreenOnAwake); - // + } + + public __preload (): void { + if (EDITOR_NOT_IN_PREVIEW) { + return; + } + this._impl = VideoPlayerImplManager.getImpl(this); + this.syncSource(); + this._impl.componentEventList.set(EventType.META_LOADED, this.onMetaLoaded.bind(this)); this._impl.componentEventList.set(EventType.READY_TO_PLAY, this.onReadyToPlay.bind(this)); this._impl.componentEventList.set(EventType.PLAYING, this.onPlaying.bind(this)); From 3a470a6dff6d00fefc41cbe9b7961e7c585daa4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 13 Jul 2023 14:18:53 +0800 Subject: [PATCH 037/232] Add utilities to check integrity of pal implementations (#15694) * Add utilities to check integrity of pal implementation * Fix screen adapter * Fix game pad input * Apply suggestions from code review Co-authored-by: PP * Add license --------- Co-authored-by: PP --- @types/pal/input.d.ts | 1 + @types/pal/screen-adapter.d.ts | 8 +-- @types/pal/system-info.d.ts | 6 ++- pal/env/minigame/env.ts | 3 ++ pal/env/native/env.ts | 5 +- pal/env/runtime/env.ts | 3 ++ pal/env/web/env.ts | 4 ++ pal/input/minigame/index.ts | 4 ++ pal/input/native/index.ts | 4 ++ pal/input/web/index.ts | 4 ++ pal/integrity-check.ts | 54 +++++++++++++++++++ pal/minigame/alipay.ts | 3 ++ pal/minigame/baidu.ts | 3 ++ pal/minigame/bytedance.ts | 3 ++ pal/minigame/non-minigame.ts | 4 ++ pal/minigame/runtime.ts | 3 ++ pal/minigame/taobao.ts | 3 ++ pal/minigame/taobao_minigame.ts | 3 ++ pal/minigame/wechat.ts | 3 ++ pal/minigame/wechat_mini_program.ts | 3 ++ pal/minigame/xiaomi.ts | 3 ++ pal/pacer/pacer-minigame.ts | 3 ++ pal/pacer/pacer-native.ts | 3 ++ pal/pacer/pacer-web.ts | 3 ++ pal/screen-adapter/minigame/screen-adapter.ts | 3 ++ pal/screen-adapter/native/screen-adapter.ts | 3 ++ pal/screen-adapter/web/screen-adapter.ts | 3 ++ pal/system-info/minigame/system-info.ts | 3 ++ pal/system-info/native/system-info.ts | 3 ++ pal/system-info/web/system-info.ts | 3 ++ pal/wasm/wasm-minigame.ts | 3 ++ pal/wasm/wasm-native.ts | 3 ++ pal/wasm/wasm-web.ts | 3 ++ 33 files changed, 154 insertions(+), 9 deletions(-) create mode 100644 pal/integrity-check.ts diff --git a/@types/pal/input.d.ts b/@types/pal/input.d.ts index 5dfb192becb..892fa1c294f 100644 --- a/@types/pal/input.d.ts +++ b/@types/pal/input.d.ts @@ -52,6 +52,7 @@ declare module 'pal/input' { * Class designed for gamepad input */ export class GamepadInputDevice { + private constructor(deviceId: number); /** * @engineInternal */ diff --git a/@types/pal/screen-adapter.d.ts b/@types/pal/screen-adapter.d.ts index 505e2e661fb..363e6f42326 100644 --- a/@types/pal/screen-adapter.d.ts +++ b/@types/pal/screen-adapter.d.ts @@ -79,12 +79,6 @@ declare module 'pal/screen-adapter' { */ public get resolution (): import('cocos/core/math').Size; - /** - * Update the resolution by resolutionScale. - * This method rebuilds the size of frame buffer and the size of canvas. - * This method should be called when window resized (fullscreen changing included) or the resolution scale changed. - */ - private _updateResolution (); /** * Get and set the resolution scale of screen, which will affect the quality of the rendering. * Note: if this value is set too high, the rendering performance of GPU will be reduced, this value is 1 by default. @@ -123,4 +117,6 @@ declare module 'pal/screen-adapter' { } export const screenAdapter: ScreenAdapter; + + export {}; } diff --git a/@types/pal/system-info.d.ts b/@types/pal/system-info.d.ts index 4cb322b7afe..cec8f7f032c 100644 --- a/@types/pal/system-info.d.ts +++ b/@types/pal/system-info.d.ts @@ -57,10 +57,12 @@ declare module 'pal/system-info' { */ public exit(): void; - on (event: PalSystemEvent, cb: (...args: any)=>void, target?: any): void; - off (event: PalSystemEvent, cb?: (...args: any)=>void, target?: any): void; + on (event: PalSystemEvent, cb: (...args: any) => void, target?: any): void; + off (event: PalSystemEvent, cb?: (...args: any) => void, target?: any): void; // TODO: support onError } export const systemInfo: SystemInfo; + + export {}; } diff --git a/pal/env/minigame/env.ts b/pal/env/minigame/env.ts index cd57091c42a..21fa0118eb3 100644 --- a/pal/env/minigame/env.ts +++ b/pal/env/minigame/env.ts @@ -24,6 +24,7 @@ /* eslint-disable import/no-dynamic-require */ import { BAIDU, TAOBAO, TAOBAO_MINIGAME, WECHAT, WECHAT_MINI_PROGRAM, XIAOMI } from 'internal:constants'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; declare const require: (path: string) => any; declare const __baiduRequire: (path: string) => any; @@ -54,3 +55,5 @@ export function loadJsFile (path: string): any { } return require(`../${path}`); } + +checkPalIntegrity(withImpl()); diff --git a/pal/env/native/env.ts b/pal/env/native/env.ts index 082671beb31..65db77f5cdd 100644 --- a/pal/env/native/env.ts +++ b/pal/env/native/env.ts @@ -22,7 +22,8 @@ THE SOFTWARE. */ -import { PREVIEW } from "internal:constants"; +import { PREVIEW } from 'internal:constants'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; declare const require: (path: string) => Promise; @@ -69,3 +70,5 @@ export function loadJsFile (path: string): Promise { return require(`${path}`); } } + +checkPalIntegrity(withImpl()); diff --git a/pal/env/runtime/env.ts b/pal/env/runtime/env.ts index cedeca6aa61..d418ba86b1f 100644 --- a/pal/env/runtime/env.ts +++ b/pal/env/runtime/env.ts @@ -23,6 +23,7 @@ */ import { COCOSPLAY, HUAWEI, OPPO, VIVO } from 'internal:constants'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; declare const require: (path: string) => Promise; declare const ral: any; @@ -52,3 +53,5 @@ export function loadJsFile (path: string): Promise { // eslint-disable-next-line import/no-dynamic-require return require(`${path}`); } + +checkPalIntegrity(withImpl()); diff --git a/pal/env/web/env.ts b/pal/env/web/env.ts index ff35915bbcb..e0aee6672a7 100644 --- a/pal/env/web/env.ts +++ b/pal/env/web/env.ts @@ -22,6 +22,8 @@ THE SOFTWARE. */ +import { checkPalIntegrity, withImpl } from '../../integrity-check'; + export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } { const frame = document.querySelector('#GameDiv') as HTMLDivElement; const container = document.querySelector('#Cocos3dGameContainer') as HTMLDivElement; @@ -62,3 +64,5 @@ export function loadJsFile (path: string): Promise { document.head.appendChild(script); }); } + +checkPalIntegrity(withImpl()); diff --git a/pal/input/minigame/index.ts b/pal/input/minigame/index.ts index 4af5ab414e7..a30638e3682 100644 --- a/pal/input/minigame/index.ts +++ b/pal/input/minigame/index.ts @@ -22,6 +22,8 @@ THE SOFTWARE. */ +import { checkPalIntegrity, withImpl } from '../../integrity-check'; + export * from './accelerometer-input'; export * from './gamepad-input'; export * from './handle-input'; @@ -30,3 +32,5 @@ export * from './handheld-input'; export * from './keyboard-input'; export * from './mouse-input'; export * from './touch-input'; + +checkPalIntegrity(withImpl()); diff --git a/pal/input/native/index.ts b/pal/input/native/index.ts index 4af5ab414e7..a30638e3682 100644 --- a/pal/input/native/index.ts +++ b/pal/input/native/index.ts @@ -22,6 +22,8 @@ THE SOFTWARE. */ +import { checkPalIntegrity, withImpl } from '../../integrity-check'; + export * from './accelerometer-input'; export * from './gamepad-input'; export * from './handle-input'; @@ -30,3 +32,5 @@ export * from './handheld-input'; export * from './keyboard-input'; export * from './mouse-input'; export * from './touch-input'; + +checkPalIntegrity(withImpl()); diff --git a/pal/input/web/index.ts b/pal/input/web/index.ts index 4af5ab414e7..a30638e3682 100644 --- a/pal/input/web/index.ts +++ b/pal/input/web/index.ts @@ -22,6 +22,8 @@ THE SOFTWARE. */ +import { checkPalIntegrity, withImpl } from '../../integrity-check'; + export * from './accelerometer-input'; export * from './gamepad-input'; export * from './handle-input'; @@ -30,3 +32,5 @@ export * from './handheld-input'; export * from './keyboard-input'; export * from './mouse-input'; export * from './touch-input'; + +checkPalIntegrity(withImpl()); diff --git a/pal/integrity-check.ts b/pal/integrity-check.ts new file mode 100644 index 00000000000..44838582ab5 --- /dev/null +++ b/pal/integrity-check.ts @@ -0,0 +1,54 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +declare const guard: unique symbol; + +type Guard = typeof guard; + +/** + * Checks if a PAL implementation module is compatible with its target interface module. + * + * @example + * If you write the following in somewhere: + * + * ```ts + * checkPalIntegrity( + * withImpl()); + * ``` + * + * you will receive a compilation error + * if your implementation module is not fulfil the interface module. + * + * @note This function should be easily tree-shaken. + */ +export function checkPalIntegrity (impl: T & Guard) { +} + +/** + * Utility function, see example of `checkPalIntegrity()`. + * + */ +export function withImpl () { + return 0 as unknown as T & Guard; +} diff --git a/pal/minigame/alipay.ts b/pal/minigame/alipay.ts index 6f5c8e7b630..be1f535e267 100644 --- a/pal/minigame/alipay.ts +++ b/pal/minigame/alipay.ts @@ -23,6 +23,7 @@ */ import { IMiniGame } from 'pal/minigame'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; @@ -158,3 +159,5 @@ minigame.getSafeArea = function (): SafeArea { // #endregion SafeArea export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/baidu.ts b/pal/minigame/baidu.ts index 81955833f15..2f0b86ea669 100644 --- a/pal/minigame/baidu.ts +++ b/pal/minigame/baidu.ts @@ -23,6 +23,7 @@ */ import { IMiniGame } from 'pal/minigame'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; @@ -111,3 +112,5 @@ minigame.getSafeArea = function (): SafeArea { // #endregion SafeArea export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/bytedance.ts b/pal/minigame/bytedance.ts index b8148703f7c..e81d37e56c1 100644 --- a/pal/minigame/bytedance.ts +++ b/pal/minigame/bytedance.ts @@ -23,6 +23,7 @@ */ import { IMiniGame, SystemInfo } from 'pal/minigame'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; @@ -125,3 +126,5 @@ minigame.getSafeArea = function (): SafeArea { // #endregion SafeArea export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/non-minigame.ts b/pal/minigame/non-minigame.ts index 01053d21fc1..4e70986d6e9 100644 --- a/pal/minigame/non-minigame.ts +++ b/pal/minigame/non-minigame.ts @@ -22,5 +22,9 @@ THE SOFTWARE. */ +import { checkPalIntegrity, withImpl } from '../integrity-check'; + const minigame: any = {}; export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/runtime.ts b/pal/minigame/runtime.ts index 3c2336b0c57..8dfad251c88 100644 --- a/pal/minigame/runtime.ts +++ b/pal/minigame/runtime.ts @@ -24,6 +24,7 @@ import { COCOSPLAY, HUAWEI, LINKSURE, OPPO, QTT, VIVO } from 'internal:constants'; import { SystemInfo, IMiniGame } from 'pal/minigame'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; @@ -152,3 +153,5 @@ minigame.getSafeArea = function (): SafeArea { // #endregion SafeArea export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/taobao.ts b/pal/minigame/taobao.ts index 4c8948a3079..8e5f9e18974 100644 --- a/pal/minigame/taobao.ts +++ b/pal/minigame/taobao.ts @@ -26,6 +26,7 @@ import { IMiniGame, SystemInfo } from 'pal/minigame'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; import { Language } from '../system-info/enum-type'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; //taobao IDE language ("Chinese") //taobao phone language (Andrond: "cn", iPad: 'zh_CN') @@ -217,3 +218,5 @@ function adapterGL (gl): void { } export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/taobao_minigame.ts b/pal/minigame/taobao_minigame.ts index 7f52e5a88d4..5db86b6cfa9 100644 --- a/pal/minigame/taobao_minigame.ts +++ b/pal/minigame/taobao_minigame.ts @@ -26,6 +26,7 @@ import { IMiniGame, SystemInfo } from 'pal/minigame'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; import { Language } from '../system-info/enum-type'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; //taobao IDE language ("Chinese") //taobao phone language (Andrond: "cn", iPad: 'zh_CN') @@ -229,3 +230,5 @@ function adapterGL (gl): void { minigame.loadSubpackage = my.loadSubPackage.bind(my); export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/wechat.ts b/pal/minigame/wechat.ts index 5049cf6163a..9a912da3bf8 100644 --- a/pal/minigame/wechat.ts +++ b/pal/minigame/wechat.ts @@ -23,6 +23,7 @@ */ import { IMiniGame, SystemInfo } from 'pal/minigame'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; @@ -174,3 +175,5 @@ if (systemInfo.platform === 'windows' && versionCompare(systemInfo.SDKVersion, ' } export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/wechat_mini_program.ts b/pal/minigame/wechat_mini_program.ts index 8abf6e2d0c4..61034a008d3 100644 --- a/pal/minigame/wechat_mini_program.ts +++ b/pal/minigame/wechat_mini_program.ts @@ -23,6 +23,7 @@ */ import { IMiniGame, SystemInfo } from 'pal/minigame'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; @@ -197,3 +198,5 @@ gl.texSubImage2D = function (...args): void { }; export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/minigame/xiaomi.ts b/pal/minigame/xiaomi.ts index 9a07a7a7b46..e182de7f828 100644 --- a/pal/minigame/xiaomi.ts +++ b/pal/minigame/xiaomi.ts @@ -23,6 +23,7 @@ */ import { IMiniGame } from 'pal/minigame'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; import { Orientation } from '../screen-adapter/enum-type'; import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; @@ -150,3 +151,5 @@ minigame.getSafeArea = function (): SafeArea { // #endregion SafeArea export { minigame }; + +checkPalIntegrity(withImpl()); diff --git a/pal/pacer/pacer-minigame.ts b/pal/pacer/pacer-minigame.ts index 841e014ec3e..17b42c385fb 100644 --- a/pal/pacer/pacer-minigame.ts +++ b/pal/pacer/pacer-minigame.ts @@ -24,6 +24,7 @@ import { minigame } from 'pal/minigame'; import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; export class Pacer { private _rafHandle = 0; @@ -79,3 +80,5 @@ export class Pacer { this._isPlaying = false; } } + +checkPalIntegrity(withImpl()); diff --git a/pal/pacer/pacer-native.ts b/pal/pacer/pacer-native.ts index 15ef3c2b100..a4ae05b6148 100644 --- a/pal/pacer/pacer-native.ts +++ b/pal/pacer/pacer-native.ts @@ -23,6 +23,7 @@ */ import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; declare const jsb: any; export class Pacer { @@ -79,3 +80,5 @@ export class Pacer { this._isPlaying = false; } } + +checkPalIntegrity(withImpl()); diff --git a/pal/pacer/pacer-web.ts b/pal/pacer/pacer-web.ts index bf9aed7f704..f24212984a2 100644 --- a/pal/pacer/pacer-web.ts +++ b/pal/pacer/pacer-web.ts @@ -24,6 +24,7 @@ import { EDITOR } from 'internal:constants'; import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; const FRAME_RESET_TIME = 2000; @@ -144,3 +145,5 @@ export class Pacer { } } } + +checkPalIntegrity(withImpl()); diff --git a/pal/screen-adapter/minigame/screen-adapter.ts b/pal/screen-adapter/minigame/screen-adapter.ts index f95deecca7e..cc720af7d19 100644 --- a/pal/screen-adapter/minigame/screen-adapter.ts +++ b/pal/screen-adapter/minigame/screen-adapter.ts @@ -31,6 +31,7 @@ import { EventTarget } from '../../../cocos/core/event/event-target'; import { Size } from '../../../cocos/core/math'; import { OS } from '../../system-info/enum-type'; import { Orientation } from '../enum-type'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; declare const my: any; @@ -174,3 +175,5 @@ class ScreenAdapter extends EventTarget { } export const screenAdapter = new ScreenAdapter(); + +checkPalIntegrity(withImpl()); diff --git a/pal/screen-adapter/native/screen-adapter.ts b/pal/screen-adapter/native/screen-adapter.ts index 0e0056104e5..29cdec1adfa 100644 --- a/pal/screen-adapter/native/screen-adapter.ts +++ b/pal/screen-adapter/native/screen-adapter.ts @@ -25,6 +25,7 @@ import { EDITOR } from 'internal:constants'; import { EventTarget } from '../../../cocos/core/event/event-target'; import { Size } from '../../../cocos/core/math'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; import { Orientation } from '../enum-type'; export interface SafeAreaEdge { @@ -183,3 +184,5 @@ class ScreenAdapter extends EventTarget { } export const screenAdapter = new ScreenAdapter(); + +checkPalIntegrity(withImpl()); diff --git a/pal/screen-adapter/web/screen-adapter.ts b/pal/screen-adapter/web/screen-adapter.ts index 86590be5ddf..15ed7d9af15 100644 --- a/pal/screen-adapter/web/screen-adapter.ts +++ b/pal/screen-adapter/web/screen-adapter.ts @@ -30,6 +30,7 @@ import { EventTarget } from '../../../cocos/core/event/event-target'; import { Size } from '../../../cocos/core/math'; import { Orientation } from '../enum-type'; import legacyCC from '../../../predefine'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; interface ICachedStyle { width: string; @@ -562,3 +563,5 @@ class ScreenAdapter extends EventTarget { } export const screenAdapter = new ScreenAdapter(); + +checkPalIntegrity(withImpl()); diff --git a/pal/system-info/minigame/system-info.ts b/pal/system-info/minigame/system-info.ts index bb8fa7f2964..b00600cfa59 100644 --- a/pal/system-info/minigame/system-info.ts +++ b/pal/system-info/minigame/system-info.ts @@ -26,6 +26,7 @@ import { ALIPAY, BAIDU, BYTEDANCE, COCOSPLAY, HUAWEI, LINKSURE, OPPO, QTT, VIVO, import { minigame } from 'pal/minigame'; import { IFeatureMap } from 'pal/system-info'; import { EventTarget } from '../../../cocos/core/event'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; // NOTE: register minigame platform here @@ -256,3 +257,5 @@ class SystemInfo extends EventTarget { } export const systemInfo = new SystemInfo(); + +checkPalIntegrity(withImpl()); diff --git a/pal/system-info/native/system-info.ts b/pal/system-info/native/system-info.ts index 4b2b4dfab2f..ab32f1c8824 100644 --- a/pal/system-info/native/system-info.ts +++ b/pal/system-info/native/system-info.ts @@ -24,6 +24,7 @@ import { OPEN_HARMONY } from 'internal:constants'; import { EventTarget } from '../../../cocos/core/event'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; type IFeatureMap = { @@ -194,3 +195,5 @@ class SystemInfo extends EventTarget { } export const systemInfo = new SystemInfo(); + +checkPalIntegrity(withImpl()); diff --git a/pal/system-info/web/system-info.ts b/pal/system-info/web/system-info.ts index 044c99eafdf..14d6c3311dd 100644 --- a/pal/system-info/web/system-info.ts +++ b/pal/system-info/web/system-info.ts @@ -25,6 +25,7 @@ import { DEBUG, EDITOR, PREVIEW, TEST } from 'internal:constants'; import { IFeatureMap } from 'pal/system-info'; import { EventTarget } from '../../../cocos/core/event'; +import { checkPalIntegrity, withImpl } from '../../integrity-check'; import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; class SystemInfo extends EventTarget { @@ -383,3 +384,5 @@ class SystemInfo extends EventTarget { } export const systemInfo = new SystemInfo(); + +checkPalIntegrity(withImpl()); diff --git a/pal/wasm/wasm-minigame.ts b/pal/wasm/wasm-minigame.ts index 2d19a2beb6f..a7527f15235 100644 --- a/pal/wasm/wasm-minigame.ts +++ b/pal/wasm/wasm-minigame.ts @@ -25,6 +25,7 @@ import { HUAWEI, TAOBAO_MINIGAME, WASM_SUBPACKAGE, XIAOMI } from 'internal:constants'; import { minigame } from 'pal/minigame'; import { basename } from '../../cocos/core/utils/path'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { return getPlatformBinaryUrl(wasmUrl).then((url) => WebAssembly.instantiate(url, importObject)); @@ -108,3 +109,5 @@ function getPlatformBinaryUrl (binaryUrl: string): Promise { } }); } + +checkPalIntegrity(withImpl()); diff --git a/pal/wasm/wasm-native.ts b/pal/wasm/wasm-native.ts index 04b19d90a47..57a9d3ef8ad 100644 --- a/pal/wasm/wasm-native.ts +++ b/pal/wasm/wasm-native.ts @@ -23,6 +23,7 @@ */ import { EDITOR } from 'internal:constants'; import { native } from '../../cocos/native-binding/index'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { return fetchBuffer(wasmUrl).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, importObject)); @@ -53,3 +54,5 @@ export function fetchBuffer (binaryUrl: string): Promise { export function ensureWasmModuleReady (): Promise { return Promise.resolve(); } + +checkPalIntegrity(withImpl()); diff --git a/pal/wasm/wasm-web.ts b/pal/wasm/wasm-web.ts index b61c0cf5893..6585310a34f 100644 --- a/pal/wasm/wasm-web.ts +++ b/pal/wasm/wasm-web.ts @@ -23,6 +23,7 @@ */ import { EDITOR, PREVIEW } from 'internal:constants'; +import { checkPalIntegrity, withImpl } from '../integrity-check'; declare const require: any; @@ -64,3 +65,5 @@ export function fetchBuffer (binaryUrl: string): Promise { export function ensureWasmModuleReady (): Promise { return Promise.resolve(); } + +checkPalIntegrity(withImpl()); From d31a3d6188d87379e14fcd3082f022358aeb987b Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 14 Jul 2023 09:58:27 +0800 Subject: [PATCH 038/232] fix #15704: [swig] The generated glue code is wrong if rename an inner class (#15710) --- native/external-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external-config.json b/native/external-config.json index 0947b936cfc..f181e91c4c4 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-4" + "checkout": "v3.8.1-5" } } From e6dc2215c81f9e183c89f4f468c216eb2251ac75 Mon Sep 17 00:00:00 2001 From: Myway Date: Fri, 14 Jul 2023 10:28:37 +0800 Subject: [PATCH 039/232] change heightmap range (#15716) --- cocos/terrain/terrain-asset.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/cocos/terrain/terrain-asset.ts b/cocos/terrain/terrain-asset.ts index 0a1fa12f141..156360f280d 100644 --- a/cocos/terrain/terrain-asset.ts +++ b/cocos/terrain/terrain-asset.ts @@ -32,7 +32,8 @@ export const TERRAIN_BLOCK_TILE_COMPLEXITY = 32; export const TERRAIN_BLOCK_VERTEX_COMPLEXITY = 33; export const TERRAIN_BLOCK_VERTEX_SIZE = 8; // position + normal + uv export const TERRAIN_HEIGHT_BASE = 32768; -export const TERRAIN_HEIGHT_FACTORY = 1.0 / 512.0; +export const TERRAIN_HEIGHT_FACTORY = 1.0 / 128.0; +export const TERRAIN_HEIGHT_FACTORY_V7 = 1.0 / 512.0; export const TERRAIN_HEIGHT_FMIN = (-TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY; export const TERRAIN_HEIGHT_FMAX = (65535 - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY; export const TERRAIN_NORTH_INDEX = 0; @@ -47,6 +48,7 @@ export const TERRAIN_DATA_VERSION4 = 0x01010004; export const TERRAIN_DATA_VERSION5 = 0x01010005; export const TERRAIN_DATA_VERSION6 = 0x01010006; export const TERRAIN_DATA_VERSION7 = 0x01010007; +export const TERRAIN_DATA_VERSION8 = 0x01010008; export const TERRAIN_DATA_VERSION_DEFAULT = 0x01010111; class TerrainBuffer { @@ -475,7 +477,8 @@ export class TerrainAsset extends Asset { && this._version !== TERRAIN_DATA_VERSION4 && this._version !== TERRAIN_DATA_VERSION5 && this._version !== TERRAIN_DATA_VERSION6 - && this._version !== TERRAIN_DATA_VERSION7) { + && this._version !== TERRAIN_DATA_VERSION7 + && this._version !== TERRAIN_DATA_VERSION8) { return false; } @@ -498,6 +501,14 @@ export class TerrainAsset extends Asset { this.heights[i] = stream.readInt16(); } + if (this._version < TERRAIN_DATA_VERSION8) { + for (let i = 0; i < this.heights.length; ++i) { + const h = (this._heights[i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY_V7; + const ch = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY; + this.heights[i] = ch; + } + } + // normals if (this._version >= TERRAIN_DATA_VERSION6) { const normalBufferSize = stream.readInt(); @@ -560,7 +571,7 @@ export class TerrainAsset extends Asset { const stream = new TerrainBuffer(); // version - stream.writeInt32(TERRAIN_DATA_VERSION7); + stream.writeInt32(TERRAIN_DATA_VERSION8); // geometry info stream.writeDouble(this.tileSize); From f87d196f8dd8954c579951a7713380011c4b17a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 14 Jul 2023 10:33:16 +0800 Subject: [PATCH 040/232] Add Vec3.generateOrthogonal (#15705) --- cocos/core/math/vec3.ts | 49 ++++++++++++++------------ tests/core/math/vec3.test.ts | 66 ++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 22 deletions(-) diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index a82d05dfa0e..969ae9290a2 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -408,7 +408,7 @@ export class Vec3 extends ValueType { // If the directions are almost opposite, // every vector that orthonormal to the directions can be the rotation axis. const fromNormalized = Vec3.multiplyScalar(cacheV1, from, 1.0 / lenFrom); - const axis = chooseAnyPerpendicular(cacheV2, fromNormalized); + const axis = Vec3.generateOrthogonal(cacheV2, fromNormalized); const angle = Math.PI * t; rotateAxisAngle(cacheV3, fromNormalized, axis, angle); Vec3.multiplyScalar(out, cacheV3, lenLerped); @@ -801,6 +801,32 @@ export class Vec3 extends ValueType { return out; } + /** + * @zh 生成指定向量的一个正交单位向量。如果指定的向量 **精确地** 是零向量,则返回 **精确的** 零向量。 + * @en Generates an unit vector orthogonal to specified vector. + * If the specified vector is **strictly** zero vector, the result is **strict** zero vector. + * @param out @zh 生成的向量。@en The generated vector. + * @param n @zh 输入向量。该向量 **不必** 是标准化的。 @en The input vector. **Need not** to be normalized. + * @returns `out` + */ + public static generateOrthogonal (out: Out, n: Readonly): Out { + const { x, y, z } = n; + // 1. Drop the component with minimal magnitude. + // 2. Negate one of the remain components. + // 3. Swap the remain components. + const absX = Math.abs(x); + const absY = Math.abs(y); + const absZ = Math.abs(z); + if (absX < absY && absX < absZ) { + Vec3.set(out, 0.0, z, -y); + } else if (absY < absZ) { + Vec3.set(out, z, 0.0, -x); + } else { + Vec3.set(out, y, -x, 0.0); + } + return Vec3.normalize(out, out); + } + /** * @en x component. * @zh x 分量。 @@ -1185,27 +1211,6 @@ export function v3 (x?: number | Vec3, y?: number, z?: number): Vec3 { return new Vec3(x as any, y, z); } -/** - * Chooses an arbitrary unit vector that is perpendicular to input. - */ -function chooseAnyPerpendicular (out: Vec3, v: Readonly): Vec3 { - const { x, y, z } = v; - // 1. Drop the component with minimal magnitude. - // 2. Negate one of the remain components. - // 3. Swap the remain components. - const absX = Math.abs(x); - const absY = Math.abs(y); - const absZ = Math.abs(z); - if (absX < absY && absX < absZ) { - Vec3.set(out, 0.0, z, -y); - } else if (absY < absZ) { - Vec3.set(out, z, 0.0, -x); - } else { - Vec3.set(out, y, -x, 0.0); - } - return Vec3.normalize(out, out); -} - /** * Rotates `input` around `axis` for `angle` radians. */ diff --git a/tests/core/math/vec3.test.ts b/tests/core/math/vec3.test.ts index f28b16de61b..b7020520af6 100644 --- a/tests/core/math/vec3.test.ts +++ b/tests/core/math/vec3.test.ts @@ -3,6 +3,7 @@ import { Vec3 } from '../../../cocos/core/math/vec3'; import { Mat3 } from '../../../cocos/core/math/mat3'; import { Mat4 } from '../../../cocos/core/math/mat4'; import { Quat } from '../../../cocos/core/math/quat'; +import '../../utils/matchers/value-type-asymmetric-matchers'; describe('Test Vec3', () => { test('normalize', () => { @@ -169,4 +170,69 @@ describe('Test Vec3', () => { log('moveTowards: ', value0); expect(Vec3.equals(value0, expect0)).toBe(true); }); + + test(`generateOrthogonal`, () => { + // Zero input results zero result. + expect(gen(Vec3.ZERO)).toBeCloseToVec3(Vec3.ZERO); + + // Even the input is very close to zero, the result is not zero. + expect(gen(Vec3.add(new Vec3(), Vec3.ZERO, new Vec3(1e-10, 1e-20, 1e-30)))).toEqual({ + x: 9.999999999999999e-11, + y: -1, + z: 0, + }); + + // Especially observe the behavior on standard unit vectors. + { + for (const len of [1, -1, 0.3, -6.18]) { + if (len > 0) { + expect(gen(new Vec3(len, 0, 0))).toBeCloseToVec3(new Vec3(0, -1, 0)); + expect(gen(new Vec3(0, len, 0))).toBeCloseToVec3(new Vec3(1, 0, 0)); + expect(gen(new Vec3(0, 0, len))).toBeCloseToVec3(new Vec3(1, 0, 0)); + } else { + expect(gen(new Vec3(len, 0, 0))).toBeCloseToVec3(new Vec3(0, 1, 0)); + expect(gen(new Vec3(0, len, 0))).toBeCloseToVec3(new Vec3(-1, 0, 0)); + expect(gen(new Vec3(0, 0, len))).toBeCloseToVec3(new Vec3(-1, 0, 0)); + } + } + } + + expect(gen(new Vec3(1, -2, 3))).toEqual({ + x: 0, + y: 0.8320502943378437, + z: 0.5547001962252291, + }); + expect(gen(new Vec3(1, -1, -1))).toEqual({ + x: -0.7071067811865475, + y: -0.7071067811865475, + z: 0, + }); + + // The input vector need not to be normalized, + // but its effect should be equivalent to its normalized version. + ((v: Readonly) => void expect(gen(v)).toBeCloseToVec3(gen(Vec3.normalize(new Vec3(), v))))( + new Vec3(1, -2, 3)); + + function gen (input: Readonly) { + const result = new Vec3(Number.NaN, Number.NaN, Number.NaN); + + // The input should not be modified. + const inputFrozen = Object.freeze(Vec3.clone(input)); + + // The return value should be the `out` argument. + expect(Vec3.generateOrthogonal(result, inputFrozen)).toBe(result); + + if (Vec3.strictEquals(input, Vec3.ZERO)) { + // If the input is strictly 0, the result should be strictly 0. + expect(Vec3.strictEquals(result, Vec3.ZERO)).toBe(true); + } else { + // Otherwise, the result should be normalized. + expect(Vec3.lengthSqr(result)).toBeCloseTo(1, 5); + // The result should be orthogonal to input. + expect(Vec3.angle(input, result)).toBeCloseTo(Math.PI / 2, 5); + } + + return result; + }; + }); }); \ No newline at end of file From f26e2c4326e9395d6b71bb80bada02b3d3fe2ff5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 14 Jul 2023 13:42:14 +0800 Subject: [PATCH 041/232] Upgrade eslint, relax eslint rule explicit-function-return-type (#15723) * Upgrade eslint, relax explicit-function-return-type * Update .eslintrc.yaml Co-authored-by: PP --------- Co-authored-by: PP --- .eslintrc.yaml | 7 +- package-lock.json | 3045 ++++++++++++++++++++++++++------------------- package.json | 28 +- 3 files changed, 1798 insertions(+), 1282 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 98e5a9d4498..33743846d93 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -11,8 +11,7 @@ extends: - plugin:@typescript-eslint/recommended - plugin:@typescript-eslint/recommended-requiring-type-checking -plugins: - - '@typescript-eslint' +plugins: ["@typescript-eslint"] settings: import/resolver: @@ -146,4 +145,6 @@ rules: # Prefer the interface style. '@typescript-eslint/consistent-type-definitions': [error, interface] - '@typescript-eslint/explicit-function-return-type': [error] + '@typescript-eslint/explicit-function-return-type': [error, { + allowIIFEs: true, // IIFEs are widely used, writing their signature twice is painful + }] diff --git a/package-lock.json b/package-lock.json index a39812198e8..0fa7f37bda9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,12 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "@aashutoshrathi/word-wrap": { + "version": "1.2.6", + "resolved": "https://registry.npmmirror.com/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz", + "integrity": "sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==", + "dev": true + }, "@ampproject/remapping": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", @@ -1116,7 +1122,7 @@ }, "@babel/plugin-syntax-async-generators": { "version": "7.8.4", - "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-async-generators/download/@babel/plugin-syntax-async-generators-7.8.4.tgz", + "resolved": "https://registry.nlark.com/@babel/plugin-syntax-async-generators/download/@babel/plugin-syntax-async-generators-7.8.4.tgz", "integrity": "sha1-qYP7Gusuw/btBCohD2QOkOeG/g0=", "dev": true, "requires": { @@ -1168,7 +1174,7 @@ }, "@babel/plugin-syntax-dynamic-import": { "version": "7.8.3", - "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-dynamic-import/download/@babel/plugin-syntax-dynamic-import-7.8.3.tgz", + "resolved": "https://registry.nlark.com/@babel/plugin-syntax-dynamic-import/download/@babel/plugin-syntax-dynamic-import-7.8.3.tgz?cache=0&sync_timestamp=1618847125283&other_urls=https%3A%2F%2Fregistry.nlark.com%2F%40babel%2Fplugin-syntax-dynamic-import%2Fdownload%2F%40babel%2Fplugin-syntax-dynamic-import-7.8.3.tgz", "integrity": "sha1-Yr+Ysto80h1iYVT8lu5bPLaOrLM=", "dev": true, "requires": { @@ -1211,7 +1217,7 @@ }, "@babel/plugin-syntax-json-strings": { "version": "7.8.3", - "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-json-strings/download/@babel/plugin-syntax-json-strings-7.8.3.tgz", + "resolved": "https://registry.nlark.com/@babel/plugin-syntax-json-strings/download/@babel/plugin-syntax-json-strings-7.8.3.tgz", "integrity": "sha1-AcohtmjNghjJ5kDLbdiMVBKyyWo=", "dev": true, "requires": { @@ -1220,7 +1226,7 @@ }, "@babel/plugin-syntax-logical-assignment-operators": { "version": "7.10.4", - "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-logical-assignment-operators/download/@babel/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "resolved": "https://registry.nlark.com/@babel/plugin-syntax-logical-assignment-operators/download/@babel/plugin-syntax-logical-assignment-operators-7.10.4.tgz", "integrity": "sha1-ypHvRjA1MESLkGZSusLp/plB9pk=", "dev": true, "requires": { @@ -1263,7 +1269,7 @@ }, "@babel/plugin-syntax-object-rest-spread": { "version": "7.8.3", - "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-object-rest-spread/download/@babel/plugin-syntax-object-rest-spread-7.8.3.tgz", + "resolved": "https://registry.nlark.com/@babel/plugin-syntax-object-rest-spread/download/@babel/plugin-syntax-object-rest-spread-7.8.3.tgz", "integrity": "sha1-YOIl7cvZimQDMqLnLdPmbxr1WHE=", "dev": true, "requires": { @@ -1281,7 +1287,7 @@ }, "@babel/plugin-syntax-optional-chaining": { "version": "7.8.3", - "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-optional-chaining/download/@babel/plugin-syntax-optional-chaining-7.8.3.tgz", + "resolved": "https://registry.nlark.com/@babel/plugin-syntax-optional-chaining/download/@babel/plugin-syntax-optional-chaining-7.8.3.tgz", "integrity": "sha1-T2nCq5UWfgGAzVM2YT+MV4j31Io=", "dev": true, "requires": { @@ -1641,7 +1647,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.npmmirror.com/@babel/preset-env/download/@babel/preset-env-7.8.7.tgz?cache=0&sync_timestamp=1637103615805&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40babel%2Fpreset-env%2Fdownload%2F%40babel%2Fpreset-env-7.8.7.tgz", "integrity": "sha1-H8fYnH910tcMK2do3mwuBJs8uds=", "dev": true, "requires": { @@ -1817,7 +1823,7 @@ }, "@cocos/box2d": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/@cocos/box2d/download/@cocos/box2d-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/@cocos/box2d/download/@cocos/box2d-1.0.1.tgz", "integrity": "sha1-Fc2lzPxRCCt91tNoo+S55IXS5To=", "requires": { "@types/systemjs": "^0.20.6" @@ -1857,13 +1863,13 @@ "dependencies": { "ansi-regex": { "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { @@ -1872,7 +1878,7 @@ }, "cliui": { "version": "6.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "resolved": "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz", "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", "dev": true, "requires": { @@ -1883,7 +1889,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { @@ -1892,13 +1898,13 @@ }, "color-name": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "find-up": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "resolved": "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { @@ -1908,7 +1914,7 @@ }, "fs-extra": { "version": "8.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "resolved": "https://registry.npmmirror.com/fs-extra/-/fs-extra-8.1.0.tgz", "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", "dev": true, "requires": { @@ -1919,7 +1925,7 @@ }, "get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "resolved": "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, @@ -1934,13 +1940,13 @@ }, "is-fullwidth-code-point": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "locate-path": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { @@ -1949,7 +1955,7 @@ }, "p-locate": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { @@ -1958,13 +1964,13 @@ }, "path-exists": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "require-main-filename": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, @@ -1990,7 +1996,7 @@ }, "string-width": { "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "requires": { @@ -2001,7 +2007,7 @@ }, "strip-ansi": { "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { @@ -2016,7 +2022,7 @@ }, "wrap-ansi": { "version": "6.2.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz", "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "requires": { @@ -2027,13 +2033,13 @@ }, "y18n": { "version": "4.0.3", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "resolved": "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz", "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true }, "yargs": { "version": "15.4.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "resolved": "https://registry.npmmirror.com/yargs/-/yargs-15.4.1.tgz", "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "requires": { @@ -2052,7 +2058,7 @@ }, "yargs-parser": { "version": "18.1.3", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-18.1.3.tgz", "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", "dev": true, "requires": { @@ -3528,40 +3534,58 @@ "integrity": "sha512-A9983Q0LnDGdLPjxyXQ00sbV+K+O+ko2Dr+CZigbHWtX9pNfxlaBkMR8X1CztI73zuEyEBXTVjx7CE+/VSwDiQ==" }, "@eslint/eslintrc": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", - "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/@eslint/eslintrc/-/eslintrc-2.1.0.tgz", + "integrity": "sha512-Lj7DECXqIVCqnqjjHMPna4vn6GJcMgul/wuS0je9OZ9gsL0zzDpKPVtcG1HaDVc+9y+qgXneTeUMbCqXJNpH1A==", "dev": true, "requires": { "ajv": "^6.12.4", - "debug": "^4.1.1", - "espree": "^7.3.0", - "globals": "^13.9.0", - "ignore": "^4.0.6", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", "strip-json-comments": "^3.1.1" }, "dependencies": { + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, "globals": { - "version": "13.11.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.11.0.tgz", - "integrity": "sha512-08/xrJ7wQjK9kkkRoI3OFUBbLx4f+6x3SGwcPvQ0QH6goFDrOU2oyAWrmh3dJezu65buo+HBMzAMQy6rovVC3g==", + "version": "13.20.0", + "resolved": "https://registry.npmmirror.com/globals/-/globals-13.20.0.tgz", + "integrity": "sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ==", "dev": true, "requires": { "type-fest": "^0.20.2" } }, - "ignore": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", - "dev": true + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "requires": { + "argparse": "^2.0.1" + } }, "type-fest": { "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "resolved": "https://registry.npmmirror.com/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true } @@ -3573,14 +3597,14 @@ "integrity": "sha512-lxJ9R5ygVm8ZWgYdUweoq5ownDlJ4upvoWmO4eLxBYHdMo+vZ/Rx0EN6MbKWDJOSUGrqJy2Gt+Dyv/VKml0fjg==" }, "@humanwhocodes/config-array": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", - "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "version": "0.11.10", + "resolved": "https://registry.npmmirror.com/@humanwhocodes/config-array/-/config-array-0.11.10.tgz", + "integrity": "sha512-KVVjQmNUepDVGXNuoRRdmmEjruj0KfiGSbS8LVc12LMsWDQzRXJ0qdhN8L8uUigKpfEHRhlaQFY0ib1tnUbNeQ==", "dev": true, "requires": { - "@humanwhocodes/object-schema": "^1.2.0", + "@humanwhocodes/object-schema": "^1.2.1", "debug": "^4.1.1", - "minimatch": "^3.0.4" + "minimatch": "^3.0.5" } }, "@humanwhocodes/module-importer": { @@ -3589,9 +3613,9 @@ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==" }, "@humanwhocodes/object-schema": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz", - "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==", + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", + "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", "dev": true }, "@istanbuljs/load-nyc-config": { @@ -5821,7 +5845,7 @@ }, "@jest/types": { "version": "24.9.0", - "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-24.9.0.tgz", + "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-24.9.0.tgz", "integrity": "sha1-Y8smy3UA0Gnlo4lEGnxqtekJ/Fk=", "dev": true, "requires": { @@ -5852,7 +5876,7 @@ }, "@jridgewell/resolve-uri": { "version": "3.0.7", - "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.0.7.tgz", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.0.7.tgz", "integrity": "sha512-8cXDaBBHOr2pQ7j77Y6Vp5VDT2sIqWyWQ56TjEq4ih/a4iST3dItRe8Q9fp0rrIl9DoKhWQtUQz/YpOxLkXbNA==" }, "@jridgewell/set-array": { @@ -5885,12 +5909,12 @@ }, "@jridgewell/sourcemap-codec": { "version": "1.4.13", - "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.13.tgz", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.13.tgz", "integrity": "sha512-GryiOJmNcWbovBxTfZSF71V/mXbgcV3MewDe3kIMCLyIh5e7SKAeUZs+rMnJ8jkMolZ/4/VsdBmMrw3l+VdZ3w==" }, "@jridgewell/trace-mapping": { "version": "0.3.13", - "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.13.tgz", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.13.tgz", "integrity": "sha512-o1xbKhp9qnIAoHJSWd6KlCZfqslL4valSF81H8ImioOAxluWYWOpWkpyktY2vnt4tbrX9XYaxovq6cgowaJp2w==", "requires": { "@jridgewell/resolve-uri": "^3.0.3", @@ -6148,7 +6172,7 @@ }, "@types/fs-extra": { "version": "5.1.0", - "resolved": "https://registry.npm.taobao.org/@types/fs-extra/download/@types/fs-extra-5.1.0.tgz", + "resolved": "https://registry.npmmirror.com/@types/fs-extra/download/@types/fs-extra-5.1.0.tgz", "integrity": "sha1-KjJe+XkBUEo4KHGMOQ00uEJqEKE=", "dev": true, "requires": { @@ -6181,7 +6205,7 @@ }, "@types/istanbul-reports": { "version": "1.1.2", - "resolved": "https://registry.npm.taobao.org/@types/istanbul-reports/download/@types/istanbul-reports-1.1.2.tgz?cache=0&sync_timestamp=1613379043554&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Fistanbul-reports%2Fdownload%2F%40types%2Fistanbul-reports-1.1.2.tgz", + "resolved": "https://registry.npmmirror.com/@types/istanbul-reports/download/@types/istanbul-reports-1.1.2.tgz?cache=0&sync_timestamp=1637266160892&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fistanbul-reports%2Fdownload%2F%40types%2Fistanbul-reports-1.1.2.tgz", "integrity": "sha1-6HXMaJ5HvOVJ7IHz315vbxHPrrI=", "dev": true, "requires": { @@ -6191,7 +6215,7 @@ }, "@types/jest": { "version": "24.9.1", - "resolved": "https://registry.npm.taobao.org/@types/jest/download/@types/jest-24.9.1.tgz?cache=0&sync_timestamp=1616695463771&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Fjest%2Fdownload%2F%40types%2Fjest-24.9.1.tgz", + "resolved": "https://registry.npmmirror.com/@types/jest/download/@types/jest-24.9.1.tgz", "integrity": "sha1-Arr5Vzx48bmXSl82d4s2aqd71TQ=", "dev": true, "requires": { @@ -6214,6 +6238,12 @@ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz", "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==" }, + "@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmmirror.com/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true + }, "@types/node": { "version": "13.1.7", "resolved": "https://registry.npm.taobao.org/@types/node/download/@types/node-13.1.7.tgz", @@ -6276,33 +6306,79 @@ "dev": true }, "@typescript-eslint/eslint-plugin": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.29.3.tgz", - "integrity": "sha512-tBgfA3K/3TsZY46ROGvoRxQr1wBkclbVqRQep97MjVHJzcRBURRY3sNFqLk0/Xr//BY5hM9H2p/kp+6qim85SA==", + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.0.0.tgz", + "integrity": "sha512-xuv6ghKGoiq856Bww/yVYnXGsKa588kY3M0XK7uUW/3fJNNULKRfZfSBkMTSpqGG/8ZCXCadfh8G/z/B4aqS/A==", "dev": true, "requires": { - "@typescript-eslint/experimental-utils": "4.29.3", - "@typescript-eslint/scope-manager": "4.29.3", - "debug": "^4.3.1", - "functional-red-black-tree": "^1.0.1", - "regexpp": "^3.1.0", - "semver": "^7.3.5", - "tsutils": "^3.21.0" + "@eslint-community/regexpp": "^4.5.0", + "@typescript-eslint/scope-manager": "6.0.0", + "@typescript-eslint/type-utils": "6.0.0", + "@typescript-eslint/utils": "6.0.0", + "@typescript-eslint/visitor-keys": "6.0.0", + "debug": "^4.3.4", + "grapheme-splitter": "^1.0.4", + "graphemer": "^1.4.0", + "ignore": "^5.2.4", + "natural-compare": "^1.4.0", + "natural-compare-lite": "^1.4.0", + "semver": "^7.5.0", + "ts-api-utils": "^1.0.1" }, "dependencies": { + "@eslint-community/regexpp": { + "version": "4.5.1", + "resolved": "https://registry.npmmirror.com/@eslint-community/regexpp/-/regexpp-4.5.1.tgz", + "integrity": "sha512-Z5ba73P98O1KUYCCJTUeVpja9RcGoMdncZ6T49FCUl2lN38JtCJ+3WgIDBv0AuY4WChU5PmtJmOCTlN6FZTFKQ==", + "dev": true + }, + "@types/json-schema": { + "version": "7.0.12", + "resolved": "https://registry.npmmirror.com/@types/json-schema/-/json-schema-7.0.12.tgz", + "integrity": "sha512-Hr5Jfhc9eYOQNPYO5WLDq/n4jqijdHNlDXjuAQkkt+mWdQR+XJToOHrsD4cPaMXpn6KO7y2+wM8AZEs8VpBLVA==", + "dev": true + }, + "@typescript-eslint/type-utils": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/type-utils/-/type-utils-6.0.0.tgz", + "integrity": "sha512-ah6LJvLgkoZ/pyJ9GAdFkzeuMZ8goV6BH7eC9FPmojrnX9yNCIsfjB+zYcnex28YO3RFvBkV6rMV6WpIqkPvoQ==", + "dev": true, + "requires": { + "@typescript-eslint/typescript-estree": "6.0.0", + "@typescript-eslint/utils": "6.0.0", + "debug": "^4.3.4", + "ts-api-utils": "^1.0.1" + } + }, + "@typescript-eslint/utils": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/utils/-/utils-6.0.0.tgz", + "integrity": "sha512-SOr6l4NB6HE4H/ktz0JVVWNXqCJTOo/mHnvIte1ZhBQ0Cvd04x5uKZa3zT6tiodL06zf5xxdK8COiDvPnQ27JQ==", + "dev": true, + "requires": { + "@eslint-community/eslint-utils": "^4.3.0", + "@types/json-schema": "^7.0.11", + "@types/semver": "^7.3.12", + "@typescript-eslint/scope-manager": "6.0.0", + "@typescript-eslint/types": "6.0.0", + "@typescript-eslint/typescript-estree": "6.0.0", + "eslint-scope": "^5.1.1", + "semver": "^7.5.0" + } + }, "debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "version": "4.3.4", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dev": true, "requires": { "ms": "2.1.2" } }, "semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "version": "7.5.4", + "resolved": "https://registry.npmmirror.com/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, "requires": { "lru-cache": "^6.0.0" @@ -6310,36 +6386,23 @@ } } }, - "@typescript-eslint/experimental-utils": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.29.3.tgz", - "integrity": "sha512-ffIvbytTVWz+3keg+Sy94FG1QeOvmV9dP2YSdLFHw/ieLXWCa3U1TYu8IRCOpMv2/SPS8XqhM1+ou1YHsdzKrg==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.7", - "@typescript-eslint/scope-manager": "4.29.3", - "@typescript-eslint/types": "4.29.3", - "@typescript-eslint/typescript-estree": "4.29.3", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" - } - }, "@typescript-eslint/parser": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-4.29.3.tgz", - "integrity": "sha512-jrHOV5g2u8ROghmspKoW7pN8T/qUzk0+DITun0MELptvngtMrwUJ1tv5zMI04CYVEUsSrN4jV7AKSv+I0y0EfQ==", + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-6.0.0.tgz", + "integrity": "sha512-TNaufYSPrr1U8n+3xN+Yp9g31vQDJqhXzzPSHfQDLcaO4tU+mCfODPxCwf4H530zo7aUBE3QIdxCXamEnG04Tg==", "dev": true, "requires": { - "@typescript-eslint/scope-manager": "4.29.3", - "@typescript-eslint/types": "4.29.3", - "@typescript-eslint/typescript-estree": "4.29.3", - "debug": "^4.3.1" + "@typescript-eslint/scope-manager": "6.0.0", + "@typescript-eslint/types": "6.0.0", + "@typescript-eslint/typescript-estree": "6.0.0", + "@typescript-eslint/visitor-keys": "6.0.0", + "debug": "^4.3.4" }, "dependencies": { "debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "version": "4.3.4", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dev": true, "requires": { "ms": "2.1.2" @@ -6348,13 +6411,13 @@ } }, "@typescript-eslint/scope-manager": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.29.3.tgz", - "integrity": "sha512-x+w8BLXO7iWPkG5mEy9bA1iFRnk36p/goVlYobVWHyDw69YmaH9q6eA+Fgl7kYHmFvWlebUTUfhtIg4zbbl8PA==", + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-6.0.0.tgz", + "integrity": "sha512-o4q0KHlgCZTqjuaZ25nw5W57NeykZT9LiMEG4do/ovwvOcPnDO1BI5BQdCsUkjxFyrCL0cSzLjvIMfR9uo7cWg==", "dev": true, "requires": { - "@typescript-eslint/types": "4.29.3", - "@typescript-eslint/visitor-keys": "4.29.3" + "@typescript-eslint/types": "6.0.0", + "@typescript-eslint/visitor-keys": "6.0.0" } }, "@typescript-eslint/type-utils": { @@ -6509,57 +6572,137 @@ } }, "@typescript-eslint/types": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.29.3.tgz", - "integrity": "sha512-s1eV1lKNgoIYLAl1JUba8NhULmf+jOmmeFO1G5MN/RBCyyzg4TIOfIOICVNC06lor+Xmy4FypIIhFiJXOknhIg==", + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/types/-/types-6.0.0.tgz", + "integrity": "sha512-Zk9KDggyZM6tj0AJWYYKgF0yQyrcnievdhG0g5FqyU3Y2DRxJn4yWY21sJC0QKBckbsdKKjYDV2yVrrEvuTgxg==", "dev": true }, "@typescript-eslint/typescript-estree": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.29.3.tgz", - "integrity": "sha512-45oQJA0bxna4O5TMwz55/TpgjX1YrAPOI/rb6kPgmdnemRZx/dB0rsx+Ku8jpDvqTxcE1C/qEbVHbS3h0hflag==", + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.0.0.tgz", + "integrity": "sha512-2zq4O7P6YCQADfmJ5OTDQTP3ktajnXIRrYAtHM9ofto/CJZV3QfJ89GEaM2BNGeSr1KgmBuLhEkz5FBkS2RQhQ==", "dev": true, "requires": { - "@typescript-eslint/types": "4.29.3", - "@typescript-eslint/visitor-keys": "4.29.3", - "debug": "^4.3.1", - "globby": "^11.0.3", - "is-glob": "^4.0.1", - "semver": "^7.3.5", - "tsutils": "^3.21.0" + "@typescript-eslint/types": "6.0.0", + "@typescript-eslint/visitor-keys": "6.0.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.5.0", + "ts-api-utils": "^1.0.1" }, "dependencies": { + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, "debug": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", - "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "version": "4.3.4", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dev": true, "requires": { "ms": "2.1.2" } }, + "fast-glob": { + "version": "3.3.0", + "resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.0.tgz", + "integrity": "sha512-ChDuvbOypPuNjO8yIDf36x7BlZX1smcUMTTcyoIjycexOxd6DFsKsg21qVBzEmr3G7fUKIRy2/psii+CIUt7FA==", + "dev": true, + "requires": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "requires": { + "is-glob": "^4.0.1" + } + }, "globby": { - "version": "11.0.4", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.4.tgz", - "integrity": "sha512-9O4MVG9ioZJ08ffbcyVYyLOJLk5JQ688pJ4eMGLpdWLHq/Wr1D9BlriLQyL0E+jbkuePVZXYFj47QM/v093wHg==", + "version": "11.1.0", + "resolved": "https://registry.npmmirror.com/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", "dev": true, "requires": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", - "fast-glob": "^3.1.1", - "ignore": "^5.1.4", - "merge2": "^1.3.0", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", "slash": "^3.0.0" } }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "requires": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + } + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true + }, "semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "version": "7.5.4", + "resolved": "https://registry.npmmirror.com/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, "requires": { "lru-cache": "^6.0.0" } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } } } }, @@ -6728,13 +6871,13 @@ } }, "@typescript-eslint/visitor-keys": { - "version": "4.29.3", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.29.3.tgz", - "integrity": "sha512-MGGfJvXT4asUTeVs0Q2m+sY63UsfnA+C/FDgBKV3itLBmM9H0u+URcneePtkd0at1YELmZK6HSolCqM4Fzs6yA==", + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.0.0.tgz", + "integrity": "sha512-cvJ63l8c0yXdeT5POHpL0Q1cZoRcmRKFCtSjNGJxPkcP571EfZMcNbzWAc7oK3D1dRzm/V5EwtkANTZxqvuuUA==", "dev": true, "requires": { - "@typescript-eslint/types": "4.29.3", - "eslint-visitor-keys": "^2.0.0" + "@typescript-eslint/types": "6.0.0", + "eslint-visitor-keys": "^3.4.1" } }, "JSONStream": { @@ -6749,7 +6892,7 @@ }, "abab": { "version": "2.0.6", - "resolved": "https://registry.npmmirror.com/abab/-/abab-2.0.6.tgz", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", "dev": true }, @@ -6761,7 +6904,7 @@ }, "acorn-globals": { "version": "6.0.0", - "resolved": "https://registry.npmmirror.com/acorn-globals/-/acorn-globals-6.0.0.tgz", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz", "integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==", "dev": true, "requires": { @@ -6787,13 +6930,13 @@ }, "acorn-walk": { "version": "7.2.0", - "resolved": "https://registry.npm.taobao.org/acorn-walk/download/acorn-walk-7.2.0.tgz", + "resolved": "https://registry.nlark.com/acorn-walk/download/acorn-walk-7.2.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.nlark.com%2Facorn-walk%2Fdownload%2Facorn-walk-7.2.0.tgz", "integrity": "sha1-DeiJpgEgOQmw++B7iTjcIdLpZ7w=", "dev": true }, "agent-base": { "version": "6.0.2", - "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", "dev": true, "requires": { @@ -6856,7 +6999,7 @@ }, "ansi-styles": { "version": "3.2.1", - "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-3.2.1.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-3.2.1.tgz", "integrity": "sha1-QfuyAkPlCxK+DwS43tvwdSDOhB0=", "requires": { "color-convert": "^1.9.0" @@ -6864,13 +7007,13 @@ }, "ansi-wrap": { "version": "0.1.0", - "resolved": "https://registry.npm.taobao.org/ansi-wrap/download/ansi-wrap-0.1.0.tgz", + "resolved": "https://registry.nlark.com/ansi-wrap/download/ansi-wrap-0.1.0.tgz", "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", "dev": true }, "anymatch": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/anymatch/download/anymatch-2.0.0.tgz", + "resolved": "https://registry.nlark.com/anymatch/download/anymatch-2.0.0.tgz", "integrity": "sha1-vLJLTzeTTZqnrBe0ra+J58du8us=", "dev": true, "requires": { @@ -6889,7 +7032,7 @@ }, "archy": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/archy/download/archy-1.0.0.tgz", + "resolved": "https://registry.nlark.com/archy/download/archy-1.0.0.tgz", "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", "dev": true }, @@ -6904,7 +7047,7 @@ }, "arr-diff": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/arr-diff/download/arr-diff-4.0.0.tgz", + "resolved": "https://registry.nlark.com/arr-diff/download/arr-diff-4.0.0.tgz", "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", "dev": true }, @@ -6919,13 +7062,13 @@ }, "arr-flatten": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/arr-flatten/download/arr-flatten-1.1.0.tgz", + "resolved": "https://registry.nlark.com/arr-flatten/download/arr-flatten-1.1.0.tgz", "integrity": "sha1-NgSLv/TntH4TZkQxbJlmnqWukfE=", "dev": true }, "arr-map": { "version": "2.0.2", - "resolved": "https://registry.npm.taobao.org/arr-map/download/arr-map-2.0.2.tgz", + "resolved": "https://registry.nlark.com/arr-map/download/arr-map-2.0.2.tgz", "integrity": "sha1-Onc0X/wc814qkYJWAfnljy4kysQ=", "dev": true, "requires": { @@ -6934,10 +7077,50 @@ }, "arr-union": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/arr-union/download/arr-union-3.1.0.tgz", + "resolved": "https://registry.nlark.com/arr-union/download/arr-union-3.1.0.tgz", "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", "dev": true }, + "array-buffer-byte-length": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/array-buffer-byte-length/-/array-buffer-byte-length-1.0.0.tgz", + "integrity": "sha512-LPuwb2P+NrQw3XhxGc36+XSvuBPopovXYTR9Ew++Du9Yb/bx5AzBfrIsBoj0EZUifjQU+sHL21sseZ3jerWO/A==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "is-array-buffer": "^3.0.1" + }, + "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + } + } + }, "array-each": { "version": "1.0.1", "resolved": "https://registry.npm.taobao.org/array-each/download/array-each-1.0.1.tgz", @@ -6945,21 +7128,21 @@ "dev": true }, "array-includes": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.3.tgz", - "integrity": "sha512-gcem1KlBU7c9rB+Rq8/3PPKsK2kjqeEBa3bD5kkQo4nYlOHQCJqIJFqBXDEfwaRuYTT4E+FxA9xez7Gf/e3Q7A==", + "version": "3.1.6", + "resolved": "https://registry.npmmirror.com/array-includes/-/array-includes-3.1.6.tgz", + "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.0-next.2", - "get-intrinsic": "^1.1.1", - "is-string": "^1.0.5" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "get-intrinsic": "^1.1.3", + "is-string": "^1.0.7" }, "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -6967,16 +7150,33 @@ "get-intrinsic": "^1.0.2" } }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", "dev": true, "requires": { "function-bind": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true } } }, @@ -7042,49 +7242,142 @@ }, "array-union": { "version": "2.1.0", - "resolved": "https://registry.npm.taobao.org/array-union/download/array-union-2.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/array-union/download/array-union-2.1.0.tgz?cache=0&sync_timestamp=1614624262896&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Farray-union%2Fdownload%2Farray-union-2.1.0.tgz", "integrity": "sha1-t5hCCtvrHego2ErNii4j0+/oXo0=" }, "array-unique": { "version": "0.3.2", - "resolved": "https://registry.npm.taobao.org/array-unique/download/array-unique-0.3.2.tgz", + "resolved": "https://registry.nlark.com/array-unique/download/array-unique-0.3.2.tgz", "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "dev": true }, "array.prototype.flat": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.4.tgz", - "integrity": "sha512-4470Xi3GAPAjZqFcljX2xzckv1qeKPizoNkiS0+O4IoPR2ZNpcjE0pkhdihlDouK+x6QOast26B4Q/O9DJnwSg==", - "dev": true, - "requires": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.0-next.1" - } - }, - "asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "version": "1.3.1", + "resolved": "https://registry.npmmirror.com/array.prototype.flat/-/array.prototype.flat-1.3.1.tgz", + "integrity": "sha512-roTU0KWIOmJ4DRLmwKd19Otg0/mT3qPNt0Qb3GWW8iObuZXxrjB/pzn0R3hqpRSWg4HCwqx+0vwOnWnvlOyeIA==", "dev": true, "requires": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "es-shim-unscopables": "^1.0.0" }, "dependencies": { - "bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "dev": true - } - } - }, - "assert": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/assert/-/assert-1.5.0.tgz", + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + } + } + }, + "array.prototype.flatmap": { + "version": "1.3.1", + "resolved": "https://registry.npmmirror.com/array.prototype.flatmap/-/array.prototype.flatmap-1.3.1.tgz", + "integrity": "sha512-8UGn9O1FDVvMNB0UlLv4voxRMze7+FpHyF5mSMRjWHUMlpoDViniy05870VlxhfgTnLbpuwTzvD76MTtWxB/mQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", + "es-shim-unscopables": "^1.0.0" + }, + "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + } + } + }, + "asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + }, + "dependencies": { + "bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + } + } + }, + "assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.5.0.tgz", "integrity": "sha512-EDsgawzwoun2CZkCgtxJbv392v4nbk9XDD06zI+kQYoBM/3RBWLlEyJARDOmhAAosBjWACEkKL6S+lIZtcAubA==", "dev": true, "requires": { @@ -7115,12 +7408,6 @@ "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", "dev": true }, - "astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true - }, "async": { "version": "2.6.4", "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", @@ -7144,13 +7431,13 @@ }, "async-each": { "version": "1.0.3", - "resolved": "https://registry.npm.taobao.org/async-each/download/async-each-1.0.3.tgz", + "resolved": "https://registry.nlark.com/async-each/download/async-each-1.0.3.tgz", "integrity": "sha1-tyfb+H12UWAvBvTUrDh/R9kbDL8=", "dev": true }, "async-settle": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/async-settle/download/async-settle-1.0.0.tgz", + "resolved": "https://registry.nlark.com/async-settle/download/async-settle-1.0.0.tgz", "integrity": "sha1-HQqRS7Aldb7IqPOnTlCA9yssDGs=", "dev": true, "requires": { @@ -7159,13 +7446,13 @@ }, "asynckit": { "version": "0.4.0", - "resolved": "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "dev": true }, "atob": { "version": "2.1.2", - "resolved": "https://registry.npm.taobao.org/atob/download/atob-2.1.2.tgz", + "resolved": "https://registry.nlark.com/atob/download/atob-2.1.2.tgz", "integrity": "sha1-bZUX654DDSQ2ZmZR6GvZ9vE1M8k=", "dev": true }, @@ -7329,7 +7616,7 @@ }, "bach": { "version": "1.2.0", - "resolved": "https://registry.npm.taobao.org/bach/download/bach-1.2.0.tgz", + "resolved": "https://registry.npmmirror.com/bach/download/bach-1.2.0.tgz", "integrity": "sha1-Szzpa/JxNPeaG0FKUcFONMO9mIA=", "dev": true, "requires": { @@ -7375,7 +7662,7 @@ }, "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -7384,7 +7671,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -7412,13 +7699,13 @@ }, "basic-auth": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/basic-auth/download/basic-auth-1.1.0.tgz", + "resolved": "https://registry.nlark.com/basic-auth/download/basic-auth-1.1.0.tgz", "integrity": "sha1-RSIe5Cn37h5QNb4/UVM/HN/SmIQ=", "dev": true }, "binary-extensions": { "version": "1.13.1", - "resolved": "https://registry.npm.taobao.org/binary-extensions/download/binary-extensions-1.13.1.tgz", + "resolved": "https://registry.nlark.com/binary-extensions/download/binary-extensions-1.13.1.tgz", "integrity": "sha1-WYr+VHVbKGilMw0q/51Ou1Mgm2U=", "dev": true }, @@ -7440,7 +7727,7 @@ }, "brace-expansion": { "version": "1.1.11", - "resolved": "https://registry.npm.taobao.org/brace-expansion/download/brace-expansion-1.1.11.tgz", + "resolved": "https://registry.nlark.com/brace-expansion/download/brace-expansion-1.1.11.tgz", "integrity": "sha1-PH/L9SnYcibz0vUrlm/1Jx60Qd0=", "requires": { "balanced-match": "^1.0.0", @@ -7498,7 +7785,7 @@ }, "browser-process-hrtime": { "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, @@ -7762,7 +8049,7 @@ }, "bs-logger": { "version": "0.2.6", - "resolved": "https://registry.npm.taobao.org/bs-logger/download/bs-logger-0.2.6.tgz", + "resolved": "https://registry.nlark.com/bs-logger/download/bs-logger-0.2.6.tgz", "integrity": "sha1-6302UwenLPl0zGzadraDVK0za9g=", "dev": true, "requires": { @@ -7826,7 +8113,7 @@ }, "cache-base": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/cache-base/download/cache-base-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/cache-base/download/cache-base-1.0.1.tgz?cache=0&sync_timestamp=1636237266442&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fcache-base%2Fdownload%2Fcache-base-1.0.1.tgz", "integrity": "sha1-Cn9GQWgxyLZi7jb+TnxZ129marI=", "dev": true, "requires": { @@ -7859,12 +8146,12 @@ }, "callsites": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/callsites/download/callsites-3.1.0.tgz", + "resolved": "https://registry.nlark.com/callsites/download/callsites-3.1.0.tgz", "integrity": "sha1-s2MKvYlDQy9Us/BRkjjjPNffL3M=" }, "camelcase": { "version": "5.3.1", - "resolved": "https://registry.npm.taobao.org/camelcase/download/camelcase-5.3.1.tgz", + "resolved": "https://registry.npmmirror.com/camelcase/download/camelcase-5.3.1.tgz?cache=0&sync_timestamp=1636945130104&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fcamelcase%2Fdownload%2Fcamelcase-5.3.1.tgz", "integrity": "sha1-48mzFWnhBoEd8kL3FXJaH0xJQyA=", "dev": true }, @@ -7876,7 +8163,7 @@ }, "chalk": { "version": "2.4.2", - "resolved": "https://registry.npm.taobao.org/chalk/download/chalk-2.4.2.tgz?cache=0&sync_timestamp=1573282918610&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fchalk%2Fdownload%2Fchalk-2.4.2.tgz", + "resolved": "https://registry.npmmirror.com/chalk/download/chalk-2.4.2.tgz", "integrity": "sha1-zUJUFnelQzPPVBpJEIwUMrRMlCQ=", "requires": { "ansi-styles": "^3.2.1", @@ -7893,12 +8180,12 @@ "child_process": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/child_process/-/child_process-1.0.2.tgz", - "integrity": "sha1-sffn/HPSXn/R1FWtyU4UODAYK1o=", + "integrity": "sha512-Wmza/JzL0SiWz7kl6MhIKT5ceIlnFPJX+lwUGj7Clhy5MMldsSoJR0+uvRzOS5Kv45Mq7t1PoE8TsOA9bzvb6g==", "dev": true }, "chokidar": { "version": "2.1.8", - "resolved": "https://registry.npm.taobao.org/chokidar/download/chokidar-2.1.8.tgz", + "resolved": "https://registry.npmmirror.com/chokidar/download/chokidar-2.1.8.tgz", "integrity": "sha1-gEs6e2qZNYw8XGHnHYco8EHP+Rc=", "dev": true, "requires": { @@ -7918,7 +8205,7 @@ "dependencies": { "glob-parent": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/glob-parent/download/glob-parent-3.1.0.tgz?cache=0&sync_timestamp=1569108917227&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fglob-parent%2Fdownload%2Fglob-parent-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/glob-parent/download/glob-parent-3.1.0.tgz", "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", "dev": true, "requires": { @@ -7928,7 +8215,7 @@ "dependencies": { "is-glob": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/is-glob/download/is-glob-3.1.0.tgz", "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { @@ -7956,7 +8243,7 @@ }, "ci-info": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/ci-info/download/ci-info-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/ci-info/download/ci-info-2.0.0.tgz", "integrity": "sha1-Z6npZL4xpR4V5QENWObxKDQAL0Y=", "dev": true }, @@ -7978,7 +8265,7 @@ }, "class-utils": { "version": "0.3.6", - "resolved": "https://registry.npm.taobao.org/class-utils/download/class-utils-0.3.6.tgz", + "resolved": "https://registry.nlark.com/class-utils/download/class-utils-0.3.6.tgz", "integrity": "sha1-+TNprouafOAv1B+q0MqDAzGQxGM=", "dev": true, "requires": { @@ -8018,7 +8305,7 @@ }, "clone": { "version": "2.1.2", - "resolved": "https://registry.npm.taobao.org/clone/download/clone-2.1.2.tgz", + "resolved": "https://registry.nlark.com/clone/download/clone-2.1.2.tgz", "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", "dev": true }, @@ -8053,7 +8340,7 @@ }, "code-point-at": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/code-point-at/download/code-point-at-1.1.0.tgz", + "resolved": "https://registry.npmmirror.com/code-point-at/download/code-point-at-1.1.0.tgz", "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", "dev": true }, @@ -8065,7 +8352,7 @@ }, "collection-map": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/collection-map/download/collection-map-1.0.0.tgz", + "resolved": "https://registry.nlark.com/collection-map/download/collection-map-1.0.0.tgz", "integrity": "sha1-rqDwb40mx4DCt1SUOFVEsiVa8Yw=", "dev": true, "requires": { @@ -8086,7 +8373,7 @@ }, "color-convert": { "version": "1.9.3", - "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-1.9.3.tgz", + "resolved": "https://registry.nlark.com/color-convert/download/color-convert-1.9.3.tgz", "integrity": "sha1-u3GFBpDh8TZWfeYp0tVHHe2kweg=", "requires": { "color-name": "1.1.3" @@ -8137,7 +8424,7 @@ }, "combined-stream": { "version": "1.0.8", - "resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "dev": true, "requires": { @@ -8146,19 +8433,19 @@ }, "commander": { "version": "2.20.3", - "resolved": "https://registry.npm.taobao.org/commander/download/commander-2.20.3.tgz", + "resolved": "https://registry.npmmirror.com/commander/download/commander-2.20.3.tgz?cache=0&sync_timestamp=1634886357672&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fcommander%2Fdownload%2Fcommander-2.20.3.tgz", "integrity": "sha1-/UhehMA+tIgcIHIrpIA16FMa6zM=", "dev": true }, "commondir": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/commondir/-/commondir-1.0.1.tgz", "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", "dev": true }, "component-emitter": { "version": "1.3.0", - "resolved": "https://registry.npm.taobao.org/component-emitter/download/component-emitter-1.3.0.tgz", + "resolved": "https://registry.nlark.com/component-emitter/download/component-emitter-1.3.0.tgz", "integrity": "sha1-FuQHD7qK4ptnnyIVhT7hgasuq8A=", "dev": true }, @@ -8169,7 +8456,7 @@ }, "concat-stream": { "version": "1.6.2", - "resolved": "https://registry.npm.taobao.org/concat-stream/download/concat-stream-1.6.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fconcat-stream%2Fdownload%2Fconcat-stream-1.6.2.tgz", + "resolved": "https://registry.nlark.com/concat-stream/download/concat-stream-1.6.2.tgz", "integrity": "sha1-kEvfGUzTEi/Gdcd/xKw9T/D9GjQ=", "dev": true, "requires": { @@ -8180,9 +8467,9 @@ } }, "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==", + "version": "1.0.11", + "resolved": "https://registry.npmmirror.com/confusing-browser-globals/-/confusing-browser-globals-1.0.11.tgz", + "integrity": "sha512-JsPKdmh8ZkmnHxDk55FZ1TqVLvEQTvoByJZRN9jzI0UjxK/QgAmsphz7PGtqgPieQZ/CQcHWXCR7ATDNhGe+YA==", "dev": true }, "console-browserify": { @@ -8207,7 +8494,7 @@ }, "copy-descriptor": { "version": "0.1.1", - "resolved": "https://registry.npm.taobao.org/copy-descriptor/download/copy-descriptor-0.1.1.tgz", + "resolved": "https://registry.nlark.com/copy-descriptor/download/copy-descriptor-0.1.1.tgz", "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", "dev": true }, @@ -8241,7 +8528,7 @@ "dependencies": { "semver": { "version": "7.0.0", - "resolved": "https://registry.npm.taobao.org/semver/download/semver-7.0.0.tgz?cache=0&sync_timestamp=1581458063470&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsemver%2Fdownload%2Fsemver-7.0.0.tgz", + "resolved": "https://registry.nlark.com/semver/download/semver-7.0.0.tgz?cache=0&sync_timestamp=1618846864940&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsemver%2Fdownload%2Fsemver-7.0.0.tgz", "integrity": "sha1-XzyjV2HkfgWyBsba/yz4FPAxa44=", "dev": true } @@ -8249,13 +8536,13 @@ }, "core-util-is": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/core-util-is/download/core-util-is-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", "dev": true }, "corser": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/corser/download/corser-2.0.1.tgz", + "resolved": "https://registry.nlark.com/corser/download/corser-2.0.1.tgz", "integrity": "sha1-jtolLsqrWEDc2XXOuQ2TcMgZ/4c=", "dev": true }, @@ -8349,7 +8636,7 @@ }, "cssstyle": { "version": "2.3.0", - "resolved": "https://registry.npmmirror.com/cssstyle/-/cssstyle-2.3.0.tgz", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", "dev": true, "requires": { @@ -8358,7 +8645,7 @@ "dependencies": { "cssom": { "version": "0.3.8", - "resolved": "https://registry.npmmirror.com/cssom/-/cssom-0.3.8.tgz", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", "dev": true } @@ -8396,13 +8683,13 @@ }, "decamelize": { "version": "1.2.0", - "resolved": "https://registry.npm.taobao.org/decamelize/download/decamelize-1.2.0.tgz", + "resolved": "https://registry.npmmirror.com/decamelize/download/decamelize-1.2.0.tgz?cache=0&sync_timestamp=1633055760479&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fdecamelize%2Fdownload%2Fdecamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, "decimal.js": { "version": "10.3.1", - "resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.3.1.tgz", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==", "dev": true }, @@ -8415,7 +8702,7 @@ "dedent": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==" + "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=" }, "deep-is": { "version": "0.1.3", @@ -8453,7 +8740,7 @@ }, "define-properties": { "version": "1.1.3", - "resolved": "https://registry.npm.taobao.org/define-properties/download/define-properties-1.1.3.tgz", + "resolved": "https://registry.nlark.com/define-properties/download/define-properties-1.1.3.tgz?cache=0&sync_timestamp=1618847174317&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fdefine-properties%2Fdownload%2Fdefine-properties-1.1.3.tgz", "integrity": "sha1-z4jabL7ib+bbcJT2HYcMvYTO6fE=", "dev": true, "requires": { @@ -8472,7 +8759,7 @@ "dependencies": { "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -8481,7 +8768,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -8533,7 +8820,7 @@ }, "delayed-stream": { "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", "dev": true }, @@ -8592,7 +8879,7 @@ }, "diff-sequences": { "version": "24.9.0", - "resolved": "https://registry.npm.taobao.org/diff-sequences/download/diff-sequences-24.9.0.tgz?cache=0&sync_timestamp=1579655107286&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fdiff-sequences%2Fdownload%2Fdiff-sequences-24.9.0.tgz", + "resolved": "https://registry.npmmirror.com/diff-sequences/download/diff-sequences-24.9.0.tgz", "integrity": "sha1-VxXWJE4qpl9Iu6C8ly2wsLEelbU=", "dev": true }, @@ -8677,7 +8964,7 @@ }, "ecstatic": { "version": "3.3.2", - "resolved": "https://registry.npm.taobao.org/ecstatic/download/ecstatic-3.3.2.tgz", + "resolved": "https://registry.npmmirror.com/ecstatic/download/ecstatic-3.3.2.tgz", "integrity": "sha1-bR3UmBTQBZRoLGUq22YHamnUbEg=", "dev": true, "requires": { @@ -8736,26 +9023,9 @@ "once": "^1.4.0" } }, - "enquirer": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", - "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", - "dev": true, - "requires": { - "ansi-colors": "^4.1.1" - }, - "dependencies": { - "ansi-colors": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", - "dev": true - } - } - }, "error-ex": { "version": "1.3.2", - "resolved": "https://registry.npm.taobao.org/error-ex/download/error-ex-1.3.2.tgz", + "resolved": "https://registry.nlark.com/error-ex/download/error-ex-1.3.2.tgz", "integrity": "sha1-tKxAZIEH/c3PriQvQovqihTU8b8=", "dev": true, "requires": { @@ -8763,33 +9033,51 @@ } }, "es-abstract": { - "version": "1.18.5", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.5.tgz", - "integrity": "sha512-DDggyJLoS91CkJjgauM5c0yZMjiD1uK3KcaCeAmffGwZ+ODWzOkPN4QwRbsK5DOFf06fywmyLci3ZD8jLGhVYA==", + "version": "1.21.3", + "resolved": "https://registry.npmmirror.com/es-abstract/-/es-abstract-1.21.3.tgz", + "integrity": "sha512-ZU4miiY1j3sGPFLJ34VJXEqhpmL+HGByCinGHv4HC+Fxl2fI2Z4yR6tl0mORnDr6PA8eihWo4LmSWDbvhALckg==", "dev": true, "requires": { + "array-buffer-byte-length": "^1.0.0", + "available-typed-arrays": "^1.0.5", "call-bind": "^1.0.2", + "es-set-tostringtag": "^2.0.1", "es-to-primitive": "^1.2.1", - "function-bind": "^1.1.1", - "get-intrinsic": "^1.1.1", + "function.prototype.name": "^1.1.5", + "get-intrinsic": "^1.2.1", + "get-symbol-description": "^1.0.0", + "globalthis": "^1.0.3", + "gopd": "^1.0.1", "has": "^1.0.3", - "has-symbols": "^1.0.2", - "internal-slot": "^1.0.3", - "is-callable": "^1.2.3", - "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.3", - "is-string": "^1.0.6", - "object-inspect": "^1.11.0", + "has-property-descriptors": "^1.0.0", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "internal-slot": "^1.0.5", + "is-array-buffer": "^3.0.2", + "is-callable": "^1.2.7", + "is-negative-zero": "^2.0.2", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "is-string": "^1.0.7", + "is-typed-array": "^1.1.10", + "is-weakref": "^1.0.2", + "object-inspect": "^1.12.3", "object-keys": "^1.1.1", - "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.4", - "string.prototype.trimstart": "^1.0.4", - "unbox-primitive": "^1.0.1" + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.5.0", + "safe-regex-test": "^1.0.0", + "string.prototype.trim": "^1.2.7", + "string.prototype.trimend": "^1.0.6", + "string.prototype.trimstart": "^1.0.6", + "typed-array-byte-offset": "^1.0.0", + "typed-array-length": "^1.0.4", + "unbox-primitive": "^1.0.2", + "which-typed-array": "^1.1.10" }, "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -8797,43 +9085,149 @@ "get-intrinsic": "^1.0.2" } }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", "dev": true, "requires": { "function-bind": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" } }, "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + }, + "internal-slot": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/internal-slot/-/internal-slot-1.0.5.tgz", + "integrity": "sha512-Y+R5hJrzs52QCG2laLn4udYVnxsfny9CpOhNhUvk/SSSVyF6T27FzRbF0sroPidSu3X8oEAkOn2K804mjpt6UQ==", + "dev": true, + "requires": { + "get-intrinsic": "^1.2.0", + "has": "^1.0.3", + "side-channel": "^1.0.4" + } + }, + "is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmmirror.com/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", "dev": true }, + "is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmmirror.com/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", + "dev": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + } + }, "object-inspect": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz", - "integrity": "sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==", + "version": "1.12.3", + "resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.12.3.tgz", + "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", "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==", + "version": "4.1.4", + "resolved": "https://registry.npmmirror.com/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", "dev": true, "requires": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "has-symbols": "^1.0.1", + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", "object-keys": "^1.1.1" } + }, + "regexp.prototype.flags": { + "version": "1.5.0", + "resolved": "https://registry.npmmirror.com/regexp.prototype.flags/-/regexp.prototype.flags-1.5.0.tgz", + "integrity": "sha512-0SutC3pNudRKgquxGoRGIz946MZVHqbNfPjBdxeOhBrdgDKlRoXmYLQN9xRbrR09ZXWeGAdPuif7egofn6v5LA==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "functions-have-names": "^1.2.3" + } + }, + "which-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmmirror.com/which-typed-array/-/which-typed-array-1.1.10.tgz", + "integrity": "sha512-uxoA5vLUfRPdjCuJ1h5LlYdmTLbYfums398v3WLkM+i/Wltl2/XyZpQWKbN++ck5L64SR/grOHqtXCUKmlZPNA==", + "dev": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0", + "is-typed-array": "^1.1.10" + } + } + } + }, + "es-set-tostringtag": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/es-set-tostringtag/-/es-set-tostringtag-2.0.1.tgz", + "integrity": "sha512-g3OMbtlwY3QewlqAiMLI47KywjWZoEytKr8pf6iTC8uJq5bIAH52Z9pnQ8pVL6whrCto53JZDuUIsifGeLorTg==", + "dev": true, + "requires": { + "get-intrinsic": "^1.1.3", + "has": "^1.0.3", + "has-tostringtag": "^1.0.0" + }, + "dependencies": { + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true } } }, + "es-shim-unscopables": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/es-shim-unscopables/-/es-shim-unscopables-1.0.0.tgz", + "integrity": "sha512-Jm6GPcCdC30eMLbZ2x8z2WuRwAws3zTBBKuusffYVUrNj/GVSUAZ+xKMaUpfNDR5IbyNA5LJbaecoUVbmUcB1w==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, "es-to-primitive": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", @@ -8858,7 +9252,7 @@ }, "es6-iterator": { "version": "2.0.3", - "resolved": "https://registry.npm.taobao.org/es6-iterator/download/es6-iterator-2.0.3.tgz", + "resolved": "https://registry.nlark.com/es6-iterator/download/es6-iterator-2.0.3.tgz", "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "dev": true, "requires": { @@ -8891,17 +9285,17 @@ }, "escalade": { "version": "3.1.1", - "resolved": "https://registry.npm.taobao.org/escalade/download/escalade-3.1.1.tgz?cache=0&sync_timestamp=1602567343144&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fescalade%2Fdownload%2Fescalade-3.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/escalade/download/escalade-3.1.1.tgz", "integrity": "sha1-2M/ccACWXFoBdLSoLqpcBVJ0LkA=" }, "escape-string-regexp": { "version": "1.0.5", - "resolved": "https://registry.npm.taobao.org/escape-string-regexp/download/escape-string-regexp-1.0.5.tgz", + "resolved": "https://registry.nlark.com/escape-string-regexp/download/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "escodegen": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/escodegen/-/escodegen-2.0.0.tgz", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz", "integrity": "sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw==", "dev": true, "requires": { @@ -8914,13 +9308,13 @@ "dependencies": { "estraverse": { "version": "5.3.0", - "resolved": "https://registry.npmmirror.com/estraverse/-/estraverse-5.3.0.tgz", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true }, "source-map": { "version": "0.6.1", - "resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.6.1.tgz", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "optional": true @@ -8928,137 +9322,118 @@ } }, "eslint": { - "version": "7.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", - "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", + "version": "8.44.0", + "resolved": "https://registry.npmmirror.com/eslint/-/eslint-8.44.0.tgz", + "integrity": "sha512-0wpHoUbDUHgNCyvFB5aXLiQVfK9B0at6gUvzy83k4kAsQ/u769TQDX6iKC+aO4upIHO9WSaA3QoXYQDHbNwf1A==", "dev": true, "requires": { - "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.4.3", - "@humanwhocodes/config-array": "^0.5.0", + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.4.0", + "@eslint/eslintrc": "^2.1.0", + "@eslint/js": "8.44.0", + "@humanwhocodes/config-array": "^0.11.10", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", - "debug": "^4.0.1", + "debug": "^4.3.2", "doctrine": "^3.0.0", - "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^2.0.0", - "espree": "^7.3.1", - "esquery": "^1.4.0", + "eslint-scope": "^7.2.0", + "eslint-visitor-keys": "^3.4.1", + "espree": "^9.6.0", + "esquery": "^1.4.2", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", - "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.1.2", - "globals": "^13.6.0", - "ignore": "^4.0.6", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "js-yaml": "^3.13.1", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.2", "natural-compare": "^1.4.0", - "optionator": "^0.9.1", - "progress": "^2.0.0", - "regexpp": "^3.1.0", - "semver": "^7.2.1", - "strip-ansi": "^6.0.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", "strip-json-comments": "^3.1.0", - "table": "^6.0.9", - "text-table": "^0.2.0", - "v8-compile-cache": "^2.0.3" + "text-table": "^0.2.0" }, "dependencies": { - "@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "@eslint/js": { + "version": "8.44.0", + "resolved": "https://registry.npmmirror.com/@eslint/js/-/js-8.44.0.tgz", + "integrity": "sha512-Ag+9YM4ocKQx9AarydN0KY2j0ErMHNIocPDrVo8zAE44xLTjEtz81OdR68/cydGtk6m6jDb5Za3r2useMzYmSw==", + "dev": true + }, + "@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "dev": true, "requires": { - "@babel/highlight": "^7.10.4" + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" } }, - "@babel/helper-validator-identifier": { - "version": "7.14.9", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.9.tgz", - "integrity": "sha512-pQYxPY0UP6IHISRitNe8bsijHex4TWZXi2HwKVsjPiltzlhse2znVcm9Ace510VT1kxIHjGJCZZQBX2gJDbo0g==", + "@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmmirror.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "dev": true }, - "@babel/highlight": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", - "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", + "@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmmirror.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.14.5", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - }, - "dependencies": { - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - } + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" } }, "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, "chalk": { "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "resolved": "https://registry.npmmirror.com/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "requires": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" - }, - "dependencies": { - "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": { - "color-convert": "^2.0.1" - } - }, - "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" - } - } } }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { @@ -9067,13 +9442,13 @@ }, "color-name": { "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "resolved": "https://registry.npmmirror.com/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", + "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "requires": { @@ -9082,42 +9457,71 @@ "which": "^2.0.1" } }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, "escape-string-regexp": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", "dev": true }, - "eslint-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", + "eslint-scope": { + "version": "7.2.0", + "resolved": "https://registry.npmmirror.com/eslint-scope/-/eslint-scope-7.2.0.tgz", + "integrity": "sha512-DYj5deGlHBfMt15J7rdtyKNq/Nqlv5KfU4iodrQ019XESsRnwXH9KAE0y3cwtUHDo2ob7CypAnCqefh6vioWRw==", "dev": true, "requires": { - "eslint-visitor-keys": "^1.1.0" - }, - "dependencies": { - "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": "^4.3.0", + "estraverse": "^5.2.0" + } + }, + "estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmmirror.com/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true + }, + "find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "requires": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" } }, "glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, "requires": { - "is-glob": "^4.0.1" + "is-glob": "^4.0.3" + }, + "dependencies": { + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + } } }, "globals": { - "version": "13.11.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.11.0.tgz", - "integrity": "sha512-08/xrJ7wQjK9kkkRoI3OFUBbLx4f+6x3SGwcPvQ0QH6goFDrOU2oyAWrmh3dJezu65buo+HBMzAMQy6rovVC3g==", + "version": "13.20.0", + "resolved": "https://registry.npmmirror.com/globals/-/globals-13.20.0.tgz", + "integrity": "sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ==", "dev": true, "requires": { "type-fest": "^0.20.2" @@ -9125,19 +9529,22 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, - "ignore": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", - "dev": true + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "requires": { + "argparse": "^2.0.1" + } }, "levn": { "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "resolved": "https://registry.npmmirror.com/levn/-/levn-0.4.1.tgz", "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "requires": { @@ -9145,44 +9552,68 @@ "type-check": "~0.4.0" } }, + "locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "requires": { + "p-locate": "^5.0.0" + } + }, "optionator": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", - "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", + "version": "0.9.3", + "resolved": "https://registry.npmmirror.com/optionator/-/optionator-0.9.3.tgz", + "integrity": "sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==", "dev": true, "requires": { + "@aashutoshrathi/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" + "type-check": "^0.4.0" + } + }, + "p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "requires": { + "yocto-queue": "^0.1.0" + } + }, + "p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "requires": { + "p-limit": "^3.0.2" } }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, "path-key": { "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "resolved": "https://registry.npmmirror.com/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", + "resolved": "https://registry.npmmirror.com/prelude-ls/-/prelude-ls-1.2.1.tgz", "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true }, - "semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", - "dev": true, - "requires": { - "lru-cache": "^6.0.0" - } - }, "shebang-command": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "requires": { @@ -9191,22 +9622,31 @@ }, "shebang-regex": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "resolved": "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "has-flag": "^4.0.0" } }, "type-check": { "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "resolved": "https://registry.npmmirror.com/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "requires": { @@ -9215,59 +9655,96 @@ }, "type-fest": { "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "resolved": "https://registry.npmmirror.com/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true - }, - "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==", + "version": "15.0.0", + "resolved": "https://registry.npmmirror.com/eslint-config-airbnb-base/-/eslint-config-airbnb-base-15.0.0.tgz", + "integrity": "sha512-xaX3z4ZZIcFLvh2oUNvcX5oEofXda7giYmuplVxoOg5A7EXJMrUyqRgR+mhDhPK8LZ4PttFOBvCYDbX3sUoUig==", "dev": true, "requires": { "confusing-browser-globals": "^1.0.10", "object.assign": "^4.1.2", - "object.entries": "^1.1.2" + "object.entries": "^1.1.5", + "semver": "^6.3.0" }, "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "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==", + "version": "4.1.4", + "resolved": "https://registry.npmmirror.com/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", "dev": true, "requires": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "has-symbols": "^1.0.1", + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", "object-keys": "^1.1.1" } + }, + "semver": { + "version": "6.3.1", + "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true } } }, "eslint-import-resolver-node": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.6.tgz", - "integrity": "sha512-0En0w03NRVMn9Uiyn8YRPDKvWjxCWkslUEhGNTdGx15RvPJYQ+lbOlqrlNI2vEAs4pDYK4f/HN2TbDmk5TP0iw==", + "version": "0.3.7", + "resolved": "https://registry.npmmirror.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.7.tgz", + "integrity": "sha512-gozW2blMLJCeFpBwugLTGyvVjNoeo1knonXAcatC6bjPBZitotxdWf7Gimr25N4c0AAOo4eOUfaG82IJPDpqCA==", "dev": true, "requires": { "debug": "^3.2.7", - "resolve": "^1.20.0" + "is-core-module": "^2.11.0", + "resolve": "^1.22.1" }, "dependencies": { "debug": { "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "requires": { @@ -9275,252 +9752,103 @@ } }, "resolve": { - "version": "1.20.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", - "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "version": "1.22.2", + "resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.2.tgz", + "integrity": "sha512-Sb+mjNHOULsBv818T40qSPeRiuWLyaGMa5ewydRLFimneixmVy2zdivRl+AF6jaYPC8ERxGDmFSiqui6SfPd+g==", "dev": true, "requires": { - "is-core-module": "^2.2.0", - "path-parse": "^1.0.6" + "is-core-module": "^2.11.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" } } } }, "eslint-module-utils": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.6.2.tgz", - "integrity": "sha512-QG8pcgThYOuqxupd06oYTZoNOGaUdTY1PqK+oS6ElF6vs4pBdk/aYxFVQQXzcrAqp9m7cl7lb2ubazX+g16k2Q==", + "version": "2.8.0", + "resolved": "https://registry.npmmirror.com/eslint-module-utils/-/eslint-module-utils-2.8.0.tgz", + "integrity": "sha512-aWajIYfsqCKRDgUfjEXNN/JlrzauMuSEy5sbd7WXbtW3EH6A6MpwEh42c7qD+MqQo9QMJ6fWLAeIJynx0g6OAw==", "dev": true, "requires": { - "debug": "^3.2.7", - "pkg-dir": "^2.0.0" + "debug": "^3.2.7" }, "dependencies": { "debug": { "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "requires": { "ms": "^2.1.1" } - }, - "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" - } - }, - "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 - }, - "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.24.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.24.1.tgz", - "integrity": "sha512-KSFWhNxPH8OGJwpRJJs+Z7I0a13E2iFQZJIvSnCu6KUs4qmgAm3xN9GYBCSoiGWmwA7gERZPXqYQjcoCROnYhQ==", + "version": "2.27.5", + "resolved": "https://registry.npmmirror.com/eslint-plugin-import/-/eslint-plugin-import-2.27.5.tgz", + "integrity": "sha512-LmEt3GVofgiGuiE+ORpnvP+kAm3h6MLZJ4Q5HCyHADofsb4VzXFsRiWj3c0OFiV+3DWFh0qg3v9gcPlfc3zRow==", "dev": true, "requires": { - "array-includes": "^3.1.3", - "array.prototype.flat": "^1.2.4", - "debug": "^2.6.9", + "array-includes": "^3.1.6", + "array.prototype.flat": "^1.3.1", + "array.prototype.flatmap": "^1.3.1", + "debug": "^3.2.7", "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.6", - "eslint-module-utils": "^2.6.2", - "find-up": "^2.0.0", + "eslint-import-resolver-node": "^0.3.7", + "eslint-module-utils": "^2.7.4", "has": "^1.0.3", - "is-core-module": "^2.6.0", - "minimatch": "^3.0.4", - "object.values": "^1.1.4", - "pkg-up": "^2.0.0", - "read-pkg-up": "^3.0.0", - "resolve": "^1.20.0", - "tsconfig-paths": "^3.10.1" + "is-core-module": "^2.11.0", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.values": "^1.1.6", + "resolve": "^1.22.1", + "semver": "^6.3.0", + "tsconfig-paths": "^3.14.1" }, "dependencies": { "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "version": "3.2.7", + "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "requires": { - "ms": "2.0.0" + "ms": "^2.1.1" } }, "doctrine": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "resolved": "https://registry.npmmirror.com/doctrine/-/doctrine-2.1.0.tgz", "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", "dev": true, "requires": { "esutils": "^2.0.2" } }, - "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": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.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 - }, - "parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", - "dev": true, - "requires": { - "error-ex": "^1.3.1", - "json-parse-better-errors": "^1.0.1" - } - }, - "path-type": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", - "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", - "dev": true, - "requires": { - "pify": "^3.0.0" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - } - }, - "read-pkg-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", - "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "requires": { - "find-up": "^2.0.0", - "read-pkg": "^3.0.0" + "is-extglob": "^2.1.1" } }, "resolve": { - "version": "1.20.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", - "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "version": "1.22.2", + "resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.2.tgz", + "integrity": "sha512-Sb+mjNHOULsBv818T40qSPeRiuWLyaGMa5ewydRLFimneixmVy2zdivRl+AF6jaYPC8ERxGDmFSiqui6SfPd+g==", "dev": true, "requires": { - "is-core-module": "^2.2.0", - "path-parse": "^1.0.6" + "is-core-module": "^2.11.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" } }, - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "semver": { + "version": "6.3.1", + "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true } } @@ -9547,36 +9875,27 @@ "estraverse": "^4.1.1" } }, - "eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^2.0.0" - } - }, "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", + "version": "3.4.1", + "resolved": "https://registry.npmmirror.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.1.tgz", + "integrity": "sha512-pZnmmLwYzf+kWaM/Qgrvpen51upAktaaiI01nsJD/Yr3lMOdNtq0cxkrrg16w64VtisN6okbs7Q8AfGqj4c9fA==", "dev": true }, "espree": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", - "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", + "version": "9.6.0", + "resolved": "https://registry.npmmirror.com/espree/-/espree-9.6.0.tgz", + "integrity": "sha512-1FH/IiruXZ84tpUlm0aCUEwMl2Ho5ilqVh0VvQXw+byAz/4SAciyHLlfmL5WYqsvD38oymdUwBss0LtK8m4s/A==", "dev": true, "requires": { - "acorn": "^7.4.0", - "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^1.3.0" + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" }, "dependencies": { - "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==", + "acorn": { + "version": "8.10.0", + "resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.10.0.tgz", + "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", "dev": true } } @@ -9588,18 +9907,18 @@ "dev": true }, "esquery": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", - "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", + "version": "1.5.0", + "resolved": "https://registry.npmmirror.com/esquery/-/esquery-1.5.0.tgz", + "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", "dev": true, "requires": { "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==", + "version": "5.3.0", + "resolved": "https://registry.npmmirror.com/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true } } @@ -9659,7 +9978,7 @@ }, "execa": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/execa/download/execa-1.0.0.tgz?cache=0&sync_timestamp=1576749091315&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fexeca%2Fdownload%2Fexeca-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/execa/download/execa-1.0.0.tgz?cache=0&sync_timestamp=1637147207309&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fexeca%2Fdownload%2Fexeca-1.0.0.tgz", "integrity": "sha1-xiNqW7TfbW8V6I5/AXeYIWdJ3dg=", "dev": true, "requires": { @@ -9695,7 +10014,7 @@ "dependencies": { "debug": { "version": "2.6.9", - "resolved": "https://registry.npm.taobao.org/debug/download/debug-2.6.9.tgz", + "resolved": "https://registry.npmmirror.com/debug/download/debug-2.6.9.tgz", "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", "dev": true, "requires": { @@ -9713,7 +10032,7 @@ }, "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -9722,7 +10041,7 @@ }, "ms": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/ms/download/ms-2.0.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fms%2Fdownload%2Fms-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/ms/download/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true } @@ -9730,7 +10049,7 @@ }, "expand-tilde": { "version": "2.0.2", - "resolved": "https://registry.npm.taobao.org/expand-tilde/download/expand-tilde-2.0.2.tgz", + "resolved": "https://registry.nlark.com/expand-tilde/download/expand-tilde-2.0.2.tgz", "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", "dev": true, "requires": { @@ -9739,7 +10058,7 @@ }, "expect": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/expect/download/expect-26.6.2.tgz?cache=0&sync_timestamp=1616701586390&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fexpect%2Fdownload%2Fexpect-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/expect/download/expect-26.6.2.tgz", "integrity": "sha1-xrmWvya/P+GLZ7LQ9R/JgbqTRBc=", "dev": true, "requires": { @@ -9753,7 +10072,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -9784,7 +10103,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -9803,7 +10122,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -9818,19 +10137,19 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", + "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, "jest-get-type": { "version": "26.3.0", - "resolved": "https://registry.npm.taobao.org/jest-get-type/download/jest-get-type-26.3.0.tgz", + "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-26.3.0.tgz", "integrity": "sha1-6X3Dw/U8K0Bsp6+u1Ek7HQmRmeA=", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -9864,7 +10183,7 @@ }, "extend-shallow": { "version": "3.0.2", - "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-3.0.2.tgz", + "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-3.0.2.tgz", "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", "dev": true, "requires": { @@ -9874,7 +10193,7 @@ "dependencies": { "is-extendable": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/is-extendable/download/is-extendable-1.0.1.tgz", + "resolved": "https://registry.nlark.com/is-extendable/download/is-extendable-1.0.1.tgz", "integrity": "sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=", "dev": true, "requires": { @@ -9885,7 +10204,7 @@ }, "extglob": { "version": "2.0.4", - "resolved": "https://registry.npm.taobao.org/extglob/download/extglob-2.0.4.tgz", + "resolved": "https://registry.nlark.com/extglob/download/extglob-2.0.4.tgz", "integrity": "sha1-rQD+TcYSqSMuhxhxHcXLWrAoVUM=", "dev": true, "requires": { @@ -9910,7 +10229,7 @@ }, "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -9919,7 +10238,7 @@ }, "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -9928,7 +10247,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -9950,7 +10269,7 @@ }, "fancy-log": { "version": "1.3.3", - "resolved": "https://registry.npm.taobao.org/fancy-log/download/fancy-log-1.3.3.tgz", + "resolved": "https://registry.nlark.com/fancy-log/download/fancy-log-1.3.3.tgz", "integrity": "sha1-28GRVPVYaQFQojlToK29A1vkX8c=", "dev": true, "requires": { @@ -10031,7 +10350,7 @@ }, "fast-levenshtein": { "version": "2.0.6", - "resolved": "https://registry.npm.taobao.org/fast-levenshtein/download/fast-levenshtein-2.0.6.tgz", + "resolved": "https://registry.nlark.com/fast-levenshtein/download/fast-levenshtein-2.0.6.tgz", "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" }, "fast-safe-stringify": { @@ -10186,7 +10505,7 @@ }, "for-own": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/for-own/download/for-own-1.0.0.tgz", + "resolved": "https://registry.nlark.com/for-own/download/for-own-1.0.0.tgz", "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", "dev": true, "requires": { @@ -10195,7 +10514,7 @@ }, "fragment-cache": { "version": "0.2.1", - "resolved": "https://registry.npm.taobao.org/fragment-cache/download/fragment-cache-0.2.1.tgz", + "resolved": "https://registry.nlark.com/fragment-cache/download/fragment-cache-0.2.1.tgz", "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", "dev": true, "requires": { @@ -10205,12 +10524,12 @@ "fs": { "version": "0.0.1-security", "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", - "integrity": "sha1-invTcYa23d84E/I4WLV+yq9eQdQ=", + "integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==", "dev": true }, "fs-extra": { "version": "7.0.1", - "resolved": "https://registry.npm.taobao.org/fs-extra/download/fs-extra-7.0.1.tgz", + "resolved": "https://registry.nlark.com/fs-extra/download/fs-extra-7.0.1.tgz", "integrity": "sha1-TxicRKoSO4lfcigE9V6iPq3DSOk=", "dev": true, "requires": { @@ -10221,7 +10540,7 @@ }, "fs-mkdirp-stream": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/fs-mkdirp-stream/download/fs-mkdirp-stream-1.0.0.tgz", + "resolved": "https://registry.nlark.com/fs-mkdirp-stream/download/fs-mkdirp-stream-1.0.0.tgz", "integrity": "sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes=", "dev": true, "requires": { @@ -10231,7 +10550,7 @@ }, "fs.realpath": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/fs.realpath/download/fs.realpath-1.0.0.tgz", + "resolved": "https://registry.nlark.com/fs.realpath/download/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "fsevents": { @@ -10864,7 +11183,7 @@ }, "function-bind": { "version": "1.1.1", - "resolved": "https://registry.npm.taobao.org/function-bind/download/function-bind-1.1.1.tgz", + "resolved": "https://registry.nlark.com/function-bind/download/function-bind-1.1.1.tgz", "integrity": "sha1-pWiZ0+o8m6uHS7l3O3xe3pL0iV0=" }, "function.prototype.name": { @@ -11037,12 +11356,6 @@ } } }, - "functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/functional-red-black-tree/download/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true - }, "functions-have-names": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", @@ -11051,7 +11364,7 @@ }, "gensync": { "version": "1.0.0-beta.2", - "resolved": "https://registry.npm.taobao.org/gensync/download/gensync-1.0.0-beta.2.tgz", + "resolved": "https://registry.nlark.com/gensync/download/gensync-1.0.0-beta.2.tgz", "integrity": "sha1-MqbudsPX9S1GsrGuXZP+qFgKJeA=" }, "get-assigned-identifiers": { @@ -11085,7 +11398,7 @@ }, "get-stream": { "version": "4.1.0", - "resolved": "https://registry.npm.taobao.org/get-stream/download/get-stream-4.1.0.tgz", + "resolved": "https://registry.nlark.com/get-stream/download/get-stream-4.1.0.tgz", "integrity": "sha1-wbJVV189wh1Zv8ec09K0axw6VLU=", "dev": true, "requires": { @@ -11127,7 +11440,7 @@ }, "get-value": { "version": "2.0.6", - "resolved": "https://registry.npm.taobao.org/get-value/download/get-value-2.0.6.tgz", + "resolved": "https://registry.nlark.com/get-value/download/get-value-2.0.6.tgz", "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", "dev": true }, @@ -11166,7 +11479,7 @@ }, "glob-stream": { "version": "6.1.0", - "resolved": "https://registry.npm.taobao.org/glob-stream/download/glob-stream-6.1.0.tgz", + "resolved": "https://registry.nlark.com/glob-stream/download/glob-stream-6.1.0.tgz", "integrity": "sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ=", "dev": true, "requires": { @@ -11184,7 +11497,7 @@ "dependencies": { "glob-parent": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/glob-parent/download/glob-parent-3.1.0.tgz?cache=0&sync_timestamp=1569108917227&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fglob-parent%2Fdownload%2Fglob-parent-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/glob-parent/download/glob-parent-3.1.0.tgz", "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", "dev": true, "requires": { @@ -11194,7 +11507,7 @@ }, "is-glob": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/is-glob/download/is-glob-3.1.0.tgz", "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { @@ -11219,7 +11532,7 @@ }, "global-modules": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/global-modules/download/global-modules-1.0.0.tgz?cache=0&sync_timestamp=1571657602039&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fglobal-modules%2Fdownload%2Fglobal-modules-1.0.0.tgz", + "resolved": "https://registry.nlark.com/global-modules/download/global-modules-1.0.0.tgz", "integrity": "sha1-bXcPDrUjrHgWTXK15xqIdyZcw+o=", "dev": true, "requires": { @@ -11254,9 +11567,18 @@ }, "globals": { "version": "11.12.0", - "resolved": "https://registry.npm.taobao.org/globals/download/globals-11.12.0.tgz", + "resolved": "https://registry.npmmirror.com/globals/download/globals-11.12.0.tgz", "integrity": "sha1-q4eVM4hooLq9hSV1gBjCp+uVxC4=" }, + "globalthis": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/globalthis/-/globalthis-1.0.3.tgz", + "integrity": "sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA==", + "dev": true, + "requires": { + "define-properties": "^1.1.3" + } + }, "globby": { "version": "11.0.1", "resolved": "https://registry.npm.taobao.org/globby/download/globby-11.0.1.tgz", @@ -11279,15 +11601,44 @@ } } }, - "glogg": { - "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/glogg/download/glogg-1.0.2.tgz", - "integrity": "sha1-LX3XAr7aIus7/634gGltpthGMT8=", - "dev": true, - "requires": { - "sparkles": "^1.0.0" - } - }, + "glogg": { + "version": "1.0.2", + "resolved": "https://registry.nlark.com/glogg/download/glogg-1.0.2.tgz", + "integrity": "sha1-LX3XAr7aIus7/634gGltpthGMT8=", + "dev": true, + "requires": { + "sparkles": "^1.0.0" + } + }, + "gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "requires": { + "get-intrinsic": "^1.1.3" + }, + "dependencies": { + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + } + } + }, "graceful-fs": { "version": "4.2.3", "resolved": "https://registry.npm.taobao.org/graceful-fs/download/graceful-fs-4.2.3.tgz", @@ -11298,6 +11649,12 @@ "resolved": "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz", "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==" }, + "graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true + }, "gulp": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/gulp/-/gulp-4.0.2.tgz", @@ -11313,7 +11670,7 @@ "camelcase": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", - "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", + "integrity": "sha512-4nhGqUkc4BqbBBB4Q6zLuD7lzzrHYrjKGeYaEji/3tFR5VdJu9v+LilhGIVe8wxEJPPOeWo7eg8dwY13TZ1BNg==", "dev": true }, "gulp-cli": { @@ -11344,7 +11701,7 @@ }, "is-fullwidth-code-point": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-fullwidth-code-point/download/is-fullwidth-code-point-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-fullwidth-code-point/download/is-fullwidth-code-point-1.0.0.tgz", "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "dev": true, "requires": { @@ -11353,7 +11710,7 @@ }, "string-width": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/string-width/download/string-width-1.0.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstring-width%2Fdownload%2Fstring-width-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/string-width/download/string-width-1.0.2.tgz?cache=0&sync_timestamp=1632421309919&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fstring-width%2Fdownload%2Fstring-width-1.0.2.tgz", "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "requires": { @@ -11469,7 +11826,7 @@ }, "gulplog": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/gulplog/download/gulplog-1.0.0.tgz", + "resolved": "https://registry.nlark.com/gulplog/download/gulplog-1.0.0.tgz", "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", "dev": true, "requires": { @@ -11478,7 +11835,7 @@ }, "has": { "version": "1.0.3", - "resolved": "https://registry.npm.taobao.org/has/download/has-1.0.3.tgz", + "resolved": "https://registry.nlark.com/has/download/has-1.0.3.tgz", "integrity": "sha1-ci18v8H2qoJB8W3YFOAR4fQeh5Y=", "requires": { "function-bind": "^1.1.1" @@ -11492,7 +11849,7 @@ }, "has-flag": { "version": "3.0.0", - "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-3.0.0.tgz", + "resolved": "https://registry.nlark.com/has-flag/download/has-flag-3.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "has-gulplog": { @@ -11526,6 +11883,12 @@ } } }, + "has-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/has-proto/-/has-proto-1.0.1.tgz", + "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", + "dev": true + }, "has-symbols": { "version": "1.0.1", "resolved": "https://registry.npm.taobao.org/has-symbols/download/has-symbols-1.0.1.tgz", @@ -11551,7 +11914,7 @@ }, "has-value": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/has-value/download/has-value-1.0.0.tgz", + "resolved": "https://registry.nlark.com/has-value/download/has-value-1.0.0.tgz", "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", "dev": true, "requires": { @@ -11562,7 +11925,7 @@ }, "has-values": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/has-values/download/has-values-1.0.0.tgz", + "resolved": "https://registry.nlark.com/has-values/download/has-values-1.0.0.tgz", "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", "dev": true, "requires": { @@ -11676,7 +12039,7 @@ }, "http-proxy": { "version": "1.18.1", - "resolved": "https://registry.npm.taobao.org/http-proxy/download/http-proxy-1.18.1.tgz", + "resolved": "https://registry.nlark.com/http-proxy/download/http-proxy-1.18.1.tgz?cache=0&sync_timestamp=1618847045732&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhttp-proxy%2Fdownload%2Fhttp-proxy-1.18.1.tgz", "integrity": "sha1-QBVB8FNIhLv5UmAzTnL4juOXZUk=", "dev": true, "requires": { @@ -11687,7 +12050,7 @@ }, "http-server": { "version": "0.12.3", - "resolved": "https://registry.npm.taobao.org/http-server/download/http-server-0.12.3.tgz", + "resolved": "https://registry.npmmirror.com/http-server/download/http-server-0.12.3.tgz?cache=0&sync_timestamp=1634685922991&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fhttp-server%2Fdownload%2Fhttp-server-0.12.3.tgz", "integrity": "sha1-ugRx0OzEJYhmFss1xPryeRQKDTc=", "dev": true, "requires": { @@ -11711,7 +12074,7 @@ }, "https-proxy-agent": { "version": "5.0.1", - "resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", "dev": true, "requires": { @@ -11732,9 +12095,9 @@ "dev": true }, "ignore": { - "version": "5.1.8", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", - "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", + "version": "5.2.4", + "resolved": "https://registry.npmmirror.com/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true }, "import-fresh": { @@ -11758,7 +12121,7 @@ }, "imurmurhash": { "version": "0.1.4", - "resolved": "https://registry.npm.taobao.org/imurmurhash/download/imurmurhash-0.1.4.tgz", + "resolved": "https://registry.nlark.com/imurmurhash/download/imurmurhash-0.1.4.tgz", "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" }, "indent-string": { @@ -11778,7 +12141,7 @@ }, "inherits": { "version": "2.0.4", - "resolved": "https://registry.npm.taobao.org/inherits/download/inherits-2.0.4.tgz", + "resolved": "https://registry.nlark.com/inherits/download/inherits-2.0.4.tgz", "integrity": "sha1-D6LGT5MpF8NDOg3tVTY6rjdBa3w=" }, "ini": { @@ -11846,7 +12209,7 @@ }, "invariant": { "version": "2.2.4", - "resolved": "https://registry.npm.taobao.org/invariant/download/invariant-2.2.4.tgz", + "resolved": "https://registry.npm.taobao.org/invariant/download/invariant-2.2.4.tgz?cache=0&sync_timestamp=1615984365242&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Finvariant%2Fdownload%2Finvariant-2.2.4.tgz", "integrity": "sha1-YQ88ksk1nOHbYW5TgAjSP/NRWOY=", "dev": true, "requires": { @@ -11855,7 +12218,7 @@ }, "invert-kv": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/invert-kv/download/invert-kv-1.0.0.tgz", + "resolved": "https://registry.nlark.com/invert-kv/download/invert-kv-1.0.0.tgz?cache=0&sync_timestamp=1630996809231&other_urls=https%3A%2F%2Fregistry.nlark.com%2Finvert-kv%2Fdownload%2Finvert-kv-1.0.0.tgz", "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", "dev": true }, @@ -11871,7 +12234,7 @@ }, "is-accessor-descriptor": { "version": "0.1.6", - "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-0.1.6.tgz", + "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-0.1.6.tgz", "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "dev": true, "requires": { @@ -11922,6 +12285,60 @@ } } }, + "is-array-buffer": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/is-array-buffer/-/is-array-buffer-3.0.2.tgz", + "integrity": "sha512-y+FyyR/w8vfIRq4eQcM1EYgSTnmHXPqaF+IgzgraytCFq5Xh8lllDVmAZolPJiZttZLeFSINPYMaEJ7/vWUa1w==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.0", + "is-typed-array": "^1.1.10" + }, + "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + }, + "is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmmirror.com/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", + "dev": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + } + } + } + }, "is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npm.taobao.org/is-arrayish/download/is-arrayish-0.2.1.tgz", @@ -11939,7 +12356,7 @@ }, "is-binary-path": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/is-binary-path/download/is-binary-path-1.0.1.tgz", + "resolved": "https://registry.nlark.com/is-binary-path/download/is-binary-path-1.0.1.tgz", "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", "dev": true, "requires": { @@ -11981,7 +12398,7 @@ }, "is-buffer": { "version": "1.1.6", - "resolved": "https://registry.npm.taobao.org/is-buffer/download/is-buffer-1.1.6.tgz", + "resolved": "https://registry.npm.taobao.org/is-buffer/download/is-buffer-1.1.6.tgz?cache=0&sync_timestamp=1604432327227&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fis-buffer%2Fdownload%2Fis-buffer-1.1.6.tgz", "integrity": "sha1-76ouqdqg16suoTqXsritUf776L4=", "dev": true }, @@ -11993,7 +12410,7 @@ }, "is-ci": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/is-ci/download/is-ci-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/is-ci/download/is-ci-2.0.0.tgz?cache=0&sync_timestamp=1635261061017&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fis-ci%2Fdownload%2Fis-ci-2.0.0.tgz", "integrity": "sha1-a8YzQYGBDgS1wis9WJ/cpVAmQEw=", "dev": true, "requires": { @@ -12001,9 +12418,9 @@ } }, "is-core-module": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.6.0.tgz", - "integrity": "sha512-wShG8vs60jKfPWpF2KZRaAtvt3a20OAn7+IJ6hLPECpSABLcKtFKTTI4ZtH5QcBruBHlq+WsdHWyz0BCZW7svQ==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/is-core-module/-/is-core-module-2.12.1.tgz", + "integrity": "sha512-Q4ZuBAe2FUsKtyQJoQHlvP8OvBERxO3jEmy1I7hcRXcJBGGHFh/aJBswbXuS9sgrDH2QUO8ilkwNPHvHMd8clg==", "dev": true, "requires": { "has": "^1.0.3" @@ -12011,7 +12428,7 @@ }, "is-data-descriptor": { "version": "0.1.4", - "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-0.1.4.tgz", + "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-0.1.4.tgz", "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "dev": true, "requires": { @@ -12059,14 +12476,14 @@ }, "is-docker": { "version": "2.2.1", - "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "resolved": "https://registry.npmmirror.com/is-docker/-/is-docker-2.2.1.tgz", "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", "dev": true, "optional": true }, "is-extendable": { "version": "0.1.1", - "resolved": "https://registry.npm.taobao.org/is-extendable/download/is-extendable-0.1.1.tgz", + "resolved": "https://registry.nlark.com/is-extendable/download/is-extendable-0.1.1.tgz", "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", "dev": true }, @@ -12107,20 +12524,20 @@ }, "is-module": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/is-module/-/is-module-1.0.0.tgz", "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", "dev": true }, "is-negated-glob": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-negated-glob/download/is-negated-glob-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-negated-glob/download/is-negated-glob-1.0.0.tgz", "integrity": "sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI=", "dev": true }, "is-negative-zero": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", - "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/is-negative-zero/-/is-negative-zero-2.0.2.tgz", + "integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==", "dev": true }, "is-number": { @@ -12174,7 +12591,7 @@ }, "is-potential-custom-element-name": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", "dev": true }, @@ -12263,7 +12680,7 @@ }, "is-stream": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/is-stream/download/is-stream-1.1.0.tgz", + "resolved": "https://registry.nlark.com/is-stream/download/is-stream-1.1.0.tgz", "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", "dev": true }, @@ -12519,13 +12936,13 @@ }, "is-windows": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/is-windows/download/is-windows-1.0.2.tgz", + "resolved": "https://registry.nlark.com/is-windows/download/is-windows-1.0.2.tgz", "integrity": "sha1-0YUOuXkezRjmGCzhKjDzlmNLsZ0=", "dev": true }, "is-wsl": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "resolved": "https://registry.npmmirror.com/is-wsl/-/is-wsl-2.2.0.tgz", "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", "dev": true, "optional": true, @@ -12535,13 +12952,13 @@ }, "isarray": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/isarray/download/isarray-1.0.0.tgz?cache=0&sync_timestamp=1562592096220&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fisarray%2Fdownload%2Fisarray-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/isarray/download/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true }, "isexe": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/isexe/download/isexe-2.0.0.tgz", + "resolved": "https://registry.nlark.com/isexe/download/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, "isobject": { @@ -13544,7 +13961,7 @@ }, "jest-diff": { "version": "24.9.0", - "resolved": "https://registry.npm.taobao.org/jest-diff/download/jest-diff-24.9.0.tgz", + "resolved": "https://registry.npmmirror.com/jest-diff/download/jest-diff-24.9.0.tgz", "integrity": "sha1-kxt9DVd4obr3RSy4FuMl43JAVdo=", "dev": true, "requires": { @@ -14016,7 +14433,7 @@ }, "@types/istanbul-reports": { "version": "3.0.1", - "resolved": "https://registry.npmmirror.com/@types/istanbul-reports/download/@types/istanbul-reports-3.0.1.tgz", + "resolved": "https://registry.npmmirror.com/@types/istanbul-reports/download/@types/istanbul-reports-3.0.1.tgz?cache=0&sync_timestamp=1637266160892&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fistanbul-reports%2Fdownload%2F%40types%2Fistanbul-reports-3.0.1.tgz", "integrity": "sha1-kVP+mLuivVZaY63ZQ21vDX+EaP8=", "dev": true, "requires": { @@ -14025,7 +14442,7 @@ }, "@types/yargs": { "version": "16.0.4", - "resolved": "https://registry.npmmirror.com/@types/yargs/download/@types/yargs-16.0.4.tgz", + "resolved": "https://registry.npmmirror.com/@types/yargs/download/@types/yargs-16.0.4.tgz?cache=0&sync_timestamp=1637271118840&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fyargs%2Fdownload%2F%40types%2Fyargs-16.0.4.tgz", "integrity": "sha1-JqrZjdLCo45CEIbqmtQrnlFkKXc=", "dev": true, "requires": { @@ -14040,7 +14457,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1618995588464&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -14049,7 +14466,7 @@ }, "chalk": { "version": "4.1.2", - "resolved": "https://registry.nlark.com/chalk/download/chalk-4.1.2.tgz?cache=0&sync_timestamp=1627646655305&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fchalk%2Fdownload%2Fchalk-4.1.2.tgz", + "resolved": "https://registry.npmmirror.com/chalk/download/chalk-4.1.2.tgz", "integrity": "sha1-qsTit3NKdAhnrrFr8CqtVWoeegE=", "dev": true, "requires": { @@ -14128,7 +14545,7 @@ "dependencies": { "ansi-styles": { "version": "5.2.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-5.2.0.tgz?cache=0&sync_timestamp=1618995588464&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fansi-styles%2Fdownload%2Fansi-styles-5.2.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-5.2.0.tgz", "integrity": "sha1-B0SWkK1Fd30ZJKwquy/IiV26g2s=", "dev": true } @@ -14136,7 +14553,7 @@ }, "react-is": { "version": "17.0.2", - "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz?cache=0&sync_timestamp=1637338596901&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Freact-is%2Fdownload%2Freact-is-17.0.2.tgz", + "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz", "integrity": "sha1-5pHUqOnHiTZWVVOas3J2Kw77VPA=", "dev": true }, @@ -14153,7 +14570,7 @@ }, "jest-get-type": { "version": "24.9.0", - "resolved": "https://registry.npm.taobao.org/jest-get-type/download/jest-get-type-24.9.0.tgz?cache=0&sync_timestamp=1579655144842&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-get-type%2Fdownload%2Fjest-get-type-24.9.0.tgz", + "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-24.9.0.tgz", "integrity": "sha1-FoSgyKUPLkkBtmRK6GH1ee7S7w4=", "dev": true }, @@ -14446,7 +14863,7 @@ }, "jest-matcher-deep-close-to": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/jest-matcher-deep-close-to/download/jest-matcher-deep-close-to-2.0.1.tgz", + "resolved": "https://registry.npmmirror.com/jest-matcher-deep-close-to/download/jest-matcher-deep-close-to-2.0.1.tgz", "integrity": "sha1-L50NpE94oWo5BNGJguOV6Y43XFo=", "dev": true, "requires": { @@ -14455,7 +14872,7 @@ "dependencies": { "@jest/types": { "version": "25.5.0", - "resolved": "https://registry.nlark.com/@jest/types/download/@jest/types-25.5.0.tgz?cache=0&sync_timestamp=1624900057884&other_urls=https%3A%2F%2Fregistry.nlark.com%2F%40jest%2Ftypes%2Fdownload%2F%40jest%2Ftypes-25.5.0.tgz", + "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-25.5.0.tgz", "integrity": "sha1-TWpHk/e5WZ/DaAh3uFapfbzPKp0=", "dev": true, "requires": { @@ -14467,7 +14884,7 @@ }, "@types/yargs": { "version": "15.0.14", - "resolved": "https://registry.nlark.com/@types/yargs/download/@types/yargs-15.0.14.tgz", + "resolved": "https://registry.npmmirror.com/@types/yargs/download/@types/yargs-15.0.14.tgz?cache=0&sync_timestamp=1637271118840&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fyargs%2Fdownload%2F%40types%2Fyargs-15.0.14.tgz", "integrity": "sha1-Jtgh3biecEkhYLZtEKDrbfj2+wY=", "dev": true, "requires": { @@ -14491,7 +14908,7 @@ }, "chalk": { "version": "3.0.0", - "resolved": "https://registry.nlark.com/chalk/download/chalk-3.0.0.tgz?cache=0&sync_timestamp=1618995367379&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fchalk%2Fdownload%2Fchalk-3.0.0.tgz", + "resolved": "https://registry.npmmirror.com/chalk/download/chalk-3.0.0.tgz", "integrity": "sha1-P3PCv1JlkfV0zEksUeJFY0n4ROQ=", "dev": true, "requires": { @@ -14501,7 +14918,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -14516,7 +14933,7 @@ }, "diff-sequences": { "version": "25.2.6", - "resolved": "https://registry.nlark.com/diff-sequences/download/diff-sequences-25.2.6.tgz?cache=0&sync_timestamp=1624900057366&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fdiff-sequences%2Fdownload%2Fdiff-sequences-25.2.6.tgz", + "resolved": "https://registry.npmmirror.com/diff-sequences/download/diff-sequences-25.2.6.tgz", "integrity": "sha1-X0Z8AO3TU1K3vKRteSfWDmh6dt0=", "dev": true }, @@ -14528,7 +14945,7 @@ }, "jest-diff": { "version": "25.5.0", - "resolved": "https://registry.nlark.com/jest-diff/download/jest-diff-25.5.0.tgz", + "resolved": "https://registry.npmmirror.com/jest-diff/download/jest-diff-25.5.0.tgz", "integrity": "sha1-HdJu1k+WZnwGjO8Ca2d9+gGvz6k=", "dev": true, "requires": { @@ -14540,13 +14957,13 @@ }, "jest-get-type": { "version": "25.2.6", - "resolved": "https://registry.nlark.com/jest-get-type/download/jest-get-type-25.2.6.tgz?cache=0&sync_timestamp=1624900056951&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fjest-get-type%2Fdownload%2Fjest-get-type-25.2.6.tgz", + "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-25.2.6.tgz", "integrity": "sha1-Cwoy+riQi0TVCL6BaBSH26u42Hc=", "dev": true }, "jest-matcher-utils": { "version": "25.4.0", - "resolved": "https://registry.nlark.com/jest-matcher-utils/download/jest-matcher-utils-25.4.0.tgz", + "resolved": "https://registry.npmmirror.com/jest-matcher-utils/download/jest-matcher-utils-25.4.0.tgz", "integrity": "sha1-3D567EAqHlZ+2AtXK5rShYeIleY=", "dev": true, "requires": { @@ -14558,7 +14975,7 @@ }, "pretty-format": { "version": "25.5.0", - "resolved": "https://registry.nlark.com/pretty-format/download/pretty-format-25.5.0.tgz", + "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-25.5.0.tgz", "integrity": "sha1-eHPB13T2gsNLjUi2dDor8qxVeRo=", "dev": true, "requires": { @@ -14570,7 +14987,7 @@ }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.nlark.com/supports-color/download/supports-color-7.2.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -14581,7 +14998,7 @@ }, "jest-matcher-utils": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/jest-matcher-utils/download/jest-matcher-utils-26.6.2.tgz?cache=0&sync_timestamp=1616701585427&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-matcher-utils%2Fdownload%2Fjest-matcher-utils-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/jest-matcher-utils/download/jest-matcher-utils-26.6.2.tgz", "integrity": "sha1-jm/W6GPIstMaxkcu6yN7xZXlPno=", "dev": true, "requires": { @@ -14593,7 +15010,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -14630,7 +15047,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -14649,7 +15066,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -14664,19 +15081,19 @@ }, "diff-sequences": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/diff-sequences/download/diff-sequences-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/diff-sequences/download/diff-sequences-26.6.2.tgz", "integrity": "sha1-SLqZFX3hkjQS7tQdtrbUqpynwLE=", "dev": true }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", + "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, "jest-diff": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/jest-diff/download/jest-diff-26.6.2.tgz?cache=0&sync_timestamp=1616701585219&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-diff%2Fdownload%2Fjest-diff-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/jest-diff/download/jest-diff-26.6.2.tgz", "integrity": "sha1-GqdGi1LDpo19XF/c381eSb0WQ5Q=", "dev": true, "requires": { @@ -14688,13 +15105,13 @@ }, "jest-get-type": { "version": "26.3.0", - "resolved": "https://registry.npm.taobao.org/jest-get-type/download/jest-get-type-26.3.0.tgz", + "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-26.3.0.tgz", "integrity": "sha1-6X3Dw/U8K0Bsp6+u1Ek7HQmRmeA=", "dev": true }, "pretty-format": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/pretty-format/download/pretty-format-26.6.2.tgz?cache=0&sync_timestamp=1616701219088&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fpretty-format%2Fdownload%2Fpretty-format-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-26.6.2.tgz", "integrity": "sha1-41wnBfFMt/4v6U+geDRbREEg/JM=", "dev": true, "requires": { @@ -14706,13 +15123,13 @@ }, "react-is": { "version": "17.0.2", - "resolved": "https://registry.npm.taobao.org/react-is/download/react-is-17.0.2.tgz", + "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz", "integrity": "sha1-5pHUqOnHiTZWVVOas3J2Kw77VPA=", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -14723,7 +15140,7 @@ }, "jest-message-util": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/jest-message-util/download/jest-message-util-26.6.2.tgz?cache=0&sync_timestamp=1616701584149&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-message-util%2Fdownload%2Fjest-message-util-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/jest-message-util/download/jest-message-util-26.6.2.tgz", "integrity": "sha1-WBc3RK1vwFBrXSEVC5vlbvABygc=", "dev": true, "requires": { @@ -14740,7 +15157,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -14777,7 +15194,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -14805,7 +15222,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -14835,7 +15252,7 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", + "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, @@ -14857,7 +15274,7 @@ }, "pretty-format": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/pretty-format/download/pretty-format-26.6.2.tgz?cache=0&sync_timestamp=1616701219088&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fpretty-format%2Fdownload%2Fpretty-format-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-26.6.2.tgz", "integrity": "sha1-41wnBfFMt/4v6U+geDRbREEg/JM=", "dev": true, "requires": { @@ -14869,13 +15286,13 @@ }, "react-is": { "version": "17.0.2", - "resolved": "https://registry.npm.taobao.org/react-is/download/react-is-17.0.2.tgz", + "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz", "integrity": "sha1-5pHUqOnHiTZWVVOas3J2Kw77VPA=", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -14994,7 +15411,7 @@ }, "jest-regex-util": { "version": "26.0.0", - "resolved": "https://registry.npm.taobao.org/jest-regex-util/download/jest-regex-util-26.0.0.tgz?cache=0&sync_timestamp=1607352728942&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-regex-util%2Fdownload%2Fjest-regex-util-26.0.0.tgz", + "resolved": "https://registry.npmmirror.com/jest-regex-util/download/jest-regex-util-26.0.0.tgz", "integrity": "sha1-0l5xhLNuOf1GbDvEG+CXHoIf7ig=", "dev": true }, @@ -16283,7 +16700,7 @@ }, "jest-util": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/jest-util/download/jest-util-26.6.2.tgz?cache=0&sync_timestamp=1616701582882&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-util%2Fdownload%2Fjest-util-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/jest-util/download/jest-util-26.6.2.tgz", "integrity": "sha1-kHU12+TVpstMR6ybkm9q8pV2y8E=", "dev": true, "requires": { @@ -16297,7 +16714,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -16328,7 +16745,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -16356,7 +16773,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -16386,7 +16803,7 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", + "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, @@ -16408,7 +16825,7 @@ }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -16700,7 +17117,7 @@ }, "jest-worker": { "version": "26.6.2", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-26.6.2.tgz", + "resolved": "https://registry.npmmirror.com/jest-worker/-/jest-worker-26.6.2.tgz", "integrity": "sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==", "dev": true, "requires": { @@ -16711,13 +17128,13 @@ "dependencies": { "has-flag": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { @@ -16733,7 +17150,7 @@ }, "js-tokens": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/js-tokens/download/js-tokens-4.0.0.tgz", + "resolved": "https://registry.nlark.com/js-tokens/download/js-tokens-4.0.0.tgz", "integrity": "sha1-GSA/tZmR35jjoocFDUZHzerzJJk=" }, "js-yaml": { @@ -16748,7 +17165,7 @@ }, "jsdom": { "version": "19.0.0", - "resolved": "https://registry.npmmirror.com/jsdom/-/jsdom-19.0.0.tgz", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-19.0.0.tgz", "integrity": "sha512-RYAyjCbxy/vri/CfnjUWJQQtZ3LKlLnDqj+9XLNnJPgEGeirZs3hllKR20re8LUZ6o1b1X4Jat+Qd26zmP41+A==", "dev": true, "requires": { @@ -16789,7 +17206,7 @@ }, "acorn": { "version": "8.7.1", - "resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.7.1.tgz", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.1.tgz", "integrity": "sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==", "dev": true }, @@ -16936,15 +17353,9 @@ }, "jsesc": { "version": "2.5.2", - "resolved": "https://registry.npm.taobao.org/jsesc/download/jsesc-2.5.2.tgz", + "resolved": "https://registry.nlark.com/jsesc/download/jsesc-2.5.2.tgz", "integrity": "sha1-gFZNLkg9rPbo7yCWUKZ98/DCg6Q=" }, - "json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", - "dev": true - }, "json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmmirror.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -16953,12 +17364,12 @@ }, "json-schema-traverse": { "version": "0.4.1", - "resolved": "https://registry.npm.taobao.org/json-schema-traverse/download/json-schema-traverse-0.4.1.tgz", + "resolved": "https://registry.nlark.com/json-schema-traverse/download/json-schema-traverse-0.4.1.tgz", "integrity": "sha1-afaofZUTq4u4/mO9sJecRI5oRmA=" }, "json-stable-stringify-without-jsonify": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/json-stable-stringify-without-jsonify/download/json-stable-stringify-without-jsonify-1.0.1.tgz", + "resolved": "https://registry.nlark.com/json-stable-stringify-without-jsonify/download/json-stable-stringify-without-jsonify-1.0.1.tgz", "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=" }, "json5": { @@ -16974,7 +17385,7 @@ }, "jsonfile": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/jsonfile/download/jsonfile-4.0.0.tgz", + "resolved": "https://registry.nlark.com/jsonfile/download/jsonfile-4.0.0.tgz", "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", "dev": true, "requires": { @@ -17017,7 +17428,7 @@ }, "last-run": { "version": "1.1.1", - "resolved": "https://registry.npm.taobao.org/last-run/download/last-run-1.1.1.tgz", + "resolved": "https://registry.nlark.com/last-run/download/last-run-1.1.1.tgz", "integrity": "sha1-RblpQsF7HHnHchmCWbqUO+v4yls=", "dev": true, "requires": { @@ -17036,7 +17447,7 @@ }, "lcid": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/lcid/download/lcid-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/lcid/download/lcid-1.0.0.tgz", "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", "dev": true, "requires": { @@ -17054,7 +17465,7 @@ }, "leven": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/leven/download/leven-3.1.0.tgz", + "resolved": "https://registry.nlark.com/leven/download/leven-3.1.0.tgz?cache=0&sync_timestamp=1628597922950&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fleven%2Fdownload%2Fleven-3.1.0.tgz", "integrity": "sha1-d4kd6DQGTMy6gq54QrtrFKE+1/I=", "dev": true }, @@ -17069,7 +17480,7 @@ }, "levn": { "version": "0.3.0", - "resolved": "https://registry.npmmirror.com/levn/-/levn-0.3.0.tgz", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", "dev": true, "requires": { @@ -17101,7 +17512,7 @@ }, "load-json-file": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/load-json-file/download/load-json-file-1.1.0.tgz", + "resolved": "https://registry.nlark.com/load-json-file/download/load-json-file-1.1.0.tgz?cache=0&sync_timestamp=1631508607226&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fload-json-file%2Fdownload%2Fload-json-file-1.1.0.tgz", "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "dev": true, "requires": { @@ -17128,12 +17539,6 @@ "integrity": "sha1-tEf2ZwoEVbv+7dETku/zMOoJdUg=", "dev": true }, - "lodash.clonedeep": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", - "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", - "dev": true - }, "lodash.memoize": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", @@ -17145,15 +17550,9 @@ "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==" }, - "lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", - "dev": true - }, "loose-envify": { "version": "1.4.0", - "resolved": "https://registry.npm.taobao.org/loose-envify/download/loose-envify-1.4.0.tgz", + "resolved": "https://registry.nlark.com/loose-envify/download/loose-envify-1.4.0.tgz", "integrity": "sha1-ce5R+nvkyuwaY4OffmgtgTLTDK8=", "dev": true, "requires": { @@ -17162,7 +17561,7 @@ }, "lru-cache": { "version": "6.0.0", - "resolved": "https://registry.npm.taobao.org/lru-cache/download/lru-cache-6.0.0.tgz", + "resolved": "https://registry.nlark.com/lru-cache/download/lru-cache-6.0.0.tgz", "integrity": "sha1-bW/mVw69lqr5D8rR2vo7JWbbOpQ=", "requires": { "yallist": "^4.0.0" @@ -17196,7 +17595,7 @@ }, "make-error": { "version": "1.3.6", - "resolved": "https://registry.npm.taobao.org/make-error/download/make-error-1.3.6.tgz?cache=0&sync_timestamp=1582105630664&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmake-error%2Fdownload%2Fmake-error-1.3.6.tgz", + "resolved": "https://registry.nlark.com/make-error/download/make-error-1.3.6.tgz", "integrity": "sha1-LrLjfqm2fEiR9oShOUeZr0hM96I=", "dev": true }, @@ -17229,7 +17628,7 @@ }, "map-age-cleaner": { "version": "0.1.3", - "resolved": "https://registry.npm.taobao.org/map-age-cleaner/download/map-age-cleaner-0.1.3.tgz", + "resolved": "https://registry.nlark.com/map-age-cleaner/download/map-age-cleaner-0.1.3.tgz?cache=0&sync_timestamp=1629750856019&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fmap-age-cleaner%2Fdownload%2Fmap-age-cleaner-0.1.3.tgz", "integrity": "sha1-fVg6cwZDTAVf5HSw9FB45uG0uSo=", "dev": true, "requires": { @@ -17238,13 +17637,13 @@ }, "map-cache": { "version": "0.2.2", - "resolved": "https://registry.npm.taobao.org/map-cache/download/map-cache-0.2.2.tgz", + "resolved": "https://registry.nlark.com/map-cache/download/map-cache-0.2.2.tgz", "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", "dev": true }, "map-visit": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/map-visit/download/map-visit-1.0.0.tgz", + "resolved": "https://registry.nlark.com/map-visit/download/map-visit-1.0.0.tgz", "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", "dev": true, "requires": { @@ -17265,7 +17664,7 @@ "dependencies": { "findup-sync": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/findup-sync/download/findup-sync-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/findup-sync/download/findup-sync-2.0.0.tgz?cache=0&sync_timestamp=1635766114067&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Ffindup-sync%2Fdownload%2Ffindup-sync-2.0.0.tgz", "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", "dev": true, "requires": { @@ -17277,7 +17676,7 @@ }, "is-glob": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/is-glob/download/is-glob-3.1.0.tgz", "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { @@ -17299,7 +17698,7 @@ }, "mem": { "version": "4.3.0", - "resolved": "https://registry.npm.taobao.org/mem/download/mem-4.3.0.tgz", + "resolved": "https://registry.nlark.com/mem/download/mem-4.3.0.tgz?cache=0&sync_timestamp=1626534487701&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fmem%2Fdownload%2Fmem-4.3.0.tgz", "integrity": "sha1-Rhr0l7xK4JYIzbLmDu+2m/90QXg=", "dev": true, "requires": { @@ -17318,7 +17717,7 @@ }, "merge-stream": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/merge-stream/download/merge-stream-2.0.0.tgz", + "resolved": "https://registry.nlark.com/merge-stream/download/merge-stream-2.0.0.tgz", "integrity": "sha1-UoI2KaFN0AyXcPtq1H3GMQ8sH2A=", "dev": true }, @@ -17368,19 +17767,19 @@ }, "mime": { "version": "1.6.0", - "resolved": "https://registry.npm.taobao.org/mime/download/mime-1.6.0.tgz?cache=0&sync_timestamp=1560034758817&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmime%2Fdownload%2Fmime-1.6.0.tgz", + "resolved": "https://registry.npmmirror.com/mime/download/mime-1.6.0.tgz", "integrity": "sha1-Ms2eXGRVO9WNGaVor0Uqz/BJgbE=", "dev": true }, "mime-db": { "version": "1.52.0", - "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true }, "mime-types": { "version": "2.1.35", - "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "requires": { @@ -17389,7 +17788,7 @@ }, "mimic-fn": { "version": "2.1.0", - "resolved": "https://registry.npmmirror.com/mimic-fn/-/mimic-fn-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", "dev": true }, @@ -17415,7 +17814,7 @@ }, "minimist": { "version": "1.2.5", - "resolved": "https://registry.npm.taobao.org/minimist/download/minimist-1.2.5.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fminimist%2Fdownload%2Fminimist-1.2.5.tgz", + "resolved": "https://registry.npm.taobao.org/minimist/download/minimist-1.2.5.tgz", "integrity": "sha1-Z9ZgFLZqaoqqDAg8X9WN9OTpdgI=", "dev": true }, @@ -17426,7 +17825,7 @@ }, "mixin-deep": { "version": "1.3.2", - "resolved": "https://registry.npm.taobao.org/mixin-deep/download/mixin-deep-1.3.2.tgz", + "resolved": "https://registry.nlark.com/mixin-deep/download/mixin-deep-1.3.2.tgz", "integrity": "sha1-ESC0PcNZp4Xc5ltVuC4lfM9HlWY=", "dev": true, "requires": { @@ -17436,7 +17835,7 @@ "dependencies": { "is-extendable": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/is-extendable/download/is-extendable-1.0.1.tgz", + "resolved": "https://registry.nlark.com/is-extendable/download/is-extendable-1.0.1.tgz", "integrity": "sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=", "dev": true, "requires": { @@ -17476,7 +17875,7 @@ }, "ms": { "version": "2.1.2", - "resolved": "https://registry.npm.taobao.org/ms/download/ms-2.1.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fms%2Fdownload%2Fms-2.1.2.tgz", + "resolved": "https://registry.npmmirror.com/ms/download/ms-2.1.2.tgz", "integrity": "sha1-0J0fNXtEP0kzgqjrPM0YOHKuYAk=" }, "mute-stdout": { @@ -17501,7 +17900,7 @@ }, "nanomatch": { "version": "1.2.13", - "resolved": "https://registry.npm.taobao.org/nanomatch/download/nanomatch-1.2.13.tgz", + "resolved": "https://registry.nlark.com/nanomatch/download/nanomatch-1.2.13.tgz", "integrity": "sha1-uHqKpPwN6P5r6IiVs4mD/yZb0Rk=", "dev": true, "requires": { @@ -17520,7 +17919,7 @@ }, "natural-compare": { "version": "1.4.0", - "resolved": "https://registry.npm.taobao.org/natural-compare/download/natural-compare-1.4.0.tgz", + "resolved": "https://registry.nlark.com/natural-compare/download/natural-compare-1.4.0.tgz", "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" }, "natural-compare-lite": { @@ -17530,13 +17929,13 @@ }, "next-tick": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/next-tick/download/next-tick-1.0.0.tgz", + "resolved": "https://registry.nlark.com/next-tick/download/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", "dev": true }, "nice-try": { "version": "1.0.5", - "resolved": "https://registry.npm.taobao.org/nice-try/download/nice-try-1.0.5.tgz", + "resolved": "https://registry.nlark.com/nice-try/download/nice-try-1.0.5.tgz", "integrity": "sha1-ozeKdpbOfSI+iPybdkvX7xCJ42Y=", "dev": true }, @@ -17554,7 +17953,7 @@ }, "normalize-package-data": { "version": "2.5.0", - "resolved": "https://registry.npm.taobao.org/normalize-package-data/download/normalize-package-data-2.5.0.tgz", + "resolved": "https://registry.nlark.com/normalize-package-data/download/normalize-package-data-2.5.0.tgz?cache=0&sync_timestamp=1629301872905&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fnormalize-package-data%2Fdownload%2Fnormalize-package-data-2.5.0.tgz", "integrity": "sha1-5m2xg4sgDB38IzIl0SyzZSDiNKg=", "dev": true, "requires": { @@ -17584,7 +17983,7 @@ }, "npm-run-path": { "version": "2.0.2", - "resolved": "https://registry.npm.taobao.org/npm-run-path/download/npm-run-path-2.0.2.tgz?cache=0&sync_timestamp=1577053500910&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fnpm-run-path%2Fdownload%2Fnpm-run-path-2.0.2.tgz", + "resolved": "https://registry.npmmirror.com/npm-run-path/download/npm-run-path-2.0.2.tgz?cache=0&sync_timestamp=1633420566316&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fnpm-run-path%2Fdownload%2Fnpm-run-path-2.0.2.tgz", "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", "dev": true, "requires": { @@ -17593,13 +17992,13 @@ }, "number-is-nan": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/number-is-nan/download/number-is-nan-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/number-is-nan/download/number-is-nan-1.0.1.tgz", "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", "dev": true }, "nwsapi": { "version": "2.2.0", - "resolved": "https://registry.npmmirror.com/nwsapi/-/nwsapi-2.2.0.tgz", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz", "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", "dev": true }, @@ -17648,13 +18047,13 @@ }, "object-keys": { "version": "1.1.1", - "resolved": "https://registry.npm.taobao.org/object-keys/download/object-keys-1.1.1.tgz", + "resolved": "https://registry.nlark.com/object-keys/download/object-keys-1.1.1.tgz", "integrity": "sha1-HEfyct8nfzsdrwYWd9nILiMixg4=", "dev": true }, "object-visit": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/object-visit/download/object-visit-1.0.1.tgz", + "resolved": "https://registry.nlark.com/object-visit/download/object-visit-1.0.1.tgz", "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", "dev": true, "requires": { @@ -17686,19 +18085,19 @@ } }, "object.entries": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.4.tgz", - "integrity": "sha512-h4LWKWE+wKQGhtMjZEBud7uLGhqyLwj8fpHOarZhD2uY3C9cRtk57VQ89ke3moByLXMedqs3XCHzyb4AmA2DjA==", + "version": "1.1.6", + "resolved": "https://registry.npmmirror.com/object.entries/-/object.entries-1.1.6.tgz", + "integrity": "sha512-leTPzo4Zvg3pmbQ3rDK69Rl8GQvIqMWubrkxONG9/ojtFE2rD9fjMKfSI5BxW3osRH1m6VdzmqK8oAY9aT4x5w==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.2" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -17706,16 +18105,33 @@ "get-intrinsic": "^1.0.2" } }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", "dev": true, "requires": { "function-bind": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true } } }, @@ -17749,19 +18165,19 @@ } }, "object.values": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.4.tgz", - "integrity": "sha512-TnGo7j4XSnKQoK3MfvkzqKCi0nVe/D9I9IjwTNYdb/fxYHpjrluHVOgw0AF6jrRFGMPHdfuidR09tIDiIvnaSg==", + "version": "1.1.6", + "resolved": "https://registry.npmmirror.com/object.values/-/object.values-1.1.6.tgz", + "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.2" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -17769,22 +18185,39 @@ "get-intrinsic": "^1.0.2" } }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", "dev": true, "requires": { "function-bind": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true } } }, "once": { "version": "1.4.0", - "resolved": "https://registry.npm.taobao.org/once/download/once-1.4.0.tgz", + "resolved": "https://registry.nlark.com/once/download/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "requires": { "wrappy": "1" @@ -17792,7 +18225,7 @@ }, "onetime": { "version": "5.1.2", - "resolved": "https://registry.npmmirror.com/onetime/-/onetime-5.1.2.tgz", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dev": true, "requires": { @@ -17812,13 +18245,13 @@ }, "opener": { "version": "1.5.2", - "resolved": "https://registry.npm.taobao.org/opener/download/opener-1.5.2.tgz", + "resolved": "https://registry.nlark.com/opener/download/opener-1.5.2.tgz?cache=0&sync_timestamp=1618847055043&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fopener%2Fdownload%2Fopener-1.5.2.tgz", "integrity": "sha1-XTfh81B3udysQwE3InGv3rKhNZg=", "dev": true }, "optionator": { "version": "0.8.3", - "resolved": "https://registry.npmmirror.com/optionator/-/optionator-0.8.3.tgz", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", "dev": true, "requires": { @@ -17847,7 +18280,7 @@ }, "os-locale": { "version": "1.4.0", - "resolved": "https://registry.npm.taobao.org/os-locale/download/os-locale-1.4.0.tgz", + "resolved": "https://registry.npmmirror.com/os-locale/download/os-locale-1.4.0.tgz?cache=0&sync_timestamp=1633618260196&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fos-locale%2Fdownload%2Fos-locale-1.4.0.tgz", "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", "dev": true, "requires": { @@ -17862,7 +18295,7 @@ }, "p-finally": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/p-finally/download/p-finally-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/p-finally/download/p-finally-1.0.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fp-finally%2Fdownload%2Fp-finally-1.0.0.tgz", "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", "dev": true }, @@ -17901,7 +18334,7 @@ }, "p-try": { "version": "2.2.0", - "resolved": "https://registry.npm.taobao.org/p-try/download/p-try-2.2.0.tgz", + "resolved": "https://registry.npmmirror.com/p-try/download/p-try-2.2.0.tgz", "integrity": "sha1-yyhoVA4xPWHeWPr741zpAE1VQOY=", "dev": true }, @@ -17954,7 +18387,7 @@ }, "parse-json": { "version": "2.2.0", - "resolved": "https://registry.npm.taobao.org/parse-json/download/parse-json-2.2.0.tgz", + "resolved": "https://registry.npmmirror.com/parse-json/download/parse-json-2.2.0.tgz?cache=0&sync_timestamp=1637475717072&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fparse-json%2Fdownload%2Fparse-json-2.2.0.tgz", "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", "dev": true, "requires": { @@ -17963,7 +18396,7 @@ }, "parse-node-version": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/parse-node-version/download/parse-node-version-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/parse-node-version/download/parse-node-version-1.0.1.tgz", "integrity": "sha1-4rXb7eAOf6m8NjYH9TMn6LBzGJs=", "dev": true }, @@ -17975,20 +18408,20 @@ }, "parse5": { "version": "6.0.1", - "resolved": "https://registry.npmmirror.com/parse5/-/parse5-6.0.1.tgz", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", "dev": true }, "pascalcase": { "version": "0.1.1", - "resolved": "https://registry.npm.taobao.org/pascalcase/download/pascalcase-0.1.1.tgz", + "resolved": "https://registry.nlark.com/pascalcase/download/pascalcase-0.1.1.tgz", "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", "dev": true }, "path": { "version": "0.12.7", "resolved": "https://registry.npmjs.org/path/-/path-0.12.7.tgz", - "integrity": "sha1-1NwqUGxM4hl+tIHr/NWzbAFAsQ8=", + "integrity": "sha512-aXXC6s+1w7otVF9UletFkFcDsJeO7lSZBPUQhtb5O0xJe8LtYhj/GxldoL09bBj9+ZmE2hNoHqQSFMN5fikh4Q==", "dev": true, "requires": { "process": "^0.11.1", @@ -18003,13 +18436,13 @@ }, "path-dirname": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/path-dirname/download/path-dirname-1.0.2.tgz", + "resolved": "https://registry.nlark.com/path-dirname/download/path-dirname-1.0.2.tgz", "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", "dev": true }, "path-exists": { "version": "3.0.0", - "resolved": "https://registry.npm.taobao.org/path-exists/download/path-exists-3.0.0.tgz", + "resolved": "https://registry.nlark.com/path-exists/download/path-exists-3.0.0.tgz", "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", "dev": true }, @@ -18037,7 +18470,7 @@ }, "path-root": { "version": "0.1.1", - "resolved": "https://registry.npm.taobao.org/path-root/download/path-root-0.1.1.tgz", + "resolved": "https://registry.nlark.com/path-root/download/path-root-0.1.1.tgz", "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", "dev": true, "requires": { @@ -18046,7 +18479,7 @@ }, "path-root-regex": { "version": "0.1.2", - "resolved": "https://registry.npm.taobao.org/path-root-regex/download/path-root-regex-0.1.2.tgz", + "resolved": "https://registry.nlark.com/path-root-regex/download/path-root-regex-0.1.2.tgz", "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", "dev": true }, @@ -18103,19 +18536,19 @@ }, "pify": { "version": "2.3.0", - "resolved": "https://registry.npm.taobao.org/pify/download/pify-2.3.0.tgz?cache=0&sync_timestamp=1581697613983&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fpify%2Fdownload%2Fpify-2.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/pify/download/pify-2.3.0.tgz", "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "dev": true }, "pinkie": { "version": "2.0.4", - "resolved": "https://registry.npm.taobao.org/pinkie/download/pinkie-2.0.4.tgz", + "resolved": "https://registry.nlark.com/pinkie/download/pinkie-2.0.4.tgz", "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", "dev": true }, "pinkie-promise": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/pinkie-promise/download/pinkie-promise-2.0.1.tgz", + "resolved": "https://registry.nlark.com/pinkie-promise/download/pinkie-promise-2.0.1.tgz?cache=0&sync_timestamp=1618847023792&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fpinkie-promise%2Fdownload%2Fpinkie-promise-2.0.1.tgz", "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", "dev": true, "requires": { @@ -18173,60 +18606,6 @@ } } }, - "pkg-up": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-2.0.0.tgz", - "integrity": "sha1-yBmscoBZpGHKscOImivjxJoATX8=", - "dev": true, - "requires": { - "find-up": "^2.1.0" - }, - "dependencies": { - "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" - } - }, - "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 - } - } - }, "plugin-error": { "version": "1.0.1", "resolved": "https://registry.npmmirror.com/plugin-error/-/plugin-error-1.0.1.tgz", @@ -18247,7 +18626,7 @@ }, "portfinder": { "version": "1.0.28", - "resolved": "https://registry.npm.taobao.org/portfinder/download/portfinder-1.0.28.tgz", + "resolved": "https://registry.nlark.com/portfinder/download/portfinder-1.0.28.tgz", "integrity": "sha1-Z8RiKFK9U3TdHdkA93n1NGL6x3g=", "dev": true, "requires": { @@ -18258,7 +18637,7 @@ "dependencies": { "debug": { "version": "3.2.7", - "resolved": "https://registry.npm.taobao.org/debug/download/debug-3.2.7.tgz?cache=0&sync_timestamp=1607566580543&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fdebug%2Fdownload%2Fdebug-3.2.7.tgz", + "resolved": "https://registry.npmmirror.com/debug/download/debug-3.2.7.tgz", "integrity": "sha1-clgLfpFF+zm2Z2+cXl+xALk0F5o=", "dev": true, "requires": { @@ -18278,19 +18657,19 @@ }, "posix-character-classes": { "version": "0.1.1", - "resolved": "https://registry.npm.taobao.org/posix-character-classes/download/posix-character-classes-0.1.1.tgz", + "resolved": "https://registry.nlark.com/posix-character-classes/download/posix-character-classes-0.1.1.tgz", "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", "dev": true }, "prelude-ls": { "version": "1.1.2", - "resolved": "https://registry.npmmirror.com/prelude-ls/-/prelude-ls-1.1.2.tgz", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", "dev": true }, "pretty-format": { "version": "24.9.0", - "resolved": "https://registry.npm.taobao.org/pretty-format/download/pretty-format-24.9.0.tgz", + "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-24.9.0.tgz", "integrity": "sha1-EvrDGzcBmk7qPBGqmpWet2KKp8k=", "dev": true, "requires": { @@ -18302,7 +18681,7 @@ "dependencies": { "ansi-regex": { "version": "4.1.0", - "resolved": "https://registry.npm.taobao.org/ansi-regex/download/ansi-regex-4.1.0.tgz", + "resolved": "https://registry.nlark.com/ansi-regex/download/ansi-regex-4.1.0.tgz", "integrity": "sha1-i5+PCM8ay4Q3Vqg5yox+MWjFGZc=", "dev": true } @@ -18323,7 +18702,7 @@ "process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", "dev": true }, "process-nextick-args": { @@ -18332,12 +18711,6 @@ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "dev": true }, - "progress": { - "version": "2.0.3", - "resolved": "https://registry.npm.taobao.org/progress/download/progress-2.0.3.tgz", - "integrity": "sha1-foz42PW48jnBvGi+tOt4Vn1XLvg=", - "dev": true - }, "prompts": { "version": "2.4.2", "resolved": "https://registry.npmmirror.com/prompts/-/prompts-2.4.2.tgz", @@ -18350,7 +18723,7 @@ }, "psl": { "version": "1.8.0", - "resolved": "https://registry.npmmirror.com/psl/-/psl-1.8.0.tgz", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", "dev": true }, @@ -18422,7 +18795,7 @@ }, "punycode": { "version": "2.1.1", - "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.1.1.tgz", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", "dev": true }, @@ -18468,7 +18841,7 @@ }, "react-is": { "version": "16.13.1", - "resolved": "https://registry.npm.taobao.org/react-is/download/react-is-16.13.1.tgz", + "resolved": "https://registry.npmmirror.com/react-is/download/react-is-16.13.1.tgz", "integrity": "sha1-eJcppNw23imZ3BVt1sHZwYzqVqQ=", "dev": true }, @@ -18483,7 +18856,7 @@ }, "read-pkg": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/read-pkg/download/read-pkg-1.1.0.tgz", + "resolved": "https://registry.nlark.com/read-pkg/download/read-pkg-1.1.0.tgz", "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", "dev": true, "requires": { @@ -18494,7 +18867,7 @@ }, "read-pkg-up": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/read-pkg-up/download/read-pkg-up-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/read-pkg-up/download/read-pkg-up-1.0.1.tgz", "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", "dev": true, "requires": { @@ -18504,7 +18877,7 @@ "dependencies": { "find-up": { "version": "1.1.2", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "resolved": "https://registry.npmmirror.com/find-up/download/find-up-1.1.2.tgz?cache=0&sync_timestamp=1633620747957&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Ffind-up%2Fdownload%2Ffind-up-1.1.2.tgz", "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { @@ -18514,7 +18887,7 @@ }, "path-exists": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "resolved": "https://registry.nlark.com/path-exists/download/path-exists-2.1.0.tgz", "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "dev": true, "requires": { @@ -18551,7 +18924,7 @@ }, "readdirp": { "version": "2.2.1", - "resolved": "https://registry.npm.taobao.org/readdirp/download/readdirp-2.2.1.tgz?cache=0&sync_timestamp=1575629866543&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Freaddirp%2Fdownload%2Freaddirp-2.2.1.tgz", + "resolved": "https://registry.nlark.com/readdirp/download/readdirp-2.2.1.tgz", "integrity": "sha1-DodiKjMlqjPokihcr4tOhGUppSU=", "dev": true, "requires": { @@ -18562,7 +18935,7 @@ }, "rechoir": { "version": "0.6.2", - "resolved": "https://registry.npm.taobao.org/rechoir/download/rechoir-0.6.2.tgz", + "resolved": "https://registry.nlark.com/rechoir/download/rechoir-0.6.2.tgz?cache=0&sync_timestamp=1627101677944&other_urls=https%3A%2F%2Fregistry.nlark.com%2Frechoir%2Fdownload%2Frechoir-0.6.2.tgz", "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", "dev": true, "requires": { @@ -18602,7 +18975,7 @@ }, "regex-not": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/regex-not/download/regex-not-1.0.2.tgz", + "resolved": "https://registry.nlark.com/regex-not/download/regex-not-1.0.2.tgz", "integrity": "sha1-H07OJ+ALC2XgJHpoEOaoXYOldSw=", "dev": true, "requires": { @@ -18644,12 +19017,6 @@ } } }, - "regexpp": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", - "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", - "dev": true - }, "regexpu-core": { "version": "4.7.0", "resolved": "https://registry.npm.taobao.org/regexpu-core/download/regexpu-core-4.7.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fregexpu-core%2Fdownload%2Fregexpu-core-4.7.0.tgz", @@ -18681,7 +19048,7 @@ "dependencies": { "jsesc": { "version": "0.5.0", - "resolved": "https://registry.npm.taobao.org/jsesc/download/jsesc-0.5.0.tgz", + "resolved": "https://registry.nlark.com/jsesc/download/jsesc-0.5.0.tgz", "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", "dev": true } @@ -18710,7 +19077,7 @@ }, "remove-trailing-separator": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/remove-trailing-separator/download/remove-trailing-separator-1.1.0.tgz", + "resolved": "https://registry.nlark.com/remove-trailing-separator/download/remove-trailing-separator-1.1.0.tgz", "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", "dev": true }, @@ -18745,16 +19112,10 @@ }, "require-directory": { "version": "2.1.1", - "resolved": "https://registry.npm.taobao.org/require-directory/download/require-directory-2.1.1.tgz", + "resolved": "https://registry.nlark.com/require-directory/download/require-directory-2.1.1.tgz", "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, - "require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true - }, "require-main-filename": { "version": "1.0.1", "resolved": "https://registry.npm.taobao.org/require-main-filename/download/require-main-filename-1.0.1.tgz", @@ -18763,7 +19124,7 @@ }, "requires-port": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/requires-port/download/requires-port-1.0.0.tgz", + "resolved": "https://registry.nlark.com/requires-port/download/requires-port-1.0.0.tgz", "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", "dev": true }, @@ -18819,7 +19180,7 @@ }, "resolve-url": { "version": "0.2.1", - "resolved": "https://registry.npm.taobao.org/resolve-url/download/resolve-url-0.2.1.tgz", + "resolved": "https://registry.npmmirror.com/resolve-url/download/resolve-url-0.2.1.tgz", "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", "dev": true }, @@ -18831,7 +19192,7 @@ }, "ret": { "version": "0.1.15", - "resolved": "https://registry.npm.taobao.org/ret/download/ret-0.1.15.tgz", + "resolved": "https://registry.nlark.com/ret/download/ret-0.1.15.tgz", "integrity": "sha1-uKSCXVvbH8P29Twrwz+BOIaBx7w=", "dev": true }, @@ -19071,7 +19432,7 @@ }, "safe-buffer": { "version": "5.1.2", - "resolved": "https://registry.npm.taobao.org/safe-buffer/download/safe-buffer-5.1.2.tgz", + "resolved": "https://registry.nlark.com/safe-buffer/download/safe-buffer-5.1.2.tgz?cache=0&sync_timestamp=1618847044058&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsafe-buffer%2Fdownload%2Fsafe-buffer-5.1.2.tgz", "integrity": "sha1-mR7GnSluAxN0fVm9/St0XDX4go0=" }, "safe-regex": { @@ -19083,15 +19444,56 @@ "ret": "~0.1.10" } }, + "safe-regex-test": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/safe-regex-test/-/safe-regex-test-1.0.0.tgz", + "integrity": "sha512-JBUUzyOgEwXQY1NuPtvcj/qcBDbDmEvWufhlnXZIm75DEHp+afM1r1ujJpJsV/gSM4t59tpDyPi1sd6ZaPFfsA==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-regex": "^1.1.4" + }, + "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + } + } + }, "safer-buffer": { "version": "2.1.2", - "resolved": "https://registry.npm.taobao.org/safer-buffer/download/safer-buffer-2.1.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsafer-buffer%2Fdownload%2Fsafer-buffer-2.1.2.tgz", + "resolved": "https://registry.nlark.com/safer-buffer/download/safer-buffer-2.1.2.tgz", "integrity": "sha1-RPoWGwGHuVSd2Eu5GAL5vYOFzWo=", "dev": true }, "saxes": { "version": "5.0.1", - "resolved": "https://registry.npmmirror.com/saxes/-/saxes-5.0.1.tgz", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", "dev": true, "requires": { @@ -19112,7 +19514,7 @@ }, "semver-greatest-satisfied-range": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/semver-greatest-satisfied-range/download/semver-greatest-satisfied-range-1.1.0.tgz", + "resolved": "https://registry.nlark.com/semver-greatest-satisfied-range/download/semver-greatest-satisfied-range-1.1.0.tgz", "integrity": "sha1-E+jCZYq5aRywzXEJMkAoDTb3els=", "dev": true, "requires": { @@ -19130,13 +19532,13 @@ }, "set-blocking": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/set-blocking/download/set-blocking-2.0.0.tgz", + "resolved": "https://registry.nlark.com/set-blocking/download/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, "set-value": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/set-value/download/set-value-2.0.1.tgz", + "resolved": "https://registry.nlark.com/set-value/download/set-value-2.0.1.tgz", "integrity": "sha1-oY1AUw5vB95CKMfe/kInr4ytAFs=", "dev": true, "requires": { @@ -19148,7 +19550,7 @@ "dependencies": { "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -19210,7 +19612,7 @@ }, "side-channel": { "version": "1.0.4", - "resolved": "https://registry.npm.taobao.org/side-channel/download/side-channel-1.0.4.tgz", + "resolved": "https://registry.nlark.com/side-channel/download/side-channel-1.0.4.tgz", "integrity": "sha1-785cj9wQTudRslxY1CkAEfpeos8=", "dev": true, "requires": { @@ -19225,82 +19627,39 @@ "integrity": "sha1-FfWfN2+FXERpY5SPDSTNNje0q8Y=", "dev": true, "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - } - } - } - }, - "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npm.taobao.org/signal-exit/download/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", - "dev": true - }, - "simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "dev": true - }, - "sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmmirror.com/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true - }, - "slash": { - "version": "3.0.0", - "resolved": "https://registry.npm.taobao.org/slash/download/slash-3.0.0.tgz", - "integrity": "sha1-ZTm+hwwWWtvVJAIg2+Nh8bxNRjQ=" - }, - "slice-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, - "requires": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "dependencies": { - "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": { - "color-convert": "^2.0.1" - } - }, - "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 - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + } } } }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npm.taobao.org/signal-exit/download/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "dev": true + }, + "sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.nlark.com/slash/download/slash-3.0.0.tgz", + "integrity": "sha1-ZTm+hwwWWtvVJAIg2+Nh8bxNRjQ=" + }, "snapdragon": { "version": "0.8.2", - "resolved": "https://registry.npm.taobao.org/snapdragon/download/snapdragon-0.8.2.tgz", + "resolved": "https://registry.npm.taobao.org/snapdragon/download/snapdragon-0.8.2.tgz?cache=0&sync_timestamp=1617971785350&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsnapdragon%2Fdownload%2Fsnapdragon-0.8.2.tgz", "integrity": "sha1-ZJIufFZbDhQgS6GqfWlkJ40lGC0=", "dev": true, "requires": { @@ -19316,7 +19675,7 @@ "dependencies": { "debug": { "version": "2.6.9", - "resolved": "https://registry.npm.taobao.org/debug/download/debug-2.6.9.tgz", + "resolved": "https://registry.npmmirror.com/debug/download/debug-2.6.9.tgz", "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", "dev": true, "requires": { @@ -19334,7 +19693,7 @@ }, "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -19343,7 +19702,7 @@ }, "ms": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/ms/download/ms-2.0.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fms%2Fdownload%2Fms-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/ms/download/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true } @@ -19371,7 +19730,7 @@ }, "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -19380,7 +19739,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -19402,7 +19761,7 @@ }, "snapdragon-util": { "version": "3.0.1", - "resolved": "https://registry.npm.taobao.org/snapdragon-util/download/snapdragon-util-3.0.1.tgz", + "resolved": "https://registry.nlark.com/snapdragon-util/download/snapdragon-util-3.0.1.tgz", "integrity": "sha1-+VZHlIbyrNeXAGk/b3uAXkWrVuI=", "dev": true, "requires": { @@ -19471,7 +19830,7 @@ }, "sparkles": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/sparkles/download/sparkles-1.0.1.tgz", + "resolved": "https://registry.nlark.com/sparkles/download/sparkles-1.0.1.tgz", "integrity": "sha1-AI22XtzmxQ7sDF4ijhlFBh3QQ3w=", "dev": true }, @@ -19515,7 +19874,7 @@ }, "split-string": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/split-string/download/split-string-3.1.0.tgz", + "resolved": "https://registry.nlark.com/split-string/download/split-string-3.1.0.tgz", "integrity": "sha1-fLCd2jqGWFcFxks5pkZgOGguj+I=", "dev": true, "requires": { @@ -19524,13 +19883,13 @@ }, "sprintf-js": { "version": "1.0.3", - "resolved": "https://registry.npm.taobao.org/sprintf-js/download/sprintf-js-1.0.3.tgz", + "resolved": "https://registry.nlark.com/sprintf-js/download/sprintf-js-1.0.3.tgz?cache=0&sync_timestamp=1618847174560&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsprintf-js%2Fdownload%2Fsprintf-js-1.0.3.tgz", "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, "stack-trace": { "version": "0.0.10", - "resolved": "https://registry.npm.taobao.org/stack-trace/download/stack-trace-0.0.10.tgz", + "resolved": "https://registry.nlark.com/stack-trace/download/stack-trace-0.0.10.tgz?cache=0&sync_timestamp=1620387179562&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fstack-trace%2Fdownload%2Fstack-trace-0.0.10.tgz", "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", "dev": true }, @@ -19545,7 +19904,7 @@ "dependencies": { "escape-string-regexp": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/escape-string-regexp/download/escape-string-regexp-2.0.0.tgz", + "resolved": "https://registry.nlark.com/escape-string-regexp/download/escape-string-regexp-2.0.0.tgz", "integrity": "sha1-owME6Z2qMuI7L9IPUbq9B8/8o0Q=", "dev": true } @@ -19737,19 +20096,71 @@ } } }, + "string.prototype.trim": { + "version": "1.2.7", + "resolved": "https://registry.npmmirror.com/string.prototype.trim/-/string.prototype.trim-1.2.7.tgz", + "integrity": "sha512-p6TmeT1T3411M8Cgg9wBTMRtY2q9+PNy9EV1i2lIXUN/btt763oIfxwN3RR8VU6wHX8j/1CFy0L+YuThm6bgOg==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" + }, + "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + } + } + }, "string.prototype.trimend": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", - "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "version": "1.0.6", + "resolved": "https://registry.npmmirror.com/string.prototype.trimend/-/string.prototype.trimend-1.0.6.tgz", + "integrity": "sha512-JySq+4mrPf9EsDBEDYMOb/lM7XQLulwg5R/m1r0PXEFqrV0qHvl58sdTilSXtKOflCsK2E8jxf+GKC0T07RWwQ==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -19757,32 +20168,50 @@ "get-intrinsic": "^1.0.2" } }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", "dev": true, "requires": { "function-bind": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true } } }, "string.prototype.trimstart": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", - "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "version": "1.0.6", + "resolved": "https://registry.npmmirror.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.6.tgz", + "integrity": "sha512-omqjMDaY92pbn5HOX7f9IccLA+U1tA9GvtU4JrodiXFfYB7jPzzHpRzpglLAjtUV6bB557zwClJezTqnAiYnQA==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -19790,16 +20219,33 @@ "get-intrinsic": "^1.0.2" } }, + "define-properties": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.0.tgz", + "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", "dev": true, "requires": { "function-bind": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true } } }, @@ -19829,7 +20275,7 @@ }, "strip-eof": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/strip-eof/download/strip-eof-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/strip-eof/download/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", "dev": true }, @@ -19855,7 +20301,7 @@ }, "supports-color": { "version": "5.5.0", - "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-5.5.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-5.5.0.tgz", "integrity": "sha1-4uaaRKyHcveKHsCzW2id9lMO/I8=", "requires": { "has-flag": "^3.0.0" @@ -19890,7 +20336,7 @@ }, "supports-preserve-symlinks-flag": { "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" }, "sver-compat": { @@ -19905,7 +20351,7 @@ }, "symbol-tree": { "version": "3.2.4", - "resolved": "https://registry.npmmirror.com/symbol-tree/-/symbol-tree-3.2.4.tgz", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, @@ -19918,78 +20364,6 @@ "acorn-node": "^1.2.0" } }, - "table": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/table/-/table-6.7.1.tgz", - "integrity": "sha512-ZGum47Yi6KOOFDE8m223td53ath2enHcYLgOCjGr5ngu8bdIARQk6mN/wRMv4yMRcHnCSnHbCEha4sobQx5yWg==", - "dev": true, - "requires": { - "ajv": "^8.0.1", - "lodash.clonedeep": "^4.5.0", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0" - }, - "dependencies": { - "ajv": { - "version": "8.6.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.6.2.tgz", - "integrity": "sha512-9807RlWAgT564wT+DjeyU5OFMPjmzxVobvDFmNAhY+5zD6A2ly3jDp6sgnfyDtlIQ+7H97oc/DGCzzfu9rjw9w==", - "dev": true, - "requires": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - } - }, - "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", - "dev": true - }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true - }, - "json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true - }, - "string-width": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", - "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", - "dev": true, - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.0" - } - }, - "strip-ansi": { - "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": "^5.0.0" - } - } - } - }, "terminal-link": { "version": "2.1.1", "resolved": "https://registry.npmmirror.com/terminal-link/-/terminal-link-2.1.1.tgz", @@ -20049,7 +20423,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.nlark.com/text-table/download/text-table-0.2.0.tgz?cache=0&sync_timestamp=1618847142316&other_urls=https%3A%2F%2Fregistry.nlark.com%2Ftext-table%2Fdownload%2Ftext-table-0.2.0.tgz", "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" }, "tfig": { @@ -20211,7 +20585,7 @@ }, "time-stamp": { "version": "1.1.0", - "resolved": "https://registry.npm.taobao.org/time-stamp/download/time-stamp-1.1.0.tgz", + "resolved": "https://registry.nlark.com/time-stamp/download/time-stamp-1.1.0.tgz", "integrity": "sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=", "dev": true }, @@ -20235,13 +20609,13 @@ }, "tmpl": { "version": "1.0.5", - "resolved": "https://registry.npmmirror.com/tmpl/-/tmpl-1.0.5.tgz", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", "dev": true }, "to-absolute-glob": { "version": "2.0.2", - "resolved": "https://registry.npm.taobao.org/to-absolute-glob/download/to-absolute-glob-2.0.2.tgz", + "resolved": "https://registry.nlark.com/to-absolute-glob/download/to-absolute-glob-2.0.2.tgz", "integrity": "sha1-GGX0PZ50sIItufFFt4z/fQ98hJs=", "dev": true, "requires": { @@ -20251,12 +20625,12 @@ }, "to-fast-properties": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/to-fast-properties/download/to-fast-properties-2.0.0.tgz", + "resolved": "https://registry.nlark.com/to-fast-properties/download/to-fast-properties-2.0.0.tgz?cache=0&sync_timestamp=1628418893613&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fto-fast-properties%2Fdownload%2Fto-fast-properties-2.0.0.tgz", "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=" }, "to-object-path": { "version": "0.3.0", - "resolved": "https://registry.npm.taobao.org/to-object-path/download/to-object-path-0.3.0.tgz", + "resolved": "https://registry.nlark.com/to-object-path/download/to-object-path-0.3.0.tgz", "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", "dev": true, "requires": { @@ -20276,7 +20650,7 @@ }, "to-regex": { "version": "3.0.2", - "resolved": "https://registry.npm.taobao.org/to-regex/download/to-regex-3.0.2.tgz", + "resolved": "https://registry.nlark.com/to-regex/download/to-regex-3.0.2.tgz", "integrity": "sha1-E8/dmzNlUvMLUfM6iuG0Knp1mc4=", "dev": true, "requires": { @@ -20307,7 +20681,7 @@ }, "tough-cookie": { "version": "4.0.0", - "resolved": "https://registry.npmmirror.com/tough-cookie/-/tough-cookie-4.0.0.tgz", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", "dev": true, "requires": { @@ -20322,6 +20696,12 @@ "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", "dev": true }, + "ts-api-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/ts-api-utils/-/ts-api-utils-1.0.1.tgz", + "integrity": "sha512-lC/RGlPmwdrIBFTX59wwNzqh7aR2otPNPR/5brHZm/XKFYKsfqxihXUe9pU3JI+3vGkl+vyCoNNnPhJn3aLK1A==", + "dev": true + }, "ts-jest": { "version": "26.5.4", "resolved": "https://registry.npm.taobao.org/ts-jest/download/ts-jest-26.5.4.tgz", @@ -20342,13 +20722,13 @@ "dependencies": { "mkdirp": { "version": "1.0.4", - "resolved": "https://registry.npm.taobao.org/mkdirp/download/mkdirp-1.0.4.tgz?cache=0&sync_timestamp=1587535418745&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmkdirp%2Fdownload%2Fmkdirp-1.0.4.tgz", + "resolved": "https://registry.npmmirror.com/mkdirp/download/mkdirp-1.0.4.tgz", "integrity": "sha1-PrXtYmInVteaXw4qIh3+utdcL34=", "dev": true }, "semver": { "version": "7.3.5", - "resolved": "https://registry.npm.taobao.org/semver/download/semver-7.3.5.tgz?cache=0&sync_timestamp=1616463603361&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsemver%2Fdownload%2Fsemver-7.3.5.tgz", + "resolved": "https://registry.nlark.com/semver/download/semver-7.3.5.tgz?cache=0&sync_timestamp=1618846864940&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsemver%2Fdownload%2Fsemver-7.3.5.tgz", "integrity": "sha1-C2Ich5NI2JmOSw5L6Us/EuYBjvc=", "dev": true, "requires": { @@ -20364,20 +20744,36 @@ } }, "tsconfig-paths": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.10.1.tgz", - "integrity": "sha512-rETidPDgCpltxF7MjBZlAFPUHv5aHH2MymyPvh+vEyWAED4Eb/WeMbsnD/JDr4OKPOA1TssDHgIcpTN5Kh0p6Q==", + "version": "3.14.2", + "resolved": "https://registry.npmmirror.com/tsconfig-paths/-/tsconfig-paths-3.14.2.tgz", + "integrity": "sha512-o/9iXgCYc5L/JxCHPe3Hvh8Q/2xm5Z+p18PESBU6Ff33695QnCHBEjcytY2q19ua7Mbl/DavtBOLq+oG0RCL+g==", "dev": true, "requires": { - "json5": "^2.2.0", - "minimist": "^1.2.0", + "@types/json5": "^0.0.29", + "json5": "^1.0.2", + "minimist": "^1.2.6", "strip-bom": "^3.0.0" }, "dependencies": { + "json5": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + }, + "minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmmirror.com/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true + }, "strip-bom": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "resolved": "https://registry.npmmirror.com/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", "dev": true } } @@ -20428,6 +20824,103 @@ "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", "dev": true }, + "typed-array-byte-offset": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/typed-array-byte-offset/-/typed-array-byte-offset-1.0.0.tgz", + "integrity": "sha512-RD97prjEt9EL8YgAgpOkf3O4IF9lhJFr9g0htQkm0rchFp/Vx7LW5Q8fSXXub7BXAODyUQohRMyOc3faCPd0hg==", + "dev": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "has-proto": "^1.0.1", + "is-typed-array": "^1.1.10" + }, + "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + }, + "is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmmirror.com/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", + "dev": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + } + } + } + }, + "typed-array-length": { + "version": "1.0.4", + "resolved": "https://registry.npmmirror.com/typed-array-length/-/typed-array-length-1.0.4.tgz", + "integrity": "sha512-KjZypGq+I/H7HI5HlOoGHkWUUGq+Q0TPhQurLbyrVrvnKTBgzLhIJ7j6J/XTQOi0d1RjyZ0wdas8bKs2p0x3Ng==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "is-typed-array": "^1.1.9" + }, + "dependencies": { + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + } + } + }, "typedarray": { "version": "0.0.6", "resolved": "https://registry.npm.taobao.org/typedarray/download/typedarray-0.0.6.tgz", @@ -20578,28 +21071,56 @@ "dev": true }, "unbox-primitive": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", - "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/unbox-primitive/-/unbox-primitive-1.0.2.tgz", + "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", "dev": true, "requires": { - "function-bind": "^1.1.1", - "has-bigints": "^1.0.1", - "has-symbols": "^1.0.2", + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", "which-boxed-primitive": "^1.0.2" }, "dependencies": { - "has-symbols": { + "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "get-intrinsic": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + } + }, + "has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", "dev": true } } }, "unc-path-regex": { "version": "0.1.2", - "resolved": "https://registry.npm.taobao.org/unc-path-regex/download/unc-path-regex-0.1.2.tgz", + "resolved": "https://registry.nlark.com/unc-path-regex/download/unc-path-regex-0.1.2.tgz", "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", "dev": true }, @@ -20669,7 +21190,7 @@ }, "union": { "version": "0.5.0", - "resolved": "https://registry.npm.taobao.org/union/download/union-0.5.0.tgz", + "resolved": "https://registry.nlark.com/union/download/union-0.5.0.tgz", "integrity": "sha1-ssEb6E9gU4U3uEbtuboma6AJAHU=", "dev": true, "requires": { @@ -20678,7 +21199,7 @@ }, "union-value": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/union-value/download/union-value-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/union-value/download/union-value-1.0.1.tgz", "integrity": "sha1-C2/nuDWuzaYcbqTU8CwUIh4QmEc=", "dev": true, "requires": { @@ -20700,13 +21221,13 @@ }, "universalify": { "version": "0.1.2", - "resolved": "https://registry.npm.taobao.org/universalify/download/universalify-0.1.2.tgz", + "resolved": "https://registry.nlark.com/universalify/download/universalify-0.1.2.tgz", "integrity": "sha1-tkb2m+OULavOzJ1mOcgNwQXvqmY=", "dev": true }, "unset-value": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/unset-value/download/unset-value-1.0.0.tgz", + "resolved": "https://registry.nlark.com/unset-value/download/unset-value-1.0.0.tgz", "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", "dev": true, "requires": { @@ -20716,7 +21237,7 @@ "dependencies": { "has-value": { "version": "0.3.1", - "resolved": "https://registry.npm.taobao.org/has-value/download/has-value-0.3.1.tgz", + "resolved": "https://registry.nlark.com/has-value/download/has-value-0.3.1.tgz", "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", "dev": true, "requires": { @@ -20738,7 +21259,7 @@ }, "has-values": { "version": "0.1.4", - "resolved": "https://registry.npm.taobao.org/has-values/download/has-values-0.1.4.tgz", + "resolved": "https://registry.nlark.com/has-values/download/has-values-0.1.4.tgz", "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", "dev": true }, @@ -20752,7 +21273,7 @@ }, "upath": { "version": "1.2.0", - "resolved": "https://registry.npm.taobao.org/upath/download/upath-1.2.0.tgz?cache=0&sync_timestamp=1567457281208&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fupath%2Fdownload%2Fupath-1.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/upath/download/upath-1.2.0.tgz", "integrity": "sha1-j2bbzVWog6za5ECK+LA1pQRMGJQ=", "dev": true }, @@ -20782,7 +21303,7 @@ }, "urix": { "version": "0.1.0", - "resolved": "https://registry.npm.taobao.org/urix/download/urix-0.1.0.tgz", + "resolved": "https://registry.npmmirror.com/urix/download/urix-0.1.0.tgz", "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", "dev": true }, @@ -20806,13 +21327,13 @@ }, "url-join": { "version": "2.0.5", - "resolved": "https://registry.npm.taobao.org/url-join/download/url-join-2.0.5.tgz", + "resolved": "https://registry.nlark.com/url-join/download/url-join-2.0.5.tgz", "integrity": "sha1-WvIvGMBSoACkjXuCxenC4v7tpyg=", "dev": true }, "use": { "version": "3.1.1", - "resolved": "https://registry.npm.taobao.org/use/download/use-3.1.1.tgz", + "resolved": "https://registry.nlark.com/use/download/use-3.1.1.tgz", "integrity": "sha1-1QyMrHmhn7wg8pEfVuuXP04QBw8=", "dev": true }, @@ -20827,7 +21348,7 @@ "dependencies": { "inherits": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "resolved": "https://registry.nlark.com/inherits/download/inherits-2.0.3.tgz", "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "dev": true } @@ -20835,16 +21356,10 @@ }, "util-deprecate": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/util-deprecate/download/util-deprecate-1.0.2.tgz", + "resolved": "https://registry.nlark.com/util-deprecate/download/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "dev": true }, - "v8-compile-cache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", - "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", - "dev": true - }, "v8-to-istanbul": { "version": "9.0.1", "resolved": "https://registry.npmmirror.com/v8-to-istanbul/-/v8-to-istanbul-9.0.1.tgz", @@ -20867,7 +21382,7 @@ }, "validate-npm-package-license": { "version": "3.0.4", - "resolved": "https://registry.npm.taobao.org/validate-npm-package-license/download/validate-npm-package-license-3.0.4.tgz", + "resolved": "https://registry.nlark.com/validate-npm-package-license/download/validate-npm-package-license-3.0.4.tgz", "integrity": "sha1-/JH2uce6FchX9MssXe/uw51PQQo=", "dev": true, "requires": { @@ -20877,7 +21392,7 @@ }, "value-or-function": { "version": "3.0.0", - "resolved": "https://registry.npm.taobao.org/value-or-function/download/value-or-function-3.0.0.tgz", + "resolved": "https://registry.nlark.com/value-or-function/download/value-or-function-3.0.0.tgz", "integrity": "sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM=", "dev": true }, @@ -21022,7 +21537,7 @@ }, "w3c-hr-time": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", "dev": true, "requires": { @@ -21254,7 +21769,7 @@ }, "wrappy": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/wrappy/download/wrappy-1.0.2.tgz", + "resolved": "https://registry.nlark.com/wrappy/download/wrappy-1.0.2.tgz?cache=0&sync_timestamp=1619133505879&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fwrappy%2Fdownload%2Fwrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { @@ -21277,7 +21792,7 @@ }, "xmlchars": { "version": "2.2.0", - "resolved": "https://registry.npmmirror.com/xmlchars/-/xmlchars-2.2.0.tgz", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "dev": true }, @@ -21301,12 +21816,12 @@ }, "yallist": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/yallist/download/yallist-4.0.0.tgz", + "resolved": "https://registry.nlark.com/yallist/download/yallist-4.0.0.tgz?cache=0&sync_timestamp=1622604530774&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fyallist%2Fdownload%2Fyallist-4.0.0.tgz", "integrity": "sha1-m7knkNnA7/7GO+c1GeEaNQGaOnI=" }, "yargs": { "version": "12.0.5", - "resolved": "https://registry.npm.taobao.org/yargs/download/yargs-12.0.5.tgz?cache=0&sync_timestamp=1583129847322&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fyargs%2Fdownload%2Fyargs-12.0.5.tgz", + "resolved": "https://registry.npmmirror.com/yargs/download/yargs-12.0.5.tgz?cache=0&sync_timestamp=1632605487521&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fyargs%2Fdownload%2Fyargs-12.0.5.tgz", "integrity": "sha1-BfWZe2CWR7ZPZrgeO0sQo2jnrRM=", "dev": true, "requires": { @@ -21326,13 +21841,13 @@ "dependencies": { "ansi-regex": { "version": "3.0.0", - "resolved": "https://registry.npm.taobao.org/ansi-regex/download/ansi-regex-3.0.0.tgz?cache=0&sync_timestamp=1570188663907&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-regex%2Fdownload%2Fansi-regex-3.0.0.tgz", + "resolved": "https://registry.nlark.com/ansi-regex/download/ansi-regex-3.0.0.tgz", "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", "dev": true }, "cliui": { "version": "4.1.0", - "resolved": "https://registry.npm.taobao.org/cliui/download/cliui-4.1.0.tgz?cache=0&sync_timestamp=1573943292170&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcliui%2Fdownload%2Fcliui-4.1.0.tgz", + "resolved": "https://registry.nlark.com/cliui/download/cliui-4.1.0.tgz", "integrity": "sha1-NIQi2+gtgAswIu709qwQvy5NG0k=", "dev": true, "requires": { @@ -21352,13 +21867,13 @@ }, "invert-kv": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/invert-kv/download/invert-kv-2.0.0.tgz", + "resolved": "https://registry.nlark.com/invert-kv/download/invert-kv-2.0.0.tgz?cache=0&sync_timestamp=1630996809231&other_urls=https%3A%2F%2Fregistry.nlark.com%2Finvert-kv%2Fdownload%2Finvert-kv-2.0.0.tgz", "integrity": "sha1-c5P1r6Weyf9fZ6J2INEcIm4+7AI=", "dev": true }, "lcid": { "version": "2.0.0", - "resolved": "https://registry.npm.taobao.org/lcid/download/lcid-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/lcid/download/lcid-2.0.0.tgz", "integrity": "sha1-bvXS32DlL4LrIopMNz6NHzlyU88=", "dev": true, "requires": { @@ -21377,7 +21892,7 @@ }, "os-locale": { "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/os-locale/download/os-locale-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/os-locale/download/os-locale-3.1.0.tgz?cache=0&sync_timestamp=1633618260196&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fos-locale%2Fdownload%2Fos-locale-3.1.0.tgz", "integrity": "sha1-qAKm7hfyTBBIOrmTVxnO9O0Wvxo=", "dev": true, "requires": { @@ -21403,7 +21918,7 @@ }, "string-width": { "version": "2.1.1", - "resolved": "https://registry.npm.taobao.org/string-width/download/string-width-2.1.1.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstring-width%2Fdownload%2Fstring-width-2.1.1.tgz", + "resolved": "https://registry.npmmirror.com/string-width/download/string-width-2.1.1.tgz?cache=0&sync_timestamp=1632421309919&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fstring-width%2Fdownload%2Fstring-width-2.1.1.tgz", "integrity": "sha1-q5Pyeo3BPSjKyBXEYhQ6bZASrp4=", "dev": true, "requires": { @@ -21413,7 +21928,7 @@ }, "strip-ansi": { "version": "4.0.0", - "resolved": "https://registry.npm.taobao.org/strip-ansi/download/strip-ansi-4.0.0.tgz?cache=0&sync_timestamp=1573280518303&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstrip-ansi%2Fdownload%2Fstrip-ansi-4.0.0.tgz", + "resolved": "https://registry.npmmirror.com/strip-ansi/download/strip-ansi-4.0.0.tgz", "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { @@ -21434,7 +21949,7 @@ }, "yargs-parser": { "version": "11.1.1", - "resolved": "https://registry.npm.taobao.org/yargs-parser/download/yargs-parser-11.1.1.tgz?cache=0&sync_timestamp=1583130314354&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fyargs-parser%2Fdownload%2Fyargs-parser-11.1.1.tgz", + "resolved": "https://registry.npmmirror.com/yargs-parser/download/yargs-parser-11.1.1.tgz?cache=0&sync_timestamp=1637031045984&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fyargs-parser%2Fdownload%2Fyargs-parser-11.1.1.tgz", "integrity": "sha1-h5oIZZc7yp9rq1y987HGfsfTvPQ=", "dev": true, "requires": { @@ -21465,4 +21980,4 @@ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==" } } -} \ No newline at end of file +} diff --git a/package.json b/package.json index f85cadfaea6..2a7ceb35714 100644 --- a/package.json +++ b/package.json @@ -35,28 +35,33 @@ }, "devDependencies": { "@babel/core": "^7.13.10", + "@babel/plugin-proposal-export-default-from": "^7.17.12", "@babel/preset-env": "7.8.7", "@cocos/babel-preset-cc": "2.2.0", "@cocos/build-engine": "4.4.1", "@types/fs-extra": "^5.0.4", "@types/jest": "^24.9.1", "@types/yargs": "^12.0.14", - "@typescript-eslint/eslint-plugin": "^4.29.3", - "@typescript-eslint/parser": "^4.29.3", + "@typescript-eslint/eslint-plugin": "^6.0.0", + "@typescript-eslint/parser": "^6.0.0", "async": "^2.6.4", + "babelify": "^10.0.0", + "browserify": "^17.0.0", "chalk": "^2.4.1", "child_process": "^1.0.2", "commander": "^2.20.3", "dat.gui": "^0.7.5", "del": "^6.0.0", - "eslint": "^7.32.0", - "eslint-config-airbnb-base": "^14.2.1", - "eslint-plugin-import": "^2.24.1", + "eslint": "^8.44.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-plugin-import": "^2.27.5", "fs": "^0.0.1-security", "fs-extra": "^7.0.1", "ftp": "0.3.10", "gulp": "^4.0.2", + "gulp-rename": "^2.0.0", "gulp-sequence": "^1.0.0", + "gulp-uglify": "^3.0.2", "gulp-zip": "^5.0.2", "http-server": "^0.12.3", "jest": "^28.0.2", @@ -75,15 +80,10 @@ "typedoc-plugin-cc": "file:scripts/typedoc-plugin", "typescript": "^4.3.5", "vconsole": "^3.3.0", - "which": "^2.0.2", - "yargs": "^12.0.5", - "@babel/plugin-proposal-export-default-from": "^7.17.12", - "babelify": "^10.0.0", - "browserify": "^17.0.0", - "gulp-rename": "^2.0.0", - "gulp-uglify": "^3.0.2", "vinyl-buffer": "^1.0.1", - "vinyl-source-stream": "^2.0.0" + "vinyl-source-stream": "^2.0.0", + "which": "^2.0.2", + "yargs": "^12.0.5" }, "dependencies": { "@cocos/box2d": "1.0.1", @@ -91,4 +91,4 @@ "@cocos/ccbuild": "^1.0.0-alpha.7", "@cocos/dragonbones-js": "^1.0.1" } -} \ No newline at end of file +} From 25996141395fb4d960247745949ac244acb47cc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 14 Jul 2023 14:22:25 +0800 Subject: [PATCH 042/232] Fix eslint (#15728) --- .eslintrc.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 33743846d93..6b0db3f8be9 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -146,5 +146,5 @@ rules: # Prefer the interface style. '@typescript-eslint/consistent-type-definitions': [error, interface] '@typescript-eslint/explicit-function-return-type': [error, { - allowIIFEs: true, // IIFEs are widely used, writing their signature twice is painful + allowIIFEs: true, # IIFEs are widely used, writing their signature twice is painful }] From b324a21e85bc3ee9ec5b83941957d07dbd3dfa48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 14 Jul 2023 18:52:02 +0800 Subject: [PATCH 043/232] Upgrade CI node (#15743) --- .github/workflows/web-quality.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/web-quality.yml b/.github/workflows/web-quality.yml index 97aa573fe7e..b29601847cb 100644 --- a/.github/workflows/web-quality.yml +++ b/.github/workflows/web-quality.yml @@ -18,7 +18,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 with: - node-version: 12 + node-version: '14.19' - name: Download external run: | From 45a80113612bc5f28aeb336d4671a479e7225d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 17 Jul 2023 11:23:32 +0800 Subject: [PATCH 044/232] Bump CI Node version to 16.x (#15751) * Update web-quality.yml --- .github/workflows/web-quality.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/web-quality.yml b/.github/workflows/web-quality.yml index b29601847cb..092c2a1886d 100644 --- a/.github/workflows/web-quality.yml +++ b/.github/workflows/web-quality.yml @@ -18,14 +18,14 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 with: - node-version: '14.19' + node-version: '16.x' - name: Download external run: | EXT_VERSION=`node ./.github/workflows/get-native-external-version.js` git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos/cocos-engine-external native/external - - run: npm ci + - run: npx npm@6 ci - name: Run ESLint shell: pwsh From fb2f76d0289b870aea230e70069a47a9926b83cd Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Mon, 17 Jul 2023 11:43:55 +0800 Subject: [PATCH 045/232] Repair mac platform to open the pointerlock click mouse will appear offset problem. (#15750) --- native/cocos/platform/mac/View.mm | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/native/cocos/platform/mac/View.mm b/native/cocos/platform/mac/View.mm index 405af26fdee..6fbb047f3aa 100644 --- a/native/cocos/platform/mac/View.mm +++ b/native/cocos/platform/mac/View.mm @@ -38,6 +38,7 @@ of this software and associated engine source code (the "Software"), a limited, @implementation View { cc::MouseEvent _mouseEvent; cc::KeyboardEvent _keyboardEvent; + NSRect _contentRect; AppDelegate *_delegate; } @@ -73,6 +74,11 @@ - (instancetype)initWithFrame:(NSRect)frameRect { owner:self userInfo:nil] autorelease]; [self addTrackingArea:trackingArea]; + + NSWindow* window = self.window; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidMove:) name:NSWindowDidMoveNotification + object:window]; + [self updateContentRect]; } return self; } @@ -88,6 +94,7 @@ - (void)mtkView:(nonnull MTKView *)view drawableSizeWillChange:(CGSize)size { ev.width = static_cast(size.width); ev.height = static_cast(size.height); cc::events::WindowEvent::broadcast(ev); + [self updateContentRect]; } - (void)displayLayer:(CALayer *)layer { @@ -110,6 +117,8 @@ - (void)setFrameSize:(NSSize)newSize { ev.height = static_cast(nativeSize.height); cc::events::WindowEvent::broadcast(ev); } + + [self updateContentRect]; } - (void)viewDidChangeBackingProperties { @@ -133,6 +142,7 @@ - (void)viewDidChangeBackingProperties { ev.height = static_cast(height); cc::events::WindowEvent::broadcast(ev); } + [self updateContentRect]; } - (void)keyDown:(NSEvent *)event { @@ -272,6 +282,15 @@ - (BOOL)acceptsFirstResponder { return YES; } +- (void)updateContentRect { + NSWindow* window = self.window; + _contentRect = [window contentRectForFrameRect:[window frame]]; +} + +- (void)windowDidMove:(NSNotification *)aNotification { + [self updateContentRect]; +} + - (void)sendMouseEvent:(int)button type:(cc::MouseEvent::Type)type event:(NSEvent *)event { _mouseEvent.windowId = [self getWindowId]; _mouseEvent.type = type; @@ -311,9 +330,11 @@ - (void)sendMouseEvent:(int)button type:(cc::MouseEvent::Type)type event:(NSEven } auto mainDisplayId = CGMainDisplayID(); - float windowX = contentRect.origin.x; + + float windowX = _contentRect.origin.x; float windowY = - CGDisplayPixelsHigh(mainDisplayId) - contentRect.origin.y - contentRect.size.height; + CGDisplayPixelsHigh(mainDisplayId) - _contentRect.origin.y - _contentRect.size.height; + window->setLastMousePos(windowX + _mouseEvent.x, windowY + _mouseEvent.y); } cc::events::Mouse::broadcast(_mouseEvent); From ebfcbb62286282146cb79260471503bb92674e34 Mon Sep 17 00:00:00 2001 From: PP Date: Mon, 17 Jul 2023 14:24:48 +0800 Subject: [PATCH 046/232] [AOT] fix ts engine compile (#15745) --- cocos/physics/framework/physics-selector.ts | 2 +- cocos/physics/physx/instantiate.jsb.ts | 4 ++-- templates/openharmony/entry/src/main/ets/cocos/game.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index b7041aa82f0..4cd1131ce66 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -64,7 +64,7 @@ interface IPhysicsWrapperObject { interface IPhysicsBackend { [key: string]: IPhysicsWrapperObject; } -interface IPhysicsSelector { +export interface IPhysicsSelector { /** * @en * The id of the physics engine being used by the physics system. diff --git a/cocos/physics/physx/instantiate.jsb.ts b/cocos/physics/physx/instantiate.jsb.ts index 972a27ee0a7..4d9c0bc7f41 100644 --- a/cocos/physics/physx/instantiate.jsb.ts +++ b/cocos/physics/physx/instantiate.jsb.ts @@ -26,6 +26,6 @@ * hack for jsb, shoule be refactor in futrue */ -import { selector } from '../framework/physics-selector'; +import { selector, IPhysicsSelector } from '../framework/physics-selector'; -selector.id = 'physx'; +(selector as Mutable).id = 'physx'; diff --git a/templates/openharmony/entry/src/main/ets/cocos/game.ts b/templates/openharmony/entry/src/main/ets/cocos/game.ts index ae8937562fe..30d203a2e2b 100644 --- a/templates/openharmony/entry/src/main/ets/cocos/game.ts +++ b/templates/openharmony/entry/src/main/ets/cocos/game.ts @@ -80,7 +80,7 @@ export function launchEngine (): Promise { return systemReady().then(() => { // @ts-ignore window.oh.loadModule = loadModule; - import('./jsb-adapter/web-adapter.js').then(() => { + return import('./jsb-adapter/web-adapter.js').then(() => { return import('./src/<%= systemBundleUrl%>').then(() => { System.warmup({ importMap, From 95c93e51c13ac4a6ad02bc51bc60954fe23c9359 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Mon, 17 Jul 2023 16:11:13 +0800 Subject: [PATCH 047/232] refine: Optimize the display of the editing box on the Android platform. (#15730) * refine: Optimize the display of the editing box on the Android platform. --- .../com/cocos/lib/CocosEditBoxActivity.java | 108 +++++++----------- 1 file changed, 41 insertions(+), 67 deletions(-) diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java index 7e885b79678..388b9fdb27f 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosEditBoxActivity.java @@ -28,7 +28,6 @@ of this software and associated documentation files (the "Software"), to deal import android.app.Activity; import android.content.Context; import android.content.Intent; -import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; @@ -44,6 +43,7 @@ of this software and associated documentation files (the "Software"), to deal import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; +import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; @@ -68,8 +68,6 @@ public class CocosEditBoxActivity extends Activity { private Button mButton = null; private String mButtonTitle = null; private boolean mConfirmHold = true; - private RelativeLayout mButtonLayout = null; - private RelativeLayout.LayoutParams mButtonParams; private int mEditTextID = 1; private int mButtonLayoutID = 2; @@ -80,24 +78,15 @@ class Cocos2dxEditText extends EditText { private final String TAG = "Cocos2dxEditBox"; private boolean mIsMultiLine = false; private TextWatcher mTextWatcher = null; - private Paint mPaint; - private int mLineColor = DARK_GREEN; - private float mLineWidth = 2f; private boolean keyboardVisible = false; private int mScreenHeight; private boolean mCheckKeyboardShowNormally = false; public Cocos2dxEditText(Activity context){ super(context); - //remove focus border - this.setBackground(null); this.setTextColor(Color.BLACK); mScreenHeight = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)). getDefaultDisplay().getHeight(); - mPaint = new Paint(); - mPaint.setStrokeWidth(mLineWidth); - mPaint.setStyle(Paint.Style.FILL); - mPaint.setColor(mLineColor); mTextWatcher = new TextWatcher() { @Override @@ -119,20 +108,6 @@ public void afterTextChanged(Editable s) { registKeyboardVisible(); } - /*************************************************************************************** - Override functions. - **************************************************************************************/ - - @Override - protected void onDraw(Canvas canvas) { - // draw the underline - int padB = this.getPaddingBottom(); - canvas.drawLine(getScrollX(), this.getHeight() - padB / 2 - mLineWidth, - getScrollX() + this.getWidth(), - this.getHeight() - padB / 2 - mLineWidth, mPaint); - super.onDraw(canvas); - } - /*************************************************************************************** Public functions. **************************************************************************************/ @@ -245,7 +220,9 @@ public void onGlobalLayout() { if (!keyboardVisible) { keyboardVisible = true; } + getRootView().scrollTo(0, heightDiff); } else { + getRootView().scrollTo(0, 0); if (mCheckKeyboardShowNormally && !keyboardVisible) { Toast.makeText(CocosEditBoxActivity.this, R.string.tip_disable_safe_input_type, Toast.LENGTH_SHORT).show(); } @@ -314,52 +291,58 @@ public void onClick(View view) { **************************************************************************************/ private void addItems(RelativeLayout layout) { RelativeLayout myLayout = new RelativeLayout(this); - this.addEditText(myLayout); - this.addButton(myLayout); + myLayout.setBackgroundColor(Color.argb(255, 244, 244, 244)); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); + ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); layout.addView(myLayout, layoutParams); - //FXI ME: Is it needed? - // When touch area outside EditText and soft keyboard, then hide. -// layout.setOnTouchListener(new View.OnTouchListener() { -// @Override -// public boolean onTouch(View v, MotionEvent event) { -// Cocos2dxEditBox.this.hide(); -// return true; -// } -// -// }); + this.addEditText(myLayout); + this.addButton(myLayout); } + private int dpToPixel(int dp) { + final float scale = getResources().getDisplayMetrics().density; + int px = (int) (dp * scale + 0.5f); + return px; + } private void addEditText(RelativeLayout layout) { mEditText = new Cocos2dxEditText(this); mEditText.setVisibility(View.INVISIBLE); - mEditText.setBackgroundColor(Color.WHITE); + mEditText.setGravity(Gravity.CENTER_VERTICAL); + mEditText.setBackground(getRoundRectShape(18, Color.WHITE, Color.WHITE)); mEditText.setId(mEditTextID); + int bottomPadding = dpToPixel(4); + int leftPadding = dpToPixel(3); + mEditText.setPadding(leftPadding,bottomPadding,leftPadding,bottomPadding); + RelativeLayout.LayoutParams editParams = new RelativeLayout.LayoutParams( - ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + + editParams.addRule(RelativeLayout.CENTER_VERTICAL); editParams.addRule(RelativeLayout.LEFT_OF, mButtonLayoutID); + int bottomMargin = dpToPixel(5); + int leftMargin = dpToPixel(4); + editParams.setMargins(leftMargin, bottomMargin, bottomMargin, bottomMargin); layout.addView(mEditText, editParams); } private void addButton(RelativeLayout layout) { mButton = new Button(this); - mButtonParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); mButton.setTextColor(Color.WHITE); - mButton.setBackground(getRoundRectShape()); - mButtonLayout = new RelativeLayout(GlobalObject.getActivity()); - mButtonLayout.setBackgroundColor(Color.WHITE); - RelativeLayout.LayoutParams buttonLayoutParams = new RelativeLayout.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - buttonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); - buttonLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, mEditTextID); - buttonLayoutParams.addRule(RelativeLayout.ALIGN_TOP, mEditTextID); - mButtonLayout.addView(mButton, mButtonParams); - mButtonLayout.setId(mButtonLayoutID); - layout.addView(mButtonLayout, buttonLayoutParams); + mButton.setTextSize(16); + mButton.setBackground(getRoundRectShape(18, DARK_GREEN, DARK_GREEN_PRESS)); + int paddingLeft = dpToPixel(5); + mButton.setPadding(paddingLeft,0,paddingLeft,0); + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); + layoutParams.addRule(RelativeLayout.ALIGN_TOP, mEditTextID); + layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, mEditTextID); + layoutParams.rightMargin = dpToPixel(4); + layout.addView(mButton, layoutParams); + mButton.setGravity(Gravity.CENTER); + mButton.setId(mButtonLayoutID); mButton.setOnClickListener(new View.OnClickListener() { @Override @@ -372,18 +355,17 @@ public void onClick(View v) { }); } - private Drawable getRoundRectShape() { - int radius = 7; + private Drawable getRoundRectShape(int radius, int normalColor, int pressColor) { float[] outerRadii = new float[]{radius, radius, radius, radius, radius, radius, radius, radius}; RoundRectShape roundRectShape = new RoundRectShape(outerRadii, null, null); ShapeDrawable shapeDrawableNormal = new ShapeDrawable(); shapeDrawableNormal.setShape(roundRectShape); shapeDrawableNormal.getPaint().setStyle(Paint.Style.FILL); - shapeDrawableNormal.getPaint().setColor(DARK_GREEN); + shapeDrawableNormal.getPaint().setColor(normalColor); ShapeDrawable shapeDrawablePress = new ShapeDrawable(); shapeDrawablePress.setShape(roundRectShape); shapeDrawablePress.getPaint().setStyle(Paint.Style.FILL); - shapeDrawablePress.getPaint().setColor(DARK_GREEN_PRESS); + shapeDrawablePress.getPaint().setColor(pressColor); StateListDrawable drawable = new StateListDrawable(); drawable.addState(new int[]{android.R.attr.state_pressed}, shapeDrawablePress); drawable.addState(new int[]{}, shapeDrawableNormal); @@ -400,19 +382,11 @@ private void hide() { public void show(String defaultValue, int maxLength, boolean isMultiline, boolean confirmHold, String confirmType, String inputType) { mConfirmHold = confirmHold; mEditText.show(defaultValue, maxLength, isMultiline, confirmHold, confirmType, inputType); - int editPaddingBottom = mEditText.getPaddingBottom(); - int editPadding = mEditText.getPaddingTop(); - mEditText.setPadding(editPadding, editPadding, editPadding, editPaddingBottom); mButton.setText(mButtonTitle); if (TextUtils.isEmpty(mButtonTitle)) { - mButton.setPadding(0, 0, 0, 0); - mButtonParams.setMargins(0, 0, 0, 0); - mButtonLayout.setVisibility(View.INVISIBLE); + mButton.setVisibility(View.INVISIBLE); } else { - int buttonTextPadding = mEditText.getPaddingBottom() / 2; - mButton.setPadding(editPadding, buttonTextPadding, editPadding, buttonTextPadding); - mButtonParams.setMargins(0, buttonTextPadding, 0, 0); - mButtonLayout.setVisibility(View.VISIBLE); + mButton.setVisibility(View.VISIBLE); } this.openKeyboard(); From 7a4841404f805626778b94aee78413cca61263cf Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Mon, 17 Jul 2023 16:59:04 +0800 Subject: [PATCH 048/232] fix test (#15755) --- native/cocos/renderer/pipeline/custom/test/test.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cocos/renderer/pipeline/custom/test/test.h b/native/cocos/renderer/pipeline/custom/test/test.h index d5d2b5e0458..cb28556b1dc 100644 --- a/native/cocos/renderer/pipeline/custom/test/test.h +++ b/native/cocos/renderer/pipeline/custom/test/test.h @@ -77,7 +77,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn add_vertex(layoutGraphData, RenderPhaseTag{}, ""); auto &layout = layoutGraphData.layouts.back(); - auto &descPair = layout.descriptorSets.emplace(UpdateFrequency::PER_PASS, DescriptorSetData{renderGraph.get_allocator()}); + const auto &descPair = layout.descriptorSets.emplace(UpdateFrequency::PER_PASS, DescriptorSetData{renderGraph.get_allocator()}); auto &descData = (*descPair.first).second.descriptorSetLayoutData; for (size_t i = 0; i < layoutInfo.size(); ++i) { const ccstd::string passName = "pass" + std::to_string(i); From 979e3c9677a47b4357d6d6fe3f8908ec7f2e3ee3 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Tue, 18 Jul 2023 11:55:05 +0800 Subject: [PATCH 049/232] V3.8.1 msaa (#15584) --- .../reflection-probe-component.ts | 8 +- cocos/gfx/base/define.ts | 31 +- cocos/gfx/base/device.ts | 30 +- cocos/gfx/webgl/webgl-commands.ts | 312 ++-- cocos/gfx/webgl2/webgl2-commands.ts | 440 +++-- cocos/render-scene/core/pass.ts | 38 +- cocos/rendering/custom/executor.ts | 266 ++- cocos/rendering/custom/index.jsb.ts | 8 +- cocos/rendering/custom/index.ts | 6 +- cocos/rendering/custom/pipeline.ts | 113 +- cocos/rendering/custom/render-graph.ts | 7 +- cocos/rendering/custom/scene.ts | 34 + cocos/rendering/custom/types.ts | 3 + cocos/rendering/custom/web-pipeline.ts | 428 +++-- cocos/rendering/custom/web-scene-visitor.ts | 4 +- cocos/rendering/custom/web-scene.ts | 2 +- native/CMakeLists.txt | 6 +- native/cocos/core/assets/RenderTexture.cpp | 2 +- .../cocos/renderer/frame-graph/FrameGraph.cpp | 2 +- .../renderer/gfx-agent/CommandBufferAgent.cpp | 21 + .../renderer/gfx-agent/CommandBufferAgent.h | 1 + .../cocos/renderer/gfx-agent/DeviceAgent.cpp | 4 + native/cocos/renderer/gfx-agent/DeviceAgent.h | 2 +- .../renderer/gfx-agent/FramebufferAgent.cpp | 3 + .../renderer/gfx-base/GFXCommandBuffer.h | 1 + .../cocos/renderer/gfx-base/GFXDef-common.h | 25 +- native/cocos/renderer/gfx-base/GFXDef.cpp | 24 +- native/cocos/renderer/gfx-base/GFXDevice.cpp | 2 +- native/cocos/renderer/gfx-base/GFXDevice.h | 6 + .../renderer/gfx-base/GFXFramebuffer.cpp | 2 + .../cocos/renderer/gfx-base/GFXFramebuffer.h | 2 + .../cocos/renderer/gfx-base/GFXRenderPass.cpp | 5 +- .../cocos/renderer/gfx-base/GFXRenderPass.h | 2 + native/cocos/renderer/gfx-base/GFXTexture.cpp | 6 +- .../renderer/gfx-empty/EmptyCommandBuffer.cpp | 3 + .../renderer/gfx-empty/EmptyCommandBuffer.h | 1 + .../renderer/gfx-gles2/GLES2CommandBuffer.cpp | 4 + .../renderer/gfx-gles2/GLES2CommandBuffer.h | 1 + .../renderer/gfx-gles2/GLES2Commands.cpp | 29 +- .../cocos/renderer/gfx-gles2/GLES2Commands.h | 2 + .../cocos/renderer/gfx-gles2/GLES2Device.cpp | 8 + native/cocos/renderer/gfx-gles2/GLES2Device.h | 2 +- .../renderer/gfx-gles2/GLES2GPUObjects.h | 4 +- .../gfx-gles2/GLES2PrimaryCommandBuffer.cpp | 4 + .../gfx-gles2/GLES2PrimaryCommandBuffer.h | 1 + .../cocos/renderer/gfx-gles2/GLES2Texture.cpp | 10 +- .../renderer/gfx-gles3/GLES3CommandBuffer.cpp | 4 + .../renderer/gfx-gles3/GLES3CommandBuffer.h | 1 + .../renderer/gfx-gles3/GLES3Commands.cpp | 932 +++++----- .../cocos/renderer/gfx-gles3/GLES3Commands.h | 2 + .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 11 +- native/cocos/renderer/gfx-gles3/GLES3Device.h | 4 +- .../renderer/gfx-gles3/GLES3Framebuffer.cpp | 27 +- .../renderer/gfx-gles3/GLES3Framebuffer.h | 1 + .../renderer/gfx-gles3/GLES3GPUObjects.h | 85 +- .../gfx-gles3/GLES3PrimaryCommandBuffer.cpp | 4 + .../gfx-gles3/GLES3PrimaryCommandBuffer.h | 1 + .../renderer/gfx-gles3/GLES3RenderPass.cpp | 10 +- .../cocos/renderer/gfx-gles3/GLES3Texture.cpp | 14 +- .../renderer/gfx-metal/MTLCommandBuffer.h | 1 + .../renderer/gfx-metal/MTLCommandBuffer.mm | 34 +- native/cocos/renderer/gfx-metal/MTLDevice.h | 5 +- native/cocos/renderer/gfx-metal/MTLDevice.mm | 25 +- .../renderer/gfx-metal/MTLPipelineState.mm | 2 +- native/cocos/renderer/gfx-metal/MTLTexture.h | 2 + native/cocos/renderer/gfx-metal/MTLTexture.mm | 39 +- native/cocos/renderer/gfx-metal/MTLUtils.mm | 12 +- .../gfx-validator/CommandBufferValidator.cpp | 39 +- .../gfx-validator/CommandBufferValidator.h | 1 + .../gfx-validator/DeviceValidator.cpp | 4 + .../renderer/gfx-validator/DeviceValidator.h | 2 +- .../gfx-validator/FramebufferValidator.cpp | 11 + .../renderer/gfx-vulkan/VKCommandBuffer.cpp | 54 +- .../renderer/gfx-vulkan/VKCommandBuffer.h | 1 + .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 209 +-- native/cocos/renderer/gfx-vulkan/VKDevice.cpp | 19 + native/cocos/renderer/gfx-vulkan/VKDevice.h | 2 +- .../renderer/gfx-vulkan/VKFramebuffer.cpp | 5 + .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 17 +- .../renderer/gfx-vulkan/VKRenderPass.cpp | 10 +- .../cocos/renderer/gfx-vulkan/VKTexture.cpp | 6 +- native/cocos/renderer/gfx-vulkan/VKUtils.cpp | 24 +- native/cocos/renderer/gfx-vulkan/VKUtils.h | 3 +- .../gfx-wgpu/WGPUDescriptorSetLayout.cpp | 2 +- .../renderer/gfx-wgpu/WGPURenderPass.cpp | 8 +- .../cocos/renderer/gfx-wgpu/WGPUTexture.cpp | 4 +- native/cocos/renderer/gfx-wgpu/WGPUUtils.h | 16 +- .../renderer/pipeline/RenderPipeline.cpp | 2 +- .../pipeline/custom/FGDispatcherTypes.h | 3 + .../pipeline/custom/FrameGraphDispatcher.cpp | 251 ++- .../pipeline/custom/NativeBuiltinUtils.cpp | 557 ++++++ .../pipeline/custom/NativeBuiltinUtils.h | 86 + .../pipeline/custom/NativeDefaultScene.cpp | 50 - .../pipeline/custom/NativeExecutor.cpp | 105 +- .../pipeline/custom/NativePipeline.cpp | 396 +++-- .../pipeline/custom/NativePipelineFwd.h | 4 +- .../pipeline/custom/NativePipelineTypes.cpp | 9 +- .../pipeline/custom/NativePipelineTypes.h | 231 ++- .../pipeline/custom/NativeRenderGraph.cpp | 1494 ++++------------- .../custom/NativeRenderGraphUtils.cpp | 327 ++++ .../pipeline/custom/NativeRenderGraphUtils.h | 216 +++ .../pipeline/custom/NativeResourceGraph.cpp | 11 +- .../pipeline/custom/NativeSceneCulling.cpp | 13 +- .../renderer/pipeline/custom/NativeSetter.cpp | 153 ++ .../renderer/pipeline/custom/NativeUtils.cpp | 153 +- .../renderer/pipeline/custom/NativeUtils.h | 40 +- .../pipeline/custom/RenderCommonFwd.h | 10 + .../pipeline/custom/RenderCommonTypes.h | 27 + .../pipeline/custom/RenderGraphTypes.cpp | 15 +- .../pipeline/custom/RenderGraphTypes.h | 10 +- .../pipeline/custom/RenderInterfaceFwd.h | 5 +- .../pipeline/custom/RenderInterfaceTypes.h | 107 +- .../renderer/pipeline/custom/test/test.h | 51 +- .../renderer/pipeline/shadow/ShadowFlow.cpp | 4 +- .../src/complicated_barrier_case.cpp | 13 +- .../src/simple_closed_barrier_test.cpp | 8 +- native/tools/swig-config/gfx.i | 1 + native/tools/swig-config/render.i | 4 - 118 files changed, 4908 insertions(+), 3016 deletions(-) create mode 100644 cocos/rendering/custom/scene.ts create mode 100644 native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp create mode 100644 native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.h delete mode 100644 native/cocos/renderer/pipeline/custom/NativeDefaultScene.cpp create mode 100644 native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp create mode 100644 native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h create mode 100644 native/cocos/renderer/pipeline/custom/NativeSetter.cpp diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index ec66ef564b2..9c94934eef3 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -23,7 +23,7 @@ */ import { ccclass, executeInEditMode, menu, playOnFocus, serializable, tooltip, type, visible } from 'cc.decorator'; import { EDITOR, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; -import { CCBoolean, CCObject, Color, Enum, Vec3 } from '../../core'; +import { CCBoolean, CCObject, Color, Enum, Vec3, warn } from '../../core'; import { TextureCube } from '../../asset/assets'; import { scene } from '../../render-scene'; @@ -127,7 +127,7 @@ export class ReflectionProbe extends Component { * @zh 设置探针类型,环境反射或者平面反射 */ @type(Enum(ProbeType)) - set probeType (value: number) { + set probeType (value: ProbeType) { this.probe.probeType = value; if (value !== this._probeType) { const lastSize = this._size.clone(); @@ -151,7 +151,7 @@ export class ReflectionProbe extends Component { this._objFlags ^= CCObject.Flags.IsRotationLocked; } if (!this._sourceCamera) { - console.warn('the reflection camera is invalid, please set the reflection camera'); + warn('the reflection camera is invalid, please set the reflection camera'); } else { this.probe.switchProbeType(value, this._sourceCamera.camera); } @@ -163,7 +163,7 @@ export class ReflectionProbe extends Component { this.size = this._size; } } - get probeType (): number { + get probeType (): ProbeType { return this._probeType; } diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 769ade2ff90..53eeb4062cb 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -21,6 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* eslint-disable no-empty-function */ import { Queue } from './queue'; import { Buffer } from './buffer'; @@ -129,6 +130,7 @@ export enum Feature { SUBPASS_COLOR_INPUT, SUBPASS_DEPTH_STENCIL_INPUT, RASTERIZATION_ORDER_COHERENT, + MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL, COUNT, } @@ -405,6 +407,7 @@ export enum TextureFlagBit { GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments EXTERNAL_OES = 0x4, // External oes texture EXTERNAL_NORMAL = 0x8, // External normal texture + LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. } export enum FormatFeatureBit { @@ -417,10 +420,13 @@ export enum FormatFeatureBit { } export enum SampleCount { - ONE, // Single sample - MULTIPLE_PERFORMANCE, // Multiple samples prioritizing performance over quality - MULTIPLE_BALANCE, // Multiple samples leveraging both quality and performance - MULTIPLE_QUALITY, // Multiple samples prioritizing quality over performance + X1 = 0x01, + X2 = 0x02, + X4 = 0x04, + X8 = 0x08, + X16 = 0x10, + X32 = 0x20, + X64 = 0x40 } export enum VsyncMode { @@ -1171,7 +1177,7 @@ export class TextureInfo { public flags: TextureFlags = TextureFlagBit.NONE, public layerCount: number = 1, public levelCount: number = 1, - public samples: SampleCount = SampleCount.ONE, + public samples: SampleCount = SampleCount.X1, public depth: number = 1, public externalRes: number = 0, ) {} @@ -1513,7 +1519,7 @@ export class ColorAttachment { constructor ( public format: Format = Format.UNKNOWN, - public sampleCount: SampleCount = SampleCount.ONE, + public sampleCount: SampleCount = SampleCount.X1, public loadOp: LoadOp = LoadOp.CLEAR, public storeOp: StoreOp = StoreOp.STORE, public barrier: GeneralBarrier = null!, @@ -1534,7 +1540,7 @@ export class DepthStencilAttachment { constructor ( public format: Format = Format.UNKNOWN, - public sampleCount: SampleCount = SampleCount.ONE, + public sampleCount: SampleCount = SampleCount.X1, public depthLoadOp: LoadOp = LoadOp.CLEAR, public depthStoreOp: StoreOp = StoreOp.STORE, public stencilLoadOp: LoadOp = LoadOp.CLEAR, @@ -1608,6 +1614,7 @@ export class RenderPassInfo { constructor ( public colorAttachments: ColorAttachment[] = [], public depthStencilAttachment: DepthStencilAttachment = new DepthStencilAttachment(), + public depthStencilResolveAttachment: DepthStencilAttachment = new DepthStencilAttachment(), public subpasses: SubpassInfo[] = [], public dependencies: SubpassDependency[] = [], ) {} @@ -1615,6 +1622,7 @@ export class RenderPassInfo { public copy (info: Readonly): RenderPassInfo { deepCopy(this.colorAttachments, info.colorAttachments, ColorAttachment); this.depthStencilAttachment.copy(info.depthStencilAttachment); + this.depthStencilResolveAttachment.copy(info.depthStencilResolveAttachment); deepCopy(this.subpasses, info.subpasses, SubpassInfo); deepCopy(this.dependencies, info.dependencies, SubpassDependency); return this; @@ -1703,12 +1711,14 @@ export class FramebufferInfo { public renderPass: RenderPass = null!, public colorTextures: Texture[] = [], public depthStencilTexture: Texture | null = null, + public depthStencilResolveTexture: Texture | null = null, ) {} public copy (info: Readonly): FramebufferInfo { this.renderPass = info.renderPass; this.colorTextures = info.colorTextures.slice(); this.depthStencilTexture = info.depthStencilTexture; + this.depthStencilResolveTexture = info.depthStencilResolveTexture; return this; } } @@ -2245,8 +2255,11 @@ export function FormatSize (format: Format, width: number, height: number, depth * @param mips The target mip levels. */ export function FormatSurfaceSize ( - format: Format, width: number, height: number, - depth: number, mips: number, + format: Format, + width: number, + height: number, + depth: number, + mips: number, ): number { let size = 0; diff --git a/cocos/gfx/base/device.ts b/cocos/gfx/base/device.ts index e0272538b24..ff4f113b59f 100644 --- a/cocos/gfx/base/device.ts +++ b/cocos/gfx/base/device.ts @@ -28,7 +28,7 @@ import { ShaderInfo, InputAssemblerInfo, RenderPassInfo, FramebufferInfo, DescriptorSetLayoutInfo, PipelineLayoutInfo, QueueInfo, BufferTextureCopy, DeviceInfo, DeviceCaps, GeneralBarrierInfo, TextureBarrierInfo, BufferBarrierInfo, SwapchainInfo, BindingMappingInfo, Format, FormatFeature, TextureType, TextureUsageBit, - TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, + TextureFlagBit, Offset, Extent, SampleCount, TextureSubresLayers, TextureUsage, TextureFlags, } from './define'; import { Buffer } from './buffer'; import { CommandBuffer } from './command-buffer'; @@ -359,6 +359,17 @@ export abstract class Device { * @param format The GFX format to be queried. */ public enableAutoBarrier (en: boolean): void {} + + /** + * @en Get maximum supported sample count. + * @zh 获取最大可支持的 Samples 参数 + * @param format The GFX texture format. + * @param usage The GFX texture usage. + * @param flags The GFX texture create flags. + */ + public getMaxSampleCount (format: Format, usage: TextureUsage, flags: TextureFlags): SampleCount { + return SampleCount.X1; + } } export class DefaultResource { @@ -377,7 +388,8 @@ export class DefaultResource { TextureType.TEX2D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, )); const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1)); @@ -388,7 +400,8 @@ export class DefaultResource { TextureType.CUBE, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, 6, )); @@ -410,10 +423,12 @@ export class DefaultResource { TextureType.TEX3D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, - 1, 1, - SampleCount.ONE, + 1, + 1, + SampleCount.X1, 2, )); const copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 2), new TextureSubresLayers(0, 0, 1)); @@ -424,7 +439,8 @@ export class DefaultResource { TextureType.TEX2D_ARRAY, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, - 2, 2, + 2, + 2, TextureFlagBit.NONE, 2, )); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 9c4f73c093c..f64ea3cc4ea 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -179,7 +179,7 @@ export function GFXFormatToWebGLInternalFormat (format: Format, gl: WebGLRenderi case Format.DEPTH_STENCIL: return gl.DEPTH_STENCIL; default: { - console.error('Unsupported Format, convert to WebGL internal format failed.'); + error('Unsupported Format, convert to WebGL internal format failed.'); return gl.RGBA; } } @@ -261,7 +261,7 @@ export function GFXFormatToWebGLFormat (format: Format, gl: WebGLRenderingContex case Format.ASTC_SRGBA_12X12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; default: { - console.error('Unsupported Format, convert to WebGL format failed.'); + error('Unsupported Format, convert to WebGL format failed.'); return gl.RGBA; } } @@ -288,7 +288,7 @@ function GFXTypeToWebGLType (type: Type, gl: WebGLRenderingContext): GLenum { 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.'); + error('Unsupported GLType, convert to GL type failed.'); return Type.UNKNOWN; } } @@ -315,7 +315,7 @@ function GFXTypeToTypedArrayCtor (type: Type): Int32ArrayConstructor | Float32Ar case Type.MAT4: return Float32Array; default: { - console.error('Unsupported GLType, convert to TypedArrayConstructor failed.'); + error('Unsupported GLType, convert to TypedArrayConstructor failed.'); return Float32Array; } } @@ -342,13 +342,13 @@ function WebGLTypeToGFXType (glType: GLenum, gl: WebGLRenderingContext): Type { case gl.SAMPLER_2D: return Type.SAMPLER2D; case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; default: { - console.error('Unsupported GLType, convert to Type failed.'); + error('Unsupported GLType, convert to Type failed.'); return Type.UNKNOWN; } } } -function WebGLGetTypeSize (glType: GLenum, gl: WebGLRenderingContext): Type { +function WebGLGetTypeSize (glType: GLenum, gl: WebGLRenderingContext): number { switch (glType) { case gl.BOOL: return 4; case gl.BOOL_VEC2: return 8; @@ -369,13 +369,13 @@ function WebGLGetTypeSize (glType: GLenum, gl: WebGLRenderingContext): Type { case gl.SAMPLER_2D: return 4; case gl.SAMPLER_CUBE: return 4; default: { - console.error('Unsupported GLType, get type failed.'); + error('Unsupported GLType, get type failed.'); return 0; } } } -function WebGLGetComponentCount (glType: GLenum, gl: WebGLRenderingContext): Type { +function WebGLGetComponentCount (glType: GLenum, gl: WebGLRenderingContext): number { switch (glType) { case gl.FLOAT_MAT2: return 2; case gl.FLOAT_MAT3: return 3; @@ -665,7 +665,7 @@ export function WebGLCmdFuncCreateBuffer (device: WebGLDevice, gpuBuffer: IWebGL } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } @@ -764,13 +764,18 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL || (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } -export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer, buffer: Readonly, - offset: number, size: number): void { +export function WebGLCmdFuncUpdateBuffer ( + device: WebGLDevice, + gpuBuffer: IWebGLGPUBuffer, + buffer: Readonly, + offset: number, + size: number, +): void { if (gpuBuffer.usage & BufferUsageBit.UNIFORM) { if (ArrayBuffer.isView(buffer)) { gpuBuffer.vf32!.set(buffer as Float32Array, offset / Float32Array.BYTES_PER_ELEMENT); @@ -820,7 +825,7 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGL break; } default: { - console.error('Unsupported BufferType, update buffer failed.'); + error('Unsupported BufferType, update buffer failed.'); return; } } @@ -940,8 +945,17 @@ export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWeb 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); + 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); } @@ -967,7 +981,7 @@ export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWeb break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1084,8 +1098,17 @@ export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWeb 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); + 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); } @@ -1094,7 +1117,7 @@ export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWeb break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1178,19 +1201,19 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuff if (status !== gl.FRAMEBUFFER_COMPLETE) { switch (status) { case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); break; } case gl.FRAMEBUFFER_UNSUPPORTED: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); break; } default: @@ -1236,7 +1259,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL break; } default: { - console.error('Unsupported ShaderType.'); + error('Unsupported ShaderType.'); return; } } @@ -1248,9 +1271,9 @@ 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('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); - console.error(gl.getShaderInfoLog(gpuStage.glShader)); + error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); + error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); + error(gl.getShaderInfoLog(gpuStage.glShader)); for (let l = 0; l < gpuShader.gpuStages.length; l++) { const stage = gpuShader.gpuStages[k]; @@ -1294,13 +1317,13 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { debug(`Shader '${gpuShader.name}' compilation succeeded.`); } else { - console.error(`Failed to link shader '${gpuShader.name}'.`); - console.error(gl.getProgramInfoLog(gpuShader.glProgram)); + error(`Failed to link shader '${gpuShader.name}'.`); + error(gl.getProgramInfoLog(gpuShader.glProgram)); return; } // parse inputs - const activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); + const activeAttribCount: number = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); gpuShader.glInputs = new Array(activeAttribCount); for (let i = 0; i < activeAttribCount; ++i) { @@ -1375,9 +1398,9 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL // WebGL doesn't support Framebuffer Fetch for (let i = 0; i < gpuShader.subpassInputs.length; ++i) { const subpassInput = gpuShader.subpassInputs[i]; - gpuShader.samplerTextures.push(new UniformSamplerTexture( - subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count, - )); + gpuShader.samplerTextures.push( + new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count), + ); } // create uniform sampler textures @@ -2575,24 +2598,38 @@ export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: Readonly 0) { const offset = drawInfo.firstIndex * indexBuffer.stride; - ia.drawElementsInstancedANGLE(glPrimitive, drawInfo.indexCount, - gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount); + ia.drawElementsInstancedANGLE( + glPrimitive, + drawInfo.indexCount, + gpuInputAssembler.glIndexType, + offset, + drawInfo.instanceCount, + ); } } else if (drawInfo.vertexCount > 0) { ia.drawArraysInstancedANGLE(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount); @@ -2652,8 +2703,15 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLDevice, cmdPackage: WebGLC 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); + WebGLCmdFuncBeginRenderPass( + device, + cmd0.gpuRenderPass, + cmd0.gpuFramebuffer, + cmd0.renderArea, + cmd0.clearColors, + cmd0.clearDepth, + cmd0.clearStencil, + ); break; } /* @@ -2665,8 +2723,14 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLDevice, cmdPackage: WebGLC */ case WebGLCmd.BIND_STATES: { const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; - WebGLCmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, - cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates); + WebGLCmdFuncBindStates( + device, + cmd2.gpuPipelineState, + cmd2.gpuInputAssembler, + cmd2.gpuDescriptorSets, + cmd2.dynamicOffsets, + cmd2.dynamicStates, + ); break; } case WebGLCmd.DRAW: { @@ -2715,9 +2779,15 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( 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++]); + gl.texSubImage2D( + gl.TEXTURE_2D, + region.texSubres.mipLevel, + region.texOffset.x, + region.texOffset.y, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[n++], + ); } break; } @@ -2727,15 +2797,21 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( // 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++]); + 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.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -2746,11 +2822,13 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( } let stagingBuffer = new Uint8Array(1); -function pixelBufferPick (buffer: ArrayBufferView, +function pixelBufferPick ( + buffer: ArrayBufferView, format: Format, offset: number, stride: Extent, - extent: Extent): ArrayBufferView { + extent: Extent, +): ArrayBufferView { const blockHeight = formatAlignment(format).height; const bufferSize = FormatSize(format, extent.width, extent.height, extent.depth); @@ -2835,22 +2913,38 @@ export function WebGLCmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== (WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL as number) && !device.extensions.noCompressedTexSubImage2D) { + gl.compressedTexSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_2D, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } break; @@ -2884,29 +2978,46 @@ export function WebGLCmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== (WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL as number) + && !device.extensions.noCompressedTexSubImage2D) { + gl.compressedTexSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } } break; } default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -2945,7 +3056,7 @@ export function WebGLCmdFuncCopyTextureToBuffers ( break; } default: { - console.error('Unsupported GL texture type, copy texture to buffers failed.'); + error('Unsupported GL texture type, copy texture to buffers failed.'); } } gl.bindFramebuffer(gl.FRAMEBUFFER, null); @@ -2953,8 +3064,13 @@ export function WebGLCmdFuncCopyTextureToBuffers ( gl.deleteFramebuffer(framebuffer); } -export function WebGLCmdFuncBlitTexture (device: WebGLDevice, - srcTexture: Readonly, dstTexture: IWebGLGPUTexture, regions: Readonly, filter: Filter): void { +export function WebGLCmdFuncBlitTexture ( + device: WebGLDevice, + srcTexture: Readonly, + dstTexture: IWebGLGPUTexture, + regions: Readonly, + filter: Filter, +): void { // logic different from native, because framebuffer map is not implemented in webgl device.blitManager.draw(srcTexture, dstTexture, regions as TextureBlit[], filter); } diff --git a/cocos/gfx/webgl2/webgl2-commands.ts b/cocos/gfx/webgl2/webgl2-commands.ts index 136a6eebfd7..80f4caab35c 100644 --- a/cocos/gfx/webgl2/webgl2-commands.ts +++ b/cocos/gfx/webgl2/webgl2-commands.ts @@ -304,7 +304,7 @@ export function GFXFormatToWebGLInternalFormat (format: Format, gl: WebGL2Render case Format.ASTC_SRGBA_12X12: return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; default: { - console.error('Unsupported Format, convert to WebGL internal format failed.'); + error('Unsupported Format, convert to WebGL internal format failed.'); return gl.RGBA; } } @@ -423,7 +423,7 @@ export function GFXFormatToWebGLFormat (format: Format, gl: WebGL2RenderingConte case Format.ASTC_SRGBA_12X12: return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; default: { - console.error('Unsupported Format, convert to WebGL format failed.'); + error('Unsupported Format, convert to WebGL format failed.'); return gl.RGBA; } } @@ -458,7 +458,7 @@ function GFXTypeToWebGLType (type: Type, gl: WebGL2RenderingContext): GLenum { 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.'); + error('Unsupported GLType, convert to GL type failed.'); return Type.UNKNOWN; } } @@ -496,13 +496,13 @@ function WebGLTypeToGFXType (glType: GLenum, gl: WebGL2RenderingContext): Type { case gl.SAMPLER_3D: return Type.SAMPLER3D; case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; default: { - console.error('Unsupported GLType, convert to Type failed.'); + error('Unsupported GLType, convert to Type failed.'); return Type.UNKNOWN; } } } -function WebGLGetTypeSize (glType: GLenum, gl: WebGL2RenderingContext): Type { +function WebGLGetTypeSize (glType: GLenum, gl: WebGL2RenderingContext): number { switch (glType) { case gl.BOOL: return 4; case gl.BOOL_VEC2: return 8; @@ -543,7 +543,7 @@ function WebGLGetTypeSize (glType: GLenum, gl: WebGL2RenderingContext): Type { case gl.UNSIGNED_INT_SAMPLER_3D: return 4; case gl.UNSIGNED_INT_SAMPLER_CUBE: return 4; default: { - console.error('Unsupported GLType, get type failed.'); + error('Unsupported GLType, get type failed.'); return 0; } } @@ -855,7 +855,7 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWeb } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } @@ -962,13 +962,18 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb || (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { gpuBuffer.glTarget = gl.NONE; } else { - console.error('Unsupported BufferType, create buffer failed.'); + error('Unsupported BufferType, create buffer failed.'); gpuBuffer.glTarget = gl.NONE; } } -export function WebGL2CmdFuncUpdateBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer, buffer: Readonly, - offset: number, size: number): void { +export function WebGL2CmdFuncUpdateBuffer ( + device: WebGL2Device, + gpuBuffer: IWebGL2GPUBuffer, + buffer: Readonly, + offset: number, + size: number, +): void { if (gpuBuffer.usage & BufferUsageBit.INDIRECT) { gpuBuffer.indirects.clearDraws(); const drawInfos = (buffer as IndirectBuffer).drawInfos; @@ -1037,7 +1042,7 @@ export function WebGL2CmdFuncUpdateBuffer (device: WebGL2Device, gpuBuffer: IWeb break; } default: { - console.error('Unsupported BufferType, update buffer failed.'); + error('Unsupported BufferType, update buffer failed.'); } } } @@ -1064,7 +1069,7 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW errorID(9100, maxSize, device.capabilities.maxTextureSize); } - if (gpuTexture.samples === SampleCount.ONE) { + if (gpuTexture.samples === SampleCount.X1) { gpuTexture.glTexture = gl.createTexture(); if (gpuTexture.size > 0) { const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; @@ -1094,8 +1099,13 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; } - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, - gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); + gl.renderbufferStorageMultisample( + gl.RENDERBUFFER, + gpuTexture.samples, + gpuTexture.glInternalFmt, + gpuTexture.width, + gpuTexture.height, + ); } } break; @@ -1199,7 +1209,7 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1254,7 +1264,7 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW errorID(9100, maxSize, device.capabilities.maxTextureSize); } - if (gpuTexture.samples === SampleCount.ONE) { + if (gpuTexture.samples === SampleCount.X1) { const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { @@ -1281,8 +1291,13 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; } - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, - gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); + gl.renderbufferStorageMultisample( + gl.RENDERBUFFER, + gpuTexture.samples, + gpuTexture.glInternalFmt, + gpuTexture.width, + gpuTexture.height, + ); } break; } @@ -1387,7 +1402,7 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW break; } default: { - console.error('Unsupported TextureType, create texture failed.'); + error('Unsupported TextureType, create texture failed.'); gpuTexture.type = TextureType.TEX2D; gpuTexture.glTarget = gl.TEXTURE_2D; } @@ -1521,19 +1536,19 @@ export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebu if (status !== gl.FRAMEBUFFER_COMPLETE) { switch (status) { case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); break; } case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); break; } case gl.FRAMEBUFFER_UNSUPPORTED: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); + error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); break; } default: @@ -1579,7 +1594,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb break; } default: { - console.error('Unsupported ShaderType.'); + error('Unsupported ShaderType.'); return; } } @@ -1591,9 +1606,9 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb gl.compileShader(gpuStage.glShader); if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { - console.error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); - console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); - console.error(gl.getShaderInfoLog(gpuStage.glShader)); + error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); + error('Shader source dump:', gpuStage.source.replace(/^|\n/g, (): string => `\n${lineNumber++} `)); + error(gl.getShaderInfoLog(gpuStage.glShader)); for (let l = 0; l < gpuShader.gpuStages.length; l++) { const stage = gpuShader.gpuStages[k]; @@ -1637,13 +1652,13 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { debug(`Shader '${gpuShader.name}' compilation succeeded.`); } else { - console.error(`Failed to link shader '${gpuShader.name}'.`); - console.error(gl.getProgramInfoLog(gpuShader.glProgram)); + error(`Failed to link shader '${gpuShader.name}'.`); + error(gl.getProgramInfoLog(gpuShader.glProgram)); return; } // parse inputs - const activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); + const activeAttribCount: number = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); gpuShader.glInputs = new Array(activeAttribCount); for (let i = 0; i < activeAttribCount; ++i) { @@ -1675,7 +1690,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb } // create uniform blocks - const activeBlockCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORM_BLOCKS); + const activeBlockCount: number = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORM_BLOCKS); let blockName: string; let blockIdx: number; let blockSize: number; @@ -1728,9 +1743,9 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb // WebGL doesn't support Framebuffer Fetch for (let i = 0; i < gpuShader.subpassInputs.length; ++i) { const subpassInput = gpuShader.subpassInputs[i]; - gpuShader.samplerTextures.push(new UniformSamplerTexture( - subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count, - )); + gpuShader.samplerTextures.push( + new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type.SAMPLER2D, subpassInput.count), + ); } // create uniform sampler textures @@ -2372,8 +2387,13 @@ export function WebGL2CmdFuncBindStates ( 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); + gl.bindBufferRange( + gl.UNIFORM_BUFFER, + glBlock.glBinding, + gpuDescriptor.gpuBuffer.glBuffer, + offset, + gpuDescriptor.gpuBuffer.size, + ); } else { gl.bindBufferBase(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer); } @@ -2637,24 +2657,38 @@ export function WebGL2CmdFuncDraw (device: WebGL2Device, drawInfo: Readonly 0) { const offset = drawInfo.firstIndex * indexBuffer.stride; - gl.drawElementsInstanced(glPrimitive, drawInfo.indexCount, - gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount); + gl.drawElementsInstanced( + glPrimitive, + drawInfo.indexCount, + gpuInputAssembler.glIndexType, + offset, + drawInfo.instanceCount, + ); } } else if (drawInfo.vertexCount > 0) { gl.drawArraysInstanced(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount); @@ -2714,8 +2762,15 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebG 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); + WebGL2CmdFuncBeginRenderPass( + device, + cmd0.gpuRenderPass, + cmd0.gpuFramebuffer, + cmd0.renderArea, + cmd0.clearColors, + cmd0.clearDepth, + cmd0.clearStencil, + ); break; } /* @@ -2727,8 +2782,14 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebG */ case WebGL2Cmd.BIND_STATES: { const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; - WebGL2CmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, - cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates); + WebGL2CmdFuncBindStates( + device, + cmd2.gpuPipelineState, + cmd2.gpuInputAssembler, + cmd2.gpuDescriptorSets, + cmd2.dynamicOffsets, + cmd2.dynamicStates, + ); break; } case WebGL2Cmd.DRAW: { @@ -2789,14 +2850,29 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { if (toUseTexImage2D(texImages, regions)) { - gl.texImage2D(gl.TEXTURE_2D, regions[0].texSubres.mipLevel, gpuTexture.glInternalFmt, regions[0].texExtent.width, - regions[0].texExtent.height, 0, gpuTexture.glFormat, gpuTexture.glType, texImages[0]); + gl.texImage2D( + gl.TEXTURE_2D, + regions[0].texSubres.mipLevel, + gpuTexture.glInternalFmt, + regions[0].texExtent.width, + regions[0].texExtent.height, + 0, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[0], + ); } else { 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++]); + gl.texSubImage2D( + gl.TEXTURE_2D, + region.texSubres.mipLevel, + region.texOffset.x, + region.texOffset.y, + gpuTexture.glFormat, + gpuTexture.glType, + texImages[n++], + ); } } break; @@ -2806,15 +2882,21 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( 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++]); + 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.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -2824,11 +2906,13 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( } let stagingBuffer = new Uint8Array(1); -function pixelBufferPick (buffer: ArrayBufferView, +function pixelBufferPick ( + buffer: ArrayBufferView, format: Format, offset: number, stride: Extent, - extent: Extent): ArrayBufferView { + extent: Extent, +): ArrayBufferView { const blockHeight = formatAlignment(format).height; const bufferSize = FormatSize(format, extent.width, extent.height, extent.depth); @@ -2913,22 +2997,38 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage2D( + gl.TEXTURE_2D, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_2D, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } break; @@ -2965,22 +3065,43 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, + gl.texSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + gl.compressedTexImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, extent.depth, 0, - pixels); + destWidth, + destHeight, + extent.depth, + 0, + pixels, + ); } } } @@ -3015,22 +3136,43 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, - offset.x, offset.y, offset.z, - destWidth, destHeight, extent.depth, + gl.texSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, + offset.x, + offset.y, + offset.z, + destWidth, + destHeight, + extent.depth, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + gl.compressedTexImage3D( + gl.TEXTURE_2D_ARRAY, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, extent.depth, 0, - pixels); + destWidth, + destHeight, + extent.depth, + 0, + pixels, + ); } } break; @@ -3064,29 +3206,45 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, - gpuTexture.glFormat, gpuTexture.glType, - pixels); - } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, - offset.x, offset.y, - destWidth, destHeight, + gl.texSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, gpuTexture.glFormat, - pixels); + gpuTexture.glType, + pixels, + ); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) { + gl.compressedTexSubImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, + offset.x, + offset.y, + destWidth, + destHeight, + gpuTexture.glFormat, + pixels, + ); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + gl.compressedTexImage2D( + gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, + mipLevel, gpuTexture.glInternalFmt, - destWidth, destHeight, 0, - pixels); + destWidth, + destHeight, + 0, + pixels, + ); } } } break; } default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); + error('Unsupported GL texture type, copy buffer to texture failed.'); } } @@ -3125,7 +3283,7 @@ export function WebGL2CmdFuncCopyTextureToBuffers ( break; } default: { - console.error('Unsupported GL texture type, copy texture to buffers failed.'); + error('Unsupported GL texture type, copy texture to buffers failed.'); } } gl.bindFramebuffer(gl.FRAMEBUFFER, null); @@ -3168,9 +3326,16 @@ export function WebGL2CmdFuncBlitFramebuffer ( const glFilter = (filter === Filter.LINEAR || filter === Filter.ANISOTROPIC) ? gl.LINEAR : gl.NEAREST; 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, + 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, ); if (rebindFBO) { @@ -3205,7 +3370,7 @@ export function WebGL2CmdFuncBlitTexture ( const blitInfo = (formatInfo: FormatInfo): { mask: number; attachment: number; } => { let mask = 0; - let attachment = gl.COLOR_ATTACHMENT0; + let attachment: number = gl.COLOR_ATTACHMENT0; if (formatInfo.hasStencil) { attachment = gl.DEPTH_STENCIL_ATTACHMENT; @@ -3269,9 +3434,16 @@ export function WebGL2CmdFuncBlitTexture ( } gl.blitFramebuffer( - region.srcOffset.x, region.srcOffset.y, region.srcOffset.x + region.srcExtent.width, region.srcOffset.y + region.srcExtent.height, - region.dstOffset.x, region.dstOffset.y, region.dstOffset.x + region.dstExtent.width, region.dstOffset.y + region.dstExtent.height, - srcMask, glFilter, + region.srcOffset.x, + region.srcOffset.y, + region.srcOffset.x + region.srcExtent.width, + region.srcOffset.y + region.srcExtent.height, + region.dstOffset.x, + region.dstOffset.y, + region.dstOffset.x + region.dstExtent.width, + region.dstOffset.y + region.dstExtent.height, + srcMask, + glFilter, ); } diff --git a/cocos/render-scene/core/pass.ts b/cocos/render-scene/core/pass.ts index a1a7c93ca72..4345d8c5003 100644 --- a/cocos/render-scene/core/pass.ts +++ b/cocos/render-scene/core/pass.ts @@ -28,13 +28,15 @@ import { TextureBase } from '../../asset/assets/texture-base'; import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; import { getPhaseID } from '../../rendering/pass-phase'; import { murmurhash2_32_gc, errorID, assertID, cclegacy, warnID } from '../../core'; -import { BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color, +import { + BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color, BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet, DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, Shader, PipelineLayout, deviceManager, UniformBlock, } from '../../gfx'; import { EffectAsset } from '../../asset/assets/effect-asset'; import { IProgramInfo, programLib } from './program-lib'; -import { MacroRecord, MaterialProperty, customizeType, getBindingFromHandle, getDefaultFromType, getStringFromType, +import { + MacroRecord, MaterialProperty, customizeType, getBindingFromHandle, getDefaultFromType, getStringFromType, getOffsetFromHandle, getTypeFromHandle, type2reader, type2writer, getCountFromHandle, type2validator, } from './pass-utils'; import { RenderPassStage, RenderPriority } from '../../rendering/define'; @@ -182,7 +184,7 @@ export class Pass { protected _shaderInfo: IProgramInfo = null!; protected _defines: MacroRecord = {}; protected _properties: Record = {}; - protected _shader: Shader | null = null + protected _shader: Shader | null = null; protected _bs: BlendState = new BlendState(); protected _dss: DepthStencilState = new DepthStencilState(); protected _rs: RasterizerState = new RasterizerState(); @@ -190,6 +192,7 @@ export class Pass { protected _stage: RenderPassStage = RenderPassStage.DEFAULT; protected _phase = getPhaseID('default'); protected _passID = 0xFFFFFFFF; + protected _subpassID = 0xFFFFFFFF; protected _phaseID = 0xFFFFFFFF; protected _primitive: PrimitiveMode = PrimitiveMode.TRIANGLE_LIST; protected _batchingScheme: BatchingSchemes = BatchingSchemes.NONE; @@ -488,7 +491,10 @@ export class Pass { if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { const programLib = cclegacy.rendering.programLib as ProgramLibrary; const program = programLib.getProgramVariant( - this._device, this._phaseID, this._programName, this._defines, + this._device, + this._phaseID, + this._programName, + this._defines, ); if (!program) { warnID(12103, this._programName); @@ -576,11 +582,17 @@ export class Pass { const r = cclegacy.rendering; if (typeof info.phase === 'number') { this._passID = (info as Pass)._passID; + this._subpassID = (info as Pass)._subpassID; this._phaseID = (info as Pass)._phaseID; } else { this._passID = r.getPassID(info.pass); if (this._passID !== r.INVALID_ID) { - this._phaseID = r.getPhaseID(this._passID, info.phase); + if (info.subpass) { + this._subpassID = r.getSubpassID(this._passID, info.subpass); + this._phaseID = r.getPhaseID(this._subpassID, info.phase); + } else { + this._phaseID = r.getPhaseID(this._passID, info.phase); + } } } if (this._passID === r.INVALID_ID) { @@ -683,8 +695,11 @@ export class Pass { const bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo); // non-builtin UBO data pools, note that the effect compiler // guarantees these bindings to be consecutive, starting from 0 and non-array-typed - this._blocks[binding] = new Float32Array(this._rootBlock!, _bufferViewInfo.offset, - size / Float32Array.BYTES_PER_ELEMENT); + this._blocks[binding] = new Float32Array( + this._rootBlock!, + _bufferViewInfo.offset, + size / Float32Array.BYTES_PER_ELEMENT, + ); this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length); this._descriptorSet.bindBuffer(binding, bufferView); } @@ -728,8 +743,11 @@ export class Pass { const bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo); // non-builtin UBO data pools, note that the effect compiler // guarantees these bindings to be consecutive, starting from 0 and non-array-typed - this._blocks[binding] = new Float32Array(this._rootBlock!, _bufferViewInfo.offset, - size / Float32Array.BYTES_PER_ELEMENT); + this._blocks[binding] = new Float32Array( + this._rootBlock!, + _bufferViewInfo.offset, + size / Float32Array.BYTES_PER_ELEMENT, + ); this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length); this._descriptorSet.bindBuffer(binding, bufferView); } @@ -778,7 +796,7 @@ export class Pass { this._blocks = target._blocks; this._blocksInt = target._blocksInt; - this._dynamics = target._dynamics; + this._dynamics = target._dynamics; this._shader = target._shader; diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 574ffff1ba9..b5492e7a13c 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -20,7 +20,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ + ****************************************************************************/ /** * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= @@ -32,9 +32,43 @@ import { getPhaseID, InstancedBuffer, PipelineStateManager } from '..'; import { assert, cclegacy, RecyclePool } from '../../core'; import intersect from '../../core/geometry/intersect'; import { Sphere } from '../../core/geometry/sphere'; -import { AccessFlagBit, Attribute, Buffer, BufferInfo, BufferUsageBit, BufferViewInfo, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, DescriptorSet, DescriptorSetInfo, Device, deviceManager, Format, Framebuffer, - FramebufferInfo, GeneralBarrierInfo, InputAssemblerInfo, LoadOp, MemoryUsageBit, PipelineState, Rect, RenderPass, RenderPassInfo, Sampler, SamplerInfo, StoreOp, SurfaceTransform, Swapchain, Texture, TextureInfo, - TextureType, TextureUsageBit, Viewport } from '../../gfx'; +import { + AccessFlagBit, + Attribute, + Buffer, + BufferInfo, + BufferUsageBit, + BufferViewInfo, + Color, + ColorAttachment, + CommandBuffer, + DepthStencilAttachment, + DescriptorSet, + DescriptorSetInfo, + Device, + deviceManager, + Format, + Framebuffer, + FramebufferInfo, + GeneralBarrierInfo, + InputAssembler, + InputAssemblerInfo, + LoadOp, + MemoryUsageBit, + PipelineState, + Rect, + RenderPass, + RenderPassInfo, + Shader, + StoreOp, + SurfaceTransform, + Swapchain, + Texture, + TextureInfo, + TextureType, + TextureUsageBit, + Viewport, +} from '../../gfx'; import { legacyCC } from '../../core/global-exports'; import { Vec3 } from '../../core/math/vec3'; import { Vec4 } from '../../core/math/vec4'; @@ -46,11 +80,47 @@ import { IRenderPass, isEnableEffect, SetIndex, UBODeferredLight, UBOForwardLigh import { PipelineSceneData } from '../pipeline-scene-data'; import { PipelineInputAssemblerData } from '../render-pipeline'; import { DescriptorSetData, LayoutGraphData, PipelineLayoutData, RenderPhaseData, RenderStageData } from './layout-graph'; -import { BasicPipeline, SceneVisitor } from './pipeline'; -import { Blit, ClearView, ComputePass, ComputeSubpass, CopyPass, Dispatch, FormatView, ManagedBuffer, ManagedResource, ManagedTexture, MovePass, - RasterPass, RasterSubpass, RaytracePass, RenderData, RenderGraph, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResolvePass, ResourceDesc, - ResourceGraph, ResourceGraphVisitor, ResourceTraits, SceneData, SubresourceView, ComputeView, RasterView } from './render-graph'; -import { AttachmentType, QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; +import { BasicPipeline } from './pipeline'; +import { SceneVisitor } from './scene'; +import { + Blit, + ClearView, + ComputePass, + ComputeSubpass, + ComputeView, + CopyPass, + Dispatch, + FormatView, + ManagedBuffer, + ManagedResource, + ManagedTexture, + MovePass, + RasterPass, + RasterSubpass, + RasterView, + RaytracePass, + RenderData, + RenderGraph, + RenderGraphVisitor, + RenderQueue, + RenderSwapchain, + ResolvePass, + ResourceDesc, + ResourceGraph, + ResourceGraphVisitor, + ResourceTraits, + SceneData, + SubresourceView, +} from './render-graph'; +import { + AttachmentType, + QueueHint, + ResourceDimension, + ResourceFlags, + ResourceResidency, + SceneFlags, + UpdateFrequency, +} from './types'; import { PipelineUBO } from '../pipeline-ubo'; import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; @@ -59,7 +129,14 @@ import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue' import { PlanarShadowQueue } from '../planar-shadow-queue'; import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph'; import { VectorGraphColorMap } from './effect'; -import { getDescBindingFromName, getDescriptorSetDataFromLayout, getDescriptorSetDataFromLayoutId, getRenderArea, mergeSrcToTargetDesc, updateGlobalDescBinding } from './define'; +import { + getDescBindingFromName, + getDescriptorSetDataFromLayout, + getDescriptorSetDataFromLayoutId, + getRenderArea, + mergeSrcToTargetDesc, + updateGlobalDescBinding, +} from './define'; import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; import { Texture2D } from '../../asset/assets/texture-2d'; @@ -177,6 +254,8 @@ class DeviceTexture extends DeviceResource { if (info.flags & ResourceFlags.INPUT_ATTACHMENT) usageFlags |= TextureUsageBit.INPUT_ATTACHMENT; if (info.flags & ResourceFlags.SAMPLED) usageFlags |= TextureUsageBit.SAMPLED; if (info.flags & ResourceFlags.STORAGE) usageFlags |= TextureUsageBit.STORAGE; + if (info.flags & ResourceFlags.TRANSFER_SRC) usageFlags |= TextureUsageBit.TRANSFER_SRC; + if (info.flags & ResourceFlags.TRANSFER_DST) usageFlags |= TextureUsageBit.TRANSFER_DST; this._texture = context.device.createTexture(new TextureInfo( type, @@ -405,7 +484,7 @@ class DeviceRenderQueue { get renderPhase (): RenderPhaseData | null { return this._renderPhase; } get viewport (): Viewport | null { return this._viewport; } get scissor (): Rect | null { return this._scissor; } - private _sceneVisitor; + private _sceneVisitor!: WebSceneVisitor; private _blitDesc: BlitDesc | null = null; private _queueId = -1; set queueId (val) { this._queueId = val; } @@ -428,8 +507,10 @@ class DeviceRenderQueue { this._devicePass = devicePass; if (isEnableEffect()) this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id) || 'default'); if (!this._sceneVisitor) { - this._sceneVisitor = new WebSceneVisitor(context.commandBuffer, - context.pipeline.pipelineSceneData); + this._sceneVisitor = new WebSceneVisitor( + context.commandBuffer, + context.pipeline.pipelineSceneData, + ); } } createBlitDesc (blit: Blit): void { @@ -535,7 +616,7 @@ class RenderPassLayoutInfo { protected _layout: PipelineLayoutData; protected _inputName: string; protected _descriptorSet: DescriptorSet | null = null; - constructor (layoutId, input: [string, ComputeView[]]) { + constructor (layoutId: number, input: [string, ComputeView[]]) { this._inputName = input[0]; this._layoutID = layoutId; const lg = context.layoutGraph; @@ -754,9 +835,11 @@ class DeviceRenderPass { // )); // } this._renderPass = device.createRenderPass(new RenderPassInfo(colors, depthStencilAttachment)); - this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo(this._renderPass, + this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo( + this._renderPass, swapchain ? [swapchain.colorTexture] : colorTexs, - swapchain ? swapchain.depthStencilTexture : depthTex)); + swapchain ? swapchain.depthStencilTexture : depthTex, + )); } get layoutName (): string { return this._layoutName; } get passID (): number { return this._passID; } @@ -821,8 +904,13 @@ class DeviceRenderPass { const pass = submodel.passes[0]; const ia = submodel.inputAssembler; const device = context.device; - const pso = PipelineStateManager.getOrCreatePipelineState(device, pass, - submodel.shaders[0], renderPass, ia); + const pso = PipelineStateManager.getOrCreatePipelineState( + device, + pass, + submodel.shaders[0], + renderPass, + ia, + ); const descData = getDescriptorSetDataFromLayoutId(pass.passID)!; mergeSrcToTargetDesc(descData.descriptorSet, context.pipeline.descriptorSet, true); profilerViewport.width = rect.width; @@ -851,10 +939,18 @@ class DeviceRenderPass { renderPassArea.width = tex.width; renderPassArea.height = tex.height; } - cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, renderPassArea, - this.clearColor, this.clearDepth, this.clearStencil); - cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, - context.pipeline.descriptorSet); + cmdBuff.beginRenderPass( + this.renderPass, + this.framebuffer, + renderPassArea, + this.clearColor, + this.clearDepth, + this.clearStencil, + ); + cmdBuff.bindDescriptorSet( + SetIndex.GLOBAL, + context.pipeline.descriptorSet, + ); for (const queue of this._deviceQueues) { queue.record(); } @@ -1014,7 +1110,7 @@ class GraphScene { } this.blit = null; } - init (scene, blit, sceneID): void { + init (scene: SceneData | null, blit: Blit | null, sceneID): void { this._copyScene(scene); this._copyBlit(blit); this.sceneID = sceneID; @@ -1027,8 +1123,12 @@ class DevicePreSceneTask extends WebSceneTask { protected _graphScene: GraphScene; private _cmdBuff: CommandBuffer; constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { - super(context.pipelineSceneData, context.ubo, - graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); + super( + context.pipelineSceneData, + context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, + visitor, + ); this._currentQueue = queue; this._graphScene = graphScene; this._renderPass = queue.devicePass.renderPass; @@ -1096,6 +1196,7 @@ class DevicePreSceneTask extends WebSceneTask { const probes = cclegacy.internal.reflectionProbeManager.getProbes(); for (let i = 0; i < probes.length; i++) { if (probes[i].hasFrameBuffer(this._currentQueue.devicePass.framebuffer)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._submitInfo.reflectionProbe.gatherRenderObjects(probes[i], this.camera, this._cmdBuff); break; } @@ -1162,7 +1263,7 @@ class DevicePreSceneTask extends WebSceneTask { protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false): void { const subModel = ro.model.subModels[subModelIdx]; - const pass = subModel.passes[passIdx]; + const pass: Pass = subModel.passes[passIdx]; const shader = subModel.shaders[passIdx]; const currTransparent = pass.blendState.targets[0].blend; const devicePass = this._currentQueue.devicePass; @@ -1172,7 +1273,7 @@ class DevicePreSceneTask extends WebSceneTask { if (currTransparent !== isTransparent || !(pass.phaseID & (isTransparent ? phase : this._currentQueue.phaseID))) { return; } - const hash = (0 << 30) | pass.priority << 16 | subModel.priority << 8 | passIdx; + const hash = (0 << 30) | pass.priority as number << 16 | subModel.priority as number << 8 | passIdx; const rp = context.pools.addPassInfo(); rp.priority = ro.model.priority; rp.hash = hash; @@ -1233,8 +1334,12 @@ class DeviceSceneTask extends WebSceneTask { protected _renderPass: RenderPass; protected _graphScene: GraphScene; constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { - super(context.pipelineSceneData, context.ubo, - graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); + super( + context.pipelineSceneData, + context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, + visitor, + ); this._currentQueue = queue; this._renderPass = this._currentQueue.devicePass.renderPass; this._graphScene = graphScene; @@ -1258,14 +1363,20 @@ class DeviceSceneTask extends WebSceneTask { : currSubmitInfo.opaqueList; for (let i = 0; i < renderList.length; ++i) { const { subModel, passIdx } = renderList[i]; - const { inputAssembler } = subModel; - const pass = subModel.passes[passIdx]; - const shader = subModel.shaders[passIdx]; - const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, - pass, shader, this._renderPass, inputAssembler); + const inputAssembler: InputAssembler = subModel.inputAssembler; + const pass: Pass = subModel.passes[passIdx]; + const shader: Shader = subModel.shaders[passIdx]; + const descriptorSet: DescriptorSet = subModel.descriptorSet; + const pso = PipelineStateManager.getOrCreatePipelineState( + deviceManager.gfxDevice, + pass, + shader, + this._renderPass, + inputAssembler, + ); this.visitor.bindPipelineState(pso); this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); - this.visitor.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet); + this.visitor.bindDescriptorSet(SetIndex.LOCAL, descriptorSet); this.visitor.bindInputAssembler(inputAssembler); this.visitor.draw(inputAssembler); } @@ -1289,13 +1400,18 @@ class DeviceSceneTask extends WebSceneTask { const instance = instances[b]; if (!instance.count) { continue; } const shader = instance.shader!; - const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, - shader, this._renderPass, instance.ia); + const pso = PipelineStateManager.getOrCreatePipelineState( + deviceManager.gfxDevice, + pass, + shader, + this._renderPass, + instance.ia, + ); if (lastPSO !== pso) { this.visitor.bindPipelineState(pso); lastPSO = pso; } - const ia: any = instance.ia; + const ia: InputAssembler = instance.ia; this.visitor.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets); this.visitor.bindInputAssembler(ia); this.visitor.draw(ia); @@ -1320,7 +1436,7 @@ class DeviceSceneTask extends WebSceneTask { const pass = batch.passes[j]; if (((isEnableEffect()) ? pass.phaseID : pass.phase) !== this._currentQueue.phaseID) continue; const shader = batch.shaders[j]; - const inputAssembler: any = batch.inputAssembler!; + const inputAssembler: InputAssembler = batch.inputAssembler!; const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, shader, this._renderPass, inputAssembler); this.visitor.bindPipelineState(pso); this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); @@ -1337,14 +1453,22 @@ class DeviceSceneTask extends WebSceneTask { protected _recordShadowMap (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.shadowMap.get(this.graphScene.sceneID)!.recordCommandBuffer(context.device, - this._renderPass, context.commandBuffer); + currSubmitInfo.shadowMap.get(this.graphScene.sceneID)!.recordCommandBuffer( + context.device, + this._renderPass, + + context.commandBuffer, + ); } protected _recordReflectionProbe (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.reflectionProbe?.recordCommandBuffer(context.device, - this._renderPass, context.commandBuffer); + currSubmitInfo.reflectionProbe?.recordCommandBuffer( + context.device, + this._renderPass, + + context.commandBuffer, + ); } private _clearExtBlitDesc (desc, extResId: number[]): void { @@ -1371,12 +1495,17 @@ class DeviceSceneTask extends WebSceneTask { pass.update(); const shader = pass.getShaderVariant(); const devicePass = this._currentQueue.devicePass; - const screenIa: any = this._currentQueue.blitDesc!.screenQuad!.quadIA; + const screenIa: InputAssembler = this._currentQueue.blitDesc!.screenQuad!.quadIA!; const globalDesc = context.pipeline.descriptorSet; - let pso; + let pso: PipelineState | null = null; if (pass !== null && shader !== null && screenIa !== null) { - pso = PipelineStateManager.getOrCreatePipelineState(context.device, pass, shader, - devicePass.renderPass, screenIa); + pso = PipelineStateManager.getOrCreatePipelineState( + context.device, + pass, + shader, + devicePass.renderPass, + screenIa, + ); } if (pso) { this.visitor.bindPipelineState(pso); @@ -1397,18 +1526,22 @@ class DeviceSceneTask extends WebSceneTask { const devicePass = this._currentQueue.devicePass; const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.additiveLight?.recordCommandBuffer(context.device, + currSubmitInfo.additiveLight?.recordCommandBuffer( + context.device, this._renderPass, - context.commandBuffer); + context.commandBuffer, + ); } private _recordPlanarShadows (): void { const devicePass = this._currentQueue.devicePass; const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.planarQueue?.recordCommandBuffer(context.device, + currSubmitInfo.planarQueue?.recordCommandBuffer( + context.device, this._renderPass, - context.commandBuffer); + context.commandBuffer, + ); } protected _updateGlobal (data: RenderData): void { const devicePass = this._currentQueue.devicePass; @@ -1495,8 +1628,10 @@ class DeviceSceneTask extends WebSceneTask { if (graphSceneData.flags & SceneFlags.DEFAULT_LIGHTING) { this._recordAdditiveLights(); } - this.visitor.bindDescriptorSet(SetIndex.GLOBAL, - context.pipeline.descriptorSet); + this.visitor.bindDescriptorSet( + SetIndex.GLOBAL, + context.pipeline.descriptorSet, + ); if (graphSceneData.flags & SceneFlags.PLANAR_SHADOW) { this._recordPlanarShadows(); } @@ -1504,8 +1639,12 @@ class DeviceSceneTask extends WebSceneTask { this._recordTransparentList(); } if (graphSceneData.flags & SceneFlags.GEOMETRY) { - this.camera!.geometryRenderer?.render(devicePass.renderPass, - context.commandBuffer, context.pipeline.pipelineSceneData); + this.camera!.geometryRenderer?.render( + devicePass.renderPass, + context.commandBuffer, + + context.pipeline.pipelineSceneData, + ); } if (graphSceneData.flags & SceneFlags.UI) { this._recordUI(); @@ -1692,7 +1831,7 @@ class BlitInfo { const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; const vbSize = vbStride * 4; const device = cclegacy.director.root.device; - const quadVB = device.createBuffer(new BufferInfo( + const quadVB: Buffer = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE | MemoryUsageBit.HOST, vbSize, @@ -1707,7 +1846,7 @@ class BlitInfo { const ibStride = Uint8Array.BYTES_PER_ELEMENT; const ibSize = ibStride * 6; - const quadIB = device.createBuffer(new BufferInfo( + const quadIB: Buffer = device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, @@ -1744,14 +1883,16 @@ class BlitInfo { } class ExecutorContext { - constructor (pipeline: BasicPipeline, + constructor ( + pipeline: BasicPipeline, ubo: PipelineUBO, device: Device, resourceGraph: ResourceGraph, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, width: number, - height: number) { + height: number, + ) { this.pipeline = pipeline; this.device = device; this.commandBuffer = device.commandBuffer; @@ -1804,12 +1945,15 @@ class ExecutorContext { } export class Executor { - constructor (pipeline: BasicPipeline, + constructor ( + pipeline: BasicPipeline, ubo: PipelineUBO, device: Device, resourceGraph: ResourceGraph, layoutGraph: LayoutGraphData, - width: number, height: number) { + width: number, + height: number, + ) { context = this._context = new ExecutorContext( pipeline, ubo, diff --git a/cocos/rendering/custom/index.jsb.ts b/cocos/rendering/custom/index.jsb.ts index ce9a0e531f6..7aa8b0d0a23 100644 --- a/cocos/rendering/custom/index.jsb.ts +++ b/cocos/rendering/custom/index.jsb.ts @@ -25,7 +25,7 @@ declare const render: any; import { Pipeline, PipelineBuilder, RenderingModule } from './pipeline'; -import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; +import { DeferredPipelineBuilder } from './builtin-pipelines'; import { CustomPipelineBuilder, TestPipelineBuilder } from './custom-pipeline'; import { Device } from '../../gfx'; import { PostProcessBuilder } from '../post-process/post-process-builder'; @@ -92,11 +92,15 @@ export function getPassID (name: string | undefined): number { return _renderModule.getPassID(name); } +export function getSubpassID (passID: number, name: string): number { + return _renderModule.getSubpassID(passID, name); +} + export function getPhaseID (passID: number, name: string | number | undefined): number { if (name === undefined) { return _renderModule.getPhaseID(passID, 'default'); } - if (typeof(name) === 'number') { + if (typeof (name) === 'number') { return _renderModule.getPhaseID(passID, name.toString()); } return _renderModule.getPhaseID(passID, name); diff --git a/cocos/rendering/custom/index.ts b/cocos/rendering/custom/index.ts index cfbd706696e..ab1c8fa240a 100644 --- a/cocos/rendering/custom/index.ts +++ b/cocos/rendering/custom/index.ts @@ -32,7 +32,7 @@ import { LayoutGraphData, loadLayoutGraphData } from './layout-graph'; import { BinaryInputArchive } from './binary-archive'; import { WebProgramLibrary } from './web-program-library'; import { Device } from '../../gfx'; -import { initializeLayoutGraphData, terminateLayoutGraphData, getCustomPassID, getCustomPhaseID } from './layout-graph-utils'; +import { initializeLayoutGraphData, terminateLayoutGraphData, getCustomPassID, getCustomPhaseID, getCustomSubpassID } from './layout-graph-utils'; import { ProgramLibrary } from './private'; import { PostProcessBuilder } from '../post-process/post-process-builder'; @@ -101,6 +101,10 @@ export function getPassID (name: string | undefined): number { return getCustomPassID(defaultLayoutGraph, name); } +export function getSubpassID (passID: number, name: string): number { + return getCustomSubpassID(defaultLayoutGraph, passID, name); +} + export function getPhaseID (passID: number, name: string | number | undefined): number { return getCustomPhaseID(defaultLayoutGraph, passID, name); } diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index 7bdabfe1981..c679c5796dd 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -30,15 +30,17 @@ /* eslint-disable max-len */ import { Material } from '../../asset/assets'; import { Camera } from '../../render-scene/scene/camera'; +import { DirectionalLight } from '../../render-scene/scene/directional-light'; import { GeometryRenderer } from '../geometry-renderer'; -import { Buffer, BufferInfo, ClearFlagBit, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, DrawInfo, Format, InputAssembler, LoadOp, PipelineState, Rect, ResolveMode, Sampler, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureInfo, Viewport } from '../../gfx'; +import { Buffer, BufferInfo, ClearFlagBit, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, Format, LoadOp, ResolveMode, SampleCount, Sampler, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureInfo, Viewport } from '../../gfx'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { Mat4, Quat, Vec2, Vec4 } from '../../core/math'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { AccessType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceResidency, SceneFlags, TaskType, UpdateFrequency, UploadPair } from './types'; +import { AccessType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency, UploadPair } from './types'; import { RenderWindow } from '../../render-scene/core/render-window'; -import { Model } from '../../render-scene/scene'; +import { Light, Model } from '../../render-scene/scene'; +import { SpotLight } from '../../render-scene/scene/spot-light'; /** * @engineInternal @@ -249,6 +251,11 @@ export enum SubpassCapabilities { * @zh 支持读取当前像素任意颜色值 */ INPUT_COLOR_MRT = 1 << 2, + /** + * @en Each subpass has its own sample count. + * @zh 每个Subpass拥有不同的采样数 + */ + HETEROGENEOUS_SAMPLE_COUNT = 1 << 3, } /** @@ -368,6 +375,10 @@ export interface Setter extends RenderNode { * @param name @en descriptor name in shader. @zh 填写着色器中的描述符(descriptor)名字 */ setSampler (name: string, sampler: Sampler): void; + setBuiltinCameraConstants (camera: Camera): void; + setBuiltinShadowMapConstants (light: DirectionalLight): void; + setBuiltinDirectionalLightViewConstants (light: DirectionalLight, level?: number): void; + setBuiltinSpotLightViewConstants (light: SpotLight): void; } /** @@ -391,6 +402,16 @@ export interface RenderQueueBuilder extends Setter { camera: Camera, light: LightInfo, sceneFlags?: SceneFlags): void; + addScene (camera: Camera, sceneFlags: SceneFlags): void; + addSceneCulledByDirectionalLight ( + camera: Camera, + sceneFlags: SceneFlags, + light: DirectionalLight, + level: number): void; + addSceneCulledBySpotLight ( + camera: Camera, + sceneFlags: SceneFlags, + light: SpotLight): void; /** * @en Render a full-screen quad. * @zh 渲染全屏四边形 @@ -528,6 +549,15 @@ export interface BasicRenderPassBuilder extends Setter { showStatistics: boolean; } +export interface BasicMultisampleRenderPassBuilder extends BasicRenderPassBuilder { + resolveRenderTarget (source: string, target: string): void; + resolveDepthStencil ( + source: string, + target: string, + depthMode?: ResolveMode, + stencilMode?: ResolveMode): void; +} + /** * @en BasicPipeline * Basic pipeline provides basic rendering features which are supported on all platforms. @@ -643,6 +673,27 @@ export interface BasicPipeline extends PipelineRuntime { width: number, height: number, format?: Format): void; + addResource ( + name: string, + dimension: ResourceDimension, + format: Format, + width: number, + height: number, + depth: number, + arraySize: number, + mipLevels: number, + sampleCount: SampleCount, + flags: ResourceFlags, + residency: ResourceResidency): number; + updateResource ( + name: string, + format: Format, + width: number, + height: number, + depth: number, + arraySize: number, + mipLevels: number, + sampleCount: SampleCount): void; /** * @engineInternal * @en Begin rendering one frame @@ -690,7 +741,7 @@ export interface BasicPipeline extends PipelineRuntime { height: number, count: number, quality: number, - passName?: string): BasicRenderPassBuilder; + passName?: string): BasicMultisampleRenderPassBuilder; /** * @deprecated Method will be removed in 3.9.0 */ @@ -1054,6 +1105,17 @@ export interface RenderPassBuilder extends BasicRenderPassBuilder { setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void; } +export interface MultisampleRenderPassBuilder extends BasicMultisampleRenderPassBuilder { + addStorageBuffer ( + name: string, + accessType: AccessType, + slotName: string): void; + addStorageImage ( + name: string, + accessType: AccessType, + slotName: string): void; +} + /** * @en Compute pass * @zh 计算通道 @@ -1133,38 +1195,6 @@ export interface ComputePassBuilder extends Setter { setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void; } -/** - * @deprecated @en Not used @zh 未使用 - */ -export interface SceneVisitor { - readonly pipelineSceneData: PipelineSceneData; - setViewport (vp: Viewport): void; - setScissor (rect: Rect): void; - bindPipelineState (pso: PipelineState): void; - bindInputAssembler (ia: InputAssembler): void; - draw (info: DrawInfo): void; - - bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: number[]): void; - updateBuffer (buffer: Buffer, data: ArrayBuffer, size?: number): void; -} - -/** - * @deprecated @en Not used @zh 未使用 - */ -export interface SceneTask { - readonly taskType: TaskType; - start (): void; - join (): void; - submit (): void; -} - -/** - * @deprecated @en Not used @zh 未使用 - */ -export interface SceneTransversal { - transverse (visitor: SceneVisitor): SceneTask; -} - /** * @en Render pipeline. * @zh 渲染管线 @@ -1259,6 +1289,12 @@ export interface Pipeline extends BasicPipeline { width: number, height: number, passName: string): RenderPassBuilder; + addMultisampleRenderPass ( + width: number, + height: number, + count: number, + quality: number, + passName: string): MultisampleRenderPassBuilder; /** * @en Add compute pass * @zh 添加计算通道 @@ -1308,6 +1344,11 @@ export interface Pipeline extends BasicPipeline { * @param movePairs @en Array of move source and target @zh 移动来源与目标的数组 */ addMovePass (movePairs: MovePair[]): void; + addBuiltinGpuCullingPass ( + camera: Camera, + hzbName?: string, + light?: Light | null): void; + addBuiltinHzbGenerationPass (sourceDepthStencilName: string, targetHzbName: string): void; /** * @experimental */ diff --git a/cocos/rendering/custom/render-graph.ts b/cocos/rendering/custom/render-graph.ts index afbb675ef8d..41078871395 100644 --- a/cocos/rendering/custom/render-graph.ts +++ b/cocos/rendering/custom/render-graph.ts @@ -114,7 +114,7 @@ export class ResourceDesc { depthOrArraySize = 0; mipLevels = 0; format: Format = Format.UNKNOWN; - sampleCount: SampleCount = SampleCount.ONE; + sampleCount: SampleCount = SampleCount.X1; textureFlags: TextureFlagBit = TextureFlagBit.NONE; flags: ResourceFlags = ResourceFlags.NONE; } @@ -164,6 +164,7 @@ export class ManagedResource { export class Subpass { readonly rasterViews: Map = new Map(); readonly computeViews: Map = new Map(); + readonly resolvePairs: ResolvePair[] = []; } //================================================================= @@ -171,8 +172,6 @@ export class Subpass { //================================================================= // Graph Concept export class SubpassGraphVertex { - constructor () { - } readonly _outEdges: OutE[] = []; readonly _inEdges: OutE[] = []; } @@ -1656,6 +1655,7 @@ export class RenderGraph implements BidirectionalGraph clear (): void { // Members this.index.clear(); + this.sortedVertices.length = 0; // ComponentGraph this._names.length = 0; this._layoutNodes.length = 0; @@ -2267,4 +2267,5 @@ export class RenderGraph implements BidirectionalGraph readonly _data: RenderData[] = []; readonly _valid: boolean[] = []; readonly index: Map = new Map(); + readonly sortedVertices: number[] = []; } diff --git a/cocos/rendering/custom/scene.ts b/cocos/rendering/custom/scene.ts new file mode 100644 index 00000000000..d46cf08a273 --- /dev/null +++ b/cocos/rendering/custom/scene.ts @@ -0,0 +1,34 @@ +import { + Buffer, + DescriptorSet, + DrawInfo, + InputAssembler, + PipelineState, + Rect, + Viewport, +} from '../../gfx'; +import { PipelineSceneData } from '../pipeline-scene-data'; +import { TaskType } from './types'; + +export interface SceneVisitor { + readonly pipelineSceneData: PipelineSceneData; + setViewport (vp: Viewport): void; + setScissor (rect: Rect): void; + bindPipelineState (pso: PipelineState): void; + bindInputAssembler (ia: InputAssembler): void; + draw (info: DrawInfo | InputAssembler): void; + + bindDescriptorSet (set: number, descriptorSet: DescriptorSet, dynamicOffsets?: number[]): void; + updateBuffer (buffer: Buffer, data: ArrayBuffer, size?: number): void; +} + +export interface SceneTask { + readonly taskType: TaskType; + start (): void; + join (): void; + submit (): void; +} + +export interface SceneTransversal { + transverse (visitor: SceneVisitor): SceneTask; +} diff --git a/cocos/rendering/custom/types.ts b/cocos/rendering/custom/types.ts index c964335b4ff..d09e3b8a9fe 100644 --- a/cocos/rendering/custom/types.ts +++ b/cocos/rendering/custom/types.ts @@ -168,6 +168,8 @@ export enum ResourceFlags { DEPTH_STENCIL_ATTACHMENT = 0x20, INPUT_ATTACHMENT = 0x40, SHADING_RATE = 0x80, + TRANSFER_SRC = 0x100, + TRANSFER_DST = 0x200, } export enum TaskType { @@ -205,6 +207,7 @@ export enum SceneFlags { DRAW_INSTANCING = 0x800, DRAW_NON_INSTANCING = 0x1000, REFLECTION_PROBE = 0x2000, + GPU_DRIVEN = 0x4000, ALL = 0xFFFFFFFF, } diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index ec05c6e9ee2..c1bac8ca455 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -25,11 +25,11 @@ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; import { DEBUG } from 'internal:constants'; -import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo, UniformBlock } from '../../gfx'; -import { Mat4, Quat, toRadian, Vec2, Vec3, Vec4, assert, macro, cclegacy } from '../../core'; +import { Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo, UniformBlock, ResolveMode, SampleCount, Color } from '../../gfx'; +import { Mat4, Quat, toRadian, Vec2, Vec3, Vec4, assert, macro, cclegacy, IVec4Like, IMat4Like, IVec2Like, Color as CoreColor } from '../../core'; import { AccessType, AttachmentType, CopyPair, LightInfo, LightingMode, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; import { ComputeView, RasterView, Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedBuffer, ManagedResource, MovePass, RasterPass, RasterSubpass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData, Subpass } from './render-graph'; -import { ComputePassBuilder, ComputeQueueBuilder, ComputeSubpassBuilder, BasicPipeline, PipelineBuilder, RenderPassBuilder, RenderQueueBuilder, RenderSubpassBuilder, PipelineType, BasicRenderPassBuilder, PipelineCapabilities } from './pipeline'; +import { ComputePassBuilder, ComputeQueueBuilder, ComputeSubpassBuilder, BasicPipeline, PipelineBuilder, RenderPassBuilder, RenderQueueBuilder, RenderSubpassBuilder, PipelineType, BasicRenderPassBuilder, PipelineCapabilities, BasicMultisampleRenderPassBuilder } from './pipeline'; import { PipelineSceneData } from '../pipeline-scene-data'; import { Model, Camera, ShadowType, CSMLevel, DirectionalLight, SpotLight, PCFType, Shadows } from '../../render-scene/scene'; import { Light, LightType } from '../../render-scene/scene/light'; @@ -54,6 +54,9 @@ import { getUBOTypeCount } from './utils'; import { initGlobalDescBinding } from './define'; import { createGfxDescriptorSetsAndPipelines } from './layout-graph-utils'; import { Root } from '../../root'; +import { CSMLayers, CSMShadowLayer } from '../shadow/csm-layers'; +import { Scene } from '../../scene-graph'; +import { Director } from '../../game'; const _uboVec = new Vec4(); const _uboVec3 = new Vec3(); @@ -75,32 +78,34 @@ export class WebSetter { this._lg = lg; } - protected _copyToBuffer (target: any, offset: number, type: Type): void { + protected _copyToBuffer (target: IVec4Like | Quat | IVec2Like | IMat4Like | number, offset: number, type: Type): void { assert(offset !== -1); const arr = this.getCurrConstant(); switch (type) { case Type.FLOAT4: - Vec4.toArray(arr, target, offset); + Vec4.toArray(arr, target as IVec4Like, offset); break; case Type.MAT4: - Mat4.toArray(arr, target, offset); + Mat4.toArray(arr, target as IMat4Like, offset); break; case Type.FLOAT: - arr[offset] = target; + arr[offset] = target as number; break; case Type.SAMPLER2D: break; case Type.TEXTURE2D: break; - case Type.FLOAT2: - arr[offset + 0] = target.x; - arr[offset + 1] = target.y; + case Type.FLOAT2: { + const vec2Val = target as IVec2Like; + arr[offset + 0] = vec2Val.x; + arr[offset + 1] = vec2Val.y; + } break; default: } } - protected _applyCurrConstantBuffer (name: string, target: any, type: Type, idx = 0): void { + protected _applyCurrConstantBuffer (name: string, target: IVec4Like | Quat | IVec2Like | IMat4Like | number, type: Type, idx = 0): void { const offset = this.getUniformOffset(name, type, idx); this._copyToBuffer(target, offset, type); } @@ -189,7 +194,7 @@ export class WebSetter { this._currCount += getUBOTypeCount(uniform.type) * uniform.count; } if (!this._data.constants.get(num)) { - const value = new Array(this._currCount); + const value: number[] = new Array(this._currCount); value.fill(0); this._data.constants.set(num, value); } @@ -211,7 +216,7 @@ export class WebSetter { public setColor (name: string, color: Color, idx = 0): void { this._applyCurrConstantBuffer(name, color, Type.FLOAT4, idx); } - public offsetColor (color: Color, offset: number): void { + public offsetColor (color: Color | CoreColor, offset: number): void { this._copyToBuffer(color, offset, Type.FLOAT4); } public setVec4 (name: string, vec: Vec4, idx = 0): void { @@ -249,18 +254,18 @@ export class WebSetter { const num = this._lg.attributeIndex.get(name)!; this._data.samplers.set(num, sampler); } - // public setCameraConstants (camera: Camera): void { + public setBuiltinCameraConstants (camera: Camera): void { - // } - // public setDirectionalLightProjectionConstants (light: DirectionalLight): void { + } + public setBuiltinShadowMapConstants (light: Light, numLevels?: number): void { - // } - // public setSpotLightProjectionConstants (light: SpotLight): void { + } + public setBuiltinDirectionalLightViewConstants (light: DirectionalLight): void { - // } - // public setShadowMapConstants (light: Light, numLevels?: number): void { + } + public setBuiltinSpotLightViewConstants (light: SpotLight): void { - // } + } public hasSampler (name: string): boolean { const id = this._lg.attributeIndex.get(name); if (id === undefined) { @@ -283,16 +288,18 @@ export class WebSetter { protected _data: RenderData; protected _lg: LayoutGraphData; protected _currBlock; - protected _currStage; + protected _currStage: string = ''; protected _currCount; protected _currConstant: number[] = []; } -function setShadowUBOLightView (setter: WebSetter, +function setShadowUBOLightView ( + setter: WebSetter, camera: Camera, light: Light, level: number, - layout = 'default'): void { + layout = 'default', +): void { const director = cclegacy.director; const pipeline = (director.root as Root).pipeline; const device = pipeline.device; @@ -319,9 +326,9 @@ function setShadowUBOLightView (setter: WebSetter, if (shadowInfo.type === ShadowType.ShadowMap) { let near = 0.1; let far = 0; - let matShadowView; - let matShadowProj; - let matShadowViewProj; + let matShadowView: Mat4; + let matShadowProj: Mat4; + let matShadowViewProj: Mat4; let levelCount = 0; if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { matShadowView = csmLayers.specialLayer.matShadowView; @@ -394,12 +401,21 @@ function setShadowUBOLightView (setter: WebSetter, const matViewOffset = setter.getUniformOffset('cc_matLightView', Type.MAT4); const matViewProOffset = setter.getUniformOffset('cc_matLightViewProj', Type.MAT4); if (setter.hasUniform(matViewOffset) || setter.hasUniform(matViewProOffset)) { - Mat4.invert(_matView, (light as any).node.getWorldMatrix()); + Mat4.invert(_matView, spotLight.node!.getWorldMatrix()); } if (setter.hasUniform(matViewOffset)) setter.offsetMat4(_matView, matViewOffset); if (setter.hasUniform(matViewProOffset)) { - Mat4.perspective(_mulMatView, (light as any).angle, 1.0, 0.001, (light as any).range, - true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); + Mat4.perspective( + _mulMatView, + spotLight.angle, + 1.0, + 0.001, + spotLight.range, + true, + cap.clipSpaceMinZ, + cap.clipSpaceSignY, + 0, + ); Mat4.multiply(_matView, _mulMatView, _matView); setter.offsetMat4(_matView, matViewProOffset); } @@ -449,12 +465,12 @@ function getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'default'): void { const director = cclegacy.director; const pipeline = director.root.pipeline; - const device = pipeline.device; + const device: Device = pipeline.device; const scene = director.getScene(); - const mainLight = camera && camera.scene ? camera.scene.mainLight : scene ? scene.renderScene.mainLight : null; + const mainLight: DirectionalLight = camera && camera.scene ? camera.scene.mainLight : scene ? scene.renderScene.mainLight : null; const sceneData = pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - const csmLayers = sceneData.csmLayers; + const shadowInfo: Shadows = sceneData.shadows; + const csmLayers: CSMLayers = sceneData.csmLayers; const csmSupported = sceneData.csmSupported; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const hasCCShadow = setter.addConstant('CCShadow', layout); @@ -465,11 +481,11 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) { if (hasCCShadow) { setter.setCurrConstant('CCShadow', layout); - const matShadowView = csmLayers.specialLayer.matShadowView; - const matShadowProj = csmLayers.specialLayer.matShadowProj; - const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; - const near = mainLight.shadowNear; - const far = mainLight.shadowFar; + const matShadowView: Mat4 = csmLayers.specialLayer.matShadowView; + const matShadowProj: Mat4 = csmLayers.specialLayer.matShadowProj; + const matShadowViewProj: Mat4 = csmLayers.specialLayer.matShadowViewProj; + const near: number = mainLight.shadowNear; + const far: number = mainLight.shadowFar; uniformOffset = setter.getUniformOffset('cc_matLightView', Type.MAT4); if (setter.hasUniform(uniformOffset)) { setter.offsetMat4(matShadowView, uniformOffset); @@ -504,8 +520,8 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd const layerThreshold = getPCFRadius(shadowInfo, mainLight); setter.setCurrConstant('CCCSM', layout); for (let i = 0; i < mainLight.csmLevel; i++) { - const layer = csmLayers.layers[i]; - const matShadowView = layer.matShadowView; + const layer: CSMShadowLayer = csmLayers.layers[i]; + const matShadowView: Mat4 = layer.matShadowView; uniformOffset = setter.getUniformOffset('cc_csmViewDir0', Type.FLOAT4, i); if (setter.hasUniform(uniformOffset)) { _uboVec.set(matShadowView.m00, matShadowView.m04, matShadowView.m08, layerThreshold); @@ -591,10 +607,13 @@ function setShadowUBOView (setter: WebSetter, camera: Camera | null, layout = 'd } } -function setCameraUBOValues (setter: WebSetter, - camera: Readonly | null, cfg: Readonly, - scene: Readonly, - layoutName = 'default'): void { +function setCameraUBOValues ( + setter: WebSetter, + camera: Readonly | null, + cfg: Readonly, + scene: RenderScene | null, + layoutName = 'default', +): void { const director = cclegacy.director; const root = director.root; const pipeline = root.pipeline as WebPipeline; @@ -741,14 +760,14 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado const root = director.root; if (skybox.reflectionMap) { const texture = skybox.reflectionMap.getGFXTexture()!; - const sampler = root.device.getSampler(skybox.reflectionMap.getSamplerInfo()); + const sampler: Sampler = root.device.getSampler(skybox.reflectionMap.getSamplerInfo()); setter.setTexture('cc_environment', texture); setter.setSampler('cc_environment', sampler); } else { const envmap = skybox.envmap ? skybox.envmap : builtinResMgr.get('default-cube-texture'); if (envmap) { const texture = envmap.getGFXTexture()!; - const sampler = root.device.getSampler(envmap.getSamplerInfo()); + const sampler: Sampler = root.device.getSampler(envmap.getSamplerInfo()); setter.setTexture('cc_environment', texture); setter.setSampler('cc_environment', sampler); } @@ -756,11 +775,11 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado const diffuseMap = skybox.diffuseMap ? skybox.diffuseMap : builtinResMgr.get('default-cube-texture'); if (diffuseMap) { const texture = diffuseMap.getGFXTexture()!; - const sampler = root.device.getSampler(diffuseMap.getSamplerInfo()); + const sampler: Sampler = root.device.getSampler(diffuseMap.getSamplerInfo()); setter.setTexture('cc_diffuseMap', texture); setter.setSampler('cc_diffuseMap', sampler); } - const pointSampler = root.device.getSampler(_samplerPointInfo); + const pointSampler: Sampler = root.device.getSampler(_samplerPointInfo); if (!setter.hasSampler('cc_shadowMap')) { setter.setSampler('cc_shadowMap', pointSampler); } @@ -779,7 +798,7 @@ function getFirstChildLayoutName (lg: LayoutGraphData, parentID: number): string if (lg.numVertices() && parentID !== 0xFFFFFFFF && lg.numChildren(parentID)) { const childNodes = lg.children(parentID); if (childNodes.next().value && childNodes.next().value.target !== lg.nullVertex()) { - const ququeLayoutID = childNodes.next().value.target; + const ququeLayoutID: number = childNodes.next().value.target; return lg.getName(ququeLayoutID); } } @@ -812,14 +831,16 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void { const sceneData = new SceneData(camera.scene, camera, sceneFlags, light); - this._renderGraph.addVertex( - RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID, - ); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID); const layoutName = this.getLayoutName(); - const scene = cclegacy.director.getScene(); - setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : scene ? scene.renderScene : null, - layoutName); + const scene: Scene = cclegacy.director.getScene(); + setCameraUBOValues( + this, + camera, + this._pipeline, + camera.scene || (scene ? scene.renderScene : null), + layoutName, + ); if (sceneFlags & SceneFlags.SHADOW_CASTER) { setShadowUBOLightView(this, camera, light.light!, light.level, layoutName); } else { @@ -828,33 +849,37 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild setTextureUBOView(this, camera, this._pipeline); initGlobalDescBinding(this._data, layoutName); } - // addScene (camera: Camera, sceneFlags = SceneFlags.NONE): void { - // const sceneData = new SceneData(camera.scene, camera, sceneFlags); - // this._renderGraph.addVertex( - // RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID, - // ); - // } - // addSceneCulledByDirectionalLight (camera: Camera, sceneFlags: SceneFlags, light: DirectionalLight, level: number): void { - // const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, level)); - // this._renderGraph.addVertex( - // RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID, - // ); - // } - // addSceneCulledBySpotLight (camera: Camera, sceneFlags: SceneFlags, light: SpotLight): void { - // const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, 0)); - // this._renderGraph.addVertex( - // RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID, - // ); - // } + addScene (camera: Camera, sceneFlags = SceneFlags.NONE): void { + const sceneData = new SceneData(camera.scene, camera, sceneFlags); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID); + } + addSceneCulledByDirectionalLight (camera: Camera, sceneFlags: SceneFlags, light: DirectionalLight, level: number): void { + const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, level)); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID); + } + addSceneCulledBySpotLight (camera: Camera, sceneFlags: SceneFlags, light: SpotLight): void { + const sceneData = new SceneData(camera.scene, camera, sceneFlags, new LightInfo(light, 0)); + this._renderGraph.addVertex(RenderGraphValue.Scene, sceneData, 'Scene', '', new RenderData(), false, this._vertID); + } addFullscreenQuad (material: Material, passID: number, sceneFlags = SceneFlags.NONE, name = 'Quad'): void { this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, null), - name, '', new RenderData(), false, this._vertID, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, null), + name, + '', + new RenderData(), + false, + this._vertID, ); const layoutName = this.getLayoutName(); - const scene = cclegacy.director.getScene(); - setCameraUBOValues(this, null, this._pipeline, - scene ? scene.renderScene : null, layoutName); + const scene: Scene | null = cclegacy.director.getScene(); + setCameraUBOValues( + this, + null, + this._pipeline, + scene ? scene.renderScene : null, + layoutName, + ); if (sceneFlags & SceneFlags.SHADOW_CASTER) { // setShadowUBOLightView(this, light.light!, light.level); } else { @@ -865,13 +890,23 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild } addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags = SceneFlags.NONE): void { this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, camera), - 'CameraQuad', '', new RenderData(), false, this._vertID, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, camera), + 'CameraQuad', + '', + new RenderData(), + false, + this._vertID, ); const layoutName = this.getLayoutName(); - const scene = cclegacy.director.getScene(); - setCameraUBOValues(this, camera, this._pipeline, - camera.scene ? camera.scene : scene ? scene.renderScene : null, layoutName); + const scene: Scene = cclegacy.director.getScene(); + setCameraUBOValues( + this, + camera, + this._pipeline, + camera.scene || (scene ? scene.renderScene : null), + layoutName, + ); if (sceneFlags & SceneFlags.SHADOW_CASTER) { // setShadowUBOLightView(this, light.light!, light.level); } else { @@ -882,8 +917,13 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild } clearRenderTarget (name: string, color: Color = new Color()): void { this._renderGraph.addVertex( - RenderGraphValue.Clear, [new ClearView(name, ClearFlagBit.COLOR, color)], - 'ClearRenderTarget', '', new RenderData(), false, this._vertID, + RenderGraphValue.Clear, + [new ClearView(name, ClearFlagBit.COLOR, color)], + 'ClearRenderTarget', + '', + new RenderData(), + false, + this._vertID, ); } setViewport (viewport: Viewport): void { @@ -899,8 +939,14 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild } export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassBuilder { - constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, - vertID: number, subpass: RasterSubpass, pipeline: PipelineSceneData) { + constructor ( + data: RenderData, + renderGraph: RenderGraph, + layoutGraph: LayoutGraphData, + vertID: number, + subpass: RasterSubpass, + pipeline: PipelineSceneData, + ) { super(data, layoutGraph); this._renderGraph = renderGraph; this._layoutGraph = layoutGraph; @@ -908,11 +954,12 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB this._subpass = subpass; this._pipeline = pipeline; - const layoutName = this._renderGraph.component( - RenderGraphComponent.Layout, this._vertID, - ); + const layoutName = this._renderGraph.component(RenderGraphComponent.Layout, this._vertID); this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } + addRenderTarget (name: string, accessType: AccessType, slotName?: string | undefined, loadOp?: LoadOp | undefined, storeOp?: StoreOp | undefined, color?: Color | undefined): void { + throw new Error('Method not implemented.'); + } setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void { throw new Error('Method not implemented.'); } @@ -925,9 +972,7 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB set name (name: string) { this._renderGraph.setName(this._vertID, name); } - addRenderTarget (name: string, accessType: AccessType, slotName: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, clearColor = new Color()): void { - throw new Error('Method not implemented.'); - } + addDepthStencil (name: string, accessType: AccessType, depthSlotName = '', stencilSlotName = '', loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { throw new Error('Method not implemented.'); } @@ -950,9 +995,7 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB } const queue = new RenderQueue(hint); const data = new RenderData(); - const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID, - ); + const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); } get showStatistics (): boolean { @@ -970,7 +1013,7 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB private readonly _layoutGraph: LayoutGraphData; } -export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBuilder { +export class WebRenderPassBuilder extends WebSetter implements BasicMultisampleRenderPassBuilder { constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, resourceGraph: ResourceGraph, vertID: number, pass: RasterPass, pipeline: PipelineSceneData) { super(data, layoutGraph); this._renderGraph = renderGraph; @@ -980,9 +1023,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu this._pass = pass; this._pipeline = pipeline; - const layoutName = this._renderGraph.component( - RenderGraphComponent.Layout, this._vertID, - ); + const layoutName = this._renderGraph.component(RenderGraphComponent.Layout, this._vertID); this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void { @@ -1009,25 +1050,44 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu if (loadOp === LoadOp.LOAD) { clearFlag = ClearFlagBit.NONE; } - const view = new RasterView('', - AccessType.WRITE, AttachmentType.RENDER_TARGET, + const view = new RasterView( + '', + AccessType.WRITE, + + AttachmentType.RENDER_TARGET, loadOp, storeOp, clearFlag, - clearColor); + clearColor, + ); this._pass.rasterViews.set(name, view); } addDepthStencil (name: string, loadOp = LoadOp.CLEAR, storeOp = StoreOp.STORE, depth = 1, stencil = 0, clearFlag = ClearFlagBit.DEPTH_STENCIL): void { if (DEBUG) { assert(Boolean(name && this._resourceGraph.contains(name))); } - const view = new RasterView('', - AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + const view = new RasterView( + '', + AccessType.WRITE, + + AttachmentType.DEPTH_STENCIL, loadOp, storeOp, clearFlag, - new Color(depth, stencil, 0, 0)); + new Color(depth, stencil, 0, 0), + ); this._pass.rasterViews.set(name, view); + } + resolveRenderTarget (source: string, target: string): void { + + } + resolveDepthStencil ( + source: string, + target: string, + depthMode?: ResolveMode, + stencilMode?: ResolveMode, + ): void { + } private _addComputeResource (name: string, accessType: AccessType, slotName: string): void { const view = new ComputeView(slotName); @@ -1064,9 +1124,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu this._pass.subpassGraph.addVertex(name, new Subpass()); const subpass = new RasterSubpass(subpassID, 1, 0); const data = new RenderData(); - const vertID = this._renderGraph.addVertex( - RenderGraphValue.RasterSubpass, subpass, name, layoutName, data, false, - ); + const vertID = this._renderGraph.addVertex(RenderGraphValue.RasterSubpass, subpass, name, layoutName, data, false); const result = new WebRenderSubpassBuilder(data, this._renderGraph, this._layoutGraph, vertID, subpass, this._pipeline); return result; } @@ -1077,34 +1135,51 @@ export class WebRenderPassBuilder extends WebSetter implements BasicRenderPassBu } const queue = new RenderQueue(hint); const data = new RenderData(); - const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID, - ); + const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); } addFullscreenQuad (material: Material, passID: number, sceneFlags = SceneFlags.NONE, name = 'FullscreenQuad'): void { const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); const queueId = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, - 'Queue', '', new RenderData(), - false, this._vertID, + RenderGraphValue.Queue, + queue, + 'Queue', + '', + new RenderData(), + false, + this._vertID, ); this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, null), - name, '', new RenderData(), false, queueId, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, null), + name, + '', + new RenderData(), + false, + queueId, ); } addCameraQuad (camera: Camera, material: Material, passID: number, sceneFlags: SceneFlags, name = 'CameraQuad'): void { const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); const queueId = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, - 'Queue', '', new RenderData(), false, this._vertID, + RenderGraphValue.Queue, + queue, + 'Queue', + '', + new RenderData(), + false, + this._vertID, ); this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(material, passID, sceneFlags, camera), - name, '', new RenderData(), false, queueId, + RenderGraphValue.Blit, + new Blit(material, passID, sceneFlags, camera), + name, + '', + new RenderData(), + false, + queueId, ); } setViewport (viewport: Viewport): void { @@ -1153,7 +1228,15 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui this._renderGraph.addVertex( RenderGraphValue.Dispatch, new Dispatch(material, passID, threadGroupCountX, threadGroupCountY, threadGroupCountZ), - name, '', new RenderData(), false, this._vertID, + name, + + '', + + new RenderData(), + + false, + + this._vertID, ); } private readonly _renderGraph: RenderGraph; @@ -1172,9 +1255,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild this._pass = pass; this._pipeline = pipeline; - const layoutName = this._renderGraph.component( - RenderGraphComponent.Layout, this._vertID, - ); + const layoutName = this._renderGraph.component(RenderGraphComponent.Layout, this._vertID); this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } setCustomShaderStages (name: string, stageFlags: ShaderStageFlagBit): void { @@ -1208,9 +1289,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild } const queue = new RenderQueue(); const data = new RenderData(); - const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID, - ); + const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebComputeQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); } private readonly _renderGraph: RenderGraph; @@ -1302,10 +1381,13 @@ export class WebPipeline implements BasicPipeline { if (renderWindow.swapchain === null) { assert(renderWindow.framebuffer.colorTextures.length === 1 && renderWindow.framebuffer.colorTextures[0] !== null); + desc.sampleCount = renderWindow.framebuffer.colorTextures[0].info.samples; return this._resourceGraph.addVertex( ResourceGraphValue.Framebuffer, renderWindow.framebuffer, - name, desc, + name, + + desc, new ResourceTraits(ResourceResidency.EXTERNAL), new ResourceStates(), new SamplerInfo(), @@ -1314,7 +1396,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.Swapchain, new RenderSwapchain(renderWindow.swapchain), - name, desc, + name, + + desc, new ResourceTraits(ResourceResidency.BACKBUFFER), new ResourceStates(), new SamplerInfo(), @@ -1365,6 +1449,39 @@ export class WebPipeline implements BasicPipeline { desc.width = width; desc.height = height; } + addResource (name: string, dimension: ResourceDimension, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount, flags: ResourceFlags, residency: ResourceResidency): number { + const desc = new ResourceDesc(); + desc.dimension = dimension; + desc.width = width; + desc.height = height; + desc.depthOrArraySize = dimension === ResourceDimension.TEXTURE3D ? depth : arraySize; + desc.mipLevels = mipLevels; + desc.format = format; + desc.sampleCount = sampleCount; + desc.flags = flags; + return this._resourceGraph.addVertex( + ResourceGraphValue.Managed, + new ManagedResource(), + name, + + desc, + new ResourceTraits(residency), + new ResourceStates(), + new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), + ); + } + updateResource (name: string, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount): void { + const resId = this.resourceGraph.vertex(name); + const desc = this.resourceGraph.getDesc(resId); + desc.width = width; + desc.height = height; + desc.depthOrArraySize = desc.dimension === ResourceDimension.TEXTURE3D ? depth : arraySize; + desc.mipLevels = mipLevels; + if (format !== Format.UNKNOWN) { + desc.format = format; + } + desc.sampleCount = sampleCount; + } public containsResource (name: string): boolean { return this._resourceGraph.contains(name); } @@ -1618,7 +1735,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.ManagedBuffer, new ManagedBuffer(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(), @@ -1632,12 +1751,15 @@ export class WebPipeline implements BasicPipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; + desc.sampleCount = SampleCount.X1; desc.flags = ResourceFlags.COLOR_ATTACHMENT | ResourceFlags.SAMPLED; return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), @@ -1651,11 +1773,14 @@ export class WebPipeline implements BasicPipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; + desc.sampleCount = SampleCount.X1; desc.flags = ResourceFlags.DEPTH_STENCIL_ATTACHMENT | ResourceFlags.SAMPLED; return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.POINT, Filter.POINT, Filter.NONE), @@ -1673,7 +1798,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.POINT, Filter.POINT, Filter.NONE), @@ -1692,7 +1819,9 @@ export class WebPipeline implements BasicPipeline { return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), - name, desc, + name, + + desc, new ResourceTraits(residency), new ResourceStates(), new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), @@ -1724,8 +1853,15 @@ export class WebPipeline implements BasicPipeline { throw new Error('Cannot run without creating rendergraph'); } if (!this._executor) { - this._executor = new Executor(this, this._pipelineUBO, this._device, - this._resourceGraph, this.layoutGraph, this.width, this.height); + this._executor = new Executor( + this, + this._pipelineUBO, + this._device, + this._resourceGraph, + this.layoutGraph, + this.width, + this.height, + ); } this._executor.resize(this.width, this.height); this._executor.execute(this._renderGraph); @@ -1762,7 +1898,7 @@ export class WebPipeline implements BasicPipeline { this.execute(); this.endFrame(); } - addRenderPassImpl (width: number, height: number, layoutName: string, count = 1, quality = 0): BasicRenderPassBuilder { + addRenderPassImpl (width: number, height: number, layoutName: string, count = 1, quality = 0): BasicMultisampleRenderPassBuilder { if (DEBUG) { const stageId = this.layoutGraph.locateChild(this.layoutGraph.nullVertex(), layoutName); assert(stageId !== 0xFFFFFFFF); @@ -1778,9 +1914,7 @@ export class WebPipeline implements BasicPipeline { pass.quality = quality; const data = new RenderData(); - const vertID = this._renderGraph!.addVertex( - RenderGraphValue.RasterPass, pass, name, layoutName, data, false, - ); + const vertID = this._renderGraph!.addVertex(RenderGraphValue.RasterPass, pass, name, layoutName, data, false); const result = new WebRenderPassBuilder(data, this._renderGraph!, this._layoutGraph, this._resourceGraph, vertID, pass, this._pipelineSceneData); this._updateRasterPassConstants(result, width, height, isEnableEffect() ? layoutName : 'default'); initGlobalDescBinding(data, layoutName); @@ -1789,7 +1923,7 @@ export class WebPipeline implements BasicPipeline { addRenderPass (width: number, height: number, layoutName = 'default'): BasicRenderPassBuilder { return this.addRenderPassImpl(width, height, layoutName); } - addMultisampleRenderPass (width: number, height: number, count: number, quality: number, layoutName = 'default'): BasicRenderPassBuilder { + addMultisampleRenderPass (width: number, height: number, count: number, quality: number, layoutName = 'default'): BasicMultisampleRenderPassBuilder { assert(count > 1); return this.addRenderPassImpl(width, height, layoutName, count, quality); } @@ -1815,8 +1949,8 @@ export class WebPipeline implements BasicPipeline { } protected _updateRasterPassConstants (setter: WebSetter, width: number, height: number, layoutName = 'default'): void { - const director = cclegacy.director; - const root = director.root; + const director: Director = cclegacy.director; + const root: Root = director.root!; const shadingWidth = width; const shadingHeight = height; const pipeline = root.pipeline as WebPipeline; @@ -1843,7 +1977,7 @@ export class WebPipeline implements BasicPipeline { if (debugView) { if (setter.hasUniform(uniformOffset)) { const debugPackVec: number[] = [debugView.singleMode as number, 0.0, 0.0, 0.0]; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { + for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < (DebugViewCompositeType.MAX_BIT_COUNT as number); i++) { const idx = i >> 3; const bit = i % 8; debugPackVec[idx + 1] += (debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0) * (10.0 ** bit); diff --git a/cocos/rendering/custom/web-scene-visitor.ts b/cocos/rendering/custom/web-scene-visitor.ts index 81f3d187c15..04f4e94bb19 100644 --- a/cocos/rendering/custom/web-scene-visitor.ts +++ b/cocos/rendering/custom/web-scene-visitor.ts @@ -24,7 +24,7 @@ import { PipelineState, DescriptorSet, InputAssembler, DrawInfo, Buffer, CommandBuffer, Rect, Viewport } from '../../gfx'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { SceneVisitor } from './pipeline'; +import { SceneVisitor } from './scene'; export class WebSceneVisitor implements SceneVisitor { protected _pipelineSceneData: PipelineSceneData; @@ -51,7 +51,7 @@ export class WebSceneVisitor implements SceneVisitor { public bindInputAssembler (ia: InputAssembler): void { this._commandBuffer.bindInputAssembler(ia); } - public draw (info: DrawInfo): void { + public draw (info: DrawInfo | InputAssembler): void { this._commandBuffer.draw(info); } public updateBuffer (buffer: Buffer, data: ArrayBuffer, size?: number): void { diff --git a/cocos/rendering/custom/web-scene.ts b/cocos/rendering/custom/web-scene.ts index 7a4c6a6150f..ea0272151da 100644 --- a/cocos/rendering/custom/web-scene.ts +++ b/cocos/rendering/custom/web-scene.ts @@ -28,7 +28,7 @@ import { RenderScene, scene } from '../../render-scene'; import { Camera, Model, ShadowType, SKYBOX_FLAG } from '../../render-scene/scene'; import { IRenderObject, IRenderPass, UBOShadow } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { SceneTask, SceneTransversal, SceneVisitor } from './pipeline'; +import { SceneTask, SceneTransversal, SceneVisitor } from './scene'; import { TaskType } from './types'; import { PipelineUBO } from '../pipeline-ubo'; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 4e9a2c3d98c..bf1218beb9c 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1410,7 +1410,8 @@ cocos_source_files( cocos/renderer/pipeline/custom/LayoutGraphTypes.h cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp cocos/renderer/pipeline/custom/LayoutGraphUtils.h - cocos/renderer/pipeline/custom/NativeDefaultScene.cpp + cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp + cocos/renderer/pipeline/custom/NativeBuiltinUtils.h cocos/renderer/pipeline/custom/NativeExecutor.cpp cocos/renderer/pipeline/custom/NativeFactory.cpp cocos/renderer/pipeline/custom/NativeFwd.h @@ -1422,10 +1423,13 @@ cocos_source_files( cocos/renderer/pipeline/custom/NativePools.cpp cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp cocos/renderer/pipeline/custom/NativeRenderGraph.cpp + cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp + cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h cocos/renderer/pipeline/custom/NativeRenderQueue.cpp cocos/renderer/pipeline/custom/NativeRenderingModule.cpp cocos/renderer/pipeline/custom/NativeResourceGraph.cpp cocos/renderer/pipeline/custom/NativeSceneCulling.cpp + cocos/renderer/pipeline/custom/NativeSetter.cpp cocos/renderer/pipeline/custom/NativeTypes.cpp cocos/renderer/pipeline/custom/NativeTypes.h cocos/renderer/pipeline/custom/NativeUtils.cpp diff --git a/native/cocos/core/assets/RenderTexture.cpp b/native/cocos/core/assets/RenderTexture.cpp index 79224297f73..564e94cb923 100644 --- a/native/cocos/core/assets/RenderTexture.cpp +++ b/native/cocos/core/assets/RenderTexture.cpp @@ -36,7 +36,7 @@ gfx::RenderPassInfo getDefaultRenderPassInfo(gfx::Device *device) { gfx::RenderPassInfo info; info.colorAttachments.push_back({ gfx::Format::RGBA8, - gfx::SampleCount::ONE, + gfx::SampleCount::X1, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, device->getGeneralBarrier({ diff --git a/native/cocos/renderer/frame-graph/FrameGraph.cpp b/native/cocos/renderer/frame-graph/FrameGraph.cpp index 25b14f79e09..594d16a0c9b 100644 --- a/native/cocos/renderer/frame-graph/FrameGraph.cpp +++ b/native/cocos/renderer/frame-graph/FrameGraph.cpp @@ -426,7 +426,7 @@ void FrameGraph::computeStoreActionAndMemoryless() { const gfx::TextureInfo &textureDesc = static_cast *>(renderTarget)->get().getDesc(); renderTarget->_memoryless = renderTarget->_neverLoaded && renderTarget->_neverStored; - renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::ONE && renderTarget->_writerCount < 2; + renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::X1 && renderTarget->_writerCount < 2; } } diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 204df36fafa..7689387fd31 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -383,6 +383,27 @@ void CommandBufferAgent::updateBuffer(Buffer *buff, const void *data, uint32_t s }); } +void CommandBufferAgent::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + Texture *actorSrcTexture = nullptr; + Texture *actorDstTexture = nullptr; + if (srcTexture) actorSrcTexture = static_cast(srcTexture)->getActor(); + if (dstTexture) actorDstTexture = static_cast(dstTexture)->getActor(); + + auto *actorRegions = _messageQueue->allocate(count); + memcpy(actorRegions, regions, count * sizeof(TextureCopy)); + + ENQUEUE_MESSAGE_5( + _messageQueue, CommandBufferBlitTexture, + actor, getActor(), + srcTexture, actorSrcTexture, + dstTexture, actorDstTexture, + regions, actorRegions, + count, count, + { + actor->resolveTexture(srcTexture, dstTexture, regions, count); + }); +} + void CommandBufferAgent::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { Texture *actorSrcTexture = nullptr; Texture *actorDstTexture = nullptr; diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h index 95ddf92a57f..b3cf37ff0e8 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h @@ -61,6 +61,7 @@ class CC_DLL CommandBufferAgent final : public Agent { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index 16fe3f531e7..872fb3bf849 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -455,5 +455,9 @@ void DeviceAgent::frameSync() { }); } +SampleCount DeviceAgent::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + return _actor->getMaxSampleCount(format, usage, flags); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.h b/native/cocos/renderer/gfx-agent/DeviceAgent.h index cbbb9693467..ce11e0feb5b 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.h +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.h @@ -106,7 +106,7 @@ class CC_DLL DeviceAgent final : public Agent { void presentSignal(); void enableAutoBarrier(bool en) override; - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static DeviceAgent *instance; diff --git a/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp b/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp index 0c54378d084..8b3f0191408 100644 --- a/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp @@ -57,6 +57,9 @@ void FramebufferAgent::doInit(const FramebufferInfo &info) { if (info.depthStencilTexture) { actorInfo.depthStencilTexture = static_cast(info.depthStencilTexture)->getActor(); } + if (info.depthStencilResolveTexture) { + actorInfo.depthStencilResolveTexture = static_cast(info.depthStencilResolveTexture)->getActor(); + } actorInfo.renderPass = static_cast(info.renderPass)->getActor(); ENQUEUE_MESSAGE_2( diff --git a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h index c16065c74b2..00a6d46e2aa 100644 --- a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h +++ b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h @@ -63,6 +63,7 @@ class CC_DLL CommandBuffer : public GFXObject, public RefCounted { virtual void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) = 0; virtual void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) = 0; virtual void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) = 0; + virtual void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) = 0; virtual void execute(CommandBuffer *const *cmdBuffs, uint32_t count) = 0; virtual void dispatch(const DispatchInfo &info) = 0; virtual void beginQuery(QueryPool *queryPool, uint32_t id) = 0; diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 943cc1242c1..ab5c7bd810f 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -175,9 +175,12 @@ enum class Feature : uint32_t { COMPUTE_SHADER, // @deprecated INPUT_ATTACHMENT_BENEFIT, + SUBPASS_COLOR_INPUT, SUBPASS_DEPTH_STENCIL_INPUT, RASTERIZATION_ORDER_NOCOHERENT, + + MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL, // resolve depth stencil COUNT, }; CC_ENUM_CONVERSION_OPERATOR(Feature); @@ -472,9 +475,10 @@ CC_ENUM_BITWISE_OPERATORS(TextureUsageBit); enum class TextureFlagBit : uint32_t { NONE = 0, GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter - GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments + GENERAL_LAYOUT = 0x2, // @deprecated, For inout framebuffer attachments EXTERNAL_OES = 0x4, // External oes texture EXTERNAL_NORMAL = 0x8, // External normal texture + LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. }; using TextureFlags = TextureFlagBit; CC_ENUM_BITWISE_OPERATORS(TextureFlagBit); @@ -492,10 +496,13 @@ using FormatFeature = FormatFeatureBit; CC_ENUM_BITWISE_OPERATORS(FormatFeatureBit); enum class SampleCount : uint32_t { - ONE, // Single sample - MULTIPLE_PERFORMANCE, // Multiple samples prioritizing performance over quality - MULTIPLE_BALANCE, // Multiple samples leveraging both quality and performance - MULTIPLE_QUALITY, // Multiple samples prioritizing quality over performance + X1 = 0x01, + X2 = 0x02, + X4 = 0x04, + X8 = 0x08, + X16 = 0x10, + X32 = 0x20, + X64 = 0x40 }; CC_ENUM_CONVERSION_OPERATOR(SampleCount); @@ -1064,7 +1071,7 @@ struct ALIGNAS(8) TextureInfo { TextureFlags flags{TextureFlagBit::NONE}; uint32_t layerCount{1}; uint32_t levelCount{1}; - SampleCount samples{SampleCount::ONE}; + SampleCount samples{SampleCount::X1}; uint32_t depth{1}; void *externalRes{nullptr}; // CVPixelBuffer for Metal, EGLImage for GLES #if CC_CPU_ARCH == CC_CPU_ARCH_32 @@ -1272,7 +1279,7 @@ struct InputAssemblerInfo { struct ALIGNAS(8) ColorAttachment { Format format{Format::UNKNOWN}; - SampleCount sampleCount{SampleCount::ONE}; + SampleCount sampleCount{SampleCount::X1}; LoadOp loadOp{LoadOp::CLEAR}; StoreOp storeOp{StoreOp::STORE}; GeneralBarrier *barrier{nullptr}; @@ -1284,7 +1291,7 @@ using ColorAttachmentList = ccstd::vector; struct ALIGNAS(8) DepthStencilAttachment { Format format{Format::UNKNOWN}; - SampleCount sampleCount{SampleCount::ONE}; + SampleCount sampleCount{SampleCount::X1}; LoadOp depthLoadOp{LoadOp::CLEAR}; StoreOp depthStoreOp{StoreOp::STORE}; LoadOp stencilLoadOp{LoadOp::CLEAR}; @@ -1327,6 +1334,7 @@ using SubpassDependencyList = ccstd::vector; struct RenderPassInfo { ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; + DepthStencilAttachment depthStencilResolveAttachment; SubpassInfoList subpasses; SubpassDependencyList dependencies; @@ -1386,6 +1394,7 @@ struct FramebufferInfo { RenderPass *renderPass{nullptr}; TextureList colorTextures; Texture *depthStencilTexture{nullptr}; // @ts-nullable + Texture *depthStencilResolveTexture{nullptr}; // @ts-nullable EXPOSE_COPY_FN(FramebufferInfo) }; diff --git a/native/cocos/renderer/gfx-base/GFXDef.cpp b/native/cocos/renderer/gfx-base/GFXDef.cpp index c7e35253f44..00a9bc6873e 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.cpp +++ b/native/cocos/renderer/gfx-base/GFXDef.cpp @@ -107,6 +107,7 @@ ccstd::hash_t Hasher::operator()(const RenderPassInfo &info) con ccstd::hash_t seed = 4; ccstd::hash_combine(seed, info.colorAttachments); ccstd::hash_combine(seed, info.depthStencilAttachment); + ccstd::hash_combine(seed, info.depthStencilResolveAttachment); ccstd::hash_combine(seed, info.subpasses); ccstd::hash_combine(seed, info.dependencies); return seed; @@ -115,6 +116,7 @@ ccstd::hash_t Hasher::operator()(const RenderPassInfo &info) con bool operator==(const RenderPassInfo &lhs, const RenderPassInfo &rhs) { return lhs.colorAttachments == rhs.colorAttachments && lhs.depthStencilAttachment == rhs.depthStencilAttachment && + lhs.depthStencilResolveAttachment == rhs.depthStencilResolveAttachment && lhs.subpasses == rhs.subpasses && lhs.dependencies == rhs.dependencies; } @@ -122,19 +124,17 @@ bool operator==(const RenderPassInfo &lhs, const RenderPassInfo &rhs) { template <> ccstd::hash_t Hasher::operator()(const FramebufferInfo &info) const { // render pass is mostly irrelevant - ccstd::hash_t seed; + ccstd::hash_t seed = static_cast(info.colorTextures.size()) + + static_cast(info.depthStencilTexture != nullptr) + + static_cast(info.depthStencilResolveTexture != nullptr); if (info.depthStencilTexture) { - seed = (static_cast(info.colorTextures.size()) + 1) * 3 + 1; - ccstd::hash_combine(seed, info.depthStencilTexture); - ccstd::hash_combine(seed, info.depthStencilTexture->getRaw()); - ccstd::hash_combine(seed, info.depthStencilTexture->getHash()); - } else { - seed = static_cast(info.colorTextures.size()) * 3 + 1; + ccstd::hash_combine(seed, info.depthStencilTexture->getObjectID()); + } + if (info.depthStencilResolveTexture) { + ccstd::hash_combine(seed, info.depthStencilResolveTexture->getObjectID()); } for (auto *colorTexture : info.colorTextures) { - ccstd::hash_combine(seed, colorTexture); - ccstd::hash_combine(seed, colorTexture->getRaw()); - ccstd::hash_combine(seed, colorTexture->getHash()); + ccstd::hash_combine(seed, colorTexture->getObjectID()); } ccstd::hash_combine(seed, info.renderPass->getHash()); return seed; @@ -149,6 +149,10 @@ bool operator==(const FramebufferInfo &lhs, const FramebufferInfo &rhs) { res = lhs.depthStencilTexture == rhs.depthStencilTexture; } + if (res) { + res = lhs.depthStencilResolveTexture == rhs.depthStencilResolveTexture; + } + if (res) { for (size_t i = 0; i < lhs.colorTextures.size(); ++i) { res = lhs.colorTextures[i]->getRaw() == rhs.colorTextures[i]->getRaw() && diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index c8e8805d26a..a19e4da5198 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -154,7 +154,7 @@ DefaultResource::DefaultResource(Device *device) { if (device->getCapabilities().max3DTextureSize >= 2) { _texture3D = device->createTexture({TextureType::TEX3D, TextureUsageBit::STORAGE | TextureUsageBit::SAMPLED | TextureUsageBit::TRANSFER_DST, - Format::RGBA8, 2, 2, TextureFlagBit::NONE, 1, 1, SampleCount::ONE, 2}); + Format::RGBA8, 2, 2, TextureFlagBit::NONE, 1, 1, SampleCount::X1, 2}); BufferTextureCopy region = {0, 0, 0, {0, 0, 0}, {2, 2, 2}, {0, 0, 1}}; device->copyBuffersToTexture(&bufferData, _texture3D, ®ion, 1); } diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index 9ab7df85557..e59e8c5041e 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -122,6 +122,12 @@ class CC_DLL Device : public RefCounted { void registerOnAcquireCallback(ExecuteMethod &&execute); virtual void enableAutoBarrier(bool en) { _options.enableBarrierDeduce = en; } + virtual SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + std::ignore = format; + std::ignore = usage; + std::ignore = flags; + return SampleCount::X1; + }; protected: static Device *instance; diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp index 1fd8b6cce16..dfbdd20430c 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp @@ -44,6 +44,7 @@ void Framebuffer::initialize(const FramebufferInfo &info) { _renderPass = info.renderPass; _colorTextures = info.colorTextures; _depthStencilTexture = info.depthStencilTexture; + _depthStencilResolveTexture = info.depthStencilResolveTexture; doInit(info); } @@ -54,6 +55,7 @@ void Framebuffer::destroy() { _renderPass = nullptr; _colorTextures.clear(); _depthStencilTexture = nullptr; + _depthStencilResolveTexture = nullptr; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.h b/native/cocos/renderer/gfx-base/GFXFramebuffer.h index 01a8b3a925b..21125fc1607 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.h +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.h @@ -45,6 +45,7 @@ class CC_DLL Framebuffer : public GFXObject, public RefCounted { inline RenderPass *getRenderPass() const { return _renderPass; } inline const TextureList &getColorTextures() const { return _colorTextures; } inline Texture *getDepthStencilTexture() const { return _depthStencilTexture; } + inline Texture *getDepthStencilResolveTexture() const { return _depthStencilResolveTexture; } protected: virtual void doInit(const FramebufferInfo &info) = 0; @@ -56,6 +57,7 @@ class CC_DLL Framebuffer : public GFXObject, public RefCounted { TextureList _colorTextures; // weak reference Texture *_depthStencilTexture{nullptr}; + Texture *_depthStencilResolveTexture{nullptr}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp index 7dff13380dd..91cb468c246 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp @@ -44,8 +44,8 @@ ccstd::hash_t RenderPass::computeHash() { for (const ColorAttachment &ca : _colorAttachments) { ccstd::hash_combine(seed, ca); } - const auto &ds = _depthStencilAttachment; - ccstd::hash_combine(seed, ds); + ccstd::hash_combine(seed, _depthStencilAttachment); + ccstd::hash_combine(seed, _depthStencilResolveAttachment); ccstd::hash_combine(seed, _subpasses); return seed; @@ -58,6 +58,7 @@ ccstd::hash_t RenderPass::computeHash(const RenderPassInfo &info) { void RenderPass::initialize(const RenderPassInfo &info) { _colorAttachments = info.colorAttachments; _depthStencilAttachment = info.depthStencilAttachment; + _depthStencilResolveAttachment = info.depthStencilResolveAttachment; _subpasses = info.subpasses; _dependencies = info.dependencies; _hash = computeHash(); diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.h b/native/cocos/renderer/gfx-base/GFXRenderPass.h index 12d606ecf6a..f51502c6326 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.h +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.h @@ -42,6 +42,7 @@ class CC_DLL RenderPass : public GFXObject, public RefCounted { inline const ColorAttachmentList &getColorAttachments() const { return _colorAttachments; } inline const DepthStencilAttachment &getDepthStencilAttachment() const { return _depthStencilAttachment; } + inline const DepthStencilAttachment &getDepthStencilResolveAttachment() const { return _depthStencilResolveAttachment; } inline const SubpassInfoList &getSubpasses() const { return _subpasses; } inline const SubpassDependencyList &getDependencies() const { return _dependencies; } inline ccstd::hash_t getHash() const { return _hash; } @@ -54,6 +55,7 @@ class CC_DLL RenderPass : public GFXObject, public RefCounted { ColorAttachmentList _colorAttachments; DepthStencilAttachment _depthStencilAttachment; + DepthStencilAttachment _depthStencilResolveAttachment; SubpassInfoList _subpasses; SubpassDependencyList _dependencies; ccstd::hash_t _hash = 0; diff --git a/native/cocos/renderer/gfx-base/GFXTexture.cpp b/native/cocos/renderer/gfx-base/GFXTexture.cpp index d8b6a7cde05..0f1a7c2c14d 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.cpp +++ b/native/cocos/renderer/gfx-base/GFXTexture.cpp @@ -128,11 +128,11 @@ void Texture::updateTextureInfo(const SwapchainTextureInfo &info, Texture *out) out->_info.layerCount = 1; out->_info.levelCount = 1; out->_info.depth = 1; - out->_info.samples = SampleCount::ONE; + out->_info.samples = SampleCount::X1; out->_info.flags = TextureFlagBit::NONE; - out->_info.usage = GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth + out->_info.usage = TextureUsageBit::SAMPLED | (GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth ? TextureUsageBit::DEPTH_STENCIL_ATTACHMENT - : TextureUsageBit::COLOR_ATTACHMENT; + : TextureUsageBit::COLOR_ATTACHMENT); out->_swapchain = info.swapchain; out->_size = formatSize(info.format, info.width, info.height, 1); out->_hash = computeHash(out); diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp index 8db04e5f6fc..8c2e17a36b1 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp @@ -99,6 +99,9 @@ void EmptyCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c void EmptyCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { } +void EmptyCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { +} + void EmptyCommandBuffer::dispatch(const DispatchInfo &info) { } diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h index f83d684b098..d429d23f61c 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h @@ -52,6 +52,7 @@ class CC_DLL EmptyCommandBuffer final : public CommandBuffer { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp index 5ee07a69a7c..daaf4efc6e9 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp @@ -316,6 +316,10 @@ void GLES2CommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, c // should not copy texture in a secondary command buffer } +void GLES2CommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + // should not copy texture in a secondary command buffer +} + void GLES2CommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { GLES2CmdBlitTexture *cmd = _cmdAllocator->blitTextureCmdPool.alloc(); if (srcTexture) cmd->gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h index 20e948ecbcf..06185861895 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h @@ -64,6 +64,7 @@ class CC_GLES2_API GLES2CommandBuffer : public CommandBuffer { void updateBuffer(Buffer *buff, const void *data, uint32_t size) override; void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override {} diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp index 2d7b38666fd..1d9ca68f441 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp @@ -574,22 +574,13 @@ void cmdFuncGLES2CreateTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) gpuTexture->glFormat = mapGLFormat(gpuTexture->format); gpuTexture->glType = formatToGLType(gpuTexture->format); gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); + gpuTexture->glSamples = static_cast(gpuTexture->samples); - if (gpuTexture->samples > SampleCount::ONE) { - if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE) { - GLint maxSamples; - glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); - - auto requestedSampleCount = static_cast(gpuTexture->samples); - gpuTexture->glSamples = std::min(maxSamples, requestedSampleCount); - - // skip multi-sampled attachment resources if we can use auto resolve - if (gpuTexture->usage == TextureUsageBit::COLOR_ATTACHMENT) { - gpuTexture->memoryless = true; - return; - } - } else { - gpuTexture->glSamples = 1; // fallback to single sample if the extensions is not available + if (gpuTexture->samples > SampleCount::X1) { + if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE && + hasFlag(gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED)) { + gpuTexture->memoryAllocated = false; + return; } } @@ -810,7 +801,7 @@ void cmdFuncGLES2DestroyTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture } void cmdFuncGLES2ResizeTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) { - if (gpuTexture->memoryless || gpuTexture->glTarget == GL_TEXTURE_EXTERNAL_OES) return; + if (!gpuTexture->memoryAllocated || gpuTexture->glTarget == GL_TEXTURE_EXTERNAL_OES) return; if (gpuTexture->glSamples <= 1) { switch (gpuTexture->type) { @@ -3042,6 +3033,12 @@ void cmdFuncGLES2ExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmdPackage) { } } +GLint cmdFuncGLES2GetMaxSampleCount() { + GLint maxSamples = 1; + GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples)); + return maxSamples; +} + void GLES2GPUBlitManager::initialize() { _gpuShader.name = "Blit Pass"; _gpuShader.blocks.push_back({ diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.h b/native/cocos/renderer/gfx-gles2/GLES2Commands.h index e87736708f9..670b8e3ae34 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.h @@ -246,5 +246,7 @@ void cmdFuncGLES2BlitTexture(GLES2Device *device, void cmdFuncGLES2ExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmdPackage); +GLint cmdFuncGLES2GetMaxSampleCount(); + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index 77404c2c066..38d0864da4b 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -176,6 +176,7 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { } } #endif + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = false; // not implement yet. ccstd::string compressedFmts; if (getFormatFeatures(Format::ETC_RGB8) != FormatFeature::NONE) { @@ -534,5 +535,12 @@ void GLES2Device::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, co cmdFuncGLES2CopyTextureToBuffers(this, static_cast(src)->gpuTexture(), buffers, region, count); } +SampleCount GLES2Device::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + std::ignore = format; + std::ignore = usage; + std::ignore = flags; + return static_cast(cmdFuncGLES2GetMaxSampleCount()); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.h b/native/cocos/renderer/gfx-gles2/GLES2Device.h index 44867f653a8..0b7269005f0 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.h @@ -95,7 +95,7 @@ class CC_GLES2_API GLES2Device final : public Device { // check the specified format is texture-exclusive (no renderbuffers allowed) inline bool isTextureExclusive(const Format &format) { return _textureExclusive[static_cast(format)]; }; - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static GLES2Device *instance; diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index 31057eec95b..99ce522f08d 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -118,10 +118,10 @@ struct GLES2GPUTexture { uint32_t size{0}; uint32_t arrayLayer{1}; uint32_t mipLevel{1}; - SampleCount samples{SampleCount::ONE}; + SampleCount samples{SampleCount::X1}; TextureFlags flags{TextureFlagBit::NONE}; bool isPowerOf2{false}; - bool memoryless{false}; + bool memoryAllocated{true}; // false if swapchain image or implicit ms render buffer. GLenum glTarget{0}; GLenum glInternalFmt{0}; GLenum glFormat{0}; diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp index 6336745e101..1c3832849a8 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp @@ -149,6 +149,10 @@ void GLES2PrimaryCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffe } } +void GLES2PrimaryCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + copyTexture(srcTexture, dstTexture, regions, count); +} + void GLES2PrimaryCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { GLES2GPUTexture *gpuTextureSrc = nullptr; GLES2GPUTexture *gpuTextureDst = nullptr; diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h index 358b3de968f..2a3411c9eef 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h @@ -46,6 +46,7 @@ class CC_GLES2_API GLES2PrimaryCommandBuffer final : public GLES2CommandBuffer { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; protected: diff --git a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp index ad127f1557c..2656dff1b46 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp @@ -59,7 +59,7 @@ void GLES2Texture::doInit(const TextureInfo & /*info*/) { cmdFuncGLES2CreateTexture(GLES2Device::getInstance(), _gpuTexture); - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize += _size; CC_PROFILE_MEMORY_INC(Texture, _size); } @@ -72,7 +72,7 @@ void GLES2Texture::doInit(const TextureViewInfo &info) { void GLES2Texture::doDestroy() { if (_gpuTexture) { if (!_isTextureView) { - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -85,7 +85,7 @@ void GLES2Texture::doDestroy() { } void GLES2Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -97,7 +97,7 @@ void GLES2Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { GLES2Device::getInstance()->framebufferHub()->update(_gpuTexture); - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES2Device::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_INC(Texture, size); } @@ -135,7 +135,7 @@ void GLES2Texture::doInit(const SwapchainTextureInfo & /*info*/) { _gpuTexture->samples = _info.samples; _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->memoryless = true; + _gpuTexture->memoryAllocated = false; _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index 6066660b980..706dd795a59 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -303,6 +303,10 @@ void GLES3CommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, c // should not copy texture in a secondary command buffer } +void GLES3CommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + // should not resolve texture in a secondary command buffer +} + void GLES3CommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { GLES3CmdBlitTexture *cmd = _cmdAllocator->blitTextureCmdPool.alloc(); if (srcTexture) cmd->gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h index 594a8e059f4..d42b50d43bc 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h @@ -64,6 +64,7 @@ class CC_GLES3_API GLES3CommandBuffer : public CommandBuffer { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const * /*buffers*/, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const * /*textures*/, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index a4ba060a41e..afddfc2d1a7 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -491,6 +491,18 @@ GLenum formatToGLType(Format format) { } } +GLenum getTextureTarget(TextureType type) { + switch (type) { + case TextureType::TEX2D: return GL_TEXTURE_2D; + case TextureType::TEX2D_ARRAY: return GL_TEXTURE_2D_ARRAY; + case TextureType::TEX3D: return GL_TEXTURE_3D; + case TextureType::CUBE: return GL_TEXTURE_CUBE_MAP; + default: + CC_ABORT(); + return GL_NONE; + } +} + uint32_t glComponentCount(GLenum glType) { switch (glType) { case GL_FLOAT_MAT2: @@ -575,17 +587,6 @@ const GLenum GL_MEMORY_ACCESS[] = { GL_WRITE_ONLY, GL_READ_WRITE, }; - -const GLint GL_SAMPLE_COUNT[] = { - 1, - 2, -#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_IOS - 4, -#else - 8, -#endif - 16, -}; } // namespace void cmdFuncGLES3CreateBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { @@ -800,31 +801,77 @@ void cmdFuncGLES3ResizeBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { } } -void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { - static ccstd::vector supportedSampleCounts; +static void renderBufferStorage(GLES3Device *device, GLES3GPUTexture *gpuTexture) { + CC_ASSERT(gpuTexture->type == TextureType::TEX2D); + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer != glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); + glRenderbuffer = gpuTexture->glRenderbuffer; + } + if (gpuTexture->glSamples > 1) { + GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } else { + GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } +} + +static void textureStorage(GLES3Device *device, GLES3GPUTexture *gpuTexture) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(gpuTexture->glTarget, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + uint32_t w = gpuTexture->width; + uint32_t h = gpuTexture->height; + uint32_t d = gpuTexture->type == TextureType::TEX2D_ARRAY ? gpuTexture->arrayLayer : gpuTexture->depth; + + switch (gpuTexture->type) { + case TextureType::CUBE: + CC_ASSERT(gpuTexture->glSamples <= 1); + case TextureType::TEX2D: + if (gpuTexture->glSamples > 1 && !gpuTexture->immutable && device->constantRegistry()->glMinorVersion >= 1) { + gpuTexture->glTarget = GL_TEXTURE_2D_MULTISAMPLE; + GL_CHECK(glTexStorage2DMultisample(gpuTexture->glTarget, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, GL_FALSE)); + } else { + GL_CHECK(glTexStorage2D(gpuTexture->glTarget, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); + } + break; + case TextureType::TEX3D: + CC_ASSERT(gpuTexture->glSamples <= 1); + case TextureType::TEX2D_ARRAY: + if (gpuTexture->glSamples > 1 && !gpuTexture->immutable && device->constantRegistry()->glMinorVersion >= 1) { + gpuTexture->glTarget = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; + GL_CHECK(glTexStorage3DMultisample(gpuTexture->glTarget, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, d, GL_FALSE)); + } else { + GL_CHECK(glTexStorage3D(gpuTexture->glTarget, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); + } + break; + default: + break; + } +} +static bool useRenderBuffer(const GLES3Device *device, Format format, TextureUsage usage) { + return !device->isTextureExclusive(format) && + hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT, usage); +} + +void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); gpuTexture->glFormat = mapGLFormat(gpuTexture->format); gpuTexture->glType = formatToGLType(gpuTexture->format); - if (gpuTexture->samples > SampleCount::ONE) { - GLint supportedSampleCountCount = 0; - GL_CHECK(glGetInternalformativ(GL_RENDERBUFFER, gpuTexture->glInternalFmt, GL_SAMPLES, 1, &supportedSampleCountCount)); - supportedSampleCounts.resize(supportedSampleCountCount); - GL_CHECK(glGetInternalformativ(GL_RENDERBUFFER, gpuTexture->glInternalFmt, GL_SAMPLES, supportedSampleCountCount, supportedSampleCounts.data())); - - auto requestedSampleCount = GL_SAMPLE_COUNT[toNumber(gpuTexture->samples)]; - for (GLint sampleCount : supportedSampleCounts) { - if (sampleCount <= requestedSampleCount) { - gpuTexture->glSamples = sampleCount; - break; - } - } + bool supportRenderBufferMS = device->constantRegistry()->mMSRT > MSRTSupportLevel::NONE; + gpuTexture->useRenderBuffer = useRenderBuffer(device, gpuTexture->format, gpuTexture->usage) && + (gpuTexture->glSamples <= 1 || supportRenderBufferMS); - // skip multi-sampled attachment resources if we can use auto resolve - if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE && - gpuTexture->usage == TextureUsageBit::COLOR_ATTACHMENT) { - gpuTexture->memoryless = true; + if (gpuTexture->glSamples > 1) { + // Allocate render buffer when binding a framebuffer if the MSRT extension is not present. + if (gpuTexture->useRenderBuffer && + hasFlag(gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED)) { + gpuTexture->glTarget = GL_RENDERBUFFER; + gpuTexture->memoryAllocated = false; return; } } @@ -838,97 +885,18 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) return; } - if (!device->isTextureExclusive(gpuTexture->format) && (gpuTexture->glSamples > 1 || hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT, gpuTexture->usage))) { - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_RENDERBUFFER; - GL_CHECK(glGenRenderbuffers(1, &gpuTexture->glRenderbuffer)); - if (gpuTexture->size > 0) { - GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; - if (gpuTexture->glRenderbuffer != glRenderbuffer) { - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); - glRenderbuffer = gpuTexture->glRenderbuffer; - } - if (gpuTexture->glSamples > 1) { - GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } else { - GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } - } - break; - } - default: - CC_ABORT(); - break; - } + if (gpuTexture->size == 0) { + return; + } + + if (gpuTexture->useRenderBuffer) { + gpuTexture->glTarget = GL_RENDERBUFFER; + GL_CHECK(glGenRenderbuffers(1, &gpuTexture->glRenderbuffer)); + renderBufferStorage(device, gpuTexture); } else { - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_TEXTURE_2D; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - GL_CHECK(glTexStorage2D(GL_TEXTURE_2D, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); - } - break; - } - case TextureType::TEX2D_ARRAY: { - gpuTexture->glTarget = GL_TEXTURE_2D_ARRAY; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - uint32_t d = gpuTexture->arrayLayer; - GL_CHECK(glTexStorage3D(GL_TEXTURE_2D_ARRAY, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); - } - break; - } - case TextureType::TEX3D: { - gpuTexture->glTarget = GL_TEXTURE_3D; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_3D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - uint32_t d = gpuTexture->depth; - GL_CHECK(glTexStorage3D(GL_TEXTURE_3D, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); - } - break; - } - case TextureType::CUBE: { - gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint32_t w = gpuTexture->width; - uint32_t h = gpuTexture->height; - GL_CHECK(glTexStorage2D(GL_TEXTURE_CUBE_MAP, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); - } - break; - } - default: - CC_ABORT(); - break; - } + gpuTexture->glTarget = getTextureTarget(gpuTexture->type); + GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); + textureStorage(device, gpuTexture); } } @@ -957,36 +925,18 @@ void cmdFuncGLES3DestroyTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture } void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { - if (gpuTexture->memoryless || hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES) || + if (!gpuTexture->memoryAllocated || + hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES) || hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_NORMAL)) { return; } - if (gpuTexture->glSamples <= 1) { + if (!gpuTexture->useRenderBuffer) { // immutable by default cmdFuncGLES3DestroyTexture(device, gpuTexture); cmdFuncGLES3CreateTexture(device, gpuTexture); - } else { - switch (gpuTexture->type) { - case TextureType::TEX2D: { - if (gpuTexture->size > 0) { - GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; - if (gpuTexture->glRenderbuffer != glRenderbuffer) { - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); - glRenderbuffer = gpuTexture->glRenderbuffer; - } - if (gpuTexture->glSamples > 1) { - GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } else { - GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); - } - } - break; - } - default: - CC_ABORT(); - break; - } + } else if (gpuTexture->size > 0){ + renderBufferStorage(device, gpuTexture); } } @@ -1450,6 +1400,10 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * } for (auto &resolve : sub.resolves) { + if (resolve == INVALID_BINDING) { + gpuRenderPass->resolves.emplace_back(resolve); + continue; + } auto &index = gpuRenderPass->indices[resolve]; if (index == INVALID_BINDING) { index = static_cast(gpuRenderPass->resolves.size()); @@ -1458,6 +1412,7 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * } gpuRenderPass->depthStencil = sub.depthStencil; + gpuRenderPass->depthStencilResolve = sub.depthStencilResolve; } } @@ -1514,187 +1469,168 @@ void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GPUInputAssembl gpuInputAssembler->glVAOs.clear(); } -static GLES3GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES3Device *device, - const ccstd::vector &attachments, const uint32_t *colors, size_t colorCount, - const GLES3GPUTextureView *depthStencilView, - const uint32_t *resolves = nullptr, - const GLES3GPUTextureView *depthStencilResolveView = nullptr, - GLbitfield *resolveMask = nullptr) { - static ccstd::vector drawBuffers; - GLES3GPUStateCache *cache = device->stateCache(); - GLES3GPUFramebuffer::GLFramebufferInfo res; - - GL_CHECK(glGenFramebuffers(1, &res.glFramebuffer)); - if (cache->glDrawFramebuffer != res.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, res.glFramebuffer)); - cache->glDrawFramebuffer = res.glFramebuffer; - } - - drawBuffers.clear(); - - auto supportLevel = device->constantRegistry()->mMSRT; - bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); - - for (size_t j = 0; j < colorCount; ++j) { - GLES3GPUTextureView *gpuColorTextureView = attachments[colors[j]]; - GLES3GPUTextureView *gpuResolveTextureView = resolves ? attachments[resolves[j]] : nullptr; - GLES3GPUTexture *gpuColorTexture = gpuColorTextureView->gpuTexture; - GLES3GPUTexture *gpuResolveTexture = resolves ? gpuResolveTextureView->gpuTexture : nullptr; - - drawBuffers.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); - - if (gpuResolveTexture) { - if (autoResolve) { - GL_CHECK(glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), - gpuResolveTexture->glTarget, gpuResolveTexture->glTexture, - gpuResolveTextureView->baseLevel, gpuColorTexture->glSamples)); +static GLES3GPUSwapchain *getSwapchainIfExists(const ccstd::vector &textureViews, const uint32_t *indices, size_t count) { + GLES3GPUSwapchain *swapchain{nullptr}; + if (indices) { + for (size_t i = 0; i < count; ++i) { + if (indices[i] == INVALID_BINDING) { continue; } - *resolveMask |= GL_COLOR_BUFFER_BIT; // fallback to blit-based manual resolve - } - if (gpuColorTexture) { - if (gpuColorTexture->glTexture) { - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), - gpuColorTexture->glTarget, gpuColorTexture->glTexture, gpuColorTextureView->baseLevel)); - } else { - GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), - gpuColorTexture->glTarget, gpuColorTexture->glRenderbuffer)); + auto *colorTexture = textureViews[indices[i]]->gpuTexture; + if (colorTexture->swapchain) { + swapchain = colorTexture->swapchain; } } - res.width = std::min(res.width, gpuColorTexture->width); - res.height = std::min(res.height, gpuColorTexture->height); } + return swapchain; +} - GLES3GPUTexture *depthStencil = depthStencilView ? depthStencilView->gpuTexture : nullptr; - GLES3GPUTexture *depthStencilResolve = depthStencilResolveView ? depthStencilResolveView->gpuTexture : nullptr; - if (depthStencil) { - bool hasStencil = GFX_FORMAT_INFOS[static_cast(depthStencil->format)].hasStencil; - GLenum glAttachment = hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT; - if (depthStencil->glTexture) { - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glTexture, depthStencilView->baseLevel)); - } else if (depthStencil->glRenderbuffer) { - GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glRenderbuffer)); - } - - // fallback to blit-based manual resolve - if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; - res.width = std::min(res.width, depthStencil->width >> depthStencilView->baseLevel); - res.height = std::min(res.height, depthStencil->height >> depthStencilView->baseLevel); +static GLbitfield getColorBufferMask(Format format) { + GLbitfield mask = 0U; + const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(format)]; + if (info.hasDepth || info.hasStencil) { + if (info.hasDepth) mask |= GL_DEPTH_BUFFER_BIT; + if (info.hasStencil) mask |= GL_STENCIL_BUFFER_BIT; + } else { + mask = GL_COLOR_BUFFER_BIT; } + return mask; +} - // register to framebuffer caches - if (colorCount == 1) device->framebufferCacheMap()->registerExternal(res.glFramebuffer, attachments[colors[0]]->gpuTexture, 0); - if (depthStencil) device->framebufferCacheMap()->registerExternal(res.glFramebuffer, depthStencilView->gpuTexture, 0); +static void doResolve(GLES3Device *device, GLES3GPUFramebuffer *gpuFbo) { + device->context()->makeCurrent(gpuFbo->resolveFramebuffer.swapchain, gpuFbo->framebuffer.swapchain); + auto *cache = device->stateCache(); + auto width = gpuFbo->width; + auto height = gpuFbo->height; - GL_CHECK(glDrawBuffers(utils::toUint(drawBuffers.size()), drawBuffers.data())); + if (cache->glReadFramebuffer != gpuFbo->framebuffer.handle) { + GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, gpuFbo->framebuffer.handle)); + cache->glReadFramebuffer = gpuFbo->framebuffer.handle; + } - GLenum status; - GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - if (status != GL_FRAMEBUFFER_COMPLETE) { - switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); - break; - default: - CC_LOG_ERROR("checkFramebufferStatus() - %x", status); - break; - } + if (cache->glDrawFramebuffer != gpuFbo->resolveFramebuffer.handle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gpuFbo->resolveFramebuffer.handle)); + cache->glDrawFramebuffer = gpuFbo->resolveFramebuffer.handle; } - return res; -} + gpuFbo->resolveFramebuffer.processLoad(GL_DRAW_FRAMEBUFFER); -static GLES3GPUSwapchain *getSwapchainIfExists(const ccstd::vector &textureViews, const uint32_t *indices, size_t count) { - GLES3GPUSwapchain *swapchain{nullptr}; - if (indices) { - size_t offscreenCount{0}; - for (size_t i = 0; i < count; ++i) { - auto *colorTexture = textureViews[indices[i]]->gpuTexture; - if (colorTexture->swapchain) { - swapchain = colorTexture->swapchain; - } else { - ++offscreenCount; + if (!gpuFbo->colorBlitPairs.empty()) { + auto resolveColorNum = gpuFbo->resolveFramebuffer.colors.size(); + std::vector drawBuffers(resolveColorNum, GL_NONE); + for (auto &[src, dst] : gpuFbo->colorBlitPairs) { + drawBuffers[dst] = GL_COLOR_ATTACHMENT0 + dst; + GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0 + src)); + if (gpuFbo->resolveFramebuffer.handle != 0) { + GL_CHECK(glDrawBuffers(resolveColorNum, drawBuffers.data())); } + + GL_CHECK(glBlitFramebuffer( + 0, 0, width, height, + 0, 0, width, height, + GL_COLOR_BUFFER_BIT, GL_NEAREST)); + drawBuffers[dst] = GL_NONE; } - CC_ASSERT(!offscreenCount || offscreenCount == count); } - return swapchain; + if (gpuFbo->dsResolveMask != 0 && gpuFbo->resolveFramebuffer.handle != 0) { + GL_CHECK(glBlitFramebuffer( + 0, 0, width, height, + 0, 0, width, height, + gpuFbo->dsResolveMask, GL_NEAREST)); + } + + gpuFbo->framebuffer.processStore(GL_READ_FRAMEBUFFER); + gpuFbo->resolveFramebuffer.processStore(GL_DRAW_FRAMEBUFFER); } -static void doCreateFramebufferInstance(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO, const ccstd::vector &colors, - uint32_t depthStencil, GLES3GPUFramebuffer::Framebuffer *outFBO, - const uint32_t *resolves = nullptr, uint32_t depthStencilResolve = INVALID_BINDING) { - GLES3GPUSwapchain *swapchain{getSwapchainIfExists(gpuFBO->gpuColorViews, colors.data(), colors.size())}; - if (!swapchain) { - const GLES3GPUTextureView *depthStencilTextureView = nullptr; - if (depthStencil != INVALID_BINDING) { - depthStencilTextureView = depthStencil < gpuFBO->gpuColorViews.size() - ? gpuFBO->gpuColorViews[depthStencil] - : gpuFBO->gpuDepthStencilView; - } - const GLES3GPUTextureView *depthStencilResolveTextureView = nullptr; - if (depthStencilResolve != INVALID_BINDING) { - depthStencilResolveTextureView = depthStencilResolve < gpuFBO->gpuColorViews.size() - ? gpuFBO->gpuColorViews[depthStencilResolve] - : gpuFBO->gpuDepthStencilView; - } - - outFBO->framebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorViews, colors.data(), utils::toUint(colors.size()), - depthStencilTextureView, resolves, depthStencilResolveTextureView, &outFBO->resolveMask)); - if (outFBO->resolveMask) { - size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? utils::toUint(colors.size()) : 0U; - GLES3GPUSwapchain *resolveSwapchain{getSwapchainIfExists(gpuFBO->gpuColorViews, resolves, resolveCount)}; - if (!resolveSwapchain) { - outFBO->resolveFramebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorViews, resolves, resolveCount, depthStencilResolveTextureView)); +void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { + const auto *renderPass = gpuFBO->gpuRenderPass; + const auto &colors = renderPass->colors; + const auto &resolves = renderPass->resolves; + const auto &indices = renderPass->indices; + const auto depthStencil = renderPass->depthStencil; + const auto depthStencilResolve = renderPass->depthStencilResolve; + + gpuFBO->framebuffer.initialize(getSwapchainIfExists(gpuFBO->gpuColorViews, colors.data(), colors.size())); + gpuFBO->resolveFramebuffer.initialize(getSwapchainIfExists(gpuFBO->gpuColorViews, resolves.data(), resolves.size())); + + auto supportLevel = device->constantRegistry()->mMSRT; + /* + * LEVEL0 does ont support on-chip resolve + * LEVEL1 only support COLOR_ATTACHMENT0 + * LEVEL2 support COLOR_ATTACHMENT(i) + DEPTH_STENCIL + */ + uint32_t supportCount = supportLevel > MSRTSupportLevel::LEVEL1 ? 255 : static_cast(supportLevel); + constexpr bool useDsResolve = true; + + uint32_t resolveColorIndex = 0; + for (uint32_t i = 0; i < colors.size(); ++i) { + const auto &attachmentIndex = colors[i]; + const auto &colorIndex = indices[attachmentIndex]; + const auto &resolveIndex = resolves.empty() ? INVALID_BINDING : resolves[attachmentIndex]; + + const auto &desc = renderPass->colorAttachments[attachmentIndex]; + const auto *view = gpuFBO->gpuColorViews[attachmentIndex]; + CC_ASSERT(view != nullptr); + + // need to resolve + if (view->gpuTexture->glSamples > 1 && resolveIndex != INVALID_BINDING) { + const auto &resolveDesc = renderPass->colorAttachments[resolveIndex]; + const auto *resolveView = gpuFBO->gpuColorViews[resolveIndex]; + CC_ASSERT(resolveView != nullptr); + bool lazilyAllocated = hasFlag(view->gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED); + + if (lazilyAllocated && // MS attachment should be memoryless + resolveView->gpuTexture->swapchain == nullptr && // not back buffer + i < supportCount) { // extension limit + gpuFBO->framebuffer.bindColorMultiSample(resolveView, colorIndex, view->gpuTexture->glSamples, resolveDesc); } else { - outFBO->resolveFramebuffer.initialize(resolveSwapchain); + // implicit MS not supported, fallback to MS Renderbuffer + gpuFBO->colorBlitPairs.emplace_back(colorIndex, resolveColorIndex); + gpuFBO->framebuffer.bindColor(view, colorIndex, desc); + gpuFBO->resolveFramebuffer.bindColor(resolveView, resolveColorIndex++, resolveDesc); } + continue; } - } else { - outFBO->framebuffer.initialize(swapchain); + gpuFBO->framebuffer.bindColor(view, colorIndex, desc); } -} -void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { - const auto &colors = gpuFBO->gpuRenderPass->colors; - const auto &resolves = gpuFBO->gpuRenderPass->resolves; - const auto &depthStencil = gpuFBO->gpuRenderPass->depthStencil; + if (depthStencil != INVALID_BINDING) { + const auto &desc = renderPass->depthStencilAttachment; + const auto *view = gpuFBO->gpuDepthStencilView; + CC_ASSERT(view != nullptr); - doCreateFramebufferInstance(device, gpuFBO, colors, depthStencil, &gpuFBO->frameBuffer, resolves.empty() ? nullptr : resolves.data()); -} + if (view->gpuTexture->glSamples > 1 && depthStencilResolve != INVALID_BINDING) { + const auto &resolveDesc = renderPass->depthStencilResolveAttachment; + const auto *resolveView = gpuFBO->gpuDepthStencilResolveView; + bool lazilyAllocated = hasFlag(view->gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED); -void GLES3GPUFramebuffer::GLFramebuffer::destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap) { - if (swapchain) { - swapchain = nullptr; - } else { - if (cache->glDrawFramebuffer == _glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); - cache->glDrawFramebuffer = 0; + if (lazilyAllocated && // MS attachment should be memoryless + resolveView->gpuTexture->swapchain == nullptr && // not back buffer + supportCount > 1 && // extension limit + useDsResolve) { // enable ds resolve + gpuFBO->framebuffer.bindDepthStencilMultiSample(resolveView, view->gpuTexture->glSamples, resolveDesc); + } else { + // implicit MS not supported, fallback to MS Renderbuffer + gpuFBO->dsResolveMask = getColorBufferMask(desc.format); + gpuFBO->framebuffer.bindDepthStencil(view, desc); + gpuFBO->resolveFramebuffer.bindDepthStencil(resolveView, resolveDesc); + } + } else { + gpuFBO->framebuffer.bindDepthStencil(view, desc); } - GL_CHECK(glDeleteFramebuffers(1, &_glFramebuffer)); - framebufferCacheMap->unregisterExternal(_glFramebuffer); - _glFramebuffer = 0U; } + + gpuFBO->framebuffer.finalize(device->stateCache()); + gpuFBO->resolveFramebuffer.finalize(device->stateCache()); } void cmdFuncGLES3DestroyFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { auto *cache = device->stateCache(); auto *framebufferCacheMap = device->framebufferCacheMap(); - gpuFBO->frameBuffer.framebuffer.destroy(cache, framebufferCacheMap); - gpuFBO->frameBuffer.resolveFramebuffer.destroy(cache, framebufferCacheMap); + gpuFBO->framebuffer.destroy(cache, framebufferCacheMap); + gpuFBO->resolveFramebuffer.destroy(cache, framebufferCacheMap); } void completeBarrier(GLES3GPUGeneralBarrier *barrier) { @@ -1856,7 +1792,6 @@ void cmdFuncGLES3Query(GLES3Device * /*device*/, GLES3QueryPool *queryPool, GLES void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRenderPass, GLES3GPUFramebuffer *gpuFramebuffer, const Rect *renderArea, const Color *clearColors, float clearDepth, uint32_t clearStencil) { - ccstd::vector invalidAttachments; GLES3GPUStateCache *cache = device->stateCache(); GLES3ObjectCache &gfxStateCache = cache->gfxStateCache; gfxStateCache.subpassIdx = 0; @@ -1868,14 +1803,18 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen gfxStateCache.clearStencil = clearStencil; if (gpuFramebuffer && gpuRenderPass) { - auto &instance = gpuFramebuffer->frameBuffer; + auto &framebuffer = gpuFramebuffer->framebuffer; + auto &resolveFramebuffer = gpuFramebuffer->resolveFramebuffer; + if (gpuFramebuffer->resolveFramebuffer.isActive()) { + device->context()->makeCurrent(resolveFramebuffer.swapchain, framebuffer.swapchain); + } else { + device->context()->makeCurrent(framebuffer.swapchain); + } - GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); - device->context()->makeCurrent(instance.framebuffer.swapchain, instance.framebuffer.swapchain); - if (cache->glDrawFramebuffer != glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glFramebuffer)); - cache->glDrawFramebuffer = glFramebuffer; + if (cache->glDrawFramebuffer != framebuffer.handle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer.handle)); + cache->glDrawFramebuffer = framebuffer.handle; } if (cache->viewport.left != renderArea->x || @@ -1895,38 +1834,27 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen } GLbitfield glClears = 0; - invalidAttachments.clear(); - float fColors[4]{}; bool maskSet = false; auto performLoadOp = [&](uint32_t attachmentIndex, uint32_t glAttachmentIndex) { const ColorAttachment &colorAttachment = gpuRenderPass->colorAttachments[attachmentIndex]; - if (colorAttachment.format != Format::UNKNOWN) { - switch (colorAttachment.loadOp) { - case LoadOp::LOAD: break; // GL default behaviour - case LoadOp::CLEAR: { - if (!maskSet && cache->bs.targets[0].blendColorMask != ColorMask::ALL) { - GL_CHECK(glColorMask(true, true, true, true)); - maskSet = true; - } + if (colorAttachment.format != Format::UNKNOWN && colorAttachment.loadOp == LoadOp::CLEAR) { + if (!maskSet && cache->bs.targets[0].blendColorMask != ColorMask::ALL) { + GL_CHECK(glColorMask(true, true, true, true)); + maskSet = true; + } - const Color &color = clearColors[attachmentIndex]; - if (glFramebuffer) { - fColors[0] = color.x; - fColors[1] = color.y; - fColors[2] = color.z; - fColors[3] = color.w; - GL_CHECK(glClearBufferfv(GL_COLOR, glAttachmentIndex, fColors)); - } else { - GL_CHECK(glClearColor(color.x, color.y, color.z, color.w)); - glClears |= GL_COLOR_BUFFER_BIT; - } - } break; - case LoadOp::DISCARD: - // invalidate fbo - invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); - break; + const Color &color = clearColors[attachmentIndex]; + if (framebuffer.handle) { + fColors[0] = color.x; + fColors[1] = color.y; + fColors[2] = color.z; + fColors[3] = color.w; + GL_CHECK(glClearBufferfv(GL_COLOR, glAttachmentIndex, fColors)); + } else { + GL_CHECK(glClearColor(color.x, color.y, color.z, color.w)); + glClears |= GL_COLOR_BUFFER_BIT; } } }; @@ -1940,43 +1868,25 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen depthLoadOp = stencilLoadOp = gpuRenderPass->colorAttachments[attachmentIndex].loadOp; hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; } - switch (gpuRenderPass->depthStencilAttachment.depthLoadOp) { - case LoadOp::LOAD: break; // GL default behaviour - case LoadOp::CLEAR: - if (!cache->dss.depthWrite) { - GL_CHECK(glDepthMask(true)); - } - GL_CHECK(glClearDepthf(clearDepth)); - glClears |= GL_DEPTH_BUFFER_BIT; - break; - case LoadOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH); - break; + if (gpuRenderPass->depthStencilAttachment.depthLoadOp == LoadOp::CLEAR) { + if (!cache->dss.depthWrite) { + GL_CHECK(glDepthMask(true)); + } + GL_CHECK(glClearDepthf(clearDepth)); + glClears |= GL_DEPTH_BUFFER_BIT; } - if (hasStencils) { - switch (gpuRenderPass->depthStencilAttachment.depthLoadOp) { - case LoadOp::LOAD: break; // GL default behaviour - case LoadOp::CLEAR: { - if (!cache->dss.stencilWriteMaskFront) { - GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); - } - if (!cache->dss.stencilWriteMaskBack) { - GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); - } - GL_CHECK(glClearStencil(clearStencil)); - glClears |= GL_STENCIL_BUFFER_BIT; - } break; - case LoadOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL); - break; + if (hasStencils && gpuRenderPass->depthStencilAttachment.depthLoadOp == LoadOp::CLEAR) { + if (!cache->dss.stencilWriteMaskFront) { + GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); + } + if (!cache->dss.stencilWriteMaskBack) { + GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); } + GL_CHECK(glClearStencil(clearStencil)); + glClears |= GL_STENCIL_BUFFER_BIT; } } - if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); - } - if (glClears) { GL_CHECK(glClear(glClears)); } @@ -2010,6 +1920,8 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen performLoadOp(i, indices[i]); } performDepthStencilLoadOp(gpuRenderPass->depthStencil); + + framebuffer.processLoad(GL_DRAW_FRAMEBUFFER); } } @@ -2031,113 +1943,14 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { GLES3GPUStateCache *cache = device->stateCache(); GLES3ObjectCache &gfxStateCache = cache->gfxStateCache; - GLES3GPURenderPass *gpuRenderPass = gfxStateCache.gpuRenderPass; GLES3GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; - const auto &instance = gpuFramebuffer->frameBuffer; - const SubpassInfo &subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; - - GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); - GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); - GLenum invalidateTarget = GL_DRAW_FRAMEBUFFER; - - auto performStoreOp = [&](uint32_t attachmentIndex, uint32_t glAttachmentIndex) { - const ColorAttachment &colorAttachment = gpuRenderPass->colorAttachments[attachmentIndex]; - if (colorAttachment.format != Format::UNKNOWN) { - switch (colorAttachment.storeOp) { - case StoreOp::STORE: break; - case StoreOp::DISCARD: - // invalidate fbo - invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); - break; - } - } - }; - - auto performDepthStencilStoreOp = [&](uint32_t attachmentIndex) { - if (attachmentIndex != INVALID_BINDING) { - StoreOp depthStoreOp = gpuRenderPass->depthStencilAttachment.depthStoreOp; - StoreOp stencilStoreOp = gpuRenderPass->depthStencilAttachment.stencilStoreOp; - bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; - if (attachmentIndex < gpuRenderPass->colorAttachments.size()) { - depthStoreOp = stencilStoreOp = gpuRenderPass->colorAttachments[attachmentIndex].storeOp; - hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; - } - switch (gpuRenderPass->depthStencilAttachment.depthStoreOp) { - case StoreOp::STORE: break; - case StoreOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH); - break; - } - if (hasStencils) { - switch (gpuRenderPass->depthStencilAttachment.stencilStoreOp) { - case StoreOp::STORE: break; - case StoreOp::DISCARD: - invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL); - break; - } - } - } - - if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(invalidateTarget, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); - } - }; - - if (instance.resolveMask) { - device->context()->makeCurrent(instance.resolveFramebuffer.swapchain, instance.framebuffer.swapchain); - - if (cache->glReadFramebuffer != glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, glFramebuffer)); - cache->glReadFramebuffer = glFramebuffer; - } - - if (cache->glDrawFramebuffer != glResolveFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glResolveFramebuffer)); - cache->glDrawFramebuffer = glResolveFramebuffer; - } - - if (instance.resolveMask & GL_COLOR_BUFFER_BIT) { - for (uint32_t i = 0; i < subpass.colors.size(); ++i) { - auto attachment = static_cast(GL_COLOR_ATTACHMENT0 + i); - GL_CHECK(glReadBuffer(attachment)); - GL_CHECK(glDrawBuffers(1, &attachment)); - - GLES3GPUTexture *srcTex = gpuFramebuffer->gpuColorViews[subpass.colors[i]]->gpuTexture; - GLES3GPUTexture *dstTex = gpuFramebuffer->gpuColorViews[subpass.resolves[i]]->gpuTexture; - - ensureScissorRect(cache, 0, 0, dstTex->width, dstTex->height); - GL_CHECK(glBlitFramebuffer( - 0, 0, srcTex->width, srcTex->height, - 0, 0, dstTex->width, dstTex->height, - GL_COLOR_BUFFER_BIT, GL_NEAREST)); - } - } - - if (instance.resolveMask & GL_DEPTH_BUFFER_BIT) { - GLES3GPUTexture *srcTex = subpass.depthStencil < gpuFramebuffer->gpuColorViews.size() - ? gpuFramebuffer->gpuColorViews[subpass.depthStencil]->gpuTexture - : gpuFramebuffer->gpuDepthStencilView->gpuTexture; - GLES3GPUTexture *dstTex = subpass.depthStencilResolve < gpuFramebuffer->gpuColorViews.size() - ? gpuFramebuffer->gpuColorViews[subpass.depthStencilResolve]->gpuTexture - : gpuFramebuffer->gpuDepthStencilView->gpuTexture; - - ensureScissorRect(cache, 0, 0, dstTex->width, dstTex->height); - GL_CHECK(glBlitFramebuffer( - 0, 0, srcTex->width, srcTex->height, - 0, 0, dstTex->width, dstTex->height, - instance.resolveMask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT), GL_NEAREST)); - } - - invalidateTarget = GL_READ_FRAMEBUFFER; + if (gpuFramebuffer->resolveFramebuffer.isActive()) { + doResolve(device, gpuFramebuffer); + } else { + gpuFramebuffer->framebuffer.processStore(GL_DRAW_FRAMEBUFFER); } - const auto &attachments = gpuRenderPass->colorAttachments; - const auto &indices = gpuRenderPass->indices; - for (uint32_t i = 0; i < attachments.size(); ++i) { - performStoreOp(i, indices[i]); - } - performDepthStencilStoreOp(gpuRenderPass->depthStencil); // if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { // GL_CHECK(glFramebufferFetchBarrierEXT()); // } else if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { @@ -2362,6 +2175,10 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli const GLES3GPUUniformBuffer &glBuffer = gpuPipelineState->gpuShader->glBuffers[j]; const GLES3GPUDescriptorSet *gpuDescriptorSet = gpuDescriptorSets[glBuffer.set]; + if (gpuDescriptorSet == nullptr) { + continue; + } + const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glBuffer.binding); const GLES3GPUDescriptor &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; @@ -2817,7 +2634,7 @@ uint8_t *funcGLES3PixelBufferPick(const uint8_t *buffer, Format format, uint32_t } void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const *buffers, GLES3GPUTexture *gpuTexture, const BufferTextureCopy *regions, uint32_t count) { - if (gpuTexture->memoryless) return; + if (!gpuTexture->memoryAllocated) return; GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; if (glTexture != gpuTexture->glTexture) { @@ -3065,15 +2882,7 @@ void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc const TextureBlit *regions, uint32_t count, Filter filter) { GLES3GPUStateCache *cache = device->stateCache(); - GLbitfield mask = 0U; - const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(gpuTextureSrc->format)]; - if (info.hasDepth || info.hasStencil) { - if (info.hasDepth) mask |= GL_DEPTH_BUFFER_BIT; - if (info.hasStencil) mask |= GL_STENCIL_BUFFER_BIT; - } else { - mask = GL_COLOR_BUFFER_BIT; - } - + GLbitfield mask = getColorBufferMask(gpuTextureSrc->format); for (uint32_t i = 0U; i < count; ++i) { const TextureBlit ®ion = regions[i]; @@ -3184,6 +2993,180 @@ void cmdFuncGLES3ExecuteCmds(GLES3Device *device, GLES3CmdPackage *cmdPackage) { } } +void GLES3GPUFramebufferObject::initialize(GLES3GPUSwapchain *swc) { + swapchain = swc; +} + +void GLES3GPUFramebufferObject::bindColor(const GLES3GPUTextureView *texture, uint32_t colorIndex, const ColorAttachment &attachment) { + bindColorMultiSample(texture, colorIndex, 1, attachment); +} + +void GLES3GPUFramebufferObject::bindColorMultiSample(const GLES3GPUTextureView *texture, uint32_t colorIndex, GLint samples, const ColorAttachment &attachment) { + if (colorIndex >= colors.size()) { + colors.resize(colorIndex + 1); + } + bool isDefaultFb = swapchain != nullptr; + + if (attachment.loadOp == LoadOp::DISCARD) { + loadInvalidates.emplace_back(isDefaultFb ? GL_COLOR : GL_COLOR_ATTACHMENT0 + colorIndex); + } + if (attachment.storeOp == StoreOp::DISCARD) { + storeInvalidates.emplace_back(isDefaultFb ? GL_COLOR : GL_COLOR_ATTACHMENT0 + colorIndex); + } + colors[colorIndex] = {texture, samples}; +} + +void GLES3GPUFramebufferObject::bindDepthStencil(const GLES3GPUTextureView *texture, const DepthStencilAttachment &attachment) { + bindDepthStencilMultiSample(texture, 1, attachment); +} + +void GLES3GPUFramebufferObject::bindDepthStencilMultiSample(const GLES3GPUTextureView *texture, GLint samples, const DepthStencilAttachment &attachment) { + const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(texture->gpuTexture->format)]; + + bool isDefaultFb = swapchain != nullptr; + bool hasDepth = info.hasDepth; + bool hasStencil = info.hasStencil; + + dsAttachment = hasDepth && hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : + hasDepth ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT; + + if (hasDepth) { + auto att = isDefaultFb ? GL_DEPTH : GL_DEPTH_ATTACHMENT; + if (attachment.depthLoadOp == LoadOp::DISCARD) { + loadInvalidates.emplace_back(att); + } + if (attachment.depthStoreOp == StoreOp::DISCARD) { + storeInvalidates.emplace_back(att); + } + } + if (hasStencil) { + auto att = isDefaultFb ? GL_STENCIL : GL_STENCIL_ATTACHMENT; + if (attachment.stencilLoadOp == LoadOp::DISCARD) { + loadInvalidates.emplace_back(att); + } + if (attachment.stencilStoreOp == StoreOp::DISCARD) { + storeInvalidates.emplace_back(att); + } + } + + depthStencil.first = texture; + depthStencil.second = samples; +} + +bool GLES3GPUFramebufferObject::isActive() const { + return swapchain != nullptr || (handle != 0); +} + +void GLES3GPUFramebufferObject::processLoad(GLenum target) { + if (!loadInvalidates.empty()) { + GL_CHECK(glInvalidateFramebuffer(target, utils::toUint(loadInvalidates.size()), loadInvalidates.data())); + } +} + +void GLES3GPUFramebufferObject::processStore(GLenum target) { + if (!storeInvalidates.empty()) { + GL_CHECK(glInvalidateFramebuffer(target, utils::toUint(storeInvalidates.size()), storeInvalidates.data())); + } +} + +void GLES3GPUFramebufferObject::finalize(GLES3GPUStateCache *cache) { + if (swapchain != nullptr) { + return; + } + + if (colors.empty() && dsAttachment == GL_NONE) { + return; + } + + GL_CHECK(glGenFramebuffers(1, &handle)); + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, handle)); + cache->glDrawFramebuffer = handle; + + auto bindAttachment = [](GLenum attachment, GLint samples, const GLES3GPUTextureView *view) { + auto *texture = view->gpuTexture; + if (samples > 1) { + CC_ASSERT(view->gpuTexture->glTexture != 0); + GL_CHECK(glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, + attachment, + GL_TEXTURE_2D, + texture->glTexture, + view->baseLevel, + static_cast(samples))); + return; + } + + if (texture->useRenderBuffer) { + /* + * Renderbuffer is not allocated if using lazily allocated flag. + * If the attachment does not meet the implicit MS condition, renderbuffer should be allocated here. + */ + if (view->gpuTexture->glRenderbuffer == 0) { + GL_CHECK(glGenRenderbuffers(1, &view->gpuTexture->glRenderbuffer)); + renderBufferStorage(GLES3Device::getInstance(), texture); + } + GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, attachment, texture->glTarget, texture->glRenderbuffer)); + } else { + GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, texture->glTarget, texture->glTexture, view->baseLevel)); + } + }; + + ccstd::vector drawBuffers(colors.size(), GL_NONE); + for (uint32_t i = 0; i < colors.size(); ++i) { + const auto &[view, samples] = colors[i]; + auto att = static_cast(GL_COLOR_ATTACHMENT0 + i); + drawBuffers[i] = att; + bindAttachment(att, samples, view); + } + + if (depthStencil.first != nullptr) { + const auto &[view, samples] = depthStencil; + bindAttachment(dsAttachment, samples, view); + } + + if (!drawBuffers.empty()) { + GL_CHECK(glDrawBuffers(drawBuffers.size(), drawBuffers.data())); + } + + GLenum status; + GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); + if (status != GL_FRAMEBUFFER_COMPLETE) { + switch (status) { + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); + break; + default: + CC_LOG_ERROR("checkFramebufferStatus() - %x", status); + break; + } + } +} + +void GLES3GPUFramebufferObject::destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap) { + if (swapchain) { + swapchain = nullptr; + } else { + if (cache->glDrawFramebuffer == handle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); + cache->glDrawFramebuffer = 0; + } + GL_CHECK(glDeleteFramebuffers(1, &handle)); + framebufferCacheMap->unregisterExternal(handle); + handle = 0U; + } +} + void GLES3GPUFramebufferHub::update(GLES3GPUTexture *texture) { auto &pool = _framebuffers[texture]; for (auto *framebuffer : pool) { @@ -3192,5 +3175,16 @@ void GLES3GPUFramebufferHub::update(GLES3GPUTexture *texture) { } } +GLint cmdFuncGLES3GetMaxSampleCount(const GLES3Device *device, Format format, TextureUsage usage, TextureFlags flags) { + std::ignore = flags; + + auto internalFormat = mapGLInternalFormat(format); + auto target = useRenderBuffer(device, format, usage) ? GL_RENDERBUFFER : GL_TEXTURE_2D_MULTISAMPLE; + + GLint maxSamples = 1; + GL_CHECK(glGetInternalformativ(target, internalFormat, GL_SAMPLES, 1, &maxSamples)); + return maxSamples; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index 7108e4ecee1..c9d612550de 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -312,5 +312,7 @@ void cmdFuncGLES3Dispatch(GLES3Device *device, const GLES3GPUDispatchInfo &info) void cmdFuncGLES3MemoryBarrier(GLES3Device *device, GLbitfield barriers, GLbitfield barriersByRegion); +GLint cmdFuncGLES3GetMaxSampleCount(const GLES3Device *device, Format format, TextureUsage usage, TextureFlags flags); + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index c8de3ad8f35..79bc6937af8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -121,7 +121,6 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { ccstd::string fbfLevelStr = "NONE"; // PVRVFrame has issues on their support -//#if CC_PLATFORM != CC_PLATFORM_WINDOWS if (checkExtension("framebuffer_fetch")) { ccstd::string nonCoherent = "framebuffer_fetch_non"; @@ -153,17 +152,20 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; fbfLevelStr += "_DEPTH_STENCIL"; } -//#endif + ccstd::string msaaLevelStr = "NONE"; #if CC_PLATFORM != CC_PLATFORM_WINDOWS || ALLOW_MULTISAMPLED_RENDER_TO_TEXTURE_ON_DESKTOP if (checkExtension("multisampled_render_to_texture")) { + msaaLevelStr = "MSRT1"; if (checkExtension("multisampled_render_to_texture2")) { _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL2; + msaaLevelStr = "MSRT2"; } else { _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL1; } } #endif + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = true; ccstd::string compressedFmts; @@ -242,6 +244,7 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { CC_LOG_INFO("VERSION: %s", _version.c_str()); CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); + CC_LOG_INFO("MULTI_SAMPLE_RENDER_TO_TEXTURE: %s", msaaLevelStr.c_str()); if (_xr) { _xr->initializeGLESData(pfnGLES3wLoadProc(), GLES3Device::getInstance()->context()); @@ -610,5 +613,9 @@ void GLES3Device::getQueryPoolResults(QueryPool *queryPool) { cmdBuff->getQueryPoolResults(queryPool); } +SampleCount GLES3Device::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + return static_cast(cmdFuncGLES3GetMaxSampleCount(this, format, usage, flags)); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index 5eed7ca400f..cba5ba99a0c 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -95,8 +95,8 @@ class CC_GLES3_API GLES3Device final : public Device { return _stagingBuffer; } - inline bool isTextureExclusive(const Format &format) { return _textureExclusive[static_cast(format)]; }; - + inline bool isTextureExclusive(const Format &format) const { return _textureExclusive[static_cast(format)]; }; + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static GLES3Device *instance; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp index 0eb96c3b3c5..1b4b8e0f19f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp @@ -41,10 +41,25 @@ GLES3Framebuffer::~GLES3Framebuffer() { destroy(); } +void GLES3Framebuffer::updateExtent() { + if (!_colorTextures.empty()) { + const auto *tex = _colorTextures[0]; + _gpuFBO->width = tex->getWidth(); + _gpuFBO->height = tex->getHeight(); + return; + } + if (_depthStencilTexture != nullptr) { + _gpuFBO->width = _depthStencilTexture->getWidth(); + _gpuFBO->height = _depthStencilTexture->getHeight(); + return; + } +} + void GLES3Framebuffer::doInit(const FramebufferInfo & /*info*/) { _gpuFBO = ccnew GLES3GPUFramebuffer; - _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); + updateExtent(); + _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); _gpuFBO->gpuColorViews.resize(_colorTextures.size()); for (size_t i = 0; i < _colorTextures.size(); ++i) { auto *colorTexture = static_cast(_colorTextures.at(i)); @@ -58,6 +73,12 @@ void GLES3Framebuffer::doInit(const FramebufferInfo & /*info*/) { GLES3Device::getInstance()->framebufferHub()->connect(depthTexture->gpuTexture(), _gpuFBO); } + if (_depthStencilResolveTexture) { + auto *depthTexture = static_cast(_depthStencilResolveTexture); + _gpuFBO->gpuDepthStencilResolveView = depthTexture->gpuTextureView(); + GLES3Device::getInstance()->framebufferHub()->connect(depthTexture->gpuTexture(), _gpuFBO); + } + cmdFuncGLES3CreateFramebuffer(GLES3Device::getInstance(), _gpuFBO); } @@ -73,6 +94,10 @@ void GLES3Framebuffer::doDestroy() { auto *depthTexture = static_cast(_depthStencilTexture); GLES3Device::getInstance()->framebufferHub()->disengage(depthTexture->gpuTexture(), _gpuFBO); } + if (_depthStencilResolveTexture) { + auto *depthTexture = static_cast(_depthStencilResolveTexture); + GLES3Device::getInstance()->framebufferHub()->disengage(depthTexture->gpuTexture(), _gpuFBO); + } delete _gpuFBO; _gpuFBO = nullptr; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h index 50abda51bcb..15620265e8b 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h @@ -42,6 +42,7 @@ class CC_GLES3_API GLES3Framebuffer final : public Framebuffer { protected: void doInit(const FramebufferInfo &info) override; void doDestroy() override; + void updateExtent(); GLES3GPUFramebuffer *_gpuFBO = nullptr; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 7c1317f2847..169767fe082 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -130,10 +130,11 @@ struct GLES3GPUTexture { uint32_t size{0}; uint32_t arrayLayer{1}; uint32_t mipLevel{1}; - SampleCount samples{SampleCount::ONE}; TextureFlags flags{TextureFlagBit::NONE}; + bool immutable{true}; bool isPowerOf2{false}; - bool memoryless{false}; + bool useRenderBuffer{false}; + bool memoryAllocated{true}; // false if swapchain image or implicit ms render buffer. GLenum glTarget{0}; GLenum glInternalFmt{0}; GLenum glFormat{0}; @@ -320,63 +321,63 @@ struct GLES3GPUGeneralBarrier { GLbitfield glBarriersByRegion = 0U; }; -using DrawBuffer = std::vector; +using DrawBuffer = ccstd::vector; struct GLES3GPURenderPass { ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; + DepthStencilAttachment depthStencilResolveAttachment; SubpassInfoList subpasses; SubpassDependencyList dependencies; - std::vector colors; - std::vector resolves; + ccstd::vector colors; + ccstd::vector resolves; uint32_t depthStencil = INVALID_BINDING; - std::vector indices; // offsets to GL_COLOR_ATTACHMENT_0 - std::vector drawBuffers; + uint32_t depthStencilResolve = INVALID_BINDING; + ccstd::vector indices; // offsets to GL_COLOR_ATTACHMENT_0 + ccstd::vector drawBuffers; }; class GLES3GPUFramebufferCacheMap; -class GLES3GPUFramebuffer final { -public: - GLES3GPURenderPass *gpuRenderPass{nullptr}; - GLES3GPUTextureViewList gpuColorViews; - GLES3GPUTextureView *gpuDepthStencilView{nullptr}; +struct GLES3GPUFramebufferObject { + void initialize(GLES3GPUSwapchain *swc = nullptr); - struct GLFramebufferInfo { - GLuint glFramebuffer{0U}; - uint32_t width{UINT_MAX}; - uint32_t height{UINT_MAX}; - }; - struct GLFramebuffer { - inline void initialize(GLES3GPUSwapchain *sc) { swapchain = sc; } - inline void initialize(const GLFramebufferInfo &info) { - _glFramebuffer = info.glFramebuffer; - _width = info.width; - _height = info.height; - } - inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } - inline uint32_t getWidth() const { return swapchain ? swapchain->gpuColorTexture->width : _width; } - inline uint32_t getHeight() const { return swapchain ? swapchain->gpuColorTexture->height : _height; } + void bindColor(const GLES3GPUTextureView *texture, uint32_t colorIndex, const ColorAttachment &attachment); + void bindColorMultiSample(const GLES3GPUTextureView *texture, uint32_t colorIndex, GLint samples, const ColorAttachment &attachment); + void bindDepthStencil(const GLES3GPUTextureView *texture, const DepthStencilAttachment &attachment); + void bindDepthStencilMultiSample(const GLES3GPUTextureView *texture, GLint samples, const DepthStencilAttachment &attachment); - void destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap); + bool isActive() const; + void finalize(GLES3GPUStateCache *cache); + void processLoad(GLenum target); + void processStore(GLenum target); + void destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap); - GLES3GPUSwapchain *swapchain{nullptr}; + using Reference = std::pair; - private: - GLuint _glFramebuffer{0U}; - uint32_t _width{0U}; - uint32_t _height{0U}; - }; + GLuint handle{0}; + GLES3GPUSwapchain *swapchain{nullptr}; - struct Framebuffer { - GLFramebuffer framebuffer; + ccstd::vector colors; + Reference depthStencil{nullptr, 1}; + GLenum dsAttachment{GL_NONE}; - // for blit-based manual resolving - GLbitfield resolveMask{0U}; - GLFramebuffer resolveFramebuffer; - }; + ccstd::vector loadInvalidates; + ccstd::vector storeInvalidates; +}; - // one per subpass, if not using FBF - Framebuffer frameBuffer; +class GLES3GPUFramebuffer final { +public: + GLES3GPURenderPass *gpuRenderPass{nullptr}; + GLES3GPUTextureViewList gpuColorViews; + GLES3GPUTextureView *gpuDepthStencilView{nullptr}; + GLES3GPUTextureView *gpuDepthStencilResolveView{nullptr}; + + uint32_t width{UINT_MAX}; + uint32_t height{UINT_MAX}; + GLbitfield dsResolveMask = 0; + std::vector> colorBlitPairs; + GLES3GPUFramebufferObject framebuffer; + GLES3GPUFramebufferObject resolveFramebuffer; }; struct GLES3GPUDescriptorSetLayout { diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp index a4892670923..c409f6023a8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp @@ -138,6 +138,10 @@ void GLES3PrimaryCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffe } } +void GLES3PrimaryCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + copyTexture(srcTexture, dstTexture, regions, count); +} + void GLES3PrimaryCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { GLES3GPUTexture *gpuTextureSrc = nullptr; GLES3GPUTexture *gpuTextureDst = nullptr; diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h index 79d82f6bd31..3ae09735302 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h @@ -49,6 +49,7 @@ class CC_GLES3_API GLES3PrimaryCommandBuffer final : public GLES3CommandBuffer { void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const * /*buffers*/, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const * /*textures*/, uint32_t textureBarrierCount) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void beginQuery(QueryPool *queryPool, uint32_t id) override; void endQuery(QueryPool *queryPool, uint32_t id) override; void resetQueryPool(QueryPool *queryPool) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp index 2029f901eb3..76f8328171a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp @@ -44,6 +44,7 @@ void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { _gpuRenderPass = ccnew GLES3GPURenderPass; _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; + _gpuRenderPass->depthStencilResolveAttachment = _depthStencilResolveAttachment; _gpuRenderPass->subpasses = _subpasses; _gpuRenderPass->dependencies = _dependencies; @@ -59,14 +60,17 @@ void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { if (_depthStencilAttachment.format != Format::UNKNOWN) { subpass.depthStencil = colorCount; } + if (_depthStencilResolveAttachment.format != Format::UNKNOWN) { + subpass.depthStencil = colorCount + 1; + } } else { // unify depth stencil index for (auto &subpass : _gpuRenderPass->subpasses) { - if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil > colorCount) { + if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil >= colorCount) { subpass.depthStencil = colorCount; } - if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencilResolve > colorCount) { - subpass.depthStencilResolve = colorCount; + if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencil >= colorCount) { + subpass.depthStencilResolve = colorCount + 1; } } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index a4c729b6788..286ef62b78f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -52,7 +52,7 @@ void GLES3Texture::doInit(const TextureInfo & /*info*/) { _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; + _gpuTexture->glSamples = static_cast(_info.samples); _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; _gpuTexture->isPowerOf2 = math::isPowerOfTwo(_info.width) && math::isPowerOfTwo(_info.height); @@ -71,7 +71,7 @@ void GLES3Texture::doInit(const TextureInfo & /*info*/) { cmdFuncGLES3CreateTexture(GLES3Device::getInstance(), _gpuTexture); - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize += _size; CC_PROFILE_MEMORY_INC(Texture, _size); } @@ -101,7 +101,7 @@ void GLES3Texture::doDestroy() { CC_SAFE_DELETE(_gpuTextureView); if (_gpuTexture) { if (!_isTextureView) { - if (!_gpuTexture->memoryless) { + if (_gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -115,7 +115,7 @@ void GLES3Texture::doDestroy() { } void GLES3Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { - if (!_isTextureView && !_gpuTexture->memoryless) { + if (!_isTextureView && _gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } @@ -129,7 +129,7 @@ void GLES3Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { GLES3Device::getInstance()->framebufferHub()->update(_gpuTexture); - if (!_isTextureView && !_gpuTexture->memoryless) { + if (!_isTextureView && _gpuTexture->memoryAllocated) { GLES3Device::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_INC(Texture, size); } @@ -164,10 +164,10 @@ void GLES3Texture::doInit(const SwapchainTextureInfo & /*info*/) { _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; + _gpuTexture->glSamples = static_cast(_info.samples); _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->memoryless = true; + _gpuTexture->memoryAllocated = false; _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); _gpuTextureView = ccnew GLES3GPUTextureView; createTextureView(); diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h index 7567af5316f..bb38f1530cd 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h @@ -73,6 +73,7 @@ class CCMTLCommandBuffer final : public CommandBuffer { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 0779591c601..84cd6f958e0 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -237,6 +237,15 @@ of this software and associated engine source code (the "Software"), a limited, if(color >= colorAttachments.size()) { continue; // depthStencil as output } + if (subpasses[i].resolves.size() > j) { + uint32_t resolve = subpasses[i].resolves[j]; + auto *resolveTex = static_cast(colorTextures[resolve]); + mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); + mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; + mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; + } if (visited[color]) continue; auto *ccMtlTexture = static_cast(colorTextures[color]); @@ -255,17 +264,6 @@ of this software and associated engine source code (the "Software"), a limited, mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; visited[color] = true; _colorAppearedBefore.set(color); - if (subpasses[i].resolves.size() > j) { - uint32_t resolve = subpasses[i].resolves[j]; - auto *resolveTex = static_cast(colorTextures[resolve]); - if (resolveTex->textureInfo().samples == SampleCount::ONE) - continue; - mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); - mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; - mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; - mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; - mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; - } } } updateDepthStencilState(ccMtlRenderPass->getCurrentSubpassIndex(), mtlRenderPassDescriptor); @@ -388,19 +386,13 @@ of this software and associated engine source code (the "Software"), a limited, } if (subpass.depthStencilResolve != INVALID_BINDING) { - const CCMTLTexture *dsResolveTex = nullptr; - if (subpass.depthStencilResolve >= colorTextures.size()) { - dsResolveTex = static_cast(curFBO->getDepthStencilTexture()); - } else { - dsResolveTex = static_cast(colorTextures[subpass.depthStencilResolve]); - } - descriptor.depthAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.depthAttachment.resolveTexture = static_cast(curFBO->getDepthStencilTexture())->getMTLTexture(); descriptor.depthAttachment.resolveLevel = 0; descriptor.depthAttachment.resolveSlice = 0; descriptor.depthAttachment.resolveDepthPlane = 0; descriptor.depthAttachment.storeAction = subpass.depthResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; - descriptor.stencilAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.stencilAttachment.resolveTexture = static_cast(curFBO->getDepthStencilResolveTexture())->getMTLTexture(); descriptor.stencilAttachment.resolveLevel = 0; descriptor.stencilAttachment.resolveSlice = 0; descriptor.stencilAttachment.resolveDepthPlane = 0; @@ -919,6 +911,10 @@ of this software and associated engine source code (the "Software"), a limited, } } +void CCMTLCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + // not supported. +} + void CCMTLCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { ccstd::vector blitRegions(count); for (uint32_t i = 0; i < count; ++i) { diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index b76443f1bd6..14064a3f308 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -62,7 +62,7 @@ class CCMTLDevice final : public Device { using Device::createRenderPass; using Device::createShader; using Device::createTexture; - + void frameSync() override; void acquire(Swapchain *const *swapchains, uint32_t count) override; @@ -88,6 +88,8 @@ class CCMTLDevice final : public Device { _swapchains.erase(iter); } } + + inline CCMTLGPUDeviceObject* gpuObject() const { return _gpuDeviceObj; } protected: static CCMTLDevice *_instance; @@ -114,6 +116,7 @@ class CCMTLDevice final : public Device { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; void getQueryPoolResults(QueryPool *queryPool) override; + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; void onMemoryWarning(); void initFormatFeatures(uint32_t family); diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index db0ceef627d..186a152bcda 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -73,7 +73,7 @@ of this software and associated engine source code (the "Software"), a limited, bool CCMTLDevice::doInit(const DeviceInfo &info) { _gpuDeviceObj = ccnew CCMTLGPUDeviceObject; - + _currentFrameIndex = 0; id mtlDevice = MTLCreateSystemDefaultDevice(); @@ -87,7 +87,7 @@ of this software and associated engine source code (the "Software"), a limited, } _mtlFeatureSet = mu::highestSupportedFeatureSet(mtlDevice); _version = std::to_string(_mtlFeatureSet); - + const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); _indirectDrawSupported = mu::isIndirectDrawSupported(gpuFamily); _caps.maxVertexAttributes = mu::getMaxVertexAttributes(gpuFamily); @@ -139,13 +139,15 @@ of this software and associated engine source code (the "Software"), a limited, _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = false; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = [mtlDevice supportsFamily: MTLGPUFamilyApple3]; + QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; _queue = createQueue(queueInfo); QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, true}; _queryPool = createQueryPool(queryPoolInfo); - + CommandBufferInfo cmdBuffInfo; cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; @@ -527,5 +529,22 @@ of this software and associated engine source code (the "Software"), a limited, _formatFeatures[toNumber(Format::RGB10A2)] |= FormatFeature::VERTEX_ATTRIBUTE; } +SampleCount CCMTLDevice::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + const SampleCount sampleCounts[] = { + SampleCount::X64, + SampleCount::X32, + SampleCount::X16, + SampleCount::X8, + SampleCount::X4, + SampleCount::X2, + }; + for (auto sampleCount : sampleCounts) { + if ([_mtlDevice supportsTextureSampleCount: static_cast(sampleCount)]) { + return sampleCount; + } + } + return SampleCount::X1; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 7bd26adbae7..447ca460e19 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -333,7 +333,7 @@ of this software and associated engine source code (the "Software"), a limited, } } - SampleCount sample = SampleCount::ONE; + SampleCount sample = SampleCount::X1; Format depthStencilFormat; if (depthStencilTexIndex != INVALID_BINDING && depthStencilTexIndex < _renderPass->getColorAttachments().size()) { sample = _renderPass->getColorAttachments()[depthStencilTexIndex].sampleCount; diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.h b/native/cocos/renderer/gfx-metal/MTLTexture.h index 65eaf60e101..38a48205a57 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.h +++ b/native/cocos/renderer/gfx-metal/MTLTexture.h @@ -72,6 +72,8 @@ class CCMTLTexture final : public Texture { bool _isArray = false; bool _isPVRTC = false; + bool _allocateMemory = true; // allocate device memory by metal driver. + id _mtlTexture = nil; id _mtlTextureView = nil; }; diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.mm b/native/cocos/renderer/gfx-metal/MTLTexture.mm index 5812ca53e10..edab24a636a 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.mm +++ b/native/cocos/renderer/gfx-metal/MTLTexture.mm @@ -144,8 +144,10 @@ of this software and associated engine source code (the "Software"), a limited, return; } - CCMTLDevice::getInstance()->getMemoryStatus().textureSize += _size; - CC_PROFILE_MEMORY_INC(Texture, _size); + if (_allocateMemory) { + CCMTLDevice::getInstance()->getMemoryStatus().textureSize += _size; + CC_PROFILE_MEMORY_INC(Texture, _size); + } } void CCMTLTexture::doInit(const TextureViewInfo &info) { @@ -223,27 +225,15 @@ of this software and associated engine source code (the "Software"), a limited, descriptor.mipmapLevelCount = _info.levelCount; descriptor.arrayLength = _info.type == TextureType::CUBE ? 1 : _info.layerCount; - if (hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT, _info.usage) && mu::isImageBlockSupported()) { -#if MEMLESS_ON - // mac SDK mem_less unavailable before 11.0 - #if MAC_MEMORY_LESS_TEXTURE_SUPPORT || CC_PLATFORM == CC_PLATFORM_IOS - //xcode OS version warning - if (@available(macOS 11.0, *)) { + descriptor.storageMode = MTLStorageModePrivate; + if (@available(macos 11.0, ios 10.0, *)) { + bool memoryless = hasFlag(_info.flags, TextureFlagBit::LAZILY_ALLOCATED) && + hasFlag(_info.usage, TextureUsageBit::COLOR_ATTACHMENT) && + hasFlag(_info.usage, TextureUsageBit::DEPTH_STENCIL_ATTACHMENT); + if (memoryless) { descriptor.storageMode = MTLStorageModeMemoryless; - } else { - descriptor.storageMode = MTLStorageModePrivate; + _allocateMemory = false; } - #else - descriptor.storageMode = MTLStorageModePrivate; - #endif -#else - descriptor.storageMode = MTLStorageModePrivate; -#endif - } else if (hasFlag(_info.usage, TextureUsage::COLOR_ATTACHMENT) || - hasFlag(_info.usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT) || - hasFlag(_info.usage, TextureUsage::INPUT_ATTACHMENT) || - hasFlag(_info.usage, TextureUsage::STORAGE)) { - descriptor.storageMode = MTLStorageModePrivate; } id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); @@ -262,8 +252,9 @@ of this software and associated engine source code (the "Software"), a limited, void CCMTLTexture::doDestroy() { //decrease only non-swapchain tex and have had been inited. - if (!_swapchain && _mtlTexture) { + if (!_swapchain && _mtlTexture && _allocateMemory) { CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= _size; + CC_PROFILE_MEMORY_DEC(Texture, _size); } if (_swapchain) { @@ -281,8 +272,6 @@ of this software and associated engine source code (the "Software"), a limited, _mtlTexture = nil; } - CC_PROFILE_MEMORY_DEC(Texture, _size); - std::function destroyFunc = [mtlTexure]() { if (mtlTexure) { //TODO_Zeqiang: [mac12 | ios15, ...) validate here @@ -319,7 +308,7 @@ of this software and associated engine source code (the "Software"), a limited, // texture is a wrapper of drawable when _swapchain is active, drawable is not a resource alloc by gfx, // but the system so skip here. - if (!_swapchain) { + if (!_swapchain && _allocateMemory) { CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= oldSize; CCMTLDevice::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_DEC(Texture, oldSize); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 18869415bba..d2864e9b917 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -847,17 +847,7 @@ void main() { } NSUInteger mu::toMTLSampleCount(SampleCount count) { - //TODO_Zeqiang: query from device. - switch (count) { - case SampleCount::ONE: return 1; - case SampleCount::MULTIPLE_PERFORMANCE: return 2; - case SampleCount::MULTIPLE_BALANCE: return 4; - case SampleCount::MULTIPLE_QUALITY: - return 8; - // case SampleCount::X16: return 16; - // case SampleCount::X32: return 32; - // case SampleCount::X64: return 64; - } + return static_cast(count); } MTLSamplerAddressMode mu::toMTLSamplerAddressMode(Address mode) { diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp index abae1798305..bab7e3c6ca5 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp @@ -418,6 +418,41 @@ void CommandBufferValidator::copyBuffersToTexture(const uint8_t *const *buffers, _actor->copyBuffersToTexture(buffers, textureValidator->getActor(), regions, count); } +void CommandBufferValidator::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + CC_ASSERT(isInited()); + CC_ASSERT(srcTexture && static_cast(srcTexture)->isInited()); + CC_ASSERT(dstTexture && static_cast(dstTexture)->isInited()); + const auto &srcInfo = srcTexture->getInfo(); + const auto &dstInfo = dstTexture->getInfo(); + + CC_ASSERT(srcInfo.format == dstInfo.format); + CC_ASSERT(srcInfo.format != Format::DEPTH_STENCIL && + srcInfo.format != Format::DEPTH); + + CC_ASSERT(srcInfo.samples > SampleCount::X1 && + dstInfo.samples == SampleCount::X1); + + CC_ASSERT(!_insideRenderPass); + + for (uint32_t i = 0; i < count; ++i) { + const auto ®ion = regions[i]; + CC_ASSERT(region.srcOffset.x + region.extent.width <= srcInfo.width); + CC_ASSERT(region.srcOffset.y + region.extent.height <= srcInfo.height); + CC_ASSERT(region.srcOffset.z + region.extent.depth <= srcInfo.depth); + + CC_ASSERT(region.dstOffset.x + region.extent.width <= dstInfo.width); + CC_ASSERT(region.dstOffset.y + region.extent.height <= dstInfo.height); + CC_ASSERT(region.dstOffset.z + region.extent.depth <= dstInfo.depth); + } + + Texture *actorSrcTexture = nullptr; + Texture *actorDstTexture = nullptr; + if (srcTexture) actorSrcTexture = static_cast(srcTexture)->getActor(); + if (dstTexture) actorDstTexture = static_cast(dstTexture)->getActor(); + + _actor->resolveTexture(actorSrcTexture, actorDstTexture, regions, count); +} + void CommandBufferValidator::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { CC_ASSERT(isInited()); CC_ASSERT(srcTexture && static_cast(srcTexture)->isInited()); @@ -453,9 +488,9 @@ void CommandBufferValidator::blitTexture(Texture *srcTexture, Texture *dstTextur CC_ASSERT(srcTexture && static_cast(srcTexture)->isInited()); CC_ASSERT(dstTexture && static_cast(dstTexture)->isInited()); // Blit on multisampled texture is not allowed. - CC_ASSERT(srcTexture->getInfo().samples == SampleCount::ONE); + CC_ASSERT(srcTexture->getInfo().samples == SampleCount::X1); // blit on multisampled texture is not allowed. - CC_ASSERT(dstTexture->getInfo().samples == SampleCount::ONE); + CC_ASSERT(dstTexture->getInfo().samples == SampleCount::X1); // Command 'blitTexture' must be recorded outside render passes. CC_ASSERT(!_insideRenderPass); diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h index f7b0ee52748..3ec70240be2 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h @@ -58,6 +58,7 @@ class CC_DLL CommandBufferValidator final : public Agent { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index f44d42aee1c..ff97a9910a1 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -352,5 +352,9 @@ void DeviceValidator::frameSync() { _actor->frameSync(); } +SampleCount DeviceValidator::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + return _actor->getMaxSampleCount(format, usage, flags); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.h b/native/cocos/renderer/gfx-validator/DeviceValidator.h index 111737a0869..4122d715e75 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.h +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.h @@ -95,7 +95,7 @@ class CC_DLL DeviceValidator final : public Agent { inline uint64_t currentFrame() const { return _currentFrame; } void enableAutoBarrier(bool enable) override; - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static DeviceValidator *instance; diff --git a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp index bf6c868d479..8c4166bbb8e 100644 --- a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp @@ -54,6 +54,9 @@ void FramebufferValidator::doInit(const FramebufferInfo &info) { if (info.renderPass->getDepthStencilAttachment().format != Format::UNKNOWN) { CC_ASSERT(info.depthStencilTexture); } + if (info.renderPass->getDepthStencilResolveAttachment().format != Format::UNKNOWN) { + CC_ASSERT(info.depthStencilResolveTexture); + } for (uint32_t i = 0U; i < info.colorTextures.size(); ++i) { const auto &desc = info.renderPass->getColorAttachments()[i]; @@ -67,6 +70,11 @@ void FramebufferValidator::doInit(const FramebufferInfo &info) { CC_ASSERT(hasFlag(info.depthStencilTexture->getInfo().usage, TextureUsageBit::DEPTH_STENCIL_ATTACHMENT)); CC_ASSERT(info.depthStencilTexture->getFormat() == info.renderPass->getDepthStencilAttachment().format); } + if (info.depthStencilResolveTexture) { + CC_ASSERT(static_cast(info.depthStencilResolveTexture)->isInited()); + CC_ASSERT(hasFlag(info.depthStencilResolveTexture->getInfo().usage, TextureUsageBit::DEPTH_STENCIL_ATTACHMENT)); + CC_ASSERT(info.depthStencilResolveTexture->getFormat() == info.renderPass->getDepthStencilResolveAttachment().format); + } /////////// execute /////////// @@ -79,6 +87,9 @@ void FramebufferValidator::doInit(const FramebufferInfo &info) { if (info.depthStencilTexture) { actorInfo.depthStencilTexture = static_cast(info.depthStencilTexture)->getActor(); } + if (info.depthStencilResolveTexture) { + actorInfo.depthStencilResolveTexture = static_cast(info.depthStencilResolveTexture)->getActor(); + } actorInfo.renderPass = static_cast(info.renderPass)->getActor(); _actor->initialize(actorInfo); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index fb62c102e02..7aefa9312fc 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -168,15 +168,17 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo } ccstd::vector &clearValues = _curGPURenderPass->clearValues; - bool depthEnabled = _curGPURenderPass->depthStencilAttachment.format != Format::UNKNOWN; - size_t attachmentCount = depthEnabled ? clearValues.size() - 1 : clearValues.size(); - + size_t attachmentCount = _curGPURenderPass->colorAttachments.size(); for (size_t i = 0U; i < attachmentCount; ++i) { clearValues[i].color = {{colors[i].x, colors[i].y, colors[i].z, colors[i].w}}; } - if (depthEnabled) { + + if (_curGPURenderPass->depthStencilAttachment.format != Format::UNKNOWN) { clearValues[attachmentCount].depthStencil = {depth, stencil}; } + if (_curGPURenderPass->depthStencilResolveAttachment.format != Format::UNKNOWN) { + clearValues[attachmentCount + 1].depthStencil = {depth, stencil}; + } Rect safeArea{ std::min(renderArea.x, static_cast(_curGPUFBO->width)), @@ -516,6 +518,50 @@ void CCVKCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Text cmdFuncCCVKCopyBuffersToTexture(CCVKDevice::getInstance(), buffers, static_cast(texture)->gpuTexture(), regions, count, _gpuCommandBuffer); } +void CCVKCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { + VkImageAspectFlags srcAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + VkImageAspectFlags dstAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + VkImage srcImage = VK_NULL_HANDLE; + VkImage dstImage = VK_NULL_HANDLE; + + auto getImage = [](Texture * texture) -> auto { + CCVKGPUTexture *gpuTexture = static_cast(texture)->gpuTexture(); + return gpuTexture->swapchain ? std::pair{gpuTexture->aspectMask, gpuTexture->swapchainVkImages[gpuTexture->swapchain->curImageIndex]} : std::pair{gpuTexture->aspectMask, gpuTexture->vkImage}; + }; + + std::tie(srcAspectMask, srcImage) = getImage(srcTexture); + std::tie(dstAspectMask, dstImage) = getImage(dstTexture); + + ccstd::vector resolveRegions(count); + for (uint32_t i = 0U; i < count; ++i) { + const TextureCopy ®ion = regions[i]; + auto &resolveRegion = resolveRegions[i]; + + resolveRegion.srcSubresource.aspectMask = srcAspectMask; + resolveRegion.srcSubresource.mipLevel = region.srcSubres.mipLevel; + resolveRegion.srcSubresource.baseArrayLayer = region.srcSubres.baseArrayLayer; + resolveRegion.srcSubresource.layerCount = region.srcSubres.layerCount; + + resolveRegion.dstSubresource.aspectMask = dstAspectMask; + resolveRegion.dstSubresource.mipLevel = region.dstSubres.mipLevel; + resolveRegion.dstSubresource.baseArrayLayer = region.dstSubres.baseArrayLayer; + resolveRegion.dstSubresource.layerCount = region.dstSubres.layerCount; + + resolveRegion.srcOffset.x = region.srcOffset.x; + resolveRegion.srcOffset.y = region.srcOffset.y; + resolveRegion.srcOffset.z = region.srcOffset.z; + + resolveRegion.dstOffset.x = region.dstOffset.x; + resolveRegion.dstOffset.y = region.dstOffset.y; + resolveRegion.dstOffset.z = region.dstOffset.z; + + resolveRegion.extent.width = region.extent.width; + resolveRegion.extent.height = region.extent.height; + resolveRegion.extent.depth = region.extent.depth; + } + vkCmdResolveImage(_gpuCommandBuffer->vkCommandBuffer, srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, count, resolveRegions.data()); +} + void CCVKCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { VkImageAspectFlags srcAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; VkImageAspectFlags dstAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h index 3438684cbe9..1eae85158ed 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h @@ -58,6 +58,7 @@ class CC_VULKAN_API CCVKCommandBuffer final : public CommandBuffer { void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; void copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; + void resolveTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) override; void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GeneralBarrier *barrier, const BufferBarrier *const *bufferBarriers, const Buffer *const *buffers, uint32_t bufferBarrierCount, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 4d65e96f6c6..cf098298382 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -119,11 +119,6 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { if (!gpuTexture->size) return; gpuTexture->aspectMask = mapVkImageAspectFlags(gpuTexture->format); - // storage images has to be in general layout - // if (hasFlag(gpuTexture->usage, TextureUsageBit::STORAGE)) gpuTexture->flags |= TextureFlagBit::GENERAL_LAYOUT; - // remove stencil aspect for depth textures with sampled usage - if (hasFlag(gpuTexture->usage, TextureUsageBit::SAMPLED)) gpuTexture->aspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT; - auto createFn = [device, gpuTexture](VkImage *pVkImage, VmaAllocation *pVmaAllocation) { VkFormat vkFormat = mapVkFormat(gpuTexture->format, device->gpuDevice()); VkFormatFeatureFlags features = mapVkFormatFeatureFlags(gpuTexture->usage); @@ -135,10 +130,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { return; } - VkImageUsageFlags usageFlags = mapVkImageUsageFlagBits(gpuTexture->usage); - if (hasFlag(gpuTexture->flags, TextureFlags::GEN_MIPMAP)) { - usageFlags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - } + VkImageUsageFlags usageFlags = mapVkImageUsageFlags(gpuTexture->usage, gpuTexture->flags); VkImageCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; createInfo.flags = mapVkImageCreateFlags(gpuTexture->type); @@ -147,7 +139,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { createInfo.extent = {gpuTexture->width, gpuTexture->height, gpuTexture->depth}; createInfo.mipLevels = gpuTexture->mipLevels; createInfo.arrayLayers = gpuTexture->arrayLayers; - createInfo.samples = device->gpuContext()->getSampleCountForAttachments(gpuTexture->format, vkFormat, gpuTexture->samples); + createInfo.samples = static_cast(gpuTexture->samples); createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; createInfo.usage = usageFlags; createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; @@ -156,23 +148,25 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; VmaAllocationInfo res; - - if (ENABLE_LAZY_ALLOCATION && hasAllFlags(TEXTURE_USAGE_TRANSIENT, gpuTexture->usage)) { - createInfo.usage = usageFlags | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; + const VkFlags lazilyAllocatedFilterFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | + VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT | + VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; + if (hasFlag(gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED) && + (lazilyAllocatedFilterFlags & usageFlags) == usageFlags) { allocInfo.usage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; VkResult result = vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, pVkImage, pVmaAllocation, &res); if (!result) { - gpuTexture->memoryless = true; + gpuTexture->memoryAllocated = false; return; } - // feature not present, fallback - createInfo.usage = usageFlags; + // feature not present, fallback to device memory allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; } - gpuTexture->memoryless = false; + gpuTexture->memoryAllocated = true; VK_CHECK(vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, pVkImage, pVmaAllocation, &res)); }; @@ -190,7 +184,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { gpuTexture->swapchainVkImages[i] = gpuTexture->swapchain->swapchainImages[i]; } } - gpuTexture->memoryless = true; + gpuTexture->memoryAllocated = false; } else if (hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES) || hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_NORMAL)) { gpuTexture->vkImage = gpuTexture->externalVKImage; } else { @@ -382,11 +376,18 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende ccstd::vector shadingRateReferences; const size_t colorAttachmentCount = gpuRenderPass->colorAttachments.size(); - const size_t hasDepth = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; - attachmentDescriptions.assign(colorAttachmentCount + hasDepth, {VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2}); - gpuRenderPass->clearValues.resize(colorAttachmentCount + hasDepth); - beginAccessInfos.resize(colorAttachmentCount + hasDepth); - endAccessInfos.resize(colorAttachmentCount + hasDepth); + const size_t hasDepthStencil = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; + const size_t hasDepthResolve = gpuRenderPass->depthStencilResolveAttachment.format != Format::UNKNOWN ? 1 : 0; + auto attachmentCount = static_cast(colorAttachmentCount + hasDepthStencil + hasDepthResolve); + uint32_t depthIndex = colorAttachmentCount; + uint32_t stencilIndex = colorAttachmentCount + 1; + + const bool hasStencil = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; + + attachmentDescriptions.assign(attachmentCount, {VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2}); + gpuRenderPass->clearValues.resize(attachmentCount); + beginAccessInfos.resize(attachmentCount); + endAccessInfos.resize(attachmentCount); shadingRateReferences.resize(gpuRenderPass->subpasses.size(), {VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR}); for (size_t i = 0U; i < colorAttachmentCount; ++i) { @@ -395,34 +396,43 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende getInitialFinalLayout(device, static_cast(attachment.barrier), false); VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); - bool hasStencil = GFX_FORMAT_INFOS[toNumber(attachment.format)].hasStencil; - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(attachment.format, vkFormat, attachment.sampleCount); - attachmentDescriptions[i].format = vkFormat; - attachmentDescriptions[i].samples = samples; + attachmentDescriptions[i].samples = static_cast(attachment.sampleCount); attachmentDescriptions[i].loadOp = mapVkLoadOp(attachment.loadOp); attachmentDescriptions[i].storeOp = mapVkStoreOp(attachment.storeOp); - attachmentDescriptions[i].stencilLoadOp = hasStencil ? attachmentDescriptions[i].loadOp : VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachmentDescriptions[i].stencilStoreOp = hasStencil ? attachmentDescriptions[i].storeOp : VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachmentDescriptions[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescriptions[i].initialLayout = attachment.loadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; attachmentDescriptions[i].finalLayout = finalLayout; } - if (hasDepth) { - const DepthStencilAttachment &depthStencilAttachment = gpuRenderPass->depthStencilAttachment; - auto [initialLayout, finalLayout] = getInitialFinalLayout(device, static_cast(depthStencilAttachment.barrier), true); - - VkFormat vkFormat = mapVkFormat(depthStencilAttachment.format, device->gpuDevice()); - bool hasStencil = GFX_FORMAT_INFOS[toNumber(depthStencilAttachment.format)].hasStencil; - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(depthStencilAttachment.format, vkFormat, depthStencilAttachment.sampleCount); - - attachmentDescriptions[colorAttachmentCount].format = vkFormat; - attachmentDescriptions[colorAttachmentCount].samples = samples; - attachmentDescriptions[colorAttachmentCount].loadOp = mapVkLoadOp(depthStencilAttachment.depthLoadOp); - attachmentDescriptions[colorAttachmentCount].storeOp = mapVkStoreOp(depthStencilAttachment.depthStoreOp); - attachmentDescriptions[colorAttachmentCount].stencilLoadOp = hasStencil ? mapVkLoadOp(depthStencilAttachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachmentDescriptions[colorAttachmentCount].stencilStoreOp = hasStencil ? mapVkStoreOp(depthStencilAttachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[colorAttachmentCount].initialLayout = depthStencilAttachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; - attachmentDescriptions[colorAttachmentCount].finalLayout = finalLayout; + if (hasDepthStencil) { + const DepthStencilAttachment &attachment = gpuRenderPass->depthStencilAttachment; + auto [initialLayout, finalLayout] = getInitialFinalLayout(device, static_cast(attachment.barrier), true); + + VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); + attachmentDescriptions[depthIndex].format = vkFormat; + attachmentDescriptions[depthIndex].samples = static_cast(attachment.sampleCount); + attachmentDescriptions[depthIndex].loadOp = mapVkLoadOp(attachment.depthLoadOp); + attachmentDescriptions[depthIndex].storeOp = mapVkStoreOp(attachment.depthStoreOp); + attachmentDescriptions[depthIndex].stencilLoadOp = hasStencil ? mapVkLoadOp(attachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[depthIndex].stencilStoreOp = hasStencil ? mapVkStoreOp(attachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachmentDescriptions[depthIndex].initialLayout = attachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; + attachmentDescriptions[depthIndex].finalLayout = finalLayout; + } + if (hasDepthResolve) { + const DepthStencilAttachment &attachment = gpuRenderPass->depthStencilResolveAttachment; + auto [initialLayout, finalLayout] = getInitialFinalLayout(device, static_cast(attachment.barrier), true); + + VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); + + attachmentDescriptions[stencilIndex].format = vkFormat; + attachmentDescriptions[stencilIndex].samples = VK_SAMPLE_COUNT_1_BIT; + attachmentDescriptions[stencilIndex].loadOp = mapVkLoadOp(attachment.depthLoadOp); + attachmentDescriptions[stencilIndex].storeOp = mapVkStoreOp(attachment.depthStoreOp); + attachmentDescriptions[stencilIndex].stencilLoadOp = hasStencil ? mapVkLoadOp(attachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[stencilIndex].stencilStoreOp = hasStencil ? mapVkStoreOp(attachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachmentDescriptions[stencilIndex].initialLayout = attachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : initialLayout; + attachmentDescriptions[stencilIndex].finalLayout = finalLayout; } size_t subpassCount = gpuRenderPass->subpasses.size(); @@ -433,62 +443,41 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkSampleCountFlagBits sampleCount = VK_SAMPLE_COUNT_1_BIT; for (uint32_t input : subpassInfo.inputs) { + bool appearsInOutput = std::find(subpassInfo.colors.begin(), subpassInfo.colors.end(), input) != subpassInfo.colors.end(); if (input == gpuRenderPass->colorAttachments.size()) { - VkImageLayout layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; + VkImageLayout layout = subpassInfo.depthStencil != INVALID_BINDING ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_DEPTH_BIT}); } else { - VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkImageLayout layout = appearsInOutput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_COLOR_BIT}); } } for (uint32_t color : subpassInfo.colors) { - const ColorAttachment &desc = gpuRenderPass->colorAttachments[color]; const VkAttachmentDescription2 &attachment = attachmentDescriptions[color]; bool appearsInInput = std::find(subpassInfo.inputs.begin(), subpassInfo.inputs.end(), color) != subpassInfo.inputs.end(); VkImageLayout layout = appearsInInput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, color, layout, VK_IMAGE_ASPECT_COLOR_BIT}); sampleCount = std::max(sampleCount, attachment.samples); } - for (uint32_t resolve : subpassInfo.resolves) { - VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + for (uint32_t resolveIn : subpassInfo.resolves) { + VkImageLayout layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + auto resolve = resolveIn == gfx::INVALID_BINDING ? VK_ATTACHMENT_UNUSED : resolveIn; + CC_ASSERT(INVALID_BINDING == VK_ATTACHMENT_UNUSED); attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, resolve, layout, VK_IMAGE_ASPECT_COLOR_BIT}); } if (subpassInfo.depthStencil != INVALID_BINDING) { - Format dsFormat{Format::UNKNOWN}; - if (subpassInfo.depthStencil >= colorAttachmentCount) { - const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; - const VkAttachmentDescription2 &attachment = attachmentDescriptions.back(); - dsFormat = desc.format; - sampleCount = std::max(sampleCount, attachment.samples); - } else { - const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencil]; - const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; - dsFormat = desc.format; - sampleCount = std::max(sampleCount, attachment.samples); - } + const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; + sampleCount = std::max(sampleCount, attachment.samples); bool appearsInInput = std::find(subpassInfo.inputs.begin(), subpassInfo.inputs.end(), subpassInfo.depthStencil) != subpassInfo.inputs.end(); - VkImageAspectFlags aspect = GFX_FORMAT_INFOS[toNumber(dsFormat)].hasStencil - ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT - : VK_IMAGE_ASPECT_DEPTH_BIT; + VkImageAspectFlags aspect = hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; VkImageLayout layout = appearsInInput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencil, layout, aspect}); } if (subpassInfo.depthStencilResolve != INVALID_BINDING) { - Format dsFormat{Format::UNKNOWN}; - if (subpassInfo.depthStencilResolve >= colorAttachmentCount) { - const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; - dsFormat = desc.format; - } else { - const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencilResolve]; - dsFormat = desc.format; - } - - VkImageAspectFlags aspect = GFX_FORMAT_INFOS[toNumber(dsFormat)].hasStencil - ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT - : VK_IMAGE_ASPECT_DEPTH_BIT; + VkImageAspectFlags aspect = hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; VkImageLayout layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencilResolve, layout, aspect}); } @@ -547,8 +536,14 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkResolveModeFlagBits depthResolveMode = VK_RESOLVE_MODES[toNumber(subpassInfo.depthResolveMode)]; VkResolveModeFlagBits stencilResolveMode = VK_RESOLVE_MODES[toNumber(subpassInfo.stencilResolveMode)]; - if ((depthResolveMode & prop.supportedDepthResolveModes) == 0) depthResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; - if ((stencilResolveMode & prop.supportedStencilResolveModes) == 0) stencilResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + if ((depthResolveMode & prop.supportedDepthResolveModes) == 0) { + depthResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + CC_LOG_WARNING("render pass depth resolve mode [%u] not supported, use Sample0 instead.", toNumber(subpassInfo.depthResolveMode)); + } + if ((stencilResolveMode & prop.supportedStencilResolveModes) == 0) { + stencilResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + CC_LOG_WARNING("render pass stencil resolve mode [%u] not supported, use Sample0 instead.", toNumber(subpassInfo.stencilResolveMode)); + } if (!prop.independentResolveNone && stencilResolveMode != depthResolveMode) { stencilResolveMode = depthResolveMode; @@ -572,6 +567,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } size_t dependencyCount = gpuRenderPass->dependencies.size(); + gpuRenderPass->hasSelfDependency.resize(subpassCount, false); dependencyManager.clear(); bool manuallyDeduce = true; @@ -584,8 +580,6 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (!manuallyDeduce) { // offset = 0U; ccstd::unordered_set subpassExternalFilter; - - gpuRenderPass->hasSelfDependency.resize(subpassCount, false); for (uint32_t i = 0U; i < dependencyCount; ++i) { const auto &dependency{gpuRenderPass->dependencies[i]}; VkSubpassDependency2 vkDependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2}; @@ -669,8 +663,8 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } } }; - attachmentStatistics.resize(colorAttachmentCount + hasDepth); - for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { + attachmentStatistics.resize(attachmentCount); + for (uint32_t i = 0U; i < utils ::toUint(attachmentCount); ++i) { attachmentStatistics[i].clear(); calculateLifeCycle(i, attachmentStatistics[i]); CC_ASSERT(attachmentStatistics[i].loadSubpass != VK_SUBPASS_EXTERNAL && @@ -697,7 +691,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkSubpassDependency2 beginDependency; uint32_t lastLoadSubpass{VK_SUBPASS_EXTERNAL}; bool beginDependencyValid{false}; - for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { + for (uint32_t i = 0U; i < attachmentCount; ++i) { auto &statistics = attachmentStatistics[i]; if (lastLoadSubpass != statistics.loadSubpass) { if (beginDependencyValid) dependencyManager.append(beginDependency); @@ -729,7 +723,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkSubpassDependency2 endDependency; uint32_t lastStoreSubpass{VK_SUBPASS_EXTERNAL}; bool endDependencyValid{false}; - for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { + for (uint32_t i = 0U; i < attachmentCount; ++i) { auto &statistics = attachmentStatistics[i]; if (lastStoreSubpass != statistics.storeSubpass) { if (endDependencyValid) dependencyManager.append(endDependency); @@ -759,7 +753,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; return dependency; }; - for (size_t i = 0U; i < colorAttachmentCount + hasDepth; ++i) { + for (size_t i = 0U; i < attachmentCount; ++i) { auto &statistics{attachmentStatistics[i]}; const AttachmentStatistics::SubpassRef *prevRef{nullptr}; @@ -788,8 +782,12 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFramebuffer) { size_t colorViewCount = gpuFramebuffer->gpuColorViews.size(); - bool hasDepth = gpuFramebuffer->gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN; - ccstd::vector attachments(colorViewCount + hasDepth); + const auto *gpuRenderPass = gpuFramebuffer->gpuRenderPass.get(); + const size_t hasDepthStencil = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; + const size_t hasDepthResolve = gpuRenderPass->depthStencilResolveAttachment.format != Format::UNKNOWN ? 1 : 0; + auto attachmentCount = static_cast(colorViewCount + hasDepthStencil + hasDepthResolve); + + ccstd::vector attachments(attachmentCount); VkFramebufferCreateInfo createInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; createInfo.width = createInfo.height = UINT_MAX; @@ -809,14 +807,20 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra createInfo.height = std::min(createInfo.height, std::max(1U, gpuFramebuffer->gpuColorViews[i]->gpuTexture->height >> gpuFramebuffer->gpuColorViews[i]->baseLevel)); } } - if (hasDepth) { + if (hasDepthStencil) { if (gpuFramebuffer->gpuDepthStencilView->gpuTexture->swapchain) { gpuFramebuffer->swapchain = gpuFramebuffer->gpuDepthStencilView->gpuTexture->swapchain; swapchainImageIndices |= (1 << colorViewCount); } else { attachments[colorViewCount] = gpuFramebuffer->gpuDepthStencilView->vkImageView; } + createInfo.width = std::min(createInfo.width, std::max(1U, gpuFramebuffer->gpuDepthStencilView->gpuTexture->width >> gpuFramebuffer->gpuDepthStencilView->baseLevel)); + createInfo.height = std::min(createInfo.height, std::max(1U, gpuFramebuffer->gpuDepthStencilView->gpuTexture->height >> gpuFramebuffer->gpuDepthStencilView->baseLevel)); + } + if (hasDepthResolve) { + attachments[colorViewCount + 1] = gpuFramebuffer->gpuDepthStencilResolveView->vkImageView; } + gpuFramebuffer->isOffscreen = !swapchainImageIndices; gpuFramebuffer->width = createInfo.width; gpuFramebuffer->height = createInfo.height; @@ -1590,33 +1594,6 @@ bool CCVKGPURenderPass::hasShadingAttachment(uint32_t subPassId) const { return subpasses[subPassId].shadingRate != INVALID_BINDING; } -VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format, VkFormat vkFormat, SampleCount sampleCount) const { - if (sampleCount <= SampleCount::ONE) return VK_SAMPLE_COUNT_1_BIT; - - static ccstd::unordered_map cacheMap; - if (!cacheMap.count(format)) { - bool hasDepth = GFX_FORMAT_INFOS[toNumber(format)].hasDepth; - VkImageUsageFlags usages = hasDepth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - - VkImageFormatProperties properties; - vkGetPhysicalDeviceImageFormatProperties(physicalDevice, vkFormat, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, usages, 0, &properties); - cacheMap[format] = properties.sampleCounts; - } - - VkSampleCountFlags availableSampleCounts = cacheMap[format]; - - auto requestedSampleCount = VK_SAMPLE_COUNT_FLAGS[toNumber(sampleCount)]; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_64_BIT) return VK_SAMPLE_COUNT_64_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_32_BIT) return VK_SAMPLE_COUNT_32_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_16_BIT) return VK_SAMPLE_COUNT_16_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_8_BIT) return VK_SAMPLE_COUNT_8_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_4_BIT) return VK_SAMPLE_COUNT_4_BIT; - if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_2_BIT) return VK_SAMPLE_COUNT_2_BIT; - - return VK_SAMPLE_COUNT_1_BIT; -} - void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { if (_buffersToBeChecked.empty() && _texturesToBeChecked.empty()) return; diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index acc577be13c..85d9bacdfcb 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -768,6 +768,7 @@ void CCVKDevice::initDeviceFeature() { _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = true; _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = checkExtension("VK_KHR_depth_stencil_resolve"); } void CCVKDevice::initFormatFeature() { @@ -1084,5 +1085,23 @@ static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( return vkCreateRenderPass(device, &renderPassCreateInfo, pAllocator, pRenderPass); } +SampleCount CCVKDevice::getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const { + auto vkFormat = mapVkFormat(format, gpuDevice()); + auto usages = mapVkImageUsageFlags(usage, flags); + + VkImageFormatProperties imageFormatProperties = {}; + vkGetPhysicalDeviceImageFormatProperties(_gpuContext->physicalDevice, vkFormat, VK_IMAGE_TYPE_2D, + VK_IMAGE_TILING_OPTIMAL, usages, 0, &imageFormatProperties); + + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_64_BIT) return SampleCount::X64; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_32_BIT) return SampleCount::X32; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_16_BIT) return SampleCount::X16; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_8_BIT) return SampleCount::X8; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_4_BIT) return SampleCount::X4; + if (imageFormatProperties.sampleCounts & VK_SAMPLE_COUNT_2_BIT) return SampleCount::X2; + + return SampleCount::X1; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index c53f6cb20ad..4d7d9c938a8 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -105,7 +105,7 @@ class CC_VULKAN_API CCVKDevice final : public Device { void waitAllFences(); void updateBackBufferCount(uint32_t backBufferCount); - + SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; protected: static CCVKDevice *instance; diff --git a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp index efb463ba464..7bf4d5d2881 100644 --- a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp @@ -54,6 +54,11 @@ void CCVKFramebuffer::doInit(const FramebufferInfo & /*info*/) { _gpuFBO->gpuDepthStencilView = depthTex->gpuTextureView(); } + if (_depthStencilResolveTexture) { + auto *depthTex = static_cast(_depthStencilResolveTexture); + _gpuFBO->gpuDepthStencilResolveView = depthTex->gpuTextureView(); + } + cmdFuncCCVKCreateFramebuffer(CCVKDevice::getInstance(), _gpuFBO); } diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index c47e4a76fae..cb386223c67 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -71,8 +71,6 @@ class CCVKGPUContext final { return std::strcmp(ext, extension.c_str()) == 0; }); } - - VkSampleCountFlagBits getSampleCountForAttachments(Format format, VkFormat vkFormat, SampleCount sampleCount) const; }; struct CCVKAccessInfo { @@ -119,6 +117,7 @@ class CCVKGPURenderPass final : public CCVKGPUDeviceObject { ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; + DepthStencilAttachment depthStencilResolveAttachment; SubpassInfoList subpasses; SubpassDependencyList dependencies; @@ -148,10 +147,19 @@ struct CCVKGPUTexture : public CCVKGPUDeviceObject { uint32_t size = 0U; uint32_t arrayLayers = 1U; uint32_t mipLevels = 1U; - SampleCount samples = SampleCount::ONE; + SampleCount samples = SampleCount::X1; TextureFlags flags = TextureFlagBit::NONE; VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - bool memoryless = false; + + /* + * allocate and bind memory by Texture. + * If any of the following conditions are met, then the statement is false + * 1. Texture is a swapchain image. + * 2. Texture has flag LAZILY_ALLOCATED. + * 3. Memory bound manually bound. + * 4. Sparse Image. + */ + bool memoryAllocated = true; VkImage vkImage = VK_NULL_HANDLE; VmaAllocation vmaAllocation = VK_NULL_HANDLE; @@ -258,6 +266,7 @@ struct CCVKGPUFramebuffer : public CCVKGPUDeviceObject { ConstPtr gpuRenderPass; ccstd::vector> gpuColorViews; ConstPtr gpuDepthStencilView; + ConstPtr gpuDepthStencilResolveView; VkFramebuffer vkFramebuffer = VK_NULL_HANDLE; std::vector vkFrameBuffers; CCVKGPUSwapchain *swapchain = nullptr; diff --git a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp index 8597bf22a8b..ce705b9ee89 100644 --- a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp @@ -41,6 +41,7 @@ void CCVKRenderPass::doInit(const RenderPassInfo & /*info*/) { _gpuRenderPass = ccnew CCVKGPURenderPass; _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; + _gpuRenderPass->depthStencilResolveAttachment = _depthStencilResolveAttachment; _gpuRenderPass->subpasses = _subpasses; _gpuRenderPass->dependencies = _dependencies; @@ -56,14 +57,17 @@ void CCVKRenderPass::doInit(const RenderPassInfo & /*info*/) { if (_depthStencilAttachment.format != Format::UNKNOWN) { subpass.depthStencil = colorCount; } + if (_depthStencilResolveAttachment.format != Format::UNKNOWN) { + subpass.depthStencilResolve = colorCount + 1; + } } else { // unify depth stencil index for (auto &subpass : _gpuRenderPass->subpasses) { - if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil > colorCount) { + if (subpass.depthStencil != INVALID_BINDING && subpass.depthStencil >= colorCount) { subpass.depthStencil = colorCount; } - if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencilResolve > colorCount) { - subpass.depthStencilResolve = colorCount; + if (subpass.depthStencilResolve != INVALID_BINDING && subpass.depthStencilResolve >= colorCount) { + subpass.depthStencilResolve = colorCount + 1; } } } diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp index 8af0555a995..5f0a3e85b47 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp @@ -60,7 +60,7 @@ void CCVKTexture::createTexture(uint32_t width, uint32_t height, uint32_t size, if (_swapchain != nullptr) { _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); - _gpuTexture->memoryless = true; + _gpuTexture->memoryAllocated = false; } _gpuTexture->type = _info.type; @@ -121,14 +121,14 @@ void CCVKTexture::doInit(const SwapchainTextureInfo & /*info*/) { void CCVKGPUTexture::init() { cmdFuncCCVKCreateTexture(CCVKDevice::getInstance(), this); - if (!memoryless) { + if (memoryAllocated) { CCVKDevice::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_INC(Texture, size); } } void CCVKGPUTexture::shutdown() { - if (!memoryless) { + if (memoryAllocated) { CCVKDevice::getInstance()->getMemoryStatus().textureSize -= size; CC_PROFILE_MEMORY_DEC(Texture, size); } diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp index 2b328b47e18..4d9c78dfc6e 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp @@ -229,8 +229,8 @@ VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage) { return static_cast(flags); } -VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage) { - uint32_t flags = 0U; +VkImageUsageFlags mapVkImageUsageFlags(TextureUsage usage, TextureFlags textureFlags) { + VkImageUsageFlags flags = 0; if (hasFlag(usage, TextureUsage::TRANSFER_SRC)) flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if (hasFlag(usage, TextureUsage::TRANSFER_DST)) flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (hasFlag(usage, TextureUsage::SAMPLED)) flags |= VK_IMAGE_USAGE_SAMPLED_BIT; @@ -239,7 +239,14 @@ VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage) { if (hasFlag(usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT)) flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; if (hasFlag(usage, TextureUsage::INPUT_ATTACHMENT)) flags |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; if (hasFlag(usage, TextureUsage::SHADING_RATE)) flags |= VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR; - return static_cast(flags); + + if (hasFlag(textureFlags, TextureFlags::GEN_MIPMAP)) { + flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } + if (hasFlag(textureFlags, TextureFlags::LAZILY_ALLOCATED)) { + flags |= VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; + } + return flags; } VkImageAspectFlags mapVkImageAspectFlags(Format format) { @@ -493,17 +500,6 @@ const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[] = { VK_STENCIL_FACE_FRONT_AND_BACK, }; -const VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[] = { - VK_SAMPLE_COUNT_1_BIT, - VK_SAMPLE_COUNT_2_BIT, -#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_IOS - VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, -#else // desktop platforms - VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, -#endif - VK_SAMPLE_COUNT_16_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, -}; - const VkAccessFlags FULL_ACCESS_FLAGS = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT | diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.h b/native/cocos/renderer/gfx-vulkan/VKUtils.h index 4b7ac04abee..26bf88d35ea 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.h +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.h @@ -58,7 +58,7 @@ VkAttachmentStoreOp mapVkStoreOp(StoreOp storeOp); VkBufferUsageFlagBits mapVkBufferUsageFlagBits(BufferUsage usage); VkImageType mapVkImageType(TextureType type); VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage); -VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage); +VkImageUsageFlags mapVkImageUsageFlags(TextureUsage usage, TextureFlags textureFlags); VkImageAspectFlags mapVkImageAspectFlags(Format format); VkImageCreateFlags mapVkImageCreateFlags(TextureType type); VkImageViewType mapVkImageViewType(TextureType viewType); @@ -94,7 +94,6 @@ extern const VkPipelineBindPoint VK_PIPELINE_BIND_POINTS[]; extern const VkResolveModeFlagBits VK_RESOLVE_MODES[]; extern const VkImageLayout VK_IMAGE_LAYOUTS[]; extern const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[]; -extern const VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[]; extern const VkAccessFlags FULL_ACCESS_FLAGS; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp index b9f2c8b0703..432b1ad9ef7 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp @@ -169,7 +169,7 @@ void CCWGPUDescriptorSetLayout::updateTextureLayout(uint8_t binding, const CCWGP const CCWGPUTexture *ccTex = static_cast(texture->isTextureView() ? texture->getViewInfo().texture : texture); TextureType type = ccTex->getViewInfo().type; (*iter).texture.viewDimension = toWGPUTextureViewDimension(type); - (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::ONE; + (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::X1; } } else { (*iter).texture.nextInChain = nullptr; diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp index 467e0f1639d..dc425a1ae64 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp @@ -36,13 +36,13 @@ using namespace emscripten; class CCWGPURenderPassHelper { public: explicit CCWGPURenderPassHelper(const RenderPassInfo &info) { - SampleCount samples = SampleCount::ONE; + SampleCount samples = SampleCount::X1; for (size_t i = 0; i < info.colorAttachments.size(); i++) { colors[i].loadOp = toWGPULoadOp(info.colorAttachments[i].loadOp); colors[i].storeOp = toWGPUStoreOp(info.colorAttachments[i].storeOp); colors[i].clearValue = defaultClearColor; // TODO_Zeqaing : subpass - if (info.colorAttachments[i].sampleCount != SampleCount::ONE) + if (info.colorAttachments[i].sampleCount != SampleCount::X1) samples = info.colorAttachments[i].sampleCount; } @@ -54,7 +54,7 @@ class CCWGPURenderPassHelper { depthStencils[0].depthClearValue = defaultClearDepth; depthStencils[0].depthReadOnly = false; depthStencils[0].stencilReadOnly = false; - if (samples == SampleCount::ONE) + if (samples == SampleCount::X1) samples = info.depthStencilAttachment.sampleCount; renderPassDesc = ccnew WGPURenderPassDescriptor; @@ -106,4 +106,4 @@ void CCWGPURenderPass::doDestroy() { } } // namespace gfx -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp index d3f486c99ba..77f723e0c13 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp @@ -234,7 +234,7 @@ CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { .flags = TextureFlagBit::NONE, .layerCount = 1, .levelCount = 1, - .samples = SampleCount::ONE, + .samples = SampleCount::X1, .depth = 1, .externalRes = nullptr, }; @@ -256,7 +256,7 @@ CCWGPUTexture *CCWGPUTexture::defaultStorageTexture() { .flags = TextureFlagBit::NONE, .layerCount = 1, .levelCount = 1, - .samples = SampleCount::ONE, + .samples = SampleCount::X1, .depth = 1, .externalRes = nullptr, }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h index 1ab82fb8fc3..f79f50c4896 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUUtils.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUUtils.h @@ -395,21 +395,7 @@ static WGPUShaderStageFlags toWGPUShaderStageFlag(ShaderStageFlagBit flag) { // TODO_Zeqiang: more flexible strategy static uint32_t toWGPUSampleCount(SampleCount sampleCount) { - // TODO_Zeqiang: msaa - return 1; - switch (sampleCount) { - case SampleCount::ONE: - return 1; - case SampleCount::MULTIPLE_PERFORMANCE: - return 4; - case SampleCount::MULTIPLE_BALANCE: - return 4; - case SampleCount::MULTIPLE_QUALITY: - return 4; - default: - printf("unsupport sampleCount %d.", sampleCount); - return 1; - } + return static_cast(sampleCount); } // NONE = 0, diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index 7cbecfdf110..4dc96a47421 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -40,7 +40,7 @@ #if CC_USE_DEBUG_RENDERER #include "profiler/DebugRenderer.h" #endif -#include "custom/NativeUtils.h" +#include "custom/NativeBuiltinUtils.h" #include "scene/Camera.h" #include "scene/Skybox.h" diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index f89f2c4aa2c..0ac3830c647 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -114,7 +114,10 @@ struct LayoutAccess { struct FGRenderPassInfo { std::vector colorAccesses; LayoutAccess dsAccess; + LayoutAccess dsResolveAccess; gfx::RenderPassInfo rpInfo; + std::vector orderedViews; + bool needResolve{false}; }; struct ResourceAccessGraph { diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 7ea920e5133..1a2cffac76a 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include "FGDispatcherGraphs.h" #include "FGDispatcherTypes.h" @@ -494,6 +495,9 @@ struct BarrierVisitor : public boost::bfs_visitor<> { dependency.srcSubpass = INVALID_ID; dependency.dstSubpass = subpassIdx; for (const auto &barrier : barriers.frontBarriers) { + if (barrier.beginStatus.accessFlag == gfx::AccessFlagBit::NONE) { + continue; + } auto resID = barrier.resourceID; auto findBarrierByResID = [resID](const Barrier &barrier) { return barrier.resourceID == resID; @@ -1034,7 +1038,8 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { if (batchedBarriers.find(i) == batchedBarriers.end()) { batchedBarriers.emplace(i, BarrierNode{}); auto &rpInfo = rag.rpInfos[i].rpInfo; - if (rpInfo.subpasses.size() > 1) { + // NOLINTNEXTLINE (readability-container-size-empty) + if (rpInfo.subpasses.size() >= 1) { batchedBarriers[i].subpassBarriers.resize(rpInfo.subpasses.size()); } } @@ -1097,8 +1102,9 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { // external res barrier for next frame for (const auto &externalPair : externalResMap) { + const auto &resName = externalPair.first; const auto &transition = externalPair.second; - auto resID = resourceGraph.valueIndex.at(externalPair.first); + auto resID = resourceGraph.valueIndex.at(resName); const auto &resTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, resID); auto &rescStates = get(ResourceGraph::StatesTag{}, resourceGraph, resID); @@ -1107,7 +1113,7 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { // 1. resource been written in this frame; // 2. first meet in this frame (no idea if any writes in next frame) // 3. backbuffer present - bool needNextBarrier = (namesSet.find(externalPair.first) != namesSet.end()) || (rescStates.states == gfx::AccessFlagBit::NONE); + bool needNextBarrier = (namesSet.find(resName) != namesSet.end()) || (rescStates.states == gfx::AccessFlagBit::NONE); // persistant resource states cached here rescStates.states = transition.currStatus.accessFlag; @@ -1144,21 +1150,13 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { bool hasSubpass = !(batchedBarriers[passID].subpassBarriers.size() <= 1); if (hasSubpass) { - auto &subpassBarriers = batchedBarriers[passID].subpassBarriers; - for (int i = static_cast(subpassBarriers.size()) - 1; i >= 0; --i) { - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - - const auto &frontBarriers = subpassBarriers[i].frontBarriers; - auto &rearBarriers = subpassBarriers[i].rearBarriers; - auto found = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID) != frontBarriers.end() || - std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID) != rearBarriers.end(); - if (found) { - rearBarriers.push_back(nextFrameResBarrier); - break; - } - } + // rpinfo instead + auto &fgRenderPassInfo = rag.rpInfos.at(passID); + auto iter = std::find(fgRenderPassInfo.orderedViews.begin(), fgRenderPassInfo.orderedViews.end(), resName.c_str()); + CC_ASSERT(iter != fgRenderPassInfo.orderedViews.end()); + auto index = std::distance(fgRenderPassInfo.orderedViews.begin(), iter); + index -= fgRenderPassInfo.rpInfo.depthStencilAttachment.format != gfx::Format::UNKNOWN; + fgRenderPassInfo.colorAccesses[index].nextAccess = nextFrameResBarrier.endStatus.accessFlag; } else { auto &rearBarriers = batchedBarriers[passID].blockBarrier.rearBarriers; rearBarriers.emplace_back(nextFrameResBarrier); @@ -1235,6 +1233,11 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { const auto &dsAccess = fgRenderpassInfo.dsAccess; dsAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); } + auto &dsResolveAttachment = fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; + if (dsResolveAttachment.format != gfx::Format::UNKNOWN) { + const auto &dsAccess = fgRenderpassInfo.dsResolveAccess; + dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); + } } } } @@ -1860,13 +1863,15 @@ auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAcce gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; // TODO(Zeqiang): visbility of slot name "_" not found - if (memAccess == gfx::MemoryAccess::READ_ONLY) { + if (hasFlag(memAccess, gfx::MemoryAccess::READ_ONLY)) { if ((desc.flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE && rasterized) { texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::INPUT_ATTACHMENT)); } else { texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::SAMPLED | gfx::TextureUsage::STORAGE | gfx::TextureUsage::SHADING_RATE | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT)); } - } else { + } + + if (hasFlag(memAccess, gfx::MemoryAccess::WRITE_ONLY)) { texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::STORAGE)); } @@ -2092,23 +2097,65 @@ bool checkComputeViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, P return dependent; } -void fillRenderPassInfo(const RasterView &view, gfx::RenderPassInfo &rpInfo, uint32_t index, const ResourceDesc &viewDesc) { - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { +bool checkResolveResource(const Graphs &graphs, uint32_t vertID, uint32_t /*passID*/, ResourceAccessNode &node, const ccstd::pmr::vector &resolves) { + const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + bool dependent = false; + for (const auto &pair : resolves) { + const auto &resolveTargetName = pair.target; + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex(resolveTargetName, resourceGraph)); + gfx::AccessFlags accessFlag = gfx::AccessFlags::COLOR_ATTACHMENT_WRITE; + gfx::TextureUsage usage = gfx::TextureUsage::COLOR_ATTACHMENT; + if (desc.format == gfx::Format::DEPTH_STENCIL) { + accessFlag = gfx::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE; + usage = gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; + } + ViewStatus viewStatus{resolveTargetName, + PassType::RASTER, + gfx::ShaderStageFlags::FRAGMENT, + gfx::MemoryAccess::WRITE_ONLY, + accessFlag, usage}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); + if (lastVertId != INVALID_ID) { + tryAddEdge(lastVertId, vertID, resourceAccessGraph); + tryAddEdge(lastVertId, vertID, relationGraph); + dependent = true; + } + } + // sort for vector intersection + std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); + + return dependent; +} + +void fillRenderPassInfo(gfx::LoadOp loadOp, gfx::StoreOp storeOp, AttachmentType attachmentType, gfx::RenderPassInfo &rpInfo, uint32_t index, const ResourceDesc &viewDesc, bool resolve) { + if (attachmentType != AttachmentType::DEPTH_STENCIL) { auto &colorAttachment = rpInfo.colorAttachments[index]; - colorAttachment.format = viewDesc.format; - colorAttachment.loadOp = view.loadOp; - colorAttachment.storeOp = view.storeOp; - colorAttachment.sampleCount = viewDesc.sampleCount; - // colorAttachment.barrier = getGeneralBarrier(gfx::Device::getInstance(), view, prevAccess, nextAccess); + if (colorAttachment.format == gfx::Format::UNKNOWN) { + colorAttachment.format = viewDesc.format; + colorAttachment.loadOp = loadOp; + colorAttachment.storeOp = storeOp; + colorAttachment.sampleCount = viewDesc.sampleCount; + } else { + colorAttachment.storeOp = storeOp; + } + } else { - auto &depthStencilAttachment = rpInfo.depthStencilAttachment; - depthStencilAttachment.format = viewDesc.format; - depthStencilAttachment.depthLoadOp = view.loadOp; - depthStencilAttachment.depthStoreOp = view.storeOp; - depthStencilAttachment.stencilLoadOp = view.loadOp; - depthStencilAttachment.stencilStoreOp = view.storeOp; - depthStencilAttachment.sampleCount = viewDesc.sampleCount; - // depthStencilAttachment.barrier = getGeneralBarrier(gfx::Device::getInstance(), view, prevAccess, nextAccess); + auto &depthStencilAttachment = resolve ? + rpInfo.depthStencilResolveAttachment : + rpInfo.depthStencilAttachment; + if (depthStencilAttachment.format == gfx::Format::UNKNOWN) { + depthStencilAttachment.format = viewDesc.format; + depthStencilAttachment.depthLoadOp = loadOp; + depthStencilAttachment.depthStoreOp = storeOp; + depthStencilAttachment.stencilLoadOp = loadOp; + depthStencilAttachment.stencilStoreOp = storeOp; + depthStencilAttachment.sampleCount = viewDesc.sampleCount; + } else { + // TODO(Zeqiang): separate ds + depthStencilAttachment.depthStoreOp = storeOp; + depthStencilAttachment.stencilStoreOp = storeOp; + } } } @@ -2153,7 +2200,6 @@ void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass & const auto &view = pass.rasterViews.at(name); const auto &viewDesc = get(ResourceGraph::DescTag{}, resourceGraph, resID); auto prevAccess = pair.second; - CC_ASSERT(slotID < node.attachmentStatus.size()); // TD:remove find auto nodeIter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), [resID](const AccessStatus &status) { return status.vertID == resID; @@ -2182,10 +2228,27 @@ void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass & fgRenderpassInfo.dsAccess.prevAccess = prevAccess; fgRenderpassInfo.dsAccess.nextAccess = nextAccess; } - fillRenderPassInfo(view, rpInfo, slotID, viewDesc); + fillRenderPassInfo(view.loadOp, view.storeOp, view.attachmentType, rpInfo, slotID, viewDesc, false); + fgRenderpassInfo.orderedViews.emplace_back(name); } } else { - auto colorSize = pass.attachmentIndexMap.size(); + auto colorSize = pass.rasterViews.size(); + bool hasDS = std::any_of(pass.rasterViews.begin(), pass.rasterViews.end(), [](const auto &pair) { + return pair.second.attachmentType == AttachmentType::DEPTH_STENCIL; + }); + colorSize -= hasDS; + const auto &subpasses = pass.subpassGraph.subpasses; + uint32_t count = 0; + const auto &resg = resourceGraph; + auto resolveNum = std::accumulate(subpasses.begin(), subpasses.end(), 0, [&resg](uint32_t initVal, const Subpass &subpass) { + auto iter = std::find_if(subpass.resolvePairs.begin(), subpass.resolvePairs.end(), [&resg](const auto &pair) { + auto resID = vertex(pair.target, resg); + const auto& desc = get(ResourceGraph::DescTag{}, resg, resID); + return desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH; + }); + return initVal + subpass.resolvePairs.size() - (iter != subpass.resolvePairs.end()); + }); + colorSize += resolveNum; rpInfo.colorAttachments.resize(colorSize); fgRenderpassInfo.colorAccesses.resize(colorSize); } @@ -2266,6 +2329,7 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub uint32_t accessType; uint32_t attachmentType; std::string_view slotName; + uint32_t samplesReverseWeight; }; using RasterViewSortKey = std::tuple; struct SubpassRasterViewData { @@ -2274,15 +2338,35 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub gfx::AccessFlags access; }; + bool hasDS{false}; ccstd::vector viewIndex; for (const auto &[name, view] : pass.rasterViews) { auto resIter = rag.resourceIndex.find(name); + const auto &resID = vertex(name, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resg, resID); + gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; + viewIndex.emplace_back(SubpassRasterViewData{ + {ACCESS_TYPE_WEIGHT[static_cast(view.accessType)], ATTACHMENT_TYPE_WEIGHT[static_cast(view.attachmentType)], view.slotName, static_cast(desc.sampleCount)}, + name, + prevAccess, + }); + hasDS |= view.attachmentType == AttachmentType::DEPTH_STENCIL; + } + + for (const auto &resolve : pass.resolvePairs) { + auto resIter = rag.resourceIndex.find(resolve.target); gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; viewIndex.emplace_back(SubpassRasterViewData{ - {ACCESS_TYPE_WEIGHT[static_cast(view.accessType)], ATTACHMENT_TYPE_WEIGHT[static_cast(view.attachmentType)], view.slotName}, name, prevAccess}); + {ACCESS_TYPE_WEIGHT[static_cast(AccessType::WRITE)], ATTACHMENT_TYPE_WEIGHT[static_cast(AttachmentType::RENDER_TARGET)], "_", 0xFFFFFFFF}, + resolve.target, + prevAccess, + }); } std::sort(viewIndex.begin(), viewIndex.end(), [](const SubpassRasterViewData &lhs, const SubpassRasterViewData &rhs) { + if (lhs.sortKey.samplesReverseWeight != rhs.sortKey.samplesReverseWeight) { + return lhs.sortKey.samplesReverseWeight < rhs.sortKey.samplesReverseWeight; + } if (lhs.sortKey.accessType != rhs.sortKey.accessType) { return lhs.sortKey.accessType < rhs.sortKey.accessType; } @@ -2308,49 +2392,94 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub bool dependent{false}; dependent |= checkRasterViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.rasterViews); dependent |= checkComputeViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.computeViews); + dependent |= checkResolveResource(graphs, parentRagVert, passID, *head, pass.resolvePairs); if (!dependent) { tryAddEdge(EXPECT_START_ID, parentRagVert, resourceAccessGraph); tryAddEdge(EXPECT_START_ID, parentRagVert, relationGraph); } + if (!pass.resolvePairs.empty()) { + // ds resolve stores in depthStencilResolve + subpassInfo.resolves.resize(pass.rasterViews.size() - hasDS, gfx::INVALID_BINDING); + } + uint32_t localSlot = 0; + bool dsAppeared{false}; for (const auto &[sortKey, name, access] : viewIndex) { const auto *const resName = name.data(); auto findByResID = [&](const AccessStatus &status) { return status.vertID == rag.resourceIndex.at(resName); }; auto iter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), findByResID); - const auto &view = pass.rasterViews.at(resName); + + // TODO(Zeqiang): remove find + const auto &targetName = name; auto resID = rag.resourceIndex.at(resName); const auto &viewDesc = get(ResourceGraph::DescTag{}, resg, rag.resourceIndex.at(resName)); - uint32_t slot = uberPass.attachmentIndexMap.size(); - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { + AttachmentType attachmentType{AttachmentType::RENDER_TARGET}; + AccessType accessType{AccessType::WRITE}; + gfx::LoadOp loadOp{gfx::LoadOp::DISCARD}; + gfx::StoreOp storeOp{gfx::StoreOp::STORE}; + + uint32_t slot = dsAppeared ? localSlot - 1 : localSlot; + // std::distance(uberPass.rasterViews.begin(), uberPass.rasterViews.find(resName)); + // slot = dsAppeared ? slot - 1 : slot; + /*if (attachmentType != AttachmentType::DEPTH_STENCIL) { CC_ASSERT(uberPass.attachmentIndexMap.count(resName)); slot = uberPass.attachmentIndexMap.at(resName); - } + }*/ // TD:remove find auto nodeIter = std::find_if(head->attachmentStatus.begin(), head->attachmentStatus.end(), [resID](const AccessStatus &status) { return status.vertID == resID; }); auto nextAccess = nodeIter->accessFlag; - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { - if (view.attachmentType == AttachmentType::SHADING_RATE) { - subpassInfo.shadingRate = slot; + + auto resolveIter = std::find_if(pass.resolvePairs.begin(), pass.resolvePairs.end(), [&targetName](const ResolvePair &resolve) { + return strcmp(resolve.target.c_str(), targetName.data()) == 0; + }); + bool resolveView = resolveIter != pass.resolvePairs.end(); + if (resolveView) { + attachmentType = viewDesc.format == gfx::Format::DEPTH_STENCIL ? AttachmentType::DEPTH_STENCIL : AttachmentType::RENDER_TARGET; + if (attachmentType == AttachmentType::DEPTH_STENCIL) { + subpassInfo.depthStencilResolve = slot; + subpassInfo.depthResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode; + subpassInfo.stencilResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode1; + fgRenderpassInfo.dsResolveAccess.nextAccess = nextAccess; } else { - if (view.accessType != AccessType::READ) { - subpassInfo.colors.emplace_back(slot); - } - if (view.accessType != AccessType::WRITE) { - subpassInfo.inputs.emplace_back(slot); - } + auto indexIter = std::find(fgRenderpassInfo.orderedViews.begin(), fgRenderpassInfo.orderedViews.end(), resolveIter->source.c_str()); + auto srcIndex = indexIter == fgRenderpassInfo.orderedViews.end() ? fgRenderpassInfo.orderedViews.size() + : std::distance(fgRenderpassInfo.orderedViews.begin(), indexIter); + subpassInfo.resolves[srcIndex] = slot; + fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; } - fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; + accessType = AccessType::WRITE; } else { - fgRenderpassInfo.dsAccess.nextAccess = nextAccess; - subpassInfo.depthStencil = rpInfo.colorAttachments.size(); + const auto &view = pass.rasterViews.at(resName); + attachmentType = view.attachmentType; + accessType = view.accessType; + loadOp = view.loadOp; + storeOp = view.storeOp; + + if (attachmentType != AttachmentType::DEPTH_STENCIL) { + if (attachmentType == AttachmentType::SHADING_RATE) { + subpassInfo.shadingRate = slot; + } else { + if (accessType != AccessType::READ) { + subpassInfo.colors.emplace_back(slot); + } + if (accessType != AccessType::WRITE) { + subpassInfo.inputs.emplace_back(slot); + } + } + fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; + } else { + fgRenderpassInfo.dsAccess.nextAccess = nextAccess; + subpassInfo.depthStencil = rpInfo.colorAttachments.size(); + dsAppeared = true; + } } if (iter == node.attachmentStatus.end()) { @@ -2360,13 +2489,19 @@ void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSub CC_ASSERT(head->attachmentStatus.size() > localSlot); auto nextAccess = head->attachmentStatus[localSlot].accessFlag; - if (view.attachmentType == AttachmentType::DEPTH_STENCIL) { - fgRenderpassInfo.dsAccess.prevAccess = prevAccess; + if (attachmentType == AttachmentType::DEPTH_STENCIL) { + if (resolveView) { + fgRenderpassInfo.dsResolveAccess.prevAccess = prevAccess; + } else { + fgRenderpassInfo.dsAccess.prevAccess = prevAccess; + } } else { fgRenderpassInfo.colorAccesses[slot].prevAccess = prevAccess; } - fillRenderPassInfo(view, rpInfo, slot, viewDesc); + fgRenderpassInfo.orderedViews.emplace_back(resName); } + fillRenderPassInfo(loadOp, storeOp, attachmentType, rpInfo, slot, viewDesc, resolveView); + fgRenderpassInfo.needResolve |= resolveView; ++localSlot; } diff --git a/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp new file mode 100644 index 00000000000..07c7d0aaa33 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.cpp @@ -0,0 +1,557 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "NativeBuiltinUtils.h" +#include "cocos/application/ApplicationManager.h" +#include "cocos/renderer/gfx-base/GFXDef-common.h" +#include "cocos/renderer/gfx-base/GFXDevice.h" +#include "cocos/renderer/pipeline/PipelineSceneData.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" +#include "cocos/renderer/pipeline/custom/NativeTypes.h" +#include "cocos/renderer/pipeline/custom/NativeUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" +#include "cocos/scene/Camera.h" +#include "cocos/scene/Fog.h" +#include "cocos/scene/Skybox.h" +#include "cocos/scene/SpotLight.h" + +namespace cc { + +namespace render { + +void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]) { + auto minX = static_cast(viewport.x); + auto maxX = static_cast(viewport.x + viewport.z); + auto minY = static_cast(viewport.y); + auto maxY = static_cast(viewport.y + viewport.w); + if (device.getCapabilities().screenSpaceSignY > 0) { + std::swap(minY, maxY); + } + int n = 0; + vbData[n++] = -1.0F; + vbData[n++] = -1.0F; + vbData[n++] = minX; // uv + vbData[n++] = maxY; + vbData[n++] = 1.0F; + vbData[n++] = -1.0F; + vbData[n++] = maxX; + vbData[n++] = maxY; + vbData[n++] = -1.0F; + vbData[n++] = 1.0F; + vbData[n++] = minX; + vbData[n++] = minY; + vbData[n++] = 1.0F; + vbData[n++] = 1.0F; + vbData[n++] = maxX; + vbData[n++] = minY; +} + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) +void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter) { + const auto &root = *Root::getInstance(); + const auto shadingWidth = static_cast(width); + const auto shadingHeight = static_cast(height); + setter.setVec4( + "cc_time", + Vec4( + root.getCumulativeTime(), + root.getFrameTime(), + static_cast(CC_CURRENT_ENGINE()->getTotalFrames()), + 0.0F)); + + setter.setVec4( + "cc_screenSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); + setter.setVec4( + "cc_nativeSize", + Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); +#if 0 + const auto *debugView = root.getDebugView(); + if (debugView) { + setter.setVec4( + "cc_debug_view_mode", + Vec4(static_cast(debugView->getSingleMode()), + debugView->isLightingWithAlbedo() ? 1.0F : 0.0F, + debugView->isCsmLayerColoration() ? 1.0F : 0.0F, + 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = debugView->isCompositeModeEnabled(i) ? 1.0F : 0.0F; + const auto packIdx = static_cast(floor(static_cast(i) / 4.0F)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } else { + setter.setVec4("cc_debug_view_mode", Vec4(0.0F, 1.0F, 0.0F, 0.0F)); + Vec4 debugPackVec{}; + for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); + i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { + const auto idx = i % 4; + (&debugPackVec.x)[idx] = 1.0F; + const auto packIdx = static_cast(floor(i / 4.0)); + if (idx == 3) { + std::string name("cc_debug_view_composite_pack_"); + name.append(std::to_string(packIdx + 1)); + setter.setVec4(name, debugPackVec); + } + } + } +#endif +} + +namespace { + +uint8_t getCombineSignY(gfx::Device *device) { + // 0: vk, 1: metal, 2: none, 3: gl-like + static int8_t combineSignY{-1}; + if (combineSignY < 0) { + const float screenSpaceSignY = device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F; + const float clipSpaceSignY = device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; + combineSignY = static_cast(static_cast(screenSpaceSignY) << 1 | static_cast(clipSpaceSignY)); + } + return static_cast(combineSignY); +} + +} // namespace + +void setCameraUBOValues( + const scene::Camera &camera, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &cfg, + const scene::DirectionalLight *mainLight, + RenderData &data) { + CC_EXPECTS(camera.getNode()); + CC_EXPECTS(cfg.getSkybox()); + const auto &skybox = *cfg.getSkybox(); + const auto &shadingScale = cfg.getShadingScale(); + // Camera + setMat4Impl(data, layoutGraph, "cc_matView", camera.getMatView()); + setMat4Impl(data, layoutGraph, "cc_matViewInv", camera.getNode()->getWorldMatrix()); + setMat4Impl(data, layoutGraph, "cc_matProj", camera.getMatProj()); + setMat4Impl(data, layoutGraph, "cc_matProjInv", camera.getMatProjInv()); + setMat4Impl(data, layoutGraph, "cc_matViewProj", camera.getMatViewProj()); + setMat4Impl(data, layoutGraph, "cc_matViewProjInv", camera.getMatViewProjInv()); + setVec4Impl(data, layoutGraph, "cc_cameraPos", + Vec4( + camera.getPosition().x, + camera.getPosition().y, + camera.getPosition().z, + getCombineSignY(cc::gfx::Device::getInstance()))); + setVec4Impl(data, layoutGraph, "cc_surfaceTransform", + Vec4( + static_cast(camera.getSurfaceTransform()), + static_cast(camera.getCameraUsage()), + cosf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))), + sinf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))))); + setVec4Impl(data, layoutGraph, "cc_screenScale", + Vec4( + cfg.getShadingScale(), + cfg.getShadingScale(), + 1.0F / cfg.getShadingScale(), + 1.0F / cfg.getShadingScale())); + setVec4Impl(data, layoutGraph, "cc_exposure", + Vec4( + camera.getExposure(), + 1.0F / camera.getExposure(), + cfg.isHDR() ? 1.0F : 0.0F, + 1.0F / scene::Camera::getStandardExposureValue())); + + if (mainLight) { + const auto &shadowInfo = *cfg.getShadows(); + const bool shadowEnable = (mainLight->isShadowEnabled() && + shadowInfo.getType() == scene::ShadowType::SHADOW_MAP); + setVec4Impl(data, layoutGraph, "cc_mainLitDir", + Vec4( + mainLight->getDirection().x, + mainLight->getDirection().y, + mainLight->getDirection().z, + shadowEnable)); + auto r = mainLight->getColor().x; + auto g = mainLight->getColor().y; + auto b = mainLight->getColor().z; + if (mainLight->isUseColorTemperature()) { + r *= mainLight->getColorTemperatureRGB().x; + g *= mainLight->getColorTemperatureRGB().y; + b *= mainLight->getColorTemperatureRGB().z; + } + auto w = mainLight->getIlluminance(); + if (cfg.isHDR()) { + w *= camera.getExposure(); + } + setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(r, g, b, w)); + } else { + setVec4Impl(data, layoutGraph, "cc_mainLitDir", Vec4(0, 0, 1, 0)); + setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(0, 0, 0, 0)); + } + + CC_EXPECTS(cfg.getAmbient()); + auto &ambient = *cfg.getAmbient(); + auto &skyColor = ambient.getSkyColor(); + if (cfg.isHDR()) { + skyColor.w = ambient.getSkyIllum() * camera.getExposure(); + } else { + skyColor.w = ambient.getSkyIllum(); + } + setVec4Impl(data, layoutGraph, "cc_ambientSky", + Vec4(skyColor.x, skyColor.y, skyColor.z, skyColor.w)); + setVec4Impl(data, layoutGraph, "cc_ambientGround", + Vec4( + ambient.getGroundAlbedo().x, + ambient.getGroundAlbedo().y, + ambient.getGroundAlbedo().z, + skybox.getEnvmap() ? static_cast(skybox.getEnvmap()->mipmapLevel()) : 1.0F)); + + CC_EXPECTS(cfg.getFog()); + const auto &fog = *cfg.getFog(); + + const auto &colorTempRGB = fog.getColorArray(); + setVec4Impl(data, layoutGraph, "cc_fogColor", + Vec4(colorTempRGB.x, colorTempRGB.y, colorTempRGB.z, colorTempRGB.z)); + setVec4Impl(data, layoutGraph, "cc_fogBase", + Vec4(fog.getFogStart(), fog.getFogEnd(), fog.getFogDensity(), 0.0F)); + setVec4Impl(data, layoutGraph, "cc_fogAdd", + Vec4(fog.getFogTop(), fog.getFogRange(), fog.getFogAtten(), 0.0F)); + setVec4Impl(data, layoutGraph, "cc_nearFar", + Vec4(camera.getNearClip(), camera.getFarClip(), camera.getClipSpaceMinz(), 0.0F)); + setVec4Impl(data, layoutGraph, "cc_viewPort", + Vec4( + camera.getViewport().x, + camera.getViewport().y, + shadingScale * static_cast(camera.getWindow()->getWidth()) * camera.getViewport().z, + shadingScale * static_cast(camera.getWindow()->getHeight()) * camera.getViewport().w)); +} + +namespace { + +float getPCFRadius( + const scene::Shadows &shadowInfo, + const scene::DirectionalLight &mainLight) { + const auto &shadowMapSize = shadowInfo.getSize().x; + switch (mainLight.getShadowPcf()) { + case scene::PCFType::HARD: + return 0.0F; + case scene::PCFType::SOFT: + return 1.0F / (shadowMapSize * 0.5F); + case scene::PCFType::SOFT_2X: + return 2.0F / (shadowMapSize * 0.5F); + case scene::PCFType::SOFT_4X: + return 3.0F / (shadowMapSize * 0.5F); + default: + break; + } + return 0.0F; +} + +} // namespace + +void setShadowUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::DirectionalLight &mainLight, + RenderData &data) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &csmSupported = sceneData.getCSMSupported(); + const auto &packing = pipeline::supportsR32FloatTexture(&device) ? 0.0F : 1.0F; + Vec4 vec4ShadowInfo{}; + if (shadowInfo.isEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + if (mainLight.isShadowEnabled()) { + if (mainLight.isShadowFixedArea() || + mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1 || !csmSupported) { + // Shadow + const auto &matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + const auto &matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + const auto &matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + const auto &near = mainLight.getShadowNear(); + const auto &far = mainLight.getShadowFar(); + + setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); + setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15])); + + setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); + setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + { // CSM + const auto layerThreshold = getPCFRadius(shadowInfo, mainLight); + const auto numCascades = static_cast(mainLight.getCSMLevel()); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir0", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir1", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir2", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmAtlas", numCascades); + setMat4ArraySizeImpl(data, layoutGraph, "cc_matCSMViewProj", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjDepthInfo", numCascades); + setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjInfo", numCascades); + + Vec4 csmSplitsInfo{}; + for (uint32_t i = 0; i < numCascades; ++i) { + const auto &layer = *csmLayers.getLayers()[i]; + + const auto &matShadowView = layer.getMatShadowView(); + vec4ShadowInfo.set(matShadowView.m[0], matShadowView.m[4], matShadowView.m[8], layerThreshold); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir0", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[1], matShadowView.m[5], matShadowView.m[9], layer.getSplitCameraNear()); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir1", vec4ShadowInfo, i); + vec4ShadowInfo.set(matShadowView.m[2], matShadowView.m[6], matShadowView.m[10], layer.getSplitCameraFar()); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir2", vec4ShadowInfo, i); + + const auto &csmAtlas = layer.getCSMAtlas(); + setVec4ArrayElemImpl(data, layoutGraph, "cc_csmAtlas", csmAtlas, i); + + const auto &matShadowViewProj = layer.getMatShadowViewProj(); + setMat4ArrayElemImpl(data, layoutGraph, "cc_matCSMViewProj", matShadowViewProj, i); + + const auto &matShadowProj = layer.getMatShadowProj(); + setVec4ArrayElemImpl(data, layoutGraph, + "cc_csmProjDepthInfo", + Vec4(matShadowProj.m[10], matShadowProj.m[14], + matShadowProj.m[11], matShadowProj.m[15]), + i); + + setVec4ArrayElemImpl(data, layoutGraph, + "cc_csmProjInfo", + Vec4(matShadowProj.m[00], matShadowProj.m[05], + 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]), + i); + + (&csmSplitsInfo.x)[i] = layer.getSplitCameraFar() / mainLight.getShadowDistance(); + } + setVec4Impl(data, layoutGraph, "cc_csmSplitsInfo", csmSplitsInfo); + } + { // Shadow + vec4ShadowInfo.set(0, 0, 0, 1.0F - mainLight.getShadowSaturation()); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + static_cast(scene::LightType::DIRECTIONAL), + packing, + mainLight.getShadowNormalBias(), + static_cast(mainLight.getCSMLevel())); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + } + } + { // Shadow + vec4ShadowInfo.set( + shadowInfo.getSize().x, shadowInfo.getSize().y, + static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); + setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + } else { + Vec3 tempVec3 = shadowInfo.getNormal().getNormalized(); + setVec4Impl(data, layoutGraph, + "cc_planarNDInfo", + Vec4(tempVec3.x, tempVec3.y, tempVec3.z, -shadowInfo.getDistance())); + } + { + const auto &color = shadowInfo.getShadowColor4f(); + setColorImpl(data, layoutGraph, "cc_shadowColor", + gfx::Color{color[0], color[1], color[2], color[3]}); + } + } +} + +void setShadowUBOLightView( + gfx::Device *device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::Light &light, + uint32_t level, + RenderData &data) { + const auto &shadowInfo = *sceneData.getShadows(); + const auto &csmLayers = *sceneData.getCSMLayers(); + const auto &packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; + const auto &cap = device->getCapabilities(); + Vec4 vec4ShadowInfo{}; + + // ShadowMap + switch (light.getType()) { + case scene::LightType::DIRECTIONAL: { + const auto &mainLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && mainLight.isShadowEnabled()) { + if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { + float near = 0.1F; + float far = 0.0F; + Mat4 matShadowView; + Mat4 matShadowProj; + Mat4 matShadowViewProj; + scene::CSMLevel levelCount{}; + if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { + matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); + matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); + matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); + if (mainLight.isShadowFixedArea()) { + near = mainLight.getShadowNear(); + far = mainLight.getShadowFar(); + levelCount = static_cast(0); + } else { + near = 0.1F; + far = csmLayers.getSpecialLayer()->getShadowCameraFar(); + levelCount = scene::CSMLevel::LEVEL_1; + } + vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + } else { + const auto &layer = *csmLayers.getLayers()[level]; + matShadowView = layer.getMatShadowView(); + matShadowProj = layer.getMatShadowProj(); + matShadowViewProj = layer.getMatShadowViewProj(); + + near = layer.getSplitCameraNear(); + far = layer.getSplitCameraFar(); + levelCount = mainLight.getCSMLevel(); + } + setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); + setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", + Vec4( + matShadowProj.m[10], + matShadowProj.m[14], + matShadowProj.m[11], + matShadowProj.m[15])); + setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", + Vec4( + matShadowProj.m[00], + matShadowProj.m[05], + 1.0F / matShadowProj.m[00], + 1.0F / matShadowProj.m[05])); + setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); + vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + static_cast(scene::LightType::DIRECTIONAL), + packing, + mainLight.getShadowNormalBias(), + static_cast(levelCount)); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); + vec4ShadowInfo.set( + shadowInfo.getSize().x, + shadowInfo.getSize().y, + static_cast(mainLight.getShadowPcf()), + mainLight.getShadowBias()); + setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); + } + } + break; + } + case scene::LightType::SPOT: { + const auto &spotLight = dynamic_cast(light); + if (shadowInfo.isEnabled() && spotLight.isShadowEnabled()) { + const auto &matShadowCamera = spotLight.getNode()->getWorldMatrix(); + const auto matShadowView = matShadowCamera.getInversed(); + setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); + + Mat4 matShadowViewProj{}; + Mat4::createPerspective(spotLight.getAngle(), 1.0F, 0.001F, + spotLight.getRange(), true, + cap.clipSpaceMinZ, cap.clipSpaceSignY, 0, &matShadowViewProj); + matShadowViewProj.multiply(matShadowView); + setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); + + const Vec4 shadowNFLSInfos(0.01F, spotLight.getRange(), 0.0F, 0.0F); + setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", shadowNFLSInfos); + + const Vec4 shadowWHPBInfos( + shadowInfo.getSize().x, + shadowInfo.getSize().y, + spotLight.getShadowPcf(), + spotLight.getShadowBias()); + setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", shadowWHPBInfos); + + const Vec4 shadowLPNNInfos(static_cast(scene::LightType::SPOT), packing, spotLight.getShadowNormalBias(), 0.0F); + setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", shadowLPNNInfos); + } + break; + } + default: + break; + } + + const auto &color = shadowInfo.getShadowColor4f(); + setColorImpl(data, layoutGraph, "cc_shadowColor", gfx::Color{color[0], color[1], color[2], color[3]}); +} + +void setLegacyTextureUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + RenderData &data) { + const auto &skybox = *sceneData.getSkybox(); + if (skybox.getReflectionMap()) { + auto &texture = *skybox.getReflectionMap()->getGFXTexture(); + auto *sampler = device.getSampler(skybox.getReflectionMap()->getSamplerInfo()); + setTextureImpl(data, layoutGraph, "cc_environment", &texture); + setSamplerImpl(data, layoutGraph, "cc_environment", sampler); + } else { + const auto *envmap = + skybox.getEnvmap() + ? skybox.getEnvmap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (envmap) { + auto *texture = envmap->getGFXTexture(); + auto *sampler = device.getSampler(envmap->getSamplerInfo()); + setTextureImpl(data, layoutGraph, "cc_environment", texture); + setSamplerImpl(data, layoutGraph, "cc_environment", sampler); + } + } + const auto *diffuseMap = + skybox.getDiffuseMap() + ? skybox.getDiffuseMap() + : BuiltinResMgr::getInstance()->get("default-cube-texture"); + if (diffuseMap) { + auto *texture = diffuseMap->getGFXTexture(); + auto *sampler = device.getSampler(diffuseMap->getSamplerInfo()); + setTextureImpl(data, layoutGraph, "cc_diffuseMap", texture); + setSamplerImpl(data, layoutGraph, "cc_diffuseMap", sampler); + } + gfx::SamplerInfo samplerPointInfo{ + gfx::Filter::POINT, + gfx::Filter::POINT, + gfx::Filter::NONE, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + gfx::Address::CLAMP}; + auto *pointSampler = device.getSampler(samplerPointInfo); + setSamplerImpl(data, layoutGraph, "cc_shadowMap", pointSampler); + // setTextureImpl(data, layoutGraph, "cc_shadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); + setSamplerImpl(data, layoutGraph, "cc_spotShadowMap", pointSampler); + // setTextureImpl(data, layoutGraph, "cc_spotShadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.h b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.h new file mode 100644 index 00000000000..b123a5332ac --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeBuiltinUtils.h @@ -0,0 +1,86 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include +#include "cocos/renderer/pipeline/custom/LayoutGraphFwd.h" +#include "cocos/renderer/pipeline/custom/NativeFwd.h" +#include "cocos/renderer/pipeline/custom/RenderGraphFwd.h" + +namespace cc { + +namespace scene { +class Camera; +class DirectionalLight; +} // namespace scene + +namespace gfx { +class Device; +} // namespace gfx + +namespace pipeline { +class PipelineSceneData; +} // namespace pipeline + +namespace render { + +void setCameraUBOValues( + const scene::Camera &camera, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &cfg, + const scene::DirectionalLight *mainLight, + RenderData &data); + +void setLegacyTextureUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + RenderData &data); + +// For use shadow map +void setShadowUBOView( + gfx::Device &device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::DirectionalLight &mainLight, + RenderData &data); + +// For build shadow map +void setShadowUBOLightView( + gfx::Device *device, + const LayoutGraphData &layoutGraph, + const pipeline::PipelineSceneData &sceneData, + const scene::Light &light, + uint32_t level, + RenderData &data); + +// Render graph +void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter); + +// Geometry +void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]); + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeDefaultScene.cpp b/native/cocos/renderer/pipeline/custom/NativeDefaultScene.cpp deleted file mode 100644 index 219ef6690e4..00000000000 --- a/native/cocos/renderer/pipeline/custom/NativeDefaultScene.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/**************************************************************************** - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "NativePipelineTypes.h" - -namespace cc { - -namespace render { - -const pipeline::PipelineSceneData *DefaultSceneVisitor::getPipelineSceneData() const { - return nullptr; -} - -void DefaultSceneVisitor::setViewport(const gfx::Viewport &vp) {} -void DefaultSceneVisitor::setScissor(const gfx::Rect &rect) {} -void DefaultSceneVisitor::bindPipelineState(gfx::PipelineState *pso) {} -void DefaultSceneVisitor::bindDescriptorSet(uint32_t set, gfx::DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) {} -void DefaultSceneVisitor::bindInputAssembler(gfx::InputAssembler *ia) {} -void DefaultSceneVisitor::updateBuffer(gfx::Buffer *buff, const void *data, uint32_t size) {} -void DefaultSceneVisitor::draw(const gfx::DrawInfo &info) {} - -SceneTask *DefaultForwardLightingTransversal::transverse(SceneVisitor *visitor) const { - std::ignore = visitor; - return nullptr; -} - -} // namespace render - -} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index c044f4204a3..23fdda466bc 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -97,6 +97,7 @@ struct RenderGraphVisitorContext { void clear(gfx::RenderPassInfo& info) { info.colorAttachments.clear(); info.depthStencilAttachment = {}; + info.depthStencilResolveAttachment = {}; info.subpasses.clear(); info.dependencies.clear(); } @@ -177,25 +178,34 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( fbInfo.colorTextures.reserve(pass.rasterViews.size()); PmrFlatSet set(scratch); - auto fillFrameBufferInfo = [&](const auto& pass) { - auto numTotalAttachments = static_cast(pass.rasterViews.size()); - - PmrFlatMap viewIndex(scratch); - for (const auto& [name, view] : pass.rasterViews) { - if (set.emplace(name).second) { - viewIndex.emplace(view.slotID, name); - } - } + auto fillFrameBufferInfo = [&](const ccstd::vector& passViews, bool hasResolve) { + std::ignore = hasResolve; + const auto& uberPass = pass; + auto numTotalAttachments = static_cast(passViews.size()); // uint32_t dsvCount = 0; uint32_t index = 0; - for (const auto& [slotID, name] : viewIndex) { - const auto& view = pass.rasterViews.at(name); - const auto resID = vertex(name, ctx.resourceGraph); - const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); + for (const auto& nameIn : passViews) { + const char* name = nameIn.c_str(); + bool colorLikeView{true}; + bool dsResolveAttachment{false}; + auto clearColor = gfx::Color{}; + auto iter = pass.rasterViews.find(name); + if(iter != pass.rasterViews.end()) { + const auto& view = iter->second; + colorLikeView = view.attachmentType == AttachmentType::RENDER_TARGET || view.attachmentType == AttachmentType::SHADING_RATE; + clearColor = view.clearColor; + } else { + // resolves + const auto resID = vertex(name, ctx.resourceGraph); + const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); + CC_ASSERT(hasResolve && desc.sampleCount == gfx::SampleCount::X1); + colorLikeView = desc.format != gfx::Format::DEPTH_STENCIL && desc.format != gfx::Format::DEPTH; + dsResolveAttachment = !colorLikeView; + } - if (view.attachmentType == AttachmentType::RENDER_TARGET || view.attachmentType == AttachmentType::SHADING_RATE) { // RenderTarget - data.clearColors.emplace_back(view.clearColor); + if (colorLikeView) { // RenderTarget + data.clearColors.emplace_back(clearColor); auto resID = findVertex(name, resg); visitObject( @@ -239,22 +249,23 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( std::ignore = view; CC_EXPECTS(false); }); - } else if (view.attachmentType == AttachmentType::DEPTH_STENCIL) { // DepthStencil - data.clearDepth = view.clearColor.x; - data.clearStencil = static_cast(view.clearColor.y); + } else { // DepthStencil + if (!dsResolveAttachment) { + data.clearDepth = clearColor.x; + data.clearStencil = static_cast(clearColor.y); + } + + auto &dsAttachment = dsResolveAttachment ? fbInfo.depthStencilResolveTexture : fbInfo.depthStencilTexture; - if (!fbInfo.depthStencilTexture) { - auto resID = findVertex(name, resg); - visitObject( + auto resID = findVertex(name, resg); + visitObject( resID, resg, [&](const ManagedTexture& tex) { CC_EXPECTS(tex.texture); - CC_EXPECTS(!fbInfo.depthStencilTexture); - fbInfo.depthStencilTexture = tex.texture.get(); + dsAttachment = tex.texture.get(); }, [&](const IntrusivePtr& tex) { - CC_EXPECTS(!fbInfo.depthStencilTexture); - fbInfo.depthStencilTexture = tex.get(); + dsAttachment = tex.get(); }, [&](const FormatView& view) { std::ignore = view; @@ -267,7 +278,6 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( [](const auto& /*unused*/) { CC_EXPECTS(false); }); - } } ++index; } @@ -281,14 +291,14 @@ PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( // persistent cache data.clearColors.reserve(numColors); - rpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID).rpInfo; - fillFrameBufferInfo(pass); + const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); + rpInfo = fgdRpInfo.rpInfo; + fillFrameBufferInfo(fgdRpInfo.orderedViews, false); } else { - rpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID).rpInfo; - for (const auto& subpass : pass.subpassGraph.subpasses) { - fillFrameBufferInfo(subpass); - } + const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); + rpInfo = fgdRpInfo.rpInfo; + fillFrameBufferInfo(fgdRpInfo.orderedViews, fgdRpInfo.needResolve); } CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); CC_ENSURES(rpInfo.colorAttachments.size() == fbInfo.colorTextures.size()); @@ -923,6 +933,9 @@ getComputeViews(RenderGraph::vertex_descriptor passID, const RenderGraph& rg) { if (holds(passID, rg)) { return get(RasterPassTag{}, passID, rg).computeViews; } + if (holds(passID, rg)) { + return get(RasterSubpassTag{}, passID, rg).computeViews; + } CC_EXPECTS(holds(passID, rg)); return get(ComputeTag{}, passID, rg).computeViews; } @@ -1135,7 +1148,17 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { const auto& subpass = get(RasterSubpassTag{}, vertID, ctx.g); // render pass const auto& layoutName = get(RenderGraph::LayoutTag{}, ctx.g, vertID); - const auto& layoutID = locate(LayoutGraphData::null_vertex(), layoutName, ctx.lg); + + auto parentLayoutID = ctx.currentPassLayoutID; + auto layoutID = parentLayoutID; + if (!layoutName.empty()) { + auto parentID = parent(ctx.currentPassLayoutID, ctx.lg); + if (parentID != LayoutGraphData::null_vertex()) { + parentLayoutID = parentID; + } + layoutID = locate(parentLayoutID, layoutName, ctx.lg); + } + ctx.currentPassLayoutID = layoutID; // get layout auto& layout = get(LayoutGraphData::LayoutTag{}, ctx.lg, layoutID); @@ -1241,7 +1264,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } const auto& nodeID = iter->second; auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end() && iter2->second.subpassBarriers.empty()) { + if (iter2 != ctx.barrierMap.end()) { submitBarriers(iter2->second.blockBarrier.frontBarriers); } } @@ -1252,7 +1275,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } const auto& nodeID = iter->second; auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end() && iter2->second.subpassBarriers.empty()) { + if (iter2 != ctx.barrierMap.end()) { submitBarriers(iter2->second.blockBarrier.rearBarriers); } } @@ -1741,6 +1764,11 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { CC_EXPECTS(resID != ResourceGraph::null_vertex()); resg.mount(ctx.device, resID); } + for (const auto& resolve : pass.resolvePairs) { + auto resID = findVertex(resolve.target, resg); + CC_EXPECTS(resID != ResourceGraph::null_vertex()); + resg.mount(ctx.device, resID); + } } void mountResources(const RasterPass& pass) const { @@ -2212,7 +2240,12 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { scratch}; RenderGraphVisitor visitor{{}, ctx}; - boost::depth_first_search(fg, visitor, get(colors, rg)); + auto colors = rg.colors(scratch); + for (const auto vertID : ctx.g.sortedVertices) { + if (holds(vertID, ctx.g) || holds(vertID, ctx.g) || holds(vertID, ctx.g)) { + boost::depth_first_visit(fg, vertID, visitor, get(colors, ctx.g)); + } + } } // collect statistics diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index 2d736168d4b..ff89a8cd6dc 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -22,44 +22,18 @@ THE SOFTWARE. ****************************************************************************/ -#include -#include -#include "LayoutGraphFwd.h" -#include "LayoutGraphGraphs.h" -#include "LayoutGraphNames.h" -#include "LayoutGraphTypes.h" -#include "LayoutGraphUtils.h" -#include "NativePipelineFwd.h" -#include "NativePipelineTypes.h" -#include "NativeUtils.h" -#include "RenderCommonTypes.h" -#include "RenderGraphGraphs.h" -#include "RenderGraphTypes.h" -#include "RenderInterfaceFwd.h" -#include "RenderInterfaceTypes.h" -#include "RenderingModule.h" -#include "cocos/base/Macros.h" -#include "cocos/base/Ptr.h" -#include "cocos/base/StringUtil.h" -#include "cocos/base/std/container/string.h" -#include "cocos/math/Mat4.h" -#include "cocos/renderer/gfx-base/GFXBuffer.h" -#include "cocos/renderer/gfx-base/GFXDef-common.h" -#include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" -#include "cocos/renderer/gfx-base/GFXDevice.h" -#include "cocos/renderer/gfx-base/GFXInputAssembler.h" -#include "cocos/renderer/gfx-base/GFXSwapchain.h" -#include "cocos/renderer/gfx-base/states/GFXSampler.h" -#include "cocos/renderer/pipeline/Enum.h" -#include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" #include "cocos/renderer/pipeline/PipelineSceneData.h" #include "cocos/renderer/pipeline/PipelineStateManager.h" -#include "cocos/renderer/pipeline/RenderPipeline.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphUtils.h" +#include "cocos/renderer/pipeline/custom/NativeBuiltinUtils.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/RenderingModule.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/RenderWindow.h" -#include "details/DebugUtils.h" -#include "details/GslUtils.h" - #if CC_USE_DEBUG_RENDERER #include "profiler/DebugRenderer.h" #endif @@ -68,11 +42,6 @@ namespace cc { namespace render { -SceneTask *NativeSceneTransversal::transverse(SceneVisitor *visitor) const { - std::ignore = visitor; - return nullptr; -} - NativePipeline::NativePipeline(const allocator_type &alloc) noexcept : device(gfx::Device::getInstance()), globalDSManager(std::make_unique()), @@ -118,15 +87,17 @@ uint32_t NativePipeline::addRenderWindow(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED | + ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; CC_EXPECTS(renderWindow); if (!renderWindow->getSwapchain()) { CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().size() == 1); CC_ASSERT(renderWindow->getFramebuffer()->getColorTextures().at(0)); + desc.sampleCount = renderWindow->getFramebuffer()->getColorTextures().at(0)->getInfo().samples; return addVertex( FramebufferTag{}, std::forward_as_tuple(name.c_str()), @@ -163,9 +134,9 @@ uint32_t NativePipeline::addStorageBuffer(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::STORAGE; + desc.flags = ResourceFlags::STORAGE | ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; return addVertex( ManagedBufferTag{}, @@ -187,9 +158,10 @@ uint32_t NativePipeline::addRenderTarget(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED | + ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; return addVertex( ManagedTextureTag{}, @@ -211,9 +183,10 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::DEPTH_STENCIL_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::DEPTH_STENCIL_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT | ResourceFlags::SAMPLED | + ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; CC_EXPECTS(residency == ResourceResidency::MANAGED || residency == ResourceResidency::MEMORYLESS); @@ -232,6 +205,67 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format resourceGraph); } +uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimension dimension, + gfx::Format format, + uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, + gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) { + ResourceDesc desc{ + dimension, + 0, + width, + height, + static_cast(dimension == ResourceDimension::TEXTURE3D ? depth : arraySize), + static_cast(mipLevels), + format, + sampleCount, + residency == ResourceResidency::MEMORYLESS ? gfx::TextureFlagBit::LAZILY_ALLOCATED : gfx::TextureFlagBit::NONE, + flags, + }; + return addVertex( + ManagedTextureTag{}, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(ResourceTraits{residency}), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + resourceGraph); +} + +void NativePipeline::updateResource(const ccstd::string& name, gfx::Format format, + uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, // NOLINT(bugprone-easily-swappable-parameters) + gfx::SampleCount sampleCount) { + auto resID = findVertex(ccstd::pmr::string(name, get_allocator()), resourceGraph); + if (resID == ResourceGraph::null_vertex()) { + return; + } + auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + + // update format + if (format == gfx::Format::UNKNOWN) { + format = desc.format; + } + visitObject( + resID, resourceGraph, + [&](ManagedTexture &tex) { + uint32_t depthOrArraySize = static_cast( + desc.dimension == ResourceDimension::TEXTURE3D ? depth : arraySize); + bool invalidate = + std::forward_as_tuple(desc.width, desc.height, desc.depthOrArraySize, desc.mipLevels, desc.format, desc.sampleCount) != + std::forward_as_tuple(width, height, depthOrArraySize, mipLevels, format, sampleCount); + if (invalidate) { + desc.width = width; + desc.height = height; + desc.depthOrArraySize = depthOrArraySize; + desc.mipLevels = mipLevels; + desc.format = format; + desc.sampleCount = sampleCount; + resourceGraph.invalidatePersistentRenderPassAndFramebuffer(tex.texture.get()); + } + }, + [](const auto & /*res*/) {}); +} + // NOLINTNEXTLINE uint32_t NativePipeline::addStorageTexture(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) { ResourceDesc desc{}; @@ -241,9 +275,9 @@ uint32_t NativePipeline::addStorageTexture(const ccstd::string &name, gfx::Forma desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::STORAGE | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::STORAGE | ResourceFlags::SAMPLED | ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST;; CC_EXPECTS(residency == ResourceResidency::MANAGED || residency == ResourceResidency::MEMORYLESS); @@ -270,9 +304,9 @@ uint32_t NativePipeline::addShadingRateTexture(const ccstd::string &name, uint32 desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = gfx::Format::R8UI; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; - desc.flags = ResourceFlags::SHADING_RATE | ResourceFlags::STORAGE | ResourceFlags::SAMPLED; + desc.flags = ResourceFlags::SHADING_RATE | ResourceFlags::STORAGE | ResourceFlags::SAMPLED | ResourceFlags::TRANSFER_SRC | ResourceFlags::TRANSFER_DST; CC_EXPECTS(residency == ResourceResidency::MANAGED || residency == ResourceResidency::MEMORYLESS); @@ -306,7 +340,7 @@ uint32_t NativePipeline::addCustomBuffer( desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = gfx::Format::UNKNOWN; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = gfx::TextureFlagBit::NONE; desc.flags = ResourceFlags::NONE; @@ -338,7 +372,7 @@ uint32_t NativePipeline::addCustomTexture( desc.depthOrArraySize = info.layerCount; desc.mipLevels = info.levelCount; desc.format = info.format; - desc.sampleCount = gfx::SampleCount::ONE; + desc.sampleCount = gfx::SampleCount::X1; desc.textureFlags = info.flags; desc.flags = ResourceFlags::NONE; @@ -504,6 +538,7 @@ void NativePipeline::updateShadingRateTexture( } void NativePipeline::beginFrame() { + // noop } void NativePipeline::update(const scene::Camera *camera) { @@ -516,59 +551,52 @@ void NativePipeline::update(const scene::Camera *camera) { } void NativePipeline::endFrame() { + // noop } -namespace { - -RenderPassBuilder *addRenderPassImpl( - const PipelineRuntime *ppl, - RenderGraph &renderGraph, const NativeProgramLibrary &lib, - uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) - uint32_t count, uint32_t quality, // NOLINT(bugprone-easily-swappable-parameters) +RenderPassBuilder *NativePipeline::addRenderPass( + uint32_t width, uint32_t height, const ccstd::string &passName) { - RasterPass pass(renderGraph.get_allocator()); - pass.width = width; - pass.height = height; - pass.viewport.width = width; - pass.viewport.height = height; - pass.count = count; - pass.quality = quality; - - auto passID = addVertex( - RasterPassTag{}, - std::forward_as_tuple(passName), - std::forward_as_tuple(passName), - std::forward_as_tuple(), - std::forward_as_tuple(), - std::forward_as_tuple(std::move(pass)), - renderGraph); + const auto &layoutGraph = programLibrary->layoutGraph; - auto passLayoutID = locate(LayoutGraphData::null_vertex(), passName, lib.layoutGraph); - CC_EXPECTS(passLayoutID != LayoutGraphData::null_vertex()); + auto [passID, passLayoutID] = addRenderPassVertex( + renderGraph, layoutGraph, + width, height, 1, 0, passName); auto *builder = ccnew NativeRenderPassBuilder( - ppl, &renderGraph, passID, &lib.layoutGraph, passLayoutID); + this, &renderGraph, passID, &layoutGraph, passLayoutID); + updateRasterPassConstants(width, height, *builder); return builder; } -} // namespace - -RenderPassBuilder *NativePipeline::addRenderPass( - uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) - const ccstd::string &passName) { - return addRenderPassImpl( - this, renderGraph, *programLibrary, width, height, 1, 0, passName); -} - -BasicRenderPassBuilder *NativePipeline::addMultisampleRenderPass( - uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) +MultisampleRenderPassBuilder *NativePipeline::addMultisampleRenderPass( + uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) { CC_EXPECTS(count > 1); - return addRenderPassImpl( - this, renderGraph, *programLibrary, width, height, count, quality, passName); + const auto &layoutGraph = programLibrary->layoutGraph; + + auto [passID, passLayoutID] = addRenderPassVertex( + renderGraph, layoutGraph, + width, height, count, quality, passName); + + auto &pass = get(RasterPassTag{}, passID, renderGraph); + + auto [subpassID, subpassLayoutID] = addRenderSubpassVertex( + pass, renderGraph, passID, + layoutGraph, passLayoutID, + "", // subpassName is empty + count, quality); + + auto *builder = ccnew NativeMultisampleRenderPassBuilder( + this, &renderGraph, passID, &layoutGraph, passLayoutID, + subpassID, subpassLayoutID); + + updateRasterPassConstants(pass.width, pass.height, *builder); + + return builder; } void NativePipeline::addResolvePass(const ccstd::vector &resolvePairs) { @@ -578,7 +606,7 @@ void NativePipeline::addResolvePass(const ccstd::vector &resolvePai pass.resolvePairs.emplace_back(pair); } std::string_view name("Resolve"); - addVertex( + addVertex2( ResolveTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -590,7 +618,7 @@ void NativePipeline::addResolvePass(const ccstd::vector &resolvePai // NOLINTNEXTLINE ComputePassBuilder *NativePipeline::addComputePass(const ccstd::string &passName) { - auto passID = addVertex( + auto passID = addVertex2( ComputeTag{}, std::forward_as_tuple(passName), std::forward_as_tuple(passName), @@ -611,7 +639,7 @@ void NativePipeline::addMovePass(const ccstd::vector &movePairs) { pass.movePairs.emplace_back(pair); } std::string_view name("Move"); - addVertex( + addVertex2( MoveTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -621,6 +649,180 @@ void NativePipeline::addMovePass(const ccstd::vector &movePairs) { renderGraph); } +namespace { + +void setupGpuDrivenResources( + NativePipeline& ppl, uint32_t cullingID, ResourceGraph& resg, const std::string &hzbName) { + ccstd::pmr::string name(resg.get_allocator()); + { // init resource + name = "_GpuInit"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = addVertex( + PersistentBufferTag{}, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple(), + std::forward_as_tuple(ResourceTraits{ResourceResidency::EXTERNAL}), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(/*xxx*/), + resg); + } else { + CC_EXPECTS(holds(resID, resg)); + // get(PersistentBufferTag{}, resID, resg) = xxx; + } + } + { + name = "CCObjectBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCInstanceBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCDrawIndirectBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCDrawInstanceBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + { + name = "CCVisibilityBuffer"; + name.append(std::to_string(cullingID)); + auto resID = findVertex(name, resg); + if (resID == ResourceGraph::null_vertex()) { + resID = ppl.addStorageBuffer(std::string(name), gfx::Format::UNKNOWN, 0, ResourceResidency::MANAGED); + } else { + CC_EXPECTS(holds(resID, resg)); + ppl.updateStorageBuffer(std::string(name), 0, gfx::Format::UNKNOWN); + } + } + if (!hzbName.empty()) { + + } +} + +} // namespace + +void NativePipeline::addBuiltinGpuCullingPass( + const scene::Camera *camera, const std::string &hzbName, const scene::Light *light) { + std::ignore = camera; + const uint32_t cullingID = ++nativeContext.sceneCulling.gpuCullingPassID; + setupGpuDrivenResources(*this, cullingID, resourceGraph, hzbName); + + if (light) { + // build light culling pass + return; + } + + const std::string objectBuffer = "CCObjectBuffer" + std::to_string(cullingID); + const std::string instanceBuffer = "CCInstanceBuffer" + std::to_string(cullingID); + const std::string drawIndirectBuffer = "CCDrawIndirectBuffer" + std::to_string(cullingID); + const std::string drawInstanceBuffer = "CCDrawInstanceBuffer" + std::to_string(cullingID); + const std::string visibilityBuffer = "CCVisibilityBuffer" + std::to_string(cullingID); + + // init indirected buffers + { + CopyPass copyPass{renderGraph.get_allocator()}; + { + CopyPair copyPair{renderGraph.get_allocator()}; + copyPair.source = "xxx"; + copyPair.target = drawIndirectBuffer; + copyPair.mipLevels = 1; + copyPair.numSlices = 1; + copyPass.copyPairs.emplace_back(std::move(copyPair)); + } + + auto copyID = addVertex2(CopyTag{}, + std::forward_as_tuple("CopyInitialIndirectBuffer"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(copyPass)), + renderGraph); + CC_ENSURES(copyID != RenderGraph::null_vertex()); + } + // run compute cullling pass + { + ComputePass computePass{renderGraph.get_allocator()}; + { + auto res = computePass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawIndirectBuffer), + std::forward_as_tuple()); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawIndirectBuffer"; + view.accessType = AccessType::WRITE; + view.shaderStageFlags = gfx::ShaderStageFlagBit::COMPUTE; + } + { + auto res = computePass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawInstanceBuffer), + std::forward_as_tuple()); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawInstanceBuffer"; + view.accessType = AccessType::WRITE; + view.shaderStageFlags = gfx::ShaderStageFlagBit::COMPUTE; + } + { + auto res = computePass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(visibilityBuffer), + std::forward_as_tuple()); + auto& view = res.first->second.emplace_back(); + view.name = "CCVisibilityBuffer"; + view.accessType = AccessType::WRITE; + view.shaderStageFlags = gfx::ShaderStageFlagBit::COMPUTE; + } + + auto computePassID = addVertex2(ComputeTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(computePass)), + renderGraph); + CC_ENSURES(computePassID != RenderGraph::null_vertex()); + } +} + +void NativePipeline::addBuiltinHzbGenerationPass( + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) + const std::string &sourceDepthStencilName, const std::string &targetHzbName) { +} + void NativePipeline::addCopyPass(const ccstd::vector ©Pairs) { CopyPass pass(renderGraph.get_allocator()); pass.copyPairs.reserve(copyPairs.size()); @@ -628,7 +830,7 @@ void NativePipeline::addCopyPass(const ccstd::vector ©Pairs) { pass.copyPairs.emplace_back(pair); } std::string_view name("Copy"); - addVertex( + addVertex2( CopyTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -646,7 +848,7 @@ void NativePipeline::addUploadPass(ccstd::vector &uploadPairs) { } uploadPairs.clear(); std::string_view name("Upload"); - addVertex( + addVertex2( CopyTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h index 13635e3aff2..846d97ac32d 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h @@ -46,15 +46,13 @@ class NativeRenderSubpassBuilder; class NativeMultisampleRenderSubpassBuilder; class NativeComputeSubpassBuilder; class NativeRenderPassBuilder; +class NativeMultisampleRenderPassBuilder; class NativeComputeQueueBuilder; class NativeComputePassBuilder; -class NativeSceneTransversal; struct RenderInstancingQueue; struct DrawInstance; struct RenderDrawQueue; struct NativeRenderQueue; -class DefaultSceneVisitor; -class DefaultForwardLightingTransversal; struct ResourceGroup; struct BufferPool; struct DescriptorSetPool; diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp index cf5285f441e..d8de417ef46 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp @@ -80,12 +80,6 @@ NativeRenderQueue::NativeRenderQueue(NativeRenderQueue&& rhs, const allocator_ty sceneFlags(rhs.sceneFlags), subpassOrPassLayoutID(rhs.subpassOrPassLayoutID) {} -DefaultSceneVisitor::DefaultSceneVisitor(const allocator_type& alloc) noexcept -: name(alloc) {} - -DefaultForwardLightingTransversal::DefaultForwardLightingTransversal(const allocator_type& alloc) noexcept -: name(alloc) {} - ResourceGroup::ResourceGroup(const allocator_type& alloc) noexcept : instancingBuffers(alloc) {} @@ -186,7 +180,8 @@ SceneCulling::SceneCulling(SceneCulling&& rhs, const allocator_type& alloc) renderQueues(std::move(rhs.renderQueues), alloc), sceneQueryIndex(std::move(rhs.sceneQueryIndex), alloc), numCullingQueries(rhs.numCullingQueries), - numRenderQueues(rhs.numRenderQueues) {} + numRenderQueues(rhs.numRenderQueues), + gpuCullingPassID(rhs.gpuCullingPassID) {} NativeRenderContext::NativeRenderContext(std::unique_ptr defaultResourceIn, const allocator_type& alloc) noexcept : defaultResource(std::move(defaultResourceIn)), diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index 97ee431bc01..b21235bc46b 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -86,6 +86,10 @@ class NativeSetter : public NativeRenderNode { void setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) /*implements*/; void setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) /*implements*/; void setSampler(const ccstd::string &name, gfx::Sampler *sampler) /*implements*/; + void setBuiltinCameraConstants(const scene::Camera *camera) /*implements*/; + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) /*implements*/; + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) /*implements*/; + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) /*implements*/; void setVec4ArraySize(const ccstd::string& name, uint32_t sz); void setVec4ArrayElem(const ccstd::string& name, const cc::Vec4& vec, uint32_t id); @@ -165,8 +169,23 @@ class NativeRenderQueueBuilder final : public RenderQueueBuilder, public NativeS void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) override; + void addScene(const scene::Camera *camera, SceneFlags sceneFlags) override; + void addSceneCulledByDirectionalLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::DirectionalLight *light, uint32_t level) override; + void addSceneCulledBySpotLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::SpotLight *light) override; void addFullscreenQuad(Material *material, uint32_t passID, SceneFlags sceneFlags) override; void addCameraQuad(scene::Camera *camera, Material *material, uint32_t passID, SceneFlags sceneFlags) override; void clearRenderTarget(const ccstd::string &name, const gfx::Color &color) override; @@ -225,6 +244,18 @@ class NativeRenderSubpassBuilder final : public RenderSubpassBuilder, public Nat void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override { NativeRenderSubpassBuilderImpl::addRenderTarget(name, accessType, slotName, loadOp, storeOp, color); @@ -309,6 +340,18 @@ class NativeMultisampleRenderSubpassBuilder final : public MultisampleRenderSubp void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override { NativeRenderSubpassBuilderImpl::addRenderTarget(name, accessType, slotName, loadOp, storeOp, color); @@ -396,6 +439,18 @@ class NativeComputeSubpassBuilder final : public ComputeSubpassBuilder, public N void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, const ccstd::string &slotName) override; void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; @@ -456,6 +511,18 @@ class NativeRenderPassBuilder final : public RenderPassBuilder, public NativeSet void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override; void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; @@ -475,6 +542,91 @@ class NativeRenderPassBuilder final : public RenderPassBuilder, public NativeSet void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) override; }; +class NativeMultisampleRenderPassBuilder final : public MultisampleRenderPassBuilder, public NativeSetter { +public: + NativeMultisampleRenderPassBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t nodeIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn, uint32_t subpassIDIn, uint32_t subpassLayoutIDIn) noexcept // NOLINT + : NativeSetter(pipelineRuntimeIn, renderGraphIn, nodeIDIn, layoutGraphIn, layoutIDIn), + subpassID(subpassIDIn), + subpassLayoutID(subpassLayoutIDIn) {} + + ccstd::string getName() const override { + return NativeRenderNode::getName(); + } + void setName(const ccstd::string &name) override { + NativeRenderNode::setName(name); + } + void setCustomBehavior(const ccstd::string &name) override { + NativeRenderNode::setCustomBehavior(name); + } + + void setMat4(const ccstd::string &name, const Mat4 &mat) override { + NativeSetter::setMat4(name, mat); + } + void setQuaternion(const ccstd::string &name, const Quaternion &quat) override { + NativeSetter::setQuaternion(name, quat); + } + void setColor(const ccstd::string &name, const gfx::Color &color) override { + NativeSetter::setColor(name, color); + } + void setVec4(const ccstd::string &name, const Vec4 &vec) override { + NativeSetter::setVec4(name, vec); + } + void setVec2(const ccstd::string &name, const Vec2 &vec) override { + NativeSetter::setVec2(name, vec); + } + void setFloat(const ccstd::string &name, float v) override { + NativeSetter::setFloat(name, v); + } + void setArrayBuffer(const ccstd::string &name, const ArrayBuffer *arrayBuffer) override { + NativeSetter::setArrayBuffer(name, arrayBuffer); + } + void setBuffer(const ccstd::string &name, gfx::Buffer *buffer) override { + NativeSetter::setBuffer(name, buffer); + } + void setTexture(const ccstd::string &name, gfx::Texture *texture) override { + NativeSetter::setTexture(name, texture); + } + void setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) override { + NativeSetter::setReadWriteBuffer(name, buffer); + } + void setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) override { + NativeSetter::setReadWriteTexture(name, texture); + } + void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { + NativeSetter::setSampler(name, sampler); + } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } + + void addRenderTarget(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) override; + void addDepthStencil(const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) override; + void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; + RenderQueueBuilder *addQueue(QueueHint hint, const ccstd::string &phaseName) override; + void setViewport(const gfx::Viewport &viewport) override; + void setVersion(const ccstd::string &name, uint64_t version) override; + bool getShowStatistics() const override; + void setShowStatistics(bool enable) override; + + void resolveRenderTarget(const ccstd::string &source, const ccstd::string &target) override; + void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target, gfx::ResolveMode depthMode, gfx::ResolveMode stencilMode) override; + + void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; + void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; + + uint32_t subpassID{RenderGraph::null_vertex()}; + uint32_t subpassLayoutID{RenderGraph::null_vertex()}; +}; + class NativeComputeQueueBuilder final : public ComputeQueueBuilder, public NativeSetter { public: NativeComputeQueueBuilder(const PipelineRuntime* pipelineRuntimeIn, RenderGraph* renderGraphIn, uint32_t nodeIDIn, const LayoutGraphData* layoutGraphIn, uint32_t layoutIDIn) noexcept @@ -526,6 +678,18 @@ class NativeComputeQueueBuilder final : public ComputeQueueBuilder, public Nativ void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addDispatch(uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, Material *material, uint32_t passID) override; }; @@ -581,6 +745,18 @@ class NativeComputePassBuilder final : public ComputePassBuilder, public NativeS void setSampler(const ccstd::string &name, gfx::Sampler *sampler) override { NativeSetter::setSampler(name, sampler); } + void setBuiltinCameraConstants(const scene::Camera *camera) override { + NativeSetter::setBuiltinCameraConstants(camera); + } + void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { + NativeSetter::setBuiltinShadowMapConstants(light); + } + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { + NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); + } + void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) override { + NativeSetter::setBuiltinSpotLightViewConstants(light); + } void addTexture(const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) override; void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) override; @@ -590,19 +766,6 @@ class NativeComputePassBuilder final : public ComputePassBuilder, public NativeS void setCustomShaderStages(const ccstd::string &name, gfx::ShaderStageFlagBit stageFlags) override; }; -class NativeSceneTransversal final : public SceneTransversal { -public: - NativeSceneTransversal() = default; - NativeSceneTransversal(const scene::Camera* cameraIn, const scene::RenderScene* sceneIn) noexcept - : camera(cameraIn), - scene(sceneIn) {} - - SceneTask *transverse(SceneVisitor *visitor) const override; - - const scene::Camera* camera{nullptr}; - const scene::RenderScene* scene{nullptr}; -}; - struct RenderInstancingQueue { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -694,41 +857,6 @@ struct NativeRenderQueue { uint32_t subpassOrPassLayoutID{0xFFFFFFFF}; }; -class DefaultSceneVisitor final : public SceneVisitor { -public: - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {name.get_allocator().resource()}; - } - - DefaultSceneVisitor(const allocator_type& alloc) noexcept; // NOLINT - - const pipeline::PipelineSceneData *getPipelineSceneData() const override; - void setViewport(const gfx::Viewport &vp) override; - void setScissor(const gfx::Rect &rect) override; - void bindPipelineState(gfx::PipelineState *pso) override; - void bindDescriptorSet(uint32_t set, gfx::DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; - void bindInputAssembler(gfx::InputAssembler *ia) override; - void updateBuffer(gfx::Buffer *buff, const void *data, uint32_t size) override; - void draw(const gfx::DrawInfo &info) override; - - ccstd::pmr::string name; -}; - -class DefaultForwardLightingTransversal final : public SceneTransversal { -public: - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {name.get_allocator().resource()}; - } - - DefaultForwardLightingTransversal(const allocator_type& alloc) noexcept; // NOLINT - - SceneTask *transverse(SceneVisitor *visitor) const override; - - ccstd::pmr::string name; -}; - struct ResourceGroup { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -968,6 +1096,7 @@ struct SceneCulling { PmrFlatMap sceneQueryIndex; uint32_t numCullingQueries{0}; uint32_t numRenderQueues{0}; + uint32_t gpuCullingPassID{0xFFFFFFFF}; }; struct NativeRenderContext { @@ -1109,10 +1238,11 @@ class NativePipeline final : public Pipeline { uint32_t addDepthStencil(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; void updateRenderTarget(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; + uint32_t addResource(const ccstd::string &name, ResourceDimension dimension, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) override; + void updateResource(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) override; void beginFrame() override; void update(const scene::Camera *camera) override; void endFrame() override; - BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) override; void addResolvePass(const ccstd::vector &resolvePairs) override; void addCopyPass(const ccstd::vector ©Pairs) override; gfx::DescriptorSetLayout *getDescriptorSetLayout(const ccstd::string &shaderName, UpdateFrequency freq) override; @@ -1124,9 +1254,12 @@ class NativePipeline final : public Pipeline { void updateStorageTexture(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; void updateShadingRateTexture(const ccstd::string &name, uint32_t width, uint32_t height) override; RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &passName) override; + MultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) override; ComputePassBuilder *addComputePass(const ccstd::string &passName) override; void addUploadPass(ccstd::vector &uploadPairs) override; void addMovePass(const ccstd::vector &movePairs) override; + void addBuiltinGpuCullingPass(const scene::Camera *camera, const std::string &hzbName, const scene::Light *light) override; + void addBuiltinHzbGenerationPass(const std::string &sourceDepthStencilName, const std::string &targetHzbName) override; uint32_t addCustomBuffer(const ccstd::string &name, const gfx::BufferInfo &info, const std::string &type) override; uint32_t addCustomTexture(const ccstd::string &name, const gfx::TextureInfo &info, const std::string &type) override; diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index c5ddc488354..528c95d5ce7 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -22,31 +22,14 @@ THE SOFTWARE. ****************************************************************************/ -#include -#include -#include "LayoutGraphGraphs.h" -#include "NativePipelineGraphs.h" -#include "NativePipelineTypes.h" -#include "NativeUtils.h" -#include "RenderCommonNames.h" -#include "RenderCommonTypes.h" -#include "RenderGraphFwd.h" -#include "RenderGraphGraphs.h" -#include "RenderGraphTypes.h" -#include "RenderingModule.h" -#include "cocos/math/Utils.h" -#include "cocos/renderer/pipeline/Define.h" -#include "cocos/renderer/pipeline/PipelineUBO.h" +#include "cocos/renderer/pipeline/custom/NativeBuiltinUtils.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" #include "cocos/scene/DirectionalLight.h" -#include "cocos/scene/Fog.h" -#include "cocos/scene/Skybox.h" +#include "cocos/scene/RenderScene.h" #include "cocos/scene/SpotLight.h" -#include "details/DebugUtils.h" -#include "details/GraphView.h" -#include "details/GslUtils.h" -#include "gfx-base/GFXDef-common.h" -#include "gfx-base/GFXDevice.h" -#include "pipeline/PipelineSceneData.h" namespace cc { @@ -64,300 +47,17 @@ void NativeRenderNode::setCustomBehavior(const ccstd::string &name) { // NOLINT( get(RenderGraph::DataTag{}, *renderGraph, nodeID).custom = std::string_view{name}; } -void NativeSetter::setMat4(const ccstd::string &name, const Mat4 &mat) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setMat4Impl(data, *layoutGraph, name, mat); -} - -void NativeSetter::setQuaternion(const ccstd::string &name, const Quaternion &quat) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setQuaternionImpl(data, *layoutGraph, name, quat); -} - -void NativeSetter::setColor(const ccstd::string &name, const gfx::Color &color) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setColorImpl(data, *layoutGraph, name, color); -} - -void NativeSetter::setVec4(const ccstd::string &name, const Vec4 &vec) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec4Impl(data, *layoutGraph, name, vec); -} - -void NativeSetter::setVec2(const ccstd::string &name, const Vec2 &vec) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec2Impl(data, *layoutGraph, name, vec); -} - -void NativeSetter::setFloat(const ccstd::string &name, float v) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setFloatImpl(data, *layoutGraph, name, v); -} - -void NativeSetter::setArrayBuffer(const ccstd::string &name, const ArrayBuffer *buffer) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setArrayBufferImpl(data, *layoutGraph, name, *buffer); -} - -void NativeSetter::setBuffer(const ccstd::string &name, gfx::Buffer *buffer) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setBufferImpl(data, *layoutGraph, name, buffer); -} - -void NativeSetter::setTexture(const ccstd::string &name, gfx::Texture *texture) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setTextureImpl(data, *layoutGraph, name, texture); -} - -void NativeSetter::setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setReadWriteBufferImpl(data, *layoutGraph, name, buffer); -} - -void NativeSetter::setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setReadWriteTextureImpl(data, *layoutGraph, name, texture); -} - -void NativeSetter::setSampler(const ccstd::string &name, gfx::Sampler *sampler) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setSamplerImpl(data, *layoutGraph, name, sampler); -} - -void NativeSetter::setVec4ArraySize(const ccstd::string &name, uint32_t sz) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec4ArraySizeImpl(data, *layoutGraph, name, sz); -} - -void NativeSetter::setVec4ArrayElem(const ccstd::string &name, const cc::Vec4 &vec, uint32_t id) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setVec4ArrayElemImpl(data, *layoutGraph, name, vec, id); -} - -void NativeSetter::setMat4ArraySize(const ccstd::string &name, uint32_t sz) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setMat4ArraySizeImpl(data, *layoutGraph, name, sz); -} - -void NativeSetter::setMat4ArrayElem(const ccstd::string &name, const cc::Mat4 &mat, uint32_t id) { - auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - setMat4ArrayElemImpl(data, *layoutGraph, name, mat, id); -} - -namespace { - -uint8_t getCombineSignY(gfx::Device *device) { - // 0: vk, 1: metal, 2: none, 3: gl-like - static int8_t combineSignY{-1}; - if (combineSignY < 0) { - const float screenSpaceSignY = device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F; - const float clipSpaceSignY = device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; - combineSignY = static_cast(static_cast(screenSpaceSignY) << 1 | static_cast(clipSpaceSignY)); +RenderGraph::vertex_descriptor RenderGraph::getPassID(vertex_descriptor nodeID) const { + CC_EXPECTS(nodeID != null_vertex()); + for (auto parentID = nodeID; + parentID != RenderGraph::null_vertex(); + parentID = parent(nodeID, *this)) { + nodeID = parentID; } - return static_cast(combineSignY); -} - -void setCameraUBOValues( - const scene::Camera &camera, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &cfg, - const scene::DirectionalLight *mainLight, - RenderData &data) { - CC_EXPECTS(camera.getNode()); - CC_EXPECTS(cfg.getSkybox()); - const auto &skybox = *cfg.getSkybox(); - const auto &shadingScale = cfg.getShadingScale(); - // Camera - setMat4Impl(data, layoutGraph, "cc_matView", camera.getMatView()); - setMat4Impl(data, layoutGraph, "cc_matViewInv", camera.getNode()->getWorldMatrix()); - setMat4Impl(data, layoutGraph, "cc_matProj", camera.getMatProj()); - setMat4Impl(data, layoutGraph, "cc_matProjInv", camera.getMatProjInv()); - setMat4Impl(data, layoutGraph, "cc_matViewProj", camera.getMatViewProj()); - setMat4Impl(data, layoutGraph, "cc_matViewProjInv", camera.getMatViewProjInv()); - setVec4Impl(data, layoutGraph, "cc_cameraPos", - Vec4( - camera.getPosition().x, - camera.getPosition().y, - camera.getPosition().z, - getCombineSignY(cc::gfx::Device::getInstance()))); - setVec4Impl(data, layoutGraph, "cc_surfaceTransform", - Vec4( - static_cast(camera.getSurfaceTransform()), - static_cast(camera.getCameraUsage()), - cosf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))), - sinf(static_cast(mathutils::toRadian(skybox.getRotationAngle()))))); - setVec4Impl(data, layoutGraph, "cc_screenScale", - Vec4( - cfg.getShadingScale(), - cfg.getShadingScale(), - 1.0F / cfg.getShadingScale(), - 1.0F / cfg.getShadingScale())); - setVec4Impl(data, layoutGraph, "cc_exposure", - Vec4( - camera.getExposure(), - 1.0F / camera.getExposure(), - cfg.isHDR() ? 1.0F : 0.0F, - 1.0F / scene::Camera::getStandardExposureValue())); - - if (mainLight) { - const auto &shadowInfo = *cfg.getShadows(); - const bool shadowEnable = (mainLight->isShadowEnabled() && - shadowInfo.getType() == scene::ShadowType::SHADOW_MAP); - setVec4Impl(data, layoutGraph, "cc_mainLitDir", - Vec4( - mainLight->getDirection().x, - mainLight->getDirection().y, - mainLight->getDirection().z, - shadowEnable)); - auto r = mainLight->getColor().x; - auto g = mainLight->getColor().y; - auto b = mainLight->getColor().z; - if (mainLight->isUseColorTemperature()) { - r *= mainLight->getColorTemperatureRGB().x; - g *= mainLight->getColorTemperatureRGB().y; - b *= mainLight->getColorTemperatureRGB().z; - } - auto w = mainLight->getIlluminance(); - if (cfg.isHDR()) { - w *= camera.getExposure(); - } - setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(r, g, b, w)); - } else { - setVec4Impl(data, layoutGraph, "cc_mainLitDir", Vec4(0, 0, 1, 0)); - setVec4Impl(data, layoutGraph, "cc_mainLitColor", Vec4(0, 0, 0, 0)); - } - - CC_EXPECTS(cfg.getAmbient()); - auto &ambient = *cfg.getAmbient(); - auto &skyColor = ambient.getSkyColor(); - if (cfg.isHDR()) { - skyColor.w = ambient.getSkyIllum() * camera.getExposure(); - } else { - skyColor.w = ambient.getSkyIllum(); - } - setVec4Impl(data, layoutGraph, "cc_ambientSky", - Vec4(skyColor.x, skyColor.y, skyColor.z, skyColor.w)); - setVec4Impl(data, layoutGraph, "cc_ambientGround", - Vec4( - ambient.getGroundAlbedo().x, - ambient.getGroundAlbedo().y, - ambient.getGroundAlbedo().z, - skybox.getEnvmap() ? static_cast(skybox.getEnvmap()->mipmapLevel()) : 1.0F)); - - CC_EXPECTS(cfg.getFog()); - const auto &fog = *cfg.getFog(); - - const auto &colorTempRGB = fog.getColorArray(); - setVec4Impl(data, layoutGraph, "cc_fogColor", - Vec4(colorTempRGB.x, colorTempRGB.y, colorTempRGB.z, colorTempRGB.z)); - setVec4Impl(data, layoutGraph, "cc_fogBase", - Vec4(fog.getFogStart(), fog.getFogEnd(), fog.getFogDensity(), 0.0F)); - setVec4Impl(data, layoutGraph, "cc_fogAdd", - Vec4(fog.getFogTop(), fog.getFogRange(), fog.getFogAtten(), 0.0F)); - setVec4Impl(data, layoutGraph, "cc_nearFar", - Vec4(camera.getNearClip(), camera.getFarClip(), camera.getClipSpaceMinz(), 0.0F)); - setVec4Impl(data, layoutGraph, "cc_viewPort", - Vec4( - camera.getViewport().x, - camera.getViewport().y, - shadingScale * static_cast(camera.getWindow()->getWidth()) * camera.getViewport().z, - shadingScale * static_cast(camera.getWindow()->getHeight()) * camera.getViewport().w)); + CC_ENSURES(nodeID != null_vertex()); + return nodeID; } -} // namespace - -// void NativeSetter::setCameraConstants(const scene::Camera *camera) { -// auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); -// setCameraUBOValues( -// *camera, -// *layoutGraph, -// *pipelineRuntime->getPipelineSceneData(), -// camera->getScene()->getMainLight(), data); -// } - -// void NativeSetter::setDirectionalLightProjectionConstants( -// const scene::DirectionalLight* light, uint32_t level) { -// CC_EXPECTS(light); -// const auto *device = pipelineRuntime->getDevice(); -// const auto &mainLight = *light; -// const auto& pplScenData = *pipelineRuntime->getPipelineSceneData(); -// const auto &shadowInfo = *pplScenData.getShadows(); -// const auto &csmLayers = *pplScenData.getCSMLayers(); -// const auto packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; - -// auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - -// float near = 0.1; -// float far = 0; -// Mat4 matShadowView; -// Mat4 matShadowProj; -// Mat4 matShadowViewProj; -// Vec4 vec4ShadowInfo{}; - -// scene::CSMLevel levelCount{}; -// if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { -// matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); -// matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); -// matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); -// if (mainLight.isShadowFixedArea()) { -// near = mainLight.getShadowNear(); -// far = mainLight.getShadowFar(); -// levelCount = static_cast(0); -// } else { -// near = 0.1; -// far = csmLayers.getSpecialLayer()->getShadowCameraFar(); -// levelCount = scene::CSMLevel::LEVEL_1; -// } -// vec4ShadowInfo.set(0.0F, packing, mainLight.getShadowNormalBias(), 0); -// setVec4Impl(data, *layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); -// } else { -// const auto &layer = *csmLayers.getLayers()[level]; -// matShadowView = layer.getMatShadowView(); -// matShadowProj = layer.getMatShadowProj(); -// matShadowViewProj = layer.getMatShadowViewProj(); - -// near = layer.getSplitCameraNear(); -// far = layer.getSplitCameraFar(); -// levelCount = mainLight.getCSMLevel(); -// } -// setMat4Impl(data, *layoutGraph, "cc_matLightView", matShadowView); -// setVec4Impl(data, *layoutGraph, "cc_shadowProjDepthInfo", -// Vec4( -// matShadowProj.m[10], -// matShadowProj.m[14], -// matShadowProj.m[11], -// matShadowProj.m[15])); -// setVec4Impl(data, *layoutGraph, "cc_shadowProjInfo", -// Vec4( -// matShadowProj.m[00], -// matShadowProj.m[05], -// 1.0F / matShadowProj.m[00], -// 1.0F / matShadowProj.m[05])); -// setMat4Impl(data, *layoutGraph, "cc_matLightViewProj", matShadowViewProj); -// vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); -// setVec4Impl(data, *layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); -// vec4ShadowInfo.set( -// 0.0F, -// packing, -// mainLight.getShadowNormalBias(), -// static_cast(levelCount)); -// setVec4Impl(data, *layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); -// vec4ShadowInfo.set( -// shadowInfo.getSize().x, -// shadowInfo.getSize().y, -// static_cast(mainLight.getShadowPcf()), -// mainLight.getShadowBias()); -// setVec4Impl(data, *layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); -// } - -// void NativeSetter::setSpotLightProjectionConstants(const scene::SpotLight* light) { - -// } - -// void NativeSetter::setShadowMapConstants(const scene::Light* light, uint32_t numLevels) { - -// } - namespace { template @@ -466,105 +166,14 @@ void NativeRenderPassBuilder::addDepthStencil( stencil); } -namespace { - -void addComputeView(NativeRenderPassBuilder &builder, const ccstd::string &name, const ComputeView &view) { - CC_EXPECTS(!name.empty()); - CC_EXPECTS(!view.name.empty()); - auto &pass = get(RasterPassTag{}, builder.nodeID, *builder.renderGraph); - auto iter = pass.computeViews.find(name.c_str()); - if (iter == pass.computeViews.end()) { - bool added = false; - std::tie(iter, added) = pass.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); -} - -void addComputeView(NativeComputePassBuilder &builder, const ccstd::string &name, const ComputeView &view) { - CC_EXPECTS(!name.empty()); - CC_EXPECTS(!view.name.empty()); - auto &pass = get(ComputeTag{}, builder.nodeID, *builder.renderGraph); - auto iter = pass.computeViews.find(name.c_str()); - if (iter == pass.computeViews.end()) { - bool added = false; - std::tie(iter, added) = pass.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); -} - -template -void addComputeViewImpl( - const ccstd::string &name, const ComputeView &view, - RenderGraph::vertex_descriptor subpassID, - RenderGraph &renderGraph) { - CC_EXPECTS(!name.empty()); - CC_EXPECTS(!view.name.empty()); - auto &subpass = get(Tag{}, subpassID, renderGraph); - const auto passID = parent(subpassID, renderGraph); - CC_EXPECTS(passID != RenderGraph::null_vertex()); - CC_EXPECTS(holds(passID, renderGraph)); - auto &pass = get(RasterPassTag{}, passID, renderGraph); - CC_EXPECTS(subpass.subpassID < num_vertices(pass.subpassGraph)); - auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); - CC_EXPECTS(subpass.computeViews.size() == subpassData.computeViews.size()); - { - auto iter = subpassData.computeViews.find(name.c_str()); - if (iter == subpassData.computeViews.end()) { - bool added = false; - std::tie(iter, added) = subpassData.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); - } - { - auto iter = subpass.computeViews.find(name.c_str()); - if (iter == subpass.computeViews.end()) { - bool added = false; - std::tie(iter, added) = subpass.computeViews.emplace( - std::piecewise_construct, - std::forward_as_tuple(name.c_str()), - std::forward_as_tuple()); - CC_ENSURES(added); - } - iter->second.emplace_back(view); - } - CC_ENSURES(subpass.computeViews.size() == subpassData.computeViews.size()); - CC_ENSURES(subpass.computeViews.find(std::string_view{name}) != subpass.computeViews.end()); - CC_ENSURES(subpassData.computeViews.find(std::string_view{name}) != subpassData.computeViews.end()); - CC_ENSURES(subpass.computeViews.find(std::string_view{name})->second.size() == - subpassData.computeViews.find(std::string_view{name})->second.size()); -} - -void addComputeView( - NativeRenderSubpassBuilderImpl &builder, - const ccstd::string &name, const ComputeView &view) { - addComputeViewImpl(name, view, builder.nodeID, *builder.renderGraph); -} - -void addComputeView( - NativeComputeSubpassBuilder &builder, const ccstd::string &name, const ComputeView &view) { - addComputeViewImpl(name, view, builder.nodeID, *builder.renderGraph); -} - -} // namespace - // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) void NativeRenderPassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addPassComputeViewImpl( + RasterPassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -586,8 +195,10 @@ void NativeRenderPassBuilder::addTexture( void NativeRenderPassBuilder::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + RasterPassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -601,8 +212,10 @@ void NativeRenderPassBuilder::addStorageBuffer( void NativeRenderPassBuilder::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + RasterPassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -717,6 +330,8 @@ void addRasterViewImpl( gfx::ShaderStageFlagBit::NONE)); CC_ENSURES(res.second); res.first->second.slotID = slotID; + + pass.rasterViews.emplace(name, subpass.rasterViews.at(name.data())); } CC_ENSURES(subpass.rasterViews.size() == subpassData.rasterViews.size()); } @@ -768,8 +383,10 @@ void NativeRenderSubpassBuilderImpl::addDepthStencil( void NativeRenderSubpassBuilderImpl::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -791,8 +408,10 @@ void NativeRenderSubpassBuilderImpl::addTexture( void NativeRenderSubpassBuilderImpl::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -806,8 +425,10 @@ void NativeRenderSubpassBuilderImpl::addStorageBuffer( void NativeRenderSubpassBuilderImpl::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -887,7 +508,7 @@ RenderQueueBuilder *NativeRenderSubpassBuilderImpl::addQueue( const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -912,12 +533,19 @@ void NativeRenderSubpassBuilderImpl::setShowStatistics(bool enable) { void NativeMultisampleRenderSubpassBuilder::resolveRenderTarget( const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) auto &subpass = get(RasterSubpassTag{}, nodeID, *renderGraph); + + auto parentID = parent(nodeID, *renderGraph); + auto &pass = get(RasterPassTag{}, parentID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), ResolveFlags::COLOR, gfx::ResolveMode::AVERAGE, gfx::ResolveMode::NONE); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( @@ -931,12 +559,19 @@ void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( if (stencilMode != gfx::ResolveMode::NONE) { flags |= ResolveFlags::STENCIL; } + + auto parentID = parent(nodeID, *renderGraph); + auto &pass = get(RasterPassTag{}, parentID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), flags, depthMode, stencilMode); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } void NativeComputeSubpassBuilder::addRenderTarget(const ccstd::string &name, const ccstd::string &slotName) { @@ -958,8 +593,10 @@ void NativeComputeSubpassBuilder::addRenderTarget(const ccstd::string &name, con void NativeComputeSubpassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addSubpassComputeViewImpl( + ComputeSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -981,8 +618,10 @@ void NativeComputeSubpassBuilder::addTexture( void NativeComputeSubpassBuilder::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + ComputeSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -996,8 +635,10 @@ void NativeComputeSubpassBuilder::addStorageBuffer( void NativeComputeSubpassBuilder::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addSubpassComputeViewImpl( + ComputeSubpassTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1021,7 +662,7 @@ ComputeQueueBuilder *NativeComputeSubpassBuilder::addQueue(const ccstd::string & const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -1033,315 +674,11 @@ ComputeQueueBuilder *NativeComputeSubpassBuilder::addQueue(const ccstd::string & return new NativeComputeQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph, phaseLayoutID); } -namespace { - -void setShadowUBOLightView( - gfx::Device *device, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &sceneData, - const scene::Light &light, - uint32_t level, - RenderData &data) { - const auto &shadowInfo = *sceneData.getShadows(); - const auto &csmLayers = *sceneData.getCSMLayers(); - const auto &packing = pipeline::supportsR32FloatTexture(device) ? 0.0F : 1.0F; - const auto &cap = device->getCapabilities(); - Vec4 vec4ShadowInfo{}; - - // ShadowMap - switch (light.getType()) { - case scene::LightType::DIRECTIONAL: { - const auto &mainLight = dynamic_cast(light); - if (shadowInfo.isEnabled() && mainLight.isShadowEnabled()) { - if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { - float near = 0.1F; - float far = 0.0F; - Mat4 matShadowView; - Mat4 matShadowProj; - Mat4 matShadowViewProj; - scene::CSMLevel levelCount{}; - if (mainLight.isShadowFixedArea() || mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1) { - matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); - matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); - matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); - if (mainLight.isShadowFixedArea()) { - near = mainLight.getShadowNear(); - far = mainLight.getShadowFar(); - levelCount = static_cast(0); - } else { - near = 0.1F; - far = csmLayers.getSpecialLayer()->getShadowCameraFar(); - levelCount = scene::CSMLevel::LEVEL_1; - } - vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - } else { - const auto &layer = *csmLayers.getLayers()[level]; - matShadowView = layer.getMatShadowView(); - matShadowProj = layer.getMatShadowProj(); - matShadowViewProj = layer.getMatShadowViewProj(); - - near = layer.getSplitCameraNear(); - far = layer.getSplitCameraFar(); - levelCount = mainLight.getCSMLevel(); - } - setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); - setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", - Vec4( - matShadowProj.m[10], - matShadowProj.m[14], - matShadowProj.m[11], - matShadowProj.m[15])); - setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", - Vec4( - matShadowProj.m[00], - matShadowProj.m[05], - 1.0F / matShadowProj.m[00], - 1.0F / matShadowProj.m[05])); - setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); - vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); - vec4ShadowInfo.set( - static_cast(scene::LightType::DIRECTIONAL), - packing, - mainLight.getShadowNormalBias(), - static_cast(levelCount)); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - vec4ShadowInfo.set( - shadowInfo.getSize().x, - shadowInfo.getSize().y, - static_cast(mainLight.getShadowPcf()), - mainLight.getShadowBias()); - setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); - } - } - break; - } - case scene::LightType::SPOT: { - const auto &spotLight = dynamic_cast(light); - if (shadowInfo.isEnabled() && spotLight.isShadowEnabled()) { - const auto &matShadowCamera = spotLight.getNode()->getWorldMatrix(); - const auto matShadowView = matShadowCamera.getInversed(); - setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); - - Mat4 matShadowViewProj{}; - Mat4::createPerspective(spotLight.getAngle(), 1.0F, 0.001F, - spotLight.getRange(), true, - cap.clipSpaceMinZ, cap.clipSpaceSignY, 0, &matShadowViewProj); - matShadowViewProj.multiply(matShadowView); - setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); - - const Vec4 shadowNFLSInfos(0.01F, spotLight.getRange(), 0.0F, 0.0F); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", shadowNFLSInfos); - - const Vec4 shadowWHPBInfos( - shadowInfo.getSize().x, - shadowInfo.getSize().y, - spotLight.getShadowPcf(), - spotLight.getShadowBias()); - setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", shadowWHPBInfos); - - const Vec4 shadowLPNNInfos(static_cast(scene::LightType::SPOT), packing, spotLight.getShadowNormalBias(), 0.0F); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", shadowLPNNInfos); - } - break; - } - default: - break; - } - - const auto &color = shadowInfo.getShadowColor4f(); - setColorImpl(data, layoutGraph, "cc_shadowColor", gfx::Color{color[0], color[1], color[2], color[3]}); -} - -float getPCFRadius( - const scene::Shadows &shadowInfo, - const scene::DirectionalLight &mainLight) { - const auto &shadowMapSize = shadowInfo.getSize().x; - switch (mainLight.getShadowPcf()) { - case scene::PCFType::HARD: - return 0.0F; - case scene::PCFType::SOFT: - return 1.0F / (shadowMapSize * 0.5F); - case scene::PCFType::SOFT_2X: - return 2.0F / (shadowMapSize * 0.5F); - case scene::PCFType::SOFT_4X: - return 3.0F / (shadowMapSize * 0.5F); - default: - break; - } - return 0.0F; -} - -void setShadowUBOView( - gfx::Device &device, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &sceneData, - const scene::DirectionalLight &mainLight, - RenderData &data) { - const auto &shadowInfo = *sceneData.getShadows(); - const auto &csmLayers = *sceneData.getCSMLayers(); - const auto &csmSupported = sceneData.getCSMSupported(); - const auto &packing = pipeline::supportsR32FloatTexture(&device) ? 0.0F : 1.0F; - Vec4 vec4ShadowInfo{}; - if (shadowInfo.isEnabled()) { - if (shadowInfo.getType() == scene::ShadowType::SHADOW_MAP) { - if (mainLight.isShadowEnabled()) { - if (mainLight.isShadowFixedArea() || - mainLight.getCSMLevel() == scene::CSMLevel::LEVEL_1 || !csmSupported) { - // Shadow - const auto &matShadowView = csmLayers.getSpecialLayer()->getMatShadowView(); - const auto &matShadowProj = csmLayers.getSpecialLayer()->getMatShadowProj(); - const auto &matShadowViewProj = csmLayers.getSpecialLayer()->getMatShadowViewProj(); - const auto &near = mainLight.getShadowNear(); - const auto &far = mainLight.getShadowFar(); - - setMat4Impl(data, layoutGraph, "cc_matLightView", matShadowView); - setVec4Impl(data, layoutGraph, "cc_shadowProjDepthInfo", - Vec4(matShadowProj.m[10], matShadowProj.m[14], - matShadowProj.m[11], matShadowProj.m[15])); - - setVec4Impl(data, layoutGraph, "cc_shadowProjInfo", - Vec4(matShadowProj.m[00], matShadowProj.m[05], - 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05])); - setMat4Impl(data, layoutGraph, "cc_matLightViewProj", matShadowViewProj); - vec4ShadowInfo.set(near, far, 0, 1.0F - mainLight.getShadowSaturation()); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); - vec4ShadowInfo.set(static_cast(scene::LightType::DIRECTIONAL), packing, mainLight.getShadowNormalBias(), 0); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - } else { - { // CSM - const auto layerThreshold = getPCFRadius(shadowInfo, mainLight); - const auto numCascades = static_cast(mainLight.getCSMLevel()); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir0", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir1", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmViewDir2", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmAtlas", numCascades); - setMat4ArraySizeImpl(data, layoutGraph, "cc_matCSMViewProj", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjDepthInfo", numCascades); - setVec4ArraySizeImpl(data, layoutGraph, "cc_csmProjInfo", numCascades); - - Vec4 csmSplitsInfo{}; - for (uint32_t i = 0; i < numCascades; ++i) { - const auto &layer = *csmLayers.getLayers()[i]; - - const auto &matShadowView = layer.getMatShadowView(); - vec4ShadowInfo.set(matShadowView.m[0], matShadowView.m[4], matShadowView.m[8], layerThreshold); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir0", vec4ShadowInfo, i); - vec4ShadowInfo.set(matShadowView.m[1], matShadowView.m[5], matShadowView.m[9], layer.getSplitCameraNear()); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir1", vec4ShadowInfo, i); - vec4ShadowInfo.set(matShadowView.m[2], matShadowView.m[6], matShadowView.m[10], layer.getSplitCameraFar()); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmViewDir2", vec4ShadowInfo, i); - - const auto &csmAtlas = layer.getCSMAtlas(); - setVec4ArrayElemImpl(data, layoutGraph, "cc_csmAtlas", csmAtlas, i); - - const auto &matShadowViewProj = layer.getMatShadowViewProj(); - setMat4ArrayElemImpl(data, layoutGraph, "cc_matCSMViewProj", matShadowViewProj, i); - - const auto &matShadowProj = layer.getMatShadowProj(); - setVec4ArrayElemImpl(data, layoutGraph, - "cc_csmProjDepthInfo", - Vec4(matShadowProj.m[10], matShadowProj.m[14], - matShadowProj.m[11], matShadowProj.m[15]), - i); - - setVec4ArrayElemImpl(data, layoutGraph, - "cc_csmProjInfo", - Vec4(matShadowProj.m[00], matShadowProj.m[05], - 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]), - i); - - (&csmSplitsInfo.x)[i] = layer.getSplitCameraFar() / mainLight.getShadowDistance(); - } - setVec4Impl(data, layoutGraph, "cc_csmSplitsInfo", csmSplitsInfo); - } - { // Shadow - vec4ShadowInfo.set(0, 0, 0, 1.0F - mainLight.getShadowSaturation()); - setVec4Impl(data, layoutGraph, "cc_shadowNFLSInfo", vec4ShadowInfo); - vec4ShadowInfo.set( - static_cast(scene::LightType::DIRECTIONAL), - packing, - mainLight.getShadowNormalBias(), - static_cast(mainLight.getCSMLevel())); - setVec4Impl(data, layoutGraph, "cc_shadowLPNNInfo", vec4ShadowInfo); - } - } - { // Shadow - vec4ShadowInfo.set( - shadowInfo.getSize().x, shadowInfo.getSize().y, - static_cast(mainLight.getShadowPcf()), mainLight.getShadowBias()); - setVec4Impl(data, layoutGraph, "cc_shadowWHPBInfo", vec4ShadowInfo); - } - } - } else { - Vec3 tempVec3 = shadowInfo.getNormal().getNormalized(); - setVec4Impl(data, layoutGraph, - "cc_planarNDInfo", - Vec4(tempVec3.x, tempVec3.y, tempVec3.z, -shadowInfo.getDistance())); - } - { - const auto &color = shadowInfo.getShadowColor4f(); - setColorImpl(data, layoutGraph, "cc_shadowColor", - gfx::Color{color[0], color[1], color[2], color[3]}); - } - } -} - -void setTextureUBOView( - gfx::Device &device, - const LayoutGraphData &layoutGraph, - const pipeline::PipelineSceneData &sceneData, - RenderData &data) { - const auto &skybox = *sceneData.getSkybox(); - if (skybox.getReflectionMap()) { - auto &texture = *skybox.getReflectionMap()->getGFXTexture(); - auto *sampler = device.getSampler(skybox.getReflectionMap()->getSamplerInfo()); - setTextureImpl(data, layoutGraph, "cc_environment", &texture); - setSamplerImpl(data, layoutGraph, "cc_environment", sampler); - } else { - const auto *envmap = - skybox.getEnvmap() - ? skybox.getEnvmap() - : BuiltinResMgr::getInstance()->get("default-cube-texture"); - if (envmap) { - auto *texture = envmap->getGFXTexture(); - auto *sampler = device.getSampler(envmap->getSamplerInfo()); - setTextureImpl(data, layoutGraph, "cc_environment", texture); - setSamplerImpl(data, layoutGraph, "cc_environment", sampler); - } - } - const auto *diffuseMap = - skybox.getDiffuseMap() - ? skybox.getDiffuseMap() - : BuiltinResMgr::getInstance()->get("default-cube-texture"); - if (diffuseMap) { - auto *texture = diffuseMap->getGFXTexture(); - auto *sampler = device.getSampler(diffuseMap->getSamplerInfo()); - setTextureImpl(data, layoutGraph, "cc_diffuseMap", texture); - setSamplerImpl(data, layoutGraph, "cc_diffuseMap", sampler); - } - gfx::SamplerInfo samplerPointInfo{ - gfx::Filter::POINT, - gfx::Filter::POINT, - gfx::Filter::NONE, - gfx::Address::CLAMP, - gfx::Address::CLAMP, - gfx::Address::CLAMP}; - auto *pointSampler = device.getSampler(samplerPointInfo); - setSamplerImpl(data, layoutGraph, "cc_shadowMap", pointSampler); - // setTextureImpl(data, layoutGraph, "cc_shadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); - setSamplerImpl(data, layoutGraph, "cc_spotShadowMap", pointSampler); - // setTextureImpl(data, layoutGraph, "cc_spotShadowMap", BuiltinResMgr::getInstance()->get("default-texture")->getGFXTexture()); -} - -} // namespace - void NativeRenderQueueBuilder::addSceneOfCamera( scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) { const auto *pLight = light.light.get(); SceneData scene(camera->getScene(), camera, sceneFlags, light); - auto sceneID = addVertex( + auto sceneID = addVertex2( SceneTag{}, std::forward_as_tuple("Camera"), std::forward_as_tuple(), @@ -1376,67 +713,103 @@ void NativeRenderQueueBuilder::addSceneOfCamera( *pDirLight, data); } } - setTextureUBOView( + setLegacyTextureUBOView( *pipelineRuntime->getDevice(), *layoutGraph, *pipelineRuntime->getPipelineSceneData(), data); } -// void NativeRenderQueueBuilder::addScene(const scene::Camera *camera, SceneFlags sceneFlags) { -// SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{}); - -// auto sceneID = addVertex( -// SceneTag{}, -// std::forward_as_tuple("Scene"), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(std::move(data)), -// *renderGraph, nodeID); -// CC_ENSURES(sceneID != RenderGraph::null_vertex()); -// } - -// void NativeRenderQueueBuilder::addSceneCulledByDirectionalLight( -// const scene::Camera *camera, SceneFlags sceneFlags, -// scene::DirectionalLight *light, uint32_t level) { -// CC_EXPECTS(light); -// CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); -// SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, level}); - -// auto sceneID = addVertex( -// SceneTag{}, -// std::forward_as_tuple("Scene"), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(std::move(data)), -// *renderGraph, nodeID); -// CC_ENSURES(sceneID != RenderGraph::null_vertex()); -// } - -// void NativeRenderQueueBuilder::addSceneCulledBySpotLight( -// const scene::Camera *camera, SceneFlags sceneFlags, -// scene::SpotLight *light) { -// CC_EXPECTS(light); -// CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); -// SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, 0}); - -// auto sceneID = addVertex( -// SceneTag{}, -// std::forward_as_tuple("Scene"), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(), -// std::forward_as_tuple(std::move(data)), -// *renderGraph, nodeID); -// CC_ENSURES(sceneID != RenderGraph::null_vertex()); -// } +void NativeRenderQueueBuilder::addScene(const scene::Camera *camera, SceneFlags sceneFlags) { + SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{}); + + auto sceneID = addVertex2( + SceneTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(data)), + *renderGraph, nodeID); + CC_ENSURES(sceneID != RenderGraph::null_vertex()); + + if (any(sceneFlags & SceneFlags::GPU_DRIVEN)) { + const auto passID = renderGraph->getPassID(nodeID); + const auto cullingID = dynamic_cast(pipelineRuntime)->nativeContext.sceneCulling.gpuCullingPassID; + CC_EXPECTS(cullingID != 0xFFFFFFFF); + if (holds(passID, *renderGraph)) { + ccstd::pmr::string drawIndirectBuffer("CCDrawIndirectBuffer"); + drawIndirectBuffer.append(std::to_string(cullingID)); + ccstd::pmr::string drawInstanceBuffer("CCDrawInstanceBuffer"); + drawInstanceBuffer.append(std::to_string(cullingID)); + + auto& rasterPass = get(RasterPassTag{}, passID, *renderGraph); + if (rasterPass.computeViews.find(drawIndirectBuffer) != rasterPass.computeViews.end()) { + auto res = rasterPass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawIndirectBuffer), + std::forward_as_tuple()); + CC_ENSURES(res.second); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawIndirectBuffer"; + view.accessType = AccessType::READ; + view.shaderStageFlags = gfx::ShaderStageFlagBit::VERTEX | gfx::ShaderStageFlagBit::FRAGMENT; + } + if (rasterPass.computeViews.find(drawInstanceBuffer) != rasterPass.computeViews.end()) { + auto res = rasterPass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(drawInstanceBuffer), + std::forward_as_tuple()); + CC_ENSURES(res.second); + auto& view = res.first->second.emplace_back(); + view.name = "CCDrawInstanceBuffer"; + view.accessType = AccessType::READ; + view.shaderStageFlags = gfx::ShaderStageFlagBit::VERTEX | gfx::ShaderStageFlagBit::FRAGMENT; + } + } + } +} + +void NativeRenderQueueBuilder::addSceneCulledByDirectionalLight( + const scene::Camera *camera, SceneFlags sceneFlags, + scene::DirectionalLight *light, uint32_t level) { + CC_EXPECTS(light); + CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); + SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, level}); + + auto sceneID = addVertex2( + SceneTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(data)), + *renderGraph, nodeID); + CC_ENSURES(sceneID != RenderGraph::null_vertex()); +} + +void NativeRenderQueueBuilder::addSceneCulledBySpotLight( + const scene::Camera *camera, SceneFlags sceneFlags, + scene::SpotLight *light) { + CC_EXPECTS(light); + CC_EXPECTS(light->getType() != scene::LightType::UNKNOWN); + SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{light, 0}); + + auto sceneID = addVertex2( + SceneTag{}, + std::forward_as_tuple("Scene"), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(data)), + *renderGraph, nodeID); + CC_ENSURES(sceneID != RenderGraph::null_vertex()); +} void NativeRenderQueueBuilder::addFullscreenQuad( Material *material, uint32_t passID, SceneFlags sceneFlags) { std::string_view name = "FullscreenQuad"; - auto drawID = addVertex( + auto drawID = addVertex2( BlitTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1451,7 +824,7 @@ void NativeRenderQueueBuilder::addCameraQuad( scene::Camera *camera, cc::Material *material, uint32_t passID, SceneFlags sceneFlags) { std::string_view name = "CameraQuad"; - auto drawID = addVertex( + auto drawID = addVertex2( BlitTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1479,7 +852,7 @@ void NativeRenderQueueBuilder::addCameraQuad( *pDirLight, data); } } - setTextureUBOView( + setLegacyTextureUBOView( *pipelineRuntime->getDevice(), *layoutGraph, *pipelineRuntime->getPipelineSceneData(), @@ -1490,7 +863,7 @@ void NativeRenderQueueBuilder::clearRenderTarget(const ccstd::string &name, cons ccstd::pmr::vector clears(renderGraph->get_allocator()); clears.emplace_back(name.c_str(), gfx::ClearFlagBit::COLOR, color); - auto clearID = addVertex( + auto clearID = addVertex2( ClearTag{}, std::forward_as_tuple("ClearRenderTarget"), std::forward_as_tuple(), @@ -1508,7 +881,7 @@ void NativeRenderQueueBuilder::setViewport(const gfx::Viewport &viewport) { void NativeRenderQueueBuilder::addCustomCommand(std::string_view customBehavior) { std::string_view name = "FullscreenQuad"; - auto drawID = addVertex( + auto drawID = addVertex2( BlitTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1533,7 +906,7 @@ RenderQueueBuilder *NativeRenderPassBuilder::addQueue( const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -1554,40 +927,10 @@ SubpassBuilder *addRenderSubpassImpl( const LayoutGraphData &layoutGraph, LayoutGraphData::vertex_descriptor passLayoutID, const ccstd::string &subpassName, uint32_t count, uint32_t quality) { // NOLINT(bugprone-easily-swappable-parameters) - CC_EXPECTS(!subpassName.empty()); auto &pass = get(RasterPassTag{}, passID, renderGraph); - auto &subpassGraph = pass.subpassGraph; - const auto subpassIndex = num_vertices(pass.subpassGraph); - { - auto id = addVertex( - std::piecewise_construct, - std::forward_as_tuple(subpassName), - std::forward_as_tuple(), - subpassGraph); - CC_ENSURES(id == subpassIndex); - } - RasterSubpass subpass(subpassIndex, count, quality, renderGraph.get_allocator()); - subpass.viewport.width = pass.width; - subpass.viewport.height = pass.height; - - auto subpassID = addVertex( - RasterSubpassTag{}, - std::forward_as_tuple(subpassName), - std::forward_as_tuple(subpassName), - std::forward_as_tuple(), - std::forward_as_tuple(), - std::forward_as_tuple(std::move(subpass)), - renderGraph, passID); - - auto subpassLayoutID = LayoutGraphData::null_vertex(); - if constexpr (ENABLE_SUBPASS) { - subpassLayoutID = locate(passLayoutID, subpassName, layoutGraph); - } else { - subpassLayoutID = locate(LayoutGraphData::null_vertex(), subpassName, layoutGraph); - } - - CC_EXPECTS(subpassLayoutID != LayoutGraphData::null_vertex()); + auto [subpassID, subpassLayoutID] = addRenderSubpassVertex( + pass, renderGraph, passID, layoutGraph, passLayoutID, subpassName, count, quality); auto *builder = ccnew SubpassBuilder( pipelineRuntime, &renderGraph, subpassID, &layoutGraph, subpassLayoutID); @@ -1625,7 +968,7 @@ ComputeSubpassBuilder *NativeRenderPassBuilder::addComputeSubpass(const ccstd::s ComputeSubpass subpass(subpassIndex, renderGraph->get_allocator()); - auto subpassID = addVertex( + auto subpassID = addVertex2( ComputeSubpassTag{}, std::forward_as_tuple(subpassName), std::forward_as_tuple(subpassName), @@ -1658,12 +1001,187 @@ void NativeRenderPassBuilder::setVersion(const ccstd::string &name, uint64_t ver // noop } +void NativeMultisampleRenderPassBuilder::addRenderTarget( + const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, const gfx::Color &color) { + addRasterViewImpl( + name, + "", + "", + AccessType::WRITE, + AttachmentType::RENDER_TARGET, + loadOp, + storeOp, + gfx::ClearFlagBit::COLOR, + color, + subpassID, + *renderGraph); +} + +void NativeMultisampleRenderPassBuilder::addDepthStencil( + const ccstd::string &name, gfx::LoadOp loadOp, gfx::StoreOp storeOp, + float depth, uint8_t stencil, gfx::ClearFlagBit clearFlags) { // NOLINT(bugprone-easily-swappable-parameters) + addRasterViewImpl( + name, + "", + "", + AccessType::WRITE, + AttachmentType::DEPTH_STENCIL, + loadOp, + storeOp, + clearFlags, + gfx::Color{depth, static_cast(stencil)}, + subpassID, + *renderGraph); +} + +void NativeMultisampleRenderPassBuilder::addTexture( + const ccstd::string &name, const ccstd::string &slotName, // NOLINT(bugprone-easily-swappable-parameters) + gfx::Sampler *sampler, uint32_t plane) { + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + subpassID, + name, + ComputeView{ + ccstd::pmr::string(slotName, renderGraph->get_allocator()), + AccessType::READ, + plane, + gfx::ClearFlagBit::NONE, + ClearValueType::NONE, + ClearValue{}, + gfx::ShaderStageFlagBit::NONE, + renderGraph->get_allocator()}); + if (sampler) { + auto iter = layoutGraph->attributeIndex.find(std::string_view{slotName}); + if (iter != layoutGraph->attributeIndex.end()) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, subpassID); + data.samplers[iter->second.value] = sampler; + } + } +} + +void NativeMultisampleRenderPassBuilder::addStorageBuffer( + const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + subpassID, + name, + ComputeView{ + ccstd::pmr::string(slotName, renderGraph->get_allocator()), + accessType, + gfx::ClearFlagBit::NONE, + ClearValueType::NONE, + ClearValue{}, + gfx::ShaderStageFlagBit::NONE, + renderGraph->get_allocator()}); +} + +void NativeMultisampleRenderPassBuilder::addStorageImage( + const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { + addSubpassComputeViewImpl( + RasterSubpassTag{}, + *renderGraph, + subpassID, + name, + ComputeView{ + ccstd::pmr::string(slotName, renderGraph->get_allocator()), + accessType, + gfx::ClearFlagBit::NONE, + ClearValueType::NONE, + ClearValue{}, + gfx::ShaderStageFlagBit::NONE, + renderGraph->get_allocator()}); +} + +RenderQueueBuilder *NativeMultisampleRenderPassBuilder::addQueue( + QueueHint hint, const ccstd::string &phaseName) { + CC_EXPECTS(!phaseName.empty()); + CC_EXPECTS(subpassLayoutID == layoutID); + CC_EXPECTS(subpassLayoutID != LayoutGraphData::null_vertex()); + + const auto phaseLayoutID = locate(subpassLayoutID, phaseName, *layoutGraph); + CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); + + auto queueID = addVertex2( + QueueTag{}, + std::forward_as_tuple(phaseName), + std::forward_as_tuple(phaseName), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(hint, phaseLayoutID), + *renderGraph, subpassID); + + return new NativeRenderQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph, phaseLayoutID); +} + +void NativeMultisampleRenderPassBuilder::setViewport(const gfx::Viewport &viewport) { + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + subpass.viewport = viewport; +} + +void NativeMultisampleRenderPassBuilder::setVersion(const ccstd::string &name, uint64_t version) { + // noop +} + +bool NativeMultisampleRenderPassBuilder::getShowStatistics() const { + const auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + return subpass.showStatistics; +} + +void NativeMultisampleRenderPassBuilder::setShowStatistics(bool enable) { + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + subpass.showStatistics = enable; +} + +void NativeMultisampleRenderPassBuilder::resolveRenderTarget( + const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + + subpass.resolvePairs.emplace_back( + ccstd::pmr::string(source.data(), renderGraph->get_allocator()), + ccstd::pmr::string(target.data(), renderGraph->get_allocator()), + ResolveFlags::COLOR, + gfx::ResolveMode::AVERAGE, + gfx::ResolveMode::NONE); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); +} + +void NativeMultisampleRenderPassBuilder::resolveDepthStencil( + const ccstd::string &source, const ccstd::string &target, // NOLINT(bugprone-easily-swappable-parameters) + gfx::ResolveMode depthMode, gfx::ResolveMode stencilMode) { // NOLINT(bugprone-easily-swappable-parameters) + auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); + ResolveFlags flags = ResolveFlags::NONE; + if (depthMode != gfx::ResolveMode::NONE) { + flags |= ResolveFlags::DEPTH; + } + if (stencilMode != gfx::ResolveMode::NONE) { + flags |= ResolveFlags::STENCIL; + } + + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + + subpass.resolvePairs.emplace_back( + ccstd::pmr::string(source.data(), renderGraph->get_allocator()), + ccstd::pmr::string(target.data(), renderGraph->get_allocator()), + flags, + depthMode, + stencilMode); + + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); +} + // NativeComputeQueue void NativeComputeQueueBuilder::addDispatch( uint32_t threadGroupCountX, uint32_t threadGroupCountY, uint32_t threadGroupCountZ, Material *material, uint32_t passID) { std::string_view name("Dispatch"); - addVertex( + addVertex2( DispatchTag{}, std::forward_as_tuple(name), std::forward_as_tuple(), @@ -1682,8 +1200,10 @@ void NativeComputeQueueBuilder::addDispatch( void NativeComputePassBuilder::addTexture( const ccstd::string &name, const ccstd::string &slotName, gfx::Sampler *sampler, uint32_t plane) { - addComputeView( - *this, + addPassComputeViewImpl( + ComputeTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1705,8 +1225,10 @@ void NativeComputePassBuilder::addTexture( void NativeComputePassBuilder::addStorageBuffer( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + ComputeTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1720,8 +1242,10 @@ void NativeComputePassBuilder::addStorageBuffer( void NativeComputePassBuilder::addStorageImage( const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) { - addComputeView( - *this, + addPassComputeViewImpl( + ComputeTag{}, + *renderGraph, + nodeID, name, ComputeView{ ccstd::pmr::string(slotName, renderGraph->get_allocator()), @@ -1759,7 +1283,7 @@ ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &pha const auto phaseLayoutID = locate(layoutID, phaseName, *layoutGraph); CC_ENSURES(phaseLayoutID != LayoutGraphData::null_vertex()); - auto queueID = addVertex( + auto queueID = addVertex2( QueueTag{}, std::forward_as_tuple(phaseName), std::forward_as_tuple(phaseName), @@ -1771,318 +1295,6 @@ ComputeQueueBuilder *NativeComputePassBuilder::addQueue(const ccstd::string &pha return new NativeComputeQueueBuilder(pipelineRuntime, renderGraph, queueID, layoutGraph, phaseLayoutID); } -namespace { - -const char *getName(const gfx::LoadOp &op) { - switch (op) { - case gfx::LoadOp::LOAD: - return "LOAD"; - case gfx::LoadOp::CLEAR: - return "CLEAR"; - case gfx::LoadOp::DISCARD: - return "DISCARD"; - default: - return "UNKNOWN"; - } - return "UNKNOWN"; -} - -const char *getName(const gfx::StoreOp &op) { - switch (op) { - case gfx::StoreOp::STORE: - return "STORE"; - case gfx::StoreOp::DISCARD: - return "DISCARD"; - default: - return "UNKNOWN"; - } - return "UNKNOWN"; -} - -std::string getName(const gfx::ClearFlagBit &flags) { - std::ostringstream oss; - int count = 0; - if (hasAnyFlags(flags, gfx::ClearFlagBit::COLOR)) { - if (count++) { - oss << "|"; - } - oss << "COLOR"; - } - if (hasAnyFlags(flags, gfx::ClearFlagBit::DEPTH)) { - if (count++) { - oss << "|"; - } - oss << "DEPTH"; - } - if (hasAnyFlags(flags, gfx::ClearFlagBit::STENCIL)) { - if (count++) { - oss << "|"; - } - oss << "STENCIL"; - } - if (flags == gfx::ClearFlagBit::NONE) { - oss << "NONE"; - } - return oss.str(); -} - -struct RenderGraphPrintVisitor : boost::dfs_visitor<> { - void discover_vertex( - RenderGraph::vertex_descriptor vertID, - const AddressableView &gv) const { - const auto &g = gv.mGraph; - const auto &name = get(RenderGraph::NameTag{}, g, vertID); - visitObject( - vertID, gv.mGraph, - [&](const RasterPass &pass) { - OSS << "RasterPass \"" << name << "\" {\n"; - indent(space); - for (const auto &[name, rasterView] : pass.rasterViews) { - OSS << "RasterView \"" << name << "\" {\n"; - { - INDENT(); - OSS << "slotName: \"" << rasterView.slotName << "\";\n"; - OSS << "accessType: " << getName(rasterView.accessType) << ";\n"; - OSS << "attachmentType: " << getName(rasterView.attachmentType) << ";\n"; - OSS << "loadOp: " << getName(rasterView.loadOp) << ";\n"; - OSS << "storeOp: " << getName(rasterView.storeOp) << ";\n"; - OSS << "clearFlags: " << getName(rasterView.clearFlags) << ";\n"; - const auto &c = rasterView.clearColor; - if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - for (const auto &[name, computeViews] : pass.computeViews) { - OSS << "ComputeViews \"" << name << "\" {\n"; - { - INDENT(); - for (const auto &computeView : computeViews) { - OSS << "ComputeView \"" << computeView.name << "\" {\n"; - { - INDENT(); - OSS << "accessType: " << getName(computeView.accessType) << ";\n"; - OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; - const auto &c = computeView.clearValue; - if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - } - OSS << "}\n"; - } - }, - [&](const RasterSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputeSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputePass &pass) { - OSS << "ComputePass \"" << name << "\" {\n"; - indent(space); - for (const auto &[name, computeViews] : pass.computeViews) { - OSS << "ComputeViews \"" << name << "\" {\n"; - { - INDENT(); - for (const auto &computeView : computeViews) { - OSS << "ComputeView \"" << computeView.name << "\" {\n"; - { - INDENT(); - OSS << "accessType: " << getName(computeView.accessType) << ";\n"; - OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; - const auto &c = computeView.clearValue; - if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - } - OSS << "}\n"; - } - }, - [&](const ResolvePass &pass) { - OSS << "ResolvePass \"" << name << "\" {\n"; - for (const auto &pair : pass.resolvePairs) { - INDENT(); - OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; - } - indent(space); - }, - [&](const CopyPass &pass) { - OSS << "CopyPass \"" << name << "\" {\n"; - for (const auto &pair : pass.copyPairs) { - INDENT(); - OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; - } - indent(space); - }, - [&](const MovePass &pass) { - OSS << "MovePass \"" << name << "\" {\n"; - for (const auto &pair : pass.movePairs) { - INDENT(); - OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; - } - indent(space); - }, - [&](const RaytracePass &pass) { - std::ignore = pass; - OSS << "RaytracePass \"" << name << "\" {\n"; - indent(space); - }, - [&](const RenderQueue &queue) { - OSS << "Queue \"" << name << "\" {\n"; - { - INDENT(); - OSS << "hint: " << getName(queue.hint) << ";\n"; - } - indent(space); - }, - [&](const SceneData &scene) { - std::ignore = scene; - OSS << "Scene \"" << name << "\" {\n"; - indent(space); - }, - [&](const Blit &blit) { - std::ignore = blit; - OSS << "Blit \"" << name << "\";\n"; - }, - [&](const Dispatch &dispatch) { - OSS << "Dispatch \"" << name << "\", [" - << dispatch.threadGroupCountX << ", " - << dispatch.threadGroupCountY << ", " - << dispatch.threadGroupCountZ << "];\n"; - }, - [&](const ccstd::pmr::vector &clearViews) { - OSS << "Clear \"" << name << "\" {\n"; - indent(space); - for (const auto &view : clearViews) { - INDENT(); - OSS << "\"" << view.slotName << "\" {\n"; - { - INDENT(); - OSS << "clearFlags: " << getName(view.clearFlags) << ";\n"; - const auto &c = view.clearColor; - if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::COLOR)) { - OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; - } else if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { - OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; - } - } - OSS << "}\n"; - } - }, - [&](const gfx::Viewport &vp) { - OSS << "Viewport \"" << name << "\" [" - << "left: " << vp.left << ", " - << "top: " << vp.top << ", " - << "width: " << vp.width << ", " - << "height: " << vp.height << ", " - << "minDepth: " << vp.minDepth << ", " - << "maxDepth: " << vp.maxDepth << "]\n"; - }); - } - - void finish_vertex( - RenderGraph::vertex_descriptor vertID, - const AddressableView &gv) const { - std::ignore = gv; - visitObject( - vertID, gv.mGraph, - [&](const RasterPass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const RasterSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputeSubpass &subpass) { - std::ignore = subpass; - }, - [&](const ComputePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const ResolvePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const CopyPass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const MovePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const RaytracePass &pass) { - std::ignore = pass; - unindent(space); - OSS << "}\n"; - }, - [&](const RenderQueue &queue) { - std::ignore = queue; - unindent(space); - OSS << "}\n"; - }, - [&](const SceneData &scene) { - std::ignore = scene; - unindent(space); - OSS << "}\n"; - }, - [&](const Blit &blit) { - }, - [&](const Dispatch &dispatch) { - }, - [&](const ccstd::pmr::vector &clear) { - std::ignore = clear; - unindent(space); - OSS << "}\n"; - }, - [&](const gfx::Viewport &clear) { - }); - } - - std::ostringstream &oss; - ccstd::pmr::string &space; -}; - -} // namespace - -ccstd::string RenderGraph::print( - boost::container::pmr::memory_resource *scratch) const { - const auto &rg = *this; - std::ostringstream oss; - ccstd::pmr::string space(scratch); - oss << "\n"; - OSS << "RenderGraph {\n"; - { - INDENT(); - RenderGraphPrintVisitor visitor{ - {}, oss, space}; - AddressableView graphView(rg); - auto colors = rg.colors(scratch); - boost::depth_first_search(graphView, visitor, get(colors, rg)); - } - OSS << "}\n"; - return oss.str(); -} - } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp new file mode 100644 index 00000000000..dce7e2773fa --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.cpp @@ -0,0 +1,327 @@ +#include +#include +#include "cocos/renderer/pipeline/custom/RenderCommonNames.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/details/DebugUtils.h" +#include "cocos/renderer/pipeline/custom/details/GraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GraphView.h" + +namespace cc { + +namespace render { + +namespace { + +const char *getName(const gfx::LoadOp &op) { + switch (op) { + case gfx::LoadOp::LOAD: + return "LOAD"; + case gfx::LoadOp::CLEAR: + return "CLEAR"; + case gfx::LoadOp::DISCARD: + return "DISCARD"; + default: + return "UNKNOWN"; + } + return "UNKNOWN"; +} + +const char *getName(const gfx::StoreOp &op) { + switch (op) { + case gfx::StoreOp::STORE: + return "STORE"; + case gfx::StoreOp::DISCARD: + return "DISCARD"; + default: + return "UNKNOWN"; + } + return "UNKNOWN"; +} + +std::string getName(const gfx::ClearFlagBit &flags) { + std::ostringstream oss; + int count = 0; + if (hasAnyFlags(flags, gfx::ClearFlagBit::COLOR)) { + if (count++) { + oss << "|"; + } + oss << "COLOR"; + } + if (hasAnyFlags(flags, gfx::ClearFlagBit::DEPTH)) { + if (count++) { + oss << "|"; + } + oss << "DEPTH"; + } + if (hasAnyFlags(flags, gfx::ClearFlagBit::STENCIL)) { + if (count++) { + oss << "|"; + } + oss << "STENCIL"; + } + if (flags == gfx::ClearFlagBit::NONE) { + oss << "NONE"; + } + return oss.str(); +} + +struct RenderGraphPrintVisitor : boost::dfs_visitor<> { + void discover_vertex( + RenderGraph::vertex_descriptor vertID, + const AddressableView &gv) const { + const auto &g = gv.mGraph; + const auto &name = get(RenderGraph::NameTag{}, g, vertID); + visitObject( + vertID, gv.mGraph, + [&](const RasterPass &pass) { + OSS << "RasterPass \"" << name << "\" {\n"; + indent(space); + for (const auto &[name, rasterView] : pass.rasterViews) { + OSS << "RasterView \"" << name << "\" {\n"; + { + INDENT(); + OSS << "slotName: \"" << rasterView.slotName << "\";\n"; + OSS << "accessType: " << getName(rasterView.accessType) << ";\n"; + OSS << "attachmentType: " << getName(rasterView.attachmentType) << ";\n"; + OSS << "loadOp: " << getName(rasterView.loadOp) << ";\n"; + OSS << "storeOp: " << getName(rasterView.storeOp) << ";\n"; + OSS << "clearFlags: " << getName(rasterView.clearFlags) << ";\n"; + const auto &c = rasterView.clearColor; + if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(rasterView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + for (const auto &[name, computeViews] : pass.computeViews) { + OSS << "ComputeViews \"" << name << "\" {\n"; + { + INDENT(); + for (const auto &computeView : computeViews) { + OSS << "ComputeView \"" << computeView.name << "\" {\n"; + { + INDENT(); + OSS << "accessType: " << getName(computeView.accessType) << ";\n"; + OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; + const auto &c = computeView.clearValue; + if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + } + OSS << "}\n"; + } + }, + [&](const RasterSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputeSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputePass &pass) { + OSS << "ComputePass \"" << name << "\" {\n"; + indent(space); + for (const auto &[name, computeViews] : pass.computeViews) { + OSS << "ComputeViews \"" << name << "\" {\n"; + { + INDENT(); + for (const auto &computeView : computeViews) { + OSS << "ComputeView \"" << computeView.name << "\" {\n"; + { + INDENT(); + OSS << "accessType: " << getName(computeView.accessType) << ";\n"; + OSS << "clearFlags: " << getName(computeView.clearFlags) << ";\n"; + const auto &c = computeView.clearValue; + if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(computeView.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + } + OSS << "}\n"; + } + }, + [&](const ResolvePass &pass) { + OSS << "ResolvePass \"" << name << "\" {\n"; + for (const auto &pair : pass.resolvePairs) { + INDENT(); + OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; + } + indent(space); + }, + [&](const CopyPass &pass) { + OSS << "CopyPass \"" << name << "\" {\n"; + for (const auto &pair : pass.copyPairs) { + INDENT(); + OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; + } + indent(space); + }, + [&](const MovePass &pass) { + OSS << "MovePass \"" << name << "\" {\n"; + for (const auto &pair : pass.movePairs) { + INDENT(); + OSS << "source: \"" << pair.source << "\", target: \"" << pair.target << "\"\n"; + } + indent(space); + }, + [&](const RaytracePass &pass) { + std::ignore = pass; + OSS << "RaytracePass \"" << name << "\" {\n"; + indent(space); + }, + [&](const RenderQueue &queue) { + OSS << "Queue \"" << name << "\" {\n"; + { + INDENT(); + OSS << "hint: " << getName(queue.hint) << ";\n"; + } + indent(space); + }, + [&](const SceneData &scene) { + std::ignore = scene; + OSS << "Scene \"" << name << "\" {\n"; + indent(space); + }, + [&](const Blit &blit) { + std::ignore = blit; + OSS << "Blit \"" << name << "\";\n"; + }, + [&](const Dispatch &dispatch) { + OSS << "Dispatch \"" << name << "\", [" + << dispatch.threadGroupCountX << ", " + << dispatch.threadGroupCountY << ", " + << dispatch.threadGroupCountZ << "];\n"; + }, + [&](const ccstd::pmr::vector &clearViews) { + OSS << "Clear \"" << name << "\" {\n"; + indent(space); + for (const auto &view : clearViews) { + INDENT(); + OSS << "\"" << view.slotName << "\" {\n"; + { + INDENT(); + OSS << "clearFlags: " << getName(view.clearFlags) << ";\n"; + const auto &c = view.clearColor; + if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::COLOR)) { + OSS << "clearColor: [" << c.x << ", " << c.y << ", " << c.z << ", " << c.z << "];\n"; + } else if (hasAnyFlags(view.clearFlags, gfx::ClearFlagBit::DEPTH_STENCIL)) { + OSS << "clearColor: [" << c.x << ", " << c.y << "];\n"; + } + } + OSS << "}\n"; + } + }, + [&](const gfx::Viewport &vp) { + OSS << "Viewport \"" << name << "\" [" + << "left: " << vp.left << ", " + << "top: " << vp.top << ", " + << "width: " << vp.width << ", " + << "height: " << vp.height << ", " + << "minDepth: " << vp.minDepth << ", " + << "maxDepth: " << vp.maxDepth << "]\n"; + }); + } + + void finish_vertex( + RenderGraph::vertex_descriptor vertID, + const AddressableView &gv) const { + std::ignore = gv; + visitObject( + vertID, gv.mGraph, + [&](const RasterPass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const RasterSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputeSubpass &subpass) { + std::ignore = subpass; + }, + [&](const ComputePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const ResolvePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const CopyPass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const MovePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const RaytracePass &pass) { + std::ignore = pass; + unindent(space); + OSS << "}\n"; + }, + [&](const RenderQueue &queue) { + std::ignore = queue; + unindent(space); + OSS << "}\n"; + }, + [&](const SceneData &scene) { + std::ignore = scene; + unindent(space); + OSS << "}\n"; + }, + [&](const Blit &blit) { + }, + [&](const Dispatch &dispatch) { + }, + [&](const ccstd::pmr::vector &clear) { + std::ignore = clear; + unindent(space); + OSS << "}\n"; + }, + [&](const gfx::Viewport &clear) { + }); + } + + std::ostringstream &oss; + ccstd::pmr::string &space; +}; + +} // namespace + +ccstd::string RenderGraph::print( + boost::container::pmr::memory_resource *scratch) const { + const auto &rg = *this; + std::ostringstream oss; + ccstd::pmr::string space(scratch); + oss << "\n"; + OSS << "RenderGraph {\n"; + { + INDENT(); + RenderGraphPrintVisitor visitor{ + {}, oss, space}; + AddressableView graphView(rg); + auto colors = rg.colors(scratch); + boost::depth_first_search(graphView, visitor, get(colors, rg)); + } + OSS << "}\n"; + return oss.str(); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h new file mode 100644 index 00000000000..18858869210 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h @@ -0,0 +1,216 @@ +#pragma once +#include "cocos/renderer/pipeline/custom/LayoutGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/NativeTypes.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" +#include "pipeline/custom/RenderGraphTypes.h" + +namespace cc { + +namespace render { + +template +RenderGraph::vertex_descriptor +addVertex2(Tag tag, Component0 &&c0, Component1 &&c1, Component2 &&c2, Component3 &&c3, ValueT &&val, + RenderGraph &g, RenderGraph::vertex_descriptor u = RenderGraph::null_vertex()) { + auto v = addVertex( + tag, + std::forward(c0), + std::forward(c1), + std::forward(c2), + std::forward(c3), + std::forward(val), + g, + u); + g.sortedVertices.emplace_back(v); + CC_EXPECTS(g.sortedVertices.size() == num_vertices(g)); + return v; +} + +inline LayoutGraphData::vertex_descriptor getSubpassOrPassID( + RenderGraph::vertex_descriptor vertID, + const RenderGraph &rg, const LayoutGraphData &lg) { + const auto queueID = parent(vertID, rg); + CC_ENSURES(queueID != RenderGraph::null_vertex()); + const auto subpassOrPassID = parent(queueID, rg); + CC_ENSURES(subpassOrPassID != RenderGraph::null_vertex()); + const auto passID = parent(subpassOrPassID, rg); + + auto layoutID = LayoutGraphData::null_vertex(); + if (passID == RenderGraph::null_vertex()) { // single render pass + const auto &layoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); + CC_ENSURES(!layoutName.empty()); + layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lg); + } else { // render pass + const auto &passLayoutName = get(RenderGraph::LayoutTag{}, rg, passID); + CC_ENSURES(!passLayoutName.empty()); + const auto passLayoutID = locate(LayoutGraphData::null_vertex(), passLayoutName, lg); + CC_ENSURES(passLayoutID != LayoutGraphData::null_vertex()); + + const auto &subpassLayoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); + if (subpassLayoutName.empty()) { + layoutID = passLayoutID; // expect to be multisample pass + } else { + const auto subpassLayoutID = locate(passLayoutID, subpassLayoutName, lg); + CC_ENSURES(subpassLayoutID != LayoutGraphData::null_vertex()); + layoutID = subpassLayoutID; + } + + } + CC_ENSURES(layoutID != LayoutGraphData::null_vertex()); + return layoutID; +} + +inline std::tuple +addRenderPassVertex( + RenderGraph &renderGraph, const LayoutGraphData &layoutGraph, + uint32_t width, uint32_t height, // NOLINT(bugprone-easily-swappable-parameters) + uint32_t count, uint32_t quality, // NOLINT(bugprone-easily-swappable-parameters) + const ccstd::string &passName) { + RasterPass pass(renderGraph.get_allocator()); + pass.width = width; + pass.height = height; + pass.viewport.width = width; + pass.viewport.height = height; + pass.count = count; + pass.quality = quality; + + auto passID = addVertex2( + RasterPassTag{}, + std::forward_as_tuple(passName), + std::forward_as_tuple(passName), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(pass)), + renderGraph); + + auto passLayoutID = locate(LayoutGraphData::null_vertex(), passName, layoutGraph); + CC_EXPECTS(passLayoutID != LayoutGraphData::null_vertex()); + + return {passID, passLayoutID}; +} + +inline std::tuple +addRenderSubpassVertex( + RasterPass &pass, + RenderGraph &renderGraph, RenderGraph::vertex_descriptor passID, + const LayoutGraphData &layoutGraph, LayoutGraphData::vertex_descriptor passLayoutID, + const ccstd::string &subpassName, + uint32_t count, uint32_t quality) { // NOLINT(bugprone-easily-swappable-parameters) + + // if subpassName is empty, it must be basic multisample render pass + CC_EXPECTS(!subpassName.empty() || count > 1); + + auto &subpassGraph = pass.subpassGraph; + const auto subpassIndex = num_vertices(pass.subpassGraph); + { + auto id = addVertex( + std::piecewise_construct, + std::forward_as_tuple(subpassName), + std::forward_as_tuple(), + subpassGraph); + CC_ENSURES(id == subpassIndex); + } + + RasterSubpass subpass(subpassIndex, count, quality, renderGraph.get_allocator()); + subpass.viewport.width = pass.width; + subpass.viewport.height = pass.height; + + auto subpassID = addVertex2( + RasterSubpassTag{}, + std::forward_as_tuple(subpassName), + std::forward_as_tuple(subpassName), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(std::move(subpass)), + renderGraph, passID); + + auto subpassLayoutID = LayoutGraphData::null_vertex(); + if (subpassName.empty()) { // Basic multisample render pass (single subpass) + CC_EXPECTS(count > 1); + subpassLayoutID = passLayoutID; + } else { + if constexpr (ENABLE_SUBPASS) { + subpassLayoutID = locate(passLayoutID, subpassName, layoutGraph); + } else { + subpassLayoutID = locate(LayoutGraphData::null_vertex(), subpassName, layoutGraph); + } + } + CC_ENSURES(subpassLayoutID != LayoutGraphData::null_vertex()); + + return {subpassID, subpassLayoutID}; +} + +template +void addPassComputeViewImpl( + Tag tag, + RenderGraph &renderGraph, + RenderGraph::vertex_descriptor passID, + const ccstd::string &name, const ComputeView &view) { + std::ignore = tag; + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); + auto &pass = get(Tag{}, passID, renderGraph); + auto iter = pass.computeViews.find(name.c_str()); + if (iter == pass.computeViews.end()) { + bool added = false; + std::tie(iter, added) = pass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple()); + CC_ENSURES(added); + } + iter->second.emplace_back(view); +} + +template +void addSubpassComputeViewImpl( + Tag tag, + RenderGraph &renderGraph, + RenderGraph::vertex_descriptor subpassID, + const ccstd::string &name, const ComputeView &view) { + std::ignore = tag; + CC_EXPECTS(!name.empty()); + CC_EXPECTS(!view.name.empty()); + auto &subpass = get(Tag{}, subpassID, renderGraph); + const auto passID = parent(subpassID, renderGraph); + CC_EXPECTS(passID != RenderGraph::null_vertex()); + CC_EXPECTS(holds(passID, renderGraph)); + auto &pass = get(RasterPassTag{}, passID, renderGraph); + CC_EXPECTS(subpass.subpassID < num_vertices(pass.subpassGraph)); + auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); + CC_EXPECTS(subpass.computeViews.size() == subpassData.computeViews.size()); + { + auto iter = subpassData.computeViews.find(name.c_str()); + if (iter == subpassData.computeViews.end()) { + bool added = false; + std::tie(iter, added) = subpassData.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple()); + CC_ENSURES(added); + } + iter->second.emplace_back(view); + } + { + auto iter = subpass.computeViews.find(name.c_str()); + if (iter == subpass.computeViews.end()) { + bool added = false; + std::tie(iter, added) = subpass.computeViews.emplace( + std::piecewise_construct, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple()); + CC_ENSURES(added); + } + iter->second.emplace_back(view); + } + CC_ENSURES(subpass.computeViews.size() == subpassData.computeViews.size()); + CC_ENSURES(subpass.computeViews.find(std::string_view{name}) != subpass.computeViews.end()); + CC_ENSURES(subpassData.computeViews.find(std::string_view{name}) != subpassData.computeViews.end()); + CC_ENSURES(subpass.computeViews.find(std::string_view{name})->second.size() == + subpassData.computeViews.find(std::string_view{name})->second.size()); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 20709a6f97f..984e215a9ad 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -126,7 +126,7 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { } // usage - TextureUsage usage = TextureUsage::SAMPLED | TextureUsage::TRANSFER_SRC | TextureUsage::TRANSFER_DST; + TextureUsage usage = TextureUsage::NONE; if (any(desc.flags & ResourceFlags::COLOR_ATTACHMENT)) { usage |= TextureUsage::COLOR_ATTACHMENT; } @@ -143,6 +143,15 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { if (any(desc.flags & ResourceFlags::SHADING_RATE)) { usage |= TextureUsage::SHADING_RATE; } + if (any(desc.flags & ResourceFlags::SAMPLED)) { + usage |= TextureUsage::SAMPLED; + } + if (any(desc.flags & ResourceFlags::TRANSFER_SRC)) { + usage |= TextureUsage::TRANSFER_SRC; + } + if (any(desc.flags & ResourceFlags::TRANSFER_DST)) { + usage |= TextureUsage::TRANSFER_DST; + } return { type, diff --git a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp index 28f590b1b5f..f2cfd0111b0 100644 --- a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp @@ -1,16 +1,11 @@ -#include "LayoutGraphGraphs.h" -#include "NativePipelineTypes.h" -#include "NativeUtils.h" -#include "RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" +#include "cocos/renderer/pipeline/custom/details/Range.h" #include "cocos/scene/Octree.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/Skybox.h" #include "cocos/scene/SpotLight.h" -#include "details/GslUtils.h" -#include "details/Range.h" -#include "pipeline/custom/LayoutGraphTypes.h" -#include "pipeline/custom/NativeUtils.h" -#include "pipeline/custom/RenderCommonTypes.h" namespace cc { diff --git a/native/cocos/renderer/pipeline/custom/NativeSetter.cpp b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp new file mode 100644 index 00000000000..6f4e2ca6fd9 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp @@ -0,0 +1,153 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "cocos/renderer/pipeline/custom/NativeBuiltinUtils.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/NativeUtils.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/scene/RenderScene.h" +#include "cocos/scene/SpotLight.h" + +namespace cc { + +namespace render { + +void NativeSetter::setMat4(const ccstd::string &name, const Mat4 &mat) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setMat4Impl(data, *layoutGraph, name, mat); +} + +void NativeSetter::setQuaternion(const ccstd::string &name, const Quaternion &quat) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setQuaternionImpl(data, *layoutGraph, name, quat); +} + +void NativeSetter::setColor(const ccstd::string &name, const gfx::Color &color) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setColorImpl(data, *layoutGraph, name, color); +} + +void NativeSetter::setVec4(const ccstd::string &name, const Vec4 &vec) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec4Impl(data, *layoutGraph, name, vec); +} + +void NativeSetter::setVec2(const ccstd::string &name, const Vec2 &vec) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec2Impl(data, *layoutGraph, name, vec); +} + +void NativeSetter::setFloat(const ccstd::string &name, float v) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setFloatImpl(data, *layoutGraph, name, v); +} + +void NativeSetter::setArrayBuffer(const ccstd::string &name, const ArrayBuffer *buffer) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setArrayBufferImpl(data, *layoutGraph, name, *buffer); +} + +void NativeSetter::setBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setBufferImpl(data, *layoutGraph, name, buffer); +} + +void NativeSetter::setTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setTextureImpl(data, *layoutGraph, name, texture); +} + +void NativeSetter::setReadWriteBuffer(const ccstd::string &name, gfx::Buffer *buffer) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setReadWriteBufferImpl(data, *layoutGraph, name, buffer); +} + +void NativeSetter::setReadWriteTexture(const ccstd::string &name, gfx::Texture *texture) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setReadWriteTextureImpl(data, *layoutGraph, name, texture); +} + +void NativeSetter::setSampler(const ccstd::string &name, gfx::Sampler *sampler) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setSamplerImpl(data, *layoutGraph, name, sampler); +} + +void NativeSetter::setVec4ArraySize(const ccstd::string &name, uint32_t sz) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec4ArraySizeImpl(data, *layoutGraph, name, sz); +} + +void NativeSetter::setVec4ArrayElem(const ccstd::string &name, const cc::Vec4 &vec, uint32_t id) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setVec4ArrayElemImpl(data, *layoutGraph, name, vec, id); +} + +void NativeSetter::setMat4ArraySize(const ccstd::string &name, uint32_t sz) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setMat4ArraySizeImpl(data, *layoutGraph, name, sz); +} + +void NativeSetter::setMat4ArrayElem(const ccstd::string &name, const cc::Mat4 &mat, uint32_t id) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setMat4ArrayElemImpl(data, *layoutGraph, name, mat, id); +} + +void NativeSetter::setBuiltinCameraConstants(const scene::Camera *camera) { + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setCameraUBOValues( + *camera, + *layoutGraph, + *pipelineRuntime->getPipelineSceneData(), + camera->getScene()->getMainLight(), data); +} + +void NativeSetter::setBuiltinDirectionalLightViewConstants( + const scene::DirectionalLight *light, uint32_t level) { + CC_EXPECTS(light); + auto *device = pipelineRuntime->getDevice(); + const auto &sceneData = *pipelineRuntime->getPipelineSceneData(); + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setShadowUBOLightView(device, *layoutGraph, sceneData, *light, level, data); +} + +void NativeSetter::setBuiltinSpotLightViewConstants(const scene::SpotLight *light) { + CC_EXPECTS(light); + auto *device = pipelineRuntime->getDevice(); + const auto &sceneData = *pipelineRuntime->getPipelineSceneData(); + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setShadowUBOLightView(device, *layoutGraph, sceneData, *light, 0, data); +} + +void NativeSetter::setBuiltinShadowMapConstants( + const scene::DirectionalLight *light) { + CC_EXPECTS(light); + auto *device = pipelineRuntime->getDevice(); + const auto &sceneData = *pipelineRuntime->getPipelineSceneData(); + auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); + setShadowUBOView(*device, *layoutGraph, sceneData, *light, data); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.cpp b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp index 75af2336a16..4edad502350 100644 --- a/native/cocos/renderer/pipeline/custom/NativeUtils.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.cpp @@ -1,98 +1,36 @@ -#include "NativeUtils.h" -#include "LayoutGraphGraphs.h" -#include "NativePipelineTypes.h" -#include "RenderGraphGraphs.h" -#include "cocos/application/ApplicationManager.h" -#include "cocos/core/Root.h" -#include "details/GslUtils.h" +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "cocos/renderer/pipeline/custom/NativeUtils.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" +#include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" +#include "cocos/renderer/pipeline/custom/details/GslUtils.h" namespace cc { -namespace render { - -void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]) { - auto minX = static_cast(viewport.x); - auto maxX = static_cast(viewport.x + viewport.z); - auto minY = static_cast(viewport.y); - auto maxY = static_cast(viewport.y + viewport.w); - if (device.getCapabilities().screenSpaceSignY > 0) { - std::swap(minY, maxY); - } - int n = 0; - vbData[n++] = -1.0F; - vbData[n++] = -1.0F; - vbData[n++] = minX; // uv - vbData[n++] = maxY; - vbData[n++] = 1.0F; - vbData[n++] = -1.0F; - vbData[n++] = maxX; - vbData[n++] = maxY; - vbData[n++] = -1.0F; - vbData[n++] = 1.0F; - vbData[n++] = minX; - vbData[n++] = minY; - vbData[n++] = 1.0F; - vbData[n++] = 1.0F; - vbData[n++] = maxX; - vbData[n++] = minY; -} -// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) -void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter) { - const auto &root = *Root::getInstance(); - const auto shadingWidth = static_cast(width); - const auto shadingHeight = static_cast(height); - setter.setVec4( - "cc_time", - Vec4( - root.getCumulativeTime(), - root.getFrameTime(), - static_cast(CC_CURRENT_ENGINE()->getTotalFrames()), - 0.0F)); - - setter.setVec4( - "cc_screenSize", - Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); - setter.setVec4( - "cc_nativeSize", - Vec4(shadingWidth, shadingHeight, 1.0F / shadingWidth, 1.0F / shadingHeight)); -#if 0 - const auto *debugView = root.getDebugView(); - if (debugView) { - setter.setVec4( - "cc_debug_view_mode", - Vec4(static_cast(debugView->getSingleMode()), - debugView->isLightingWithAlbedo() ? 1.0F : 0.0F, - debugView->isCsmLayerColoration() ? 1.0F : 0.0F, - 0.0F)); - Vec4 debugPackVec{}; - for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); - i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { - const auto idx = i % 4; - (&debugPackVec.x)[idx] = debugView->isCompositeModeEnabled(i) ? 1.0F : 0.0F; - const auto packIdx = static_cast(floor(static_cast(i) / 4.0F)); - if (idx == 3) { - std::string name("cc_debug_view_composite_pack_"); - name.append(std::to_string(packIdx + 1)); - setter.setVec4(name, debugPackVec); - } - } - } else { - setter.setVec4("cc_debug_view_mode", Vec4(0.0F, 1.0F, 0.0F, 0.0F)); - Vec4 debugPackVec{}; - for (auto i = static_cast(pipeline::DebugViewCompositeType::DIRECT_DIFFUSE); - i < static_cast(pipeline::DebugViewCompositeType::MAX_BIT_COUNT); ++i) { - const auto idx = i % 4; - (&debugPackVec.x)[idx] = 1.0F; - const auto packIdx = static_cast(floor(i / 4.0)); - if (idx == 3) { - std::string name("cc_debug_view_composite_pack_"); - name.append(std::to_string(packIdx + 1)); - setter.setVec4(name, debugPackVec); - } - } - } -#endif -} +namespace render { namespace { @@ -225,35 +163,6 @@ void setSamplerImpl(RenderData &data, const LayoutGraphData &lg, const ccstd::st data.samplers[nameID.value] = sampler; } -LayoutGraphData::vertex_descriptor getSubpassOrPassID( - RenderGraph::vertex_descriptor vertID, - const RenderGraph &rg, const LayoutGraphData &lg) { - const auto queueID = parent(vertID, rg); - CC_ENSURES(queueID != RenderGraph::null_vertex()); - const auto subpassOrPassID = parent(queueID, rg); - CC_ENSURES(subpassOrPassID != RenderGraph::null_vertex()); - const auto passID = parent(subpassOrPassID, rg); - - auto layoutID = LayoutGraphData::null_vertex(); - if (passID == RenderGraph::null_vertex()) { // single render pass - const auto &layoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); - CC_ENSURES(!layoutName.empty()); - layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lg); - } else { // render pass - const auto &passLayoutName = get(RenderGraph::LayoutTag{}, rg, passID); - CC_ENSURES(!passLayoutName.empty()); - const auto passLayoutID = locate(LayoutGraphData::null_vertex(), passLayoutName, lg); - CC_ENSURES(passLayoutID != LayoutGraphData::null_vertex()); - - const auto &subpassLayoutName = get(RenderGraph::LayoutTag{}, rg, subpassOrPassID); - CC_ENSURES(!subpassLayoutName.empty()); - const auto subpassLayoutID = locate(passLayoutID, subpassLayoutName, lg); - CC_ENSURES(subpassLayoutID != LayoutGraphData::null_vertex()); - layoutID = subpassLayoutID; - } - CC_ENSURES(layoutID != LayoutGraphData::null_vertex()); - return layoutID; -} - } // namespace render + } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeUtils.h b/native/cocos/renderer/pipeline/custom/NativeUtils.h index 620aa64b3e2..82595dc3c92 100644 --- a/native/cocos/renderer/pipeline/custom/NativeUtils.h +++ b/native/cocos/renderer/pipeline/custom/NativeUtils.h @@ -1,18 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + #pragma once #include "cocos/core/ArrayBuffer.h" #include "cocos/math/Vec4.h" -#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" -#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphFwd.h" +#include "cocos/renderer/pipeline/custom/RenderGraphFwd.h" #include "cocos/renderer/pipeline/custom/RenderInterfaceFwd.h" namespace cc { -namespace gfx { -class Device; -} -namespace render { -void setupQuadVertexBuffer(gfx::Device &device, const Vec4 &viewport, float vbData[16]); -void updateRasterPassConstants(uint32_t width, uint32_t height, Setter &setter); +namespace render { void setMat4Impl( RenderData &data, const LayoutGraphData &lg, std::string_view name, @@ -56,11 +75,6 @@ void setReadWriteTextureImpl(RenderData &data, const LayoutGraphData &lg, const void setSamplerImpl(RenderData &data, const LayoutGraphData &lg, const ccstd::string &name, gfx::Sampler *sampler); -// Implementation -LayoutGraphData::vertex_descriptor getSubpassOrPassID( - RenderGraph::vertex_descriptor vertID, - const RenderGraph &rg, const LayoutGraphData &lg); - } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h b/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h index 8f54ad52ca6..1628d725ef7 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonFwd.h @@ -29,6 +29,7 @@ */ // clang-format off #pragma once +#include "cocos/base/std/hash/hash.h" #include "cocos/base/std/variant.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" @@ -84,4 +85,13 @@ struct PipelineStatistics; } // namespace cc +namespace ccstd { + +template <> +struct hash { + hash_t operator()(const cc::render::ResolvePair& val) const noexcept; +}; + +} // namespace ccstd + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h index fea8e265f87..eb6dfe6a9b3 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h @@ -32,6 +32,7 @@ #include "cocos/base/Ptr.h" #include "cocos/base/std/container/map.h" #include "cocos/base/std/container/string.h" +#include "cocos/base/std/hash/hash.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/pipeline/custom/RenderCommonFwd.h" #include "cocos/scene/Light.h" @@ -101,6 +102,8 @@ enum class ResourceFlags : uint32_t { DEPTH_STENCIL_ATTACHMENT = 0x20, INPUT_ATTACHMENT = 0x40, SHADING_RATE = 0x80, + TRANSFER_SRC = 0x100, + TRANSFER_DST = 0x200, }; constexpr ResourceFlags operator|(const ResourceFlags lhs, const ResourceFlags rhs) noexcept { @@ -154,6 +157,7 @@ enum class SceneFlags : uint32_t { DRAW_INSTANCING = 0x800, DRAW_NON_INSTANCING = 0x1000, REFLECTION_PROBE = 0x2000, + GPU_DRIVEN = 0x4000, ALL = 0xFFFFFFFF, }; @@ -325,6 +329,15 @@ struct ResolvePair { gfx::ResolveMode mode1{gfx::ResolveMode::SAMPLE_ZERO}; }; +inline bool operator==(const ResolvePair& lhs, const ResolvePair& rhs) noexcept { + return std::forward_as_tuple(lhs.source, lhs.target, lhs.resolveFlags, lhs.mode, lhs.mode1) == + std::forward_as_tuple(rhs.source, rhs.target, rhs.resolveFlags, rhs.mode, rhs.mode1); +} + +inline bool operator!=(const ResolvePair& lhs, const ResolvePair& rhs) noexcept { + return !(lhs == rhs); +} + struct CopyPair { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -420,4 +433,18 @@ struct PipelineStatistics { } // namespace cc +namespace ccstd { + +inline hash_t hash::operator()(const cc::render::ResolvePair& val) const noexcept { + hash_t seed = 0; + hash_combine(seed, val.source); + hash_combine(seed, val.target); + hash_combine(seed, val.resolveFlags); + hash_combine(seed, val.mode); + hash_combine(seed, val.mode1); + return seed; +} + +} // namespace ccstd + // clang-format on diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp index 0d6236eb388..bcb977b9e35 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.cpp @@ -124,15 +124,18 @@ ComputeView::ComputeView(ComputeView const& rhs, const allocator_type& alloc) Subpass::Subpass(const allocator_type& alloc) noexcept : rasterViews(alloc), - computeViews(alloc) {} + computeViews(alloc), + resolvePairs(alloc) {} Subpass::Subpass(Subpass&& rhs, const allocator_type& alloc) : rasterViews(std::move(rhs.rasterViews), alloc), - computeViews(std::move(rhs.computeViews), alloc) {} + computeViews(std::move(rhs.computeViews), alloc), + resolvePairs(std::move(rhs.resolvePairs), alloc) {} Subpass::Subpass(Subpass const& rhs, const allocator_type& alloc) : rasterViews(rhs.rasterViews, alloc), - computeViews(rhs.computeViews, alloc) {} + computeViews(rhs.computeViews, alloc), + resolvePairs(rhs.resolvePairs, alloc) {} SubpassGraph::SubpassGraph(const allocator_type& alloc) noexcept : _vertices(alloc), @@ -416,7 +419,8 @@ RenderGraph::RenderGraph(const allocator_type& alloc) noexcept dispatches(alloc), clearViews(alloc), viewports(alloc), - index(alloc) {} + index(alloc), + sortedVertices(alloc) {} RenderGraph::RenderGraph(RenderGraph&& rhs, const allocator_type& alloc) : objects(std::move(rhs.objects), alloc), @@ -439,7 +443,8 @@ RenderGraph::RenderGraph(RenderGraph&& rhs, const allocator_type& alloc) dispatches(std::move(rhs.dispatches), alloc), clearViews(std::move(rhs.clearViews), alloc), viewports(std::move(rhs.viewports), alloc), - index(std::move(rhs.index), alloc) {} + index(std::move(rhs.index), alloc), + sortedVertices(std::move(rhs.sortedVertices), alloc) {} // ContinuousContainer void RenderGraph::reserve(vertices_size_type sz) { diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h index d0f7e0aa9f7..acf43826fd8 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h @@ -166,7 +166,7 @@ struct ResourceDesc { uint16_t depthOrArraySize{0}; uint16_t mipLevels{0}; gfx::Format format{gfx::Format::UNKNOWN}; - gfx::SampleCount sampleCount{gfx::SampleCount::ONE}; + gfx::SampleCount sampleCount{gfx::SampleCount::X1}; gfx::TextureFlagBit textureFlags{gfx::TextureFlagBit::NONE}; ResourceFlags flags{ResourceFlags::NONE}; }; @@ -242,11 +242,12 @@ struct Subpass { PmrTransparentMap rasterViews; PmrTransparentMap> computeViews; + ccstd::pmr::vector resolvePairs; }; inline bool operator==(const Subpass& lhs, const Subpass& rhs) noexcept { - return std::forward_as_tuple(lhs.rasterViews, lhs.computeViews) == - std::forward_as_tuple(rhs.rasterViews, rhs.computeViews); + return std::forward_as_tuple(lhs.rasterViews, lhs.computeViews, lhs.resolvePairs) == + std::forward_as_tuple(rhs.rasterViews, rhs.computeViews, rhs.resolvePairs); } inline bool operator!=(const Subpass& lhs, const Subpass& rhs) noexcept { @@ -1047,6 +1048,7 @@ struct RenderGraph { impl::ValueHandle, impl::ValueHandle>; + vertex_descriptor getPassID(vertex_descriptor nodeID) const; ccstd::string print(boost::container::pmr::memory_resource* scratch) const; // ContinuousContainer @@ -1123,6 +1125,7 @@ struct RenderGraph { ccstd::pmr::vector viewports; // Members PmrUnorderedStringMap index; + ccstd::pmr::vector sortedVertices; }; } // namespace render @@ -1168,6 +1171,7 @@ inline hash_t hash::operator()(const cc::render::Subpass& v hash_t seed = 0; hash_combine(seed, val.rasterViews); hash_combine(seed, val.computeViews); + hash_combine(seed, val.resolvePairs); return seed; } diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h index c88d1732b0d..7a72a5f60e8 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceFwd.h @@ -49,16 +49,15 @@ class RenderNode; class Setter; class RenderQueueBuilder; class BasicRenderPassBuilder; +class BasicMultisampleRenderPassBuilder; class BasicPipeline; class RenderSubpassBuilder; class MultisampleRenderSubpassBuilder; class ComputeQueueBuilder; class ComputeSubpassBuilder; class RenderPassBuilder; +class MultisampleRenderPassBuilder; class ComputePassBuilder; -class SceneVisitor; -class SceneTask; -class SceneTransversal; class Pipeline; class PipelineBuilder; class RenderingModule; diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index 3a2d25b3a39..4c5e015b567 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -290,6 +290,11 @@ enum class SubpassCapabilities : uint32_t { * @zh 支持读取当前像素任意颜色值 */ INPUT_COLOR_MRT = 1 << 2, + /** + * @en Each subpass has its own sample count. + * @zh 每个Subpass拥有不同的采样数 + */ + HETEROGENEOUS_SAMPLE_COUNT = 1 << 3, }; constexpr SubpassCapabilities operator|(const SubpassCapabilities lhs, const SubpassCapabilities rhs) noexcept { @@ -445,6 +450,13 @@ class Setter : public RenderNode { * @param name @en descriptor name in shader. @zh 填写着色器中的描述符(descriptor)名字 */ virtual void setSampler(const ccstd::string &name, gfx::Sampler *sampler) = 0; + virtual void setBuiltinCameraConstants(const scene::Camera *camera) = 0; + virtual void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) = 0; + virtual void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) = 0; + virtual void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) = 0; + void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light) { + setBuiltinDirectionalLightViewConstants(light, 0); + } }; /** @@ -468,6 +480,9 @@ class RenderQueueBuilder : public Setter { * @param sceneFlags @en Rendering flags of the scene @zh 场景渲染标志位 */ virtual void addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) = 0; + virtual void addScene(const scene::Camera *camera, SceneFlags sceneFlags) = 0; + virtual void addSceneCulledByDirectionalLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::DirectionalLight *light, uint32_t level) = 0; + virtual void addSceneCulledBySpotLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::SpotLight *light) = 0; /** * @en Render a full-screen quad. * @zh 渲染全屏四边形 @@ -636,6 +651,20 @@ class BasicRenderPassBuilder : public Setter { } }; +class BasicMultisampleRenderPassBuilder : public BasicRenderPassBuilder { +public: + BasicMultisampleRenderPassBuilder() noexcept = default; + + virtual void resolveRenderTarget(const ccstd::string &source, const ccstd::string &target) = 0; + virtual void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target, gfx::ResolveMode depthMode, gfx::ResolveMode stencilMode) = 0; + void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target) { + resolveDepthStencil(source, target, gfx::ResolveMode::SAMPLE_ZERO, gfx::ResolveMode::SAMPLE_ZERO); + } + void resolveDepthStencil(const ccstd::string &source, const ccstd::string &target, gfx::ResolveMode depthMode) { + resolveDepthStencil(source, target, depthMode, gfx::ResolveMode::SAMPLE_ZERO); + } +}; + /** * @en BasicPipeline * Basic pipeline provides basic rendering features which are supported on all platforms. @@ -731,6 +760,8 @@ class BasicPipeline : public PipelineRuntime { * @param format @en Format of the resource @zh 资源的格式 */ virtual void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) = 0; + virtual uint32_t addResource(const ccstd::string &name, ResourceDimension dimension, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) = 0; + virtual void updateResource(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) = 0; /** * @engineInternal * @en Begin rendering one frame @@ -770,7 +801,7 @@ class BasicPipeline : public PipelineRuntime { * @param passName @en Pass name declared in the effect. Default value is 'default' @zh effect中的pass name,缺省为'default' * @returns Multisample basic render pass builder */ - virtual BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) = 0; + virtual BasicMultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) = 0; /** * @deprecated Method will be removed in 3.9.0 */ @@ -815,7 +846,7 @@ class BasicPipeline : public PipelineRuntime { BasicRenderPassBuilder *addRenderPass(uint32_t width, uint32_t height) { return addRenderPass(width, height, "default"); } - BasicRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality) { + BasicMultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality) { return addMultisampleRenderPass(width, height, count, quality, "default"); } }; @@ -1187,6 +1218,14 @@ class RenderPassBuilder : public BasicRenderPassBuilder { } }; +class MultisampleRenderPassBuilder : public BasicMultisampleRenderPassBuilder { +public: + MultisampleRenderPassBuilder() noexcept = default; + + virtual void addStorageBuffer(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) = 0; + virtual void addStorageImage(const ccstd::string &name, AccessType accessType, const ccstd::string &slotName) = 0; +}; + /** * @en Compute pass * @zh 计算通道 @@ -1271,61 +1310,6 @@ class ComputePassBuilder : public Setter { } }; -/** - * @deprecated @en Not used @zh 未使用 - */ -class SceneVisitor { -public: - SceneVisitor() noexcept = default; - SceneVisitor(SceneVisitor&& rhs) = delete; - SceneVisitor(SceneVisitor const& rhs) = delete; - SceneVisitor& operator=(SceneVisitor&& rhs) = delete; - SceneVisitor& operator=(SceneVisitor const& rhs) = delete; - virtual ~SceneVisitor() noexcept = default; - - virtual const pipeline::PipelineSceneData *getPipelineSceneData() const = 0; - virtual void setViewport(const gfx::Viewport &vp) = 0; - virtual void setScissor(const gfx::Rect &rect) = 0; - virtual void bindPipelineState(gfx::PipelineState *pso) = 0; - virtual void bindDescriptorSet(uint32_t set, gfx::DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) = 0; - virtual void bindInputAssembler(gfx::InputAssembler *ia) = 0; - virtual void updateBuffer(gfx::Buffer *buff, const void *data, uint32_t size) = 0; - virtual void draw(const gfx::DrawInfo &info) = 0; -}; - -/** - * @deprecated @en Not used @zh 未使用 - */ -class SceneTask { -public: - SceneTask() noexcept = default; - SceneTask(SceneTask&& rhs) = delete; - SceneTask(SceneTask const& rhs) = delete; - SceneTask& operator=(SceneTask&& rhs) = delete; - SceneTask& operator=(SceneTask const& rhs) = delete; - virtual ~SceneTask() noexcept = default; - - virtual TaskType getTaskType() const noexcept = 0; - virtual void start() = 0; - virtual void join() = 0; - virtual void submit() = 0; -}; - -/** - * @deprecated @en Not used @zh 未使用 - */ -class SceneTransversal { -public: - SceneTransversal() noexcept = default; - SceneTransversal(SceneTransversal&& rhs) = delete; - SceneTransversal(SceneTransversal const& rhs) = delete; - SceneTransversal& operator=(SceneTransversal&& rhs) = delete; - SceneTransversal& operator=(SceneTransversal const& rhs) = delete; - virtual ~SceneTransversal() noexcept = default; - - virtual SceneTask *transverse(SceneVisitor *visitor) const = 0; -}; - /** * @en Render pipeline. * @zh 渲染管线 @@ -1389,6 +1373,7 @@ class Pipeline : public BasicPipeline { */ virtual void updateShadingRateTexture(const ccstd::string &name, uint32_t width, uint32_t height) = 0; RenderPassBuilder *addRenderPass(uint32_t width, uint32_t height, const ccstd::string &passName) override = 0 /* covariant */; + MultisampleRenderPassBuilder *addMultisampleRenderPass(uint32_t width, uint32_t height, uint32_t count, uint32_t quality, const ccstd::string &passName) override = 0 /* covariant */; /** * @en Add compute pass * @zh 添加计算通道 @@ -1438,6 +1423,8 @@ class Pipeline : public BasicPipeline { * @param movePairs @en Array of move source and target @zh 移动来源与目标的数组 */ virtual void addMovePass(const ccstd::vector &movePairs) = 0; + virtual void addBuiltinGpuCullingPass(const scene::Camera *camera, const std::string &hzbName, const scene::Light *light) = 0; + virtual void addBuiltinHzbGenerationPass(const std::string &sourceDepthStencilName, const std::string &targetHzbName) = 0; /** * @experimental */ @@ -1461,6 +1448,12 @@ class Pipeline : public BasicPipeline { void updateStorageTexture(const ccstd::string &name, uint32_t width, uint32_t height) { updateStorageTexture(name, width, height, gfx::Format::UNKNOWN); } + void addBuiltinGpuCullingPass(const scene::Camera *camera) { + addBuiltinGpuCullingPass(camera, "", nullptr); + } + void addBuiltinGpuCullingPass(const scene::Camera *camera, const std::string &hzbName) { + addBuiltinGpuCullingPass(camera, hzbName, nullptr); + } }; /** diff --git a/native/cocos/renderer/pipeline/custom/test/test.h b/native/cocos/renderer/pipeline/custom/test/test.h index cb28556b1dc..ed8f44f5eec 100644 --- a/native/cocos/renderer/pipeline/custom/test/test.h +++ b/native/cocos/renderer/pipeline/custom/test/test.h @@ -149,7 +149,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn nameSet.emplace(viewName); } - auto &rasterViews = hasSubpass ? (*subpass).rasterViews : raster.rasterViews; + auto &views = hasSubpass ? (*subpass).rasterViews : raster.rasterViews; auto view = RasterView{ viewName.c_str(), isOutput ? AccessType::WRITE : AccessType::READ, @@ -161,7 +161,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn gfx::ShaderStageFlagBit::NONE, }; view.slotID = slot; - rasterViews.emplace(viewName.c_str(), view); + views.emplace(viewName.c_str(), view); if (subpassViews) { subpassViews->emplace(viewName.c_str(), view); @@ -170,6 +170,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn if (iter == raster.attachmentIndexMap.end()) { raster.attachmentIndexMap.emplace(viewName, newID); } + rasterViews.emplace(viewName, view); } ++slot; } @@ -566,117 +567,117 @@ static void runTestGraph(const RenderGraph &renderGraph, const ResourceGraph &re using cc::gfx::TextureFlagBit; \ ResourceInfo resources = { \ {"0", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"1", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"2", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"3", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"4", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"5", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"6", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"7", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"8", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"9", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"10", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"11", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"12", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"13", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"14", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"15", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"16", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"17", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"18", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::MANAGED}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"19", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::EXTERNAL}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"20", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::EXTERNAL}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"21", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::EXTERNAL}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ {"22", \ - {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::ONE, TextureFlagBit::NONE, \ + {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ {ResourceResidency::BACKBUFFER}, \ {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index adc4639b49c..115e2fe5ca8 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -283,7 +283,7 @@ void ShadowFlow::initShadowFrameBuffer(const RenderPipeline *pipeline, const sce const gfx::ColorAttachment colorAttachment{ format, - gfx::SampleCount::ONE, + gfx::SampleCount::X1, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, device->getGeneralBarrier({ @@ -294,7 +294,7 @@ void ShadowFlow::initShadowFrameBuffer(const RenderPipeline *pipeline, const sce const gfx::DepthStencilAttachment depthStencilAttachment{ gfx::Format::DEPTH, - gfx::SampleCount::ONE, + gfx::SampleCount::X1, gfx::LoadOp::CLEAR, gfx::StoreOp::DISCARD, gfx::LoadOp::CLEAR, diff --git a/native/tests/unit-test/src/complicated_barrier_case.cpp b/native/tests/unit-test/src/complicated_barrier_case.cpp index ec1f32703e2..3fdb5ae8a40 100644 --- a/native/tests/unit-test/src/complicated_barrier_case.cpp +++ b/native/tests/unit-test/src/complicated_barrier_case.cpp @@ -136,7 +136,11 @@ TEST(complicatedBarrierTest, test12) { const auto& node3 = barrierMap.at(3); ExpectEq(node3.blockBarrier.frontBarriers.empty(), true); ExpectEq(node3.blockBarrier.rearBarriers.empty(), true); - ExpectEq(node3.subpassBarriers.empty(), true); + + // subpass barrier size is the same as renderpass subpassinfo, though maybe empty. + ExpectEq(node3.subpassBarriers.size() == 1, true); + ExpectEq(node3.subpassBarriers.front().frontBarriers.empty(), true); + ExpectEq(node3.subpassBarriers.front().rearBarriers.empty(), true); //node4 const auto& node4 = barrierMap.at(4); @@ -181,6 +185,7 @@ TEST(complicatedBarrierTest, test12) { const auto& node5 = barrierMap.at(5); ExpectEq(node5.blockBarrier.frontBarriers.size() == 1, true); ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); + // not raster pass ExpectEq(node5.subpassBarriers.empty(), true); auto iter7in5 = findBarrierByResID(node5.blockBarrier.rearBarriers, 7); @@ -198,6 +203,7 @@ TEST(complicatedBarrierTest, test12) { ExpectEq(node6.blockBarrier.frontBarriers.size() == 1, true); // resource later used by raster pass, so that layout can be transferred automatically. ExpectEq(node6.blockBarrier.rearBarriers.empty(), true); + // not a raster pass ExpectEq(node6.subpassBarriers.empty(), true); // node7 @@ -205,7 +211,7 @@ TEST(complicatedBarrierTest, test12) { // undefined layout already in initial layout ExpectEq(node7.blockBarrier.frontBarriers.empty(), true); ExpectEq(node7.blockBarrier.rearBarriers.empty(), true); - ExpectEq(node7.subpassBarriers.empty(), true); + ExpectEq(node7.subpassBarriers.empty(), false); ExpectEq(node7.blockBarrier.rearBarriers.size(), 0); @@ -219,7 +225,7 @@ TEST(complicatedBarrierTest, test12) { const auto& node13 = barrierMap.at(13); ExpectEq(node13.blockBarrier.frontBarriers.size(), 0); ExpectEq(node13.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node13.subpassBarriers.empty(), true); + ExpectEq(node13.subpassBarriers.empty(), false); //node14: almost the same as 13 @@ -234,6 +240,7 @@ TEST(complicatedBarrierTest, test12) { const auto& node16 = barrierMap.at(16); ExpectEq(node16.blockBarrier.frontBarriers.empty(), true); ExpectEq(node16.blockBarrier.rearBarriers.empty(), true); + // not raster pass ExpectEq(node16.subpassBarriers.empty(), true); //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); diff --git a/native/tests/unit-test/src/simple_closed_barrier_test.cpp b/native/tests/unit-test/src/simple_closed_barrier_test.cpp index 6cfbcc275e2..644132e90fb 100644 --- a/native/tests/unit-test/src/simple_closed_barrier_test.cpp +++ b/native/tests/unit-test/src/simple_closed_barrier_test.cpp @@ -54,7 +54,9 @@ TEST(simpleClosedBarrierTest, test11) { const auto& node1 = barrierMap.at(1); ExpectEq(node1.blockBarrier.frontBarriers.size(), 0); ExpectEq(node1.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node1.subpassBarriers.empty(), true); + ExpectEq(node1.subpassBarriers.size() == 1, true); + ExpectEq(node1.subpassBarriers.front().frontBarriers.empty(), true); + ExpectEq(node1.subpassBarriers.front().rearBarriers.empty(), true); // transitioned by renderpass info //ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); @@ -65,7 +67,9 @@ TEST(simpleClosedBarrierTest, test11) { const auto& node2 = barrierMap.at(2); ExpectEq(node2.blockBarrier.frontBarriers.size(), 0); ExpectEq(node2.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node2.subpassBarriers.empty(), true); + ExpectEq(node2.subpassBarriers.size() == 1, true); + ExpectEq(node2.subpassBarriers.front().frontBarriers.empty(), true); + ExpectEq(node2.subpassBarriers.front().rearBarriers.empty(), true); // ditto //// res3 diff --git a/native/tools/swig-config/gfx.i b/native/tools/swig-config/gfx.i index 452f7b47ae9..a0944e0ffd7 100644 --- a/native/tools/swig-config/gfx.i +++ b/native/tools/swig-config/gfx.i @@ -65,6 +65,7 @@ namespace cc { namespace gfx { %ignore CommandBuffer::execute; %ignore CommandBuffer::updateBuffer; +%ignore CommandBuffer::resolveTexture; %ignore CommandBuffer::copyBuffersToTexture; %rename(drawWithInfo) CommandBuffer::draw(const DrawInfo&); diff --git a/native/tools/swig-config/render.i b/native/tools/swig-config/render.i index 4db861b41f0..dbaf304bec1 100644 --- a/native/tools/swig-config/render.i +++ b/native/tools/swig-config/render.i @@ -47,8 +47,6 @@ using namespace cc::render; %ignore cc::render::PipelineRuntime::isOcclusionQueryEnabled; %ignore cc::render::PipelineRuntime::resetRenderQueue; %ignore cc::render::PipelineRuntime::isRenderQueueReset; -%ignore cc::render::SceneVisitor::bindDescriptorSet; -%ignore cc::render::SceneVisitor::updateBuffer; // ----- Rename Section ------ // Brief: Classes, methods or attributes needs to be renamed @@ -118,8 +116,6 @@ using namespace cc::render; %attribute(cc::render::BasicPipeline, cc::render::PipelineType, type, getType); %attribute(cc::render::BasicPipeline, cc::render::PipelineCapabilities, capabilities, getCapabilities); %attribute(cc::render::RenderSubpassBuilder, bool, showStatistics, getShowStatistics, setShowStatistics); -%attribute(cc::render::SceneVisitor, cc::pipeline::PipelineSceneData*, pipelineSceneData, getPipelineSceneData); -%attribute(cc::render::SceneTask, cc::render::TaskType, taskType, getTaskType); // ----- Import Section ------ // Brief: Import header files which are depended by 'Include Section' From b21499ffce8182853c2e71155a215e8c324753dc Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Wed, 19 Jul 2023 10:38:20 +0800 Subject: [PATCH 050/232] Fix potential error: cache invalid player due to object's destroy (#15746) * Fix potential error: cache invalid player due to object's destroy --- cocos/audio/audio-source.ts | 74 ++++++++++++++++++++++++------------- 1 file changed, 48 insertions(+), 26 deletions(-) diff --git a/cocos/audio/audio-source.ts b/cocos/audio/audio-source.ts index 7f966341c8b..07f35a44f39 100644 --- a/cocos/audio/audio-source.ts +++ b/cocos/audio/audio-source.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { AudioPlayer } from 'pal/audio'; +import { AudioPlayer, OneShotAudio } from 'pal/audio'; import { ccclass, help, menu, tooltip, type, range, serializable } from 'cc.decorator'; import { AudioPCMDataView, AudioState } from '../../pal/audio/type'; import { Component } from '../scene-graph/component'; @@ -59,6 +59,7 @@ export class AudioSource extends Component { @type(AudioClip) protected _clip: AudioClip | null = null; protected _player: AudioPlayer | null = null; + private _hasRegisterListener: boolean = false; @serializable protected _loop = false; @@ -78,9 +79,7 @@ export class AudioSource extends Component { private _resetPlayer (): void { if (this._player) { audioManager.removePlaying(this._player); - this._player.offEnded(); - this._player.offInterruptionBegin(); - this._player.offInterruptionEnd(); + this._unregisterListener(); this._player.destroy(); this._player = null; } @@ -137,6 +136,14 @@ export class AudioSource extends Component { // clear old player this._resetPlayer(); this._player = player; + this._syncStates(); + this.node?.emit(_LOADED_EVENT); + }).catch((e) => {}); + } + + private _registerListener (): void { + if (!this._hasRegisterListener && this._player) { + const player = this._player; player.onEnded(() => { audioManager.removePlaying(player); this.node?.emit(AudioSourceEventType.ENDED, this); @@ -145,11 +152,21 @@ export class AudioSource extends Component { audioManager.removePlaying(player); }); player.onInterruptionEnd(() => { - audioManager.addPlaying(player); + if (this._player === player) { + audioManager.addPlaying(player); + } }); - this._syncStates(); - this.node?.emit(_LOADED_EVENT); - }).catch((e) => {}); + this._hasRegisterListener = true; + } + } + + private _unregisterListener (): void { + if (this._player && this._hasRegisterListener) { + this._player.offEnded(); + this._player.offInterruptionBegin(); + this._player.offInterruptionEnd(); + this._hasRegisterListener = false; + } } /** @@ -231,8 +248,7 @@ export class AudioSource extends Component { public onDestroy (): void { this.stop(); - this._player?.destroy(); - this._player = null; + this.clip = null;// It will trigger _syncPlayer then call resetPlayer } /** * @en @@ -332,16 +348,21 @@ export class AudioSource extends Component { this._operationsBeforeLoading.push('play'); return; } + this._registerListener(); audioManager.discardOnePlayingIfNeeded(); // Replay if the audio is playing if (this.state === AudioState.PLAYING) { this._player?.stop().catch((e) => {}); } const player = this._player; - this._player?.play().then(() => { - audioManager.addPlaying(player!); - this.node?.emit(AudioSourceEventType.STARTED, this); - }).catch((e) => {}); + if (player) { + player.play().then(() => { + this.node?.emit(AudioSourceEventType.STARTED, this); + }).catch((e) => { + audioManager.removePlaying(player); + }); + audioManager.addPlaying(player); + } } /** @@ -355,10 +376,7 @@ export class AudioSource extends Component { this._operationsBeforeLoading.push('pause'); return; } - const player = this._player; - this._player?.pause().then(() => { - audioManager.removePlaying(player!); - }).catch((e) => {}); + this._player?.pause().catch((e) => {}); } /** @@ -372,10 +390,10 @@ export class AudioSource extends Component { this._operationsBeforeLoading.push('stop'); return; } - const player = this._player; - this._player?.stop().then(() => { - audioManager.removePlaying(player!); - }).catch((e) => {}); + if (this._player) { + this._player.stop().catch((e) => {}); + audioManager.removePlaying(this._player); + } } /** @@ -391,18 +409,22 @@ export class AudioSource extends Component { console.error('Invalid audio clip'); return; } + let player: OneShotAudio; AudioPlayer.loadOneShotAudio(clip._nativeAsset.url, this._volume * volumeScale, { audioLoadMode: clip.loadMode, }).then((oneShotAudio) => { + player = oneShotAudio; audioManager.discardOnePlayingIfNeeded(); - oneShotAudio.onPlay = (): void => { - audioManager.addPlaying(oneShotAudio); - }; oneShotAudio.onEnd = (): void => { audioManager.removePlaying(oneShotAudio); }; oneShotAudio.play(); - }).catch((e): void => {}); + audioManager.addPlaying(oneShotAudio); + }).catch((e): void => { + if (player) { + audioManager.removePlaying(player); + } + }); } protected _syncStates (): void { From 839a086ecadeaccecf9f2589e1d5da7453dee6d7 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Wed, 19 Jul 2023 10:38:59 +0800 Subject: [PATCH 051/232] Add smallestScreenSize to Manifest.xml (#15763) --- templates/android/template/app/AndroidManifest.xml | 4 ++-- templates/android/template/instantapp/AndroidManifest.xml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/templates/android/template/app/AndroidManifest.xml b/templates/android/template/app/AndroidManifest.xml index 7aeabfd8f3c..a85bb7ca777 100644 --- a/templates/android/template/app/AndroidManifest.xml +++ b/templates/android/template/app/AndroidManifest.xml @@ -20,7 +20,7 @@ diff --git a/templates/android/template/instantapp/AndroidManifest.xml b/templates/android/template/instantapp/AndroidManifest.xml index 5aee933752e..0216ac9da8f 100644 --- a/templates/android/template/instantapp/AndroidManifest.xml +++ b/templates/android/template/instantapp/AndroidManifest.xml @@ -25,7 +25,7 @@ From 41304cfbd13cf65b49adc2d0ea838eff4c0f64f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 19 Jul 2023 17:46:17 +0800 Subject: [PATCH 052/232] fix setter for node.siblingIndex (#15776) --- cocos/scene-graph/node.jsb.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos/scene-graph/node.jsb.ts b/cocos/scene-graph/node.jsb.ts index db1a53c5b5c..15f31c4beee 100644 --- a/cocos/scene-graph/node.jsb.ts +++ b/cocos/scene-graph/node.jsb.ts @@ -1012,7 +1012,7 @@ Object.defineProperty(nodeProto, '_siblingIndex', { return this._sharedInt32Arr[0]; // Int32, 0: siblingIndex }, set(v) { - this.setSiblingIndex(v); + this._sharedInt32Arr[0] = v; }, }); @@ -1024,10 +1024,11 @@ Object.defineProperty(nodeProto, 'siblingIndex', { return this._sharedInt32Arr[0]; // Int32, 0: siblingIndex }, set(v) { - this.setSiblingIndex(v); + this._sharedInt32Arr[0] = v; }, }); +// note: setSiblingIndex is a JSB function, DO NOT override it nodeProto.getSiblingIndex = function getSiblingIndex() { return this._sharedInt32Arr[0]; // Int32, 0: siblingIndex }; From 9ce02b54aa6bf54016c5fc4ccbb4f47004e4696a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 20 Jul 2023 10:21:41 +0800 Subject: [PATCH 053/232] use boost-bcp to reduce external size (#15770) --- native/utils/clear-platform.js | 293 ++++++++++- package-lock.json | 905 +++++++++++++++++++-------------- package.json | 4 + 3 files changed, 806 insertions(+), 396 deletions(-) diff --git a/native/utils/clear-platform.js b/native/utils/clear-platform.js index b034dd2113a..0cba7d8934e 100644 --- a/native/utils/clear-platform.js +++ b/native/utils/clear-platform.js @@ -1,8 +1,17 @@ 'use strict'; +// @ts-check + const chalk = require('chalk'); const path = require("path"); const fs = require('fs-extra'); +const tar = require('tar'); +const zlib = require('zlib'); +const axios = require('axios'); +const ProgressBar = require('progress'); +const os = require('os'); +const child_process = require('child_process'); +const fetch = require('node-fetch'); // usage: npm run clear-platform let externalDir = path.join(__dirname, "../external"); @@ -13,13 +22,22 @@ let winUsefulDirs = ['android', 'cmake', 'emscripten', 'ohos', 'sources', 'win64 let linuxUsefulDirs = ['android', 'cmake', 'emscripten', 'linux', 'ohos', 'sources']; let allDirs = []; +['log', 'warn', 'error', 'info'].forEach(field => { + const oldFn = console[field]; + console[field] = function (...args) { + oldFn.apply(this, [`[clear-platform.js:${field}] `, ...args]); + }; +}); + + main(); -function main() { +async function main() { readDirectory(externalDir, allDirs); console.log(chalk.green(`==== current exists 3rd-libs directories ====`)); console.log(allDirs); cleanPlatform(process.platform); + await minimizeBoost(); } function readDirectory(path, filesList) { @@ -52,7 +70,7 @@ function cleanPlatform(platform) { if (winUselessDirs.length > 0) { console.log(chalk.magenta(`==== Remove win32 useless 3rd-libs ====`)); console.log(winUselessDirs); - for (let i = 0; i < winUselessDirs.length; i++) { + for (let i = 0; i < winUselessDirs.length; i++) { let clearDirectory = path.join(externalDir, winUselessDirs[i]); console.log(` ${chalk.green('Remove directory: ')} ${clearDirectory}`); ensureRemove(clearDirectory); @@ -63,7 +81,7 @@ function cleanPlatform(platform) { } else if (platform === 'linux') { // linux let linuxUselessDirs = getArrDiff(allDirs, linuxUsefulDirs); - if (linuxUselessDirs.length > 0) { + if (linuxUselessDirs.length > 0) { console.log(chalk.magenta(`==== Remove linux useless 3rd-libs ====`)); console.log(linuxUselessDirs); for (let i = 0; i < linuxUselessDirs.length; i++) { @@ -99,7 +117,272 @@ function ensureRemove(clearDirectory) { } function getArrDiff(arr1, arr2) { - return arr1.concat(arr2).filter(function(v, i, arr) { - return arr.indexOf(v) === arr.lastIndexOf(v); + return arr1.concat(arr2).filter(function (v, i, arr) { + return arr.indexOf(v) === arr.lastIndexOf(v); + }); +} + +function execName(fn, winPostFix = '.exe', linuxPosFix = '') { + return os.platform() === 'win32' ? fn + winPostFix : fn + linuxPosFix; +} + +async function runCommand(dir, cmd, ...args) { + console.log(`Exec ${cmd} with [${args.join(', ')}]`); + return new Promise((resolve, reject) => { + const child = child_process.spawn(cmd, args, { + cwd: dir, + shell: true, + }); + child.stdout.on('data', (data) => { + console.log(data.toString('utf8')); + }); + child.stderr.on('data', (data) => { + console.error(data.toString('utf8')); + }); + child.on('error', (data) => { + console.log(`Error:`); + console.error(data.toString('utf8')); + }); + child.on('close', (code) => { + if (code == 0) { + return resolve(); + } + console.error(`Command ${cmd} exited with code ${code}`) + reject(new Error(`Command ${cmd} exited with code ${code}`)); + }) }); } + +async function filterFiles(root, tstFn) { + const all = []; + const walk = async (dir) => { + const st = fs.statSync(dir); + if (st.isDirectory()) { + const files = await fs.readdir(dir); + const sub = []; + for (let f of files) { + if (f.startsWith('.')) continue; + const p = path.join(dir, f); + if (tstFn(p, true)) sub.push(walk(p)); + } + await Promise.all(sub); + } else { + if (tstFn(dir, false)) all.push(dir); + } + } + await walk(root); + return all; +} + +async function batcher(array, batchSize, fn) { + for (let i = 0, l = array.length; i < l; i += batchSize) { + await Promise.all(array.slice(i, i + batchSize).map(fn)) + } +} + +async function minimizeBoost() { + const BOOST_VERSION = [1, 78, 0] + const BOOST_VERSION_DOTTED = BOOST_VERSION.join('.'); + const BOOST_VERSION_UNDERSCORE = BOOST_VERSION.join('_'); + const BOOST_ZIP_FILE = `boost_${BOOST_VERSION_UNDERSCORE}.tar.gz`; + const EXTERNAL_SOURCE_DIR = path.join(__dirname, '..', 'external', 'sources'); + const BOOST_DOWNLOAD = path.join(EXTERNAL_SOURCE_DIR, 'boost-download'); + const BOOST_ORIG_PATH = path.join(EXTERNAL_SOURCE_DIR, 'boost'); + const BOOST_DEST = path.join(EXTERNAL_SOURCE_DIR, 'boost-minimized'); + const BOOST_DECOMPRESSED_PATH = path.join(BOOST_DOWNLOAD, `boost_${BOOST_VERSION_UNDERSCORE}`); + const BOOST_FILE_PATH = path.join(BOOST_DOWNLOAD, BOOST_ZIP_FILE); + const BOOST_URL_REMOTE = `https://jaist.dl.sourceforge.net/project/boost/boost/${BOOST_VERSION_DOTTED}/boost_${BOOST_VERSION_UNDERSCORE}.tar.gz` + const BOOST_URL_LOCAL = `http://ftp.cocos.org/TestBuilds/Editor-3d/tools/boost_${BOOST_VERSION_UNDERSCORE}.tar.gz` + + const BCP_PATH = path.join(BOOST_DECOMPRESSED_PATH, 'dist', 'bin', execName('bcp')); + const ENGINE_ROOT = path.normalize(path.join(__dirname, '../../')); + + let headersUsedByEngine = []; + + const fnCheckDirectories = async () => { + if (!await fs.pathExists(BOOST_DOWNLOAD)) { + await fs.mkdir(BOOST_DOWNLOAD); + } + if (!await fs.pathExists(BOOST_DEST)) { + await fs.mkdir(BOOST_DEST); + } + } + + const fnDownloadWithAxios = async (url, dstUrl) => { + let bar = null; + const dstFile = fs.createWriteStream(dstUrl); + return new Promise((resolve, reject) => { + axios.get(url, { responseType: 'stream' }) + .then((res) => { + // console.log(res.headers); + const total = res.headers['Content-Length'] || res.headers['content-length']; + bar = new ProgressBar('Downloading [:bar] :percent :etas', { + complete: '=', + incomplete: ' ', + width: 40, + total: parseInt(total) + }); + res.data.pipe(dstFile); + res.data.on('data', (chunk) => { bar.tick(chunk.length); }); + res.data.on('end', () => { + console.log(` Download Finished`); + resolve(); + }); + }).catch(err => reject(err)); + }); + }; + + const fnDownloadWithCurl = async (url, dstUrl) => { + await runCommand(BOOST_DOWNLOAD, 'curl', url, '-o', `"${dstUrl}"`) + } + + const rm = async (file) => { + const st = fs.statSync(file); + if (st.isDirectory()) { + const files = (await fs.readdir(file)).filter(x => x !== '.' && x !== '..').map(x => path.join(file, x)); + await Promise.all(files.map(x => rm(x))); + await fs.rmdir(file) + } else { + await fs.unlink(file); + } + }; + + const fnDownloadBoost = async () => { + const targetExist = await fs.pathExists(BOOST_FILE_PATH); + if (!targetExist) { + let boostURL; + console.log(`Testing local url: ${BOOST_URL_LOCAL}`); + try { + const FETCH_TIMEOUTOUT = 3000; + const testLocal = await Promise.race( [fetch(BOOST_URL_LOCAL), new Promise((_, r)=> { + setTimeout(()=> r(new Error('Request timed out')), FETCH_TIMEOUTOUT); + })]); + if (testLocal.ok) { + console.log(` Use ${BOOST_URL_LOCAL}!`); + boostURL = BOOST_URL_LOCAL; + } else { + console.log(` Failed on error code, use ${BOOST_URL_REMOTE}!`); + boostURL = BOOST_URL_REMOTE; + } + } catch (e) { + console.error(e); + console.log(` Failed on exception, use ${BOOST_URL_REMOTE}!`); + boostURL = BOOST_URL_REMOTE; + } + console.log(` downloading ${boostURL}\n to ${BOOST_FILE_PATH}`); + + await fnDownloadWithAxios(boostURL, BOOST_FILE_PATH); + // await fnDownloadWithCurl(BOOST_URL, BOOST_FILE_PATH); + } else { + console.log(`Skip downloading, file ${BOOST_FILE_PATH} exists.`); + } + }; + + const fnDecompressBoost = async () => { + if (await fs.pathExists(BOOST_DECOMPRESSED_PATH)) { + console.log(` Folder ${BOOST_DECOMPRESSED_PATH} exists, skip decompressing...`); + return; + } + console.log(`Decompressing file ${BOOST_FILE_PATH}`); + const srcStream = fs.createReadStream(BOOST_FILE_PATH); + const st = fs.statSync(BOOST_FILE_PATH); + let bar; + return new Promise((resolve, reject) => { + bar = new ProgressBar(' Extracting [:bar] :percent :etas', { + complete: '=', + incomplete: ' ', + width: 40, + total: st.size + }); + srcStream.on('data', chunk => bar.tick(chunk.length)) + .pipe(zlib.createGunzip()) + .pipe(tar.extract({ cwd: BOOST_DOWNLOAD })) + .on('entry', (entry) => { + // console.log(` processing ${entry.path}`); + }) + .on('error', err => { + console.error(` decompressing error!`); + reject(err); + }) + .on('end', () => { + console.log(` decompressing done!`); + resolve(); + }); + }); + }; + + const fnCompileBoost = async () => { + if (await fs.pathExists(BCP_PATH)) { + console.log(` File ${BCP_PATH} already exists, skip compilation`); + return; + } + const bootstrap = path.join(BOOST_DECOMPRESSED_PATH, execName('bootstrap', '.bat', '.sh')); + const b2 = path.join(BOOST_DECOMPRESSED_PATH, execName('b2')); + await runCommand(BOOST_DECOMPRESSED_PATH, bootstrap); + await runCommand(BOOST_DECOMPRESSED_PATH, b2, 'headers'); + await runCommand(BOOST_DECOMPRESSED_PATH, b2, 'tools/bcp'); + + if (await fs.pathExists(BCP_PATH)) { + console.log(` Compile bcp.exe successed!`); + } else { + console.error(` Failed to compile bcp.exe, file not found!`) + } + }; + + const fnCollectBoostHeaders = async () => { + console.log(` Analyzing source files...`); + const allSource = await filterFiles(ENGINE_ROOT, (path, isdir) => { + return isdir ? !/native(\\|\/)+external/.test(path) : ['.h', '.hpp', '.cpp', '.mm'].filter(e => path.endsWith(e)).length > 0; + }); + console.log(`${allSource.length} files found!`); + const R = /#include\s+[<"]boost\/([^">]+)/ + const boostHeaders = {}; + await batcher(allSource, 20, async (file) => { + const data = await fs.readFile(file, 'utf8') + const includes = data.split(`\n`).filter(x => x.trim().startsWith("#include")).map(x => x.trim()).filter(x => R.test(x)); + includes.forEach(x => { + const m = x.match(R); + if (m) { + boostHeaders[m[1]] = true; + } + }) + }) + headersUsedByEngine = Object.keys(boostHeaders).sort(); + console.log(` headers: ${headersUsedByEngine.join(', ')}`); + }; + + const fnRunBCP = async () => { + await runCommand(BOOST_DECOMPRESSED_PATH, BCP_PATH, + `--boost="${BOOST_DECOMPRESSED_PATH}"`, + 'graph', /* manually add components here */ + ...headersUsedByEngine, + BOOST_DEST + ); + + if (await fs.pathExists(BOOST_ORIG_PATH)) { + console.log(`Remove old folder ${BOOST_ORIG_PATH}`); + await rm(BOOST_ORIG_PATH); + } + console.log(`Link to minimized boost folder ${BOOST_DEST}`); + await fs.rename(path.join(BOOST_DEST, 'boost'), BOOST_ORIG_PATH); + if (await fs.pathExists(BOOST_DEST)) { + console.log(`Remove folder ${BOOST_DEST}`); + await rm(BOOST_DEST); + } + }; + + const fnCleanUp = async () => { + if (await fs.pathExists(BOOST_DOWNLOAD)) { + await rm(BOOST_DOWNLOAD); + } + } + + + await fnCheckDirectories(); + await fnDownloadBoost(); + await fnDecompressBoost(); + await fnCompileBoost(); + await fnCollectBoostHeaders(); + await fnRunBCP(); + await fnCleanUp(); // skip this step when debugging +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 0fa7f37bda9..b276c5e8771 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1122,7 +1122,7 @@ }, "@babel/plugin-syntax-async-generators": { "version": "7.8.4", - "resolved": "https://registry.nlark.com/@babel/plugin-syntax-async-generators/download/@babel/plugin-syntax-async-generators-7.8.4.tgz", + "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-async-generators/download/@babel/plugin-syntax-async-generators-7.8.4.tgz", "integrity": "sha1-qYP7Gusuw/btBCohD2QOkOeG/g0=", "dev": true, "requires": { @@ -1174,7 +1174,7 @@ }, "@babel/plugin-syntax-dynamic-import": { "version": "7.8.3", - "resolved": "https://registry.nlark.com/@babel/plugin-syntax-dynamic-import/download/@babel/plugin-syntax-dynamic-import-7.8.3.tgz?cache=0&sync_timestamp=1618847125283&other_urls=https%3A%2F%2Fregistry.nlark.com%2F%40babel%2Fplugin-syntax-dynamic-import%2Fdownload%2F%40babel%2Fplugin-syntax-dynamic-import-7.8.3.tgz", + "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-dynamic-import/download/@babel/plugin-syntax-dynamic-import-7.8.3.tgz", "integrity": "sha1-Yr+Ysto80h1iYVT8lu5bPLaOrLM=", "dev": true, "requires": { @@ -1217,7 +1217,7 @@ }, "@babel/plugin-syntax-json-strings": { "version": "7.8.3", - "resolved": "https://registry.nlark.com/@babel/plugin-syntax-json-strings/download/@babel/plugin-syntax-json-strings-7.8.3.tgz", + "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-json-strings/download/@babel/plugin-syntax-json-strings-7.8.3.tgz", "integrity": "sha1-AcohtmjNghjJ5kDLbdiMVBKyyWo=", "dev": true, "requires": { @@ -1226,7 +1226,7 @@ }, "@babel/plugin-syntax-logical-assignment-operators": { "version": "7.10.4", - "resolved": "https://registry.nlark.com/@babel/plugin-syntax-logical-assignment-operators/download/@babel/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-logical-assignment-operators/download/@babel/plugin-syntax-logical-assignment-operators-7.10.4.tgz", "integrity": "sha1-ypHvRjA1MESLkGZSusLp/plB9pk=", "dev": true, "requires": { @@ -1269,7 +1269,7 @@ }, "@babel/plugin-syntax-object-rest-spread": { "version": "7.8.3", - "resolved": "https://registry.nlark.com/@babel/plugin-syntax-object-rest-spread/download/@babel/plugin-syntax-object-rest-spread-7.8.3.tgz", + "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-object-rest-spread/download/@babel/plugin-syntax-object-rest-spread-7.8.3.tgz", "integrity": "sha1-YOIl7cvZimQDMqLnLdPmbxr1WHE=", "dev": true, "requires": { @@ -1287,7 +1287,7 @@ }, "@babel/plugin-syntax-optional-chaining": { "version": "7.8.3", - "resolved": "https://registry.nlark.com/@babel/plugin-syntax-optional-chaining/download/@babel/plugin-syntax-optional-chaining-7.8.3.tgz", + "resolved": "https://registry.npm.taobao.org/@babel/plugin-syntax-optional-chaining/download/@babel/plugin-syntax-optional-chaining-7.8.3.tgz", "integrity": "sha1-T2nCq5UWfgGAzVM2YT+MV4j31Io=", "dev": true, "requires": { @@ -1647,7 +1647,7 @@ }, "@babel/preset-env": { "version": "7.8.7", - "resolved": "https://registry.npmmirror.com/@babel/preset-env/download/@babel/preset-env-7.8.7.tgz?cache=0&sync_timestamp=1637103615805&other_urls=https%3A%2F%2Fregistry.npmmirror.com%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?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", "integrity": "sha1-H8fYnH910tcMK2do3mwuBJs8uds=", "dev": true, "requires": { @@ -1823,7 +1823,7 @@ }, "@cocos/box2d": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/@cocos/box2d/download/@cocos/box2d-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/@cocos/box2d/download/@cocos/box2d-1.0.1.tgz", "integrity": "sha1-Fc2lzPxRCCt91tNoo+S55IXS5To=", "requires": { "@types/systemjs": "^0.20.6" @@ -1863,13 +1863,13 @@ "dependencies": { "ansi-regex": { "version": "5.0.1", - "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { @@ -1878,7 +1878,7 @@ }, "cliui": { "version": "6.0.0", - "resolved": "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", "dev": true, "requires": { @@ -1889,7 +1889,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { @@ -1898,13 +1898,13 @@ }, "color-name": { "version": "1.1.4", - "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "find-up": { "version": "4.1.0", - "resolved": "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { @@ -1914,7 +1914,7 @@ }, "fs-extra": { "version": "8.1.0", - "resolved": "https://registry.npmmirror.com/fs-extra/-/fs-extra-8.1.0.tgz", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", "dev": true, "requires": { @@ -1925,7 +1925,7 @@ }, "get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, @@ -1940,13 +1940,13 @@ }, "is-fullwidth-code-point": { "version": "3.0.0", - "resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "locate-path": { "version": "5.0.0", - "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { @@ -1955,7 +1955,7 @@ }, "p-locate": { "version": "4.1.0", - "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { @@ -1964,13 +1964,13 @@ }, "path-exists": { "version": "4.0.0", - "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "require-main-filename": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, @@ -1996,7 +1996,7 @@ }, "string-width": { "version": "4.2.3", - "resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "requires": { @@ -2007,7 +2007,7 @@ }, "strip-ansi": { "version": "6.0.1", - "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { @@ -2022,7 +2022,7 @@ }, "wrap-ansi": { "version": "6.2.0", - "resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "requires": { @@ -2033,13 +2033,13 @@ }, "y18n": { "version": "4.0.3", - "resolved": "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true }, "yargs": { "version": "15.4.1", - "resolved": "https://registry.npmmirror.com/yargs/-/yargs-15.4.1.tgz", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "requires": { @@ -2058,7 +2058,7 @@ }, "yargs-parser": { "version": "18.1.3", - "resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-18.1.3.tgz", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", "dev": true, "requires": { @@ -3585,7 +3585,7 @@ }, "type-fest": { "version": "0.20.2", - "resolved": "https://registry.npmmirror.com/type-fest/-/type-fest-0.20.2.tgz", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true } @@ -5845,7 +5845,7 @@ }, "@jest/types": { "version": "24.9.0", - "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-24.9.0.tgz", + "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-24.9.0.tgz", "integrity": "sha1-Y8smy3UA0Gnlo4lEGnxqtekJ/Fk=", "dev": true, "requires": { @@ -5876,7 +5876,7 @@ }, "@jridgewell/resolve-uri": { "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.0.7.tgz", + "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.0.7.tgz", "integrity": "sha512-8cXDaBBHOr2pQ7j77Y6Vp5VDT2sIqWyWQ56TjEq4ih/a4iST3dItRe8Q9fp0rrIl9DoKhWQtUQz/YpOxLkXbNA==" }, "@jridgewell/set-array": { @@ -5909,12 +5909,12 @@ }, "@jridgewell/sourcemap-codec": { "version": "1.4.13", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.13.tgz", + "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.13.tgz", "integrity": "sha512-GryiOJmNcWbovBxTfZSF71V/mXbgcV3MewDe3kIMCLyIh5e7SKAeUZs+rMnJ8jkMolZ/4/VsdBmMrw3l+VdZ3w==" }, "@jridgewell/trace-mapping": { "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.13.tgz", + "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.13.tgz", "integrity": "sha512-o1xbKhp9qnIAoHJSWd6KlCZfqslL4valSF81H8ImioOAxluWYWOpWkpyktY2vnt4tbrX9XYaxovq6cgowaJp2w==", "requires": { "@jridgewell/resolve-uri": "^3.0.3", @@ -6172,7 +6172,7 @@ }, "@types/fs-extra": { "version": "5.1.0", - "resolved": "https://registry.npmmirror.com/@types/fs-extra/download/@types/fs-extra-5.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/@types/fs-extra/download/@types/fs-extra-5.1.0.tgz", "integrity": "sha1-KjJe+XkBUEo4KHGMOQ00uEJqEKE=", "dev": true, "requires": { @@ -6205,7 +6205,7 @@ }, "@types/istanbul-reports": { "version": "1.1.2", - "resolved": "https://registry.npmmirror.com/@types/istanbul-reports/download/@types/istanbul-reports-1.1.2.tgz?cache=0&sync_timestamp=1637266160892&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fistanbul-reports%2Fdownload%2F%40types%2Fistanbul-reports-1.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/@types/istanbul-reports/download/@types/istanbul-reports-1.1.2.tgz?cache=0&sync_timestamp=1613379043554&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Fistanbul-reports%2Fdownload%2F%40types%2Fistanbul-reports-1.1.2.tgz", "integrity": "sha1-6HXMaJ5HvOVJ7IHz315vbxHPrrI=", "dev": true, "requires": { @@ -6215,7 +6215,7 @@ }, "@types/jest": { "version": "24.9.1", - "resolved": "https://registry.npmmirror.com/@types/jest/download/@types/jest-24.9.1.tgz", + "resolved": "https://registry.npm.taobao.org/@types/jest/download/@types/jest-24.9.1.tgz?cache=0&sync_timestamp=1616695463771&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Fjest%2Fdownload%2F%40types%2Fjest-24.9.1.tgz", "integrity": "sha1-Arr5Vzx48bmXSl82d4s2aqd71TQ=", "dev": true, "requires": { @@ -6892,7 +6892,7 @@ }, "abab": { "version": "2.0.6", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", + "resolved": "https://registry.npmmirror.com/abab/-/abab-2.0.6.tgz", "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", "dev": true }, @@ -6904,7 +6904,7 @@ }, "acorn-globals": { "version": "6.0.0", - "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz", + "resolved": "https://registry.npmmirror.com/acorn-globals/-/acorn-globals-6.0.0.tgz", "integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==", "dev": true, "requires": { @@ -6930,13 +6930,13 @@ }, "acorn-walk": { "version": "7.2.0", - "resolved": "https://registry.nlark.com/acorn-walk/download/acorn-walk-7.2.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.nlark.com%2Facorn-walk%2Fdownload%2Facorn-walk-7.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/acorn-walk/download/acorn-walk-7.2.0.tgz", "integrity": "sha1-DeiJpgEgOQmw++B7iTjcIdLpZ7w=", "dev": true }, "agent-base": { "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz", "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", "dev": true, "requires": { @@ -6999,7 +6999,7 @@ }, "ansi-styles": { "version": "3.2.1", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-3.2.1.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-3.2.1.tgz", "integrity": "sha1-QfuyAkPlCxK+DwS43tvwdSDOhB0=", "requires": { "color-convert": "^1.9.0" @@ -7007,13 +7007,13 @@ }, "ansi-wrap": { "version": "0.1.0", - "resolved": "https://registry.nlark.com/ansi-wrap/download/ansi-wrap-0.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-wrap/download/ansi-wrap-0.1.0.tgz", "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", "dev": true }, "anymatch": { "version": "2.0.0", - "resolved": "https://registry.nlark.com/anymatch/download/anymatch-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/anymatch/download/anymatch-2.0.0.tgz", "integrity": "sha1-vLJLTzeTTZqnrBe0ra+J58du8us=", "dev": true, "requires": { @@ -7032,7 +7032,7 @@ }, "archy": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/archy/download/archy-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/archy/download/archy-1.0.0.tgz", "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", "dev": true }, @@ -7047,7 +7047,7 @@ }, "arr-diff": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/arr-diff/download/arr-diff-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/arr-diff/download/arr-diff-4.0.0.tgz", "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", "dev": true }, @@ -7062,13 +7062,13 @@ }, "arr-flatten": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/arr-flatten/download/arr-flatten-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/arr-flatten/download/arr-flatten-1.1.0.tgz", "integrity": "sha1-NgSLv/TntH4TZkQxbJlmnqWukfE=", "dev": true }, "arr-map": { "version": "2.0.2", - "resolved": "https://registry.nlark.com/arr-map/download/arr-map-2.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/arr-map/download/arr-map-2.0.2.tgz", "integrity": "sha1-Onc0X/wc814qkYJWAfnljy4kysQ=", "dev": true, "requires": { @@ -7077,7 +7077,7 @@ }, "arr-union": { "version": "3.1.0", - "resolved": "https://registry.nlark.com/arr-union/download/arr-union-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/arr-union/download/arr-union-3.1.0.tgz", "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", "dev": true }, @@ -7142,7 +7142,7 @@ "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -7242,12 +7242,12 @@ }, "array-union": { "version": "2.1.0", - "resolved": "https://registry.npm.taobao.org/array-union/download/array-union-2.1.0.tgz?cache=0&sync_timestamp=1614624262896&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Farray-union%2Fdownload%2Farray-union-2.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/array-union/download/array-union-2.1.0.tgz", "integrity": "sha1-t5hCCtvrHego2ErNii4j0+/oXo0=" }, "array-unique": { "version": "0.3.2", - "resolved": "https://registry.nlark.com/array-unique/download/array-unique-0.3.2.tgz", + "resolved": "https://registry.npm.taobao.org/array-unique/download/array-unique-0.3.2.tgz", "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "dev": true }, @@ -7431,13 +7431,13 @@ }, "async-each": { "version": "1.0.3", - "resolved": "https://registry.nlark.com/async-each/download/async-each-1.0.3.tgz", + "resolved": "https://registry.npm.taobao.org/async-each/download/async-each-1.0.3.tgz", "integrity": "sha1-tyfb+H12UWAvBvTUrDh/R9kbDL8=", "dev": true }, "async-settle": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/async-settle/download/async-settle-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/async-settle/download/async-settle-1.0.0.tgz", "integrity": "sha1-HQqRS7Aldb7IqPOnTlCA9yssDGs=", "dev": true, "requires": { @@ -7446,13 +7446,13 @@ }, "asynckit": { "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "resolved": "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "dev": true }, "atob": { "version": "2.1.2", - "resolved": "https://registry.nlark.com/atob/download/atob-2.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/atob/download/atob-2.1.2.tgz", "integrity": "sha1-bZUX654DDSQ2ZmZR6GvZ9vE1M8k=", "dev": true }, @@ -7462,6 +7462,25 @@ "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", "dev": true }, + "axios": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.4.0.tgz", + "integrity": "sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==", + "dev": true, + "requires": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + }, + "dependencies": { + "follow-redirects": { + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", + "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", + "dev": true + } + } + }, "babel-jest": { "version": "28.1.2", "resolved": "https://registry.npmmirror.com/babel-jest/-/babel-jest-28.1.2.tgz", @@ -7616,7 +7635,7 @@ }, "bach": { "version": "1.2.0", - "resolved": "https://registry.npmmirror.com/bach/download/bach-1.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/bach/download/bach-1.2.0.tgz", "integrity": "sha1-Szzpa/JxNPeaG0FKUcFONMO9mIA=", "dev": true, "requires": { @@ -7662,7 +7681,7 @@ }, "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -7671,7 +7690,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -7699,13 +7718,13 @@ }, "basic-auth": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/basic-auth/download/basic-auth-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/basic-auth/download/basic-auth-1.1.0.tgz", "integrity": "sha1-RSIe5Cn37h5QNb4/UVM/HN/SmIQ=", "dev": true }, "binary-extensions": { "version": "1.13.1", - "resolved": "https://registry.nlark.com/binary-extensions/download/binary-extensions-1.13.1.tgz", + "resolved": "https://registry.npm.taobao.org/binary-extensions/download/binary-extensions-1.13.1.tgz", "integrity": "sha1-WYr+VHVbKGilMw0q/51Ou1Mgm2U=", "dev": true }, @@ -7727,7 +7746,7 @@ }, "brace-expansion": { "version": "1.1.11", - "resolved": "https://registry.nlark.com/brace-expansion/download/brace-expansion-1.1.11.tgz", + "resolved": "https://registry.npm.taobao.org/brace-expansion/download/brace-expansion-1.1.11.tgz", "integrity": "sha1-PH/L9SnYcibz0vUrlm/1Jx60Qd0=", "requires": { "balanced-match": "^1.0.0", @@ -7785,7 +7804,7 @@ }, "browser-process-hrtime": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, @@ -8049,7 +8068,7 @@ }, "bs-logger": { "version": "0.2.6", - "resolved": "https://registry.nlark.com/bs-logger/download/bs-logger-0.2.6.tgz", + "resolved": "https://registry.npm.taobao.org/bs-logger/download/bs-logger-0.2.6.tgz", "integrity": "sha1-6302UwenLPl0zGzadraDVK0za9g=", "dev": true, "requires": { @@ -8113,7 +8132,7 @@ }, "cache-base": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/cache-base/download/cache-base-1.0.1.tgz?cache=0&sync_timestamp=1636237266442&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fcache-base%2Fdownload%2Fcache-base-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/cache-base/download/cache-base-1.0.1.tgz", "integrity": "sha1-Cn9GQWgxyLZi7jb+TnxZ129marI=", "dev": true, "requires": { @@ -8146,12 +8165,12 @@ }, "callsites": { "version": "3.1.0", - "resolved": "https://registry.nlark.com/callsites/download/callsites-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/callsites/download/callsites-3.1.0.tgz", "integrity": "sha1-s2MKvYlDQy9Us/BRkjjjPNffL3M=" }, "camelcase": { "version": "5.3.1", - "resolved": "https://registry.npmmirror.com/camelcase/download/camelcase-5.3.1.tgz?cache=0&sync_timestamp=1636945130104&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fcamelcase%2Fdownload%2Fcamelcase-5.3.1.tgz", + "resolved": "https://registry.npm.taobao.org/camelcase/download/camelcase-5.3.1.tgz", "integrity": "sha1-48mzFWnhBoEd8kL3FXJaH0xJQyA=", "dev": true }, @@ -8163,7 +8182,7 @@ }, "chalk": { "version": "2.4.2", - "resolved": "https://registry.npmmirror.com/chalk/download/chalk-2.4.2.tgz", + "resolved": "https://registry.npm.taobao.org/chalk/download/chalk-2.4.2.tgz?cache=0&sync_timestamp=1573282918610&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fchalk%2Fdownload%2Fchalk-2.4.2.tgz", "integrity": "sha1-zUJUFnelQzPPVBpJEIwUMrRMlCQ=", "requires": { "ansi-styles": "^3.2.1", @@ -8180,12 +8199,12 @@ "child_process": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/child_process/-/child_process-1.0.2.tgz", - "integrity": "sha512-Wmza/JzL0SiWz7kl6MhIKT5ceIlnFPJX+lwUGj7Clhy5MMldsSoJR0+uvRzOS5Kv45Mq7t1PoE8TsOA9bzvb6g==", + "integrity": "sha1-sffn/HPSXn/R1FWtyU4UODAYK1o=", "dev": true }, "chokidar": { "version": "2.1.8", - "resolved": "https://registry.npmmirror.com/chokidar/download/chokidar-2.1.8.tgz", + "resolved": "https://registry.npm.taobao.org/chokidar/download/chokidar-2.1.8.tgz", "integrity": "sha1-gEs6e2qZNYw8XGHnHYco8EHP+Rc=", "dev": true, "requires": { @@ -8205,7 +8224,7 @@ "dependencies": { "glob-parent": { "version": "3.1.0", - "resolved": "https://registry.npmmirror.com/glob-parent/download/glob-parent-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/glob-parent/download/glob-parent-3.1.0.tgz?cache=0&sync_timestamp=1569108917227&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fglob-parent%2Fdownload%2Fglob-parent-3.1.0.tgz", "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", "dev": true, "requires": { @@ -8215,7 +8234,7 @@ "dependencies": { "is-glob": { "version": "3.1.0", - "resolved": "https://registry.npmmirror.com/is-glob/download/is-glob-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-3.1.0.tgz", "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { @@ -8241,9 +8260,15 @@ } } }, + "chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "dev": true + }, "ci-info": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/ci-info/download/ci-info-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/ci-info/download/ci-info-2.0.0.tgz", "integrity": "sha1-Z6npZL4xpR4V5QENWObxKDQAL0Y=", "dev": true }, @@ -8265,7 +8290,7 @@ }, "class-utils": { "version": "0.3.6", - "resolved": "https://registry.nlark.com/class-utils/download/class-utils-0.3.6.tgz", + "resolved": "https://registry.npm.taobao.org/class-utils/download/class-utils-0.3.6.tgz", "integrity": "sha1-+TNprouafOAv1B+q0MqDAzGQxGM=", "dev": true, "requires": { @@ -8305,7 +8330,7 @@ }, "clone": { "version": "2.1.2", - "resolved": "https://registry.nlark.com/clone/download/clone-2.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/clone/download/clone-2.1.2.tgz", "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", "dev": true }, @@ -8340,7 +8365,7 @@ }, "code-point-at": { "version": "1.1.0", - "resolved": "https://registry.npmmirror.com/code-point-at/download/code-point-at-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/code-point-at/download/code-point-at-1.1.0.tgz", "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", "dev": true }, @@ -8352,7 +8377,7 @@ }, "collection-map": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/collection-map/download/collection-map-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/collection-map/download/collection-map-1.0.0.tgz", "integrity": "sha1-rqDwb40mx4DCt1SUOFVEsiVa8Yw=", "dev": true, "requires": { @@ -8373,7 +8398,7 @@ }, "color-convert": { "version": "1.9.3", - "resolved": "https://registry.nlark.com/color-convert/download/color-convert-1.9.3.tgz", + "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-1.9.3.tgz", "integrity": "sha1-u3GFBpDh8TZWfeYp0tVHHe2kweg=", "requires": { "color-name": "1.1.3" @@ -8424,7 +8449,7 @@ }, "combined-stream": { "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "dev": true, "requires": { @@ -8433,19 +8458,19 @@ }, "commander": { "version": "2.20.3", - "resolved": "https://registry.npmmirror.com/commander/download/commander-2.20.3.tgz?cache=0&sync_timestamp=1634886357672&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fcommander%2Fdownload%2Fcommander-2.20.3.tgz", + "resolved": "https://registry.npm.taobao.org/commander/download/commander-2.20.3.tgz", "integrity": "sha1-/UhehMA+tIgcIHIrpIA16FMa6zM=", "dev": true }, "commondir": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/commondir/-/commondir-1.0.1.tgz", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", "dev": true }, "component-emitter": { "version": "1.3.0", - "resolved": "https://registry.nlark.com/component-emitter/download/component-emitter-1.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/component-emitter/download/component-emitter-1.3.0.tgz", "integrity": "sha1-FuQHD7qK4ptnnyIVhT7hgasuq8A=", "dev": true }, @@ -8456,7 +8481,7 @@ }, "concat-stream": { "version": "1.6.2", - "resolved": "https://registry.nlark.com/concat-stream/download/concat-stream-1.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/concat-stream/download/concat-stream-1.6.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fconcat-stream%2Fdownload%2Fconcat-stream-1.6.2.tgz", "integrity": "sha1-kEvfGUzTEi/Gdcd/xKw9T/D9GjQ=", "dev": true, "requires": { @@ -8494,7 +8519,7 @@ }, "copy-descriptor": { "version": "0.1.1", - "resolved": "https://registry.nlark.com/copy-descriptor/download/copy-descriptor-0.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/copy-descriptor/download/copy-descriptor-0.1.1.tgz", "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", "dev": true }, @@ -8528,7 +8553,7 @@ "dependencies": { "semver": { "version": "7.0.0", - "resolved": "https://registry.nlark.com/semver/download/semver-7.0.0.tgz?cache=0&sync_timestamp=1618846864940&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsemver%2Fdownload%2Fsemver-7.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/semver/download/semver-7.0.0.tgz?cache=0&sync_timestamp=1581458063470&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsemver%2Fdownload%2Fsemver-7.0.0.tgz", "integrity": "sha1-XzyjV2HkfgWyBsba/yz4FPAxa44=", "dev": true } @@ -8536,13 +8561,13 @@ }, "core-util-is": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/core-util-is/download/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", "dev": true }, "corser": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/corser/download/corser-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/corser/download/corser-2.0.1.tgz", "integrity": "sha1-jtolLsqrWEDc2XXOuQ2TcMgZ/4c=", "dev": true }, @@ -8636,7 +8661,7 @@ }, "cssstyle": { "version": "2.3.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", + "resolved": "https://registry.npmmirror.com/cssstyle/-/cssstyle-2.3.0.tgz", "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", "dev": true, "requires": { @@ -8645,7 +8670,7 @@ "dependencies": { "cssom": { "version": "0.3.8", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", + "resolved": "https://registry.npmmirror.com/cssom/-/cssom-0.3.8.tgz", "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", "dev": true } @@ -8683,13 +8708,13 @@ }, "decamelize": { "version": "1.2.0", - "resolved": "https://registry.npmmirror.com/decamelize/download/decamelize-1.2.0.tgz?cache=0&sync_timestamp=1633055760479&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fdecamelize%2Fdownload%2Fdecamelize-1.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/decamelize/download/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, "decimal.js": { "version": "10.3.1", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", + "resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.3.1.tgz", "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==", "dev": true }, @@ -8702,7 +8727,7 @@ "dedent": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=" + "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==" }, "deep-is": { "version": "0.1.3", @@ -8740,7 +8765,7 @@ }, "define-properties": { "version": "1.1.3", - "resolved": "https://registry.nlark.com/define-properties/download/define-properties-1.1.3.tgz?cache=0&sync_timestamp=1618847174317&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fdefine-properties%2Fdownload%2Fdefine-properties-1.1.3.tgz", + "resolved": "https://registry.npm.taobao.org/define-properties/download/define-properties-1.1.3.tgz", "integrity": "sha1-z4jabL7ib+bbcJT2HYcMvYTO6fE=", "dev": true, "requires": { @@ -8759,7 +8784,7 @@ "dependencies": { "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -8768,7 +8793,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -8820,7 +8845,7 @@ }, "delayed-stream": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", "dev": true }, @@ -8879,7 +8904,7 @@ }, "diff-sequences": { "version": "24.9.0", - "resolved": "https://registry.npmmirror.com/diff-sequences/download/diff-sequences-24.9.0.tgz", + "resolved": "https://registry.npm.taobao.org/diff-sequences/download/diff-sequences-24.9.0.tgz?cache=0&sync_timestamp=1579655107286&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fdiff-sequences%2Fdownload%2Fdiff-sequences-24.9.0.tgz", "integrity": "sha1-VxXWJE4qpl9Iu6C8ly2wsLEelbU=", "dev": true }, @@ -8964,7 +8989,7 @@ }, "ecstatic": { "version": "3.3.2", - "resolved": "https://registry.npmmirror.com/ecstatic/download/ecstatic-3.3.2.tgz", + "resolved": "https://registry.npm.taobao.org/ecstatic/download/ecstatic-3.3.2.tgz", "integrity": "sha1-bR3UmBTQBZRoLGUq22YHamnUbEg=", "dev": true, "requires": { @@ -9025,7 +9050,7 @@ }, "error-ex": { "version": "1.3.2", - "resolved": "https://registry.nlark.com/error-ex/download/error-ex-1.3.2.tgz", + "resolved": "https://registry.npm.taobao.org/error-ex/download/error-ex-1.3.2.tgz", "integrity": "sha1-tKxAZIEH/c3PriQvQovqihTU8b8=", "dev": true, "requires": { @@ -9077,7 +9102,7 @@ "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -9252,7 +9277,7 @@ }, "es6-iterator": { "version": "2.0.3", - "resolved": "https://registry.nlark.com/es6-iterator/download/es6-iterator-2.0.3.tgz", + "resolved": "https://registry.npm.taobao.org/es6-iterator/download/es6-iterator-2.0.3.tgz", "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "dev": true, "requires": { @@ -9285,17 +9310,17 @@ }, "escalade": { "version": "3.1.1", - "resolved": "https://registry.npm.taobao.org/escalade/download/escalade-3.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/escalade/download/escalade-3.1.1.tgz?cache=0&sync_timestamp=1602567343144&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fescalade%2Fdownload%2Fescalade-3.1.1.tgz", "integrity": "sha1-2M/ccACWXFoBdLSoLqpcBVJ0LkA=" }, "escape-string-regexp": { "version": "1.0.5", - "resolved": "https://registry.nlark.com/escape-string-regexp/download/escape-string-regexp-1.0.5.tgz", + "resolved": "https://registry.npm.taobao.org/escape-string-regexp/download/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "escodegen": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/escodegen/-/escodegen-2.0.0.tgz", "integrity": "sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw==", "dev": true, "requires": { @@ -9308,13 +9333,13 @@ "dependencies": { "estraverse": { "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "resolved": "https://registry.npmmirror.com/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true }, "source-map": { "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "optional": true @@ -9423,7 +9448,7 @@ }, "chalk": { "version": "4.1.2", - "resolved": "https://registry.npmmirror.com/chalk/-/chalk-4.1.2.tgz", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "requires": { @@ -9433,7 +9458,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { @@ -9442,13 +9467,13 @@ }, "color-name": { "version": "1.1.4", - "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", + "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.npmmirror.com/cross-spawn/-/cross-spawn-7.0.3.tgz", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "requires": { @@ -9468,7 +9493,7 @@ }, "escape-string-regexp": { "version": "4.0.0", - "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", "dev": true }, @@ -9529,7 +9554,7 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, @@ -9544,7 +9569,7 @@ }, "levn": { "version": "0.4.1", - "resolved": "https://registry.npmmirror.com/levn/-/levn-0.4.1.tgz", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "requires": { @@ -9601,19 +9626,19 @@ }, "path-key": { "version": "3.1.1", - "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz", + "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.npmmirror.com/prelude-ls/-/prelude-ls-1.2.1.tgz", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true }, "shebang-command": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "requires": { @@ -9622,7 +9647,7 @@ }, "shebang-regex": { "version": "3.0.0", - "resolved": "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, @@ -9646,7 +9671,7 @@ }, "type-check": { "version": "0.4.0", - "resolved": "https://registry.npmmirror.com/type-check/-/type-check-0.4.0.tgz", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "requires": { @@ -9655,7 +9680,7 @@ }, "type-fest": { "version": "0.20.2", - "resolved": "https://registry.npmmirror.com/type-fest/-/type-fest-0.20.2.tgz", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true } @@ -9744,7 +9769,7 @@ "dependencies": { "debug": { "version": "3.2.7", - "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "requires": { @@ -9775,7 +9800,7 @@ "dependencies": { "debug": { "version": "3.2.7", - "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, "requires": { @@ -9818,7 +9843,7 @@ }, "doctrine": { "version": "2.1.0", - "resolved": "https://registry.npmmirror.com/doctrine/-/doctrine-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", "dev": true, "requires": { @@ -9978,7 +10003,7 @@ }, "execa": { "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/execa/download/execa-1.0.0.tgz?cache=0&sync_timestamp=1637147207309&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fexeca%2Fdownload%2Fexeca-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/execa/download/execa-1.0.0.tgz?cache=0&sync_timestamp=1576749091315&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fexeca%2Fdownload%2Fexeca-1.0.0.tgz", "integrity": "sha1-xiNqW7TfbW8V6I5/AXeYIWdJ3dg=", "dev": true, "requires": { @@ -10014,7 +10039,7 @@ "dependencies": { "debug": { "version": "2.6.9", - "resolved": "https://registry.npmmirror.com/debug/download/debug-2.6.9.tgz", + "resolved": "https://registry.npm.taobao.org/debug/download/debug-2.6.9.tgz", "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", "dev": true, "requires": { @@ -10032,7 +10057,7 @@ }, "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -10041,7 +10066,7 @@ }, "ms": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/ms/download/ms-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/ms/download/ms-2.0.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fms%2Fdownload%2Fms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true } @@ -10049,7 +10074,7 @@ }, "expand-tilde": { "version": "2.0.2", - "resolved": "https://registry.nlark.com/expand-tilde/download/expand-tilde-2.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/expand-tilde/download/expand-tilde-2.0.2.tgz", "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", "dev": true, "requires": { @@ -10058,7 +10083,7 @@ }, "expect": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/expect/download/expect-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/expect/download/expect-26.6.2.tgz?cache=0&sync_timestamp=1616701586390&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fexpect%2Fdownload%2Fexpect-26.6.2.tgz", "integrity": "sha1-xrmWvya/P+GLZ7LQ9R/JgbqTRBc=", "dev": true, "requires": { @@ -10072,7 +10097,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -10103,7 +10128,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -10122,7 +10147,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -10137,19 +10162,19 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, "jest-get-type": { "version": "26.3.0", - "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-26.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/jest-get-type/download/jest-get-type-26.3.0.tgz", "integrity": "sha1-6X3Dw/U8K0Bsp6+u1Ek7HQmRmeA=", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -10183,7 +10208,7 @@ }, "extend-shallow": { "version": "3.0.2", - "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-3.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-3.0.2.tgz", "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", "dev": true, "requires": { @@ -10193,7 +10218,7 @@ "dependencies": { "is-extendable": { "version": "1.0.1", - "resolved": "https://registry.nlark.com/is-extendable/download/is-extendable-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/is-extendable/download/is-extendable-1.0.1.tgz", "integrity": "sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=", "dev": true, "requires": { @@ -10204,7 +10229,7 @@ }, "extglob": { "version": "2.0.4", - "resolved": "https://registry.nlark.com/extglob/download/extglob-2.0.4.tgz", + "resolved": "https://registry.npm.taobao.org/extglob/download/extglob-2.0.4.tgz", "integrity": "sha1-rQD+TcYSqSMuhxhxHcXLWrAoVUM=", "dev": true, "requires": { @@ -10229,7 +10254,7 @@ }, "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -10238,7 +10263,7 @@ }, "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -10247,7 +10272,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -10269,7 +10294,7 @@ }, "fancy-log": { "version": "1.3.3", - "resolved": "https://registry.nlark.com/fancy-log/download/fancy-log-1.3.3.tgz", + "resolved": "https://registry.npm.taobao.org/fancy-log/download/fancy-log-1.3.3.tgz", "integrity": "sha1-28GRVPVYaQFQojlToK29A1vkX8c=", "dev": true, "requires": { @@ -10350,7 +10375,7 @@ }, "fast-levenshtein": { "version": "2.0.6", - "resolved": "https://registry.nlark.com/fast-levenshtein/download/fast-levenshtein-2.0.6.tgz", + "resolved": "https://registry.npm.taobao.org/fast-levenshtein/download/fast-levenshtein-2.0.6.tgz", "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" }, "fast-safe-stringify": { @@ -10505,16 +10530,27 @@ }, "for-own": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/for-own/download/for-own-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/for-own/download/for-own-1.0.0.tgz", "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", "dev": true, "requires": { "for-in": "^1.0.1" } }, + "form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + } + }, "fragment-cache": { "version": "0.2.1", - "resolved": "https://registry.nlark.com/fragment-cache/download/fragment-cache-0.2.1.tgz", + "resolved": "https://registry.npm.taobao.org/fragment-cache/download/fragment-cache-0.2.1.tgz", "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", "dev": true, "requires": { @@ -10524,12 +10560,12 @@ "fs": { "version": "0.0.1-security", "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", - "integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==", + "integrity": "sha1-invTcYa23d84E/I4WLV+yq9eQdQ=", "dev": true }, "fs-extra": { "version": "7.0.1", - "resolved": "https://registry.nlark.com/fs-extra/download/fs-extra-7.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/fs-extra/download/fs-extra-7.0.1.tgz", "integrity": "sha1-TxicRKoSO4lfcigE9V6iPq3DSOk=", "dev": true, "requires": { @@ -10538,9 +10574,29 @@ "universalify": "^0.1.0" } }, + "fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dev": true, + "requires": { + "minipass": "^3.0.0" + }, + "dependencies": { + "minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dev": true, + "requires": { + "yallist": "^4.0.0" + } + } + } + }, "fs-mkdirp-stream": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/fs-mkdirp-stream/download/fs-mkdirp-stream-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/fs-mkdirp-stream/download/fs-mkdirp-stream-1.0.0.tgz", "integrity": "sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes=", "dev": true, "requires": { @@ -10550,7 +10606,7 @@ }, "fs.realpath": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/fs.realpath/download/fs.realpath-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/fs.realpath/download/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "fsevents": { @@ -11183,7 +11239,7 @@ }, "function-bind": { "version": "1.1.1", - "resolved": "https://registry.nlark.com/function-bind/download/function-bind-1.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/function-bind/download/function-bind-1.1.1.tgz", "integrity": "sha1-pWiZ0+o8m6uHS7l3O3xe3pL0iV0=" }, "function.prototype.name": { @@ -11364,7 +11420,7 @@ }, "gensync": { "version": "1.0.0-beta.2", - "resolved": "https://registry.nlark.com/gensync/download/gensync-1.0.0-beta.2.tgz", + "resolved": "https://registry.npm.taobao.org/gensync/download/gensync-1.0.0-beta.2.tgz", "integrity": "sha1-MqbudsPX9S1GsrGuXZP+qFgKJeA=" }, "get-assigned-identifiers": { @@ -11398,7 +11454,7 @@ }, "get-stream": { "version": "4.1.0", - "resolved": "https://registry.nlark.com/get-stream/download/get-stream-4.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/get-stream/download/get-stream-4.1.0.tgz", "integrity": "sha1-wbJVV189wh1Zv8ec09K0axw6VLU=", "dev": true, "requires": { @@ -11440,7 +11496,7 @@ }, "get-value": { "version": "2.0.6", - "resolved": "https://registry.nlark.com/get-value/download/get-value-2.0.6.tgz", + "resolved": "https://registry.npm.taobao.org/get-value/download/get-value-2.0.6.tgz", "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", "dev": true }, @@ -11479,7 +11535,7 @@ }, "glob-stream": { "version": "6.1.0", - "resolved": "https://registry.nlark.com/glob-stream/download/glob-stream-6.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/glob-stream/download/glob-stream-6.1.0.tgz", "integrity": "sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ=", "dev": true, "requires": { @@ -11497,7 +11553,7 @@ "dependencies": { "glob-parent": { "version": "3.1.0", - "resolved": "https://registry.npmmirror.com/glob-parent/download/glob-parent-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/glob-parent/download/glob-parent-3.1.0.tgz?cache=0&sync_timestamp=1569108917227&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fglob-parent%2Fdownload%2Fglob-parent-3.1.0.tgz", "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", "dev": true, "requires": { @@ -11507,7 +11563,7 @@ }, "is-glob": { "version": "3.1.0", - "resolved": "https://registry.npmmirror.com/is-glob/download/is-glob-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-3.1.0.tgz", "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { @@ -11532,7 +11588,7 @@ }, "global-modules": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/global-modules/download/global-modules-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/global-modules/download/global-modules-1.0.0.tgz?cache=0&sync_timestamp=1571657602039&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fglobal-modules%2Fdownload%2Fglobal-modules-1.0.0.tgz", "integrity": "sha1-bXcPDrUjrHgWTXK15xqIdyZcw+o=", "dev": true, "requires": { @@ -11567,7 +11623,7 @@ }, "globals": { "version": "11.12.0", - "resolved": "https://registry.npmmirror.com/globals/download/globals-11.12.0.tgz", + "resolved": "https://registry.npm.taobao.org/globals/download/globals-11.12.0.tgz", "integrity": "sha1-q4eVM4hooLq9hSV1gBjCp+uVxC4=" }, "globalthis": { @@ -11603,7 +11659,7 @@ }, "glogg": { "version": "1.0.2", - "resolved": "https://registry.nlark.com/glogg/download/glogg-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/glogg/download/glogg-1.0.2.tgz", "integrity": "sha1-LX3XAr7aIus7/634gGltpthGMT8=", "dev": true, "requires": { @@ -11670,7 +11726,7 @@ "camelcase": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", - "integrity": "sha512-4nhGqUkc4BqbBBB4Q6zLuD7lzzrHYrjKGeYaEji/3tFR5VdJu9v+LilhGIVe8wxEJPPOeWo7eg8dwY13TZ1BNg==", + "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", "dev": true }, "gulp-cli": { @@ -11701,7 +11757,7 @@ }, "is-fullwidth-code-point": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-fullwidth-code-point/download/is-fullwidth-code-point-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-fullwidth-code-point/download/is-fullwidth-code-point-1.0.0.tgz", "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "dev": true, "requires": { @@ -11710,7 +11766,7 @@ }, "string-width": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/string-width/download/string-width-1.0.2.tgz?cache=0&sync_timestamp=1632421309919&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fstring-width%2Fdownload%2Fstring-width-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/string-width/download/string-width-1.0.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstring-width%2Fdownload%2Fstring-width-1.0.2.tgz", "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "requires": { @@ -11826,7 +11882,7 @@ }, "gulplog": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/gulplog/download/gulplog-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/gulplog/download/gulplog-1.0.0.tgz", "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", "dev": true, "requires": { @@ -11835,7 +11891,7 @@ }, "has": { "version": "1.0.3", - "resolved": "https://registry.nlark.com/has/download/has-1.0.3.tgz", + "resolved": "https://registry.npm.taobao.org/has/download/has-1.0.3.tgz", "integrity": "sha1-ci18v8H2qoJB8W3YFOAR4fQeh5Y=", "requires": { "function-bind": "^1.1.1" @@ -11849,7 +11905,7 @@ }, "has-flag": { "version": "3.0.0", - "resolved": "https://registry.nlark.com/has-flag/download/has-flag-3.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-3.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "has-gulplog": { @@ -11914,7 +11970,7 @@ }, "has-value": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/has-value/download/has-value-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/has-value/download/has-value-1.0.0.tgz", "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", "dev": true, "requires": { @@ -11925,7 +11981,7 @@ }, "has-values": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/has-values/download/has-values-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/has-values/download/has-values-1.0.0.tgz", "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", "dev": true, "requires": { @@ -12039,7 +12095,7 @@ }, "http-proxy": { "version": "1.18.1", - "resolved": "https://registry.nlark.com/http-proxy/download/http-proxy-1.18.1.tgz?cache=0&sync_timestamp=1618847045732&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhttp-proxy%2Fdownload%2Fhttp-proxy-1.18.1.tgz", + "resolved": "https://registry.npm.taobao.org/http-proxy/download/http-proxy-1.18.1.tgz", "integrity": "sha1-QBVB8FNIhLv5UmAzTnL4juOXZUk=", "dev": true, "requires": { @@ -12050,7 +12106,7 @@ }, "http-server": { "version": "0.12.3", - "resolved": "https://registry.npmmirror.com/http-server/download/http-server-0.12.3.tgz?cache=0&sync_timestamp=1634685922991&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fhttp-server%2Fdownload%2Fhttp-server-0.12.3.tgz", + "resolved": "https://registry.npm.taobao.org/http-server/download/http-server-0.12.3.tgz", "integrity": "sha1-ugRx0OzEJYhmFss1xPryeRQKDTc=", "dev": true, "requires": { @@ -12074,7 +12130,7 @@ }, "https-proxy-agent": { "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", "dev": true, "requires": { @@ -12121,7 +12177,7 @@ }, "imurmurhash": { "version": "0.1.4", - "resolved": "https://registry.nlark.com/imurmurhash/download/imurmurhash-0.1.4.tgz", + "resolved": "https://registry.npm.taobao.org/imurmurhash/download/imurmurhash-0.1.4.tgz", "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" }, "indent-string": { @@ -12141,7 +12197,7 @@ }, "inherits": { "version": "2.0.4", - "resolved": "https://registry.nlark.com/inherits/download/inherits-2.0.4.tgz", + "resolved": "https://registry.npm.taobao.org/inherits/download/inherits-2.0.4.tgz", "integrity": "sha1-D6LGT5MpF8NDOg3tVTY6rjdBa3w=" }, "ini": { @@ -12209,7 +12265,7 @@ }, "invariant": { "version": "2.2.4", - "resolved": "https://registry.npm.taobao.org/invariant/download/invariant-2.2.4.tgz?cache=0&sync_timestamp=1615984365242&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Finvariant%2Fdownload%2Finvariant-2.2.4.tgz", + "resolved": "https://registry.npm.taobao.org/invariant/download/invariant-2.2.4.tgz", "integrity": "sha1-YQ88ksk1nOHbYW5TgAjSP/NRWOY=", "dev": true, "requires": { @@ -12218,7 +12274,7 @@ }, "invert-kv": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/invert-kv/download/invert-kv-1.0.0.tgz?cache=0&sync_timestamp=1630996809231&other_urls=https%3A%2F%2Fregistry.nlark.com%2Finvert-kv%2Fdownload%2Finvert-kv-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/invert-kv/download/invert-kv-1.0.0.tgz", "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", "dev": true }, @@ -12234,7 +12290,7 @@ }, "is-accessor-descriptor": { "version": "0.1.6", - "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-0.1.6.tgz", + "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-0.1.6.tgz", "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "dev": true, "requires": { @@ -12356,7 +12412,7 @@ }, "is-binary-path": { "version": "1.0.1", - "resolved": "https://registry.nlark.com/is-binary-path/download/is-binary-path-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/is-binary-path/download/is-binary-path-1.0.1.tgz", "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", "dev": true, "requires": { @@ -12398,7 +12454,7 @@ }, "is-buffer": { "version": "1.1.6", - "resolved": "https://registry.npm.taobao.org/is-buffer/download/is-buffer-1.1.6.tgz?cache=0&sync_timestamp=1604432327227&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fis-buffer%2Fdownload%2Fis-buffer-1.1.6.tgz", + "resolved": "https://registry.npm.taobao.org/is-buffer/download/is-buffer-1.1.6.tgz", "integrity": "sha1-76ouqdqg16suoTqXsritUf776L4=", "dev": true }, @@ -12410,7 +12466,7 @@ }, "is-ci": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/is-ci/download/is-ci-2.0.0.tgz?cache=0&sync_timestamp=1635261061017&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fis-ci%2Fdownload%2Fis-ci-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-ci/download/is-ci-2.0.0.tgz", "integrity": "sha1-a8YzQYGBDgS1wis9WJ/cpVAmQEw=", "dev": true, "requires": { @@ -12428,7 +12484,7 @@ }, "is-data-descriptor": { "version": "0.1.4", - "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-0.1.4.tgz", + "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-0.1.4.tgz", "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "dev": true, "requires": { @@ -12483,7 +12539,7 @@ }, "is-extendable": { "version": "0.1.1", - "resolved": "https://registry.nlark.com/is-extendable/download/is-extendable-0.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/is-extendable/download/is-extendable-0.1.1.tgz", "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", "dev": true }, @@ -12524,13 +12580,13 @@ }, "is-module": { "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/is-module/-/is-module-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", "dev": true }, "is-negated-glob": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-negated-glob/download/is-negated-glob-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-negated-glob/download/is-negated-glob-1.0.0.tgz", "integrity": "sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI=", "dev": true }, @@ -12591,7 +12647,7 @@ }, "is-potential-custom-element-name": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", "dev": true }, @@ -12680,7 +12736,7 @@ }, "is-stream": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/is-stream/download/is-stream-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-stream/download/is-stream-1.1.0.tgz", "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", "dev": true }, @@ -12936,7 +12992,7 @@ }, "is-windows": { "version": "1.0.2", - "resolved": "https://registry.nlark.com/is-windows/download/is-windows-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/is-windows/download/is-windows-1.0.2.tgz", "integrity": "sha1-0YUOuXkezRjmGCzhKjDzlmNLsZ0=", "dev": true }, @@ -12952,13 +13008,13 @@ }, "isarray": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/isarray/download/isarray-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/isarray/download/isarray-1.0.0.tgz?cache=0&sync_timestamp=1562592096220&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fisarray%2Fdownload%2Fisarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true }, "isexe": { "version": "2.0.0", - "resolved": "https://registry.nlark.com/isexe/download/isexe-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/isexe/download/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, "isobject": { @@ -13961,7 +14017,7 @@ }, "jest-diff": { "version": "24.9.0", - "resolved": "https://registry.npmmirror.com/jest-diff/download/jest-diff-24.9.0.tgz", + "resolved": "https://registry.npm.taobao.org/jest-diff/download/jest-diff-24.9.0.tgz", "integrity": "sha1-kxt9DVd4obr3RSy4FuMl43JAVdo=", "dev": true, "requires": { @@ -14433,7 +14489,7 @@ }, "@types/istanbul-reports": { "version": "3.0.1", - "resolved": "https://registry.npmmirror.com/@types/istanbul-reports/download/@types/istanbul-reports-3.0.1.tgz?cache=0&sync_timestamp=1637266160892&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fistanbul-reports%2Fdownload%2F%40types%2Fistanbul-reports-3.0.1.tgz", + "resolved": "https://registry.npmmirror.com/@types/istanbul-reports/download/@types/istanbul-reports-3.0.1.tgz", "integrity": "sha1-kVP+mLuivVZaY63ZQ21vDX+EaP8=", "dev": true, "requires": { @@ -14442,7 +14498,7 @@ }, "@types/yargs": { "version": "16.0.4", - "resolved": "https://registry.npmmirror.com/@types/yargs/download/@types/yargs-16.0.4.tgz?cache=0&sync_timestamp=1637271118840&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fyargs%2Fdownload%2F%40types%2Fyargs-16.0.4.tgz", + "resolved": "https://registry.npmmirror.com/@types/yargs/download/@types/yargs-16.0.4.tgz", "integrity": "sha1-JqrZjdLCo45CEIbqmtQrnlFkKXc=", "dev": true, "requires": { @@ -14457,7 +14513,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1618995588464&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -14466,7 +14522,7 @@ }, "chalk": { "version": "4.1.2", - "resolved": "https://registry.npmmirror.com/chalk/download/chalk-4.1.2.tgz", + "resolved": "https://registry.nlark.com/chalk/download/chalk-4.1.2.tgz?cache=0&sync_timestamp=1627646655305&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fchalk%2Fdownload%2Fchalk-4.1.2.tgz", "integrity": "sha1-qsTit3NKdAhnrrFr8CqtVWoeegE=", "dev": true, "requires": { @@ -14545,7 +14601,7 @@ "dependencies": { "ansi-styles": { "version": "5.2.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-5.2.0.tgz", + "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-5.2.0.tgz?cache=0&sync_timestamp=1618995588464&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fansi-styles%2Fdownload%2Fansi-styles-5.2.0.tgz", "integrity": "sha1-B0SWkK1Fd30ZJKwquy/IiV26g2s=", "dev": true } @@ -14553,7 +14609,7 @@ }, "react-is": { "version": "17.0.2", - "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz", + "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz?cache=0&sync_timestamp=1637338596901&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Freact-is%2Fdownload%2Freact-is-17.0.2.tgz", "integrity": "sha1-5pHUqOnHiTZWVVOas3J2Kw77VPA=", "dev": true }, @@ -14570,7 +14626,7 @@ }, "jest-get-type": { "version": "24.9.0", - "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-24.9.0.tgz", + "resolved": "https://registry.npm.taobao.org/jest-get-type/download/jest-get-type-24.9.0.tgz?cache=0&sync_timestamp=1579655144842&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-get-type%2Fdownload%2Fjest-get-type-24.9.0.tgz", "integrity": "sha1-FoSgyKUPLkkBtmRK6GH1ee7S7w4=", "dev": true }, @@ -14863,7 +14919,7 @@ }, "jest-matcher-deep-close-to": { "version": "2.0.1", - "resolved": "https://registry.npmmirror.com/jest-matcher-deep-close-to/download/jest-matcher-deep-close-to-2.0.1.tgz", + "resolved": "https://registry.nlark.com/jest-matcher-deep-close-to/download/jest-matcher-deep-close-to-2.0.1.tgz", "integrity": "sha1-L50NpE94oWo5BNGJguOV6Y43XFo=", "dev": true, "requires": { @@ -14872,7 +14928,7 @@ "dependencies": { "@jest/types": { "version": "25.5.0", - "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-25.5.0.tgz", + "resolved": "https://registry.nlark.com/@jest/types/download/@jest/types-25.5.0.tgz?cache=0&sync_timestamp=1624900057884&other_urls=https%3A%2F%2Fregistry.nlark.com%2F%40jest%2Ftypes%2Fdownload%2F%40jest%2Ftypes-25.5.0.tgz", "integrity": "sha1-TWpHk/e5WZ/DaAh3uFapfbzPKp0=", "dev": true, "requires": { @@ -14884,7 +14940,7 @@ }, "@types/yargs": { "version": "15.0.14", - "resolved": "https://registry.npmmirror.com/@types/yargs/download/@types/yargs-15.0.14.tgz?cache=0&sync_timestamp=1637271118840&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2F%40types%2Fyargs%2Fdownload%2F%40types%2Fyargs-15.0.14.tgz", + "resolved": "https://registry.nlark.com/@types/yargs/download/@types/yargs-15.0.14.tgz", "integrity": "sha1-Jtgh3biecEkhYLZtEKDrbfj2+wY=", "dev": true, "requires": { @@ -14908,7 +14964,7 @@ }, "chalk": { "version": "3.0.0", - "resolved": "https://registry.npmmirror.com/chalk/download/chalk-3.0.0.tgz", + "resolved": "https://registry.nlark.com/chalk/download/chalk-3.0.0.tgz?cache=0&sync_timestamp=1618995367379&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fchalk%2Fdownload%2Fchalk-3.0.0.tgz", "integrity": "sha1-P3PCv1JlkfV0zEksUeJFY0n4ROQ=", "dev": true, "requires": { @@ -14918,7 +14974,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -14933,7 +14989,7 @@ }, "diff-sequences": { "version": "25.2.6", - "resolved": "https://registry.npmmirror.com/diff-sequences/download/diff-sequences-25.2.6.tgz", + "resolved": "https://registry.nlark.com/diff-sequences/download/diff-sequences-25.2.6.tgz?cache=0&sync_timestamp=1624900057366&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fdiff-sequences%2Fdownload%2Fdiff-sequences-25.2.6.tgz", "integrity": "sha1-X0Z8AO3TU1K3vKRteSfWDmh6dt0=", "dev": true }, @@ -14945,7 +15001,7 @@ }, "jest-diff": { "version": "25.5.0", - "resolved": "https://registry.npmmirror.com/jest-diff/download/jest-diff-25.5.0.tgz", + "resolved": "https://registry.nlark.com/jest-diff/download/jest-diff-25.5.0.tgz", "integrity": "sha1-HdJu1k+WZnwGjO8Ca2d9+gGvz6k=", "dev": true, "requires": { @@ -14957,13 +15013,13 @@ }, "jest-get-type": { "version": "25.2.6", - "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-25.2.6.tgz", + "resolved": "https://registry.nlark.com/jest-get-type/download/jest-get-type-25.2.6.tgz?cache=0&sync_timestamp=1624900056951&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fjest-get-type%2Fdownload%2Fjest-get-type-25.2.6.tgz", "integrity": "sha1-Cwoy+riQi0TVCL6BaBSH26u42Hc=", "dev": true }, "jest-matcher-utils": { "version": "25.4.0", - "resolved": "https://registry.npmmirror.com/jest-matcher-utils/download/jest-matcher-utils-25.4.0.tgz", + "resolved": "https://registry.nlark.com/jest-matcher-utils/download/jest-matcher-utils-25.4.0.tgz", "integrity": "sha1-3D567EAqHlZ+2AtXK5rShYeIleY=", "dev": true, "requires": { @@ -14975,7 +15031,7 @@ }, "pretty-format": { "version": "25.5.0", - "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-25.5.0.tgz", + "resolved": "https://registry.nlark.com/pretty-format/download/pretty-format-25.5.0.tgz", "integrity": "sha1-eHPB13T2gsNLjUi2dDor8qxVeRo=", "dev": true, "requires": { @@ -14987,7 +15043,7 @@ }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", + "resolved": "https://registry.nlark.com/supports-color/download/supports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -14998,7 +15054,7 @@ }, "jest-matcher-utils": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/jest-matcher-utils/download/jest-matcher-utils-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/jest-matcher-utils/download/jest-matcher-utils-26.6.2.tgz?cache=0&sync_timestamp=1616701585427&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-matcher-utils%2Fdownload%2Fjest-matcher-utils-26.6.2.tgz", "integrity": "sha1-jm/W6GPIstMaxkcu6yN7xZXlPno=", "dev": true, "requires": { @@ -15010,7 +15066,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -15047,7 +15103,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -15066,7 +15122,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -15081,19 +15137,19 @@ }, "diff-sequences": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/diff-sequences/download/diff-sequences-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/diff-sequences/download/diff-sequences-26.6.2.tgz", "integrity": "sha1-SLqZFX3hkjQS7tQdtrbUqpynwLE=", "dev": true }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, "jest-diff": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/jest-diff/download/jest-diff-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/jest-diff/download/jest-diff-26.6.2.tgz?cache=0&sync_timestamp=1616701585219&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-diff%2Fdownload%2Fjest-diff-26.6.2.tgz", "integrity": "sha1-GqdGi1LDpo19XF/c381eSb0WQ5Q=", "dev": true, "requires": { @@ -15105,13 +15161,13 @@ }, "jest-get-type": { "version": "26.3.0", - "resolved": "https://registry.npmmirror.com/jest-get-type/download/jest-get-type-26.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/jest-get-type/download/jest-get-type-26.3.0.tgz", "integrity": "sha1-6X3Dw/U8K0Bsp6+u1Ek7HQmRmeA=", "dev": true }, "pretty-format": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/pretty-format/download/pretty-format-26.6.2.tgz?cache=0&sync_timestamp=1616701219088&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fpretty-format%2Fdownload%2Fpretty-format-26.6.2.tgz", "integrity": "sha1-41wnBfFMt/4v6U+geDRbREEg/JM=", "dev": true, "requires": { @@ -15123,13 +15179,13 @@ }, "react-is": { "version": "17.0.2", - "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/react-is/download/react-is-17.0.2.tgz", "integrity": "sha1-5pHUqOnHiTZWVVOas3J2Kw77VPA=", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -15140,7 +15196,7 @@ }, "jest-message-util": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/jest-message-util/download/jest-message-util-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/jest-message-util/download/jest-message-util-26.6.2.tgz?cache=0&sync_timestamp=1616701584149&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-message-util%2Fdownload%2Fjest-message-util-26.6.2.tgz", "integrity": "sha1-WBc3RK1vwFBrXSEVC5vlbvABygc=", "dev": true, "requires": { @@ -15157,7 +15213,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -15194,7 +15250,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -15222,7 +15278,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -15252,7 +15308,7 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, @@ -15274,7 +15330,7 @@ }, "pretty-format": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/pretty-format/download/pretty-format-26.6.2.tgz?cache=0&sync_timestamp=1616701219088&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fpretty-format%2Fdownload%2Fpretty-format-26.6.2.tgz", "integrity": "sha1-41wnBfFMt/4v6U+geDRbREEg/JM=", "dev": true, "requires": { @@ -15286,13 +15342,13 @@ }, "react-is": { "version": "17.0.2", - "resolved": "https://registry.npmmirror.com/react-is/download/react-is-17.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/react-is/download/react-is-17.0.2.tgz", "integrity": "sha1-5pHUqOnHiTZWVVOas3J2Kw77VPA=", "dev": true }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -15411,7 +15467,7 @@ }, "jest-regex-util": { "version": "26.0.0", - "resolved": "https://registry.npmmirror.com/jest-regex-util/download/jest-regex-util-26.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/jest-regex-util/download/jest-regex-util-26.0.0.tgz?cache=0&sync_timestamp=1607352728942&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-regex-util%2Fdownload%2Fjest-regex-util-26.0.0.tgz", "integrity": "sha1-0l5xhLNuOf1GbDvEG+CXHoIf7ig=", "dev": true }, @@ -16700,7 +16756,7 @@ }, "jest-util": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/jest-util/download/jest-util-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/jest-util/download/jest-util-26.6.2.tgz?cache=0&sync_timestamp=1616701582882&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fjest-util%2Fdownload%2Fjest-util-26.6.2.tgz", "integrity": "sha1-kHU12+TVpstMR6ybkm9q8pV2y8E=", "dev": true, "requires": { @@ -16714,7 +16770,7 @@ "dependencies": { "@jest/types": { "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/@jest/types/download/@jest/types-26.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/@jest/types/download/@jest/types-26.6.2.tgz", "integrity": "sha1-vvWlMgMOHYii9abZM/hOlyJu1I4=", "dev": true, "requires": { @@ -16745,7 +16801,7 @@ }, "ansi-styles": { "version": "4.3.0", - "resolved": "https://registry.nlark.com/ansi-styles/download/ansi-styles-4.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-styles/download/ansi-styles-4.3.0.tgz?cache=0&sync_timestamp=1611327117754&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-styles%2Fdownload%2Fansi-styles-4.3.0.tgz", "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", "dev": true, "requires": { @@ -16773,7 +16829,7 @@ }, "color-convert": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/color-convert/download/color-convert-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/color-convert/download/color-convert-2.0.1.tgz", "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", "dev": true, "requires": { @@ -16803,7 +16859,7 @@ }, "has-flag": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/has-flag/download/has-flag-4.0.0.tgz?cache=0&sync_timestamp=1626715907927&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fhas-flag%2Fdownload%2Fhas-flag-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/has-flag/download/has-flag-4.0.0.tgz", "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", "dev": true }, @@ -16825,7 +16881,7 @@ }, "supports-color": { "version": "7.2.0", - "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-7.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-7.2.0.tgz?cache=0&sync_timestamp=1611394043517&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsupports-color%2Fdownload%2Fsupports-color-7.2.0.tgz", "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", "dev": true, "requires": { @@ -17150,7 +17206,7 @@ }, "js-tokens": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/js-tokens/download/js-tokens-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/js-tokens/download/js-tokens-4.0.0.tgz", "integrity": "sha1-GSA/tZmR35jjoocFDUZHzerzJJk=" }, "js-yaml": { @@ -17165,7 +17221,7 @@ }, "jsdom": { "version": "19.0.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-19.0.0.tgz", + "resolved": "https://registry.npmmirror.com/jsdom/-/jsdom-19.0.0.tgz", "integrity": "sha512-RYAyjCbxy/vri/CfnjUWJQQtZ3LKlLnDqj+9XLNnJPgEGeirZs3hllKR20re8LUZ6o1b1X4Jat+Qd26zmP41+A==", "dev": true, "requires": { @@ -17206,7 +17262,7 @@ }, "acorn": { "version": "8.7.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.1.tgz", + "resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.7.1.tgz", "integrity": "sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==", "dev": true }, @@ -17353,7 +17409,7 @@ }, "jsesc": { "version": "2.5.2", - "resolved": "https://registry.nlark.com/jsesc/download/jsesc-2.5.2.tgz", + "resolved": "https://registry.npm.taobao.org/jsesc/download/jsesc-2.5.2.tgz", "integrity": "sha1-gFZNLkg9rPbo7yCWUKZ98/DCg6Q=" }, "json-parse-even-better-errors": { @@ -17364,12 +17420,12 @@ }, "json-schema-traverse": { "version": "0.4.1", - "resolved": "https://registry.nlark.com/json-schema-traverse/download/json-schema-traverse-0.4.1.tgz", + "resolved": "https://registry.npm.taobao.org/json-schema-traverse/download/json-schema-traverse-0.4.1.tgz", "integrity": "sha1-afaofZUTq4u4/mO9sJecRI5oRmA=" }, "json-stable-stringify-without-jsonify": { "version": "1.0.1", - "resolved": "https://registry.nlark.com/json-stable-stringify-without-jsonify/download/json-stable-stringify-without-jsonify-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/json-stable-stringify-without-jsonify/download/json-stable-stringify-without-jsonify-1.0.1.tgz", "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=" }, "json5": { @@ -17385,7 +17441,7 @@ }, "jsonfile": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/jsonfile/download/jsonfile-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/jsonfile/download/jsonfile-4.0.0.tgz", "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", "dev": true, "requires": { @@ -17428,7 +17484,7 @@ }, "last-run": { "version": "1.1.1", - "resolved": "https://registry.nlark.com/last-run/download/last-run-1.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/last-run/download/last-run-1.1.1.tgz", "integrity": "sha1-RblpQsF7HHnHchmCWbqUO+v4yls=", "dev": true, "requires": { @@ -17447,7 +17503,7 @@ }, "lcid": { "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/lcid/download/lcid-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/lcid/download/lcid-1.0.0.tgz", "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", "dev": true, "requires": { @@ -17465,7 +17521,7 @@ }, "leven": { "version": "3.1.0", - "resolved": "https://registry.nlark.com/leven/download/leven-3.1.0.tgz?cache=0&sync_timestamp=1628597922950&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fleven%2Fdownload%2Fleven-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/leven/download/leven-3.1.0.tgz", "integrity": "sha1-d4kd6DQGTMy6gq54QrtrFKE+1/I=", "dev": true }, @@ -17480,7 +17536,7 @@ }, "levn": { "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "resolved": "https://registry.npmmirror.com/levn/-/levn-0.3.0.tgz", "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", "dev": true, "requires": { @@ -17512,7 +17568,7 @@ }, "load-json-file": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/load-json-file/download/load-json-file-1.1.0.tgz?cache=0&sync_timestamp=1631508607226&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fload-json-file%2Fdownload%2Fload-json-file-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/load-json-file/download/load-json-file-1.1.0.tgz", "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "dev": true, "requires": { @@ -17552,7 +17608,7 @@ }, "loose-envify": { "version": "1.4.0", - "resolved": "https://registry.nlark.com/loose-envify/download/loose-envify-1.4.0.tgz", + "resolved": "https://registry.npm.taobao.org/loose-envify/download/loose-envify-1.4.0.tgz", "integrity": "sha1-ce5R+nvkyuwaY4OffmgtgTLTDK8=", "dev": true, "requires": { @@ -17561,7 +17617,7 @@ }, "lru-cache": { "version": "6.0.0", - "resolved": "https://registry.nlark.com/lru-cache/download/lru-cache-6.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/lru-cache/download/lru-cache-6.0.0.tgz", "integrity": "sha1-bW/mVw69lqr5D8rR2vo7JWbbOpQ=", "requires": { "yallist": "^4.0.0" @@ -17595,7 +17651,7 @@ }, "make-error": { "version": "1.3.6", - "resolved": "https://registry.nlark.com/make-error/download/make-error-1.3.6.tgz", + "resolved": "https://registry.npm.taobao.org/make-error/download/make-error-1.3.6.tgz?cache=0&sync_timestamp=1582105630664&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmake-error%2Fdownload%2Fmake-error-1.3.6.tgz", "integrity": "sha1-LrLjfqm2fEiR9oShOUeZr0hM96I=", "dev": true }, @@ -17628,7 +17684,7 @@ }, "map-age-cleaner": { "version": "0.1.3", - "resolved": "https://registry.nlark.com/map-age-cleaner/download/map-age-cleaner-0.1.3.tgz?cache=0&sync_timestamp=1629750856019&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fmap-age-cleaner%2Fdownload%2Fmap-age-cleaner-0.1.3.tgz", + "resolved": "https://registry.npm.taobao.org/map-age-cleaner/download/map-age-cleaner-0.1.3.tgz", "integrity": "sha1-fVg6cwZDTAVf5HSw9FB45uG0uSo=", "dev": true, "requires": { @@ -17637,13 +17693,13 @@ }, "map-cache": { "version": "0.2.2", - "resolved": "https://registry.nlark.com/map-cache/download/map-cache-0.2.2.tgz", + "resolved": "https://registry.npm.taobao.org/map-cache/download/map-cache-0.2.2.tgz", "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", "dev": true }, "map-visit": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/map-visit/download/map-visit-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/map-visit/download/map-visit-1.0.0.tgz", "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", "dev": true, "requires": { @@ -17664,7 +17720,7 @@ "dependencies": { "findup-sync": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/findup-sync/download/findup-sync-2.0.0.tgz?cache=0&sync_timestamp=1635766114067&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Ffindup-sync%2Fdownload%2Ffindup-sync-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/findup-sync/download/findup-sync-2.0.0.tgz", "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", "dev": true, "requires": { @@ -17676,7 +17732,7 @@ }, "is-glob": { "version": "3.1.0", - "resolved": "https://registry.npmmirror.com/is-glob/download/is-glob-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-3.1.0.tgz", "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { @@ -17698,7 +17754,7 @@ }, "mem": { "version": "4.3.0", - "resolved": "https://registry.nlark.com/mem/download/mem-4.3.0.tgz?cache=0&sync_timestamp=1626534487701&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fmem%2Fdownload%2Fmem-4.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/mem/download/mem-4.3.0.tgz", "integrity": "sha1-Rhr0l7xK4JYIzbLmDu+2m/90QXg=", "dev": true, "requires": { @@ -17717,7 +17773,7 @@ }, "merge-stream": { "version": "2.0.0", - "resolved": "https://registry.nlark.com/merge-stream/download/merge-stream-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/merge-stream/download/merge-stream-2.0.0.tgz", "integrity": "sha1-UoI2KaFN0AyXcPtq1H3GMQ8sH2A=", "dev": true }, @@ -17767,19 +17823,19 @@ }, "mime": { "version": "1.6.0", - "resolved": "https://registry.npmmirror.com/mime/download/mime-1.6.0.tgz", + "resolved": "https://registry.npm.taobao.org/mime/download/mime-1.6.0.tgz?cache=0&sync_timestamp=1560034758817&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmime%2Fdownload%2Fmime-1.6.0.tgz", "integrity": "sha1-Ms2eXGRVO9WNGaVor0Uqz/BJgbE=", "dev": true }, "mime-db": { "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true }, "mime-types": { "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "requires": { @@ -17788,7 +17844,7 @@ }, "mimic-fn": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "resolved": "https://registry.npmmirror.com/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", "dev": true }, @@ -17814,7 +17870,7 @@ }, "minimist": { "version": "1.2.5", - "resolved": "https://registry.npm.taobao.org/minimist/download/minimist-1.2.5.tgz", + "resolved": "https://registry.npm.taobao.org/minimist/download/minimist-1.2.5.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fminimist%2Fdownload%2Fminimist-1.2.5.tgz", "integrity": "sha1-Z9ZgFLZqaoqqDAg8X9WN9OTpdgI=", "dev": true }, @@ -17823,9 +17879,30 @@ "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.5.tgz", "integrity": "sha512-+yQl7SX3bIT83Lhb4BVorMAHVuqsskxRdlmO9kTpyukp8vsm2Sn/fUOV9xlnG8/a5JsypJzap21lz/y3FBMJ8Q==" }, + "minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dev": true, + "requires": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "dependencies": { + "minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dev": true, + "requires": { + "yallist": "^4.0.0" + } + } + } + }, "mixin-deep": { "version": "1.3.2", - "resolved": "https://registry.nlark.com/mixin-deep/download/mixin-deep-1.3.2.tgz", + "resolved": "https://registry.npm.taobao.org/mixin-deep/download/mixin-deep-1.3.2.tgz", "integrity": "sha1-ESC0PcNZp4Xc5ltVuC4lfM9HlWY=", "dev": true, "requires": { @@ -17835,7 +17912,7 @@ "dependencies": { "is-extendable": { "version": "1.0.1", - "resolved": "https://registry.nlark.com/is-extendable/download/is-extendable-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/is-extendable/download/is-extendable-1.0.1.tgz", "integrity": "sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=", "dev": true, "requires": { @@ -17844,6 +17921,12 @@ } } }, + "mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true + }, "mkdirp-classic": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", @@ -17875,7 +17958,7 @@ }, "ms": { "version": "2.1.2", - "resolved": "https://registry.npmmirror.com/ms/download/ms-2.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/ms/download/ms-2.1.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fms%2Fdownload%2Fms-2.1.2.tgz", "integrity": "sha1-0J0fNXtEP0kzgqjrPM0YOHKuYAk=" }, "mute-stdout": { @@ -17900,7 +17983,7 @@ }, "nanomatch": { "version": "1.2.13", - "resolved": "https://registry.nlark.com/nanomatch/download/nanomatch-1.2.13.tgz", + "resolved": "https://registry.npm.taobao.org/nanomatch/download/nanomatch-1.2.13.tgz", "integrity": "sha1-uHqKpPwN6P5r6IiVs4mD/yZb0Rk=", "dev": true, "requires": { @@ -17919,7 +18002,7 @@ }, "natural-compare": { "version": "1.4.0", - "resolved": "https://registry.nlark.com/natural-compare/download/natural-compare-1.4.0.tgz", + "resolved": "https://registry.npm.taobao.org/natural-compare/download/natural-compare-1.4.0.tgz", "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" }, "natural-compare-lite": { @@ -17929,16 +18012,22 @@ }, "next-tick": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/next-tick/download/next-tick-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/next-tick/download/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", "dev": true }, "nice-try": { "version": "1.0.5", - "resolved": "https://registry.nlark.com/nice-try/download/nice-try-1.0.5.tgz", + "resolved": "https://registry.npm.taobao.org/nice-try/download/nice-try-1.0.5.tgz", "integrity": "sha1-ozeKdpbOfSI+iPybdkvX7xCJ42Y=", "dev": true }, + "node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", + "dev": true + }, "node-int64": { "version": "0.4.0", "resolved": "https://registry.npmmirror.com/node-int64/-/node-int64-0.4.0.tgz", @@ -17953,7 +18042,7 @@ }, "normalize-package-data": { "version": "2.5.0", - "resolved": "https://registry.nlark.com/normalize-package-data/download/normalize-package-data-2.5.0.tgz?cache=0&sync_timestamp=1629301872905&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fnormalize-package-data%2Fdownload%2Fnormalize-package-data-2.5.0.tgz", + "resolved": "https://registry.npm.taobao.org/normalize-package-data/download/normalize-package-data-2.5.0.tgz", "integrity": "sha1-5m2xg4sgDB38IzIl0SyzZSDiNKg=", "dev": true, "requires": { @@ -17983,7 +18072,7 @@ }, "npm-run-path": { "version": "2.0.2", - "resolved": "https://registry.npmmirror.com/npm-run-path/download/npm-run-path-2.0.2.tgz?cache=0&sync_timestamp=1633420566316&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fnpm-run-path%2Fdownload%2Fnpm-run-path-2.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/npm-run-path/download/npm-run-path-2.0.2.tgz?cache=0&sync_timestamp=1577053500910&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fnpm-run-path%2Fdownload%2Fnpm-run-path-2.0.2.tgz", "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", "dev": true, "requires": { @@ -17992,13 +18081,13 @@ }, "number-is-nan": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/number-is-nan/download/number-is-nan-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/number-is-nan/download/number-is-nan-1.0.1.tgz", "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", "dev": true }, "nwsapi": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz", + "resolved": "https://registry.npmmirror.com/nwsapi/-/nwsapi-2.2.0.tgz", "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", "dev": true }, @@ -18047,13 +18136,13 @@ }, "object-keys": { "version": "1.1.1", - "resolved": "https://registry.nlark.com/object-keys/download/object-keys-1.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/object-keys/download/object-keys-1.1.1.tgz", "integrity": "sha1-HEfyct8nfzsdrwYWd9nILiMixg4=", "dev": true }, "object-visit": { "version": "1.0.1", - "resolved": "https://registry.nlark.com/object-visit/download/object-visit-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/object-visit/download/object-visit-1.0.1.tgz", "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", "dev": true, "requires": { @@ -18097,7 +18186,7 @@ "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -18177,7 +18266,7 @@ "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -18217,7 +18306,7 @@ }, "once": { "version": "1.4.0", - "resolved": "https://registry.nlark.com/once/download/once-1.4.0.tgz", + "resolved": "https://registry.npm.taobao.org/once/download/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "requires": { "wrappy": "1" @@ -18225,7 +18314,7 @@ }, "onetime": { "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "resolved": "https://registry.npmmirror.com/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dev": true, "requires": { @@ -18245,13 +18334,13 @@ }, "opener": { "version": "1.5.2", - "resolved": "https://registry.nlark.com/opener/download/opener-1.5.2.tgz?cache=0&sync_timestamp=1618847055043&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fopener%2Fdownload%2Fopener-1.5.2.tgz", + "resolved": "https://registry.npm.taobao.org/opener/download/opener-1.5.2.tgz", "integrity": "sha1-XTfh81B3udysQwE3InGv3rKhNZg=", "dev": true }, "optionator": { "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "resolved": "https://registry.npmmirror.com/optionator/-/optionator-0.8.3.tgz", "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", "dev": true, "requires": { @@ -18280,7 +18369,7 @@ }, "os-locale": { "version": "1.4.0", - "resolved": "https://registry.npmmirror.com/os-locale/download/os-locale-1.4.0.tgz?cache=0&sync_timestamp=1633618260196&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fos-locale%2Fdownload%2Fos-locale-1.4.0.tgz", + "resolved": "https://registry.npm.taobao.org/os-locale/download/os-locale-1.4.0.tgz", "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", "dev": true, "requires": { @@ -18295,7 +18384,7 @@ }, "p-finally": { "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/p-finally/download/p-finally-1.0.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fp-finally%2Fdownload%2Fp-finally-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/p-finally/download/p-finally-1.0.0.tgz", "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", "dev": true }, @@ -18334,7 +18423,7 @@ }, "p-try": { "version": "2.2.0", - "resolved": "https://registry.npmmirror.com/p-try/download/p-try-2.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/p-try/download/p-try-2.2.0.tgz", "integrity": "sha1-yyhoVA4xPWHeWPr741zpAE1VQOY=", "dev": true }, @@ -18387,7 +18476,7 @@ }, "parse-json": { "version": "2.2.0", - "resolved": "https://registry.npmmirror.com/parse-json/download/parse-json-2.2.0.tgz?cache=0&sync_timestamp=1637475717072&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fparse-json%2Fdownload%2Fparse-json-2.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/parse-json/download/parse-json-2.2.0.tgz", "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", "dev": true, "requires": { @@ -18396,7 +18485,7 @@ }, "parse-node-version": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/parse-node-version/download/parse-node-version-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/parse-node-version/download/parse-node-version-1.0.1.tgz", "integrity": "sha1-4rXb7eAOf6m8NjYH9TMn6LBzGJs=", "dev": true }, @@ -18408,20 +18497,20 @@ }, "parse5": { "version": "6.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "resolved": "https://registry.npmmirror.com/parse5/-/parse5-6.0.1.tgz", "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", "dev": true }, "pascalcase": { "version": "0.1.1", - "resolved": "https://registry.nlark.com/pascalcase/download/pascalcase-0.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/pascalcase/download/pascalcase-0.1.1.tgz", "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", "dev": true }, "path": { "version": "0.12.7", "resolved": "https://registry.npmjs.org/path/-/path-0.12.7.tgz", - "integrity": "sha512-aXXC6s+1w7otVF9UletFkFcDsJeO7lSZBPUQhtb5O0xJe8LtYhj/GxldoL09bBj9+ZmE2hNoHqQSFMN5fikh4Q==", + "integrity": "sha1-1NwqUGxM4hl+tIHr/NWzbAFAsQ8=", "dev": true, "requires": { "process": "^0.11.1", @@ -18436,13 +18525,13 @@ }, "path-dirname": { "version": "1.0.2", - "resolved": "https://registry.nlark.com/path-dirname/download/path-dirname-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/path-dirname/download/path-dirname-1.0.2.tgz", "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", "dev": true }, "path-exists": { "version": "3.0.0", - "resolved": "https://registry.nlark.com/path-exists/download/path-exists-3.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/path-exists/download/path-exists-3.0.0.tgz", "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", "dev": true }, @@ -18470,7 +18559,7 @@ }, "path-root": { "version": "0.1.1", - "resolved": "https://registry.nlark.com/path-root/download/path-root-0.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/path-root/download/path-root-0.1.1.tgz", "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", "dev": true, "requires": { @@ -18479,7 +18568,7 @@ }, "path-root-regex": { "version": "0.1.2", - "resolved": "https://registry.nlark.com/path-root-regex/download/path-root-regex-0.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/path-root-regex/download/path-root-regex-0.1.2.tgz", "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", "dev": true }, @@ -18536,19 +18625,19 @@ }, "pify": { "version": "2.3.0", - "resolved": "https://registry.npm.taobao.org/pify/download/pify-2.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/pify/download/pify-2.3.0.tgz?cache=0&sync_timestamp=1581697613983&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fpify%2Fdownload%2Fpify-2.3.0.tgz", "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "dev": true }, "pinkie": { "version": "2.0.4", - "resolved": "https://registry.nlark.com/pinkie/download/pinkie-2.0.4.tgz", + "resolved": "https://registry.npm.taobao.org/pinkie/download/pinkie-2.0.4.tgz", "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", "dev": true }, "pinkie-promise": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/pinkie-promise/download/pinkie-promise-2.0.1.tgz?cache=0&sync_timestamp=1618847023792&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fpinkie-promise%2Fdownload%2Fpinkie-promise-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/pinkie-promise/download/pinkie-promise-2.0.1.tgz", "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", "dev": true, "requires": { @@ -18626,7 +18715,7 @@ }, "portfinder": { "version": "1.0.28", - "resolved": "https://registry.nlark.com/portfinder/download/portfinder-1.0.28.tgz", + "resolved": "https://registry.npm.taobao.org/portfinder/download/portfinder-1.0.28.tgz", "integrity": "sha1-Z8RiKFK9U3TdHdkA93n1NGL6x3g=", "dev": true, "requires": { @@ -18637,7 +18726,7 @@ "dependencies": { "debug": { "version": "3.2.7", - "resolved": "https://registry.npmmirror.com/debug/download/debug-3.2.7.tgz", + "resolved": "https://registry.npm.taobao.org/debug/download/debug-3.2.7.tgz?cache=0&sync_timestamp=1607566580543&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fdebug%2Fdownload%2Fdebug-3.2.7.tgz", "integrity": "sha1-clgLfpFF+zm2Z2+cXl+xALk0F5o=", "dev": true, "requires": { @@ -18657,19 +18746,19 @@ }, "posix-character-classes": { "version": "0.1.1", - "resolved": "https://registry.nlark.com/posix-character-classes/download/posix-character-classes-0.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/posix-character-classes/download/posix-character-classes-0.1.1.tgz", "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", "dev": true }, "prelude-ls": { "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "resolved": "https://registry.npmmirror.com/prelude-ls/-/prelude-ls-1.1.2.tgz", "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", "dev": true }, "pretty-format": { "version": "24.9.0", - "resolved": "https://registry.npmmirror.com/pretty-format/download/pretty-format-24.9.0.tgz", + "resolved": "https://registry.npm.taobao.org/pretty-format/download/pretty-format-24.9.0.tgz", "integrity": "sha1-EvrDGzcBmk7qPBGqmpWet2KKp8k=", "dev": true, "requires": { @@ -18681,7 +18770,7 @@ "dependencies": { "ansi-regex": { "version": "4.1.0", - "resolved": "https://registry.nlark.com/ansi-regex/download/ansi-regex-4.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-regex/download/ansi-regex-4.1.0.tgz", "integrity": "sha1-i5+PCM8ay4Q3Vqg5yox+MWjFGZc=", "dev": true } @@ -18702,7 +18791,7 @@ "process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", "dev": true }, "process-nextick-args": { @@ -18711,6 +18800,12 @@ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "dev": true }, + "progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true + }, "prompts": { "version": "2.4.2", "resolved": "https://registry.npmmirror.com/prompts/-/prompts-2.4.2.tgz", @@ -18721,9 +18816,15 @@ "sisteransi": "^1.0.5" } }, + "proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "dev": true + }, "psl": { "version": "1.8.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "resolved": "https://registry.npmmirror.com/psl/-/psl-1.8.0.tgz", "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", "dev": true }, @@ -18795,7 +18896,7 @@ }, "punycode": { "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", "dev": true }, @@ -18841,7 +18942,7 @@ }, "react-is": { "version": "16.13.1", - "resolved": "https://registry.npmmirror.com/react-is/download/react-is-16.13.1.tgz", + "resolved": "https://registry.npm.taobao.org/react-is/download/react-is-16.13.1.tgz", "integrity": "sha1-eJcppNw23imZ3BVt1sHZwYzqVqQ=", "dev": true }, @@ -18856,7 +18957,7 @@ }, "read-pkg": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/read-pkg/download/read-pkg-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/read-pkg/download/read-pkg-1.1.0.tgz", "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", "dev": true, "requires": { @@ -18867,7 +18968,7 @@ }, "read-pkg-up": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/read-pkg-up/download/read-pkg-up-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/read-pkg-up/download/read-pkg-up-1.0.1.tgz", "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", "dev": true, "requires": { @@ -18877,7 +18978,7 @@ "dependencies": { "find-up": { "version": "1.1.2", - "resolved": "https://registry.npmmirror.com/find-up/download/find-up-1.1.2.tgz?cache=0&sync_timestamp=1633620747957&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Ffind-up%2Fdownload%2Ffind-up-1.1.2.tgz", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { @@ -18887,7 +18988,7 @@ }, "path-exists": { "version": "2.1.0", - "resolved": "https://registry.nlark.com/path-exists/download/path-exists-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "dev": true, "requires": { @@ -18924,7 +19025,7 @@ }, "readdirp": { "version": "2.2.1", - "resolved": "https://registry.nlark.com/readdirp/download/readdirp-2.2.1.tgz", + "resolved": "https://registry.npm.taobao.org/readdirp/download/readdirp-2.2.1.tgz?cache=0&sync_timestamp=1575629866543&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Freaddirp%2Fdownload%2Freaddirp-2.2.1.tgz", "integrity": "sha1-DodiKjMlqjPokihcr4tOhGUppSU=", "dev": true, "requires": { @@ -18935,7 +19036,7 @@ }, "rechoir": { "version": "0.6.2", - "resolved": "https://registry.nlark.com/rechoir/download/rechoir-0.6.2.tgz?cache=0&sync_timestamp=1627101677944&other_urls=https%3A%2F%2Fregistry.nlark.com%2Frechoir%2Fdownload%2Frechoir-0.6.2.tgz", + "resolved": "https://registry.npm.taobao.org/rechoir/download/rechoir-0.6.2.tgz", "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", "dev": true, "requires": { @@ -18975,7 +19076,7 @@ }, "regex-not": { "version": "1.0.2", - "resolved": "https://registry.nlark.com/regex-not/download/regex-not-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/regex-not/download/regex-not-1.0.2.tgz", "integrity": "sha1-H07OJ+ALC2XgJHpoEOaoXYOldSw=", "dev": true, "requires": { @@ -19048,7 +19149,7 @@ "dependencies": { "jsesc": { "version": "0.5.0", - "resolved": "https://registry.nlark.com/jsesc/download/jsesc-0.5.0.tgz", + "resolved": "https://registry.npm.taobao.org/jsesc/download/jsesc-0.5.0.tgz", "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", "dev": true } @@ -19077,7 +19178,7 @@ }, "remove-trailing-separator": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/remove-trailing-separator/download/remove-trailing-separator-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/remove-trailing-separator/download/remove-trailing-separator-1.1.0.tgz", "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", "dev": true }, @@ -19112,7 +19213,7 @@ }, "require-directory": { "version": "2.1.1", - "resolved": "https://registry.nlark.com/require-directory/download/require-directory-2.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/require-directory/download/require-directory-2.1.1.tgz", "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, @@ -19124,7 +19225,7 @@ }, "requires-port": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/requires-port/download/requires-port-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/requires-port/download/requires-port-1.0.0.tgz", "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", "dev": true }, @@ -19180,7 +19281,7 @@ }, "resolve-url": { "version": "0.2.1", - "resolved": "https://registry.npmmirror.com/resolve-url/download/resolve-url-0.2.1.tgz", + "resolved": "https://registry.npm.taobao.org/resolve-url/download/resolve-url-0.2.1.tgz", "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", "dev": true }, @@ -19192,7 +19293,7 @@ }, "ret": { "version": "0.1.15", - "resolved": "https://registry.nlark.com/ret/download/ret-0.1.15.tgz", + "resolved": "https://registry.npm.taobao.org/ret/download/ret-0.1.15.tgz", "integrity": "sha1-uKSCXVvbH8P29Twrwz+BOIaBx7w=", "dev": true }, @@ -19275,7 +19376,7 @@ }, "@babel/highlight": { "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", + "resolved": "https://registry.npmmirror.com/@babel/highlight/-/highlight-7.18.6.tgz", "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", "dev": true, "requires": { @@ -19432,7 +19533,7 @@ }, "safe-buffer": { "version": "5.1.2", - "resolved": "https://registry.nlark.com/safe-buffer/download/safe-buffer-5.1.2.tgz?cache=0&sync_timestamp=1618847044058&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsafe-buffer%2Fdownload%2Fsafe-buffer-5.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/safe-buffer/download/safe-buffer-5.1.2.tgz", "integrity": "sha1-mR7GnSluAxN0fVm9/St0XDX4go0=" }, "safe-regex": { @@ -19487,13 +19588,13 @@ }, "safer-buffer": { "version": "2.1.2", - "resolved": "https://registry.nlark.com/safer-buffer/download/safer-buffer-2.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/safer-buffer/download/safer-buffer-2.1.2.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsafer-buffer%2Fdownload%2Fsafer-buffer-2.1.2.tgz", "integrity": "sha1-RPoWGwGHuVSd2Eu5GAL5vYOFzWo=", "dev": true }, "saxes": { "version": "5.0.1", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", + "resolved": "https://registry.npmmirror.com/saxes/-/saxes-5.0.1.tgz", "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", "dev": true, "requires": { @@ -19514,7 +19615,7 @@ }, "semver-greatest-satisfied-range": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/semver-greatest-satisfied-range/download/semver-greatest-satisfied-range-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/semver-greatest-satisfied-range/download/semver-greatest-satisfied-range-1.1.0.tgz", "integrity": "sha1-E+jCZYq5aRywzXEJMkAoDTb3els=", "dev": true, "requires": { @@ -19532,13 +19633,13 @@ }, "set-blocking": { "version": "2.0.0", - "resolved": "https://registry.nlark.com/set-blocking/download/set-blocking-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/set-blocking/download/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, "set-value": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/set-value/download/set-value-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/set-value/download/set-value-2.0.1.tgz", "integrity": "sha1-oY1AUw5vB95CKMfe/kInr4ytAFs=", "dev": true, "requires": { @@ -19550,7 +19651,7 @@ "dependencies": { "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -19612,7 +19713,7 @@ }, "side-channel": { "version": "1.0.4", - "resolved": "https://registry.nlark.com/side-channel/download/side-channel-1.0.4.tgz", + "resolved": "https://registry.npm.taobao.org/side-channel/download/side-channel-1.0.4.tgz", "integrity": "sha1-785cj9wQTudRslxY1CkAEfpeos8=", "dev": true, "requires": { @@ -19654,12 +19755,12 @@ }, "slash": { "version": "3.0.0", - "resolved": "https://registry.nlark.com/slash/download/slash-3.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/slash/download/slash-3.0.0.tgz", "integrity": "sha1-ZTm+hwwWWtvVJAIg2+Nh8bxNRjQ=" }, "snapdragon": { "version": "0.8.2", - "resolved": "https://registry.npm.taobao.org/snapdragon/download/snapdragon-0.8.2.tgz?cache=0&sync_timestamp=1617971785350&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsnapdragon%2Fdownload%2Fsnapdragon-0.8.2.tgz", + "resolved": "https://registry.npm.taobao.org/snapdragon/download/snapdragon-0.8.2.tgz", "integrity": "sha1-ZJIufFZbDhQgS6GqfWlkJ40lGC0=", "dev": true, "requires": { @@ -19675,7 +19776,7 @@ "dependencies": { "debug": { "version": "2.6.9", - "resolved": "https://registry.npmmirror.com/debug/download/debug-2.6.9.tgz", + "resolved": "https://registry.npm.taobao.org/debug/download/debug-2.6.9.tgz", "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", "dev": true, "requires": { @@ -19693,7 +19794,7 @@ }, "extend-shallow": { "version": "2.0.1", - "resolved": "https://registry.nlark.com/extend-shallow/download/extend-shallow-2.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { @@ -19702,7 +19803,7 @@ }, "ms": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/ms/download/ms-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/ms/download/ms-2.0.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fms%2Fdownload%2Fms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true } @@ -19730,7 +19831,7 @@ }, "is-accessor-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", "dev": true, "requires": { @@ -19739,7 +19840,7 @@ }, "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz", "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", "dev": true, "requires": { @@ -19761,7 +19862,7 @@ }, "snapdragon-util": { "version": "3.0.1", - "resolved": "https://registry.nlark.com/snapdragon-util/download/snapdragon-util-3.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/snapdragon-util/download/snapdragon-util-3.0.1.tgz", "integrity": "sha1-+VZHlIbyrNeXAGk/b3uAXkWrVuI=", "dev": true, "requires": { @@ -19830,7 +19931,7 @@ }, "sparkles": { "version": "1.0.1", - "resolved": "https://registry.nlark.com/sparkles/download/sparkles-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/sparkles/download/sparkles-1.0.1.tgz", "integrity": "sha1-AI22XtzmxQ7sDF4ijhlFBh3QQ3w=", "dev": true }, @@ -19874,7 +19975,7 @@ }, "split-string": { "version": "3.1.0", - "resolved": "https://registry.nlark.com/split-string/download/split-string-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/split-string/download/split-string-3.1.0.tgz", "integrity": "sha1-fLCd2jqGWFcFxks5pkZgOGguj+I=", "dev": true, "requires": { @@ -19883,13 +19984,13 @@ }, "sprintf-js": { "version": "1.0.3", - "resolved": "https://registry.nlark.com/sprintf-js/download/sprintf-js-1.0.3.tgz?cache=0&sync_timestamp=1618847174560&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsprintf-js%2Fdownload%2Fsprintf-js-1.0.3.tgz", + "resolved": "https://registry.npm.taobao.org/sprintf-js/download/sprintf-js-1.0.3.tgz", "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, "stack-trace": { "version": "0.0.10", - "resolved": "https://registry.nlark.com/stack-trace/download/stack-trace-0.0.10.tgz?cache=0&sync_timestamp=1620387179562&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fstack-trace%2Fdownload%2Fstack-trace-0.0.10.tgz", + "resolved": "https://registry.npm.taobao.org/stack-trace/download/stack-trace-0.0.10.tgz", "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", "dev": true }, @@ -19904,7 +20005,7 @@ "dependencies": { "escape-string-regexp": { "version": "2.0.0", - "resolved": "https://registry.nlark.com/escape-string-regexp/download/escape-string-regexp-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/escape-string-regexp/download/escape-string-regexp-2.0.0.tgz", "integrity": "sha1-owME6Z2qMuI7L9IPUbq9B8/8o0Q=", "dev": true } @@ -20160,7 +20261,7 @@ "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -20211,7 +20312,7 @@ "dependencies": { "call-bind": { "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "requires": { @@ -20275,7 +20376,7 @@ }, "strip-eof": { "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/strip-eof/download/strip-eof-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/strip-eof/download/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", "dev": true }, @@ -20301,7 +20402,7 @@ }, "supports-color": { "version": "5.5.0", - "resolved": "https://registry.npmmirror.com/supports-color/download/supports-color-5.5.0.tgz", + "resolved": "https://registry.npm.taobao.org/supports-color/download/supports-color-5.5.0.tgz", "integrity": "sha1-4uaaRKyHcveKHsCzW2id9lMO/I8=", "requires": { "has-flag": "^3.0.0" @@ -20336,7 +20437,7 @@ }, "supports-preserve-symlinks-flag": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" }, "sver-compat": { @@ -20351,7 +20452,7 @@ }, "symbol-tree": { "version": "3.2.4", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "resolved": "https://registry.npmmirror.com/symbol-tree/-/symbol-tree-3.2.4.tgz", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, @@ -20364,6 +20465,28 @@ "acorn-node": "^1.2.0" } }, + "tar": { + "version": "6.1.15", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.15.tgz", + "integrity": "sha512-/zKt9UyngnxIT/EAGYuxaMYgOIJiP81ab9ZfkILq4oNLPFX50qyYmu7jRj9qeXoxmJHjGlbH0+cm2uy1WCs10A==", + "dev": true, + "requires": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "dependencies": { + "minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "dev": true + } + } + }, "terminal-link": { "version": "2.1.1", "resolved": "https://registry.npmmirror.com/terminal-link/-/terminal-link-2.1.1.tgz", @@ -20400,7 +20523,7 @@ }, "source-map-support": { "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "resolved": "https://registry.npmmirror.com/source-map-support/download/source-map-support-0.5.21.tgz", "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", "dev": true, "requires": { @@ -20423,7 +20546,7 @@ }, "text-table": { "version": "0.2.0", - "resolved": "https://registry.nlark.com/text-table/download/text-table-0.2.0.tgz?cache=0&sync_timestamp=1618847142316&other_urls=https%3A%2F%2Fregistry.nlark.com%2Ftext-table%2Fdownload%2Ftext-table-0.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/text-table/download/text-table-0.2.0.tgz", "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" }, "tfig": { @@ -20439,13 +20562,13 @@ "dependencies": { "ansi-regex": { "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-4.1.1.tgz", "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", "dev": true }, "cliui": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "resolved": "https://registry.npmmirror.com/cliui/-/cliui-5.0.0.tgz", "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", "dev": true, "requires": { @@ -20456,25 +20579,25 @@ }, "emoji-regex": { "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-7.0.3.tgz", "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", "dev": true }, "get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "resolved": "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, "require-main-filename": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, "string-width": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/string-width/-/string-width-3.1.0.tgz", "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", "dev": true, "requires": { @@ -20485,7 +20608,7 @@ }, "strip-ansi": { "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-5.2.0.tgz", "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "dev": true, "requires": { @@ -20500,7 +20623,7 @@ }, "wrap-ansi": { "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-5.1.0.tgz", "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", "dev": true, "requires": { @@ -20511,13 +20634,13 @@ }, "y18n": { "version": "4.0.3", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "resolved": "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz", "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true }, "yargs": { "version": "13.3.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", + "resolved": "https://registry.npmmirror.com/yargs/-/yargs-13.3.2.tgz", "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", "dev": true, "requires": { @@ -20535,7 +20658,7 @@ }, "yargs-parser": { "version": "13.1.2", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", + "resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-13.1.2.tgz", "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", "dev": true, "requires": { @@ -20585,7 +20708,7 @@ }, "time-stamp": { "version": "1.1.0", - "resolved": "https://registry.nlark.com/time-stamp/download/time-stamp-1.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/time-stamp/download/time-stamp-1.1.0.tgz", "integrity": "sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=", "dev": true }, @@ -20609,13 +20732,13 @@ }, "tmpl": { "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "resolved": "https://registry.npmmirror.com/tmpl/-/tmpl-1.0.5.tgz", "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", "dev": true }, "to-absolute-glob": { "version": "2.0.2", - "resolved": "https://registry.nlark.com/to-absolute-glob/download/to-absolute-glob-2.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/to-absolute-glob/download/to-absolute-glob-2.0.2.tgz", "integrity": "sha1-GGX0PZ50sIItufFFt4z/fQ98hJs=", "dev": true, "requires": { @@ -20625,12 +20748,12 @@ }, "to-fast-properties": { "version": "2.0.0", - "resolved": "https://registry.nlark.com/to-fast-properties/download/to-fast-properties-2.0.0.tgz?cache=0&sync_timestamp=1628418893613&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fto-fast-properties%2Fdownload%2Fto-fast-properties-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/to-fast-properties/download/to-fast-properties-2.0.0.tgz", "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=" }, "to-object-path": { "version": "0.3.0", - "resolved": "https://registry.nlark.com/to-object-path/download/to-object-path-0.3.0.tgz", + "resolved": "https://registry.npm.taobao.org/to-object-path/download/to-object-path-0.3.0.tgz", "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", "dev": true, "requires": { @@ -20650,7 +20773,7 @@ }, "to-regex": { "version": "3.0.2", - "resolved": "https://registry.nlark.com/to-regex/download/to-regex-3.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/to-regex/download/to-regex-3.0.2.tgz", "integrity": "sha1-E8/dmzNlUvMLUfM6iuG0Knp1mc4=", "dev": true, "requires": { @@ -20681,7 +20804,7 @@ }, "tough-cookie": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", + "resolved": "https://registry.npmmirror.com/tough-cookie/-/tough-cookie-4.0.0.tgz", "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", "dev": true, "requires": { @@ -20722,13 +20845,13 @@ "dependencies": { "mkdirp": { "version": "1.0.4", - "resolved": "https://registry.npmmirror.com/mkdirp/download/mkdirp-1.0.4.tgz", + "resolved": "https://registry.npm.taobao.org/mkdirp/download/mkdirp-1.0.4.tgz?cache=0&sync_timestamp=1587535418745&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmkdirp%2Fdownload%2Fmkdirp-1.0.4.tgz", "integrity": "sha1-PrXtYmInVteaXw4qIh3+utdcL34=", "dev": true }, "semver": { "version": "7.3.5", - "resolved": "https://registry.nlark.com/semver/download/semver-7.3.5.tgz?cache=0&sync_timestamp=1618846864940&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fsemver%2Fdownload%2Fsemver-7.3.5.tgz", + "resolved": "https://registry.npm.taobao.org/semver/download/semver-7.3.5.tgz?cache=0&sync_timestamp=1616463603361&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsemver%2Fdownload%2Fsemver-7.3.5.tgz", "integrity": "sha1-C2Ich5NI2JmOSw5L6Us/EuYBjvc=", "dev": true, "requires": { @@ -21120,7 +21243,7 @@ }, "unc-path-regex": { "version": "0.1.2", - "resolved": "https://registry.nlark.com/unc-path-regex/download/unc-path-regex-0.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/unc-path-regex/download/unc-path-regex-0.1.2.tgz", "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", "dev": true }, @@ -21190,7 +21313,7 @@ }, "union": { "version": "0.5.0", - "resolved": "https://registry.nlark.com/union/download/union-0.5.0.tgz", + "resolved": "https://registry.npm.taobao.org/union/download/union-0.5.0.tgz", "integrity": "sha1-ssEb6E9gU4U3uEbtuboma6AJAHU=", "dev": true, "requires": { @@ -21199,7 +21322,7 @@ }, "union-value": { "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/union-value/download/union-value-1.0.1.tgz", + "resolved": "https://registry.npm.taobao.org/union-value/download/union-value-1.0.1.tgz", "integrity": "sha1-C2/nuDWuzaYcbqTU8CwUIh4QmEc=", "dev": true, "requires": { @@ -21221,13 +21344,13 @@ }, "universalify": { "version": "0.1.2", - "resolved": "https://registry.nlark.com/universalify/download/universalify-0.1.2.tgz", + "resolved": "https://registry.npm.taobao.org/universalify/download/universalify-0.1.2.tgz", "integrity": "sha1-tkb2m+OULavOzJ1mOcgNwQXvqmY=", "dev": true }, "unset-value": { "version": "1.0.0", - "resolved": "https://registry.nlark.com/unset-value/download/unset-value-1.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/unset-value/download/unset-value-1.0.0.tgz", "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", "dev": true, "requires": { @@ -21237,7 +21360,7 @@ "dependencies": { "has-value": { "version": "0.3.1", - "resolved": "https://registry.nlark.com/has-value/download/has-value-0.3.1.tgz", + "resolved": "https://registry.npm.taobao.org/has-value/download/has-value-0.3.1.tgz", "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", "dev": true, "requires": { @@ -21259,7 +21382,7 @@ }, "has-values": { "version": "0.1.4", - "resolved": "https://registry.nlark.com/has-values/download/has-values-0.1.4.tgz", + "resolved": "https://registry.npm.taobao.org/has-values/download/has-values-0.1.4.tgz", "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", "dev": true }, @@ -21273,7 +21396,7 @@ }, "upath": { "version": "1.2.0", - "resolved": "https://registry.npm.taobao.org/upath/download/upath-1.2.0.tgz", + "resolved": "https://registry.npm.taobao.org/upath/download/upath-1.2.0.tgz?cache=0&sync_timestamp=1567457281208&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fupath%2Fdownload%2Fupath-1.2.0.tgz", "integrity": "sha1-j2bbzVWog6za5ECK+LA1pQRMGJQ=", "dev": true }, @@ -21303,7 +21426,7 @@ }, "urix": { "version": "0.1.0", - "resolved": "https://registry.npmmirror.com/urix/download/urix-0.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/urix/download/urix-0.1.0.tgz", "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", "dev": true }, @@ -21327,13 +21450,13 @@ }, "url-join": { "version": "2.0.5", - "resolved": "https://registry.nlark.com/url-join/download/url-join-2.0.5.tgz", + "resolved": "https://registry.npm.taobao.org/url-join/download/url-join-2.0.5.tgz", "integrity": "sha1-WvIvGMBSoACkjXuCxenC4v7tpyg=", "dev": true }, "use": { "version": "3.1.1", - "resolved": "https://registry.nlark.com/use/download/use-3.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/use/download/use-3.1.1.tgz", "integrity": "sha1-1QyMrHmhn7wg8pEfVuuXP04QBw8=", "dev": true }, @@ -21348,7 +21471,7 @@ "dependencies": { "inherits": { "version": "2.0.3", - "resolved": "https://registry.nlark.com/inherits/download/inherits-2.0.3.tgz", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "dev": true } @@ -21356,7 +21479,7 @@ }, "util-deprecate": { "version": "1.0.2", - "resolved": "https://registry.nlark.com/util-deprecate/download/util-deprecate-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/util-deprecate/download/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "dev": true }, @@ -21382,7 +21505,7 @@ }, "validate-npm-package-license": { "version": "3.0.4", - "resolved": "https://registry.nlark.com/validate-npm-package-license/download/validate-npm-package-license-3.0.4.tgz", + "resolved": "https://registry.npm.taobao.org/validate-npm-package-license/download/validate-npm-package-license-3.0.4.tgz", "integrity": "sha1-/JH2uce6FchX9MssXe/uw51PQQo=", "dev": true, "requires": { @@ -21392,7 +21515,7 @@ }, "value-or-function": { "version": "3.0.0", - "resolved": "https://registry.nlark.com/value-or-function/download/value-or-function-3.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/value-or-function/download/value-or-function-3.0.0.tgz", "integrity": "sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM=", "dev": true }, @@ -21537,7 +21660,7 @@ }, "w3c-hr-time": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", "dev": true, "requires": { @@ -21769,7 +21892,7 @@ }, "wrappy": { "version": "1.0.2", - "resolved": "https://registry.nlark.com/wrappy/download/wrappy-1.0.2.tgz?cache=0&sync_timestamp=1619133505879&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fwrappy%2Fdownload%2Fwrappy-1.0.2.tgz", + "resolved": "https://registry.npm.taobao.org/wrappy/download/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { @@ -21792,7 +21915,7 @@ }, "xmlchars": { "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "resolved": "https://registry.npmmirror.com/xmlchars/-/xmlchars-2.2.0.tgz", "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "dev": true }, @@ -21816,12 +21939,12 @@ }, "yallist": { "version": "4.0.0", - "resolved": "https://registry.nlark.com/yallist/download/yallist-4.0.0.tgz?cache=0&sync_timestamp=1622604530774&other_urls=https%3A%2F%2Fregistry.nlark.com%2Fyallist%2Fdownload%2Fyallist-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/yallist/download/yallist-4.0.0.tgz", "integrity": "sha1-m7knkNnA7/7GO+c1GeEaNQGaOnI=" }, "yargs": { "version": "12.0.5", - "resolved": "https://registry.npmmirror.com/yargs/download/yargs-12.0.5.tgz?cache=0&sync_timestamp=1632605487521&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fyargs%2Fdownload%2Fyargs-12.0.5.tgz", + "resolved": "https://registry.npm.taobao.org/yargs/download/yargs-12.0.5.tgz?cache=0&sync_timestamp=1583129847322&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fyargs%2Fdownload%2Fyargs-12.0.5.tgz", "integrity": "sha1-BfWZe2CWR7ZPZrgeO0sQo2jnrRM=", "dev": true, "requires": { @@ -21841,13 +21964,13 @@ "dependencies": { "ansi-regex": { "version": "3.0.0", - "resolved": "https://registry.nlark.com/ansi-regex/download/ansi-regex-3.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/ansi-regex/download/ansi-regex-3.0.0.tgz?cache=0&sync_timestamp=1570188663907&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-regex%2Fdownload%2Fansi-regex-3.0.0.tgz", "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", "dev": true }, "cliui": { "version": "4.1.0", - "resolved": "https://registry.nlark.com/cliui/download/cliui-4.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/cliui/download/cliui-4.1.0.tgz?cache=0&sync_timestamp=1573943292170&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcliui%2Fdownload%2Fcliui-4.1.0.tgz", "integrity": "sha1-NIQi2+gtgAswIu709qwQvy5NG0k=", "dev": true, "requires": { @@ -21867,13 +21990,13 @@ }, "invert-kv": { "version": "2.0.0", - "resolved": "https://registry.nlark.com/invert-kv/download/invert-kv-2.0.0.tgz?cache=0&sync_timestamp=1630996809231&other_urls=https%3A%2F%2Fregistry.nlark.com%2Finvert-kv%2Fdownload%2Finvert-kv-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/invert-kv/download/invert-kv-2.0.0.tgz", "integrity": "sha1-c5P1r6Weyf9fZ6J2INEcIm4+7AI=", "dev": true }, "lcid": { "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/lcid/download/lcid-2.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/lcid/download/lcid-2.0.0.tgz", "integrity": "sha1-bvXS32DlL4LrIopMNz6NHzlyU88=", "dev": true, "requires": { @@ -21892,7 +22015,7 @@ }, "os-locale": { "version": "3.1.0", - "resolved": "https://registry.npmmirror.com/os-locale/download/os-locale-3.1.0.tgz?cache=0&sync_timestamp=1633618260196&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fos-locale%2Fdownload%2Fos-locale-3.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/os-locale/download/os-locale-3.1.0.tgz", "integrity": "sha1-qAKm7hfyTBBIOrmTVxnO9O0Wvxo=", "dev": true, "requires": { @@ -21918,7 +22041,7 @@ }, "string-width": { "version": "2.1.1", - "resolved": "https://registry.npmmirror.com/string-width/download/string-width-2.1.1.tgz?cache=0&sync_timestamp=1632421309919&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fstring-width%2Fdownload%2Fstring-width-2.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/string-width/download/string-width-2.1.1.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstring-width%2Fdownload%2Fstring-width-2.1.1.tgz", "integrity": "sha1-q5Pyeo3BPSjKyBXEYhQ6bZASrp4=", "dev": true, "requires": { @@ -21928,7 +22051,7 @@ }, "strip-ansi": { "version": "4.0.0", - "resolved": "https://registry.npmmirror.com/strip-ansi/download/strip-ansi-4.0.0.tgz", + "resolved": "https://registry.npm.taobao.org/strip-ansi/download/strip-ansi-4.0.0.tgz?cache=0&sync_timestamp=1573280518303&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstrip-ansi%2Fdownload%2Fstrip-ansi-4.0.0.tgz", "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { @@ -21949,7 +22072,7 @@ }, "yargs-parser": { "version": "11.1.1", - "resolved": "https://registry.npmmirror.com/yargs-parser/download/yargs-parser-11.1.1.tgz?cache=0&sync_timestamp=1637031045984&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fyargs-parser%2Fdownload%2Fyargs-parser-11.1.1.tgz", + "resolved": "https://registry.npm.taobao.org/yargs-parser/download/yargs-parser-11.1.1.tgz?cache=0&sync_timestamp=1583130314354&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fyargs-parser%2Fdownload%2Fyargs-parser-11.1.1.tgz", "integrity": "sha1-h5oIZZc7yp9rq1y987HGfsfTvPQ=", "dev": true, "requires": { diff --git a/package.json b/package.json index 2a7ceb35714..6276d27946c 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,7 @@ "@typescript-eslint/eslint-plugin": "^6.0.0", "@typescript-eslint/parser": "^6.0.0", "async": "^2.6.4", + "axios": "^1.4.0", "babelify": "^10.0.0", "browserify": "^17.0.0", "chalk": "^2.4.1", @@ -69,10 +70,13 @@ "jest-extended": "^1.1.0", "jest-matcher-deep-close-to": "^2.0.1", "jsdom": "^19.0.0", + "node-fetch": "^2.6.1", "path": "^0.12.7", "pngjs": "^6.0.0", + "progress": "^2.0.3", "spectorjs": "^0.9.15", "stats.js": "^0.17.0", + "tar": "^6.1.15", "tmp": "^0.2.1", "tree-kill": "^1.2.0", "ts-jest": "^26.5.4", From ebbba606ca3d5b2c35d8cb2d7d59d2aad1955dd7 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Thu, 20 Jul 2023 16:33:16 +0800 Subject: [PATCH 054/232] Fix videoplayer status after pause&finish (#15782) * fix videoplayer.isplaying status after pause * fix isPlaying status when play video finish --- cocos/video/video-player-impl.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/video/video-player-impl.ts b/cocos/video/video-player-impl.ts index ac921c4828f..cc9a4ba7d64 100644 --- a/cocos/video/video-player-impl.ts +++ b/cocos/video/video-player-impl.ts @@ -163,11 +163,11 @@ export abstract class VideoPlayerImpl { } public onPause (e: Event): void { + this._playing = false; if (this._ignorePause) { this._ignorePause = false; return; } - this._playing = false; this.dispatchEvent(EventType.PAUSED); } @@ -178,6 +178,7 @@ export abstract class VideoPlayerImpl { } public onEnded (e: Event): void { + this._playing = false; this.dispatchEvent(EventType.COMPLETED); } @@ -193,7 +194,6 @@ export abstract class VideoPlayerImpl { } } - // public play (): void { if (this._loadedMeta || this._loaded) { this.canPlay(); From 6d666d2f1dfda58a354efb16892ec0898d7480f4 Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Thu, 20 Jul 2023 17:32:12 +0800 Subject: [PATCH 055/232] Fix the problem of incorrect screen resolution after resize. (#15785) --- native/cocos/engine/Engine.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index f376d142c1d..50d34212923 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -323,10 +323,12 @@ bool Engine::redirectWindowEvent(const WindowEvent &ev) { isHandled = true; } else if (ev.type == WindowEvent::Type::SIZE_CHANGED || ev.type == WindowEvent::Type::RESIZED) { - events::Resize::broadcast(ev.width, ev.height, ev.windowId); auto *w = CC_GET_SYSTEM_WINDOW(ev.windowId); CC_ASSERT(w); w->setViewSize(ev.width, ev.height); + // Because the ts layer calls the getviewsize interface in response to resize. + // So we need to set the view size when sending the message. + events::Resize::broadcast(ev.width, ev.height, ev.windowId); isHandled = true; } else if (ev.type == WindowEvent::Type::HIDDEN || ev.type == WindowEvent::Type::MINIMIZED) { From 9cffcaa84cc21b0470432b76f54d6adc0c40ab92 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Thu, 20 Jul 2023 19:08:32 +0800 Subject: [PATCH 056/232] add multi-layers lighting model and fix direct specular (#15778) --- .../assets/chunks/common/lighting/brdf.chunk | 27 +- .../assets/chunks/common/lighting/bxdf.chunk | 49 ++- .../lighting-intermediate-data.chunk | 11 +- .../data-structures/lighting-result.chunk | 28 +- .../lighting-flow/common-flow.chunk | 57 ++- .../model-functions/standard.chunk | 105 ++++- .../model-functions/toon.chunk | 18 + .../surfaces/data-structures/standard.chunk | 7 +- .../default-functions/standard-fs.chunk | 45 +- .../effect-macros/common-macros.chunk | 11 +- .../module-functions/debug-view.chunk | 31 +- .../module-functions/standard-fs.chunk | 115 ++++-- .../surfaces/module-functions/toon-fs.chunk | 11 +- .../surfaces/module-functions/unlit-fs.chunk | 6 +- .../assets/effects/advanced/car-paint.effect | 383 ++++++++++++++++++ .../effects/advanced/car-paint.effect.meta | 11 + editor/assets/effects/advanced/glass.effect | 354 ++++++++++++++++ .../assets/effects/advanced/glass.effect.meta | 11 + editor/assets/effects/advanced/hair.effect | 2 +- .../dcc/vat/houdini-fluid-v3-liquid.effect | 2 +- .../util/dcc/vat/zeno-fluid-liquid.effect | 2 +- 21 files changed, 1186 insertions(+), 100 deletions(-) create mode 100644 editor/assets/effects/advanced/car-paint.effect create mode 100644 editor/assets/effects/advanced/car-paint.effect.meta create mode 100644 editor/assets/effects/advanced/glass.effect create mode 100644 editor/assets/effects/advanced/glass.effect.meta diff --git a/editor/assets/chunks/common/lighting/brdf.chunk b/editor/assets/chunks/common/lighting/brdf.chunk index 976a93914bc..ef4fea792a1 100644 --- a/editor/assets/chunks/common/lighting/brdf.chunk +++ b/editor/assets/chunks/common/lighting/brdf.chunk @@ -1,5 +1,6 @@ #include +// for dielectric(non-metal) surfaces float F0ToIor(float F0) { return 2.0f / (1.0f - sqrt(F0)) - 1.0f; @@ -11,9 +12,15 @@ float IorToF0(float ior) return F0_sqrt * F0_sqrt; } -float V_Kelemen(float LoH) +float square(float a) { return a * a;} +vec2 square(vec2 a) { return a * a;} +vec3 square(vec3 a) { return a * a;} +float G_Schlick( float roughness, float NoV, float NoL ) { - return 0.25 / (LoH * LoH); + float k = square( 0.5 + 0.5*roughness ); + float G_SchlickV = NoV * (1.0 - k) + k; + float G_SchlickL = NoL * (1.0 - k) + k; + return 0.25 / ( G_SchlickV * G_SchlickL ); } vec3 F_Schlick( vec3 specularColor, float VoH ) @@ -22,6 +29,12 @@ vec3 F_Schlick( vec3 specularColor, float VoH ) float selfShadowTerm = saturate(50.0 * specularColor.g); return specularColor * (1.0 - Fc) + vec3(selfShadowTerm * Fc); } +vec3 F_SchlickMultiplier( vec3 specularColor, float VoH ) +{ + float Fc = exp2( (-5.55473 * VoH - 6.98316) * VoH ); + float selfShadowTerm = saturate(50.0 * specularColor.g); + return vec3(1.0 - Fc) + vec3(selfShadowTerm * Fc) / (specularColor + vec3(EPSILON)); +} float D_GGX(float roughness, float NoH) { @@ -92,6 +105,16 @@ vec3 IntegratedGFApprox (vec3 specular, float roughness, float NoV) { AB.y *= clamp(50.0 * specular.g, 0.0, 1.0); return max(vec3(0.0), specular * AB.x + AB.y); } +void IntegratedGFMultiplier (out vec3 integratedGF, out vec3 integratedF, vec3 specular, float roughness, float NoV) { + const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022); + const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04); + vec4 r = roughness * c0 + c1; + float a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y; + vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw; + AB.y *= clamp(50.0 * specular.g, 0.0, 1.0); + integratedF = vec3(max(0.0, AB.x)); + integratedGF = max(vec3(0.0), vec3(AB.x) + vec3(AB.y) / (specular + EPSILON_LOWP)); +} //Diffuse_Lambert #define DiffuseCoefficient_EnergyConservation INV_PI diff --git a/editor/assets/chunks/common/lighting/bxdf.chunk b/editor/assets/chunks/common/lighting/bxdf.chunk index b3fd91dfbc7..ba06af07417 100644 --- a/editor/assets/chunks/common/lighting/bxdf.chunk +++ b/editor/assets/chunks/common/lighting/bxdf.chunk @@ -1,5 +1,6 @@ // saturated N dot V +// for env reflection with dielectric(non-metal) and smooth surfaces float CalculateFresnelCoefficient(float ior, float NoVSat) { float g, c, n, prev, next; @@ -13,11 +14,49 @@ float CalculateFresnelCoefficient(float ior, float NoVSat) return 0.5 * prev * (1.0 + next); } +// for arbitary smooth surfaces +float CalculateFresnelCoefficient(float F0, float F90, float NoVSat) +{ + return mix(F90, F0, NoVSat); +} + vec3 CalculateScattering(vec3 unscatteredColor, float distance, float outScatterExtinctCoef, float inScatterExtinctCoef, float inScatterCoef, vec3 inScatterColor, vec3 outScatterColor) { - vec2 e = vec2(outScatterExtinctCoef, inScatterExtinctCoef * inScatterCoef); - vec2 extinction = exp(-e * distance); - vec3 inScattered = (1.0 - extinction.y) * inScatterColor; - vec3 outScattered = unscatteredColor * extinction.x * outScatterColor; - return outScattered + inScattered; + vec2 e = vec2(outScatterExtinctCoef, inScatterExtinctCoef * inScatterCoef); + vec2 extinction = exp(-e * distance); + vec3 inScattered = (1.0 - extinction.y) * inScatterColor; + vec3 outScattered = unscatteredColor * extinction.x * outScatterColor; + return outScattered + inScattered; +} + + +// LastLayerF for temporary use +// S is spec without GF +void InitializeLayerBlending(out vec3 blendedBaseLayerD, out vec3 blendedBaseLayerS, + out vec3 blendedSubLayerD, out vec3 blendedSubLayerS, + out vec3 lastLayerF, + in vec3 baseD, in vec3 baseS + ) +{ + blendedBaseLayerD = baseD; + blendedBaseLayerS = baseS; + blendedSubLayerD = blendedSubLayerS = vec3(0.0); + lastLayerF = vec3(1.0); +} + +// use subLayerF instead of subLayerGF for ior-dependent 0-1 range +void CalculateLayerBlending(inout vec3 blendedBaseLayerD, inout vec3 blendedBaseLayerS, + inout vec3 blendedSubLayerD, inout vec3 blendedSubLayerS, + inout vec3 lastLayerF, + in vec3 subLayerD, in vec3 subLayerDiffuseColor, + in vec3 subLayerS, in vec3 subLayerSpecularColor, + in float subLayerOpacity, inout vec3 subLayerF + ) +{ + subLayerF = saturate(subLayerF * subLayerOpacity); + blendedSubLayerD = blendedSubLayerD * (vec3(1.0) - lastLayerF) + subLayerD * subLayerDiffuseColor * subLayerF; + blendedSubLayerS = blendedSubLayerS *(vec3(1.0) - lastLayerF) + subLayerS * subLayerSpecularColor * subLayerF; + blendedBaseLayerD *= vec3(1.0) - subLayerF; + blendedBaseLayerS *= vec3(1.0) - subLayerF; + lastLayerF = subLayerF; } diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk index 7a4b39bd1a9..54e54b14bbf 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk @@ -5,9 +5,9 @@ struct LightingIntermediateData float distToCamera, distToCameraSqr; // pos->camera float angleAttenuation, distAttenuation; - float NoL, NoV, NoH;//, VoH; + float NoL, NoV, NoH, VoH; float NoLSat, NoVSat, NoHSat;//, VoHSat; // clamped to 0-1 - float NoVAbsSat; // abs and clamped to 1 + float NoVAbsSat, VoHAbsSat; // abs and clamped to 1 HIGHP_VALUE_STRUCT_DEFINE(vec3, worldPosition); @@ -16,7 +16,8 @@ struct LightingIntermediateData // material data float specularParam; // roughness or specular power - float ior; + // todo: add F0 & F90 + float ior, layerOpacity; #if CC_SURFACES_LIGHTING_ANISOTROPIC float anisotropyShape; @@ -92,9 +93,11 @@ void CCSurfacesLightingGetIntermediateData_PerLight(inout LightingIntermediateDa // dot data.NoL = dot(data.N, data.L); data.NoH = dot(data.N, data.H); - // data.VoH = dot(data.V, data.H); + data.VoH = dot(data.V, data.H); data.NoLSat = max(data.NoL, 0.0); data.NoHSat = max(data.NoH, 0.0); // data.VoHSat = max(data.VoH, 0.0); + + data.VoHAbsSat = max(abs(data.VoH), 0.0); } diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk index 6ab96c09d35..d6310b378a2 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk @@ -1,18 +1,21 @@ struct LightingResult { // material-dependent lighting data - vec3 diffuseColorWithLighting, specularColorWithLighting, specularColorWithEnvLighting; + vec3 diffuseColorWithLighting, specularColorWithLighting; // pure lighting - vec3 directDiffuse, directSpecular; - vec3 environmentDiffuse, environmentSpecular; + vec3 directDiffuse, directSpecular, directGF; + vec3 environmentDiffuse, environmentSpecular, environmentGF; float shadow, ao; vec3 lightmapColor; vec3 emissive; // advanced -#if CC_SURFACES_LIGHTING_USE_FRESNEL - float fresnel; + vec3 fresnel; // for transmit materials , rim or special effects + +#if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + vec3 directDiffuseSubLayers, directSpecularSubLayers; + vec3 environmentDiffuseSubLayers, environmentSpecularSubLayers; #endif #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR @@ -20,10 +23,12 @@ struct LightingResult #endif #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE vec3 directTransmitDiffuse, environmentTransmitDiffuse; -#endif +#endif #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR vec3 direct2ndSpecular, environment2ndSpecular; - vec3 specularColorWithLighting2ndSpecular, specularColorWithEnvLighting2ndSpecular; + vec3 specularColorWithLighting2ndSpecular; + vec3 directGF2ndSpecular, environmentGF2ndSpecular; + vec3 directSubLayerF, environmentSubLayerF; #endif #if CC_SURFACES_LIGHTING_TT vec3 directTT; @@ -31,3 +36,12 @@ struct LightingResult #endif //vec3 scattered; }; + + +/* for multi-layer materials, should define: +struct LightingResultPerLayer +{ + vec3 diffuseColorWithLighting, specularColorWithLighting; + vec3 directDiffuse, directSpecular, directGF; + vec3 environmentDiffuse, environmentSpecular, environmentGF; +}*/ diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index a9a6316003a..d21d83c428d 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -11,16 +11,15 @@ CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData); LightingResult lightingResult; - CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, lightingResult.specularColorWithEnvLighting, surfaceData, lightingData); + CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); lightingResultAccumulated.diffuseColorWithLighting = lightingResult.diffuseColorWithLighting; lightingResultAccumulated.specularColorWithLighting = lightingResult.specularColorWithLighting; - lightingResultAccumulated.specularColorWithEnvLighting = lightingResult.specularColorWithEnvLighting; #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR vec3 diff; SurfacesMaterialData surfaceData2ndSpecular; CCSurfacesGetSurfacesMaterialData2ndSpecular(surfaceData2ndSpecular, surfaceData); - CCSurfacesLightingInitializeColorWithLighting(diff, lightingResultAccumulated.specularColorWithLighting2ndSpecular, lightingResultAccumulated.specularColorWithEnvLighting2ndSpecular, surfaceData2ndSpecular, lightingData); + CCSurfacesLightingInitializeColorWithLighting(diff, lightingResultAccumulated.specularColorWithLighting2ndSpecular, surfaceData2ndSpecular, lightingData); #endif int numLights = CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD ? LIGHTS_PER_PASS : int(cc_lightDir[0].w); @@ -29,15 +28,18 @@ vec3 lightDirWithLength = IS_RANGED_DIRECTIONAL_LIGHT(cc_lightPos[i].w) ? -normalize(cc_lightDir[i].xyz) : cc_lightPos[i].xyz - worldPos; CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, lightDirWithLength); - CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, lightingResult.specularColorWithEnvLighting, surfaceData, lightingData); + CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); vec3 diffuseLighting, specularLighting; CCSurfacesLightingCalculateDirect(diffuseLighting, specularLighting, lightingData, cc_lightColor[i]); - float fresnel = 1.0; #if CC_SURFACES_LIGHTING_USE_FRESNEL - fresnel = lightingResult.fresnel = CCSurfaceLightingCalculateFresnel(lightingData); + vec3 fresnel = CCSurfaceLightingCalculateExtraFresnel(lightingData); + #else + vec3 fresnel = vec3(1.0); #endif + lightingResult.fresnel = fresnel; + float shadow = 1.0; #if CC_RECEIVE_SHADOW && CC_SHADOW_TYPE == CC_SHADOW_MAP @@ -84,7 +86,8 @@ lightingData.angleAttenuation = angleAtt; lightingData.distAttenuation = distAtt; lightingResult.directDiffuse = diffuseLighting * multiplier; - lightingResult.directSpecular = specularLighting * multiplier * fresnel; + lightingResult.directSpecular = specularLighting * multiplier; + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF, lightingData, lightingResult.specularColorWithLighting, vec3(1.0)); vec4 attenuatedLightColorAndIntensity = vec4(cc_lightColor[i].xyz, cc_lightColor[i].w * multiplier); @@ -106,13 +109,18 @@ CCSurfacesInitializeLightingIntermediateData(lightingData2ndSpecular, surfaceData2ndSpecular); CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData2ndSpecular, surfaceData, lightDirWithLength); CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); - lightingResult.direct2ndSpecular *= multiplier * fresnel; + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, vec3(1.0)); + + lightingResult.direct2ndSpecular *= multiplier; #endif #if CC_SURFACES_LIGHTING_TT CCSurfacesLightingCalculateDirectTT(lightingResult, lightingData, attenuatedLightColorAndIntensity); #endif + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + CCSurfacesLightingCalculateDirectMultiLayerBlending(lightingResult, lightingData2ndSpecular); + #endif // user-defined lighting model #ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT @@ -139,7 +147,7 @@ CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData); CCSurfacesInitializeLightingResult(lightingResult, surfaceData); - CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, lightingResult.specularColorWithEnvLighting, surfaceData, lightingData); + CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, -cc_mainLitDir.xyz); @@ -200,20 +208,24 @@ #endif + // apply SSR, local probe & global probe + vec3 unused; + CCSurfacesLightingCalculateEnvironment(lightingResult.environmentDiffuse, lightingResult.environmentSpecular, lightingData, cc_ambientSky.w); + CCSurfaceLightingCalculateEnvironmentFresnel(lightingResult.environmentGF, unused, lightingData, lightingResult.specularColorWithLighting); + // dynamic & stationary dir light lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); #if !CC_DISABLE_DIRECTIONAL_LIGHT && !CC_FORWARD_ADD - CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, lightingResult.specularColorWithEnvLighting, surfaceData, lightingData); + CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF, lightingData, lightingResult.specularColorWithLighting, lightingResult.environmentGF); #endif - // apply SSR, local probe & global probe - CCSurfacesLightingCalculateEnvironment(lightingResult.environmentDiffuse, lightingResult.environmentSpecular, lightingData, cc_ambientSky.w); - - #if CC_SURFACES_LIGHTING_USE_FRESNEL - lightingResult.fresnel = CCSurfaceLightingCalculateFresnel(lightingData); + lightingResult.fresnel = CCSurfaceLightingCalculateExtraFresnel(lightingData); + #else + lightingResult.fresnel = vec3(1.0); #endif #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR @@ -236,17 +248,26 @@ LightingIntermediateData lightingData2ndSpecular; CCSurfacesInitializeLightingIntermediateData(lightingData2ndSpecular, surfaceData2ndSpecular); CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData2ndSpecular, surfaceData2ndSpecular, -cc_mainLitDir.xyz); - CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); - CCSurfacesLightingCalculateEnvironment2ndSpecular(lightingResult.environment2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.environmentSpecular); vec3 diff; - CCSurfacesLightingInitializeColorWithLighting(diff, lightingResult.specularColorWithLighting2ndSpecular, lightingResult.specularColorWithEnvLighting2ndSpecular, surfaceData2ndSpecular, lightingData2ndSpecular); + CCSurfacesLightingInitializeColorWithLighting(diff, lightingResult.specularColorWithLighting2ndSpecular, surfaceData2ndSpecular, lightingData2ndSpecular); + + CCSurfacesLightingCalculateEnvironment2ndSpecular(lightingResult.environment2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.environmentSpecular); + CCSurfaceLightingCalculateEnvironmentFresnel(lightingResult.environmentGF2ndSpecular, lightingResult.environmentSubLayerF, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular); + + CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, lightingResult.environmentGF2ndSpecular); #endif #if CC_SURFACES_LIGHTING_TT CCSurfacesLightingCalculateDirectTT(lightingResult, lightingData, cc_mainLitColor); #endif + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + CCSurfacesLightingCalculateDirectMultiLayerBlending(lightingResult, lightingData2ndSpecular); + CCSurfacesLightingCalculateEnvironmentMultiLayerBlending(lightingResult, lightingData2ndSpecular); + #endif + // user-defined lighting model #ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT LightingMiscData miscData; diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index 922bc513a21..accd9389b63 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -59,9 +59,43 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l } #if CC_SURFACES_LIGHTING_USE_FRESNEL - float CCSurfaceLightingCalculateFresnel(in LightingIntermediateData lightingData) +vec3 CCSurfaceLightingCalculateExtraFresnel(in LightingIntermediateData lightingData) +{ + float fresnel = CalculateFresnelCoefficient(lightingData.ior, lightingData.NoVAbsSat); //NoVSat for single side, and NoVAbsSat for two sided + return vec3(fresnel); +} +#endif + +void CCSurfaceLightingCalculateDirectFresnel(out vec3 directGF, in LightingIntermediateData lightingData, vec3 specularColor, in vec3 environmentGF) +{ + #if CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING + // local lighting also use EnvIntegratedFresnel for estimated GF terms, calculate accurate GF instead in the future, CCSurfacesDebugViewLightingResult also needs modified + directGF = environmentGF; + #else + float roughness = lightingData.specularParam; + directGF = F_SchlickMultiplier(specularColor, lightingData.VoHAbsSat) * G_Schlick(roughness, lightingData.NoVSat, lightingData.NoLSat); + #endif +} + +void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 integratedF, in LightingIntermediateData lightingData, vec3 specularColor) +{ + float roughness = lightingData.specularParam; + IntegratedGFMultiplier(integratedGF, integratedF, specularColor, roughness, lightingData.NoVAbsSat); +} + +#if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + void CCSurfaceLightingCalculateDirectSubLayerFresnel(out vec3 subLayerF, in LightingIntermediateData lightingData, vec3 specularColor) + { + float VoH = lightingData.VoHAbsSat; + subLayerF = vec3(exp2( (-5.55473 * VoH - 6.98316) * VoH )); + } + void CCSurfaceLightingCalculateEnvironmentSubLayerFresnel(out vec3 subLayerF, in LightingIntermediateData lightingData, vec3 specularColor) { - return CalculateFresnelCoefficient(lightingData.ior, abs(lightingData.NoV)); //NoVSat for single side, and NoVAbs for two sided + // ior related: + subLayerF = vec3(CalculateFresnelCoefficient(lightingData.ior, lightingData.NoVSat)); + // F0 F90 related: + // if (equalf(lightingData.ior, 0.0)) + // subLayerF = vec3(CalculateFresnelCoefficient(lightingData.F0, lightingData.F90, lightingData.NoVSat)); } #endif @@ -218,3 +252,70 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l lightingResult.directTT = ttLighting * DiffuseCoefficient_EnergyConservation * lightSourceColorAndIntensity.xyz* lightSourceColorAndIntensity.w; } #endif + +#if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + // todo: layer result in LightingResult separate to single structure like LightingResultPerLayer + void CCSurfacesLightingCalculateDirectMultiLayerBlending(inout LightingResult lightingResult + , in LightingIntermediateData lightingData2ndLayer + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND > 1 + // add more layers... + #endif + ) + { + vec3 lastLayerF, zeroDiffuse = vec3(0.0); + vec3 blendedBaseD = lightingResult.directDiffuse, blendedBaseS = lightingResult.directSpecular; + InitializeLayerBlending(blendedBaseD, blendedBaseS, + lightingResult.directDiffuseSubLayers, lightingResult.directSpecularSubLayers, + lastLayerF, + lightingResult.directDiffuse, lightingResult.directSpecular + ); + + CCSurfaceLightingCalculateDirectSubLayerFresnel(lightingResult.directSubLayerF, lightingData2ndLayer, lightingResult.specularColorWithLighting2ndSpecular); + CalculateLayerBlending (blendedBaseD, blendedBaseS, + lightingResult.directDiffuseSubLayers, lightingResult.directSpecularSubLayers, + lastLayerF, + zeroDiffuse, zeroDiffuse, + lightingResult.direct2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, + lightingData2ndLayer.layerOpacity, lightingResult.directSubLayerF + ); + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND > 1 + // add more layers... + #endif + + // output + lightingResult.directDiffuse = blendedBaseD; + lightingResult.directSpecular = blendedBaseS; + } + + void CCSurfacesLightingCalculateEnvironmentMultiLayerBlending(inout LightingResult lightingResult + , in LightingIntermediateData lightingData2ndLayer + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND > 1 + // add more layers... + #endif + ) + { + vec3 lastLayerF, zeroDiffuse = vec3(0.0); + vec3 blendedBaseD = lightingResult.environmentDiffuse, blendedBaseS = lightingResult.environmentSpecular; + InitializeLayerBlending(blendedBaseD, blendedBaseS, + lightingResult.environmentDiffuseSubLayers, lightingResult.environmentSpecularSubLayers, + lastLayerF, + lightingResult.environmentDiffuse, lightingResult.environmentSpecular + ); + + CCSurfaceLightingCalculateEnvironmentSubLayerFresnel(lightingResult.environmentSubLayerF, lightingData2ndLayer, lightingResult.specularColorWithLighting2ndSpecular); + CalculateLayerBlending (blendedBaseD, blendedBaseS, + lightingResult.environmentDiffuseSubLayers, lightingResult.environmentSpecularSubLayers, + lastLayerF, + zeroDiffuse, zeroDiffuse, + lightingResult.environment2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, + lightingData2ndLayer.layerOpacity, lightingResult.environmentSubLayerF + ); + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND > 1 + // add more layers... + #endif + + // output + lightingResult.environmentDiffuse = blendedBaseD; + lightingResult.environmentSpecular = blendedBaseS; + } +#endif diff --git a/editor/assets/chunks/lighting-models/model-functions/toon.chunk b/editor/assets/chunks/lighting-models/model-functions/toon.chunk index cdea2dff79a..1e4088faae4 100644 --- a/editor/assets/chunks/lighting-models/model-functions/toon.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/toon.chunk @@ -40,3 +40,21 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l lightingDiffuse = vec3(0.0); lightingSpecular = vec3(0.0); } + + +#if CC_SURFACES_LIGHTING_USE_FRESNEL +vec3 CCSurfaceLightingCalculateExtraFresnel(in LightingIntermediateData lightingData) +{ + return vec3(1.0); +} +#endif + +void CCSurfaceLightingCalculateDirectFresnel(out vec3 fresnel, in LightingIntermediateData lightingData, vec3 specularColor, in vec3 environmentGF) +{ + fresnel = vec3(1.0); +} + +void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, out vec3 integratedF, in LightingIntermediateData lightingData, vec3 specularColor) +{ + integratedF = integratedGF = vec3(1.0); +} diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk b/editor/assets/chunks/surfaces/data-structures/standard.chunk index 52cbfb976b9..fd8f052538a 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk @@ -27,9 +27,14 @@ struct SurfacesMaterialData vec4 transmitDiffuseParams; #endif #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR + // for storage only, copied with CCSurfacesGetSurfacesMaterialData2ndSpecular vec3 baseColor2ndSpecular, color2ndSpecular; - float intensity2ndSpecular, roughness2ndSpecular; + float intensity2ndSpecular, roughness2ndSpecular, metallic2ndSpecular; vec3 worldNormal2ndSpecular, worldTangent2ndSpecular, worldBinormal2ndSpecular; + #if CC_SURFACES_LIGHTING_ANISOTROPIC + float anisotropyShape2ndSpecular; + #endif + float ior2ndSpecular, opacity2ndSpecular; // for multi-layer #endif #if CC_SURFACES_LIGHTING_TT vec3 baseColorTT; diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index e7f3446aacd..230cbf6f2bb 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -164,6 +164,18 @@ vec3 SurfacesFragmentModifyTTColor(in vec3 baseColor) } #endif +#ifndef CC_SURFACES_FRAGMENT_MODIFY_SSS_PARAMS +// depends on CC_SURFACES_FRAGMENT_MODIFY_SSS_PARAMS +vec4 SurfacesFragmentModifySSSParams() +{ + // x: sssIntensity, moisture + // y: sssCurvature, for preintegrated sss + // z: sssColoration, for sss transmitted light color with dark area + // w: unused + return vec4(1.0, 0.1, 1.0, 0.0); +} +#endif + #ifndef CC_SURFACES_FRAGMENT_MODIFY_DUAL_LOBE_SPECULAR_PARAMS // depends on CC_SURFACES_FRAGMENT_MODIFY_DUAL_LOBE_SPECULAR_PARAMS vec4 SurfacesFragmentModifyDualLobeSpecularParams(float roughness) @@ -174,15 +186,32 @@ vec4 SurfacesFragmentModifyDualLobeSpecularParams(float roughness) } #endif -#ifndef CC_SURFACES_FRAGMENT_MODIFY_SSS_PARAMS -// depends on CC_SURFACES_FRAGMENT_MODIFY_SSS_PARAMS -vec4 SurfacesFragmentModifySSSParams() +#ifndef CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_PARAMS +// depends on CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_PARAMS +vec4 SurfacesFragmentModifyClearCoatParams() { - // x: sssIntensity, moisture - // y: sssCurvature, for preintegrated sss - // z: sssColoration, for sss transmitted light color with dark area - // w: unused - return vec4(1.0, 0.1, 1.0, 0.0); + //x: coat roughness + //y: coat ior + //z: coat opacity + //w: coat intensity + return vec4(0.2, 1.5, 1.0, 1.0); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_COLOR +// depends on CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_COLOR +vec3 SurfacesFragmentModifyClearCoatColor() +{ + // for iridescense color variation + return vec3(1.0, 1.0, 1.0); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_WORLD_NORMAL +// depends on CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_WORLD_NORMAL +vec3 SurfacesFragmentModifyClearCoatWorldNormal() +{ + return normalize(FSInput_worldNormal); } #endif diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk index ec593297817..6c8caca0b8d 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk @@ -87,11 +87,20 @@ #define CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR 1 #endif #endif - #ifndef CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR #define CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR 0 #endif +// this value should be sub-layers count +#ifndef CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + #if CC_SURFACES_LIGHTING_CLEAR_COAT + #define CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND 1 + #endif +#endif +#ifndef CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + #define CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND 0 +#endif + // render-to-color-map can disable functionality to avoid error data map #ifndef CC_SURFACES_ENABLE_DEBUG_VIEW diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk index 2ea1d14f81e..5f380b79db6 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk @@ -110,13 +110,13 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR)) { - color.rgb = lightingResult.directSpecular * lightingResult.specularColorWithEnvLighting; + color.rgb = lightingResult.directSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF; isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_ALL)) { - color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting; + color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF; isSRGBColor = true; } @@ -128,13 +128,13 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_SPECULAR)) { - color.rgb = lightingResult.environmentSpecular * lightingResult.specularColorWithEnvLighting; + color.rgb = lightingResult.environmentSpecular * lightingResult.specularColorWithLighting * lightingResult.environmentGF; isSRGBColor = true; } if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_ALL)) { - color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting; + color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting * lightingResult.environmentGF; isSRGBColor = true; } @@ -162,14 +162,11 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) isSRGBColor = false; } - float fresnel = 0.0; + vec3 fresnel = lightingResult.fresnel; vec3 directTransmitSpecular = vec3(0.0), environmentTransmitSpecular = vec3(0.0); vec3 directTransmitDiffuse = vec3(0.0), environmentTransmitDiffuse = vec3(0.0); vec3 diffuseColorWithLightingTT = vec3(0.0), specularColorWithLighting2ndSpecular = vec3(0.0); vec3 direct2ndSpecular = vec3(0.0), environment2ndSpecular = vec3(0.0); - #if CC_SURFACES_LIGHTING_USE_FRESNEL - fresnel = lightingResult.fresnel; - #endif #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR directTransmitSpecular = lightingResult.directTransmitSpecular; environmentTransmitSpecular = lightingResult.environmentTransmitSpecular; @@ -179,11 +176,19 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) environmentTransmitDiffuse = lightingResult.environmentTransmitDiffuse; #endif #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR - direct2ndSpecular = lightingResult.direct2ndSpecular; - environment2ndSpecular = lightingResult.environment2ndSpecular; - specularColorWithLighting2ndSpecular = lightingResult.specularColorWithEnvLighting2ndSpecular; + direct2ndSpecular = lightingResult.direct2ndSpecular * lightingResult.directGF2ndSpecular; + environment2ndSpecular = lightingResult.environment2ndSpecular * lightingResult.environmentGF2ndSpecular; + specularColorWithLighting2ndSpecular = lightingResult.specularColorWithLighting2ndSpecular; + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + fresnel = lightingResult.environmentSubLayerF; + #endif + #endif + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + direct2ndSpecular = lightingResult.directSpecularSubLayers; + environment2ndSpecular = lightingResult.environmentSpecularSubLayers; #endif + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRESNEL)) { color.rgb = vec3(fresnel); @@ -287,9 +292,7 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_AO) lightingResult.ao = 1.0; - #if CC_SURFACES_LIGHTING_USE_FRESNEL if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_FRESNEL) - lightingResult.fresnel = 1.0; - #endif + lightingResult.fresnel = vec3(1.0); } #endif diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index ce3c9a81b59..6399cee8adc 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -47,12 +47,18 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) // skip in shader graph, need extra code vec4 trtParams = SurfacesFragmentModifyTRTParams(); surfaceData.roughness2ndSpecular = saturate(surfaceData.roughness + trtParams.x); + surfaceData.metallic2ndSpecular = surfaceData.metallic; surfaceData.intensity2ndSpecular = trtParams.w; surfaceData.baseColor2ndSpecular = vec3(1.0); // specular color use specified trt color only surfaceData.color2ndSpecular = SurfacesFragmentModifyTRTColor(); surfaceData.worldNormal2ndSpecular = surfaceData.worldNormal; surfaceData.worldTangent2ndSpecular = surfaceData.worldTangent; surfaceData.worldBinormal2ndSpecular = surfaceData.worldBinormal; + surfaceData.ior2ndSpecular = surfaceData.ior; //unused + surfaceData.opacity2ndSpecular = 1.0; // unused + #if CC_SURFACES_LIGHTING_ANISOTROPIC + surfaceData.anisotropyShape2ndSpecular = surfaceData.anisotropyShape; + #endif RotateNormalAndBinormal(surfaceData.worldBinormal2ndSpecular, surfaceData.worldNormal2ndSpecular, surfaceData.worldTangent2ndSpecular, trtParams.y, FSInput_mirrorNormal); #endif @@ -67,12 +73,37 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) // skip in shader graph, need extra code vec4 dualLobeParams = SurfacesFragmentModifyDualLobeSpecularParams(surfaceData.roughness); surfaceData.roughness2ndSpecular = saturate(dualLobeParams.x); + surfaceData.metallic2ndSpecular = surfaceData.metallic; surfaceData.intensity2ndSpecular = dualLobeParams.w; surfaceData.baseColor2ndSpecular = surfaceData.baseColor.rgb; surfaceData.color2ndSpecular = vec3(1.0); // no extra coloration surfaceData.worldNormal2ndSpecular = surfaceData.worldNormal; surfaceData.worldTangent2ndSpecular = surfaceData.worldTangent; surfaceData.worldBinormal2ndSpecular = surfaceData.worldBinormal; + surfaceData.ior2ndSpecular = surfaceData.ior; + surfaceData.opacity2ndSpecular = 1.0; // unused + #if CC_SURFACES_LIGHTING_ANISOTROPIC + surfaceData.anisotropyShape2ndSpecular = surfaceData.anisotropyShape; + #endif +#endif + +#if CC_SURFACES_LIGHTING_CLEAR_COAT + // skip in shader graph, need extra code + vec4 clearCoatParams = SurfacesFragmentModifyClearCoatParams(); + surfaceData.roughness2ndSpecular = clearCoatParams.x; + surfaceData.metallic2ndSpecular = 0.0; + surfaceData.ior2ndSpecular = clearCoatParams.y; + surfaceData.opacity2ndSpecular = clearCoatParams.z; + surfaceData.intensity2ndSpecular = clearCoatParams.w; + surfaceData.baseColor2ndSpecular = vec3(1.0); // specular color use specified coat color only + surfaceData.color2ndSpecular = SurfacesFragmentModifyClearCoatColor(); + surfaceData.worldNormal2ndSpecular = SurfacesFragmentModifyClearCoatWorldNormal(); + surfaceData.worldBinormal2ndSpecular = surfaceData.worldBinormal; + surfaceData.worldTangent2ndSpecular = CalculateTangent(surfaceData.worldNormal2ndSpecular, surfaceData.worldBinormal2ndSpecular); + #if CC_SURFACES_LIGHTING_ANISOTROPIC + surfaceData.anisotropyShape2ndSpecular = surfaceData.anisotropyShape; + // float anisoRotation = xxx; RotateNormalAndBinormal(surfaceData.worldBinormal2ndSpecular, surfaceData.worldNormal2ndSpecular, surfaceData.worldTangent2ndSpecular, anisoRotation, FSInput_mirrorNormal); + #endif #endif #if CC_SURFACES_LIGHTING_SSS @@ -114,19 +145,20 @@ vec3 CCSurfacesGetSpecularColor(in SurfacesMaterialData surfaceData) } // Diffuse/Specular Color with BRDF lighting preparation -void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, inout vec3 specularColorWithEnvLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) { diffuseColorWithLighting = CCSurfacesGetDiffuseColor(surfaceData); specularColorWithLighting = CCSurfacesGetSpecularColor(surfaceData).xyz; // (Intergrated) GF/4Pi use approximate value for both direct lighting and environment lighting // accuracy value can be calculated in LightingCalculateDirect/Environment instead of IntegratedGFApprox - specularColorWithEnvLighting = IntegratedGFApprox(specularColorWithLighting, surfaceData.roughness, lightingData.NoVAbsSat); + // specularColorWithEnvLighting = IntegratedGFApprox(specularColorWithLighting, surfaceData.roughness, lightingData.NoVAbsSat); } // Update two colors with BRDF which depend on lights (optional) -void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, inout vec3 specularColorWithEnvLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) { } + // Copy material data to lighting data // such as tangent data for anisotropic materials void CCSurfacesInitializeLightingIntermediateData(inout LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData) @@ -140,6 +172,7 @@ void CCSurfacesInitializeLightingIntermediateData(inout LightingIntermediateData ); lightingData.specularParam = surfaceData.roughness; lightingData.ior = surfaceData.ior; + lightingData.layerOpacity = surfaceData.baseColor.a; #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE lightingData.transmitScatteringParams = surfaceData.transmitScatteringParams; lightingData.inScatteringColor = surfaceData.inScatteringColor; @@ -178,11 +211,16 @@ void CCSurfacesGetLightingIntermediateDataTransmitDiffuse(inout LightingIntermed void CCSurfacesGetSurfacesMaterialData2ndSpecular(inout SurfacesMaterialData surfaceData2ndSpecular, in SurfacesMaterialData surfaceData) { surfaceData2ndSpecular = surfaceData; - surfaceData2ndSpecular.baseColor = vec4(surfaceData.baseColor2ndSpecular, 1.0); + surfaceData2ndSpecular.baseColor = vec4(surfaceData.baseColor2ndSpecular, surfaceData.opacity2ndSpecular); surfaceData2ndSpecular.roughness = surfaceData.roughness2ndSpecular; + surfaceData2ndSpecular.metallic = surfaceData.metallic2ndSpecular; surfaceData2ndSpecular.worldNormal = surfaceData.worldNormal2ndSpecular; surfaceData2ndSpecular.worldTangent = surfaceData.worldTangent2ndSpecular; surfaceData2ndSpecular.worldBinormal = surfaceData.worldBinormal2ndSpecular; + surfaceData2ndSpecular.ior = surfaceData.ior2ndSpecular; + #if CC_SURFACES_LIGHTING_ANISOTROPIC + surfaceData2ndSpecular.anisotropyShape = surfaceData.anisotropyShape2ndSpecular; + #endif } #endif @@ -191,12 +229,21 @@ void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult, in { lightingResult.ao = surfaceData.ao; lightingResult.emissive = surfaceData.emissive; + lightingResult.directGF = vec3(1.0); +#if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + lightingResult.directDiffuseSubLayers = lightingResult.directSpecularSubLayers = vec3(0.0); + lightingResult.environmentDiffuseSubLayers = lightingResult.environmentSpecularSubLayers = vec3(0.0); +#endif } // Init accumulated lighting results for additive pass void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult) { lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); + lightingResult.directGF = vec3(1.0); +#if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + lightingResult.directDiffuseSubLayers = lightingResult.directSpecularSubLayers = vec3(0.0); +#endif #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR lightingResult.directTransmitSpecular = vec3(0.0); @@ -212,20 +259,25 @@ void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult) #endif } -// Accumulated lighting results for additive pass +// Accumulated lighting results for additive pass only void CCSurfacesAccumulateLightingResult(inout LightingResult lightingResultAccumulated, in LightingResult lightingResult) { lightingResultAccumulated.directDiffuse += lightingResult.directDiffuse * lightingResult.shadow; - lightingResultAccumulated.directSpecular += lightingResult.directSpecular * lightingResult.shadow; + lightingResultAccumulated.directSpecular += lightingResult.directSpecular * lightingResult.shadow * lightingResult.directGF * lightingResult.fresnel; + + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + lightingResultAccumulated.directDiffuseSubLayers += lightingResult.directDiffuseSubLayers * lightingResult.shadow; + lightingResultAccumulated.directSpecularSubLayers += lightingResult.directSpecularSubLayers * lightingResult.shadow; + #endif #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - lightingResultAccumulated.directTransmitSpecular += lightingResult.directTransmitSpecular; + lightingResultAccumulated.directTransmitSpecular += lightingResult.directTransmitSpecular * (vec3(1.0) - lightingResult.fresnel); #endif #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE lightingResultAccumulated.directTransmitDiffuse += lightingResult.directTransmitDiffuse; #endif #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR - lightingResultAccumulated.direct2ndSpecular += lightingResult.direct2ndSpecular * lightingResult.shadow; + lightingResultAccumulated.direct2ndSpecular += lightingResult.direct2ndSpecular * lightingResult.shadow * lightingResult.directGF2ndSpecular * lightingResult.fresnel; #endif #if CC_SURFACES_LIGHTING_TT lightingResultAccumulated.directTT += lightingResult.directTT * lightingResult.shadow; @@ -256,16 +308,20 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li { vec4 color = vec4(0.0, 0.0, 0.0, surfaceData.baseColor.a); - // todo: local lighting also use EnvLightingSpecularColor for estimated GF terms, calculate accurate GF instead in the future, CCSurfacesDebugViewLightingResult also needs modified #if CC_FORWARD_ADD // shadow and fresnel has already been applied with common flow color.xyz += lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting - + lightingResult.directSpecular * lightingResult.specularColorWithEnvLighting + + lightingResult.directSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - + lightingResult.directTransmitSpecular * lightingResult.specularColorWithEnvLighting + + lightingResult.directTransmitSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF #endif - #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR - + lightingResult.direct2ndSpecular * lightingResult.specularColorWithEnvLighting2ndSpecular * surfaceData.color2ndSpecular + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + + lightingResult.directDiffuseSubLayers + + lightingResult.directSpecularSubLayers + #else + #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR + + lightingResult.direct2ndSpecular * lightingResult.specularColorWithLighting2ndSpecular * surfaceData.color2ndSpecular * lightingResult.directGF2ndSpecular + #endif #endif #if CC_SURFACES_LIGHTING_TT + lightingResult.directTT * lightingResult.diffuseColorWithLightingTT @@ -276,20 +332,22 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li ; #else - float fresnel = 1.0; - #if CC_SURFACES_LIGHTING_USE_FRESNEL - fresnel = lightingResult.fresnel; - #endif - float invFresnel = 1.0 - fresnel; + vec3 fresnel = lightingResult.fresnel; + vec3 invFresnel = vec3(1.0) - fresnel; color.xyz += ( lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting - + lightingResult.directSpecular * lightingResult.specularColorWithEnvLighting * fresnel + + lightingResult.directSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF * fresnel #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - + lightingResult.directTransmitSpecular * lightingResult.specularColorWithEnvLighting * invFresnel + + lightingResult.directTransmitSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF * invFresnel #endif - #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR - + lightingResult.direct2ndSpecular * lightingResult.specularColorWithEnvLighting2ndSpecular * surfaceData.color2ndSpecular + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + + lightingResult.directDiffuseSubLayers + + lightingResult.directSpecularSubLayers + #else + #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR + + lightingResult.direct2ndSpecular * lightingResult.specularColorWithLighting2ndSpecular * surfaceData.color2ndSpecular * lightingResult.directGF2ndSpecular + #endif #endif #if CC_SURFACES_LIGHTING_TT + lightingResult.directTT * lightingResult.diffuseColorWithLightingTT @@ -309,12 +367,17 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li color.xyz += ( lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting - + lightingResult.environmentSpecular * lightingResult.specularColorWithEnvLighting * fresnel + + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting * lightingResult.environmentGF * fresnel #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR - + lightingResult.environmentTransmitSpecular * lightingResult.specularColorWithEnvLighting * invFresnel + + lightingResult.environmentTransmitSpecular * lightingResult.specularColorWithLighting * lightingResult.environmentGF * invFresnel #endif - #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR - + lightingResult.environment2ndSpecular * lightingResult.specularColorWithEnvLighting2ndSpecular * surfaceData.color2ndSpecular + #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + + lightingResult.environmentDiffuseSubLayers + + lightingResult.environmentSpecularSubLayers + #else + #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR + + lightingResult.environment2ndSpecular * lightingResult.specularColorWithLighting2ndSpecular * surfaceData.color2ndSpecular * lightingResult.environmentGF2ndSpecular + #endif #endif ) * lightingResult.ao diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk index 5afc2f508e4..f2019bc22e3 100644 --- a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk @@ -50,12 +50,12 @@ vec3 CCSurfacesGetSpecularColor(in SurfacesMaterialData surfaceData) { return surfaceData.specular.xyz; } -void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, inout vec3 specularColorWithEnvLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) { diffuseColorWithLighting = vec3(0.0); - specularColorWithEnvLighting = specularColorWithLighting = surfaceData.specular.xyz * surfaceData.baseStep; + specularColorWithLighting = surfaceData.specular.xyz * surfaceData.baseStep; } -void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, inout vec3 specularColorWithEnvLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) { float NL = 0.5 * lightingData.NoL + 0.5; @@ -68,7 +68,6 @@ void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLig diffuseColorWithLighting = diffuse * surfaceData.baseStep; } - // Copy material data to lighting data // such as tangent data for anisotropic materials void CCSurfacesInitializeLightingIntermediateData(inout LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData) @@ -140,8 +139,8 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li LightingIntermediateData lightingData; lightingData.NoL = -1.0; vec3 backLightingDiffuse, backLightingSpecular; - CCSurfacesLightingInitializeColorWithLighting(backLightingDiffuse, backLightingSpecular, backLightingSpecular, surfaceData, lightingData); - CCSurfacesLightingCalculateColorWithLighting(backLightingDiffuse, backLightingSpecular, backLightingSpecular, surfaceData, lightingData); + CCSurfacesLightingInitializeColorWithLighting(backLightingDiffuse, backLightingSpecular, surfaceData, lightingData); + CCSurfacesLightingCalculateColorWithLighting(backLightingDiffuse, backLightingSpecular, surfaceData, lightingData); color.xyz += mix(lightingResult.directDiffuse, lightingResult.lightmapColor, lightmapCoef) * mix(backLightingDiffuse, lightingResult.diffuseColorWithLighting, lightingResult.shadow) diff --git a/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk b/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk index edc14d1b03f..ed8a5ce578c 100644 --- a/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk @@ -27,13 +27,13 @@ vec3 CCSurfacesGetSpecularColor(in SurfacesMaterialData surfaceData) } // Diffuse/Specular Color with BRDF lighting preparation -void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, inout vec3 specularColorWithEnvLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) { diffuseColorWithLighting = CCSurfacesGetDiffuseColor(surfaceData); - specularColorWithEnvLighting = specularColorWithLighting = CCSurfacesGetSpecularColor(surfaceData).xyz; + specularColorWithLighting = CCSurfacesGetSpecularColor(surfaceData).xyz; } // Update two colors with BRDF which depend on lights (optional) -void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, inout vec3 specularColorWithEnvLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) { } diff --git a/editor/assets/effects/advanced/car-paint.effect b/editor/assets/effects/advanced/car-paint.effect new file mode 100644 index 00000000000..6e5aede6071 --- /dev/null +++ b/editor/assets/effects/advanced/car-paint.effect @@ -0,0 +1,383 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 0.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + roughness: { value: 0.5, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.0, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + addOnShadowBias: { value: 0.0, target: emissiveScaleParam.z } + coatRoughness: { value: 0.05, target: coatParam.x, editor: { slide : true, range : [0, 1.0] , step : 0.0001 } } + coatIOR: { value: 1.0, target: coatParam.y, editor: { slide : true, range : [1.0, 1.5] , step : 0.0001 } } + coatOpacity: { value: 1.0, target: coatParam.z, editor: { slide : true, range : [0.0, 1.0] , step : 0.0001 } } + coatIntensity: { value: 1.0, target: coatParam.w, editor: { slide : true, range : [0.0, 3.0] , step : 0.0001 } } + coatColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { displayName: CoatColor, type: color } } + flakeDensity: { value: 0.5, target: flakeParam.x, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } + flakeColorIntensity: { value: 0.2, target: flakeParam.y, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } + flakeTiling: { value: 10.0, target: flakeParam.z, editor: { parent: USE_FLAKE, slide: true, range: [1.0, 40.0], step: 0.001 } } + coatNormalStrength: { value: 0.1, target: flakeParam.w, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } + gradientColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { parent: USE_GRADIENT_COLOR, type: color } } + gradientIntensity: { value: 0.5, target: emissiveScaleParam.y, editor: { parent: USE_GRADIENT_COLOR, slide: true, range: [0, 1.0], step: 0.001 } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + normalMap: { value: normal } + coatNormalMap: { value: normal, editor: { parent: USE_FLAKE } } + flakeDataMap: { value: white, editor: { parent: USE_FLAKE } } + pbrMap: { value: grey } + occlusionMap: { value: white } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + rasterizerState: + cullMode: front + properties: + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + - &reflect-map + vert: standard-vs + frag: reflect-map-fs + phase: reflect-map + propertyIndex: 0 + - &planar-shadow + vert: planar-shadow-vs + frag: planar-shadow-fs + phase: planar-shadow + propertyIndex: 0 + depthStencilState: + depthTest: true + depthWrite: false + stencilTestFront: true + stencilFuncFront: not_equal + stencilPassOpFront: replace + stencilRef: 0x80 # only use the leftmost bit + stencilReadMask: 0x80 + stencilWriteMask: 0x80 + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + - &deferred + vert: standard-vs + frag: standard-fs + pass: gbuffer + phase: gbuffer + embeddedMacros: { CC_PIPELINE_TYPE: 1 } + propertyIndex: 0 + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: &d1 + depthTest: true + depthWrite: false + blendState: &b1 + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster + - *planar-shadow + - &deferred-forward + vert: standard-vs + frag: standard-fs + phase: deferred-forward + embeddedMacros: { CC_PIPELINE_TYPE: 0 } + propertyIndex: 0 + depthStencilState: *d1 + blendState: *b1 +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + vec4 pbrParams; + vec4 emissiveScaleParam; + vec4 coatParam; + vec4 coatColor; + vec4 flakeParam; + vec4 gradientColor; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta HAS_SECOND_UV + #pragma define-meta USE_TWOSIDE + #pragma define-meta USE_VERTEX_COLOR + #pragma define-meta USE_FLAKE + + #define CC_SURFACES_USE_SECOND_UV HAS_SECOND_UV + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR + #define CC_SURFACES_LIGHTING_CLEAR_COAT 1 + + // depend on UI macros +#if USE_NORMAL_MAP || USE_FLAKE + #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif +}% + +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_SHADOW_BIAS + vec2 SurfacesVertexModifyShadowBias(in SurfacesStandardVertexIntermediate In, vec2 originShadowBias) + { + return originShadowBias + vec2(emissiveScaleParam.z, 0.0); + } + + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw; + #if CC_SURFACES_USE_SECOND_UV + In.texCoord1 = In.texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + } +}% + +CCProgram surface-fragment %{ + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) + #endif + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + #pragma define-meta DEFAULT_UV options([v_uv, v_uv1]) + #if USE_PBR_MAP + uniform sampler2D pbrMap; + #endif + #if USE_OCCLUSION_MAP + uniform sampler2D occlusionMap; + #endif + #if USE_FLAKE + uniform sampler2D coatNormalMap; + uniform sampler2D flakeDataMap; + #endif + + #pragma define OCCLUSION_CHANNEL r + #pragma define ROUGHNESS_CHANNEL g + #pragma define METALLIC_CHANNEL b + #pragma define SPECULAR_INTENSITY_CHANNEL a + + #if USE_ALPHA_TEST + #pragma define-meta ALPHA_TEST_CHANNEL options([a, r]) + #endif + + #define CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_PARAMS + vec4 SurfacesFragmentModifyClearCoatParams() + { + return vec4(coatParam.x, coatParam.y - 0.99, coatParam.z, coatParam.w * 2.0); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_COLOR + vec3 SurfacesFragmentModifyClearCoatColor() + { + return coatColor.xyz; + } + + vec4 sampleFlake(sampler2D tex, vec2 uv) + { + vec4 blurred = texture(tex, uv); + vec4 detailed = fragTextureLod(tex, uv, 1.0); + return lerp(blurred, detailed, 0.3); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_WORLD_NORMAL + vec3 SurfacesFragmentModifyClearCoatWorldNormal() + { + vec3 normal = FSInput_worldNormal; + #if USE_FLAKE + float density = flakeParam.x, densityMin = 0.25, flakeTiling = flakeParam.z; + vec2 uv = FSInput_texcoord * flakeTiling; + vec4 data = sampleFlake(flakeDataMap, uv); + vec3 nmmp = (sampleFlake(coatNormalMap, uv).xyz - vec3(0.5)) * 2.0; + float C = (data.a - 1.0) / density + 1.0; + float bumpIntensity = saturate(max(densityMin, C)); + nmmp = lerp(vec3(0.0, 0.0, 1.0), nmmp, bumpIntensity); + normal = CalculateNormalFromTangentSpace(nmmp, flakeParam.w, normalize(normal.xyz), normalize(FSInput_worldTangent), FSInput_mirrorNormal); + #endif + + return normalize(normal); + } + + #include + + + #include + #define CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA + void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) + { + #if USE_GRADIENT_COLOR + vec3 viewDir = normalize(cc_cameraPos.xyz - surfaceData.worldPos); + float NoVSat = saturate(dot(surfaceData.worldNormal, viewDir)); + surfaceData.baseColor.rgb = lerp(gradientColor, surfaceData.baseColor, pow(NoVSat, emissiveScaleParam.y)).rgb; + #endif + + #if USE_FLAKE + float density = flakeParam.x, flakeColorIntensity = flakeParam.y, flakeTiling = flakeParam.z; + vec2 uv = FSInput_texcoord * flakeTiling; + + vec4 data = sampleFlake(flakeDataMap, uv); + float C = (data.a - 1.0) / density + 1.0; + float flakeTintWeight = 1.0; + float flakeWeight = saturate(C) * flakeTintWeight * flakeColorIntensity; + + // color + vec4 flakeA = vec4(0.972,0.96,0.915,1); + vec4 flakeB = vec4(1.0,0.78,0.344,1); + vec4 flakeColor = lerp(flakeA, flakeB, data.r); + + vec4 color = surfaceData.baseColor; + color = lerp(color, flakeColor, flakeWeight); + color = lerp(surfaceData.baseColor, color, surfaceData.metallic); + surfaceData.baseColor = color; + surfaceData.roughness *= lerp(1.0, 0.5, flakeWeight); + #endif + } +}% + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram planar-shadow-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram planar-shadow-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram reflect-map-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + #include + #include +}% + diff --git a/editor/assets/effects/advanced/car-paint.effect.meta b/editor/assets/effects/advanced/car-paint.effect.meta new file mode 100644 index 00000000000..ab9bcd058f7 --- /dev/null +++ b/editor/assets/effects/advanced/car-paint.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.7.0", + "importer": "effect", + "imported": true, + "uuid": "304a12db-3955-46e4-b712-e5e26f45258b", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/advanced/glass.effect b/editor/assets/effects/advanced/glass.effect new file mode 100644 index 00000000000..f8c76e0ce2e --- /dev/null +++ b/editor/assets/effects/advanced/glass.effect @@ -0,0 +1,354 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [0.05, 0.05, 0.05, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + roughness: { value: 0.0, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.0, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.2, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + F0: { value: 0.7, target: emissiveScaleParam.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + F90: { value: 0.9, target: emissiveScaleParam.y, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + gradientColor: { value: [0.0, 0.05, 0.0, 1.0], linear: true, editor: { parent: USE_GRADIENT_COLOR, type: color } } + gradientIntensity: { value: 0.2, target: emissiveScaleParam.z, editor: { parent: USE_GRADIENT_COLOR, slide: true, range: [0, 1.0], step: 0.001 } } + normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + normalMap: { value: normal } + pbrMap: { value: grey } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + rasterizerState: + cullMode: front + properties: + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + - &reflect-map + vert: standard-vs + frag: reflect-map-fs + phase: reflect-map + propertyIndex: 0 + - &planar-shadow + vert: planar-shadow-vs + frag: planar-shadow-fs + phase: planar-shadow + propertyIndex: 0 + depthStencilState: + depthTest: true + depthWrite: false + stencilTestFront: true + stencilFuncFront: not_equal + stencilPassOpFront: replace + stencilRef: 0x80 # only use the leftmost bit + stencilReadMask: 0x80 + stencilWriteMask: 0x80 + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + - &deferred + vert: standard-vs + frag: standard-fs + pass: gbuffer + phase: gbuffer + embeddedMacros: { CC_PIPELINE_TYPE: 1 } + propertyIndex: 0 + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: &d1 + depthTest: true + depthWrite: false + blendState: &b1 + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster + - *planar-shadow + - &deferred-forward + vert: standard-vs + frag: standard-fs + phase: deferred-forward + embeddedMacros: { CC_PIPELINE_TYPE: 0 } + propertyIndex: 0 + depthStencilState: *d1 + blendState: *b1 +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + vec4 pbrParams; + vec4 emissiveScaleParam; + vec4 gradientColor; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta USE_TWOSIDE + #pragma define-meta USE_VERTEX_COLOR + #pragma define-meta USE_PROBE_REFRACTION editor({ tooltip: 'Use transparency technique when disabled, otherwise use opaque technique' }) + + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR + #define CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR USE_PROBE_REFRACTION + #define CC_SURFACES_LIGHTING_USE_FRESNEL USE_PROBE_REFRACTION + + // depend on UI macros +#if USE_NORMAL_MAP + #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif +}% + +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw; + #if CC_SURFACES_USE_SECOND_UV + In.texCoord1 = In.texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + } +}% + +CCProgram surface-fragment %{ + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) + #endif + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + #if USE_PBR_MAP + uniform sampler2D pbrMap; + #endif + #pragma define-meta DEFAULT_UV options([v_uv, v_uv1]) + + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + vec4 baseColor = albedo; + + #if USE_VERTEX_COLOR + baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear + baseColor.a *= FSInput_vertexColor.a; + #endif + + #if USE_ALBEDO_MAP + vec4 texColor = texture(albedoMap, ALBEDO_UV); + texColor.rgb = SRGBToLinear(texColor.rgb); + baseColor *= texColor; + #endif + + baseColor.rgb *= albedoScaleAndCutoff.xyz; + return baseColor; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL + vec3 SurfacesFragmentModifyWorldNormal() + { + vec3 normal = FSInput_worldNormal; + #if USE_NORMAL_MAP + vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5); + normal = CalculateNormalFromTangentSpace(nmmp, emissiveScaleParam.w, normalize(normal.xyz), normalize(FSInput_worldTangent), FSInput_mirrorNormal); + #endif + + return normalize(normal); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS + vec4 SurfacesFragmentModifyPBRParams() + { + vec4 pbr = pbrParams; + pbr.x = 1.0; + #if USE_PBR_MAP + vec4 res = texture(pbrMap, DEFAULT_UV); + pbr.yzw *= res.yzw; + #endif + + return pbr; + } + + #include + #include + #define CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA + void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) + { + vec3 viewDir = normalize(cc_cameraPos.xyz - surfaceData.worldPos); + float NoVSat = saturate(dot(surfaceData.worldNormal, viewDir)); + + #if !USE_PROBE_REFRACTION + // fresnel for alpha blend + float F0 = emissiveScaleParam.x, F90 = emissiveScaleParam.y; + surfaceData.baseColor.a = CalculateFresnelCoefficient(min(F0, F90), F90, NoVSat); + #endif + + #if USE_GRADIENT_COLOR + surfaceData.baseColor.rgb = lerp(gradientColor * albedoScaleAndCutoff, surfaceData.baseColor, pow(NoVSat, emissiveScaleParam.z)).rgb; + #endif + } + + #include + #define CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT + void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, in LightingMiscData miscData) + { + #if USE_PROBE_REFRACTION + // fresnel for refraction + vec3 viewDir = normalize(cc_cameraPos.xyz - surfaceData.worldPos); + float NoVSat = saturate(dot(surfaceData.worldNormal, viewDir)); + float F0 = emissiveScaleParam.x, F90 = emissiveScaleParam.y; + float fresnel = CalculateFresnelCoefficient(min(F0, F90), F90, NoVSat); + result.fresnel = vec3(fresnel); + #else + // simply fix oit depth issue for bright color alpha blending + float threshold = 0.5, bright = dot(result.environmentSpecular, vec3(0.33333)); + if (bright > threshold) + result.environmentSpecular = result.environmentSpecular / bright * threshold; + #endif + } +}% + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram planar-shadow-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram planar-shadow-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram reflect-map-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + #include + #include +}% + diff --git a/editor/assets/effects/advanced/glass.effect.meta b/editor/assets/effects/advanced/glass.effect.meta new file mode 100644 index 00000000000..ff18657e4e4 --- /dev/null +++ b/editor/assets/effects/advanced/glass.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.7.0", + "importer": "effect", + "imported": true, + "uuid": "f288f946-150b-443d-b4b3-0227c5117c93", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/advanced/hair.effect b/editor/assets/effects/advanced/hair.effect index 3a2d18e2b2e..9c500f38a29 100644 --- a/editor/assets/effects/advanced/hair.effect +++ b/editor/assets/effects/advanced/hair.effect @@ -26,7 +26,7 @@ CCEffect %{ anisotropyMap: { value: black } roughnessTRT: { value: 0.2, target: trtParams.x, editor: { displayName: TRT Roughness Offset, slide: true, range: [0, 1.0], step: 0.001, tooltip: 'The extend range of internal reflection lighting around the direct specular' } } offsetTRT: { value: 0.0, target: trtParams.y, editor: { displayName: TRT Lighting Offset, slide: true, range: [-0.5, 0.5], step: 0.001, tooltip: 'The position offset of internal reflection lighting compared to direct specular' } } - IntensityTRT: { value: 1.0, target: trtParams.w, editor: { displayName: TRT Intensity, slide: true, range: [0, 5.0], step: 0.01 } } + IntensityTRT: { value: 2.0, target: trtParams.w, editor: { displayName: TRT Intensity, slide: true, range: [0, 10.0], step: 0.01 } } baseColorTRT: { value: [0.5, 0.33, 0.18, 1.0], target: trtColor, linear: true, editor: { displayName: TRT Albedo, type: color, tooltip: 'The color of internal reflection lighting' } } ScatterCoefTT: { value: 0.0, target: ttParams.x, editor: { displayName: TT Scatter Coef, slide: true, range: [0, 1.0], step: 0.01, tooltip: 'The saturation of internal transmit lighting color' } } IntensityTT: { value: 1.0, target: ttParams.w, editor: { displayName: TT Intensity, slide: true, range: [0, 1.0], step: 0.01 } } diff --git a/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect b/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect index 25d9e5c09f8..2a4d39a1e9a 100644 --- a/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect +++ b/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect @@ -301,7 +301,7 @@ CCProgram surface-fragment %{ return normalize(CalculateNormalFromTangentSpace(nmmp, normalIntensity, N, T, FSInput_mirrorNormal)); } - float GetFresnel(float fresnel) + vec3 GetFresnel(vec3 fresnel) { return saturate(fresnel * 1.5); } diff --git a/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect b/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect index fb1af249d9d..e553d178eda 100644 --- a/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect +++ b/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect @@ -226,7 +226,7 @@ CCProgram surface-fragment %{ return normalize(CalculateNormalFromTangentSpace(nmmp, normalIntensity, N, T, FSInput_mirrorNormal)); } - float GetFresnel(float fresnel) + vec3 GetFresnel(vec3 fresnel) { return saturate(fresnel * 1.5); } From d83d2ac3f11eeb5e81e91562d405c3574d19406c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Thu, 20 Jul 2023 22:03:11 +0800 Subject: [PATCH 057/232] fix reflection probe type for skin and instancing (#15789) --- cocos/3d/framework/mesh-renderer.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index 00d82bb0e8d..2132c568b88 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -901,10 +901,11 @@ export class MeshRenderer extends ModelRenderer { // because the lighting map will influence the model's shader this._model.initLightingmap(this.bakeSettings.texture, this.bakeSettings.uvParam); this._updateUseLightProbe(); - this._updateUseReflectionProbe(); + this._updateUseReflectionProbeType(); this._updateModelParams(); this._onUpdateLightingmap(); this._onUpdateLocalShadowBiasAndProbeId(); + this._updateUseReflectionProbe(); this._updateReceiveDirLight(); this._onUpdateReflectionProbeDataMap(); this._onUpdateLocalReflectionProbeData(); @@ -1185,6 +1186,11 @@ export class MeshRenderer extends ModelRenderer { this._updateReflectionProbeTexture(); } + protected _updateUseReflectionProbeType () { + if (!this._model) return; + this._model.reflectionProbeType = this.bakeSettings.reflectionProbe; + } + protected _updateBakeToReflectionProbe () { if (!this._model) { return; } this._model.bakeToReflectionProbe = this.bakeSettings.bakeToReflectionProbe; From aacc0d7261ba3fc9b6c0018e4205ef7290aff592 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Fri, 21 Jul 2023 11:48:57 +0800 Subject: [PATCH 058/232] add help for reflection probe and rename Fxaa (#15790) --- cocos/3d/reflection-probe/reflection-probe-component.ts | 3 ++- cocos/rendering/post-process/components/fxaa.ts | 8 ++++---- cocos/rendering/post-process/passes/fxaa-pass.ts | 4 ++-- editor/i18n/en/localization.js | 3 ++- editor/i18n/zh/localization.js | 3 ++- 5 files changed, 12 insertions(+), 9 deletions(-) diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index eb24ff03c03..3a125488251 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass, executeInEditMode, menu, playOnFocus, serializable, tooltip, type, visible } from 'cc.decorator'; +import { ccclass, executeInEditMode, help, menu, playOnFocus, serializable, tooltip, type, visible } from 'cc.decorator'; import { EDITOR, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { CCBoolean, CCObject, Color, Enum, Vec3 } from '../../core'; @@ -62,6 +62,7 @@ export enum ProbeResolution { @menu('Rendering/ReflectionProbe') @executeInEditMode @playOnFocus +@help('i18n:cc.ReflectionProbe') export class ReflectionProbe extends Component { protected static readonly DEFAULT_CUBE_SIZE: Readonly = new Vec3(1, 1, 1); protected static readonly DEFAULT_PLANER_SIZE: Readonly = new Vec3(5, 0.5, 5); diff --git a/cocos/rendering/post-process/components/fxaa.ts b/cocos/rendering/post-process/components/fxaa.ts index 8f1c8a23d86..41fb51f05cc 100644 --- a/cocos/rendering/post-process/components/fxaa.ts +++ b/cocos/rendering/post-process/components/fxaa.ts @@ -1,10 +1,10 @@ import { ccclass, disallowMultiple, executeInEditMode, help, menu } from '../../../core/data/decorators'; import { PostProcessSetting } from './post-process-setting'; -@ccclass('cc.Fxaa') -@help('cc.Fxaa') -@menu('PostProcess/Fxaa') +@ccclass('cc.FXAA') +@help('cc.FXAA') +@menu('PostProcess/FXAA') @disallowMultiple @executeInEditMode -export class Fxaa extends PostProcessSetting { +export class FXAA extends PostProcessSetting { } diff --git a/cocos/rendering/post-process/passes/fxaa-pass.ts b/cocos/rendering/post-process/passes/fxaa-pass.ts index 64419cad668..80a774571a9 100644 --- a/cocos/rendering/post-process/passes/fxaa-pass.ts +++ b/cocos/rendering/post-process/passes/fxaa-pass.ts @@ -6,10 +6,10 @@ import { getCameraUniqueID } from '../../custom/define'; import { passContext } from '../utils/pass-context'; import { getSetting, SettingPass } from './setting-pass'; -import { Fxaa } from '../components/fxaa'; +import { FXAA } from '../components/fxaa'; export class FxaaPass extends SettingPass { - get setting () { return getSetting(Fxaa); } + get setting () { return getSetting(FXAA); } name = 'FxaaPass' effectName = 'pipeline/post-process/fxaa-hq'; diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 1ba99832758..7b238392b84 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -137,12 +137,13 @@ module.exports = link(mixin({ BlitScreen: `${url}/${version}/manual/en/render-pipeline/post-process/blit-screen.html`, TAA: `${url}/${version}/manual/en/render-pipeline/post-process/index.html`, FSR: `${url}/${version}/manual/en/render-pipeline/post-process/index.html`, - Fxaa: `${url}/${version}/manual/en/render-pipeline/post-process/index.html`, + FXAA: `${url}/${version}/manual/en/render-pipeline/post-process/index.html`, Bloom: `${url}/${version}/manual/en/render-pipeline/post-process/index.html`, HBAO: `${url}/${version}/manual/en/render-pipeline/post-process/index.html`, ColorGrading: `${url}/${version}/manual/en/render-pipeline/post-process/index.html`, Skin: `${url}/${version}/manual/en/shader/advanced-shader/skin.html`, RenderRoot2D: `${url}/${version}/manual/en/ui-system/components/editor/renderroot2d.html`, + ReflectionProbe: `${url}/${version}/manual/en/concepts/scene/light/probe/reflection-art-workflow.html`, }, assets: { javascript: `${url}/${version}/manual/en/concepts/scene/node-component.html`, diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 2e51cd91d3d..9e562d57c3d 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -137,12 +137,13 @@ module.exports = link(mixin({ BlitScreen: `${url}/${version}/manual/zh/render-pipeline/post-process/blit-screen.html`, TAA: `${url}/${version}/manual/zh/render-pipeline/post-process/index.html`, FSR: `${url}/${version}/manual/zh/render-pipeline/post-process/index.html`, - Fxaa: `${url}/${version}/manual/zh/render-pipeline/post-process/index.html`, + FXAA: `${url}/${version}/manual/zh/render-pipeline/post-process/index.html`, Bloom: `${url}/${version}/manual/zh/render-pipeline/post-process/index.html`, HBAO: `${url}/${version}/manual/zh/render-pipeline/post-process/index.html`, ColorGrading: `${url}/${version}/manual/zh/render-pipeline/post-process/index.html`, Skin: `${url}/${version}/manual/zh/shader/advanced-shader/skin.html`, RenderRoot2D: `${url}/${version}/manual/zh/ui-system/components/editor/renderroot2d.html`, + ReflectionProbe: `${url}/${version}/manual/zh/concepts/scene/light/probe/reflection-art-workflow.html`, }, assets: { javascript: `${url}/${version}/manual/zh/concepts/scene/node-component.html`, From 775b794aa9f079da75a16b3836bd0f07804cce8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 21 Jul 2023 11:54:54 +0800 Subject: [PATCH 059/232] Fix clip visiting in animation controller; fix typo (#15791) --- editor/src/marionette/preview.ts | 1 - editor/src/marionette/visit.ts | 15 +++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/editor/src/marionette/preview.ts b/editor/src/marionette/preview.ts index 42566e88fc7..c7b8d2f16ce 100644 --- a/editor/src/marionette/preview.ts +++ b/editor/src/marionette/preview.ts @@ -88,7 +88,6 @@ class AnimationGraphPartialPreviewer { const bindingContext = new AnimationGraphBindingContext( this._root, this._poseLayoutMaintainer, this._varInstances, this._dummyAnimationController, - new EventTarget(), ); poseLayoutMaintainer.startBind(); diff --git a/editor/src/marionette/visit.ts b/editor/src/marionette/visit.ts index a6e4e8dc512..12bf082ece7 100644 --- a/editor/src/marionette/visit.ts +++ b/editor/src/marionette/visit.ts @@ -15,6 +15,7 @@ import { PoseNodeStateMachine } from '../../../cocos/animation/marionette/pose-g import { PoseNodePlayMotion } from "../../../cocos/animation/marionette/pose-graph/pose-nodes/play-motion"; import { PoseNodeSampleMotion } from "../../../cocos/animation/marionette/pose-graph/pose-nodes/sample-motion"; import { PoseGraph } from "../../../cocos/animation/marionette/pose-graph/pose-graph"; +import { AnimationGraphVariant } from "../../../cocos/animation/marionette/animation-graph-variant"; export function* visitAnimationGraphEditorExtras(animationGraph: AnimationGraph): Generator { for (const layer of animationGraph.layers) { @@ -112,7 +113,17 @@ export function* visitAnimationClipsInController(animationController: AnimationC const { graph, } = animationController; - if (graph) { - yield* visitAnimationClips(graph as AnimationGraph); + if (graph instanceof AnimationGraph) { + yield* visitAnimationClips(graph); + } else if (graph instanceof AnimationGraphVariant) { + const { + original, + clipOverrides, + } = graph; + if (original) { + for (const clip of visitAnimationClips(original)) { + yield clipOverrides.get(clip) ?? clip; + } + } } } From 3ca7d08db3694437a93e97f65aca6266435312e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 21 Jul 2023 14:32:12 +0800 Subject: [PATCH 060/232] Animation components localization (#15701) Fix --- .../skeletal-animation/skeletal-animation.ts | 6 +-- cocos/animation/animation-component.ts | 6 +-- editor/i18n/en/animation.js | 40 +++++++++++++++++++ editor/i18n/zh/animation.js | 37 +++++++++++++++++ editor/i18n/zh/localization.js | 7 ---- 5 files changed, 82 insertions(+), 14 deletions(-) diff --git a/cocos/3d/skeletal-animation/skeletal-animation.ts b/cocos/3d/skeletal-animation/skeletal-animation.ts index 62f980eb51c..a53df4e3ffc 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation.ts @@ -23,7 +23,7 @@ */ import { - ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, serializable, editable, + ccclass, executeInEditMode, executionOrder, help, menu, type, serializable, editable, } from 'cc.decorator'; import { SkinnedMeshRenderer } from '../skinned-mesh-renderer'; import { Mat4, cclegacy, js, assertIsTrue } from '../../core'; @@ -107,7 +107,7 @@ export class SkeletalAnimation extends Animation { * 当前动画组件维护的挂点数组。要挂载自定义节点到受动画驱动的骨骼上,必须先在此注册挂点。 */ @type([Socket]) - @tooltip('i18n:animation.sockets') + @editable get sockets (): Socket[] { return this._sockets; } @@ -131,7 +131,7 @@ export class SkeletalAnimation extends Animation { * 是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,但所有动画效果会被彻底固定,不支持任何形式的编辑和混合。
* 运行时动态修改此选项会在播放下一条动画片段时生效。 */ - @tooltip('i18n:animation.use_baked_animation') + @editable get useBakedAnimation (): boolean { return this._useBakedAnimation; } diff --git a/cocos/animation/animation-component.ts b/cocos/animation/animation-component.ts index 0c1045fc680..ced9b78886e 100644 --- a/cocos/animation/animation-component.ts +++ b/cocos/animation/animation-component.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, serializable } from 'cc.decorator'; +import { ccclass, executeInEditMode, executionOrder, help, menu, type, serializable, editable } from 'cc.decorator'; import { EDITOR_NOT_IN_PREVIEW, TEST } from 'internal:constants'; import { Component } from '../scene-graph/component'; import { Eventify, warnID, js, cclegacy } from '../core'; @@ -60,7 +60,6 @@ export class Animation extends Eventify(Component) { * 设置时,已有剪辑关联的动画状态将被停止;若默认剪辑不在新的动画剪辑中,将被重置为空。 */ @type([AnimationClip]) - @tooltip('i18n:animation.clips') get clips (): (AnimationClip | null)[] { return this._clips; } @@ -103,7 +102,6 @@ export class Animation extends Eventify(Component) { * @see [[playOnLoad]] */ @type(AnimationClip) - @tooltip('i18n:animation.default_clip') get defaultClip (): AnimationClip | null { return this._defaultClip; } @@ -131,7 +129,7 @@ export class Animation extends Eventify(Component) { * 注意,若在组件开始运行前调用了 `crossFade` 或 `play()`,此字段将不会生效。 */ @serializable - @tooltip('i18n:animation.play_on_load') + @editable public playOnLoad = false; /** diff --git a/editor/i18n/en/animation.js b/editor/i18n/en/animation.js index 7d5f7e45433..055ec951478 100644 --- a/editor/i18n/en/animation.js +++ b/editor/i18n/en/animation.js @@ -18,7 +18,47 @@ module.exports = { classes: { 'cc': { + 'Animation': { + 'properties': { + 'clips': { + displayName: 'Clips', + tooltip: 'All clips this component governs.', + }, + 'defaultClip': { + displayName: 'Default Clip', + tooltip: 'The default clip to play.', + }, + 'playOnLoad': { + displayName: 'Play On Load', + tooltip: 'Whether automatically play the default clip after component loaded.', + }, + }, + }, + 'SkeletalAnimation': { + 'properties': { + __extends__: 'classes.cc.Animation.properties', + 'sockets': { + displayName: 'Sockets', + tooltip: 'The joint sockets this animation component maintains. ' + + 'Sockets have to be registered here before attaching custom nodes to animated joints.', + }, + 'useBakedAnimation': { + displayName: 'Use Baked Animation', + tooltip: `Whether to bake animations. Default to true, ` + + `which substantially increases performance while making all animations completely fixed.` + + `Dynamically changing this property will take effect when playing the next animation clip.`, + }, + }, + }, 'animation': { + 'AnimationController': { + properties: { + 'graph': { + displayName: 'Graph', + tooltip: 'The animation graph or animation graph variant associated with this animation controller.', + }, + }, + }, 'PoseGraphOutputNode': { displayName: 'Output Pose', }, diff --git a/editor/i18n/zh/animation.js b/editor/i18n/zh/animation.js index 08fe6073151..a164ef8588a 100644 --- a/editor/i18n/zh/animation.js +++ b/editor/i18n/zh/animation.js @@ -18,7 +18,44 @@ module.exports = { classes: { 'cc': { + 'Animation': { + 'properties': { + 'clips': { + displayName: '剪辑列表', + tooltip: '此组件管理的所有剪辑。', + }, + 'defaultClip': { + displayName: '默认剪辑', + tooltip: '默认播放的剪辑。', + }, + 'playOnLoad': { + displayName: '加载后播放', + tooltip: '是否在组件加载完成后自动播放默认剪辑。', + }, + }, + }, + 'SkeletalAnimation': { + 'properties': { + __extends__: 'classes.cc.Animation.properties', + 'sockets': { + displayName: '挂点列表', + tooltip: '当前动画组件维护的挂点列表。要挂载自定义节点到受动画驱动的骨骼上,必须先在此注册挂点。', + }, + 'useBakedAnimation': { + displayName: '预烘培动画', + tooltip: '是否预烘焙动画,默认启用,可以大幅提高运行效时率,但所有动画效果会被彻底固定,不支持任何形式的编辑和混合。', + }, + }, + }, 'animation': { + 'AnimationController': { + properties: { + 'graph': { + displayName: '图', + tooltip: '此动画控制器所关联的动画图或动画图变体。', + }, + }, + }, 'PoseGraphOutputNode': { displayName: '输出姿态', }, diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 2e51cd91d3d..ae59472f96f 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -225,13 +225,6 @@ module.exports = link(mixin({ shadowMapSize: '阴影贴图分辨率,目前支持 Low_256x256、Medium_512x512、High_1024x1024、Ultra_2048x2048 四种精度的纹理', maxReceived: '产生阴影的有效光源数量', }, - animation: { - default_clip: '在勾选自动播放或调用 play() 时默认播放的动画 clip。', - clips: '通过脚本可以访问并播放的 AnimationClip 列表', - play_on_load: '是否在运行游戏后自动播放默认动画 clip。', - use_baked_animation: '是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,
但所有动画效果会被彻底固定,不支持任何形式的编辑', - sockets: '当前动画组件维护的挂点数组。要挂载自定义节点到受动画驱动的骨骼上,必须先在此注册挂点', - }, audio: { clip: '通过该组件播放的默认 AudioClip 引用', volume: '音频的音量', From 72db3322bdfed3af3f5cee355b64d3dea057bac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=90=89=E6=9E=97?= <798080536@qq.com> Date: Fri, 21 Jul 2023 15:19:24 +0800 Subject: [PATCH 061/232] add light probe group help (#15797) --- cocos/core/math/vec2.ts | 8 +------- cocos/gi/light-probe/light-probe-group.ts | 2 ++ editor/i18n/en/localization.js | 1 + editor/i18n/zh/localization.js | 1 + native/cocos/math/Vec2.h | 1 - 5 files changed, 5 insertions(+), 8 deletions(-) diff --git a/cocos/core/math/vec2.ts b/cocos/core/math/vec2.ts index b3d9aa33150..4513d732f6c 100644 --- a/cocos/core/math/vec2.ts +++ b/cocos/core/math/vec2.ts @@ -297,13 +297,10 @@ export class Vec2 extends ValueType { * @override (a:Vec2, b:Vec2) => number * @override [deprecated] (out:Vec3, a:Vec2, b:Vec2) => Vec3 */ - /** - * @deprecated since v3.8.0, There is no physical meaning. - */ public static cross (a: IVec2Like, b: IVec2Like): number; /** - * @deprecated since v3.8.0, There is no physical meaning. + * @deprecated Consider use another overrides please. */ public static cross (out: Vec3, a: Out, b: Out): Vec3; @@ -719,9 +716,6 @@ export class Vec2 extends ValueType { * @param other specified vector * @return `out` */ - /** - * @deprecated since v3.8.0, There is no physical meaning. - */ public cross (other: Vec2): number { return this.x * other.y - this.y * other.x; } diff --git a/cocos/gi/light-probe/light-probe-group.ts b/cocos/gi/light-probe/light-probe-group.ts index 4da0e6bbad3..1e993cdb9d0 100644 --- a/cocos/gi/light-probe/light-probe-group.ts +++ b/cocos/gi/light-probe/light-probe-group.ts @@ -28,6 +28,7 @@ import { displayName, editable, executeInEditMode, + help, menu, range, serializable, @@ -46,6 +47,7 @@ import { AutoPlacement, PlaceMethod } from './auto-placement'; * @zh 光照探针组组件。 */ @ccclass('cc.LightProbeGroup') +@help('i18n:cc.LightProbeGroup') @menu('Rendering/LightProbeGroup') @disallowMultiple @executeInEditMode diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 1ba99832758..922eb971dae 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -71,6 +71,7 @@ module.exports = link(mixin({ DirectionalLight: `${url}/${version}/manual/en/concepts/scene/light/lightType/dir-light.html`, SphereLight: `${url}/${version}/manual/en/concepts/scene/light/lightType/sphere-light.html`, SpotLight: `${url}/${version}/manual/en/concepts/scene/light/lightType/spot-light.html`, + LightProbeGroup: `${url}/${version}/manual/en/concepts/scene/light/probe/light-probe.html`, UICoordinateTracker: `${url}/${version}/manual/en/ui-system/components/editor/ui-coordinate-tracker.html`, Animation: `${url}/${version}/manual/en/animation/animation-component.html`, SkeletalAnimation: `${url}/${version}/manual/en/animation/skeletal-animation.html`, diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index ae59472f96f..7e0569856a5 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -71,6 +71,7 @@ module.exports = link(mixin({ DirectionalLight: `${url}/${version}/manual/zh/concepts/scene/light/lightType/dir-light.html`, SphereLight: `${url}/${version}/manual/zh/concepts/scene/light/lightType/sphere-light.html`, SpotLight: `${url}/${version}/manual/zh/concepts/scene/light/lightType/spot-light.html`, + LightProbeGroup: `${url}/${version}/manual/zh/concepts/scene/light/probe/light-probe.html`, UICoordinateTracker: `${url}/${version}/manual/zh/ui-system/components/editor/ui-coordinate-tracker.html`, Animation: `${url}/${version}/manual/zh/animation/animation-component.html`, SkeletalAnimation: `${url}/${version}/manual/zh/animation/skeletal-animation.html`, diff --git a/native/cocos/math/Vec2.h b/native/cocos/math/Vec2.h index 163c3350c67..dcf5abaac9c 100644 --- a/native/cocos/math/Vec2.h +++ b/native/cocos/math/Vec2.h @@ -510,7 +510,6 @@ class CC_DLL Vec2 { /** Calculates cross product of two points. @return float @since v2.1.4 - @deprecated since v3.8.0, There is no physical meaning. */ inline float cross(const Vec2 &other) const { return x * other.y - y * other.x; From acab20f3482fb82f1770e99c2acffe497aff1f11 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Mon, 24 Jul 2023 10:21:39 +0800 Subject: [PATCH 062/232] fix multi touch cause crash on Android platform (#15796) --- .../cocos/platform/android/AndroidPlatform.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index d39df1f0d16..fc8d213420a 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -422,7 +422,8 @@ class GameInputProxy { if (actionMasked == AMOTION_EVENT_ACTION_DOWN || actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { if (actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { - eventChangedIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + eventChangedIndex = ((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) + >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); } else { eventChangedIndex = 0; } @@ -431,7 +432,8 @@ class GameInputProxy { actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { touchEvent.type = cc::TouchEvent::Type::ENDED; if (actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { - eventChangedIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + eventChangedIndex = ((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) + >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); } else { eventChangedIndex = 0; } @@ -443,8 +445,9 @@ class GameInputProxy { return false; } + bool touchHandled = true; if (eventChangedIndex >= 0) { - addTouchEvent(touchEvent, eventChangedIndex, motionEvent); + touchHandled = addTouchEvent(touchEvent, eventChangedIndex, motionEvent); } else { for (int i = 0; i < motionEvent->pointerCount; i++) { addTouchEvent(touchEvent, i, motionEvent); @@ -452,7 +455,7 @@ class GameInputProxy { } events::Touch::broadcast(touchEvent); touchEvent.touches.clear(); - return true; + return touchHandled; } return false; } @@ -670,14 +673,15 @@ class GameInputProxy { } private: - static void addTouchEvent(cc::TouchEvent &touchEvent, int index, GameActivityMotionEvent *motionEvent) { + static bool addTouchEvent(cc::TouchEvent &touchEvent, int index, GameActivityMotionEvent *motionEvent) { if (index < 0 || index >= motionEvent->pointerCount) { - ABORT_IF(false); + return false; } int id = motionEvent->pointers[index].id; float x = GameActivityPointerAxes_getX(&motionEvent->pointers[index]); float y = GameActivityPointerAxes_getY(&motionEvent->pointers[index]); touchEvent.touches.emplace_back(x, y, id); + return true; } static void setMousePosition(cc::MouseEvent &mouseEvent, GameActivityMotionEvent *motionEvent) { From 069557388ac9994193c20fcd0c0052d7634ebca7 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Tue, 25 Jul 2023 10:01:24 +0800 Subject: [PATCH 063/232] sky effect support blend and fog (#15801) --- .../lighting-flow/common-flow.chunk | 2 ++ .../model-functions/standard.chunk | 2 +- .../main-functions/misc/sky-fs.chunk | 9 ++++- .../assets/effects/advanced/car-paint.effect | 2 +- editor/assets/effects/advanced/glass.effect | 2 +- editor/assets/effects/advanced/sky.effect | 35 +++++++++++++++---- 6 files changed, 41 insertions(+), 11 deletions(-) diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index d21d83c428d..ad2dc2efcae 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -119,6 +119,7 @@ #endif #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + lightingResult.specularColorWithLighting2ndSpecular *= surfaceData.color2ndSpecular; //temporary coloration CCSurfacesLightingCalculateDirectMultiLayerBlending(lightingResult, lightingData2ndSpecular); #endif @@ -264,6 +265,7 @@ #endif #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND + lightingResult.specularColorWithLighting2ndSpecular *= surfaceData.color2ndSpecular; //temporary coloration CCSurfacesLightingCalculateDirectMultiLayerBlending(lightingResult, lightingData2ndSpecular); CCSurfacesLightingCalculateEnvironmentMultiLayerBlending(lightingResult, lightingData2ndSpecular); #endif diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index accd9389b63..74d1afe399f 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -123,7 +123,7 @@ void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 in #if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE envSpec = EnvReflection(cc_reflectionProbeCubemap, R, roughness, cc_ambientGround.w); #endif - //todo: planar refraction from scene color + // todo: planar refraction from scene color when use planar probe or no probe #endif #if CC_USE_IBL && CC_USE_REFLECTION_PROBE != REFLECTION_PROBE_TYPE_CUBE diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk index 74e5b4de8ea..ec31cee9515 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk @@ -22,5 +22,12 @@ void main() { color.rgb = LinearToSRGB(color.rgb); #endif - fragColorX = color; + //todo: LDR fogging in gamma space, HDR fogging should move before tone mapping + #if CC_USE_FOG != CC_FOG_NONE + float fogFactor = 1.0; + CC_TRANSFER_FOG_BASE(vec4(FSInput_worldPos, 1.0), fogFactor); + CC_APPLY_FOG_BASE(color, fogFactor); + #endif + + fragColorX = color; } diff --git a/editor/assets/effects/advanced/car-paint.effect b/editor/assets/effects/advanced/car-paint.effect index 6e5aede6071..186e6b5276f 100644 --- a/editor/assets/effects/advanced/car-paint.effect +++ b/editor/assets/effects/advanced/car-paint.effect @@ -24,7 +24,7 @@ CCEffect %{ coatColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { displayName: CoatColor, type: color } } flakeDensity: { value: 0.5, target: flakeParam.x, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } flakeColorIntensity: { value: 0.2, target: flakeParam.y, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } - flakeTiling: { value: 10.0, target: flakeParam.z, editor: { parent: USE_FLAKE, slide: true, range: [1.0, 40.0], step: 0.001 } } + flakeTiling: { value: 10.0, target: flakeParam.z, editor: { parent: USE_FLAKE, slide: true, range: [1.0, 50.0], step: 0.001 } } coatNormalStrength: { value: 0.1, target: flakeParam.w, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } gradientColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { parent: USE_GRADIENT_COLOR, type: color } } gradientIntensity: { value: 0.5, target: emissiveScaleParam.y, editor: { parent: USE_GRADIENT_COLOR, slide: true, range: [0, 1.0], step: 0.001 } } diff --git a/editor/assets/effects/advanced/glass.effect b/editor/assets/effects/advanced/glass.effect index f8c76e0ce2e..8fd1228902a 100644 --- a/editor/assets/effects/advanced/glass.effect +++ b/editor/assets/effects/advanced/glass.effect @@ -239,7 +239,7 @@ CCProgram surface-fragment %{ float fresnel = CalculateFresnelCoefficient(min(F0, F90), F90, NoVSat); result.fresnel = vec3(fresnel); #else - // simply fix oit depth issue for bright color alpha blending + // simply fix single blend source issue for bright color alpha blending float threshold = 0.5, bright = dot(result.environmentSpecular, vec3(0.33333)); if (bright > threshold) result.environmentSpecular = result.environmentSpecular / bright * threshold; diff --git a/editor/assets/effects/advanced/sky.effect b/editor/assets/effects/advanced/sky.effect index d8c9f59d29d..b7e2e59ff2f 100644 --- a/editor/assets/effects/advanced/sky.effect +++ b/editor/assets/effects/advanced/sky.effect @@ -7,7 +7,10 @@ CCEffect %{ - vert: sky-vs frag: sky-fs properties: &props - environmentMap: { value: grey } + environmentMap: { value: grey } + positionScaling: { value: 1.0, target: params.w, editor: { tooltip: 'Set a smaller value (such as less than 1.0) to remove the effects of fog' } } + blendEnvironmentMap: { value: grey, editor: { parent: BLEND_ENV_MAP } } + blendWeight: { value: 0.0, target: params.x, editor: { parent: BLEND_ENV_MAP } } priority : max - 10 rasterizerState : &r1 cullMode : none @@ -24,30 +27,46 @@ CCEffect %{ depthStencilState: *d1 }% +CCProgram shared-ubos %{ + uniform Constants { + vec4 params; + }; +}% CCProgram surface-vertex %{ #define CC_SURFACES_VERTEX_MODIFY_WORLD_POS vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) { // Apply uniform scaling for atmosphere effects - return In.worldPos; + return In.worldPos * params.w; } }% CCProgram surface-fragment %{ - uniform samplerCube environmentMap; + #if BLEND_ENV_MAP + uniform samplerCube blendEnvironmentMap; + #endif #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec3 sampleEnvMap(samplerCube tex, vec3 R) + { + vec3 c = vec3(1.0); + #if USE_RGBE_CUBEMAP + c *= unpackRGBE(fragTextureLod(tex, R, 0.0)); + #else + c *= SRGBToLinear(fragTextureLod(tex, R, 0.0).rgb); + #endif + return c; + } vec4 SurfacesFragmentModifyBaseColorAndTransparency() { vec3 c = vec3(1.0); #if CC_USE_IBL vec3 normal = normalize(FSInput_worldNormal); vec3 rotationDir = RotationVecFromAxisY(normal.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); - #if USE_RGBE_CUBEMAP - c *= unpackRGBE(fragTextureLod(environmentMap, rotationDir.xyz, 0.0)); - #else - c *= SRGBToLinear(fragTextureLod(environmentMap, rotationDir.xyz, 0.0).rgb); + c = sampleEnvMap(environmentMap, rotationDir); + #if BLEND_ENV_MAP + c = mix(c, sampleEnvMap(blendEnvironmentMap, rotationDir), params.x); #endif #endif return vec4(c * cc_ambientSky.w, 1.0); @@ -59,6 +78,7 @@ CCProgram sky-vs %{ #include #include + #include #include #include }% @@ -69,6 +89,7 @@ CCProgram sky-fs %{ #include #include + #include #include #include }% From d97d3c655a28cdaec52882921a3a60f5eb2f343f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Tue, 25 Jul 2023 15:40:55 +0800 Subject: [PATCH 064/232] add global post settings (#15558) --- cocos/native-binding/decorators.ts | 20 ++++- cocos/render-scene/scene/index.jsb.ts | 10 +++ cocos/render-scene/scene/index.ts | 1 + cocos/render-scene/scene/post-settings.ts | 37 +++++++++ cocos/rendering/pipeline-scene-data.ts | 11 ++- cocos/scene-graph/scene-globals.jsb.ts | 24 +++++- cocos/scene-graph/scene-globals.ts | 46 +++++++++++- editor/i18n/en/localization.js | 3 + editor/i18n/zh/localization.js | 3 + editor/inspector/contributions/node.js | 7 ++ native/CMakeLists.txt | 2 + .../cocos/core/scene-graph/SceneGlobals.cpp | 10 +++ native/cocos/core/scene-graph/SceneGlobals.h | 4 + .../renderer/pipeline/PipelineSceneData.cpp | 4 + .../renderer/pipeline/PipelineSceneData.h | 4 + native/cocos/scene/PostSettings.cpp | 75 +++++++++++++++++++ native/cocos/scene/PostSettings.h | 67 +++++++++++++++++ native/tools/swig-config/pipeline.i | 1 + native/tools/swig-config/scene.i | 6 ++ 19 files changed, 328 insertions(+), 7 deletions(-) create mode 100644 cocos/render-scene/scene/post-settings.ts create mode 100644 native/cocos/scene/PostSettings.cpp create mode 100644 native/cocos/scene/PostSettings.h diff --git a/cocos/native-binding/decorators.ts b/cocos/native-binding/decorators.ts index fb4dc49c7c9..cfdfc74d5c9 100644 --- a/cocos/native-binding/decorators.ts +++ b/cocos/native-binding/decorators.ts @@ -792,6 +792,21 @@ export function patch_cc_PointLight(ctx: cc_PointLight_Context_Args, apply = def apply(() => { $.ccclass('cc.PointLight')(PointLight); }, 'ccclass', null); } // end of patch_cc_PointLight +//---- class cc_PostSettingsInfo +interface cc_PostSettingsInfo_Context_Args { + PostSettingsInfo: any; + ToneMappingType: any; +} +export function patch_cc_PostSettingsInfo(ctx: cc_PostSettingsInfo_Context_Args, apply = defaultExec) { + const { PostSettingsInfo, ToneMappingType } = { ...ctx }; + const toneMappingTypeDescriptor = Object.getOwnPropertyDescriptor(PostSettingsInfo.prototype, 'toneMappingType'); + apply(() => { $.tooltip('i18n:tone_mapping.toneMappingType')(PostSettingsInfo.prototype, 'toneMappingType', toneMappingTypeDescriptor); }, 'tooltip', 'toneMappingType'); + apply(() => { $.type(ToneMappingType)(PostSettingsInfo.prototype, 'toneMappingType', toneMappingTypeDescriptor); }, 'type', 'toneMappingType'); + apply(() => { $.editable(PostSettingsInfo.prototype, 'toneMappingType', toneMappingTypeDescriptor); }, 'editable', 'toneMappingType'); + apply(() => { $.serializable(PostSettingsInfo.prototype, '_toneMappingType', () => { return ToneMappingType.DEFAULT; }); }, 'serializable', '_toneMappingType'); + apply(() => { $.ccclass('cc.PostSettingsInfo')(PostSettingsInfo); }, 'ccclass', null); +} // end of patch_cc_PostSettingsInfo + //---- class cc_RangedDirectionalLight interface cc_RangedDirectionalLight_Context_Args { RangedDirectionalLight: any; @@ -874,9 +889,10 @@ interface cc_SceneGlobals_Context_Args { OctreeInfo: any; SkinInfo: any; LightProbeInfo: any; + PostSettingsInfo: any; } export function patch_cc_SceneGlobals(ctx: cc_SceneGlobals_Context_Args, apply = defaultExec) { - const { SceneGlobals, AmbientInfo, ShadowsInfo, SkyboxInfo, FogInfo, OctreeInfo, SkinInfo, LightProbeInfo } = { ...ctx }; + const { SceneGlobals, AmbientInfo, ShadowsInfo, SkyboxInfo, FogInfo, OctreeInfo, SkinInfo, LightProbeInfo, PostSettingsInfo } = { ...ctx }; const skyboxDescriptor = Object.getOwnPropertyDescriptor(SceneGlobals.prototype, 'skybox'); apply(() => { $.editable(SceneGlobals.prototype, 'ambient', () => { return new AmbientInfo(); }); }, 'editable', 'ambient'); apply(() => { $.serializable(SceneGlobals.prototype, 'ambient', () => { return new AmbientInfo(); }); }, 'serializable', 'ambient'); @@ -893,6 +909,8 @@ export function patch_cc_SceneGlobals(ctx: cc_SceneGlobals_Context_Args, apply = apply(() => { $.editable(SceneGlobals.prototype, 'skin', () => { return new SkinInfo(); }); }, 'editable', 'skin'); apply(() => { $.serializable(SceneGlobals.prototype, 'lightProbeInfo', () => { return new LightProbeInfo(); }); }, 'serializable', 'lightProbeInfo'); apply(() => { $.editable(SceneGlobals.prototype, 'lightProbeInfo', () => { return new LightProbeInfo(); }); }, 'editable', 'lightProbeInfo'); + apply(() => { $.serializable(SceneGlobals.prototype, 'postSettings', () => { return new PostSettingsInfo(); }); }, 'serializable', 'postSettings'); + apply(() => { $.editable(SceneGlobals.prototype, 'postSettings', () => { return new PostSettingsInfo(); }); }, 'editable', 'postSettings'); apply(() => { $.serializable(SceneGlobals.prototype, 'bakedWithStationaryMainLight', () => { return false; }); }, 'serializable', 'bakedWithStationaryMainLight'); apply(() => { $.editable(SceneGlobals.prototype, 'bakedWithStationaryMainLight', () => { return false; }); }, 'editable', 'bakedWithStationaryMainLight'); apply(() => { $.serializable(SceneGlobals.prototype, 'bakedWithHighpLightmap', () => { return false; }); }, 'serializable', 'bakedWithHighpLightmap'); diff --git a/cocos/render-scene/scene/index.jsb.ts b/cocos/render-scene/scene/index.jsb.ts index 87d7cff567e..9cdfcdbacc9 100644 --- a/cocos/render-scene/scene/index.jsb.ts +++ b/cocos/render-scene/scene/index.jsb.ts @@ -40,6 +40,7 @@ import type { Fog as JsbFog, Shadows as JsbShadows, Skybox as JsbSkybox, + PostSettings as JsbPostSettings } from './index'; // NOTE: why don't we export FogInfo and ShadowInfo from 'index.ts' @@ -339,6 +340,11 @@ export const EnvironmentLightingType = Enum({ DIFFUSEMAP_WITH_REFLECTION: 2, }); +export const ToneMappingType = Enum({ + DEFAULT: 0, + LINEAR: 1, +}); + export const ShadowsInfo: typeof JsbShadowsInfo = jsb.ShadowsInfo; export type ShadowsInfo = JsbShadowsInfo; export const Shadows: typeof JsbShadows = jsb.Shadows; @@ -377,6 +383,10 @@ export const Skybox: typeof JsbSkybox = jsb.Skybox; export type Skybox = JsbSkybox; cclegacy.Skybox = Skybox; +export const PostSettings: typeof JsbPostSettings = jsb.PostSettings; +export type PostSettings = JsbPostSettings; +cclegacy.PostSettings = PostSettings; + export * from './model'; export * from './submodel'; export * from './camera'; diff --git a/cocos/render-scene/scene/index.ts b/cocos/render-scene/scene/index.ts index f16cab46bd9..51843260cb6 100644 --- a/cocos/render-scene/scene/index.ts +++ b/cocos/render-scene/scene/index.ts @@ -39,3 +39,4 @@ export * from './point-light'; export * from './ranged-directional-light'; export * from './reflection-probe'; export * from './lod-group'; +export * from './post-settings'; diff --git a/cocos/render-scene/scene/post-settings.ts b/cocos/render-scene/scene/post-settings.ts new file mode 100644 index 00000000000..9d124385770 --- /dev/null +++ b/cocos/render-scene/scene/post-settings.ts @@ -0,0 +1,37 @@ +import { Enum, cclegacy } from '../../core'; +import { PostSettingsInfo } from '../../scene-graph/scene-globals'; + +export const ToneMappingType = Enum({ + DEFAULT: 0, + LINEAR: 1, +}); + +export class PostSettings { + protected _toneMappingType = ToneMappingType.DEFAULT; + protected _activated = false; + + set toneMappingType (val) { + this._toneMappingType = val; + this._updatePipeline(); + } + get toneMappingType (): number { + return this._toneMappingType; + } + public initialize (postSettingsInfo: PostSettingsInfo): void { + this._toneMappingType = postSettingsInfo.toneMappingType; + } + + public activate (): void { + this._updatePipeline(); + this._activated = true; + } + + protected _updatePipeline (): void { + const root = cclegacy.director.root; + const pipeline = root.pipeline; + pipeline.macros.CC_TONE_MAPPING_TYPE = this._toneMappingType; + if (this._activated) { + root.onGlobalPipelineStateChanged(); + } + } +} diff --git a/cocos/rendering/pipeline-scene-data.ts b/cocos/rendering/pipeline-scene-data.ts index ccee5477714..529d6c44cb9 100644 --- a/cocos/rendering/pipeline-scene-data.ts +++ b/cocos/rendering/pipeline-scene-data.ts @@ -34,7 +34,7 @@ import { Pass } from '../render-scene/core/pass'; import { CSMLayers } from './shadow/csm-layers'; import { cclegacy } from '../core'; import { Skin } from '../render-scene/scene/skin'; -import { Model } from '../render-scene/scene'; +import { Model, PostSettings } from '../render-scene/scene'; import { MeshRenderer } from '../3d/framework/mesh-renderer'; const GEOMETRY_RENDERER_TECHNIQUE_COUNT = 6; @@ -108,6 +108,7 @@ export class PipelineSceneData { public csmLayers: CSMLayers = new CSMLayers(); public octree: Octree = new Octree(); public skin: Skin = new Skin(); + public postSettings: PostSettings = new PostSettings(); public lightProbes = cclegacy.internal.LightProbes ? new cclegacy.internal.LightProbes() : null; /** @@ -224,7 +225,9 @@ export class PipelineSceneData { const vbSize = vbStride * 8; this._occlusionQueryVertexBuffer = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, vbSize, vbStride, + MemoryUsageBit.DEVICE, + vbSize, + vbStride, )); this._occlusionQueryVertexBuffer.update(vertices); @@ -234,7 +237,9 @@ export class PipelineSceneData { const ibSize = ibStride * 36; this._occlusionQueryIndicesBuffer = device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, ibSize, ibStride, + MemoryUsageBit.DEVICE, + ibSize, + ibStride, )); this._occlusionQueryIndicesBuffer.update(indices); diff --git a/cocos/scene-graph/scene-globals.jsb.ts b/cocos/scene-graph/scene-globals.jsb.ts index 36421dd2515..fc00e60db45 100644 --- a/cocos/scene-graph/scene-globals.jsb.ts +++ b/cocos/scene-graph/scene-globals.jsb.ts @@ -24,7 +24,7 @@ import { legacyCC } from '../core/global-exports'; import { CCFloat, CCInteger } from '../core/data'; import { TextureCube } from '../asset/assets/texture-cube'; import { Enum } from '../core/value-types'; -import { Ambient, EnvironmentLightingType } from '../render-scene/scene'; +import { Ambient, EnvironmentLightingType, ToneMappingType } from '../render-scene/scene'; import { Material } from '../asset/assets/material'; import { Vec2, Vec3, Color, Vec4 } from '../core/math'; import * as decros from '../native-binding/decorators'; @@ -37,6 +37,7 @@ import type { SceneGlobals as JsbSceneGlobals, LightProbeInfo as JsbLightProbeInfo, SkinInfo as JsbSkinInfo, + PostSettingsInfo as JsbPostSettingsInfo, } from './scene-globals'; declare const jsb: any; @@ -181,6 +182,10 @@ export const SkinInfo: typeof JsbSkinInfo = jsb.SkinInfo; export type SkinInfo = JsbSkinInfo; legacyCC.SkinInfo = SkinInfo; +export const PostSettingsInfo: typeof JsbPostSettingsInfo = jsb.PostSettingsInfo; +export type PostSettingsInfo = JsbPostSettingsInfo; +legacyCC.PostSettingsInfo = PostSettingsInfo; + (function () { const sceneGlobalsProto: any = SceneGlobals.prototype; @@ -192,6 +197,7 @@ legacyCC.SkinInfo = SkinInfo; this._octreeRef = this.getOctreeInfo(); this._lightProbeRef = this.getLightProbeInfo(); this._skinRef = this.getSkinInfo(); + this._postSettingsRef = this.getPostSettingsInfo(); }; Object.defineProperty(sceneGlobalsProto, 'ambient', { @@ -290,13 +296,25 @@ legacyCC.SkinInfo = SkinInfo; }, }); + Object.defineProperty(sceneGlobalsProto, 'postSettings', { + enumerable: true, + configurable: true, + get() { + return this._postSettingsRef; + }, + set(v) { + this._postSettingsRef = v; + this.setPostSettingsInfo(v); + }, + }); + })(); // handle meta data, it is generated automatically -decros.patch_cc_SceneGlobals({SceneGlobals, AmbientInfo, SkyboxInfo, FogInfo, ShadowsInfo, LightProbeInfo, OctreeInfo, SkinInfo}); +decros.patch_cc_SceneGlobals({SceneGlobals, AmbientInfo, SkyboxInfo, FogInfo, ShadowsInfo, LightProbeInfo, OctreeInfo, SkinInfo, PostSettingsInfo}); decros.patch_cc_OctreeInfo({OctreeInfo, CCInteger, Vec3, DEFAULT_WORLD_MAX_POS, DEFAULT_WORLD_MIN_POS, DEFAULT_OCTREE_DEPTH}); @@ -311,3 +329,5 @@ decros.patch_cc_AmbientInfo({AmbientInfo, Vec4, Ambient, CCFloat, legacyCC}); decros.patch_cc_LightProbeInfo({LightProbeInfo, CCFloat, CCInteger}); decros.patch_cc_SkinInfo({SkinInfo, CCFloat}); + +decros.patch_cc_PostSettingsInfo({PostSettingsInfo, ToneMappingType}); diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index 158b717febe..f3d97b259d5 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -45,6 +45,7 @@ import { cclegacy, macro } from '../core'; import { Scene } from './scene'; import { NodeEventType } from './node-event'; import { property } from '../core/data/class-decorator'; +import { PostSettings, ToneMappingType } from '../render-scene/scene/post-settings'; const _up = new Vec3(0, 1, 0); const _v3 = new Vec3(); @@ -1183,6 +1184,40 @@ export class SkinInfo { } legacyCC.SkinInfo = SkinInfo; +@ccclass('cc.PostSettingsInfo') +export class PostSettingsInfo { + /** + * @zh 色调映射类型 + * @en Tone mapping type + */ + @editable + @type(ToneMappingType) + @tooltip('i18n:tone_mapping.toneMappingType') + set toneMappingType (val) { + this._toneMappingType = val; + if (this._resource) { + this._resource.toneMappingType = val; + } + } + + get toneMappingType (): number { + return this._toneMappingType; + } + + @serializable + protected _toneMappingType = ToneMappingType.DEFAULT; + + protected _resource: PostSettings | null = null; + + public activate (resource: PostSettings): void { + this._resource = resource; + this._resource.initialize(this); + this._resource.activate(); + } +} + +legacyCC.PostSettingsInfo = PostSettingsInfo; + export interface ILightProbeNode { node: Node; probes: Vec3[] | null; @@ -1613,6 +1648,14 @@ export class SceneGlobals { @serializable public lightProbeInfo = new LightProbeInfo(); + /** + * @en Tone mapping related configuration + * @zh 色调映射相关配置 + */ + @editable + @serializable + public postSettings = new PostSettingsInfo(); + /** * @en bake with stationary main light * @zh 主光源是否以静止状态烘培 @@ -1648,8 +1691,9 @@ export class SceneGlobals { this.fog.activate(sceneData.fog); this.octree.activate(sceneData.octree); this.skin.activate(sceneData.skin); + this.postSettings.activate(sceneData.postSettings); if (this.lightProbeInfo && sceneData.lightProbes) { - this.lightProbeInfo.activate(scene, sceneData.lightProbes); + this.lightProbeInfo.activate(scene, sceneData.lightProbes as LightProbes); } const root = legacyCC.director.root as Root; diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 922eb971dae..4afe3536027 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -1318,6 +1318,9 @@ module.exports = link(mixin({ shadingScale: 'Rendering resolution.', enableShadingScaleInEditor: 'Enable Shading Scale In Editor', }, + tone_mapping: { + toneMappingType: 'Tone mapping type,valid only when HDR is enabled.', + }, }, require('./animation'), diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 7e0569856a5..9a3d870375a 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -1292,6 +1292,9 @@ module.exports = link(mixin({ shadingScale: '渲染分辨率', enableShadingScaleInEditor: '是否在编辑器中缩放渲染分辨率', }, + tone_mapping: { + toneMappingType: '色调映射方式,只在启用HDR时生效。', + }, }, require('./animation'), diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index fb0dbce8e80..bf17bebb444 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -381,6 +381,7 @@ exports.template = /* html*/` + @@ -453,6 +454,7 @@ exports.$ = { sceneSkyboxAfter: '.container > .body > .scene > .skybox > .after', sceneOctree: '.container > .body > .scene > .octree', sceneSkin: '.container > .body > .scene > .skin', + scenePostSettings: '.scene > .postSettings', node: '.container > .body > .node', nodeHeader: '.container > .body > .node > .component-header', @@ -953,6 +955,9 @@ const Elements = { panel.dump._globals.skin.help = panel.getHelpUrl({ help: 'i18n:cc.Skin' }); panel.$.sceneSkin.render(panel.dump._globals.skin); + panel.dump._globals.postSettings.displayName = 'PostSettings'; + panel.$.scenePostSettings.render(panel.dump._globals.postSettings); + const $skyProps = panel.$.sceneSkybox.querySelectorAll('ui-prop[type="dump"]'); $skyProps.forEach(($prop) => { if ($prop.dump.name === 'envLightingType') { @@ -1089,6 +1094,8 @@ const Elements = { const $prop = useHDR ? panel.$.sceneSkyboxEnvmapHDR : panel.$.sceneSkyboxEnvmapLDR; const uuid = $prop.dump.value.uuid; Elements.scene.setEnvMapAndConvolutionMap.call(panel, uuid); + + panel.$.scenePostSettings.style.display = useHDR ? 'inline-flex' : 'none'; }, skyboxEnvmapChange(useHDR, event) { const panel = this; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index bf1218beb9c..a1c3dacce9b 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1536,6 +1536,8 @@ cocos_source_files( cocos/scene/ReflectionProbeManager.h cocos/scene/Skin.h cocos/scene/Skin.cpp + cocos/scene/PostSettings.h + cocos/scene/PostSettings.cpp ) ##### primitive diff --git a/native/cocos/core/scene-graph/SceneGlobals.cpp b/native/cocos/core/scene-graph/SceneGlobals.cpp index d198e627d6c..6947fcbb5b6 100644 --- a/native/cocos/core/scene-graph/SceneGlobals.cpp +++ b/native/cocos/core/scene-graph/SceneGlobals.cpp @@ -33,6 +33,7 @@ #include "scene/Shadow.h" #include "scene/Skin.h" #include "scene/Skybox.h" +#include "scene/PostSettings.h" namespace cc { @@ -46,6 +47,7 @@ SceneGlobals::SceneGlobals() { _bakedWithStationaryMainLight = false; _bakedWithHighpLightmap = false; _skinInfo = ccnew scene::SkinInfo(); + _postSettingsInfo = ccnew scene::PostSettingsInfo(); } void SceneGlobals::activate(Scene *scene) { @@ -78,6 +80,10 @@ void SceneGlobals::activate(Scene *scene) { _skinInfo->activate(sceneData->getSkin()); } + if (_postSettingsInfo != nullptr && sceneData->getPostSettings()) { + _postSettingsInfo->activate(sceneData->getPostSettings()); + } + Root::getInstance()->onGlobalPipelineStateChanged(); } @@ -117,4 +123,8 @@ void SceneGlobals::setSkinInfo(scene::SkinInfo *info) { _skinInfo = info; } +void SceneGlobals::setPostSettingsInfo(scene::PostSettingsInfo *info) { + _postSettingsInfo = info; +} + } // namespace cc diff --git a/native/cocos/core/scene-graph/SceneGlobals.h b/native/cocos/core/scene-graph/SceneGlobals.h index 802151fbc65..b16f688cf02 100644 --- a/native/cocos/core/scene-graph/SceneGlobals.h +++ b/native/cocos/core/scene-graph/SceneGlobals.h @@ -36,6 +36,7 @@ class SkyboxInfo; class FogInfo; class OctreeInfo; class SkinInfo; +class PostSettingsInfo; } // namespace scene namespace gi { @@ -58,6 +59,7 @@ class SceneGlobals : public RefCounted { inline bool getBakedWithStationaryMainLight() const { return _bakedWithStationaryMainLight; } inline bool getBakedWithHighpLightmap() const { return _bakedWithHighpLightmap; } inline scene::SkinInfo *getSkinInfo() const { return _skinInfo.get(); } + inline scene::PostSettingsInfo *getPostSettingsInfo() const { return _postSettingsInfo.get(); } void setAmbientInfo(scene::AmbientInfo *info); void setShadowsInfo(scene::ShadowsInfo *info); @@ -68,6 +70,7 @@ class SceneGlobals : public RefCounted { void setBakedWithStationaryMainLight(bool value); void setBakedWithHighpLightmap(bool value); void setSkinInfo(scene::SkinInfo *info); + void setPostSettingsInfo(scene::PostSettingsInfo *info); private: IntrusivePtr _ambientInfo; @@ -77,6 +80,7 @@ class SceneGlobals : public RefCounted { IntrusivePtr _octreeInfo; IntrusivePtr _lightProbeInfo; IntrusivePtr _skinInfo; + IntrusivePtr _postSettingsInfo; bool _bakedWithStationaryMainLight; bool _bakedWithHighpLightmap; }; diff --git a/native/cocos/renderer/pipeline/PipelineSceneData.cpp b/native/cocos/renderer/pipeline/PipelineSceneData.cpp index 6383ee2032a..3a0db2f82ec 100644 --- a/native/cocos/renderer/pipeline/PipelineSceneData.cpp +++ b/native/cocos/renderer/pipeline/PipelineSceneData.cpp @@ -38,6 +38,8 @@ #include "scene/Shadow.h" #include "scene/Skin.h" #include "scene/Skybox.h" +#include "scene/Model.h" +#include "scene/PostSettings.h" namespace cc { namespace pipeline { @@ -51,6 +53,7 @@ PipelineSceneData::PipelineSceneData() { _octree = ccnew scene::Octree(); _lightProbes = ccnew gi::LightProbes(); _skin = ccnew scene::Skin(); + _postSettings = ccnew scene ::PostSettings(); } PipelineSceneData::~PipelineSceneData() { @@ -62,6 +65,7 @@ PipelineSceneData::~PipelineSceneData() { CC_SAFE_DELETE(_csmLayers); CC_SAFE_DELETE(_lightProbes); CC_SAFE_DELETE(_skin); + CC_SAFE_DELETE(_postSettings); } void PipelineSceneData::activate(gfx::Device *device) { diff --git a/native/cocos/renderer/pipeline/PipelineSceneData.h b/native/cocos/renderer/pipeline/PipelineSceneData.h index cb9e9eeab0a..1b2867a0b49 100644 --- a/native/cocos/renderer/pipeline/PipelineSceneData.h +++ b/native/cocos/renderer/pipeline/PipelineSceneData.h @@ -44,6 +44,7 @@ class Fog; class Octree; class Light; class Skin; +class PostSettings; } // namespace scene namespace gi { class LightProbes; @@ -76,6 +77,7 @@ class CC_DLL PipelineSceneData : public RefCounted { inline scene::Octree *getOctree() const { return _octree; } inline gi::LightProbes *getLightProbes() const { return _lightProbes; } inline scene::Skin *getSkin() const { return _skin; } + inline scene::PostSettings *getPostSettings() const { return _postSettings; } inline gfx::InputAssembler *getOcclusionQueryInputAssembler() const { return _occlusionQueryInputAssembler; } inline scene::Pass *getOcclusionQueryPass() const { return _occlusionQueryPass; } inline gfx::Shader *getOcclusionQueryShader() const { return _occlusionQueryShader; } @@ -134,6 +136,8 @@ class CC_DLL PipelineSceneData : public RefCounted { scene::Skin *_skin{nullptr}; // manage memory manually CSMLayers *_csmLayers{nullptr}; + // manage memory manually + scene::PostSettings *_postSettings{nullptr}; bool _isHDR{true}; bool _csmSupported{true}; diff --git a/native/cocos/scene/PostSettings.cpp b/native/cocos/scene/PostSettings.cpp new file mode 100644 index 00000000000..b83bb044a50 --- /dev/null +++ b/native/cocos/scene/PostSettings.cpp @@ -0,0 +1,75 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "scene/PostSettings.h" +#include "core/Root.h" +#include "renderer/pipeline/custom/RenderInterfaceTypes.h" +namespace cc { +namespace scene { + +void PostSettingsInfo::activate(PostSettings *resource) { + _resource = resource; + if (_resource != nullptr) { + _resource->initialize(*this); + _resource->activate(); + } +} +void PostSettingsInfo::setToneMappingType(ToneMappingType toneMappingType) { + _toneMappingType = toneMappingType; + + if (_resource != nullptr) { + _resource->setToneMappingType(toneMappingType); + } +} + +void PostSettings::activate() { + _activated = true; + updatePipeline(); +} + +void PostSettings::initialize(const PostSettingsInfo &postSettingsInfo) { + _activated = false; + _toneMappingType = postSettingsInfo.getToneMappingType(); +} + +void PostSettings::setToneMappingType(ToneMappingType toneMappingType) { + _toneMappingType = toneMappingType; + updatePipeline(); +} + +void PostSettings::updatePipeline() const { + + Root *root = Root::getInstance(); + auto *pipeline = root->getPipeline(); + + pipeline->setValue("CC_TONE_MAPPING_TYPE", static_cast(_toneMappingType)); + + if (_activated) + { + root->onGlobalPipelineStateChanged(); + } +} + +} // namespace scene +} // namespace cc diff --git a/native/cocos/scene/PostSettings.h b/native/cocos/scene/PostSettings.h new file mode 100644 index 00000000000..f81d4106a29 --- /dev/null +++ b/native/cocos/scene/PostSettings.h @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "base/RefCounted.h" + +namespace cc { + namespace scene { + enum class ToneMappingType { + DEFAULT = 0, + LINEAR = 1, + }; + + class PostSettings; + class PostSettingsInfo : public RefCounted { + public: + PostSettingsInfo() = default; + ~PostSettingsInfo() override = default; + + inline ToneMappingType getToneMappingType() const { return _toneMappingType; } + void setToneMappingType(ToneMappingType toneMappingType); + + void activate(PostSettings *resource); + PostSettings *_resource{nullptr}; + ToneMappingType _toneMappingType{ ToneMappingType::DEFAULT }; + }; + + class PostSettings final { + public: + PostSettings() = default; + ~PostSettings() = default; + void activate(); + + void initialize(const PostSettingsInfo &postSettingsInfo); + inline ToneMappingType getToneMappingType() const { return _toneMappingType; } + void setToneMappingType(ToneMappingType toneMappingType); + private: + void updatePipeline() const; + bool _activated{ false }; + ToneMappingType _toneMappingType{ ToneMappingType::DEFAULT }; + }; + + + }// namespace scene +} // namespace cc diff --git a/native/tools/swig-config/pipeline.i b/native/tools/swig-config/pipeline.i index 9df3b14f6a9..130145affda 100644 --- a/native/tools/swig-config/pipeline.i +++ b/native/tools/swig-config/pipeline.i @@ -169,6 +169,7 @@ using namespace cc; %attribute(cc::pipeline::PipelineSceneData, cc::scene::Skybox*, skybox, getSkybox); %attribute(cc::pipeline::PipelineSceneData, cc::scene::Shadows*, shadows, getShadows); %attribute(cc::pipeline::PipelineSceneData, cc::scene::Skin*, skin, getSkin); +%attribute(cc::pipeline::PipelineSceneData, cc::scene::PostSettings*, postSettings, getPostSettings); %attribute(cc::pipeline::PipelineSceneData, cc::gi::LightProbes*, lightProbes, getLightProbes); %attribute(cc::pipeline::PipelineSceneData, ccstd::vector, validPunctualLights, getValidPunctualLights, setValidPunctualLights); %attribute(cc::pipeline::PipelineSceneData, bool, csmSupported, getCSMSupported); diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index 946c8fab6df..73b03f4ddd3 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -23,6 +23,7 @@ #include "scene/Shadow.h" #include "scene/Skybox.h" #include "scene/Skin.h" +#include "scene/PostSettings.h" #include "scene/DirectionalLight.h" #include "scene/SpotLight.h" #include "scene/SphereLight.h" @@ -478,6 +479,8 @@ using namespace cc; %attribute(cc::scene::Skin, float, blurRadius, getBlurRadius, setBlurRadius); %attribute(cc::scene::Skin, float, sssIntensity, getSSSIntensity, setSSSIntensity); +%attribute(cc::scene::PostSettings, cc::scene::ToneMappingType, toneMappingType, getToneMappingType, setToneMappingType); + %attribute(cc::scene::Model, cc::scene::RenderScene*, scene, getScene, setScene); %attribute(cc::scene::Model, ccstd::vector> &, _subModels, getSubModels); %attribute(cc::scene::Model, ccstd::vector> &, subModels, getSubModels); @@ -578,6 +581,8 @@ using namespace cc; %attribute(cc::scene::OctreeInfo, cc::Vec3&, maxPos, getMaxPos, setMaxPos); %attribute(cc::scene::OctreeInfo, uint32_t, depth, getDepth, setDepth); +%attribute(cc::scene::PostSettingsInfo, cc::scene::ToneMappingType, toneMappingType, getToneMappingType, setToneMappingType); + %attribute(cc::Scene, bool, autoReleaseAssets, isAutoReleaseAssets, setAutoReleaseAssets); %attribute(cc::scene::ReflectionProbe, cc::scene::ReflectionProbe::ProbeType, probeType, getProbeType, setProbeType); @@ -678,6 +683,7 @@ using namespace cc; %include "scene/Shadow.h" %include "scene/Skybox.h" %include "scene/Skin.h" +%include "scene/PostSettings.h" %include "scene/DirectionalLight.h" %include "scene/SpotLight.h" %include "scene/SphereLight.h" From 32245a2e20ec4e6c5a6573c0c811796483930d1b Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Tue, 25 Jul 2023 18:17:28 +0800 Subject: [PATCH 065/232] fix : node._instantiate has different behavior in native scene (#15816) --- cocos/scene-graph/node.jsb.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/cocos/scene-graph/node.jsb.ts b/cocos/scene-graph/node.jsb.ts index 15f31c4beee..3f4308293ce 100644 --- a/cocos/scene-graph/node.jsb.ts +++ b/cocos/scene-graph/node.jsb.ts @@ -1304,20 +1304,13 @@ nodeProto._instantiate = function (cloned: Node, isSyncedNode: boolean) { const newPrefabInfo = (cloned as any)._prefab; if (EDITOR && newPrefabInfo) { if (cloned === newPrefabInfo.root) { + EditorExtends.PrefabUtils.addPrefabInstance?.(cloned); // newPrefabInfo.fileId = ''; } else { // var PrefabUtils = Editor.require('scene://utils/prefab'); // PrefabUtils.unlinkPrefab(cloned); } } - if (EDITOR_NOT_IN_PREVIEW) { - // TODO: Property 'sync' does not exist on type 'PrefabInfo'. - // issue: https://github.com/cocos/cocos-engine/issues/14643 - const syncing = newPrefabInfo && cloned === newPrefabInfo.root && (newPrefabInfo as any).sync; - if (!syncing) { - cloned.name += ' (Clone)'; - } - } // reset and init // NOTE: access protected property From b6bcc12b7ecbece9712a0d045d4e0df2520143ad Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Wed, 26 Jul 2023 10:15:45 +0800 Subject: [PATCH 066/232] Solve unchecked websocket link failure issue (#15799) --- native/external-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external-config.json b/native/external-config.json index 143079286e8..082f542393f 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-6" + "checkout": "v3.8.1-8" } } From 31342c46334ec7380c72b3ee4bc8580324022a7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 26 Jul 2023 11:09:38 +0800 Subject: [PATCH 067/232] Update editable.ts (#15820) --- cocos/core/data/decorators/editable.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/cocos/core/data/decorators/editable.ts b/cocos/core/data/decorators/editable.ts index 75ab976b2f0..bf8d59df181 100644 --- a/cocos/core/data/decorators/editable.ts +++ b/cocos/core/data/decorators/editable.ts @@ -289,11 +289,7 @@ export const displayOrder: (order: number) => LegacyPropertyDecorator = !DEV * 设置该属性在编辑器中的计量单位。 * @param name 计量单位的名称。 */ -export const unit: (name: -| 'lm' -| 'lx' -| 'cd/m²' -) => LegacyPropertyDecorator = !DEV +export const unit: (name: string) => LegacyPropertyDecorator = !DEV ? emptyDecoratorFn : setPropertyStashVar1WithImplicitVisible('unit'); From b9c259eb2aa5a1c0b466c36d31e9c186ef82b3a3 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Wed, 26 Jul 2023 11:11:41 +0800 Subject: [PATCH 068/232] add shader functions (#15814) --- .../chunks/common/math/coordinates.chunk | 10 +++++++ editor/assets/chunks/common/math/number.chunk | 11 ++++++++ .../assets/effects/advanced/car-paint.effect | 28 ++++++++++++------- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/editor/assets/chunks/common/math/coordinates.chunk b/editor/assets/chunks/common/math/coordinates.chunk index 08c05a227c9..c994cfc699d 100644 --- a/editor/assets/chunks/common/math/coordinates.chunk +++ b/editor/assets/chunks/common/math/coordinates.chunk @@ -101,6 +101,16 @@ vec3 RotationVecFromAxisY(vec3 v, float rotateAngleArc) return RotationVecFromAxisY(v, cos(rotateAngleArc), sin(rotateAngleArc)); } +vec3 RotationVecFromAxis(vec3 v, vec3 axis, float rotateAngleArc) +{ + float cosAngle = cos(rotateAngleArc); + float sinAngle = sin(rotateAngleArc); + vec3 crossProd = cross(axis, v); + float dotProd = dot(axis, v); + vec3 axisScaled = axis * dotProd * (1.0 - cosAngle); + return v * cosAngle + crossProd * sinAngle + axisScaled; +} + // rotationAngle: radians, 0-2Pi void RotateTangentAndBinormal(inout vec3 tangent, inout vec3 binormal, vec3 normal, float rotationAngle) { diff --git a/editor/assets/chunks/common/math/number.chunk b/editor/assets/chunks/common/math/number.chunk index cec08efffa7..843fa2ba750 100644 --- a/editor/assets/chunks/common/math/number.chunk +++ b/editor/assets/chunks/common/math/number.chunk @@ -51,3 +51,14 @@ vec4 rsqrt(vec4 value) { return vec4(1.0) / sqrt(value); } float rand(vec2 seeds_zero_to_one) { return fract(sin(dot(seeds_zero_to_one.xy, vec2(12.9898, 78.233))) * 43758.5453); } + +#if __VERSION__ <= 100 + mat4 transpose(mat4 v) { + mat4 tmp; + tmp[0] = vec4(v[0].x, v[1].x, v[2].x, v[3].x); + tmp[1] = vec4(v[0].y, v[1].y, v[2].y, v[3].y); + tmp[2] = vec4(v[0].z, v[1].z, v[2].z, v[3].z); + tmp[3] = vec4(v[0].w, v[1].w, v[2].w, v[3].w); + return tmp; + } +#endif diff --git a/editor/assets/effects/advanced/car-paint.effect b/editor/assets/effects/advanced/car-paint.effect index 186e6b5276f..457fd1d97c5 100644 --- a/editor/assets/effects/advanced/car-paint.effect +++ b/editor/assets/effects/advanced/car-paint.effect @@ -24,7 +24,7 @@ CCEffect %{ coatColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { displayName: CoatColor, type: color } } flakeDensity: { value: 0.5, target: flakeParam.x, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } flakeColorIntensity: { value: 0.2, target: flakeParam.y, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } - flakeTiling: { value: 10.0, target: flakeParam.z, editor: { parent: USE_FLAKE, slide: true, range: [1.0, 50.0], step: 0.001 } } + flakeTiling: { value: 10.0, target: flakeParam.z, editor: { parent: USE_FLAKE, slide: true, range: [1.0, 100.0], step: 0.001 } } coatNormalStrength: { value: 0.1, target: flakeParam.w, editor: { parent: USE_FLAKE, slide: true, range: [0, 1.0], step: 0.001 } } gradientColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { parent: USE_GRADIENT_COLOR, type: color } } gradientIntensity: { value: 0.5, target: emissiveScaleParam.y, editor: { parent: USE_GRADIENT_COLOR, slide: true, range: [0, 1.0], step: 0.001 } } @@ -215,12 +215,20 @@ CCProgram surface-fragment %{ return coatColor.xyz; } - vec4 sampleFlake(sampler2D tex, vec2 uv) - { - vec4 blurred = texture(tex, uv); - vec4 detailed = fragTextureLod(tex, uv, 1.0); - return lerp(blurred, detailed, 0.3); - } + #if USE_FLAKE + vec4 sampleFlakeData(vec2 uv) + { + vec4 blurred = texture(flakeDataMap, uv); + vec4 detailed = fragTextureLod(flakeDataMap, uv, 1.0); + return lerp(blurred, detailed, 0.3); + } + vec4 sampleFlakeNormal(vec2 uv) + { + vec4 blurred = texture(coatNormalMap, uv); + vec4 detailed = fragTextureLod(coatNormalMap, uv, 1.0); + return lerp(blurred, detailed, 0.3); + } + #endif #define CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_WORLD_NORMAL vec3 SurfacesFragmentModifyClearCoatWorldNormal() @@ -229,8 +237,8 @@ CCProgram surface-fragment %{ #if USE_FLAKE float density = flakeParam.x, densityMin = 0.25, flakeTiling = flakeParam.z; vec2 uv = FSInput_texcoord * flakeTiling; - vec4 data = sampleFlake(flakeDataMap, uv); - vec3 nmmp = (sampleFlake(coatNormalMap, uv).xyz - vec3(0.5)) * 2.0; + vec4 data = sampleFlakeData(uv); + vec3 nmmp = (sampleFlakeNormal(uv).xyz - vec3(0.5)) * 2.0; float C = (data.a - 1.0) / density + 1.0; float bumpIntensity = saturate(max(densityMin, C)); nmmp = lerp(vec3(0.0, 0.0, 1.0), nmmp, bumpIntensity); @@ -257,7 +265,7 @@ CCProgram surface-fragment %{ float density = flakeParam.x, flakeColorIntensity = flakeParam.y, flakeTiling = flakeParam.z; vec2 uv = FSInput_texcoord * flakeTiling; - vec4 data = sampleFlake(flakeDataMap, uv); + vec4 data = sampleFlakeData(uv); float C = (data.a - 1.0) / density + 1.0; float flakeTintWeight = 1.0; float flakeWeight = saturate(C) * flakeTintWeight * flakeColorIntensity; From 2e2b7ec03206f5b187bd5949c5c95e1fa5462c84 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 26 Jul 2023 11:12:42 +0800 Subject: [PATCH 069/232] fixed fsr input/output size (#15798) --- .../rendering/post-process/passes/fsr-pass.ts | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/cocos/rendering/post-process/passes/fsr-pass.ts b/cocos/rendering/post-process/passes/fsr-pass.ts index eedfed677df..1231470b58e 100644 --- a/cocos/rendering/post-process/passes/fsr-pass.ts +++ b/cocos/rendering/post-process/passes/fsr-pass.ts @@ -10,12 +10,14 @@ import { FSR } from '../components/fsr'; import { getSetting, SettingPass } from './setting-pass'; import { game } from '../../../game'; +const tempVec4 = new Vec4(); + export class FSRPass extends SettingPass { get setting (): FSR { return getSetting(FSR); } - name = 'FSRPass' + name = 'FSRPass'; effectName = 'pipeline/post-process/fsr'; - outputNames = ['FSRColor'] + outputNames = ['FSRColor']; checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); @@ -31,20 +33,16 @@ export class FSRPass extends SettingPass { passContext.material = this.material; passContext.clearBlack(); - passContext.updatePassViewPort(1 / passContext.shadingScale); + passContext.updatePassViewPort(1 / passContext.shadingScale, 0); - const inputWidth = Math.floor(game.canvas!.width * passContext.shadingScale); - const inputHeight = Math.floor(game.canvas!.height * passContext.shadingScale); - const outWidth = Math.floor(game.canvas!.width); - const outHeight = Math.floor(game.canvas!.height); + const inputWidth = Math.floor(passContext.passViewport.width * passContext.shadingScale); + const inputHeight = Math.floor(passContext.passViewport.height * passContext.shadingScale); + const outWidth = Math.floor(passContext.passViewport.width); + const outHeight = Math.floor(passContext.passViewport.height); const setting = this.setting; - this.material.setProperty('fsrParams', new Vec4(clamp(1.0 - setting.sharpness, 0.02, 0.98), 0, 0, 0)); - this.material.setProperty('texSize', - new Vec4( - inputWidth, inputHeight, - outWidth, outHeight, - )); + this.material.setProperty('fsrParams', tempVec4.set(clamp(1.0 - setting.sharpness, 0.02, 0.98), 0, 0, 0)); + this.material.setProperty('texSize', tempVec4.set(inputWidth, inputHeight, outWidth, outHeight)); const input0 = this.lastPass!.slotName(camera, 0); const easu = `FSR_EASU${cameraID}`; From e8e704cf184e87848b2a94845bedc96689b186cd Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 26 Jul 2023 11:13:14 +0800 Subject: [PATCH 070/232] fixed fsr/fxaa alpha (#15800) --- editor/assets/effects/pipeline/post-process/fsr.effect | 6 ++++-- editor/assets/effects/pipeline/post-process/fxaa-hq.effect | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/editor/assets/effects/pipeline/post-process/fsr.effect b/editor/assets/effects/pipeline/post-process/fsr.effect index 90728255e88..d7afb9fcc6a 100644 --- a/editor/assets/effects/pipeline/post-process/fsr.effect +++ b/editor/assets/effects/pipeline/post-process/fsr.effect @@ -80,7 +80,8 @@ CCProgram fs-easu %{ rendersize, rendersize, texSize.zw ); FsrEasuF(c, gl_FragCoord.xy, con0, con1, con2, con3); - fragColor = vec4(c.xyz, 1.); + float alpha = texture(outputResultMap, v_uv).a; + fragColor = vec4(c.xyz, alpha); } }% @@ -115,6 +116,7 @@ CCProgram fs-rcas %{ // Perform RCAS pass vec3 col = FsrRcasF(gl_FragCoord.xy, con); - fragColor = vec4(col, 1.); + float alpha = texture(outputResultMap, v_uv).a; + fragColor = vec4(col, alpha); } }% diff --git a/editor/assets/effects/pipeline/post-process/fxaa-hq.effect b/editor/assets/effects/pipeline/post-process/fxaa-hq.effect index 3f894f98fc2..1312f6e0508 100644 --- a/editor/assets/effects/pipeline/post-process/fxaa-hq.effect +++ b/editor/assets/effects/pipeline/post-process/fxaa-hq.effect @@ -35,7 +35,8 @@ CCProgram fxaa-edge-fs %{ vec4 frag () { vec3 color = FxaaPixelShader(v_uv, sceneColorMap, texSize.zw); - return vec4(color, 1.0); + float alpha = texture(sceneColorMap, v_uv).a; + return vec4(color, alpha); } }% From 41a16d73224e1e8f5ad52dfe690a4f78b09a11b2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 26 Jul 2023 12:07:22 +0800 Subject: [PATCH 071/232] Fix ci --- cocos/2d/components/ui-opacity.ts | 5 +- cocos/render-scene/scene/reflection-probe.ts | 9 +- cocos/rendering/custom/define.ts | 472 +++++++++++++----- .../post-process/passes/fxaa-pass.ts | 4 +- cocos/spine/assembler/simple.ts | 28 +- cocos/spine/skeleton.ts | 21 +- 6 files changed, 381 insertions(+), 158 deletions(-) diff --git a/cocos/2d/components/ui-opacity.ts b/cocos/2d/components/ui-opacity.ts index 68d2052b247..2990cf854c9 100644 --- a/cocos/2d/components/ui-opacity.ts +++ b/cocos/2d/components/ui-opacity.ts @@ -68,12 +68,11 @@ export class UIOpacity extends Component { this.setEntityLocalOpacityDirtyRecursively(true); - if(EDITOR_NOT_IN_PREVIEW) { - setTimeout(()=>{ + if (EDITOR_NOT_IN_PREVIEW) { + setTimeout(() => { EditorExtends.Node.emit('change', this.node.uuid, this.node); }, 200); } - } private setEntityLocalOpacityDirtyRecursively (dirty: boolean): void { diff --git a/cocos/render-scene/scene/reflection-probe.ts b/cocos/render-scene/scene/reflection-probe.ts index ea7a32e481c..43bc0526fe0 100644 --- a/cocos/render-scene/scene/reflection-probe.ts +++ b/cocos/render-scene/scene/reflection-probe.ts @@ -29,6 +29,7 @@ import { CAMERA_DEFAULT_MASK } from '../../rendering/define'; import { ClearFlagBit, Framebuffer } from '../../gfx'; import { TextureCube } from '../../asset/assets/texture-cube'; import { RenderTexture } from '../../asset/assets/render-texture'; +import { view } from '../../ui/view'; export enum ProbeClearFlag { SKYBOX = SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL, @@ -125,10 +126,10 @@ export class ReflectionProbe { * @en Set probe type,cube or planar. * @zh 设置探针类型,cube或者planar */ - set probeType (value: number) { + set probeType (value: ProbeType) { this._probeType = value; } - get probeType (): number { + get probeType (): ProbeType { return this._probeType; } @@ -308,7 +309,7 @@ export class ReflectionProbe { public renderPlanarReflection (sourceCamera: Camera): void { if (!sourceCamera) return; if (!this.realtimePlanarTexture) { - const canvasSize = cclegacy.view.getDesignResolutionSize(); + const canvasSize = view.getDesignResolutionSize(); this.realtimePlanarTexture = this._createTargetTexture(canvasSize.width, canvasSize.height); cclegacy.internal.reflectionProbeManager.updatePlanarMap(this, this.realtimePlanarTexture.getGFXTexture()); } @@ -317,7 +318,7 @@ export class ReflectionProbe { this._needRender = true; } - public switchProbeType (type: number, sourceCamera: Camera | null): void { + public switchProbeType (type: ProbeType, sourceCamera: Camera | null): void { if (type === ProbeType.CUBE) { this._needRender = false; } else if (sourceCamera !== null) { diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 83cebdd8e45..21769f3a145 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -44,6 +44,8 @@ import { WebPipeline } from './web-pipeline'; import { DescriptorSetData } from './layout-graph'; import { AABB } from '../../core/geometry'; import { DebugViewCompositeType, DebugViewSingleType } from '../debug-view'; +import { ReflectionProbeManager } from '../../3d/reflection-probe/reflection-probe-manager'; +import { director } from '../../game/director'; const _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5); const _tmpBoundingBox = new AABB(); @@ -148,7 +150,14 @@ export function getLoadOpOfClearFlag (clearFlag: ClearFlagBit, attachment: Attac return loadOp; } -export function getRenderArea (camera: Camera, width: number, height: number, light: Light | null = null, level = 0, out?: Rect): Rect { +export function getRenderArea ( + camera: Camera, + width: number, + height: number, + light: Light | null = null, + level = 0, + out: Rect | undefined = undefined, +): Rect { out = out || new Rect(); const vp = camera ? camera.viewport : new Rect(0, 0, 1, 1); const w = width; @@ -222,10 +231,12 @@ export function buildCopyPass (ppl: BasicPipeline, inOuts: CopyPair[]): void { } let fxaaData: FxaaData | null = null; -export function buildFxaaPass (camera: Camera, +export function buildFxaaPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): { rtName: string; dsName: string; } { + inputDS: string, +): { rtName: string; dsName: string; } { if (!fxaaData) { fxaaData = new FxaaData(); } @@ -262,7 +273,9 @@ export function buildFxaaPass (camera: Camera, fxaaPass.addRenderTarget(fxaaPassRTName, LoadOp.CLEAR, StoreOp.STORE, clearColor); fxaaData.fxaaMaterial.setProperty('texSize', new Vec4(width, height, 1.0 / width, 1.0 / height), fxaaPassIdx); fxaaPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, fxaaData.fxaaMaterial, fxaaPassIdx, + camera, + fxaaData.fxaaMaterial, + fxaaPassIdx, SceneFlags.NONE, ); return { rtName: fxaaPassRTName, dsName: inputDS }; @@ -318,12 +331,14 @@ class BloomData { } } let bloomData: BloomData | null = null; -export function buildBloomPass (camera: Camera, +export function buildBloomPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, threshold = 0.6, iterations = 2, - intensity = 2.0): { rtName: string; dsName: string; } { + intensity = 2.0, +): { rtName: string; dsName: string; } { if (!bloomData) { bloomData = new BloomData(); } @@ -366,7 +381,9 @@ export function buildBloomPass (camera: Camera, bloomPrefilterPass.addRenderTarget(bloomPassPrefilterRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', new Vec4(0, 0, bloomData.threshold, 0), 0); bloomPrefilterPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, bloomData.bloomMaterial, 0, + camera, + bloomData.bloomMaterial, + 0, SceneFlags.NONE, ); // === Bloom downSampler === @@ -393,7 +410,9 @@ export function buildBloomPass (camera: Camera, bloomDownSamplePass.addRenderTarget(bloomPassDownSampleRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', texSize, BLOOM_DOWNSAMPLEPASS_INDEX + i); bloomDownSamplePass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, bloomData.bloomMaterial, BLOOM_DOWNSAMPLEPASS_INDEX + i, + camera, + bloomData.bloomMaterial, + BLOOM_DOWNSAMPLEPASS_INDEX + i, SceneFlags.NONE, ); } @@ -421,7 +440,9 @@ export function buildBloomPass (camera: Camera, bloomUpSamplePass.addRenderTarget(bloomPassUpSampleRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', texSize, BLOOM_UPSAMPLEPASS_INDEX + i); bloomUpSamplePass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, bloomData.bloomMaterial, BLOOM_UPSAMPLEPASS_INDEX + i, + camera, + bloomData.bloomMaterial, + BLOOM_UPSAMPLEPASS_INDEX + i, SceneFlags.NONE, ); } @@ -445,7 +466,9 @@ export function buildBloomPass (camera: Camera, bloomCombinePass.addRenderTarget(bloomPassCombineRTName, LoadOp.CLEAR, StoreOp.STORE, bloomClearColor); bloomData.bloomMaterial.setProperty('texSize', new Vec4(0, 0, 0, bloomData.intensity), BLOOM_COMBINEPASS_INDEX); bloomCombinePass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, bloomData.bloomMaterial, BLOOM_COMBINEPASS_INDEX, + camera, + bloomData.bloomMaterial, + BLOOM_COMBINEPASS_INDEX, SceneFlags.NONE, ); return { rtName: bloomPassCombineRTName, dsName: bloomPassCombineDSName }; @@ -476,9 +499,11 @@ export class PostInfo { let postInfo: PostInfo; -export function buildPostprocessPass (camera: Camera, +export function buildPostprocessPass ( + camera: Camera, ppl: BasicPipeline, - inputTex: string): { rtName: string; dsName: string; } { + inputTex: string, +): { rtName: string; dsName: string; } { if (!postInfo) { postInfo = new PostInfo(); } @@ -506,24 +531,38 @@ export function buildPostprocessPass (camera: Camera, postClearColor.y = camera.clearColor.y; postClearColor.z = camera.clearColor.z; } - postprocessPass.addRenderTarget(postprocessPassRTName, - getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, postClearColor); - postprocessPass.addDepthStencil(postprocessPassDS, + postprocessPass.addRenderTarget( + postprocessPassRTName, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + + StoreOp.STORE, + + postClearColor, + ); + postprocessPass.addDepthStencil( + postprocessPassDS, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), - StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag); - postprocessPass.addQueue(QueueHint.NONE).addFullscreenQuad( - postInfo.postMaterial, 0, SceneFlags.NONE, + StoreOp.STORE, + + camera.clearDepth, + + camera.clearStencil, + + camera.clearFlag, ); + postprocessPass.addQueue(QueueHint.NONE).addFullscreenQuad(postInfo.postMaterial, 0, SceneFlags.NONE); if (getProfilerCamera() === camera) { postprocessPass.showStatistics = true; } return { rtName: postprocessPassRTName, dsName: postprocessPassDS }; } -export function buildForwardPass (camera: Camera, +export function buildForwardPass ( + camera: Camera, ppl: BasicPipeline, isOffScreen: boolean, - enabledAlpha = true): { rtName: string; dsName: string; } { + enabledAlpha = true, +): { rtName: string; dsName: string; } { if (EDITOR) { ppl.setMacroInt('CC_PIPELINE_TYPE', 0); } @@ -564,22 +603,29 @@ export function buildForwardPass (camera: Camera, forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap'); } } - forwardPass.addRenderTarget(forwardPassRTName, + forwardPass.addRenderTarget( + forwardPassRTName, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, - new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); - forwardPass.addDepthStencil(forwardPassDSName, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w), + ); + forwardPass.addDepthStencil( + forwardPassDSName, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), // If the depth texture is used by subsequent passes, it must be set to store. isOffScreen ? StoreOp.DISCARD : StoreOp.STORE, camera.clearDepth, camera.clearStencil, - camera.clearFlag); + camera.clearFlag, + ); forwardPass .addQueue(QueueHint.RENDER_OPAQUE) - .addSceneOfCamera(camera, new LightInfo(), + .addSceneOfCamera( + camera, + new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT - | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING); + | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING, + ); let sceneFlags = SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY; if (!isOffScreen) { sceneFlags |= SceneFlags.UI; @@ -594,10 +640,15 @@ export function buildForwardPass (camera: Camera, } let shadowPass; -export function buildShadowPass (passName: Readonly, +export function buildShadowPass ( + passName: Readonly, ppl: BasicPipeline, - camera: Camera, light: Light, level: number, - width: Readonly, height: Readonly): void { + camera: Camera, + light: Light, + level: number, + width: Readonly, + height: Readonly, +): void { const fboW = width; const fboH = height; const area = getRenderArea(camera, width, height, light, level); @@ -617,25 +668,37 @@ export function buildShadowPass (passName: Readonly, shadowPass.name = passName; shadowPass.setViewport(new Viewport(0, 0, fboW, fboH)); shadowPass.addRenderTarget(shadowMapName, LoadOp.CLEAR, StoreOp.STORE, new Color(1, 1, 1, camera.clearColor.w)); - shadowPass.addDepthStencil(`${shadowMapName}Depth`, LoadOp.CLEAR, StoreOp.DISCARD, - camera.clearDepth, camera.clearStencil, ClearFlagBit.DEPTH_STENCIL); + shadowPass.addDepthStencil( + `${shadowMapName}Depth`, + LoadOp.CLEAR, + StoreOp.DISCARD, + camera.clearDepth, + camera.clearStencil, + ClearFlagBit.DEPTH_STENCIL, + ); } const queue = shadowPass.addQueue(QueueHint.RENDER_OPAQUE, 'shadow-caster'); - queue.addSceneOfCamera(camera, new LightInfo(light, level), - SceneFlags.SHADOW_CASTER); + queue.addSceneOfCamera( + camera, + new LightInfo(light, level), + SceneFlags.SHADOW_CASTER, + ); queue.setViewport(new Viewport(area.x, area.y, area.width, area.height)); } -export function buildReflectionProbePasss (camera: Camera, - ppl: BasicPipeline): void { - if (!cclegacy.internal.reflectionProbeManager) return; - const probes = cclegacy.internal.reflectionProbeManager.getProbes(); +export function buildReflectionProbePasss ( + camera: Camera, + ppl: BasicPipeline, +): void { + const reflectionProbeManager = cclegacy.internal.reflectionProbeManager as ReflectionProbeManager; + if (!reflectionProbeManager) return; + const probes = reflectionProbeManager.getProbes(); if (probes.length === 0) return; for (let i = 0; i < probes.length; i++) { const probe = probes[i]; if (probe.needRender) { if (probes[i].probeType === ProbeType.PLANAR) { - buildReflectionProbePass(camera, ppl, probe, probe.realtimePlanarTexture.window!, 0); + buildReflectionProbePass(camera, ppl, probe, probe.realtimePlanarTexture!.window!, 0); } else if (EDITOR) { for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) { probe.updateCameraDir(faceIdx); @@ -647,8 +710,13 @@ export function buildReflectionProbePasss (camera: Camera, } } -export function buildReflectionProbePass (camera: Camera, - ppl: BasicPipeline, probe: ReflectionProbe, renderWindow: RenderWindow, faceIdx: number): void { +export function buildReflectionProbePass ( + camera: Camera, + ppl: BasicPipeline, + probe: ReflectionProbe, + renderWindow: RenderWindow, + faceIdx: number, +): void { const cameraName = `Camera${faceIdx}`; const area = probe.renderArea(); const width = area.x; @@ -668,10 +736,20 @@ export function buildReflectionProbePass (camera: Camera, const probePass = ppl.addRenderPass(width, height, 'default'); probePass.name = `ReflectionProbePass${faceIdx}`; probePass.setViewport(new Viewport(0, 0, width, height)); - probePass.addRenderTarget(probePassRTName, getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.RENDER_TARGET), - StoreOp.STORE, new Color(probeCamera.clearColor.x, probeCamera.clearColor.y, probeCamera.clearColor.z, probeCamera.clearColor.w)); - probePass.addDepthStencil(probePassDSName, getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.DEPTH_STENCIL), - StoreOp.STORE, probeCamera.clearDepth, probeCamera.clearStencil, probeCamera.clearFlag); + probePass.addRenderTarget( + probePassRTName, + getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + new Color(probeCamera.clearColor.x, probeCamera.clearColor.y, probeCamera.clearColor.z, probeCamera.clearColor.w), + ); + probePass.addDepthStencil( + probePassDSName, + getLoadOpOfClearFlag(probeCamera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, + probeCamera.clearDepth, + probeCamera.clearStencil, + probeCamera.clearFlag, + ); const passBuilder = probePass.addQueue(QueueHint.RENDER_OPAQUE); passBuilder.addSceneOfCamera(camera, new LightInfo(), SceneFlags.REFLECTION_PROBE); updateCameraUBO(passBuilder as unknown as any, probeCamera, ppl); @@ -720,14 +798,28 @@ export function buildShadowPasses (cameraName: string, camera: Camera, ppl: Basi if (mainLight && mainLight.shadowEnabled) { shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; if (mainLight.shadowFixedArea) { - buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, - camera, mainLight, 0, mapWidth, mapHeight); + buildShadowPass( + shadowInfo.mainLightShadowNames[0], + ppl, + camera, + mainLight, + 0, + mapWidth, + mapHeight, + ); } else { const csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; shadowInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; for (let i = 0; i < csmLevel; i++) { - buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, - camera, mainLight, i, mapWidth, mapHeight); + buildShadowPass( + shadowInfo.mainLightShadowNames[0], + ppl, + camera, + mainLight, + i, + mapWidth, + mapHeight, + ); } } } @@ -736,8 +828,15 @@ export function buildShadowPasses (cameraName: string, camera: Camera, ppl: Basi const light = shadowInfo.validLights[l]; const passName = `SpotLightShadow${l.toString()}${cameraName}`; shadowInfo.spotLightShadowNames[l] = passName; - buildShadowPass(passName, ppl, - camera, light, 0, mapWidth, mapHeight); + buildShadowPass( + passName, + ppl, + camera, + light, + 0, + mapWidth, + mapHeight, + ); } return shadowInfo; } @@ -750,8 +849,10 @@ export class GBufferInfo { ds!: string; } // deferred passes -export function buildGBufferPass (camera: Camera, - ppl: BasicPipeline): GBufferInfo { +export function buildGBufferPass ( + camera: Camera, + ppl: BasicPipeline, +): GBufferInfo { const cameraID = getCameraUniqueID(camera); const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; @@ -869,7 +970,9 @@ export function buildLightingPass (camera: Camera, ppl: BasicPipeline, gBuffer: lightingClearColor.w = 0; lightingPass.addRenderTarget(deferredLightingPassRTName, LoadOp.CLEAR, StoreOp.STORE, lightingClearColor); lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, lightingInfo.deferredLightingMaterial, 0, + camera, + lightingInfo.deferredLightingMaterial, + 0, SceneFlags.VOLUMETRIC_LIGHTING, ); // lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), @@ -899,8 +1002,10 @@ function getClearFlags (attachment: AttachmentType, clearFlag: ClearFlagBit, loa } } -export function buildUIPass (camera: Camera, - ppl: BasicPipeline): void { +export function buildUIPass ( + camera: Camera, + ppl: BasicPipeline, +): void { const cameraID = getCameraUniqueID(camera); const cameraName = `Camera${cameraID}`; const area = getRenderArea(camera, camera.window.width, camera.window.height); @@ -918,14 +1023,22 @@ export function buildUIPass (camera: Camera, const uiAndProfilerPass = ppl.addRenderPass(width, height, 'default'); uiAndProfilerPass.name = `CameraUIAndProfilerPass${cameraID}`; uiAndProfilerPass.setViewport(new Viewport(area.x, area.y, width, height)); - uiAndProfilerPass.addRenderTarget(dsUIAndProfilerPassRTName, + uiAndProfilerPass.addRenderTarget( + dsUIAndProfilerPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, - new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); - uiAndProfilerPass.addDepthStencil(dsUIAndProfilerPassDSName, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w), + ); + uiAndProfilerPass.addDepthStencil( + dsUIAndProfilerPassDSName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, - camera.clearDepth, camera.clearStencil, camera.clearFlag); + camera.clearDepth, + + camera.clearStencil, + + camera.clearFlag, + ); const sceneFlags = SceneFlags.UI; uiAndProfilerPass .addQueue(QueueHint.RENDER_TRANSPARENT) @@ -936,7 +1049,7 @@ export function buildUIPass (camera: Camera, } export function updateCameraUBO (setter: any, camera: Readonly, ppl: Readonly): void { - const pipeline = cclegacy.director.root.pipeline; + const pipeline = director.root!.pipeline as WebPipeline; const sceneData = ppl.pipelineSceneData; const skybox = sceneData.skybox; setter.addConstant('CCCamera'); @@ -986,7 +1099,7 @@ export function getDescBindingFromName (bindingName: string): number { const layoutGraph = pipeline.layoutGraph; const vertIds = layoutGraph.vertices(); const descId = layoutGraph.attributeIndex.get(bindingName); - let currDesData; + let currDesData: DescriptorSetData; for (const i of vertIds) { const layout = layoutGraph.getLayout(i); for (const [k, descData] of layout.descriptorSets) { @@ -1020,10 +1133,12 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa let buffer = descriptorSet.getBuffer(bindId); let haveBuff = true; if (!buffer && !isUpdate) { - buffer = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + buffer = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, value.length * 4, - value.length * 4)); + value.length * 4, + )); haveBuff = false; } if (isUpdate) { @@ -1198,7 +1313,7 @@ class SSSSBlurData { const o = -range + i * step; const sign = o < 0.0 ? -1.0 : 1.0; // eslint-disable-next-line no-restricted-properties - this._kernel[i].w = range * sign * Math.abs(Math.pow(o, EXPONENT)) / Math.pow(range, EXPONENT); + this._kernel[i].w = range * sign * Math.abs(o ** EXPONENT) / range ** EXPONENT; } // Calculate the weights: @@ -1295,10 +1410,12 @@ export function hasSkinObject (ppl: BasicPipeline): boolean { return sceneData.skin.enabled && sceneData.standardSkinModel !== null; } -function _buildSSSSBlurPass (camera: Camera, +function _buildSSSSBlurPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): { rtName: string; dsName: string; } { + inputDS: string, +): { rtName: string; dsName: string; } { const sceneData = ppl.pipelineSceneData; const skin = sceneData.skin; const standardSkinModel = sceneData.standardSkinModel; @@ -1350,10 +1467,18 @@ function _buildSSSSBlurPass (camera: Camera, sampler.mipFilter = Filter.NONE; copyInputDSPass.addTexture(inputDS, 'depthRaw'); } - copyInputDSPass.addRenderTarget(ssssBlurDSName, - LoadOp.CLEAR, StoreOp.STORE, new Color(1.0, 0.0, 0.0, 0.0)); + copyInputDSPass.addRenderTarget( + ssssBlurDSName, + LoadOp.CLEAR, + + StoreOp.STORE, + + new Color(1.0, 0.0, 0.0, 0.0), + ); copyInputDSPass.addQueue(QueueHint.RENDER_OPAQUE | QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, ssssBlurData.ssssBlurMaterial, COPY_INPUT_DS_PASS_INDEX, + camera, + ssssBlurData.ssssBlurMaterial, + COPY_INPUT_DS_PASS_INDEX, SceneFlags.NONE, ); @@ -1378,13 +1503,25 @@ function _buildSSSSBlurPass (camera: Camera, ssssblurXPass.addTexture(ssssBlurDSName, 'depthTex'); } ssssblurXPass.addRenderTarget(ssssBlurRTName, LoadOp.CLEAR, StoreOp.STORE, ssssBlurClearColor); - ssssblurXPass.addDepthStencil(inputDS, LoadOp.LOAD, StoreOp.STORE, - camera.clearDepth, camera.clearStencil, camera.clearFlag); - ssssBlurData.ssssBlurMaterial.setProperty('blurInfo', new Vec4(ssssBlurData.ssssFov, ssssBlurData.ssssWidth, - ssssBlurData.boundingBox, ssssBlurData.ssssScale), SSSS_BLUR_X_PASS_INDEX); + ssssblurXPass.addDepthStencil( + inputDS, + LoadOp.LOAD, + StoreOp.STORE, + camera.clearDepth, + camera.clearStencil, + camera.clearFlag, + ); + ssssBlurData.ssssBlurMaterial.setProperty('blurInfo', new Vec4( + ssssBlurData.ssssFov, + ssssBlurData.ssssWidth, + ssssBlurData.boundingBox, + ssssBlurData.ssssScale, + ), SSSS_BLUR_X_PASS_INDEX); ssssBlurData.ssssBlurMaterial.setProperty('kernel', ssssBlurData.kernel, SSSS_BLUR_X_PASS_INDEX); ssssblurXPass.addQueue(QueueHint.RENDER_OPAQUE | QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, ssssBlurData.ssssBlurMaterial, SSSS_BLUR_X_PASS_INDEX, + camera, + ssssBlurData.ssssBlurMaterial, + SSSS_BLUR_X_PASS_INDEX, SceneFlags.NONE, ); @@ -1409,13 +1546,25 @@ function _buildSSSSBlurPass (camera: Camera, ssssblurYPass.addTexture(ssssBlurDSName, 'depthTex'); } ssssblurYPass.addRenderTarget(inputRT, LoadOp.LOAD, StoreOp.STORE, ssssBlurClearColor); - ssssblurYPass.addDepthStencil(inputDS, LoadOp.LOAD, StoreOp.STORE, - camera.clearDepth, camera.clearStencil, camera.clearFlag); - ssssBlurData.ssssBlurMaterial.setProperty('blurInfo', new Vec4(ssssBlurData.ssssFov, ssssBlurData.ssssWidth, - ssssBlurData.boundingBox, ssssBlurData.ssssScale), SSSS_BLUR_Y_PASS_INDEX); + ssssblurYPass.addDepthStencil( + inputDS, + LoadOp.LOAD, + StoreOp.STORE, + camera.clearDepth, + camera.clearStencil, + camera.clearFlag, + ); + ssssBlurData.ssssBlurMaterial.setProperty('blurInfo', new Vec4( + ssssBlurData.ssssFov, + ssssBlurData.ssssWidth, + ssssBlurData.boundingBox, + ssssBlurData.ssssScale, + ), SSSS_BLUR_Y_PASS_INDEX); ssssBlurData.ssssBlurMaterial.setProperty('kernel', ssssBlurData.kernel, SSSS_BLUR_Y_PASS_INDEX); ssssblurYPass.addQueue(QueueHint.RENDER_OPAQUE | QueueHint.RENDER_TRANSPARENT).addCameraQuad( - camera, ssssBlurData.ssssBlurMaterial, SSSS_BLUR_Y_PASS_INDEX, + camera, + ssssBlurData.ssssBlurMaterial, + SSSS_BLUR_Y_PASS_INDEX, SceneFlags.NONE, ); return { rtName: inputRT, dsName: inputDS }; @@ -1439,10 +1588,12 @@ class ToneMappingInfo { } let toneMappingInfo: ToneMappingInfo | null = null; -export function buildToneMappingPass (camera: Camera, +export function buildToneMappingPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): { rtName: string; dsName: string; } { + inputDS: string, +): { rtName: string; dsName: string; } { if (!ppl.pipelineSceneData.isHDR || !ppl.getMacroBool('CC_USE_FLOAT_OUTPUT')) return { rtName: inputRT, dsName: inputDS }; if (!toneMappingInfo) { toneMappingInfo = new ToneMappingInfo(); @@ -1474,29 +1625,42 @@ export function buildToneMappingPass (camera: Camera, if (ppl.containsResource(inputRT)) { toneMappingPass.addTexture(inputRT, 'u_texSampler'); } - toneMappingPass.addRenderTarget(toneMappingPassRTName, + toneMappingPass.addRenderTarget( + toneMappingPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), - StoreOp.STORE, toneMappingClearColor); - toneMappingPass.addDepthStencil(toneMappingPassDS, + StoreOp.STORE, + + toneMappingClearColor, + ); + toneMappingPass.addDepthStencil( + toneMappingPassDS, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, - camera.clearDepth, camera.clearStencil, camera.clearFlag); - toneMappingPass.addQueue(QueueHint.NONE).addFullscreenQuad( - toneMappingInfo.toneMappingMaterial, 0, SceneFlags.NONE, + camera.clearDepth, + + camera.clearStencil, + + camera.clearFlag, + ); + toneMappingPass.addQueue(QueueHint.NONE).addFullscreenQuad(toneMappingInfo.toneMappingMaterial, 0, SceneFlags.NONE); + toneMappingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera( + camera, + new LightInfo(), + SceneFlags.UI, ); - toneMappingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), - SceneFlags.UI); if (getProfilerCamera() === camera) { toneMappingPass.showStatistics = true; } return { rtName: toneMappingPassRTName, dsName: toneMappingPassDS }; } -export function buildTransparencyPass (camera: Camera, +export function buildTransparencyPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, inputDS: string, - hasDeferredTransparencyObject: boolean): { rtName: string; dsName: string; } { + hasDeferredTransparencyObject: boolean, +): { rtName: string; dsName: string; } { if (hasDeferredTransparencyObject) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -1519,22 +1683,36 @@ export function buildTransparencyPass (camera: Camera, alphaPass.addTexture(spotShadowName, 'cc_spotShadowMap'); } } - alphaPass.addRenderTarget(inputRT, - LoadOp.LOAD, StoreOp.STORE, - new Color(camera.clearDepth, camera.clearStencil, 0, 0)); - alphaPass.addDepthStencil(inputDS, - LoadOp.LOAD, StoreOp.STORE, - camera.clearDepth, camera.clearStencil, camera.clearFlag); + alphaPass.addRenderTarget( + inputRT, + LoadOp.LOAD, + + StoreOp.STORE, + new Color(camera.clearDepth, camera.clearStencil, 0, 0), + ); + alphaPass.addDepthStencil( + inputDS, + LoadOp.LOAD, + + StoreOp.STORE, + camera.clearDepth, + + camera.clearStencil, + + camera.clearFlag, + ); alphaPass .addQueue(QueueHint.RENDER_TRANSPARENT) .addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY); return { rtName: inputRT, dsName: inputDS }; } -function _buildSpecularPass (camera: Camera, +function _buildSpecularPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): { rtName: string; dsName: string; } { + inputDS: string, +): { rtName: string; dsName: string; } { if (EDITOR) { ppl.setMacroInt('CC_PIPELINE_TYPE', 0); } @@ -1558,29 +1736,49 @@ function _buildSpecularPass (camera: Camera, specalurPass.addTexture(spotShadowName, 'cc_spotShadowMap'); } } - specalurPass.addRenderTarget(inputRT, - LoadOp.LOAD, StoreOp.STORE, - new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); - specalurPass.addDepthStencil(inputDS, - LoadOp.LOAD, StoreOp.STORE, - camera.clearDepth, camera.clearStencil, camera.clearFlag); + specalurPass.addRenderTarget( + inputRT, + LoadOp.LOAD, + + StoreOp.STORE, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w), + ); + specalurPass.addDepthStencil( + inputDS, + LoadOp.LOAD, + + StoreOp.STORE, + camera.clearDepth, + + camera.clearStencil, + + camera.clearFlag, + ); specalurPass .addQueue(QueueHint.RENDER_OPAQUE, 'default') - .addSceneOfCamera(camera, new LightInfo(), + .addSceneOfCamera( + camera, + new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.PLANAR_SHADOW - | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING | SceneFlags.GEOMETRY); + | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING | SceneFlags.GEOMETRY, + ); specalurPass .addQueue(QueueHint.RENDER_TRANSPARENT, 'forward-add') - .addSceneOfCamera(camera, new LightInfo(), + .addSceneOfCamera( + camera, + new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.PLANAR_SHADOW - | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING | SceneFlags.GEOMETRY); + | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING | SceneFlags.GEOMETRY, + ); return { rtName: inputRT, dsName: inputDS }; } -export function buildSSSSPass (camera: Camera, +export function buildSSSSPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): { rtName: string; dsName: string; } { + inputDS: string, +): { rtName: string; dsName: string; } { if (hasSkinObject(ppl)) { forceEnableFloatOutput(ppl); const blurInfo = _buildSSSSBlurPass(camera, ppl, inputRT, inputDS); @@ -1736,10 +1934,12 @@ class HBAOParams { let _hbaoParams: HBAOParams | null = null; const vec2 = new Vec2(); -function _buildHBAOPass (camera: Camera, +function _buildHBAOPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): { rtName: string; dsName: string; } { + inputDS: string, +): { rtName: string; dsName: string; } { if (!_hbaoParams) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -1780,17 +1980,21 @@ function _buildHBAOPass (camera: Camera, _hbaoParams.hbaoMaterial.setProperty('randomTexSize', new Vec4(_hbaoParams.randomTexture.width, _hbaoParams.randomTexture.height, 1.0 / _hbaoParams.randomTexture.width, 1.0 / _hbaoParams.randomTexture.height), passIdx); _hbaoParams.hbaoMaterial.setProperty('blurParam', _hbaoParams.blurParam, passIdx); hbaoPass.addQueue(QueueHint.RENDER_TRANSPARENT | QueueHint.RENDER_OPAQUE).addCameraQuad( - camera, _hbaoParams.hbaoMaterial, passIdx, + camera, + _hbaoParams.hbaoMaterial, + passIdx, SceneFlags.NONE, ); return { rtName: hbaoRTName, dsName: inputDS }; } -function _buildHBAOBlurPass (camera: Camera, +function _buildHBAOBlurPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, inputDS: string, - isYPass: boolean): { rtName: string; dsName: string; } { + isYPass: boolean, +): { rtName: string; dsName: string; } { if (!_hbaoParams) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -1848,17 +2052,21 @@ function _buildHBAOBlurPass (camera: Camera, _hbaoParams.hbaoMaterial.setProperty('miscParam', _hbaoParams.miscParam, passIdx); _hbaoParams.hbaoMaterial.setProperty('blurParam', _hbaoParams.blurParam, passIdx); blurPass.addQueue(QueueHint.RENDER_TRANSPARENT | QueueHint.RENDER_OPAQUE).addCameraQuad( - camera, _hbaoParams.hbaoMaterial, passIdx, + camera, + _hbaoParams.hbaoMaterial, + passIdx, SceneFlags.NONE, ); return { rtName: outputRTName, dsName: inputDS }; } -function _buildHBAOCombinedPass (camera: Camera, +function _buildHBAOCombinedPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, inputDS: string, - outputRT: string): { rtName: string; dsName: string; } { + outputRT: string, +): { rtName: string; dsName: string; } { if (!_hbaoParams) return { rtName: inputRT, dsName: inputDS }; const cameraID = getCameraUniqueID(camera); @@ -1900,13 +2108,16 @@ function _buildHBAOCombinedPass (camera: Camera, _hbaoParams.hbaoMaterial.setProperty('miscParam', _hbaoParams.miscParam, passIdx); _hbaoParams.hbaoMaterial.setProperty('blurParam', _hbaoParams.blurParam, passIdx); hbaoPass.addQueue(QueueHint.RENDER_TRANSPARENT | QueueHint.RENDER_OPAQUE).addCameraQuad( - camera, _hbaoParams.hbaoMaterial, passIdx, + camera, + _hbaoParams.hbaoMaterial, + passIdx, SceneFlags.NONE, ); return { rtName: outputRTName, dsName: inputDS }; } -export function buildHBAOPasses (camera: Camera, +export function buildHBAOPasses ( + camera: Camera, ppl: BasicPipeline, inputRT: string, inputDS: string, @@ -1915,7 +2126,8 @@ export function buildHBAOPasses (camera: Camera, blurSharpness = 3, aoSaturation = 1.0, aoStrength = 1.0, - needBlur = true): { rtName: string; dsName: string; } { + needBlur = true, +): { rtName: string; dsName: string; } { const area = getRenderArea(camera, camera.window.width, camera.window.height); const width = area.width; const height = area.height; @@ -1967,7 +2179,7 @@ export const CLUSTER_COUNT = CLUSTERS_X * CLUSTERS_Y * CLUSTERS_Z; class ClusterLightData { declare clusterBuildCS: Material; - declare clusterLightCullingCS: Material + declare clusterLightCullingCS: Material; clusters_x_threads = 16; clusters_y_threads = 8; clusters_z_threads = 1; @@ -2000,8 +2212,11 @@ class ClusterLightData { } let _clusterLightData: ClusterLightData | null = null; -export function buildLightClusterBuildPass (camera: Camera, clusterData: ClusterLightData, - ppl: Pipeline): void { +export function buildLightClusterBuildPass ( + camera: Camera, + clusterData: ClusterLightData, + ppl: Pipeline, +): void { const cameraID = getCameraUniqueID(camera); const clusterBufferName = `clusterBuffer${cameraID}`; @@ -2025,8 +2240,11 @@ export function buildLightClusterBuildPass (camera: Camera, clusterData: Cluster clusterPass.setMat4('cc_matProjInv', camera.matProjInv); } -export function buildLightClusterCullingPass (camera: Camera, clusterData: ClusterLightData, - ppl: Pipeline): void { +export function buildLightClusterCullingPass ( + camera: Camera, + clusterData: ClusterLightData, + ppl: Pipeline, +): void { const cameraID = getCameraUniqueID(camera); const clusterBufferName = `clusterBuffer${cameraID}`; const clusterLightBufferName = `clusterLightBuffer${cameraID}`; diff --git a/cocos/rendering/post-process/passes/fxaa-pass.ts b/cocos/rendering/post-process/passes/fxaa-pass.ts index 41baed363e7..1689fa22e81 100644 --- a/cocos/rendering/post-process/passes/fxaa-pass.ts +++ b/cocos/rendering/post-process/passes/fxaa-pass.ts @@ -11,9 +11,9 @@ import { FXAA } from '../components/fxaa'; export class FxaaPass extends SettingPass { get setting (): FXAA { return getSetting(FXAA); } - name = 'FxaaPass' + name = 'FxaaPass'; effectName = 'pipeline/post-process/fxaa-hq'; - outputNames = ['FxaaColor'] + outputNames = ['FxaaColor']; public render (camera: Camera, ppl: Pipeline): void { const cameraID = getCameraUniqueID(camera); diff --git a/cocos/spine/assembler/simple.ts b/cocos/spine/assembler/simple.ts index 4dfd998eb1d..f7e853bc516 100644 --- a/cocos/spine/assembler/simple.ts +++ b/cocos/spine/assembler/simple.ts @@ -98,11 +98,11 @@ export const simple: IAssembler = { const batcher = director.root!.batcher2D; const attributes = useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B; if (useTint) { - accessor = _tintAccessor = new StaticVBAccessor(device, attributes, this.vCount); + accessor = _tintAccessor = new StaticVBAccessor(device, attributes, this.vCount as number); // Register to batcher so that batcher can upload buffers after batching process batcher.registerBufferAccessor(Number.parseInt('SPINETINT', 36), _tintAccessor); } else { - accessor = _accessor = new StaticVBAccessor(device, attributes, this.vCount); + accessor = _accessor = new StaticVBAccessor(device, attributes, this.vCount as number); // Register to batcher so that batcher can upload buffers after batching process batcher.registerBufferAccessor(Number.parseInt('SPINE', 36), _accessor); } @@ -148,8 +148,8 @@ function realTimeTraverse (comp: Skeleton): void { const floatStride = (_useTint ? _byteStrideTwoColor : _byteStrideOneColor) / Float32Array.BYTES_PER_ELEMENT; const model = comp.updateRenderData(); if (!model) return; - const vc = model.vCount; - const ic = model.iCount; + const vc = model.vCount as number; + const ic = model.iCount as number; const rd = comp.renderData!; if (rd.vertexCount !== vc || rd.indexCount !== ic) { @@ -165,7 +165,7 @@ function realTimeTraverse (comp: Skeleton): void { const vLength = vc * Float32Array.BYTES_PER_ELEMENT * floatStride; // eslint-disable-next-line @typescript-eslint/restrict-plus-operands const vData = spine.wasmUtil.wasm.HEAPU8.subarray(vPtr, vPtr + vLength); - vUint8Buf.set(vData); + vUint8Buf.set(vData as TypedArray); const iPtr = model.iPtr; const ibuf = rd.indices!; @@ -173,7 +173,7 @@ function realTimeTraverse (comp: Skeleton): void { // eslint-disable-next-line @typescript-eslint/restrict-plus-operands const iData = spine.wasmUtil.wasm.HEAPU8.subarray(iPtr, iPtr + iLength); const iUint8Buf = new Uint8Array(ibuf.buffer); - iUint8Buf.set(iData); + iUint8Buf.set(iData as TypedArray); const chunkOffset = rd.chunk.vertexOffset; for (let i = 0; i < ic; i++) { ibuf[i] += chunkOffset; @@ -185,8 +185,8 @@ function realTimeTraverse (comp: Skeleton): void { let indexCount = 0; for (let i = 0; i < count; i++) { const mesh = meshes.get(i); - const material = _getSlotMaterial(mesh.blendMode, comp); - const textureID = mesh.textureID; + const material = _getSlotMaterial(mesh.blendMode as number, comp); + const textureID = mesh.textureID as number; indexCount = mesh.iCount; comp.requestDrawData(material, textureID, indexOffset, indexCount); indexOffset += indexCount; @@ -278,8 +278,8 @@ function cacheTraverse (comp: Skeleton): void { const model = comp.updateRenderData(); if (!model) return; - const vc = model.vCount; - const ic = model.iCount; + const vc = model.vCount as number; + const ic = model.iCount as number; const rd = comp.renderData!; if (rd.vertexCount !== vc || rd.indexCount !== ic) { rd.resize(vc, ic); @@ -289,7 +289,7 @@ function cacheTraverse (comp: Skeleton): void { const vbuf = rd.chunk.vb; const vUint8Buf = new Uint8Array(vbuf.buffer, vbuf.byteOffset, Float32Array.BYTES_PER_ELEMENT * vbuf.length); - vUint8Buf.set(model.vData); + vUint8Buf.set(model.vData as TypedArray); const nodeColor = comp.color; if (nodeColor._val !== 0xffffffff || _premultipliedAlpha) { @@ -318,7 +318,7 @@ function cacheTraverse (comp: Skeleton): void { } const iUint16Buf = rd.indices!; - iUint16Buf.set(model.iData); + iUint16Buf.set(model.iData as TypedArray); const chunkOffset = rd.chunk.vertexOffset; for (let i = 0; i < ic; i++) { iUint16Buf[i] += chunkOffset; @@ -330,10 +330,10 @@ function cacheTraverse (comp: Skeleton): void { let indexCount = 0; for (let i = 0; i < count; i++) { const mesh = meshes[i]; - const material = _getSlotMaterial(mesh.blendMode, comp); + const material = _getSlotMaterial(mesh.blendMode as number, comp); const textureID = mesh.textureID; indexCount = mesh.iCount; - comp.requestDrawData(material, textureID, indexOffset, indexCount); + comp.requestDrawData(material, textureID as number, indexOffset, indexCount); indexOffset += indexCount; } diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 6844673b69c..691702d985a 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -25,7 +25,7 @@ import { EDITOR_NOT_IN_PREVIEW, JSB } from 'internal:constants'; import { ccclass, executeInEditMode, help, menu, serializable, type, displayName, override, displayOrder, editable, tooltip } from 'cc.decorator'; import { Material, Texture2D } from '../asset/assets'; import { error, logID, warn } from '../core/platform/debug'; -import { Enum, ccenum } from '../core/value-types/enum'; +import { Enum, EnumType, ccenum } from '../core/value-types/enum'; import { Node } from '../scene-graph'; import { CCObject, Color, RecyclePool, js } from '../core'; import { SkeletonData } from './skeleton-data'; @@ -65,6 +65,11 @@ export const timeScale = 1.0; * @zh Spine 动画缓存类型。 */ export enum AnimationCacheMode { + /** + * @en Unset mode. + * @zh 未设置模式。 + */ + UNSET = -1, /** * @en The realtime mode. * @zh 实时计算模式。 @@ -207,7 +212,7 @@ export class Skeleton extends UIRenderer { @serializable protected _timeScale = 1; @serializable - protected _preCacheMode = -1; + protected _preCacheMode: AnimationCacheMode = AnimationCacheMode.UNSET; @serializable protected _cacheMode = AnimationCacheMode.REALTIME; @serializable @@ -241,8 +246,8 @@ export class Skeleton extends UIRenderer { }), 1); protected _materialCache: { [key: string]: MaterialInstance } = {} as any; public paused = false; - protected _enumSkins: any = Enum({}); - protected _enumAnimations: any = Enum({}); + protected _enumSkins: EnumType = Enum({}); + protected _enumAnimations: EnumType = Enum({}); protected attachUtil: AttachUtil; protected _socketNodes: Map = new Map(); protected _cachedSockets: Map = new Map(); @@ -725,7 +730,7 @@ export class Skeleton extends UIRenderer { if (this.debugBones || this.debugSlots) { warn('Debug bones or slots is invalid in cached mode'); } - const skeletonInfo = this._skeletonCache!.getSkeletonCache((this.skeletonData as any).uuid, skeletonData); + const skeletonInfo = this._skeletonCache!.getSkeletonCache(this.skeletonData!.uuid, skeletonData); this._skeleton = skeletonInfo.skeleton; } else { this._skeleton = this._instance.initSkeleton(skeletonData); @@ -1396,9 +1401,9 @@ export class Skeleton extends UIRenderer { } this._cachedSockets.clear(); const bones = this._skeleton.bones; - const getBoneName = (bone: spine.Bone): any => { + const getBoneName = (bone: spine.Bone): string => { if (bone.parent == null) return bone.data.name || ''; - return `${getBoneName(bones[bone.parent.data.index]) as string}/${bone.data.name}`; + return `${getBoneName(bones[bone.parent.data.index])}/${bone.data.name}`; }; for (let i = 0, l = bones.length; i < l; i++) { const bd = bones[i].data; @@ -1494,7 +1499,7 @@ export class Skeleton extends UIRenderer { /** * @engineInternal */ - protected _updateColor (): void { + public _updateColor (): void { this.node._uiProps.colorDirty = true; const r = this._color.r / 255.0; const g = this._color.g / 255.0; From 546b36209fcd0a7e981843e797fe8d07def3a978 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 26 Jul 2023 13:16:34 +0800 Subject: [PATCH 072/232] Fix circular dependencies --- cocos/rendering/deferred/lighting-stage.ts | 13 ++++-- cocos/rendering/forward/forward-pipeline.ts | 6 +++ cocos/rendering/index.ts | 8 +--- cocos/rendering/pipeline-scene-data.ts | 7 ++-- .../reflection-probe/reflection-probe-flow.ts | 7 ++-- .../rendering/render-additive-light-queue.ts | 16 +++++-- .../render-reflection-probe-queue.ts | 8 ++-- cocos/rendering/shadow/csm-layers.ts | 42 +++++++++++++++---- cocos/rendering/shadow/shadow-stage.ts | 24 ++++++++--- cocos/root.ts | 14 +++++-- 10 files changed, 105 insertions(+), 40 deletions(-) diff --git a/cocos/rendering/deferred/lighting-stage.ts b/cocos/rendering/deferred/lighting-stage.ts index ebb09a9efc7..e420c39ab2a 100644 --- a/cocos/rendering/deferred/lighting-stage.ts +++ b/cocos/rendering/deferred/lighting-stage.ts @@ -28,7 +28,8 @@ */ import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; -import { Camera, LightType } from '../../render-scene/scene'; +import { Camera } from '../../render-scene/scene/camera'; +import { LightType } from '../../render-scene/scene/light'; import { UBODeferredLight, SetIndex, UBOForwardLight, UBOLocal } from '../define'; import { getPhaseID } from '../pass-phase'; import { Color, Rect, Buffer, BufferUsageBit, MemoryUsageBit, BufferInfo, BufferViewInfo, DescriptorSet, @@ -355,8 +356,14 @@ export class LightingStage extends RenderStage { pipeline.pipelineUBO.updateShadowUBO(camera); - cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, - colors, camera.clearDepth, camera.clearStencil); + cmdBuff.beginRenderPass( + renderPass, + framebuffer, + this._renderArea, + colors, + camera.clearDepth, + camera.clearStencil, + ); cmdBuff.setScissor(pipeline.generateScissor(camera)); cmdBuff.setViewport(pipeline.generateViewport(camera)); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); diff --git a/cocos/rendering/forward/forward-pipeline.ts b/cocos/rendering/forward/forward-pipeline.ts index a8bdcaf1832..48322d0c130 100644 --- a/cocos/rendering/forward/forward-pipeline.ts +++ b/cocos/rendering/forward/forward-pipeline.ts @@ -39,6 +39,12 @@ import { ReflectionProbeFlow } from '../reflection-probe/reflection-probe-flow'; const PIPELINE_TYPE = 0; +export function createDefaultPipeline (): ForwardPipeline { + const rppl = new ForwardPipeline(); + rppl.initialize({ flows: [] }); + return rppl; +} + /** * @en The forward render pipeline * @zh 前向渲染管线。 diff --git a/cocos/rendering/index.ts b/cocos/rendering/index.ts index 68a0d0434a8..df06cd7656e 100644 --- a/cocos/rendering/index.ts +++ b/cocos/rendering/index.ts @@ -35,7 +35,7 @@ export { RenderFlow } from './render-flow'; export { RenderStage } from './render-stage'; export { PipelineSceneData } from './pipeline-scene-data'; -export { ForwardPipeline } from './forward/forward-pipeline'; +export { ForwardPipeline, createDefaultPipeline } from './forward/forward-pipeline'; export { ForwardFlow } from './forward/forward-flow'; export { ForwardStage } from './forward/forward-stage'; export { DeferredPipeline } from './deferred/deferred-pipeline'; @@ -55,9 +55,3 @@ export { DebugView } from './debug-view'; export { ReflectionProbeFlow } from './reflection-probe/reflection-probe-flow'; export { ReflectionProbeStage } from './reflection-probe/reflection-probe-stage'; - -export function createDefaultPipeline (): ForwardPipeline { - const rppl = new ForwardPipeline(); - rppl.initialize({ flows: [] }); - return rppl; -} diff --git a/cocos/rendering/pipeline-scene-data.ts b/cocos/rendering/pipeline-scene-data.ts index 529d6c44cb9..314539ec16a 100644 --- a/cocos/rendering/pipeline-scene-data.ts +++ b/cocos/rendering/pipeline-scene-data.ts @@ -32,9 +32,10 @@ import { Light } from '../render-scene/scene/light'; import { Material } from '../asset/assets'; import { Pass } from '../render-scene/core/pass'; import { CSMLayers } from './shadow/csm-layers'; -import { cclegacy } from '../core'; +import { legacyCC } from '../core/global-exports'; import { Skin } from '../render-scene/scene/skin'; -import { Model, PostSettings } from '../render-scene/scene'; +import { Model } from '../render-scene/scene/model'; +import { PostSettings } from '../render-scene/scene/post-settings'; import { MeshRenderer } from '../3d/framework/mesh-renderer'; const GEOMETRY_RENDERER_TECHNIQUE_COUNT = 6; @@ -109,7 +110,7 @@ export class PipelineSceneData { public octree: Octree = new Octree(); public skin: Skin = new Skin(); public postSettings: PostSettings = new PostSettings(); - public lightProbes = cclegacy.internal.LightProbes ? new cclegacy.internal.LightProbes() : null; + public lightProbes = legacyCC.internal.LightProbes ? new legacyCC.internal.LightProbes() : null; /** * @en The list for valid punctual Lights, only available after the scene culling of the current frame. diff --git a/cocos/rendering/reflection-probe/reflection-probe-flow.ts b/cocos/rendering/reflection-probe/reflection-probe-flow.ts index 20611207a19..3ceabf5a832 100644 --- a/cocos/rendering/reflection-probe/reflection-probe-flow.ts +++ b/cocos/rendering/reflection-probe/reflection-probe-flow.ts @@ -26,8 +26,9 @@ import { ccclass } from 'cc.decorator'; import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { ReflectionProbeStage } from './reflection-probe-stage'; import { RenderFlowTag } from '../pipeline-serialization'; -import { RenderPipeline } from '..'; -import { Camera, ProbeType, ReflectionProbe } from '../../render-scene/scene'; +import { RenderPipeline } from '../render-pipeline'; +import { Camera } from '../../render-scene/scene/camera'; +import { ProbeType, ReflectionProbe } from '../../render-scene/scene/reflection-probe'; import { cclegacy } from '../../core'; /** @@ -61,7 +62,7 @@ export class ReflectionProbeFlow extends RenderFlow { if (!cclegacy.internal.reflectionProbeManager) { return; } - const probes = cclegacy.internal.reflectionProbeManager.getProbes(); + const probes = cclegacy.internal.reflectionProbeManager.getProbes() as ReflectionProbe[]; for (let i = 0; i < probes.length; i++) { if (probes[i].needRender) { if (EDITOR || probes[i].probeType === ProbeType.PLANAR) { diff --git a/cocos/rendering/render-additive-light-queue.ts b/cocos/rendering/render-additive-light-queue.ts index 94b8e02841e..ce569f7260e 100644 --- a/cocos/rendering/render-additive-light-queue.ts +++ b/cocos/rendering/render-additive-light-queue.ts @@ -38,7 +38,8 @@ import { getPhaseID } from './pass-phase'; import { Light, LightType } from '../render-scene/scene/light'; import { SetIndex, UBOForwardLight, UBOShadow, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, supportsR32FloatTexture, isEnableEffect } from './define'; -import { Camera, ShadowType } from '../render-scene/scene'; +import { Camera } from '../render-scene/scene/camera'; +import { ShadowType } from '../render-scene/scene/shadows'; import { GlobalDSManager } from './global-descriptor-set-manager'; import { PipelineUBO } from './pipeline-ubo'; import { PipelineRuntime } from './custom/pipeline'; @@ -386,8 +387,17 @@ export class RenderAdditiveLightQueue { Mat4.invert(_matShadowView, (light as SpotLight).node!.getWorldMatrix()); // light proj - Mat4.perspective(_matShadowViewProj, (light as SpotLight).angle, 1.0, 0.001, (light as SpotLight).range, - true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); + Mat4.perspective( + _matShadowViewProj, + (light as SpotLight).angle, + 1.0, + 0.001, + (light as SpotLight).range, + true, + cap.clipSpaceMinZ, + cap.clipSpaceSignY, + 0, + ); matShadowProj = _matShadowViewProj.clone(); matShadowInvProj = _matShadowViewProj.clone().invert(); diff --git a/cocos/rendering/render-reflection-probe-queue.ts b/cocos/rendering/render-reflection-probe-queue.ts index 725b4a4ec6f..4f78db4a021 100644 --- a/cocos/rendering/render-reflection-probe-queue.ts +++ b/cocos/rendering/render-reflection-probe-queue.ts @@ -27,11 +27,11 @@ import { isEnableEffect, SetIndex } from './define'; import { Device, RenderPass, Shader, CommandBuffer } from '../gfx'; import { getPhaseID } from './pass-phase'; import { PipelineStateManager } from './pipeline-state-manager'; -import { Pass, BatchingSchemes } from '../render-scene/core/pass'; +import { Pass, BatchingSchemes, IMacroPatch } from '../render-scene/core/pass'; import { Model } from '../render-scene/scene/model'; -import { Camera, ProbeType, ReflectionProbe, SKYBOX_FLAG } from '../render-scene/scene'; +import { ProbeType, ReflectionProbe } from '../render-scene/scene/reflection-probe'; +import { Camera, SKYBOX_FLAG } from '../render-scene/scene/camera'; import { PipelineRuntime } from './custom/pipeline'; -import { IMacroPatch, RenderScene } from '../render-scene'; import { RenderInstancedQueue } from './render-instanced-queue'; import { cclegacy, geometry } from '../core'; import { Layers } from '../scene-graph/layers'; @@ -77,7 +77,7 @@ export class RenderReflectionProbeQueue { private _subModelsArray: SubModel[] = []; private _passArray: Pass[] = []; private _shaderArray: Shader[] = []; - private _rgbeSubModelsArray: SubModel[]=[] + private _rgbeSubModelsArray: SubModel[] = []; private _instancedQueue: RenderInstancedQueue; private _patches: IMacroPatch[] = []; diff --git a/cocos/rendering/shadow/csm-layers.ts b/cocos/rendering/shadow/csm-layers.ts index fcf74e54312..bed455e4bbe 100644 --- a/cocos/rendering/shadow/csm-layers.ts +++ b/cocos/rendering/shadow/csm-layers.ts @@ -20,7 +20,9 @@ THE SOFTWARE. */ -import { DirectionalLight, Camera, Shadows, CSMLevel, CSMOptimizationMode } from '../../render-scene/scene'; +import { Shadows, CSMLevel, CSMOptimizationMode } from '../../render-scene/scene/shadows'; +import { DirectionalLight } from '../../render-scene/scene/directional-light'; +import { Camera } from '../../render-scene/scene/camera'; import { Mat4, Vec3, Vec2, Vec4 } from '../../core/math'; import { Frustum, AABB } from '../../core/geometry'; import { IRenderObject } from '../define'; @@ -186,8 +188,17 @@ export class ShadowLayerVolume { // snap to whole texels const halfOrthoSizeWidth = orthoSizeWidth * 0.5; const halfOrthoSizeHeight = orthoSizeHeight * 0.5; - Mat4.ortho(_matShadowProj, -halfOrthoSizeWidth, halfOrthoSizeWidth, -halfOrthoSizeHeight, halfOrthoSizeHeight, - 0.1, this._shadowCameraFar, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); + Mat4.ortho( + _matShadowProj, + -halfOrthoSizeWidth, + halfOrthoSizeWidth, + -halfOrthoSizeHeight, + halfOrthoSizeHeight, + 0.1, + this._shadowCameraFar, + device.capabilities.clipSpaceMinZ, + device.capabilities.clipSpaceSignY, + ); Mat4.multiply(_matShadowViewProjArbitaryPos, _matShadowProj, shadowViewArbitaryPos); Vec3.transformMat4(_projPos, _shadowPos, _matShadowViewProjArbitaryPos); @@ -209,8 +220,14 @@ export class ShadowLayerVolume { Mat4.copy(this._matShadowViewProj, _matShadowViewProj); } - Frustum.createOrtho(this._validFrustum, orthoSizeWidth, orthoSizeHeight, - 0.1, this._shadowCameraFar, _matShadowTrans); + Frustum.createOrtho( + this._validFrustum, + orthoSizeWidth, + orthoSizeHeight, + 0.1, + this._shadowCameraFar, + _matShadowTrans, + ); } } export class CSMShadowLayer extends ShadowLayerVolume { @@ -335,8 +352,17 @@ export class CSMLayers { const far = dirLight.shadowFar; Mat4.fromRT(_matShadowTrans, dirLight.node!.getWorldRotation(), dirLight.node!.getWorldPosition()); Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, - device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); + Mat4.ortho( + _matShadowProj, + -x, + x, + -y, + y, + near, + far, + device.capabilities.clipSpaceMinZ, + device.capabilities.clipSpaceSignY, + ); Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); this._specialLayer.matShadowView = _matShadowView; this._specialLayer.matShadowProj = _matShadowProj; @@ -356,7 +382,7 @@ export class CSMLayers { // i ÷ numbers of level const si = i / level; // eslint-disable-next-line no-restricted-properties - const preNear = lambda * (nd * Math.pow(ratio, si)) + (1 - lambda) * (nd + (fd - nd) * si); + const preNear = lambda * (nd * ratio ** si) + (1 - lambda) * (nd + (fd - nd) * si); // Slightly increase the overlap to avoid fracture const nextFar = preNear * 1.005; this._layers[i].splitCameraNear = preNear; diff --git a/cocos/rendering/shadow/shadow-stage.ts b/cocos/rendering/shadow/shadow-stage.ts index edae01d16ac..020bd72715e 100644 --- a/cocos/rendering/shadow/shadow-stage.ts +++ b/cocos/rendering/shadow/shadow-stage.ts @@ -31,7 +31,9 @@ import { ForwardPipeline } from '../forward/forward-pipeline'; import { SetIndex } from '../define'; import { Light, LightType } from '../../render-scene/scene/light'; import { ShadowFlow } from './shadow-flow'; -import { Camera, CSMLevel, DirectionalLight } from '../../render-scene/scene'; +import { DirectionalLight } from '../../render-scene/scene/directional-light'; +import { CSMLevel } from '../../render-scene/scene/shadows'; +import { Camera } from '../../render-scene/scene/camera'; const colors: Color[] = [new Color(1, 1, 1, 1)]; @@ -98,8 +100,14 @@ export class ShadowStage extends RenderStage { const cmdBuff = pipeline.commandBuffers[0]; const renderPass = this._shadowFrameBuffer.renderPass; - cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, - colors, camera.clearDepth, camera.clearStencil); + cmdBuff.beginRenderPass( + renderPass, + this._shadowFrameBuffer, + this._renderArea, + colors, + camera.clearDepth, + camera.clearStencil, + ); cmdBuff.endRenderPass(); this._isShadowMapCleared = true; } @@ -151,8 +159,14 @@ export class ShadowStage extends RenderStage { const renderPass = this._shadowFrameBuffer.renderPass; - cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, - colors, camera.clearDepth, camera.clearStencil); + cmdBuff.beginRenderPass( + renderPass, + this._shadowFrameBuffer, + this._renderArea, + colors, + camera.clearDepth, + camera.clearStencil, + ); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet); this._additiveShadowQueue.recordCommandBuffer(device, renderPass, cmdBuff); diff --git a/cocos/root.ts b/cocos/root.ts index efab7abacb0..99c2d28dd60 100644 --- a/cocos/root.ts +++ b/cocos/root.ts @@ -23,7 +23,9 @@ */ import { Pool, cclegacy, warnID, settings, Settings, macro } from './core'; -import { RenderPipeline, createDefaultPipeline, DeferredPipeline } from './rendering'; +import type { RenderPipeline } from './rendering/render-pipeline'; +import { DeferredPipeline } from './rendering/deferred/deferred-pipeline'; +import { createDefaultPipeline } from './rendering/forward/forward-pipeline'; import { DebugView } from './rendering/debug-view'; import { Camera, CameraType, Light, Model, TrackingType } from './render-scene/scene'; import type { DataPoolManager } from './3d/skeletal-animation/data-pool-manager'; @@ -41,6 +43,7 @@ import { Batcher2D } from './2d/renderer/batcher-2d'; import { IPipelineEvent } from './rendering/pipeline-event'; import { localDescriptorSetLayout_ResizeMaxJoints, UBOCamera, UBOGlobal, UBOLocal, UBOShadow, UBOWorldBound } from './rendering/define'; import { XREye, XRPoseType } from './xr/xr-enums'; +import { ICustomJointTextureLayout } from './3d/skeletal-animation/skeletal-animation-utils'; /** * @en Initialization information for the Root @@ -311,7 +314,10 @@ export class Root { swapchain, }); this._curWindow = this._mainWindow; - const customJointTextureLayouts = settings.querySettings(Settings.Category.ANIMATION, 'customJointTextureLayouts') || []; + const customJointTextureLayouts = settings.querySettings( + Settings.Category.ANIMATION, + 'customJointTextureLayouts', + ) as ICustomJointTextureLayout[] || []; this._dataPoolMgr?.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts); this._resizeMaxJointForDS(); } @@ -717,7 +723,7 @@ export class Root { let allcameras: Camera[] = []; const webxrHmdPoseInfos = xr.webxrHmdPoseInfos; - for (let xrEye = 0; xrEye < viewCount; xrEye++) { + for (let xrEye: XREye = 0; xrEye < viewCount; xrEye++) { for (const window of windows) { allcameras = allcameras.concat(window.cameras); if (window.swapchain) { @@ -789,7 +795,7 @@ export class Root { if (this._pipeline && cameraList.length > 0) { this._device.acquire([deviceManager.swapchain]); const scenes = this._scenes; - const stamp = director.getTotalFrames(); + const stamp = director.getTotalFrames() as number; if (this._batcher) { this._batcher.update(); From e0bfd7e1cf46979ac85b735794ce83a180b165c7 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 26 Jul 2023 13:16:46 +0800 Subject: [PATCH 073/232] Fix DS_Store ignore in tempaltes --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4dfa79f089c..229c3ea39a6 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,7 @@ native/external/ scripts/typedoc-plugin/lib/ !templates/**/* +templates/**/.DS_Store @types/consts.d.ts From 61422450d3bb76e4f40881d2d70ab4ba68391bfa Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 26 Jul 2023 13:50:04 +0800 Subject: [PATCH 074/232] Fix circular dependencies --- cocos/render-scene/scene/reflection-probe.ts | 10 ++++----- cocos/rendering/custom/define.ts | 16 +++++++++----- .../global-descriptor-set-manager.ts | 3 +-- .../reflection-probe-stage.ts | 22 ++++++++++++++----- 4 files changed, 32 insertions(+), 19 deletions(-) diff --git a/cocos/render-scene/scene/reflection-probe.ts b/cocos/render-scene/scene/reflection-probe.ts index 43bc0526fe0..9c794c75172 100644 --- a/cocos/render-scene/scene/reflection-probe.ts +++ b/cocos/render-scene/scene/reflection-probe.ts @@ -24,12 +24,11 @@ import { EDITOR } from 'internal:constants'; import { Camera, CameraAperture, CameraFOVAxis, CameraISO, CameraProjection, CameraShutter, CameraType, SKYBOX_FLAG, TrackingType } from './camera'; import { Node } from '../../scene-graph/node'; -import { Color, Quat, Rect, toRadian, Vec2, Vec3, geometry, cclegacy, Vec4 } from '../../core'; +import { Color, Quat, Rect, toRadian, Vec2, Vec3, geometry, cclegacy, Vec4, Size } from '../../core'; import { CAMERA_DEFAULT_MASK } from '../../rendering/define'; import { ClearFlagBit, Framebuffer } from '../../gfx'; import { TextureCube } from '../../asset/assets/texture-cube'; import { RenderTexture } from '../../asset/assets/render-texture'; -import { view } from '../../ui/view'; export enum ProbeClearFlag { SKYBOX = SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL, @@ -309,7 +308,7 @@ export class ReflectionProbe { public renderPlanarReflection (sourceCamera: Camera): void { if (!sourceCamera) return; if (!this.realtimePlanarTexture) { - const canvasSize = view.getDesignResolutionSize(); + const canvasSize = cclegacy.view.getDesignResolutionSize() as Size; this.realtimePlanarTexture = this._createTargetTexture(canvasSize.width, canvasSize.height); cclegacy.internal.reflectionProbeManager.updatePlanarMap(this, this.realtimePlanarTexture.getGFXTexture()); } @@ -422,14 +421,13 @@ export class ReflectionProbe { private _createCamera (cameraNode: Node): Camera | null { const root = cclegacy.director.root; if (!this._camera) { - this._camera = (cclegacy.director.root).createCamera(); + this._camera = root.createCamera(); if (!this._camera) return null; this._camera.initialize({ name: cameraNode.name, node: cameraNode, projection: CameraProjection.PERSPECTIVE, - window: EDITOR ? cclegacy.director.root && cclegacy.director.root.mainWindow - : cclegacy.director.root && cclegacy.director.root.tempWindow, + window: EDITOR ? root && root.mainWindow : root && root.tempWindow, priority: 0, cameraType: CameraType.DEFAULT, trackingType: TrackingType.NO_TRACKING, diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 21769f3a145..a2a983c9b3b 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -25,10 +25,15 @@ import { EDITOR } from 'internal:constants'; import { BufferInfo, Buffer, BufferUsageBit, ClearFlagBit, Color, DescriptorSet, LoadOp, Format, Rect, Sampler, StoreOp, Texture, Viewport, MemoryUsageBit, Filter, Address } from '../../gfx'; -import { - Camera, CSMLevel, DirectionalLight, Light, LightType, ProbeType, ReflectionProbe, - ShadowType, SKYBOX_FLAG, SpotLight, PointLight, RangedDirectionalLight, SphereLight, -} from '../../render-scene/scene'; +import { ProbeType, ReflectionProbe } from '../../render-scene/scene/reflection-probe'; +import { Camera, SKYBOX_FLAG } from '../../render-scene/scene/camera'; +import { CSMLevel, ShadowType } from '../../render-scene/scene/shadows'; +import { Light, LightType } from '../../render-scene/scene/light'; +import { DirectionalLight } from '../../render-scene/scene/directional-light'; +import { RangedDirectionalLight } from '../../render-scene/scene/ranged-directional-light'; +import { PointLight } from '../../render-scene/scene/point-light'; +import { SphereLight } from '../../render-scene/scene/sphere-light'; +import { SpotLight } from '../../render-scene/scene/spot-light'; import { supportsR32FloatTexture, supportsRGBA16HalfFloatTexture } from '../define'; import { BasicPipeline, Pipeline } from './pipeline'; import { @@ -45,7 +50,6 @@ import { DescriptorSetData } from './layout-graph'; import { AABB } from '../../core/geometry'; import { DebugViewCompositeType, DebugViewSingleType } from '../debug-view'; import { ReflectionProbeManager } from '../../3d/reflection-probe/reflection-probe-manager'; -import { director } from '../../game/director'; const _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5); const _tmpBoundingBox = new AABB(); @@ -1049,7 +1053,7 @@ export function buildUIPass ( } export function updateCameraUBO (setter: any, camera: Readonly, ppl: Readonly): void { - const pipeline = director.root!.pipeline as WebPipeline; + const pipeline = cclegacy.director.root!.pipeline as WebPipeline; const sceneData = ppl.pipelineSceneData; const skybox = sceneData.skybox; setter.addConstant('CCCamera'); diff --git a/cocos/rendering/global-descriptor-set-manager.ts b/cocos/rendering/global-descriptor-set-manager.ts index aff3b5a0798..e0c2a27ef58 100644 --- a/cocos/rendering/global-descriptor-set-manager.ts +++ b/cocos/rendering/global-descriptor-set-manager.ts @@ -22,10 +22,9 @@ THE SOFTWARE. */ -import { cclegacy } from '../core'; import { Device, BufferUsageBit, MemoryUsageBit, BufferInfo, Filter, Address, Sampler, DescriptorSet, DescriptorSetInfo, Buffer, Texture, DescriptorSetLayoutInfo, DescriptorSetLayout, SamplerInfo } from '../gfx'; -import { Light } from '../render-scene/scene'; +import { Light } from '../render-scene/scene/light'; import { getDescBindingFromName, getDescriptorSetDataFromLayout } from './custom/define'; import { UBOShadow, globalDescriptorSetLayout, PipelineGlobalBindings, isEnableEffect } from './define'; diff --git a/cocos/rendering/reflection-probe/reflection-probe-stage.ts b/cocos/rendering/reflection-probe/reflection-probe-stage.ts index beacaacb375..1514374938d 100644 --- a/cocos/rendering/reflection-probe/reflection-probe-stage.ts +++ b/cocos/rendering/reflection-probe/reflection-probe-stage.ts @@ -29,7 +29,7 @@ import { ForwardStagePriority } from '../enum'; import { ForwardPipeline } from '../forward/forward-pipeline'; import { SetIndex } from '../define'; import { ReflectionProbeFlow } from './reflection-probe-flow'; -import { Camera, ProbeType, ReflectionProbe } from '../../render-scene/scene'; +import { Camera, ReflectionProbe } from '../../render-scene/scene'; import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; import { Vec3 } from '../../core'; import { packRGBE } from '../../core/math/color'; @@ -90,8 +90,14 @@ export class ReflectionProbeStage extends RenderStage { const cmdBuff = pipeline.commandBuffers[0]; const renderPass = this._frameBuffer.renderPass; - cmdBuff.beginRenderPass(renderPass, this._frameBuffer, this._renderArea, - colors, camera.clearDepth, camera.clearStencil); + cmdBuff.beginRenderPass( + renderPass, + this._frameBuffer, + this._renderArea, + colors, + camera.clearDepth, + camera.clearStencil, + ); cmdBuff.endRenderPass(); } @@ -119,8 +125,14 @@ export class ReflectionProbeStage extends RenderStage { colors[0].w = rgbe.w; } const device = pipeline.device; - cmdBuff.beginRenderPass(renderPass, this._frameBuffer!, this._renderArea, - colors, this._probe!.camera.clearDepth, this._probe!.camera.clearStencil); + cmdBuff.beginRenderPass( + renderPass, + this._frameBuffer!, + this._renderArea, + colors, + this._probe!.camera.clearDepth, + this._probe!.camera.clearStencil, + ); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); this._probeRenderQueue.recordCommandBuffer(device, renderPass, cmdBuff); From 0d4e5497e242ddec11e960290d2579ee90eabde4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Wed, 26 Jul 2023 17:25:33 +0800 Subject: [PATCH 075/232] [Bug] fix widget undo bug (#15741) * fix widget undo bug * next tick snapshot --- editor/inspector/components/widget.js | 28 ++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/editor/inspector/components/widget.js b/editor/inspector/components/widget.js index 2b6fafc7193..8c7b0b371a0 100644 --- a/editor/inspector/components/widget.js +++ b/editor/inspector/components/widget.js @@ -565,6 +565,12 @@ exports.methods = { this.$refs.summitProp.dispatch('change-dump'); }, + snapshot() { + // next tick snapshot + setTimeout(() => { + this.$refs.summitProp.dispatch('confirm-dump'); + }); + }, getUnit(type) { const data = this.dump.value; @@ -661,6 +667,7 @@ exports.methods = { const { dump } = update(this.dump, true); this.$refs.summitProp.dump = dump; this.$refs.summitProp.dispatch('change-dump'); + this.snapshot(); }, select(event) { @@ -892,7 +899,7 @@ exports.methods = { this.dimensionVertical = this.getDimensionVertical(); } - this.$refs.summitProp.dispatch('confirm-dump'); + this.snapshot(); }, toggleLock(direction) { @@ -931,6 +938,7 @@ exports.methods = { } this.$refs.summitProp.dispatch('change-dump'); + this.snapshot(); }, isLock(direction) { const lockValue = this.dump.value._lockFlags.value; @@ -1046,7 +1054,9 @@ const template = /* html*/` @@ -1065,6 +1075,7 @@ const template = /* html*/` :disabled="!dump.value.isAlignHorizontalCenter.value" :value="dump.value.editorHorizontalCenter.value" @change="change('editorHorizontalCenter', $event.target.value)" + @confirm="snapshot()" @unit-click="changeUnit('editorHorizontalCenter')"> @@ -1078,7 +1089,9 @@ const template = /* html*/` @@ -1121,7 +1134,9 @@ const template = /* html*/` @@ -1139,6 +1154,7 @@ const template = /* html*/` @@ -1153,7 +1169,9 @@ const template = /* html*/` From a9ffcad7ea774793e50a184f4d996c1bade09317 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Wed, 26 Jul 2023 17:26:01 +0800 Subject: [PATCH 076/232] =?UTF-8?q?[Bug]=20when=20editor=20change=20langua?= =?UTF-8?q?ge=EF=BC=8Cupdate=20fbx=20editing=20interface=20(#15762)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * when editor change language,update fbx editing interface * update --- editor/inspector/assets/fbx/model.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index 63c6561fb2a..6fac16493b2 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -889,6 +889,27 @@ const Elements = { }, }, // lods end + // when lang change + i18n: { + ready() { + const panel = this; + + Elements.i18n.changeBind = Elements.i18n.change.bind(panel); + Editor.Message.addBroadcastListener('i18n:change', Elements.i18n.changeBind); + }, + close() { + Editor.Message.removeBroadcastListener('i18n:change', Elements.i18n.changeBind); + Elements.i18n.changeBind = undefined; + }, + change() { + const panel = this; + + Elements.normals.update.call(panel); + Elements.tangents.update.call(panel); + Elements.morphNormals.update.call(panel); + Elements.meshOptimizerAlgorithm.update.call(panel); + }, + }, }; exports.methods = { From 30061b151dafb76ec940f2f3d08d5266630f0528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Wed, 26 Jul 2023 17:59:31 +0800 Subject: [PATCH 077/232] reflectionprobe manager add function for users (#15824) --- .../reflection-probe-component.ts | 18 +++++++------ .../reflection-probe-manager.ts | 26 +++++++++++++++---- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index dcd2f840c9a..2f3c06e53d6 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -326,12 +326,14 @@ export class ReflectionProbe extends Component { ReflectionProbeManager.probeManager.onUpdateProbes(true); this._probe.enable(); } + this.node.on(Node.EventType.TRANSFORM_CHANGED, this._onProbeTransformChanged, this); } onDisable (): void { if (this._probe) { ReflectionProbeManager.probeManager.unregister(this._probe); this._probe.disable(); } + this.node.off(Node.EventType.TRANSFORM_CHANGED, this._onProbeTransformChanged); } public start (): void { @@ -363,14 +365,6 @@ export class ReflectionProbe extends Component { } } } - - if (this.node.hasChangedFlags) { - this.probe.updateBoundingBox(); - } - if (this.node.hasChangedFlags & TransformBit.POSITION) { - ReflectionProbeManager.probeManager.onUpdateProbes(true); - ReflectionProbeManager.probeManager.updateProbeData(); - } } if (this.probeType === ProbeType.PLANAR && this.sourceCamera) { if ((this.sourceCamera.node.hasChangedFlags & TransformBit.TRS) @@ -391,6 +385,14 @@ export class ReflectionProbe extends Component { ReflectionProbeManager.probeManager.updatePreviewSphere(this.probe); } + private _onProbeTransformChanged (type: TransformBit): void { + this.probe.updateBoundingBox(); + if (type & Node.TransformBit.POSITION) { + ReflectionProbeManager.probeManager.onUpdateProbes(true); + ReflectionProbeManager.probeManager.updateProbeData(); + } + } + private _createProbe (): void { if (this._probeId === -1 || ReflectionProbeManager.probeManager.exists(this._probeId)) { this._probeId = ReflectionProbeManager.probeManager.getNewReflectionProbeId(); diff --git a/cocos/3d/reflection-probe/reflection-probe-manager.ts b/cocos/3d/reflection-probe/reflection-probe-manager.ts index 9b114aff0f4..88dc20c07d3 100644 --- a/cocos/3d/reflection-probe/reflection-probe-manager.ts +++ b/cocos/3d/reflection-probe/reflection-probe-manager.ts @@ -86,7 +86,7 @@ export class ReflectionProbeManager { if (!scene || !scene.renderScene) { return; } - const models = scene.renderScene.models; + const models = scene.renderScene.models as Model[]; for (let i = 0; i < models.length; i++) { const model = models[i]; if (!model.node) continue; @@ -106,7 +106,7 @@ export class ReflectionProbeManager { if (!scene || !scene.renderScene) { return; } - const models = scene.renderScene.models; + const models = scene.renderScene.models as Model[]; for (let i = 0; i < models.length; i++) { const model = models[i]; if (!model.node) continue; @@ -441,6 +441,22 @@ export class ReflectionProbeManager { return null; } + /** + * @en Set reflection probe used by the model. + * @zh 手动设置模型使用的反射探针。 + * @param model set the probe for this model + * @param probe reflection probe to be set + * @param blendProbe reflection probe for blend + */ + public setReflectionProbe (model: Model, probe: ReflectionProbe, blendProbe: ReflectionProbe | null = null): void { + if (!probe) return; + this._useCubeModels.set(model, probe); + this._updateCubemapOfModel(model, probe); + if (blendProbe) { + this._updateBlendProbeInfo(model, probe, blendProbe); + } + } + /** * @en * select the probe with the nearest distance. @@ -535,7 +551,8 @@ export class ReflectionProbeManager { if (probe) { meshRender.updateReflectionProbeDataMap(this._dataTexture); if (this._isUsedBlending(model)) { - this._updateBlendProbeInfo(model, probe); + const blendProbe = this._getBlendProbe(model); + this._updateBlendProbeInfo(model, probe, blendProbe); } } } @@ -559,7 +576,7 @@ export class ReflectionProbeManager { return false; } - private _updateBlendProbeInfo (model: Model, probe: ReflectionProbe): void { + private _updateBlendProbeInfo (model: Model, probe: ReflectionProbe, blendProbe: ReflectionProbe | null): void { const node = model.node; if (!node) { return; @@ -568,7 +585,6 @@ export class ReflectionProbeManager { if (!meshRender) { return; } - const blendProbe = this._getBlendProbe(model); if (blendProbe) { meshRender.updateReflectionProbeBlendId(blendProbe.getProbeId()); meshRender.updateProbeBlendCubemap(blendProbe.cubemap); From cd90419f2e453872f60877bf66ccd8a8d294f265 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Wed, 26 Jul 2023 18:00:51 +0800 Subject: [PATCH 078/232] fix editing fbx animation events interface bug (#15718) * fix the bug of changing select fbx, the preview interface did not update * fix editing fbx animation events interface bug --- .../assets/fbx/event-editor/editor.js | 70 ++++++++------ .../assets/fbx/event-editor/event-item.js | 27 +----- .../assets/fbx/event-editor/index.js | 15 ++- editor/inspector/assets/fbx/events/events.js | 95 +++++++------------ editor/inspector/assets/fbx/events/index.js | 95 +++++++++++++++---- editor/inspector/assets/fbx/preview.js | 63 ++++++++---- 6 files changed, 212 insertions(+), 153 deletions(-) diff --git a/editor/inspector/assets/fbx/event-editor/editor.js b/editor/inspector/assets/fbx/event-editor/editor.js index ecf08c083d8..a7f3af354d0 100644 --- a/editor/inspector/assets/fbx/event-editor/editor.js +++ b/editor/inspector/assets/fbx/event-editor/editor.js @@ -6,15 +6,15 @@ const eventItem = require('./event-item'); exports.template = `
- - + +
:index="index" :key="index" @update="updateValue" + @delete="deleteValue" >
@@ -50,8 +51,8 @@ exports.data = function() { dirty: false, debounceSave: null, // time value - frame: 0, - RealFrame: 0, + frame: -1, + RealFrame: -1, show: false, }; }; @@ -71,26 +72,27 @@ exports.methods = { that.showToast(Editor.I18n.t('animator.event.enter_func_name')); return; } - that.value.push({ - func: that.newFuncName, - params: [], - frame: that.frame, + that.$emit('addFunc', that.frame, that.newFuncName); + setTimeout(() => { + that.newFuncName = ''; }); - that.dirty = true; - that.debounceSave(); }, updateValue(eventInfo, index) { const that = this; - if (!eventInfo) { - that.value.splice(index, 1); - } else { - that.value[index] = eventInfo; - } + that.value[index] = eventInfo; that.dirty = true; that.debounceSave(); }, + deleteValue(index) { + const that = this; + const eventInfo = that.value[index]; + if (eventInfo) { + that.$emit('delFunc', eventInfo.frame, eventInfo); + } + }, + showToast(msg, time = 800) { const that = this; if (that.toast) { @@ -106,23 +108,37 @@ exports.methods = { }, time); }, - async saveData() { + saveData() { const that = this; - that.$emit('update', that.frame, that.value); + that.$emit('update', that.value); that.dirty = false; }, - refresh() { + refresh(events) { const that = this; - let data = that.events.filter((item) => { - return item.frame === that.frame; - }); - if (data.length < 1) { - that.value = []; - return; + const infos = []; + + if (Array.isArray(events)) { + if (!events.length) { + this.frame = -1; + } + + events.forEach((item) => { + if (item.info.frame === that.frame) { + infos.push(item.info); + } + }); } - that.value = JSON.parse(JSON.stringify(data)); - that.newFuncName = ''; + + that.value = infos; + that.show = !!infos.length; + + }, + hide() { + this.$emit('hide'); + }, + unselect() { + this.show = false; }, }; diff --git a/editor/inspector/assets/fbx/event-editor/event-item.js b/editor/inspector/assets/fbx/event-editor/event-item.js index 65c525958cb..88865cd5e69 100644 --- a/editor/inspector/assets/fbx/event-editor/event-item.js +++ b/editor/inspector/assets/fbx/event-editor/event-item.js @@ -80,16 +80,6 @@ exports.props = [ 'index', ]; -exports.computed = { - selectEvent() { - const that = this; - if (!that.selectInfo) { - return null; - } - return that.selectInfo.data; - }, -}; - exports.methods = { onConfirm(event) { const that = this; @@ -126,27 +116,20 @@ exports.methods = { const that = this; const name = event.target.getAttribute('name'); let index = event.target.getAttribute('index'); - const eventInfo = that.event; - let dirty = false; switch (name) { case 'delFunc': - that.$emit('update', null, that.index); + that.$emit('delete', that.index); return; case 'addParams': - dirty = true; - eventInfo.params.splice(eventInfo.params.length - 1, 0, 'param'); + that.event.params.splice(that.event.params.length - 1, 0, 'param'); break; case 'delParams': - dirty = true; - eventInfo.params.splice(index, 1); + that.event.params.splice(index, 1); break; case 'clearParams': - if (eventInfo.params.length) { - dirty = true; - eventInfo.params = []; - } + that.event.params = []; break; } - dirty && that.$emit('update', that.event, that.index); + that.$emit('update', that.event, that.index); }, }; diff --git a/editor/inspector/assets/fbx/event-editor/index.js b/editor/inspector/assets/fbx/event-editor/index.js index 1e549ac1983..c15d4562a38 100644 --- a/editor/inspector/assets/fbx/event-editor/index.js +++ b/editor/inspector/assets/fbx/event-editor/index.js @@ -14,8 +14,19 @@ exports.ready = function() { components: eventEditor.components, mounted: eventEditor.mounted, }); - this.eventEditorVm.$on('update', (frame, eventInfos) => { - this.events.updateEventInfo.call(this, frame, eventInfos); + this.eventEditorVm.$on('update', (eventInfos) => { + this.events.updateEventInfo.call(this, eventInfos); + }); + + this.eventEditorVm.$on('addFunc', (frame, newFuncName) => { + this.events.addEvent.call(this, frame, newFuncName); + }); + + this.eventEditorVm.$on('delFunc', (frame, eventInfo) => { + this.events.delEvent.call(this, frame, eventInfo); + }); + this.eventEditorVm.$on('hide', (frame, eventInfo) => { + this.events.unselect.call(this, frame, eventInfo); }); }; diff --git a/editor/inspector/assets/fbx/events/events.js b/editor/inspector/assets/fbx/events/events.js index 8d476c3a8c6..71bc60abc97 100644 --- a/editor/inspector/assets/fbx/events/events.js +++ b/editor/inspector/assets/fbx/events/events.js @@ -4,25 +4,16 @@ exports.template = /* html */`
-
@@ -31,18 +22,7 @@ exports.template = /* html */` exports.data = { events: [], offset: 0, - selectEvent: [], - eventEditorInfo: { - frame: 0, - events: [{ - func: '', - params: [], - frame: 0, - }], - }, - selectInfo: { - frames: [], - }, + frame: -1, }; exports.methods = { @@ -53,45 +33,40 @@ exports.methods = { onPopMenu(event, eventInfo) { const that = this; const menu = [{ - label: Editor.I18n.t(`animator.event.edit`), - click() { - that.openEventEditor(eventInfo); - }, - }, { label: Editor.I18n.t(`animator.event.delete`), click() { that.$emit('del', eventInfo); }, - }, - ]; + }]; Editor.Menu.popup({ - x: event.pageX, - y: event.pageY, menu, }); }, - onMouseDown(event, info) { + onMouseDown(event, item) { const that = this; event.stopPropagation(); - const data = JSON.parse(JSON.stringify(info)); - let selectIndex = that.selectInfo && that.selectInfo.frames.indexOf(info.frame); - if (typeof selectIndex !== 'number' || selectIndex === -1) { - that.selectInfo = { - startX: event.x, - data: [data], - offset: 0, - offsetFrame: 0, - frames: [info.frame], - }; - } else { - that.selectInfo.startX = event.x; + this.frame = item.info.frame; + + const clientX = event.clientX; + const startX = item.x; + function mousemove(event) { + const timelineX = startX + (event.clientX - clientX); + that.$emit('move', item, timelineX); + } + + function mouseup() { + that.$emit('moveEnd', item); + document.removeEventListener('mousemove', mousemove); + document.removeEventListener('mouseup', mouseup); } + document.addEventListener('mousemove', mousemove); + document.addEventListener('mouseup', mouseup); }, openEventEditor(eventInfo) { - // HACK 目前的事件帧会有重复关键帧重叠的情况 - this.selectInfo.frames = [eventInfo.frame]; + // 目前的事件帧会有重复关键帧重叠的情况 + this.frame = eventInfo.frame; this.$emit('edit', eventInfo); }, @@ -99,17 +74,15 @@ exports.methods = { return `transform: translateX(${x || 0}px);`; }, - onDomMouseDown() { - this.selectInfo = { - frames: [], - }; + refresh(eventInfos) { + this.events = eventInfos; + if (!eventInfos.some((item) => item.info.frame === this.frame)) { + this.unselect(); + } }, -}; -exports.mounted = function() { - document.addEventListener('mousedown', this.onDomMouseDown); + unselect() { + this.frame = -1; + }, }; -exports.beforeDestroy = function() { - document.removeEventListener('mousedown', this.onDomMouseDown); -}; diff --git a/editor/inspector/assets/fbx/events/index.js b/editor/inspector/assets/fbx/events/index.js index 29e11f4c141..18e64467ee2 100644 --- a/editor/inspector/assets/fbx/events/index.js +++ b/editor/inspector/assets/fbx/events/index.js @@ -20,11 +20,9 @@ exports.ready = function() { if (this.checkDisabledEditEvent()) { return; } - this.eventEditorVm.events = this.eventVm.events; this.eventEditorVm.frame = eventInfo.frame; this.eventEditorVm.RealFrame = Math.round(eventInfo && eventInfo.frame * this.curEditClipInfo.fps || 0); - this.eventEditorVm.refresh(); - this.eventEditorVm.show = true; + this.eventEditorVm.refresh(this.eventVm.events); }); this.eventVm.$on('del', (eventInfo) => { if (this.checkDisabledEditEvent()) { @@ -32,10 +30,26 @@ exports.ready = function() { } this.events.delEvent.call(this, eventInfo.frame); }); + + this.eventVm.$on('move', (eventItem, timelineX) => { + if (this.checkDisabledEditEvent()) { + return; + } + this.events.moveEvent.call(this, eventItem, timelineX); + }); + + this.eventVm.$on('moveEnd', (eventItem) => { + if (this.checkDisabledEditEvent()) { + return; + } + this.eventVm.openEventEditor(eventItem.info); + this.dispatch('snapshot'); + }); }; -exports.update = function(eventInfo) { - this.eventVm.events = eventInfo; +exports.update = function(eventInfos) { + this.eventVm.refresh(eventInfos); + this.eventEditorVm.refresh(eventInfos); }; exports.apply = async function() { @@ -52,45 +66,84 @@ exports.apply = async function() { this.events.eventsMap = {}; }; -exports.addNewEvent = function(time) { +exports.addEvent = function(time, newFuncName = '') { const newInfo = { + // 注意: frame 是时间 frame: time, - func: '', + func: newFuncName, params: [], }; + const userData = this.curEditClipInfo.userData; if (!userData.events) { userData.events = [newInfo]; } else { - userData.events.push(newInfo); - userData.events.sort((a, b) => a.frame - b.frame); + // 已经存在空记录 + if (!newFuncName && userData.events.some(event => event.frame === time && event.func === newFuncName)) { + return; + } + + let exist = false; + for (const event of userData.events) { + if (event.frame === time && event.func === '') { + event.func = newFuncName; + exist = true; + break; + } + } + + if (!exist) { + userData.events.push(newInfo); + userData.events.sort((a, b) => a.frame - b.frame); + } } - this.events.eventsMap[this.curEditClipInfo.clipUUID] = userData.events; + this.updateEventInfo(); this.dispatch('change'); this.dispatch('snapshot'); + + this.eventVm.openEventEditor(newInfo); }; -exports.delEvent = function(time) { +exports.delEvent = function(frame, info) { const userData = this.curEditClipInfo.userData; - userData.events = userData.events.filter((item) => item.frame !== time); - this.events.eventsMap[this.curEditClipInfo.clipUUID] = userData.events; + if (info) { + userData.events = userData.events.filter((item) => item !== info); + } else { + // 删除多个 + userData.events = userData.events.filter((item) => item.frame !== frame); + } + this.updateEventInfo(); this.dispatch('change'); this.dispatch('snapshot'); }; -exports.updateEventInfo = function(time, eventInfos) { +exports.moveEvent = function(eventItem, timelineX) { + const frame = Math.min(this.$.animationTime._config.max, Math.max(0, Math.round(this.$.animationTime.pixelToValue(timelineX)))); + + eventItem.info.frame = frame / this.curEditClipInfo.fps; + eventItem.x = this.$.animationTime.valueToPixel(frame); + + this.dispatch('change'); +}; + +exports.unselect = function() { + this.eventVm.unselect(); + this.eventEditorVm.unselect(); +}; + +exports.updateEventInfo = function(eventInfos) { const userData = this.curEditClipInfo.userData; - let newEvents = []; - if (userData.events) { - newEvents = userData.events.filter((item) => item.frame !== time); + if (userData && userData.events && Array.isArray(eventInfos)) { + eventInfos.forEach((eventInfo) => { + if (!userData.events.includes(eventInfo)) { + userData.events.push(eventInfo); + } + }); } - newEvents.push(...eventInfos); - userData.events = newEvents; - this.events.eventsMap[this.curEditClipInfo.clipUUID] = newEvents; this.updateEventInfo(); this.dispatch('change'); - this.dispatch('update'); + this.dispatch('snapshot'); }; diff --git a/editor/inspector/assets/fbx/preview.js b/editor/inspector/assets/fbx/preview.js index 0937b7c346e..8b4fed5d2bb 100644 --- a/editor/inspector/assets/fbx/preview.js +++ b/editor/inspector/assets/fbx/preview.js @@ -27,7 +27,7 @@ exports.template = /* html */`
- +
@@ -168,6 +168,7 @@ ui-icon { background: var(--color-normal-fill); } #event-editor { + position: relative; line-height: 20px; width: 100%; height: 70%; @@ -186,6 +187,9 @@ ui-icon { background: var(--color-normal-fill-emphasis); padding: 2px 4px; } + #event-editor > header .title { + color: var(--color-focus-fill); + } #event-editor > .header .name { margin: 0 4px; } @@ -194,7 +198,6 @@ ui-icon { margin: 0 2px; } #event-editor > .functions { - padding: 4px; overflow-y: auto; flex: 1; height: 100%; @@ -234,6 +237,7 @@ ui-icon { #event-editor ui-checkbox, #event-editor ui-num-input { flex: 1; + margin-left: 4px; } #event-editor ui-section { width: 100%; @@ -259,6 +263,15 @@ ui-icon { font-style: italic; text-align: center; } + #event-editor .toast { + position: absolute; + top: 54px; + right: 4px; + z-index: 1; + padding: 0 4px; + background-color: var(--color-normal-fill-emphasis); + color: var(--color-warn-fill); + } `; exports.$ = { @@ -484,7 +497,11 @@ exports.methods = { async onTabChanged(activeTab) { if (typeof activeTab === 'string') { this.activeTab = activeTab; - this.$.animationInfo.style.display = this.activeTab === 'animation' ? 'block' : 'none'; + const isAnimationTab = this.activeTab === 'animation'; + this.$.animationInfo.style.display = isAnimationTab ? 'block' : 'none'; + if (!isAnimationTab) { + this.eventEditorVm.show = false; + } this.$.modelInfo.style.display = this.activeTab === 'model' ? 'block' : 'none'; await this.stopAnimation(); } @@ -534,19 +551,22 @@ exports.methods = { }, addEventToCurTime() { - this.events.addNewEvent.call(this, this.$.animationTime.value / this.curEditClipInfo.fps); + this.events.addEvent.call(this, this.$.animationTime.value / this.curEditClipInfo.fps); }, updateEventInfo() { let eventInfos = []; - const events = this.curEditClipInfo.userData.events; - if (Array.isArray(events)) { - eventInfos = events.map((info) => { - return { - ...info, - x: this.$.animationTime.valueToPixel(info.frame * this.curEditClipInfo.fps), - }; - }); + + if (this.curEditClipInfo && this.curEditClipInfo.userData) { + const events = this.curEditClipInfo.userData.events; + if (Array.isArray(events)) { + eventInfos = events.map((info) => { + return { + info, + x: this.$.animationTime.valueToPixel(info.frame * this.curEditClipInfo.fps), + }; + }); + } } this.events.update.call(this, eventInfos); @@ -633,22 +653,16 @@ exports.methods = { }, async setCurEditClipInfo(clipInfo) { this.curEditClipInfo = clipInfo; + this.curTotalFrames = 0; if (clipInfo) { this.curTotalFrames = Math.round(clipInfo.duration * clipInfo.fps); - this.$.animationTime.setConfig({ - max: this.curTotalFrames, - }); - this.$.duration.innerHTML = `Duration: ${this.curTotalFrames}`; + // update animation events, clipInfo.clipUUID may be undefined if (clipInfo.clipUUID) { const subId = clipInfo.clipUUID.match(/@(.*)/)[1]; this.curEditClipInfo.userData = this.meta.subMetas[subId] && this.meta.subMetas[subId].userData || {}; - this.updateEventInfo(); } - if (this.$.animationTimeSlider) { - this.$.animationTimeSlider.max = this.curTotalFrames; - } await callModelPreviewFunction( 'setPlaybackRange', clipInfo.from, @@ -665,6 +679,12 @@ exports.methods = { await this.stopAnimation(); } + + this.$.animationTime.setConfig({ + max: this.curTotalFrames, + }); + this.$.duration.innerHTML = `Totals: ${this.curTotalFrames}`; + this.updateEventInfo(); }, onAnimationPlayStateChanged(state) { this.setCurPlayState(state); @@ -757,7 +777,10 @@ exports.update = async function(assetList, metaList) { this.splitClipIndex = 0; const clipInfo = animation.methods.getCurClipInfo.call(this); await this.onEditClipInfoChanged(clipInfo); + } else { + await this.setCurEditClipInfo(); } + this.eventEditorVm.show = false; this.setCurPlayState(PLAY_STATE.STOP); this.isPreviewDataDirty = true; this.refreshPreview(); From f20bf8ce110a04c69489f3f392f7e423a57f7b8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Fri, 28 Jul 2023 16:24:35 +0800 Subject: [PATCH 079/232] init reflection probe id with native engine (#15829) --- native/cocos/scene/Model.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 07b953f6910..7085d355383 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -298,7 +298,7 @@ class Model : public RefCounted { Vec3 _lastWorldBoundCenter{INFINITY, INFINITY, INFINITY}; - Vec4 _shadowBias; + Vec4 _shadowBias{0.F, 0.F, -1.F, -1.F}; Vec4 _lightmapUVParam; // For JS From 44795e465ff034d3b51338f70f7b538f405db2f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 31 Jul 2023 10:54:17 +0800 Subject: [PATCH 080/232] Workflow: fix interface check workflow comment (#15795) --- .../web-interface-check-pr-comment.yml | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/.github/workflows/web-interface-check-pr-comment.yml b/.github/workflows/web-interface-check-pr-comment.yml index ec549062ed7..79816558b63 100644 --- a/.github/workflows/web-interface-check-pr-comment.yml +++ b/.github/workflows/web-interface-check-pr-comment.yml @@ -14,14 +14,29 @@ jobs: if: github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-latest steps: - - name: Download artifacts + - name: 'Get source run informations' + uses: potiuk/get-workflow-origin@v1_1 + id: source_run_info + with: + token: ${{ secrets.GITHUB_TOKEN }} + sourceRunId: ${{ github.event.workflow_run.id }} + + - name: 'Debug' + run: | + Write-Host "Source PR Number: ${{ github.event.workflow_run.pull_requests[0].number }}" + shell: pwsh + + - name: Download artifacts env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} RUN_ID: ${{ github.event.workflow_run.id }} run: | - gh run download -R "${{ github.repository }}" --name "interface-diff.txt" "$RUN_ID" + gh run download -R "${{ github.repository }}" --name "interface-diff.txt" "$RUN_ID" + - name: Post interface-diff.txt as comment uses: marocchino/sticky-pull-request-comment@v2 with: - path: interface-diff.txt - number: ${{ github.event.workflow_run.pull_requests[0].number }} \ No newline at end of file + path: interface-diff.txt + number: ${{ steps.source_run_info.outputs.pullRequestNumber }} + # The following matters, see: https://github.com/orgs/community/discussions/25220 + # number: ${{ github.event.workflow_run.pull_requests[0].number }} \ No newline at end of file From 75add41002db8be9ea1f9dcf8553a343bf92a43d Mon Sep 17 00:00:00 2001 From: PP Date: Mon, 31 Jul 2023 11:33:59 +0800 Subject: [PATCH 081/232] fix: asm.js subpackage without spine module (#15822) # Conflicts: # pal/wasm/wasm-minigame.ts --- pal/wasm/wasm-minigame.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pal/wasm/wasm-minigame.ts b/pal/wasm/wasm-minigame.ts index a7527f15235..cd5e2c88f06 100644 --- a/pal/wasm/wasm-minigame.ts +++ b/pal/wasm/wasm-minigame.ts @@ -26,6 +26,7 @@ import { HUAWEI, TAOBAO_MINIGAME, WASM_SUBPACKAGE, XIAOMI } from 'internal:const import { minigame } from 'pal/minigame'; import { basename } from '../../cocos/core/utils/path'; import { checkPalIntegrity, withImpl } from '../integrity-check'; +import { log } from '../../cocos/core/platform/debug'; export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { return getPlatformBinaryUrl(wasmUrl).then((url) => WebAssembly.instantiate(url, importObject)); @@ -55,7 +56,8 @@ function loadSubpackage (name: string): Promise { resolve(); }, fail (err) { - reject(err); + log(`Load subpacakge '${name}' failed, maybe we don't need this subpacakge or it's an engine build issue, for detailed: `, err); + resolve(); }, }); } else { From da25afce01596081b9df6cc8af0082e7b68da745 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Mon, 31 Jul 2023 11:34:43 +0800 Subject: [PATCH 082/232] Modify compileType's default value to minigame (#15815) --- templates/taobao-mini-game/mini.project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/taobao-mini-game/mini.project.json b/templates/taobao-mini-game/mini.project.json index c0457aca825..9dd8e2c19d2 100644 --- a/templates/taobao-mini-game/mini.project.json +++ b/templates/taobao-mini-game/mini.project.json @@ -1,7 +1,7 @@ { "miniprogramRoot": "client", "pluginRoot": "widget", - "compileType": "plugin", + "compileType": "minigame", "enableAppxNg": true, "widgetRuntimeVersion": "3.0-vue" } From 715d5d11b943e43e3c3f4c511e78604a1674cb16 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 31 Jul 2023 11:36:12 +0800 Subject: [PATCH 083/232] fixed scene._instantiate on native platforms. (#15771) * fixed scene._instantiate/updateWorldTransform on native platforms. --- cocos/scene-graph/scene.jsb.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos/scene-graph/scene.jsb.ts b/cocos/scene-graph/scene.jsb.ts index 2b94ca35c48..65365bda651 100644 --- a/cocos/scene-graph/scene.jsb.ts +++ b/cocos/scene-graph/scene.jsb.ts @@ -138,5 +138,7 @@ sceneProto._activate = function (active: boolean) { } }; +sceneProto._instantiate = function(): void {}; + // handle meta data, it is generated automatically patch_cc_Scene({Scene, SceneGlobals}); From 45926d262c0125bb801ab674ad3de68122e1ff6d Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Mon, 31 Jul 2023 14:12:30 +0800 Subject: [PATCH 084/232] fix shader lighting flow (#15833) * fix shader lighting flow * code --- editor/assets/chunks/common/math/number.chunk | 7 +++++++ .../data-structures/lighting-result.chunk | 1 + .../lighting-models/lighting-flow/common-flow.chunk | 3 ++- .../chunks/surfaces/data-structures/standard.chunk | 13 +++++++++++++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/editor/assets/chunks/common/math/number.chunk b/editor/assets/chunks/common/math/number.chunk index 843fa2ba750..f4a840be943 100644 --- a/editor/assets/chunks/common/math/number.chunk +++ b/editor/assets/chunks/common/math/number.chunk @@ -52,6 +52,13 @@ float rand(vec2 seeds_zero_to_one) { return fract(sin(dot(seeds_zero_to_one.xy, vec2(12.9898, 78.233))) * 43758.5453); } +// like smoothstep, but it's linear interpolation +float linearstep(float minValue, float maxValue, float value) { return saturate((value - minValue) / (maxValue - minValue)); } +vec2 linearstep(vec2 minValue, vec2 maxValue, vec2 value) { return saturate((value - minValue) / (maxValue - minValue)); } +vec3 linearstep(vec3 minValue, vec3 maxValue, vec3 value) { return saturate((value - minValue) / (maxValue - minValue)); } +vec4 linearstep(vec4 minValue, vec4 maxValue, vec4 value) { return saturate((value - minValue) / (maxValue - minValue)); } + + #if __VERSION__ <= 100 mat4 transpose(mat4 v) { mat4 tmp; diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk index d6310b378a2..fd148768dde 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk @@ -44,4 +44,5 @@ struct LightingResultPerLayer vec3 diffuseColorWithLighting, specularColorWithLighting; vec3 directDiffuse, directSpecular, directGF; vec3 environmentDiffuse, environmentSpecular, environmentGF; + vec3 directSubLayerF, environmentSubLayerF; }*/ diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index ad2dc2efcae..4bce62ff3eb 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -19,7 +19,8 @@ vec3 diff; SurfacesMaterialData surfaceData2ndSpecular; CCSurfacesGetSurfacesMaterialData2ndSpecular(surfaceData2ndSpecular, surfaceData); - CCSurfacesLightingInitializeColorWithLighting(diff, lightingResultAccumulated.specularColorWithLighting2ndSpecular, surfaceData2ndSpecular, lightingData); + CCSurfacesLightingInitializeColorWithLighting(diff, lightingResult.specularColorWithLighting2ndSpecular, surfaceData2ndSpecular, lightingData); + lightingResultAccumulated.specularColorWithLighting2ndSpecular = lightingResult.specularColorWithLighting2ndSpecular; #endif int numLights = CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD ? LIGHTS_PER_PASS : int(cc_lightDir[0].w); diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk b/editor/assets/chunks/surfaces/data-structures/standard.chunk index fd8f052538a..a45f0309095 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk @@ -44,3 +44,16 @@ struct SurfacesMaterialData vec4 sssParams; #endif }; + +/* +struct SurfacesMaterialDataPerLayer +{ + vec3 baseColor, layerColoration; + float intensity, roughness, metallic; + vec3 worldNormal, worldTangent, worldBinormal; + #if CC_SURFACES_LIGHTING_ANISOTROPIC + float anisotropyShape; + #endif + float ior, opacity; +} +*/ \ No newline at end of file From d73096a1c5d5e19513a69e830aa300268fed1ea1 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Mon, 31 Jul 2023 14:13:03 +0800 Subject: [PATCH 085/232] Fix the problem of noise when playing web audio for more than 5 minutes. (#15807) * Fix the problem of noise when playing web audio for more than 5 minutes. --- pal/audio/minigame/player-web.ts | 3 +++ pal/audio/web/player-web.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/pal/audio/minigame/player-web.ts b/pal/audio/minigame/player-web.ts index 5d972be780c..869da1306cb 100644 --- a/pal/audio/minigame/player-web.ts +++ b/pal/audio/minigame/player-web.ts @@ -81,6 +81,7 @@ export class OneShotAudioWeb { this._bufferSourceNode.onended = null; // stop will call ended callback audioBufferManager.tryReleasingCache(this._url); this._bufferSourceNode.stop(); + this._bufferSourceNode.disconnect(); this._bufferSourceNode.buffer = null; } } @@ -278,7 +279,9 @@ export class AudioPlayerWeb implements OperationQueueable { if (this._sourceNode) { this._sourceNode.onended = null; // stop will call ended callback this._sourceNode.stop(); + this._sourceNode.disconnect(); this._sourceNode.buffer = null; + this._sourceNode = undefined; } } catch (e) { // sourceNode can't be stopped twice, especially on Safari. diff --git a/pal/audio/web/player-web.ts b/pal/audio/web/player-web.ts index 7b7a0bc1d5f..5d703d35d63 100644 --- a/pal/audio/web/player-web.ts +++ b/pal/audio/web/player-web.ts @@ -206,6 +206,7 @@ export class OneShotAudioWeb { clearTimeout(this._currentTimer); audioBufferManager.tryReleasingCache(this._url); this._bufferSourceNode.stop(); + this._bufferSourceNode.disconnect(); this._bufferSourceNode.buffer = null; } } @@ -438,7 +439,9 @@ export class AudioPlayerWeb implements OperationQueueable { try { if (this._sourceNode) { this._sourceNode.stop(); + this._sourceNode.disconnect(); this._sourceNode.buffer = null; + this._sourceNode = undefined; } } catch (e) { // sourceNode can't be stopped twice, especially on Safari. From 74872602b9df40d08540a44ab1bf02400ccc62fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 31 Jul 2023 14:19:28 +0800 Subject: [PATCH 086/232] Eslint: fix indent rule for decorators (#15735) --- .eslintrc.yaml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 6b0db3f8be9..839c15e7fa4 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -70,7 +70,14 @@ rules: import/extensions: off # typescript doesn't support this import/no-unresolved: off # TODO: fix internal modules import/prefer-default-export: off # prefer named exports - indent: off # use @typescript-eslint/indent instead for better compatibility + indent: [error, 4, { + SwitchCase: 0, + ignoredNodes: [ # https://stackoverflow.com/a/72897089 + "FunctionExpression > .params[decorators.length > 0]", + "FunctionExpression > .params > :matches(Decorator, :not(:first-child))", + "ClassBody.body > PropertyDefinition[decorators.length > 0] > .key", + ] + }] lines-between-class-members: off # be more lenient on member declarations max-classes-per-file: off # helper classes are common @@ -103,9 +110,6 @@ rules: 'ts-nocheck': true, 'ts-check': false, }] - '@typescript-eslint/indent': [warn, 4, { - SwitchCase: 0 - }] '@typescript-eslint/no-unused-expressions': warn # TODO: this is just too much work From 762fd501c7cf991f8a24c25eb4c1273431ae6851 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 31 Jul 2023 14:20:52 +0800 Subject: [PATCH 087/232] Eslint: off default-case-last (#15733) --- .eslintrc.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 839c15e7fa4..09f5032bf31 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -101,6 +101,7 @@ rules: prefer-destructuring: off # auto-fix is not smart enough to merge different instances linebreak-style: off # we don't enforce this on everyone's dev environment for now spaced-comment: off # for license declarations + default-case-last: off # Place default case clause to first make it more clear that this switch statement has handled all cases ##### TYPESCRIPT-SPECIFIC RULE OVERRIDES ##### From 95cd245055658c14df3e36a2570aeb60883d6dfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 31 Jul 2023 14:21:36 +0800 Subject: [PATCH 088/232] ESLint: replace no-empty-function with typescript version (#15732) --- .eslintrc.yaml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 09f5032bf31..397a8ee08d4 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -61,6 +61,7 @@ rules: quotes: [warn, single, { allowTemplateLiterals: true }] # force single, but allow template literal no-else-return: off # else-return is a common pattern which clearly expresses the control flow no-unused-expressions: off # taken over by '@typescript-eslint/no-unused-expressions' + no-empty-function: off # taken over by '@typescript-eslint/no-empty-function' ##### AIRBNB-SPECIFIC RULE OVERRIDES ##### @@ -126,7 +127,16 @@ rules: '@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-empty-function': [error, { + allow: [ + private-constructors, + protected-constructors, + decoratedFunctions, + overrideMethods, + ] + }] + '@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 From 54c81416ec928d8fd6607f0ca22312a83af1e087 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Mon, 31 Jul 2023 14:42:25 +0800 Subject: [PATCH 089/232] refactor : call safeMeasureText when needed (#15754) --- cocos/2d/utils/font-loader.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/utils/font-loader.ts b/cocos/2d/utils/font-loader.ts index 5ede5e34ca5..a4940d8a903 100644 --- a/cocos/2d/utils/font-loader.ts +++ b/cocos/2d/utils/font-loader.ts @@ -167,7 +167,6 @@ export function loadFont (url: string, options: Record, onComplete: // Default width reference to test whether new font is loaded correctly const fontDesc = `40px ${fontFamilyName}`; - const refWidth = safeMeasureText(_canvasContext!, _testString, fontDesc); // Setup font face style const fontStyle = ccdocument.createElement('style'); @@ -195,6 +194,7 @@ export function loadFont (url: string, options: Record, onComplete: if (useNativeCheck()) { nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete); } else { + const refWidth = safeMeasureText(_canvasContext!, _testString, fontDesc); // Save loading font const fontLoadHandle = { fontFamilyName, From 4a2f290516dca33675bb3219fe2133238e0fbbed Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Tue, 1 Aug 2023 11:34:40 +0800 Subject: [PATCH 090/232] Fix audio can not be paused & resume on mini game platform (#15811) * Fix audio can not be paused & resume on mini game platform --- pal/audio/minigame/player-minigame.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index 88e03a50be9..a5cc67e40e6 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -30,7 +30,6 @@ import { AudioEvent, AudioPCMDataView, AudioState, AudioType } from '../type'; import { clamp, clamp01 } from '../../../cocos/core'; import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue'; import { OS } from '../../system-info/enum-type'; -import { Game, game } from '../../../cocos/game'; export class OneShotAudioMinigame { private _innerAudioContext: InnerAudioContext; @@ -58,6 +57,8 @@ export class OneShotAudioMinigame { }); const endCallback = (): void => { if (this._innerAudioContext) { + systemInfo.off('hide', this._onInterruptedBegin, this); + systemInfo.off('show', this._onInterruptedEnd, this); this._onEndCb?.(); nativeAudio.destroy(); // NOTE: Type 'null' is not assignable to type 'InnerAudioContext'. @@ -66,6 +67,18 @@ export class OneShotAudioMinigame { }; nativeAudio.onEnded(endCallback); nativeAudio.onStop(endCallback);//OneShotAudio can not be reused. + + // event + systemInfo.on('hide', this._onInterruptedBegin, this); + systemInfo.on('show', this._onInterruptedEnd, this); + } + + private _onInterruptedBegin (): void { + this._innerAudioContext.pause(); + } + + private _onInterruptedEnd (): void { + this._innerAudioContext.play(); } public play (): void { @@ -109,8 +122,8 @@ export class AudioPlayerMinigame implements OperationQueueable { this._eventTarget = new EventTarget(); // event - game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); + systemInfo.on('hide', this._onInterruptedBegin, this); + systemInfo.on('show', this._onInterruptedEnd, this); const eventTarget = this._eventTarget; this._onPlay = (): void => { this._state = AudioState.PLAYING; @@ -171,8 +184,8 @@ export class AudioPlayerMinigame implements OperationQueueable { innerAudioContext.onEnded(this._onEnded); } destroy (): void { - game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); + systemInfo.off('hide', this._onInterruptedBegin, this); + systemInfo.off('show', this._onInterruptedEnd, this); if (this._innerAudioContext) { ['Play', 'Pause', 'Stop', 'Seeked', 'Ended'].forEach((event) => { this._offEvent(event); @@ -196,7 +209,7 @@ export class AudioPlayerMinigame implements OperationQueueable { private _onInterruptedEnd (): void { // We don't know whether onShow or resolve callback in pause promise is called at first. if (!this._readyToHandleOnShow) { - this._eventTarget.once(AudioEvent.INTERRUPTION_BEGIN, this._onInterruptedEnd, this); + this._eventTarget.once(AudioEvent.INTERRUPTION_END, this._onInterruptedEnd, this); return; } if (this._state === AudioState.INTERRUPTED) { From 22388ba7019b3b95b33c1d26f1acaf7f1c08cdc2 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Tue, 1 Aug 2023 14:24:27 +0800 Subject: [PATCH 091/232] The Taobao platform has improved the implementation of innerAudioContext. (#15839) --- pal/audio/minigame/player-minigame.ts | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index a5cc67e40e6..e363567f403 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -151,9 +151,14 @@ export class AudioPlayerMinigame implements OperationQueueable { // Reset all properties this._resetSeekCache(); eventTarget.emit(AudioEvent.STOPPED); - const currentTime = this._innerAudioContext ? this._innerAudioContext.currentTime : 0; - if (currentTime !== 0) { - this._innerAudioContext.seek(0); + if (TAOBAO || TAOBAO_MINIGAME) { + /**Unable to seek again after stop; After stop, regardless of whether the starttime has been set, + the playback will always start from 0 again**/ + } else { + const currentTime = this._innerAudioContext ? this._innerAudioContext.currentTime : 0; + if (currentTime !== 0) { + this._innerAudioContext.seek(0); + } } }; innerAudioContext.onStop(this._onStop); @@ -168,12 +173,6 @@ export class AudioPlayerMinigame implements OperationQueueable { this._needSeek = false; } } - - // TaoBao iOS: After calling pause or stop, when seek is called, it will automatically play and call onPlay. - if ((TAOBAO || TAOBAO_MINIGAME) && systemInfo.os === OS.IOS - && (this._state === AudioState.PAUSED || this._state === AudioState.STOPPED)) { - innerAudioContext.pause(); - } }; innerAudioContext.onSeeked(this._onSeeked); this._onEnded = (): void => { @@ -350,14 +349,6 @@ export class AudioPlayerMinigame implements OperationQueueable { @enqueueOperation stop (): Promise { - // NOTE: on Taobao, it is designed that innerAudioContext is useless after calling stop. - // so we implement stop as pase + seek. - if (TAOBAO || TAOBAO_MINIGAME) { - this._innerAudioContext.pause(); - this._innerAudioContext.seek(0); - this._onStop?.(); - return Promise.resolve(); - } return new Promise((resolve) => { this._eventTarget.once(AudioEvent.STOPPED, resolve); this._innerAudioContext.stop(); From 5eddce91f13526e43496d8ad97cd363b1cc22419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Tue, 1 Aug 2023 14:50:45 +0800 Subject: [PATCH 092/232] PoseGraph: support editor decorators on node inputs (#15819) * PoseGraph: support editor decorators on node inputs * Fix lint error --- .../marionette/pose-graph/decorator/input.ts | 25 ++++++++++++++++--- .../pose-graph/graph-output-node.ts | 7 ++---- .../pose-graph/pose-nodes/additively-blend.ts | 3 ++- .../pose-graph/pose-nodes/apply-transform.ts | 7 +++--- .../pose-nodes/blend-in-proportion.ts | 3 ++- .../pose-nodes/blend-two-pose-base.ts | 3 ++- .../pose-nodes/ik/two-bone-ik-solver.ts | 8 +++--- .../pose-nodes/intensity-specification.ts | 3 ++- .../pose-graph/pose-nodes/play-motion.ts | 5 ++-- .../src/marionette/pose-graph-editor-api.ts | 12 +++++++++ .../pose-graph/pose-graph-authoring.test.ts | 17 +++++++++++++ 11 files changed, 72 insertions(+), 21 deletions(-) diff --git a/cocos/animation/marionette/pose-graph/decorator/input.ts b/cocos/animation/marionette/pose-graph/decorator/input.ts index 38e2f2135af..2c223606ccb 100644 --- a/cocos/animation/marionette/pose-graph/decorator/input.ts +++ b/cocos/animation/marionette/pose-graph/decorator/input.ts @@ -1,6 +1,8 @@ /* eslint-disable @typescript-eslint/ban-types */ import { error, js } from '../../../../core'; +import { PropertyStashInternalFlag } from '../../../../core/data/class-stash'; +import { getOrCreatePropertyStash } from '../../../../core/data/decorators/property'; import { PoseGraphNodeInputMappingOptions, globalPoseGraphNodeInputManager } from '../foundation/authoring/input-authoring'; import { PoseGraphType } from '../foundation/type-system'; import { PoseNode } from '../pose-node'; @@ -38,10 +40,6 @@ export type { PoseGraphNodeInputMappingOptions }; */ export function input (options: PoseGraphNodeInputMappingOptions): PropertyDecorator { return (target, propertyKey): void => { - if (typeof propertyKey !== 'string') { - error(`@input can be only applied to string-named fields.`); - return; - } const targetConstructor = target.constructor; if (options.type === PoseGraphType.POSE) { if (!js.isChildClassOf(targetConstructor, PoseNode)) { @@ -55,6 +53,25 @@ export function input (options: PoseGraphNodeInputMappingOptions): PropertyDecor error(`@input can be only applied to fields of subclasses of PoseNode or PureValueNode.`); return; } + inputUnchecked(options)(target, propertyKey); + }; +} + +/** + * Unchecked version of `@input()`. + * @internal + */ +export function inputUnchecked (options: PoseGraphNodeInputMappingOptions): PropertyDecorator { + return (target, propertyKey) => { + if (typeof propertyKey !== 'string') { + error(`@input can be only applied to string-named fields.`); + return; + } + + const targetConstructor = target.constructor; globalPoseGraphNodeInputManager.setPropertyNodeInputRecord(targetConstructor, propertyKey, options); + + const propertyStash = getOrCreatePropertyStash(target, propertyKey); + propertyStash.__internalFlags |= (PropertyStashInternalFlag.STANDALONE | PropertyStashInternalFlag.IMPLICIT_VISIBLE); }; } diff --git a/cocos/animation/marionette/pose-graph/graph-output-node.ts b/cocos/animation/marionette/pose-graph/graph-output-node.ts index 6c8711eca18..422f14103a2 100644 --- a/cocos/animation/marionette/pose-graph/graph-output-node.ts +++ b/cocos/animation/marionette/pose-graph/graph-output-node.ts @@ -4,8 +4,8 @@ import { CLASS_NAME_PREFIX_ANIM } from '../../define'; import { PoseNode } from './pose-node'; import { PoseGraphType } from './foundation/type-system'; import { PoseGraphNode } from './foundation/pose-graph-node'; -import { globalPoseGraphNodeInputManager } from './foundation/authoring/input-authoring'; import { poseGraphNodeAppearance } from './decorator/node'; +import { inputUnchecked } from './decorator/input'; @ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseGraphOutputNode`) @poseGraphNodeAppearance({ @@ -15,9 +15,6 @@ import { poseGraphNodeAppearance } from './decorator/node'; export class PoseGraphOutputNode extends PoseGraphNode { // Don't use @input since it requires the owner class being subclass of `PoseNode`. @serializable + @inputUnchecked({ type: PoseGraphType.POSE }) pose: PoseNode | null = null; } - -globalPoseGraphNodeInputManager.setPropertyNodeInputRecord(PoseGraphOutputNode, 'pose', { - type: PoseGraphType.POSE, -}); diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts b/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts index 77cffebd07f..81c9d200c47 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/additively-blend.ts @@ -1,4 +1,4 @@ -import { ccclass, serializable } from '../../../../core/data/decorators'; +import { ccclass, range, serializable } from '../../../../core/data/decorators'; import { Pose, applyDeltaPose } from '../../../core/pose'; import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; import { poseGraphNodeAppearance, poseGraphNodeCategory } from '../decorator/node'; @@ -29,6 +29,7 @@ export class PoseNodeAdditivelyBlend extends PoseNode { @serializable @input({ type: PoseGraphType.FLOAT }) + @range([0.0, 1.0, 0.01]) public ratio = 1.0; public bind (context: AnimationGraphBindingContext): void { diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts b/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts index 2909c1f2bcc..fb3e2eb4e45 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/apply-transform.ts @@ -1,5 +1,5 @@ import { EDITOR } from 'internal:constants'; -import { ccclass, editable, serializable, type, visible } from '../../../../core/data/decorators'; +import { ccclass, editable, range, serializable, type, visible } from '../../../../core/data/decorators'; import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; import { PoseNode, PoseTransformSpaceRequirement } from '../pose-node'; import { @@ -47,7 +47,7 @@ export class PoseNodeApplyTransform extends PoseNodeModifyPoseBase { @serializable @editable @input({ type: PoseGraphType.VEC3 }) - @visible(function visible(this: PoseNodeApplyTransform) { return this.positionOperation !== TransformOperation.LEAVE_UNCHANGED; }) + @visible(function visible (this: PoseNodeApplyTransform) { return this.positionOperation !== TransformOperation.LEAVE_UNCHANGED; }) public position = new Vec3(); @serializable @@ -58,11 +58,12 @@ export class PoseNodeApplyTransform extends PoseNodeModifyPoseBase { @serializable @editable @input({ type: PoseGraphType.QUAT }) - @visible(function visible(this: PoseNodeApplyTransform) { return this.rotationOperation !== TransformOperation.LEAVE_UNCHANGED; }) + @visible(function visible (this: PoseNodeApplyTransform) { return this.rotationOperation !== TransformOperation.LEAVE_UNCHANGED; }) public rotation = new Quat(); @serializable @editable + @range([0.0, 1.0, 0.01]) public intensity = new IntensitySpecification(); @serializable diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts b/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts index ed84d2a146e..e7f2d732048 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/blend-in-proportion.ts @@ -1,5 +1,5 @@ import { EDITOR } from 'internal:constants'; -import { ccclass, serializable } from '../../../../core/data/decorators'; +import { ccclass, range, serializable } from '../../../../core/data/decorators'; import { blendPoseInto, Pose } from '../../../core/pose'; import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; import { PoseNode, PoseTransformSpaceRequirement } from '../pose-node'; @@ -29,6 +29,7 @@ export class PoseNodeBlendInProportion extends PoseNode { arraySyncGroup: 'blend-item', arraySyncGroupFollower: true, }) + @range([0.0, Number.POSITIVE_INFINITY]) public readonly proportions: number[] = []; public bind (context: AnimationGraphBindingContext): void { diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts b/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts index e87ce7e4b8e..dc8e30b1cfd 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/blend-two-pose-base.ts @@ -1,4 +1,4 @@ -import { ccclass, editable, serializable, type } from '../../../../core/data/decorators'; +import { ccclass, editable, range, serializable, type } from '../../../../core/data/decorators'; import { Pose } from '../../../core/pose'; import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; import { PoseNode, PoseTransformSpaceRequirement } from '../pose-node'; @@ -22,6 +22,7 @@ export abstract class PoseNodeBlendTwoPoseBase extends PoseNode { @serializable @input({ type: PoseGraphType.FLOAT }) + @range([0.0, 1.0, 0.01]) ratio = 1.0; public bind (context: AnimationGraphBindingContext): void { diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts b/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts index 5e92050e114..fa0006bb10a 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/ik/two-bone-ik-solver.ts @@ -56,18 +56,18 @@ class TargetSpecification { @serializable @editable - @visible(function visible(this: TargetSpecification) { return this.type === TargetSpecificationType.VALUE; }) + @visible(function visible (this: TargetSpecification) { return this.type === TargetSpecificationType.VALUE; }) public targetPosition = new Vec3(); @serializable @editable @type(TransformSpace) - @visible(function visible(this: TargetSpecification) { return this.type === TargetSpecificationType.VALUE; }) + @visible(function visible (this: TargetSpecification) { return this.type === TargetSpecificationType.VALUE; }) public targetPositionSpace = TransformSpace.WORLD; @serializable @editable - @visible(function visible(this: TargetSpecification) { return this.type === TargetSpecificationType.BONE; }) + @visible(function visible (this: TargetSpecification) { return this.type === TargetSpecificationType.BONE; }) public targetBone = ''; public bind (context: AnimationGraphBindingContext, sourceBoneHandle: TransformHandle): void { @@ -117,6 +117,7 @@ export class PoseNodeTwoBoneIKSolver extends PoseNodeModifyPoseBase { public readonly endEffectorTarget = new TargetSpecification(TargetSpecificationType.VALUE); @input({ type: PoseGraphType.VEC3 }) + @visible(function visible (this: PoseNodeTwoBoneIKSolver) { return this.endEffectorTarget.type === TargetSpecificationType.VALUE; }) get endEffectorTargetPosition (): Vec3 { return this.endEffectorTarget.targetPosition; } @@ -130,6 +131,7 @@ export class PoseNodeTwoBoneIKSolver extends PoseNodeModifyPoseBase { public readonly poleTarget = new TargetSpecification(TargetSpecificationType.NONE); @input({ type: PoseGraphType.VEC3 }) + @visible(function visible (this: PoseNodeTwoBoneIKSolver) { return this.poleTarget.type === TargetSpecificationType.VALUE; }) get poleTargetPosition (): Vec3 { return this.poleTarget.targetPosition; } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts b/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts index 36a779ba580..85922a169b4 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/intensity-specification.ts @@ -1,5 +1,5 @@ import { ccenum } from '../../../../core'; -import { ccclass, editable, serializable, type, visible } from '../../../../core/data/decorators'; +import { ccclass, editable, range, serializable, type, visible } from '../../../../core/data/decorators'; import { AuxiliaryCurveHandle } from '../../../core/animation-handle'; import { Pose } from '../../../core/pose'; import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; @@ -22,6 +22,7 @@ export class IntensitySpecification { @serializable @editable @visible(function visible (this: IntensitySpecification): boolean { return this.type === IntensityType.VALUE; }) + @range([0.0, 1.0, 0.01]) public value = 1.0; @serializable diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts b/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts index a93d7606d64..78e8b8b3c5f 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts @@ -1,5 +1,5 @@ import { EDITOR } from 'internal:constants'; -import { ccclass, displayName, editable, serializable } from '../../../../core/data/decorators'; +import { ccclass, displayName, editable, serializable, unit } from '../../../../core/data/decorators'; import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; import { ClipMotion } from '../../motion/clip-motion'; import { createEval } from '../../create-eval'; @@ -43,6 +43,7 @@ export class PoseNodePlayMotion extends PoseNode { @serializable @input({ type: PoseGraphType.FLOAT }) + @unit('s') public startTime = 0.0; @serializable @@ -79,7 +80,7 @@ export class PoseNodePlayMotion extends PoseNode { } public settle (context: AnimationGraphSettleContext): void { - + // override } public reenter (): void { diff --git a/editor/src/marionette/pose-graph-editor-api.ts b/editor/src/marionette/pose-graph-editor-api.ts index 8cfc4354570..cbd1cb20487 100644 --- a/editor/src/marionette/pose-graph-editor-api.ts +++ b/editor/src/marionette/pose-graph-editor-api.ts @@ -13,6 +13,7 @@ import { PoseGraphStash, StateMachine } from "../../../cocos/animation/marionett import { PoseNodeLocation, visitPoseNodeInLayer } from "./visit/visit-pose-node"; import { PoseGraph } from '../../../cocos/animation/marionette/pose-graph/pose-graph'; import { PoseNodeStateMachine } from "../../../cocos/animation/marionette/pose-graph/pose-nodes/state-machine"; +import { attr } from "../../../cocos/core/data/utils/attribute"; type Constructor = new (...args: any[]) => T; @@ -92,6 +93,17 @@ export function getInputDefaultDisplayName(inputKey: poseGraphOp.InputKey) { } } +export function getPoseGraphNodeInputAttrs(node: PoseGraphNode, inputKey: poseGraphOp.InputKey) { + const [propertyName] = inputKey; + const attrs = attr(node.constructor, propertyName); + delete attrs.type; + delete attrs.ctor; + if (Array.isArray(node[propertyName])) { + delete attrs['default']; + } + return attrs; +} + function clonePoseGraphNode(node: PoseGraphNode) { return instantiate(node); } diff --git a/tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts b/tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts index 1400fcce30d..ce29bd5dbb8 100644 --- a/tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts +++ b/tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts @@ -13,6 +13,9 @@ import { poseGraphCreateNodeFactory, poseGraphNodeAppearance, poseGraphNodeHide, import { PoseGraphNodeEditorMetadata, getPoseGraphNodeEditorMetadata } from "../../../../cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring"; import { composeInputKeyInternally, createPoseGraph, getTheOnlyInputKey, getTheOnlyOutputKey, normalizeNodeInputMetadata, UnimplementedPoseNode, UnimplementedPVNode } from "./utils/misc"; import { PoseNode } from "../../../../cocos/animation/marionette/pose-graph/pose-node"; +import { ccclass } from "../../../../cocos/core/data/class-decorator"; +import { unregisterClass } from "../../../../cocos/core/utils/js-typed"; +import { attr } from "../../../../cocos/core/data/utils/attribute"; describe(`Class PoseGraph`, () => { test(`Default`, () => { @@ -162,6 +165,20 @@ describe(`Input decorator @input`, () => { return _Node; } }); + + test(`@input implies default visibility`, () => { + @ccclass('C') + class Node extends UnimplementedPoseNode { + @input({ type: PoseGraphType.FLOAT }) + p = 0.0; + } + + expect(attr(Node, 'p')).toStrictEqual(expect.objectContaining({ + visible: true, + })); + + unregisterClass(Node); + }); }); describe(`Node editor decorators`, () => { From 06341f3037ce74068f6612d1dc5b578a5ab4ec9c Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Wed, 2 Aug 2023 14:20:24 +0800 Subject: [PATCH 093/232] Uncapture global mouse events. (#15834) --- native/cocos/platform/SDLHelper.cpp | 4 ---- native/external-config.json | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/native/cocos/platform/SDLHelper.cpp b/native/cocos/platform/SDLHelper.cpp index b588395f33d..56e71618b8c 100644 --- a/native/cocos/platform/SDLHelper.cpp +++ b/native/cocos/platform/SDLHelper.cpp @@ -198,10 +198,6 @@ void SDLHelper::dispatchWindowEvent(uint32_t windowId, const SDL_WindowEvent &we events::WindowEvent::broadcast(ev); break; } - case SDL_WINDOWEVENT_ENTER: { - SDL_CaptureMouse(SDL_TRUE); - break; - } case SDL_WINDOWEVENT_CLOSE: { ev.type = WindowEvent::Type::CLOSE; events::WindowEvent::broadcast(ev); diff --git a/native/external-config.json b/native/external-config.json index 082f542393f..5427b2b8bfa 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-8" + "checkout": "v3.8.1-9" } } From 326ba66a9a4334cd4d592fd974c55b5790219159 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Wed, 2 Aug 2023 14:34:50 +0800 Subject: [PATCH 094/232] implement some wechat splashScreen features (#15827) * implement some wechat splashScreen features * fix unit-test may not get logo&background condition * fix eslint --- cocos/game/splash-screen.ts | 299 ++++++++++++++++---------- templates/wechatgame/first-screen.ejs | 61 ++++-- 2 files changed, 227 insertions(+), 133 deletions(-) diff --git a/cocos/game/splash-screen.ts b/cocos/game/splash-screen.ts index fb85f3f1c59..87ee4f71ff3 100644 --- a/cocos/game/splash-screen.ts +++ b/cocos/game/splash-screen.ts @@ -28,7 +28,7 @@ import { clamp01, Mat4, Vec2, Settings, settings, sys, cclegacy, easing, preTran import { Sampler, SamplerInfo, Shader, Texture, TextureInfo, Device, InputAssembler, InputAssemblerInfo, Attribute, Buffer, BufferInfo, Rect, Color, BufferTextureCopy, CommandBuffer, BufferUsageBit, Format, - MemoryUsageBit, TextureType, TextureUsageBit, Address, Swapchain, + MemoryUsageBit, TextureType, TextureUsageBit, Address, Swapchain, Framebuffer, } from '../gfx'; import { PipelineStateManager } from '../rendering'; import { SetIndex } from '../rendering/define'; @@ -36,7 +36,8 @@ import { ccwindow, legacyCC } from '../core/global-exports'; import { XREye } from '../xr/xr-enums'; const v2_0 = new Vec2(); -type SplashEffectType = 'default' | 'custom' | 'off'; +type SplashLogoType = 'default' | 'none' | 'custom'; +type SplashBackgroundType = 'default' | 'color' | 'custom'; type WatermarkLocationType = 'default' | 'topLeft' | 'topRight' | 'topCenter' | 'bottomLeft' | 'bottomCenter' | 'bottomRight'; interface ISplashSetting { @@ -44,12 +45,21 @@ interface ISplashSetting { totalTime: number; watermarkLocation: WatermarkLocationType; autoFit: boolean; + logo?: SplashLogo; + background?: SplashBackground; +} - url?: string; - type?: SplashEffectType; +interface SplashBackground { + type: SplashBackgroundType; + color?: Color; + image?: string; + base64?: string; +} - bgBase64: string; - base64src: string; +interface SplashLogo { + type: SplashLogoType; + image?: string; + base64?: string; } export class SplashScreen { @@ -117,14 +127,12 @@ export class SplashScreen { totalTime: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'totalTime') ?? 3000, watermarkLocation: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'watermarkLocation') ?? 'default', autoFit: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'autoFit') ?? true, - url: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'url') ?? '', - type: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'type') ?? 'default', - bgBase64: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'bgBase64') ?? '', - base64src: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'base64src') ?? '', + logo: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'logo') ?? undefined, + background: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'background') ?? undefined, }; this._curTime = 0; - if (EDITOR || this.settings.base64src === '' || this.settings.totalTime <= 0) { + if (EDITOR || this.settings.totalTime <= 0 || this.settings.logo === undefined || this.settings.background === undefined) { this.settings.totalTime = 0; } else { this.device = cclegacy.director.root!.device; @@ -133,36 +141,45 @@ export class SplashScreen { this.preInit(); this.initLayout(); - this.initWaterMark(); - const bgPromise = new Promise((resolve, reject): void => { - this.bgImage = new ccwindow.Image(); - this.bgImage.onload = (): void => { - this.initBG(); - resolve(); - }; - this.bgImage.onerror = (): void => { - reject(); - }; - this.bgImage.src = this.settings.bgBase64; - }); - const logoPromise = new Promise((resolve, reject): void => { - this.logoImage = new ccwindow.Image(); - this.logoImage.onload = (): void => { - this.initLogo(); - resolve(); - }; - this.logoImage.onerror = (): void => { - reject(); - }; - this.logoImage.src = this.settings.base64src; - }); + if (this.settings.logo.type === 'default') { + this.initWaterMark(); + } + let bgPromise = Promise.resolve(); + let logoPromise = Promise.resolve(); + if (this.settings.background.type === 'custom') { + bgPromise = new Promise((resolve, reject): void => { + this.bgImage = new ccwindow.Image(); + this.bgImage.onload = (): void => { + this.initBG(); + resolve(); + }; + this.bgImage.onerror = (): void => { + reject(); + }; + this.bgImage.src = this.settings.background!.base64!; + }); + } + if (this.settings.logo.type !== 'none') { + logoPromise = new Promise((resolve, reject): void => { + this.logoImage = new ccwindow.Image(); + this.logoImage.onload = (): void => { + this.initLogo(); + resolve(); + }; + this.logoImage.onerror = (): void => { + reject(); + }; + this.logoImage.src = this.settings.logo!.base64!; + }); + } return Promise.all([bgPromise, logoPromise]); } return Promise.resolve([]); } private preInit (): void { - this.clearColors = [new Color(0, 0, 0, 255)]; // clean to black + const clearColor = this.settings.background?.color; + this.clearColors = clearColor ? [new Color(clearColor.x, clearColor.y, clearColor.z, clearColor.w)] : [new Color(0, 0, 0, 1)]; const { device, swapchain } = this; this.renderArea = new Rect(0, 0, swapchain.width, swapchain.height); this.cmdBuff = device.commandBuffer; @@ -174,7 +191,9 @@ export class SplashScreen { const vbSize = vbStride * 4; this.vertexBuffers = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, vbSize, vbStride, + MemoryUsageBit.DEVICE, + vbSize, + vbStride, )); this.vertexBuffers.update(verts); @@ -184,7 +203,9 @@ export class SplashScreen { const ibSize = ibStride * 6; this.indicesBuffers = device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, ibSize, ibStride, + MemoryUsageBit.DEVICE, + ibSize, + ibStride, )); this.indicesBuffers.update(indices); @@ -196,8 +217,18 @@ export class SplashScreen { this.quadAssmebler = device.createInputAssembler(IAInfo); this.projection = new Mat4(); - Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, - device.capabilities.clipSpaceSignY, swapchain.surfaceTransform); + Mat4.ortho( + this.projection, + -1, + 1, + -1, + 1, + -1, + 1, + device.capabilities.clipSpaceMinZ, + device.capabilities.clipSpaceSignY, + swapchain.surfaceTransform, + ); this.isMobile = sys.isMobile; } @@ -250,8 +281,18 @@ export class SplashScreen { public update (deltaTime: number): void { const settings = this.settings; const { device, swapchain } = this; - Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, - device.capabilities.clipSpaceSignY, swapchain.surfaceTransform); + Mat4.ortho( + this.projection, + -1, + 1, + -1, + 1, + -1, + 1, + device.capabilities.clipSpaceMinZ, + device.capabilities.clipSpaceSignY, + swapchain.surfaceTransform, + ); const dw = swapchain.width; const dh = swapchain.height; this.initScale(); @@ -259,40 +300,41 @@ export class SplashScreen { const percent = clamp01(this._curTime / settings.totalTime); const u_p = easing.cubicOut(percent); - // update bg uniform let scaleX = 1; let scaleY = 1; - if (dw < dh) { - scaleX = dh * this.bgRatio; - scaleY = dh; - } else { - scaleX = dw; - scaleY = dw * this.bgRatio; - } - - this.bgMat.setProperty('resolution', v2_0.set(dw, dh), 0); - this.bgMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); - this.bgMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0); - this.bgMat.setProperty('percent', 1.0); - this.bgMat.setProperty('u_projection', this.projection); - this.bgMat.passes[0].update(); + // update bg uniform + if (this.settings.background!.type === 'custom') { + if (dw < dh) { + scaleX = dh * this.bgRatio; + scaleY = dh; + } else { + scaleX = dw; + scaleY = dw * this.bgRatio; + } + this.bgMat.setProperty('resolution', v2_0.set(dw, dh), 0); + this.bgMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); + this.bgMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0); + this.bgMat.setProperty('percent', 1.0); + this.bgMat.setProperty('u_projection', this.projection); + this.bgMat.passes[0].update(); + } // update logo uniform - scaleX = 1; - scaleY = 1; - scaleX = this.logoWidth * this.scaleSize * settings.displayRatio; - scaleY = this.logoHeight * this.scaleSize * settings.displayRatio; const logoYTrans = dh * this.logoYTrans; - - this.logoMat.setProperty('resolution', v2_0.set(dw, dh), 0); - this.logoMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); - this.logoMat.setProperty('translate', v2_0.set(dw * this.logoXTrans, logoYTrans), 0); - this.logoMat.setProperty('percent', u_p); - this.logoMat.setProperty('u_projection', this.projection); - this.logoMat.passes[0].update(); + if (this.settings.logo!.type !== 'none') { + scaleX = this.logoWidth * this.scaleSize * settings.displayRatio; + scaleY = this.logoHeight * this.scaleSize * settings.displayRatio; + + this.logoMat.setProperty('resolution', v2_0.set(dw, dh), 0); + this.logoMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); + this.logoMat.setProperty('translate', v2_0.set(dw * this.logoXTrans, logoYTrans), 0); + this.logoMat.setProperty('percent', u_p); + this.logoMat.setProperty('u_projection', this.projection); + this.logoMat.passes[0].update(); + } // update watermark uniform - if (this.watermarkMat) { + if (this.settings.logo!.type === 'default' && this.watermarkMat) { const watermarkTW = this.watermarkTexture.width; const watermarkTH = this.watermarkTexture.height; scaleX = watermarkTW; scaleY = watermarkTH; @@ -406,8 +448,11 @@ export class SplashScreen { region.texExtent.height = watermarkImg.height; region.texExtent.depth = 1; this.watermarkTexture = this.device.createTexture(new TextureInfo( - TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, - Format.RGBA8, watermarkImg.width, watermarkImg.height, + TextureType.TEX2D, + TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, + Format.RGBA8, + watermarkImg.width, + watermarkImg.height, )); this.device.copyTexImagesToTexture([watermarkImg], this.watermarkTexture, [region]); // create material @@ -431,13 +476,23 @@ export class SplashScreen { // device's fov may be asymmetry let radioLeft = 1.0; let radioRight = 1.0; - if (xrEye === XREye.LEFT) { - radioLeft = Math.abs(Math.tan(xrFov[0])) / Math.abs(Math.tan(xrFov[1])); - } else if (xrEye === XREye.RIGHT) { - radioRight = Math.abs(Math.tan(xrFov[1])) / Math.abs(Math.tan(xrFov[0])); + if (xrEye === XREye.LEFT as number) { + radioLeft = Math.abs(Math.tan(xrFov[0] as number)) / Math.abs(Math.tan(xrFov[1] as number)); + } else if (xrEye === XREye.RIGHT as number) { + radioRight = Math.abs(Math.tan(xrFov[1] as number)) / Math.abs(Math.tan(xrFov[0] as number)); } - Mat4.ortho(this.projection, -radioLeft, radioRight, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, - device.capabilities.clipSpaceSignY, swapchain.surfaceTransform); + Mat4.ortho( + this.projection, + -radioLeft, + radioRight, + -1, + 1, + -1, + 1, + device.capabilities.clipSpaceMinZ, + device.capabilities.clipSpaceSignY, + swapchain.surfaceTransform, + ); // keep scale to [-1, 1] only use offset this.projection.m00 = preTransforms[swapchain.surfaceTransform][0]; this.projection.m05 = preTransforms[swapchain.surfaceTransform][3] * device.capabilities.clipSpaceSignY; @@ -457,7 +512,7 @@ export class SplashScreen { device.acquire([swapchain]); // record command const cmdBuff = this.cmdBuff; - const framebuffer = cclegacy.director.root!.mainWindow!.framebuffer; + const framebuffer = cclegacy.director.root!.mainWindow!.framebuffer as Framebuffer; const renderArea = this.renderArea; renderArea.width = swapchain.width; @@ -466,28 +521,48 @@ export class SplashScreen { cmdBuff.begin(); cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0); - const bgPass = this.bgMat.passes[0]; - const bgPso = PipelineStateManager.getOrCreatePipelineState(device, bgPass, this.shader, framebuffer.renderPass, - this.quadAssmebler); - - cmdBuff.bindPipelineState(bgPso); - cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, bgPass.descriptorSet); - cmdBuff.bindInputAssembler(this.quadAssmebler); - cmdBuff.draw(this.quadAssmebler); - - const logoPass = this.logoMat.passes[0]; - const logoPso = PipelineStateManager.getOrCreatePipelineState(device, logoPass, this.shader, framebuffer.renderPass, - this.quadAssmebler); + if (this.settings.background!.type === 'custom') { + const bgPass = this.bgMat.passes[0]; + const bgPso = PipelineStateManager.getOrCreatePipelineState( + device, + bgPass, + this.shader, + framebuffer.renderPass, + this.quadAssmebler, + ); + + cmdBuff.bindPipelineState(bgPso); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, bgPass.descriptorSet); + cmdBuff.bindInputAssembler(this.quadAssmebler); + cmdBuff.draw(this.quadAssmebler); + } - cmdBuff.bindPipelineState(logoPso); - cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet); - cmdBuff.bindInputAssembler(this.quadAssmebler); - cmdBuff.draw(this.quadAssmebler); + if (this.settings.logo!.type !== 'none') { + const logoPass = this.logoMat.passes[0]; + const logoPso = PipelineStateManager.getOrCreatePipelineState( + device, + logoPass, + this.shader, + framebuffer.renderPass, + this.quadAssmebler, + ); + + cmdBuff.bindPipelineState(logoPso); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet); + cmdBuff.bindInputAssembler(this.quadAssmebler); + cmdBuff.draw(this.quadAssmebler); + } - if (this.watermarkMat) { + if (this.settings.logo!.type === 'default' && this.watermarkMat) { const wartermarkPass = this.watermarkMat.passes[0]; - const watermarkPso = PipelineStateManager.getOrCreatePipelineState(device, - wartermarkPass, this.shader, framebuffer.renderPass, this.quadAssmebler); + const watermarkPso = PipelineStateManager.getOrCreatePipelineState( + device, + wartermarkPass, + this.shader, + framebuffer.renderPass, + this.quadAssmebler, + ); + cmdBuff.bindPipelineState(watermarkPso); cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet); cmdBuff.bindInputAssembler(this.quadAssmebler); @@ -512,21 +587,25 @@ export class SplashScreen { this.device = null!; this.swapchain = null!; this.clearColors = null!; - if ((this.bgImage as any).destroy) (this.bgImage as any).destroy(); - this.bgImage = null!; - this.bgMat.destroy(); - this.bgMat = null!; - this.bgTexture.destroy(); - this.bgTexture = null!; - if ((this.logoImage as any).destroy) (this.logoImage as any).destroy(); - this.logoImage = null!; + if (this.settings.background!.type === 'custom') { + if ((this.bgImage as any).destroy) (this.bgImage as any).destroy(); + this.bgImage = null!; + this.bgMat.destroy(); + this.bgMat = null!; + this.bgTexture.destroy(); + this.bgTexture = null!; + } + if (this.settings.logo!.type !== 'none') { + if ((this.logoImage as any).destroy) (this.logoImage as any).destroy(); + this.logoImage = null!; + this.logoMat.destroy(); + this.logoMat = null!; + this.logoTexture.destroy(); + this.logoTexture = null!; + } this.renderArea = null!; this.cmdBuff = null!; this.shader = null!; - this.logoMat.destroy(); - this.logoMat = null!; - this.logoTexture.destroy(); - this.logoTexture = null!; this.quadAssmebler.destroy(); this.quadAssmebler = null!; this.vertexBuffers.destroy(); @@ -536,7 +615,7 @@ export class SplashScreen { this.sampler = null!; /** text */ - if (this.watermarkTexture) { + if (this.settings.logo!.type === 'default' && this.watermarkTexture) { this.watermarkMat.destroy(); this.watermarkMat = null!; this.watermarkTexture.destroy(); @@ -554,7 +633,7 @@ export class SplashScreen { } return SplashScreen._ins; } - + // eslint-disable-next-line no-empty-function private constructor () {} } diff --git a/templates/wechatgame/first-screen.ejs b/templates/wechatgame/first-screen.ejs index 1e25ee187fe..1025e60e115 100644 --- a/templates/wechatgame/first-screen.ejs +++ b/templates/wechatgame/first-screen.ejs @@ -27,9 +27,14 @@ void main() { const FS_BG = ` precision mediump float; uniform sampler2D u_Sampler; +uniform float u_flip; varying vec2 v_TexCoord; void main() { - gl_FragColor = texture2D(u_Sampler, v_TexCoord); + vec2 texCoord = v_TexCoord; + if(u_flip > 0.5) { + texCoord.y = 1.0 - texCoord.y; + } + gl_FragColor = texture2D(u_Sampler, texCoord); }`; const VS_PROGRESSBAR = ` @@ -82,7 +87,14 @@ let progress = 0.0; let progressBarColor = [61 / 255, 197 / 255, 222 / 255, 1]; let progressBackground = [100 / 255, 111 / 255, 118 / 255, 1]; let afterTick = null; +let backgroundFilp = 1.0; // set 0 to not flip let displayRatio = <%= displayRatio%>; +let bgColor = [<%= bgColor%>]; +let useCustomBg = <%= useCustomBg%>; +let useLogo = <%= useLogo%>; +let useDefaultLogo = <%= useDefaultLogo%>; +let logoName = '<%= logoName %>'; +let bgName = '<%= bgName %>'; function initShaders(vshader, fshader) { return createProgram(vshader, fshader); @@ -333,6 +345,8 @@ function drawTexture(gl, program, texture, vertexBuffer, vertexFormatLength) { gl.bindTexture(gl.TEXTURE_2D, texture); var uSampler = gl.getUniformLocation(program, 'u_Sampler'); gl.uniform1i(uSampler, 0); + var uFlip = gl.getUniformLocation(program, 'u_flip'); + gl.uniform1f(uFlip, backgroundFilp); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); var aPosition = gl.getAttribLocation(program, 'a_Position'); gl.enableVertexAttribArray(aPosition); @@ -363,20 +377,16 @@ function drawProgressBar(gl, program, vertexBuffer, vertexFormatLength, progress } function draw() { - gl.disable(gl.SCISSOR_TEST); - gl.disable(gl.CULL_FACE); - gl.disable(gl.DEPTH_TEST); - gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); - gl.clearColor(0.0, 0.0, 0.0, 0.0); + gl.clearColor(bgColor[0], bgColor[1], bgColor[2], bgColor[3]); gl.clear(gl.COLOR_BUFFER_BIT); // draw background - drawTexture(gl, programBg, bgTexture, bgVertexBuffer, 4); + useCustomBg && drawTexture(gl, programBg, bgTexture, bgVertexBuffer, 4); // draw logo - drawTexture(gl, program, logoTexture, vertexBuffer, 4); + useLogo && drawTexture(gl, program, logoTexture, vertexBuffer, 4); // draw slogan - drawTexture(gl, program, sloganTexture, sloganVertexBuffer, 4); + useLogo && useDefaultLogo && drawTexture(gl, program, sloganTexture, sloganVertexBuffer, 4); // draw progress bar drawProgressBar(gl, programProgress, vertexBufferProgress, 3, progress, progressBarColor, progressBackground); } @@ -398,12 +408,12 @@ function end() { gl.useProgram(null); gl.bindTexture(gl.TEXTURE_2D, null); gl.bindBuffer(gl.ARRAY_BUFFER, null); - gl.deleteTexture(logoTexture); - gl.deleteTexture(sloganTexture); - gl.deleteTexture(bgTexture); + useLogo && gl.deleteTexture(logoTexture); + useLogo && useDefaultLogo && gl.deleteTexture(sloganTexture); + useCustomBg && gl.deleteTexture(bgTexture); gl.deleteBuffer(vertexBuffer); - gl.deleteBuffer(bgVertexBuffer); - gl.deleteBuffer(sloganVertexBuffer); + useCustomBg && gl.deleteBuffer(bgVertexBuffer); + useLogo && useDefaultLogo && gl.deleteBuffer(sloganVertexBuffer); gl.deleteBuffer(vertexBufferProgress); gl.deleteProgram(program); gl.deleteProgram(programBg); @@ -434,30 +444,35 @@ function start(alpha, antialias, useWebgl2) { gl = window.canvas.getContext("webgl", options); } initVertexBuffer(); - initBgVertexBuffer(); - initSloganVertexBuffer(); + useCustomBg && initBgVertexBuffer(); + useLogo && useDefaultLogo && initSloganVertexBuffer(); initProgressVertexBuffer(); initLogoTexture(); - initBgTexture(); - initSloganTexture(); + useCustomBg && initBgTexture(); + useLogo && useDefaultLogo && initSloganTexture(); - program = initShaders(VS_LOGO, FS_LOGO); - programBg = initShaders(VS_BG, FS_BG); + if (useLogo) { + program = initShaders(VS_LOGO, FS_LOGO); + } + if (useCustomBg) { + programBg = initShaders(VS_BG, FS_BG); + } programProgress = initShaders(VS_PROGRESSBAR, FS_PROGRESSBAR); tick(); + return Promise.all([ //logo should be loaded earlier than slogan - loadImage('logo.png').then(() => { + useLogo && loadImage(logoName).then(() => { updateVertexBuffer(); updateLogoTexture(); }).then(() => { - return loadSlogan('slogan.png').then(() => { + return useLogo && useDefaultLogo && loadSlogan('slogan.png').then(() => { updateSloganVertexBuffer(); updateSloganTexture(); }); }), - loadBackground('background.png').then(() => { + useCustomBg && loadBackground(bgName).then(() => { updateBgVertexBuffer(); updateBgTexture(); }) From 3c6a84934e0df9b3474921c64a7d675ec84754f9 Mon Sep 17 00:00:00 2001 From: PP Date: Thu, 3 Aug 2023 10:29:33 +0800 Subject: [PATCH 095/232] fix some bugs for cyberpunk demo on OH platform (#15846) * fix: bug on Destructuring Assignment syntax on OH * [AOT] workaround skip Storage type checking on OH * reuse fullscreen on OH platform --- .../marionette/animation-graph-animation-clip-binding.ts | 4 +++- cocos/core/platform/sys.ts | 7 +++++-- .../entry/src/main/ets/MainAbility/MainAbility.ts | 6 +++--- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/cocos/animation/marionette/animation-graph-animation-clip-binding.ts b/cocos/animation/marionette/animation-graph-animation-clip-binding.ts index 298a61777a5..0c2ab2d0297 100644 --- a/cocos/animation/marionette/animation-graph-animation-clip-binding.ts +++ b/cocos/animation/marionette/animation-graph-animation-clip-binding.ts @@ -356,8 +356,10 @@ class AnimationClipAGEvaluationRegular implements AnimationClipAGEvaluation { const { tracks, - [exoticAnimationTag]: exoticAnimation, + // NOTE: on OH platform, there is a bug on Destructuring Assignment syntax. + // [exoticAnimationTag]: exoticAnimation, } = clip; + const exoticAnimation = clip[exoticAnimationTag]; for (const track of tracks) { if (track instanceof UntypedTrack) { diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index 8c475705488..3a6dbeebcb6 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -33,6 +33,9 @@ import { warnID, log } from './debug'; import { NetworkType, Language, OS, Platform, BrowserType, Feature } from '../../../pal/system-info/enum-type'; import { screen } from './screen'; +// TODO: the type Storage conflicts with the one on OH platform. +type Storage = any; + export declare namespace sys { /** * @en @@ -292,7 +295,7 @@ export const sys = { * @zh 尝试打开一个 web 页面,并非在所有平台都有效。 * @param url @zh 访问的链接。 @en Visited links. */ - openURL (url): void { + openURL (url: string): void { systemInfo.openURL(url); }, @@ -304,7 +307,7 @@ export const sys = { .then((): any => systemInfo.init()) .then((): void => { try { - let localStorage: Storage | null = sys.localStorage = window.localStorage; + let localStorage: Storage = sys.localStorage = window.localStorage; localStorage.setItem('storage', ''); localStorage.removeItem('storage'); localStorage = null; diff --git a/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts b/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts index 5f9c7db98b5..51b6bbd2d4f 100644 --- a/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts +++ b/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts @@ -61,9 +61,9 @@ export default class MainAbility extends UIAbility { } }); // Set full screen - //windowStage.getMainWindow().then((window: window.Window) => { - // window.setFullScreen(true); - //}); + windowStage.getMainWindow().then((window: window.Window) => { + window.setWindowSystemBarEnable([]); + }); nativeContext.writablePathInit(this.context.cacheDir); } From c7195e8cf636f1e54f44f413d1fa3dbdb8a8febe Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Fri, 4 Aug 2023 10:48:43 +0800 Subject: [PATCH 096/232] fix 2d particle and tiledMap prefab position problem (#15836) --- editor/assets/default_prefab/ui/ParticleSystem2D.prefab | 6 +++--- editor/assets/default_prefab/ui/TiledMap.prefab | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab index 673afadd40f..9f7c9901cff 100644 --- a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab +++ b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab @@ -31,9 +31,9 @@ }, "_lpos": { "__type__": "cc.Vec3", - "x": -480, - "y": -320, - "z": -1 + "x": 0, + "y": 0, + "z": 0 }, "_lrot": { "__type__": "cc.Quat", diff --git a/editor/assets/default_prefab/ui/TiledMap.prefab b/editor/assets/default_prefab/ui/TiledMap.prefab index 853e6d0571f..dc0ee1acdb6 100644 --- a/editor/assets/default_prefab/ui/TiledMap.prefab +++ b/editor/assets/default_prefab/ui/TiledMap.prefab @@ -31,8 +31,8 @@ }, "_lpos": { "__type__": "cc.Vec3", - "x": -480, - "y": -320, + "x": 0, + "y": 0, "z": 0 }, "_lrot": { From 31324e5c658f91138e9ebf9e2cee5b5f77a7beb1 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Fri, 4 Aug 2023 10:49:17 +0800 Subject: [PATCH 097/232] cancel restore prefab undo record (#15808) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix : prefab undo problems removed/apply components undo; revert-prefab undo; * 还原部分不需要的undo * fix : node._instantiate has different behavior in native scene * Revert "fix : node._instantiate has different behavior in native scene" This reverts commit a896450198ff466cf32c8a72888b082ce40818fa. * remove reset prefab undo record --- editor/inspector/contributions/node.js | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index bf17bebb444..07504266776 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -643,20 +643,6 @@ const Elements = { const role = button.getAttribute('role'); - const recordings = []; - for (const dump of panel.dumps) { - const prefab = dump.__prefab__; - switch (role) { - case 'reset': { - recordings.push(prefab.rootUuid); - } - } - } - let undoID; - if (recordings.length) { - undoID = await beginRecording(recordings); - } - for (const dump of panel.dumps) { const prefab = dump.__prefab__; @@ -688,10 +674,6 @@ const Elements = { } } } - - if (recordings.length && undoID) { - await endRecording(undoID); - } }); }, async update() { From c6cc635840e70566ebf0a98755763f21790a0e73 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Fri, 4 Aug 2023 10:53:07 +0800 Subject: [PATCH 098/232] fix: terrain data lost when open prefab in editor (#15841) * fix: terrain data lost when open prefab in editor * fix spell error and eslint check failed --- cocos/terrain/terrain.ts | 140 ++++++++++++++++++++++----------------- 1 file changed, 78 insertions(+), 62 deletions(-) diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index 66855790fda..d5e3e6c1ff1 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -23,6 +23,7 @@ */ import { ccclass, disallowMultiple, executeInEditMode, help, visible, type, serializable, editable, disallowAnimation } from 'cc.decorator'; +import { EDITOR } from 'internal:constants'; import { builtinResMgr } from '../asset/asset-manager'; import { ModelRenderer } from '../misc/model-renderer'; import { EffectAsset, Texture2D } from '../asset/assets'; @@ -32,7 +33,7 @@ import { RenderingSubMesh } from '../asset/assets/rendering-sub-mesh'; import { Component } from '../scene-graph/component'; import { CCObject, isValid } from '../core/data/object'; import { director } from '../game/director'; -import { AttributeName, BufferUsageBit, Format, MemoryUsageBit, PrimitiveMode, Attribute, Buffer, BufferInfo, deviceManager } from '../gfx'; +import { AttributeName, BufferUsageBit, Format, MemoryUsageBit, PrimitiveMode, Attribute, Buffer, BufferInfo, deviceManager, Texture } from '../gfx'; import { clamp, Rect, Size, Vec2, Vec3, Vec4 } from '../core/math'; import { MacroRecord } from '../render-scene/core/pass-utils'; import { Pass, scene } from '../render-scene'; @@ -293,7 +294,7 @@ class TerrainRenderable extends ModelRenderer { return false; } - /** + /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateLightingmap (texture: Texture2D | null, uvParam: Vec4): void { @@ -445,8 +446,14 @@ export class TerrainBlock { new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), ]; - this._renderable._meshData = new RenderingSubMesh([vertexBuffer], gfxAttributes, - PrimitiveMode.TRIANGLE_LIST, this._terrain._getSharedIndexBuffer(), null, false); + this._renderable._meshData = new RenderingSubMesh( + [vertexBuffer], + gfxAttributes, + PrimitiveMode.TRIANGLE_LIST, + this._terrain._getSharedIndexBuffer(), + null, + false, + ); this._renderable._model = (legacyCC.director.root as Root).createModel(scene.Model); this._renderable._model.createBoundingShape(this._bbMin, this._bbMax); this._renderable._model.node = this._renderable._model.transform = this._node; @@ -455,7 +462,7 @@ export class TerrainBlock { this.visible = true; } - // reset weightmap + // reset weightMap this._updateWeightMap(); // reset material @@ -507,7 +514,7 @@ export class TerrainBlock { const getNormalTex = (layer: TerrainLayer|null): Texture2D | null => { let normalTex = layer !== null ? layer.normalMap : null; if (normalTex === null) { - normalTex = legacyCC.builtinResMgr.get('normal-texture'); + normalTex = builtinResMgr.get('normal-texture'); } return normalTex; @@ -515,12 +522,12 @@ export class TerrainBlock { const mtl = this._renderable._currentMaterial; if (mtl !== null) { - const nlayers = this.getMaxLayer(); + const nLayers = this.getMaxLayer(); const uvScale = new Vec4(1, 1, 1, 1); const roughness = new Vec4(1, 1, 1, 1); const metallic = new Vec4(0, 0, 0, 0); - if (nlayers === 0) { + if (nLayers === 0) { if (this.layers[0] !== -1) { const l0 = this._terrain.getLayer(this.layers[0]); @@ -535,12 +542,12 @@ export class TerrainBlock { mtl.setProperty('normalMap0', getNormalTex(l0)); } } else { - mtl.setProperty('detailMap0', legacyCC.builtinResMgr.get('default-texture')); + mtl.setProperty('detailMap0', builtinResMgr.get('default-texture')); if (useNormalMap) { - mtl.setProperty('normalMap0', legacyCC.builtinResMgr.get('normal-texture')); + mtl.setProperty('normalMap0', builtinResMgr.get('normal-texture')); } } - } else if (nlayers === 1) { + } else if (nLayers === 1) { const l0 = this._terrain.getLayer(this.layers[0]); const l1 = this._terrain.getLayer(this.layers[1]); @@ -562,7 +569,7 @@ export class TerrainBlock { mtl.setProperty('normalMap0', getNormalTex(l0)); mtl.setProperty('normalMap1', getNormalTex(l1)); } - } else if (nlayers === 2) { + } else if (nLayers === 2) { const l0 = this._terrain.getLayer(this.layers[0]); const l1 = this._terrain.getLayer(this.layers[1]); const l2 = this._terrain.getLayer(this.layers[2]); @@ -592,7 +599,7 @@ export class TerrainBlock { mtl.setProperty('normalMap1', getNormalTex(l1)); mtl.setProperty('normalMap2', getNormalTex(l2)); } - } else if (nlayers === 3) { + } else if (nLayers === 3) { const l0 = this._terrain.getLayer(this.layers[0]); const l1 = this._terrain.getLayer(this.layers[1]); const l2 = this._terrain.getLayer(this.layers[2]); @@ -853,7 +860,7 @@ export class TerrainBlock { return 0; } - public _getMaterialDefines (nlayers: number): MacroRecord { + public _getMaterialDefines (nLayers: number): MacroRecord { let lightmapMacroValue = 1; /*static*/ if (this._terrain.node && this._terrain.node.scene) { if (this._terrain.node.scene.globals.bakedWithStationaryMainLight) { @@ -861,7 +868,7 @@ export class TerrainBlock { } } return { - LAYERS: nlayers + 1, + LAYERS: nLayers + 1, CC_USE_LIGHTMAP: this.lightmap !== null ? lightmapMacroValue : 0, USE_NORMALMAP: this._terrain.useNormalMap ? 1 : 0, USE_PBR: this._terrain.usePBR ? 1 : 0, @@ -903,9 +910,9 @@ export class TerrainBlock { } public _updateWeightMap (): void { - const nlayers = this.getMaxLayer(); + const nLayers = this.getMaxLayer(); - if (nlayers === 0) { + if (nLayers === 0) { if (this._weightMap != null) { this._weightMap.destroy(); this._weightMap = null; @@ -1047,18 +1054,18 @@ export class TerrainBlock { return verts[idx * TERRAIN_BLOCK_VERTEX_SIZE + 1]; } - private _updateLodBuffer (vertecs: Float32Array): void { + private _updateLodBuffer (vertices: Float32Array): void { this._lodLevel = 0; this._lodKey = new TerrainLodKey(); - this._calcErrorMetrics(vertecs); - this._calcLevelDistances(vertecs); + this._calcErrorMetrics(vertices); + this._calcLevelDistances(vertices); } - private _calcErrorMetrics (vertecs: Float32Array): void { + private _calcErrorMetrics (vertices: Float32Array): void { this._errorMetrics[0] = 0; for (let i = 1; i < TERRAIN_LOD_LEVELS; ++i) { - this._errorMetrics[i] = this._calcErrorMetric(i, vertecs); + this._errorMetrics[i] = this._calcErrorMetric(i, vertices); } for (let i = 2; i < TERRAIN_LOD_LEVELS; ++i) { @@ -1066,23 +1073,23 @@ export class TerrainBlock { } } - private _calcErrorMetric (level: number, vertecs: Float32Array): number { + private _calcErrorMetric (level: number, vertices: Float32Array): number { let err = 0.0; const step = 1 << level; - const xSectionVerts = TERRAIN_BLOCK_VERTEX_COMPLEXITY; - const ySectionVerts = TERRAIN_BLOCK_VERTEX_COMPLEXITY; - const xSides = (xSectionVerts - 1) >> level; - const ySides = (ySectionVerts - 1) >> level; + const xSectionVertices = TERRAIN_BLOCK_VERTEX_COMPLEXITY; + const ySectionVertices = TERRAIN_BLOCK_VERTEX_COMPLEXITY; + const xSides = (xSectionVertices - 1) >> level; + const ySides = (ySectionVertices - 1) >> level; - for (let y = 0; y < ySectionVerts; y += step) { + for (let y = 0; y < ySectionVertices; y += step) { for (let x = 0; x < xSides; ++x) { const x0 = x * step; const x1 = x0 + step; const xm = (x1 + x0) / 2; - const h0 = this._getHeight(x0, y, vertecs); - const h1 = this._getHeight(x1, y, vertecs); - const hm = this._getHeight(xm, y, vertecs); + const h0 = this._getHeight(x0, y, vertices); + const h1 = this._getHeight(x1, y, vertices); + const hm = this._getHeight(xm, y, vertices); const hmi = (h0 + h1) / 2; const delta = Math.abs(hm - hmi); @@ -1091,15 +1098,15 @@ export class TerrainBlock { } } - for (let x = 0; x < xSectionVerts; x += step) { + for (let x = 0; x < xSectionVertices; x += step) { for (let y = 0; y < ySides; ++y) { const y0 = y * step; const y1 = y0 + step; const ym = (y0 + y1) / 2; - const h0 = this._getHeight(x, y0, vertecs); - const h1 = this._getHeight(x, y1, vertecs); - const hm = this._getHeight(x, ym, vertecs); + const h0 = this._getHeight(x, y0, vertices); + const h1 = this._getHeight(x, y1, vertices); + const hm = this._getHeight(x, ym, vertices); const hmi = (h0 + h1) / 2; const delta = Math.abs(hm - hmi); @@ -1118,9 +1125,9 @@ export class TerrainBlock { const x1 = x0 + step; const xm = (x0 + x1) / 2; - const h0 = this._getHeight(x0, y0, vertecs); - const h1 = this._getHeight(x1, y1, vertecs); - const hm = this._getHeight(xm, ym, vertecs); + const h0 = this._getHeight(x0, y0, vertices); + const h1 = this._getHeight(x1, y1, vertices); + const hm = this._getHeight(xm, ym, vertices); const hmi = (h0 + h1) / 2; const delta = Math.abs(hm - hmi); @@ -1132,10 +1139,10 @@ export class TerrainBlock { return err; } - private _calcLevelDistances (vertecs: Float32Array): void { - const pixelerr = 4; + private _calcLevelDistances (vertices: Float32Array): void { + const pixelErr = 4; const resolution = 768; - const c = 1.0 / (2 * pixelerr / resolution); + const c = 1.0 / (2 * pixelErr / resolution); for (let i = 1; i < TERRAIN_LOD_LEVELS; ++i) { const e = this._errorMetrics[i]; @@ -1265,7 +1272,7 @@ export class Terrain extends Component { } this._blocks = []; - // restore to defualt + // restore to default if (this.__asset === null) { this._effectAsset = null; this._lightmapInfos = []; @@ -1829,6 +1836,9 @@ export class Terrain extends Component { public setHeight (i: number, j: number, h: number): void { h = clamp(h, TERRAIN_HEIGHT_FMIN, TERRAIN_HEIGHT_FMAX); this._heights[j * this.vertexCount[0] + i] = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY; + if (EDITOR && this._asset) { + this._asset.heights[j * this.vertexCount[0] + i] = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY; + } } /** @@ -1984,6 +1994,12 @@ export class Terrain extends Component { this._weights[index * 4 + 1] = w.y * 255; this._weights[index * 4 + 2] = w.z * 255; this._weights[index * 4 + 3] = w.w * 255; + if (EDITOR && this._asset) { + this._asset.weights[index * 4 + 0] = w.x * 255; + this._asset.weights[index * 4 + 1] = w.y * 255; + this._asset.weights[index * 4 + 2] = w.x * 255; + this._asset.weights[index * 4 + 3] = w.w * 255; + } } /** @@ -2007,14 +2023,14 @@ export class Terrain extends Component { * @zh 根据点的坐标获得权重 */ public getWeightAt (x: number, y: number): Vec4 | null { - const uWeigthComplexity = this.weightMapSize * this.blockCount[0]; - const vWeigthComplexity = this.weightMapSize * this.blockCount[1]; - if (uWeigthComplexity === 0 || vWeigthComplexity === 0) { + const uWeightComplexity = this.weightMapSize * this.blockCount[0]; + const vWeightComplexity = this.weightMapSize * this.blockCount[1]; + if (uWeightComplexity === 0 || vWeightComplexity === 0) { return null; } - const fx = x / uWeigthComplexity; - const fy = y / vWeigthComplexity; + const fx = x / uWeightComplexity; + const fy = y / vWeightComplexity; let ix0 = Math.floor(fx); let iz0 = Math.floor(fy); @@ -2023,14 +2039,14 @@ export class Terrain extends Component { const dx = fx - ix0; const dz = fy - iz0; - if (ix0 < 0 || ix0 > uWeigthComplexity - 1 || iz0 < 0 || iz0 > vWeigthComplexity - 1) { + if (ix0 < 0 || ix0 > uWeightComplexity - 1 || iz0 < 0 || iz0 > vWeightComplexity - 1) { return null; } - ix0 = clamp(ix0, 0, uWeigthComplexity - 1); - iz0 = clamp(iz0, 0, vWeigthComplexity - 1); - ix1 = clamp(ix1, 0, uWeigthComplexity - 1); - iz1 = clamp(iz1, 0, vWeigthComplexity - 1); + ix0 = clamp(ix0, 0, uWeightComplexity - 1); + iz0 = clamp(iz0, 0, vWeightComplexity - 1); + ix1 = clamp(ix1, 0, uWeightComplexity - 1); + iz1 = clamp(iz1, 0, vWeightComplexity - 1); let a = this.getWeight(ix0, iz0); const b = this.getWeight(ix1, iz0); @@ -2062,18 +2078,18 @@ export class Terrain extends Component { * @zh 根据点的坐标获得权重最大的纹理层 */ public getMaxWeightLayerAt (x: number, y: number): TerrainLayer | null { - const uWeigthComplexity = this.weightMapSize * this.blockCount[0]; - const vWeigthComplexity = this.weightMapSize * this.blockCount[1]; - if (uWeigthComplexity === 0 || vWeigthComplexity === 0) { + const uWeightComplexity = this.weightMapSize * this.blockCount[0]; + const vWeightComplexity = this.weightMapSize * this.blockCount[1]; + if (uWeightComplexity === 0 || vWeightComplexity === 0) { return null; } - const fx = x / uWeigthComplexity; - const fy = y / vWeigthComplexity; + const fx = x / uWeightComplexity; + const fy = y / vWeightComplexity; const ix0 = Math.floor(fx); const iz0 = Math.floor(fy); - if (ix0 < 0 || ix0 > uWeigthComplexity - 1 || iz0 < 0 || iz0 > vWeigthComplexity - 1) { + if (ix0 < 0 || ix0 > uWeightComplexity - 1 || iz0 < 0 || iz0 > vWeightComplexity - 1) { return null; } @@ -2295,9 +2311,9 @@ export class Terrain extends Component { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _resetLightmap (enble: boolean): void { + public _resetLightmap (enable: boolean): void { this._lightmapInfos.length = 0; - if (enble) { + if (enable) { for (let i = 0; i < this._blockCount[0] * this._blockCount[1]; ++i) { this._lightmapInfos.push(new TerrainBlockLightmapInfo()); } @@ -2310,12 +2326,12 @@ export class Terrain extends Component { public _updateLightmap (blockId: number, tex: Texture2D|null, uOff: number, vOff: number, uScale: number, vScale: number): void { if (tex) { // ensure the lightmap infos is initialized - if (this._lightmapInfos.length == 0) { + if (this._lightmapInfos.length === 0) { for (let i = 0; i < this._blockCount[0] * this._blockCount[1]; ++i) { this._lightmapInfos.push(new TerrainBlockLightmapInfo()); } } - } else if (this._lightmapInfos.length == 0) { + } else if (this._lightmapInfos.length === 0) { return; } From 1cbe27b4009629a2a2b08d3088621929b42d26d8 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 4 Aug 2023 11:37:12 +0800 Subject: [PATCH 099/232] fix reflection probe affected by sky rotation (#15857) --- editor/assets/chunks/common/texture/cubemap.chunk | 10 ++++------ .../model-functions/standard-common.chunk | 2 ++ editor/assets/effects/advanced/glass.effect | 10 ++++++++++ editor/assets/effects/advanced/sky.effect | 3 ++- .../util/dcc/imported-specular-glossiness.effect | 11 ++++++----- 5 files changed, 24 insertions(+), 12 deletions(-) diff --git a/editor/assets/chunks/common/texture/cubemap.chunk b/editor/assets/chunks/common/texture/cubemap.chunk index 4cf105bcb20..4d310f151ac 100644 --- a/editor/assets/chunks/common/texture/cubemap.chunk +++ b/editor/assets/chunks/common/texture/cubemap.chunk @@ -36,6 +36,7 @@ float RoughnessToPerceptualRoughness(float roughness) #endif } + // for skybox IBL vec3 EnvReflection(samplerCube tex, vec3 R, float roughness, float mipCount) { // simulate GGX convolution #if !CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING && !CC_IBL_CONVOLUTED @@ -52,16 +53,13 @@ float RoughnessToPerceptualRoughness(float roughness) } + // for reflection probe vec3 EnvReflectionOfReflectionProbe(samplerCube tex, vec3 R, float roughness, float mipCount, bool isRGBE) { // simulate GGX convolution #if !CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING && !CC_IBL_CONVOLUTED roughness = RoughnessToPerceptualRoughness(roughness); #endif - vec3 rotationDir = RotationVecFromAxisY(R.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); - vec4 envmap = fragTextureLod(tex, rotationDir, roughness * (mipCount - 1.0)); - if (isRGBE) - return unpackRGBE(envmap); - else - return SRGBToLinear(envmap.rgb); + vec4 envmap = fragTextureLod(tex, R, roughness * (mipCount - 1.0)); + return isRGBE ? unpackRGBE(envmap) : SRGBToLinear(envmap.rgb); } diff --git a/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk b/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk index db9fb783137..78ab23eba1f 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk @@ -62,6 +62,7 @@ vec3 CalculateDirectSpecular(in LightingIntermediateData lightingData, in vec4 l } #endif +// for skybox IBL vec3 SampleEnvironmentSpecular(samplerCube tex, in LightingIntermediateData lightingData, float mipCount) { vec3 envSpec = vec3(0.0); @@ -84,6 +85,7 @@ vec3 SampleEnvironmentSpecular(samplerCube tex, in LightingIntermediateData ligh return envSpec; } +// for reflection probe vec3 SampleEnvironmentSpecular(samplerCube tex, in LightingIntermediateData lightingData, float mipCount, vec3 worldPos, vec3 cubeCenterPos, vec3 boxHalfSize, bool isRGBE) { vec3 envSpec = vec3(0.0); diff --git a/editor/assets/effects/advanced/glass.effect b/editor/assets/effects/advanced/glass.effect index 8fd1228902a..e16bf1878c1 100644 --- a/editor/assets/effects/advanced/glass.effect +++ b/editor/assets/effects/advanced/glass.effect @@ -87,6 +87,8 @@ CCEffect %{ - vert: standard-vs frag: standard-fs embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + rasterizerState: + cullMode: Front depthStencilState: &d1 depthTest: true depthWrite: false @@ -97,6 +99,14 @@ CCEffect %{ blendDst: one_minus_src_alpha blendDstAlpha: one_minus_src_alpha properties: *props + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + rasterizerState: + cullMode: Back + depthStencilState: *d1 + blendState: *b1 + properties: *props - *forward-add - *shadow-caster - *planar-shadow diff --git a/editor/assets/effects/advanced/sky.effect b/editor/assets/effects/advanced/sky.effect index b7e2e59ff2f..c2f5232529f 100644 --- a/editor/assets/effects/advanced/sky.effect +++ b/editor/assets/effects/advanced/sky.effect @@ -11,6 +11,7 @@ CCEffect %{ positionScaling: { value: 1.0, target: params.w, editor: { tooltip: 'Set a smaller value (such as less than 1.0) to remove the effects of fog' } } blendEnvironmentMap: { value: grey, editor: { parent: BLEND_ENV_MAP } } blendWeight: { value: 0.0, target: params.x, editor: { parent: BLEND_ENV_MAP } } + brightMultiplier: { value: 1.0, target: params.y } priority : max - 10 rasterizerState : &r1 cullMode : none @@ -69,7 +70,7 @@ CCProgram surface-fragment %{ c = mix(c, sampleEnvMap(blendEnvironmentMap, rotationDir), params.x); #endif #endif - return vec4(c * cc_ambientSky.w, 1.0); + return vec4(c * cc_ambientSky.w * params.y, 1.0); } }% diff --git a/editor/assets/effects/util/dcc/imported-specular-glossiness.effect b/editor/assets/effects/util/dcc/imported-specular-glossiness.effect index fe4565b98bc..3707e2168ba 100644 --- a/editor/assets/effects/util/dcc/imported-specular-glossiness.effect +++ b/editor/assets/effects/util/dcc/imported-specular-glossiness.effect @@ -15,12 +15,12 @@ CCEffect %{ emissiveMap: { value: grey } emissiveScale: { value: 1.0 } emissiveScaleMap: { value: grey } - shininessExponentMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } - shininessExponent: { value: 100.0, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } - specularGlossinessMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } + shininessExponentMap: { value: grey } + shininessExponent: { value: 100.0 } + specularGlossinessMap: { value: grey } specularColor: { value: [0.0, 0.0, 0.0, 0.0], linear: true, editor: { displayName: SpecularColor, type: color } } - specularMap: { value: grey, editor: { parent: '!HAS_EXPORTED_METALLIC' } } - specularFactor: { value: 1.0, editor: { parent: '!HAS_EXPORTED_METALLIC' } } + specularMap: { value: grey } + specularFactor: { value: 1.0 } transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } @@ -81,6 +81,7 @@ CCEffect %{ blendSrc: src_alpha blendDst: one_minus_src_alpha blendDstAlpha: one_minus_src_alpha + properties: *props - *forward-add - *shadow-caster - &deferred-forward From b37b73a7b798810bd3660fa8e378567d4c9ac820 Mon Sep 17 00:00:00 2001 From: Jiujiang Liu <37231523+moshuying@users.noreply.github.com> Date: Fri, 4 Aug 2023 16:20:53 +0800 Subject: [PATCH 100/232] make allowDataAccess is only available at runtime. (#15835) * make allowDataAccess is only available at runtime. --- cocos/3d/assets/mesh.ts | 5 +++-- native/cocos/3d/assets/Mesh.cpp | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 39b823bb07a..0ca33d88c63 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -23,6 +23,7 @@ */ import { ccclass, serializable } from 'cc.decorator'; +import { EDITOR } from 'internal:constants'; import { Asset } from '../../asset/assets/asset'; import { IDynamicGeometry } from '../../primitive/define'; import { BufferBlob } from '../misc/buffer-blob'; @@ -493,7 +494,7 @@ export class Mesh extends Asset { } this._isMeshDataUploaded = true; - if (!this._allowDataAccess) { + if (!this._allowDataAccess && !EDITOR) { this.releaseData(); } } @@ -1304,7 +1305,7 @@ export class Mesh extends Asset { */ public set allowDataAccess (allowDataAccess: boolean) { this._allowDataAccess = allowDataAccess; - if (this._isMeshDataUploaded && !this._allowDataAccess) { + if (this._isMeshDataUploaded && !this._allowDataAccess && !EDITOR) { this.releaseData(); } } diff --git a/native/cocos/3d/assets/Mesh.cpp b/native/cocos/3d/assets/Mesh.cpp index 588247e8d78..e0b2034f89c 100644 --- a/native/cocos/3d/assets/Mesh.cpp +++ b/native/cocos/3d/assets/Mesh.cpp @@ -439,9 +439,11 @@ void Mesh::initialize() { } _isMeshDataUploaded = true; +#if !CC_EDITOR if (!_allowDataAccess) { releaseData(); } +#endif } } @@ -1260,9 +1262,11 @@ void Mesh::initDefault(const ccstd::optional &uuid) { void Mesh::setAllowDataAccess(bool allowDataAccess) { _allowDataAccess = allowDataAccess; +#if !CC_EDITOR if (_isMeshDataUploaded && !_allowDataAccess) { releaseData(); } +#endif } void Mesh::releaseData() { From 6fec3201fd39c8d2dc2425ea3e195fd5037ffc25 Mon Sep 17 00:00:00 2001 From: Canvas Date: Mon, 7 Aug 2023 10:23:34 +0800 Subject: [PATCH 101/232] fix spine-skeleton-instance.cpp 3.8.0 -> 3.8.1 missing code issue. (#15876) --- .../spine-wasm/spine-type-export.cpp | 229 +++++++++--------- 1 file changed, 117 insertions(+), 112 deletions(-) diff --git a/native/cocos/editor-support/spine-wasm/spine-type-export.cpp b/native/cocos/editor-support/spine-wasm/spine-type-export.cpp index a574fc17fcc..b5c22169054 100644 --- a/native/cocos/editor-support/spine-wasm/spine-type-export.cpp +++ b/native/cocos/editor-support/spine-wasm/spine-type-export.cpp @@ -942,9 +942,11 @@ EMSCRIPTEN_BINDINGS(spine) { .constructor() .function("getDefaultMix", &AnimationStateData::getDefaultMix) .function("getSkeletonData", &AnimationStateData::getSkeletonData, allow_raw_pointers()) - .function("setMix", optional_override([](AnimationStateData &obj, std::string fromName, std::string toName, float duration) { - .function("setMixWith", optional_override([](AnimationStateData &obj, Animation *from, Animation *to, float duration) { return obj.setMix(from, to, duration); }), allow_raw_pointers()) - .function("getMix", &AnimationStateData::getMix, allow_raw_pointers()); + .function("setMix", optional_override([](AnimationStateData &obj, const std::string& fromName, const std::string& toName, float duration) { + return obj.setMix(STRING_STD2SP(fromName), STRING_STD2SP(toName), duration);})) + .function("setMixWith", optional_override([](AnimationStateData &obj, Animation* from, Animation* to, float duration) { + return obj.setMix(from, to, duration);}), allow_raw_pointers()) + .function("getMix", &AnimationStateData::getMix, allow_raw_pointers()); // .function("setMixWith", &Skeleton::setMixWith_Export) //.function("getMix", &Skeleton::setMix_Export); @@ -1071,116 +1073,119 @@ EMSCRIPTEN_BINDINGS(spine) { .function("setSkinByName", optional_override([](Skeleton &obj, const std::string& name) { return obj.setSkin(STRING_STD2SP(name));})) .function("setSkin", static_cast(&Skeleton::setSkin), allow_raw_pointer()) - .function("getAttachmentByName", optional_override([](Skeleton &obj, std::string slotName, std::string attachmentName) { - .function("getAttachment", optional_override([](Skeleton &obj, int slotIndex, std::string attachmentName) { - .function("setAttachment", optional_override([](Skeleton &obj, std::string slotName, std::string attachmentName) { - .function("findIkConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findIkConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findTransformConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findTransformConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findPathConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findPathConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - //.function("getBounds", &Skeleton::getBounds) - .function("update", &Skeleton::update); - - // incomplete - // class_("SkeletonBinary") - // .constructor() - // .function("setProp_scale", &SkeletonBinary::setScale); - //.function("getProp_scale", &SkeletonBinary::getScale) - //.function("readSkeletonData", &SkeletonBinary::readSkeletonData) - //.function("setCurve", &SkeletonBinary::setCurve); - // incomplete - - // class_("SkeletonJson") - // .constructor() - // .constructor(); - //.function("readSkeletonData", &SkeletonJson::readSkeletonData) - //.function("getProp_scale", &SkeletonJson::getScale) - - class_("VertexEffect") - .function("begin", &VertexEffect::begin, pure_virtual()) - //.function("transform", &VertexEffect::transform, pure_virtual()) - .function("end", &VertexEffect::end, pure_virtual()); - - class_>("JitterEffect") - .constructor() - .function("getJitterX", &JitterVertexEffect::getJitterX) - .function("setJitterX", &JitterVertexEffect::setJitterX) - .function("getJitterY", &JitterVertexEffect::getJitterY) - .function("setJitterY", &JitterVertexEffect::setJitterY) - .function("begin", &JitterVertexEffect::begin) - //.function("transform", &JitterVertexEffect::transform) - .function("end", &JitterVertexEffect::end); - - class_>("SwirlEffect") - .constructor() - .function("getCenterX", &SwirlVertexEffect::getCenterX) - .function("setCenterX", &SwirlVertexEffect::setCenterX) - .function("getCenterY", &SwirlVertexEffect::getCenterY) - .function("setCenterY", &SwirlVertexEffect::setCenterY) - .function("getRadius", &SwirlVertexEffect::getRadius) - .function("setRadius", &SwirlVertexEffect::setRadius) - .function("getAngle", &SwirlVertexEffect::getAngle) - .function("setAngle", &SwirlVertexEffect::setAngle) - .function("begin", &SwirlVertexEffect::begin) - //.function("transform", &SwirlVertexEffect::transform) - .function("end", &SwirlVertexEffect::end); - - class_("SlotMesh") - .property("vCount", &SlotMesh::vCount) - .property("iCount", &SlotMesh::iCount) - .property("blendMode", &SlotMesh::blendMode) - .property("textureID", &SlotMesh::textureID); - - register_vector("VectorSlotMesh"); - class_("SpineModel") - .property("vCount", &SpineModel::vCount) - .property("iCount", &SpineModel::iCount) - .property("vPtr", &SpineModel::vPtr) - .property("iPtr", &SpineModel::iPtr) - .function("getMeshes", &SpineModel::getMeshes); - - class_("SpineDebugShape") - .property("type", &SpineDebugShape::type) - .property("vOffset", &SpineDebugShape::vOffset) - .property("vCount", &SpineDebugShape::vCount) - .property("iOffset", &SpineDebugShape::iOffset) - .property("iCount", &SpineDebugShape::iCount); - - register_vector("VectorDebugShape"); - class_("SkeletonInstance") - .constructor<>() - .function("initSkeleton", &SpineSkeletonInstance::initSkeleton, allow_raw_pointers()) - .function("setAnimation", &SpineSkeletonInstance::setAnimation, allow_raw_pointers()) - .function("setSkin", &SpineSkeletonInstance::setSkin) - .function("updateAnimation", &SpineSkeletonInstance::updateAnimation) - .function("updateRenderData", &SpineSkeletonInstance::updateRenderData, allow_raw_pointer()) - .function("setPremultipliedAlpha", &SpineSkeletonInstance::setPremultipliedAlpha) - .function("setUseTint", &SpineSkeletonInstance::setUseTint) - .function("setColor", &SpineSkeletonInstance::setColor) - .function("setJitterEffect", &SpineSkeletonInstance::setJitterEffect, allow_raw_pointer()) - .function("setSwirlEffect", &SpineSkeletonInstance::setSwirlEffect, allow_raw_pointer()) - .function("clearEffect", &SpineSkeletonInstance::clearEffect) - .function("getAnimationState", &SpineSkeletonInstance::getAnimationState, allow_raw_pointer()) - .function("setMix", &SpineSkeletonInstance::setMix) - .function("setListener", &SpineSkeletonInstance::setListener) - .function("setDebugMode", &SpineSkeletonInstance::setDebugMode) - .function("getDebugShapes", &SpineSkeletonInstance::getDebugShapes) - .function("resizeSlotRegion", &SpineSkeletonInstance::resizeSlotRegion) - .function("setSlotTexture", &SpineSkeletonInstance::setSlotTexture); + .function("getAttachmentByName", optional_override([](Skeleton &obj, const std::string& slotName, const std::string& attachmentName) { + return obj.getAttachment(STRING_STD2SP(slotName), STRING_STD2SP(attachmentName));}), allow_raw_pointers()) + .function("getAttachment", optional_override([](Skeleton &obj, int slotIndex, const std::string& attachmentName) { + return obj.getAttachment(slotIndex, STRING_STD2SP(attachmentName));}),allow_raw_pointers()) + .function("setAttachment", optional_override([](Skeleton &obj, const std::string& slotName, const std::string& attachmentName) { + return obj.setAttachment(STRING_STD2SP(slotName), STRING_STD2SP(attachmentName));})) + .function("findIkConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findIkConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findTransformConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findTransformConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findPathConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findPathConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + //.function("getBounds", &Skeleton::getBounds) + .function("update", &Skeleton::update); + + // incomplete + // class_("SkeletonBinary") + // .constructor() + // .function("setProp_scale", &SkeletonBinary::setScale); + //.function("getProp_scale", &SkeletonBinary::getScale) + //.function("readSkeletonData", &SkeletonBinary::readSkeletonData) + //.function("setCurve", &SkeletonBinary::setCurve); + // incomplete + + // class_("SkeletonJson") + // .constructor() + // .constructor(); + //.function("readSkeletonData", &SkeletonJson::readSkeletonData) + //.function("getProp_scale", &SkeletonJson::getScale) + + class_("VertexEffect") + .function("begin", &VertexEffect::begin, pure_virtual()) + //.function("transform", &VertexEffect::transform, pure_virtual()) + .function("end", &VertexEffect::end, pure_virtual()); + + class_>("JitterEffect") + .constructor() + .function("getJitterX", &JitterVertexEffect::getJitterX) + .function("setJitterX", &JitterVertexEffect::setJitterX) + .function("getJitterY", &JitterVertexEffect::getJitterY) + .function("setJitterY", &JitterVertexEffect::setJitterY) + .function("begin", &JitterVertexEffect::begin) + //.function("transform", &JitterVertexEffect::transform) + .function("end", &JitterVertexEffect::end); + + class_>("SwirlEffect") + .constructor() + .function("getCenterX", &SwirlVertexEffect::getCenterX) + .function("setCenterX", &SwirlVertexEffect::setCenterX) + .function("getCenterY", &SwirlVertexEffect::getCenterY) + .function("setCenterY", &SwirlVertexEffect::setCenterY) + .function("getRadius", &SwirlVertexEffect::getRadius) + .function("setRadius", &SwirlVertexEffect::setRadius) + .function("getAngle", &SwirlVertexEffect::getAngle) + .function("setAngle", &SwirlVertexEffect::setAngle) + .function("begin", &SwirlVertexEffect::begin) + //.function("transform", &SwirlVertexEffect::transform) + .function("end", &SwirlVertexEffect::end); + + class_("SlotMesh") + .property("vCount", &SlotMesh::vCount) + .property("iCount", &SlotMesh::iCount) + .property("blendMode", &SlotMesh::blendMode) + .property("textureID", &SlotMesh::textureID); + + register_vector("VectorSlotMesh"); + class_("SpineModel") + .property("vCount", &SpineModel::vCount) + .property("iCount", &SpineModel::iCount) + .property("vPtr", &SpineModel::vPtr) + .property("iPtr", &SpineModel::iPtr) + .function("getMeshes", &SpineModel::getMeshes); + + class_("SpineDebugShape") + .property("type", &SpineDebugShape::type) + .property("vOffset", &SpineDebugShape::vOffset) + .property("vCount", &SpineDebugShape::vCount) + .property("iOffset", &SpineDebugShape::iOffset) + .property("iCount", &SpineDebugShape::iCount); + + register_vector("VectorDebugShape"); + class_("SkeletonInstance") + .constructor<>() + .function("initSkeleton", &SpineSkeletonInstance::initSkeleton, allow_raw_pointers()) + .function("setAnimation", &SpineSkeletonInstance::setAnimation, allow_raw_pointers()) + .function("setSkin", &SpineSkeletonInstance::setSkin) + .function("updateAnimation", &SpineSkeletonInstance::updateAnimation) + .function("updateRenderData", &SpineSkeletonInstance::updateRenderData, allow_raw_pointer()) + .function("setPremultipliedAlpha", &SpineSkeletonInstance::setPremultipliedAlpha) + .function("setUseTint", &SpineSkeletonInstance::setUseTint) + .function("setColor", &SpineSkeletonInstance::setColor) + .function("setJitterEffect", &SpineSkeletonInstance::setJitterEffect, allow_raw_pointer()) + .function("setSwirlEffect", &SpineSkeletonInstance::setSwirlEffect, allow_raw_pointer()) + .function("clearEffect", &SpineSkeletonInstance::clearEffect) + .function("getAnimationState", &SpineSkeletonInstance::getAnimationState, allow_raw_pointer()) + .function("setMix", &SpineSkeletonInstance::setMix) + .function("setListener", &SpineSkeletonInstance::setListener) + .function("setDebugMode", &SpineSkeletonInstance::setDebugMode) + .function("getDebugShapes", &SpineSkeletonInstance::getDebugShapes) + .function("resizeSlotRegion", &SpineSkeletonInstance::resizeSlotRegion) + .function("setSlotTexture", &SpineSkeletonInstance::setSlotTexture); } EMSCRIPTEN_BINDINGS(cocos_spine) { - class_("SpineWasmUtil") - .class_function("spineWasmInit", &SpineWasmUtil::spineWasmInit) - .class_function("spineWasmDestroy", &SpineWasmUtil::spineWasmDestroy) - .class_function("queryStoreMemory", &SpineWasmUtil::queryStoreMemory) - .class_function("querySpineSkeletonDataByUUID", &SpineWasmUtil::querySpineSkeletonDataByUUID, allow_raw_pointers()) - .class_function("createSpineSkeletonDataWithJson", &SpineWasmUtil::createSpineSkeletonDataWithJson, allow_raw_pointers()) - .class_function("createSpineSkeletonDataWithBinary", &SpineWasmUtil::createSpineSkeletonDataWithBinary, allow_raw_pointers()) - .class_function("registerSpineSkeletonDataWithUUID", &SpineWasmUtil::registerSpineSkeletonDataWithUUID, allow_raw_pointers()) - .class_function("destroySpineSkeletonDataWithUUID", &SpineWasmUtil::destroySpineSkeletonDataWithUUID) - .class_function("destroySpineInstance", &SpineWasmUtil::destroySpineInstance, allow_raw_pointers()) - .class_function("getCurrentListenerID", &SpineWasmUtil::getCurrentListenerID) - .class_function("getCurrentEventType", &SpineWasmUtil::getCurrentEventType) - .class_function("getCurrentTrackEntry", &SpineWasmUtil::getCurrentTrackEntry, allow_raw_pointers()) - .class_function("getCurrentEvent", &SpineWasmUtil::getCurrentEvent, allow_raw_pointers()); + class_("SpineWasmUtil") + .class_function("spineWasmInit", &SpineWasmUtil::spineWasmInit) + .class_function("spineWasmDestroy", &SpineWasmUtil::spineWasmDestroy) + .class_function("queryStoreMemory", &SpineWasmUtil::queryStoreMemory) + .class_function("querySpineSkeletonDataByUUID", &SpineWasmUtil::querySpineSkeletonDataByUUID, allow_raw_pointers()) + .class_function("createSpineSkeletonDataWithJson", &SpineWasmUtil::createSpineSkeletonDataWithJson, allow_raw_pointers()) + .class_function("createSpineSkeletonDataWithBinary", &SpineWasmUtil::createSpineSkeletonDataWithBinary, allow_raw_pointers()) + .class_function("registerSpineSkeletonDataWithUUID", &SpineWasmUtil::registerSpineSkeletonDataWithUUID, allow_raw_pointers()) + .class_function("destroySpineSkeletonDataWithUUID", &SpineWasmUtil::destroySpineSkeletonDataWithUUID) + .class_function("destroySpineInstance", &SpineWasmUtil::destroySpineInstance, allow_raw_pointers()) + .class_function("getCurrentListenerID", &SpineWasmUtil::getCurrentListenerID) + .class_function("getCurrentEventType", &SpineWasmUtil::getCurrentEventType) + .class_function("getCurrentTrackEntry", &SpineWasmUtil::getCurrentTrackEntry, allow_raw_pointers()) + .class_function("getCurrentEvent", &SpineWasmUtil::getCurrentEvent, allow_raw_pointers()); } From a907d68d59071ae6061fd6a1f012068d3d108124 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Mon, 7 Aug 2023 10:54:19 +0800 Subject: [PATCH 102/232] cmake/swig allow remove genereated/../temp directory (#15726) --- native/cmake/predefine.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index bffb8619a7c..ad50d295355 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -301,7 +301,6 @@ function(cc_gen_swig_files cfg_directory output_dir) set(dep_files) get_filename_component(mod_name ${cfg} NAME_WE) - file(MAKE_DIRECTORY ${output_dir}/temp) set(output_file_tmp ${output_dir}/temp/jsb_${mod_name}_auto.cpp) set(output_file ${output_dir}/jsb_${mod_name}_auto.cpp) @@ -315,6 +314,7 @@ function(cc_gen_swig_files cfg_directory output_dir) ${output_hfile} ${output_file} COMMAND ${CMAKE_COMMAND} -E echo "Running swig with config file ${cfg} ..." + COMMAND ${CMAKE_COMMAND} -E make_directory ${output_dir}/temp COMMAND ${SWIG_EXEC} ${SWIG_ARGS} ${output_file_tmp} ${cfg} From 4b26cc878436e04aa89133073979878ba02b9062 Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Mon, 7 Aug 2023 11:19:41 +0800 Subject: [PATCH 103/232] fix PipelineStateChanged updating issue by performance optimization (#15753) --- cocos/3d/framework/mesh-renderer.ts | 1 + cocos/render-scene/scene/submodel.ts | 17 +++++++++++++++++ native/cocos/scene/Define.h | 13 +++++++++++++ native/cocos/scene/SubModel.cpp | 15 +++++++++++++++ native/cocos/scene/SubModel.h | 1 + native/tools/swig-config/scene.i | 2 ++ 6 files changed, 49 insertions(+) diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index b1039d5e25a..8b277d23e4c 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -593,6 +593,7 @@ export class MeshRenderer extends ModelRenderer { if (!this._model) { this._updateModels(); } + this._model!.onGlobalPipelineStateChanged(); this._updateCastShadow(); this._updateReceiveShadow(); this._updateShadowBias(); diff --git a/cocos/render-scene/scene/submodel.ts b/cocos/render-scene/scene/submodel.ts index f2533ed7c26..a1e51f42617 100644 --- a/cocos/render-scene/scene/submodel.ts +++ b/cocos/render-scene/scene/submodel.ts @@ -32,6 +32,7 @@ import { DescriptorSet, DescriptorSetInfo, Device, InputAssembler, Texture, Text import { errorID, Mat4, cclegacy } from '../../core'; import { getPhaseID } from '../../rendering/pass-phase'; import { Root } from '../../root'; +import { MacroRecord } from '../core/pass-utils'; const _dsInfo = new DescriptorSetInfo(null!); const MAX_PASS_COUNT = 8; @@ -54,6 +55,7 @@ export class SubModel { protected _shaders: Shader[] | null = null; protected _subMesh: RenderingSubMesh | null = null; protected _patches: IMacroPatch[] | null = null; + protected _globalPatches: MacroRecord | null = null; protected _priority: RenderPriority = RenderPriority.DEFAULT; protected _inputAssembler: InputAssembler | null = null; protected _descriptorSet: DescriptorSet | null = null; @@ -294,6 +296,7 @@ export class SubModel { this.priority = RenderPriority.DEFAULT; this._patches = null; + this._globalPatches = null; this._subMesh = null; this._passes = null; @@ -324,6 +327,20 @@ export class SubModel { * @zh 管线更新回调 */ public onPipelineStateChanged (): void { + const root = cclegacy.director.root as Root; + const pipeline = root.pipeline; + const pipelinePatches = Object.entries(pipeline.macros); + if (!this._globalPatches && pipelinePatches.length === 0) { + return; + } else if (pipelinePatches.length) { + if (this._globalPatches && pipelinePatches.length === this._globalPatches.length) { + const globalPatches = Object.entries(this._globalPatches); + const patchesStateUnchanged = JSON.stringify(pipelinePatches.sort()) === JSON.stringify(globalPatches.sort()); + if (patchesStateUnchanged) return; + } + } + this._globalPatches = pipeline.macros; + const passes = this._passes; if (!passes) { return; } diff --git a/native/cocos/scene/Define.h b/native/cocos/scene/Define.h index 41920f1882e..e2cef2df8b2 100644 --- a/native/cocos/scene/Define.h +++ b/native/cocos/scene/Define.h @@ -24,6 +24,8 @@ #pragma once +#include + #include "base/std/container/string.h" #include "renderer/core/PassUtils.h" @@ -34,6 +36,17 @@ struct IMacroPatch { ccstd::string name; MacroValue value; + IMacroPatch() = default; + IMacroPatch(const ccstd::string& n, const MacroValue& v) { + name = n; + value = v; + } + + IMacroPatch(const std::pair& pair) { + name = pair.first; + value = pair.second; + } + bool operator==(const IMacroPatch& rhs) const { return rhs.name == name && rhs.value == value; } diff --git a/native/cocos/scene/SubModel.cpp b/native/cocos/scene/SubModel.cpp index d376bbdac5c..e244b169319 100644 --- a/native/cocos/scene/SubModel.cpp +++ b/native/cocos/scene/SubModel.cpp @@ -199,6 +199,7 @@ void SubModel::destroy() { _priority = pipeline::RenderPriority::DEFAULT; _patches.clear(); + _globalPatches.clear(); _subMesh = nullptr; _passes.reset(); _shaders.clear(); @@ -208,6 +209,20 @@ void SubModel::destroy() { } void SubModel::onPipelineStateChanged() { + const auto *pipeline = Root::getInstance()->getPipeline(); + ccstd::vector pipelinePatches(pipeline->getMacros().begin(), pipeline->getMacros().end()); + ccstd::vector globalPatches(_globalPatches.begin(), _globalPatches.end()); + if (pipelinePatches.empty() && globalPatches.empty()) { + return; + } + + std::sort(pipelinePatches.begin(), pipelinePatches.end(), IMacroPatch::compare); + std::sort(globalPatches.begin(), globalPatches.end(), IMacroPatch::compare); + if (std::equal(std::begin(pipelinePatches), std::end(pipelinePatches), std::begin(globalPatches), std::end(globalPatches))) { + return; + } + _globalPatches = pipeline->getMacros(); + const auto &passes = *_passes; if (passes.empty()) return; diff --git a/native/cocos/scene/SubModel.h b/native/cocos/scene/SubModel.h index 3f2104f803b..f92d9fffee4 100644 --- a/native/cocos/scene/SubModel.h +++ b/native/cocos/scene/SubModel.h @@ -114,6 +114,7 @@ class SubModel : public RefCounted { IntrusivePtr _subMesh; InstancedAttributeBlock _instancedAttributeBlock{}; + MacroRecord _globalPatches; ccstd::vector _patches; ccstd::vector> _shaders; diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index 73b03f4ddd3..6464584d826 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -105,6 +105,8 @@ using namespace cc; %ignore cc::Root::getEventProcessor; %ignore cc::Node::getEventProcessor; +%ignore cc::scene::IMacroPatch::IMacroPatch(const std::pair&); + %ignore cc::Node::setRTSInternal; %ignore cc::Node::setRTS; //FIXME: These methods binding code will generate SwigValueWrapper type which is not supported now. From b42a2faf6c15675bf033216e214144fc792827c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 7 Aug 2023 11:27:02 +0800 Subject: [PATCH 104/232] Optimize pack-manager for style&lint (#15872) * Optimize pack-manager for style&lint * Fix --- cocos/asset/asset-manager/pack-manager.ts | 59 +++++++++++++++-------- 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/cocos/asset/asset-manager/pack-manager.ts b/cocos/asset/asset-manager/pack-manager.ts index ae4275b2073..cab8fbc8aa7 100644 --- a/cocos/asset/asset-manager/pack-manager.ts +++ b/cocos/asset/asset-manager/pack-manager.ts @@ -25,17 +25,22 @@ import { ImageAsset } from '../assets/image-asset'; import { Texture2D } from '../assets/texture-2d'; import { packCustomObjData, unpackJSONs } from '../../serialization/deserialize'; -import { error, errorID, js } from '../../core'; +import { assertIsTrue, error, errorID, js } from '../../core'; import Cache from './cache'; import downloader from './downloader'; import { transform } from './helper'; import RequestItem from './request-item'; import { files } from './shared'; -export type Unpacker = (packUuid: string[], data: any, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void; +export type Unpacker = ( + packUuid: string[], + data: any, + options: Record, + onComplete: ((err: Error | null, data?: any) => void), +) => void; interface IUnpackRequest { - onComplete: ((err: Error | null, data?: any | null) => void); + onComplete: ((err: Error | null, data?: any) => void); id: string; } @@ -73,12 +78,17 @@ export class PackManager { * }); * */ - public unpackJson (pack: string[], json: any, options: Record, onComplete: ((err: Error | null, data?: Record | null) => void)): void { - let out = js.createMap(true); + public unpackJson ( + pack: string[], + json: any, + options: Record, + onComplete: ((err: Error | null, data?: Record | null) => void), + ): void { + const out: Record = js.createMap(true); let err: Error | null = null; if (Array.isArray(json)) { - json = unpackJSONs(json as any); + json = unpackJSONs(json as unknown as Parameters[0]); if (json.length !== pack.length) { errorID(4915); @@ -107,7 +117,8 @@ export class PackManager { } } else { err = new Error('unmatched type pack!'); - out = null; + onComplete(err, null); + return; } } onComplete(err, out); @@ -170,7 +181,13 @@ export class PackManager { * }); * */ - public unpack (pack: string[], data: any, type: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { + public unpack ( + pack: string[], + data: any, + type: string, + options: Record, + onComplete: ((err: Error | null, data?: any) => void), + ): void { if (!data) { onComplete(new Error('package data is wrong!')); return; @@ -200,7 +217,7 @@ export class PackManager { * packManager.load(requestItem, null, (err, data) => console.log(err)); * */ - public load (item: RequestItem, options: Record | null, onComplete: ((err: Error | null, data?: any | null) => void)): void { + public load (item: RequestItem, options: Record | null, onComplete: ((err: Error | null, data?: any) => void)): void { // if not in any package, download as uausl if (item.isNative || !item.info || !item.info.packs) { downloader.download(item.id, item.url, item.ext, item.options, onComplete); @@ -215,35 +232,39 @@ export class PackManager { const packs = item.info.packs; // find a loading package - let pack = packs.find((val): boolean => this._loading.has(val.uuid)); + const loadingPack = packs.find((val): boolean => this._loading.has(val.uuid)); - if (pack) { - this._loading.get(pack.uuid)!.push({ onComplete, id: item.id }); + if (loadingPack) { + const req = this._loading.get(loadingPack.uuid); + assertIsTrue(req); + req.push({ onComplete, id: item.id }); return; } // download a new package - pack = packs[0]; + const pack = packs[0]; this._loading.add(pack.uuid, [{ onComplete, id: item.id }]); // find the url of pack - const url = transform(pack.uuid, { ext: pack.ext, bundle: item.config!.name }) as string; + assertIsTrue(item.config); + const url = transform(pack.uuid, { ext: pack.ext, bundle: item.config.name }) as string; downloader.download(pack.uuid, url, pack.ext, item.options, (err, data): void => { - files.remove(pack!.uuid); + files.remove(pack.uuid); if (err) { error(err.message, err.stack); } // unpack package - this.unpack(pack!.packedUuids, data, pack!.ext, item.options, (err2, result): void => { + this.unpack(pack.packedUuids, data, pack.ext, item.options, (err2, result): void => { if (!err2) { for (const id in result) { files.add(id, result[id]); } } - const callbacks = this._loading.remove(pack!.uuid); - for (let i = 0, l = callbacks!.length; i < l; i++) { - const cb = callbacks![i]; + const callbacks = this._loading.remove(pack.uuid); + assertIsTrue(callbacks); + for (let i = 0, l = callbacks.length; i < l; i++) { + const cb = callbacks[i]; if (err || err2) { cb.onComplete(err || err2); continue; From 9f7bf8a8ebe96edd38d15b4d91cde206d9a1007e Mon Sep 17 00:00:00 2001 From: zhifenghu Date: Mon, 7 Aug 2023 13:41:48 +0800 Subject: [PATCH 105/232] =?UTF-8?q?Update=20utils.ts,=20replace=20the=20ra?= =?UTF-8?q?ndom=20function,=20to=20make=20particle=20scenes=E2=80=A6=20(#1?= =?UTF-8?q?5838)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update utils.ts, replace the random function, to make particle scenes support automated testing * core/math/utils.ts add method: setRandGenerator * core/math/utils.ts add method: setRandGenerator --------- Co-authored-by: 胡志锋 --- cocos/core/curves/gradient.ts | 6 +- cocos/core/math/utils.ts | 19 ++++++- cocos/particle-2d/particle-simulator-2d.ts | 58 ++++++++++---------- cocos/particle/animator/noise-module.ts | 6 +- cocos/particle/animator/texture-animation.ts | 12 ++-- 5 files changed, 57 insertions(+), 44 deletions(-) diff --git a/cocos/core/curves/gradient.ts b/cocos/core/curves/gradient.ts index 9ad938e15de..9d1b76ac11b 100644 --- a/cocos/core/curves/gradient.ts +++ b/cocos/core/curves/gradient.ts @@ -24,7 +24,7 @@ import { CCClass } from '../data'; import { Enum } from '../value-types'; -import { Color, lerp, repeat, EPSILON, approx } from '../math'; +import { Color, lerp, repeat, EPSILON, approx, random } from '../math'; const Mode = Enum({ Blend: 0, @@ -172,8 +172,8 @@ export class Gradient { * @returns @en Randomized color. @zh 随机生成的颜色。 */ public getRandomColor (out: Color): Color { - const c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)]; - const a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)]; + const c = this.colorKeys[Math.trunc(random() * this.colorKeys.length)]; + const a = this.alphaKeys[Math.trunc(random() * this.alphaKeys.length)]; out.set(c.color); out._set_a_unsafe(a.alpha); return out; diff --git a/cocos/core/math/utils.ts b/cocos/core/math/utils.ts index 0af2c7d624a..3b653aba193 100644 --- a/cocos/core/math/utils.ts +++ b/cocos/core/math/utils.ts @@ -31,6 +31,8 @@ const _d2r = Math.PI / 180.0; const _r2d = 180.0 / Math.PI; +let _random = Math.random; + export const HALF_PI = Math.PI * 0.5; export const TWO_PI = Math.PI * 2.0; @@ -121,7 +123,18 @@ export function toDegree (a: number): number { /** * @method random */ -export const random = Math.random; +export function random (): number { + return _random(); +} + +/** + * @en Set a custom random number generator, default to Math.random + * @zh 设置自定义随机数生成器,默认为 Math.random + * @param func custom random number generator + */ +export function setRandGenerator number> (func: TFunction): void { + _random = func; +} /** * @en Returns a floating-point random number between min (inclusive) and max (exclusive).
@@ -129,10 +142,10 @@ export const random = Math.random; * @method randomRange * @param min * @param max - * @return The random number. + * @return {Number} The random number. */ export function randomRange (min: number, max: number): number { - return Math.random() * (max - min) + min; + return random() * (max - min) + min; } /** diff --git a/cocos/particle-2d/particle-simulator-2d.ts b/cocos/particle-2d/particle-simulator-2d.ts index 2902322ea8a..96e68cf67b7 100644 --- a/cocos/particle-2d/particle-simulator-2d.ts +++ b/cocos/particle-2d/particle-simulator-2d.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { Vec2, Color, js, misc } from '../core'; +import { Vec2, Color, js, misc, random, IColorLike } from '../core'; import { vfmtPosUvColor, getComponentPerVertex } from '../2d/renderer/vertex-format'; import { PositionType, EmitterMode, START_SIZE_EQUAL_TO_END_SIZE, START_RADIUS_EQUAL_TO_END_RADIUS } from './define'; import { ParticleSystem2D } from './particle-system-2d'; @@ -150,12 +150,12 @@ export class Simulator { // Init particle // timeToLive // no negative life. prevent division by 0 - particle.timeToLive = psys.life + psys.lifeVar * (Math.random() - 0.5) * 2; + particle.timeToLive = psys.life + psys.lifeVar * (random() - 0.5) * 2; const timeToLive = particle.timeToLive = Math.max(0, particle.timeToLive); // position - particle.pos.x = psys.sourcePos.x + psys.posVar.x * (Math.random() - 0.5) * 2; - particle.pos.y = psys.sourcePos.y + psys.posVar.y * (Math.random() - 0.5) * 2; + particle.pos.x = psys.sourcePos.x + psys.posVar.x * (random() - 0.5) * 2; + particle.pos.y = psys.sourcePos.y + psys.posVar.y * (random() - 0.5) * 2; // Color let sr = 0; @@ -167,30 +167,30 @@ export class Simulator { const endColor = psys.endColor; const endColorVar = psys.endColorVar; - particle.color.r = sr = misc.clampf(startColor.r + startColorVar.r * (Math.random() - 0.5) * 2, 0, 255); - particle.color.g = sg = misc.clampf(startColor.g + startColorVar.g * (Math.random() - 0.5) * 2, 0, 255); - particle.color.b = sb = misc.clampf(startColor.b + startColorVar.b * (Math.random() - 0.5) * 2, 0, 255); - particle.color.a = sa = misc.clampf(startColor.a + startColorVar.a * (Math.random() - 0.5) * 2, 0, 255); - particle.deltaColor.r = (misc.clampf(endColor.r + endColorVar.r * (Math.random() - 0.5) * 2, 0, 255) - sr) / timeToLive; - particle.deltaColor.g = (misc.clampf(endColor.g + endColorVar.g * (Math.random() - 0.5) * 2, 0, 255) - sg) / timeToLive; - particle.deltaColor.b = (misc.clampf(endColor.b + endColorVar.b * (Math.random() - 0.5) * 2, 0, 255) - sb) / timeToLive; - particle.deltaColor.a = (misc.clampf(endColor.a + endColorVar.a * (Math.random() - 0.5) * 2, 0, 255) - sa) / timeToLive; + particle.color.r = sr = misc.clampf(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255); + particle.color.g = sg = misc.clampf(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255); + particle.color.b = sb = misc.clampf(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255); + particle.color.a = sa = misc.clampf(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255); + particle.deltaColor.r = (misc.clampf(endColor.r + endColorVar.r * (random() - 0.5) * 2, 0, 255) - sr) / timeToLive; + particle.deltaColor.g = (misc.clampf(endColor.g + endColorVar.g * (random() - 0.5) * 2, 0, 255) - sg) / timeToLive; + particle.deltaColor.b = (misc.clampf(endColor.b + endColorVar.b * (random() - 0.5) * 2, 0, 255) - sb) / timeToLive; + particle.deltaColor.a = (misc.clampf(endColor.a + endColorVar.a * (random() - 0.5) * 2, 0, 255) - sa) / timeToLive; // size - let startS = psys.startSize + psys.startSizeVar * (Math.random() - 0.5) * 2; + let startS = psys.startSize + psys.startSizeVar * (random() - 0.5) * 2; startS = Math.max(0, startS); // No negative value particle.size = startS; if (psys.endSize === START_SIZE_EQUAL_TO_END_SIZE) { particle.deltaSize = 0; } else { - let endS = psys.endSize + psys.endSizeVar * (Math.random() - 0.5) * 2; + let endS = psys.endSize + psys.endSizeVar * (random() - 0.5) * 2; endS = Math.max(0, endS); // No negative values particle.deltaSize = (endS - startS) / timeToLive; } // rotation - const startA = psys.startSpin + psys.startSpinVar * (Math.random() - 0.5) * 2; - const endA = psys.endSpin + psys.endSpinVar * (Math.random() - 0.5) * 2; + const startA = psys.startSpin + psys.startSpinVar * (random() - 0.5) * 2; + const endA = psys.endSpin + psys.endSpinVar * (random() - 0.5) * 2; particle.rotation = startA; particle.deltaRotation = (endA - startA) / timeToLive; @@ -202,18 +202,18 @@ export class Simulator { particle.aspectRatio = psys.aspectRatio || 1; // direction - const a = misc.degreesToRadians(psys.angle + this._worldRotation + psys.angleVar * (Math.random() - 0.5) * 2); + const a = misc.degreesToRadians(psys.angle + this._worldRotation + psys.angleVar * (random() - 0.5) * 2); // Mode Gravity: A if (psys.emitterMode === EmitterMode.GRAVITY) { - const s = psys.speed + psys.speedVar * (Math.random() - 0.5) * 2; + const s = psys.speed + psys.speedVar * (random() - 0.5) * 2; // direction particle.dir.x = Math.cos(a); particle.dir.y = Math.sin(a); particle.dir.multiplyScalar(s); // radial accel - particle.radialAccel = psys.radialAccel + psys.radialAccelVar * (Math.random() - 0.5) * 2; + particle.radialAccel = psys.radialAccel + psys.radialAccelVar * (random() - 0.5) * 2; // tangential accel - particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (Math.random() - 0.5) * 2; + particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (random() - 0.5) * 2; // rotation is dir if (psys.rotationIsDir) { particle.rotation = -misc.radiansToDegrees(Math.atan2(particle.dir.y, particle.dir.x)); @@ -221,12 +221,12 @@ export class Simulator { } else { // Mode Radius: B // Set the default diameter of the particle from the source position - const startRadius = psys.startRadius + psys.startRadiusVar * (Math.random() - 0.5) * 2; - const endRadius = psys.endRadius + psys.endRadiusVar * (Math.random() - 0.5) * 2; + const startRadius = psys.startRadius + psys.startRadiusVar * (random() - 0.5) * 2; + const endRadius = psys.endRadius + psys.endRadiusVar * (random() - 0.5) * 2; particle.radius = startRadius; particle.deltaRadius = (psys.endRadius === START_RADIUS_EQUAL_TO_END_RADIUS) ? 0 : (endRadius - startRadius) / timeToLive; particle.angle = a; - particle.degreesPerSecond = misc.degreesToRadians(psys.rotatePerS + psys.rotatePerSVar * (Math.random() - 0.5) * 2); + particle.degreesPerSecond = misc.degreesToRadians(psys.rotatePerS + psys.rotatePerSVar * (random() - 0.5) * 2); } } @@ -275,7 +275,7 @@ export class Simulator { const y1 = -halfHeight; const x2 = halfWidth; const y2 = halfHeight; - const rad = -misc.degreesToRadians(particle.rotation); + const rad = -misc.degreesToRadians(particle.rotation as number); const cr = Math.cos(rad); const sr = Math.sin(rad); // bl @@ -313,13 +313,13 @@ export class Simulator { vbuf[offset + 29] = 0; } // color - Color.toArray(vbuf, particle.color, offset + 5); - Color.toArray(vbuf, particle.color, offset + 14); - Color.toArray(vbuf, particle.color, offset + 23); - Color.toArray(vbuf, particle.color, offset + 32); + Color.toArray(vbuf, particle.color as IColorLike, offset + 5); + Color.toArray(vbuf, particle.color as IColorLike, offset + 14); + Color.toArray(vbuf, particle.color as IColorLike, offset + 23); + Color.toArray(vbuf, particle.color as IColorLike, offset + 32); } - public step (dt): void { + public step (dt: number): void { const assembler = this.sys.assembler!; const psys = this.sys; const node = psys.node; diff --git a/cocos/particle/animator/noise-module.ts b/cocos/particle/animator/noise-module.ts index b4106e54f90..0eb677aed3f 100644 --- a/cocos/particle/animator/noise-module.ts +++ b/cocos/particle/animator/noise-module.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { CCFloat, CCInteger, _decorator, Vec3 } from '../../core'; +import { CCFloat, CCInteger, _decorator, Vec3, random } from '../../core'; import { ParticleNoise } from '../noise'; import { Particle, PARTICLE_MODULE_NAME, ParticleModuleBase } from '../particle'; @@ -302,12 +302,12 @@ export class NoiseModule extends ParticleModuleBase { this.noise.setOctaves(this.octaves, this.octaveMultiplier, this.octaveScale); this.samplePosition.set(particle.position); - this.samplePosition.add3f(Math.random() * 1.0, Math.random() * 1.0, Math.random() * 1.0); + this.samplePosition.add3f(random() * 1.0, random() * 1.0, random() * 1.0); this.noise.setSamplePoint(this.samplePosition); this.noise.getNoiseParticle(); const noisePosition: Vec3 = this.noise.getResult(); - noisePosition.multiply3f(Math.random(), Math.random(), Math.random()); + noisePosition.multiply3f(random(), random(), random()); Vec3.add(particle.position, particle.position, noisePosition.multiplyScalar(dt)); } diff --git a/cocos/particle/animator/texture-animation.ts b/cocos/particle/animator/texture-animation.ts index a08dd4f5b05..fd15feccbc1 100644 --- a/cocos/particle/animator/texture-animation.ts +++ b/cocos/particle/animator/texture-animation.ts @@ -23,7 +23,7 @@ */ import { ccclass, tooltip, displayOrder, type, formerlySerializedAs, serializable, range } from 'cc.decorator'; -import { lerp, pseudoRandom, repeat, Enum } from '../../core'; +import { lerp, pseudoRandom, repeat, Enum, random, error } from '../../core'; import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle'; import CurveRange from './curve-range'; import { ModuleRandSeed } from '../enum'; @@ -117,7 +117,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { set mode (val) { if (val !== Mode.Grid) { - console.error('particle texture animation\'s sprites is not supported!'); + error('particle texture animation\'s sprites is not supported!'); } } @@ -207,7 +207,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { } set flipU (val) { - console.error('particle texture animation\'s flipU is not supported!'); + error('particle texture animation\'s flipU is not supported!'); } @serializable @@ -218,7 +218,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { } set flipV (val) { - console.error('particle texture animation\'s flipV is not supported!'); + error('particle texture animation\'s flipV is not supported!'); } @serializable @@ -229,7 +229,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { } set uvChannelMask (val) { - console.error('particle texture animation\'s uvChannelMask is not supported!'); + error('particle texture animation\'s uvChannelMask is not supported!'); } /** @@ -263,7 +263,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { * @internal */ public init (p: Particle): void { - p.startRow = Math.floor(Math.random() * this.numTilesY); + p.startRow = Math.floor(random() * this.numTilesY); } /** From 5886a0066d040b71e4b5105030cbb2a9dfd792b2 Mon Sep 17 00:00:00 2001 From: oahc09 Date: Mon, 7 Aug 2023 14:33:07 +0800 Subject: [PATCH 106/232] fix:camera trackingtype/cameratype jsb attribute lost (#15867) (used in xr) --- native/tools/swig-config/scene.i | 2 ++ 1 file changed, 2 insertions(+) diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index 6464584d826..39aa6e93646 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -445,6 +445,8 @@ using namespace cc; %attribute(cc::scene::Camera, cc::pipeline::GeometryRenderer *, geometryRenderer, getGeometryRenderer); %attribute(cc::scene::Camera, uint32_t, systemWindowId, getSystemWindowId); %attribute(cc::scene::Camera, cc::scene::CameraUsage, cameraUsage, getCameraUsage, setCameraUsage); +%attribute(cc::scene::Camera, cc::scene::TrackingType, trackingType, getTrackingType, setTrackingType); +%attribute(cc::scene::Camera, cc::scene::CameraType, cameraType, getCameraType, setCameraType); %attribute(cc::scene::RenderScene, ccstd::string&, name, getName); %attribute(cc::scene::RenderScene, ccstd::vector>&, cameras, getCameras); From 29bd5d6aa4bdc820e27a2f044b58ebddc8c18971 Mon Sep 17 00:00:00 2001 From: oahc09 Date: Mon, 7 Aug 2023 14:33:43 +0800 Subject: [PATCH 107/232] improve:remove constraint-layout dependency on spaces template (#15868) --- templates/xr-spaces/template/app/build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/templates/xr-spaces/template/app/build.gradle b/templates/xr-spaces/template/app/build.gradle index 5d056b6b99e..2c4adb6f9cd 100644 --- a/templates/xr-spaces/template/app/build.gradle +++ b/templates/xr-spaces/template/app/build.gradle @@ -108,7 +108,6 @@ dependencies { implementation 'androidx.navigation:navigation-ui-ktx:2.4.2' implementation 'androidx.navigation:navigation-fragment-ktx:2.4.2' implementation 'com.google.android.material:material:1.3.0' - implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.31' // spaces controller implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) From b7ad5b1e6b2c16e96a841614739397930c8779e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Mon, 7 Aug 2023 15:23:45 +0800 Subject: [PATCH 108/232] fix skybox model not updated when onGlobalPipelineMacroChange (#15886) --- cocos/root.ts | 4 ++++ native/cocos/core/Root.cpp | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/cocos/root.ts b/cocos/root.ts index 99c2d28dd60..17c61a1b5b8 100644 --- a/cocos/root.ts +++ b/cocos/root.ts @@ -451,6 +451,10 @@ export class Root { this._scenes[i].onGlobalPipelineStateChanged(); } + if (this._pipeline!.pipelineSceneData.skybox.enabled) { + this._pipeline!.pipelineSceneData.skybox.model!.onGlobalPipelineStateChanged(); + } + this._pipeline!.onGlobalPipelineStateChanged(); } diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 928d838f28c..a08d9d8fbca 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -48,6 +48,7 @@ #include "scene/Camera.h" #include "scene/DirectionalLight.h" #include "scene/SpotLight.h" +#include "scene/Skybox.h" namespace cc { @@ -358,6 +359,11 @@ void Root::onGlobalPipelineStateChanged() { scene->onGlobalPipelineStateChanged(); } + if (_pipelineRuntime->getPipelineSceneData()->getSkybox()->isEnabled()) + { + _pipelineRuntime->getPipelineSceneData()->getSkybox()->getModel()->onGlobalPipelineStateChanged(); + } + _pipelineRuntime->onGlobalPipelineStateChanged(); } From 592432c70e245c4c6aef1d40962db807bbbc7a28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Tue, 8 Aug 2023 18:40:38 +0800 Subject: [PATCH 109/232] [Optimize] compiled deserialization related code (#15892) * Typing compiled deserialize * Optimize code structure * Rename * Tweak * Tweak * Update --- .../compiled/builtin-value-type.ts | 129 +++++++ cocos/serialization/deserialize-dynamic.ts | 12 +- .../deserialize-type-utilities.ts | 29 ++ cocos/serialization/deserialize.ts | 348 +++++++----------- editor/exports/serialization.ts | 4 + 5 files changed, 298 insertions(+), 224 deletions(-) create mode 100644 cocos/serialization/compiled/builtin-value-type.ts create mode 100644 cocos/serialization/deserialize-type-utilities.ts diff --git a/cocos/serialization/compiled/builtin-value-type.ts b/cocos/serialization/compiled/builtin-value-type.ts new file mode 100644 index 00000000000..c6b4afb7e72 --- /dev/null +++ b/cocos/serialization/compiled/builtin-value-type.ts @@ -0,0 +1,129 @@ +import { JSB } from 'internal:constants'; +import { Vec2, Vec3, Vec4, Color, Size, Rect, Quat, Mat4, assertIsTrue, ValueType } from '../../core'; +import type { IRuntimeFileData } from '../deserialize'; + +/** + * If a value type is not registered in this list, it will be serialized as plain class. + */ +const constructorMap = [ + Vec2, // 0 + Vec3, // 1 + Vec4, // 2 + Quat, // 3 + Color, // 4 + Size, // 5 + Rect, // 6 + Mat4, // 7 +] as const; + +type ConstructorMap = typeof constructorMap; + +export type ValueTypeData = [ + typeIndex: number, + ...values: number[], +]; + +type SetterInput = [reserved: number, ...values: number[]]; + +type Setter = (value: T, result: SetterInput) => void; + +type SetterMapImpl = T extends readonly [infer Head, ...infer Tails] + ? Head extends abstract new (...args: any) => any + ? readonly [Setter>, ...SetterMapImpl] + : readonly [Head, ...SetterMapImpl] + : readonly []; + +type SetterMap = SetterMapImpl; + +function vec4LikeSetter (obj: T, data: SetterInput): void { + obj.x = data[1]; + obj.y = data[2]; + obj.z = data[3]; + obj.w = data[4]; +} + +const setterMap: SetterMap = [ + (obj: Vec2, data: SetterInput): void => { + obj.x = data[1]; + obj.y = data[2]; + }, + (obj: Vec3, data: SetterInput): void => { + obj.x = data[1]; + obj.y = data[2]; + obj.z = data[3]; + }, + vec4LikeSetter, // Vec4 + vec4LikeSetter, // Quat + (obj: Color, data: SetterInput): void => { + obj._val = data[1]; + }, + (obj: Size, data: SetterInput): void => { + obj.width = data[1]; + obj.height = data[2]; + }, + (obj: Rect, data: SetterInput): void => { + obj.x = data[1]; + obj.y = data[2]; + obj.width = data[3]; + obj.height = data[4]; + }, + (obj: Mat4, data: SetterInput): void => { + Mat4.fromArray(obj, data, 1); + }, +]; + +export function serializeBuiltinValueType (obj: ValueType): ValueTypeData | null { + const ctor = obj.constructor; + const typeId = (constructorMap as readonly any[]).indexOf(ctor); + switch (ctor) { + case Vec2: + return [typeId, (obj as Vec2).x, (obj as Vec2).y]; + case Vec3: + return [typeId, (obj as Vec3).x, (obj as Vec3).y, (obj as Vec3).z]; + case Vec4: + case Quat: + return [typeId, (obj as Vec4).x, (obj as Vec4).y, (obj as Vec4).z, (obj as Vec4).w]; + case Color: + return [typeId, (obj as Color)._val]; + case Size: + return [typeId, (obj as Size).width, (obj as Size).height]; + case Rect: + return [typeId, (obj as Rect).x, (obj as Rect).y, (obj as Rect).width, (obj as Rect).height]; + case Mat4: { + const res: ValueTypeData = new Array(1 + 16) as ValueTypeData; + res[0] = typeId; + Mat4.toArray(res, obj as Mat4, 1); + return res; + } + default: + return null; + } +} + +export function deserializeBuiltinValueType (data: IRuntimeFileData, owner: any, key: string, value: ValueTypeData): void { + const typeIndex = value[0]; + assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length); + const object = new (constructorMap[typeIndex])(); + const setter = setterMap[typeIndex] as Setter; + setter(object, value); + owner[key] = object; +} + +export function deserializeBuiltinValueTypeInto (data: IRuntimeFileData, owner: any, key: string, value: ValueTypeData): void { + const typeIndex = value[0]; + assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length); + if (JSB) { + // The native layer type corresponding to the BuiltinValueTypes has not been exported exclude Color, + // so we need to set to native after value changed. + const tmp = owner[key]; + const setter = setterMap[typeIndex] as Setter; + setter(tmp, value); + owner[key] = tmp; + } else { + const object = owner[key]; + const setter = setterMap[typeIndex] as Setter; + setter(object, value); + } +} + +export {}; diff --git a/cocos/serialization/deserialize-dynamic.ts b/cocos/serialization/deserialize-dynamic.ts index 9b26fd27be5..d15266d3ad8 100644 --- a/cocos/serialization/deserialize-dynamic.ts +++ b/cocos/serialization/deserialize-dynamic.ts @@ -657,10 +657,12 @@ class _Deserializer { } const rawDeserialize: CompiledDeserializeFn = deserialize; - deserialize = function (deserializer: _Deserializer, + deserialize = function ( + deserializer: _Deserializer, object: Record, deserialized: Record, - constructor: AnyFunction): void { + constructor: AnyFunction, + ): void { rawDeserialize(deserializer, object, deserialized, constructor); if (!object._$erialized) { error(`Unable to stash previously serialized data. ${JSON.stringify(deserialized)}`); @@ -828,13 +830,15 @@ class _Deserializer { } } -export function deserializeDynamic (data: SerializedData | CCON, details: Details, options?: { +export interface DeserializeDynamicOptions { classFinder?: ClassFinder; ignoreEditorOnly?: boolean; createAssetRefs?: boolean; customEnv?: unknown; reportMissingClass?: ReportMissingClass; -}): any { +} + +export function deserializeDynamic (data: SerializedData | CCON, details: Details, options?: DeserializeDynamicOptions): any { options = options || {}; const classFinder = options.classFinder || js.getClassById; const createAssetRefs = options.createAssetRefs || sys.platform === Platform.EDITOR_CORE; diff --git a/cocos/serialization/deserialize-type-utilities.ts b/cocos/serialization/deserialize-type-utilities.ts new file mode 100644 index 00000000000..ddff611339b --- /dev/null +++ b/cocos/serialization/deserialize-type-utilities.ts @@ -0,0 +1,29 @@ +type EnumMapImpl< + Map extends Record, + _, + Minus1 extends any[] = [], + Index extends keyof Map = Minus1['length'] +> = [ + ...(Minus1 extends [infer _2, ...infer Remain] ? EnumMapImpl : []), + // Index, + Map[Index], +]; + +type MapTuple, T> = T extends [infer _1, ...infer Remain] ? EnumMapImpl : never; + +type Tuple = R['length'] extends N ? R : Tuple; + +export type MapEnum, Length extends number> = MapTuple>; + +type TupleSplit = + O['length'] extends N ? [O, T] : T extends readonly [infer F, ...infer R] ? + TupleSplit : [O, T]; + +type TakeFirst = + TupleSplit[0]; + +type SkipFirst = + TupleSplit[1]; + +export type TupleSlice = + SkipFirst, S>; diff --git a/cocos/serialization/deserialize.ts b/cocos/serialization/deserialize.ts index 05b6c7723a9..8f88ae4091a 100644 --- a/cocos/serialization/deserialize.ts +++ b/cocos/serialization/deserialize.ts @@ -23,18 +23,21 @@ */ import { EDITOR, TEST, PREVIEW, DEBUG, JSB, DEV } from 'internal:constants'; -import { cclegacy, ValueType, Vec2, Vec3, Vec4, Color, Size, Rect, Quat, Mat4, errorID, getError, js } from '../core'; +import { cclegacy, errorID, getError, js, assertIsTrue } from '../core'; -import { deserializeDynamic, parseUuidDependenciesDynamic } from './deserialize-dynamic'; +import { deserializeDynamic, DeserializeDynamicOptions, parseUuidDependenciesDynamic } from './deserialize-dynamic'; import { Asset } from '../asset/assets/asset'; -import type { CCON } from './ccon'; import type { CompiledDeserializeFn } from './deserialize-dynamic'; import { reportMissingClass as defaultReportMissingClass } from './report-missing-class'; +import type { MapEnum, TupleSlice } from './deserialize-type-utilities'; + const FORCE_COMPILED = false; // TODO: BUILD; +import { deserializeBuiltinValueType, deserializeBuiltinValueTypeInto } from './compiled/builtin-value-type'; + /** ************************************************************************** * BUILT-IN TYPES / CONSTAINTS *************************************************************************** */ @@ -42,102 +45,6 @@ const FORCE_COMPILED = false; // TODO: BUILD; const SUPPORT_MIN_FORMAT_VERSION = 1; const EMPTY_PLACEHOLDER = 0; -// Used for Data.ValueType. -// If a value type is not registered in this list, it will be serialized to Data.Class. -const BuiltinValueTypes: (typeof ValueType)[] = [ - Vec2, // 0 - Vec3, // 1 - Vec4, // 2 - Quat, // 3 - Color, // 4 - Size, // 5 - Rect, // 6 - Mat4, // 7 -]; - -// Used for Data.ValueTypeCreated. -function BuiltinValueTypeParsers_xyzw (obj: Vec4 | Quat, data: number[]): void { - obj.x = data[1]; - obj.y = data[2]; - obj.z = data[3]; - obj.w = data[4]; -} -const BuiltinValueTypeSetters: ((obj: any, data: number[]) => void)[] = [ - (obj: Vec2, data: number[]): void => { - obj.x = data[1]; - obj.y = data[2]; - }, - (obj: Vec3, data: number[]): void => { - obj.x = data[1]; - obj.y = data[2]; - obj.z = data[3]; - }, - BuiltinValueTypeParsers_xyzw, // Vec4 - BuiltinValueTypeParsers_xyzw, // Quat - (obj: Color, data: number[]): void => { - obj._val = data[1]; - }, - (obj: Size, data: number[]): void => { - obj.width = data[1]; - obj.height = data[2]; - }, - (obj: Rect, data: number[]): void => { - obj.x = data[1]; - obj.y = data[2]; - obj.width = data[3]; - obj.height = data[4]; - }, - (obj: Mat4, data: number[]): void => { - Mat4.fromArray(obj, data, 1); - }, -]; - -function serializeBuiltinValueTypes (obj: ValueType): IValueTypeData | null { - const ctor = obj.constructor as typeof ValueType; - const typeId = BuiltinValueTypes.indexOf(ctor); - switch (ctor) { - case Vec2: - return [typeId, (obj as Vec2).x, (obj as Vec2).y]; - case Vec3: - return [typeId, (obj as Vec3).x, (obj as Vec3).y, (obj as Vec3).z]; - case Vec4: - case Quat: - return [typeId, (obj as Vec4).x, (obj as Vec4).y, (obj as Vec4).z, (obj as Vec4).w]; - case Color: - return [typeId, (obj as Color)._val]; - case Size: - return [typeId, (obj as Size).width, (obj as Size).height]; - case Rect: - return [typeId, (obj as Rect).x, (obj as Rect).y, (obj as Rect).width, (obj as Rect).height]; - case Mat4: { - const res: IValueTypeData = new Array(1 + 16) as IValueTypeData; - res[VALUETYPE_SETTER] = typeId; - Mat4.toArray(res, obj as Mat4, 1); - return res; - } - default: - return null; - } -} - -// // TODO: Used for Data.TypedArray. -// const TypedArrays = [ -// Float32Array, -// Float64Array, -// -// Int8Array, -// Int16Array, -// Int32Array, -// -// Uint8Array, -// Uint16Array, -// Uint32Array, -// -// Uint8ClampedArray, -// // BigInt64Array, -// // BigUint64Array, -// ]; - /** ************************************************************************** * TYPE DECLARATIONS *************************************************************************** */ @@ -217,12 +124,6 @@ const enum DataTypeID { // Common TypedArray for legacyCC.Node only. Never be null. TRS, - // // From the point of view of simplified implementation, - // // it is not supported to deserialize TypedArray that is initialized to null in the constructor. - // // Also, the length of TypedArray cannot be changed. - // // Developers will rarely manually assign a null. - // TypedArray, - // ValueType without default value (in arrays, dictionaries). // Developers will rarely manually assign a null. ValueType, @@ -257,7 +158,6 @@ interface DataTypes { [DataTypeID.ValueTypeCreated]: IValueTypeData; [DataTypeID.AssetRefByInnerObj]: number; [DataTypeID.TRS]: ITRSData; - // [DataTypeID.TypedArray]: Array; [DataTypeID.ValueType]: IValueTypeData; [DataTypeID.Array_Class]: DataTypes[DataTypeID.Class][]; [DataTypeID.CustomizedClass]: ICustomObjectData; @@ -355,7 +255,6 @@ interface ICustomObjectData extends Array { [CUSTOM_OBJ_DATA_CONTENT]: ICustomObjectDataContent; } -const VALUETYPE_SETTER = 0; type IValueTypeData = [ // Predefined parsing function index number, @@ -400,13 +299,6 @@ export declare namespace deserialize.Internal { export type IArrayData_ = IArrayData; } -// const TYPEDARRAY_TYPE = 0; -// const TYPEDARRAY_ELEMENTS = 1; -// interface ITypedArrayData extends Array { -// [TYPEDARRAY_TYPE]: number, -// [TYPEDARRAY_ELEMENTS]: number[], -// } - const enum Refs { EACH_RECORD_LENGTH = 3, OWNER_OFFSET = 0, @@ -450,9 +342,9 @@ const enum File { } // Main file structure -interface IFileData extends Array { +interface IFileDataMap { // version - [File.Version]: number | FileInfo | any; + [File.Version]: number; // Shared data area, the higher the number of references, the higher the position @@ -481,13 +373,40 @@ interface IFileData extends Array { [File.DependUuidIndices]: (StringIndex|string)[]; } -// type Body = Pick -type Shared = Pick; -const PACKED_SECTIONS = File.Instances; -interface IPackedFileData extends Shared { - [PACKED_SECTIONS]: IFileData[]; +type IFileData = MapEnum<{ + [x in keyof IFileDataMap as `${x}`]: IFileDataMap[x]; +}, 11 /* Currently we should manually specify the enumerators count. */>; + +type IRuntimeFileDataMap = Omit & { + [File.Context]: FileInfo & DeserializeContext; } +/** + * At runtime, we intruded the original file data and injected some helpers. + */ +export type IRuntimeFileData = MapEnum<{ + [x in keyof IRuntimeFileDataMap as `${x}`]: IRuntimeFileDataMap[x]; +}, 11 /* Currently we should manually specify the enumerators count. */>; + +type IDeserializeInput = IFileData | IRuntimeFileData; + +type ISharedData = TupleSlice; + +type IPackedFileSection = [ + ...document: TupleSlice, +]; + +const PACKED_SECTIONS = File.Instances; + +type IPackedFileData = [ + /** Version. */ + version: number, + + ...shared: ISharedData, + + sections: IPackedFileSection[], +]; + export declare namespace deserialize.Internal { export import Refs_ = Refs; export type IRefs_ = IRefs; @@ -500,13 +419,17 @@ interface ICustomHandler { result: Details, customEnv: any, } -type ClassFinder = (type: string) => AnyCtor; +type ClassFinder = deserialize.ClassFinder; + +interface DeserializeContext extends ICustomHandler { + _version?: number; +} interface IOptions extends Partial { classFinder?: ClassFinder; - reportMissingClass: deserialize.ReportMissingClass; - _version?: number; + reportMissingClass?: deserialize.ReportMissingClass; } + interface ICustomClass { _deserialize?: (content: any, context: ICustomHandler) => void; } @@ -527,21 +450,21 @@ export class Details { * @zh * 对象列表,其中每个对象有属性需要通过 uuid 进行资源加载 */ - uuidObjList: IFileData[File.DependObjs] | null = null; + uuidObjList: IRuntimeFileData[File.DependObjs] | null = null; /** * @en * the corresponding field name which referenced to the asset * @zh * 引用着资源的字段名称 */ - uuidPropList: IFileData[File.DependKeys] | null = null; + uuidPropList: IRuntimeFileData[File.DependKeys] | null = null; /** * @en * list of the depends assets' uuid * @zh * 依赖资源的 uuid 列表 */ - uuidList: IFileData[File.DependUuidIndices] | null = null; + uuidList: IRuntimeFileData[File.DependUuidIndices] | null = null; /** * @en @@ -566,7 +489,7 @@ export class Details { * @method init * @param {Object} data */ - init (data?: IFileData): void { + init (data?: IDeserializeInput): void { if (FORCE_COMPILED || data) { this.uuidObjList = data![File.DependObjs]; this.uuidPropList = data![File.DependKeys]; @@ -641,7 +564,7 @@ if (EDITOR || TEST) { }; } -export function dereference (refs: IRefs, instances: IFileData[File.Instances], strings: IFileData[File.SharedStrings]): void { +export function dereference (refs: IRefs, instances: IRuntimeFileData[File.Instances], strings: IRuntimeFileData[File.SharedStrings]): void { const dataLength = refs.length - 1; let i = 0; // owner is object @@ -673,7 +596,7 @@ export function dereference (refs: IRefs, instances: IFileData[File.Instances], // -function deserializeCCObject (data: IFileData, objectData: IClassObjectData): Record { +function deserializeCCObject (data: IRuntimeFileData, objectData: IClassObjectData): Record { const mask = data[File.SharedMasks][objectData[OBJ_DATA_MASK]]; const clazz = mask[MASK_CLASS]; const ctor = clazz[CLASS_TYPE] as Exclude; @@ -707,7 +630,7 @@ function deserializeCCObject (data: IFileData, objectData: IClassObjectData): Re return obj; } -function deserializeCustomCCObject (data: IFileData, ctor: Ctor, value: ICustomObjectDataContent): ICustomClass { +function deserializeCustomCCObject (data: IRuntimeFileData, ctor: Ctor, value: ICustomObjectDataContent): ICustomClass { // eslint-disable-next-line new-cap const obj = new ctor(); if (obj._deserialize) { @@ -720,13 +643,13 @@ function deserializeCustomCCObject (data: IFileData, ctor: Ctor, v // Parse Functions -type ParseFunction = (data: IFileData, owner: any, key: string, value: T) => void; +type ParseFunction = (data: IRuntimeFileData, owner: any, key: string, value: T) => void; -function assignSimple (data: IFileData, owner: any, key: string, value: DataTypes[DataTypeID.SimpleType]): void { +function assignSimple (data: IRuntimeFileData, owner: any, key: string, value: DataTypes[DataTypeID.SimpleType]): void { owner[key] = value; } -function assignInstanceRef (data: IFileData, owner: any, key: string, value: InstanceBnotReverseIndex): void { +function assignInstanceRef (data: IRuntimeFileData, owner: any, key: string, value: InstanceBnotReverseIndex): void { if (value >= 0) { owner[key] = data[File.Instances][value]; } else { @@ -735,7 +658,7 @@ function assignInstanceRef (data: IFileData, owner: any, key: string, value: Ins } function genArrayParser (parser: ParseFunction): ParseFunction { - return (data: IFileData, owner: any, key: string, value: T[]): void => { + return (data: IRuntimeFileData, owner: any, key: string, value: T[]): void => { for (let i = 0; i < value.length; ++i) { parser(data, value, i as unknown as string, value[i]); } @@ -743,46 +666,26 @@ function genArrayParser (parser: ParseFunction): ParseFunction { }; } -function parseAssetRefByInnerObj (data: IFileData, owner: any, key: string, value: number): void { +function parseAssetRefByInnerObj (data: IRuntimeFileData, owner: any, key: string, value: number): void { owner[key] = null; data[File.DependObjs][value] = owner; } -function parseClass (data: IFileData, owner: any, key: string, value: IClassObjectData): void { +function parseClass (data: IRuntimeFileData, owner: any, key: string, value: IClassObjectData): void { owner[key] = deserializeCCObject(data, value); } -function parseCustomClass (data: IFileData, owner: any, key: string, value: ICustomObjectData): void { +function parseCustomClass (data: IRuntimeFileData, owner: any, key: string, value: ICustomObjectData): void { const ctor = data[File.SharedClasses][value[CUSTOM_OBJ_DATA_CLASS]] as CCClassConstructor; owner[key] = deserializeCustomCCObject(data, ctor, value[CUSTOM_OBJ_DATA_CONTENT]); } -function parseValueTypeCreated (data: IFileData, owner: any, key: string, value: IValueTypeData): void { - /**BuiltinValueTypes index: Vec2=0, Vec3=1, Vec4=2, Quat=3, Color=4, Size=5, Rect=6, Mat4=7 - The native layer type corresponding to the BuiltinValueTypes has not been exported exclude Color, - so we need to set to native after value changed - * */ - if (JSB) { - const tmp = owner[key]; - BuiltinValueTypeSetters[value[VALUETYPE_SETTER]](tmp, value); - owner[key] = tmp; - } else { - BuiltinValueTypeSetters[value[VALUETYPE_SETTER]](owner[key], value); - } -} - -function parseValueType (data: IFileData, owner: any, key: string, value: IValueTypeData): void { - const val: ValueType = new BuiltinValueTypes[value[VALUETYPE_SETTER]](); - BuiltinValueTypeSetters[value[VALUETYPE_SETTER]](val, value); - owner[key] = val; -} - -function parseTRS (data: IFileData, owner: any, key: string, value: ITRSData): void { +function parseTRS (data: IRuntimeFileData, owner: any, key: string, value: ITRSData): void { const typedArray = owner[key] as (Float32Array | Float64Array); typedArray.set(value); } -function parseDict (data: IFileData, owner: any, key: string, value: IDictData): void { +function parseDict (data: IRuntimeFileData, owner: any, key: string, value: IDictData): void { const dict = value[DICT_JSON_LAYOUT]; owner[key] = dict; for (let i = DICT_JSON_LAYOUT + 1; i < value.length; i += 3) { @@ -794,7 +697,7 @@ function parseDict (data: IFileData, owner: any, key: string, value: IDictData): } } -function parseArray (data: IFileData, owner: any, key: string, value: IArrayData): void { +function parseArray (data: IRuntimeFileData, owner: any, key: string, value: IArrayData): void { const array = value[ARRAY_ITEM_VALUES]; for (let i = 0; i < array.length; ++i) { const subValue = array[i]; @@ -808,17 +711,6 @@ function parseArray (data: IFileData, owner: any, key: string, value: IArrayData owner[key] = array; } -// function parseTypedArray (data: IFileData, owner: any, key: string, value: ITypedArrayData) { -// let val: ValueType = new TypedArrays[value[TYPEDARRAY_TYPE]](); -// BuiltinValueTypeSetters[value[VALUETYPE_SETTER]](val, value); -// // obj = new window[serialized.ctor](array.length); -// // for (let i = 0; i < array.length; ++i) { -// // obj[i] = array[i]; -// // } -// // return obj; -// owner[key] = val; -// } - const ASSIGNMENTS: { [K in keyof DataTypes]?: ParseFunction; // eslint-disable-next-line @typescript-eslint/ban-types @@ -828,17 +720,16 @@ ASSIGNMENTS[DataTypeID.InstanceRef] = assignInstanceRef; ASSIGNMENTS[DataTypeID.Array_InstanceRef] = genArrayParser(assignInstanceRef); ASSIGNMENTS[DataTypeID.Array_AssetRefByInnerObj] = genArrayParser(parseAssetRefByInnerObj); ASSIGNMENTS[DataTypeID.Class] = parseClass; -ASSIGNMENTS[DataTypeID.ValueTypeCreated] = parseValueTypeCreated; +ASSIGNMENTS[DataTypeID.ValueTypeCreated] = deserializeBuiltinValueTypeInto; ASSIGNMENTS[DataTypeID.AssetRefByInnerObj] = parseAssetRefByInnerObj; ASSIGNMENTS[DataTypeID.TRS] = parseTRS; -ASSIGNMENTS[DataTypeID.ValueType] = parseValueType; +ASSIGNMENTS[DataTypeID.ValueType] = deserializeBuiltinValueType; ASSIGNMENTS[DataTypeID.Array_Class] = genArrayParser(parseClass); ASSIGNMENTS[DataTypeID.CustomizedClass] = parseCustomClass; ASSIGNMENTS[DataTypeID.Dict] = parseDict; ASSIGNMENTS[DataTypeID.Array] = parseArray; -// ASSIGNMENTS[DataTypeID.TypedArray] = parseTypedArray; -function parseInstances (data: IFileData): RootInstanceIndex { +function parseInstances (data: IRuntimeFileData): RootInstanceIndex { const instances = data[File.Instances]; const instanceTypes = data[File.InstanceTypes]; const instanceTypesLen = instanceTypes === EMPTY_PLACEHOLDER ? 0 : (instanceTypes).length; @@ -929,7 +820,7 @@ function doLookupClass (classFinder, type: string, container: any[], index: numb container[index] = klass; } -function lookupClasses (data: IPackedFileData, silent: boolean, customFinder: ClassFinder | undefined, reportMissingClass: deserialize.ReportMissingClass): void { +function lookupClasses (data: [any, ...ISharedData, ...any[]], silent: boolean, customFinder: ClassFinder | undefined, reportMissingClass: deserialize.ReportMissingClass): void { const classFinder = customFinder || js.getClassById; const classes = data[File.SharedClasses]; for (let i = 0; i < classes.length; ++i) { @@ -948,7 +839,7 @@ function lookupClasses (data: IPackedFileData, silent: boolean, customFinder: Cl } } -function cacheMasks (data: IPackedFileData): void { +function cacheMasks (data: [any, ...ISharedData, ...any[]]): void { const masks = data[File.SharedMasks]; if (masks) { const classes = data[File.SharedClasses]; @@ -959,7 +850,7 @@ function cacheMasks (data: IPackedFileData): void { } } -function parseResult (data: IFileData): void { +function parseResult (data: IRuntimeFileData): void { const instances = data[File.Instances]; const sharedStrings = data[File.SharedStrings]; const dependSharedUuids = data[File.SharedUuids]; @@ -1005,9 +896,35 @@ export function isCompiledJson (json: unknown): boolean { } } -/** - * @module cc - */ +function initializeDeserializationContext( + data: IDeserializeInput, + details: Details, + options?: IOptions & DeserializeDynamicOptions, +) { + details.init(data); + + options ??= {}; + + let version = data[File.Version]; + let preprocessed = false; + if (typeof version === 'object') { + preprocessed = version.preprocessed; + version = version.version; + } + if (version < SUPPORT_MIN_FORMAT_VERSION) { + throw new Error(getError(5304, version)); + } + + const context = options as IRuntimeFileData[File.Context]; + context._version = version; + context.result = details; + data[File.Context] = context; + + if (!preprocessed) { + lookupClasses(data as IRuntimeFileData, false, options.classFinder, options.reportMissingClass ?? deserialize.reportMissingClass); + cacheMasks(data as IRuntimeFileData); + } +} /** * @en Deserializes a previously serialized object to reconstruct it to the original. @@ -1018,54 +935,47 @@ export function isCompiledJson (json: unknown): boolean { * @param options Deserialization Options. * @return The original object. */ -export function deserialize (data: IFileData | string | CCON | any, details: Details | any, options?: IOptions | any): unknown { +export function deserialize (data: IDeserializeInput | string | any, details?: Details, options?: IOptions & DeserializeDynamicOptions): unknown { if (typeof data === 'string') { data = JSON.parse(data); } - const borrowDetails = !details; - details = details || Details.pool.get(); + let isBorrowedDetails = false; + if (!details) { + const borrowedDetails = Details.pool.get(); + assertIsTrue(borrowedDetails, `Can not allocate deserialization details`); + details = borrowedDetails; + isBorrowedDetails = true; + } + let res; if (!FORCE_COMPILED && !isCompiledJson(data)) { res = deserializeDynamic(data, details, options); } else { - details.init(data); - options = options || {}; - - let version = data[File.Version]; - let preprocessed = false; - if (typeof version === 'object') { - preprocessed = version.preprocessed; - version = version.version; - } - if (version < SUPPORT_MIN_FORMAT_VERSION) { - throw new Error(getError(5304, version)); - } - options._version = version; - options.result = details; - data[File.Context] = options; + initializeDeserializationContext( + data, + details, + options, + ); - if (!preprocessed) { - lookupClasses(data, false, options.classFinder, options.reportMissingClass ?? deserialize.reportMissingClass); - cacheMasks(data); - } + const runtimeData = data as IRuntimeFileData; cclegacy.game._isCloning = true; - const instances = data[File.Instances]; - const rootIndex = parseInstances(data); + const instances = runtimeData[File.Instances]; + const rootIndex = parseInstances(runtimeData); cclegacy.game._isCloning = false; - if (data[File.Refs]) { - dereference(data[File.Refs] as IRefs, instances, data[File.SharedStrings]); + if (runtimeData[File.Refs]) { + dereference(runtimeData[File.Refs] as IRefs, instances, runtimeData[File.SharedStrings]); } - parseResult(data); + parseResult(runtimeData); res = instances[rootIndex]; } - if (borrowDetails) { + if (isBorrowedDetails) { Details.pool.put(details); } @@ -1095,7 +1005,8 @@ class FileInfo { } } -export function unpackJSONs (data: IPackedFileData, classFinder?: ClassFinder, reportMissingClass?: deserialize.ReportMissingClass): IFileData[] { +export function unpackJSONs ( + data: IPackedFileData, classFinder?: ClassFinder, reportMissingClass?: deserialize.ReportMissingClass): IDeserializeInput[] { if (data[File.Version] < SUPPORT_MIN_FORMAT_VERSION) { throw new Error(getError(5304, data[File.Version])); } @@ -1110,9 +1021,10 @@ export function unpackJSONs (data: IPackedFileData, classFinder?: ClassFinder, r const sections = data[PACKED_SECTIONS]; for (let i = 0; i < sections.length; ++i) { - sections[i].unshift(version, sharedUuids, sharedStrings, sharedClasses, sharedMasks); + const section = sections[i]; + (section as any[]).unshift(version, sharedUuids, sharedStrings, sharedClasses, sharedMasks); } - return sections; + return sections as unknown as IDeserializeInput[]; } export function packCustomObjData (type: string, data: IClassObjectData|OtherObjectData, hasNativeDep?: boolean): IFileData { @@ -1126,7 +1038,7 @@ export function packCustomObjData (type: string, data: IClassObjectData|OtherObj ]; } -export function hasNativeDep (data: IFileData): boolean { +export function hasNativeDep (data: IRuntimeFileData): boolean { const instances = data[File.Instances]; const rootInfo = instances[instances.length - 1]; if (typeof rootInfo !== 'number') { @@ -1136,7 +1048,7 @@ export function hasNativeDep (data: IFileData): boolean { } } -function getDependUuidList (json: IFileData): string[] { +function getDependUuidList (json: IRuntimeFileData): string[] { const sharedUuids = json[File.SharedUuids]; // eslint-disable-next-line @typescript-eslint/no-unsafe-return return json[File.DependUuidIndices].map((index) => sharedUuids[index]); @@ -1145,7 +1057,7 @@ function getDependUuidList (json: IFileData): string[] { export function parseUuidDependencies (serialized: unknown): string[] { // eslint-disable-next-line @typescript-eslint/ban-types if (!DEV || isCompiledJson(serialized as object)) { - return getDependUuidList(serialized as IFileData); + return getDependUuidList(serialized as IRuntimeFileData); } else { return parseUuidDependenciesDynamic(serialized); } @@ -1182,8 +1094,6 @@ if (EDITOR || TEST) { ARRAY_ITEM_VALUES: typeof ARRAY_ITEM_VALUES, PACKED_SECTIONS: typeof PACKED_SECTIONS, }; - deserialize._BuiltinValueTypes = BuiltinValueTypes; - deserialize._serializeBuiltinValueTypes = serializeBuiltinValueTypes; } if (TEST) { @@ -1224,9 +1134,7 @@ if (TEST) { CustomizedClass: DataTypeID.CustomizedClass, Dict: DataTypeID.Dict, Array: DataTypeID.Array, - // TypedArray: DataTypeID.TypedArray, }, - BuiltinValueTypes, unpackJSONs, }; } diff --git a/editor/exports/serialization.ts b/editor/exports/serialization.ts index cc3ac576bab..00b297fa884 100644 --- a/editor/exports/serialization.ts +++ b/editor/exports/serialization.ts @@ -7,3 +7,7 @@ export { decodeCCONBinary, parseCCONJson, } from '../../cocos/serialization/ccon'; + +export { + serializeBuiltinValueType, +} from '../../cocos/serialization/compiled/builtin-value-type'; From f55abfa9492bb2bf8a7d0bdc9232121930eb25d0 Mon Sep 17 00:00:00 2001 From: Jiujiang Liu <37231523+moshuying@users.noreply.github.com> Date: Wed, 9 Aug 2023 10:05:39 +0800 Subject: [PATCH 110/232] remove _fitDesignResolution function call in EVENT_AFTER_UPDATE (#15802) * fix can't adjust the 2D camera in editor * simple code * update function name * remove unused import function * use anchorX * update code --- cocos/2d/framework/canvas.ts | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/cocos/2d/framework/canvas.ts b/cocos/2d/framework/canvas.ts index a4aef03ff73..87e4eb5e422 100644 --- a/cocos/2d/framework/canvas.ts +++ b/cocos/2d/framework/canvas.ts @@ -124,7 +124,7 @@ export class Canvas extends RenderRoot2D { protected _thisOnCameraResized: () => void; // fit canvas node to design resolution - protected _fitDesignResolution: (() => void) | undefined; + protected fitDesignResolution_EDITOR: (() => void) | undefined; private _pos = new Vec3(); private _renderMode = RenderMode.OVERLAY; @@ -134,16 +134,33 @@ export class Canvas extends RenderRoot2D { this._thisOnCameraResized = this._onResizeCamera.bind(this); if (EDITOR) { - this._fitDesignResolution = (): void => { + this.fitDesignResolution_EDITOR = (): void => { // TODO: support paddings of locked widget this.node.getPosition(this._pos); const nodeSize = view.getDesignResolutionSize(); - Vec3.set(_worldPos, nodeSize.width * 0.5, nodeSize.height * 0.5, 0); + const trans = this.node._uiProps.uiTransformComp!; + + let scaleX = this.node.scale.x; + let anchorX = trans.anchorX; + if (scaleX < 0) { + anchorX = 1.0 - anchorX; + scaleX = -scaleX; + } + nodeSize.width = scaleX === 0 ? nodeSize.width : nodeSize.width / scaleX; + + let scaleY = this.node.scale.y; + let anchorY = trans.anchorY; + if (scaleY < 0) { + anchorY = 1.0 - anchorY; + scaleY = -scaleY; + } + nodeSize.height = scaleY === 0 ? nodeSize.height : nodeSize.height / scaleY; + + Vec3.set(_worldPos, nodeSize.width * anchorX, nodeSize.height * anchorY, 0); if (!this._pos.equals(_worldPos)) { this.node.setPosition(_worldPos); } - const trans = this.node._uiProps.uiTransformComp!; if (trans.width !== nodeSize.width) { trans.width = nodeSize.width; } @@ -160,7 +177,7 @@ export class Canvas extends RenderRoot2D { if (widget) { widget.updateAlignment(); } else if (EDITOR) { - this._fitDesignResolution!(); + this.fitDesignResolution_EDITOR!(); } if (!EDITOR) { @@ -173,9 +190,6 @@ export class Canvas extends RenderRoot2D { this._onResizeCamera(); if (EDITOR) { - // Constantly align canvas node in edit mode - cclegacy.director.on(cclegacy.Director.EVENT_AFTER_UPDATE, this._fitDesignResolution!, this); - // In Editor can not edit these attrs. // (Position in Node, contentSize in uiTransform) // (anchor in uiTransform, but it can edit, this is different from cocos creator) @@ -203,11 +217,7 @@ export class Canvas extends RenderRoot2D { public onDestroy (): void { super.onDestroy(); - if (EDITOR) { - cclegacy.director.off(cclegacy.Director.EVENT_AFTER_UPDATE, this._fitDesignResolution!, this); - } else { - this.node.off(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized); - } + this.node.off(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized); } protected _onResizeCamera (): void { From 0abd8c4da5fe89fefe3ace24cd3192aeb67a799f Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Wed, 9 Aug 2023 10:35:13 +0800 Subject: [PATCH 111/232] fix metal pvrtc upload issue (#15894) --- native/cocos/renderer/gfx-metal/MTLTexture.mm | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.mm b/native/cocos/renderer/gfx-metal/MTLTexture.mm index edab24a636a..96d7b9a1bc1 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.mm +++ b/native/cocos/renderer/gfx-metal/MTLTexture.mm @@ -225,17 +225,21 @@ of this software and associated engine source code (the "Software"), a limited, descriptor.mipmapLevelCount = _info.levelCount; descriptor.arrayLength = _info.type == TextureType::CUBE ? 1 : _info.layerCount; - descriptor.storageMode = MTLStorageModePrivate; + bool memoryless = false; if (@available(macos 11.0, ios 10.0, *)) { - bool memoryless = hasFlag(_info.flags, TextureFlagBit::LAZILY_ALLOCATED) && - hasFlag(_info.usage, TextureUsageBit::COLOR_ATTACHMENT) && - hasFlag(_info.usage, TextureUsageBit::DEPTH_STENCIL_ATTACHMENT); + memoryless = hasFlag(_info.flags, TextureFlagBit::LAZILY_ALLOCATED) && + hasAllFlags(TextureUsageBit::COLOR_ATTACHMENT | TextureUsageBit::DEPTH_STENCIL_ATTACHMENT | TextureUsageBit::INPUT_ATTACHMENT, _info.usage); if (memoryless) { descriptor.storageMode = MTLStorageModeMemoryless; _allocateMemory = false; } } + if (!memoryless && !_isPVRTC) { + // pvrtc can not use blit encoder to upload data. + descriptor.storageMode = MTLStorageModePrivate; + } + id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); _mtlTexture = [mtlDevice newTextureWithDescriptor:descriptor]; From 1adef66108ca1af649515cb75b4f1ccf831a4dd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 9 Aug 2023 10:50:48 +0800 Subject: [PATCH 112/232] Mesh renderer(s) I18N (#15823) * Mesh renderers i18n * Update editor/i18n/en/rendering.js * Fix mesh renderer i18n * Update editor/i18n/en/modules/rendering.js --- cocos/3d/framework/mesh-renderer.ts | 49 ++++----- .../skinned-mesh-renderer.ts | 3 +- editor/i18n/en/localization.js | 10 +- editor/i18n/en/modules/rendering.js | 101 ++++++++++++++++++ editor/i18n/zh/localization.js | 10 +- editor/i18n/zh/modules/rendering.js | 101 ++++++++++++++++++ 6 files changed, 230 insertions(+), 44 deletions(-) create mode 100644 editor/i18n/en/modules/rendering.js create mode 100644 editor/i18n/zh/modules/rendering.js diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index 8b277d23e4c..ab371efe3d5 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ import { JSB } from 'internal:constants'; -import { displayName, displayOrder, group, range } from 'cc.decorator'; +import { displayOrder, group, range } from 'cc.decorator'; import { Texture2D, TextureCube } from '../../asset/assets'; import { Material } from '../../asset/assets/material'; import { Mesh } from '../assets/mesh'; @@ -44,7 +44,7 @@ import { SubModel } from '../../render-scene/scene'; import { isEnableEffect } from '../../rendering/define'; import type { Model } from '../../render-scene/scene'; -const { property, ccclass, help, executeInEditMode, executionOrder, menu, tooltip, visible, type, +const { ccclass, help, executeInEditMode, executionOrder, menu, visible, type, formerlySerializedAs, serializable, editable, disallowAnimation } = _decorator; let _phaseID = getPhaseID('specular-pass'); @@ -152,7 +152,7 @@ class ModelBakeSettings extends EventTarget { * @zh 模型是否是静态的并可以烘培光照贴图。 * 注意:模型顶点数据必须包含第二套 UV 属性来支持光照贴图烘焙。 */ - @group({ id: 'LightMap', name: 'LightMapSettings', displayOrder: 0, style: 'section' }) + @group({ id: 'LightMap', name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.LightMap.displayName', displayOrder: 0, style: 'section' }) @editable get bakeable (): boolean { return this._bakeable; @@ -166,7 +166,7 @@ class ModelBakeSettings extends EventTarget { * @en Whether to cast shadow in light map baking. * @zh 在光照贴图烘焙中是否投射阴影。 */ - @group({ id: 'LightMap', name: 'LightMapSettings' }) + @group({ id: 'LightMap', name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.LightMap.displayName' }) @editable get castShadow (): boolean { return this._castShadow; @@ -180,7 +180,7 @@ class ModelBakeSettings extends EventTarget { * @en Whether to receive shadow in light map baking. * @zh 在光照贴图烘焙中是否接受阴影。 */ - @group({ id: 'LightMap', name: 'LightMapSettings' }) + @group({ id: 'LightMap', name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.LightMap.displayName' }) @editable get receiveShadow (): boolean { return this._receiveShadow; @@ -194,7 +194,7 @@ class ModelBakeSettings extends EventTarget { * @en The lightmap size. * @zh 光照图大小。 */ - @group({ id: 'LightMap', name: 'LightMapSettings' }) + @group({ id: 'LightMap', name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.LightMap.displayName' }) @editable @type(CCInteger) @range([0, 1024]) @@ -210,7 +210,7 @@ class ModelBakeSettings extends EventTarget { * @en Whether to use light probe which provides indirect light to dynamic objects. * @zh 模型是否使用光照探针,光照探针为动态物体提供间接光。 */ - @group({ id: 'LightProbe', name: 'LightProbeSettings', displayOrder: 1, style: 'section' }) + @group({ id: 'LightProbe', name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.LightProbe.displayName', displayOrder: 1, style: 'section' }) @editable @type(CCBoolean) get useLightProbe (): boolean { @@ -226,7 +226,7 @@ class ModelBakeSettings extends EventTarget { * @en Whether the model is used to calculate light probe * @zh 模型是否用于计算光照探针 */ - @group({ id: 'LightProbe', name: 'LightProbeSettings' }) + @group({ id: 'LightProbe', name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.LightProbe.displayName' }) @editable @type(CCBoolean) get bakeToLightProbe (): boolean { @@ -241,7 +241,12 @@ class ModelBakeSettings extends EventTarget { * @en Used to set whether to use the reflection probe or set probe's type. * @zh 用于设置是否使用反射探针或者设置反射探针的类型。 */ - @group({ id: 'ReflectionProbe', name: 'ReflectionProbeSettings', displayOrder: 2, style: 'section' }) + @group({ + id: 'ReflectionProbe', + name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.ReflectionProbe.displayName', + displayOrder: 2, + style: 'section', + }) @type(Enum(ReflectionProbeType)) get reflectionProbe (): ReflectionProbeType { return this._reflectionProbeType; @@ -256,7 +261,7 @@ class ModelBakeSettings extends EventTarget { * @en Whether the model can be render by the reflection probe * @zh 模型是否能被反射探针渲染 */ - @group({ id: 'ReflectionProbe', name: 'ReflectionProbeSettings' }) + @group({ id: 'ReflectionProbe', name: 'i18n:ENGINE.classes.cc.ModelBakeSettings.groups.ReflectionProbe.displayName' }) @type(CCBoolean) get bakeToReflectionProbe (): boolean { return this._bakeToReflectionProbe; @@ -338,8 +343,12 @@ export class MeshRenderer extends ModelRenderer { * @zh 实时光照下模型局部的阴影偏移。 */ @type(CCFloat) - @tooltip('i18n:model.shadow_bias') - @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings', displayOrder: 2, style: 'section' }) + @group({ + id: 'DynamicShadow', + name: 'i18n:ENGINE.classes.cc.MeshRenderer.groups.DynamicShadow.displayName', + displayOrder: 2, + style: 'section', + }) @disallowAnimation get shadowBias (): number { return this._shadowBias; @@ -356,8 +365,7 @@ export class MeshRenderer extends ModelRenderer { * @zh 实时光照下模型局部的阴影法线偏移。 */ @type(CCFloat) - @tooltip('i18n:model.shadow_normal_bias') - @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings' }) + @group({ id: 'DynamicShadow', name: 'i18n:ENGINE.classes.cc.MeshRenderer.groups.DynamicShadow.displayName' }) @disallowAnimation get shadowNormalBias (): number { return this._shadowNormalBias; @@ -374,8 +382,7 @@ export class MeshRenderer extends ModelRenderer { * @zh 实时光照下阴影投射方式。 */ @type(ModelShadowCastingMode) - @tooltip('i18n:model.shadow_casting_model') - @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings' }) + @group({ id: 'DynamicShadow', name: 'i18n:ENGINE.classes.cc.MeshRenderer.groups.DynamicShadow.displayName' }) @disallowAnimation @visible(false) get shadowCastingMode (): number { @@ -387,9 +394,7 @@ export class MeshRenderer extends ModelRenderer { this._updateCastShadow(); } - @displayName('Shadow Casting Mode') - @tooltip('i18n:model.shadow_casting_model') - @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings' }) + @group({ id: 'DynamicShadow', name: 'i18n:ENGINE.classes.cc.MeshRenderer.groups.DynamicShadow.displayName' }) @disallowAnimation get shadowCastingModeForInspector (): boolean { return this.shadowCastingMode === ModelShadowCastingMode.ON; @@ -431,9 +436,7 @@ export class MeshRenderer extends ModelRenderer { this._updateReceiveShadow(); } - @displayName('Receive Shadow') - @tooltip('i18n:model.shadow_receiving_model') - @group({ id: 'DynamicShadow', name: 'DynamicShadowSettings' }) + @group({ id: 'DynamicShadow', name: 'i18n:ENGINE.classes.cc.MeshRenderer.groups.DynamicShadow.displayName' }) @disallowAnimation get receiveShadowForInspector (): boolean { return this._shadowReceivingMode === ModelShadowReceivingMode.ON; @@ -451,7 +454,6 @@ export class MeshRenderer extends ModelRenderer { */ @type(Mesh) @displayOrder(1) - @tooltip('i18n:model.mesh') get mesh (): Mesh | null { return this._mesh; } @@ -508,7 +510,6 @@ export class MeshRenderer extends ModelRenderer { * @zh 设置是否是全局的4s标准模型组件 */ @type(CCBoolean) - @tooltip('i18n:model.standard_skin_model') @disallowAnimation get isGlobalStandardSkinObject (): boolean { return this._enabledGlobalStandardSkinObject; diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts index ef6a78cc522..7f3125b3275 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts @@ -24,7 +24,7 @@ */ import { - ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, + ccclass, executeInEditMode, executionOrder, help, menu, type, } from 'cc.decorator'; import type { AnimationClip } from '../../animation/animation-clip'; import { Material } from '../../asset/assets'; @@ -74,7 +74,6 @@ export class SkinnedMeshRenderer extends MeshRenderer { * @zh 骨骼根节点的引用,对应控制此模型的动画组件所在节点。 */ @type(Node) - @tooltip('i18n:model.skinning_root') get skinningRoot (): Node | null { return this._skinningRoot; } diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 287be46a1b1..58c8f5f6fe2 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -296,15 +296,6 @@ module.exports = link(mixin({ csmLayersTransition: 'Enable or disable CSM layers transition(Improve quality, reduce performance)', csmTransitionRange: 'CSM layers transition range(in NDC space: value range is 0 to 1)', }, - model: { - shadow_receiving_model: 'Shadow receive mode', - shadow_casting_model: 'Shadow projection mode', - mesh: 'The mesh of the model', - skinning_root: 'The skinning root, where the controlling Animation is located', - shadow_bias: 'Bias value (world space unit) that can avoid moire artifacts with shadows for model.
The more the value, the more the light leakage', - shadow_normal_bias: 'Bias value (world space unit) that can avoid moire artifacts with surfaces that parallel to the directional light', - standard_skin_model: 'Bias value (world space unit) that ensure globally unique standard skin model', - }, sprite: { gray_scale: 'Whether turn on grayscale rendering mode', sprite_frame: 'Sprite Frame image to use', @@ -1324,6 +1315,7 @@ module.exports = link(mixin({ }, }, +require('./modules/rendering'), require('./animation'), )); diff --git a/editor/i18n/en/modules/rendering.js b/editor/i18n/en/modules/rendering.js new file mode 100644 index 00000000000..3806a1f47a6 --- /dev/null +++ b/editor/i18n/en/modules/rendering.js @@ -0,0 +1,101 @@ +/* eslint-disable quote-props */ + +module.exports = { + classes: { + 'cc': { + 'ModelBakeSettings': { + groups: { + LightMap: { + displayName: 'Light Map Settings', + }, + LightProbe: { + displayName: 'Light Probe Settings', + }, + ReflectionProbe: { + displayName: 'Reflection Probe Settings', + }, + }, + properties: { + 'bakeable': { + displayName: 'Bakeable', + }, + 'castShadow': { + displayName: 'Cast Shadows', + }, + 'receiveShadow': { + displayName: 'Receive Shadows', + }, + 'lightmapSize': { + displayName: 'Light Map Size', + }, + 'useLightProbe': { + displayName: 'Use Light Probe', + }, + 'bakeToLightProbe': { + displayName: 'Bake To Light Probe', + }, + 'reflectionProbe': { + displayName: 'Reflection Probe', + }, + 'bakeToReflectionProbe': { + displayName: 'Bake To Reflection Probe', + }, + }, + }, + 'MeshRenderer': { + groups: { + DynamicShadow: { + displayName: 'Dynamic Shadow Settings', + }, + }, + properties: { + 'mesh': { + displayName: 'Mesh', + tooltip: 'The mesh asset.', + }, + 'sharedMaterials': { + displayName: 'Materials', + tooltip: 'Material array. Each item in turn specifies material of sub mesh.', + }, + 'shadowCastingModeForInspector': { + displayName: 'Cast Shadows', + tooltip: 'Whether if this mesh casts shadows.', + }, + 'receiveShadowForInspector': { + displayName: 'Receive Shadows', + tooltip: 'Whether if this mesh receives shadows.', + }, + 'shadowBias': { + displayName: 'Shadow Bias', + tooltip: 'Bias value (world space unit) that can avoid moire artifacts with shadows for model.
The more the value, the more the light leakage.', + }, + 'shadowNormalBias': { + displayName: 'Shadow Normal Bias', + tooltip: 'Bias value (world space unit) that can avoid moire artifacts with surfaces that parallel to the directional light.', + }, + 'bakeSettings': { + displayName: 'Bake Settings', + tooltip: 'Bake settings related to global lighting.', + }, + 'isGlobalStandardSkinObject': { + displayName: 'Global Standard Skin Object', + tooltip: 'The engine needs to know the scale of the model corresponding to the skin material in order to calculate the skin scattered light correctly. If no model is checked, the model with the skin material will be automatically selected for calculation.', + }, + }, + }, + 'SkinnedMeshRenderer': { + properties: { + __extends__: 'classes.cc.MeshRenderer.properties', + 'skeleton': { + displayName: 'Skeleton', + tooltip: 'Skeleton asset.', + }, + 'skinningRoot': { + displayName: 'Skinning Root', + tooltip: 'Reference to the root bone. In general, it\'s the node where animation component is located.', + }, + }, + }, + }, + }, +}; diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index fbb81ad5f56..7dd090de518 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -286,15 +286,6 @@ module.exports = link(mixin({ csmLayersTransition: '是否开启级联阴影层级过渡(提升质量,降低性能)', csmTransitionRange: '级联阴影层级过渡范围(NDC空间: 取值范围为 0 ~ 1)', }, - model: { - shadow_receiving_model: '阴影接受方式', - shadow_casting_model: '阴影投射方式', - mesh: '模型的网格数据', - skinning_root: '骨骼根节点的引用,对应控制此模型的动画组件所在节点', - shadow_bias: '模型额外增加深度偏移值(世界空间单位)可以有效消除阴影摩尔纹,但是过大的值可能造成漏光现象', - shadow_normal_bias: '模型额外增加法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,
防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', - standard_skin_model: '模型额外设定全局唯一的标准皮肤模型', - }, sprite: { gray_scale: '是否开启灰度渲染模式', atlas: '图片资源所属的 Atlas 图集资源', @@ -1298,6 +1289,7 @@ module.exports = link(mixin({ }, }, +require('./modules/rendering'), require('./animation'), )); diff --git a/editor/i18n/zh/modules/rendering.js b/editor/i18n/zh/modules/rendering.js new file mode 100644 index 00000000000..c202e2eda20 --- /dev/null +++ b/editor/i18n/zh/modules/rendering.js @@ -0,0 +1,101 @@ +/* eslint-disable quote-props */ + +module.exports = { + classes: { + 'cc': { + 'ModelBakeSettings': { + groups: { + LightMap: { + displayName: '光照贴图设置', + }, + LightProbe: { + displayName: '光照探针设置', + }, + ReflectionProbe: { + displayName: '反射探针设置', + }, + }, + properties: { + 'bakeable': { + displayName: '可烘焙', + }, + 'castShadow': { + displayName: '投射阴影', + }, + 'receiveShadow': { + displayName: '接收阴影', + }, + 'lightmapSize': { + displayName: '光照贴图尺寸', + }, + 'useLightProbe': { + displayName: '使用光照探针', + }, + 'bakeToLightProbe': { + displayName: '烘焙至光照探针', + }, + 'reflectionProbe': { + displayName: '反射探针', + }, + 'bakeToReflectionProbe': { + displayName: '烘焙至反射探针', + }, + }, + }, + 'MeshRenderer': { + groups: { + DynamicShadow: { + displayName: '动态阴影设置', + }, + }, + properties: { + 'mesh': { + displayName: '网格', + tooltip: '网格资源。', + }, + 'sharedMaterials': { + displayName: '材质', + tooltip: '材质资源数组。每一项依次指定了子网格的材质。', + }, + 'shadowCastingModeForInspector': { + displayName: '投射阴影', + tooltip: '此网格是否投射阴影。', + }, + 'receiveShadowForInspector': { + displayName: '接收阴影', + tooltip: '此网格是否接收阴影。', + }, + 'shadowBias': { + displayName: '阴影偏移', + tooltip: '模型额外增加深度偏移值(世界空间单位)可以有效消除阴影摩尔纹,但是过大的值可能造成漏光现象。', + }, + 'shadowNormalBias': { + displayName: '阴影法线偏移', + tooltip: '模型额外增加法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,
防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差。', + }, + 'bakeSettings': { + displayName: '烘焙设置', + tooltip: '全局光照相关的烘焙设置。', + }, + 'isGlobalStandardSkinObject': { + displayName: '全局标准蒙皮模型', + tooltip: '模型额外设定全局唯一的标准皮肤模型', + }, + }, + }, + 'SkinnedMeshRenderer': { + properties: { + __extends__: 'classes.cc.MeshRenderer.properties', + 'skeleton': { + displayName: '骨骼', + tooltip: '骨骼资源。', + }, + 'skinningRoot': { + displayName: '蒙皮根', + tooltip: '骨骼根节点的引用,对应控制此模型的动画组件所在节点。', + }, + }, + }, + }, + }, +}; From 71eedef4faa85a2dc374c7143f31db64ffa08add Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Wed, 9 Aug 2023 11:23:30 +0800 Subject: [PATCH 113/232] add sorting & tiled help doc (#15900) * add sorting help doc * add tiled tile doc --- cocos/sorting/sorting.ts | 3 ++- editor/i18n/en/localization.js | 2 ++ editor/i18n/zh/localization.js | 2 ++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos/sorting/sorting.ts b/cocos/sorting/sorting.ts index a6516221c71..23d96b60451 100644 --- a/cocos/sorting/sorting.ts +++ b/cocos/sorting/sorting.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { ccclass, disallowMultiple, editable, executeInEditMode, menu, range, serializable, type } from 'cc.decorator'; +import { ccclass, disallowMultiple, editable, executeInEditMode, help, menu, range, serializable, type } from 'cc.decorator'; import { clamp } from '../core/math'; import { SortingLayers } from './sorting-layers'; import { Component } from '../scene-graph/component'; @@ -41,6 +41,7 @@ const MIN_INT16 = -1 << 15; */ @ccclass('cc.Sorting') @menu('Sorting/Sorting') +@help('i18n:cc.Sorting') @disallowMultiple @executeInEditMode export class Sorting extends Component { diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 58c8f5f6fe2..ac6f45fe483 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -130,6 +130,7 @@ module.exports = link(mixin({ SafeArea: `${url}/${version}/manual/en/ui-system/components/editor/safearea.html`, Terrain: `${url}/${version}/manual/en/editor/terrain/`, TiledMap: `${url}/${version}/manual/en/editor/components/tiledmap.html`, + TiledTile: `${url}/${version}/manual/en/editor/components/tiledtile.html`, Spine: `${url}/${version}/manual/en/editor/components/spine.html`, DragonBones: `${url}/${version}/manual/en/editor/components/dragonbones.html`, OctreeCulling: `${url}/${version}/manual/en/advanced-topics/native-scene-culling.html`, @@ -145,6 +146,7 @@ module.exports = link(mixin({ Skin: `${url}/${version}/manual/en/shader/advanced-shader/skin.html`, RenderRoot2D: `${url}/${version}/manual/en/ui-system/components/editor/renderroot2d.html`, ReflectionProbe: `${url}/${version}/manual/en/concepts/scene/light/probe/reflection-art-workflow.html`, + Sorting: `${url}/${version}/manual/en/engine/rendering/sorting.html`, }, assets: { javascript: `${url}/${version}/manual/en/concepts/scene/node-component.html`, diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 7dd090de518..a2c1052c6fb 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -130,6 +130,7 @@ module.exports = link(mixin({ SafeArea: `${url}/${version}/manual/zh/ui-system/components/editor/safearea.html`, Terrain: `${url}/${version}/manual/zh/editor/terrain/`, TiledMap: `${url}/${version}/manual/zh/editor/components/tiledmap.html`, + TiledTile: `${url}/${version}/manual/zh/editor/components/tiledtile.html`, Spine: `${url}/${version}/manual/zh/editor/components/spine.html`, DragonBones: `${url}/${version}/manual/zh/editor/components/dragonbones.html`, OctreeCulling: `${url}/${version}/manual/zh/advanced-topics/native-scene-culling.html`, @@ -145,6 +146,7 @@ module.exports = link(mixin({ Skin: `${url}/${version}/manual/zh/shader/advanced-shader/skin.html`, RenderRoot2D: `${url}/${version}/manual/zh/ui-system/components/editor/renderroot2d.html`, ReflectionProbe: `${url}/${version}/manual/zh/concepts/scene/light/probe/reflection-art-workflow.html`, + Sorting: `${url}/${version}/manual/zh/engine/rendering/sorting.html`, }, assets: { javascript: `${url}/${version}/manual/zh/concepts/scene/node-component.html`, From 904cdd8664d49dbb90f9ad5ce714f937989dee2f Mon Sep 17 00:00:00 2001 From: PP Date: Wed, 9 Aug 2023 11:25:38 +0800 Subject: [PATCH 114/232] fix: api issues in typedoc (#15826) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: typedoc wrong typeArguments update * fix: cull engineInternal tag * export Screen class * Update cocos/core/platform/index.ts Co-authored-by: Leslie Leigh (李的序) * fix typing * fix eslint # Conflicts: # cocos/core/platform/screen.ts * fix: cull engine internal with groups culling * Update cocos/core/platform/index.ts Co-authored-by: Leslie Leigh (李的序) * fix eslint * Update scripts/typedoc-plugin/src/cull-engine-internal.ts * optimize --------- Co-authored-by: Leslie Leigh (李的序) --- cocos/core/platform/index.ts | 1 + cocos/core/platform/screen.ts | 14 +- .../src/cull-engine-internal.ts | 146 ++++++++++ scripts/typedoc-plugin/src/plugin.ts | 23 +- .../engine-internal.test.ts.snap | 269 ++++++++++++++++++ .../fix-type-arguments.test.ts.snap | 229 +++++++++++++++ .../test/engine-internal.test.ts | 6 + .../test/fix-type-arguments.test.ts | 6 + .../test/inputs/link/engine-internal.ts | 74 +++++ .../test/inputs/link/fix-type-arguments.ts | 5 + 10 files changed, 765 insertions(+), 8 deletions(-) create mode 100644 scripts/typedoc-plugin/src/cull-engine-internal.ts create mode 100644 scripts/typedoc-plugin/test/__snapshots__/engine-internal.test.ts.snap create mode 100644 scripts/typedoc-plugin/test/__snapshots__/fix-type-arguments.test.ts.snap create mode 100644 scripts/typedoc-plugin/test/engine-internal.test.ts create mode 100644 scripts/typedoc-plugin/test/fix-type-arguments.test.ts create mode 100644 scripts/typedoc-plugin/test/inputs/link/engine-internal.ts create mode 100644 scripts/typedoc-plugin/test/inputs/link/fix-type-arguments.ts diff --git a/cocos/core/platform/index.ts b/cocos/core/platform/index.ts index 9109c0d9f05..7dd81eabbf4 100644 --- a/cocos/core/platform/index.ts +++ b/cocos/core/platform/index.ts @@ -45,3 +45,4 @@ export { } from './debug'; export { screen } from './screen'; +export type { Screen } from './screen'; diff --git a/cocos/core/platform/screen.ts b/cocos/core/platform/screen.ts index 0cfb92be0e6..97cffce324a 100644 --- a/cocos/core/platform/screen.ts +++ b/cocos/core/platform/screen.ts @@ -29,13 +29,13 @@ import { IScreenOptions, screenAdapter } from 'pal/screen-adapter'; import { legacyCC } from '../global-exports'; import { Size } from '../math'; import { Settings, settings } from '../settings'; -import { warnID } from './debug'; +import { error, warn, warnID } from './debug'; import { PalScreenEvent } from '../../../pal/screen-adapter/enum-type'; /** * @en The screen API provides an easy way to do some screen managing stuff. * @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。 */ -class Screen { +export class Screen { /** * @internal */ @@ -157,7 +157,7 @@ class Screen { return screenAdapter.requestFullScreen().then((): void => { onFullScreenChange?.call(document); // this case is only used on Web platforms, which is deprecated since v3.3.0 }).catch((err): void => { - console.error(err); + error(err); onFullScreenError?.call(document); // this case is only used on Web platforms, which is deprecated since v3.3.0 }); } @@ -180,7 +180,7 @@ class Screen { * @deprecated since v3.3, please use screen.requestFullScreen() instead. */ public autoFullScreen (element: HTMLElement, onFullScreenChange: (this: Document, ev: any) => any): void { - this.requestFullScreen(element, onFullScreenChange)?.catch((e): void => {}); + this.requestFullScreen(element, onFullScreenChange)?.catch((e): void => { warn(e); }); } /** @@ -198,7 +198,7 @@ class Screen { * @zh * 注册screen事件回调。 */ - public on (type: PalScreenEvent, callback: any, target?: any): void { + public on (type: PalScreenEvent, callback: (...args: any) => void, target?: any): void { screenAdapter.on(type, callback, target); } @@ -208,7 +208,7 @@ class Screen { * @zh * 注册单次的screen事件回调。 */ - public once (type: PalScreenEvent, callback?: any, target?: any): void { + public once (type: PalScreenEvent, callback: (...args: any) => void, target?: any): void { screenAdapter.once(type, callback, target); } @@ -218,7 +218,7 @@ class Screen { * @zh * 取消注册screen事件回调。 */ - public off (type: PalScreenEvent, callback?: any, target?: any): void { + public off (type: PalScreenEvent, callback?: (...args: any) => void, target?: any): void { screenAdapter.off(type, callback, target); } } diff --git a/scripts/typedoc-plugin/src/cull-engine-internal.ts b/scripts/typedoc-plugin/src/cull-engine-internal.ts new file mode 100644 index 00000000000..bce54586778 --- /dev/null +++ b/scripts/typedoc-plugin/src/cull-engine-internal.ts @@ -0,0 +1,146 @@ +import { Reflection, ReflectionKind, SerializeEvent } from "typedoc"; + +const TAG_ENGINE_INTERNAL = 'engineInternal'.toLowerCase(); + +export function cullEngineInternal (serializeOutput: SerializeEvent['output']): void { + traverseObject(serializeOutput); +} + +function hasTagEngineInternal (obj: Reflection): boolean { + if (obj.comment?.tags) { + for (const tagItem of obj.comment.tags) { + // @ts-expect-error Property 'tag' does not exist on type 'CommentTag'. + if (tagItem.tag === TAG_ENGINE_INTERNAL) { + return true; + } + } + return false; + } + return false; +} + +function traverseObject (obj: Record, recentGroups?: any[]): void { + for (const key in obj) { + if (key === 'groups') { + continue; + } + const item = obj[key]; + if (typeof item === 'number' || typeof item === 'string' || typeof item === 'undefined') { + continue; + } + if (Array.isArray(item)) { + traverseArray(item, obj.groups ?? recentGroups); + } else { + traverseObject(item, obj.groups ?? recentGroups); + } + } +} + +function traverseArray (arr: Array, recentGroups?: any[]): void { + for (let i = arr.length - 1; i >= 0; --i) { + const item = arr[i]; + if (typeof item === 'number' || typeof item === 'string') { + continue; + } + if (Array.isArray(item)) { + traverseArray(item, recentGroups); + } else { + if (handleObject(item)) { + const index = arr.indexOf(item); + if (index > -1) { + arr.splice(index, 1); + } + if (recentGroups) { + const group = recentGroups.find((group: Record) => group.kind === item.kind); + if (group) { + const groupChildIndex = group.children.indexOf(item.id); + if (groupChildIndex > -1) { + group.children.splice(groupChildIndex, 1); + } + if (group.children.length === 0) { + const groupIndex = recentGroups.findIndex((group: Record) => group.kind === item.kind); + if (groupIndex > -1) { + recentGroups.splice(groupIndex, 1); + } + } + } + } + } else { + traverseObject(item, recentGroups); + } + } + } +} + +function isReflection (obj: Record): obj is Reflection { + return typeof obj.kind !== 'undefined'; +} + +/** + * @returns whether we need to remove the object from array + */ +function handleObject (obj: Record): boolean { + if (!isReflection(obj)) { + return false; + } + switch(obj.kind) { + case ReflectionKind.Namespace: + case ReflectionKind.Enum: + case ReflectionKind.EnumMember: + case ReflectionKind.Variable: + case ReflectionKind.Class: + case ReflectionKind.Interface: + case ReflectionKind.Constructor: + case ReflectionKind.Property: + case ReflectionKind.CallSignature: + case ReflectionKind.IndexSignature: + case ReflectionKind.ConstructorSignature: + case ReflectionKind.TypeLiteral: + case ReflectionKind.TypeAlias: + case ReflectionKind.GetSignature: + case ReflectionKind.SetSignature: + return hasTagEngineInternal(obj); + case ReflectionKind.Function: + case ReflectionKind.Method: + return handleFunctionOrMethod(obj); + case ReflectionKind.Accessor: + return handleAccessor(obj); + default: + return false; + + } +} + +/** + * @returns whether we need to remove the object from array + */ +function handleFunctionOrMethod (funcOrMethod: Record): boolean { + if (Array.isArray(funcOrMethod.signatures)) { + traverseArray(funcOrMethod.signatures); + if (funcOrMethod.signatures.length === 0) { + return true; + } + } + return false; +} + +/** + * @returns whether we need to remove the object from array + */ +function handleAccessor (accessor: Record): boolean { + let needRemove = true; + if (Array.isArray(accessor.getSignature)) { + traverseArray(accessor.getSignature); + if (accessor.getSignature.length !== 0) { + needRemove = false; + } + } + if (Array.isArray(accessor.setSignature)) { + traverseArray(accessor.setSignature); + if (accessor.setSignature.length !== 0) { + needRemove = false; + } + } + return needRemove; +} + diff --git a/scripts/typedoc-plugin/src/plugin.ts b/scripts/typedoc-plugin/src/plugin.ts index 2a41cfbf11a..5cdec3328b8 100644 --- a/scripts/typedoc-plugin/src/plugin.ts +++ b/scripts/typedoc-plugin/src/plugin.ts @@ -1,8 +1,9 @@ // eslint-disable-next-line import/no-extraneous-dependencies -import { Application, Converter, Context, Reflection, Comment, CommentTag, SerializerComponent, ReflectionKind, SignatureReflection, ProjectReflection, ContainerReflection, DeclarationReflection, ParameterReflection, ReferenceReflection } from 'typedoc'; +import { Application, Converter, Context, Reflection, Comment, CommentTag, SerializerComponent, ReflectionKind, SignatureReflection, ProjectReflection, ContainerReflection, DeclarationReflection, Serializer, SerializeEvent, ReferenceReflection } from 'typedoc'; import ts from 'typescript'; import fs from 'fs-extra'; import ps from 'path'; +import { cullEngineInternal } from './cull-engine-internal'; const TAG_NAME_CC_CATEGORY = 'ccCategory'; @@ -55,6 +56,10 @@ export function load (app: Application) { }); }); + app.serializer.on(Serializer.EVENT_END, (serializeEvent: SerializeEvent) => { + cullEngineInternal(serializeEvent.output) + }); + type ReflectionId = Reflection['id']; type CategoryInfo = { @@ -114,6 +119,7 @@ export function load (app: Application) { } function onCreateSignature (_context: Context, reflection: SignatureReflection, node?: ts.Node) { + fixTypeArguments(_context, reflection, node); handleTagLegacyPublic(_context, reflection, node); } @@ -163,6 +169,21 @@ export function load (app: Application) { comment.tags.push(new CommentTag('deprecated', undefined, 'This key is reserved for internal usage.')); } + // NOTE: this is a bug on typedoc, we fix in this plugin. + // should not generate typeArguments field in typeParameters' type field. + function fixTypeArguments (_context: Context, reflection: SignatureReflection, node?: ts.Node) { + if (reflection.typeParameters) { + for (const typeParam of reflection.typeParameters) { + // @ts-ignore + const typeArguments = typeParam.type?.typeArguments; + if (typeArguments?.[0]?.name === typeParam.name) { + // @ts-ignore + delete typeParam.type.typeArguments; + } + } + } + } + function setCategory (reflectionId: ReflectionId, categoryId: string, categoryConfig: CategoryConfig) { (categoryMap[categoryId] ??= { ...categoryConfig, diff --git a/scripts/typedoc-plugin/test/__snapshots__/engine-internal.test.ts.snap b/scripts/typedoc-plugin/test/__snapshots__/engine-internal.test.ts.snap new file mode 100644 index 00000000000..5d7aa31f2ca --- /dev/null +++ b/scripts/typedoc-plugin/test/__snapshots__/engine-internal.test.ts.snap @@ -0,0 +1,269 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`fix type arguments 1`] = ` +Object { + "categories": undefined, + "ccCategories": Array [], + "children": Array [ + Object { + "categories": undefined, + "children": Array [ + Object { + "categories": undefined, + "children": undefined, + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": undefined, + "id": 10, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 512, + "kindString": "Constructor", + "name": "constructor", + "overwrites": undefined, + "signatures": Array [ + Object { + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "flags": Object {}, + "id": 11, + "implementationOf": undefined, + "inheritedFrom": undefined, + "kind": 16384, + "kindString": "Constructor signature", + "name": "new Class2", + "overwrites": undefined, + "parameters": undefined, + "type": Object { + "id": 6, + "name": "Class2", + "type": "reference", + }, + "typeParameter": undefined, + }, + ], + "sources": undefined, + "type": undefined, + "typeParameter": undefined, + }, + ], + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": Array [ + Object { + "children": Array [ + 10, + ], + "kind": 512, + "title": "Constructors", + }, + ], + "id": 6, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 128, + "kindString": "Class", + "name": "Class2", + "overwrites": undefined, + "signatures": undefined, + "sources": Array [ + Object { + "character": 13, + "fileName": "engine-internal.ts", + "line": 6, + }, + ], + "type": undefined, + "typeParameter": undefined, + }, + Object { + "categories": undefined, + "children": Array [], + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": Array [], + "id": 27, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 256, + "kindString": "Interface", + "name": "Interface2", + "overwrites": undefined, + "signatures": undefined, + "sources": Array [ + Object { + "character": 17, + "fileName": "engine-internal.ts", + "line": 55, + }, + ], + "type": undefined, + "typeParameter": undefined, + }, + Object { + "categories": undefined, + "children": undefined, + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": "...", + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object { + "isConst": true, + }, + "groups": undefined, + "id": 21, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 32, + "kindString": "Variable", + "name": "obj2", + "overwrites": undefined, + "signatures": undefined, + "sources": Array [ + Object { + "character": 13, + "fileName": "engine-internal.ts", + "line": 38, + }, + ], + "type": Object { + "declaration": Object { + "categories": undefined, + "children": Array [ + Object { + "categories": undefined, + "children": undefined, + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": "1", + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": undefined, + "id": 23, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 1024, + "kindString": "Property", + "name": "testProp", + "overwrites": undefined, + "signatures": undefined, + "sources": undefined, + "type": Object { + "name": "number", + "type": "intrinsic", + }, + "typeParameter": undefined, + }, + ], + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": Array [ + Object { + "children": Array [ + 23, + ], + "kind": 1024, + "title": "Properties", + }, + ], + "id": 22, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 65536, + "kindString": "Type literal", + "name": "__type", + "overwrites": undefined, + "signatures": undefined, + "sources": undefined, + "type": undefined, + "typeParameter": undefined, + }, + "type": "reflection", + }, + "typeParameter": undefined, + }, + ], + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "flags": Object {}, + "groups": Array [ + Object { + "children": Array [ + 6, + ], + "kind": 128, + "title": "Classes", + }, + Object { + "children": Array [ + 27, + ], + "kind": 256, + "title": "Interfaces", + }, + Object { + "children": Array [ + 21, + ], + "kind": 32, + "title": "Variables", + }, + ], + "id": 0, + "kind": 1, + "kindString": "Project", + "name": "typedoc-plugin-cc", + "originalName": "", + "sources": Array [ + Object { + "character": 0, + "fileName": "engine-internal.ts", + "line": 4, + }, + ], +} +`; diff --git a/scripts/typedoc-plugin/test/__snapshots__/fix-type-arguments.test.ts.snap b/scripts/typedoc-plugin/test/__snapshots__/fix-type-arguments.test.ts.snap new file mode 100644 index 00000000000..574e4c8c8dd --- /dev/null +++ b/scripts/typedoc-plugin/test/__snapshots__/fix-type-arguments.test.ts.snap @@ -0,0 +1,229 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`fix type arguments 1`] = ` +Object { + "categories": undefined, + "ccCategories": Array [], + "children": Array [ + Object { + "categories": undefined, + "children": Array [ + Object { + "categories": undefined, + "children": undefined, + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": undefined, + "id": 6, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 512, + "kindString": "Constructor", + "name": "constructor", + "overwrites": undefined, + "signatures": Array [ + Object { + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "flags": Object {}, + "id": 7, + "implementationOf": undefined, + "inheritedFrom": undefined, + "kind": 16384, + "kindString": "Constructor signature", + "name": "new A", + "overwrites": undefined, + "parameters": undefined, + "type": Object { + "id": 5, + "name": "A", + "type": "reference", + }, + "typeParameter": undefined, + }, + ], + "sources": undefined, + "type": undefined, + "typeParameter": undefined, + }, + ], + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": Array [ + Object { + "children": Array [ + 6, + ], + "kind": 512, + "title": "Constructors", + }, + ], + "id": 5, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 128, + "kindString": "Class", + "name": "A", + "overwrites": undefined, + "signatures": undefined, + "sources": Array [ + Object { + "character": 13, + "fileName": "fix-type-arguments.ts", + "line": 1, + }, + ], + "type": undefined, + "typeParameter": undefined, + }, + Object { + "categories": undefined, + "children": undefined, + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "extendedBy": undefined, + "extendedTypes": undefined, + "flags": Object {}, + "groups": undefined, + "id": 1, + "implementationOf": undefined, + "implementedBy": undefined, + "implementedTypes": undefined, + "indexSignature": undefined, + "inheritedFrom": undefined, + "kind": 64, + "kindString": "Function", + "name": "test", + "overwrites": undefined, + "signatures": Array [ + Object { + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "flags": Object {}, + "id": 2, + "implementationOf": undefined, + "inheritedFrom": undefined, + "kind": 4096, + "kindString": "Call signature", + "name": "test", + "overwrites": undefined, + "parameters": Array [ + Object { + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "defaultValue": undefined, + "flags": Object {}, + "id": 4, + "kind": 32768, + "kindString": "Parameter", + "name": "t", + "type": Object { + "id": 5, + "name": "A", + "type": "reference", + }, + }, + ], + "type": Object { + "name": "Record", + "package": "typescript", + "qualifiedName": "Record", + "type": "reference", + "typeArguments": Array [ + Object { + "name": "string", + "type": "intrinsic", + }, + Object { + "id": 3, + "name": "T", + "type": "reference", + }, + ], + }, + "typeParameter": Array [ + Object { + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "default": undefined, + "flags": Object {}, + "id": 3, + "kind": 131072, + "kindString": "Type parameter", + "name": "T", + "type": Object { + "id": 5, + "name": "A", + "type": "reference", + }, + }, + ], + }, + ], + "sources": Array [ + Object { + "character": 16, + "fileName": "fix-type-arguments.ts", + "line": 3, + }, + ], + "type": undefined, + "typeParameter": undefined, + }, + ], + "comment": undefined, + "decorates": undefined, + "decorators": undefined, + "flags": Object {}, + "groups": Array [ + Object { + "children": Array [ + 5, + ], + "kind": 128, + "title": "Classes", + }, + Object { + "children": Array [ + 1, + ], + "kind": 64, + "title": "Functions", + }, + ], + "id": 0, + "kind": 1, + "kindString": "Project", + "name": "typedoc-plugin-cc", + "originalName": "", + "sources": Array [ + Object { + "character": 0, + "fileName": "fix-type-arguments.ts", + "line": 1, + }, + ], +} +`; diff --git a/scripts/typedoc-plugin/test/engine-internal.test.ts b/scripts/typedoc-plugin/test/engine-internal.test.ts new file mode 100644 index 00000000000..2c822b23de8 --- /dev/null +++ b/scripts/typedoc-plugin/test/engine-internal.test.ts @@ -0,0 +1,6 @@ +import ps from 'path'; +import { runTest } from './test-util'; + +test(`fix type arguments`, async () => { + await runTest(ps.join(__dirname, './inputs/link/'), 'engine-internal.ts'); +}); diff --git a/scripts/typedoc-plugin/test/fix-type-arguments.test.ts b/scripts/typedoc-plugin/test/fix-type-arguments.test.ts new file mode 100644 index 00000000000..ec63153deff --- /dev/null +++ b/scripts/typedoc-plugin/test/fix-type-arguments.test.ts @@ -0,0 +1,6 @@ +import ps from 'path'; +import { runTest } from './test-util'; + +test(`fix type arguments`, async () => { + await runTest(ps.join(__dirname, './inputs/link/'), 'fix-type-arguments.ts'); +}); diff --git a/scripts/typedoc-plugin/test/inputs/link/engine-internal.ts b/scripts/typedoc-plugin/test/inputs/link/engine-internal.ts new file mode 100644 index 00000000000..091d0c9ecd4 --- /dev/null +++ b/scripts/typedoc-plugin/test/inputs/link/engine-internal.ts @@ -0,0 +1,74 @@ +/** + * @engineInternal + */ +export class Class1 {} + +export class Class2 { + /** + * @engineInternal + */ + static testStaticProp: number; + /** + * @engineInternal + */ + static testStaticMdthod() {}; + /** + * @engineInternal + */ + get getterSetter (): number { return 1; } + /** + * @engineInternal + */ + set getterSetter (a: number) {} + /** + * @engineInternal + */ + testProp: number; + /** + * @engineInternal + */ + testMethod () {} +} + +/** + * @engineInternal + */ +export const obj1 = {} + +export const obj2 = { + /** + * @engineInternal + */ + testProp: 1, + /** + * @engineInternal + */ + testMethod () {}, + +} + +/** + * @engineInternal + */ +export interface Interface1 {} + +export interface Interface2 { + /** + * @engineInternal + */ + testProp: number; + /** + * @engineInternal + */ + testMethod (); +} + +/** + * @engineInternal + */ +export function testFunc () {} + +/** + * @engineInternal + */ +export enum TestEnum {} \ No newline at end of file diff --git a/scripts/typedoc-plugin/test/inputs/link/fix-type-arguments.ts b/scripts/typedoc-plugin/test/inputs/link/fix-type-arguments.ts new file mode 100644 index 00000000000..5b353bacb20 --- /dev/null +++ b/scripts/typedoc-plugin/test/inputs/link/fix-type-arguments.ts @@ -0,0 +1,5 @@ +export class A {} + +export function test(t: A): Record { + throw 'not impl'; +} From 8c1a005d215591b76ac2a364db5a802aa11b6e18 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Wed, 9 Aug 2023 11:27:39 +0800 Subject: [PATCH 115/232] add http patch request process (#15898) --- .../bindings/manual/jsb_xmlhttprequest.cpp | 5 ++++- native/cocos/network/HttpClient-apple.mm | 6 +++++- native/cocos/network/HttpClient-java.cpp | 8 +++++++- native/cocos/network/HttpClient.cpp | 18 ++++++++++++++++++ native/cocos/network/HttpRequest.h | 1 + .../com/cocos/lib/CocosHttpURLConnection.java | 3 ++- .../com/cocos/lib/CocosHttpURLConnection.java | 1 + platforms/native/builtin/jsb-adapter/fetch.js | 2 +- 8 files changed, 39 insertions(+), 5 deletions(-) diff --git a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp index dd37ca74f4c..fdf44d48355 100644 --- a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp +++ b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp @@ -261,6 +261,9 @@ bool XMLHttpRequest::open(const ccstd::string &method, const ccstd::string &url) requestType = HttpRequest::Type::HEAD; } else if (_method == "delete" || _method == "DELETE") { requestType = HttpRequest::Type::DELETE; + } else if (_method == "patch" || _method == "PATCH") { + requestType = HttpRequest::Type::PATCH; + } CC_ASSERT(requestType != HttpRequest::Type::UNKNOWN); @@ -513,7 +516,7 @@ void XMLHttpRequest::sendRequest() { void XMLHttpRequest::setHttpRequestData(const char *data, size_t len) { if (len > 0 && - (_method == "post" || _method == "POST" || _method == "put" || _method == "PUT")) { + (_method == "post" || _method == "POST" || _method == "put" || _method == "PUT" || _method == "patch" || _method == "PATCH")) { _httpRequest->setRequestData(data, len); } } diff --git a/native/cocos/network/HttpClient-apple.mm b/native/cocos/network/HttpClient-apple.mm index b0335c69952..bcafaf913e6 100644 --- a/native/cocos/network/HttpClient-apple.mm +++ b/native/cocos/network/HttpClient-apple.mm @@ -165,7 +165,7 @@ static int processTask(HttpClient *client, HttpRequest *request, NSString *reque } //if request type is post or put,set header and data - if ([requestType isEqual:@"POST"] || [requestType isEqual:@"PUT"]) { + if ([requestType isEqual:@"POST"] || [requestType isEqual:@"PUT"] || [requestType isEqual:@"PATCH"]) { char *requestDataBuffer = request->getRequestData(); if (nullptr != requestDataBuffer && 0 != request->getRequestDataSize()) { NSData *postData = [NSData dataWithBytes:requestDataBuffer length:request->getRequestDataSize()]; @@ -466,6 +466,10 @@ static int processTask(HttpClient *client, HttpRequest *request, NSString *reque requestType = @"DELETE"; break; + case HttpRequest::Type::PATCH: + requestType = @"PATCH"; + break; + default: CC_ABORT(); break; diff --git a/native/cocos/network/HttpClient-java.cpp b/native/cocos/network/HttpClient-java.cpp index 0e1ec005a3d..86b1d94ddce 100644 --- a/native/cocos/network/HttpClient-java.cpp +++ b/native/cocos/network/HttpClient-java.cpp @@ -634,6 +634,11 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) case HttpRequest::Type::DELETE: urlConnection.setRequestMethod("DELETE"); break; + + case HttpRequest::Type::PATCH: + urlConnection.setRequestMethod("PATCH"); + break; + default: break; } @@ -647,7 +652,8 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) } if (HttpRequest::Type::POST == requestType || - HttpRequest::Type::PUT == requestType) { + HttpRequest::Type::PUT == requestType || + HttpRequest::Type::PATCH == requestType) { urlConnection.sendRequest(request); } diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index 5476f9c79ac..f4a728992a5 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -76,6 +76,7 @@ static int processGetTask(HttpClient *client, HttpRequest *request, write_callba static int processPostTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream, char *errorBuffer); static int processPutTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream, char *errorBuffer); static int processDeleteTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream, char *errorBuffer); +static int processPatchTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream, char *errorBuffer); // int processDownloadTask(HttpRequest *task, write_callback callback, void *stream, int32_t *errorCode); // Worker thread @@ -307,6 +308,13 @@ static int processDeleteTask(HttpClient *client, HttpRequest *request, write_cal return ok ? 0 : 1; } +//Process PATCH Request +static int processPatchTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream, char *errorBuffer) { + CURLRaii curl; + bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_CUSTOMREQUEST, "PATCH") && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData()) && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize()) && curl.perform(responseCode); + return ok ? 0 : 1; +} + // HttpClient implementation HttpClient *HttpClient::getInstance() { if (_httpClient == nullptr) { @@ -511,6 +519,16 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) responseMessage); break; + case HttpRequest::Type::PATCH: + retValue = processPatchTask(this, request, + writeData, + response->getResponseData(), + &responseCode, + writeHeaderData, + response->getResponseHeader(), + responseMessage); + break; + default: CC_ABORT(); break; diff --git a/native/cocos/network/HttpRequest.h b/native/cocos/network/HttpRequest.h index 31d01f04b6e..ef0ffbf4a2c 100644 --- a/native/cocos/network/HttpRequest.h +++ b/native/cocos/network/HttpRequest.h @@ -72,6 +72,7 @@ class CC_DLL HttpRequest : public RefCounted { PUT, DELETE, HEAD, + PATCH, UNKNOWN, }; diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosHttpURLConnection.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosHttpURLConnection.java index c5bb2e72c44..221298649c7 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosHttpURLConnection.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosHttpURLConnection.java @@ -59,6 +59,7 @@ public class CocosHttpURLConnection private static String TAG = "CocosHttpURLConnection"; private static final String POST_METHOD = "POST" ; private static final String PUT_METHOD = "PUT" ; + private static final String PATCH_METHOD = "PATCH" ; static HttpURLConnection createHttpURLConnection(String linkURL) { URL url; @@ -86,7 +87,7 @@ static void setReadAndConnectTimeout(HttpURLConnection urlConnection, int readMi static void setRequestMethod(HttpURLConnection urlConnection, String method){ try { urlConnection.setRequestMethod(method); - if(method.equalsIgnoreCase(POST_METHOD) || method.equalsIgnoreCase(PUT_METHOD)) { + if(method.equalsIgnoreCase(POST_METHOD) || method.equalsIgnoreCase(PUT_METHOD) || method.equalsIgnoreCase(PATCH_METHOD)) { urlConnection.setDoOutput(true); } } catch (ProtocolException e) { diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHttpURLConnection.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHttpURLConnection.java index e2faea71ed6..fb3d202a455 100644 --- a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHttpURLConnection.java +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHttpURLConnection.java @@ -61,6 +61,7 @@ public class CocosHttpURLConnection { private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, "CocosHttpURLConnection"); private static final String POST_METHOD = "POST"; private static final String PUT_METHOD = "PUT"; + private static final String PATCH_METHOD = "PATCH"; @SuppressWarnings("unused") static HttpURLConnection createHttpURLConnection(String linkURL) { diff --git a/platforms/native/builtin/jsb-adapter/fetch.js b/platforms/native/builtin/jsb-adapter/fetch.js index 2ec5efb8686..e776a89f9ee 100644 --- a/platforms/native/builtin/jsb-adapter/fetch.js +++ b/platforms/native/builtin/jsb-adapter/fetch.js @@ -289,7 +289,7 @@ function Body () { } // HTTP methods whose capitalization should be normalized -const methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; +const methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH']; function normalizeMethod (method) { const upcased = method.toUpperCase(); From b48581d91a42a3bf5419ff2dc503c9cb23cca89c Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Wed, 9 Aug 2023 15:23:40 +0800 Subject: [PATCH 116/232] V3.8.1 pipeline (#15875) --- cocos/core/geometry/intersect.ts | 54 +- cocos/gfx/base/define.ts | 3 +- cocos/render-scene/scene/camera.ts | 39 +- cocos/rendering/custom/compiler.ts | 118 +- cocos/rendering/custom/define.ts | 65 +- cocos/rendering/custom/executor.ts | 418 +- cocos/rendering/custom/scene-culling.ts | 416 ++ cocos/rendering/custom/web-pipeline-types.ts | 234 + cocos/rendering/custom/web-pipeline.ts | 36 +- .../post-process/passes/forward-pass.ts | 20 +- .../post-process/passes/skin-pass.ts | 52 +- .../cocos/renderer/gfx-base/GFXDef-common.h | 16 +- native/cocos/renderer/gfx-base/GFXTexture.cpp | 2 + native/cocos/renderer/gfx-base/GFXTexture.h | 2 +- .../renderer/gfx-gles3/GLES3Commands.cpp | 19 +- .../renderer/gfx-gles3/GLES3GPUObjects.h | 2 + .../renderer/gfx-gles3/GLES3PipelineState.cpp | 12 +- .../cocos/renderer/gfx-gles3/GLES3Texture.cpp | 2 + .../renderer/gfx-metal/MTLCommandBuffer.mm | 11 +- native/cocos/renderer/gfx-metal/MTLDevice.mm | 2 +- .../renderer/gfx-metal/MTLPipelineState.mm | 5 +- .../cocos/renderer/gfx-metal/MTLRenderPass.mm | 8 +- native/cocos/renderer/gfx-metal/MTLShader.mm | 8 +- native/cocos/renderer/gfx-metal/MTLTexture.mm | 11 +- native/cocos/renderer/gfx-metal/MTLUtils.h | 3 +- native/cocos/renderer/gfx-metal/MTLUtils.mm | 20 +- .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 31 +- .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 2 + .../cocos/renderer/gfx-vulkan/VKTexture.cpp | 4 + .../pipeline/custom/FGDispatcherGraphs.h | 1786 +++---- .../pipeline/custom/FGDispatcherTypes.cpp | 280 +- .../pipeline/custom/FGDispatcherTypes.h | 953 ++-- .../pipeline/custom/FrameGraphDispatcher.cpp | 4130 ++++++++--------- .../pipeline/custom/NativeExecutor.cpp | 359 +- .../pipeline/custom/NativePipeline.cpp | 50 +- .../pipeline/custom/NativeRenderGraph.cpp | 36 +- .../pipeline/custom/NativeRenderGraphUtils.h | 13 + .../pipeline/custom/NativeResourceGraph.cpp | 35 +- .../pipeline/custom/NativeSceneCulling.cpp | 55 +- .../renderer/pipeline/custom/test/test.h | 300 +- .../src/complicated_barrier_case.cpp | 201 +- .../unit-test/src/simple_barrier_test.cpp | 40 +- .../src/simple_closed_barrier_test.cpp | 137 +- 43 files changed, 4951 insertions(+), 5039 deletions(-) create mode 100644 cocos/rendering/custom/scene-culling.ts create mode 100644 cocos/rendering/custom/web-pipeline-types.ts diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index 157b6578dfa..fff0a2702dc 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -413,10 +413,12 @@ const lineTriangle = (function (): (line: Line, triangle: Triangle, outPt?: Vec3 const u = 1.0 - v - w; // outPt = u*a + v*d + w*c; - Vec3.set(outPt, + Vec3.set( + outPt, triangle.a.x * u + triangle.b.x * v + triangle.c.x * w, triangle.a.y * u + triangle.b.y * v + triangle.c.y * w, - triangle.a.z * u + triangle.b.z * v + triangle.c.z * w); + triangle.a.z * u + triangle.b.z * v + triangle.c.z * w, + ); } return 1; @@ -527,38 +529,54 @@ function getAABBVertices (min: Vec3, max: Vec3, out: Vec3[]): void { } function getOBBVertices (c: Vec3, e: Vec3, a1: Vec3, a2: Vec3, a3: Vec3, out: Vec3[]): void { - Vec3.set(out[0], + Vec3.set( + out[0], c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z, - c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z); - Vec3.set(out[1], + c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z, + ); + Vec3.set( + out[1], c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z, - c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z); - Vec3.set(out[2], + c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z, + ); + Vec3.set( + out[2], c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z, - c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z); - Vec3.set(out[3], + c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z, + ); + Vec3.set( + out[3], c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z, - c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z); - Vec3.set(out[4], + c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[4], c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z, - c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z); - Vec3.set(out[5], + c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[5], c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z, - c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z); - Vec3.set(out[6], + c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[6], c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z, - c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z); - Vec3.set(out[7], + c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[7], c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z, - c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z); + c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z, + ); } function getInterval (vertices: any[] | Vec3[], axis: Vec3): number[] { diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 53eeb4062cb..6e614fb3630 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -407,7 +407,8 @@ export enum TextureFlagBit { GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments EXTERNAL_OES = 0x4, // External oes texture EXTERNAL_NORMAL = 0x8, // External normal texture - LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. + LAZILY_ALLOCATED = 0x10, // Try lazily allocated mode. + MUTABLE_VIEW_FORMAT = 0x40, // texture view as different format } export enum FormatFeatureBit { diff --git a/cocos/render-scene/scene/camera.ts b/cocos/render-scene/scene/camera.ts index 31171d10aca..ab8cedbd6c2 100644 --- a/cocos/render-scene/scene/camera.ts +++ b/cocos/render-scene/scene/camera.ts @@ -1032,14 +1032,33 @@ export class Camera { const wndXREye = xr.webXRWindowMap.get(this._window); this._matProj.set(xr.webXRMatProjs[wndXREye]); } else { - Mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip, - this._fovAxis === CameraFOVAxis.VERTICAL, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation); + Mat4.perspective( + this._matProj, + this._fov, + this._aspect, + this._nearClip, + this._farClip, + this._fovAxis === CameraFOVAxis.VERTICAL, + this._device.capabilities.clipSpaceMinZ, + projectionSignY, + orientation, + ); } } else { const x = this._orthoHeight * this._aspect; const y = this._orthoHeight; - Mat4.ortho(this._matProj, -x, x, -y, y, this._nearClip, this._farClip, - this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation); + Mat4.ortho( + this._matProj, + -x, + x, + -y, + y, + this._nearClip, + this._farClip, + this._device.capabilities.clipSpaceMinZ, + projectionSignY, + orientation, + ); } Mat4.invert(this._matProjInv, this._matProj); viewProjDirty = true; @@ -1240,10 +1259,12 @@ export class Camera { if (this._proj === CameraProjection.PERSPECTIVE) { // calculate screen pos in far clip plane - Vec3.set(out, + Vec3.set( + out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, - 1.0); + 1.0, + ); // transform to world const { x, y } = out; @@ -1256,10 +1277,12 @@ export class Camera { Vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z)); } else { - Vec3.set(out, + Vec3.set( + out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, - screenPos.z * 2 - 1); + screenPos.z * 2 - 1, + ); // transform to world const { x, y } = out; diff --git a/cocos/rendering/custom/compiler.ts b/cocos/rendering/custom/compiler.ts index 651729239d3..da170462e25 100644 --- a/cocos/rendering/custom/compiler.ts +++ b/cocos/rendering/custom/compiler.ts @@ -32,68 +32,50 @@ import { Blit, ClearView, ComputePass, ComputeSubpass, CopyPass, Dispatch, Forma RasterPass, RasterSubpass, RaytracePass, RenderGraph, RenderGraphVisitor, RasterView, ComputeView, RenderQueue, RenderSwapchain, ResolvePass, ResourceGraph, ResourceGraphVisitor, SceneData, SubresourceView } from './render-graph'; import { AccessType, ResourceResidency, SceneFlags } from './types'; +import { hashCombineNum, hashCombineStr } from './define'; -let hashCode = 0; - -function hashCombine (hash): void { - hashCode ^= (hash >>> 0) + 0x9e3779b9 + (hashCode << 6) + (hashCode >> 2); -} - -function hashCombineNum (val: number): void { - const hash = 5381; - hashCombine((hash * 33) ^ val); -} - -function hashCombineStr (str: string): void { - // DJB2 HASH - let hash = 5381; - for (let i = 0; i < str.length; i++) { - hash = (hash * 33) ^ str.charCodeAt(i); - } - hashCombine(hash); -} function genHashValue (pass: RasterPass): void { - hashCode = 0; + let hashCode = 0; for (const [name, raster] of pass.rasterViews) { - hashCombineStr('raster'); - hashCombineStr(name); - hashCombineStr(raster.slotName); - hashCombineNum(raster.accessType); - hashCombineNum(raster.attachmentType); - hashCombineNum(raster.loadOp); - hashCombineNum(raster.storeOp); - hashCombineNum(raster.clearFlags); - hashCombineNum(raster.clearColor.x); - hashCombineNum(raster.clearColor.y); - hashCombineNum(raster.clearColor.z); - hashCombineNum(raster.clearColor.w); - hashCombineNum(raster.slotID); - hashCombineNum(raster.shaderStageFlags); + hashCode = hashCombineStr('raster', hashCode); + hashCode = hashCombineStr(name, hashCode); + hashCode = hashCombineStr(raster.slotName, hashCode); + hashCode = hashCombineNum(raster.accessType, hashCode); + hashCode = hashCombineNum(raster.attachmentType, hashCode); + hashCode = hashCombineNum(raster.loadOp, hashCode); + hashCode = hashCombineNum(raster.storeOp, hashCode); + hashCode = hashCombineNum(raster.clearFlags, hashCode); + hashCode = hashCombineNum(raster.clearColor.x, hashCode); + hashCode = hashCombineNum(raster.clearColor.y, hashCode); + hashCode = hashCombineNum(raster.clearColor.z, hashCode); + hashCode = hashCombineNum(raster.clearColor.w, hashCode); + hashCode = hashCombineNum(raster.slotID, hashCode); + hashCode = hashCombineNum(raster.shaderStageFlags, hashCode); } for (const [name, computes] of pass.computeViews) { - hashCombineStr(name); + hashCode = hashCombineStr(name, hashCode); for (const compute of computes) { - hashCombineStr('compute'); - hashCombineStr(compute.name); - hashCombineNum(compute.accessType); - hashCombineNum(compute.clearFlags); - hashCombineNum(compute.clearValueType); - hashCombineNum(compute.clearValue.x); - hashCombineNum(compute.clearValue.y); - hashCombineNum(compute.clearValue.z); - hashCombineNum(compute.clearValue.w); - hashCombineNum(compute.shaderStageFlags); + hashCode = hashCombineStr('compute', hashCode); + hashCode = hashCombineStr(compute.name, hashCode); + hashCode = hashCombineNum(compute.accessType, hashCode); + hashCode = hashCombineNum(compute.clearFlags, hashCode); + hashCode = hashCombineNum(compute.clearValueType, hashCode); + hashCode = hashCombineNum(compute.clearValue.x, hashCode); + hashCode = hashCombineNum(compute.clearValue.y, hashCode); + hashCode = hashCombineNum(compute.clearValue.z, hashCode); + hashCode = hashCombineNum(compute.clearValue.w, hashCode); + hashCode = hashCombineNum(compute.shaderStageFlags, hashCode); } } - hashCombineNum(pass.width); - hashCombineNum(pass.height); - hashCombineNum(pass.viewport.left); - hashCombineNum(pass.viewport.top); - hashCombineNum(pass.viewport.width); - hashCombineNum(pass.viewport.height); - hashCombineNum(pass.viewport.minDepth); - hashCombineNum(pass.viewport.maxDepth); - hashCombineNum(pass.showStatistics ? 1 : 0); + hashCode = hashCombineNum(pass.width, hashCode); + hashCode = hashCombineNum(pass.height, hashCode); + hashCode = hashCombineNum(pass.viewport.left, hashCode); + hashCode = hashCombineNum(pass.viewport.top, hashCode); + hashCode = hashCombineNum(pass.viewport.width, hashCode); + hashCode = hashCombineNum(pass.viewport.height, hashCode); + hashCode = hashCombineNum(pass.viewport.minDepth, hashCode); + hashCode = hashCombineNum(pass.viewport.maxDepth, hashCode); + hashCode = hashCombineNum(pass.showStatistics ? 1 : 0, hashCode); pass.hashValue = hashCode; } @@ -157,8 +139,10 @@ class PassVisitor implements RenderGraphVisitor { isPreRaster = true; // TODO: Shadow map is rather special, as it will be merged into one pass later, and then this determination can be removed. if (!this._isShadowMap(this.sceneID)) { - assert(currRaster.loadOp === LoadOp.LOAD, - `The resource with name ${input} is being used, and the pass that uses this resource must have loadOp set to 'load'`); + assert( + currRaster.loadOp === LoadOp.LOAD, + `The resource with name ${input} is being used, and the pass that uses this resource must have loadOp set to 'load'`, + ); } } } @@ -287,7 +271,7 @@ class PassVisitor implements RenderGraphVisitor { this._currPass = value; const outputId = this.resID; const outputName = resourceGraph.vertexName(outputId); - let vertID; + let vertID: number; for (const pair of value.copyPairs) { if (pair.target === outputName) { rg.setValid(this.passID, true); @@ -345,7 +329,7 @@ class PassManagerVisitor extends DefaultVisitor { class ResourceVisitor implements ResourceGraphVisitor { private readonly _context: CompilerContext; public resID = 0xFFFFFFFF; - private _passManagerVis; + private _passManagerVis!: PassManagerVisitor; constructor (context: CompilerContext) { this._context = context; } @@ -392,10 +376,12 @@ class ResourceUseContext { computes: Map = new Map(); } class CompilerContext { - set (pipeline: BasicPipeline, + set ( + pipeline: BasicPipeline, resGraph: ResourceGraph, renderGraph: RenderGraph, - layoutGraph: LayoutGraphData): void { + layoutGraph: LayoutGraphData, + ): void { this.pipeline = pipeline; this.resourceGraph = resGraph; this.renderGraph = renderGraph; @@ -417,10 +403,12 @@ export class Compiler { private _pipeline: BasicPipeline; private _layoutGraph: LayoutGraphData; private _visitor: ResourceManagerVisitor; - constructor (pipeline: BasicPipeline, + constructor ( + pipeline: BasicPipeline, renderGraph: RenderGraph, resGraph: ResourceGraph, - layoutGraph: LayoutGraphData) { + layoutGraph: LayoutGraphData, + ) { this._pipeline = pipeline; this._resourceGraph = resGraph; this._layoutGraph = layoutGraph; @@ -447,8 +435,10 @@ export class Compiler { const firstRaster = use.rasters.get(min)!; switch (trait.residency) { case ResourceResidency.PERSISTENT: - assert(firstRaster.loadOp !== LoadOp.DISCARD, - `The loadOp for persistent resources in the top-level pass cannot be set to 'discard'.`); + assert( + firstRaster.loadOp !== LoadOp.DISCARD, + `The loadOp for persistent resources in the top-level pass cannot be set to 'discard'.`, + ); break; case ResourceResidency.MANAGED: assert(firstRaster.loadOp === LoadOp.CLEAR, `The loadOp for Managed resources in the top-level pass can only be set to 'clear'.`); diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index a2a983c9b3b..b131e820357 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -44,9 +44,9 @@ import { Vec2, Vec3, Vec4, macro, geometry, toRadian, cclegacy, assert, nextPow2 import { ImageAsset, Material, Texture2D } from '../../asset/assets'; import { getProfilerCamera, SRGBToLinear } from '../pipeline-funcs'; import { RenderWindow } from '../../render-scene/core/render-window'; -import { RenderData } from './render-graph'; +import { RenderData, RenderGraph } from './render-graph'; import { WebPipeline } from './web-pipeline'; -import { DescriptorSetData } from './layout-graph'; +import { DescriptorSetData, LayoutGraph, LayoutGraphData } from './layout-graph'; import { AABB } from '../../core/geometry'; import { DebugViewCompositeType, DebugViewSingleType } from '../debug-view'; import { ReflectionProbeManager } from '../../3d/reflection-probe/reflection-probe-manager'; @@ -685,7 +685,7 @@ export function buildShadowPass ( queue.addSceneOfCamera( camera, new LightInfo(light, level), - SceneFlags.SHADOW_CASTER, + SceneFlags.SHADOW_CASTER | SceneFlags.OPAQUE_OBJECT | SceneFlags.TRANSPARENT_OBJECT, ); queue.setViewport(new Viewport(area.x, area.y, area.width, area.height)); } @@ -706,6 +706,7 @@ export function buildReflectionProbePasss ( } else if (EDITOR) { for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) { probe.updateCameraDir(faceIdx); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument buildReflectionProbePass(camera, ppl, probe, probe.bakedCubeTextures[faceIdx].window!, faceIdx); } probe.needRender = false; @@ -1127,7 +1128,9 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa const constants = data.constants; const samplers = data.samplers; const textures = data.textures; - const device = cclegacy.director.root.device; + const root = cclegacy.director.root; + const device = root.device; + const pipeline = root.pipeline as WebPipeline; const descriptorSetData = getDescriptorSetDataFromLayout(layout)!; const descriptorSet = descriptorSetData.descriptorSet!; for (const [key, value] of constants) { @@ -1160,7 +1163,7 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa const bindId = getDescBinding(key, descriptorSetData); if (bindId === -1) { continue; } const tex = descriptorSet.getTexture(bindId); - if (!tex || isUpdate) { + if (!tex || (isUpdate && value !== pipeline.defaultTexture)) { bindGlobalDesc(descriptorSet, bindId, value); } } @@ -1168,7 +1171,7 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa const bindId = getDescBinding(key, descriptorSetData); if (bindId === -1) { continue; } const sampler = descriptorSet.getSampler(bindId); - if (!sampler || isUpdate) { + if (!sampler || (isUpdate && value !== pipeline.defaultSampler)) { bindGlobalDesc(descriptorSet, bindId, value); } } @@ -2440,3 +2443,53 @@ export function buildClusterPasses (camera: Camera, pipeline: BasicPipeline): vo buildLightClusterBuildPass(camera, _clusterLightData, ppl); buildLightClusterCullingPass(camera, _clusterLightData, ppl); } + +function hashCombine (hash, currHash: number): number { + return currHash ^= (hash >>> 0) + 0x9e3779b9 + (currHash << 6) + (currHash >> 2); +} + +export function hashCombineNum (val: number, currHash: number): number { + const hash = 5381; + return hashCombine((hash * 33) ^ val, currHash); +} + +export function hashCombineStr (str: string, currHash: number): number { + // DJB2 HASH + let hash = 5381; + for (let i = 0; i < str.length; i++) { + hash = (hash * 33) ^ str.charCodeAt(i); + } + return hashCombine(hash, currHash); +} + +export function bool (val): boolean { + return !!val; +} + +export function getSubpassOrPassID (sceneId: number, rg: RenderGraph, lg: LayoutGraphData): number { + const queueId = rg.getParent(sceneId); + assert(queueId !== 0xFFFFFFFF); + const subpassOrPassID = rg.getParent(queueId); + assert(subpassOrPassID !== 0xFFFFFFFF); + const passId = rg.getParent(subpassOrPassID); + let layoutId = lg.nullVertex(); + // single render pass + if (passId === rg.nullVertex()) { + const layoutName: string = rg.getLayout(subpassOrPassID); + assert(!!layoutName); + layoutId = lg.locateChild(lg.nullVertex(), layoutName); + } else { + const passLayoutName: string = rg.getLayout(passId); + assert(!!passLayoutName); + const passLayoutId = lg.locateChild(lg.nullVertex(), passLayoutName); + assert(passLayoutId !== lg.nullVertex()); + + const subpassLayoutName: string = rg.getLayout(subpassOrPassID); + assert(!!subpassLayoutName); + const subpassLayoutId = lg.locateChild(passLayoutId, subpassLayoutName); + assert(subpassLayoutId !== lg.nullVertex()); + layoutId = subpassLayoutId; + } + assert(layoutId !== lg.nullVertex()); + return layoutId; +} diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 548ab24cc3d..445a712e1ed 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -72,7 +72,7 @@ import { import { legacyCC } from '../../core/global-exports'; import { Vec3 } from '../../core/math/vec3'; import { Vec4 } from '../../core/math/vec4'; -import { BatchingSchemes, Pass } from '../../render-scene'; +import { Pass } from '../../render-scene'; import { Camera } from '../../render-scene/scene/camera'; import { ShadowType } from '../../render-scene/scene/shadows'; import { Root } from '../../root'; @@ -125,8 +125,6 @@ import { PipelineUBO } from '../pipeline-ubo'; import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; import { RenderAdditiveLightQueue } from '../render-additive-light-queue'; -import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue'; -import { PlanarShadowQueue } from '../planar-shadow-queue'; import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph'; import { VectorGraphColorMap } from './effect'; import { @@ -141,6 +139,7 @@ import { import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; import { Texture2D } from '../../asset/assets/texture-2d'; +import { SceneCulling } from './scene-culling'; class ResourceVisitor implements ResourceGraphVisitor { name: string; @@ -448,7 +447,7 @@ class BlitDesc { const deferredLitsBufView = context.blit.deferredLitsBufView; this._lightBufferData = context.blit.lightBufferData; this._lightBufferData.fill(0); - const binding = isEnableEffect() ? getDescBindingFromName('CCForwardLight') : UBOForwardLight.BINDING; + // const binding = isEnableEffect() ? getDescBindingFromName('CCForwardLight') : UBOForwardLight.BINDING; this._stageDesc.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView); } this._stageDesc.bindBuffer(UBOLocal.BINDING, context.blit.emptyLocalUBO); @@ -506,7 +505,7 @@ class DeviceRenderQueue { } this.queueId = id; this._devicePass = devicePass; - if (isEnableEffect()) this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id) || 'default'); + this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id)); if (!this._sceneVisitor) { this._sceneVisitor = new WebSceneVisitor( context.commandBuffer, @@ -573,39 +572,11 @@ class DeviceRenderQueue { } class SubmitInfo { - public instances = new Set(); - public renderInstanceQueue: InstancedBuffer[] = []; - public opaqueList: RenderInfo[] = []; - public transparentList: RenderInfo[] = []; - public planarQueue: PlanarShadowQueue | null = null; // - public shadowMap: Map = new Map(); public additiveLight: RenderAdditiveLightQueue | null = null; public reflectionProbe: RenderReflectionProbeQueue | null = null; - private _clearInstances (): void { - const it = this.instances.values(); let res = it.next(); - while (!res.done) { - res.value.clear(); - res = it.next(); - } - this.instances.clear(); - } - - private _clearShadowMap (): void { - for (const shadowMap of this.shadowMap) { - shadowMap[1].clear(); - } - this.shadowMap.clear(); - } - reset (): void { - this._clearInstances(); - this.renderInstanceQueue.length = 0; - this.opaqueList.length = 0; - this.transparentList.length = 0; - this.planarQueue = null; - this._clearShadowMap(); this.additiveLight = null; this.reflectionProbe = null; } @@ -961,23 +932,7 @@ class DeviceRenderPass { cmdBuff.endRenderPass(); } - private _clear (): void { - for (const [cam, infoMap] of context.submitMap) { - for (const [id, info] of infoMap) { - info.additiveLight?.clear(); - const it = info.instances.values(); let res = it.next(); - while (!res.done) { - res.value.clear(); - res = it.next(); - } - info.renderInstanceQueue = []; - info.instances.clear(); - } - } - } - postPass (): void { - this._clear(); // this.submitMap.clear(); for (const queue of this._deviceQueues) { queue.postRecord(); @@ -1151,182 +1106,17 @@ class DevicePreSceneTask extends WebSceneTask { public start (): void { if (this.graphScene.blit) { this._currentQueue.createBlitDesc(this.graphScene.blit); - return; - } - if (!this.camera) { - return; } - const devicePass = this._currentQueue.devicePass; - const submitMap = context.submitMap; - let submitInfoMap = submitMap.get(this.camera); - if (submitInfoMap && submitInfoMap.has(this._currentQueue.phaseID)) { - this._submitInfo = submitInfoMap.get(this._currentQueue.phaseID)!; - } else { - if (!submitInfoMap) { - submitInfoMap = new Map(); - submitMap.set(this.camera, submitInfoMap); - } - this._submitInfo = new SubmitInfo(); - submitInfoMap.set(this._currentQueue.phaseID, this._submitInfo); - } - // culling - if ((!isShadowMap(this.graphScene) || (isShadowMap(this.graphScene) && this.graphScene.scene!.light.level === 0)) - && this.camera !== context.cullCamera) { - super.start(); - context.cullCamera = this.camera; - } - - // shadowmap - if (isShadowMap(this.graphScene)) { - const scene = this.graphScene.scene!; - assert(scene.light.light !== null); - let shadowQueue = this._submitInfo.shadowMap.get(this.graphScene.sceneID); - if (!shadowQueue) { - shadowQueue = new RenderShadowMapBatchedQueue(context.pipeline); - this._submitInfo.shadowMap.set(this.graphScene.sceneID, shadowQueue); - } - this.sceneData.shadowFrameBufferMap.set(scene.light.light, devicePass.framebuffer); - shadowQueue.gatherLightPasses(this.camera, scene.light.light, this._cmdBuff, scene.light.level); - return; - } - // reflection probe - if (this.graphScene.scene!.flags & SceneFlags.REFLECTION_PROBE && !this._submitInfo.reflectionProbe) { - this._submitInfo.reflectionProbe = context.pools.addReflectionProbe(); - this._submitInfo.reflectionProbe.clear(); - if (cclegacy.internal.reflectionProbeManager) { - const probes = cclegacy.internal.reflectionProbeManager.getProbes(); - for (let i = 0; i < probes.length; i++) { - if (probes[i].hasFrameBuffer(this._currentQueue.devicePass.framebuffer)) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._submitInfo.reflectionProbe.gatherRenderObjects(probes[i], this.camera, this._cmdBuff); - break; - } - } - } - return; - } - const sceneFlag = this._graphScene.scene!.flags; - // If it is not empty, it means that it has been added and will not be traversed. - const isEmpty = !this._submitInfo.opaqueList.length - && !this._submitInfo.transparentList.length - && !this._submitInfo.instances.size; - if (isEmpty) { - for (const ro of this.sceneData.renderObjects) { - const subModels = ro.model.subModels; - for (const subModel of subModels) { - const passes = subModel.passes; - for (const p of passes) { - if (((isEnableEffect()) ? p.phaseID : p.phase) !== this._currentQueue.phaseID) continue; - const batchingScheme = p.batchingScheme; - if (batchingScheme === BatchingSchemes.INSTANCING) { - const instancedBuffer = p.getInstancedBuffer(); - instancedBuffer.merge(subModel, passes.indexOf(p)); - this._submitInfo.instances.add(instancedBuffer); - } else { - this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p)); - this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p), true); - } - } - } - } - this._instancedSort(); - } - if (sceneFlag & SceneFlags.DEFAULT_LIGHTING) { - this._submitInfo.additiveLight = context.additiveLight; - validPunctualLightsCulling(context.pipeline, this.camera); - this._submitInfo.additiveLight.gatherLightPasses(this.camera, this._cmdBuff, this._currentQueue.devicePass.layoutName); - } - if (sceneFlag & SceneFlags.PLANAR_SHADOW) { - this._submitInfo.planarQueue = context.planarShadow; - this._submitInfo.planarQueue.gatherShadowPasses(this.camera, this._cmdBuff); - } - if (sceneFlag & SceneFlags.OPAQUE_OBJECT) { this._submitInfo.opaqueList.sort(this._opaqueCompareFn); } - if (sceneFlag & SceneFlags.TRANSPARENT_OBJECT) { this._submitInfo.transparentList.sort(this._transparentCompareFn); } - } - - protected _instancedSort (): void { - let it = this._submitInfo!.instances.values(); - let res = it.next(); - while (!res.done) { - if (!(res.value.pass.blendState.targets[0].blend)) { - this._submitInfo!.renderInstanceQueue.push(res.value); - } - res = it.next(); - } - it = this._submitInfo!.renderInstanceQueue.values(); - res = it.next(); - while (!res.done) { - if (res.value.pass.blendState.targets[0].blend) { - this._submitInfo!.renderInstanceQueue.push(res.value); - } - res = it.next(); - } - } - - protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false): void { - const subModel = ro.model.subModels[subModelIdx]; - const pass: Pass = subModel.passes[passIdx]; - const shader = subModel.shaders[passIdx]; - const currTransparent = pass.blendState.targets[0].blend; - const devicePass = this._currentQueue.devicePass; - const passId = devicePass.passID; - const phase = isEnableEffect() ? this._currentQueue.phaseID // | cclegacy.rendering.getPhaseID(passId, 'planarShadow') - : getPhaseID('default') | getPhaseID('planarShadow'); - if (currTransparent !== isTransparent || !(pass.phaseID & (isTransparent ? phase : this._currentQueue.phaseID))) { - return; - } - const hash = (0 << 30) | pass.priority as number << 16 | subModel.priority as number << 8 | passIdx; - const rp = context.pools.addPassInfo(); - rp.priority = ro.model.priority; - rp.hash = hash; - rp.depth = ro.depth || 0; - rp.shaderId = shader.typedID; - rp.subModel = subModel; - rp.passIdx = passIdx; - if (isTransparent) this._submitInfo!.transparentList.push(rp); - else this._submitInfo!.opaqueList.push(rp); - } - - /** - * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. - * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 - */ - protected _opaqueCompareFn (a: RenderInfo, b: RenderInfo): number { - return (a.hash - b.hash) || (a.depth - b.depth) || (a.shaderId - b.shaderId); - } - /** - * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. - * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 - */ - protected _transparentCompareFn (a: RenderInfo, b: RenderInfo): number { - return (a.priority - b.priority) || (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); - } - - private _uploadInstanceBuffers (): void { - if (this._currentQueue.isUploadInstance) return; - const it = this._submitInfo!.instances.values(); let res = it.next(); - while (!res.done) { - if (res.value.hasPendingModels) res.value.uploadBuffers(this._cmdBuff); - res = it.next(); - } - this._currentQueue.isUploadInstance = true; - } - - protected _updateGlobal (data: RenderData): void { - const devicePass = this._currentQueue.devicePass; - updateGlobalDescBinding(data, isEnableEffect() ? context.renderGraph.getLayout(devicePass.rasterPassInfo.id) : 'default'); - if (!isEnableEffect()) context.pipeline.descriptorSet.update(); } public submit (): void { if (this.graphScene.blit) { this._currentQueue.blitDesc!.update(); - return; - } - if (isShadowMap(this.graphScene)) { - return; } - this._uploadInstanceBuffers(); + // if (isShadowMap(this.graphScene)) { + + // } + // this._uploadInstanceBuffers(); } } @@ -1358,70 +1148,7 @@ class DeviceSceneTask extends WebSceneTask { } get graphScene (): GraphScene { return this._graphScene; } public start (): void {} - protected _recordRenderList (isTransparent: boolean): void { - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - const renderList = isTransparent ? currSubmitInfo.transparentList - : currSubmitInfo.opaqueList; - for (let i = 0; i < renderList.length; ++i) { - const { subModel, passIdx } = renderList[i]; - const inputAssembler: InputAssembler = subModel.inputAssembler; - const pass: Pass = subModel.passes[passIdx]; - const shader: Shader = subModel.shaders[passIdx]; - const descriptorSet: DescriptorSet = subModel.descriptorSet; - const pso = PipelineStateManager.getOrCreatePipelineState( - deviceManager.gfxDevice, - pass, - shader, - this._renderPass, - inputAssembler, - ); - this.visitor.bindPipelineState(pso); - this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); - this.visitor.bindDescriptorSet(SetIndex.LOCAL, descriptorSet); - this.visitor.bindInputAssembler(inputAssembler); - this.visitor.draw(inputAssembler); - } - } - protected _recordOpaqueList (): void { - this._recordRenderList(false); - } - protected _recordInstences (): void { - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - const it = currSubmitInfo.renderInstanceQueue.length === 0 - ? currSubmitInfo.instances.values() - : currSubmitInfo.renderInstanceQueue.values(); - let res = it.next(); - while (!res.done) { - const { instances, pass, hasPendingModels } = res.value; - if (hasPendingModels) { - this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); - let lastPSO: PipelineState | null = null; - for (let b = 0; b < instances.length; ++b) { - const instance = instances[b]; - if (!instance.count) { continue; } - const shader = instance.shader!; - const pso = PipelineStateManager.getOrCreatePipelineState( - deviceManager.gfxDevice, - pass, - shader, - this._renderPass, - instance.ia, - ); - if (lastPSO !== pso) { - this.visitor.bindPipelineState(pso); - lastPSO = pso; - } - const ia: InputAssembler = instance.ia; - this.visitor.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets); - this.visitor.bindInputAssembler(ia); - this.visitor.draw(ia); - } - } - res = it.next(); - } - } + protected _recordUI (): void { const batches = this.camera!.scene!.batches; for (let i = 0; i < batches.length; i++) { @@ -1436,7 +1163,7 @@ class DeviceSceneTask extends WebSceneTask { const count = batch.shaders.length; for (let j = 0; j < count; j++) { const pass = batch.passes[j]; - if (((isEnableEffect()) ? pass.phaseID : pass.phase) !== this._currentQueue.phaseID) continue; + if (pass.phaseID !== this._currentQueue.phaseID) continue; const shader = batch.shaders[j]; const inputAssembler: InputAssembler = batch.inputAssembler!; const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, shader, this._renderPass, inputAssembler); @@ -1449,19 +1176,7 @@ class DeviceSceneTask extends WebSceneTask { } } } - protected _recordTransparentList (): void { - this._recordRenderList(true); - } - protected _recordShadowMap (): void { - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.shadowMap.get(this.graphScene.sceneID)!.recordCommandBuffer( - context.device, - this._renderPass, - context.commandBuffer, - ); - } protected _recordReflectionProbe (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; @@ -1513,63 +1228,22 @@ class DeviceSceneTask extends WebSceneTask { this.visitor.bindPipelineState(pso); const layoutStage = devicePass.renderLayout; const layoutDesc = layoutStage!.descriptorSet!; - const extResId: number[] = isEnableEffect() ? [] : mergeSrcToTargetDesc(pass.descriptorSet, layoutDesc); + const extResId: number[] = []; // if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc); - this.visitor.bindDescriptorSet(SetIndex.MATERIAL, isEnableEffect() ? pass.descriptorSet : layoutDesc); + this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); this.visitor.bindDescriptorSet(SetIndex.LOCAL, this._currentQueue.blitDesc!.stageDesc!); this.visitor.bindInputAssembler(screenIa); this.visitor.draw(screenIa); // The desc data obtained from the outside should be cleaned up so that the data can be modified this._clearExtBlitDesc(layoutDesc, extResId); - // if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, globalDesc); } } - private _recordAdditiveLights (): void { - const devicePass = this._currentQueue.devicePass; - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.additiveLight?.recordCommandBuffer( - context.device, - this._renderPass, - context.commandBuffer, - ); - } - private _recordPlanarShadows (): void { - const devicePass = this._currentQueue.devicePass; - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.planarQueue?.recordCommandBuffer( - context.device, - this._renderPass, - context.commandBuffer, - ); - } protected _updateGlobal (data: RenderData): void { const devicePass = this._currentQueue.devicePass; - updateGlobalDescBinding(data, isEnableEffect() ? context.renderGraph.getLayout(devicePass.rasterPassInfo.id) : 'default'); - if (!isEnableEffect()) context.pipeline.descriptorSet.update(); - } - protected _setMainLightShadowTex (data: RenderData): void { - const graphScene = this.graphScene; - if (graphScene.scene && graphScene.scene.camera) { - const mainLight = graphScene.scene.camera.scene!.mainLight; - const shadowFrameBufferMap = this.sceneData.shadowFrameBufferMap; - if (mainLight && shadowFrameBufferMap.has(mainLight)) { - const shadowAttrID = context.layoutGraph.attributeIndex.get('cc_shadowMap'); - const defaultTex = builtinResMgr.get('default-texture').getGFXTexture()!; - for (const [key, value] of data.textures) { - if (key === shadowAttrID) { - const tex = data.textures.get(shadowAttrID); - if (tex === defaultTex) { - data.textures.set(key, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); - } - return; - } - } - } - } + updateGlobalDescBinding(data, context.renderGraph.getLayout(devicePass.rasterPassInfo.id)); } + protected _updateRenderData (): void { if (this._currentQueue.isUpdateUBO) return; const devicePass = this._currentQueue.devicePass; @@ -1580,19 +1254,16 @@ class DeviceSceneTask extends WebSceneTask { // CCCamera, CCShadow, CCCSM const queueId = this._currentQueue.queueId; const queueRenderData = context.renderGraph.getData(queueId)!; - this._setMainLightShadowTex(queueRenderData); this._updateGlobal(queueRenderData); - if (isEnableEffect()) { - const layoutName = context.renderGraph.getLayout(rasterId); - const descSetData = getDescriptorSetDataFromLayout(layoutName); - mergeSrcToTargetDesc(descSetData!.descriptorSet, context.pipeline.descriptorSet, true); - } + + const layoutName = context.renderGraph.getLayout(rasterId); + const descSetData = getDescriptorSetDataFromLayout(layoutName); + mergeSrcToTargetDesc(descSetData!.descriptorSet, context.pipeline.descriptorSet, true); this._currentQueue.isUpdateUBO = true; } - public submit (): void { - const devicePass = this._currentQueue.devicePass; + + private _applyViewport (): void { const queueViewport = this._currentQueue.viewport; - this._updateRenderData(); if (queueViewport) { this.visitor.setViewport(queueViewport); this.visitor.setScissor(this._currentQueue.scissor!); @@ -1610,41 +1281,29 @@ class DeviceSceneTask extends WebSceneTask { this.visitor.setViewport(sceneViewport); this.visitor.setScissor(area); } + } + + public submit (): void { + const devicePass = this._currentQueue.devicePass; + const sceneCulling = context.culling; + this._updateRenderData(); + this._applyViewport(); // Currently processing blit and camera first if (this.graphScene.blit) { this._recordBlit(); return; } - if (isShadowMap(this.graphScene)) { - this._recordShadowMap(); - return; - } + const renderQueueDesc = sceneCulling.sceneQueryIndex.get(this.graphScene.sceneID)!; + const renderQueue = sceneCulling.renderQueues[renderQueueDesc.renderQueueTarget]; const graphSceneData = this.graphScene.scene!; - if (graphSceneData.flags & SceneFlags.OPAQUE_OBJECT - || graphSceneData.flags & SceneFlags.CUTOUT_OBJECT) { - this._recordOpaqueList(); - } - if (graphSceneData.flags & SceneFlags.DRAW_INSTANCING) { - this._recordInstences(); - } - if (graphSceneData.flags & SceneFlags.DEFAULT_LIGHTING) { - this._recordAdditiveLights(); - } - this.visitor.bindDescriptorSet( - SetIndex.GLOBAL, - context.pipeline.descriptorSet, - ); - if (graphSceneData.flags & SceneFlags.PLANAR_SHADOW) { - this._recordPlanarShadows(); - } - if (graphSceneData.flags & SceneFlags.TRANSPARENT_OBJECT) { - this._recordTransparentList(); - } + renderQueue.opaqueQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer); + renderQueue.opaqueInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer); + renderQueue.transparentInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer); + renderQueue.transparentQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer); if (graphSceneData.flags & SceneFlags.GEOMETRY) { this.camera!.geometryRenderer?.render( devicePass.renderPass, context.commandBuffer, - context.pipeline.pipelineSceneData, ); } @@ -1907,12 +1566,12 @@ class ExecutorContext { this.width = width; this.height = height; this.additiveLight = new RenderAdditiveLightQueue(pipeline); - this.shadowMapBatched = new RenderShadowMapBatchedQueue(pipeline); - this.planarShadow = new PlanarShadowQueue(pipeline); this.pools = new ExecutorPools(this); this.blit = new BlitInfo(this); + this.culling = new SceneCulling(); } reset (): void { + this.culling.clear(); this.pools.reset(); this.cullCamera = null; for (const infoMap of this.submitMap) { @@ -1935,11 +1594,10 @@ class ExecutorContext { readonly root: Root; readonly ubo: PipelineUBO; readonly additiveLight: RenderAdditiveLightQueue; - readonly shadowMapBatched: RenderShadowMapBatchedQueue; - readonly planarShadow: PlanarShadowQueue; readonly submitMap: Map> = new Map>(); readonly pools: ExecutorPools; readonly blit: BlitInfo; + readonly culling: SceneCulling; renderGraph: RenderGraph; width: number; height: number; @@ -1998,8 +1656,10 @@ export class Executor { execute (rg: RenderGraph): void { context.renderGraph = rg; context.reset(); - this._removeDeviceResource(); const cmdBuff = context.commandBuffer; + context.culling.buildRenderQueues(rg, context.layoutGraph, context.pipelineSceneData); + context.culling.uploadInstancing(cmdBuff); + this._removeDeviceResource(); cmdBuff.begin(); if (!this._visitor) this._visitor = new RenderVisitor(); depthFirstSearch(this._visitor.graphView, this._visitor, this._visitor.colorMap); diff --git a/cocos/rendering/custom/scene-culling.ts b/cocos/rendering/custom/scene-culling.ts new file mode 100644 index 00000000000..b337a00f6de --- /dev/null +++ b/cocos/rendering/custom/scene-culling.ts @@ -0,0 +1,416 @@ +import { Vec3, assert } from '../../core'; +import { Frustum, intersect, AABB } from '../../core/geometry'; +import { CommandBuffer } from '../../gfx'; +import { BatchingSchemes, Pass, RenderScene } from '../../render-scene'; +import { CSMLevel, Camera, DirectionalLight, Light, LightType, Model, SKYBOX_FLAG, ShadowType, SpotLight } from '../../render-scene/scene'; +import { Node } from '../../scene-graph'; +import { PipelineSceneData } from '../pipeline-scene-data'; +import { hashCombineStr, getSubpassOrPassID, bool } from './define'; +import { LayoutGraphData } from './layout-graph'; +import { RenderGraph, RenderGraphValue, SceneData } from './render-graph'; +import { SceneFlags } from './types'; +import { RenderQueue, RenderQueueDesc } from './web-pipeline-types'; + +function computeCullingKey (camera: Camera | null, light: Light | null, castShadows: boolean, lightLevel: number): number { + let hashCode = 0; + if (camera) { + // camera + hashCode = hashCombineStr(`u${camera.node.uuid}`, hashCode); + hashCode = hashCombineStr(`p${camera.priority}`, hashCode); + hashCode = hashCombineStr(`v${camera.visibility}`, hashCode); + hashCode = hashCombineStr(`f${camera.clearFlag}`, hashCode); + hashCode = hashCombineStr(`cx${camera.clearColor.x}cy${camera.clearColor.y}cz${camera.clearColor.z}cw${camera.clearColor.w}`, hashCode); + hashCode = hashCombineStr(`cd${camera.clearDepth}cs${camera.clearStencil}`, hashCode); + hashCode = hashCombineStr(`pj${camera.projectionType}`, hashCode); + hashCode = hashCombineStr(`fa${camera.fovAxis}`, hashCode); + hashCode = hashCombineStr(`fov${camera.fov}`, hashCode); + hashCode = hashCombineStr(`n${camera.nearClip}`, hashCode); + hashCode = hashCombineStr(`far${camera.farClip}`, hashCode); + hashCode = hashCombineStr(`apt${camera.aperture}`, hashCode); + hashCode = hashCombineStr(`sht${camera.shutter}`, hashCode); + hashCode = hashCombineStr(`iso${camera.iso}`, hashCode); + hashCode = hashCombineStr(`rx${camera.viewport.x}ry${camera.viewport.y}rw${camera.viewport.width}rh${camera.viewport.height}`, hashCode); + hashCode = hashCombineStr(`upp${camera.usePostProcess}`, hashCode); + } + // light + if (light) { + hashCode = hashCombineStr(`u${light.node!.uuid}`, hashCode); + // hashCode = hashCombineStr(`cx${light.finalColor.x}cy${light.finalColor.y}cz${light.finalColor.z}`, hashCode); + // hashCode = hashCombineStr(`ct${light.useColorTemperature}`, hashCode); + // hashCode = hashCombineStr(`ctv${light.colorTemperature}`, hashCode); + // hashCode = hashCombineStr(`vis${light.visibility}`, hashCode); + // hashCode = hashCombineStr(`tp${light.type}`, hashCode); + // switch (light.type) { + // case LightType.DIRECTIONAL: + // hashCode = hashCombineStr(`${(light as DirectionalLight).illuminance}`, hashCode); + // break; + // default: + // } + } + hashCode = hashCombineStr(`cast${castShadows}`, hashCode); + hashCode = hashCombineStr(`level${lightLevel}`, hashCode); + return hashCode; +} + +class CullingKey { + camera: Camera | null; + light: Light | null; + castShadows = false; + lightLevel = 0xffffffff; + constructor (camera: Camera | null, light: Light | null, castShadows: boolean, lightLevel: number) { + this.camera = camera; + this.light = light; + this.castShadows = castShadows; + this.lightLevel = lightLevel; + } +} + +let pSceneData: PipelineSceneData; + +class CullingQueries { + // key: hash val + culledResultIndex: Map = new Map(); + cullingKeyResult: Map = new Map(); +} + +function isNodeVisible (node: Node, visibility: number): boolean { + return node && ((visibility & node.layer) === node.layer); +} + +function isModelVisible (model: Model, visibility: number): boolean { + return !!(visibility & model.visFlags); +} +const transWorldBounds = new AABB(); +function isFrustumVisible (model: Model, frustum: Readonly, castShadow: boolean): boolean { + const modelWorldBounds = model.worldBounds; + if (!modelWorldBounds) { + return false; + } + transWorldBounds.copy(modelWorldBounds); + const shadows = pSceneData.shadows; + if (shadows.type === ShadowType.Planar && castShadow) { + AABB.transform(transWorldBounds, modelWorldBounds, shadows.matLight); + } + return !intersect.aabbFrustum(transWorldBounds, frustum); +} + +function sceneCulling ( + skyboxModelToSkip: Model | null, + scene: RenderScene, + camera: Camera, + camOrLightFrustum: Readonly, + castShadow: boolean, + models: Array, +): void { + const visibility = camera.visibility; + for (const model of scene.models) { + assert(!!model); + if (!model.enabled || model === skyboxModelToSkip || (castShadow && !model.castShadow)) { + continue; + } + if (scene && scene.isCulledByLod(camera, model)) { + continue; + } + + if (isNodeVisible(model.node, visibility) + || isModelVisible(model, visibility)) { + // frustum culling + if (isFrustumVisible(model, camOrLightFrustum, castShadow)) { + continue; + } + + models.push(model); + } + } +} + +function isBlend (pass: Pass): boolean { + let bBlend = false; + for (const target of pass.blendState.targets) { + if (target.blend) { + bBlend = true; + } + } + return bBlend; +} + +function computeSortingDepth (camera: Camera, model: Model): number { + let depth = 0; + if (model.node) { + const node = model.transform; + const tempVec3 = new Vec3(); + const position = Vec3.subtract(tempVec3, node.worldPosition, camera.position); + depth = position.dot(camera.forward); + } + return depth; +} + +function addRenderObject ( + phaseLayoutId: number, + isDrawOpaqueOrMask: boolean, + isDrawBlend: boolean, + camera: Camera, + model: Model, + queue: RenderQueue, +): void { + const subModels = model.subModels; + const subModelCount = subModels.length; + for (let subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { + const subModel = subModels[subModelIdx]; + const passes = subModel.passes; + const passCount = passes.length; + for (let passIdx = 0; passIdx < passCount; ++passIdx) { + const pass = passes[passIdx]; + // check phase + const phaseAllowed = phaseLayoutId === pass.phaseID; + if (!phaseAllowed) { + continue; + } + // check scene flags + const is_blend = isBlend(pass); + const isOpaqueOrMask = !is_blend; + if (!isDrawBlend && is_blend) { + // skip transparent object + continue; + } + if (!isDrawOpaqueOrMask && isOpaqueOrMask) { + // skip opaque object + continue; + } + + // add object to queue + if (pass.batchingScheme === BatchingSchemes.INSTANCING) { + const instancedBuffer = pass.getInstancedBuffer(); + instancedBuffer.merge(subModel, passIdx); + if (is_blend) { + queue.transparentInstancingQueue.add(instancedBuffer); + } else { + queue.opaqueInstancingQueue.add(instancedBuffer); + } + } else { + const depth = computeSortingDepth(camera, model); + if (is_blend) { + queue.transparentQueue.add(model, depth, subModelIdx, passIdx); + } else { + queue.opaqueQueue.add(model, depth, subModelIdx, passIdx); + } + } + } + } +} + +export class SceneCulling { + sceneQueries: Map = new Map(); + culledResults: Array> = new Array>(); + renderQueues: Array = new Array(); + sceneQueryIndex: Map = new Map(); + // source id + numCullingQueries = 0; + // target id + numRenderQueues = 0; + layoutGraph; + renderGraph; + clear (): void { + this.sceneQueries.clear(); + for (const c of this.culledResults) { + c.length = 0; + } + this.culledResults.length = 0; + for (const q of this.renderQueues) { + q.clear(); + } + this.renderQueues.length = 0; + this.sceneQueryIndex.clear(); + this.numCullingQueries = 0; + this.numRenderQueues = 0; + } + + buildRenderQueues (rg: RenderGraph, lg: LayoutGraphData, pplSceneData: PipelineSceneData): void { + this.layoutGraph = lg; + this.renderGraph = rg; + pSceneData = pplSceneData; + this.collectCullingQueries(rg, lg); + this.batchCulling(pplSceneData); + this.fillRenderQueues(rg, pplSceneData); + } + + private getOrCreateSceneCullingQuery (sceneData: SceneData): number { + const scene = sceneData.scene!; + let queries = this.sceneQueries.get(scene); + if (!queries) { + this.sceneQueries.set(scene, new CullingQueries()); + queries = this.sceneQueries.get(scene); + } + const castShadow = bool(sceneData.flags & SceneFlags.SHADOW_CASTER); + const key = computeCullingKey(sceneData.camera, sceneData.light.light, castShadow, sceneData.light.level); + const cullNum = queries!.culledResultIndex.get(key); + if (cullNum !== undefined) { + return cullNum; + } + const soureceID = this.numCullingQueries++; + if (this.numCullingQueries > this.culledResults.length) { + assert(this.numCullingQueries === (this.culledResults.length + 1)); + this.culledResults.push([]); + } + queries!.culledResultIndex.set(key, soureceID); + queries!.cullingKeyResult.set(key, new CullingKey(sceneData.camera, sceneData.light.light, castShadow, sceneData.light.level)); + return soureceID; + } + + private createRenderQueue (sceneFlags: SceneFlags, subpassOrPassLayoutID: number): number { + const targetID = this.numRenderQueues++; + if (this.numRenderQueues > this.renderQueues.length) { + assert(this.numRenderQueues === (this.renderQueues.length + 1)); + this.renderQueues.push(new RenderQueue()); + } + assert(targetID < this.renderQueues.length); + const rq = this.renderQueues[targetID]; + rq.sceneFlags = sceneFlags; + rq.subpassOrPassLayoutID = subpassOrPassLayoutID; + return targetID; + } + + private collectCullingQueries (rg: RenderGraph, lg: LayoutGraphData): void { + for (const v of rg.vertices()) { + if (!rg.holds(RenderGraphValue.Scene, v) || !rg.getValid(v)) { + continue; + } + const sceneData = rg.getScene(v); + if (!sceneData.scene) { + assert(!!sceneData.scene); + continue; + } + const sourceID = this.getOrCreateSceneCullingQuery(sceneData); + const layoutID = getSubpassOrPassID(v, rg, lg); + const targetID = this.createRenderQueue(sceneData.flags, layoutID); + + const lightType = sceneData.light.light ? sceneData.light.light.type : LightType.UNKNOWN; + // add render queue to query source + this.sceneQueryIndex.set(v, new RenderQueueDesc(sourceID, targetID, lightType)); + } + } + + uploadInstancing (cmdBuffer: CommandBuffer): void { + for (let queueID = 0; queueID !== this.numRenderQueues; ++queueID) { + assert(this.numRenderQueues <= this.renderQueues.length); + const queue = this.renderQueues[queueID]; + queue.opaqueInstancingQueue.uploadBuffers(cmdBuffer); + queue.transparentInstancingQueue.uploadBuffers(cmdBuffer); + } + } + + private batchCulling (pplSceneData: PipelineSceneData): void { + const skybox = pplSceneData.skybox; + const skyboxModelToSkip = skybox ? skybox.model : null; + for (const [scene, queries] of this.sceneQueries) { + assert(!!scene); + for (const [key, sourceID] of queries.culledResultIndex) { + const cullingKey = queries.cullingKeyResult.get(key)!; + assert(!!cullingKey.camera); + assert(cullingKey.camera.scene === scene); + const camera = cullingKey.camera; + const light = cullingKey.light; + const level = cullingKey.lightLevel; + const castShadow = cullingKey.castShadows; + assert(sourceID < this.culledResults.length); + const models = this.culledResults[sourceID]; + if (light) { + switch (light.type) { + case LightType.SPOT: + sceneCulling(skyboxModelToSkip, scene, camera, (light as SpotLight).frustum, castShadow, models); + break; + case LightType.DIRECTIONAL: { + const csmLayers = pplSceneData.csmLayers; + const mainLight: DirectionalLight = light as DirectionalLight; + const csmLevel = mainLight.csmLevel; + let frustum: Readonly; + const shadows = pplSceneData.shadows; + if (shadows.type === ShadowType.Planar) { + frustum = camera.frustum; + } else { + if (shadows.enabled && shadows.type === ShadowType.ShadowMap && mainLight && mainLight.node) { + // pplSceneData.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); + csmLayers.update(pplSceneData, camera); + } + + if (mainLight.shadowFixedArea || csmLevel === CSMLevel.LEVEL_1) { + frustum = csmLayers.specialLayer.validFrustum; + } else { + frustum = csmLayers.layers[level].validFrustum; + } + } + sceneCulling(skyboxModelToSkip, scene, camera, frustum, castShadow, models); + } + break; + default: + } + } else { + sceneCulling(skyboxModelToSkip, scene, camera, camera.frustum, castShadow, models); + } + } + } + } + + private fillRenderQueues (rg: RenderGraph, pplSceneData: PipelineSceneData): void { + const skybox = pplSceneData.skybox; + for (const [sceneId, desc] of this.sceneQueryIndex) { + assert(rg.holds(RenderGraphValue.Scene, sceneId)); + const sourceId = desc.culledSource; + const targetId = desc.renderQueueTarget; + const sceneData = rg.getScene(sceneId); + const isDrawBlend = bool(sceneData.flags & SceneFlags.TRANSPARENT_OBJECT); + const isDrawOpaqueOrMask = bool(sceneData.flags & (SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT)); + const isDrawShadowCaster = bool(sceneData.flags & SceneFlags.SHADOW_CASTER); + if (!isDrawShadowCaster && !isDrawBlend && !isDrawOpaqueOrMask) { + continue; + } + // render queue info + const renderQueueId = rg.getParent(sceneId); + assert(rg.holds(RenderGraphValue.Queue, renderQueueId)); + const graphRenderQueue = rg.getQueue(renderQueueId); + const phaseLayoutId = graphRenderQueue.phaseID; + assert(phaseLayoutId !== this.layoutGraph.nullVertex()); + + // culling source + assert(sourceId < this.culledResults.length); + const sourceModels = this.culledResults[sourceId]; + + // queue target + assert(targetId < this.renderQueues.length); + const renderQueue = this.renderQueues[targetId]; + assert(renderQueue.empty()); + + // skybox + const camera = sceneData.camera; + assert(!!camera); + if (!bool(sceneData.flags & SceneFlags.SHADOW_CASTER) + && skybox && skybox.enabled + && (camera.clearFlag & SKYBOX_FLAG)) { + assert(!!skybox.model); + const model = skybox.model; + const node = model.node; + let depth = 0; + if (node) { + const tempVec3 = new Vec3(); + Vec3.subtract(tempVec3, node.worldPosition, camera.position); + depth = tempVec3.dot(camera.forward); + } + renderQueue.opaqueQueue.add(model, depth, 0, 0); + } + + // fill render queue + for (const model of sourceModels) { + addRenderObject( + phaseLayoutId, + isDrawOpaqueOrMask, + isDrawBlend, + camera, + model, + renderQueue, + ); + } + // post-processing + renderQueue.sort(); + } + } +} diff --git a/cocos/rendering/custom/web-pipeline-types.ts b/cocos/rendering/custom/web-pipeline-types.ts new file mode 100644 index 00000000000..c41128cefd4 --- /dev/null +++ b/cocos/rendering/custom/web-pipeline-types.ts @@ -0,0 +1,234 @@ +import { CommandBuffer, DescriptorSet, Device, PipelineState, RenderPass, deviceManager } from '../../gfx'; +import { RenderScene } from '../../render-scene'; +import { Camera, Light, LightType, Model, SubModel } from '../../render-scene/scene'; +import { SetIndex } from '../define'; +import { InstancedBuffer } from '../instanced-buffer'; +import { PipelineStateManager } from '../pipeline-state-manager'; +import { SceneFlags } from './types'; + +export class DrawInstance { + subModel: SubModel | null; + priority: number; + hash: number; + depth: number; + shaderID: number; + passIndex: number; + + constructor ( + subModel: SubModel | null = null, + priority = 0, + hash = 0, + depth = 0, + shaderID = 0, + passIndex = 0, + ) { + this.subModel = subModel; + this.priority = priority; + this.hash = hash; + this.depth = depth; + this.shaderID = shaderID; + this.passIndex = passIndex; + } +} + +export class RenderDrawQueue { + instances: Array = new Array(); + + add (model: Model, depth: number, subModelIdx: number, passIdx: number): void { + const subModel = model.subModels[subModelIdx]; + const pass = subModel.passes[passIdx]; + const passPriority = pass.priority; + const modelPriority = subModel.priority; + const shaderId = subModel.shaders[passIdx].typedID; + const hash = (0 << 30) | (passPriority as number << 16) | (modelPriority as number << 8) | passIdx; + const priority = model.priority; + + this.instances.push(new DrawInstance(subModel, priority, hash, depth, shaderId, passIdx)); + } + /** + * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. + * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 + */ + sortOpaqueOrCutout (): void { + this.instances.sort((lhs: DrawInstance, rhs: DrawInstance) => { + if (lhs.hash !== rhs.hash) { + return lhs.hash - rhs.hash; + } + if (lhs.depth !== rhs.depth) { + return lhs.depth - rhs.depth; + } + return lhs.shaderID - rhs.shaderID; + }); + } + /** + * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. + * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 + */ + sortTransparent (): void { + this.instances.sort((lhs: DrawInstance, rhs: DrawInstance) => { + if (lhs.priority !== rhs.priority) { + return lhs.priority - rhs.priority; + } + if (lhs.hash !== rhs.hash) { + return lhs.hash - rhs.hash; + } + if (lhs.depth !== rhs.depth) { + return rhs.depth - lhs.depth; // 注意此处的差值顺序,为了按照降序排列 + } + return lhs.shaderID - rhs.shaderID; + }); + } + + recordCommandBuffer ( + device: Device, + renderPass: RenderPass, + cmdBuffer: CommandBuffer, + ): void { + for (const instance of this.instances) { + const subModel = instance.subModel!; + + const passIdx = instance.passIndex; + const inputAssembler = subModel.inputAssembler; + const pass = subModel.passes[passIdx]; + const shader = subModel.shaders[passIdx]; + const pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler); + + cmdBuffer.bindPipelineState(pso); + cmdBuffer.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); + cmdBuffer.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet); + cmdBuffer.bindInputAssembler(inputAssembler); + cmdBuffer.draw(inputAssembler); + } + } +} + +export class RenderInstancingQueue { + batches: Set = new Set(); + sortedBatches: Array = new Array(); + + add (instancedBuffer: InstancedBuffer): void { + this.batches.add(instancedBuffer); + } + + sort (): void { + this.sortedBatches = Array.from(this.batches); + } + + uploadBuffers (cmdBuffer: CommandBuffer): void { + for (const instanceBuffer of this.batches) { + if (instanceBuffer.hasPendingModels) { + instanceBuffer.uploadBuffers(cmdBuffer); + } + } + } + + recordCommandBuffer ( + renderPass: RenderPass, + cmdBuffer: CommandBuffer, + ds: DescriptorSet | null = null, + offset = 0, + dynamicOffsets: number[] | null = null, + ): void { + const renderQueue = this.sortedBatches; + for (const instanceBuffer of renderQueue) { + if (!instanceBuffer.hasPendingModels) { + continue; + } + const instances = instanceBuffer.instances; + const drawPass = instanceBuffer.pass; + cmdBuffer.bindDescriptorSet(SetIndex.MATERIAL, drawPass.descriptorSet); + let lastPSO: PipelineState | null = null; + for (const instance of instances) { + if (!instance.count) { + continue; + } + const pso = PipelineStateManager.getOrCreatePipelineState( + deviceManager.gfxDevice, + drawPass, + instance.shader!, + renderPass, + instance.ia, + ); + if (lastPSO !== pso) { + cmdBuffer.bindPipelineState(pso); + lastPSO = pso; + } + if (ds) { + cmdBuffer.bindDescriptorSet(SetIndex.GLOBAL, ds, [offset]); + } + if (dynamicOffsets) { + cmdBuffer.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, dynamicOffsets); + } else { + cmdBuffer.bindDescriptorSet( + SetIndex.LOCAL, + instance.descriptorSet, + instanceBuffer.dynamicOffsets, + ); + } + cmdBuffer.bindInputAssembler(instance.ia); + cmdBuffer.draw(instance.ia); + } + } + } +} + +export class RenderQueueDesc { + culledSource: number; + renderQueueTarget: number; + lightType: LightType; + + constructor ( + culledSourceIn = 0xFFFFFFFF, + renderQueueTargetIn = 0xFFFFFFFF, + lightTypeIn: LightType = LightType.UNKNOWN, + ) { + this.culledSource = culledSourceIn; + this.renderQueueTarget = renderQueueTargetIn; + this.lightType = lightTypeIn; + } +} + +export class RenderQueue { + opaqueQueue: RenderDrawQueue = new RenderDrawQueue(); + transparentQueue: RenderDrawQueue = new RenderDrawQueue(); + opaqueInstancingQueue: RenderInstancingQueue = new RenderInstancingQueue(); + transparentInstancingQueue: RenderInstancingQueue = new RenderInstancingQueue(); + sceneFlags: SceneFlags = SceneFlags.NONE; + subpassOrPassLayoutID = 0xffffffff; + + sort (): void { + this.opaqueQueue.sortOpaqueOrCutout(); + this.transparentQueue.sortTransparent(); + this.opaqueInstancingQueue.sort(); + this.transparentInstancingQueue.sort(); + } + + private _clearInstances (instances: Set): void { + const it = instances.values(); let res = it.next(); + while (!res.done) { + res.value.clear(); + res = it.next(); + } + instances.clear(); + } + + clear (): void { + this.opaqueQueue.instances.length = 0; + this.transparentQueue.instances.length = 0; + this._clearInstances(this.opaqueInstancingQueue.batches); + this.opaqueInstancingQueue.sortedBatches.length = 0; + this._clearInstances(this.transparentInstancingQueue.batches); + this.transparentInstancingQueue.sortedBatches.length = 0; + this.sceneFlags = SceneFlags.NONE; + this.subpassOrPassLayoutID = 0xFFFFFFFF; + } + + empty (): boolean { + return this.opaqueQueue.instances.length === 0 + && this.transparentQueue.instances.length === 0 + && this.opaqueInstancingQueue.batches.size === 0 + && this.opaqueInstancingQueue.sortedBatches.length === 0 + && this.transparentInstancingQueue.batches.size === 0 + && this.transparentInstancingQueue.sortedBatches.length === 0; + } +} diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index c1bac8ca455..08e171ab45c 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -304,7 +304,11 @@ function setShadowUBOLightView ( const pipeline = (director.root as Root).pipeline; const device = pipeline.device; const sceneData = pipeline.pipelineSceneData; + const shadowInfo = sceneData.shadows; + if (shadowInfo.type === ShadowType.Planar) { + return; + } const csmLayers = sceneData.csmLayers; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const cap = pipeline.device.capabilities; @@ -758,6 +762,7 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado const skybox = cfg.skybox; const director = cclegacy.director; const root = director.root; + const pipeline = root.pipeline as WebPipeline; if (skybox.reflectionMap) { const texture = skybox.reflectionMap.getGFXTexture()!; const sampler: Sampler = root.device.getSampler(skybox.reflectionMap.getSamplerInfo()); @@ -779,18 +784,17 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado setter.setTexture('cc_diffuseMap', texture); setter.setSampler('cc_diffuseMap', sampler); } - const pointSampler: Sampler = root.device.getSampler(_samplerPointInfo); if (!setter.hasSampler('cc_shadowMap')) { - setter.setSampler('cc_shadowMap', pointSampler); + setter.setSampler('cc_shadowMap', pipeline.defaultSampler); } if (!setter.hasTexture('cc_shadowMap')) { - setter.setTexture('cc_shadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + setter.setTexture('cc_shadowMap', pipeline.defaultTexture); } if (!setter.hasSampler('cc_spotShadowMap')) { - setter.setSampler('cc_spotShadowMap', pointSampler); + setter.setSampler('cc_spotShadowMap', pipeline.defaultSampler); } if (!setter.hasTexture('cc_spotShadowMap')) { - setter.setTexture('cc_spotShadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + setter.setTexture('cc_spotShadowMap', pipeline.defaultTexture); } } @@ -989,11 +993,12 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB throw new Error('Method not implemented.'); } addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = 'default'): RenderQueueBuilder { + const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); if (DEBUG) { - const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); } const queue = new RenderQueue(hint); + queue.phaseID = layoutId; const data = new RenderData(); const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); @@ -1129,11 +1134,12 @@ export class WebRenderPassBuilder extends WebSetter implements BasicMultisampleR return result; } addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = 'default'): WebRenderQueueBuilder { + const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); if (DEBUG) { - const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); } const queue = new RenderQueue(hint); + queue.phaseID = layoutId; const data = new RenderData(); const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); @@ -1283,11 +1289,12 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild throw new Error('Method not implemented.'); } addQueue (layoutName = 'default'): WebComputeQueueBuilder { + const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); if (DEBUG) { - const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); } const queue = new RenderQueue(); + queue.phaseID = layoutId; const data = new RenderData(); const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebComputeQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); @@ -1556,6 +1563,14 @@ export class WebPipeline implements BasicPipeline { return this._globalDescSetData; } + get defaultSampler (): Sampler { + return this._defaultSampler; + } + + get defaultTexture (): Texture { + return builtinResMgr.get('default-texture').getGFXTexture()!; + } + private _compileMaterial (): void { this._copyPassMat.initialize({ effectName: 'pipeline/copy-pass', @@ -1587,7 +1602,9 @@ export class WebPipeline implements BasicPipeline { // 0: SHADOWMAP_LINER_DEPTH_OFF, 1: SHADOWMAP_LINER_DEPTH_ON. const isLinear = this._device.gfxAPI === API.WEBGL ? 1 : 0; this.setMacroInt('CC_SHADOWMAP_USE_LINEAR_DEPTH', isLinear); - + const director: Director = cclegacy.director; + const root: Root = director.root!; + this._defaultSampler = root.device.getSampler(_samplerPointInfo); // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. this.pipelineSceneData.csmSupported = this.device.capabilities.maxFragmentUniformVectors >= (WebPipeline.CSM_UNIFORM_VECTORS + WebPipeline.GLOBAL_UNIFORM_VECTORS); @@ -1998,6 +2015,7 @@ export class WebPipeline implements BasicPipeline { private _copyPassMat: Material = new Material(); private _device!: Device; private _globalDSManager!: GlobalDSManager; + private _defaultSampler!: Sampler; private _globalDescriptorSet: DescriptorSet | null = null; private _globalDescriptorSetInfo: DescriptorSetInfo | null = null; private _globalDescriptorSetLayout: DescriptorSetLayout | null = null; diff --git a/cocos/rendering/post-process/passes/forward-pass.ts b/cocos/rendering/post-process/passes/forward-pass.ts index ef9f478d28e..e81630d80d2 100644 --- a/cocos/rendering/post-process/passes/forward-pass.ts +++ b/cocos/rendering/post-process/passes/forward-pass.ts @@ -11,7 +11,7 @@ import { ShadowPass } from './shadow-pass'; export class ForwardPass extends BasePass { name = 'ForwardPass'; - outputNames = ['ForwardColor', 'ForwardDS'] + outputNames = ['ForwardColor', 'ForwardDS']; enableInAllEditorCamera = true; depthBufferShadingScale = 1; @@ -70,11 +70,21 @@ export class ForwardPass extends BasePass { } } pass.addQueue(QueueHint.RENDER_OPAQUE) - .addSceneOfCamera(camera, + .addSceneOfCamera( + camera, new LightInfo(), - SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT - | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING | SceneFlags.GEOMETRY); - + SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT + | SceneFlags.DEFAULT_LIGHTING | SceneFlags.GEOMETRY, + ); + if (camera.scene?.mainLight) { + pass.addQueue(QueueHint.RENDER_TRANSPARENT, 'planar-shadow') + .addSceneOfCamera( + camera, + new LightInfo(camera.scene?.mainLight), + SceneFlags.TRANSPARENT_OBJECT | SceneFlags.SHADOW_CASTER + | SceneFlags.DEFAULT_LIGHTING | SceneFlags.GEOMETRY, + ); + } passContext.forwardPass = this; } } diff --git a/cocos/rendering/post-process/passes/skin-pass.ts b/cocos/rendering/post-process/passes/skin-pass.ts index bcbc60fdc82..24bdd068a8b 100644 --- a/cocos/rendering/post-process/passes/skin-pass.ts +++ b/cocos/rendering/post-process/passes/skin-pass.ts @@ -120,7 +120,7 @@ export class SSSSBlurData { const o = -range + i * step; const sign = o < 0.0 ? -1.0 : 1.0; // eslint-disable-next-line no-restricted-properties - this._kernel[i].w = range * sign * Math.abs(Math.pow(o, EXPONENT)) / Math.pow(range, EXPONENT); + this._kernel[i].w = range * sign * Math.abs(o ** EXPONENT) / range ** EXPONENT; } // Calculate the weights: @@ -185,9 +185,9 @@ export class SSSSBlurData { } export class SkinPass extends SettingPass { - name = 'SkinPass' + name = 'SkinPass'; effectName = 'pipeline/ssss-blur'; - outputNames = ['SSSSBlur', 'SSSSBlurDS'] + outputNames = ['SSSSBlur', 'SSSSBlurDS']; ssssBlurData = new SSSSBlurData(); private _activate = false; @@ -220,10 +220,12 @@ export class SkinPass extends SettingPass { this._buildSpecularPass(camera, ppl, inputRT!, inputDS); } - private _buildSSSSBlurPass (camera: Camera, + private _buildSSSSBlurPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): void { + inputDS: string, + ): void { const cameraID = getCameraUniqueID(camera); const pipelineSceneData = ppl.pipelineSceneData; @@ -259,8 +261,12 @@ export class SkinPass extends SettingPass { passIdx = SSSS_BLUR_X_PASS_INDEX; const ssssblurXPassLayoutName = 'ssss-blurX'; const ssssblurXPassPassName = `ssss-blurX${cameraID}`; - this.material.setProperty('blurInfo', new Vec4(camera.fov, skin.blurRadius, - boundingBox, skin.sssIntensity), passIdx); + this.material.setProperty('blurInfo', new Vec4( + camera.fov, + skin.blurRadius, + boundingBox, + skin.sssIntensity, + ), passIdx); this.material.setProperty('kernel', this.ssssBlurData.kernel, passIdx); passContext.updatePassViewPort() .addRenderPass(ssssblurXPassLayoutName, ssssblurXPassPassName) @@ -276,8 +282,12 @@ export class SkinPass extends SettingPass { passIdx = SSSS_BLUR_Y_PASS_INDEX; const ssssblurYPassLayoutName = 'ssss-blurY'; const ssssblurYPassPassName = `ssss-blurY${cameraID}`; - this.material.setProperty('blurInfo', new Vec4(camera.fov, skin.blurRadius, - boundingBox, skin.sssIntensity), passIdx); + this.material.setProperty('blurInfo', new Vec4( + camera.fov, + skin.blurRadius, + boundingBox, + skin.sssIntensity, + ), passIdx); this.material.setProperty('kernel', this.ssssBlurData.kernel, passIdx); passContext.updatePassViewPort() .addRenderPass(ssssblurYPassLayoutName, ssssblurYPassPassName) @@ -290,10 +300,12 @@ export class SkinPass extends SettingPass { .version(); } - private _buildSpecularPass (camera: Camera, + private _buildSpecularPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): void { + inputDS: string, + ): void { const cameraID = getCameraUniqueID(camera); const layoutName = 'specular-pass'; const passName = `specular-pass${cameraID}`; @@ -323,13 +335,19 @@ export class SkinPass extends SettingPass { } pass.addQueue(QueueHint.RENDER_OPAQUE, 'default') - .addSceneOfCamera(camera, new LightInfo(), - SceneFlags.TRANSPARENT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.PLANAR_SHADOW - | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING); + .addSceneOfCamera( + camera, + new LightInfo(), + SceneFlags.TRANSPARENT_OBJECT + | SceneFlags.CUTOUT_OBJECT, + ); pass.addQueue(QueueHint.RENDER_TRANSPARENT, 'forward-add') - .addSceneOfCamera(camera, new LightInfo(), - SceneFlags.TRANSPARENT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.PLANAR_SHADOW - | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING); + .addSceneOfCamera( + camera, + new LightInfo(), + SceneFlags.TRANSPARENT_OBJECT + | SceneFlags.CUTOUT_OBJECT, + ); } slotName (camera: Camera, index = 0): string { diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index ab5c7bd810f..a8a6e4b22d2 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -173,9 +173,8 @@ enum class Feature : uint32_t { MULTIPLE_RENDER_TARGETS, BLEND_MINMAX, COMPUTE_SHADER, - // @deprecated - INPUT_ATTACHMENT_BENEFIT, + INPUT_ATTACHMENT_BENEFIT, // @deprecated SUBPASS_COLOR_INPUT, SUBPASS_DEPTH_STENCIL_INPUT, RASTERIZATION_ORDER_NOCOHERENT, @@ -474,11 +473,12 @@ CC_ENUM_BITWISE_OPERATORS(TextureUsageBit); enum class TextureFlagBit : uint32_t { NONE = 0, - GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter - GENERAL_LAYOUT = 0x2, // @deprecated, For inout framebuffer attachments - EXTERNAL_OES = 0x4, // External oes texture - EXTERNAL_NORMAL = 0x8, // External normal texture - LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. + GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter + GENERAL_LAYOUT = 0x2, // @deprecated, For inout framebuffer attachments + EXTERNAL_OES = 0x4, // External oes texture + EXTERNAL_NORMAL = 0x8, // External normal texture + LAZILY_ALLOCATED = 0x10, // Try lazily allocated mode. + MUTABLE_VIEW_FORMAT = 0x40, // texture view as different format }; using TextureFlags = TextureFlagBit; CC_ENUM_BITWISE_OPERATORS(TextureFlagBit); @@ -1089,6 +1089,8 @@ struct ALIGNAS(8) TextureViewInfo { uint32_t levelCount{1}; uint32_t baseLayer{0}; uint32_t layerCount{1}; + uint32_t basePlane{0}; + uint32_t planeCount{1}; #if CC_CPU_ARCH == CC_CPU_ARCH_32 uint32_t _padding{0}; #endif diff --git a/native/cocos/renderer/gfx-base/GFXTexture.cpp b/native/cocos/renderer/gfx-base/GFXTexture.cpp index 0f1a7c2c14d..59432996a07 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.cpp +++ b/native/cocos/renderer/gfx-base/GFXTexture.cpp @@ -144,6 +144,8 @@ void Texture::updateTextureInfo(const SwapchainTextureInfo &info, Texture *out) out->_viewInfo.layerCount = out->_info.layerCount; out->_viewInfo.baseLevel = 0; out->_viewInfo.levelCount = out->_info.levelCount; + out->_viewInfo.basePlane = 0; + out->_viewInfo.planeCount = info.format == gfx::Format::DEPTH_STENCIL ? 2 : 1; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXTexture.h b/native/cocos/renderer/gfx-base/GFXTexture.h index b00defb4fc4..0d29fcfc27d 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.h +++ b/native/cocos/renderer/gfx-base/GFXTexture.h @@ -51,7 +51,7 @@ class CC_DLL Texture : public GFXObject, public RefCounted { inline ccstd::hash_t getHash() const { return _hash; } // convenient getter for common usages - inline Format getFormat() const { return _info.format; } + inline Format getFormat() const { return _isTextureView ? _viewInfo.format : _info.format; } inline uint32_t getWidth() const { return _info.width; } inline uint32_t getHeight() const { return _info.height; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index afddfc2d1a7..231ed1d3b5e 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -1375,16 +1375,21 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * auto &attachments = gpuRenderPass->colorAttachments; auto &drawBuffers = gpuRenderPass->drawBuffers; + bool hasDS = (gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN); gpuRenderPass->drawBuffers.resize(subPasses.size()); - gpuRenderPass->indices.resize(attachments.size(), INVALID_BINDING); + gpuRenderPass->indices.resize(attachments.size() + hasDS, INVALID_BINDING); for (uint32_t i = 0; i < subPasses.size(); ++i) { auto &sub = subPasses[i]; auto &drawBuffer = drawBuffers[i]; - std::vector visited(gpuRenderPass->colorAttachments.size()); + std::vector visited(gpuRenderPass->colorAttachments.size() + hasDS); for (auto &input : sub.inputs) { visited[input] = true; + if(input == gpuRenderPass->colorAttachments.size()) { + // ds input + continue; + } drawBuffer.emplace_back(gpuRenderPass->indices[input]); } @@ -1411,8 +1416,14 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * } } - gpuRenderPass->depthStencil = sub.depthStencil; - gpuRenderPass->depthStencilResolve = sub.depthStencilResolve; + + if (sub.depthStencil != gfx::INVALID_BINDING) { + gpuRenderPass->depthStencil = sub.depthStencil; + gpuRenderPass->indices.back() = gpuRenderPass->depthStencil; + } + if (sub.depthStencilResolve != gfx::INVALID_BINDING) { + gpuRenderPass->depthStencilResolve = sub.depthStencilResolve; + } } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 169767fe082..0005cf0c6b8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -156,6 +156,8 @@ struct GLES3GPUTextureView { Format format = Format::UNKNOWN; uint32_t baseLevel = 0U; uint32_t levelCount = 1U; + uint32_t basePlane = 0U; + uint32_t planeCount = 0U; }; using GLES3GPUTextureViewList = ccstd::vector; diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp index 067c5037471..cd97b6fdf4e 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp @@ -61,14 +61,20 @@ void updateGPUShaderSourceByRenderPass(GLES3GPUShader *gpuShader, GLES3GPURender } CC_ASSERT(subpassIndex < renderPass->subpasses.size()); - if (renderPass->subpasses[subpassIndex].inputs.empty()) { + if (renderPass->subpasses.size() <= 1) { return; } - auto &drawBuffers = renderPass->drawBuffers.at(subpassIndex); + bool dsInput{false}; + if (renderPass->depthStencil != INVALID_BINDING && !renderPass->subpasses[subpassIndex].inputs.empty()) { + const auto &inputs = renderPass->subpasses[subpassIndex].inputs; + // depth stencil input should always lies at the end of index list. + dsInput = inputs.back() == renderPass->depthStencil; + } + auto &drawBuffers = renderPass->drawBuffers.at(subpassIndex); ccstd::string::size_type offset = 0; for (uint32_t i = 0; i < drawBuffers.size(); ++i) { - const char* layoutPrefix = "layout(location = "; + const char *layoutPrefix = "layout(location = "; std::stringstream ss1; ss1 << layoutPrefix << i << ") out"; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index 286ef62b78f..2026ec3d019 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -95,6 +95,8 @@ void GLES3Texture::createTextureView() { _gpuTextureView->format = _viewInfo.format; _gpuTextureView->baseLevel = _viewInfo.baseLevel; _gpuTextureView->levelCount = _viewInfo.levelCount; + _gpuTextureView->basePlane = _viewInfo.basePlane; + _gpuTextureView->planeCount = _viewInfo.planeCount; } void GLES3Texture::doDestroy() { diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 84cd6f958e0..eef51f0eef7 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -219,7 +219,9 @@ of this software and associated engine source code (the "Software"), a limited, for (size_t i = 0; i < subpasses.size(); ++i) { for (size_t j = 0; j < subpasses[i].inputs.size(); ++j) { uint32_t input = subpasses[i].inputs[j]; - if(input >= colorAttachments.size()) { + if(input >= colorAttachments.size() || + colorAttachments[input].format == Format::DEPTH_STENCIL || + colorAttachments[input].format == Format::DEPTH) { continue; // depthStencil as input } if (visited[input]) @@ -237,7 +239,7 @@ of this software and associated engine source code (the "Software"), a limited, if(color >= colorAttachments.size()) { continue; // depthStencil as output } - if (subpasses[i].resolves.size() > j) { + if (!subpasses[i].resolves.empty() && subpasses[i].resolves[j] != INVALID_BINDING) { uint32_t resolve = subpasses[i].resolves[j]; auto *resolveTex = static_cast(colorTextures[resolve]); mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); @@ -245,6 +247,8 @@ of this software and associated engine source code (the "Software"), a limited, mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; + } else { + mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; } if (visited[color]) continue; @@ -261,7 +265,6 @@ of this software and associated engine source code (the "Software"), a limited, } else { mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); } - mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; visited[color] = true; _colorAppearedBefore.set(color); } @@ -386,7 +389,7 @@ of this software and associated engine source code (the "Software"), a limited, } if (subpass.depthStencilResolve != INVALID_BINDING) { - descriptor.depthAttachment.resolveTexture = static_cast(curFBO->getDepthStencilTexture())->getMTLTexture(); + descriptor.depthAttachment.resolveTexture = static_cast(curFBO->getDepthStencilResolveTexture())->getMTLTexture(); descriptor.depthAttachment.resolveLevel = 0; descriptor.depthAttachment.resolveSlice = 0; descriptor.depthAttachment.resolveDepthPlane = 0; diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 186a152bcda..097d14dd0b1 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -135,7 +135,7 @@ of this software and associated engine source code (the "Software"), a limited, _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; _features[toNumber(Feature::COMPUTE_SHADER)] = true; _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; - _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = false; + _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = true; _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = false; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 447ca460e19..5eb009affe0 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -304,10 +304,11 @@ of this software and associated engine source code (the "Software"), a limited, depthStencilTexIndex = subpass.depthStencil; for (size_t i = 0; i < subpass.inputs.size(); ++i) { uint32_t input = subpass.inputs[i]; + if (inputs.find(input) == inputs.end()) { inputs.insert(input); - if(input >= colorAttachments.size()) { - depthStencilTexIndex = input; + if(_renderPass->getColorAttachments()[input].format == Format::DEPTH || + _renderPass->getColorAttachments()[input].format == Format::DEPTH_STENCIL) { continue; } mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[input].format); diff --git a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm index 06c177998ea..51b98ea9f3e 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm +++ b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm @@ -93,7 +93,13 @@ of this software and associated engine source code (the "Software"), a limited, auto &drawBuffer = _drawBuffers[i]; for (auto &input : subPass.inputs) { - auto &index = _colorIndices[input]; + auto index = INVALID_BINDING; + if(input < _colorAttachments.size()) { + index = _colorIndices[input]; + } else { + // ds input + index = input; + } CC_ASSERT(index != INVALID_BINDING); // input should not appear before color or depthstencil. readBuffer.emplace_back(index); } diff --git a/native/cocos/renderer/gfx-metal/MTLShader.mm b/native/cocos/renderer/gfx-metal/MTLShader.mm index 3a81909b736..24b7e35b6a4 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -73,9 +73,9 @@ of this software and associated engine source code (the "Software"), a limited, _specializedFragFuncs = [[NSMutableDictionary alloc] init]; // spirv-cross for input attachment needs RenderPass to build [[color(index)]], // build gpu shader only when there is no subPass input. - if (!checkInputAttachment(info)) { - gpuShader(nullptr, 0); - } +// if (!checkInputAttachment(info)) { +// gpuShader(nullptr, 0); +// } } void CCMTLShader::doDestroy() { @@ -169,7 +169,7 @@ of this software and associated engine source code (the "Software"), a limited, const auto &drawBuffer = renderPass != nullptr ? renderPass->getDrawBuffer(subPass) : emptyBuffer; const auto &readBuffer = renderPass != nullptr ? renderPass->getReadBuffer(subPass) : emptyBuffer; ccstd::string mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize() / unitSize, stage.stage, - _gpuShader, drawBuffer, readBuffer); + _gpuShader, renderPass, subPass); NSString* shader = [NSString stringWithUTF8String:mtlShaderSrc.c_str()]; NSError* error = nil; diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.mm b/native/cocos/renderer/gfx-metal/MTLTexture.mm index 96d7b9a1bc1..2359cd99697 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.mm +++ b/native/cocos/renderer/gfx-metal/MTLTexture.mm @@ -162,8 +162,14 @@ of this software and associated engine source code (the "Software"), a limited, } _convertedFormat = mu::convertGFXPixelFormat(_viewInfo.format); auto mtlTextureType = mu::toMTLTextureType(_viewInfo.type); + + MTLPixelFormat format = mu::toMTLPixelFormat(_convertedFormat); + if(_viewInfo.format == Format::DEPTH_STENCIL) { + format = _viewInfo.basePlane == 0 ? mu::toMTLPixelFormat(_viewInfo.texture->getFormat()) : MTLPixelFormatX32_Stencil8; + } + _mtlTextureView = [static_cast(_viewInfo.texture)->_mtlTexture - newTextureViewWithPixelFormat:mu::toMTLPixelFormat(_convertedFormat) + newTextureViewWithPixelFormat:format textureType:mtlTextureType levels:NSMakeRange(_viewInfo.baseLevel, _viewInfo.levelCount) slices:NSMakeRange(_viewInfo.baseLayer, _viewInfo.layerCount)]; @@ -220,6 +226,9 @@ of this software and associated engine source code (the "Software"), a limited, return false; descriptor.usage = mu::toMTLTextureUsage(_info.usage); + if(hasFlag(_info.flags, TextureFlags::MUTABLE_VIEW_FORMAT)) { + descriptor.usage |= MTLTextureUsagePixelFormatView; + } descriptor.sampleCount = mu::toMTLSampleCount(_info.samples); descriptor.textureType = descriptor.sampleCount > 1 ? MTLTextureType2DMultisample : mu::toMTLTextureType(_info.type); descriptor.mipmapLevelCount = _info.levelCount; diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index f055f6de261..18f597b3f3b 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -71,8 +71,7 @@ MTLSamplerAddressMode toMTLSamplerAddressMode(Address); int toMTLSamplerBorderColor(const Color &); MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(Filter); MTLSamplerMipFilter toMTLSamplerMipFilter(Filter); -ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, - const ccstd::vector &drawBuffer, const ccstd::vector &readBuffer); +ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, RenderPass* renderpass, uint32_t subpassIndex); const uint8_t *convertRGB8ToRGBA8(const uint8_t *source, uint32_t length); const uint8_t *convertRGB32FToRGBA32F(const uint8_t *source, uint32_t length); NSUInteger highestSupportedFeatureSet(id device); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index d2864e9b917..cf4f3fc7a8c 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -35,6 +35,7 @@ of this software and associated engine source code (the "Software"), a limited, #include "spirv_cross/spirv_msl.hpp" #include "TargetConditionals.h" #include "base/Log.h" +#include namespace cc { namespace gfx { @@ -918,8 +919,8 @@ void main() { ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, - const ccstd::vector &drawBuffer, - const ccstd::vector &readBuffer) { + RenderPass* renderPass, + uint32_t subpassIndex) { CCMTLDevice *device = CCMTLDevice::getInstance(); spirv_cross::CompilerMSL msl(ir, word_count); @@ -1057,18 +1058,24 @@ void main() { } if (executionModel == spv::ExecutionModelFragment) { + auto* ccRenderPass = static_cast(renderPass); + const auto& readBuffer = ccRenderPass ? ccRenderPass->getReadBuffer(subpassIndex) : ccstd::vector{}; if (!resources.subpass_inputs.empty()) { - gpuShader->inputs.resize(resources.subpass_inputs.size()); +// gpuShader->inputs.resize(resources.subpass_inputs.size()); for (size_t i = 0; i < resources.subpass_inputs.size(); i++) { const auto &attachment = resources.subpass_inputs[i]; - gpuShader->inputs[i].name = attachment.name; - auto id = msl.get_decoration(attachment.id, spv::DecorationInputAttachmentIndex); - auto loc = id >= readBuffer.size() ? id : readBuffer[id]; + auto inputIndex = msl.get_decoration(attachment.id, spv::DecorationInputAttachmentIndex); + auto loc = inputIndex >= readBuffer.size() ? inputIndex : readBuffer[inputIndex]; + // depth stencil input not support in metal + CC_ASSERT(loc != renderPass->getColorAttachments().size()); + auto& input = gpuShader->inputs.emplace_back(); + input.name = attachment.name; msl.set_decoration(attachment.id, spv::DecorationInputAttachmentIndex, loc); } } gpuShader->outputs.resize(resources.stage_outputs.size()); + const auto& drawBuffer = renderPass ? ccRenderPass->getDrawBuffer(subpassIndex) : ccstd::vector{}; for (size_t i = 0; i < resources.stage_outputs.size(); i++) { const auto &stageOutput = resources.stage_outputs[i]; auto set = msl.get_decoration(stageOutput.id, spv::DecorationDescriptorSet); @@ -1096,6 +1103,7 @@ void main() { CC_LOG_ERROR("Compile to MSL failed."); CC_LOG_ERROR("%s", output.c_str()); } + return output; } diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index cf098298382..0468624dd53 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -196,15 +196,31 @@ void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTex if (!gpuTextureView->gpuTexture) return; auto createFn = [device, gpuTextureView](VkImage vkImage, VkImageView *pVkImageView) { + auto format = gpuTextureView->format; + auto mapAspect = [](CCVKGPUTextureView *gpuTextureView) { + auto aspectMask = gpuTextureView->gpuTexture->aspectMask; + if (gpuTextureView->gpuTexture->format == Format::DEPTH_STENCIL) { + uint32_t planeIndex = gpuTextureView->basePlane; + uint32_t planeCount = gpuTextureView->planeCount; + aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT << planeIndex; + CC_ASSERT(planeIndex + planeCount <= 2); + CC_ASSERT(planeCount > 0); + while (planeCount && --planeCount) { + aspectMask |= (aspectMask << 1); + } + } + return aspectMask; + }; + VkImageViewCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; createInfo.image = vkImage; createInfo.viewType = mapVkImageViewType(gpuTextureView->type); - createInfo.format = mapVkFormat(gpuTextureView->format, device->gpuDevice()); - createInfo.subresourceRange.aspectMask = gpuTextureView->gpuTexture->aspectMask; + createInfo.subresourceRange.aspectMask = mapAspect(gpuTextureView); createInfo.subresourceRange.baseMipLevel = gpuTextureView->baseLevel; createInfo.subresourceRange.levelCount = gpuTextureView->levelCount; createInfo.subresourceRange.baseArrayLayer = gpuTextureView->baseLayer; createInfo.subresourceRange.layerCount = gpuTextureView->layerCount; + createInfo.format = mapVkFormat(format, device->gpuDevice()); VK_CHECK(vkCreateImageView(device->gpuDevice()->vkDevice, &createInfo, nullptr, pVkImageView)); }; @@ -444,13 +460,13 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende for (uint32_t input : subpassInfo.inputs) { bool appearsInOutput = std::find(subpassInfo.colors.begin(), subpassInfo.colors.end(), input) != subpassInfo.colors.end(); + VkImageLayout layout = appearsInOutput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkImageAspectFlags aspectFlag = VK_IMAGE_ASPECT_COLOR_BIT; if (input == gpuRenderPass->colorAttachments.size()) { - VkImageLayout layout = subpassInfo.depthStencil != INVALID_BINDING ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; - attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_DEPTH_BIT}); - } else { - VkImageLayout layout = appearsInOutput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_COLOR_BIT}); + layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; + aspectFlag = VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT; } + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, aspectFlag}); } for (uint32_t color : subpassInfo.colors) { const VkAttachmentDescription2 &attachment = attachmentDescriptions[color]; @@ -518,7 +534,6 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende offset += subpassInfo.resolves.size(); } } - if (!subpassInfo.preserves.empty()) { desc.preserveAttachmentCount = utils::toUint(subpassInfo.preserves.size()); desc.pPreserveAttachments = subpassInfo.preserves.data(); diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index cb386223c67..edb7dfc6f42 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -188,6 +188,8 @@ struct CCVKGPUTextureView : public CCVKGPUDeviceObject { uint32_t levelCount = 1U; uint32_t baseLayer = 0U; uint32_t layerCount = 1U; + uint32_t basePlane = 0U; + uint32_t planeCount = 1U; ccstd::vector swapchainVkImageViews; diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp index 5f0a3e85b47..c9b74b170ba 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp @@ -43,6 +43,7 @@ CCVKTexture::~CCVKTexture() { void CCVKTexture::doInit(const TextureInfo & /*info*/) { createTexture(_info.width, _info.height, _size); + _viewInfo.planeCount = _info.format == Format::DEPTH_STENCIL ? 2 : 1; createTextureView(); } @@ -71,6 +72,7 @@ void CCVKTexture::createTexture(uint32_t width, uint32_t height, uint32_t size, _gpuTexture->mipLevels = _info.levelCount; _gpuTexture->samples = _info.samples; _gpuTexture->flags = _info.flags; + bool hasExternalFlag = hasFlag(_gpuTexture->flags, TextureFlagBit::EXTERNAL_NORMAL); if (hasExternalFlag) { _gpuTexture->externalVKImage = reinterpret_cast(_info.externalRes); @@ -90,6 +92,8 @@ void CCVKTexture::createTextureView(bool initGPUTextureView) { _gpuTextureView->levelCount = _viewInfo.levelCount; _gpuTextureView->baseLayer = _viewInfo.baseLayer; _gpuTextureView->layerCount = _viewInfo.layerCount; + _gpuTextureView->basePlane = _viewInfo.basePlane; + _gpuTextureView->planeCount = _viewInfo.planeCount; if (initGPUTextureView) { _gpuTextureView->init(); diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h b/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h index 4050a7fbb5d..c12b37f57bc 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h @@ -1,824 +1,962 @@ -/**************************************************************************** - Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -/** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ -// clang-format off -#pragma once -#include -#include -#include "cocos/renderer/pipeline/custom/FGDispatcherTypes.h" -#include "cocos/renderer/pipeline/custom/details/GraphImpl.h" -#include "cocos/renderer/pipeline/custom/details/Overload.h" -#include "cocos/renderer/pipeline/custom/details/PathUtils.h" - -namespace cc { - -namespace render { - -// IncidenceGraph -inline ResourceAccessGraph::vertex_descriptor -source(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { - return e.source; -} - -inline ResourceAccessGraph::vertex_descriptor -target(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { - return e.target; -} - -inline std::pair -out_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return std::make_pair( - ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), - ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); -} - -inline ResourceAccessGraph::degree_size_type -out_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getOutEdgeList(u).size()); -} - -inline std::pair -edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, const ResourceAccessGraph& g) noexcept { - const auto& outEdgeList = g.getOutEdgeList(u); - auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), ResourceAccessGraph::OutEdge(v)); - bool hasEdge = (iter != outEdgeList.end()); - return {ResourceAccessGraph::edge_descriptor(u, v), hasEdge}; -} - -// BidirectionalGraph(Directed) -inline std::pair -in_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return std::make_pair( - ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), - ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); -} - -inline ResourceAccessGraph::degree_size_type -in_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getInEdgeList(u).size()); -} - -inline ResourceAccessGraph::degree_size_type -degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { - return in_degree(u, g) + out_degree(u, g); -} - -// AdjacencyGraph -inline std::pair -adjacent_vertices(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - auto edges = out_edges(u, g); - return std::make_pair(ResourceAccessGraph::adjacency_iterator(edges.first, &g), ResourceAccessGraph::adjacency_iterator(edges.second, &g)); -} - -// VertexListGraph -inline std::pair -vertices(const ResourceAccessGraph& g) noexcept { - return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); -} - -inline ResourceAccessGraph::vertices_size_type -num_vertices(const ResourceAccessGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getVertexList().size()); -} - -// EdgeListGraph -inline std::pair -edges(const ResourceAccessGraph& g0) noexcept { - auto& g = const_cast(g0); - return std::make_pair( - ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), - ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); -} - -inline ResourceAccessGraph::edges_size_type -num_edges(const ResourceAccessGraph& g) noexcept { // NOLINT - ResourceAccessGraph::edges_size_type numEdges = 0; - - auto range = vertices(g); - for (auto iter = range.first; iter != range.second; ++iter) { - numEdges += out_degree(*iter, g); - } - return numEdges; -} - -// MutableGraph(Edge) -inline std::pair -add_edge( // NOLINT - ResourceAccessGraph::vertex_descriptor u, - ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) { - auto& outEdgeList = g.getOutEdgeList(u); - outEdgeList.emplace_back(v); - - auto& inEdgeList = g.getInEdgeList(v); - inEdgeList.emplace_back(u); - - return std::make_pair(ResourceAccessGraph::edge_descriptor(u, v), true); -} - -inline void remove_edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) noexcept { // NOLINT - auto& s = g._vertices[u]; - auto& t = g._vertices[v]; - s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), ResourceAccessGraph::OutEdge(v)), s.outEdges.end()); - t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), ResourceAccessGraph::InEdge(u)), t.inEdges.end()); -} - -inline void remove_edge(ResourceAccessGraph::out_edge_iterator outIter, ResourceAccessGraph& g) noexcept { // NOLINT - auto e = *outIter; - const auto u = source(e, g); - const auto v = target(e, g); - auto& s = g._vertices[u]; - auto& t = g._vertices[v]; - auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), ResourceAccessGraph::InEdge(u)); - CC_EXPECTS(inIter != t.inEdges.end()); - t.inEdges.erase(inIter); - s.outEdges.erase(outIter.base()); -} - -inline void remove_edge(ResourceAccessGraph::edge_descriptor e, ResourceAccessGraph& g) noexcept { // NOLINT - const auto u = source(e, g); - const auto v = target(e, g); - auto& s = g._vertices[u]; - auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), ResourceAccessGraph::OutEdge(v)); - CC_EXPECTS(outIter != s.outEdges.end()); - remove_edge(ResourceAccessGraph::out_edge_iterator(outIter, u), g); -} - -// MutableGraph(Vertex) -inline void clear_out_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - // Bidirectional (OutEdges) - auto& outEdgeList = g.getOutEdgeList(u); - auto outEnd = outEdgeList.end(); - for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { - auto& inEdgeList = g.getInEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - outEdgeList.clear(); -} - -inline void clear_in_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - // Bidirectional (InEdges) - auto& inEdgeList = g.getInEdgeList(u); - auto inEnd = inEdgeList.end(); - for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { - auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - inEdgeList.clear(); -} - -inline void clear_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - clear_out_edges(u, g); - clear_in_edges(u, g); -} - -inline void remove_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - { // UuidGraph - const auto& key = g.passID[u]; - auto num = g.passIndex.erase(key); - CC_ENSURES(num == 1); - for (auto&& pair : g.passIndex) { - auto& v = pair.second; - if (v > u) { - --v; - } - } - } - impl::removeVectorVertex(const_cast(g), u, ResourceAccessGraph::directed_category{}); - - // remove components - g.passID.erase(g.passID.begin() + static_cast(u)); - g.access.erase(g.access.begin() + static_cast(u)); -} - -// MutablePropertyGraph(Vertex) -template -inline ResourceAccessGraph::vertex_descriptor -addVertex(Component0&& c0, Component1&& c1, ResourceAccessGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - { // UuidGraph - const auto& uuid = c0; - auto res = g.passIndex.emplace(uuid, v); - CC_ENSURES(res.second); - } - g.passID.emplace_back(std::forward(c0)); - g.access.emplace_back(std::forward(c1)); - - return v; -} - -template -inline ResourceAccessGraph::vertex_descriptor -addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, Component1&& c1, ResourceAccessGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - { // UuidGraph - std::apply( - [&](const auto&... args) { - auto res = g.passIndex.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); - CC_ENSURES(res.second); - }, - c0); - } - - std::apply( - [&](auto&&... args) { - g.passID.emplace_back(std::forward(args)...); - }, - std::forward(c0)); - - std::apply( - [&](auto&&... args) { - g.access.emplace_back(std::forward(args)...); - }, - std::forward(c1)); - - return v; -} - -// IncidenceGraph -inline RelationGraph::vertex_descriptor -source(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { - return e.source; -} - -inline RelationGraph::vertex_descriptor -target(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { - return e.target; -} - -inline std::pair -out_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - return std::make_pair( - RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), - RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); -} - -inline RelationGraph::degree_size_type -out_degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getOutEdgeList(u).size()); -} - -inline std::pair -edge(RelationGraph::vertex_descriptor u, RelationGraph::vertex_descriptor v, const RelationGraph& g) noexcept { - const auto& outEdgeList = g.getOutEdgeList(u); - auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), RelationGraph::OutEdge(v)); - bool hasEdge = (iter != outEdgeList.end()); - return {RelationGraph::edge_descriptor(u, v), hasEdge}; -} - -// BidirectionalGraph(Directed) -inline std::pair -in_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - return std::make_pair( - RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), - RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); -} - -inline RelationGraph::degree_size_type -in_degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getInEdgeList(u).size()); -} - -inline RelationGraph::degree_size_type -degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { - return in_degree(u, g) + out_degree(u, g); -} - -// AdjacencyGraph -inline std::pair -adjacent_vertices(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - auto edges = out_edges(u, g); - return std::make_pair(RelationGraph::adjacency_iterator(edges.first, &g), RelationGraph::adjacency_iterator(edges.second, &g)); -} - -// VertexListGraph -inline std::pair -vertices(const RelationGraph& g) noexcept { - return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); -} - -inline RelationGraph::vertices_size_type -num_vertices(const RelationGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getVertexList().size()); -} - -// EdgeListGraph -inline std::pair -edges(const RelationGraph& g0) noexcept { - auto& g = const_cast(g0); - return std::make_pair( - RelationGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), - RelationGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); -} - -inline RelationGraph::edges_size_type -num_edges(const RelationGraph& g) noexcept { // NOLINT - RelationGraph::edges_size_type numEdges = 0; - - auto range = vertices(g); - for (auto iter = range.first; iter != range.second; ++iter) { - numEdges += out_degree(*iter, g); - } - return numEdges; -} - -// MutableGraph(Edge) -inline std::pair -add_edge( // NOLINT - RelationGraph::vertex_descriptor u, - RelationGraph::vertex_descriptor v, RelationGraph& g) { - auto& outEdgeList = g.getOutEdgeList(u); - outEdgeList.emplace_back(v); - - auto& inEdgeList = g.getInEdgeList(v); - inEdgeList.emplace_back(u); - - return std::make_pair(RelationGraph::edge_descriptor(u, v), true); -} - -inline void remove_edge(RelationGraph::vertex_descriptor u, RelationGraph::vertex_descriptor v, RelationGraph& g) noexcept { // NOLINT - auto& s = g._vertices[u]; - auto& t = g._vertices[v]; - s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), RelationGraph::OutEdge(v)), s.outEdges.end()); - t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), RelationGraph::InEdge(u)), t.inEdges.end()); -} - -inline void remove_edge(RelationGraph::out_edge_iterator outIter, RelationGraph& g) noexcept { // NOLINT - auto e = *outIter; - const auto u = source(e, g); - const auto v = target(e, g); - auto& s = g._vertices[u]; - auto& t = g._vertices[v]; - auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), RelationGraph::InEdge(u)); - CC_EXPECTS(inIter != t.inEdges.end()); - t.inEdges.erase(inIter); - s.outEdges.erase(outIter.base()); -} - -inline void remove_edge(RelationGraph::edge_descriptor e, RelationGraph& g) noexcept { // NOLINT - const auto u = source(e, g); - const auto v = target(e, g); - auto& s = g._vertices[u]; - auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), RelationGraph::OutEdge(v)); - CC_EXPECTS(outIter != s.outEdges.end()); - remove_edge(RelationGraph::out_edge_iterator(outIter, u), g); -} - -// MutableGraph(Vertex) -inline void clear_out_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT - // Bidirectional (OutEdges) - auto& outEdgeList = g.getOutEdgeList(u); - auto outEnd = outEdgeList.end(); - for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { - auto& inEdgeList = g.getInEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - outEdgeList.clear(); -} - -inline void clear_in_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT - // Bidirectional (InEdges) - auto& inEdgeList = g.getInEdgeList(u); - auto inEnd = inEdgeList.end(); - for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { - auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - inEdgeList.clear(); -} - -inline void clear_vertex(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT - clear_out_edges(u, g); - clear_in_edges(u, g); -} - -inline void remove_vertex(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT - { // UuidGraph - const auto& key = g.descID[u]; - auto num = g.vertexMap.erase(key); - CC_ENSURES(num == 1); - for (auto&& pair : g.vertexMap) { - auto& v = pair.second; - if (v > u) { - --v; - } - } - } - impl::removeVectorVertex(const_cast(g), u, RelationGraph::directed_category{}); - - // remove components - g.descID.erase(g.descID.begin() + static_cast(u)); -} - -// MutablePropertyGraph(Vertex) -template -inline RelationGraph::vertex_descriptor -addVertex(Component0&& c0, RelationGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - { // UuidGraph - const auto& uuid = c0; - auto res = g.vertexMap.emplace(uuid, v); - CC_ENSURES(res.second); - } - g.descID.emplace_back(std::forward(c0)); - - return v; -} - -template -inline RelationGraph::vertex_descriptor -addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, RelationGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - { // UuidGraph - std::apply( - [&](const auto&... args) { - auto res = g.vertexMap.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); - CC_ENSURES(res.second); - }, - c0); - } - - std::apply( - [&](auto&&... args) { - g.descID.emplace_back(std::forward(args)...); - }, - std::forward(c0)); - - return v; -} - -} // namespace render - -} // namespace cc - -namespace boost { - -// Vertex Index -template <> -struct property_map { - using const_type = identity_property_map; - using type = identity_property_map; -}; - -// Vertex Component -template <> -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - const cc::render::ResourceAccessGraph, - const ccstd::pmr::vector, - cc::render::RenderGraph::vertex_descriptor, - const cc::render::RenderGraph::vertex_descriptor&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - cc::render::ResourceAccessGraph, - ccstd::pmr::vector, - cc::render::RenderGraph::vertex_descriptor, - cc::render::RenderGraph::vertex_descriptor&>; -}; - -// Vertex Component -template <> -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - const cc::render::ResourceAccessGraph, - const ccstd::pmr::vector, - cc::render::ResourceAccessNode, - const cc::render::ResourceAccessNode&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - cc::render::ResourceAccessGraph, - ccstd::pmr::vector, - cc::render::ResourceAccessNode, - cc::render::ResourceAccessNode&>; -}; - -// Vertex ComponentMember -template -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< - lvalue_property_map_tag, - const cc::render::ResourceAccessGraph, - const ccstd::pmr::vector, - T, - const T&, - T cc::render::ResourceAccessNode::*>; - using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< - lvalue_property_map_tag, - cc::render::ResourceAccessGraph, - ccstd::pmr::vector, - T, - T&, - T cc::render::ResourceAccessNode::*>; -}; - -// Vertex Index -template <> -struct property_map { - using const_type = identity_property_map; - using type = identity_property_map; -}; - -// Vertex Component -template <> -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - const cc::render::RelationGraph, - const ccstd::pmr::vector, - cc::render::ResourceAccessGraph::vertex_descriptor, - const cc::render::ResourceAccessGraph::vertex_descriptor&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - cc::render::RelationGraph, - ccstd::pmr::vector, - cc::render::ResourceAccessGraph::vertex_descriptor, - cc::render::ResourceAccessGraph::vertex_descriptor&>; -}; - -} // namespace boost - -namespace cc { - -namespace render { - -// Vertex Index -inline boost::property_map::const_type -get(boost::vertex_index_t /*tag*/, const ResourceAccessGraph& /*g*/) noexcept { - return {}; -} - -inline boost::property_map::type -get(boost::vertex_index_t /*tag*/, ResourceAccessGraph& /*g*/) noexcept { - return {}; -} - -inline impl::ColorMap -get(ccstd::pmr::vector& colors, const ResourceAccessGraph& /*g*/) noexcept { - return {colors}; -} - -// Vertex Component -inline typename boost::property_map::const_type -get(ResourceAccessGraph::PassIDTag /*tag*/, const ResourceAccessGraph& g) noexcept { - return {g.passID}; -} - -inline typename boost::property_map::type -get(ResourceAccessGraph::PassIDTag /*tag*/, ResourceAccessGraph& g) noexcept { - return {g.passID}; -} - -// Vertex Component -inline typename boost::property_map::const_type -get(ResourceAccessGraph::AccessNodeTag /*tag*/, const ResourceAccessGraph& g) noexcept { - return {g.access}; -} - -inline typename boost::property_map::type -get(ResourceAccessGraph::AccessNodeTag /*tag*/, ResourceAccessGraph& g) noexcept { - return {g.access}; -} - -// Vertex ComponentMember -template -inline typename boost::property_map::const_type -get(T ResourceAccessNode::*memberPointer, const ResourceAccessGraph& g) noexcept { - return {g.access, memberPointer}; -} - -template -inline typename boost::property_map::type -get(T ResourceAccessNode::*memberPointer, ResourceAccessGraph& g) noexcept { - return {g.access, memberPointer}; -} - -// Vertex Constant Getter -template -inline decltype(auto) -get(Tag tag, const ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Mutable Getter -template -inline decltype(auto) -get(Tag tag, ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Setter -template -inline void put( - Tag tag, ResourceAccessGraph& g, - ResourceAccessGraph::vertex_descriptor v, - Args&&... args) { - put(get(tag, g), v, std::forward(args)...); -} - -// UuidGraph -inline ResourceAccessGraph::vertex_descriptor -vertex(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) { - return g.passIndex.at(key); -} - -template -inline ResourceAccessGraph::vertex_descriptor -vertex(const KeyLike& key, const ResourceAccessGraph& g) { - const auto& index = g.passIndex; - auto iter = index.find(key); - if (iter == index.end()) { - throw std::out_of_range("at(key, ResourceAccessGraph) out of range"); - } - return iter->second; -} - -template -inline ResourceAccessGraph::vertex_descriptor -findVertex(const KeyLike& key, const ResourceAccessGraph& g) noexcept { - const auto& index = g.passIndex; - auto iter = index.find(key); - if (iter == index.end()) { - return ResourceAccessGraph::null_vertex(); - } - return iter->second; -} - -inline bool -contains(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) noexcept { - auto iter = g.passIndex.find(key); - return iter != g.passIndex.end(); -} - -template -inline bool -contains(const KeyLike& key, const ResourceAccessGraph& g) noexcept { - auto iter = g.passIndex.find(key); - return iter != g.passIndex.end(); -} - -// MutableGraph(Vertex) -inline ResourceAccessGraph::vertex_descriptor -add_vertex(ResourceAccessGraph& g, const RenderGraph::vertex_descriptor& key) { // NOLINT - return addVertex( - std::piecewise_construct, - std::forward_as_tuple(key), // passID - std::forward_as_tuple(), // access - g); -} - -// Vertex Index -inline boost::property_map::const_type -get(boost::vertex_index_t /*tag*/, const RelationGraph& /*g*/) noexcept { - return {}; -} - -inline boost::property_map::type -get(boost::vertex_index_t /*tag*/, RelationGraph& /*g*/) noexcept { - return {}; -} - -inline impl::ColorMap -get(ccstd::pmr::vector& colors, const RelationGraph& /*g*/) noexcept { - return {colors}; -} - -// Vertex Component -inline typename boost::property_map::const_type -get(RelationGraph::DescIDTag /*tag*/, const RelationGraph& g) noexcept { - return {g.descID}; -} - -inline typename boost::property_map::type -get(RelationGraph::DescIDTag /*tag*/, RelationGraph& g) noexcept { - return {g.descID}; -} - -// Vertex Constant Getter -template -inline decltype(auto) -get(Tag tag, const RelationGraph& g, RelationGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Mutable Getter -template -inline decltype(auto) -get(Tag tag, RelationGraph& g, RelationGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Setter -template -inline void put( - Tag tag, RelationGraph& g, - RelationGraph::vertex_descriptor v, - Args&&... args) { - put(get(tag, g), v, std::forward(args)...); -} - -// UuidGraph -inline RelationGraph::vertex_descriptor -vertex(const ResourceAccessGraph::vertex_descriptor& key, const RelationGraph& g) { - return g.vertexMap.at(key); -} - -template -inline RelationGraph::vertex_descriptor -vertex(const KeyLike& key, const RelationGraph& g) { - const auto& index = g.vertexMap; - auto iter = index.find(key); - if (iter == index.end()) { - throw std::out_of_range("at(key, RelationGraph) out of range"); - } - return iter->second; -} - -template -inline RelationGraph::vertex_descriptor -findVertex(const KeyLike& key, const RelationGraph& g) noexcept { - const auto& index = g.vertexMap; - auto iter = index.find(key); - if (iter == index.end()) { - return RelationGraph::null_vertex(); - } - return iter->second; -} - -inline bool -contains(const ResourceAccessGraph::vertex_descriptor& key, const RelationGraph& g) noexcept { - auto iter = g.vertexMap.find(key); - return iter != g.vertexMap.end(); -} - -template -inline bool -contains(const KeyLike& key, const RelationGraph& g) noexcept { - auto iter = g.vertexMap.find(key); - return iter != g.vertexMap.end(); -} - -// MutableGraph(Vertex) -inline RelationGraph::vertex_descriptor -add_vertex(RelationGraph& g, const ResourceAccessGraph::vertex_descriptor& key) { // NOLINT - return addVertex( - std::piecewise_construct, - std::forward_as_tuple(key), // descID - g); -} - -} // namespace render - -} // namespace cc - -// clang-format on +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +/** + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * The following section is auto-generated. + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + */ +// clang-format off +#pragma once +#include +#include +#include "cocos/renderer/pipeline/custom/FGDispatcherTypes.h" +#include "cocos/renderer/pipeline/custom/details/GraphImpl.h" +#include "cocos/renderer/pipeline/custom/details/Overload.h" +#include "cocos/renderer/pipeline/custom/details/PathUtils.h" + +namespace cc { + +namespace render { + +// IncidenceGraph +inline ResourceAccessGraph::vertex_descriptor +source(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { + return e.source; +} + +inline ResourceAccessGraph::vertex_descriptor +target(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { + return e.target; +} + +inline std::pair +out_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return std::make_pair( + ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), + ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); +} + +inline ResourceAccessGraph::degree_size_type +out_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getOutEdgeList(u).size()); +} + +inline std::pair +edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, const ResourceAccessGraph& g) noexcept { + const auto& outEdgeList = g.getOutEdgeList(u); + auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), ResourceAccessGraph::OutEdge(v)); + bool hasEdge = (iter != outEdgeList.end()); + return {ResourceAccessGraph::edge_descriptor(u, v), hasEdge}; +} + +// BidirectionalGraph(Directed) +inline std::pair +in_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return std::make_pair( + ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), + ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); +} + +inline ResourceAccessGraph::degree_size_type +in_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getInEdgeList(u).size()); +} + +inline ResourceAccessGraph::degree_size_type +degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { + return in_degree(u, g) + out_degree(u, g); +} + +// AdjacencyGraph +inline std::pair +adjacent_vertices(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + auto edges = out_edges(u, g); + return std::make_pair(ResourceAccessGraph::adjacency_iterator(edges.first, &g), ResourceAccessGraph::adjacency_iterator(edges.second, &g)); +} + +// VertexListGraph +inline std::pair +vertices(const ResourceAccessGraph& g) noexcept { + return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); +} + +inline ResourceAccessGraph::vertices_size_type +num_vertices(const ResourceAccessGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getVertexList().size()); +} + +// EdgeListGraph +inline std::pair +edges(const ResourceAccessGraph& g0) noexcept { + auto& g = const_cast(g0); + return std::make_pair( + ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), + ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); +} + +inline ResourceAccessGraph::edges_size_type +num_edges(const ResourceAccessGraph& g) noexcept { // NOLINT + ResourceAccessGraph::edges_size_type numEdges = 0; + + auto range = vertices(g); + for (auto iter = range.first; iter != range.second; ++iter) { + numEdges += out_degree(*iter, g); + } + return numEdges; +} + +// MutableGraph(Edge) +inline std::pair +add_edge( // NOLINT + ResourceAccessGraph::vertex_descriptor u, + ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) { + auto& outEdgeList = g.getOutEdgeList(u); + outEdgeList.emplace_back(v); + + auto& inEdgeList = g.getInEdgeList(v); + inEdgeList.emplace_back(u); + + return std::make_pair(ResourceAccessGraph::edge_descriptor(u, v), true); +} + +inline void remove_edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) noexcept { // NOLINT + auto& s = g._vertices[u]; + auto& t = g._vertices[v]; + s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), ResourceAccessGraph::OutEdge(v)), s.outEdges.end()); + t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), ResourceAccessGraph::InEdge(u)), t.inEdges.end()); +} + +inline void remove_edge(ResourceAccessGraph::out_edge_iterator outIter, ResourceAccessGraph& g) noexcept { // NOLINT + auto e = *outIter; + const auto u = source(e, g); + const auto v = target(e, g); + auto& s = g._vertices[u]; + auto& t = g._vertices[v]; + auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), ResourceAccessGraph::InEdge(u)); + CC_EXPECTS(inIter != t.inEdges.end()); + t.inEdges.erase(inIter); + s.outEdges.erase(outIter.base()); +} + +inline void remove_edge(ResourceAccessGraph::edge_descriptor e, ResourceAccessGraph& g) noexcept { // NOLINT + const auto u = source(e, g); + const auto v = target(e, g); + auto& s = g._vertices[u]; + auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), ResourceAccessGraph::OutEdge(v)); + CC_EXPECTS(outIter != s.outEdges.end()); + remove_edge(ResourceAccessGraph::out_edge_iterator(outIter, u), g); +} + +// MutableGraph(Vertex) +inline void clear_out_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + // Bidirectional (OutEdges) + auto& outEdgeList = g.getOutEdgeList(u); + auto outEnd = outEdgeList.end(); + for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { + auto& inEdgeList = g.getInEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + outEdgeList.clear(); +} + +inline void clear_in_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + // Bidirectional (InEdges) + auto& inEdgeList = g.getInEdgeList(u); + auto inEnd = inEdgeList.end(); + for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { + auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + inEdgeList.clear(); +} + +inline void clear_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + clear_out_edges(u, g); + clear_in_edges(u, g); +} + +inline void remove_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + { // UuidGraph + const auto& key = g.passID[u]; + auto num = g.passIndex.erase(key); + CC_ENSURES(num == 1); + for (auto&& pair : g.passIndex) { + auto& v = pair.second; + if (v > u) { + --v; + } + } + } + impl::removeVectorVertex(const_cast(g), u, ResourceAccessGraph::directed_category{}); + + // remove components + g.passID.erase(g.passID.begin() + static_cast(u)); + g.passResource.erase(g.passResource.begin() + static_cast(u)); + g.rpInfo.erase(g.rpInfo.begin() + static_cast(u)); + g.barrier.erase(g.barrier.begin() + static_cast(u)); +} + +// MutablePropertyGraph(Vertex) +template +inline ResourceAccessGraph::vertex_descriptor +addVertex(Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, ResourceAccessGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + const auto& uuid = c0; + auto res = g.passIndex.emplace(uuid, v); + CC_ENSURES(res.second); + } + g.passID.emplace_back(std::forward(c0)); + g.passResource.emplace_back(std::forward(c1)); + g.rpInfo.emplace_back(std::forward(c2)); + g.barrier.emplace_back(std::forward(c3)); + + return v; +} + +template +inline ResourceAccessGraph::vertex_descriptor +addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, ResourceAccessGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + std::apply( + [&](const auto&... args) { + auto res = g.passIndex.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); + CC_ENSURES(res.second); + }, + c0); + } + + std::apply( + [&](auto&&... args) { + g.passID.emplace_back(std::forward(args)...); + }, + std::forward(c0)); + + std::apply( + [&](auto&&... args) { + g.passResource.emplace_back(std::forward(args)...); + }, + std::forward(c1)); + + std::apply( + [&](auto&&... args) { + g.rpInfo.emplace_back(std::forward(args)...); + }, + std::forward(c2)); + + std::apply( + [&](auto&&... args) { + g.barrier.emplace_back(std::forward(args)...); + }, + std::forward(c3)); + + return v; +} + +// IncidenceGraph +inline RelationGraph::vertex_descriptor +source(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { + return e.source; +} + +inline RelationGraph::vertex_descriptor +target(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { + return e.target; +} + +inline std::pair +out_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return std::make_pair( + RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), + RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); +} + +inline RelationGraph::degree_size_type +out_degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getOutEdgeList(u).size()); +} + +inline std::pair +edge(RelationGraph::vertex_descriptor u, RelationGraph::vertex_descriptor v, const RelationGraph& g) noexcept { + const auto& outEdgeList = g.getOutEdgeList(u); + auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), RelationGraph::OutEdge(v)); + bool hasEdge = (iter != outEdgeList.end()); + return {RelationGraph::edge_descriptor(u, v), hasEdge}; +} + +// BidirectionalGraph(Directed) +inline std::pair +in_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return std::make_pair( + RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), + RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); +} + +inline RelationGraph::degree_size_type +in_degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getInEdgeList(u).size()); +} + +inline RelationGraph::degree_size_type +degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { + return in_degree(u, g) + out_degree(u, g); +} + +// AdjacencyGraph +inline std::pair +adjacent_vertices(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + auto edges = out_edges(u, g); + return std::make_pair(RelationGraph::adjacency_iterator(edges.first, &g), RelationGraph::adjacency_iterator(edges.second, &g)); +} + +// VertexListGraph +inline std::pair +vertices(const RelationGraph& g) noexcept { + return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); +} + +inline RelationGraph::vertices_size_type +num_vertices(const RelationGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getVertexList().size()); +} + +// EdgeListGraph +inline std::pair +edges(const RelationGraph& g0) noexcept { + auto& g = const_cast(g0); + return std::make_pair( + RelationGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), + RelationGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); +} + +inline RelationGraph::edges_size_type +num_edges(const RelationGraph& g) noexcept { // NOLINT + RelationGraph::edges_size_type numEdges = 0; + + auto range = vertices(g); + for (auto iter = range.first; iter != range.second; ++iter) { + numEdges += out_degree(*iter, g); + } + return numEdges; +} + +// MutableGraph(Edge) +inline std::pair +add_edge( // NOLINT + RelationGraph::vertex_descriptor u, + RelationGraph::vertex_descriptor v, RelationGraph& g) { + auto& outEdgeList = g.getOutEdgeList(u); + outEdgeList.emplace_back(v); + + auto& inEdgeList = g.getInEdgeList(v); + inEdgeList.emplace_back(u); + + return std::make_pair(RelationGraph::edge_descriptor(u, v), true); +} + +inline void remove_edge(RelationGraph::vertex_descriptor u, RelationGraph::vertex_descriptor v, RelationGraph& g) noexcept { // NOLINT + auto& s = g._vertices[u]; + auto& t = g._vertices[v]; + s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), RelationGraph::OutEdge(v)), s.outEdges.end()); + t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), RelationGraph::InEdge(u)), t.inEdges.end()); +} + +inline void remove_edge(RelationGraph::out_edge_iterator outIter, RelationGraph& g) noexcept { // NOLINT + auto e = *outIter; + const auto u = source(e, g); + const auto v = target(e, g); + auto& s = g._vertices[u]; + auto& t = g._vertices[v]; + auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), RelationGraph::InEdge(u)); + CC_EXPECTS(inIter != t.inEdges.end()); + t.inEdges.erase(inIter); + s.outEdges.erase(outIter.base()); +} + +inline void remove_edge(RelationGraph::edge_descriptor e, RelationGraph& g) noexcept { // NOLINT + const auto u = source(e, g); + const auto v = target(e, g); + auto& s = g._vertices[u]; + auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), RelationGraph::OutEdge(v)); + CC_EXPECTS(outIter != s.outEdges.end()); + remove_edge(RelationGraph::out_edge_iterator(outIter, u), g); +} + +// MutableGraph(Vertex) +inline void clear_out_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT + // Bidirectional (OutEdges) + auto& outEdgeList = g.getOutEdgeList(u); + auto outEnd = outEdgeList.end(); + for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { + auto& inEdgeList = g.getInEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + outEdgeList.clear(); +} + +inline void clear_in_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT + // Bidirectional (InEdges) + auto& inEdgeList = g.getInEdgeList(u); + auto inEnd = inEdgeList.end(); + for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { + auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + inEdgeList.clear(); +} + +inline void clear_vertex(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT + clear_out_edges(u, g); + clear_in_edges(u, g); +} + +inline void remove_vertex(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT + { // UuidGraph + const auto& key = g.descID[u]; + auto num = g.vertexMap.erase(key); + CC_ENSURES(num == 1); + for (auto&& pair : g.vertexMap) { + auto& v = pair.second; + if (v > u) { + --v; + } + } + } + impl::removeVectorVertex(const_cast(g), u, RelationGraph::directed_category{}); + + // remove components + g.descID.erase(g.descID.begin() + static_cast(u)); +} + +// MutablePropertyGraph(Vertex) +template +inline RelationGraph::vertex_descriptor +addVertex(Component0&& c0, RelationGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + const auto& uuid = c0; + auto res = g.vertexMap.emplace(uuid, v); + CC_ENSURES(res.second); + } + g.descID.emplace_back(std::forward(c0)); + + return v; +} + +template +inline RelationGraph::vertex_descriptor +addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, RelationGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + std::apply( + [&](const auto&... args) { + auto res = g.vertexMap.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); + CC_ENSURES(res.second); + }, + c0); + } + + std::apply( + [&](auto&&... args) { + g.descID.emplace_back(std::forward(args)...); + }, + std::forward(c0)); + + return v; +} + +} // namespace render + +} // namespace cc + +namespace boost { + +// Vertex Index +template <> +struct property_map { + using const_type = identity_property_map; + using type = identity_property_map; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::RenderGraph::vertex_descriptor, + const cc::render::RenderGraph::vertex_descriptor&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::RenderGraph::vertex_descriptor, + cc::render::RenderGraph::vertex_descriptor&>; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::ResourceAccessNode, + const cc::render::ResourceAccessNode&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::ResourceAccessNode, + cc::render::ResourceAccessNode&>; +}; + +// Vertex ComponentMember +template +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + T, + const T&, + T cc::render::ResourceAccessNode::*>; + using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + T, + T&, + T cc::render::ResourceAccessNode::*>; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::FGRenderPassInfo, + const cc::render::FGRenderPassInfo&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::FGRenderPassInfo, + cc::render::FGRenderPassInfo&>; +}; + +// Vertex ComponentMember +template +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + T, + const T&, + T cc::render::FGRenderPassInfo::*>; + using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + T, + T&, + T cc::render::FGRenderPassInfo::*>; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::BarrierNode, + const cc::render::BarrierNode&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::BarrierNode, + cc::render::BarrierNode&>; +}; + +// Vertex ComponentMember +template +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + T, + const T&, + T cc::render::BarrierNode::*>; + using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + T, + T&, + T cc::render::BarrierNode::*>; +}; + +// Vertex Index +template <> +struct property_map { + using const_type = identity_property_map; + using type = identity_property_map; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::RelationGraph, + const ccstd::pmr::vector, + cc::render::ResourceAccessGraph::vertex_descriptor, + const cc::render::ResourceAccessGraph::vertex_descriptor&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::RelationGraph, + ccstd::pmr::vector, + cc::render::ResourceAccessGraph::vertex_descriptor, + cc::render::ResourceAccessGraph::vertex_descriptor&>; +}; + +} // namespace boost + +namespace cc { + +namespace render { + +// Vertex Index +inline boost::property_map::const_type +get(boost::vertex_index_t /*tag*/, const ResourceAccessGraph& /*g*/) noexcept { + return {}; +} + +inline boost::property_map::type +get(boost::vertex_index_t /*tag*/, ResourceAccessGraph& /*g*/) noexcept { + return {}; +} + +inline impl::ColorMap +get(ccstd::pmr::vector& colors, const ResourceAccessGraph& /*g*/) noexcept { + return {colors}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::PassIDTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.passID}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::PassIDTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.passID}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::PassNodeTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.passResource}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::PassNodeTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.passResource}; +} + +// Vertex ComponentMember +template +inline typename boost::property_map::const_type +get(T ResourceAccessNode::*memberPointer, const ResourceAccessGraph& g) noexcept { + return {g.passResource, memberPointer}; +} + +template +inline typename boost::property_map::type +get(T ResourceAccessNode::*memberPointer, ResourceAccessGraph& g) noexcept { + return {g.passResource, memberPointer}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::RenderPassInfoTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.rpInfo}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::RenderPassInfoTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.rpInfo}; +} + +// Vertex ComponentMember +template +inline typename boost::property_map::const_type +get(T FGRenderPassInfo::*memberPointer, const ResourceAccessGraph& g) noexcept { + return {g.rpInfo, memberPointer}; +} + +template +inline typename boost::property_map::type +get(T FGRenderPassInfo::*memberPointer, ResourceAccessGraph& g) noexcept { + return {g.rpInfo, memberPointer}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::BarrierTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.barrier}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::BarrierTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.barrier}; +} + +// Vertex ComponentMember +template +inline typename boost::property_map::const_type +get(T BarrierNode::*memberPointer, const ResourceAccessGraph& g) noexcept { + return {g.barrier, memberPointer}; +} + +template +inline typename boost::property_map::type +get(T BarrierNode::*memberPointer, ResourceAccessGraph& g) noexcept { + return {g.barrier, memberPointer}; +} + +// Vertex Constant Getter +template +inline decltype(auto) +get(Tag tag, const ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Mutable Getter +template +inline decltype(auto) +get(Tag tag, ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Setter +template +inline void put( + Tag tag, ResourceAccessGraph& g, + ResourceAccessGraph::vertex_descriptor v, + Args&&... args) { + put(get(tag, g), v, std::forward(args)...); +} + +// UuidGraph +inline ResourceAccessGraph::vertex_descriptor +vertex(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) { + return g.passIndex.at(key); +} + +template +inline ResourceAccessGraph::vertex_descriptor +vertex(const KeyLike& key, const ResourceAccessGraph& g) { + const auto& index = g.passIndex; + auto iter = index.find(key); + if (iter == index.end()) { + throw std::out_of_range("at(key, ResourceAccessGraph) out of range"); + } + return iter->second; +} + +template +inline ResourceAccessGraph::vertex_descriptor +findVertex(const KeyLike& key, const ResourceAccessGraph& g) noexcept { + const auto& index = g.passIndex; + auto iter = index.find(key); + if (iter == index.end()) { + return ResourceAccessGraph::null_vertex(); + } + return iter->second; +} + +inline bool +contains(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) noexcept { + auto iter = g.passIndex.find(key); + return iter != g.passIndex.end(); +} + +template +inline bool +contains(const KeyLike& key, const ResourceAccessGraph& g) noexcept { + auto iter = g.passIndex.find(key); + return iter != g.passIndex.end(); +} + +// MutableGraph(Vertex) +inline ResourceAccessGraph::vertex_descriptor +add_vertex(ResourceAccessGraph& g, const RenderGraph::vertex_descriptor& key) { // NOLINT + return addVertex( + std::piecewise_construct, + std::forward_as_tuple(key), // passID + std::forward_as_tuple(), // passResource + std::forward_as_tuple(), // rpInfo + std::forward_as_tuple(), // barrier + g); +} + +// Vertex Index +inline boost::property_map::const_type +get(boost::vertex_index_t /*tag*/, const RelationGraph& /*g*/) noexcept { + return {}; +} + +inline boost::property_map::type +get(boost::vertex_index_t /*tag*/, RelationGraph& /*g*/) noexcept { + return {}; +} + +inline impl::ColorMap +get(ccstd::pmr::vector& colors, const RelationGraph& /*g*/) noexcept { + return {colors}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(RelationGraph::DescIDTag /*tag*/, const RelationGraph& g) noexcept { + return {g.descID}; +} + +inline typename boost::property_map::type +get(RelationGraph::DescIDTag /*tag*/, RelationGraph& g) noexcept { + return {g.descID}; +} + +// Vertex Constant Getter +template +inline decltype(auto) +get(Tag tag, const RelationGraph& g, RelationGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Mutable Getter +template +inline decltype(auto) +get(Tag tag, RelationGraph& g, RelationGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Setter +template +inline void put( + Tag tag, RelationGraph& g, + RelationGraph::vertex_descriptor v, + Args&&... args) { + put(get(tag, g), v, std::forward(args)...); +} + +// UuidGraph +inline RelationGraph::vertex_descriptor +vertex(const ResourceAccessGraph::vertex_descriptor& key, const RelationGraph& g) { + return g.vertexMap.at(key); +} + +template +inline RelationGraph::vertex_descriptor +vertex(const KeyLike& key, const RelationGraph& g) { + const auto& index = g.vertexMap; + auto iter = index.find(key); + if (iter == index.end()) { + throw std::out_of_range("at(key, RelationGraph) out of range"); + } + return iter->second; +} + +template +inline RelationGraph::vertex_descriptor +findVertex(const KeyLike& key, const RelationGraph& g) noexcept { + const auto& index = g.vertexMap; + auto iter = index.find(key); + if (iter == index.end()) { + return RelationGraph::null_vertex(); + } + return iter->second; +} + +inline bool +contains(const ResourceAccessGraph::vertex_descriptor& key, const RelationGraph& g) noexcept { + auto iter = g.vertexMap.find(key); + return iter != g.vertexMap.end(); +} + +template +inline bool +contains(const KeyLike& key, const RelationGraph& g) noexcept { + auto iter = g.vertexMap.find(key); + return iter != g.vertexMap.end(); +} + +// MutableGraph(Vertex) +inline RelationGraph::vertex_descriptor +add_vertex(RelationGraph& g, const ResourceAccessGraph::vertex_descriptor& key) { // NOLINT + return addVertex( + std::piecewise_construct, + std::forward_as_tuple(key), // descID + g); +} + +} // namespace render + +} // namespace cc + +// clang-format on diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index 01ba6c84a29..1982760fd0a 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -1,107 +1,173 @@ -/**************************************************************************** - Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -/** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ -// clang-format off -#include "FGDispatcherTypes.h" - -namespace cc { - -namespace render { - -ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept -: _vertices(alloc), - passID(alloc), - access(alloc), - passIndex(alloc), - resourceNames(alloc), - resourceIndex(alloc), - leafPasses(alloc), - culledPasses(alloc), - accessRecord(alloc), - resourceLifeRecord(alloc), - topologicalOrder(alloc), - rpInfos(alloc), - subpassIndex(alloc) {} - -// ContinuousContainer -void ResourceAccessGraph::reserve(vertices_size_type sz) { - _vertices.reserve(sz); - passID.reserve(sz); - access.reserve(sz); -} - -ResourceAccessGraph::Vertex::Vertex(const allocator_type& alloc) noexcept -: outEdges(alloc), - inEdges(alloc) {} - -ResourceAccessGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) -: outEdges(std::move(rhs.outEdges), alloc), - inEdges(std::move(rhs.inEdges), alloc) {} - -ResourceAccessGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) -: outEdges(rhs.outEdges, alloc), - inEdges(rhs.inEdges, alloc) {} - -RelationGraph::RelationGraph(const allocator_type& alloc) noexcept -: _vertices(alloc), - descID(alloc), - vertexMap(alloc) {} - -// ContinuousContainer -void RelationGraph::reserve(vertices_size_type sz) { - _vertices.reserve(sz); - descID.reserve(sz); -} - -RelationGraph::Vertex::Vertex(const allocator_type& alloc) noexcept -: outEdges(alloc), - inEdges(alloc) {} - -RelationGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) -: outEdges(std::move(rhs.outEdges), alloc), - inEdges(std::move(rhs.inEdges), alloc) {} - -RelationGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) -: outEdges(rhs.outEdges, alloc), - inEdges(rhs.inEdges, alloc) {} - -FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept -: resourceAccessGraph(alloc), - resourceGraph(resourceGraphIn), - graph(graphIn), - layoutGraph(layoutGraphIn), - scratch(scratchIn), - externalResMap(alloc), - relationGraph(alloc) {} - -} // namespace render - -} // namespace cc - -// clang-format on +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +/** + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * The following section is auto-generated. + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + */ +// clang-format off +#include "FGDispatcherTypes.h" + +namespace cc { + +namespace render { + +ResourceAccessNode::ResourceAccessNode(const allocator_type& alloc) noexcept +: resourceStatus(alloc) {} + +ResourceAccessNode::ResourceAccessNode(ResourceAccessNode&& rhs, const allocator_type& alloc) +: resourceStatus(std::move(rhs.resourceStatus), alloc) {} + +ResourceAccessNode::ResourceAccessNode(ResourceAccessNode const& rhs, const allocator_type& alloc) +: resourceStatus(rhs.resourceStatus, alloc) {} + +AttachmentInfo::AttachmentInfo(const allocator_type& alloc) noexcept +: parentName(alloc) {} + +AttachmentInfo::AttachmentInfo(AttachmentInfo&& rhs, const allocator_type& alloc) +: parentName(std::move(rhs.parentName), alloc), + attachmentIndex(rhs.attachmentIndex), + isResolveView(rhs.isResolveView) {} + +AttachmentInfo::AttachmentInfo(AttachmentInfo const& rhs, const allocator_type& alloc) +: parentName(rhs.parentName, alloc), + attachmentIndex(rhs.attachmentIndex), + isResolveView(rhs.isResolveView) {} + +FGRenderPassInfo::FGRenderPassInfo(const allocator_type& alloc) noexcept +: orderedViews(alloc), + viewIndex(alloc) {} + +FGRenderPassInfo::FGRenderPassInfo(FGRenderPassInfo&& rhs, const allocator_type& alloc) +: colorAccesses(std::move(rhs.colorAccesses)), + dsAccess(rhs.dsAccess), + dsResolveAccess(rhs.dsResolveAccess), + rpInfo(std::move(rhs.rpInfo)), + orderedViews(std::move(rhs.orderedViews), alloc), + viewIndex(std::move(rhs.viewIndex), alloc), + resolveCount(rhs.resolveCount), + uniqueRasterViewCount(rhs.uniqueRasterViewCount) {} + +FGRenderPassInfo::FGRenderPassInfo(FGRenderPassInfo const& rhs, const allocator_type& alloc) +: colorAccesses(rhs.colorAccesses), + dsAccess(rhs.dsAccess), + dsResolveAccess(rhs.dsResolveAccess), + rpInfo(rhs.rpInfo), + orderedViews(rhs.orderedViews, alloc), + viewIndex(rhs.viewIndex, alloc), + resolveCount(rhs.resolveCount), + uniqueRasterViewCount(rhs.uniqueRasterViewCount) {} + +ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept +: _vertices(alloc), + passID(alloc), + passResource(alloc), + rpInfo(alloc), + barrier(alloc), + passIndex(alloc), + resourceNames(alloc), + resourceIndex(alloc), + leafPasses(alloc), + culledPasses(alloc), + resourceLifeRecord(alloc), + topologicalOrder(alloc), + resourceAccess(alloc), + movedTarget(alloc), + movedSourceStatus(alloc) {} + +// ContinuousContainer +void ResourceAccessGraph::reserve(vertices_size_type sz) { + _vertices.reserve(sz); + passID.reserve(sz); + passResource.reserve(sz); + rpInfo.reserve(sz); + barrier.reserve(sz); +} + +ResourceAccessGraph::Vertex::Vertex(const allocator_type& alloc) noexcept +: outEdges(alloc), + inEdges(alloc) {} + +ResourceAccessGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) +: outEdges(std::move(rhs.outEdges), alloc), + inEdges(std::move(rhs.inEdges), alloc) {} + +ResourceAccessGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) +: outEdges(rhs.outEdges, alloc), + inEdges(rhs.inEdges, alloc) {} + +RelationGraph::RelationGraph(const allocator_type& alloc) noexcept +: _vertices(alloc), + descID(alloc), + vertexMap(alloc) {} + +// ContinuousContainer +void RelationGraph::reserve(vertices_size_type sz) { + _vertices.reserve(sz); + descID.reserve(sz); +} + +RelationGraph::Vertex::Vertex(const allocator_type& alloc) noexcept +: outEdges(alloc), + inEdges(alloc) {} + +RelationGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) +: outEdges(std::move(rhs.outEdges), alloc), + inEdges(std::move(rhs.inEdges), alloc) {} + +RelationGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) +: outEdges(rhs.outEdges, alloc), + inEdges(rhs.inEdges, alloc) {} + +RenderingInfo::RenderingInfo(const allocator_type& alloc) noexcept +: clearColors(alloc) {} + +RenderingInfo::RenderingInfo(RenderingInfo&& rhs, const allocator_type& alloc) +: renderpassInfo(std::move(rhs.renderpassInfo)), + framebufferInfo(std::move(rhs.framebufferInfo)), + clearColors(std::move(rhs.clearColors), alloc), + clearDepth(rhs.clearDepth), + clearStencil(rhs.clearStencil) {} + +RenderingInfo::RenderingInfo(RenderingInfo const& rhs, const allocator_type& alloc) +: renderpassInfo(rhs.renderpassInfo), + framebufferInfo(rhs.framebufferInfo), + clearColors(rhs.clearColors, alloc), + clearDepth(rhs.clearDepth), + clearStencil(rhs.clearStencil) {} + +FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& renderGraphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept +: resourceAccessGraph(alloc), + resourceGraph(resourceGraphIn), + renderGraph(renderGraphIn), + layoutGraph(layoutGraphIn), + scratch(scratchIn), + relationGraph(alloc) {} + +} // namespace render + +} // namespace cc + +// clang-format on diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index 0ac3830c647..25816eaf81c 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -1,451 +1,502 @@ -/**************************************************************************** - Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -/** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ -// clang-format off -#pragma once -#include -#include -#include -#include -#include -#include "cocos/base/std/container/string.h" -#include "cocos/base/std/container/vector.h" -#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" -#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" -#include "cocos/renderer/pipeline/custom/details/GraphTypes.h" -#include "cocos/renderer/pipeline/custom/details/Map.h" -#include "cocos/renderer/pipeline/custom/details/Set.h" -#include "gfx-base/GFXDef-common.h" - -namespace cc { - -namespace render { - -struct NullTag { -}; - -struct ResourceLifeRecord { - uint32_t start{0}; - uint32_t end{0}; -}; - -struct LeafStatus { - bool isExternal{false}; - bool needCulling{false}; -}; - -struct BufferRange { - uint32_t offset{0}; - uint32_t size{0}; -}; - -inline bool operator<(const BufferRange& lhs, const BufferRange& rhs) noexcept { - return std::forward_as_tuple(lhs.offset, lhs.size) < - std::forward_as_tuple(rhs.offset, rhs.size); -} - -struct TextureRange { - uint32_t firstSlice{0}; - uint32_t numSlices{1}; - uint32_t mipLevel{0}; - uint32_t levelCount{1}; -}; - -inline bool operator<(const TextureRange& lhs, const TextureRange& rhs) noexcept { - return std::forward_as_tuple(lhs.firstSlice, lhs.numSlices, lhs.mipLevel, lhs.levelCount) < - std::forward_as_tuple(rhs.firstSlice, rhs.numSlices, rhs.mipLevel, rhs.levelCount); -} - -using Range = ccstd::variant; - -using ResourceUsage = ccstd::variant; - -struct AccessStatus { - uint32_t vertID{0xFFFFFFFF}; - gfx::ShaderStageFlagBit visibility{gfx::ShaderStageFlagBit::NONE}; - gfx::MemoryAccessBit access{gfx::MemoryAccessBit::NONE}; - gfx::PassType passType{gfx::PassType::RASTER}; - gfx::AccessFlagBit accessFlag{gfx::AccessFlagBit::NONE}; - ResourceUsage usage; - Range range; -}; - -struct ResourceTransition { - AccessStatus lastStatus; - AccessStatus currStatus; -}; - -struct ResourceAccessNode { - std::vector attachmentStatus; - struct ResourceAccessNode* nextSubpass{nullptr}; -}; - -struct LayoutAccess { - gfx::AccessFlagBit prevAccess{gfx::AccessFlagBit::NONE}; - gfx::AccessFlagBit nextAccess{gfx::AccessFlagBit::NONE}; -}; - -struct FGRenderPassInfo { - std::vector colorAccesses; - LayoutAccess dsAccess; - LayoutAccess dsResolveAccess; - gfx::RenderPassInfo rpInfo; - std::vector orderedViews; - bool needResolve{false}; -}; - -struct ResourceAccessGraph { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {_vertices.get_allocator().resource()}; - } - - inline boost::container::pmr::memory_resource* resource() const noexcept { - return get_allocator().resource(); - } - - ResourceAccessGraph(const allocator_type& alloc) noexcept; // NOLINT - ResourceAccessGraph(ResourceAccessGraph&& rhs) = delete; - ResourceAccessGraph(ResourceAccessGraph const& rhs) = delete; - ResourceAccessGraph& operator=(ResourceAccessGraph&& rhs) = delete; - ResourceAccessGraph& operator=(ResourceAccessGraph const& rhs) = delete; - - // Graph - using directed_category = boost::bidirectional_tag; - using vertex_descriptor = uint32_t; - using edge_descriptor = impl::EdgeDescriptor; - using edge_parallel_category = boost::allow_parallel_edge_tag; - struct traversal_category // NOLINT - : virtual boost::incidence_graph_tag, - virtual boost::bidirectional_graph_tag, - virtual boost::adjacency_graph_tag, - virtual boost::vertex_list_graph_tag, - virtual boost::edge_list_graph_tag {}; - - constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT - return std::numeric_limits::max(); - } - - // IncidenceGraph - using OutEdge = impl::StoredEdge; - using out_edge_iterator = impl::OutEdgeIter< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - using degree_size_type = uint32_t; - - // BidirectionalGraph - using InEdge = impl::StoredEdge; - using in_edge_iterator = impl::InEdgeIter< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - - // AdjacencyGraph - using adjacency_iterator = boost::adjacency_iterator_generator< - ResourceAccessGraph, vertex_descriptor, out_edge_iterator>::type; - - // VertexListGraph - using vertex_iterator = boost::integer_range::iterator; - using vertices_size_type = uint32_t; - - // VertexList help functions - inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].outEdges; - } - inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].outEdges; - } - - inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].inEdges; - } - inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].inEdges; - } - - inline boost::integer_range getVertexList() const noexcept { - return {0, static_cast(_vertices.size())}; - } - - inline vertex_descriptor getCurrentID() const noexcept { - return static_cast(_vertices.size()); - } - - inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { - return ccstd::pmr::vector(_vertices.size(), mr); - } - - // EdgeListGraph - using edge_iterator = impl::DirectedEdgeIterator; - using edges_size_type = uint32_t; - - ~ResourceAccessGraph() { - for (auto& node : access) { - auto* resNode = node.nextSubpass; - node.nextSubpass = nullptr; - while(resNode) { - auto* oldResNode = resNode; - resNode = resNode->nextSubpass; - oldResNode->nextSubpass = nullptr; - delete oldResNode; - } - } - } - - - // ContinuousContainer - void reserve(vertices_size_type sz); - - // Members - struct Vertex { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {outEdges.get_allocator().resource()}; - } - - Vertex(const allocator_type& alloc) noexcept; // NOLINT - Vertex(Vertex&& rhs, const allocator_type& alloc); - Vertex(Vertex const& rhs, const allocator_type& alloc); - - Vertex(Vertex&& rhs) noexcept = default; - Vertex(Vertex const& rhs) = delete; - Vertex& operator=(Vertex&& rhs) = default; - Vertex& operator=(Vertex const& rhs) = default; - - ccstd::pmr::vector outEdges; - ccstd::pmr::vector inEdges; - }; - - struct PassIDTag {}; - struct AccessNodeTag {}; - - // Vertices - ccstd::pmr::vector _vertices; - // Components - ccstd::pmr::vector passID; - ccstd::pmr::vector access; - // UuidGraph - PmrUnorderedMap passIndex; - // Members - ccstd::pmr::vector resourceNames; - PmrUnorderedStringMap resourceIndex; - vertex_descriptor presentPassID{0xFFFFFFFF}; - PmrFlatMap leafPasses; - PmrFlatSet culledPasses; - PmrFlatMap accessRecord; - PmrFlatMap resourceLifeRecord; - ccstd::pmr::vector topologicalOrder; - PmrFlatMap rpInfos; - PmrFlatMap subpassIndex; -}; - -struct RelationGraph { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {_vertices.get_allocator().resource()}; - } - - inline boost::container::pmr::memory_resource* resource() const noexcept { - return get_allocator().resource(); - } - - RelationGraph(const allocator_type& alloc) noexcept; // NOLINT - RelationGraph(RelationGraph&& rhs) = delete; - RelationGraph(RelationGraph const& rhs) = delete; - RelationGraph& operator=(RelationGraph&& rhs) = delete; - RelationGraph& operator=(RelationGraph const& rhs) = delete; - - // Graph - using directed_category = boost::bidirectional_tag; - using vertex_descriptor = uint32_t; - using edge_descriptor = impl::EdgeDescriptor; - using edge_parallel_category = boost::allow_parallel_edge_tag; - struct traversal_category // NOLINT - : virtual boost::incidence_graph_tag, - virtual boost::bidirectional_graph_tag, - virtual boost::adjacency_graph_tag, - virtual boost::vertex_list_graph_tag, - virtual boost::edge_list_graph_tag {}; - - constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT - return std::numeric_limits::max(); - } - - // IncidenceGraph - using OutEdge = impl::StoredEdge; - using out_edge_iterator = impl::OutEdgeIter< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - using degree_size_type = uint32_t; - - // BidirectionalGraph - using InEdge = impl::StoredEdge; - using in_edge_iterator = impl::InEdgeIter< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - - // AdjacencyGraph - using adjacency_iterator = boost::adjacency_iterator_generator< - RelationGraph, vertex_descriptor, out_edge_iterator>::type; - - // VertexListGraph - using vertex_iterator = boost::integer_range::iterator; - using vertices_size_type = uint32_t; - - // VertexList help functions - inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].outEdges; - } - inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].outEdges; - } - - inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].inEdges; - } - inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].inEdges; - } - - inline boost::integer_range getVertexList() const noexcept { - return {0, static_cast(_vertices.size())}; - } - - inline vertex_descriptor getCurrentID() const noexcept { - return static_cast(_vertices.size()); - } - - inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { - return ccstd::pmr::vector(_vertices.size(), mr); - } - - // EdgeListGraph - using edge_iterator = impl::DirectedEdgeIterator; - using edges_size_type = uint32_t; - - // ContinuousContainer - void reserve(vertices_size_type sz); - - // Members - struct Vertex { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {outEdges.get_allocator().resource()}; - } - - Vertex(const allocator_type& alloc) noexcept; // NOLINT - Vertex(Vertex&& rhs, const allocator_type& alloc); - Vertex(Vertex const& rhs, const allocator_type& alloc); - - Vertex(Vertex&& rhs) noexcept = default; - Vertex(Vertex const& rhs) = delete; - Vertex& operator=(Vertex&& rhs) = default; - Vertex& operator=(Vertex const& rhs) = default; - - ccstd::pmr::vector outEdges; - ccstd::pmr::vector inEdges; - }; - - struct DescIDTag {}; - - // Vertices - ccstd::pmr::vector _vertices; - // Components - ccstd::pmr::vector descID; - // UuidGraph - PmrUnorderedMap vertexMap; -}; - -struct Barrier { - ResourceGraph::vertex_descriptor resourceID{0xFFFFFFFF}; - gfx::BarrierType type{gfx::BarrierType::FULL}; - gfx::GFXObject* barrier{nullptr}; - AccessStatus beginStatus; - AccessStatus endStatus; -}; - -struct BarrierPair { - std::vector frontBarriers; - std::vector rearBarriers; -}; - -struct BarrierNode { - BarrierPair blockBarrier; - std::vector subpassBarriers; -}; - -struct FrameGraphDispatcher { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {resourceAccessGraph.get_allocator().resource()}; - } - - FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; - FrameGraphDispatcher(FrameGraphDispatcher&& rhs) = delete; - FrameGraphDispatcher(FrameGraphDispatcher const& rhs) = delete; - FrameGraphDispatcher& operator=(FrameGraphDispatcher&& rhs) = delete; - FrameGraphDispatcher& operator=(FrameGraphDispatcher const& rhs) = delete; - - using BarrierMap = PmrMap; - - void enablePassReorder(bool enable); - - // how much paralell-execution weights during pass reorder, - // eg:0.3 means 30% of effort aim to paralellize execution, other 70% aim to decrease memory using. - // 0 by default - void setParalellWeight(float paralellExecWeight); - - void enableMemoryAliasing(bool enable); - - void run(); - - const ResourceAccessNode& getAttachmentStatus(RenderGraph::vertex_descriptor renderGraphVertID) const; - - inline const BarrierMap& getBarriers() const { return barrierMap; } - - BarrierMap barrierMap; - - ResourceAccessGraph resourceAccessGraph; - ResourceGraph& resourceGraph; - const RenderGraph& graph; - const LayoutGraphData& layoutGraph; - boost::container::pmr::memory_resource* scratch{nullptr}; - PmrFlatMap externalResMap; - RelationGraph relationGraph; - bool _enablePassReorder{false}; - bool _enableAutoBarrier{true}; - bool _enableMemoryAliasing{false}; - bool _accessGraphBuilt{false}; - float _paralellExecWeight{0.0F}; -}; - -} // namespace render - -} // namespace cc - -// clang-format on +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +/** + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * The following section is auto-generated. + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + */ +// clang-format off +#pragma once +#include +#include +#include +#include +#include +#include "cocos/base/std/container/string.h" +#include "cocos/base/std/container/vector.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" +#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/Map.h" +#include "cocos/renderer/pipeline/custom/details/Set.h" +#include "gfx-base/GFXDef-common.h" + +namespace cc { + +namespace render { + +struct NullTag { +}; + +struct ResourceLifeRecord { + uint32_t start{0}; + uint32_t end{0}; +}; + +struct LeafStatus { + bool isExternal{false}; + bool needCulling{false}; +}; + +struct ResourceRange { + uint32_t width{0}; + uint32_t height{0}; + uint32_t depthOrArraySize{0}; + uint32_t firstSlice{0}; + uint32_t numSlices{0}; + uint32_t mipLevel{0}; + uint32_t levelCount{0}; + uint32_t basePlane{0}; + uint32_t planeCount{0}; +}; + +struct AccessStatus { + gfx::AccessFlagBit accessFlag{gfx::AccessFlagBit::NONE}; + ResourceRange range; +}; + +struct ResourceAccessNode { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {resourceStatus.get_allocator().resource()}; + } + + ResourceAccessNode(const allocator_type& alloc) noexcept; // NOLINT + ResourceAccessNode(ResourceAccessNode&& rhs, const allocator_type& alloc); + ResourceAccessNode(ResourceAccessNode const& rhs, const allocator_type& alloc); + + ResourceAccessNode(ResourceAccessNode&& rhs) noexcept = default; + ResourceAccessNode(ResourceAccessNode const& rhs) = delete; + ResourceAccessNode& operator=(ResourceAccessNode&& rhs) = default; + ResourceAccessNode& operator=(ResourceAccessNode const& rhs) = default; + + PmrFlatMap resourceStatus; +}; + +struct LayoutAccess { + gfx::AccessFlagBit prevAccess{gfx::AccessFlagBit::NONE}; + gfx::AccessFlagBit nextAccess{gfx::AccessFlagBit::NONE}; +}; + +struct AttachmentInfo { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {parentName.get_allocator().resource()}; + } + + AttachmentInfo(const allocator_type& alloc) noexcept; // NOLINT + AttachmentInfo(AttachmentInfo&& rhs, const allocator_type& alloc); + AttachmentInfo(AttachmentInfo const& rhs, const allocator_type& alloc); + + AttachmentInfo(AttachmentInfo&& rhs) noexcept = default; + AttachmentInfo(AttachmentInfo const& rhs) = delete; + AttachmentInfo& operator=(AttachmentInfo&& rhs) = default; + AttachmentInfo& operator=(AttachmentInfo const& rhs) = default; + + ccstd::pmr::string parentName; + uint32_t attachmentIndex{0}; + uint32_t isResolveView{0}; +}; + +struct FGRenderPassInfo { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {orderedViews.get_allocator().resource()}; + } + + FGRenderPassInfo(const allocator_type& alloc) noexcept; // NOLINT + FGRenderPassInfo(FGRenderPassInfo&& rhs, const allocator_type& alloc); + FGRenderPassInfo(FGRenderPassInfo const& rhs, const allocator_type& alloc); + + FGRenderPassInfo(FGRenderPassInfo&& rhs) noexcept = default; + FGRenderPassInfo(FGRenderPassInfo const& rhs) = delete; + FGRenderPassInfo& operator=(FGRenderPassInfo&& rhs) = default; + FGRenderPassInfo& operator=(FGRenderPassInfo const& rhs) = default; + + std::vector colorAccesses; + LayoutAccess dsAccess; + LayoutAccess dsResolveAccess; + gfx::RenderPassInfo rpInfo; + ccstd::pmr::vector orderedViews; + PmrTransparentMap viewIndex; + uint32_t resolveCount{0}; + uint32_t uniqueRasterViewCount{0}; +}; + +struct Barrier { + ResourceGraph::vertex_descriptor resourceID{0xFFFFFFFF}; + gfx::BarrierType type{gfx::BarrierType::FULL}; + gfx::GFXObject* barrier{nullptr}; + RenderGraph::vertex_descriptor beginVert{0xFFFFFFFF}; + RenderGraph::vertex_descriptor endVert{0xFFFFFFFF}; + AccessStatus beginStatus; + AccessStatus endStatus; +}; + +struct BarrierNode { + std::vector frontBarriers; + std::vector rearBarriers; +}; + +struct ResourceAccessGraph { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {_vertices.get_allocator().resource()}; + } + + inline boost::container::pmr::memory_resource* resource() const noexcept { + return get_allocator().resource(); + } + + ResourceAccessGraph(const allocator_type& alloc) noexcept; // NOLINT + ResourceAccessGraph(ResourceAccessGraph&& rhs) = delete; + ResourceAccessGraph(ResourceAccessGraph const& rhs) = delete; + ResourceAccessGraph& operator=(ResourceAccessGraph&& rhs) = delete; + ResourceAccessGraph& operator=(ResourceAccessGraph const& rhs) = delete; + + // Graph + using directed_category = boost::bidirectional_tag; + using vertex_descriptor = uint32_t; + using edge_descriptor = impl::EdgeDescriptor; + using edge_parallel_category = boost::allow_parallel_edge_tag; + struct traversal_category // NOLINT + : virtual boost::incidence_graph_tag, + virtual boost::bidirectional_graph_tag, + virtual boost::adjacency_graph_tag, + virtual boost::vertex_list_graph_tag, + virtual boost::edge_list_graph_tag {}; + + constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT + return std::numeric_limits::max(); + } + + // IncidenceGraph + using OutEdge = impl::StoredEdge; + using out_edge_iterator = impl::OutEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + using degree_size_type = uint32_t; + + // BidirectionalGraph + using InEdge = impl::StoredEdge; + using in_edge_iterator = impl::InEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + + // AdjacencyGraph + using adjacency_iterator = boost::adjacency_iterator_generator< + ResourceAccessGraph, vertex_descriptor, out_edge_iterator>::type; + + // VertexListGraph + using vertex_iterator = boost::integer_range::iterator; + using vertices_size_type = uint32_t; + + // VertexList help functions + inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].outEdges; + } + inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].outEdges; + } + + inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].inEdges; + } + inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].inEdges; + } + + inline boost::integer_range getVertexList() const noexcept { + return {0, static_cast(_vertices.size())}; + } + + inline vertex_descriptor getCurrentID() const noexcept { + return static_cast(_vertices.size()); + } + + inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { + return ccstd::pmr::vector(_vertices.size(), mr); + } + + // EdgeListGraph + using edge_iterator = impl::DirectedEdgeIterator; + using edges_size_type = uint32_t; + + LayoutAccess getAccess(ccstd::pmr::string, RenderGraph::vertex_descriptor vertID); + + + // ContinuousContainer + void reserve(vertices_size_type sz); + + // Members + struct Vertex { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {outEdges.get_allocator().resource()}; + } + + Vertex(const allocator_type& alloc) noexcept; // NOLINT + Vertex(Vertex&& rhs, const allocator_type& alloc); + Vertex(Vertex const& rhs, const allocator_type& alloc); + + Vertex(Vertex&& rhs) noexcept = default; + Vertex(Vertex const& rhs) = delete; + Vertex& operator=(Vertex&& rhs) = default; + Vertex& operator=(Vertex const& rhs) = default; + + ccstd::pmr::vector outEdges; + ccstd::pmr::vector inEdges; + }; + + struct PassIDTag {}; + struct PassNodeTag {}; + struct RenderPassInfoTag {}; + struct BarrierTag {}; + + // Vertices + ccstd::pmr::vector _vertices; + // Components + ccstd::pmr::vector passID; + ccstd::pmr::vector passResource; + ccstd::pmr::vector rpInfo; + ccstd::pmr::vector barrier; + // UuidGraph + PmrUnorderedMap passIndex; + // Members + ccstd::pmr::vector resourceNames; + PmrUnorderedStringMap resourceIndex; + vertex_descriptor presentPassID{0xFFFFFFFF}; + PmrFlatMap leafPasses; + PmrFlatSet culledPasses; + PmrFlatMap resourceLifeRecord; + ccstd::pmr::vector topologicalOrder; + PmrTransparentMap> resourceAccess; + PmrFlatMap> movedTarget; + PmrFlatMap movedSourceStatus; +}; + +struct RelationGraph { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {_vertices.get_allocator().resource()}; + } + + inline boost::container::pmr::memory_resource* resource() const noexcept { + return get_allocator().resource(); + } + + RelationGraph(const allocator_type& alloc) noexcept; // NOLINT + RelationGraph(RelationGraph&& rhs) = delete; + RelationGraph(RelationGraph const& rhs) = delete; + RelationGraph& operator=(RelationGraph&& rhs) = delete; + RelationGraph& operator=(RelationGraph const& rhs) = delete; + + // Graph + using directed_category = boost::bidirectional_tag; + using vertex_descriptor = uint32_t; + using edge_descriptor = impl::EdgeDescriptor; + using edge_parallel_category = boost::allow_parallel_edge_tag; + struct traversal_category // NOLINT + : virtual boost::incidence_graph_tag, + virtual boost::bidirectional_graph_tag, + virtual boost::adjacency_graph_tag, + virtual boost::vertex_list_graph_tag, + virtual boost::edge_list_graph_tag {}; + + constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT + return std::numeric_limits::max(); + } + + // IncidenceGraph + using OutEdge = impl::StoredEdge; + using out_edge_iterator = impl::OutEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + using degree_size_type = uint32_t; + + // BidirectionalGraph + using InEdge = impl::StoredEdge; + using in_edge_iterator = impl::InEdgeIter< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + + // AdjacencyGraph + using adjacency_iterator = boost::adjacency_iterator_generator< + RelationGraph, vertex_descriptor, out_edge_iterator>::type; + + // VertexListGraph + using vertex_iterator = boost::integer_range::iterator; + using vertices_size_type = uint32_t; + + // VertexList help functions + inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].outEdges; + } + inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].outEdges; + } + + inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].inEdges; + } + inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].inEdges; + } + + inline boost::integer_range getVertexList() const noexcept { + return {0, static_cast(_vertices.size())}; + } + + inline vertex_descriptor getCurrentID() const noexcept { + return static_cast(_vertices.size()); + } + + inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { + return ccstd::pmr::vector(_vertices.size(), mr); + } + + // EdgeListGraph + using edge_iterator = impl::DirectedEdgeIterator; + using edges_size_type = uint32_t; + + // ContinuousContainer + void reserve(vertices_size_type sz); + + // Members + struct Vertex { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {outEdges.get_allocator().resource()}; + } + + Vertex(const allocator_type& alloc) noexcept; // NOLINT + Vertex(Vertex&& rhs, const allocator_type& alloc); + Vertex(Vertex const& rhs, const allocator_type& alloc); + + Vertex(Vertex&& rhs) noexcept = default; + Vertex(Vertex const& rhs) = delete; + Vertex& operator=(Vertex&& rhs) = default; + Vertex& operator=(Vertex const& rhs) = default; + + ccstd::pmr::vector outEdges; + ccstd::pmr::vector inEdges; + }; + + struct DescIDTag {}; + + // Vertices + ccstd::pmr::vector _vertices; + // Components + ccstd::pmr::vector descID; + // UuidGraph + PmrUnorderedMap vertexMap; +}; + +struct RenderingInfo { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {clearColors.get_allocator().resource()}; + } + + RenderingInfo(const allocator_type& alloc) noexcept; // NOLINT + RenderingInfo(RenderingInfo&& rhs, const allocator_type& alloc); + RenderingInfo(RenderingInfo const& rhs, const allocator_type& alloc); + + RenderingInfo(RenderingInfo&& rhs) noexcept = default; + RenderingInfo(RenderingInfo const& rhs) = delete; + RenderingInfo& operator=(RenderingInfo&& rhs) = default; + RenderingInfo& operator=(RenderingInfo const& rhs) = default; + + gfx::RenderPassInfo renderpassInfo; + gfx::FramebufferInfo framebufferInfo; + ccstd::pmr::vector clearColors; + float clearDepth{0}; + uint8_t clearStencil{0}; +}; + +struct FrameGraphDispatcher { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {resourceAccessGraph.get_allocator().resource()}; + } + + FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& renderGraphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; + FrameGraphDispatcher(FrameGraphDispatcher&& rhs) = delete; + FrameGraphDispatcher(FrameGraphDispatcher const& rhs) = delete; + FrameGraphDispatcher& operator=(FrameGraphDispatcher&& rhs) = delete; + FrameGraphDispatcher& operator=(FrameGraphDispatcher const& rhs) = delete; + + + void enablePassReorder(bool enable); + + // how much paralell-execution weights during pass reorder, + // eg:0.3 means 30% of effort aim to paralellize execution, other 70% aim to decrease memory using. + // 0 by default + void setParalellWeight(float paralellExecWeight); + + void enableMemoryAliasing(bool enable); + + void run(); + + const BarrierNode& getBarrier(RenderGraph::vertex_descriptor u) const; + + const ResourceAccessNode& getAccessNode(RenderGraph::vertex_descriptor u) const; + + const gfx::RenderPassInfo& getRenderPassInfo(RenderGraph::vertex_descriptor u) const; + + RenderingInfo getRenderPassAndFrameBuffer(RenderGraph::vertex_descriptor u, const ResourceGraph& resg) const; + + LayoutAccess getResourceAccess(ResourceGraph::vertex_descriptor r, RenderGraph::vertex_descriptor p) const; + + // those resource been moved point to another resID + ResourceGraph::vertex_descriptor realResourceID(const ccstd::pmr::string& name) const; + + PmrFlatMap buildDescriptorIndex( + const PmrTransparentMap>&computeViews, + const PmrTransparentMap& rasterViews, + boost::container::pmr::memory_resource* scratch) const; + + PmrFlatMap buildDescriptorIndex( + const PmrTransparentMap>&computeViews, + boost::container::pmr::memory_resource* scratch) const; + + ResourceAccessGraph resourceAccessGraph; + ResourceGraph& resourceGraph; + const RenderGraph& renderGraph; + const LayoutGraphData& layoutGraph; + boost::container::pmr::memory_resource* scratch{nullptr}; + RelationGraph relationGraph; + bool _enablePassReorder{false}; + bool _enableAutoBarrier{true}; + bool _enableMemoryAliasing{false}; + bool _accessGraphBuilt{false}; + float _paralellExecWeight{0.0F}; +}; + +} // namespace render + +} // namespace cc + +// clang-format on diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 1a2cffac76a..6cdd864a2b4 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,7 @@ #include "boost/graph/hawick_circuits.hpp" #include "boost/graph/visitors.hpp" #include "boost/lexical_cast.hpp" +#include "details/GraphView.h" #include "details/Range.h" #include "gfx-base/GFXBarrier.h" #include "gfx-base/GFXDef-common.h" @@ -54,11 +56,20 @@ #include "pipeline/custom/RenderCommonFwd.h" #include "pipeline/custom/RenderGraphTypes.h" #include "pipeline/custom/details/GslUtils.h" +#include "NativeRenderGraphUtils.h" #ifndef BRANCH_CULLING #define BRANCH_CULLING 0 #endif +#define ENABLE_FGD_WARNNING 1 + +#ifdef ENABLE_FGD_WARNNING + #define FGD_WARNING(...) printf(##__VA_ARGS__) +#else + #define FGD_WARNING(...) +#endif + namespace cc { namespace render { @@ -91,35 +102,219 @@ void FrameGraphDispatcher::setParalellWeight(float paralellExecWeight) { _paralellExecWeight = clampf(paralellExecWeight, 0.0F, 1.0F); } -const ResourceAccessNode &FrameGraphDispatcher::getAttachmentStatus(RenderGraph::vertex_descriptor renderGraphVertID) const { - auto iter = resourceAccessGraph.subpassIndex.find(renderGraphVertID); - auto ragVertID = resourceAccessGraph.passIndex.at(renderGraphVertID); - const ResourceAccessNode *accessNode = &resourceAccessGraph.access.at(ragVertID); - if (iter != resourceAccessGraph.subpassIndex.end()) { - auto subpassIndex = iter->second; - accessNode = accessNode->nextSubpass; - CC_ASSERT(accessNode); - while (subpassIndex) { - accessNode = accessNode->nextSubpass; - --subpassIndex; - CC_ASSERT(accessNode); +const BarrierNode &FrameGraphDispatcher::getBarrier(RenderGraph::vertex_descriptor u) const { + auto ragVertID = resourceAccessGraph.passIndex.at(u); + return get(ResourceAccessGraph::BarrierTag{}, resourceAccessGraph, ragVertID); +} + +const ResourceAccessNode &FrameGraphDispatcher::getAccessNode(RenderGraph::vertex_descriptor u) const { + auto ragVertID = resourceAccessGraph.passIndex.at(u); + return get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, ragVertID); +} + +const gfx::RenderPassInfo &FrameGraphDispatcher::getRenderPassInfo(RenderGraph::vertex_descriptor u) const { + CC_EXPECTS(holds(u, renderGraph)); + auto ragVertID = resourceAccessGraph.passIndex.at(u); + return get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, ragVertID).rpInfo; +} + +ResourceGraph::vertex_descriptor FrameGraphDispatcher::realResourceID(const ccstd::pmr::string &name) const { + return resourceAccessGraph.resourceIndex.at(name); +} + +ResourceGraph::vertex_descriptor locateSubres(ResourceGraph::vertex_descriptor resID, const ResourceGraph &resg, std::string_view name) { + auto resName = get(ResourceGraph::NameTag{}, resg, resID); + resName += "/"; + resName += name; + return findVertex(resName, resg); +} + +ResourceGraph::vertex_descriptor locateSubres(ResourceGraph::vertex_descriptor resID, + const ResourceGraph &resg, + uint32_t basePlane) { + auto ret = resID; + const auto &desc = get(ResourceGraph::DescTag{}, resg, resID); + if (desc.format == gfx::Format::DEPTH_STENCIL) { + ret = basePlane == 0 ? locateSubres(resID, resg, DEPTH_PLANE_NAME) : locateSubres(resID, resg, STENCIL_PLANE_NAME); + } + return ret; +} + +PmrFlatMap FrameGraphDispatcher::buildDescriptorIndex( + const PmrTransparentMap> &computeViews, + boost::container::pmr::memory_resource *scratch) const { + PmrFlatMap resourceIndex(scratch); + resourceIndex.reserve(computeViews.size() * 2); + if (!computeViews.empty()) { + for (const auto &[resName, computeViews] : computeViews) { + auto resID = realResourceID(resName); + for (const auto &computeView : computeViews) { + const auto &name = computeView.name; + CC_EXPECTS(!name.empty()); + const auto nameID = layoutGraph.attributeIndex.at(name); + auto subresID = locateSubres(resID, resourceGraph, computeView.plane); + resourceIndex.emplace(nameID, subresID); + } + } + } + return resourceIndex; +} + +PmrFlatMap FrameGraphDispatcher::buildDescriptorIndex( + const PmrTransparentMap> &computeViews, + const PmrTransparentMap &rasterViews, + boost::container::pmr::memory_resource *scratch) const { + + auto resourceIndex = buildDescriptorIndex(computeViews, scratch); + if (!rasterViews.empty()) { + NameLocalID unused{128}; + // input sort by slot name + ccstd::pmr::map> inputs(scratch); + for (const auto &[resourceName, rasterView] : rasterViews) { + if (rasterView.accessType != AccessType::WRITE) { + if (!defaultAttachment(rasterView.slotName)) { + std::string_view suffix = rasterView.attachmentType == AttachmentType::DEPTH_STENCIL ? DEPTH_PLANE_NAME : ""; + inputs.emplace(std::piecewise_construct, + std::forward_as_tuple(rasterView.slotName), + std::forward_as_tuple(resourceName, suffix)); + } + if (!defaultAttachment(rasterView.slotName1)) { + CC_EXPECTS(rasterView.attachmentType == AttachmentType::DEPTH_STENCIL); + std::string_view suffix = STENCIL_PLANE_NAME; + inputs.emplace(std::piecewise_construct, + std::forward_as_tuple(rasterView.slotName1), + std::forward_as_tuple(resourceName, suffix)); + } + } + } + // build pass resources + for (const auto &[slotName, nameInfo] : inputs) { + auto resID = realResourceID(nameInfo.first.data()); + if (!nameInfo.second.empty()) { + resID = locateSubres(resID, resourceGraph, nameInfo.second); + } + resourceIndex.emplace(unused, resID); + unused.value++; } } - return *accessNode; + + return resourceIndex; +} + +RenderingInfo FrameGraphDispatcher::getRenderPassAndFrameBuffer(RenderGraph::vertex_descriptor u, const ResourceGraph &resg) const { + auto ragVertID = resourceAccessGraph.passIndex.at(u); + const auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, ragVertID); + const auto &orderedViews = fgRenderPassInfo.orderedViews; + const auto &viewIndex = fgRenderPassInfo.viewIndex; + + RenderingInfo renderingInfo(scratch); + renderingInfo.renderpassInfo = getRenderPassInfo(u); + gfx::FramebufferInfo fbInfo{ + nullptr, + }; + + CC_ENSURES(holds(u, renderGraph)); + const RasterPass &pass = get(RasterPassTag{}, u, renderGraph); + + for (const auto &viewName : orderedViews) { + const auto &info = viewIndex.at(viewName); + auto attachmentIndex = info.attachmentIndex; + gfx::Color clearColor{}; + if (!info.isResolveView) { + const auto &rasterView = pass.rasterViews.at(viewName); + clearColor = rasterView.clearColor; + } + if (info.attachmentIndex != gfx::INVALID_BINDING) { + // colorLike + renderingInfo.clearColors.emplace_back(clearColor); + + auto resID = resourceAccessGraph.resourceIndex.at(viewName); + visitObject( + resID, resg, + [&](const ManagedResource &res) { + std::ignore = res; + CC_EXPECTS(false); + }, + [&](const ManagedBuffer &res) { + std::ignore = res; + CC_EXPECTS(false); + }, + [&](const ManagedTexture &tex) { + CC_EXPECTS(tex.texture); + fbInfo.colorTextures.emplace_back(tex.texture); + }, + [&](const IntrusivePtr &res) { + std::ignore = res; + CC_EXPECTS(false); + }, + [&](const IntrusivePtr &tex) { + fbInfo.colorTextures.emplace_back(tex); + }, + [&](const IntrusivePtr &fb) { + CC_EXPECTS(fb->getColorTextures().size() == 1); + CC_EXPECTS(fb->getColorTextures().at(0)); + // render window attaches a depthStencil by default, which may differs from renderpassInfo here. + // data.framebuffer = fb; + }, + [&](const RenderSwapchain &sc) { + fbInfo.colorTextures.emplace_back(sc.swapchain->getColorTexture()); + }, + [&](const FormatView &view) { + // TODO(zhouzhenglong): add ImageView support + std::ignore = view; + CC_EXPECTS(false); + }, + [&](const SubresourceView &view) { + fbInfo.colorTextures.emplace_back(view.textureView); + }); + } else { + // ds or ds resolve + if (!info.isResolveView) { + renderingInfo.clearDepth = clearColor.x; + renderingInfo.clearStencil = static_cast(clearColor.y); + } + + auto &dsAttachment = info.isResolveView ? fbInfo.depthStencilResolveTexture : fbInfo.depthStencilTexture; + + auto resID = resourceAccessGraph.resourceIndex.at(viewName); + visitObject( + resID, resg, + [&](const ManagedTexture &tex) { + CC_EXPECTS(tex.texture); + dsAttachment = tex.texture.get(); + }, + [&](const IntrusivePtr &tex) { + dsAttachment = tex.get(); + }, + [&](const FormatView &view) { + std::ignore = view; + CC_EXPECTS(false); + }, + [&](const SubresourceView &view) { + std::ignore = view; + CC_EXPECTS(false); + }, + [](const auto & /*unused*/) { + CC_EXPECTS(false); + }); + } + } + renderingInfo.framebufferInfo = fbInfo; + + return renderingInfo; +} + +LayoutAccess FrameGraphDispatcher::getResourceAccess(ResourceGraph::vertex_descriptor r, RenderGraph::vertex_descriptor p) const { + auto ragVertID = resourceAccessGraph.passIndex.at(p); + const auto &resName = get(ResourceGraph::NameTag{}, resourceGraph, r); + auto range = resourceAccessGraph.resourceAccess.at(resName).equal_range(ragVertID); + return {range.first->second.accessFlag, range.second->second.accessFlag}; } /////////////////////////////////////////////////////////////////////////////////////INTERNAL⚡IMPLEMENTATION///////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------predefine------------------------------------------------------------------ using PmrString = ccstd::pmr::string; -using RAG = ResourceAccessGraph; -using LGD = LayoutGraphData; -using gfx::PassType; -using BarrierMap = FrameGraphDispatcher::BarrierMap; -using AccessVertex = ResourceAccessGraph::vertex_descriptor; -using InputStatusTuple = std::tuple; -using ResourceHandle = ResourceGraph::vertex_descriptor; -using ResourceNames = PmrFlatSet; using EdgeList = std::pair; using CloseCircuit = std::pair; using CloseCircuits = std::vector; @@ -134,30 +329,23 @@ using ResourceLifeRecordMap = PmrFlatMap; struct Graphs { const RenderGraph &renderGraph; - ResourceGraph &resourceGraph; const LayoutGraphData &layoutGraphData; + ResourceGraph &resourceGraph; ResourceAccessGraph &resourceAccessGraph; RelationGraph &relationGraph; }; struct ViewStatus { - PmrString name; - const PassType passType; + const ccstd::pmr::string &name; + const AccessType access; const gfx::ShaderStageFlagBit visibility; - const gfx::MemoryAccessBit access; const gfx::AccessFlags accessFlag; - const ResourceUsage usage; + const ResourceRange ⦥ }; -auto defaultAccess = gfx::MemoryAccessBit::NONE; -auto defaultVisibility = gfx::ShaderStageFlagBit::NONE; - constexpr uint32_t EXPECT_START_ID = 0; constexpr uint32_t INVALID_ID = 0xFFFFFFFF; -using AccessTable = PmrFlatMap; -using ExternalResMap = PmrFlatMap; - // for scoped enum only template class GfxTypeConverter { @@ -168,39 +356,11 @@ class GfxTypeConverter { } }; -// static auto toGfxAccess = GfxTypeConverter(); -gfx::MemoryAccessBit toGfxAccess(AccessType type) { - switch (type) { - case AccessType::READ: - return gfx::MemoryAccessBit::READ_ONLY; - case AccessType::WRITE: - return gfx::MemoryAccessBit::WRITE_ONLY; - case AccessType::READ_WRITE: - return gfx::MemoryAccessBit::READ_WRITE; - default: - return gfx::MemoryAccessBit::NONE; - } -}; - // TODO(Zeqiang): remove barrier in renderpassinfo gfx::GeneralBarrier *getGeneralBarrier(gfx::Device *device, gfx::AccessFlagBit prevAccess, gfx::AccessFlagBit nextAccess) { return device->getGeneralBarrier({prevAccess, nextAccess}); } -// AccessStatus.vertID : in resourceNode it's resource ID; in barrierNode it's pass ID. -AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGraph &rg, const ViewStatus &status); -gfx::ShaderStageFlagBit getVisibilityByDescName(const RenderGraph &renderGraph, const LGD &lgd, uint32_t passID, const PmrString &resName); - -PmrString addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status); -void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range); -void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass); -void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass); -void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSubpass &pass); -void processComputeSubpass(const Graphs &graphs, uint32_t passID, const ComputeSubpass &pass); -void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass); -void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass); -auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph, bool rasterized); - // execution order BUT NOT LOGICALLY bool isPassExecAdjecent(uint32_t passLID, uint32_t passRID) { return std::abs(static_cast(passLID) - static_cast(passRID)) <= 1; @@ -235,11 +395,21 @@ inline bool isAttachmentAccess(gfx::AccessFlagBit flag) { gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE); } +// SHADING_RATE may be ambiguos inline bool isReadOnlyAccess(gfx::AccessFlagBit flag) { - return flag < gfx::AccessFlagBit::PRESENT || flag == gfx::AccessFlagBit::SHADING_RATE; + return static_cast(flag) < static_cast(gfx::AccessFlagBit::PRESENT) || flag == gfx::AccessFlagBit::SHADING_RATE; +} + +bool accessDependent(const gfx::AccessFlagBit lhs, const gfx::AccessFlagBit &rhs, bool buffer) { + bool dep{false}; + if (buffer) { + dep = !isReadOnlyAccess(lhs) || !isReadOnlyAccess(rhs); + } else { + dep = (!isReadOnlyAccess(lhs) || !isReadOnlyAccess(rhs)) || (lhs != rhs); + } + return dep; } -bool isTransitionStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs); template bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph); @@ -249,2362 +419,2006 @@ inline RelationGraph::vertex_descriptor add_vertex(RelationGraph &g) { // NOLINT return add_vertex(g, count++); } -// status of resource access -void buildAccessGraph(const Graphs &graphs) { - // what we need: - // - pass dependency - // - pass attachment access - // AccessTable accessRecord; +bool isResourceView(const ResourceGraph::vertex_descriptor v, const ResourceGraph &resg) { + return resg.isTextureView(v); // || isBufferView +} - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - size_t numPasses = 0; - numPasses += renderGraph.rasterPasses.size(); - numPasses += renderGraph.computePasses.size(); - numPasses += renderGraph.copyPasses.size(); - numPasses += renderGraph.movePasses.size(); - numPasses += renderGraph.raytracePasses.size(); +ResourceRange getResourceRange(const ResourceGraph::vertex_descriptor v, + const ResourceGraph &resg) { + const auto &desc = get(ResourceGraph::DescTag{}, resg, v); + ResourceRange range{ + desc.width, + desc.height, + desc.depthOrArraySize, + }; - resourceAccessGraph.reserve(static_cast(numPasses)); - resourceAccessGraph.resourceNames.reserve(128); - resourceAccessGraph.resourceIndex.reserve(128); + if (isResourceView(v, resg)) { + const auto *const subResView = get_if(v, &resg); + range.firstSlice = subResView->firstArraySlice; + range.numSlices = subResView->numArraySlices; + range.mipLevel = subResView->indexOrFirstMipLevel; + range.levelCount = subResView->numMipLevels; + range.basePlane = subResView->firstPlane; + range.planeCount = subResView->numPlanes; + } else { + range.numSlices = desc.depthOrArraySize; + range.levelCount = desc.mipLevels; + } - resourceAccessGraph.topologicalOrder.reserve(numPasses); - resourceAccessGraph.topologicalOrder.clear(); - resourceAccessGraph.resourceLifeRecord.reserve(resourceGraph.names.size()); + return range; +} - if (!resourceAccessGraph.resourceLifeRecord.empty()) { - resourceAccessGraph.resourceLifeRecord.clear(); +ResourceGraph::vertex_descriptor realID(const ccstd::pmr::string &name, const ResourceGraph &resg) { + auto resID = vertex(name, resg); + while (parent(resID, resg) != ResourceGraph::null_vertex()) { + resID = parent(resID, resg); } + return resID; +} - if (!resourceAccessGraph.leafPasses.empty()) { - resourceAccessGraph.leafPasses.clear(); - } - if (!resourceAccessGraph.culledPasses.empty()) { - resourceAccessGraph.culledPasses.clear(); - } +bool depthStencil(gfx::Format format) { + return format == gfx::Format::DEPTH_STENCIL || format == gfx::Format::DEPTH; +} - // const auto &names = get(RenderGraph::Name, renderGraph); - for (size_t i = 1; i <= numPasses; ++i) { - resourceAccessGraph.leafPasses.emplace(i, LeafStatus{false, true}); +void subResourceFeedback(ResourceGraph &resg, ResourceGraph::vertex_descriptor parentID, gfx::Format subFormat) { + auto &parentDesc = get(ResourceGraph::DescTag{}, resg, parentID); + if (depthStencil(subFormat) || parentDesc.format != subFormat) { + parentDesc.textureFlags |= gfx::TextureFlagBit::MUTABLE_VIEW_FORMAT; } +} - auto startID = add_vertex(resourceAccessGraph, INVALID_ID - 1); - CC_EXPECTS(startID == EXPECT_START_ID); - - add_vertex(relationGraph, startID); +auto dependencyCheck(ResourceAccessGraph &rag, ResourceAccessGraph::vertex_descriptor curVertID, ResourceGraph &resourceGraph, const ViewStatus &viewStatus) { + auto &accessRecord = rag.resourceAccess; + const auto &[name, access, visibility, accessFlag, originRange] = viewStatus; + auto resourceID = rag.resourceIndex.at(name); + const auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, resourceID); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resourceID); - for (const auto passID : makeRange(vertices(renderGraph))) { - visitObject( - passID, renderGraph, - [&](const RasterPass &pass) { - processRasterPass(graphs, passID, pass); - }, - [&](const RasterSubpass &pass) { - processRasterSubpass(graphs, passID, pass); - }, - [&](const ComputeSubpass &pass) { - processComputeSubpass(graphs, passID, pass); - }, - [&](const ComputePass &pass) { - processComputePass(graphs, passID, pass); - }, - [&](const CopyPass &pass) { - processCopyPass(graphs, passID, pass); - }, - [&](const RaytracePass &pass) { - processRaytracePass(graphs, passID, pass); - }, - [&](const auto & /*pass*/) { - // do nothing - }); + auto range = originRange; + if (rag.movedSourceStatus.find(name) != rag.movedSourceStatus.end()) { + range = rag.movedSourceStatus.at(name).range; } - auto &rag = resourceAccessGraph; - auto branchCulling = [](ResourceAccessGraph::vertex_descriptor vertex, ResourceAccessGraph &rag) -> void { - CC_EXPECTS(out_degree(vertex, rag) == 0); - using FuncType = void (*)(ResourceAccessGraph::vertex_descriptor, ResourceAccessGraph &); - static FuncType leafCulling = [](ResourceAccessGraph::vertex_descriptor vertex, ResourceAccessGraph &rag) { - rag.culledPasses.emplace(vertex); - auto &attachments = get(ResourceAccessGraph::AccessNodeTag{}, rag, vertex); - attachments.attachmentStatus.clear(); - if (attachments.nextSubpass) { - delete attachments.nextSubpass; - attachments.nextSubpass = nullptr; - } - auto inEdges = in_edges(vertex, rag); - for (auto iter = inEdges.first; iter < inEdges.second;) { - auto inEdge = *iter; - auto srcVert = source(inEdge, rag); - remove_edge(inEdge, rag); - if (out_degree(srcVert, rag) == 0) { - leafCulling(srcVert, rag); - } - inEdges = in_edges(vertex, rag); - iter = inEdges.first; - } - }; - leafCulling(vertex, rag); - }; + bool isExternalPass = get(get(ResourceGraph::TraitsTag{}, resourceGraph), resourceID).hasSideEffects(); + auto iter = accessRecord.find(name); + ResourceAccessGraph::vertex_descriptor lastVertID{EXPECT_START_ID}; + gfx::AccessFlagBit lastAccess{gfx::AccessFlagBit::NONE}; - // no present pass found, add a fake node to gather leaf node(s). - if (resourceAccessGraph.presentPassID == 0xFFFFFFFF) { - auto ragEndNode = add_vertex(rag, RenderGraph::null_vertex()); - auto rlgEndNode = add_vertex(relationGraph, ragEndNode); - // keep sync before pass reorder done. - CC_EXPECTS(ragEndNode == rlgEndNode); - resourceAccessGraph.presentPassID = ragEndNode; - auto iter = resourceAccessGraph.leafPasses.find(ragEndNode); - constexpr bool isExternal = true; - constexpr bool needCulling = false; - if (iter == resourceAccessGraph.leafPasses.end()) { - resourceAccessGraph.leafPasses.emplace(ragEndNode, LeafStatus{isExternal, needCulling}); + if (iter == accessRecord.end()) { + accessRecord[name].emplace(curVertID, AccessStatus{accessFlag, range}); + if (isExternalPass) { + rag.leafPasses[curVertID] = LeafStatus{true, isReadOnlyAccess(accessFlag)}; + lastAccess = states.states; + } + + // update parent + auto parentID = realID(name, resourceGraph); + if (parentID != resourceID) { + const auto &realName = get(ResourceGraph::NameTag{}, resourceGraph, parentID); + auto lastIter = accessRecord[realName].rbegin(); + if (lastIter->first == curVertID) { + // in case more than 1 view of same resource in a renderpass + ++lastIter; + } + accessRecord[name].emplace(*lastIter); + accessRecord[realName][curVertID] = AccessStatus{accessFlag, range}; + subResourceFeedback(resourceGraph, parentID, desc.format); } else { - resourceAccessGraph.leafPasses.at(ragEndNode) = LeafStatus{isExternal, needCulling}; + accessRecord[name].emplace(0, AccessStatus{lastAccess, range}); } - } + } else { + auto &transMap = iter->second; + CC_ASSERT(!transMap.empty()); - // make leaf node closed walk for pass reorder - for (auto pass : resourceAccessGraph.leafPasses) { - bool isExternal = pass.second.isExternal; - bool needCulling = pass.second.needCulling; + const auto lastRecordIter = (--transMap.end()); + const auto &lastStatus = lastRecordIter->second; + lastAccess = lastStatus.accessFlag; + bool isBuffer = desc.dimension == ResourceDimension::BUFFER; + bool dependent = accessDependent(lastAccess, accessFlag, isBuffer); - if (pass.first != resourceAccessGraph.presentPassID) { - if (isExternal && !needCulling) { - add_edge(pass.first, resourceAccessGraph.presentPassID, resourceAccessGraph); - } else { - // write into transient resources, culled - if constexpr (ENABLE_BRANCH_CULLING) { - branchCulling(pass.first, resourceAccessGraph); + if (!dependent) { + for (auto recordIter = transMap.rbegin(); recordIter != transMap.rend(); ++recordIter) { + if (accessDependent(recordIter->second.accessFlag, accessFlag, isBuffer)) { + lastVertID = recordIter->first; + break; } } - } - } - for (auto rit = resourceAccessGraph.culledPasses.rbegin(); rit != resourceAccessGraph.culledPasses.rend(); ++rit) { - // remove culled vertices, std::less make this set ascending order, so reverse iterate - remove_vertex(*rit, relationGraph); - } - - for (auto rlgVert : makeRange(vertices(relationGraph))) { - auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, rlgVert); - rag.topologicalOrder.emplace_back(ragVert); - } -} + if (isExternalPass) { + // only external res will be manually record here, leaf pass with transient resource will be culled by default, + // those leaf passes with ALL read access on external(or with transients) res can be culled. + rag.leafPasses[curVertID].needCulling &= (access == AccessType::READ); + lastAccess = states.states; + } + transMap[curVertID] = {accessFlag, range}; + } else { + lastVertID = lastRecordIter->first; + transMap[curVertID] = {accessFlag, range}; -#pragma region BUILD_BARRIERS -struct BarrierVisitor : public boost::bfs_visitor<> { - using Vertex = ResourceAccessGraph::vertex_descriptor; - using Edge = ResourceAccessGraph::edge_descriptor; - using Graph = ResourceAccessGraph; - - explicit BarrierVisitor( - const ResourceGraph &rg, - BarrierMap &barriers, // what we get - ExternalResMap &extMap, // record external res between frames - ResourceNames &resourceNamesIn, // for resource record - const AccessTable &accessRecordIn, // resource last meet - ResourceLifeRecordMap &rescLifeRecord, // resource lifetime - PmrFlatMap &rpInfosIn) - : barrierMap(barriers), resourceGraph(rg), externalMap(extMap), resourceNames(resourceNamesIn), accessRecord(accessRecordIn), resourceLifeRecord(rescLifeRecord), rpInfos(rpInfosIn) {} - - void updateResourceLifeTime(const ResourceAccessNode &node, ResourceAccessGraph::vertex_descriptor u) { - for (const auto &access : node.attachmentStatus) { - auto name = get(ResourceGraph::NameTag{}, resourceGraph, access.vertID); - if (resourceLifeRecord.find(name) == resourceLifeRecord.end()) { - resourceLifeRecord.emplace(name, ResourceLifeRecord{u, u}); - } else { - resourceLifeRecord.at(name).end = u; + if (rag.leafPasses.find(curVertID) != rag.leafPasses.end()) { + // only write into externalRes counts + if (isExternalPass) { + rag.leafPasses[curVertID].needCulling &= (access == AccessType::READ); + } } } - } - - struct AccessNodeInfo { - const std::vector &status; - std::vector &edgeBarriers; // need to barrier front or back - const Vertex &vertID; - uint32_t subpassIndex{INVALID_ID}; - }; - void processVertex(Vertex u, const Graph &g) { - if (in_degree(u, g) == 0 && out_degree(u, g) == 0) { - // culled - return; + if (rag.leafPasses.find(lastVertID) != rag.leafPasses.end()) { + rag.leafPasses.erase(lastVertID); } - const ResourceAccessNode &access = get(ResourceAccessGraph::AccessNodeTag{}, g, u); - updateResourceLifeTime(access, u); - - if (barrierMap.find(u) == barrierMap.end()) { - barrierMap.emplace(u, BarrierNode{{}, {}}); + if(viewStatus.access != AccessType::WRITE) { + subResourceFeedback(resourceGraph, resourceID, desc.format); } + } + auto lastDependentVert = lastVertID; // last dependent vert, WAW/WAR/RAW + auto nearestAccess = lastAccess; // last access, maybe RAR + return std::make_tuple(lastDependentVert, nearestAccess); +} - const auto *srcAccess = &access; - - auto *dstAccess = access.nextSubpass; - auto &blockBarrier = barrierMap[u].blockBarrier; - auto &barriers = barrierMap[u].subpassBarriers; - - uint32_t srcSubpass = 0; - uint32_t dstSubpass = 1; - bool isAdjacent = true; // subpass always adjacent to each other - if (dstAccess) { - if (!dstAccess->nextSubpass) { - return; - } - // subpass at least two passes inside. - // the very first pass becomes attachment status collection of all subpass - CC_ASSERT(dstAccess->nextSubpass); - srcAccess = dstAccess; - dstAccess = dstAccess->nextSubpass; - } - while (srcAccess) { - while (dstAccess) { - // 2 barriers at least when subpass exist - std::vector &srcRearBarriers = barriers[srcSubpass].rearBarriers; - std::vector &dstFrontBarriers = barriers[dstSubpass].frontBarriers; - - AccessNodeInfo from = {srcAccess->attachmentStatus, srcRearBarriers, u, srcSubpass}; - AccessNodeInfo to = {dstAccess->attachmentStatus, dstFrontBarriers, u, dstSubpass}; - std::set noUseSet; - fillBarrier(from, to, isAdjacent, noUseSet); - - dstAccess = dstAccess->nextSubpass; - ++dstSubpass; - } - srcAccess = srcAccess->nextSubpass; - if (srcAccess) { - dstAccess = srcAccess->nextSubpass; - ++srcSubpass; - dstSubpass = srcSubpass + 1; - } +ResourceGraph::vertex_descriptor parentResource(ResourceGraph::vertex_descriptor vert, const ResourceGraph &resg) { + const auto &desc = get(ResourceGraph::DescTag{}, resg, vert); + auto ret = vert; + if (desc.dimension == ResourceDimension::BUFFER) { + // TODO(Zeqaing): bufferview + } else { + auto srcParentID = vert; + while (resg.isTextureView(srcParentID)) { + srcParentID = parent(srcParentID, resg); } + ret = srcParentID; } + return ret; +} - void discover_vertex(Vertex u, const Graph &g) { - processVertex(u, g); - } - - void finish_vertex(Vertex u, const Graph &g) { - auto &rearBarriers = barrierMap[u].blockBarrier.rearBarriers; - auto &frontBarriers = barrierMap[u].blockBarrier.frontBarriers; - Barrier *lastSubpassBarrier = nullptr; - uint32_t subpassIdx{0}; - for (const auto &barriers : barrierMap[u].subpassBarriers) { - if (!barriers.frontBarriers.empty()) { - auto &subpassDependencies = rpInfos.at(u).rpInfo.dependencies; - auto dependency = gfx::SubpassDependency{}; - dependency.srcSubpass = INVALID_ID; - dependency.dstSubpass = subpassIdx; - for (const auto &barrier : barriers.frontBarriers) { - if (barrier.beginStatus.accessFlag == gfx::AccessFlagBit::NONE) { - continue; - } - auto resID = barrier.resourceID; - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; - auto firstMeetIter = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID); - auto innerResIter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); - - if (firstMeetIter == frontBarriers.end() && innerResIter == rearBarriers.end() && resFinalPassID >= u) { - auto &collect = frontBarriers.emplace_back(barrier); - collect.beginStatus.vertID = collect.endStatus.vertID = u; - } - if ((barrier.beginStatus.vertID > dependency.srcSubpass) && (barrier.beginStatus.vertID != INVALID_ID)) { - dependency.srcSubpass = barrier.beginStatus.vertID; - } - - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); - if (desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH) { - if (g.access.at(u).attachmentStatus.size() > 1) { - auto &dsDep = subpassDependencies.emplace_back(); - dsDep.srcSubpass = dependency.srcSubpass; - dsDep.dstSubpass = dependency.dstSubpass; - dsDep.prevAccesses |= barrier.beginStatus.accessFlag; - dsDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - bool isWriteAccess = !isReadOnlyAccess(barrier.endStatus.accessFlag); - if (isWriteAccess) { - auto &dep = subpassDependencies.emplace_back(); - dep.srcSubpass = dependency.srcSubpass; - dep.dstSubpass = dependency.dstSubpass; - dep.prevAccesses |= barrier.beginStatus.accessFlag; - dep.nextAccesses |= barrier.endStatus.accessFlag; - if (hasReadAccess(barrier.endStatus.accessFlag)) { - auto &selfDep = subpassDependencies.emplace_back(); - selfDep.srcSubpass = dependency.dstSubpass; - selfDep.dstSubpass = dependency.dstSubpass; - selfDep.prevAccesses |= barrier.endStatus.accessFlag; - selfDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - dependency.prevAccesses |= barrier.beginStatus.accessFlag; - dependency.nextAccesses |= barrier.endStatus.accessFlag; - } - } - } - if (dependency.prevAccesses != gfx::AccessFlagBit::NONE) { - subpassDependencies.emplace_back(dependency); - } - } - - if (!barriers.rearBarriers.empty()) { - auto &subpassDependencies = rpInfos.at(u).rpInfo.dependencies; - auto dependency = gfx::SubpassDependency{}; - dependency.srcSubpass = subpassIdx; - dependency.dstSubpass = INVALID_ID; - for (const auto &barrier : barriers.rearBarriers) { - if (barrier.endStatus.vertID < dependency.dstSubpass) { - dependency.dstSubpass = barrier.endStatus.vertID; - } +gfx::ShaderStageFlagBit getVisibility(const RenderGraph &renderGraph, const LayoutGraphData &lgd, uint32_t passID, const PmrString &resName) { // NOLINT + auto iter = lgd.attributeIndex.find(resName); + if (iter == lgd.attributeIndex.end()) { + iter = lgd.constantIndex.find(resName); + if (iter == lgd.constantIndex.end()) { + // resource not in descriptor: eg. input or output attachment. + return gfx::ShaderStageFlagBit::NONE; + } + } + auto slotID = iter->second; - auto resID = barrier.resourceID; - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); - if (desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH) { - if (g.access.at(u).attachmentStatus.size() > 1) { - auto &dsDep = subpassDependencies.emplace_back(); - dsDep.srcSubpass = dependency.srcSubpass; - dsDep.dstSubpass = dependency.dstSubpass; - dsDep.prevAccesses |= barrier.beginStatus.accessFlag; - dsDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - bool isWriteAccess = !isReadOnlyAccess(barrier.endStatus.accessFlag); - if (isWriteAccess) { - auto &dep = subpassDependencies.emplace_back(); - dep.srcSubpass = dependency.srcSubpass; - dep.dstSubpass = dependency.dstSubpass; - dep.prevAccesses |= barrier.beginStatus.accessFlag; - dep.nextAccesses |= barrier.endStatus.accessFlag; - if (hasReadAccess(barrier.endStatus.accessFlag)) { - auto &selfDep = subpassDependencies.emplace_back(); - selfDep.srcSubpass = dependency.dstSubpass; - selfDep.dstSubpass = dependency.dstSubpass; - selfDep.prevAccesses |= barrier.endStatus.accessFlag; - selfDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - dependency.prevAccesses |= barrier.beginStatus.accessFlag; - dependency.nextAccesses |= barrier.endStatus.accessFlag; - } - } - } - if (dependency.prevAccesses != gfx::AccessFlagBit::NONE) { - subpassDependencies.emplace_back(dependency); + auto layoutName = get(RenderGraph::LayoutTag{}, renderGraph, passID); + auto layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lgd); + const auto &layout = get(LayoutGraphData::LayoutTag{}, lgd, layoutID); + for (const auto &pair : layout.descriptorSets) { + for (const auto &block : pair.second.descriptorSetLayoutData.descriptorBlocks) { + for (const auto &descriptor : block.descriptors) { + if (descriptor.descriptorID.value == slotID.value) { + return block.visibility; } } - ++subpassIdx; } } + // unreachable + CC_EXPECTS(false); - void fillBarrier(const AccessNodeInfo &from, const AccessNodeInfo &to, bool isAdjacent, std::set &subpassResourceSet) { - const auto &[srcStatus, srcRearBarriers, srcPassVert, srcHasSubpass] = from; - const auto &[dstStatus, dstFrontBarriers, dstPassVert, dstHasSubpass] = to; - auto srcVert = srcPassVert; - auto dstVert = dstPassVert; - bool subToSubDeps = false; - if (srcPassVert == dstPassVert) { - srcVert = srcHasSubpass; - dstVert = dstHasSubpass; - subToSubDeps = true; - } - - bool dstExternalDeps = (srcHasSubpass != INVALID_ID) && (dstHasSubpass == INVALID_ID); - bool srcExternalDeps = (srcHasSubpass == INVALID_ID) && (dstHasSubpass != INVALID_ID); - - std::vector commonResources; - std::set_intersection(srcStatus.begin(), srcStatus.end(), - dstStatus.begin(), dstStatus.end(), - std::back_inserter(commonResources), - [](const AccessStatus &lhs, const AccessStatus &rhs) { - return lhs.vertID < rhs.vertID; - }); - if (!commonResources.empty()) { - // this edge is a logic edge added during pass reorder, - // no real dependency between this two vertices. - - // NOLINTNEXTLINE - for (uint32_t i = 0; i < commonResources.size(); ++i) { - uint32_t resourceID = commonResources[i].vertID; - if (subpassResourceSet.find(resourceID) != subpassResourceSet.end()) { - continue; - } - subpassResourceSet.emplace(resourceID); - auto findAccessByID = [resourceID](const AccessStatus &resAccess) { return resAccess.vertID == resourceID; }; - auto fromIter = std::find_if(srcStatus.begin(), srcStatus.end(), findAccessByID); - auto toIter = std::find_if(dstStatus.begin(), dstStatus.end(), findAccessByID); + return gfx::ShaderStageFlagBit::NONE; +}; - // can't happen - CC_ASSERT(fromIter != srcStatus.end()); - CC_ASSERT(toIter != dstStatus.end()); +gfx::MemoryAccessBit toGfxAccess(AccessType type) { + switch (type) { + case AccessType::READ: + return gfx::MemoryAccessBit::READ_ONLY; + case AccessType::WRITE: + return gfx::MemoryAccessBit::WRITE_ONLY; + case AccessType::READ_WRITE: + return gfx::MemoryAccessBit::READ_WRITE; + default: + return gfx::MemoryAccessBit::NONE; + } +}; - if (!isTransitionStatusDependent(*fromIter, *toIter)) { - continue; - } - - auto findBarrierNodeByResID = [resourceID](const Barrier &barrier) { return resourceID == barrier.resourceID; }; +auto mapTextureFlags(ResourceFlags flags) { + gfx::TextureUsage usage = gfx::TextureUsage::NONE; + if ((flags & ResourceFlags::SAMPLED) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::SAMPLED; + } + if ((flags & ResourceFlags::STORAGE) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::STORAGE; + } + if ((flags & ResourceFlags::SHADING_RATE) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::SHADING_RATE; + } + if ((flags & ResourceFlags::COLOR_ATTACHMENT) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::COLOR_ATTACHMENT; + } + if ((flags & ResourceFlags::DEPTH_STENCIL_ATTACHMENT) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; + } + if ((flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::INPUT_ATTACHMENT; + } + return usage; +} - auto srcBarrierIter = srcRearBarriers.empty() ? srcRearBarriers.end() : std::find_if(srcRearBarriers.begin(), srcRearBarriers.end(), findBarrierNodeByResID); - auto dstBarrierIter = dstFrontBarriers.empty() ? dstFrontBarriers.end() : std::find_if(dstFrontBarriers.begin(), dstFrontBarriers.end(), findBarrierNodeByResID); +auto getTextureStatus(std::string_view name, AccessType access, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph, bool rasterized) { + gfx::ShaderStageFlags vis{visibility}; + if (vis == gfx::ShaderStageFlags::NONE) { + // attachment + vis = gfx::ShaderStageFlagBit::FRAGMENT; + } + gfx::AccessFlags accesFlag; + auto vertex = resourceGraph.valueIndex.at(name.data()); - auto dstVertDistribute = [&](uint32_t &vertID, bool depends) { - if (depends) { - vertID = INVALID_ID; - } else if (subToSubDeps) { - vertID = dstVert; - } else { - vertID = isAdjacent ? srcVert : dstVert; - } - }; - if (srcBarrierIter == srcRearBarriers.end()) { - auto srcAccess = (*fromIter); - srcAccess.vertID = dstExternalDeps ? INVALID_ID : srcVert; - auto dstAccess = (*toIter); - dstVertDistribute(dstAccess.vertID, dstExternalDeps); - - srcRearBarriers.emplace_back(Barrier{ - resourceID, - isAdjacent ? gfx::BarrierType::FULL : gfx::BarrierType::SPLIT_BEGIN, - nullptr, // generate later - srcAccess, - dstAccess, - }); - srcBarrierIter = std::prev(srcRearBarriers.end()); - } else { - if (isAdjacent) { - srcBarrierIter->type = gfx::BarrierType::FULL; - auto srcAccess = (*fromIter); - srcAccess.vertID = dstExternalDeps ? INVALID_ID : srcVert; - srcBarrierIter->beginStatus = srcAccess; - auto dstAccess = (*toIter); - dstVertDistribute(dstAccess.vertID, dstExternalDeps); - srcBarrierIter->endStatus = dstAccess; - } else { - auto &blockBarrier = barrierMap.at(srcPassVert).blockBarrier; - auto lastVert = srcBarrierIter->beginStatus.vertID; - auto blockIter = blockBarrier.rearBarriers.end(); - if (subToSubDeps) { - blockIter = std::find_if(blockBarrier.rearBarriers.begin(), blockBarrier.rearBarriers.end(), findBarrierNodeByResID); - lastVert = blockIter->beginStatus.vertID; - } - if (srcVert >= lastVert) { - auto srcAccess = (*fromIter); - srcAccess.vertID = srcVert; - if (blockIter != blockBarrier.rearBarriers.end()) { - blockIter->beginStatus = srcAccess; - } - - uint32_t siblingPass = lastVert; - if (srcVert > lastVert) { - auto &siblingPassBarrier = barrierMap[siblingPass].blockBarrier.rearBarriers; - auto siblingIter = std::find_if(siblingPassBarrier.begin(), siblingPassBarrier.end(), - [resourceID](const Barrier &barrier) { - return resourceID == barrier.resourceID; - }); - CC_ASSERT(siblingIter != siblingPassBarrier.end()); - siblingPassBarrier.erase(siblingIter); - } - } - } - } + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex); - if (srcBarrierIter->type == gfx::BarrierType::SPLIT_BEGIN) { - auto srcAccess = (*fromIter); - srcAccess.vertID = srcExternalDeps ? INVALID_ID : srcVert; - auto dstAccess = (*toIter); - dstVertDistribute(dstAccess.vertID, dstExternalDeps); - if (dstBarrierIter == dstFrontBarriers.end()) { - // if isAdjacent, full barrier already in src rear barriers. - if (!isAdjacent) { - dstFrontBarriers.emplace_back(Barrier{ - resourceID, - gfx::BarrierType::SPLIT_END, - nullptr, - srcAccess, - dstAccess, - }); - } - } else { - if (isAdjacent) { - // adjacent, barrier should be commit at fromPass, and remove this iter from dstBarriers - srcBarrierIter->type = gfx::BarrierType::FULL; - srcBarrierIter->beginStatus = srcAccess; - srcBarrierIter->endStatus = dstAccess; - dstFrontBarriers.erase(dstBarrierIter); - } else { - // logic but not exec adjacent - // and more adjacent(distance from src) than another pass which hold a use of resourceID - // replace previous one - - // 1 --> 2 --> 3 - // ↓ - // 4 --> 5 --> 6 - - // [if] real pass order: 1 - 2 - 4 - 5 - 3 - 6 - - // 2 and 5 read from ResA, 6 writes to ResA - // 5 and 6 logically adjacent but not adjacent in execution order. - // barrier for ResA between 2 - 6 can be totally replaced by 5 - 6 - auto &blockBarrier = barrierMap.at(dstPassVert).blockBarrier; - auto blockIter = blockBarrier.frontBarriers.end(); - auto lastVert = dstBarrierIter->endStatus.vertID; - if (subToSubDeps) { - blockIter = std::find_if(blockBarrier.frontBarriers.begin(), blockBarrier.frontBarriers.end(), findBarrierNodeByResID); - lastVert = blockIter->endStatus.vertID; - } - if (dstVert <= lastVert) { - uint32_t siblingPass = lastVert; - dstBarrierIter->endStatus = dstAccess; - - // remove the further redundant barrier - auto &siblingPassBarrier = barrierMap[siblingPass].blockBarrier.frontBarriers; - auto siblingIter = std::find_if(siblingPassBarrier.begin(), siblingPassBarrier.end(), - [resourceID](const Barrier &barrier) { - return resourceID == barrier.resourceID; - }); - CC_ASSERT(siblingIter != siblingPassBarrier.end()); - siblingPassBarrier.erase(siblingIter); - } - } - } - } - } + // can't find this resource in layoutdata, should be output attachment. + gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; + if (access != AccessType::WRITE) { + if ((desc.flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE && rasterized) { + texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::INPUT_ATTACHMENT)); + } else { + texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::SAMPLED | gfx::TextureUsage::STORAGE | gfx::TextureUsage::SHADING_RATE | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT)); } + } - //----------------------------------------------check external---------------------------------------------- - auto barrierExternalRes = [&](const AccessStatus &resourcecAccess, Vertex vert) { - uint32_t rescID = resourcecAccess.vertID; - const auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, rescID); - const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, rescID); - const PmrString &resName = get(ResourceGraph::NameTag{}, resourceGraph, rescID); - auto resIter = externalMap.find(resName); - if (traits.hasSideEffects()) { - // first meet in this frame - if (resIter == externalMap.end()) { - // first meet in this program - if (states.states == gfx::AccessFlagBit::NONE) { - auto lastRescAccess = AccessStatus{ - vert, - gfx::ShaderStageFlagBit::NONE, - gfx::MemoryAccessBit::NONE, - gfx::PassType::RASTER, - gfx::AccessFlagBit::NONE, - gfx::TextureUsageBit::NONE, - TextureRange{}, - }; - auto currRescAccess = resourcecAccess; - - // resource id in access -> pass id in barrier - currRescAccess.vertID = vert; - - lastRescAccess.accessFlag = gfx::AccessFlagBit::NONE; - - externalMap.insert({resName, - ResourceTransition{ - lastRescAccess, - currRescAccess, - }}); - } else { - externalMap[resName].lastStatus = {}; - externalMap[resName].lastStatus.vertID = INVALID_ID; - externalMap[resName].lastStatus.accessFlag = states.states; - // deprecated - externalMap[resName].lastStatus.usage = gfx::TextureUsageBit::NONE; - externalMap[resName].lastStatus.range = TextureRange{}; - - externalMap[resName].currStatus = resourcecAccess; - externalMap[resName].currStatus.vertID = vert; - - const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, rescID); - if (isTransitionStatusDependent(externalMap[resName].lastStatus, externalMap[resName].currStatus)) { - resourceNames.emplace(resName); - } - } - } else { - if (resIter->second.currStatus.vertID < vert) { - //[pass: vert] is later access than in iter. - externalMap[resName].currStatus = resourcecAccess; - externalMap[resName].currStatus.vertID = vert; - if (!isReadOnlyAccess(resourcecAccess.accessFlag)) { - resourceNames.emplace(resName); - } - } - } - } - }; + if (access != AccessType::READ) { + texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::STORAGE)); + } + accesFlag = gfx::getAccessFlags(texUsage, toGfxAccess(access), vis); - for (const AccessStatus &rescAccess : srcStatus) { - barrierExternalRes(rescAccess, from.vertID); - } + return std::make_tuple(vis, accesFlag); +}; - for (const AccessStatus &rescAccess : dstStatus) { - barrierExternalRes(rescAccess, to.vertID); - } - //--------------------------------------------------------------------------------------------------------- +auto getBufferStatus(const PmrString &name, AccessType access, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph) { + gfx::AccessFlags accesFlag; + auto vertex = resourceGraph.valueIndex.at(name); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex); + + gfx::BufferUsage bufferUsage{gfx::BufferUsage::NONE}; + // copy is not included in this logic because copy can be set TRANSFER_xxx directly. + if (access != AccessType::READ) { + bufferUsage = gfx::BufferUsage::STORAGE; } - void examine_edge(Edge e, const Graph &g) { - Vertex from = source(e, g); - Vertex to = target(e, g); + if (access != AccessType::WRITE) { + bool uniformFlag = (desc.flags & ResourceFlags::UNIFORM) != ResourceFlags::NONE; + bool storageFlag = (desc.flags & ResourceFlags::STORAGE) != ResourceFlags::NONE; - // hasSubpass ? fromAccess is a single node with all attachment status stored in 'attachmentStatus' - // : fromAccess is head of chain of subpasses, which stores all attachment status in 'attachmentStatus' - const ResourceAccessNode &fromAccess = get(ResourceAccessGraph::AccessNodeTag{}, g, from); - const ResourceAccessNode &toAccess = get(ResourceAccessGraph::AccessNodeTag{}, g, to); + // CC_EXPECTS(uniformFlag ^ storageFlag); + // uniform or read-only storage buffer + bufferUsage = uniformFlag ? gfx::BufferUsage::UNIFORM : gfx::BufferUsage::STORAGE; + } - bool isAdjacent = isPassExecAdjecent(from, to); - std::vector commonResources; + // those buffers not found in descriptorlayout but appear here, + // can and only can be VERTEX/INDEX/INDIRECT BUFFER, + // only copy pass is allowed. - const auto *srcHead = &fromAccess; - const auto *dstHead = &toAccess; + auto memAccess = toGfxAccess(access); + accesFlag = gfx::getAccessFlags(bufferUsage, gfx::MemoryUsage::DEVICE, memAccess, visibility); + return std::make_tuple(visibility, accesFlag); +}; - bool srcHasSubpass = srcHead->nextSubpass; - bool dstHasSubpass = dstHead->nextSubpass; - srcHead = srcHasSubpass ? srcHead->nextSubpass : srcHead; +void addAccessStatus(ResourceAccessGraph &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status) { + const auto &[name, access, visibility, accessFlag, range] = status; + uint32_t rescID = rg.valueIndex.at(name); + const auto &resourceDesc = get(ResourceGraph::DescTag{}, rg, rescID); + const auto &traits = get(ResourceGraph::TraitsTag{}, rg, rescID); - std::stack reverseSubpassQ; - while (srcHead) { - reverseSubpassQ.push(srcHead); - srcHead = srcHead->nextSubpass; - } - ccstd::set subpassResourceSet; - while (!reverseSubpassQ.empty()) { - uint32_t srcSubpassIndex = reverseSubpassQ.size() - 1; - srcHead = reverseSubpassQ.top(); - reverseSubpassQ.pop(); - const std::vector &fromStatus = srcHead->attachmentStatus; - std::vector &srcRearBarriers = srcHasSubpass ? barrierMap[from].subpassBarriers[srcSubpassIndex].rearBarriers : barrierMap[from].blockBarrier.rearBarriers; - uint32_t dstSubpassIndex = 0; - dstHead = &toAccess; - bool dstHasSubpass = dstHead->nextSubpass; - dstHead = dstHasSubpass ? toAccess.nextSubpass : &toAccess; - while (dstHead) { - const std::vector &toStatus = dstHead->attachmentStatus; - std::vector &dstFrontBarriers = dstHasSubpass ? barrierMap[to].subpassBarriers[dstSubpassIndex].frontBarriers : barrierMap[to].blockBarrier.frontBarriers; - AccessNodeInfo fromInfo = {fromStatus, srcRearBarriers, from, srcHasSubpass ? static_cast(reverseSubpassQ.size()) : INVALID_ID}; - AccessNodeInfo toInfo = {toStatus, dstFrontBarriers, to, dstHasSubpass ? dstSubpassIndex : INVALID_ID}; - bool isExecAdjacent = isAdjacent && (!srcHead->nextSubpass && !dstSubpassIndex); - fillBarrier(fromInfo, toInfo, isAdjacent, subpassResourceSet); - dstHead = dstHead->nextSubpass; - ++dstSubpassIndex; - } - } + CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); + if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { + rag.resourceIndex.emplace(name, rescID); + rag.resourceNames.emplace_back(name); + } - auto &rearBarriers = barrierMap[from].blockBarrier.rearBarriers; - auto &frontBarriers = barrierMap[from].blockBarrier.frontBarriers; - - uint32_t subpassIdx = 0; - for (const auto &barriers : barrierMap[from].subpassBarriers) { - for (const auto &barrier : barriers.rearBarriers) { - auto resID = barrier.resourceID; - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - auto iter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); - auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; - - if (resFinalPassID > from) { - const auto *dstHead = dstHasSubpass ? toAccess.nextSubpass : &toAccess; - const AccessStatus *dstAccess{nullptr}; - while (dstHead) { - auto iter = std::find_if(dstHead->attachmentStatus.begin(), dstHead->attachmentStatus.end(), [resID](const AccessStatus &access) { - return access.vertID == resID; - }); - if (iter != dstHead->attachmentStatus.end()) { - dstAccess = &(*iter); - break; - } - dstHead = dstHead->nextSubpass; - } + node.resourceStatus.emplace(name, AccessStatus{ + accessFlag, + range, + }); +} - if (!dstAccess) { - continue; - } +namespace { +const uint32_t ATTACHMENT_TYPE_WEIGHT[] = {0, 2, 1}; - const auto *srcHead = srcHasSubpass ? fromAccess.nextSubpass : &fromAccess; - uint32_t step = 0; - while (step <= subpassIdx) { - srcHead = srcHead->nextSubpass; - ++step; - } +struct AttachmentSortKey { + gfx::SampleCount samples; + AccessType accessType; + uint32_t attachmentWeight; + const ccstd::pmr::string name; +}; - bool laterUse = false; - while (srcHead) { - const auto &attachments = srcHead->attachmentStatus; - laterUse |= std::any_of(attachments.begin(), attachments.end(), [resID](const AccessStatus &access) { - return access.vertID == resID; - }); - srcHead = srcHead->nextSubpass; - } +struct AttachmentComparator { + bool operator()(const AttachmentSortKey &lhs, const AttachmentSortKey &rhs) const { + return std::tie(rhs.samples, lhs.accessType, lhs.attachmentWeight, lhs.name) < std::tie(lhs.samples, rhs.accessType, rhs.attachmentWeight, rhs.name); + } +}; - // laterUse: in case it's a split begin/end. - const auto &srcAccess = laterUse ? barrier.endStatus : barrier.beginStatus; - if (isTransitionStatusDependent(srcAccess, *dstAccess)) { - if (iter == rearBarriers.end()) { - auto &collect = rearBarriers.emplace_back(barrier); - collect.beginStatus.vertID = from; - collect.endStatus.vertID = isAdjacent ? from : to; - } else if (iter->endStatus.vertID >= to) { - (*iter) = barrier; - iter->beginStatus.vertID = from; - iter->endStatus.vertID = isAdjacent ? from : to; - } - } - } - } +struct ViewInfo { + gfx::Format format{gfx::Format::UNKNOWN}; + LayoutAccess access; + gfx::LoadOp loadOp; + gfx::StoreOp storeOp; + AttachmentType attachmentType; +}; - for (const auto &barrier : barriers.frontBarriers) { - auto resID = barrier.resourceID; - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; - auto firstMeetIter = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID); - auto innerResIter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); - - if (firstMeetIter == frontBarriers.end() && innerResIter == rearBarriers.end() && resFinalPassID > from) { - frontBarriers.emplace_back(barrier); +using AttachmentMap = ccstd::pmr::map; +} // namespace + +void fillRenderPassInfo(const AttachmentMap &colorMap, + FGRenderPassInfo &fgRenderpassInfo, + const ResourceGraph &resg) { + for (const auto &pair : colorMap) { + const auto &key = pair.first; + const auto &viewInfo = pair.second; + if (viewInfo.attachmentType == AttachmentType::DEPTH_STENCIL) { + // put ds[sample > 1] to ds, ds[sample == 1] to dsResolve, swap them if not a ms pass in endRenderPass. + bool ms = key.samples != gfx::SampleCount::X1; + auto &ds = ms ? fgRenderpassInfo.rpInfo.depthStencilAttachment + : fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; + auto &dsAccess = ms ? fgRenderpassInfo.dsAccess : fgRenderpassInfo.dsResolveAccess; + if (ds.format == gfx::Format::UNKNOWN) { + ds.depthLoadOp = viewInfo.loadOp; + ds.stencilLoadOp = viewInfo.loadOp; + ds.sampleCount = key.samples; + ds.format = viewInfo.format; + dsAccess.prevAccess = viewInfo.access.prevAccess; + } + ds.depthStoreOp = viewInfo.storeOp; + ds.stencilStoreOp = viewInfo.storeOp; + dsAccess.nextAccess = viewInfo.access.nextAccess; + + auto iter = fgRenderpassInfo.viewIndex.find(key.name.c_str()); + if (iter == fgRenderpassInfo.viewIndex.end()) { + auto parentID = realID(key.name, resg); + const auto &parentName = get(ResourceGraph::NameTag{}, resg, parentID); + AttachmentInfo attachmentInfo(fgRenderpassInfo.get_allocator()); + attachmentInfo.parentName = parentName; + attachmentInfo.attachmentIndex = gfx::INVALID_BINDING; + attachmentInfo.isResolveView = fgRenderpassInfo.resolveCount && key.samples == gfx::SampleCount::X1; + fgRenderpassInfo.viewIndex.emplace(key.name, attachmentInfo); + } + } else { + auto iter = fgRenderpassInfo.viewIndex.find(key.name.c_str()); + auto &colors = fgRenderpassInfo.rpInfo.colorAttachments; + if (iter == fgRenderpassInfo.viewIndex.end()) { + auto colorIndex = fgRenderpassInfo.orderedViews.size(); + auto &color = colors.emplace_back(); + color.format = viewInfo.format; + color.sampleCount = key.samples; + color.storeOp = viewInfo.storeOp; + color.loadOp = viewInfo.loadOp; + fgRenderpassInfo.colorAccesses.emplace_back(LayoutAccess{viewInfo.access.prevAccess, viewInfo.access.nextAccess}); + fgRenderpassInfo.colorAccesses[colorIndex].nextAccess = viewInfo.access.nextAccess; + + auto parentID = realID(key.name, resg); + const auto &parentName = get(ResourceGraph::NameTag{}, resg, parentID); + AttachmentInfo attachmentInfo(fgRenderpassInfo.get_allocator()); + attachmentInfo.parentName = parentName; + attachmentInfo.attachmentIndex = static_cast(fgRenderpassInfo.orderedViews.size()); + attachmentInfo.isResolveView = fgRenderpassInfo.resolveCount && key.samples == gfx::SampleCount::X1; + + fgRenderpassInfo.viewIndex.emplace(key.name, attachmentInfo); + fgRenderpassInfo.orderedViews.emplace_back(key.name); + } else { + const auto &attachmentInfo = fgRenderpassInfo.viewIndex.at(key.name); + auto cIndex = attachmentInfo.attachmentIndex; + if (cIndex == gfx::INVALID_BINDING) { + bool ms = key.samples == gfx::SampleCount::X1; + auto &ds = ms ? fgRenderpassInfo.rpInfo.depthStencilAttachment : fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; + ds.depthStoreOp = viewInfo.storeOp; + ds.stencilStoreOp = viewInfo.storeOp; + auto &access = ms ? fgRenderpassInfo.dsAccess : fgRenderpassInfo.dsResolveAccess; + access.nextAccess = viewInfo.access.nextAccess; + } else { + auto &color = fgRenderpassInfo.rpInfo.colorAttachments[cIndex]; + color.storeOp = viewInfo.storeOp; + fgRenderpassInfo.colorAccesses[cIndex].nextAccess = viewInfo.access.nextAccess; } } } - subpassIdx++; } - - const AccessTable &accessRecord; - BarrierMap &barrierMap; - const ResourceGraph &resourceGraph; - ExternalResMap &externalMap; // last frame to curr frame status transition - ResourceNames &resourceNames; // record those which been written - ResourceLifeRecordMap &resourceLifeRecord; - PmrFlatMap &rpInfos; }; -void buildBarriers(FrameGraphDispatcher &fgDispatcher) { - auto *scratch = fgDispatcher.scratch; - const auto &renderGraph = fgDispatcher.graph; - const auto &layoutGraph = fgDispatcher.layoutGraph; - auto &resourceGraph = fgDispatcher.resourceGraph; - auto &relationGraph = fgDispatcher.relationGraph; - auto &externalResMap = fgDispatcher.externalResMap; - auto &rag = fgDispatcher.resourceAccessGraph; +[[nodiscard("concat")]] ccstd::pmr::string concatResName( + std::string_view name0, + std::string_view name1, + boost::container::pmr::memory_resource *scratch) { + ccstd::pmr::string name(name0, scratch); + name += "/"; + name += name1; + return name; +} - // record resource current in-access and out-access for every single node - if (!fgDispatcher._accessGraphBuilt) { - const Graphs graphs{renderGraph, resourceGraph, layoutGraph, rag, relationGraph}; - buildAccessGraph(graphs); - fgDispatcher._accessGraphBuilt = true; +void extractNames(const ccstd::pmr::string &resName, + const RasterView &view, + ccstd::pmr::vector> &names) { + // depth_stencil + if (view.attachmentType == AttachmentType::DEPTH_STENCIL) { + if (!defaultAttachment(view.slotName)) { + if (strstr(resName.c_str(), "/")) { + names.emplace_back(resName, 0); + } else { + auto &subresName = names.emplace_back(); + subresName.first = concatResName(resName, DEPTH_PLANE_NAME, names.get_allocator().resource()); + subresName.second = 0; + } + } + if (!defaultAttachment(view.slotName1)) { + if (strstr(resName.c_str(), "/")) { + names.emplace_back(resName, 1); + } else { + auto &subresName = names.emplace_back(); + subresName.first = concatResName(resName, STENCIL_PLANE_NAME, names.get_allocator().resource()); + subresName.second = 1; + } + } } - // found pass id in this map ? barriers you should commit when run into this pass - // : or no extra barrier needed. - BarrierMap &batchedBarriers = fgDispatcher.barrierMap; + // cube - { - // barrier first meet - // O(N) actually - ccstd::set firstMeet; - for (size_t i = 0; i < rag.access.size(); ++i) { - const auto *status = &rag.access[i]; - for (const auto &attachment : status->attachmentStatus) { - AccessStatus lastStatus{ - static_cast(i), - gfx::ShaderStageFlagBit::NONE, - gfx::MemoryAccessBit::NONE, - gfx::PassType::RASTER, - gfx::AccessFlagBit::NONE, - gfx::TextureUsageBit::NONE, - TextureRange{}, - }; - - AccessStatus currStatus = attachment; - currStatus.vertID = static_cast(i); - - gfx::BarrierType bType = gfx::BarrierType::FULL; - const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, attachment.vertID); - if (traits.hasSideEffects()) { - const auto &accessFlag = get(ResourceGraph::StatesTag{}, resourceGraph, attachment.vertID).states; - if (accessFlag != gfx::AccessFlagBit::NONE) { - lastStatus.accessFlag = accessFlag; - bType = traits.residency == ResourceResidency::BACKBUFFER ? gfx::BarrierType::FULL : gfx::BarrierType::SPLIT_END; - } - if (!isTransitionStatusDependent(lastStatus, currStatus)) { - continue; - } - } - if (firstMeet.find(attachment.vertID) == firstMeet.end()) { - firstMeet.emplace(attachment.vertID); - - if (batchedBarriers.find(i) == batchedBarriers.end()) { - batchedBarriers.emplace(i, BarrierNode{}); - auto &rpInfo = rag.rpInfos[i].rpInfo; - // NOLINTNEXTLINE (readability-container-size-empty) - if (rpInfo.subpasses.size() >= 1) { - batchedBarriers[i].subpassBarriers.resize(rpInfo.subpasses.size()); - } - } + // array + + if (names.empty()) { + names.emplace_back(resName, 0); + } +} - auto &blockFrontBarrier = batchedBarriers.at(i).blockBarrier.frontBarriers; - auto resIter = std::find_if(blockFrontBarrier.begin(), blockFrontBarrier.end(), [&attachment](const Barrier &barrier) { return barrier.resourceID == attachment.vertID; }); - if (resIter == blockFrontBarrier.end()) { - Barrier firstMeetBarrier{ - attachment.vertID, - bType, - nullptr, - lastStatus, - currStatus, - }; - blockFrontBarrier.emplace_back(firstMeetBarrier); - } - auto *nextStatus = status->nextSubpass; - uint32_t index = 0; - while (nextStatus) { - const auto &subpassStatus = nextStatus->attachmentStatus; - auto &subpassBarriers = batchedBarriers.at(i).subpassBarriers; - auto &frontBarriers = subpassBarriers[index].frontBarriers; - auto iter = std::find_if(subpassStatus.begin(), subpassStatus.end(), [&attachment](const AccessStatus &access) { return access.vertID == attachment.vertID; }); - if (iter != subpassStatus.end()) { - lastStatus.vertID = 0xFFFFFFFF; - currStatus.vertID = index; - currStatus.accessFlag = iter->accessFlag; - Barrier firstMeetBarrier{ - attachment.vertID, - bType, - nullptr, - lastStatus, - currStatus, - }; - frontBarriers.emplace_back(firstMeetBarrier); - break; - } - nextStatus = nextStatus->nextSubpass; - index++; - } - } - } - } +[[nodiscard("subresName")]] ccstd::pmr::string getSubresName(const ccstd::pmr::string &resName, + uint32_t planeID, const ResourceGraph& resg, + boost::container::pmr::memory_resource* scratch) { + const auto& desc = get(ResourceGraph::DescTag{}, resg, vertex(resName, resg)); + if(desc.format == gfx::Format::DEPTH_STENCIL) { + auto nameView = planeID == 0 ? DEPTH_PLANE_NAME : STENCIL_PLANE_NAME; + const auto &subresName = concatResName(resName, nameView, scratch); + return subresName; } + - ResourceNames namesSet; - { - // barrier between passes - BarrierVisitor visitor(resourceGraph, batchedBarriers, externalResMap, namesSet, rag.accessRecord, rag.resourceLifeRecord, rag.rpInfos); - auto colors = rag.colors(scratch); - boost::queue q; - - boost::breadth_first_visit( - rag, - EXPECT_START_ID, - q, - visitor, - get(colors, rag)); - } - - // external res barrier for next frame - for (const auto &externalPair : externalResMap) { - const auto &resName = externalPair.first; - const auto &transition = externalPair.second; - auto resID = resourceGraph.valueIndex.at(resName); - const auto &resTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, resID); - auto &rescStates = get(ResourceGraph::StatesTag{}, resourceGraph, resID); - - bool backBuffer = resTraits.residency == ResourceResidency::BACKBUFFER; - // when to dispatch a barrier on persistent: - // 1. resource been written in this frame; - // 2. first meet in this frame (no idea if any writes in next frame) - // 3. backbuffer present - bool needNextBarrier = (namesSet.find(resName) != namesSet.end()) || (rescStates.states == gfx::AccessFlagBit::NONE); - - // persistant resource states cached here - rescStates.states = transition.currStatus.accessFlag; - - if (!backBuffer && !needNextBarrier) { - continue; - } + // cube - auto passID = transition.currStatus.vertID; - if (batchedBarriers.find(passID) == batchedBarriers.end()) { - batchedBarriers.emplace(passID, BarrierNode{}); - } + // array - Barrier nextFrameResBarrier{ - resID, - gfx::BarrierType::SPLIT_BEGIN, - nullptr, - externalResMap[externalPair.first].currStatus, - {}}; - - if (backBuffer) { - nextFrameResBarrier.endStatus = { - INVALID_ID, - gfx::ShaderStageFlagBit::NONE, - gfx::MemoryAccessBit::NONE, - gfx::PassType::PRESENT, - gfx::AccessFlagBit::PRESENT, - gfx::TextureUsageBit::NONE, - TextureRange{}, - }; - nextFrameResBarrier.type = gfx::BarrierType::FULL; - rescStates.states = gfx::AccessFlagBit::PRESENT; - } + // UNREACHABLE + CC_ASSERT(false); + return ""; +} - bool hasSubpass = !(batchedBarriers[passID].subpassBarriers.size() <= 1); - if (hasSubpass) { - // rpinfo instead - auto &fgRenderPassInfo = rag.rpInfos.at(passID); - auto iter = std::find(fgRenderPassInfo.orderedViews.begin(), fgRenderPassInfo.orderedViews.end(), resName.c_str()); - CC_ASSERT(iter != fgRenderPassInfo.orderedViews.end()); - auto index = std::distance(fgRenderPassInfo.orderedViews.begin(), iter); - index -= fgRenderPassInfo.rpInfo.depthStencilAttachment.format != gfx::Format::UNKNOWN; - fgRenderPassInfo.colorAccesses[index].nextAccess = nextFrameResBarrier.endStatus.accessFlag; - } else { - auto &rearBarriers = batchedBarriers[passID].blockBarrier.rearBarriers; - rearBarriers.emplace_back(nextFrameResBarrier); - } +auto checkRasterViews(const Graphs &graphs, + ResourceAccessGraph::vertex_descriptor ragVertID, + ResourceAccessNode &node, + const RasterViewsMap &rasterViews, + AttachmentMap &colorMap) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + const auto passID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, ragVertID); + bool dependent = false; + bool hasDS = false; + + auto explicitVis = gfx::ShaderStageFlagBit::NONE; + if (holds(passID, renderGraph)) { + explicitVis |= gfx::ShaderStageFlagBit::COMPUTE; } - { - const auto &resDescs = get(ResourceGraph::DescTag{}, resourceGraph); - auto genGFXBarrier = [&resDescs](std::vector &barriers) { - for (auto &passBarrier : barriers) { - const auto &desc = get(resDescs, passBarrier.resourceID); - if (desc.dimension == ResourceDimension::BUFFER) { - gfx::BufferBarrierInfo info; - info.prevAccesses = passBarrier.beginStatus.accessFlag; - info.nextAccesses = passBarrier.endStatus.accessFlag; - const auto &range = ccstd::get(passBarrier.endStatus.range); - info.offset = range.offset; - info.size = range.size; - info.type = passBarrier.type; - passBarrier.barrier = gfx::Device::getInstance()->getBufferBarrier(info); - } else { - gfx::TextureBarrierInfo info; - info.prevAccesses = passBarrier.beginStatus.accessFlag; - info.nextAccesses = passBarrier.endStatus.accessFlag; - const auto &range = ccstd::get(passBarrier.beginStatus.range); - info.baseMipLevel = range.mipLevel; - info.levelCount = range.levelCount; - info.baseSlice = range.firstSlice; - info.sliceCount = range.numSlices; - info.type = passBarrier.type; - passBarrier.barrier = gfx::Device::getInstance()->getTextureBarrier(info); - } - } - }; + for (const auto &pair : rasterViews) { + const auto &rasterView = pair.second; + const auto &resName = pair.first; + const auto resID = vertex(resName, resourceGraph); + auto access = rasterView.accessType; + gfx::ShaderStageFlagBit originVis = getVisibility(renderGraph, layoutGraphData, passID, pair.second.slotName) | explicitVis | pair.second.shaderStageFlags; + const auto &[vis, accessFlag] = getTextureStatus(resName.data(), access, originVis, resourceGraph, true); + auto range = getResourceRange(resID, resourceGraph); + + ViewStatus viewStatus{resName, access, vis, accessFlag, range}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); - constexpr static bool USING_RENDERPASS_DEP_INSTEAD_OF_BARRIER{true}; - if constexpr (USING_RENDERPASS_DEP_INSTEAD_OF_BARRIER) { - auto prune = [&rag, &renderGraph, &resourceGraph](std::vector &barriers) { - barriers.erase(std::remove_if(barriers.begin(), barriers.end(), [&rag, &renderGraph, &resourceGraph](Barrier &barrier) { - bool fromAttachment = isAttachmentAccess(barrier.beginStatus.accessFlag) || barrier.beginStatus.accessFlag == gfx::AccessFlagBit::NONE; - bool toAttachment = isAttachmentAccess(barrier.endStatus.accessFlag); - return toAttachment; - }), - barriers.end()); - }; - for (auto &passBarrierInfo : batchedBarriers) { - auto &passBarrierNode = passBarrierInfo.second; - prune(passBarrierNode.blockBarrier.frontBarriers); - prune(passBarrierNode.blockBarrier.rearBarriers); - } - } + const auto &[lastVertId, lastAccess] = dependencyCheck(resourceAccessGraph, ragVertID, resourceGraph, viewStatus); + tryAddEdge(lastVertId, ragVertID, resourceAccessGraph); + tryAddEdge(lastVertId, ragVertID, relationGraph); + dependent |= (lastVertId != EXPECT_START_ID); + + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + colorMap.emplace(AttachmentSortKey{desc.sampleCount, + rasterView.accessType, + ATTACHMENT_TYPE_WEIGHT[static_cast(rasterView.attachmentType)], + resName}, + ViewInfo{desc.format, + LayoutAccess{lastAccess, accessFlag}, + rasterView.loadOp, + rasterView.storeOp, + rasterView.attachmentType}); + hasDS |= rasterView.attachmentType == AttachmentType::DEPTH_STENCIL; + + ccstd::pmr::vector> names(resourceAccessGraph.get_allocator()); + extractNames(resName, rasterView, names); + for (const auto& [subresFullName, plane] : names) { + resourceAccessGraph.resourceIndex.emplace(subresFullName, vertex(subresFullName, resourceGraph)); + } + } + return std::make_tuple(dependent, hasDS); +} - // generate gfx barrier - for (auto &passBarrierInfo : batchedBarriers) { - auto &passBarrierNode = passBarrierInfo.second; - genGFXBarrier(passBarrierNode.blockBarrier.frontBarriers); - genGFXBarrier(passBarrierNode.blockBarrier.rearBarriers); - for (auto &subpassBarrier : passBarrierNode.subpassBarriers) { - genGFXBarrier(subpassBarrier.frontBarriers); - genGFXBarrier(subpassBarrier.rearBarriers); - } - } - } +bool checkComputeViews(const Graphs &graphs, ResourceAccessGraph::vertex_descriptor ragVertID, ResourceAccessNode &node, const ComputeViewsMap &computeViews) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + const auto passID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, ragVertID); + bool dependent = false; - { - for (auto &[vert, fgRenderpassInfo] : rag.rpInfos) { - auto &colorAttachments = fgRenderpassInfo.rpInfo.colorAttachments; - for (uint32_t i = 0; i < colorAttachments.size(); ++i) { - const auto &colorAccess = fgRenderpassInfo.colorAccesses[i]; - colorAttachments[i].barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), colorAccess.prevAccess, colorAccess.nextAccess); + for (const auto &pair : computeViews) { + const auto &values = pair.second; + const auto &resName = pair.first; + const auto resID = vertex(resName, resourceGraph); + auto range = getResourceRange(vertex(resName, resourceGraph), resourceGraph); + for (const auto &computeView : values) { + gfx::ShaderStageFlagBit vis = gfx::ShaderStageFlagBit::NONE; + for (const auto &view : pair.second) { + vis |= getVisibility(renderGraph, layoutGraphData, passID, view.name); + vis |= view.shaderStageFlags; } - auto &dsAttachment = fgRenderpassInfo.rpInfo.depthStencilAttachment; - if (dsAttachment.format != gfx::Format::UNKNOWN) { - const auto &dsAccess = fgRenderpassInfo.dsAccess; - dsAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + gfx::AccessFlagBit accessFlag{gfx::AccessFlagBit::NONE}; + if (desc.dimension == ResourceDimension::BUFFER) { + const auto &[ignore0, access] = getBufferStatus(pair.first, computeView.accessType, vis, resourceGraph); + accessFlag = access; + } else { + const auto &[ignore0, access] = getTextureStatus(pair.first, computeView.accessType, vis, resourceGraph, false); + accessFlag = access; } - auto &dsResolveAttachment = fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; - if (dsResolveAttachment.format != gfx::Format::UNKNOWN) { - const auto &dsAccess = fgRenderpassInfo.dsResolveAccess; - dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); + range.firstSlice = computeView.plane; + range.numSlices = 1; + ViewStatus viewStatus{pair.first, computeView.accessType, vis, accessFlag, range}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + auto [lastVertId, neareastAccess] = dependencyCheck(resourceAccessGraph, ragVertID, resourceGraph, viewStatus); + + tryAddEdge(lastVertId, ragVertID, resourceAccessGraph); + tryAddEdge(lastVertId, ragVertID, relationGraph); + dependent = lastVertId != EXPECT_START_ID; + + if(out_degree(resID, resourceGraph)) { + const auto& subresFullName = getSubresName(resName, computeView.plane, resourceGraph, resourceAccessGraph.resource()); + resourceAccessGraph.resourceIndex.emplace(subresFullName, vertex(subresFullName, resourceGraph)); } } } + + return dependent; } -#pragma endregion BUILD_BARRIERS -#pragma region PASS_REORDER +bool checkResolveResource(const Graphs &graphs, + uint32_t ragVertID, + ResourceAccessNode &node, + const ccstd::pmr::vector &resolves, + AttachmentMap &colorMap) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + const auto passID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, ragVertID); + bool dependent = false; -struct PassVisitor : boost::dfs_visitor<> { - using RLGVertex = RelationGraph::vertex_descriptor; - using RLGEdge = RelationGraph::edge_descriptor; - using InEdgeRange = std::pair; - using OutEdgeRange = std::pair; + for (const auto &pair : resolves) { + const auto &resolveTargetName = pair.target; - PassVisitor(RelationGraph &tcIn, CloseCircuits &circuitsIn) : _relationGraph(tcIn), _circuits(circuitsIn) {} + const auto &resID = vertex(resolveTargetName, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); - void start_vertex(RLGVertex u, const RelationGraph &g) {} + bool isDS = desc.format == gfx::Format::DEPTH_STENCIL; + auto accessFlag = isDS ? gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE : gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE; - void discover_vertex(RLGVertex u, const RelationGraph &g) {} + gfx::ShaderStageFlagBit vis = gfx::ShaderStageFlagBit::FRAGMENT; + auto range = getResourceRange(resID, resourceGraph); - void examine_edge(RLGEdge e, const RelationGraph &g) { + ViewStatus viewStatus{resolveTargetName, AccessType::WRITE, vis, accessFlag, range}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + + const auto &[lastVertId, lastAccess] = dependencyCheck(resourceAccessGraph, ragVertID, resourceGraph, viewStatus); + tryAddEdge(lastVertId, ragVertID, resourceAccessGraph); + tryAddEdge(lastVertId, ragVertID, relationGraph); + dependent = lastVertId != EXPECT_START_ID; + + AttachmentType attachmentType = isDS ? AttachmentType::DEPTH_STENCIL : AttachmentType::RENDER_TARGET; + colorMap.emplace(AttachmentSortKey{desc.sampleCount, + AccessType::WRITE, + ATTACHMENT_TYPE_WEIGHT[static_cast(attachmentType)], + resolveTargetName}, + ViewInfo{desc.format, + LayoutAccess{lastAccess, accessFlag}, + gfx::LoadOp::DISCARD, + gfx::StoreOp::STORE, + attachmentType}); } + return dependent; +} - void tree_edge(RLGEdge e, const RelationGraph &g) {} +uint32_t record(uint32_t index) { + uint32_t res = 1 << index; + return res; +} - void back_edge(RLGEdge e, const RelationGraph &g) {} +uint32_t record(const ccstd::vector &indices) { + uint32_t res = 0; + for (auto attachmentIndex : indices) { + res |= 1 << attachmentIndex; + } + return res; +} - void forward_or_cross_edge(RLGEdge e, const RelationGraph &g) { - // the vertex which: - // 1. is ancestor of targetID; - // 2. sourceID is reachable at this specific vert; - // is where the closed-path started. - // note that `reachable` may results to multiple paths, choose the shortest one. - auto sourceID = source(e, g); - auto targetID = target(e, g); +void extract(uint32_t val, ccstd::vector &preserves) { + uint32_t index = 0; + while (val) { + if (val & 0x1) { + preserves.emplace_back(index); + } + val = val >> 1; + ++index; + } +} - using RhsRangePair = std::pair; +void getPreserves(gfx::RenderPassInfo &rpInfo) { + std::stack stack; + for (auto &info : rpInfo.subpasses) { + stack.push(&info); + } - bool foundIntersect = false; - std::queue vertQ; - auto iterPair = in_edges(targetID, g); - vertQ.emplace(RhsRangePair{iterPair.first, iterPair}); + auto dsIndex = record(rpInfo.colorAttachments.size()); + auto dsMask = record(rpInfo.colorAttachments.size()) | record(rpInfo.colorAttachments.size() + 1); - // from source vertex on this edge back to branch point - EdgeList rhsPath; - bool rootEdge = true; - while (!foundIntersect && !vertQ.empty()) { - auto rangePair = vertQ.front(); - vertQ.pop(); - auto range = rangePair.second; - for (auto iter = range.first; iter != range.second; ++iter) { - auto srcID = source((*iter), g); - if (sourceID == srcID) { - continue; - } - auto e = edge(srcID, sourceID, _relationGraph); - auto recordIter = rootEdge ? iter : rangePair.first; - if (!e.second) { - vertQ.emplace(RhsRangePair{recordIter, in_edges(srcID, g)}); - } else { - rhsPath = {(*iter), *recordIter}; - foundIntersect = true; - break; - } - } - rootEdge = false; + uint32_t laterRead{0}; + while (!stack.empty()) { + auto *tail = stack.top(); + stack.pop(); + + auto readRecord = record(tail->inputs); + auto writeRecord = record(tail->colors); + auto resolveRecord = record(tail->resolves); + + uint32_t dsRecord = 0; + if (tail->depthStencil != INVALID_ID) { + dsRecord |= record(tail->depthStencil); } - assert(foundIntersect); + if (tail->depthStencilResolve != INVALID_ID) { + dsRecord |= record(tail->depthStencilResolve); + } + auto shown = readRecord | writeRecord | resolveRecord | dsRecord; + auto needPreserve = (shown | laterRead) ^ shown; + needPreserve = (needPreserve & dsMask) == dsMask ? (needPreserve & ~dsMask) | dsIndex : (needPreserve & ~dsMask); + extract(needPreserve, tail->preserves); + laterRead |= readRecord; + } +} - using LhsRangePair = std::pair; - auto branchVert = source(rhsPath.first, g); - bool found = false; - std::queue forwardVertQ; - auto forwardIterPair = out_edges(branchVert, g); - forwardVertQ.emplace(LhsRangePair{forwardIterPair.first, forwardIterPair}); - EdgeList lhsPath; - rootEdge = true; - while (!found && !forwardVertQ.empty()) { - auto rangePair = forwardVertQ.front(); - forwardVertQ.pop(); - auto range = rangePair.second; - for (auto iter = range.first; iter != range.second; ++iter) { - if ((*iter) == rhsPath.first) { - continue; - } - auto dstID = target((*iter), g); - auto e = edge(dstID, sourceID, _relationGraph); - auto recordIter = rootEdge ? iter : rangePair.first; - if (!e.second) { - forwardVertQ.emplace(LhsRangePair{recordIter, out_edges(dstID, g)}); - } else { - found = true; - lhsPath = {*recordIter, (*iter)}; - break; - } - } - rootEdge = true; - } - assert(found); - lhsPath.second = e; - - _circuits.emplace_back(CloseCircuit{lhsPath, rhsPath}); - }; +uint32_t getDepthStencilSlot(uint32_t uniqueResourceCount, uint32_t resolveCount, bool hasDS) { + auto dsSlot = uniqueResourceCount - hasDS + resolveCount; + return dsSlot; +} -private: - RelationGraph &_relationGraph; - CloseCircuits &_circuits; -}; +void startRenderPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; -// forward (vertex ascending): -// -- true: how much resource this pass writes to, which has an effect of later passes; -// -- false: how much resource this pass reads from, which is dependent from former passes. -auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, ResourceAccessGraph::vertex_descriptor vert, bool forward) { - const ResourceAccessNode &accessNode = get(RAG::AccessNodeTag{}, rag, vert); - int64_t score = 0; - bool forceAdjacent = false; - for (const auto &resc : accessNode.attachmentStatus) { - int64_t eval = 0; - auto rescID = resc.vertID; - const ResourceDesc &desc = get(ResourceGraph::DescTag{}, rescGraph, rescID); - const ResourceTraits &traits = get(ResourceGraph::TraitsTag{}, rescGraph, rescID); + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - gfx::MemoryAccessBit substractFilter = forward ? gfx::MemoryAccessBit::READ_ONLY : gfx::MemoryAccessBit::WRITE_ONLY; - if (resc.access == substractFilter) { - // forward calculate write(s), backward calculate read(s). - continue; - } + auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, vertID); + if (pass.subpassGraph.subpasses.empty()) { + AttachmentMap colorMap(resourceAccessGraph.get_allocator()); + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, vertID); + std::ignore = checkRasterViews(graphs, rlgVertID, accessNode, pass.rasterViews, colorMap); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); + fillRenderPassInfo(colorMap, fgRenderPassInfo, resourceGraph); + } else { + const auto &subpasses = pass.subpassGraph.subpasses; + uint32_t initVal{0}; + fgRenderPassInfo.resolveCount = std::accumulate(subpasses.begin(), subpasses.end(), initVal, [](uint32_t ct, const Subpass &subpass) { + return ct + subpass.resolvePairs.size(); + }); + } - switch (desc.dimension) { - case ResourceDimension::BUFFER: - eval = desc.width; - break; - case ResourceDimension::TEXTURE1D: - case ResourceDimension::TEXTURE2D: - case ResourceDimension::TEXTURE3D: - eval = gfx::formatSize(desc.format, desc.width, desc.height, desc.depthOrArraySize); - break; + const auto &subpasses = pass.subpassGraph.subpasses; + uint32_t initVal{0}; + ccstd::pmr::set resSet{resourceAccessGraph.get_allocator()}; + for (const auto &subpass : subpasses) { + for (const auto &view : subpass.rasterViews) { + resSet.emplace(realID(view.first, resourceGraph)); } - - if (traits.residency == ResourceResidency::MEMORYLESS) { - forceAdjacent = true; - score = forward ? std::numeric_limits::lowest() : std::numeric_limits::max(); - break; + auto &dsResolveAttachment = fgRenderPassInfo.rpInfo.depthStencilResolveAttachment; + if (dsResolveAttachment.format != gfx::Format::UNKNOWN) { + const auto &dsAccess = fgRenderPassInfo.dsResolveAccess; + dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); } } - return std::make_tuple(forceAdjacent, score); -}; - -void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, const RelationGraph &relationGraphTc, const RelationVerts &lhsVerts, const RelationVerts &rhsVerts) { - assert(lhsVerts.size() >= 2); - assert(rhsVerts.size() >= 2); + fgRenderPassInfo.uniqueRasterViewCount = resSet.size(); +} - auto evaluate = [&rag, &rescGraph, &relationGraph](RelationVert vert, bool forward) { - auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, vert); - return evaluateHeaviness(rag, rescGraph, ragVert, forward); - }; +void endRenderPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; - if (lhsVerts.size() == 2 || rhsVerts.size() == 2) { - /* - 1 ----------- 2 - \ __--/ - 3 --`` - no extra choice, only 1 - 3 - 2 - */ - const RelationVerts *shorterPath = lhsVerts.size() == 2 ? &lhsVerts : &rhsVerts; - remove_edge((*shorterPath)[0], (*shorterPath)[1], relationGraph); - } else { - // fist and last joint pass in this circuit don't get involved in reorder. - auto firstLhsNode = lhsVerts[1]; - auto lastLhsNode = lhsVerts[lhsVerts.size() - 2]; + auto vertID = resourceAccessGraph.passIndex.at(passID); + auto rlgVertID = relationGraph.vertexMap.at(vertID); - const auto &lhsBackwardStatus = evaluate(firstLhsNode, false); - bool lhsAdjacentToStart = std::get<0>(lhsBackwardStatus); - const auto &lhsForwardStatus = evaluate(lastLhsNode, true); - bool lhsAdjacentToEnd = std::get<0>(lhsForwardStatus); + auto &node = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, vertID); + auto &fgRenderpassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, vertID); - auto firstRhsNode = rhsVerts[1]; - auto lastRhsNode = rhsVerts[rhsVerts.size() - 2]; + bool filledDS{fgRenderpassInfo.dsAccess.nextAccess != gfx::AccessFlags::NONE}; + bool filledDSResolve{fgRenderpassInfo.dsResolveAccess.nextAccess != gfx::AccessFlags::NONE}; + if (filledDSResolve && !filledDS) { + CC_ASSERT(fgRenderpassInfo.rpInfo.depthStencilAttachment.format == gfx::Format::UNKNOWN); + std::swap(fgRenderpassInfo.rpInfo.depthStencilAttachment, fgRenderpassInfo.rpInfo.depthStencilResolveAttachment); + std::swap(fgRenderpassInfo.dsAccess, fgRenderpassInfo.dsResolveAccess); + } - const auto &rhsBackwardStatus = evaluate(firstRhsNode, true); - bool rhsAdjacentToStart = std::get<0>(rhsBackwardStatus); - const auto &rhsForwardStatus = evaluate(lastRhsNode, false); - bool rhsAdjacentToEnd = std::get<0>(rhsForwardStatus); + auto colorSize = fgRenderpassInfo.orderedViews.size(); + for (auto dsIter = fgRenderpassInfo.viewIndex.begin(); dsIter != fgRenderpassInfo.viewIndex.end(); ++dsIter) { + const auto &resName = dsIter->first; + const auto &parentName = dsIter->second.parentName; + if ((dsIter->second.attachmentIndex == gfx::INVALID_BINDING) && (resName == parentName)) { + fgRenderpassInfo.orderedViews.emplace_back(dsIter->first); + } + } - if (lhsAdjacentToStart || rhsAdjacentToEnd || lhsAdjacentToEnd || rhsAdjacentToStart) { - const RelationVerts *formerPath = &lhsVerts; - const RelationVerts *latterPath = &rhsVerts; - if (rhsAdjacentToStart || lhsAdjacentToEnd) { - swap(formerPath, latterPath); - } + if (!pass.subpassGraph.subpasses.empty()) { + // for (auto &subpassInfo : fgRenderpassInfo.rpInfo.subpasses) { + // if (subpassInfo.depthStencil != gfx::INVALID_BINDING) { + // if (subpassInfo.depthStencil != gfx::INVALID_BINDING) { + // subpassInfo.depthStencil = colorSize; + // } + // if (subpassInfo.depthStencilResolve != gfx::INVALID_BINDING) { + // subpassInfo.depthStencilResolve = colorSize + 1; + // } + // } + // } + getPreserves(fgRenderpassInfo.rpInfo); + } +} - remove_edge((*latterPath)[0], (*latterPath)[1], relationGraph); - remove_edge((*formerPath)[formerPath->size() - 2], (*formerPath)[formerPath->size() - 1], relationGraph); +void startRenderSubpass(const Graphs &graphs, uint32_t passID, const RasterSubpass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; - tryAddEdge((*formerPath)[formerPath->size() - 2], (*latterPath)[1], relationGraph); - } + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - assert(lhsVerts.size() >= 3 && rhsVerts.size() >= 3); - constexpr int64_t score = std::numeric_limits::lowest(); - ccstd::vector> candidateSections; - std::queue lhsSection; - for (size_t i = 1; i < lhsVerts.size(); ++i) { - auto tryE = edge(lhsVerts[i], lhsVerts[i - 1], relationGraphTc); - auto tryRE = edge(lhsVerts[i - 1], lhsVerts[i], relationGraphTc); - // check if original reachable - if (!tryE.second && !tryRE.second) { - remove_edge(lhsVerts[i - 1], lhsVerts[i], relationGraph); - candidateSections.emplace_back(lhsSection); - std::queue clearQ; - lhsSection.swap(clearQ); + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + + auto parentID = parent(passID, renderGraph); + auto parentRagVertID = resourceAccessGraph.passIndex.at(parentID); + auto &fgRenderpassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, parentRagVertID); + AttachmentMap colorMap(resourceAccessGraph.get_allocator()); + + auto [hasDep, hasDS] = checkRasterViews(graphs, rlgVertID, accessNode, pass.rasterViews, colorMap); + hasDep |= checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); + hasDep |= checkResolveResource(graphs, rlgVertID, accessNode, pass.resolvePairs, colorMap); + fillRenderPassInfo(colorMap, fgRenderpassInfo, resourceGraph); + + auto &subpassInfo = fgRenderpassInfo.rpInfo.subpasses.emplace_back(); + auto &dependencies = fgRenderpassInfo.rpInfo.dependencies; + + // subpass info & subpass dependencies + for (const auto &pair : colorMap) { + const auto &sortKey = pair.first; + const std::string_view name = sortKey.name; + auto resID = vertex(sortKey.name, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + const auto &[ignored, cIndex, isResolveView] = fgRenderpassInfo.viewIndex.at(name.data()); + if (isResolveView) { + auto resolveIter = std::find_if(pass.resolvePairs.begin(), pass.resolvePairs.end(), [&name](const ResolvePair &resolve) { + return strcmp(resolve.target.c_str(), name.data()) == 0; + }); + if (desc.format == gfx::Format::DEPTH_STENCIL) { + subpassInfo.depthStencilResolve = getDepthStencilSlot(fgRenderpassInfo.uniqueRasterViewCount, fgRenderpassInfo.resolveCount, hasDS) + 1; + if (resolveIter->mode != gfx::ResolveMode::NONE) { + subpassInfo.depthResolveMode = resolveIter->mode; + } + if (resolveIter->mode1 != gfx::ResolveMode::NONE) { + subpassInfo.stencilResolveMode = resolveIter->mode1; + } + } else { + if (subpassInfo.resolves.empty()) { + subpassInfo.resolves.resize(pass.rasterViews.size() - hasDS, gfx::INVALID_BINDING); + } + const auto &resolveSrc = resolveIter->source; + const auto &resourceSrcInfo = fgRenderpassInfo.viewIndex.at(resolveSrc); + subpassInfo.resolves[resourceSrcInfo.attachmentIndex] = cIndex; } - auto e = edge(lhsVerts[i], lhsVerts[i - 1], relationGraph); - // verts comes in order, so either real edge exist or logic edge is added. - CC_ASSERT(e.second); - - lhsSection.emplace(e.first); - } - if (candidateSections.empty()) { - // if this one is a tight edge(no logic edge, dependent from one to its next), - // keep this whole chain as a candidate. - remove_edge(lhsVerts[0], lhsVerts[1], relationGraph); - remove_edge(lhsVerts[lhsVerts.size() - 2], lhsVerts[lhsVerts.size() - 1], relationGraph); - candidateSections.emplace_back(std::move(lhsSection)); - } + } else { + if (desc.format == gfx::Format::DEPTH_STENCIL) { + auto dsSlot = getDepthStencilSlot(fgRenderpassInfo.uniqueRasterViewCount, fgRenderpassInfo.resolveCount, hasDS); + if (sortKey.accessType != AccessType::WRITE) { + subpassInfo.inputs.emplace_back(dsSlot); + } + if (sortKey.accessType != AccessType::READ) { + subpassInfo.depthStencil = dsSlot; + } + } else { + if (sortKey.accessType != AccessType::WRITE) { + subpassInfo.inputs.emplace_back(cIndex); + } + if (sortKey.accessType != AccessType::READ) { + subpassInfo.colors.emplace_back(cIndex); + } - std::queue rhsSection; - for (size_t i = 1; i < rhsVerts.size(); ++i) { - auto tryE = edge(rhsVerts[i], rhsVerts[i - 1], relationGraphTc); - auto tryRE = edge(rhsVerts[i - 1], rhsVerts[i], relationGraphTc); - if (!tryE.second && !tryRE.second) { - remove_edge(rhsVerts[i - 1], rhsVerts[i], relationGraph); - candidateSections.emplace_back(rhsSection); - std::queue clearQ; - rhsSection.swap(clearQ); + if (sortKey.accessType == AccessType::READ_WRITE) { + auto &selfDependency = dependencies.emplace_back(); + selfDependency.srcSubpass = pass.subpassID; + selfDependency.dstSubpass = pass.subpassID; + selfDependency.prevAccesses = pair.second.access.nextAccess; + selfDependency.nextAccesses = pair.second.access.nextAccess; + } } - auto e = edge(rhsVerts[i], rhsVerts[i - 1], relationGraph); - // verts comes in order, so either real edge exist or logic edge is added. - CC_ASSERT(e.second); - rhsSection.emplace(e.first); } - // lhs verts already put in. - if (candidateSections.size() == 1) { - remove_edge(rhsVerts[0], rhsVerts[1], relationGraph); - remove_edge(rhsVerts[rhsVerts.size() - 2], rhsVerts[rhsVerts.size() - 1], relationGraph); - candidateSections.emplace_back(std::move(rhsSection)); - } - - assert(candidateSections.size() >= 2); - - ScoreMap scMap; - auto tailVert = lhsVerts[0]; - while (!candidateSections.empty()) { - int64_t lightest = std::numeric_limits::max(); - uint32_t index = 0; - for (size_t i = 0; i < candidateSections.size(); ++i) { - auto e = candidateSections[i].front(); - auto srcVert = source(e, relationGraph); - auto dstVert = target(e, relationGraph); - int64_t srcBackwardScore = 0; - int64_t dstForwardScore = 0; - if (scMap.find(srcVert) == scMap.end()) { - auto res = evaluate(srcVert, false); - srcBackwardScore = std::get<1>(res); - res = evaluate(srcVert, true); - auto srcForwardScore = std::get<1>(res); - scMap.emplace(srcVert, std::pair(srcBackwardScore, srcForwardScore)); - } else { - srcBackwardScore = std::get<0>(scMap.at(srcVert)); - } - if (scMap.find(dstVert) == scMap.end()) { - auto res = evaluate(dstVert, false); - dstForwardScore = std::get<1>(res); - res = evaluate(dstVert, true); - auto dstBackwardScore = std::get<1>(res); - scMap.emplace(dstVert, std::pair(dstBackwardScore, dstForwardScore)); - } else { - dstForwardScore = std::get<1>(scMap.at(dstVert)); + if (hasDep) { + auto &dependency = dependencies.emplace_back(); + auto lastIter = ++resourceAccessGraph.resourceAccess[name.data()].rbegin(); + bool isBuffer = desc.dimension == ResourceDimension::BUFFER; + if (accessDependent(lastIter->second.accessFlag, accessNode.resourceStatus.at(name.data()).accessFlag, isBuffer) && lastIter->second.accessFlag != gfx::AccessFlagBit::NONE) { + auto lastVert = lastIter->first; + auto lastPassID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, lastVert); + auto lastPassIndex = INVALID_ID; + if (holds(lastPassID, renderGraph) && (parent(lastPassID, renderGraph) == parentID)) { + const auto *lastPass = get_if(lastPassID, &renderGraph); + lastPassIndex = lastPass->subpassID; } - // we are in a simple path, so all the "input(this path)" resource of this path come from the first vertex, - // all the "output(this path)" come to the last vertex, other resources are "internally(this path)" produced and destroyed. - // so only input of first vertex and output of last vertex are taken into account. - // [simple path]: path without diverged edges. - auto score = dstForwardScore - srcBackwardScore; - if (lightest > score) { - lightest = score; - index = i; - } - } - auto e = candidateSections[index].front(); - candidateSections[index].pop(); - if (candidateSections[index].empty()) { - auto iter = candidateSections.begin(); - std::advance(iter, index); - candidateSections.erase(iter); + auto &dependency = dependencies.emplace_back(); + dependency.srcSubpass = lastPassIndex; + dependency.dstSubpass = pass.subpassID; + dependency.prevAccesses = lastIter->second.accessFlag; + dependency.nextAccesses = pair.second.access.nextAccess; } - auto srcVert = source(e, relationGraph); - auto dstVert = target(e, relationGraph); - tryAddEdge(tailVert, srcVert, relationGraph); - tailVert = dstVert; } - - tryAddEdge(tailVert, lhsVerts.back(), relationGraph); } } -// return : can be further reduced? -bool reduce(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, RelationGraph &relationGraphTc, const CloseCircuit &circuit) { - auto checkPath = [&relationGraph](std::stack &vertices, RelationGraph::vertex_descriptor endVert, RelationVerts &stackTrace) { - bool simpleGraph = true; - while (!vertices.empty()) { - auto vert = vertices.top(); - vertices.pop(); - stackTrace.emplace_back(vert); +void startComputeSubpass(const Graphs &graphs, uint32_t passID, const ComputeSubpass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; - if (endVert == vert) { - break; - } + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - if (out_degree(vert, relationGraph) > 1) { - simpleGraph = false; - break; - } - auto r = out_edges(vert, relationGraph); - for (auto rIter = r.first; rIter != r.second; ++rIter) { - auto dstID = target(*rIter, relationGraph); - vertices.push(dstID); - } - if (r.first == r.second) { - stackTrace.pop_back(); - } - } - return simpleGraph; - }; + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + AttachmentMap colorMap(resourceAccessGraph.get_allocator()); - // check if there is a sub branch on lhs - auto lhsEdges = circuit.first; - auto startVert = target(lhsEdges.first, relationGraph); - auto endVert = source(lhsEdges.second, relationGraph); - - std::stack vertices; - vertices.emplace(startVert); + auto parentID = parent(passID, renderGraph); + auto parentRagVertID = resourceAccessGraph.passIndex.at(parentID); + auto &fgRenderpassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, parentRagVertID); - RelationVerts lhsVisited; - auto branchStartVert = source(lhsEdges.first, relationGraph); - auto branchEndVert = target(lhsEdges.second, relationGraph); - lhsVisited.push_back(branchStartVert); - // check if there is a branch on lhs path - if (!checkPath(vertices, endVert, lhsVisited)) { - return false; - } - lhsVisited.push_back(branchEndVert); - // if it's a simple graph, lhs path must can be dfs to the end at the first time. - assert(vertices.empty()); + std::ignore = checkRasterViews(graphs, rlgVertID, accessNode, pass.rasterViews, colorMap); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); - auto rhsEdges = circuit.second; - startVert = target(rhsEdges.first, relationGraph); - endVert = source(rhsEdges.second, relationGraph); - vertices.emplace(startVert); + fillRenderPassInfo(colorMap, fgRenderpassInfo, resourceGraph); +} - RelationVerts rhsVisited; - rhsVisited.push_back(branchStartVert); - if (!checkPath(vertices, endVert, rhsVisited)) { - return false; - } - rhsVisited.push_back(branchEndVert); +void startComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; - // merge this circuit - // from - /* 2 - 3 - 4 - / \ - 1 8 - \ / - 5 - 6 - 7 + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - to - 1 - A - B - 8 or 1 - B - A -8 depends on algorithm + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); +} - ${A} : 2 - 3 - 4 - ${B} : 5 - 6 - 7 - */ +void startCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; - evaluateAndTryMerge(rag, rescGraph, relationGraph, relationGraphTc, lhsVisited, rhsVisited); + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); - return true; -} + auto &resg = resourceGraph; + auto &rag = resourceAccessGraph; + auto &rlg = relationGraph; + auto checkCopy = [&](const ccstd::pmr::string &resName, + uint32_t firstSlice, + uint32_t firstMip, + uint32_t firstPlane, + uint32_t sliceCount, + uint32_t mipCount, + bool read) { + auto srcID = vertex(resName, resg); + auto srcRange = getResourceRange(srcID, resg); + srcRange.firstSlice = firstSlice; + srcRange.mipLevel = firstMip; + srcRange.basePlane = firstPlane; + srcRange.numSlices = sliceCount; + srcRange.levelCount = mipCount; + + AccessType access = read ? AccessType::READ : AccessType::WRITE; + gfx::AccessFlags accessFlag = read ? gfx::AccessFlags::TRANSFER_READ : gfx::AccessFlags::TRANSFER_WRITE; + ViewStatus srcViewStatus{resName, access, gfx::ShaderStageFlagBit::NONE, accessFlag, srcRange}; + addAccessStatus(rag, resg, accessNode, srcViewStatus); + const auto &[lastVertSrc, ignore1] = dependencyCheck(rag, vertID, resg, srcViewStatus); + tryAddEdge(lastVertSrc, vertID, rag); + tryAddEdge(lastVertSrc, rlgVertID, rlg); + }; -template -void applyRelation(RelationGraph &relationGraph, const TargetGraph &targetGraph) { - CC_EXPECTS(relationGraph.vertices.size() == targetGraph.vertices.size()); + for (const auto © : pass.copyPairs) { + checkCopy(copy.source, + copy.sourceFirstSlice, copy.sourceMostDetailedMip, copy.sourcePlaneSlice, + copy.numSlices, copy.mipLevels, true); - // remove all edges - for (auto vert : targetGraph.vertices) { - clear_in_edges(vert, targetGraph); - clear_out_edges(vert, targetGraph); + checkCopy(copy.target, + copy.targetFirstSlice, copy.targetMostDetailedMip, copy.targetPlaneSlice, + copy.numSlices, copy.mipLevels, false); } - for (auto vert : relationGraph.vertices) { - auto inEdges = in_edges(vert, relationGraph); - for (auto e : makeRange(inEdges)) { - auto srcVert = source(e, relationGraph); - // auto checkEdge = edge(srcVert, vert, targetGraph); - add_edge(srcVert, vert, targetGraph); - } + for (const auto &upload : pass.uploadPairs) { + checkCopy(upload.target, + upload.targetFirstSlice, upload.targetMostDetailedMip, upload.targetPlaneSlice, + upload.numSlices, upload.mipLevels, false); } } -void passReorder(FrameGraphDispatcher &fgDispatcher) { - auto *scratch = fgDispatcher.scratch; - const auto &renderGraph = fgDispatcher.graph; - const auto &layoutGraph = fgDispatcher.layoutGraph; - auto &resourceGraph = fgDispatcher.resourceGraph; - auto &relationGraph = fgDispatcher.relationGraph; - auto &rag = fgDispatcher.resourceAccessGraph; +void startRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; - if (!fgDispatcher._accessGraphBuilt) { - const Graphs graphs{renderGraph, resourceGraph, layoutGraph, rag, relationGraph}; - buildAccessGraph(graphs); - fgDispatcher._accessGraphBuilt = true; - } + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - { - // determine do mem saving how many times - RelationGraph relationGraphTc(fgDispatcher.get_allocator()); - boost::transitive_closure(relationGraph, relationGraphTc); + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); +} - CloseCircuits circuits; - std::vector crossEdges; - PassVisitor visitor(relationGraphTc, circuits); - auto colors = relationGraph.colors(scratch); - boost::depth_first_search(relationGraph, visitor, get(colors, relationGraph)); +namespace { +struct SliceNode { + bool full{false}; + ccstd::pmr::vector mips; +}; - float percent = 0.0F; - uint32_t count = 0; - auto total = circuits.size(); +struct TextureNode { + bool full{false}; + ccstd::pmr::vector slices; +}; - float memsavePercent = 1.0F - fgDispatcher._paralellExecWeight; - for (auto iter = circuits.begin(); (iter != circuits.end()) && (percent < memsavePercent);) { - bool reduced = reduce(rag, resourceGraph, relationGraph, relationGraphTc, (*iter)); - if (reduced) { - ++count; - iter = circuits.erase(iter); - percent = count / static_cast(total); - } else { - ++iter; +struct ResourceNode { + ccstd::pmr::vector planes; +}; +} // namespace + +bool rangeCheck(ccstd::pmr::map &status, + const ResourceDesc &desc, + const PmrString &targetName, + uint32_t firstSlice, uint32_t numSlices, + uint32_t firstMip, uint32_t mipLevels, + uint32_t planeIndex) { + if (status.find(targetName) == status.end()) { + status.emplace(targetName, ResourceNode{}); + } + + if (planeIndex >= status[targetName].planes.size()) { + status[targetName].planes.resize(planeIndex + 1); + status[targetName].planes[planeIndex].slices.resize(desc.depthOrArraySize); + for (auto &slice : status[targetName].planes[planeIndex].slices) { + slice.mips.resize(desc.mipLevels, std::numeric_limits::max()); + } + } + + // no spare space in target + bool check = !status[targetName].planes[planeIndex].full; + for (auto slice = firstSlice; slice < firstSlice + numSlices; ++slice) { + auto &slices = status[targetName].planes[planeIndex].slices; + // no spare space in this slice + check &= !slices[slice].full; + for (auto mip = firstMip; mip < firstMip + mipLevels; ++mip) { + auto &mips = slices[slice].mips; + // this mip has been taken + check &= mips[mip] == std::numeric_limits::max(); + mips[mip] = mip; + auto maxIter = std::max_element(mips.begin(), mips.end()); + if ((*maxIter) != std::numeric_limits::max()) { + // linear increasing + check &= (*maxIter) == mips.size() - 1; + slices[slice].full = true; } } + if (std::all_of(slices.begin(), slices.end(), [](const SliceNode &sliceNode) { return sliceNode.full; })) { + status[targetName].planes[planeIndex].full = true; + } + } + return check; +} - // topological sort - rag.topologicalOrder.clear(); - bool empty = relationGraph._vertices.empty(); - ScoreMap scoreMap; - RelationVerts candidates; - candidates.push_back(EXPECT_START_ID); - - std::vector candidateBuffer; - uint32_t coloredVerts = 0; - while (coloredVerts < relationGraph._vertices.size()) { - // decreasing order, pop back from vector, push into queue, then it's ascending order. - std::sort(candidates.begin(), candidates.end(), [&](RelationVert lhsVert, RelationVert rhsVert) { - int64_t lhsForwardScore{0}; - int64_t rhsForwardScore{0}; - int64_t lhsBackwardScore{0}; - int64_t rhsBackwardScore{0}; - if (scoreMap.find(lhsVert) == scoreMap.end()) { - auto lhsRagVert = get(RelationGraph::DescIDTag{}, relationGraph, lhsVert); - const auto &lhsForwardStatus = evaluateHeaviness(rag, resourceGraph, lhsRagVert, true); - lhsForwardScore = get<1>(lhsForwardStatus); - const auto &lhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, lhsRagVert, false); - lhsBackwardScore = get<1>(lhsBackwardStatus); - scoreMap.emplace(lhsVert, std::pair{lhsBackwardScore, lhsForwardScore}); - } else { - lhsBackwardScore = scoreMap[lhsVert].first; - lhsForwardScore = scoreMap[lhsVert].second; +bool moveValidation(const MovePass& pass, ResourceAccessGraph& rag, const ResourceGraph& resourceGraph) { + bool check = true; + // ccstd::pmr::map sourceCheck; + ccstd::pmr::map targetCheck; + for (const auto &movePair : pass.movePairs) { + const auto &fromResName = movePair.source; + const auto fromResID = resourceGraph.valueIndex.at(fromResName); + const auto &fromResDesc = get(ResourceGraph::DescTag{}, resourceGraph, fromResID); + + const auto &toResName = movePair.target; + const auto toResID = resourceGraph.valueIndex.at(toResName); + const auto &toResDesc = get(ResourceGraph::DescTag{}, resourceGraph, toResID); + + const auto &fromResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, fromResID); + const auto &toResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, toResID); + auto commonUsage = fromResDesc.flags | toResDesc.flags; + + // bool sourceRangeValid = rangeCheck(targetCheck, toResDesc, fromResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); + bool targetRangeValid = rangeCheck(targetCheck, toResDesc, toResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); + + uint32_t validConditions[] = { + !fromResTraits.hasSideEffects(), + rag.movedSourceStatus.find(toResName) == rag.movedSourceStatus.end(), + rag.movedSourceStatus.find(fromResName) == rag.movedSourceStatus.end(), + targetRangeValid, + fromResTraits.residency != ResourceResidency::MEMORYLESS && toResTraits.residency != ResourceResidency::MEMORYLESS, + fromResDesc.dimension == toResDesc.dimension, + fromResDesc.width == toResDesc.width, + fromResDesc.height == toResDesc.height, + fromResDesc.format == toResDesc.format, + fromResDesc.sampleCount == toResDesc.sampleCount, + (fromResDesc.depthOrArraySize == toResDesc.depthOrArraySize) || (toResDesc.dimension != ResourceDimension::BUFFER), // full move if resource is buffer + }; + bool val = std::min_element(std::begin(validConditions), std::end(validConditions)); + check &= val; + } + + // full destination + check &= std::all_of(targetCheck.begin(), targetCheck.end(), [](const auto &pair) { + const ResourceNode &resNode = pair.second; + return std::all_of(resNode.planes.begin(), resNode.planes.end(), [](const auto &textureNode) { + return textureNode.full; + }); + }); + + return check; + } + +void startMovePass(const Graphs &graphs, uint32_t passID, const MovePass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + if(moveValidation(pass, resourceAccessGraph, resourceGraph)) { + for(const auto& pair : pass.movePairs) { + auto srcResourceRange = getResourceRange(vertex(pair.source, resourceGraph), resourceGraph); + srcResourceRange.firstSlice = pair.targetFirstSlice; + srcResourceRange.mipLevel = pair.targetMostDetailedMip; + srcResourceRange.basePlane = pair.targetPlaneSlice; + + auto lastStatusIter = resourceAccessGraph.resourceAccess.at(pair.source).rbegin(); + resourceAccessGraph.movedSourceStatus.emplace(pair.source, AccessStatus{lastStatusIter->second.accessFlag, srcResourceRange}); + resourceAccessGraph.movedTarget[pair.target].emplace_back(pair.source); + resourceAccessGraph.resourceAccess[pair.target] = resourceAccessGraph.resourceAccess[pair.source]; + + auto targetResID = findVertex(pair.target, resourceGraph); + resourceAccessGraph.resourceIndex[pair.target] = targetResID; + + auto &rag = resourceAccessGraph; + std::function feedBack = [&](const ccstd::pmr::string &source, ResourceGraph::vertex_descriptor v) { + rag.resourceIndex[source] = v; + if (rag.movedTarget.find(source) != rag.movedTarget.end()) { + for (const auto &prt : rag.movedTarget[source]) { + feedBack(prt, v); + } } + }; + feedBack(pair.source, targetResID); + } + } else { + for(const auto& pair : pass.movePairs) { + CopyPass copyPass(resourceAccessGraph.get_allocator()); + copyPass.copyPairs.emplace_back(CopyPair( + pair.source, + pair.target, + pair.mipLevels, pair.numSlices, + 0, 0, 0, + pair.targetMostDetailedMip, pair.targetFirstSlice, pair.targetPlaneSlice)); + startCopyPass(graphs, passID, copyPass); + } + } +} - if (scoreMap.find(rhsVert) == scoreMap.end()) { - auto rhsRagVert = get(RelationGraph::DescIDTag{}, relationGraph, rhsVert); - const auto &rhsForwardStatus = evaluateHeaviness(rag, resourceGraph, rhsRagVert, true); - rhsForwardScore = get<1>(rhsForwardStatus); - const auto &rhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, rhsRagVert, false); - rhsBackwardScore = get<1>(rhsBackwardStatus); - scoreMap.emplace(rhsVert, std::pair{rhsBackwardScore, rhsForwardScore}); - } else { - rhsBackwardScore = scoreMap[rhsVert].first; - rhsForwardScore = scoreMap[rhsVert].second; - } - return lhsBackwardScore - lhsForwardScore > rhsBackwardScore - rhsForwardScore; +struct DependencyVisitor : boost::dfs_visitor<> { + void discover_vertex(RenderGraph::vertex_descriptor passID, + const AddressableView &gv) const { + visitObject( + passID, gv.mGraph, + [&](const RasterPass &pass) { + startRenderPass(graphs, passID, pass); + }, + [&](const RasterSubpass &pass) { + startRenderSubpass(graphs, passID, pass); + }, + [&](const ComputeSubpass &pass) { + startComputeSubpass(graphs, passID, pass); + }, + [&](const ComputePass &pass) { + startComputePass(graphs, passID, pass); + }, + [&](const CopyPass &pass) { + startCopyPass(graphs, passID, pass); + }, + [&](const MovePass &pass) { + startMovePass(graphs, passID, pass); + }, + [&](const RaytracePass &pass) { + startRaytracePass(graphs, passID, pass); + }, + [&](const auto & /*pass*/) { + // do nothing }); + } - const auto vert = candidates.back(); - candidates.pop_back(); + void finish_vertex(RenderGraph::vertex_descriptor passID, + const AddressableView &gv) const { + visitObject( + passID, gv.mGraph, + [&](const RasterPass &pass) { + endRenderPass(graphs, passID, pass); + }, + [&](const auto & /*pass*/) { + // do nothing + }); + } - auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, vert); - rag.topologicalOrder.emplace_back(ragVert); - if (!candidateBuffer.empty()) { - candidates.insert(candidates.end(), candidateBuffer.begin(), candidateBuffer.end()); - candidateBuffer.clear(); - } + const Graphs &graphs; +}; - for (const auto nextGeneration : makeRange(out_edges(vert, relationGraph))) { - auto targetID = target(nextGeneration, relationGraph); - if (in_degree(targetID, relationGraph) == 1) { - candidateBuffer.emplace_back(targetID); - } - } +// status of resource access +void buildAccessGraph(const Graphs &graphs) { + // what we need: + // - pass dependency + // - pass attachment access + // AccessTable accessRecord; - auto deprecatedEdges = out_edges(vert, relationGraph); - for (auto iter = deprecatedEdges.first; iter < deprecatedEdges.second;) { - remove_edge(*iter, relationGraph); - deprecatedEdges = out_edges(vert, relationGraph); - iter = deprecatedEdges.first; - } + const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + size_t numPasses = 0; + numPasses += renderGraph.rasterPasses.size(); + numPasses += renderGraph.computePasses.size(); + numPasses += renderGraph.copyPasses.size(); + numPasses += renderGraph.movePasses.size(); + numPasses += renderGraph.raytracePasses.size(); - if (candidates.empty()) { - candidates.insert(candidates.end(), candidateBuffer.begin(), candidateBuffer.end()); - candidateBuffer.clear(); - } + resourceAccessGraph.reserve(static_cast(numPasses)); + resourceAccessGraph.resourceNames.reserve(128); + resourceAccessGraph.resourceIndex.reserve(128); - coloredVerts++; - } + resourceAccessGraph.topologicalOrder.reserve(numPasses); + resourceAccessGraph.topologicalOrder.clear(); + resourceAccessGraph.resourceLifeRecord.reserve(resourceGraph.names.size()); - // remove all edges - for (auto vert : makeRange(vertices(rag))) { - clear_in_edges(vert, rag); - clear_out_edges(vert, rag); - } + if (!resourceAccessGraph.resourceLifeRecord.empty()) { + resourceAccessGraph.resourceLifeRecord.clear(); + } - // apply relation - for (auto rlgVert : makeRange(vertices(relationGraph))) { - auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, rlgVert); - auto inEdges = in_edges(rlgVert, relationGraph); - for (auto e : makeRange(inEdges)) { - auto srcRlgVert = source(e, relationGraph); - auto srcRagVert = get(RelationGraph::DescIDTag{}, relationGraph, srcRlgVert); - add_edge(srcRagVert, ragVert, rag); - } - } + if (!resourceAccessGraph.leafPasses.empty()) { + resourceAccessGraph.leafPasses.clear(); + } + if (!resourceAccessGraph.culledPasses.empty()) { + resourceAccessGraph.culledPasses.clear(); } -} -#pragma endregion PASS_REORDER + // const auto &names = get(RenderGraph::Name, renderGraph); + for (size_t i = 1; i <= numPasses; ++i) { + resourceAccessGraph.leafPasses.emplace(i, LeafStatus{false, true}); + } -void memoryAliasing(FrameGraphDispatcher &fgDispatcher) { -} + auto startID = add_vertex(resourceAccessGraph, INVALID_ID - 1); + CC_EXPECTS(startID == EXPECT_START_ID); -#pragma region assisstantFuncDefinition -template -bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph) { - auto e = edge(srcVertex, dstVertex, graph); - if (!e.second) { - auto res = add_edge(srcVertex, dstVertex, graph); - CC_ENSURES(res.second); - return true; - } - return false; -} - -bool isTransitionStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs) { - return !(isReadOnlyAccess(lhs.accessFlag) && isReadOnlyAccess(rhs.accessFlag)); -} - -auto mapTextureFlags(ResourceFlags flags) { - gfx::TextureUsage usage = gfx::TextureUsage::NONE; - if ((flags & ResourceFlags::SAMPLED) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::SAMPLED; - } - if ((flags & ResourceFlags::STORAGE) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::STORAGE; - } - if ((flags & ResourceFlags::SHADING_RATE) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::SHADING_RATE; - } - if ((flags & ResourceFlags::COLOR_ATTACHMENT) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::COLOR_ATTACHMENT; - } - if ((flags & ResourceFlags::DEPTH_STENCIL_ATTACHMENT) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; - } - if ((flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::INPUT_ATTACHMENT; - } - return usage; -} + add_vertex(relationGraph, startID); -auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph, bool rasterized) { - ResourceUsage usage; - gfx::ShaderStageFlags vis{gfx::ShaderStageFlags::NONE}; - vis |= visibility; - gfx::AccessFlags accesFlag; - auto vertex = resourceGraph.valueIndex.at(name); - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex); - if (desc.dimension == ResourceDimension::BUFFER) { - gfx::BufferUsage bufferUsage{gfx::BufferUsage::NONE}; - // copy is not included in this logic because copy can be set TRANSFER_xxx directly. - if (gfx::hasFlag(memAccess, gfx::MemoryAccessBit::WRITE_ONLY)) { - bufferUsage = gfx::BufferUsage::STORAGE; + DependencyVisitor visitor{{}, graphs}; + auto colors = renderGraph.colors(renderGraph.resource()); + AddressableView gv{renderGraph}; + for (const auto passID : renderGraph.sortedVertices) { + if (!holds(passID, renderGraph) && !holds(passID, renderGraph)) { + boost::depth_first_visit(gv, passID, visitor, get(colors, renderGraph)); } + } - if (gfx::hasFlag(memAccess, gfx::MemoryAccessBit::READ_ONLY)) { - bool uniformFlag = (desc.flags & ResourceFlags::UNIFORM) != ResourceFlags::NONE; - bool storageFlag = (desc.flags & ResourceFlags::STORAGE) != ResourceFlags::NONE; - - // CC_EXPECTS(uniformFlag ^ storageFlag); - // uniform or read-only storage buffer - bufferUsage = uniformFlag ? gfx::BufferUsage::UNIFORM : gfx::BufferUsage::STORAGE; - } + auto &rag = resourceAccessGraph; + auto branchCulling = [](ResourceAccessGraph::vertex_descriptor vertex, ResourceAccessGraph &rag) -> void { + CC_EXPECTS(out_degree(vertex, rag) == 0); + using FuncType = void (*)(ResourceAccessGraph::vertex_descriptor, ResourceAccessGraph &); + static FuncType leafCulling = [](ResourceAccessGraph::vertex_descriptor vertex, ResourceAccessGraph &rag) { + rag.culledPasses.emplace(vertex); + auto &attachments = get(ResourceAccessGraph::PassNodeTag{}, rag, vertex); + attachments.resourceStatus.clear(); + auto inEdges = in_edges(vertex, rag); + for (auto iter = inEdges.first; iter < inEdges.second;) { + auto inEdge = *iter; + auto srcVert = source(inEdge, rag); + remove_edge(inEdge, rag); + if (out_degree(srcVert, rag) == 0) { + leafCulling(srcVert, rag); + } + inEdges = in_edges(vertex, rag); + iter = inEdges.first; + } + }; + leafCulling(vertex, rag); + }; - if (passType == PassType::COMPUTE) { - vis |= gfx::ShaderStageFlagBit::COMPUTE; + // no present pass found, add a fake node to gather leaf node(s). + if (resourceAccessGraph.presentPassID == 0xFFFFFFFF) { + auto ragEndNode = add_vertex(rag, RenderGraph::null_vertex()); + auto rlgEndNode = add_vertex(relationGraph, ragEndNode); + // keep sync before pass reorder done. + CC_EXPECTS(ragEndNode == rlgEndNode); + resourceAccessGraph.presentPassID = ragEndNode; + auto iter = resourceAccessGraph.leafPasses.find(ragEndNode); + constexpr bool isExternal = true; + constexpr bool needCulling = false; + if (iter == resourceAccessGraph.leafPasses.end()) { + resourceAccessGraph.leafPasses.emplace(ragEndNode, LeafStatus{isExternal, needCulling}); + } else { + resourceAccessGraph.leafPasses.at(ragEndNode) = LeafStatus{isExternal, needCulling}; } + } - // those buffers not found in descriptorlayout but appear here, - // can and only can be VERTEX/INDEX/INDIRECT BUFFER, - // only copy pass is allowed. - if (vis == gfx::ShaderStageFlags::NONE) { - CC_EXPECTS(passType == PassType::COPY); - } - usage = bufferUsage; - accesFlag = gfx::getAccessFlags(bufferUsage, gfx::MemoryUsage::DEVICE, memAccess, vis); - } else { - // can't find this resource in layoutdata, not in descriptor so either input or output attachment. - gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; + // make leaf node closed walk for pass reorder + for (auto pass : resourceAccessGraph.leafPasses) { + bool isExternal = pass.second.isExternal; + bool needCulling = pass.second.needCulling; - // TODO(Zeqiang): visbility of slot name "_" not found - if (hasFlag(memAccess, gfx::MemoryAccess::READ_ONLY)) { - if ((desc.flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE && rasterized) { - texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::INPUT_ATTACHMENT)); + if (pass.first != resourceAccessGraph.presentPassID) { + if (isExternal && !needCulling) { + add_edge(pass.first, resourceAccessGraph.presentPassID, resourceAccessGraph); } else { - texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::SAMPLED | gfx::TextureUsage::STORAGE | gfx::TextureUsage::SHADING_RATE | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT)); + // write into transient resources, culled + if constexpr (ENABLE_BRANCH_CULLING) { + branchCulling(pass.first, resourceAccessGraph); + } } } - - if (hasFlag(memAccess, gfx::MemoryAccess::WRITE_ONLY)) { - texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::STORAGE)); - } - - if (vis == gfx::ShaderStageFlags::NONE) { - vis = passType == gfx::PassType::RASTER ? gfx::ShaderStageFlags::FRAGMENT : gfx::ShaderStageFlags::COMPUTE; - } - - usage = texUsage; - accesFlag = gfx::getAccessFlags(texUsage, memAccess, vis); } - - return std::make_tuple(vis, usage, accesFlag); -} - -void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range) { - const auto &[name, passType, visibility, access, accessFlag, usage] = status; - CC_EXPECTS(hasAnyFlags(accessFlag, gfx::AccessFlags::TRANSFER_READ | gfx::AccessFlags::TRANSFER_WRITE)); - - uint32_t rescID = rg.valueIndex.at(name); - - CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); - if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { - rag.resourceIndex.emplace(name, rescID); - rag.resourceNames.emplace_back(name); + for (auto rit = resourceAccessGraph.culledPasses.rbegin(); rit != resourceAccessGraph.culledPasses.rend(); ++rit) { + // remove culled vertices, std::less make this set ascending order, so reverse iterate + remove_vertex(*rit, relationGraph); } - node.attachmentStatus.emplace_back(AccessStatus{ - rescID, - visibility, - access, - passType, - accessFlag, - usage, - range, - }); + for (auto rlgVert : makeRange(vertices(relationGraph))) { + auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, rlgVert); + rag.topologicalOrder.emplace_back(ragVert); + } } -PmrString addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status) { - const auto &[name, passType, visibility, access, accessFlag, usage] = status; - uint32_t rescID = rg.valueIndex.at(name); - const auto &resourceDesc = get(ResourceGraph::DescTag{}, rg, rescID); - const auto &traits = get(ResourceGraph::TraitsTag{}, rg, rescID); - // const PmrString *resName = &name; - - Range range; - if (resourceDesc.dimension == ResourceDimension::BUFFER) { - range = BufferRange{0, resourceDesc.width}; - } else { - range = TextureRange{0, 1, 0, resourceDesc.mipLevels}; - } +#pragma region BUILD_BARRIERS +void buildBarriers(FrameGraphDispatcher &fgDispatcher) { + auto *scratch = fgDispatcher.scratch; + const auto &renderGraph = fgDispatcher.renderGraph; + const auto &layoutGraph = fgDispatcher.layoutGraph; + auto &resourceGraph = fgDispatcher.resourceGraph; + auto &relationGraph = fgDispatcher.relationGraph; + auto &rag = fgDispatcher.resourceAccessGraph; - CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); - if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { - rag.resourceIndex.emplace(name, rescID); - rag.resourceNames.emplace_back(name); + // record resource current in-access and out-access for every single node + if (!fgDispatcher._accessGraphBuilt) { + const Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; + buildAccessGraph(graphs); + fgDispatcher._accessGraphBuilt = true; } - node.attachmentStatus.emplace_back(AccessStatus{ - rescID, - visibility, - access, - passType, - accessFlag, - usage, - range, - }); - return name; -} - -AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGraph &rg, const ViewStatus &viewStatus) { - const auto &[name, passType, visibility, access, accessFlag, usage] = viewStatus; - auto &accessRecord = rag.accessRecord; - - bool readOnly = isReadOnlyAccess(accessFlag); + auto getGFXBarrier = [&resourceGraph](const Barrier &barrier) { + gfx::GFXObject *gfxBarrier{nullptr}; + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, barrier.resourceID); + if (desc.dimension == ResourceDimension::BUFFER) { + gfx::BufferBarrierInfo info; + info.prevAccesses = barrier.beginStatus.accessFlag; + info.nextAccesses = barrier.endStatus.accessFlag; + const auto &range = barrier.endStatus.range; + info.offset = 0; + info.size = range.depthOrArraySize; + info.type = barrier.type; + gfxBarrier = gfx::Device::getInstance()->getBufferBarrier(info); + } else { + gfx::TextureBarrierInfo info; + info.prevAccesses = barrier.beginStatus.accessFlag; + info.nextAccesses = barrier.endStatus.accessFlag; + const auto &range = barrier.beginStatus.range; + info.baseMipLevel = range.mipLevel; + info.levelCount = range.levelCount; + info.baseSlice = range.firstSlice; + info.sliceCount = range.numSlices; + info.type = barrier.type; + gfxBarrier = gfx::Device::getInstance()->getTextureBarrier(info); + } + return gfxBarrier; + }; - AccessVertex lastVertID = INVALID_ID; - CC_EXPECTS(rag.resourceIndex.find(name) != rag.resourceIndex.end()); - auto resourceID = rag.resourceIndex[name]; - bool isExternalPass = get(get(ResourceGraph::TraitsTag{}, rg), resourceID).hasSideEffects(); - auto iter = accessRecord.find(resourceID); - if (iter == accessRecord.end()) { - accessRecord.emplace( - resourceID, - ResourceTransition{ - {}, - {curVertID, visibility, access, passType, accessFlag, usage, Range{}}}); - if (isExternalPass) { - rag.leafPasses[curVertID] = LeafStatus{true, access == gfx::MemoryAccessBit::READ_ONLY}; + // found pass id in this map ? barriers you should commit when run into this pass + // : or no extra barrier needed. + for (auto &accessPair : rag.resourceAccess) { + const auto &resName = accessPair.first; + if (rag.movedSourceStatus.find(resName) != rag.movedSourceStatus.end()) { + // moved, history of this resource access will be copied to moved target. + continue; } - } else { - ResourceTransition &trans = iter->second; - auto &currAccessStatus = trans.currStatus; - auto lastReadOnly = isReadOnlyAccess(currAccessStatus.accessFlag) && (currAccessStatus.access == gfx::MemoryAccessBit::READ_ONLY); - if (readOnly && lastReadOnly) { - if (isExternalPass) { - // only external res will be manually record here, leaf pass with transient resource will be culled by default, - // those leaf passes with ALL read access on external(or with transients) res can be culled. - rag.leafPasses[curVertID].needCulling &= (access == gfx::MemoryAccessBit::READ_ONLY); - - // current READ, no WRITE before in this frame, it's expected to be external. - bool dirtyExternalRes = trans.lastStatus.vertID == INVALID_ID; - if (!dirtyExternalRes) { - tryAddEdge(EXPECT_START_ID, curVertID, rag); - if (rag.leafPasses.find(EXPECT_START_ID) != rag.leafPasses.end()) { - rag.leafPasses.erase(EXPECT_START_ID); - } - } - } else { - tryAddEdge(trans.lastStatus.vertID, curVertID, rag); - if (rag.leafPasses.find(trans.lastStatus.vertID) != rag.leafPasses.end()) { - rag.leafPasses.erase(trans.lastStatus.vertID); + + const auto &resID = findVertex(resName, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + bool isBuffer = desc.dimension == ResourceDimension::BUFFER; + + const auto &accessRecord = accessPair.second; + auto iter = accessRecord.begin(); + auto nextIter = iter; + std::advance(nextIter, 1); + for (; nextIter != accessRecord.end(); ++iter, ++nextIter) { + auto srcRagVertID = iter->first; + auto dstRagVertID = nextIter->first; + auto srcPassID = get(ResourceAccessGraph::PassIDTag{}, rag, srcRagVertID); + auto dstPassID = get(ResourceAccessGraph::PassIDTag{}, rag, dstRagVertID); + + if (holds(dstPassID, renderGraph) || holds(dstPassID, renderGraph)) { + const auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, rag, dstRagVertID); + if (fgRenderPassInfo.viewIndex.find(resName) != fgRenderPassInfo.viewIndex.end()) { + // renderpass info instead + continue; } } - trans.currStatus = {curVertID, visibility, access, passType, accessFlag, usage, Range{}}; - lastVertID = trans.lastStatus.vertID; - } else { - // avoid subpass self depends - if (trans.currStatus.vertID != curVertID) { - lastVertID = trans.currStatus.vertID; - trans.lastStatus = trans.currStatus; - trans.currStatus = {curVertID, visibility, access, passType, accessFlag, usage, Range{}}; - if (rag.leafPasses.find(trans.lastStatus.vertID) != rag.leafPasses.end()) { - rag.leafPasses.erase(trans.lastStatus.vertID); + + // subpass layout transition + if ((srcRagVertID != 0) && (holds(srcPassID, renderGraph) || holds(srcPassID, renderGraph))) { + auto ragVertID = srcRagVertID; + if (holds(srcPassID, renderGraph)) { + auto parentID = parent(srcPassID, renderGraph); + ragVertID = rag.passIndex.at(parentID); } - if (rag.leafPasses.find(curVertID) != rag.leafPasses.end()) { - // only write into externalRes counts - if (isExternalPass) { - // same as above - rag.leafPasses[curVertID].needCulling &= (access == gfx::MemoryAccessBit::READ_ONLY); - } + // RenderPass Info + auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, rag, ragVertID); + std::string_view resName = get(ResourceGraph::NameTag{}, resourceGraph, resID); + auto colorIter = std::find(fgRenderPassInfo.orderedViews.begin(), fgRenderPassInfo.orderedViews.end(), resName); + auto colorIndex = std::distance(fgRenderPassInfo.orderedViews.begin(), colorIter); + if (colorIndex < fgRenderPassInfo.colorAccesses.size()) { + fgRenderPassInfo.colorAccesses[colorIndex].nextAccess = nextIter->second.accessFlag; + } else if (colorIndex == fgRenderPassInfo.colorAccesses.size()) { + fgRenderPassInfo.dsAccess.nextAccess = nextIter->second.accessFlag; + } else if (colorIndex == fgRenderPassInfo.colorAccesses.size() + 1) { + fgRenderPassInfo.dsResolveAccess.nextAccess = nextIter->second.accessFlag; } - } else { - trans.currStatus = {curVertID, visibility, trans.currStatus.access | access, passType, accessFlag, usage, Range{}}; - } - } - } - return lastVertID; -} -gfx::ShaderStageFlagBit getVisibilityByDescName(const RenderGraph &renderGraph, const LGD &lgd, uint32_t passID, const PmrString &resName) { - auto iter = lgd.attributeIndex.find(resName); - if (iter == lgd.attributeIndex.end()) { - iter = lgd.constantIndex.find(resName); - if (iter == lgd.constantIndex.end()) { - // resource not in descriptor: eg. input or output attachment. - return gfx::ShaderStageFlagBit::NONE; - } - } - auto slotID = iter->second; + if (holds(srcPassID, renderGraph) && + accessDependent(iter->second.accessFlag, nextIter->second.accessFlag, isBuffer)) { + const auto *subpass = get_if(srcPassID, &renderGraph); + CC_ASSERT(subpass); + auto subpassID = subpass->subpassID; + auto &dependency = fgRenderPassInfo.rpInfo.dependencies.emplace_back(); + dependency.srcSubpass = subpass->subpassID; + dependency.dstSubpass = INVALID_ID; + dependency.prevAccesses = iter->second.accessFlag; + dependency.nextAccesses = nextIter->second.accessFlag; + } + continue; + } - auto layoutName = get(RenderGraph::LayoutTag{}, renderGraph, passID); - auto layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lgd); - const auto &layout = get(LayoutGraphData::LayoutTag{}, lgd, layoutID); - for (const auto &pair : layout.descriptorSets) { - for (const auto &block : pair.second.descriptorSetLayoutData.descriptorBlocks) { - for (const auto &descriptor : block.descriptors) { - if (descriptor.descriptorID.value == slotID.value) { - return block.visibility; + // undefined access + if (iter == accessRecord.begin()) { + auto &dstBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, dstRagVertID); + auto &firstMeetBarrier = dstBarrierNode.frontBarriers.emplace_back(); + firstMeetBarrier.resourceID = resID; + firstMeetBarrier.type = gfx::BarrierType::FULL; + firstMeetBarrier.beginVert = dstPassID; + firstMeetBarrier.endVert = dstPassID; + firstMeetBarrier.beginStatus = iter->second; + firstMeetBarrier.endStatus = nextIter->second; + firstMeetBarrier.barrier = getGFXBarrier(firstMeetBarrier); + } else if (accessDependent(iter->second.accessFlag, nextIter->second.accessFlag, isBuffer)) { + auto &srcBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, srcRagVertID); + auto &beginBarrier = srcBarrierNode.rearBarriers.emplace_back(); + beginBarrier.resourceID = resID; + beginBarrier.beginVert = srcPassID; + beginBarrier.endVert = dstPassID; + beginBarrier.beginStatus = iter->second; + beginBarrier.endStatus = nextIter->second; + if (isPassExecAdjecent(iter->first, nextIter->first)) { + beginBarrier.type = gfx::BarrierType::FULL; + } else { + beginBarrier.type = gfx::BarrierType::SPLIT_BEGIN; + + auto &dstBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, dstRagVertID); + auto &endBarrier = dstBarrierNode.frontBarriers.emplace_back(); + endBarrier.resourceID = resID; + endBarrier.type = gfx::BarrierType::SPLIT_END; + endBarrier.beginVert = srcPassID; + endBarrier.endVert = dstPassID; + endBarrier.beginStatus = iter->second; + endBarrier.endStatus = nextIter->second; + endBarrier.barrier = getGFXBarrier(endBarrier); } + beginBarrier.barrier = getGFXBarrier(beginBarrier); } } - } - - // unreachable - CC_EXPECTS(false); - return gfx::ShaderStageFlagBit::NONE; -}; - -bool checkRasterViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, PassType passType, ResourceAccessNode &node, const RasterViewsMap &rasterViews) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - bool dependent = false; - - for (const auto &pair : rasterViews) { - const auto &rasterView = pair.second; - auto access = toGfxAccess(rasterView.accessType); - gfx::ShaderStageFlagBit tryGotVis = getVisibilityByDescName(renderGraph, layoutGraphData, passID, pair.second.slotName); - tryGotVis |= pair.second.shaderStageFlags; - const auto &[vis, usage, accessFlag] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph, true); - ViewStatus viewStatus{pair.first, passType, vis, access, accessFlag, usage}; - addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); - auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); - if (lastVertId != INVALID_ID && lastVertId != vertID) { - tryAddEdge(lastVertId, vertID, resourceAccessGraph); - tryAddEdge(lastVertId, vertID, relationGraph); - dependent = true; + const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, resID); + auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, resID); + if (traits.hasSideEffects()) { + states.states = iter->second.accessFlag; + if (traits.residency == ResourceResidency::BACKBUFFER) { + auto lastAccessPassID = get(ResourceAccessGraph::PassIDTag{}, rag, iter->first); + auto &barrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, iter->first); + auto &presentBarrier = barrierNode.rearBarriers.emplace_back(); + presentBarrier.resourceID = resID; + presentBarrier.type = gfx::BarrierType::FULL; + presentBarrier.beginVert = lastAccessPassID; + presentBarrier.endVert = lastAccessPassID; + presentBarrier.beginStatus = iter->second; + presentBarrier.endStatus = {gfx::AccessFlagBit::PRESENT, iter->second.range}; + presentBarrier.barrier = getGFXBarrier(presentBarrier); + + states.states = gfx::AccessFlagBit::NONE; + } } } - // sort for vector intersection - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); - - return dependent; -} - -bool checkComputeViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, PassType passType, ResourceAccessNode &node, const ComputeViewsMap &computeViews) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - bool dependent = false; - - for (const auto &pair : computeViews) { - const auto &values = pair.second; - for (const auto &computeView : values) { - auto access = toGfxAccess(computeView.accessType); - gfx::ShaderStageFlagBit tryGotVis = gfx::ShaderStageFlagBit::NONE; - for (const auto &view : pair.second) { - tryGotVis |= getVisibilityByDescName(renderGraph, layoutGraphData, passID, view.name); - tryGotVis |= view.shaderStageFlags; + { + for (auto &fgRenderpassInfo : rag.rpInfo) { + auto &colorAttachments = fgRenderpassInfo.rpInfo.colorAttachments; + uint32_t count{0}; + for (auto &color : colorAttachments) { + const auto &colorAccess = fgRenderpassInfo.colorAccesses[count]; + color.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), + colorAccess.prevAccess, + colorAccess.nextAccess); + ++count; } - const auto &[vis, usage, accessFlag] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph, false); - ViewStatus viewStatus{pair.first, passType, vis, access, accessFlag, usage}; - addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); - auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); - if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, resourceAccessGraph); - tryAddEdge(lastVertId, vertID, relationGraph); - dependent = true; + auto &dsAttachment = fgRenderpassInfo.rpInfo.depthStencilAttachment; + if (dsAttachment.format != gfx::Format::UNKNOWN) { + const auto &dsAccess = fgRenderpassInfo.dsAccess; + dsAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), + dsAccess.prevAccess, + dsAccess.nextAccess); + } + auto &dsResolveAttachment = fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; + if (dsResolveAttachment.format != gfx::Format::UNKNOWN) { + const auto &dsResolveAccess = fgRenderpassInfo.dsResolveAccess; + dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), + dsResolveAccess.prevAccess, + dsResolveAccess.nextAccess); } } } +} +#pragma endregion BUILD_BARRIERS - // sort for vector intersection - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); +#pragma region PASS_REORDER - return dependent; -} +struct PassVisitor : boost::dfs_visitor<> { + using RLGVertex = RelationGraph::vertex_descriptor; + using RLGEdge = RelationGraph::edge_descriptor; + using InEdgeRange = std::pair; + using OutEdgeRange = std::pair; -bool checkResolveResource(const Graphs &graphs, uint32_t vertID, uint32_t /*passID*/, ResourceAccessNode &node, const ccstd::pmr::vector &resolves) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - bool dependent = false; - for (const auto &pair : resolves) { - const auto &resolveTargetName = pair.target; - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex(resolveTargetName, resourceGraph)); - gfx::AccessFlags accessFlag = gfx::AccessFlags::COLOR_ATTACHMENT_WRITE; - gfx::TextureUsage usage = gfx::TextureUsage::COLOR_ATTACHMENT; - if (desc.format == gfx::Format::DEPTH_STENCIL) { - accessFlag = gfx::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE; - usage = gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; - } - ViewStatus viewStatus{resolveTargetName, - PassType::RASTER, - gfx::ShaderStageFlags::FRAGMENT, - gfx::MemoryAccess::WRITE_ONLY, - accessFlag, usage}; - addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); - auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); - if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, resourceAccessGraph); - tryAddEdge(lastVertId, vertID, relationGraph); - dependent = true; - } - } - // sort for vector intersection - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); + PassVisitor(RelationGraph &tcIn, CloseCircuits &circuitsIn) : _relationGraph(tcIn), _circuits(circuitsIn) {} - return dependent; -} + void start_vertex(RLGVertex u, const RelationGraph &g) {} -void fillRenderPassInfo(gfx::LoadOp loadOp, gfx::StoreOp storeOp, AttachmentType attachmentType, gfx::RenderPassInfo &rpInfo, uint32_t index, const ResourceDesc &viewDesc, bool resolve) { - if (attachmentType != AttachmentType::DEPTH_STENCIL) { - auto &colorAttachment = rpInfo.colorAttachments[index]; - if (colorAttachment.format == gfx::Format::UNKNOWN) { - colorAttachment.format = viewDesc.format; - colorAttachment.loadOp = loadOp; - colorAttachment.storeOp = storeOp; - colorAttachment.sampleCount = viewDesc.sampleCount; - } else { - colorAttachment.storeOp = storeOp; - } + void discover_vertex(RLGVertex u, const RelationGraph &g) {} - } else { - auto &depthStencilAttachment = resolve ? - rpInfo.depthStencilResolveAttachment : - rpInfo.depthStencilAttachment; - if (depthStencilAttachment.format == gfx::Format::UNKNOWN) { - depthStencilAttachment.format = viewDesc.format; - depthStencilAttachment.depthLoadOp = loadOp; - depthStencilAttachment.depthStoreOp = storeOp; - depthStencilAttachment.stencilLoadOp = loadOp; - depthStencilAttachment.stencilStoreOp = storeOp; - depthStencilAttachment.sampleCount = viewDesc.sampleCount; - } else { - // TODO(Zeqiang): separate ds - depthStencilAttachment.depthStoreOp = storeOp; - depthStencilAttachment.stencilStoreOp = storeOp; - } + void examine_edge(RLGEdge e, const RelationGraph &g) { } -} -void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + void tree_edge(RLGEdge e, const RelationGraph &g) {} - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - const auto &subpasses = pass.subpassGraph.subpasses; - bool hasSubpass = !subpasses.empty(); - auto &fgRenderpassInfo = resourceAccessGraph.rpInfos.emplace(vertID, FGRenderPassInfo{}).first->second; - auto &rpInfo = fgRenderpassInfo.rpInfo; - if (!hasSubpass) { - auto &rag = resourceAccessGraph; - auto size = std::count_if(pass.rasterViews.begin(), pass.rasterViews.end(), [](const auto &pair) { - return pair.second.attachmentType != AttachmentType::DEPTH_STENCIL; - }); - rpInfo.colorAttachments.resize(size); - fgRenderpassInfo.colorAccesses.resize(size); - PmrFlatMap> viewIndex(rag.get_allocator()); - for (const auto &[name, view] : pass.rasterViews) { - auto resIter = rag.resourceIndex.find(name); - gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; - viewIndex.emplace(std::piecewise_construct, std::forward_as_tuple(view.slotID), std::forward_as_tuple(name, prevAccess)); - } + void back_edge(RLGEdge e, const RelationGraph &g) {} - bool dependent = false; - dependent |= checkRasterViews(graphs, vertID, passID, PassType::RASTER, node, pass.rasterViews); - dependent |= checkComputeViews(graphs, vertID, passID, PassType::RASTER, node, pass.computeViews); + void forward_or_cross_edge(RLGEdge e, const RelationGraph &g) { + // the vertex which: + // 1. is ancestor of targetID; + // 2. sourceID is reachable at this specific vert; + // is where the closed-path started. + // note that `reachable` may results to multiple paths, choose the shortest one. + auto sourceID = source(e, g); + auto targetID = target(e, g); - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); + using RhsRangePair = std::pair; + + bool foundIntersect = false; + std::queue vertQ; + auto iterPair = in_edges(targetID, g); + vertQ.emplace(RhsRangePair{iterPair.first, iterPair}); + + // from source vertex on this edge back to branch point + EdgeList rhsPath; + bool rootEdge = true; + while (!foundIntersect && !vertQ.empty()) { + auto rangePair = vertQ.front(); + vertQ.pop(); + auto range = rangePair.second; + for (auto iter = range.first; iter != range.second; ++iter) { + auto srcID = source((*iter), g); + if (sourceID == srcID) { + continue; + } + auto e = edge(srcID, sourceID, _relationGraph); + auto recordIter = rootEdge ? iter : rangePair.first; + if (!e.second) { + vertQ.emplace(RhsRangePair{recordIter, in_edges(srcID, g)}); + } else { + rhsPath = {(*iter), *recordIter}; + foundIntersect = true; + break; + } + } + rootEdge = false; + } + assert(foundIntersect); + + using LhsRangePair = std::pair; + auto branchVert = source(rhsPath.first, g); + bool found = false; + std::queue forwardVertQ; + auto forwardIterPair = out_edges(branchVert, g); + forwardVertQ.emplace(LhsRangePair{forwardIterPair.first, forwardIterPair}); + EdgeList lhsPath; + rootEdge = true; + while (!found && !forwardVertQ.empty()) { + auto rangePair = forwardVertQ.front(); + forwardVertQ.pop(); + auto range = rangePair.second; + for (auto iter = range.first; iter != range.second; ++iter) { + if ((*iter) == rhsPath.first) { + continue; + } + auto dstID = target((*iter), g); + auto e = edge(dstID, sourceID, _relationGraph); + auto recordIter = rootEdge ? iter : rangePair.first; + if (!e.second) { + forwardVertQ.emplace(LhsRangePair{recordIter, out_edges(dstID, g)}); + } else { + found = true; + lhsPath = {*recordIter, (*iter)}; + break; + } + } + rootEdge = true; + } + assert(found); + lhsPath.second = e; + + _circuits.emplace_back(CloseCircuit{lhsPath, rhsPath}); + }; + +private: + RelationGraph &_relationGraph; + CloseCircuits &_circuits; +}; + +// forward (vertex ascending): +// -- true: how much resource this pass writes to, which has an effect of later passes; +// -- false: how much resource this pass reads from, which is dependent from former passes. +auto evaluateHeaviness(const ResourceAccessGraph &rag, const ResourceGraph &rescGraph, ResourceAccessGraph::vertex_descriptor vert, bool forward) { + const ResourceAccessNode &accessNode = get(ResourceAccessGraph::PassNodeTag{}, rag, vert); + int64_t score = 0; + bool forceAdjacent = false; + for (const auto &pair : accessNode.resourceStatus) { + int64_t eval = 0; + auto rescID = rag.resourceIndex.at(pair.first); + const ResourceDesc &desc = get(ResourceGraph::DescTag{}, rescGraph, rescID); + const ResourceTraits &traits = get(ResourceGraph::TraitsTag{}, rescGraph, rescID); + + const auto &resc = pair.second; + if (!(isReadOnlyAccess(resc.accessFlag) ^ forward)) { + // forward calculate write(s), backward calculate read(s). + continue; + } + + switch (desc.dimension) { + case ResourceDimension::BUFFER: + eval = desc.width; + break; + case ResourceDimension::TEXTURE1D: + case ResourceDimension::TEXTURE2D: + case ResourceDimension::TEXTURE3D: + eval = gfx::formatSize(desc.format, desc.width, desc.height, desc.depthOrArraySize); + break; + } + + if (traits.residency == ResourceResidency::MEMORYLESS) { + forceAdjacent = true; + score = forward ? std::numeric_limits::lowest() : std::numeric_limits::max(); + break; } + } + return std::make_tuple(forceAdjacent, score); +}; + +void evaluateAndTryMerge(const ResourceAccessGraph &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, const RelationGraph &relationGraphTc, const RelationVerts &lhsVerts, const RelationVerts &rhsVerts) { + assert(lhsVerts.size() >= 2); + assert(rhsVerts.size() >= 2); + + auto evaluate = [&rag, &rescGraph, &relationGraph](RelationVert vert, bool forward) { + auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, vert); + return evaluateHeaviness(rag, rescGraph, ragVert, forward); + }; + + if (lhsVerts.size() == 2 || rhsVerts.size() == 2) { + /* + 1 ----------- 2 + \ __--/ + 3 --`` + no extra choice, only 1 - 3 - 2 + */ + const RelationVerts *shorterPath = lhsVerts.size() == 2 ? &lhsVerts : &rhsVerts; + remove_edge((*shorterPath)[0], (*shorterPath)[1], relationGraph); + } else { + // fist and last joint pass in this circuit don't get involved in reorder. + auto firstLhsNode = lhsVerts[1]; + auto lastLhsNode = lhsVerts[lhsVerts.size() - 2]; + + const auto &lhsBackwardStatus = evaluate(firstLhsNode, false); + bool lhsAdjacentToStart = std::get<0>(lhsBackwardStatus); + const auto &lhsForwardStatus = evaluate(lastLhsNode, true); + bool lhsAdjacentToEnd = std::get<0>(lhsForwardStatus); + + auto firstRhsNode = rhsVerts[1]; + auto lastRhsNode = rhsVerts[rhsVerts.size() - 2]; + + const auto &rhsBackwardStatus = evaluate(firstRhsNode, true); + bool rhsAdjacentToStart = std::get<0>(rhsBackwardStatus); + const auto &rhsForwardStatus = evaluate(lastRhsNode, false); + bool rhsAdjacentToEnd = std::get<0>(rhsForwardStatus); + + if (lhsAdjacentToStart || rhsAdjacentToEnd || lhsAdjacentToEnd || rhsAdjacentToStart) { + const RelationVerts *formerPath = &lhsVerts; + const RelationVerts *latterPath = &rhsVerts; + if (rhsAdjacentToStart || lhsAdjacentToEnd) { + swap(formerPath, latterPath); + } + + remove_edge((*latterPath)[0], (*latterPath)[1], relationGraph); + remove_edge((*formerPath)[formerPath->size() - 2], (*formerPath)[formerPath->size() - 1], relationGraph); + + tryAddEdge((*formerPath)[formerPath->size() - 2], (*latterPath)[1], relationGraph); + } + + assert(lhsVerts.size() >= 3 && rhsVerts.size() >= 3); + constexpr int64_t score = std::numeric_limits::lowest(); + ccstd::vector> candidateSections; + std::queue lhsSection; + for (size_t i = 1; i < lhsVerts.size(); ++i) { + auto tryE = edge(lhsVerts[i], lhsVerts[i - 1], relationGraphTc); + auto tryRE = edge(lhsVerts[i - 1], lhsVerts[i], relationGraphTc); + // check if original reachable + if (!tryE.second && !tryRE.second) { + remove_edge(lhsVerts[i - 1], lhsVerts[i], relationGraph); + candidateSections.emplace_back(lhsSection); + std::queue clearQ; + lhsSection.swap(clearQ); + } + auto e = edge(lhsVerts[i], lhsVerts[i - 1], relationGraph); + // verts comes in order, so either real edge exist or logic edge is added. + CC_ASSERT(e.second); + + lhsSection.emplace(e.first); + } + if (candidateSections.empty()) { + // if this one is a tight edge(no logic edge, dependent from one to its next), + // keep this whole chain as a candidate. + remove_edge(lhsVerts[0], lhsVerts[1], relationGraph); + remove_edge(lhsVerts[lhsVerts.size() - 2], lhsVerts[lhsVerts.size() - 1], relationGraph); + candidateSections.emplace_back(std::move(lhsSection)); + } + + std::queue rhsSection; + for (size_t i = 1; i < rhsVerts.size(); ++i) { + auto tryE = edge(rhsVerts[i], rhsVerts[i - 1], relationGraphTc); + auto tryRE = edge(rhsVerts[i - 1], rhsVerts[i], relationGraphTc); + if (!tryE.second && !tryRE.second) { + remove_edge(rhsVerts[i - 1], rhsVerts[i], relationGraph); + candidateSections.emplace_back(rhsSection); + std::queue clearQ; + rhsSection.swap(clearQ); + } + auto e = edge(rhsVerts[i], rhsVerts[i - 1], relationGraph); + // verts comes in order, so either real edge exist or logic edge is added. + CC_ASSERT(e.second); + rhsSection.emplace(e.first); + } + + // lhs verts already put in. + if (candidateSections.size() == 1) { + remove_edge(rhsVerts[0], rhsVerts[1], relationGraph); + remove_edge(rhsVerts[rhsVerts.size() - 2], rhsVerts[rhsVerts.size() - 1], relationGraph); + candidateSections.emplace_back(std::move(rhsSection)); + } + + assert(candidateSections.size() >= 2); + + ScoreMap scMap; + auto tailVert = lhsVerts[0]; + while (!candidateSections.empty()) { + int64_t lightest = std::numeric_limits::max(); + uint32_t index = 0; + for (size_t i = 0; i < candidateSections.size(); ++i) { + auto e = candidateSections[i].front(); + auto srcVert = source(e, relationGraph); + auto dstVert = target(e, relationGraph); + int64_t srcBackwardScore = 0; + int64_t dstForwardScore = 0; + if (scMap.find(srcVert) == scMap.end()) { + auto res = evaluate(srcVert, false); + srcBackwardScore = std::get<1>(res); + res = evaluate(srcVert, true); + auto srcForwardScore = std::get<1>(res); + scMap.emplace(srcVert, std::pair(srcBackwardScore, srcForwardScore)); + } else { + srcBackwardScore = std::get<0>(scMap.at(srcVert)); + } + if (scMap.find(dstVert) == scMap.end()) { + auto res = evaluate(dstVert, false); + dstForwardScore = std::get<1>(res); + res = evaluate(dstVert, true); + auto dstBackwardScore = std::get<1>(res); + scMap.emplace(dstVert, std::pair(dstBackwardScore, dstForwardScore)); + } else { + dstForwardScore = std::get<1>(scMap.at(dstVert)); + } + + // we are in a simple path, so all the "input(this path)" resource of this path come from the first vertex, + // all the "output(this path)" come to the last vertex, other resources are "internally(this path)" produced and destroyed. + // so only input of first vertex and output of last vertex are taken into account. + // [simple path]: path without diverged edges. + auto score = dstForwardScore - srcBackwardScore; + if (lightest > score) { + lightest = score; + index = i; + } + } + auto e = candidateSections[index].front(); + candidateSections[index].pop(); + if (candidateSections[index].empty()) { + auto iter = candidateSections.begin(); + std::advance(iter, index); + candidateSections.erase(iter); + } + auto srcVert = source(e, relationGraph); + auto dstVert = target(e, relationGraph); + tryAddEdge(tailVert, srcVert, relationGraph); + tailVert = dstVert; + } + + tryAddEdge(tailVert, lhsVerts.back(), relationGraph); + } +} + +// return : can be further reduced? +bool reduce(const ResourceAccessGraph &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, RelationGraph &relationGraphTc, const CloseCircuit &circuit) { + auto checkPath = [&relationGraph](std::stack &vertices, RelationGraph::vertex_descriptor endVert, RelationVerts &stackTrace) { + bool simpleGraph = true; + while (!vertices.empty()) { + auto vert = vertices.top(); + vertices.pop(); + stackTrace.emplace_back(vert); + + if (endVert == vert) { + break; + } + + if (out_degree(vert, relationGraph) > 1) { + simpleGraph = false; + break; + } + auto r = out_edges(vert, relationGraph); + for (auto rIter = r.first; rIter != r.second; ++rIter) { + auto dstID = target(*rIter, relationGraph); + vertices.push(dstID); + } + if (r.first == r.second) { + stackTrace.pop_back(); + } + } + return simpleGraph; + }; + + // check if there is a sub branch on lhs + auto lhsEdges = circuit.first; + auto startVert = target(lhsEdges.first, relationGraph); + auto endVert = source(lhsEdges.second, relationGraph); + + std::stack vertices; + vertices.emplace(startVert); + + RelationVerts lhsVisited; + auto branchStartVert = source(lhsEdges.first, relationGraph); + auto branchEndVert = target(lhsEdges.second, relationGraph); + lhsVisited.push_back(branchStartVert); + // check if there is a branch on lhs path + if (!checkPath(vertices, endVert, lhsVisited)) { + return false; + } + lhsVisited.push_back(branchEndVert); + // if it's a simple graph, lhs path must can be dfs to the end at the first time. + assert(vertices.empty()); - // initial layout(accessrecord.laststatus) and final layout(accessrecord.currstatus) can be filled here - for (const auto &[slotID, pair] : viewIndex) { - const auto &name = pair.first; - const auto resID = rag.resourceIndex.at(name); - const auto &view = pass.rasterViews.at(name); - const auto &viewDesc = get(ResourceGraph::DescTag{}, resourceGraph, resID); - auto prevAccess = pair.second; - // TD:remove find - auto nodeIter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), [resID](const AccessStatus &status) { - return status.vertID == resID; - }); - auto nextAccess = nodeIter->accessFlag; + auto rhsEdges = circuit.second; + startVert = target(rhsEdges.first, relationGraph); + endVert = source(rhsEdges.second, relationGraph); + vertices.emplace(startVert); - if (rpInfo.subpasses.empty()) { - rpInfo.subpasses.emplace_back(); - } - auto &subpassInfo = rpInfo.subpasses.front(); - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { - if (view.attachmentType == AttachmentType::SHADING_RATE) { - subpassInfo.shadingRate = slotID; - } else { - if (view.accessType != AccessType::READ) { - subpassInfo.colors.emplace_back(slotID); - } - if (view.accessType != AccessType::WRITE) { - subpassInfo.inputs.emplace_back(slotID); - } - } - fgRenderpassInfo.colorAccesses[slotID].prevAccess = prevAccess; - fgRenderpassInfo.colorAccesses[slotID].nextAccess = nextAccess; - } else { - subpassInfo.depthStencil = pass.rasterViews.size() - 1; - fgRenderpassInfo.dsAccess.prevAccess = prevAccess; - fgRenderpassInfo.dsAccess.nextAccess = nextAccess; - } - fillRenderPassInfo(view.loadOp, view.storeOp, view.attachmentType, rpInfo, slotID, viewDesc, false); - fgRenderpassInfo.orderedViews.emplace_back(name); - } - } else { - auto colorSize = pass.rasterViews.size(); - bool hasDS = std::any_of(pass.rasterViews.begin(), pass.rasterViews.end(), [](const auto &pair) { - return pair.second.attachmentType == AttachmentType::DEPTH_STENCIL; - }); - colorSize -= hasDS; - const auto &subpasses = pass.subpassGraph.subpasses; - uint32_t count = 0; - const auto &resg = resourceGraph; - auto resolveNum = std::accumulate(subpasses.begin(), subpasses.end(), 0, [&resg](uint32_t initVal, const Subpass &subpass) { - auto iter = std::find_if(subpass.resolvePairs.begin(), subpass.resolvePairs.end(), [&resg](const auto &pair) { - auto resID = vertex(pair.target, resg); - const auto& desc = get(ResourceGraph::DescTag{}, resg, resID); - return desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH; - }); - return initVal + subpass.resolvePairs.size() - (iter != subpass.resolvePairs.end()); - }); - colorSize += resolveNum; - rpInfo.colorAttachments.resize(colorSize); - fgRenderpassInfo.colorAccesses.resize(colorSize); + RelationVerts rhsVisited; + rhsVisited.push_back(branchStartVert); + if (!checkPath(vertices, endVert, rhsVisited)) { + return false; } -} + rhsVisited.push_back(branchEndVert); -void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + // merge this circuit + // from + /* 2 - 3 - 4 + / \ + 1 8 + \ / + 5 - 6 - 7 - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - bool dependent = checkComputeViews(graphs, vertID, passID, PassType::COMPUTE, node, pass.computeViews); + to + 1 - A - B - 8 or 1 - B - A -8 depends on algorithm - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } -} + ${A} : 2 - 3 - 4 + ${B} : 5 - 6 - 7 + */ -uint32_t record(const ccstd::vector &indices) { - uint32_t res = 0; - for (auto attachmentIndex : indices) { - res |= 1 << attachmentIndex; - } - return res; -} + evaluateAndTryMerge(rag, rescGraph, relationGraph, relationGraphTc, lhsVisited, rhsVisited); -void extract(uint32_t val, ccstd::vector &preserves) { - uint32_t index = 0; - while (val) { - if (val & 0x1) { - preserves.emplace_back(index); - } - val = val >> 1; - ++index; - } + return true; } -void getPreserves(gfx::RenderPassInfo &rpInfo) { - std::stack stack; - for (auto &info : rpInfo.subpasses) { - stack.push(&info); - } +template +void applyRelation(RelationGraph &relationGraph, const TargetGraph &targetGraph) { + CC_EXPECTS(relationGraph.vertices.size() == targetGraph.vertices.size()); - uint32_t laterRead{0}; - while (!stack.empty()) { - auto *tail = stack.top(); - stack.pop(); + // remove all edges + for (auto vert : targetGraph.vertices) { + clear_in_edges(vert, targetGraph); + clear_out_edges(vert, targetGraph); + } - auto readRecord = record(tail->inputs); - auto writeRecord = record(tail->colors); - auto resolveRecord = record(tail->resolves); - auto shown = readRecord | writeRecord | resolveRecord; - auto needPreserve = (shown | laterRead) ^ shown; - extract(needPreserve, tail->preserves); - laterRead |= readRecord; + for (auto vert : relationGraph.vertices) { + auto inEdges = in_edges(vert, relationGraph); + for (auto e : makeRange(inEdges)) { + auto srcVert = source(e, relationGraph); + // auto checkEdge = edge(srcVert, vert, targetGraph); + add_edge(srcVert, vert, targetGraph); + } } } -void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSubpass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - const auto &obj = renderGraph.objects.at(passID); - const auto parentID = obj.parents.front().target; - const auto parentRagVert = resourceAccessGraph.passIndex.at(parentID); - const auto *parentPass = get_if(parentID, &renderGraph); - CC_EXPECTS(parentPass); - const auto &rag = resourceAccessGraph; - const auto &resg = resourceGraph; - const auto &uberPass = *parentPass; - - resourceAccessGraph.passIndex[passID] = parentRagVert; - - static const uint32_t ACCESS_TYPE_WEIGHT[] = {0, 1, 2}; - static const uint32_t ATTACHMENT_TYPE_WEIGHT[] = {0, 2, 1}; - - struct SubpassRasterViewSortKey { - uint32_t accessType; - uint32_t attachmentType; - std::string_view slotName; - uint32_t samplesReverseWeight; - }; - using RasterViewSortKey = std::tuple; - struct SubpassRasterViewData { - SubpassRasterViewSortKey sortKey; - std::string_view name; - gfx::AccessFlags access; - }; +void passReorder(FrameGraphDispatcher &fgDispatcher) { + auto *scratch = fgDispatcher.scratch; + const auto &renderGraph = fgDispatcher.renderGraph; + const auto &layoutGraph = fgDispatcher.layoutGraph; + auto &resourceGraph = fgDispatcher.resourceGraph; + auto &relationGraph = fgDispatcher.relationGraph; + auto &rag = fgDispatcher.resourceAccessGraph; - bool hasDS{false}; - ccstd::vector viewIndex; - for (const auto &[name, view] : pass.rasterViews) { - auto resIter = rag.resourceIndex.find(name); - const auto &resID = vertex(name, resourceGraph); - const auto &desc = get(ResourceGraph::DescTag{}, resg, resID); - gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; - viewIndex.emplace_back(SubpassRasterViewData{ - {ACCESS_TYPE_WEIGHT[static_cast(view.accessType)], ATTACHMENT_TYPE_WEIGHT[static_cast(view.attachmentType)], view.slotName, static_cast(desc.sampleCount)}, - name, - prevAccess, - }); - hasDS |= view.attachmentType == AttachmentType::DEPTH_STENCIL; + if (!fgDispatcher._accessGraphBuilt) { + const Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; + buildAccessGraph(graphs); + fgDispatcher._accessGraphBuilt = true; } - for (const auto &resolve : pass.resolvePairs) { - auto resIter = rag.resourceIndex.find(resolve.target); - gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; - viewIndex.emplace_back(SubpassRasterViewData{ - {ACCESS_TYPE_WEIGHT[static_cast(AccessType::WRITE)], ATTACHMENT_TYPE_WEIGHT[static_cast(AttachmentType::RENDER_TARGET)], "_", 0xFFFFFFFF}, - resolve.target, - prevAccess, - }); - } + { + // determine do mem saving how many times + RelationGraph relationGraphTc(fgDispatcher.get_allocator()); + boost::transitive_closure(relationGraph, relationGraphTc); - std::sort(viewIndex.begin(), viewIndex.end(), [](const SubpassRasterViewData &lhs, const SubpassRasterViewData &rhs) { - if (lhs.sortKey.samplesReverseWeight != rhs.sortKey.samplesReverseWeight) { - return lhs.sortKey.samplesReverseWeight < rhs.sortKey.samplesReverseWeight; - } - if (lhs.sortKey.accessType != rhs.sortKey.accessType) { - return lhs.sortKey.accessType < rhs.sortKey.accessType; - } - if (lhs.sortKey.attachmentType != rhs.sortKey.attachmentType) { - return lhs.sortKey.attachmentType < rhs.sortKey.attachmentType; - } - return lhs.sortKey.slotName < rhs.sortKey.slotName; - }); - - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, parentRagVert); - auto &fgRenderpassInfo = resourceAccessGraph.rpInfos.at(parentRagVert); - auto &rpInfo = fgRenderpassInfo.rpInfo; - auto &subpassInfo = rpInfo.subpasses.emplace_back(); - auto *lastNode = &node; - uint32_t subpassIndex = 0; - while (lastNode->nextSubpass) { - lastNode = lastNode->nextSubpass; - ++subpassIndex; - } - lastNode->nextSubpass = new ResourceAccessNode; - resourceAccessGraph.subpassIndex.emplace(passID, subpassIndex); - auto *head = lastNode->nextSubpass; - bool dependent{false}; - dependent |= checkRasterViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.rasterViews); - dependent |= checkComputeViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.computeViews); - dependent |= checkResolveResource(graphs, parentRagVert, passID, *head, pass.resolvePairs); - - if (!dependent) { - tryAddEdge(EXPECT_START_ID, parentRagVert, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, parentRagVert, relationGraph); - } - - if (!pass.resolvePairs.empty()) { - // ds resolve stores in depthStencilResolve - subpassInfo.resolves.resize(pass.rasterViews.size() - hasDS, gfx::INVALID_BINDING); - } - - uint32_t localSlot = 0; - bool dsAppeared{false}; - for (const auto &[sortKey, name, access] : viewIndex) { - const auto *const resName = name.data(); - auto findByResID = [&](const AccessStatus &status) { - return status.vertID == rag.resourceIndex.at(resName); - }; - auto iter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), findByResID); - - // TODO(Zeqiang): remove find - const auto &targetName = name; - auto resID = rag.resourceIndex.at(resName); - const auto &viewDesc = get(ResourceGraph::DescTag{}, resg, rag.resourceIndex.at(resName)); - - AttachmentType attachmentType{AttachmentType::RENDER_TARGET}; - AccessType accessType{AccessType::WRITE}; - gfx::LoadOp loadOp{gfx::LoadOp::DISCARD}; - gfx::StoreOp storeOp{gfx::StoreOp::STORE}; - - uint32_t slot = dsAppeared ? localSlot - 1 : localSlot; - // std::distance(uberPass.rasterViews.begin(), uberPass.rasterViews.find(resName)); - // slot = dsAppeared ? slot - 1 : slot; - /*if (attachmentType != AttachmentType::DEPTH_STENCIL) { - CC_ASSERT(uberPass.attachmentIndexMap.count(resName)); - slot = uberPass.attachmentIndexMap.at(resName); - }*/ - - // TD:remove find - auto nodeIter = std::find_if(head->attachmentStatus.begin(), head->attachmentStatus.end(), [resID](const AccessStatus &status) { - return status.vertID == resID; - }); - auto nextAccess = nodeIter->accessFlag; + CloseCircuits circuits; + std::vector crossEdges; + PassVisitor visitor(relationGraphTc, circuits); + auto colors = relationGraph.colors(scratch); + boost::depth_first_search(relationGraph, visitor, get(colors, relationGraph)); - auto resolveIter = std::find_if(pass.resolvePairs.begin(), pass.resolvePairs.end(), [&targetName](const ResolvePair &resolve) { - return strcmp(resolve.target.c_str(), targetName.data()) == 0; - }); - bool resolveView = resolveIter != pass.resolvePairs.end(); - if (resolveView) { - attachmentType = viewDesc.format == gfx::Format::DEPTH_STENCIL ? AttachmentType::DEPTH_STENCIL : AttachmentType::RENDER_TARGET; - if (attachmentType == AttachmentType::DEPTH_STENCIL) { - subpassInfo.depthStencilResolve = slot; - subpassInfo.depthResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode; - subpassInfo.stencilResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode1; - fgRenderpassInfo.dsResolveAccess.nextAccess = nextAccess; - } else { - auto indexIter = std::find(fgRenderpassInfo.orderedViews.begin(), fgRenderpassInfo.orderedViews.end(), resolveIter->source.c_str()); - auto srcIndex = indexIter == fgRenderpassInfo.orderedViews.end() ? fgRenderpassInfo.orderedViews.size() - : std::distance(fgRenderpassInfo.orderedViews.begin(), indexIter); - subpassInfo.resolves[srcIndex] = slot; - fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; - } - accessType = AccessType::WRITE; - } else { - const auto &view = pass.rasterViews.at(resName); - attachmentType = view.attachmentType; - accessType = view.accessType; - loadOp = view.loadOp; - storeOp = view.storeOp; - - if (attachmentType != AttachmentType::DEPTH_STENCIL) { - if (attachmentType == AttachmentType::SHADING_RATE) { - subpassInfo.shadingRate = slot; - } else { - if (accessType != AccessType::READ) { - subpassInfo.colors.emplace_back(slot); - } - if (accessType != AccessType::WRITE) { - subpassInfo.inputs.emplace_back(slot); - } - } - fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; + float percent = 0.0F; + uint32_t count = 0; + auto total = circuits.size(); + + float memsavePercent = 1.0F - fgDispatcher._paralellExecWeight; + for (auto iter = circuits.begin(); (iter != circuits.end()) && (percent < memsavePercent);) { + bool reduced = reduce(rag, resourceGraph, relationGraph, relationGraphTc, (*iter)); + if (reduced) { + ++count; + iter = circuits.erase(iter); + percent = count / static_cast(total); } else { - fgRenderpassInfo.dsAccess.nextAccess = nextAccess; - subpassInfo.depthStencil = rpInfo.colorAttachments.size(); - dsAppeared = true; + ++iter; } } - if (iter == node.attachmentStatus.end()) { - auto curIter = std::find_if(head->attachmentStatus.begin(), head->attachmentStatus.end(), findByResID); - node.attachmentStatus.emplace_back(*curIter); - auto prevAccess = access; - CC_ASSERT(head->attachmentStatus.size() > localSlot); - auto nextAccess = head->attachmentStatus[localSlot].accessFlag; + // topological sort + rag.topologicalOrder.clear(); + bool empty = relationGraph._vertices.empty(); + ScoreMap scoreMap; + RelationVerts candidates; + candidates.push_back(EXPECT_START_ID); - if (attachmentType == AttachmentType::DEPTH_STENCIL) { - if (resolveView) { - fgRenderpassInfo.dsResolveAccess.prevAccess = prevAccess; + std::vector candidateBuffer; + uint32_t coloredVerts = 0; + while (coloredVerts < relationGraph._vertices.size()) { + // decreasing order, pop back from vector, push into queue, then it's ascending order. + std::sort(candidates.begin(), candidates.end(), [&](RelationVert lhsVert, RelationVert rhsVert) { + int64_t lhsForwardScore{0}; + int64_t rhsForwardScore{0}; + int64_t lhsBackwardScore{0}; + int64_t rhsBackwardScore{0}; + if (scoreMap.find(lhsVert) == scoreMap.end()) { + auto lhsRagVert = get(RelationGraph::DescIDTag{}, relationGraph, lhsVert); + const auto &lhsForwardStatus = evaluateHeaviness(rag, resourceGraph, lhsRagVert, true); + lhsForwardScore = get<1>(lhsForwardStatus); + const auto &lhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, lhsRagVert, false); + lhsBackwardScore = get<1>(lhsBackwardStatus); + scoreMap.emplace(lhsVert, std::pair{lhsBackwardScore, lhsForwardScore}); } else { - fgRenderpassInfo.dsAccess.prevAccess = prevAccess; + lhsBackwardScore = scoreMap[lhsVert].first; + lhsForwardScore = scoreMap[lhsVert].second; } - } else { - fgRenderpassInfo.colorAccesses[slot].prevAccess = prevAccess; - } - fgRenderpassInfo.orderedViews.emplace_back(resName); - } - fillRenderPassInfo(loadOp, storeOp, attachmentType, rpInfo, slot, viewDesc, resolveView); - fgRenderpassInfo.needResolve |= resolveView; - ++localSlot; - } - if (pass.subpassID == uberPass.subpassGraph.subpasses.size() - 1) { - getPreserves(rpInfo); - } -} - -void processComputeSubpass(const Graphs &graphs, uint32_t passID, const ComputeSubpass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - const auto &obj = renderGraph.objects.at(passID); - const auto parentID = obj.parents.front().target; - const auto parentRagVert = resourceAccessGraph.passIndex.at(parentID); - const auto *parentPass = get_if(parentID, &renderGraph); - CC_EXPECTS(parentPass); - const auto &rag = resourceAccessGraph; - const auto &resg = resourceGraph; - const auto &uberPass = *parentPass; - - resourceAccessGraph.passIndex[passID] = parentRagVert; + if (scoreMap.find(rhsVert) == scoreMap.end()) { + auto rhsRagVert = get(RelationGraph::DescIDTag{}, relationGraph, rhsVert); + const auto &rhsForwardStatus = evaluateHeaviness(rag, resourceGraph, rhsRagVert, true); + rhsForwardScore = get<1>(rhsForwardStatus); + const auto &rhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, rhsRagVert, false); + rhsBackwardScore = get<1>(rhsBackwardStatus); + scoreMap.emplace(rhsVert, std::pair{rhsBackwardScore, rhsForwardScore}); + } else { + rhsBackwardScore = scoreMap[rhsVert].first; + rhsForwardScore = scoreMap[rhsVert].second; + } + return lhsBackwardScore - lhsForwardScore > rhsBackwardScore - rhsForwardScore; + }); - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, parentRagVert); + const auto vert = candidates.back(); + candidates.pop_back(); - auto *lastNode = &node; - while (lastNode->nextSubpass) { - lastNode = lastNode->nextSubpass; - } - lastNode->nextSubpass = new ResourceAccessNode; - auto *head = lastNode->nextSubpass; + auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, vert); + rag.topologicalOrder.emplace_back(ragVert); + if (!candidateBuffer.empty()) { + candidates.insert(candidates.end(), candidateBuffer.begin(), candidateBuffer.end()); + candidateBuffer.clear(); + } - bool dependent = checkComputeViews(graphs, parentRagVert, passID, PassType::COMPUTE, *head, pass.computeViews); + for (const auto nextGeneration : makeRange(out_edges(vert, relationGraph))) { + auto targetID = target(nextGeneration, relationGraph); + if (in_degree(targetID, relationGraph) == 1) { + candidateBuffer.emplace_back(targetID); + } + } - if (!dependent) { - tryAddEdge(EXPECT_START_ID, parentRagVert, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, parentRagVert, relationGraph); - } -} + auto deprecatedEdges = out_edges(vert, relationGraph); + for (auto iter = deprecatedEdges.first; iter < deprecatedEdges.second;) { + remove_edge(*iter, relationGraph); + deprecatedEdges = out_edges(vert, relationGraph); + iter = deprecatedEdges.first; + } -void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + if (candidates.empty()) { + candidates.insert(candidates.end(), candidateBuffer.begin(), candidateBuffer.end()); + candidateBuffer.clear(); + } - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + coloredVerts++; + } - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - bool dependent = false; - for (const auto &pair : pass.copyPairs) { - auto sourceRange = Range{ - TextureRange{ - pair.sourceFirstSlice, - pair.sourcePlaneSlice, - pair.mipLevels, - pair.numSlices, - }}; - auto targetRange = Range{ - TextureRange{ - pair.targetFirstSlice, - pair.targetPlaneSlice, - pair.mipLevels, - pair.numSlices, - }}; - ResourceUsage srcUsage = gfx::TextureUsage::TRANSFER_SRC; - ViewStatus srcViewStatus{pair.source, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::READ_ONLY, gfx::AccessFlags::TRANSFER_READ, srcUsage}; - addCopyAccessStatus(resourceAccessGraph, resourceGraph, node, srcViewStatus, sourceRange); - ResourceUsage dstUsage = gfx::TextureUsage::TRANSFER_DST; - ViewStatus dstViewStatus{pair.target, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY, gfx::AccessFlags::TRANSFER_WRITE, dstUsage}; - addCopyAccessStatus(resourceAccessGraph, resourceGraph, node, dstViewStatus, targetRange); - - uint32_t lastVertSrc = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, srcViewStatus); - if (lastVertSrc != INVALID_ID) { - tryAddEdge(lastVertSrc, vertID, resourceAccessGraph); - tryAddEdge(lastVertSrc, rlgVertID, relationGraph); - dependent = true; + // remove all edges + for (auto vert : makeRange(vertices(rag))) { + clear_in_edges(vert, rag); + clear_out_edges(vert, rag); } - uint32_t lastVertDst = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, dstViewStatus); - if (lastVertDst != INVALID_ID) { - tryAddEdge(lastVertDst, vertID, resourceAccessGraph); - tryAddEdge(lastVertDst, rlgVertID, relationGraph); - dependent = true; + + // apply relation + for (auto rlgVert : makeRange(vertices(relationGraph))) { + auto ragVert = get(RelationGraph::DescIDTag{}, relationGraph, rlgVert); + auto inEdges = in_edges(rlgVert, relationGraph); + for (auto e : makeRange(inEdges)) { + auto srcRlgVert = source(e, relationGraph); + auto srcRagVert = get(RelationGraph::DescIDTag{}, relationGraph, srcRlgVert); + add_edge(srcRagVert, ragVert, rag); + } } } - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); } -void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); +#pragma endregion PASS_REORDER - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - bool dependent = checkComputeViews(graphs, vertID, passID, PassType::RAYTRACE, node, pass.computeViews); +void memoryAliasing(FrameGraphDispatcher &fgDispatcher) { +} - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); +#pragma region assisstantFuncDefinition +template +bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph) { + auto e = edge(srcVertex, dstVertex, graph); + if (!e.second) { + auto res = add_edge(srcVertex, dstVertex, graph); + CC_ENSURES(res.second); + return true; } + return false; +} + +bool isTransitionStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs) { + return !(isReadOnlyAccess(lhs.accessFlag) && isReadOnlyAccess(rhs.accessFlag)); } #pragma endregion assisstantFuncDefinition diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index 23fdda466bc..c52a13d114c 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -35,6 +35,7 @@ #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" #include "RenderingModule.h" +#include "NativeRenderGraphUtils.h" #include "cocos/renderer/gfx-base/GFXBarrier.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" @@ -70,7 +71,6 @@ struct RenderGraphVisitorContext { const RenderGraph& g; ResourceGraph& resourceGraph; const FrameGraphDispatcher& fgd; - const FrameGraphDispatcher::BarrierMap& barrierMap; const ccstd::pmr::vector& validPasses; gfx::Device* device = nullptr; gfx::CommandBuffer* cmdBuff = nullptr; @@ -164,145 +164,24 @@ gfx::GeneralBarrier* getGeneralBarrier(gfx::Device* device, const RasterView& vi return nullptr; } +ResourceGraph::vertex_descriptor getResourceID(const ccstd::pmr::string& name, const FrameGraphDispatcher& fgd) { + return fgd.realResourceID(name); +} + PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( RenderGraphVisitorContext& ctx, const RasterPass& pass, - boost::container::pmr::memory_resource* scratch) { + boost::container::pmr::memory_resource* /*scratch*/) { auto& resg = ctx.resourceGraph; PersistentRenderPassAndFramebuffer data(pass.get_allocator()); - gfx::RenderPassInfo rpInfo{}; - - gfx::FramebufferInfo fbInfo{ - data.renderPass, - }; - fbInfo.colorTextures.reserve(pass.rasterViews.size()); - - PmrFlatSet set(scratch); - auto fillFrameBufferInfo = [&](const ccstd::vector& passViews, bool hasResolve) { - std::ignore = hasResolve; - const auto& uberPass = pass; - auto numTotalAttachments = static_cast(passViews.size()); - - // uint32_t dsvCount = 0; - uint32_t index = 0; - for (const auto& nameIn : passViews) { - const char* name = nameIn.c_str(); - bool colorLikeView{true}; - bool dsResolveAttachment{false}; - auto clearColor = gfx::Color{}; - auto iter = pass.rasterViews.find(name); - if(iter != pass.rasterViews.end()) { - const auto& view = iter->second; - colorLikeView = view.attachmentType == AttachmentType::RENDER_TARGET || view.attachmentType == AttachmentType::SHADING_RATE; - clearColor = view.clearColor; - } else { - // resolves - const auto resID = vertex(name, ctx.resourceGraph); - const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); - CC_ASSERT(hasResolve && desc.sampleCount == gfx::SampleCount::X1); - colorLikeView = desc.format != gfx::Format::DEPTH_STENCIL && desc.format != gfx::Format::DEPTH; - dsResolveAttachment = !colorLikeView; - } - - if (colorLikeView) { // RenderTarget - data.clearColors.emplace_back(clearColor); - - auto resID = findVertex(name, resg); - visitObject( - resID, resg, - [&](const ManagedResource& res) { - std::ignore = res; - CC_EXPECTS(false); - }, - [&](const ManagedBuffer& res) { - std::ignore = res; - CC_EXPECTS(false); - }, - [&](const ManagedTexture& tex) { - CC_EXPECTS(tex.texture); - fbInfo.colorTextures.emplace_back(tex.texture); - }, - [&](const IntrusivePtr& res) { - std::ignore = res; - CC_EXPECTS(false); - }, - [&](const IntrusivePtr& tex) { - fbInfo.colorTextures.emplace_back(tex); - }, - [&](const IntrusivePtr& fb) { - CC_EXPECTS(fb->getColorTextures().size() == 1); - CC_EXPECTS(fb->getColorTextures().at(0)); - fbInfo.colorTextures.emplace_back(fb->getColorTextures()[index]); - // render window attaches a depthStencil by default, which may differs from renderpassInfo here. - // data.framebuffer = fb; - }, - [&](const RenderSwapchain& sc) { - fbInfo.colorTextures.emplace_back(sc.swapchain->getColorTexture()); - }, - [&](const FormatView& view) { - // TODO(zhouzhenglong): add ImageView support - std::ignore = view; - CC_EXPECTS(false); - }, - [&](const SubresourceView& view) { - // TODO(zhouzhenglong): add ImageView support - std::ignore = view; - CC_EXPECTS(false); - }); - } else { // DepthStencil - if (!dsResolveAttachment) { - data.clearDepth = clearColor.x; - data.clearStencil = static_cast(clearColor.y); - } - - auto &dsAttachment = dsResolveAttachment ? fbInfo.depthStencilResolveTexture : fbInfo.depthStencilTexture; - - auto resID = findVertex(name, resg); - visitObject( - resID, resg, - [&](const ManagedTexture& tex) { - CC_EXPECTS(tex.texture); - dsAttachment = tex.texture.get(); - }, - [&](const IntrusivePtr& tex) { - dsAttachment = tex.get(); - }, - [&](const FormatView& view) { - std::ignore = view; - CC_EXPECTS(false); - }, - [&](const SubresourceView& view) { - std::ignore = view; - CC_EXPECTS(false); - }, - [](const auto& /*unused*/) { - CC_EXPECTS(false); - }); - } - ++index; - } - }; - - const auto passID = ctx.currentInFlightPassID; - const auto ragVertID = ctx.fgd.resourceAccessGraph.passIndex.at(passID); - if (pass.subpassGraph.subpasses.empty()) { - const auto numInputs = getRasterPassInputCount(pass); - const auto numColors = getRasterPassOutputCount(pass); + auto [rpInfo, fbInfo, clearColors, clearDepth, clearStencil] = ctx.fgd.getRenderPassAndFrameBuffer(ctx.currentInFlightPassID, resg); - // persistent cache - data.clearColors.reserve(numColors); - const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); - rpInfo = fgdRpInfo.rpInfo; - fillFrameBufferInfo(fgdRpInfo.orderedViews, false); - - } else { - const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); - rpInfo = fgdRpInfo.rpInfo; - fillFrameBufferInfo(fgdRpInfo.orderedViews, fgdRpInfo.needResolve); - } - CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); + // CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); CC_ENSURES(rpInfo.colorAttachments.size() == fbInfo.colorTextures.size()); + data.clearColors = std::move(clearColors); + data.clearDepth = clearDepth; + data.clearStencil = clearStencil; data.renderPass = ctx.device->createRenderPass(rpInfo); fbInfo.renderPass = data.renderPass; data.framebuffer = ctx.device->createFramebuffer(fbInfo); @@ -660,28 +539,23 @@ gfx::DescriptorSet* initDescriptorSet( } break; case DescriptorTypeOrder::INPUT_ATTACHMENT: { - for (auto d : block.descriptors) { - CC_EXPECTS(d.count == 1); - auto iter = resourceIndex.find(d.descriptorID); - if (iter != resourceIndex.end()) { - // render graph textures - auto* texture = resg.getTexture(iter->second); - gfx::AccessFlags access = gfx::AccessFlagBit::NONE; - if (accessNode != nullptr) { - auto accIter = std::find_if( - accessNode->attachmentStatus.begin(), accessNode->attachmentStatus.end(), - [iter](const AccessStatus& status) { - return status.vertID == iter->second; - }); - access = accIter != accessNode->attachmentStatus.end() ? accIter->accessFlag : gfx::AccessFlagBit::NONE; - } - - CC_ENSURES(texture); - newSet->bindTexture(bindID, texture, 0, access); + for (const auto& [descID, resID] : resourceIndex) { + std::ignore = descID; + // render graph textures + auto* texture = resg.getTexture(resID); + gfx::AccessFlags access = gfx::AccessFlagBit::NONE; + if (accessNode != nullptr) { + // whole access only now. + auto parentID = parent(resID, resg); + parentID = parentID == ResourceGraph::null_vertex() ? resID : parentID; + const auto& resName = get(ResourceGraph::NameTag{}, resg, parentID); + access = accessNode->resourceStatus.at(resName).accessFlag; } - bindID += d.count; - } + CC_ENSURES(texture); + newSet->bindTexture(bindID, texture, 0, access); + bindID += 1; + } }; break; default: @@ -908,26 +782,6 @@ void submitProfilerCommands( cmdBuff->draw(ia); } -PmrFlatMap -buildResourceIndex( - const ResourceGraph& resg, - const LayoutGraphData& lg, - const PmrTransparentMap>& computeViews, - boost::container::pmr::memory_resource* scratch) { - PmrFlatMap resourceIndex(scratch); - resourceIndex.reserve(computeViews.size() * 2); - for (const auto& [resName, computeViews] : computeViews) { - const auto resID = vertex(resName, resg); - for (const auto& computeView : computeViews) { - const auto& name = computeView.name; - CC_EXPECTS(!name.empty()); - const auto nameID = lg.attributeIndex.at(name); - resourceIndex.emplace(nameID, resID); - } - } - return resourceIndex; -} - const PmrTransparentMap>& getComputeViews(RenderGraph::vertex_descriptor passID, const RenderGraph& rg) { if (holds(passID, rg)) { @@ -1073,8 +927,7 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { } // build pass resources - const auto& resourceIndex = buildResourceIndex( - ctx.resourceGraph, ctx.lg, computeViews, ctx.scratch); + const auto& resourceIndex = ctx.fgd.buildDescriptorIndex(computeViews, ctx.scratch); // populate set auto& set = iter->second; @@ -1106,8 +959,7 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { } // build pass resources - const auto& resourceIndex = buildResourceIndex( - ctx.resourceGraph, ctx.lg, computeViews, ctx.scratch); + const auto& resourceIndex = ctx.fgd.buildDescriptorIndex(computeViews, ctx.scratch); // find scene resource const auto* const sceneResource = getFirstSceneResource(vertID); @@ -1148,7 +1000,6 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { const auto& subpass = get(RasterSubpassTag{}, vertID, ctx.g); // render pass const auto& layoutName = get(RenderGraph::LayoutTag{}, ctx.g, vertID); - auto parentLayoutID = ctx.currentPassLayoutID; auto layoutID = parentLayoutID; if (!layoutName.empty()) { @@ -1169,35 +1020,12 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { return; } - // build pass resources - /* const auto& resourceIndex = buildResourceIndex( - ctx.resourceGraph, ctx.lg, subpass.computeViews, ctx.scratch);*/ - PmrFlatMap resourceIndex(ctx.scratch); - - resourceIndex.reserve(subpass.rasterViews.size() * 2); - for (const auto& [resName, rasterView] : subpass.rasterViews) { - const auto resID = vertex(resName, ctx.resourceGraph); - auto ragId = ctx.fgd.resourceAccessGraph.passIndex.at(vertID); - const auto& attachments = ctx.fgd.resourceAccessGraph.access[ragId].attachmentStatus; - auto resIter = std::find_if(attachments.begin(), attachments.end(), [resID](const AccessStatus& status) { - return status.vertID == resID; - }); - - auto slotName = rasterView.slotName; - if (rasterView.accessType == AccessType::READ || rasterView.accessType == AccessType::READ_WRITE) { - slotName.insert(0, "__in"); - } - auto iter = ctx.lg.attributeIndex.find(slotName); - if (iter != ctx.lg.attributeIndex.end()) { - resourceIndex.emplace(iter->second, resID); - } - } - + const auto& resourceIndex = ctx.fgd.buildDescriptorIndex(subpass.computeViews, subpass.rasterViews, ctx.scratch); // populate set auto& set = iter->second; const auto& user = get(RenderGraph::DataTag{}, ctx.g, vertID); auto& node = ctx.context.layoutGraphResources.at(layoutID); - const auto& accessNode = ctx.fgd.getAttachmentStatus(vertID); + const auto& accessNode = ctx.fgd.getAccessNode(vertID); auto* perPassSet = initDescriptorSet( ctx.resourceGraph, @@ -1258,25 +1086,15 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { textureBarriers.data(), textures.data(), static_cast(textureBarriers.size())); } void frontBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); - if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { - return; - } - const auto& nodeID = iter->second; - auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end()) { - submitBarriers(iter2->second.blockBarrier.frontBarriers); + const auto& barrier = ctx.fgd.getBarrier(vertID); + if (!barrier.frontBarriers.empty()) { + submitBarriers(barrier.frontBarriers); } } void rearBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); - if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { - return; - } - const auto& nodeID = iter->second; - auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end()) { - submitBarriers(iter2->second.blockBarrier.rearBarriers); + const auto& barrier = ctx.fgd.getBarrier(vertID); + if (!barrier.rearBarriers.empty()) { + submitBarriers(barrier.rearBarriers); } } void tryBindPerPassDescriptorSet(RenderGraph::vertex_descriptor vertID) const { @@ -1352,6 +1170,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { if (subpass.subpassID) { ctx.cmdBuff->nextSubpass(); } + //ctx.cmdBuff->setViewport(subpass); tryBindPerPassDescriptorSet(vertID); ctx.subpassIndex = subpass.subpassID; // noop @@ -1546,32 +1365,14 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { const auto* scene = camera->getScene(); const auto& queueDesc = ctx.context.sceneCulling.sceneQueryIndex.at(sceneID); const auto& queue = ctx.context.sceneCulling.renderQueues[queueDesc.renderQueueTarget]; - bool bDraw = any(sceneData.flags & SceneFlags::DRAW_NON_INSTANCING); - bool bDrawInstancing = any(sceneData.flags & SceneFlags::DRAW_INSTANCING); - if (!bDraw && !bDrawInstancing) { - bDraw = true; - bDrawInstancing = true; - } - const bool bDrawBlend = any(sceneData.flags & SceneFlags::TRANSPARENT_OBJECT); - const bool bDrawOpaqueOrMask = any(sceneData.flags & (SceneFlags::OPAQUE_OBJECT | SceneFlags::CUTOUT_OBJECT)); - const bool bDrawShadowCaster = any(sceneData.flags & SceneFlags::SHADOW_CASTER); - - if (bDrawShadowCaster || bDrawOpaqueOrMask) { - queue.opaqueQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - if (bDrawInstancing) { - queue.opaqueInstancingQueue.recordCommandBuffer( - ctx.currentPass, ctx.cmdBuff); - } - } - if (bDrawBlend) { - queue.transparentQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - if (bDrawInstancing) { - queue.transparentInstancingQueue.recordCommandBuffer( - ctx.currentPass, ctx.cmdBuff); - } - } + queue.opaqueQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); + queue.opaqueInstancingQueue.recordCommandBuffer( + ctx.currentPass, ctx.cmdBuff); + queue.transparentQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); + queue.transparentInstancingQueue.recordCommandBuffer( + ctx.currentPass, ctx.cmdBuff); if (any(sceneData.flags & SceneFlags::UI)) { submitUICommands(ctx.currentPass, ctx.currentPassLayoutID, camera, ctx.cmdBuff); @@ -1750,41 +1551,41 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } void end(const gfx::Viewport& pass, RenderGraph::vertex_descriptor vertID) const { } + + void mountResource(const ccstd::pmr::string& name) const { // NOLINT(misc-no-recursion) + auto resIter = ctx.fgd.resourceAccessGraph.resourceIndex.find(name); + if (resIter != ctx.fgd.resourceAccessGraph.resourceIndex.end()) { + auto resID = resIter->second; + auto& resg = ctx.resourceGraph; + resg.mount(ctx.device, resID); + for (const auto& subres : makeRange(children(resID, resg))) { + const auto& subresName = get(ResourceGraph::NameTag{}, resg, subres.target); + mountResource(subresName); + } + } + } void mountResources(const Subpass& pass) const { - auto& resg = ctx.resourceGraph; // mount managed resources for (const auto& [name, view] : pass.rasterViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } for (const auto& resolve : pass.resolvePairs) { - auto resID = findVertex(resolve.target, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(resolve.target); } } void mountResources(const RasterPass& pass) const { - auto& resg = ctx.resourceGraph; // mount managed resources for (const auto& [name, view] : pass.rasterViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } - for (const auto& subpass : pass.subpassGraph.subpasses) { mountResources(subpass); } @@ -1794,9 +1595,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } } @@ -1804,9 +1603,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } } @@ -1814,9 +1611,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } } @@ -1824,12 +1619,8 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& pair : pass.resolvePairs) { - const auto& srcID = findVertex(pair.source, resg); - CC_EXPECTS(srcID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, srcID); - const auto& dstID = findVertex(pair.target, resg); - CC_EXPECTS(dstID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, dstID); + mountResource(pair.source); + mountResource(pair.target); } } @@ -1837,17 +1628,11 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& pair : pass.copyPairs) { - const auto& srcID = findVertex(pair.source, resg); - CC_EXPECTS(srcID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, srcID); - const auto& dstID = findVertex(pair.target, resg); - CC_EXPECTS(dstID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, dstID); + mountResource(pair.source); + mountResource(pair.target); } for (const auto& pair : pass.uploadPairs) { - const auto& dstID = findVertex(pair.target, resg); - CC_EXPECTS(dstID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, dstID); + mountResource(pair.target); } } @@ -2223,7 +2008,7 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { RenderGraphVisitorContext ctx{ ppl.nativeContext, lg, rg, ppl.resourceGraph, - fgd, fgd.barrierMap, + fgd, validPasses, ppl.device, submit.primaryCommandBuffer, &ppl, diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index ff89a8cd6dc..f747e151f36 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -42,6 +42,50 @@ namespace cc { namespace render { +template +void addSubresourceNode(ResourceGraph::vertex_descriptor v, const ccstd::string &name, ResourceGraph &resg); + +template <> +void addSubresourceNode(ResourceGraph::vertex_descriptor v, const ccstd::string &name, ResourceGraph &resg) { + SubresourceView view{ + nullptr, + gfx::Format::DEPTH_STENCIL, + 0, 1, 0, 1, 0, 1}; + + auto desc = get(ResourceGraph::DescTag{}, resg, v); + auto traits = get(ResourceGraph::TraitsTag{}, resg, v); + auto samplerInfo = get(ResourceGraph::SamplerTag{}, resg, v); + + ccstd::string depthName{name}; + depthName += "/"; + depthName += DEPTH_PLANE_NAME; + auto depthID = addVertex( + SubresourceViewTag{}, + std::forward_as_tuple(depthName.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(traits.residency), + std::forward_as_tuple(), + std::forward_as_tuple(samplerInfo), + std::forward_as_tuple(view), + resg, + v); + + view.firstPlane = 1; + ccstd::string stencilName{name}; + stencilName += "/"; + stencilName += STENCIL_PLANE_NAME; + auto stencilID = addVertex( + SubresourceViewTag{}, + std::forward_as_tuple(stencilName.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(traits.residency), + std::forward_as_tuple(), + std::forward_as_tuple(samplerInfo), + std::forward_as_tuple(view), + resg, + v); +} + NativePipeline::NativePipeline(const allocator_type &alloc) noexcept : device(gfx::Device::getInstance()), globalDSManager(std::make_unique()), @@ -194,7 +238,8 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format samplerInfo.magFilter = gfx::Filter::POINT; samplerInfo.minFilter = gfx::Filter::POINT; samplerInfo.mipFilter = gfx::Filter::NONE; - return addVertex( + + auto resID = addVertex( ManagedTextureTag{}, std::forward_as_tuple(name.c_str()), std::forward_as_tuple(desc), @@ -203,6 +248,9 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format std::forward_as_tuple(samplerInfo), std::forward_as_tuple(), resourceGraph); + + addSubresourceNode(resID, name, resourceGraph); + return resID; } uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimension dimension, diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index 528c95d5ce7..91c9dcf73b4 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -298,6 +298,21 @@ void addRasterViewImpl( auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); const auto slotID = getSlotID(pass, name, attachmentType); CC_EXPECTS(subpass.rasterViews.size() == subpassData.rasterViews.size()); + auto nameIter = subpassData.rasterViews.find(name); + + if (nameIter != subpassData.rasterViews.end()) { + auto &view = subpass.rasterViews.at(name.data()); + if (!defaultAttachment(slotName)) { + nameIter->second.slotName = slotName; + view.slotName = slotName; + } + if (!defaultAttachment(slotName1)) { + nameIter->second.slotName1 = slotName1; + view.slotName1 = slotName1; + } + return; + } + { auto res = subpassData.rasterViews.emplace( std::piecewise_construct, @@ -321,6 +336,7 @@ void addRasterViewImpl( std::forward_as_tuple(name), std::forward_as_tuple( ccstd::pmr::string(slotName, subpassData.get_allocator()), + ccstd::pmr::string(slotName1, subpassData.get_allocator()), accessType, attachmentType, loadOp, @@ -533,18 +549,18 @@ void NativeRenderSubpassBuilderImpl::setShowStatistics(bool enable) { void NativeMultisampleRenderSubpassBuilder::resolveRenderTarget( const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) auto &subpass = get(RasterSubpassTag{}, nodeID, *renderGraph); - + auto parentID = parent(nodeID, *renderGraph); auto &pass = get(RasterPassTag{}, parentID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); - + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), ResolveFlags::COLOR, gfx::ResolveMode::AVERAGE, gfx::ResolveMode::NONE); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } @@ -559,7 +575,7 @@ void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( if (stencilMode != gfx::ResolveMode::NONE) { flags |= ResolveFlags::STENCIL; } - + auto parentID = parent(nodeID, *renderGraph); auto &pass = get(RasterPassTag{}, parentID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); @@ -570,7 +586,7 @@ void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( flags, depthMode, stencilMode); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } @@ -1137,17 +1153,17 @@ void NativeMultisampleRenderPassBuilder::setShowStatistics(bool enable) { void NativeMultisampleRenderPassBuilder::resolveRenderTarget( const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); - + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); - + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), ResolveFlags::COLOR, gfx::ResolveMode::AVERAGE, gfx::ResolveMode::NONE); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } @@ -1162,7 +1178,7 @@ void NativeMultisampleRenderPassBuilder::resolveDepthStencil( if (stencilMode != gfx::ResolveMode::NONE) { flags |= ResolveFlags::STENCIL; } - + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); @@ -1172,7 +1188,7 @@ void NativeMultisampleRenderPassBuilder::resolveDepthStencil( flags, depthMode, stencilMode); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h index 18858869210..bf1ff547408 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h @@ -211,6 +211,19 @@ void addSubpassComputeViewImpl( subpassData.computeViews.find(std::string_view{name})->second.size()); } +inline bool defaultAttachment(std::string_view slotName) { + return slotName.empty() || slotName == "_"; +} + +static constexpr std::string_view DEPTH_PLANE_NAME = "depth"; +static constexpr std::string_view STENCIL_PLANE_NAME = "stencil"; +static constexpr std::string_view CUBE_TOP_NAME = "Top"; +static constexpr std::string_view CUBE_BOTTOM_NAME = "Bottom"; +static constexpr std::string_view CUBE_FRONT_NAME = "Front"; +static constexpr std::string_view CUBE_REAR_NAME = "Rear"; +static constexpr std::string_view CUBE_LEFT_NAME = "Left"; +static constexpr std::string_view CUBE_RIGHT_NAME = "Right"; + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 984e215a9ad..5c8ce3ee84f 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -22,10 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include #include "NativePipelineTypes.h" #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" #include "cocos/renderer/gfx-base/GFXDevice.h" +#include "details/GraphView.h" #include "details/Range.h" #include "gfx-base/GFXDef-common.h" #include "pipeline/custom/RenderCommonFwd.h" @@ -168,6 +170,23 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { }; } +gfx::TextureViewInfo getTextureViewInfo(const SubresourceView& subresView, const ResourceDesc& desc, bool bCube = false) { + using namespace gfx; // NOLINT(google-build-using-namespace) + + const auto& textureInfo = getTextureInfo(desc, bCube); + + return { + nullptr, + textureInfo.type, + subresView.format, + subresView.indexOrFirstMipLevel, + subresView.numMipLevels, + subresView.firstArraySlice, + subresView.numArraySlices, + subresView.firstPlane, + subresView.numPlanes, + }; +} } // namespace bool ManagedTexture::checkResource(const ResourceDesc& desc) const { @@ -243,10 +262,9 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { CC_EXPECTS(parentID != resg.null_vertex()); CC_EXPECTS(resg.isTexture(parentID)); CC_ENSURES(!resg.isTextureView(parentID)); - mount(device, parentID); + mount(device, parentID); // NOLINT(misc-no-recursion) }, - [&](const SubresourceView& view) { // NOLINT(misc-no-recursion) - std::ignore = view; + [&](SubresourceView& view) { // NOLINT(misc-no-recursion) auto parentID = parent(vertID, resg); CC_EXPECTS(parentID != resg.null_vertex()); while (resg.isTextureView(parentID)) { @@ -255,7 +273,13 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { CC_EXPECTS(parentID != resg.null_vertex()); CC_EXPECTS(resg.isTexture(parentID)); CC_ENSURES(!resg.isTextureView(parentID)); - mount(device, parentID); + auto* parentTexture = resg.getTexture(parentID); + const auto& desc = get(ResourceGraph::DescTag{}, resg, vertID); + if (!view.textureView) { + auto textureViewInfo = getTextureViewInfo(view, desc); + textureViewInfo.texture = parentTexture; + view.textureView = device->createTexture(textureViewInfo); + } }); } @@ -362,8 +386,7 @@ gfx::Texture* ResourceGraph::getTexture(vertex_descriptor resID) { }, [&](const SubresourceView& view) { // TODO(zhouzhenglong): add ImageView support - std::ignore = view; - CC_EXPECTS(false); + texture = view.textureView; }, [&](const auto& buffer) { std::ignore = buffer; diff --git a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp index f2cfd0111b0..0b9a2865259 100644 --- a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp @@ -104,7 +104,7 @@ void SceneCulling::collectCullingQueries( } namespace { - +const pipeline::PipelineSceneData* pSceneData = nullptr; bool isNodeVisible(const Node* node, uint32_t visibility) { return node && ((visibility & node->getLayer()) == node->getLayer()); } @@ -113,9 +113,18 @@ uint32_t isModelVisible(const scene::Model& model, uint32_t visibility) { return visibility & static_cast(model.getVisFlags()); } -bool isFrustumVisible(const scene::Model& model, const geometry::Frustum& frustum) { +bool isFrustumVisible(const scene::Model& model, const geometry::Frustum& frustum, bool castShadow) { const auto* const modelWorldBounds = model.getWorldBounds(); - return !modelWorldBounds || modelWorldBounds->aabbFrustum(frustum); + if (!modelWorldBounds) { + return true; + } + geometry::AABB transWorldBounds{}; + transWorldBounds.set(modelWorldBounds->getCenter(), modelWorldBounds->getHalfExtents()); + const scene::Shadows& shadows = *pSceneData->getShadows(); + if (shadows.getType() == scene::ShadowType::PLANAR && castShadow) { + modelWorldBounds->transform(shadows.getMatLight(), &transWorldBounds); + } + return transWorldBounds.aabbFrustum(frustum); } void octreeCulling( @@ -183,7 +192,7 @@ void bruteForceCulling( // filter model by view visibility if (isNodeVisible(model.getNode(), visibility) || isModelVisible(model, visibility)) { // frustum culling - if (!isFrustumVisible(model, cameraOrLightFrustum)) { + if (!isFrustumVisible(model, cameraOrLightFrustum, bCastShadow)) { continue; } // is skybox, skip @@ -248,14 +257,23 @@ void SceneCulling::batchCulling(const pipeline::PipelineSceneData& pplSceneData) models); break; case scene::LightType::DIRECTIONAL: { - const auto& csmLayers = *pplSceneData.getCSMLayers(); + auto& csmLayers = *pplSceneData.getCSMLayers(); const auto* mainLight = dynamic_cast(light); const auto& csmLevel = mainLight->getCSMLevel(); const geometry::Frustum* frustum = nullptr; - if (mainLight->isShadowFixedArea() || csmLevel == scene::CSMLevel::LEVEL_1) { - frustum = &csmLayers.getSpecialLayer()->getValidFrustum(); + const auto& shadows = *pplSceneData.getShadows(); + if (shadows.getType() == scene::ShadowType::PLANAR) { + frustum = &camera.getFrustum(); } else { - frustum = &csmLayers.getLayers()[level]->getValidFrustum(); + if (shadows.isEnabled() && shadows.getType() == scene::ShadowType::SHADOW_MAP && mainLight && mainLight->getNode()) { + csmLayers.update(&pplSceneData, &camera); + } + // const + if (mainLight->isShadowFixedArea() || csmLevel == scene::CSMLevel::LEVEL_1) { + frustum = &csmLayers.getSpecialLayer()->getValidFrustum(); + } else { + frustum = &csmLayers.getLayers()[level]->getValidFrustum(); + } } sceneCulling( skyboxModelToSkip, @@ -281,7 +299,6 @@ void SceneCulling::batchCulling(const pipeline::PipelineSceneData& pplSceneData) } namespace { - bool isBlend(const scene::Pass& pass) { bool bBlend = false; for (const auto& target : pass.getBlendState()->targets) { @@ -307,7 +324,6 @@ void addRenderObject( LayoutGraphData::vertex_descriptor phaseLayoutID, const bool bDrawOpaqueOrMask, const bool bDrawBlend, - const bool bDrawShadowCaster, const scene::Camera& camera, const scene::Model& model, NativeRenderQueue& queue) { @@ -328,15 +344,13 @@ void addRenderObject( // check scene flags const bool bBlend = isBlend(pass); const bool bOpaqueOrMask = !bBlend; - if (!bDrawShadowCaster) { - if (!bDrawBlend && bBlend) { - // skip transparent object - continue; - } - if (!bDrawOpaqueOrMask && bOpaqueOrMask) { - // skip opaque object - continue; - } + if (!bDrawBlend && bBlend) { + // skip transparent object + continue; + } + if (!bDrawOpaqueOrMask && bOpaqueOrMask) { + // skip opaque object + continue; } // add object to queue @@ -417,7 +431,7 @@ void SceneCulling::fillRenderQueues( // fill native queue for (const auto* const model : sourceModels) { addRenderObject( - phaseLayoutID, bDrawOpaqueOrMask, bDrawBlend, bDrawShadowCaster, + phaseLayoutID, bDrawOpaqueOrMask, bDrawBlend, *sceneData.camera, *model, nativeQueue); } @@ -429,6 +443,7 @@ void SceneCulling::fillRenderQueues( void SceneCulling::buildRenderQueues( const RenderGraph& rg, const LayoutGraphData& lg, const pipeline::PipelineSceneData& pplSceneData) { + pSceneData = &pplSceneData; collectCullingQueries(rg, lg); batchCulling(pplSceneData); fillRenderQueues(rg, pplSceneData); diff --git a/native/cocos/renderer/pipeline/custom/test/test.h b/native/cocos/renderer/pipeline/custom/test/test.h index ed8f44f5eec..f329ac731f4 100644 --- a/native/cocos/renderer/pipeline/custom/test/test.h +++ b/native/cocos/renderer/pipeline/custom/test/test.h @@ -60,7 +60,6 @@ using framegraph::PassBarrierPair; using framegraph::ResourceBarrier; using RasterViews = PmrTransparentMap; using ComputeViews = PmrTransparentMap>; -using BarrierMap = FrameGraphDispatcher::BarrierMap; static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescInfo, const LayoutInfo &layoutInfo, RenderGraph &renderGraph, ResourceGraph &rescGraph, LayoutGraphData &layoutGraphData) { for (const auto &resc : rescInfo) { @@ -104,6 +103,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn auto addRasterNode = [&](const vector>> &subpasses, uint32_t count, uint32_t passID) { const ccstd::string name = "pass" + std::to_string(passID); const auto vertexID = add_vertex(renderGraph, RasterPassTag{}, name.c_str()); + renderGraph.sortedVertices.emplace_back(vertexID); auto &raster = get(RasterPassTag{}, vertexID, renderGraph); auto &subpassGraph = raster.subpassGraph; @@ -195,6 +195,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn const ccstd::string name = "pass" + std::to_string(passCount++); const auto vertexID = add_vertex(renderGraph, ComputeTag{}, name.c_str()); + renderGraph.sortedVertices.emplace_back(vertexID); assert(subpasses.back().size() == 2); // inputs and outputs auto &computePass = get(ComputeTag{}, vertexID, renderGraph); @@ -231,6 +232,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn const ccstd::string name = "pass" + std::to_string(passCount++); const auto vertexID = add_vertex(renderGraph, CopyTag{}, name.c_str()); + renderGraph.sortedVertices.emplace_back(vertexID); assert(subpasses.back().size() == 2); // inputs and outputs auto ©Pass = get(CopyTag{}, vertexID, renderGraph); const auto &inputsAndOutputs = subpasses.back(); @@ -260,302 +262,6 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn fgDispatcher.run(); */ } -static void fillBarriers(const ResourceGraph &resourceGraph, const BarrierPair &barrierInfo, framegraph::PassNodeBuilder &builder, PassBarrierPair &barriers) { - auto doFill = [&builder, &resourceGraph](const std::vector &edgeInfo, std::vector &edgeBarriers) { - for (const auto &resBarrier : edgeInfo) { - const auto &name = get(ResourceGraph::NameTag{}, resourceGraph, resBarrier.resourceID); - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resBarrier.resourceID); - auto type = desc.dimension == ResourceDimension::BUFFER ? cc::framegraph::ResourceType::BUFFER : cc::framegraph::ResourceType::TEXTURE; - framegraph::Range layerRange; - framegraph::Range mipRange; - if (type == framegraph::ResourceType::BUFFER) { - auto bufferRange = ccstd::get(resBarrier.beginStatus.range); - layerRange = {0, 0}; - mipRange = {bufferRange.offset, bufferRange.size}; - } else { - auto textureRange = ccstd::get(resBarrier.beginStatus.range); - layerRange = {textureRange.firstSlice, textureRange.numSlices}; - mipRange = {textureRange.mipLevel, textureRange.levelCount}; - } - - edgeBarriers.emplace_back(cc::framegraph::ResourceBarrier{ - type, - resBarrier.type, - builder.readFromBlackboard(framegraph::FrameGraph::stringToHandle(name.c_str())), - {resBarrier.beginStatus.passType, - resBarrier.beginStatus.visibility, - resBarrier.beginStatus.access}, - {resBarrier.endStatus.passType, - resBarrier.endStatus.visibility, - resBarrier.endStatus.access}, - layerRange, - mipRange, - }); - } - }; - - doFill(barrierInfo.frontBarriers, barriers.frontBarriers); - doFill(barrierInfo.rearBarriers, barriers.rearBarriers); -} - -struct TestRenderData { - ccstd::vector> outputTexes; -}; - -struct FrameGraphPassInfo { - framegraph::FrameGraph &frameGraph; - const RenderGraph &renderGraph; - const ResourceGraph &resourceGraph; - const RasterViews &rasterViews; - const ComputeViews &computeViews; - const BarrierMap &barrierMap; - uint32_t passID{0}; - bool isSubpass{false}; - bool subpassEnd{false}; -}; - -static void addPassToFrameGraph(const FrameGraphPassInfo &info) { - const auto &rasterViews = info.rasterViews; - const auto &passID = info.passID; - const auto &barrierMap = info.barrierMap; - const auto &renderGraph = info.renderGraph; - const auto &resourceGraph = info.resourceGraph; - auto &frameGraph = info.frameGraph; - bool isSupass = info.isSubpass; - bool subpassEnd = info.subpassEnd; - - auto forwardSetup = [&](framegraph::PassNodeBuilder &builder, TestRenderData &data) { - if (isSupass) { - builder.subpass(subpassEnd); - } - - auto goThroughRasterViews = [&](const RasterViews &views) { - for (const auto &view : views) { - const auto handle = framegraph::FrameGraph::stringToHandle(view.second.slotName.c_str()); - auto typedHandle = builder.readFromBlackboard(handle); - data.outputTexes.emplace_back(); - auto &lastTex = data.outputTexes.back(); - framegraph::Texture::Descriptor colorTexInfo; - colorTexInfo.format = gfx::Format::RGBA8; - - // if (rasterView.second.accessType == AccessType::READ) { - colorTexInfo.usage = gfx::TextureUsage::INPUT_ATTACHMENT | gfx::TextureUsage::COLOR_ATTACHMENT; - //} - lastTex.first = view.second.accessType; - lastTex.second = static_cast(typedHandle); - - if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { - colorTexInfo.width = 960; - colorTexInfo.height = 640; - - lastTex.second = builder.create(handle, colorTexInfo); - } - - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = view.second.attachmentType == AttachmentType::RENDER_TARGET ? framegraph::RenderTargetAttachment::Usage::COLOR : framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - colorAttachmentInfo.clearColor = view.second.clearColor; - colorAttachmentInfo.loadOp = view.second.loadOp; - if (view.second.accessType == AccessType::WRITE) { - lastTex.second = builder.write(lastTex.second, colorAttachmentInfo); - builder.writeToBlackboard(handle, lastTex.second); - colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE; - } else { - colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COLOR_ATTACHMENT_READ; - auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); - builder.writeToBlackboard(handle, res); - } - } - }; - - auto goThroughComputeViews = [&](const ComputeViews &views) { - for (const auto &pair : views) { - for (const auto &view : pair.second) { - const auto handle = framegraph::FrameGraph::stringToHandle(view.name.c_str()); - auto typedHandle = builder.readFromBlackboard(handle); - data.outputTexes.emplace_back(); - auto &lastTex = data.outputTexes.back(); - framegraph::Texture::Descriptor colorTexInfo; - colorTexInfo.format = gfx::Format::RGBA8; - - // if (rasterView.second.accessType == AccessType::READ) { - colorTexInfo.usage = gfx::TextureUsage::INPUT_ATTACHMENT | gfx::TextureUsage::COLOR_ATTACHMENT; - //} - lastTex.first = view.accessType; - lastTex.second = static_cast(typedHandle); - - if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { - colorTexInfo.width = 960; - colorTexInfo.height = 640; - - lastTex.second = builder.create(handle, colorTexInfo); - } - - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - - if (view.accessType == AccessType::WRITE) { - lastTex.second = builder.write(lastTex.second); - builder.writeToBlackboard(handle, lastTex.second); - } else { - auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); - builder.writeToBlackboard(handle, res); - } - } - } - }; - - goThroughRasterViews(info.rasterViews); - goThroughComputeViews(info.computeViews); - - builder.setViewport({0U, 640U, 0U, 960U, 0.0F, 1.0F}, {0U, 0U, 960U, 640U}); - - if (barrierMap.find(passID + 1) == barrierMap.end()) { - return; - } - const auto &barrier = barrierMap.at(passID + 1); - PassBarrierPair barrierPairs; - fillBarriers(resourceGraph, barrier.blockBarrier, builder, barrierPairs); - builder.setBarrier(barrierPairs); - }; - - auto forwardExec = [](const TestRenderData &data, - const framegraph::DevicePassResourceTable &table) { - /*for(const auto& pair: data.outputTexes) { - if(pair.first == AccessType::WRITE) { - table.getWrite(pair.second); - } - if(pair.first == AccessType::READ) { - table.getRead(pair.second); - } - if(pair.first == AccessType::READ_WRITE) { - table.getRead(pair.second); - table.getWrite(pair.second); - } - }*/ - }; - - auto passHandle = framegraph::FrameGraph::stringToHandle(get(RenderGraph::NameTag{}, renderGraph, passID).c_str()); - - string presentHandle; - - for (const auto &view : rasterViews) { - // write or read_write - if (view.second.accessType != AccessType::READ) { - presentHandle = view.first; - break; - } - } - - frameGraph.addPass(static_cast(ForwardInsertPoint::IP_FORWARD), passHandle, forwardSetup, forwardExec); -} - -static void runTestGraph(const RenderGraph &renderGraph, const ResourceGraph &resourceGraph, const LayoutGraphData &layoutGraphData, const FrameGraphDispatcher &fgDispatcher) { - const auto &barriers = fgDispatcher.getBarriers(); - - framegraph::FrameGraph framegraph; - - auto *device = gfx::Device::getInstance(); - if (!device) { - device = gfx::DeviceManager::create(); - } - - for (const auto passID : makeRange(vertices(renderGraph))) { - visitObject( - passID, renderGraph, - [&](const RasterPass &pass) { - // TestRenderData tmpData; - const auto &subpasses = get(SubpassGraph::SubpassTag{}, pass.subpassGraph); - uint32_t count = 0; - for (const auto &subpass : *subpasses.container) { - FrameGraphPassInfo info = { - framegraph, - renderGraph, - resourceGraph, - subpass.rasterViews, - subpass.computeViews, - fgDispatcher.getBarriers(), - passID, - true, - count < subpasses.container->size() - 1}; - addPassToFrameGraph(info); - ++count; - }; - if ((*subpasses.container).empty()) { - FrameGraphPassInfo info = { - framegraph, - renderGraph, - resourceGraph, - pass.rasterViews, - pass.computeViews, - fgDispatcher.getBarriers(), - passID, - false, - false}; - addPassToFrameGraph(info); - ++count; - } - }, - [&](const ComputePass &pass) { - // TestRenderData tmpData; - FrameGraphPassInfo info = { - framegraph, - renderGraph, - resourceGraph, - {}, - pass.computeViews, - fgDispatcher.getBarriers(), - passID, - false, - false}; - addPassToFrameGraph(info); - }, - [&](const CopyPass &pass) { - auto forwardSetup = [&](framegraph::PassNodeBuilder &builder, TestRenderData &data) { - for (const auto &pair : pass.copyPairs) { - for (size_t i = 0; i < 2; ++i) { - bool write = (i % 2 == 0); - const auto handle = framegraph::FrameGraph::stringToHandle(write ? pair.target.c_str() : pair.source.c_str()); - auto typedHandle = builder.readFromBlackboard(handle); - data.outputTexes.emplace_back(); - auto &lastTex = data.outputTexes.back(); - framegraph::Texture::Descriptor colorTexInfo; - colorTexInfo.format = gfx::Format::RGBA8; - colorTexInfo.usage = write ? gfx::TextureUsage::TRANSFER_DST : gfx::TextureUsage::TRANSFER_SRC; - - lastTex.second = static_cast(typedHandle); - - if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { - colorTexInfo.width = 960; - colorTexInfo.height = 640; - - lastTex.second = builder.create(handle, colorTexInfo); - } - - if (write) { - lastTex.second = builder.write(lastTex.second); - builder.writeToBlackboard(handle, lastTex.second); - } else { - auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); - builder.writeToBlackboard(handle, res); - } - } - } - }; - - auto forwardExec = [](const TestRenderData &data, - const framegraph::DevicePassResourceTable &table) { - }; - - auto passHandle = framegraph::FrameGraph::stringToHandle(get(RenderGraph::NameTag{}, renderGraph, passID).c_str()); - framegraph.addPass(static_cast(ForwardInsertPoint::IP_FORWARD), passHandle, forwardSetup, forwardExec); - }, - [&](const RaytracePass &pass) {}, - [&](const auto & /*pass*/) {}); - } - framegraph.compile(); - framegraph.execute(); - framegraph.reset(); -} - #define TEST_CASE_DEFINE \ using namespace cc::render; \ using cc::gfx::AccessFlagBit; \ diff --git a/native/tests/unit-test/src/complicated_barrier_case.cpp b/native/tests/unit-test/src/complicated_barrier_case.cpp index 3fdb5ae8a40..a837a4867a1 100644 --- a/native/tests/unit-test/src/complicated_barrier_case.cpp +++ b/native/tests/unit-test/src/complicated_barrier_case.cpp @@ -46,202 +46,67 @@ TEST(complicatedBarrierTest, test12) { }); }; - const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& barrierMap = fgDispatcher.resourceAccessGraph.barrier; const auto& rag = fgDispatcher.resourceAccessGraph; - ExpectEq(rag._vertices.size() == 17, true); + ExpectEq(rag._vertices.size() == 23, true); // head const auto& head = barrierMap.at(0); - ExpectEq(head.blockBarrier.frontBarriers.empty(), true); - ExpectEq(head.blockBarrier.rearBarriers.empty(), true); - ExpectEq(head.subpassBarriers.empty(), true); + ExpectEq(head.frontBarriers.empty(), true); + ExpectEq(head.rearBarriers.empty(), true); // 1st node const auto& node1 = barrierMap.at(1); // block barrier: replace by rnderpass info, same below //ExpectEq(node1.blockBarrier.frontBarriers.size() == 2, true); //ExpectEq(node1.blockBarrier.rearBarriers.size() == 1, true); - ExpectEq(node1.subpassBarriers.empty(), false); - - //ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].resourceID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].beginStatus.vertID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.vertID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); - - //subpass barrier: like normal pass - const auto& node1subpass = node1.subpassBarriers; - ExpectEq(node1subpass[0].frontBarriers.empty(), false); - ExpectEq(node1subpass[0].rearBarriers.size() == 1, true); - - // undefined external depends - const auto& node1subpassres0 = node1subpass[0].rearBarriers[0]; - ExpectEq(node1subpassres0.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node1subpassres0.resourceID == 0, true); - // vertid in subpass:subpass index, same below - ExpectEq(node1subpassres0.beginStatus.vertID == 0, true); - ExpectEq(node1subpassres0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node1subpassres0.beginStatus.passType == PassType::RASTER, true); - ExpectEq(node1subpassres0.endStatus.vertID == 1, true); - ; - ExpectEq(node1subpassres0.endStatus.access == MemoryAccessBit::READ_ONLY, true); - ExpectEq(node1subpassres0.endStatus.passType == PassType::RASTER, true); - - ExpectEq(node1subpass[1].frontBarriers.size() == 1, true); - const auto& node1subpassres1 = node1subpass[1].rearBarriers[0]; - ExpectEq(node1subpassres1.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node1subpassres1.resourceID == 1, true); - ExpectEq(node1subpassres1.beginStatus.vertID == 1, true); - ExpectEq(node1subpassres1.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node1subpassres1.beginStatus.passType == PassType::RASTER, true); - ExpectEq(node1subpassres1.endStatus.vertID == 1, true); - ; - ExpectEq(node1subpassres1.endStatus.access == MemoryAccessBit::READ_ONLY, true); - ExpectEq(node1subpassres1.endStatus.passType == PassType::RASTER, true); - - //node2 - const auto& node2 = barrierMap.at(2); - //ExpectEq(node2.blockBarrier.frontBarriers.size() == 2, true); - //ExpectEq(node2.blockBarrier.rearBarriers.size() == 1, true); - ExpectEq(node2.subpassBarriers.size() == 2, true); - - //const auto& node2blockRear = node2.blockBarrier.rearBarriers; - //auto iter3in2 = findBarrierByResID(node2blockRear, 3); - //const auto& res3in2 = (*iter3in2); - //ExpectEq(res3in2.resourceID == 3, true); - //ExpectEq(res3in2.type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(res3in2.beginStatus.vertID == 2, true); - //ExpectEq(res3in2.beginStatus.passType == PassType::RASTER, true); - //ExpectEq(res3in2.endStatus.vertID == 2, true); - //ExpectEq(res3in2.endStatus.passType == PassType::RASTER, true); - - const auto& node2subpass = node2.subpassBarriers; - ExpectEq(node2subpass.empty(), false); - // subpass dependency instead of extra barrier - ExpectEq(node2subpass[0].frontBarriers.size() == 1, true); - ExpectEq(node2subpass[0].rearBarriers.empty(), false); - - const auto& node2subpassRes2 = node2subpass[0].rearBarriers[0]; - ExpectEq(node2subpassRes2.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node2subpassRes2.resourceID == 2, true); - ExpectEq(node2subpassRes2.beginStatus.vertID == 0, true); - ExpectEq(node2subpassRes2.beginStatus.passType == PassType::RASTER, true); - ExpectEq(node2subpassRes2.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node2subpassRes2.endStatus.vertID == 1, true); - ExpectEq(node2subpassRes2.endStatus.access == MemoryAccessBit::READ_ONLY, true); //node3 // renderpass info layout instead - const auto& node3 = barrierMap.at(3); - ExpectEq(node3.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node3.blockBarrier.rearBarriers.empty(), true); - - // subpass barrier size is the same as renderpass subpassinfo, though maybe empty. - ExpectEq(node3.subpassBarriers.size() == 1, true); - ExpectEq(node3.subpassBarriers.front().frontBarriers.empty(), true); - ExpectEq(node3.subpassBarriers.front().rearBarriers.empty(), true); - - //node4 - const auto& node4 = barrierMap.at(4); - //ExpectEq(node4.blockBarrier.frontBarriers.size() == 2, true); - //ExpectEq(node4.blockBarrier.rearBarriers.size() == 1, true); - ExpectEq(node4.subpassBarriers.empty(), false); - - //const auto& node4block = node4.blockBarrier; - //auto iter5in4 = findBarrierByResID(node4block.rearBarriers, 5); - //ExpectEq(iter5in4 == node4block.rearBarriers.end(), true); - - //auto iter6in4 = findBarrierByResID(node4block.rearBarriers, 6); - //ExpectEq(iter6in4 != node4block.rearBarriers.end(), true); - //ExpectEq((*iter6in4).type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq((*iter6in4).resourceID == 6, true); - //ExpectEq((*iter6in4).beginStatus.vertID == 4, true); - //ExpectEq((*iter6in4).endStatus.vertID == 14, true); - - const auto& node4subpass0 = node4.subpassBarriers[0]; - // subpass undefined external depends - ExpectEq(node4subpass0.frontBarriers.empty(), false); - ExpectEq(node4subpass0.rearBarriers.size() == 1, true); - ExpectEq(node4subpass0.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node4subpass0.rearBarriers[0].resourceID == 5, true); - ExpectEq(node4subpass0.rearBarriers[0].beginStatus.vertID == 0, true); - ExpectEq(node4subpass0.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node4subpass0.rearBarriers[0].endStatus.vertID == 1, true); - ExpectEq(node4subpass0.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); - - const auto& node4subpass1 = node4.subpassBarriers[1]; - ExpectEq(node4subpass1.frontBarriers.empty(), false); - ExpectEq(node4subpass1.rearBarriers.size() == 1, true); - ExpectEq(node4subpass1.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - ExpectEq(node4subpass1.rearBarriers[0].resourceID == 6, true); - // external subpass depends - ExpectEq(node4subpass1.rearBarriers[0].beginStatus.vertID == 0xFFFFFFFF, true); - ExpectEq(node4subpass1.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - // external subpass depends - ExpectEq(node4subpass1.rearBarriers[0].endStatus.vertID == 0xFFFFFFFF, true); - ExpectEq(node4subpass1.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); - - const auto& node5 = barrierMap.at(5); - ExpectEq(node5.blockBarrier.frontBarriers.size() == 1, true); - ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); - // not raster pass - ExpectEq(node5.subpassBarriers.empty(), true); - - auto iter7in5 = findBarrierByResID(node5.blockBarrier.rearBarriers, 7); - const auto& res7in5 = (*iter7in5); - ExpectEq(res7in5.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(res7in5.resourceID == 7, true); - ExpectEq(res7in5.beginStatus.vertID == 5, true); - ExpectEq(res7in5.endStatus.vertID == 5, true); - ExpectEq(res7in5.beginStatus.passType == PassType::COPY, true); - ExpectEq(res7in5.endStatus.passType == PassType::COPY, true); - ExpectEq(res7in5.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(res7in5.endStatus.access == MemoryAccessBit::READ_ONLY, true); - - const auto& node6 = barrierMap.at(6); - ExpectEq(node6.blockBarrier.frontBarriers.size() == 1, true); + const auto& node3 = barrierMap.at(7); + ExpectEq(node3.frontBarriers.empty(), true); + ExpectEq(node3.rearBarriers.empty(), true); + + const auto& node11 = barrierMap.at(11); + ExpectEq(node11.frontBarriers.size() == 1, true); + ExpectEq(node11.rearBarriers.size() == 1, true); + + auto iter7in11 = findBarrierByResID(node11.rearBarriers, 7); + const auto& res7in11 = (*iter7in11); + ExpectEq(res7in11.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(res7in11.resourceID == 7, true); + ExpectEq(res7in11.beginStatus.accessFlag == AccessFlagBit::TRANSFER_WRITE, true); + ExpectEq(res7in11.endStatus.accessFlag == AccessFlagBit::TRANSFER_READ, true); + + const auto& node12 = barrierMap.at(12); + ExpectEq(node12.frontBarriers.size() == 1, true); // resource later used by raster pass, so that layout can be transferred automatically. - ExpectEq(node6.blockBarrier.rearBarriers.empty(), true); - // not a raster pass - ExpectEq(node6.subpassBarriers.empty(), true); + ExpectEq(node12.rearBarriers.empty(), true); // node7 - const auto& node7 = barrierMap.at(7); + const auto& node13 = barrierMap.at(13); // undefined layout already in initial layout - ExpectEq(node7.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node7.blockBarrier.rearBarriers.empty(), true); - ExpectEq(node7.subpassBarriers.empty(), false); - - ExpectEq(node7.blockBarrier.rearBarriers.size(), 0); - - //node8: almost the same as node7 - //node9: almost the same as node8 - //node10: ditto - //node11: ditto - //node12: ditto + ExpectEq(node13.frontBarriers.empty(), true); + ExpectEq(node13.rearBarriers.empty(), true); //node13 - const auto& node13 = barrierMap.at(13); - ExpectEq(node13.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node13.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node13.subpassBarriers.empty(), false); + const auto& node19 = barrierMap.at(19); + ExpectEq(node19.frontBarriers.size(), 0); + ExpectEq(node19.rearBarriers.size(), 0); //node14: almost the same as 13 //node15: ditto - const auto& node15 = barrierMap.at(15); - const auto& theone = node15.blockBarrier.rearBarriers.front(); + const auto& node21 = barrierMap.at(21); + const auto& theone = node21.rearBarriers.front(); ExpectEq(theone.resourceID == 22, true); ExpectEq(theone.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(theone.endStatus.vertID == 0xFFFFFFFF, true); + ExpectEq(theone.endStatus.accessFlag == AccessFlagBit::PRESENT, true); //node16 const auto& node16 = barrierMap.at(16); - ExpectEq(node16.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node16.blockBarrier.rearBarriers.empty(), true); - // not raster pass - ExpectEq(node16.subpassBarriers.empty(), true); + ExpectEq(node16.frontBarriers.empty(), true); + ExpectEq(node16.rearBarriers.empty(), true); //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); } diff --git a/native/tests/unit-test/src/simple_barrier_test.cpp b/native/tests/unit-test/src/simple_barrier_test.cpp index d6c7dc7b5fc..108418e7ced 100644 --- a/native/tests/unit-test/src/simple_barrier_test.cpp +++ b/native/tests/unit-test/src/simple_barrier_test.cpp @@ -40,44 +40,22 @@ TEST(barrierTest, test10) { FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, resource, resource); fgDispatcher.run(); - const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& barrierMap = fgDispatcher.resourceAccessGraph.barrier; const auto& rag = fgDispatcher.resourceAccessGraph; - ExpectEq(rag._vertices.size() == 4, true); + ExpectEq(rag._vertices.size() == 6, true); // head const auto& head = barrierMap.at(0); - ExpectEq(head.blockBarrier.frontBarriers.empty(), true); - ExpectEq(head.blockBarrier.rearBarriers.empty(), true); - - // 1st node - const auto& node1 = barrierMap.at(1); - //ExpectEq(node1.blockBarrier.frontBarriers.size() == 4, true); - //ExpectEq(node1.blockBarrier.rearBarriers.size() == 1, true); - - // undefined external - ExpectEq(node1.subpassBarriers[0].frontBarriers.size() == 3, true); - ExpectEq(node1.subpassBarriers[0].rearBarriers.size() == 3, true); - - // undefined external - ExpectEq(node1.subpassBarriers[1].frontBarriers.size() == 1, true); - ExpectEq(node1.subpassBarriers[1].rearBarriers.size() == 1, true); - - //const auto& barrier = node1.blockBarrier.rearBarriers[0]; - //ExpectEq(barrier.type == BarrierType::FULL, true); - //ExpectEq(barrier.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ////resID 3 - //ExpectEq(barrier.beginStatus.visibility == std::get<2>(layoutInfo[0][3]), true); + ExpectEq(head.frontBarriers.empty(), true); + ExpectEq(head.rearBarriers.empty(), true); //// 2nd node - const auto& node2 = barrierMap.at(2); - ExpectEq(node2.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node2.blockBarrier.rearBarriers.size() == 1, true); + const auto& node4 = barrierMap.at(4); + ExpectEq(node4.frontBarriers.size(), 0); + ExpectEq(node4.rearBarriers.size() == 1, true); - const auto& node2RearBarrier0 = node2.blockBarrier.rearBarriers.back(); - ExpectEq(node2RearBarrier0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node2RearBarrier0.beginStatus.visibility == ShaderStageFlagBit::FRAGMENT, true); - ExpectEq(node2RearBarrier0.endStatus.accessFlag == AccessFlagBit::PRESENT, true); - //endstatus: whatever it was, it's COLOR_ATTACHMENT_OPTIMAL + const auto& node4RearBarrier0 = node4.rearBarriers.back(); + ExpectEq(node4RearBarrier0.endStatus.accessFlag == AccessFlagBit::PRESENT, true); //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); } diff --git a/native/tests/unit-test/src/simple_closed_barrier_test.cpp b/native/tests/unit-test/src/simple_closed_barrier_test.cpp index 644132e90fb..095cc345508 100644 --- a/native/tests/unit-test/src/simple_closed_barrier_test.cpp +++ b/native/tests/unit-test/src/simple_closed_barrier_test.cpp @@ -40,148 +40,29 @@ TEST(simpleClosedBarrierTest, test11) { FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, resource, resource); fgDispatcher.run(); - const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& barrierMap = fgDispatcher.resourceAccessGraph.barrier; const auto& rag = fgDispatcher.resourceAccessGraph; ExpectEq(rag._vertices.size() == 10, true); // head const auto& head = barrierMap.at(0); - ExpectEq(head.blockBarrier.frontBarriers.empty(), true); - ExpectEq(head.blockBarrier.rearBarriers.empty(), true); - ExpectEq(head.subpassBarriers.empty(), true); + ExpectEq(head.frontBarriers.empty(), true); + ExpectEq(head.rearBarriers.empty(), true); // 1st node const auto& node1 = barrierMap.at(1); - ExpectEq(node1.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node1.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node1.subpassBarriers.size() == 1, true); - ExpectEq(node1.subpassBarriers.front().frontBarriers.empty(), true); - ExpectEq(node1.subpassBarriers.front().rearBarriers.empty(), true); - - // transitioned by renderpass info - //ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.vertID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node1.blockBarrier.rearBarriers[1].endStatus.vertID == 3, true); + ExpectEq(node1.frontBarriers.size(), 0); + ExpectEq(node1.rearBarriers.size(), 0); const auto& node2 = barrierMap.at(2); - ExpectEq(node2.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node2.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node2.subpassBarriers.size() == 1, true); - ExpectEq(node2.subpassBarriers.front().frontBarriers.empty(), true); - ExpectEq(node2.subpassBarriers.front().rearBarriers.empty(), true); - - // ditto - //// res3 - //ExpectEq(node2.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node2.blockBarrier.rearBarriers[1].beginStatus.vertID == 2, true); - //ExpectEq(node2.blockBarrier.rearBarriers[1].endStatus.vertID == 5, true); - //// res2 - //ExpectEq(node2.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node2.blockBarrier.rearBarriers[0].beginStatus.vertID == 2, true); - //ExpectEq(node2.blockBarrier.rearBarriers[0].endStatus.vertID == 4, true); - - //const auto& node3 = barrierMap.at(3); - //ExpectEq(node3.blockBarrier.frontBarriers.size() == 3, true); - //ExpectEq(node3.blockBarrier.rearBarriers.size() == 2, true); - //ExpectEq(node3.subpassBarriers.empty(), true); - - //const auto& res1Index = std::find_if(node3.blockBarrier.frontBarriers.begin(), node3.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 1; }); - //ExpectEq(res1Index != node3.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res1Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res1Index->beginStatus.vertID == 1, true); - //ExpectEq(res1Index->endStatus.vertID == 3, true); - //// res 5 - //ExpectEq(node3.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node3.blockBarrier.rearBarriers[0].beginStatus.vertID == 3, true); - //ExpectEq(node3.blockBarrier.rearBarriers[0].endStatus.vertID == 3, true); - //// res 4 - //ExpectEq(node3.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node3.blockBarrier.rearBarriers[1].beginStatus.vertID == 3, true); - //ExpectEq(node3.blockBarrier.rearBarriers[1].endStatus.vertID == 5, true); - - //const auto& node4 = barrierMap.at(4); - //ExpectEq(node4.blockBarrier.frontBarriers.size() == 2, true); - //ExpectEq(node4.blockBarrier.rearBarriers.size() == 1, true); - //ExpectEq(node4.subpassBarriers.empty(), true); - - //const auto& res3Index = std::find_if(node4.blockBarrier.frontBarriers.begin(), node4.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 3; }); - //ExpectEq(res3Index != node4.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res3Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res3Index->beginStatus.vertID == 2, true); - //ExpectEq(res3Index->endStatus.vertID == 4, true); - - //ExpectEq(node4.blockBarrier.rearBarriers[0].resourceID == 6, true); - //ExpectEq(node4.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node4.blockBarrier.rearBarriers[0].beginStatus.vertID == 4, true); - //ExpectEq(node4.blockBarrier.rearBarriers[0].endStatus.vertID == 4, true); - - //const auto& node5 = barrierMap.at(5); - //ExpectEq(node5.blockBarrier.frontBarriers.size() == 3, true); - //ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); - //ExpectEq(node5.subpassBarriers.empty(), true); - - //const auto& res2Index = std::find_if(node5.blockBarrier.frontBarriers.begin(), node5.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 2; }); - //ExpectEq(res2Index != node5.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res2Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res2Index->beginStatus.vertID == 2, true); - //ExpectEq(res2Index->endStatus.vertID == 5, true); - //const auto& res4Index = std::find_if(node5.blockBarrier.frontBarriers.begin(), node5.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 4; }); - //ExpectEq(res4Index != node5.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res4Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res4Index->beginStatus.vertID == 3, true); - //ExpectEq(res4Index->endStatus.vertID == 5, true); - - //ExpectEq(node5.blockBarrier.rearBarriers[0].resourceID == 7, true); - //ExpectEq(node5.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node5.blockBarrier.rearBarriers[0].beginStatus.vertID == 5, true); - //ExpectEq(node5.blockBarrier.rearBarriers[0].endStatus.vertID == 8, true); - - //const auto& node6 = barrierMap.at(6); - //ExpectEq(node6.blockBarrier.frontBarriers.size() == 1, true); - //ExpectEq(node6.blockBarrier.rearBarriers.size() == 1, true); - //ExpectEq(node6.subpassBarriers.empty(), true); - - //ExpectEq(node6.blockBarrier.rearBarriers[0].resourceID == 8, true); - //ExpectEq(node6.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node6.blockBarrier.rearBarriers[0].beginStatus.vertID == 6, true); - //ExpectEq(node6.blockBarrier.rearBarriers[0].endStatus.vertID == 6, true); - - //const auto& node7 = barrierMap.at(7); - //ExpectEq(node7.subpassBarriers.empty(), true); - //ExpectEq(node7.blockBarrier.frontBarriers.size() == 1, true); - //ExpectEq(node7.blockBarrier.rearBarriers.size() == 1, true); - - //ExpectEq(node7.blockBarrier.rearBarriers[0].resourceID == 9, true); - //ExpectEq(node7.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node7.blockBarrier.rearBarriers[0].beginStatus.vertID == 7, true); - //ExpectEq(node7.blockBarrier.rearBarriers[0].endStatus.vertID == 7, true); - - //const auto& node8 = barrierMap.at(8); - //ExpectEq(node8.subpassBarriers.empty(), true); - //ExpectEq(node8.blockBarrier.frontBarriers.empty(), false); // size == 1 - //ExpectEq(node8.blockBarrier.rearBarriers.size() == 1, true); - - //ExpectEq(node8.blockBarrier.frontBarriers[1].resourceID == 7, true); - //ExpectEq(node8.blockBarrier.frontBarriers[1].type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(node8.blockBarrier.frontBarriers[1].beginStatus.vertID == 5, true); - //ExpectEq(node8.blockBarrier.frontBarriers[1].endStatus.vertID == 8, true); - - //ExpectEq(node8.blockBarrier.rearBarriers[0].resourceID == 22, true); - //ExpectEq(node8.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node8.blockBarrier.rearBarriers[0].beginStatus.vertID == 8, true); - //ExpectEq(node8.blockBarrier.rearBarriers[0].endStatus.vertID == 0xFFFFFFFF, true); + ExpectEq(node2.frontBarriers.size(), 0); + ExpectEq(node2.rearBarriers.size(), 0); // TODO: validate renderpassInfo instead const auto& node9 = barrierMap.at(9); - ExpectEq(node9.subpassBarriers.empty(), true); - ExpectEq(node9.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node9.blockBarrier.rearBarriers.empty(), true); - // const auto& node2RearBarrier0 = node2.blockBarrier.rearBarriers.back(); - // ExpectEq(node2RearBarrier0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - // ExpectEq(node2RearBarrier0.beginStatus.visibility == ShaderStageFlagBit::VERTEX, true); - // ExpectEq(node2RearBarrier0.endStatus.access == MemoryAccessBit::READ_ONLY, true); + ExpectEq(node9.frontBarriers.empty(), true); + ExpectEq(node9.rearBarriers.empty(), true); //endstatus: whatever it was, it's COLOR_ATTACHMENT_OPTIMAL //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); From 46a59abe0c5cbf0b1270333f304eb495eb5f1d42 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Wed, 9 Aug 2023 16:04:27 +0800 Subject: [PATCH 117/232] refactor : prefab code optimization and protection (#15845) * refactor : prefab code optimization and protection * remove extra if * remove extra param * replace class with interface * Update cocos/scene-graph/prefab/utils.ts Co-authored-by: PP * remove command and protect access * add prefab getter in node.jsb.ts --------- Co-authored-by: PP --- cocos/scene-graph/node.jsb.ts | 32 +++++++++-- cocos/scene-graph/node.ts | 6 +- cocos/scene-graph/prefab/prefab-info.ts | 4 +- cocos/scene-graph/prefab/utils.ts | 73 +++++++++++-------------- 4 files changed, 67 insertions(+), 48 deletions(-) diff --git a/cocos/scene-graph/node.jsb.ts b/cocos/scene-graph/node.jsb.ts index 3f4308293ce..ed2e4274521 100644 --- a/cocos/scene-graph/node.jsb.ts +++ b/cocos/scene-graph/node.jsb.ts @@ -1016,6 +1016,14 @@ Object.defineProperty(nodeProto, '_siblingIndex', { }, }); +Object.defineProperty(nodeProto, 'prefab', { + configurable: true, + enumerable: true, + get() { + return this._prefab; + }, +}); + // External classes need to access it through getter/setter Object.defineProperty(nodeProto, 'siblingIndex', { configurable: true, @@ -1214,11 +1222,25 @@ nodeProto[serializeTag] = function (serializationOutput: SerializationOutput, co // discard props disallow to synchronize const isRoot = this._prefab?.root === this; if (isRoot) { - serializationOutput.writeProperty('_objFlags', this._objFlags); - serializationOutput.writeProperty('_parent', this._parent); - serializationOutput.writeProperty('_prefab', this._prefab); - if (context.customArguments.keepNodeUuid) { - serializationOutput.writeProperty('_id', this._id); + // if B prefab is in A prefab,B can be referenced by component.We should discard it.because B is not the root of prefab + let isNestedPrefab = false; + let parent = this.getParent(); + while (parent) { + const nestedRoots = parent._prefab?.nestedPrefabInstanceRoots; + if (nestedRoots && nestedRoots.length > 0) { + // if this node is not in nestedPrefabInstanceRoots,it means this node is not the root of prefab,so it should be discarded. + isNestedPrefab = !nestedRoots.some((root) => root === this); + break; + } + parent = parent.getParent(); + } + if (!isNestedPrefab) { + serializationOutput.writeProperty('_objFlags', this._objFlags); + serializationOutput.writeProperty('_parent', this._parent); + serializationOutput.writeProperty('_prefab', this._prefab); + if (context.customArguments.keepNodeUuid) { + serializationOutput.writeProperty('_id', this._id); + } } // TODO: editorExtrasTag may be a symbol in the future serializationOutput.writeProperty(editorExtrasTag, this[editorExtrasTag]); diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index aa7607d4aa1..c1724a27da3 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -363,6 +363,10 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { */ @serializable protected _prefab: PrefabInfo | null = null; + /** + * @engineInternal + */ + public get prefab (): PrefabInfo | null { return this._prefab; } protected _scene: Scene = null!; @@ -1806,7 +1810,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { let isNestedPrefab = false; let parent = this.getParent(); while (parent) { - const nestedRoots = parent?._prefab?.nestedPrefabInstanceRoots; + const nestedRoots = parent._prefab?.nestedPrefabInstanceRoots; if (nestedRoots && nestedRoots.length > 0) { // if this node is not in nestedPrefabInstanceRoots,it means this node is not the root of prefab,so it should be discarded. isNestedPrefab = !nestedRoots.some((root) => root === this); diff --git a/cocos/scene-graph/prefab/prefab-info.ts b/cocos/scene-graph/prefab/prefab-info.ts index f4427d7a04c..dac885a21aa 100644 --- a/cocos/scene-graph/prefab/prefab-info.ts +++ b/cocos/scene-graph/prefab/prefab-info.ts @@ -167,7 +167,7 @@ export class PrefabInstance { @type([TargetInfo]) public removedComponents: TargetInfo[] = []; - public targetMap: Record = {}; + public targetMap: TargetMap = {}; /** * make sure prefab instance expand only once @@ -201,6 +201,8 @@ export class PrefabInstance { } } +export interface TargetMap { [k: string]: TargetMap | Node | Component } + @ccclass('cc.PrefabInfo') export class PrefabInfo { // the most top node of this prefab in the scene diff --git a/cocos/scene-graph/prefab/utils.ts b/cocos/scene-graph/prefab/utils.ts index 8e59d819bab..94c31c8b6b4 100644 --- a/cocos/scene-graph/prefab/utils.ts +++ b/cocos/scene-graph/prefab/utils.ts @@ -27,15 +27,20 @@ import { EDITOR, SUPPORT_JIT } from 'internal:constants'; import { cclegacy, errorID, warn, editorExtrasTag } from '../../core'; import { Node } from '../node'; import { Component } from '../component'; -import { MountedChildrenInfo, PropertyOverrideInfo, MountedComponentsInfo, TargetInfo } from './prefab-info'; +import { + MountedChildrenInfo, + PropertyOverrideInfo, + MountedComponentsInfo, + TargetInfo, TargetMap, + PrefabInstance, + TargetOverrideInfo, +} from './prefab-info'; import { ValueType } from '../../core/value-types'; export * from './prefab-info'; export function createNodeWithPrefab (node: Node): void { - // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. - // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const prefabInfo = (node as any)._prefab; + const prefabInfo = node?.prefab; if (!prefabInfo) { return; } @@ -63,7 +68,6 @@ export function createNodeWithPrefab (node: Node): void { const _id = node.uuid; // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const _prefab = (node as any)._prefab; const editorExtras = node[editorExtrasTag]; // instantiate prefab @@ -90,16 +94,14 @@ export function createNodeWithPrefab (node: Node): void { node[editorExtrasTag] = editorExtras; } - // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. - // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - if ((node as any)._prefab) { + if (node.prefab) { // just keep the instance - (node as any)._prefab.instance = _prefab?.instance; + node.prefab.instance = prefabInfo.instance; } } // TODO: more efficient id->Node/Component map -export function generateTargetMap (node: Node, targetMap: any, isRoot: boolean): void { +export function generateTargetMap (node: Node, targetMap: TargetMap, isRoot: boolean): void { if (!targetMap) { return; } @@ -110,17 +112,13 @@ export function generateTargetMap (node: Node, targetMap: any, isRoot: boolean): let curTargetMap = targetMap; - // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. - // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const prefabInstance = (node as any)._prefab?.instance; + const prefabInstance = node.prefab?.instance; if (!isRoot && prefabInstance) { targetMap[prefabInstance.fileId] = {}; - curTargetMap = targetMap[prefabInstance.fileId]; + curTargetMap = targetMap[prefabInstance.fileId] as TargetMap; } - // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. - // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const prefabInfo = (node as any)._prefab; + const prefabInfo = node.prefab; if (prefabInfo) { curTargetMap[prefabInfo.fileId] = node; } @@ -158,7 +156,7 @@ export function getTarget (localID: string[], targetMap: any): Node | Component return target; } -export function applyMountedChildren (node: Node, mountedChildren: MountedChildrenInfo[], targetMap: Record): void { +export function applyMountedChildren (node: Node, mountedChildren: MountedChildrenInfo[], targetMap: TargetMap): void { if (!mountedChildren) { return; } @@ -175,7 +173,7 @@ export function applyMountedChildren (node: Node, mountedChildren: MountedChildr const localID = childInfo.targetInfo.localID; if (localID.length > 0) { for (let i = 0; i < localID.length - 1; i++) { - curTargetMap = curTargetMap[localID[i]]; + curTargetMap = curTargetMap[localID[i]] as TargetMap; } } if (childInfo.nodes) { @@ -205,7 +203,7 @@ export function applyMountedChildren (node: Node, mountedChildren: MountedChildr } } -export function applyMountedComponents (node: Node, mountedComponents: MountedComponentsInfo[], targetMap: Record): void { +export function applyMountedComponents (node: Node, mountedComponents: MountedComponentsInfo[], targetMap: TargetMap): void { if (!mountedComponents) { return; } @@ -240,7 +238,7 @@ export function applyMountedComponents (node: Node, mountedComponents: MountedCo } } -export function applyRemovedComponents (node: Node, removedComponents: TargetInfo[], targetMap: Record): void { +export function applyRemovedComponents (node: Node, removedComponents: TargetInfo[], targetMap: TargetMap): void { if (!removedComponents) { return; } @@ -261,7 +259,7 @@ export function applyRemovedComponents (node: Node, removedComponents: TargetInf } } -export function applyPropertyOverrides (node: Node, propertyOverrides: PropertyOverrideInfo[], targetMap: Record): void { +export function applyPropertyOverrides (node: Node, propertyOverrides: PropertyOverrideInfo[], targetMap: TargetMap): void { if (propertyOverrides.length <= 0) { return; } @@ -320,9 +318,7 @@ export function applyPropertyOverrides (node: Node, propertyOverrides: PropertyO } export function applyTargetOverrides (node: Node): void { - // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. - // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const targetOverrides = (node as any)._prefab?.targetOverrides; + const targetOverrides = node.prefab?.targetOverrides as TargetOverrideInfo[]; if (targetOverrides) { for (let i = 0; i < targetOverrides.length; i++) { const targetOverride = targetOverrides[i]; @@ -330,8 +326,8 @@ export function applyTargetOverrides (node: Node): void { let source: Node | Component | null = targetOverride.source; const sourceInfo = targetOverride.sourceInfo; if (sourceInfo) { - // TODO: targetOverride.source is type of `Node | Component`, while `_prefab` does not exist on type 'Component'. - const sourceInstance = targetOverride.source?._prefab?.instance; + const src = targetOverride.source as Node; + const sourceInstance = src?.prefab?.instance; if (sourceInstance && sourceInstance.targetMap) { source = getTarget(sourceInfo.localID, sourceInstance.targetMap); } @@ -347,8 +343,8 @@ export function applyTargetOverrides (node: Node): void { if (!targetInfo) { continue; } - - const targetInstance = targetOverride.target?._prefab?.instance; + const targetAsNode = targetOverride.target as Node; + const targetInstance = targetAsNode?.prefab?.instance; if (!targetInstance || !targetInstance.targetMap) { continue; } @@ -385,10 +381,7 @@ export function applyTargetOverrides (node: Node): void { } export function expandPrefabInstanceNode (node: Node, recursively = false): void { - // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. - // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const prefabInfo = (node as any)._prefab; - const prefabInstance = prefabInfo?.instance; + const prefabInstance = node?.prefab?.instance as PrefabInstance; if (prefabInstance && !prefabInstance.expanded) { createNodeWithPrefab(node); // nested prefab should expand before parent(property override order) @@ -400,7 +393,7 @@ export function expandPrefabInstanceNode (node: Node, recursively = false): void } } - const targetMap: Record = {}; + const targetMap = {}; prefabInstance.targetMap = targetMap; generateTargetMap(node, targetMap, true); applyMountedChildren(node, prefabInstance.mountedChildren, targetMap); @@ -418,17 +411,15 @@ export function expandPrefabInstanceNode (node: Node, recursively = false): void } export function expandNestedPrefabInstanceNode (node: Node): void { - // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. - // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const prefabInfo = (node as any)._prefab; + const prefabInfo = node.prefab; if (prefabInfo && prefabInfo.nestedPrefabInstanceRoots) { prefabInfo.nestedPrefabInstanceRoots.forEach((instanceNode: Node) => { expandPrefabInstanceNode(instanceNode); // when expanding the prefab,it's children will be change,so need to apply after expanded - if (!EDITOR) { - applyNodeAndComponentId(instanceNode, (instanceNode as any)._prefab?.instance?.fileId ?? ''); - } + // if (!EDITOR) { + // applyNodeAndComponentId(instanceNode, (instanceNode as any)._prefab?.instance?.fileId ?? ''); + // } }); } } @@ -445,7 +436,7 @@ export function applyNodeAndComponentId (prefabInstanceNode: Node, rootId: strin const child = children[i]; // TODO(PP_Pro): after we support editorOnly tag, we could remove this any type assertion. // Tracking issue: https://github.com/cocos/cocos-engine/issues/14613 - const prefabInfo = (child as any)._prefab!; + const prefabInfo = child.prefab!; const fileId = prefabInfo?.instance ? prefabInfo.instance.fileId : prefabInfo?.fileId; if (!fileId) continue; child.id = `${rootId}${fileId}`; From e00bf293260e68e76b479d77688dab8b88dfa6fb Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Thu, 10 Aug 2023 10:25:17 +0800 Subject: [PATCH 118/232] fix glass effect and planar shadow bias (#15881) --- .../post-process/components/post-process.ts | 8 +- .../post-process/post-process-builder.ts | 13 ++- .../chunks/common/lighting/functions.chunk | 16 ++-- .../render-planar-shadow/vs.chunk | 2 +- editor/assets/effects/advanced/glass.effect | 83 ++++++++++++------- 5 files changed, 76 insertions(+), 46 deletions(-) diff --git a/cocos/rendering/post-process/components/post-process.ts b/cocos/rendering/post-process/components/post-process.ts index 86de77d06f1..ac5454530ad 100644 --- a/cocos/rendering/post-process/components/post-process.ts +++ b/cocos/rendering/post-process/components/post-process.ts @@ -10,17 +10,17 @@ import { PostProcessSetting } from './post-process-setting'; @disallowMultiple @executeInEditMode export class PostProcess extends Component { - static all: PostProcess[] = [] + static all: PostProcess[] = []; @tooltip('i18n:postprocess.global') @property global = true; @property - _shadingScale = 1 + _shadingScale = 1; @tooltip('i18n:postprocess.shadingScale') @slide - @range([0.01, 1, 0.01]) + @range([0.01, 4, 0.01]) @property get shadingScale (): number { return this._shadingScale; @@ -38,7 +38,7 @@ export class PostProcess extends Component { @property enableShadingScaleInEditor = false; - settings: Map = new Map() + settings: Map = new Map(); addSetting (setting: PostProcessSetting): void { this.settings.set(setting.constructor as typeof PostProcessSetting, setting); diff --git a/cocos/rendering/post-process/post-process-builder.ts b/cocos/rendering/post-process/post-process-builder.ts index b240de3a8d7..bfe9b18377a 100644 --- a/cocos/rendering/post-process/post-process-builder.ts +++ b/cocos/rendering/post-process/post-process-builder.ts @@ -43,15 +43,20 @@ export class PostProcessBuilder implements PipelineBuilder { // rendering dependent data generation this.addPass(shadowPass); - // forward pipeline + // opaque objects forward lighting this.addPass(forward); - this.addPass(new SkinPass()); - this.addPass(new ForwardTransparencyPass()); - // pipeline related + // depth-based shading this.addPass(new HBAOPass()); + + // hdr this.addPass(new ToneMappingPass()); + // simple fog with LDR after tone-mapping, atmosphere with HDR before tone-mapping + // this.addPass(new FogPass()); + + // transparency should after hdr and depth-based shading + this.addPass(new ForwardTransparencyPass()); // user post-processing this.addPass(new TAAPass()); diff --git a/editor/assets/chunks/common/lighting/functions.chunk b/editor/assets/chunks/common/lighting/functions.chunk index 4d7375b06bc..cc744e5f7ab 100644 --- a/editor/assets/chunks/common/lighting/functions.chunk +++ b/editor/assets/chunks/common/lighting/functions.chunk @@ -86,14 +86,18 @@ vec4 CalculatePlanarShadowPos(vec3 meshWorldPos, vec3 cameraPos, vec3 lightDir, vec3 P = meshWorldPos; vec3 L = lightDir; vec3 N = plane.xyz; - float d = plane.w + 0.001; + float d = plane.w + EPSILON_LOWP; float dist = (-d - dot(P, N)) / (dot(L, N) + EPSILON_LOWP); vec3 shadowPos = P + L * dist; - // avoid z-fighting with shadow plane - vec3 view = normalize(cameraPos.xyz - shadowPos); - float viewLength = length(cameraPos.xyz - shadowPos); - shadowPos += view * min(1.0, 0.005 * viewLength); - return vec4(shadowPos, dist); } +// calculate planar clip pos from world pos +vec4 CalculatePlanarShadowClipPos(vec4 shadowPos, vec3 cameraPos, mat4 matView, mat4 matProj, vec4 nearFar) { + vec4 camPos = matView * vec4(shadowPos.xyz, 1.0); + // avoid z-fighting with shadow receive plane, add camera bias with perspective correction + // notice that near plane should not be too small, assume near 1, far 1000 + float lerpCoef = saturate((nearFar.z < 0.0 ? -camPos.z : camPos.z) / (nearFar.y - nearFar.x)); + camPos.z += mix(nearFar.x * 0.01, nearFar.y * EPSILON_LOWP, lerpCoef); + return matProj * camPos; +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk index f2b34e3506a..75f3708624b 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk @@ -22,7 +22,7 @@ void main() In.worldPos = shadowPos.xyz; // Clip Space - In.clipPos = cc_matProj * cc_matView * vec4(In.worldPos, 1.0); + In.clipPos = CalculatePlanarShadowClipPos(shadowPos, cc_cameraPos.xyz, cc_matView, cc_matProj, cc_nearFar); In.clipPos = SurfacesVertexModifyClipPos(In); // Other Surfaces Function diff --git a/editor/assets/effects/advanced/glass.effect b/editor/assets/effects/advanced/glass.effect index e16bf1878c1..b1d7fce571a 100644 --- a/editor/assets/effects/advanced/glass.effect +++ b/editor/assets/effects/advanced/glass.effect @@ -2,18 +2,28 @@ CCEffect %{ techniques: - - name: opaque + - name: single-sided passes: - vert: standard-vs frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + rasterizerState: + cullMode: Back + depthStencilState: &d1 + depthTest: true + depthWrite: false + blendState: &b1 + targets: + - blend: true + blendSrc: one + blendDst: src_alpha properties: &props tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } mainColor: { value: [0.05, 0.05, 0.05, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } roughness: { value: 0.0, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - metallic: { value: 0.0, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - specularIntensity: { value: 0.2, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } - F0: { value: 0.7, target: emissiveScaleParam.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + F0: { value: 0.5, target: emissiveScaleParam.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } F90: { value: 0.9, target: emissiveScaleParam.y, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } gradientColor: { value: [0.0, 0.05, 0.0, 1.0], linear: true, editor: { parent: USE_GRADIENT_COLOR, type: color } } gradientIntensity: { value: 0.2, target: emissiveScaleParam.z, editor: { parent: USE_GRADIENT_COLOR, slide: true, range: [0, 1.0], step: 0.001 } } @@ -82,31 +92,37 @@ CCEffect %{ phase: gbuffer embeddedMacros: { CC_PIPELINE_TYPE: 1 } propertyIndex: 0 - - name: transparent + - name: two-sided passes: - vert: standard-vs frag: standard-fs - embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true, TECHNIQUE_TWO_SIDE: true } rasterizerState: cullMode: Front - depthStencilState: &d1 - depthTest: true - depthWrite: false - blendState: &b1 - targets: - - blend: true - blendSrc: src_alpha - blendDst: one_minus_src_alpha - blendDstAlpha: one_minus_src_alpha - properties: *props + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [0.05, 0.05, 0.05, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + roughness: { value: 0.0, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + F0: { value: 0.5, target: emissiveScaleParam.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + F90: { value: 0.9, target: emissiveScaleParam.y, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + gradientColor: { value: [0.0, 0.05, 0.0, 1.0], linear: true, editor: { parent: USE_GRADIENT_COLOR, type: color } } + gradientIntensity: { value: 0.2, target: emissiveScaleParam.z, editor: { parent: USE_GRADIENT_COLOR, slide: true, range: [0, 1.0], step: 0.001 } } + normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + normalMap: { value: normal } + pbrMap: { value: grey } + depthStencilState: *d1 + blendState: *b1 - vert: standard-vs frag: standard-fs - embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true, TECHNIQUE_TWO_SIDE: true } rasterizerState: cullMode: Back + propertyIndex: 0 depthStencilState: *d1 blendState: *b1 - properties: *props - *forward-add - *shadow-caster - *planar-shadow @@ -133,11 +149,9 @@ CCProgram shared-ubos %{ CCProgram macro-remapping %{ // ui displayed macros - #pragma define-meta USE_TWOSIDE #pragma define-meta USE_VERTEX_COLOR #pragma define-meta USE_PROBE_REFRACTION editor({ tooltip: 'Use transparency technique when disabled, otherwise use opaque technique' }) - #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR #define CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR USE_PROBE_REFRACTION #define CC_SURFACES_LIGHTING_USE_FRESNEL USE_PROBE_REFRACTION @@ -145,6 +159,10 @@ CCProgram macro-remapping %{ // depend on UI macros #if USE_NORMAL_MAP #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif + // depend on technique macros +#if TECHNIQUE_TWO_SIDE + #define CC_SURFACES_USE_TWO_SIDED 1 #endif }% @@ -210,9 +228,10 @@ CCProgram surface-fragment %{ { vec4 pbr = pbrParams; pbr.x = 1.0; + pbr.z = 1.0; #if USE_PBR_MAP vec4 res = texture(pbrMap, DEFAULT_UV); - pbr.yzw *= res.yzw; + pbr.yw *= res.yw; #endif return pbr; @@ -227,9 +246,12 @@ CCProgram surface-fragment %{ float NoVSat = saturate(dot(surfaceData.worldNormal, viewDir)); #if !USE_PROBE_REFRACTION - // fresnel for alpha blend + // final color = srcColor * F + dstColor * (1-F) * glassColor + // srcAlpha = (1-F) * glassColorBright (use bright instead for one channel) + // srcBlend = 1, dstBlend = srcAlpha float F0 = emissiveScaleParam.x, F90 = emissiveScaleParam.y; - surfaceData.baseColor.a = CalculateFresnelCoefficient(min(F0, F90), F90, NoVSat); + float fresnel = CalculateFresnelCoefficient(min(F0, F90), F90, NoVSat); + surfaceData.baseColor.a = (1.0 - fresnel) * length(surfaceData.baseColor.rgb); #endif #if USE_GRADIENT_COLOR @@ -241,14 +263,13 @@ CCProgram surface-fragment %{ #define CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, in LightingMiscData miscData) { - #if USE_PROBE_REFRACTION - // fresnel for refraction - vec3 viewDir = normalize(cc_cameraPos.xyz - surfaceData.worldPos); - float NoVSat = saturate(dot(surfaceData.worldNormal, viewDir)); - float F0 = emissiveScaleParam.x, F90 = emissiveScaleParam.y; - float fresnel = CalculateFresnelCoefficient(min(F0, F90), F90, NoVSat); - result.fresnel = vec3(fresnel); - #else + vec3 viewDir = normalize(cc_cameraPos.xyz - surfaceData.worldPos); + float NoVSat = saturate(dot(surfaceData.worldNormal, viewDir)); + float F0 = emissiveScaleParam.x, F90 = emissiveScaleParam.y; + float fresnel = CalculateFresnelCoefficient(min(F0, F90), F90, NoVSat); + result.fresnel = vec3(fresnel); + + #if !USE_PROBE_REFRACTION // simply fix single blend source issue for bright color alpha blending float threshold = 0.5, bright = dot(result.environmentSpecular, vec3(0.33333)); if (bright > threshold) From e69ae568a090614a05f1871477f7b58a04e3c692 Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Thu, 10 Aug 2023 10:29:08 +0800 Subject: [PATCH 119/232] remove ia pool. (#15880) * remove ia pool. * fix vb / ib leaks in ui mesh && renderDrawInfo --- native/cocos/2d/renderer/Batcher2d.cpp | 17 ++++-- native/cocos/2d/renderer/RenderDrawInfo.cpp | 61 ++++++------------- native/cocos/2d/renderer/RenderDrawInfo.h | 10 +-- native/cocos/2d/renderer/UIMeshBuffer.cpp | 48 +++++---------- native/cocos/2d/renderer/UIMeshBuffer.h | 9 ++- .../renderer/pipeline/InstancedBuffer.cpp | 17 +++--- .../cocos/renderer/pipeline/InstancedBuffer.h | 2 +- .../pipeline/RenderInstancedQueue.cpp | 2 +- native/cocos/renderer/pipeline/UIPhase.cpp | 2 +- .../pipeline/custom/NativeExecutor.cpp | 2 +- .../pipeline/custom/NativeRenderQueue.cpp | 4 +- native/cocos/scene/DrawBatch2D.cpp | 5 ++ native/cocos/scene/DrawBatch2D.h | 6 +- 13 files changed, 81 insertions(+), 104 deletions(-) diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index c1ffb4d9e9f..8e05a432868 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -332,9 +332,14 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { return; } gfx::InputAssembler* ia = nullptr; + + uint32_t indexOffset = 0; + uint32_t indexCount = 0; if (drawInfo->getIsMeshBuffer()) { // Todo MeshBuffer RenderData ia = drawInfo->requestIA(getDevice()); + indexOffset = drawInfo->getIndexOffset(); + indexCount = drawInfo->getIbCount(); _meshRenderDrawInfo.emplace_back(drawInfo); } else { UIMeshBuffer* currMeshBuffer = drawInfo->getMeshBuffer(); @@ -342,13 +347,11 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { currMeshBuffer->setDirty(true); ia = currMeshBuffer->requireFreeIA(getDevice()); - uint32_t indexCount = currMeshBuffer->getIndexOffset() - _indexStart; + indexCount = currMeshBuffer->getIndexOffset() - _indexStart; if (ia == nullptr) { return; } - - ia->setFirstIndex(_indexStart); - ia->setIndexCount(indexCount); + indexOffset = _indexStart; _indexStart = currMeshBuffer->getIndexOffset(); } @@ -364,6 +367,8 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { auto* curdrawBatch = _drawBatchPool.alloc(); curdrawBatch->setVisFlags(_currLayer); curdrawBatch->setInputAssembler(ia); + curdrawBatch->setFirstIndex(indexOffset); + curdrawBatch->setIndexCount(indexCount); curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash); const auto& pass = curdrawBatch->getPasses().at(0); @@ -392,8 +397,6 @@ void Batcher2d::generateBatchForMiddleware(RenderEntity* entity, RenderDrawInfo* meshBuffer->setDirty(true); gfx::InputAssembler* ia = meshBuffer->requireFreeIA(getDevice()); - ia->setFirstIndex(drawInfo->getIndexOffset()); - ia->setIndexCount(drawInfo->getIbCount()); // stencilstage auto stencilStage = _stencilManager->getStencilStage(); @@ -403,6 +406,8 @@ void Batcher2d::generateBatchForMiddleware(RenderEntity* entity, RenderDrawInfo* auto* curdrawBatch = _drawBatchPool.alloc(); curdrawBatch->setVisFlags(_currLayer); curdrawBatch->setInputAssembler(ia); + curdrawBatch->setFirstIndex(drawInfo->getIndexOffset()); + curdrawBatch->setIndexCount(drawInfo->getIbCount()); curdrawBatch->fillPass(material, depthStencil, dssHash); const auto& pass = curdrawBatch->getPasses().at(0); if (entity->getUseLocal()) { diff --git a/native/cocos/2d/renderer/RenderDrawInfo.cpp b/native/cocos/2d/renderer/RenderDrawInfo.cpp index f376de0f979..94397e3c382 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.cpp +++ b/native/cocos/2d/renderer/RenderDrawInfo.cpp @@ -51,56 +51,30 @@ void RenderDrawInfo::changeMeshBuffer() { gfx::InputAssembler* RenderDrawInfo::requestIA(gfx::Device* device) { CC_ASSERT(_drawInfoAttrs._isMeshBuffer && _drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP); - if (!_iaPool) { - _iaPool = ccnew ccstd::vector; - } - if (_nextFreeIAHandle >= _iaPool->size()) { - initIAInfo(device); - } - auto* ia = (*_iaPool)[_nextFreeIAHandle++]; - ia->setFirstIndex(getIndexOffset()); - ia->setIndexCount(getIbCount()); - return ia; + return initIAInfo(device); } void RenderDrawInfo::uploadBuffers() { CC_ASSERT(_drawInfoAttrs._isMeshBuffer && _drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP); if (_drawInfoAttrs._vbCount == 0 || _drawInfoAttrs._ibCount == 0) return; uint32_t size = _drawInfoAttrs._vbCount * 9 * sizeof(float); // magic Number - gfx::Buffer* vBuffer = _iaInfo->vertexBuffers[0]; + gfx::Buffer* vBuffer = _ia->getVertexBuffers()[0]; vBuffer->resize(size); vBuffer->update(_vDataBuffer); - gfx::Buffer* iBuffer = _iaInfo->indexBuffer; + gfx::Buffer* iBuffer = _ia->getIndexBuffer(); uint32_t iSize = _drawInfoAttrs._ibCount * 2; iBuffer->resize(iSize); iBuffer->update(_iDataBuffer); } -void RenderDrawInfo::resetMeshIA() { +void RenderDrawInfo::resetMeshIA() { // NOLINT(readability-make-member-function-const) CC_ASSERT(_drawInfoAttrs._isMeshBuffer && _drawInfoAttrs._drawInfoType == RenderDrawInfoType::COMP); - _nextFreeIAHandle = 0; } void RenderDrawInfo::destroy() { - _nextFreeIAHandle = 0; - if (_iaInfo) { - CC_SAFE_DELETE(_iaInfo->indexBuffer); - if (!_iaInfo->vertexBuffers.empty()) { - // only one vb - CC_SAFE_DELETE(_iaInfo->vertexBuffers[0]); - _iaInfo->vertexBuffers.clear(); - } - CC_SAFE_DELETE(_iaInfo); - } - - if (_iaPool) { - for (auto* ia : *_iaPool) { - CC_SAFE_DELETE(ia); - } - _iaPool->clear(); - CC_SAFE_DELETE(_iaPool); - } - + _vb = nullptr; + _ib = nullptr; + _ia = nullptr; if (_localDSBF) { CC_SAFE_DELETE(_localDSBF->ds); CC_SAFE_DELETE(_localDSBF->uboBuf); @@ -109,31 +83,30 @@ void RenderDrawInfo::destroy() { } gfx::InputAssembler* RenderDrawInfo::initIAInfo(gfx::Device* device) { - if (_iaPool->empty()) { - _iaInfo = ccnew gfx::InputAssemblerInfo(); + if (!_ia) { + gfx::InputAssemblerInfo iaInfo = {}; uint32_t vbStride = 9 * sizeof(float); // magic Number uint32_t ibStride = sizeof(uint16_t); - auto* vertexBuffer = device->createBuffer({ + _vb = device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, vbStride * 3, vbStride, }); - auto* indexBuffer = device->createBuffer({ + _ib = device->createBuffer({ gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, ibStride * 3, ibStride, }); - _iaInfo->attributes = *(Root::getInstance()->getBatcher2D()->getDefaultAttribute()); - _iaInfo->vertexBuffers.emplace_back(vertexBuffer); - _iaInfo->indexBuffer = indexBuffer; - } - auto* ia = device->createInputAssembler(*_iaInfo); - _iaPool->emplace_back(ia); + iaInfo.attributes = *(Root::getInstance()->getBatcher2D()->getDefaultAttribute()); + iaInfo.vertexBuffers.emplace_back(_vb); + iaInfo.indexBuffer = _ib; - return ia; + _ia = device->createInputAssembler(iaInfo); + } + return _ia; } void RenderDrawInfo::updateLocalDescriptorSet(Node* transform, const gfx::DescriptorSetLayout* dsLayout) { diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index ee4ab7b2b47..a06266be5c5 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -24,6 +24,7 @@ #pragma once #include "2d/renderer/UIMeshBuffer.h" +#include "base/Ptr.h" #include "base/Macros.h" #include "base/TypeDef.h" #include "bindings/utils/BindingUtils.h" @@ -266,8 +267,6 @@ class RenderDrawInfo final { ccstd::hash_t _dataHash{0}; } _drawInfoAttrs{}; - uint16_t _nextFreeIAHandle{0}; - bindings::NativeMemorySharedToScriptActor _attrSharedBufferActor; // weak reference Material* _material{nullptr}; @@ -291,8 +290,11 @@ class RenderDrawInfo final { scene::Model* _model; uint8_t* _sharedBuffer; }; - gfx::InputAssemblerInfo* _iaInfo{nullptr}; - ccstd::vector* _iaPool{nullptr}; LocalDSBF* _localDSBF{nullptr}; + + // ia + IntrusivePtr _ia; + IntrusivePtr _vb; + IntrusivePtr _ib; }; } // namespace cc diff --git a/native/cocos/2d/renderer/UIMeshBuffer.cpp b/native/cocos/2d/renderer/UIMeshBuffer.cpp index 6f539c46e2d..bf8f307f2cd 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.cpp +++ b/native/cocos/2d/renderer/UIMeshBuffer.cpp @@ -59,25 +59,17 @@ void UIMeshBuffer::initialize(ccstd::vector&& attrs, bool needCr void UIMeshBuffer::reset() { setIndexOffset(0); - _nextFreeIAHandle = 0; _dirty = false; } void UIMeshBuffer::resetIA() { - for (auto* ia : _iaPool) { - ia->setFirstIndex(0); - ia->setIndexCount(0); - } } void UIMeshBuffer::destroy() { reset(); _attributes.clear(); - for (auto* vb : _iaInfo.vertexBuffers) { - delete vb; - } - _iaInfo.vertexBuffers.clear(); - CC_SAFE_DELETE(_iaInfo.indexBuffer); + _vb = nullptr; + _ib = nullptr; if (_needDeleteVData) { delete _vData; delete _iData; @@ -85,11 +77,7 @@ void UIMeshBuffer::destroy() { _vData = nullptr; _iData = nullptr; // Destroy InputAssemblers - for (auto* ia : _iaPool) { - ia->destroy(); - delete ia; - } - _iaPool.clear(); + _ia = nullptr; if (_needDeleteLayout) { CC_SAFE_DELETE(_meshBufferLayout); } @@ -100,24 +88,20 @@ void UIMeshBuffer::setDirty() { } gfx::InputAssembler* UIMeshBuffer::requireFreeIA(gfx::Device* device) { - if (_nextFreeIAHandle >= _iaPool.size()) { - createNewIA(device); - } - return _iaPool[_nextFreeIAHandle++]; + return createNewIA(device); } void UIMeshBuffer::uploadBuffers() { uint32_t byteOffset = getByteOffset(); bool dirty = getDirty(); - if (_meshBufferLayout == nullptr || byteOffset == 0 || !dirty || _iaPool.empty()) { + if (_meshBufferLayout == nullptr || byteOffset == 0 || !dirty || !_ia) { return; } uint32_t indexCount = getIndexOffset(); uint32_t byteCount = getByteOffset(); - gfx::InputAssembler* ia = _iaPool[0]; - gfx::BufferList vBuffers = ia->getVertexBuffers(); + gfx::BufferList vBuffers = _ia->getVertexBuffers(); if (!vBuffers.empty()) { gfx::Buffer* vBuffer = vBuffers[0]; if (byteCount > vBuffer->getSize()) { @@ -125,7 +109,7 @@ void UIMeshBuffer::uploadBuffers() { } vBuffer->update(_vData); } - gfx::Buffer* iBuffer = ia->getIndexBuffer(); + gfx::Buffer* iBuffer = _ia->getIndexBuffer(); if (indexCount * 2 > iBuffer->getSize()) { iBuffer->resize(indexCount * 2); } @@ -139,31 +123,31 @@ void UIMeshBuffer::recycleIA(gfx::InputAssembler* ia) { } gfx::InputAssembler* UIMeshBuffer::createNewIA(gfx::Device* device) { - if (_iaPool.empty()) { + if (!_ia) { uint32_t vbStride = _vertexFormatBytes; uint32_t ibStride = sizeof(uint16_t); - auto* vertexBuffer = device->createBuffer({ + gfx::InputAssemblerInfo iaInfo = {}; + _vb = device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, vbStride * 3, vbStride, }); - auto* indexBuffer = device->createBuffer({ + _ib = device->createBuffer({ gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE | gfx::MemoryUsageBit::HOST, ibStride * 3, ibStride, }); - _iaInfo.attributes = _attributes; - _iaInfo.vertexBuffers.emplace_back(vertexBuffer); - _iaInfo.indexBuffer = indexBuffer; + iaInfo.attributes = _attributes; + iaInfo.vertexBuffers.emplace_back(_vb); + iaInfo.indexBuffer = _ib; + _ia = device->createInputAssembler(iaInfo); } - auto* ia = device->createInputAssembler(_iaInfo); - _iaPool.emplace_back(ia); - return ia; + return _ia; } void UIMeshBuffer::syncSharedBufferToNative(uint32_t* buffer) { diff --git a/native/cocos/2d/renderer/UIMeshBuffer.h b/native/cocos/2d/renderer/UIMeshBuffer.h index 1ae94eed180..8e2bbef8e54 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.h +++ b/native/cocos/2d/renderer/UIMeshBuffer.h @@ -23,9 +23,12 @@ ****************************************************************************/ #pragma once +#include "base/Ptr.h" #include "base/Macros.h" #include "base/TypeDef.h" +#include "renderer/gfx-base/GFXInputAssembler.h" #include "renderer/gfx-base/GFXDef-common.h" +#include "renderer/gfx-base/GFXBuffer.h" namespace cc { @@ -84,11 +87,11 @@ class UIMeshBuffer final { uint32_t _vertexFormatBytes{0}; uint32_t _initVDataCount{0}; uint32_t _initIDataCount{0}; - uint32_t _nextFreeIAHandle{0}; ccstd::vector _attributes; - ccstd::vector _iaPool{}; - gfx::InputAssemblerInfo _iaInfo; + IntrusivePtr _ia; + IntrusivePtr _vb; + IntrusivePtr _ib; bool _dirty{false}; bool _needDeleteVData{false}; diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index 56d2311aa52..bd5f02f1d4b 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -74,7 +74,7 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh } for (auto &instance : _instances) { - if (instance.ia->getIndexBuffer() != sourceIA->getIndexBuffer() || instance.count >= MAX_CAPACITY) { + if (instance.ia->getIndexBuffer() != sourceIA->getIndexBuffer() || instance.drawInfo.instanceCount >= MAX_CAPACITY) { continue; } @@ -99,7 +99,7 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh if (instance.stride != stride) { continue; } - if (instance.count >= instance.capacity) { // resize buffers + if (instance.drawInfo.instanceCount >= instance.capacity) { // resize buffers instance.capacity <<= 1; const auto newSize = instance.stride * instance.capacity; instance.data = static_cast(CC_REALLOC(instance.data, newSize)); @@ -111,7 +111,7 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh if (instance.descriptorSet != descriptorSet) { instance.descriptorSet = descriptorSet; } - memcpy(instance.data + instance.stride * instance.count++, attrs.buffer.buffer()->getData(), stride); + memcpy(instance.data + instance.stride * instance.drawInfo.instanceCount++, attrs.buffer.buffer()->getData(), stride); _hasPendingModels = true; return; } @@ -144,24 +144,25 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh vertexBuffers.emplace_back(vb); const gfx::InputAssemblerInfo iaInfo = {attributes, vertexBuffers, indexBuffer}; auto *ia = _device->createInputAssembler(iaInfo); - InstancedItem item = {1, INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, - lightingMap, reflectionProbeCubemap, reflectionProbePlanarMap, reflectionProbeType, reflectionProbeBlendCubemap}; + InstancedItem item = {INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, + lightingMap, reflectionProbeCubemap, reflectionProbePlanarMap, reflectionProbeType, reflectionProbeBlendCubemap, + ia->getDrawInfo()}; + item.drawInfo.instanceCount = 1; _instances.emplace_back(item); _hasPendingModels = true; } void InstancedBuffer::uploadBuffers(gfx::CommandBuffer *cmdBuff) const { for (const auto &instance : _instances) { - if (!instance.count) continue; + if (!instance.drawInfo.instanceCount) continue; cmdBuff->updateBuffer(instance.vb, instance.data, instance.vb->getSize()); - instance.ia->setInstanceCount(instance.count); } } void InstancedBuffer::clear() { for (auto &instance : _instances) { - instance.count = 0; + instance.drawInfo.instanceCount = 0; } _hasPendingModels = false; } diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.h b/native/cocos/renderer/pipeline/InstancedBuffer.h index 0d979365268..e77d9b61d59 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.h +++ b/native/cocos/renderer/pipeline/InstancedBuffer.h @@ -38,7 +38,6 @@ namespace pipeline { struct PSOInfo; struct CC_DLL InstancedItem { - uint32_t count = 0; uint32_t capacity = 0; gfx::Buffer *vb = nullptr; uint8_t *data = nullptr; @@ -51,6 +50,7 @@ struct CC_DLL InstancedItem { gfx::Texture *reflectionProbePlanarMap = nullptr; uint32_t reflectionProbeType = 0; gfx::Texture *reflectionProbeBlendCubemap = nullptr; + gfx::DrawInfo drawInfo; }; using InstancedItemList = ccstd::vector; using DynamicOffsetList = ccstd::vector; diff --git a/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp b/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp index ccc84e0b469..4a0a50654cc 100644 --- a/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp @@ -68,7 +68,7 @@ void RenderInstancedQueue::recordCommandBuffer(gfx::Device * /*device*/, gfx::Re cmdBuffer->bindDescriptorSet(materialSet, pass->getDescriptorSet()); gfx::PipelineState *lastPSO = nullptr; for (const auto &instance : instances) { - if (!instance.count) { + if (!instance.drawInfo.instanceCount) { continue; } auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, instance.shader, instance.ia, renderPass); diff --git a/native/cocos/renderer/pipeline/UIPhase.cpp b/native/cocos/renderer/pipeline/UIPhase.cpp index 6cdf32ee00f..337846ba9d2 100644 --- a/native/cocos/renderer/pipeline/UIPhase.cpp +++ b/native/cocos/renderer/pipeline/UIPhase.cpp @@ -58,7 +58,7 @@ void UIPhase::render(scene::Camera *camera, gfx::RenderPass *renderPass) { cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); cmdBuff->bindInputAssembler(inputAssembler); cmdBuff->bindDescriptorSet(localSet, ds); - cmdBuff->draw(inputAssembler); + cmdBuff->draw(batch->getDrawInfo()); } } } diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index c52a13d114c..aefd8293e5c 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -742,7 +742,7 @@ void submitUICommands( cmdBuff->bindInputAssembler(inputAssembler); cmdBuff->bindDescriptorSet( static_cast(pipeline::SetIndex::LOCAL), ds); - cmdBuff->draw(inputAssembler); + cmdBuff->draw(batch->getDrawInfo()); } } } diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp index 4c42773416f..3f95918ac34 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp @@ -114,7 +114,7 @@ void RenderInstancingQueue::add( instanceBuffer->setPass(&pass); const auto &instances = instanceBuffer->getInstances(); for (const auto &item : instances) { - CC_EXPECTS(item.count == 0); + CC_EXPECTS(item.drawInfo.instanceCount == 0); } } auto &instancedBuffer = *instanceBuffers[iter->second]; @@ -150,7 +150,7 @@ void RenderInstancingQueue::recordCommandBuffer( cmdBuffer->bindDescriptorSet(pipeline::materialSet, drawPass->getDescriptorSet()); gfx::PipelineState *lastPSO = nullptr; for (const auto &instance : instances) { - if (!instance.count) { + if (!instance.drawInfo.instanceCount) { continue; } auto *pso = pipeline::PipelineStateManager::getOrCreatePipelineState( diff --git a/native/cocos/scene/DrawBatch2D.cpp b/native/cocos/scene/DrawBatch2D.cpp index 7266484adc4..9cf626faeca 100644 --- a/native/cocos/scene/DrawBatch2D.cpp +++ b/native/cocos/scene/DrawBatch2D.cpp @@ -58,5 +58,10 @@ void DrawBatch2D::fillPass(Material *mat, const gfx::DepthStencilState *depthSte } } +void DrawBatch2D::setInputAssembler(gfx::InputAssembler *ia) { + _inputAssembler = ia; + _drawInfo = _inputAssembler->getDrawInfo(); +} + } // namespace scene } // namespace cc diff --git a/native/cocos/scene/DrawBatch2D.h b/native/cocos/scene/DrawBatch2D.h index cda702f3098..94bd4a8a809 100644 --- a/native/cocos/scene/DrawBatch2D.h +++ b/native/cocos/scene/DrawBatch2D.h @@ -47,12 +47,15 @@ class DrawBatch2D final : public RefCounted { void clear(); void fillPass(Material *mat, const gfx::DepthStencilState *depthStencilState, ccstd::hash_t dsHash, const ccstd::vector *patches = nullptr); + void setInputAssembler(gfx::InputAssembler *ia); + inline void setFirstIndex(uint32_t index) { _drawInfo.firstIndex = index; } + inline void setIndexCount(uint32_t count) { _drawInfo.indexCount = count; } - inline void setInputAssembler(gfx::InputAssembler *ia) { _inputAssembler = ia; } inline void setDescriptorSet(gfx::DescriptorSet *descriptorSet) { _descriptorSet = descriptorSet; } inline void setVisFlags(uint32_t flags) { _visFlags = flags; } inline void setModel(Model *model) { _model = model; } + inline const gfx::DrawInfo &getDrawInfo() const { return _drawInfo; } inline gfx::InputAssembler *getInputAssembler() const { return _inputAssembler; } inline gfx::DescriptorSet *getDescriptorSet() const { return _descriptorSet; } inline uint32_t getVisFlags() const { return _visFlags; } @@ -68,6 +71,7 @@ class DrawBatch2D final : public RefCounted { ccstd::vector _shaders; Model *_model{nullptr}; + gfx::DrawInfo _drawInfo; CC_DISALLOW_COPY_MOVE_ASSIGN(DrawBatch2D); }; From 2e61800f9f7721aa212ce4b417b959c76ad37abe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Thu, 10 Aug 2023 11:37:06 +0800 Subject: [PATCH 120/232] revert custom pipeline pass order (#15915) --- cocos/rendering/post-process/post-process-builder.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/cocos/rendering/post-process/post-process-builder.ts b/cocos/rendering/post-process/post-process-builder.ts index bfe9b18377a..550d8fa15dd 100644 --- a/cocos/rendering/post-process/post-process-builder.ts +++ b/cocos/rendering/post-process/post-process-builder.ts @@ -50,14 +50,13 @@ export class PostProcessBuilder implements PipelineBuilder { // depth-based shading this.addPass(new HBAOPass()); - // hdr - this.addPass(new ToneMappingPass()); - // simple fog with LDR after tone-mapping, atmosphere with HDR before tone-mapping - // this.addPass(new FogPass()); - // transparency should after hdr and depth-based shading + // temporary ignore CC_USE_FLOAT_OUTPUT this.addPass(new ForwardTransparencyPass()); + // float output related processing: hdr + fog + this.addPass(new ToneMappingPass()); + // user post-processing this.addPass(new TAAPass()); this.addPass(new FxaaPass()); From ad6e3dcf8acf3bb5292c11c5ab87e23a6ed158a0 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 10 Aug 2023 16:43:16 +0800 Subject: [PATCH 121/232] V3.8.1 pipeline (#15906) --- cocos/rendering/custom/pipeline.ts | 13 +- cocos/rendering/custom/types.ts | 6 +- cocos/rendering/custom/web-pipeline.ts | 41 +- .../renderer/frame-graph/ImmutableState.cpp | 8 +- .../cocos/renderer/gfx-base/GFXDef-common.h | 18 +- .../gfx-vulkan/states/VKTextureBarrier.cpp | 8 +- .../pipeline/custom/FGDispatcherTypes.cpp | 3 +- .../pipeline/custom/FGDispatcherTypes.h | 38 +- .../pipeline/custom/FrameGraphDispatcher.cpp | 448 ++++++++++++------ .../pipeline/custom/NativePipelineTypes.h | 127 ++++- .../pipeline/custom/NativeRenderGraph.cpp | 3 +- .../pipeline/custom/NativeRenderGraphUtils.h | 12 +- .../pipeline/custom/NativeResourceGraph.cpp | 10 +- .../renderer/pipeline/custom/NativeSetter.cpp | 15 + .../pipeline/custom/RenderCommonJsb.cpp | 7 + .../custom/RenderCommonSerialization.h | 2 + .../pipeline/custom/RenderCommonTypes.h | 5 + .../pipeline/custom/RenderInterfaceTypes.h | 13 +- 18 files changed, 565 insertions(+), 212 deletions(-) diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index c679c5796dd..68e6d54d984 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -37,9 +37,12 @@ import { GlobalDSManager } from '../global-descriptor-set-manager'; import { Mat4, Quat, Vec2, Vec4 } from '../../core/math'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { PipelineSceneData } from '../pipeline-scene-data'; +import { PointLight } from '../../render-scene/scene/point-light'; +import { RangedDirectionalLight } from '../../render-scene/scene/ranged-directional-light'; import { AccessType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency, UploadPair } from './types'; import { RenderWindow } from '../../render-scene/core/render-window'; import { Light, Model } from '../../render-scene/scene'; +import { SphereLight } from '../../render-scene/scene/sphere-light'; import { SpotLight } from '../../render-scene/scene/spot-light'; /** @@ -377,6 +380,11 @@ export interface Setter extends RenderNode { setSampler (name: string, sampler: Sampler): void; setBuiltinCameraConstants (camera: Camera): void; setBuiltinShadowMapConstants (light: DirectionalLight): void; + setBuiltinDirectionalLightConstants (light: DirectionalLight, camera: Camera): void; + setBuiltinSphereLightConstants (light: SphereLight, camera: Camera): void; + setBuiltinSpotLightConstants (light: SpotLight, camera: Camera): void; + setBuiltinPointLightConstants (light: PointLight, camera: Camera): void; + setBuiltinRangedDirectionalLightConstants (light: RangedDirectionalLight, camera: Camera): void; setBuiltinDirectionalLightViewConstants (light: DirectionalLight, level?: number): void; setBuiltinSpotLightViewConstants (light: SpotLight): void; } @@ -402,7 +410,10 @@ export interface RenderQueueBuilder extends Setter { camera: Camera, light: LightInfo, sceneFlags?: SceneFlags): void; - addScene (camera: Camera, sceneFlags: SceneFlags): void; + addScene ( + camera: Camera, + sceneFlags: SceneFlags, + light?: Light | null): void; addSceneCulledByDirectionalLight ( camera: Camera, sceneFlags: SceneFlags, diff --git a/cocos/rendering/custom/types.ts b/cocos/rendering/custom/types.ts index d09e3b8a9fe..bde9ca132f7 100644 --- a/cocos/rendering/custom/types.ts +++ b/cocos/rendering/custom/types.ts @@ -288,12 +288,14 @@ export function getClearValueTypeName (e: ClearValueType): string { } export class LightInfo { - constructor (light: Light | null = null, level = 0) { + constructor (light: Light | null = null, level = 0, culledByLight = false) { this.light = light; this.level = level; + this.culledByLight = culledByLight; } /*refcount*/ light: Light | null; level: number; + culledByLight: boolean; } export enum DescriptorTypeOrder { @@ -505,11 +507,13 @@ export class PipelineStatistics { export function saveLightInfo (ar: OutputArchive, v: LightInfo): void { // skip, v.light: Light ar.writeNumber(v.level); + ar.writeBool(v.culledByLight); } export function loadLightInfo (ar: InputArchive, v: LightInfo): void { // skip, v.light: Light v.level = ar.readNumber(); + v.culledByLight = ar.readBool(); } export function saveDescriptor (ar: OutputArchive, v: Descriptor): void { diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 08e171ab45c..fa46e3dab45 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -31,7 +31,7 @@ import { AccessType, AttachmentType, CopyPair, LightInfo, LightingMode, MovePair import { ComputeView, RasterView, Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedBuffer, ManagedResource, MovePass, RasterPass, RasterSubpass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData, Subpass } from './render-graph'; import { ComputePassBuilder, ComputeQueueBuilder, ComputeSubpassBuilder, BasicPipeline, PipelineBuilder, RenderPassBuilder, RenderQueueBuilder, RenderSubpassBuilder, PipelineType, BasicRenderPassBuilder, PipelineCapabilities, BasicMultisampleRenderPassBuilder } from './pipeline'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { Model, Camera, ShadowType, CSMLevel, DirectionalLight, SpotLight, PCFType, Shadows } from '../../render-scene/scene'; +import { Model, Camera, ShadowType, CSMLevel, DirectionalLight, SpotLight, PCFType, Shadows, SphereLight, PointLight, RangedDirectionalLight } from '../../render-scene/scene'; import { Light, LightType } from '../../render-scene/scene/light'; import { DescriptorSetData, DescriptorSetLayoutData, LayoutGraphData } from './layout-graph'; import { Executor } from './executor'; @@ -237,7 +237,9 @@ export class WebSetter { public offsetFloat (v: number, offset: number): void { this._copyToBuffer(v, offset, Type.FLOAT); } - public setBuffer (name: string, buffer: Buffer): void {} + public setBuffer (name: string, buffer: Buffer): void { + // TODO + } public setTexture (name: string, texture: Texture): void { if (this._getCurrDescriptorBlock(name) === -1) { return; @@ -245,8 +247,12 @@ export class WebSetter { const num = this._lg.attributeIndex.get(name)!; this._data.textures.set(num, texture); } - public setReadWriteBuffer (name: string, buffer: Buffer): void {} - public setReadWriteTexture (name: string, texture: Texture): void {} + public setReadWriteBuffer (name: string, buffer: Buffer): void { + // TODO + } + public setReadWriteTexture (name: string, texture: Texture): void { + // TODO + } public setSampler (name: string, sampler: Sampler): void { if (this._getCurrDescriptorBlock(name) === -1) { return; @@ -255,16 +261,31 @@ export class WebSetter { this._data.samplers.set(num, sampler); } public setBuiltinCameraConstants (camera: Camera): void { - + // TODO } public setBuiltinShadowMapConstants (light: Light, numLevels?: number): void { - + // TODO } public setBuiltinDirectionalLightViewConstants (light: DirectionalLight): void { - + // TODO } public setBuiltinSpotLightViewConstants (light: SpotLight): void { - + // TODO + } + public setBuiltinDirectionalLightConstants (light: DirectionalLight, camera: Camera): void { + // TODO + } + public setBuiltinSphereLightConstants (light: SphereLight, camera: Camera): void { + // TODO + } + public setBuiltinSpotLightConstants (light: SpotLight, camera: Camera): void { + // TODO + } + public setBuiltinPointLightConstants (light: PointLight, camera: Camera): void { + // TODO + } + public setBuiltinRangedDirectionalLightConstants (light: RangedDirectionalLight, camera: Camera): void { + // TODO } public hasSampler (name: string): boolean { const id = this._lg.attributeIndex.get(name); @@ -1084,7 +1105,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicMultisampleR this._pass.rasterViews.set(name, view); } resolveRenderTarget (source: string, target: string): void { - + // TODO } resolveDepthStencil ( source: string, @@ -1092,7 +1113,7 @@ export class WebRenderPassBuilder extends WebSetter implements BasicMultisampleR depthMode?: ResolveMode, stencilMode?: ResolveMode, ): void { - + // TODO } private _addComputeResource (name: string, accessType: AccessType, slotName: string): void { const view = new ComputeView(slotName); diff --git a/native/cocos/renderer/frame-graph/ImmutableState.cpp b/native/cocos/renderer/frame-graph/ImmutableState.cpp index 24a0b9ad604..4c62c3608a3 100644 --- a/native/cocos/renderer/frame-graph/ImmutableState.cpp +++ b/native/cocos/renderer/frame-graph/ImmutableState.cpp @@ -85,10 +85,10 @@ std::pair getBarrier(const ResourceBarrier& ba info.type = barrierInfo.barrierType; info.prevAccesses = getAccessFlags(usage, barrierInfo.beginStatus); info.nextAccesses = getAccessFlags(usage, barrierInfo.endStatus); - info.baseMipLevel = static_cast(barrierInfo.mipRange.base); - info.levelCount = static_cast(barrierInfo.mipRange.len); - info.baseSlice = static_cast(barrierInfo.layerRange.base); - info.sliceCount = static_cast(barrierInfo.layerRange.len); + info.range.mipLevel = static_cast(barrierInfo.mipRange.base); + info.range.levelCount = static_cast(barrierInfo.mipRange.len); + info.range.firstSlice = static_cast(barrierInfo.layerRange.base); + info.range.numSlices = static_cast(barrierInfo.layerRange.len); res.first = gfx::Device::getInstance()->getTextureBarrier(info); res.second = gfxTexture; diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index a8a6e4b22d2..da39c2c6dee 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -1343,6 +1343,18 @@ struct RenderPassInfo { EXPOSE_COPY_FN(RenderPassInfo) }; +struct ResourceRange { + uint32_t width{0}; + uint32_t height{0}; + uint32_t depthOrArraySize{0}; + uint32_t firstSlice{0}; + uint32_t numSlices{0}; + uint32_t mipLevel{0}; + uint32_t levelCount{0}; + uint32_t basePlane{0}; + uint32_t planeCount{0}; +}; + struct ALIGNAS(8) GeneralBarrierInfo { AccessFlags prevAccesses{AccessFlagBit::NONE}; AccessFlags nextAccesses{AccessFlagBit::NONE}; @@ -1360,11 +1372,7 @@ struct ALIGNAS(8) TextureBarrierInfo { BarrierType type{BarrierType::FULL}; - uint32_t baseMipLevel{0}; - uint32_t levelCount{1}; - uint32_t baseSlice{0}; - uint32_t sliceCount{1}; - + ResourceRange range{}; uint64_t discardContents{0}; // @ts-boolean Queue *srcQueue{nullptr}; // @ts-nullable diff --git a/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp index 86199a46bc0..61aa80a32e2 100644 --- a/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp +++ b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp @@ -44,10 +44,10 @@ CCVKTextureBarrier::CCVKTextureBarrier(const TextureBarrierInfo &info) : Texture _gpuBarrier->barrier.prevLayout = getAccessLayout(info.prevAccesses); _gpuBarrier->barrier.nextLayout = getAccessLayout(info.nextAccesses); _gpuBarrier->barrier.discardContents = !!info.discardContents; - _gpuBarrier->barrier.subresourceRange.baseMipLevel = 0U; - _gpuBarrier->barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; - _gpuBarrier->barrier.subresourceRange.baseArrayLayer = 0U; - _gpuBarrier->barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; + _gpuBarrier->barrier.subresourceRange.baseMipLevel = info.range.mipLevel; + _gpuBarrier->barrier.subresourceRange.levelCount = info.range.levelCount; + _gpuBarrier->barrier.subresourceRange.baseArrayLayer = info.range.firstSlice; + _gpuBarrier->barrier.subresourceRange.layerCount = info.range.numSlices; _gpuBarrier->barrier.srcQueueFamilyIndex = info.srcQueue ? static_cast(info.srcQueue)->gpuQueue()->queueFamilyIndex : VK_QUEUE_FAMILY_IGNORED; diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index 1982760fd0a..41d24898bcf 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -95,7 +95,8 @@ ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept topologicalOrder(alloc), resourceAccess(alloc), movedTarget(alloc), - movedSourceStatus(alloc) {} + movedSourceStatus(alloc), + movedTargetStatus(alloc) {} // ContinuousContainer void ResourceAccessGraph::reserve(vertices_size_type sz) { diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index 25816eaf81c..4f6b586f6f4 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -60,21 +60,9 @@ struct LeafStatus { bool needCulling{false}; }; -struct ResourceRange { - uint32_t width{0}; - uint32_t height{0}; - uint32_t depthOrArraySize{0}; - uint32_t firstSlice{0}; - uint32_t numSlices{0}; - uint32_t mipLevel{0}; - uint32_t levelCount{0}; - uint32_t basePlane{0}; - uint32_t planeCount{0}; -}; - struct AccessStatus { gfx::AccessFlagBit accessFlag{gfx::AccessFlagBit::NONE}; - ResourceRange range; + gfx::ResourceRange range; }; struct ResourceAccessNode { @@ -135,7 +123,7 @@ struct FGRenderPassInfo { FGRenderPassInfo& operator=(FGRenderPassInfo&& rhs) = default; FGRenderPassInfo& operator=(FGRenderPassInfo const& rhs) = default; - std::vector colorAccesses; + ccstd::vector colorAccesses; LayoutAccess dsAccess; LayoutAccess dsResolveAccess; gfx::RenderPassInfo rpInfo; @@ -156,8 +144,23 @@ struct Barrier { }; struct BarrierNode { - std::vector frontBarriers; - std::vector rearBarriers; + ccstd::vector frontBarriers; + ccstd::vector rearBarriers; +}; + +struct SliceNode { + bool full{false}; + ccstd::vector mips; +}; + +struct TextureNode { + bool full{false}; + ccstd::vector slices; +}; + +struct ResourceNode { + bool full{false}; + ccstd::vector planes; }; struct ResourceAccessGraph { @@ -293,8 +296,9 @@ struct ResourceAccessGraph { PmrFlatMap resourceLifeRecord; ccstd::pmr::vector topologicalOrder; PmrTransparentMap> resourceAccess; - PmrFlatMap> movedTarget; + PmrFlatMap> movedTarget; PmrFlatMap movedSourceStatus; + PmrFlatMap movedTargetStatus; }; struct RelationGraph { diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 6cdd864a2b4..d18121f8761 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -122,6 +122,57 @@ ResourceGraph::vertex_descriptor FrameGraphDispatcher::realResourceID(const ccst return resourceAccessGraph.resourceIndex.at(name); } +[[nodiscard]] ccstd::pmr::string concatResName( + std::string_view name0, + std::string_view name1, + boost::container::pmr::memory_resource *scratch) { + ccstd::pmr::string name(name0, scratch); + name += "/"; + name += name1; + return name; +} + +[[nodiscard]] ccstd::pmr::string getSubresNameByPlane(const ccstd::pmr::string &resName, + uint32_t planeID, const ResourceGraph &resg, + boost::container::pmr::memory_resource *scratch) { + const auto &desc = get(ResourceGraph::DescTag{}, resg, vertex(resName, resg)); + // depth stencil + if (desc.format == gfx::Format::DEPTH_STENCIL) { + auto nameView = planeID == 0 ? DEPTH_PLANE_NAME : STENCIL_PLANE_NAME; + const auto &subresName = concatResName(resName, nameView, scratch); + return subresName; + } + + // array + if (desc.dimension == ResourceDimension::TEXTURE2D && desc.depthOrArraySize > 1) { + ccstd::pmr::set leaves(scratch); + auto resID = vertex(resName, resg); + + using LeafGatherFunc = std::function &)>; + LeafGatherFunc leafGather = [&](ResourceGraph::vertex_descriptor v, const ResourceGraph &resg, ccstd::pmr::set &names) { + for (const auto &e : makeRange(children(v, resg))) { + if (!out_degree(e.target, resg)) { + const auto &rName = get(ResourceGraph::NameTag{}, resg, e.target); + names.emplace(rName); + } else { + leafGather(e.target, resg, names); + } + } + }; + leafGather(resID, resg, leaves); + + auto iter = leaves.begin(); + std::advance(iter, planeID); + return (*iter); + } + + // cube + + // UNREACHABLE + CC_ASSERT(false); + return ""; +} + ResourceGraph::vertex_descriptor locateSubres(ResourceGraph::vertex_descriptor resID, const ResourceGraph &resg, std::string_view name) { auto resName = get(ResourceGraph::NameTag{}, resg, resID); resName += "/"; @@ -129,15 +180,12 @@ ResourceGraph::vertex_descriptor locateSubres(ResourceGraph::vertex_descriptor r return findVertex(resName, resg); } -ResourceGraph::vertex_descriptor locateSubres(ResourceGraph::vertex_descriptor resID, +ResourceGraph::vertex_descriptor locateSubres(const ccstd::pmr::string& originName, const ResourceGraph &resg, - uint32_t basePlane) { - auto ret = resID; - const auto &desc = get(ResourceGraph::DescTag{}, resg, resID); - if (desc.format == gfx::Format::DEPTH_STENCIL) { - ret = basePlane == 0 ? locateSubres(resID, resg, DEPTH_PLANE_NAME) : locateSubres(resID, resg, STENCIL_PLANE_NAME); - } - return ret; + uint32_t basePlane, + boost::container::pmr::memory_resource *scratch) { + const auto &resName = getSubresNameByPlane(originName, basePlane, resg, scratch); + return findVertex(resName, resg); } PmrFlatMap FrameGraphDispatcher::buildDescriptorIndex( @@ -152,7 +200,7 @@ PmrFlatMap FrameGraphDispatcher:: const auto &name = computeView.name; CC_EXPECTS(!name.empty()); const auto nameID = layoutGraph.attributeIndex.at(name); - auto subresID = locateSubres(resID, resourceGraph, computeView.plane); + auto subresID = locateSubres(resName, resourceGraph, computeView.plane, scratch); resourceIndex.emplace(nameID, subresID); } } @@ -317,11 +365,11 @@ LayoutAccess FrameGraphDispatcher::getResourceAccess(ResourceGraph::vertex_descr using PmrString = ccstd::pmr::string; using EdgeList = std::pair; using CloseCircuit = std::pair; -using CloseCircuits = std::vector; +using CloseCircuits = ccstd::vector; using RelationVert = RelationGraph::vertex_descriptor; -using RelationVerts = std::vector; +using RelationVerts = ccstd::vector; using RelationEdge = RelationGraph::edge_descriptor; -using RelationEdges = std::vector; +using RelationEdges = ccstd::vector; using ScoreMap = std::map>; using RasterViewsMap = PmrTransparentMap; using ComputeViewsMap = PmrTransparentMap>; @@ -340,7 +388,7 @@ struct ViewStatus { const AccessType access; const gfx::ShaderStageFlagBit visibility; const gfx::AccessFlags accessFlag; - const ResourceRange ⦥ + const gfx::ResourceRange ⦥ }; constexpr uint32_t EXPECT_START_ID = 0; @@ -423,10 +471,10 @@ bool isResourceView(const ResourceGraph::vertex_descriptor v, const ResourceGrap return resg.isTextureView(v); // || isBufferView } -ResourceRange getResourceRange(const ResourceGraph::vertex_descriptor v, +gfx::ResourceRange getResourceRange(const ResourceGraph::vertex_descriptor v, const ResourceGraph &resg) { const auto &desc = get(ResourceGraph::DescTag{}, resg, v); - ResourceRange range{ + gfx::ResourceRange range{ desc.width, desc.height, desc.depthOrArraySize, @@ -813,16 +861,6 @@ void fillRenderPassInfo(const AttachmentMap &colorMap, } }; -[[nodiscard("concat")]] ccstd::pmr::string concatResName( - std::string_view name0, - std::string_view name1, - boost::container::pmr::memory_resource *scratch) { - ccstd::pmr::string name(name0, scratch); - name += "/"; - name += name1; - return name; -} - void extractNames(const ccstd::pmr::string &resName, const RasterView &view, ccstd::pmr::vector> &names) { @@ -857,26 +895,6 @@ void extractNames(const ccstd::pmr::string &resName, } } -[[nodiscard("subresName")]] ccstd::pmr::string getSubresName(const ccstd::pmr::string &resName, - uint32_t planeID, const ResourceGraph& resg, - boost::container::pmr::memory_resource* scratch) { - const auto& desc = get(ResourceGraph::DescTag{}, resg, vertex(resName, resg)); - if(desc.format == gfx::Format::DEPTH_STENCIL) { - auto nameView = planeID == 0 ? DEPTH_PLANE_NAME : STENCIL_PLANE_NAME; - const auto &subresName = concatResName(resName, nameView, scratch); - return subresName; - } - - - // cube - - // array - - // UNREACHABLE - CC_ASSERT(false); - return ""; -} - auto checkRasterViews(const Graphs &graphs, ResourceAccessGraph::vertex_descriptor ragVertID, ResourceAccessNode &node, @@ -965,8 +983,8 @@ bool checkComputeViews(const Graphs &graphs, ResourceAccessGraph::vertex_descrip tryAddEdge(lastVertId, ragVertID, relationGraph); dependent = lastVertId != EXPECT_START_ID; - if(out_degree(resID, resourceGraph)) { - const auto& subresFullName = getSubresName(resName, computeView.plane, resourceGraph, resourceAccessGraph.resource()); + if (out_degree(resID, resourceGraph) && (computeView.plane != 0xFFFFFFFF)) { + const auto& subresFullName = getSubresNameByPlane(resName, computeView.plane, resourceGraph, resourceAccessGraph.resource()); resourceAccessGraph.resourceIndex.emplace(subresFullName, vertex(subresFullName, resourceGraph)); } } @@ -1352,118 +1370,163 @@ void startRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); } -namespace { -struct SliceNode { - bool full{false}; - ccstd::pmr::vector mips; -}; - -struct TextureNode { - bool full{false}; - ccstd::pmr::vector slices; -}; - -struct ResourceNode { - ccstd::pmr::vector planes; -}; -} // namespace - -bool rangeCheck(ccstd::pmr::map &status, - const ResourceDesc &desc, - const PmrString &targetName, +bool rangeCheck(ResourceNode &status, + const ResourceDesc &/*desc*/, + const PmrString &/*targetName*/, uint32_t firstSlice, uint32_t numSlices, uint32_t firstMip, uint32_t mipLevels, uint32_t planeIndex) { - if (status.find(targetName) == status.end()) { - status.emplace(targetName, ResourceNode{}); + CC_ASSERT(planeIndex < status.planes.size()); + // spare space in target + bool check = !status.full; + check &= !status.planes[planeIndex].full; + if (check) { + for (auto slice = firstSlice; slice < firstSlice + numSlices; ++slice) { + auto &slices = status.planes[planeIndex].slices; + // no spare space in this slice + check &= !slices[slice].full; + if (!check) { + continue; + } + for (auto mip = firstMip; mip < firstMip + mipLevels; ++mip) { + auto &mips = slices[slice].mips; + // this mip has been taken + check &= mips[mip] == std::numeric_limits::max(); + if (!check) { + continue; + } + mips[mip] = mip; + auto maxIter = std::max_element(mips.begin(), mips.end()); + if ((*maxIter) != std::numeric_limits::max()) { + // linear increasing + check &= (*maxIter) == mips.size() - 1; + slices[slice].full = true; + } + } + if (std::all_of(slices.begin(), slices.end(), [](const SliceNode &sliceNode) { return sliceNode.full; })) { + status.planes[planeIndex].full = true; + } + } } + return check; +} - if (planeIndex >= status[targetName].planes.size()) { - status[targetName].planes.resize(planeIndex + 1); - status[targetName].planes[planeIndex].slices.resize(desc.depthOrArraySize); - for (auto &slice : status[targetName].planes[planeIndex].slices) { - slice.mips.resize(desc.mipLevels, std::numeric_limits::max()); - } +uint32_t getPlaneCount(gfx::Format format) { + switch (format) { + case gfx::Format::DEPTH_STENCIL: + return 2; + default: + return 1; } +} - // no spare space in target - bool check = !status[targetName].planes[planeIndex].full; - for (auto slice = firstSlice; slice < firstSlice + numSlices; ++slice) { - auto &slices = status[targetName].planes[planeIndex].slices; - // no spare space in this slice - check &= !slices[slice].full; - for (auto mip = firstMip; mip < firstMip + mipLevels; ++mip) { - auto &mips = slices[slice].mips; - // this mip has been taken - check &= mips[mip] == std::numeric_limits::max(); - mips[mip] = mip; - auto maxIter = std::max_element(mips.begin(), mips.end()); - if ((*maxIter) != std::numeric_limits::max()) { - // linear increasing - check &= (*maxIter) == mips.size() - 1; - slices[slice].full = true; +bool moveValidation(const MovePass& pass, ResourceAccessGraph& rag, const ResourceGraph& resourceGraph) { + bool check = true; + ccstd::pmr::vector targets(rag.get_allocator()); + for (const auto &movePair : pass.movePairs) { + const auto &fromResName = movePair.source; + const auto fromResID = resourceGraph.valueIndex.at(fromResName); + const auto &fromResDesc = get(ResourceGraph::DescTag{}, resourceGraph, fromResID); + + const auto &toResName = movePair.target; + const auto toResID = resourceGraph.valueIndex.at(toResName); + const auto &toResDesc = get(ResourceGraph::DescTag{}, resourceGraph, toResID); + + const auto &fromResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, fromResID); + const auto &toResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, toResID); + auto commonUsage = fromResDesc.flags | toResDesc.flags; + + targets.emplace_back(toResName); + + if (rag.movedTargetStatus.find(toResName) == rag.movedTargetStatus.end()) { + rag.movedTargetStatus[toResName].planes.resize(getPlaneCount(toResDesc.format)); + for (auto &plane : rag.movedTargetStatus[toResName].planes) { + plane.slices.resize(toResDesc.depthOrArraySize); + for (auto &slice : plane.slices) { + slice.mips.resize(toResDesc.mipLevels, std::numeric_limits::max()); + } } } - if (std::all_of(slices.begin(), slices.end(), [](const SliceNode &sliceNode) { return sliceNode.full; })) { - status[targetName].planes[planeIndex].full = true; - } + + rangeCheck(rag.movedTargetStatus[toResName], toResDesc, toResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); + uint32_t validConditions[] = { + !fromResTraits.hasSideEffects(), + rag.movedSourceStatus.find(toResName) == rag.movedSourceStatus.end(), + rag.movedSourceStatus.find(fromResName) == rag.movedSourceStatus.end(), + fromResTraits.residency != ResourceResidency::MEMORYLESS && toResTraits.residency != ResourceResidency::MEMORYLESS, + fromResDesc.dimension == toResDesc.dimension, + fromResDesc.width == toResDesc.width, + fromResDesc.height == toResDesc.height, + fromResDesc.format == toResDesc.format, + fromResDesc.sampleCount == toResDesc.sampleCount, + (fromResDesc.depthOrArraySize == toResDesc.depthOrArraySize) || (toResDesc.dimension != ResourceDimension::BUFFER), // full move if resource is buffer + }; + bool val = std::min_element(std::begin(validConditions), std::end(validConditions)); + check &= val; } + + // full check + std::for_each(targets.begin(), targets.end(), [&](const ccstd::pmr::string &target) { + ResourceNode &resNode = rag.movedTargetStatus[target]; + resNode.full |= std::all_of(resNode.planes.begin(), resNode.planes.end(), [](const auto &textureNode) { + return textureNode.full; + }); + }); + return check; } -bool moveValidation(const MovePass& pass, ResourceAccessGraph& rag, const ResourceGraph& resourceGraph) { - bool check = true; - // ccstd::pmr::map sourceCheck; - ccstd::pmr::map targetCheck; - for (const auto &movePair : pass.movePairs) { - const auto &fromResName = movePair.source; - const auto fromResID = resourceGraph.valueIndex.at(fromResName); - const auto &fromResDesc = get(ResourceGraph::DescTag{}, resourceGraph, fromResID); - - const auto &toResName = movePair.target; - const auto toResID = resourceGraph.valueIndex.at(toResName); - const auto &toResDesc = get(ResourceGraph::DescTag{}, resourceGraph, toResID); - - const auto &fromResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, fromResID); - const auto &toResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, toResID); - auto commonUsage = fromResDesc.flags | toResDesc.flags; - - // bool sourceRangeValid = rangeCheck(targetCheck, toResDesc, fromResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); - bool targetRangeValid = rangeCheck(targetCheck, toResDesc, toResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); - - uint32_t validConditions[] = { - !fromResTraits.hasSideEffects(), - rag.movedSourceStatus.find(toResName) == rag.movedSourceStatus.end(), - rag.movedSourceStatus.find(fromResName) == rag.movedSourceStatus.end(), - targetRangeValid, - fromResTraits.residency != ResourceResidency::MEMORYLESS && toResTraits.residency != ResourceResidency::MEMORYLESS, - fromResDesc.dimension == toResDesc.dimension, - fromResDesc.width == toResDesc.width, - fromResDesc.height == toResDesc.height, - fromResDesc.format == toResDesc.format, - fromResDesc.sampleCount == toResDesc.sampleCount, - (fromResDesc.depthOrArraySize == toResDesc.depthOrArraySize) || (toResDesc.dimension != ResourceDimension::BUFFER), // full move if resource is buffer - }; - bool val = std::min_element(std::begin(validConditions), std::end(validConditions)); - check &= val; - } - - // full destination - check &= std::all_of(targetCheck.begin(), targetCheck.end(), [](const auto &pair) { - const ResourceNode &resNode = pair.second; - return std::all_of(resNode.planes.begin(), resNode.planes.end(), [](const auto &textureNode) { - return textureNode.full; - }); - }); - - return check; - } +[[nodiscard]] ccstd::pmr::string getSubresourceNameByRange( + const gfx::ResourceRange &range, + boost::container::pmr::memory_resource *scratch) { + ccstd::pmr::string subresName(scratch); + // if () { + // switch (range.firstSlice) { + // case 0: + // return CUBE_RIGHT_NAME.data(); + // case 1: + // return CUBE_LEFT_NAME.data(); + // case 2: + // return CUBE_TOP_NAME.data(); + // case 3: + // return CUBE_BOTTOM_NAME.data(); + // case 4: + // return CUBE_FRONT_NAME.data(); + // case 5: + // return CUBE_REAR_NAME.data(); + // default: + // break; + // } + // } else { + std::string suffix = std::to_string(range.basePlane) + "_" + std::to_string(range.planeCount) + "_" + std::to_string(range.firstSlice) + "_" + std::to_string(range.numSlices) + "_" + std::to_string(range.mipLevel) + "_" + std::to_string(range.levelCount); + subresName = suffix; + // } + return subresName; +} + +gfx::SamplerInfo makePointSamplerInfo() { + return gfx::SamplerInfo{gfx::Filter::POINT, gfx::Filter::POINT, gfx::Filter::POINT}; +} + +SubresourceView makeSubresourceView(const ResourceDesc& desc, const gfx::ResourceRange& range) { + SubresourceView view{}; + view.firstArraySlice = range.firstSlice; + view.numArraySlices = range.numSlices; + view.indexOrFirstMipLevel = range.mipLevel; + view.numMipLevels = range.levelCount; + view.firstPlane = range.basePlane; + view.numPlanes = range.planeCount; + view.format = desc.format; + view.textureView = nullptr; + return view; +} void startMovePass(const Graphs &graphs, uint32_t passID, const MovePass &pass) { const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; - if(moveValidation(pass, resourceAccessGraph, resourceGraph)) { - for(const auto& pair : pass.movePairs) { + if (moveValidation(pass, resourceAccessGraph, resourceGraph)) { + for (const auto &pair : pass.movePairs) { + auto toleranceRange = getResourceRange(vertex(pair.target, resourceGraph), resourceGraph); auto srcResourceRange = getResourceRange(vertex(pair.source, resourceGraph), resourceGraph); srcResourceRange.firstSlice = pair.targetFirstSlice; srcResourceRange.mipLevel = pair.targetMostDetailedMip; @@ -1471,17 +1534,20 @@ void startMovePass(const Graphs &graphs, uint32_t passID, const MovePass &pass) auto lastStatusIter = resourceAccessGraph.resourceAccess.at(pair.source).rbegin(); resourceAccessGraph.movedSourceStatus.emplace(pair.source, AccessStatus{lastStatusIter->second.accessFlag, srcResourceRange}); - resourceAccessGraph.movedTarget[pair.target].emplace_back(pair.source); + resourceAccessGraph.movedTarget[pair.target].emplace(getSubresourceNameByRange(srcResourceRange, resourceAccessGraph.resource()), pair.source); resourceAccessGraph.resourceAccess[pair.target] = resourceAccessGraph.resourceAccess[pair.source]; auto targetResID = findVertex(pair.target, resourceGraph); resourceAccessGraph.resourceIndex[pair.target] = targetResID; auto &rag = resourceAccessGraph; - std::function feedBack = [&](const ccstd::pmr::string &source, ResourceGraph::vertex_descriptor v) { + std::function feedBack = [&]( + const ccstd::pmr::string &source, + ResourceGraph::vertex_descriptor v) { rag.resourceIndex[source] = v; + if (rag.movedTarget.find(source) != rag.movedTarget.end()) { - for (const auto &prt : rag.movedTarget[source]) { + for (const auto &[rangeStr, prt] : rag.movedTarget[source]) { feedBack(prt, v); } } @@ -1548,19 +1614,67 @@ struct DependencyVisitor : boost::dfs_visitor<> { const Graphs &graphs; }; +void subresourceAnalysis(ResourceAccessGraph& rag, ResourceGraph& resg) { + using RecursiveFuncType = std::function &, const ccstd::pmr::string &)>; + RecursiveFuncType addSubres = [&](const PmrFlatMap &subreses, const ccstd::pmr::string &resName) { + if (subreses.size() == 1) { + const auto &src = subreses.begin()->second; + rag.resourceIndex[src] = rag.resourceIndex.at(resName); + + if (rag.movedTarget.find(src) != rag.movedTarget.end()) { + addSubres(rag.movedTarget.at(src), src); + } + } else { + for (const auto &[rangeStr, subres] : subreses) { + auto targetResID = rag.resourceIndex.at(resName); + const auto &targetName = get(ResourceGraph::NameTag{}, resg, targetResID); + const auto &targetDesc = get(ResourceGraph::DescTag{}, resg, targetResID); + const auto &srcResourceRange = rag.movedSourceStatus.at(subres).range; + const auto &targetTraits = get(ResourceGraph::TraitsTag{}, resg, targetResID); + const auto &indexName = concatResName(targetName, subres, rag.resource()); + auto subresID = findVertex(indexName, resg); + if (subresID == ResourceGraph::null_vertex()) { + const auto &subView = makeSubresourceView(targetDesc, srcResourceRange); + // register to resourcegraph + subresID = addVertex( + SubresourceViewTag{}, + std::forward_as_tuple(indexName), + std::forward_as_tuple(targetDesc), + std::forward_as_tuple(targetTraits), + std::forward_as_tuple(), + std::forward_as_tuple(makePointSamplerInfo()), + std::forward_as_tuple(subView), + resg, + targetResID); + } + rag.resourceIndex[subres] = subresID; + + if (rag.movedTarget.find(subres) != rag.movedTarget.end()) { + addSubres(rag.movedTarget.at(subres), subres); + } + } + } + }; + + for (const auto &[targetName, subreses] : rag.movedTarget) { + if (subreses.size() > 1 && rag.movedSourceStatus.find(targetName) == rag.movedSourceStatus.end()) { + addSubres(rag.movedTarget.at(targetName), targetName); + } + } +} + // status of resource access -void buildAccessGraph(const Graphs &graphs) { +void buildAccessGraph(Graphs &graphs) { // what we need: // - pass dependency // - pass attachment access // AccessTable accessRecord; - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; + auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; size_t numPasses = 0; numPasses += renderGraph.rasterPasses.size(); numPasses += renderGraph.computePasses.size(); numPasses += renderGraph.copyPasses.size(); - numPasses += renderGraph.movePasses.size(); numPasses += renderGraph.raytracePasses.size(); resourceAccessGraph.reserve(static_cast(numPasses)); @@ -1601,6 +1715,9 @@ void buildAccessGraph(const Graphs &graphs) { } } + // moved resource + subresourceAnalysis(resourceAccessGraph, resourceGraph); + auto &rag = resourceAccessGraph; auto branchCulling = [](ResourceAccessGraph::vertex_descriptor vertex, ResourceAccessGraph &rag) -> void { CC_EXPECTS(out_degree(vertex, rag) == 0); @@ -1669,6 +1786,23 @@ void buildAccessGraph(const Graphs &graphs) { } #pragma region BUILD_BARRIERS +gfx::ResourceRange getOriginRange(ResourceGraph::vertex_descriptor v, const gfx::ResourceRange &currRange, const ResourceGraph &resg) { + gfx::ResourceRange ret = currRange; + auto resID = parent(v, resg); + if (resID == ResourceGraph::null_vertex()) { + return ret; + } + + while (resg.isTextureView(resID)) { + const auto &subresView = get(SubresourceViewTag{}, resID, resg); + ret.firstSlice += subresView.firstArraySlice; + ret.mipLevel += subresView.indexOrFirstMipLevel; + ret.basePlane += subresView.firstPlane; + resID = parent(resID, resg); + } + return ret; +} + void buildBarriers(FrameGraphDispatcher &fgDispatcher) { auto *scratch = fgDispatcher.scratch; const auto &renderGraph = fgDispatcher.renderGraph; @@ -1679,7 +1813,7 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { // record resource current in-access and out-access for every single node if (!fgDispatcher._accessGraphBuilt) { - const Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; + Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; buildAccessGraph(graphs); fgDispatcher._accessGraphBuilt = true; } @@ -1697,14 +1831,11 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { info.type = barrier.type; gfxBarrier = gfx::Device::getInstance()->getBufferBarrier(info); } else { + const auto& originRange = getOriginRange(barrier.resourceID, barrier.endStatus.range, resourceGraph); gfx::TextureBarrierInfo info; info.prevAccesses = barrier.beginStatus.accessFlag; info.nextAccesses = barrier.endStatus.accessFlag; - const auto &range = barrier.beginStatus.range; - info.baseMipLevel = range.mipLevel; - info.levelCount = range.levelCount; - info.baseSlice = range.firstSlice; - info.sliceCount = range.numSlices; + info.range = originRange; info.type = barrier.type; gfxBarrier = gfx::Device::getInstance()->getTextureBarrier(info); } @@ -1736,7 +1867,8 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { if (holds(dstPassID, renderGraph) || holds(dstPassID, renderGraph)) { const auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, rag, dstRagVertID); - if (fgRenderPassInfo.viewIndex.find(resName) != fgRenderPassInfo.viewIndex.end()) { + if (fgRenderPassInfo.viewIndex.find(resName) != fgRenderPassInfo.viewIndex.end() || + rag.movedTargetStatus.find(resName) != rag.movedTargetStatus.end()) { // renderpass info instead continue; } @@ -2275,7 +2407,7 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { auto &rag = fgDispatcher.resourceAccessGraph; if (!fgDispatcher._accessGraphBuilt) { - const Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; + Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; buildAccessGraph(graphs); fgDispatcher._accessGraphBuilt = true; } @@ -2286,7 +2418,7 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { boost::transitive_closure(relationGraph, relationGraphTc); CloseCircuits circuits; - std::vector crossEdges; + ccstd::vector crossEdges; PassVisitor visitor(relationGraphTc, circuits); auto colors = relationGraph.colors(scratch); boost::depth_first_search(relationGraph, visitor, get(colors, relationGraph)); @@ -2314,7 +2446,7 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { RelationVerts candidates; candidates.push_back(EXPECT_START_ID); - std::vector candidateBuffer; + ccstd::vector candidateBuffer; uint32_t coloredVerts = 0; while (coloredVerts < relationGraph._vertices.size()) { // decreasing order, pop back from vector, push into queue, then it's ascending order. diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index b21235bc46b..1fdb0ebed7d 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -88,6 +88,11 @@ class NativeSetter : public NativeRenderNode { void setSampler(const ccstd::string &name, gfx::Sampler *sampler) /*implements*/; void setBuiltinCameraConstants(const scene::Camera *camera) /*implements*/; void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) /*implements*/; + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) /*implements*/; + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) /*implements*/; + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) /*implements*/; + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) /*implements*/; + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) /*implements*/; void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) /*implements*/; void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) /*implements*/; @@ -175,6 +180,21 @@ class NativeRenderQueueBuilder final : public RenderQueueBuilder, public NativeS void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } @@ -183,7 +203,7 @@ class NativeRenderQueueBuilder final : public RenderQueueBuilder, public NativeS } void addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) override; - void addScene(const scene::Camera *camera, SceneFlags sceneFlags) override; + void addScene(const scene::Camera *camera, SceneFlags sceneFlags, const scene::Light *light) override; void addSceneCulledByDirectionalLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::DirectionalLight *light, uint32_t level) override; void addSceneCulledBySpotLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::SpotLight *light) override; void addFullscreenQuad(Material *material, uint32_t passID, SceneFlags sceneFlags) override; @@ -250,6 +270,21 @@ class NativeRenderSubpassBuilder final : public RenderSubpassBuilder, public Nat void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } @@ -346,6 +381,21 @@ class NativeMultisampleRenderSubpassBuilder final : public MultisampleRenderSubp void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } @@ -445,6 +495,21 @@ class NativeComputeSubpassBuilder final : public ComputeSubpassBuilder, public N void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } @@ -517,6 +582,21 @@ class NativeRenderPassBuilder final : public RenderPassBuilder, public NativeSet void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } @@ -601,6 +681,21 @@ class NativeMultisampleRenderPassBuilder final : public MultisampleRenderPassBui void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } @@ -684,6 +779,21 @@ class NativeComputeQueueBuilder final : public ComputeQueueBuilder, public Nativ void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } @@ -751,6 +861,21 @@ class NativeComputePassBuilder final : public ComputePassBuilder, public NativeS void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) override { NativeSetter::setBuiltinShadowMapConstants(light); } + void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinDirectionalLightConstants(light, camera); + } + void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSphereLightConstants(light, camera); + } + void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinSpotLightConstants(light, camera); + } + void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinPointLightConstants(light, camera); + } + void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) override { + NativeSetter::setBuiltinRangedDirectionalLightConstants(light, camera); + } void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) override { NativeSetter::setBuiltinDirectionalLightViewConstants(light, level); } diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index 91c9dcf73b4..960cb08d0d4 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -736,7 +736,8 @@ void NativeRenderQueueBuilder::addSceneOfCamera( data); } -void NativeRenderQueueBuilder::addScene(const scene::Camera *camera, SceneFlags sceneFlags) { +void NativeRenderQueueBuilder::addScene(const scene::Camera *camera, SceneFlags sceneFlags, const scene::Light *light) { + std::ignore = light; SceneData data(camera->getScene(), camera, sceneFlags, LightInfo{}); auto sceneID = addVertex2( diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h index bf1ff547408..a28f1c6fdf7 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h @@ -217,12 +217,12 @@ inline bool defaultAttachment(std::string_view slotName) { static constexpr std::string_view DEPTH_PLANE_NAME = "depth"; static constexpr std::string_view STENCIL_PLANE_NAME = "stencil"; -static constexpr std::string_view CUBE_TOP_NAME = "Top"; -static constexpr std::string_view CUBE_BOTTOM_NAME = "Bottom"; -static constexpr std::string_view CUBE_FRONT_NAME = "Front"; -static constexpr std::string_view CUBE_REAR_NAME = "Rear"; -static constexpr std::string_view CUBE_LEFT_NAME = "Left"; -static constexpr std::string_view CUBE_RIGHT_NAME = "Right"; +static constexpr std::string_view CUBE_TOP_NAME = "top"; +static constexpr std::string_view CUBE_BOTTOM_NAME = "bottom"; +static constexpr std::string_view CUBE_FRONT_NAME = "front"; +static constexpr std::string_view CUBE_REAR_NAME = "rear"; +static constexpr std::string_view CUBE_LEFT_NAME = "left"; +static constexpr std::string_view CUBE_RIGHT_NAME = "right"; } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 5c8ce3ee84f..1086f449745 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -262,21 +262,27 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { CC_EXPECTS(parentID != resg.null_vertex()); CC_EXPECTS(resg.isTexture(parentID)); CC_ENSURES(!resg.isTextureView(parentID)); - mount(device, parentID); // NOLINT(misc-no-recursion) + mount(device, parentID); }, [&](SubresourceView& view) { // NOLINT(misc-no-recursion) + SubresourceView originView = view; auto parentID = parent(vertID, resg); CC_EXPECTS(parentID != resg.null_vertex()); while (resg.isTextureView(parentID)) { + const auto& prtView = get(SubresourceViewTag{}, parentID, resg); + originView.firstPlane += prtView.firstPlane; + originView.firstArraySlice += prtView.firstArraySlice; + originView.indexOrFirstMipLevel += prtView.indexOrFirstMipLevel; parentID = parent(parentID, resg); } CC_EXPECTS(parentID != resg.null_vertex()); CC_EXPECTS(resg.isTexture(parentID)); CC_ENSURES(!resg.isTextureView(parentID)); + mount(device, parentID); // NOLINT(misc-no-recursion) auto* parentTexture = resg.getTexture(parentID); const auto& desc = get(ResourceGraph::DescTag{}, resg, vertID); if (!view.textureView) { - auto textureViewInfo = getTextureViewInfo(view, desc); + auto textureViewInfo = getTextureViewInfo(originView, desc); textureViewInfo.texture = parentTexture; view.textureView = device->createTexture(textureViewInfo); } diff --git a/native/cocos/renderer/pipeline/custom/NativeSetter.cpp b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp index 6f4e2ca6fd9..bb313d6cfca 100644 --- a/native/cocos/renderer/pipeline/custom/NativeSetter.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp @@ -148,6 +148,21 @@ void NativeSetter::setBuiltinShadowMapConstants( setShadowUBOView(*device, *layoutGraph, sceneData, *light, data); } +void NativeSetter::setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) { +} + +void NativeSetter::setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) { +} + +void NativeSetter::setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) { +} + +void NativeSetter::setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) { +} + +void NativeSetter::setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) { +} + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp index 9bb23563b0b..c7fed6ceedb 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonJsb.cpp @@ -44,6 +44,9 @@ bool nativevalue_to_se(const cc::render::LightInfo &from, se::Value &to, se::Obj nativevalue_to_se(from.level, tmp, ctx); obj->setProperty("level", tmp); + nativevalue_to_se(from.culledByLight, tmp, ctx); + obj->setProperty("culledByLight", tmp); + to.setObject(obj); return true; } @@ -242,6 +245,10 @@ bool sevalue_to_native(const se::Value &from, cc::render: if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->level), ctx); } + obj->getProperty("culledByLight", &field, true); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->culledByLight), ctx); + } return ok; } diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h index 49fa456c4cd..4c9467badf2 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.h @@ -40,11 +40,13 @@ namespace render { inline void save(OutputArchive& ar, const LightInfo& v) { // skip, light: IntrusivePtr save(ar, v.level); + save(ar, v.culledByLight); } inline void load(InputArchive& ar, LightInfo& v) { // skip, light: IntrusivePtr load(ar, v.level); + load(ar, v.culledByLight); } inline void save(OutputArchive& ar, const Descriptor& v) { diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h index eb6dfe6a9b3..cad5d71c02c 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderCommonTypes.h @@ -211,12 +211,17 @@ enum class ClearValueType { struct LightInfo { LightInfo() = default; + LightInfo(IntrusivePtr lightIn, uint32_t levelIn, bool culledByLightIn) noexcept + : light(std::move(lightIn)), + level(levelIn), + culledByLight(culledByLightIn) {} LightInfo(IntrusivePtr lightIn, uint32_t levelIn) noexcept : light(std::move(lightIn)), level(levelIn) {} IntrusivePtr light; uint32_t level{0}; + bool culledByLight{false}; }; enum class DescriptorTypeOrder { diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index 4c5e015b567..77845fd5c64 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -57,7 +57,10 @@ class GeometryRenderer; namespace scene { class DirectionalLight; +class SphereLight; class SpotLight; +class PointLight; +class RangedDirectionalLight; class Model; class RenderScene; class RenderWindow; @@ -452,6 +455,11 @@ class Setter : public RenderNode { virtual void setSampler(const ccstd::string &name, gfx::Sampler *sampler) = 0; virtual void setBuiltinCameraConstants(const scene::Camera *camera) = 0; virtual void setBuiltinShadowMapConstants(const scene::DirectionalLight *light) = 0; + virtual void setBuiltinDirectionalLightConstants(const scene::DirectionalLight *light, const scene::Camera *camera) = 0; + virtual void setBuiltinSphereLightConstants(const scene::SphereLight *light, const scene::Camera *camera) = 0; + virtual void setBuiltinSpotLightConstants(const scene::SpotLight *light, const scene::Camera *camera) = 0; + virtual void setBuiltinPointLightConstants(const scene::PointLight *light, const scene::Camera *camera) = 0; + virtual void setBuiltinRangedDirectionalLightConstants(const scene::RangedDirectionalLight *light, const scene::Camera *camera) = 0; virtual void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light, uint32_t level) = 0; virtual void setBuiltinSpotLightViewConstants(const scene::SpotLight *light) = 0; void setBuiltinDirectionalLightViewConstants(const scene::DirectionalLight *light) { @@ -480,7 +488,7 @@ class RenderQueueBuilder : public Setter { * @param sceneFlags @en Rendering flags of the scene @zh 场景渲染标志位 */ virtual void addSceneOfCamera(scene::Camera *camera, LightInfo light, SceneFlags sceneFlags) = 0; - virtual void addScene(const scene::Camera *camera, SceneFlags sceneFlags) = 0; + virtual void addScene(const scene::Camera *camera, SceneFlags sceneFlags, const scene::Light *light) = 0; virtual void addSceneCulledByDirectionalLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::DirectionalLight *light, uint32_t level) = 0; virtual void addSceneCulledBySpotLight(const scene::Camera *camera, SceneFlags sceneFlags, scene::SpotLight *light) = 0; /** @@ -520,6 +528,9 @@ class RenderQueueBuilder : public Setter { void addSceneOfCamera(scene::Camera *camera, LightInfo light) { addSceneOfCamera(camera, std::move(light), SceneFlags::NONE); } + void addScene(const scene::Camera *camera, SceneFlags sceneFlags) { + addScene(camera, sceneFlags, nullptr); + } void addFullscreenQuad(Material *material, uint32_t passID) { addFullscreenQuad(material, passID, SceneFlags::NONE); } From e1caa285bfcb5086fcb47f580aca5db5e98e987c Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Thu, 10 Aug 2023 16:48:34 +0800 Subject: [PATCH 122/232] update migrated resources and meta files (#15919) --- .../default_materials/default-billboard-material.mtl.meta | 2 +- editor/assets/default_materials/default-clear-stencil.mtl.meta | 2 +- .../default_materials/default-material-transparent.mtl.meta | 2 +- editor/assets/default_materials/default-material.mtl.meta | 2 +- .../default_materials/default-particle-gpu-material.mtl.meta | 2 +- .../assets/default_materials/default-particle-material.mtl.meta | 2 +- editor/assets/default_materials/default-spine-material.mtl.meta | 2 +- .../default_materials/default-sprite-renderer-material.mtl.meta | 2 +- editor/assets/default_materials/default-trail-material.mtl.meta | 2 +- .../assets/default_materials/missing-effect-material.mtl.meta | 2 +- editor/assets/default_materials/missing-material.mtl.meta | 2 +- editor/assets/default_materials/particle-add.mtl.meta | 2 +- editor/assets/default_materials/standard-material.mtl.meta | 2 +- editor/assets/default_materials/ui-alpha-test-material.mtl.meta | 2 +- editor/assets/default_materials/ui-base-material.mtl.meta | 2 +- editor/assets/default_materials/ui-graphics-material.mtl.meta | 2 +- .../default_materials/ui-sprite-alpha-sep-material.mtl.meta | 2 +- .../ui-sprite-gray-alpha-sep-material.mtl.meta | 2 +- .../assets/default_materials/ui-sprite-gray-material.mtl.meta | 2 +- editor/assets/default_materials/ui-sprite-material.mtl.meta | 2 +- editor/assets/default_renderpipeline/deferred-lighting.mtl.meta | 2 +- editor/assets/default_renderpipeline/post-process.mtl.meta | 2 +- editor/assets/default_renderpipeline/tonemap.mtl.meta | 2 +- .../default_skybox/default_skybox_reflection_convolution.meta | 2 +- editor/assets/effects/advanced/car-paint.effect.meta | 2 +- editor/assets/effects/advanced/eye.effect.meta | 2 +- editor/assets/effects/advanced/glass.effect.meta | 2 +- editor/assets/effects/advanced/hair.effect.meta | 2 +- editor/assets/effects/advanced/leaf.effect.meta | 2 +- editor/assets/effects/advanced/simple-skin.effect.meta | 2 +- editor/assets/effects/advanced/skin.effect.meta | 2 +- editor/assets/effects/advanced/sky.effect.meta | 2 +- editor/assets/effects/advanced/water.effect.meta | 2 +- .../assets/effects/builtin-reflection-probe-preview.effect.meta | 2 +- editor/assets/effects/builtin-standard.effect.meta | 2 +- editor/assets/effects/builtin-terrain.effect.meta | 2 +- editor/assets/effects/builtin-toon.effect.meta | 2 +- editor/assets/effects/builtin-unlit.effect | 2 +- editor/assets/effects/builtin-unlit.effect.meta | 2 +- editor/assets/effects/for2d/builtin-spine.effect.meta | 2 +- editor/assets/effects/for2d/builtin-sprite-renderer.effect.meta | 2 +- editor/assets/effects/for2d/builtin-sprite.effect.meta | 2 +- .../assets/effects/internal/builtin-camera-texture.effect.meta | 2 +- .../assets/effects/internal/builtin-clear-stencil.effect.meta | 2 +- .../assets/effects/internal/builtin-debug-renderer.effect.meta | 2 +- .../effects/internal/builtin-geometry-renderer.effect.meta | 2 +- editor/assets/effects/internal/builtin-graphics.effect.meta | 2 +- .../assets/effects/internal/builtin-occlusion-query.effect.meta | 2 +- .../effects/internal/builtin-reflection-deferred.effect.meta | 2 +- editor/assets/effects/internal/builtin-wireframe.effect.meta | 2 +- .../assets/effects/internal/editor/box-height-light.effect.meta | 2 +- editor/assets/effects/internal/editor/gizmo.effect.meta | 2 +- editor/assets/effects/internal/editor/grid-2d.effect.meta | 2 +- editor/assets/effects/internal/editor/grid-stroke.effect.meta | 2 +- editor/assets/effects/internal/editor/grid.effect.meta | 2 +- .../internal/editor/light-probe-visualization.effect.meta | 2 +- editor/assets/effects/internal/editor/light.effect.meta | 2 +- .../effects/internal/editor/terrain-circle-brush.effect.meta | 2 +- .../effects/internal/editor/terrain-image-brush.effect.meta | 2 +- .../effects/internal/editor/terrain-select-brush.effect.meta | 2 +- editor/assets/effects/legacy/standard.effect | 2 +- editor/assets/effects/legacy/standard.effect.meta | 2 +- editor/assets/effects/legacy/terrain.effect.meta | 2 +- editor/assets/effects/legacy/toon.effect | 2 +- editor/assets/effects/legacy/toon.effect.meta | 2 +- editor/assets/effects/particles/builtin-billboard.effect.meta | 2 +- .../assets/effects/particles/builtin-particle-gpu.effect.meta | 2 +- .../assets/effects/particles/builtin-particle-trail.effect.meta | 2 +- .../effects/particles/builtin-particle-xr-trail.effect.meta | 2 +- editor/assets/effects/particles/builtin-particle.effect.meta | 2 +- editor/assets/effects/pipeline/cluster-build.effect.meta | 2 +- editor/assets/effects/pipeline/cluster-culling.effect.meta | 2 +- editor/assets/effects/pipeline/copy-pass.effect.meta | 2 +- editor/assets/effects/pipeline/deferred-lighting.effect.meta | 2 +- editor/assets/effects/pipeline/planar-shadow.effect | 2 +- editor/assets/effects/pipeline/planar-shadow.effect.meta | 2 +- editor/assets/effects/pipeline/post-process.effect.meta | 2 +- .../effects/pipeline/post-process/blit-screen.effect.meta | 2 +- editor/assets/effects/pipeline/post-process/bloom.effect.meta | 2 +- .../effects/pipeline/post-process/color-grading.effect.meta | 2 +- editor/assets/effects/pipeline/post-process/fsr.effect.meta | 2 +- editor/assets/effects/pipeline/post-process/fxaa-hq.effect.meta | 2 +- editor/assets/effects/pipeline/post-process/hbao.effect.meta | 2 +- editor/assets/effects/pipeline/post-process/taa.effect.meta | 2 +- editor/assets/effects/pipeline/skybox.effect.meta | 2 +- editor/assets/effects/pipeline/smaa.effect.meta | 2 +- editor/assets/effects/pipeline/ssss-blur.effect.meta | 2 +- editor/assets/effects/pipeline/tone-mapping.effect.meta | 2 +- editor/assets/effects/pipeline/tonemap.effect.meta | 2 +- editor/assets/effects/util/batched-unlit.effect.meta | 2 +- .../effects/util/dcc/imported-metallic-roughness.effect.meta | 2 +- .../effects/util/dcc/imported-specular-glossiness.effect.meta | 2 +- .../effects/util/dcc/vat/houdini-fluid-v3-liquid.effect.meta | 2 +- .../effects/util/dcc/vat/houdini-rigidbody-v2.effect.meta | 2 +- .../assets/effects/util/dcc/vat/houdini-softbody-v3.effect.meta | 2 +- .../assets/effects/util/dcc/vat/zeno-fluid-liquid.effect.meta | 2 +- editor/assets/effects/util/profiler.effect.meta | 2 +- editor/assets/effects/util/sequence-anim.effect.meta | 2 +- editor/assets/effects/util/splash-screen.effect.meta | 2 +- editor/assets/gizmo/scene-gizmo.mtl.meta | 2 +- editor/assets/primitives.fbx.meta | 2 +- 101 files changed, 101 insertions(+), 101 deletions(-) diff --git a/editor/assets/default_materials/default-billboard-material.mtl.meta b/editor/assets/default_materials/default-billboard-material.mtl.meta index 97c632b971a..30541e5428d 100644 --- a/editor/assets/default_materials/default-billboard-material.mtl.meta +++ b/editor/assets/default_materials/default-billboard-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "78e0584a-4343-4727-8f37-e14e65c2a2db", diff --git a/editor/assets/default_materials/default-clear-stencil.mtl.meta b/editor/assets/default_materials/default-clear-stencil.mtl.meta index 59957ce2d90..eda15d5834f 100644 --- a/editor/assets/default_materials/default-clear-stencil.mtl.meta +++ b/editor/assets/default_materials/default-clear-stencil.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "8bbdbcdd-5cd4-4100-b6d5-b7c9625b6107", diff --git a/editor/assets/default_materials/default-material-transparent.mtl.meta b/editor/assets/default_materials/default-material-transparent.mtl.meta index 3004bebb7e1..b89988be04a 100644 --- a/editor/assets/default_materials/default-material-transparent.mtl.meta +++ b/editor/assets/default_materials/default-material-transparent.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "c31a901b-671b-4c3d-9246-f9a6e5f14b90", diff --git a/editor/assets/default_materials/default-material.mtl.meta b/editor/assets/default_materials/default-material.mtl.meta index 83e5e18ca35..54d86f1c5e2 100644 --- a/editor/assets/default_materials/default-material.mtl.meta +++ b/editor/assets/default_materials/default-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "d3c7820c-2a98-4429-8bc7-b8453bc9ac41", diff --git a/editor/assets/default_materials/default-particle-gpu-material.mtl.meta b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta index 3101eed10c6..26f4857ba72 100644 --- a/editor/assets/default_materials/default-particle-gpu-material.mtl.meta +++ b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "14da1725-c4c2-42b4-ab08-ee0aeb6898b3", diff --git a/editor/assets/default_materials/default-particle-material.mtl.meta b/editor/assets/default_materials/default-particle-material.mtl.meta index 27adeff5d1f..52181681191 100644 --- a/editor/assets/default_materials/default-particle-material.mtl.meta +++ b/editor/assets/default_materials/default-particle-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "c0143906-9aed-447e-9436-2ae8512d1b6e", diff --git a/editor/assets/default_materials/default-spine-material.mtl.meta b/editor/assets/default_materials/default-spine-material.mtl.meta index 239ea622378..28f0270a8ba 100644 --- a/editor/assets/default_materials/default-spine-material.mtl.meta +++ b/editor/assets/default_materials/default-spine-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "b5d6115f-0370-4d7c-aad3-c194cc71cf98", diff --git a/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta index 36d4b1b9d7d..7522338b2a2 100644 --- a/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta +++ b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "ade8a15a-dcca-4b3c-84c6-f6476ac875bb", diff --git a/editor/assets/default_materials/default-trail-material.mtl.meta b/editor/assets/default_materials/default-trail-material.mtl.meta index ca98959efa5..ee024a443cf 100644 --- a/editor/assets/default_materials/default-trail-material.mtl.meta +++ b/editor/assets/default_materials/default-trail-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "081cab31-dccd-428e-8652-f2404cc81c47", diff --git a/editor/assets/default_materials/missing-effect-material.mtl.meta b/editor/assets/default_materials/missing-effect-material.mtl.meta index 0d6c0175c70..357c63d4b56 100644 --- a/editor/assets/default_materials/missing-effect-material.mtl.meta +++ b/editor/assets/default_materials/missing-effect-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "bcd64cc6-2dd9-43f6-abbe-66318d332032", diff --git a/editor/assets/default_materials/missing-material.mtl.meta b/editor/assets/default_materials/missing-material.mtl.meta index c0eca933e1d..21c3cc19eb5 100644 --- a/editor/assets/default_materials/missing-material.mtl.meta +++ b/editor/assets/default_materials/missing-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "d930590d-bb92-4cc8-8bd1-23cd027f9edf", diff --git a/editor/assets/default_materials/particle-add.mtl.meta b/editor/assets/default_materials/particle-add.mtl.meta index f39079d5941..8fc08632bc6 100644 --- a/editor/assets/default_materials/particle-add.mtl.meta +++ b/editor/assets/default_materials/particle-add.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "ea7478b0-408d-4052-b703-f0d2355e095f", diff --git a/editor/assets/default_materials/standard-material.mtl.meta b/editor/assets/default_materials/standard-material.mtl.meta index efa764a77fb..d06873e5eff 100644 --- a/editor/assets/default_materials/standard-material.mtl.meta +++ b/editor/assets/default_materials/standard-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "620b6bf3-0369-4560-837f-2a2c00b73c26", diff --git a/editor/assets/default_materials/ui-alpha-test-material.mtl.meta b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta index 9668081cb8c..b812dc8e877 100644 --- a/editor/assets/default_materials/ui-alpha-test-material.mtl.meta +++ b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "50f4348b-c883-4e2f-8f11-ce233b859fa1", diff --git a/editor/assets/default_materials/ui-base-material.mtl.meta b/editor/assets/default_materials/ui-base-material.mtl.meta index 3868077a162..99ec1144165 100644 --- a/editor/assets/default_materials/ui-base-material.mtl.meta +++ b/editor/assets/default_materials/ui-base-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "e9aa9a3e-5b2b-4ac7-a2c7-073de2b2b24f", diff --git a/editor/assets/default_materials/ui-graphics-material.mtl.meta b/editor/assets/default_materials/ui-graphics-material.mtl.meta index e675d6d4285..2ad1171d01d 100644 --- a/editor/assets/default_materials/ui-graphics-material.mtl.meta +++ b/editor/assets/default_materials/ui-graphics-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "f0416e68-0200-4b77-a926-4f9d16e494da", diff --git a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta index 3daa36ec41a..80b2d330942 100644 --- a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "f92806d7-1768-443f-afe8-12bcde84d0f0", diff --git a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta index bd23e805167..60a7e8ab2d4 100644 --- a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "dd3a144d-ab7f-41f0-82b8-2e43a090d496", diff --git a/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta index 27b4f4eaf2b..5d36041efd4 100644 --- a/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "efe8e2a3-eace-427b-b4f1-cb8a937ec77d", diff --git a/editor/assets/default_materials/ui-sprite-material.mtl.meta b/editor/assets/default_materials/ui-sprite-material.mtl.meta index bbcc1cf1853..2d3d0228aa4 100644 --- a/editor/assets/default_materials/ui-sprite-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "fda095cb-831d-4601-ad94-846013963de8", diff --git a/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta b/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta index c696d8160c3..8dcbb302cd2 100644 --- a/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta +++ b/editor/assets/default_renderpipeline/deferred-lighting.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "016951c5-5a09-4dd0-9bb7-f4958a82d690", diff --git a/editor/assets/default_renderpipeline/post-process.mtl.meta b/editor/assets/default_renderpipeline/post-process.mtl.meta index 9fc995df587..1628fe91995 100644 --- a/editor/assets/default_renderpipeline/post-process.mtl.meta +++ b/editor/assets/default_renderpipeline/post-process.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "85c4d630-c264-4b18-90a4-c52d594e6099", diff --git a/editor/assets/default_renderpipeline/tonemap.mtl.meta b/editor/assets/default_renderpipeline/tonemap.mtl.meta index 544c5e13089..b51062591b9 100644 --- a/editor/assets/default_renderpipeline/tonemap.mtl.meta +++ b/editor/assets/default_renderpipeline/tonemap.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "9d9704d8-08b4-4917-ba47-9d778bc77ac6", diff --git a/editor/assets/default_skybox/default_skybox_reflection_convolution.meta b/editor/assets/default_skybox/default_skybox_reflection_convolution.meta index 2016e16c5c9..830a17f0cea 100644 --- a/editor/assets/default_skybox/default_skybox_reflection_convolution.meta +++ b/editor/assets/default_skybox/default_skybox_reflection_convolution.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.0", + "ver": "1.2.0", "importer": "directory", "imported": true, "uuid": "288581a6-1075-4a1a-adab-f3ed958c9fda", diff --git a/editor/assets/effects/advanced/car-paint.effect.meta b/editor/assets/effects/advanced/car-paint.effect.meta index ab9bcd058f7..261f6eaa239 100644 --- a/editor/assets/effects/advanced/car-paint.effect.meta +++ b/editor/assets/effects/advanced/car-paint.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "304a12db-3955-46e4-b712-e5e26f45258b", diff --git a/editor/assets/effects/advanced/eye.effect.meta b/editor/assets/effects/advanced/eye.effect.meta index 0cd76ea35fb..1275e3af3bb 100644 --- a/editor/assets/effects/advanced/eye.effect.meta +++ b/editor/assets/effects/advanced/eye.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "f0475923-826e-45dc-85cc-b5d9c2b220e9", diff --git a/editor/assets/effects/advanced/glass.effect.meta b/editor/assets/effects/advanced/glass.effect.meta index ff18657e4e4..1e94ce3febe 100644 --- a/editor/assets/effects/advanced/glass.effect.meta +++ b/editor/assets/effects/advanced/glass.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "f288f946-150b-443d-b4b3-0227c5117c93", diff --git a/editor/assets/effects/advanced/hair.effect.meta b/editor/assets/effects/advanced/hair.effect.meta index 38cf30eebe5..1fe7a338d61 100644 --- a/editor/assets/effects/advanced/hair.effect.meta +++ b/editor/assets/effects/advanced/hair.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "fc0ce5f8-063d-42da-b13a-2fad25abb951", diff --git a/editor/assets/effects/advanced/leaf.effect.meta b/editor/assets/effects/advanced/leaf.effect.meta index d068f7e67a9..53ee284b278 100644 --- a/editor/assets/effects/advanced/leaf.effect.meta +++ b/editor/assets/effects/advanced/leaf.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "e396231e-43c6-4547-86f5-0ef92bf154ce", diff --git a/editor/assets/effects/advanced/simple-skin.effect.meta b/editor/assets/effects/advanced/simple-skin.effect.meta index 16cc329e815..081faa26feb 100644 --- a/editor/assets/effects/advanced/simple-skin.effect.meta +++ b/editor/assets/effects/advanced/simple-skin.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "472c676f-9f77-4c8d-b550-17825aa0176b", diff --git a/editor/assets/effects/advanced/skin.effect.meta b/editor/assets/effects/advanced/skin.effect.meta index f222e073b8a..4b803714253 100644 --- a/editor/assets/effects/advanced/skin.effect.meta +++ b/editor/assets/effects/advanced/skin.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "4a31bd46-8da1-4d9a-add5-9ac43967159e", diff --git a/editor/assets/effects/advanced/sky.effect.meta b/editor/assets/effects/advanced/sky.effect.meta index ec88f7c3a6a..ef47fae816b 100644 --- a/editor/assets/effects/advanced/sky.effect.meta +++ b/editor/assets/effects/advanced/sky.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "6308c013-7d49-4160-9516-562dd205b480", diff --git a/editor/assets/effects/advanced/water.effect.meta b/editor/assets/effects/advanced/water.effect.meta index c7b13ba16d4..480554d72cc 100644 --- a/editor/assets/effects/advanced/water.effect.meta +++ b/editor/assets/effects/advanced/water.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "113a72d8-20cd-42cd-ba96-37cc1046971a", diff --git a/editor/assets/effects/builtin-reflection-probe-preview.effect.meta b/editor/assets/effects/builtin-reflection-probe-preview.effect.meta index c540294993a..065dc24e40c 100644 --- a/editor/assets/effects/builtin-reflection-probe-preview.effect.meta +++ b/editor/assets/effects/builtin-reflection-probe-preview.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "fe0128c2-5496-4330-880a-cfee413aabf2", diff --git a/editor/assets/effects/builtin-standard.effect.meta b/editor/assets/effects/builtin-standard.effect.meta index 6a8c6858b2d..5717fdff49e 100644 --- a/editor/assets/effects/builtin-standard.effect.meta +++ b/editor/assets/effects/builtin-standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "c8f66d17-351a-48da-a12c-0212d28575c4", diff --git a/editor/assets/effects/builtin-terrain.effect.meta b/editor/assets/effects/builtin-terrain.effect.meta index 2c8b10dbf75..75853fa4b44 100644 --- a/editor/assets/effects/builtin-terrain.effect.meta +++ b/editor/assets/effects/builtin-terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "a0fd9f76-74fe-423c-92d9-298906c189ba", diff --git a/editor/assets/effects/builtin-toon.effect.meta b/editor/assets/effects/builtin-toon.effect.meta index cfb5f3d8347..226200a8666 100644 --- a/editor/assets/effects/builtin-toon.effect.meta +++ b/editor/assets/effects/builtin-toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "9b20a514-6cc3-49de-b216-b6b863046249", diff --git a/editor/assets/effects/builtin-unlit.effect b/editor/assets/effects/builtin-unlit.effect index 66dd4e82a30..9e66463f93e 100644 --- a/editor/assets/effects/builtin-unlit.effect +++ b/editor/assets/effects/builtin-unlit.effect @@ -224,7 +224,7 @@ CCProgram planar-shadow-vs %{ CCGetWorldMatrixFull(matWorld, matWorldIT); vec3 worldPos = (matWorld * position).xyz; vec4 shadowPos = CalculatePlanarShadowPos(worldPos, cc_cameraPos.xyz, cc_mainLitDir.xyz, cc_planarNDInfo); - position = cc_matProj * cc_matView * vec4(shadowPos.xyz, 1.0); + position = CalculatePlanarShadowClipPos(shadowPos, cc_cameraPos.xyz, cc_matView, cc_matProj, cc_nearFar); v_dist = shadowPos.w; return position; } diff --git a/editor/assets/effects/builtin-unlit.effect.meta b/editor/assets/effects/builtin-unlit.effect.meta index 2fe2e7bace7..0ca98bd11a9 100644 --- a/editor/assets/effects/builtin-unlit.effect.meta +++ b/editor/assets/effects/builtin-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", diff --git a/editor/assets/effects/for2d/builtin-spine.effect.meta b/editor/assets/effects/for2d/builtin-spine.effect.meta index fc9e2eb9b3e..8ad4cf39924 100644 --- a/editor/assets/effects/for2d/builtin-spine.effect.meta +++ b/editor/assets/effects/for2d/builtin-spine.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "c27215d8-6835-4b68-bfbb-bdeac6100c04", diff --git a/editor/assets/effects/for2d/builtin-sprite-renderer.effect.meta b/editor/assets/effects/for2d/builtin-sprite-renderer.effect.meta index b8f6101904c..33d4405da8c 100644 --- a/editor/assets/effects/for2d/builtin-sprite-renderer.effect.meta +++ b/editor/assets/effects/for2d/builtin-sprite-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "6ef1defe-7997-477a-9b35-c18859ff8066", diff --git a/editor/assets/effects/for2d/builtin-sprite.effect.meta b/editor/assets/effects/for2d/builtin-sprite.effect.meta index 527f83b57bc..fe4f27599eb 100644 --- a/editor/assets/effects/for2d/builtin-sprite.effect.meta +++ b/editor/assets/effects/for2d/builtin-sprite.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", diff --git a/editor/assets/effects/internal/builtin-camera-texture.effect.meta b/editor/assets/effects/internal/builtin-camera-texture.effect.meta index e09762d7403..da163a0e0cf 100644 --- a/editor/assets/effects/internal/builtin-camera-texture.effect.meta +++ b/editor/assets/effects/internal/builtin-camera-texture.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "bf4078d6-d2d7-4073-83bb-cd6f1802e880", diff --git a/editor/assets/effects/internal/builtin-clear-stencil.effect.meta b/editor/assets/effects/internal/builtin-clear-stencil.effect.meta index f63a690ac8b..1d837e5d023 100644 --- a/editor/assets/effects/internal/builtin-clear-stencil.effect.meta +++ b/editor/assets/effects/internal/builtin-clear-stencil.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "810e96e4-e456-4468-9b59-f4e8f39732c0", diff --git a/editor/assets/effects/internal/builtin-debug-renderer.effect.meta b/editor/assets/effects/internal/builtin-debug-renderer.effect.meta index 700e4b98ec1..326701e50ae 100644 --- a/editor/assets/effects/internal/builtin-debug-renderer.effect.meta +++ b/editor/assets/effects/internal/builtin-debug-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "ff9be190-20a4-4e48-b68c-76e3c7cff085", diff --git a/editor/assets/effects/internal/builtin-geometry-renderer.effect.meta b/editor/assets/effects/internal/builtin-geometry-renderer.effect.meta index 844ce9422c8..433fc41b8a9 100644 --- a/editor/assets/effects/internal/builtin-geometry-renderer.effect.meta +++ b/editor/assets/effects/internal/builtin-geometry-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "4bb480dd-8384-4bc9-987f-de67cc53052a", diff --git a/editor/assets/effects/internal/builtin-graphics.effect.meta b/editor/assets/effects/internal/builtin-graphics.effect.meta index 97829cf794d..a3cf5c552e4 100644 --- a/editor/assets/effects/internal/builtin-graphics.effect.meta +++ b/editor/assets/effects/internal/builtin-graphics.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", diff --git a/editor/assets/effects/internal/builtin-occlusion-query.effect.meta b/editor/assets/effects/internal/builtin-occlusion-query.effect.meta index a955dc72385..8c8af2eb664 100644 --- a/editor/assets/effects/internal/builtin-occlusion-query.effect.meta +++ b/editor/assets/effects/internal/builtin-occlusion-query.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "d9937e59-61fe-4ec6-92ab-7ac5a19c89b0", diff --git a/editor/assets/effects/internal/builtin-reflection-deferred.effect.meta b/editor/assets/effects/internal/builtin-reflection-deferred.effect.meta index 7d6e2989c6c..672651d87a5 100644 --- a/editor/assets/effects/internal/builtin-reflection-deferred.effect.meta +++ b/editor/assets/effects/internal/builtin-reflection-deferred.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "99498f84-efe6-43a6-a9a7-e6e93eb845c1", diff --git a/editor/assets/effects/internal/builtin-wireframe.effect.meta b/editor/assets/effects/internal/builtin-wireframe.effect.meta index aed6bcd53ed..eeeb9db3123 100644 --- a/editor/assets/effects/internal/builtin-wireframe.effect.meta +++ b/editor/assets/effects/internal/builtin-wireframe.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "81127eb0-7556-453c-b147-670782dd5e53", diff --git a/editor/assets/effects/internal/editor/box-height-light.effect.meta b/editor/assets/effects/internal/editor/box-height-light.effect.meta index 199ad0f4633..b263688f2f1 100644 --- a/editor/assets/effects/internal/editor/box-height-light.effect.meta +++ b/editor/assets/effects/internal/editor/box-height-light.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "084eba38-5336-4444-8c8c-aebb75d5c627", diff --git a/editor/assets/effects/internal/editor/gizmo.effect.meta b/editor/assets/effects/internal/editor/gizmo.effect.meta index 0278556eb7e..940b8cd97c1 100644 --- a/editor/assets/effects/internal/editor/gizmo.effect.meta +++ b/editor/assets/effects/internal/editor/gizmo.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "9d6c6bde-2fe2-44ee-883b-909608948b04", diff --git a/editor/assets/effects/internal/editor/grid-2d.effect.meta b/editor/assets/effects/internal/editor/grid-2d.effect.meta index bba39239f35..26fbab581cb 100644 --- a/editor/assets/effects/internal/editor/grid-2d.effect.meta +++ b/editor/assets/effects/internal/editor/grid-2d.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "cb2c332a-fa5e-4235-a129-f011634bb7ad", diff --git a/editor/assets/effects/internal/editor/grid-stroke.effect.meta b/editor/assets/effects/internal/editor/grid-stroke.effect.meta index c2d9b0d7380..0987e8da4e0 100644 --- a/editor/assets/effects/internal/editor/grid-stroke.effect.meta +++ b/editor/assets/effects/internal/editor/grid-stroke.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "4736e978-c8fa-449f-9cf6-fe0158ded9d7", diff --git a/editor/assets/effects/internal/editor/grid.effect.meta b/editor/assets/effects/internal/editor/grid.effect.meta index a9cef638460..a6cf0c3ca28 100644 --- a/editor/assets/effects/internal/editor/grid.effect.meta +++ b/editor/assets/effects/internal/editor/grid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "ba35f02e-a81c-464c-bfc5-c788328da667", diff --git a/editor/assets/effects/internal/editor/light-probe-visualization.effect.meta b/editor/assets/effects/internal/editor/light-probe-visualization.effect.meta index 4fe7da93955..9a64267f86a 100644 --- a/editor/assets/effects/internal/editor/light-probe-visualization.effect.meta +++ b/editor/assets/effects/internal/editor/light-probe-visualization.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "5967a800-25ad-4c00-9872-5c4ba7840d17", diff --git a/editor/assets/effects/internal/editor/light.effect.meta b/editor/assets/effects/internal/editor/light.effect.meta index d3ebdc13e52..f3c52d329da 100644 --- a/editor/assets/effects/internal/editor/light.effect.meta +++ b/editor/assets/effects/internal/editor/light.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "e4e4cb19-8dd2-450d-ad20-1a818263b8d3", diff --git a/editor/assets/effects/internal/editor/terrain-circle-brush.effect.meta b/editor/assets/effects/internal/editor/terrain-circle-brush.effect.meta index c7c10c39060..6c30fa011fb 100644 --- a/editor/assets/effects/internal/editor/terrain-circle-brush.effect.meta +++ b/editor/assets/effects/internal/editor/terrain-circle-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "a3e72674-c38f-4336-a285-1826b1799cd7", diff --git a/editor/assets/effects/internal/editor/terrain-image-brush.effect.meta b/editor/assets/effects/internal/editor/terrain-image-brush.effect.meta index 3eb7cb6e671..08fc24c3bcc 100644 --- a/editor/assets/effects/internal/editor/terrain-image-brush.effect.meta +++ b/editor/assets/effects/internal/editor/terrain-image-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "7a115de7-2d94-4620-8b89-766d7f8cbff9", diff --git a/editor/assets/effects/internal/editor/terrain-select-brush.effect.meta b/editor/assets/effects/internal/editor/terrain-select-brush.effect.meta index 91b9d23d7ce..c3a4cc82895 100644 --- a/editor/assets/effects/internal/editor/terrain-select-brush.effect.meta +++ b/editor/assets/effects/internal/editor/terrain-select-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "9b4d3fa5-89bf-4715-b69a-dbbd1efaf6a5", diff --git a/editor/assets/effects/legacy/standard.effect b/editor/assets/effects/legacy/standard.effect index 27a0f682fad..1fb84c73d7e 100644 --- a/editor/assets/effects/legacy/standard.effect +++ b/editor/assets/effects/legacy/standard.effect @@ -479,7 +479,7 @@ CCProgram planar-shadow-vs %{ CCGetWorldMatrixFull(matWorld, matWorldIT); vec3 worldPos = (matWorld * position).xyz; vec4 shadowPos = CalculatePlanarShadowPos(worldPos, cc_cameraPos.xyz, cc_mainLitDir.xyz, cc_planarNDInfo); - position = cc_matProj * cc_matView * vec4(shadowPos.xyz, 1.0); + position = CalculatePlanarShadowClipPos(shadowPos, cc_cameraPos.xyz, cc_matView, cc_matProj, cc_nearFar); v_dist = shadowPos.w; return position; } diff --git a/editor/assets/effects/legacy/standard.effect.meta b/editor/assets/effects/legacy/standard.effect.meta index e0859a963c1..0ba8e3ebf40 100644 --- a/editor/assets/effects/legacy/standard.effect.meta +++ b/editor/assets/effects/legacy/standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "1baf0fc9-befa-459c-8bdd-af1a450a0319", diff --git a/editor/assets/effects/legacy/terrain.effect.meta b/editor/assets/effects/legacy/terrain.effect.meta index 887ba0738d1..d6c8fb4b9d0 100644 --- a/editor/assets/effects/legacy/terrain.effect.meta +++ b/editor/assets/effects/legacy/terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "1d08ef62-a503-4ce2-8b9a-46c90873f7d3", diff --git a/editor/assets/effects/legacy/toon.effect b/editor/assets/effects/legacy/toon.effect index 8b17d1f90bc..bb675a2c08a 100644 --- a/editor/assets/effects/legacy/toon.effect +++ b/editor/assets/effects/legacy/toon.effect @@ -383,7 +383,7 @@ CCProgram planar-shadow-vs %{ CCGetWorldMatrixFull(matWorld, matWorldIT); vec3 worldPos = (matWorld * position).xyz; vec4 shadowPos = CalculatePlanarShadowPos(worldPos, cc_cameraPos.xyz, cc_mainLitDir.xyz, cc_planarNDInfo); - position = cc_matProj * cc_matView * vec4(shadowPos.xyz, 1.0); + position = CalculatePlanarShadowClipPos(shadowPos, cc_cameraPos.xyz, cc_matView, cc_matProj, cc_nearFar); v_dist = shadowPos.w; return position; } diff --git a/editor/assets/effects/legacy/toon.effect.meta b/editor/assets/effects/legacy/toon.effect.meta index d270abbe2f3..9d0f3cc5a99 100644 --- a/editor/assets/effects/legacy/toon.effect.meta +++ b/editor/assets/effects/legacy/toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "a7612b54-35e3-4238-a1a9-4a7b54635839", diff --git a/editor/assets/effects/particles/builtin-billboard.effect.meta b/editor/assets/effects/particles/builtin-billboard.effect.meta index b90611a1b7e..b6a07c4cdf1 100644 --- a/editor/assets/effects/particles/builtin-billboard.effect.meta +++ b/editor/assets/effects/particles/builtin-billboard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "711ebe11-f673-4cd9-9a83-63c60ba54c5b", diff --git a/editor/assets/effects/particles/builtin-particle-gpu.effect.meta b/editor/assets/effects/particles/builtin-particle-gpu.effect.meta index 24d7bd9355f..be38363be70 100644 --- a/editor/assets/effects/particles/builtin-particle-gpu.effect.meta +++ b/editor/assets/effects/particles/builtin-particle-gpu.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "971bdb23-3ff6-43eb-b422-1c30165a3663", diff --git a/editor/assets/effects/particles/builtin-particle-trail.effect.meta b/editor/assets/effects/particles/builtin-particle-trail.effect.meta index 1c14836fe56..a08422c7d43 100644 --- a/editor/assets/effects/particles/builtin-particle-trail.effect.meta +++ b/editor/assets/effects/particles/builtin-particle-trail.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "17debcc3-0a6b-4b8a-b00b-dc58b885581e", diff --git a/editor/assets/effects/particles/builtin-particle-xr-trail.effect.meta b/editor/assets/effects/particles/builtin-particle-xr-trail.effect.meta index 1826d5b599e..560e8501fea 100644 --- a/editor/assets/effects/particles/builtin-particle-xr-trail.effect.meta +++ b/editor/assets/effects/particles/builtin-particle-xr-trail.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "e38f81af-70ec-4f7a-b377-767b0ec76377", diff --git a/editor/assets/effects/particles/builtin-particle.effect.meta b/editor/assets/effects/particles/builtin-particle.effect.meta index 5d9e53d8b11..b6087c80a3e 100644 --- a/editor/assets/effects/particles/builtin-particle.effect.meta +++ b/editor/assets/effects/particles/builtin-particle.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "d1346436-ac96-4271-b863-1f4fdead95b0", diff --git a/editor/assets/effects/pipeline/cluster-build.effect.meta b/editor/assets/effects/pipeline/cluster-build.effect.meta index 9a260f92272..3cc9bff3bad 100644 --- a/editor/assets/effects/pipeline/cluster-build.effect.meta +++ b/editor/assets/effects/pipeline/cluster-build.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "45e7c0c8-2699-4912-b45f-d42bb8384189", diff --git a/editor/assets/effects/pipeline/cluster-culling.effect.meta b/editor/assets/effects/pipeline/cluster-culling.effect.meta index 443cf29b85b..5d8158f41f9 100644 --- a/editor/assets/effects/pipeline/cluster-culling.effect.meta +++ b/editor/assets/effects/pipeline/cluster-culling.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "84ac6f69-3086-455a-86a4-561da8ee710b", diff --git a/editor/assets/effects/pipeline/copy-pass.effect.meta b/editor/assets/effects/pipeline/copy-pass.effect.meta index d7d899473cf..3bbb41e6a83 100644 --- a/editor/assets/effects/pipeline/copy-pass.effect.meta +++ b/editor/assets/effects/pipeline/copy-pass.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "5c601d96-e4c7-4698-991b-7ee674b11079", diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect.meta b/editor/assets/effects/pipeline/deferred-lighting.effect.meta index 4a8108c5bcd..c86dad44813 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect.meta +++ b/editor/assets/effects/pipeline/deferred-lighting.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "5d45aa00-e064-4938-b314-4265f0c2258c", diff --git a/editor/assets/effects/pipeline/planar-shadow.effect b/editor/assets/effects/pipeline/planar-shadow.effect index 37dfa15ff43..6d2d2ab39b8 100644 --- a/editor/assets/effects/pipeline/planar-shadow.effect +++ b/editor/assets/effects/pipeline/planar-shadow.effect @@ -42,7 +42,7 @@ CCProgram planar-shadow-vs %{ CCGetWorldMatrixFull(matWorld, matWorldIT); vec3 worldPos = (matWorld * position).xyz; vec4 shadowPos = CalculatePlanarShadowPos(worldPos, cc_cameraPos.xyz, cc_mainLitDir.xyz, cc_planarNDInfo); - position = cc_matProj * cc_matView * vec4(shadowPos.xyz, 1.0); + position = CalculatePlanarShadowClipPos(shadowPos, cc_cameraPos.xyz, cc_matView, cc_matProj, cc_nearFar); v_dist = shadowPos.w; return position; } diff --git a/editor/assets/effects/pipeline/planar-shadow.effect.meta b/editor/assets/effects/pipeline/planar-shadow.effect.meta index 46c48545665..b251f4fa0f5 100644 --- a/editor/assets/effects/pipeline/planar-shadow.effect.meta +++ b/editor/assets/effects/pipeline/planar-shadow.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "9361fd90-ba52-4f84-aa93-6e878fd576ca", diff --git a/editor/assets/effects/pipeline/post-process.effect.meta b/editor/assets/effects/pipeline/post-process.effect.meta index e0a6d9bb789..bc3a945662a 100644 --- a/editor/assets/effects/pipeline/post-process.effect.meta +++ b/editor/assets/effects/pipeline/post-process.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "ec8106fe-05bf-4e94-943c-e0d3b7bb5e45", diff --git a/editor/assets/effects/pipeline/post-process/blit-screen.effect.meta b/editor/assets/effects/pipeline/post-process/blit-screen.effect.meta index b4eff22bd22..27b29250e2a 100644 --- a/editor/assets/effects/pipeline/post-process/blit-screen.effect.meta +++ b/editor/assets/effects/pipeline/post-process/blit-screen.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "15049ccd-4dd7-451e-a8ae-af66735c929e", diff --git a/editor/assets/effects/pipeline/post-process/bloom.effect.meta b/editor/assets/effects/pipeline/post-process/bloom.effect.meta index 0c686db6ff8..458a21e4b56 100644 --- a/editor/assets/effects/pipeline/post-process/bloom.effect.meta +++ b/editor/assets/effects/pipeline/post-process/bloom.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", diff --git a/editor/assets/effects/pipeline/post-process/color-grading.effect.meta b/editor/assets/effects/pipeline/post-process/color-grading.effect.meta index 9d139cfe59d..0b4c6ba983d 100644 --- a/editor/assets/effects/pipeline/post-process/color-grading.effect.meta +++ b/editor/assets/effects/pipeline/post-process/color-grading.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "cafd95c9-c558-46f9-9812-1224b65c09ee", diff --git a/editor/assets/effects/pipeline/post-process/fsr.effect.meta b/editor/assets/effects/pipeline/post-process/fsr.effect.meta index 267b7c5e580..df5e6864a0e 100644 --- a/editor/assets/effects/pipeline/post-process/fsr.effect.meta +++ b/editor/assets/effects/pipeline/post-process/fsr.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "4361db28-3f24-44cc-8e51-32ee5fd651ac", diff --git a/editor/assets/effects/pipeline/post-process/fxaa-hq.effect.meta b/editor/assets/effects/pipeline/post-process/fxaa-hq.effect.meta index 7c27ed1bb51..9a77b5d4ee6 100644 --- a/editor/assets/effects/pipeline/post-process/fxaa-hq.effect.meta +++ b/editor/assets/effects/pipeline/post-process/fxaa-hq.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "2df0a40b-26c2-47ce-be0d-4d3cd4164737", diff --git a/editor/assets/effects/pipeline/post-process/hbao.effect.meta b/editor/assets/effects/pipeline/post-process/hbao.effect.meta index ac5960d2983..6fc26e66b8c 100644 --- a/editor/assets/effects/pipeline/post-process/hbao.effect.meta +++ b/editor/assets/effects/pipeline/post-process/hbao.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "dace6a58-1705-48c7-a275-70afc9534e88", diff --git a/editor/assets/effects/pipeline/post-process/taa.effect.meta b/editor/assets/effects/pipeline/post-process/taa.effect.meta index 39dc8c8f33a..d832336b57f 100644 --- a/editor/assets/effects/pipeline/post-process/taa.effect.meta +++ b/editor/assets/effects/pipeline/post-process/taa.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "4c3ce6de-e6d1-47f7-aa36-36b9b58f72d3", diff --git a/editor/assets/effects/pipeline/skybox.effect.meta b/editor/assets/effects/pipeline/skybox.effect.meta index d49387be035..56d743815e5 100644 --- a/editor/assets/effects/pipeline/skybox.effect.meta +++ b/editor/assets/effects/pipeline/skybox.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "511d2633-09a7-4bdd-ac42-f778032124b3", diff --git a/editor/assets/effects/pipeline/smaa.effect.meta b/editor/assets/effects/pipeline/smaa.effect.meta index b5c86ff2f42..435be92966b 100644 --- a/editor/assets/effects/pipeline/smaa.effect.meta +++ b/editor/assets/effects/pipeline/smaa.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "6624c63c-0e3d-4d5f-bd15-a7805b71c521", diff --git a/editor/assets/effects/pipeline/ssss-blur.effect.meta b/editor/assets/effects/pipeline/ssss-blur.effect.meta index a825e8b98f6..6f889822566 100644 --- a/editor/assets/effects/pipeline/ssss-blur.effect.meta +++ b/editor/assets/effects/pipeline/ssss-blur.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "39f74202-ead5-4a45-b966-273d526adbf1", diff --git a/editor/assets/effects/pipeline/tone-mapping.effect.meta b/editor/assets/effects/pipeline/tone-mapping.effect.meta index 4d1ff515a04..d4014bb3990 100644 --- a/editor/assets/effects/pipeline/tone-mapping.effect.meta +++ b/editor/assets/effects/pipeline/tone-mapping.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "8f6ac413-2f1e-4b88-b26f-54556b5dd510", diff --git a/editor/assets/effects/pipeline/tonemap.effect.meta b/editor/assets/effects/pipeline/tonemap.effect.meta index 4412f06b567..b003a872005 100644 --- a/editor/assets/effects/pipeline/tonemap.effect.meta +++ b/editor/assets/effects/pipeline/tonemap.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "31b152ff-f689-4082-a292-3eb5a0b33014", diff --git a/editor/assets/effects/util/batched-unlit.effect.meta b/editor/assets/effects/util/batched-unlit.effect.meta index ad474d50d27..c13466188c7 100644 --- a/editor/assets/effects/util/batched-unlit.effect.meta +++ b/editor/assets/effects/util/batched-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "f1556893-88b6-4c65-8c16-a5256ef3ad25", diff --git a/editor/assets/effects/util/dcc/imported-metallic-roughness.effect.meta b/editor/assets/effects/util/dcc/imported-metallic-roughness.effect.meta index 6bd413e7466..f23a325ce8f 100644 --- a/editor/assets/effects/util/dcc/imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/util/dcc/imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "2ec11458-f855-4978-b14d-f3ed5cf697fa", diff --git a/editor/assets/effects/util/dcc/imported-specular-glossiness.effect.meta b/editor/assets/effects/util/dcc/imported-specular-glossiness.effect.meta index cb060f0b106..a9bec6e8556 100644 --- a/editor/assets/effects/util/dcc/imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/util/dcc/imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "f648964e-8d32-41fc-9ac9-7a1e714dd17b", diff --git a/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect.meta b/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect.meta index 9adc94f3cc3..dee128e9120 100644 --- a/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect.meta +++ b/editor/assets/effects/util/dcc/vat/houdini-fluid-v3-liquid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "fbc18e4a-ab74-48df-9106-38e7bd10ff25", diff --git a/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect.meta b/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect.meta index 1040e10497f..d1ea97c6589 100644 --- a/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect.meta +++ b/editor/assets/effects/util/dcc/vat/houdini-rigidbody-v2.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "08c6d756-c02f-48a2-9e8a-55ec59a8f83d", diff --git a/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect.meta b/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect.meta index ad98ce231d4..8645d9592ad 100644 --- a/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect.meta +++ b/editor/assets/effects/util/dcc/vat/houdini-softbody-v3.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "c3e70c74-2523-40e6-a4e5-4abfa1849608", diff --git a/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect.meta b/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect.meta index 49113370890..18b94dd71a7 100644 --- a/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect.meta +++ b/editor/assets/effects/util/dcc/vat/zeno-fluid-liquid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "6ce2c98a-5c87-4066-90aa-7be93bcbb738", diff --git a/editor/assets/effects/util/profiler.effect.meta b/editor/assets/effects/util/profiler.effect.meta index 1133058bc04..aeb1326938d 100644 --- a/editor/assets/effects/util/profiler.effect.meta +++ b/editor/assets/effects/util/profiler.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "871c3b6c-7379-419d-bda3-794b239ab90d", diff --git a/editor/assets/effects/util/sequence-anim.effect.meta b/editor/assets/effects/util/sequence-anim.effect.meta index d679d0649dd..55a1c59f7e4 100644 --- a/editor/assets/effects/util/sequence-anim.effect.meta +++ b/editor/assets/effects/util/sequence-anim.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "27cc5a0b-ec0b-4a67-98cf-b42d4fa971de", diff --git a/editor/assets/effects/util/splash-screen.effect.meta b/editor/assets/effects/util/splash-screen.effect.meta index 673fdd2f0b4..66f9a7021ed 100644 --- a/editor/assets/effects/util/splash-screen.effect.meta +++ b/editor/assets/effects/util/splash-screen.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.7.0", + "ver": "1.7.1", "importer": "effect", "imported": true, "uuid": "970b0598-bcb0-4714-91fb-2e81440dccd8", diff --git a/editor/assets/gizmo/scene-gizmo.mtl.meta b/editor/assets/gizmo/scene-gizmo.mtl.meta index fc18a472abd..f3b08a2958c 100644 --- a/editor/assets/gizmo/scene-gizmo.mtl.meta +++ b/editor/assets/gizmo/scene-gizmo.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.20", + "ver": "1.0.21", "importer": "material", "imported": true, "uuid": "6d3bfb1f-604a-4fb3-9fd8-789862cc55e7", diff --git a/editor/assets/primitives.fbx.meta b/editor/assets/primitives.fbx.meta index 5221ff981fc..d749817046b 100644 --- a/editor/assets/primitives.fbx.meta +++ b/editor/assets/primitives.fbx.meta @@ -171,7 +171,7 @@ "displayName": "", "id": "aae0f", "name": "primitives.prefab", - "ver": "1.0.13", + "ver": "1.0.14", "imported": true, "files": [ ".json" From 6b8009561e9d5ab301ab12c68647d12c9986959a Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Thu, 10 Aug 2023 17:06:53 +0800 Subject: [PATCH 123/232] refine: erase unneed audio operation & fix potential bug (#15884) * refine: erase unneeded audio operation & fix some potential bug --- cocos/audio/audio-source.ts | 67 ++++++++++++++++++++------- pal/audio/minigame/player-minigame.ts | 25 ++++++++-- pal/audio/operation-queue.ts | 36 +++++++++++++- 3 files changed, 106 insertions(+), 22 deletions(-) diff --git a/cocos/audio/audio-source.ts b/cocos/audio/audio-source.ts index 07f35a44f39..6627ad45353 100644 --- a/cocos/audio/audio-source.ts +++ b/cocos/audio/audio-source.ts @@ -38,6 +38,18 @@ enum AudioSourceEventType { ENDED = 'ended', } +enum AudioOperationType { + PLAY = 'play', + STOP = 'stop', + PAUSE = 'pause', + SEEK = 'seek' +} + +interface AudioOperationInfo { + op: AudioOperationType; + params: any[] | null; +} + /** * @en * A representation of a single audio source,
@@ -68,10 +80,10 @@ export class AudioSource extends Component { @serializable protected _volume = 1; - private _cachedCurrentTime = 0; + private _cachedCurrentTime = -1; // An operation queue to store the operations before loading the AudioPlayer. - private _operationsBeforeLoading: string[] = []; + private _operationsBeforeLoading: AudioOperationInfo[] = []; private _isLoaded = false; private _lastSetClip: AudioClip | null = null; @@ -113,6 +125,7 @@ export class AudioSource extends Component { return; } if (!clip._nativeAsset) { + // eslint-disable-next-line no-console console.error('Invalid audio clip'); return; } @@ -138,6 +151,7 @@ export class AudioSource extends Component { this._player = player; this._syncStates(); this.node?.emit(_LOADED_EVENT); + // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch((e) => {}); } @@ -178,7 +192,9 @@ export class AudioSource extends Component { @tooltip('i18n:audio.loop') set loop (val) { this._loop = val; - this._player && (this._player.loop = val); + if (this._player) { + this._player.loop = val; + } } get loop (): boolean { return this._loop; @@ -214,6 +230,7 @@ export class AudioSource extends Component { @range([0.0, 1.0]) @tooltip('i18n:audio.volume') set volume (val) { + // eslint-disable-next-line no-console if (Number.isNaN(val)) { console.warn('illegal audio volume!'); return; } val = clamp(val, 0, 1); if (this._player) { @@ -275,6 +292,7 @@ export class AudioSource extends Component { public getPCMData (channelIndex: number): Promise { return new Promise((resolve) => { if (channelIndex !== 0 && channelIndex !== 1) { + // eslint-disable-next-line no-console console.warn('Only support channel index 0 or 1 to get buffer'); resolve(undefined); return; @@ -345,13 +363,14 @@ export class AudioSource extends Component { */ public play (): void { if (!this._isLoaded && this.clip) { - this._operationsBeforeLoading.push('play'); + this._operationsBeforeLoading.push({ op: AudioOperationType.PLAY, params: null }); return; } this._registerListener(); audioManager.discardOnePlayingIfNeeded(); // Replay if the audio is playing if (this.state === AudioState.PLAYING) { + // eslint-disable-next-line @typescript-eslint/no-empty-function this._player?.stop().catch((e) => {}); } const player = this._player; @@ -373,9 +392,10 @@ export class AudioSource extends Component { */ public pause (): void { if (!this._isLoaded && this.clip) { - this._operationsBeforeLoading.push('pause'); + this._operationsBeforeLoading.push({ op: AudioOperationType.PAUSE, params: null }); return; } + // eslint-disable-next-line @typescript-eslint/no-empty-function this._player?.pause().catch((e) => {}); } @@ -387,10 +407,11 @@ export class AudioSource extends Component { */ public stop (): void { if (!this._isLoaded && this.clip) { - this._operationsBeforeLoading.push('stop'); + this._operationsBeforeLoading.push({ op: AudioOperationType.STOP, params: null }); return; } if (this._player) { + // eslint-disable-next-line @typescript-eslint/no-empty-function this._player.stop().catch((e) => {}); audioManager.removePlaying(this._player); } @@ -406,6 +427,7 @@ export class AudioSource extends Component { */ public playOneShot (clip: AudioClip, volumeScale = 1): void { if (!clip._nativeAsset) { + // eslint-disable-next-line no-console console.error('Invalid audio clip'); return; } @@ -428,15 +450,22 @@ export class AudioSource extends Component { } protected _syncStates (): void { - if (!this._player) { return; } - this._player.seek(this._cachedCurrentTime).then((): void => { - if (this._player) { - this._player.loop = this._loop; - this._player.volume = this._volume; - this._operationsBeforeLoading.forEach((opName): void => { this[opName]?.(); }); - this._operationsBeforeLoading.length = 0; - } - }).catch((e): void => {}); + if (this._player) { + this._player.loop = this._loop; + this._player.volume = this._volume; + this._operationsBeforeLoading.forEach((opInfo): void => { + if (opInfo.op === AudioOperationType.SEEK) { + this._cachedCurrentTime = (opInfo.params && opInfo.params[0]) as number; + if (this._player) { + // eslint-disable-next-line @typescript-eslint/no-empty-function + this._player.seek(this._cachedCurrentTime).catch((e): void => {}); + } + } else { + this[opInfo.op]?.(); + } + }); + this._operationsBeforeLoading.length = 0; + } } /** @@ -447,9 +476,15 @@ export class AudioSource extends Component { * @param num playback time to jump to. */ set currentTime (num: number) { + // eslint-disable-next-line no-console if (Number.isNaN(num)) { console.warn('illegal audio time!'); return; } num = clamp(num, 0, this.duration); + if (!this._isLoaded && this.clip) { + this._operationsBeforeLoading.push({ op: AudioOperationType.SEEK, params: [num] }); + return; + } this._cachedCurrentTime = num; + // eslint-disable-next-line @typescript-eslint/no-empty-function this._player?.seek(this._cachedCurrentTime).catch((e): void => {}); } @@ -460,7 +495,7 @@ export class AudioSource extends Component { * 以秒为单位获取当前播放时间。 */ get currentTime (): number { - return this._player ? this._player.currentTime : this._cachedCurrentTime; + return this._player ? this._player.currentTime : (this._cachedCurrentTime < 0 ? 0 : this._cachedCurrentTime); } /** diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index e363567f403..d2f81712c3f 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -129,6 +129,7 @@ export class AudioPlayerMinigame implements OperationQueueable { this._state = AudioState.PLAYING; eventTarget.emit(AudioEvent.PLAYED); if (this._needSeek) { + // eslint-disable-next-line @typescript-eslint/no-empty-function this.seek(this._cacheTime).catch((e) => {}); } }; @@ -168,6 +169,7 @@ export class AudioPlayerMinigame implements OperationQueueable { if (this._needSeek) { this._needSeek = false; if (this._cacheTime.toFixed(3) !== this._innerAudioContext.currentTime.toFixed(3)) { + // eslint-disable-next-line @typescript-eslint/no-empty-function this.seek(this._cacheTime).catch((e) => {}); } else { this._needSeek = false; @@ -189,7 +191,7 @@ export class AudioPlayerMinigame implements OperationQueueable { ['Play', 'Pause', 'Stop', 'Seeked', 'Ended'].forEach((event) => { this._offEvent(event); }); - // NOTE: innewAudioContext might not stop the audio playing, have to call it explicitly. + // NOTE: innerAudioContext might not stop the audio playing, have to call it explicitly. this._innerAudioContext.stop(); this._innerAudioContext.destroy(); // NOTE: Type 'null' is not assignable to type 'InnerAudioContext' @@ -202,6 +204,7 @@ export class AudioPlayerMinigame implements OperationQueueable { this._state = AudioState.INTERRUPTED; this._readyToHandleOnShow = true; this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN); + // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch((e) => {}); } } @@ -214,6 +217,7 @@ export class AudioPlayerMinigame implements OperationQueueable { if (this._state === AudioState.INTERRUPTED) { this.play().then(() => { this._eventTarget.emit(AudioEvent.INTERRUPTION_END); + // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch((e) => {}); } this._readyToHandleOnShow = false; @@ -235,6 +239,7 @@ export class AudioPlayerMinigame implements OperationQueueable { return new Promise((resolve) => { AudioPlayerMinigame.loadNative(url).then((innerAudioContext) => { resolve(new AudioPlayerMinigame(innerAudioContext as InnerAudioContext)); + // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch((e) => {}); }); } @@ -259,6 +264,7 @@ export class AudioPlayerMinigame implements OperationQueueable { clearTimeout(timer); // eslint-disable-next-line no-console console.error('failed to load innerAudioContext'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument reject(new Error(err)); } innerAudioContext.onCanplay(success); @@ -270,6 +276,7 @@ export class AudioPlayerMinigame implements OperationQueueable { return new Promise((resolve, reject) => { AudioPlayerMinigame.loadNative(url).then((innerAudioContext) => { // HACK: AudioPlayer should be a friend class in OneShotAudio + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument resolve(new (OneShotAudioMinigame as any)(innerAudioContext, volume)); }).catch(reject); }); @@ -318,12 +325,15 @@ export class AudioPlayerMinigame implements OperationQueueable { if (this._state === AudioState.PLAYING && !this._seeking) { time = clamp(time, 0, this.duration); this._seeking = true; + this._eventTarget.once(AudioEvent.SEEKED, resolve); this._innerAudioContext.seek(time); - } else if (this._cacheTime !== time) { // Skip the invalid seek - this._cacheTime = time; - this._needSeek = true; + } else { + if (this._cacheTime !== time) { // Skip the invalid seek + this._cacheTime = time; + this._needSeek = true; + } + resolve(); } - resolve(); }); } @@ -350,6 +360,11 @@ export class AudioPlayerMinigame implements OperationQueueable { @enqueueOperation stop (): Promise { return new Promise((resolve) => { + if (AudioState.INIT === this._state) { + this._resetSeekCache(); + resolve(); + return; + } this._eventTarget.once(AudioEvent.STOPPED, resolve); this._innerAudioContext.stop(); }); diff --git a/pal/audio/operation-queue.ts b/pal/audio/operation-queue.ts index 158b6ea694d..761affd21d4 100644 --- a/pal/audio/operation-queue.ts +++ b/pal/audio/operation-queue.ts @@ -26,6 +26,7 @@ import { EventTarget } from '../../cocos/core'; type OperationMethod = (...args: any[]) => Promise; export interface OperationInfo { + op: string; id: number; func: OperationMethod; args: any[], @@ -37,18 +38,48 @@ export interface OperationQueueable { _eventTarget: EventTarget; } +function removeUnneededCalls (instance: OperationQueueable): void { + const size = instance._operationQueue.length; + const tmpQueue = instance._operationQueue.slice(); + const reserveOps: OperationInfo[] = []; + let seekSearched = false; + for (let i = size - 1; i >= 0; i--) { + const opInfo = tmpQueue[i]; + if (opInfo.op === 'stop') { + reserveOps.push(opInfo); + break; + } else if (opInfo.op === 'seek') { + if (!seekSearched) { + reserveOps.push(opInfo); + seekSearched = true; + } + } else if (seekSearched) { + reserveOps.push(opInfo); + break; + } else if (reserveOps.length === 0) { + reserveOps.push(opInfo); + } + } + instance._operationQueue = reserveOps.reverse(); +} + let operationId = 0; function _tryCallingRecursively (target: T, opInfo: OperationInfo): void { if (opInfo.invoking) { return; } opInfo.invoking = true; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument opInfo.func.call(target, ...opInfo.args).then(() => { opInfo.invoking = false; target._operationQueue.shift(); target._eventTarget.emit(opInfo.id.toString()); + removeUnneededCalls(target); const nextOpInfo: OperationInfo = target._operationQueue[0]; - nextOpInfo && _tryCallingRecursively(target, nextOpInfo); + if (nextOpInfo) { + _tryCallingRecursively(target, nextOpInfo); + } + // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch((e) => {}); } @@ -64,14 +95,17 @@ function _tryCallingRecursively (target: T, opInfo * It means that, for example, you can't call stop in the implementation of play operation, * because that would cause the operation deadlock. */ +// eslint-disable-next-line max-len export function enqueueOperation (target: T, propertyKey: string, descriptor: TypedPropertyDescriptor): void { const originalOperation = descriptor.value!; + // eslint-disable-next-line func-names descriptor.value = function (...args: any[]): Promise { return new Promise((resolve) => { const id = operationId++; const instance = this as OperationQueueable; // enqueue operation instance._operationQueue.push({ + op: propertyKey, id, func: originalOperation, args, From eded5a94434d5bdf4b254a0db0be25c1eac55efa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Thu, 10 Aug 2023 17:18:08 +0800 Subject: [PATCH 124/232] add updateEnvMap for native (#15889) --- native/cocos/scene/Skybox.cpp | 14 ++++++++++++++ native/cocos/scene/Skybox.h | 1 + 2 files changed, 15 insertions(+) diff --git a/native/cocos/scene/Skybox.cpp b/native/cocos/scene/Skybox.cpp index 590f13f78fc..a8c59676abc 100644 --- a/native/cocos/scene/Skybox.cpp +++ b/native/cocos/scene/Skybox.cpp @@ -215,6 +215,20 @@ void SkyboxInfo::setMaterialProperty(const ccstd::string &name, const MaterialPr } } +void SkyboxInfo::updateEnvMap(TextureCube *val) { + if (!val) { + setApplyDiffuseMap(false); + setUseIBL(false); + setEnvLightingType(EnvironmentLightingType::HEMISPHERE_DIFFUSE); + } + if (_resource) { + _resource->setEnvMaps(_envmapHDR, _envmapLDR); + _resource->setDiffuseMaps(_diffuseMapHDR, _diffuseMapLDR); + _resource->setReflectionMaps(_reflectionHDR, _reflectionLDR); + _resource->setEnvmap(val); + } +} + void SkyboxInfo::activate(Skybox *resource) { _resource = resource; // weak reference Root::getInstance()->getPipeline()->getPipelineSceneData()->setHDR(_useHDR); diff --git a/native/cocos/scene/Skybox.h b/native/cocos/scene/Skybox.h index ad222dab32d..4312ad2df25 100644 --- a/native/cocos/scene/Skybox.h +++ b/native/cocos/scene/Skybox.h @@ -172,6 +172,7 @@ class SkyboxInfo : public RefCounted { inline Material *getSkyboxMaterial() const { return _editableMaterial; } void setMaterialProperty(const ccstd::string &name, const MaterialPropertyVariant &val, index_t passIdx = CC_INVALID_INDEX) const; + void updateEnvMap(TextureCube *val); void activate(Skybox *resource); From 0eec68226879b5314cbcc327d6a1315434352dc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Thu, 10 Aug 2023 17:18:21 +0800 Subject: [PATCH 125/232] fix incorrect display of preview plane for reflection probe (#15896) --- .../reflection-probe/ReflectionProbeFlow.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeFlow.cpp b/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeFlow.cpp index 4aaad4f02d1..3c3578c3e51 100644 --- a/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeFlow.cpp +++ b/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeFlow.cpp @@ -63,6 +63,11 @@ void ReflectionProbeFlow::render(scene::Camera *camera) { const auto *sceneData = _pipeline->getPipelineSceneData(); const auto probes = scene::ReflectionProbeManager::getInstance()->getAllProbes(); for (auto *probe : probes) { +#if CC_EDITOR + if (camera->getCameraUsage() != scene::CameraUsage::SCENE_VIEW) { + continue; + } +#endif if (probe->needRender()) { renderStage(camera, probe); } @@ -81,9 +86,13 @@ void ReflectionProbeFlow::renderStage(scene::Camera *camera, scene::ReflectionPr for (uint32_t faceIdx = 0; faceIdx < 6; faceIdx++) { //update camera dirction probe->updateCameraDir(faceIdx); - RenderTexture *rt = probe->getBakedCubeTextures()[faceIdx]; + ccstd::vector> cubeFaces = probe->getBakedCubeTextures(); + if (cubeFaces.empty()) { + probe->setNeedRender(false); + return; + } auto *reflectionProbeStage = static_cast(stage.get()); - reflectionProbeStage->setUsage(rt->getWindow()->getFramebuffer(), probe); + reflectionProbeStage->setUsage(cubeFaces[faceIdx]->getWindow()->getFramebuffer(), probe); reflectionProbeStage->render(camera); } probe->setNeedRender(false); From 78e3b6eece06d6543015a4f0fc297dce55a038c1 Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Thu, 10 Aug 2023 17:51:34 +0800 Subject: [PATCH 126/232] add preferredScreenEdgesDeferringSystemGestures to prevent accidental touch (#15920) --- templates/ios/ViewController.mm | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/templates/ios/ViewController.mm b/templates/ios/ViewController.mm index 1c1e77a4262..eba965cc7cf 100644 --- a/templates/ios/ViewController.mm +++ b/templates/ios/ViewController.mm @@ -50,9 +50,15 @@ - (BOOL)prefersStatusBarHidden { return YES; } -// Controls the application's preferred home indicator auto-hiding when this view controller is shown. +// Controls the application's screen edge gesture delay to prevent accidental touches +- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures +{ + return UIRectEdgeAll; +} + +// Controls the application's preferred home indicator auto-showing otherwise preferredScreenEdgesDeferringSystemGestures is invalidation - (BOOL)prefersHomeIndicatorAutoHidden { - return YES; + return NO; } - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator { From fa0a4fefef8e55830a509cbaca0632a322558194 Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Fri, 11 Aug 2023 10:10:04 +0800 Subject: [PATCH 127/232] fix Native Pipeline with render texture. (#15913) * fix shader block memory overwrite issue. * fix Native Pipeline with render texture. --- native/cocos/core/assets/EffectAsset.cpp | 13 ++++++++++--- .../cocos/renderer/gfx-gles3/GLES3Commands.cpp | 16 ++++++++++++++-- native/cocos/scene/Pass.cpp | 13 ++----------- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index da675688ea5..3de9bb7c778 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -226,9 +226,16 @@ void EffectAsset::precompile() { continue; } - ccstd::vector defines = EffectAsset::doCombine(ccstd::vector(), combination, combination.begin()); - for (auto &define : defines) { - ProgramLib::getInstance()->getGFXShader(root->getDevice(), shader.name, define, root->getPipeline()); + // Native Program Lib can not precompile shader variant without phaseID. + // Shaders are compiled only during the compilation of PSO. A new mechanism may be needed for pre-compilation. + auto *programLib = render::getProgramLibrary(); + if (programLib == nullptr) { + ccstd::vector defines = EffectAsset::doCombine( + ccstd::vector(), combination, combination.begin()); + for (auto &define: defines) { + ProgramLib::getInstance()->getGFXShader(root->getDevice(), shader.name, define, + root->getPipeline()); + } } } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 231ed1d3b5e..104ebfe5ce3 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -1594,7 +1594,12 @@ void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpu if (lazilyAllocated && // MS attachment should be memoryless resolveView->gpuTexture->swapchain == nullptr && // not back buffer i < supportCount) { // extension limit - gpuFBO->framebuffer.bindColorMultiSample(resolveView, colorIndex, view->gpuTexture->glSamples, resolveDesc); + auto validateDesc = resolveDesc; + // implicit MS take color slot, so color loadOP should be used. + // resolve attachment with Store::Discard is meaningless. + validateDesc.loadOp = desc.loadOp; + validateDesc.storeOp = StoreOp::STORE; + gpuFBO->framebuffer.bindColorMultiSample(resolveView, colorIndex, view->gpuTexture->glSamples, validateDesc); } else { // implicit MS not supported, fallback to MS Renderbuffer gpuFBO->colorBlitPairs.emplace_back(colorIndex, resolveColorIndex); @@ -1620,7 +1625,14 @@ void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpu resolveView->gpuTexture->swapchain == nullptr && // not back buffer supportCount > 1 && // extension limit useDsResolve) { // enable ds resolve - gpuFBO->framebuffer.bindDepthStencilMultiSample(resolveView, view->gpuTexture->glSamples, resolveDesc); + auto validateDesc = resolveDesc; + // implicit MS take ds slot, so ds MS loadOP should be used. + // resolve attachment with Store::Discard is meaningless. + validateDesc.depthLoadOp = desc.depthLoadOp; + validateDesc.depthStoreOp = StoreOp::STORE; + validateDesc.stencilLoadOp = desc.stencilLoadOp; + validateDesc.stencilStoreOp = StoreOp::STORE; + gpuFBO->framebuffer.bindDepthStencilMultiSample(resolveView, view->gpuTexture->glSamples, validateDesc); } else { // implicit MS not supported, fallback to MS Renderbuffer gpuFBO->dsResolveMask = getColorBufferMask(desc.format); diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index 16ad740e353..13518a78464 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -416,17 +416,8 @@ void Pass::resetUBOs() { ofs += size; } }; - auto *programLib = render::getProgramLibrary(); - if (programLib) { - const auto &set = _shaderInfo->descriptors.at( - static_cast(pipeline::SetIndex::MATERIAL)); - for (const auto &block : set.blocks) { - updateBuffer(block); - } - } else { - for (const auto &u : _shaderInfo->blocks) { - updateBuffer(u); - } + for (const auto &u : _shaderInfo->blocks) { + updateBuffer(u); } _rootBufferDirty = true; } From 6e653079a1778bf5f631f52ae66834b75d8f70da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Fri, 11 Aug 2023 11:30:17 +0800 Subject: [PATCH 128/232] fix reset property in inspector (#15864) --- editor/inspector/contributions/node.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 07504266776..13285f5336a 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -81,7 +81,7 @@ exports.listeners = { snapshotLock(panel, true, panel.uuidList); } - const dump = event.target.dump; + const dump = target.dump; if (!dump || panel.isDialoging) { return; } @@ -181,7 +181,7 @@ exports.listeners = { // Editor.Message.send('scene', 'snapshot'); const undoID = await beginRecording(panel.uuidList); - const dump = event.target.dump; + const dump = target.dump; let cancel = false; try { for (let i = 0; i < panel.uuidList.length; i++) { @@ -214,7 +214,7 @@ exports.listeners = { clearTimeout(panel.previewTimeId); const undoID = await beginRecording(panel.uuidList); - const dump = event.target.dump; + const dump = target.dump; try { for (let i = 0; i < panel.uuidList.length; i++) { const uuid = panel.uuidList[i]; @@ -240,7 +240,7 @@ exports.listeners = { return; } - const dump = event.target.dump; + const dump = target.dump; if (!dump || panel.isDialoging) { return; } From 60b5a7de66943e156968dc29dae3a011addc33f6 Mon Sep 17 00:00:00 2001 From: zxx43 Date: Fri, 11 Aug 2023 14:07:30 +0800 Subject: [PATCH 129/232] 3.8.1 add spine jsb apis (#15674) * open some spine apis * add some apis * add spine jsb convert * add some manual interfaces * fix some jsb * fix getAttachments * remove findAttachmentsForSlot * manual VertexEffect::begin * remove SkinEntry * change some apis * fix isObject * use entry ptr instead of entry * remove array.get() * remove array.get() * fix ci * fix ci * change include * fix SWIGINTERN * fix test-case * use rename * check spine instance null * fix eslint * fix eslint * add some missing apis * add getAttachmentByName * modify jsb api * fix eslint --- cocos/spine/skeleton.ts | 25 +- native/CMakeLists.txt | 5 +- .../bindings/manual/jsb_conversions_spec.cpp | 23 + .../bindings/manual/jsb_conversions_spec.h | 5 + .../bindings/manual/jsb_spine_manual.cpp | 318 +++++++++ .../spine-creator-support/Vector2.cpp | 48 ++ .../spine-creator-support/Vector2.h | 54 ++ native/tools/swig-config/spine.i | 623 +++++++++++++++--- platforms/native/engine/jsb-spine-skeleton.js | 4 +- 9 files changed, 990 insertions(+), 115 deletions(-) create mode 100644 native/cocos/editor-support/spine-creator-support/Vector2.cpp create mode 100644 native/cocos/editor-support/spine-creator-support/Vector2.h diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 691702d985a..c4e81ab9dab 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -626,6 +626,7 @@ export class Skeleton extends UIRenderer { this._updateDebugDraw(); } + // eslint-disable-next-line @typescript-eslint/no-empty-function public onRestore (): void { } @@ -730,8 +731,10 @@ export class Skeleton extends UIRenderer { if (this.debugBones || this.debugSlots) { warn('Debug bones or slots is invalid in cached mode'); } - const skeletonInfo = this._skeletonCache!.getSkeletonCache(this.skeletonData!.uuid, skeletonData); - this._skeleton = skeletonInfo.skeleton; + if (this.skeletonData) { + const skeletonInfo = this._skeletonCache!.getSkeletonCache(this.skeletonData.uuid, skeletonData); + this._skeleton = skeletonInfo.skeleton; + } } else { this._skeleton = this._instance.initSkeleton(skeletonData); this._state = this._instance.getAnimationState(); @@ -993,15 +996,7 @@ export class Skeleton extends UIRenderer { for (let i = 0; i < this._drawList.length; i++) { const dc = this._drawList.data[i]; if (dc.texture) { - batcher.commitMiddleware( - this, - meshBuffer, - origin + dc.indexOffset, - dc.indexCount, - dc.texture, - dc.material!, - this._enableBatch, - ); + batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, dc.indexCount, dc.texture, dc.material!, this._enableBatch); } indicesCount += dc.indexCount; } @@ -1189,7 +1184,7 @@ export class Skeleton extends UIRenderer { * skeleton.setAnimationCacheMode(sp.Skeleton.AnimationCacheMode.SHARED_CACHE); */ public setAnimationCacheMode (cacheMode: AnimationCacheMode): void { - if (this._preCacheMode !== cacheMode) { + if (this._preCacheMode !== cacheMode) { this._cacheMode = cacheMode; //this.setSkin(this.defaultSkin); this._updateSkeletonData(); @@ -1407,7 +1402,7 @@ export class Skeleton extends UIRenderer { }; for (let i = 0, l = bones.length; i < l; i++) { const bd = bones[i].data; - const boneName = getBoneName(bones[i]); + const boneName: string = getBoneName(bones[i]); this._cachedSockets.set(boneName, bd.index); } } @@ -1473,7 +1468,9 @@ export class Skeleton extends UIRenderer { this._debugRenderer.node.destroy(); this._debugRenderer = null; if (!this.isAnimationCached()) { - if (!JSB) this._instance.setDebugMode(false); + if (this._instance) { + this._instance.setDebugMode(false); + } } } } diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index a1c3dacce9b..a1da31bfede 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -2374,7 +2374,10 @@ if(USE_MIDDLEWARE) NO_WERROR cocos/editor-support/spine-creator-support/spine-cocos2dx.cpp cocos/editor-support/spine-creator-support/spine-cocos2dx.h NO_WERROR cocos/editor-support/spine-creator-support/VertexEffectDelegate.cpp - cocos/editor-support/spine-creator-support/VertexEffectDelegate.h + cocos/editor-support/spine-creator-support/VertexEffectDelegate.h + cocos/editor-support/spine-creator-support/VertexEffectDelegate.h + NO_WERROR cocos/editor-support/spine-creator-support/Vector2.cpp + cocos/editor-support/spine-creator-support/Vector2.h ) cocos_source_files( diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.cpp b/native/cocos/bindings/manual/jsb_conversions_spec.cpp index e0e27adc138..91620cd2c13 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.cpp +++ b/native/cocos/bindings/manual/jsb_conversions_spec.cpp @@ -50,6 +50,10 @@ #include "scene/Shadow.h" #include "scene/Skybox.h" +#if CC_USE_SPINE +#include "cocos/editor-support/spine-creator-support/Vector2.h" +#endif + ///////////////////////// utils ///////////////////////// #define CHECK_ASSIGN_PRVOBJ_RET(jsObj, nativeObj) \ @@ -1162,6 +1166,25 @@ bool sevalue_to_native(const se::Value &v, spine::Vector *ret, se return true; } + +bool sevalue_to_native(const se::Value &from, spine::Vector2 *to, se::Object * /*unused*/) { + SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Vec2 failed!"); + + se::Object *obj = from.toObject(); + CHECK_ASSIGN_PRVOBJ_RET(obj, to) + se::Value tmp; + set_member_field(obj, to, "x", &spine::Vector2::x, tmp); + set_member_field(obj, to, "y", &spine::Vector2::y, tmp); + return true; +} + +bool nativevalue_to_se(const spine::Vector2 &from, se::Value &to, se::Object * /*unused*/) { + se::HandleObject obj(se::Object::createPlainObject()); + obj->setProperty("x", se::Value(from.x)); + obj->setProperty("y", se::Value(from.y)); + to.setObject(obj); + return true; +} #endif #if CC_USE_MIDDLEWARE diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.h b/native/cocos/bindings/manual/jsb_conversions_spec.h index d36a7dc5bc7..09ef024954b 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.h +++ b/native/cocos/bindings/manual/jsb_conversions_spec.h @@ -133,6 +133,7 @@ template class Vector; template class Map; +class Vector2; } // namespace spine #endif @@ -600,6 +601,10 @@ bool nativevalue_to_se(const spine::String &obj, se::Value &val, se::Object *ctx bool sevalue_to_native(const se::Value &v, spine::Vector *ret, se::Object *ctx); // NOLINT(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, spine::Vector2 *to, se::Object * /*unused*/); // NOLINT(readability-identifier-naming) + +bool nativevalue_to_se(const spine::Vector2 &from, se::Value &to, se::Object * /*unused*/); // NOLINT(readability-identifier-naming) + #endif inline bool nativevalue_to_se(const se::Object *from, se::Value &to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) diff --git a/native/cocos/bindings/manual/jsb_spine_manual.cpp b/native/cocos/bindings/manual/jsb_spine_manual.cpp index 5eef2266929..6e550dc889d 100644 --- a/native/cocos/bindings/manual/jsb_spine_manual.cpp +++ b/native/cocos/bindings/manual/jsb_spine_manual.cpp @@ -37,6 +37,7 @@ #include "spine-creator-support/SkeletonDataMgr.h" #include "spine-creator-support/SkeletonRenderer.h" #include "spine-creator-support/spine-cocos2dx.h" +#include "spine-creator-support/Vector2.h" using namespace cc; @@ -213,6 +214,311 @@ static bool js_register_spine_retainSkeletonData(se::State &s) { } SE_BIND_FUNC(js_register_spine_retainSkeletonData) +static bool js_VertexAttachment_computeWorldVertices(se::State &s) { + const auto &args = s.args(); + + spine::VertexAttachment *vertexAttachment = SE_THIS_OBJECT(s); + if (nullptr == vertexAttachment) return true; + + spine::Slot *slot = nullptr; + size_t start = 0, count = 0, offset = 0, stride = 0; + se::Value worldVerticesVal; + + bool ok = false; + ok = sevalue_to_native(args[0], &slot, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing slot"); + + ok = sevalue_to_native(args[1], &start, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing start"); + + ok = sevalue_to_native(args[2], &worldVerticesVal, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing vertices"); + + ok = sevalue_to_native(args[3], &count, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing count"); + + ok = sevalue_to_native(args[4], &offset, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing offset"); + + ok = sevalue_to_native(args[5], &stride, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing stride"); + + if (worldVerticesVal.toObject()->isTypedArray()) { + uint8_t* ptr = nullptr; + size_t len = 0; + worldVerticesVal.toObject()->getTypedArrayData(&ptr, &len); + vertexAttachment->computeWorldVertices(*slot, start, count, reinterpret_cast(ptr), offset, stride); + } else if (worldVerticesVal.toObject()->isArray()) { + spine::Vector worldVertices; + worldVertices.ensureCapacity(count); + vertexAttachment->computeWorldVertices(*slot, start, count, worldVertices, 0); + + int tCount = offset + (count >> 1) * stride; + + for (size_t i = offset, t = 0; i < tCount; i += stride, t += 2) { + worldVerticesVal.toObject()->setArrayElement(i, se::Value(worldVertices[t])); + worldVerticesVal.toObject()->setArrayElement(i + 1, se::Value(worldVertices[t + 1])); + } + } + return true; +} +SE_BIND_FUNC(js_VertexAttachment_computeWorldVertices) + +static bool js_RegionAttachment_computeWorldVertices(se::State &s) { + const auto &args = s.args(); + + spine::RegionAttachment *regionAttachment = SE_THIS_OBJECT(s); + if (nullptr == regionAttachment) return true; + + spine::Bone *bone = nullptr; + size_t offset = 0, stride = 0; + se::Value worldVerticesVal; + + bool ok = false; + ok = sevalue_to_native(args[0], &bone, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + ok = sevalue_to_native(args[1], &worldVerticesVal, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + ok = sevalue_to_native(args[2], &offset, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + ok = sevalue_to_native(args[3], &stride, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + if (worldVerticesVal.toObject()->isTypedArray()) { + uint8_t* ptr = nullptr; + size_t len = 0; + worldVerticesVal.toObject()->getTypedArrayData(&ptr, &len); + regionAttachment->computeWorldVertices(*bone, reinterpret_cast(ptr), offset, stride); + } else if (worldVerticesVal.toObject()->isArray()) { + spine::Vector worldVertices; + int count = 8; + worldVertices.ensureCapacity(count); + regionAttachment->computeWorldVertices(*bone, worldVertices, 0); + + int curr = offset; + worldVerticesVal.toObject()->setArrayElement(curr, se::Value(worldVertices[0])); + worldVerticesVal.toObject()->setArrayElement(curr + 1, se::Value(worldVertices[1])); + + curr += stride; + worldVerticesVal.toObject()->setArrayElement(curr, se::Value(worldVertices[2])); + worldVerticesVal.toObject()->setArrayElement(curr + 1, se::Value(worldVertices[3])); + + curr += stride; + worldVerticesVal.toObject()->setArrayElement(curr, se::Value(worldVertices[4])); + worldVerticesVal.toObject()->setArrayElement(curr + 1, se::Value(worldVertices[5])); + + curr += stride; + worldVerticesVal.toObject()->setArrayElement(curr, se::Value(worldVertices[6])); + worldVerticesVal.toObject()->setArrayElement(curr + 1, se::Value(worldVertices[7])); + } + return true; +} +SE_BIND_FUNC(js_RegionAttachment_computeWorldVertices) + +static bool js_Skeleton_getBounds(se::State &s) { + const auto &args = s.args(); + spine::Skeleton* skeleton = SE_THIS_OBJECT(s); + if (nullptr == skeleton) return true; + + se::Value temp; + + bool ok = false; + ok = sevalue_to_native(args[2], &temp, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + { + float offx = 0.F, offy = 0.F, sizex = 0.F, sizey = 0.F; + spine::Vector outVertexBuffer; + skeleton->getBounds(offx, offy, sizex, sizey, outVertexBuffer); + args[0].toObject()->setProperty("x", se::Value(offx)); + args[0].toObject()->setProperty("y", se::Value(offy)); + args[1].toObject()->setProperty("x", se::Value(sizex)); + args[1].toObject()->setProperty("y", se::Value(sizey)); + if (temp.isObject()) { + for (int i = 0; i < outVertexBuffer.size(); ++i) { + temp.toObject()->setArrayElement(i, se::Value(outVertexBuffer[i])); + } + } + } + return true; +} +SE_BIND_FUNC(js_Skeleton_getBounds) + +static bool js_Bone_worldToLocal(se::State &s) { + const auto &args = s.args(); + spine::Bone* bone = SE_THIS_OBJECT(s); + if (nullptr == bone) return true; + + spine::Vector2 world(0, 0); + + bool ok = false; + ok = sevalue_to_native(args[0], &world, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + float outX = 0.F, outY = 0.F; + bone->worldToLocal(world.x, world.y, outX, outY); + + spine::Vector2 outNative(outX, outY); + se::Value ret; + nativevalue_to_se(outNative, ret, s.thisObject()); + s.rval().setObject(ret.toObject()); + return true; +} +SE_BIND_FUNC(js_Bone_worldToLocal) + +static bool js_Bone_localToWorld(se::State &s) { + const auto &args = s.args(); + spine::Bone* bone = SE_THIS_OBJECT(s); + if (nullptr == bone) return true; + + spine::Vector2 local(0, 0); + + bool ok = false; + ok = sevalue_to_native(args[0], &local, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + float outX = 0.F, outY = 0.F; + bone->localToWorld(local.x, local.y, outX, outY); + + spine::Vector2 outNative(outX, outY); + se::Value ret; + nativevalue_to_se(outNative, ret, s.thisObject()); + s.rval().setObject(ret.toObject()); + return true; +} +SE_BIND_FUNC(js_Bone_localToWorld) + +static bool js_PointAttachment_computeWorldPosition(se::State &s) { + const auto &args = s.args(); + spine::PointAttachment* pointAttachment = SE_THIS_OBJECT(s); + if (nullptr == pointAttachment) return true; + + spine::Bone* bone = nullptr; + + bool ok = false; + ok = sevalue_to_native(args[0], &bone, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + float outX = 0.F, outY = 0.F; + pointAttachment->computeWorldPosition(*bone, outX, outY); + + spine::Vector2 outNative(outX, outY); + se::Value ret; + nativevalue_to_se(outNative, ret, s.thisObject()); + s.rval().setObject(ret.toObject()); + return true; +} +SE_BIND_FUNC(js_PointAttachment_computeWorldPosition) + +static bool js_Skin_findAttachmentsForSlot(se::State &s) { + const auto &args = s.args(); + spine::Skin* skin = SE_THIS_OBJECT(s); + if (nullptr == skin) return true; + + size_t slotIndex = 0; + se::Value attachmentsVal; + + bool ok = false; + ok = sevalue_to_native(args[0], &slotIndex, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + attachmentsVal = args[1]; + ok = attachmentsVal.isObject(); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + spine::Skin::AttachmentMap::Entries entries = skin->getAttachments(); + uint32_t index = 0; + while (entries.hasNext()) { + spine::Skin::AttachmentMap::Entry &entry = entries.next(); + if (entry._slotIndex == slotIndex) { + se::Value entryVal; + ok = nativevalue_to_se(&entry, entryVal); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + attachmentsVal.toObject()->setArrayElement(index++, entryVal); + } + } + return true; +} +SE_BIND_FUNC(js_Skin_findAttachmentsForSlot) + +static bool js_VertexEffect_transform(se::State &s) { + const auto &args = s.args(); + spine::VertexEffect* effect = SE_THIS_OBJECT(s); + if (nullptr == effect) return true; + + float outX = 0.F, outY = 0.F; + effect->transform(outX, outY); + + args[0].toObject()->setProperty("x", se::Value(outX)); + args[0].toObject()->setProperty("y", se::Value(outY)); + return true; +} +SE_BIND_FUNC(js_VertexEffect_transform) + +static bool js_SwirlVertexEffect_transform(se::State &s) { + const auto &args = s.args(); + spine::SwirlVertexEffect* effect = SE_THIS_OBJECT(s); + if (nullptr == effect) return true; + + float outX = 0.F, outY = 0.F; + effect->transform(outX, outY); + + args[0].toObject()->setProperty("x", se::Value(outX)); + args[0].toObject()->setProperty("y", se::Value(outY)); + return true; +} +SE_BIND_FUNC(js_SwirlVertexEffect_transform) + +static bool js_JitterVertexEffect_transform(se::State &s) { + const auto &args = s.args(); + spine::JitterVertexEffect* effect = SE_THIS_OBJECT(s); + if (nullptr == effect) return true; + + float outX = 0.F, outY = 0.F; + effect->transform(outX, outY); + + args[0].toObject()->setProperty("x", se::Value(outX)); + args[0].toObject()->setProperty("y", se::Value(outY)); + return true; +} +SE_BIND_FUNC(js_JitterVertexEffect_transform) + +static bool js_spine_Skin_getAttachments(se::State& s) { + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + spine::Skin *skin = (spine::Skin *) NULL ; + + if(argc != 0) { + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; + } + skin = SE_THIS_OBJECT(s); + if (nullptr == skin) return true; + spine::Skin::AttachmentMap::Entries attachments = skin->getAttachments(); + + std::vector entries; + while (attachments.hasNext()) { + spine::Skin::AttachmentMap::Entry &entry = attachments.next(); + se::Value entryVal; + ok = nativevalue_to_se(&entry, entryVal); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + entries.push_back(entryVal); + } + + se::HandleObject array(se::Object::createArrayObject(entries.size())); + for (int i = 0; i < entries.size(); ++i) { + array->setArrayElement(i, entries[i]); + } + s.rval().setObject(array); + + return true; +} +SE_BIND_FUNC(js_spine_Skin_getAttachments) + bool register_all_spine_manual(se::Object *obj) { // Get the ns se::Value nsVal; @@ -228,6 +534,18 @@ bool register_all_spine_manual(se::Object *obj) { ns->defineFunction("retainSkeletonData", _SE(js_register_spine_retainSkeletonData)); ns->defineFunction("disposeSkeletonData", _SE(js_register_spine_disposeSkeletonData)); + __jsb_spine_VertexAttachment_proto->defineFunction("computeWorldVertices", _SE(js_VertexAttachment_computeWorldVertices)); + __jsb_spine_RegionAttachment_proto->defineFunction("computeWorldVertices", _SE(js_RegionAttachment_computeWorldVertices)); + __jsb_spine_Skeleton_proto->defineFunction("getBounds", _SE(js_Skeleton_getBounds)); + __jsb_spine_Skin_proto->defineFunction("getAttachmentsForSlot", _SE(js_Skin_findAttachmentsForSlot)); + __jsb_spine_Bone_proto->defineFunction("worldToLocal", _SE(js_Bone_worldToLocal)); + __jsb_spine_Bone_proto->defineFunction("localToWorld", _SE(js_Bone_localToWorld)); + __jsb_spine_PointAttachment_proto->defineFunction("computeWorldPosition", _SE(js_PointAttachment_computeWorldPosition)); + __jsb_spine_VertexEffect_proto->defineFunction("transform", _SE(js_VertexEffect_transform)); + __jsb_spine_SwirlVertexEffect_proto->defineFunction("transform", _SE(js_SwirlVertexEffect_transform)); + __jsb_spine_JitterVertexEffect_proto->defineFunction("transform", _SE(js_JitterVertexEffect_transform)); + __jsb_spine_Skin_proto->defineFunction("getAttachments", _SE(js_spine_Skin_getAttachments)); + spine::setSpineObjectDisposeCallback([](void *spineObj) { if (!se::NativePtrToObjectMap::isValid()) { return; diff --git a/native/cocos/editor-support/spine-creator-support/Vector2.cpp b/native/cocos/editor-support/spine-creator-support/Vector2.cpp new file mode 100644 index 00000000000..3b18308506c --- /dev/null +++ b/native/cocos/editor-support/spine-creator-support/Vector2.cpp @@ -0,0 +1,48 @@ +#include "Vector2.h" +#include +namespace spine { + +Vector2::Vector2(): x(0), y(0) { + +} + +Vector2::Vector2(float x, float y) { + this->x = x; + this->y = y; +} + +Vector2::~Vector2() {} + +void Vector2::setX(float x) { + this->x = x; +} + +float Vector2::getX() { + return x; +} + +void Vector2::setY(float y) { + this->y = y; +} + +float Vector2::getY() { + return y; +} + +Vector2& Vector2::set(float x, float y) { + this->setX(x); + this->setY(y); + return *this; +} + +float Vector2::length() { + return sqrt(x * x + y * y); +} + +Vector2& Vector2::normalize() { + float invLen = 1.F / length(); + this->setX(x * invLen); + this->setY(y * invLen); + return *this; +} +} \ No newline at end of file diff --git a/native/cocos/editor-support/spine-creator-support/Vector2.h b/native/cocos/editor-support/spine-creator-support/Vector2.h new file mode 100644 index 00000000000..0f62883bc4c --- /dev/null +++ b/native/cocos/editor-support/spine-creator-support/Vector2.h @@ -0,0 +1,54 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma once + +#include "spine/spine.h" + +namespace spine { + class Vector2 + { + public: + float x, y; + public: + Vector2(); + Vector2(float x, float y); + ~Vector2(); + + void setX(float x); + float getX(); + + void setY(float y); + float getY(); + + Vector2 &set(float x, float y); + float length(); + Vector2 &normalize(); + }; +} \ No newline at end of file diff --git a/native/tools/swig-config/spine.i b/native/tools/swig-config/spine.i index 2bde5f2acdd..4d92e47b311 100644 --- a/native/tools/swig-config/spine.i +++ b/native/tools/swig-config/spine.i @@ -13,6 +13,7 @@ #include "bindings/jswrapper/SeApi.h" #include "bindings/manual/jsb_conversions.h" #include "editor-support/spine-creator-support/spine-cocos2dx.h" +#include "editor-support/spine-creator-support/Vector2.h" %} // Insert code at the beginning of generated source file (.cpp) @@ -22,6 +23,8 @@ #include "bindings/auto/jsb_cocos_auto.h" #include "bindings/auto/jsb_spine_auto.h" using namespace spine; + +#define SWIGINTERN static %} // ----- Ignore Section ------ @@ -37,66 +40,17 @@ using namespace spine; // 1. 'Ignore Section' should be placed before attribute definition and %import/%include // 2. namespace is needed // +%ignore spine::MathUtil; %ignore cc::RefCounted; %ignore *::rtti; %ignore spine::SkeletonCache::SegmentData; %ignore spine::SkeletonCache::BoneData; %ignore spine::SkeletonCache::FrameData; %ignore spine::SkeletonCache::AnimationData; -%ignore spine::Skin::AttachmentMap; - -%ignore spine::Animation::Animation; -%ignore spine::TrackEntry::TrackEntry; -%ignore spine::AnimationState::AnimationState; -%ignore spine::AnimationStateData::AnimationStateData; -%ignore spine::Attachment::Attachment; -%ignore spine::AttachmentTimeline::AttachmentTimeline; -%ignore spine::BoundingBoxAttachment::BoundingBoxAttachment; -%ignore spine::Bone::Bone; -%ignore spine::BoneData::BoneData; -%ignore spine::ClippingAttachment::ClippingAttachment; -%ignore spine::Color::Color; -%ignore spine::ColorTimeline::ColorTimeline; -%ignore spine::CurveTimeline::CurveTimeline; -%ignore spine::DeformTimeline::DeformTimeline; -%ignore spine::DrawOrderTimeline::DrawOrderTimeline; -%ignore spine::Event::Event; -%ignore spine::EventData::EventData; -%ignore spine::EventTimeline::EventTimeline; -%ignore spine::IkConstraint::IkConstraint; -%ignore spine::IkConstraintData::IkConstraintData; -%ignore spine::IkConstraintTimeline::IkConstraintTimeline; -%ignore spine::MeshAttachment::MeshAttachment; +%ignore spine::Skin::AttachmentMap::getEntries; + %ignore spine::Polygon::Polygon; %ignore spine::Polygon::_vertices; -%ignore spine::PathAttachment::PathAttachment; -%ignore spine::PathConstraint::PathConstraint; -%ignore spine::PathConstraintData::PathConstraintData; -%ignore spine::PathConstraintMixTimeline::PathConstraintMixTimeline; -%ignore spine::PathConstraintPositionTimeline::PathConstraintPositionTimeline; -%ignore spine::PathConstraintSpacingTimeline::PathConstraintSpacingTimeline; -%ignore spine::PointAttachment::PointAttachment; -%ignore spine::RegionAttachment::RegionAttachment; -%ignore spine::RotateTimeline::RotateTimeline; -%ignore spine::ScaleTimeline::ScaleTimeline; -%ignore spine::ShearTimeline::ShearTimeline; -%ignore spine::Skeleton::Skeleton; -%ignore spine::Slot::Slot; -%ignore spine::Skin::Skin; -%ignore spine::SlotData::SlotData; -%ignore spine::SkeletonBounds::SkeletonBounds; -%ignore spine::SkeletonData::SkeletonData; -%ignore spine::Timeline::Timeline; -%ignore spine::TransformConstraint::TransformConstraint; -%ignore spine::TransformConstraintData::TransformConstraintData; -%ignore spine::TransformConstraintTimeline::TransformConstraintTimeline; -%ignore spine::TranslateTimeline::TranslateTimeline; -%ignore spine::TwoColorTimeline::TwoColorTimeline; -%ignore spine::VertexAttachment::VertexAttachment; -%ignore spine::VertexEffect::VertexEffect; -%ignore spine::JitterVertexEffect::JitterVertexEffect; -%ignore spine::SwirlVertexEffect::SwirlVertexEffect; -%ignore spine::ConstraintData::ConstraintData; %ignore spine::SkeletonRenderer::create; %ignore spine::SkeletonRenderer::initWithJsonFile; @@ -110,83 +64,43 @@ using namespace spine; %ignore spine::SkeletonAnimation::createWithData; %ignore spine::SkeletonAnimation::onTrackEntryEvent; %ignore spine::SkeletonAnimation::onAnimationStateEvent; -%ignore spine::Animation::apply; %ignore spine::TrackEntry::setListener; -%ignore spine::AnimationState::apply; %ignore spine::AnimationState::setListener; %ignore spine::Attachment::getRTTI; -%ignore spine::AttachmentTimeline::apply; %ignore spine::AttachmentTimeline::getRTTI; %ignore spine::BoundingBoxAttachment::getRTTI; -%ignore spine::Bone::worldToLocal; -%ignore spine::Bone::localToWorld; %ignore spine::Bone::getRTTI; +%ignore spine::Bone::worldToLocal(float, float, float&, float&); +%ignore spine::Bone::localToWorld(float, float, float&, float&); %ignore spine::ClippingAttachment::getRTTI; -%ignore spine::Color::set; -%ignore spine::Color::add; -%ignore spine::ColorTimeline::apply; %ignore spine::ColorTimeline::getRTTI; -%ignore spine::CurveTimeline::apply; %ignore spine::CurveTimeline::getRTTI; -%ignore spine::DeformTimeline::apply; -%ignore spine::DeformTimeline::setFrame; %ignore spine::DeformTimeline::getVertices; %ignore spine::DeformTimeline::getRTTI; -%ignore spine::DrawOrderTimeline::apply; -%ignore spine::DrawOrderTimeline::setFrame; -%ignore spine::DrawOrderTimeline::getDrawOrders; %ignore spine::DrawOrderTimeline::getRTTI; -%ignore spine::EventTimeline::apply; %ignore spine::EventTimeline::getRTTI; -%ignore spine::IkConstraint::apply; %ignore spine::IkConstraint::getRTTI; -%ignore spine::IkConstraintTimeline::apply; +%ignore spine::IkConstraint::apply(Bone&, float, float, bool, bool, bool, float); +%ignore spine::IkConstraint::apply(Bone&, Bone&, float, float, int, bool, float, float); %ignore spine::IkConstraintTimeline::getRTTI; %ignore spine::MeshAttachment::getRTTI; %ignore spine::PathAttachment::getRTTI; %ignore spine::PathConstraint::getRTTI; -%ignore spine::PathConstraintMixTimeline::apply; %ignore spine::PathConstraintMixTimeline::getRTTI; -%ignore spine::PathConstraintPositionTimeline::apply; %ignore spine::PathConstraintPositionTimeline::getRTTI; -%ignore spine::PathConstraintSpacingTimeline::apply; %ignore spine::PathConstraintSpacingTimeline::getRTTI; -%ignore spine::PointAttachment::computeWorldPosition; %ignore spine::PointAttachment::getRTTI; -%ignore spine::PointAttachment::computeWorldRotation; -%ignore spine::RegionAttachment::computeWorldVertices; %ignore spine::RegionAttachment::getRTTI; -%ignore spine::RotateTimeline::apply; %ignore spine::RotateTimeline::getRTTI; -%ignore spine::ScaleTimeline::apply; %ignore spine::ScaleTimeline::getRTTI; -%ignore spine::ShearTimeline::apply; %ignore spine::ShearTimeline::getRTTI; -%ignore spine::Skeleton::getBounds; -%ignore spine::Skin::getAttachments; -%ignore spine::Skin::findAttachmentsForSlot; %ignore spine::Skin::findNamesForSlot; -%ignore spine::SkeletonBounds::update; -%ignore spine::SkeletonBounds::aabbIntersectsSkeleton; -%ignore spine::Timeline::apply; +%ignore spine::Skin::getAttachments; %ignore spine::Timeline::getRTTI; %ignore spine::TransformConstraint::getRTTI; -%ignore spine::TransformConstraintTimeline::apply; %ignore spine::TransformConstraintTimeline::getRTTI; -%ignore spine::TranslateTimeline::apply; %ignore spine::TranslateTimeline::getRTTI; -%ignore spine::TwoColorTimeline::apply; %ignore spine::TwoColorTimeline::getRTTI; -%ignore spine::VertexEffect::begin; -%ignore spine::VertexEffect::transform; -%ignore spine::VertexEffect::end; -%ignore spine::JitterVertexEffect::begin; -%ignore spine::JitterVertexEffect::transform; -%ignore spine::JitterVertexEffect::end; -%ignore spine::SwirlVertexEffect::begin; -%ignore spine::SwirlVertexEffect::transform; -%ignore spine::SwirlVertexEffect::end; -%ignore spine::VertexAttachment::computeWorldVertices; %ignore spine::VertexAttachment::getRTTI; %ignore spine::SkeletonDataMgr::destroyInstance; %ignore spine::SkeletonDataMgr::hasSkeletonData; @@ -196,6 +110,32 @@ using namespace spine; %ignore spine::SkeletonCacheAnimation::render; %ignore spine::SkeletonCacheAnimation::requestDrawInfo; %ignore spine::SkeletonCacheAnimation::requestMaterial; +%ignore spine::Timeline::apply(Skeleton&, float, float, Vector*, float, MixBlend, MixDirection); +%ignore spine::AnimationState::apply(Skeleton&); +%ignore spine::Animation::apply(Skeleton&, float, float, bool, Vector*, float, MixBlend, MixDirection); +%ignore spine::VertexAttachment::computeWorldVertices; +%ignore spine::Bone::Bone(BoneData&, Skeleton&, Bone*); +%ignore spine::Bone::Bone(BoneData&, Skeleton&); +%ignore spine::Event::Event(float, const EventData&); +%ignore spine::IkConstraint::IkConstraint(IkConstraintData&, Skeleton&); +%ignore spine::PathConstraint::PathConstraint(PathConstraintData&, Skeleton&); +%ignore spine::PointAttachment::computeWorldPosition; +%ignore spine::PointAttachment::computeWorldRotation(Bone&); +%ignore spine::RegionAttachment::computeWorldVertices; +%ignore spine::Slot::Slot(SlotData&, Bone&); +%ignore spine::VertexEffect::begin(Skeleton &); +%ignore spine::TransformConstraint::TransformConstraint(TransformConstraintData&, Skeleton&); +%ignore spine::SkeletonBounds::update(Skeleton&, bool); +%ignore spine::SlotData::SlotData(int, const String&, BoneData&); +%ignore spine::SwirlVertexEffect::SwirlVertexEffect(float, Interpolation&); +%ignore spine::SwirlVertexEffect::transform(float&, float&); +%ignore spine::JitterVertexEffect::transform(float&, float&); +%ignore spine::VertexEffect::transform(float&, float&); +%ignore spine::DeformTimeline::setFrame(int, float, Vector&); +%ignore spine::DrawOrderTimeline::setFrame(size_t, float, Vector&); +%ignore spine::Skeleton::getBounds; +%ignore spine::Bone::updateWorldTransform(float, float, float, float, float, float, float); +%ignore spine::Skin::findAttachmentsForSlot; // ----- Rename Section ------ // Brief: Classes, methods or attributes needs to be renamed @@ -214,6 +154,56 @@ using namespace spine; %rename(setTrackCompleteListenerNative) spine::SkeletonAnimation::setTrackCompleteListener; %rename(create) spine::SkeletonRenderer::createWithFile; +%rename(frames) spine::TranslateTimeline::_frames; +%rename(boneIndex) spine::TranslateTimeline::_boneIndex; +%rename(frames) spine::TwoColorTimeline::_frames; +%rename(frames) spine::IkConstraintTimeline::_frames; +%rename(ikConstraintIndex) spine::IkConstraintTimeline::_ikConstraintIndex; +%rename(frames) spine::TransformConstraintTimeline::_frames; +%rename(transformConstraintIndex) spine::TransformConstraintTimeline::_transformConstraintIndex; +%rename(frames) spine::PathConstraintPositionTimeline::_frames; +%rename(pathConstraintIndex) spine::PathConstraintPositionTimeline::_pathConstraintIndex; +%rename(frames) spine::PathConstraintMixTimeline::_frames; +%rename(pathConstraintIndex) spine::PathConstraintMixTimeline::_pathConstraintIndex; +%rename(events) spine::AnimationState::_events; +%rename(queue) spine::AnimationState::_queue; +%rename(animationsChanged) spine::AnimationState::_animationsChanged; +%rename(trackEntryPool) spine::AnimationState::_trackEntryPool; +%rename(listener) spine::TrackEntry::_listener; +%rename(nextAnimationLast) spine::TrackEntry::_nextAnimationLast; +%rename(trackLast) spine::TrackEntry::_trackLast; +%rename(nextTrackLast) spine::TrackEntry::_nextTrackLast; +%rename(interruptAlpha) spine::TrackEntry::_interruptAlpha; +%rename(totalAlpha) spine::TrackEntry::_totalAlpha; +%rename(timelineMode) spine::TrackEntry::_timelineMode; +%rename(timelineHoldMix) spine::TrackEntry::_timelineHoldMix; +%rename(timelinesRotation) spine::TrackEntry::_timelinesRotation; +%rename(drainDisabled) spine::EventQueue::_drainDisabled; +%rename(animState) spine::EventQueue::_state; +%rename(setMixWith) spine::AnimationStateData::setMix; +%rename(TextureAtlas) spine::Atlas; +%rename(sorted) spine::Bone::_sorted; +%rename(spaces) spine::PathConstraint::_spaces; +%rename(positions) spine::PathConstraint::_positions; +%rename(world) spine::PathConstraint::_world; +%rename(curves) spine::PathConstraint::_curves; +%rename(lengths) spine::PathConstraint::_lengths; +%rename(segments) spine::PathConstraint::_segments; +%rename(attachmentLoader) spine::SkeletonBinary::_attachmentLoader; +%rename(minX) spine::SkeletonBounds::_minX; +%rename(minY) spine::SkeletonBounds::_minY; +%rename(maxX) spine::SkeletonBounds::_maxX; +%rename(maxY) spine::SkeletonBounds::_maxY; +%rename(boundingBoxes) spine::SkeletonBounds::_boundingBoxes; +%rename(polygons) spine::SkeletonBounds::_polygons; +%rename(attachmentLoader) spine::SkeletonJson::_attachmentLoader; +%rename(JitterEffect) spine::JitterVertexEffect; +%rename(SwirlEffect) spine::SwirlVertexEffect; +%rename(setSkinByName) spine::Skeleton::setSkin(const String &); +%rename(slotIndex) spine::Skin::AttachmentMap::Entry::_slotIndex; +%rename(name) spine::Skin::AttachmentMap::Entry::_name; +%rename(attachment) spine::Skin::AttachmentMap::Entry::_attachment; + // ----- Module Macro Section ------ // Brief: Generated code should be wrapped inside a macro // Usage: @@ -243,6 +233,300 @@ using namespace spine; // 4. 'Attribute Section' should be placed before 'Import Section' and 'Include Section' // +%attribute(spine::Animation, spine::String&, name, getName); +%attribute(spine::Animation, spine::Vector&, timelines, getTimelines); +%attribute(spine::Animation, float, duration, getDuration, setDuration); + +%attribute(spine::RotateTimeline, int, boneIndex, getBoneIndex, setBoneIndex); +%attribute(spine::RotateTimeline, spine::Vector&, frames, getFrames); + +%attribute(spine::ColorTimeline, int, slotIndex, getSlotIndex, setSlotIndex); +%attribute(spine::ColorTimeline, spine::Vector&, frames, getFrames); + +%attribute(spine::TwoColorTimeline, int, slotIndex, getSlotIndex, setSlotIndex); + +%attribute(spine::AttachmentTimeline, size_t, slotIndex, getSlotIndex, setSlotIndex); +%attribute(spine::AttachmentTimeline, spine::Vector&, frames, getFrames); +%attribute(spine::AttachmentTimeline, spine::Vector&, attachmentNames, getAttachmentNames); + +%attribute(spine::DeformTimeline, int, slotIndex, getSlotIndex, setSlotIndex); +%attribute(spine::DeformTimeline, spine::Vector&, frames, getFrames); +%attribute(spine::DeformTimeline, spine::Vector&, frameVertices, getVertices); +%attribute(spine::DeformTimeline, spine::VertexAttachment*, attachment, getAttachment); + +%attribute(spine::EventTimeline, spine::Vector, frames, getFrames); +%attribute(spine::EventTimeline, spine::Vector&, events, getEvents); + +%attribute(spine::DrawOrderTimeline, spine::Vector&, frames, getFrames); +%attribute(spine::DrawOrderTimeline, spine::Vector>&, drawOrders, getDrawOrders); + +%attribute(spine::AnimationState, spine::AnimationStateData*, data, getData); +%attribute(spine::AnimationState, spine::Vector&, tracks, getTracks); +%attribute(spine::AnimationState, float, timeScale, getTimeScale, setTimeScale); + +%attribute(spine::TrackEntry, spine::Animation*, animation, getAnimation); +%attribute(spine::TrackEntry, spine::TrackEntry*, next, getNext); +%attribute(spine::TrackEntry, spine::TrackEntry*, mixingFrom, getMixingFrom); +%attribute(spine::TrackEntry, spine::TrackEntry*, mixingTo, getMixingTo); +%attribute(spine::TrackEntry, int, trackIndex, getTrackIndex); +%attribute(spine::TrackEntry, bool, loop, getLoop, setLoop); +%attribute(spine::TrackEntry, bool, holdPrevious, getHoldPrevious, setHoldPrevious); +%attribute(spine::TrackEntry, float, eventThreshold, getEventThreshold, setEventThreshold); +%attribute(spine::TrackEntry, float, attachmentThreshold, getAttachmentThreshold, setAttachmentThreshold); +%attribute(spine::TrackEntry, float, drawOrderThreshold, getDrawOrderThreshold, setDrawOrderThreshold); +%attribute(spine::TrackEntry, float, animationStart, getAnimationStart, setAnimationStart); +%attribute(spine::TrackEntry, float, animationEnd, getAnimationEnd, setAnimationEnd); +%attribute(spine::TrackEntry, float, animationLast, getAnimationLast, setAnimationLast); +%attribute(spine::TrackEntry, float, delay, getDelay, setDelay); +%attribute(spine::TrackEntry, float, trackTime, getTrackTime, setTrackTime); +%attribute(spine::TrackEntry, float, trackEnd, getTrackEnd, setTrackEnd); +%attribute(spine::TrackEntry, float, timeScale, getTimeScale, setTimeScale); +%attribute(spine::TrackEntry, float, alpha, getAlpha, setAlpha); +%attribute(spine::TrackEntry, float, mixTime, getMixTime, setMixTime); +%attribute(spine::TrackEntry, float, mixDuration, getMixDuration, setMixDuration); +%attribute(spine::TrackEntry, spine::MixBlend, mixBlend, getMixBlend, setMixBlend); + +%attribute(spine::AnimationStateData, spine::SkeletonData*, skeletonData, getSkeletonData); +%attribute(spine::AnimationStateData, float, defaultMix, getDefaultMix, setDefaultMix); + +%attribute(spine::Bone, spine::BoneData&, data, getData); +%attribute(spine::Bone, spine::Skeleton&, skeleton, getSkeleton); +%attribute(spine::Bone, spine::Bone*, parent, getParent); +%attribute(spine::Bone, spine::Vector&, children, getChildren); +%attribute(spine::Bone, float, x, getX, setX); +%attribute(spine::Bone, float, y, getY, setY); +%attribute(spine::Bone, float, rotation, getRotation, setRotation); +%attribute(spine::Bone, float, scaleX, getScaleX, setScaleX); +%attribute(spine::Bone, float, scaleY, getScaleY, setScaleY); +%attribute(spine::Bone, float, shearX, getShearX, setShearX); +%attribute(spine::Bone, float, shearY, getShearY, setShearY); +%attribute(spine::Bone, float, ax, getAX, setAX); +%attribute(spine::Bone, float, ay, getAY, setAY); +%attribute(spine::Bone, float, arotation, getAppliedRotation, setAppliedRotation); +%attribute(spine::Bone, float, ascaleX, getAScaleX, setAScaleX); +%attribute(spine::Bone, float, ascaleY, getAScaleY, setAScaleY); +%attribute(spine::Bone, float, ashearX, getAShearX, setAShearX); +%attribute(spine::Bone, float, ashearY, getAShearY, setAShearY); +%attribute(spine::Bone, bool, appliedValid, isAppliedValid, setAppliedValid); +%attribute(spine::Bone, float, a, getA, setA); +%attribute(spine::Bone, float, b, getB, setB); +%attribute(spine::Bone, float, c, getC, setC); +%attribute(spine::Bone, float, d, getD, setD); +%attribute(spine::Bone, float, worldX, getWorldX, setWorldX); +%attribute(spine::Bone, float, worldY, getWorldY, setWorldY); +%attribute(spine::Bone, bool, active, isActive, setActive); + +%attribute(spine::BoneData, int, index, getIndex); +%attribute(spine::BoneData, spine::String&, name, getName); +%attribute(spine::BoneData, spine::BoneData*, parent, getParent); +%attribute(spine::BoneData, float, length, getLength, setLength); +%attribute(spine::BoneData, float, x, getX, setX); +%attribute(spine::BoneData, float, y, getY, setY); +%attribute(spine::BoneData, float, rotation, getRotation, setRotation); +%attribute(spine::BoneData, float, scaleX, getScaleX, setScaleX); +%attribute(spine::BoneData, float, scaleY, getScaleY, setScaleY); +%attribute(spine::BoneData, float, shearX, getShearX, setShearX); +%attribute(spine::BoneData, float, shearY, getShearY, setShearY); +%attribute(spine::BoneData, spine::TransformMode, transformMode, getTransformMode, setTransformMode); +%attribute(spine::BoneData, bool, skinRequired, isSkinRequired, setSkinRequired); + +%attribute(spine::ConstraintData, spine::String&, name, getName); +%attribute(spine::ConstraintData, size_t, order, getOrder, setOrder); +%attribute(spine::ConstraintData, bool, skinRequired, isSkinRequired, setSkinRequired); + +%attribute(spine::Event, spine::EventData&, data, getData); +%attribute(spine::Event, int, intValue, getIntValue, setIntValue); +%attribute(spine::Event, float, floatValue, getFloatValue, setFloatValue); +%attribute(spine::Event, spine::String&, stringValue, getStringValue, setStringValue); +%attribute(spine::Event, float, time, getTime); +%attribute(spine::Event, float, volume, getVolume, setVolume); +%attribute(spine::Event, float, balance, getBalance, setBalance); + +%attribute(spine::EventData, spine::String&, name, getName); +%attribute(spine::EventData, int, intValue, getIntValue, setIntValue); +%attribute(spine::EventData, float, floatValue, getFloatValue, setFloatValue); +%attribute(spine::EventData, spine::String&, stringValue, getStringValue, setStringValue); +%attribute(spine::EventData, float, volume, getVolume, setVolume); +%attribute(spine::EventData, float, balance, getBalance, setBalance); +%attribute(spine::EventData, spine::String&, audioPath, getAudioPath, setAudioPath); + +%attribute(spine::IkConstraint, spine::IkConstraintData&, data, getData); +%attribute(spine::IkConstraint, spine::Vector&, bones, getBones); +%attribute(spine::IkConstraint, spine::Bone*, target, getTarget, setTarget); +%attribute(spine::IkConstraint, int, bendDirection, getBendDirection, setBendDirection); +%attribute(spine::IkConstraint, bool, compress, getCompress, setCompress); +%attribute(spine::IkConstraint, bool, stretch, getStretch, setStretch); +%attribute(spine::IkConstraint, float, mix, getMix, setMix); +%attribute(spine::IkConstraint, float, softness, getSoftness, setSoftness); +%attribute(spine::IkConstraint, bool, active, isActive, setActive); + +%attribute(spine::IkConstraintData, spine::Vector&, bones, getBones); +%attribute(spine::IkConstraintData, spine::BoneData*, target, getTarget); +%attribute(spine::IkConstraintData, int, bendDirection, getBendDirection, setBendDirection); +%attribute(spine::IkConstraintData, bool, compress, getCompress, setCompress); +%attribute(spine::IkConstraintData, bool, stretch, getStretch, setStretch); +%attribute(spine::IkConstraintData, bool, uniform, getUniform, setUniform); +%attribute(spine::IkConstraintData, float, mix, getMix, setMix); +%attribute(spine::IkConstraintData, float, softness, getSoftness, setSoftness); + +%attribute(spine::PathConstraint, spine::PathConstraintData&, data, getData); +%attribute(spine::PathConstraint, spine::Vector&, bones, getBones); +%attribute(spine::PathConstraint, spine::Slot*, target, getTarget, setTarget); +%attribute(spine::PathConstraint, float, position, getPosition, setPosition); +%attribute(spine::PathConstraint, float, spacing, getSpacing, setSpacing); +%attribute(spine::PathConstraint, float, rotateMix, getRotateMix, setRotateMix); +%attribute(spine::PathConstraint, float, translateMix, getTranslateMix, setTranslateMix); +%attribute(spine::PathConstraint, bool, active, isActive, setActive); + +%attribute(spine::PathConstraintData, spine::Vector&, bones, getBones); +%attribute(spine::PathConstraintData, spine::SlotData*, target, getTarget, setTarget); +%attribute(spine::PathConstraintData, spine::PositionMode, positionMode, getPositionMode, setPositionMode); +%attribute(spine::PathConstraintData, spine::SpacingMode, spacingMode, getSpacingMode, setSpacingMode); +%attribute(spine::PathConstraintData, spine::RotateMode, rotateMode, getRotateMode, setRotateMode); +%attribute(spine::PathConstraintData, float, offsetRotation, getOffsetRotation, setOffsetRotation); +%attribute(spine::PathConstraintData, float, position, getPosition, setPosition); +%attribute(spine::PathConstraintData, float, spacing, getSpacing, setSpacing); +%attribute(spine::PathConstraintData, float, rotateMix, getRotateMix, setRotateMix); +%attribute(spine::PathConstraintData, float, translateMix, getTranslateMix, setTranslateMix); + +%attribute(spine::Skeleton, spine::SkeletonData*, data, getData); +%attribute(spine::Skeleton, spine::Vector&, bones, getBones); +%attribute(spine::Skeleton, spine::Vector&, slots, getSlots); +%attribute(spine::Skeleton, spine::Vector&, drawOrder, getDrawOrder); +%attribute(spine::Skeleton, spine::Vector&, ikConstraints, getIkConstraints); +%attribute(spine::Skeleton, spine::Vector&, transformConstraints, getTransformConstraints); +%attribute(spine::Skeleton, spine::Vector&, pathConstraints, getPathConstraints); +%attribute(spine::Skeleton, spine::Vector&, _updateCache, getUpdateCacheList); +%attribute(spine::Skeleton, spine::Skin*, skin, getSkin, setSkin); +%attribute(spine::Skeleton, spine::Color&, color, getColor); +%attribute(spine::Skeleton, float, time, getTime, setTime); +%attribute(spine::Skeleton, float, scaleX, getScaleX, setScaleX); +%attribute(spine::Skeleton, float, scaleY, getScaleY, setScaleY); +%attribute(spine::Skeleton, float, x, getX, setX); +%attribute(spine::Skeleton, float, y, getY, setY); + +%attribute(spine::SkeletonBinary, float, scale, setScale); + +%attribute(spine::SkeletonClipping, spine::Vector&, clippedVertices, getClippedVertices); +%attribute(spine::SkeletonClipping, spine::Vector&, clippedTriangles, getClippedTriangles); + +%attribute(spine::SkeletonData, spine::String&, name, getName, setName); +%attribute(spine::SkeletonData, spine::Vector&, bones, getBones); +%attribute(spine::SkeletonData, spine::Vector&, slots, getSlots); +%attribute(spine::SkeletonData, spine::Vector&, skins, getSkins); +%attribute(spine::SkeletonData, spine::Skin*, defaultSkin, getDefaultSkin, setDefaultSkin); +%attribute(spine::SkeletonData, spine::Vector&, events, getEvents); +%attribute(spine::SkeletonData, spine::Vector&, animations, getAnimations); +%attribute(spine::SkeletonData, spine::Vector&, ikConstraints, getIkConstraints); +%attribute(spine::SkeletonData, spine::Vector&, transformConstraints, getTransformConstraints); +%attribute(spine::SkeletonData, spine::Vector&, pathConstraints, getPathConstraints); +%attribute(spine::SkeletonData, float, x, getX, setX); +%attribute(spine::SkeletonData, float, y, getY, setY); +%attribute(spine::SkeletonData, float, width, getWidth, setWidth); +%attribute(spine::SkeletonData, float, height, getHeight, setHeight); +%attribute(spine::SkeletonData, spine::String&, version, getVersion, setVersion); +%attribute(spine::SkeletonData, spine::String&, hash, getHash, setHash); +%attribute(spine::SkeletonData, float, fps, getFps, setFps); +%attribute(spine::SkeletonData, spine::String&, imagesPath, getImagesPath, setImagesPath); +%attribute(spine::SkeletonData, spine::String&, audioPath, getAudioPath, setAudioPath); + +%attribute(spine::SkeletonJson, float, scale, setScale); + +%attribute(spine::Skin, spine::String&, name, getName); +%attribute(spine::Skin, spine::Vector&, bones, getBones); +%attribute(spine::Skin, spine::Vector&, constraints, getConstraints); + +%attribute(spine::Slot, spine::SlotData&, data, getData); +%attribute(spine::Slot, spine::Bone&, bone, getBone); +%attribute(spine::Slot, spine::Color&, color, getColor); +%attribute(spine::Slot, spine::Color&, darkColor, getDarkColor); +%attribute(spine::Slot, spine::Attachment*, attachment, getAttachment, setAttachment); +%attribute(spine::Slot, spine::Vector&, deform, getDeform); + +%attribute(spine::SlotData, int, index, getIndex); +%attribute(spine::SlotData, spine::String&, name, getName); +%attribute(spine::SlotData, spine::BoneData&, boneData, getBoneData); +%attribute(spine::SlotData, spine::Color&, color, getColor); +%attribute(spine::SlotData, spine::Color&, darkColor, getDarkColor); +%attribute(spine::SlotData, spine::String&, attachmentName, getAttachmentName, setAttachmentName); +%attribute(spine::SlotData, spine::BlendMode, blendMode, getBlendMode, setBlendMode); + +%attribute(spine::TransformConstraint, spine::TransformConstraintData&, data, getData); +%attribute(spine::TransformConstraint, spine::Vector&, bones, getBones); +%attribute(spine::TransformConstraint, spine::Bone*, target, getTarget, setTarget); +%attribute(spine::TransformConstraint, float, rotateMix, getRotateMix, setRotateMix); +%attribute(spine::TransformConstraint, float, translateMix, getTranslateMix, setTranslateMix); +%attribute(spine::TransformConstraint, float, scaleMix, getScaleMix, setScaleMix); +%attribute(spine::TransformConstraint, float, shearMix, getShearMix, setShearMix); +%attribute(spine::TransformConstraint, bool, active, isActive, setActive); + +%attribute(spine::TransformConstraintData, spine::Vector&, bones, getBones); +%attribute(spine::TransformConstraintData, spine::BoneData*, target, getTarget); +%attribute(spine::TransformConstraintData, float, rotateMix, getRotateMix); +%attribute(spine::TransformConstraintData, float, translateMix, getTranslateMix); +%attribute(spine::TransformConstraintData, float, scaleMix, getScaleMix); +%attribute(spine::TransformConstraintData, float, shearMix, getShearMix); +%attribute(spine::TransformConstraintData, float, offsetRotation, getOffsetRotation); +%attribute(spine::TransformConstraintData, float, offsetX, getOffsetX); +%attribute(spine::TransformConstraintData, float, offsetY, getOffsetY); +%attribute(spine::TransformConstraintData, float, offsetScaleX, getOffsetScaleX); +%attribute(spine::TransformConstraintData, float, offsetScaleY, getOffsetScaleY); +%attribute(spine::TransformConstraintData, float, offsetShearY, getOffsetShearY); +%attribute(spine::TransformConstraintData, bool, relative, isRelative); +%attribute(spine::TransformConstraintData, bool, local, isLocal); + +%attribute(spine::Attachment, spine::String&, name, getName); + +%attribute(spine::VertexAttachment, int, id, getId); +%attribute(spine::VertexAttachment, spine::Vector&, bones, getBones); +%attribute(spine::VertexAttachment, spine::Vector&, vertices, getVertices); +%attribute(spine::VertexAttachment, size_t, worldVerticesLength, getWorldVerticesLength, setWorldVerticesLength); +%attribute(spine::VertexAttachment, spine::VertexAttachment*, deformAttachment, getDeformAttachment, setDeformAttachment); + +%attribute(spine::ClippingAttachment, spine::SlotData*, endSlot, getEndSlot, setEndSlot); + +%attribute(spine::MeshAttachment, spine::String&, path, getPath, setPath); +%attribute(spine::MeshAttachment, spine::Vector&, regionUVs, getRegionUVs); +%attribute(spine::MeshAttachment, spine::Vector&, uvs, getUVs); +%attribute(spine::MeshAttachment, spine::Vector&, triangles, getTriangles); +%attribute(spine::MeshAttachment, spine::Color&, color, getColor); +%attribute(spine::MeshAttachment, float, width, getWidth, setWidth); +%attribute(spine::MeshAttachment, float, height, getHeight, setHeight); +%attribute(spine::MeshAttachment, int, hullLength, getHullLength, setHullLength); +%attribute(spine::MeshAttachment, spine::Vector&, edges, getEdges); + +%attribute(spine::PathAttachment, spine::Vector&, lengths, getLengths); +%attribute(spine::PathAttachment, bool, closed, isClosed, setClosed); +%attribute(spine::PathAttachment, bool, constantSpeed, isConstantSpeed, setConstantSpeed); + +%attribute(spine::PointAttachment, float, x, getX, setX); +%attribute(spine::PointAttachment, float, y, getY, setY); +%attribute(spine::PointAttachment, float, rotation, getRotation, setRotation); + +%attribute(spine::RegionAttachment, float, x, getX, setX); +%attribute(spine::RegionAttachment, float, y, getY, setY); +%attribute(spine::RegionAttachment, float, scaleX, getScaleX, setScaleX); +%attribute(spine::RegionAttachment, float, scaleY, getScaleY, setScaleY); +%attribute(spine::RegionAttachment, float, rotation, getRotation, setRotation); +%attribute(spine::RegionAttachment, float, width, getWidth, setWidth); +%attribute(spine::RegionAttachment, float, height, getHeight, setHeight); +%attribute(spine::RegionAttachment, spine::Color&, color, getColor); +%attribute(spine::RegionAttachment, spine::String&, path, getPath, setPath); +%attribute(spine::RegionAttachment, void*, rendererObject, getRendererObject, setRendererObject); +%attribute(spine::RegionAttachment, spine::Vector&, offset, getOffset); +%attribute(spine::RegionAttachment, spine::Vector&, uvs, getUVs); + +%attribute(spine::JitterVertexEffect, float, jitterX, getJitterX, setJitterX); +%attribute(spine::JitterVertexEffect, float, jitterY, getJitterY, setJitterY); + +%attribute(spine::SwirlVertexEffect, float, centerX, getCenterX, setCenterX); +%attribute(spine::SwirlVertexEffect, float, centerY, getCenterY, setCenterY); +%attribute(spine::SwirlVertexEffect, float, radius, getRadius, setRadius); +%attribute(spine::SwirlVertexEffect, float, angle, getAngle, setAngle); + +%attribute(spine::Vector2, float, x, getX, setX); +%attribute(spine::Vector2, float, y, getY, setY); + // ----- Import Section ------ // Brief: Import header files which are depended by 'Include Section' // Note: @@ -257,6 +541,7 @@ using namespace spine; // ----- Include Section ------ // Brief: Include header files in which classes and methods will be bound +%include "editor-support/spine/MathUtil.h" %include "editor-support/spine/MixBlend.h" %include "editor-support/spine/MixDirection.h" %include "editor-support/spine/TransformMode.h" @@ -318,4 +603,146 @@ using namespace spine; %include "editor-support/spine-creator-support/SkeletonAnimation.h" %include "editor-support/spine-creator-support/SkeletonDataMgr.h" %include "editor-support/spine-creator-support/SkeletonCacheAnimation.h" -%include "editor-support/spine-creator-support/SkeletonCacheMgr.h" \ No newline at end of file +%include "editor-support/spine-creator-support/SkeletonCacheMgr.h" + +%extend spine::IkConstraint { + void apply1(Bone *bone, float targetX, float targetY, bool compress, bool stretch, bool uniform, float alpha) { + IkConstraint::apply(*bone, targetX, targetY, compress, stretch, uniform, alpha); + } + + void apply2(Bone *parent, Bone *child, float targetX, float targetY, int bendDir, bool stretch, float softness, float alpha) { + IkConstraint::apply(*parent, *child, targetX, targetY, bendDir, stretch, softness, alpha); + } +}; + +%extend spine::Bone { + Bone(spine::BoneData *data, spine::Skeleton *skeleton, spine::Bone *parent) { + return new Bone(*data, *skeleton, parent); + } + + void updateWorldTransformWith(float x, float y, float rotation, float scaleX, float scaleY, float shearX, float shearY) { + $self->updateWorldTransform(x, y, rotation, scaleX, scaleY, shearX, shearY); + } +} + +%extend spine::Slot { + Slot(spine::SlotData *data, spine::Bone *bone) { + return new Slot(*data, *bone); + } +} + +%extend spine::Timeline { + void apply(spine::Skeleton *skeleton, float lastTime, float time, const ccstd::vector& events, float alpha, spine::MixBlend blend, spine::MixDirection direction) { + spine::Vector spEvents; + for (int i = 0; i < events.size(); ++i) { + spEvents.add(events[i]); + } + $self->apply(*skeleton, lastTime, time, &spEvents, alpha, blend, direction); + } +} + +%extend spine::AnimationState { + void apply(spine::Skeleton* skeleton) { + $self->apply(*skeleton); + } +} + +%extend spine::Animation { + void apply(spine::Skeleton *skeleton, float lastTime, float time, bool loop, const ccstd::vector& events, float alpha, spine::MixBlend blend, spine::MixDirection direction) { + spine::Vector spEvents; + for (int i = 0; i < events.size(); ++i) { + spEvents.add(events[i]); + } + $self->apply(*skeleton, lastTime, time, loop, &spEvents, alpha, blend, direction); + } +} + +%extend spine::Event { + Event(float time, spine::EventData *data) { + return new Event(time, *data); + } +} + +%extend spine::IkConstraint { + IkConstraint(spine::IkConstraintData *data, spine::Skeleton *skeleton) { + return new IkConstraint(*data, *skeleton); + } +} + +%extend spine::PathConstraint { + PathConstraint(spine::PathConstraintData* data, spine::Skeleton* skeleton) { + return new PathConstraint(*data, *skeleton); + } +} + +%extend spine::PointAttachment { + float computeWorldRotation(spine::Bone* bone) { + return $self->computeWorldRotation(*bone); + } +} + +%extend spine::SkeletonBounds { + void update(spine::Skeleton* skeleton, bool updateAabb) { + $self->update(*skeleton, updateAabb); + } +} + +%extend spine::TransformConstraint { + TransformConstraint(spine::TransformConstraintData* data, spine::Skeleton* skeleton) { + return new TransformConstraint(*data, *skeleton); + } +} + +%extend spine::SlotData { + SlotData(int index, const ccstd::string *name, spine::BoneData *boneData) { + spine::String spName(name->data()); + return new SlotData(index, spName, *boneData); + } +} + +%extend spine::VertexEffect { + void begin(spine::Skeleton *skeleton) { + $self->begin(*skeleton); + } +} + +%extend spine::SwirlVertexEffect { + SwirlVertexEffect(float radius, spine::Interpolation *interpolation) { + return new SwirlVertexEffect(radius, *interpolation); + } +} + +%extend spine::DeformTimeline { + void setFrame(int frameIndex, float time, const ccstd::vector& vertices) { + spine::Vector spVertices; + for (int i = 0; i < vertices.size(); ++i) { + spVertices.add(vertices[i]); + } + $self->setFrame(frameIndex, time, spVertices); + } +} + +%extend spine::DrawOrderTimeline { + void setFrame(size_t frameIndex, float time, const ccstd::vector& drawOrder) { + spine::Vector spDrawOrder; + spDrawOrder.ensureCapacity(drawOrder.size()); + for (int i = 0; i < drawOrder.size(); ++i) { + spDrawOrder.add(drawOrder[i]); + } + $self->setFrame(frameIndex, time, spDrawOrder); + } +} + +%extend spine::Color { + spine::Color &setFromColor(const spine::Color &other) { + return $self->set(other); + } +} + +%extend spine::Skeleton { + spine::Attachment &getAttachmentByName(const std::string &slotName, const std::string &attachmentName) { + spine::String slot(slotName.data()); + spine::String attachment(attachmentName.data()); + return *($self->getAttachment(slot, attachment)); + } +} \ No newline at end of file diff --git a/platforms/native/engine/jsb-spine-skeleton.js b/platforms/native/engine/jsb-spine-skeleton.js index ae233945e23..10e1bacf9a6 100644 --- a/platforms/native/engine/jsb-spine-skeleton.js +++ b/platforms/native/engine/jsb-spine-skeleton.js @@ -133,8 +133,8 @@ const cacheManager = require('./jsb-cache-manager'); } this._skeletonCache = spine.initSkeletonData(uuid, filePath, atlasText, jsbTextures, this.scale); if (this._skeletonCache) { - this.width = this._skeletonCache.getWidth(); - this.height = this._skeletonCache.getHeight(); + this.width = this._skeletonCache.width; + this.height = this._skeletonCache.height; } }; From c04f35599c2e5c8302239ae7df15152232d65bbb Mon Sep 17 00:00:00 2001 From: Zeqiang Li Date: Fri, 11 Aug 2023 16:06:12 +0800 Subject: [PATCH 130/232] Merge branch 'v3.8.1-pipeline' of github.com:star-e/engine into v3.8.1-pipeline (#15930) --- native/cocos/renderer/gfx-base/GFXBarrier.cpp | 16 ++--- .../pipeline/custom/FrameGraphDispatcher.cpp | 61 +++++++++++++------ 2 files changed, 53 insertions(+), 24 deletions(-) diff --git a/native/cocos/renderer/gfx-base/GFXBarrier.cpp b/native/cocos/renderer/gfx-base/GFXBarrier.cpp index 688c9a42612..b495fd4d031 100644 --- a/native/cocos/renderer/gfx-base/GFXBarrier.cpp +++ b/native/cocos/renderer/gfx-base/GFXBarrier.cpp @@ -270,7 +270,7 @@ constexpr AccessElem ACCESS_MAP[] = { // ACCESS_READ | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA, // AccessFlags::COLOR_ATTACHMENT_READ}, - {CARE_MEMACCESS | CARE_RESTYPE | CARE_CMNUSAGE, + {CARE_MEMACCESS | CARE_RESTYPE | CARE_CMNUSAGE | CARE_SHADERSTAGE, ACCESS_READ | RES_TEXTURE | CMN_VB_OR_DS | CMN_ROM, AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ}, @@ -280,12 +280,14 @@ constexpr AccessElem ACCESS_MAP[] = { {IGNORE_MEMUSAGE, ACCESS_READ | RES_TEXTURE | SHADERSTAGE_COMP | CMN_ROM, - AccessFlags::COMPUTE_SHADER_READ_TEXTURE}, + AccessFlags::COMPUTE_SHADER_READ_TEXTURE, + CMN_VB_OR_DS}, // shading rate has its own flag {CARE_MEMACCESS | CARE_SHADERSTAGE | CARE_CMNUSAGE, ACCESS_READ | SHADERSTAGE_COMP | CMN_STORAGE, - AccessFlags::COMPUTE_SHADER_READ_OTHER}, + AccessFlags::COMPUTE_SHADER_READ_OTHER, + RES_TEXTURE | CMN_ROM}, {CARE_MEMACCESS | CARE_CMNUSAGE, ACCESS_READ | CMN_COPY_SRC, @@ -350,10 +352,10 @@ constexpr bool validateAccess(ResourceType type, CommonUsage usage, MemoryAccess res = !(*std::max_element(std::begin(conflicts), std::end(conflicts))); } else if (type == ResourceType::TEXTURE) { uint32_t conflicts[] = { - hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::VB_OR_DS | CommonUsage::INDIRECT_OR_INPUT) && !hasFlag(visibility, ShaderStageFlags::FRAGMENT), // color/ds/input not in fragment - hasFlag(usage, CommonUsage::INDIRECT_OR_INPUT) && !hasFlag(access, MemoryAccess::READ_ONLY), // input needs read - hasAllFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::STORAGE), // storage ^ sampled - hasFlag(usage, CommonUsage::COPY_SRC) && !hasAllFlags(MemoryAccess::READ_ONLY, access), // transfer src ==> read_only + // hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::VB_OR_DS | CommonUsage::INDIRECT_OR_INPUT) && !hasFlag(visibility, ShaderStageFlags::FRAGMENT), // color/ds/input not in fragment + hasFlag(usage, CommonUsage::INDIRECT_OR_INPUT) && !hasFlag(access, MemoryAccess::READ_ONLY), // input needs read + hasAllFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::STORAGE), // storage ^ sampled + hasFlag(usage, CommonUsage::COPY_SRC) && !hasAllFlags(MemoryAccess::READ_ONLY, access), // transfer src ==> read_only hasFlag(usage, CommonUsage::COPY_DST) && !hasAllFlags(MemoryAccess::WRITE_ONLY, access), hasFlag(usage, CommonUsage::INDIRECT_OR_INPUT) && !hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::VB_OR_DS), // input needs to specify color or ds // transfer dst ==> write_only hasAllFlags(usage, CommonUsage::COPY_SRC | CommonUsage::COPY_DST), // both src and dst diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index d18121f8761..60babdea94f 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -143,6 +143,11 @@ ResourceGraph::vertex_descriptor FrameGraphDispatcher::realResourceID(const ccst return subresName; } + auto namedID = findVertex(resName, resg); + if (parent(namedID, resg) == ResourceGraph::null_vertex()) { + return resName; + } + // array if (desc.dimension == ResourceDimension::TEXTURE2D && desc.depthOrArraySize > 1) { ccstd::pmr::set leaves(scratch); @@ -188,6 +193,21 @@ ResourceGraph::vertex_descriptor locateSubres(const ccstd::pmr::string& originNa return findVertex(resName, resg); } +ResourceGraph::vertex_descriptor locateSubres(const ccstd::pmr::string &originName, + const ResourceGraph &resg, + uint32_t basePlane, + const ResourceAccessGraph& rag, + boost::container::pmr::memory_resource *scratch) { + auto originID = findVertex(originName, resg); + if (rag.movedSourceStatus.find(originName) != rag.movedSourceStatus.end()) { + return rag.resourceIndex.at(originName); + } + + const auto &resName = getSubresNameByPlane(originName, basePlane, resg, scratch); + return findVertex(resName, resg); +} + + PmrFlatMap FrameGraphDispatcher::buildDescriptorIndex( const PmrTransparentMap> &computeViews, boost::container::pmr::memory_resource *scratch) const { @@ -200,7 +220,7 @@ PmrFlatMap FrameGraphDispatcher:: const auto &name = computeView.name; CC_EXPECTS(!name.empty()); const auto nameID = layoutGraph.attributeIndex.at(name); - auto subresID = locateSubres(resName, resourceGraph, computeView.plane, scratch); + auto subresID = locateSubres(resName, resourceGraph, computeView.plane, resourceAccessGraph, scratch); resourceIndex.emplace(nameID, subresID); } } @@ -1448,6 +1468,8 @@ bool moveValidation(const MovePass& pass, ResourceAccessGraph& rag, const Resour } } + auto safeShift = [](uint32_t num, uint8_t bit) { return std::max(1u, num >> bit); }; + rangeCheck(rag.movedTargetStatus[toResName], toResDesc, toResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); uint32_t validConditions[] = { !fromResTraits.hasSideEffects(), @@ -1455,13 +1477,13 @@ bool moveValidation(const MovePass& pass, ResourceAccessGraph& rag, const Resour rag.movedSourceStatus.find(fromResName) == rag.movedSourceStatus.end(), fromResTraits.residency != ResourceResidency::MEMORYLESS && toResTraits.residency != ResourceResidency::MEMORYLESS, fromResDesc.dimension == toResDesc.dimension, - fromResDesc.width == toResDesc.width, - fromResDesc.height == toResDesc.height, + fromResDesc.width == safeShift(toResDesc.width, movePair.targetMostDetailedMip), + fromResDesc.height == safeShift(toResDesc.height, movePair.targetMostDetailedMip), fromResDesc.format == toResDesc.format, fromResDesc.sampleCount == toResDesc.sampleCount, (fromResDesc.depthOrArraySize == toResDesc.depthOrArraySize) || (toResDesc.dimension != ResourceDimension::BUFFER), // full move if resource is buffer }; - bool val = std::min_element(std::begin(validConditions), std::end(validConditions)); + bool val = *std::min_element(std::begin(validConditions), std::end(validConditions)); check &= val; } @@ -1535,7 +1557,11 @@ void startMovePass(const Graphs &graphs, uint32_t passID, const MovePass &pass) auto lastStatusIter = resourceAccessGraph.resourceAccess.at(pair.source).rbegin(); resourceAccessGraph.movedSourceStatus.emplace(pair.source, AccessStatus{lastStatusIter->second.accessFlag, srcResourceRange}); resourceAccessGraph.movedTarget[pair.target].emplace(getSubresourceNameByRange(srcResourceRange, resourceAccessGraph.resource()), pair.source); - resourceAccessGraph.resourceAccess[pair.target] = resourceAccessGraph.resourceAccess[pair.source]; + + const auto &srcAccess = resourceAccessGraph.resourceAccess.at(pair.source); + auto &targetAccess = resourceAccessGraph.resourceAccess[pair.target]; + targetAccess.clear(); + targetAccess.emplace(*srcAccess.rbegin()); auto targetResID = findVertex(pair.target, resourceGraph); resourceAccessGraph.resourceIndex[pair.target] = targetResID; @@ -1846,12 +1872,9 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { // : or no extra barrier needed. for (auto &accessPair : rag.resourceAccess) { const auto &resName = accessPair.first; - if (rag.movedSourceStatus.find(resName) != rag.movedSourceStatus.end()) { - // moved, history of this resource access will be copied to moved target. - continue; - } - const auto &resID = findVertex(resName, resourceGraph); + auto resID = findVertex(resName, resourceGraph); + auto realResourceID = resID; const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); bool isBuffer = desc.dimension == ResourceDimension::BUFFER; @@ -1908,11 +1931,15 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { continue; } + if (rag.movedSourceStatus.find(resName) != rag.movedSourceStatus.end()) { + realResourceID = rag.resourceIndex.at(resName); + } + // undefined access - if (iter == accessRecord.begin()) { + if (srcRagVertID == 0) { auto &dstBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, dstRagVertID); auto &firstMeetBarrier = dstBarrierNode.frontBarriers.emplace_back(); - firstMeetBarrier.resourceID = resID; + firstMeetBarrier.resourceID = realResourceID; firstMeetBarrier.type = gfx::BarrierType::FULL; firstMeetBarrier.beginVert = dstPassID; firstMeetBarrier.endVert = dstPassID; @@ -1922,7 +1949,7 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { } else if (accessDependent(iter->second.accessFlag, nextIter->second.accessFlag, isBuffer)) { auto &srcBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, srcRagVertID); auto &beginBarrier = srcBarrierNode.rearBarriers.emplace_back(); - beginBarrier.resourceID = resID; + beginBarrier.resourceID = realResourceID; beginBarrier.beginVert = srcPassID; beginBarrier.endVert = dstPassID; beginBarrier.beginStatus = iter->second; @@ -1934,7 +1961,7 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { auto &dstBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, dstRagVertID); auto &endBarrier = dstBarrierNode.frontBarriers.emplace_back(); - endBarrier.resourceID = resID; + endBarrier.resourceID = realResourceID; endBarrier.type = gfx::BarrierType::SPLIT_END; endBarrier.beginVert = srcPassID; endBarrier.endVert = dstPassID; @@ -1945,15 +1972,15 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { beginBarrier.barrier = getGFXBarrier(beginBarrier); } } - const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, resID); - auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, resID); + const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, realResourceID); + auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, realResourceID); if (traits.hasSideEffects()) { states.states = iter->second.accessFlag; if (traits.residency == ResourceResidency::BACKBUFFER) { auto lastAccessPassID = get(ResourceAccessGraph::PassIDTag{}, rag, iter->first); auto &barrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, iter->first); auto &presentBarrier = barrierNode.rearBarriers.emplace_back(); - presentBarrier.resourceID = resID; + presentBarrier.resourceID = realResourceID; presentBarrier.type = gfx::BarrierType::FULL; presentBarrier.beginVert = lastAccessPassID; presentBarrier.endVert = lastAccessPassID; From 85eaac8d5e819aaaffdb75c8471a5078a290ccf4 Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Fri, 11 Aug 2023 17:28:16 +0800 Subject: [PATCH 131/232] revert Synchronize groundLightingColor settings from #14509 (#15931) --- native/cocos/scene/Ambient.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cocos/scene/Ambient.cpp b/native/cocos/scene/Ambient.cpp index 85d3fc65c73..7aebad344e0 100644 --- a/native/cocos/scene/Ambient.cpp +++ b/native/cocos/scene/Ambient.cpp @@ -98,7 +98,7 @@ float AmbientInfo::getSkyIllum() const { } void AmbientInfo::setGroundLightingColor(const Color &val) { - const Vec4 v4(val.r, val.g, val.b, val.a); + const Vec4 v4(static_cast(val.r) / 255.F, static_cast(val.g) / 255.F, static_cast(val.b) / 255.F, static_cast(val.a) / 255.F); const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); if (isHDR) { _groundAlbedoHDR.set(v4); From 9aafdbdd0512c3b2d7b5b0c5b48c9ec321f84c07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Fri, 11 Aug 2023 17:30:32 +0800 Subject: [PATCH 132/232] fix switch Env Lighting Type in the editor displays incorrectly and probe does not update position from parent node (#15925) --- .../reflection-probe-component.ts | 18 ++++++++---------- cocos/render-scene/scene/skybox.ts | 3 ++- editor/inspector/contributions/node.js | 4 ++-- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index 2f3c06e53d6..e5c36ee2fb6 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -326,14 +326,12 @@ export class ReflectionProbe extends Component { ReflectionProbeManager.probeManager.onUpdateProbes(true); this._probe.enable(); } - this.node.on(Node.EventType.TRANSFORM_CHANGED, this._onProbeTransformChanged, this); } onDisable (): void { if (this._probe) { ReflectionProbeManager.probeManager.unregister(this._probe); this._probe.disable(); } - this.node.off(Node.EventType.TRANSFORM_CHANGED, this._onProbeTransformChanged); } public start (): void { @@ -373,6 +371,14 @@ export class ReflectionProbe extends Component { this.probe.renderPlanarReflection(this.sourceCamera.camera); } } + + if (this.node.hasChangedFlags) { + this.probe.updateBoundingBox(); + } + if (this.node.hasChangedFlags & TransformBit.POSITION) { + ReflectionProbeManager.probeManager.onUpdateProbes(true); + ReflectionProbeManager.probeManager.updateProbeData(); + } } /** @@ -385,14 +391,6 @@ export class ReflectionProbe extends Component { ReflectionProbeManager.probeManager.updatePreviewSphere(this.probe); } - private _onProbeTransformChanged (type: TransformBit): void { - this.probe.updateBoundingBox(); - if (type & Node.TransformBit.POSITION) { - ReflectionProbeManager.probeManager.onUpdateProbes(true); - ReflectionProbeManager.probeManager.updateProbeData(); - } - } - private _createProbe (): void { if (this._probeId === -1 || ReflectionProbeManager.probeManager.exists(this._probeId)) { this._probeId = ReflectionProbeManager.probeManager.getNewReflectionProbeId(); diff --git a/cocos/render-scene/scene/skybox.ts b/cocos/render-scene/scene/skybox.ts index 2d8b6da60f7..30ce5bb5960 100644 --- a/cocos/render-scene/scene/skybox.ts +++ b/cocos/render-scene/scene/skybox.ts @@ -365,7 +365,8 @@ export class Skybox { const pipeline = root.pipeline; const useIBLValue = this.useIBL ? (this.isRGBE ? 2 : 1) : 0; - const useDiffuseMapValue = (this.useIBL && this.useDiffuseMap && this.diffuseMap) ? (this.isRGBE ? 2 : 1) : 0; + const useDiffuseMapValue = (this.useIBL && this.useDiffuseMap && this.diffuseMap && this.diffuseMap !== this._default) + ? (this.isRGBE ? 2 : 1) : 0; const useHDRValue = this.useHDR; const useConvMapValue = this.useConvolutionMap; diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 13285f5336a..e454f83b46d 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -454,7 +454,7 @@ exports.$ = { sceneSkyboxAfter: '.container > .body > .scene > .skybox > .after', sceneOctree: '.container > .body > .scene > .octree', sceneSkin: '.container > .body > .scene > .skin', - scenePostSettings: '.scene > .postSettings', + scenePostSettings: '.container > .body > .scene > .postSettings', node: '.container > .body > .node', nodeHeader: '.container > .body > .node > .component-header', @@ -1077,7 +1077,7 @@ const Elements = { const uuid = $prop.dump.value.uuid; Elements.scene.setEnvMapAndConvolutionMap.call(panel, uuid); - panel.$.scenePostSettings.style.display = useHDR ? 'inline-flex' : 'none'; + panel.$.scenePostSettings.style.display = useHDR ? 'block' : 'none'; }, skyboxEnvmapChange(useHDR, event) { const panel = this; From 0c47721fad34da5ba14a14d8772737facf0bb4f4 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 14 Aug 2023 09:55:59 +0800 Subject: [PATCH 133/232] fixed #15885: [bug] Crash or freeze if restarting game many times on non-android platforms. (#15922) --- native/cocos/storage/local-storage/LocalStorage.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/native/cocos/storage/local-storage/LocalStorage.cpp b/native/cocos/storage/local-storage/LocalStorage.cpp index 20b5fb277a8..1aa2edd17e4 100644 --- a/native/cocos/storage/local-storage/LocalStorage.cpp +++ b/native/cocos/storage/local-storage/LocalStorage.cpp @@ -40,6 +40,7 @@ #endif #include "base/Macros.h" +#include "base/Log.h" static int _initialized = 0; static sqlite3 *_db; @@ -109,8 +110,15 @@ void localStorageFree() { sqlite3_finalize(_stmt_select); sqlite3_finalize(_stmt_remove); sqlite3_finalize(_stmt_update); + sqlite3_finalize(_stmt_clear); + sqlite3_finalize(_stmt_key); + sqlite3_finalize(_stmt_count); - sqlite3_close(_db); + int ret = sqlite3_close(_db); + CC_ASSERT(ret == SQLITE_OK); + if (ret != SQLITE_OK) { + CC_LOG_ERROR("sqlite3_close failed, ret: %d", ret); + } _initialized = 0; } From 2b266acce7d014706b631eccfc3283063cf1ec21 Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Mon, 14 Aug 2023 09:56:59 +0800 Subject: [PATCH 134/232] fix gles3 gl target (#15914) * fix gles3 gl target * remove texture view type. --- .../renderer/gfx-gles3/GLES3CommandBuffer.cpp | 4 +- .../renderer/gfx-gles3/GLES3Commands.cpp | 101 +++++++++++------- .../cocos/renderer/gfx-gles3/GLES3Commands.h | 15 +-- .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 2 +- .../renderer/gfx-gles3/GLES3GPUObjects.h | 11 +- .../gfx-gles3/GLES3PrimaryCommandBuffer.cpp | 16 +-- .../cocos/renderer/gfx-gles3/GLES3Texture.cpp | 4 + 7 files changed, 90 insertions(+), 63 deletions(-) diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index 706dd795a59..a7396a35587 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -309,8 +309,8 @@ void GLES3CommandBuffer::resolveTexture(Texture *srcTexture, Texture *dstTexture void GLES3CommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { GLES3CmdBlitTexture *cmd = _cmdAllocator->blitTextureCmdPool.alloc(); - if (srcTexture) cmd->gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); - if (dstTexture) cmd->gpuTextureDst = static_cast(dstTexture)->gpuTexture(); + if (srcTexture) cmd->gpuTextureSrcView = static_cast(srcTexture)->gpuTextureView(); + if (dstTexture) cmd->gpuTextureDstView = static_cast(dstTexture)->gpuTextureView(); cmd->regions = regions; cmd->count = count; cmd->filter = filter; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 104ebfe5ce3..46581b89681 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -491,12 +491,17 @@ GLenum formatToGLType(Format format) { } } -GLenum getTextureTarget(TextureType type) { - switch (type) { - case TextureType::TEX2D: return GL_TEXTURE_2D; +GLenum getTextureViewTarget(GLES3GPUTextureView *view) { + switch (view->type) { case TextureType::TEX2D_ARRAY: return GL_TEXTURE_2D_ARRAY; case TextureType::TEX3D: return GL_TEXTURE_3D; case TextureType::CUBE: return GL_TEXTURE_CUBE_MAP; + case TextureType::TEX2D: { + if (hasFlag(view->gpuTexture->flags, TextureFlagBit::EXTERNAL_OES)) { + return GL_TEXTURE_EXTERNAL_OES; + } + return view->gpuTexture->type == TextureType::CUBE ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + view->baseLayer : GL_TEXTURE_2D; + } default: CC_ABORT(); return GL_NONE; @@ -819,7 +824,6 @@ static void textureStorage(GLES3Device *device, GLES3GPUTexture *gpuTexture) { GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(gpuTexture->glTarget, gpuTexture->glTexture)); glTexture = gpuTexture->glTexture; } uint32_t w = gpuTexture->width; @@ -829,22 +833,31 @@ static void textureStorage(GLES3Device *device, GLES3GPUTexture *gpuTexture) { switch (gpuTexture->type) { case TextureType::CUBE: CC_ASSERT(gpuTexture->glSamples <= 1); + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); + GL_CHECK(glTexStorage2D(GL_TEXTURE_CUBE_MAP, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); + break; case TextureType::TEX2D: if (gpuTexture->glSamples > 1 && !gpuTexture->immutable && device->constantRegistry()->glMinorVersion >= 1) { - gpuTexture->glTarget = GL_TEXTURE_2D_MULTISAMPLE; - GL_CHECK(glTexStorage2DMultisample(gpuTexture->glTarget, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, GL_FALSE)); + GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, gpuTexture->glTexture)); + GL_CHECK(glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, GL_FALSE)); } else { - GL_CHECK(glTexStorage2D(gpuTexture->glTarget, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); + auto target = hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES) ? GL_TEXTURE_EXTERNAL_OES : GL_TEXTURE_2D; + GL_CHECK(glBindTexture(target, gpuTexture->glTexture)); + GL_CHECK(glTexStorage2D(target, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); } break; case TextureType::TEX3D: CC_ASSERT(gpuTexture->glSamples <= 1); + GL_CHECK(glBindTexture(GL_TEXTURE_3D, gpuTexture->glTexture)); + GL_CHECK(glTexStorage3D(GL_TEXTURE_3D, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); + break; case TextureType::TEX2D_ARRAY: if (gpuTexture->glSamples > 1 && !gpuTexture->immutable && device->constantRegistry()->glMinorVersion >= 1) { - gpuTexture->glTarget = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; - GL_CHECK(glTexStorage3DMultisample(gpuTexture->glTarget, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, d, GL_FALSE)); + GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE_ARRAY, gpuTexture->glTexture)); + GL_CHECK(glTexStorage3DMultisample(GL_TEXTURE_2D_MULTISAMPLE_ARRAY, gpuTexture->glSamples, gpuTexture->glInternalFmt, w, h, d, GL_FALSE)); } else { - GL_CHECK(glTexStorage3D(gpuTexture->glTarget, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); + GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, gpuTexture->glTexture)); + GL_CHECK(glTexStorage3D(GL_TEXTURE_2D_ARRAY, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h, d)); } break; default: @@ -870,31 +883,19 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) // Allocate render buffer when binding a framebuffer if the MSRT extension is not present. if (gpuTexture->useRenderBuffer && hasFlag(gpuTexture->flags, TextureFlagBit::LAZILY_ALLOCATED)) { - gpuTexture->glTarget = GL_RENDERBUFFER; gpuTexture->memoryAllocated = false; return; } } - if (gpuTexture->glTexture) { - if (hasFlag(gpuTexture->flags, TextureFlagBit::EXTERNAL_OES)) { - gpuTexture->glTarget = GL_TEXTURE_EXTERNAL_OES; - } else { - gpuTexture->glTarget = GL_TEXTURE_2D; - } - return; - } - - if (gpuTexture->size == 0) { + if (gpuTexture->glTexture || gpuTexture->size == 0) { return; } if (gpuTexture->useRenderBuffer) { - gpuTexture->glTarget = GL_RENDERBUFFER; GL_CHECK(glGenRenderbuffers(1, &gpuTexture->glRenderbuffer)); renderBufferStorage(device, gpuTexture); } else { - gpuTexture->glTarget = getTextureTarget(gpuTexture->type); GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); textureStorage(device, gpuTexture); } @@ -940,6 +941,10 @@ void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) } } +void cmdFuncGLES3CreateTextureView(GLES3Device */*device*/, GLES3GPUTextureView *gpuTextureView) { + gpuTextureView->glTarget = getTextureViewTarget(gpuTextureView); +} + void cmdFuncGLES3PrepareSamplerInfo(GLES3Device * /*device*/, GLES3GPUSampler *gpuSampler) { if (gpuSampler->minFilter == Filter::LINEAR || gpuSampler->minFilter == Filter::ANISOTROPIC) { if (gpuSampler->mipFilter == Filter::LINEAR || gpuSampler->mipFilter == Filter::ANISOTROPIC) { @@ -2281,7 +2286,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GL_CHECK(glActiveTexture(GL_TEXTURE0 + unit)); cache->texUint = unit; } - GL_CHECK(glBindTexture(gpuTexture->glTarget, glTexture)); + GL_CHECK(glBindTexture(gpuTextureView->glTarget, glTexture)); cache->glTextures[unit] = glTexture; } @@ -2661,7 +2666,6 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; if (glTexture != gpuTexture->glTexture) { - GL_CHECK(glBindTexture(gpuTexture->glTarget, gpuTexture->glTexture)); glTexture = gpuTexture->glTexture; } @@ -2673,11 +2677,15 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const uint32_t destWidth = 0; uint32_t destHeight = 0; - switch (gpuTexture->glTarget) { - case GL_TEXTURE_2D: { + auto target = GL_NONE; + switch (gpuTexture->type) { + case TextureType::TEX2D: { Extent extent{}; Offset offset{}; Extent stride{}; + + target = GL_TEXTURE_2D; + GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; uint32_t mipLevel = region.texSubres.mipLevel; @@ -2720,10 +2728,13 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const } break; } - case GL_TEXTURE_2D_ARRAY: { + case TextureType::TEX2D_ARRAY: { Extent extent{}; Offset offset{}; Extent stride{}; + + target = GL_TEXTURE_2D_ARRAY; + GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, gpuTexture->glTexture)); for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; uint32_t d = region.texSubres.layerCount; @@ -2773,11 +2784,13 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const } break; } - case GL_TEXTURE_3D: { + case TextureType::TEX3D: { Extent extent{}; Offset offset{}; Extent stride{}; + target = GL_TEXTURE_3D; + GL_CHECK(glBindTexture(GL_TEXTURE_3D, gpuTexture->glTexture)); for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; uint32_t mipLevel = region.texSubres.mipLevel; @@ -2822,10 +2835,13 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const } break; } - case GL_TEXTURE_CUBE_MAP: { + case TextureType::CUBE: { Extent extent{}; Offset offset{}; Extent stride{}; + + target = GL_TEXTURE_CUBE_MAP; + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; uint32_t mipLevel = region.texSubres.mipLevel; @@ -2879,20 +2895,21 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const break; } - if (!isCompressed && hasFlag(gpuTexture->flags, TextureFlagBit::GEN_MIPMAP)) { - GL_CHECK(glBindTexture(gpuTexture->glTarget, gpuTexture->glTexture)); - GL_CHECK(glGenerateMipmap(gpuTexture->glTarget)); + if (!isCompressed && hasFlag(gpuTexture->flags, TextureFlagBit::GEN_MIPMAP) && target != GL_NONE) { + GL_CHECK(glBindTexture(target, gpuTexture->glTexture)); + GL_CHECK(glGenerateMipmap(target)); } } -void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, GLES3GPUTexture *gpuTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count) { +void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, GLES3GPUTextureView *gpuTextureView, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count) { + const auto *gpuTexture = gpuTextureView->gpuTexture; auto glFormat = gpuTexture->glFormat; auto glType = gpuTexture->glType; for (uint32_t i = 0; i < count; ++i) { auto region = regions[i]; uint8_t *copyDst = buffers[i]; - auto framebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTexture, region.texSubres); + auto framebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureView, region.texSubres); if (device->stateCache()->glReadFramebuffer != framebuffer) { GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer)); device->stateCache()->glReadFramebuffer = framebuffer; @@ -2901,9 +2918,11 @@ void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, GLES3GPUTexture *gpuT } } -void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc, GLES3GPUTexture *gpuTextureDst, +void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTextureView *gpuTextureSrcView, GLES3GPUTextureView *gpuTextureDstView, const TextureBlit *regions, uint32_t count, Filter filter) { GLES3GPUStateCache *cache = device->stateCache(); + const auto *gpuTextureSrc = gpuTextureSrcView->gpuTexture; + const auto *gpuTextureDst = gpuTextureDstView->gpuTexture; GLbitfield mask = getColorBufferMask(gpuTextureSrc->format); for (uint32_t i = 0U; i < count; ++i) { @@ -2915,7 +2934,7 @@ void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc if (gpuTextureSrc->swapchain) { srcFramebuffer = gpuTextureSrc->swapchain->glFramebuffer; } else { - srcFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureSrc, region.srcSubres); + srcFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureSrcView, region.srcSubres); } if (cache->glReadFramebuffer != srcFramebuffer) { GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFramebuffer)); @@ -2926,7 +2945,7 @@ void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc if (gpuTextureDst->swapchain) { dstFramebuffer = gpuTextureDst->swapchain->glFramebuffer; } else { - dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst, region.dstSubres); + dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDstView, region.dstSubres); } if (cache->glDrawFramebuffer != dstFramebuffer) { GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFramebuffer)); @@ -3001,7 +3020,7 @@ void cmdFuncGLES3ExecuteCmds(GLES3Device *device, GLES3CmdPackage *cmdPackage) { } case GLESCmdType::BLIT_TEXTURE: { GLES3CmdBlitTexture *cmd = cmdPackage->blitTextureCmds[cmdIdx]; - cmdFuncGLES3BlitTexture(device, cmd->gpuTextureSrc, cmd->gpuTextureDst, cmd->regions, cmd->count, cmd->filter); + cmdFuncGLES3BlitTexture(device, cmd->gpuTextureSrcView, cmd->gpuTextureDstView, cmd->regions, cmd->count, cmd->filter); break; } case GLESCmdType::QUERY: { @@ -3127,9 +3146,9 @@ void GLES3GPUFramebufferObject::finalize(GLES3GPUStateCache *cache) { GL_CHECK(glGenRenderbuffers(1, &view->gpuTexture->glRenderbuffer)); renderBufferStorage(GLES3Device::getInstance(), texture); } - GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, attachment, texture->glTarget, texture->glRenderbuffer)); + GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, attachment, GL_RENDERBUFFER, texture->glRenderbuffer)); } else { - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, texture->glTarget, texture->glTexture, view->baseLevel)); + GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, view->glTarget, texture->glTexture, view->baseLevel)); } }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index c9d612550de..c04634354c6 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -133,8 +133,8 @@ class GLES3CmdCopyBufferToTexture final : public GLESCmd { class GLES3CmdBlitTexture final : public GLESCmd { public: - GLES3GPUTexture *gpuTextureSrc = nullptr; - GLES3GPUTexture *gpuTextureDst = nullptr; + GLES3GPUTextureView *gpuTextureSrcView = nullptr; + GLES3GPUTextureView *gpuTextureDstView = nullptr; const TextureBlit *regions = nullptr; uint32_t count = 0U; Filter filter = Filter::POINT; @@ -142,8 +142,8 @@ class GLES3CmdBlitTexture final : public GLESCmd { GLES3CmdBlitTexture() : GLESCmd(GLESCmdType::BLIT_TEXTURE) {} void clear() override { - gpuTextureSrc = nullptr; - gpuTextureDst = nullptr; + gpuTextureSrcView = nullptr; + gpuTextureDstView = nullptr; regions = nullptr; count = 0U; } @@ -246,6 +246,7 @@ void cmdFuncGLES3ResizeBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer); void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture); void cmdFuncGLES3DestroyTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture); void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture); +void cmdFuncGLES3CreateTextureView(GLES3Device *device, GLES3GPUTextureView *gpuTextureView); void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader, GLES3GPUPipelineLayout *pipelineLayout); void cmdFuncGLES3DestroyShader(GLES3Device *device, GLES3GPUShader *gpuShader); void cmdFuncGLES3CreateRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRenderPass); @@ -294,14 +295,14 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const BufferTextureCopy *regions, uint32_t count); void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, - GLES3GPUTexture *gpuTexture, + GLES3GPUTextureView *gpuTextureView, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count); void cmdFuncGLES3BlitTexture(GLES3Device *device, - GLES3GPUTexture *gpuTextureSrc, - GLES3GPUTexture *gpuTextureDst, + GLES3GPUTextureView *gpuTextureSrcView, + GLES3GPUTextureView *gpuTextureDstView, const TextureBlit *regions, uint32_t count, Filter filter); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index 79bc6937af8..e97f7e00c79 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -604,7 +604,7 @@ void GLES3Device::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d void GLES3Device::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count) { CC_PROFILE(GLES3DeviceCopyTextureToBuffers); - cmdFuncGLES3CopyTextureToBuffers(this, static_cast(srcTexture)->gpuTexture(), buffers, regions, count); + cmdFuncGLES3CopyTextureToBuffers(this, static_cast(srcTexture)->gpuTextureView(), buffers, regions, count); } void GLES3Device::getQueryPoolResults(QueryPool *queryPool) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 0005cf0c6b8..66588d21014 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -135,7 +135,6 @@ struct GLES3GPUTexture { bool isPowerOf2{false}; bool useRenderBuffer{false}; bool memoryAllocated{true}; // false if swapchain image or implicit ms render buffer. - GLenum glTarget{0}; GLenum glInternalFmt{0}; GLenum glFormat{0}; GLenum glType{0}; @@ -156,8 +155,11 @@ struct GLES3GPUTextureView { Format format = Format::UNKNOWN; uint32_t baseLevel = 0U; uint32_t levelCount = 1U; + uint32_t baseLayer = 0U; + uint32_t layerCount = 1U; uint32_t basePlane = 0U; uint32_t planeCount = 0U; + GLenum glTarget{0}; }; using GLES3GPUTextureViewList = ccstd::vector; @@ -574,7 +576,8 @@ class GLES3GPUFramebufferCacheMap final { } } - GLuint getFramebufferFromTexture(const GLES3GPUTexture *gpuTexture, const TextureSubresLayers &subres) { + GLuint getFramebufferFromTexture(const GLES3GPUTextureView *gpuTextureView, const TextureSubresLayers &subres) { + const auto *gpuTexture = gpuTextureView->gpuTexture; bool isTexture = gpuTexture->glTexture; GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; auto &cacheMap = isTexture ? _textureMap : _renderbufferMap; @@ -601,9 +604,9 @@ class GLES3GPUFramebufferCacheMap final { attachment = GL_DEPTH_ATTACHMENT; } if (isTexture) { - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, gpuTexture->glTarget, glResource, mipLevel)); + GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, gpuTextureView->glTarget, glResource, mipLevel)); } else { - GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, attachment, gpuTexture->glTarget, glResource)); + GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, attachment, GL_RENDERBUFFER, glResource)); } GLenum status; diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp index c409f6023a8..86219e7e151 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp @@ -143,10 +143,10 @@ void GLES3PrimaryCommandBuffer::resolveTexture(Texture *srcTexture, Texture *dst } void GLES3PrimaryCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTexture, const TextureCopy *regions, uint32_t count) { - GLES3GPUTexture *gpuTextureSrc = nullptr; - GLES3GPUTexture *gpuTextureDst = nullptr; - if (srcTexture) gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); - if (dstTexture) gpuTextureDst = static_cast(dstTexture)->gpuTexture(); + GLES3GPUTextureView *gpuTextureSrc = nullptr; + GLES3GPUTextureView *gpuTextureDst = nullptr; + if (srcTexture) gpuTextureSrc = static_cast(srcTexture)->gpuTextureView(); + if (dstTexture) gpuTextureDst = static_cast(dstTexture)->gpuTextureView(); ccstd::vector blitRegions(count); for (uint32_t i = 0; i < count; ++i) { @@ -166,10 +166,10 @@ void GLES3PrimaryCommandBuffer::copyTexture(Texture *srcTexture, Texture *dstTex } void GLES3PrimaryCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { - GLES3GPUTexture *gpuTextureSrc = nullptr; - GLES3GPUTexture *gpuTextureDst = nullptr; - if (srcTexture) gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); - if (dstTexture) gpuTextureDst = static_cast(dstTexture)->gpuTexture(); + GLES3GPUTextureView *gpuTextureSrc = nullptr; + GLES3GPUTextureView *gpuTextureDst = nullptr; + if (srcTexture) gpuTextureSrc = static_cast(srcTexture)->gpuTextureView(); + if (dstTexture) gpuTextureDst = static_cast(dstTexture)->gpuTextureView(); cmdFuncGLES3BlitTexture(GLES3Device::getInstance(), gpuTextureSrc, gpuTextureDst, regions, count, filter); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index 2026ec3d019..2bab251e70b 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -95,8 +95,12 @@ void GLES3Texture::createTextureView() { _gpuTextureView->format = _viewInfo.format; _gpuTextureView->baseLevel = _viewInfo.baseLevel; _gpuTextureView->levelCount = _viewInfo.levelCount; + _gpuTextureView->baseLayer = _viewInfo.baseLayer; + _gpuTextureView->layerCount = _viewInfo.layerCount; _gpuTextureView->basePlane = _viewInfo.basePlane; _gpuTextureView->planeCount = _viewInfo.planeCount; + cmdFuncGLES3CreateTextureView(GLES3Device::getInstance(), _gpuTextureView); + } void GLES3Texture::doDestroy() { From 8403962f94d256a56243bb1ef751b713a0e6571d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 14 Aug 2023 10:29:38 +0800 Subject: [PATCH 135/232] AnimationGraph: fix clip overriding in nested structure (#15932) * Bug introduce FF * Fix clip overriding in animation graph * Fix lint * Fix lint --- .../marionette/animation-graph-context.ts | 6 ++- cocos/animation/marionette/graph-eval.ts | 8 ++-- .../marionette/motion/animation-blend-1d.ts | 17 ++++--- .../marionette/motion/animation-blend-2d.ts | 9 +--- .../motion/animation-blend-direct.ts | 2 - .../marionette/motion/animation-blend.ts | 24 +++------- .../marionette/motion/clip-motion.ts | 14 +++--- cocos/animation/marionette/motion/motion.ts | 7 +-- .../pose-graph/default-top-level-pose-node.ts | 9 +--- .../pose-graph/pose-nodes/play-motion.ts | 2 +- .../pose-graph/pose-nodes/sample-motion.ts | 11 +++-- .../pose-graph/pose-nodes/state-machine.ts | 1 - .../state-machine/state-machine-eval.ts | 22 ++++----- editor/src/marionette/preview.ts | 2 +- .../pose-nodes/state-machine-node.test.ts | 46 +++++++++++++++++++ .../animation/new-gen-anim/utils/eval-mock.ts | 3 +- 16 files changed, 104 insertions(+), 79 deletions(-) diff --git a/cocos/animation/marionette/animation-graph-context.ts b/cocos/animation/marionette/animation-graph-context.ts index 2072fb19444..ea090ca4bac 100644 --- a/cocos/animation/marionette/animation-graph-context.ts +++ b/cocos/animation/marionette/animation-graph-context.ts @@ -289,10 +289,12 @@ const checkBindStatus = (bindStarted = false): MethodDecorator => (_, _propertyK if (vendor) { // eslint-disable-next-line func-names descriptor.value = function (this: { readonly _bindStarted: boolean }, ...args: unknown[]): any { - assertIsTrue(this._bindStarted === bindStarted, + assertIsTrue( + this._bindStarted === bindStarted, bindStarted ? `The operation is invalid since bind has not been started.` - : `The operation is invalid since bind has already been started.`); + : `The operation is invalid since bind has already been started.`, + ); // eslint-disable-next-line @typescript-eslint/no-unsafe-return return vendor.call(this, ...args); }; diff --git a/cocos/animation/marionette/graph-eval.ts b/cocos/animation/marionette/graph-eval.ts index 52558d27d7f..997f5871795 100644 --- a/cocos/animation/marionette/graph-eval.ts +++ b/cocos/animation/marionette/graph-eval.ts @@ -80,9 +80,7 @@ export class AnimationGraphEval { const poseLayoutMaintainer = new AnimationGraphPoseLayoutMaintainer(root, this._auxiliaryCurveRegistry); this._poseLayoutMaintainer = poseLayoutMaintainer; - const bindingContext = new AnimationGraphBindingContext( - root, poseLayoutMaintainer, this._varInstances, controller, - ); + const bindingContext = new AnimationGraphBindingContext(root, poseLayoutMaintainer, this._varInstances, controller); bindingContext._setClipOverrides(clipOverrides ?? undefined); this._bindingContext = bindingContext; @@ -97,7 +95,6 @@ export class AnimationGraphEval { this._rootPoseNode = new DefaultTopLevelPoseNode( graph, bindingContext, - clipOverrides, poseStashAllocator, ); @@ -221,7 +218,8 @@ export class AnimationGraphEval { poseLayoutMaintainer.startBind(); - this._rootPoseNode.overrideClips(overrides, this._bindingContext); + this._bindingContext._setClipOverrides(overrides); + this._rootPoseNode.overrideClips(this._bindingContext); this._updateAfterPossiblePoseLayoutChange(); } diff --git a/cocos/animation/marionette/motion/animation-blend-1d.ts b/cocos/animation/marionette/motion/animation-blend-1d.ts index 27499753ad7..1e609a29cb7 100644 --- a/cocos/animation/marionette/motion/animation-blend-1d.ts +++ b/cocos/animation/marionette/motion/animation-blend-1d.ts @@ -80,12 +80,15 @@ export class AnimationBlend1D extends AnimationBlend { public [createEval] ( context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, ): any { const evaluation = new AnimationBlend1DEval( - context, clipOverrides, ignoreEmbeddedPlayers, - this, this._items, this._items.map(({ threshold }) => threshold), 0.0, + context, + ignoreEmbeddedPlayers, + this, + this._items, + this._items.map(({ threshold }) => threshold), + 0.0, ); const initialValue = bindOr( context, @@ -109,11 +112,13 @@ class AnimationBlend1DEval extends AnimationBlendEval { constructor ( context: AnimationGraphBindingContext, - overrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, - base: AnimationBlend, items: AnimationBlendItem[], thresholds: readonly number[], input: number, + base: AnimationBlend, + items: AnimationBlendItem[], + thresholds: readonly number[], + input: number, ) { - super(context, overrides, ignoreEmbeddedPlayers, base, items, [input]); + super(context, ignoreEmbeddedPlayers, base, items, [input]); this._thresholds = thresholds; this.doEval(); } diff --git a/cocos/animation/marionette/motion/animation-blend-2d.ts b/cocos/animation/marionette/motion/animation-blend-2d.ts index b4ce6ab9a16..40b4f822a2e 100644 --- a/cocos/animation/marionette/motion/animation-blend-2d.ts +++ b/cocos/animation/marionette/motion/animation-blend-2d.ts @@ -116,7 +116,6 @@ export class AnimationBlend2D extends AnimationBlend { public [createEval] ( context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, ): AnimationBlendEval { const { algorithm } = this; @@ -126,7 +125,6 @@ export class AnimationBlend2D extends AnimationBlend { assertIsTrue(this._polarSpaceGBI, `The polar space interpolator is not setup correctly!`); evaluation = new PolarSpaceGradientBandBlend2DEval( context, - clipOverrides, ignoreEmbeddedPlayers, this, this._items, @@ -141,7 +139,6 @@ export class AnimationBlend2D extends AnimationBlend { case Algorithm.FREEFORM_CARTESIAN: evaluation = new AnimationBlend2DEval( context, - clipOverrides, ignoreEmbeddedPlayers, this, this._items, @@ -200,7 +197,6 @@ class AnimationBlend2DEval extends AnimationBlendEval { constructor ( context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, base: AnimationBlend, items: AnimationBlendItem[], @@ -208,7 +204,7 @@ class AnimationBlend2DEval extends AnimationBlendEval { algorithm: Algorithm.SIMPLE_DIRECTIONAL | Algorithm.FREEFORM_CARTESIAN, inputs: [number, number], ) { - super(context, clipOverrides, ignoreEmbeddedPlayers, base, items, inputs); + super(context, ignoreEmbeddedPlayers, base, items, inputs); this._thresholds = thresholds; this._algorithm = algorithm; this.doEval(); @@ -236,14 +232,13 @@ class PolarSpaceGradientBandBlend2DEval extends AnimationBlendEval { constructor ( context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, base: AnimationBlend, items: AnimationBlendItem[], interpolator: PolarSpaceGradientBandInterpolator2D, inputs: [number, number], ) { - super(context, clipOverrides, ignoreEmbeddedPlayers, base, items, inputs); + super(context, ignoreEmbeddedPlayers, base, items, inputs); this._interpolator = interpolator; this.doEval(); } diff --git a/cocos/animation/marionette/motion/animation-blend-direct.ts b/cocos/animation/marionette/motion/animation-blend-direct.ts index 0a59f8d8f3e..ce53ebbf2bc 100644 --- a/cocos/animation/marionette/motion/animation-blend-direct.ts +++ b/cocos/animation/marionette/motion/animation-blend-direct.ts @@ -74,12 +74,10 @@ export class AnimationBlendDirect extends AnimationBlend { public [createEval] ( context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, ): AnimationBlendDirectEval { const myEval: AnimationBlendDirectEval = new AnimationBlendDirectEval( context, - clipOverrides, ignoreEmbeddedPlayers, this, this._items, diff --git a/cocos/animation/marionette/motion/animation-blend.ts b/cocos/animation/marionette/motion/animation-blend.ts index 9162838c109..cfe62a039bf 100644 --- a/cocos/animation/marionette/motion/animation-blend.ts +++ b/cocos/animation/marionette/motion/animation-blend.ts @@ -27,7 +27,6 @@ import { Motion, MotionEval, MotionPort } from './motion'; import { createEval } from '../create-eval'; import { VariableTypeMismatchedError } from '../errors'; import { ClipStatus } from '../state-machine/state-machine-eval'; -import type { ReadonlyClipOverrideMap } from '../clip-overriding'; import { CLASS_NAME_PREFIX_ANIM } from '../../define'; import { getMotionRuntimeID, RUNTIME_ID_ENABLED } from '../graph-debug'; @@ -37,14 +36,6 @@ import { blendPoseInto, Pose } from '../../core/pose'; const { ccclass, serializable } = _decorator; -export interface AnimationBlend extends Motion, EditorExtendable { - [createEval] ( - _context: AnimationGraphBindingContext, - overrides: ReadonlyClipOverrideMap | null, - ignoreEmbeddedPlayers: boolean, - ): MotionEval | null; -} - @ccclass(`${CLASS_NAME_PREFIX_ANIM}AnimationBlendItem`) export class AnimationBlendItem { @serializable @@ -73,7 +64,7 @@ export abstract class AnimationBlend extends Motion { } } -export class AnimationBlendEval implements MotionEval { +export abstract class AnimationBlendEval implements MotionEval { public declare runtimeId?: number; private declare _childEvaluators: (MotionEval | null)[]; @@ -82,13 +73,12 @@ export class AnimationBlendEval implements MotionEval { constructor ( context: AnimationGraphBindingContext, - overrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, base: AnimationBlend, children: AnimationBlendItem[], inputs: number[], ) { - this._childEvaluators = children.map((child) => child.motion?.[createEval](context, overrides, ignoreEmbeddedPlayers) ?? null); + this._childEvaluators = children.map((child) => child.motion?.[createEval](context, ignoreEmbeddedPlayers) ?? null); this._weights = new Array(this._childEvaluators.length).fill(0); this._inputs = [...inputs]; if (RUNTIME_ID_ENABLED) { @@ -180,9 +170,9 @@ export class AnimationBlendEval implements MotionEval { return context.pushDefaultedPose(); } - public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { + public overrideClips (context: AnimationGraphBindingContext): void { for (let iChild = 0; iChild < this._childEvaluators.length; ++iChild) { - this._childEvaluators[iChild]?.overrideClips(overrides, context); + this._childEvaluators[iChild]?.overrideClips(context); } } @@ -195,9 +185,7 @@ export class AnimationBlendEval implements MotionEval { this.eval(this._weights, this._inputs); } - protected eval (_weights: number[], _inputs: readonly number[]): void { - - } + protected abstract eval (_weights: number[], _inputs: readonly number[]): void; } class AnimationBlendPort implements MotionPort { @@ -212,7 +200,7 @@ class AnimationBlendPort implements MotionPort { return this._host.__evaluatePort(this, progress, context); } - public reenter () { + public reenter (): void { const { childPorts } = this; const nChildPorts = childPorts.length; for (let iChild = 0; iChild < nChildPorts; ++iChild) { diff --git a/cocos/animation/marionette/motion/clip-motion.ts b/cocos/animation/marionette/motion/clip-motion.ts index def4d6ca5af..8cfce0db347 100644 --- a/cocos/animation/marionette/motion/clip-motion.ts +++ b/cocos/animation/marionette/motion/clip-motion.ts @@ -48,13 +48,12 @@ export class ClipMotion extends Motion { public [createEval] ( context: AnimationGraphBindingContext, - overrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, ): ClipMotionEval | null { if (!this.clip) { return null; } - const clipMotionEval = new ClipMotionEval(context, this.clip, overrides, ignoreEmbeddedPlayers); + const clipMotionEval = new ClipMotionEval(context, this.clip, ignoreEmbeddedPlayers); if (RUNTIME_ID_ENABLED) { clipMotionEval.runtimeId = getMotionRuntimeID(this); } @@ -82,12 +81,11 @@ class ClipMotionEval implements MotionEval { constructor ( context: AnimationGraphBindingContext, clip: AnimationClip, - clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, ) { this._originalClip = clip; this._ignoreEmbeddedPlayers = ignoreEmbeddedPlayers; - const overriding = clipOverrides?.get(clip) ?? clip; + const overriding = context.clipOverrides?.get(clip) ?? clip; this._setClip(overriding, context); } @@ -160,15 +158,15 @@ class ClipMotionEval implements MotionEval { return pose; } - public overrideClips (clipOverrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { + public overrideClips (context: AnimationGraphBindingContext): void { const { _originalClip: originalClip } = this; - const overriding = clipOverrides.get(originalClip); + const overriding = context.clipOverrides?.get(originalClip); if (overriding) { this._setClip(overriding, context); } } - public reenter () { + public reenter (): void { this._frameEventEval?.reset(); } @@ -216,7 +214,7 @@ class ClipMotionPort implements MotionPort { return this._eval[evaluatePortTag](progress, context); } - public reenter () { + public reenter (): void { this._eval.reenter(); } diff --git a/cocos/animation/marionette/motion/motion.ts b/cocos/animation/marionette/motion/motion.ts index d6084f3db26..f22a3195a4f 100644 --- a/cocos/animation/marionette/motion/motion.ts +++ b/cocos/animation/marionette/motion/motion.ts @@ -58,7 +58,7 @@ export interface MotionEval { getClipStatuses(baseWeight: number): Iterator; - overrideClips(clipOverrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void; + overrideClips(context: AnimationGraphBindingContext): void; createPort(): MotionPort; } @@ -69,7 +69,6 @@ export interface MotionEval { export abstract class Motion extends EditorExtendable { abstract [createEval] ( context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, ignoreEmbeddedPlayers: boolean, ): MotionEval | null; @@ -79,7 +78,9 @@ export abstract class Motion extends EditorExtendable { * // TODO: HACK * @internal */ - __callOnAfterDeserializeRecursive (): void { } + __callOnAfterDeserializeRecursive (): void { + // Can be overrode in subclasses. + } } export interface MotionPort { diff --git a/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts b/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts index 47396c48a76..bf57c6b5f46 100644 --- a/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts +++ b/cocos/animation/marionette/pose-graph/default-top-level-pose-node.ts @@ -4,7 +4,6 @@ import { AnimationGraph, Layer } from '../animation-graph'; import { AnimationGraphBindingContext, AnimationGraphEvaluationContext, AnimationGraphSettleContext, AnimationGraphUpdateContext } from '../animation-graph-context'; import { AnimationMask } from '../animation-mask'; -import { ReadonlyClipOverrideMap } from '../clip-overriding'; import { TopLevelStateMachineEvaluation } from '../state-machine/state-machine-eval'; import { PoseNode } from './pose-node'; import { RuntimeMotionSyncManager } from './motion-sync/runtime-motion-sync'; @@ -14,7 +13,6 @@ export class DefaultTopLevelPoseNode extends PoseNode { constructor ( graph: AnimationGraph, bindingContext: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, poseStashAllocator: PoseStashAllocator, ) { super(); @@ -23,7 +21,6 @@ export class DefaultTopLevelPoseNode extends PoseNode { const record = new LayerEvaluationRecord( layer, bindingContext, - clipOverrides, poseStashAllocator, ); @@ -69,13 +66,13 @@ export class DefaultTopLevelPoseNode extends PoseNode { return this._layerRecords[layerIndex].stateMachineEvaluation; } - public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { + public overrideClips (context: AnimationGraphBindingContext): void { const { _layerRecords: layerRecords } = this; const nLayers = layerRecords.length; for (let iLayer = 0; iLayer < nLayers; ++iLayer) { const layerRecord = layerRecords[iLayer]; context._pushAdditiveFlag(layerRecord.additive); - layerRecord.stateMachineEvaluation.overrideClips(overrides, context); + layerRecord.stateMachineEvaluation.overrideClips(context); context._popAdditiveFlag(); } } @@ -116,7 +113,6 @@ class LayerEvaluationRecord { constructor ( layer: Layer, bindingContext: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, poseStashAllocator: PoseStashAllocator, ) { const stashManager = new RuntimeStashManager(poseStashAllocator); @@ -145,7 +141,6 @@ class LayerEvaluationRecord { layer.stateMachine, layer.name, bindingContext, - clipOverrides, ); bindingContext._popAdditiveFlag(); diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts b/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts index 78e8b8b3c5f..9560ac9a3fe 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/play-motion.ts @@ -69,7 +69,7 @@ export class PoseNodePlayMotion extends PoseNode { if (!motion) { return; } - const motionEval = motion[createEval](context, context.clipOverrides ?? null, false); + const motionEval = motion[createEval](context, false); if (!motionEval) { return; } diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts b/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts index 7e8fb921505..fac5e8fe16f 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/sample-motion.ts @@ -43,7 +43,7 @@ export class PoseNodeSampleMotion extends PoseNode { if (!motion) { return; } - const motionEval = motion[createEval](context, context.clipOverrides ?? null, true); + const motionEval = motion[createEval](context, true); if (!motionEval) { return; } @@ -51,11 +51,16 @@ export class PoseNodeSampleMotion extends PoseNode { this._workspace = workspace; } - public settle (context: AnimationGraphSettleContext): void { } + public settle (context: AnimationGraphSettleContext): void { + // Do nothing. + } - public reenter (): void { } + public reenter (): void { + // Do nothing. + } protected doUpdate (context: AnimationGraphUpdateContext): void { + // Do nothing. } protected doEvaluate (context: AnimationGraphEvaluationContext): Pose { diff --git a/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts b/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts index bd88711ab4d..35e0122e9f1 100644 --- a/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts +++ b/cocos/animation/marionette/pose-graph/pose-nodes/state-machine.ts @@ -42,7 +42,6 @@ export class PoseNodeStateMachine extends PoseNode { this.stateMachine, '', context, - null, ); } diff --git a/cocos/animation/marionette/state-machine/state-machine-eval.ts b/cocos/animation/marionette/state-machine/state-machine-eval.ts index 56114bff2a1..9536abb54f4 100644 --- a/cocos/animation/marionette/state-machine/state-machine-eval.ts +++ b/cocos/animation/marionette/state-machine/state-machine-eval.ts @@ -119,7 +119,6 @@ class TopLevelStateMachineEvaluation { stateMachine: StateMachine, name: string, context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, ) { this._additive = context.additive; this.name = name; @@ -128,7 +127,6 @@ class TopLevelStateMachineEvaluation { stateMachine, null, context, - clipOverrides, name, ); this._topLevelEntry = entry; @@ -252,12 +250,12 @@ class TopLevelStateMachineEvaluation { } } - public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { + public overrideClips (context: AnimationGraphBindingContext): void { const { _motionStates: motionStates } = this; const nMotionStates = motionStates.length; for (let iMotionState = 0; iMotionState < nMotionStates; ++iMotionState) { const node = motionStates[iMotionState]; - node.overrideClips(overrides, context); + node.overrideClips(context); } } @@ -285,7 +283,6 @@ class TopLevelStateMachineEvaluation { graph: StateMachine, parentStateMachineInfo: StateMachineInfo | null, context: AnimationGraphBindingContext, - clipOverrides: ReadonlyClipOverrideMap | null, __DEBUG_ID__: string, ): StateMachineInfo { const nodes = Array.from(graph.states()); @@ -296,7 +293,7 @@ class TopLevelStateMachineEvaluation { const nodeEvaluations = nodes.map((node): NodeEval | VMSMEval | null => { if (node instanceof MotionState) { - const motionStateEval = new VMSMEval(node, context, clipOverrides); + const motionStateEval = new VMSMEval(node, context); this._motionStates.push(motionStateEval); return motionStateEval; } else if (node === graph.entryState) { @@ -342,7 +339,6 @@ class TopLevelStateMachineEvaluation { node.stateMachine, stateMachineInfo, context, - clipOverrides, `${__DEBUG_ID__}/${node.name}`, ); subStateMachineInfo.components = new InstantiatedComponents(node); @@ -682,9 +678,7 @@ class TopLevelStateMachineEvaluation { * * @returns The transition matched, or null if there's no matched transition. */ - private _matchTransition ( - node: NodeEval, realNode: NodeEval, - ): TransitionEval | null { + private _matchTransition (node: NodeEval, realNode: NodeEval): TransitionEval | null { assertIsTrue(node === realNode || node.kind === NodeKind.any); const { _conditionEvaluationContext: conditionEvaluationContext } = this; @@ -1214,7 +1208,7 @@ interface StateMachineInfo { * Track the evaluation of a virtual motion state-machine. */ class VMSMEval { - constructor (state: MotionState, context: AnimationGraphBindingContext, overrides: ReadonlyClipOverrideMap | null) { + constructor (state: MotionState, context: AnimationGraphBindingContext) { const name = state.name; this._baseSpeed = state.speed; @@ -1231,7 +1225,7 @@ class VMSMEval { } } - const sourceEval = state.motion?.[createEval](context, overrides, false) ?? null; + const sourceEval = state.motion?.[createEval](context, false) ?? null; if (sourceEval) { Object.defineProperty(sourceEval, '__DEBUG_ID__', { value: name }); } @@ -1298,8 +1292,8 @@ class VMSMEval { } } - public overrideClips (overrides: ReadonlyClipOverrideMap, context: AnimationGraphBindingContext): void { - this._source?.overrideClips(overrides, context); + public overrideClips (context: AnimationGraphBindingContext): void { + this._source?.overrideClips(context); } private _source: MotionEval | null = null; diff --git a/editor/src/marionette/preview.ts b/editor/src/marionette/preview.ts index c7b8d2f16ce..b0b92d39d38 100644 --- a/editor/src/marionette/preview.ts +++ b/editor/src/marionette/preview.ts @@ -432,7 +432,7 @@ class MotionEvalRecord { } public rebind(bindContext: AnimationGraphBindingContext) { - const motionEval = this._motion[createEval](bindContext, null, true); + const motionEval = this._motion[createEval](bindContext, true); if (!motionEval) { return; diff --git a/tests/animation/new-gen-anim/pose-graph/pose-nodes/state-machine-node.test.ts b/tests/animation/new-gen-anim/pose-graph/pose-nodes/state-machine-node.test.ts index c58704f9fd3..692043569bb 100644 --- a/tests/animation/new-gen-anim/pose-graph/pose-nodes/state-machine-node.test.ts +++ b/tests/animation/new-gen-anim/pose-graph/pose-nodes/state-machine-node.test.ts @@ -1,4 +1,5 @@ import { AnimationController } from "../../../../../cocos/animation/animation"; +import { AnimationGraphVariant } from "../../../../../cocos/animation/marionette/animation-graph-variant"; import { lerp } from "../../../../../exports/base"; import { AnimationGraphEvalMock } from "../../utils/eval-mock"; import { createAnimationGraph, StateMachineParams, VariableDeclarationParams } from "../../utils/factory"; @@ -187,4 +188,49 @@ describe(`Reentering`, () => { }, }; } +}); + +test(`Clip overriding in state machine node`, () => { + const fixture = { + animation_1: new LinearRealValueAnimationFixture(1., 2., 3.), + animation_2: new LinearRealValueAnimationFixture(-0.5, -3, 1), + }; + + const valueObserver = new SingleRealValueObserver(); + + const motion1 = fixture.animation_1.createMotion(valueObserver.getCreateMotionContext()); + const motion2 = fixture.animation_2.createMotion(valueObserver.getCreateMotionContext()); + + const animationGraph = createAnimationGraph({ + layers: [{ + // Outer SM. + stateMachine: { + entryTransitions: [{ to: 'innerSM' }], + states: { + 'innerSM': { + type: 'procedural', + graph: { + rootNode: { + 'type': 'state-machine', + // Inner SM. + stateMachine: { + entryTransitions: [{ to: 'm' }], + states: { 'm': { type: 'motion', motion: motion1 } }, + }, + }, + }, + }, + }, + }, + }], + }); + + const animationGraphVariant = new AnimationGraphVariant(); + animationGraphVariant.original = animationGraph; + animationGraphVariant.clipOverrides.set(motion1.clip, motion2.clip); + + const evalMock = new AnimationGraphEvalMock(valueObserver.root, animationGraphVariant); + + evalMock.step(fixture.animation_2.duration * 0.3); + expect(valueObserver.value).toBeCloseTo(fixture.animation_2.getExpected(evalMock.current), 5); }); \ No newline at end of file diff --git a/tests/animation/new-gen-anim/utils/eval-mock.ts b/tests/animation/new-gen-anim/utils/eval-mock.ts index 4cad7f4403b..6919ee07416 100644 --- a/tests/animation/new-gen-anim/utils/eval-mock.ts +++ b/tests/animation/new-gen-anim/utils/eval-mock.ts @@ -1,12 +1,13 @@ import { AnimationController } from "../../../../cocos/animation/animation"; import { AnimationGraph } from "../../../../cocos/animation/marionette/animation-graph"; +import { AnimationGraphVariant } from "../../../../cocos/animation/marionette/animation-graph-variant"; import { AnimationGraphEval } from "../../../../cocos/animation/marionette/graph-eval"; import { Node } from "../../../../cocos/scene-graph"; export class AnimationGraphEvalMock { constructor( node: Node, - animationGraph: AnimationGraph, + animationGraph: AnimationGraph | AnimationGraphVariant, ) { const controller = node.addComponent(AnimationController) as AnimationController; this._controller = controller; From 4ca3c88d8d465c425582ef18f16a630ef36fe7b7 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Mon, 14 Aug 2023 10:48:24 +0800 Subject: [PATCH 136/232] Fix the issue on some platform, the audio cannot start playing at the exact position after calling stop and then seek (#15924) * Fix the issue On the Huawei platform, the audio cannot start playing at the exact position after calling stop and then seek --- pal/audio/minigame/player-minigame.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index d2f81712c3f..cecf6e83231 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -24,7 +24,7 @@ import { minigame } from 'pal/minigame'; import { systemInfo } from 'pal/system-info'; -import { TAOBAO, TAOBAO_MINIGAME } from 'internal:constants'; +import { TAOBAO, TAOBAO_MINIGAME, HUAWEI, VIVO, OPPO } from 'internal:constants'; import { EventTarget } from '../../../cocos/core/event'; import { AudioEvent, AudioPCMDataView, AudioState, AudioType } from '../type'; import { clamp, clamp01 } from '../../../cocos/core'; @@ -107,6 +107,9 @@ export class AudioPlayerMinigame implements OperationQueueable { this._cacheTime = 0; this._needSeek = false; this._seeking = false; + if ((HUAWEI || VIVO || OPPO) && this._innerAudioContext) { + this._innerAudioContext.startTime = 0; + } } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. @@ -168,11 +171,9 @@ export class AudioPlayerMinigame implements OperationQueueable { this._seeking = false; if (this._needSeek) { this._needSeek = false; - if (this._cacheTime.toFixed(3) !== this._innerAudioContext.currentTime.toFixed(3)) { + if (this._cacheTime.toFixed(2) !== this._innerAudioContext.currentTime.toFixed(2)) { // eslint-disable-next-line @typescript-eslint/no-empty-function this.seek(this._cacheTime).catch((e) => {}); - } else { - this._needSeek = false; } } }; @@ -304,6 +305,9 @@ export class AudioPlayerMinigame implements OperationQueueable { return this._innerAudioContext.duration; } get currentTime (): number { + if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) { + return this._innerAudioContext.startTime; + } if (this._state !== AudioState.PLAYING || this._needSeek || this._seeking) { return this._cacheTime; } @@ -328,7 +332,10 @@ export class AudioPlayerMinigame implements OperationQueueable { this._eventTarget.once(AudioEvent.SEEKED, resolve); this._innerAudioContext.seek(time); } else { - if (this._cacheTime !== time) { // Skip the invalid seek + //Huawei, vivo, Oppo platform, after stop, regardless of whether the seek has been called, the playback will always start from 0 again + if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) { + this._innerAudioContext.startTime = time; + } else if (this._cacheTime !== time) { // Skip the invalid seek this._cacheTime = time; this._needSeek = true; } From 6d04a1477a00d1ebb0672cb34ebe6b94c1e1e5f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 14 Aug 2023 11:38:52 +0800 Subject: [PATCH 137/232] Re-support non-transform animation in animation graph (#15842) --- .../animation-graph-animation-clip-binding.ts | 49 +++++- tests/animation/newgenanim.test.ts | 157 +++++++++++++++++- 2 files changed, 195 insertions(+), 11 deletions(-) diff --git a/cocos/animation/marionette/animation-graph-animation-clip-binding.ts b/cocos/animation/marionette/animation-graph-animation-clip-binding.ts index 0c2ab2d0297..4d01923400b 100644 --- a/cocos/animation/marionette/animation-graph-animation-clip-binding.ts +++ b/cocos/animation/marionette/animation-graph-animation-clip-binding.ts @@ -8,7 +8,7 @@ import { AuxiliaryCurveHandle, TransformHandle } from '../core/animation-handle' import { calculateDeltaPose, Pose } from '../core/pose'; import { createEvalSymbol } from '../define'; import { ExoticTrsAGEvaluation } from '../exotic-animation/exotic-animation'; -import { isTrsPropertyName, normalizedFollowTag, Track, TrackBinding, trackBindingTag, TrackEval } from '../tracks/track'; +import { isTrsPropertyName, normalizedFollowTag, RuntimeBinding, Track, TrackBinding, trackBindingTag, TrackEval } from '../tracks/track'; import { UntypedTrack } from '../tracks/untyped-track'; import { AnimationGraphEvaluationContext } from './animation-graph-context'; @@ -204,6 +204,26 @@ function bindPoseTransform ( } } +class NonTransformPoseBinding implements PoseBinding { + constructor ( + public readonly binding: RuntimeBinding, + ) { + + } + + destroy (): void { + // Needs no destroy. + } + + setValue (value: any, _pose: Pose): void { + this.binding.setValue(value); + } + + getValue (pose: Pose): any { + return this.binding.getValue?.() ?? undefined; + } +} + /** * Describes the evaluation of a animation clip track in sense of animation graph. */ @@ -230,7 +250,11 @@ class AGTrackEvaluation { private _trackSampler: TrackEval; } -function bindTrackAG (animationClip: AnimationClip, track: Track, bindContext: AnimationClipGraphBindingContext): PoseBinding | undefined { +function bindTrackAG ( + animationClip: AnimationClip, + track: Track, + bindContext: AnimationClipGraphBindingContext, +): PoseBinding | undefined { const trackBinding = track[trackBindingTag]; const trackTarget = createRuntimeBindingAG(trackBinding, bindContext); if (DEBUG && !trackTarget) { @@ -247,7 +271,10 @@ function bindTrackAG (animationClip: AnimationClip, track: Track, bindContext: A return trackTarget ?? undefined; } -function createRuntimeBindingAG (track: TrackBinding, bindContext: AnimationClipGraphBindingContext): PoseBinding | null | undefined { +function createRuntimeBindingAG ( + track: TrackBinding, + bindContext: AnimationClipGraphBindingContext, +): PoseBinding | null | undefined { const { origin, } = bindContext; @@ -288,10 +315,16 @@ function createRuntimeBindingAG (track: TrackBinding, bindContext: AnimationClip } } - // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - // TODO: here should be resolved before this can be landed. - error(`Animation graph currently only supports (bone) transform animations.`); - return undefined; + // If this path does not aim a transform target, + // we create `NonTransformPoseBinding` using default binding. + { + const nonTransformBinding = track.createRuntimeBinding(bindContext.origin, undefined, false); + if (!nonTransformBinding) { + return null; + } + + return new NonTransformPoseBinding(nonTransformBinding); + } } class AuxiliaryCurveEvaluation { @@ -363,7 +396,7 @@ class AnimationClipAGEvaluationRegular implements AnimationClipAGEvaluation { for (const track of tracks) { if (track instanceof UntypedTrack) { - // Untyped track is not supported in AG. + // Untyped track is not supported in AG. continue; } if (Array.from(track.channels()).every(({ curve }) => curve.keyFramesCount === 0)) { diff --git a/tests/animation/newgenanim.test.ts b/tests/animation/newgenanim.test.ts index b7b668ea281..f7234da60a8 100644 --- a/tests/animation/newgenanim.test.ts +++ b/tests/animation/newgenanim.test.ts @@ -10,7 +10,7 @@ import '../utils/matcher-deep-close-to'; import { BinaryCondition, UnaryCondition, TriggerCondition } from '../../cocos/animation/marionette/state-machine/condition'; import { AnimationController } from '../../cocos/animation/marionette/animation-controller'; import { StateMachineComponent } from '../../cocos/animation/marionette/state-machine/state-machine-component'; -import { VectorTrack } from '../../cocos/animation/animation'; +import { RealTrack, VectorTrack } from '../../cocos/animation/animation'; import 'jest-extended'; import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; import { additiveSettingsTag, AnimationClip } from '../../cocos/animation/animation-clip'; @@ -19,12 +19,13 @@ import { MotionState } from '../../cocos/animation/marionette/state-machine/moti import { Node, Component } from '../../cocos/scene-graph'; import * as maskTestHelper from './new-gen-anim/utils/mask-test-helper'; import '../utils/matchers/value-type-asymmetric-matchers'; -import { AnimationBlend1DFixture, LinearRealValueAnimationFixture, ConstantRealValueAnimationFixture, RealValueAnimationFixture } from './new-gen-anim/utils/fixtures'; +import { AnimationBlend1DFixture, LinearRealValueAnimationFixture, ConstantRealValueAnimationFixture, RealValueAnimationFixture, CreateMotionContext } from './new-gen-anim/utils/fixtures'; import { NodeTransformValueObserver } from './new-gen-anim/utils/node-transform-value-observer'; import { SingleRealValueObserver } from './new-gen-anim/utils/single-real-value-observer'; import { createAnimationGraph, StateParams, TransitionParams } from './new-gen-anim/utils/factory'; import { captureWarns } from '../utils/log-capture'; -import { AnimationGraphEvalMock } from './new-gen-anim/utils/eval-mock'; +import { AnimationGraphEvalMock, generateIntervals } from './new-gen-anim/utils/eval-mock'; +import { ccclass } from '../../cocos/core/data/class-decorator'; /** * Notable changes @@ -5247,6 +5248,156 @@ describe('NewGen Anim', () => { return animationGraph; } }); + + describe(`Non-transform animation`, () => { + test(`Behavior in state machine`, () => { + /// In below: + /// - "tp" means "target property". + + const fixture = { + common_tp_default_value: 9, + animation_1: ((duration: number) => ({ + duration, + exclusive_tp_default_value: 3., + exclusive_animation: new LinearRealValueAnimationFixture(1, 2, duration), + common_animation: new LinearRealValueAnimationFixture(3, 4, duration), + }))(2.0), + animation_2: ((duration: number) => ({ + duration, + exclusive_tp_default_value: 2., + exclusive_animation: new LinearRealValueAnimationFixture(5, 6, duration), + common_animation: new LinearRealValueAnimationFixture(7, 8, duration), + }))(1.5), + transitionDuration: 0.3, + }; + + @ccclass('TargetObject') + class TargetObject extends Component { + tp_common = fixture.common_tp_default_value; + tp_anim_1_only = fixture.animation_1.exclusive_tp_default_value; + tp_anim_2_only = fixture.animation_2.exclusive_tp_default_value; + } + + const createMotion = (params: typeof fixture.animation_1, exclusive_tp_key: keyof TargetObject) => { + const clip = new AnimationClip(); + clip.duration = params.duration; + { + const track = new RealTrack(); + track.path.toComponent(TargetObject).toProperty('tp_common' as keyof TargetObject); + params.common_animation.setupCurve(track.channel.curve); + clip.addTrack(track); + } + { + const track = new RealTrack(); + track.path.toComponent(TargetObject).toProperty(exclusive_tp_key); + params.exclusive_animation.setupCurve(track.channel.curve); + clip.addTrack(track); + } + const clipMotion = new ClipMotion(); + clipMotion.clip = clip; + return clipMotion as NonNullableClipMotion; + }; + + const clipMotion1 = createMotion(fixture.animation_1, 'tp_anim_1_only'); + const clipMotion2 = createMotion(fixture.animation_2, 'tp_anim_2_only'); + const animationGraph = createAnimationGraph({ + variableDeclarations: { 'EnableTransition': { type: 'boolean' } }, + layers: [{ + stateMachine: { + entryTransitions: [{ to: 'motion1' }], + transitions: [{ + from: 'motion1', to: 'motion2', exitTimeEnabled: false, duration: fixture.transitionDuration, + conditions: [{ type: 'unary', operand: { type: 'variable', name: 'EnableTransition' }, operator: 'to-be-true' }], + }], + states: { + 'motion1': { type: 'motion', motion: clipMotion1, }, + 'motion2': { type: 'motion', motion: clipMotion2 }, + }, + }, + }], + }); + + const origin = new Node(); + + const targetObject = origin.addComponent(TargetObject) as TargetObject; + + const check = (() => { + let expected_common = fixture.common_tp_default_value; + let expected_anim_1_only = fixture.animation_1.exclusive_tp_default_value; + let expected_anim_2_only = fixture.animation_2.exclusive_tp_default_value; + + return ({ + common, + anim_1_only: anim_1_exclusive, + anim_2_only: anim_2_exclusive, + }: Partial<{ + common: number, + anim_1_only: number, + anim_2_only: number, + }>) => { + expected_common = common ?? expected_common; + expected_anim_1_only = anim_1_exclusive ?? expected_anim_1_only; + expected_anim_2_only = anim_2_exclusive ?? expected_anim_2_only; + expect(targetObject.tp_common).toBeCloseTo(expected_common, 5); + expect(targetObject.tp_anim_1_only).toBeCloseTo(expected_anim_1_only, 5); + expect(targetObject.tp_anim_2_only).toBeCloseTo(expected_anim_2_only, 5); + }; + })(); + + const evalMock = new AnimationGraphEvalMock(origin, animationGraph); + + check({}); + + // If no transition, the animation is normally sampled. + for (const [t] of generateIntervals(0.2, 0.7, 0.9)) { + evalMock.step(fixture.animation_1.duration * t); + + const tAnim = Math.min(evalMock.current, fixture.animation_1.duration); + check({ + anim_1_only: fixture.animation_1.exclusive_animation.getExpected(tAnim), + + common: fixture.animation_1.common_animation.getExpected(tAnim), + + // Not changed since anim2 is not playing. + anim_2_only: undefined, + }); + } + + // During transition or after transition finished. + evalMock.controller.setValue('EnableTransition', true); + const start_time_of_motion2_state = evalMock.current; + for (const [t] of generateIntervals(0.15, 0.88)) { + evalMock.step(fixture.transitionDuration * t); + + const tAnim = Math.min(evalMock.current - start_time_of_motion2_state, fixture.animation_1.duration); + check({ + // Anim1's exclusive property is not affected. + anim_1_only: fixture.animation_1.exclusive_animation.getExpected(Math.min(evalMock.current, fixture.animation_1.duration)), + + // But the common property is fully governed by anim2 instead. + common: fixture.animation_2.common_animation.getExpected(tAnim), + + anim_2_only: fixture.animation_2.exclusive_animation.getExpected(tAnim), + }); + } + + // After transition finished, only motion2 plays. + for (const [t] of generateIntervals(1.2, 1.5)) { + evalMock.step(fixture.transitionDuration * t); + + const tAnim = Math.min(evalMock.current - start_time_of_motion2_state, fixture.animation_1.duration); + check({ + // Not changed since anim2 is not playing. + anim_1_only: undefined, + + // But the common property is fully governed by anim2 instead. + common: fixture.animation_2.common_animation.getExpected(tAnim), + + anim_2_only: fixture.animation_2.exclusive_animation.getExpected(tAnim), + }); + } + }); + }); }); function assertivelyGetGraphVariable(graph: AnimationGraph, name: string) { From ac4fa7462467c0b25887976c5a6ef0001e995a12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Mon, 14 Aug 2023 11:40:13 +0800 Subject: [PATCH 138/232] Windows: Suppressing the Warning When Linking (#15943) --- native/CMakeLists.txt | 5 +++++ templates/windows/CMakeLists.txt | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index a1da31bfede..8e0e4296446 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -3105,6 +3105,11 @@ if(MSVC) /wd4098 # defaultlib conflicts /wd4099 # PDB 'filename' was not found with 'object/library' or at 'path'; linking object as if no debug info ) + target_link_options(${ENGINE_NAME} PUBLIC + /ignore:4099 # PDB 'filename' was not found with 'object/library' or at 'path'; linking object as if no debug info + /ignore:4098 # defaultlib 'library' conflicts with use of other libs; use /NODEFAULTLIB:library + /ignore:4204 # 'filename' is missing debugging information for referencing module; linking object as if no debug info + ) endif() if(CC_USE_VULKAN) diff --git a/templates/windows/CMakeLists.txt b/templates/windows/CMakeLists.txt index c91dd01ad48..9f3d15f91f8 100644 --- a/templates/windows/CMakeLists.txt +++ b/templates/windows/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.8) +cmake_minimum_required(VERSION 3.18) set(APP_NAME "CocosGame" CACHE STRING "Project Name") project(${APP_NAME} CXX) From e09252efd8d9ff36d064d5a1c5dbc98c54f9b39f Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Mon, 14 Aug 2023 14:11:18 +0800 Subject: [PATCH 139/232] export downloadJson and downloadArraybuffer (#15905) * export downloadJson and downloadArraybuffer add underscore * Update cocos/asset/asset-manager/downloader.ts * Update cocos/asset/asset-manager/downloader.ts * fix lint * fix lint --- cocos/asset/asset-manager/download-file.ts | 14 ++--- cocos/asset/asset-manager/downloader.ts | 62 +++++++++++-------- .../minigame/common/engine/AssetManager.js | 2 + platforms/native/engine/jsb-loader.js | 2 + .../runtime/common/engine/asset-manager.js | 2 + 5 files changed, 49 insertions(+), 33 deletions(-) diff --git a/cocos/asset/asset-manager/download-file.ts b/cocos/asset/asset-manager/download-file.ts index e331b6ebbd6..daceda1279a 100644 --- a/cocos/asset/asset-manager/download-file.ts +++ b/cocos/asset/asset-manager/download-file.ts @@ -22,27 +22,27 @@ THE SOFTWARE. */ -type FileProgressCallback = (loaded: number, total: number) => void; +export type FileProgressCallback = (loaded: number, total: number) => void; export default function downloadFile ( url: string, options: Record, onProgress: FileProgressCallback | null | undefined, - onComplete: ((err: Error | null, data?: any | null) => void), + onComplete: ((err: Error | null, data?: any) => void), ): XMLHttpRequest { const xhr = new XMLHttpRequest(); const errInfo = `download failed: ${url}, status: `; xhr.open('GET', url, true); - if (options.xhrResponseType !== undefined) { xhr.responseType = options.xhrResponseType; } - if (options.xhrWithCredentials !== undefined) { xhr.withCredentials = options.xhrWithCredentials; } - if (options.xhrMimeType !== undefined && xhr.overrideMimeType) { xhr.overrideMimeType(options.xhrMimeType); } - if (options.xhrTimeout !== undefined) { xhr.timeout = options.xhrTimeout; } + if (options.xhrResponseType !== undefined) { xhr.responseType = options.xhrResponseType as XMLHttpRequestResponseType; } + if (options.xhrWithCredentials !== undefined) { xhr.withCredentials = options.xhrWithCredentials as boolean; } + if (options.xhrMimeType !== undefined && xhr.overrideMimeType) { xhr.overrideMimeType(options.xhrMimeType as string); } + if (options.xhrTimeout !== undefined) { xhr.timeout = options.xhrTimeout as number; } if (options.xhrHeader) { for (const header in options.xhrHeader) { - xhr.setRequestHeader(header, options.xhrHeader[header]); + xhr.setRequestHeader(header, options.xhrHeader[header] as string); } } diff --git a/cocos/asset/asset-manager/downloader.ts b/cocos/asset/asset-manager/downloader.ts index d763e639e84..18548777aab 100644 --- a/cocos/asset/asset-manager/downloader.ts +++ b/cocos/asset/asset-manager/downloader.ts @@ -26,45 +26,45 @@ import { BUILD, EDITOR, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { sys, js, misc, path, cclegacy } from '../../core'; import Cache from './cache'; import downloadDomImage from './download-dom-image'; -import downloadFile from './download-file'; +import downloadFile, { FileProgressCallback } from './download-file'; import downloadScript from './download-script'; import { files } from './shared'; import { retry, RetryFunction, urlAppendTimestamp } from './utilities'; import { IConfigOption } from './config'; import { CCON, parseCCONJson, decodeCCONBinary } from '../../serialization/ccon'; -export type DownloadHandler = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void; +export type DownloadHandler = (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)) => void; interface IDownloadRequest { id: string; priority: number; url: string; options: Record; - done: ((err: Error | null, data?: any | null) => void); + done: ((err: Error | null, data?: any) => void); handler: DownloadHandler; } const REGEX = /^(?:\w+:\/\/|\.+\/).+/; -const downloadImage = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { +const downloadImage = (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)): void => { // if createImageBitmap is valid, we can transform blob to ImageBitmap. Otherwise, just use HTMLImageElement to load const func = sys.hasFeature(sys.Feature.IMAGE_BITMAP) && cclegacy.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage; func(url, options, onComplete); }; -const downloadBlob = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { +const downloadBlob = (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)): void => { options.xhrResponseType = 'blob'; - downloadFile(url, options, options.onFileProgress, onComplete); + downloadFile(url, options, options.onFileProgress as FileProgressCallback, onComplete); }; const downloadJson = (url: string, options: Record, onComplete: ((err: Error | null, data?: Record | null) => void)): void => { options.xhrResponseType = 'json'; - downloadFile(url, options, options.onFileProgress, onComplete); + downloadFile(url, options, options.onFileProgress as FileProgressCallback, onComplete); }; -const downloadArrayBuffer = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { +const downloadArrayBuffer = (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)): void => { options.xhrResponseType = 'arraybuffer'; - downloadFile(url, options, options.onFileProgress, onComplete); + downloadFile(url, options, options.onFileProgress as FileProgressCallback, onComplete); }; const downloadCCON = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)): void => { @@ -75,7 +75,7 @@ const downloadCCON = (url: string, options: Record, onComplete: ((e } const cconPreface = parseCCONJson(json); const chunkPromises = Promise.all(cconPreface.chunks.map((chunk): Promise => new Promise((resolve, reject): void => { - downloadArrayBuffer(`${path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer): void => { + downloadArrayBuffer(`${path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer: ArrayBuffer): void => { if (err) { reject(err); } else { @@ -86,7 +86,7 @@ const downloadCCON = (url: string, options: Record, onComplete: ((e chunkPromises.then((chunks): void => { const ccon = new CCON(cconPreface.document, chunks); onComplete(null, ccon); - }).catch((err): void => { + }).catch((err: Error): void => { onComplete(err); }); }); @@ -107,12 +107,12 @@ const downloadCCONB = (url: string, options: Record, onComplete: (( }); }; -const downloadText = (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { +const downloadText = (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)): void => { options.xhrResponseType = 'text'; - downloadFile(url, options, options.onFileProgress, onComplete); + downloadFile(url, options, options.onFileProgress as FileProgressCallback, onComplete); }; -const downloadBundle = (nameOrUrl: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void => { +const downloadBundle = (nameOrUrl: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)): void => { const bundleName = path.basename(nameOrUrl); let url = nameOrUrl; if (!REGEX.test(url)) { @@ -262,6 +262,16 @@ export class Downloader { */ public downloadScript = downloadScript; + /** + * @engineInternal + */ + public _downloadArrayBuffer = downloadArrayBuffer; + + /** + * @engineInternal + */ + public _downloadJson = downloadJson; + // default handler map private _downloaders: Record = { // Images @@ -310,7 +320,7 @@ export class Downloader { default: downloadText, }; - private _downloading = new Cache<((err: Error | null, data?: any | null) => void)[]>(); + private _downloading = new Cache<((err: Error | null, data?: any) => void)[]>(); private _queue: IDownloadRequest[] = []; private _queueDirty = false; // the number of loading thread @@ -360,11 +370,11 @@ export class Downloader { * '.ext': (url, options, onComplete) => onComplete(null, null)}); * */ - public register (type: string, handler: (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void): void; - public register (map: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>): void; + public register (type: string, handler: (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)) => void): void; + public register (map: Record, onComplete: ((err: Error | null, data?: any) => void)) => void>): void; public register ( - type: string | Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void>, - handler?: (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)) => void, + type: string | Record, onComplete: ((err: Error | null, data?: any) => void)) => void>, + handler?: (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)) => void, ): void { if (typeof type === 'object') { js.mixin(this._downloaders, type); @@ -397,7 +407,7 @@ export class Downloader { * download('http://example.com/test.tga', '.tga', { onFileProgress: (loaded, total) => console.log(loaded/total) }, * onComplete: (err) => console.log(err)); */ - public download (id: string, url: string, type: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { + public download (id: string, url: string, type: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)): void { // if it is downloaded, don't download again const file = files.get(id); if (file) { @@ -419,9 +429,9 @@ export class Downloader { } // if download fail, should retry - const maxRetryCount = typeof options.maxRetryCount !== 'undefined' ? options.maxRetryCount : this.maxRetryCount; - const maxConcurrency = typeof options.maxConcurrency !== 'undefined' ? options.maxConcurrency : this.maxConcurrency; - const maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame : this.maxRequestsPerFrame; + const maxRetryCount = typeof options.maxRetryCount !== 'undefined' ? options.maxRetryCount as number : this.maxRetryCount; + const maxConcurrency = typeof options.maxConcurrency !== 'undefined' ? options.maxConcurrency as number : this.maxConcurrency; + const maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame as number : this.maxRequestsPerFrame; const handler = this._downloaders[type] || this._downloaders.default; const process: RetryFunction = (index, callback): void => { @@ -437,7 +447,7 @@ export class Downloader { // refresh this._updateTime(); - const done: ((err: Error | null, data?: any | null) => void) = (err, data): void => { + const done: ((err: Error | null, data?: any) => void) = (err, data): void => { // when finish downloading, update _totalNum this._totalNum--; this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame); @@ -458,9 +468,9 @@ export class Downloader { }; // when retry finished, invoke callbacks - const finale = (err, result): void => { + const finale = (err: Error | null, result : any): void => { if (!err) { files.add(id, result); } - const callbacks = this._downloading.remove(id) as ((err: Error | null, data?: any | null) => void)[]; + const callbacks = this._downloading.remove(id) as ((err: Error | null, data?: any) => void)[]; for (let i = 0, l = callbacks.length; i < l; i++) { callbacks[i](err, result); } diff --git a/platforms/minigame/common/engine/AssetManager.js b/platforms/minigame/common/engine/AssetManager.js index 7d1ceee4a83..8ff48de056b 100644 --- a/platforms/minigame/common/engine/AssetManager.js +++ b/platforms/minigame/common/engine/AssetManager.js @@ -325,6 +325,8 @@ const parsePlist = function (url, options, onComplete) { }; downloader.downloadScript = downloadScript; +downloader._downloadArrayBuffer = downloadArrayBuffer; +downloader._downloadJson = downloadJson; parser.parsePVRTex = parsePVRTex; parser.parsePKMTex = parsePKMTex; parser.parseASTCTex = parseASTCTex; diff --git a/platforms/native/engine/jsb-loader.js b/platforms/native/engine/jsb-loader.js index 5b430aa61c7..f310b02549b 100644 --- a/platforms/native/engine/jsb-loader.js +++ b/platforms/native/engine/jsb-loader.js @@ -291,6 +291,8 @@ parser.parsePKMTex = downloader.downloadDomImage; parser.parseASTCTex = downloader.downloadDomImage; parser.parsePlist = parsePlist; downloader.downloadScript = downloadScript; +downloader._downloadArrayBuffer = downloadArrayBuffer; +downloader._downloadJson = downloadJson; function loadAudioPlayer (url, options, onComplete) { cc.AudioPlayer.load(url).then((player) => { diff --git a/platforms/runtime/common/engine/asset-manager.js b/platforms/runtime/common/engine/asset-manager.js index 7dc1f7d126b..10b691be7ad 100644 --- a/platforms/runtime/common/engine/asset-manager.js +++ b/platforms/runtime/common/engine/asset-manager.js @@ -288,6 +288,8 @@ const parsePlist = function (url, options, onComplete) { }; downloader.downloadScript = downloadScript; +downloader._downloadArrayBuffer = downloadArrayBuffer; +downloader._downloadJson = downloadJson; parser.parsePVRTex = parsePVRTex; parser.parsePKMTex = parsePKMTex; parser.parseASTCTex = parseASTCTex; From b76a4053b583b65d151e75ab907f6104ea3e7934 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 14 Aug 2023 15:07:14 +0800 Subject: [PATCH 140/232] remove duplicate codes and unify logic (#15854) --- cocos/game/game.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/cocos/game/game.ts b/cocos/game/game.ts index 5f3eac8149d..14086b18be7 100644 --- a/cocos/game/game.ts +++ b/cocos/game/game.ts @@ -646,9 +646,7 @@ export class Game extends EventTarget { */ public on (type: string, callback: () => void, target?: any, once?: boolean): any { // Make sure EVENT_ENGINE_INITED callbacks to be invoked - if ((this._engineInited && type === Game.EVENT_ENGINE_INITED) - || (this._inited && type === Game.EVENT_GAME_INITED) - || (this._rendererInitialized && type === Game.EVENT_RENDERER_INITED)) { + if (this.canRegisterEvent(type)) { callback.call(target); } return this.eventTargetOn(type, callback, target, once); @@ -668,12 +666,18 @@ export class Game extends EventTarget { */ public once (type: string, callback: () => void, target?: any): any { // Make sure EVENT_ENGINE_INITED callbacks to be invoked - if (this._engineInited && type === Game.EVENT_ENGINE_INITED) { + if (this.canRegisterEvent(type)) { return callback.call(target); } return this.eventTargetOnce(type, callback, target); } + private canRegisterEvent (type: string): boolean { + return this._engineInited && type === Game.EVENT_ENGINE_INITED + || this._inited && type === Game.EVENT_GAME_INITED + || this._rendererInitialized && type === Game.EVENT_RENDERER_INITED; + } + /** * @en Init game with configuration object. Initialization process like below: * -PreBaseInitEvent From 7cbb06fa0021c0c6a2d395c7d10adb91d49438e5 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 14 Aug 2023 15:34:03 +0800 Subject: [PATCH 141/232] fix some eslint error (#15948) --- cocos/rendering/debug-view.ts | 1 - cocos/rendering/define.ts | 63 ++++-- cocos/rendering/geometry-renderer.ts | 181 +++++++++++++++--- cocos/rendering/index.ts | 1 - cocos/rendering/instanced-buffer.ts | 5 +- cocos/rendering/pipeline-state-manager.ts | 5 +- cocos/rendering/pipeline-ubo.ts | 29 ++- .../post-process/components/blit-screen.ts | 6 +- .../rendering/post-process/components/fsr.ts | 2 +- .../post-process/components/taa-mask.ts | 4 +- .../rendering/post-process/components/taa.ts | 8 +- .../post-process/passes/base-pass.ts | 6 +- .../post-process/passes/blit-screen-pass.ts | 6 +- .../post-process/passes/bloom-pass.ts | 4 +- .../post-process/passes/color-grading-pass.ts | 4 +- .../post-process/passes/forward-final-pass.ts | 6 +- .../passes/forward-transparency-pass.ts | 6 +- .../forward-transparency-simple-pass.ts | 6 +- .../rendering/post-process/passes/fsr-pass.ts | 1 - .../post-process/passes/hbao-pass.ts | 22 ++- .../post-process/passes/setting-pass.ts | 2 +- .../post-process/passes/shadow-pass.ts | 8 +- .../rendering/post-process/passes/taa-pass.ts | 2 +- .../post-process/passes/tone-mapping-pass.ts | 4 +- .../post-process/utils/pass-context.ts | 24 +-- cocos/rendering/render-instanced-queue.ts | 11 +- cocos/rendering/scene-culling.ts | 3 +- 27 files changed, 303 insertions(+), 117 deletions(-) diff --git a/cocos/rendering/debug-view.ts b/cocos/rendering/debug-view.ts index 395b37581b7..28d661ced23 100644 --- a/cocos/rendering/debug-view.ts +++ b/cocos/rendering/debug-view.ts @@ -22,7 +22,6 @@ THE SOFTWARE. */ -import { JSB } from 'internal:constants'; import { cclegacy } from '../core'; import { Root } from '../root'; diff --git a/cocos/rendering/define.ts b/cocos/rendering/define.ts index 5d0d24d6643..6b9c1a3593d 100644 --- a/cocos/rendering/define.ts +++ b/cocos/rendering/define.ts @@ -651,8 +651,13 @@ localDescriptorSetLayout.bindings[UNIFORM_POSITION_MORPH_TEXTURE_BINDING] = UNIF const UNIFORM_NORMAL_MORPH_TEXTURE_NAME = 'cc_NormalDisplacements'; export const UNIFORM_NORMAL_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_NORMAL; const UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX); -const UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, - UNIFORM_NORMAL_MORPH_TEXTURE_NAME, Type.SAMPLER2D, 1); +const UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture( + SetIndex.LOCAL, + UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, + UNIFORM_NORMAL_MORPH_TEXTURE_NAME, + Type.SAMPLER2D, + 1, +); localDescriptorSetLayout.layouts[UNIFORM_NORMAL_MORPH_TEXTURE_NAME] = UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_NORMAL_MORPH_TEXTURE_BINDING] = UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR; @@ -663,8 +668,13 @@ localDescriptorSetLayout.bindings[UNIFORM_NORMAL_MORPH_TEXTURE_BINDING] = UNIFOR const UNIFORM_TANGENT_MORPH_TEXTURE_NAME = 'cc_TangentDisplacements'; export const UNIFORM_TANGENT_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_TANGENT; const UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX); -const UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, - UNIFORM_TANGENT_MORPH_TEXTURE_NAME, Type.SAMPLER2D, 1); +const UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture( + SetIndex.LOCAL, + UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, + UNIFORM_TANGENT_MORPH_TEXTURE_NAME, + Type.SAMPLER2D, + 1, +); localDescriptorSetLayout.layouts[UNIFORM_TANGENT_MORPH_TEXTURE_NAME] = UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_TANGENT_MORPH_TEXTURE_BINDING] = UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR; @@ -675,8 +685,13 @@ localDescriptorSetLayout.bindings[UNIFORM_TANGENT_MORPH_TEXTURE_BINDING] = UNIFO const UNIFORM_LIGHTMAP_TEXTURE_NAME = 'cc_lightingMap'; export const UNIFORM_LIGHTMAP_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_LIGHTMAP; const UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_LIGHTMAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT); -const UNIFORM_LIGHTMAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_LIGHTMAP_TEXTURE_BINDING, - UNIFORM_LIGHTMAP_TEXTURE_NAME, Type.SAMPLER2D, 1); +const UNIFORM_LIGHTMAP_TEXTURE_LAYOUT = new UniformSamplerTexture( + SetIndex.LOCAL, + UNIFORM_LIGHTMAP_TEXTURE_BINDING, + UNIFORM_LIGHTMAP_TEXTURE_NAME, + Type.SAMPLER2D, + 1, +); localDescriptorSetLayout.layouts[UNIFORM_LIGHTMAP_TEXTURE_NAME] = UNIFORM_LIGHTMAP_TEXTURE_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_LIGHTMAP_TEXTURE_BINDING] = UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR; @@ -720,8 +735,13 @@ localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_STORAGE_BINDING] = UNIFORM_ const UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME = 'cc_reflectionProbeCubemap'; export const UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_CUBE; const UNIFORM_REFLECTION_PROBE_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT); -const UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, - UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME, Type.SAMPLER_CUBE, 1); +const UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT = new UniformSamplerTexture( + SetIndex.LOCAL, + UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, + UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME, + Type.SAMPLER_CUBE, + 1, +); localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME] = UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING] = UNIFORM_REFLECTION_PROBE_CUBEMAP_DESCRIPTOR; @@ -732,8 +752,13 @@ localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING] = UN const UNIFORM_REFLECTION_PROBE_TEXTURE_NAME = 'cc_reflectionProbePlanarMap'; export const UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_PLANAR; const UNIFORM_REFLECTION_PROBE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT); -const UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, - UNIFORM_REFLECTION_PROBE_TEXTURE_NAME, Type.SAMPLER2D, 1); +const UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT = new UniformSamplerTexture( + SetIndex.LOCAL, + UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, + UNIFORM_REFLECTION_PROBE_TEXTURE_NAME, + Type.SAMPLER2D, + 1, +); localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_TEXTURE_NAME] = UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING] = UNIFORM_REFLECTION_PROBE_TEXTURE_DESCRIPTOR; @@ -744,8 +769,13 @@ localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING] = UN const UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME = 'cc_reflectionProbeDataMap'; export const UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_DATA_MAP; const UNIFORM_REFLECTION_PROBE_DATA_MAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT); -const UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, - UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME, Type.SAMPLER2D, 1); +const UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT = new UniformSamplerTexture( + SetIndex.LOCAL, + UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, + UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME, + Type.SAMPLER2D, + 1, +); localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME] = UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING] = UNIFORM_REFLECTION_PROBE_DATA_MAP_DESCRIPTOR; @@ -756,8 +786,13 @@ localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING] = U const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME = 'cc_reflectionProbeBlendCubemap'; export const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_BLEND_CUBE; const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT); -const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, - UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME, Type.SAMPLER_CUBE, 1); +const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT = new UniformSamplerTexture( + SetIndex.LOCAL, + UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, + UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME, + Type.SAMPLER_CUBE, + 1, +); localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME] = UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING] = UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_DESCRIPTOR; diff --git a/cocos/rendering/geometry-renderer.ts b/cocos/rendering/geometry-renderer.ts index 6b4eee1aaf9..41ebe43f715 100644 --- a/cocos/rendering/geometry-renderer.ts +++ b/cocos/rendering/geometry-renderer.ts @@ -93,8 +93,12 @@ class GeometryVertexBuffer { this._vertexCount = 0; this._stride = stride; this._vertices = new Float32Array(maxVertices * stride / Float32Array.BYTES_PER_ELEMENT); - this._buffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, maxVertices * stride, stride)); + this._buffer = device.createBuffer(new BufferInfo( + BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + maxVertices * stride, + stride, + )); this._inputAssembler = device.createInputAssembler(new InputAssemblerInfo(attributes, [this._buffer], null)); } @@ -395,8 +399,15 @@ export class GeometryRenderer { } } - public addBoundingBox (aabb: geometry.AABB, color: Color, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform: Mat4 = new Mat4()): void { + public addBoundingBox ( + aabb: geometry.AABB, + color: Color, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform: Mat4 = new Mat4(), + ): void { /** * 2---3 * / / @@ -490,8 +501,19 @@ export class GeometryRenderer { this.addLine(vertices[3], vertices[7], color, depthTest); } - public addCapsule (center: Vec3, radius: number, height: number, color: Color, segmentsU = 32, hemiSegmentsV = 8, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addCapsule ( + center: Vec3, + radius: number, + height: number, + color: Color, + segmentsU = 32, + hemiSegmentsV = 8, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const deltaPhi = Math.PI * 2.0 / segmentsU; const deltaTheta = Math.PI / 2.0 / hemiSegmentsV; const bottomCenter = new Vec3(center.x, center.y - height / 2.0, center.z); @@ -551,8 +573,18 @@ export class GeometryRenderer { } } - public addCylinder (center: Vec3, radius: number, height: number, color: Color, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addCylinder ( + center: Vec3, + radius: number, + height: number, + color: Color, + segments = 32, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const deltaPhi = Math.PI * 2.0 / segments; const bottomCenter = new Vec3(center.x, center.y - height / 2.0, center.z); const topCenter = new Vec3(center.x, center.y + height / 2.0, center.z); @@ -587,8 +619,18 @@ export class GeometryRenderer { } } - public addCone (center: Vec3, radius: number, height: number, color: Color, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addCone ( + center: Vec3, + radius: number, + height: number, + color: Color, + segments = 32, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const deltaPhi = Math.PI * 2.0 / segments; const bottomCenter = new Vec3(center.x, center.y - height / 2.0, center.z); const topCenter = new Vec3(center.x, center.y + height / 2.0, center.z); @@ -636,8 +678,17 @@ export class GeometryRenderer { } } - public addArc (center: Vec3, radius: number, color: Color, startAngle: number, endAngle: number, segments = 32, - depthTest = true, useTransform = false, transform = new Mat4()): void { + public addArc ( + center: Vec3, + radius: number, + color: Color, + startAngle: number, + endAngle: number, + segments = 32, + depthTest = true, + useTransform = false, + transform = new Mat4(), + ): void { const startRadian = toRadian(startAngle); const endRadian = toRadian(endAngle); const deltaPhi = (endRadian - startRadian) / segments; @@ -660,8 +711,17 @@ export class GeometryRenderer { } } - public addPolygon (center: Vec3, radius: number, color: Color, segments = 6, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addPolygon ( + center: Vec3, + radius: number, + color: Color, + segments = 6, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { if (wireframe) { this.addCircle(center, radius, color, segments, depthTest, useTransform, transform); } else { @@ -669,8 +729,17 @@ export class GeometryRenderer { } } - public addDisc (center: Vec3, radius: number, color: Color, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addDisc ( + center: Vec3, + radius: number, + color: Color, + segments = 32, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const deltaPhi = Math.PI * 2.0 / segments; const points = new Array(); const newCenter = new Vec3(center); @@ -701,8 +770,19 @@ export class GeometryRenderer { } } - public addSector (center: Vec3, radius: number, color: Color, startAngle: number, endAngle: number, segments = 32, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addSector ( + center: Vec3, + radius: number, + color: Color, + startAngle: number, + endAngle: number, + segments = 32, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const startRadian = toRadian(startAngle); const endRadian = toRadian(endAngle); const deltaPhi = (endRadian - startRadian) / segments; @@ -735,8 +815,18 @@ export class GeometryRenderer { } } - public addSphere (center: Vec3, radius: number, color: Color, segmentsU = 32, segmentsV = 16, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addSphere ( + center: Vec3, + radius: number, + color: Color, + segmentsU = 32, + segmentsV = 16, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const deltaPhi = Math.PI * 2.0 / segmentsU; const deltaTheta = Math.PI / segmentsV; const points = new Array>(); @@ -777,8 +867,19 @@ export class GeometryRenderer { } } - public addTorus (center: Vec3, bigRadius: number, radius: number, color: Color, segmentsU = 32, segmentsV = 16, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addTorus ( + center: Vec3, + bigRadius: number, + radius: number, + color: Color, + segmentsU = 32, + segmentsV = 16, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const deltaPhi = Math.PI * 2.0 / segmentsU; const deltaTheta = Math.PI * 2.0 / segmentsV; const points = new Array>(); @@ -818,8 +919,16 @@ export class GeometryRenderer { } } - public addOctahedron (center: Vec3, radius: number, color: Color, - wireframe = true, depthTest = true, unlit = false, useTransform = false, transform = new Mat4()): void { + public addOctahedron ( + center: Vec3, + radius: number, + color: Color, + wireframe = true, + depthTest = true, + unlit = false, + useTransform = false, + transform = new Mat4(), + ): void { const points = new Array(); points.push(new Vec3(radius + center.x, center.y, center.z)); @@ -862,8 +971,17 @@ export class GeometryRenderer { } } - public addBezier (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, color: Color, segments = 32, - depthTest = true, useTransform = false, transform = new Mat4()): void { + public addBezier ( + v0: Vec3, + v1: Vec3, + v2: Vec3, + v3: Vec3, + color: Color, + segments = 32, + depthTest = true, + useTransform = false, + transform = new Mat4(), + ): void { const deltaT = 1.0 / segments; const points = new Array(); @@ -936,8 +1054,15 @@ export class GeometryRenderer { } } - public addIndexedMesh (center: Vec3, vertices: Array, indices: Array, color: Color, - depthTest = true, useTransform = false, transform = new Mat4()): void { + public addIndexedMesh ( + center: Vec3, + vertices: Array, + indices: Array, + color: Color, + depthTest = true, + useTransform = false, + transform = new Mat4(), + ): void { for (let i = 0; i < indices.length; i += 3) { const v0 = new Vec3(center.x + vertices[indices[i]].x, center.y + vertices[indices[i]].y, center.z + vertices[indices[i]].z); const v1 = new Vec3(center.x + vertices[indices[i + 1]].x, center.y + vertices[indices[i + 1]].y, center.z + vertices[indices[i + 1]].z); diff --git a/cocos/rendering/index.ts b/cocos/rendering/index.ts index df06cd7656e..b99dea2b298 100644 --- a/cocos/rendering/index.ts +++ b/cocos/rendering/index.ts @@ -24,7 +24,6 @@ import './deprecated'; import * as pipeline from './define'; -import { ForwardPipeline } from './forward/forward-pipeline'; export { pipeline }; diff --git a/cocos/rendering/instanced-buffer.ts b/cocos/rendering/instanced-buffer.ts index 7df49320153..005ff7bc4ee 100644 --- a/cocos/rendering/instanced-buffer.ts +++ b/cocos/rendering/instanced-buffer.ts @@ -23,8 +23,9 @@ */ import { Pass } from '../render-scene'; -import { IInstancedAttributeBlock, SubModel } from '../render-scene/scene'; -import { UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING } from './define'; +import { SubModel } from '../render-scene/scene'; +import { UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, + UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING } from './define'; import { BufferUsageBit, MemoryUsageBit, Device, Texture, InputAssembler, InputAssemblerInfo, Attribute, Buffer, BufferInfo, CommandBuffer, Shader, DescriptorSet } from '../gfx'; diff --git a/cocos/rendering/pipeline-state-manager.ts b/cocos/rendering/pipeline-state-manager.ts index 2df742117a1..4dbb7cd3c3a 100644 --- a/cocos/rendering/pipeline-state-manager.ts +++ b/cocos/rendering/pipeline-state-manager.ts @@ -41,7 +41,10 @@ export class PipelineStateManager { const pipelineLayout = pass.pipelineLayout; const inputState = new InputState(ia.attributes); const psoInfo = new PipelineStateInfo( - shader, pipelineLayout, renderPass, inputState, + shader, + pipelineLayout, + renderPass, + inputState, pass.rasterizerState, pass.depthStencilState, pass.blendState, diff --git a/cocos/rendering/pipeline-ubo.ts b/cocos/rendering/pipeline-ubo.ts index 4961924d62a..38bfb231123 100644 --- a/cocos/rendering/pipeline-ubo.ts +++ b/cocos/rendering/pipeline-ubo.ts @@ -35,7 +35,6 @@ import { RenderWindow } from '../render-scene/core/render-window'; import { builtinResMgr } from '../asset/asset-manager/builtin-res-mgr'; import { Texture2D } from '../asset/assets'; import { DebugViewCompositeType } from './debug-view'; -import { legacyCC } from '../core/global-exports'; import { getDescBindingFromName } from './custom/define'; const _matShadowView = new Mat4(); @@ -91,8 +90,11 @@ export class PipelineUBO { fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.csmLayerColoration ? 1.0 : 0.0) * (10.0 ** 7.0); } - public static updateCameraUBOView (pipeline: PipelineRuntime, bufferView: Float32Array, - camera: Camera): void { + public static updateCameraUBOView ( + pipeline: PipelineRuntime, + bufferView: Float32Array, + camera: Camera, + ): void { const scene = camera.scene ? camera.scene : cclegacy.director.getScene().renderScene; const mainLight = scene.mainLight; const sceneData = pipeline.pipelineSceneData; @@ -217,8 +219,12 @@ export class PipelineUBO { shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance; } - public static updateShadowUBOView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, - csmBufferView: Float32Array, camera: Camera): void { + public static updateShadowUBOView ( + pipeline: PipelineRuntime, + shadowBufferView: Float32Array, + csmBufferView: Float32Array, + camera: Camera, + ): void { const device = pipeline.device; const mainLight = camera.scene!.mainLight; const sceneData = pipeline.pipelineSceneData; @@ -395,8 +401,17 @@ export class PipelineUBO { Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - Mat4.perspective(_matShadowProj, (light as any).angle, 1.0, 0.001, (light as any).range, - true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); + Mat4.perspective( + _matShadowProj, + (light as any).angle, + 1.0, + 0.001, + (light as any).range, + true, + cap.clipSpaceMinZ, + cap.clipSpaceSignY, + 0, + ); Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); diff --git a/cocos/rendering/post-process/components/blit-screen.ts b/cocos/rendering/post-process/components/blit-screen.ts index bf78dc464ac..32363fb6609 100644 --- a/cocos/rendering/post-process/components/blit-screen.ts +++ b/cocos/rendering/post-process/components/blit-screen.ts @@ -18,7 +18,7 @@ class BlitScreenMaterial { } @property - enable = true + enable = true; } @ccclass('cc.BlitScreen') @@ -28,7 +28,7 @@ class BlitScreenMaterial { @executeInEditMode export class BlitScreen extends PostProcessSetting { @property(Material) - _activeMaterials: Material[] = [] + _activeMaterials: Material[] = []; @property({ type: Material, visible: false }) get activeMaterials (): Material[] { return this._activeMaterials; @@ -47,7 +47,7 @@ export class BlitScreen extends PostProcessSetting { } @property(BlitScreenMaterial) - _materials: BlitScreenMaterial[] = [] + _materials: BlitScreenMaterial[] = []; @property(BlitScreenMaterial) get materials (): BlitScreenMaterial[] { diff --git a/cocos/rendering/post-process/components/fsr.ts b/cocos/rendering/post-process/components/fsr.ts index a5ab8f739bf..db52428a12c 100644 --- a/cocos/rendering/post-process/components/fsr.ts +++ b/cocos/rendering/post-process/components/fsr.ts @@ -10,7 +10,7 @@ import { PostProcessSetting } from './post-process-setting'; @executeInEditMode export class FSR extends PostProcessSetting { @serializable - _sharpness = 0.8 + _sharpness = 0.8; @tooltip('i18n:fsr.sharpness') @slide diff --git a/cocos/rendering/post-process/components/taa-mask.ts b/cocos/rendering/post-process/components/taa-mask.ts index 8f257576696..ff416e93a0c 100644 --- a/cocos/rendering/post-process/components/taa-mask.ts +++ b/cocos/rendering/post-process/components/taa-mask.ts @@ -14,7 +14,7 @@ export class TAAMask extends Component { _mask: RenderTexture | undefined; - get mask () { + get mask (): RenderTexture | undefined { if (!this.maskCamera || !this.maskCamera.enabledInHierarchy) { return undefined; } @@ -25,7 +25,7 @@ export class TAAMask extends Component { return this._mask; } - start () { + start (): void { if (!this.maskCamera) { warn('Can not find a Camera for TAAMask'); return; diff --git a/cocos/rendering/post-process/components/taa.ts b/cocos/rendering/post-process/components/taa.ts index 343ee1e4953..fb9c2a6c746 100644 --- a/cocos/rendering/post-process/components/taa.ts +++ b/cocos/rendering/post-process/components/taa.ts @@ -9,13 +9,13 @@ import { PostProcessSetting } from './post-process-setting'; @executeInEditMode export class TAA extends PostProcessSetting { @property - _sampleScale = 1 + _sampleScale = 1; @tooltip('i18n:taa.sampleScale') @slide @range([0.01, 5, 0.01]) @property - get sampleScale () { + get sampleScale (): number { return this._sampleScale; } set sampleScale (v) { @@ -23,12 +23,12 @@ export class TAA extends PostProcessSetting { } @property - _feedback = 0.95 + _feedback = 0.95; @tooltip('i18n:taa.feedback') @slide @range([0.0, 1, 0.01]) @property - get feedback () { + get feedback (): number { return this._feedback; } set feedback (v) { diff --git a/cocos/rendering/post-process/passes/base-pass.ts b/cocos/rendering/post-process/passes/base-pass.ts index cef4cb7942d..3038bfaf661 100644 --- a/cocos/rendering/post-process/passes/base-pass.ts +++ b/cocos/rendering/post-process/passes/base-pass.ts @@ -55,7 +55,7 @@ export abstract class BasePass { abstract name: string; effectName = 'pipeline/post-process/blit-screen'; - _id = 0 + _id = 0; constructor () { this._id = _BasePassID++; } @@ -65,7 +65,7 @@ export abstract class BasePass { // private _materialMap: Map = new Map() - _material: Material | undefined + _material: Material | undefined; get material (): Material { const effectReloaded = false; // if (EDITOR && this._material) { @@ -97,7 +97,7 @@ export abstract class BasePass { } enable = true; - outputNames: string[] = [] + outputNames: string[] = []; lastPass: BasePass | undefined; diff --git a/cocos/rendering/post-process/passes/blit-screen-pass.ts b/cocos/rendering/post-process/passes/blit-screen-pass.ts index 11f8001ee80..3e862328db1 100644 --- a/cocos/rendering/post-process/passes/blit-screen-pass.ts +++ b/cocos/rendering/post-process/passes/blit-screen-pass.ts @@ -1,5 +1,3 @@ -import { EDITOR } from 'internal:constants'; - import { Format } from '../../../gfx'; import { Camera } from '../../../render-scene/scene'; import { Pipeline } from '../../custom/pipeline'; @@ -14,10 +12,10 @@ const outputNames = ['BlitScreenColor0', 'BlitScreenColor1']; export class BlitScreenPass extends SettingPass { get setting (): BlitScreen { return getSetting(BlitScreen); } - name = 'BlitScreenPass' + name = 'BlitScreenPass'; effectName = 'pipeline/post-process/blit-screen'; - outputName = outputNames[0] + outputName = outputNames[0]; slotName (camera: Camera, index = 0): string { return this.outputName; diff --git a/cocos/rendering/post-process/passes/bloom-pass.ts b/cocos/rendering/post-process/passes/bloom-pass.ts index 6c53ec842a1..85330ea852f 100644 --- a/cocos/rendering/post-process/passes/bloom-pass.ts +++ b/cocos/rendering/post-process/passes/bloom-pass.ts @@ -24,9 +24,9 @@ export class BloomPass extends SettingPass { return enable; } - name = 'BloomPass' + name = 'BloomPass'; effectName = 'pipeline/post-process/bloom'; - outputNames = ['BloomColor'] + outputNames = ['BloomColor']; public render (camera: Camera, ppl: Pipeline): void { const cameraID = getCameraUniqueID(camera); diff --git a/cocos/rendering/post-process/passes/color-grading-pass.ts b/cocos/rendering/post-process/passes/color-grading-pass.ts index 6f4dee97a86..d824d077e9f 100644 --- a/cocos/rendering/post-process/passes/color-grading-pass.ts +++ b/cocos/rendering/post-process/passes/color-grading-pass.ts @@ -20,9 +20,9 @@ export class ColorGradingPass extends SettingPass { return enable; } - name = 'ColorGradingPass' + name = 'ColorGradingPass'; effectName = 'pipeline/post-process/color-grading'; - outputNames = ['ColorGrading'] + outputNames = ['ColorGrading']; public render (camera: Camera, ppl: Pipeline): void { const cameraID = getCameraUniqueID(camera); diff --git a/cocos/rendering/post-process/passes/forward-final-pass.ts b/cocos/rendering/post-process/passes/forward-final-pass.ts index 06372f2c185..1ae8bdead67 100644 --- a/cocos/rendering/post-process/passes/forward-final-pass.ts +++ b/cocos/rendering/post-process/passes/forward-final-pass.ts @@ -1,8 +1,4 @@ -import { EDITOR } from 'internal:constants'; - import { Vec4 } from '../../../core'; -import { director } from '../../../game'; - import { ClearFlagBit, Format } from '../../../gfx'; import { Camera } from '../../../render-scene/scene'; import { getCameraUniqueID } from '../../custom/define'; @@ -12,7 +8,7 @@ import { BasePass } from './base-pass'; export class ForwardFinalPass extends BasePass { name = 'ForwardFinalPass'; - outputNames = ['ForwardFinalColor'] + outputNames = ['ForwardFinalColor']; enableInAllEditorCamera = true; diff --git a/cocos/rendering/post-process/passes/forward-transparency-pass.ts b/cocos/rendering/post-process/passes/forward-transparency-pass.ts index 5214195e162..22d438656ef 100644 --- a/cocos/rendering/post-process/passes/forward-transparency-pass.ts +++ b/cocos/rendering/post-process/passes/forward-transparency-pass.ts @@ -72,8 +72,10 @@ export class ForwardTransparencyPass extends BasePass { } pass.addQueue(QueueHint.RENDER_TRANSPARENT) - .addSceneOfCamera(camera, + .addSceneOfCamera( + camera, new LightInfo(), - SceneFlags.UI | SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY); + SceneFlags.UI | SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY, + ); } } diff --git a/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts b/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts index 620c7a56347..72d371eba7b 100644 --- a/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts +++ b/cocos/rendering/post-process/passes/forward-transparency-simple-pass.ts @@ -39,8 +39,10 @@ export class ForwardTransparencySimplePass extends BasePass { public render (camera: Camera, ppl: Pipeline): void { const pass = passContext.pass!; pass.addQueue(QueueHint.RENDER_TRANSPARENT) - .addSceneOfCamera(camera, + .addSceneOfCamera( + camera, new LightInfo(), - SceneFlags.UI | SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY); + SceneFlags.UI | SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY, + ); } } diff --git a/cocos/rendering/post-process/passes/fsr-pass.ts b/cocos/rendering/post-process/passes/fsr-pass.ts index 1231470b58e..b9353c1282a 100644 --- a/cocos/rendering/post-process/passes/fsr-pass.ts +++ b/cocos/rendering/post-process/passes/fsr-pass.ts @@ -8,7 +8,6 @@ import { passContext } from '../utils/pass-context'; import { FSR } from '../components/fsr'; import { getSetting, SettingPass } from './setting-pass'; -import { game } from '../../../game'; const tempVec4 = new Vec4(); diff --git a/cocos/rendering/post-process/passes/hbao-pass.ts b/cocos/rendering/post-process/passes/hbao-pass.ts index 384fb3aa632..aea741f6d32 100644 --- a/cocos/rendering/post-process/passes/hbao-pass.ts +++ b/cocos/rendering/post-process/passes/hbao-pass.ts @@ -182,9 +182,9 @@ export class HBAOPass extends SettingPass { get setting (): HBAO { return getSetting(HBAO); } - name = 'HBAOPass' + name = 'HBAOPass'; effectName = 'pipeline/post-process/hbao'; - outputNames = ['hbaoRTName', 'hbaoBluredRTName'] + outputNames = ['hbaoRTName', 'hbaoBluredRTName']; checkEnable (camera: Camera): boolean { let enable = super.checkEnable(camera); @@ -267,14 +267,16 @@ export class HBAOPass extends SettingPass { this.material.setProperty('uvDepthToEyePosParams', this._hbaoParams!.uvDepthToEyePosParams, passIdx); this.material.setProperty('radiusParam', this._hbaoParams!.radiusParam, passIdx); this.material.setProperty('miscParam', this._hbaoParams!.miscParam, passIdx); - this.material.setProperty('randomTexSize', + this.material.setProperty( + 'randomTexSize', new Vec4( this._hbaoParams!.randomTexture.width, this._hbaoParams!.randomTexture.height, 1.0 / this._hbaoParams!.randomTexture.width, 1.0 / this._hbaoParams!.randomTexture.height, ), - passIdx); + passIdx, + ); this.material.setProperty('blurParam', this._hbaoParams!.blurParam, passIdx); passContext.clearBlack(); @@ -301,14 +303,16 @@ export class HBAOPass extends SettingPass { this.material.setProperty('uvDepthToEyePosParams', this._hbaoParams!.uvDepthToEyePosParams, passIdx); this.material.setProperty('radiusParam', this._hbaoParams!.radiusParam, passIdx); this.material.setProperty('miscParam', this._hbaoParams!.miscParam, passIdx); - this.material.setProperty('randomTexSize', + this.material.setProperty( + 'randomTexSize', new Vec4( this._hbaoParams!.randomTexture.width, this._hbaoParams!.randomTexture.height, 1.0 / this._hbaoParams!.randomTexture.width, 1.0 / this._hbaoParams!.randomTexture.height, ), - passIdx); + passIdx, + ); this.material.setProperty('blurParam', this._hbaoParams!.blurParam, passIdx); let outputRT = super.slotName(camera, 1); @@ -337,14 +341,16 @@ export class HBAOPass extends SettingPass { this.material.setProperty('uvDepthToEyePosParams', this._hbaoParams!.uvDepthToEyePosParams, passIdx); this.material.setProperty('radiusParam', this._hbaoParams!.radiusParam, passIdx); this.material.setProperty('miscParam', this._hbaoParams!.miscParam, passIdx); - this.material.setProperty('randomTexSize', + this.material.setProperty( + 'randomTexSize', new Vec4( this._hbaoParams!.randomTexture.width, this._hbaoParams!.randomTexture.height, 1.0 / this._hbaoParams!.randomTexture.width, 1.0 / this._hbaoParams!.randomTexture.height, ), - passIdx); + passIdx, + ); this.material.setProperty('blurParam', this._hbaoParams!.blurParam, passIdx); passContext.clearFlag = ClearFlagBit.NONE; diff --git a/cocos/rendering/post-process/passes/setting-pass.ts b/cocos/rendering/post-process/passes/setting-pass.ts index 2e7b5326af8..66dd313f000 100644 --- a/cocos/rendering/post-process/passes/setting-pass.ts +++ b/cocos/rendering/post-process/passes/setting-pass.ts @@ -13,7 +13,7 @@ export function getSetting (settingClass: new () = } export abstract class SettingPass extends BasePass { - getSetting = getSetting + getSetting = getSetting; get setting (): PostProcessSetting { return this.getSetting(PostProcessSetting); } checkEnable (camera: Camera): boolean { diff --git a/cocos/rendering/post-process/passes/shadow-pass.ts b/cocos/rendering/post-process/passes/shadow-pass.ts index af623a6f019..417a6a99795 100644 --- a/cocos/rendering/post-process/passes/shadow-pass.ts +++ b/cocos/rendering/post-process/passes/shadow-pass.ts @@ -1,14 +1,14 @@ import { Camera } from '../../../render-scene/scene'; import { buildShadowPasses, getCameraUniqueID } from '../../custom/define'; -import { Pipeline, PipelineType } from '../../custom/pipeline'; +import { Pipeline } from '../../custom/pipeline'; import { passContext } from '../utils/pass-context'; import { BasePass } from './base-pass'; export class ShadowPass extends BasePass { - name = 'ShadowPass' + name = 'ShadowPass'; - mainLightShadows: string[] = [] - spotLightShadows: string[] = [] + mainLightShadows: string[] = []; + spotLightShadows: string[] = []; public render (camera: Camera, ppl: Pipeline): void { passContext.shadowPass = this; diff --git a/cocos/rendering/post-process/passes/taa-pass.ts b/cocos/rendering/post-process/passes/taa-pass.ts index 8ac1904eefc..a8688cd62f1 100644 --- a/cocos/rendering/post-process/passes/taa-pass.ts +++ b/cocos/rendering/post-process/passes/taa-pass.ts @@ -86,7 +86,7 @@ const SampleOffsets = { export class TAAPass extends SettingPass { get setting (): TAA { return getSetting(TAA); } - name = 'TAAPass' + name = 'TAAPass'; effectName = 'pipeline/post-process/taa'; outputNames = ['TAA_First', 'TAA_Second']; diff --git a/cocos/rendering/post-process/passes/tone-mapping-pass.ts b/cocos/rendering/post-process/passes/tone-mapping-pass.ts index 721a9fae0f5..9231c71742b 100644 --- a/cocos/rendering/post-process/passes/tone-mapping-pass.ts +++ b/cocos/rendering/post-process/passes/tone-mapping-pass.ts @@ -33,9 +33,9 @@ import { SettingPass } from './setting-pass'; import { Root } from '../../../root'; export class ToneMappingPass extends SettingPass { - name = 'ToneMappingPass' + name = 'ToneMappingPass'; effectName = 'pipeline/tone-mapping'; - outputNames = ['ToneMapping'] + outputNames = ['ToneMapping']; enableInAllEditorCamera = true; enable = true; diff --git a/cocos/rendering/post-process/utils/pass-context.ts b/cocos/rendering/post-process/utils/pass-context.ts index a3677222b70..a8d783e92b2 100644 --- a/cocos/rendering/post-process/utils/pass-context.ts +++ b/cocos/rendering/post-process/utils/pass-context.ts @@ -11,15 +11,15 @@ import { Vec4 } from '../../../core'; export class PassContext { clearFlag: ClearFlagBit = ClearFlagBit.COLOR; - clearColor = new Color() - clearDepthColor = new Color() - ppl: Pipeline| undefined - camera: Camera| undefined - material: Material| undefined - pass: RenderPassBuilder| undefined - rasterWidth = 0 - rasterHeight = 0 - layoutName = '' + clearColor = new Color(); + clearDepthColor = new Color(); + ppl: Pipeline| undefined; + camera: Camera| undefined; + material: Material| undefined; + pass: RenderPassBuilder| undefined; + rasterWidth = 0; + rasterHeight = 0; + layoutName = ''; shadingScale = 1; viewport = new Rect(); @@ -171,8 +171,10 @@ export class PassContext { blitScreen (passIdx = 0): PassContext { this.pass!.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( - this.camera!, this.material!, passIdx, - SceneFlags.NONE, + this.camera!, +this.material!, +passIdx, +SceneFlags.NONE, ); return this; } diff --git a/cocos/rendering/render-instanced-queue.ts b/cocos/rendering/render-instanced-queue.ts index c97467799c9..7c94ca12372 100644 --- a/cocos/rendering/render-instanced-queue.ts +++ b/cocos/rendering/render-instanced-queue.ts @@ -38,7 +38,7 @@ export class RenderInstancedQueue { */ public queue = new Set(); - private _renderQueue : InstancedBuffer[] = []; + private _renderQueue: InstancedBuffer[] = []; /** * @en Clear the render queue @@ -86,8 +86,13 @@ export class RenderInstancedQueue { * @zh 记录命令缓冲。 * @param cmdBuff The command buffer to store the result */ - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer, - descriptorSet: DescriptorSet | null = null, dynamicOffsets?: Readonly): void { + public recordCommandBuffer ( + device: Device, + renderPass: RenderPass, + cmdBuff: CommandBuffer, + descriptorSet: DescriptorSet | null = null, + dynamicOffsets?: Readonly, + ): void { const it = this._renderQueue.length === 0 ? this.queue.values() : this._renderQueue[Symbol.iterator](); let res = it.next(); diff --git a/cocos/rendering/scene-culling.ts b/cocos/rendering/scene-culling.ts index 419a0bda854..ca507ed247e 100644 --- a/cocos/rendering/scene-culling.ts +++ b/cocos/rendering/scene-culling.ts @@ -21,10 +21,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { EDITOR } from 'internal:constants'; import { Model } from '../render-scene/scene/model'; import { Camera, CameraUsage, SKYBOX_FLAG } from '../render-scene/scene/camera'; -import { Vec3, Pool, warnID, geometry, cclegacy } from '../core'; +import { Vec3, Pool, geometry, cclegacy } from '../core'; import { RenderPipeline } from './render-pipeline'; import { IRenderObject, UBOShadow } from './define'; import { ShadowType, CSMOptimizationMode } from '../render-scene/scene/shadows'; From ceb15e9410a801e0b66f50716d5c54f66cc96c7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 14 Aug 2023 15:45:24 +0800 Subject: [PATCH 142/232] Optimize CCON downloading code (#15950) --- cocos/asset/asset-manager/downloader.ts | 8 ++-- .../minigame/common/engine/AssetManager.js | 43 ------------------- platforms/native/engine/jsb-loader.js | 43 ------------------- .../runtime/common/engine/asset-manager.js | 43 ------------------- 4 files changed, 4 insertions(+), 133 deletions(-) diff --git a/cocos/asset/asset-manager/downloader.ts b/cocos/asset/asset-manager/downloader.ts index 18548777aab..fa87cb3fac9 100644 --- a/cocos/asset/asset-manager/downloader.ts +++ b/cocos/asset/asset-manager/downloader.ts @@ -68,14 +68,14 @@ const downloadArrayBuffer = (url: string, options: Record, onComple }; const downloadCCON = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)): void => { - downloadJson(url, options, (err, json): void => { + downloader._downloadJson(url, options, (err, json): void => { if (err) { onComplete(err); return; } const cconPreface = parseCCONJson(json); const chunkPromises = Promise.all(cconPreface.chunks.map((chunk): Promise => new Promise((resolve, reject): void => { - downloadArrayBuffer(`${path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer: ArrayBuffer): void => { + downloader._downloadArrayBuffer(`${path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer: ArrayBuffer): void => { if (err) { reject(err); } else { @@ -93,7 +93,7 @@ const downloadCCON = (url: string, options: Record, onComplete: ((e }; const downloadCCONB = (url: string, options: Record, onComplete: ((err: Error | null, data?: CCON | null) => void)): void => { - downloadArrayBuffer(url, options, (err, arrayBuffer: ArrayBuffer): void => { + downloader._downloadArrayBuffer(url, options, (err, arrayBuffer: ArrayBuffer): void => { if (err) { onComplete(err); return; @@ -468,7 +468,7 @@ export class Downloader { }; // when retry finished, invoke callbacks - const finale = (err: Error | null, result : any): void => { + const finale = (err: Error | null, result: any): void => { if (!err) { files.add(id, result); } const callbacks = this._downloading.remove(id) as ((err: Error | null, data?: any) => void)[]; for (let i = 0, l = callbacks.length; i < l; i++) { diff --git a/platforms/minigame/common/engine/AssetManager.js b/platforms/minigame/common/engine/AssetManager.js index 8ff48de056b..1f60dac52f2 100644 --- a/platforms/minigame/common/engine/AssetManager.js +++ b/platforms/minigame/common/engine/AssetManager.js @@ -165,46 +165,6 @@ function downloadAsset (url, options, onComplete) { download(url, doNothing, options, options.onFileProgress, onComplete); } -const downloadCCON = (url, options, onComplete) => { - downloadJson(url, options, (err, json) => { - if (err) { - onComplete(err); - return; - } - const cconPreface = cc.internal.parseCCONJson(json); - const chunkPromises = Promise.all(cconPreface.chunks.map((chunk) => new Promise((resolve, reject) => { - downloadArrayBuffer(`${cc.path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => { - if (errChunk) { - reject(errChunk); - } else { - resolve(new Uint8Array(chunkBuffer)); - } - }); - }))); - chunkPromises.then((chunks) => { - const ccon = new cc.internal.CCON(cconPreface.document, chunks); - onComplete(null, ccon); - }).catch((err) => { - onComplete(err); - }); - }); -}; - -const downloadCCONB = (url, options, onComplete) => { - downloadArrayBuffer(url, options, (err, arrayBuffer) => { - if (err) { - onComplete(err); - return; - } - try { - const ccon = cc.internal.decodeCCONBinary(new Uint8Array(arrayBuffer)); - onComplete(null, ccon); - } catch (err) { - onComplete(err); - } - }); -}; - function downloadBundle (nameOrUrl, options, onComplete) { const bundleName = cc.path.basename(nameOrUrl); const version = options.version || cc.assetManager.downloader.bundleVers[bundleName]; @@ -362,9 +322,6 @@ downloader.register({ '.svg': downloadAsset, '.ttc': downloadAsset, - '.ccon': downloadCCON, - '.cconb': downloadCCONB, - // Txt '.txt': downloadAsset, '.xml': downloadAsset, diff --git a/platforms/native/engine/jsb-loader.js b/platforms/native/engine/jsb-loader.js index f310b02549b..59e88aaa395 100644 --- a/platforms/native/engine/jsb-loader.js +++ b/platforms/native/engine/jsb-loader.js @@ -219,46 +219,6 @@ function downloadBundle (nameOrUrl, options, onComplete) { }); } -const downloadCCON = (url, options, onComplete) => { - downloadJson(url, options, (err, json) => { - if (err) { - onComplete(err); - return; - } - const cconPreface = cc.internal.parseCCONJson(json); - const chunkPromises = Promise.all(cconPreface.chunks.map((chunk) => new Promise((resolve, reject) => { - downloadArrayBuffer(`${cc.path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => { - if (errChunk) { - reject(errChunk); - } else { - resolve(new Uint8Array(chunkBuffer)); - } - }); - }))); - chunkPromises.then((chunks) => { - const ccon = new cc.internal.CCON(cconPreface.document, chunks); - onComplete(null, ccon); - }).catch((err) => { - onComplete(err); - }); - }); -}; - -const downloadCCONB = (url, options, onComplete) => { - downloadArrayBuffer(url, options, (err, arrayBuffer) => { - if (err) { - onComplete(err); - return; - } - try { - const ccon = cc.internal.decodeCCONBinary(new Uint8Array(arrayBuffer)); - onComplete(null, ccon); - } catch (err) { - onComplete(err); - } - }); -}; - function downloadArrayBuffer (url, options, onComplete) { download(url, parseArrayBuffer, options, options.onFileProgress, onComplete); } @@ -333,9 +293,6 @@ downloader.register({ '.wav': downloadAsset, '.m4a': downloadAsset, - '.ccon': downloadCCON, - '.cconb': downloadCCONB, - // Video '.mp4': downloadAsset, '.avi': downloadAsset, diff --git a/platforms/runtime/common/engine/asset-manager.js b/platforms/runtime/common/engine/asset-manager.js index 10b691be7ad..ea4645c8d2c 100644 --- a/platforms/runtime/common/engine/asset-manager.js +++ b/platforms/runtime/common/engine/asset-manager.js @@ -211,46 +211,6 @@ function downloadBundle (nameOrUrl, options, onComplete) { } } -const downloadCCON = (url, options, onComplete) => { - downloadJson(url, options, (err, json) => { - if (err) { - onComplete(err); - return; - } - const cconPreface = cc.internal.parseCCONJson(json); - const chunkPromises = Promise.all(cconPreface.chunks.map((chunk) => new Promise((resolve, reject) => { - downloadArrayBuffer(`${cc.path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => { - if (errChunk) { - reject(errChunk); - } else { - resolve(new Uint8Array(chunkBuffer)); - } - }); - }))); - chunkPromises.then((chunks) => { - const ccon = new cc.internal.CCON(cconPreface.document, chunks); - onComplete(null, ccon); - }).catch((err) => { - onComplete(err); - }); - }); -}; - -const downloadCCONB = (url, options, onComplete) => { - downloadArrayBuffer(url, options, (err, arrayBuffer) => { - if (err) { - onComplete(err); - return; - } - try { - const ccon = cc.internal.decodeCCONBinary(new Uint8Array(arrayBuffer)); - onComplete(null, ccon); - } catch (err) { - onComplete(err); - } - }); -}; - function downloadArrayBuffer (url, options, onComplete) { download(url, parseArrayBuffer, options, options.onFileProgress, onComplete); } @@ -340,9 +300,6 @@ downloader.register({ '.json': downloadJson, '.ExportJson': downloadAsset, - '.ccon': downloadCCON, - '.cconb': downloadCCONB, - '.binary': downloadAsset, '.bin': downloadAsset, '.dbbin': downloadAsset, From d007151f2a4cfa9e82a2add4d3c1ad31e370458f Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Mon, 14 Aug 2023 16:02:55 +0800 Subject: [PATCH 143/232] refine code style (#15947) --- .../rendering/post-process/components/blit-screen.ts | 12 ++++++------ cocos/rendering/post-process/components/fsr.ts | 4 ++-- .../post-process/components/post-process-setting.ts | 2 +- .../post-process/components/post-process.ts | 2 +- cocos/rendering/post-process/components/taa.ts | 8 ++++---- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/cocos/rendering/post-process/components/blit-screen.ts b/cocos/rendering/post-process/components/blit-screen.ts index 32363fb6609..ebd4a3fc2f7 100644 --- a/cocos/rendering/post-process/components/blit-screen.ts +++ b/cocos/rendering/post-process/components/blit-screen.ts @@ -7,7 +7,7 @@ import { PostProcessSetting } from './post-process-setting'; @ccclass('cc.BlitScreenMaterial') class BlitScreenMaterial { @property(Material) - _material: Material | undefined; + protected _material: Material | undefined; @property(Material) get material (): Material | undefined { @@ -28,7 +28,7 @@ class BlitScreenMaterial { @executeInEditMode export class BlitScreen extends PostProcessSetting { @property(Material) - _activeMaterials: Material[] = []; + protected _activeMaterials: Material[] = []; @property({ type: Material, visible: false }) get activeMaterials (): Material[] { return this._activeMaterials; @@ -47,7 +47,7 @@ export class BlitScreen extends PostProcessSetting { } @property(BlitScreenMaterial) - _materials: BlitScreenMaterial[] = []; + protected _materials: BlitScreenMaterial[] = []; @property(BlitScreenMaterial) get materials (): BlitScreenMaterial[] { @@ -60,10 +60,10 @@ export class BlitScreen extends PostProcessSetting { globalThis.cce.Engine.repaintInEditMode(); }, 50); } - this.updateActiveMateirals(); + this.updateActiveMaterials(); } - updateActiveMateirals (): void { + updateActiveMaterials (): void { const materials = this._materials; this._activeMaterials.length = 0; for (let i = 0; i < materials.length; i++) { @@ -75,6 +75,6 @@ export class BlitScreen extends PostProcessSetting { } onLoad (): void { - this.updateActiveMateirals(); + this.updateActiveMaterials(); } } diff --git a/cocos/rendering/post-process/components/fsr.ts b/cocos/rendering/post-process/components/fsr.ts index db52428a12c..b3d74377028 100644 --- a/cocos/rendering/post-process/components/fsr.ts +++ b/cocos/rendering/post-process/components/fsr.ts @@ -10,7 +10,7 @@ import { PostProcessSetting } from './post-process-setting'; @executeInEditMode export class FSR extends PostProcessSetting { @serializable - _sharpness = 0.8; + protected _sharpness = 0.8; @tooltip('i18n:fsr.sharpness') @slide @@ -19,7 +19,7 @@ export class FSR extends PostProcessSetting { get sharpness (): number { return this._sharpness; } - set sharpness (v) { + set sharpness (v: number) { this._sharpness = v; } } diff --git a/cocos/rendering/post-process/components/post-process-setting.ts b/cocos/rendering/post-process/components/post-process-setting.ts index 0e7cb12306e..9f27b5bc50e 100644 --- a/cocos/rendering/post-process/components/post-process-setting.ts +++ b/cocos/rendering/post-process/components/post-process-setting.ts @@ -6,7 +6,7 @@ import { PostProcess } from './post-process'; @requireComponent(PostProcess) @executeInEditMode export class PostProcessSetting extends Component { - static _default: PostProcessSetting | undefined + protected static _default: PostProcessSetting | undefined; static get default (): PostProcessSetting { if (!this._default) { this._default = new this(); diff --git a/cocos/rendering/post-process/components/post-process.ts b/cocos/rendering/post-process/components/post-process.ts index ac5454530ad..ef98e92990f 100644 --- a/cocos/rendering/post-process/components/post-process.ts +++ b/cocos/rendering/post-process/components/post-process.ts @@ -17,7 +17,7 @@ export class PostProcess extends Component { global = true; @property - _shadingScale = 1; + protected _shadingScale = 1; @tooltip('i18n:postprocess.shadingScale') @slide @range([0.01, 4, 0.01]) diff --git a/cocos/rendering/post-process/components/taa.ts b/cocos/rendering/post-process/components/taa.ts index fb9c2a6c746..8622b429542 100644 --- a/cocos/rendering/post-process/components/taa.ts +++ b/cocos/rendering/post-process/components/taa.ts @@ -9,7 +9,7 @@ import { PostProcessSetting } from './post-process-setting'; @executeInEditMode export class TAA extends PostProcessSetting { @property - _sampleScale = 1; + protected _sampleScale = 1; @tooltip('i18n:taa.sampleScale') @slide @@ -18,12 +18,12 @@ export class TAA extends PostProcessSetting { get sampleScale (): number { return this._sampleScale; } - set sampleScale (v) { + set sampleScale (v: number) { this._sampleScale = v; } @property - _feedback = 0.95; + protected _feedback = 0.95; @tooltip('i18n:taa.feedback') @slide @range([0.0, 1, 0.01]) @@ -31,7 +31,7 @@ export class TAA extends PostProcessSetting { get feedback (): number { return this._feedback; } - set feedback (v) { + set feedback (v: number) { this._feedback = v; } } From 06327fe407295fa75dc83f88a2314dddd8bb70b5 Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Tue, 15 Aug 2023 11:09:05 +0800 Subject: [PATCH 144/232] fix webgl framebuffer get(width/ height) issue (#15927) --- cocos/gfx/webgl/webgl-framebuffer.ts | 16 ++++++++++++++-- cocos/gfx/webgl2/webgl2-framebuffer.ts | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts index e60aa0b3691..aeab6338e91 100644 --- a/cocos/gfx/webgl/webgl-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -69,13 +69,25 @@ export class WebGLFramebuffer extends Framebuffer { glFramebuffer: null, isOffscreen: true, get width (): number { - return this.isOffscreen ? width : this.gpuColorTextures[0].width; + if (this.isOffscreen) { + return width; + } else if (this.gpuColorTextures.length > 0) { + return this.gpuColorTextures[0].width; + } else { + return this.gpuDepthStencilTexture!.width; + } }, set width (val) { width = val; }, get height (): number { - return this.isOffscreen ? height : this.gpuColorTextures[0].height; + if (this.isOffscreen) { + return height; + } else if (this.gpuColorTextures.length > 0) { + return this.gpuColorTextures[0].height; + } else { + return this.gpuDepthStencilTexture!.height; + } }, set height (val) { height = val; diff --git a/cocos/gfx/webgl2/webgl2-framebuffer.ts b/cocos/gfx/webgl2/webgl2-framebuffer.ts index 8ee609cb4b5..255c7a9a6b3 100644 --- a/cocos/gfx/webgl2/webgl2-framebuffer.ts +++ b/cocos/gfx/webgl2/webgl2-framebuffer.ts @@ -77,7 +77,7 @@ export class WebGL2Framebuffer extends Framebuffer { }, get height (): number { if (this.isOffscreen) { - return width; + return height; } else if (this.gpuColorViews.length > 0) { return this.gpuColorViews[0].gpuTexture.height; } else { From c24a5186dd192b427636f0d5f7e22a51324ffdaa Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Tue, 15 Aug 2023 13:00:30 +0800 Subject: [PATCH 145/232] Custom Pipeline Debug Marker && gfx push marker(gles2,3, vk) (#15957) --- .../renderer/gfx-agent/CommandBufferAgent.cpp | 29 ++++++++++++ .../renderer/gfx-agent/CommandBufferAgent.h | 3 ++ .../renderer/gfx-base/GFXCommandBuffer.h | 3 ++ .../cocos/renderer/gfx-base/GFXDef-common.h | 5 ++ .../renderer/gfx-empty/EmptyCommandBuffer.cpp | 9 ++++ .../renderer/gfx-empty/EmptyCommandBuffer.h | 3 ++ .../renderer/gfx-gles2/GLES2CommandBuffer.cpp | 9 ++++ .../renderer/gfx-gles2/GLES2CommandBuffer.h | 3 ++ .../renderer/gfx-gles2/GLES2Commands.cpp | 18 +++++++ .../cocos/renderer/gfx-gles2/GLES2Commands.h | 4 ++ .../cocos/renderer/gfx-gles2/GLES2Device.cpp | 4 ++ .../renderer/gfx-gles2/GLES2GPUObjects.h | 1 + .../gfx-gles2/GLES2PrimaryCommandBuffer.cpp | 12 +++++ .../gfx-gles2/GLES2PrimaryCommandBuffer.h | 3 ++ .../renderer/gfx-gles3/GLES3CommandBuffer.cpp | 9 ++++ .../renderer/gfx-gles3/GLES3CommandBuffer.h | 3 ++ .../renderer/gfx-gles3/GLES3Commands.cpp | 18 +++++++ .../cocos/renderer/gfx-gles3/GLES3Commands.h | 4 ++ .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 4 ++ .../renderer/gfx-gles3/GLES3GPUObjects.h | 1 + .../gfx-gles3/GLES3PrimaryCommandBuffer.cpp | 12 +++++ .../gfx-gles3/GLES3PrimaryCommandBuffer.h | 3 ++ .../renderer/gfx-metal/MTLCommandBuffer.h | 3 ++ .../renderer/gfx-metal/MTLCommandBuffer.mm | 7 +++ .../gfx-validator/CommandBufferValidator.cpp | 12 +++++ .../gfx-validator/CommandBufferValidator.h | 3 ++ .../renderer/gfx-vulkan/VKCommandBuffer.cpp | 47 +++++++++++++++++++ .../renderer/gfx-vulkan/VKCommandBuffer.h | 5 ++ native/cocos/renderer/gfx-vulkan/VKDevice.cpp | 13 +++++ .../renderer/gfx-vulkan/VKGPUContext.cpp | 3 +- .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 2 + .../renderer/gfx-wgpu/WGPUCommandBuffer.cpp | 11 +++++ .../renderer/gfx-wgpu/WGPUCommandBuffer.h | 3 ++ .../pipeline/custom/NativeExecutor.cpp | 38 +++++++++++++-- 34 files changed, 301 insertions(+), 6 deletions(-) diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 7689387fd31..6e1d70febdb 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -199,6 +199,35 @@ void CommandBufferAgent::endRenderPass() { }); } +void CommandBufferAgent::insertMarker(const MarkerInfo &marker) { + ENQUEUE_MESSAGE_2( + _messageQueue, CommandBufferInsertMarker, + actor, getActor(), + marker, marker, + { + actor->insertMarker(marker); + }); +} + +void CommandBufferAgent::beginMarker(const MarkerInfo &marker) { + ENQUEUE_MESSAGE_2( + _messageQueue, CommandBufferBeginMarker, + actor, getActor(), + marker, marker, + { + actor->beginMarker(marker); + }); +} + +void CommandBufferAgent::endMarker() { + ENQUEUE_MESSAGE_1( + _messageQueue, CommandBufferEndMarker, + actor, getActor(), + { + actor->endMarker(); + }); +} + void CommandBufferAgent::execute(CommandBuffer *const *cmdBuffs, uint32_t count) { if (!count) return; diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h index b3cf37ff0e8..87a6ce8276e 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h @@ -44,6 +44,9 @@ class CC_DLL CommandBufferAgent final : public Agent { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; diff --git a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h index 00a6d46e2aa..d521474ea0c 100644 --- a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h +++ b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h @@ -46,6 +46,9 @@ class CC_DLL CommandBuffer : public GFXObject, public RefCounted { virtual void end() = 0; virtual void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) = 0; virtual void endRenderPass() = 0; + virtual void insertMarker(const MarkerInfo &marker) = 0; + virtual void beginMarker(const MarkerInfo &marker) = 0; + virtual void endMarker() = 0; virtual void bindPipelineState(PipelineState *pso) = 0; virtual void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) = 0; virtual void bindInputAssembler(InputAssembler *ia) = 0; diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index da39c2c6dee..32712dbba97 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -964,6 +964,11 @@ struct Color { }; using ColorList = ccstd::vector; +struct MarkerInfo { + ccstd::string name; + Color color; +}; + struct BindingMappingInfo { /** * For non-vulkan backends, to maintain compatibility and maximize diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp index 8c2e17a36b1..3a6b283ca88 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp @@ -45,6 +45,15 @@ void EmptyCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb void EmptyCommandBuffer::endRenderPass() { } +void EmptyCommandBuffer::insertMarker(const MarkerInfo &marker) { +} + +void EmptyCommandBuffer::beginMarker(const MarkerInfo &marker) { +} + +void EmptyCommandBuffer::endMarker() { +} + void EmptyCommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t count) { } diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h index d429d23f61c..77ef43864f7 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h @@ -35,6 +35,9 @@ class CC_DLL EmptyCommandBuffer final : public CommandBuffer { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp index daaf4efc6e9..34efe7a17db 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp @@ -138,6 +138,15 @@ void GLES2CommandBuffer::nextSubpass() { _curCmdPackage->cmds.push(GLESCmdType::BEGIN_RENDER_PASS); } +void GLES2CommandBuffer::insertMarker(const MarkerInfo &marker) { + std::ignore = marker; +} +void GLES2CommandBuffer::beginMarker(const MarkerInfo &marker) { + std::ignore = marker; +} +void GLES2CommandBuffer::endMarker() { +} + void GLES2CommandBuffer::bindPipelineState(PipelineState *pso) { GLES2GPUPipelineState *gpuPipelineState = static_cast(pso)->gpuPipelineState(); if (_curGPUPipelineState != gpuPipelineState) { diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h index 06185861895..ad4275dad47 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h @@ -48,6 +48,9 @@ class CC_GLES2_API GLES2CommandBuffer : public CommandBuffer { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp index 1d9ca68f441..0ec135ac3ca 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp @@ -3039,6 +3039,24 @@ GLint cmdFuncGLES2GetMaxSampleCount() { return maxSamples; } +void cmdFuncGLES2InsertMarker(GLES2Device *device, GLsizei length, const char *marker) { + if (device->constantRegistry()->debugMarker) { + glInsertEventMarkerEXT(length, marker); + } +} + +void cmdFuncGLES2PushGroupMarker(GLES2Device *device, GLsizei length, const char *marker) { + if (device->constantRegistry()->debugMarker) { + glPushGroupMarkerEXT(length, marker); + } +} + +void cmdFuncGLES2PopGroupMarker(GLES2Device *device) { + if (device->constantRegistry()->debugMarker) { + glPopGroupMarkerEXT(); + } +} + void GLES2GPUBlitManager::initialize() { _gpuShader.name = "Blit Pass"; _gpuShader.blocks.push_back({ diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.h b/native/cocos/renderer/gfx-gles2/GLES2Commands.h index 670b8e3ae34..80ab7d90cf8 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.h @@ -246,6 +246,10 @@ void cmdFuncGLES2BlitTexture(GLES2Device *device, void cmdFuncGLES2ExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmdPackage); +void cmdFuncGLES2InsertMarker(GLES2Device *device, GLsizei length, const char *marker); +void cmdFuncGLES2PushGroupMarker(GLES2Device *device, GLsizei length, const char *marker); +void cmdFuncGLES2PopGroupMarker(GLES2Device *device); + GLint cmdFuncGLES2GetMaxSampleCount(); } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index 38d0864da4b..f07071766e8 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -178,6 +178,10 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { #endif _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = false; // not implement yet. + if (checkExtension(CC_TOSTR(GL_EXT_debug_marker))) { + _gpuConstantRegistry->debugMarker = true; + } + ccstd::string compressedFmts; if (getFormatFeatures(Format::ETC_RGB8) != FormatFeature::NONE) { compressedFmts += "etc1 "; diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index 99ce522f08d..3a37c01abfb 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -42,6 +42,7 @@ struct GLES2GPUConstantRegistry { bool useDrawInstanced = false; bool useInstancedArrays = false; bool useDiscardFramebuffer = false; + bool debugMarker = false; }; class GLES2GPUStateCache; diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp index 1c3832849a8..cdf297701a2 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp @@ -80,6 +80,18 @@ void GLES2PrimaryCommandBuffer::nextSubpass() { cmdFuncGLES2BeginRenderPass(GLES2Device::getInstance(), ++_curSubpassIdx); } +void GLES2PrimaryCommandBuffer::insertMarker(const MarkerInfo &marker) { + cmdFuncGLES2InsertMarker(GLES2Device::getInstance(), marker.name.size(), marker.name.data()); +} + +void GLES2PrimaryCommandBuffer::beginMarker(const MarkerInfo &marker) { + cmdFuncGLES2PushGroupMarker(GLES2Device::getInstance(), marker.name.size(), marker.name.data()); +} + +void GLES2PrimaryCommandBuffer::endMarker() { + cmdFuncGLES2PopGroupMarker(GLES2Device::getInstance()); +} + void GLES2PrimaryCommandBuffer::draw(const DrawInfo &info) { CC_PROFILE(GLES2PrimaryCommandBufferDraw); if (_isStateInvalid) { diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h index 2a3411c9eef..8ef11408f63 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h @@ -39,6 +39,9 @@ class CC_GLES2_API GLES2PrimaryCommandBuffer final : public GLES2CommandBuffer { void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; void nextSubpass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void draw(const DrawInfo &info) override; void setViewport(const Viewport &vp) override; void setScissor(const Rect &rect) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index a7396a35587..b0321b81d40 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -139,6 +139,15 @@ void GLES3CommandBuffer::nextSubpass() { _curCmdPackage->cmds.push(GLESCmdType::BEGIN_RENDER_PASS); } +void GLES3CommandBuffer::insertMarker(const MarkerInfo &marker) { + std::ignore = marker; +} +void GLES3CommandBuffer::beginMarker(const MarkerInfo &marker) { + std::ignore = marker; +} +void GLES3CommandBuffer::endMarker() { +} + void GLES3CommandBuffer::bindPipelineState(PipelineState *pso) { GLES3GPUPipelineState *gpuPipelineState = static_cast(pso)->gpuPipelineState(); if (_curGPUPipelineState != gpuPipelineState) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h index d42b50d43bc..25af0d6d22e 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h @@ -47,6 +47,9 @@ class CC_GLES3_API GLES3CommandBuffer : public CommandBuffer { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 46581b89681..03a57149824 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -2564,6 +2564,24 @@ void cmdFuncGLES3MemoryBarrier(GLES3Device * /*device*/, GLbitfield barriers, GL if (barriersByRegion) GL_CHECK(glMemoryBarrierByRegion(barriersByRegion)); } +void cmdFuncGLES3InsertMarker(GLES3Device *device, GLsizei length, const char *marker) { + if (device->constantRegistry()->debugMarker) { + glInsertEventMarkerEXT(length, marker); + } +} + +void cmdFuncGLES3PushGroupMarker(GLES3Device *device, GLsizei length, const char *marker) { + if (device->constantRegistry()->debugMarker) { + glPushGroupMarkerEXT(length, marker); + } +} + +void cmdFuncGLES3PopGroupMarker(GLES3Device *device) { + if (device->constantRegistry()->debugMarker) { + glPopGroupMarkerEXT(); + } +} + static void uploadBufferData(GLenum target, GLintptr offset, GLsizeiptr length, const void *buffer) { #if 0 GL_CHECK(glBufferSubData(target, offset, length, buffer)); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index c04634354c6..ef9eee6365b 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -313,6 +313,10 @@ void cmdFuncGLES3Dispatch(GLES3Device *device, const GLES3GPUDispatchInfo &info) void cmdFuncGLES3MemoryBarrier(GLES3Device *device, GLbitfield barriers, GLbitfield barriersByRegion); +void cmdFuncGLES3InsertMarker(GLES3Device *device, GLsizei length, const char *marker); +void cmdFuncGLES3PushGroupMarker(GLES3Device *device, GLsizei length, const char *marker); +void cmdFuncGLES3PopGroupMarker(GLES3Device *device); + GLint cmdFuncGLES3GetMaxSampleCount(const GLES3Device *device, Format format, TextureUsage usage, TextureFlags flags); } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index e97f7e00c79..6f3043b9aec 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -148,6 +148,10 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = true; } + if (checkExtension(CC_TOSTR(GL_EXT_debug_marker))) { + _gpuConstantRegistry->debugMarker = true; + } + if (checkExtension(CC_TOSTR(ARM_shader_framebuffer_fetch_depth_stencil))) { _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; fbfLevelStr += "_DEPTH_STENCIL"; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 66588d21014..46332eee71f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -43,6 +43,7 @@ struct GLES3GPUConstantRegistry { MSRTSupportLevel mMSRT{MSRTSupportLevel::NONE}; FBFSupportLevel mFBF{FBFSupportLevel::NONE}; + bool debugMarker = false; }; class GLES3GPUStateCache; diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp index 86219e7e151..bde2aac8991 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp @@ -80,6 +80,18 @@ void GLES3PrimaryCommandBuffer::nextSubpass() { ++_curSubpassIdx; } +void GLES3PrimaryCommandBuffer::insertMarker(const MarkerInfo &marker) { + cmdFuncGLES3InsertMarker(GLES3Device::getInstance(), marker.name.size(), marker.name.data()); +} + +void GLES3PrimaryCommandBuffer::beginMarker(const MarkerInfo &marker) { + cmdFuncGLES3PushGroupMarker(GLES3Device::getInstance(), marker.name.size(), marker.name.data()); +} + +void GLES3PrimaryCommandBuffer::endMarker() { + cmdFuncGLES3PopGroupMarker(GLES3Device::getInstance()); +} + void GLES3PrimaryCommandBuffer::draw(const DrawInfo &info) { CC_PROFILE(GLES3PrimaryCommandBufferDraw); if (_isStateInvalid) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h index 3ae09735302..93ab3a06dd7 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h @@ -39,6 +39,9 @@ class CC_GLES3_API GLES3PrimaryCommandBuffer final : public GLES3CommandBuffer { void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; void nextSubpass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void draw(const DrawInfo &info) override; void setViewport(const Viewport &vp) override; void setScissor(const Rect &rect) override; diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h index bb38f1530cd..51941df646a 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h @@ -56,6 +56,9 @@ class CCMTLCommandBuffer final : public CommandBuffer { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index eef51f0eef7..b1a11e32e84 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -332,6 +332,13 @@ of this software and associated engine source code (the "Software"), a limited, _gpuCommandBufferObj->renderPass->reset(); } +void CCMTLCommandBuffer::insertMarker(const MarkerInfo &marker) { +} +void CCMTLCommandBuffer::beginMarker(const MarkerInfo &marker) { +} +void CCMTLCommandBuffer::endMarker() { +} + void CCMTLCommandBuffer::afterCommit() { _gpuCommandBufferObj->renderPass = nullptr; _gpuCommandBufferObj->fbo = nullptr; diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp index bab7e3c6ca5..fcc1a2c571d 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp @@ -206,6 +206,18 @@ void CommandBufferValidator::endRenderPass() { _actor->endRenderPass(); } +void CommandBufferValidator::insertMarker(const MarkerInfo &marker) { + _actor->insertMarker(marker); +} + +void CommandBufferValidator::beginMarker(const MarkerInfo &marker) { + _actor->beginMarker(marker); +} + +void CommandBufferValidator::endMarker() { + _actor->endMarker(); +} + void CommandBufferValidator::execute(CommandBuffer *const *cmdBuffs, uint32_t count) { CC_ASSERT(isInited()); diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h index 3ec70240be2..75071593d8b 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h @@ -41,6 +41,9 @@ class CC_DLL CommandBufferValidator final : public Agent { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index 7aefa9312fc..f1a7da28720 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -245,6 +245,53 @@ void CCVKCommandBuffer::endRenderPass() { } } +void CCVKCommandBuffer::insertMarker(const MarkerInfo &marker) { + auto *context = CCVKDevice::getInstance()->gpuContext(); + if (context->debugUtils) { + _utilLabelInfo.pLabelName = marker.name.c_str(); + _utilLabelInfo.color[0] = marker.color.x; + _utilLabelInfo.color[1] = marker.color.y; + _utilLabelInfo.color[2] = marker.color.z; + _utilLabelInfo.color[3] = marker.color.w; + vkCmdInsertDebugUtilsLabelEXT(_gpuCommandBuffer->vkCommandBuffer, &_utilLabelInfo); + } else if (context->debugReport) { + _markerInfo.pMarkerName = marker.name.c_str(); + _markerInfo.color[0] = marker.color.x; + _markerInfo.color[1] = marker.color.y; + _markerInfo.color[2] = marker.color.z; + _markerInfo.color[3] = marker.color.w; + vkCmdDebugMarkerInsertEXT(_gpuCommandBuffer->vkCommandBuffer, &_markerInfo); + } +} + +void CCVKCommandBuffer::beginMarker(const MarkerInfo &marker) { + auto *context = CCVKDevice::getInstance()->gpuContext(); + if (context->debugUtils) { + _utilLabelInfo.pLabelName = marker.name.c_str(); + _utilLabelInfo.color[0] = marker.color.x; + _utilLabelInfo.color[1] = marker.color.y; + _utilLabelInfo.color[2] = marker.color.z; + _utilLabelInfo.color[3] = marker.color.w; + vkCmdBeginDebugUtilsLabelEXT(_gpuCommandBuffer->vkCommandBuffer, &_utilLabelInfo); + } else if (context->debugReport) { + _markerInfo.pMarkerName = marker.name.c_str(); + _markerInfo.color[0] = marker.color.x; + _markerInfo.color[1] = marker.color.y; + _markerInfo.color[2] = marker.color.z; + _markerInfo.color[3] = marker.color.w; + vkCmdDebugMarkerBeginEXT(_gpuCommandBuffer->vkCommandBuffer, &_markerInfo); + } +} + +void CCVKCommandBuffer::endMarker() { + auto *context = CCVKDevice::getInstance()->gpuContext(); + if (context->debugUtils) { + vkCmdEndDebugUtilsLabelEXT(_gpuCommandBuffer->vkCommandBuffer); + } else if (context->debugReport) { + vkCmdDebugMarkerEndEXT(_gpuCommandBuffer->vkCommandBuffer); + } +} + void CCVKCommandBuffer::bindPipelineState(PipelineState *pso) { CCVKGPUPipelineState *gpuPipelineState = static_cast(pso)->gpuPipelineState(); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h index 1eae85158ed..55adb5a8e57 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h @@ -41,6 +41,9 @@ class CC_VULKAN_API CCVKCommandBuffer final : public CommandBuffer { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; @@ -105,6 +108,8 @@ class CC_VULKAN_API CCVKCommandBuffer final : public CommandBuffer { ccstd::unordered_map _barrierEvents; ccstd::queue _pendingQueue; + VkDebugMarkerMarkerInfoEXT _markerInfo = {VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT, nullptr}; + VkDebugUtilsLabelEXT _utilLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 85d9bacdfcb..ce3e89b09dc 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -123,6 +123,9 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { VK_KHR_SWAPCHAIN_EXTENSION_NAME, }; requestedExtensions.push_back(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME); +#if CC_DEBUG + requestedExtensions.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME); +#endif if (_gpuDevice->minorVersion < 2) { requestedExtensions.push_back(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME); } @@ -769,6 +772,16 @@ void CCVKDevice::initDeviceFeature() { _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = checkExtension("VK_KHR_depth_stencil_resolve"); + + _gpuContext->debugReport = _gpuContext->checkExtension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME) && + checkExtension(VK_EXT_DEBUG_MARKER_EXTENSION_NAME) && + (vkCmdDebugMarkerBeginEXT != nullptr) && + (vkCmdDebugMarkerInsertEXT != nullptr) && + (vkCmdDebugMarkerEndEXT != nullptr); + _gpuContext->debugUtils = _gpuContext->checkExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME) && + (vkCmdBeginDebugUtilsLabelEXT != nullptr) && + (vkCmdInsertDebugUtilsLabelEXT != nullptr) && + (vkCmdEndDebugUtilsLabelEXT != nullptr); } void CCVKDevice::initFormatFeature() { diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp index 52af6780706..3a3a114aeae 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp @@ -190,7 +190,9 @@ bool CCVKGPUContext::initialize() { break; } } +#endif +#if CC_DEBUG // Check if VK_EXT_debug_utils is supported, which supersedes VK_EXT_Debug_Report bool debugUtils = false; if (isExtensionSupported(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, supportedExtensions)) { @@ -338,7 +340,6 @@ bool CCVKGPUContext::initialize() { vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertiesCount, nullptr); queueFamilyProperties.resize(queueFamilyPropertiesCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertiesCount, queueFamilyProperties.data()); - return true; } diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index edb7dfc6f42..71c4e9cbd2b 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -62,6 +62,8 @@ class CCVKGPUContext final { uint32_t minorVersion = 0; bool validationEnabled = false; + bool debugUtils = false; + bool debugReport = false; ccstd::vector layers; ccstd::vector extensions; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp index d5591fb82cb..1900ad1e405 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp @@ -239,6 +239,17 @@ void CCWGPUCommandBuffer::endRenderPass() { _gpuCommandBufferObj->renderPassBegan = false; } +void CCWGPUCommandBuffer::insertMarker(const MarkerInfo &marker) { + std::ignore = marker; +} + +void CCWGPUCommandBuffer::beginMarker(const MarkerInfo &marker) { + std::ignore = marker; +} + +void CCWGPUCommandBuffer::endMarker() { +} + void CCWGPUCommandBuffer::bindPipelineState(PipelineState *pso) { _gpuCommandBufferObj->stateCache.pipelineState = static_cast(pso); } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h index e621bbcc346..345ba104f4c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h @@ -46,6 +46,9 @@ class CCWGPUCommandBuffer final : public CommandBuffer { void end() override; void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) override; void endRenderPass() override; + void insertMarker(const MarkerInfo &marker) override; + void beginMarker(const MarkerInfo &marker) override; + void endMarker() override; void bindPipelineState(PipelineState *pso) override; void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) override; void bindInputAssembler(InputAssembler *ia) override; diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index aefd8293e5c..bacbc8a90a6 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -59,6 +59,13 @@ namespace render { namespace { constexpr uint32_t INVALID_ID = 0xFFFFFFFF; +constexpr gfx::Color RASTER_COLOR{0.0, 1.0, 0.0, 1.0}; +constexpr gfx::Color RENDER_QUEUE_COLOR{0.0, 0.5, 0.5, 1.0}; +constexpr gfx::Color COMPUTE_COLOR{0.0, 0.0, 1.0, 1.0}; + +gfx::MarkerInfo makeMarkerInfo(const char *str, const gfx::Color &color) { + return gfx::MarkerInfo{str, color}; +} struct RenderGraphVisitorContext { RenderGraphVisitorContext(RenderGraphVisitorContext&&) = delete; @@ -1117,6 +1124,9 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } } void begin(const RasterPass& pass, RenderGraph::vertex_descriptor vertID) const { +#if CC_DEBUG + ctx.cmdBuff->beginMarker(makeMarkerInfo(get(RenderGraph::NameTag{}, ctx.g, vertID).c_str(), RASTER_COLOR)); +#endif const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID); if (!renderData.custom.empty()) { const auto& passes = ctx.ppl->custom.renderPasses; @@ -1142,13 +1152,11 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& res = fetchOrCreateFramebuffer(ctx, pass, ctx.scratch); const auto& data = res; auto* cmdBuff = ctx.cmdBuff; - cmdBuff->beginRenderPass( data.renderPass.get(), data.framebuffer.get(), scissor, data.clearColors.data(), data.clearDepth, data.clearStencil); - ctx.currentPass = data.renderPass.get(); } @@ -1156,6 +1164,10 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { tryBindPerPassDescriptorSet(vertID); } void begin(const RasterSubpass& subpass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) +#if CC_DEBUG + ctx.cmdBuff->insertMarker(makeMarkerInfo(get(RenderGraph::NameTag{}, ctx.g, vertID).c_str(), RASTER_COLOR)); +#endif + const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID); if (!renderData.custom.empty()) { const auto& subpasses = ctx.ppl->custom.renderSubpasses; @@ -1191,6 +1203,10 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { // noop } void begin(const ComputePass& pass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) +#if CC_DEBUG + ctx.cmdBuff->beginMarker(makeMarkerInfo(get(RenderGraph::NameTag{}, ctx.g, vertID).c_str(), COMPUTE_COLOR)); +#endif + const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID); if (!renderData.custom.empty()) { const auto& passes = ctx.ppl->custom.computePasses; @@ -1339,6 +1355,10 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { CC_EXPECTS(false); } void begin(const RenderQueue& queue, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) +#if CC_DEBUG + ctx.cmdBuff->beginMarker(makeMarkerInfo(get(RenderGraph::NameTag{}, ctx.g, vertID).c_str(), RENDER_QUEUE_COLOR)); +#endif + const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID); if (!renderData.custom.empty()) { const auto& queues = ctx.ppl->custom.renderQueues; @@ -1348,7 +1368,6 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { return; } } - if (queue.viewport.width != 0 && queue.viewport.height != 0) { ctx.cmdBuff->setViewport(queue.viewport); } @@ -1462,6 +1481,10 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { ctx.cmdBuff->endRenderPass(); ctx.currentPass = nullptr; ctx.currentPassLayoutID = LayoutGraphData::null_vertex(); + +#if CC_DEBUG + ctx.cmdBuff->endMarker(); +#endif } void end(const RasterSubpass& subpass, RenderGraph::vertex_descriptor vertID) const { // NOLINT(readability-convert-member-functions-to-static) const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID); @@ -1504,7 +1527,9 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { return; } } - +#if CC_DEBUG + ctx.cmdBuff->endMarker(); +#endif std::ignore = pass; } void end(const ResolvePass& pass, RenderGraph::vertex_descriptor vertID) const { @@ -1529,6 +1554,9 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { return; } } +#if CC_DEBUG + ctx.cmdBuff->endMarker(); +#endif std::ignore = pass; } void end(const SceneData& pass, RenderGraph::vertex_descriptor vertID) const { @@ -1551,7 +1579,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } void end(const gfx::Viewport& pass, RenderGraph::vertex_descriptor vertID) const { } - + void mountResource(const ccstd::pmr::string& name) const { // NOLINT(misc-no-recursion) auto resIter = ctx.fgd.resourceAccessGraph.resourceIndex.find(name); if (resIter != ctx.fgd.resourceAccessGraph.resourceIndex.end()) { From 7a554ea28ec7c2777e8d29e985e7d9b607969dcc Mon Sep 17 00:00:00 2001 From: Jiujiang Liu <37231523+moshuying@users.noreply.github.com> Date: Tue, 15 Aug 2023 14:25:08 +0800 Subject: [PATCH 146/232] [Feature] Improve interacive preview (#15655) * improve preview * support key f * eslint fix * support reset camera * update code * format code * format code * update code format * remove key down * update code format --- editor/inspector/assets/fbx/preview.js | 16 ++++++++++++---- editor/inspector/assets/material-header.js | 12 +++++++++++- editor/inspector/assets/mesh-preview.js | 12 +++++++++++- editor/inspector/assets/skeleton-preview.js | 11 ++++++++++- 4 files changed, 44 insertions(+), 7 deletions(-) diff --git a/editor/inspector/assets/fbx/preview.js b/editor/inspector/assets/fbx/preview.js index 8b4fed5d2bb..ad9b5fa0967 100644 --- a/editor/inspector/assets/fbx/preview.js +++ b/editor/inspector/assets/fbx/preview.js @@ -13,7 +13,7 @@ exports.template = /* html */`
-
+
@@ -352,7 +352,7 @@ const Elements = { ready() { const panel = this; panel.$.canvas.addEventListener('mousedown', async (event) => { - await callModelPreviewFunction('onMouseDown', { x: event.x, y: event.y }); + await callModelPreviewFunction('onMouseDown', { x: event.x, y: event.y, button: event.button }); async function mousemove(event) { await callModelPreviewFunction('onMouseMove', { @@ -381,6 +381,14 @@ const Elements = { panel.isPreviewDataDirty = true; }); + panel.$.canvas.addEventListener('wheel', async (event) => { + await callModelPreviewFunction('onMouseWheel', { + wheelDeltaY: event.wheelDeltaY, + wheelDeltaX: event.wheelDeltaX, + }); + panel.isPreviewDataDirty = true; + }); + const GlPreview = Editor._Module.require('PreviewExtends').default; panel.glPreview = new GlPreview('scene:model-preview', 'query-model-preview-data'); panel.isPreviewDataDirty = true; @@ -441,8 +449,8 @@ const Elements = { exports.methods = { /** - * - * @param {boolean} hasModel + * + * @param {boolean} hasModel */ updatePanelHidden(hasModel) { this.$.noModel.hidden = hasModel; diff --git a/editor/inspector/assets/material-header.js b/editor/inspector/assets/material-header.js index 504f650ac97..f0ab30cb00b 100644 --- a/editor/inspector/assets/material-header.js +++ b/editor/inspector/assets/material-header.js @@ -95,6 +95,7 @@ exports.methods = { exports.ready = async function() { const panel = this; + callMaterialPreviewFunction('resetCamera'); callMaterialPreviewFunction('setLightEnable', true); panel.$.light.addEventListener('confirm', async () => { await callMaterialPreviewFunction('setLightEnable', this.$.light.checked); @@ -108,7 +109,7 @@ exports.ready = async function() { }); panel.$.canvas.addEventListener('mousedown', async (event) => { - await callMaterialPreviewFunction('onMouseDown', { x: event.x, y: event.y }); + await callMaterialPreviewFunction('onMouseDown', { x: event.x, y: event.y, button: event.button }); async function mousemove(event) { await callMaterialPreviewFunction('onMouseMove', { @@ -136,6 +137,14 @@ exports.ready = async function() { panel.isPreviewDataDirty = true; }); + panel.$.canvas.addEventListener('wheel', async (event) => { + await callMaterialPreviewFunction('onMouseWheel', { + wheelDeltaY: event.wheelDeltaY, + wheelDeltaX: event.wheelDeltaX + }); + panel.isPreviewDataDirty = true; + }); + const GlPreview = Editor._Module.require('PreviewExtends').default; panel.glPreview = new GlPreview('scene:material-preview', 'query-material-preview-data'); @@ -153,6 +162,7 @@ exports.ready = async function() { exports.update = async function(assetList, metaList) { const panel = this; + callMaterialPreviewFunction('resetCamera'); panel.assetList = assetList; panel.metaList = metaList; diff --git a/editor/inspector/assets/mesh-preview.js b/editor/inspector/assets/mesh-preview.js index 36305763307..a69fd881961 100644 --- a/editor/inspector/assets/mesh-preview.js +++ b/editor/inspector/assets/mesh-preview.js @@ -102,7 +102,7 @@ const Elements = { panel.$.canvas.addEventListener('mousedown', async (event) => { // Non-model previews do not respond to events if (panel.$.previewType.value !== previewSelectType.shaded) { return; } - await callMeshPreviewFunction('onMouseDown', { x: event.x, y: event.y }); + await callMeshPreviewFunction('onMouseDown', { x: event.x, y: event.y, button: event.button }); async function mousemove(event) { await callMeshPreviewFunction('onMouseMove', { @@ -131,6 +131,16 @@ const Elements = { panel.isPreviewDataDirty = true; }); + panel.$.canvas.addEventListener('wheel', async (event) => { + // Non-model previews do not respond to events + if (panel.$.previewType.value !== previewSelectType.shaded) { return; } + await callMeshPreviewFunction('onMouseWheel', { + wheelDeltaY: event.wheelDeltaY, + wheelDeltaX: event.wheelDeltaX, + }); + panel.isPreviewDataDirty = true; + }); + const GlPreview = Editor._Module.require('PreviewExtends').default; panel.glPreview = new GlPreview('scene:mesh-preview', 'query-mesh-preview-data'); diff --git a/editor/inspector/assets/skeleton-preview.js b/editor/inspector/assets/skeleton-preview.js index a30033d94dd..f588382f703 100644 --- a/editor/inspector/assets/skeleton-preview.js +++ b/editor/inspector/assets/skeleton-preview.js @@ -49,7 +49,7 @@ const Elements = { const panel = this; panel.$.canvas.addEventListener('mousedown', async (event) => { - await callSkeletonPreviewFunction('onMouseDown', { x: event.x, y: event.y }); + await callSkeletonPreviewFunction('onMouseDown', { x: event.x, y: event.y, button: event.button }); async function mousemove(event) { await callSkeletonPreviewFunction('onMouseMove', { @@ -79,6 +79,15 @@ const Elements = { panel.isPreviewDataDirty = true; }); + panel.$.canvas.addEventListener('wheel', async (event) => { + await callSkeletonPreviewFunction('onMouseWheel', { + wheelDeltaY: event.wheelDeltaY, + wheelDeltaX: event.wheelDeltaX, + }); + panel.isPreviewDataDirty = true; + }); + + const GlPreview = Editor._Module.require('PreviewExtends').default; panel.glPreview = new GlPreview('scene:skeleton-preview', 'query-skeleton-preview-data'); From c63fc769d5d6d5befd41eace5d342aea4c4fe236 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Tue, 15 Aug 2023 14:30:24 +0800 Subject: [PATCH 147/232] update prefab meta version (#15907) --- editor/assets/default_prefab/2d/Camera.prefab.meta | 2 +- editor/assets/default_prefab/2d/ui/Canvas.prefab.meta | 2 +- editor/assets/default_prefab/3d/Capsule.prefab.meta | 2 +- editor/assets/default_prefab/3d/Cone.prefab.meta | 2 +- editor/assets/default_prefab/3d/Cube.prefab.meta | 2 +- editor/assets/default_prefab/3d/Cylinder.prefab.meta | 2 +- editor/assets/default_prefab/3d/Plane.prefab.meta | 2 +- editor/assets/default_prefab/3d/Quad.prefab.meta | 2 +- editor/assets/default_prefab/3d/Sphere.prefab.meta | 2 +- editor/assets/default_prefab/3d/Torus.prefab.meta | 2 +- editor/assets/default_prefab/Camera.prefab.meta | 2 +- editor/assets/default_prefab/Terrain.prefab.meta | 2 +- editor/assets/default_prefab/light/Point Light.prefab.meta | 2 +- .../default_prefab/light/Ranged Directional Light.prefab.meta | 2 +- editor/assets/default_prefab/light/Reflection Probe.prefab.meta | 2 +- editor/assets/default_prefab/light/Sphere Light.prefab.meta | 2 +- editor/assets/default_prefab/light/Spot Light.prefab.meta | 2 +- editor/assets/default_prefab/ui/Button.prefab.meta | 2 +- editor/assets/default_prefab/ui/Canvas.prefab.meta | 2 +- editor/assets/default_prefab/ui/EditBox.prefab.meta | 2 +- editor/assets/default_prefab/ui/Graphics.prefab.meta | 2 +- editor/assets/default_prefab/ui/Label.prefab.meta | 2 +- editor/assets/default_prefab/ui/Layout.prefab.meta | 2 +- editor/assets/default_prefab/ui/Mask.prefab.meta | 2 +- editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta | 2 +- editor/assets/default_prefab/ui/ProgressBar.prefab.meta | 2 +- editor/assets/default_prefab/ui/RichText.prefab.meta | 2 +- editor/assets/default_prefab/ui/ScrollView.prefab.meta | 2 +- editor/assets/default_prefab/ui/Slider.prefab.meta | 2 +- editor/assets/default_prefab/ui/Sprite.prefab.meta | 2 +- editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta | 2 +- editor/assets/default_prefab/ui/SpriteSplash.prefab.meta | 2 +- editor/assets/default_prefab/ui/TiledMap.prefab.meta | 2 +- editor/assets/default_prefab/ui/Toggle.prefab.meta | 2 +- editor/assets/default_prefab/ui/ToggleContainer.prefab.meta | 2 +- editor/assets/default_prefab/ui/VideoPlayer.prefab.meta | 2 +- editor/assets/default_prefab/ui/WebView.prefab.meta | 2 +- editor/assets/default_prefab/ui/Widget.prefab.meta | 2 +- editor/assets/default_prefab/ui/pageView.prefab.meta | 2 +- editor/assets/tools/debug-view-runtime-control.prefab.meta | 2 +- 40 files changed, 40 insertions(+), 40 deletions(-) diff --git a/editor/assets/default_prefab/2d/Camera.prefab.meta b/editor/assets/default_prefab/2d/Camera.prefab.meta index 43be72409f2..9140b81984e 100644 --- a/editor/assets/default_prefab/2d/Camera.prefab.meta +++ b/editor/assets/default_prefab/2d/Camera.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "3487d118-0158-4983-93fe-c3822790e7c5", diff --git a/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta b/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta index e2403d261e1..955de65ec05 100644 --- a/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta +++ b/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "4c33600e-9ca9-483b-b734-946008261697", diff --git a/editor/assets/default_prefab/3d/Capsule.prefab.meta b/editor/assets/default_prefab/3d/Capsule.prefab.meta index 16e79757c68..a5a21cf019f 100644 --- a/editor/assets/default_prefab/3d/Capsule.prefab.meta +++ b/editor/assets/default_prefab/3d/Capsule.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "73ce1f7f-d1f4-4942-ad93-66ca3b3041ab", diff --git a/editor/assets/default_prefab/3d/Cone.prefab.meta b/editor/assets/default_prefab/3d/Cone.prefab.meta index 99f4f574333..5b5113f9f0d 100644 --- a/editor/assets/default_prefab/3d/Cone.prefab.meta +++ b/editor/assets/default_prefab/3d/Cone.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "6350d660-e888-4acf-a552-f3b719ae9110", diff --git a/editor/assets/default_prefab/3d/Cube.prefab.meta b/editor/assets/default_prefab/3d/Cube.prefab.meta index 7c12ed89459..12020ef451a 100644 --- a/editor/assets/default_prefab/3d/Cube.prefab.meta +++ b/editor/assets/default_prefab/3d/Cube.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "30da77a1-f02d-4ede-aa56-403452ee7fde", diff --git a/editor/assets/default_prefab/3d/Cylinder.prefab.meta b/editor/assets/default_prefab/3d/Cylinder.prefab.meta index 71bf262ef47..6c5684fdca6 100644 --- a/editor/assets/default_prefab/3d/Cylinder.prefab.meta +++ b/editor/assets/default_prefab/3d/Cylinder.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "ab3e16f9-671e-48a7-90b7-d0884d9cbb85", diff --git a/editor/assets/default_prefab/3d/Plane.prefab.meta b/editor/assets/default_prefab/3d/Plane.prefab.meta index 7bae40651b3..d38151b7473 100644 --- a/editor/assets/default_prefab/3d/Plane.prefab.meta +++ b/editor/assets/default_prefab/3d/Plane.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "40563723-f8fc-4216-99ea-a81636435c10", diff --git a/editor/assets/default_prefab/3d/Quad.prefab.meta b/editor/assets/default_prefab/3d/Quad.prefab.meta index 32c9ec2aab2..dc8e2b361b2 100644 --- a/editor/assets/default_prefab/3d/Quad.prefab.meta +++ b/editor/assets/default_prefab/3d/Quad.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "34a07346-9f62-4a84-90ae-cb83f7a426c1", diff --git a/editor/assets/default_prefab/3d/Sphere.prefab.meta b/editor/assets/default_prefab/3d/Sphere.prefab.meta index 5a2a2da0fad..ab4f2ec0c6f 100644 --- a/editor/assets/default_prefab/3d/Sphere.prefab.meta +++ b/editor/assets/default_prefab/3d/Sphere.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "655c9519-1a37-472b-bae6-29fefac0b550", diff --git a/editor/assets/default_prefab/3d/Torus.prefab.meta b/editor/assets/default_prefab/3d/Torus.prefab.meta index 7ec5945df32..eb825d2f575 100644 --- a/editor/assets/default_prefab/3d/Torus.prefab.meta +++ b/editor/assets/default_prefab/3d/Torus.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "d47f5d5e-c931-4ff4-987b-cc818a728b82", diff --git a/editor/assets/default_prefab/Camera.prefab.meta b/editor/assets/default_prefab/Camera.prefab.meta index 8f1baf0ca72..c59e4c5e4a4 100644 --- a/editor/assets/default_prefab/Camera.prefab.meta +++ b/editor/assets/default_prefab/Camera.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "bb0a6472-cd67-4afb-a031-94fca8f4cc92", diff --git a/editor/assets/default_prefab/Terrain.prefab.meta b/editor/assets/default_prefab/Terrain.prefab.meta index 2b0c2d2db4d..4cd34a340d4 100644 --- a/editor/assets/default_prefab/Terrain.prefab.meta +++ b/editor/assets/default_prefab/Terrain.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "90e8b0d4-12dc-412d-9156-ea1fdb18c15b", diff --git a/editor/assets/default_prefab/light/Point Light.prefab.meta b/editor/assets/default_prefab/light/Point Light.prefab.meta index 4af906d625c..54d9e7a4705 100644 --- a/editor/assets/default_prefab/light/Point Light.prefab.meta +++ b/editor/assets/default_prefab/light/Point Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "03029371-ee64-4f14-820a-d495ad7cdc29", diff --git a/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta b/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta index 27a9e7d9482..9181f35f84d 100644 --- a/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta +++ b/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "df72d0f6-49d3-452a-b082-8b23d38b33af", diff --git a/editor/assets/default_prefab/light/Reflection Probe.prefab.meta b/editor/assets/default_prefab/light/Reflection Probe.prefab.meta index ee7309cdab8..872b7155bc6 100644 --- a/editor/assets/default_prefab/light/Reflection Probe.prefab.meta +++ b/editor/assets/default_prefab/light/Reflection Probe.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "d8b49b64-cfba-4cfa-be53-1e469547b28b", diff --git a/editor/assets/default_prefab/light/Sphere Light.prefab.meta b/editor/assets/default_prefab/light/Sphere Light.prefab.meta index 6079668c77f..f6235f6b6d1 100644 --- a/editor/assets/default_prefab/light/Sphere Light.prefab.meta +++ b/editor/assets/default_prefab/light/Sphere Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "4182ee46-ffa0-4de2-b66b-c93cc6c7e9b8", diff --git a/editor/assets/default_prefab/light/Spot Light.prefab.meta b/editor/assets/default_prefab/light/Spot Light.prefab.meta index 1183e7231ef..911d5933b42 100644 --- a/editor/assets/default_prefab/light/Spot Light.prefab.meta +++ b/editor/assets/default_prefab/light/Spot Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "7a49aa24-bd7a-40a8-b31a-b2a9da85abcd", diff --git a/editor/assets/default_prefab/ui/Button.prefab.meta b/editor/assets/default_prefab/ui/Button.prefab.meta index 0083d6b4730..6b0771367ba 100644 --- a/editor/assets/default_prefab/ui/Button.prefab.meta +++ b/editor/assets/default_prefab/ui/Button.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "90bdd2a9-2838-4888-b66c-e94c8b7a5169", diff --git a/editor/assets/default_prefab/ui/Canvas.prefab.meta b/editor/assets/default_prefab/ui/Canvas.prefab.meta index 3fedba353a8..4384e4d0773 100644 --- a/editor/assets/default_prefab/ui/Canvas.prefab.meta +++ b/editor/assets/default_prefab/ui/Canvas.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "f773db21-62b8-4540-956a-29bacf5ddbf5", diff --git a/editor/assets/default_prefab/ui/EditBox.prefab.meta b/editor/assets/default_prefab/ui/EditBox.prefab.meta index fd9818f9ec4..f3ead2aa227 100644 --- a/editor/assets/default_prefab/ui/EditBox.prefab.meta +++ b/editor/assets/default_prefab/ui/EditBox.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "05e79121-8675-4551-9ad7-1b901a4025db", diff --git a/editor/assets/default_prefab/ui/Graphics.prefab.meta b/editor/assets/default_prefab/ui/Graphics.prefab.meta index bd27edc00ed..406c853a9f5 100644 --- a/editor/assets/default_prefab/ui/Graphics.prefab.meta +++ b/editor/assets/default_prefab/ui/Graphics.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "c96e159e-43ea-4a16-8279-05bc39119d1a", diff --git a/editor/assets/default_prefab/ui/Label.prefab.meta b/editor/assets/default_prefab/ui/Label.prefab.meta index e6618c474cf..2c633805df3 100644 --- a/editor/assets/default_prefab/ui/Label.prefab.meta +++ b/editor/assets/default_prefab/ui/Label.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "36008810-7ad3-47c0-8112-e30aee089e45", diff --git a/editor/assets/default_prefab/ui/Layout.prefab.meta b/editor/assets/default_prefab/ui/Layout.prefab.meta index f3eb67a7375..ac6f83cd8ab 100644 --- a/editor/assets/default_prefab/ui/Layout.prefab.meta +++ b/editor/assets/default_prefab/ui/Layout.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "a9ef7dfc-ea8b-4cf8-918e-36da948c4de0", diff --git a/editor/assets/default_prefab/ui/Mask.prefab.meta b/editor/assets/default_prefab/ui/Mask.prefab.meta index 24665d8fb56..2b415c21c59 100644 --- a/editor/assets/default_prefab/ui/Mask.prefab.meta +++ b/editor/assets/default_prefab/ui/Mask.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "7fa63aed-f3e2-46a5-8a7c-c1a1adf6cea6", diff --git a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta index b9d8833352b..4876341a321 100644 --- a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta +++ b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "f396261e-3e06-41ec-bdd6-9a8b6d99026f", diff --git a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta index 3611777f751..2f564bd5be8 100644 --- a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta +++ b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "0d9353c4-6fb9-49bb-bc62-77f1750078c2", diff --git a/editor/assets/default_prefab/ui/RichText.prefab.meta b/editor/assets/default_prefab/ui/RichText.prefab.meta index 20f31329057..09136191923 100644 --- a/editor/assets/default_prefab/ui/RichText.prefab.meta +++ b/editor/assets/default_prefab/ui/RichText.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "fc6bfcfa-8086-4326-809b-0ba1226bac7d", diff --git a/editor/assets/default_prefab/ui/ScrollView.prefab.meta b/editor/assets/default_prefab/ui/ScrollView.prefab.meta index 181bba25466..a54b724011e 100644 --- a/editor/assets/default_prefab/ui/ScrollView.prefab.meta +++ b/editor/assets/default_prefab/ui/ScrollView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "c1baa707-78d6-4b89-8d5d-0b7fdf0c39bc", diff --git a/editor/assets/default_prefab/ui/Slider.prefab.meta b/editor/assets/default_prefab/ui/Slider.prefab.meta index d2a1e307889..e74b124a086 100644 --- a/editor/assets/default_prefab/ui/Slider.prefab.meta +++ b/editor/assets/default_prefab/ui/Slider.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "2bd7e5b6-cd8c-41a1-8136-ddb8efbf6326", diff --git a/editor/assets/default_prefab/ui/Sprite.prefab.meta b/editor/assets/default_prefab/ui/Sprite.prefab.meta index 6730fc2d496..da1efd5e39a 100644 --- a/editor/assets/default_prefab/ui/Sprite.prefab.meta +++ b/editor/assets/default_prefab/ui/Sprite.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "9db8cd0b-cbe4-42e7-96a9-a239620c0a9d", diff --git a/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta index 8778f9d8b0b..40cf1cc1d08 100644 --- a/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta +++ b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "279ed042-5a65-4efe-9afb-2fc23c61e15a", diff --git a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta index 0d0314abfe6..cbfcc852751 100644 --- a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta +++ b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "e5f21aad-3a69-4011-ac62-b74352ac025e", diff --git a/editor/assets/default_prefab/ui/TiledMap.prefab.meta b/editor/assets/default_prefab/ui/TiledMap.prefab.meta index bc8c3ce131a..4b1b2c4e25c 100644 --- a/editor/assets/default_prefab/ui/TiledMap.prefab.meta +++ b/editor/assets/default_prefab/ui/TiledMap.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "3139fa4f-8c42-4ce6-98be-15e848d9734c", diff --git a/editor/assets/default_prefab/ui/Toggle.prefab.meta b/editor/assets/default_prefab/ui/Toggle.prefab.meta index 06548ff1b1c..bd92c9057e5 100644 --- a/editor/assets/default_prefab/ui/Toggle.prefab.meta +++ b/editor/assets/default_prefab/ui/Toggle.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "0e89afe7-56de-4f99-96a1-cba8a75bedd2", diff --git a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta index 970e885179b..311dc9b3c86 100644 --- a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta +++ b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "2af73429-41d1-4346-9062-7798e42945dd", diff --git a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta index db30f12dd43..9f090bd41eb 100644 --- a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta +++ b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "7e089eaf-fa97-40d7-8a20-741a152585df", diff --git a/editor/assets/default_prefab/ui/WebView.prefab.meta b/editor/assets/default_prefab/ui/WebView.prefab.meta index e3ea7e3eef3..a5df7884ecc 100644 --- a/editor/assets/default_prefab/ui/WebView.prefab.meta +++ b/editor/assets/default_prefab/ui/WebView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "9c541fa2-1dc8-4d8b-813a-aec89133f5b1", diff --git a/editor/assets/default_prefab/ui/Widget.prefab.meta b/editor/assets/default_prefab/ui/Widget.prefab.meta index 42a5c51e716..bcf252290f4 100644 --- a/editor/assets/default_prefab/ui/Widget.prefab.meta +++ b/editor/assets/default_prefab/ui/Widget.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "36ed4422-3542-4cc4-bf02-dc4bfc590836", diff --git a/editor/assets/default_prefab/ui/pageView.prefab.meta b/editor/assets/default_prefab/ui/pageView.prefab.meta index 8e7a54907e6..95d4ec9593f 100644 --- a/editor/assets/default_prefab/ui/pageView.prefab.meta +++ b/editor/assets/default_prefab/ui/pageView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "20a5d8cb-ccad-4543-a937-fccd98c9f3de", diff --git a/editor/assets/tools/debug-view-runtime-control.prefab.meta b/editor/assets/tools/debug-view-runtime-control.prefab.meta index d6157b53851..8ed35ee2c61 100644 --- a/editor/assets/tools/debug-view-runtime-control.prefab.meta +++ b/editor/assets/tools/debug-view-runtime-control.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.46", "importer": "prefab", "imported": true, "uuid": "7f4ddeab-efa9-4b76-bf6a-029520f68461", From 88bad37193fd0ea804ecc48347d0a7091a943bdf Mon Sep 17 00:00:00 2001 From: oahc09 Date: Tue, 15 Aug 2023 15:06:32 +0800 Subject: [PATCH 148/232] improve:xr pico enable detach device thread when use vulkan (#15926) --- native/cocos/renderer/GFXDeviceManager.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/native/cocos/renderer/GFXDeviceManager.h b/native/cocos/renderer/GFXDeviceManager.h index 04fda885a05..15d5d1538dd 100644 --- a/native/cocos/renderer/GFXDeviceManager.h +++ b/native/cocos/renderer/GFXDeviceManager.h @@ -82,10 +82,6 @@ class CC_DLL DeviceManager final { #endif #ifdef CC_USE_VULKAN - #if XR_OEM_PICO - Device::isSupportDetachDeviceThread = false; - #endif - bool skipVulkan = false; #if CC_PLATFORM == CC_PLATFORM_ANDROID auto sdkVersion = BasePlatform::getPlatform()->getSdkVersion(); From 22ab4b2e4485d4b3f4ebd27ae0e38d7bbe5327f4 Mon Sep 17 00:00:00 2001 From: oahc09 Date: Tue, 15 Aug 2023 15:07:37 +0800 Subject: [PATCH 149/232] improve:xr pico use vk1.1 (#15959) --- native/cocos/platform/java/modules/XRInterface.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cocos/platform/java/modules/XRInterface.cpp b/native/cocos/platform/java/modules/XRInterface.cpp index a9995cbfe55..cc9981801a0 100644 --- a/native/cocos/platform/java/modules/XRInterface.cpp +++ b/native/cocos/platform/java/modules/XRInterface.cpp @@ -481,7 +481,7 @@ void XRInterface::initialize(void *javaVM, void *activity) { #if XR_OEM_PICO std::string graphicsApiName = GraphicsApiOpenglES; #if CC_USE_VULKAN - graphicsApiName = GraphicsApiVulkan_1_0; + graphicsApiName = GraphicsApiVulkan_1_1; #endif xr::XrEntry::getInstance()->createXrInstance(graphicsApiName.c_str()); #endif From 012531ffeb515b8cd97e421178e288ab274b06e5 Mon Sep 17 00:00:00 2001 From: bofeng-song Date: Tue, 15 Aug 2023 16:59:11 +0800 Subject: [PATCH 150/232] Fix logic error of audio's currentTime (#15962) --- pal/audio/minigame/player-minigame.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index cecf6e83231..8f6ed0a67ed 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -329,6 +329,7 @@ export class AudioPlayerMinigame implements OperationQueueable { if (this._state === AudioState.PLAYING && !this._seeking) { time = clamp(time, 0, this.duration); this._seeking = true; + this._cacheTime = time; this._eventTarget.once(AudioEvent.SEEKED, resolve); this._innerAudioContext.seek(time); } else { From dfe70e83a4361ad4421521a612faa5e17ed092be Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Wed, 16 Aug 2023 11:20:03 +0800 Subject: [PATCH 151/232] deprecated UIMeshRenderer (#15956) * deprecated UIMeshRenderer * update * add info * fix CI --- cocos/2d/components/ui-mesh-renderer.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index 9542a49abbd..1cf5f6791f7 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -34,7 +34,7 @@ import { NativeUIModelProxy } from '../renderer/native-2d'; import { uiRendererManager } from '../framework/ui-renderer-manager'; import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; import { MeshRenderData, RenderData } from '../renderer/render-data'; -import { assert, cclegacy } from '../../core'; +import { assert, cclegacy, warn } from '../../core'; import { RenderDrawInfoType } from '../renderer/render-draw-info'; import type { UIRenderer } from '../framework/ui-renderer'; @@ -47,6 +47,8 @@ import type { UIRenderer } from '../framework/ui-renderer'; * @zh * UI 模型基础组件。 * 当你在 UI 中放置模型或者粒子的时候,必须添加该组件才能渲染。该组件必须放置在带有 [[MeshRenderer]] 或者 [[ParticleSystem]] 组件的节点上。 + * @deprecated This component is not recommended to be used, please use Render Texture instead. + * See [UIMeshRenderer Reference](https://docs.cocos.com/creator/manual/en/ui-system/components/editor/ui-model.html) */ @ccclass('cc.UIMeshRenderer') @help('i18n:cc.UIMeshRenderer') @@ -99,7 +101,7 @@ export class UIMeshRenderer extends Component { this._modelComponent = this.getComponent('cc.ModelRenderer') as ModelRenderer; if (!this._modelComponent) { - console.warn(`node '${this.node && this.node.name}' doesn't have any renderable component`); + warn(`node '${this.node && this.node.name}' doesn't have any renderable component`); return; } if (JSB) { @@ -176,7 +178,7 @@ export class UIMeshRenderer extends Component { } } - private _uploadRenderData (index): void { + private _uploadRenderData (index: number): void { if (JSB) { const renderData = MeshRenderData.add(); // TODO: here we weirdly use UIMeshRenderer as UIRenderer @@ -200,6 +202,7 @@ export class UIMeshRenderer extends Component { * 注意:不要手动调用该函数,除非你理解整个流程。 */ public postUpdateAssembler (render: IBatcher): void { + // No behavior for this component } public update (): void { @@ -251,12 +254,14 @@ export class UIMeshRenderer extends Component { * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ public setNodeDirty (): void { + // No behavior for this component } /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ public setTextureDirty (): void { + // No behavior for this component } protected _canRender (): boolean { From e2b1e2c3186c3e6621c69248779bcbfe9e1d88a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Wed, 16 Aug 2023 11:43:39 +0800 Subject: [PATCH 152/232] show node component icon (#15850) --- editor/inspector/contributions/node.js | 1 + 1 file changed, 1 insertion(+) diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index e454f83b46d..cba64780a8c 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -1211,6 +1211,7 @@ const Elements = {
+ ${component.type}${component.mountedRoot ? '+' : ''} From cdaff8725e9e765cec6cce815abde1dff471322f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 16 Aug 2023 14:06:34 +0800 Subject: [PATCH 153/232] Optimize general animation performance 3.8.0 (#15582) * Optimize general animation performance 3.8.0 * Fix lint --- cocos/animation/animation-clip.ts | 21 +++++++++++++-------- cocos/animation/tracks/vector-track.ts | 19 +++++++++---------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/cocos/animation/animation-clip.ts b/cocos/animation/animation-clip.ts index 7285e2a1fd9..eca1c287722 100644 --- a/cocos/animation/animation-clip.ts +++ b/cocos/animation/animation-clip.ts @@ -26,7 +26,9 @@ import { ccclass, serializable } from 'cc.decorator'; import { DEBUG } from 'internal:constants'; import { Asset } from '../asset/assets/asset'; import { SpriteFrame } from '../2d/assets/sprite-frame'; -import { errorID, warnID, cclegacy, js, geometry, approx, clamp, Mat4, Quat, Vec3, murmurhash2_32_gc, binarySearchEpsilon, assertIsTrue, RealCurve } from '../core'; +import { errorID, warnID, cclegacy, js, geometry, approx, clamp, Mat4, Quat, + Vec3, murmurhash2_32_gc, binarySearchEpsilon, assertIsTrue, RealCurve, +} from '../core'; import { SkelAnimDataHub } from '../3d/skeletal-animation/skeletal-animation-data-hub'; import { WrapMode as AnimationWrapMode, WrapMode } from './types'; import { Node } from '../scene-graph/node'; @@ -790,9 +792,9 @@ export class AnimationClip extends Asset { ratios: number[]; eventGroups: IAnimationEventGroup[]; } = { - ratios: [], - eventGroups: [], - }; + ratios: [], + eventGroups: [], + }; private _createEvalWithBinder (target: unknown, binder: Binder, rootMotionOptions: RootMotionOptions | undefined): AnimationClipEvaluation { if (this._legacyDataDirty) { @@ -1039,12 +1041,14 @@ class TrackEvalStatus { constructor (binding: RuntimeBinding, trackEval: TrackEval) { this._binding = binding; this._trackEval = trackEval; + this._shouldEvaluateDefault = !!binding.getValue && trackEval.requiresDefault; } public evaluate (time: number): void { const { _binding: binding, _trackEval: trackEval } = this; - const defaultValue = binding.getValue && trackEval.requiresDefault - ? binding.getValue() as TValue extends unknown ? unknown : Readonly + const defaultValue = this._shouldEvaluateDefault + // See `this._shouldEvaluateDefault` for the assertion. + ? (binding.getValue!)() as TValue extends unknown ? unknown : Readonly : undefined; const value = trackEval.evaluate(time, defaultValue); binding.setValue(value); @@ -1052,6 +1056,7 @@ class TrackEvalStatus { private _binding: RuntimeBinding; private _trackEval: TrackEval; + private _shouldEvaluateDefault = true; } interface AnimationClipEvalContext { @@ -1450,7 +1455,7 @@ class RootMotionEvaluation { } function relativeTransform (out: Mat4, from: Mat4, to: Mat4): void { -Mat4.invert(out, from); + Mat4.invert(out, from); Mat4.multiply(out, to, out); } @@ -1533,7 +1538,7 @@ class EventEvaluator { } } - public reset () { + public reset (): void { this._lastFrameIndex = -1; this._lastIterations = 0.0; this._lastDirection = 0; diff --git a/cocos/animation/tracks/vector-track.ts b/cocos/animation/tracks/vector-track.ts index fa71b8263bf..468d71e2a3c 100644 --- a/cocos/animation/tracks/vector-track.ts +++ b/cocos/animation/tracks/vector-track.ts @@ -141,21 +141,20 @@ export class Vec3TrackEval implements TrackEval { } public evaluate (time: number, defaultValue?: Readonly): Vec3 { + const { _x, _y, _z, _result } = this; if (defaultValue) { - Vec3.copy(this._result, defaultValue); + Vec3.copy(_result, defaultValue); } - - if (this._x) { - this._result.x = this._x.evaluate(time); + if (_x) { + _result.x = _x.evaluate(time); } - if (this._y) { - this._result.y = this._y.evaluate(time); + if (_y) { + _result.y = _y.evaluate(time); } - if (this._z) { - this._result.z = this._z.evaluate(time); + if (_z) { + _result.z = _z.evaluate(time); } - - return this._result; + return _result; } private _result: Vec3 = new Vec3(); From 7ed24f87ad21900c0bb68bbfc30062acef0ce915 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Wed, 16 Aug 2023 14:10:49 +0800 Subject: [PATCH 154/232] update native/external-config to v3.8.1-10 (#15965) --- native/external-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external-config.json b/native/external-config.json index 5427b2b8bfa..b16d14480ec 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-9" + "checkout": "v3.8.1-10" } } From a7213c3b6cb0099bb446cf2acd612f954be7033c Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Wed, 16 Aug 2023 14:11:03 +0800 Subject: [PATCH 155/232] RichText: support set default font color (#15669) * add richText default color * doc --- cocos/2d/components/rich-text.ts | 45 ++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/cocos/2d/components/rich-text.ts b/cocos/2d/components/rich-text.ts index 385f5cb2647..a81d5ea8743 100644 --- a/cocos/2d/components/rich-text.ts +++ b/cocos/2d/components/rich-text.ts @@ -236,6 +236,26 @@ export class RichText extends Component { this._updateRichTextStatus(); } + /** + * @en + * Font color of RichText. Works when the text content does not have a color parameter set. Transparency cascade is not supported. + * + * @zh + * 富文本默认文字颜色。在文本内容没有设置颜色参数时生效。暂不支持颜色级联。 + */ + @type(Color) + get fontColor (): Color { + return this._fontColor; + } + set fontColor (value: Color) { + if (this._fontColor === value) { + return; + } + + this._fontColor = value; + this._updateTextDefaultColor(); + } + /** * @en * Custom System font of RichText. @@ -454,6 +474,8 @@ export class RichText extends Component { @serializable protected _fontSize = 40; @serializable + protected _fontColor: Color = Color.WHITE.clone(); + @serializable protected _maxWidth = 0; @serializable protected _fontFamily = 'Arial'; @@ -1023,6 +1045,21 @@ export class RichText extends Component { } } + protected _updateTextDefaultColor (): void { + for (let i = 0; i < this._segments.length; ++i) { + const segment = this._segments[i]; + const label = segment.node.getComponent(Label); + if (!label) { + continue; + } + if (this._textArray[segment.styleIndex]?.style?.color) { + continue; + } + + label.color = this._fontColor; + } + } + protected _updateRichText (): void { if (!this.enabledInHierarchy) { return; @@ -1241,7 +1278,11 @@ export class RichText extends Component { } if (textStyle) { - label.color = this._convertLiteralColorValue(textStyle.color || 'white'); + if (textStyle.color) { + label.color = this._convertLiteralColorValue(textStyle.color); + } else { + label.color = this._fontColor; + } label.isBold = !!textStyle.bold; label.isItalic = !!textStyle.italic; // TODO: temporary implementation, the italic effect should be implemented in the internal of label-assembler. @@ -1293,7 +1334,7 @@ export class RichText extends Component { protected _resetLabelState (label: Label): void { label.fontSize = this._fontSize; - label.color = Color.WHITE; + label.color = this._fontColor; label.isBold = false; label.isItalic = false; label.isUnderline = false; From 02f7d6e8bb7f194d3cfc61176990a2ae4ed6d5f7 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Wed, 16 Aug 2023 15:05:06 +0800 Subject: [PATCH 156/232] V3.8.1 mesh collider set mesh (#15520) * bullet mesh-collider supports changing mesh after initialization #15363 * physx mesh-collider supports changing mesh after initialization #15363 * tweak --- .../bullet/shapes/bullet-trimesh-shape.ts | 42 ++++++++++--------- .../physx/shapes/physx-trimesh-shape.ts | 8 ++-- .../physics/physx/shapes/PhysXTrimesh.cpp | 1 + 3 files changed, 28 insertions(+), 23 deletions(-) diff --git a/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts b/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts index 8893c1fbffc..935fe7f4b93 100644 --- a/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts @@ -42,28 +42,30 @@ export class BulletTrimeshShape extends BulletShape implements ITrimeshShape { if (!this._isInitialized) return; if (this._impl && BulletCache.isNotEmptyShape(this._impl)) { - // TODO: change the mesh after initialization - warnID(9620); - } else { - const mesh = v; - if (mesh && mesh.renderingSubMeshes.length > 0) { - if (this.collider.convex) { - const btTriangleMesh = this._getBtTriangleMesh(mesh); - this._impl = bt.ConvexTriangleMeshShape_new(btTriangleMesh); - } else { - this.btBVHMeshShape = BulletBvhTriangleMeshShape.getBulletBvhTriangleMeshShape(mesh.hash, mesh); - this._impl = bt.ScaledBvhTriangleMeshShape_new(this.btBVHMeshShape.bulletBvhTriangleMeshShapePtr, 1, 1, 1); - } - const bt_v3 = BulletCache.instance.BT_V3_0; - cocos2BulletVec3(bt_v3, this._collider.node.worldScale); - bt.CollisionShape_setLocalScaling(this._impl, bt_v3); - bt.CollisionShape_setMargin(this._impl, 0.01); - this.setCompound(this._compound); - this.updateByReAdd(); - this.setWrapper(); + if (this._compound) { bt.CompoundShape_removeChildShape(this._compound, this._impl); } + bt._safe_delete(this._impl, EBulletType.EBulletTypeCollisionShape); + BulletCache.delWrapper(this._impl, BulletShape.TYPE); + this._impl = 0; + } + + const mesh = v; + if (mesh && mesh.renderingSubMeshes.length > 0) { + if (this.collider.convex) { + const btTriangleMesh = this._getBtTriangleMesh(mesh); + this._impl = bt.ConvexTriangleMeshShape_new(btTriangleMesh); } else { - this._impl = bt.EmptyShape_static(); + this.btBVHMeshShape = BulletBvhTriangleMeshShape.getBulletBvhTriangleMeshShape(mesh.hash, mesh); + this._impl = bt.ScaledBvhTriangleMeshShape_new(this.btBVHMeshShape.bulletBvhTriangleMeshShapePtr, 1, 1, 1); } + const bt_v3 = BulletCache.instance.BT_V3_0; + cocos2BulletVec3(bt_v3, this._collider.node.worldScale); + bt.CollisionShape_setLocalScaling(this._impl, bt_v3); + bt.CollisionShape_setMargin(this._impl, 0.01); + this.setCompound(this._compound); + this.updateByReAdd(); + this.setWrapper(); + } else { + this._impl = bt.EmptyShape_static(); } } diff --git a/cocos/physics/physx/shapes/physx-trimesh-shape.ts b/cocos/physics/physx/shapes/physx-trimesh-shape.ts index 77841f09846..bdbd797b326 100644 --- a/cocos/physics/physx/shapes/physx-trimesh-shape.ts +++ b/cocos/physics/physx/shapes/physx-trimesh-shape.ts @@ -27,7 +27,7 @@ import { IVec3Like, Quat, Vec3 } from '../../../core'; import { Mesh } from '../../../3d/assets'; import { MeshCollider, PhysicsMaterial } from '../../framework'; import { ITrimeshShape } from '../../spec/i-physics-shape'; -import { createConvexMesh, createMeshGeometryFlags, createTriangleMesh, PX, _trans, removeReference } from '../physx-adapter'; +import { addReference, createConvexMesh, createMeshGeometryFlags, createTriangleMesh, PX, _trans, removeReference } from '../physx-adapter'; import { EPhysXShapeType, PhysXShape } from './physx-shape'; import { AttributeName } from '../../../gfx'; import { PhysXInstance } from '../physx-instance'; @@ -42,6 +42,7 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape { setMesh (v: Mesh | null): void { if (v && v.renderingSubMeshes.length > 0) { if (this._impl != null) { + this.removeFromBody(); removeReference(this, this._impl); this._impl.release(); this._impl = null; @@ -49,7 +50,7 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape { const physics = PhysXInstance.physics; const collider = this.collider; - const pxmat = this.getSharedMaterial(collider.sharedMaterial!); + const pxmat = this.getSharedMaterial(collider.sharedMaterial); const meshScale = PhysXShape.MESH_SCALE; meshScale.setScale(Vec3.ONE); meshScale.setRotation(Quat.IDENTITY); @@ -73,7 +74,8 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape { } this.updateGeometry(); this._impl = physics.createShape(this.geometry, pxmat, true, this._flags); - this.updateByReAdd(); + this.addToBody(); + addReference(this, this._impl);//in case setMesh is called after initialization } } diff --git a/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp b/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp index f4b0506044c..e8f854d16d4 100644 --- a/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp +++ b/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp @@ -38,6 +38,7 @@ void PhysXTrimesh::setMesh(uint32_t objectID) { uintptr_t handle = PhysXWorld::getInstance().getPXPtrWithPXObjectID(objectID); if (handle == 0) return; if (_mShape) { + getSharedBody().removeShape(*this); eraseFromShapeMap(); _mShape->release(); _mShape = nullptr; From 1256656efd31a85a6770665be81cfac61609158b Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Wed, 16 Aug 2023 15:16:43 +0800 Subject: [PATCH 157/232] deferred tone-mapping and fog with float output in custom pipeline (#15968) --- cocos/render-scene/core/pass.ts | 16 +++++++++ ...g-pass.ts => float-output-process-pass.ts} | 10 +++--- cocos/rendering/post-process/passes/index.ts | 2 +- .../post-process/post-process-builder.ts | 9 ++--- .../main-functions/misc/sky-fs.chunk | 2 +- .../render-to-scene/pipeline/forward-fs.chunk | 20 +++++------ ...ing.effect => float-output-process.effect} | 33 ++++++++++++++++--- ....meta => float-output-process.effect.meta} | 0 .../pipeline/post-process/chunks/hbao.chunk | 2 +- native/cocos/scene/Pass.cpp | 15 +++++++++ native/cocos/scene/Pass.h | 1 + 11 files changed, 84 insertions(+), 26 deletions(-) rename cocos/rendering/post-process/passes/{tone-mapping-pass.ts => float-output-process-pass.ts} (89%) rename editor/assets/effects/pipeline/{tone-mapping.effect => float-output-process.effect} (56%) rename editor/assets/effects/pipeline/{tone-mapping.effect.meta => float-output-process.effect.meta} (100%) diff --git a/cocos/render-scene/core/pass.ts b/cocos/render-scene/core/pass.ts index 4345d8c5003..408d5938c5f 100644 --- a/cocos/render-scene/core/pass.ts +++ b/cocos/render-scene/core/pass.ts @@ -546,6 +546,10 @@ export class Pass { this._defines[patch.name] = patch.value; } + if (this._isBlend) { + this._defines.CC_IS_TRANSPARENCY_PASS = 1; + } + let shader: Shader | null = null; if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { const program = (cclegacy.rendering.programLib as ProgramLibrary) @@ -564,15 +568,27 @@ export class Pass { return shader; } + protected get _isBlend (): boolean { + let bBlend = false; + for (const target of this.blendState.targets) { + if (target.blend) { + bBlend = true; + } + } + return bBlend; + } + // internal use /** * @private */ + // eslint-disable-next-line @typescript-eslint/no-empty-function public beginChangeStatesSilently (): void {} /** * @private */ + // eslint-disable-next-line @typescript-eslint/no-empty-function public endChangeStatesSilently (): void {} protected _doInit (info: IPassInfoFull, copyDefines = false): void { diff --git a/cocos/rendering/post-process/passes/tone-mapping-pass.ts b/cocos/rendering/post-process/passes/float-output-process-pass.ts similarity index 89% rename from cocos/rendering/post-process/passes/tone-mapping-pass.ts rename to cocos/rendering/post-process/passes/float-output-process-pass.ts index 9231c71742b..4570061fe2e 100644 --- a/cocos/rendering/post-process/passes/tone-mapping-pass.ts +++ b/cocos/rendering/post-process/passes/float-output-process-pass.ts @@ -32,10 +32,10 @@ import { passContext } from '../utils/pass-context'; import { SettingPass } from './setting-pass'; import { Root } from '../../../root'; -export class ToneMappingPass extends SettingPass { - name = 'ToneMappingPass'; - effectName = 'pipeline/tone-mapping'; - outputNames = ['ToneMapping']; +export class FloatOutputProcessPass extends SettingPass { + name = 'FloatOutputProcessesPass'; + effectName = 'pipeline/float-output-processes'; + outputNames = ['FloatOutputProcesses']; enableInAllEditorCamera = true; enable = true; @@ -49,6 +49,7 @@ export class ToneMappingPass extends SettingPass { passContext.material = this.material; const input = this.lastPass!.slotName(camera, 0); + const inputDS = passContext.depthSlotName; const output = this.slotName(camera, 0); const layoutName = 'tone-mapping'; const passName = `tone-mapping${cameraID}`; @@ -59,6 +60,7 @@ export class ToneMappingPass extends SettingPass { passContext.updatePassViewPort() .addRenderPass(layoutName, passName) .setPassInput(input, 'u_texSampler') + .setPassInput(inputDS, 'DepthTex') .addRasterView(output, Format.RGBA8) .blitScreen(passIndx) .version(); diff --git a/cocos/rendering/post-process/passes/index.ts b/cocos/rendering/post-process/passes/index.ts index 1c69822da92..00009f2f35a 100644 --- a/cocos/rendering/post-process/passes/index.ts +++ b/cocos/rendering/post-process/passes/index.ts @@ -9,7 +9,7 @@ export * from './bloom-pass'; export * from './fxaa-pass'; export * from './forward-final-pass'; export * from './shadow-pass'; -export * from './tone-mapping-pass'; +export * from './float-output-process-pass'; export * from './forward-transparency-pass'; export * from './forward-transparency-simple-pass'; export * from './skin-pass'; diff --git a/cocos/rendering/post-process/post-process-builder.ts b/cocos/rendering/post-process/post-process-builder.ts index 550d8fa15dd..5dd938caef3 100644 --- a/cocos/rendering/post-process/post-process-builder.ts +++ b/cocos/rendering/post-process/post-process-builder.ts @@ -19,7 +19,8 @@ import { PostProcess } from './components/post-process'; import { director } from '../../game'; import { Camera as CameraComponent } from '../../misc'; -import { BloomPass, ColorGradingPass, ForwardTransparencyPass, ForwardTransparencySimplePass, FxaaPass, SkinPass, ToneMappingPass } from './passes'; +import { BloomPass, ColorGradingPass, FloatOutputProcessPass, ForwardTransparencyPass, + ForwardTransparencySimplePass, FxaaPass, SkinPass } from './passes'; import { PipelineEventType } from '../pipeline-event'; export class PostProcessBuilder implements PipelineBuilder { @@ -50,13 +51,13 @@ export class PostProcessBuilder implements PipelineBuilder { // depth-based shading this.addPass(new HBAOPass()); + // float output related deferred processing: hdr + fog + this.addPass(new FloatOutputProcessPass()); + // transparency should after hdr and depth-based shading // temporary ignore CC_USE_FLOAT_OUTPUT this.addPass(new ForwardTransparencyPass()); - // float output related processing: hdr + fog - this.addPass(new ToneMappingPass()); - // user post-processing this.addPass(new TAAPass()); this.addPass(new FxaaPass()); diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk index ec31cee9515..36e8e4c8eb2 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk @@ -17,7 +17,7 @@ void main() { #if CC_USE_RGBE_OUTPUT color = packRGBE(color.rgb); - #elif !CC_USE_FLOAT_OUTPUT + #else//todo: change to #elif !CC_USE_FLOAT_OUTPUT when sky render queue has been fixed with custom pipeline color.rgb = HDRToLDR(color.rgb); color.rgb = LinearToSRGB(color.rgb); #endif diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index fc75b629d9b..a2c0d94165c 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -128,26 +128,24 @@ void main() { #endif #endif - // Fog, rgbe and gamma output can't apply fog with forward-add pass - // todo: apply fogColorBrightness to fogColor for supporting scatter lighting with HDR - #if CC_USE_FOG != CC_FOG_NONE - #if CC_USE_FLOAT_OUTPUT - CC_APPLY_FOG_BASE(color, fogFactor); - #elif !CC_FORWARD_ADD - CC_APPLY_FOG_BASE(color, fogFactor); - #endif - #endif - // Color output #if CC_USE_RGBE_OUTPUT color = packRGBE(color.rgb); // for reflection-map #else color = CCSurfacesDebugDisplayInvalidNumber(color); - #if !CC_USE_FLOAT_OUTPUT + #if !CC_USE_FLOAT_OUTPUT || CC_IS_TRANSPARENCY_PASS color.rgb = HDRToLDR(color.rgb); color.rgb = LinearToSRGB(color.rgb); #endif #endif + // Fog, rgbe and gamma output can't apply fog with forward-add pass + // todo: apply fogColorBrightness to fogColor for supporting scatter lighting with HDR + #if CC_USE_FOG != CC_FOG_NONE && (!CC_USE_FLOAT_OUTPUT || CC_IS_TRANSPARENCY_PASS) + #if !CC_FORWARD_ADD + CC_APPLY_FOG_BASE(color, fogFactor); + #endif + #endif + fragColorX = color; } diff --git a/editor/assets/effects/pipeline/tone-mapping.effect b/editor/assets/effects/pipeline/float-output-process.effect similarity index 56% rename from editor/assets/effects/pipeline/tone-mapping.effect rename to editor/assets/effects/pipeline/float-output-process.effect index d280e6b52d6..055d728a4e9 100644 --- a/editor/assets/effects/pipeline/tone-mapping.effect +++ b/editor/assets/effects/pipeline/float-output-process.effect @@ -24,11 +24,15 @@ CCProgram tonemap-fs %{ #include #include #include + #include + #include in vec2 v_uv; #pragma rate u_texSampler pass layout(binding = 0) uniform sampler2D u_texSampler; + #pragma rate DepthTex pass + layout(binding = 1) uniform sampler2D DepthTex; //Sample_Point_Clamp layout(location = 0) out vec4 fragColor; @@ -41,12 +45,33 @@ CCProgram tonemap-fs %{ } vec4 CCFragOutput_PostProcess(vec4 color) { - if (!DebugViewNeedDisplayOriginalData()) { - #if CC_USE_FLOAT_OUTPUT - color.rgb = HDR2LDR_PostProcess(color.rgb); - color.rgb = LinearToSRGB(color.rgb); + + // fog related + vec4 worldPos = vec4(0.0); + #if CC_USE_FOG != CC_FOG_NONE + float depth = texture(DepthTex, v_uv).r; + vec3 posHS = vec3(v_uv, depth) * 2.0 - vec3(1.0); + CC_HANDLE_GET_CLIP_FLIP(posHS.xy); + worldPos = GetWorldPosFromNDCPosRH(posHS, cc_matProj, cc_matViewProjInv); #endif + + // todo: apply fogColorBrightness to fogColor for supporting scatter lighting with HDR + + // tone mapping + if (!DebugViewNeedDisplayOriginalData()) { + #if CC_USE_FLOAT_OUTPUT + color.rgb = HDR2LDR_PostProcess(color.rgb); + color.rgb = LinearToSRGB(color.rgb); + #endif } + + // LDR fog + #if CC_USE_FOG != CC_FOG_NONE + float fogFactor = 1.0; + CC_TRANSFER_FOG_BASE(worldPos, fogFactor); + CC_APPLY_FOG_BASE(color, fogFactor); + #endif + return color; } diff --git a/editor/assets/effects/pipeline/tone-mapping.effect.meta b/editor/assets/effects/pipeline/float-output-process.effect.meta similarity index 100% rename from editor/assets/effects/pipeline/tone-mapping.effect.meta rename to editor/assets/effects/pipeline/float-output-process.effect.meta diff --git a/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk b/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk index 7dbfc531644..ebfa1fcd336 100644 --- a/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk +++ b/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk @@ -296,7 +296,7 @@ float CalculateAO(vec2 uv) ao = 1.0 - ao * INV_NUM_DIRECTIONS * g_Strength; - #if CC_USE_FOG != CC_FOG_NONE + #if CC_USE_FOG != CC_FOG_NONE && !CC_USE_FLOAT_OUTPUT float fogFactor = 1.0; // no fog float depth = texture(DepthTex, uv).r; vec3 posHS = vec3(uv, depth) * 2.0 - vec3(1.0); diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index 13518a78464..cc57e887ed1 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -498,6 +498,10 @@ gfx::Shader *Pass::getShaderVariant(const ccstd::vector &patches) { _defines[patch.name] = patch.value; } + if (isBlend()) { + _defines["CC_IS_TRANSPARENCY_PASS"] = MacroValue(true); + } + gfx::Shader *shader = nullptr; auto *programLib = render::getProgramLibrary(); if (programLib) { @@ -518,6 +522,17 @@ gfx::Shader *Pass::getShaderVariant(const ccstd::vector &patches) { return shader; } +bool Pass::isBlend() { + bool isBlend = false; + for (const auto target : _blendState.targets) { + if (target.blend) { + isBlend = true; + } + } + + return isBlend; +} + IPassInfoFull Pass::getPassInfoFull() const { IPassInfoFull ret; ret.passIndex = _passIndex; diff --git a/native/cocos/scene/Pass.h b/native/cocos/scene/Pass.h index a3324ab4e06..e714e900ad3 100644 --- a/native/cocos/scene/Pass.h +++ b/native/cocos/scene/Pass.h @@ -315,6 +315,7 @@ class Pass : public RefCounted { gfx::BufferViewInfo &bufferViewInfo, ccstd::vector &startOffsets, size_t &count); + bool isBlend(); protected: void setState(const gfx::BlendState &bs, const gfx::DepthStencilState &dss, const gfx::RasterizerState &rs, gfx::DescriptorSet *ds); From b30c076168811e2c28f9cab8cea19b1c1c4a4f55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Wed, 16 Aug 2023 15:52:27 +0800 Subject: [PATCH 158/232] optimize the frequency of calls to onUpdateProbes. (#15858) --- cocos/3d/framework/mesh-renderer.ts | 5 +- .../reflection-probe-component.ts | 34 +++++-- .../reflection-probe-manager.ts | 93 +++++++++++++++---- cocos/render-scene/scene/reflection-probe.ts | 3 +- 4 files changed, 106 insertions(+), 29 deletions(-) diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index ab371efe3d5..9869186e7d1 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -1073,6 +1073,7 @@ export class MeshRenderer extends ModelRenderer { this._onUpdateLocalReflectionProbeData(); } + // eslint-disable-next-line @typescript-eslint/no-empty-function protected _onMeshChanged (old: Mesh | null): void { } @@ -1145,12 +1146,12 @@ export class MeshRenderer extends ModelRenderer { if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) { - cclegacy.internal.reflectionProbeManager.updateUseCubeModels(this._model); + cclegacy.internal.reflectionProbeManager.selectReflectionProbe(this._model); if (!cclegacy.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, false)) { warnID(16302); } } else if (this.bakeSettings.reflectionProbe === ReflectionProbeType.PLANAR_REFLECTION) { - cclegacy.internal.reflectionProbeManager.updateUsePlanarModels(this._model); + cclegacy.internal.reflectionProbeManager.selectPlanarReflectionProbe(this._model); if (!cclegacy.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, true)) { warnID(16302); } diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index e5c36ee2fb6..3708c0493a3 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -101,7 +101,9 @@ export class ReflectionProbe extends Component { protected _previewSphere: Node | null = null; protected _previewPlane: Node | null = null; - protected _sourceCameraPos = new Vec3(0, 0, 0); + private _sourceCameraPos = new Vec3(0, 0, 0); + + private _position = new Vec3(0, 0, 0); /** * @en @@ -114,8 +116,10 @@ export class ReflectionProbe extends Component { absolute(this._size); this.probe.size = this._size; if (this.probe) { - ReflectionProbeManager.probeManager.onUpdateProbes(true); + this.probe.updateBoundingBox(); + ReflectionProbeManager.probeManager.onUpdateProbes(); ReflectionProbeManager.probeManager.updateProbeData(); + ReflectionProbeManager.probeManager.updateProbeOfModels(); } } @type(Vec3) @@ -263,7 +267,7 @@ export class ReflectionProbe extends Component { set cubemap (val: TextureCube | null) { this._cubemap = val; this.probe.cubemap = val; - ReflectionProbeManager.probeManager.onUpdateProbes(true); + ReflectionProbeManager.probeManager.onUpdateProbes(); } get cubemap (): TextureCube | null { @@ -312,7 +316,9 @@ export class ReflectionProbe extends Component { public onLoad (): void { this._createProbe(); - ReflectionProbeManager.probeManager.registerEvent(); + if (EDITOR) { + ReflectionProbeManager.probeManager.registerEvent(); + } } onEnable (): void { @@ -323,7 +329,7 @@ export class ReflectionProbe extends Component { this._probe.updateProbeId(this._probeId); } ReflectionProbeManager.probeManager.register(this._probe); - ReflectionProbeManager.probeManager.onUpdateProbes(true); + ReflectionProbeManager.probeManager.onUpdateProbes(); this._probe.enable(); } } @@ -340,6 +346,7 @@ export class ReflectionProbe extends Component { ReflectionProbeManager.probeManager.filterModelsForPlanarReflection(); } ReflectionProbeManager.probeManager.updateProbeData(); + this._position = this.node.getWorldPosition().clone(); } public onDestroy (): void { @@ -372,13 +379,22 @@ export class ReflectionProbe extends Component { } } - if (this.node.hasChangedFlags) { - this.probe.updateBoundingBox(); - } if (this.node.hasChangedFlags & TransformBit.POSITION) { - ReflectionProbeManager.probeManager.onUpdateProbes(true); + this.probe.updateBoundingBox(); + ReflectionProbeManager.probeManager.onUpdateProbes(); ReflectionProbeManager.probeManager.updateProbeData(); } + + //update probe info for realtime + if (!EDITOR) { + const worldPos = this.node.getWorldPosition(); + if (!this._position.equals(worldPos)) { + this._position = worldPos; + this.probe.updateBoundingBox(); + ReflectionProbeManager.probeManager.updateProbeData(); + ReflectionProbeManager.probeManager.updateProbeOfModels(); + } + } } /** diff --git a/cocos/3d/reflection-probe/reflection-probe-manager.ts b/cocos/3d/reflection-probe/reflection-probe-manager.ts index 88dc20c07d3..c4ac433ee71 100644 --- a/cocos/3d/reflection-probe/reflection-probe-manager.ts +++ b/cocos/3d/reflection-probe/reflection-probe-manager.ts @@ -65,22 +65,26 @@ export class ReflectionProbeManager { set updateForRuntime (val: boolean) { this._updateForRuntime = val; } + get updateForRuntime (): boolean { return this._updateForRuntime; } + /** + * @engineInternal + */ public registerEvent (): void { if (!this._registeredEvent) { cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_UPDATE, this.onUpdateProbes, this); this._registeredEvent = true; } } + /** - * @en refresh all reflection probe - * @zh 刷新所有反射探针 + * @en Refresh all reflection probe. + * @zh 刷新所有反射探针。 */ - public onUpdateProbes (forceUpdate = false): void { - if (!EDITOR && !this._updateForRuntime) return; + public onUpdateProbes (): void { if (this._probes.length === 0) return; const scene = cclegacy.director.getScene(); if (!scene || !scene.renderScene) { @@ -90,16 +94,20 @@ export class ReflectionProbeManager { for (let i = 0; i < models.length; i++) { const model = models[i]; if (!model.node) continue; - if ((model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) && (model.node.hasChangedFlags || forceUpdate)) { + if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) { if (model.reflectionProbeType === ReflectionProbeType.BAKED_CUBEMAP || this._isUsedBlending(model)) { - this.updateUseCubeModels(model); + this.selectReflectionProbe(model); } else if (model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION) { - this.updateUsePlanarModels(model); + this.selectPlanarReflectionProbe(model); } } } } + /** + * @en filter models that use planar reflection. + * @zh 筛选使用平面反射的模型 + */ public filterModelsForPlanarReflection (): void { if (this._probes.length === 0) return; const scene = cclegacy.director.getScene(); @@ -111,11 +119,14 @@ export class ReflectionProbeManager { const model = models[i]; if (!model.node) continue; if ((model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) && model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION) { - this.updateUsePlanarModels(model); + this.selectPlanarReflectionProbe(model); } } } + /** + * @engineInternal + */ public clearPlanarReflectionMap (probe: ReflectionProbe): void { for (const entry of this._usePlanarModels.entries()) { if (entry[1] === probe) { @@ -124,6 +135,9 @@ export class ReflectionProbeManager { } } + /** + * @engineInternal + */ public register (probe: ReflectionProbe): void { const index = this._probes.indexOf(probe); if (index === -1) { @@ -132,6 +146,9 @@ export class ReflectionProbeManager { } } + /** + * @engineInternal + */ public unregister (probe: ReflectionProbe): void { for (let i = 0; i < this._probes.length; i++) { if (this._probes[i] === probe) { @@ -145,6 +162,9 @@ export class ReflectionProbeManager { this.updateProbeData(); } + /** + * @engineInternal + */ public exists (probeId: number): boolean { if (this._probes.length === 0) return false; for (let i = 0; i < this._probes.length; i++) { @@ -155,6 +175,9 @@ export class ReflectionProbeManager { return false; } + /** + * @engineInternal + */ public getNewReflectionProbeId (): number { let probeId = 0; // eslint-disable-next-line no-constant-condition @@ -167,10 +190,18 @@ export class ReflectionProbeManager { } } + /** + * @en Get all reflection probes in the scene. + * @zh 获取场景中所有的反射探针 + */ public getProbes (): ReflectionProbe[] { return this._probes; } + /** + * @en Get reflection probe by id. + * @zh 根据id获取反射探针 + */ public getProbeById (probeId: number): ReflectionProbe | null { for (let i = 0; i < this._probes.length; i++) { if (this._probes[i].getProbeId() === probeId) { @@ -180,10 +211,16 @@ export class ReflectionProbeManager { return null; } + /** + * @engineInternal + */ public clearAll (): void { this._probes = []; } + /** + * @engineInternal + */ public getProbeByCamera (camera: Camera): ReflectionProbe | null { for (let i = 0; i < this._probes.length; i++) { if (this._probes[i].camera === camera) { @@ -241,7 +278,7 @@ export class ReflectionProbeManager { * @param probe update the model for reflection probe * @engineInternal */ - public updateUsePlanarModels (model: Model): void { + public selectPlanarReflectionProbe (model: Model): void { if (!model.node || !model.worldBounds || model.reflectionProbeType !== ReflectionProbeType.PLANAR_REFLECTION) return; for (let i = 0; i < this._probes.length; i++) { const probe = this._probes[i]; @@ -272,12 +309,11 @@ export class ReflectionProbeManager { } /** - * @en Update objects using reflection probe for bake cubemap. - * @zh 更新使用反射探针烘焙cubemap的物体。 - * @param model update the model for reflection probe - * @engineInternal + * @en Selecting the appropriate reflection probe for the model, it will use the closest one based on distance. + * @zh 为模型选择适用的反射探针,会使用距离最近的。 + * @param model select for this model */ - public updateUseCubeModels (model: Model): void { + public selectReflectionProbe (model: Model): void { if (model.node && model.worldBounds && ((model.node.layer & REFLECTION_PROBE_DEFAULT_MASK))) { model.updateWorldBound(); const nearest = this._getNearestProbe(model); @@ -441,7 +477,7 @@ export class ReflectionProbeManager { return null; } - /** + /** * @en Set reflection probe used by the model. * @zh 手动设置模型使用的反射探针。 * @param model set the probe for this model @@ -457,6 +493,29 @@ export class ReflectionProbeManager { } } + /** + * @engineInternal + */ + public updateProbeOfModels (): void { + if (this._probes.length === 0) return; + const scene = cclegacy.director.getScene(); + if (!scene || !scene.renderScene) { + return; + } + const models = scene.renderScene.models as Model[]; + for (let i = 0; i < models.length; i++) { + const model = models[i]; + if (!model.node) continue; + if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) { + if (model.reflectionProbeType === ReflectionProbeType.BAKED_CUBEMAP + || model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION + || this._isUsedBlending(model)) { + model.updateReflectionProbeId(); + } + } + } + } + /** * @en * select the probe with the nearest distance. @@ -523,14 +582,14 @@ export class ReflectionProbeManager { const p = this._useCubeModels.get(key); if (p !== undefined && p === probe) { this._useCubeModels.delete(key); - this.updateUseCubeModels(key); + this.selectReflectionProbe(key); } } for (const key of this._usePlanarModels.keys()) { const p = this._usePlanarModels.get(key); if (p !== undefined && p === probe) { this._usePlanarModels.delete(key); - this.updateUsePlanarModels(key); + this.selectPlanarReflectionProbe(key); } } } diff --git a/cocos/render-scene/scene/reflection-probe.ts b/cocos/render-scene/scene/reflection-probe.ts index 9c794c75172..8b10802b7ca 100644 --- a/cocos/render-scene/scene/reflection-probe.ts +++ b/cocos/render-scene/scene/reflection-probe.ts @@ -364,8 +364,10 @@ export class ReflectionProbe { this.realtimePlanarTexture = null; } } + // eslint-disable-next-line @typescript-eslint/no-empty-function public enable (): void { } + // eslint-disable-next-line @typescript-eslint/no-empty-function public disable (): void { } @@ -376,7 +378,6 @@ export class ReflectionProbe { public updateBoundingBox (): void { if (this.node) { - this.node.updateWorldTransform(); const pos = this.node.getWorldPosition(); geometry.AABB.set(this._boundingBox!, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); } From 23f222730a1bc47fe409f89ab3879f1a03a82e84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 16 Aug 2023 16:58:42 +0800 Subject: [PATCH 159/232] Android Build Panel: Add `resizeableActivity` Option (#15713) * resizeable activity --- scripts/native-pack-tool/package-lock.json | 34 ++- scripts/native-pack-tool/package.json | 6 +- .../source/platforms/android.ts | 196 ++++++++++++------ scripts/native-pack-tool/source/utils.ts | 22 +- 4 files changed, 182 insertions(+), 76 deletions(-) diff --git a/scripts/native-pack-tool/package-lock.json b/scripts/native-pack-tool/package-lock.json index 43a55b0c26c..029e8e021c6 100644 --- a/scripts/native-pack-tool/package-lock.json +++ b/scripts/native-pack-tool/package-lock.json @@ -18,6 +18,19 @@ "resolved": "https://registry.npmmirror.com/@nodelib/fs.stat/-/fs.stat-1.1.3.tgz", "integrity": "sha512-shAmDyaQC4H92APFoIaVDHCx5bStIocgvbwQyxPRrbUY20V1EYTbSDchWbuwlMG3V17cprZhA6+78JfB+3DTPw==" }, + "@types/node": { + "version": "20.4.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.1.tgz", + "integrity": "sha512-JIzsAvJeA/5iY6Y/OxZbv1lUcc8dNSE77lb2gnBH+/PJ3lFR1Ccvgwl5JWnHAkNHcRsT0TbpVOsiMKZ1F/yyJg==" + }, + "@types/xml2js": { + "version": "0.4.11", + "resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.11.tgz", + "integrity": "sha512-JdigeAKmCyoJUiQljjr7tQG3if9NkqGUgwEUqBvV0N7LM4HyQk7UXCnusRa1lnvXAEYJ8mw8GtZWioagNztOwA==", + "requires": { + "@types/node": "*" + } + }, "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -746,7 +759,7 @@ }, "json5": { "version": "2.2.3", - "resolved": "https://registry.npmmirror.com/json5/-/json5-2.2.3.tgz", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" }, "jsonfile": { @@ -983,6 +996,11 @@ "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + }, "set-value": { "version": "2.0.1", "resolved": "https://registry.npmmirror.com/set-value/-/set-value-2.0.1.tgz", @@ -1288,6 +1306,20 @@ "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, + "xml2js": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.0.tgz", + "integrity": "sha512-eLTh0kA8uHceqesPqSE+VvO1CDDJWMwlQfB6LuN6T8w6MaDJ8Txm8P7s5cHD0miF0V+GGTZrDQfxPZQVsur33w==", + "requires": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + } + }, + "xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==" + }, "xxtea-node": { "version": "1.1.4", "resolved": "https://registry.npmmirror.com/xxtea-node/-/xxtea-node-1.1.4.tgz", diff --git a/scripts/native-pack-tool/package.json b/scripts/native-pack-tool/package.json index a525a59ddb8..ec27875c9f0 100644 --- a/scripts/native-pack-tool/package.json +++ b/scripts/native-pack-tool/package.json @@ -12,12 +12,14 @@ "clean": "tsc --clean" }, "dependencies": { + "@types/xml2js": "^0.4.11", "fs-extra": "^10.1.0", "globby": "^8.0.2", "iconv-lite": "^0.4.24", + "json5": "^2.2.1", + "xml2js": "^0.6.0", "xxtea-node": "^1.1.4", "yargs": "^17.5.1", - "zlib": "^1.0.5", - "json5": "^2.2.1" + "zlib": "^1.0.5" } } diff --git a/scripts/native-pack-tool/source/platforms/android.ts b/scripts/native-pack-tool/source/platforms/android.ts index 143559a2e12..212974a8ae1 100644 --- a/scripts/native-pack-tool/source/platforms/android.ts +++ b/scripts/native-pack-tool/source/platforms/android.ts @@ -4,6 +4,7 @@ import { CocosParams, NativePackTool } from "../base/default"; import { cchelper, Paths } from "../utils"; import * as URL from 'url'; import { spawn, spawnSync } from 'child_process'; +import * as xml2js from 'xml2js'; export interface IOrientation { landscapeLeft: boolean; @@ -27,11 +28,15 @@ export interface IAndroidParams { orientation: IOrientation; appBundle: boolean; + resizeableActivity: boolean; } +const DefaultAPILevel = 27; export class AndroidPackTool extends NativePackTool { params!: CocosParams; + private firstTimeBuild: boolean = false; + protected async copyPlatformTemplate() { // 原生工程不重复拷贝 TODO 复用前需要做版本检测 if (!fs.existsSync(this.paths.nativePrjDir)) { @@ -43,8 +48,10 @@ export class AndroidPackTool extends NativePackTool { // 拷贝 lite 仓库的 templates/android/template 文件到构建输出目录 await fs.copy(ps.join(this.paths.nativeTemplateDirInCocos, this.params.platform, 'template'), this.paths.platformTemplateDirInPrj, { overwrite: false }); this.writeEngineVersion(); + this.firstTimeBuild = true; } else { this.validateNativeDir(); + this.firstTimeBuild = false; } } @@ -60,10 +67,9 @@ export class AndroidPackTool extends NativePackTool { await this.generateCMakeConfig(); await this.excuteCocosTemplateTask(); - await this.setOrientation(); - await this.encrypteScripts(); await this.updateAndroidGradleValues(); - await this.configAndroidInstant(); + await this.updateManifest(); + await this.encrypteScripts(); await this.generateAppNameValues(); return true; } @@ -122,40 +128,134 @@ export class AndroidPackTool extends NativePackTool { return await this.copyToDist(); } - protected async setOrientation() { - const cfg = this.params.platformParams.orientation; + private mapOrientationValue() { + const orientation = this.params.platformParams.orientation; + let orientationValue = 'unspecified'; + + if (orientation.landscapeRight && orientation.landscapeLeft && (orientation.portrait || orientation.upsideDown)) { + orientationValue = 'fullSensor'; + } else if ((orientation.landscapeRight || orientation.landscapeLeft) && (orientation.portrait || orientation.upsideDown)) { + orientationValue = 'unspecified'; + } else if (orientation.landscapeRight && !orientation.landscapeLeft) { + orientationValue = 'landscape'; + } else if (!orientation.landscapeRight && orientation.landscapeLeft) { + orientationValue = 'reverseLandscape'; + } else if (orientation.landscapeRight && orientation.landscapeLeft) { + orientationValue = 'sensorLandscape'; + } else if (orientation.portrait && !orientation.upsideDown) { + orientationValue = 'portrait'; + } else if (!orientation.portrait && orientation.upsideDown) { + orientationValue = 'reversePortrait'; + } else if (orientation.portrait && orientation.upsideDown) { + orientationValue = 'sensorPortrait'; + } + return orientationValue; + } + + protected async updateManifest() { + + if (!this.firstTimeBuild) { + console.log(`AndroidManifest.xml has already been updated!`); + return; + } + + const resizeableActivity: boolean = this.params.platformParams.resizeableActivity; const manifestPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'app/AndroidManifest.xml'); const instantManifestPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'instantapp/AndroidManifest.xml'); - if (fs.existsSync(manifestPath) && fs.existsSync(instantManifestPath)) { - const pattern = /android:screenOrientation="[^"]*"/; - let replaceString = 'android:screenOrientation="unspecified"'; - - if (cfg.landscapeRight && cfg.landscapeLeft && (cfg.portrait || cfg.upsideDown)) { - replaceString = 'android:screenOrientation="fullSensor"'; - } else if ((cfg.landscapeRight || cfg.landscapeLeft) && (cfg.portrait || cfg.upsideDown)) { - replaceString = 'android:screenOrientation="unspecified"'; - } else if (cfg.landscapeRight && !cfg.landscapeLeft) { - replaceString = 'android:screenOrientation="landscape"'; - } else if (!cfg.landscapeRight && cfg.landscapeLeft) { - replaceString = 'android:screenOrientation="reverseLandscape"'; - } else if (cfg.landscapeRight && cfg.landscapeLeft) { - replaceString = 'android:screenOrientation="sensorLandscape"'; - } else if (cfg.portrait && !cfg.upsideDown) { - replaceString = 'android:screenOrientation="portrait"'; - } else if (!cfg.portrait && cfg.upsideDown) { - const oriValue = 'reversePortrait'; - replaceString = `android:screenOrientation="${oriValue}"`; - } else if (cfg.portrait && cfg.upsideDown) { - const oriValue = 'sensorPortrait'; - replaceString = `android:screenOrientation="${oriValue}"`; + + const fnParseXml = async (xmlFile: string) => { + const xmlData = await fs.readFile(xmlFile, 'utf8'); + const data = await xml2js.parseStringPromise(xmlData); + return { + data, + save: async () => { + const builder = new xml2js.Builder(); + const dstXML = builder.buildObject(data); + await fs.writeFile(xmlFile, dstXML, 'utf8'); + } + } + }; + const fnUpdateOrientation = (data: any) => { + const attrRef = data.manifest.application[0].activity[0].$; + attrRef['android:screenOrientation'] = this.mapOrientationValue(); + }; + const fnUpdateResizeableActivity = (data: any) => { + const activityRef = data.manifest.application[0].$; + activityRef['android:resizeableActivity'] = resizeableActivity ? 'true' : 'false'; + }; + const fnUpdateMaxAspectRation = (data: any) => { + if (resizeableActivity) return; // disabled + const maxAspectRatio: string = this.params.platformParams.maxAspectRatio; + if (!maxAspectRatio) return; // value not set + const matchFrac = maxAspectRatio.match(/^(\d+):(\d+)$/); + let aspectRatioFloatValue; + try { + if (matchFrac) { + aspectRatioFloatValue = Number.parseInt(matchFrac[1], 10) / Number.parseInt(matchFrac[2], 10); + } else { + aspectRatioFloatValue = Number.parseFloat(maxAspectRatio); + } + } catch (e) { + console.error(e); + console.error(`Error when parsing '${maxAspectRatio}', fallback maxAspectRatio to default value`); + aspectRatioFloatValue = 2.4; + } + + let apiLevel = this.params.platformParams.apiLevel; + if (apiLevel === undefined) apiLevel = DefaultAPILevel; + + + if (apiLevel >= 26) { // Android 8.0 + const activities = data.manifest.application[0].activity; + for (const activity of activities) { + activity.$['android:maxAspectRatio'] = `${aspectRatioFloatValue}`; + } + } else { + const application = data.manifest.application[0]; + //append meta-data + application['meta-data'].push({ + $:{'android:name': 'android.max_aspect', 'android:value': `${aspectRatioFloatValue}`} + }); + } + + }; + const fnUpdateCategory = (data: any) => { + if (!this.params.platformParams.androidInstant) { + console.log('android instant not configured'); + return; + } + const url = this.params.platformParams.remoteUrl; + if (!url) { + return; } + const urlInfo = URL.parse(url); + if (!urlInfo.host) { + throw new Error(`parse url ${url} fail`); + } + const intentFilter: any = data.manifest.application[0].activity[0]['intent-filter'][0]; + if (intentFilter) { + intentFilter.data ||= []; + intentFilter.data = intentFilter.data.concat([ + { $: { 'android:host': urlInfo.host, 'android:pathPattern': urlInfo.path, 'android:scheme': 'https' } }, + { $: { 'android:scheme': 'http' } } + ]); + } + } - let content = await fs.readFile(manifestPath, 'utf8'); - content = content.replace(pattern, replaceString); - let instantContent = await fs.readFile(instantManifestPath, 'utf8'); - instantContent = instantContent.replace(pattern, replaceString); - await fs.writeFile(manifestPath, content); - await fs.writeFile(instantManifestPath, instantContent); + if (fs.existsSync(manifestPath)) { + const app = await fnParseXml(manifestPath); + await fnUpdateOrientation(app.data); + await fnUpdateResizeableActivity(app.data); + await fnUpdateMaxAspectRation(app.data); + await app.save(); + } + if (fs.existsSync(instantManifestPath)) { + const instant = await fnParseXml(instantManifestPath); + await fnUpdateOrientation(instant.data); + await fnUpdateResizeableActivity(instant.data); + await fnUpdateMaxAspectRation(instant.data); + await fnUpdateCategory(instant.data); + await instant.save(); } } @@ -177,7 +277,7 @@ export class AndroidPackTool extends NativePackTool { } let apiLevel = options.apiLevel; if (!apiLevel) { - apiLevel = 27; + apiLevel = DefaultAPILevel; } console.log(`AndroidAPI level ${apiLevel}`); let content = fs.readFileSync(gradlePropertyPath, 'utf-8'); @@ -236,34 +336,6 @@ export class AndroidPackTool extends NativePackTool { } } - protected async configAndroidInstant() { - if (!this.params.platformParams.androidInstant) { - console.log('android instant not configured'); - return; - } - const url = this.params.platformParams.remoteUrl; - if (!url) { - return; - } - const manifestPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'instantapp/AndroidManifest.xml'); - if (!fs.existsSync(manifestPath)) { - throw new Error(`${manifestPath} not found`); - } - const urlInfo = URL.parse(url); - if (!urlInfo.host) { - throw new Error(`parse url ${url} fail`); - } - let manifest = fs.readFileSync(manifestPath, 'utf8'); - manifest = manifest.replace(//, (str) => { - let newStr = ''; - newStr += `\n ` - + `\n `; - return newStr; - }); - - fs.writeFileSync(manifestPath, manifest, 'utf8'); - } - private async generateAppNameValues() { const valuesPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'res/values/strings.xml'); const matchCnt = fs.readFileSync(valuesPath, 'utf8').toString().split('\n').map(x => x.trim()).filter(x => /name=\"app_name\"/.test(x)).length; diff --git a/scripts/native-pack-tool/source/utils.ts b/scripts/native-pack-tool/source/utils.ts index 22e57038415..67eeb88a4dc 100644 --- a/scripts/native-pack-tool/source/utils.ts +++ b/scripts/native-pack-tool/source/utils.ts @@ -416,7 +416,7 @@ export class cchelper { } export const toolHelper = { - getXcodeMajorVerion():number { + getXcodeMajorVerion(): number { try { const output = execSync('xcrun xcodebuild -version').toString('utf8'); return Number.parseInt(output.match(/Xcode\s(\d+)\.\d+/)![1]); @@ -427,15 +427,15 @@ export const toolHelper = { } }, - async runCommand(cmd:string, args:string[], cb?:(code:number, stdout:string, stderr:string)=>void): Promise { + async runCommand(cmd: string, args: string[], cb?: (code: number, stdout: string, stderr: string) => void): Promise { return new Promise((resolve, reject) => { const cp = spawn(cmd, args); - const stdErr:Buffer[] = []; - const stdOut:Buffer[] = []; - cp.stderr.on('data', (d)=>stdErr.push(d)); - cp.stdout.on('data', (d)=>stdOut.push(d)); - cp.on('close', (code, signal)=>{ - if(cb) { + const stdErr: Buffer[] = []; + const stdOut: Buffer[] = []; + cp.stderr.on('data', (d) => stdErr.push(d)); + cp.stdout.on('data', (d) => stdOut.push(d)); + cp.on('close', (code, signal) => { + if (cb) { cb(code as any, Buffer.concat(stdOut).toString('utf8'), Buffer.concat(stdErr).toString('utf8')); } resolve(code === 0); @@ -464,7 +464,7 @@ export const toolHelper = { }); cp.stdout.on('data', (data: any) => { const msg = iconv.decode(data, 'gbk').toString(); - if(/warning/i.test(msg)) { + if (/warning/i.test(msg)) { console.log(`[cmake-warn] ${msg}`); } else { console.log(`[cmake] ${msg}`); @@ -472,9 +472,9 @@ export const toolHelper = { }); cp.stderr.on('data', (data: any) => { const msg = iconv.decode(data, 'gbk').toString(); - if(/CMake Warning/.test(msg) || /warning/i.test(msg)) { + if (/CMake Warning/.test(msg) || /warning/i.test(msg)) { console.log(`[cmake-warn] ${msg}`); - }else{ + } else { console.error(`[cmake-err] ${msg}`); } }); From 544854c9f6fea7b7b69002f65a0fb332cebd2a3d Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Wed, 16 Aug 2023 17:30:28 +0800 Subject: [PATCH 160/232] add model invalidateLocalData interface (#15623) --- cocos/render-scene/scene/model.ts | 9 +++++++++ native/cocos/scene/Model.h | 1 + 2 files changed, 10 insertions(+) diff --git a/cocos/render-scene/scene/model.ts b/cocos/render-scene/scene/model.ts index 3cc86fb88f6..360d856a821 100644 --- a/cocos/render-scene/scene/model.ts +++ b/cocos/render-scene/scene/model.ts @@ -735,6 +735,15 @@ export class Model { } } + /** + * @engineInternal + * @en Invalidate local data + * @zh 使本地数据失效 + */ + public invalidateLocalData (): void { + this._localDataUpdated = true; + } + public showTetrahedron (): boolean { return this.isLightProbeAvailable(); } diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 7085d355383..5a77d27a549 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -239,6 +239,7 @@ class Model : public RefCounted { _receiveDirLight = value; onMacroPatchesStateChanged(); } + inline void invalidateLocalData() { _localDataUpdated = true; } // For JS inline void setCalledFromJS(bool v) { _isCalledFromJS = v; } From 6afc186c67e4702185b291cd911a65e4a5dddca6 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Wed, 16 Aug 2023 18:06:47 +0800 Subject: [PATCH 161/232] remove button wrong sprite set (#15949) * remove button wrong sprite set * fix CI --- cocos/ui/button.ts | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/cocos/ui/button.ts b/cocos/ui/button.ts index 2411f97a860..067da5d4525 100644 --- a/cocos/ui/button.ts +++ b/cocos/ui/button.ts @@ -23,7 +23,8 @@ THE SOFTWARE. */ -import { ccclass, help, executionOrder, menu, requireComponent, tooltip, displayOrder, type, rangeMin, rangeMax, serializable, executeInEditMode } from 'cc.decorator'; +import { ccclass, help, executionOrder, menu, requireComponent, tooltip, displayOrder, type, rangeMin, + rangeMax, serializable, executeInEditMode } from 'cc.decorator'; import { EDITOR, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { SpriteFrame } from '../2d/assets'; import { Component, EventHandler as ComponentEventHandler } from '../scene-graph'; @@ -122,7 +123,8 @@ export enum EventType { * - cc.Node.EventType.MOUSE_LEAVE * - cc.Node.EventType.MOUSE_UP * - * The developer can get the current clicked node with `event.target` from event object which is passed as parameter in the callback function of click event. + * The developer can get the current clicked node with `event.target` from event object which is passed as parameter + * in the callback function of click event. * * @zh * 按钮组件。可以被按下,或者点击。
@@ -398,7 +400,8 @@ export class Button extends Component { * @en * When user press the button, the button will zoom to a scale. * The final scale of the button equals (button original scale * zoomScale) - * NOTE: Setting zoomScale less than 1 is not adviced, which could fire the touchCancel event if the touch point is out of touch area after scaling. + * NOTE: Setting zoomScale less than 1 is not adviced, which could fire the touchCancel event + * if the touch point is out of touch area after scaling. * if you need to do so, you should set target as another background node instead of the button node. * * @zh @@ -583,11 +586,6 @@ export class Button extends Component { this.target = this.node; } - const sprite = this.node.getComponent(Sprite); - if (sprite) { - this._normalSprite = sprite.spriteFrame; - } - this._applyTarget(); this._resetState(); } @@ -859,7 +857,7 @@ export class Button extends Component { this.target.setScale(this._originalScale); } } else { - let state; + let state: string; if (hit) { state = State.PRESSED; } else { @@ -940,7 +938,7 @@ export class Button extends Component { return; } - if (EDITOR || state === State.DISABLED) { + if (EDITOR || state === State.DISABLED.toString()) { renderComp.color = color; } else { this._fromColor = renderComp.color.clone(); @@ -962,7 +960,7 @@ export class Button extends Component { return; } - if (state === State.PRESSED) { + if (state === State.PRESSED.toString()) { this._zoomUp(); } else { this._zoomBack(); From 93e397e9f06bda6bfbf3bac0965d1e79ba7b5b84 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 17 Aug 2023 10:04:39 +0800 Subject: [PATCH 162/232] Fix sprite size mode change by preload (#15908) * Fix sprite size mode change by preload * fix on runtime --- cocos/2d/components/sprite.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 4af575e7e5d..e6d958d3814 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -27,7 +27,7 @@ import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, range import { BUILD, EDITOR } from 'internal:constants'; import { SpriteAtlas } from '../assets/sprite-atlas'; import { SpriteFrame } from '../assets/sprite-frame'; -import { Vec2, cclegacy, ccenum, clamp } from '../../core'; +import { Vec2, cclegacy, ccenum, clamp, warn } from '../../core'; import { IBatcher } from '../renderer/i-batcher'; import { UIRenderer, InstanceMaterialType } from '../framework/ui-renderer'; import { PixelFormat } from '../../asset/assets/asset-enum'; @@ -480,9 +480,9 @@ export class Sprite extends UIRenderer { public __preload (): void { this.changeMaterialForDefine(); super.__preload(); + this._applySpriteSize(); if (EDITOR) { - this._resized(); this.node.on(NodeEventType.SIZE_CHANGED, this._resized, this); } } @@ -526,7 +526,7 @@ export class Sprite extends UIRenderer { */ public changeSpriteFrameFromAtlas (name: string): void { if (!this._atlas) { - console.warn('SpriteAtlas is null.'); + warn('SpriteAtlas is null.'); return; } const sprite = this._atlas.getSpriteFrame(name); From 39acb6560f0d47fc7fe4cf3579ad63cab2e354e0 Mon Sep 17 00:00:00 2001 From: zxx43 Date: Thu, 17 Aug 2023 10:17:32 +0800 Subject: [PATCH 163/232] use buffer size instead of capacity to initialize buffer (#15775) * use buffer size instead of capacity to initialize buffer * fix eslint * set min buffer size 16 * remove loop --- cocos/particle/models/particle-batch-model.ts | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index 33a611473d1..a302acdeddf 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -49,6 +49,7 @@ const _uvs_ins = [ export default class ParticleBatchModel extends scene.Model { private _capacity: number; + private _bufferSize: number; private _vertAttrs: Attribute[] | null; private _vertAttribSize: number; private _vBuffer: ArrayBuffer | null; @@ -80,6 +81,7 @@ export default class ParticleBatchModel extends scene.Model { this.type = scene.ModelType.PARTICLE_BATCH; this._capacity = 0; + this._bufferSize = 16; this._vertAttrs = null; this._vertAttribSize = 0; @@ -105,6 +107,7 @@ export default class ParticleBatchModel extends scene.Model { public setCapacity (capacity: number): void { const capChanged = this._capacity !== capacity; this._capacity = capacity; + this._bufferSize = Math.max(this._capacity, 16); if (this._subMeshData && capChanged) { this.rebuild(); } @@ -165,19 +168,25 @@ export default class ParticleBatchModel extends scene.Model { const vertexBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - this._vertAttribSize * this._capacity * this._vertCount, + this._vertAttribSize * this._bufferSize * this._vertCount, this._vertAttribSize, )); - const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._capacity * this._vertCount); + const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._bufferSize * this._vertCount); if (this._mesh && this._capacity > 0) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison let vOffset = (this._vertAttrs![this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD)] as any).offset; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSize, vOffset); // copy mesh uv to ATTR_TEX_COORD + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3); vOffset = (this._vertAttrs![vIdx++] as any).offset; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSize, vOffset); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSize, vOffset); // copy mesh normal to ATTR_NORMAL vOffset = (this._vertAttrs![vIdx++] as any).offset; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSize, vOffset)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { @@ -191,7 +200,7 @@ export default class ParticleBatchModel extends scene.Model { } vertexBuffer.update(vBuffer); - const indices: Uint16Array = new Uint16Array(this._capacity * this._indexCount); + const indices: Uint16Array = new Uint16Array(this._bufferSize * this._indexCount); if (this._mesh && this._capacity > 0) { this._mesh.copyIndices(0, indices); for (let i = 1; i < this._capacity; i++) { @@ -215,7 +224,7 @@ export default class ParticleBatchModel extends scene.Model { const indexBuffer: Buffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - this._capacity * this._indexCount * Uint16Array.BYTES_PER_ELEMENT, + this._bufferSize * this._indexCount * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT, )); @@ -236,11 +245,11 @@ export default class ParticleBatchModel extends scene.Model { const vertexBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - this._vertAttribSize * this._capacity, + this._vertAttribSize * this._bufferSize, this._vertAttribSize, )); - const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._capacity); + const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._bufferSize); vertexBuffer.update(vBuffer); this._insBuffers.push(vertexBuffer); @@ -265,15 +274,21 @@ export default class ParticleBatchModel extends scene.Model { const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSizeStatic * this._vertCount); if (this._mesh) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD); // find ATTR_TEX_COORD index let vOffset = (this._vertAttrs![vIdx] as any).offset; // find ATTR_TEX_COORD offset + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh uv to ATTR_TEX_COORD + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3); // find ATTR_TEX_COORD3 index vOffset = (this._vertAttrs![vIdx++] as any).offset; // find ATTR_TEX_COORD3 offset + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh normal to ATTR_NORMAL vOffset = (this._vertAttrs![vIdx++] as any).offset; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSizeStatic, vOffset)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { @@ -412,7 +427,7 @@ export default class ParticleBatchModel extends scene.Model { } } - public addGPUParticleVertexData (p: Particle, num: number, time:number): void { + public addGPUParticleVertexData (p: Particle, num: number, time: number): void { if (!this._useInstance) { let offset = num * this._vertAttrsFloatCount * this._vertCount; for (let i = 0; i < this._vertCount; i++) { @@ -451,7 +466,7 @@ export default class ParticleBatchModel extends scene.Model { } } - private addGPUParticleVertexDataIns (p: Particle, num: number, time:number): void { + private addGPUParticleVertexDataIns (p: Particle, num: number, time: number): void { let offset = num * this._vertAttrsFloatCount; let idx = offset; this._vdataF32![idx++] = p.position.x; From 331fab3c6b341a715f770f28d37103766b1c35ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 17 Aug 2023 10:21:44 +0800 Subject: [PATCH 164/232] SkeletalAnimation: disable animation baking in pure editor mode (#15977) --- .../skeletal-animation/skeletal-animation.ts | 76 ++++++++++++------- tests/animation/skeletal-animation.test.ts | 39 ++++++++++ 2 files changed, 86 insertions(+), 29 deletions(-) diff --git a/cocos/3d/skeletal-animation/skeletal-animation.ts b/cocos/3d/skeletal-animation/skeletal-animation.ts index a53df4e3ffc..9bba33a2c59 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation.ts @@ -25,8 +25,9 @@ import { ccclass, executeInEditMode, executionOrder, help, menu, type, serializable, editable, } from 'cc.decorator'; +import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { SkinnedMeshRenderer } from '../skinned-mesh-renderer'; -import { Mat4, cclegacy, js, assertIsTrue } from '../../core'; +import { Mat4, cclegacy, js, assertIsTrue, warn } from '../../core'; import { DataPoolManager } from './data-pool-manager'; import { Node } from '../../scene-graph/node'; import { AnimationClip } from '../../animation/animation-clip'; @@ -37,6 +38,8 @@ import { getWorldTransformUntilRoot } from '../../animation/transform-utils'; import type { AnimationState } from '../../animation/animation-state'; import { getGlobalAnimationManager } from '../../animation/global-animation-manager'; +const FORCE_BAN_BAKED_ANIMATION = EDITOR_NOT_IN_PREVIEW; + /** * @en The socket to synchronize transform from skeletal joint to target node. * @zh 骨骼动画的挂点,用于将骨骼树的挂点节点变化矩阵同步到目标节点上 @@ -113,7 +116,7 @@ export class SkeletalAnimation extends Animation { } set sockets (val) { - if (!this._useBakedAnimation) { + if (!this._useBakedEffectively) { const animMgr = getGlobalAnimationManager(); animMgr.removeSockets(this.node, this._sockets); animMgr.addSockets(this.node, val); @@ -127,33 +130,20 @@ export class SkeletalAnimation extends Animation { * Whether to bake animations. Default to true,
* which substantially increases performance while making all animations completely fixed.
* Dynamically changing this property will take effect when playing the next animation clip. + * Note, in editor(not in preview) mode, this option takes no effect: animation is always non-baked. * @zh * 是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,但所有动画效果会被彻底固定,不支持任何形式的编辑和混合。
* 运行时动态修改此选项会在播放下一条动画片段时生效。 + * 注意,在编辑器(非预览)模式下,此选项不起作用:动画总是非预烘焙的。 */ @editable get useBakedAnimation (): boolean { return this._useBakedAnimation; } - set useBakedAnimation (val) { - this._useBakedAnimation = val; - - for (const stateName in this._nameToState) { - const state = this._nameToState[stateName] as SkeletalAnimationState; - state.setUseBaked(val); - } - - this._users.forEach((user) => { - user.setUseBakedAnimation(val); - }); - - if (this._useBakedAnimation) { - getGlobalAnimationManager().removeSockets(this.node, this._sockets); - } else { - getGlobalAnimationManager().addSockets(this.node, this._sockets); - this._currentBakedState = null; - } + set useBakedAnimation (value) { + this._useBakedAnimation = value; + this._applyBakeFlagChange(); } @serializable @@ -193,12 +183,12 @@ export class SkeletalAnimation extends Animation { public start (): void { this.sockets = this._sockets; - this.useBakedAnimation = this._useBakedAnimation; + this._applyBakeFlagChange(); super.start(); } public pause (): void { - if (!this._useBakedAnimation) { + if (!this._useBakedEffectively) { super.pause(); } else { this._currentBakedState?.pause(); @@ -206,7 +196,7 @@ export class SkeletalAnimation extends Animation { } public resume (): void { - if (!this._useBakedAnimation) { + if (!this._useBakedEffectively) { super.resume(); } else { this._currentBakedState?.resume(); @@ -214,7 +204,7 @@ export class SkeletalAnimation extends Animation { } public stop (): void { - if (!this._useBakedAnimation) { + if (!this._useBakedEffectively) { super.stop(); } else if (this._currentBakedState) { this._currentBakedState.stop(); @@ -276,7 +266,7 @@ export class SkeletalAnimation extends Animation { const socket = this._sockets.find((s) => s.path === path); if (socket) { return socket.target; } const joint = this.node.getChildByPath(path); - if (!joint) { console.warn('illegal socket path'); return null; } + if (!joint) { warn('illegal socket path'); return null; } const target = new Node(); target.parent = this.node; this._sockets.push(new Socket(path, target)); @@ -288,14 +278,14 @@ export class SkeletalAnimation extends Animation { * @internal This method only friends to skinned mesh renderer. */ public notifySkinnedMeshAdded (skinnedMeshRenderer: SkinnedMeshRenderer): void { - const { _useBakedAnimation: useBakedAnimation } = this; + const { _useBakedEffectively } = this; const formerBound = skinnedMeshRenderer.associatedAnimation; if (formerBound) { formerBound._users.delete(skinnedMeshRenderer); } skinnedMeshRenderer.associatedAnimation = this; - skinnedMeshRenderer.setUseBakedAnimation(useBakedAnimation, true); - if (useBakedAnimation) { + skinnedMeshRenderer.setUseBakedAnimation(_useBakedEffectively, true); + if (_useBakedEffectively) { const { _currentBakedState: playingState } = this; if (playingState) { skinnedMeshRenderer.uploadAnimation(playingState.clip); @@ -333,7 +323,7 @@ export class SkeletalAnimation extends Animation { } protected doPlayOrCrossFade (state: AnimationState, duration: number): void { - if (this._useBakedAnimation) { + if (this._useBakedEffectively) { if (this._currentBakedState) { this._currentBakedState.stop(); } @@ -354,4 +344,32 @@ export class SkeletalAnimation extends Animation { this.notifySkinnedMeshRemoved(user); }); } + + private get _useBakedEffectively (): boolean { + if (FORCE_BAN_BAKED_ANIMATION) { + return false; + } else { + return this._useBakedAnimation; + } + } + + private _applyBakeFlagChange (): void { + const useBakedEffectively = this._useBakedEffectively; + + for (const stateName in this._nameToState) { + const state = this._nameToState[stateName] as SkeletalAnimationState; + state.setUseBaked(useBakedEffectively); + } + + this._users.forEach((user) => { + user.setUseBakedAnimation(useBakedEffectively); + }); + + if (useBakedEffectively) { + getGlobalAnimationManager().removeSockets(this.node, this._sockets); + } else { + getGlobalAnimationManager().addSockets(this.node, this._sockets); + this._currentBakedState = null; + } + } } diff --git a/tests/animation/skeletal-animation.test.ts b/tests/animation/skeletal-animation.test.ts index 6c6433b5f41..4c7605be10e 100644 --- a/tests/animation/skeletal-animation.test.ts +++ b/tests/animation/skeletal-animation.test.ts @@ -8,6 +8,9 @@ import { JointAnimationInfo } from '../../cocos/3d/skeletal-animation/skeletal-a import { SkinnedMeshRenderer } from '../../cocos/3d/skinned-mesh-renderer'; import { Node, Scene } from '../../cocos/scene-graph'; import { director, game } from '../../cocos/game'; +import { SkinningModel } from '../../cocos/3d/models/skinning-model'; +import { Mesh, Skeleton } from '../../cocos/3d'; +import { BakedSkinningModel } from '../../cocos/3d/models/baked-skinning-model'; describe('Skeletal animation state', () => { function createSimpleClip(name: string, duration: number, from: number, to: number, path = '') { @@ -220,4 +223,40 @@ describe('Skeletal animation component', () => { skeletalAnimation.enabled = true; expect(state.isPlaying && !state.isPaused).toBe(true); }); + + describe(`useBakedAnimation`, () => { + test.each([ + [true], + [false], + ] as [use: boolean][])(`useBakedAnimation: %s`, ( + use, + ) => { + const clip = new AnimationClip('meow'); + clip.duration = 1.0; + + const node = new Node(); + + const skinnedMeshRenderer = node.addComponent(SkinnedMeshRenderer) as SkinnedMeshRenderer; + skinnedMeshRenderer.mesh = new Mesh(); + skinnedMeshRenderer.skeleton = new Skeleton(); + skinnedMeshRenderer.skinningRoot = node; + + const skeletalAnimation = node.addComponent(SkeletalAnimation) as SkeletalAnimation; + skeletalAnimation.clips = [clip]; + + skeletalAnimation.useBakedAnimation = use; + expect(skeletalAnimation.useBakedAnimation).toBe(use); + + const scene = new Scene('Scene'); + scene.addChild(node); + + director.runSceneImmediate(scene); + + if (use) { + expect(skinnedMeshRenderer.model).toBeInstanceOf(BakedSkinningModel); + } else { + expect(skinnedMeshRenderer.model).toBeInstanceOf(SkinningModel); + } + }); + }); }); \ No newline at end of file From 0a50141a7e87aaa32880d6bc73bdf2095322d46e Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Thu, 17 Aug 2023 10:22:55 +0800 Subject: [PATCH 165/232] add sheen lighting model and substance support for sheen and coat (#15970) --- .../data-structures/lighting-result.chunk | 2 + .../lighting-flow/common-flow.chunk | 9 + .../model-functions/standard.chunk | 3 +- .../surfaces/data-structures/standard.chunk | 1 + .../default-functions/standard-fs.chunk | 20 + .../effect-macros/common-macros.chunk | 5 +- .../module-functions/standard-fs.chunk | 18 + .../assets/effects/advanced/car-paint.effect | 11 +- editor/assets/effects/advanced/fabric.effect | 346 ++++++++++++++++++ .../effects/advanced/fabric.effect.meta | 11 + 10 files changed, 422 insertions(+), 4 deletions(-) create mode 100644 editor/assets/effects/advanced/fabric.effect create mode 100644 editor/assets/effects/advanced/fabric.effect.meta diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk index fd148768dde..11e5a19c741 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk @@ -24,6 +24,8 @@ struct LightingResult #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE vec3 directTransmitDiffuse, environmentTransmitDiffuse; #endif + // used for retro/internal-reflection such as TRT, Dual-Lobe Specular, Sheen... + // multi-layer (coat) just temporary use here, it should be moved to LightingResultPerLayer member #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR vec3 direct2ndSpecular, environment2ndSpecular; vec3 specularColorWithLighting2ndSpecular; diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index 4bce62ff3eb..88078372f3a 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -111,6 +111,10 @@ CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData2ndSpecular, surfaceData, lightDirWithLength); CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, vec3(1.0)); + #if CC_SURFACES_LIGHTING_SHEEN + vec3 extraF = CCSurfaceLightingCalculateExtraFresnel(lightingData2ndSpecular); + lightingResult.directGF2ndSpecular *= extraF; + #endif lightingResult.direct2ndSpecular *= multiplier; #endif @@ -259,6 +263,11 @@ CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, lightingResult.environmentGF2ndSpecular); + #if CC_SURFACES_LIGHTING_SHEEN + vec3 extraF = CCSurfaceLightingCalculateExtraFresnel(lightingData2ndSpecular); + lightingResult.environmentGF2ndSpecular *= extraF; + lightingResult.directGF2ndSpecular *= extraF; + #endif #endif #if CC_SURFACES_LIGHTING_TT diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index 74d1afe399f..89f25c75547 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -58,13 +58,11 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l #endif } -#if CC_SURFACES_LIGHTING_USE_FRESNEL vec3 CCSurfaceLightingCalculateExtraFresnel(in LightingIntermediateData lightingData) { float fresnel = CalculateFresnelCoefficient(lightingData.ior, lightingData.NoVAbsSat); //NoVSat for single side, and NoVAbsSat for two sided return vec3(fresnel); } -#endif void CCSurfaceLightingCalculateDirectFresnel(out vec3 directGF, in LightingIntermediateData lightingData, vec3 specularColor, in vec3 environmentGF) { @@ -255,6 +253,7 @@ void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 in #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND // todo: layer result in LightingResult separate to single structure like LightingResultPerLayer + // todo: after structuring, add TRT/Sheen to eachLayer's direct/environmentSpecular before blending void CCSurfacesLightingCalculateDirectMultiLayerBlending(inout LightingResult lightingResult , in LightingIntermediateData lightingData2ndLayer #if CC_SURFACES_LIGHTING_USE_MULTIPLE_LAYER_BLEND > 1 diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk b/editor/assets/chunks/surfaces/data-structures/standard.chunk index a45f0309095..35ad979848b 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk @@ -28,6 +28,7 @@ struct SurfacesMaterialData #endif #if CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR // for storage only, copied with CCSurfacesGetSurfacesMaterialData2ndSpecular + // todo: use SurfacesMaterialDataPerLayer instead vec3 baseColor2ndSpecular, color2ndSpecular; float intensity2ndSpecular, roughness2ndSpecular, metallic2ndSpecular; vec3 worldNormal2ndSpecular, worldTangent2ndSpecular, worldBinormal2ndSpecular; diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index 230cbf6f2bb..038a9e75993 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -215,6 +215,26 @@ vec3 SurfacesFragmentModifyClearCoatWorldNormal() } #endif +#ifndef CC_SURFACES_FRAGMENT_MODIFY_SHEEN_PARAMS +// depends on CC_SURFACES_FRAGMENT_MODIFY_SHEEN_PARAMS +vec4 SurfacesFragmentModifySheenParams() +{ + //x: sheen roughness + //y: sheen ior + //z: sheen opacity + //w: sheen intensity + return vec4(0.7, 1.0, 1.0, 1.0); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_SHEEN_COLOR +// depends on CC_SURFACES_FRAGMENT_MODIFY_SHEEN_COLOR +vec3 SurfacesFragmentModifySheenColor() +{ + return vec3(1.0, 1.0, 1.0); +} +#endif + #ifndef CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA // depends on CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA // some material datas use shared raw data, avoid sample / calculate same raw data multiply times, use this function for better performance diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk index 6c8caca0b8d..dd8d5c245ca 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk @@ -71,6 +71,9 @@ #ifndef CC_SURFACES_LIGHTING_DUAL_LOBE_SPECULAR #define CC_SURFACES_LIGHTING_DUAL_LOBE_SPECULAR 0 #endif +#ifndef CC_SURFACES_LIGHTING_SHEEN + #define CC_SURFACES_LIGHTING_SHEEN 0 +#endif #ifndef CC_SURFACES_LIGHTING_CLEAR_COAT #define CC_SURFACES_LIGHTING_CLEAR_COAT 0 #endif @@ -83,7 +86,7 @@ // common 2nd-specular for TRT / Dual-Lobe / Wet / ClearCoat... #ifndef CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR - #if CC_SURFACES_LIGHTING_TRT || CC_SURFACES_LIGHTING_DUAL_LOBE_SPECULAR || CC_SURFACES_LIGHTING_CLEAR_COAT + #if CC_SURFACES_LIGHTING_TRT || CC_SURFACES_LIGHTING_DUAL_LOBE_SPECULAR || CC_SURFACES_LIGHTING_SHEEN || CC_SURFACES_LIGHTING_CLEAR_COAT #define CC_SURFACES_LIGHTING_2ND_LAYER_SPECULAR 1 #endif #endif diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index 6399cee8adc..6d139729e86 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -87,6 +87,24 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) #endif #endif +#if CC_SURFACES_LIGHTING_SHEEN + // skip in shader graph, need extra code + vec4 sheenParams = SurfacesFragmentModifySheenParams(); + surfaceData.roughness2ndSpecular = saturate(sheenParams.x); + surfaceData.ior2ndSpecular = sheenParams.y; + surfaceData.intensity2ndSpecular = sheenParams.z * sheenParams.w; + surfaceData.metallic2ndSpecular = 1.0; + surfaceData.baseColor2ndSpecular = SurfacesFragmentModifySheenColor(); + surfaceData.color2ndSpecular = vec3(1.0); // no extra coloration + surfaceData.worldNormal2ndSpecular = surfaceData.worldNormal; + surfaceData.worldTangent2ndSpecular = surfaceData.worldTangent; + surfaceData.worldBinormal2ndSpecular = surfaceData.worldBinormal; + surfaceData.opacity2ndSpecular = 1.0; // unused + #if CC_SURFACES_LIGHTING_ANISOTROPIC + surfaceData.anisotropyShape2ndSpecular = surfaceData.anisotropyShape; + #endif +#endif + #if CC_SURFACES_LIGHTING_CLEAR_COAT // skip in shader graph, need extra code vec4 clearCoatParams = SurfacesFragmentModifyClearCoatParams(); diff --git a/editor/assets/effects/advanced/car-paint.effect b/editor/assets/effects/advanced/car-paint.effect index 457fd1d97c5..6d7b0a97083 100644 --- a/editor/assets/effects/advanced/car-paint.effect +++ b/editor/assets/effects/advanced/car-paint.effect @@ -30,6 +30,7 @@ CCEffect %{ gradientIntensity: { value: 0.5, target: emissiveScaleParam.y, editor: { parent: USE_GRADIENT_COLOR, slide: true, range: [0, 1.0], step: 0.001 } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } normalMap: { value: normal } + coatDataMap: { value: white, editor: { parent: USE_COAT_DATA_MAP, tooltip: 'r: Coat Roughness g: Coat Specular Intensity b: Coat Opacity.' } } coatNormalMap: { value: normal, editor: { parent: USE_FLAKE } } flakeDataMap: { value: white, editor: { parent: USE_FLAKE } } pbrMap: { value: grey } @@ -193,6 +194,9 @@ CCProgram surface-fragment %{ uniform sampler2D coatNormalMap; uniform sampler2D flakeDataMap; #endif + #if USE_COAT_DATA_MAP + uniform sampler2D coatDataMap; + #endif #pragma define OCCLUSION_CHANNEL r #pragma define ROUGHNESS_CHANNEL g @@ -206,7 +210,12 @@ CCProgram surface-fragment %{ #define CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_PARAMS vec4 SurfacesFragmentModifyClearCoatParams() { - return vec4(coatParam.x, coatParam.y - 0.99, coatParam.z, coatParam.w * 2.0); + vec4 params = vec4(coatParam.x, coatParam.y - 0.99, coatParam.z, coatParam.w * 2.0); + #if USE_COAT_DATA_MAP + vec4 coatData = texture(coatDataMap, FSInput_texcoord); + params *= vec4(coatData.r, 1.0, coatData.b, coatData.g); + #endif + return params; } #define CC_SURFACES_FRAGMENT_MODIFY_CLEAR_COAT_COLOR diff --git a/editor/assets/effects/advanced/fabric.effect b/editor/assets/effects/advanced/fabric.effect new file mode 100644 index 00000000000..4803793548b --- /dev/null +++ b/editor/assets/effects/advanced/fabric.effect @@ -0,0 +1,346 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 0.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + roughness: { value: 0.5, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.0, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + anisotropyIntensity: { value: 1.0, target: anisotropyParam.x, editor: { parent: IS_ANISOTROPY, slide : true, range : [0.0, 1.0] , step : 0.0001 } } + anisotropyRotation: { value: 0.0, target: anisotropyParam.y, editor: { parent: IS_ANISOTROPY, slide : true, range : [0, 1.0] , step : 0.0001 } } + anisotropyMapResolutionHeight: { value: 0.0, target: anisotropyParam.w, editor: { parent: FIX_ANISOTROPIC_ROTATION_MAP } } + addOnShadowBias: { value: 0.0, target: anisotropyParam.z } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + normalMap: { value: normal } + pbrMap: { value: grey } + occlusionMap: { value: white } + anisotropyMap: { value: black, editor : { parent: IS_ANISOTROPY } } + sheenColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { type: color } } + sheenRoughness: { value: 1.0, target: emissiveScaleParam.x, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + sheenIOR: { value: 1.0, target: emissiveScaleParam.y, editor: { slide: true, range: [1.0, 2.0], step: 0.001 } } + sheenOpacity: { value: 1.0, target: emissiveScaleParam.z, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + sheenMap: { value: white, editor: { parent: USE_SHEEN_MAP, tooltips: 'r: sheen roughness g: sheen opacity' } } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + rasterizerState: + cullMode: front + properties: + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + - &reflect-map + vert: standard-vs + frag: reflect-map-fs + phase: reflect-map + propertyIndex: 0 + - &planar-shadow + vert: planar-shadow-vs + frag: planar-shadow-fs + phase: planar-shadow + propertyIndex: 0 + depthStencilState: + depthTest: true + depthWrite: false + stencilTestFront: true + stencilFuncFront: not_equal + stencilPassOpFront: replace + stencilRef: 0x80 # only use the leftmost bit + stencilReadMask: 0x80 + stencilWriteMask: 0x80 + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + - &deferred + vert: standard-vs + frag: standard-fs + pass: gbuffer + phase: gbuffer + embeddedMacros: { CC_PIPELINE_TYPE: 1 } + propertyIndex: 0 + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: &d1 + depthTest: true + depthWrite: false + blendState: &b1 + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster + - *planar-shadow + - &deferred-forward + vert: standard-vs + frag: standard-fs + phase: deferred-forward + embeddedMacros: { CC_PIPELINE_TYPE: 0 } + propertyIndex: 0 + depthStencilState: *d1 + blendState: *b1 +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + vec4 pbrParams; + vec4 sheenColor; + vec4 emissiveScaleParam; + vec4 anisotropyParam; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta HAS_SECOND_UV + #pragma define-meta USE_TWOSIDE + #pragma define-meta IS_ANISOTROPY + #pragma define-meta USE_VERTEX_COLOR + + #define CC_SURFACES_USE_SECOND_UV HAS_SECOND_UV + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_LIGHTING_ANISOTROPIC IS_ANISOTROPY + #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR + #define CC_SURFACES_LIGHTING_SHEEN 1 + + // depend on UI macros +#if IS_ANISOTROPY || USE_NORMAL_MAP + #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif + + // functionality for each effect + #define CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT 31 +}% + +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_SHADOW_BIAS + vec2 SurfacesVertexModifyShadowBias(in SurfacesStandardVertexIntermediate In, vec2 originShadowBias) + { + return originShadowBias + vec2(anisotropyParam.z, 0.0); + } + + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw; + #if CC_SURFACES_USE_SECOND_UV + In.texCoord1 = In.texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + } +}% + +CCProgram surface-fragment %{ + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) + #endif + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + #pragma define-meta DEFAULT_UV options([v_uv, v_uv1]) + #if USE_PBR_MAP + uniform sampler2D pbrMap; + #endif + #if USE_OCCLUSION_MAP + uniform sampler2D occlusionMap; + #endif + #if IS_ANISOTROPY && USE_ANISOTROPY_MAP + uniform sampler2D anisotropyMap; + #endif + #if USE_SHEEN_MAP + uniform sampler2D sheenMap; + #endif + + #pragma define OCCLUSION_CHANNEL r + #pragma define ROUGHNESS_CHANNEL g + #pragma define METALLIC_CHANNEL b + #pragma define SPECULAR_INTENSITY_CHANNEL a + + #if USE_ALPHA_TEST + #pragma define-meta ALPHA_TEST_CHANNEL options([a, r]) + #endif + + #define CC_SURFACES_FRAGMENT_MODIFY_ANISOTROPY_PARAMS + vec4 SurfacesFragmentModifyAnisotropyParams(out float isRotation) + { + float anisotropyRotation = anisotropyParam.y * PI; + float anisotropyShape = anisotropyParam.x; + #if IS_ANISOTROPY && USE_ANISOTROPY_MAP + // Rotation angle should disable trilinear filtering + vec4 tex = texture(anisotropyMap, DEFAULT_UV); + anisotropyRotation = fract(anisotropyRotation * 0.5 + tex.y) * PI2; + // less value is better for SP exported shape + anisotropyShape *= tex.x; + #endif + + isRotation = 1.0; + return vec4(anisotropyShape, anisotropyRotation, 0.0, 0.0); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_SHEEN_PARAMS + vec4 SurfacesFragmentModifySheenParams() + { + vec4 param = vec4(emissiveScaleParam.x, emissiveScaleParam.y - 0.9, emissiveScaleParam.z, 1.0); + #if USE_SHEEN_MAP + param.xz *= texture(sheenMap, FSInput_texcoord).xy; + #endif + return param; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_SHEEN_COLOR + vec3 SurfacesFragmentModifySheenColor() + { + return sheenColor.rgb; + } + + #include +}% + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram planar-shadow-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram planar-shadow-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include +}% + +CCProgram reflect-map-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + #include + #include +}% + diff --git a/editor/assets/effects/advanced/fabric.effect.meta b/editor/assets/effects/advanced/fabric.effect.meta new file mode 100644 index 00000000000..8a62097c4df --- /dev/null +++ b/editor/assets/effects/advanced/fabric.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.7.0", + "importer": "effect", + "imported": true, + "uuid": "b25c7601-1d07-4a56-86c5-62e83ea7c61e", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} From 6e7841fbbbe4a522da88f258a994f6a01dcc4c4f Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Thu, 17 Aug 2023 10:24:49 +0800 Subject: [PATCH 166/232] fixed colorTemperatureRGB jsb binding. (#15972) --- native/tools/swig-config/scene.i | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index 39aa6e93646..2a2fff63cae 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -80,7 +80,7 @@ using namespace cc; } }, result); - + SE_PRECONDITION2(ok, false, "Error processing arguments"); %} @@ -337,6 +337,7 @@ using namespace cc; %attribute(cc::scene::Light, ccstd::string&, name, getName, setName); %attribute(cc::scene::Light, cc::scene::RenderScene*, scene, getScene); %attribute(cc::scene::Light, uint32_t, visibility, getVisibility, setVisibility); +%attribute(cc::scene::Light, cc::Vec3&, colorTemperatureRGB, getColorTemperatureRGB, setColorTemperatureRGB); %attribute(cc::scene::LODData, float, screenUsagePercentage, getScreenUsagePercentage, setScreenUsagePercentage); %attribute(cc::scene::LODData, ccstd::vector>&, models, getModels); From c0adb51d36a2c950e76b05f61d5206b1b94436a0 Mon Sep 17 00:00:00 2001 From: zxx43 Date: Thu, 17 Aug 2023 10:38:56 +0800 Subject: [PATCH 167/232] add jsb Slot::getAttachment & Slot::setAttachment (#15964) * add Slot::getAttachment & Slot::setAttachment * Use nativevalue_to_se instead of native_ptr_to_seval in js_spine_Slot_getAttachment * merge into 1 statement --- .../bindings/manual/jsb_spine_manual.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/native/cocos/bindings/manual/jsb_spine_manual.cpp b/native/cocos/bindings/manual/jsb_spine_manual.cpp index 6e550dc889d..4bc5f5fbb68 100644 --- a/native/cocos/bindings/manual/jsb_spine_manual.cpp +++ b/native/cocos/bindings/manual/jsb_spine_manual.cpp @@ -519,6 +519,42 @@ static bool js_spine_Skin_getAttachments(se::State& s) { } SE_BIND_FUNC(js_spine_Skin_getAttachments) +static bool js_spine_Slot_setAttachment(se::State& s) { + CC_UNUSED bool ok = true; + const auto& args = s.args(); + spine::Slot *slot = (spine::Slot *) NULL ; + + slot = SE_THIS_OBJECT(s); + if (nullptr == slot) return true; + + spine::Attachment* attachment = nullptr; + + ok = sevalue_to_native(args[0], &attachment, s.thisObject()); + SE_PRECONDITION2(ok, false, "Error processing arguments"); + + slot->setAttachment(attachment); + + return true; +} +SE_BIND_FUNC(js_spine_Slot_setAttachment) + +static bool js_spine_Slot_getAttachment(se::State& s) { + CC_UNUSED bool ok = true; + const auto& args = s.args(); + spine::Slot *slot = (spine::Slot *) NULL ; + + slot = SE_THIS_OBJECT(s); + if (nullptr == slot) return true; + + spine::Attachment *attachment = slot->getAttachment(); + if (attachment) { + nativevalue_to_se(attachment, s.rval(), s.thisObject()); + return true; + } + return false; +} +SE_BIND_FUNC(js_spine_Slot_getAttachment) + bool register_all_spine_manual(se::Object *obj) { // Get the ns se::Value nsVal; @@ -545,6 +581,8 @@ bool register_all_spine_manual(se::Object *obj) { __jsb_spine_SwirlVertexEffect_proto->defineFunction("transform", _SE(js_SwirlVertexEffect_transform)); __jsb_spine_JitterVertexEffect_proto->defineFunction("transform", _SE(js_JitterVertexEffect_transform)); __jsb_spine_Skin_proto->defineFunction("getAttachments", _SE(js_spine_Skin_getAttachments)); + __jsb_spine_Slot_proto->defineFunction("setAttachment", _SE(js_spine_Slot_setAttachment)); + __jsb_spine_Slot_proto->defineFunction("getAttachment", _SE(js_spine_Slot_getAttachment)); spine::setSpineObjectDisposeCallback([](void *spineObj) { if (!se::NativePtrToObjectMap::isValid()) { From dd356191613e9cc87c8f93cc98e0fc8095dfa5c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 17 Aug 2023 11:15:43 +0800 Subject: [PATCH 168/232] Revert interface check (#15991) * Revert "Workflow: fix interface check workflow comment (#15795)" This reverts commit 44795e465ff034d3b51338f70f7b538f405db2f9. * Revert "V3.8.0 (#15697)" This reverts commit 1c16ac25d8268f977bcc625d31dea2d775e3afd1. --------- Co-authored-by: intrigus-lgtm <60750685+intrigus-lgtm@users.noreply.github.com> --- .github/workflows/run_test_cases.yml | 46 +++++-------------- .../workflows/run_test_cases_pr_comment.yml | 36 --------------- .../web-interface-check-pr-comment.yml | 42 ----------------- .github/workflows/web-interface-check.yml | 9 +--- 4 files changed, 13 insertions(+), 120 deletions(-) delete mode 100644 .github/workflows/run_test_cases_pr_comment.yml delete mode 100644 .github/workflows/web-interface-check-pr-comment.yml diff --git a/.github/workflows/run_test_cases.yml b/.github/workflows/run_test_cases.yml index 038ebd04c88..8e15788a1f3 100644 --- a/.github/workflows/run_test_cases.yml +++ b/.github/workflows/run_test_cases.yml @@ -1,12 +1,10 @@ name: run test cases on: - pull_request: + pull_request_target: issue_comment: types: [created, edited] -permissions: read-all - # github.head_ref is only defined on pull_request events concurrency: group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} @@ -281,38 +279,16 @@ jobs: JOBID=`cat /usr/local/lib/node_modules/@cctest/scheduler/logs/PR-TEST/nowJobId.log` cd .. python3 -u ./python/main.py --target=job_editor --jobid=$JOBID - - name: Write comment body and issue number to file - uses: actions/github-script@v5 - env: - PR_AUTHOR: ${{ steps.parse_pr.outputs.pr_author }} - EDITOR_VERSION: ${{ steps.run_test_cases.outputs.editor }} - TASK_STATUS: ${{ steps.run_test_cases.outputs.status }} - TASK_REPORT: ${{ steps.run_test_cases.outputs.report }} - JOB_ID: ${{ steps.run_test_cases.outputs.jobid }} - GITHUB_RUN_ID: ${{ github.run_id }} - PR_NUMBER: ${{ steps.get_pr.outputs.pr_number }} + - name: Update Comment + uses: peter-evans/create-or-update-comment@v1 with: - script: | - const fs = require('fs'); - fs.writeFileSync('pr.txt', process.env.PR_NUMBER); - fs.writeFileSync('comment.txt', `@${process.env.PR_AUTHOR}, Please check the result of \`run test cases\`: + issue-number: ${{ steps.get_pr.outputs.pr_number }} + body: | + @${{ steps.parse_pr.outputs.pr_author }}, Please check the result of `run test cases`: - Test Platform: PR-Test - - Editor Version: ${process.env.EDITOR_VERSION} - - Task Result: ${process.env.TASK_STATUS} - - Task URL: http://cctest.cocos.org/#/reportview/PR-TEST/${process.env.JOB_ID}/-1 - - GitHub Action: https://github.com/cocos/cocos-engine/actions/runs/${process.env.GITHUB_RUN_ID} + - Editor Version: ${{ steps.run_test_cases.outputs.editor }} + - Task Result: ${{ steps.run_test_cases.outputs.status }} + - Task URL: http://cctest.cocos.org/#/reportview/PR-TEST/${{ steps.run_test_cases.outputs.jobid }}/-1 + - GitHub Action: https://github.com/cocos/cocos-engine/actions/runs/${{ github.run_id }} ## Task Details - ${process.env.TASK_REPORT}`); - - name: Upload artifact - uses: actions/upload-artifact@v2 - with: - name: pr.txt - path: | - pr.txt - - name: Upload artifact - uses: actions/upload-artifact@v2 - with: - name: comment.txt - path: | - comment.txt - \ No newline at end of file + ${{ steps.run_test_cases.outputs.report }} diff --git a/.github/workflows/run_test_cases_pr_comment.yml b/.github/workflows/run_test_cases_pr_comment.yml deleted file mode 100644 index 7c425fb30c9..00000000000 --- a/.github/workflows/run_test_cases_pr_comment.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: run test cases PR comment -on: - workflow_run: - workflows: ["run test cases"] - types: - - completed - -permissions: - issues: write - pull-requests: write - -jobs: - post-pr-comment: - if: github.event.workflow_run.conclusion == 'success' - runs-on: ubuntu-latest - steps: - - name: Download artifacts - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RUN_ID: ${{ github.event.workflow_run.id }} - run: | - gh run download -R "${{ github.repository }}" --name "pr.txt" "$RUN_ID" - gh run download -R "${{ github.repository }}" --name "comment.txt" "$RUN_ID" - - name: Set PR environment variable - uses: actions/github-script@v4 - with: - script: | - const fs = require('fs'); - const pr = fs.readFileSync('pr.txt', 'utf8').trim(); - core.exportVariable('PR_NUMBER', pr); - - - name: Update Comment - uses: peter-evans/create-or-update-comment@v3 - with: - issue-number: ${{ env.PR_NUMBER }} - body-path: 'comment.txt' \ No newline at end of file diff --git a/.github/workflows/web-interface-check-pr-comment.yml b/.github/workflows/web-interface-check-pr-comment.yml deleted file mode 100644 index 79816558b63..00000000000 --- a/.github/workflows/web-interface-check-pr-comment.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: Interface check PR comment -on: - workflow_run: - workflows: [" Interface check"] - types: - - completed - -permissions: - issues: write - pull-requests: write - -jobs: - post-pr-comment: - if: github.event.workflow_run.conclusion == 'success' - runs-on: ubuntu-latest - steps: - - name: 'Get source run informations' - uses: potiuk/get-workflow-origin@v1_1 - id: source_run_info - with: - token: ${{ secrets.GITHUB_TOKEN }} - sourceRunId: ${{ github.event.workflow_run.id }} - - - name: 'Debug' - run: | - Write-Host "Source PR Number: ${{ github.event.workflow_run.pull_requests[0].number }}" - shell: pwsh - - - name: Download artifacts - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RUN_ID: ${{ github.event.workflow_run.id }} - run: | - gh run download -R "${{ github.repository }}" --name "interface-diff.txt" "$RUN_ID" - - - name: Post interface-diff.txt as comment - uses: marocchino/sticky-pull-request-comment@v2 - with: - path: interface-diff.txt - number: ${{ steps.source_run_info.outputs.pullRequestNumber }} - # The following matters, see: https://github.com/orgs/community/discussions/25220 - # number: ${{ github.event.workflow_run.pull_requests[0].number }} \ No newline at end of file diff --git a/.github/workflows/web-interface-check.yml b/.github/workflows/web-interface-check.yml index f96ce3b2235..25f5e3492dd 100644 --- a/.github/workflows/web-interface-check.yml +++ b/.github/workflows/web-interface-check.yml @@ -1,15 +1,13 @@ name: Interface check #on: push -on: [pull_request] +on: [pull_request_target] # github.head_ref is only defined on pull_request events concurrency: group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} cancel-in-progress: true -permissions: read-all - jobs: interface_check: if: @@ -81,9 +79,6 @@ jobs: cat ./interface-diff.txt node ./.github/workflows/interface-check-report.js - - name: Upload interface-diff.txt artifact - uses: actions/upload-artifact@v2 + - uses: marocchino/sticky-pull-request-comment@v2 with: - name: interface-diff.txt path: ./engine/interface-diff.txt - \ No newline at end of file From 9b08b34a2b2d6b86f0871492329e5d12e8b52b3b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 17 Aug 2023 13:15:21 +0800 Subject: [PATCH 169/232] Replace Renderer setMaterial with setSharedMaterial (#15980) * Replace Renderer setMaterial with setSharedMaterial * Fix all usage of Renderer.setMaterial * Soft deprecate Renderer.setMaterial * Remove unnecessary change --- EngineErrorMap.md | 4 ++++ cocos/2d/components/graphics.ts | 6 +++--- cocos/2d/framework/ui-renderer.ts | 8 ++++---- .../skinned-mesh-renderer.ts | 4 ++-- cocos/dragon-bones/ArmatureDisplay.ts | 13 ++++++++++--- cocos/misc/renderer.ts | 19 +++++++++++++------ cocos/particle-2d/particle-system-2d.ts | 2 +- cocos/particle/line.ts | 2 +- .../renderer/particle-system-renderer-data.ts | 4 ++-- cocos/spine/skeleton.ts | 2 +- cocos/terrain/terrain.ts | 2 +- 11 files changed, 42 insertions(+), 24 deletions(-) diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 8d5856b5a24..bf943cfd907 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3267,6 +3267,10 @@ PassUtils: illegal uniform handle, accessing uniform at offset %d Pass: setUniform is invoked with incompatible uniform data type for binding %d, expected type is %s +### 12012 + +Can't set a material instance to a sharedMaterial slot + ### 12100 The font size is too big to be fitted into texture atlas. Please switch to other label cache modes or choose a smaller font size. diff --git a/cocos/2d/components/graphics.ts b/cocos/2d/components/graphics.ts index 1f4fb1c8e32..08248a4b935 100644 --- a/cocos/2d/components/graphics.ts +++ b/cocos/2d/components/graphics.ts @@ -34,7 +34,7 @@ import { IAssembler } from '../renderer/base'; import { IBatcher } from '../renderer/i-batcher'; import { LineCap, LineJoin } from '../assembler/graphics/types'; import { Impl } from '../assembler/graphics/webgl/impl'; -import { RenderingSubMesh } from '../../asset/assets'; +import { Material, RenderingSubMesh } from '../../asset/assets'; import { Format, PrimitiveMode, Attribute, Device, BufferUsageBit, BufferInfo, MemoryUsageBit, deviceManager } from '../../gfx'; import { vfmtPosColor, getAttributeStride, getComponentPerVertex } from '../renderer/vertex-format'; import { NativeUIModelProxy } from '../renderer/native-2d'; @@ -528,7 +528,7 @@ export class Graphics extends UIRenderer { * @param h @en The height of the rectangle. * @zh 矩形高度。 */ - public fillRect (x, y, w, h): void { + public fillRect (x: number, y: number, w: number, h: number): void { this.rect(x, y, w, h); this.fill(); } @@ -615,7 +615,7 @@ export class Graphics extends UIRenderer { mat = this.getMaterialInstance(0); } else { mat = builtinResMgr.get('ui-graphics-material'); - this.setMaterial(mat, 0); + this.setSharedMaterial(mat as Material, 0); mat = this.getMaterialInstance(0); mat.recompileShaders({ USE_LOCAL: true }); } diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 440fedc6424..bb4c4a2abd6 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -151,12 +151,12 @@ export class UIRenderer extends Renderer { set sharedMaterials (val) { for (let i = 0; i < val.length; i++) { if (val[i] !== this._materials[i]) { - this.setMaterial(val[i], i); + this.setSharedMaterial(val[i], i); } } if (val.length < this._materials.length) { for (let i = val.length; i < this._materials.length; i++) { - this.setMaterial(null, i); + this.setSharedMaterial(null, i); } this._materials.splice(val.length); } @@ -450,12 +450,12 @@ export class UIRenderer extends Renderer { public updateMaterial (): void { if (this._customMaterial) { if (this.getSharedMaterial(0) !== this._customMaterial) { - this.setMaterial(this._customMaterial, 0); + this.setSharedMaterial(this._customMaterial, 0); } return; } const mat = this._updateBuiltinMaterial(); - this.setMaterial(mat, 0); + this.setSharedMaterial(mat, 0); if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) { this.getMaterialInstance(0)!.recompileShaders({ USE_ALPHA_TEST: true }); } diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts index 7f3125b3275..84cd794e0a2 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts @@ -143,8 +143,8 @@ export class SkinnedMeshRenderer extends MeshRenderer { } } - public setMaterial (material: Material | null, index: number): void { - super.setMaterial(material, index); + public setSharedMaterial (material: Material | null, index: number): void { + super.setSharedMaterial(material, index); if (this._modelType === SkinningModel) { this.getMaterialInstance(index); } diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index 2e70e6d9660..0c27f29e0cc 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -715,7 +715,7 @@ export class ArmatureDisplay extends UIRenderer { let mat; if (this._customMaterial) mat = this._customMaterial; else mat = this._updateBuiltinMaterial(); - this.setMaterial(mat, 0); + this.setSharedMaterial(mat as Material, 0); this._cleanMaterialCache(); } @@ -732,8 +732,15 @@ export class ArmatureDisplay extends UIRenderer { this._drawIdx = i; const dc = this._drawList.data[i]; if (dc.texture) { - batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, - dc.indexCount, dc.texture, dc.material!, this._enableBatch); + batcher.commitMiddleware( + this, + meshBuffer, + origin + dc.indexOffset, + dc.indexCount, + dc.texture, + dc.material!, + this._enableBatch, + ); } indicesCount += dc.indexCount; } diff --git a/cocos/misc/renderer.ts b/cocos/misc/renderer.ts index 8f5c9dc8e58..f7ccdbd2ca4 100644 --- a/cocos/misc/renderer.ts +++ b/cocos/misc/renderer.ts @@ -26,7 +26,7 @@ import { EDITOR } from 'internal:constants'; import { Material } from '../asset/assets/material'; import { Component } from '../scene-graph'; import { IMaterialInstanceInfo, MaterialInstance } from '../render-scene/core/material-instance'; -import { warnID, _decorator } from '../core'; +import { warnID, _decorator, errorID } from '../core'; const _matInsInfo: IMaterialInstanceInfo = { parent: null!, @@ -78,12 +78,12 @@ export class Renderer extends Component { set sharedMaterials (val) { for (let i = 0; i < val.length; i++) { if (val[i] !== this._materials[i]) { - this.setMaterial(val[i], i); + this.setSharedMaterial(val[i], i); } } if (val.length < this._materials.length) { for (let i = val.length; i < this._materials.length; i++) { - this.setMaterial(null, i); + this.setSharedMaterial(null, i); } this._materials.splice(val.length); } @@ -145,6 +145,13 @@ export class Renderer extends Component { return this.getSharedMaterial(idx); } + /** + * @deprecated Since v3.8.1, please use [[setSharedMaterial]] instead. + */ + public setMaterial (material: Material | null, index: number): void { + this.setSharedMaterial(material, index); + } + /** * @en Get the shared material asset of the specified sub-model. * @zh 获取指定子模型的共享材质资源。 @@ -161,9 +168,9 @@ export class Renderer extends Component { * new material instance will be created automatically if the sub-model is already using one. * @zh 设置指定子模型的 sharedMaterial,如果对应位置有材质实例则会创建一个对应的材质实例。 */ - public setMaterial (material: Material | null, index: number): void { + public setSharedMaterial (material: Material | null, index: number): void { if (material && material instanceof MaterialInstance) { - console.error('Can\'t set a material instance to a sharedMaterial slot'); + errorID(12012); } this._materials[index] = material; const inst = this._materialInstances[index]; @@ -223,7 +230,7 @@ export class Renderer extends Component { // Skip identity check if it's a Material property // Or if there is a MaterialInstance already if (matInst !== this._materials[index] || curInst) { - this.setMaterial(matInst as Material, index); + this.setSharedMaterial(matInst as Material, index); } } diff --git a/cocos/particle-2d/particle-system-2d.ts b/cocos/particle-2d/particle-system-2d.ts index 153d83816f5..2b40985c812 100644 --- a/cocos/particle-2d/particle-system-2d.ts +++ b/cocos/particle-2d/particle-system-2d.ts @@ -1178,7 +1178,7 @@ export class ParticleSystem2D extends UIRenderer { */ public _updateMaterial (): void { if (this._customMaterial) { - this.setMaterial(this._customMaterial, 0); + this.setSharedMaterial(this._customMaterial, 0); const target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0]; this._dstBlendFactor = target.blendDst; this._srcBlendFactor = target.blendSrc; diff --git a/cocos/particle/line.ts b/cocos/particle/line.ts index 7524a2abf94..348dcff09ce 100644 --- a/cocos/particle/line.ts +++ b/cocos/particle/line.ts @@ -73,7 +73,7 @@ export class Line extends ModelRenderer { } set lineMaterial (val) { - this.setMaterial(val, 0); + this.setSharedMaterial(val, 0); } @override diff --git a/cocos/particle/renderer/particle-system-renderer-data.ts b/cocos/particle/renderer/particle-system-renderer-data.ts index 5f3ca4e0b29..f50bcce3c35 100644 --- a/cocos/particle/renderer/particle-system-renderer-data.ts +++ b/cocos/particle/renderer/particle-system-renderer-data.ts @@ -146,7 +146,7 @@ export default class ParticleSystemRenderer { public set particleMaterial (val: Material | null) { if (this._particleSystem) { - this._particleSystem.setMaterial(val, 0); + this._particleSystem.setSharedMaterial(val, 0); } } @@ -226,7 +226,7 @@ export default class ParticleSystemRenderer { public set trailMaterial (val: Material | null) { if (this._particleSystem) { - this._particleSystem.setMaterial(val, 1); + this._particleSystem.setSharedMaterial(val, 1); } } diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index c4e81ab9dab..3c4a77efac7 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -1034,7 +1034,7 @@ export class Skeleton extends UIRenderer { let mat: Material; if (this._customMaterial) mat = this._customMaterial; else mat = this._updateBuiltinMaterial(); - this.setMaterial(mat, 0); + this.setSharedMaterial(mat, 0); this._cleanMaterialCache(); } diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index d5e3e6c1ff1..e973a6b2e71 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -283,7 +283,7 @@ class TerrainRenderable extends ModelRenderer { this._model.initSubModel(0, this._meshData, this._currentMaterial); } - this.setMaterial(this._currentMaterial, 0); + this.setSharedMaterial(this._currentMaterial, 0); this._currentMaterialLayers = nLayers; this._model.enabled = true; From ed670e7b1b8ca3e20b73b419c987e6d9e61e35bf Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Thu, 17 Aug 2023 15:42:40 +0800 Subject: [PATCH 170/232] NativePipeline external texture (#15946) * NativePipeline external texture * fix lint. * fix format. --- cocos/asset/assets/simple-texture.ts | 2 +- cocos/rendering/custom/pipeline.ts | 33 ++++++- cocos/rendering/custom/render-graph.ts | 3 +- cocos/rendering/custom/web-pipeline.ts | 88 +++++++++++++++++-- native/cocos/core/assets/SimpleTexture.cpp | 2 +- .../pipeline/custom/FrameGraphDispatcher.cpp | 17 ++-- .../pipeline/custom/LayoutGraphUtils.cpp | 29 ++++++ .../pipeline/custom/LayoutGraphUtils.h | 4 + .../pipeline/custom/NativePipeline.cpp | 83 ++++++++++++++++- .../pipeline/custom/NativePipelineTypes.h | 6 ++ .../pipeline/custom/NativeResourceGraph.cpp | 44 ++-------- .../pipeline/custom/RenderGraphTypes.h | 2 + .../pipeline/custom/RenderInterfaceTypes.h | 6 ++ 13 files changed, 263 insertions(+), 56 deletions(-) diff --git a/cocos/asset/assets/simple-texture.ts b/cocos/asset/assets/simple-texture.ts index 9d902b38896..1bd3e8907c0 100644 --- a/cocos/asset/assets/simple-texture.ts +++ b/cocos/asset/assets/simple-texture.ts @@ -310,7 +310,7 @@ export class SimpleTexture extends TextureBase { } } const textureCreateInfo = this._getGfxTextureCreateInfo({ - usage: TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, + usage: TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST | TextureUsageBit.COLOR_ATTACHMENT, format: this._getGFXFormat(), levelCount: this._mipmapLevel, flags, diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index 68e6d54d984..9635183715e 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -32,7 +32,7 @@ import { Material } from '../../asset/assets'; import { Camera } from '../../render-scene/scene/camera'; import { DirectionalLight } from '../../render-scene/scene/directional-light'; import { GeometryRenderer } from '../geometry-renderer'; -import { Buffer, BufferInfo, ClearFlagBit, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, Format, LoadOp, ResolveMode, SampleCount, Sampler, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureInfo, Viewport } from '../../gfx'; +import { Buffer, BufferInfo, ClearFlagBit, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, Format, LoadOp, ResolveMode, SampleCount, Sampler, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureInfo, TextureType, Viewport } from '../../gfx'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { Mat4, Quat, Vec2, Vec4 } from '../../core/math'; import { MacroRecord } from '../../render-scene/core/pass-utils'; @@ -684,6 +684,37 @@ export interface BasicPipeline extends PipelineRuntime { width: number, height: number, format?: Format): void; + addBuffer ( + name: string, + size: number, + flags: ResourceFlags, + residency: ResourceResidency): number; + updateBuffer ( + name: string, + size: number): void; + addExternalTexture (name: string, texture: Texture, flags: ResourceFlags): number; + updateExternalTexture (name: string, texture: Texture): void; + addTexture ( + name: string, + textureType: TextureType, + format: Format, + width: number, + height: number, + depth: number, + arraySize: number, + mipLevels: number, + sampleCount: SampleCount, + flags: ResourceFlags, + residency: ResourceResidency): number; + updateTexture ( + name: string, + format: Format, + width: number, + height: number, + depth: number, + arraySize: number, + mipLevels: number, + sampleCount: SampleCount): void; addResource ( name: string, dimension: ResourceDimension, diff --git a/cocos/rendering/custom/render-graph.ts b/cocos/rendering/custom/render-graph.ts index 41078871395..fa3f241f839 100644 --- a/cocos/rendering/custom/render-graph.ts +++ b/cocos/rendering/custom/render-graph.ts @@ -31,7 +31,7 @@ import { AdjI, AdjacencyGraph, BidirectionalGraph, ComponentGraph, ED, InEI, MutableGraph, MutableReferenceGraph, NamedGraph, OutE, OutEI, PolymorphicGraph, PropertyGraph, PropertyMap, ReferenceGraph, UuidGraph, VertexListGraph, directional, parallel, reindexEdgeList, traversal } from './graph'; import { Material } from '../../asset/assets'; import { Camera } from '../../render-scene/scene/camera'; -import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, LoadOp, RenderPass, SampleCount, Sampler, SamplerInfo, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureFlagBit, Viewport } from '../../gfx'; +import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, LoadOp, RenderPass, SampleCount, Sampler, SamplerInfo, ShaderStageFlagBit, StoreOp, Swapchain, Texture, TextureFlagBit, Viewport, TextureType } from '../../gfx'; import { AccessType, AttachmentType, ClearValueType, CopyPair, LightInfo, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UploadPair } from './types'; import { RenderScene } from '../../render-scene/core/render-scene'; import { RenderWindow } from '../../render-scene/core/render-window'; @@ -117,6 +117,7 @@ export class ResourceDesc { sampleCount: SampleCount = SampleCount.X1; textureFlags: TextureFlagBit = TextureFlagBit.NONE; flags: ResourceFlags = ResourceFlags.NONE; + viewType: TextureType = TextureType.TEX2D; } export class ResourceTraits { diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index fa46e3dab45..31be6f797d7 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -20,12 +20,12 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ + ****************************************************************************/ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; import { DEBUG } from 'internal:constants'; -import { Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo, UniformBlock, ResolveMode, SampleCount, Color } from '../../gfx'; +import { Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer, Type, SamplerInfo, Filter, Address, DescriptorSetInfo, LoadOp, StoreOp, ShaderStageFlagBit, BufferInfo, TextureInfo, TextureType, UniformBlock, ResolveMode, SampleCount, Color } from '../../gfx'; import { Mat4, Quat, toRadian, Vec2, Vec3, Vec4, assert, macro, cclegacy, IVec4Like, IMat4Like, IVec2Like, Color as CoreColor } from '../../core'; import { AccessType, AttachmentType, CopyPair, LightInfo, LightingMode, MovePair, QueueHint, ResolvePair, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; import { ComputeView, RasterView, Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedBuffer, ManagedResource, MovePass, RasterPass, RasterSubpass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData, Subpass } from './render-graph'; @@ -830,6 +830,39 @@ function getFirstChildLayoutName (lg: LayoutGraphData, parentID: number): string return ''; } +function getTextureType (dimension: ResourceDimension, arraySize: number): TextureType { + switch (dimension) { + case ResourceDimension.TEXTURE1D: + return arraySize > 1 ? TextureType.TEX1D_ARRAY : TextureType.TEX1D; + case ResourceDimension.TEXTURE2D: + return arraySize > 1 ? TextureType.TEX2D_ARRAY : TextureType.TEX2D; + case ResourceDimension.TEXTURE3D: + return TextureType.TEX3D; + case ResourceDimension.BUFFER: + return TextureType.TEX2D; + default: + break; + } + return TextureType.TEX2D; +} + +function getResourceDimension (type: TextureType): ResourceDimension { + switch (type) { + case TextureType.TEX1D: + case TextureType.TEX1D_ARRAY: + return ResourceDimension.TEXTURE1D; + case TextureType.TEX2D: + case TextureType.TEX2D_ARRAY: + case TextureType.CUBE: + return ResourceDimension.TEXTURE2D; + case TextureType.TEX3D: + return ResourceDimension.TEXTURE3D; + default: + break; + } + return ResourceDimension.TEXTURE2D; +} + export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuilder { constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, vertID: number, queue: RenderQueue, pipeline: PipelineSceneData) { super(data, layoutGraph); @@ -1477,16 +1510,47 @@ export class WebPipeline implements BasicPipeline { desc.width = width; desc.height = height; } - addResource (name: string, dimension: ResourceDimension, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount, flags: ResourceFlags, residency: ResourceResidency): number { + + public addBuffer (name: string, size: number, flags: ResourceFlags, residency: ResourceResidency): number { + const desc = new ResourceDesc(); + desc.dimension = ResourceDimension.BUFFER; + desc.width = size; + desc.flags = flags; + return this._resourceGraph.addVertex( + ResourceGraphValue.Managed, + new ManagedResource(), + name, + + desc, + new ResourceTraits(residency), + new ResourceStates(), + new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), + ); + } + + public updateBuffer (name: string, size: number): void { + this.updateResource(name, Format.UNKNOWN, size, 0, 0, 0, 0, SampleCount.X1); + } + + public addExternalTexture (name: string, texture: Texture, flags: ResourceFlags): number { + throw new Error('Method not implemented.'); + } + + public updateExternalTexture (name: string, texture: Texture): void { + throw new Error('Method not implemented.'); + } + + public addTexture (name: string, textureType: TextureType, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount, flags: ResourceFlags, residency: ResourceResidency): number { const desc = new ResourceDesc(); - desc.dimension = dimension; + desc.dimension = getResourceDimension(textureType); desc.width = width; desc.height = height; - desc.depthOrArraySize = dimension === ResourceDimension.TEXTURE3D ? depth : arraySize; + desc.depthOrArraySize = desc.dimension === ResourceDimension.TEXTURE3D ? depth : arraySize; desc.mipLevels = mipLevels; desc.format = format; desc.sampleCount = sampleCount; desc.flags = flags; + desc.viewType = textureType; return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), @@ -1498,7 +1562,19 @@ export class WebPipeline implements BasicPipeline { new SamplerInfo(Filter.LINEAR, Filter.LINEAR, Filter.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP), ); } - updateResource (name: string, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount): void { + + public updateTexture (name: string, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount): void { + this.updateResource(name, format, width, height, depth, arraySize, mipLevels, sampleCount); + } + + public addResource (name: string, dimension: ResourceDimension, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount, flags: ResourceFlags, residency: ResourceResidency): number { + if (dimension === ResourceDimension.BUFFER) { + return this.addBuffer(name, width, flags, residency); + } else { + return this.addTexture(name, getTextureType(dimension, arraySize), format, width, height, depth, arraySize, mipLevels, sampleCount, flags, residency); + } + } + public updateResource (name: string, format: Format, width: number, height: number, depth: number, arraySize: number, mipLevels: number, sampleCount: SampleCount): void { const resId = this.resourceGraph.vertex(name); const desc = this.resourceGraph.getDesc(resId); desc.width = width; diff --git a/native/cocos/core/assets/SimpleTexture.cpp b/native/cocos/core/assets/SimpleTexture.cpp index 145aae30126..74e0018b1fe 100644 --- a/native/cocos/core/assets/SimpleTexture.cpp +++ b/native/cocos/core/assets/SimpleTexture.cpp @@ -140,7 +140,7 @@ void SimpleTexture::createTexture(gfx::Device *device) { } auto textureCreateInfo = getGfxTextureCreateInfo( - gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_DST, + gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_DST | gfx::TextureUsageBit::COLOR_ATTACHMENT, getGFXFormat(), _mipmapLevel, flags); diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 60babdea94f..e6087402ac8 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -189,6 +189,9 @@ ResourceGraph::vertex_descriptor locateSubres(const ccstd::pmr::string& originNa const ResourceGraph &resg, uint32_t basePlane, boost::container::pmr::memory_resource *scratch) { + if (basePlane == 0xFFFFFFFF) { + return findVertex(originName, resg); + } const auto &resName = getSubresNameByPlane(originName, basePlane, resg, scratch); return findVertex(resName, resg); } @@ -909,7 +912,7 @@ void extractNames(const ccstd::pmr::string &resName, // cube // array - + if (names.empty()) { names.emplace_back(resName, 0); } @@ -1002,7 +1005,7 @@ bool checkComputeViews(const Graphs &graphs, ResourceAccessGraph::vertex_descrip tryAddEdge(lastVertId, ragVertID, resourceAccessGraph); tryAddEdge(lastVertId, ragVertID, relationGraph); dependent = lastVertId != EXPECT_START_ID; - + if (out_degree(resID, resourceGraph) && (computeView.plane != 0xFFFFFFFF)) { const auto& subresFullName = getSubresNameByPlane(resName, computeView.plane, resourceGraph, resourceAccessGraph.resource()); resourceAccessGraph.resourceIndex.emplace(subresFullName, vertex(subresFullName, resourceGraph)); @@ -1530,7 +1533,7 @@ gfx::SamplerInfo makePointSamplerInfo() { return gfx::SamplerInfo{gfx::Filter::POINT, gfx::Filter::POINT, gfx::Filter::POINT}; } -SubresourceView makeSubresourceView(const ResourceDesc& desc, const gfx::ResourceRange& range) { +SubresourceView makeSubresourceView(const ResourceDesc& srcDesc, const ResourceDesc &targetDesc, const gfx::ResourceRange& range) { SubresourceView view{}; view.firstArraySlice = range.firstSlice; view.numArraySlices = range.numSlices; @@ -1538,7 +1541,8 @@ SubresourceView makeSubresourceView(const ResourceDesc& desc, const gfx::Resourc view.numMipLevels = range.levelCount; view.firstPlane = range.basePlane; view.numPlanes = range.planeCount; - view.format = desc.format; + view.format = targetDesc.format; + view.viewType = srcDesc.viewType; view.textureView = nullptr; return view; } @@ -1652,7 +1656,10 @@ void subresourceAnalysis(ResourceAccessGraph& rag, ResourceGraph& resg) { } } else { for (const auto &[rangeStr, subres] : subreses) { + auto descResViewID = findVertex(subres, resg); auto targetResID = rag.resourceIndex.at(resName); + + const auto &srcDesc = get(ResourceGraph::DescTag{}, resg, descResViewID); const auto &targetName = get(ResourceGraph::NameTag{}, resg, targetResID); const auto &targetDesc = get(ResourceGraph::DescTag{}, resg, targetResID); const auto &srcResourceRange = rag.movedSourceStatus.at(subres).range; @@ -1660,7 +1667,7 @@ void subresourceAnalysis(ResourceAccessGraph& rag, ResourceGraph& resg) { const auto &indexName = concatResName(targetName, subres, rag.resource()); auto subresID = findVertex(indexName, resg); if (subresID == ResourceGraph::null_vertex()) { - const auto &subView = makeSubresourceView(targetDesc, srcResourceRange); + const auto &subView = makeSubresourceView(srcDesc, targetDesc, srcResourceRange); // register to resourcegraph subresID = addVertex( SubresourceViewTag{}, diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp index 1854385cd5c..74c230b1dba 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.cpp @@ -477,6 +477,35 @@ void printLayoutGraphData( } } +gfx::TextureType getTextureType(ResourceDimension dimension, uint32_t arraySize) { + switch (dimension) { + case ResourceDimension::TEXTURE1D: + return arraySize > 1 ? gfx::TextureType::TEX1D_ARRAY : gfx::TextureType::TEX1D; + case ResourceDimension::TEXTURE2D: + return arraySize > 1 ? gfx::TextureType::TEX2D_ARRAY : gfx::TextureType::TEX2D; + case ResourceDimension::TEXTURE3D: + return gfx::TextureType::TEX3D; + case ResourceDimension::BUFFER: + default: + return gfx::TextureType::TEX2D; + } +} + +ResourceDimension getResourceDimension(gfx::TextureType type) { + switch (type) { + case gfx::TextureType::TEX1D: + case gfx::TextureType::TEX1D_ARRAY: + return ResourceDimension::TEXTURE1D; + case gfx::TextureType::TEX3D: + return ResourceDimension::TEXTURE3D; + case gfx::TextureType::TEX2D: + case gfx::TextureType::TEX2D_ARRAY: + case gfx::TextureType::CUBE: + default: + return ResourceDimension::TEXTURE2D; + } +} + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h index 389fd95dbd7..acb5780ebe8 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h @@ -65,6 +65,10 @@ void printLayoutGraphData( const LayoutGraphData& lg, std::ostream& oss, boost::container::pmr::memory_resource* scratch); +gfx::TextureType getTextureType(ResourceDimension dimension, uint32_t arraySize); +ResourceDimension getResourceDimension(gfx::TextureType type); + + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index f747e151f36..7896ae83828 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -122,6 +122,47 @@ bool NativePipeline::containsResource(const ccstd::string &name) const { return contains(name.c_str(), resourceGraph); } +uint32_t NativePipeline::addExternalTexture(const ccstd::string &name, gfx::Texture *texture, ResourceFlags flags) { + const auto &texInfo = texture->getInfo(); + ResourceDesc desc{}; + desc.dimension = getResourceDimension(texInfo.type); + desc.width = texInfo.width; + desc.height = texInfo.height; + desc.depthOrArraySize = desc.dimension == ResourceDimension::TEXTURE3D ? texInfo.depth : texInfo.layerCount; + desc.mipLevels = texInfo.levelCount; + desc.format = texture->getFormat(); + desc.sampleCount = gfx::SampleCount::X1; + desc.textureFlags = texture->getInfo().flags; + desc.flags = flags; + desc.viewType = texInfo.type; + + return addVertex( + PersistentTextureTag{}, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(ResourceTraits{ResourceResidency::EXTERNAL}), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(texture), + resourceGraph); +} + +void NativePipeline::updateExternalTexture(const ccstd::string &name, gfx::Texture *texture) { + auto resID = findVertex(ccstd::pmr::string(name, get_allocator()), resourceGraph); + if (resID == ResourceGraph::null_vertex()) { + return; + } + auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + visitObject( + resID, resourceGraph, + [&](IntrusivePtr &tex) { + desc.width = texture->getWidth(); + desc.height = texture->getHeight(); + tex = texture; + }, + [](const auto & /*res*/) {}); +} + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) uint32_t NativePipeline::addRenderWindow(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, scene::RenderWindow *renderWindow) { ResourceDesc desc{}; @@ -253,10 +294,8 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format return resID; } -uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimension dimension, - gfx::Format format, - uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, - gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) { +uint32_t NativePipeline::addTexture(const ccstd::string &name, gfx::TextureType type, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) { + const auto dimension = getResourceDimension(type); ResourceDesc desc{ dimension, 0, @@ -268,6 +307,7 @@ uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimensio sampleCount, residency == ResourceResidency::MEMORYLESS ? gfx::TextureFlagBit::LAZILY_ALLOCATED : gfx::TextureFlagBit::NONE, flags, + type }; return addVertex( ManagedTextureTag{}, @@ -280,6 +320,38 @@ uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimensio resourceGraph); } +void NativePipeline::updateTexture(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) { + updateResource(name, format, width, height, depth, arraySize, mipLevels, sampleCount); +} + +uint32_t NativePipeline::addBuffer(const ccstd::string &name, uint32_t size, ResourceFlags flags, ResourceResidency residency) { + ResourceDesc desc = {}; + desc.dimension = ResourceDimension::BUFFER; + desc.width = size; + desc.flags = flags; + return addVertex( + ManagedBufferTag{}, + std::forward_as_tuple(name.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(ResourceTraits{residency}), + std::forward_as_tuple(), + std::forward_as_tuple(), + std::forward_as_tuple(), + resourceGraph); +} + +void NativePipeline::updateBuffer(const ccstd::string &name, uint32_t size) { + updateResource(name, gfx::Format::UNKNOWN, size, 0, 0, 0, 0, gfx::SampleCount::X1); +} + +uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimension dimension, + gfx::Format format, + uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, + gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) { + return dimension == ResourceDimension::BUFFER ? addBuffer(name, width, flags, residency) : + addTexture(name, getTextureType(dimension, arraySize), format, width, height, depth, arraySize, mipLevels, sampleCount, flags, residency); +} + void NativePipeline::updateResource(const ccstd::string& name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, // NOLINT(bugprone-easily-swappable-parameters) gfx::SampleCount sampleCount) { @@ -311,6 +383,9 @@ void NativePipeline::updateResource(const ccstd::string& name, gfx::Format forma resourceGraph.invalidatePersistentRenderPassAndFramebuffer(tex.texture.get()); } }, + [&](ManagedBuffer &/*buffer*/) { + desc.width = width; + }, [](const auto & /*res*/) {}); } diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index 1fdb0ebed7d..2f5704b28f8 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -1357,12 +1357,18 @@ class NativePipeline final : public Pipeline { void beginSetup() override; void endSetup() override; bool containsResource(const ccstd::string &name) const override; + uint32_t addExternalTexture(const ccstd::string &name, gfx::Texture *texture, ResourceFlags flags) override; + void updateExternalTexture(const ccstd::string &name, gfx::Texture *texture) override; uint32_t addRenderWindow(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, scene::RenderWindow *renderWindow) override; void updateRenderWindow(const ccstd::string &name, scene::RenderWindow *renderWindow) override; uint32_t addRenderTarget(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; uint32_t addDepthStencil(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, ResourceResidency residency) override; void updateRenderTarget(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) override; + uint32_t addTexture(const ccstd::string &name, gfx::TextureType type, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) override; + void updateTexture(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) override; + uint32_t addBuffer(const ccstd::string &name, uint32_t size, ResourceFlags flags, ResourceResidency residency) override; + void updateBuffer(const ccstd::string &name, uint32_t size) override; uint32_t addResource(const ccstd::string &name, ResourceDimension dimension, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) override; void updateResource(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) override; void beginFrame() override; diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 1086f449745..750616d549a 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -97,35 +97,8 @@ gfx::BufferInfo getBufferInfo(const ResourceDesc& desc) { }; } -gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { +gfx::TextureInfo getTextureInfo(const ResourceDesc& desc) { using namespace gfx; // NOLINT(google-build-using-namespace) - // type - auto type = TextureType::TEX1D; - switch (desc.dimension) { - case ResourceDimension::TEXTURE1D: - if (desc.depthOrArraySize > 1) { - type = TextureType::TEX1D_ARRAY; - } else { - type = TextureType::TEX1D; - } - break; - case ResourceDimension::TEXTURE2D: - if (desc.depthOrArraySize > 1) { - if (bCube) { - type = TextureType::CUBE; - } else { - type = TextureType::TEX2D_ARRAY; - } - } else { - type = TextureType::TEX2D; - } - break; - case ResourceDimension::TEXTURE3D: - type = TextureType::TEX3D; - break; - case ResourceDimension::BUFFER: - CC_EXPECTS(false); - } // usage TextureUsage usage = TextureUsage::NONE; @@ -156,28 +129,26 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { } return { - type, + desc.viewType, usage, desc.format, desc.width, desc.height, desc.textureFlags, - type == TextureType::TEX3D ? 1U : desc.depthOrArraySize, + desc.viewType == TextureType::TEX3D ? 1U : desc.depthOrArraySize, desc.mipLevels, desc.sampleCount, - type == TextureType::TEX3D ? desc.depthOrArraySize : 1U, + desc.viewType == TextureType::TEX3D ? desc.depthOrArraySize : 1U, nullptr, }; } -gfx::TextureViewInfo getTextureViewInfo(const SubresourceView& subresView, const ResourceDesc& desc, bool bCube = false) { +gfx::TextureViewInfo getTextureViewInfo(const SubresourceView& subresView) { using namespace gfx; // NOLINT(google-build-using-namespace) - const auto& textureInfo = getTextureInfo(desc, bCube); - return { nullptr, - textureInfo.type, + subresView.viewType, subresView.format, subresView.indexOrFirstMipLevel, subresView.numMipLevels, @@ -280,9 +251,8 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { CC_ENSURES(!resg.isTextureView(parentID)); mount(device, parentID); // NOLINT(misc-no-recursion) auto* parentTexture = resg.getTexture(parentID); - const auto& desc = get(ResourceGraph::DescTag{}, resg, vertID); if (!view.textureView) { - auto textureViewInfo = getTextureViewInfo(originView, desc); + auto textureViewInfo = getTextureViewInfo(originView); textureViewInfo.texture = parentTexture; view.textureView = device->createTexture(textureViewInfo); } diff --git a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h index acf43826fd8..75abe2d1bf1 100644 --- a/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderGraphTypes.h @@ -169,6 +169,7 @@ struct ResourceDesc { gfx::SampleCount sampleCount{gfx::SampleCount::X1}; gfx::TextureFlagBit textureFlags{gfx::TextureFlagBit::NONE}; ResourceFlags flags{ResourceFlags::NONE}; + gfx::TextureType viewType{gfx::TextureType::TEX2D}; }; struct ResourceTraits { @@ -515,6 +516,7 @@ struct SubresourceView { uint16_t numArraySlices{0}; uint16_t firstPlane{0}; uint16_t numPlanes{0}; + gfx::TextureType viewType; }; struct ResourceGraph { diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index 77845fd5c64..29e13290601 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -773,6 +773,12 @@ class BasicPipeline : public PipelineRuntime { virtual void updateDepthStencil(const ccstd::string &name, uint32_t width, uint32_t height, gfx::Format format) = 0; virtual uint32_t addResource(const ccstd::string &name, ResourceDimension dimension, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) = 0; virtual void updateResource(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) = 0; + virtual uint32_t addTexture(const ccstd::string &name, gfx::TextureType type, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount, ResourceFlags flags, ResourceResidency residency) = 0; + virtual void updateTexture(const ccstd::string &name, gfx::Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, gfx::SampleCount sampleCount) = 0; + virtual uint32_t addBuffer(const ccstd::string &name, uint32_t size, ResourceFlags flags, ResourceResidency residency) = 0; + virtual void updateBuffer(const ccstd::string &name, uint32_t size) = 0; + virtual uint32_t addExternalTexture(const ccstd::string &name, gfx::Texture *texture, ResourceFlags flags) = 0; + virtual void updateExternalTexture(const ccstd::string &name, gfx::Texture *texture) = 0; /** * @engineInternal * @en Begin rendering one frame From d988b2373a4935535c5891cac74c96f57ed4db96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 17 Aug 2023 16:16:15 +0800 Subject: [PATCH 171/232] Fix: Inactivated skeletal animation components shall not affect skinned mesh renderers (#13779) --- .../skinned-mesh-renderer.ts | 2 +- tests/animation/skeletal-animation.test.ts | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts index 84cd794e0a2..c59dfa62b93 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts @@ -173,7 +173,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { } const animation = skinningRoot.getComponent('cc.SkeletalAnimation') as SkeletalAnimation; - if (animation) { + if (animation && animation.enabledInHierarchy) { animation.notifySkinnedMeshAdded(this); } else { this.setUseBakedAnimation(false); diff --git a/tests/animation/skeletal-animation.test.ts b/tests/animation/skeletal-animation.test.ts index 4c7605be10e..a73c9cac0ed 100644 --- a/tests/animation/skeletal-animation.test.ts +++ b/tests/animation/skeletal-animation.test.ts @@ -224,6 +224,26 @@ describe('Skeletal animation component', () => { expect(state.isPlaying && !state.isPaused).toBe(true); }); + test('Bugfix - Inactivated skeletal animation components shall not affect skinned mesh renderers', () => { + const node = new Node(); + const skeletalAnimation = node.addComponent(SkeletalAnimation) as SkeletalAnimation; + skeletalAnimation.enabled = false; + const skinnedMeshRenderer = node.addComponent(SkinnedMeshRenderer) as SkinnedMeshRenderer; + skinnedMeshRenderer.skinningRoot = node; + + const scene = new Scene(''); + scene.addChild(node); + + director.runSceneImmediate(scene); + // The skinned mesh renderer shall not being in baked mode. + expect(skinnedMeshRenderer.model).not.toBeInstanceOf(BakedSkinningModel); + + // While skeletal animation is activated, the skinned mesh renderer should be turned into baked mode. + skeletalAnimation.enabled = true; + director.tick(0.2); + expect(skinnedMeshRenderer.model).toBeInstanceOf(BakedSkinningModel); + }); + describe(`useBakedAnimation`, () => { test.each([ [true], From 7401b55e09cd99ddfcd65fb5bca165df04d6cdc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 17 Aug 2023 16:19:29 +0800 Subject: [PATCH 172/232] add java_home (#15996) --- .../native-pack-tool/source/base/default.ts | 12 +++++----- .../source/platforms/android.ts | 22 +++++++++++++++---- .../source/platforms/openharmony.ts | 4 +++- scripts/native-pack-tool/source/utils.ts | 2 +- 4 files changed, 28 insertions(+), 12 deletions(-) diff --git a/scripts/native-pack-tool/source/base/default.ts b/scripts/native-pack-tool/source/base/default.ts index 3f9899653dc..b7e5a994980 100644 --- a/scripts/native-pack-tool/source/base/default.ts +++ b/scripts/native-pack-tool/source/base/default.ts @@ -370,7 +370,7 @@ export abstract class NativePackTool { protected getExcutableNameOrDefault(): string { const en = this.params.executableName; - return en ? en : this.projectNameASCII(); + return en ? en : this.projectNameASCII(); } protected async excuteTemplateTask(tasks: CocosProjectTasks) { @@ -422,7 +422,7 @@ export abstract class NativePackTool { replaceFilesDelay[fp] = replaceFilesDelay[fp] || []; replaceFilesDelay[fp].push({ reg: name, - content: this.params.platformParams.packageName!, + content: (this.params.platformParams as any).packageName!, }); }); delete tasks.projectReplacePackageName; @@ -454,7 +454,7 @@ export abstract class NativePackTool { } }); Object.keys(config).forEach((key: string) => { - if(typeof config[key] !== 'string') { + if (typeof config[key] !== 'string') { console.error(`cMakeConfig.${key} is not a string, "${config[key]}"`); } else { content += config[key] + '\n'; @@ -468,7 +468,7 @@ export abstract class NativePackTool { args.push(`-DRES_DIR="${cchelper.fixPath(this.paths.buildDir)}"`); args.push(`-DAPP_NAME="${this.params.projectName}"`); args.push(`-DLAUNCH_TYPE="${this.buildType}"`); - if (this.params.platformParams?.skipUpdateXcodeProject) { + if ((this.params.platformParams as any).skipUpdateXcodeProject) { args.push(`-DCMAKE_SUPPRESS_REGENERATION=ON`); } } @@ -543,7 +543,7 @@ export abstract class NativePackTool { // cocos.compile.json export class CocosParams { - platformParams!: T | any; + platformParams: T; public debug: boolean; public projectName: string; public cmakePath: string; @@ -602,7 +602,7 @@ export class CocosParams { CC_ENABLE_SWAPPY: false, } - constructor(params: CocosParams) { + constructor(params: CocosParams) { this.buildAssetsDir = params.buildAssetsDir; this.projectName = params.projectName; this.debug = params.debug; diff --git a/scripts/native-pack-tool/source/platforms/android.ts b/scripts/native-pack-tool/source/platforms/android.ts index 212974a8ae1..6cb7d8f1260 100644 --- a/scripts/native-pack-tool/source/platforms/android.ts +++ b/scripts/native-pack-tool/source/platforms/android.ts @@ -5,6 +5,7 @@ import { cchelper, Paths } from "../utils"; import * as URL from 'url'; import { spawn, spawnSync } from 'child_process'; import * as xml2js from 'xml2js'; +import { platform } from 'os'; export interface IOrientation { landscapeLeft: boolean; @@ -17,7 +18,10 @@ export interface IAndroidParams { packageName: string; sdkPath: string; ndkPath: string; + javaHome: string; + javaPath: string; androidInstant: boolean, + maxAspectRatio: string; remoteUrl?: string; apiLevel: number; appABIs: string[]; @@ -25,6 +29,7 @@ export interface IAndroidParams { keystoreAlias: string; keystoreAliasPassword: string; keystorePath: string; + inputSDK: boolean; orientation: IOrientation; appBundle: boolean; @@ -77,6 +82,18 @@ export class AndroidPackTool extends NativePackTool { async make() { const options = this.params.platformParams; + if (options.javaHome) { + if (process.env.JAVA_HOME !== options.javaHome) { + process.env.JAVA_HOME = options.javaHome; + console.log(`Update JAVA_HOME to ${options.javaHome}`); + } + if (!process.env.PATH!.startsWith(options.javaHome)) { + const sep = platform() === 'win32' ? ';' : ':'; + process.env.PATH = ps.join(options.javaHome, 'bin') + sep + process.env.PATH; + console.log(`Add JAVA_HOME/bin to PATH`); + } + } + const projDir: string = this.paths.nativePrjDir; if (!fs.existsSync(projDir)) { throw new Error(`dir ${projDir} not exits`); @@ -93,7 +110,6 @@ export class AndroidPackTool extends NativePackTool { // compile android buildMode = `${this.projectNameASCII()}:assemble${outputMode}`; - // await cchelper.runCmd(gradle, [buildMode /* "--quiet",*/ /*"--build-cache", "--project-cache-dir", nativePrjDir */], false, projDir); // pushd const originDir = process.cwd(); @@ -111,7 +127,6 @@ export class AndroidPackTool extends NativePackTool { // compile android-instant if (options.androidInstant) { buildMode = `instantapp:assemble${outputMode}`; - // await cchelper.runCmd(gradle, [buildMode, /*"--quiet",*/ /*"--build-cache", "--project-cache-dir", nativePrjDir*/], false, projDir); await cchelper.runCmd(gradle, [buildMode], false, projDir); } @@ -122,7 +137,6 @@ export class AndroidPackTool extends NativePackTool { } else { buildMode = `${this.params.projectName}:bundle${outputMode}`; } - // await cchelper.runCmd(gradle, [buildMode, /*"--quiet",*/ /*"--build-cache", "--project-cache-dir", nativePrjDir*/], false, projDir); await cchelper.runCmd(gradle, [buildMode], false, projDir); } return await this.copyToDist(); @@ -214,7 +228,7 @@ export class AndroidPackTool extends NativePackTool { const application = data.manifest.application[0]; //append meta-data application['meta-data'].push({ - $:{'android:name': 'android.max_aspect', 'android:value': `${aspectRatioFloatValue}`} + $: { 'android:name': 'android.max_aspect', 'android:value': `${aspectRatioFloatValue}` } }); } diff --git a/scripts/native-pack-tool/source/platforms/openharmony.ts b/scripts/native-pack-tool/source/platforms/openharmony.ts index b7a18fa9d15..45af3334f3a 100644 --- a/scripts/native-pack-tool/source/platforms/openharmony.ts +++ b/scripts/native-pack-tool/source/platforms/openharmony.ts @@ -20,6 +20,8 @@ export interface OHOSParam { ndkPath: string; orientation: IOrientation; packageName: string; + appABIs: string[]; + apiLevel: number; } export class OpenHarmonyPackTool extends NativePackTool { @@ -143,7 +145,7 @@ export class OpenHarmonyPackTool extends NativePackTool { hdcExe, ['uninstall', packageName], false, hdcCwd); console.debug(`${hdc} install -r ${hapFile}`); await cchelper.runCmd( - hdcExe,['install', '-r', hapFile], false, hdcCwd); + hdcExe, ['install', '-r', hapFile], false, hdcCwd); console.debug(`${hdc} shell aa start -a ${ability} -b ${packageName}`); await cchelper.runCmd( hdcExe, ['shell', 'aa', 'start', '-a', ability, '-b', packageName, '-m', moduleName], false, hdcCwd); diff --git a/scripts/native-pack-tool/source/utils.ts b/scripts/native-pack-tool/source/utils.ts index 67eeb88a4dc..b6559cbd19a 100644 --- a/scripts/native-pack-tool/source/utils.ts +++ b/scripts/native-pack-tool/source/utils.ts @@ -557,7 +557,7 @@ export class Paths { this.buildDir = params.buildDir; this.buildAssetsDir = params.buildAssetsDir; if (params.platform === 'windows') { - this.platformTemplateDirName = params.platformParams.targetPlatform === "win32" ? "win32" : "win64"; + this.platformTemplateDirName = (params.platformParams as any).targetPlatform === "win32" ? "win32" : "win64"; } else { this.platformTemplateDirName = params.platformName ? params.platformName : this.platform; } From 310142ea016bc874d8a955929e3601d5709ba99e Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Thu, 17 Aug 2023 16:42:36 +0800 Subject: [PATCH 173/232] [ci skip][AUTO]: Automated code generating update: 9a8c159ac0a52aeaafcf6460a0ea2bc0d9a6b2eb (#15946) (#16002) Co-authored-by: cocos-robot --- native/cocos/core/builtin/DebugInfos.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/native/cocos/core/builtin/DebugInfos.cpp b/native/cocos/core/builtin/DebugInfos.cpp index bb0597c5234..8571eefcfa6 100644 --- a/native/cocos/core/builtin/DebugInfos.cpp +++ b/native/cocos/core/builtin/DebugInfos.cpp @@ -445,6 +445,7 @@ ccstd::unordered_map debugInfos = { { 12009, "GeometryRenderer: too many triangles." }, { 12010, "PassUtils: illegal uniform handle, accessing uniform at offset %d" }, { 12011, "Pass: setUniform is invoked with incompatible uniform data type for binding %d, expected type is %s" }, +{ 12012, "Can't set a material instance to a sharedMaterial slot" }, { 12100, "The font size is too big to be fitted into texture atlas. Please switch to other label cache modes or choose a smaller font size." }, { 12101, "The asset %s has been destroyed!" }, { 12102, "Base pass cannot override states, please use pass instance instead." }, From 4e1ddee39bf29196ce3614a3914bffae28d56d03 Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Thu, 17 Aug 2023 17:15:29 +0800 Subject: [PATCH 174/232] [ci skip][AUTO]: Automated code generating update: dec20a47dcf2f1929010ba90c4fec99ded4de3e1 (#15996) (#16007) Co-authored-by: cocos-robot From 52cb79d9eb8d0ba26d62c4530d990202efd9a82c Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Thu, 17 Aug 2023 17:27:53 +0800 Subject: [PATCH 175/232] [fix] update primitives.fbx: sphere bbx now centerd at zero. #15300 (#15952) --- editor/assets/primitives.fbx | Bin 242784 -> 213184 bytes editor/assets/primitives.fbx.meta | 73 ++++++++++++++++++------------ 2 files changed, 45 insertions(+), 28 deletions(-) diff --git a/editor/assets/primitives.fbx b/editor/assets/primitives.fbx index 1ddad73bd082bda2cf04aee3b1cf8516e996080e..f93a097616a8ad8a93a4c72736061aaa7b8fd4b9 100755 GIT binary patch delta 99634 zcmZ^~2~<1PDoh7(xgq>Dy zVE@NY(|>cEJj-p;q`E1{{F!quc>3E6UWjqG9(q0rxn?ux!lR!i%j_mi3b8@neBwBD z2Q@nW@YateO`60+ez$R)YP;z>+E#n;lVgKCfE|%bHp^^0kUwk|PWA!^XW+0$AQqeH zxT!Ya1P&V)ss(^#0GJuMx%vo;J&o`yb3ghCjAjcdEQ2;%Ya78~ckZGpWG z{(mkBMJ|0DV1xhrk`FLbU7WHLIEpl7;ioH$mrDdopVU3B7Oc4IF+K)OMShv$G23(H zYVVb6*3Db9eqyPm+3oj9D9Vj+zA<+ z?q!SGPZ*DA57`DgOv;>}Z|jm-bk}w|a>ssyO$qYW{u>)DveAKv^PX{Wo-10c;eG7`)GjaOSMTNmu@J{~wOPUQWnN$2GXcpCN8eu9?)UwjUvpjzpWY zi2Y}7$aBZdHbY<(j@#vgymWO%e*0{b&1IzJvp^dY;_CDR?)$mmwq?jYCtuv{xfh+6 zA)m~3#tmCXk!M_2zO=6aD*hgS&MR?s#z0(}sy~-FE|65mU$peOBdVJSVxPNEym4Rj%-^-!hO9Q$zJxkO*YcCEWk#D%wO({ z1D9eMeqy;7E*Tr{vMIah;b)`0=;4M8db{C5SAazxvK6eb`fGD$NGgaqp~t5<{7U4L zbxxV{*tQ;-ud{3?BkUEkaFHvq7|r~VZA-9y2h}0(R@}kqRwK;SOQr-Kq(&W#kEI=6 zg@yQJjApx6gES#b-f=MQaLwv};@p++cb?cJUnDFS?{0Dl;(3AnG;Skngp!lWETxSELj#p|EP8rE15XvdnhIKQ>XPir8M z8c)^)<9gRx)5>e@8XE|4@N~m4Z2>~^oQ!bS&a(LxIqK<#NY<{f=>sRf!L42gAaW}% zb)9vNLeI}_l*o*A6rA^Z@bqmqnFw!P7*4hx^Jiv3fvx8UlP2xl0Aj-lIlX>6E^h-! z6<0*PegkfX7qV9Kc0xEoS!-XI&jd~vh9F$A$K^O=|Ko*gjyR;!2agl_{%snYl8e53aC+a101G31SJ-|{u*swxw!u&SefrTHM_lIT zUbb`LfZf2T;GfOJpGox?CW3z-?LQbBefBm&Y4gmXA0S>9|xkCxgN zneRkRq^IA zN1|GCOPra;;l~J3+IH7Js#Jfs_9ghCZC?_@`4^LjNv5<@|sw0&?d=HCZQBkRvejhVz2e;dp zZ#qiX-Xif~a#Mj9^O@$ZK8#A2rKZGHI#F8;gt)M4iQPVZnfev2BH~%)&< zC4`8odsJ&Jc%tPFEUZY9rnfK z8Hf5wEGbn$D@bBP`m-g&)ufGn23^%yl^h?(&Aaw z|59*}|C)_9tG21nLHZW;bV_~7Ey^p-yK`P#i4rpI)Kc{|40}AQ(tNWNMz zG;kQhryP2`x2a%B~n2KSI@pyWnXB zaGB=G84CJmC`Ud1U-S2qo&{Ewe#{;EI+JW+T3+k43*A<6jNY(O5@#y?D$Uul+#Kf1 zlDCwe=t8MP6QATpkI=>+3{CNhNg5>4H#zVec^ z>KOA{VyC*eTRkdXZYd+4fL=Hb$4xQ?{I}^t7{K!RLYOfQqR3S9v=70{U^azO1V8)f zpIK*8I@NC-6OH3F2mwTzCl)w2UpaO%B#!wMS8;VuCTm=-!Q;)2nw2r*u5?{WD(d1d z7-bWUX(DD(5{mvbNWeplVPcb~B|9cs$QUsMSH^KTk)cfSt4N-!&cb6!%DRIEWttpi z7yOoKcJFq9(2|sI2rRfJ0!;WUqCWN^>RP2lYieYUUY2p!Dhg$=R_jQ87shG!r|c)X|Ow4X;JCI%M2guvQFwW0%2eonr>95h-CS)l1EWp@U!CCQr%q;fnf}t zWwb$Mv>!ItYro1ShN%booLQB*5KAu8N4S)!xf0czm9TML168PGeZRhY0L}11|9o%q zzW*}$f%=r=tQw~wmbq3dOMIu%1tw~I)Tpc8LLc@hUUf8?MJ3cKr4-A}l2xbqD!f2A zq}(Q$Yf<}Dh}k_vQY(6`i_&w1+VYNOhu6(C>1@k10&#v%IC1s>-0@lM{vXBk4sU-! z**FNlcd3ybY$X8;>G46T$JZS_ad$1P@1C58XTyZ9I+C|QTT(;Xm`woyg@PDijAfOe zL7Kj=9sOBDM``0Nw@AiOZlSyyq$Y2Zu`yDU`u=Gxc)n#gA{xYXKB;2zj=y0lcTc&yJF~_Npe>x+YO(fFgJA{{mt9Ih$V549tD4kM%AwVJJ|(Z zJnfH7(%E;TMq83t8+RGDvI{(T-roL1MZ5B;JGh`=Tmddne8nBg2n&YjF){RP0-X;Y zT_$h&Fuyi1l%T=qbGWc$@KCl?)e=_YAVY}6h*iWQ`_VfA;8jG0Z@pz8M*rw(%RXau zjt};3C(^_m?rZ~phpWD#>=vb*;NPsBnO_rEb!)t5RKl*))iNHc1(8oE>(uoxOPUp3$U?!Lqa~FeG5|R=LPfQ<}iYZ&uUI+$*9oX}x=N z_h*D$b@Xgf&O0yzTax9t^cg}hx`=z+r4CT(NpfWl6`h@uO95FO!y2!7JOmQNA(O;1 zj>`0}YZDUj39T^qNueZ#Yy3syL2d6bO62$kLN22xUtDbNY2C=Y_LA8Q7lQ1V8L=M! zCpw#wMG1jfG3Y%YSv3fxYJi(9Y7SeS-FYRzDGPa*~ z&NeaRysei*LySvI18x74_7m^u$p;)u=`8NQEXARO@S9XUf&S=CK^QkiN~sZhJjVh_ za>KO&CghsI%+hpn-MxrWS%tR}-@x_m?^BF#5nOfXG5(rYPbh)}WsDJNz92mGvPGwq z$Tv!*tk6+G!Kj5g^k0+uvQ!|v!Q1!L`*>}O_i@d)a|2W38j5$j1xvMK4_BpCjT$c% z$pNCsQYaxEtPogz9PNc`g|vS98)kPX!QRR|ABLhI%SyY`^eLLue1P15!bq$@(^FwW zOf@0CJZv;ZYxtu@y(7DY@e$in)p|k-)`wZG0bCFyY+NreG=-bR+|*3AMcg-1UYWhV zXjMe_$pWcd^H#x1Q@%|@V$O~0bU`b*wBu>8^o(bH@!W4pPKvT#R+P19wh@SeGTJjj zQ4~}pNGfCGi=VRTBimq@=dDdXYlS=DDro39E2fqW=>0lm%GFMTL^V&QhPKue64gzr zx$t`Yb!leUdv}6~1q;7=BdWn1D!G|Y63@Y>Dr-8P0*@Nt*JZxBM2Di`XF>C?5{C-s zKKp57(X*ej?0_pI*_wOlwXG6ShjnJb6}KEYlx#dJCdy!?k1S(JmEu4}f2Nrg>O#Z- zg4^H$^%z?_f-J{@{BV#tlKAglP*cNmbCi-Zlt!6c^G(Nj5OBIr3$5zoaS7~fF-r8B z)R(n{qTH5fR=q`8k(8t#J)eAbj#9FtN3pgqD#X>DbH2c^uIQPoyY%+!Kx3t{=1Kj@ zBQ86j`r;{XN}egZ5<)u%(3PQ5i6%8G!YFAUlj>7bUV5QXw3g!d)|wuTnRs+S_bGQG z8-l69*^dBvxk4;h-J8l9Ngf~6ZEmVKTy;Z~5R*qTRu>e;sL7h|2%iW>+rj*>XBDPi zO1w&{=b~`wDmOR&yY49^UpsCVR&1v^lWSi@NEOj8(_7h(O6lwEJ7d<{1J7`ty*aT% zbFNuwo!#O&|6{yLeNO+Cgg0=-iXzAJR`&fhgL9mvjOu9YR=Nu8{ILLZr;PWO4y_g5 zO1SnCdkDEUkx+A#_=_f(+HosKJ)G0G8DEW0n%{hJ;R|!kD2noFZ0e*3BDGCDlfMbfV zM*F?T1&pZL#N1MV`#}_z`cWQmE9T$csT^Y({WM8=UHv6yHmf=)?cU%IO*jBJ6&P(H z%VO9iPfK_svm}I8?bT6(fn%@7BwQKUP?UxU;b$#f-pk{qN8H&lZ-HcVDWiQG_O{8- zqq$^`pxa;2;s8t{9W_dTXEjg%$%+vvBItLdgb=R67@ibp-V@W-|01T5jS44XVd}G~ zp`scr=q6CEu++(-n33wmw@G~tW^Jmuv17_MHG0yUo!|4cZj8r;|)kFD#J$g zqneK8=3I4}vgR6@!s^?xk^WC!G*NXl9STd{F6P}!4K^vpmkl zSE)tgcwxu1h8{ij!79D(n>n!HOcJUSZ_wRiDx)NF|ATc z-u5pRi2ijgm?+?MAK|^!VNGj zhGuKoz;aK?n)!ZaEO!CWnb4ZPjiQ<;|7{{;v_u?AD2a#^e;?`+653E@N3Ly>J!vty zh@OB{eJ;i$B9IE5eya)Zj^yrB9Sh8+#~pCA%a>(_y=N^Ty(efZ#2>9usq*N|;UY&n zGB<<6`&r|``kS?elQ=9PeG6QadeX51n9Cn5tN{IOd_rGSm$gST;CXC}lH$aHi6P0)!oPH+~* zF`q?HFK3NgIV;~4aOnS1R?;;LAGv8%$-VvnZ-MbJkUalR$=66+3lT)Afm%xnwGR;2 ze_N^x_EtQ9JZ_Etw1Swo{ZD+-7B=_@mw(-1A4Vl8CHsY{_5X$!NU21g8Rgt59S_8~%ghvc@w$b5QBDLlD0 zj9yDM=N@a)sm|Y>$!u?f_^Q8{w_J-@+Of~bEl{U!9;)N*O1SAokg38;%qBxeKY^*p zFx{yQ<4V}7$ERI`Va*;Y&+U=HvDSFwX^UYlg(r`&1g{+(=i@gjc(;Z3$ebWm5q?N+ zC@!Q>g9RDo=i_>__$kgjRoloms-Mx`!ZhEu4D+04)!*~b}ZNggo7!CQFwdN0#;b5CA(C>7@2DIIUkqLW4YIp^GC`c)gLM|7%< z1&P=4a!tBRdEE-Jz;3AOD~^cAdL?Fe-_5B=;kJ^KB(e-xoRwyI=4g)aw-jgs;=zAO z3XZ6~Jt?qKAxIfh`{M6-nVx$w3CRUHBX_)b>USP|G;imq;-=eZUKp=?l+X2*z~0cP zDp7;T+>f;!VY$`ho{;6*t%0cX^>>9`n$PE|gaKI`*^FUyZmxJ9Uv^+ocbIRdhR`qD zwy43I(rh?3+UhPisnfn7tTG!J=L#k2rvzS!smv^y&QEgtkHi6fY;L^8Q9^N6oVL`F zq)nR7KNYIqlDkLQtbH)&U6065E=xga^Md8C+*vhV0&=YvAm91fl$b{VsY%R6>Tysp zA0c|>Xz<+}yYE9~s84WB7Kf6~DwEl%PbPQoLJ!NPS1B~xCA4mbVcM29sFq~8rSlUG z*Q#?lfwQ{Gih7w*l1h7ZYLg~4RY)Kjw+q?r%Z2Y?$RAn`q+s<05-S^Gsmsl0Q!zHq zHBJRe=2vObyVQ*=qvS=Vw^345tkL9^G=f%0nD#6usSF^{4A*}ILM@>IFDR1*w&KHA?M3ZZ7@l|F=^6vVgB?) z^H){8c4Jw0GSP!bbWh*lJRJ9-0F;R1XCQxWLP63~wrt;ADz$^q03LL9A;%aXNFqj! z#+jOOwaJfDC@eZ}KkGVPdy8NJR^*s>K>nN)9$ntuU8>hQAycC{l84tEp%bIvGT|ox z6GSXwrmGt5(MbRpm{KTo01qjA1E`m~HAk5IJ3S z!{!W1r;OJNmm7Q3j)D!Hs-lXS)N*|6Wr+tE6-q zFI!A$g?ccJFl~V}Yg~F>)xpl#UVCkD{5(WxlCx)jbz=rQwf0p75YrI4!XBK;{b z{ozKfU*naH6u4I-dKF5Ev-rg6^4g#{j`&k*KTCYU=!qAIS8$n;W)m@8+@5%@03uw( zYE95Vg1F8y@kIT!L{RSl8ykgMnDhlEDE4GxBDN;RZ@i{SAU6miesZUziY=zOoyMgC z&I`tqdUsX~#!1E&##@N{*wwYRR0s}X#00ugY>KhRo&PRbV1d70ed(N}_(f2zv(4?| z!%;P#;96ko{vq4jb~diQ-a4k1;y%MI|Is?0;cN48=6#~=2e|D&g3k)(*|LAMw)#J} zeTfZxY<)fndo|Hp|GU>7hkWMGADOrB4?CU#a4{(c9 zX5BtV*!yv0>5ADGKRL1WNB;{hSJ;n@C4qWW0O39*il$|28! zp4*v5_K-ssHjFAH`G)3)_n<<|CSZm8@RGITfj0&(=p$F|M!W z62H&x)P{qV_cByLVnPec;pV0L+=fp*?e@v0e#>BRDZB#!VAP^Gp4DHlXr) z;fMf|ousk;aF6|+8o*F+&WYoU$s@&o>8~^~FLIWq=;v1lniBR~j=>2>1TRSGd49h$ zLu8j;0gG3{!#%}{*6(!%m8M@M?$58WK2mRmx_1FLu=Ej^(6iPVHwwjM5UY3!6lAXr zI78B_ukNNASwp-18=36b+uSc1jY7%_?XBdi{uKVMv^*C@$_&mZufBG`pd`O!Z1(xf z0ehF|ReATc{)oh`=_tCHc=n`e##;ntF~&vxrXlTd`Yj%Q^7|_x@GzaBg*j9Zn>J-) z3LfOcPzx&iy7n#NjTuE@qV4O$TPJwkn5We0Z!t2snR>qxbK-tZ2Kj}a6$(XNh=aY z?0w+e0nKPDS*|l(;hH>!P$cmVC(rLU?$hB)T~tLX6}|tgRu*bAEMknA3zfk?c`6cuVfMC9<%t*V_#qHr`vc6_rcj>cf`53mR!{XB*nJV%rx9F>{ zaJu$HzX0c~mS{r0;;9Xf|N1-JGas==^p8>bZrfmGpWiN(+brp2E_8^}DCVHrQFyUBU?B*fxZtSs9XV`S5^SE)T$ptaLdpyZI-gQnI8&5JKrh|HQ;ty*X{fn< zX~ca4@iVbu0}PyD3B+5z9y`LS@M`0Dog_(?I-HTRsz9_is={Infz@ri+pmQ0CMR2L zIMov-El%E>sUuT0#fmlnONt zXUnFmIxq|_#0w~O(8$cbr76u5HU)l`3a7qD!=GUQDN6y^3E3m;zf&l~<0w=IwK-rj zVS6W-Ke0n^l+v3Hm=3JS-{R9u4l-X5Ucw?x?x;h?g84-l)LKKaJB8uz0iq;5fH_-| zN9>!KBNl1C)quAPe@KH!d;A+8#J-%1MfL$oA7>>Wtt~L$0_=*mQt*YHhN8$vx+Q&=@~UB{uy5g=#$OsE zz6!w4#%sB(AI!vSXmBAxEA{HCIt5%u)6&NH^^+LQaDM`4MnnYbw0kC0`)h2v-P+pL zYr3e(04(T+JdNhNa-~1bf0*?&cHeK-#AC7ep_%o<%V`OMKV1fZKlJX!+BQI(VPgYO zCTDf6ViO#pi`=SQ763OU zByv`14~=S%2?>BG`)t%Enu6&J?pK~SJV*dE2>oEkXk_oF(hH!W~EJz}Jy z00_`lPb)Gu3>y3~*Y`Qa7+Ewie0uzLDP5|hSYb|)0x%}xC5CFF3Fa59pC|AtjM^y} zD>we)^BTBQOG<|o=w9;$4hF){?ZCCham|;gyJ0@(k0*cA`8I&J08T+*K2IUCV^4Lb z01lU>FmNgQRW(6-c8lcNtb0g~4k=p`~T$j^l!=y?FhnmbsE zPIe(i8yo6Y(sI8c4y15OR0ebdtP+NdiT8r2G=Xdw4Eq-Hk~NLR{aDcg)>S8K6BE~c2X39pWf<&B|16+0!# zp=#gzB0<4mWf!;Iw4*l5dp|ix0H6UsTDkEn{9iISVyh1PH!z*!1pBvKFX_iy1`HybtfM?|Q?->dDKZUO_$WQ6e( zNs`1iF$a6Gz*Bi3csliy1f;fJWxU1Of~y}d@xHi*fnyU=lb zll^Ga84@%1h2Aq&8*vGaU24QKAxjk)nMLjFwmjB#&h!VrS*HTG6d~{#e|pNftvq#BueDaX!G+^a6&F>1KR)m;AqTFNz0}j*6ms5}eg!e|Ga#~Q+jI{@sC;A1 zU_NY!gR(>p=pyTKO~|k+j24;8R_+wO$4Wj)8OZ8C1e<^gnk{KA-&_l7^#(=#=&Off z1EtjT;on%BFKFbe{v0Mp)B=t7WB*g7@G$7;H#z{uPG+6ILA49YRTTg_QdIQjVdvW@5mAXYK9uDsKn)nivjABHOe8SDuzSAkk0 zZDtCFMKkgnpkQwnp6O2*V=Ta`+=qb2mto9$lIi>w10Ta3K-j+lu_QdxGzL5h=s4!t za_oxYVtTQF(u(Pa43A#$Bx~Y+fL`Ku2}Uk96aYDzC*nL3u6G0Z3}e_wyui6u2Sos5 zX#;+9V7m29;Wjorms1GF350u4+eP6q2Eji5a9 zU-Sh)-~kH9H1h@SQ%?Re%MbA1EbeYeyh9x|zj7Abrf+glJlzE?x;EURO%O4St70mL zFW?)ww_%=T;|~N=W6jo5qdYT~x6|S**#+IOCCc3mv{RvEV|-#dOjtCb!^LgFBXi-3 z4vq1g_#i}Ze2@Gl<79*3WEbZUWD2em?l}W^{?SfFXKZ>J0H$U2Dc%8z2giz?hg35` zIxZ!j*&~~Sf^u|795+yr^^(3*cLXT&dHQzmHFJ71xXV@^7Un3VI()x&u5pE3cEwd8lGfiM@}4*KxJE6H`^y=ACL$@MuDID)gY{3QBE(10orhRet95}CgRBBR}KOo z@g&w-2rIun?(+hgu+a38YYurKL0}?SSLl8D4K9W!FcQ-Qv76O#7eO`O|2e2h|AMv( zcjO2fAgr$vbDNrHEPm$Be0b5Y{AGE5_Z{CyexsKh=;NDI-V6L=__s5y7U2cYEvjqtPc*?p&2;;BcBhiN;(qK3xrUx1q+v2L^4 z)4$v=AH>(Sp3z_*%NykuwP(IGZ&Xl?{|`wDwA;1{`@&$$pt-!y52#Jzj0mt5llW_1 z=r^RR_}-KJ$Y+(Ks=+9U@e-7o${`MU#helU#5(+}vM@WpYAB=K(&8=%`~;q73TLSe zaVBq@D5-Ib-#zPMC@lJ%@mhFROU)3H^Q`Xw@)~u^+~!$uHnUw?EWfH z!_)EEr&5PgNdF#DGI)g{j}s)QPo zN^2)svEMzLYr2D8(_F+X^)-$4!eQhK@p|dqz$|YM;l`LVTw~k~aVa}j+UNmunx%D6 zmiIE@qw>BL{1M?@VjmJh?YzxnUm*3~@I$yyeOSC|J07Sm+JwQs<@xQ3J26Jw!e}g& z8nm{=U>+wiBH_>chzF(?MGjkkI?wl}@?7ka0_T^mff)^JSx|?1Y5tJ&;BNB^Wrw1TX1v9IAWG&vAnY=?RX^}u!ylq6 z3(g5tie^~ZNlh+x$w`h$nbJbpP>^f?&cin8Q-!Abp z^adpu!fFN(_Xc?r|GDV#L)N;T^ttYw8#>?bUf$1IS^EpD-Qn6%r>09;k06a7C|bAe zfl6a5`q7(c1|G;>bCH($aw>(3L&n2bwRpP2)^=Z2U@151-i#eJ(z<$p8FP?We$@x%ifau7TPxDs1Fa z`;u~wH~b*l%4jrH`9}QpT&0Aru%y-4Z}jp z$ky!Y(4hj*dY8rU`#FBw%9qp~(SqpdlaLG_@Rh+0M6VJv{>MC*-9k@oR5nTf*l=A5 z7{&?fk~TIaU2bZ|55aMvj%r>}dhk{Kydr2uM6}|rV%r$#aTDw$@gCX`))}@wos`CC z94+YUS{iXUS9N#ldmH5Wg{vS|0_vYKew&2$&d4r*kx&O+#rIuWZ?%9^ll~2=!&j=R z-Tlv}_#B}$v-EZY9p`T3$CQOhw(kc!jC;Wj9O16cceEw8s@pr_p>h#X&J4@(Jl2bu zP(!e zJzs|&7_tn;g(h@g7YytA63@f&&yt2TUwTJsXiMNe;vr^J;BNo+Kb?NJz{P+ZMXf^z zh-anRCH0Z!!<8s7k-OLv{SH{KMXD{64wT}o2^tHJ;W-m7( zIF7+N4g1t5pC6;;;@=8?=Uk0}0G+APcZT(s9b{-39?5-XQm#tRlac*}#r}yPq}l@J8X~(?GEQ)MU z8Xu!RJCDz$3JsrUKh_>!0w3fZWEQjFN5azMlLsu1bX{1!Sbzv>c-?&7$MtV3+-vp+ z^ez`ExH_^=wN2bBB>G$~zuThQo~8W(*iTqE@Yo!gru*Vg0H8#u zT_*Vyo@{D9XNXCcY98pqMRGs9F1)d+4DLD=%ixug(coBJC`AZr%Kjo z?wDxluO4aS#xdeB0ML7d9fNit`(j1_A>DC~^S#8m&5EK>d+xP(V5mEn9Xq*T=8G@U zaf9J2Qzoe~(M~dWRc0{zgS$BP)#@X6SoJFMbM7x=g3XpXk)`P&NB8p%kRRLXAew0s z9=s#T^cN+g5MK|o8E7r@BEPhvj}CKFV?lgq=vYq}L{FgM!I-qRS|`@g-bt_ZygK31 zcN^@(OwJ-mKw#v#v}oFe-z$F{zoFAgG#jWu&Hiwc`Wq8Fmz{2>K-H}0{8jBAdRQ(; zhr;t3uIV?d3`Bd&LSEjr>{l`KPxzl3%Z3kY8v>cd_NB3{t%XIY4coBQwT|T(0o&}^ z1IJgLD&Ehn1_1yd&1rw`#u1Pl6U)5?IuaNq#l?99=0_7z(-ic)x9c2cox4}InYSa` zr=FDS5WbAu3wF$!@n<~0;k8k|xvRp!LySL@mk=xj1s_qsuTbV&p82FaBr**OqW3FmFZy6Rq)l?D8R%V{g zODH>4T+)p#GvyE`Z7lcGzU@1@UO&Lrx6Z8(xE)itWQB3gPMN`*_8gxKT>)*n!o2W^ z0nvGvzF+rb?+uI(1!Y|0IS=<^J=1uYHefoQkCxw(Zajx8QnWh zZxdqV3EceDrC{c8AnH!ZZ}G%)m|Z9NL(m{c^~FwK@rSyALDoG5*;`yl|Ak0+S5@a( zdvJHVrf4KoaH1QO?=x%ud=dBaILucCgAP(X#avjE8xhpd&U%B*F;aPAYQ#~+>9m>& z*B>ZI2A*%`Hlr)E8+0*zr5v=54}o4k{&$LV0!wIT;K&{zfV&KH#QJkxH9qZZBvu>iOkK+Cuh1bYkH zPI9}uRpa>=1I*}d^7@EQK#dPM_+Zimqm*zu*&`(W&Vp1T(NJNBk%DoYBl?ZR4Q>!~ zN);*T`XK!Vuvrc`!ZWC$rmdL{MR1hMS#Kz%?Uop(l2SeZ-wrW$%T66n_fXKn27NX$ zn!Q}QC_tLGwg&eDIlwFyJR+4IzjZ5m;AlcUU;yX$5lk=Y+RvvKy z&3d3ZJ;*;mf4DO@7RjpTq_uV|gT{0oU@sS><0Eb)RO~v_8jHXntSuM-fSx0_pwLAi zY`7BT59~8EUUnf*7U~a~tCkQIQ51c`GT{%=O_mtW^R4CA#}K~7UAM0)H>cL!gi6^$ z?HNWcmog-S2jjX>{VPgkk@SZOSF-s{lKzn>c}XDcRxYO|cP1!Ip1$$*d+8q2I<^h7 z$B-UBNKW!S@&Uc4iw*+^H6R&Ti^<%f91v$sKek#jrth)KaS* zszQ^la&K8QlQ3cuegg%{e;g0vG&JGQG!=C`$!&@c!{$(20zMwWf-=x2iq|N531XWh z4caO86YLG_1sx5%eRYtV_gKvx${yDXn6-$2FM*=)KM$w)$Sc<2%|YfjYt)Xfl~wC& zWj=Lp=-xGI>`Mcs+3jZlm2pM`40=HUF^}-?Lt)QTwG_yU^IXoGA~B6PTzdn5mDqUy z0?^sQjqScxp-uC!s>kRTI$`T$_C~SpJX@trk=*dx#pQs`^jOrd{2n+SidKd97QZpj ztlJ(dG5LtbV|ahlAL>kPyDJ7NY~O{-#zB zCht93j(P}PF~yK#8*?iIzyQF|NTCiiynlKOwtB3*e-$5^0;j|A+l?Q>qrTMoAXo99 z*peUUfak=JQfD7ZzPjzt7RI`a&Y*_t50up{SH68Fl zkqex#cgdP(KD)$+j(BhT1}hgb0*+d~acC?xY&Lu;o$zV+9Eu8&*YbD$0ewG&HVyv)$6O0n!e{jK;k22jv$aiKuy_$9wTSC_Ne8CE6J1%{tuQz+NUZhAO3J+4`H2K z|GiF~^n>~4cH=g|y6l?VRDkvsuz%`%)Xma+2D|;LaHu(=%wQbGbnl%znqZ&E32y@W zKak9SAK34AS~(j6Ktx0KxMqOw?tw|_4)W5gWa!_3;F z=l;A$v47M6H?(??n>AGyqNYxEDw|CEy?=$AkH5JY6i=nfqoo%BjbjN1upr`?LU@dJ zX8Z=FLsU_;I{%JPPmehRUEn+Ebe&5hhRP8PP~dgl`b5qR3RoLyFT8Z;BWi$toq2pW zyRjyn#3BW7UJHYYUNZ(EcN1qH$ck*n^=?IVxA2*n1kbZ>RPwtgGzylQtnCa7lS6{W zD4?bV*%@cmYOIgOE}Q{{vru>pQ){BQo_U}fHVL$GqQvmG7KTG?Bh$A^T3il3hxJnOw7nxz}d;r5zb4>UQE1!wXnHf z6DoA5ww;ZiDTc+eCbmg*!VfE^v!C>X&(82aGZ%sWY_rC*!wN_`NxjQ}Wd`2h=V3a} z$SHvs<}TPh=3=zPw7So9XA~Y~aAk!J4s#)tHDBqNQ+ws4#SA*;R?fZ?M=ms*2%=JR zMk*%kxVkUBhnQ_`nrUdgv6A0+&e^Qg~@<20;QH{?6Gl^HhfR*p_luD8XoQD z^u3RZuW7^2Cz79akU!U_*eYXzWPQy4V$6;RV~r+EvVCLc*hzjs3u!6MexaDEulhsNT3*0sS0|d< zY3!HRp+3t`V7=mh)_Xe)Yju}&k0h*@C0GOVA`262z@H%CgT0%+;?4d)3*Kqy9MvrV z>phyQ3I<<4^!dY!c6^2Q>Sp$y3`1ozvJWmM$XS3sCVr>f*-Ai+ok520BnRe-~D=4>68% z@QXhhDI_l5Y97>jFrTjk_3I_@IgCrDJUY>}8DC+(YTo6-#SaH+|07$7 z@gHE}0xlVR0s?eB4qQ5xFceV|-g}aD^qI-KE-2@oY1)aL2903=a4#tOv=Uj)5DGMj zvV0ds^e_Vf9W%9TqgtCC+LX*wD-}b+#6PodIY>e4C|^@JMrv1&GS|bTdRm<#P+8n! zpoxlfWeoKljW4F=h!Gpin8>gjBB5XKLI1Lw$3FmllM?J5X;>Tws*kx;5!I_l6uXO@S4m zSru#Y!>t12v}aWBE02VIfU7W~+)^;JVlygLsoo-^CXg(eoe7J?1c{fhjhFlEB&gDM zCo+DnGwgHt|HyjxfTrvHfBXQaI30`C@hAz%GV`F4QXv8gTV_g1GVi2ZR+&vjL2kle z+dCsALzo7N2y7`S-e4)}xNac|2*MPEsayt(F)qT`#@K!PK40(A<@5XXhXL>R>-Ky- z@2}_M^#)hmDo!#rF7P|g#j3fFpvnWzHgHed{Q&s|cNOsI9hOt=uC~e&|6Z$YT;;0% z>kaG^DD4{rt{|x^Hpd$!%6|{z*kD~b^wdF+I_#Wjkm1j&Ontazf${%kKqRU(&m$dEFj1YUmfRs;~$i zmEHZhp`)RwfPRUDyf#VJn1PQXZ)0%q*jg052E17u!)eA)&;{kIjspc91pgP5-3Fq1 zgJJgpD_0T^C%8y8fO9~aR!)s^s8+#P(i=gVi=7crLEisV{M-Pt0e=2m2mRHL z$@FhmgABow>X34#qB8fwzN_h^zic>@9-~e z$$sl|N_-9Be%|@Y3wt0>XQ=3ZJq$dcvjqJD%j<@>>gx*5$g@muV*fP%1A;RnLrlsg zVt*LJk*DJxLhhTwImOZ&67w?;>=Om0gXUWNF!2TVJaItrF^}FZ)(2JWn-!$JG^9f* zOd&(}alvh`17y$yad}~zTgKwJE%x-OxZ2Q{le2=5Y3O^Xb5<( zCfT!L><6O~4wEtDx@UC|v_%#+6p>McWiQD48yfP-+8fKi^>+{71|4xk$GgjEUQ&Di?x$~YE&Ux)X%n{@9B4*_=@VTGVv;{SwQ=|C0 zd3Pbq{ll23a z4&hmCUJe#lp{CHld4AhBfBZ@{b( z;R9aaI70BwgA|o90QWirQX)HQQaFz4H9(X%iY1WFfkI_GpHssL0x!bVKhmR{twnX5 zE`<24P`_F@g)Og+**1C<5_<`XnlGI98wEAJ3DxA7&P1B_t5&i0f`yV!w(9NtJhkS< zdCJORu?%wEB7*~@ESh&Qo`&_rS+~8QhQWRm6frsAI6#;fJ$Q0cPrIg>0QygoMF2G` zS~z21wv_r!=U<|hc)=t=j8XMdHYt-_^z^j(LE&@jg4TkeAZ-J=1_gRv*7QF7z*rHg zDl@I~&**rKOPq;bWUudpwSYSV+#l1Bn_2K=^ata}Apsny9ESsrVfuDn-SbZDsMuRO z0v73wV(Y#UkM$7WnyPV|)1`dCQP`q725*|u>WWEY0?G1)*NLo}33Wh?CgTb*j?;@e zKSRmNIMI&Wh3=#hV(gE?yR2K5j|*6PAy^NpF?ZkkXwg-t-O=w@@8{(kfCeb=LHQ!@ zl^Sf90Qn3t4e6P<*EEyG0OM(dvme|j=B$k?oIJKqu?|&*JzU@ypG`>32Td4h@!?sX z+s@S`KxMLpLzJPz$0Ddlhl3nstZ#&rqpC4b6J5%^3u(7k^|MkSdsQUpf8Evpnq0FA zD>yViIWV5v>S1m>oP*uZgo7X*9ZDt4aE#U!EBk3v!8O7j&7M0kQqy3ngztZ;I2KVL zsvtuhQ>y)HRdXV%S9wT`{Zfz=K5i|ClX!t*Tx$*gpt!;d(lrlXSBg6+oy4C&bOO9a z@|Dly*5-KoYG|J~=u@D82fNxooIDF+#j@#QKRDtk?SFqHNJ(P)>HI1X`RD}an-Ng0MGeOCA z3wi&0w7*kyP_$q`0q5w>pihnJ7xB;J+l&K#^ZV!cvIrA;g?3P*x-D!a9VgO18(H{@ zzj_vv+O4@1K$Ywk#DElWC6kS9e2dDtjB82D9a2E`XT5Ju!O!2WGR~81#S8DT5&mGc zcYs^@wrz;Ekpw04^Cl+ctzqD{wW%y2 zV5q&ApOyMHhdvV3iFyz^X-Z|0zjLMTv~nD^Je{CZHZ=sn}jmaphfcwy!^7*a`gd4dsGF56tJe0vVtnI zNHn3VQHTiqK97YSD2&oP{;4)nTm`%L8Hc0W~1_IC@(y1-j1p-{68)D19zNq#KN;yWcn}X6YXo~_68Ic)L2;iC=8mi(c z+5;-K;u9#V<8CUj{VAJ$l-GUh8b$x9bY>7!HXy%{Yya<=rr1;>6b?6_f{hI`G(bygShQM?K@pVa{j2dANcpM&2yxD@ zr_ife8}&KFH+Y$nQA@qmEZ(aw`&ExuKi$QoNs=9<3x}U!i0s!O;H#A-Xi8 z!d4lLkOz|*@8^K>YH~Qw zzKg>)+SI{rR5FW;kH($KR(OPwd!$XQ3>+->RQM~vEA{g(^TP8mHH6wQh5tdlmi|47 zcB$1Ziu+GU%?#YeGrbj`0QcEoCj;Av>-Fy$ZyN6e8-roZP(cpZMVwU^gdo2817igk zRDdX;GB~`{`-BNL7|{r7MNsLlN~$@$0jxXv%bOUgExYEM_{aOG5N(x^EQIX5+YoYX zei5rT%C$zo6F`-86B*EiHn2>ADx0GPR8|hoaR_6C3UU!sL^NN2l<58yY<{UtQsSWWLRmH1nTx zi;wWF8%mQN%k!vvB@&hHA{R4V&S!&qJPKzDXNU>J(SjoN1nH2m%N(HhCq7L^IGq8{ zbdb;1hjON|D7dG5EKo0^Urvfl)IzZb4uiRZS+H^9X;C3l`1`pm5!Cd*gtROU{)*NE zwzlTw6MuONz++G;wSS4Te%>SY1m6ZOfFjLyvK*lkR+6{7|DhDk#XbJd$ugE zNBns%17nz

ow>f55Cv^Wfwg4C9hZy_hZ~@*rM=TWtD*`@Qa0NyN_4mH`PdVI3fH zoe&(vpuDyYB+&) zKgC_eN9V0X>LE=%*IBgOxXf1dsnFDqQGA#2Hj`e9he99>0;$EJgLI7{8!!q(&xKS` zeUC@nLGx4kdba^j>u_~RFE=#JcvHR$Cn@5=Pf5j43=5fmDCs0>&L$yb!92!)0L_Ji zxrQ3J&hdbsq1Zqmpu<=U^RNwj^d^8eg5VF|hKZmQg4O7O{Q)Js(wi_81YC&|jasoz zp7%cY(RA;X@C(WZ+Nu_)WX=-OjH!G?Ibf~;;t=ho1}gGx$iqgpt@0KJT0*rj7bbYl zR?r&6g!C(*AEE5A$=k4sN*0iE!a7lvabv+!EB05>=1(s~=WIpjC}*pl_0lNdY&I-o zYD?M4mR;%%%(rDn8S^83Z^V>Uy%31TTV%#V=@ZYn|K(1ZgEvxdW3f*ZEXxa5_Rpjy zrTip0$>e{Oaow|orI)o)BeKSg$FPBUNszTI3csMYX*{MD+uo%ZqM0}u6Ws_dr`%%A zjF?au%;(!~;&7x9wEvr&d#=(s)a?`Esh?D=w`Kckew2>Ysuw{B8g4$h8Y+hJ$X{5h zKY)F26z??#SI8D46hV)$db*wwaaVXdi$9|a+odeo@dK>0VFx8R&}6fEgJ-7o zTB4~Jiw*)`PGQAdWF)?SdXH zeaYCjrnjOq9{Y!e#+- z_-o@G**5Dpw^FJDCwc` zq7B(40=o=R4`PcKHYC(ZzeC_kUEx)6gXIK z^0*2|ym`O}*h}U~#6@p5{GDoBNQgHJI{G(p7>~j^nhxB#Zan<>o$4 zV%PA7_y$?cv^tCv$|61RbE9Iv8t2GR((-BgJnJtE>x&64HixXP;vUZb1N-J-wam@u zTE6mSeT?NyYkzY;kwBiJyXvIygB*qf_;ylgR8erdu{x z=QoJO>UPOaR^-PsTrlRY{JJJ4aV1&$pfmkd?)_TUzc3}zqc@+r3aQ(!1-+mS17;0D zzMUZiC=S+q29r>%O|BU)p{&6%2VkS8xY0GG^WYNQR8K zUjWb@n5$-9QEeqngOGd3h)}cnn7<|ZVfAr<%d`SSPCKQ3q!Rh8b(;Dr$5EwuPOph6 zGj7)Ve_3WW`ZBdV@9jLk5dg^$=uJ^c#27Uy(Lq*<)t~I^B?i27@K89e` zjpBZd2NdwmCThev0pw@qQ47In{0+dFkNJ5g2nHF;sNS2;o!~Xa<`i{b)ITFTmLR`S z%l1^?RGT$BjcWVJ6K<&r_m>!J8K^jcD$T?z6!9BQsM1F3z z)tF+mJd$PDz+KOG6;4)O02IsecvF{Fvb1$d!8PuhufVdXT{7whi7;R+H*~IfveUB^ z;no|$p`uuW^{KZENnL|`DxQ>j+U|xBGSn@;#O8*mpSb${!Emd9O`@4v-)ZfM$S~9A z)TI(C=taa{TuyZk>zaOq$c(oL`e#^aB5*IJy~`R(e=c%e=yq}p}dKuOdx)5lHcPzQ29yQgpP^_onmKPg?Pkalw15KIH zIIWI@V-=yHL-uvs{4A0T&7SH`gX4Y(D4K`pXff--Ye$YLz?DYX9U3X4W{zo;Fs zh9BZl8C?4?8(k=XU@$12L^pjPC41!$Kar>*K&~M<;^CeMEp|k;)@@Y2nYt+Ad74V| zLMVQbC{+Jebf0Ec`PUFGi)z{ud#Dng0coH2#!o^yNp3tww))CU7DWroG}f&7Cywx) zrc|a9!$mYn#B{#O8D9R?ku;JdkDh2^E>)MM>Z8==Oxvv^NjxNquD&&*CAPL6^oq{2Q^Y=S~yNyd$amlsKbBH1&h< z5bG1SQ7k>72M*_&E5KtI2UvHyWLwrA6j*SlB9e@>DDslmx{t)3=ON@UTsZOhHE-^! zakcE-c0iR-`~>wB{7ILiQ_ z>@A4T7xVG=VzB}RMF|P(KY^kTM~tZt*2-`IIRfIDwuy>WlwFj**?vvlC{-d}$LPe8 zEc)3av&PL|S61nEX&)A71etNc{dX8`h@6_9pqNJS9O+`wKGLWO5_yG4?Wz**a<*Cg zn^<4lB5{uUARB{S0;=Du~i>{fHMoqePRzetQAxBsubd+Q&UioIdKt`)u^G&h&I z-Hzb!W9uK6iop-?d7_Uo&5QqgsTkpP+wb-}c7F3Jd~gU|Hf9fhOSUWN2+W$j=FL~W zlpN%}2s-z;|DR57es3@MVg0`@y!!gvA7rq<`%b%v^5W#C-5u=_8q14RKa)O{WvFuN zrI~-$M0N7-khTh2ud%jiBJYq|h1V5BM$#B&Out6nX!#2NoHJhJ+(R9a zsg;p&l+tfUhc*$76FyFcx`&j2zBmfp=H}xVDW5!?m8II?p;%Wse9uu49MX3-G+x(8 zV76Rv4V?Uq;EWANY37G8`c?#uukIG)Q)nsundu5$`xA!1UoNQreU{LFa+mT>WsFlH z+-MX1kV`VO&!%YE{%pzl7uZsA!oYQAK+r@#!NYRcpH?cE)_?C6KGZ~*U*pKozsv3= zaEE{4R*%RzbDXp_tHF~YkQh@JR+HVI1XF!#o*urY+0jm^`IUFRb@Yxv+P|9IKU&b2 zQGAAQpt9XHTCLowUNg?wP1Svyd~lcSRbqL|69R9McJK_Zm8!16L{Gv5P&Ss_ctQJ` zkSQOm70e+rJBCJzh0Mxfh4mlR+P2^~(*2W1X;~GFSZ=B5bZW{AVjjVn*>XCRbuNt% z9@iLCsob`F@@|Y%jqV_);P(t7v+uEl$(X98k^{^kwNer%`5cxJIi+oVbhGW15Uuiu zx~d->qbpaq$7ADlQfBQQ0c)rZcDg%0gj_yV*_;z)Xy>&%cH z9C9~JD?cC*DwL7c4szM=bame?g+M=Xy(ZK={73b8<&t`5bK>6csu{k}DRwg^S5QQe z%3CTiQ$3X~N-7^|NRq#7p2N`f$2didEY3}yJS{Mt4Z6-`J$!?~_>N0F{P;D(_4s6e z54K@oov&x)RFU?4K->NeE!675G*?P|p%{8i_%5x~(6@(3UDb4gbog8l)!eTl>FUJT z#M&V9;QgP3mdRm?Z?ZYMpFrfaDrYZebrly`7FvF9rl$P<3a?_a(Z4(4iHOA1t#M}6 z9&31gd1a~xV}*o7n(l8)kDgXOA-0AMsWxP?^+ThyJCq=`{&PoxUy>+%)#H&IrdB`B zAr0NzK(*AikeU6*x4l7_|L8)xflobKk*d_-a*6w-8geHC~J6}!z!LE zE(+*tCdL=GJBO%sb&j6o^+Qi?#wvr!mAaZ*0@ZKiS1;Do{cQ5#-xpC2tjgmNBz;HI zoK#A{%aU^u4u zIoePsC6Qawh|BMg817HPN~bQ(=JqEN*ufL+c20V!C$ay#3@=?97iiqzmeQ8t)LOU3 zt9k@m8yc_S$B;O2BN2}?LUa|ygdRpxubC9%6gg2FgspmB>}~D)b$0JU)(G4ms&sU+ zl+(DSL(jAp_q;tmqNISyGD?iOMZOx7wFa(gpH1~IVyhEsjdQCL5?cezx@$zTGM2z9 z@87&S$XTtCXIQ2hC>X2#VPHVt?t3Dv^77?0OYTdlC&6&u!Aml-fMB@7l+TXTolnp0 z5Ts7k1!FpmEZ;KOPGFg*`qM#p2yDxQF(k>Xi>CGt4_A>AR8G2YI1(ShW4()H@`r|s z))T3wc=ys&L;qK$E`nYD7hT<^qy+Qigumfl3DIOySB;Y*l&7PryR}%4TjfX;C+S^} z$!jeQR7_h~>`W|d5QXbHrt0Avb%!__3LlHLFNC+%UCrTE{WtWVT>T~gvlk+2)N_T&Sd+)SH=Gr4W zzPz>l3}>kCHD5umb9jxS=E<=vLvyAj?i#^js0$YFGAR#sC!{-K6`i5viu4T9Wc!B5 zg3z&|%h@hOtWhyokeXy2z_Zah|Sg3Xw3yzWN9K1|ZKa=H8 z1$EdOU-eVQHua7cN1vXKgspWAzSXkh!oy7ty@tox%Uegv9)ubXkH##In3Cl)8If%x zJB71bD;$d}bXw!nbb(IQq0OVmy)39uwfY83J`lMXr}~AYA^mdULchr(ZpGvknVyrH z@HmvCmsj~8eq2j8Yc7?=Pe~muajzAtF>l9_rFAfMeYvYKOWg%R zr0Li6IRsPRZ^HC+rhNEIr^vX=Lq+sfbzRl7j~Z4dQ3cgxuqz*?FE`Xi0cwlII4(+6 zhCJdELZ$Z`w4F!Ey0+Owbzj8yvq@_Gk8FR#^2gy8DRHW!}rjXhmF#UfQ3H%TDj|=8tl_j;A z+MNLf?YUVAQUZ}u;T3wgFUo2D@R&PQdD<;1I=lNeWum>7sjug2 zWxt2(?=}^OPdwEA+(DA`sY**G+a)!5q~2rNuUpS5lCRbf{JKM%kG-fV)qk8jRC1iS zyfQqEKp{0&sCBC-UdG8MX(GepOv+BJ>}^H-;k+QCZg@isbFkKU(Ydg@E~>?iu{+4{ z@D;bo_AMBZsf-oT6|ay}{3%{3s#k#1Z^e)b`(GA3viNpJ3NygVb1PMPh)Ag70E0U*}PzXoR zl_WQ1u;4;Xi!RHzXJo*wddOd~nkwr|x{k4uf4B4Cv_5>`f(<{!;`N!rGnAc1Z}U`c zRJ_vHktpdHx~2)OE4iFzaC1Ab>PqURd?tOn^lI;Qp(IE$a&;*Ee8_={9jVj<{#)C( zj0av_?ZucZ6durTR#V2A*Jazs=UYHO;2BWb|>-95p((k{D+}`CMH6{*1UOe(Xvl({+9ONgIj+8$D%o( z+HKiV`z2SHDyq<8M2R``!_IK=Za6ea_Q;QG`<3@OX@8qzv5s0AFk&^&&)#(Y*VxQj zN>h{z(cN^LalAfMoi~nMt4|tA^d-?qYo+7#Ql`c9zs#^>p5b7gX#vOwL6-B!)BS0e980|uF>cUQG4+QL=6v>z_ z@@uZvgT2>d)wS$a;RY%1Rf&(H!|%|4pN5VG$3j$|4qUg|kioRJVq6)WFncffl{`ex^py9qcKJl^ zj@GUee5^EoRh1dlO_Dr`7Q4_IYkEq3THn6gb*Db>-gK9`x?Uk){bGE#^ic)BtGwR% zReo${+0#t;QC@e%RqPk_3|dLfD`NOjneee7u?to}dqKfU>-VZwcb8{I6~r8N73OmMKs1v=mLq#7y zQlj+6N0-ON2$z+{)>g(=b?U|#LB^(v{if|bx=Z?lnYp=Ll@ZtiMS~S)fw@p0#zVW< zItB(kRxi^Ysp>2r?Sr0lwY1hK7scDAV+TxMPee1$9$>sLgc;qb&s8Z7!SrUm5iNBg z2bRM`yil{`r+q6+mGjf!4bf09TH$tIc*D5~6T?%#FcOdXwR(Sbpr}IWd_C40Agv$Y zjY&1={k^00hr*>^b<+#gyIf#PmeMy#sj4tUPLsYH$fwKu4an`j8Fk2Z>#p|+;iMX6 zdQxU+PFGC?@f?{!i$s*2B}Nkz4(X@6;@WkaIZ;3#p$ojvs*E;emDkT6g+Zlj5~Z-f z2tC|Vojc%C%yXqKR&?lc10-mRuDC)Q>ZAB^SWF)xU~&SYe87A78h7--dJFi`v%^HR z{YI8Q`lBux-{bhMT6^io(e=L>wz^I#37XD}*s5Wtw6ttxa8`oc_1@g$sKR>RNX zD@C_~5e|)^C0>KZ^*)iVci}H{@I~j~ge>1@=|L-t$4Q{Z5~W@ZJ`?yxvFCRKN8>++ z&POC}QXBwM@IV%>7r990AXcZ!^I$j1*Kzg(v5TEpL6Pl#L1^6t#nI4&v`Tjdwl2Tv zP)})Yv!XT^NkOXI3?s%qN3<-jM~g47jD;;-50t`OVrF&0*8i7&8P;m~3dumesdV~~ z)Ft#`(rp+~ul^j?%%CE&QeNwVr3v6&*wFuJ(M(b%&}!24HxQFZDwTWGt5>x8p^ZqI zKzyB#i$DkB9sv{fL&vX$F4(Hr@v!?o(OWP?T$(FPo%0bi>aIYm=$&`BtGeDd7dVTT zNACU*Co4h59B&@-$qXex3t}^pehULSEdSUN#)o-UsPkXILQIIRvFY7tq8}pG<`ZDz z!kkptZIc$sl?WvCPJNcEh(oovUcRzzk^RBtVh(aFX z@7180?$mdvF(%@)@9_O7MntmwiYO5BAB6~#)8JEa@wEt!hYOk(3$ zG{btJzzc?PxE6bdaom;sn+tXt%XTGSaiKP1!iSl}@JvO^ShVTX0aHR`yfl5M^ei+c z?##>`^zp6YkNIRY;QGLT_J;)=TIy2@N&)uT9e%W|6d|6Vs{_$ab|UWHkN9o_&OO$B zNXr~SOvOfz2K6yWki<>6Y&{>tkgkYD@As&}jcY;if%=OItYt)3fsMe*&uMeuS&%9m zx(WYKf)u3lJQ$UgJlUbDa7k)H#zX0ek0lNe!(;15NG*Z|kj1|iz zog{kib>%{&M5_-VP0@j?=YhT|nNMc=5Fd4ufos2=Xhnxq0%Xi~3W`Bp2xzFm9n`>Y zouCN*V(}4P2ZFY4!Hv|Tm;=CeRdOT`u{FStY8Rnja>B(A$x-*ldrL*w;?e@#c1s?m zB2_L?^`JMK7;9iQ-9<=f;5KX!)US|E7)MHf3}g`K{)9n+R~YYd5p@WyG_+e1CnS%p zAk84QxcLr5Tt7>e`hoy*a|?AR$Pq=s-@2Y2x~D#Q7gL1dHj;|Vdj(ow#H;XlY%mq6 zov-yAv{pK@P9{3qV&O`d4dX_1_mEGdPcp0bQ|WdYY=Vb8=6gCQFG?$sbXtq%5}^)9 z1TBqbu*>VcWEDuO9>ys&u@ZW#eh=p_jET#C3}}z2Oxkg@fBlG#=&FG38(RR>A>#0q&ecj8E`YHqCTwXs9U%^t`8qMw!8DESWc>7JI@+P1vS+yI{ zsvPlnAE#e90^Hss0haz(%MijlgN-~_6nmzpcf z>*LjE^L1muV^SA6V(QG8tLR@f?vup;(eKpHvFU6j(w-6^WcKV#M|?M=APlXsnY5>w z_o~g z1?@`sec>foRrH7OGt^Bf_8V8yL!{HVnQlFwTGbL&aJjqlkm-S`pR7(n&60W%$Amt@ zbw2hAzPbabUu7?@uQ!7e2>N!pq#a&MYV<~QItH98b|Ifa{h2l+3#hEeUw+OAs)`sp z!GtZ)Y}+5c0^iiNxUek24N^Sb|1u=W%3G*Oc@M~H>~r8=aPU6BKv?R1T0zCbZ@w_3 z)TQ_aqNk@E6T!0mXlRjB*!ao`>tWOg)^oSJbKEdnUw21kMiZ$)WX?pKk}Ho#Cgo|O zR6Ar`5t1!O5_JThhES$QjJzIqFsQi2k|2wPW#)r$#5~$0^#)dl*=@()@RjFHuammO z;8WolIB_846V;tCJFdIwZ1v?>F>YEg4sLBl_^t=zt6qo?r$N)vf>Q%Fi;4R&NyvOX z?9&gQsNWlxq{e`#InW`db}9DcC%Ot(VacDt(7^6CU7-a>4m7~K;3Oa=Iv=gH2dCmB zQn++|7R)wzCo2>&HU*z_*`OLNxJ{40jO!%bK|zsu2x0|%ZtH=EJHQg+Tki_C^+v=6z&h2{ zl>2a#l#lltikLrAI)$`Cvy6aokd>Y_REDM&hEHQV&YYZFWY)3jD@Z7Nk<%Hz9Os@Y z{H339-LJ)&tPp90^3OR@h-$9*gNMH%ReK$^&hhMg@p)%bKY| z?oh!ZAs@(88iDpoETZwj{hSBEKq)y#9NV4%tEt8oAWz9}EmG~g>qzjf+qNo7kNZ_- z+{YK&Ji{W~5)02DVPyavfME{dCN&uMiCfT~^ycAiT@ngTbw)&`XnQjGcL4s`17CeeFrrM?|@ql1V4cP{0p)^y@etv>`d;Z zSV?s!Yi+cPK z5s8Ob5)PV{34%Q!+WR=Q4;?{zj+_rm#dd?g%k79(^M(kDCH%xHju)mYNdN+abJzp( z@%q<{N(1@7jhN*ioeED)>u^su8c!6&;5@zwXNCdXje)2M!rEQFmQTU6*#kBaxIPup zu3)vb3T;CX?!@>l!Elu;{}I_7$#JA)e!=(bOV~4DGmfMKW~v1v08a#Ho#nVfE?5Dp zsrJTw4`&g?b6~s&#}N}};x2Uz3J_k`A7p%lzhXUy@4W&MO?ebg37GccIty#Z=f22h zF<*tzIxQ<*wjo0IR=?^9Kkd zaLENkr*!=9)mITEhO9<1G-$>hh5h%YjjG7ZcsvV&ZNdlZerKQ18}dY@TSF6!0s{MabrB&}z~W zrM?e*NV)PCMYA)B53M5PXOy5Y7?M_~`$9C7WDvJFu`JYuDYWN*kOc2Gaeiwt|otpAQfzaG|pnC-*P>QZ88zEF-m)19{_0gtt2fE4J{(5#v zeVMw_m0ao~dZdVxHiSxzs^`(B9}bu{lDaavUu1?3dUxwKbm-XC;!JLMCPiM>qg&FU z3-2APrVO6=3uR}Nmk;=;h;qOAs zCEqSB(2qx(x(_gdAm)eOa+S zEN||3z1P)xFFC(l8GK#oO7F>}?#$%NYobl61Ey$FS4-!3$_rEf2qIO5+JY1c_9fDM zaxiK@!!BIH+i|6v4Cx0@r)1nDHQ-*KUnu^rQx`WYsv1S_)sSSv!_G*YmxF&8&w%6} z1s9_}wEsNZxup%^$|OL)2@Nug$MBJOVxo5kBnrTLZ^4JB;F2AH8^jRgBL^(QeK0ES z97}8owOh4dleA3`I|#X=->I@B!?XnOV(U#>WOFI9Ucr7ykz#ddp<%i=i{25u5a1YQIpc-c*Cw~)~xZgHBCt2--dmo`CXh2(Zt)N!v znO5AdnKf93oQ4M5obfoumR$3~&6NVT+)21bBRs`WI7GyKI3Wl36H-U(MJJ-FS0n3_ zjM>7}(yq`Q)rW(DDinsX>o;|{4;uqjA1 z$|*=6#h^5F?^a(DJzQFX=j$*SxVoP517h{;uZ(ZOc?22HvUVYR0p+0RUne9QlzYhi zX-EB9KHzpCaasXRf+-gF>NcS6F_*jKEtv#aA`%d6E*jhu_w6ntdy{D5lN>>s^V_NI29t9|}re#(FBhUVI>&i!hM-ADGXFUgIi z*%57@*Id5D*7@TlcK^2D2T#6&ktRqE@7n*0|FX*N-P|op?atb>JagCVvHQU8XVi&v zE*jkKw(V!s)~c?k;;_R0yJfbfUd#XXbON3p^>J8cKX*C)H2VXfD%tDLDb2D!wcIwH z|9SnbnQZw?vp2j@vv+gf*k?y^IJdzrm%7i6`06i94iq}u=YH(#;9{TpA^)=v>?C&f z>=pbaAKCrK!Me!m1rDK`*-|pClVDEANPqQUe~XkGvm5@XA=w)Hk!_8; zKjsgS?JnBc{g;1YjooH@`_xZulfYOGu6D;zPdGc+zSnA3Z2JSgn*Oza>c`J) zv-p#xUR{rRSm^M}`oH$jp1R(~Qt9h$d=U`zw}-~{HkMi#WPAAhZx0>L1_*=6@z&to7Zrbn{OWAvE$c@}*_s*-o zy!sbMeeyN`mwk5MzHML69>7$(1-YI-P(Fy z_1U%H_{R^9Eb{!{`1=RGE}wHK{T~}voOsLe_KNl7b$RdlEjat4o8Uv_Hlr=R|J&K%8{`K7iem&umr-s!C)Cyle^rqRHvY1Wv( z$iFyb=GQ5pl@!0-2}equyCw<#Dq^3=`hgP3*C4Ntd!D3cAvF#d^}P(Zlk2|4EN8%w~-? z;^u3#YHiT+Tk_aX^SJx{)T*uUjYi@74gYP8t5TfR=V86o*7XGm^;0{p(}bQY$jxJi zK8IUfM3sB`Pl{?@j4ESuvfcNpPq#g%ZVP-U&(K}L1aQH^iq+KSphJR-1tV{Vc|}xi z@uxN)yUT%3!jSYS8z}sg%SDX9SNxmz-;FuT^!Or>y24$#1tWA()Y|~nE%9!q&x()p zcx>1;jrHi;Zm~FtLQ#%-J>xM!G0B>IqS!UR-7%}@hwKoZd1!g)n6f8Vh}9mkWH266 zlKA?0>&evIfcS;2edf!Q)Q#2+68ezvsylo@LJgmNdN8_${Ne}iRN;pG@5`f_jKP2c z6kr+Sy#9~J$mVqo2k(#cZZ?Xx4$)GcPwl`u;C50%!)|LHVLC;XJUb+bHYQ?LPUi0> ztGCc1mjf=FYTT4mtq^USmi*`~*W5b8=C&Q%%c`sGqLLdFJn64E;evC`Kib$;bR!u)hOY9v*>?r`aD%YTcV}-soZ?<3?)VX@4!+G zIsfn=?FMJeMCrHZPO0XgCM)|JMPCF0H1Xamq|q|oVs?}XwVsDwKjy$_6SLa!{xNTS z0Jv+ojQm8p+gkQkgK^UswvqfUX;?-{FkMih-mxb2XVBNO*b{^lefCz06!mZYvE4w7 zg^%p&v+wP<^&Y$1ijeGH*t;S46s%|pws&U3v$EHMSnCTqt>{LQW-c`6Zo>Rj-UGKS zI8@W}>tPrCo%+#=R@+PPF-J7bCG&s#ucVy_-=Psxsc^3$b0cvvn=CO!w9w9#kwmrO zi^h{~8lEQ{(?6Fft#l`E>&s=Ni~6@GV&jy;c3)Q9vHB&Ar(LsNb3|Li3@nVlPr5`zPr`o-q zsYe-sN&GVNTw80en7gbGgw37t8!;~|%djP9ZN{wQ_|@Pazcz|;qISjO1c5!n(;kHwN}{#}ZdGT?mH{+~)E&2bNf$0Cp}1zc}GM0ooIRT#fJz zD&T0q8|nXzb1O~~lJVcR=R+SyFSM4OB^cl=Gh5T9da_9gEPpaN#-Q(*X2s_$B)=0f7PbN|R4cB_GTm?&rv|ob-p682 z#4SchS^2g|)4GnbdGn)SYmSyphtj%w#eE`ZM64`cvvh*dFyw)AvHI zm66Z;z=N7JRlQqs@k1r;v6jdeH=Adda3?me1LLZwCn+{oO4l`J1 z8=j95ug!+x-sGyXm9)04oOH2w_v88*rn=oQRHRk#Hv!~uo&Py>*TzWC-N>PKW*`}^ z{pqk#%%J~Q7o|pA7H}Uv`)cDHoi^oFD%o5vKUqWPq6PC7V`Gnv2U^fI8iN`So=4!o zCix+G%0;00DT4o_Ve_}8ngHWb?$*GsfS-RacKdcxL+&thjHgF0tU6)qRr0%`<)yJk zWG*h?y@RteiH^C~a29B3NC&!q&uF9@Uc{IfiSlR0V_Tet;C>6UZu6LLM1+Wr3HP(E zgbd)c(e58pJdGLE1nT84i`<$3aGaw5=_4YEtRnAyJ@G$C8z6Pmz*8?o?6i=0vEhy- z2;J`^xCm4m#8wX2_ZcYKS_EN+ma%|bdWCs!t05p=b&4*TCGcX&wMn}s_WI8rX>hnJ>R`Oy5a!e& z?3$4L$Hrw|yj42sH5#dPbe<%Jt6;|sI^N%9surV8xx7Mhd#AVcw0t8-J_b*&8b1+S zIt;hCDUVK9|IFpd>{ec0bz&j;7b#z`4t>{EzGq5(N2fj!_W}9IfcXEWncwJ10c4BU4dMJr1?wgUVH z?15nu_M4_|;w?FIJuZ)L!Ut}2uPLr4smIp2U&nQ)y4|MyEJ0Pqc&=8z-mMW>Nxy+S zE?{Z&hD$hi1H(V$DKshAhqAHMtB&|CHKv>1mA6w-cBsQ1@hAVtDD zL2!~^7>{4sa1P@*-4yS+U+ea2T>kQ9lDR^y(J~eKT>EH{I8{9+DD@YqCLCJZgvCYU zsr#f~YS;WLzMAqh5&HsIVVje;xxJTgRxQ=M?{!Bc3-Sj&{xoF}x7J3vq(ybbsAFy; z?MJMPTk9(6OZEGOB8v4J*C78rfvvn zjrnRAEksh^jq&ghn6|#B(;DD zD5*@5F-m{{0YV5N<4NAy=LGe=_ro^fBs*tVdkx?Bt-X87ZnB>S%@7Z1oA`W%py`(s zVc~+jNia7#$`_KEk~|wXAeD2wZhSi=a&h6Yaq?VL0HAa!BO0FVTRLy`Ny$Gt4f0Mz)q zty*ng0-1ou%(oZ(jM7DvFhg~kt}*&&o+ zr7M=9%c~UMF$^^jl?gc4T8ssOG9!wSLs(kSB0Fmu@}{VNyV7xryMM&(Op|4^$bjxl z24zt)OD{IW^{%);+UHiyNk>C9@2j+u2SKoUA*wPAJg_CtS3$g>vrLk)s%kqu>;5}~ z;g+>^mEqVO10=K1^X@djx)eCyk^D!l+jM0bFs%=Yw9?GT}6!?m{<#$fNn{ zjdL8nW^Hafrk1(B8Mk^YRA_?YffH?NM|QQo*El4ud*9F!NWW|sIc8bDD6&kRQU*!I zN6#|^`Id{3m|=*;lN>()zdvqZ6@4nloXtHnMUV-9F~5-}%x82&RJ?Dx%Dgg|*c7O~ z?$~5541X(TX86*-Lim;{*d`AE=tT1DvfPgDSw(O=R*ybb zI)^_@-!irRdruc$EsJ?8T$7hB>BTA*KDw}RF&G)e&=B5R&2nI255GbgDa!Jb?&wo+ z;R$p%M#jO*o#U+Z{Lqn;ECkoHuRF)#t@^+jzb~RH1bVnnp}6WzKS|%FS=un-z%ppo zlzEgm8OssYbKvFaYS^-B%8Gc|e^oFj=E%7Y{dia9_DhdL(!_9vD!7WZ?GfZv9JLo* zPXAzZ?8N72tVqKTFw&TqnRzE2>&v|O;%x4Q>rA_4H~UW=cWejL)0g%hU?1^I{ZXv$ zo|9L2ey9cij4~x^E#0x1vll>;TjBic*}-zOA$G@imF_#JEttPwUeLLof0ORWC@uP! zIgKx<&ZXQ5BAg*YI`+;0*>5PW8u|-rk@)m^}{i`iuSTwjYn9>$=c|E(w zd`_zp3-`mVLJwQ3$*htOeuOy)14AV#-CkmOQe`W|*yh4eR8K-q*!;}G(BiCnM>?Jn zPBjFtAuyCP#Z`3X{U|bEE2pvXAFtu&KEFJp44evbo*kbTNEMhNb;Xc;#@8?{P_3%1 z-lJ?|^caR#I)XkV!#H~872GWKEUo@Gw_qrm98dKXjt1-2^rlCS8!8A=m+DAYW&SnN zkU;pj@GeuJ#>@IL=9-V*O>cmWzj=qV6V3EMW;y}DcwJ6^h!LI;p+}YQrQkj}=^DvD z+#w4c!U_9et9x|j?%R&1G$&%w!C1qfG6(5R91;_&wOXLU z87-5PyOnN7$rLo{K(AGsBT?&43$RUBM~d}rTbRQ8j-4H_kp*CG(si*@V6ju)S%W%& z-d!)i7F-)oR+KFcoj|4Glw<0pXsJN-yfd*sHHj_S*nSTH3A>3HTQj<9jjX|+>DZ~n z$^w2qaR03Vs4Gywgo|7KD`^v0YTgz!`Dve1h9h)Xv>pYBcj-KRw4f>0DqZDK_P-af`r`2Z22szt)`8E z?KX-$@7j#>zZ46eO6m7fyNnrvf)*dC8#%r;Y!_yXlE<8B5z;D7QvR`FcgW&Z+NhO8 zY0Oj^g$l-WS}_9Psle_z|Mq1<85@!BxJp zI?Izby|40dzj}Y%I56_|1GKb08TLZ&tL95jt6>=(RAa#Ur*-zAc78VZ@6^+R)kG0} z2hZ#Q@0#m)nRIRZs)iOAtyc2iq$AAlrBltPFh;sgSakPG(^AR_{? z`p{8BQ$qE^Tl~}ysGjldBn|+XYbAvC&!O^tt`5E-=KwcYqq%AK31Z*REb=T4n4WYY z=n{iv`@?iy(WG6hG0rydmdb+up(V{@ToK#S#>3b9HzcHXa&Gj;;#>JAwBnR#+3GTQZX>&!ay zMN}dDQy&J_0O0bmo1&o&5%S8KLOF_6l&u=bb-{aC1lRO63Tqjfd4wr3x8Z;2^>vs~ zw(pQ-@$WFb2E6IrJi(iEW{qpFK6j+NQEu0;u3BdqGiLXVM z%AmdR7eI=**BHODy{E!zh|F&H*!~gZUql@)Tp|{8?hX8pxUt~n6q>L5=wVVp7Tm|d zcV!qYd(b;+y-jdGM-IC@Ap8u%`rveWceQB6X-AfN$7B5B<5$lUki05+`-scb6rM6) z#WS-hsNf(;jccrH8ZV>Ui436X{?-Ye0Z zh+&mLXZ>QRwSO>@t3lxd%wrk_(tY{Mng^hmDg_vPcZgIQu2}^09x%}>devRz2t&v^ zA2PM^Pvk3&A}0GHoJ36e6i0@-4pMIEZVw4$i@+aEpN9N6P*#Z;z(y}atn_Qc@!a%Y z!rh_5iz#u-bvzIT(KXSy|!j^_CK1NL&pBZs7;cx!@(T* zfk?~E7)<(N_nBCq#Hzx=$Mp7~?iKb#@66u?b`^e%_E<+-W!y&9VkHWjDBo7N2Isju zq{Wdp(_c)042ZDJoRRSmN^QWPv<5s%I z2uO}Kvh(u=gL=TgRum=Qk$#P~r^vr=IA5jC#FSa0UEr`FFQjO<;#YQLYaucd(??q~ z-78DEw^b}EYqEat#FYW;*u3#90`7B_wRRQEyIjHE=0?i)6*EzcjwEwCM4O~2d@Y*s z$ON$vSW@z7+?`qgmO}(r_Vn0lo8Ls$E8@?fe)*P03Dk#KA@^mfGpdA^gU%U(Od9e4 z9UWi{1TLnD&msHI-+eTv){u%bUZ9K?O>_~N-$}~g&P_tBT3Q(->(u@=YA-7=yO{ z{4?`{nPAJwq8c7pEI*uz&>HysvP9`00^gPvJV)(YasiwAX6)&`=VLI-;y zt(<;9=D&Lpi;^xor9Ebyd@+hw>x=8C5>3|CPk{GsC z49zkODR1+BcA_|Z$6JYMfplGajG!#wP{7GBb;fXA0P}R--^#PHiQqp^R^7$)^SRT2 z9vY1MN{v`qDeqAL9^(<=Q>37a|EKYO{4*G9KJ8li<>5_oj^!A(dbnoqjWo$#SEt#A z;FR_B_tV=Amzt;jeALLF+-UCV$RG~adI;DPL4OO(vgKR?G$SzE$F|~d#ocMT` z>88VbGerD2+IB2kKgyP7j(B=q+il8q9FH1Zhw`b?V1aVk#1YU zWFFgfn5qBy@^Gx2gIF7l;X|v~af7TMYgvG`=h;KhUEQEwBbKNa49+GH?wOW{j-A)j zKR`1EQfz{y23-Sz^?-lBl+WD08;L9o!1L4vk5EVUMe-e2H4RLkgZ{1T4fG84VxAd$ zZ(96XaK)Gece-X!f4s)k5J?Hjmtkr+?bpg*kN;>3$BI(4H8;3O{{V=}#dxW8IYHHEowf@2reF((QPmB#|oHp_&xEtdS5b;m-p_+)dz^OvA$f+IjQJf06qUyCDkA84q|l05tWVb7Rf@E{_GK{JzX#m8Rwztd zsiO;|XQ;!0?-MBs0>Xy9&IzGZ(NAn&xqF84b~37SyCVpwq@6W%4-U;G>ZTq-CgVi< zNJQg>%_R*?k( zJ!+@1IK4GTD_xtutMc=;z`x74stZO^ikuQ1^C(i6{)WZK`y|cKnjWq*ateA{?5PQihroxK#9WE!DY+_wHf{mac6pOh$q4aEzDL6lX+2p2`UT#(n-81L3TD-+E)}x<=g_=!|6>mqT7?d3uj;?_X&X<48JNIQH10TU|LzP z-hhLIfKHq+qCD{Y212ldX4^$|0aQwZlMGWjeCq&c`W5^kOc2!u^=% z46och@;nNB-8y@r=VtY+%M8y8u-!myK!o!4Y5zwO{?_?w^A@X3ZaPglWA3JJ;_y%9 zOipAHpFqs606=*z~(fkx`#_it{Gm5S_7WnM&dBHp_gIRfn?LStV@# z!Je;ZU7307Ws~$)W?P*ciW|ZyG&pQMts6t)kMtQ|d?e2R0Ot`bp}WBm_7JHX7DM9! z_@Q>gA4olcZHAb9qXxi7WdyL&nU+3~2ZCaZfuivgqz0rdBDG;&e12p-5(63x8#GwS zS5kGwb&wv$*dP@D{nYS{^HW8(rNj@s=(1$LlxKVm2j!on9{=t<>9hzv4L-9XOOE9k z=uKx2@WgU)HKKw*GjV>;zItebLO};%S2w}$h8e*!OJ2s}hF@k-kiwDt%Ui^Ewqv_- zV(Tap6<9J==9w#iy;mypy6#=KSfooxLF8e`2uRK3Y8FyaV&9`gL6f+)$Il{Imz5!{ zT2y73dT8)ne*ZTT^$Q?h)Csv2p1*!I^c!&6d(J;ls1oNyo=a8-F(rTg7 z;j9ZNgX;b@WvN=(D!auPK(b1fc1X4KMn)*rK=WAX6=REIDokhQDgP3=KXqUZZ$2)~ zk~8=;;<3U_hlvB#eXr7WnK|}PE)P#%g7daeg}F|Zj7Fc|!D-jVi(~?NG9XAGBarUs zmxuK%b!;`mW-;KsRw;Sx6^0?dJ6g>WpwhWKO~lhN5miA zF=R$HPZ$N?rrOKAP8)n9|0i}O(Zp_14sM(}h<~|8u_u{Np*ge3RyNKlH|DISsxo^M zCnL`fdA%5xQm%|sNM=77|C0aK{3z0DGZCGJ5aT&`Sq4ZC9F!+vMGl1M0ep{1RNHCr zr#d9*A;byZNw4B7`h-OD1EDy4-$^uppCaTt#i`9~!@YX>)^B;{Gr1P7>=rUa&~Sm& z)~U(ph;{~TD5YhRQzWzZc&*L8;5v!7=Q}X@-KzLu`p1qjBkDyVB4ZX!ZK13dB1Ic$ zD8SMPV{~d7+cA_3pcVfAAC+T;9t3JmV4V;>f;@vD{}J#9c$4968oit;1Kt^xYS$IZ z&6Fn?fouZDI>{V4&8tcQn!>}NEeEhIAxzm~?;@bb}*T6;)DCJ|= zt${g;99uSCwUY4itHhXAe}x0>_THz=I&0x#a3J4;@%@gmGgH+zYoMhGHZ*2}5C(dfS6X6@xJ*# z6{U&lQIMoz7t6YhPw(n6rWst?sq3KY11d-QwFN%#l65|M*Y5usiGyO#h@9tO4v1(e zhWpwhkh1~U1cV__b|}lkpP7*M1^_jpMo(r+v;t<=OvK@(NQ-=i_N9B7DIIh)+k-3g z*oJaap@tM3`DE^l$QL3Lbn1`9SJS0BI-%@*iHZ{$VF>LKS^h{Z5As3(w#ME06p(;O zlBOxJ*3M)ZxRD4NMD_=XBSOxQBA7Fj7zHkmj}6D92Z=Wk+Ol`?{_i+c5yq4b;Kq)n zbiCnwRm$$ivSZ2T7~>h8NnGNAt1(&^a)NAXVM44Iyj@qht{&Z*E+9w zi&QrDHWVu;@2}32xk)(X%#{m+@xx@Hi=@i=g3i&>?!uc$IYxl;j8^tg;P2-seR@Lu z^hX&8*iid{KCUT|8r;eRffm3)ng|p)GI!i`JeFdz0LL`7695EebFF5Qo_E@evPF~z z(y31@%OmMUjN`ce*ko8S{Vv(X(rkoGTuxvAi+4(O89vX_9y=rZQ>pPoga zqobf40>@lstKGN zAQxx{$e0T>D1IedTyBjenM?#5&aE|<+cSeeZAsvk(u=i7H1X@o zF7SlrH=Z!m`mosZo^TTEKKw6rW@sKi+p_BS6#S>2EKLXjPcp6j*QALBhV%X2t&-hR zem^vNyahVBK!afn>@8MUNf)*0Yh**ug-D>} zfw7S%5HD?`!3rAreCh$OgHq`$L?H`q5gyIKdrxr40%O#A1C*qt}&z`BVxD zB-+?k_6SVLP>G_VY>Y_ytFjvWK$*D5QjTOhnZxI?{PZ~Lct|}(5<)=p%K_jRK|gU2 z=pKOnPFeQ9v?}a|y3#7N$@3B65VlY%1EvPl^uXDuDj@P^X|@aic>{@|L?W(El)-jm zpdti_XtlNBQ;NZET?8P}2zf+QI30{jVhrhaD>Ro0W>;aS)(iUaNWxXI0)+^}pXdI> zx(-R<2ff-rMM{V)u@Wdo77{ZIREsaw-iRPa7$$P9tdcB+8??S4&O7CA9h?|C6^Ma| zQoN8&!JOqfM*JaP*@1n5W+nnCMd{xOL_5r}iA6b6+r+N>1H6IO`G}rd)Wd2?=@sO6 z9~-9n*2=6u<$OV@jJ~2BYqWN}NlGJ%1BV4G4MSxS)S8?=!CT%=;F7roXAhgtj=ilN zPsAmPL8zDK)anf$3$U@VALMnzW=Fd4T_CJ~oSE1<4(O)+JngI^<0SLco9Bn7M);&j z#N2deHrerc6C;l5&b~9!%)+4D6|6KuA68zW=P_WNzfj&}H&h@+F0cEYO5^t;-$IAY z=vvkI3t0g3fq1vi4m8-RTivf==_rM43m)q`b*pujnVZghA#p!I666imCu^*mTGi($ zAfbZd#T*^0B3-9myIt#HvUEF)#g%IGnBIVZMN~WP+B=%?zND7eKI;IP7~-~1G=901 z6=qAedLkLoGKVfMH8ax0L-KtXrQBICTi<#T(w8)d0PRyqW)I<5F{@hx^zlg5Oh_b< zrVF*TfZv5G8o2TMl+)(@0ViGWpRfrN=%wIx7YBlwkfcg`u;4@JMo{2U@-Q;tBw%yP ztzIX~h!H|If>=aavIiSSjX>r==pf{f$ldI$a4MndA@3Eb{SNE&dgT24N@|$u_2^3w z=`VdGD8)N1mM^UT7p>jsPSDyIktZlKbsNm$cH@@*9{x{%RNdHk9sxHe{E9Z*fw_Z~4xt7ztV_%mZfV8#E&n@GMe-r`?U};d%=1 zf((q9Ha=b^t=42dH`ai^>AWif3ty(?wP?Gg9Yi_`>U_b*vtsj~DN%Ws?a-Go8uE@{ zL3LVgBK~bzlfhND8p&PU{W80ay+8jz?rm{Nvt4gBpOB#O>F69G=h^s z+S->K_+qUl?g}XjDxbEhS>WFR>Y<_p zn!n7?bjBv%b51>5)TEhvjTGwat*a@KJ0h{m>iafBOY0x@C6+ru>R5}zEW60i>#?h( z-hCBTH{T=IklEj(Jwsj+$P|@I{a~bFNVcwDIRR+8Q~c+Oj&n^&YG`h{9w!*Y_DQSz zb~?p(?%^0aoLc;jE&8i7=-<-NOpx9-e`_sB6~xqu`#j0D#r$T1_i;8$U@^m zPfd|*xBdmbhkLBfqa7$tUaqvXO2MV|WNP?Z!l^BubZjm(QDqxc_m{iCK2Sg4SE78* zs5fpVbd?W+egMHEKR|!EK&`eb&P1bTJs1_#iEBX;u^^l8v9Aiux z4a7h4cfcDTjRZ|A(kK!_SVE(?3-NUG#>RXe{>ICp(9Ovn(Ibv+m`@iq8fHB@DPHB+ zfit?3{$k-um`fUet9UgN009t5W~(&_nZ6YYLJo8v<>)?6F`tRUM*b|1N|PbKVHU@s z^5`~v63Mntx^GhhF;Z}&5*`H$Tb;~Qz_qMn9*1Fhl>slcmjtlsJSD6`7vHI#J#2#U zphiWbT?baX*L*_)ab$Wyy%2~TXjQo3_|1Tw4EOh-z3OY z)?jyoJQq^i;RZdnR(W$uhhpR+d)46XYKG(vr@!iRe*PoN2C@oKI!xgen!CFD>*Tz~ z*`c1(NClCP;+fSyMNuPr(keU>GY%BaUiiQVm12>|Yzul;wh}|n1XTk`&+xh()b6}K z>lrdb=Q~1&3qH?H?{>lH6P?%t-fqpR_q87wY37p#DwJ%ap(Znou?}{rC!UdPCw^sE zY~M1RFG39c#>;5mcCB9^?q!@|KI1HZp@6M5)U=fLW9o68UqW6|vFS&xU%A9XCH^iO zHWmrLqj=B`il?uX&?C1zO>Dj}oET1=R|p<*Q(0>WvR!nf`yi73Xrvy@aWp^y(A1ja zOBa2&8#c~Ef-+;44}PUSrBy2q`NfHTL-ZStC&gl<-Ui!iOS7j~Pa>cil_j>N1lU3( zmhKI?=~SQ8!CPYOOtF=QEjOy&wB{X0}eg+i=5~yDph8|Vm zL!hG8vgoBrQ%su$AhDQ}Y>>)ABf?M|{+LigrrJi8^dRV?X^GjEhJ;fsj0{VPavN20 zl@xZ9akN%tbiJ?K(Pw=OpdKj@FAnUpHpdApO-;sC#bi&(QsZW;y?dity#YE^2vW5& z%_jI4Y_*h!Hao{)K%hXPEY?QL(xe713c%};68leljY4jUQi3?5{nL_6+oi;g@(yd~ z0f~5vQjlU<4CUxspy0PvpIAoC5KFo*q~`%&jM(Z^;^UbO`1l{0^5Q6K)DGwLXn8QK z_|B?dzfXLQv_XOGg5i8S2AcAdE!bydd#CtYc590`DX8%xmwR>SZF)ZGScO4)y1e9p#-Omf0Fm2K?-1z0#yZZUGw!(Q#aw_8{T7=I5IfI)E zZBI~4s*8r}2#rW(qRr^d!-r)5gWXUuA~#~>8I(;rZvIfMifDX7g6yo}DRd^kRo$Zi zROicv%>MBNk7ravCp%woi0n`&Fp{WtymR+m*_kA zEyXT@z3FQ@%%3_t2EY}!LH|>f&mkV}{2Sb0oc9OxuN1vMC^<*jH zk*d(?0t7&`l+-4z z#6Isji`FDid|rVOT_f}={b}DD>37Po%!QCm{lmGcSt-4I914LKhq8JzOEqWN->c?S zIK2yv0zKi$xj^fakNQl06qu9zwqe4^9~6y(Wl2qzZU$K`ApbAm9WWet0QgB+a;bxW zEw(Chc$L^)%iEyLqLy^B0-mVVCxtG26 z$jqQA7LvSwbcsrBRzCsCL1M+Lc5h{$X~f`*DyO^qwh#KMc7RIP=|^XPx55~N6q~%W zkHknx^UC=VGJ~K10w1(+%&^7+fwutq0rd)M*a2(f-V4fiN0ymUi&X#~~KQ<{%@76xrYB>>PMy7*ikYBPOpu%j`a5V5%zQzxP5 zPP=@bx5Cci-L$6r_8H!fo{6I6J014&;sJZ-2x(&ms3*B{A4?b=4 zbP`li%gPk=@>q*7jeEAoJ@z&*#FmG7TffDiL(}5%Ompvn+N-GRgUT{sE8lMQI@9PE zgffqsF?VI64MJf?YNJ<=w3WjLEZ9h+#Ni)_kyQ}!wA+%|z`cK2qAu>!|4K^n@aNWT z*VLNtn%E=NWu{{r{`~-cy87qLM5F-UF+d@<$UM(fjIzV`FcG3Sq%{-Drz<5vn%Y@o6+d>*6Vy<4fdu@PvG`(Ym6Z{06Mk}wVW=;*PHuE{4sqH~na4RFiY)VsPXbO5B zK$jDmqvGm3v6mwZExbVa>?J0lW^Ex_Q7mg%(JY0xx(CH9`>`j%1dI zIsvXyoY++Z@DZ>`NC*1y6THd|NFH;Ejj9EwgFqE25vViucHlA4>M1?(pgjC9qD{3! z&_>#IFIPJo`N1Jf3(<;jm8Exk1_7qC=Md`(=#b22B{fX}ydd|_70*cmYUs!;z>y0~ zni?;YX6{vAae1!)+a1&O(m=syUYBWz`VSG9>%@hUB-MCe{cv< z6P|fQ0Bi~EO`NLIJ~QsM24f&4gchWm5!BrS`t+boq$+Ko$?B)|DyP`@%V>}|A3&>a zh=(_%pG)siSC)<3Ikmir_qK7stWyJ}f|7+z)tf=->eXm_TRT8XvMB#p&h}V9fDN5X ze3jQ0`iXd>`TkjL-b^wZxn0l?9OL;$EWcTJH&>Yj z*N$XGpk0-wTMOlDQ49AISR=|&&?nheS4YwMp6L<*@X!xu!ytGPUMiAKs zP;rAx0mB|bi1WYUdQqcRMk@|P?lLOem^}D9Xw?xVhLJ0dID<8*aY1Dq)I4h#3g|>3 zFu*D8!Br{Mf)3;RnX{TDoz{P4dA6+_JA=M5Jwz2zvGB6{Rq+$bZELf;nP#-aS2O6b zgQF~tVm9Bnzt5J34UG!lP3VZP(jWI1%oE4&%3|5}7YX38VeV(a9ru6ekUnQWvwg-M z-uQvDpPaHqDVjugP|s7K@s4nGEfG6u4_$W&-b9LZ@W>f<%Nb@eL#N~{tf&Wglk*K! zfj)GWbzA;l_4++hB}S|G88pDB#BXc=6nrkIt!FIrp{_BHJnz+9xq@lcv*q#DPf&YlS{@`q}gjrMsZNt{xlwPH_VK zCraSwMQy@4wpox~KxI5)A#{$coAIZKyvD-K1EBiObkFK0>JM`6DT~eOU%h+d*mypg^*$r z^+(nb_7K%3aI^=+Rgf7%+W>~RU*LrE{zjA>VK9qE^2?*Ep*sq-n}Be7dvc3eGZ!hg z7lF_eoSzd-##R%{e1QCeTPTfSoz znc-eFTCcaW)^&y`ft`2@F%ySjxurkN-*jIJolh?=!UZbmb^7#?-2Rn3alU#IuV`o+ ze3GzrHI=jXIMvb@L)%1m;a07xX-h6+~)Sa&osy|q46 zGzpN>4zoY&X^`-e<2Xfpp??K|p@Q1((%wb>%&`8Da}>U0bEGqaXDD+u;o|&i%+f3* ztOq-Qdg|z@+wm)*vdB)B;C_)E^`H{2LbYlmo%0Y1)}k+<-550% z63|WiEVTL?A@(C32_aA++INIp85T+|ya70zlb|@*Ezvs(3e3q+5DwJYhEme04nR%w zkc{5ZnTz+0SN+~MG9J8i;yd$ni+F^Dw8T-=>2%U~GF-*qCf)~qX! zeCO|C4i+W;&*hZM+Qp*(Zg%KlXBY&@@R9R`iu7|m=E_(Gmriq?cxIvNLf2$?!=S@m zUAfTJ%cWo$`Fp~Jt`l84z9ruftA)NB`r31u7fK!>Zfjhq^AX=dFZ^BoU3Y)$B1-dj z&3AnaFE#|Y?sdspfxhsm%Yx;v9*%3|a+jA2(7OJy+&PL0ULZqp4PD_Pk_WnOas3ru z!1;bE+7#qE*Clo(8j7?z%Zk^A^I|w{ZacgnZ0;t!AcmT_k{D{HXo%wiRr zJl8QIoaZ{4c>C^8YO9tGs|*wW-vA$nAB=F3ts<|Ju*}Mpuib$@;w;GZQeC}P5f|>X z%+2IGf7dJU0&eYk7nd;7G~ZkO>U3Qeu72$v#;$(NH1Do)oIO|vqLG_Rl5ygKMgU*j}Q)*ABYw6(7tZHA-7YRLayOCHU6{bj}oR?yzb>Wxw%YON1o5Mb*~M&ZJqOLC)d4ZnjE&%G(%pQ=JE9|dCfarceuE& z+2A5t#&#`rHNuN=dtCo;`6zYj^0vge{_uv&r(4iqpSmzNy?QLJhc>-tl;xY8K$mL8LmI?eD#1`zT8O~+}52= zliKy_plkC^r@{Su7kM=Q^`o3!PJ_GPJi2oCYu|O>?X(=f-NbhZgZrNS@|@gUZtW(| zCxrdl*WP41zcz>cn!z2ea~j+mFAWZR=YR`ZQ~X~eD;m!oPrUutf7We@*}HA?me?QK z{zD%92#zGYu`4yAYj@fDhvC=14qg7|_KOd$&U$d^S;?nM>(*(i+S^xnuPsUFm_F;z z_*MUT@0W+?xW8{0b7+nCuKgb$T`{@u!Ee=T&K)}XL+|$7-XtshHs9=6-McT#bcD1P8k)pIc&?(adRS1JfZeno*5{-x3?&3g(P@Lwd^@v?09OV*C-`hnT>GMf)0{o&7TJLudtb+BU&#+f|& zR3tl+dR*Lg?|Rc$OzPObS^81#Zhc|2y`}D#Ogj>F#p>%7vik`~Dh8WabiHJudB2ZbY#GBGXu;3XP0|ID;xN;?)Xny%v!ufr%p(-R5@`ctUxT4*qq`LI z?;reUQz2*SFLGbi=bznS*z0y+pO-S5P8b~tCt?i7SboogDPcR~1!}-%@s9I$>x423 zuAXy$#YV8QqP=b2U}P_jMr=N>_2#)z+6>7}^p=O2sxn*MLg_!1c|+Iv4~__Z77Av* z=mLXbmu618*ZGF-cdrQR9y4q?S|fcvnD(`p*PIsUQ^(owL&qvMA6?z|SNx!0Ve1pH ztD!plTsp69lX-txP=h6~$%B_C$ni<|aq2S<9;a{H)RlkxY2Gq)g_K3M^7j?49o)<; z8B^Jp(=tq9udrz96fIF}TaBi?tY%P8QdX?`+sJFsY~OiB?-+PE;o~68p)KAu_1e_? zd)MY0qlWWO&LWNL?rkp(btm<>7e-%AwnqPE#;8I5V4WFuvipkce9%^cXN6_Nt3G;Xlj#+c1gC|4U z-O`Kmh9)t0=V2QprbeM4*2e8pZl@Q74t3quJn)TX(*s-gS^pz`;=x_NRqP(QP}C;0 z)E>yIpJ|LwtMW1i`e2ohuB*$3{)%Kz=2$8M*=wk$SqWVwXWhBB!?UvW*C%|;8$)UH zSK{|$UFDbnU*2X4=mA?|cO!#(7`bn^qxL{0z#69gnxJnBpM^tfsM~{Z%IJ;Kuz?QN z3Tc4R;b(r%iuKIlUl6T`{yqGKcN3wD%Bg)}5IEqQ*;LEEidhyM0USEjJU*JE) zz9nAPtvir?&og>nbj#R6E|^uPo9BCtnF2gw_X?fDo?gbzUX`sh_iNX!rw{(G1}m;y zE9M?B*=sOM#?s3M>y#*c@QD!4p`>ixRlk_hT|teLIB+2yPh@&??5c6}X}kv=1>L$W zkwT#luPtfZ?nue#_>GMhS~?0=m>d4Ne@eSxEV!tL(J{^S;p#0#HJo`&spC}Hgv-g2 zvN4fI`wZKS2Mpb}!ssvD@O}YyQ_HcfGVfPk&0H8L-D;e&LiMGtNuYnC^RxCu_h#Pv zC1X~$;=U?-_vrKw#oHxqZuAF@>bs%r<+_k$UBp@oH|G8eVPo{(Do*uU%2xesp25iM zc%S8#*4Ay?-hOmet0bhQU!b|X%O2%v&yrP}dUbeFi3e|t@@Pum^;irh`c(R7w-b2UolvF zKv?daeDR9*uDixR}vToLpQe)p+c_dLcq)vVYN2L-lAfU#K`4>Vjs$_f@vMB{=q!{N(|P}8Wr%y-qPi8~kw%O)ILhZmgdo|hB+N)WP3CFw zYjXdXyLS|`y&+npsY=f4xLEcx|G!?~on|}gY!Bn23Oplu;yFe3UAvn9-Yng!K6`HT z>e^poqb?7=?H+l$N)g>PF+A0}ePA4IvZG73<^&_5=*3><1?z2w`HUyC3;fYNUMQo1 zV|owE^n}O<)A*in8*^Z)v}xg=KBgY)Pv?bGRz$5EY*%e4pCNsmqEGKTwh*F(k7=+g zi>cz8GQj>-+0XCJ|W8tY?5sw+Dx&e;K}Bf)4uz@-lQ}A8FSXv3%UkrD=ignMyfHx6QEhEaI25u`H*~t= z+)1rRRCE*%>-Cjy<&DD}gWb}d#*TfWf!TcHmO08c(}!aPT+RT4Iy885;T>1y-|?zu zpM6u!^$Wl2b1ULyK5vi)2zf_6)MKJj%UU=G!`1v;pM(qW0MeT!=2FZZ`&Js@uH0_? z-SLF5p*o#NEg$v~3>PPSnWs7?h;HuPcUTPZPJK4|{r4JKMQxHP5`pJ$xGh+}{;g3w zJ-?__?Y<|Qy*8QKy}ed}7oYTH^b4dD`kX4|KhOn_DWe;n58gE0ah1P_mGMiPswIv;d~gBnMPhqS=>rjF<>yA}aw+_M zwhq6lVfJltRKVE$9&U*@SWsG1h$+Z-Z1LCDt)Ac5BT74?Z|bEdJ7 z6V6oDgPVkiu$9$5xXOdSeTukGZem#*6_dfSz^Rrv{R=qz_!I9m{_LYm{cb8VElE4< z*h){X!P0wG&HloDqXuvLGfJ}BPg-4CPnH+R9sk7Aj`$>S?lbArnY``ozNHW6IwC2$ zT(P@OF_7}psy0aItpAj9v}bi0`ek)W=5XEi8-jk%DeOACDnx0Vuu`@DWBsYll#@R8 z)?|I=u&?9lRKw%2S;{G8;my~$#l~<$#SeCD0xSJ*58Bzxfl*r6`aL9iAoz$UicIk* zxOZI9G2Q~~T1$h?dqvbkb660gQ+`GKSlo8rI)-UF`$SwV?_}uUX!`h#bj z6J%WpPHC8usuczqZ zA~~nEiZdzt@1!A>IkRUj_Tt#W!ImL#UQ*juIymUGh!E;M-gR2vU;gr958gie*^5%% z^{I0Dl=!H1>LUxEI{Ff&(`;UlwM139>lUXz!6)ls$-XrOrFz9&$JyxbnI+Q&w|q=L z(kC(dL-xY2G^V9tM=?2^mX&ocec2nnb9TPs?h1;hH@G_3N;(uX$1nt)7D-~ByS(yYHGI>>BITj>Q%QMalfA_!sb6o~@iBCjUXIh=)2u8+Y`bD);x4 z%FtqbRv(kE+@<47vW@(J7Ix71BrCVsIA~64t3T}5iiJ@-eOf|-Jeo?h>Vu}3shu-; z7vPrFPEY3TI6n?n0PzSiLoE^2dqBU`)N5xQ?OfNdUEY?5x0jdY{#JItfwdR1tUZ1C z;(<}D)?@m=1dg0szx$2`Q@cGgA=-A_$J*SR^xM9tYZV7P9zNLP2-D3nPwIz<`c!{% z!jycrfsu`IpHbnr&7dIT!55HE^H5x#!Xwzo7%;a3onfXtz-H|)k3XGKclpv zEAxfNPF{Gaxfa zQa`N*PuT@dCIlH?cxlG8Y^Il7nX)%Ut!=Bwtk`U8D?IhWT(EZvXKz%2xLhCK9d4{K z*&>7PGdH*P$d#pjOg2R?6wrslV{H3w@8< zPgxpKiSyrNR@y&*3YHd1#!s%7ANHu9@eUkIQRF;#6W^HCBkh%yQR;oXlj|evZr$;8 z6nXM)3zkNI=XIySL-31_NER?8I5B6a)AR{qKEl^ahT? z@_2GU!XRh5^!a&f+?09@`_$fM*8c9;S=1J)P%T7B?53$J1KhigYX0jr-uQWI5ByT2 zI>Yc{>6BZ^`KO~Ov}~~lD~&t3KJ*w%qFZc+$Z_l%2;WZdxF4&pWW)`eMk3^ zmY74=Zex~^Rf7!}wYR20cAyfE6sFeibcn#Jt`S*s}P7Rz8*rxs`r>OV2{#~D5it342!xlm;dX_VY+Q(1kmwkbx# zA)~OwO@6cYmt$b>{v*L_$#Y4q?YHSf1^()Hn2 z)tbS!dvF5VGk>G>yJ1t)1H1Xfok@lnDMr6svGJoaqhBe95yQiBbmi9bZG~R`Qu@qv zJiXlnE3*7;@vv4~e`*_yTx+3LR(WaJ%jAjYPj%^pKBiuLdFcyk`9$WhZz2|EX@D>1 zz*sCT`>4ECIf0oVtJa?0=YXHN%#bp8j~(!ZZY;b_AN7gqhe7*~H5pUjW8xwiI3Ij@ zG;J{yI`OcL_qn6hk@|HG5nOPZf3-G`3OqDir|JALYPDy#NH zS?rO?R^8&M=H1QzSK!TSs~KCkkX|Z%o?}#o)r#1sk65o%#l}Qk(_@QLPwVFb5JBP) zu-agqp4btaxC3mC$Fb%qS31~x-evfZL8VvPot@}O7B88gMy$93- zT@&;9hm^73ykSZki?<%UYp}Y1YEDazGZplj*Sult z^tNq-@Sjl3l)Vb3wr#~|X+R!@_u%O&iN0K$bZM(l+5PO0(*3_;T=0!5g?w??)N2eb z@f)Ps;BQcbyue_fYPo=ZsdUrSw`G(MAqp!;O&8o1@Anao-`nxIpt{`{JmLS)_9kFW zB;EeMipn@DsHli+Dk`oZqOubm7j#rIiVDaQ0f9jTL}U+X9T!BlQB*)6(Qy=!O++>W ziLymmjIu@90tAQ$#Ynb9<+Er3VP9-Z)d3S z4CDwA$op9okaG$PKsFr$`u{HAg2}Pf^0kl^!2%AQu(pfo$##^r@Rk zATMJ*1^G!~4#-B{KqIFjIG~?oy?)SgKC3W4z^fp{-pa2fbFnp}HNdm-B)EIp*R|HG zAi(|@$V%}bb1GeT;x;rz9)>-~S$CkutA&NV`7PUYp2JgVZ_Nien)M6FafVcocYH_( zInod0T2?a1k%nZDw|@W{$-ku!dL}Ch^d!R)(05q^o*!ui@*wLj$l-=XAnRE^FRDEi zsRU6pq0Ixgs9lp#7;l&bg*#(1;jy!kF6X?-ZLF^##~MBdSwAMDXmH||7RV*6VUS6N z8NI3%6yKkrLpZhLel5tLrabgWzI+eVcm)EYa7zy8t1hw!EknP4&hE`O*)aiiD@2BY zT;{?B`R3_G9|r9GT2fY+ zG`0q4SHwUg?{oHo{Ns5X$SYeA&{He&LGQ~s3i^Tb4xp>pf$Uy!ALK7N`$4um@5qy5 zwSLZkhIMy=KObU`Lc{Z&SV*z#DcejDU5FzZic7Y$}bHv+?Ph6|2|gf>q=UVSR7XwW__~ z6(IN8JOX*$eW1Ogdq8e+{sQuZ%~O!I?gKp(^#o+H^LvnoY<>e-dwI6ty06ccQ+_RN z%8^a20espT=$2g0g<3EEnJvf(zZSEl^Fddn%>rFZ52^JEaILW>=Z9|T1=lrVgP}%k z=OL)^eF6kNbW<;Mlo(?Kvb*yH$X^mNLDq2tniy*fva)k8$Q21`Aa8U7+A&52WNT+3 z$c+gwVM4b)1==yz0|DK@xgYe}1eh_Qo1X&S9!o(H%~I07>! zY>^V9)h)JiU!Es9*0~h+WFif2Mw$!~ z#6mk6EMnCxDP$N`iu6gZTz)zNz8}ayU|An{j(|4@vJhBN2hynE{DDj=Eb9a5RH)%V zHWe~bevcHn=`}#250W z6CUQw(WROoE79aZUOPen*`wGRWJvI>0dX`Fke7}Gfb3d)669q*AY0K?cWSPF8o_{W zd9d;z9lQ=g!2Kl1?nQ%cH{(H9VLbu;X%HmHBqK-g-YtR+vMs9!@?*wOE)4n?Rw5uV zL9YSPCqid?Z)pQk#EJl!7*q_hfd=%oH_`%R0qZu%SArlv+HKPSdigDRkgv0@fPA|U zfdmP6g95%hG8FU*77_G_LWr&1_94LU-!cLD2`dKV#6rlAcDuZRz8`4^au4f1$kz)Y zKicVeLw~v_gdx-vK>tY+8evr4_I8v*}mhOkguHd?}r z35bC^7RX4&2<)WeYY#hls@eIq3@)d^{3X*qfvn+s0%UhJTacGofE-He1lioz24o*K znC*kg;UJ4>Z$X~v`xB(kRZ!{GuFJ4uIzB_dP1a682o<8kJiQTenKOJ1=g{zHh`7m` z35a2Sq#4A}qCx|9|C9qyF9|#{06|e#B}0E`6*@aLU!;IfDT_?tz@c4f3D}_=7r-tK z`~>on7LZdb13>o3@d7#IJS>-##daXOSDpgdHV2NUfdS`Xrl%lENuaYU-9Qh{fg}@1 zI1fq2VUa4x%9RH|-k;+HvhR7Q++hg^a*su22u#Cj=Qi+r)CQ6ac})|nysW4^=w`Ze z?E_6sYuZZKb7u~OJr%p7pb z!dVL5eoBBt(m(P#@_&`sq0RpxueS`mO+d4wBXR^LOo?V3Oc>4ba_CmL-Z4n2$Bx)Q zrdLw}nN&Ura;lyq$hJ{1@L?J(ka6XoL5|lu1@g%#n2cfSE+8|@zk*z#cN%1eD5yJ3 z^D)Sn@^>J|>KzB!DhleBsA+*rEk}ky&(?#P&gZVkhcu2|0JBA6a3iazwmtgMIYt1r z;#WYpdiwyeSO9rZqH+~-F;ejmWTxIhkg*Hk9An{*gHWR!Lndxy%8CZ(rpaJV%*~WR z4w;)SgMpZvErWb^;~4_k_(lc-E8xa+83Kd7&_M<#m8wsrSjd;>C2)%4T_|M0>!dLL zf#T;ZDWn(G94RbP)ifz2M%5xI9FtU^NGb4|C(Y{JCBotDAbXc&Bj9}WF$B(GqHPhF zFwrLw2u-xZf1A}2=*0g)TK`vB{rsz;NLV-MDSM0e{UC5YX(tg4gIlCKd1dOt=Hz?3WE@aSC~TxJ97ddN9`McnW(N3 z3PJgQvO4mAlh*%-tnLtziq;nZ0#4hABoI8@&Ho=I#X#=n!+|Lv@f{4dYf|48ct?Fr8zf1f%6>7_*7 z3NjzJycd601T8FIuB}vbIkglg$)*E(iRjvHsIddCp-dpkm#ZQg+ zcUirA{da1t!ZZj&Fx)-~cAvU(o_T#_zW z;ZRG1qEptq94M-9#J6Vkrp%OS)k^FoIt${+1jRy5;AL_C_6-7>gO?g?)2L@rXUB+T=scn^H-TOZKN!a zP0mq|Hdz^6dEoJG!W=3BavZGW+LVW8=7 z`TQ$0h4a>5+qUNBnj3~o4z9VrWBa=`;ilhj_$}dhRod^jR`&n=@V47&kJLEtkUsaz zs}HPjNj~&6(UrLWzO8HY!u-!pv2rnnop=3oih6IDAR0kk*Wc`x%vSng#o~R7_o~fX zd;5o#Drax+)tIyN*pZDrCywu5=)dFRLH*2E^@j{f#`NDT(u&giu(rNtJAF-c#>>jN zb^|YHGcA%YR2jwF`<1CHnvVR?Vg2vAi2NHqqAu=^uVws)ee^^-jr=Ej&G>hF{a2@v z|8``i28Pst-M0GL;yp|C%5U#pvhnxZdzKq@AKSgS;_h+FbtfBsvXG13QU9Y!%BA|l z7`X*{r7KuRw%2aqZFyM(@9Mv(PzY7KP(Cj;+3)>MgVvEZO1iUGuKee8ME=Ws{Qof> z_x$gB{a2@v|1uw^dVS_UJsq(e?Sw_8H&@+S(RFZD#L~KVt0L7#H$1%Q{Nv({sdqM+ z=497oSZ6g`$A}tLPTVH+Jqii-da%ImAl^!jnBYI_O z^S9)bYBzm3o8&NI)SaN|TRF!X-+4b&BY6F)-IzVatM6V|6S4k&(2_&z?_JvdetkUt zd%>=CcaOa_d7k!!$lvkl2UYb;pZ02Mt~i@;%zXRXrTR5FZ; zcelS#q3m76zU@A1poTGf5o;gVbRFtW`u&dO`Y+vgu&aGGK8pIj{n*j1xSvnksc@1sz?) zT=oC@8GLx2>j`8y=G?h7w%O5FA1nD^e+xG^-}Y|XWBl1)Ho7IaTv>N&vfMc7d~UUQ zxEe1}U#GB()_ReyMW6jSF?(Lu!bjJX4(-S(k2|l| z2V?)oaB9A!ucqO9k*N7ulcihvrlUvRz&ib_?`soJ)V=R6c)yPHL;LX`RF)M#{_pC< zpaI1@ryR}y;!4^ZBdAePwja4}Hx%5RIKzaub9#&f>zpIBZ=XGWNIUNQ#rLVd{xR&x z{gC$hee=C8ecZ1YCSG`Tfqs?6{}@obtIOQs2dml_{b+c5pVDE|h_!J)8YiBOJ8XWv z_{p{Hn}RHM<~8sf9{l_$TH*EAN3n_vw%2UXOgwW-rPt<6#4_`o59?b7(7uarqVYuL z7qs%;>CX)4_53Ah?}pBOOO9?CS$pTmroOXxj_L@Oj(VX14Lo6W*o^D(+x1<>|7wh8 za?Zc3)e)&(ta1NP*l|mDdW>fGY2P%sw#0Jnr}8D(HO#et%+IND|6|yZS04|^JB)p# z$Y(T&|(|2gNGkN=#Xx92@gaEh68-=~J;T8f2K1?DrO~UT(cmEgPnqj?~CxV%aU3Tz>tc z4aeb3BVKOStflc&SNdODrl)qgW|32lfE8}O)CB}a&m}MgO19AGof8%ix$`V z{C@BGveM(Bcl}??ec?Z|bjiN1cbginzub3m-}bfFPsH8Yc`JM?(`n<)%lFr;I_|sj z^x5=|PUP-akIWQNVkk*B7AHLu#BVF|W9#$6sQmUCwh_BDzks=o-AoN@!Wen(Kb^DT zaR$jSKg!p-2{*6R%aCo{FG@boKrm;lTZfhNm)b@1r^FlrWO zz3`4^pcDU?V@udPUHM{n0ToX zQrs1+&YsCm8h$fbz8pKbWJnQz(O~jJxcBS&;YQt8f<)?Ymj6u`-}rX(%C?Q0vu6?m zzu-3y?}q38elVD+sLaLJFQ4T4P#Pz-GmGaIYE#YGbuCv!k?ncjQQ>6rPQ83g)prG?6qdOYj%Rt^QZCc+_K#vFJq;|L-!(B6!EXfXP4PtD!wMziQprxc5_O7Xz5+a-L6W2_J>L}LU{9I(1k>M4rUiwG zW~p+62C9cvvPR@0MTHtKKX=`IW~HiVJfc2716SJiiP65$R6QSGW|L|zdl`cW^v~V-YFg)F$@06wbB0I-`3D2XPVn~=^%gc zsX*M-4+WHBlP;Ba%8n}$g~@#wgRqW7!ksb2LElSTi9cHh{cKwAglrc09@5lCg7{AY zI_1Q|QHJjI>^-T1T`83o8wuw|%5zvj^K=^mw^{~BwZe$Vwb(!mkuo=I^hZ_s;p^6Y zFV#C^M$){J-_i%H%?1R>d}c6pr{WC7R74VCyP2cRFJ9?N>1Y*QvFIW+R&i(O(u;c? zJG#O{8BEtnGtO4{OXP)MCx2FKW_tpTj^Pu^bX$4nIwHg`gKFj8RPQ<*??U(|`8jfa-HVz#&-#lJ|N7C9( zw#7cqKG@3rC~TE+F!RUdQ(*R2@|7?} z0zG^e#z6K)OSC!VNbK#w!i~ zP^{s5#~~K3FwPJ9PBFZ=Jj>+Cy$<)$!>m2J`5|^4N0kdr#CoARN=(GNaqpXYfkE;W z!A1$bM5fr$^J3_5p%#v^sU^ArJG#HMKK94Hv!hEm3k^l-0oOzaHIcD<&op(A$++Q6 z!r898kxxjUY%bT=H+#tU`6zNB*5!$AV1Q=)Xq5(kH?Au*#_HV2zT|7}F`lQ3TeCRV zg*Uau*Op`NCK^II@hvV_YzS1t3HGSH#g07*D0|dKwK5aZ3~fWldLrC~!(;1ArK6oY z6G%M;?ZYn`L%SQo5%6^`Kq{pxK7H*G2O+A-QmmHtnbs+({yp=ZHli+ z2XWVfR%gE;hQ6Y`wX&u(ct2GXtQ^J=>W>W%emz`B&fx1KIm}Wm){?&TckECVT7;~; z&^=mC;K<=TPRy=91i#N^yy|U|%?byJB7u zJGx)ZSI?YgZJfwEGyEjr{a)l4cI2&Lr_JC3$&=VMxO0L0Hp(offR<|NW{e4W^`Y4} zXxKkMHu%A;h;G-_bBo6<3odADk@?lcDw=tWAKy$f4C;8SF?=v3gBW>SX`lP>e*5CL$|F_M<@s8q zk?^rSxa;Cq^a#>1(@zxSA+0`#R2Nt-$6B&fJC7XUd)B_u`%6B}>{I-(Q}St(p9_x5 zQ`pVE!Jlv~JaV&tt-*zIr6+g=UdO1pBT{$8hgBbcX_Mq#ym%GyX|;g$m6rKLCv08k zR$_;|USNSqb#dnjw{$VLC0j=K6Wr_v$nIwCaPZJMcht8BAIE|ohZs+LxZ?Rn{%H4n0jzuxBl zHb$e?65L1nW8&-iuh_oS^W)fPY^$tYvP;o7|!SG5>&iM8-pVxJ~Lc^j{bHBJ5m z`ADs$)~C;WQ`oW*hL;yVIFYi{pdb_`@q2f(Oxm20eWKFpQVrT$<(8whGBtdDNQcN% zRQSeV_@#WUI<6{=%Z1GmhWoH`E;TGxlvD^_hH>NF5v8zoh`{I-jrN|A-)+E5kRR>2 zX)>X2Ikqf*ALh1je6LxItu!Lu)oiFgTU(*c=+$A|o*>>rQ=}`5{l-b#v&U zGv~DjXwo{1N4gcODZE1D1+y`}{bx$Qr?O6Yj$QDNBoagNke?K^$)H6XW#H9Dk|A%r zWIqy`vq(cPQ@seUG5yAmM%-4lUdR=c%DQmpUcZqrQ=CWi7Ridbqr(W4fKKno=G9^w z0SBk5VBTMm8)Gt~a59lnmn1!dbkt>!&hZv$V}^Yw#slS%WBWfJD#)LV5+uT;j?m-^ zCl0B$T#+5cY$5i{FCn@9hI2DRbgmN`n4j_Vohcu?jJz58Lqy3|HRZ3rkm#&J549x4 z4r!|^`z_-u)9Qx4RB+>DWRI$0rHZSd^QinRdR=OEjqeqodZ&$;VK3v1)BrQ~%&x1v zk5>p@6yKYLU3sg z@|Vf)$Lnt^I(+Rgo=xM9BosR5*j?H~MP9)oT9 zE(k&`XQzE6CS9iU#R_<#IEHOipJ+;D711a0j!k|^7tCleB<5QhkCk!Hi5nVICeEnq z^n0mkM!iZZXY)eWAVCTYzars&%=IT)S!}%EV!twp*%&h!LSTeme-^-fVPC?bObBavAwf2eaNhhOZc?hB<51$hD#ay`2wVPw6)y|liUH&AUpBTjaF2(I*yCTbM&7`flK_JH zQrbsLJBuHa>c2#Y&5fZa%jJcoEK@GV*L+ms-X+2p%jAh{TgQhNm&5IV5+m0i}{3>M6!h8k@I1`J%@WbutJ#Dcch6qf8;lR?<}&y z;U)J>BymJ&GM1w=zt!PIdZy2FhfF_DiCLP%NKa(pm|R$zLx$2`O-|*hTl8`MDqMLg zhkHAS=q^#0N*K$NJ$P}HO@cj~)&?3pz3ns-Xpd;(FG@=4kW*xPZr0=Rz_0tV{FJk( zkvPLFSB@=?d6s;dJu$l9^iKA8U`F*`DiIkT7!T|?jaYA#4M+1<$fsjvyi6(!-)+7? za2zi_MRtq{is9=fwx5+PnMj`z*sNVH+4Nb_#gPAH?U3DDsZvLx=-N;8pt??TjRCps z8iHo+6Zh={?>k^3TyWJHeRGEB?@P5s@eMi?yvvH1Q+IIieCu+>ZYPq$WWBU19%;^u zlN>%q2neDM%4u+M4?HgtB@5t>m(6_MWMZB#^H=d3gXVDaA4k;r7Co>-vW4lfD(jBP10SxIOAbdAPUx;1!YyHLG#`C3 zBFwE#?+h)L)i<-G*a7Qu-*X~F?wC+cu1rbXC&l)8YAhW*>`KlN94IktmPNSK%3*Pz=^ljMFS2>2z8dA9q}Z|| znU#p0MY!h0^j3DXq`xDy>$a#=pYIZhD~c_?APevi6&zC( z6}V?cwZhFHY;$D%O&I5jkSI27#ww`ySr0|V$B35>K2BAbkUVbt0m6-=Oq98hiuycB z#$gd81%#EBAn)`F(Gb^7ZnzzLIiTFa{FlzCxC=DH`w=oHs_=K}O6@^Xyh4|pq;McH zwv2HZJ3*gsfq9!9H!@oD_@gvP;XN$EkRhaF`0*jG^dP|2L zqpSpWoQ1%mH$2!}hmTjo%7)E6$Llx9-c448J4p&>qdA3i~TY#oJRdd93Xk+1~7W+6@sU{2`+Ncy>e@Q`mM>|%W68O)a~?T7a@c_vlN9VyGPWnXZD_iEZbKHq1nA&kP7 zn7CE#H@V9DW@b4_~QC7+1 zxk$F5Og+f9*7RJjF8MxpK`W`qRZ7-2?~aWfWxfs69SrWRN_qFHylM=u<~9}MIo?Bkh4)iSCk`ik#`WgT4~!EB zc1qbMVG0b%_9`Tte$kE2&8k5ZZejYTn#l3 zEp*#ljc7Kz5`z=VG5ZPfR|MQ+BPTRW!dxrj1d~-rJVAV%4%rg9O|s-ljy@I#PF^B~ z21v=BNYSTJ0~%9N4?mbo)tpuANR?Kp2y40Fg%b|nb@c5QOXpHGmt5n8s_~j|0xRw&kl_u{|XHWuHLryXS@&Hruiep3I?n%i)JbQM~>!*mpZ0RGd z;$e}t<#;zjVjfmOFtd#lnbz+gbHir@a%D`PGlbqx{JobsqSZv4iRRs3H)-z~E- zb8WhsF*9z_4+p zNtAX+f_)(5YCzQ<~ZrLP3%p+c7eakdhK{a7bve#8oI2@NlW|>~JbJTahc% zD=9IR`U#~eY~-kJK|F%ZjxCTK@gZSkfyn8P&DlQws=F}tpX%{utWWwHX8gfeV!rG% zU0Y-N_i3@mf*v#$g}$^FU_ypkG^aSxgatiJ^q5VNeDY&TzZUr*|0vEOKDPQ$-x*e7 zu3Kx6$+}I<(B{1VfXy1jP$tfr*hav&I87WkDs; z@hoxF_^Ys^m~qbD`y7v=sivWcVhy%?W&JmL9O-7<&&E71i_aDrBohZ@GegzPvEw_a z8pdWt`Bwr~^%RXwH#>gTEZA2vAhQTL?Z`^iX7G*z10os;YX+8~&cMp( zBFV4gQ(Be>L5=a?Df@$Q~Nf}5$?)@+Y&9i94-O&j-P z%2*Pw0r4x!R3}1ft6kM-V`|d=@sO&Ji)NPJaH2dZHRM6|^l)ZqGbX|H(K?c~&9q~| zgT!M0KYgtCMbagQ>7C$8Q4a_o;!*&<<_K6Z-|bsM#bK zDs(9SjNg;c(dMc6Pb>Al&!&3VeV7k3V!EKa+58(JLf*3b>da~xaZ}xcg&-nmPOXHg z88F`cgv-xCekF#TDwx_A>K?7jE-0Q5 zOgA#s)4F@U`)W>R|q+sh1Qcqw?aEM6$V(}(<6bl1PYDt`}8bC zV&lM3#ty3Nk5T#~kY~-l_;&nl{9$lfe5pQE`e%OlmT%S4$$u?2bijS<(Ai^dCUB6M zC;e4XQKf7wgnCU~`R@T5Z8G~Jc#ll?vM;zv`efQ8PU^QVwWMlOInz-b%|ocAXvAQR zao)!${V~PUIjPLZKr{zEVJc3IQ(ti7-zvgMN+Lw-rR~3GrjAdoS;3I`yFNd1PsnH^ z7ZVz0wiWqv`=6o>tgO@%d44P9XpE%<7dX!N?%MPWmsMTGqE zsinxo@;?!Ul3#oN7_aG(kJ0+WNzjX5GuhnJtz45BpF1lHCUn`~y2=(K5cU{4K{CJ( zh7{7m7Nfa?(EqL5{nC$pVX1%A9AonLD*dsRHSpn&KfeCY#Wof3c6*G-{~#I@Z4#y= z`zzHT2VI{qd`TR443T*M+jKSg04vA?na(EQqeh^gWPo$Y$ZRWwBp3vIpk#nnUq9Mx z&Ym6-I5PutFd7dxT9dEqtgNgI>>EI5ihTM%%`D zW1)d)AivGPsUO`T2!$zBd-i7+LtZMNUQIdWL2jlNw=19_DQcom&3}7V4?**f1p{>n znz=q`MV{j1siQ%WFD4n41y;g~FiFM8|%tQ7UIr zcII^qBlc-QOEvZ>6V4gVzm8$jQ%T;s)Z{GocsiUaP!qF85EBPFpI_go#SDCbAmft) ziX55|cGmJ$3n#RhJ{>DD@Dd^w5abvT0j$iE#Pqxo&D2rb&jXHX3UJ z??jdDb&CUGQ_>dJ@W(IRD&gVppT09RJ-^Gfva|DL+I9s+($N&(pljzJM3rf|)dRXQ zNryH3?#q};xW#)nK+o-RsqFmpGI6^?EU`A(Hz?}-{ire*w_HFsCv9a7fBrI{5{}T` z_X6v^%e}I59bN@(;^5 zab6unw`vVD>YY`>{ZE^+URWMJtJdW49>wng{shI30CXRPE~1b*K$}sh0-(&h03r8K z>PMhXq0~8)GGo06@I0IB)|`1S)3(WD&^V*s*xx4ApYy_!)7W|aozp86~#{ip8o;xT`05*pcWJoAwUhHol^&DtN{HD zbt^?*!L#6SrN`4Y?=M-dg8|uP&4b6n^F*QQO&)ac#}WJ~0e?gdozXAD&<1eOzyuu{ zmwAQNIV>GK8kWq04Fm2PlzAMyYt9Sl~h6 z52y!+zC^eVT4t3sryLK@Gsy$_w0hIfm~lp%3V5LpUbr_prF_ULGfuGzSA6#Yjbkuc zDF!N4Mk_5H_~oUgGW55v3#xax1Jxf!ov^KRLQ-^4rC+;%EFk6Z#yS*SPleSpw7fKy~}ir>&V z|79rJ3>umtv=upMC1hJDgk~?gg@y)+MIHPE4Vs~`p#eXJ#)b&7X|qyEO$?x)#m47_ z<|}ye?ZE{BxG*1FPzD!t8=VFnAuc5lmr#fcAC1d60IJ}E0l44;acPIRlvsspzH3M0 z5{kBq#zhltwrt=k^3qcF4hk%wK!`d-LJR7n%9HvjUD4>GK1rY<$A!I-$C!pFQ=+j|{4g;d&<3D+IfDhf3pi>j0 zk0@|%+ZLXuYFy(qcw?TQ4cVzo zt;xF(mCQjp@Eu5tQR#P7GD0Pkf`_OzdA~v>Gmt7#3a-~}^3FgdlNzU#N}y7G%MfU} z7}YSKtw$qq4I=Si14Kd&W}tyD%)t8JzpQmlS)X2JeAE%jeghX>VI4e&?leH8J^Ei* z);Bq&JVgN<0FMB00pKYBH2~NGkPCnt0JUfhj{$H8Aj=r$e=88dK=6R*MG0JZp4~&3 zcgw4mZ}BX+px)$t8^Zk?M7E;;ML;COY4HBDvgWO}fIWv*dI^9;0A2#n13)zZrvS*b z0U!;4ivZjM;5h(|0Hg!ZgaT*{NIDP!K%@Zi+W&z^0U_Vfmb?%+)h4IGUC+y!z3jvD zT7C!21F&4cdZD7N0N4SLj{-3IEl&aP0)Py_1OVy)m;fM!_0fX5;Rl8BP?!aUZBR%C zHzuATFh@$DvlCSl(Ahv>NWf5lkpLqCMgd$^hrXCRgGC0>82S}}M*x%o5Dq{L3P4{> zAR2)XjiCepasXffKm))MfE2U_a3c_+F?1JzH0Wz!NC0x$maGq)JGlA*`jP^DF-Zl^ z8@OWN1W?g@0F(jH0l)#GL564qLNtb60?-4%W&o@K$U*_Afeg_IglG)C24EZjRR9bC z@P1x@glzXRsk*uCG+>zuh-V<=)S(#QQh*}^7YHs7r9oz~10owLLIAh|z*PXk0Z;@$ z0{}CqA~XY*WDo!m0K@^13IG-WA__nap;-XnQ{0+M5=wq*8hQd)HDK0&WrIVAV>%=d zN8la<=LQvJ0?`6QAP`(2+ED=Jr05|4P5@{^VJsACLM!IbN*K5yg6TYjg917fkf4A9 zF%Pp%O$@-f2&ARc@)9_Z|#LVl3Jev$$ZkuXrhL5+o-Nw6~pb|#>uXsww*py7!H zfCRwItJ0nq0av?god)MFgeCp96qfWbx_sB5>0tp#k5K6=Dy^@9gU5wVC;g1JVJBG1 zKR{ZEUeWs^KO_(q~k%L?u;_Sg16K<|y>= zyBvc9LW12AM8LA2BhYCNX<{P z%Z!oQp8(8(U9BJ?^a8O3%@{!B0^tTk?J)py0k8&O2mn(wVF17bpcjCxP{ZjLa0vbh zfKC9`K&19_AbpOU&v_Ye7*g?lNX1)E!g7BN3-JgnvM&(Oi-7eYFc_PGI0Z!J2_TAq z_z{RkAkG2N2!JO5O(=j?K?cAQfHnX^02l{A6@Xm;c%6U|Pdcj_pV#sVFk8TQfGr1X zD`0kTsK|!{mX{Ue1URA||D$IxdWe1TvAp$&v35GiOC;6@-sW2gZD4*==`a0lQ63Y>(_vd_B5=b6Av4s--e z4A>mN<^!e-oz;QPI>6DH4ABULXbg=4und6B09XT%g`fn4gACyabO1sK#6locfiM8V z8-O;n3iQOs4uA>c+E-+K^5cv)IMX1*nMME~92!DTMXUj%!jjny*juP)F96{H!~&oJ zfEncC&|(1g0q`CGD}Mws1`u>0h$sP7gi?U`0f-794nr030Ax47V)Fcw?mFlQCj%vL zG7t)*z&`~ToS(Lt02T-s7d&o9&lY}y)%yYfbmdw=VJsAqpb>LuM1t;_4F&H0HVByx zB{(RdKuE)2R75Z;{G(8B3lM>jrTL@*rt6>-a+wJA3_TH}K@k>eCBeQ_*q4CT3Y`5p0beVuSidWrlE zi|TQrp=n4Ke{HAU#S-m>v56cr+n@}4?)x$qb_jN{hBhO#YPhhd-Re3GP-9a<7Jr8m zbtd(?M_Cs0?IkCM&l%whj)=5+Kse#PfJ_l3mS*`7dS7rtN$UoLP3{ZH6y6t*@Do50 zwFZRw>;>c>KHMw%fx;{b4I}f;W^n`B9hn38L{4Z5l~M3|cdyV=d0;$R=WY>&emyiS zDH4#2pB$Op&Vbk#Gx$aOCNQo=%x-2d%khj~_BK0cRz_V9N9^VUv7C<>Z6SholM=3H=X+Xrf&z()9H zM&I-Ia&uRlxjgeZTt~Q1t1q4=HA~d~<*5;RMU;{`PPJ+q!QL zCy0WLsfQEzG){Nu&xaEX)}b|N$%WVd^)P^02kNIEPT*ZX{rCZ`hQA8sy6V3@oZ$P0 z>C!iUFGU)@J)9u*Tj{CBzwNuM@!L}d%o?X3POxbC_E~;o(+?Tw(Ejrw19HDGX2nPR zI8zhJf{>vf+1!E`_!#AmiREm)Mf=zrlol_(a`4f*wX-cgf2ZlHRetNR;hZ(I7A-zE zc&K;%;d^a6NheMEMv@*7FOqLKy(r^7Ug$Nb_N2IZPCBl{bj7AqtZ@;iGDihr4lP`k z&Wo)!p*{U=CCCj%yJENtmZken_@7@drXfG&tV~t(vBR|IHwPP~tc=h0E5S#kVr%rTP%4ll_Dndr7hQL$PrhvKJe9Mz0B)?BuT2I!~Q-y*vDBNBlVOoe{E2 zxVl(|FShe=u?}BoiR+39Ub&0SBaMHh^KB#=k7eIsnl2=77M~E@F~78*a*6s0K4QU- zONZ6NNKFz^cD|rHwC6H^omu+DH=?%TwInU;kp`+9uUt`lGWIqg$t zPJbKS3K%GKz#dEu*w(r}>jf9o4vg%%`|{P#c{@&j`fX0MOcwpy@#ek1H8yA6^v&kg z7*X{}0t$ZU?)TSA=Qt)}Be;>p)RA>!?W{NK5m&JZ8l>%A(c-Jx ze#?hdyJGpS7k2GEZJi^z14RBsKWhUodaYMmUP6-S^`NA+^>diXML&0gp_cnc3wX@DSANvPEyMG9S@Q+2gcSKgnsGw@ZOcn$ZZ{P%gt#$FE1+? zb;GonvBOFO>NRs}$BcCFXFHkn@jo9Bs^`ZNBE244=QxagpC92^Iq~uE=j9=b zTlVOlQT-Y`APrFi)G_*hCHf-DjO9V>+dj$3bEDbCZEC(zPtO%?G>@C>0 zzR!?@ZTR4J#yl|iTE!WPU`xQ3fuVQ5se);Mtp-~QrVX|UY%AC{Fnwr$#x5`;FjFw} z!AL)V?FTyub{NbO>=f7uFdHy?urpw1!F~oi4|W0U5?Bxz9_%vMHL#mt=+OKMb{8xG zEE((}*zaJ-GkD1Wdja+etPrditOBeYj0RQ(RtxqKtRAch>jFOTb!NrVlk!w;&F7O#d=<3!+}@-wv@> zt$#bj-f#W(5qllF0nfuikdEo0feNSoMWZ7G|NguO@gN9j;br&<$JPXl=h8hZDpQBG z-aT8um;xp{x~qPQ(9$V->!ytI9>XwSh_ z_f94!wz=!`+=wlqc{vx7TFnzBh#8lfQex-Q#rm0%5}ofJAL!he@G$kbVN$w&Ok47i zo%pTcBkNMljf}SH?qvGS>5Nq_&;umJ$Z@3ihb#B2$ zwJK$`;WlRXS5|Iu6?MP_U(GNGXT;rnAk;UHq!lM0VF|}ZHfl##kaqH~BOQCK{l1go z*bj;BWh5$T%L8jo+(ltiuHicQu)7@5?$bMZ zSUmA@Z7f$`;cHENU!j5;CZ1S* zNvz4qiRpVL-^B1LNlQs({4;D`%YgEcc;5iZ7GjATMh=ORTu1AFY+Y;mi%)aduYETrx0k$Yr4pzv z#yr=MPN51jRm+<8#{KnnVwO&-W{fGuZ?=Ofc6>vdEOHkCJbfxMrj0aD2&yjiR$qz? zJ});cibVM6-p0L)1p=e*1UK0`p=|6pp7{d2&We_o>=R#a!GwvAxKoY zfmDWtf50btf8iTLfc7|CaL9Ru_cdAasKry>x|_R-ge%%v7+-I-&v3rKvsy2wUA6W7 zh>C?!$n<^0JY3B_8N8TzoAr*bO4MZ`eZ1Nd-6~%-YQzuUnFn2A0`XTlP6FYQtsFuzCXC@j9i|9lg75%+>9 zIA?UeB+_bUc$8JmTd9L1HfDc`H}ge#yqUWzQ%~_N-+<`U)!6V~ z*6fa{6+7c^7vlVJlAs+wX(hLM-i_UmE`R=XIB4o5SEU!t2%Bb^cm8#fD|fc@Z&%`^ zc796}{jf20C60UdKhuQs^sh6}D{;^)hGvM9pus8Ry^>o?_bk26*}Al;Lcy3}@ZtxP zkMfJ|9*ZiUyKL`OXML?lTG943v$d{Tmgj9-^mg~+#ZPRL{ZEQ*+fHgd&Url~XkPh6 z;pt?rWm_nR_@MrSQDEpe(v$P5uq<_`*WZ!%i4v1D zqUZiSMQ$ST>K+xp7Ja(lCax$a#a7hziA1UrcUF*ejVvX(o+gQn*%-f03%7AqY-@Av zfPI#da%9cO%f=Dyts1e<6hvu$A4cUH9}!Hw{ELN;E#We?iTgAy)6kYQaH=#>~%FrMciaMEx43X?hDCAz3TOpb!V@O5a zB56=`oaQ>sU3-}CwG^<8VP&l>jH>wI?u&z4j7@i+e2 zr2LE&y*WPV)AN^%<3HW=C})vsP4(UGSIr+1$``jUbM;1lXm}v)RMzf$NqW~7?@Ygv z7xgCMg|GLYpCW3?9V*jvIwscN3#_efUX`kLZHia9g?;7oO21dOr5^%p)Ay$Cvwaa@ zma1Ru+g5V^eGhlHZn0dS%PW3a>g1%Fn&|VczJl~Ge&y&}JIA&lK({LH`oP*iGkzs~Fo3T0adoMlUN6@HOw ziL=owW%oo>mY5YCririO&(vaym_G4BUQa>vu|ED-L$W(>q_#zmPZTx z9V&SK5lb5*3J1zKN*x_3{N9ts>_7Y7oa-3FJ9Vda`hsrnH#U6>`WpWbc;)sLWgMN% z)m9R#{&5ESktddv@P(sr&buK8df|AkYjuv7^8C>D{4>@`@-~|5-KN?F-*Q_tZvA1C zTmKAj3QP;UU2{JPu5={ibwqvX-E$yAK{uz!z@^r?*xxUH8`oG8LYnuPkLR?(taSL#ppQ`Hhd=6RFUZ5}tdUWZcU99aY@Q z8Xgb-kXm}|y`!LLm}h2nv|QQ29D7bG7ZsH<9A@Gv=OpV^rv7-}J-=~5a*l#_Ws8G3 zB?_GqCZ30y#=4aqbyPGbY)RlV_Z?m({-5II6Wm|8bE@K_6YK3hwVQeLC?vRNxtn>R*R=6U3H4d(?%b;Q zLy7f<9z9A4YR}!Xyh;WVa}oq2++DRlExybwD-E@SWUiS32#CAK!o&l9%I2b^TEJ#4p?Q%L2q*Xp60Ps&f+cB$R+W7(_x7{q{735~{kz?FU*%9HJ>06kA^YEqjbGOmGq8mlM_=qN zcKOqTrxfm6`T5)sRda>-;_y87qp^KS?B$^b-PBEvq3|O^H@rXdo7^e%VetBo!So+k z@B==RLo}P2(f#r|i^p%1pP2v z=U)Ud${B`v_GOc_OV57oN<8wy;2badbVF|Q{(!1K@B9(|Ese_Q?SH7R=2R*O&7FKE z#$Vp4dDlf={sya#t8YH7XjE7>vsNql?||pt%Vgj6@m5@jvxr#FUDAJumq=HbmmX8` zUmE0NlYF#e(yhoty$?P(JbIAfF=BPbH1E{lT;nad;n}><(<`=do;B3$k>8NLyhVY| z=m>FO^KAH6R+R3u?wNRUako}-{*@I)E#|GIP9N%5aaZPj?*M`vZMO}Xlmv8!Z( ze;IFonPjek$CQbs0h!6%DOLL$d~*#>H+;FD5t!Ze%q2JWbcQTy`*Fdm4Obj43c7qO zcnTc@ye=t;O%7KIYk$05_WY;yaXVQb{fsZ7_0gdxef;7h*5{*seZBnUs^fECUS2cx zWct7~#>YxSEewVww1uHBz|-B4D+P%^Z*+b7;4G&;|@R#4o%DZYQUy+dx1U0mBE zx4sSW>F1(7oom?-+H&0b0^-xJMQ7v`**$2RS=_xUK0PEl<8_g1TpL~7{cC(fPg38< zNVSuZ%Cj@8?N|wqtD{HHMjyi)EOqvdJ79Cq?`{y+iS=3@J?w<5S+F8sd>!*A4s3!!RE?Hg~Uj<8K z$=MQ%7w+j-J-4PvjH#X%!mN&K8u8aKCI&jcPUH*P);f_dXgBJZ?`7n_rx@Nf_!On7*+0FU+e@bKp*xRN%tuX!+v%bMMc!^4}JaR6AUWzb0# zHIwjgKk+^k^?J9E@NjqwF1uJDQg*0-golj;I6Q2KelUN1>vv7VSa$_jk5#KkF|k%s zOt%$^;s4`JY06Qw!&Y&&q@&vRxH4Cv^QVbQ9@>Ndyw-)8rD&dFPo%_=g_bC(Vqjol zCPK$02ekns^OYA^A{3@;tkE)t^h}pm)<2{#$})rW3jb&;ONdSh3y7fv#<3*JOte6z z^DApew_K-XESm0!Dunb%n}gb-=@m#Iq*n}hc33b-g!W^sAcC2CAv&co1Q!S*iiLtS z3UCD#LdB%T6{tl}fu&F|N!Qqi8(>NN!s}Qr#VyVxg1@Ju2634S5dlJn25J$cX9^XQ z3eXrdr=#@9pYt!nJrF4rEF2m;++&WeSg`Q=nTv4`JMN3-;w~4qj2RQuGNM>m09tH` zDi%YEGZ6^WgHVN*=saj87A#B`lf-ib3H}U%h3Sr{9wz^C;gE6hm}rm!mTP|;;|fwi z=Ff8iwFoYRT7V|eUsF8%i zOvnK#!o%@a$_tog=vb5qpK?KM7E5}5ysJh~_+0>#0WzU`2_mVQ$QlO*1|UfsSvlf> zP#QQO+;+eLB?t!`LO7r#;eb+v1H#T7$^xPYE|)ohP_7Jd01hJ@a5&+BBM1kSB^(fh z!$ko{5)LR&I3R?GArBw~#eplp-9DO}0748I9Doot2M(x2IG{4&fMW>kM;s;*@D9Xbaslr|93~y`F2rFn0`Eo~CMob9 z#9{IR??qgk;an6YM<<9gj()`3dw;xBPD4&~kiP-!$ef@R1|`F_LBs##RRmOG4D-(f z5mRL5$T-O6BKrl|LS##jEk|a9>{n!V$krp20PNV+&Duw>zoq5TO%#`T-S5nP5*CQbNvf1cRlxxYF4myjk3!%=uc~vsCT`+ zC$PEe+r+f=O_3dlNmt3$q=j&=nP%K;cT20Kb=bD2BP#r*x?iHA)>8#DD>c$Of_b;E zx}|B#<}b)K;F`Wzu^ae~_nzii?d+3>THkaXNttcWMY`=c#uw~; zD^<^4tQalDKOzX`#@^24tZeM9G_9Ff&r{~7IqVMzd|R8{9&u0h2|tX(nRRCWir76- z?{f`qJZ+08FdO#kfR%rPpxFDGmBmAzR*L84$#WK*IMVV^E&FU$QqNycdaZbqeb`=| z*Ajo(A4Pj6%zxS&Jd3+9FS+A%ubdRW&Bt3eYuz$E+Z!GW^BQyIj;bbIT!`9Ow|Kzv zrTmhVjymNWrTpMObIL-r9m4Xx4Upy-_O?se6DPHe%kbTK{s6{z z?>F~RnmY3;(ZHm0ILf;^*Pjn`h(u?J1*$Tpe+N-*FY+`OaFx%f-P}L=ZSa;I)4z-^ zl;XeZpg##VC`Q*^{LB3Fo(MjbWFDG3>Exlx8so0yOTJ1rszWLl7f3zX?_SKmF1v{@i&*OKt8y$Lf~o>YMe49Yb%{=I1G$%y#(FGiq{W zP-6G`^c64I=bi54>T+ZDhBTJkC^P+~aP0H1VZ9cso>_VMtq61o9@cxP^1=GRh(gcT z1zQ3ve=Cu4oAV~j%ri2*H7}7X7P!mIe;n(_dv^+RCyTzt$Ru|*8{uB@&5mLR|LwjW%m4RnFI2x(Q~SEXq6T7C3~JU{n?mOq~&<5(X1mZ+Ur+Jo4U)Q27kx6 zfkn|y9C1sQ5k=phMp<$DBz{zJpDZO1WrVd3PNUGrUhxf~DU0V>jXcU5`p;sk!%>2v z&z2{=w`ObJzG{2#{=E;&ZLHs|pSA4ZvXEyNtd_5AlH7iZepdT#?}@9PJKyvh>$sK{ z3@`86%VpF41vSM?%HCRq7jXO2hYkaKCVFi}qE()D&rSMzD{uyRIo@?{G z12Pi#P!{L=R^Qt3x5L-|Z~GrgrXA~%d(EG`^K>3h;ef63#>)fOzHQ{*IOFSjCE_>k z(obX8*z{dp^VINF|3?3A`C8Ygj8!#bYw0BJoLw!OW^EO8wOTiiQ9XJ*{n@F`s^FMs z9EX;^m*oL5vCp|PCiGZ`BQl}^Tf_n;O70Uj+Wwvy0-o=KU9Ttha{u#WJ4cqcR z(VVo)0$)ApABS@UJ{9}^mLL<2CvzYN+HrE3CpJ8FHIQi{vm&TPIG{G+fa3`VoIp6> zM8W}e2nW<99B>lhfO-r^k8mK9i31Ss0}uf?m2g0P!T}8k2Q(xc(1>urX@mnB6An0? zaKIU`g@DRtAcMUOaKM>_1I{8G5cWEd2XHpwfM$dP!d?jS0L~#C(1LJ44&huNmgEEh zvrnFj5R8os_R7Ek)d&YvB^(g;%8&<8g>b;Jgag7>8S(%s5sr|{d{Y32A~M)30|y*U zI3VoEARQ3)%D@5T2?vBZgw`U)hb9)Yn}d9iHk_ox4sRIYkR}6LNXP_NkPc~*ghSd8!XZt9a7cq05BVXDML4916Ao!`Kpt@>tkolfmrW)%87@tqv!JwD zY0|W~C8fdYkft3?(VE&|L20p!hr-G1sg*KtMSM*_;Wk?&9_a|_=m-*rc;vzV@A1e` zEroF`i{ZGVGdYwBYt=C3`NZ-W#&k3lJB$jwt~iE%yIEYD)iMkoPjkhG)7LGj#Vlz# zT=09`@aS+DB{m)6DlWm&7(rj(hK8(sI2~7W^ufjCYMg&!f^KZ>q6MX3*|7B^L5(d&*-s;pyj zwB~74>8Mfk<68)u<><#psCg{ok@UUOlqGdxBo%sJb8%><@@Q7|NIK#?wUV_^o^C!* z&8Mx7q4wXFrz2^~n!XMvUGj9=F={Jo`Y2j1jAB#kHjko>!l?PIY(@IqaY}7sWH3}M zCI-)YvCU39y?x!B#l)9+ZgF;74Ksb2v-j37qp&0=MJ#E#0+tk_fF(663`&|e8cVu0 z8cVu%5~&z61|)4{*^IgPJL>hT0Ap!xFlEH*7()-7rPi_*DuPfedf6#Thjj>THNwz6 z@<0)bRUQZ3q&9wKBM}QX`A#<{kAIPBq=co$s9>q#N?2;C5|(PAJSa6p8B1+Z7LmGY zES7q0EF-lBfJn7g!BWFiu++;TNa|Y^EOkHyOLb;5QY9TbnIXLrhK4k792V81jzxVN zheheBVo|}WgQ7}Ru_%t3h^PoPEUH$G5j9hNP}DhfEUHo+i!#21M5(c{sHJQy>b^Gp z_zI<_9VElTgAMDVm#@>7pGW#N8!KIa3c%!>u7Q>A*1$^NYYZx#q=}UVYlNrr^>L1yD=}-9ocy%y=yB zybcz}9goF59*@OoO&ApCGXaY$njj+1WFi)Ka3Uiv7l4S<)xqNYbg;NFe<5)Xb+EW9 z9Y)*)^T~L1#-Di0f;v)+XpK~5wDK=eYOKw=SZlr>)|#V>waQJxT6azw)cRx+)~clk z@~r8%;i$15dZ3X?(xXD%jFoBS3zV)j+>h=~JB?`hDdH;PdRUzHWZZKV`c&vS)9)Sk zb|xdn@H)k2-I|QW?AFI(5EW<3{N-qBfwa{zVk? zMd5dSEGkPMPrT{Vn29G@Vacdjc@F)e!Y>9`&1)m9Ce{F}X*R%WRv8Yei891$B#js~ zs@jFs9;;c;)2*S~;rLEmj0QW8x^MKK1lAd0f#arOfkRAS8C0ax|Dt3jj&vR#%B+R3 z2XS+9-{ic@XBxUioP3;jZF6#44HZUAV;_91nEzZk#fG_bxSq%0VX? z)0OF-yOcF+@(kMQZ|XPJ2?o{Z)W0bXRWO4J)lgHVRidd4tRmCF7Dzfq$f6d|xqngW ztevQ7Xv0BWHxW_#%0xtInkiPgXeL$~#o*6M8)u3r<;)UMdJUa?SK2!ZD_w62NR&pI ziYQ$^oA!&QCQDX$hyQ^@-iby}gdvu+mpSTxjTmY;D}6TY6hmn!STc`8{FBwt=VHyo zaWClHbr_(f!W`qxa0%g4?7PE`ID}7(?~aqif!Ak|OQjKqaE<(4qKP>0QY2DB+niL+ z-1j1mHN=7MK@rCZ;=s3qh$B^asS)tX4>^PlY9tQf)co$ynnNm|L`n!-YD*m7O9&mu zg(W0O31Jtc{9HolXdn(pX;MPiH<}i>^6zyB9lsKX;{sAb*lEXpE+KRz3rmQT5_lCw zF?6AWnbOcDq?%y!H+YX36FD9}_sR5g0ijOHb7Wsf*V8fZRj29a9vmIp>oR7{PWTTe z_laXSk`ATpTjw-p%osY-G2VIY59#Z^1dnXw5x(d&-)T1dm(%P|=Yzf}C}afK?lcKi z?F`2Egy*5Y{bcE)faP!->OUws3ZCukhZ^q;Kc0ZjnX(P_iPN_**?A^v)4x5aWM{`1 zLgxvn-;r+j$x)PDKkeC_5(Oq01BSio zTtc0kVDE7|owmc&aobS$$H7-8d%((ZIMmV^u>WV9{@?Ay6hKxbI+ z&QwxT;@$(K)SU-^NdLik{QtiBBkVDLjnmh_R-Ti0{gAwWHxaQ`@}h&ga=QP6ig5Y` zZWurNiv?v12LAMIth@hLm0!ssljh0z^Ar5tmM&bpWZ}|fGnXtM*>o^=`3f(1)r2rN z0FIfvDEklm7`i851$OC*z~#G&KS!Vm|2e_cX&?O8ggK}Sjt<8OqFzjZ`7=G>ITQU* z?h|3Vn+KdQaRDlBBK%>72V64I-??z&n4CDQ^Ox|@L=0+Rq#rlQ-#Kv7X#cO1FsNT9 z!K(v2VBw_2sF#z@Pu}P}d-9l^)n9^N?VB9v1du*C1|^vcZ$^9Md=}{ZIo!Ttg;OxR z({+baI$Z9GLsh$iRd~bGrp!U1rhuuv;pi#8P6Qa5vUdEI_y5y;J5* znDS>|UJU3Om@+!c($51?3qOa2UwFX3em>VJ1HSV)gxWC`+4scH){=Hp4(>UWlC1gM zfoE5D7kEn0Cr+zj(igKl{@8Ui>^Sg82l%59#6<1hb7+t43*^TmHahzS7#W9>e*vq# zJYe6cQ7FHu@XO%o@cF50QI{OEz=KogpblXjhMqrdB1$s#AD={_rhS}ttQ#0U1%{?A zN5%friL3<{PxEk!gw@lQp`QQGA5hDu!(Q%-$5IX)@S6V5iky$Sjmc530OsYotwKF@ z1Lqcoa-I&e=6l0eg1>|_rV~(?7s4}z)8TP$6XC(>pP^XOM;9@{>1Wu}eHkiY;XlKn z*19`P%XD9Yy6q0zJ-lIw`?pS$;8S1vz-zw@b0UM*Zq%zUVbzyEIC;UFJ;G5(J-~bO zU^jFysuyYQMlF~D4$dED&hS7bjWk<8vjSB%|$&$no&;P@CPppoZ>y#IlZqL%lC$_&zkF8GHXoETX*L<@P}E!&aPiM9@fL5bEly;e+7Qz3qSbE0|k#X zhe5LiX|4jyKV|mUaN2B7rx-`860~w1EemLU3V%80C#OU3u{jB-mO1eIIeVPv&K)(? zfw{|_DIXuI!9(rGhlyV=cXs=F^tGMfVb8~hyWpYhwPD~MBlln z*nc03{N|!cK0XEjj%4^Pgtz<6b@~ppwm20!o^9YIgC8uIHyhF;r#i*&c*XbeOEI-(Ahrn5b>!U{1@U6PsXl9r6d1%!~3v4 zsBV8)@4pwdW`To2m~)*M!t~`cPz4L%#|z?7ss#YO>w)_mSa=(iu^2Wk{u&NlG!FHC z;YYvwbR0OOU5kMyVLsisCwbqx#s6U6`Rby7UCG%F9)4XD4C zz}6*r;6|ZKV^RB-Iy|p*=@REBOC1Zr!E*yWnf^P?eI6VMeKJX{Y z7C5=WOP1|Gk(Pnod%!oBg`ujK!9P#&fInTn)Y)_Sm>e?VLQ%`tIwyh$;7<`CN;fSB zuk5fR{(GFh7Yb-fx55)zOf<^rCI^Uxq86)bD}+y%pyW?3kRz z<56z#f}pvm*$$R-Fr)L_VMt*0&5*DW4!eg9d7wirJ02ffi{|xuH(GUfp7DVp6&1$6-IR9WMu zcq3CDcjcDE+1YfZrzwPMb(P#tQpzlk2#h!NY?{uM-nrSzrb8AHZ;xCgOr@_eH0v2H zfyE&MAM%LlrcB?idKj}a)DTintZ){kW&dK4<}eJkwF-AdCUNJR^qr9Uuf(iyDjnLI@*Vv|eZ1-iGYxsMJ)s`oaCGMHol4|R|QH`T31-6nnK29AP*g+Y# zNJ-p-Ek!D|JJH;F5pQqgTYC$nq2>>QcHUGxSUz4GthotQsJoxJ4+j5+mSZ}Of+Jnc zAX6D?f7^#FBE#T~Gp4e-(l}7skjymGegn;R#_)4Z<>ZNnELDbtGpPz+Ux^Cph;JZCY@wH;Rrs@^HFHniKXjTqk z_{J>aQ{FABj*GQh0x(<*M})I$AvPIjypeOLLgY_iSF27y*mem{?KmwiOdFH zybz6?L&14j9X|`Ylue}Silba@xm^rmKU&BM>dhr~nEd$muHo7fyF=9(97!VvpMC=> zXN?cN%f2bOTYi{PdyYxW!!y){kWOe9^3rTkY_qK^3N$7S(cXZ6NLQahS9jy| zczWMT9;u}YLi0_mhs+wXbt$gH(xyr?p)cAi@sshu_8DWWu*QAxuK-rTOny)(zrp}8 z#J*=!H`qU9DKS2a*cK=VvPcuH0h2onscKP^I)cNqNPCYFJ1pufU!v5pQ@MUZ45mU? zgNfwlN@}`uY?^>pJi`cunmz1!@eIadMT3C(P+V?*kKdCg zh{fBSi$g0^qB2ewSJO_iYVEh!L4*2X%pg?(F;dm{Y*R^R*fas$jD4ohFL@k@!k2ZHqT4OC<*RL(C#;5M&KaeUGvJWU*!p zA#26Oh%<+c;{mvTQ>`@U(sxcrOLYHoTW)YD)pbg|PH{dL;B_%`Z{2(|rltCn!f6$Z& z{4W$3Z`WnHG{sl>M2jDYOyPOYNU|dTP&OhdC^rbacfM$y$IiIE0MOkW>9%CraR# z+Pag8B2%+stCx}z$bUJ|x+aJ(-KWh`iZFmVDyZ8|JtV0GbaHh7&PN}n=wGTmQj!f; z)_=&WtYC-b0keL$S4H~r$sNJJ%ifWDgNwc&cvs!kHINk>%GaxnwZ?9DF?7U7%qH&S z^_8196BvDB6S|?|G~{ky&?zK<*$Tad7?utALvMyDUw4`@m=$9OJb7;s;C}0&&|kIw z*$A{OQUEOiG#sY4S71yKK1MN@*ZHKs+9xdu>WnB+(;3mdCyFQ5T?P+! z(Gj(1{C!|6;4A6PlNIiPfIgqOTRYsJC=4AzzzTB@iY1-2xxzz?C#k??CDaTV*dN3o z8+&>0$kQPiV~G?`Q{l|^u05A?N}*qJO6ywo^bYLwE))q{=-EZd+8@25EdtTzg&fLa z!Asc!<=scq3TLF6rQ1XpE@1FhkADtwBfpbL)kN^)bFx?5zl|^AW}$h=K{{MB7etbt zEC#UKM7H^w_8VjbwxKT-4VC*`ljX$cBFlo1byXB6-1vaK18{AXHmdIlBibp;N)`o> z6#YT;BPD}%vm)EWmji{tsXH3$l1v;jB*SbnZSR?4aFqR8-K*71@YXXiI)1)ZN#+8tvwnkOV zwNC0dz%X3~g*yTc97DY)bUEL!msoAP3oEOy$A!!K@An+s>Fv%wQ)FIRQr8HRcdF5Y z?x7sYpQj6IV_IVZ=0$S5R9T*(d}M902^ML)P-e=?Y$!JzWV|X(0Z@6=!C?kNF@hWT zqI)BD1BXg(`u9+!o>VmJ|*Gj%^9DoDswo?6u3fMFd0QmzjTT!Ge|B{@Q&6Mfs zatQKXAlpYC6noJB%Uu6+l)d4h5edW;cCNX0^H(xSEj}4|;q-92ap5}I{&3NVdp>jL z83u5H`mBN!%EyKE*8qD`M?;CiJ%`lh9%}1^(AOmIvjWkSq*BZbz`t`zvi=Igft{Ua z3cd+s9npO00{k7pS?gHd-O_Ic_NkSfS>e_v|1ZHwEk@)E^B2l8yF+*F1G-T{eFHdg zlsJ%;ar-@Z9he!I6h7wAP?d3G-oN;Q9PG1)_#g;aU!UazY4x`X)+(#>S{5Y?q>}&T zG@PL2QTozsf7=t@JF4>g>;mnc{N*{)?_{+Fwr=-Ag}XbO*byxIc$_$+x=&=?by|rq z5E3;#RJYiMk7wD-B!(DwSk$Rhr~`2T^W7Jz=3T;Q=^RFU?dNP_9vV=P0-+$e%spDP zbSVPYN5tv@zn3!Jm;A&wi$3dJ3)%FZN(sz94wC8|Zf}4V~MMZERq3)dB_Iq`2OVDA& zZps|WHg0lCJZW&awwMJGsiTo#)D8MlPwOjfmBfi`SM#oZ(dqlGeVaLnmeL(aX4CXf zJb31Q2#B}?gIR;6*MaFyD}NxSEV3O6orB?PesVY`qMSs!ABib=rans>7j8`JaL+Gl zc>d;NKzKDS*75*?1wn_kKY68T!tj7>pHsH^zImBGN^C0GKeUGDSJ0YC`T~}viKD|` zB74{u*{cT zzSL(4(fV3#Dthh?NFl#_WNS5vz^?xi1gmcTO-Eo7xfmEP>K7~{(peQR^Bz& zf+#*#Sy7j~ZMQp~_J4OshDr=TzbpF~jzfVSR0EF;jd&32+HGllGYTw_PVq_#OTYIH zwLQ^ibwfs4#)@=Be^M<+66Ql;SUdMLyT&uRE@)S>&oCw7z4~Ltp)8j&Pm++shYy<6 zRWIW@uP}_(yGP<%I9(5ew-XpHKzkm)+a zlw^7QN^jlgf{+*8{d6?m#`L*e8)pqHvB~s`D(e@WrYdnO$#UpOxvJeL*Ow;7a{YhQ zCd*?PnVwvlrOA^?_2ft-cU-vCI2|vRof3~OiC9C*2j1V3j#z@P-mGeY3?;bkR@n`- z$lBJzhx!6_uKa%PUHf6(bO|F$b$+L^urHK<5G1wz8`;$3s@4R9e_XU!5{`a(CaB7K zG3X>a+GafzZ1a>Dh&qP7x(c_pybAZLss!IHRuzZSAEb)QZxR_f^zTxQ_ZjWRZb_P9 zdAxWw<<69YyjKyS?>N+pht8<9O>P29HY7>a!U|uni$BtR!lZ9mF86SxS*APUC)!mr z(4sZ5Y{is8;|!K$CQlJFrzr5=*6aN%kp$D}Trl zW>eLT+EriJHG#I0Rs2?b@JMnwU|GfsaqT&AD1>l~sBXra;^==v7=G)s3JFK#j9s4) zs`lsUxFE*_Q5HBBC{2j*x^;ZOGnUEr9R59YU#M#hPpD1KK2?t6`>DwySE-A>`s%4S zxN_-McKO#Vh4n2f;es~NGDM<^v|fzodQ-@?cO~ZaUE*0h^OS#+V7YN~xcrd?1Bsa9 zLHH&2z-W+^(TX9d6p15W+v^bd`MWEFtQCN;d-4fp5Lbo6_xt7RYE)bx23+0$OGc>= z8x6HanY-R{tDS!^RE*1ze2&glO!_UOE6=)KWlXV1S(4~D$&prkT6?%vmYxQpZwAhb zMT5Fou9*sk_x~p8mhWzXy^k;=&PcWyfJ-HKRea38II_p~n6rop0rMFDHrCSPcd!G~ zE(oboeLRw*1N(gl_GuL%FX=$&b(9szBF`agfXEm!UovQX(9I%HJ2}5WUE278XmSYW zBGGb%DK|bisWO$}_{%!1UD}x1M?BvPU%L!uj71D*aD&q0m7CRz@T}9~Q-l|2&_`X;7|uGH=?;I}qw zXzhn3vyW&qpw@Iz4p*vuqRNLDeLB9SNu2ft(H4QX#4$3vwEOA&+bVw*{*K)gGEnm* zR8%<}ZMHBoY-MJ*L)JD4IBV`xl))ty5ovLc|a}mF3T39qOWYx&tt?3|rrCBr5*1+iNfOByB)P5YoW-AS zyP@DZuD6C7e-Zm5}!j^+ULC5i(%ZYr@kFBK*WIm*^}y;tH;E0zxH&U{m!cMg$zyg4=1o+m6ftL!*Isag1it9l*Zoa3G5|QFcqC$QUV(>Ei z^n_Fie~~&wB%OtOC&(yyG)thJFqb8d5_g=HeU?-yve(a*E+804`JA2_)SO`(NIlWa{m|qk`fvr=8GBnR z#KZkS50~IGHDs!jj)n^&eddtp55r$aD@LGe`{;>g#t=pTDvZi)}-R?)742Y+p4`XvA210 zb4%-*x2je6kcT}5rD>JEG4#nvM^x0OqWP@bZJ4vJra|2v-i8&>Z+vxXy)BH43ODZ- z5=z-$u!kBjJ6U4=2lfG+U6!M;hSr~hHiZ;RR^i@d6a~gZl~A8~Z%ct+g5`xGDWr`+yYe~QF~NPK4ZQZmM3wRAizHXDZL3Id?rCo>J# zb2v}c-$Ax;1Qja>g}TGM{$4N9J|j3Mx&JhgP&3XO=Zbbk>@mD@^5;{ zS!*3l=CYn)iw9HRBG|%3YvQ3Jw|$^KMi^GAq$_HjX-x!s#jD)5Uadv4p3wufO4mkK z5>F+FJ1|mzQ4zH$FsqR*cd19tk5fZZXg{GfHAJ5XXfvI+KNGCZZsl}|OH!q9ye&M> zN{h6G3pQu>=XRyWhkgQfM5yVj#`)S|*@UFt@9bK0d+pk^f-zB5(ToqXVkB`ph8jp07!eoNSf@w}7-dDCZza}dQD! z#ao}haTEQhe$VK=T<*{E1C!SHT8CPFJMW}Xvl5JEk#&>MwPu}HeuAj3=SEo$Yr#6^QCEX$gIHPsM`MR4K zzYSoB3j~`d>$dKF3-bs%EXSEhcVz{n~U#Xx5Y!9hQgg7Fzd+j=}_nBkB zf}ikLa7diY=F<1Z#ZMnI#(h{Pu`+H4awVL>L}EVuyR(S>;CS9QT7fvnBD$A7D^j`% z|EuAa-g-xa2Yhmsal*nZ5i4^o7ZHG;Wf0l0{h9g`EV5Vtf+WjD`{od^t~DnJRO9&C zD9FstLpJl;)yV;SCMR`(cq&sm2YH2Q>hYh(6t6L&Yp2Seif%=|viT7)dUJ zDka;}zx`ci-XM?7PKkfp0A>35a01LYkt(jb+3>x3NF2kT`}7=oN&+#OO9H^a*fsT4 z{b{|Vitc0Kr!Y^i^2TefLQO|qk_;DX0@`)cq!c zdzsN;4&ZR3DQALSXWrAAf_1z`L$8tGCQ6|g+f(tDFtr@5p~U*^ltA2}-1`jLNv`U? z#@Ox`&I_|VHguH(XEoyuHG<^4=>+{=b9w;aG~>}=AJrScYgN%*!<)%RFpG>HUHe4% zDZb=e=wE2>wC{adoY<0 zy97+dSe34$zHUp7bOF(8_w7LImR7SNVvlX@2;rCmFH!^AEq%7Q7~j>;liAygbq!=fbs;}!V$&Ln{{K(UyH8{2$au^s` z4riR2FHvZ}HzF>wRG@GEjtQkKkle5H<uyPyhR9K zp*IG+UIGGzBeH3HPbECGJhk`iJ~0)GBhI(ao~)L~4$(R6F2zgUCV@;8@k6%GKaZ~} znt}%FHwM2qeq-}RyI@}-&`OQINNwiU_D7};K!x8iPpqN;E-Wb;UKoBdp!x+P(sI2i zVf`93aEi`EpUZgPW%N?|p?88q)%zz1R8``8bjhaxD>$=>&~JOcfYp6luGkJ#PLIn{ zLF;kEut1SBpJ@{wX}RcU)x-ee*pWcsYqg-N7V(LF+x7m>kMbs|Z$nEVD!xk^6L0$+ zzZJ3hNg@549c<}Lw8=N_3Z{}^o!USfY^JyW?Ffc=`@1uN^H{Y~k9g}-d{hXSbQJkQ zuAkkKXee09&Mc3+2n4Z1FNpA4`Wp`zWB%by`J4BO-W6=$+)*N>HbPLNJ6lv*%mJ?V zOV#@YICf$jVo<}ifstb!-_0(u<8vMQsX9lWm7;w z-cflqYU5jdqNE%N!Gvi{4rY}6aC4F!M~iT1>!As=T%Q)rBIoZ05q^Hg-=qm5z-`GVcrAOHgB3@u9e$CsvgFQY6_2VFI6?<4h4K zifIj-gTKc0RViqy!epFei?l5+%EtP}L02F#+x4iVR?`gq#bA#ElDgEVOqk60Sw*SU zJ`(exs=LjdoY#`{^@7--c+T`9Pcv`Qhjsia?$FUtd_*P7i*OcUszFLTFARhm9zh%C z#VjP~_mB9h)nd@-UwoR2-@SwMG2}}&LM!&zlLZY8s#;tBMfQl`I!hAemx_PLIOOG% z0I6PS0%91~y!s(Ts5V0jbvH}Xj^MZS5-t?z&Z|n}I1WF;7GuaX+xr9bFl;=&nstlU zW1dWF(nrT|(;vH~+fFmQdNu)8ysjEtNcmfA-bWtgU3WI-AwTU!?@k3|K=Kq(0^k)%lnQ30vrUUPO!)qUe-U6s{+2oY8F!YoCzc0JMk`GzeeAi zcF8qI1j)m(0YgBIn`~d0>0I;z_31u?UtGe4*~HBXpa#5pjxj23SmL`i!~;BQl}7st z*}~IIoJjL`W{;xD7EQP1j3!nvLqE=J)~YPuT*hN~^3wX`Q4iQ&nWLa;FJk0rrqmEs za=L9*-qR8OZGx;D&3ax*Xuczui(ft>{HZuBg&8@$%%I%?5ZKdr@~2EetGjxgO1C#{ zTa0Rl!pKz0oSKxnE0g#q?_?L6cF0rdpn z9=^)$u4-Te(_RdxLZ_yVAganUg6qNKKUb7w)TG|_2?OHHhQWW z|KYE+pOEz2%XsFf;%q(SQc) zS)-wR2a;|F!h65_pJ2WXNya}WUHSZBJR;i>E^mO?J=*AzzixF1kW(~Uy}ifa7x~tK zTs@RSt$xfVNQUON%$9CKe`=mJtb!?GhBT5~HFyr)8vTm@*zSElhi<%fJ=SJucobh~ z=Z2?OZUWN@OTBUkYA|~63M|(85znw% zzBOAP4>FTOtg#J}s1qP>xWIl$T0?7M&O>8Goo-kbRvwX_4f<k}4H~8*_%Kpm4Bu3p(sw`!LLscNI@OwYuWWoY9 zlIM)Xeaw90yULXfv`D;2q#c8VFeHn5*&89Y?qcB^-0NxMfn;Ap>t{pnZ9ulh>FvFi zp@;nN5!u@Os!_KWn@R-r9DkzW=l)#|8CKAxJY$?>WXq-zsKs@N5_?*HL6;=uI8MAc z=fCo7|MelhHeZ1&vci$*dQwpXqU|XCSk{d`hBKgV^V;nvz?K`LFQi5OLyN{!Ux-d3 z$Q=dEsrOF+U#0y$nrk7j6XzS)w22@^!mU*$f{Yl6;mELnDIMklxr!94#s>qb4b*7Q z8g{ttdQGwvO8FFE`5RwPIiUy)k?pSoV;2)$rmhjAos9BH~!nhk>>9<}=Ch*r# z_NBjTM7L_cB=3}1AGe?{9C~Nc%k^yvTGJ-R8P#xbq8(?|b5|;x14XY?lWSt)d-R=B z2{QoQ%X zT}V4(zhN zxyv@c*bX8u;RODy?H>OF{SLY%(Nhtq*WLW%edVXpV~j}SORG9ZfraWln(4Q(E7^EZ zwp+<#<5vrX{l5~$yOddmTcn^nQI$f!g!@#P+MpgsvonfF0vFl0*mzPNKGqAETp>G} zMB}~3u3&?7f{k&#P(atdqS+S4`fdZ7sGr;Q+LNmPY;(45jip*vn-hu`&juR8Llr+v z!QVSxy37cjvtt)MmQ#Dl!R(=fT@RCb{QJ$zzm{A}Lu|DZut;HkdDIS~6p+oa7Ee(E z|6=nib{lP?np*PEQlmu?Q;=K0}M;+sS+(uw}&94R2Vs=YgP`=%!B;ZMypXz<}C z9`^w=0t0PfHrNkH=ir-7mr6l@k*NnFByrWN2GUOhWds;EI8P>ypuK3YzsjR`0a<(W zN@=NL30ShX1k}7rTg>UH+k8Vpf!yS@tVHW3g;Rc-@c&^R3vXb=Jbd=3c_Kk35*wOm zyrrk^hDc}aZ8i6Tm+-8?%A(VJCGSRdvdEWvMzsaH`Kr+NOHfm6XT3FVm zxl!<|Zlm{`dNnvnAXY+vGKq-7mnT(1d+l2oZm!@K;9Rr$?Y3;oU-x{&iBaCq)Zmro zqa#JW%t9RJRlc=WuDIcs5GlSvGeq#h1XDk(Bgi&q)55%&5>R$!)jjdz1YY{X#xSjz z-M8PXBqs-U&uvpV!^et>xG&t6&`elklTVJUhb1iQh#-6GZ&(ycd%jl6YSv^s%@Iq2pc+KJ7I`K2R zA08>>H8rPQm@T=cRS}O!fa;pzn%q=*OV+0THXej|u0#6nQl z9dr`iwzu!iO!QD+vDvnvd&47p@+_|+{~{}!%PBI1K?AD(kVH#CK%FuO^K0oPQGn53 zzeJgfJKz6ux^Rq@?G0r83Xg==(db$Nwir0^O67#Y#{V z$|&>zTpX=!_I>`(K_^R(a0PQuL@6k^zWvpqDl56Q_n36Gt)A9k+6&S(Quo9c_Wi0V zEwF?gvBVlEDzG9#vj)|xY42tClqoExc}d^?4oT`&FE*xxeNY0H zP{x0yPi(74WNVqIRne(Wze4G=<^kBKpDB*4m((e*DH@G^X=S2hn<4bE$e!0Jx^28c zO5StJ-fR?k6d5olnmba9wFT2QWDxTtz2M9FDG3LmuHH0I(VkIgSchLm*&Qi3<$H%1 zD~=6H)U5~bK+y5Hf9?3I)fOZDhRr{+Db+>#{)&}u&jYn#f{Qe5#~qFl>tek4!dCu{ zsQV4t)~b#F^JG9EW1Y=cgnnCKTjj+;n~Uxn3oL$%p!B@!s^UYBy4cEVUd36a>MjVW z$LtTOe@VS7Q}33V^`WkekY#yoAkA*!2D2V(!W=GEK#doaz7Cm*>!b71x_XNN2=5L} zO6mZPvt5yz$`bAiII>m6I5AhTl>pI-q#6&%CxM71y7e zUU9K>1&I;|B1Ur>bfNU24|3@E<+^Z?0{^@1ANEK#ht&AeQ)dcG+5*dj$V-yJ+*oWd zMO!b5eoCt8`|}-)e`FiduORncVCT8+eiq$hbf&#Rp9t8&Z6ofuqr&=t+YkJdaP33k zNX2aiGpRZQB`YKve6w&Xwn!5YsC2&#K zR^6qLDEtvq-7}G!?2kV1Hr@`riDxG7`O{w7B?81he_fkCzdpGuw8)AUH?Uvn>GtF& z^Mw8_9aiX+oP7=Rx^M5nA*hheXj>nNM;0^{{U2n^;3?4kpL&DOM; z+2YTb34hXnm)*&rumop-1NevzXitt%WdE8b@`qzHe{UduOk7M2jq@hGmJ6!4q z@Xvi$36w@zdew1<5fGiR%twB=CA1cZ(sEh7Yjn9KUJkc({baN|Od zdMTTYMbQi)=#Ud8KYpp}54Oy;7wiVcQlo!qj?Mp&_Q3UI1TxN@sMw%?cm40Cq5mJd zMgjvK?7FuM>^h!J>(I3aDlG<4qFZ z%fSTKE3l8cCUifIew7}70R0uN-!prV18yl=dt-aYKizKwV7CS) zqd#}@-v~urM8}o$dva1v10CB(ktFhHwK0ep+I=4$eh?p7yPNM0bO4B*Pyr=Q5b$P+ zgMhR94|;(O$g?)+*0q>N|k* zgWHoKBfBG7O+Dhn9#SyzOT@EJX=&D<@ChoVP@G`f!N`t!F;HP))-@M#y8=LBO<_!b z;|p&0ek(|a(zfN*#KdBdJJ511^ry8;nYeCif7JH8n#)&A1-lUxa9T1K<~@v`HyOE~ z+J8ex>NW%q)9z%0Qe%;SF)tJN%t3Zz`lq6~m$jJ6Dy9D)e&LG5B{d~r^c`nBpH@Bx6t zeQ{#-^CKHZSTHz75U_&>q&6oO=USd*!L3YqXk3dJR`zZ7aAPpuZ0+p7Cg=kOs!ZYP zkNZXTY|jreT13a8LxrzAoAF~J(+|a}6o(~y;|J^&JZ?OMCK%iGRrTqr%-y;=?OkK? zg~=yWy1o$W(V&59?*r_cS`f<%^2#X1mJ!$3;IE58KD7XA8)~%O(A`FqdiScl+iihX z5D5NY{}58|xQZgkeu%7G)QN_k*+Er#!aGXW6&c8!m!Tuc2W((~N=)Y4=g>A%2;OEy z_Z+ir@+uaXD)+7gmCVB5WXR?HR)7YvDnyivh8g>UfMyhX;#K>!KO3%-K-JUBAsQou zIY2O_@;IJoiPE)p9peuk@wR>Hz?*6GCw+|PEP=a%do3A@N0njfhEQElq{ zx})H_Opb>74HUE+KKqI8JTDHj!#x23;!ADz#?IfH?;)NJ2>0@~{^HSQU-Ymy0tr_a z=>~uEeI(To4@-a_94$i%HI6OE$7S++pp*^Z6O3R|<7RKk-!ExFwf7W10$R}Pr{uNu zpHT?#_G7dc=u-udZaYzY02EEEuMS&+>Nj)m$UFv2`HFPy?k3ks39p}mRl6}8oe@H2 zmnR+YPV)h`i?oe-LOms!W!sboE;hjzvQWt+n@!wC|9zSiC!Emd{tVE69IpS?oF#SG zO_II)gCefr!L9ZM*V{5N?W|*`GklTFf&4GGa!H}AR656zEwGWjp6rj!mcIVm<8I{j zDfJDkWB@o2xLSud#(^@}h~|$GvHsA|kZ%&)iNkMO!}}_)dG+adR{xf^Ja&K~(Ij8x zCD%@q^nz3s@)I5a*wWfl?IXF;lG;8ANe2Kl@iD}k1TMPL@{Y;#kun8xD>V?V3&|_8 z-ty5SnY%-TIPO^Soy->7x|J*w)>TMp?9Y@4==SkJj@*5J$n%&-D#2&pSjsFB{AGEy z!?nOCyI8d&DG)l>6p)KP)$dvhjtZ{(G!;f$a(dJ0;v0Qd_S05y5I+y4?7Udc;LHY$I71#wBX2xfpSkS+C1y zamAj@7aV#qE3>q*6kM`g>rJye0`20${-O&Cs1OuI^O}HT-j00`P$nX2aBo(Dm+7@kZ<F%x#%3lZH?40H=La{LcUlxc`=p^FO9X7Q1bdUbGjoS?HmKzSfl*!X^HRq#axabcnL^ zeA4_#X%$cY9-q)v13|!wQ0D0M#4e68Dt-cU#GcMDt#t_NlvS}wY_n`bCXd93p zWKe(AZSx&gA9!yca*^)iwHVbR`v|)s%xgeSl|{f0a|Y5b$S8kf9V!j|3w;hy!3up_ zuM=q3GnSRR{fW@l~=@L)}&h7)0quFLcwl!E4e43Un_jb2Io3p+05M(vKa`}hX2|# zVPofudw`b2t-9%vv7Bj{pzw-J^`xFx0KyN#PVMw&cGg+Rdszwl`;hu`_IaXN^XADx z2@Ls)fxYJNrIffzyg5e?ft3DH_fz|c2=Iksc`$U3>07J~L3-7zyc)|vCSeDp?ph0K z1V%?f63cC+(Bn!$na~-z8Udl#NAZ37>7?&Ogt#1pn1Q{$22v>@JR-O;9;mQ)_|~s8 zcIwyEC%>jj_KIAr#ylOaX-46zVjV-+CElvwPNC1#NqM(G} zNZ@10v0x*`%3xMoHh8%0p_lmy#9R^kaY=JJZcuO?{Rgv0RkbNwU{$fD6E{~ zydLPMY?Z1;jH|k-r^>`FZ$znpj$CEnTZuw#@i3uXJ@n{GVFG@SuHXz(K@*qgE2@pJ z(({pGD5MI=HK>@)LYHDfEzna01~-Eq04;MZKit~txO!gJB}6mfq1{NLemCu!X$`se zX36}?Bl6s=*jdrFO{MU@8)=}uplt~$?lN9Sy8`WIjZ=mwT!2#0Hx>h#s`0un+Qjgg z?Fi`S;*B4oNk(iI|0aZ=7Ov;^subX>IgkYhZDzMddox9EZXtB9tjrcDfeVZjD-4y$ zHwctqk-+-O&XW(wP> zND7J|eRTUkYF+K#;EC0)kJ~!>7g@dS1|q@0rPdKXDBS6@42`%dadX;PaD~<%xqf}R zT#@Gkk~JHLWbR&b_ySt~gs8zI7sf!_Krd;xWG`*kk(@=Vn36ZQm~%yDMUSAGGnK&~ zO;vYr)kvnA=Y$}N+ncB+89NB(rNQ_GHFt z`o&O$@^#5Rv!J77RAEbl$SWrc@8+wHlO**JpcUjR#(+ZeqRHwvMj5!Zr23fBE`a>} zBdN7hzXKb!zIer+=S}K<4#ek3{PW^Wo%gGzl5KPCGhehuh{J$8cLr`HCb3RR3`e=F zx?|v;e&{dcRv?|FUYo;KhGXlQnr`rI0rI&M5FhVwt!e|L#e(o`Odcn^uc6IaG$L=r zpYe%|4M@2gUEF0bfXq}l2Dt)=*Ol^!$K;{)FB#t@Pe=HUD_SWMRb1Sye1-)dE%C&; z+c+SdDk;vZ`M>yj53nZBE?~GoEw8njI;n!BYAq@iY7yB4kz@h{A zo9`%BJb2#lO7z!Wq7Rb0_7(V|1<%igDqq#FYC~&Qaj;t)a|Yaw(TaFpELNFJ^ra{? zj&yyRdB@I-cPwEKLF$P0M{5dV{|%na1J`z`(PCLdeFV$LxHAIw?`^LJ74bWYfjk*{ z5At=RmFjf#QAmU8y<+>}z_|1pPkNr6Q}`9qImPzk)@b)QQlD>m9_yO3@94;aL3t)t z&p}c@Un2-B_)9jvmWp(N`lfpR6zLXG=%qw72Aw9PzW84=lAaJ@U0yg4Hb3i*rH|_l z_ZJ~T_5gTR>|{@12s&Kw1g{0O*bj0DH_-*9W$ez-#v*s-wpX#X?b339YOVU%$(9*b^$Bne!}&|k$cHuhJ;-$hrjn{9s@X@ZL2wT$i_c%D=hXnm?~Q!Z83D^r zkp-9c4Jf-Ls*Bu2p#zpo71(HFI)$H+(K1duxB5||K8&8`MD!MdFd2$Z(fml~U5XGT zPdllsBOl~PVw})Fex)ZqNrpw_AQ_oo>(Az|OTTl+(sdTtl`PAe`{x~UaGH2)%jQG) z<6HS*nAp&y{?pDch$~SyYKLGK8<|S1IT-7HYM!9-mA(tscvvsT^h|jXQCpWhpt=)# z1dpw~;oExA7kg#V=Unjyc8W+~4vu#(09q-L4vgpsQj52>kRk}|Xr0_pFfy~AcoyuW z&e>)lTzuGcLl#eyQo=L?Rl-qG4vP-)9kC>z@3+*vzL&5pC!y+KM+5{4{&79B@RY-@ zl6A}rlz$Auu8jMkt{7<{sV`NyApV`a7p!EE6jmL{e-pt(IH=f^6JCaaGvHmV1M1ECtWutyMov#vGcNvq zKID%0giJWXlACwj%VFl>?(ie-lhEQ;rMBJ`3}Wz)`HATd?qr``h0F)E*O2#wh?ez` zv7$P=kGE_55Pc$?VsMUcP#@G>E@(~nZ@LV^zbcVEuoQ^Aq(ev_6YenV9y7|wwp?5u z2p6JwJKW^l15^FR)o7O-?m7pXW0|e6W?Sc!{>uVS^%f5THO)Lw;0{hVY9NR) zNM-}8yM4Y5hSj7z)n{jU^+6@Q#o<2KqZ-H7e%z*LemOe_JlBy8VfV`Vkgr#|=AX7P zXi3;1GO+LnHm}>|ZZmsSqgtcgOJErnHcnx&qCe(;dk?XbXy;T@3<8*8LX>aPuhdbo zNj7BQ`AhI6OAH+mBFaDQGy77A6!ZU1g8-Le}t zNxissu!wiqxeyciIS(?j#zEe~1^`RaQgNQWXh7t9CAEcC`C)K$MRxbs<3^zd4gIScv=%7ILg5M%U>JL912>&LinBo`jalNedlpCrFY!_BL2qrB!=V)I}gi8Hk5m`=#O&~ zWj@xva&aPs_FlFuqRPLk1>L>PQ4vS$RA{w*tSaMcUZ`ONaP0lD*; z+8WOLu{ZZy$7B~8>-g_qB7b#R{p1#Vb^>V#xPDW>Tj?yU=C{b_0=K^?z^PG_A@mut zVUBnx#K9odVcGL21477P)t5{GEj2RJGjl)vF=-thk&m_l8$1`2wf1C3R>&oLy-+11Z>dq1clc~IpT~FLK1SZsICvcu3~F>k$->MC z+6^^Cgiyzi=}U5g*1MB~S>B&upxQ4ITG&JE^^8Ae#CKeEJ|A9$4UHag$?Ur@qVdw0 zjCNL9Ul^z!-JT$B7Z2?K-*A*n!}MiV-mC@`Pe<3Ewq0KmBeodP?hd3?QaPc8wmhv_ zjCB+*vvb|mF4(nAVSJ@)m;_k`X@VBFipbS2wZu4jOh}+4qZ>n7kVsoyQ#oW_Nwel( zU@fAqm#vK1WIK=F3927r!hQOyf0IUdFOu0*^xbQ{u~DqP8GBJY4>p(v*O$E4Zhj>g zy7G_QS?-0q=`>=UO=hOZg5o&pQGXGO_PrY`!}5mG8w) z+06kga7P0Z=|+Z^+LtR31&p!Zk3k@xFooYafZAs5*WjZco#w50_7K8z4*t>|o0nc> zFQ!ImxP&fOQ;7Cn3PYH0ceMzP$`cGq?0=miRy&Gya-~pbspXLo_9Xm%$}<f67ag2EcLDJ>Qh2p|>scf4<5NWDP3 zpulH5mX@J9;f>M!(}$9nVzuL~&ZP!TtTnf5?H+ij`ED@(XA0 zIQT)(EuL#t>UguYYL+*qPyYdl@6F^-Rj<7TZXmr<@-{SPUMcNmzhg=zO4l zxM2Y0uZ}oC)VMM41tt>WTk+*u_DkUbL*4>ztl+6#YLvBw2hobpqnw&OMi9tgk+TML+rmKEGlz>tW=ra*{%@>z;ydj;3+`Ib_Dc4*2(l`CA&7i`y-1#`9 zz$oe=Xz`^vq$;%fBGQMLa76X0LK=M+7osv}0}rLJr$b1EszY6b$F<>$M@|{t1|{>3 zBb7HoCY8X!54+W*px#pSK@idnAiC|hSP!`!oOc4Bq9)xUp#ygf#Tqk`xHCC7!1x^X% zhI~P*{w(!=bOh_- z$Nax_`ew_Jt?qec4mahu{uA0bYJXIpl@}eWE(rO{42)VI{r>f;SE~EbYbsI5|DP_Y zkaz`~cpf=*mMj4zal$fq$2RwdEZEM+qL`Or^OWK3dhQK{?;I97az4A~hAJ1?2 ziB^|2e#bq|{Y1SOCETDSh3HR7{p28d`H-*%ge6=Qv*{a>%$2vX#Cl7SeWp)C(^rs_ zxgQcgfugm2x4I#~+Ys1C|4Q|FcfAm%F(8K7*DD8(0$oBX=)FC8h@U= zg>kC_;(Uye;WD?!#)!l&zlf5hXu97@#NLn@W6YN<=}Ca3ux8!0&3$z?l=FCI;inMGc|K%UC(63%6GKcbN@;3( z$+-vOgm)i8kk{Q5y^X>oy4z}&;}pnRG`}HfvDqp5H7b=}Gq|){_GFbJ-5X3>-OZc! zjl3JZQRJxV$)4+o-Aa-}wEGjnJW>DpYzpJfs4sJ$x_CI5EIWoW(+G>mk3&$xkt8#C zprvCrZy+qnkSci_i(snT8N6F)9S>w(1P~sk?BTaub%!q&D1u@SNWHftsr^}mA$zE| z`!2OLH`<*ni?0w&0E3*I+) z;E7%V{KKmA2EyY#0>UHbb))=HJOo>J^o~<`@q-9=hFMYcr_mC=(Sq70&wORKu1M*NDB8FM4^N^+waz60#Gx7`vg+C?Q|ZWykCj&SyH+ zsS*m8jBHJtm;i{T{$GiAEy)uPt6l=RcdEHOSj97>ywVbKIo&8rDpth1wJrIm`$}Wj zY>F$xn7i6FaMvJOHD{bxb)!@o6v0&Ki}l95lz`O5vlfviHY!ppnPvFh6DZpOMTvJo z5{s=N?+@i?jmc;X7WoOtxexJQ;==PRHCN+Z;|r-G*A=UU5Pjz{P02_MuZ3(ct&+sN&H0#(LRN|W zz9VZ(gOz_nCk=DW-0ATsx{zh3TYw>wfRL{Zs+R+=I;7%vphRJKwQ}#m?b6X%0*!9O zjJ5ZU5R}RSse!HW!?8_%tlz=7yoZ6y-aja=HUv74OR4vW2NacHHG8@dGKsYv zyT~%e$LHP==&US3t)7A`e(tpzNdFv}4gzzHj+zP^Ez|qxC6xwIV^D~9AsY;*uKPf5 zy|S0Sy_$X9Sj4$7Q%K_gQo_LWjxU3to@A8DjhaZjBAzsO{p0LG%&wRZ!*K$-X#;VV z$5JU3Vao+sMP1nPBvi;e z+Fd15d8RINm#*m7m&ZxxV4n>$mo!xo?J)DhqnQ4dnnSFYS@%VeH|tu3p$AnZ8mZ7) zo_qa9G6eiXo`fITSP=^^i7ZB=|A-3IyMd8vc9t(b5~5xXL{#*iL{NR9c3W&8ceGV+ z)S_DNR7U?{;QcMC7;pxH`tQQ>0?cZ1$YbsE4s4fo2#>r9?+M5i$T-7174+CbZN{1F zoG#HM$f`$q681t;e}Id%IK9a(8YfNT!N1x1PIK9Q38)pwfe^Ne=wq@2 zmEH=AZf7uWH#3S!;6#9VEn#gQd61|1BE(kpdH7r1O_`9pkZ(>?{pm5P4Jj%_Z)Eb;NEQ~5i+Q4Yfi~)ZVxzmT zq*`}Kx}ZkzzkD>C+e~0*O z-!6?odK#=f@Bhhh0Y|43(FLM0%#hX$*?{jm@VwWL_G5+!Yy>>p&zR?;hwLxaSFp-Q zTg#myf}H4c=sOlar$0kt3{OL!Z^&dlHA;tEK=+m4tn}<;6ys?wzNho@AYZlDx$1#f z(Fpl1|F#!hgY8rmc9zCSFi3U84w`k48-~{kfxhGJDSCBO1FNs7a+ZP|6t)$zUzT86 zuHTExx>6Y_>LPb2i6ZP~@9-_IiDpqhfa0&rKFf%1>h|40{>(rPS-b!pDMgpDw(LRk z=CNcWL5w6iwM5)=4)p85F0&qVv8YC~xQO>qWD^^3hB|&!MLS~5o{H_?I(}!CxBjoR z;J5Sy13gMw{Tetr53jOi?n=BR`bqn4y>Wkl$(mY@oV*uK$aw0A@;`vv?J*fG85Wurwj-YtP7>L%@O>w^Oy z^V75`LxF0#M*{T``l131oOWbqWqet!$IUL=k2;=wt%~_bwWuS}{Ba?%n$5)`VRq!|rABEWB{*TOOa67-@cgk)4@c?)v$ehGJX1IJ_4!;U(JwTUEx4oNn*`C}2FF1`?zpUypAdHs2ioFvl4bg%27S|MmxpdmotzpPXQQ zYm}?FbB8hsgY+pf_^bf_66qWyy<$9tli_OtNNaPk&3Bwi2P$P=LM@+d~Yt9ZVw3ER@)mpt92AuEiy5DJQuGp*;cTJW2nAT?9G=k6|k-dHXM8e2kGoZVtZMPi{cF1Ugm-)E^kyvZZZ*TZO9{W zLSODQL2P=}E(!PvGXg7Zw4J)HM_lzgxvFq4tnScQwt62lq#&ozc!Ib->b?vl=AQ(} z3{1H|5QxbYf)uE2`)R?r8!xx3v{N<6TO`flBdr`UcX*e+-bb}gm(|Ss%3QtVmHysl z=`O5$(4t$l7cTQVCW642ug}9j2ml#ni}_GGN)CPG(Couc*%~Mtkk5gpFm z?RooveNg);i;_k2PJVZCvq|Q&f6u0Uy1Z0 zjZGTQ&f?O-Z`pCV`su|Zb&nhMA!og9mT6<_JxLkLdBiEP9Sd>A3sfxZ;I0PZL}|z4$sA0`vp!hHE9;n?Lu>sEq8}l zel;)dMyrP`D`|Z6MJ=Xcc6D+VKDk14mDZCoH`KHfY;>WoYJCILv}YD}^lHM~7O*q+ zTDK5MZ&rH9Ze@n=a88es3@hf6mBU-&hcwY^>?6xYrHGwmp6fe=7 z%ocx2anGTBS)0)sI*`o#i?CPxqW^i+Nq%O1bDJ55)ZhNN2ZLa~Y>gi`%DSYQqv|4C z_q^7g6mi{UdqiiG3-@a4d_<&xItBR?$#tmXDj~DK@47uDJOQ_4g52t`T8gnX#dFJgLfR^OAd^E>TIrJ#PyZsw3J? z&}F}~UEGdNVW^{fWYxGy(Jbu*=KG>kR8TsZtT!Fq3` z{6R8PHu_?J@ zH@@`zW`b_`@xbdX9^re-DD>#MEX(57rJD9qA8T@Z2Z!!@7xE&bRT~KTZS@w`;ZvLf z>hipajMt|qq3vOxTC}uGC-sLAiR#chtDMxz+XS%(UG+`5Cq}Q&Ys|W?quny2ba}jG zPKj`(ieeaUSxMZ`w@fTl<{glawa+MBWlrzC%6(US*;3i|JCFXQtmST|e4%UGgKv5$ zolm_Y$Q%;-50+%_=2gvmgMq?O>Ai|wIpf# zya~%R%C~};{Lwd}B?NotwlYtmR+V6`Z<{tS$-?7>@^YN}i{Ufv(_~Fn`OF?sOmy3= zyttwl-n9BCO4~`ExB_!=eVd@`NeL8=p0FTf)5U27tC3#KjsW+*tI0HO$Dmuw=oWJV zqllzxFmhqQ}e z6?)lzS;nYue8}+AmFBX)lXsHU!@cHCr2e-nF_AnxlQ`Ud9h*|z-)D0xJEp@e-H+DE zq{)64EsUv=))wutPA@GjsWT5$kL2D-w)d#xH@U#7e@}K2EvDavz@`@~&p45Le@prx zd*k1>&H`qi5bxqED!Gw1KI|;;*0#lOxHpBx>^+iOcXK+cJ#tF2Fg?r6swbIEJ85Re zZQFpw-Y&(6^xk#$t}o+H1V-1!=Z@bEpD&&YD85JH85wu8V4oD$M3bse2NW zxY?_06cElBBUJt*_M??fw~q0!sgZh<{FCcSS5cPHJgcX+wEa!QdgG%MTP%X*ZJ3x9 z)f7|Mu`gG8v^9#}dn=bQbjIbl?>(}v-_4#CNV}NK;tnVDC9)X(uSyAoa8sTvwDh2L zwIxq^gG-n9_BRKWScI1LWxkyoLaVl<4{tUPR{WJ)Q(HFvg|%W`Rmd{;h}XUW5ZBLh z<;L09Ifx<}1pV$UA0*F~?htCRtJftFGitYdk^C2NZ*i5aKTULkuX*i5(kOFZIoSuq zv+Q4;h?flCO;B8*iHDy+_j`kbd*`!qN9)YJ^QDozwtl)I(Jo?}sQGq?SN$^(AAPYi zFn3F*miA{N|Lp9{g7^f|aP6z&mloLzZl!!h6f4b%C3Vj%0!8)5Ct=>Q4Pp=1%jWdq zYl#nNp8Zrtsp zzj))X_g^H)^bi}BN{TLjUIh?&G^^BROMuC=Lx(9-L6#nDes zh_-5kXEEuY?A%n{UeeBtcmgAwk2%*pOJI%O?>J7h8e_NrLb0AZ`m8ejjOsRv#>lsb z8_yTlq}eM3XD#TXR}*4~8_93Y$)r*-H{WKwDLy-_qcd*cDUsH9CYdpu`)ndhM|nf81=YJe-P~on|~*Gll}@?d7r-yg}9XfWyAkiy#4*2Uwm z6dCNEhN$e==%*$&nIlzYv#{P*7+safOZDEN_UykCk}EHx5NR|ldz#YZhNpwAMGjWbIXK*UdZDNHu*WZ ztaYh8>z&#bJ6p191j~BokqVc>RX)v<_cP)=>sWhXm2~kKsREERK=g~SvswZasy{K3 z^-iA%mw1b@vn)sb+&I1J;Wzpc>28(JhZ0{XPXSNF*<)wzPoa~3Z)qUZ6vx)hh?7A5 ziopLH`St(4^#8h287Jv4VM06OP*wj=L=cPVlJygEO7mi*^8fW|lyjJ^Q%x+efjP*J z*;F^--Qx+5j}0;}Y%RRuc4O7b9}81I>szyR^UpWW4^3It8@##D@5h^~HecLvaB*s@ zQ1!t@!Bt4f`mgp?N3tIW7AJ)~TIQKp_{->)>kP+o{ZZ}~y~Hzl#i5Jkr_8w<0&A6B zV8l>=(|pf*ulv=}Iz`x`+^_l~k%@^5#_q_{mgj!;gq)%{L|Y)>=)V;NS@D837BTE{ z_7qJ{v2UkqWamJ+W3JP%JX`vbmTO6I=XrOsMrdkH!NF$7!}?XN*EzhTeBB;3QiLom-z~<&+PMq+7CVL^)xt$H{?-n24whk6F{XR~7Px z@e^qk1YYW{YeSzf0{v5(0PMjs{ zmNMaf3pDPMIs4=wQyi1X6GT0Nvx!GTIAMuwLUXyJ*G{M4 z&N=$oPnz0N0~@lg2@|4wRT=L)v8Lvsu6=l?wR4$9}`Si+k!v8-`$cjwFk zPE&q4*44^5=->G$vh!GuRG>;4Q(;GIqt~@4O;m>y%~P8S1N18-e1SQ1K~x<+cq}LE z6%8v22r6E#K;=Gt3MF}&vA$*>EI!o6_U&{mD3VUhmfEXwf}5fB8CVEBoF3c;O?`MA z`kV-T4oVbRqUOf7L7f%NO;E%tXl!m+A$+))g9Rl{hZcISU_sPTx+Ru9$En5v6_)7= zL*eX+dP@8DuxJJAru5Bm0ZX`?%M`tZ_GQ(GVfe~z(dgx`Lyt8dgL=b8o0|v~ii7U? z%|nB+wVL*2F(ojtUKA(PCxL8`*>g+!z+DLA!Vh)9B8 zWZ@488xo(STDC9v9hZE-slv zSj>sE#1^oU<4?hqNc*AnKw{7%m}4UJK@+P()DbptT#_!SQ?{X5;*G?hOApX2xX3m_ z@%}f_u-g48ZiIfULlveM1vg{4j!BmVN1!7PJ)#yUk)4Zr!n(&LUFacMp>*zu+j2$> z8r73H4OZY&U5=sGt#P({hPt^*l|R-E9bu!nosO7Qw+E3`A{vS4fOo;NIRslyTv6aR zm@)(JGnS!vEVwLO4l`;gR5J0xr<*}@YP)!mh#lth?f}hr1t6N?WyHayW(MMg+h}gE zpm4+@EJPDJTb#>&)6GSk*N1L*e+GlcLnY_GLCvej**L2o5vy=Si#nQ(q)*^QK@b#^ z)fJ9GA8r+$6s z8CB+3cgGyIpad#OS^*@VAB0#{v!(@Fpp?TL)*v{RvF{i)C2 z%Zi&SRDL&O>xWY`ft>mdQLfHQ`72j+M6R4uAM{7OIFj=i>j?5?Pp`>P6y{h`*sf)ZU7UgI4mVdbQL~;^4EPX?!d0h}TuSg8pQ4*tEPbxit@xZ+84}Ut24BeLw)<8pCMnpuUCK1tlO_|D+x_vs zhkvIfH9eEAx=WZG^(rVhz6_S(=4%cFM!EgK*d~9|?h6$ylkUq-o@7x)&7VsoUmbrj z?5%Pt$e2Mc7{53y*Q7OjCF+aEmuCuF7*q8Jn;H1bl%R*LeC(HmfwV^^mbtwpka^D z)#XUevCz|RWFk}+!vkkun>$F(xM7I!b2G$^#DpNt5ul2JsXgIMgX0`k>E+@qxJODA zBMIrQ(xIwwQPgKf`JR;>CdcJq$Zb?k5Z)4HE2_OSCYOHdkpDbEf%JTJ*0Qe(-h*0m zv~R0LT%oU)1i`_frvS)HnMlK^K*;_J1V}??AZC-`T2ok;DA|$7?ukTvL4}`QMN-5M z7n)IscRf{{$H|$BL+%TZkm64U&S(Xt4&+H5ek{9EzEtLi6rB#2Y-OnTsWL7SWOAA} zNM3hb5Z!`d!Wx{{aIXWwb6KK#c;5!EzP85+abM&J{!TT>8QC26?C6La%g8}523vEZ z>}!}3BsVxc9!TJxphZD9tQ;t>p$9^|h&Uv>hTPGdRG?8=uiAv3titQ3kyt{g%t=7S zP(3`x#6$)<~E%c&jt;LKc>LNbtaN_L1-fF zu1FBSI&{aOIXj9|${952t;=!YSQwTjjBb7^ldYMVF7 zJedpg4ZOY>xA+3n@RLzh63kZq80v>$#2<;CuaT&X-iE}8CJb3SSs<~45})Y{K+_$@ zCH8SP6Rd^5@DfC_`Jyf)LPabNR9U=nv@6fc{io=_d6M~9gW64L;gvy&o{Wt?5Jr2V?5zs=- z-$-1xridH8&jd9)0M!L0Vm0ANV!uV~5gm=%o{l}lAKQ&+NBk<}5ESc%W<%#Fs?D@I z*o^DYA?SqgbWn3iu%^uYy7V4yzEA}v+U{cS&T7;k|Ank3M7$Nq*a`MQrD4+$&sv~~ zw7-kA**@q13}7`*lb`7?K?n0S7#h=^D$Kjdw%|h7609s%9h& zZWc=8M(A_+FiW6+>v2tP9>ay!*rij^&^^WpT7eVHdoU8;7aXLyh>+n!t;7wVX7^gs zKL5`5_;ag7K5)nTWe}1bH;=P`8go;rsNK_no`Jg70|j6~?m#F=%pt?TpN0$+F7Uf> zjyKN6K9k|5?r@u`_k6j_(I^=P_swH+T6!Fl{DKEoFlf5a1l$Y}zEqDbNyqDomd*Y2xrFp6gKwRQeBB}@< zB$hiez+NnOthtB_WZ#hjG)g^q!}Lhpg^WY~ zojA8ib!e`X6kZMuOKM);x&zI1NEJ|jOkyYULIkN~+WZ!1T2?g`HEjWI@a)8m?;#i| zF!tGK)LPv@zB&75BIb(14Uk>9jskxXx|f7gglA?DwlG(E2|o!!qJoU89>agk4G0n( z6}$o#{=X2nv5w$)v`T?UY$h&rG+S}Y@(wZuodXd27CZBh>`qF>jU|r}Fs=MMo1k)b zm6L^n* z!tcJoDKZ}K2n*LfzNBOzFydbzHg>Cb6<`P5U6G}kA29^OAa%nzGk-5KQr&TJI6KpCGjZ1}5Sg#Y9vn6Q|)|WcN%*iY-U#Z4eLp-@!8>hz+pB4LBWK zMm0xAq1u|C1Zz~VXfnY-Gq`V^K3`viyax#oAx!o*u=s$c=ODikn}kLI_ngCOaUw|n zhL;VubJK8QD!~W81ZTfP$aX5kJ=}B`cqrEq8_MJ$Cjz5l^b!%whyO}UC5X5@0^A+Z1M;Vjs16mM*{!EIApnj{t$o#1O3{JMznbe z?#SohMp0@_I zF!d1yRtWsbEFme}A6a`K=pLgfX260-k7Fx{X#1`_uj;uL8<7~%B4x~cDMl)+7WYiU zuy%vL4;HB4ir}>px2t_|M<)&EVxkzgu{XS9F#J3BB1?-3hw4H-ruP0$YZP#6W(-wCXin zpaSK(mNkKu)N>Kh6-de)Mo-6g*U8x~vbIhagcdDeP~`#b*hnC!s8g{`WXZh< zPulB>`qiaaS4lA81@WGa?(C}~J}2)W&tO~-gvL2z$=k?tYW@<0#eJuXmQQcr8`CoQ zO6gPY9q-e_Dbg<1ZItJ=UxAAPDG%F5wy3$FDAYRYIQ`<%S0ha=fv0&pwOgYj0;A$w zbnE5W?ek*TO`=ZyZ5>s)pVTz?SUFH1a#GwS>Kgl1lhe;BwFIxrO^R*jfhWi=DuEcv z@e{)h;IzdDX6wA8>5POXtdqDMvueE{Y$2V&c58P<$FvTN#b^@xu`Lk(T1$J92GZ48 zRZ2wa-s?QBbj;C`k#i(2**G}89~i+k^mbg}fG zC)|0-$AyvA5n$plj=|2$$MqSI7nJ*(8K`fn58!hc^Qm#34xAgmIA$S5_B> zVKBr|xC3Sfx)Xdoe9g|%Ae1kFU@0yaF_FT!qUdl&1LuhkoCU7=7RKB{#^DtSl7mk8 znx92AH1^}N6OEBLP@}aQ@}`agWrQUL8O9mIZR8dtoIo|`)sF<1nwk$b zm&&?fvaaH830lfD7eiVb_urtDFWPReuC@UpYiwKBO^Vq6T^GFTy+mAn3Z^&H{hmP zJ!&l0$-rmo5z-Hc=D_+nfd5~GE94&BDQpdJ;(Gdb20*#_)@og3GYn}tYm@rh8t0N1n5j_Cb*|TiH7RU@pfU)aAtaftEXTzU(^cR#c;#b z#JDOGNyLpf6N;*FW=Vks3XqGla08a!bz8vOt35!C7 zQ}Kqdy73mIoed=gnaZ|-YVhiKoiix9&{qq+&WZFCh^YxN6}ja*tfc0eXt-3dkr zhz@&vK^vA;dmQa{>c|sGw+SidKb>v5XEAf$cZMLsFF!*efPQ2D2_!r{mhwPuYgRdC z3?!VQK!Jp&(bMwwkNsw8>baOxGu5PLmZ^A&p^U0UCYGl8#sdFbZ90*O|5|C|$1Cu2 zrKU5MFuz}H;%v5gi3zja&(y`FhIw$lb_6{erLkmJZ!qobkxr9${srt^9g8A@Tj3YXvJjHFP1Xr zErC9IuQ8o$Rtc{V4x27Bk)bDkG`;=Lo7ANyOv)Nl2h(J@`ke{cbTyRwpI1M%GhvcP zOqZK}hu20nZTiPu(<^q&r%O%jOrINWru_N&Y|{bz|1@iosk`w6waMfy^SqtOH>T(9 z4KEeo_vSO()|z^o{k-0UDcWI5{OtbBDLuPujjlS8>t|lq-YQ8axcQw3hTH(r+E-_hY zn&8g)+SP<-V#4RNxtVM;HF?kcWfe>y1fv@0Xc_q*#RQT~n2ZCaOU$kUf*N7kMK+Xk zdL?{~%;cJh$x}`X{D!Tmsm*G`dpI#I``Orm{}7YU$18}K5`Q)j)2pA2J({wbN&MNw z-}KNL!+SV6F^nbRKc=8%qDpnNXgW}6Fp5f=`~!>g6lXH2@KawPp$n275%){NJWR?DtgP3`DQIlR^wU& zDVX9_lX3d7UH_kEOfsbz+l15fG`RDTFiqdAGrX$8pD^)$lG)<@Au!PeKYmV-_!Qn$}MQmrVW#W zm!2*;HD$%#oH6wz#!C01yyT+F30e6mE{f*&4pf_;Zv6Svxqqbw*u~o=oLEhn_v+sR zspiR*wXJ_ACP?HSrtJ6ncSoI{D-PO`qy9AkYat!6-T!Il?N`jcWm}a8bCX4s^Gmtm zj?ZN?$1m8|UT@ow&Q{JGAoorF*W=@@rYyVhDIu%hnCG(tzV&R3riI1s-ZGqam$wF+ z@bK>F^4Fciv34oi=YGW1`bMWT`iHK8=43f#A<<3sZU5(rBM*nXxS7MWF!G`*wm`_x zmSCqyKd9fm&vNOCJ5AqBIyO>0TSVn%5$7}1)g-2Tid>LAgBqU+2% z&Yn>ddAaA7A;dJs(o4|Kd+^+A_8Ez+c_6o_@>Ew@c;c zw2qYSg4i0;+toL*3dSAy#l^VX!TY1Nf2h)I7Yx~)@RF8_Uj>lJ9XT<7H+YWe3D@d- z!=`wnX)#O=I^Hy8PF-(02fKw%;O{R}!*L-Tbb7rWJ&kZJ;OG{@HGrELaU>1ZaQ-PA z5pE8kf^$UG2uIH=;QU`k93sI#8H4kQa6~wY5+Bv;G5sXt33_1!9+(VAgi8URV#L3M z<1m~P;E3>P07Gy-)ril4;|DmO4o8H~0_cbHnMNFy*9+$sa76fQ05O~|`~)+!L=Gok z8E;s^u^Y}I*5ea|&jskjA2t+>DnJd8z%?u5eIgv&jn6Cqd>#P0hTcVG^uRr9<27_o z1m_drxDe|9Lj1Yk;k{GvHU z(}<=HO&OXdG&N{C&=jCyN27~I6pa`fiLU{mlh`MyXQ)T0C#VOg<*3D|rKp9dVW>f; zHk$zUUjp7`IQ?Y8>iyIM;Rk*2o1c8L(RdjhP+R{=pQx>f_CAsvv~>yI*pD>zPx|?1 zqtO&vG23>VTHxdLvAO?jDr)A(F;5UFn06_pp0D=KR0m1;n0U`j7 z0Ym}B0K@{&0O$aS0{;zg9N-kd!_ByEKx*G~#x?_vekk62i$Q0AnlKt*i$7jLzZZXa zi_r|Y4G1y=Ft!hxga1yL*l_xZxmU>1BflID-#-Eu(6vVR7i}_lsRZeYQ}LggjXin3 z;@CCP@!<9o-+i@tAM4SE%vGTwFMQY9^+(S)Y_+yLF_lZWH+{@iaNDP1Q++;__}=?n zGrfZGc}#vF>u;|w$?-wSx38B4yj?{v9giF**9kk84O+_Q4s;g$&7I?|I5B>dbj#(d z1N4PMK1rKJ53!2XV~ z#rACvn$!H~HuhH((S)m?D+VwP6y;zes=N0F@ZUnNu3-1BK+5R3ckB&T`=c2 z)=jI{YM3W&GS-@lBc;Jg18oFQ63q9NL3-=0s76UO!&x@bK){>|w3SBPsWP13tTz+8F} zhr1V6yA8yM=O`U8P$?6)EYEE-SeAlqMvHLTcH9QTNWQ52|B~ZWBpu)nS@g8bwBHN z3^%Qz{?hkijgKyMmzSZxEJ%yJBwwyb*Q@_~d z(X!vpYZ;zPst0VQ>~MZ^OK~J((gB{^SE9Vei)VQ2)=}yfFp{PZjd1Uzg%k%nj-|-Y z_3qD8{yFB^*)csMzV~-w$|xol>WlW~$hE3tL!wGw)>0SB-}JZFhNZ6ER=U52L&v(( zxnn`2&6#5Z1hJ0ZzhOe;wJjD~)D>UvVYHp!7Tg9gk#O{(GI6Ft7}}9j{s-x5?mq{e_@F z7bf%_JF=X5FH%?heKX^Vr>L!)F@tnNa%%m7nt*QamLJ5?A)^63R~k}N#yjY5(z~w5 zYZ1?}t%S|J_m~Y>)E_nZe=!1x4(I2v$kg`BV1u{GkARK8v1PGsl z#4J*O=;S8=qz)0R0zl#)X&3}Z4WMU`nnZwbq!y4Nfxr`BEdb&Z1nU6MGf2fCK=@}y zK=^t9a|B4tZvfZ`fb<}OkGclwZv-E84$_ebknTZ+Abp7d;Yb%DorZKg(z)A==iA}9 z0|41|2z&u{0!#)#&tkjaA1JU-`~ds`(2W3qKmbt0_(K#p?g97(U@yQv0Ho*8eWdGt z1we`v={!^@(tGIqAOO;T&PE7=BWkRR5dg<<&FgBsfiy4z^pLv|5bj|Fgp-Vb@P$S| z__sztxQ!7Iei&ep5s(r_*AQJS23UgT-xiSX0G0yS0ek~64`4pP0)UkO_5j}lAQJ*v zB_GX*<$#+3Ae#IX;A;S&yHCgf69A?Hpg$tOG=Ptm%#VQMe<^1^pJ7_G=Rac8;7uPf z%28Z&UfFH*rdt5Pz3H$046?H&0M+|n*?A3B4Sz^>=ED))O@(XGCiIH|YqzbO!H>TY zxPI-cFK(pAf4`OZd71gdu}0ylMTbik%~)}2<(&HYOPB?ZK8e);>h z-%0=C&sz6q&ZFJJYlS_Y8!lg?w{Li%5!XD7!@?DP!)baKYE9K;hm&6pl(AM@%sZLt zPy05f-b1nM%#n<-U&$wf^Bjx&HeA3SRqakag8gvbg>%Kr&FNnSc1zY|-CP*JS@rhq zU?QtMgfF`_d~QGEM#Rs%!*Y)<+2S-SX+i7f6Q1u3aXuBRl#BOWsO}!~-YFE<${SUa z6+x-?*r^&T9qsn$st(;Pdr8LrEA5GUJ<{Fs8yTY`uiYCG7{$NyQU;?>e34Z4+p2KUi7r& z6MRJ3S+nG){TQPsw61?RI}CiXIngJBrDg%(L1!H=*I2;CiRc^>fZSjB>#Ge zeusQUZ+H33y@3YZuk{|y2?af0^qe40d3r(fWh;4d>eCVR%)B3xW9qXS9IpLE-YPLq zv)H}&wZ{Rhg7>w|R_V35J6odscGrimHmg-sX|U?L*J%8QUA(U&w=!mF^ZYCKED)a1 zJ>;e-eb;u990}sAXLX#RoO2F$sWU7#-BsP2{O_1)u%ZSn_M4^waV6Q)(9UkJt0+=@Y~^Pn8_m^CW1!)-&N$g}!lKvk;RV z6fCH;U8DEuD<1!()q6=s-4;37S={n$oWA>r%D&sBL$XOP7{eB>U=YK!X7e6&J-oK( ze<}F?N18KDelwkgAtptDUPH`^m=7@?Vz!S07U4*^ew3F8N6&nefe1%p3NbPQgd;{p z42l5Z=o!SU2oR3EO8^W%L8=5v0|W?1QUOT>1PFHkK#~Ee86;|uMnPf+0m6~SL0Sa? z!jVQnS_D;uDn|`M=ji$tfUQQ@g2a^%oNNO?4Dnpf`hM?={{zs{g3ik!rX}pH+ zp#o9CNKGNJ^fkad05oc-Of*{P{A+-ZA`po|gyVkk5}=py<fGvh=K@&B==d{;smh;L}j>DR2)ea6&aG$ zqDBG|1tiK8C4>kOViH1fGyeCv3AVqr{%@_kRYQiGbNAW%+u#27KJY-H=reerD1f{_ z^7zQZqiBL635p;nav;aN2p(U<;~RJc!(%Z#mcU~vJVM~{Ej*UNV>vulz+)vmLg5jH zOpFfyu_}AtJ5yX}n;c%7q%Oy9bo}F=G;G1}Gl;rO*yx}xFKu*WVP8()|j8*ZFVxCE8`p=@R|V?J3o=6A2-MTLqCq37VG3eSHQD~HGgBvzy2zOzmjaI z()riIfB!XVi<1rg8JPL)MeDZ^7dsTwtVbzsGxlD4>_S{Azt0{K z|AEW&Qu3?F6x%)`@9Ntwuix>a=$$#cbtZaeA zoZcCa)$2QKM6}m{b)A9JQdX4AGk2u-=X_V$b)R$HcQkIBM^>ge z(Rp3A6f4+c8hqTPT$;CybxfKY-@Tv1>gms%M^%cuMCHW=ga4s$_Y6tqQLxS!|CZjETct37JrdyrJ=+pZi{S>UwV?|y$ka{gI$K1g#5bOQ zUxkkIX0NxIH8*3h_DW+fHL5c*r#Ntvy116s3bSf+>4TL%_8oAX*Pqg}Y$Bu$1~zHA zG14A9bfI|OU5UW53GO66@fYV)H1esauKh6;-|)8UB-5uTPISdFY;$J63deN^`K7hA z{9QS5=tDntHJ;(ALi6c9&u3)3NS=xH*U@hFtDeFw^21*w$J?GBki(y`9YLQ`U*yuS z+fR}2#a^<{u!*=8=sSozmia{7*eoq~VZ7}FSK^OI>IWqc$Zt5()J=i2>zInMyIU<~ zZ-=CvGd|73&@8iD`kig$g-wLNprP(O%d{}K3hepIDi62@G|N})scmxn#CzM|!{J9K z{sLd|^ylnG+hIkK?TMsK$id*8PQy&TEC$q6$g;GyzJ|1BHuAklHi!o2!ES{nm&o6y2tF`E$o9TIcQ``ed_96QK_9%n1Y3vw1 z8tr6!;Q3`MmeOSnxtGawK z^DAMEGKu-L?1l#hQ+3b)yE2}yJX&m;XUoWEZ4NLWO#Bm$3Lgxt<*IjmbAmQgLLt7! z|2h=|ry1Z>wK9(XL1V-%kq4U;vC#=JIJo7Z`Y?|$i-(Z3s6P+O3zzPeb~JU%}(;dpJ?FLpv9z2miDOEv@S(fQcusue4ejDvlYD}x7y=vbFgP) z{T{;aVtOdv=@&krwPq#eU@w!s`0r`I=0$CkKkBBmO~?NVFTx(F)})VvwUg%i*q@l+ z#P5U`p{MdcFrJAleZQngEvEH&iub`UZ?2gU`NaIAmOGH=_}xs!JCnK7?K`$r|K+*c zv0mbFU_$?_Rb=T`v``zlB5(u(><$hXADZg}v#r<<_Q%_P!(c{i+EVqU2M!Ay*Y$2F z7+f$LO+QTf#d4hp;lPa5_#CVS#*j0TGAKX7=?}+PPiTU6?gtsnk6(V@==oCjd6Rpc zEV4wDCrLXh2+#&ATQx-PX`G?J6W&hD@q%qJJ|513(cR9#&gsjdE)C9tYnTetA8Rph z(`n0>RBG=pu1}N+@VkPyz^MC$&n<@)o*j3%Jks32K6H#c&Dxzkm;{Rfa|@|}G1Xwp z;494BJhQ^~_Fa0)A~3rw?f={jxt(abAtSn><*3$d$~#ePpNp|iY$*nGc6DPH6Dr%>`6y=#Wsj%`u- z?LVkT8_x@utV{4W%wu2fj?}^!s_&;i!?HO;`g0AGLboBoPmYUpGYtm;D;v&JlX z+5PDi-<~grU{E=~r`k7$~enbCqfkJ1qPE;@&xfw#u$Vpr(M)~WW;%kM@ z8a`$ShWT3OQ=dg>!-d`p3ZiYDE2#%b^Tyh*P^BhpS-RK?Tb_OYO&E+SJUX73Xie2i zXSF$O#@a1^WHvlLS6r70jtY(X>Wz*S)Rzz}&K58?hu>ta^~0HlvcOwlX<&d^=JxJm z{MJ!$nzh~I;VPx%mU1w3VSs9D_J*5fFd3a%VejTN)^r;8g)VHyNMHI$nqOf`YZ*!X z95yF;$*ZK34fDG7-*E23)^-~K!!T7j`Yl7cXcgC;_X%lyRKny}i9f&kIqvkK?C1nb zYO?xE%=<_pc{@cJIr?*#bbfe(e~fbv;5Th+RH1x}b-yN2B)Gg>p zqQm*Xxfu4pvd#nt@&vutW1 zoKxVzi_9Yy!`=w|F9ZqFYsv%ai1`HZSXS+@uOV5__>K@5UEJFe8?=_iGVOWNbUo&0 zKPvS??X0#F!7PRAWa0PLbg}U>!#t%1dGl{w;CLLvF#@6)G0v6KZh6yBJc}vR`!B?r zRr6mhqhS@7eXaWhRNBjt6YjeaWZaMB9JN=}`n4w5-)1BXL|M*MU$J{A&YYB=Y}e|H z=k2@K;VR}6rT&L$fD(dW*mb{vqbE$U9OTEC;KjA7bge#4EKSjkh4A?k>jhm~9~7lp z6OHxAW=p<4fQ%H5rO5S~@1bW!+8*r%vJl1Kel(=l!BpS{7FvRapX9mug$qONY zp%*N04Bcuu1nvicEfiJ6S_&f)?vxH+HtS0p&ej&4emGHRopkG$lc<**fV zy}CjkO24#R3ChopB-EIkVcslg% z$-Dn354U0K>O9#Ecl3)I%fZPez@S+)Vsd83z>bcDSzIkg{zoEh z>6E^WIbMU*zO?n}`73Q%##-E*UHVFWVjqViwZ$ErN9mOXPqz5|2WC^l=CT^O>9iTN z-Wga}?Fz9{3zzcF?!M$SrHukp+&i(tI#UX-D~{MquxMyQPMrqlZMbisN*W2{ApMKB z@P>v|V{%Bv-JY=;cJu}LI(@H!709xknOCQGVSnffP%8raoffxACSThwdF6rA!HGCL zWslTL@>okWQM9VPf?phd{P=TSY|!yO&2rbma~7E4iIH~kYet^_oClAnG2=H1`yr4b zCsZrVzb)bQTGMG;Nt1%j_k2iUnPf?Q5SOQ7fcJs}Uxmz=l4{!%toc>5y)_Dt8vef0s6QPdvhK zC3}Q<+xaKd>q<+SCVHL#ghYg>ivh%;)C4T+sf0&Wg58k6QatV^MiV5(Z~-oVmX&xQ zCXy!&2zrZ5JP5#wyTNaKpR=I_>{|b|34$yBNnBjuNz0}vv~Ee*Fa5$8I=DVCoJ_66 z9{@7keW~g~%d~hv+UWL!GqyK_sb>IEegkKItawKk!HsO7?G=91J;VOwR_UP6eNR45 zq)(k`-=WYT=u8?Z3eTIID+d{g4z>&OkO0DaBc&9;juZ&<7y{4`=QAY@`XD9w0t5t7 zTJopk_vtysmQCtQL{%;vy8&KwcRQUggKdjGBEr9C$`xPv2c6}tv+dkD;6lO8EcX&QwBK4Xx=hOX5t>|k5O&yKgh>GRCXIwyFJzrP1l^^CEWf##m!z=VcQ8=IQW`T z;A@z*q5Ww+$y7IK)sl)Ln8}M`b=@xtgP@NU6O(kh&;bHNtY*kQ2#r{#v#huh5*~&{ zhqSd{n>7Y}AY=8txZO1QL{Gt9NbdgEP~uaLPG(OLbT-QuaQ;%ep$kRv1s2DjnlfaL zd9|$Iaq=HSQ|~j@@h);$tJWp-X-?{xn?;vO4_~70BfS}|Tk~)?UEmSsHd|&Glk^81 zzogyYUta4sDdYJjn*sZXlA-9au{Js&7uO{8R)rQyI=X~BS7f~6H^3eTp9));^Q39o z7<vq}m0)Lnca*rGIL+lF7;y+K|A)>gD^A2E3le zZa@hMTJ%0F310OIylrtmO5zlFGJ=&)Qd5f}ZF6YgLeMFciN6dnlx5^cK@8-Y3g|oR zoa!8GkMJW!Gt6?NZRkRv!BZQ-EBVLi(z{DMycHB;>hSeYpDv(s+%pr`NV8kpKEY!7 z7nus|PzzVfy$6^T*+nGvHylizcsuDwdVBXoNTsa@wFfQDswyoc^^Wfb=i3mcpy)=T z$E!J6{d(K3PLRLtl0+ppg1Qre?W8J?WN!b*8K$FeVytF*WX$zCI%YD&2Y?6u3=Rydd7d|*ofl=Oy6N6M!|g?Cvu<_8 z-JAQkrr2w;wobnoD_5-KLzMgeL)hj5vvvQVpwBW<;w^NW(v2Wab4vLP-C5HK>PBHk z9*TzWIvTrC;z<)8quE!Ukf_)nLel;wtJxdtaNGMpxko)AkErfMS=04+khJWt5bIzBBcYGLI9Y62fcSRITQFo> zR{3A4aWFDE`RE$eS8?ow>;rB=^yLz3el({ioe_QWHcZ%u4FF*MPtAFqrxL%$hii5~ z_7F0P`PrZBJsQkDfIJzz?8#XPA-cIAVK}fFuc04pE%IC)H{KOo*$n$-I5GoM9*Q;< zU^@ct-=@B4JTD=-|Jch)w9RZoOXRS}W+m&|3jF`P>;Jq7^5m`78TOZtHHQ;PiosLt zc?HkWaUpjAH-LzpCvXeFyXnxDa$KA$q3Rm7peGHRb`P>8A}$XG?;)-z6EIl;_EL|6 zr+AhMuBhUNCH5ddF#qMjjfG38qc=cCUcXM(2ERZNENLq7Dr)V^6ISX}bw0aW3|}>0 zIOI5_7&;ICwcsL5On5o=pX zFO08-Jb`ph=9C=bJEde-wc+&}>lS!Em8J9_8mv#zW5Qh$0&?1G%K{4{(_{Etz#}npMppuLPZ9V{E$C*-Qiq6L{=SIQR(B zGL%wA3*O0?~?oh}ooym~H|o~PqBWRtuX^2IQ3@+1WD29)ujLqjAu zQ{ZKX02<6cl(-_mmJ2cVP_#Vz-^qA)2~Qb`HPEzU6%N~q+Q>NxNlSM&kepSe6YBh0 z+TI146CB`5J@e%MeJgT-!_mA-^J~k5FmG=|owZDC{do8JjN37vXAT*zKNWgcShf=a zuilcBJY7{lDT^}8{X3!ELr$)`TQniSw5d$ZJkHSLA$GHa#k0L@=ft{G>>aldR??L= z1S`e|ctZ|GTva4B*Il()ehx9~d{0k#0qIcCO1sd*G?CA}%ayVQ3SXMfZw!l(#0U0O z_8}ZhY3a>V8VxcwtH(E&_^4+Q+>}20vHf+#YOeI9azjoqhE|-$zIEC4F@5<2VXM~7 zdH=1uWOJ!}oY4_rHI0CLDC!ikO2TVJW~(bpk>Hvuigcz{{t}TV34$l?YSEWlXmN&QMUS_DcZ7 z0H)!Y3lZmG8mq{T=2%#85&&`vx%BlkF)e)o4rHI>39pw%AfgdjniKc0EJSbl&Pm~s zdAXi>3XBTQWcmV_+{G0?NR7>AZ*ptHF!6&}B5B*sA5T(*KSJn7lp$ISs&Xvxv_hbC ze1ea7)^_3#Nmb`1OVeW|m;J~*@mcq88`_jJ+@6@vOBIEkJ*V*T*em4pq(jT}z ziLgD}^AnA0x}rCD|9~Pm9CMVD$T1AW`CSU+QpFhD9pf2)D(R1Oxi*WgPw8e&8wCE; z%MdD_r44~})@o07?|dX{!)aOr@BUbij^ zG17pLn2dyrxWYqW@J9azMpIC=Ev=}3&niDz)pqxaC+I9Bi1d2TUhLN@p1Pw=tnUAf z-n|GSdLR8ef4d}E_&ryeBORTI2p5zSM{U%V7pc?S=hKGME3s!QrshC@K45C(fC27V zBWZq!y@T>n5iop3Q2)rqTKZH>xq~L;owiJiDa4U88msGt=j!PgL~Hnb8NpiD4nWKi zG7*+*#h?f>*~xPPb8O~`$|XdIDjXP}cQlBQJc>h&Mj1c2te_zHNQ6DC8wE6mG{3Zg zB9y$QVqUT$o&w|d?VAi06iz9vf`uRf*; zJ0!*f+NxhkPwr{e%C`&7XkMs{mg_qpc8~NarP|=eQ+rjZM+Qm^nnQ{HG}{XP02yz* z6K3l^=bx)rDlWuQovd6jPLFWMO_qfYgb#jnTx`&bi@3&@E@ggz^{fKG*hlxL;J3Nb zJzELZEaJ1UXj-K|X0iPYEK9~*>{lj7q2KDog>)?HQ4vEt>)r@zADh3foi0{Nq1H8m zxZwA7#odKaffQb|)u&m3@v?iPDs};9MYGwADN&};;P1RB3c_(jKx7oxv7^)+(^$7ZiLr_q zZd>hacf7R?;MN8XhbFOS?OyeCI%Hhb&2JzZZPuKyS^)=>05UdK@UE-LLRjbGrwb~> znu+3e><8W3#`Cm_0(w#*&25%)GRXmr1$asAlnLc7@XZFEyeL<=mVw@)p?J^_*UYbq7@afBsX`C zrz+z{4r4{KmWL9H;wh)4kBNwMI4zLMklnqYtAO0+7U`{LlwX!33p1UqrBzZ6JHoYO zZztSNjNCDLFT^K_=k=5nG4z~wku(1)O9FlqCC}kwJ^)^#RxKiln%&<82@_F#4)I%D z&}k*t6E-KJnk+|w1VdFCFQ9JzS<6V^M9Hn`EK@pOaU9O90ep&)EE?Wen>RURUAm0e(f0cpyvpBkY;0^?9A5IBG?G z3Bsn9iUx`r;W}Fv-b&1OkI0Iw4D*vYLa>Q8TXlQa8S}F8v|k5Ar(qLiN+3q3CN!aw zxAb+)dDT@=8pe((QYzrD`}R`FrL?}#l>}ToA~~v*tl{7YijUN0_YvQvPlh1g&}O?l zm+CK34A=iSoD&%JVuKP@MvjAS02bZDd-nm}l+&81$3Ps_Q>nlVItp}+-V(@so~h`S zO{Zi>QQ7sc&V+1?wDSzvE16qDsoGhFYf7zT%dXQZ3m8q-x}=wId4RBiP|in&@lb`N z1qhv?S{g_Z0A?cIQ7TpC;S5Neq7#7ki*iOArh-D&pT{Kir8es;vL*l`Xw@_`H=FhP za}Q|eu)~RK2C8x~jt2x-JH-6!SE4qW6A;~^pzwE=>O|?2yFpj+_Yi|O!4H)m5!gUp z)eMzIa$&*M!sg*;Cf50*0I*WljmJaDF(>#)8TciXb9JFIG9;)#mM_y=E;=hlP&4e# zz=jb91JweZ#EvYHW67~dUHerd6 zLT2YtA^H7m1U_gj7VA#jtHHK%OqaygB+#V%VR+OtzHJmLpX8`VXXRP$Tk1oOnPX6K zGybSrwLCwm8>`62XzIy#=_Yk-fcOzJR+M%Y1w(U2uI7b@PCggwGyDXxE5{W8I}k}A zz<8vrOFS;2&^oafW1;@=K80DdCtvrHHOXU*rJgZEIoae0yH?90hTClGL3ds=E=1r9 z?VfPEOl;f}JQ1JDm8`i*1_8l!GX7il)HH^K+F7~8@vK>rxPsy-G+}G|r?fjf<=u;% zg|+EEIL(?N*15nQLBa{!O<>_paAzvh^UC!Cv`O4~4%V||UY)6(R%%?9#(&~K6SSaf zQNligii(ot76T-+l95n4LunrD;6}|JmK98*m>1R2IMv63Y*ob$u-<`W_ZNktMX zV97@X4``sA4(A*w4e3haj?4k2`K=b64vJD~_ZB{oU2%9-$h?sGIcRj^g0jkiqDl1N zsh#HorVq#mjMK6to#dH(96}FRQR$G+eOHjK)omE6zSpD6 zvl4xrcFsMZ`XKAF?B6_x#neZt*y^owG&_8z52dUR$J=wm3q zhi@m&@XUqWbljaco6BucIhI@Ck+(hQZWg37(-33f_VfhJ3oe8ZT52#Bb~P)zAqkPW z`}v3P32=pOg3gs89VU++&xATR5{)3AX6WfJ!B6W}P?5X=t%j8Kv}HF_%jW(@aZf;> zi@-si0gB|7Y_9uM+DwKF9Yc%YiA42)cR#}x^esoroa!`FglA=d4=~`WkdrFr`GOjT zqJ`tLNLm9qQBo-bDiuEb4HzQ9>{1hOQ;-DvbcPBVeR?53?0E;(HYq<@3N~EFeY~IE zgqN10v6biDE;vMGq#lS!8(y|6Png;E8+L`xQh77X)lZDg^C|V>hyGd$$I4cGQvey& zgzaz|9DFOgkQNGbIM`lpAyM`>s0+){RltsVaw#=tE%|y8=ys5jf{dvQslfmA4IT*4nQi#g{&D6|n9GYAXNu1xQ`$hc-WA)R1dVXb|^UzPIr zf^)c4N7GWeQU~Ib4iBw>JX}}asH?Xbnm)&Dq8PP78J^XXA0z7-5kHMGXx&~X%Tv~2 zKX4kYbuu|BGeY1&5}iJ)TD{3;uHw^VS&7$UdiC);=g1K62TDZLgaBW{3nZ;`s>!7L=p)3NK6*g28WQ~(M|h@p;W zv$4)UX#f-wQ;GDA$K}#upYr=|zDIe$QKKdZen9t5ujFZL7^=#59<2YN-mNG4zOf_X-2T?zCx0K)@dvPjkO z!c;1~0pEm?A=IIe)Rszz(Ak)Yzwmh=%VEArJs1HgRou<8kBMeoHz`{Km>M9uT1$fz z6d0-Q5dP^H25&4XbjOD^+35vL0mOPHS)Ve;|6jpl)W!l3tNndJl{5@UyGtHmPzSd# zn|mC!o}R-X)QEG)5fShC0u1n!r5GzF9VnB{Tdv9!;IUMT;DDbh{o}si!HQ`el3sIc zm%(P8+bAK@CihIkXkqq&bQ}FBD#c%*ov;#t!M2#+360WD76kCYU|rB##0hJ1DpGr)(&Kw1^K{AN@3F}?rPyZgWCOlN61;W2@j&s|JywbF z{o{BXIvl-B-3$;xWhna2#woXahIxblM}L4O+mcH+m8Ma-#Il5$Rys+wgv(g6P>xA; zOs!f9r2uSib$u2U+i_zm#PlmjfO!!;q`~Z5ENXMmvvlk;R)PzTj8>VAcjE1{*F< zd6=~a5GlwW9l4aJP=FaYY@RHb)M7wU*Hj+zh5ZFVn^a=5kbD3Fncs*)B=+AR8-Wru zDaL{lv{Tebdfi-94rEJ{o1s7i7;muhF`34f&L}|IT_A)L^p!pmK(A0x8B7jzC}WrM zHh>g|i=lM{dsT_z!2z6)4BvUxAno>w&lZ%DPWNlzTWzd-Qp)rCiBCJzdIwdv2M&6BOE1wtC|tc zY!uK5&|8ookZ2WSfA ziZ=70az!?$A~>yKvsiK>hohCD8V0&Sp4b47L%GvQw^|Vkiz!C%IXe>%^TDwTs`k@T znniH}Mp~(tGxAwq3Wa62@b0#aS%$Uo9)D_FfHjQZG~~xfm9mIGrRJngRQYj(b2h&+ z@!g4!wK}Cfp)#DX{sfT&d?__ZIQT{cXG{^HRennrX7IuOq*L*%#(nf==GT}rc<_`f z#iA&Y^0}hIQ7QN27sYKA)k<;GlwLB9XHy^R>O^suCBH%Kg$%)rKGRVQ6J>4a>}<5a z!hw8Jg`GnRnFSs_HKI5sGi~6r;Rvpkt>|UhR@$N(Q0j)%n?4OtNy7HDv4!UU%DaX3 zCFG@m)^S;{X~?21)M(J6<;2bR0Ii~i^fxb)Np&jn`oM@nnu4Ubi1`H<+0T$XZ*Q;z z?)!%jMfGoDBzRXq3`jmp3eU(gkMLW+b;1Crme5=qfeoAR3kwL(M?Q=`W4C1*!$A+S&4F>mDr9`aEZMyhxT;LLu3FXNtjK{}C=RmoAqrqH zL?H#P)j=)Y8JRIik0#-Tsw!nOnbCs?cp)UHfO6l}o4z+^e&Py*La?M*rfXyt%i^Tw z3qna2^%T^%mk0y47?KEsB9nnJJWScW60v$cmq^i^k*dA>WM8?0nMYuAP3rLt196yoo3s4iX&PjpKDb6hhRWy?hSP4)MA8(FG`bvj+6byg(~5lZApiTk<`8nEmXHp z47K+qIptI;*2F$zVE+hwE)obJ|CzEsk@{Yqkw{*I(r;3+Hx!E9pmJ0;tLoD9!- z0|;GlVnl-FuQfvmq@pvhv232N$$e!e7eL@xRBVTRL`t+-okIh0_nrJETnRz|dy>~- zTWG?{YTFJ6?;uTm!Tz4M$-|ojmaw}@N{*o~p-MbKLx76GL!Jby(YTURy@!fKLO`+q z{y#btwOuV|Tk;=S-^F;Z)Nj4zkc)^tCvp2g>(d6s5>oaa$G;$gV`7J?o>Q8&eVU6x z*m`%zA-)pHaCa2!1LLFcOLf*SAh;p%b}LCAfuP$To6f+C$>jk1jAe%!4G^Er}(s5B*2(Vw&ft z@TRspe@0wf;d%K>Q6VHOVL`9t+IhF|=a;o9T@EM0sZJF9;f`wt6zT`CXM8XafwRTd zFtvQ1>=F>{hk0Z5m4CFKHu$+fIvylW{c@nh9EK#{X@6ytZ>H_cS(vp zV-O;nQb?Z<945p1o|pih*KKPc@act}qo7+Lp;z^FP)u)&#TA6-=i&v9p@p0BiS7CY?XfY@Px&qO=Tb_FYj4R=bY^v^c2EIi~652llfb8n72Q zZBR2&2N03WEd^C6>pc5Rfr@xA!5r85)G|q&Vm#^r$;{YoNj+Qb0Tda@k+S#~2@?u}+_Aw;P9GYzqSq^AYe$5!HxC88R21Q-^c z4C)968PsP9N7X*0g(J(1Aiaj}15$#A((bKxJ_RUmurl$yA%B`M2Z}n5H;y+n5vI$S zrPwa$%U+l)co#N4#BH=o2O zUJCT=$2#)__-)eEk42#BfQ^n;4~1jU#!-iLLhw&iVBg9bPOXD(bMm&Qt*)R%jnPU* z?4$QVIjA-vo_8fK#H8NBzRHpu8SJPUqSf`(?Y0FBW*Bveq@WiAQDHn1Nb=1miWHKF zH=HZ3W~^%w5>Mt*n?@*fM@jDzcLwGMW8S)=&l?JdZHLiVoB2F`Up)&r&t-|4OFtZg}nF{^*ITUVJa zyMgTbgtp&&!Qcm;_SI0L^`dH{p+L(vqC3?c>^4uh+n{HInl~V(d#pqIIFrBYJ9~u4 z(;AUB2KYWQEVE8)Ui9hz77gPnbf*yI?zBl1+FG%om|-~uMpm*w4k>?&`rAm*=5SMK zHJ~*ltJ1&?T|muPcL3dZg3Pz0fi*-pI}wmbtyu>)=%~3nKUaVpD1e6G9R&dO3gM?X zxN*eLkTBs;G>2r*NyRllTMQ_jO>&322QsGn5+pzSXWKbJAemqDSfA38kWAgtPXm>* z(*O&TgH}79Kv)Z37P-Nu;cOuyu`%x(>(@vPus!z3-{UniefZUu2D<&SwqP5$9&>?l zeWu8`+>Uh^#){Qroy`UEIiK^w2I5lNGV62?QB#i_z@Dm-`XS;x2z^+`_Dh1K_q^_t zTLR}r+GYnDjbHlCAaw@77`VGp@WJbINv;1pDB%eB^?Clds94N$g3mm;)gZ8>h8py` z_Z(;d`cF*LumM((tcm|pjZh8h1iLkts=MteSffftgroLUMsGuF5Oz*3)=v|YDjuAp zy?w2-S!ab_PW42Dj*#9`4zzlNg!efwWG`w-awH^4L&x+_MV_$~D4H(<0Mxg!Cy=p+ zeO{$2;Feo3XB{%T0u}iJFIYU5Ix5~cO=4N8$QF3;%*SMLaCSZ7cOcUcKuz&qH=WiB z%@m{x5@~3VbP+TWNOI;Rak4(Mbc&%$4*Tsu^WCD-dfVN!x0U#-%HVv48^U%|&H3yl-3Md#3vogG> zt94u%*Lj0Me+0e`s^N~@G`tjpq8Jq^g^rH|+U7z=cj&t z#4UVmKDGi1io_j{QKqBRXw7Pk&R+V^9A)ck;7LtOgI2CDvaYk*3G5tQr{kOfkp#g1 zV%wohvwyUf42acFeUK;u1cK+)>bHk($H>|Ndu(o-Z_OerU9rSe?C-m4(w6OZ(dDTWX;KHl?LnN3~Vswko9 zT-wIKVlL}oQv1vUu2q&Zlkx8?cc7NiZ*19f5>349cmeg`?>fLjWWR&(j4`aNW{@U!R! zB3E0=D4<|BzgIKd(5@OwR#apdy>et98$Y;2{JW12<29ikf4>=@~Sn0y8QX}h1l<+4& zZ&xr#b@cBWFWal&;)nv!e1TjOTB4rnIdEotf!E&NB->2R576Jbm-S;par?Eb;b)&- zl1~68@-*N!B+x}K1pRJS;0a)ggIfzpw#*${`_WU*A`N`8Q+AsH;d^Nm@T@ zy#gI4?WVm@la`dm2Eqb5NBWYePZc2c)N)$PP#?WtO33-7?pEdfr79H3CF|)qBhgc{ zX~1{vX`d`k&8cn$&Fved)=`89CX!ny9@Ffb?Mb15;HGVsB-z0J%W18BAnnn9u4dS$d;&n8!i*fjAnz>@u?Iij%14s8o-*4UK09zk7RZjlz;O9H8|uIA}9!} z3I9|5GaPN5#2M5usGFd0XgqW1dov;1eXW^=4lIYl7QqQ+IQ6R47nz@fe+7)zFB648 z+`jFZh!oJU69FaWV|zfg1JxCP(nvD~eFkZ$f#gl%p>7856flrK#L3SAV@cNg$U>c? zdUHRcCH8Bcg5Q3E=O2puY4Ozp|UqtTpJUcI!vlw@J%4 z4TyAaO%nFS8RgnQ6S?`b1+?pdz8sCFm$K?+G3Eg713%bMw(R!TOU{?17GzwBIR5+J` z19_NE{#dDt0vHFCZ21D;iY1WU3Ia;%@zo+vUI?_HVZf2-J>^RTo$XIC?`Nkdw-y1i zL7UbD{Z~x>aa1yMy0>$*>dU^hqLMm!ENaao*P4^|eFf(M75kNC{oP3za|F=k+(#_v z)`g;vLb}Y^9eow+6M#j+ssg3df3#D9dohdAILu0n(?;m-z0|$V@sO(jN$RknJ38wj z0p5@5k0{r51B>!O{37YlK)Mffj6<>5t!zJSy`ENk6Iz#rdS1mX(R-5Iy8p^ za{y>CXeeZmgCCleqDxnT zL1XhU0hSi(hc`}*wGEaSiBZE&Lm;^9x*r7aSrcd3fh2%$VU{%_TB&1yopEJ}$rxD8 z68Jc8@=Eof{+_gECa!E-ABoBXK#|2N(fa+@fLW3^ovF^2fztV5Hph6133BXvQ z9#((>%Cd$el5s?STI}h=0C7S8SFYfDBHW6}0PK){li4RKGwUBY+PWQf0iB)Mz(kT- zcr3>Y)hFQhlX(?tfT}1`bAm_--@St(v>(gZrwU#b3FDa~KfkG98u zDP2%&Mj7y=@>=NZ`*#BSr`*vPy#;9nKp*pJodVY^C`xabVc2x%l*cH{e02U3U3SLE z6_TL9fg>yWt=~xIc|;4mpV$xC1%sD{=CP?iOm%c*D1{;^r8meb3aeObt0^ehFjy(5 zMHSv5Pl-WNZZw{m;IYay2fE^JOAnqco!r@mxVaRTpRnnH*x1}Zqoj1KzPi-lnOiOf z4WK++N!MZq!~~ zwXsg4rSwe>x`1{z3ZB9&u5dW`0a*#1#^ekK#0jCw2zC*5p4_Z;Ub|z;!`2`~3Sg+6 z3ycoR%L*`I<~Rj@gZ0oW@>{T4-Pqw^P6l6459|@x_9R<1fs3JxQH=(Tz{ZM1Yt+a5 zUM=dYEH@I)wtM7M6Mu2{HXu}ojQJyGNbilq-}z>LiTd})=EtEU{8pU#%7UD z(BoIrQQ~BPWtAbRw^3WAwaOWTp_#PaJlRZ1+;aLCCe0RU)O7HHC^N@nq6DHx_OFSe zo&GN#CZKLr;+*tG#S$17WL;=B92_&K{D^g`owC%yuy0G~jcAInq!MJzKs1LjO^7iB z+b7~Mya@SKAUaM^zVBIKb7zhr9>R|&X#uLoqmdM(ouT)>e5!V)`X>`)h$7ux$NX`KqB%tYS4=C-23OYT}an z#Ww5Gh?NBYkmJh*I$OFWj)IT1rd2qIFHo`QEV^*Ip0I>tF>j!Z1QJ%;W+rwHqZ$1o zkLf)VRFxk%7yewG*c51w)ns?7u>@ze7u5x5f+;*;mr=72Gxu$1z~Nkqk}18hwya3Q zPrBK@s2m7bj6DfcjSzcUuhi*Jn|Bc%LMJS*_{J&8ZicKFl?)(r#b|q>b@89+GoXwK$o1^=ljJrcsyP|0|1$s7YrET^lmS&1M&FpJ0I)m{UFVfCQ z%<7twU=T#ouC!CmIkq>4*qP?BceyfpHm$?MUhP6o6zNQX(FIVzQ4g#tk~Ej-grC!N zA1HL|9Skf*Z?hb;H0)pv2Cd-pkkw@w|G+cmddw^|F36PZa>F`PfqHsJo5Xo&-kFqj z(-p_O*{z%8*_Kr3TtgUco03&oY_-K3J_otqaB@rc_;iEYvF!u@6>U#5c6dMB4XP$Y zu~Zdm{BF141AiyVrjXpO!Zn{3+VHd?z@0l=6`EHX*-}H#Ekf#ASYw!p`0JCC)Z1Cd|5}z^boKy8$?>G zH4K#(hI8yAX!ack_C5(44xu4;s2br^xk4?2%z9C9Me`NEOO&XN{k~speX_p6J~BLO z(fpnfE-)(epCOP7$`a~hMz~y_fd)%XN3&|*Smly;`x`j;DHi@a#U*d!MwicBDqZq^ z>v8#dq}9bGPvbIj(a2xMxRj6V9`Va)m+TqkhtwlJpX73IBl?UlT&y$xdH)wP^VqR2 zUM}%79q<2hrsMrCAuGynyyKEP)n(Vl@|9n@EE@0Pwuzi=nMV#TeZCQW#x$3aKRBKw z=Y$6R;F33I<_KSxv>)=GZE*2-8TuiQ6YP@X^4;dV+u<%>xop|=&o>`%ejIwIOU%SE?2Z+C>t zT$jnQd2>QsXd@r~`;Xk%yqKkM3|G1HkMUdn_0BK15U1a zR*z44D}2>|7qJ$v*iFw)6tBKNV@X8KFOM4Auen6+a^DcO?@r94`LXpb`r9c;6 z=fB-`>}1u80A)Q9jbjx`0gm+~vDIl?dQSQ&D|`HtdX9Xz+}j$PP@HqkTpc)bmFZqG z@5^P|4sdt=@M3*xL76$@4ts6OrS73jx%BOWmy#YY{oGB?>-^s>_3oFZSr*sHL!Wr4 z*Irt_vr_W(IAIQ!P0r(l@COtg{1c2Fw(k@5z0*z@*stdNI6iM1f~mL)ydcX@tdY1$RfX!HKO__f-v(nC{vRHZe-X;?vZFZ0d=Q}C_8 zT?@8dlANcOJ@~AY(k>A62HZ*JVb^yhb#)1oyY}{U2{Ts^@!w}*=}jreBlRcu-!vV$ z#cS<#Yugi)oqB$t4r5fD3(&09@2?!VQFQ0~#|c~R_6+!vdpp}If5BMa;zw-^ne99K?``E0^QXIo4R;=FFn-V5`E~od>`c)J zedW4&quwtcY5ucwf#m>q!EWK!kYf{eS@V~S^s~QY{Mo**t*Iz>KooRL5jjxz;JCQ` zz5W{J5zB6Fb_L5f)`p#1?U9;lti5u}LYwtsgVty{#Hn|!z8+iqc)@nzBI)g&4T@7! z_|n#xdN)d~et*98Bh{4(eR$9M)(bHYBy%?C4BCZDXSxy(K70J&470d-^iD%eKAzGT z_G)25|AZOBY_m&>J?as+VlcRdl9uSzwcPYx;E})+iW=?%>$^KKdcIhD##vVHXQSMm8!qAVON0qe&T-yWPa+y zcajZXmOtys4mN!yoLlFYT7A`K zKk3E>LuZS^u+QtN+7pha-COmAh`Qi}eiUI{QR6z+Z2~Ll{Swfn?6{{bwynQWcImLuRWiXLe<@#_Wg?OURYF}i0J zfeHU<44b8Iy;^>)dRv9}uJTuJ9@{WD@|HWx7&iTe>|5c!s(@erWc^I(=Ik^w=GR5E zf5{zvi!T3L5m+d?`h44zgQ97=Tl@3N2A*p>&aMlaM13{u7>zcoZX9;2%6{4X{FExr zvEWz7yN}*l*YrjCP>+7p2i)9(eEE2NY)tPjl{1AUgVlKXi~q;lo4`Z$xBvfe`H7-N{>cbz`>ce(G! z=l<^h|Kri)oHOSEy6v44<w7We#O#&ohXVyI7r#s=WcVZ8L>H2Hi-iU~Pdj7K({p3U`in%y zFhZ5W`Am%QHH?VZ{;bK_O8AoUh6RJPdeX$0ir!|l5vJAQ^-qJ#t+lNqJ~~t#wjv26 zb&4!fc(ux9#fa{eN9wyJQK}o*>tbf7!zSVo@W#y+n{Q87qg?(#3~Z{;92$>$LT4Xf z!NpS&=#w6VJ+63UJ>$hYT@7R|<%KAsG$(ec+pl3?@QItq%b&u@nqA3~l<(jCXbG3) z^;Q|QbFh-)IRiT~R-p*~Qj+X&*wZ{SL3@ zIeaFO$@=p|8~JCk!#hUxssVedd!p$3w#(Jhi2{o6xQv}2q`oV3n;oTQx83-TaL6rQ zEA>8IP~Ez5`YGjMmFL{)vl&zFAFxunx}QZ9-Z&PQCPUkrt(t1@nLGG;6f;)qBTk+e zB@~~D(IIADw8fJ6VtJY$wD?`CT3M3J5WLsRXBm@2B0s6{>1Pm^(88(=SFh!YJWdFj zI@)=R&&$g^Aa%@xE7L>TeJ0}vl7=(|q!*|3E{2U!n150m2s#RxhcMbx@cxU`v<8xx zO|?t;>$JU-{9VNwPHY1#q^7X9Bb5Ara=m00XT48t!hS;m{t|=NPh{{kZAl(mJFI2f z<|$HDl4wNT%i-wMhn$-OD@u)exOuvx;lEXMx$$Z_rJpND4G7e+3w4?7mRJzK^-BC6PYRkXw& z<>}H|yjURmVON;-T*UczZyY7k#?8men%_O7BvcfgQ<>LsD5rTuR;TDV?vc{z;3@hM zHi@A`JrRxw<-emFSQfyWl)`&Pxds6T1e+nx^ z=9`MtAJF4gQ7%McZ2Ry%4 z?Ro=Q6(e|5cu2fII7exj6DvbjR;{c3ye+%@MtMZmQ;0TVYMN7#qX>^q(`zhMPx*B#j2Tgp=$s|*CM4b_&?BCs}xMxcxJkJ%RsW0}2S&-EZn=FyQb~&vS|ErOL-*;=8P(4VkGexQ%Hw zY+F7;baDT;6h=`gN2X^rRkpD@SycvJ#WzTWkNsGWG7I8*<*qXLgAb zt7|Uf9cWm6y?d#h=8irGJ6r~x$r?#KGIUPyGkWe+qj3yFx88>Hn9`y~P}u&MG{gZ? zh_$}WANb1mm8R{lTw_s2#uk(<2X#MfBU;)*2H|{u1D+#!mY+ciq2F&YxvD%qXjYv! zeX!7Xs9{zxsqMyB!P2i>JaOVbT9TskR>|>~M+{BuTRktoxz07tk~ep1wQssacR&Jn za*<*9=5z*OfD1&QmMXaD{%j~L)-gbJGl_De-cPUIZS1_*r^T-OZG_O?+_AK>eBxI`=;`Zv;Jut44{ho5{_i}q=lkLoCA1QWI|u~-%`LC2-ai@09Q53Iz?)f49Dz*zM(i zE@qonYQf|i5)4>@x%AcQ>8A|YCnq5}NZB8SkdIo@$1L!e^%t4;la9mJuTJ4s_U~yR zCl-$U>bmrqIx^XX;c+5p;++!(`o@Km@E1NM>R#2JO5V|}7^a`Wsr4isSSm>a|l*tF7BDT`j5-oMCF-BZ4{b#vyf zi?!FfSk{`HX*TS?B(zyP$pqU$tFZ#)CS__d;5b&=b6dc$Nj1-?`qhnc_b;QKfnlYj zLvIRji5|x;C5|-o7v$QgkUyL)&RT!yc~JXJJPs0Do{8!dQ@wj@-*_6Lmqc(sR_c{E zDC3XD$Qb9x^SDeTQ>CbA6BXtky+#CeFoB=d7M|2c{y0t^RpG zf`36W-fEdLwP-#%C+X@wx#t}%R(FUhg1fvonyfFjbUVYvq{`boKi%e<4#y3=zd6+~ z|Ms7|4#>okszwlGM;qk{jnt1>)6K-Eo?7P^XeDW1-=)VBr-z-FZFxMkR-lqZT$9WE zsgmOvqEl>--!j@Atm`lvQ+-`zRZKfAbLOFQaPSXtWRtUOG?5f7g13A;5NT5&@O*Ji zfSTB?fPJh1TPi04FE&6O=~lRR-%w!j1`b*UZ&u(pvE-mRVget(KJI z^?8JG7U{s9!oE2QH>5W-g)!&bsALYMUc}2@*JPj=oBbh5xss&hx_eIHjbV~uFg9sU z;k#1HZtoLrroXFQWJLK%?7d>$oXE=opqi5_i(AJLdeEZ zg{BDYiqivQbM~$qUGB<`LoowOxo$Nh!w#3FF87wEJ=;nkd*dUES<+tJ`Sg9s>G6i` zT%W19Sp)&4PStb{58`!Ve%`xi`z%p|i*YhKaAc%{f6I(XXYy z%0)=SakYd!!ZK6xGfz$mdila+|Gr39MmR_sLA`#-s+NA^Fxg%7nurxn7tLz2e-%G| zNMt8`(zYmsJCAsS_;5eWb8e)fszL<@W+K_a{Y)2!>x%wkm{>3{KXD-$ZFAY>)o=9r z%6*oJv}#Qg+7GO1APmbrg(@tQnPSh0l&#*c7xy98woUPormne2iK|zK;#1Q`EuH#X zs7U$@50`nH#PGUh)7-T)Kj-nb1KT>@99ka6%F1wMZgj#U+ASl@47s?{c#> zX?Cif%9W^5#k+MNE?k0|vG^8P3b;SrN*d*99$^&kz@^;XSh(dQS{ty#Xm~kEdvwGf>RdD$pScW*WK8y`b&(2nt{28 zxda<&BCgW~AG-8$c1_jY>w&Q7AANb|V#o9Gixd75bpZ&8B3Z=aw;NvhuUA;X$73Gg z5oDY%XtvxIS2Q#2vOtl*p@Z|Y0)2VE0@owG=E|0|Y-$y|_>uLIa<6IIG0Up36YLWk z-+#gy&J)_0&=_`MXP2~V-yC03xA*sUT7RPNo65Xtm-R2cA+*nwZ%Rs3-O5qQRmwh< zz7`4t;_MKhxaxH=wkCSzG%j=;LpN(a{fQ^~XR-P0@N!VSiWuQp`h0ehTg~^8ADJin z(x$e==G(+K8)-!+*k221`WO&c@cqY^``ArQ6tg(&<|aS6{`j?vrqn&;ecwg&KEk@n z2Z?T;rk^G=i+*twZ|WFI_!qZ?i=m4YhicqYqzLjg_>f zYps=1v*k!@+ta$TCpOMfdSz1*j(jqoVwAdEU}1Ar=ZtBN|Ep4}h~sPVKo)BME5CsR zq`OxJpF}aEExdVYWQDVJ^-03t5_iyH^zz#Mi8dl0oR4+=b(uhBd1>^A;G!Y2mfW+4 zv8XX-Xrqkmt;j;z;#aZWJ5Hsu&0f3Q1!CCxJ1z%%}dC~!h?4{M%B`QdKtrFCqyyzO+y&B^qO zvG<9-g*`0O?kd-G7?XXTTw1u>B|X$G=trHp7#oKacwN{-j?ZSXpj&yz!4nyI?4=Pr z5SUN6(89^AGqOrHSYU2ApY~-|^6Y2DCgD2lzKIT1= zy#7t^u~LHcT3*n+#x6>1GF{86d7-Xw<+R^7B|>fH$)8RkN-Ntw1~`p2t;Q?`^K)yZ zCSoIl-TmgP>@z>oIb$d>?=@mg<7leUk;e3^8);2^)GXW8P?*-Ik+Hy=Pd>8!-0at= z^4dBp{q*!CG$G}d1Kra039;*$#3RBPKLW?aFX^r;oiDasR0(q3y{6l`O@b6~rE)r% zC-veaA937GN#_~qLAURy4EB#D)|r=NR?4}lhlYA*eXpT#s8@&dd)toe zurm=pVpaI??!`mC1AN8f9)sjcGt+fn8oR@ zxEcBWO`EW_h+(e~AFgZ-3xJ z>Z#~O%g}U&%D4OOq24OdcT{Z>`znSK`$Q_=`e`MoV7HX`saHZNV8kUp>c;|w$<2xNAXT+@ zAQZ1Z!AnbqXyMZ>_kP=nC>VK__;upq`cemsUUQpHoox7SQ#e&Jm}M2VC6D|vZk-E0 zJcke6-w!F{3cBoSrN%FWZ3#<9&#&}9Xk2}2JX7x{w|(kCgZ&%sNViFk3-i8W+qKWb z^&Yu!j|<3rkDXXjucq~I(blPwhI4PYMXps^zv1qkzbW>1==-7D^##984w_Vv|5n6; zj>9#v?S!-7;sq4V1JGeT_{3EV<$pr%t#12UP+t78&#c38H`JZPk_L=IH#TF|>d)gP zNy(D4ig-y^QZegN1+uawuwXP+Ulglv)y$S?%ZtmW1=ZZbOV0mPVYQCz+ILm|7v#VS9xTi_Iz@P5k_c zf=uElX9+%DkT@7AJKN?t7>nsaHDc47hXt8z*0uy9-G3H#o^}n@! z`7CtUX+rQw_o(0z-?OXvYQ?m(pO9GZm$b9Bp9WNN28Qz3&DPF`*PCxkqlIbWSMr0J zn$5Rq*AyQH!j9!$rXsEoj#B5u7A&@uC&I@9_*gZaCr{Tq`M&J}HGd}_$%j+f4W||8 zr}IS*6!)1YQr~E?EjDDWZ49Zm0pjvhY)S7Rz_L#RIu5B2`Ks)90mwz%(T>68c zuCIL-S(E*knT9J^K6x*G!{<2Oet-%0knY=~&M;dLATa1{ZZ~kG9zC*}#`dUxb$wL; zgm;z8v!UvYqPjv=olqssOW}7r0up3~)>?;j`t%qk!+xgj4$s)L_|3T^O zn(Pjnnbb{Q->V`8D#@uEy;f?t6A_&rG`mMfWY08YqBeAfAlmN5%4|Lv9aFMC9$!KUhp|> z+46qEi>vrVhemY1Nt@kuDk=(}+i{WHC^*|6MT)&4eU)5vP?06ldMCzThSyvBo-7m4^{HqcYm`*zhiG>fdr@<9BehC5E-G@72Z6$mSjKVwDE!L~R zqT6a%HW5CD3A*{?fx-N2YFd1M)m9U;=sZ>J_S41GS}bMchMldZ#!MU6gyXalOYHY* zH_*kBVo}jGW!P$;U2Cqr^9Byi!@+JEJ%avK_Kg;teK>Fq&LnC}G}DovXJhi06Q%J< zIO85mZgH(?r93xU$Z`O2FyX50yF|=a)T`x;l8ZNZB7|4|E>U{KH8y6^$X5HphVi=WmnJZL(;D4wRoR)d6=Nn}9b%lkl|?e=n`xTBy!@g>gC;}X zoNaTl%ojFX{&3p8CPg?XfP*mfz-(FRMS0YmUB?@f0lvVFo#NqHQ%l-B3JN1(DR&Dk zXuM-bEBVG0`dJsy@+xd&L@s_nH0`iAVqC00Xi60c#r`_0+`@4Xx<00c7M+v)!o$vS|gxy~Tq-M8cB5b#wnT*6; zYN)ErGvM=z#3jw;UuftXrd_2djW}bl7c&({ocYSdhMiUCc)cRMr(uIbk8l&{=8?~B z;kF1|BF@+W9KSMzjn!~_5~e(SO}!TkV-;c!<-(=+&%NKaLNRv>4>k1d6hDGso1x6; zR(Et45C$9jNp+JJ6mSSAjjA|G@Ct{G2fArqH52xV)L0%!#FT5`{pS+Ed%WnG9T7mE zTo{%=0CjrLtx%-!yP$&#>j%+;F@@RfQ>Xb@9(fCOinBbz`Tn89y=$ReihCC(eRvKD zP1wo3t8q%Y=uBmG+#^YhWbG$2Q)^?<eKsUwUCacUdE@;d|f=MiOoj z+_?^-$H&Bm54-95m`icz#ACi9=b)q>IxoxXq1U>hP*hKGAZ)i|OZi#&wZk{~hYttY zZ)`=knJTc2xBf~`#7It9d4z8^w)TPzVO_T=Yxl@uHHpNL++-*xY%9wn=wI5o;jiUQ zGS@SP-!QLMg`1v88?N9tvc4L@VoESg+tVP!YA83O?{`N|+r zf`y*DCV#RJ;XLMnh)tsma~>wojW=1S^5Vclu+X2r9d61A3zB(JrmZva6f@;vegSpp z+zp$lM)C~ifu?PQY3p3}PBUE$a&K}wMD$6{`R(o4c=NR3=&*z&4Cz4yH*9*Z<#8$O z9vKx-chY(2Ei9J_!&eT;#BI}SQ!~?DVAY#MUC6E9c1ZIdmZfeENl024dYtDWJdB>W zCLwJDj%P<9j`%j~el7H*Vq-Zvy+>2;&h$5rze|Acso}qh%Vm16c>2L*lYR@7TDpA9 z35qKU?x9a&+r@@QEwJbq*PymG4j{$gjS7ok5Ov(! z^F!rZw4X0xer>oqqkpqDK;zX~$VOS!^ln2c22O9oGs?kf`v9X)aN2D8wnq6D>lR8( z5(HXR>4jQWm(dB^Z)Tc~zn!lv(olIoU7HyXS2Z6OQ#RhP%#c2o_QjrEVRswfzPssP zT-X&9;Ap}s57D^Y(Bj?@UNK6ktJE-x!kMo>ZjFQ!Q)RLDd@wOWnE2%iK9x2;Y4Jz+ z{R<>f)nUH%+l|zV4R=Tqtf)Wfq7I)+QZhuUwe01oySjqEnb{U7oG+Ht55Uqh}QLt}^d7cwLD5q9T&q@je|Hi(7VYkjJNYVt=2t$S%`1iYm6ipSFUSyH%+L z7QYYn%oIFBuN0m9DQDp16C-rFX|&k%_d!8hIk+c0C*LxGn*6fL^M~A3O7zqC&O`z$@@s>^rV(Rz`o-UW9gHlJ z%xA*51L=p~l1IM;_6vUI-J4OBoQi?9jS% zZxaI}Q^+pY@c}&ID|wu~+(~EeuHZ{$;!Ka~Pg?P?D-1FhvIHl%rgsG!D&me!Nl6~C z&LzjiF&DM_${*)QcGB6O6Kq;0jxcxBAGPA)5FTVK3=58O&FHE(l+`er;*;E$mP-zg z+w!H|ch^VuJSQEsYrz&};#*$V8(YP)YYs9M8U?4h!g`S59*tvDs*>uWx#W~MmY8;5 z<&PX;PC5rigAL2XSxEKzR5HWr)}ue=oV)8btc{#ufBW_QB?YcaPJM+5fxF9Q&o|dyxAIaV zUJ)p)NFc(&OqI=e%AX2 zE{K&2XZ=&bLiNC*b_l+i^%t~_!>+q1&;A~oMwsieQ(tsh$eyz9!l=+M;QfQX9C#ne zl7?W|+9CGlBR3#+2mUe$Mosu91oN2j4g_-|vn!mTg`1=%#s3rOZz?G4gNsg^L@)EGn5ET0)COv190WgpMWRn z@3xX)Y{`->wE(odOO{2O9vsY^V=7%hOGO2ghXsF7?r9ieqr^DBx~PB)~P<-+_10V8j~u z7(+8FTXs1~mO_=___%c76+VJ{;{I#76Pd1RlNw4ZIO=Y!^?BeK_i#tpVJVwq6C?hxrxY+F>bx z+Z^V!(qmSUI#ehTX2}~3?r(*Idm`5n6yLrR#aSNSpmSD+g#)g8m=W)MD+%YArs|Qc)vtNV$YHV zm}7p)f%$MpESNWBOF(Q7%=L0S${*dsg1E^@1;8*e*|{nX;JGGn{Y7z{5bMt2za`$K;~9iG%GLlr*T$pXH8Z!qAd zDX296r^^4Q@FV|o7=g3W=vs?Ns~&mF5FyQE6s=0rT)8M>*P#xh+x(wbIm?I+Z2ZrK z--L5@3zV0#zq1Tv{D4Eo4>)A}aBqN&AMOE=@p~zu8Gl70n(_CU{ATkoS1n7}3qJ>Wif|7~!8hWRbZbEE>F5PTBcH`k-d&$cV*jW?nM z4PNE~1ix$Z%UsB}**MrJ(M)PN4X9Srli92fQroL7C0=Lp5mfBW9-!IAXRJCa{U4 z5bB;I3gx#QgO#Ct&TJ6632teq_|iQ-D8#o8O@6Abz&$sye{TX9NeIE{%vIrpk<-D$ z45M~}XEWfOyufYFf^R(}>bJ*siPT*A1L+kcEnmaeGXcR?W2=sC)J@6yIhA z_+#cmz~R@`0l$8j1M=;@rwrY%r$(GVIKaqH_^ z*=`DxQUN3BxG*T=^v9DRa6+SiyNSA?ID_U51VlY#8hA7PgHTAGloIg!;zEJH_z}%& zMX#Z}xEk>9HVK1!>yRbD_vjx2JXvZt;7W1#0Y7&fb-yDA#l_B`ID^8C01-mSDB#Ze zYJitZDFCh&hvv+ekE7njkzLO`)L*mkcR;?qi67>g59F1FB~ii2 z;|0NK-WLvnL)2^l!67kTMRB&TfL8|HfI@5x&jRiui3(0RF9=SvRyYU_QRfJXGwcMM z$~pwNe~>HSx`r35ybvW@NlxI4d7l8U&WgI%3PJhJ1}M)~3p|ab7Aj5)dRm4Rz#5{% z8xB|BptSjt7LdD?eAt7W2tW0XrDUfT2 zP64$Nm;xpjdti{}ir$7XeMbBsjOqMMA}|uphL8bQtVO3lq8&N~6iZ+Vn4G%+Qy_Q8 zOB5G7kKznUfPV`i0)Dd=odR#{&?#`J1g3z=gTPQZ}vV336&J;6Ex?Q}N?eLy`_kH8#Ix_kwl0!4e#!J{q&Qy^C>3gtH+ zLwUA(;Fp5zfcLFG1$e*}R=}(Gq9aF72z9T=3Aox}2!=Cc9XMuvJu8<@!C9#INVTKl zbLtnw?jW=Tv8##tcKBKdG3Wpug@nuke@tH;{AOpNEw9>+iqC~#(DFG4?mmO32kpD4 zcZNd{%wyIW2xSrK zuKQCqz~8k)?9JLYjzIf6=rCrn_moA)4)&K1IbR_Y^8VYJZ^a zHNT-a<4qK2`wsZapqpj7jOPu}Z0FWfwB_HNLdECMAJ8-oI%iRwL9rbk9$1JV3O|^L zQ1RRMUqei94TET0k@Bf1RV1byc3y5QJnuZ z;E3jyAK*Ui{!8G$9NrGRqtw2_;`{D#4}kaih`MLIhVpzJz`tXf0Nnb18EC;lgB|ej zP-K9vZ+1(fnllv#iwwR~S0e^DfFF?D3QrG8 zypJFymEc9!2+djHIh3f!iY|i*GJ#-{M1r8lshb1AmKJ&#Y}fSHiu4ET{tyEyk3+0gtr&Y3tDbGE8*zIsN!5q&!ICsU>vmXH66X zTi0$2Y)Gyiv^1L$0+WS5V;#M_Fw)UA+9RuI)^mJG3k)7kl!L*ub{8->l4}bF502qc zgLEuf1T!67r9H6<8Rx^f`6#GYkN*ZLJsL{_V2zn*0_)+gu?Uzq-7$4SyUVao; z4T}vjd;zgweia9ql?)pJGOI^houLS0=5pY7g{6Y=nHnx|q%edgoo8Lqr1K^Y@-`VR zYZTwU2gO;E0nZ7G1YE6V3*f>-XwrGY70o%XYk+q|h9eE-x0wO|i8&AWYhm%gyVbA( zuQ{XvytONuGCOOa?s-IEfsQ}YF9oXP?+R1E1gilpl)Fh3qCdmC3~m&d*1*ly`&Hm3 zq6VD;NA1ulaJ2-cfC;7t+9#K38pZkFA}GJ57x;wxg}^u0pi{uXZXfV&B`^g{e0os# zjJHvquM6;erYXSB-hTu5i<%vPpR+pv_{|cSza}0RQ1{F)QCuJi#kaHo{_TD);FC4{ zfP2`f0`6Oa29E?>0Qb98l%K-W!@n-^gS5jEKimmmi654DV2K}=c>ZCD-#J(21dQnp z_UACBowzIjFAG!v{AV3H1!k_GQ($>7x=hHDf-ZtdN1-^|2f!yd?E$|Vs9J`=;(i@E z1^TYQ6iA%ii~fOvM+p4`g&Zf!bKFOHE<@m#0;S4qI9BVf08YPxuCcA}g(t=4O=#xL zy9#v`W}@Hdi{5{)8t$p+5iwzH_vow4UV zUTMIci!gPmtE$?*Z%PDqwtZ8*->a%G^-ZP1&a!Xn66`GC8tlyB+PA7|Q@92@Be(`T zL%0SzJ-F6cRjmcrV27x~McD6yi=9;*>jPEQyEh0^6&+R83Vl<4u#@SVnme{3@#FTD zTZ-j>|2M=6PV|Kmn>KAZdd<t{#l?%0h7Wf=VC7tLf;gZ23cb zwrfQ^8@c-L4-xtI#gSKyvN283(d6&dI~xCWcQpI!joY_x@81DuRz?;E#xuwJ*Zh}# z@VWu3OA~o3!t3%#TIPs3DUa&2u8hRkj;hQjugI*kBZ;;{#f$3HbL$6@Fx&CD1)deI zb-s-hq)u<7d_|C^gbh24HQ1XKB4E7#719uYTrEE*-uU3VQH$fMxd|4=2i|<^Jif26 ztkYOsXGyh&S2{|ycI&=YwI)W>mn9z#iQIlwFU}&0sS_5o#?*`PXfM=>NH8(~l1n*N z_h8qP3&X~{9-r;_v@6w`q>z(xra3?7iPfZ2&g1hxCvsB7SB0*G^LnY$e)c>*~1Hn7^C*xSfi+WM-7U+LwmFU*&wOPUyr(p*1mu_U-Q zZ8oo*|G*N69MP){;Wyj$wSnJ!=ck-UX0ksha$ zlVQ}}4@?%Vds{>~lwZ~Dn7Uok$n7WU+Q8;$?b^uYr9I!k;o{G`VzJ65o8Y?hfozgD zzp-rMUA0fL$^PsL&lB7f^PeaA?r?gZ=y_=3d6+J<(A5xC*_5mIFOFTf@?cxn1;^ms zo;@S?q!BZXksu{!+(@9DjrT}!P22z4<3Bje{Es^Z`KLYePdf&&`ipk_pEe`%yB+ua zU)Nfa&Lm)>@$iU%srG|i@g|2JUyC=@4c%&CqM3Ns!c-@Ef2WC7`rS@L31l;;YMqe4 z3DtUKcjb}>_FFGYYqx7nV`}*1(lE8#)CmhU0xFdY`d3P@L2NQ<$Dcir$vE=JSSJ0% z>rXP71`!ImX(li7b2E-Tamr0Mdq0sC%Wz-FE{g4Wid~ZC_6t`-4|M&w5-GN*iN*dcuFp`rMet)~ryx1Bw0 zD8{w_tAU8v-Gxw_RjNAYzGjX16N`y1t)(9kwF3Wfmekv&ExKW%?#-IX*6uAjvD%Bx zS_}-UY&%2tu5Ufvz-z>4oD+A9`Qm7t5yR1hQ^&TP`*zA`^U1RIV=R~bvy!pQ!q*cp zvX93G7NdQ(U%Z|;N4pY#$MeT{oV}Um_@i6S@5UcG+W5%T$dVpQ8n8+S$zKhZ4&1fA z)9D%#ca+;_>!~Ab4rfmt&*XAoJs>Jjt?EqQ@`*a zzkRODHKnzezujDng6ctXO2q;E4zKnHn_LbL_Rx6 z@#Y`dfwERNMlw79s_uW?p5u9Uc0%2g?UEU{A|Yyue>}T?Xvd9bp$8BB8s?~4+V^oz z?cX~3pZD{@hiy!J210x^;orUTFOmIyVA;WYs@qNVg8yagY}9B+Dwj5UVM{(8teAHH zh^XeJxqmuPPFVc7ueeg+iU9QluT%)1{#Mn7hllwUXb!)7g3p8k-r|0|JKoejvcD)f1{tj&GR_@SNj?1CXkRnJG$h7 zzic>fUASa~(C~4|2U|NnN=Ay3Drf*99=orK*6~+22Tq=g?(Q&D0&etEMVi_Y=4*dJ( zME;YxNOSq}ZuH5ezs<$}tczAoKDm(<&HaAmztTlCJ&2Pz{oY-$7*lLl4{mwU$Xi+UPE2^&1ShL;JJ<;kyl;hlt(vET0&jGsY- z7+;qE`M$v~aE*;|d-CtM26Et%ThbY|7>#hhUpI(c9{c;pq2=9wJ`S;%xwzf2yZvu3 z*qeY0@PfSnA6mD?^2X=xp2xygN8Gqx%j|AAv0~lZbKpZy^556UE&l2;D!EvY6pFt6AI~Fwm_t zzQdj{Hu79O#Vvr^cp&<&*m86FT{5D3ZO4$fH_o}{#(K4Rq$68-4ZXVMg8;lpZ{Op2 zR)TZc)ULYDhZWk!I1#IM0cx2ZVw*S~^>*LNqEx|b;qY=PR@tT4O80F<-j>BY()gTu#)Za_uR57SZRv0Q zUPPpRI4QR{{-gY4R>7o1>s#~r@kNTG?)QDW*Jd>8?u;jOR8RWMn@guSHXeFe+#Kd9 zVPlA+R%(iSt<67S9-in=YZ71TWUcGlROA6RCqtGDS;Y3zG; z(uZ~;@?;M;Rc3)@Z9Jnb&i}pH^mE^z4vTqe*s`9B#7+vmCzG~QSTNCi{B62E3FEnl zDWfMxY(zi8nBVB84Ok2#eU0V`1F^zN>t1OqiNnw7guDj>eR9}8ya_Jd#vx(Y&-5<( z^&j3zc;qxKf_9i>{?qv&D%u8u78H(W^zW zv`C91(oAt@Gq0h4iJ>ghsz6%$o4blYqAY3EqV1$cwg(cLs*a1)Lq(ifFo=_^QCA$~;YT zj?gs zw{^AK)&;GP72SIR(&tO&zN*ikTX;)Ro!v9HrZLnkQ8dxuecL}`MCK;`{)_@mB7OHl zp|)2hot@qvtrJQoY~~r@@eg!etdC2cc!4vv(3qWWxCjGiX4$K4*SpG3v4ogmr^Sor zYHc;C7mIhSFTuCH4;`Kl_Y9~NVMok+E_eq`Ui4;d8_Dg<@vf+#t~=lbbyEYpSp~Y_Rw{y#i3n@0zHnLPs>fIlL)9OBL4GZV$ z^Jd7hpTcZ2n<*_jbbW>{g;XH)CharC2Y0SleZOUV1~m$x>VaTjXtXjYtiJ#uvk`9=WM5M%p%2fb+YV8TQL( z6sw0}3&@b$>&PhAbi1>M$LZHq;lsCRGL93c(Swu`Dnq{g%0>uJF%W8P=h zdtP^^M$J*u8bV1+63q+S#C0B1&-U{i3d?kKiX$#Z|8#6qp(3Z9OLeCTy!+pE-snP1 zYZIHcRc8H~KvV=XqC5?Uq_kt>JrkP}JlV>1j+htB*r+WX_`m|cp6+U~+DID@7ZY_I zxHYe(%u}IYKASGcm$59MRZuDB%CKf}==_JHdLu}$KO{f6lVFaC^n#`Ok#MYx2bbH5mgc|l{P5Fw4LB$McUb#2?s1;$8pIWZ-S zU6#3a){I3%eD8D({S*~vgkRWd7`R3u*)7pW7sc7Czas}G`?fD374_o-hTS=|@xBJ!jO&)Q{NZXBmJgjRA`9;IiW_Um z>+#gJLosVl*5#rc@a1C3?v;O3YL1!4sJK&lcjh?<8+t^Vxq_8y_Ki!Nc9|3nMkdRX@xS6PNE)J z2p2bBmb%oE?>`|pwB2)WjYaXR>2YpP3xZ(9L;rsL>6atJ5$SARYt1-$=N4QEO;OnB zd(+13?T48vBSpB~BW5IK>@%F-%aJp6Iw1U*DQq1^>}R-y)h~$%iAR+I74HT<9NZux zYY&Pki`m>G<7bapA9>T(gRuygJ6Rb`KBv8Ly9%?_s5Y8*k9=p5)= zk<2%HFV$$yabs~xLXyrb{yw8+eWdvPvEi-W+E*GY8th{#Gn?{0bS~;HmoDAc4%=qF zE-^grnD&W&N*miXym@TmuJ!;=)TDclDDq*ZJAF2LZuk7%dG-$@`H>d;{2OGVDylL@ zHgwoX@4jDbIsT<@Rb0>U=88`JkGVUUeHu19N9jCyZvKr&vo+SWUCXBeMP0BJnfo$_ zv!3$P3w!tA*>j#3|1s+XtJ=&UGlDf745eDBotW?QpZJ^SIP zPpg!YP`Ss*jTVhZy0a&Qy@=)x1hzI0EPq6%D}K;Y(IvuGm50`@kB|)OzPnTnH@dK? zr$%NLtlQD(YI8bIeXMgfZfi&TActPsRYm?CJ zy`T8b1G&!U`<;y&-2I_GjPq)93FBrJxwq$bwAH(m;&ThkN5)HsXM3_lRTk1uu4v}c zveu3-Lzc)*h<&+Q`E^~oHvK0srAVR`QAR&Y#|8v3B?`nVF|L^C^7d(0A zk;+Z1$ezoWI`lX$10rl3p?vm+dQ={XrP{-wozh&+z z8&HK%ch$>w$DM!i(y|AsYF5# zq2=dZ@sX)s7E?||#M>s?J69G_){|Q4@^I365}&;;^H3}ImJzS%j%D=RI_*H(G5q#H zsZc4bF2Zm#`u7vny}sud!^&ZSpNVd>;Y`Qoq#{+rUZqoJSqSYbj+$32 z!M)dr*QpN5OzH$j?QzE6d$ew_OWhZJ(#DmzA)mC~;#tCPB8~2Wuf^4}KNi#0d!FY$ zvdG|%iq@-?do7}s4P6MhImGN*U&3_usIux!ERG{>)s~UiSP}DGv!7&UO7SI|%ikK) z_m+t;t#qP6ZrOlt^(Mlow3L`js``Q1Qda7;XuM$}Gv5U(<}A!-HAr2}WCayn!_~g5)o{8!@XbF9z zMMvuS174kaon@Uzv)W@WE+aV)L{p#Ay@vet9+;2cD{o~h@>CiVJ$E*Q>$S*o!k!48 z)-%l6(udyWcCS0LB@0T>XFy>Ca^IQGe%RMzagt4N7l;>Dy z@AsNd-#sX`I1o)N#E)rgW9Kiy5sz4ONlNoeT>LLE4riqfjO%Ubevz=ubARvRDm9ul zD*%^l(PQhc99$l%BIWz%bIf~=JNrhpPS#xEn>9Tpy?&`Jl^FQ8voU~i7hhznllD84 ztC%6t6xUX{{xIHIzwT_SQIBulVqY9aqAMfh4yG5gIhskTT8_s-AG5~xvrWwyb`vhX zUh=~4B*ZM~LRe3iE=)@%M)W&3%1<{-$ePr>HSXp2L!!qGo-JFm`%1Jj*BsaUxWnuH z&VtU138i!EzV=Yq8amtCGZdLs2{TyvbQS&rZ$&HFt zLwe)sMgB9#WS8LI_W$PpM!zX(3ukNJL0^ORFqY@JHwFcysb*_i7rM`?%bDk1?yfLp z)v8#%`}yB^*$RIZIh+j)*b$8_(?9#JYFW^X^!8k?yX^d!woG1>jv1!iUY{c?)9 zb(i^W?n6ROyN_||Vh&5Vd`Q*lyRw+l*mdrlFHR#z8Z2kCuDB@jeJ*3I($qgrGj=S( z36BY}c)mGIa#>I3At6I{ODiD5u2CuNPFCfU^c&@?zj2meo0?m1-8o46ju0hTkzkOi zS%26Wmp=0ed*h(?j5MFq39q>HtedT!>$1e&r#iwDWWOuS{J58Rd8hR-_ql90q0e;o z=FQ5LG6qkXctswZhq;tx1u&S-jV2{w>8`EFA?_xmT%kZy_4l~Pg0=kdtDv~dS(Sozj z>0IL`z~_}zJ#)SkQg2NQuBkoEo@O?+i&C7vwlOtud=q>i4SvxU-g-}^b%FV+hES>= zL1zi=wkUpJTvLbD3{mdD^rkVi2co2b*-ag3PpMAxRmN}j3`KfP(zKB=uJlLN)I`bu z@XXyei@ogvcUg4myBmCp#9$_YYyI{zQ@cPh{t{oWVP2iZi67r_R2y4Zvwf&T847nk z?O>y`5l2bcf_0TD*5@e>36ik;UJQ{UZxlx(_K->}KgpAy-X^oMO=PsfyRhx5$Yx`Y zJ?jS3litz)I6B7JjKT7(OOgk~c1v!@V9v|L>GREsR3?r0{WeLuU$s?FQOhe&H^aw^ zUG;j!J7g@n|5A#5$`$$KSva%)7QRc3*gMGQF@b?KED<-vDd%;r;ds6sH{Mz$R^<); z(Ar)DAIsQIc*assboG~n%>1tF+0;-~#nc&-;yZtNN;(pDe7w0%i|gx<9Xat-nCoPQs zL(kA}8o6}2ixpLSU1MAG#2VF5QMXCZ3700!&@87&8Ah^xF3^~qE~kDiCtE1oyy8b` z)H4sM0_4%x9^l5M*T?ZX3PiP$>1TN_BfnGLql{NNz6*OVpHQbONgoiLKZ*}p*4L-N zn(>$74k}j31?mKW(O?el>16iiujumla|HjDp!)aS12mTK@s|vuIlff^7Rngc8Q4_P zp5s%}aQpZ*G4GC+U_;c{gmV^0ifpwlzfOOvNAeBez06raScLQO2=VIK^v3xWbz$eq zYwo3oZd0nLT1k<-AAe(>f(zsATxd;aJ?w~jX3eM{rTe0WQ7z;W+R zl2yUER>Pn%qWHkMP4^jrSpyLKhnxN?UzuSo{)W3p3n}DF*xLxQc%2G=YEfO{ce(>E{-5;Ex2v@ zz2Csz%(tmNDdr_(8yWG<`0q$Ld5Rv^w^GX|SL6e1D=JZx^E-P*^#<+DVg0YMlZ?hA zPDBZFNb!@BDZovtd$C%GImfUxw-ZMlpIMNilC7aowY3_(=%GTai9-pT@25~aKVZ<2 zexArM3gf-}if+eol%0IzM&O8Eu`hf7&Z}TnhVy29Wz0SHq<3utvvdm6FSeb(O2 zwx7C^YA*Nqrq*Pf*EE}|%L$`iOw_wPzG(*U{cD42uldD-bV~o@WnJ@dje3|CA$MS$ zn3eGR+YIRaEs9C$OKC4fJ+_aPuATwErk`d|8hb-_!3~(BFY-Ig z)4GT{jq4fBc-+3I=_2NNk@phoP75bkoq-Q$S`>8WWPOgdC8(ZQABI5CPuWHs3Y~+a zQKMfJN1A9`O1|sq3(rdz^v%pQco5yhp5Dy%fC1ikg)SF9r`}YXc!fW%=ckrsL3fUq zeHV0xFlo>w{VMO}v4OGdV4YL$OxgwBkKE6s3)FmFI-zwuMoMUeEYvbP3sbxrqM2R8*ua`X~aGWTUc>fUdc1MCocx?_^CL!ce9FvEu-2u$pVfT{Hzm3;%|msHOVfkNcsP%>5GY4ov zb6cs0MzOc${!z+)!E>2RlSjmP+25SOWK*vtoKv!yFR3l^+~jn$%I({E8a} z>5Iu}{`gC;xSH}w(U+8$PgdeHHyn?lej|TzTca?<&)Q;>_O|RvU6U=fB=kI2JMHkS zwOGTfAVNV{L4fCy<{zKo_G*!xHL24kTaNP{^J3ds=DB9oJlrJ94n}Gnb|XeVXw-mt z^Lhn$5wZEl!`iFiwNs8?@@SS`n0wjMsvzw64o~ZZjoOB}*YR`e<^(+<-+%FK@!TMS zuyG&f0{*+ih$1$`*n3#}p8x!ypEGbLvMykEF326eUx>dvSEbJD!cB|pVw^Rra~a*2 zbYZS*P90ho9M^)E)9JHsLE*C!u7Q)9&nzJuj^4%QBUiNy8y5h_p<8Z8c zT_`)dY`;b0E&!*zbV?Ur;O@5%bIbk1d%r#Zr-XpKBeb8r7nD$z2(K6>q})*5Se7tX z8R!-D%(pPiOGi3hY#Jb&UMd|cU3!xva0<7Y6y4G0wj7&P7kAYw%4Uw({La9hHn({R zV$&$n8^R@-pv~>AL4a43C3DW8zz|CaNL+KuZ%&)r826OM7}-xx4^)=@hLs40>h62# z6t-vUS6#lt$}Y2NbE`8b5lm=PX$>t`#dJrN35tAg^yg*kJJ`o4?}#(UGAF)ISg5kJ z2CHSz@bJ=B)t2X;TJWgNZE|{dYHLM@=^A|%>7ubi)M^!WPlR3W*_wuxT`5wney&rc zHA=~~Y5ZC+;n4Y5qgN{GRjD=QIPs6z|Xf(ere;{+3AlWZstp4uuI zE4RxPEh?vpY|}M)re~TR;VWDCA&ya}m1*0vW(X#zs}iR61#;n~`Kn%PrGGM^N=qb2 zF55SokytjV2V>qRR$*Fu9sN#uc2sK-gu#vFr->TK|mBuy`YUEC=q{fvd{0#L>0kohMHRZYnLard;qZ#G5{OESNAu zuxU|uQrW(wvRj>dVvQ<>zH@hV6HKu0JmWSdK``M8$xVPw_}X1;O-alw`%0JYHpcjS z!8k{|pur_`?2Lyx)QtM1gD?C8|_E7()<0Z3X-~X5*yy1wvF|%jU{C! z+m{YmOWku0n(yd6<>nIL*8P?2f?IdRnyQ>#(N&vfZb+DW&~L?JX1otJUy$@9dPApo ztPlJ0K}FT0Xv|H}Fgg8MW*Teo_*or7RgO_r&M_O+L9>1JX1l6#GMLuVGHW>J_UCKr zGd+IEf{5aib;}6W(o}0{742N6n@gpUL;bt`^=7NFJq*3vK$=NoW>;rYSKLr$S5!4S z)3~p~t^1U8ye?r&bxyCv^HIi`T{(=v1DkaP4THJZ+@I~Mb4FL?L^Xpy>B2{pu33Tx zE!z8A6h)@TDEd-bF%Q~wtQt-L|5sVS57Kov7k|&BcZ!z+w?W;iQ0e9ukGmbFHjr9H zy4R1BrMgwC8hGYT4OR`Tw<6l5mbneAU$PDENcW#DmnRpTnCQuDE0V8xKDvQ*z6g`! zpD%4-4ZapB%NA=iux>Jo<+%^ibNxF{Nzdf9D`q{7Xb6!eJ|ZpYo;ptIsXDwfx63@% z5;JOGnPziK@^;kwSmz&rALD6$8b^C{S1t~cCT2h!!bU*@YfsJ6CUd9fa&jfH(LA=J zJ&)u)h4IX%=9{`E^VnTxr-(evJQf~*C5!EL@R(#~*_fK$eaNpngu2bVU4d_c);;po zvV87Vrz6zr(M@gByHYJpoY5`ah4a&x*{i!-R(@ZkTeVMhYBcGAkH+K9%uH#bY0!*r z2Xkn1tBF@tc^~0KjcQVna%vZUXRYSJ%$K>dtR&$e5|VGd8Yj!K-y^%&UqvSwyxd3L zx-&Y{Z}k(>8CjCSkMQs--9&?z+Q0j)&MU<^lD8Hpr|yurOrm#<-?-@@^HTF}>9=-u zPYf=+%g>!vuMv{hT|~Q4@Z9R1<~Qo}?>GcK5S$Z@s1Iwz6|)o$*^e zgV1(gRj;{r$Q@fM|9vdoP5%26rfeI;_eabbzfqEJzZH%bg_S<9RqIFj?;_>0ptsHi;G3FuMOvddEzw}T*J0K7 z?Nd)O!&BwBTFtxgE;7}bytP8PpS<-&?ktT+33D>D;2c)OznEa~LcAZh2zErNvD|oJ%MB3#wNAmCoA#9}XWBit9 zu}edF%I^_%aV__OXqQ;*ahU0 zrEo`_OSQxBN!9!&z;nVKPxEw8Fx8h|={YbSB?x!SSGb`w?h1`jGYeJaj$JH1Gkft zOk}i76)l)%+&RzX`7Y4{Yh26b8yj=KYPx2SM+nUx_gqJ`V3cS9;q5)&Z>~yTMkMBK zE+p^ME%o>+dQX8oN|2K9G5wq&>{7w z%ykWC+s-`jeNY^6ywUJwL=Oh8oi)6sDm^xPO^wwPEqIf(On-yiR%G+uhfdu|BNqf8 zPx%>6{dVGf^7-SX3ERxe84%%a(Sr3sBI^5_i@c`xg^N7i{}yb#EycCh_W5Jk>b~0P zL_T+y=;HU}O%31hc8qatSo?GC)umq6XA_pv>Br3;d+9R#eSg+vSYpa+%@X2OHoyCD z5s&8{%+|cZrsN$+2qst%cZmje;`|A@>DxsEzo!NeEPOIs0!$jUynH1G3VA!~t`8*_ zyrBmYEb{&Abjjb4R_T&ga4+{;>XKK{BK@=B_b(Pvq8QeEy1^V(*^iiJAur|Fd^(Am zQh(#(-I%ZA3C=UILSDIV-VZ^9TTf%UP5+< z4SZc;3{1Rhq@qDzeOb)ca6@Nl(>U3qqBXKdfphhzk;vEvUGiF8M)PcoA);4nteU83 zwCLDEEWBs0=-A8+oQ?J-O_J4xi_>26?`7LPA1x}H3)|E^J4M(ikqjCJ;2Ut!9OmQeOaixtIl69}_a zZ&x*R&GBl*9$rl-70o9{^t~Q(t}L%=4SgIfsZo_KrbPFaii;K|g!cx+@2SVF!mQ#w zf3eTVun}>O@-Aeba7}6neeAo+-YdSPdPmkZGO0Q+`^3{TYwR-~w{(X@)|!eev|Ymk z14J>)^y}yb^Ah&<|1tR0*>@=i>vmaOqw?LG^cIo&F}1PMp2d~y>)zj%Xb^Xr@iVhU z6SA~gLXRrG$?qIfPM)nRj;^pBdxf4eKcP-PEc-+yJ58X^xwA29>Y(3Hc!dcybWo$j zwu89*diT_h$h+IIGsn|nDohMlcSLT@8T;G_*hcg3o-gf)ym4+jf2~)^k?s6>w;H~! z4Bn?(VS@EW-7C9TeT{#xpz>eZg{71CSo z#~yY+^Ta(=yFGYT1?P{$Z7-)7KXh%T&3D@}N4Rerf8MT+kV%-+T!G2gZd)EG$27I8 zJ#^hp=R0oazxZ8mb;Hx2?E^#IryJMbExWiTYHDlRJxq7}(*s-iFHY;-D%+5`t|RBi zuC4re9-*ds+up5}A)r%FYN30dVCqD#qObd?g+VC*T(SJo{{hYl5=OcXI+wM_(r)&3S2J2>Z{dTXk>zTH(sy!XflXbUw6lc$IOPlj{ zvrUKdx{8RRJiCX+mDV(?IMO;o`{9T1S7KK)ZNFAv_q=z{BgbLuL|zXo>K|1VDY zX4+2fe|lSV(#hWA@p%`0x3r({bzK+rOm|Du_Vk5wsJo?2s|F*tw7?+E4(ITV^-J5< z)h|7hX`lYQT%asXPyIAb?@HfVpwwK;*BKt%(zr3S< zaFN@$;W)QhMjgCw8)f4jj&9#ZB2mS-hoi%{Vg_q0mR>i#awxk(u!9z0dPNz}9#AC} zWzp}dA6#p`%BrI~*h01unG&ybbYqj9H!1Q8PHgtO+io#liJ@|OpbUV|_3v{jgeJV~be=z#tP-@Ss?g<^FMc9(gDbbQ+kE}K@HejU8g5rDX z2RG;T1swOVkJ8zy_NGKLYh9qr688hTH8%ad_Zk*7?NLi!K(J`4@fhgL4)5Gh|J1o^*e=fpRTiO-W1WnokBNroZh|3Lz8!vc&K|ca=2v-V>vj%qr-!|RuDSTsPIance%S-*<00Anhu9|VtvLKC z_8A;ikRxqjvjSU%UG?HF0-!%r2+Av+S5sEzsH)hL3!+ z(KWs!&GGFM@ z9=iwJi(c7_ui$QZA7-<}?c$ny`i6zIbMNX?V=Lw_sLNXI(JQ~R(fs)H(sCX4itC%= zD>Nux6@~N%##`K8j-w0KM-81CY}siQ*&0$&D1AWbIvsIwyB=AZ%ptNwBGGa)0M^X#@nY^`Sp^D=loR9&xlr z5gk1tnVxpepGMirz{phY#*P*?yz+X)Y&X%wj+V#1O83U`eSQUAU#oYX_t~b0-LKi) z>+4@ps1ddz%5oLcqm?kqImSP5(`MSHhauft^_W#%kGJa)NrxYWkeJf(_qOCdtSF?= zDhiG9*zAYVbZ~BEl5o0pn;w_vt9GpVk1e!3uSu6;c0UNg=;FC^2Fmwzv`obYPt%Ti|TGfUbzc!sE`{7|^)@o7e zy~uaXzZ7|Ck0G=lF-gl;4|ZFaKf3JLIDGdSul<@PY4a1DOw-QwhcDu%)=Zso*&!zn zcieeXY$Wk#kuC-&dU(SAV(QFhL~FU) ze)2M&{!2d`b}?drpa8zt3LUMow)% zm}wdrbKf(4YuV%!D}CI%^_{2LjoL}aPu1AGb359iZJ4&UVBNbFda0o*Dyazn$hYSN z7IY(rTwq7d@_w`Yjb3L}9qG;1$hq#<213tSI7~IMT%r-;`r}gB&34PvY=E3*eYmJJW5Y{wd^o%gYucM}o zTF*yC@VGIK;L4dFwyJ5=yirN~u;8{)t4H_oM}_r{8odfzB>8g@{7m(ckVfs=eNg+m zkyzA$LH&E3d91e8^t|5cj7@5G^EBIUZ37Pk8@ul|wXa&VfNZ3xh0lAEhyM$G2wjrro!F~zDHN>>E%|;46_uY6jcdUmYYVSP!!x& zxs?l3caX@l)GJOfS1B)clXHyxltnX%k-5H|vif$hZ5nNv4#&e~aPZztA|t3%aboaw zWmq?fEy2wF6!lrms35-Fcks1dH{nJQAH(}8WYxL&-g`6Y_c^(=PEvUiMvqCz9_(Pm z9Kck|{KTc3NcXV=Dw1z+*%@Y;3?I$h%hm+zkMViU_-Z#kK2upC z>Y@;x`w!R?+w8ESdOBMWQ>U=z_Ok~ElX7XX2{?fO4jmNNvKS|%JGy8^^`s2>LJwkV z7ubD-@WMaSW7W9o;7Yo_#O-itwRdl}F1E~_*d~=*S?C8<%ftG+D*N^76%~U?=G|ly zu0q)9quMikqJ?y+0Y}x-BJ1Blrz?7uq4aK=6UM|^eWg5^L~d2)L0rN8bl#7r#r_mc zY6_z_lS`vo_=^Y2<7sc7>R1F(X`;dM;>Wlk1&3x$)IK0#4K~%#BrIyKSn1CjYEx(k z{CP558Sk<kqEE-^iZpemR**VBc#;GvFbwks~a3u zLXEo&FX^X{!>amYVsV0e3H)yBKVVVdrbx;akZg#$3CLSa=irWa<#bsM(@nKkJZOj@ zdthDy_B5AP^3Ufoid6Io_9!MK285D%Q>DbutR#6P z5}66Iju^hct%>&lS3J@SQiC8~pUhlpNo+e%A~om|U?iOcse$;@Nj`K~6W)Ts6%X`{ zgw|_QuWB6}ZY<}x#K=C)SM`JPeZJ&fB`IsL3D1y;aY5pcZl74&RGhDN|ACB8oz0V_ z;HpSj|9&X2CcIKOGDH(7MEjT;dkOT}lN>C=pjYXZ&e5TxQIEx?lKVG-XXyDJM;1UAhC&RrTatfasQH`SgkP%oa<4=xb?BEH!#6a$#I36ey zQ~q@VL61YQYUt-NDbYfjuA<@uN_Ms!C+@;Zy5*0uHLB?Ra*cN`7D0nadq*;F*fnZP zkiw41e88)u%f1(5%J6^A&tdm|4Fbhcy!=R(s@J4eLFbr*=PZ?Bx9epu=|e|_rv(IB zL+znffcBtfzU{((Q;iH53i^NwdLA-`soMXcsh^qxQJ1+oxzwwKoTZpR>0hr(lrv65 za(q=Cox6zIcR0OzjDSzc%xnITJ`l-6UOCs_>|{1l;!_&IMN%$yQ;f_>4CS-gmXU6PzI>`0nNwd(C2e*XoDyF!q%iwL zk^gPTKby0m4uy}V49tFLQ-60Q2e-w-(w02Z?T}nS5%fE>CG=>8aUDm@_Ym(}}9cZmN%!T+V$cM92F z7dst^tXi0|N32j5ibFth3lPYpG{X%9S3J3mW`W=k6baL0Rxy(71MXe4LCJq#w#E z!!{}3=9Bx89)iS7_>(yN$ss5qFTD?m)nibWFRw9d8s)Pm2Ne3qIm(Q1mI~|m506Ij z0~@iV;N?{9LAWlxMUslN$4gc6DT9JuOEnlRoXJD>2Qh=AipZ>3hCP?_$B^zb&iwSj zUe6CR(!D{3?_i(!Vt#%I3$(AHdvIvQr&yajqd$l)hAxcS?>MxYez=Mb&t@^7Z{V&N z&XJFjkudt7BPYhf$gpVzk}3`+VcHhcymLQx+ox%YuGcgy`a>AQBlM}Kgu~Y*?8AlW z;}rusB8mJ(NBrr!-Gq<-5H`pi8tzZdVsTy750&)~TYvd;>!C-5{-3meSbPmJ?AfQD zt-?SeyUD|O{V^rJ7@um$&_5+8=nm)cr;J41!}CHq`zaKBba#u-#9<8^9>_n%53{B^ z_)i`uU=(7s@DU(Oa#`e-6teLu~bfAXhDR38}5bC}4wn(zL>;pd_FC|3tcn2cBP9~11$ zoPlOw!;kHTFQZ9H50Tu!W?MFWuaENC$w)?b)Ie1n?pLy-pGpVuWbG$~ zY|edNzbyY`wl4E#keESqiLW;g5Gx`~aD1spIn@Fq>hQZY%Bi_Zyw1DQ?#B`d+1tBW zV8G=tiHDTJ2u7Q9;9yJ^y}{cU<2*O!(#%v1-;;BD57Efc1`R$- z(IZS1I+Sa~@RQyf@;TtE?6uO%6}9t*l#gVV48Q9b7U*Iz&{9iK7Lz#QZhAO#pu-jf zT{kC|xhB@8_F)gO4|N{?nmM)UO()zch`1X2R&3s%&aX2^aK?tzCk-dA@L}G9_$ZX{)1a5|N`$zgoJ@ z-?FqVmUYKb^^kRk;#%2cn4BT#xlv1S^Ne+BFeSLJB9wP3hgy42XqMm! zwA8HyP2-Z!8L5+QEWJwgyzTTlkTsPO;8-`W_HONz+UC~66JfEeJvNWjk2|@)mr|>FV)NN*$$Zd`hup*$!m<%T_Sa^ zQ$0h3J%Ox(QtD2KR6C05SuDH}$g*{0AF8W@FnepMt;bwR4_JFllGKm3 z-i5eA1c|%1JOuC*z!L!F0LqX>3V>JuDF`5oGyvJqS0+R=EFm^@{4(|K2)i3pPp0s8 zAWKfsq-a~r%9_XPIbC~C%U`2NzZma(+}*37X-)FtW$L(_cHz{4MB$@AmOsS`Oy^`R z;3ewEm*Qgs1k2O~&4Ym~_Ce!=+7>Ib40%DtK^*5Y=S7SwKAWI7;-GudDjnkL?ERmf zumpfb0r5b@4hRWI4gjg6c2$w0*3U7HaD_ThCwvyj;yY?MYFiL}@VuUHYv*eD8zQ6_q~)Jb5)G!iBzp^*9;fiZ zG$iK=)mqcw5cDy&2|Bs=L_yQcWUFQB+#5MJsm6}Rlmtpbs7s;W9q6c1=(#i)^M-iV z9Z+L z`Qr+6U*d-jOB@TD*vSdY)QQo4QPctKqA((mMLNU<+eLDHUQcCx17?pKq`-zc(y#unU|94t_yqcaYgOWOf*t^&zug zkeLxOn+|3L$c%@~sL0II0cO(BPcf6@e*Hcgo5k7_{v%lastuM43ZYpWjKEDYwDbl6 zT6+H_poIuQ!e!ntMF?3PK`0X;3qXgEl@>zx5i&stS=k_zijX;=He_W2sF?_(ZfFHl z3oD6&R1l--mW>!0SP28rc!YjOlXq*u<|~^)(w6Rx{?X&LX>34#N230W1XiZ?ZE#)) z;2wbM@c`}vs0Gl90J8W40DK@sKq!FS$l@M=N&uAzfCXlK2MFX?z*8Vq$Rq{;&Bcj^(#QmnN4M@2O3OK79-bz65!9D$McPQ~+53Isv$Y z3eQ0GiZm0R+4K@Ve-A?Ka0aZIHnePJpOj!vCEu&StT31t^X+AZ!O1m4ZykvAC41mJ?eE&%QT%m8#FUDU;uzwb!6>gCWRULRD@E40SJR}9)i>mq10dk7(Jnn_=UDc?7q0;U2%QZAP_z{ZzkSO-Rw6r1use_J z<|4bv$ZkEdYe9A!k-HUO7Kq&ag3JyeGecx%jm(5dPXcG^>VcsFGQ@%5g0WyY^*k6} z1br)df%NGr5`*O+1`Cjc7Gg*sE+MuI*!?144-vYF&`N}mSvx}K5i$gH2w8r3cmBqy7bFN2&sfi6u!3WMYXsmFh-FOVVsQC_gWr7s{SO|=dn zCumw9gv{Fpel1~I|E0eCmAqi!xbBk0SxQQU&#yh zf1xih6$lJ-tE!^$5Q+iJ>TEQtPe5${Brn+ivA+CCUO-KV6e6ezS_&pWY|Kgw$*ZKkpccaO0S!`$$5{??AFp)@zoRJXyPxJ*z!hez%?Egz&7P}%b zF(j?@u+bD(fxuXS(qKAO`J>!m1p@%Y#VzSLfH?pH5ZDdC6TlPzn}+pg7m$-cmH{b7 zCg3E=7r=J_76XVyP9S^o7Xf&T0CEBsr~DrP97O>6fQwVUDF6W^T&xx3pwpE&a#hiJ z80VRlO|q2Bpd~BO(&S5V!TwLx#0T9xR+ zs-ys|N)Dh^35W~!f2uBjEiTx{)k|ot(U!Tea*4PT8=$HHDS;_%=mArj08{$E(-ylW ze=RN8UujER>@LW_*pN88s-jF7WdV$GEE(RLtcGD9(H4g|Cm8nR4FK+gMFdzlp|>;Z z09*%PivW5%vl&1tfOiNWA8T}=|AT;-0TCi6=*onlcSz_S5W4Fmg;kI_y#1G;dqC)} zQ#SxV1mems?3QpOi;uRR0yJ8H?(2XnHKZiN+5)crQd+Qo`_AaERxbZuTac1a-M85+ z4nsSdfTHh}h zDt6K)To))#diLz?raWKM;!T{XyR2HC(X%z9f#dIA)=!&F_%&V{(B$BnL;g-9OrSX7 zIk30e>iOIjZ{`oWhSl!K3HzoW*_dy_1V>>5$@wAIncc#gXq}x zw3d@o-KxBrQB7e=8m`D~+Zt{t8hmzi;lh1fC6w-^8P=F%S6nSOC#_W(l95JHNg9F| zFPD}%S~nYzUb+#l5?9%)~6Ia-PWYx?abYPtLESOcj1 z6`q%r7zbmxSyXH!Pw)KE#(4--d+(HuuD8f^y$ zKYcf9)u>w&!;;32UX7`={(J{}?T7D4__8L-c=$^a{OUG8IOgHUZZevrjh{66*uw4V z>T5^MAFWo_ku-Mt&f`~Bzq<9U+U@P~p9}L&Pum#0WzL0Lx4!>2|Mxk61P`3|o;)u1 z$&ueGQziKV+rX6z)U|g8-a3e3(FT;x@j41GCDX60)+dg$N6*;UMic%?bNb>8WSu8^ z-x~Y%sO-4X0lny(KIXQ5=C(Lh$!P!X;x;KkCSygGa$UQ_)LmDqdMn}nmNC=2SIYGE zvxs2wT$JrU@!O0WMDhL!9EzC2Y?|qB5`lHC;}S}0hbEHb5(liT)Ww2lt8#}Ia8z)LHubq9KpOS#m-`$me4oXgXLP>2JtCuR<= zq+LT?)DrLh8t_Q=ZsI_Lu&xwcB0O2jB$U+-jpzC__w?8KN_C{)N;M^>7UX&ZVHPn_ zzPh2G6EDpcMA&hJgO1fl8~O|5+1UcRor`d=C@Z=Ks)ID${SpPI`#IheKYoA7pkq$5 zg$+HHST$3C1@yldEEHI(p{=I`o_H5g(jNl5)Oy1eK>lAGexA8l*Oi z9Cow#k7;kADuIzbvKd8!x}TBbk7Q)?3Ug4je6h3nVY97J!1nsM@5T+|RP~oDL!mTk zWG5b-c;xsa`LI=w;{Jy%FFgT;|CH7?7%rf=lf``PsANWjUwsvLD(N?>=IkY6u?$qf z;|h;i$SNKl4x6Kc5k72(3_cw63{r8gKA$O>A;@*jjc3?nYtY`_zia5fZs#CIZ5Wc@ z`tv!v&$!qKC~`O-)J?z^I)v#8ZT=M2$iWBxDXb3%*|Z_oU!=Hd#W@;k66!M4O$WP+ zIZVe&diC(gq98{?{a6$5$?zXGaa;P!y=oPodv&Dqn;Q5NEyyq`@UoHN`-egN$7C5f zThwPiBgx>UfIaziso$C5A>RD=eO1wU|1?q`dZ^2_XX#Nz4I13P(QDYJZZj?WB6&XN zm^HDMe}Zd5t|lcgVbuSzVgF(lB-6C5K4;5FUiqWs5lWr01flds2JH}|oV$jR(9i3~ zH2)`gr>&5GuF^tXUN{mn6KV)yB>bE|4$2p!_^)O~0*<|TWFvZbPZ)XmX!haQOx-s% zo*^;#kV3=z%OhFyIr9NBVi`IyU(OrUP?WX9(+JJ7;aSy{j>g1^`DG4|OhIgTn7&A2 zmVoVc?{k&G7mXawj*$iz28GDWmOiFs59cw8=wtXJ5-}_YFjUe%KOCN%$Tu3rk=9`F ztB#u0GAw+br^^@phhR%TPn!C9R~?<~V!4UZ z|6{IU!?W|_>_Ibi3lNhnM?j6J0{6Tur6#pdM|5~{fy6;tHuDG{#UcWhGN57nhpX9sUFYZ%|=n?Cqn5cfu0$u%PcK+u-E%zZ;xahsr$fZ@Hwr%OtFzf`#f!6komzJE08E) z*oO%Qy~h8dS_%!(NFe_%s1N#$bGQGTZzD_*`FYX~5B`TV{Nng?Vq(MX{BSCM_{Xq@ zPao5r_4hMkBnv+}hVra0W;8Tz5ibb4fuaPr}qQC|Id zNl3de+* z@cjgtF0_uMa&eZo%9yN@VZ;&!jpGq7Z_ce&R6p}*P!iS1dn2P`TA6Fod9UxNluhty zCnb!bzIK_7tfLZVYHkof9P)_alY3Q){B|#^p`z-@XqSB4(4BH|?0{xkR5Ur?0F$(P z?HW>&brfP;WVDr|5=+Ji=8Q{Rd11Nu!9bFf5lswLwRE_UI3dj*s`hr-HX8#gx4U5( z_HEt{IVJtes>cf)<29>__Zqn7BmxW?KJoij68T_bd&oxgwK`8cSGVO2LxPM$32S&!Ae zbo0FCRAEZkv(j5fckav-b$aM!JAZazK^%+c$g74jmvK<$a&2=Y)$^*;n?P2GV+ch% zdQQYLUeC_j3N8Pb!uzFog565Lf+nqGEvQAgRtl!qovH#^DUK;%Iyb_I*R!`4c82(c zZD2}Xi4`<`oBXYjy1})j7}y4*>X`t?07_k6?JB5Dx!StgHS7`8xn#mEh;X>y;0QM< zu0IBl3*a1p=>T>kiwppv0Cpkp81|KN;2!j4*gsw&=($_F2i>x*hFi8f;Fc|Hs^)v6 zTebk4P))?lLo=_rVM*Iyv&tzF9z)$sRsMb0ze=(xfLpkw5Z{esP&d;wTsCva)=}G@ z@XnNXz2r&q=G0?0aA&3IUdo3p=i)G!_e0q1!QVn=u(HfSV~-I^j0*X)XV1j(QP3d$s%Vf~JWnYf!1l zt3cLFioc_F!#pzrujhX4WQde{5Q5hZh2SkI5WJz5e_BycDL&iHeQ&|Bh+`o-jHs;* z`qCG0;t)9T7C5m9gw|RCpd5h&3<#?HC;^fJqzsv$%8xn#VgxvNsG3O@7w^e{avoak zIxT-GN52g3yUKk-LDT4zO-AatYj)SE1C2rvRLLB)f?}BES&$qKwY#98h7%8_Yuz^& zG|f#p3L6B?sEi>Ul`%L&F^Q8q24x?-dg)a&+KM zjt2s;oqGaq(G{5kkRkwGb^>)7;YvMp*%>W=PO)wg-j^nUE*qb0xlEmW!~7<7;I=R+ zkflkXQ?zsE`OM+<+^Y?Nf|}xJF!hq0EWnx;CsV*S+&qFh@JN^u$g-kvz;=PpY+ldP z+5qU}-tExI*(gI24r=Eb`mEsfY_2`3<*~`#RpKrAMOIa34B6KJ>FAXO9Tx>1=Yaqu ztQV1&2vsu;21i?2fh?&b4r+CXawzK=U8@IGG9?zJ7=CE01oF*4g=3^nyy^!PF0X}9 zrbTxoJ8IJia;WQ>T5AkdG9|gC_@SK=yMm^elx{E$Q9!j&t&kna;y4n))Ix5;>lt5b zpyf|4p`rRDE=n3H^!C79UeDuN20T%$EJ`;{u1;a5U_~x%sIW_f!3O^&Y$xp1j&3W3 zt?6l~Y$k8GY-UPZk6P_5w2z#K>Rdcgoy#1kUYVc;)hp+}a~()=f{krA!(Y)8u&-^0 z_O}%VheQkZTudNCD+E{D=+StyAjcvhx zA+p2sv{_=uey4nqq{8z$$4K zSS>-$#seyPu4U}7a&_wZ)Wcr4>;7)t4D3n&b>YlkZESzu*Z!xvnSfH5!z&Zu_HF9R z)FuC1H-r7>!kJnquyag|o8Q9gX zJc6xVY)N5X`_F|l|NZS@5RCs^H-r6i;S9XS4HfnD*G_c&dmG#T^V`EP^G51su)k9{ zGg3DLuh|Z_yG17?8*TpA>SnONQ#b=>{ttCCu<^7Twk?LD72Ezz-3+?K4cz-vfnFFC z=s~f}I1KiO&Y=CFXK3@e5p6zSK%378(dP3aR4k(dcIU@|84H;;A+sK2b{3iKM`jDr zZWD6%3o^Td%w8k2_sA>|nH@rAi;czXk)^fzVEb+z>*AFXafGM92@x23lJfA@nOkt_UGtDF`_s zZ(=D>$+iO7q5FcT0kztNiC~p1(Tm52m@82}*^kR_ukkum^T2<*XtpenR3AU=p7C#VXo0e~C#$c;01In#i+kn_2f=pmDu2llS3_usMfX%qpE&x6VAPXn~ zZ&dEWBa?^a9WW5RELL7QGeKqEiq+7V%r=?!mk)eEx_H)r5HM z(Fz6@)U9YiZG`|@!Q=pd1$F4ZU*j;r0`enN172bQK4j?tLI98u03Wh!0096D0OTSI zSlG8l0B{jtK#&Qn>|6bT;J}3T2rgH>Q&E?aSk#`oI4(w`ftKMTjAlB3mkCnWRz_ zNs(PCOJwXjHz8R^i6L9IRMu84mI}$fL{c)A82d1GX867C+|kGT^Lu=L-|uhp$ISIS z=XLJ$zV5l_bzZM~?w$QMy+{sC0(^bJiJwFAR3wKk0l*?S@pDL?3UcV^B>=GQm|X&H zbISvS00_CV{g4Y=5V^1$kPG`V5&{&FfWnCc6n3Dd3e@1}6hu!7(ffhu86kSgNT}G1 zL=;3%7%_JbQQL>8H6v;Uh?-IjxG`@YP*DT&l=VQ-9F!M>-~triB8r8GqAyU469o3o z?f~}oB5GTZD J-gZz2FCx`10WmT3)1Y+{Rmct6xE3W=y4r@tP$uZ0!bhcqQ!$i zUl3?NfGiL#eFOp%uJ^Ix2!v?KBTyXziGdunuTCz!|7wzL#|w!*a81V|*R&tFrq_V` zzY^P#%l<7u{+~ye|0=i`=))zz3EKpJ}1_0auFhYzVg|2%5Ktup! ztTjq924ihBfb_u7YJ@yafZXqY4S-ezK+-UzR3sb#vH)mD%9sClo=HI303%eS2HGDO z;Q)XlQg4FPK&JtKfB;A_8&U%u1puuUa4l$A)<1YnMQWg(08|fd+ZUb(I!Fz)1^^@x z0F(<*krHSd0OYlTnz%wxibO?fpbY^6UOAXk26p zse!fxKr#X#Hjq?K4*;eJfY`VR05>F+n`z^?o*myyw@9_W++AEN;ugQ>{qLjed< z9Y6!44;2}GNB{tpAvrW;^Z`?(s#X595^%*!;lXwN2)VB9kpQq8i6`Lk0$t?s0x{(2 zf@tLFf~rX5@&`{BygulRsO?46_>i!JsFfmWoQT@pE1O`O>*wbYEm>wDMfay`r^7IJA6Qn$N9TJ~TAp7k`W>Np$2@(u)nE&+*2^jmw1gUD6CzBK8 zFSYt0bph)sPGCKy1}v~hgBtsCZ=`?*00+*4>5&-#jssu=0$c!q6#%XRAQS<#0dNh} zq?BI(hz5cnt2DrO${hhv4S;OK2=JY9bpVJV0Ad9APWcT0WFY`z1h`H)Sm_b7X$2lQ zbZrQvB_`mE%>#%Ji6ltUp$&j90QjFm3v7s}{GVhl|8;Buu7f5nAT6Q4gg{z?ei07elF}9)vgE8=_xye_}+*EG-2UGg|~CS{K^J)`E(eK((qV zUuC2WWq5)eYEUr~C<0WK6wl<&@O4!>7LnMs zV4$n({>+F{Q2Gt%Zb<@We~+<)l9@nDpo>$~$em&9YI7{YvDX7tZTDOw3ZZlYRLpQC z0khx6FrZ>4kh^MXQL*rJ?hJQVxnofYyXk%71fLc!>(SOYFa7Crl-_qFi_vXuZbf>1 zzRBtDYk9M z_kxdH{^29Yr#P$}yOGn?M^E*RF{%0dmDZU<&OfHaH*RtDQ7gT}y2PQ7p~BCopjnVc zD`;x=vG8FUr5M#S#LnZG)tCupZ4L6%x{$auM3mmoA`4lAjV?osJlrk)&l(y%^dZny z>vV47@y=G(c9z!ob?EDb)PV@R>ZnPYbJZ&L0I80Wf%p9nSRf;L9Q9_uEY z`Z{}bKT*WhTQJHpD0w>yhL`06vGE|pO?*VbY-Djpw-M?rdBjHue*OYR7(+dX6aXE^ z$UwyNW0*6TwMS3`W)duHtcc+|GH4HM*2S!b1P?)=kG2uDPGL4eB+!P#79)*eJA|}3 zhFK}}Is_3-Phn&*X$&C_(m%YS>5jt?5l6)w!W=t{G{r%b6;e#@VdAY#kR%H#i;7&& zgIW3)tqqv-M^;ekJF>!V#u144Nt{I-Q_IlbMeIC{(SpiPKtz%*crDb}noY+8S%@ik z3@_9#3lW{qU_v1|If#f+$DD)Qz{Ul2j3Opoj?o8EAK`77x})ee@)OH*ax0vHPo5!Q z{LV6DB9GQnK@Y(O;tY`9QHV&;$7~~3YG5*;*Wf>gvlwU0eMPht<84(~1%^FFY1SzP zC`zbqHx#VEtjwxWU{q#7hZG@Vz7}R5ag!!S3Gx8{X=-8&F-FRN4WV^jJ&OM_wpoc; z=cNNS7B^<*7<277DOabHfsEv*hQx1ZcbunBo`54Nn=@`@ZUaO)u z{`#Jb3d)4xd$lSnPIQ7v_3;(beaD&3cm6mkWmR1vEeBGD^Nld22`it`2wwIZSv?v&7bCpaQn)ZwLH z#8y=m$BMDJg-k4eR&-Kqhj)KatVe%ke7mQdOG@VGpYNsb@RPH#?VfKXs&SKUSR8Fa z-S2045XQYPuDh;Bd2VfzivjuQZxQULZ!p`?u>ZmzVY%Y<#*12ODl2&6d$J_*$P2L? z8$Feryj!jh7|)n1A6m;{s)0An*0NJFDqi%OH}>3E6eqx;yftfE1-@L1s+Cn1eInB$9b==z^63zs5%aHO?!yyiYZAK%{6dHPc%fyzMHZiJgN1&GAGE1)ITovZVI+H zj>+pMC&Pua8h<$|wt{1LsX1hvSpg0`lS8Ln*&>=Nxf3> z;ET!J1!*^S20_K7c4;HZTx%vNqxF2ELS>F#kK)nPmjW1?Zeez{oDuy9M?H(uOv|7B zWlqNk_@zvE#)+rGtc6EfXDp@rtDfR_n<;JlK##A1QoV|Q1_#!#NN_RQq&}E(GK)gh zdZ1?Nam*O}xEQ%!6YJah{<+q^D^Epe5~EYDbETA~1z*?su@95eHktL5&rf?2-pl{G z0FNpRC0CP1-0DN${GrrE@mw{Q07~vCCnzht;j5la^rto}v-n<>p1Y*r^z0 zcr>#mNQ-fxoi2+UYktq+HHWBLtOVb8q};{C;t9)43XL>SN-0h5qhVz^#Ay;m6iXrw ze9?anOwh0uFA~($(kIA&wviVP!V>T(c*$rMuAXg(uK0M~N<+zGkv({qMO7-{?=F!& zVly~O42lGOiEy#P5}Qnm+nkfp{i@Oj%w2Mn5azLU!s?d?*Oi1;_}WZ$xefT>K6rkn zH2um;RIXprsqkq29<^YjuCmyk+1DJm@H=6l)~Pfh)*)ryS323-{=2!4dvk@)PSU3d z%Ah9h@Vjb!M~k^;(fe##AzSl?8SkN|+@n)9X>iAo*UcpIee>5pMdrLSA5kiNibWzS zlPU4?Q|I#}PIND_4=_4xLW&9_`DHrv%GO_Z*K-p8Mnf(xkYcZVRP$Dk*+qMl~~;mqLwq zn}TC?@+7h}y)#YTk`1+r?DH%Irc8VvlD)vCrQ}f`BuF`@tmZ@|JIQ7W3~n9zV7ErR4PB zVYEfuubQ3PVq(%>y*e~w()+C4f=h^tlZ#V`Yu7HJU7VbQzou?s7qND}+-`fLD!1k@ zwAmgp*ynJim`vDy#^}M)gj(pHx-OXB*d44fhFi3%EX$b1!|*HT?t|W~Sn>F`J4xee z)grkc3+Rm@!D8d4i&nj5mu6#d28SIE7Y`70wT%4nvuTI7v~~|IT8)&s%xb}}?7EGL z`v`q|ax3)cjq|~LW7tKj(z5VbH~0|F!F;h6d-ML={Y!&{BO2`qd9!KaTm^qjX^pzU zh7D%lwu(v+_P2umROQ(M;Suwb-oI<9@MK?d%?( zwujVfiC53fZcDroK6lBdmg@1a*e=}teO>+?MIB3hC@IG&Te-f)Lzh5mn2V{v4`Ql& z3!GD0dQZOpF*wHM^XtZh!hCKmIb%MlrF+IDuH{efykAQvhfClka`gMEXX7{MU!PGc z-hX*EW&qR6L?<%e*NK91sv1!$`TZx+u~YQVRTF!E+xEJL+P!{Jc&@;Zrz1rn=Mbgo zw{FNxzlm7of^$i9C*;`>G9g57a-0=YvMryzEATqi`z*nbbJ3vW`Da>AQvPx83tIXr z$~l(VtCCxsV!9@%#$zf+yi`gG*l0LbL9X*pH6a)oa2XDWd_zp%Tyyf8<#i`(6{c@a zgKu}1ZQrgF)&ix5sLY(rGHE=>pZ^C4?@?N^nr(z&O8 zF-5fHsfzfGEhi66-4%*qJ(MbaE?79JZ+FA}@2`aJ?f&`APjmOTz+C4{wxa%Xrt{Lb z{MaqlmhPxKeM*YI))FmckV5CTgyM{NLWzp6e76SY)PVqkqbNbL`_6KLj*$-0xqbh^uG>u~F5G$XAWd=Glhb=dbpoGVOgnn`$rqt$6)-fsbq%NoPnAAY;N+Mp@q`>Pc3;N6W8)6S2C6Hh;uG45BFegDlr zX);yTr(Xj%zgq@$-Bl^o9aU0yWNzOJyL!lcN44A+8NcAOR}U_&+9ec}_Fa>a_%Wse zsu$61WGW!0wIWA8r-f#Rj2t;qi#Zjj0UL~YVXe+TgJ2i>??LlUw^*zCB4`M`m;K;OHVpyNvR;`h#_Snmn0B zv{8-0`o8a_l((7Qsd+M9J|DtfdbB5{FV=J`^~m@{J6t69*7PVw3SQ|~T$em>I5&i+ zd$hL2(@%x+Uu;s^;%d<9z#N8)2blk9BGb;dM5`L#sCdqEREJKiD+n zz8A0C)XTTv-oQr=;L@C#Y>IMEYS^5pIUXnAI_ZCHtAqXGrwNxwgihZO`~WApIbuR< z9ox{s?*8{%7=02Mq`8TDWJ+!5HZ@qlh3I%gUbeHNT7`64-r6|RwU^N$6|`m&d|1ok zOo@83;eg^gtWQ&ujZrkN?00oA{ggbf>6g~RuTwu-Px)5OvCWu7e2=2Km_DXmhTkcZ zJ82MHxN|P5LF55pf{-NEG$)!oAg(aaJMpdQC3!UXN0W^5(|Sdp*P?+U*mZ)!4)wb zpR{YIzKH#fXKIB_ zvYRaF@}m1lZHrA%3~rBWHP&9ybrwI@^IACRyHk;Cc3v-`wd0I{0nmBqUFqWNJBQcW z)d2s#;axaXJvm}prHWsaDJl?%>-dFzJgJ-Lxv+!wYOvWxt^EL8=$icjG><5JK^y;B ze@Sn8Nr$?iJ0t;*tCn1V?Q;))>GyG>F5s+*iXJiKD{_RRBQ50XMDmrpCEq%-iHV?X zQg)W_@4@*u2PMUnO}xa%Uv>AqwmE-)NVg|yHpSHKbMky?T2$-Nv_;;&-q!@qE<2I# zZ)cL94}P{$TS7kZrxQI#xNjC2H0c$&PV(3k6;6k4Ka`v}M&_7(@WfyA;y(j{A~NiN zzkj_7dpRMJBtGlJ2yvdO_G@%Bd$n`N_uf^jK5qOH$ylILHAKS=V-4ZKMMfZEtRZ~3 zh^`?lUS!VtRW31R*zn8C|J<=2GXfz`cijQQ9+HEpGlEYdvB++#^wz-4)btE?NtJV+ z0iB%vPX_kw+oj#uBrKkK${@f>8&kV|E9d!JC!X(GE3}AZ`Q?P8)X3I6yuwGGZTGTG zwjm_u4n+ubcsRcsdfzhQUk|?~YE#RB3HoYT_ar#52y!IJk$6C!xWrLJnSq`KG0d;u4h{wH&@ zZ`guT#mHQ=0~<}RoH)lm+tF%VAyN)+T@<9*1%Mfvq5Z65PaoZq2i6ghD&8GJBc-So zeQe%v7WpXL#4mMooG^brNTRPzn)1W6^HQ_Fd!D(aVTIf*$72(-L6*k?%O4h|x1MT! z3VNPr)fO~cuUyJKEnR%E=AF4|kYs99QGT-NF(Ir@5C-c0g<;7@!goR#IxjKDi7cKmOMb7c{q7t^^|xQ z)IKxhW7$DbnwXU;5a^J8RVTv1KQa3eR;*c|AL`Okqm5l@r`DBMB%1EYji_HT?2f~^ zoHGxf)R$fOtT<$08fW=?SYrZer+9T_By2ISt)HtMPcLv@)SzD;q;z|V=fN+sX{TH? zm6YBH#5$d7&)xV=xug#6Tj-%j;F?qFgePzP?5l~4 z*>`IAKZg7jo(V%d^oQIx+F_@OnVA?T9GNgRyQ%Y+8O^uIp(M4!jfJ!muT;Ecw$FWt zUg7h$-#2HzS!L?n1m8f*T)j6wr^54zf2&Q=U@NXztKs_2Awzl<2fgK?Qobn&;GREWUo33f#g+3R;-^O#m7cQ zMkb4D>xNHxd;Sp0D);oWf`hUJhSsF z{?O7r=HIf}`fn3^W9AEMj`HRwZ9H^MIPZKCtk-rz z*u-2WyzR5@!?C0Ih6l19p%%71H$}%b{W@d8MxhEQw4FTJL54)1$8$Wb5twee?K7OY z8apoiZZ<&6y3W#D(`1uVrR0YF}$xckWTDkkb^7{U0UE>F_X}J z$WpGFgZ5P`p~upW}Hc7zrJ71Lp1X2Nm1=M(Tf?p zV197!hIahX<_v);>tm|Cjj?+VW$@Hmt7u#}y(fH$1u7v(Ge#ElBPwC_Cd>hgzoQ1a zVEn-FUn9pSL*|0*p=N{*9rfn_96D~Yp*E4BV=Z&&Fawx7%OzbO=lV-KN{W)y z?|u*E?=z5m7C3m<{zr88*}Yu6;%-mxM!$F-el;WM4%qiy0@Q#hP3YyQA3ajgtqb7@@Xfu4X2 z<)>+XYT;C@N6YwQNZZ7{rm%yk&DYB#gSQ~Jp7iLIp0KlPlhp12jrH}$Z63730y5YG zM!r&2e1snFg7Kh-V*(X(y71v%C5w(2c9q0;%6=6!ADo}bm`8tC6uCk0P_9?34jt0n zehL`P6C3p3S0C#U=W3__z_O;0Z&W#$8rDM#cva7^lW0?H_1O#TD&ghfDj5rtYozU= z)UY^?(W7HG5&df1OIQXGgo6ja5y0D}Y!orrLT*#iPI5>{Zg^g)C`O1Q7F8VS;)yq` zx7#pPC1%->bUOCej;n?pxuUf9<{lcK^nASKXd#*!AG2DiDfNdJ3R$T5`p@2R;p+m- z6Z0jn=@NMpyy#o&h9aJRI6mCBM^&>`qOAQ#I+q#TC-6pPv)$hW{BWNJy@W(Gl7md5P1qJ*bX_R3J|g}Zj%!J#;j}RxdaipWgYPRv z%6^bY+We*TvR!36?^Uk_%U|O@WB96H@-LMG+OH>`#$OSbv@dq99QtSk|8^Iei%tyk z{AFTu>$mw(14nnty&r}*oc5GAy0K5c%Fb0&z711Vz83H}a7|Ao8ryUH2-UlQd(c`6 zkB39LXG&8litley=!>3dWMgS9>D~8&GL)Bx-Bh$w(!4H6zm+ar_UkI&pA%WQ{n)ha zACsbG9wql)C+spi97WCSu-$mz`?tc?F3|xCXG^_fZDg`iU^7nI3sV7@!~OD_fu}bj zJclY^@_BFZ#SE|XoA4if>?n)Lp7PVmlB_0{)>Rtn+y1;IwcI~Z_GvCZE$UVq{3U_# z$d0crG%e`O$2@Y=*Sco~Qd;w=xqm7I6_ox=B^W#to~dt;l*+SnmFWKVF6#<`zV5=2 zo{oZnp8bp9m%>daN7Q}ZWzS8Y&*Q((qTFA+$_xH}u2y*N-Qj%fR$qem&kA1M0P1MQ z!p9BRk{`0{g}H+&)Po!7mSVD{cn{KBnrnLN4F0^g{G>hI zfBaRRe#fveD{kb`>Pi0(!`fx_^gmo#S4^jUS9>Os^7?8pWf_{{CzbsJ<{Em6m+sM~ z7vjmPy*qa+g-h3z$kTTHIazCRv^6zhlo*7E4{Ypd&Nv)d(5iW=P$h^aN;AC|Ixkv6 z=$@LKA^N0jaPJ`d9q^S@Bq!zhnU4F8Q>n&3OTKJUZFjw?sj@GRb@-0Y7Q+b7ha>!* zK}iYf9<%oQX)!ulkCIQ$@O{kE-6Add?BN3!nF^hXt#x~wUQ*? zq{8eJb{E@Ky}ci=c*`%EwV(N_F-n{&#|AAvOwv-(oD^lLAOA2HI3`(VIyU(1e8&-q zQ%SRQ!H}dAN^?G6V`o@q{CB<{{ynBxA~L*1^$a1o-mG5kb4Q6gY$vZdxAf-lNYo)u zz5W1-S?im)K<_q_{dfJzjY*2wC6A6WNdGQeUo_4-|LOH5=aSh4V}imtYO(3HzKhM; z?r?j9Wj@|`eDAC|ZLx(PpIJ!Hus0!$-k$%8QE{v$L?tJhKAxp1M{lXFiqwKjsLEYF zy+^O95GLp&y6wRW+Q||kK4O^-is{25Md0SS@@u_}Ncv~7v2e0^qhsf+GT-mSc>+u+ zux?IPp*jqE>74ZGx6sO5sH!J=KEKsHOgu}8Qr3xd`z^ob$8fBQN1+A#@P63z>w?Zb z+_=`Q!e{5+{aB**2}Eugn8<3xO17^Zeq5VMYXN7(BVbh0*Yv9eC2wPIi)>D1F{z{- z?@80Rh=)nP{B;^|-Py^dZa4NX4!|WJv56!Ok6zl1=bJrVFBVxO+4;S_ToO8!L6?u7 z_nW~|;89tZ%2PkJqLNa5sgz4HZ&>J=?|sfq{c_#C{fqhbyg+`3kioB%J@h95Ml>J& zF~PbDvbE9(R;FUc^6L6-&TTULaFy0S)Na(21lV|WdyjoQ{X<7&`&ClE>Y1-_ywQi% zj?*)7W4O~2kG=0uel4x?VCj+HV)4&mdG~)xEV*hs#EFhb1mEwBS&5o1LeIPJH4iytTp0 zZv*1z@UE;yAUUZ^FF5qFO@A`xeZ0?E{D8x6ed{CFT0LV&Dq{>EmJTO)YByt4t zhd(5AG*K<|fO6xox~GQNQ10=puHDa4k7}l{-snD5*yS(tWQ}RU$(yrXI|m<0)TIdw z_Uz()BqWi-$=h@A;iLVzk9Zym^NKfcNm~Vee;abdD%567O~FVF_HzEX(fNc(`w2_u zPvXueW!q1=O&&YoxoeeM!-gUUZl4D3nFbEJ0~V6n%ptYbe|)p5)K-ENd+GQNVJR*x zsr6~&Tg|1m_ecqBvB&tu27p_%``zzU#@->vhVZ!i4a5c#V}s@01KVPQT4O^63qN@u zC^I~8OseAwXH2Kkc5~DH%7Uw_$2qI>xsvlSS>rre`P)tNS%=2A4Q&p=|F{)C8zE); zg~Rr^obS~QZ@ReOTxIh$S8(m(aNUK0pYwT*aoqdC=JCg?k|l1KKDjyJ2ipLr+)Ivc z`*xPY_i=JR;W=%K|rG=!ziO5V1l_fMnQmt)rx`u2P?E7Al-^t5D;X8 z+W1=#u*MoC$0!I$wq9}T-Nc$%5OBvDX@i3lZmf{b11X~#W!DW<`eUV(c!OCGP{Nej z*{ob$<&2 zAT>NxAf$(}!9X1LjM9;E=mpqFwgxpMwg#9`49T9cOU6=kr7OCPEJYu3SaHI19Z+73 z6Bg&dT#9Z18;o*|t1eIhzY!(`g7RIVf@h|fYb=;vPqYbRIf>VeVT`eyq~eAyCk41M z=L8jQ==tIBgbFyWVoqY98c$}G%cv!w>30qD6l3Z8*Bm;}IO6p$ljdH`dB$U~!6-}_ z@Ir0g^MMMaEif4@kf!gyY!+j;sQ0My1`M@;oYnJ^qt@%D;Sz5v=V zs-lE%BW-ZdkCjs5ZKflZFr_a3E7~6NXF8&hKiYOfzzS& z2CQI(30%?kQvkE=0OLqdN5l~B5^J|Z{JW(dgzgRmi-0=FTc0c)@h7D`Ovhtx6ojBg%d;$BD^vp$U2uot?FF$_aF9o-H%#e^Z81Tp1dC?&CbjGkgW zmdKzqwjJ7uIT4Oh`V_f>Qf@d(X)GM2q#c1$N{c`#ts$V4t`ks7&j~0cI^&y3NiPzm z^du6c6vPWC^+ckSxbC5p+@gt=ScqRZQl5G8Hh^tM^4y)f?qn5t59PTrdIit< zdnixE`zX)E`zTM!ee~REM={Rb&VIiT->gd)lun@2{#Cb@HULXUtRg&x6~2go<` z2+|&)M=<$-aRe-^L?K~lFGeyNJqD9#^cc$G&~CMV%ji}mKG3bdqfxpBaVzMm#h`S9 zV^F$-F(_R{BHFD%@LlFRvb#HB!Rdn z0-SI2mN3Nmg!V!F7_o;arArAbC`CU+DYZUCDapm7ltSWBN`vtTl@r9X(!k*r6A+Mx z_>KqK$AO%vOS-C7SM2Pr+nOF^jKOXRD2>MnD2)v%jI+x+wu(U`1Pk$Db|<1VQXZ|K z5s`?}Xh=k9NGG8*{F6``y-8@#oJ>Z0=3X+|Grt+%%$|{bg!atcM@Y|DVM-sNY^aY= zHij8QWiikxoimK{bVUrpVw_V@Hsk3l*mR_zYy?wLHh!rnn{TNoo5N`+o9Hx@O;;Mq zMm&9m^8}@%Y<{Gp&a)nMo-G+DspA<8Qqbe4jA3-!{xytPb#~Qyq^m#_1Ha+9>MGv- z->-v`43x0q(-nmGKSl}LJVpuEJVpr%WTJ#`Wuk;TGf~0^o}h%?8Q;wAYkGnb7JiC4 zmW>E-ER&}w-SDSqAG+lrQEfYs{|L06b{DDW=vBOtVKK0|n6(Hi69&yaCQ5_97j z64$wj?~gznkV(!8#)Hp@V@Du;%*ia|n?LHQ%r2s&EW}ETl!dlpBD0A0q7cvhLt<=? z;^GEyoms?jSx6Iu%On%h#g~^OB`2(1h*^?7-yMLVby)6Kyb}<&~nwPv&$OgOaU6p zR|saA0yLto5QycW`&f=^e@&S%1!%BX(c&IcfL^jI1Z7MCdJ(M<%rFJ0Kd%so=A%1b z_NBi&H)aa#F-Xb=S}Y$>BvXK%(G`MHrXYVCv&Hg}PXBw0Wx@XE=+5&uFv;4%a(-=*laDbS94BGrZ0HJ7ErT_o{ diff --git a/editor/assets/primitives.fbx.meta b/editor/assets/primitives.fbx.meta index d749817046b..ea556cdb69f 100644 --- a/editor/assets/primitives.fbx.meta +++ b/editor/assets/primitives.fbx.meta @@ -19,8 +19,8 @@ ], "subMetas": {}, "userData": { - "gltfIndex": 4, - "triangleCount": 2380 + "gltfIndex": 5, + "triangleCount": 1512 } }, "801ec": { @@ -59,12 +59,12 @@ "triangleCount": 200 } }, - "38fd2": { + "40ece": { "importer": "gltf-mesh", - "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@38fd2", + "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@40ece", "displayName": "", - "id": "38fd2", - "name": "cone.mesh", + "id": "40ece", + "name": "torus.mesh", "ver": "1.1.1", "imported": true, "files": [ @@ -74,15 +74,15 @@ "subMetas": {}, "userData": { "gltfIndex": 2, - "triangleCount": 72 + "triangleCount": 2048 } }, - "40ece": { + "fc873": { "importer": "gltf-mesh", - "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@40ece", + "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@fc873", "displayName": "", - "id": "40ece", - "name": "torus.mesh", + "id": "fc873", + "name": "quad.mesh", "ver": "1.1.1", "imported": true, "files": [ @@ -92,15 +92,15 @@ "subMetas": {}, "userData": { "gltfIndex": 3, - "triangleCount": 2048 + "triangleCount": 2 } }, - "fc873": { + "a804a": { "importer": "gltf-mesh", - "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@fc873", + "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@a804a", "displayName": "", - "id": "fc873", - "name": "quad.mesh", + "id": "a804a", + "name": "box.mesh", "ver": "1.1.1", "imported": true, "files": [ @@ -109,8 +109,8 @@ ], "subMetas": {}, "userData": { - "gltfIndex": 5, - "triangleCount": 2 + "gltfIndex": 4, + "triangleCount": 12 } }, "8abdc": { @@ -128,15 +128,15 @@ "subMetas": {}, "userData": { "gltfIndex": 6, - "triangleCount": 128 + "triangleCount": 112 } }, - "a804a": { + "38fd2": { "importer": "gltf-mesh", - "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@a804a", + "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@38fd2", "displayName": "", - "id": "a804a", - "name": "box.mesh", + "id": "38fd2", + "name": "cone.mesh", "ver": "1.1.1", "imported": true, "files": [ @@ -146,9 +146,25 @@ "subMetas": {}, "userData": { "gltfIndex": 7, - "triangleCount": 12 + "triangleCount": 64 } }, + "7a3ca": { + "importer": "gltf-material", + "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@7a3ca", + "displayName": "", + "id": "7a3ca", + "name": "lambert2.material", + "userData": { + "gltfIndex": 0 + }, + "ver": "1.0.14", + "imported": true, + "files": [ + ".json" + ], + "subMetas": {} + }, "8d883": { "importer": "gltf-material", "uuid": "1263d74c-8167-4928-91a6-4e2672411f47@8d883", @@ -156,7 +172,7 @@ "id": "8d883", "name": "lambert1.material", "userData": { - "gltfIndex": 0 + "gltfIndex": 1 }, "ver": "1.0.14", "imported": true, @@ -203,14 +219,15 @@ "meshes": [ "1263d74c-8167-4928-91a6-4e2672411f47@801ec", "1263d74c-8167-4928-91a6-4e2672411f47@2e76e", - "1263d74c-8167-4928-91a6-4e2672411f47@38fd2", "1263d74c-8167-4928-91a6-4e2672411f47@40ece", - "1263d74c-8167-4928-91a6-4e2672411f47@17020", "1263d74c-8167-4928-91a6-4e2672411f47@fc873", + "1263d74c-8167-4928-91a6-4e2672411f47@a804a", + "1263d74c-8167-4928-91a6-4e2672411f47@17020", "1263d74c-8167-4928-91a6-4e2672411f47@8abdc", - "1263d74c-8167-4928-91a6-4e2672411f47@a804a" + "1263d74c-8167-4928-91a6-4e2672411f47@38fd2" ], "materials": [ + "1263d74c-8167-4928-91a6-4e2672411f47@7a3ca", "1263d74c-8167-4928-91a6-4e2672411f47@8d883" ], "scenes": [ From 1dc3142fbbb4ee93421e3fc2754366c0abcd3517 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Thu, 17 Aug 2023 17:34:04 +0800 Subject: [PATCH 176/232] [opt] when move() is called, character controller sync physics position to scene; change default stepOffset; set minimum skinWidth (#15966) * [opt] [character controller] when move() is called, character controller sync physics position to scene immediately; change default stepOffset from 1.0 to 0.5; set minimum skinWidth 0.001 * tweak * native * eslint * eslint * eslint --- cocos/physics/bullet/bullet-world.ts | 107 ++++++++++++------ .../bullet-character-controller.ts | 30 +++-- .../character-controller.ts | 15 ++- cocos/physics/framework/physics-selector.ts | 2 + cocos/physics/physx/physx-world.ts | 8 +- cocos/physics/spec/i-character-controller.ts | 1 + native/cocos/physics/physx/PhysXWorld.cpp | 3 - .../PhysXCharacterController.h | 2 +- .../cocos/physics/sdk/CharacterController.cpp | 4 + .../cocos/physics/sdk/CharacterController.h | 1 + .../cocos/physics/spec/ICharacterController.h | 1 + platforms/native/engine/jsb-physics.js | 1 + 12 files changed, 117 insertions(+), 58 deletions(-) diff --git a/cocos/physics/bullet/bullet-world.ts b/cocos/physics/bullet/bullet-world.ts index aa4514d28aa..298b1683329 100644 --- a/cocos/physics/bullet/bullet-world.ts +++ b/cocos/physics/bullet/bullet-world.ts @@ -45,7 +45,9 @@ const v3_1 = CC_V3_1; const v3_2 = CC_V3_2; const emitHit = new CharacterControllerContact(); export class BulletWorld implements IPhysicsWorld { - setDefaultMaterial (v: PhysicsMaterial): void { } + setDefaultMaterial (v: PhysicsMaterial): void { + //empty + } setAllowSleep (v: boolean): void { bt.ccDiscreteDynamicsWorld_setAllowSleep(this._world, v); @@ -128,9 +130,9 @@ export class BulletWorld implements IPhysicsWorld { readonly oldContactsDic = new TupleDictionary(); readonly cctShapeEventDic = new TupleDictionary(); - private static _sweepBoxGeometry: any; - private static _sweepSphereGeometry: any; - private static _sweepCapsuleGeometry: any; + private static _sweepBoxGeometry: number; + private static _sweepSphereGeometry: number; + private static _sweepCapsuleGeometry: number; constructor () { this._broadphase = bt.DbvtBroadphase_new(); @@ -159,15 +161,9 @@ export class BulletWorld implements IPhysicsWorld { } step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep = 0): void { - if (!this.bodies.length && !this.ghosts.length && !this.ccts.length) return; + if (!this.bodies.length && !this.ghosts.length) return; if (timeSinceLastCalled === undefined) timeSinceLastCalled = deltaTime; bt.DynamicsWorld_stepSimulation(this._world, timeSinceLastCalled, maxSubStep, deltaTime); - - const ccts = this.ccts; - const length = ccts.length; - for (let i = 0; i < length; i++) { - ccts[i].syncPhysicsToScene(); - } } syncSceneToPhysics (): void { @@ -240,8 +236,14 @@ export class BulletWorld implements IPhysicsWorld { return false; } - sweepBox (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweepBox ( + worldRay: geometry.Ray, + halfExtent: IVec3Like, + orientation: IQuatLike, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { // cast shape const hf = BulletCache.instance.BT_V3_0; cocos2BulletVec3(hf, halfExtent); @@ -253,8 +255,13 @@ export class BulletWorld implements IPhysicsWorld { return this.sweep(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, pool, results); } - sweepBoxClosest (worldRay: geometry.Ray, halfExtent: IVec3Like, orientation: IQuatLike, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepBoxClosest ( + worldRay: geometry.Ray, + halfExtent: IVec3Like, + orientation: IQuatLike, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { // cast shape const hf = BulletCache.instance.BT_V3_0; cocos2BulletVec3(hf, halfExtent); @@ -266,8 +273,13 @@ export class BulletWorld implements IPhysicsWorld { return this.sweepClosest(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, result); } - sweepSphere (worldRay: geometry.Ray, radius: number, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweepSphere ( + worldRay: geometry.Ray, + radius: number, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { // cast shape if (!BulletWorld._sweepSphereGeometry) { BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius); @@ -276,8 +288,12 @@ export class BulletWorld implements IPhysicsWorld { return this.sweep(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, pool, results); } - sweepSphereClosest (worldRay: geometry.Ray, radius: number, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepSphereClosest ( + worldRay: geometry.Ray, + radius: number, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { // cast shape if (!BulletWorld._sweepSphereGeometry) { BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius); @@ -287,8 +303,15 @@ export class BulletWorld implements IPhysicsWorld { return this.sweepClosest(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, result); } - sweepCapsule (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweepCapsule ( + worldRay: geometry.Ray, + radius: number, + height: number, + orientation: IQuatLike, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { // cast shape if (!BulletWorld._sweepCapsuleGeometry) { BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height); @@ -297,8 +320,14 @@ export class BulletWorld implements IPhysicsWorld { return this.sweep(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, pool, results); } - sweepCapsuleClosest (worldRay: geometry.Ray, radius: number, height: number, orientation: IQuatLike, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepCapsuleClosest ( + worldRay: geometry.Ray, + radius: number, + height: number, + orientation: IQuatLike, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { // cast shape if (!BulletWorld._sweepCapsuleGeometry) { BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height); @@ -308,8 +337,14 @@ export class BulletWorld implements IPhysicsWorld { return this.sweepClosest(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, result); } - sweep (worldRay: geometry.Ray, btShapePtr: any, orientation: IQuatLike, - options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean { + sweep ( + worldRay: geometry.Ray, + btShapePtr: number, + orientation: IQuatLike, + options: IRaycastOptions, + pool: RecyclePool, + results: PhysicsRayResult[], + ): boolean { const BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0; const BT_toTransform = BulletCache.instance.BT_TRANSFORM_1; const BT_orientation = BulletCache.instance.BT_QUAT_0; @@ -344,8 +379,13 @@ export class BulletWorld implements IPhysicsWorld { return false; } - sweepClosest (worldRay: geometry.Ray, btShapePtr: any, orientation: IQuatLike, - options: IRaycastOptions, result: PhysicsRayResult): boolean { + sweepClosest ( + worldRay: geometry.Ray, + btShapePtr: number, + orientation: IQuatLike, + options: IRaycastOptions, + result: PhysicsRayResult, + ): boolean { const BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0; const BT_toTransform = BulletCache.instance.BT_TRANSFORM_1; const BT_orientation = BulletCache.instance.BT_QUAT_0; @@ -588,9 +628,9 @@ export class BulletWorld implements IPhysicsWorld { const data = this.cctShapeEventDic.getDataByKey(key); const cct: BulletCharacterController = data.BulletCharacterController; const shape: BulletShape = data.BulletShape; - const worldPos = data.worldPos; - const worldNormal = data.worldNormal; - const motionDir = data.motionDir; + const worldPos = data.worldPos as IVec3Like; + const worldNormal = data.worldNormal as IVec3Like; + const motionDir = data.motionDir as IVec3Like; const motionLength = data.motionLength; emitHit.controller = cct.characterController; emitHit.collider = shape.collider; @@ -623,8 +663,11 @@ export class BulletWorld implements IPhysicsWorld { // current contact let item = this.contactsDic.get(shape0.id, shape1.id); if (!item) { - item = this.contactsDic.set(shape0.id, shape1.id, - { shape0, shape1, contacts: [], impl: manifold }); + item = this.contactsDic.set( + shape0.id, + shape1.id, + { shape0, shape1, contacts: [], impl: manifold }, + ); } item.contacts.push(manifoldPoint);//btManifoldPoint } diff --git a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts index 19135648145..4d6ed88d53b 100644 --- a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts +++ b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts @@ -41,7 +41,7 @@ const v3_2 = new Vec3(0, 0, 0); export abstract class BulletCharacterController implements IBaseCharacterController { readonly wrappedWorld: BulletWorld; private _isEnabled = false; - protected _impl: any = null; //btCapsuleCharacterController + protected _impl: number = 0; //btCapsuleCharacterController protected _comp: CharacterController = null as any; private _btCollisionFlags = 0;//: btControllerCollisionFlag protected _word3 = 0; @@ -50,8 +50,7 @@ export abstract class BulletCharacterController implements IBaseCharacterControl private _collisionFilterMask = -1; get isEnabled (): boolean { return this._isEnabled; } - get impl (): any { - /* eslint-disable @typescript-eslint/no-unsafe-return */ + get impl (): number { return this._impl; } get characterController (): CharacterController { return this._comp; } @@ -61,8 +60,12 @@ export abstract class BulletCharacterController implements IBaseCharacterControl } // virtual - protected onComponentSet (): void { } - protected updateScale (): void { } + protected onComponentSet (): void { + //empty + } + protected updateScale (): void { + //empty + } initialize (comp: CharacterController): boolean { this._comp = comp; @@ -73,7 +76,7 @@ export abstract class BulletCharacterController implements IBaseCharacterControl this.onComponentSet(); - if (this._impl == null) { + if (this._impl === 0) { error('[Physics]: Initialize BulletCharacterController failed'); return false; } else { @@ -106,22 +109,22 @@ export abstract class BulletCharacterController implements IBaseCharacterControl //(this._comp as any) = null; bt._safe_delete(this._impl, EBulletType.EBulletTypeCharacterController); BulletCache.delWrapper(this._impl, bt.CCT_CACHE_NAME); - this._impl = null; + this._impl = 0; //(this.wrappedWorld as any) = null; } onLoad (): void { - + //empty } getPosition (out: IVec3Like): void { if (!this._impl) return; - bullet2CocosVec3(out, bt.CharacterController_getPosition(this.impl)); + bullet2CocosVec3(out, bt.CharacterController_getPosition(this.impl) as number); } setPosition (value: IVec3Like): void { if (!this._impl) return; - cocos2BulletVec3(bt.CharacterController_getPosition(this.impl), value); + cocos2BulletVec3(bt.CharacterController_getPosition(this.impl) as number, value); this.syncPhysicsToScene(); } @@ -257,8 +260,11 @@ export abstract class BulletCharacterController implements IBaseCharacterControl const motionLength = bt.ControllerHit_getHitMotionLength(hit); const s: BulletShape = BulletCache.getWrapper(shapePtr, BulletShape.TYPE); if (s) { - item = bulletWorld.cctShapeEventDic.set(this.impl, shapePtr, - { BulletCharacterController: this, BulletShape: s, worldPos, worldNormal, motionDir, motionLength }); + item = bulletWorld.cctShapeEventDic.set( + this.impl, + shapePtr, + { BulletCharacterController: this, BulletShape: s, worldPos, worldNormal, motionDir, motionLength }, + ); } } } diff --git a/cocos/physics/framework/components/character-controllers/character-controller.ts b/cocos/physics/framework/components/character-controllers/character-controller.ts index f61d683babf..73fa1e0df99 100644 --- a/cocos/physics/framework/components/character-controllers/character-controller.ts +++ b/cocos/physics/framework/components/character-controllers/character-controller.ts @@ -145,7 +145,7 @@ export class CharacterController extends Eventify(Component) { if (this._skinWidth === value) return; this._skinWidth = Math.abs(value); if (this._cct) { - this._cct.setContactOffset(value); + this._cct.setContactOffset(Math.max(0.0001, value)); } } @@ -232,11 +232,11 @@ export class CharacterController extends Eventify(Component) { @serializable private _minMoveDistance = 0.001; //[ 0, infinity ] @serializable - private _stepOffset = 1.0; + private _stepOffset = 0.5; @serializable private _slopeLimit = 45.0; //degree[ 0, 180] @serializable - private _skinWidth = 0.01; + private _skinWidth = 0.01; //[ 0.0001, infinity ] // @serializable // private _detectCollisions = true; // @serializable @@ -307,8 +307,11 @@ export class CharacterController extends Eventify(Component) { /** * @en * Sets world position of center. + * Note: Calling this function will immediately synchronize the position of + * the character controller in the physics world to the node. * @zh * 设置中心的世界坐标。 + * 注意:调用该函数会立刻将角色控制器在物理世界中的位置同步到节点上。 */ public set centerWorldPosition (value: Readonly) { if (this._isInitialized) this._cct!.setPosition(value); @@ -317,8 +320,10 @@ export class CharacterController extends Eventify(Component) { /** * @en * Gets the velocity. + * Note: velocity is only updated after move() is called. * @zh * 获取速度。 + * 注意:velocity 只会在 move() 调用后更新。 */ public get velocity (): Readonly { return this._velocity; @@ -327,8 +332,10 @@ export class CharacterController extends Eventify(Component) { /** * @en * Gets whether the character is on the ground. + * Note: isGrounded is only updated after move() is called. * @zh * 获取是否在地面上。 + * 注意:isGrounded 只会在 move() 调用后更新。 */ public get isGrounded (): boolean { return this._cct!.onGround(); @@ -351,6 +358,8 @@ export class CharacterController extends Eventify(Component) { this._currentPos.set(this.centerWorldPosition); this._velocity = this._currentPos.subtract(this._prevPos).multiplyScalar(1.0 / elapsedTime); + + this._cct!.syncPhysicsToScene(); } /// EVENT INTERFACE /// diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 4cd1131ce66..306613dc6dc 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -39,6 +39,7 @@ import { errorID, IVec3Like, warn, cclegacy } from '../../core'; import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum'; import { PhysicsMaterial } from '.'; +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents export type IPhysicsEngineId = 'builtin' | 'cannon.js' | 'bullet' | 'physx' | string; interface IPhysicsWrapperObject { @@ -524,6 +525,7 @@ const ENTIRE_CHARACTER_CONTROLLER: IEntireCharacterController = { addMask: FUNC, removeMask: FUNC, move: FUNC, + syncPhysicsToScene: FUNC, updateEventListener: FUNC, //IBoxCharacterController setHalfHeight: FUNC, diff --git a/cocos/physics/physx/physx-world.ts b/cocos/physics/physx/physx-world.ts index 0916c8b32de..d0ee6c1185a 100644 --- a/cocos/physics/physx/physx-world.ts +++ b/cocos/physics/physx/physx-world.ts @@ -76,7 +76,7 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { } step (deltaTime: number, _timeSinceLastCalled?: number, _maxSubStep = 0): void { - if (this.wrappedBodies.length === 0 && this.ccts.length === 0) return; + if (this.wrappedBodies.length === 0) return; this._simulate(deltaTime); if (!PX.MULTI_THREAD) { this._fetchResults(); @@ -84,12 +84,6 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { const body = this.wrappedBodies[i]; body.syncPhysicsToScene(); } - const ccts = this.ccts; - const length = ccts.length; - for (let i = 0; i < length; i++) { - const cct = ccts[i]; - cct.syncPhysicsToScene(); - } } } diff --git a/cocos/physics/spec/i-character-controller.ts b/cocos/physics/spec/i-character-controller.ts index 6617e58f0fb..5faa80e14a7 100644 --- a/cocos/physics/spec/i-character-controller.ts +++ b/cocos/physics/spec/i-character-controller.ts @@ -40,6 +40,7 @@ export interface IBaseCharacterController extends ILifecycle, IGroupMask { setDetectCollisions (value: boolean): void; setOverlapRecovery (value: boolean): void; move(movement: IVec3Like, minDist: number, elapsedTime: number): void; + syncPhysicsToScene (): void; } export interface ICapsuleCharacterController extends IBaseCharacterController { diff --git a/native/cocos/physics/physx/PhysXWorld.cpp b/native/cocos/physics/physx/PhysXWorld.cpp index 3adedea71f0..96f0d4084f7 100644 --- a/native/cocos/physics/physx/PhysXWorld.cpp +++ b/native/cocos/physics/physx/PhysXWorld.cpp @@ -240,9 +240,6 @@ void PhysXWorld::syncPhysicsToScene() { for (auto const &sb : _mSharedBodies) { sb->syncPhysicsToScene(); } - for (auto const &cct : _mCCTs) { - cct->syncPhysicsToScene(); - } } void PhysXWorld::syncSceneWithCheck() { diff --git a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h index 4aba1bbe3f1..5ec9197a655 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h +++ b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h @@ -56,7 +56,7 @@ class PhysXCharacterController : virtual public IBaseCharacterController { void syncScale(); void syncSceneToPhysics(); - void syncPhysicsToScene(); + virtual void syncPhysicsToScene() override; //ILifecycle void onEnable() override; diff --git a/native/cocos/physics/sdk/CharacterController.cpp b/native/cocos/physics/sdk/CharacterController.cpp index 1bd9a5569f2..fc53ac4a0fc 100644 --- a/native/cocos/physics/sdk/CharacterController.cpp +++ b/native/cocos/physics/sdk/CharacterController.cpp @@ -68,6 +68,10 @@ void CLASS::move(float x, float y, float z, float minDist, float elapsedTime) { _impl->move(x, y, z, minDist, elapsedTime); \ } \ \ +void CLASS::syncPhysicsToScene() { \ + _impl->syncPhysicsToScene(); \ +} \ + \ void CLASS::setStepOffset(float v) { \ _impl->setStepOffset(v); \ } \ diff --git a/native/cocos/physics/sdk/CharacterController.h b/native/cocos/physics/sdk/CharacterController.h index 90966630923..e87e34dc66d 100644 --- a/native/cocos/physics/sdk/CharacterController.h +++ b/native/cocos/physics/sdk/CharacterController.h @@ -47,6 +47,7 @@ virtual bool onGround() override; \ virtual void move(float x, float y, float z, float minDist, \ float elapsedTime) override; \ + void syncPhysicsToScene() override; \ virtual void setStepOffset(float v) override; \ virtual float getStepOffset() override; \ virtual void setSlopeLimit(float v) override; \ diff --git a/native/cocos/physics/spec/ICharacterController.h b/native/cocos/physics/spec/ICharacterController.h index 1e56bda9b81..26adcfbdbbc 100644 --- a/native/cocos/physics/spec/ICharacterController.h +++ b/native/cocos/physics/spec/ICharacterController.h @@ -51,6 +51,7 @@ class IBaseCharacterController : virtual public ILifecycle { virtual void setPosition(float x, float y, float z) = 0; virtual bool onGround() = 0; virtual void move(float x, float y, float z, float minDist, float elapsedTime) = 0; + virtual void syncPhysicsToScene() = 0; virtual uint32_t getGroup() = 0; virtual void setGroup(uint32_t g) = 0; diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index fe950775748..49973ef4c94 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -929,6 +929,7 @@ class CharacterController { onGround () { return this._impl.onGround(); } move (v, minDist, dt) { return this._impl.move(v.x, v.y, v.z, minDist, dt); } + syncPhysicsToScene () { this._impl.syncPhysicsToScene(); } setPosition (v) { this._impl.setPosition(v.x, v.y, v.z); } getPosition () { return this._impl.getPosition(); } From 56e00bac7fa968c15b50d3b0bfb93fe9b0ac9aa3 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Thu, 17 Aug 2023 19:05:02 +0800 Subject: [PATCH 177/232] optimize shader code size, remove unused space (#16011) --- .../chunks/builtin/functionalities/sh.chunk | 2 +- .../builtin/functionalities/shadow-map.chunk | 52 +++++------ .../builtin/uniforms/cc-forward-light.chunk | 2 +- .../common/debug/debug-view-define.chunk | 2 +- .../chunks/common/lighting/attenuation.chunk | 2 +- .../assets/chunks/common/lighting/bxdf.chunk | 2 +- .../chunks/common/lighting/functions.chunk | 6 +- .../assets/chunks/common/math/transform.chunk | 10 +-- .../assets/chunks/common/mesh/material.chunk | 6 +- .../chunks/common/mesh/vat-animation.chunk | 8 +- .../chunks/common/shadow/native-pcf.chunk | 10 +-- editor/assets/chunks/legacy/decode-base.chunk | 4 +- .../legacy/main-functions/outline-vs.chunk | 2 +- .../chunks/legacy/output-standard.chunk | 2 +- .../chunks/legacy/shading-standard-base.chunk | 12 +-- .../assets/chunks/legacy/shading-toon.chunk | 4 +- .../lighting-intermediate-data.chunk | 6 +- .../lighting-flow/common-flow.chunk | 2 +- .../model-functions/standard-common.chunk | 4 +- .../model-functions/standard.chunk | 6 +- .../assets/chunks/post-process/fxaa-hq.chunk | 70 +++++++-------- .../data-structures/vs-intermediate.chunk | 2 +- .../main-functions/misc/sky-fs.chunk | 2 +- .../render-planar-shadow/vs.chunk | 2 +- .../render-to-reflectmap/fs.chunk | 18 ++-- .../main-functions/render-to-scene/fs.chunk | 2 +- .../render-to-scene/pipeline/forward-fs.chunk | 8 +- .../main-functions/render-to-scene/vs.chunk | 2 +- .../render-to-shadowmap/vs.chunk | 2 +- .../surfaces/data-structures/standard.chunk | 4 +- .../surfaces/data-structures/toon.chunk | 2 +- .../surfaces/module-functions/common-vs.chunk | 2 +- .../module-functions/debug-view.chunk | 44 ++++----- .../module-functions/standard-fs.chunk | 6 +- .../surfaces/module-functions/toon-fs.chunk | 4 +- .../surfaces/module-functions/unlit-fs.chunk | 2 +- .../assets/effects/advanced/car-paint.effect | 2 +- .../effects/advanced/common-functions.chunk | 4 +- editor/assets/effects/advanced/eye.chunk | 8 +- editor/assets/effects/advanced/glass.effect | 2 +- editor/assets/effects/advanced/hair.effect | 8 +- .../effects/internal/builtin-wireframe.effect | 4 +- .../internal/editor/box-height-light.effect | 4 +- .../editor/light-probe-visualization.effect | 2 +- .../effects/pipeline/cluster-build.effect | 4 +- .../effects/pipeline/deferred-lighting.effect | 2 +- .../pipeline/post-process/blit-screen.effect | 8 +- .../pipeline/post-process/chunks/fsr.chunk | 6 +- .../pipeline/post-process/chunks/hbao.chunk | 8 +- .../pipeline/post-process/chunks/vs.chunk | 2 +- .../post-process/color-grading.effect | 4 +- .../effects/pipeline/post-process/fsr.effect | 6 +- .../pipeline/post-process/fxaa-hq.effect | 2 +- .../effects/pipeline/post-process/hbao.effect | 8 +- .../effects/pipeline/post-process/taa.effect | 90 +++++++++---------- .../assets/effects/pipeline/ssss-blur.effect | 2 +- .../assets/effects/util/splash-screen.effect | 4 +- 57 files changed, 248 insertions(+), 248 deletions(-) diff --git a/editor/assets/chunks/builtin/functionalities/sh.chunk b/editor/assets/chunks/builtin/functionalities/sh.chunk index 7430c4939f4..a7782e7d4c8 100644 --- a/editor/assets/chunks/builtin/functionalities/sh.chunk +++ b/editor/assets/chunks/builtin/functionalities/sh.chunk @@ -3,7 +3,7 @@ #if CC_USE_LIGHT_PROBE vec3 SHEvaluate(vec3 normal) { - vec3 result; + vec3 result; #if USE_INSTANCING // calculate linear and const terms diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk index bb744306603..8d77ed8b1bd 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk @@ -34,7 +34,7 @@ float CCGetLinearDepth(vec3 worldPos) { #include #include - + //////////////////////////////////////////////////////////Helper Functions bool GetShadowNDCPos(out vec3 shadowNDCPos, vec4 shadowPosWithDepthBias) @@ -58,9 +58,9 @@ float CCGetLinearDepth(vec3 worldPos) { if (viewNormal.z < 0.1) newShadowPos.xy += viewNormal.xy * projScaleXY * normalBias * clamp(viewNormal.z, 0.001, 0.1); } - return newShadowPos; + return newShadowPos; } - + vec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias, mat4 matLightView, vec2 projScaleXY) { vec4 newShadowPos = shadowPos; @@ -72,7 +72,7 @@ float CCGetLinearDepth(vec3 worldPos) { } return newShadowPos; } - + float GetViewSpaceDepthFromNDCDepth_Orthgraphic(float NDCDepth, float projScaleZ, float projBiasZ) { return (NDCDepth - projBiasZ) / projScaleZ; @@ -88,36 +88,36 @@ float CCGetLinearDepth(vec3 worldPos) { vec3 viewSpacePos; viewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw; viewSpacePos.z = GetViewSpaceDepthFromNDCDepth_Perspective(shadowPos.z, shadowPos.w, cc_shadowInvProjDepthInfo.x, cc_shadowInvProjDepthInfo.y); - + // Apply bias viewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias; - + // Reconstuct clipspace: cc_matLightProj * viewSpacePos vec4 clipSpacePos; clipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy; clipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0); - + // enabled linear depth? #if CC_SHADOWMAP_USE_LINEAR_DEPTH clipSpacePos.z = GetLinearDepthFromViewSpace(viewSpacePos.xyz, cc_shadowNFLSInfo.x, cc_shadowNFLSInfo.y); clipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w; #endif - + return clipSpacePos; } - + // (projScaleZ, projBiasZ) = cc_shadowProjDepthInfo.xy vec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias, float projScaleZ, float projBiasZ) { float coeffA = projScaleZ; float coeffB = projBiasZ; - + // Recover the Z distance in view space: float viewSpacePos_z = GetViewSpaceDepthFromNDCDepth_Orthgraphic(shadowPos.z, projScaleZ, projBiasZ); - + // Apply bias viewSpacePos_z += viewspaceDepthBias; - + // Reconstuct clipspace vec4 result = shadowPos; result.z = viewSpacePos_z * coeffA + coeffB; @@ -140,7 +140,7 @@ float CCGetLinearDepth(vec3 worldPos) { } return NativePCFShadowFactorHard(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); } - + float CCGetDirLightShadowFactorSoft (vec4 shadowPosWithDepthBias) { vec3 shadowNDCPos; if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { @@ -148,7 +148,7 @@ float CCGetLinearDepth(vec3 worldPos) { } return NativePCFShadowFactorSoft(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); } - + float CCGetDirLightShadowFactorSoft3X (vec4 shadowPosWithDepthBias) { vec3 shadowNDCPos; if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { @@ -156,7 +156,7 @@ float CCGetLinearDepth(vec3 worldPos) { } return NativePCFShadowFactorSoft3X(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); } - + float CCGetDirLightShadowFactorSoft5X (vec4 shadowPosWithDepthBias) { vec3 shadowNDCPos; if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { @@ -164,8 +164,8 @@ float CCGetLinearDepth(vec3 worldPos) { } return NativePCFShadowFactorSoft5X(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); } - - + + //////////////////////////////////////////////////////////Spot Light Shadow float CCGetSpotLightShadowFactorHard (vec4 shadowPosWithDepthBias, vec3 worldPos) { vec3 shadowNDCPos; @@ -174,7 +174,7 @@ float CCGetLinearDepth(vec3 worldPos) { } return NativePCFShadowFactorHard(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy); } - + float CCGetSpotLightShadowFactorSoft (vec4 shadowPosWithDepthBias, vec3 worldPos) { vec3 shadowNDCPos; if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { @@ -182,7 +182,7 @@ float CCGetLinearDepth(vec3 worldPos) { } return NativePCFShadowFactorSoft(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy); } - + float CCGetSpotLightShadowFactorSoft3X (vec4 shadowPosWithDepthBias, vec3 worldPos) { vec3 shadowNDCPos; if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { @@ -190,7 +190,7 @@ float CCGetLinearDepth(vec3 worldPos) { } return NativePCFShadowFactorSoft3X(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy); } - + float CCGetSpotLightShadowFactorSoft5X (vec4 shadowPosWithDepthBias, vec3 worldPos) { vec3 shadowNDCPos; if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { @@ -216,21 +216,21 @@ float CCGetLinearDepth(vec3 worldPos) { realtimeShadow = CCGetSpotLightShadowFactorSoft5X(pos, worldPos); }else if (pcf > 1.9) { realtimeShadow = CCGetSpotLightShadowFactorSoft3X(pos, worldPos); - }else if (pcf > 0.9) { + }else if (pcf > 0.9) { realtimeShadow = CCGetSpotLightShadowFactorSoft(pos, worldPos); - }else { + }else { realtimeShadow = CCGetSpotLightShadowFactorHard(pos, worldPos); } shadowPosWithDepthBias = pos; return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); } - + float CCShadowFactorBase(out vec4 shadowPosWithDepthBias, vec4 shadowPos, vec3 N, vec2 shadowBias) { vec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y, cc_matLightView, cc_shadowProjInfo.xy); pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, cc_shadowProjDepthInfo.x, cc_shadowProjDepthInfo.y); - + float realtimeShadow = 1.0; #if CC_DIR_SHADOW_PCF_TYPE == CC_SHADOW_PCF_SOFT_5X realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); @@ -242,13 +242,13 @@ float CCGetLinearDepth(vec3 worldPos) { realtimeShadow = CCGetDirLightShadowFactorSoft(pos); #endif #if CC_DIR_SHADOW_PCF_TYPE == CC_SHADOW_PCF_HARD - realtimeShadow = CCGetDirLightShadowFactorHard(pos); + realtimeShadow = CCGetDirLightShadowFactorHard(pos); #endif shadowPosWithDepthBias = pos; return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); } - + #if CC_SUPPORT_CASCADED_SHADOW_MAP bool CCGetCSMLevelWithTransition(out highp float ratio, vec3 clipPos) { highp float maxRange = 1.0 - cc_csmSplitsInfo.x; diff --git a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk index 589ca4958f5..fe794dcfbf4 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk @@ -14,5 +14,5 @@ layout(set = 2, binding = 1) uniform CCForwardLight { vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS]; // x: size, y: range, z: cos(half outterAngle), w: enable shadow; ranged dir light: xyz is right vec4 cc_lightDir[LIGHTS_PER_PASS]; // xyz: dir, w: unused vec4 cc_lightBoundingSizeVS[LIGHTS_PER_PASS]; //xyz: ranged dir light node half scale -}; +}; #endif diff --git a/editor/assets/chunks/common/debug/debug-view-define.chunk b/editor/assets/chunks/common/debug/debug-view-define.chunk index c738cdaeb5c..1cb6feffbed 100644 --- a/editor/assets/chunks/common/debug/debug-view-define.chunk +++ b/editor/assets/chunks/common/debug/debug-view-define.chunk @@ -80,7 +80,7 @@ bool equalf_mode(float data1, float data2) { return abs(float(data1) - float(dat // these mode shows non-lighting data, need ignore tone mapping and gamma correction bool DebugViewNeedDisplayOriginalData() { - return + return IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_NORMAL) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_TANGENT) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_BINORMAL) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSPARENCY) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_BASE_COLOR) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIFFUSE_COLOR) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SPECULAR_COLOR) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ROUGHNESS) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_METALLIC) || diff --git a/editor/assets/chunks/common/lighting/attenuation.chunk b/editor/assets/chunks/common/lighting/attenuation.chunk index 44266dc576f..86ab9c10177 100644 --- a/editor/assets/chunks/common/lighting/attenuation.chunk +++ b/editor/assets/chunks/common/lighting/attenuation.chunk @@ -43,7 +43,7 @@ float CalculateDistanceAttenuation(float distToLightSqr, float lightRadius, floa // physical attenuation float attRadiusSqrInv = 1.0 / max(lightRange, 0.01); attRadiusSqrInv *= attRadiusSqrInv; - + // artical soft edge fading float litRadiusSqr = lightRadius * lightRadius; float edgeAttenuation = (IS_POINT_LIGHT(lightType) || IS_RANGED_DIRECTIONAL_LIGHT(lightType)) ? 1.0 : litRadiusSqr / max(litRadiusSqr, distToLightSqr); diff --git a/editor/assets/chunks/common/lighting/bxdf.chunk b/editor/assets/chunks/common/lighting/bxdf.chunk index ba06af07417..478b535caf6 100644 --- a/editor/assets/chunks/common/lighting/bxdf.chunk +++ b/editor/assets/chunks/common/lighting/bxdf.chunk @@ -41,7 +41,7 @@ void InitializeLayerBlending(out vec3 blendedBaseLayerD, out vec3 blendedBaseLay blendedBaseLayerD = baseD; blendedBaseLayerS = baseS; blendedSubLayerD = blendedSubLayerS = vec3(0.0); - lastLayerF = vec3(1.0); + lastLayerF = vec3(1.0); } // use subLayerF instead of subLayerGF for ior-dependent 0-1 range diff --git a/editor/assets/chunks/common/lighting/functions.chunk b/editor/assets/chunks/common/lighting/functions.chunk index cc744e5f7ab..bfedd416ac7 100644 --- a/editor/assets/chunks/common/lighting/functions.chunk +++ b/editor/assets/chunks/common/lighting/functions.chunk @@ -7,7 +7,7 @@ vec3 CalculateRefractDirection(vec3 N, vec3 V, float NoV, float ior) // two sided float sideSign = NoV < 0.0 ? -1.0 : 1.0; N *= sideSign; - + // A: NV B:NR float cosA = abs(NoV); float sinA = sqrt(1.0 - cosA * cosA); @@ -25,7 +25,7 @@ vec3 CalculateRefractDirectionFast(vec3 N, vec3 V, float NoV, float ior) // two sided float sideSign = NoV < 0.0 ? -1.0 : 1.0; N *= sideSign; - + float w = ior * NoV; float k = sqrt(1.0 + (w - ior) * (w + ior)); // 1 + ior2 * (NoV2 - 1) vec3 R = (w - k) * N - ior * V; @@ -54,7 +54,7 @@ vec3 CalculatePlanarReflectPositionOnPlane(vec3 N, vec3 V, vec3 worldPos, vec4 p float sideSignN = dot(N, V) < 0.0 ? -1.0 : 1.0; planeN *= sideSignPlaneN; N *= sideSignN;*/ - vec3 bumpedR = normalize(reflect(-V, N)); //R' + vec3 bumpedR = normalize(reflect(-V, N)); //R' // actually reflected pos alone bumpedR direction, avoid tracing by specified a fake depth vec3 reflectedPointPos = worldPos + probeReflectedDepth * bumpedR; diff --git a/editor/assets/chunks/common/math/transform.chunk b/editor/assets/chunks/common/math/transform.chunk index fd9c9ad9855..c5d906c4ce3 100644 --- a/editor/assets/chunks/common/math/transform.chunk +++ b/editor/assets/chunks/common/math/transform.chunk @@ -167,7 +167,7 @@ void rotateCorner (inout vec2 corner, float angle){ mat3 quatToMat3(vec4 q) { vec3 m0 = vec3( - 1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z, + 1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z, 2.0 * q.x * q.y + 2.0 * q.w * q.z, 2.0 * q.x * q.z - 2.0 * q.w * q.y); vec3 m1 = vec3( @@ -176,7 +176,7 @@ mat3 quatToMat3(vec4 q) { 2.0 * q.y * q.z + 2.0 * q.w * q.x); vec3 m2 = vec3( 2.0 * q.x * q.z + 2.0 * q.w * q.y, - 2.0 * q.y * q.z - 2.0 * q.w * q.x, + 2.0 * q.y * q.z - 2.0 * q.w * q.x, 1.0 - 2.0 * q.x * q.x - 2.0 * q.y * q.y); return mat3(m0, m1, m2); } @@ -190,14 +190,14 @@ vec4 mat3ToQuat(mat3 mat) { float tr = mat[0][0] + mat[1][1] + mat[2][2]; float qw, qx, qy, qz; if (tr > 0.0) { - float S = sqrt(tr + 1.0) * 2.0; // S=4*qw + float S = sqrt(tr + 1.0) * 2.0; // S=4*qw float invS = 1.0 / S; qw = 0.25 * S; qx = (mat[1][2] - mat[2][1]) * invS; qy = (mat[2][0] - mat[0][2]) * invS; qz = (mat[0][1] - mat[1][0]) * invS; } else if ((mat[0][0] > mat[1][1])&&(mat[0][0] > mat[2][2])) { - float S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0; // S=4*qx + float S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0; // S=4*qx float invS = 1.0 / S; qw = (mat[1][2] - mat[2][1]) * invS; qx = 0.25 * S; @@ -224,7 +224,7 @@ vec4 mat3ToQuat(mat3 mat) { vec4 eulerToQuat(vec3 euler) { vec3 er = euler * 0.5; float x = er.x, y = er.y, z = er.z; - + float sx = sin(x); float cx = cos(x); float sy = sin(y); diff --git a/editor/assets/chunks/common/mesh/material.chunk b/editor/assets/chunks/common/mesh/material.chunk index 0f70837976a..435f31a76e7 100644 --- a/editor/assets/chunks/common/mesh/material.chunk +++ b/editor/assets/chunks/common/mesh/material.chunk @@ -7,10 +7,10 @@ bool GetMetallicAlbedoFromDiffuseSpecularMathematic(out float metallic, out vec3 diffuse += vec3(f0 + 0.01); specular += vec3(f0 + 0.01); - vec3 delta = (diffuse + specular) * (diffuse + specular) - 4.0 * f0 * diffuse; + vec3 delta = (diffuse + specular) * (diffuse + specular) - 4.0 * f0 * diffuse; vec3 deltaSqrt = sqrt(max(vec3(0.0), delta)); // solver - vec3 m = (-diffuse - specular + 2.0 * f0 + deltaSqrt) / (2.0 * f0); + vec3 m = (-diffuse - specular + 2.0 * f0 + deltaSqrt) / (2.0 * f0); vec3 weight = diffuse + specular; weight /= dot(weight, vec3(1.0)); float solverMetallic = dot(m, weight); @@ -20,7 +20,7 @@ bool GetMetallicAlbedoFromDiffuseSpecularMathematic(out float metallic, out vec3 && abs(m.x - m.y) < channelFaultTolerant && abs(m.x - m.z) < channelFaultTolerant && m.x >= 0.0 && m.y >= 0.0 && m.z >= 0.0 && m.x <= 1.0 && m.y <= 1.0 && m.z <= 1.0; - + metallic = isValidSolver ? solverMetallic : metallic; albedo = isValidSolver ? solverAlbedo : albedo; return isValidSolver; diff --git a/editor/assets/chunks/common/mesh/vat-animation.chunk b/editor/assets/chunks/common/mesh/vat-animation.chunk index 1d2a20c7a0b..10878821ce7 100644 --- a/editor/assets/chunks/common/mesh/vat-animation.chunk +++ b/editor/assets/chunks/common/mesh/vat-animation.chunk @@ -107,7 +107,7 @@ vec3 VATCalculateFluidVoxelUV(vec3 vatBoundingBoxMin, vec3 vatBoundingBoxMax, ve // bounding box in exported json is unscaled vatBoundingBoxMin *= VAT_FBX_TO_COCOS_COORDINATE_SCALE; vatBoundingBoxMax *= VAT_FBX_TO_COCOS_COORDINATE_SCALE; - + vec3 size = vatBoundingBoxMax - vatBoundingBoxMin; vec3 coef = (localPos - vatBoundingBoxMin) / size; return coef; @@ -119,7 +119,7 @@ vec3 VATCalculateFluidVoxelUV(vec3 vatBoundingBoxMin, vec3 vatBoundingBoxMax, ve ////////////////////////////////////////////////////////////////Rigid-body void VATGetLocalPositionRigidBody20(inout vec3 meshLocalPos, inout vec3 meshLocalNormal, inout vec3 meshLocalTangent, in vec4 meshVertexColor, vec2 thisFrameUV, float pivMax, float pivMin, float posMax, float posMin, sampler2D vatPositionTexture, sampler2D vatPositionSignTexture, sampler2D vatPositionAlphaTexture, sampler2D vatRotationTexture, sampler2D vatRotationSignTexture, sampler2D vatRotationAlphaTexture) -{ +{ // pivot float pivExpand = pivMax - pivMin; float posExpand = posMax - posMin; @@ -127,7 +127,7 @@ void VATGetLocalPositionRigidBody20(inout vec3 meshLocalPos, inout vec3 meshLoca vec3 pivot = meshVertexColor.xyz; pivot.xyz *= pivExpand; pivot.xyz += vec3(pivMin); - + // anim pos vec3 posData = SampleTextureExr(vatPositionTexture, vatPositionSignTexture, thisFrameUV); vec3 texturePos = posData; @@ -203,7 +203,7 @@ void VATGetLocalPositionRigidBody30(inout vec3 meshLocalPos, inout vec3 meshLoca if(isZUp) pivot.xyz = pivot.xzy / VAT_FBX_TO_COCOS_COORDINATE_SCALE; vec3 originPos = meshLocalPos - pivot; - + // rotation offset vec4 posData = SampleTextureExrWithAlpha(vatPositionTexture, vatPositionSignTexture, vatPositionAlphaTexture, thisFrameUV); vec4 XYZW = SampleTextureExrWithAlpha(vatRotationTexture, vatRotationSignTexture, vatRotationAlphaTexture, thisFrameUV); diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk b/editor/assets/chunks/common/shadow/native-pcf.chunk index 3457167f9a9..ab56782a846 100644 --- a/editor/assets/chunks/common/shadow/native-pcf.chunk +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk @@ -29,7 +29,7 @@ float SampleShadowMapSoft (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 sh float resultX = mix(block0, block1, coefX); float resultY = mix(block2, block3, coefX); float coefY = mod(shadowNDCPos.y, oneTap.y) * shadowMapResolution.y; - + return mix(resultX, resultY, coefY); } @@ -66,7 +66,7 @@ float NativePCFShadowFactorSoft (vec3 shadowNDCPos, highp sampler2D shadowMap, v float resultX = mix(block0, block1, coefX); float resultY = mix(block2, block3, coefX); float coefY = mod(shadowNDCPos.y, oneTap.y) * shadowMapResolution.y; - + return mix(resultX, resultY, coefY); } @@ -126,9 +126,9 @@ float NativePCFShadowFactorSoft3X (vec3 shadowNDCPos, highp sampler2D shadowMap, float NativePCFShadowFactorSoft5X (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution) { - vec2 oneTap = 1.0 / shadowMapResolution; + vec2 oneTap = 1.0 / shadowMapResolution; vec2 twoTap = oneTap * 2.0; - + vec2 offset1 = shadowNDCPos.xy + vec2(-twoTap.x, -twoTap.y); vec2 offset2 = shadowNDCPos.xy + vec2(-oneTap.x, -twoTap.y); vec2 offset3 = shadowNDCPos.xy + vec2(0.0, -twoTap.y); @@ -154,7 +154,7 @@ float NativePCFShadowFactorSoft5X (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 offset23 = shadowNDCPos.xy + vec2(0.0, twoTap.y); vec2 offset24 = shadowNDCPos.xy + vec2(oneTap.x, twoTap.y); vec2 offset25 = shadowNDCPos.xy + vec2(twoTap.x, twoTap.y); - + float block1, block2, block3, block4, block5, block6, block7, block8, block9, block10, block11, block12, block13, block14, block15, block16, block17, block18, block19, block20, block21, block22, block23, block24, block25; #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 block1 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset1))); diff --git a/editor/assets/chunks/legacy/decode-base.chunk b/editor/assets/chunks/legacy/decode-base.chunk index cddbdac9ee8..d23b9596dd9 100644 --- a/editor/assets/chunks/legacy/decode-base.chunk +++ b/editor/assets/chunks/legacy/decode-base.chunk @@ -39,7 +39,7 @@ layout(location = 3) in vec4 a_tangent; #if CC_USE_LIGHTMAP in vec4 a_lightingMapUVParam; #endif - + // TODO (jk20012001) #if CC_USE_REFLECTION_PROBE || CC_RECEIVE_SHADOW // temporary hack for effect-parser: can't detect logic OR. @@ -47,7 +47,7 @@ layout(location = 3) in vec4 a_tangent; #endif in vec4 a_localShadowBiasAndProbeId; // x:shadow bias, y:shadow normal bias, z: reflection probe id, w: reserved for blend reflection probe id #endif - + #if CC_USE_REFLECTION_PROBE in vec4 a_reflectionProbeData; // x:reflection probe blend weight #endif diff --git a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk index 3a24fe065b6..af279490966 100644 --- a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk +++ b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk @@ -28,7 +28,7 @@ vec4 vert () { In.position.xyz += normalize(In.normal) * width; vec4 pos = cc_matProj * (cc_matView * matWorld) * In.position; #endif - + float scaleZ = cc_nearFar.z == 0.0 ? 0.5 : 1.0; pos.z -= outlineParams.y * 0.002 * scaleZ; diff --git a/editor/assets/chunks/legacy/output-standard.chunk b/editor/assets/chunks/legacy/output-standard.chunk index 6ed9b3dd122..44525108a84 100644 --- a/editor/assets/chunks/legacy/output-standard.chunk +++ b/editor/assets/chunks/legacy/output-standard.chunk @@ -12,6 +12,6 @@ vec4 CCFragOutput (vec4 color) { #endif color.rgb = LinearToSRGB(color.rgb); #endif - + return color; } diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index 01a3ad3d538..08ed385c87f 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -125,7 +125,7 @@ struct StandardSurface { vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { // Calculate diffuse & specular vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic); - + vec3 specular = mix(vec3(0.08 * s.specularIntensity), s.albedo.rgb, s.metallic); vec3 position; @@ -164,20 +164,20 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { #endif s.occlusion *= s.lightmap_test; #endif - + #if !CC_DISABLE_DIRECTIONAL_LIGHT float NV = max(abs(dot(N, V)), 0.0); specular = BRDFApprox(specular, s.roughness, NV); - + vec3 H = normalize(L + V); float NH = max(dot(N, H), 0.0); vec3 lightingColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w; vec3 diffuseContrib = diffuse / PI; - + // Cook-Torrance Microfacet Specular BRDF vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N); vec3 dirlightContrib = (diffuseContrib + specularContrib); - + dirlightContrib *= shadow; finalColor += lightingColor * dirlightContrib; #endif @@ -243,7 +243,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { vec3 worldPosOffset = CalculatePlanarReflectPositionOnPlane(N, V, s.position, plane, cc_cameraPos.xyz, planarReflectionDepthScale); vec2 screenUV = GetPlanarReflectScreenUV(worldPosOffset, cc_matViewProj, cc_cameraPos.w, V, R); probe = fragTextureLod(cc_reflectionProbePlanarMap, screenUV, mipCount); - } + } env = unpackRGBE(probe); #elif CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND || CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX if (s.reflectionProbeId < 0.0) { diff --git a/editor/assets/chunks/legacy/shading-toon.chunk b/editor/assets/chunks/legacy/shading-toon.chunk index 655b72018a3..3c6801fba98 100644 --- a/editor/assets/chunks/legacy/shading-toon.chunk +++ b/editor/assets/chunks/legacy/shading-toon.chunk @@ -43,7 +43,7 @@ struct ToonSurface { vec3 SH = normalize(SL + V); float SNL = 0.5 * dot(N, SL) + 0.5; float SNH = 0.5 * dot(N, SH) + 0.5; - + vec3 diffuse = mix(s.shade1, s.shade2, clamp(1.0 + (s.shadeStep - s.shadeFeather - SNL) / s.shadeFeather, 0.0, 1.0)); diffuse = mix(s.baseColor.rgb, diffuse, @@ -87,7 +87,7 @@ struct ToonSurface { vec4 CCToonShading (ToonSurface s) { vec3 position; HIGHP_VALUE_FROM_STRUCT_DEFINED(position, s.position); - + vec3 V = normalize(cc_cameraPos.xyz - position); vec3 N = normalize(s.normal); diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk index 54e54b14bbf..66a9d556070 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk @@ -40,7 +40,7 @@ struct LightingIntermediateData // add overrided functions for difference shading-models in void CCSurfacesLightingGetIntermediateData_PerPixel(inout LightingIntermediateData data, vec3 worldNormal, vec3 worldPos, vec3 worldTangent, vec3 worldBinormal #if CC_SURFACES_LIGHTING_ANISOTROPIC - , float anisotropyShape + , float anisotropyShape #endif ) { @@ -85,7 +85,7 @@ void CCSurfacesLightingGetIntermediateData_PerLight(inout LightingIntermediateDa data.L = lightDirWithDist; data.distToLightSqr = dot(data.L, data.L); data.distToLight = sqrt(data.distToLightSqr); - + data.L /= data.distToLight; data.H = normalize(data.L + data.V); @@ -94,7 +94,7 @@ void CCSurfacesLightingGetIntermediateData_PerLight(inout LightingIntermediateDa data.NoL = dot(data.N, data.L); data.NoH = dot(data.N, data.H); data.VoH = dot(data.V, data.H); - + data.NoLSat = max(data.NoL, 0.0); data.NoHSat = max(data.NoH, 0.0); // data.VoHSat = max(data.VoH, 0.0); diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index 88078372f3a..0324db26f35 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -40,7 +40,7 @@ vec3 fresnel = vec3(1.0); #endif lightingResult.fresnel = fresnel; - + float shadow = 1.0; #if CC_RECEIVE_SHADOW && CC_SHADOW_TYPE == CC_SHADOW_MAP diff --git a/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk b/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk index 78ab23eba1f..f2d4c75844b 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard-common.chunk @@ -205,14 +205,14 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa vec3 R = normalize(CalculateReflectDirection(lightingData.N, lightingData.V, lightingData.NoV)); vec4 fixedR = CalculateBoxProjectedDirection(R, worldPos, centerPos, boxHalfSize); envSpec = mix(skyBoxEnv, envSpec, fixedR.w); - #endif + #endif }else{ vec3 centerPosBlend, boxHalfSizeBlend; float mipCountBlend; GetBlendCubeReflectionProbeData(centerPosBlend, boxHalfSizeBlend, mipCountBlend, FSInput_reflectionProbeBlendId); vec3 probeBlend = SampleEnvironmentSpecular(cc_reflectionProbeBlendCubemap, lightingData, mipCountBlend, worldPos, centerPosBlend, boxHalfSizeBlend, isBlendReflectProbeUsingRGBE(FSInput_reflectionProbeBlendId)); envSpec = mix(envSpec, probeBlend, blendFactor); - } + } } #endif #elif CC_USE_IBL diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index 89f25c75547..a0a5054f127 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -108,7 +108,7 @@ void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 in vec3 R = CalculateRefractDirection(lightingData.N, lightingData.V, lightingData.NoV, lightingData.ior); float RoL = dot(lightingData.L, normalize(R)); float calcSpec = D_GGX(roughness, saturate(RoL)); - + lightingSpecular = irradiance * calcSpec; } void CCSurfacesLightingCalculateEnvironmentTransmitSpecular(out vec3 lightingSpecular, in LightingIntermediateData lightingData, float lightIntensity) @@ -116,7 +116,7 @@ void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 in vec3 envSpec = vec3(0.0); vec3 R = CalculateRefractDirection(lightingData.N, lightingData.V, lightingData.NoV, lightingData.ior); float roughness = lightingData.specularParam; - + #if CC_USE_REFLECTION_PROBE #if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE envSpec = EnvReflection(cc_reflectionProbeCubemap, R, roughness, cc_ambientGround.w); @@ -200,7 +200,7 @@ void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 in return vec3(saturate(specBRDF)); } #endif - + void CCSurfacesLightingCalculateDirect2ndSpecular(out vec3 specularLighting, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity, float intensitySpecular, in vec3 originalSpecular) { #if !CC_SURFACES_LIGHTING_DISABLE_SPECULAR diff --git a/editor/assets/chunks/post-process/fxaa-hq.chunk b/editor/assets/chunks/post-process/fxaa-hq.chunk index 0480aaadae4..96dcb4e1981 100644 --- a/editor/assets/chunks/post-process/fxaa-hq.chunk +++ b/editor/assets/chunks/post-process/fxaa-hq.chunk @@ -110,23 +110,23 @@ float4 FxaaTexOff(FxaaTex tex, float2 pos, int2 off, float2 rcpFrame) { float FxaaLuma(float3 rgb) { - return rgb.y * (0.587/0.299) + rgb.x; } + return rgb.y * (0.587/0.299) + rgb.x; } float3 FxaaLerp3(float3 a, float3 b, float amountOfA) { - return (FxaaToFloat3(-amountOfA) * b) + - ((a * FxaaToFloat3(amountOfA)) + b); } + return (FxaaToFloat3(-amountOfA) * b) + + ((a * FxaaToFloat3(amountOfA)) + b); } float3 FxaaFilterReturn(float3 rgb) { #if FXAA_SRGB_ROP return FxaaSel3( - rgb * FxaaToFloat3(1.0/12.92), + rgb * FxaaToFloat3(1.0/12.92), FxaaPow3( - rgb * FxaaToFloat3(1.0/1.055) + FxaaToFloat3(0.055/1.055), + rgb * FxaaToFloat3(1.0/1.055) + FxaaToFloat3(0.055/1.055), FxaaToFloat3(2.4)), - rgb > FxaaToFloat3(0.04045)); + rgb > FxaaToFloat3(0.04045)); #else return rgb; #endif } - + float3 FxaaPixelShader( float2 pos, @@ -147,7 +147,7 @@ float2 rcpFrame) { float range = rangeMax - rangeMin; #if FXAA_DEBUG float lumaO = lumaM / (1.0 + (0.587/0.299)); - #endif + #endif if(range < max(FXAA_EDGE_THRESHOLD_MIN, rangeMax * FXAA_EDGE_THRESHOLD)) { #if FXAA_DEBUG return FxaaFilterReturn(FxaaToFloat3(lumaO)); @@ -155,27 +155,27 @@ float2 rcpFrame) { return FxaaFilterReturn(rgbM); } #if FXAA_SUBPIX > 0 #if FXAA_SUBPIX_FASTER - float3 rgbL = (rgbN + rgbW + rgbE + rgbS + rgbM) * + float3 rgbL = (rgbN + rgbW + rgbE + rgbS + rgbM) * FxaaToFloat3(1.0/5.0); #else float3 rgbL = rgbN + rgbW + rgbM + rgbE + rgbS; #endif - #endif - + #endif + #if FXAA_SUBPIX != 0 float lumaL = (lumaN + lumaW + lumaE + lumaS) * 0.25; float rangeL = abs(lumaL - lumaM); - #endif + #endif #if FXAA_SUBPIX == 1 - float blendL = max(0.0, - (rangeL / range) - FXAA_SUBPIX_TRIM) * FXAA_SUBPIX_TRIM_SCALE; + float blendL = max(0.0, + (rangeL / range) - FXAA_SUBPIX_TRIM) * FXAA_SUBPIX_TRIM_SCALE; blendL = min(FXAA_SUBPIX_CAP, blendL); #endif #if FXAA_SUBPIX == 2 - float blendL = rangeL / range; + float blendL = rangeL / range; #endif - + float3 rgbNW = FxaaTexOff(tex, pos.xy, FxaaInt2(-1,-1), rcpFrame).xyz; @@ -190,11 +190,11 @@ float2 rcpFrame) { float lumaNE = FxaaLuma(rgbNE); float lumaSW = FxaaLuma(rgbSW); float lumaSE = FxaaLuma(rgbSE); - float edgeVert = + float edgeVert = abs((0.25 * lumaNW) + (-0.5 * lumaN) + (0.25 * lumaNE)) + abs((0.50 * lumaW ) + (-1.0 * lumaM) + (0.50 * lumaE )) + abs((0.25 * lumaSW) + (-0.5 * lumaS) + (0.25 * lumaSE)); - float edgeHorz = + float edgeHorz = abs((0.25 * lumaNW) + (-0.5 * lumaW) + (0.25 * lumaSW)) + abs((0.50 * lumaN ) + (-1.0 * lumaM) + (0.50 * lumaS )) + abs((0.25 * lumaNE) + (-0.5 * lumaE) + (0.25 * lumaSE)); @@ -206,9 +206,9 @@ float2 rcpFrame) { float gradientS = abs(lumaS - lumaM); lumaN = (lumaN + lumaM) * 0.5; lumaS = (lumaS + lumaM) * 0.5; - - + + bool pairN = gradientN >= gradientS; if(!pairN) lumaN = lumaS; if(!pairN) gradientN = gradientS; @@ -216,15 +216,15 @@ float2 rcpFrame) { float2 posN; posN.x = pos.x + (horzSpan ? 0.0 : lengthSign * 0.5); posN.y = pos.y + (horzSpan ? lengthSign * 0.5 : 0.0); - + gradientN *= FXAA_SEARCH_THRESHOLD; - + float2 posP = posN; - float2 offNP = horzSpan ? + float2 offNP = horzSpan ? FxaaFloat2(rcpFrame.x, 0.0) : - FxaaFloat2(0.0, rcpFrame.y); + FxaaFloat2(0.0, rcpFrame.y); float lumaEndN = lumaN; float lumaEndP = lumaN; bool doneN = false; @@ -250,14 +250,14 @@ float2 rcpFrame) { #endif for(int i = 0; i < FXAA_SEARCH_STEPS; i++) { #if FXAA_SEARCH_ACCELERATION == 1 - if(!doneN) lumaEndN = + if(!doneN) lumaEndN = FxaaLuma(FxaaTexLod0(tex, posN.xy).xyz); - if(!doneP) lumaEndP = + if(!doneP) lumaEndP = FxaaLuma(FxaaTexLod0(tex, posP.xy).xyz); #else - if(!doneN) lumaEndN = + if(!doneN) lumaEndN = FxaaLuma(FxaaTexGrad(tex, posN.xy, offNP).xyz); - if(!doneP) lumaEndP = + if(!doneP) lumaEndP = FxaaLuma(FxaaTexGrad(tex, posP.xy, offNP).xyz); #endif doneN = doneN || (abs(lumaEndN - lumaN) >= gradientN); @@ -265,19 +265,19 @@ float2 rcpFrame) { if(doneN && doneP) break; if(!doneN) posN -= offNP; if(!doneP) posP += offNP; } - + float dstN = horzSpan ? pos.x - posN.x : pos.y - posN.y; float dstP = horzSpan ? posP.x - pos.x : posP.y - pos.y; bool directionN = dstN < dstP; lumaEndN = directionN ? lumaEndN : lumaEndP; - - if(((lumaM - lumaN) < 0.0) == ((lumaEndN - lumaN) < 0.0)) + + if(((lumaM - lumaN) < 0.0) == ((lumaEndN - lumaN) < 0.0)) lengthSign = 0.0; - + float spanLength = (dstP + dstN); @@ -287,8 +287,8 @@ float2 rcpFrame) { pos.x + (horzSpan ? 0.0 : subPixelOffset), pos.y + (horzSpan ? subPixelOffset : 0.0))).xyz; #if FXAA_SUBPIX == 0 - return FxaaFilterReturn(rgbF); - #else - return FxaaFilterReturn(FxaaLerp3(rgbL, rgbF, blendL)); + return FxaaFilterReturn(rgbF); + #else + return FxaaFilterReturn(FxaaLerp3(rgbL, rgbF, blendL)); #endif } diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk index c97b12c37de..f464e8da10d 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk @@ -6,7 +6,7 @@ struct SurfacesStandardVertexIntermediate #if CC_SURFACES_USE_TANGENT_SPACE vec4 tangent; #endif - + //other data #if CC_SURFACES_USE_VERTEX_COLOR vec4 color; diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk index 36e8e4c8eb2..cd1e3391a55 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk @@ -28,6 +28,6 @@ void main() { CC_TRANSFER_FOG_BASE(vec4(FSInput_worldPos, 1.0), fogFactor); CC_APPLY_FOG_BASE(color, fogFactor); #endif - + fragColorX = color; } diff --git a/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk index 75f3708624b..6de8688e421 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-planar-shadow/vs.chunk @@ -30,7 +30,7 @@ void main() SurfacesVertexModifySharedData(In); // Other Data - CCSurfacesVertexTransformUV(In); + CCSurfacesVertexTransformUV(In); CCSurfacesVertexOutput(In); diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk index ba2beb4bd2c..4e31ab6d6da 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-reflectmap/fs.chunk @@ -2,7 +2,7 @@ layout(location = 0) out vec4 fragColorX; #if CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED && !CC_FORCE_FORWARD_SHADING void main() { fragColorX = vec4(0.0, 1.0, 0.0, 1.0); } -#else +#else void main() { #if CC_DISABLE_STRUCTURE_IN_FRAGMENT_SHADER float NoL = dot(-cc_mainLitDir.xyz, FSInput_worldNormal.xyz); //trigger ubo binding @@ -15,14 +15,14 @@ layout(location = 0) out vec4 fragColorX; // Surface SurfacesMaterialData surfaceData; CCSurfacesFragmentGetMaterialData(surfaceData); - + // Shadow parameters vec2 shadowBias = vec2(0.0); #if CC_RECEIVE_SHADOW shadowBias = FSInput_shadowBias; #endif - - + + // Fog factor #if !CC_FORWARD_ADD float fogFactor = 1.0; @@ -34,20 +34,20 @@ layout(location = 0) out vec4 fragColorX; #endif #endif #endif - - + + // Lighting LightingResult lightingResult; CCSurfacesLighting(lightingResult, surfaceData, shadowBias); - + // Shading vec4 color = CCSurfacesShading(surfaceData, lightingResult); #endif - + #if !CC_FORWARD_ADD CC_APPLY_FOG_BASE(color, fogFactor); #endif - + // Color output (RGBE) fragColorX = packRGBE(color.rgb); } diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk index 74abf06c26c..044efb76765 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk @@ -2,4 +2,4 @@ #include #elif CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED #include -#endif +#endif diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index a2c0d94165c..96fe6789df5 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -1,5 +1,5 @@ layout(location = 0) out vec4 fragColorX; - + void main() { #if CC_DISABLE_STRUCTURE_IN_FRAGMENT_SHADER float NoL = dot(-cc_mainLitDir.xyz, FSInput_worldNormal.xyz); //trigger ubo binding @@ -12,7 +12,7 @@ void main() { // Surface SurfacesMaterialData surfaceData; CCSurfacesFragmentGetMaterialData(surfaceData); - + // Shadow parameters vec2 shadowBias = vec2(0.0); vec3 colDebugCSMLayer = vec3(1.0); @@ -43,7 +43,7 @@ void main() { #endif #endif - + // Fog factor float fogFactor = 1.0; #if !CC_FORWARD_ADD @@ -96,7 +96,7 @@ void main() { // Use material alpha debugColor.a = materialTransparency; - // lighting needs color space conversion + // lighting needs color space conversion #if !CC_USE_FLOAT_OUTPUT debugColor.rgb = HDRToLDR(debugColor.rgb); debugColor.rgb = LinearToSRGB(debugColor.rgb); diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk index 1f784d59585..3f09f3b939e 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk @@ -29,7 +29,7 @@ void main() SurfacesVertexModifySharedData(In); // Other Data - CCSurfacesVertexTransformUV(In); + CCSurfacesVertexTransformUV(In); CCSurfacesVertexTransferFog(In); CCSurfacesVertexTransferLightMapUV(In); diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk index cecd57a617e..9af5e4626bc 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk @@ -26,7 +26,7 @@ void main() SurfacesVertexModifySharedData(In); // Other Data - CCSurfacesVertexTransformUV(In); + CCSurfacesVertexTransformUV(In); CCSurfacesVertexOutput(In); diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk b/editor/assets/chunks/surfaces/data-structures/standard.chunk index 35ad979848b..d7148f6d3e4 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk @@ -14,7 +14,7 @@ struct SurfacesMaterialData // for advanced PBR vec3 worldTangent, worldBinormal; float ior; - + #if CC_SURFACES_LIGHTING_ANISOTROPIC float anisotropyShape; #endif @@ -22,7 +22,7 @@ struct SurfacesMaterialData #if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE vec3 outScatteringColor, inScatteringColor; vec4 transmitScatteringParams; -#endif +#endif #if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE vec4 transmitDiffuseParams; #endif diff --git a/editor/assets/chunks/surfaces/data-structures/toon.chunk b/editor/assets/chunks/surfaces/data-structures/toon.chunk index 0fe329c8354..249cbdc1fa7 100644 --- a/editor/assets/chunks/surfaces/data-structures/toon.chunk +++ b/editor/assets/chunks/surfaces/data-structures/toon.chunk @@ -1,7 +1,7 @@ struct SurfacesMaterialData { HIGHP_VALUE_STRUCT_DEFINE(vec3, worldPos); - + vec4 baseColor; vec4 specular; vec3 worldNormal; diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk index 4e2de4c6c28..a6a68d053af 100644 --- a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk @@ -146,7 +146,7 @@ void CCSurfacesVertexTransferShadow(inout SurfacesStandardVertexIntermediate In) In.shadowBiasAndProbeId.xy += cc_localShadowBias.xy; #endif #endif - + #if CC_USE_REFLECTION_PROBE #if USE_INSTANCING In.shadowBiasAndProbeId.zw = a_localShadowBiasAndProbeId.zw; diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk index 5f380b79db6..49845f038aa 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk @@ -11,7 +11,7 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) { float index = mod(cc_time.x * 10.0, 2.0); vec4 error = index < 1.0 ? vec4(1.0, 0.0, 0.2, 1.0) : vec4(0.0, 1.0, 0.2, 1.0); - + return (isnans(data) || isinfs(data)) ? error : color; } @@ -21,7 +21,7 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) { vec4 white = vec4(1.0, 1.0, 1.0, 1.0); vec4 black = vec4(0.0, 0.0, 0.0, 1.0); - + // vertex input if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_COLOR)) { @@ -31,10 +31,10 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) color = white; #endif } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_NORMAL)) - color = vec4(FSInput_worldNormal * 0.5 + vec3(0.5), 1.0); - + color = vec4(FSInput_worldNormal * 0.5 + vec3(0.5), 1.0); + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_TANGENT)) { #if CC_SURFACES_USE_TANGENT_SPACE @@ -43,7 +43,7 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) color = black; #endif } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_MIRROR)) { #if CC_SURFACES_USE_TANGENT_SPACE @@ -53,19 +53,19 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) color = black; #endif } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FACE_SIDE)) { float scalar = clamp(FSInput_faceSideSign, 0.0, 1.0); color = vec4(scalar, scalar, scalar, 1.0); } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_UV0)) color = vec4(FSInput_texcoord.xy, 0.0, 1.0); - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_UV1)) color = vec4(FSInput_texcoord1.xy, 0.0, 1.0); - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_UVLIGHTMAP)) { #if CC_USE_LIGHTMAP && !CC_FORWARD_ADD @@ -74,21 +74,21 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) color = vec4(0.0, 0.0, 0.0, 1.0); #endif } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_PROJ_DEPTH)) { vec4 clipPos = cc_matProj * cc_matView * vec4(FSInput_worldPos.xyz, 1.0); float depth = clipPos.z / clipPos.w; color = vec4(depth, depth, depth, 1.0); } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_LINEAR_DEPTH)) { vec4 viewPos = cc_matView * vec4(FSInput_worldPos.xyz, 1.0); float depth = (-viewPos.z - cc_nearFar.x) / cc_nearFar.y; color = vec4(depth, depth, depth, 1.0); } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_WORLD_POS)) color = vec4(FSInput_worldPos.xyz, 1.0); } @@ -107,55 +107,55 @@ vec4 CCSurfacesDebugDisplayInvalidInputData(vec4 color, vec3 data) color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR)) { color.rgb = lightingResult.directSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_ALL)) { color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting * lightingResult.directGF; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_DIFFUSE)) { color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_SPECULAR)) { color.rgb = lightingResult.environmentSpecular * lightingResult.specularColorWithLighting * lightingResult.environmentGF; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_ALL)) { color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting * lightingResult.environmentGF; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_LIGHT_MAP)) { color.rgb = lightingResult.lightmapColor; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_EMISSIVE)) { color.rgb = lightingResult.emissive; isSRGBColor = true; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_AO)) { color.rgb = vec3(lightingResult.ao); isSRGBColor = false; } - + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SHADOW)) { color.rgb = vec3(lightingResult.shadow); diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index 6d139729e86..86db9d4f507 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -9,7 +9,7 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) surfaceData.worldNormal = SurfacesFragmentModifyWorldNormal(); SurfacesFragmentModifyWorldTangentAndBinormal(surfaceData.worldTangent, surfaceData.worldBinormal, surfaceData.worldNormal); - + surfaceData.ior = SurfacesFragmentModifyIOR(); #if CC_SURFACES_LIGHTING_ANISOTROPIC @@ -348,7 +348,7 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li + lightingResult.directTransmitDiffuse #endif ; - + #else vec3 fresnel = lightingResult.fresnel; vec3 invFresnel = vec3(1.0) - fresnel; @@ -403,7 +403,7 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li + lightingResult.environmentTransmitDiffuse #endif ; - + color.xyz += lightingResult.emissive; #endif diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk index f2019bc22e3..816c5f457f1 100644 --- a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk @@ -127,7 +127,7 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li color.xyz += lightingResult.directSpecular * lightingResult.specularColorWithLighting; #else float lightmapCoef = 0.0; - + #if CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING color.xyz += ( mix(lightingResult.directDiffuse, lightingResult.lightmapColor, lightmapCoef) * lightingResult.diffuseColorWithLighting @@ -150,7 +150,7 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li color.xyz += lightingResult.emissive; #endif - + return color; } diff --git a/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk b/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk index ed8a5ce578c..c120d38d047 100644 --- a/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/unlit-fs.chunk @@ -4,7 +4,7 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) { HIGHP_VALUE_TO_STRUCT_DEFINED(FSInput_worldPos, surfaceData.worldPos); - + surfaceData.baseColor = SurfacesFragmentModifyBaseColorAndTransparency(); SurfacesFragmentModifySharedData(surfaceData); diff --git a/editor/assets/effects/advanced/car-paint.effect b/editor/assets/effects/advanced/car-paint.effect index 6d7b0a97083..e79dfc5047a 100644 --- a/editor/assets/effects/advanced/car-paint.effect +++ b/editor/assets/effects/advanced/car-paint.effect @@ -283,7 +283,7 @@ CCProgram surface-fragment %{ vec4 flakeA = vec4(0.972,0.96,0.915,1); vec4 flakeB = vec4(1.0,0.78,0.344,1); vec4 flakeColor = lerp(flakeA, flakeB, data.r); - + vec4 color = surfaceData.baseColor; color = lerp(color, flakeColor, flakeWeight); color = lerp(surfaceData.baseColor, color, surfaceData.metallic); diff --git a/editor/assets/effects/advanced/common-functions.chunk b/editor/assets/effects/advanced/common-functions.chunk index ac99d9d875d..4c5d71e8ede 100644 --- a/editor/assets/effects/advanced/common-functions.chunk +++ b/editor/assets/effects/advanced/common-functions.chunk @@ -6,7 +6,7 @@ vec4 SurfacesFragmentModifyBaseColorAndTransparency() { vec4 baseColor = albedo; - + #if USE_VERTEX_COLOR baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear baseColor.a *= FSInput_vertexColor.a; @@ -39,7 +39,7 @@ #if USE_ALBEDO_MAP alpha = texture(albedoMap, ALBEDO_UV).ALPHA_TEST_CHANNEL; #endif - + if (alpha < albedoScaleAndCutoff.w) discard; #endif } diff --git a/editor/assets/effects/advanced/eye.chunk b/editor/assets/effects/advanced/eye.chunk index 41f5056a345..aba20e3c03c 100644 --- a/editor/assets/effects/advanced/eye.chunk +++ b/editor/assets/effects/advanced/eye.chunk @@ -11,7 +11,7 @@ vec3 lerp_3Color(vec3 A, vec3 B, vec3 C, float alpha) vec3 GetIrisUVMask(float IrisUVRadius) { const float IrisBorderWidth = 0.04, IrisBleedWidth = 0.035, IrisMaskWidth = 0.045; - + vec3 arg3_LimbusUVWidth = vec3(IrisBorderWidth, IrisBleedWidth, IrisMaskWidth); float arg8_IrisUVRadius = IrisUVRadius * 0.03 + 0.15; // vec3 out_IrisUVMask = Custom1(IrisUVRadius,UV,LimbusUVWidth) @@ -30,7 +30,7 @@ vec2 GetIrisUV(vec2 refractedUV, float IrisUVRadius, float PupilScale) { // code between Refract->Parallax, for control pupil size const float PupilShiftX = 0.0, PupilShiftY = 0.0, ScaleIrisWithinMask = 1.0; - + float uvRadius = (IrisUVRadius*0.03+0.15) * 2.0; vec2 UV1 = refractedUV - vec2(0.5); vec2 UV =(UV1 / uvRadius) + vec2(0.5); @@ -91,7 +91,7 @@ vec3 GetGeneratedColorForIris(vec2 irisUV, sampler2D irisColorMap, float IrisCol vec3 a = lerp(desat_col2, desat_col1, alphaRB.y); vec3 lerpedColor = lerp(a, b, RadialStructuralBlendSwitch) * M_Tex.a; vec3 base = lerpedColor * lerp(1.0, M_Tex.g, AOinIris); - + float radius = distance(irisUV - vec2(0.5), vec2(0.0)); float alpha = smoothstep(0.275, 0.5, radius); return lerp(base, pow(base, vec3(LimbusDarkAmount + 1.0)), alpha); @@ -118,7 +118,7 @@ vec3 GetBlendColorForIrisAndSclera(vec3 irisUVMask, vec3 irisGeneratedColor, sam vec3 irisColor = Desaturation(irisGeneratedColor * IrisBrightness, (IrisSaturation - 0.5) * -2.0); vec3 lerpedScleraAndIris = lerp(ScleraColor, irisColor, irisUVMask.r); vec3 cloudyPupilAddColor = SphereMask(FSInput_texcoord, vec2(0.5), CloudyIrisRadius, CloudyIrisHardness) * CloudyIrisColor.rgb; - + float scleraCornerDarkMask = SphereMask(FSInput_texcoord, vec2(0.5), ScleraCornerDarkRadius, ScleraCornerDarkHardness); vec3 ScleraCorner = lerp(ScleraCornerDarkColor.rgb, vec3(1.0), scleraCornerDarkMask); vec3 BaseColor = ScleraCorner * (cloudyPupilAddColor + lerpedScleraAndIris); diff --git a/editor/assets/effects/advanced/glass.effect b/editor/assets/effects/advanced/glass.effect index b1d7fce571a..5194b4fb3b4 100644 --- a/editor/assets/effects/advanced/glass.effect +++ b/editor/assets/effects/advanced/glass.effect @@ -275,7 +275,7 @@ CCProgram surface-fragment %{ if (bright > threshold) result.environmentSpecular = result.environmentSpecular / bright * threshold; #endif - } + } }% CCProgram standard-vs %{ diff --git a/editor/assets/effects/advanced/hair.effect b/editor/assets/effects/advanced/hair.effect index 9c500f38a29..09ea5683a58 100644 --- a/editor/assets/effects/advanced/hair.effect +++ b/editor/assets/effects/advanced/hair.effect @@ -202,7 +202,7 @@ CCProgram macro-remapping %{ #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE #define CC_SURFACES_LIGHTING_ANISOTROPIC IS_ANISOTROPY #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR - + #define CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE USE_BACK_LIT #define CC_SURFACES_LIGHTING_TRT 1 #define CC_SURFACES_LIGHTING_TT 1 @@ -320,7 +320,7 @@ CCProgram surface-fragment %{ { return vec3(0.0); } - + #define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_OUT_SCATTERING_COLOR vec3 SurfacesFragmentModifyTransmitOutScatteringColor() { @@ -331,7 +331,7 @@ CCProgram surface-fragment %{ vec4 SurfacesFragmentModifyBaseColorAndTransparency() { vec4 baseColor = albedo; - + #if USE_VERTEX_COLOR baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear baseColor.a *= FSInput_vertexColor.a; @@ -400,7 +400,7 @@ CCProgram surface-fragment %{ isRotation = 1.0; return vec4(anisotropyShape, anisotropyRotation, 0.0, 0.0); } - + #include // definition of SurfacesMaterialData structure with corresponding shading-model diff --git a/editor/assets/effects/internal/builtin-wireframe.effect b/editor/assets/effects/internal/builtin-wireframe.effect index e7a03d9f751..841c062c6ca 100644 --- a/editor/assets/effects/internal/builtin-wireframe.effect +++ b/editor/assets/effects/internal/builtin-wireframe.effect @@ -20,7 +20,7 @@ CCProgram wireframe-vs %{ vec4 lineColor; }; - + out vec2 bary; out vec4 lineCol; @@ -40,7 +40,7 @@ CCProgram wireframe-vs %{ CCProgram wireframe-fs %{ precision mediump float; #include - + in vec2 bary; in vec4 lineCol; diff --git a/editor/assets/effects/internal/editor/box-height-light.effect b/editor/assets/effects/internal/editor/box-height-light.effect index ba347e6f85b..9944578db9e 100644 --- a/editor/assets/effects/internal/editor/box-height-light.effect +++ b/editor/assets/effects/internal/editor/box-height-light.effect @@ -54,13 +54,13 @@ CCProgram line-fs %{ uniform Constant { vec4 mainColor; vec4 selectedColor; - vec4 selectedFaceForward; + vec4 selectedFaceForward; }; vec4 front() { vec4 outputColor = mainColor; - // dot + // dot vec3 d = normal.xyz * selectedFaceForward.xyz; float m = max(max(d.x, d.y), d.z); float selected = step(0.9999,m); diff --git a/editor/assets/effects/internal/editor/light-probe-visualization.effect b/editor/assets/effects/internal/editor/light-probe-visualization.effect index ecb84d1e566..510e0b897bf 100644 --- a/editor/assets/effects/internal/editor/light-probe-visualization.effect +++ b/editor/assets/effects/internal/editor/light-probe-visualization.effect @@ -89,7 +89,7 @@ CCProgram gizmo-fs %{ #if CC_USE_LIGHT_PROBE #include #endif - + vec4 gizmo_fs (float alpha) { #if CC_USE_LIGHT_PROBE vec3 N = normalize(normal_w) * (float(gl_FrontFacing) * 2.0 - 1.0); diff --git a/editor/assets/effects/pipeline/cluster-build.effect b/editor/assets/effects/pipeline/cluster-build.effect index fd4f229455f..40918844c27 100644 --- a/editor/assets/effects/pipeline/cluster-build.effect +++ b/editor/assets/effects/pipeline/cluster-build.effect @@ -36,8 +36,8 @@ CCProgram cluster-main %{ 2.0 * (coord.y - cc_viewPort.y) / cc_viewPort.w - 1.0, 2.0 * coord.z - 1.0); - CC_HANDLE_SAMPLE_NDC_FLIP_STATIC(ndc.y); - + CC_HANDLE_SAMPLE_NDC_FLIP_STATIC(ndc.y); + vec4 eye = ((cc_matProjInv) * (vec4(ndc, 1.0))); eye = eye / eye.w; return eye; diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect b/editor/assets/effects/pipeline/deferred-lighting.effect index bd8ace3b455..7e7da0e4f09 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect +++ b/editor/assets/effects/pipeline/deferred-lighting.effect @@ -62,7 +62,7 @@ CCProgram lighting-fs-tiled %{ 2.0 * coord.z - 1.0); #endif - + CC_HANDLE_SAMPLE_NDC_FLIP_STATIC(ndc.y); return GetWorldPosFromNDCPosRH(ndc, cc_matProj, cc_matViewProjInv); } diff --git a/editor/assets/effects/pipeline/post-process/blit-screen.effect b/editor/assets/effects/pipeline/post-process/blit-screen.effect index f7d2c36a554..dd8073e738f 100644 --- a/editor/assets/effects/pipeline/post-process/blit-screen.effect +++ b/editor/assets/effects/pipeline/post-process/blit-screen.effect @@ -23,7 +23,7 @@ CCEffect %{ CCProgram vs %{ #include <./chunks/vs> -}% +}% CCProgram fs %{ @@ -32,7 +32,7 @@ CCProgram fs %{ // #include in vec2 v_uv; - + uniform UBO { vec4 inputViewPort; }; @@ -44,6 +44,6 @@ CCProgram fs %{ void main () { fragColor = texture(inputTexture, v_uv); } - + }% - + diff --git a/editor/assets/effects/pipeline/post-process/chunks/fsr.chunk b/editor/assets/effects/pipeline/post-process/chunks/fsr.chunk index 72cd4d0ae30..c630fb10c18 100644 --- a/editor/assets/effects/pipeline/post-process/chunks/fsr.chunk +++ b/editor/assets/effects/pipeline/post-process/chunks/fsr.chunk @@ -146,7 +146,7 @@ void FsrEasuF( // a b // r g vec2 p0 = fp * con1.xy + con1.zw; - + // These are from p0 to avoid pulling two constants on pre-Navi hardware. vec2 p1 = p0 + con2.xy; vec2 p2 = p0 + con2.zw; @@ -168,7 +168,7 @@ void FsrEasuF( vec3 gC = FsrEasuCF(p2 + off.xz); float gL = gC.g + 0.5 *(gC.r + gC.b); vec3 oC = FsrEasuCF(p3 + off.yz); float oL = oC.g + 0.5 *(oC.r + oC.b); vec3 nC = FsrEasuCF(p3 + off.xz); float nL = nC.g + 0.5 *(nC.r + nC.b); - + //------------------------------------------------------------------------------------------------------------------------------ // Simplest multi-channel approximate luma possible (luma times 2, in 2 FMA/MAD). // Accumulate for bilinear interpolation. @@ -258,7 +258,7 @@ vec3 FsrRcasF( { // Constant generated by RcasSetup(). // Algorithm uses minimal 3x3 pixel neighborhood. - // b + // b // d e f // h vec2 sp = vec2(ip); diff --git a/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk b/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk index ebfa1fcd336..001d85b8011 100644 --- a/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk +++ b/editor/assets/effects/pipeline/post-process/chunks/hbao.chunk @@ -209,13 +209,13 @@ float HorizonOcclusion(vec2 deltaUV, vec3 S = FetchEyePos(uv); float tanS = Tangent(P, S); float d2 = Length2(S - P); - + if ((d2 < g_R2) && (tanS > tanH)) { // Accumulate AO between the horizon and the sample float sinS = tanS / sqrt(1.0 + tanS*tanS); ao += Falloff(d2) * (sinS - sinH); - + // Update the current horizon angle tanH = tanS; sinH = sinS; @@ -261,8 +261,8 @@ float CalculateAO(vec2 uv) // Multiply by 0.5 to scale from [-1,1]^2 to [0,1]^2 vec2 ray_radius_uv = 0.5 * g_R * g_FocalLen / P.z; float ray_radius_pix = ray_radius_uv.x * g_AOResolution.x; - - if (ray_radius_pix < 1.0) + + if (ray_radius_pix < 1.0) { return 1.0; } diff --git a/editor/assets/effects/pipeline/post-process/chunks/vs.chunk b/editor/assets/effects/pipeline/post-process/chunks/vs.chunk index 396287289a6..19c5544f305 100644 --- a/editor/assets/effects/pipeline/post-process/chunks/vs.chunk +++ b/editor/assets/effects/pipeline/post-process/chunks/vs.chunk @@ -1,6 +1,6 @@ precision highp float; - + #include #include #include diff --git a/editor/assets/effects/pipeline/post-process/color-grading.effect b/editor/assets/effects/pipeline/post-process/color-grading.effect index d7d631b7cd0..38195b66a06 100644 --- a/editor/assets/effects/pipeline/post-process/color-grading.effect +++ b/editor/assets/effects/pipeline/post-process/color-grading.effect @@ -82,9 +82,9 @@ CCProgram color-grading-8x8-fs %{ vec2 row = floor(mulB / 8.0 + EPS); vec4 row_col = vec4(row, mulB - row * 8.0); vec4 lookup = orgColor.ggrr * (63.0 / SIZE) + row_col * (TOTAL / SIZE) + (0.5 / SIZE); - + float b1w = bValue - mulB.x; - + vec3 sampled1 = texture(colorGradingMap, lookup.zx).rgb; vec3 sampled2 = texture(colorGradingMap, lookup.wy).rgb; diff --git a/editor/assets/effects/pipeline/post-process/fsr.effect b/editor/assets/effects/pipeline/post-process/fsr.effect index d7afb9fcc6a..5a088ede8c5 100644 --- a/editor/assets/effects/pipeline/post-process/fsr.effect +++ b/editor/assets/effects/pipeline/post-process/fsr.effect @@ -72,18 +72,18 @@ CCProgram fs-easu %{ void main () { vec3 c; vec4 con0, con1, con2, con3; - + // "rendersize" refers to size of source image before upscaling. vec2 rendersize = texSize.xy; FsrEasuCon( - con0, con1, con2, con3, + con0, con1, con2, con3, rendersize, rendersize, texSize.zw ); FsrEasuF(c, gl_FragCoord.xy, con0, con1, con2, con3); float alpha = texture(outputResultMap, v_uv).a; fragColor = vec4(c.xyz, alpha); } - + }% diff --git a/editor/assets/effects/pipeline/post-process/fxaa-hq.effect b/editor/assets/effects/pipeline/post-process/fxaa-hq.effect index 1312f6e0508..720e0506b0f 100644 --- a/editor/assets/effects/pipeline/post-process/fxaa-hq.effect +++ b/editor/assets/effects/pipeline/post-process/fxaa-hq.effect @@ -36,7 +36,7 @@ CCProgram fxaa-edge-fs %{ vec4 frag () { vec3 color = FxaaPixelShader(v_uv, sceneColorMap, texSize.zw); float alpha = texture(sceneColorMap, v_uv).a; - return vec4(color, alpha); + return vec4(color, alpha); } }% diff --git a/editor/assets/effects/pipeline/post-process/hbao.effect b/editor/assets/effects/pipeline/post-process/hbao.effect index adff7297dd3..e82faf6a450 100644 --- a/editor/assets/effects/pipeline/post-process/hbao.effect +++ b/editor/assets/effects/pipeline/post-process/hbao.effect @@ -58,7 +58,7 @@ CCProgram hbao-fs %{ void main () { float ao = CalculateAO(v_uv); - fragColor = vec4(ao, ao, ao, 1.0); + fragColor = vec4(ao, ao, ao, 1.0); } }% @@ -73,7 +73,7 @@ CCProgram blurx-fs %{ void main () { float ao = BlurCore(v_uv, vec2(1.0, 0.0)); - fragColor = vec4(ao, ao, ao, 1.0); + fragColor = vec4(ao, ao, ao, 1.0); } }% @@ -88,7 +88,7 @@ CCProgram blury-fs %{ void main () { float ao = BlurCore(v_uv, vec2(0.0, 1.0)); - fragColor = vec4(ao, ao, ao, 1.0); + fragColor = vec4(ao, ao, ao, 1.0); } }% @@ -103,6 +103,6 @@ CCProgram combine-fs %{ void main () { float ao = Combine(v_uv); - fragColor = vec4(1.0, 1.0, 1.0, ao); + fragColor = vec4(1.0, 1.0, 1.0, ao); } }% diff --git a/editor/assets/effects/pipeline/post-process/taa.effect b/editor/assets/effects/pipeline/post-process/taa.effect index b7ae1196e92..a9f9e49ec02 100644 --- a/editor/assets/effects/pipeline/post-process/taa.effect +++ b/editor/assets/effects/pipeline/post-process/taa.effect @@ -33,7 +33,7 @@ CCEffect %{ CCProgram vs %{ #include <./chunks/vs> -}% +}% CCProgram fs %{ @@ -52,7 +52,7 @@ CCProgram fs %{ vec4 taaParams1; // xy: offset, z: feedback mat4 taaPrevViewProj; }; - + #pragma rate motionMaskTex uniform highp sampler2D motionMaskTex; @@ -73,14 +73,14 @@ CCProgram fs %{ vec2 taaInputTexSize(); vec2 taaPrevTexSize(); - + vec3 Reinhard(in vec3 hdr) { return hdr / (hdr + 1.0); } vec3 ReinhardInverse(in vec3 sdr) { return sdr / max(1.0 - sdr, 1e-5); } - + // metal NDC y up while texture coord y down, // keep ndc and texture coord same y direction. vec2 NDCScToUV(vec4 ndc) { @@ -92,26 +92,26 @@ CCProgram fs %{ } return uv; } - + vec2 getVelocity(vec2 unjittedUV, vec2 uv, out float depth) { // vec3 worldPos = texture(posTex, uv).xyz; - - // use unjitted depth for unjitter matrix + + // use unjitted depth for unjitter matrix depth = texture(depthTex, unjittedUV).r; vec3 worldPos = screen2WS(vec3(uv, depth)); if (abs(worldPos.x) < 0.0001 && abs(worldPos.y) < 0.0001) { return vec2(0.); } - + vec4 historyNDC = taaPrevViewProj * vec4(worldPos, 1.); - + vec2 screenPos = NDCScToUV(historyNDC); return screenPos - uv; } - - + + vec4 clip_aabb(vec3 aabb_min, vec3 aabb_max, vec4 avg, vec4 input_texel) { vec3 p_clip = 0.5 * (aabb_max + aabb_min); vec3 e_clip = 0.5 * (aabb_max - aabb_min) + 5.960464478e-8; @@ -119,64 +119,64 @@ CCProgram fs %{ vec3 v_unit = v_clip.xyz / e_clip; vec3 a_unit = abs(v_unit); float ma_unit = max(a_unit.x, max(a_unit.y, a_unit.z)); - + if (ma_unit > 1.0) return vec4(p_clip, avg.w) + v_clip / ma_unit; else return input_texel; } - + vec3 RGBToYCoCg( vec3 RGB ) { float Y = dot( RGB, vec3( 1, 2, 1 ) ); float Co = dot( RGB, vec3( 2, 0, -2 ) ); float Cg = dot( RGB, vec3( -1, 2, -1 ) ); - + return vec3( Y, Co, Cg ); } - + vec3 YCoCgToRGB( vec3 YCoCg ) { float Y = YCoCg.x * 0.25; float Co = YCoCg.y * 0.25; float Cg = YCoCg.z * 0.25; - + float R = Y + Co - Cg; float G = Y + Cg; float B = Y - Co - Cg; - + return vec3( R, G, B ); } - + vec4 taaSampleTex(sampler2D tex, vec2 uv) { vec4 color = texture(tex, uv); - + color.rgb = RGBToYCoCg(color.rgb); // color.rgb = Reinhard(color.rgb); - + return color; } - + void minmax(sampler2D mainTex, in vec2 uv, out vec4 colorMin, out vec4 colorMax) { vec2 texSize = taaInputTexSize(); - + vec2 du = vec2(texSize.x, 0.0); vec2 dv = vec2(0.0, texSize.y); - + vec4 t = taaSampleTex(mainTex, uv - dv); vec4 l = taaSampleTex(mainTex, uv - du); vec4 c = taaSampleTex(mainTex, uv); vec4 r = taaSampleTex(mainTex, uv + du); vec4 b = taaSampleTex(mainTex, uv + dv); - + colorMin = min(t, min(l, min(c, min(r, b)))); colorMax = max(t, max(l, max(c, max(r, b)))); // colorAvg = (t + l + c + r + b) / 5.0; } - + float HdrWeightY(float Color, float Exposure) { return 1. / (Color * Exposure + 4.0); // return Color; } - + vec2 WeightedLerpFactors(float WeightA, float WeightB, float Blend) { float BlendA = (1.0 - Blend) * WeightA; float BlendB = Blend * WeightB; @@ -185,58 +185,58 @@ CCProgram fs %{ BlendB *= RcpBlend; return vec2(BlendA, BlendB); } - + vec4 temporalAAPS (sampler2D taaPrevTexture, sampler2D inputTexture, vec2 uv) { vec2 unjittedUV = uv - taaParams1.xy / 2.; vec2 scaledUnjittedUV = unjittedUV; // vec2 scaledUnjittedUV = (uv - taaParams1.xy / 2.) * cc_view_pr_parameters.x; // scaledUnjittedUV = min(vec2(cc_view_pr_parameters.x - taaInputTexSize()*2.), scaledUnjittedUV); - + float depth = 0.; vec2 velocity = getVelocity(scaledUnjittedUV, uv, depth); - + vec4 prevColor = taaSampleTex(taaPrevTexture, uv + velocity); - + vec4 color = taaSampleTex(inputTexture, scaledUnjittedUV); - + vec4 colorMin, colorMax; minmax(inputTexture, scaledUnjittedUV, colorMin, colorMax); - + vec3 resultColor; - + // clamp { // if (cc_view_taa_params2.y == 0. && cc_view_taa_params2.z == 1.) { prevColor.rgb = clamp(prevColor.rgb, colorMin.rgb, colorMax.rgb); // } - + float blendFinal = 1. - taaParams1.z; - + float currentWeight = HdrWeightY(color.x, 1.); float historyWeight = HdrWeightY(prevColor.x, 1.); - + vec2 weights = WeightedLerpFactors(historyWeight, currentWeight, blendFinal); resultColor = prevColor.rgb * weights.x + color.rgb * weights.y; - + // resultColor = mix(color.rgb, prevColor.rgb, blendFinal); } - + // clip // { // prevColor = clip_aabb(colorMin.xyz, colorMax.xyz, colorAvg, prevColor); // resultColor = lerp(color.rgb, prevColor.rgb, cc_view_taa_params2.y); // } - + // if (cc_view_taa_params2.y != 0.) { // resultColor = prevColor.rgb; // } - + // resultColor = ReinhardInverse(resultColor); resultColor = YCoCgToRGB(resultColor.rgb); - + return vec4(resultColor, color.a); } - + layout(location = 0) out vec4 fragColor; @@ -253,7 +253,7 @@ CCProgram fs %{ #if USE_TAA_MASK mask = texture(motionMaskTex, v_uv); #endif - + if (mask.r > 0.) { fragColor = texture(inputTexture, v_uv); } @@ -261,6 +261,6 @@ CCProgram fs %{ fragColor = temporalAAPS(taaPrevTexture, inputTexture, v_uv); } } - + }% - + diff --git a/editor/assets/effects/pipeline/ssss-blur.effect b/editor/assets/effects/pipeline/ssss-blur.effect index 4d57aaf8951..8c571a4c25c 100644 --- a/editor/assets/effects/pipeline/ssss-blur.effect +++ b/editor/assets/effects/pipeline/ssss-blur.effect @@ -78,7 +78,7 @@ CCProgram ssssBlur %{ } - /** + /** * @param texcoord The usual quad texture coordinates. * @param dir Direction of the blur: * - First pass: float2(1.0, 0.0) diff --git a/editor/assets/effects/util/splash-screen.effect b/editor/assets/effects/util/splash-screen.effect index 4dfb03b129a..5bb9064451a 100644 --- a/editor/assets/effects/util/splash-screen.effect +++ b/editor/assets/effects/util/splash-screen.effect @@ -26,7 +26,7 @@ CCEffect %{ CCProgram splash-screen-vs %{ precision mediump float; - + #pragma define u_resolution u_buffer0.xy #pragma define u_worldScale u_buffer1.xy #pragma define u_worldTranslate u_buffer1.zw @@ -40,7 +40,7 @@ CCProgram splash-screen-vs %{ mat4 u_projection; }; - vec4 vert () { + vec4 vert () { vec2 worldPos = a_position * u_worldScale + u_worldTranslate; vec2 clipSpace = worldPos / u_resolution * 2.0 - 1.0; vec4 screenPos = u_projection * vec4(clipSpace, 0.0, 1.0); From a51263c66d336fd266d1e0e02ea6acd18faccc63 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 17 Aug 2023 19:48:06 +0800 Subject: [PATCH 178/232] fix ScrollView state bug when scrolling with mouse (#15709) * fix ScrollView state bug when scrolling with mouse * fix scroll bar state bug * fix CI * as string --- cocos/ui/scroll-view.ts | 47 +++++++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/cocos/ui/scroll-view.ts b/cocos/ui/scroll-view.ts index 6087f46b427..7f568589dba 100644 --- a/cocos/ui/scroll-view.ts +++ b/cocos/ui/scroll-view.ts @@ -29,7 +29,7 @@ import { EventHandler as ComponentEventHandler } from '../scene-graph/component- import { UITransform } from '../2d/framework'; import { Event, EventMouse, EventTouch, Touch, SystemEventType, EventHandle, EventGamepad } from '../input/types'; import { errorID, logID } from '../core/platform/debug'; -import { Size, Vec2, Vec3 } from '../core/math'; +import { Size, Vec2, Vec3, approx } from '../core/math'; import { Layout } from './layout'; import { ScrollBar } from './scroll-bar'; import { ViewGroup } from './view-group'; @@ -1067,7 +1067,7 @@ export class ScrollView extends ViewGroup { if (!this._stopMouseWheel) { this._handlePressLogic(); - this.schedule(this._checkMouseWheel, 1.0 / 60, NaN, 0); + this.schedule(this._checkMouseWheel, 1.0 / 60); this._stopMouseWheel = true; } @@ -1282,8 +1282,12 @@ export class ScrollView extends ViewGroup { return a; }, totalMovement); - out.set(totalMovement.x * (1 - this.brake) / totalTime, - totalMovement.y * (1 - this.brake) / totalTime, totalMovement.z); + out.set( + totalMovement.x * (1 - this.brake) / totalTime, + totalMovement.y * (1 - this.brake) / totalTime, + + totalMovement.z, + ); } return out; } @@ -1407,12 +1411,12 @@ export class ScrollView extends ViewGroup { } protected _dispatchEvent (event: string): void { - if (event === EventType.SCROLL_ENDED) { + if (event === EventType.SCROLL_ENDED as string) { this._scrollEventEmitMask = 0; - } else if (event === EventType.SCROLL_TO_TOP - || event === EventType.SCROLL_TO_BOTTOM - || event === EventType.SCROLL_TO_LEFT - || event === EventType.SCROLL_TO_RIGHT) { + } else if (event === EventType.SCROLL_TO_TOP as string + || event === EventType.SCROLL_TO_BOTTOM as string + || event === EventType.SCROLL_TO_LEFT as string + || event === EventType.SCROLL_TO_RIGHT as string) { const flag = (1 << eventMap[event]); if (this._scrollEventEmitMask & flag) { return; @@ -1431,8 +1435,9 @@ export class ScrollView extends ViewGroup { } this._outOfBoundaryAmountDirty = true; - if (this._isOutOfBoundary()) { - const outOfBoundary = this._getHowMuchOutOfBoundary(); + const outOfBoundary = this._getHowMuchOutOfBoundary(); + const _isOutOfBoundary = !outOfBoundary.equals(Vec3.ZERO, EPSILON); + if (_isOutOfBoundary) { _tempVec3.set(this._getContentPosition()); _tempVec3.add(outOfBoundary); this._setContentPosition(_tempVec3); @@ -1457,7 +1462,7 @@ export class ScrollView extends ViewGroup { const viewTrans = this.view; const uiTrans = this._content._uiProps.uiTransformComp!; if (this._verticalScrollBar && this._verticalScrollBar.isValid) { - if (uiTrans.height < viewTrans.height) { + if (uiTrans.height < viewTrans.height || approx(uiTrans.height, viewTrans.height)) { this._verticalScrollBar.hide(); } else { this._verticalScrollBar.show(); @@ -1465,7 +1470,7 @@ export class ScrollView extends ViewGroup { } if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) { - if (uiTrans.width < viewTrans.width) { + if (uiTrans.width < viewTrans.width || approx(uiTrans.width, viewTrans.width)) { this._horizontalScrollBar.hide(); } else { this._horizontalScrollBar.show(); @@ -1760,8 +1765,13 @@ export class ScrollView extends ViewGroup { if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON)) { this._processInertiaScroll(); + if (this._scrolling) { + this._scrolling = false; + if (!this._autoScrolling) { + this._dispatchEvent(EventType.SCROLL_ENDED); + } + } this.unschedule(this._checkMouseWheel); - this._dispatchEvent(EventType.SCROLL_ENDED); this._stopMouseWheel = false; return; } @@ -1771,8 +1781,13 @@ export class ScrollView extends ViewGroup { // mouse wheel event is ended if (this._mouseWheelEventElapsedTime > maxElapsedTime) { this._onScrollBarTouchEnded(); + if (this._scrolling) { + this._scrolling = false; + if (!this._autoScrolling) { + this._dispatchEvent(EventType.SCROLL_ENDED); + } + } this.unschedule(this._checkMouseWheel); - this._dispatchEvent(EventType.SCROLL_ENDED); this._stopMouseWheel = false; } } @@ -1865,7 +1880,7 @@ export class ScrollView extends ViewGroup { } else if (event instanceof EventHandle) { handleInputDevice = event.handleInputDevice; } - let value; + let value: Vec2; if (!this.enabledInHierarchy || this._hoverIn === XrhoverType.NONE) { return; } From 1df6a1095af9ddeb89cf2e2fbf6ea6b4d3a426a5 Mon Sep 17 00:00:00 2001 From: GengineJS <476393671@qq.com> Date: Fri, 18 Aug 2023 01:23:18 +0800 Subject: [PATCH 179/232] [Restore] additive light (#16016) --- cocos/rendering/custom/executor.ts | 106 +++++++++++++++++++++++------ 1 file changed, 84 insertions(+), 22 deletions(-) diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 445a712e1ed..2ba97a70061 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -122,13 +122,12 @@ import { UpdateFrequency, } from './types'; import { PipelineUBO } from '../pipeline-ubo'; -import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; +import { WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; import { RenderAdditiveLightQueue } from '../render-additive-light-queue'; import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph'; import { VectorGraphColorMap } from './effect'; import { - getDescBindingFromName, getDescriptorSetDataFromLayout, getDescriptorSetDataFromLayoutId, getRenderArea, @@ -137,8 +136,6 @@ import { validPunctualLightsCulling, } from './define'; import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; -import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; -import { Texture2D } from '../../asset/assets/texture-2d'; import { SceneCulling } from './scene-culling'; class ResourceVisitor implements ResourceGraphVisitor { @@ -163,6 +160,7 @@ class ResourceVisitor implements ResourceGraphVisitor { // noop } persistentBuffer (value: Buffer): void { + // noop } persistentTexture (value: Texture): void { this.createDeviceTex(value); @@ -174,8 +172,10 @@ class ResourceVisitor implements ResourceGraphVisitor { this.createDeviceTex(value); } formatView (value: FormatView): void { + // noop } subresourceView (value: SubresourceView): void { + // noop } } @@ -1106,6 +1106,16 @@ class DevicePreSceneTask extends WebSceneTask { public start (): void { if (this.graphScene.blit) { this._currentQueue.createBlitDesc(this.graphScene.blit); + return; + } + if (!this.camera) { + return; + } + const sceneFlag = this._graphScene.scene!.flags; + if (sceneFlag & SceneFlags.DEFAULT_LIGHTING) { + this._sceneCulling(); + validPunctualLightsCulling(context.pipeline, this.camera); + context.additiveLight.gatherLightPasses(this.camera, this._cmdBuff, this._currentQueue.devicePass.layoutName); } } @@ -1147,7 +1157,9 @@ class DeviceSceneTask extends WebSceneTask { } } get graphScene (): GraphScene { return this._graphScene; } - public start (): void {} + public start (): void { + // noop + } protected _recordUI (): void { const batches = this.camera!.scene!.batches; @@ -1283,6 +1295,14 @@ class DeviceSceneTask extends WebSceneTask { } } + private _recordAdditiveLights (): void { + context.additiveLight?.recordCommandBuffer( + context.device, + this._renderPass, + context.commandBuffer, + ); + } + public submit (): void { const devicePass = this._currentQueue.devicePass; const sceneCulling = context.culling; @@ -1298,6 +1318,14 @@ class DeviceSceneTask extends WebSceneTask { const graphSceneData = this.graphScene.scene!; renderQueue.opaqueQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer); renderQueue.opaqueInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer); + if (graphSceneData.flags & SceneFlags.DEFAULT_LIGHTING) { + this._recordAdditiveLights(); + this.visitor.bindDescriptorSet( + SetIndex.GLOBAL, + context.pipeline.descriptorSet, + ); + } + renderQueue.transparentInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer); renderQueue.transparentQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer); if (graphSceneData.flags & SceneFlags.GEOMETRY) { @@ -1729,13 +1757,27 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { this.currPass.resetResource(this.passID, pass); } } - rasterSubpass (value: RasterSubpass): void {} - computeSubpass (value: ComputeSubpass): void {} - compute (value: ComputePass): void {} - resolve (value: ResolvePass): void {} - copy (value: CopyPass): void {} - move (value: MovePass): void {} - raytrace (value: RaytracePass): void {} + rasterSubpass (value: RasterSubpass): void { + // noop + } + computeSubpass (value: ComputeSubpass): void { + // noop + } + compute (value: ComputePass): void { + // noop + } + resolve (value: ResolvePass): void { + // noop + } + copy (value: CopyPass): void { + // noop + } + move (value: MovePass): void { + // noop + } + raytrace (value: RaytracePass): void { + // noop + } queue (value: RenderQueue): void { if (!this.rg.getValid(this.queueID)) return; const deviceQueue = context.pools.addDeviceQueue(); @@ -1763,7 +1805,9 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { graphScene.init(null, value, -1); this.currQueue!.addSceneTask(graphScene); } - dispatch (value: Dispatch): void {} + dispatch (value: Dispatch): void { + // noop + } } class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor { @@ -1786,21 +1830,39 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor this.currPass.record(); this.currPass.postPass(); } - rasterSubpass (value: RasterSubpass): void {} - computeSubpass (value: ComputeSubpass): void {} - resolve (value: ResolvePass): void {} - compute (value: ComputePass): void {} - copy (value: CopyPass): void {} - move (value: MovePass): void {} - raytrace (value: RaytracePass): void {} + rasterSubpass (value: RasterSubpass): void { + // noop + } + computeSubpass (value: ComputeSubpass): void { + // noop + } + resolve (value: ResolvePass): void { + // noop + } + compute (value: ComputePass): void { + // noop + } + copy (value: CopyPass): void { + // noop + } + move (value: MovePass): void { + // noop + } + raytrace (value: RaytracePass): void { + // noop + } queue (value: RenderQueue): void { // collect scene results } scene (value: SceneData): void { // scene command list finished } - blit (value: Blit): void {} - dispatch (value: Dispatch): void {} + blit (value: Blit): void { + // noop + } + dispatch (value: Dispatch): void { + // noop + } } export class RenderVisitor extends DefaultVisitor { From 7a3a4f1dfbe97f741e3ec690a0310e9f8843a293 Mon Sep 17 00:00:00 2001 From: zxx43 Date: Fri, 18 Aug 2023 02:08:30 +0800 Subject: [PATCH 180/232] add missed spine api (#16010) * add missed spine api * readSkeletonData return point --- native/tools/swig-config/spine.i | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/native/tools/swig-config/spine.i b/native/tools/swig-config/spine.i index 4d92e47b311..9ffeb32ccbf 100644 --- a/native/tools/swig-config/spine.i +++ b/native/tools/swig-config/spine.i @@ -136,6 +136,7 @@ using namespace spine; %ignore spine::Skeleton::getBounds; %ignore spine::Bone::updateWorldTransform(float, float, float, float, float, float, float); %ignore spine::Skin::findAttachmentsForSlot; +%ignore spine::SkeletonBinary::readSkeletonData(const unsigned char*, int); // ----- Rename Section ------ // Brief: Classes, methods or attributes needs to be renamed @@ -203,6 +204,7 @@ using namespace spine; %rename(slotIndex) spine::Skin::AttachmentMap::Entry::_slotIndex; %rename(name) spine::Skin::AttachmentMap::Entry::_name; %rename(attachment) spine::Skin::AttachmentMap::Entry::_attachment; +%rename(signum) spine::MathUtil::sign(float); // ----- Module Macro Section ------ // Brief: Generated code should be wrapped inside a macro @@ -745,4 +747,14 @@ using namespace spine; spine::String attachment(attachmentName.data()); return *($self->getAttachment(slot, attachment)); } +} + +%extend spine::SkeletonBinary { + SkeletonData *readSkeletonData(const std::vector& binary) { + std::vector input; + for (int i = 0; i < binary.size(); ++i) { + input.push_back(binary[i]); + } + return $self->readSkeletonData(input.data(), input.size()); + } } \ No newline at end of file From 006bc6254ea51e1971a6b1a4f725df4a342a321e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=85=B5?= <49358166+xubing0906@users.noreply.github.com> Date: Fri, 18 Aug 2023 10:10:38 +0800 Subject: [PATCH 181/232] fix planar reflection error under the native custom pipeline (#16014) --- .../pipeline/reflection-probe/ReflectionProbeStage.cpp | 4 ++-- native/cocos/scene/ReflectionProbe.cpp | 2 +- native/cocos/scene/ReflectionProbe.h | 2 +- native/tools/swig-config/scene.i | 1 + 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeStage.cpp b/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeStage.cpp index 54af9f38a54..7b08a491cc0 100644 --- a/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeStage.cpp +++ b/native/cocos/renderer/pipeline/reflection-probe/ReflectionProbeStage.cpp @@ -69,8 +69,8 @@ void ReflectionProbeStage::render(scene::Camera *camera) { _renderArea.x = 0; _renderArea.y = 0; - _renderArea.width = _probe->getRenderArea().x; - _renderArea.height = _probe->getRenderArea().y; + _renderArea.width = _probe->renderArea().x; + _renderArea.height = _probe->renderArea().y; if (hasFlag(static_cast(_probe->getCamera()->getClearFlag()), gfx::ClearFlagBit::COLOR)) { _clearColors[0] = _probe->getCamera()->getClearColor(); diff --git a/native/cocos/scene/ReflectionProbe.cpp b/native/cocos/scene/ReflectionProbe.cpp index 179029732d4..58fe46f8ef2 100644 --- a/native/cocos/scene/ReflectionProbe.cpp +++ b/native/cocos/scene/ReflectionProbe.cpp @@ -267,7 +267,7 @@ void ReflectionProbe::updateCameraDir(int32_t faceIdx) { _camera->update(true); } -Vec2 ReflectionProbe::getRenderArea() const { +Vec2 ReflectionProbe::renderArea() const { if (_probeType == ProbeType::PLANAR) { return Vec2(_realtimePlanarTexture->getWidth(), _realtimePlanarTexture->getHeight()); } diff --git a/native/cocos/scene/ReflectionProbe.h b/native/cocos/scene/ReflectionProbe.h index c7f50b57824..8a17a5e06be 100644 --- a/native/cocos/scene/ReflectionProbe.h +++ b/native/cocos/scene/ReflectionProbe.h @@ -135,7 +135,7 @@ class ReflectionProbe final { inline const ccstd::vector>& getBakedCubeTextures() const { return _bakedCubeTextures; } void resetCameraParams(); void updateCameraDir(int32_t faceIdx); - Vec2 getRenderArea() const; + Vec2 renderArea() const; void packBackgroundColor(); bool isRGBE() const; diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index 2a2fff63cae..f80fd18cece 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -603,6 +603,7 @@ using namespace cc; %attribute(cc::scene::ReflectionProbe, cc::TextureCube*, cubemap, getCubeMap, setCubeMap); %attribute(cc::scene::ReflectionProbe, cc::Node*, node, getNode); %attribute(cc::scene::ReflectionProbe, cc::RenderTexture*, realtimePlanarTexture, getRealtimePlanarTexture); +%attribute(cc::scene::ReflectionProbe, cc::scene::Camera*, camera, getCamera); %attribute(cc::SceneGlobals, bool, bakedWithStationaryMainLight, getBakedWithStationaryMainLight, setBakedWithStationaryMainLight); %attribute(cc::SceneGlobals, bool, bakedWithHighpLightmap, getBakedWithHighpLightmap, setBakedWithHighpLightmap); From 0b8b6981b687ad4850ce0b7c7075b5ad414a38d2 Mon Sep 17 00:00:00 2001 From: zxx43 Date: Fri, 18 Aug 2023 10:22:12 +0800 Subject: [PATCH 182/232] fix uimeshrender in native (#15879) * fix uimeshrender in native * fix eslint --- cocos/2d/components/ui-mesh-renderer.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index 1cf5f6791f7..62bc1de4628 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -170,8 +170,10 @@ export class UIMeshRenderer extends Component { this._UIModelNativeProxy.clearModels(); this._renderEntity.clearDynamicRenderDrawInfos(); for (let i = 0; i < models.length; i++) { - this._uploadRenderData(i); - this._UIModelNativeProxy.updateModels(models[i]); + if (models[i].enabled) { + this._uploadRenderData(i); + this._UIModelNativeProxy.updateModels(models[i]); + } } this._UIModelNativeProxy.attachDrawInfo(); } @@ -189,6 +191,7 @@ export class UIMeshRenderer extends Component { // please fix the type @holycanvas // issue: https://github.com/cocos/cocos-engine/issues/14637 this._renderData = renderData as unknown as RenderData; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._renderData.material = this._modelComponent!.getMaterialInstance(index); } } @@ -201,6 +204,7 @@ export class UIMeshRenderer extends Component { * 它可能会组装额外的渲染数据到顶点数据缓冲区,也可能只是重置一些渲染状态。 * 注意:不要手动调用该函数,除非你理解整个流程。 */ + // eslint-disable-next-line @typescript-eslint/no-empty-function public postUpdateAssembler (render: IBatcher): void { // No behavior for this component } @@ -253,6 +257,7 @@ export class UIMeshRenderer extends Component { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ + // eslint-disable-next-line @typescript-eslint/no-empty-function public setNodeDirty (): void { // No behavior for this component } @@ -260,6 +265,7 @@ export class UIMeshRenderer extends Component { /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ + // eslint-disable-next-line @typescript-eslint/no-empty-function public setTextureDirty (): void { // No behavior for this component } From cf8ceed66124a94b71b881337c209812accddc4a Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Fri, 18 Aug 2023 10:47:59 +0800 Subject: [PATCH 183/232] V3.8.1 cct trigger (#15613) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * physx ts 支持 # Conflicts: # cocos/physics/framework/components/character-controllers/character-controller.ts # cocos/physics/framework/components/colliders/collider.ts # cocos/physics/physx/physx-world.ts * add bullet-character-controller trigger events * physx c++ add cct trigger * tweaks * tweaks * tweaks * tweak * tweaks * physics jsb: emitCCTShapeEvent --> emitCCTCollisionEvent --- cocos/physics/bullet/bullet-cache.ts | 10 +- cocos/physics/bullet/bullet-world.ts | 413 ++++++++++++------ .../bullet-character-controller.ts | 4 + .../character-controller.ts | 30 +- .../components/colliders/collider.ts | 19 +- cocos/physics/framework/physics-interface.ts | 8 + .../physx-box-character-controller.ts | 6 +- .../physx-capsule-character-controller.ts | 6 +- .../physx-character-controller.ts | 7 + cocos/physics/physx/physx-world.ts | 117 ++++- cocos/physics/utils/util.ts | 9 +- exports/physics-framework.ts | 1 + .../bindings/manual/jsb_conversions_spec.cpp | 12 + .../bindings/manual/jsb_conversions_spec.h | 1 + .../cocos/physics/physx/PhysXEventManager.cpp | 98 ++++- .../cocos/physics/physx/PhysXEventManager.h | 2 + native/cocos/physics/physx/PhysXWorld.h | 3 + .../PhysXCharacterController.cpp | 13 +- .../PhysXCharacterController.h | 3 + native/cocos/physics/sdk/World.cpp | 4 + native/cocos/physics/sdk/World.h | 1 + native/cocos/physics/spec/IWorld.h | 12 + platforms/native/engine/jsb-physics.js | 87 +++- 23 files changed, 673 insertions(+), 193 deletions(-) diff --git a/cocos/physics/bullet/bullet-cache.ts b/cocos/physics/bullet/bullet-cache.ts index 3d9e0f9b3f1..fe8c0567173 100644 --- a/cocos/physics/bullet/bullet-cache.ts +++ b/cocos/physics/bullet/bullet-cache.ts @@ -22,8 +22,9 @@ THE SOFTWARE. */ -import { Collider, TriggerEventType, CollisionEventType, IContactEquation } from '../../../exports/physics-framework'; +import { Collider, TriggerEventType, CollisionEventType, IContactEquation, CharacterController } from '../../../exports/physics-framework'; import { Vec3, Quat, Mat4 } from '../../core'; +import { CharacterTriggerEventType } from '../framework'; import { bt } from './instantiated'; export const TriggerEventObject = { @@ -41,6 +42,13 @@ export const CollisionEventObject = { impl: null, }; +export const CharacterTriggerEventObject = { + type: 'onControllerTriggerEnter' as unknown as CharacterTriggerEventType, + collider: null as unknown as Collider, + characterController: null as unknown as CharacterController, + impl: null, +}; + export class BulletCache { private static _instance: BulletCache; static get instance (): BulletCache { diff --git a/cocos/physics/bullet/bullet-world.ts b/cocos/physics/bullet/bullet-world.ts index 298b1683329..431158135f4 100644 --- a/cocos/physics/bullet/bullet-world.ts +++ b/cocos/physics/bullet/bullet-world.ts @@ -28,7 +28,7 @@ import { BulletRigidBody } from './bullet-rigid-body'; import { BulletShape } from './shapes/bullet-shape'; import { ArrayCollisionMatrix } from '../utils/array-collision-matrix'; import { TupleDictionary } from '../utils/tuple-dictionary'; -import { TriggerEventObject, CollisionEventObject, CC_V3_0, CC_V3_1, CC_V3_2, BulletCache } from './bullet-cache'; +import { TriggerEventObject, CollisionEventObject, CC_V3_0, CC_V3_1, CC_V3_2, BulletCache, CharacterTriggerEventObject } from './bullet-cache'; import { bullet2CocosVec3, cocos2BulletQuat, cocos2BulletVec3 } from './bullet-utils'; import { IRaycastOptions, IPhysicsWorld } from '../spec/i-physics-world'; import { PhysicsRayResult, PhysicsMaterial, CharacterControllerContact } from '../framework'; @@ -129,7 +129,8 @@ export class BulletWorld implements IPhysicsWorld { readonly contactsDic = new TupleDictionary(); readonly oldContactsDic = new TupleDictionary(); readonly cctShapeEventDic = new TupleDictionary(); - + readonly cctContactsDic = new TupleDictionary(); + readonly cctOldContactsDic = new TupleDictionary(); private static _sweepBoxGeometry: number; private static _sweepSphereGeometry: number; private static _sweepCapsuleGeometry: number; @@ -493,66 +494,127 @@ export class BulletWorld implements IPhysicsWorld { if (this._needEmitEvents) { this.gatherConatactData(); - // is enter or stay - let dicL = this.contactsDic.getLength(); - while (dicL--) { - contactsPool.push.apply(contactsPool, CollisionEventObject.contacts as BulletContactData[]); - CollisionEventObject.contacts.length = 0; - const key = this.contactsDic.getKeyByIndex(dicL); - const data = this.contactsDic.getDataByKey(key); - const shape0: BulletShape = data.shape0; - const shape1: BulletShape = data.shape1; - this.oldContactsDic.set(shape0.id, shape1.id, data); - const collider0 = shape0.collider; - const collider1 = shape1.collider; - if (collider0 && collider1) { - const isTrigger = collider0.isTrigger || collider1.isTrigger; - if (isTrigger) { - if (this.triggerArrayMat.get(shape0.id, shape1.id)) { - TriggerEventObject.type = 'onTriggerStay'; - } else { - TriggerEventObject.type = 'onTriggerEnter'; - this.triggerArrayMat.set(shape0.id, shape1.id, true); - } - TriggerEventObject.impl = data.impl; //btPersistentManifold - TriggerEventObject.selfCollider = collider0; - TriggerEventObject.otherCollider = collider1; - collider0.emit(TriggerEventObject.type, TriggerEventObject); - - TriggerEventObject.selfCollider = collider1; - TriggerEventObject.otherCollider = collider0; - collider1.emit(TriggerEventObject.type, TriggerEventObject); - this._needSyncAfterEvents = true; + + this.emitCollisionAndTriggerEvent(); + // emit cct trigger events + this.emitCCTTriggerEvent(); + } + + // emit cct collision events + if (this._needEmitCCTEvents) { + this.emitCCTCollisionEvent(); + } + } + + private emitCollisionAndTriggerEvent (): void { + // is enter or stay + let dicL = this.contactsDic.getLength(); + while (dicL--) { + contactsPool.push.apply(contactsPool, CollisionEventObject.contacts as BulletContactData[]); + CollisionEventObject.contacts.length = 0; + const key = this.contactsDic.getKeyByIndex(dicL); + const data = this.contactsDic.getDataByKey(key); + const shape0: BulletShape = data.shape0; + const shape1: BulletShape = data.shape1; + this.oldContactsDic.set(shape0.id, shape1.id, data); + const collider0 = shape0.collider; + const collider1 = shape1.collider; + if (collider0 && collider1) { + const isTrigger = collider0.isTrigger || collider1.isTrigger; + if (isTrigger) { + if (this.triggerArrayMat.get(shape0.id, shape1.id)) { + TriggerEventObject.type = 'onTriggerStay'; } else { - const body0 = collider0.attachedRigidBody; - const body1 = collider1.attachedRigidBody; - if (body0 && body1) { - if (body0.isSleeping && body1.isSleeping) continue; - } else if (!body0 && body1) { - if (body1.isSleeping) continue; - } else if (!body1 && body0) { - if (body0.isSleeping) continue; - } - if (this.collisionArrayMat.get(shape0.id, shape1.id)) { - CollisionEventObject.type = 'onCollisionStay'; + TriggerEventObject.type = 'onTriggerEnter'; + this.triggerArrayMat.set(shape0.id, shape1.id, true); + } + TriggerEventObject.impl = data.impl; //btPersistentManifold + TriggerEventObject.selfCollider = collider0; + TriggerEventObject.otherCollider = collider1; + collider0.emit(TriggerEventObject.type, TriggerEventObject); + + TriggerEventObject.selfCollider = collider1; + TriggerEventObject.otherCollider = collider0; + collider1.emit(TriggerEventObject.type, TriggerEventObject); + this._needSyncAfterEvents = true; + } else { + const body0 = collider0.attachedRigidBody; + const body1 = collider1.attachedRigidBody; + if (body0 && body1) { + if (body0.isSleeping && body1.isSleeping) continue; + } else if (!body0 && body1) { + if (body1.isSleeping) continue; + } else if (!body1 && body0) { + if (body0.isSleeping) continue; + } + if (this.collisionArrayMat.get(shape0.id, shape1.id)) { + CollisionEventObject.type = 'onCollisionStay'; + } else { + CollisionEventObject.type = 'onCollisionEnter'; + this.collisionArrayMat.set(shape0.id, shape1.id, true); + } + + for (let i = 0; i < data.contacts.length; i++) { + const cq = data.contacts[i]; //btManifoldPoint + if (contactsPool.length > 0) { + const c = contactsPool.pop(); + c!.impl = cq; //btManifoldPoint + CollisionEventObject.contacts.push(c!); } else { - CollisionEventObject.type = 'onCollisionEnter'; - this.collisionArrayMat.set(shape0.id, shape1.id, true); + const c = new BulletContactData(CollisionEventObject); + c.impl = cq; //btManifoldPoint + CollisionEventObject.contacts.push(c); } + } + CollisionEventObject.impl = data.impl; //btPersistentManifold + CollisionEventObject.selfCollider = collider0; + CollisionEventObject.otherCollider = collider1; + collider0.emit(CollisionEventObject.type, CollisionEventObject); + + CollisionEventObject.selfCollider = collider1; + CollisionEventObject.otherCollider = collider0; + collider1.emit(CollisionEventObject.type, CollisionEventObject); + this._needSyncAfterEvents = true; + } - for (let i = 0; i < data.contacts.length; i++) { - const cq = data.contacts[i]; //btManifoldPoint - if (contactsPool.length > 0) { - const c = contactsPool.pop(); - c!.impl = cq; //btManifoldPoint - CollisionEventObject.contacts.push(c!); - } else { - const c = new BulletContactData(CollisionEventObject); - c.impl = cq; //btManifoldPoint - CollisionEventObject.contacts.push(c); - } + if (this.oldContactsDic.get(shape0.id, shape1.id) == null) { + this.oldContactsDic.set(shape0.id, shape1.id, data); + } + } + } + + // is exit + let oldDicL = this.oldContactsDic.getLength(); + while (oldDicL--) { + const key = this.oldContactsDic.getKeyByIndex(oldDicL); + const data = this.oldContactsDic.getDataByKey(key); + const shape0: BulletShape = data.shape0; + const shape1: BulletShape = data.shape1; + const collider0 = shape0.collider; + const collider1 = shape1.collider; + if (collider0 && collider1) { + const isTrigger = collider0.isTrigger || collider1.isTrigger; + if (this.contactsDic.getDataByKey(key) == null) { + if (isTrigger) { + if (this.triggerArrayMat.get(shape0.id, shape1.id)) { + TriggerEventObject.type = 'onTriggerExit'; + TriggerEventObject.selfCollider = collider0; + TriggerEventObject.otherCollider = collider1; + collider0.emit(TriggerEventObject.type, TriggerEventObject); + + TriggerEventObject.selfCollider = collider1; + TriggerEventObject.otherCollider = collider0; + collider1.emit(TriggerEventObject.type, TriggerEventObject); + + this.triggerArrayMat.set(shape0.id, shape1.id, false); + this.oldContactsDic.set(shape0.id, shape1.id, null); + this._needSyncAfterEvents = true; } - CollisionEventObject.impl = data.impl; //btPersistentManifold + } else if (this.collisionArrayMat.get(shape0.id, shape1.id)) { + contactsPool.push.apply(contactsPool, CollisionEventObject.contacts as BulletContactData[]); + CollisionEventObject.contacts.length = 0; + + CollisionEventObject.type = 'onCollisionExit'; CollisionEventObject.selfCollider = collider0; CollisionEventObject.otherCollider = collider1; collider0.emit(CollisionEventObject.type, CollisionEventObject); @@ -560,89 +622,111 @@ export class BulletWorld implements IPhysicsWorld { CollisionEventObject.selfCollider = collider1; CollisionEventObject.otherCollider = collider0; collider1.emit(CollisionEventObject.type, CollisionEventObject); - this._needSyncAfterEvents = true; - } - if (this.oldContactsDic.get(shape0.id, shape1.id) == null) { - this.oldContactsDic.set(shape0.id, shape1.id, data); + this.collisionArrayMat.set(shape0.id, shape1.id, false); + this.oldContactsDic.set(shape0.id, shape1.id, null); + this._needSyncAfterEvents = true; } } } + } - // is exit - let oldDicL = this.oldContactsDic.getLength(); - while (oldDicL--) { - const key = this.oldContactsDic.getKeyByIndex(oldDicL); - const data = this.oldContactsDic.getDataByKey(key); - const shape0: BulletShape = data.shape0; - const shape1: BulletShape = data.shape1; - const collider0 = shape0.collider; - const collider1 = shape1.collider; - if (collider0 && collider1) { - const isTrigger = collider0.isTrigger || collider1.isTrigger; - if (this.contactsDic.getDataByKey(key) == null) { - if (isTrigger) { - if (this.triggerArrayMat.get(shape0.id, shape1.id)) { - TriggerEventObject.type = 'onTriggerExit'; - TriggerEventObject.selfCollider = collider0; - TriggerEventObject.otherCollider = collider1; - collider0.emit(TriggerEventObject.type, TriggerEventObject); - - TriggerEventObject.selfCollider = collider1; - TriggerEventObject.otherCollider = collider0; - collider1.emit(TriggerEventObject.type, TriggerEventObject); - - this.triggerArrayMat.set(shape0.id, shape1.id, false); - this.oldContactsDic.set(shape0.id, shape1.id, null); - this._needSyncAfterEvents = true; - } - } else if (this.collisionArrayMat.get(shape0.id, shape1.id)) { - contactsPool.push.apply(contactsPool, CollisionEventObject.contacts as BulletContactData[]); - CollisionEventObject.contacts.length = 0; - - CollisionEventObject.type = 'onCollisionExit'; - CollisionEventObject.selfCollider = collider0; - CollisionEventObject.otherCollider = collider1; - collider0.emit(CollisionEventObject.type, CollisionEventObject); + this.contactsDic.reset(); + } + + private emitCCTTriggerEvent (): void { + // is enter or stay + let dicL = this.cctContactsDic.getLength(); + while (dicL--) { + const key = this.cctContactsDic.getKeyByIndex(dicL); + const data = this.cctContactsDic.getDataByKey(key); + const shape: BulletShape = data.shape; + const cct: BulletCharacterController = data.cct; + this.cctOldContactsDic.set(shape.id, cct.id, data); + const collider = shape.collider; + const characterController = cct.characterController; + if (collider && characterController) { + const isTrigger = collider.isTrigger; + if (isTrigger) { + if (this.triggerArrayMat.get(shape.id, cct.id)) { + CharacterTriggerEventObject.type = 'onControllerTriggerStay'; + } else { + CharacterTriggerEventObject.type = 'onControllerTriggerEnter'; + this.triggerArrayMat.set(shape.id, cct.id, true); + } + CharacterTriggerEventObject.impl = data.impl; //btPersistentManifold + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + collider.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject); + + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + characterController.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject); + this._needSyncAfterEvents = true; + } - CollisionEventObject.selfCollider = collider1; - CollisionEventObject.otherCollider = collider0; - collider1.emit(CollisionEventObject.type, CollisionEventObject); + if (this.cctOldContactsDic.get(shape.id, cct.id) == null) { + this.cctOldContactsDic.set(shape.id, cct.id, data); + } + } + } - this.collisionArrayMat.set(shape0.id, shape1.id, false); - this.oldContactsDic.set(shape0.id, shape1.id, null); + // is exit + let oldDicL = this.cctOldContactsDic.getLength(); + while (oldDicL--) { + const key = this.cctOldContactsDic.getKeyByIndex(oldDicL); + const data = this.cctOldContactsDic.getDataByKey(key); + const shape: BulletShape = data.shape; + const cct: BulletCharacterController = data.cct; + const collider = shape.collider; + const characterController = cct.characterController; + if (collider && characterController) { + const isTrigger = collider.isTrigger; + if (this.cctContactsDic.getDataByKey(key) == null) { + if (isTrigger) { + if (this.triggerArrayMat.get(shape.id, cct.id)) { + CharacterTriggerEventObject.type = 'onControllerTriggerExit'; + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + collider.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject); + + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + characterController.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject); + + this.triggerArrayMat.set(shape.id, cct.id, false); + this.cctOldContactsDic.set(shape.id, cct.id, null); this._needSyncAfterEvents = true; } } } } - - this.contactsDic.reset(); } - // emit cct events - if (this._needEmitCCTEvents) { - let dicL = this.cctShapeEventDic.getLength(); - while (dicL--) { - const key = this.cctShapeEventDic.getKeyByIndex(dicL); - const data = this.cctShapeEventDic.getDataByKey(key); - const cct: BulletCharacterController = data.BulletCharacterController; - const shape: BulletShape = data.BulletShape; - const worldPos = data.worldPos as IVec3Like; - const worldNormal = data.worldNormal as IVec3Like; - const motionDir = data.motionDir as IVec3Like; - const motionLength = data.motionLength; - emitHit.controller = cct.characterController; - emitHit.collider = shape.collider; - emitHit.worldPosition.set(worldPos.x, worldPos.y, worldPos.z); - emitHit.worldNormal.set(worldNormal.x, worldNormal.y, worldNormal.z); - emitHit.motionDirection.set(motionDir.x, motionDir.y, motionDir.z); - emitHit.motionLength = motionLength; - emitHit.controller?.emit('onControllerColliderHit', emitHit); - this._needSyncAfterEvents = true; - } - this.cctShapeEventDic.reset(); + this.cctContactsDic.reset(); + } + + private emitCCTCollisionEvent (): void { + let dicL = this.cctShapeEventDic.getLength(); + while (dicL--) { + const key = this.cctShapeEventDic.getKeyByIndex(dicL); + const data = this.cctShapeEventDic.getDataByKey(key); + const cct: BulletCharacterController = data.BulletCharacterController; + const shape: BulletShape = data.BulletShape; + const worldPos = data.worldPos as IVec3Like; + const worldNormal = data.worldNormal as IVec3Like; + const motionDir = data.motionDir as IVec3Like; + const motionLength = data.motionLength; + emitHit.controller = cct.characterController; + emitHit.collider = shape.collider; + emitHit.worldPosition.set(worldPos.x, worldPos.y, worldPos.z); + emitHit.worldNormal.set(worldNormal.x, worldNormal.y, worldNormal.z); + emitHit.motionDirection.set(motionDir.x, motionDir.y, motionDir.z); + emitHit.motionLength = motionLength; + emitHit.controller?.emit('onControllerColliderHit', emitHit); + this._needSyncAfterEvents = true; } + this.cctShapeEventDic.reset(); } gatherConatactData (): void { @@ -654,22 +738,71 @@ export class BulletWorld implements IPhysicsWorld { const manifoldPoint = bt.PersistentManifold_getContactPoint(manifold, j);//btManifoldPoint const s0 = bt.ManifoldPoint_getShape0(manifoldPoint); const s1 = bt.ManifoldPoint_getShape1(manifoldPoint); - const shape0: BulletShape = BulletCache.getWrapper(s0, BulletShape.TYPE); - const shape1: BulletShape = BulletCache.getWrapper(s1, BulletShape.TYPE); - if (shape0 && shape1) { - if (shape0.collider.needTriggerEvent || shape1.collider.needTriggerEvent - || shape0.collider.needCollisionEvent || shape1.collider.needCollisionEvent - ) { - // current contact - let item = this.contactsDic.get(shape0.id, shape1.id); - if (!item) { - item = this.contactsDic.set( - shape0.id, - shape1.id, - { shape0, shape1, contacts: [], impl: manifold }, - ); + + let processed = false; + + if (!processed) { + const shape0: BulletShape = BulletCache.getWrapper(s0, BulletShape.TYPE); + const shape1: BulletShape = BulletCache.getWrapper(s1, BulletShape.TYPE); + if (shape0 && shape1) { + processed = true; + if (shape0.collider.needTriggerEvent || shape1.collider.needTriggerEvent + || shape0.collider.needCollisionEvent || shape1.collider.needCollisionEvent) { + // current contact + let item = this.contactsDic.get(shape0.id, shape1.id); + if (!item) { + item = this.contactsDic.set( + shape0.id, + shape1.id, + { shape0, shape1, contacts: [], impl: manifold }, + ); + } + item.contacts.push(manifoldPoint);//btManifoldPoint + } + } + } + + //cct - collider trigger event + if (!processed) { + const shape: BulletShape = BulletCache.getWrapper(s0, BulletShape.TYPE); + const cct: BulletCharacterController = BulletCache.getWrapper(s1, bt.CCT_CACHE_NAME); + if (shape && cct) { + processed = true; + if (shape.collider.needTriggerEvent) { + // current contact + let item = this.cctContactsDic.get(shape.id, cct.id); + if (!item) { + item = this.cctContactsDic.set( + shape.id, + cct.id, + { shape, cct, contacts: [], impl: manifold }, + ); + } + item.contacts.push(manifoldPoint);//btManifoldPoint + processed = true; + } + } + } + + //cct - collider trigger event + if (!processed) { + const cct: BulletCharacterController = BulletCache.getWrapper(s0, bt.CCT_CACHE_NAME); + const shape: BulletShape = BulletCache.getWrapper(s1, BulletShape.TYPE); + if (shape && cct) { + processed = true; + if (shape.collider.needTriggerEvent) { + // current contact + let item = this.cctContactsDic.get(shape.id, cct.id); + if (!item) { + item = this.cctContactsDic.set( + shape.id, + cct.id, + { shape, cct, contacts: [], impl: manifold }, + ); + } + item.contacts.push(manifoldPoint);//btManifoldPoint + processed = true; } - item.contacts.push(manifoldPoint);//btManifoldPoint } } } diff --git a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts index 4d6ed88d53b..7c50e656fd5 100644 --- a/cocos/physics/bullet/character-controllers/bullet-character-controller.ts +++ b/cocos/physics/bullet/character-controllers/bullet-character-controller.ts @@ -48,6 +48,8 @@ export abstract class BulletCharacterController implements IBaseCharacterControl protected _dirty = false; private _collisionFilterGroup: number = PhysicsGroup.DEFAULT; private _collisionFilterMask = -1; + private static idCounter = 0; + readonly id = BulletCharacterController.idCounter++; get isEnabled (): boolean { return this._isEnabled; } get impl (): number { @@ -86,6 +88,8 @@ export abstract class BulletCharacterController implements IBaseCharacterControl setWrapper (): void { BulletCache.setWrapper(this._impl, bt.CCT_CACHE_NAME, this); + const cctCollisionShapeImpl = bt.CharacterController_getCollisionShape(this.impl); + BulletCache.setWrapper(cctCollisionShapeImpl, bt.CCT_CACHE_NAME, this); } onEnable (): void { diff --git a/cocos/physics/framework/components/character-controllers/character-controller.ts b/cocos/physics/framework/components/character-controllers/character-controller.ts index 73fa1e0df99..ef6a0509058 100644 --- a/cocos/physics/framework/components/character-controllers/character-controller.ts +++ b/cocos/physics/framework/components/character-controllers/character-controller.ts @@ -30,7 +30,7 @@ import { Vec3, warn, CCFloat, Eventify } from '../../../../core'; import { Component } from '../../../../scene-graph'; import { IBaseCharacterController } from '../../../spec/i-character-controller'; import { ECharacterControllerType } from '../../physics-enum'; -import { CharacterCollisionEventType } from '../../physics-interface'; +import { CharacterCollisionEventType, CharacterTriggerEventType, TriggerEventType } from '../../physics-interface'; import { selector, createCharacterController } from '../../physics-selector'; import { PhysicsSystem } from '../../physics-system'; @@ -251,6 +251,7 @@ export class CharacterController extends Eventify(Component) { private _centerWorldPosition: Vec3 = new Vec3(); protected _needCollisionEvent = false; + protected _needTriggerEvent = false; protected get _isInitialized (): boolean { if (this._cct === null || !this._initialized) { @@ -285,6 +286,7 @@ export class CharacterController extends Eventify(Component) { protected onDestroy (): void { if (this._cct) { this._needCollisionEvent = false; + this._needTriggerEvent = false; this._cct.updateEventListener(); this._cct.onDestroy!(); this._cct = null; @@ -372,7 +374,8 @@ export class CharacterController extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public on void>(type: CharacterCollisionEventType, callback: TFunction, target?, once?: boolean): any { + public on void>(type: CharacterTriggerEventType | CharacterCollisionEventType, + callback: TFunction, target?, once?: boolean): any { const ret = super.on(type, callback, target, once); this._updateNeedEvent(type); return ret; @@ -387,7 +390,7 @@ export class CharacterController extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public off (type: CharacterCollisionEventType, callback?: (...any) => void, target?): void { + public off (type: CharacterTriggerEventType | CharacterCollisionEventType, callback?: (...any) => void, target?): void { super.off(type, callback, target); this._updateNeedEvent(); } @@ -401,7 +404,8 @@ export class CharacterController extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public once void>(type: CharacterCollisionEventType, callback: TFunction, target?): any { + public once void>(type: CharacterTriggerEventType | CharacterCollisionEventType, + callback: TFunction, target?): any { // TODO: callback invoker now is a entity, after `once` will not calling the upper `off`. const ret = super.once(type, callback, target); this._updateNeedEvent(type); @@ -504,14 +508,28 @@ export class CharacterController extends Eventify(Component) { return this._needCollisionEvent; } + public get needTriggerEvent (): boolean { + return this._needTriggerEvent; + } + private _updateNeedEvent (type?: string): void { if (this.isValid) { if (type !== undefined) { if (type === 'onControllerColliderHit') { this._needCollisionEvent = true; } - } else if (!this.hasEventListener('onControllerColliderHit')) { - this._needCollisionEvent = false; + if (type === 'onControllerTriggerEnter' || type === 'onControllerTriggerStay' || type === 'onControllerTriggerExit') { + this._needTriggerEvent = true; + } + } else { + if (!this.hasEventListener('onControllerColliderHit')) { + this._needCollisionEvent = false; + } + if (!(this.hasEventListener('onControllerTriggerEnter') + || this.hasEventListener('onControllerTriggerStay') + || this.hasEventListener('onControllerTriggerExit'))) { + this._needTriggerEvent = false; + } } if (this._cct) this._cct.updateEventListener(); } diff --git a/cocos/physics/framework/components/colliders/collider.ts b/cocos/physics/framework/components/colliders/collider.ts index 2c8ef0ce264..8caffad63e7 100644 --- a/cocos/physics/framework/components/colliders/collider.ts +++ b/cocos/physics/framework/components/colliders/collider.ts @@ -26,7 +26,7 @@ import { ccclass, tooltip, displayOrder, displayName, readOnly, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Eventify, Vec3, error, geometry } from '../../../../core'; -import { CollisionEventType, TriggerEventType } from '../../physics-interface'; +import { CharacterTriggerEventType, CollisionEventType, TriggerEventType } from '../../physics-interface'; import { RigidBody } from '../rigid-body'; import { PhysicsMaterial } from '../../assets/physics-material'; import { Component, Node } from '../../../../scene-graph'; @@ -248,7 +248,8 @@ export class Collider extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public on void>(type: TriggerEventType | CollisionEventType, callback: TFunction, target?, once?: boolean): any { + public on void>(type: TriggerEventType | CollisionEventType | CharacterTriggerEventType, + callback: TFunction, target?, once?: boolean): any { const ret = super.on(type, callback, target, once); this._updateNeedEvent(type); return ret; @@ -263,7 +264,7 @@ export class Collider extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public off (type: TriggerEventType | CollisionEventType, callback?: (...any) => void, target?): void { + public off (type: TriggerEventType | CollisionEventType | CharacterTriggerEventType, callback?: (...any) => void, target?): void { super.off(type, callback, target); this._updateNeedEvent(); } @@ -277,7 +278,8 @@ export class Collider extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public once void>(type: TriggerEventType | CollisionEventType, callback: TFunction, target?): any { + public once void>(type: TriggerEventType | CollisionEventType | CharacterTriggerEventType, + callback: TFunction, target?): any { // TODO: callback invoker now is a entity, after `once` will not calling the upper `off`. const ret = super.once(type, callback, target); this._updateNeedEvent(type); @@ -448,13 +450,18 @@ export class Collider extends Eventify(Component) { if (type === 'onCollisionEnter' || type === 'onCollisionStay' || type === 'onCollisionExit') { this._needCollisionEvent = true; } - if (type === 'onTriggerEnter' || type === 'onTriggerStay' || type === 'onTriggerExit') { + if (type === 'onTriggerEnter' || type === 'onTriggerStay' || type === 'onTriggerExit' + || type === 'onControllerTriggerEnter' || type === 'onControllerTriggerStay' || type === 'onControllerTriggerExit') { this._needTriggerEvent = true; } } else { if (!(this.hasEventListener('onTriggerEnter') || this.hasEventListener('onTriggerStay') - || this.hasEventListener('onTriggerExit'))) { + || this.hasEventListener('onTriggerExit') + || this.hasEventListener('onControllerTriggerEnter') + || this.hasEventListener('onControllerTriggerStay') + || this.hasEventListener('onControllerTriggerExit') + )) { this._needTriggerEvent = false; } if (!(this.hasEventListener('onCollisionEnter') diff --git a/cocos/physics/framework/physics-interface.ts b/cocos/physics/framework/physics-interface.ts index e113dee2128..452ee6e63d0 100644 --- a/cocos/physics/framework/physics-interface.ts +++ b/cocos/physics/framework/physics-interface.ts @@ -242,6 +242,14 @@ export type CollisionEventType = 'onCollisionEnter' | 'onCollisionStay' | 'onCol */ export type CollisionCallback = (event?: ICollisionEvent) => void; +/** + * @en + * The definition of the trigger event of the character controller. + * @zh + * 角色控制器触发事件的值类型定义。 + */ +export type CharacterTriggerEventType = 'onControllerTriggerEnter' | 'onControllerTriggerStay' | 'onControllerTriggerExit'; + /** * @en * Value type definitions fot the collision events of character controller. diff --git a/cocos/physics/physx/character-controllers/physx-box-character-controller.ts b/cocos/physics/physx/character-controllers/physx-box-character-controller.ts index b8c96ee72f1..3d58ac36e8e 100644 --- a/cocos/physics/physx/character-controllers/physx-box-character-controller.ts +++ b/cocos/physics/physx/character-controllers/physx-box-character-controller.ts @@ -67,7 +67,11 @@ export class PhysXBoxCharacterController extends PhysXCharacterController implem controllerDesc.setReportCallback(PX.PxUserControllerHitReport.implement(physxWorld.callback.controllerHitReportCB)); this._impl = PX.createBoxCharacterController(physxWorld.controllerManager, controllerDesc); - if (this._impl.$$) PX.IMPL_PTR[this._impl.$$.ptr] = this; + if (this._impl.$$) { + PX.IMPL_PTR[this._impl.$$.ptr] = this; + const shapePtr = this._impl.getShape().$$.ptr; + PX.IMPL_PTR[shapePtr] = this; + } this.updateScale(); } diff --git a/cocos/physics/physx/character-controllers/physx-capsule-character-controller.ts b/cocos/physics/physx/character-controllers/physx-capsule-character-controller.ts index c2c7e202622..9e4dfdd2b50 100644 --- a/cocos/physics/physx/character-controllers/physx-capsule-character-controller.ts +++ b/cocos/physics/physx/character-controllers/physx-capsule-character-controller.ts @@ -68,7 +68,11 @@ export class PhysXCapsuleCharacterController extends PhysXCharacterController im controllerDesc.setReportCallback(PX.PxUserControllerHitReport.implement(physxWorld.callback.controllerHitReportCB)); this._impl = PX.createCapsuleCharacterController(physxWorld.controllerManager, controllerDesc); - if (this._impl.$$) PX.IMPL_PTR[this._impl.$$.ptr] = this; + if (this._impl.$$) { + PX.IMPL_PTR[this._impl.$$.ptr] = this; + const shapePtr = this._impl.getShape().$$.ptr; + PX.IMPL_PTR[shapePtr] = this; + } this.updateScale(); } diff --git a/cocos/physics/physx/character-controllers/physx-character-controller.ts b/cocos/physics/physx/character-controllers/physx-character-controller.ts index da7d3e9d703..a5361c282ec 100644 --- a/cocos/physics/physx/character-controllers/physx-character-controller.ts +++ b/cocos/physics/physx/character-controllers/physx-character-controller.ts @@ -45,6 +45,9 @@ export class PhysXCharacterController implements IBaseCharacterController { protected _word3 = 0; protected _overlapRecovery = true; + readonly id: number; + private static idCounter = 0; + get isEnabled (): boolean { return this._isEnabled; } get impl (): any { /* eslint-disable @typescript-eslint/no-unsafe-return */ @@ -63,6 +66,7 @@ export class PhysXCharacterController implements IBaseCharacterController { } constructor () { + this.id = PhysXCharacterController.idCounter++; this._filterData = { word0: 1, word1: 1, word2: 1, word3: 0 }; } @@ -116,6 +120,9 @@ export class PhysXCharacterController implements IBaseCharacterController { if (this._impl.$$) { PX.IMPL_PTR[this._impl.$$.ptr] = null; delete PX.IMPL_PTR[this._impl.$$.ptr]; + const shapePtr = this._impl.getShape().$$.ptr; + PX.IMPL_PTR[shapePtr] = null; + delete PX.IMPL_PTR[shapePtr]; } this._impl.release(); this._impl = null; diff --git a/cocos/physics/physx/physx-world.ts b/cocos/physics/physx/physx-world.ts index d0ee6c1185a..6ffe301e263 100644 --- a/cocos/physics/physx/physx-world.ts +++ b/cocos/physics/physx/physx-world.ts @@ -24,7 +24,8 @@ /* eslint-disable @typescript-eslint/no-unsafe-return */ import { IPhysicsWorld, IRaycastOptions } from '../spec/i-physics-world'; -import { PhysicsMaterial, PhysicsRayResult, CollisionEventType, TriggerEventType, CharacterControllerContact } from '../framework'; +import { PhysicsMaterial, PhysicsRayResult, CollisionEventType, TriggerEventType, CharacterTriggerEventType, + CharacterControllerContact } from '../framework'; import { error, RecyclePool, js, IVec3Like, geometry, IQuatLike, Vec3, Quat } from '../../core'; import { IBaseConstraint } from '../spec/i-physics-constraint'; import { PhysXRigidBody } from './physx-rigid-body'; @@ -35,7 +36,7 @@ import { import { PhysXSharedBody } from './physx-shared-body'; import { TupleDictionary } from '../utils/tuple-dictionary'; import { PhysXContactEquation } from './physx-contact-equation'; -import { CollisionEventObject, TriggerEventObject, VEC3_0 } from '../utils/util'; +import { CollisionEventObject, TriggerEventObject, CharacterTriggerEventObject, VEC3_0 } from '../utils/util'; import { PhysXShape } from './shapes/physx-shape'; import { EFilterDataWord3 } from './physx-enum'; import { PhysXInstance } from './physx-instance'; @@ -244,7 +245,8 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { gatherEvents(this); PhysXCallback.emitTriggerEvent(); PhysXCallback.emitCollisionEvent(); - PhysXCallback.emitCCTShapeEvent(); + PhysXCallback.emitCCTCollisionEvent(); + PhysXCallback.emitCCTTriggerEvent(); } } @@ -267,6 +269,12 @@ interface ICollisionEventItem { offset: number, } +interface ITriggerEventItemCCT { + a: PhysXShape, + b: PhysXCharacterController, + times: number, +} + const triggerEventBeginDic = new TupleDictionary(); const triggerEventEndDic = new TupleDictionary(); const triggerEventsPool: ITriggerEventItem[] = []; @@ -275,6 +283,9 @@ const contactEventsPool: ICollisionEventItem[] = []; const contactsPool: [] = []; const cctShapeEventDic = new TupleDictionary(); const emitHit = new CharacterControllerContact(); +const cctTriggerEventBeginDic = new TupleDictionary(); +const cctTriggerEventEndDic = new TupleDictionary(); +const cctTriggerEventsPool: ITriggerEventItemCCT[] = []; const PhysXCallback = { eventCallback: { @@ -294,14 +305,26 @@ const PhysXCallback = { PhysXCallback.onCollision('onCollisionStay', wpa, wpb, c, d, o); }, onTriggerBegin: (a: any, b: any): void => { - const wpa = getWrapShape(a); - const wpb = getWrapShape(b); - PhysXCallback.onTrigger('onTriggerEnter', wpa, wpb, true); + const wpa = getWrapShape(a); + const wpb = getWrapShape(b); + if (wpa instanceof PhysXShape && wpb instanceof PhysXShape) { + PhysXCallback.onTrigger('onTriggerEnter', wpa, wpb, true); + } else if (wpa instanceof PhysXShape && wpb instanceof PhysXCharacterController) { + PhysXCallback.onTriggerCCT('onControllerTriggerEnter', wpa, wpb, true); + } else if (wpa instanceof PhysXCharacterController && wpb instanceof PhysXShape) { + PhysXCallback.onTriggerCCT('onControllerTriggerEnter', wpb, wpa, true); + } }, onTriggerEnd: (a: any, b: any): void => { - const wpa = getWrapShape(a); - const wpb = getWrapShape(b); - PhysXCallback.onTrigger('onTriggerExit', wpa, wpb, false); + const wpa = getWrapShape(a); + const wpb = getWrapShape(b); + if (wpa instanceof PhysXShape && wpb instanceof PhysXShape) { + PhysXCallback.onTrigger('onTriggerExit', wpa, wpb, false); + } else if (wpa instanceof PhysXShape && wpb instanceof PhysXCharacterController) { + PhysXCallback.onTriggerCCT('onControllerTriggerExit', wpa, wpb, false); + } else if (wpa instanceof PhysXCharacterController && wpb instanceof PhysXShape) { + PhysXCallback.onTriggerCCT('onControllerTriggerExit', wpb, wpa, false); + } }, }, @@ -347,6 +370,25 @@ const PhysXCallback = { } }, + onTriggerCCT (type: CharacterTriggerEventType, wpa: PhysXShape, cct: PhysXCharacterController, isEnter: boolean): void { + if (wpa && cct) { + if (wpa.collider.needTriggerEvent) { + let tE: ITriggerEventItemCCT; + if (cctTriggerEventsPool.length > 0) { + tE = cctTriggerEventsPool.pop() as ITriggerEventItemCCT; + tE.a = wpa; tE.b = cct; tE.times = 0; + } else { + tE = { a: wpa, b: cct, times: 0 }; + } + if (isEnter) { + cctTriggerEventBeginDic.set(wpa.id, cct.id, tE); + } else { + cctTriggerEventEndDic.set(wpa.id, cct.id, tE); + } + } + } + }, + emitTriggerEvent (): void { let len = triggerEventEndDic.getLength(); while (len--) { @@ -483,7 +525,7 @@ const PhysXCallback = { onControllerHit (hit: any): void { //PX.ControllersHit }, }, - emitCCTShapeEvent (): void { + emitCCTCollisionEvent (): void { let dicL = cctShapeEventDic.getLength(); while (dicL--) { const key = cctShapeEventDic.getKeyByIndex(dicL); @@ -502,4 +544,59 @@ const PhysXCallback = { } cctShapeEventDic.reset(); }, + emitCCTTriggerEvent (): void { + let len = cctTriggerEventEndDic.getLength(); + while (len--) { + const key = cctTriggerEventEndDic.getKeyByIndex(len); + const data = cctTriggerEventEndDic.getDataByKey(key); + cctTriggerEventsPool.push(data); + const dataBeg = cctTriggerEventBeginDic.getDataByKey(key); + if (dataBeg) { + cctTriggerEventsPool.push(dataBeg); + cctTriggerEventBeginDic.set(data.a.id, data.b.id, null); + } + const collider = data.a.collider; + const characterController = data.b.characterController; + if (collider && characterController) { + const type: CharacterTriggerEventType = 'onControllerTriggerExit'; + CharacterTriggerEventObject.type = type; + if (collider.needTriggerEvent) { + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + collider.emit(type, CharacterTriggerEventObject); + } + if (characterController.needTriggerEvent) { + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + characterController.emit(type, CharacterTriggerEventObject); + } + } + } + cctTriggerEventEndDic.reset(); + + len = cctTriggerEventBeginDic.getLength(); + while (len--) { + const key = cctTriggerEventBeginDic.getKeyByIndex(len); + const data = cctTriggerEventBeginDic.getDataByKey(key); + const collider = data.a.collider; + const characterController = data.b.characterController; + if (!collider || !collider.isValid || !characterController || !characterController.isValid) { + cctTriggerEventsPool.push(data); + cctTriggerEventBeginDic.set(data.a.id, data.b.id, null); + } else { + const type: CharacterTriggerEventType = data.times++ ? 'onControllerTriggerStay' : 'onControllerTriggerEnter'; + CharacterTriggerEventObject.type = type; + if (collider.needTriggerEvent) { + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + collider.emit(type, CharacterTriggerEventObject); + } + if (characterController.needTriggerEvent) { + CharacterTriggerEventObject.collider = collider; + CharacterTriggerEventObject.characterController = characterController; + characterController.emit(type, CharacterTriggerEventObject); + } + } + } + }, }; diff --git a/cocos/physics/utils/util.ts b/cocos/physics/utils/util.ts index ad8e0135a9a..ead93adcf0e 100644 --- a/cocos/physics/utils/util.ts +++ b/cocos/physics/utils/util.ts @@ -23,7 +23,7 @@ */ import { equals, Vec3, IVec3Like } from '../../core'; -import { Collider, CollisionEventType, IContactEquation, TriggerEventType } from '../framework'; +import { CharacterController, CharacterTriggerEventType, Collider, CollisionEventType, IContactEquation, TriggerEventType } from '../framework'; export { cylinder } from '../../primitive'; @@ -52,6 +52,13 @@ export const TriggerEventObject = { impl: null as any, }; +export const CharacterTriggerEventObject = { + type: 'onControllerTriggerEnter' as CharacterTriggerEventType, + collider: null as Collider | null, + characterController: null as CharacterController | null, + impl: null as any, +}; + export const CollisionEventObject = { type: 'onCollisionEnter' as CollisionEventType, selfCollider: null as unknown as Collider, diff --git a/exports/physics-framework.ts b/exports/physics-framework.ts index 3d5704b9088..cbadf86dfa5 100644 --- a/exports/physics-framework.ts +++ b/exports/physics-framework.ts @@ -77,6 +77,7 @@ export type { TriggerCallback, CharacterCollisionEventType, CharacterControllerContact, + CharacterTriggerEventType, } from '../cocos/physics/framework'; export * from '../cocos/physics/framework/deprecated'; diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.cpp b/native/cocos/bindings/manual/jsb_conversions_spec.cpp index 91620cd2c13..8af8ffc8273 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.cpp +++ b/native/cocos/bindings/manual/jsb_conversions_spec.cpp @@ -1619,6 +1619,18 @@ bool nativevalue_to_se(const ccstd::vector> &from, se::Value &to, se::Object * /*ctx*/) { + se::HandleObject array(se::Object::createArrayObject(from.size() * cc::physics::CCTTriggerEventPair::COUNT)); + for (size_t i = 0; i < from.size(); i++) { + auto t = i * cc::physics::CCTTriggerEventPair::COUNT; + array->setArrayElement(static_cast(t + 0), se::Value(from[i]->cct)); + array->setArrayElement(static_cast(t + 1), se::Value(from[i]->shape)); + array->setArrayElement(static_cast(t + 2), se::Value(static_cast(from[i]->state))); + } + to.setObject(array); + return true; +} + bool nativevalue_to_se(const cc::physics::RaycastResult &from, se::Value &to, se::Object *ctx) { se::HandleObject obj(se::Object::createPlainObject()); obj->setProperty("shape", se::Value(from.shape)); diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.h b/native/cocos/bindings/manual/jsb_conversions_spec.h index 09ef024954b..86ff9065793 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.h +++ b/native/cocos/bindings/manual/jsb_conversions_spec.h @@ -628,6 +628,7 @@ bool nativevalue_to_se(const ccstd::vector &from, se: bool nativevalue_to_se(const ccstd::vector> &from, se::Value &to, se::Object *ctx); bool nativevalue_to_se(const cc::physics::RaycastResult &from, se::Value &to, se::Object *ctx); bool nativevalue_to_se(const ccstd::vector> &from, se::Value &to, se::Object *ctx); +bool nativevalue_to_se(const ccstd::vector> &from, se::Value &to, se::Object * /*ctx*/); bool sevalue_to_native(const se::Value &from, cc::physics::ConvexDesc *to, se::Object *ctx); bool sevalue_to_native(const se::Value &from, cc::physics::TrimeshDesc *to, se::Object *ctx); diff --git a/native/cocos/physics/physx/PhysXEventManager.cpp b/native/cocos/physics/physx/PhysXEventManager.cpp index 0e20cb500a8..97338197471 100644 --- a/native/cocos/physics/physx/PhysXEventManager.cpp +++ b/native/cocos/physics/physx/PhysXEventManager.cpp @@ -34,27 +34,71 @@ namespace physics { void PhysXEventManager::SimulationEventCallback::onTrigger(physx::PxTriggerPair *pairs, physx::PxU32 count) { for (physx::PxU32 i = 0; i < count; i++) { - const physx::PxTriggerPair &tp = pairs[i]; - if (tp.flags & (physx::PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER | physx::PxTriggerPairFlag::eREMOVED_SHAPE_OTHER)) { + const physx::PxTriggerPair &triggerPair = pairs[i]; + if (triggerPair.flags & (physx::PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER | physx::PxTriggerPairFlag::eREMOVED_SHAPE_OTHER)) { continue; } - const auto &selfIter = getPxShapeMap().find(reinterpret_cast(tp.triggerShape)); - const auto &otherIter = getPxShapeMap().find(reinterpret_cast(tp.otherShape)); - if (selfIter == getPxShapeMap().end() || otherIter == getPxShapeMap().end()) { - continue; + bool processed = false; + + //collider trigger event + if (!processed) { + const auto &selfIter = getPxShapeMap().find(reinterpret_cast(triggerPair.triggerShape)); + const auto &otherIter = getPxShapeMap().find(reinterpret_cast(triggerPair.otherShape)); + if (selfIter != getPxShapeMap().end() && otherIter != getPxShapeMap().end()) { + processed = true; + const auto &self = selfIter->second; + const auto &other = otherIter->second; + auto &pairs = mManager->getTriggerPairs(); + const auto &iter = std::find_if(pairs.begin(), pairs.end(), [self, other](std::shared_ptr &pair) { + return (pair->shapeA == self || pair->shapeA == other) && (pair->shapeB == self || pair->shapeB == other); + }); + if (triggerPair.status & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) { + if (iter == pairs.end()) pairs.push_back(std::shared_ptr(ccnew TriggerEventPair{self, other})); + } else if (triggerPair.status & physx::PxPairFlag::eNOTIFY_TOUCH_LOST) { + if (iter != pairs.end()) iter->get()->state = ETouchState::EXIT; + } + } } - const auto &self = selfIter->second; - const auto &other = otherIter->second; - auto &pairs = mManager->getTriggerPairs(); - const auto &iter = std::find_if(pairs.begin(), pairs.end(), [self, other](std::shared_ptr &pair) { - return (pair->shapeA == self || pair->shapeA == other) && (pair->shapeB == self || pair->shapeB == other); - }); - if (tp.status & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) { - if (iter == pairs.end()) pairs.push_back(std::shared_ptr(ccnew TriggerEventPair{self, other})); - } else if (tp.status & physx::PxPairFlag::eNOTIFY_TOUCH_LOST) { - if (iter != pairs.end()) iter->get()->state = ETouchState::EXIT; + //cct trigger event + if (!processed) { + const auto &shapeIter = getPxShapeMap().find(reinterpret_cast(triggerPair.triggerShape)); + const auto &cctIter = getPxCCTMap().find(reinterpret_cast(triggerPair.otherShape)); + if (shapeIter != getPxShapeMap().end() && cctIter != getPxCCTMap().end()) { + processed = true; + const auto &shape = shapeIter->second; + const auto &cct = cctIter->second; + auto &pairs = mManager->getCCTTriggerPairs(); + const auto &iter = std::find_if(pairs.begin(), pairs.end(), [shape, cct](std::shared_ptr &pair) { + return (pair->shape == shape && pair->cct == cct); + }); + if (triggerPair.status & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) { + if (iter == pairs.end()) pairs.push_back(std::shared_ptr(ccnew CCTTriggerEventPair{cct, shape})); + } else if (triggerPair.status & physx::PxPairFlag::eNOTIFY_TOUCH_LOST) { + if (iter != pairs.end()) iter->get()->state = ETouchState::EXIT; + } + } + } + + //cct trigger event + if (!processed) { + const auto &cctIter = getPxCCTMap().find(reinterpret_cast(triggerPair.triggerShape)); + const auto &shapeIter = getPxShapeMap().find(reinterpret_cast(triggerPair.otherShape)); + if (shapeIter != getPxShapeMap().end() && cctIter != getPxCCTMap().end()) { + processed = true; + const auto &shape = shapeIter->second; + const auto &cct = cctIter->second; + auto &pairs = mManager->getCCTTriggerPairs(); + const auto &iter = std::find_if(pairs.begin(), pairs.end(), [shape, cct](std::shared_ptr &pair) { + return (pair->shape == shape && pair->cct == cct); + }); + if (triggerPair.status & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) { + if (iter == pairs.end()) pairs.push_back(std::shared_ptr(ccnew CCTTriggerEventPair{cct, shape})); + } else if (triggerPair.status & physx::PxPairFlag::eNOTIFY_TOUCH_LOST) { + if (iter != pairs.end()) iter->get()->state = ETouchState::EXIT; + } + } } } } @@ -121,6 +165,28 @@ void PhysXEventManager::refreshPairs() { } } + for (auto iter = getCCTTriggerPairs().begin(); iter != getCCTTriggerPairs().end();) { + uintptr_t wrapperPtrCCT = PhysXWorld::getInstance().getWrapperPtrWithObjectID(iter->get()->cct); + uintptr_t wrapperPtrShape = PhysXWorld::getInstance().getWrapperPtrWithObjectID(iter->get()->shape); + if (wrapperPtrCCT == 0 || wrapperPtrShape == 0) { + iter = getCCTTriggerPairs().erase(iter); + continue; + } + + const auto& cctIter = getPxCCTMap().find(reinterpret_cast(&(reinterpret_cast(wrapperPtrCCT)->getCCT()))); + const auto& shapeIter = getPxShapeMap().find(reinterpret_cast(&(reinterpret_cast(wrapperPtrShape)->getShape()))); + if (cctIter == getPxCCTMap().end() || shapeIter == getPxShapeMap().end()) { + iter = getCCTTriggerPairs().erase(iter); + } + else if (iter->get()->state == ETouchState::EXIT) { + iter = getCCTTriggerPairs().erase(iter); + } + else { + iter->get()->state = ETouchState::STAY; + iter++; + } + } + getConatctPairs().clear(); getCCTShapePairs().clear(); } diff --git a/native/cocos/physics/physx/PhysXEventManager.h b/native/cocos/physics/physx/PhysXEventManager.h index 36a3f4f2dd0..6cc2f0d0006 100644 --- a/native/cocos/physics/physx/PhysXEventManager.h +++ b/native/cocos/physics/physx/PhysXEventManager.h @@ -61,12 +61,14 @@ class PhysXEventManager final { inline ccstd::vector> &getTriggerPairs() { return _mTriggerPairs; } inline ccstd::vector>& getConatctPairs() { return _mConatctPairs; } inline ccstd::vector>& getCCTShapePairs() { return _mCCTShapePairs; } + inline ccstd::vector> &getCCTTriggerPairs() { return _mCCTTriggerPairs; } void refreshPairs(); private: ccstd::vector> _mTriggerPairs; ccstd::vector> _mConatctPairs; ccstd::vector> _mCCTShapePairs; + ccstd::vector> _mCCTTriggerPairs; SimulationEventCallback *_mCallback; }; diff --git a/native/cocos/physics/physx/PhysXWorld.h b/native/cocos/physics/physx/PhysXWorld.h index 007b648d163..08cfa6a9d43 100644 --- a/native/cocos/physics/physx/PhysXWorld.h +++ b/native/cocos/physics/physx/PhysXWorld.h @@ -88,6 +88,9 @@ class PhysXWorld final : virtual public IPhysicsWorld { inline ccstd::vector>& getCCTShapeEventPairs() override { return _mEventMgr->getCCTShapePairs(); } + inline ccstd::vector> &getCCTTriggerEventPairs() override { + return _mEventMgr->getCCTTriggerPairs(); + } void syncSceneToPhysics() override; void syncSceneWithCheck() override; void destroy() override; diff --git a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp index 37483bc95f3..66635d23445 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp +++ b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp @@ -259,12 +259,14 @@ void PhysXCharacterController::syncPhysicsToScene() { void PhysXCharacterController::insertToCCTMap() { if (_impl) { getPxCCTMap().insert(std::pair(reinterpret_cast(_impl), getObjectID())); + getPxCCTMap().insert(std::pair(reinterpret_cast(getShape()), getObjectID())); } } void PhysXCharacterController::eraseFromCCTMap() { if (_impl) { getPxCCTMap().erase(reinterpret_cast(_impl)); + getPxCCTMap().erase(reinterpret_cast(getShape())); } } @@ -272,6 +274,15 @@ cc::Vec3 PhysXCharacterController::scaledCenter() { return _mNode->getWorldScale() * _mCenter; } - +physx::PxShape* PhysXCharacterController::getShape() { + if (_impl) { + //cct's shape + physx::PxRigidDynamic* actor = _impl->getActor(); + physx::PxShape* shape; + actor->getShapes(&shape, 1); + return shape; + } + return nullptr; +} } // namespace physics } // namespace cc diff --git a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h index 5ec9197a655..da11603ea10 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h +++ b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h @@ -88,6 +88,8 @@ class PhysXCharacterController : virtual public IBaseCharacterController { uint32_t getObjectID() const override { return _mObjectID; }; //ICharacterController END + inline physx::PxController& getCCT() { return *_impl; }; + protected: physx::PxController* _impl{ nullptr }; uint8_t _mFlag{ 0 }; @@ -114,6 +116,7 @@ class PhysXCharacterController : virtual public IBaseCharacterController { void insertToCCTMap(); void eraseFromCCTMap(); cc::Vec3 scaledCenter(); + physx::PxShape* getShape(); }; } // namespace physics diff --git a/native/cocos/physics/sdk/World.cpp b/native/cocos/physics/sdk/World.cpp index cf0dbba7cfb..6849def1576 100644 --- a/native/cocos/physics/sdk/World.cpp +++ b/native/cocos/physics/sdk/World.cpp @@ -82,6 +82,10 @@ ccstd::vector>& World::getCCTShapeEventPairs( return _impl->getCCTShapeEventPairs(); } +ccstd::vector> &World::getCCTTriggerEventPairs() { + return _impl->getCCTTriggerEventPairs(); +} + void World::setCollisionMatrix(uint32_t i, uint32_t m) { _impl->setCollisionMatrix(i, m); } diff --git a/native/cocos/physics/sdk/World.h b/native/cocos/physics/sdk/World.h index 64661216602..33be08ac30c 100644 --- a/native/cocos/physics/sdk/World.h +++ b/native/cocos/physics/sdk/World.h @@ -44,6 +44,7 @@ class CC_DLL World final : public IPhysicsWorld { ccstd::vector> &getTriggerEventPairs() override; ccstd::vector>& getContactEventPairs() override; ccstd::vector>& getCCTShapeEventPairs() override; + ccstd::vector>& getCCTTriggerEventPairs() override; bool raycast(RaycastOptions &opt) override; bool raycastClosest(RaycastOptions &opt) override; ccstd::vector &raycastResult() override; diff --git a/native/cocos/physics/spec/IWorld.h b/native/cocos/physics/spec/IWorld.h index ea69d7d7f15..062b8d37cdc 100644 --- a/native/cocos/physics/spec/IWorld.h +++ b/native/cocos/physics/spec/IWorld.h @@ -90,6 +90,17 @@ struct CCTShapeEventPair { } }; +struct CCTTriggerEventPair { + uint32_t cct; //wrapper object ID + uint32_t shape; //wrapper object ID + ETouchState state; + static constexpr uint8_t COUNT = 3; + CCTTriggerEventPair(const uint32_t cct, const uint32_t shape) + : cct(cct), + shape(shape), + state(ETouchState::ENTER) {} +}; + struct ConvexDesc { void *positions; uint32_t positionLength; @@ -138,6 +149,7 @@ class IPhysicsWorld { virtual ccstd::vector> &getTriggerEventPairs() = 0; virtual ccstd::vector>& getContactEventPairs() = 0; virtual ccstd::vector>& getCCTShapeEventPairs() = 0; + virtual ccstd::vector> &getCCTTriggerEventPairs() = 0; virtual bool raycast(RaycastOptions &opt) = 0; virtual bool raycastClosest(RaycastOptions &opt) = 0; virtual ccstd::vector &raycastResult() = 0; diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index 49973ef4c94..8b92d375ea9 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -52,6 +52,13 @@ const CCTShapeEventObject = { motionLength: 0, }; +const CharacterTriggerEventObject = { + type: 'onControllerTriggerEnter', + characterController: null, + collider: null, + impl: null, +}; + function emitTriggerEvent (t, c0, c1, impl) { TriggerEventObject.type = t; TriggerEventObject.impl = impl; @@ -67,6 +74,19 @@ function emitTriggerEvent (t, c0, c1, impl) { } } +function emitCCTTriggerEvent (t, cct, collider, impl) { + CharacterTriggerEventObject.type = t; + CharacterTriggerEventObject.impl = impl; + CharacterTriggerEventObject.characterController = cct; + CharacterTriggerEventObject.collider = collider; + if (collider.needTriggerEvent) { + collider.emit(t, CharacterTriggerEventObject); + } + if (cct.needTriggerEvent) { + cct.emit(t, CharacterTriggerEventObject); + } +} + const quat = new cc.Quat(); const contactsPool = []; const contactBufferElementLength = 12; @@ -138,7 +158,7 @@ function emitCollisionEvent (t, c0, c1, impl, b) { } } -function emitCCTShapeEvent (t, cct, collider, b) { +function emitCCTCollisionEvent (t, cct, collider, b) { CCTShapeEventObject.type = t; const contactCount = b.length / 10; @@ -211,8 +231,16 @@ class PhysicsWorld { raycastOptions.mask = options.mask >>> 0; raycastOptions.distance = options.maxDistance; raycastOptions.queryTrigger = !!options.queryTrigger; - const isHit = this._impl.sweepBox(raycastOptions, halfExtent.x, halfExtent.y, halfExtent.z, - orientation.w, orientation.x, orientation.y, orientation.z); + const isHit = this._impl.sweepBox( + raycastOptions, + halfExtent.x, + halfExtent.y, + halfExtent.z, + orientation.w, + orientation.x, + orientation.y, + orientation.z, + ); if (isHit) { const hits = this._impl.sweepResult(); for (let i = 0; i < hits.length; i++) { @@ -231,8 +259,16 @@ class PhysicsWorld { raycastOptions.mask = options.mask >>> 0; raycastOptions.distance = options.maxDistance; raycastOptions.queryTrigger = !!options.queryTrigger; - const isHit = this._impl.sweepBoxClosest(raycastOptions, halfExtent.x, halfExtent.y, halfExtent.z, - orientation.w, orientation.x, orientation.y, orientation.z); + const isHit = this._impl.sweepBoxClosest( + raycastOptions, + halfExtent.x, + halfExtent.y, + halfExtent.z, + orientation.w, + orientation.x, + orientation.y, + orientation.z, + ); if (isHit) { const hit = this._impl.sweepClosestResult(); result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); @@ -298,8 +334,15 @@ class PhysicsWorld { raycastOptions.mask = options.mask >>> 0; raycastOptions.distance = options.maxDistance; raycastOptions.queryTrigger = !!options.queryTrigger; - const isHit = this._impl.sweepCapsuleClosest(raycastOptions, radius, height, - orientation.w, orientation.x, orientation.y, orientation.z); + const isHit = this._impl.sweepCapsuleClosest( + raycastOptions, + radius, + height, + orientation.w, + orientation.x, + orientation.y, + orientation.z, + ); if (isHit) { const hit = this._impl.sweepClosestResult(); result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal); @@ -310,7 +353,8 @@ class PhysicsWorld { emitEvents () { this.emitTriggerEvent(); this.emitCollisionEvent(); - this.emitCCTShapeEvent(); + this.emitCCTCollisionEvent(); + this.emitCCTTriggerEvent(); this._impl.emitEvents(); } @@ -366,7 +410,7 @@ class PhysicsWorld { } } - emitCCTShapeEvent () { + emitCCTCollisionEvent () { const events = this._impl.getCCTShapeEventPairs(); const len2 = events.length / 3; for (let i = 0; i < len2; i++) { @@ -375,7 +419,30 @@ class PhysicsWorld { if (!cct || !shape) continue; const c0 = cct.characterController; const c1 = shape.collider; if (!(c0 && c0.isValid && c1 && c1.isValid)) continue; - emitCCTShapeEvent('onControllerColliderHit', c0, c1, events[t + 2]); + emitCCTCollisionEvent('onControllerColliderHit', c0, c1, events[t + 2]); + } + } + + emitCCTTriggerEvent () { + const teps = this._impl.getCCTTriggerEventPairs(); + const len = teps.length / 3; + for (let i = 0; i < len; i++) { + const t = i * 3; + const sa = ptrToObj[teps[t + 0]]; + const sb = ptrToObj[teps[t + 1]]; + if (!sa || !sb) continue; + const cct = sa.characterController; + const collider = sb.collider; + if (!(cct && cct.isValid && collider && collider.isValid)) continue; + if (!collider.needTriggerEvent) continue; + const state = teps[t + 2]; + if (state === 1) { + emitCCTTriggerEvent('onControllerTriggerStay', cct, collider, teps); + } else if (state === 0) { + emitCCTTriggerEvent('onControllerTriggerEnter', cct, collider, teps); + } else { + emitCCTTriggerEvent('onControllerTriggerExit', cct, collider, teps); + } } } } From a77a6c94884e19dfb2bb97ae57f89d5a77dfaff1 Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Fri, 18 Aug 2023 11:05:53 +0800 Subject: [PATCH 184/232] fix instanced buffer. (#16017) --- native/cocos/renderer/pipeline/InstancedBuffer.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index bd5f02f1d4b..a26cc71c0b7 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -157,6 +157,7 @@ void InstancedBuffer::uploadBuffers(gfx::CommandBuffer *cmdBuff) const { if (!instance.drawInfo.instanceCount) continue; cmdBuff->updateBuffer(instance.vb, instance.data, instance.vb->getSize()); + instance.ia->setInstanceCount(instance.drawInfo.instanceCount); } } From 541ef96eb8ca01dc0a654121c97f94011fd85fbf Mon Sep 17 00:00:00 2001 From: Gin Date: Fri, 18 Aug 2023 11:27:21 +0800 Subject: [PATCH 185/232] update: i18n text of CurveRange (#16019) --- editor/i18n/en/localization.js | 13 +++++++++++++ editor/i18n/zh/localization.js | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index ac6f45fe483..c3b05125f0a 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -49,6 +49,19 @@ module.exports = link(mixin({ }, }, }, + CurveRange: { + properties: { + spline: { + displayName: 'Spline', + }, + splineMin: { + displayName: 'Spline Min', + }, + splineMax: { + displayName: 'Spline Max', + }, + }, + }, }, }, diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index a2c1052c6fb..cd3a0881867 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -50,6 +50,19 @@ module.exports = link(mixin({ }, }, }, + CurveRange: { + properties: { + spline: { + displayName: 'Spline', + }, + splineMin: { + displayName: 'Spline Min', + }, + splineMax: { + displayName: 'Spline Max', + }, + }, + }, }, help: { From c589518f3d6764d2dcdac63c881117b5ca6f242a Mon Sep 17 00:00:00 2001 From: Jiujiang Liu <37231523+moshuying@users.noreply.github.com> Date: Fri, 18 Aug 2023 13:48:21 +0800 Subject: [PATCH 186/232] disable show probe (#15887) --- cocos/scene-graph/scene-globals.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index f3d97b259d5..4907c9e0d2f 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -1312,8 +1312,6 @@ export class LightProbeInfo { * @en Whether to show light probe * @zh 是否显示光照探针 */ - @editable - @tooltip('i18n:light_probe.showProbe') set showProbe (val: boolean) { if (this._showProbe === val) return; this._showProbe = val; From f4a7b9576739ddba77d030502feb3de619a1ca0d Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Fri, 18 Aug 2023 14:32:30 +0800 Subject: [PATCH 187/232] fix sprite world matrix update bug (#15978) * fix sprite world matrix update bug * fix by flag Changed Version * add test * CI & more test --- cocos/2d/assembler/sprite/bar-filled.ts | 3 +- cocos/2d/assembler/sprite/radial-filled.ts | 63 ++++++--- cocos/2d/assembler/sprite/simple.ts | 3 +- cocos/2d/assembler/sprite/sliced.ts | 7 +- cocos/2d/assembler/sprite/tiled.ts | 14 +- cocos/2d/framework/ui-renderer.ts | 16 ++- tests/ui/sprite.test.ts | 145 +++++++++++++++++++++ 7 files changed, 218 insertions(+), 33 deletions(-) create mode 100644 tests/ui/sprite.test.ts diff --git a/cocos/2d/assembler/sprite/bar-filled.ts b/cocos/2d/assembler/sprite/bar-filled.ts index b0244832800..9d1088c62b0 100644 --- a/cocos/2d/assembler/sprite/bar-filled.ts +++ b/cocos/2d/assembler/sprite/bar-filled.ts @@ -236,9 +236,10 @@ export const barFilled: IAssembler = { fillBuffers (sprite: Sprite, renderer: IBatcher) { const renderData: RenderData = sprite.renderData!; const chunk = renderData.chunk; - if (sprite.node.hasChangedFlags || renderData.vertDirty) { + if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) { this.updateWorldVertexData(sprite, chunk); renderData.vertDirty = false; + sprite._flagChangedVersion = sprite.node.flagChangedVersion; } const bid = chunk.bufferId; diff --git a/cocos/2d/assembler/sprite/radial-filled.ts b/cocos/2d/assembler/sprite/radial-filled.ts index c7d0685e5c1..aa869b0ee17 100644 --- a/cocos/2d/assembler/sprite/radial-filled.ts +++ b/cocos/2d/assembler/sprite/radial-filled.ts @@ -27,7 +27,7 @@ import { SpriteFrame } from '../../assets'; import { Mat4, Vec2 } from '../../../core'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; -import { Sprite, UIOpacity } from '../../components'; +import { Sprite } from '../../components'; import { IAssembler } from '../../renderer/base'; import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager'; import { StaticVBChunk } from '../../renderer/static-vb-accessor'; @@ -43,9 +43,9 @@ const _intersectPoint_1: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2( const _intersectPoint_2: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; const _center = new Vec2(); const _triangles: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; -let QUAD_INDICES; +let QUAD_INDICES: Uint16Array | null = null; -function _calcIntersectedPoints (left, right, bottom, top, center: Vec2, angle, intersectPoints: Vec2[]): void { +function _calcIntersectedPoints (left, right, bottom, top, center: Vec2, angle: number, intersectPoints: Vec2[]): void { // left bottom, right, top let sinAngle = Math.sin(angle); sinAngle = Math.abs(sinAngle) > EPSILON ? sinAngle : 0; @@ -269,14 +269,22 @@ export const radialFilled: IAssembler = { // build uvs _calculateUVs(frame); _calcIntersectedPoints( - _vertices[0], _vertices[2], - _vertices[1], _vertices[3], - _center, fillStart, _intersectPoint_1, + _vertices[0], + _vertices[2], + _vertices[1], + _vertices[3], + _center, + fillStart, + _intersectPoint_1, ); _calcIntersectedPoints( - _vertices[0], _vertices[2], - _vertices[1], _vertices[3], - _center, fillStart + fillRange, _intersectPoint_2, + _vertices[0], + _vertices[2], + _vertices[1], + _vertices[3], + _center, + fillStart + fillRange, + _intersectPoint_2, ); let offset = 0; @@ -307,14 +315,21 @@ export const radialFilled: IAssembler = { if (endAngle >= fillEnd) { // startAngle to fillEnd _generateTriangle( - dataList, offset, _center, + dataList, + offset, + _center, _vertPos[triangle.x], _intersectPoint_2[triangleIndex], ); } else { // startAngle to endAngle - _generateTriangle(dataList, offset, _center, - _vertPos[triangle.x], _vertPos[triangle.y]); + _generateTriangle( + dataList, + offset, + _center, + _vertPos[triangle.x], + _vertPos[triangle.y], + ); } offset += 3; } else if (endAngle > fillStart) { @@ -322,16 +337,24 @@ export const radialFilled: IAssembler = { if (endAngle <= fillEnd) { renderData.dataLength = offset + 3; // fillStart to endAngle - _generateTriangle(dataList, offset, _center, + _generateTriangle( + dataList, + offset, + _center, _intersectPoint_1[triangleIndex], - _vertPos[triangle.y]); + _vertPos[triangle.y], + ); offset += 3; } else { renderData.dataLength = offset + 3; // fillStart to fillEnd - _generateTriangle(dataList, offset, _center, + _generateTriangle( + dataList, + offset, + _center, _intersectPoint_1[triangleIndex], - _intersectPoint_2[triangleIndex]); + _intersectPoint_2[triangleIndex], + ); offset += 3; } } @@ -348,7 +371,7 @@ export const radialFilled: IAssembler = { if (JSB) { const indexCount = renderData.indexCount; this.createQuadIndices(indexCount); - renderData.chunk.setIndexBuffer(QUAD_INDICES); + renderData.chunk.setIndexBuffer(QUAD_INDICES!); // may can update color & uv here // need dirty this.updateWorldUVData(sprite); @@ -359,7 +382,7 @@ export const radialFilled: IAssembler = { } }, - createQuadIndices (indexCount) { + createQuadIndices (indexCount: number) { QUAD_INDICES = null; QUAD_INDICES = new Uint16Array(indexCount); let offset = 0; @@ -372,9 +395,10 @@ export const radialFilled: IAssembler = { const node = comp.node; const renderData: RenderData = comp.renderData!; const chunk = renderData.chunk; - if (node.hasChangedFlags || renderData.vertDirty) { + if (comp._flagChangedVersion !== node.flagChangedVersion || renderData.vertDirty) { this.updateWorldVertexAndUVData(comp, chunk); renderData.vertDirty = false; + comp._flagChangedVersion = node.flagChangedVersion; } // forColor @@ -464,5 +488,6 @@ export const radialFilled: IAssembler = { // Too early updateColor (sprite: Sprite) { + // Update color by updateColorLate }, }; diff --git a/cocos/2d/assembler/sprite/simple.ts b/cocos/2d/assembler/sprite/simple.ts index c214a2a31e6..cd3d03048ef 100644 --- a/cocos/2d/assembler/sprite/simple.ts +++ b/cocos/2d/assembler/sprite/simple.ts @@ -99,10 +99,11 @@ export const simple: IAssembler = { const renderData = sprite.renderData!; const chunk = renderData.chunk; - if (sprite.node.hasChangedFlags || renderData.vertDirty) { + if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) { // const vb = chunk.vertexAccessor.getVertexBuffer(chunk.bufferId); this.updateWorldVerts(sprite, chunk); renderData.vertDirty = false; + sprite._flagChangedVersion = sprite.node.flagChangedVersion; } // quick version diff --git a/cocos/2d/assembler/sprite/sliced.ts b/cocos/2d/assembler/sprite/sliced.ts index 0d4be8aef0c..942d6f62038 100644 --- a/cocos/2d/assembler/sprite/sliced.ts +++ b/cocos/2d/assembler/sprite/sliced.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { Color, Mat4, Vec3 } from '../../../core'; +import { Color, Mat4 } from '../../../core'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; import { Sprite } from '../../components'; @@ -51,7 +51,7 @@ export const sliced: IAssembler = { renderData.vertexCol = 4; this.QUAD_INDICES = new Uint16Array(54); this.createQuadIndices(4, 4); - renderData.chunk.setIndexBuffer(this.QUAD_INDICES); + renderData.chunk.setIndexBuffer(this.QUAD_INDICES as Uint16Array); return renderData; }, @@ -156,9 +156,10 @@ export const sliced: IAssembler = { fillBuffers (sprite: Sprite, renderer: IBatcher) { const renderData: RenderData = sprite.renderData!; const chunk = renderData.chunk; - if (sprite.node.hasChangedFlags || renderData.vertDirty) { + if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) { this.updateWorldVertexData(sprite, chunk); renderData.vertDirty = false; + sprite._flagChangedVersion = sprite.node.flagChangedVersion; } const bid = chunk.bufferId; diff --git a/cocos/2d/assembler/sprite/tiled.ts b/cocos/2d/assembler/sprite/tiled.ts index 502ebb5fe4f..8c271e500b5 100644 --- a/cocos/2d/assembler/sprite/tiled.ts +++ b/cocos/2d/assembler/sprite/tiled.ts @@ -24,7 +24,7 @@ import { JSB } from 'internal:constants'; import { IUV, SpriteFrame } from '../../assets/sprite-frame'; -import { Mat4, Vec3, Color } from '../../../core'; +import { Mat4, Vec3, Color, error } from '../../../core'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; import { Sprite } from '../../components/sprite'; @@ -43,7 +43,7 @@ let topInner: IUV; let topOuter: IUV; let tempRenderDataLength = 0; const tempRenderData: IRenderData[] = []; -let QUAD_INDICES; +let QUAD_INDICES: Uint16Array | null = null; function has9SlicedOffsetVertexCount (spriteFrame: SpriteFrame): number { if (spriteFrame) { @@ -109,7 +109,7 @@ export const tiled: IAssembler = { if (JSB) { const indexCount = renderData.indexCount; this.createQuadIndices(indexCount); - renderData.chunk.setIndexBuffer(QUAD_INDICES); + renderData.chunk.setIndexBuffer(QUAD_INDICES!); // may can update color & uv here // need dirty this.updateWorldUVData(sprite); @@ -119,9 +119,9 @@ export const tiled: IAssembler = { renderData.updateRenderData(sprite, frame); }, - createQuadIndices (indexCount) { + createQuadIndices (indexCount: number) { if (indexCount % 6 !== 0) { - console.error('illegal index count!'); + error('illegal index count!'); return; } const quadCount = indexCount / 6; @@ -150,9 +150,10 @@ export const tiled: IAssembler = { const node = sprite.node; const renderData: RenderData = sprite.renderData!; const chunk = renderData.chunk; - if (node.hasChangedFlags || renderData.vertDirty) { + if (sprite._flagChangedVersion !== node.flagChangedVersion || renderData.vertDirty) { this.updateWorldVertexAndUVData(sprite, chunk); renderData.vertDirty = false; + sprite._flagChangedVersion = node.flagChangedVersion; } // forColor @@ -512,5 +513,6 @@ export const tiled: IAssembler = { // Too early updateColor (sprite: Sprite) { + // Update color by updateColorLate }, }; diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index bb4c4a2abd6..d79a81d315f 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -278,6 +278,10 @@ export class UIRenderer extends Renderer { * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. */ public _internalId = -1; + /** + * @engineInternal + */ + public _flagChangedVersion = -1; /** * @deprecated Since v3.7.0, this is an engine private interface that will be removed in the future. @@ -429,9 +433,13 @@ export class UIRenderer extends Renderer { } } - protected _render (render: IBatcher): void { } + protected _render (render: IBatcher): void { + // Implemented by subclasses + } - protected _postRender (render: IBatcher): void { } + protected _postRender (render: IBatcher): void { + // Implemented by subclasses + } protected _canRender (): boolean { if (DEBUG) { @@ -442,7 +450,9 @@ export class UIRenderer extends Renderer { && this._color.a > 0; } - protected _postCanRender (): void { } + protected _postCanRender (): void { + // Implemented by subclasses + } /** * @engineInternal diff --git a/tests/ui/sprite.test.ts b/tests/ui/sprite.test.ts new file mode 100644 index 00000000000..b05a02d2ee8 --- /dev/null +++ b/tests/ui/sprite.test.ts @@ -0,0 +1,145 @@ +import { Canvas, SpriteFrame, UITransform } from "../../cocos/2d"; +import { Sprite, UIOpacity } from "../../cocos/2d/components"; +import { Texture2D } from "../../cocos/asset/assets"; +import { Node } from "../../cocos/scene-graph/node"; +import { Camera, Scene, Size, Vec3, director, game } from "../../exports/base"; +import { Batcher2D } from "../../cocos/2d/renderer/batcher-2d"; + +test('sprite.updateWorldMatrix', () => { + + // @ts-expect-error + director.root!._batcher = new Batcher2D(director.root!); + + const scene = new Scene('test'); + director.runSceneImmediate(scene); + + let canvasNode = new Node("Canvas"); + scene.addChild(canvasNode); + let canvas = canvasNode.addComponent(Canvas) as Canvas; + let uitrs = canvasNode.addComponent(UITransform) as UITransform; + uitrs.contentSize = new Size(600, 600); + + let uiCamera = new Node('UICamera'); + let camera = uiCamera.addComponent(Camera) as Camera; + uiCamera.parent = canvasNode; + canvas.cameraComponent = camera; + // camera._createCamera(); + // camera.onEnable(); + + let node = new Node('root'); + let spriteFrame = new SpriteFrame(); + let texture = new Texture2D(); + spriteFrame.texture = texture; + + node.setParent(canvasNode); + + let node1 = new Node('sprite1'); + node1.addComponent(Sprite); + let sprite1 = node1.getComponent(Sprite) as Sprite; + node1.parent = node; + + let node2 = new Node('sprite2'); + node2.addComponent(Sprite); + let sprite2 = node2.getComponent(Sprite) as Sprite; + node2.parent = node; + + let node3 = new Node('sprite3'); + node3.addComponent(Sprite); + let sprite3 = node3.getComponent(Sprite) as Sprite; + node3.parent = node; + + let node4 = new Node('sprite4'); + node4.addComponent(Sprite); + let sprite4 = node4.getComponent(Sprite) as Sprite; + node4.parent = node; + + let node5 = new Node('sprite5'); + node5.addComponent(Sprite); + let sprite5 = node5.getComponent(Sprite) as Sprite; + node5.parent = node; + + sprite1.spriteFrame = spriteFrame; + sprite2.spriteFrame = spriteFrame; + sprite3.spriteFrame = spriteFrame; + sprite4.spriteFrame = spriteFrame; + sprite5.spriteFrame = spriteFrame; + + sprite1.type = Sprite.Type.SIMPLE; + sprite2.type = Sprite.Type.SLICED; + sprite3.type = Sprite.Type.TILED; + sprite4.type = Sprite.Type.FILLED; + sprite5.type = Sprite.Type.FILLED; + sprite4.fillType = Sprite.FillType.HORIZONTAL; + sprite5.fillType = Sprite.FillType.RADIAL; + + sprite5.fillRange = 1; + + let opacity = node.addComponent(UIOpacity) as UIOpacity; + + // normal part + node.setPosition(100, 100, 0); + game.step(); + expect(sprite1.node._pos).toStrictEqual(new Vec3(100, 100, 0)); + expect(sprite2.node._pos).toStrictEqual(new Vec3(100, 100, 0)); + expect(sprite3.node._pos).toStrictEqual(new Vec3(100, 100, 0)); + expect(sprite4.node._pos).toStrictEqual(new Vec3(100, 100, 0)); + expect(sprite5.node._pos).toStrictEqual(new Vec3(100, 100, 0)); + + // disabled part + node.active = false; + node.setPosition(200, 200, 0); + game.step(); + node.active = true; + game.step(); + expect(sprite1.node._pos).toStrictEqual(new Vec3(200, 200, 0)); + expect(sprite2.node._pos).toStrictEqual(new Vec3(200, 200, 0)); + expect(sprite3.node._pos).toStrictEqual(new Vec3(200, 200, 0)); + expect(sprite4.node._pos).toStrictEqual(new Vec3(200, 200, 0)); + expect(sprite5.node._pos).toStrictEqual(new Vec3(200, 200, 0)); + + // opacity part + opacity.opacity = 0; + node.setPosition(300, 300, 0); + game.step(); + opacity.opacity = 255; + game.step(); + expect(sprite1.node._pos).toStrictEqual(new Vec3(300, 300, 0)); + expect(sprite2.node._pos).toStrictEqual(new Vec3(300, 300, 0)); + expect(sprite3.node._pos).toStrictEqual(new Vec3(300, 300, 0)); + expect(sprite4.node._pos).toStrictEqual(new Vec3(300, 300, 0)); + expect(sprite5.node._pos).toStrictEqual(new Vec3(300, 300, 0)); + + // disabled & after node change part + node.active = false; + node.setPosition(200, 200, 0); + game.step(); + sprite1.node.worldMatrix; + sprite2.node.worldMatrix; + sprite3.node.worldMatrix; + sprite4.node.worldMatrix; + sprite5.node.worldMatrix; + node.active = true; + game.step(); + expect(sprite1.renderData!.chunk.vb[0]).toStrictEqual(200 - 0.5); + expect(sprite2.renderData!.chunk.vb[0]).toStrictEqual(200 - 0.5); + expect(sprite3.renderData!.chunk.vb[0]).toStrictEqual(200 - 0.5); + expect(sprite4.renderData!.chunk.vb[0]).toStrictEqual(200 - 0.5); + expect(sprite5.renderData!.chunk.vb[0]).toStrictEqual(200 - 0.5); + + // opacity & after node change part + opacity.opacity = 0; + node.setPosition(300, 300, 0); + game.step(); + sprite1.node.worldMatrix; + sprite2.node.worldMatrix; + sprite3.node.worldMatrix; + sprite4.node.worldMatrix; + sprite5.node.worldMatrix; + opacity.opacity = 255; + game.step(); + expect(sprite1.renderData!.chunk.vb[0]).toStrictEqual(300 - 0.5); + expect(sprite2.renderData!.chunk.vb[0]).toStrictEqual(300 - 0.5); + expect(sprite3.renderData!.chunk.vb[0]).toStrictEqual(300 - 0.5); + expect(sprite4.renderData!.chunk.vb[0]).toStrictEqual(300 - 0.5); + expect(sprite5.renderData!.chunk.vb[0]).toStrictEqual(300 - 0.5); +}); \ No newline at end of file From daa4a4ffbc114702f09eb3bac79e64dbc6783394 Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Fri, 18 Aug 2023 14:40:26 +0800 Subject: [PATCH 188/232] remove unnecessary code (#15687) * Revert "Revert "remove useless code (#15682)" (#15683)" This reverts commit b318b39eb97584c890249755d68b9f729061b9bb. * fix lint * Revert "fix lint" This reverts commit 269acd1715a93d59f61286d336afa9a03f07f805. * revert some change * fix lint --- cocos/2d/assembler/label/ttf.ts | 4 +-- cocos/2d/assembler/sprite/bar-filled.ts | 2 -- cocos/2d/assembler/sprite/simple.ts | 45 ++++++++++--------------- cocos/2d/assembler/sprite/sliced.ts | 8 ++--- 4 files changed, 22 insertions(+), 37 deletions(-) diff --git a/cocos/2d/assembler/label/ttf.ts b/cocos/2d/assembler/label/ttf.ts index 73c3b2b255a..68e3a4580fc 100644 --- a/cocos/2d/assembler/label/ttf.ts +++ b/cocos/2d/assembler/label/ttf.ts @@ -60,8 +60,6 @@ export const ttf: IAssembler = { Color.toArray(vData, WHITE, offset); offset += 9; } - renderData.vertexRow = 2; - renderData.vertexCol = 2; renderData.chunk.setIndexBuffer(QUAD_INDICES); return renderData; }, @@ -149,7 +147,7 @@ export const ttf: IAssembler = { }, updateColor (comp: Label) { - + // no needs to update color }, }; diff --git a/cocos/2d/assembler/sprite/bar-filled.ts b/cocos/2d/assembler/sprite/bar-filled.ts index 9d1088c62b0..31e164023ad 100644 --- a/cocos/2d/assembler/sprite/bar-filled.ts +++ b/cocos/2d/assembler/sprite/bar-filled.ts @@ -196,8 +196,6 @@ export const barFilled: IAssembler = { // 0-4 for local vertex renderData.dataLength = 4; renderData.resize(4, 6); - renderData.vertexRow = 2; - renderData.vertexCol = 2; renderData.chunk.setIndexBuffer(QUAD_INDICES); // not need diff --git a/cocos/2d/assembler/sprite/simple.ts b/cocos/2d/assembler/sprite/simple.ts index cd3d03048ef..879d13d9266 100644 --- a/cocos/2d/assembler/sprite/simple.ts +++ b/cocos/2d/assembler/sprite/simple.ts @@ -45,8 +45,6 @@ export const simple: IAssembler = { const renderData = sprite.requestRenderData(); renderData.dataLength = 4; renderData.resize(4, 6); - renderData.vertexRow = 2; - renderData.vertexCol = 2; renderData.chunk.setIndexBuffer(QUAD_INDICES); return renderData; }, @@ -107,36 +105,29 @@ export const simple: IAssembler = { } // quick version - const bid = chunk.bufferId; const vidOrigin = chunk.vertexOffset; const meshBuffer = chunk.meshBuffer; const ib = chunk.meshBuffer.iData; let indexOffset = meshBuffer.indexOffset; - // rect count = vertex count - 1 - for (let curRow = 0; curRow < renderData.vertexRow - 1; curRow++) { - for (let curCol = 0; curCol < renderData.vertexCol - 1; curCol++) { - // vid is the index of the left bottom vertex in each rect. - const vid = vidOrigin + curRow * renderData.vertexCol + curCol; - - // left bottom - ib[indexOffset++] = vid; - // right bottom - ib[indexOffset++] = vid + 1; - // left top - ib[indexOffset++] = vid + renderData.vertexCol; - - // right bottom - ib[indexOffset++] = vid + 1; - // right top - ib[indexOffset++] = vid + 1 + renderData.vertexCol; - // left top - ib[indexOffset++] = vid + renderData.vertexCol; - - // IndexOffset should add 6 when vertices of a rect are visited. - meshBuffer.indexOffset += 6; - } - } + const vid = vidOrigin; + + // left bottom + ib[indexOffset++] = vid; + // right bottom + ib[indexOffset++] = vid + 1; + // left top + ib[indexOffset++] = vid + 2; + + // right bottom + ib[indexOffset++] = vid + 1; + // right top + ib[indexOffset++] = vid + 3; + // left top + ib[indexOffset++] = vid + 2; + + // IndexOffset should add 6 when vertices of a rect are visited. + meshBuffer.indexOffset += 6; // slow version // renderer.switchBufferAccessor().appendIndices(chunk); }, diff --git a/cocos/2d/assembler/sprite/sliced.ts b/cocos/2d/assembler/sprite/sliced.ts index 942d6f62038..e7164a077cb 100644 --- a/cocos/2d/assembler/sprite/sliced.ts +++ b/cocos/2d/assembler/sprite/sliced.ts @@ -47,8 +47,6 @@ export const sliced: IAssembler = { // 0-4 for local vertex renderData.dataLength = 16; renderData.resize(16, 54); - renderData.vertexRow = 4; - renderData.vertexCol = 4; this.QUAD_INDICES = new Uint16Array(54); this.createQuadIndices(4, 4); renderData.chunk.setIndexBuffer(this.QUAD_INDICES as Uint16Array); @@ -140,9 +138,9 @@ export const sliced: IAssembler = { tempRenderData[3].x = width - appX; tempRenderData[3].y = height - appY; - for (let curRow = 0; curRow < renderData.vertexRow; curRow++) { - for (let curCol = 0; curCol < renderData.vertexCol; curCol++) { - const curIndex = curRow * renderData.vertexCol + curCol; + for (let curRow = 0; curRow < 4; curRow++) { + for (let curCol = 0; curCol < 4; curCol++) { + const curIndex = curRow * 4 + curCol; if (curIndex < renderData.dataLength && curRow < tempRenderData.length && curCol < tempRenderData.length) { From 92c37fc921357dacbe6118d5db67668d1769c81d Mon Sep 17 00:00:00 2001 From: Canvas Date: Fri, 18 Aug 2023 14:44:17 +0800 Subject: [PATCH 189/232] fix the animation name is a number and is equal to the index. (#15871) * fix the case where the animation name is a number and is equal to the index. * revert onRestore code. * fix code format. * change internal -> engineInternal. * fix code format. --- cocos/spine/skeleton.ts | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 3c4a77efac7..08c61481ddd 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -95,7 +95,7 @@ interface AnimationItem { } /** - * @internal Since v3.7.2, this is an engine private enum, only used in editor. + * @engineInternal */ export enum DefaultSkinsEnum { default = 0, @@ -103,7 +103,7 @@ export enum DefaultSkinsEnum { ccenum(DefaultSkinsEnum); /** - * @internal Since v3.7.2, this is an engine private enum, only used in editor. + * @engineInternal */ export enum DefaultAnimsEnum { '' = 0 @@ -111,7 +111,7 @@ export enum DefaultAnimsEnum { ccenum(DefaultAnimsEnum); /** - * @internal Since v3.7.2, this is an engine private enum. + * @engineInternal */ export enum SpineMaterialType { COLORED_TEXTURED = 0, @@ -125,7 +125,7 @@ interface AnimationItem { } /** - * @engineInternal Since v3.7.2, this is an engine private interface. + * @engineInternal */ export interface SkeletonDrawData { material: Material | null; @@ -253,11 +253,11 @@ export class Skeleton extends UIRenderer { protected _cachedSockets: Map = new Map(); /** - * @internal + * @engineInternal */ public _startEntry: spine.TrackEntry; /** - * @internal + * @engineInternal */ public _endEntry: spine.TrackEntry; // Paused or playing state @@ -306,7 +306,7 @@ export class Skeleton extends UIRenderer { } /** - * @engineInternal Since v3.7.2, this is an engine private interface. + * @engineInternal */ get drawList (): RecyclePool { return this._drawList; } @@ -342,7 +342,7 @@ export class Skeleton extends UIRenderer { } /** - * @internal Since v3.7.2, this is an engine private interface + * @engineInternal */ @displayName('Default Skin') @type(DefaultSkinsEnum) @@ -368,7 +368,7 @@ export class Skeleton extends UIRenderer { return 0; } /** - * @internal Since v3.7.2, this is an engine private interface. + * @engineInternal */ set _defaultSkinIndex (value: number) { let skinsEnum; @@ -393,7 +393,7 @@ export class Skeleton extends UIRenderer { // value of 0 represents no animation /** - * @internal + * @engineInternal */ @displayName('Animation') @type(DefaultAnimsEnum) @@ -416,7 +416,7 @@ export class Skeleton extends UIRenderer { return 0; } /** - * @internal + * @engineInternal */ set _animationIndex (value: number) { let animsEnum; @@ -427,7 +427,7 @@ export class Skeleton extends UIRenderer { error(`${this.name} animation enums are invalid`); return; } - const animName = animsEnum[value]; + const animName = String(animsEnum[value]); if (animName !== undefined) { this.animation = animName; if (EDITOR_NOT_IN_PREVIEW) { @@ -626,10 +626,16 @@ export class Skeleton extends UIRenderer { this._updateDebugDraw(); } - // eslint-disable-next-line @typescript-eslint/no-empty-function + // For Redo, Undo + // call markForUpdateRenderData to make sure renderData will be re-built. + /** + * @engineInternal + */ public onRestore (): void { - + this.updateMaterial(); + this.markForUpdateRenderData(); } + /** * @en Gets the animation state object. * @zh 获取动画状态。 @@ -697,7 +703,7 @@ export class Skeleton extends UIRenderer { if (!this._runtimeData) return; this.setSkeletonData(this._runtimeData); this._refreshInspector(); - if (this.defaultAnimation) this.animation = this.defaultAnimation; + if (this.defaultAnimation) this.animation = this.defaultAnimation.toString(); if (this.defaultSkin) this.setSkin(this.defaultSkin); this._updateUseTint(); this._indexBoneSockets(); @@ -1052,7 +1058,7 @@ export class Skeleton extends UIRenderer { } /** - * @engineInternal Since v3.7.2, this is an engine private interface. + * @engineInternal */ public getMaterialForBlendAndTint (src: BlendFactor, dst: BlendFactor, type: SpineMaterialType): MaterialInstance { const key = `${type}/${src}/${dst}`; @@ -1157,7 +1163,7 @@ export class Skeleton extends UIRenderer { } /** - * @engineInternal since v3.7.2 this is an engine private function. + * @engineInternal */ public syncAttachedNode (): void { // sync attached node matrix From 56417f35b06e7aa88c4bdc7a4bf70998c0082bb0 Mon Sep 17 00:00:00 2001 From: oahc09 Date: Fri, 18 Aug 2023 15:11:35 +0800 Subject: [PATCH 190/232] improve:adjust xr begin/end render frame call's position (#16021) (Calculate the correct delta time) --- native/cocos/engine/Engine.cpp | 5 +++-- native/cocos/engine/Engine.h | 3 +++ native/cocos/platform/android/AndroidPlatform.cpp | 2 -- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index 50d34212923..86d7f48e69e 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -206,6 +206,7 @@ void Engine::destroy() { int32_t Engine::run() { BasePlatform *platform = BasePlatform::getPlatform(); + _xr = CC_GET_XR_INTERFACE(); platform->runInPlatformThread([&]() { tick(); }); @@ -284,7 +285,7 @@ void Engine::tick() { #endif prevTime = std::chrono::steady_clock::now(); - + if (_xr) _xr->beginRenderFrame(); _scheduler->update(dt); se::ScriptEngine::getInstance()->handlePromiseExceptions(); @@ -292,7 +293,7 @@ void Engine::tick() { se::ScriptEngine::getInstance()->mainLoopUpdate(); cc::DeferredReleasePool::clear(); - + if (_xr) _xr->endRenderFrame(); now = std::chrono::steady_clock::now(); dtNS = dtNS * 0.1 + 0.9 * static_cast(std::chrono::duration_cast(now - prevTime).count()); dt = static_cast(dtNS) / NANOSECONDS_PER_SECOND; diff --git a/native/cocos/engine/Engine.h b/native/cocos/engine/Engine.h index ff6281faa1c..74c989c56aa 100644 --- a/native/cocos/engine/Engine.h +++ b/native/cocos/engine/Engine.h @@ -48,6 +48,7 @@ class DebugRenderer; class Profiler; class BuiltinResMgr; class ProgramLib; +class IXRInterface; #define NANOSECONDS_PER_SECOND 1000000000 #define NANOSECONDS_60FPS 16666667L @@ -132,6 +133,8 @@ class CC_DLL Engine : public BaseEngine { events::WindowEvent::Listener _windowEventListener; CC_DISALLOW_COPY_MOVE_ASSIGN(Engine); + + IXRInterface *_xr{nullptr}; }; } // namespace cc diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index fc8d213420a..b14f3e2732f 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -843,9 +843,7 @@ int32_t AndroidPlatform::loop() { if (xr && !xr->platformLoopStart()) continue; _inputProxy->handleInput(); if (_inputProxy->isAnimating() && (xr ? xr->getXRConfig(xr::XRConfigKey::SESSION_RUNNING).getBool() : true)) { - if (xr) xr->beginRenderFrame(); runTask(); - if (xr) xr->endRenderFrame(); if (_inputProxy->isActive()) { flushTasksOnGameThreadAtForegroundJNI(); } From d8e75b225de15e90fee4b2bab140a6a48f4ff16c Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Fri, 18 Aug 2023 16:02:41 +0800 Subject: [PATCH 191/232] [ci skip][AUTO]: Automated code generating update: bc27ce06eb5f4f8922ed479ea00c9cc46011c61d (#16021) (#16029) Co-authored-by: cocos-robot --- cocos/native-binding/decorators.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/cocos/native-binding/decorators.ts b/cocos/native-binding/decorators.ts index cfdfc74d5c9..d2ab61a942b 100644 --- a/cocos/native-binding/decorators.ts +++ b/cocos/native-binding/decorators.ts @@ -515,7 +515,6 @@ export function patch_cc_LightProbeInfo(ctx: cc_LightProbeInfo_Context_Args, app const giSamplesDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'giSamples'); const bouncesDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'bounces'); const reduceRingingDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'reduceRinging'); - const showProbeDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'showProbe'); const showWireframeDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'showWireframe'); const showConvexDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'showConvex'); const lightProbeSphereVolumeDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'lightProbeSphereVolume'); @@ -538,8 +537,6 @@ export function patch_cc_LightProbeInfo(ctx: cc_LightProbeInfo_Context_Args, app apply(() => { $.slide(LightProbeInfo.prototype, 'reduceRinging', reduceRingingDescriptor); }, 'slide', 'reduceRinging'); apply(() => { $.range([0.0, 0.05, 0.001])(LightProbeInfo.prototype, 'reduceRinging', reduceRingingDescriptor); }, 'range', 'reduceRinging'); apply(() => { $.editable(LightProbeInfo.prototype, 'reduceRinging', reduceRingingDescriptor); }, 'editable', 'reduceRinging'); - apply(() => { $.tooltip('i18n:light_probe.showProbe')(LightProbeInfo.prototype, 'showProbe', showProbeDescriptor); }, 'tooltip', 'showProbe'); - apply(() => { $.editable(LightProbeInfo.prototype, 'showProbe', showProbeDescriptor); }, 'editable', 'showProbe'); apply(() => { $.tooltip('i18n:light_probe.showWireframe')(LightProbeInfo.prototype, 'showWireframe', showWireframeDescriptor); }, 'tooltip', 'showWireframe'); apply(() => { $.editable(LightProbeInfo.prototype, 'showWireframe', showWireframeDescriptor); }, 'editable', 'showWireframe'); apply(() => { $.tooltip('i18n:light_probe.showConvex')(LightProbeInfo.prototype, 'showConvex', showConvexDescriptor); }, 'tooltip', 'showConvex'); From b0745d50bee84835a54866e8ae84ff0d6f5d0c1c Mon Sep 17 00:00:00 2001 From: mmyduckx <308303735@qq.com> Date: Fri, 18 Aug 2023 16:16:47 +0800 Subject: [PATCH 192/232] add bytedance videoplayer support (#16031) * add bytedance videoplayer support * refine --- .../bytedance/wrapper/engine/VideoPlayer.js | 391 ++++++++++++++++++ .../bytedance/wrapper/engine/index.js | 3 +- 2 files changed, 393 insertions(+), 1 deletion(-) create mode 100644 platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js diff --git a/platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js b/platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js new file mode 100644 index 00000000000..16c572f4e30 --- /dev/null +++ b/platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js @@ -0,0 +1,391 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + +https://www.cocos.com/ + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated engine source code (the "Software"), a limited, +worldwide, royalty-free, non-assignable, revocable and non-exclusive license +to use Cocos Creator solely to develop games on your target platforms. You shall +not use Cocos Creator software for developing other software or tools that's +used for developing games. You are not granted to publish, distribute, +sublicense, and/or sell copies of Cocos Creator. + +The software or tools in this License Agreement are licensed, not sold. +Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +if (cc.internal.VideoPlayer) { + const { EventType } = cc.internal.VideoPlayer; + + const vec3 = cc.Vec3; + const _mat4_temp = cc.mat4(); + + const _topLeft = new vec3(); + const _bottomRight = new vec3(); + + const dpr = tt.getSystemInfoSync().pixelRatio; + + cc.internal.VideoPlayerImplManager.getImpl = function (componenet) { + return new VideoPlayerImplMiniGame(componenet); + }; + + class VideoPlayerImplMiniGame extends cc.internal.VideoPlayerImpl { + constructor (componenet) { + super(componenet); + } + + syncClip (clip) { + this.removeVideoPlayer(); + if (!clip) { + return; + } + this.createVideoPlayer(clip._nativeAsset); + } + + syncURL (url) { + this.removeVideoPlayer(); + if (!url) { + return; + } + this.createVideoPlayer(url); + } + + onCanplay () { + if (this._loaded) { + return; + } + this._loaded = true; + this.setVisible(this._visible); + this.dispatchEvent(EventType.READY_TO_PLAY); + this.delayedPlay(); + } + + _bindEvent () { + const video = this._video; + const self = this; + + if (!video) { + return; + } + video.onCanplay(() => { + if (self._video !== video) return; + self._loaded = true; + self.setVisible(self._visible); + self.dispatchEvent(EventType.READY_TO_PLAY); + video.play(); + const initRect = self._getInitRect(); + function drawVideo () { + requestAnimationFrame(drawVideo); + video.paintTo(cc.game.canvas, initRect.x, initRect.y, 0, 0, initRect.width, initRect.height); + } + drawVideo(video); + }); + video.onPlay(() => { + if (self._video !== video) return; + self._playing = true; + self.dispatchEvent(EventType.PLAYING); + }); + video.onEnded(() => { + if (self._video !== video) return; + self._playing = false; + self._currentTime = self._duration; // ensure currentTime is at the end of duration + self.dispatchEvent(EventType.COMPLETED); + }); + video.onPause(() => { + if (self._video !== video) return; + self._playing = false; + self.dispatchEvent(EventType.PAUSED); + }); + video.onTimeUpdate((res) => { + self._duration = res.duration; + self._currentTime = res.position; + }); + video.onStop(() => { + if (self._video !== video) return; + self._playing = false; + self.dispatchEvent(EventType.STOPPED); + }); + } + + _unbindEvent () { + const video = this._video; + if (!video) { + return; + } + + video.offPlay(); + video.offEnded(); + video.offPause(); + video.offTimeUpdate(); + video.offStop(); + } + + createVideoPlayer (url) { + if (!tt.createVideo) { + console.warn('VideoPlayer not supported'); + return; + } + + if (!this._video) { + this._video = tt.createOffscreenVideo(); + this._duration = 0; + this._currentTime = 0; + this._loaded = false; + this.setVisible(this._visible); + this._bindEvent(); + this._forceUpdate = true; + } + + this.setURL(url); + this._forceUpdate = true; + } + + setURL (path) { + const video = this._video; + if (!video || video.src === path) { + return; + } + video.stop(); + this._unbindEvent(); + video.autoplay = true; + video.src = path; + video.muted = true; + const self = this; + this._loaded = false; + function loadedCallback () { + self._bindEvent(); + video.muted = false; + self._loaded = true; + self.dispatchEvent(EventType.READY_TO_PLAY); + } + function endedCallback () { + video.offPlay(); + video.stop(); + self._playing = false; + self._currentTime = 0; + self.dispatchEvent(EventType.COMPLETED); + } + video.onPlay(loadedCallback); + video.onEnded(endedCallback); + } + + removeVideoPlayer () { + const video = this.video; + if (video) { + video.stop(); + video.destroy(); + this._playing = false; + this._loaded = false; + this._loadedMeta = false; + this._ignorePause = false; + this._cachedCurrentTime = 0; + this._video = null; + } + } + + setVisible (value) { + const video = this._video; + if (!video || this._visible === value) { + return; + } + if (value) { + video.width = this._actualWidth || 0; + } else { + video.width = 0; // hide video + } + this._visible = value; + } + + getDuration () { + return this.duration(); + } + + duration () { + return this._duration; + } + + syncPlaybackRate (value) { + const video = this._video; + if (video && value !== video.playbackRate) { + if (value === 0.5 | value === 0.8 | value === 1.0 | value === 1.25 | value === 1.5) { + video.playbackRate = value; + } else { + console.warn('The platform does not support this PlaybackRate!'); + } + } + } + + syncVolume () { + console.warn('The platform does not support'); + } + + syncMute (enable) { + const video = this._video; + if (video && video.muted !== enable) { + video.muted = enable; + } + } + + syncLoop (enable) { + const video = this._video; + if (video && video.loop !== enable) { + video.loop = enable; + } + } + + syncStayOnBottom () { + console.warn('The platform does not support'); + } + + getCurrentTime () { + if (this.video) { + return this.currentTime(); + } + return -1; + } + + currentTime () { + return this._currentTime; + } + + seekTo (time) { + const video = this._video; + if (!video || !this._loaded) return; + video.seek(time); + } + + disable (noPause) { + if (this._video) { + if (!noPause) { + this._video.pause(); + } + this.setVisible(false); + this._visible = false; + } + } + + enable () { + if (this._video) { + this.setVisible(true); + this._visible = true; + } + } + + canPlay () { + this._video.play(); + this.syncCurrentTime(); + } + + resume () { + const video = this._video; + if (this._playing || !video) return; + + video.play(); + } + + pause () { + const video = this._video; + if (!this._playing || !video) return; + + video.pause(); + } + + stop () { + const self = this; + const video = this._video; + if (!video || !this._visible) return; + video.stop().then((res) => { + if (res.errMsg && !res.errMsg.includes('ok')) { + console.error('failed to stop video player'); + return; + } + self._currentTime = 0; + self._playing = false; + self.dispatchEvent(EventType.STOPPED); + }); + } + + canFullScreen (enabled) { + if (this._video) { + this.setFullScreenEnabled(enabled); + } + } + + setFullScreenEnabled (enable) { + const video = this._video; + if (!video || this._fullScreenEnabled === enable) { + return; + } + if (enable) { + video.requestFullScreen(); + } else { + video.exitFullScreen(); + } + this._fullScreenEnabled = enable; + } + + syncKeepAspectRatio (enabled) { + console.warn('On bytedance game videoPlayer is always keep the aspect ratio'); + } + + syncMatrix () { + // DO NOTHING... + } + + _getInitRect () { + if (!this._component || !this._uiTrans) return; + + const camera = this.UICamera; + if (!camera) { + return; + } + + this._component.node.getWorldMatrix(_mat4_temp); + const uiWidth = this._uiTrans.contentSize.width; + const uiHeight = this._uiTrans.contentSize.height; + + this._m00 = _mat4_temp.m00; + this._m01 = _mat4_temp.m01; + this._m04 = _mat4_temp.m04; + this._m05 = _mat4_temp.m05; + this._m12 = _mat4_temp.m12; + this._m13 = _mat4_temp.m13; + this._w = uiWidth; + this._h = uiHeight; + + const canvas_width = cc.game.canvas.width; + const canvas_height = cc.game.canvas.height; + + const ap = this._uiTrans.anchorPoint; + // Vectors in node space + vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0); + vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); + // Convert to world space + vec3.transformMat4(_topLeft, _topLeft, _mat4_temp); + vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp); + // Convert to Screen space + camera.worldToScreen(_topLeft, _topLeft); + camera.worldToScreen(_bottomRight, _bottomRight); + + const finalWidth = _bottomRight.x - _topLeft.x; + const finalHeight = _topLeft.y - _bottomRight.y; + + const x = _topLeft.x; + const y = canvas_height - _topLeft.y; + const width = finalWidth; + const height = finalHeight; + return { + x, y, width, height, + }; + } + } +} diff --git a/platforms/minigame/platforms/bytedance/wrapper/engine/index.js b/platforms/minigame/platforms/bytedance/wrapper/engine/index.js index bcb93ce2a33..26624d377e0 100644 --- a/platforms/minigame/platforms/bytedance/wrapper/engine/index.js +++ b/platforms/minigame/platforms/bytedance/wrapper/engine/index.js @@ -1,4 +1,5 @@ require('../fs-utils'); require('../../../../common/engine/index'); +require('./VideoPlayer'); require('./Label'); -require('./ImageAsset'); \ No newline at end of file +require('./ImageAsset'); From be9a52dc36c00a2cbfa14c84e5bd17a110714c28 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Aug 2023 17:32:05 +0800 Subject: [PATCH 193/232] export ISpriteFrameInitInfo for SpriteFrame reset (#16005) --- cocos/2d/assets/sprite-frame.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/assets/sprite-frame.ts b/cocos/2d/assets/sprite-frame.ts index abc7d4194f3..4f9394aaa4a 100644 --- a/cocos/2d/assets/sprite-frame.ts +++ b/cocos/2d/assets/sprite-frame.ts @@ -105,7 +105,7 @@ interface ISpriteFrameOriginal { * @en Information object interface for initialize a [[SpriteFrame]] asset. * @zh 用于初始化 [[SpriteFrame]] 资源的对象接口描述。 */ -interface ISpriteFrameInitInfo { +export interface ISpriteFrameInitInfo { /** * @en The texture of the sprite frame, could be `TextureBase`. * @zh 贴图对象资源,可以是 `TextureBase` 类型。 From ae9b42740b9647bce0e50581ec7ea18488efdda5 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Fri, 18 Aug 2023 18:01:55 +0800 Subject: [PATCH 194/232] deprecate conetwsit constraint, use configurable constraint instead (#15987) --- cocos/physics/framework/deprecated.ts | 7 +++++++ cocos/physics/framework/physics-enum.ts | 1 + cocos/physics/framework/physics-selector.ts | 6 ++++++ cocos/physics/physx/instantiate.ts | 3 --- cocos/physics/spec/i-physics-constraint.ts | 3 +++ 5 files changed, 17 insertions(+), 3 deletions(-) diff --git a/cocos/physics/framework/deprecated.ts b/cocos/physics/framework/deprecated.ts index 9473bf7a3d8..6a9d9519d11 100644 --- a/cocos/physics/framework/deprecated.ts +++ b/cocos/physics/framework/deprecated.ts @@ -33,6 +33,7 @@ import { RigidBody } from './components/rigid-body'; import { Collider } from './components/colliders/collider'; import { PhysicsMaterial } from './assets/physics-material'; import { Constraint } from './components/constraints/constraint'; +import { EConstraintType } from './physics-enum'; replaceProperty(PhysicsSystem, 'PhysicsSystem', [ { @@ -147,6 +148,12 @@ removeProperty(RigidBody.prototype, 'RigidBody.prototype', [ }, ]); +removeProperty(EConstraintType, 'EConstraintType.prototype', [ + { + name: 'CONE_TWIST', + }, +]); + /** * Alias of [[RigidBody]] * @deprecated Since v1.2 diff --git a/cocos/physics/framework/physics-enum.ts b/cocos/physics/framework/physics-enum.ts index 4ea4538a92f..a84d210aa48 100644 --- a/cocos/physics/framework/physics-enum.ts +++ b/cocos/physics/framework/physics-enum.ts @@ -275,6 +275,7 @@ export enum EConstraintType { * Cone twist constraint. * @zh * 锥形扭转约束。 + * @deprecated coneTwist is deprecated, please use configurable instead */ CONE_TWIST, /** diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 306613dc6dc..9be81501389 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -58,6 +58,9 @@ interface IPhysicsWrapperObject { PlaneShape?: Constructor, PointToPointConstraint?: Constructor, HingeConstraint?: Constructor, + /** + * @deprecated cone twist constraint is deprecated, please use configurable instead + */ ConeTwistConstraint?: Constructor, FixedConstraint?: Constructor, ConfigurableConstraint?: Constructor, @@ -233,6 +236,9 @@ enum ECheckType { // JOINT // PointToPointConstraint, HingeConstraint, + /** + * @deprecated cone twist constraint is deprecated, please use configurable instead + */ ConeTwistConstraint, FixedConstraint, ConfigurableConstraint, diff --git a/cocos/physics/physx/instantiate.ts b/cocos/physics/physx/instantiate.ts index 3a083bba0b1..6e89eff9701 100644 --- a/cocos/physics/physx/instantiate.ts +++ b/cocos/physics/physx/instantiate.ts @@ -58,17 +58,14 @@ game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { CylinderShape: PhysXCylinderShape, ConeShape: PhysXConeShape, TerrainShape: PhysXTerrainShape, - // SimplexShape: PhysXSimplexShape, PlaneShape: PhysXPlaneShape, PointToPointConstraint: PhysXSphericalJoint, - // PointToPointConstraint: PhysXFixedJoint, HingeConstraint: PhysXRevoluteJoint, FixedConstraint: PhysXFixedJoint, ConfigurableConstraint: PhysXConfigurableJoint, BoxCharacterController: PhysXBoxCharacterController, CapsuleCharacterController: PhysXCapsuleCharacterController, - }); }); diff --git a/cocos/physics/spec/i-physics-constraint.ts b/cocos/physics/spec/i-physics-constraint.ts index 76985a0df63..91664b25717 100644 --- a/cocos/physics/spec/i-physics-constraint.ts +++ b/cocos/physics/spec/i-physics-constraint.ts @@ -97,4 +97,7 @@ export interface IConfigurableConstraint extends IBaseConstraint { setBreakTorque(v: number): void; } +/** + * @deprecated ConeTwistConstraint is deprecated, please use ConfigurableConstraint instead + */ export type IConeTwistConstraint = IBaseConstraint From e5488b7d32189c498b70a9931538940025454646 Mon Sep 17 00:00:00 2001 From: Ling Zhan Date: Fri, 18 Aug 2023 19:30:14 +0800 Subject: [PATCH 195/232] V3.8.1 box2d wasm experimental (#15979) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * init * tsconfig.json * add box2d-wasm backend to cocos engine. not crash now in 3.8.0. * rigid-body, collider, and joint works now. * back * Joint: SetLinearFrequencyAndDampingRatio * PhysicsRayCastCallback, PhysicsAABBQueryCallback * box2d wasm debugDraw * asm.js * B2PolygonShape uses B2.ConvexPartition * box2d wasm contact disabled works now. * add unit test for physics2d. * b2ContactListenerWrapper::registerContactFixture * tweak * drawPolygon transfer array data from wasm to ts * tweak * contact event performance opt * revert to polygon collider 2d to original implementation. no need for libtess any more. * PostSolve ContactImpulse use raw pointer. * TransformVector2; debugDraw supports transform * enable rtti * WASM_OBJECT_PTR_2_TS_OBJECT, WASM_OBJECT_PTR_2_WASM_OBJECT * fix PreSolve parameter oldManifold error * B2.TransformVector2 --> b2Mul(in ts) * tweaks: code format. * eslint * eslint * remove physics-2d-box2d-wasm from render-config.json * comment tweaks * [opt] debug draw performance opt * tweaks --- cc.config.json | 3 + cocos/physics-2d/box2d-wasm/box2d.asmjs.ts | 30 ++ cocos/physics-2d/box2d-wasm/box2d.null.ts | 28 ++ cocos/physics-2d/box2d-wasm/box2d.wasmjs.ts | 31 ++ cocos/physics-2d/box2d-wasm/instantiate.ts | 60 +++ cocos/physics-2d/box2d-wasm/instantiated.ts | 148 ++++++ .../box2d-wasm/joints/distance-joint.ts | 46 ++ .../box2d-wasm/joints/fixed-joint.ts | 58 +++ .../box2d-wasm/joints/hinge-joint.ts | 83 ++++ .../physics-2d/box2d-wasm/joints/joint-2d.ts | 129 +++++ .../box2d-wasm/joints/mouse-joint.ts | 138 ++++++ .../box2d-wasm/joints/relative-joint.ts | 73 +++ .../box2d-wasm/joints/slider-joint.ts | 85 ++++ .../box2d-wasm/joints/spring-joint.ts | 63 +++ .../box2d-wasm/joints/wheel-joint.ts | 80 ++++ .../physics-2d/box2d-wasm/physics-contact.ts | 289 ++++++++++++ cocos/physics-2d/box2d-wasm/physics-world.ts | 441 ++++++++++++++++++ .../platform/physics-aabb-query-callback.ts | 73 +++ .../platform/physics-contact-listener.ts | 72 +++ .../box2d-wasm/platform/physics-debug-draw.ts | 199 ++++++++ .../platform/physics-ray-cast-callback.ts | 98 ++++ cocos/physics-2d/box2d-wasm/rigid-body.ts | 362 ++++++++++++++ .../box2d-wasm/shapes/box-shape-2d.ts | 76 +++ .../box2d-wasm/shapes/circle-shape-2d.ts | 59 +++ .../box2d-wasm/shapes/polygon-shape-2d.ts | 115 +++++ .../physics-2d/box2d-wasm/shapes/shape-2d.ts | 228 +++++++++ cocos/physics-2d/box2d/physics-world.ts | 20 +- cocos/physics-2d/builtin/builtin-world.ts | 32 +- cocos/physics-2d/framework/index.ts | 2 + .../physics-2d/framework/physics-selector.ts | 11 +- cocos/physics-2d/framework/physics-system.ts | 13 +- editor/engine-features/schema.json | 6 + editor/engine-features/types.ts | 1 + exports/physics-2d-box2d-wasm.ts | 26 ++ exports/wait-for-box2d-instantiation.ts | 27 ++ native/external-config.json | 2 +- scripts/build-engine/.vscode/launch.json | 1 + .../tests/stats-query/cc.config.json | 1 + tests/init.ts | 8 + tests/physics2d/collider.ts | 43 ++ tests/physics2d/events.ts | 49 ++ tests/physics2d/physics2d.test.ts | 50 ++ tests/physics2d/rigid-body.ts | 142 ++++++ tests/physics2d/scene-query.ts | 96 ++++ tsconfig.json | 1 + 45 files changed, 3567 insertions(+), 31 deletions(-) create mode 100644 cocos/physics-2d/box2d-wasm/box2d.asmjs.ts create mode 100644 cocos/physics-2d/box2d-wasm/box2d.null.ts create mode 100644 cocos/physics-2d/box2d-wasm/box2d.wasmjs.ts create mode 100644 cocos/physics-2d/box2d-wasm/instantiate.ts create mode 100644 cocos/physics-2d/box2d-wasm/instantiated.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/distance-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/fixed-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/hinge-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/joint-2d.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/mouse-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/relative-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/slider-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/spring-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/joints/wheel-joint.ts create mode 100644 cocos/physics-2d/box2d-wasm/physics-contact.ts create mode 100644 cocos/physics-2d/box2d-wasm/physics-world.ts create mode 100644 cocos/physics-2d/box2d-wasm/platform/physics-aabb-query-callback.ts create mode 100644 cocos/physics-2d/box2d-wasm/platform/physics-contact-listener.ts create mode 100644 cocos/physics-2d/box2d-wasm/platform/physics-debug-draw.ts create mode 100644 cocos/physics-2d/box2d-wasm/platform/physics-ray-cast-callback.ts create mode 100644 cocos/physics-2d/box2d-wasm/rigid-body.ts create mode 100644 cocos/physics-2d/box2d-wasm/shapes/box-shape-2d.ts create mode 100644 cocos/physics-2d/box2d-wasm/shapes/circle-shape-2d.ts create mode 100644 cocos/physics-2d/box2d-wasm/shapes/polygon-shape-2d.ts create mode 100644 cocos/physics-2d/box2d-wasm/shapes/shape-2d.ts create mode 100644 exports/physics-2d-box2d-wasm.ts create mode 100644 exports/wait-for-box2d-instantiation.ts create mode 100644 tests/physics2d/collider.ts create mode 100644 tests/physics2d/events.ts create mode 100644 tests/physics2d/rigid-body.ts create mode 100644 tests/physics2d/scene-query.ts diff --git a/cc.config.json b/cc.config.json index f4d4da87658..ad9f279be52 100644 --- a/cc.config.json +++ b/cc.config.json @@ -98,6 +98,9 @@ "physics-2d-builtin": { "modules": ["physics-2d-builtin", "physics-2d-framework"] }, + "physics-2d-box2d-wasm": { + "modules": ["physics-2d-box2d-wasm", "physics-2d-framework"] + }, "intersection-2d": { "modules": ["intersection-2d"] }, diff --git a/cocos/physics-2d/box2d-wasm/box2d.asmjs.ts b/cocos/physics-2d/box2d-wasm/box2d.asmjs.ts new file mode 100644 index 00000000000..a4304945dc0 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/box2d.asmjs.ts @@ -0,0 +1,30 @@ +/* + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * export box2d from internal module + */ +import asmFactory from 'external:emscripten/box2d/box2d.release.asm.js'; + +export { asmFactory }; diff --git a/cocos/physics-2d/box2d-wasm/box2d.null.ts b/cocos/physics-2d/box2d-wasm/box2d.null.ts new file mode 100644 index 00000000000..ad885b3845a --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/box2d.null.ts @@ -0,0 +1,28 @@ +/* + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * export null for module elimination + */ +export const asmFactory = null; diff --git a/cocos/physics-2d/box2d-wasm/box2d.wasmjs.ts b/cocos/physics-2d/box2d-wasm/box2d.wasmjs.ts new file mode 100644 index 00000000000..78c64b77406 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/box2d.wasmjs.ts @@ -0,0 +1,31 @@ +/* + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * export box2d from internal module + */ +import wasmFactory from 'external:emscripten/box2d/box2d.release.wasm.js'; +import box2dWasmUrl from 'external:emscripten/box2d/box2d.release.wasm.wasm'; + +export { wasmFactory, box2dWasmUrl }; diff --git a/cocos/physics-2d/box2d-wasm/instantiate.ts b/cocos/physics-2d/box2d-wasm/instantiate.ts new file mode 100644 index 00000000000..2de0f968ed4 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/instantiate.ts @@ -0,0 +1,60 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { selector } from '../framework/physics-selector'; +import { B2PhysicsWorld } from './physics-world'; +import { B2RigidBody2D } from './rigid-body'; +import { B2BoxShape } from './shapes/box-shape-2d'; +import { B2CircleShape } from './shapes/circle-shape-2d'; +import { B2PolygonShape } from './shapes/polygon-shape-2d'; +import { B2MouseJoint } from './joints/mouse-joint'; +import { B2DistanceJoint } from './joints/distance-joint'; +import { B2SpringJoint } from './joints/spring-joint'; +import { B2RelativeJoint } from './joints/relative-joint'; +import { B2SliderJoint } from './joints/slider-joint'; +import { B2FixedJoint } from './joints/fixed-joint'; +import { B2WheelJoint } from './joints/wheel-joint'; +import { B2HingeJoint } from './joints/hinge-joint'; + +import { Game, game } from '../../game'; + +game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { + selector.register('box2d-wasm', { + PhysicsWorld: B2PhysicsWorld, + RigidBody: B2RigidBody2D, + + BoxShape: B2BoxShape, + CircleShape: B2CircleShape, + PolygonShape: B2PolygonShape, + + MouseJoint: B2MouseJoint, + DistanceJoint: B2DistanceJoint, + SpringJoint: B2SpringJoint, + RelativeJoint: B2RelativeJoint, + SliderJoint: B2SliderJoint, + FixedJoint: B2FixedJoint, + WheelJoint: B2WheelJoint, + HingeJoint: B2HingeJoint, + }); +}); diff --git a/cocos/physics-2d/box2d-wasm/instantiated.ts b/cocos/physics-2d/box2d-wasm/instantiated.ts new file mode 100644 index 00000000000..5156374fd49 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/instantiated.ts @@ -0,0 +1,148 @@ +/* + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { instantiateWasm, fetchBuffer } from 'pal/wasm'; +import { JSB, WASM_SUPPORT_MODE, CULL_ASM_JS_MODULE, EDITOR, TEST } from 'internal:constants'; +import { wasmFactory, box2dWasmUrl } from './box2d.wasmjs'; +import { asmFactory } from './box2d.asmjs'; + +import { game } from '../../game'; +import { getError, error, sys, debug, IVec2Like } from '../../core'; +import { WebAssemblySupportMode } from '../../misc/webassembly-support'; + +export const B2 = {} as any; + +export function getImplPtr (wasmObject: any): number { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return (wasmObject).$$.ptr; +} + +/** +* mapping wasm-object-ptr to ts-object +* B2.Fixture pointer -->B2Shape2D +* B2.Body pointer --> B2RigidBody2D +* B2.Contact pointer --> PhysicsContact +* B2.Joint pointer --> B2Joint +* ... +*/ +const WASM_OBJECT_PTR_2_TS_OBJECT = {}; +export function addImplPtrReference (TSObject: any, implPtr: number): void { + if (implPtr) { WASM_OBJECT_PTR_2_TS_OBJECT[implPtr] = TSObject; } +} +export function removeImplPtrReference (implPtr: number): void { + if (implPtr) { + delete WASM_OBJECT_PTR_2_TS_OBJECT[implPtr]; + } +} +export function getTSObjectFromWASMObjectPtr (implPtr: number): T { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return WASM_OBJECT_PTR_2_TS_OBJECT[implPtr]; +} +export function getTSObjectFromWASMObject (impl: any): T { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return WASM_OBJECT_PTR_2_TS_OBJECT[getImplPtr(impl)]; +} + +/** +* mapping wasm-object-ptr to wasm-object +* B2.Fixture pointer -->B2.Fixture +* B2.Body pointer --> B2.Body +* B2.Contact pointer --> B2.Contact +* B2.Joint pointer --> B2.Joint +* ... +*/ +const WASM_OBJECT_PTR_2_WASM_OBJECT = {}; +export function addImplPtrReferenceWASM (WASMObject: any, implPtr: number): void { + if (implPtr) { WASM_OBJECT_PTR_2_WASM_OBJECT[implPtr] = WASMObject; } +} + +export function removeImplPtrReferenceWASM (implPtr: number): void { + if (implPtr) { + delete WASM_OBJECT_PTR_2_WASM_OBJECT[implPtr]; + } +} + +export function getWASMObjectFromWASMObjectPtr (implPtr: number): T { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return WASM_OBJECT_PTR_2_WASM_OBJECT[implPtr]; +} + +/** +* ts implementation of c++ b2Mul +*/ +export function b2Mul (T: any, v: IVec2Like, out: IVec2Like): void { + out.x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; + out.y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +function initWasm (wasmUrl: string): Promise { + return new Promise((resolve, reject) => { + const errorMessage = (err: any): string => `[box2d]: box2d wasm lib load failed: ${err}`; + wasmFactory({ + instantiateWasm ( + importObject: WebAssembly.Imports, + receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void, + ) { + // NOTE: the Promise return by instantiateWasm hook can't be caught. + instantiateWasm(wasmUrl, importObject).then((result: any) => { + receiveInstance(result.instance as WebAssembly.Instance, result.module as WebAssembly.Module); + }).catch((err) => reject(errorMessage(err))); + }, + }).then((Instance: any) => { + if (!EDITOR && !TEST) debug('[box2d]:box2d wasm lib loaded.'); + Object.assign(B2, Instance); + }).then(resolve).catch((err: any) => reject(errorMessage(err))); + }); +} + +function initAsm (): Promise { + if (asmFactory != null) { + return asmFactory().then((instance: any) => { + if (!EDITOR && !TEST) debug('[box2d]:box2d asm lib loaded.'); + Object.assign(B2, instance); + }); + } else { + return new Promise((resolve, reject) => { + resolve(); + }); + } +} + +export function waitForBox2dWasmInstantiation (): Promise { + const errorReport = (msg: any): void => { error(msg); }; + if ((WASM_SUPPORT_MODE as WebAssemblySupportMode) === WebAssemblySupportMode.MAYBE_SUPPORT) { + if (sys.hasFeature(sys.Feature.WASM)) { + return initWasm(box2dWasmUrl).catch(errorReport); + } else { + return initAsm().catch(errorReport); + } + } else if ((WASM_SUPPORT_MODE as WebAssemblySupportMode) === WebAssemblySupportMode.SUPPORT) { + return initWasm(box2dWasmUrl).catch(errorReport); + } else { + return initAsm().catch(errorReport); + } +} + +game.onPostInfrastructureInitDelegate.add(waitForBox2dWasmInstantiation); diff --git a/cocos/physics-2d/box2d-wasm/joints/distance-joint.ts b/cocos/physics-2d/box2d-wasm/joints/distance-joint.ts new file mode 100644 index 00000000000..79484881da8 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/distance-joint.ts @@ -0,0 +1,46 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { IDistanceJoint } from '../../spec/i-physics-joint'; +import { B2Joint } from './joint-2d'; +import { DistanceJoint2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; + +export class B2DistanceJoint extends B2Joint implements IDistanceJoint { + setMaxLength (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.RopeJoint).SetMaxLength(v); + } + } + + _createJointDef (): any { + const comp = this._jointComp as DistanceJoint2D; + const def = new B2.RopeJointDef(); + def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO }; + def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO }; + def.maxLength = comp.maxLength / PHYSICS_2D_PTM_RATIO; + return def; + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/fixed-joint.ts b/cocos/physics-2d/box2d-wasm/joints/fixed-joint.ts new file mode 100644 index 00000000000..d5de28d963a --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/fixed-joint.ts @@ -0,0 +1,58 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { IFixedJoint } from '../../spec/i-physics-joint'; +import { B2Joint } from './joint-2d'; +import { FixedJoint2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; + +export class B2FixedJoint extends B2Joint implements IFixedJoint { + setFrequency (v: number): void { + this.updateStiffnessAndDamping(); + } + setDampingRatio (v: number): void { + this.updateStiffnessAndDamping(); + } + updateStiffnessAndDamping (): void { + if (this._b2joint) { + B2.SetLinearFrequencyAndDampingRatio( + this._b2joint, + (this._jointComp as FixedJoint2D).frequency, + (this._jointComp as FixedJoint2D).dampingRatio, + ); + } + } + + _createJointDef (): any { + const comp = this._jointComp as FixedJoint2D; + const def = new B2.WeldJointDef(); + def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO }; + def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO }; + def.referenceAngle = 0; + def.damping = 0;//comp.dampingRatio; + def.stiffness = 1;//comp.frequency; + return def; + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/hinge-joint.ts b/cocos/physics-2d/box2d-wasm/joints/hinge-joint.ts new file mode 100644 index 00000000000..dedde81f871 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/hinge-joint.ts @@ -0,0 +1,83 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { IHingeJoint } from '../../spec/i-physics-joint'; +import { HingeJoint2D } from '../../framework'; +import { B2Joint } from './joint-2d'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { toRadian } from '../../../core'; + +export class B2HingeJoint extends B2Joint implements IHingeJoint { + enableLimit (v: boolean): void { + if (this._b2joint) { + (this._b2joint as B2.RevoluteJoint).EnableLimit(v); + } + } + setLowerAngle (v: number): void { + this.updateLimits(); + } + setUpperAngle (v: number): void { + this.updateLimits(); + } + updateLimits (): void { + if (this._b2joint) { + const comp = this._jointComp as HingeJoint2D; + (this._b2joint as B2.RevoluteJoint).SetLimits(toRadian(comp.lowerAngle), toRadian(comp.upperAngle)); + } + } + + // motor + enableMotor (v: boolean): void { + if (this._b2joint) { + (this._b2joint as B2.RevoluteJoint).EnableMotor(v); + } + } + setMaxMotorTorque (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.RevoluteJoint).SetMaxMotorTorque(v); + } + } + setMotorSpeed (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.RevoluteJoint).SetMotorSpeed(v); + } + } + + _createJointDef (): any { + const comp = this._jointComp as HingeJoint2D; + const def = new B2.RevoluteJointDef(); + def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO }; + def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO }; + + def.enableMotor = comp.enableMotor; + def.maxMotorTorque = comp.maxMotorTorque; + def.motorSpeed = toRadian(comp.motorSpeed); + + def.enableLimit = comp.enableLimit; + def.lowerAngle = toRadian(comp.lowerAngle); + def.upperAngle = toRadian(comp.upperAngle); + return def; + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/joint-2d.ts b/cocos/physics-2d/box2d-wasm/joints/joint-2d.ts new file mode 100644 index 00000000000..2f0990e0d6b --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/joint-2d.ts @@ -0,0 +1,129 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2, addImplPtrReference, addImplPtrReferenceWASM, getImplPtr } from '../instantiated'; +import { IJoint2D } from '../../spec/i-physics-joint'; +import { Joint2D, PhysicsSystem2D, RigidBody2D } from '../../framework'; +import { B2PhysicsWorld } from '../physics-world'; +import { Vec2, warn } from '../../../core'; + +export class B2Joint implements IJoint2D { + get impl (): B2.Joint | null { + return this._b2joint; + } + get comp (): Joint2D | null { + return this._jointComp; + } + get body (): RigidBody2D | null { + return this._body; + } + + protected _b2joint: B2.Joint | null = null; + protected _jointComp: Joint2D | null = null; + protected _body: RigidBody2D | null = null; + + private _inited = false; + + initialize (comp: Joint2D): void { + this._jointComp = comp; + } + + onEnable (): void { + PhysicsSystem2D.instance._callAfterStep(this, this._init); + } + + onDisable (): void { + PhysicsSystem2D.instance._callAfterStep(this, this._destroy); + } + + // need init after body and connected body init + start (): void { + PhysicsSystem2D.instance._callAfterStep(this, this._init); + } + + _init (): void { + if (this._inited) return; + + const comp = this._jointComp!; + if (!comp.isValid) { + return; + } + + this._body = comp.getComponent(RigidBody2D); + if (!this._body) { + warn(`Joint2D: Body is not found, can not create joint. Node Name: ${comp.node.name}`); + return; + } + + const def = this._createJointDef(); + if (!def) { + return; + } + + def.SetBodyA(this._body.impl!.impl as B2.Body); + const connectedBody = comp.connectedBody; + //if connected body is set but not active, return + if (connectedBody && !connectedBody.enabledInHierarchy) { + return; + } + + //if connected body is not set, use scene origin as connected body + if (!connectedBody) { + def.SetBodyB((PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).groundBodyImpl); + } else { + def.SetBodyB(connectedBody.impl!.impl as B2.Body); + } + + def.collideConnected = comp.collideConnected; + + this._b2joint = (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).impl.CreateJoint(def); + addImplPtrReference(this, getImplPtr(this._b2joint)); + addImplPtrReferenceWASM(this._b2joint, getImplPtr(this._b2joint)); + + this.updateStiffnessAndDamping(); + + this._inited = true; + } + + _destroy (): void { + if (!this._inited) return; + + (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).impl.DestroyJoint(this._b2joint!); + + this._b2joint = null; + this._inited = false; + } + + _createJointDef (): B2.JointDef | null { + return null; + } + + isValid (): Joint2D | null { + return this._b2joint && this._body && this._body.impl && this._jointComp; + } + + updateStiffnessAndDamping (): void { + // do nothing + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/mouse-joint.ts b/cocos/physics-2d/box2d-wasm/joints/mouse-joint.ts new file mode 100644 index 00000000000..f5d359056da --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/mouse-joint.ts @@ -0,0 +1,138 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { IMouseJoint } from '../../spec/i-physics-joint'; +import { B2Joint } from './joint-2d'; +import { MouseJoint2D, PhysicsSystem2D, Joint2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { IVec2Like, Vec2 } from '../../../core'; +import { Touch } from '../../../input/types'; +import { B2PhysicsWorld } from '../physics-world'; +import { NodeEventType } from '../../../scene-graph/node-event'; +import { find } from '../../../scene-graph'; + +const tempB2Vec2 = { x: 0, y: 0 };//new b2.Vec2(); + +export class B2MouseJoint extends B2Joint implements IMouseJoint { + _touchPoint = new Vec2(); + _isTouched = false; + + setTarget (v: IVec2Like): void { + if (this._b2joint) { + tempB2Vec2.x = v.x / PHYSICS_2D_PTM_RATIO; + tempB2Vec2.y = v.y / PHYSICS_2D_PTM_RATIO; + (this._b2joint as B2.MouseJoint).SetTarget(tempB2Vec2); + } + } + setFrequency (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.MouseJoint).SetFrequency(v); + } + } + setDampingRatio (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.MouseJoint).SetDampingRatio(v); + } + } + setMaxForce (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.MouseJoint).SetMaxForce(v); + } + } + + _createJointDef (): any { + const def = new B2.MouseJointDef(); + const comp = this._jointComp as MouseJoint2D; + def.target = { x: this._touchPoint.x / PHYSICS_2D_PTM_RATIO, y: this._touchPoint.y / PHYSICS_2D_PTM_RATIO }; + def.maxForce = comp.maxForce; + def.dampingRatio = comp.dampingRatio; + def.frequencyHz = comp.frequency; + return def; + } + + initialize (comp: Joint2D): void { + super.initialize(comp); + + const canvas = find('Canvas'); + if (canvas) { + canvas.on(NodeEventType.TOUCH_START, this.onTouchBegan, this); + canvas.on(NodeEventType.TOUCH_MOVE, this.onTouchMove, this); + canvas.on(NodeEventType.TOUCH_END, this.onTouchEnd, this); + canvas.on(NodeEventType.TOUCH_CANCEL, this.onTouchEnd, this); + } + } + + onEnable (): void { + //empty + } + + start (): void { + //empty + } + + onTouchBegan (event: Touch): void { + this._isTouched = true; + + const target = this._touchPoint.set(event.getUILocation()); + + const world = (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld); + const colliders = world.testPoint(target); + if (colliders.length <= 0) return; + + const body = colliders[0].body; + body!.wakeUp(); + + const comp = this._jointComp as MouseJoint2D; + comp.connectedBody = body; + + this._init(); + + this.setMaxForce(comp.maxForce * body!.getMass()); + this.setTarget(target); + } + + onTouchMove (event: Touch): void { + this._touchPoint = event.getUILocation(); + } + + onTouchEnd (event: Touch): void { + this._destroy(); + this._isTouched = false; + } + + update (): void { + if (!this._isTouched || !this.isValid()) { + return; + } + + // let camera = cc.Camera.findCamera(this.node); + // if (camera) { + // this.target = camera.getScreenToWorldPoint(this._touchPoint); + // } + // else { + this.setTarget(this._touchPoint); + // } + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/relative-joint.ts b/cocos/physics-2d/box2d-wasm/joints/relative-joint.ts new file mode 100644 index 00000000000..9b3fea118e6 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/relative-joint.ts @@ -0,0 +1,73 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { IRelativeJoint } from '../../spec/i-physics-joint'; +import { B2Joint } from './joint-2d'; +import { RelativeJoint2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { Vec2, toRadian } from '../../../core'; + +const tempB2Vec2 = { x: 0, y: 0 };//new b2.Vec2(); + +export class B2RelativeJoint extends B2Joint implements IRelativeJoint { + setMaxForce (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.MotorJoint).SetMaxForce(v); + } + } + setAngularOffset (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.MotorJoint).SetAngularOffset(toRadian(v)); + } + } + setLinearOffset (v: Vec2): void { + if (this._b2joint) { + tempB2Vec2.x = v.x / PHYSICS_2D_PTM_RATIO; + tempB2Vec2.y = v.y / PHYSICS_2D_PTM_RATIO; + (this._b2joint as B2.MotorJoint).SetLinearOffset(tempB2Vec2); + } + } + setCorrectionFactor (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.MotorJoint).SetCorrectionFactor(v); + } + } + setMaxTorque (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.MotorJoint).SetMaxTorque(v); + } + } + + _createJointDef (): any { + const comp = this._jointComp as RelativeJoint2D; + const def = new B2.MotorJointDef(); + def.linearOffset = { x: comp.linearOffset.x / PHYSICS_2D_PTM_RATIO, y: comp.linearOffset.y / PHYSICS_2D_PTM_RATIO }; + def.angularOffset = toRadian(comp.angularOffset); + def.maxForce = comp.maxForce; + def.maxTorque = comp.maxTorque; + def.correctionFactor = comp.correctionFactor; + return def; + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/slider-joint.ts b/cocos/physics-2d/box2d-wasm/joints/slider-joint.ts new file mode 100644 index 00000000000..0d22aa4ee23 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/slider-joint.ts @@ -0,0 +1,85 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { ISliderJoint } from '../../spec/i-physics-joint'; +import { B2Joint } from './joint-2d'; +import { SliderJoint2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { toRadian } from '../../../core'; + +export class B2SliderJoint extends B2Joint implements ISliderJoint { + // limit + enableLimit (v: boolean): void { + if (this._b2joint) { + (this._b2joint as B2.PrismaticJoint).EnableLimit(v); + } + } + setLowerLimit (v: number): void { + this.updateLimits(); + } + setUpperLimit (v: number): void { + this.updateLimits(); + } + updateLimits (): void { + if (this._b2joint) { + const comp = this._jointComp as SliderJoint2D; + (this._b2joint as B2.PrismaticJoint).SetLimits(comp.lowerLimit / PHYSICS_2D_PTM_RATIO, comp.upperLimit / PHYSICS_2D_PTM_RATIO); + } + } + + // motor + enableMotor (v: boolean): void { + if (this._b2joint) { + (this._b2joint as B2.PrismaticJoint).EnableMotor(v); + } + } + setMaxMotorForce (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.PrismaticJoint).SetMaxMotorForce(v); + } + } + setMotorSpeed (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.PrismaticJoint).SetMotorSpeed(v); + } + } + + _createJointDef (): any { + const comp = this._jointComp as SliderJoint2D; + const def = new B2.PrismaticJointDef(); + def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO }; + def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO }; + const angle = toRadian(comp.angle); + def.localAxisA = { x: Math.cos(angle), y: Math.sin(angle) }; + def.referenceAngle = 0; + def.enableLimit = comp.enableLimit; + def.lowerTranslation = comp.lowerLimit / PHYSICS_2D_PTM_RATIO; + def.upperTranslation = comp.upperLimit / PHYSICS_2D_PTM_RATIO; + def.enableMotor = comp.enableMotor; + def.maxMotorForce = comp.maxMotorForce; + def.motorSpeed = comp.motorSpeed; + return def; + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/spring-joint.ts b/cocos/physics-2d/box2d-wasm/joints/spring-joint.ts new file mode 100644 index 00000000000..d8faa118417 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/spring-joint.ts @@ -0,0 +1,63 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { ISpringJoint } from '../../spec/i-physics-joint'; +import { B2Joint } from './joint-2d'; +import { SpringJoint2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; + +export class B2SpringJoint extends B2Joint implements ISpringJoint { + setFrequency (v: number): void { + this.updateStiffnessAndDamping(); + } + setDampingRatio (v: number): void { + this.updateStiffnessAndDamping(); + } + updateStiffnessAndDamping (): void { + if (this._b2joint) { + B2.SetLinearFrequencyAndDampingRatio( + this._b2joint, + (this._jointComp as SpringJoint2D).frequency, + (this._jointComp as SpringJoint2D).dampingRatio, + ); + } + } + setDistance (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.DistanceJoint).SetLength(v); + } + } + + _createJointDef (): any { + const comp = this._jointComp as SpringJoint2D; + const def = new B2.DistanceJointDef(); + def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO }; + def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO }; + def.length = comp.distance / PHYSICS_2D_PTM_RATIO; + def.damping = 0;//comp.dampingRatio; + def.stiffness = 1;//comp.frequency; + return def; + } +} diff --git a/cocos/physics-2d/box2d-wasm/joints/wheel-joint.ts b/cocos/physics-2d/box2d-wasm/joints/wheel-joint.ts new file mode 100644 index 00000000000..72be5356593 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/joints/wheel-joint.ts @@ -0,0 +1,80 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { IWheelJoint } from '../../spec/i-physics-joint'; +import { WheelJoint2D } from '../../framework'; +import { B2Joint } from './joint-2d'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { toRadian } from '../../../core'; + +export class B2WheelJoint extends B2Joint implements IWheelJoint { + setFrequency (v: number): void { + this.updateStiffnessAndDamping(); + } + setDampingRatio (v: number): void { + this.updateStiffnessAndDamping(); + } + updateStiffnessAndDamping (): void { + if (this._b2joint) { + B2.SetLinearFrequencyAndDampingRatio( + this._b2joint, + (this._jointComp as WheelJoint2D).frequency, + (this._jointComp as WheelJoint2D).dampingRatio, + ); + } + } + + // motor + enableMotor (v: boolean): void { + if (this._b2joint) { + (this._b2joint as B2.WheelJoint).EnableMotor(v); + } + } + setMaxMotorTorque (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.WheelJoint).SetMaxMotorTorque(v); + } + } + setMotorSpeed (v: number): void { + if (this._b2joint) { + (this._b2joint as B2.WheelJoint).SetMotorSpeed(v); + } + } + + _createJointDef (): any { + const comp = this._jointComp as WheelJoint2D; + const def = new B2.WheelJointDef(); + def.localAnchorA = { x: comp.anchor.x / PHYSICS_2D_PTM_RATIO, y: comp.anchor.y / PHYSICS_2D_PTM_RATIO }; + def.localAnchorB = { x: comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, y: comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO }; + const angle = toRadian(comp.angle); + def.localAxisA = { x: Math.cos(angle), y: Math.sin(angle) }; + def.maxMotorTorque = comp.maxMotorTorque; + def.motorSpeed = toRadian(comp.motorSpeed); + def.enableMotor = comp.enableMotor; + def.damping = 0;//comp.dampingRatio; + def.stiffness = 1;//comp.frequency; + return def; + } +} diff --git a/cocos/physics-2d/box2d-wasm/physics-contact.ts b/cocos/physics-2d/box2d-wasm/physics-contact.ts new file mode 100644 index 00000000000..85f180a9a0e --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/physics-contact.ts @@ -0,0 +1,289 @@ +/* + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2, addImplPtrReference, getTSObjectFromWASMObjectPtr, removeImplPtrReference } from './instantiated'; +import { Vec2 } from '../../core'; +import { PHYSICS_2D_PTM_RATIO } from '../framework/physics-types'; +import { Collider2D, Contact2DType, PhysicsSystem2D } from '../framework'; +import { B2Shape2D } from './shapes/shape-2d'; +import { IPhysics2DContact, IPhysics2DImpulse, IPhysics2DManifoldPoint, IPhysics2DWorldManifold } from '../spec/i-physics-contact'; +import { B2PhysicsWorld } from './physics-world'; + +const pools: PhysicsContact[] = []; + +// temp world manifold +const pointCache = [new Vec2(), new Vec2()]; + +const worldmanifold: IPhysics2DWorldManifold = { + points: [] as Vec2[], + separations: [] as number[], + normal: new Vec2(), +}; + +class ManifoldPoint implements IPhysics2DManifoldPoint { + localPoint = new Vec2(); + normalImpulse = 0; + tangentImpulse = 0; +} + +const manifoldPointCache = [new ManifoldPoint(), new ManifoldPoint()]; + +const manifold = { + type: 0, + localPoint: new Vec2(), + localNormal: new Vec2(), + points: [] as ManifoldPoint[], +}; + +const impulse: IPhysics2DImpulse = { + normalImpulses: [] as number[], + tangentImpulses: [] as number[], +}; + +export class PhysicsContact implements IPhysics2DContact { + static get (b2contact: number): PhysicsContact { + let c = pools.pop(); + + if (!c) { + c = new PhysicsContact(); + } + + c.init(b2contact); + return c; + } + + static put (b2contact: number): void { + const c = getTSObjectFromWASMObjectPtr(b2contact); + if (!c) return; + + pools.push(c); + c.reset(); + } + + colliderA: Collider2D | null = null; + colliderB: Collider2D | null = null; + + disabled = false; + disabledOnce = false; + + private _impulsePtr: number = 0; + private _inverted = false; + private _implPtr: number = 0; //wasm object pointer + private _b2WorldmanifoldPtr: number = 0; //wasm object pointer + + _setImpulse (impulse: number): void { + this._impulsePtr = impulse; + } + + init (b2contact: number): void { + this.colliderA = (getTSObjectFromWASMObjectPtr(B2.ContactGetFixtureA(b2contact) as number)).collider; + this.colliderB = (getTSObjectFromWASMObjectPtr(B2.ContactGetFixtureB(b2contact) as number)).collider; + this.disabled = false; + this.disabledOnce = false; + this._impulsePtr = 0; + this._inverted = false; + + this._implPtr = b2contact; + addImplPtrReference(this, this._implPtr); + this._b2WorldmanifoldPtr = B2.WorldManifoldNew(); + } + + reset (): void { + this.setTangentSpeed(0); + this.resetFriction(); + this.resetRestitution(); + + this.colliderA = null; + this.colliderB = null; + this.disabled = false; + this._impulsePtr = 0; + + removeImplPtrReference(this._implPtr); + this._implPtr = 0; + + B2.WorldManifoldDelete(this._b2WorldmanifoldPtr); + this._b2WorldmanifoldPtr = 0; + } + + getWorldManifold (): IPhysics2DWorldManifold { + const points = worldmanifold.points; + const separations = worldmanifold.separations; + const normal = worldmanifold.normal; + + B2.ContactGetWorldManifold(this._implPtr, this._b2WorldmanifoldPtr); + const b2Manifold = B2.ContactGetManifold(this._implPtr); + const count = B2.ManifoldGetPointCount(b2Manifold); + points.length = separations.length = count; + + for (let i = 0; i < count; i++) { + const p = pointCache[i]; + p.x = B2.WorldManifoldGetPointValueX(this._b2WorldmanifoldPtr, i) * PHYSICS_2D_PTM_RATIO; + p.y = B2.WorldManifoldGetPointValueY(this._b2WorldmanifoldPtr, i) * PHYSICS_2D_PTM_RATIO; + points[i] = p; + separations[i] = B2.WorldManifoldGetSeparationValue(this._b2WorldmanifoldPtr, i) * PHYSICS_2D_PTM_RATIO; + } + + normal.x = B2.WorldManifoldGetNormalValueX(this._b2WorldmanifoldPtr); + normal.y = B2.WorldManifoldGetNormalValueY(this._b2WorldmanifoldPtr); + + if (this._inverted) { + normal.x *= -1; + normal.y *= -1; + } + + return worldmanifold; + } + + getManifold (): { type: number; localPoint: Vec2; localNormal: Vec2; points: ManifoldPoint[]; } { + const points = manifold.points; + const localNormal = manifold.localNormal; + const localPoint = manifold.localPoint; + + const b2Manifold = B2.ContactGetManifold(this._implPtr); + const count = points.length = B2.ManifoldGetPointCount(b2Manifold); + + for (let i = 0; i < count; i++) { + const p = manifoldPointCache[i]; + const b2p = B2.ManifoldGetManifoldPointPtr(b2Manifold, i);//B2.ManifoldPoint + p.localPoint.x = B2.ManifoldPointGetLocalPointX(b2p) * PHYSICS_2D_PTM_RATIO; + p.localPoint.y = B2.ManifoldPointGetLocalPointY(b2p) * PHYSICS_2D_PTM_RATIO; + p.normalImpulse = B2.ManifoldPointGetNormalImpulse(b2p) * PHYSICS_2D_PTM_RATIO; + p.tangentImpulse = B2.ManifoldPointGetTangentImpulse(b2p); //* PHYSICS_2D_PTM_RATIO;? + points[i] = p; + } + + localPoint.x = B2.ManifoldGetLocalPointValueX(b2Manifold) * PHYSICS_2D_PTM_RATIO; + localPoint.y = B2.ManifoldGetLocalPointValueY(b2Manifold) * PHYSICS_2D_PTM_RATIO; + localNormal.x = B2.ManifoldGetLocalNormalValueX(b2Manifold); + localNormal.y = B2.ManifoldGetLocalNormalValueY(b2Manifold); + manifold.type = B2.ManifoldGetType(b2Manifold); + + if (this._inverted) { + localNormal.x *= -1; + localNormal.y *= -1; + } + + return manifold; + } + + getImpulse (): IPhysics2DImpulse | null { + const b2impulse = this._impulsePtr; + if (!b2impulse) return null; + + const normalImpulses = impulse.normalImpulses; + const tangentImpulses = impulse.tangentImpulses; + const count = B2.ContactImpulseGetCount(b2impulse); + for (let i = 0; i < count; i++) { + normalImpulses[i] = B2.ContactImpulseGetNormalImpulse(b2impulse, i) * PHYSICS_2D_PTM_RATIO; + tangentImpulses[i] = B2.ContactImpulseGetTangentImpulse(b2impulse, i); + } + + tangentImpulses.length = normalImpulses.length = count; + + return impulse; + } + + emit (contactType: string): void { + let func = ''; + switch (contactType) { + case Contact2DType.BEGIN_CONTACT: + func = 'onBeginContact'; + break; + case Contact2DType.END_CONTACT: + func = 'onEndContact'; + break; + case Contact2DType.PRE_SOLVE: + func = 'onPreSolve'; + break; + case Contact2DType.POST_SOLVE: + func = 'onPostSolve'; + break; + default: + break; + } + + const colliderA = this.colliderA; + const colliderB = this.colliderB; + + const bodyA = colliderA!.body; + const bodyB = colliderB!.body; + + if (bodyA!.enabledContactListener) { + colliderA?.emit(contactType, colliderA, colliderB, this); + } + + if (bodyB!.enabledContactListener) { + colliderB?.emit(contactType, colliderB, colliderA, this); + } + + if (bodyA!.enabledContactListener || bodyB!.enabledContactListener) { + PhysicsSystem2D.instance.emit(contactType, colliderA, colliderB, this); + } + + if (this.disabled || this.disabledOnce) { + this.setEnabled(false); + this.disabledOnce = false; + } + } + + setEnabled (value: boolean): void { + B2.ContactSetEnabled(this._implPtr, value); + } + + isTouching (): boolean { + return B2.ContactIsTouching(this._implPtr) as boolean; + } + + setTangentSpeed (value: number): void { + B2.ContactSetTangentSpeed(this._implPtr, value); + } + + getTangentSpeed (): number { + return B2.ContactGetTangentSpeed(this._implPtr) as number; + } + + setFriction (value: number): void { + B2.ContactSetFriction(this._implPtr, value); + } + + getFriction (): number { + return B2.ContactGetFriction(this._implPtr) as number; + } + + resetFriction (): void { + B2.ContactResetFriction(this._implPtr); + } + + setRestitution (value: number): void { + B2.ContactSetRestitution(this._implPtr, value); + } + + getRestitution (): number { + return B2.ContactGetRestitution(this._implPtr) as number; + } + + resetRestitution (): void { + B2.ContactResetRestitution(this._implPtr); + } +} diff --git a/cocos/physics-2d/box2d-wasm/physics-world.ts b/cocos/physics-2d/box2d-wasm/physics-world.ts new file mode 100644 index 00000000000..c0997b14915 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/physics-world.ts @@ -0,0 +1,441 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; +import { B2, getImplPtr, addImplPtrReference, addImplPtrReferenceWASM, getTSObjectFromWASMObject, + getTSObjectFromWASMObjectPtr, removeImplPtrReference, removeImplPtrReferenceWASM } from './instantiated'; +import { IPhysicsWorld } from '../spec/i-physics-world'; +import { IVec2Like, Vec3, Quat, toRadian, Vec2, toDegree, Rect, CCObject, js } from '../../core'; +import { PHYSICS_2D_PTM_RATIO, ERaycast2DType, ERigidBody2DType } from '../framework/physics-types'; +import { Canvas } from '../../2d/framework'; +import { Graphics } from '../../2d/components'; + +import { B2RigidBody2D } from './rigid-body'; +import { PhysicsContactListener } from './platform/physics-contact-listener'; +import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback'; +import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback'; +import { PhysicsContact } from './physics-contact'; +import { Contact2DType, Collider2D, RaycastResult2D } from '../framework'; +import { B2Shape2D } from './shapes/shape-2d'; +import { PhysicsDebugDraw } from './platform/physics-debug-draw'; +import { Node, find, Layers } from '../../scene-graph'; +import { director } from '../../game'; + +const tempVec3 = new Vec3(); +const tempVec2_1 = new Vec2(); +const tempVec2_2 = new Vec2(); +const tempB2Vec2_1 = { x: 0, y: 0 }; + +// const tempB2AABB = null;//new B2.AABB(); + +const testResults: Collider2D[] = []; + +export class B2PhysicsWorld implements IPhysicsWorld { + protected _world: B2.World; + protected _bodies: B2RigidBody2D[] = []; + protected _animatedBodies: B2RigidBody2D[] = []; + protected _rotationAxis: Vec3 = new Vec3(); + protected _physicsGroundBody: B2.Body; + + protected _contactListener: B2.ContactListener; + protected _aabbQueryCallback: B2.QueryCallback; + protected _raycastQueryCallback: B2.RayCastCallback; + + private _temoBodyDef: B2.BodyDef; + private _tempB2AABB: B2.AABB; + + get impl (): B2.World { + return this._world; + } + + get groundBodyImpl (): B2.Body { + return this._physicsGroundBody; + } + + constructor () { + this._world = new B2.World({ x: 0, y: -10 }); + this._physicsGroundBody = this._world.CreateBody(new B2.BodyDef() as B2.BodyDef); + PhysicsContactListener._BeginContact = this._onBeginContact; + PhysicsContactListener._EndContact = this._onEndContact; + PhysicsContactListener._PreSolve = this._onPreSolve; + PhysicsContactListener._PostSolve = this._onPostSolve; + this._contactListener = B2.ContactListener.implement(PhysicsContactListener.callback); + this._world.SetContactListener(this._contactListener); + + this._aabbQueryCallback = B2.QueryCallback.implement(PhysicsAABBQueryCallback.callback); + this._raycastQueryCallback = B2.RayCastCallback.implement(PhysicsRayCastCallback.callback); + + this._temoBodyDef = new B2.BodyDef(); + this._tempB2AABB = new B2.AABB(); + } + + _debugGraphics: Graphics | null = null; + _b2DebugDrawer: B2.Draw | null = null; + + _debugDrawFlags = 0; + get debugDrawFlags (): number { + return this._debugDrawFlags; + } + set debugDrawFlags (v) { + if (EDITOR_NOT_IN_PREVIEW) return; + + if (!v) { + if (this._debugGraphics) { + this._debugGraphics.node.parent = null; + } + } + + this._debugDrawFlags = v; + } + + _checkDebugDrawValid (): void { + if (EDITOR_NOT_IN_PREVIEW) return; + if (!this._debugGraphics || !this._debugGraphics.isValid) { + let canvas = find('Canvas'); + if (!canvas) { + const scene = director.getScene(); + if (!scene) { + return; + } + + canvas = new Node('Canvas'); + canvas.addComponent(Canvas); + canvas.parent = scene; + } + + const node = new Node('PHYSICS_2D_DEBUG_DRAW'); + // node.zIndex = cc.macro.MAX_ZINDEX; + node.hideFlags |= CCObject.Flags.DontSave; + node.parent = canvas; + node.worldPosition = Vec3.ZERO; + node.layer = Layers.Enum.UI_2D; + + this._debugGraphics = node.addComponent(Graphics); + this._debugGraphics.lineWidth = 3; + + PhysicsDebugDraw._drawer = this._debugGraphics; + const debugDraw = B2.Draw.implement(PhysicsDebugDraw.callback);//new PhysicsDebugDraw(); + + this._b2DebugDrawer = debugDraw; + this._world.SetDebugDraw(debugDraw as B2.Draw); + } + + const parent = this._debugGraphics.node.parent!; + this._debugGraphics.node.setSiblingIndex(parent.children.length - 1); + + if (this._b2DebugDrawer) { + this._b2DebugDrawer.SetFlags(this.debugDrawFlags); + } + } + + setGravity (v: IVec2Like): void { + this._world.SetGravity(v as B2.Vec2); + } + + setAllowSleep (v: boolean): void { + this._world.SetAllowSleeping(true); + } + + step (deltaTime: number, velocityIterations = 10, positionIterations = 10): void { + const animatedBodies = this._animatedBodies; + for (let i = 0, l = animatedBodies.length; i < l; i++) { + animatedBodies[i].animate(deltaTime); + } + this._world.Step(deltaTime, velocityIterations, positionIterations); + } + + raycast (p1: Vec2, p2: Vec2, type: ERaycast2DType, mask: number): RaycastResult2D[] { + if (p1.equals(p2)) { + return []; + } + + type = type || ERaycast2DType.Closest; + + tempVec2_1.x = p1.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = p1.y / PHYSICS_2D_PTM_RATIO; + tempVec2_2.x = p2.x / PHYSICS_2D_PTM_RATIO; + tempVec2_2.y = p2.y / PHYSICS_2D_PTM_RATIO; + + PhysicsRayCastCallback.init(type, mask); + this._world.RayCast(this._raycastQueryCallback, tempVec2_1, tempVec2_2); + + const fixtures = PhysicsRayCastCallback.getFixtures(); + if (fixtures.length > 0) { + const points = PhysicsRayCastCallback.getPoints(); + const normals = PhysicsRayCastCallback.getNormals(); + const fractions = PhysicsRayCastCallback.getFractions(); + + const results: RaycastResult2D[] = []; + for (let i = 0, l = fixtures.length; i < l; i++) { + const fixture = fixtures[i]; + const shape = getTSObjectFromWASMObject(fixture); + const collider = shape.collider; + + if (type === ERaycast2DType.AllClosest) { + let result; + for (let j = 0; j < results.length; j++) { + if (results[j].collider === collider) { + result = results[j]; + } + } + + if (result) { + if (fractions[i] < result.fraction) { + result.fixtureIndex = shape.getFixtureIndex(fixture); + result.point.x = points[i].x * PHYSICS_2D_PTM_RATIO; + result.point.y = points[i].y * PHYSICS_2D_PTM_RATIO; + result.normal.x = normals[i].x; + result.normal.y = normals[i].y; + result.fraction = fractions[i]; + } + continue; + } + } + + results.push({ + collider, + fixtureIndex: shape.getFixtureIndex(fixture), + point: new Vec2(points[i].x * PHYSICS_2D_PTM_RATIO, points[i].y * PHYSICS_2D_PTM_RATIO), + normal: new Vec2(normals[i].x, normals[i].y), + fraction: fractions[i], + }); + } + + return results; + } + + return []; + } + + syncPhysicsToScene (): void { + const bodies = this._bodies; + for (let i = 0, l = bodies.length; i < l; i++) { + const body = bodies[i]; + const bodyComp = body.rigidBody; + if (bodyComp.type === ERigidBody2DType.Animated) { + body.resetVelocity(); + continue; + } + + const node = bodyComp.node; + const b2body = body.impl!; + + // position + const pos = b2body.GetPosition(); + tempVec3.x = pos.x * PHYSICS_2D_PTM_RATIO; + tempVec3.y = pos.y * PHYSICS_2D_PTM_RATIO; + tempVec3.z = 0; + node.worldPosition = tempVec3; + + // rotation + const angle = toDegree(b2body.GetAngle()); + node.setWorldRotationFromEuler(0, 0, angle); + } + } + syncSceneToPhysics (): void { + const bodies = this._bodies; + for (let i = 0; i < bodies.length; i++) { + bodies[i].syncSceneToPhysics(); + } + } + + addBody (body: B2RigidBody2D): void { + const bodies = this._bodies; + if (bodies.includes(body)) { + return; + } + + const bodyDef = this._temoBodyDef; + + const comp = body.rigidBody; + + bodyDef.allowSleep = comp.allowSleep; + bodyDef.gravityScale = comp.gravityScale; + bodyDef.linearDamping = comp.linearDamping; + bodyDef.angularDamping = comp.angularDamping; + + bodyDef.fixedRotation = comp.fixedRotation; + bodyDef.bullet = comp.bullet; + + const node = comp.node; + const pos = node.worldPosition; + bodyDef.position = { x: pos.x / PHYSICS_2D_PTM_RATIO, y: pos.y / PHYSICS_2D_PTM_RATIO }; + tempVec3.z = Quat.getAxisAngle(this._rotationAxis, node.worldRotation); + if (this._rotationAxis.z < 0.0) { + tempVec3.z = Math.PI * 2 - tempVec3.z; + } + bodyDef.angle = tempVec3.z; + + bodyDef.awake = comp.awakeOnLoad; + + if (comp.type === ERigidBody2DType.Animated) { + bodyDef.type = B2.BodyType.b2_kinematicBody; + this._animatedBodies.push(body); + body._animatedPos.set(bodyDef.position.x, bodyDef.position.y); + body._animatedAngle = bodyDef.angle; + } else { + switch (comp.type) { + case ERigidBody2DType.Dynamic: + bodyDef.type = B2.BodyType.b2_dynamicBody; + break; + case ERigidBody2DType.Static: + bodyDef.type = B2.BodyType.b2_staticBody; + break; + case ERigidBody2DType.Kinematic: + bodyDef.type = B2.BodyType.b2_kinematicBody; + break; + default: + bodyDef.type = B2.BodyType.b2_staticBody; + break; + } + } + + // read private property + const compPrivate = comp as any; + const linearVelocity = compPrivate._linearVelocity; + bodyDef.linearVelocity = { x: linearVelocity.x, y: linearVelocity.y }; + + bodyDef.angularVelocity = toRadian(compPrivate._angularVelocity as number); + + const b2Body = this._world.CreateBody(bodyDef); + addImplPtrReference(body, getImplPtr(b2Body)); + addImplPtrReferenceWASM(b2Body, getImplPtr(b2Body)); + body._imp = b2Body; + + this._bodies.push(body); + } + + removeBody (body: B2RigidBody2D): void { + if (!this._bodies.includes(body)) { + return; + } + if (body.impl) { + removeImplPtrReference(getImplPtr(body.impl)); + removeImplPtrReferenceWASM(getImplPtr(body.impl)); + this._world.DestroyBody(body.impl); + body._imp = null; + } + js.array.remove(this._bodies, body); + + const comp = body.rigidBody; + if (comp.type === ERigidBody2DType.Animated) { + js.array.remove(this._animatedBodies, body); + } + } + + registerContactFixture (fixture: B2.Fixture): void { + this._contactListener.registerContactFixture(getImplPtr(fixture)); + } + unregisterContactFixture (fixture: B2.Fixture): void { + this._contactListener.unregisterContactFixture(getImplPtr(fixture)); + } + + testPoint (point: Vec2): readonly Collider2D[] { + const x = tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO; + const y = tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO; + + const d = 0.2 / PHYSICS_2D_PTM_RATIO; + this._tempB2AABB.lowerBound = { x: x - d, y: y - d }; + this._tempB2AABB.upperBound = { x: x + d, y: y + d }; + + const callback = this._aabbQueryCallback; + PhysicsAABBQueryCallback.init(tempVec2_1); + this._world.QueryAABB(callback, this._tempB2AABB); + + const fixtures = PhysicsAABBQueryCallback.getFixtures(); + testResults.length = 0; + for (let i = 0; i < fixtures.length; i++) { + const collider = getTSObjectFromWASMObject(fixtures[i]).collider; + if (!testResults.includes(collider)) { + testResults.push(collider); + } + } + return testResults; + } + + testAABB (rect: Rect): readonly Collider2D[] { + this._tempB2AABB.lowerBound = { x: rect.xMin / PHYSICS_2D_PTM_RATIO, y: rect.yMin / PHYSICS_2D_PTM_RATIO }; + this._tempB2AABB.upperBound = { x: rect.xMax / PHYSICS_2D_PTM_RATIO, y: rect.yMax / PHYSICS_2D_PTM_RATIO }; + + const callback = this._aabbQueryCallback; + PhysicsAABBQueryCallback.init(); + this._world.QueryAABB(callback, this._tempB2AABB); + + const fixtures = PhysicsAABBQueryCallback.getFixtures(); + testResults.length = 0; + for (let i = 0; i < fixtures.length; i++) { + const collider = getTSObjectFromWASMObject(fixtures[i]).collider; + if (!testResults.includes(collider)) { + testResults.push(collider); + } + } + return testResults; + } + + drawDebug (): void { + this._checkDebugDrawValid(); + + if (!this._debugGraphics) { + return; + } + this._debugGraphics.clear(); + this._world.DebugDraw(); + } + + _onBeginContact (b2contact: number): void { + const c = PhysicsContact.get(b2contact); + c.emit(Contact2DType.BEGIN_CONTACT); + } + + _onEndContact (b2contact: number): void { + const c = getTSObjectFromWASMObjectPtr(b2contact); + if (!c) { + return; + } + c.emit(Contact2DType.END_CONTACT); + + PhysicsContact.put(b2contact); + } + + _onPreSolve (b2contact: number): void { + const c = getTSObjectFromWASMObjectPtr(b2contact); + if (!c) { + return; + } + + c.emit(Contact2DType.PRE_SOLVE); + } + + _onPostSolve (b2contact: number, impulse: number): void { + const c = getTSObjectFromWASMObjectPtr(b2contact); + if (!c) { + return; + } + + // impulse only survive during post sole callback + c._setImpulse(impulse); + c.emit(Contact2DType.POST_SOLVE); + c._setImpulse(0); + } +} diff --git a/cocos/physics-2d/box2d-wasm/platform/physics-aabb-query-callback.ts b/cocos/physics-2d/box2d-wasm/platform/physics-aabb-query-callback.ts new file mode 100644 index 00000000000..657dcc2b407 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/platform/physics-aabb-query-callback.ts @@ -0,0 +1,73 @@ +/* + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2, getTSObjectFromWASMObject, getWASMObjectFromWASMObjectPtr } from '../instantiated'; +import { Vec2 } from '../../../core'; +import { B2RigidBody2D } from '../rigid-body'; + +export class PhysicsAABBQueryCallback { + static _point = { x: 0, y: 0 }; + static _isPoint = false; + static _fixtures: B2.Fixture[] = []; + + static init (point?: Vec2): void { + if (point) { + this._isPoint = true; + this._point.x = point.x; + this._point.y = point.y; + } else { + this._isPoint = false; + } + + this._fixtures.length = 0; + } + + static ReportFixture (fixture: B2.Fixture): boolean { + if (this._isPoint) { + if (fixture.TestPoint(this._point)) { + this._fixtures.push(fixture); + } + } else { + this._fixtures.push(fixture); + } + + // True to continue the query, false to terminate the query. + return true; + } + + static getFixture (): any { + return this._fixtures[0]; + } + + static getFixtures (): any[] { + return this._fixtures; + } + + static callback = { + ReportFixture (fixture: number): boolean { + const f = getWASMObjectFromWASMObjectPtr(fixture); + return PhysicsAABBQueryCallback.ReportFixture(f); + }, + }; +} diff --git a/cocos/physics-2d/box2d-wasm/platform/physics-contact-listener.ts b/cocos/physics-2d/box2d-wasm/platform/physics-contact-listener.ts new file mode 100644 index 00000000000..088620079c3 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/platform/physics-contact-listener.ts @@ -0,0 +1,72 @@ +/* + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { js, warn } from '../../../core'; + +export class PhysicsContactListener { + static _BeginContact: Function | null = null; + static _EndContact: Function | null = null; + static _PreSolve: Function | null = null; + static _PostSolve: Function | null = null; + + static BeginContact (contact: number): void { + if (this._BeginContact) { + this._BeginContact(contact); + } + } + + static EndContact (contact: number): void { + if (this._EndContact) { + this._EndContact(contact); + } + } + + static PreSolve (contact: number, oldManifold: number): void { + if (this._PreSolve) { + this._PreSolve(contact, oldManifold); + } + } + + static PostSolve (contact: number, impulse: number): void { + if (this._PostSolve) { + this._PostSolve(contact, impulse); + } + } + + static callback = { + BeginContact (contact: number): void { + PhysicsContactListener.BeginContact(contact); + }, + EndContact (contact: number): void { + PhysicsContactListener.EndContact(contact); + }, + PreSolve (contact: number, oldManifold: number): void { + PhysicsContactListener.PreSolve(contact, oldManifold); + }, + PostSolve (contact: number, impulse: number): void { + PhysicsContactListener.PostSolve(contact, impulse); + }, + }; +} diff --git a/cocos/physics-2d/box2d-wasm/platform/physics-debug-draw.ts b/cocos/physics-2d/box2d-wasm/platform/physics-debug-draw.ts new file mode 100644 index 00000000000..9127274bdb5 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/platform/physics-debug-draw.ts @@ -0,0 +1,199 @@ +/* + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2, b2Mul } from '../instantiated'; +import { Color, warn } from '../../../core'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework'; +import { Graphics } from '../../../2d'; + +const _tmp_vec2 = { x: 0, y: 0 }; +const _tmp_vec3 = { x: 0, y: 0 }; +const _tmp_color = new Color(); + +const GREEN_COLOR = Color.GREEN; +const RED_COLOR = Color.RED; + +export class PhysicsDebugDraw {// extends B2.Draw { + static callback = { + DrawPolygon (vertices: number, vertexCount: number, color: B2.Color): void { + PhysicsDebugDraw.DrawPolygon(vertices, vertexCount, color); + }, + DrawSolidPolygon (vertices: number, vertexCount: number, color: B2.Color): void { + PhysicsDebugDraw.DrawSolidPolygon(vertices, vertexCount, color); + }, + DrawCircle (center: B2.Vec2, radius: number, color: B2.Color): void { + PhysicsDebugDraw.DrawCircle(center, radius, color); + }, + DrawSolidCircle (center: B2.Vec2, radius: number, axis, color: B2.Color): void { + PhysicsDebugDraw.DrawSolidCircle(center, radius, axis, color); + }, + DrawSegment (p1: B2.Vec2, p2: B2.Vec2, color: B2.Color): void { + PhysicsDebugDraw.DrawSegment(p1, p2, color); + }, + DrawTransform (xf: B2.Transform): void { + PhysicsDebugDraw.DrawTransform(xf); + }, + DrawPoint (center: B2.Vec2, size: number, color: B2.Color): void { + PhysicsDebugDraw.DrawPoint(center, size, color); + }, + }; + + static _drawer: Graphics | null = null; + + static _xf = { p: { x: 0, y: 0 }, q: { s: 0, c: 1 } };//new B2.Transform(); + static _dxf = { p: { x: 0, y: 0 }, q: { s: 0, c: 1 } };//new B2.Transform(); + + static _DrawPolygon (vertices: number, vertexCount: number): void { + const drawer = PhysicsDebugDraw._drawer!; + const rawVertexBuffer = B2.HEAPF32.subarray(vertices / 4, vertices / 4 + vertexCount * 2); + + for (let i = 0; i < vertexCount; i++) { + _tmp_vec2.x = rawVertexBuffer[i * 2 + 0]; + _tmp_vec2.y = rawVertexBuffer[i * 2 + 1]; + b2Mul(PhysicsDebugDraw._xf, _tmp_vec2, _tmp_vec3); + const x = _tmp_vec3.x * PHYSICS_2D_PTM_RATIO; + const y = _tmp_vec3.y * PHYSICS_2D_PTM_RATIO; + if (i === 0) drawer.moveTo(x, y); + else { + drawer.lineTo(x, y); + } + } + + drawer.close(); + } + + static DrawPolygon (vertices: number, vertexCount: number, color: B2.Color): void { + PhysicsDebugDraw._applyStrokeColor(color); + PhysicsDebugDraw._DrawPolygon(vertices, vertexCount); + PhysicsDebugDraw._drawer!.stroke(); + } + + static DrawSolidPolygon (vertices: number, vertexCount: number, color: B2.Color): void { + PhysicsDebugDraw._applyFillColor(color); + PhysicsDebugDraw._DrawPolygon(vertices, vertexCount); + PhysicsDebugDraw._drawer!.fill(); + PhysicsDebugDraw._drawer!.stroke(); + } + + static _DrawCircle (center: B2.Vec2, radius: number): void { + const p = PhysicsDebugDraw._xf.p; + PhysicsDebugDraw._drawer!.circle( + (center.x + p.x) * PHYSICS_2D_PTM_RATIO, + (center.y + p.y) * PHYSICS_2D_PTM_RATIO, + radius * PHYSICS_2D_PTM_RATIO, + ); + } + + static DrawCircle (center: B2.Vec2, radius: number, color: B2.Color): void { + PhysicsDebugDraw._applyStrokeColor(color); + PhysicsDebugDraw._DrawCircle(center, radius); + PhysicsDebugDraw._drawer!.stroke(); + } + + static DrawSolidCircle (center: B2.Vec2, radius: number, axis, color: B2.Color): void { + PhysicsDebugDraw._applyFillColor(color); + PhysicsDebugDraw._DrawCircle(center, radius); + PhysicsDebugDraw._drawer!.fill(); + } + + static DrawSegment (p1: B2.Vec2, p2: B2.Vec2, color: B2.Color): void { + const drawer = PhysicsDebugDraw._drawer!; + + if (p1.x === p2.x && p1.y === p2.y) { + PhysicsDebugDraw._applyFillColor(color); + PhysicsDebugDraw._DrawCircle(p1, 2 / PHYSICS_2D_PTM_RATIO); + drawer.fill(); + return; + } + PhysicsDebugDraw._applyStrokeColor(color); + + b2Mul(PhysicsDebugDraw._xf, p1, _tmp_vec2); + drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO); + b2Mul(PhysicsDebugDraw._xf, p2, _tmp_vec2); + drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO); + drawer.stroke(); + } + + static DrawTransform (xf: B2.Transform): void { + const drawer = PhysicsDebugDraw._drawer!; + + drawer.strokeColor = RED_COLOR; + + _tmp_vec2.x = _tmp_vec2.y = 0; + b2Mul(xf, _tmp_vec2, _tmp_vec3); + drawer.moveTo(_tmp_vec3.x * PHYSICS_2D_PTM_RATIO, _tmp_vec3.y * PHYSICS_2D_PTM_RATIO); + + _tmp_vec2.x = 1; _tmp_vec2.y = 0; + b2Mul(xf, _tmp_vec2, _tmp_vec3); + drawer.lineTo(_tmp_vec3.x * PHYSICS_2D_PTM_RATIO, _tmp_vec3.y * PHYSICS_2D_PTM_RATIO); + + drawer.stroke(); + + drawer.strokeColor = GREEN_COLOR; + + _tmp_vec2.x = _tmp_vec2.y = 0; + b2Mul(xf, _tmp_vec2, _tmp_vec3); + drawer.moveTo(_tmp_vec3.x * PHYSICS_2D_PTM_RATIO, _tmp_vec3.y * PHYSICS_2D_PTM_RATIO); + + _tmp_vec2.x = 0; _tmp_vec2.y = 1; + b2Mul(xf, _tmp_vec2, _tmp_vec3); + drawer.lineTo(_tmp_vec3.x * PHYSICS_2D_PTM_RATIO, _tmp_vec3.y * PHYSICS_2D_PTM_RATIO); + + drawer.stroke(); + } + + static DrawPoint (center, size, color): void { + // TODO + } + + static DrawParticles (): void { + // TODO + } + + static _applyStrokeColor (color: B2.Color): void { + PhysicsDebugDraw._drawer!.strokeColor = _tmp_color.set( + color.r * 255, + color.g * 255, + color.b * 255, + 150, + ); + } + + static _applyFillColor (color: B2.Color): void { + PhysicsDebugDraw._drawer!.fillColor = _tmp_color.set( + color.r * 255, + color.g * 255, + color.b * 255, + 150, + ); + } + + PushTransform (xf): void { + PhysicsDebugDraw._xf = xf; + } + + PopTransform (): void { + PhysicsDebugDraw._xf = PhysicsDebugDraw._dxf; + } +} diff --git a/cocos/physics-2d/box2d-wasm/platform/physics-ray-cast-callback.ts b/cocos/physics-2d/box2d-wasm/platform/physics-ray-cast-callback.ts new file mode 100644 index 00000000000..3c067a73da2 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/platform/physics-ray-cast-callback.ts @@ -0,0 +1,98 @@ +/* + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2, getTSObjectFromWASMObject, getWASMObjectFromWASMObjectPtr } from '../instantiated'; +import { Vec2 } from '../../../core'; +import { ERaycast2DType } from '../../framework'; +import { B2Shape2D } from '../shapes/shape-2d'; +import { B2RigidBody2D } from '../rigid-body'; + +export class PhysicsRayCastCallback {// extends B2.RayCastCallback { + static _type = ERaycast2DType.Closest; + static _fixtures: B2.Fixture[] = []; + static _points: Vec2[] = []; + static _normals: Vec2[] = []; + static _fractions: number[] = []; + + static _mask = 0xffffffff; + + static init (type: ERaycast2DType, mask: number): void { + PhysicsRayCastCallback._type = type; + PhysicsRayCastCallback._mask = mask; + PhysicsRayCastCallback._fixtures.length = 0; + PhysicsRayCastCallback._points.length = 0; + PhysicsRayCastCallback._normals.length = 0; + PhysicsRayCastCallback._fractions.length = 0; + } + + static ReportFixture (fixture: B2.Fixture, point: B2.Vec2, normal: B2.Vec2, fraction: number): any { + if ((fixture.GetFilterData().categoryBits & PhysicsRayCastCallback._mask) === 0) { + return 0; + } + + if (PhysicsRayCastCallback._type === ERaycast2DType.Closest) { + PhysicsRayCastCallback._fixtures[0] = fixture; + PhysicsRayCastCallback._points[0] = point as Vec2; + PhysicsRayCastCallback._normals[0] = normal as Vec2; + PhysicsRayCastCallback._fractions[0] = fraction; + return fraction; + } + + PhysicsRayCastCallback._fixtures.push(fixture); + PhysicsRayCastCallback._points.push(new Vec2(point.x, point.y)); + PhysicsRayCastCallback._normals.push(new Vec2(normal.x, normal.y)); + PhysicsRayCastCallback._fractions.push(fraction); + + if (PhysicsRayCastCallback._type === ERaycast2DType.Any) { + return 0; + } else if (PhysicsRayCastCallback._type >= ERaycast2DType.All) { + return 1; + } + + return fraction; + } + + static getFixtures (): B2.Fixture[] { + return PhysicsRayCastCallback._fixtures; + } + + static getPoints (): Vec2[] { + return PhysicsRayCastCallback._points; + } + + static getNormals (): Vec2[] { + return PhysicsRayCastCallback._normals; + } + + static getFractions (): number[] { + return PhysicsRayCastCallback._fractions; + } + + static callback = { + ReportFixture (fixture: number, point: B2.Vec2, normal: B2.Vec2, fraction: number): any { + const f = getWASMObjectFromWASMObjectPtr(fixture); + return PhysicsRayCastCallback.ReportFixture(f, point, normal, fraction); + }, + }; +} diff --git a/cocos/physics-2d/box2d-wasm/rigid-body.ts b/cocos/physics-2d/box2d-wasm/rigid-body.ts new file mode 100644 index 00000000000..feb13037e4c --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/rigid-body.ts @@ -0,0 +1,362 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from './instantiated'; +import { IRigidBody2D } from '../spec/i-rigid-body'; +import { RigidBody2D } from '../framework/components/rigid-body-2d'; +import { PhysicsSystem2D } from '../framework/physics-system'; +import { B2PhysicsWorld } from './physics-world'; +import { Vec2, toRadian, Vec3, Quat, IVec2Like, toDegree, TWO_PI, HALF_PI } from '../../core'; +import { PHYSICS_2D_PTM_RATIO, ERigidBody2DType } from '../framework/physics-types'; + +import { Node } from '../../scene-graph/node'; +import { Collider2D } from '../framework'; +import { NodeEventType } from '../../scene-graph/node-event'; + +const tempVec3 = new Vec3(); +const tempVec2_1 = { x: 0, y: 0 };//new B2.Vec2(0, 0); +let tempVec2_2 = { x: 0, y: 0 }; +export class B2RigidBody2D implements IRigidBody2D { + get impl (): B2.Body | null { + return this._body; + } + set _imp (v: B2.Body | null) { + this._body = v; + } + + get rigidBody (): RigidBody2D { + return this._rigidBody; + } + get isAwake (): boolean { + return this._body!.IsAwake(); + } + get isSleeping (): boolean { + return !(this._body!.IsAwake()); + } + + _animatedPos = new Vec2(); + _animatedAngle = 0; + + private _body: B2.Body | null = null; + private _rigidBody!: RigidBody2D; + + private _inited = false; + + initialize (com: RigidBody2D): void { + this._rigidBody = com; + + PhysicsSystem2D.instance._callAfterStep(this, this._init); + } + + onDestroy (): void { + PhysicsSystem2D.instance._callAfterStep(this, this._destroy); + } + + onEnable (): void { + this.setActive(true); + } + + onDisable (): void { + this.setActive(false); + } + + nodeTransformChanged (type): void { + if (PhysicsSystem2D.instance.stepping) { + return; + } + + if (type & Node.TransformBit.SCALE) { + const colliders = this.rigidBody.getComponents(Collider2D); + for (let i = 0; i < colliders.length; i++) { + colliders[i].apply(); + } + } + if (type & Node.TransformBit.POSITION) { + this.syncPositionToPhysics(true); + } + if (type & Node.TransformBit.ROTATION) { + this.syncRotationToPhysics(true); + } + } + + _init (): void { + if (this._inited) { + return; + } + + (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).addBody(this); + this.setActive(false); + + this._inited = true; + } + + _destroy (): void { + if (!this._inited) return; + + (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).removeBody(this); + + this._inited = false; + } + + animate (dt: number): void { + const b2body = this._body; + if (!b2body) return; + const b2Pos = b2body.GetPosition(); + + b2body.SetAwake(true); + + const timeStep = 1 / dt; + tempVec2_1.x = (this._animatedPos.x - b2Pos.x) * timeStep; + tempVec2_1.y = (this._animatedPos.y - b2Pos.y) * timeStep; + b2body.SetLinearVelocity(tempVec2_1); + + //convert b2Rotation to [-PI~PI], which is the same as this._animatedAngle + let b2Rotation = b2body.GetAngle() % (TWO_PI); + if (b2Rotation > Math.PI) { + b2Rotation -= TWO_PI; + } + + //calculate angular velocity + let angularVelocity = (this._animatedAngle - b2Rotation) * timeStep; + if (this._animatedAngle < -HALF_PI && b2Rotation > HALF_PI) { //ccw, crossing PI + angularVelocity = (this._animatedAngle + TWO_PI - b2Rotation) * timeStep; + } if (this._animatedAngle > HALF_PI && b2Rotation < -HALF_PI) { //cw, crossing PI + angularVelocity = (this._animatedAngle - TWO_PI - b2Rotation) * timeStep; + } + + b2body.SetAngularVelocity(angularVelocity); + } + + syncSceneToPhysics (): void { + const dirty = this._rigidBody.node.hasChangedFlags; + if (dirty) { this.nodeTransformChanged(dirty); } + } + + syncPositionToPhysics (enableAnimated = false): void { + const b2body = this._body; + if (!b2body) return; + + const pos = this._rigidBody.node.worldPosition; + + //the belowing code seems useless? + const bodyType = this._rigidBody.type; + if (bodyType === ERigidBody2DType.Animated) { + tempVec2_2 = b2body.GetLinearVelocity(); + } else { + tempVec2_2 = b2body.GetPosition(); + } + + tempVec2_2.x = pos.x / PHYSICS_2D_PTM_RATIO; + tempVec2_2.y = pos.y / PHYSICS_2D_PTM_RATIO; + + if (bodyType === ERigidBody2DType.Animated && enableAnimated) { + this._animatedPos.set(tempVec2_2.x, tempVec2_2.y); + } else { + b2body.SetTransform(tempVec2_2, b2body.GetAngle()); + } + } + + syncRotationToPhysics (enableAnimated = false): void { + const b2body = this._body; + if (!b2body) return; + + const rot = this._rigidBody.node.worldRotation; + const euler = tempVec3; + Quat.toEulerInYXZOrder(euler, rot); + const rotation = toRadian(euler.z); + + const bodyType = this._rigidBody.type; + if (bodyType === ERigidBody2DType.Animated && enableAnimated) { + this._animatedAngle = rotation; + } else { + b2body.SetTransform(b2body.GetPosition(), rotation); + } + } + + resetVelocity (): void { + const b2body = this._body; + if (!b2body) return; + + tempVec2_1.x = 0; + tempVec2_1.y = 0; + + b2body.SetLinearVelocity(tempVec2_1); + b2body.SetAngularVelocity(0); + } + + setType (v: ERigidBody2DType): void { + this._body!.SetType(v as number); + } + setLinearDamping (v: number): void { + this._body!.SetLinearDamping(v); + } + setAngularDamping (v: number): void { + this._body!.SetAngularDamping(v); + } + setGravityScale (v: number): void { + this._body!.SetGravityScale(v); + } + setFixedRotation (v: boolean): void { + this._body!.SetFixedRotation(v); + } + setAllowSleep (v: boolean): void { + this._body!.SetSleepingAllowed(v); + } + isActive (): any { + return this._body!.IsEnabled(); + } + setActive (v: boolean): void { + this._body!.SetEnabled(v); + } + wakeUp (): void { + this._body!.SetAwake(true); + } + sleep (): void { + this._body!.SetAwake(false); + } + getMass (): any { + return this._body!.GetMass(); + } + setLinearVelocity (v: IVec2Like): void { + this._body!.SetLinearVelocity(v as B2.Vec2); + } + getLinearVelocity (out: Out): Out { + const velocity = this._body!.GetLinearVelocity(); + out.x = velocity.x; + out.y = velocity.y; + return out; + } + getLinearVelocityFromWorldPoint (worldPoint: IVec2Like, out: Out): Out { + out = out || new Vec2(); + tempVec2_1.x = worldPoint.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = worldPoint.y / PHYSICS_2D_PTM_RATIO; + const temp = this._body!.GetLinearVelocityFromWorldPoint(tempVec2_1); + out.x = temp.x * PHYSICS_2D_PTM_RATIO; + out.y = temp.y * PHYSICS_2D_PTM_RATIO; + return out; + } + setAngularVelocity (v: number): void { + this._body!.SetAngularVelocity(v); + } + getAngularVelocity (): number { + return toDegree(this._body!.GetAngularVelocity()); + } + + getLocalVector (worldVector: IVec2Like, out: Out): Out { + out = out || new Vec2(); + tempVec2_1.x = worldVector.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = worldVector.y / PHYSICS_2D_PTM_RATIO; + const temp = this._body!.GetLocalVector(tempVec2_1); + out.x = temp.x * PHYSICS_2D_PTM_RATIO; + out.y = temp.y * PHYSICS_2D_PTM_RATIO; + return out; + } + getWorldVector (localVector: IVec2Like, out: Out): Out { + tempVec2_1.x = localVector.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = localVector.y / PHYSICS_2D_PTM_RATIO; + const temp = this._body!.GetWorldVector(tempVec2_1); + out.x = temp.x * PHYSICS_2D_PTM_RATIO; + out.y = temp.y * PHYSICS_2D_PTM_RATIO; + return out; + } + + getLocalPoint (worldPoint: IVec2Like, out: Out): Out { + out = out || new Vec2(); + tempVec2_1.x = worldPoint.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = worldPoint.y / PHYSICS_2D_PTM_RATIO; + const temp = this._body!.GetLocalPoint(tempVec2_1); + out.x = temp.x * PHYSICS_2D_PTM_RATIO; + out.y = temp.y * PHYSICS_2D_PTM_RATIO; + return out; + } + + getWorldPoint (localPoint: IVec2Like, out: Out): Out { + out = out || new Vec2(); + tempVec2_1.x = localPoint.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = localPoint.y / PHYSICS_2D_PTM_RATIO; + const temp = this._body!.GetWorldPoint(tempVec2_1); + out.x = temp.x * PHYSICS_2D_PTM_RATIO; + out.y = temp.y * PHYSICS_2D_PTM_RATIO; + return out; + } + + getLocalCenter (out: Out): Out { + out = out || new Vec2(); + const pos = this._body!.GetLocalCenter(); + out.x = pos.x * PHYSICS_2D_PTM_RATIO; + out.y = pos.y * PHYSICS_2D_PTM_RATIO; + return out; + } + getWorldCenter (out: Out): Out { + out = out || new Vec2(); + const pos = this._body!.GetWorldCenter(); + out.x = pos.x * PHYSICS_2D_PTM_RATIO; + out.y = pos.y * PHYSICS_2D_PTM_RATIO; + return out; + } + + getInertia (): any { + return this._body!.GetInertia(); + } + + applyForce (force: IVec2Like, point: IVec2Like, wake: boolean): void { + if (this._body) { + tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO; + this._body.ApplyForce(force as B2.Vec2, tempVec2_1, wake); + } + } + + applyForceToCenter (force: IVec2Like, wake: boolean): void { + if (this._body) { + this._body.ApplyForceToCenter(force as B2.Vec2, wake); + } + } + + applyTorque (torque: number, wake: boolean): void { + if (this._body) { + this._body.ApplyTorque(torque, wake); + } + } + + applyLinearImpulse (impulse: IVec2Like, point: IVec2Like, wake: boolean): void { + if (this._body) { + tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO; + tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO; + this._body.ApplyLinearImpulse(impulse as B2.Vec2, tempVec2_1, wake); + } + } + + applyLinearImpulseToCenter (impulse: IVec2Like, wake: boolean): void { + if (this._body) { + this._body.ApplyLinearImpulse(impulse as B2.Vec2, this._body.GetPosition(), wake); + } + } + + applyAngularImpulse (impulse: number, wake: boolean): void { + if (this._body) { + this._body.ApplyAngularImpulse(impulse, wake); + } + } +} diff --git a/cocos/physics-2d/box2d-wasm/shapes/box-shape-2d.ts b/cocos/physics-2d/box2d-wasm/shapes/box-shape-2d.ts new file mode 100644 index 00000000000..381632fb03a --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/shapes/box-shape-2d.ts @@ -0,0 +1,76 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { B2Shape2D } from './shape-2d'; +import { BoxCollider2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { IBoxShape } from '../../spec/i-physics-shape'; +import { Vec2, Rect } from '../../../core'; + +const tempAabb = new Rect(); +const tempB2Vec2_1 = { x: 0, y: 0 }; + +export class B2BoxShape extends B2Shape2D implements IBoxShape { + _worldPoints: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; + get worldPoints (): Readonly[] { + const aabb = tempAabb; + + const collider = this.collider as BoxCollider2D; + const size = collider.size; + const offset = collider.offset; + + aabb.x = offset.x - size.width / 2; + aabb.y = offset.y - size.height / 2; + aabb.width = size.width; + aabb.height = size.height; + + const wps = this._worldPoints; + const wp0 = wps[0]; const wp1 = wps[1]; + const wp2 = wps[2]; const wp3 = wps[3]; + + aabb.transformMat4ToPoints(collider.node.worldMatrix, wp0, wp1, wp2, wp3); + + return wps; + } + + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): B2.PolygonShape[] { + scaleX = Math.abs(scaleX); + scaleY = Math.abs(scaleY); + + const comp = this.collider as BoxCollider2D; + + const width = comp.size.width / 2 / PHYSICS_2D_PTM_RATIO * scaleX; + const height = comp.size.height / 2 / PHYSICS_2D_PTM_RATIO * scaleY; + const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO; + const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO; + + const shape = new B2.PolygonShape(); + tempB2Vec2_1.x = offsetX; + tempB2Vec2_1.y = offsetY; + shape.SetAsBoxWithCenterAndAngle(width, height, tempB2Vec2_1, 0); + + return [shape as unknown as B2.PolygonShape]; + } +} diff --git a/cocos/physics-2d/box2d-wasm/shapes/circle-shape-2d.ts b/cocos/physics-2d/box2d-wasm/shapes/circle-shape-2d.ts new file mode 100644 index 00000000000..254e2a1ece4 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/shapes/circle-shape-2d.ts @@ -0,0 +1,59 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { B2Shape2D } from './shape-2d'; +import { CircleCollider2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { ICircleShape } from '../../spec/i-physics-shape'; +import { Vec2 } from '../../../core'; + +export class B2CircleShape extends B2Shape2D implements ICircleShape { + get worldRadius (): number { + return (this._shapes[0]).m_radius * PHYSICS_2D_PTM_RATIO; + } + + _worldPosition = new Vec2(); + get worldPosition (): Vec2 { + const p = (this._shapes[0] as B2.CircleShape).m_p; + return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO); + } + + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): B2.CircleShape[] { + scaleX = Math.abs(scaleX); + scaleY = Math.abs(scaleY); + + const comp = this.collider as CircleCollider2D; + + const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO; + const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO; + + const shape = new B2.CircleShape(); + shape.m_radius = comp.radius / PHYSICS_2D_PTM_RATIO * scaleX; + shape.m_p.x = offsetX; + shape.m_p.y = offsetY; + + return [shape as unknown as B2.CircleShape]; + } +} diff --git a/cocos/physics-2d/box2d-wasm/shapes/polygon-shape-2d.ts b/cocos/physics-2d/box2d-wasm/shapes/polygon-shape-2d.ts new file mode 100644 index 00000000000..e192901f5ad --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/shapes/polygon-shape-2d.ts @@ -0,0 +1,115 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2 } from '../instantiated'; +import { B2Shape2D } from './shape-2d'; +import * as PolygonPartition from '../../framework/utils/polygon-partition'; +import { PolygonCollider2D } from '../../framework'; +import { PHYSICS_2D_PTM_RATIO } from '../../framework/physics-types'; +import { IPolygonShape } from '../../spec/i-physics-shape'; +import { Vec2, IVec2Like, warn } from '../../../core'; + +export class B2PolygonShape extends B2Shape2D implements IPolygonShape { + _worldPoints: Vec2[] = []; + get worldPoints (): Readonly[] { + const comp = this.collider as PolygonCollider2D; + const points = comp.points; + const worldPoints = this._worldPoints; + const m = comp.node.worldMatrix; + for (let i = 0; i < points.length; i++) { + if (!worldPoints[i]) { + worldPoints[i] = new Vec2(); + } + Vec2.transformMat4(worldPoints[i], points[i], m); + } + worldPoints.length = points.length; + + return this._worldPoints; + } + + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): B2.PolygonShape[] { + const shapes: B2.PolygonShape[] = []; + + const comp = this.collider as PolygonCollider2D; + const points = comp.points; + + // check if last point equal to first point + if (points.length > 0 && points[0].equals(points[points.length - 1])) { + points.length -= 1; + } + + const polys = PolygonPartition.ConvexPartition(points); + if (!polys) { + warn('[Physics2D] b2PolygonShape failed to decompose polygon into convex polygons, node name: ', comp.node.name); + return shapes; + } + + const offset = comp.offset; + + for (let i = 0; i < polys.length; i++) { + const poly = polys[i]; + + let shape: B2.PolygonShape | null = null; + const vertices = new B2.Vec2Vector(); + let firstVertice: B2.Vec2 | null = null; + + for (let j = 0, l = poly.length; j < l; j++) { + if (!shape) { + shape = new B2.PolygonShape(); + } + const p = poly[j]; + const x = (relativePositionX + (p.x + offset.x) * scaleX) / PHYSICS_2D_PTM_RATIO; + const y = (relativePositionY + (p.y + offset.y) * scaleY) / PHYSICS_2D_PTM_RATIO; + const v = { x, y }; + vertices.push_back(v); + + if (!firstVertice) { + firstVertice = v; + } + + if (vertices.size() === B2.maxPolygonVertices) { + shape!.Set(vertices, vertices.size() as number); + shapes.push(shape!); + + shape = null; + + if (j < l - 1) { + const temp = vertices.get(vertices.size() - 1); + vertices.resize(0, { x: 0, y: 0 });//clear + vertices.push_back(firstVertice); + vertices.push_back(temp); + } + } + } + + if (shape) { + shape.Set(vertices, vertices.size() as number); + shapes.push(shape); + } + vertices.delete(); + } + + return shapes; + } +} diff --git a/cocos/physics-2d/box2d-wasm/shapes/shape-2d.ts b/cocos/physics-2d/box2d-wasm/shapes/shape-2d.ts new file mode 100644 index 00000000000..5f102e03580 --- /dev/null +++ b/cocos/physics-2d/box2d-wasm/shapes/shape-2d.ts @@ -0,0 +1,228 @@ +/* + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { B2, getImplPtr, addImplPtrReference, addImplPtrReferenceWASM, removeImplPtrReference, + removeImplPtrReferenceWASM } from '../instantiated'; +import { IBaseShape } from '../../spec/i-physics-shape'; +import { Collider2D, PhysicsSystem2D, RigidBody2D, PHYSICS_2D_PTM_RATIO } from '../../../../exports/physics-2d-framework'; +import { Rect, Vec3 } from '../../../core'; +import { B2PhysicsWorld } from '../physics-world'; +import { PhysicsGroup } from '../../../physics/framework/physics-enum'; + +const tempFilter = { categoryBits: 0, maskBits: 0, groupIndex: 0 };// new B2.Filter(); +const lowerBound = { x: 0, y: 0 }; +const upperBound = { x: 0, y: 0 }; + +function getFilter (shape: B2Shape2D): B2.Filter { + const comp = shape.collider; + if (comp.body) { + tempFilter.categoryBits = (comp.group as PhysicsGroup) === PhysicsGroup.DEFAULT ? comp.body.group : comp.group; + } else { + tempFilter.categoryBits = comp.group; + } + tempFilter.maskBits = PhysicsSystem2D.instance.collisionMatrix[tempFilter.categoryBits]; + return tempFilter; +} + +export class B2Shape2D implements IBaseShape { + protected _shapes: B2.Shape[] = []; + protected _fixtures: B2.Fixture[] = []; + + protected _collider: Collider2D | null = null; + protected _body: B2.Body | null = null; + + private _inited = false; + + private _rect = new Rect(); + + get impl (): B2.Shape[] { + return this._shapes; + } + + get collider (): Collider2D { + return this._collider!; + } + + initialize (comp: Collider2D): void { + this._collider = comp; + } + + onLoad (): void { + //empty + } + + onEnable (): void { + PhysicsSystem2D.instance._callAfterStep(this, this._init); + } + + onDisable (): void { + PhysicsSystem2D.instance._callAfterStep(this, this._destroy); + } + + start (): void { + //empty + } + + onGroupChanged (): void { + const filter = getFilter(this); + this._fixtures.forEach((f): void => { + f.SetFilterData(filter); + }); + } + + apply (): void { + this._destroy(); + if (this.collider.enabledInHierarchy) { + this._init(); + } + } + + get worldAABB (): Readonly { + const MAX = 10e6; + + let minX = MAX; let minY = MAX; + let maxX = -MAX; let maxY = -MAX; + + const fixtures = this._fixtures; + for (let i = 0; i < fixtures.length; i++) { + const fixture = fixtures[i]; + + const count = fixture.GetShape().GetChildCount(); + for (let j = 0; j < count; j++) { + const aabb = fixture.GetAABB(j); + lowerBound.x = aabb.lowerBound.x; + lowerBound.y = aabb.lowerBound.y; + upperBound.x = aabb.upperBound.x; + upperBound.y = aabb.upperBound.y; + if (fixture.GetShape().m_type === B2.ShapeType.e_polygon) { //b2ShapeType.e_polygonShape + const skinWidth = fixture.GetShape().m_radius; + lowerBound.x += skinWidth; + lowerBound.y += skinWidth; + upperBound.x += skinWidth; + upperBound.y += skinWidth; + } + if (lowerBound.x < minX) minX = lowerBound.x; + if (lowerBound.y < minY) minY = lowerBound.y; + if (upperBound.x > maxX) maxX = upperBound.x; + if (upperBound.y > maxY) maxY = upperBound.y; + } + } + + minX *= PHYSICS_2D_PTM_RATIO; + minY *= PHYSICS_2D_PTM_RATIO; + maxX *= PHYSICS_2D_PTM_RATIO; + maxY *= PHYSICS_2D_PTM_RATIO; + + const r = this._rect; + r.x = minX; + r.y = minY; + r.width = maxX - minX; + r.height = maxY - minY; + + return r; + } + + getFixtureIndex (fixture: B2.Fixture): number { + return this._fixtures.indexOf(fixture); + } + + //relativePositionX/Y : relative Position from shape to rigid body + _createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): B2.Shape[] { + return []; + } + + _init (): void { + if (this._inited) return; + + const comp = this.collider; + const scale = comp.node.worldScale; + // relative Position from shape to rigid body + let relativePosition = Vec3.ZERO; + const body = comp.getComponent(RigidBody2D); + + //if rigid body is not attached to the same node of collider, this b2.shape is attached + // to the groundRigidBody(pos zero, rot zero) + if (body && body.impl && body.impl.impl) { + this._body = body.impl.impl as B2.Body; + } else { + this._body = (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).groundBodyImpl; + relativePosition = comp.node.worldPosition; + } + + const shapes = scale.x === 0 && scale.y === 0 ? [] : this._createShapes(scale.x, scale.y, relativePosition.x, relativePosition.y); + + const filter = getFilter(this); + + for (let i = 0; i < shapes.length; i++) { + const shape = shapes[i]; + + const fixDef = new B2.FixtureDef(); + fixDef.density = comp.density; + fixDef.isSensor = comp.sensor; + fixDef.friction = comp.friction; + fixDef.restitution = comp.restitution; + fixDef.SetShape(shape); + fixDef.filter = filter; + const fixture = this._body.CreateFixture(fixDef as B2.FixtureDef); + //fixture.m_userData = this; + addImplPtrReference(this, getImplPtr(fixture)); + addImplPtrReferenceWASM(fixture, getImplPtr(fixture)); + + if (body?.enabledContactListener) { + (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).registerContactFixture(fixture); + } + + this._shapes.push(shape); + this._fixtures.push(fixture); + } + + this._inited = true; + } + + _destroy (): void { + if (!this._inited) return; + + const fixtures = this._fixtures; + const body = this._body; + + for (let i = fixtures.length - 1; i >= 0; i--) { + const fixture = fixtures[i]; + //fixture.m_userData = null; + removeImplPtrReference(getImplPtr(fixture)); + removeImplPtrReferenceWASM(getImplPtr(fixture)); + + (PhysicsSystem2D.instance.physicsWorld as B2PhysicsWorld).unregisterContactFixture(fixture); + + if (body) { + body.DestroyFixture(fixture); + } + } + + this._body = null; + + this._fixtures.length = 0; + this._shapes.length = 0; + this._inited = false; + } +} diff --git a/cocos/physics-2d/box2d/physics-world.ts b/cocos/physics-2d/box2d/physics-world.ts index 5e6acc38b09..95dcf76cda0 100644 --- a/cocos/physics-2d/box2d/physics-world.ts +++ b/cocos/physics-2d/box2d/physics-world.ts @@ -23,13 +23,13 @@ */ import b2 from '@cocos/box2d'; -import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; +import { EDITOR_NOT_IN_PREVIEW, TEST } from 'internal:constants'; import { IPhysicsWorld } from '../spec/i-physics-world'; import { IVec2Like, Vec3, Quat, toRadian, Vec2, toDegree, Rect, CCObject, js } from '../../core'; import { PHYSICS_2D_PTM_RATIO, ERaycast2DType, ERigidBody2DType } from '../framework/physics-types'; -import { Canvas } from '../../2d/framework'; -import { Graphics } from '../../2d/components'; +// import { Canvas } from '../../2d/framework'; +// import { Graphics } from '../../2d/components'; import { b2RigidBody2D } from './rigid-body'; import { PhysicsContactListener } from './platform/physics-contact-listener'; @@ -88,7 +88,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { this._raycastQueryCallback = new PhysicsRayCastCallback(); } - _debugGraphics: Graphics | null = null; + _debugGraphics: any = null; _b2DebugDrawer: b2.Draw | null = null; _debugDrawFlags = 0; @@ -118,7 +118,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { } canvas = new Node('Canvas'); - canvas.addComponent(Canvas); + canvas.addComponent('cc.Canvas'); canvas.parent = scene; } @@ -129,9 +129,10 @@ export class b2PhysicsWorld implements IPhysicsWorld { node.worldPosition = Vec3.ZERO; node.layer = Layers.Enum.UI_2D; - this._debugGraphics = node.addComponent(Graphics); + this._debugGraphics = node.addComponent('cc.Graphics'); this._debugGraphics.lineWidth = 3; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument const debugDraw = new PhysicsDebugDraw(this._debugGraphics); this._b2DebugDrawer = debugDraw; this._world.SetDebugDraw(debugDraw); @@ -177,7 +178,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { callback.init(type, mask); this._world.RayCast(callback, tempVec2_1, tempVec2_2); - const fixtures = callback.getFixtures(); + const fixtures = callback.getFixtures() as b2.Fixture[]; if (fixtures.length > 0) { const points = callback.getPoints(); const normals = callback.getNormals(); @@ -299,10 +300,10 @@ export class b2PhysicsWorld implements IPhysicsWorld { // read private property const compPrivate = comp as any; - const linearVelocity = compPrivate._linearVelocity; + const linearVelocity = compPrivate._linearVelocity as Vec2; bodyDef.linearVelocity.Set(linearVelocity.x, linearVelocity.y); - bodyDef.angularVelocity = toRadian(compPrivate._angularVelocity); + bodyDef.angularVelocity = toRadian(compPrivate._angularVelocity as number); const b2Body = this._world.CreateBody(bodyDef); b2Body.m_userData = body; @@ -382,6 +383,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { } drawDebug (): void { + if (TEST) return; this._checkDebugDrawValid(); if (!this._debugGraphics) { diff --git a/cocos/physics-2d/builtin/builtin-world.ts b/cocos/physics-2d/builtin/builtin-world.ts index 331fa9d65d3..504e375eb57 100644 --- a/cocos/physics-2d/builtin/builtin-world.ts +++ b/cocos/physics-2d/builtin/builtin-world.ts @@ -22,11 +22,11 @@ THE SOFTWARE. */ -import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; +import { EDITOR_NOT_IN_PREVIEW, TEST } from 'internal:constants'; import { IPhysicsWorld } from '../spec/i-physics-world'; -import { Graphics } from '../../2d'; +// import { Graphics } from '../../2d'; import { CCObject, Vec3, Color, IVec2Like, Vec2, Rect, js } from '../../core'; -import { Canvas } from '../../2d/framework'; +// import { Canvas } from '../../2d/framework'; import { BuiltinShape2D } from './shapes/shape-2d'; import { BuiltinBoxShape } from './shapes/box-shape-2d'; import { BuiltinCircleShape } from './shapes/circle-shape-2d'; @@ -43,7 +43,7 @@ const testIntersectResults: Collider2D[] = []; export class BuiltinPhysicsWorld implements IPhysicsWorld { private _contacts: BuiltinContact[] = []; private _shapes: BuiltinShape2D[] = []; - private _debugGraphics: Graphics | null = null; + private _debugGraphics: any = null; private _debugDrawFlags = 0; get debugDrawFlags (): number { @@ -141,13 +141,15 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { } drawDebug (): void { + if (TEST) return; + if (!this._debugDrawFlags) { return; } this._checkDebugDrawValid(); - const debugDrawer = this._debugGraphics!; + const debugDrawer = this._debugGraphics; if (!debugDrawer) { return; } @@ -212,7 +214,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { return; } canvas = new Node('Canvas'); - canvas.addComponent(Canvas); + canvas.addComponent('cc.Canvas'); canvas.parent = scene; } @@ -222,7 +224,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { node.parent = canvas; node.worldPosition = Vec3.ZERO; - this._debugGraphics = node.addComponent(Graphics); + this._debugGraphics = node.addComponent('cc.Graphics'); this._debugGraphics.lineWidth = 2; } @@ -260,10 +262,18 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { impl (): any { return null; } - setGravity (): void { } - setAllowSleep (): void { } - syncPhysicsToScene (): void { } - syncSceneToPhysics (): void { } + setGravity (): void { + //empty + } + setAllowSleep (): void { + //empty + } + syncPhysicsToScene (): void { + //empty + } + syncSceneToPhysics (): void { + //empty + } raycast (p1: IVec2Like, p2: IVec2Like, type: ERaycast2DType): RaycastResult2D[] { return []; } diff --git a/cocos/physics-2d/framework/index.ts b/cocos/physics-2d/framework/index.ts index df5b2ecce26..5ad79a2566a 100644 --- a/cocos/physics-2d/framework/index.ts +++ b/cocos/physics-2d/framework/index.ts @@ -60,6 +60,8 @@ export const Physics2DUtils = { PolygonPartition, }; +export { selector }; + cclegacy.internal.physics2d = { selector, }; diff --git a/cocos/physics-2d/framework/physics-selector.ts b/cocos/physics-2d/framework/physics-selector.ts index 39545e108a5..958ae1da47b 100644 --- a/cocos/physics-2d/framework/physics-selector.ts +++ b/cocos/physics-2d/framework/physics-selector.ts @@ -27,12 +27,13 @@ import { EDITOR, DEBUG, TEST, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { IRigidBody2D } from '../spec/i-rigid-body'; import { IBoxShape, ICircleShape, IPolygonShape, IBaseShape } from '../spec/i-physics-shape'; import { IPhysicsWorld } from '../spec/i-physics-world'; -import { errorID } from '../../core'; +import { errorID, log } from '../../core'; import { ECollider2DType, EJoint2DType } from './physics-types'; import { IJoint2D, IDistanceJoint, ISpringJoint, IFixedJoint, IMouseJoint, IRelativeJoint, ISliderJoint, IWheelJoint, IHingeJoint } from '../spec/i-physics-joint'; -export type IPhysicsEngineId = 'builtin' | 'box2d' | string; +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents +export type IPhysicsEngineId = 'builtin' | 'box2d' | 'box2d-wasm'| string; interface IPhysicsWrapperObject { PhysicsWorld: any, @@ -109,7 +110,7 @@ export interface IPhysicsSelector { } function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void { - if (!EDITOR && !TEST) console.info(`[PHYSICS2D]: register ${id}.`); + if (!EDITOR && !TEST) log(`[PHYSICS2D]: register ${id}.`); selector.backend[id] = wrapper; if (!selector.physicsWorld || selector.id === id) { const mutableSelector = selector as Mutable; @@ -123,12 +124,12 @@ function switchTo (id: IPhysicsEngineId): void { const mutableSelector = selector as Mutable; if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) { //selector.physicsWorld.destroy();//todo - if (!TEST) console.info(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`); + if (!TEST) log(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`); mutableSelector.id = id; mutableSelector.wrapper = selector.backend[id]; mutableSelector.physicsWorld = createPhysicsWorld(); } else { - if (!EDITOR && !TEST) console.info(`[PHYSICS2D]: using ${mutableSelector.id}.`); + if (!EDITOR && !TEST) log(`[PHYSICS2D]: using ${mutableSelector.id}.`); mutableSelector.physicsWorld = createPhysicsWorld(); } } diff --git a/cocos/physics-2d/framework/physics-system.ts b/cocos/physics-2d/framework/physics-system.ts index 5b9491db8df..5f0a1de17de 100644 --- a/cocos/physics-2d/framework/physics-system.ts +++ b/cocos/physics-2d/framework/physics-system.ts @@ -177,6 +177,10 @@ export class PhysicsSystem2D extends Eventify(System) { return selector.id === 'box2d'; } + static get PHYSICS_BOX2D_WASM (): boolean { + return selector.id === 'box2d-wasm'; + } + /** * @en * Gets the predefined physics groups. @@ -374,10 +378,9 @@ export class PhysicsSystem2D extends Eventify(System) { testAABB (rect: Rect): readonly Collider2D[] { return this.physicsWorld.testAABB(rect); } + static constructAndRegister (): void { + director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, System.Priority.LOW); + } } -function initPhysicsSystem (): void { - director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, System.Priority.LOW); -} - -director.once(Director.EVENT_INIT, (): void => { initPhysicsSystem(); }); +director.once(Director.EVENT_INIT, (): void => { PhysicsSystem2D.constructAndRegister(); }); diff --git a/editor/engine-features/schema.json b/editor/engine-features/schema.json index ecdcc5fe494..b6934c7e5dc 100644 --- a/editor/engine-features/schema.json +++ b/editor/engine-features/schema.json @@ -106,6 +106,9 @@ "physics-2d-builtin": { "$ref": "#/definitions/Item" }, + "physics-2d-box2d-wasm": { + "$ref": "#/definitions/Item" + }, "physics-ammo": { "$ref": "#/definitions/Item" }, @@ -253,6 +256,9 @@ "physics-2d-builtin": { "$ref": "#/definitions/BaseItem" }, + "physics-2d-box2d-wasm": { + "$ref": "#/definitions/BaseItem" + }, "physics-ammo": { "$ref": "#/definitions/BaseItem" }, diff --git a/editor/engine-features/types.ts b/editor/engine-features/types.ts index 2ff6a5f7cd6..9c069d75e6f 100644 --- a/editor/engine-features/types.ts +++ b/editor/engine-features/types.ts @@ -22,6 +22,7 @@ export type EngineFeature = | 'physics-2d' | 'physics-2d-box2d' | 'physics-2d-builtin' + | 'physics-2d-box2d-wasm' | 'intersection-2d' | 'audio' | 'video' diff --git a/exports/physics-2d-box2d-wasm.ts b/exports/physics-2d-box2d-wasm.ts new file mode 100644 index 00000000000..c21d0973123 --- /dev/null +++ b/exports/physics-2d-box2d-wasm.ts @@ -0,0 +1,26 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +import '../cocos/physics-2d/box2d-wasm/instantiate'; diff --git a/exports/wait-for-box2d-instantiation.ts b/exports/wait-for-box2d-instantiation.ts new file mode 100644 index 00000000000..dd23861d66b --- /dev/null +++ b/exports/wait-for-box2d-instantiation.ts @@ -0,0 +1,27 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +// eslint-disable-next-line no-restricted-exports +export { waitForBox2dWasmInstantiation as default } from '../cocos/physics-2d/box2d-wasm/instantiated'; diff --git a/native/external-config.json b/native/external-config.json index b16d14480ec..72909dbc542 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-10" + "checkout": "v3.8.1-11" } } diff --git a/scripts/build-engine/.vscode/launch.json b/scripts/build-engine/.vscode/launch.json index 127a470180d..c6891179c58 100644 --- a/scripts/build-engine/.vscode/launch.json +++ b/scripts/build-engine/.vscode/launch.json @@ -42,6 +42,7 @@ "physics-2d-framework", "physics-2d-box2d", "physics-2d-builtin", + "physics-2d-box2d-wasm", "intersection-2d", "primitive", "profiler", diff --git a/scripts/build-engine/tests/stats-query/cc.config.json b/scripts/build-engine/tests/stats-query/cc.config.json index 02b5291577d..3a15eb63e6b 100644 --- a/scripts/build-engine/tests/stats-query/cc.config.json +++ b/scripts/build-engine/tests/stats-query/cc.config.json @@ -21,6 +21,7 @@ "physics-2d-framework": { "modules": [ "physics-2d-framework" ] }, "physics-2d-box2d": { "modules": [ "physics-2d-box2d", "physics-2d-framework" ] }, "physics-2d-builtin": { "modules": [ "physics-2d-builtin", "physics-2d-framework" ] }, + "physics-2d-box2d-wasm": { "modules": [ "physics-2d-box2d-wasm", "physics-2d-framework" ] }, "intersection-2d": { "modules": [ "intersection-2d" ] }, "primitive": { "modules": [ "primitive" ] }, "profiler": { "modules": [ "profiler" ] }, diff --git a/tests/init.ts b/tests/init.ts index 6f321dca9f2..4e43708972d 100644 --- a/tests/init.ts +++ b/tests/init.ts @@ -80,6 +80,7 @@ jest.mock( 'external:emscripten/webgpu/glslang.wasm', 'external:emscripten/physx/physx.release.wasm.wasm', 'external:emscripten/spine/spine.wasm', + 'external:emscripten/box2d/box2d.release.wasm.wasm', ].forEach(moduleId => { jest.mock(moduleId, () => ({ @@ -97,6 +98,7 @@ jest.mock( 'external:emscripten/webgpu/glslang.js', 'external:emscripten/physx/physx.release.wasm.js', 'external:emscripten/spine/spine.js', + 'external:emscripten/box2d/box2d.release.wasm.js', ].forEach(moduleId => { jest.mock(moduleId, () => ({ @@ -126,6 +128,12 @@ jest.mock( { virtual: true }, ); +jest.mock( + 'external:emscripten/box2d/box2d.release.asm.js', + () => jest.requireActual('../native/external/emscripten/box2d/box2d.release.asm.js'), + { virtual: true }, +); + jest.mock('../cocos/core/platform/debug', () => { const result = { __esModule: true, // Use it when dealing with esModules diff --git a/tests/physics2d/collider.ts b/tests/physics2d/collider.ts new file mode 100644 index 00000000000..dae5a929535 --- /dev/null +++ b/tests/physics2d/collider.ts @@ -0,0 +1,43 @@ +import { EPSILON, Quat, Vec2, Vec3 } from "../../cocos/core"; +import { director } from "../../cocos/game"; +import { Node } from "../../cocos/scene-graph"; +import * as physics2d from "../../exports/physics-2d-framework"; + +/** + * This function is used to test the api of the RigidBody + */ +export default function (parent: Node, _steps = 0) { + //skip builtin for now + if (physics2d.selector.id === 'builtin') + return; + + // basic api + { + const nodeCollider = new Node('Collider2D'); + parent.addChild(nodeCollider); + const initPos = new Vec3(0, 10, 0); + nodeCollider.worldPosition = initPos; + const body = nodeCollider.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + const collider = nodeCollider.addComponent(physics2d.BoxCollider2D) as physics2d.Collider2D; + + expect(collider.body).toBe(body); + + collider.density = 100; + expect(collider.density).toBe(100); + collider.apply(); + expect(body.getMass()).toBe(0.09765625); + + collider.friction = 1; + expect(collider.friction).toBe(1); + + collider.restitution = 1; + expect(collider.restitution).toBe(1); + + collider.sensor = true; + expect(collider.sensor).toBe(true); + + parent.destroyAllChildren(); + parent.removeAllChildren(); + } + +} \ No newline at end of file diff --git a/tests/physics2d/events.ts b/tests/physics2d/events.ts new file mode 100644 index 00000000000..fa59e35cda6 --- /dev/null +++ b/tests/physics2d/events.ts @@ -0,0 +1,49 @@ +import { EPSILON, Quat, Vec2, Vec3 } from "../../cocos/core"; +import { director } from "../../cocos/game"; +import { Node } from "../../cocos/scene-graph"; +import * as physics2d from "../../exports/physics-2d-framework"; + +/** + * This function is used to test the api of the RigidBody + */ +export default function (parent: Node, _steps = 0) { + //skip builtin for now + if (physics2d.selector.id === 'builtin') + return; + + // basic api + { + const nodeStaticCollider = new Node('StaticCollider2D'); + parent.addChild(nodeStaticCollider); + const initPos = new Vec3(0, 0, 0); + nodeStaticCollider.worldPosition = initPos; + const staticBody = nodeStaticCollider.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + const staticCollider = nodeStaticCollider.addComponent(physics2d.BoxCollider2D) as physics2d.Collider2D; + staticBody.type = physics2d.ERigidBody2DType.Static; + //staticBody.enabledContactListener = true; + + const nodeDynamicCollider = new Node('DynamicCollider2D'); + parent.addChild(nodeDynamicCollider); + nodeDynamicCollider.worldPosition = new Vec3(0, 2, 0); + const dynamicBody = nodeDynamicCollider.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + const dynamicCollider = nodeDynamicCollider.addComponent(physics2d.BoxCollider2D) as physics2d.Collider2D; + dynamicBody.enabledContactListener = true; + dynamicBody.type = physics2d.ERigidBody2DType.Dynamic; + + function onBeginContact (selfCollider, otherCollider, contact: physics2d.IPhysics2DContact) { + expect(contact.colliderA).toBe(dynamicCollider); + expect(contact.colliderB).toBe(staticCollider); + } + + dynamicCollider.on(physics2d.Contact2DType.BEGIN_CONTACT, onBeginContact); + + const dt = physics2d.PhysicsSystem2D.instance.fixedTimeStep; + for (let i = 0; i < 3000; i++) { + director.tick(dt); + } + + parent.destroyAllChildren(); + parent.removeAllChildren(); + } + +} \ No newline at end of file diff --git a/tests/physics2d/physics2d.test.ts b/tests/physics2d/physics2d.test.ts index 75d5329573d..db993f0cd54 100644 --- a/tests/physics2d/physics2d.test.ts +++ b/tests/physics2d/physics2d.test.ts @@ -1,6 +1,56 @@ +import { director, game, Game } from "../../cocos/game"; import Utils from "./utilis"; +import * as physics2d from "../../exports/physics-2d-framework"; +import { Node, Scene } from "../../cocos/scene-graph"; + +import waitForBox2dWasmInstantiation from "../../exports/wait-for-box2d-instantiation"; +waitForBox2dWasmInstantiation(); +import "../../exports/physics-2d-box2d-wasm"; +import "../../exports/physics-2d-box2d"; +import "../../exports/physics-2d-builtin"; + +import RigidBodyTest from "./rigid-body"; +import ColliderTest from "./collider"; +import SceneQueryTest from "./scene-query"; +import EventTest from "./events"; + +game.emit(Game.EVENT_PRE_SUBSYSTEM_INIT); +physics2d.PhysicsSystem2D.constructAndRegister(); test(`physics2d test | utils`, done => { Utils(); done(); }); + +for (const id in physics2d.selector.backend) { + test(`physics2d test | ${id}`, done => { + // init test scene (which will also immediately destroy the previous test scene) + const scene = new Scene('test-' + id); + director.runSceneImmediate(scene); + + // switch to backend after the previous scene is immediately destroyed + physics2d.selector.switchTo(id); + expect(physics2d.selector.id).toBe(id); + + const temp0 = new Node(); + scene.addChild(temp0); + + //test rigid body + RigidBodyTest(temp0); + + //test collider + ColliderTest(temp0); + + //test scene query + SceneQueryTest(temp0); + + //test events + EventTest(temp0); + + // destroy test scene + temp0.destroy(); + scene.destroy(); + // all works done + done(); + }) +} \ No newline at end of file diff --git a/tests/physics2d/rigid-body.ts b/tests/physics2d/rigid-body.ts new file mode 100644 index 00000000000..2fc4603d1d1 --- /dev/null +++ b/tests/physics2d/rigid-body.ts @@ -0,0 +1,142 @@ +import { EPSILON, Quat, Vec2, Vec3 } from "../../cocos/core"; +import { director } from "../../cocos/game"; +import { Node } from "../../cocos/scene-graph"; +import * as physics2d from "../../exports/physics-2d-framework"; + +/** + * This function is used to test the api of the RigidBody + */ +export default function (parent: Node, _steps = 0) { + //skip builtin for now + if (physics2d.selector.id === 'builtin') + return; + + // basic api + { + const nodeRigidBody = new Node('RigidBody'); + parent.addChild(nodeRigidBody); + const initPos = new Vec3(0, 10, 0); + nodeRigidBody.worldPosition = initPos; + const body = nodeRigidBody.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + + //test getLinearVelocityFromWorldPoint + { + const v2_0 = new Vec2(1, 0); + const velocity = new Vec2(); + body.getLinearVelocityFromWorldPoint(v2_0, velocity); + expect(Vec2.equals(velocity, Vec2.ZERO)).toBe(true); + } + //test getLocalVector + { + const v2_0 = new Vec2(1, 0); + const v2_1 = new Vec2(); + body.getLocalVector(v2_0, v2_1); + expect(Vec2.equals(v2_0, v2_1)).toBe(true); + } + //test getWorldVector + { + const v2_0 = new Vec2(1, 0); + const v2_1 = new Vec2(); + body.getWorldVector(v2_0, v2_1); + expect(Vec2.equals(v2_0, v2_1)).toBe(true); + } + //test getLocalPoint + { + const v2_0 = new Vec2(1, 0); + const v2_1 = new Vec2(); + body.getLocalPoint(v2_0, v2_1); + let expectLocalPoint = new Vec2(1, -10); + expect(Vec2.equals(expectLocalPoint, v2_1)).toBe(true); + } + //test getWorldPoint + { + const v2_0 = new Vec2(1, 0); + const v2_1 = new Vec2(); + body.getWorldPoint(v2_0, v2_1); + let expectWorldPoint = new Vec2(1, 10); + expect(Vec2.equals(expectWorldPoint, v2_1)).toBe(true); + } + + parent.destroyAllChildren(); + parent.removeAllChildren(); + } + + // applyForceToCenter + { + const nodeRigidBody = new Node('RigidBody2D'); + parent.addChild(nodeRigidBody); + const initPos = new Vec3(0, 0, 0); + nodeRigidBody.worldPosition = initPos; + const body = nodeRigidBody.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + + body.applyForceToCenter(new Vec2(1, 0), true); + body.gravityScale = 0; + + const dt = physics2d.PhysicsSystem2D.instance.fixedTimeStep; + for(let i = 0; i < 10; i++) + director.tick(dt); + + expect(nodeRigidBody.worldPosition.x > initPos.x).toBe(true); + expect(Math.abs(nodeRigidBody.worldPosition.y - initPos.y) < EPSILON).toBe(true); + expect(Quat.equals(nodeRigidBody.worldRotation, Quat.IDENTITY)).toBe(true); + expect(Math.abs(body.linearVelocity.y) < EPSILON).toBe(true); + expect(Math.abs(body.linearVelocity.x) > EPSILON).toBe(true); + expect(Math.abs(body.angularVelocity) < EPSILON).toBe(true); + + parent.destroyAllChildren(); + parent.removeAllChildren(); + } + + // applyTorque + if(0)//todo + { + const nodeRigidBody = new Node('RigidBody'); + parent.addChild(nodeRigidBody); + const initPos = new Vec3(0, 0, 0); + nodeRigidBody.worldPosition = initPos; + const body = nodeRigidBody.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + nodeRigidBody.addComponent(physics2d.BoxCollider2D); + + body.applyTorque(10, true); + body.gravityScale = 0; + + const dt = physics2d.PhysicsSystem2D.instance.fixedTimeStep; + for(let i = 0; i < 10; i++) + director.tick(dt); + + let eulerAngle = new Vec3(); + nodeRigidBody.worldRotation.getEulerAngles(eulerAngle); + expect(nodeRigidBody.worldPosition.y === initPos.y).toBe(true); + expect(Math.abs(eulerAngle.x) < EPSILON).toBe(true); + expect(Math.abs(eulerAngle.y) < EPSILON).toBe(true); + expect(Math.abs(eulerAngle.z) > EPSILON).toBe(true); + + parent.destroyAllChildren(); + parent.removeAllChildren(); + } + + //sleep and wakeup + { + const nodeRigidBody = new Node('RigidBody'); + parent.addChild(nodeRigidBody); + const initPos = new Vec3(0, 0, 0); + nodeRigidBody.worldPosition = initPos; + const body = nodeRigidBody.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + + + body.allowSleep = true; + body.sleep(); + expect(body.isAwake()).toBe(false); + body.wakeUp(); + expect(body.isAwake()).toBe(true); + + // todo + // body.allowSleep = false; + // body.sleep(); + // expect(body.isAwake()).toBe(true); + + parent.destroyAllChildren(); + parent.removeAllChildren(); + } + +} \ No newline at end of file diff --git a/tests/physics2d/scene-query.ts b/tests/physics2d/scene-query.ts new file mode 100644 index 00000000000..585832e2ae4 --- /dev/null +++ b/tests/physics2d/scene-query.ts @@ -0,0 +1,96 @@ +import { EPSILON, Quat, Rect, Vec2, Vec3 } from "../../cocos/core"; +import { director } from "../../cocos/game"; +import { Node } from "../../cocos/scene-graph"; +import * as physics2d from "../../exports/physics-2d-framework"; + +/** + * This function is used to test the api of the scene query + */ +export default function (parent: Node, _steps = 0) { + //skip builtin for now + if (physics2d.selector.id === 'builtin') + return; + + const nodeCollider = new Node('Collider2D'); + parent.addChild(nodeCollider); + const initPos = new Vec3(10, 0, 0); + nodeCollider.worldPosition = initPos; + const body = nodeCollider.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + const collider = nodeCollider.addComponent(physics2d.BoxCollider2D) as physics2d.Collider2D; + collider.group = 2; + + // add another collider + const nodeCollider2 = new Node('Collider2D2'); + parent.addChild(nodeCollider2); + const initPos2 = new Vec3(20, 0, 0); + nodeCollider2.worldPosition = initPos2; + const body2 = nodeCollider2.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; + const collider2 = nodeCollider2.addComponent(physics2d.BoxCollider2D) as physics2d.Collider2D; + collider2.group = physics2d.PhysicsGroup.DEFAULT; + + //test raycast cloest + { + const p0 = new Vec2(0, 0); + const p1 = new Vec2(20, 0); + let result = physics2d.PhysicsSystem2D.instance.raycast(p0, p1); + expect(result.length).toBe(1); + expect(result[0].collider.uuid).toBe(collider.uuid); + expect(Vec2.equals(result[0].point, new Vec2(9.5, 0))).toBe(true); + expect(Vec2.equals(result[0].normal, new Vec2(-1, 0))).toBe(true); + expect(Math.abs(result[0].fraction - 0.475)< 0.0001).toBe(true); + } + + //test raycast all + { + const p0 = new Vec2(0, 0); + const p1 = new Vec2(20, 0); + const type = physics2d.ERaycast2DType.All; + let result = physics2d.PhysicsSystem2D.instance.raycast(p0, p1, type); + expect(result.length).toBe(2); + + expect(result[1].collider.uuid).toBe(collider.uuid); + expect(Vec2.equals(result[1].point, new Vec2(9.5, 0))).toBe(true); + expect(Vec2.equals(result[1].normal, new Vec2(-1, 0))).toBe(true); + expect(Math.abs(result[1].fraction - 0.475)< 0.0001).toBe(true); + + expect(result[0].collider.uuid).toBe(collider2.uuid); + expect(Vec2.equals(result[0].point, new Vec2(19.5, 0))).toBe(true); + expect(Vec2.equals(result[0].normal, new Vec2(-1, 0))).toBe(true); + expect(Math.abs(result[0].fraction - 0.975)< 0.0001).toBe(true); + + } + + //test raycast all with group mask + { + const p0 = new Vec2(0, 0); + const p1 = new Vec2(20, 0); + const type = physics2d.ERaycast2DType.All; + const mask = physics2d.PhysicsGroup.DEFAULT; + let result = physics2d.PhysicsSystem2D.instance.raycast(p0, p1, type, mask); + expect(result.length).toBe(1); + expect(result[0].collider.uuid).toBe(collider2.uuid); + expect(Vec2.equals(result[0].point, new Vec2(19.5, 0))).toBe(true); + expect(Vec2.equals(result[0].normal, new Vec2(-1, 0))).toBe(true); + expect(Math.abs(result[0].fraction - 0.975)< 0.0001).toBe(true); + } + + //test testPoint + { + let result = physics2d.PhysicsSystem2D.instance.testPoint(new Vec2(10, 0)); + expect(result.length).toBe(1); + expect(result[0].uuid).toBe(collider.uuid); + } + + //test testAABB + { + let rect = new Rect(0, 0, 30, 30); + let result = physics2d.PhysicsSystem2D.instance.testAABB(rect); + expect(result.length).toBe(2); + expect(result[0].uuid).toBe(collider2.uuid); + expect(result[1].uuid).toBe(collider.uuid); + } + + + parent.destroyAllChildren(); + parent.removeAllChildren(); +} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index cb1ed02d828..be0012eabd6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -36,6 +36,7 @@ "./native/external/emscripten/physx/physx", "./native/external/emscripten/webgpu/webgpu", "./native/external/emscripten/spine/spine", + "./native/external/emscripten/box2d/box2d", // pal "./@types/pal/system-info", From 7c760c3056f33bfc5b4cdc982f94d0220f7c7aea Mon Sep 17 00:00:00 2001 From: zxx43 Date: Fri, 18 Aug 2023 23:26:36 +0800 Subject: [PATCH 196/232] 3.8.1 optimize particle pvdata type (#15928) * optimize pvdata type * fix eslint * change name of _attrs to _particleVertexData * add missed type * convert type --- cocos/particle/models/particle-batch-model.ts | 152 ++++++++---------- .../renderer/particle-system-renderer-cpu.ts | 96 ++++++----- 2 files changed, 125 insertions(+), 123 deletions(-) diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index a302acdeddf..ec93e74857e 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -173,21 +173,15 @@ export default class ParticleBatchModel extends scene.Model { )); const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._bufferSize * this._vertCount); if (this._mesh && this._capacity > 0) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison - let vOffset = (this._vertAttrs![this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD)] as any).offset; - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSize, vOffset); // copy mesh uv to ATTR_TEX_COORD - // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison - let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3); + let vOffset = (this._vertAttrs![this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD as string)] as any).offset; + this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSize, vOffset as number); // copy mesh uv to ATTR_TEX_COORD + let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3 as string); vOffset = (this._vertAttrs![vIdx++] as any).offset; - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSize, vOffset); // copy mesh position to ATTR_TEX_COORD3 + this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSize, vOffset as number); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSize, vOffset); // copy mesh normal to ATTR_NORMAL + this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSize, vOffset as number); // copy mesh normal to ATTR_NORMAL vOffset = (this._vertAttrs![vIdx++] as any).offset; - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSize, vOffset)) { // copy mesh color to ATTR_COLOR1 + if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSize, vOffset as number)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = Color.WHITE._val; @@ -274,22 +268,16 @@ export default class ParticleBatchModel extends scene.Model { const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSizeStatic * this._vertCount); if (this._mesh) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison - let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD); // find ATTR_TEX_COORD index + let vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD as string); // find ATTR_TEX_COORD index let vOffset = (this._vertAttrs![vIdx] as any).offset; // find ATTR_TEX_COORD offset - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh uv to ATTR_TEX_COORD - // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison - vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3); // find ATTR_TEX_COORD3 index + this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSizeStatic, vOffset as number); // copy mesh uv to ATTR_TEX_COORD + vIdx = this._vertAttrs!.findIndex((val): boolean => val.name === AttributeName.ATTR_TEX_COORD3 as string); // find ATTR_TEX_COORD3 index vOffset = (this._vertAttrs![vIdx++] as any).offset; // find ATTR_TEX_COORD3 offset - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh position to ATTR_TEX_COORD3 + this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSizeStatic, vOffset as number); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh normal to ATTR_NORMAL + this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSizeStatic, vOffset as number); // copy mesh normal to ATTR_NORMAL vOffset = (this._vertAttrs![vIdx++] as any).offset; - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSizeStatic, vOffset)) { // copy mesh color to ATTR_COLOR1 + if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSizeStatic, vOffset as number)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { vb[iVertex * this._vertStaticAttrsFloatCount + vOffset / 4] = Color.WHITE._val; @@ -345,41 +333,41 @@ export default class ParticleBatchModel extends scene.Model { if (!this._useInstance) { if (!this._mesh) { let offset: number = index * this._vertAttrsFloatCount; - this._vdataF32![offset++] = pvdata[0].x; // position - this._vdataF32![offset++] = pvdata[0].y; - this._vdataF32![offset++] = pvdata[0].z; - this._vdataF32![offset++] = pvdata[1].x; // uv - this._vdataF32![offset++] = pvdata[1].y; - this._vdataF32![offset++] = pvdata[1].z; // frame idx - this._vdataF32![offset++] = pvdata[2].x; // size - this._vdataF32![offset++] = pvdata[2].y; - this._vdataF32![offset++] = pvdata[2].z; - this._vdataF32![offset++] = pvdata[3].x; // rotation - this._vdataF32![offset++] = pvdata[3].y; - this._vdataF32![offset++] = pvdata[3].z; - this._vdataUint32![offset++] = pvdata[4]; // color - if (pvdata[5]) { - this._vdataF32![offset++] = pvdata[5].x; // velocity - this._vdataF32![offset++] = pvdata[5].y; - this._vdataF32![offset++] = pvdata[5].z; + this._vdataF32![offset++] = pvdata.position.x; // position + this._vdataF32![offset++] = pvdata.position.y; + this._vdataF32![offset++] = pvdata.position.z; + this._vdataF32![offset++] = pvdata.texcoord.x; // uv + this._vdataF32![offset++] = pvdata.texcoord.y; + this._vdataF32![offset++] = pvdata.texcoord.z; // frame idx + this._vdataF32![offset++] = pvdata.size.x; // size + this._vdataF32![offset++] = pvdata.size.y; + this._vdataF32![offset++] = pvdata.size.z; + this._vdataF32![offset++] = pvdata.rotation.x; // rotation + this._vdataF32![offset++] = pvdata.rotation.y; + this._vdataF32![offset++] = pvdata.rotation.z; + this._vdataUint32![offset++] = pvdata.color; // color + if (pvdata.velocity) { + this._vdataF32![offset++] = pvdata.velocity.x; // velocity + this._vdataF32![offset++] = pvdata.velocity.y; + this._vdataF32![offset++] = pvdata.velocity.z; } } else { for (let i = 0; i < this._vertCount; i++) { let offset: number = (index * this._vertCount + i) * this._vertAttrsFloatCount; - this._vdataF32![offset++] = pvdata[0].x; // position - this._vdataF32![offset++] = pvdata[0].y; - this._vdataF32![offset++] = pvdata[0].z; + this._vdataF32![offset++] = pvdata.position.x; // position + this._vdataF32![offset++] = pvdata.position.y; + this._vdataF32![offset++] = pvdata.position.z; offset += 2; // this._vdataF32![offset++] = index; - // this._vdataF32![offset++] = pvdata[1].y; - this._vdataF32![offset++] = pvdata[1].z; // frame idx - this._vdataF32![offset++] = pvdata[2].x; // size - this._vdataF32![offset++] = pvdata[2].y; - this._vdataF32![offset++] = pvdata[2].z; - this._vdataF32![offset++] = pvdata[3].x; // rotation - this._vdataF32![offset++] = pvdata[3].y; - this._vdataF32![offset++] = pvdata[3].z; - this._vdataUint32![offset++] = pvdata[4]; // color + // this._vdataF32![offset++] = pvdata.texcoord.y; + this._vdataF32![offset++] = pvdata.texcoord.z; // frame idx + this._vdataF32![offset++] = pvdata.size.x; // size + this._vdataF32![offset++] = pvdata.size.y; + this._vdataF32![offset++] = pvdata.size.z; + this._vdataF32![offset++] = pvdata.rotation.x; // rotation + this._vdataF32![offset++] = pvdata.rotation.y; + this._vdataF32![offset++] = pvdata.rotation.z; + this._vdataUint32![offset++] = pvdata.color; // color } } } else { @@ -390,40 +378,40 @@ export default class ParticleBatchModel extends scene.Model { private addParticleVertexDataIns (index: number, pvdata: PVData): void { let offset: number = index * this._vertAttrsFloatCount; if (!this._mesh) { - this._vdataF32![offset++] = pvdata[0].x; // position - this._vdataF32![offset++] = pvdata[0].y; - this._vdataF32![offset++] = pvdata[0].z; - this._vdataF32![offset++] = pvdata[1].z; // frame idx - - this._vdataF32![offset++] = pvdata[2].x; // size - this._vdataF32![offset++] = pvdata[2].y; - this._vdataF32![offset++] = pvdata[2].z; - - this._vdataF32![offset++] = pvdata[3].x; // rotation - this._vdataF32![offset++] = pvdata[3].y; - this._vdataF32![offset++] = pvdata[3].z; - - this._vdataUint32![offset++] = pvdata[4]; // color - if (pvdata[5]) { - this._vdataF32![offset++] = pvdata[5].x; // velocity - this._vdataF32![offset++] = pvdata[5].y; - this._vdataF32![offset++] = pvdata[5].z; + this._vdataF32![offset++] = pvdata.position.x; // position + this._vdataF32![offset++] = pvdata.position.y; + this._vdataF32![offset++] = pvdata.position.z; + this._vdataF32![offset++] = pvdata.texcoord.z; // frame idx + + this._vdataF32![offset++] = pvdata.size.x; // size + this._vdataF32![offset++] = pvdata.size.y; + this._vdataF32![offset++] = pvdata.size.z; + + this._vdataF32![offset++] = pvdata.rotation.x; // rotation + this._vdataF32![offset++] = pvdata.rotation.y; + this._vdataF32![offset++] = pvdata.rotation.z; + + this._vdataUint32![offset++] = pvdata.color; // color + if (pvdata.velocity) { + this._vdataF32![offset++] = pvdata.velocity.x; // velocity + this._vdataF32![offset++] = pvdata.velocity.y; + this._vdataF32![offset++] = pvdata.velocity.z; } } else { - this._vdataF32![offset++] = pvdata[0].x; // position - this._vdataF32![offset++] = pvdata[0].y; - this._vdataF32![offset++] = pvdata[0].z; - this._vdataF32![offset++] = pvdata[1].z; // frame idx + this._vdataF32![offset++] = pvdata.position.x; // position + this._vdataF32![offset++] = pvdata.position.y; + this._vdataF32![offset++] = pvdata.position.z; + this._vdataF32![offset++] = pvdata.texcoord.z; // frame idx - this._vdataF32![offset++] = pvdata[2].x; // size - this._vdataF32![offset++] = pvdata[2].y; - this._vdataF32![offset++] = pvdata[2].z; + this._vdataF32![offset++] = pvdata.size.x; // size + this._vdataF32![offset++] = pvdata.size.y; + this._vdataF32![offset++] = pvdata.size.z; - this._vdataF32![offset++] = pvdata[3].x; // rotation - this._vdataF32![offset++] = pvdata[3].y; - this._vdataF32![offset++] = pvdata[3].z; + this._vdataF32![offset++] = pvdata.rotation.x; // rotation + this._vdataF32![offset++] = pvdata.rotation.y; + this._vdataF32![offset++] = pvdata.rotation.z; - this._vdataUint32![offset++] = pvdata[4]; // color + this._vdataUint32![offset++] = pvdata.color; // color } } diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index 524d9ba9805..0f91aae63a5 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -138,9 +138,23 @@ const _matInsInfo: IMaterialInstanceInfo = { subModelIdx: 0, }; -// TODO: we should not use this type, should use a uniform array type instead. -// Tracking issue: https://github.com/cocos/cocos-engine/issues/15553 -export type PVData = [Vec3, Vec3, Vec3, Vec3, number, Vec3 | null, null]; +export class PVData { + public position: Vec3; + public texcoord: Vec3; + public size: Vec3; + public rotation: Vec3; + public color: number; + public velocity: Vec3 | null; + + constructor () { + this.position = new Vec3(); + this.texcoord = new Vec3(); + this.size = new Vec3(); + this.rotation = new Vec3(); + this.color = 0; + this.velocity = null; + } +} export default class ParticleSystemRendererCPU extends ParticleSystemRendererBase { private _defines: MacroRecord; @@ -149,7 +163,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private _tmp_velLenScale: Vec4; private _defaultMat: Material | null = null; private _node_scale: Vec3; - private _attrs: PVData; + private _particleVertexData: PVData; private _particles: RecyclePool | null = null; private _defaultTrailMat: Material | null = null; private _updateList: Map = new Map(); @@ -165,6 +179,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private _gravity: Vec4 = new Vec4(); constructor (info: any) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument super(info); this._model = null; @@ -172,7 +187,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._frameTile_velLenScale = new Vec4(1, 1, 0, 0); this._tmp_velLenScale = this._frameTile_velLenScale.clone(); this._node_scale = new Vec3(); - this._attrs = new Array(7) as PVData; + this._particleVertexData = new PVData(); this._defines = { CC_USE_WORLD_SPACE: true, CC_USE_BILLBOARD: true, @@ -233,6 +248,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas return this._defaultTrailMat; } + // eslint-disable-next-line @typescript-eslint/no-empty-function public setNewParticle (p: Particle): void { } @@ -258,6 +274,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas for (let i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) { const p = this._animateList[PARTICLE_MODULE_ORDER[i]]; if (p) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this._runAnimateList.push(p); } } @@ -279,7 +296,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas // reorder this._runAnimateList.length = 0; for (let i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) { - const p = this._animateList[PARTICLE_MODULE_ORDER[i]]; + const p: IParticleModule = this._animateList[PARTICLE_MODULE_ORDER[i]]; if (p) { this._runAnimateList.push(p); } @@ -518,29 +535,28 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private _fillMeshData (p: Particle, idx: number, fi: number): void { const i = idx / 4; - this._attrs[0] = p.position; + Vec3.copy(this._particleVertexData.position, p.position); _tempAttribUV.z = fi; - this._attrs[1] = _tempAttribUV; - this._attrs[2] = p.size; - this._attrs[3] = p.rotation; - this._attrs[4] = p.color._val; - this._model!.addParticleVertexData(i, this._attrs); + Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); + Vec3.copy(this._particleVertexData.size, p.size); + Vec3.copy(this._particleVertexData.rotation, p.rotation); + this._particleVertexData.color = p.color._val; + this._model!.addParticleVertexData(i, this._particleVertexData); } private _fillStrecthedData (p: Particle, idx: number, fi: number): void { if (!this._useInstance) { for (let j = 0; j < 4; ++j) { // four verts per particle. - this._attrs[0] = p.position; + Vec3.copy(this._particleVertexData.position, p.position); _tempAttribUV.x = _uvs[2 * j]; _tempAttribUV.y = _uvs[2 * j + 1]; _tempAttribUV.z = fi; - this._attrs[1] = _tempAttribUV; - this._attrs[2] = p.size; - this._attrs[3] = p.rotation; - this._attrs[4] = p.color._val; - this._attrs[5] = p.ultimateVelocity; - this._attrs[6] = null; - this._model!.addParticleVertexData(idx++, this._attrs); + Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); + Vec3.copy(this._particleVertexData.size, p.size); + Vec3.copy(this._particleVertexData.rotation, p.rotation); + this._particleVertexData.color = p.color._val; + this._particleVertexData.velocity = p.ultimateVelocity; + this._model!.addParticleVertexData(idx++, this._particleVertexData); } } else { this._fillStrecthedDataIns(p, idx, fi); @@ -549,29 +565,28 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private _fillStrecthedDataIns (p: Particle, idx: number, fi: number): void { const i = idx / 4; - this._attrs[0] = p.position; + Vec3.copy(this._particleVertexData.position, p.position); _tempAttribUV.z = fi; - this._attrs[1] = _tempAttribUV; - this._attrs[2] = p.size; - this._attrs[3] = p.rotation; - this._attrs[4] = p.color._val; - this._attrs[5] = p.ultimateVelocity; - this._model!.addParticleVertexData(i, this._attrs); + Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); + Vec3.copy(this._particleVertexData.size, p.size); + Vec3.copy(this._particleVertexData.rotation, p.rotation); + this._particleVertexData.color = p.color._val; + this._particleVertexData.velocity = p.ultimateVelocity; + this._model!.addParticleVertexData(i, this._particleVertexData); } private _fillNormalData (p: Particle, idx: number, fi: number): void { if (!this._useInstance) { for (let j = 0; j < 4; ++j) { // four verts per particle. - this._attrs[0] = p.position; + Vec3.copy(this._particleVertexData.position, p.position); _tempAttribUV.x = _uvs[2 * j]; _tempAttribUV.y = _uvs[2 * j + 1]; _tempAttribUV.z = fi; - this._attrs[1] = _tempAttribUV; - this._attrs[2] = p.size; - this._attrs[3] = p.rotation; - this._attrs[4] = p.color._val; - this._attrs[5] = null; - this._model!.addParticleVertexData(idx++, this._attrs); + Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); + Vec3.copy(this._particleVertexData.size, p.size); + Vec3.copy(this._particleVertexData.rotation, p.rotation); + this._particleVertexData.color = p.color._val; + this._model!.addParticleVertexData(idx++, this._particleVertexData); } } else { this._fillNormalDataIns(p, idx, fi); @@ -580,14 +595,13 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private _fillNormalDataIns (p: Particle, idx: number, fi: number): void { const i = idx / 4; - this._attrs[0] = p.position; + Vec3.copy(this._particleVertexData.position, p.position); _tempAttribUV.z = fi; - this._attrs[1] = _tempAttribUV; - this._attrs[2] = p.size; - this._attrs[3] = p.rotation; - this._attrs[4] = p.color._val; - this._attrs[5] = null; - this._model!.addParticleVertexData(i, this._attrs); + Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); + Vec3.copy(this._particleVertexData.size, p.size); + Vec3.copy(this._particleVertexData.rotation, p.rotation); + this._particleVertexData.color = p.color._val; + this._model!.addParticleVertexData(i, this._particleVertexData); } public updateVertexAttrib (): void { From c19d63d921424ac8f5101eb5349b9422cb9722ab Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Fri, 18 Aug 2023 23:39:50 +0800 Subject: [PATCH 197/232] Disallow using image bitmap by default (#16035) * Disallow using image bitmap by default * fix lint --- cocos/asset/asset-manager/asset-manager.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/asset/asset-manager/asset-manager.ts b/cocos/asset/asset-manager/asset-manager.ts index 56455b0986a..e82d6fe7dcb 100644 --- a/cocos/asset/asset-manager/asset-manager.ts +++ b/cocos/asset/asset-manager/asset-manager.ts @@ -201,7 +201,7 @@ export class AssetManager { * 是否优先使用 image bitmap 来加载图片,启用之后,图片加载速度会更快, 但内存占用会变高。 * */ - public allowImageBitmap = !EDITOR && !sys.isMobile; + public allowImageBitmap = false; /** * @en @@ -429,7 +429,7 @@ export class AssetManager { this._projectBundles = settings.querySettings(Settings.Category.ASSETS, 'projectBundles') || []; const assetsOverride = settings.querySettings(Settings.Category.ASSETS, 'assetsOverrides') || {}; for (const key in assetsOverride) { - this.assetsOverrideMap.set(key, assetsOverride[key]); + this.assetsOverrideMap.set(key, assetsOverride[key] as string); } } @@ -632,9 +632,9 @@ export class AssetManager { this.loadAny({ url }, opts, null, (err, data): void => { if (err) { error(err.message, err.stack); - if (onComp) { onComp(err, data); } + if (onComp) { onComp(err, data as T); } } else { - factory.create(url, data, opts.ext || path.extname(url), opts, (p1, p2): void => { + factory.create(url, data, (opts.ext as string) || path.extname(url), opts, (p1, p2): void => { if (onComp) { onComp(p1, p2 as T); } }); } @@ -693,7 +693,7 @@ export class AssetManager { this.loadAny({ url: nameOrUrl }, opts, null, (err, data): void => { if (err) { error(err.message, err.stack); - if (onComp) { onComp(err, data); } + if (onComp) { onComp(err, data as Bundle); } } else { factory.create(nameOrUrl, data, 'bundle', opts, (p1, p2): void => { if (onComp) { onComp(p1, p2 as Bundle); } @@ -791,7 +791,7 @@ export class AssetManager { input: [item], onProgress: onProg, options: opts, - onComplete: asyncify((err, data: T): void => { + onComplete: asyncify((err: Error | null, data: T): void => { if (!err) { if (!opts.assetId) { data._uuid = ''; From bde3cd4cc3d8020c1b6142ba67759a449da2ef00 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Mon, 21 Aug 2023 10:15:24 +0800 Subject: [PATCH 198/232] Add adv mesh functionalities. (#16009) * stage * update * update * fix physics & ray cast problem * fix default value, clean unused code, fix lint errors * clean code * update meta file * update external, license * fix tidy, circular dep * fix type cast * rm unit test * fix unit test * update comment --- EngineErrorMap.md | 12 + cocos/3d/assets/mesh.ts | 156 ++++++- cocos/3d/misc/create-mesh.ts | 30 +- cocos/3d/misc/mesh-codec.ts | 81 ++++ cocos/asset/assets/rendering-sub-mesh.ts | 148 +++++-- cocos/core/math/utils.ts | 66 +++ cocos/gfx/base/define.ts | 6 +- .../cannon/shapes/cannon-trimesh-shape.ts | 12 +- .../components/colliders/mesh-collider.ts | 2 - .../physx/shapes/physx-trimesh-shape.ts | 13 +- cocos/render-scene/scene/model.ts | 6 +- .../data-structures/vs-input.chunk | 2 +- editor/i18n/en/assets.js | 125 +++--- editor/i18n/zh/assets.js | 6 +- editor/inspector/assets/fbx/index.js | 2 +- editor/inspector/assets/fbx/model.js | 389 +++++++++--------- licenses/LICENSE_meshoptimizer.md | 21 + native/cocos/3d/assets/Mesh.cpp | 34 +- native/cocos/3d/assets/Mesh.h | 6 + native/cocos/3d/misc/CreateMesh.cpp | 68 +++ native/cocos/3d/misc/CreateMesh.h | 7 + native/cocos/core/assets/RenderingSubMesh.cpp | 148 +++++-- native/cocos/math/Utils.cpp | 57 +++ native/cocos/math/Utils.h | 4 + native/external-config.json | 4 +- .../tests/unit-test/src/math_utils_test.cpp | 1 + platforms/native/engine/jsb-physics.js | 7 +- tests/init.ts | 14 + tsconfig.json | 1 + 29 files changed, 1037 insertions(+), 391 deletions(-) create mode 100644 cocos/3d/misc/mesh-codec.ts create mode 100644 licenses/LICENSE_meshoptimizer.md diff --git a/EngineErrorMap.md b/EngineErrorMap.md index bf943cfd907..2302385d19e 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3343,6 +3343,18 @@ Can not update a static mesh. The primitiveIndex is out of range. +### 14202 + +meshopt asm decoder initialized + +### 14203 + +meshopt wasm decoder initialized + +### 14204 + +meshopt decoder error: %d + ### 14300 Can not keep world transform due to the zero scaling of parent node diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 0ca33d88c63..d064d93ddb0 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -28,7 +28,7 @@ import { Asset } from '../../asset/assets/asset'; import { IDynamicGeometry } from '../../primitive/define'; import { BufferBlob } from '../misc/buffer-blob'; import { Skeleton } from './skeleton'; -import { geometry, cclegacy, sys, warnID, Mat4, Quat, Vec3, assertIsTrue, murmurhash2_32_gc } from '../../core'; +import { geometry, cclegacy, sys, warnID, Mat4, Quat, Vec3, assertIsTrue, murmurhash2_32_gc, errorID } from '../../core'; import { RenderingSubMesh } from '../../asset/assets'; import { Attribute, Device, Buffer, BufferInfo, AttributeName, BufferUsageBit, Feature, Format, @@ -36,6 +36,8 @@ import { } from '../../gfx'; import { Morph } from './morph'; import { MorphRendering, createMorphRendering } from './morph-rendering'; +import { MeshoptDecoder } from '../misc/mesh-codec'; +import zlib from '../../../external/compression/zlib.min'; function getIndexStrideCtor (stride: number): Uint8ArrayConstructor | Uint16ArrayConstructor | Uint32ArrayConstructor { switch (stride) { @@ -77,6 +79,13 @@ export declare namespace Mesh { attributes: Attribute[]; } + export interface IMeshCluster { + clusterView: IBufferView; + triangleView: IBufferView; + vertexView: IBufferView; + coneView?: IBufferView; + } + /** * @en Sub mesh contains a list of primitives with the same type (Point, Line or Triangle) * @zh 子网格。子网格由一系列相同类型的图元组成(例如点、线、面等)。 @@ -106,6 +115,11 @@ export declare namespace Mesh { * 如未定义或指向的映射表不存在,则默认 VB 内所有关节索引数据直接对应骨骼资源数据。 */ jointMapIndex?: number; + + /** + * @en The cluster data of the sub mesh + */ + cluster?: IMeshCluster; } /** @@ -197,6 +211,30 @@ export declare namespace Mesh { * @zh 动态网格特有数据 */ dynamic?: IDynamicStruct; + + /** + * @en Whether the mesh data is quantized to reduce memory usage + * @zh 此网格数据是否经过量化以减少内存占用。 + */ + quantized?: boolean; + + /** + * @en Whether the mesh data is encoded to reduce memory usage + * @zh + */ + encoded?: boolean; + + /** + * @en Whether the mesh data is compressed to reduce memory usage + * @zh 此网格数据是否经过压缩以减少内存占用。 + */ + compressed?: boolean; + + /** + * @en Whether the mesh contains cluster data + * @zh 此网格是否包含 cluster 数据。 + */ + cluster?: boolean; } /** @@ -362,9 +400,19 @@ export class Mesh extends Asset { if (this._initialized) { return; } - this._initialized = true; + let info = { struct: this.struct, data: this.data }; + if (info.struct.compressed) { // decompress mesh data + info = inflateMesh(info); + } + if (this.struct.encoded) { // decode mesh data + info = decodeMesh(info); + } + + this._struct = info.struct; + this._data = info.data; + if (this._struct.dynamic) { const device: Device = deviceManager.gfxDevice; const vertexBuffers: Buffer[] = []; @@ -436,7 +484,7 @@ export class Mesh extends Asset { } let indexBuffer: Buffer | null = null; - let ib: any = null; + let ib: Uint8Array | Uint16Array | Uint32Array | undefined; if (prim.indexView) { const idxView = prim.indexView; @@ -752,7 +800,8 @@ export class Mesh extends Asset { for (let i = 0; i < struct.vertexBundles.length; i++) { 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) { + if (vtxBdl.attributes[j].name === (AttributeName.ATTR_POSITION as string) + || vtxBdl.attributes[j].name === (AttributeName.ATTR_NORMAL as string)) { const { format } = vtxBdl.attributes[j]; const inputView = new DataView( @@ -852,7 +901,8 @@ export class Mesh extends Asset { for (let v = 0; v < dstBundle.view.count; ++v) { dstAttrView = dstVBView.subarray(dstVBOffset, dstVBOffset + attrSize); vbView.set(dstAttrView, srcVBOffset); - if ((attr.name === AttributeName.ATTR_POSITION || attr.name === AttributeName.ATTR_NORMAL) && worldMatrix) { + if ((attr.name === (AttributeName.ATTR_POSITION as string) + || attr.name === (AttributeName.ATTR_NORMAL as string)) && worldMatrix) { const f32_temp = new Float32Array(vbView.buffer, srcVBOffset, 3); vec3_temp.set(f32_temp[0], f32_temp[1], f32_temp[2]); switch (attr.name) { @@ -1258,7 +1308,7 @@ export class Mesh extends Asset { const primitive = this._struct.primitives[primitiveIndex]; for (const vertexBundleIndex of primitive.vertexBundelIndices) { const vertexBundle = this._struct.vertexBundles[vertexBundleIndex]; - const iAttribute = vertexBundle.attributes.findIndex((a) => a.name === attributeName); + const iAttribute = vertexBundle.attributes.findIndex((a) => a.name === (attributeName as string)); if (iAttribute < 0) { continue; } @@ -1383,7 +1433,12 @@ function getReader (dataView: DataView, format: Format): ((offset: number) => nu break; } case FormatType.FLOAT: { - return (offset: number): number => dataView.getFloat32(offset, isLittleEndian); + switch (stride) { + case 2: return (offset: number) => dataView.getUint16(offset, isLittleEndian); + case 4: return (offset: number) => dataView.getFloat32(offset, isLittleEndian); + default: + } + break; } default: } @@ -1433,7 +1488,12 @@ function getWriter (dataView: DataView, format: Format): ((offset: number, value break; } case FormatType.FLOAT: { - return (offset: number, value: number): void => dataView.setFloat32(offset, value, isLittleEndian); + switch (stride) { + case 2: return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian); + default: + } + break; } default: } @@ -1441,4 +1501,84 @@ function getWriter (dataView: DataView, format: Format): ((offset: number, value return null; } +export function decodeMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo { + if (!mesh.struct.encoded) { + // the mesh is not encoded, so no need to decode + return mesh; + } + + // decode the mesh + if (!MeshoptDecoder.supported) { + return mesh; + } + + const res_checker = (res: number): void => { + if (res < 0) { + errorID(14204, res); + } + }; + + const struct = JSON.parse(JSON.stringify(mesh.struct)) as Mesh.IStruct; + + const bufferBlob = new BufferBlob(); + bufferBlob.setNextAlignment(0); + + for (const bundle of struct.vertexBundles) { + const view = bundle.view; + const bound = view.count * view.stride; + const buffer = new Uint8Array(bound); + const vertex = new Uint8Array(mesh.data.buffer, view.offset, view.length); + const res = MeshoptDecoder.decodeVertexBuffer(buffer, view.count, view.stride, vertex) as number; + res_checker(res); + + bufferBlob.setNextAlignment(view.stride); + const newView: Mesh.IBufferView = { + offset: bufferBlob.getLength(), + length: buffer.byteLength, + count: view.count, + stride: view.stride, + }; + bundle.view = newView; + bufferBlob.addBuffer(buffer); + } + + for (const primitive of struct.primitives) { + if (primitive.indexView === undefined) { + continue; + } + + const view = primitive.indexView; + const bound = view.count * view.stride; + const buffer = new Uint8Array(bound); + const index = new Uint8Array(mesh.data.buffer, view.offset, view.length); + const res = MeshoptDecoder.decodeIndexBuffer(buffer, view.count, view.stride, index) as number; + res_checker(res); + + bufferBlob.setNextAlignment(view.stride); + const newView: Mesh.IBufferView = { + offset: bufferBlob.getLength(), + length: buffer.byteLength, + count: view.count, + stride: view.stride, + }; + primitive.indexView = newView; + bufferBlob.addBuffer(buffer); + } + + const data = new Uint8Array(bufferBlob.getCombined()); + + return { + struct, + data, + }; +} + +export function inflateMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo { + const inflator = new zlib.Inflate(mesh.data); + const decompressed = inflator.decompress(); + mesh.data = decompressed; + mesh.struct.compressed = false; + return mesh; +} + // function get diff --git a/cocos/3d/misc/create-mesh.ts b/cocos/3d/misc/create-mesh.ts index dc1352344d8..176d6ee71ed 100644 --- a/cocos/3d/misc/create-mesh.ts +++ b/cocos/3d/misc/create-mesh.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { Mesh } from '../assets/mesh'; +import { Mesh, decodeMesh, inflateMesh } from '../assets/mesh'; import { AttributeName, Format, FormatInfos, PrimitiveMode, Attribute } from '../../gfx'; import { Vec3 } from '../../core'; import { IGeometry, IDynamicGeometry, ICreateMeshOptions, ICreateDynamicMeshOptions } from '../../primitive/define'; @@ -56,7 +56,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe attr = null; if (geometry.attributes) { for (const att of geometry.attributes) { - if (att.name === AttributeName.ATTR_POSITION) { + if (att.name === (AttributeName.ATTR_POSITION as string)) { attr = att; break; } @@ -78,7 +78,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe attr = null; if (geometry.attributes) { for (const att of geometry.attributes) { - if (att.name === AttributeName.ATTR_NORMAL) { + if (att.name === (AttributeName.ATTR_NORMAL as string)) { attr = att; break; } @@ -100,7 +100,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe attr = null; if (geometry.attributes) { for (const att of geometry.attributes) { - if (att.name === AttributeName.ATTR_TEX_COORD) { + if (att.name === (AttributeName.ATTR_TEX_COORD as string)) { attr = att; break; } @@ -122,7 +122,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe attr = null; if (geometry.attributes) { for (const att of geometry.attributes) { - if (att.name === AttributeName.ATTR_TANGENT) { + if (att.name === (AttributeName.ATTR_TANGENT as string)) { attr = att; break; } @@ -144,7 +144,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe attr = null; if (geometry.attributes) { for (const att of geometry.attributes) { - if (att.name === AttributeName.ATTR_COLOR) { + if (att.name === (AttributeName.ATTR_COLOR as string)) { attr = att; break; } @@ -434,6 +434,24 @@ export class MeshUtils { static createDynamicMesh (primitiveIndex: number, geometry: IDynamicGeometry, out?: Mesh, options?: ICreateDynamicMeshOptions): Mesh { return createDynamicMesh(primitiveIndex, geometry, out, options); } + + /** + * @en decode a mesh. + * + * @engineInternal + */ + static decodeMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo { + return decodeMesh(mesh); + } + + /** + * @en inflate a mesh. + * + * @engineInternal + */ + static inflateMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo { + return inflateMesh(mesh); + } } export declare namespace createMesh { diff --git a/cocos/3d/misc/mesh-codec.ts b/cocos/3d/misc/mesh-codec.ts new file mode 100644 index 00000000000..86094fce109 --- /dev/null +++ b/cocos/3d/misc/mesh-codec.ts @@ -0,0 +1,81 @@ +/* + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import meshopt_asm_factory from 'external:emscripten/meshopt/meshopt_decoder.asm.js'; +import meshopt_wasm_factory from 'external:emscripten/meshopt/meshopt_decoder.wasm.js'; + +import { WASM_SUPPORT_MODE } from 'internal:constants'; + +import { sys, logID } from '../../core'; + +import { game } from '../../game'; +import { WebAssemblySupportMode } from '../../misc/webassembly-support'; + +export const MeshoptDecoder = {} as any; + +function initDecoderASM (): Promise { + const Module = meshopt_asm_factory; + return Promise.all([Module.ready]).then(() => { + MeshoptDecoder.supported = true; + MeshoptDecoder.ready = Promise.resolve(); + MeshoptDecoder.decodeVertexBuffer = Module.decodeVertexBuffer; + MeshoptDecoder.decodeIndexBuffer = Module.decodeIndexBuffer; + MeshoptDecoder.decodeIndexSequence = Module.decodeIndexSequence; + MeshoptDecoder.decodeGltfBuffer = Module.decodeGltfBuffer; + MeshoptDecoder.useWorkers = Module.useWorkers; + MeshoptDecoder.decodeGltfBufferAsync = Module.decodeGltfBufferAsync; + logID(14202); + }); +} + +function initDecoderWASM (): Promise { + const Module = meshopt_wasm_factory; + return Promise.all([Module.ready]).then(() => { + MeshoptDecoder.supported = true; + MeshoptDecoder.ready = Promise.resolve(); + MeshoptDecoder.decodeVertexBuffer = Module.decodeVertexBuffer; + MeshoptDecoder.decodeIndexBuffer = Module.decodeIndexBuffer; + MeshoptDecoder.decodeIndexSequence = Module.decodeIndexSequence; + MeshoptDecoder.decodeGltfBuffer = Module.decodeGltfBuffer; + MeshoptDecoder.useWorkers = Module.useWorkers; + MeshoptDecoder.decodeGltfBufferAsync = Module.decodeGltfBufferAsync; + logID(14203); + }); +} + +export function InitDecoder (): Promise { + if (WASM_SUPPORT_MODE === (WebAssemblySupportMode.MAYBE_SUPPORT as number)) { + if (sys.hasFeature(sys.Feature.WASM)) { + return initDecoderWASM(); + } else { + return initDecoderASM(); + } + } else if (WASM_SUPPORT_MODE === (WebAssemblySupportMode.SUPPORT as number)) { + return initDecoderWASM(); + } else { + return initDecoderASM(); + } +} + +game.onPostInfrastructureInitDelegate.add(InitDecoder); diff --git a/cocos/asset/assets/rendering-sub-mesh.ts b/cocos/asset/assets/rendering-sub-mesh.ts index a648dc6a3ea..2ec5dd6a019 100644 --- a/cocos/asset/assets/rendering-sub-mesh.ts +++ b/cocos/asset/assets/rendering-sub-mesh.ts @@ -27,8 +27,9 @@ import { Attribute, Device, InputAssemblerInfo, Buffer, BufferInfo, AttributeName, BufferUsageBit, Format, FormatInfos, MemoryUsageBit, PrimitiveMode, DrawInfo, } from '../../gfx'; -import { Vec3, cclegacy } from '../../core'; +import { Vec3, approx, cclegacy, floatToHalf, halfToFloat, pseudoRandomRange } from '../../core'; import { Mesh } from '../../3d/assets/mesh'; +import { Root } from '../../root'; /** * @en Array views for index buffer @@ -123,6 +124,12 @@ export class RenderingSubMesh { private _drawInfo?: DrawInfo | null = null; + private static EMPTY_GEOMETRIC_INFO: IGeometricInfo = { + positions: new Float32Array(), + indices: new Uint8Array(), + boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO }, + }; + /** * @en * sub mesh's constructor. @@ -135,8 +142,11 @@ export class RenderingSubMesh { * @param indirectBuffer @en indirect buffer. @zh 间接缓冲区。 */ constructor ( - vertexBuffers: Buffer[], attributes: Attribute[], primitiveMode: PrimitiveMode, - indexBuffer: Buffer | null = null, indirectBuffer: Buffer | null = null, + vertexBuffers: Buffer[], + attributes: Attribute[], + primitiveMode: PrimitiveMode, + indexBuffer: Buffer | null = null, + indirectBuffer: Buffer | null = null, isOwnerOfIndexBuffer = true, ) { this._attributes = attributes; @@ -187,40 +197,105 @@ export class RenderingSubMesh { return this._geometricInfo; } if (this.mesh === undefined) { - return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } }; + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; } if (this.subMeshIdx === undefined) { - return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } }; + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; } 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 pAttri = this.attributes.find((element) => element.name === (AttributeName.ATTR_POSITION as string)); + + if (!pAttri) { + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + } + + let positions: Float32Array | undefined; + switch (pAttri.format) { + case Format.RG32F: + case Format.RGB32F: + { + positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array; + if (!positions) { + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + } + break; + } + case Format.RGBA32F: + { + const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array; + if (!data) { + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + } + const count = data.length / 4; + positions = new Float32Array(count * 3); + for (let i = 0; i < count; ++i) { + const dstPtr = i * 3; + const srcPtr = i * 4; + positions[dstPtr] = data[srcPtr]; + positions[dstPtr + 1] = data[srcPtr + 1]; + positions[dstPtr + 2] = data[srcPtr + 2]; + } + break; + } + case Format.RG16F: + case Format.RGB16F: + { + const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Uint16Array; + if (!data) { + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + } + positions = new Float32Array(data.length); + for (let i = 0; i < data.length; ++i) { + positions[i] = halfToFloat(data[i]); + } + break; + } + case Format.RGBA16F: + { + const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Uint16Array; + if (!data) { + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + } + const count = data.length / 4; + positions = new Float32Array(count * 3); + for (let i = 0; i < count; ++i) { + const dstPtr = i * 3; + const srcPtr = i * 4; + positions[dstPtr] = halfToFloat(data[srcPtr]); + positions[dstPtr + 1] = halfToFloat(data[srcPtr + 1]); + positions[dstPtr + 2] = halfToFloat(data[srcPtr + 2]); + } + break; + } + default: + return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + } + + const indices = mesh.readIndices(index) || undefined; const max = new Vec3(); const min = new Vec3(); - const pAttri = this.attributes.find((element): boolean => element.name === AttributeName.ATTR_POSITION); - if (pAttri) { - const conut = FormatInfos[pAttri.format].count; + + const conut = FormatInfos[pAttri.format].count; + if (conut === 2) { + max.set(positions[0], positions[1], 0); + min.set(positions[0], positions[1], 0); + } else { + max.set(positions[0], positions[1], positions[2]); + min.set(positions[0], positions[1], positions[2]); + } + for (let i = 0; i < positions.length; i += conut) { if (conut === 2) { - max.set(positions[0], positions[1], 0); - min.set(positions[0], positions[1], 0); + max.x = positions[i] > max.x ? positions[i] : max.x; + max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; + min.x = positions[i] < min.x ? positions[i] : min.x; + min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; } else { - max.set(positions[0], positions[1], positions[2]); - min.set(positions[0], positions[1], positions[2]); - } - for (let i = 0; i < positions.length; i += conut) { - if (conut === 2) { - max.x = positions[i] > max.x ? positions[i] : max.x; - max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; - min.x = positions[i] < min.x ? positions[i] : min.x; - min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; - } else { - max.x = positions[i] > max.x ? positions[i] : max.x; - max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; - max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z; - min.x = positions[i] < min.x ? positions[i] : min.x; - min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; - min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z; - } + max.x = positions[i] > max.x ? positions[i] : max.x; + max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; + max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z; + min.x = positions[i] < min.x ? positions[i] : min.x; + min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; + min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z; } } this._geometricInfo = { positions, indices, boundingBox: { max, min } }; @@ -307,14 +382,14 @@ export class RenderingSubMesh { } let jointFormat: Format; let jointOffset: number; - const { device } = cclegacy.director.root; + const { device } = cclegacy.director.root as Root; for (let i = 0; i < prim.vertexBundelIndices.length; i++) { const bundle = struct.vertexBundles[prim.vertexBundelIndices[i]]; jointOffset = 0; jointFormat = Format.UNKNOWN; for (let j = 0; j < bundle.attributes.length; j++) { const attr = bundle.attributes[j]; - if (attr.name === AttributeName.ATTR_JOINTS) { + if (attr.name === (AttributeName.ATTR_JOINTS as string)) { jointFormat = attr.format; break; } @@ -324,8 +399,15 @@ export class RenderingSubMesh { const data = new Uint8Array(this.mesh.data.buffer, bundle.view.offset, bundle.view.length); const dataView = new DataView(data.slice().buffer); const idxMap = struct.jointMaps[prim.jointMapIndex]; - mapBuffer(dataView, (cur): number => idxMap.indexOf(cur), jointFormat, jointOffset, - bundle.view.length, bundle.view.stride, dataView); + mapBuffer( + dataView, + (cur): number => idxMap.indexOf(cur), + jointFormat, + jointOffset, + bundle.view.length, + bundle.view.stride, + dataView, + ); const buffer = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, diff --git a/cocos/core/math/utils.ts b/cocos/core/math/utils.ts index 3b653aba193..607f937ba70 100644 --- a/cocos/core/math/utils.ts +++ b/cocos/core/math/utils.ts @@ -299,3 +299,69 @@ export function enumerableProps (prototype: ValueType, attrs: string[]): void { Object.defineProperty(prototype, key, { enumerable: true }); }); } + +/** + * convert float to half (short) + */ + +const toHalf = (function () { + // https://stackoverflow.com/questions/32633585/how-do-you-convert-to-half-floats-in-javascript + const floatView = new Float32Array(1); + const int32View = new Int32Array(floatView.buffer); + + return function toHalf (fval: number): number { + floatView[0] = fval; + const fbits = int32View[0]; + const s = (fbits >> 16) & 0x8000; // sign + const em = fbits & 0x7fffffff; // exp and mantissa + + let h = (em - (112 << 23) + (1 << 12)) >> 13; + h = (em < (113 << 23)) ? 0 : h; // denormals-as-zero + + h = (em >= (143 << 23)) ? 0x7c00 : h; // overflow + + h = (em > (255 << 23)) ? 0x7e00 : h; // NaN + + int32View[0] = (s | h); // pack sign and half + + return int32View[0]; + }; +}()); + +const fromHalf = (function () { + const floatView = new Float32Array(1); + const int32View = new Int32Array(floatView.buffer); + + return function fromHalf (hval: number /* uint16 */): number { + const s = (hval >> 15) & 0x00000001; // sign + const em = hval & 0x00007fff; // exp and mantissa + + let h = (em << 13); // exponent/mantissa bits + let fbits = 0; + + if (h !== 0x7c00) { // // NaN/Inf + h += (112 << 23); // exp adjust + + if (em === 0) { // // Denormals-as-zero + h = (h & 0xfffff) >> 1; // // Mantissa shift + } else if (em === 0x7fff) { // // Inf/NaN? + h = 0x7fffffff; // // NaN + } + } else { + h = 0x7f800000; // // +/-Inf + } + + fbits = (s << 31) | h; // // Sign | Exponent | Mantissa + int32View[0] = fbits; + + return floatView[0]; + }; +}()); + +export function floatToHalf (val: number) { + return toHalf(val); +} + +export function halfToFloat (val: number) { + return fromHalf(val); +} diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 6e614fb3630..235e0880c8e 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -2344,7 +2344,11 @@ export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstruct } } case FormatType.FLOAT: { - return Float32Array; + switch (stride) { + case 2: return Uint16Array; + case 4: return Float32Array; + default: return Float32Array; + } } default: } diff --git a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts index 8804ff3cfa4..63d4f3bad6e 100644 --- a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts @@ -48,8 +48,16 @@ export class CannonTrimeshShape extends CannonShape implements ITrimeshShape { if (this._shape != null) { if (mesh && mesh.renderingSubMeshes.length > 0) { const vertices = mesh.renderingSubMeshes[0].geometricInfo.positions; - const indices = mesh.renderingSubMeshes[0].geometricInfo.indices as Uint16Array; - this.updateProperties(vertices, indices); + const indices = mesh.renderingSubMeshes[0].geometricInfo.indices; + if (indices instanceof Uint8Array) { + this.updateProperties(vertices, new Uint16Array(indices)); + } else if (indices instanceof Uint16Array) { + this.updateProperties(vertices, indices); + } else if (indices instanceof Uint32Array) { + this.updateProperties(vertices, new Uint16Array(indices)); + } else { + this.updateProperties(vertices, new Uint16Array()); + } } else { this.updateProperties(new Float32Array(), new Uint16Array()); } diff --git a/cocos/physics/framework/components/colliders/mesh-collider.ts b/cocos/physics/framework/components/colliders/mesh-collider.ts index e2b4dd912ba..608ad551b74 100644 --- a/cocos/physics/framework/components/colliders/mesh-collider.ts +++ b/cocos/physics/framework/components/colliders/mesh-collider.ts @@ -110,8 +110,6 @@ export class MeshCollider extends Collider { } } - /// PRIVATE PROPERTY /// - @serializable private _mesh: Mesh | null = null; diff --git a/cocos/physics/physx/shapes/physx-trimesh-shape.ts b/cocos/physics/physx/shapes/physx-trimesh-shape.ts index bdbd797b326..edb61e4450b 100644 --- a/cocos/physics/physx/shapes/physx-trimesh-shape.ts +++ b/cocos/physics/physx/shapes/physx-trimesh-shape.ts @@ -54,10 +54,17 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape { const meshScale = PhysXShape.MESH_SCALE; meshScale.setScale(Vec3.ONE); meshScale.setRotation(Quat.IDENTITY); - if (collider.convex) { + const posBuf = v.renderingSubMeshes[0].geometricInfo.positions; + let indBuf = v.renderingSubMeshes[0].geometricInfo.indices; + if (indBuf instanceof Uint16Array) { + indBuf = new Uint32Array(indBuf); + } + if (indBuf instanceof Uint8Array) { + indBuf = new Uint32Array(indBuf); + } + if (collider.convex || indBuf === undefined) { if (PX.MESH_CONVEX[v._uuid] == null) { const cooking = PhysXInstance.cooking; - const posBuf = v.readAttribute(0, AttributeName.ATTR_POSITION)! as unknown as Float32Array; PX.MESH_CONVEX[v._uuid] = createConvexMesh(posBuf, cooking, physics); } const convexMesh = PX.MESH_CONVEX[v._uuid]; @@ -65,8 +72,6 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape { } else { if (PX.MESH_STATIC[v._uuid] == null) { const cooking = PhysXInstance.cooking; - const posBuf = v.readAttribute(0, AttributeName.ATTR_POSITION)! as unknown as Float32Array; - const indBuf = v.readIndices(0)! as unknown as Uint32Array; // Uint16Array ? PX.MESH_STATIC[v._uuid] = createTriangleMesh(posBuf, indBuf, cooking, physics); } const trimesh = PX.MESH_STATIC[v._uuid]; diff --git a/cocos/render-scene/scene/model.ts b/cocos/render-scene/scene/model.ts index 360d856a821..1e455089938 100644 --- a/cocos/render-scene/scene/model.ts +++ b/cocos/render-scene/scene/model.ts @@ -36,7 +36,11 @@ import { IMacroPatch } from '../core/pass'; import { Mat4, Vec3, Vec4, geometry, cclegacy, EPSILON } from '../../core'; import { Attribute, DescriptorSet, Device, Buffer, BufferInfo, BufferUsageBit, MemoryUsageBit, Filter, Address, SamplerInfo, deviceManager, Texture } from '../../gfx'; -import { UBOLocal, UBOSH, UBOWorldBound, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING } from '../../rendering/define'; +import { + UBOLocal, UBOSH, UBOWorldBound, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, + UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, + UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, +} from '../../rendering/define'; import { Root } from '../../root'; import { TextureCube } from '../../asset/assets'; import { ShadowType } from './shadows'; diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk index 004fdd89ed9..d709284f991 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk @@ -55,4 +55,4 @@ layout(location = 2) in vec2 a_texCoord; #if __VERSION__ < 450 in float a_vertexId; #endif -#endif +#endif \ No newline at end of file diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index 7877f58ccdb..d2393bfd1bc 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -327,84 +327,65 @@ module.exports = { name: 'Add Vertex Color', title: 'Fill vertex color with white if the model file does not contain vertex color attribute.', }, - meshOptimizer: { - name: 'Mesh Optimizer', - title: 'Mesh Optimizer is used to simplify imported mesh.
Use it when you need to reduce model face count.
In some cases, face reduction could lead to various model defect.
Tweak properties and try again in those cases.', - simplification: { - name: 'Simplification', - title: 'Simplification', - si: { - name: 'Achieve The Ratio R', - title: 'Achieve The Ratio R', - }, - sa: { - name: 'Aggressively Simplify', - title: 'Aggressively Simplify', - }, + meshOptimize: { + name: 'Mesh Optimize', + title: 'Whether to optimize the mesh data.', + vertexCache: { + name: 'Vertex Cache', + title: 'Optimize the vertex buffer to improve vertex cache hit rate.
It is recommended to enable this option for models with high vertex count.', }, - scene: { - name: 'Scene', - title: 'Scene', - kn: { - name: 'Keep Nodes Transform', - title: 'Keep Nodes Transform', - }, - ke: { - name: 'Keep Extras Data', - title: 'Keep Extras Data', - }, + vertexFetch: { + name: 'Vertex Fetch', + title: 'Optimize the vertex buffer to improve vertex fetch efficiency.
It is recommended to enable this option for models with high vertex count.', }, - miscellaneous: { - name: 'Miscellaneous', - title: 'Miscellaneous', - noq: { - name: 'Disable Quantization', - title: 'Disable Quantization', - }, - v: { - name: 'Verbose Output', - title: 'Verbose Output', - }, + overdraw: { + name: 'Overdraw', + title: 'Optimize the vertex buffer to reduce overdraw.
It is recommended to enable this option for models with high vertex count.', }, - algorithm: { - name: 'Algorithm', - simplify: 'simplify', - gltfpack: 'gltfpack (deprecated)', + }, + meshSimplify: { + name: 'Mesh Simplify', + title: 'Whether to simplify the mesh data.', + targetRatio: { + name: 'Target Ratio', + title: 'The target ratio of the simplified mesh data.
It is recommended to set this value to 0.5.', }, - simplify:{ - targetRatio: { - name: 'Ratio', - title: 'The target face count ratio after face reduction.
0 means reduce to minimum, and 1 means no face reduction at all. ', - }, - preserveSurfaceCurvature: { - name: 'Surface Curvature', - title: 'Preserve Surface Curvature', - }, - preserveBorderEdges: { - name: 'Border Edges', - title: 'Preserve Border Edges', - }, - preserveUVSeamEdges: { - name: 'UV Seam Edges', - title: 'Preserve UV Seam Edges', - }, - preserveUVFoldoverEdges: { - name: 'UV Foldover Edges', - title: 'Preserve UV Foldover Edges', - }, - agressiveness: { - name: 'Agressiveness', - title: 'Face reduction algorithm aggressiveness.
The higher it sets, the more aggressive the face reduction algorithm tries to delete faces.
High aggressiveness setting is more likely to cause defects in result.', - }, - maxIterationCount: { - name: 'Max Iteration Count', - title: 'The max iteration counts that the algorithm tries to further reduce faces of a model.
High iteration count is more likely to reach face reduction target, yet it is more likely to take more time and has higher chance to cause mistakes.', - }, + autoErrorRate: { + name: 'Auto Error Rate', + title: 'Whether to automatically calculate the error rate of the simplified mesh data.', + }, + errorRate: { + name: 'Error Rate', + title: 'The max error rate of the simplified mesh data.
This value also alters the result size.
It is recommended to tune until you get a good result.', + }, + lockBoundary: { + name: 'Lock Boundary', + title: 'Whether to lock the boundary of the simplified mesh data.', + }, + }, + meshCluster: { + name: 'Mesh Cluster', + title: 'Whether to cluster the mesh data.', + generateBounding: { + name: 'Generate Bounding', + title: 'Whether to generate bounding sphere and normal cone for the clustered mesh data.', + }, + }, + meshCompress:{ + name: 'Mesh Compress', + title: 'Whether to compress the mesh data.', + encode: { + name: 'Encode', + title: 'Encode the mesh data to reduce data size.', + }, + compress: { + name: 'Compress', + title: 'Compress the mesh data to reduce data size.', }, - gltfpack: { - warn: 'The current asset uses the gltfpack mesh optimization algorithm, which has been deprecated. Please use the new simplify face reduction algorithm.', + quantize: { + name: 'Quantize', + title: 'Quantize the mesh data to reduce data size.', }, - warn: 'Warning: After optimization, the number and names of mesh resources will change, which will cause the loss of resources referenced by the components, please update them manually in time. (In addition, for prefabs pre-generated in the model resources, the resource synchronization mechanism will update them automatically)', }, animationBakeRate: { name: 'Animation Bake Rate', diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index 80f563243d2..edf9f8acf94 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -325,9 +325,9 @@ module.exports = { name: '填充顶点色', title: '如果模型没有顶点颜色属性,添加颜色属性,填充为白色。', }, - meshOptimizer: { - name: 'Mesh 优化', - title: 'Mesh 优化可以被用来简化导入的模型,可以在需要模型减面时使用。
在一些少数情况下减面后的模型可能会出现显示异常,如发生这种情况请尝试调整参数并重试。', + meshSimplify: { + name: 'Mesh 简化', + title: 'Mesh 简化可以被用来简化导入的模型,可以在需要模型减面时使用。
在一些少数情况下减面后的模型可能会出现显示异常,如发生这种情况请尝试调整参数并重试。', simplification: { name: 'Simplification', title: 'Simplification', diff --git a/editor/inspector/assets/fbx/index.js b/editor/inspector/assets/fbx/index.js index b143506cc0f..c1e2860ab3b 100644 --- a/editor/inspector/assets/fbx/index.js +++ b/editor/inspector/assets/fbx/index.js @@ -117,7 +117,7 @@ exports.listeners = { if (!value) { return; } // 只有被勾选的时候上报埋点 const trackMap = { - meshOptimizer: 'A100000', + meshSimplify: 'A100000', 'fbx.smartMaterialEnabled': 'A100001', disableMeshSplit: 'A100002', }; diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index 6fac16493b2..8c524043019 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -40,91 +40,83 @@ exports.template = /* html */` - -

- - + +
+ +
-
- - - +
+ + + -
-
-
- -
+ + +
+ + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
-
+ + +
+ + +
+
- - + + - - + + - - + + - - + + +
+
+ +
+ + +
+
- - + + + +
+
+ +
+ + +
+
+ + + - - + + - - + +
+
@@ -254,25 +246,28 @@ exports.$ = { addVertexColorCheckbox: '.addVertexColor-checkbox', promoteSingleRootNodeCheckbox: '.promoteSingleRootNode-checkbox', generateLightmapUVNodeCheckbox: '.generateLightmapUVNode-checkbox', - meshOptimizerCheckbox: '.meshOptimizer-checkbox', - meshOptimizerAlgorithmSelect: '.meshOptimizer-algorithm-select', - // gltfpackOptions - meshOptimizerGltfpackOptions: '.gltfpack-options', - meshOptimizerSISlider: '.meshOptimizer-si-slider', - meshOptimizerSACheckbox: '.meshOptimizer-sa-checkbox', - meshOptimizerKNCheckbox: '.meshOptimizer-kn-checkbox', - meshOptimizerKECheckbox: '.meshOptimizer-ke-checkbox', - meshOptimizerNOQCheckbox: '.meshOptimizer-noq-checkbox', - meshOptimizerVCheckbox: '.meshOptimizer-v-checkbox', + + // meshOptimizeOptions + meshOptimizeCheckbox: '.meshOptimize-checkbox', + meshOptimizeVertexCacheCheckbox: '.meshOptimize-vertexCache-checkbox', + meshOptimizeVertexFetchCheckbox: '.meshOptimize-vertexFetch-checkbox', + meshOptimizeOverdrawCheckbox: '.meshOptimize-overdraw-checkbox', + // simplifyOptions - meshOptimizerSimplifyOptions: '.simplify-options', - meshOptimizerTargetRatioSlider: '.meshOptimizer-targetRatio-slider', - meshOptimizerPreserveSurfaceCurvatureCheckbox: '.meshOptimizer-preserveSurfaceCurvature-checkbox', - meshOptimizerPreserveBorderEdgesCheckbox: '.meshOptimizer-preserveBorderEdges-checkbox', - meshOptimizerPreserveUVSeamEdgesCheckbox: '.meshOptimizer-preserveUVSeamEdges-checkbox', - meshOptimizerPreserveUVFoldoverEdgesCheckbox: '.meshOptimizer-preserveUVFoldoverEdges-checkbox', - meshOptimizerAgressivenessSlider: '.meshOptimizer-agressiveness-slider', - meshOptimizerMaxIterationCountSlider: '.meshOptimizer-maxIterationCount-slider', + meshSimplifyCheckbox: '.meshSimplify-checkbox', + meshSimplifyTargetRatioSlider: '.meshSimplify-targetRatio-slider', + meshSimplifyAutoErrorRateCheckbox: '.meshSimplify-autoErrorRate-checkbox', + meshSimplifyErrorRateSlider: '.meshSimplify-errorRate-slider', + meshSimplifyLockBoundaryCheckbox: '.meshSimplify-lockBoundary-checkbox', + + meshClusterCheckbox: '.meshCluster-checkbox', + meshClusterGenerateBoundingCheckbox: '.meshCluster-generateBounding-checkbox', + + meshCompressCheckbox: '.meshCompress-checkbox', + meshCompressEncodeCheckbox: '.meshCompress-encode-checkbox', + meshCompressCompressCheckbox: '.meshCompress-compress-checkbox', + meshCompressQuantizeCheckbox: '.meshCompress-quantize-checkbox', + // lods lodsCheckbox: '.lods-checkbox', lodItems: '.lod-items', @@ -488,292 +483,278 @@ const Elements = { }, }, - meshOptimizer: { + // meshOptimize start + meshOptimize: { ready() { const panel = this; - panel.$.meshOptimizerCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.enable', 'boolean')); - panel.$.meshOptimizerCheckbox.addEventListener('confirm', () => { + panel.$.meshOptimizeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.enable', 'boolean')); + panel.$.meshOptimizeCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimizer, false, 'enable'); + panel.$.meshOptimizeCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'enable'); - updateElementInvalid.call(panel, panel.$.meshOptimizerCheckbox, 'meshOptimizer.enable'); - updateElementReadonly.call(panel, panel.$.meshOptimizerCheckbox); + updateElementInvalid.call(panel, panel.$.meshOptimizeCheckbox, 'meshOptimize.enable'); + updateElementReadonly.call(panel, panel.$.meshOptimizeCheckbox); }, }, - meshOptimizerAlgorithm: { + meshOptimizeVertexCache: { ready() { const panel = this; - panel.$.meshOptimizerAlgorithmSelect.addEventListener('change', (event) => { - panel.setProp.call(panel, 'meshOptimizer.algorithm', 'string', event); - Elements.meshOptimizerAlgorithm.update.call(panel); - }); - panel.$.meshOptimizerAlgorithmSelect.addEventListener('confirm', () => { + panel.$.meshOptimizeVertexCacheCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.vertexCache', 'boolean')); + panel.$.meshOptimizeVertexCacheCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - let optionsHtml = ''; - const types = ['simplify', 'gltfpack']; - types.forEach((type) => { - optionsHtml += ``; - }); - panel.$.meshOptimizerAlgorithmSelect.innerHTML = optionsHtml; - - const defaultValue = 'simplify'; - panel.$.meshOptimizerAlgorithmSelect.value = getPropValue.call(panel, panel.meta.userData.meshOptimizer, defaultValue, 'algorithm'); + panel.$.meshOptimizeVertexCacheCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'vertexCache'); - updateElementInvalid.call(panel, panel.$.meshOptimizerAlgorithmSelect, 'meshOptimizer.algorithm'); - updateElementReadonly.call(panel, panel.$.meshOptimizerAlgorithmSelect); - - if (panel.$.meshOptimizerAlgorithmSelect.value === defaultValue) { - panel.$.meshOptimizerGltfpackOptions.setAttribute('hidden', ''); - panel.$.meshOptimizerSimplifyOptions.removeAttribute('hidden'); - } else { - panel.$.meshOptimizerGltfpackOptions.removeAttribute('hidden'); - panel.$.meshOptimizerSimplifyOptions.setAttribute('hidden', ''); - } - - if (panel.$.meshOptimizerAlgorithmSelect.hasAttribute('invalid')) { - panel.$.meshOptimizerGltfpackOptions.setAttribute('hidden', ''); - panel.$.meshOptimizerSimplifyOptions.setAttribute('hidden', ''); - } + updateElementInvalid.call(panel, panel.$.meshOptimizeVertexCacheCheckbox, 'meshOptimize.vertexCache'); + updateElementReadonly.call(panel, panel.$.meshOptimizeVertexCacheCheckbox); }, }, - // gltfpackOptions start - si: { + meshOptimizeVertexFetch: { ready() { const panel = this; - panel.$.meshOptimizerSISlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.si', 'number')); - panel.$.meshOptimizerSISlider.addEventListener('confirm', () => { + + panel.$.meshOptimizeVertexFetchCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.vertexFetch', 'boolean')); + panel.$.meshOptimizeVertexFetchCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerSISlider.value = getPropValue.call(panel, panel.meta.userData, 1, 'meshOptimizer.gltfpackOptions.si'); + panel.$.meshOptimizeVertexFetchCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'vertexFetch'); - updateElementInvalid.call(panel, panel.$.meshOptimizerSISlider, 'meshOptimizer.gltfpackOptions.si'); - updateElementReadonly.call(panel, panel.$.meshOptimizerSISlider, true); + updateElementInvalid.call(panel, panel.$.meshOptimizeVertexFetchCheckbox, 'meshOptimize.vertexFetch'); + updateElementReadonly.call(panel, panel.$.meshOptimizeVertexFetchCheckbox); }, }, - sa: { + meshOptimizeOverdraw: { ready() { const panel = this; - panel.$.meshOptimizerSACheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.sa', 'boolean')); - panel.$.meshOptimizerSACheckbox.addEventListener('confirm', () => { + + panel.$.meshOptimizeOverdrawCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.overdraw', 'boolean')); + panel.$.meshOptimizeOverdrawCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerSACheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.gltfpackOptions.sa'); + panel.$.meshOptimizeOverdrawCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'overdraw'); - updateElementInvalid.call(panel, panel.$.meshOptimizerSACheckbox, 'meshOptimizer.gltfpackOptions.sa'); - updateElementReadonly.call(panel, panel.$.meshOptimizerSACheckbox, true); + updateElementInvalid.call(panel, panel.$.meshOptimizeOverdrawCheckbox, 'meshOptimize.overdraw'); + updateElementReadonly.call(panel, panel.$.meshOptimizeOverdrawCheckbox); }, }, - kn: { + // meshOptimize end + // meshSimplify start + meshSimplify: { ready() { const panel = this; - panel.$.meshOptimizerKNCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.kn', 'boolean')); - panel.$.meshOptimizerKNCheckbox.addEventListener('confirm', () => { + + panel.$.meshSimplifyCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.enable', 'boolean')); + panel.$.meshSimplifyCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerKNCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.gltfpackOptions.kn'); + panel.$.meshSimplifyCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, false, 'enable'); - updateElementInvalid.call(panel, panel.$.meshOptimizerKNCheckbox, 'meshOptimizer.gltfpackOptions.kn'); - updateElementReadonly.call(panel, panel.$.meshOptimizerKNCheckbox, true); + updateElementInvalid.call(panel, panel.$.meshSimplifyCheckbox, 'meshSimplify.enable'); + updateElementReadonly.call(panel, panel.$.meshSimplifyCheckbox); }, }, - ke: { + meshSimplifyTargetRatio: { ready() { const panel = this; - panel.$.meshOptimizerKECheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.ke', 'boolean')); - panel.$.meshOptimizerKECheckbox.addEventListener('confirm', () => { + panel.$.meshSimplifyTargetRatioSlider.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.targetRatio', 'number')); + panel.$.meshSimplifyTargetRatioSlider.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerKECheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.gltfpackOptions.ke'); + panel.$.meshSimplifyTargetRatioSlider.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, 1, 'targetRatio'); - updateElementInvalid.call(panel, panel.$.meshOptimizerKECheckbox, 'meshOptimizer.gltfpackOptions.ke'); - updateElementReadonly.call(panel, panel.$.meshOptimizerKECheckbox, true); + updateElementInvalid.call(panel, panel.$.meshSimplifyTargetRatioSlider, 'meshSimplify.targetRatio'); + updateElementReadonly.call(panel, panel.$.meshSimplifyTargetRatioSlider); }, }, - noq: { + meshSimplifyAutoErrorRateCheckbox: { ready() { const panel = this; - - panel.$.meshOptimizerNOQCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.noq', 'boolean')); - panel.$.meshOptimizerNOQCheckbox.addEventListener('confirm', () => { + panel.$.meshSimplifyAutoErrorRateCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.autoErrorRate', 'boolean')); + panel.$.meshSimplifyAutoErrorRateCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerNOQCheckbox.value = getPropValue.call(panel, panel.meta.userData, true, 'meshOptimizer.gltfpackOptions.noq'); + panel.$.meshSimplifyAutoErrorRateCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, false, 'autoErrorRate'); - updateElementInvalid.call(panel, panel.$.meshOptimizerNOQCheckbox, 'meshOptimizer.gltfpackOptions.noq'); - updateElementReadonly.call(panel, panel.$.meshOptimizerNOQCheckbox, true); + updateElementInvalid.call(panel, panel.$.meshSimplifyAutoErrorRateCheckbox, 'meshSimplify.autoErrorRate'); + updateElementReadonly.call(panel, panel.$.meshSimplifyAutoErrorRateCheckbox); }, }, - v: { + meshSimplifyErrorRate: { ready() { const panel = this; - panel.$.meshOptimizerVCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.v', 'boolean')); - panel.$.meshOptimizerVCheckbox.addEventListener('confirm', () => { + panel.$.meshSimplifyErrorRateSlider.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.errorRate', 'number')); + panel.$.meshSimplifyErrorRateSlider.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerVCheckbox.value = getPropValue.call(panel, panel.meta.userData, true, 'meshOptimizer.gltfpackOptions.v'); + panel.$.meshSimplifyErrorRateSlider.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, 1, 'errorRate'); - updateElementInvalid.call(panel, panel.$.meshOptimizerVCheckbox, 'meshOptimizer.gltfpackOptions.v'); - updateElementReadonly.call(panel, panel.$.meshOptimizerVCheckbox, true); + updateElementInvalid.call(panel, panel.$.meshSimplifyErrorRateSlider, 'meshSimplify.errorRate'); + updateElementReadonly.call(panel, panel.$.meshSimplifyErrorRateSlider); }, }, - // gltfpackOptions end - // simplifyOptions start - targetRatio: { + meshSimplifyLockBoundaryCheckbox: { ready() { const panel = this; - panel.$.meshOptimizerTargetRatioSlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.targetRatio', 'number')); - panel.$.meshOptimizerTargetRatioSlider.addEventListener('confirm', () => { + panel.$.meshSimplifyLockBoundaryCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.lockBoundary', 'boolean')); + panel.$.meshSimplifyLockBoundaryCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerTargetRatioSlider.value = getPropValue.call(panel, panel.meta.userData, 1, 'meshOptimizer.simplifyOptions.targetRatio'); + panel.$.meshSimplifyLockBoundaryCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, false, 'lockBoundary'); - updateElementInvalid.call(panel, panel.$.meshOptimizerTargetRatioSlider, 'meshOptimizer.simplifyOptions.targetRatio'); - updateElementReadonly.call(panel, panel.$.meshOptimizerTargetRatioSlider); + updateElementInvalid.call(panel, panel.$.meshSimplifyLockBoundaryCheckbox, 'meshSimplify.lockBoundary'); + updateElementReadonly.call(panel, panel.$.meshSimplifyLockBoundaryCheckbox); }, }, - preserveSurfaceCurvature: { + meshClusterCheckbox: { ready() { const panel = this; - panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature', 'boolean')); - panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.addEventListener('confirm', () => { + + panel.$.meshClusterCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCluster.enable', 'boolean')); + panel.$.meshClusterCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature'); + panel.$.meshClusterCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCluster, false, 'enable'); - updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature'); - updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox); + updateElementInvalid.call(panel, panel.$.meshClusterCheckbox, 'meshCluster.enable'); + updateElementReadonly.call(panel, panel.$.meshClusterCheckbox); }, }, - preserveBorderEdges: { + meshClusterGenerateBoundingCheckbox: { ready() { const panel = this; - panel.$.meshOptimizerPreserveBorderEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveBorderEdges', 'boolean')); - panel.$.meshOptimizerPreserveBorderEdgesCheckbox.addEventListener('confirm', () => { + + panel.$.meshClusterGenerateBoundingCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCluster.generateBounding', 'boolean')); + panel.$.meshClusterGenerateBoundingCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerPreserveBorderEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveBorderEdges'); + panel.$.meshClusterGenerateBoundingCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCluster, false, 'generateBounding'); - updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveBorderEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveBorderEdges'); - updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveBorderEdgesCheckbox); + updateElementInvalid.call(panel, panel.$.meshClusterGenerateBoundingCheckbox, 'meshCluster.generateBounding'); + updateElementReadonly.call(panel, panel.$.meshClusterGenerateBoundingCheckbox); }, }, - preserveUVSeamEdges: { + // meshSimplify end + // meshCompress start + meshCompress: { ready() { const panel = this; - panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges', 'boolean')); - panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.addEventListener('confirm', () => { + + panel.$.meshCompressCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.enable', 'boolean')); + panel.$.meshCompressCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges'); + panel.$.meshCompressCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'enable'); - updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges'); - updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox); + updateElementInvalid.call(panel, panel.$.meshCompressCheckbox, 'meshCompress.enable'); + updateElementReadonly.call(panel, panel.$.meshCompressCheckbox); }, }, - preserveUVFoldoverEdges: { + meshCompressEncode: { ready() { const panel = this; - panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges', 'boolean')); - panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.addEventListener('confirm', () => { + + panel.$.meshCompressEncodeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.encode', 'boolean')); + panel.$.meshCompressEncodeCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges'); + panel.$.meshCompressEncodeCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'encode'); - updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges'); - updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox); + updateElementInvalid.call(panel, panel.$.meshCompressEncodeCheckbox, 'meshCompress.encode'); + updateElementReadonly.call(panel, panel.$.meshCompressEncodeCheckbox); }, }, - agressiveness: { + meshCompressCompress: { ready() { const panel = this; - panel.$.meshOptimizerAgressivenessSlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.agressiveness', 'number')); - panel.$.meshOptimizerAgressivenessSlider.addEventListener('confirm', () => { + + panel.$.meshCompressCompressCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.compress', 'boolean')); + panel.$.meshCompressCompressCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerAgressivenessSlider.value = getPropValue.call(panel, panel.meta.userData, 7, 'meshOptimizer.simplifyOptions.agressiveness'); + panel.$.meshCompressCompressCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'compress'); - updateElementInvalid.call(panel, panel.$.meshOptimizerAgressivenessSlider, 'meshOptimizer.simplifyOptions.agressiveness'); - updateElementReadonly.call(panel, panel.$.meshOptimizerAgressivenessSlider); + updateElementInvalid.call(panel, panel.$.meshCompressCompressCheckbox, 'meshCompress.compress'); + updateElementReadonly.call(panel, panel.$.meshCompressCompressCheckbox); }, }, - maxIterationCount: { + meshCompressQuantize: { ready() { const panel = this; - panel.$.meshOptimizerMaxIterationCountSlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.maxIterationCount', 'number')); - panel.$.meshOptimizerMaxIterationCountSlider.addEventListener('confirm', () => { + + panel.$.meshCompressQuantizeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.quantize', 'boolean')); + panel.$.meshCompressQuantizeCheckbox.addEventListener('confirm', () => { panel.dispatch('snapshot'); }); }, update() { const panel = this; - panel.$.meshOptimizerMaxIterationCountSlider.value = getPropValue.call(panel, panel.meta.userData, 100, 'meshOptimizer.simplifyOptions.maxIterationCount'); + panel.$.meshCompressQuantizeCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'quantize'); - updateElementInvalid.call(panel, panel.$.meshOptimizerMaxIterationCountSlider, 'meshOptimizer.simplifyOptions.maxIterationCount'); - updateElementReadonly.call(panel, panel.$.meshOptimizerMaxIterationCountSlider); + updateElementInvalid.call(panel, panel.$.meshCompressQuantizeCheckbox, 'meshCompress.quantize'); + updateElementReadonly.call(panel, panel.$.meshCompressQuantizeCheckbox); }, }, - // simplifyOptions end + // meshCompress end // lods start lods: { ready() { @@ -1003,18 +984,18 @@ function getLodItemHTML(lodOptions, LODTriangleCounts, hasBuiltinLOD = false) {
LOD ${index}
-
+
Face count(%) + ${hasBuiltinLOD ? 'disabled' : ''}>
${LODTriangleCounts[index] || 0} Triangles
-
+
diff --git a/licenses/LICENSE_meshoptimizer.md b/licenses/LICENSE_meshoptimizer.md new file mode 100644 index 00000000000..962ed41ffbe --- /dev/null +++ b/licenses/LICENSE_meshoptimizer.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016-2023 Arseny Kapoulkine + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/native/cocos/3d/assets/Mesh.cpp b/native/cocos/3d/assets/Mesh.cpp index e0b2034f89c..615a06b3aa9 100644 --- a/native/cocos/3d/assets/Mesh.cpp +++ b/native/cocos/3d/assets/Mesh.cpp @@ -26,6 +26,7 @@ #include "3d/assets/Morph.h" #include "3d/assets/Skeleton.h" #include "3d/misc/BufferBlob.h" +#include "3d/misc/CreateMesh.h" #include "base/std/hash/hash.h" #include "core/DataView.h" #include "core/assets/RenderingSubMesh.h" @@ -102,7 +103,13 @@ DataReaderCallback getReader(const DataView &dataView, gfx::Format format) { break; } case gfx::FormatType::FLOAT: { - return [&](uint32_t offset) -> TypedArrayElementType { return dataView.getFloat32(offset); }; + switch (stride) { + case 2: return [&](uint32_t offset) -> TypedArrayElementType { return dataView.getUint16(offset); }; + case 4: return [&](uint32_t offset) -> TypedArrayElementType { return dataView.getFloat32(offset); }; + default: + break; + } + break; } default: break; @@ -159,7 +166,13 @@ DataWritterCallback getWriter(DataView &dataView, gfx::Format format) { break; } case gfx::FormatType::FLOAT: { - return [&](uint32_t offset, const TypedArrayElementType &value) { dataView.setFloat32(offset, ccstd::get(value)); }; + switch (stride) { + case 2: return [&](uint32_t offset, const TypedArrayElementType &value) { dataView.setUint16(offset, ccstd::get(value)); }; + case 4: return [&](uint32_t offset, const TypedArrayElementType &value) { dataView.setFloat32(offset, ccstd::get(value)); }; + default: + break; + } + break; } default: break; @@ -293,6 +306,15 @@ void Mesh::initialize() { _initialized = true; + if (_struct.compressed) { + // decompress + MeshUtils::inflateMesh(_struct, _data); + } + if (_struct.encoded) { + // decode + MeshUtils::decodeMesh(_struct, _data); + } + if (_struct.dynamic.has_value()) { auto *device = gfx::Device::getInstance(); gfx::BufferList vertexBuffers; @@ -1301,7 +1323,13 @@ TypedArray Mesh::createTypedArrayWithGFXFormat(gfx::Format format, uint32_t coun break; } case gfx::FormatType::FLOAT: { - return Float32Array(count); + switch (stride) { + case 2: return Uint16Array(count); + case 4: return Float32Array(count); + default: + break; + } + break; } default: break; diff --git a/native/cocos/3d/assets/Mesh.h b/native/cocos/3d/assets/Mesh.h index 8f7c37fd529..0eac30df259 100644 --- a/native/cocos/3d/assets/Mesh.h +++ b/native/cocos/3d/assets/Mesh.h @@ -196,6 +196,12 @@ class Mesh : public Asset { * @zh 动态网格特有数据 */ ccstd::optional dynamic; + + ccstd::optional encoded; + + ccstd::optional compressed; + + ccstd::optional quantized; }; struct ICreateInfo { diff --git a/native/cocos/3d/misc/CreateMesh.cpp b/native/cocos/3d/misc/CreateMesh.cpp index fa3ee334b69..e479a23d33d 100644 --- a/native/cocos/3d/misc/CreateMesh.cpp +++ b/native/cocos/3d/misc/CreateMesh.cpp @@ -23,12 +23,14 @@ ****************************************************************************/ #include "3d/misc/CreateMesh.h" +#include #include #include "3d/misc/Buffer.h" #include "3d/misc/BufferBlob.h" #include "core/ArrayBuffer.h" #include "core/DataView.h" #include "core/assets/RenderingSubMesh.h" +#include "meshopt/meshoptimizer.h" #include "renderer/gfx-base/GFXDef-common.h" namespace cc { @@ -404,4 +406,70 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome return createInfo; } +void MeshUtils::inflateMesh(const Mesh::IStruct &structInfo, Uint8Array &data) { + uLongf uncompressedSize = 0U; + for (const auto &prim : structInfo.primitives) { + uncompressedSize += prim.indexView->length; + } + for (const auto &vb : structInfo.vertexBundles) { + uncompressedSize += vb.view.length; + } + auto uncompressedData = Uint8Array(static_cast(uncompressedSize)); + auto res = uncompress(uncompressedData.buffer()->getData(), &uncompressedSize, data.buffer()->getData(), data.byteLength()); + data = uncompressedData; +} + +void MeshUtils::decodeMesh(Mesh::IStruct &structInfo, Uint8Array &data) { + BufferBlob bufferBlob; + + for (auto &bundle : structInfo.vertexBundles) { + auto &view = bundle.view; + auto bound = view.count * view.stride; + auto *buffer = ccnew ArrayBuffer(bound); + auto vertex = Uint8Array(data.buffer(), view.offset, view.length); + int res = meshopt_decodeVertexBuffer(buffer->getData(), view.count, view.stride, vertex.buffer()->getData() + vertex.byteOffset(), view.length); + if (res < 0) { + assert(false && "failed to decode vertex buffer"); + } + + bufferBlob.setNextAlignment(view.stride); + Mesh::IVertexBundle vertexBundle; + Mesh::IBufferView buffferView; + buffferView.offset = bufferBlob.getLength(); + buffferView.length = bound; + buffferView.count = view.count; + buffferView.stride = view.stride; + bufferBlob.addBuffer(buffer); + + bundle.view = buffferView; + } + + for (auto &primitive : structInfo.primitives) { + if (!primitive.indexView.has_value()) { + continue; + } + + auto view = *primitive.indexView; + auto bound = view.count * view.stride; + auto *buffer = ccnew ArrayBuffer(bound); + auto index = DataView(data.buffer(), view.offset, view.length); + int res = meshopt_decodeIndexBuffer(buffer->getData(), view.count, view.stride, index.buffer()->getData() + index.byteOffset(), view.length); + if (res < 0) { + assert(false && "failed to decode index buffer"); + } + + bufferBlob.setNextAlignment(view.stride); + Mesh::IBufferView buffferView; + buffferView.offset = bufferBlob.getLength(); + buffferView.length = bound; + buffferView.count = view.count; + buffferView.stride = view.stride; + bufferBlob.addBuffer(buffer); + + primitive.indexView = buffferView; + } + + data = Uint8Array(bufferBlob.getCombined()); +} + } // namespace cc diff --git a/native/cocos/3d/misc/CreateMesh.h b/native/cocos/3d/misc/CreateMesh.h index b87be8ad19f..84f1272168e 100644 --- a/native/cocos/3d/misc/CreateMesh.h +++ b/native/cocos/3d/misc/CreateMesh.h @@ -87,6 +87,13 @@ class MeshUtils { * @zh 创建一个动态网格ICreateInfo。 */ static Mesh::ICreateInfo createDynamicMeshInfo(const IDynamicGeometry &geometry, const ICreateDynamicMeshOptions &options = {}); + + /** + * + */ + static void inflateMesh(const Mesh::IStruct &structInfo, Uint8Array &data); + + static void decodeMesh(Mesh::IStruct &structInfo, Uint8Array &data); }; } // namespace cc diff --git a/native/cocos/core/assets/RenderingSubMesh.cpp b/native/cocos/core/assets/RenderingSubMesh.cpp index 363414194ca..de744d7d09a 100644 --- a/native/cocos/core/assets/RenderingSubMesh.cpp +++ b/native/cocos/core/assets/RenderingSubMesh.cpp @@ -28,6 +28,7 @@ #include "3d/misc/Buffer.h" #include "core/DataView.h" #include "core/TypedArray.h" +#include "math/Utils.h" #include "math/Vec3.h" #include "renderer/gfx-base/GFXBuffer.h" #include "renderer/gfx-base/GFXDevice.h" @@ -91,59 +92,118 @@ const IGeometricInfo &RenderingSubMesh::getGeometricInfo() { return EMPTY_GEOMETRIC_INFO; } - auto index = static_cast(_subMeshIdx.value()); + auto iter = std::find_if(_attributes.cbegin(), _attributes.cend(), [](const gfx::Attribute &element) -> bool { + return element.name == gfx::ATTR_NAME_POSITION; + }); + if (iter != _attributes.end()) { + return EMPTY_GEOMETRIC_INFO; + } + + const auto &attri = *iter; + const uint32_t count = gfx::GFX_FORMAT_INFOS[static_cast(attri.format)].count; + auto index = static_cast(_subMeshIdx.value()); const auto &positionsVar = _mesh->readAttribute(index, gfx::ATTR_NAME_POSITION); - const auto *pPositions = ccstd::get_if(&positionsVar); - if (pPositions != nullptr) { - const auto &positions = *pPositions; - const auto &indicesVar = _mesh->readIndices(index); - - Vec3 max; - Vec3 min; - - auto iter = std::find_if(_attributes.cbegin(), _attributes.cend(), [](const gfx::Attribute &element) -> bool { - return element.name == gfx::ATTR_NAME_POSITION; - }); - if (iter != _attributes.cend()) { - const auto &attri = *iter; - const uint32_t count = gfx::GFX_FORMAT_INFOS[static_cast(attri.format)].count; - if (count == 2) { - max.set(positions[0], positions[1], 0); - min.set(positions[0], positions[1], 0); - } else { - max.set(positions[0], positions[1], positions[2]); - min.set(positions[0], positions[1], positions[2]); - } - for (int i = 0; i < positions.length(); i += static_cast(count)) { - if (count == 2) { - max.x = positions[i] > max.x ? positions[i] : max.x; - max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; - min.x = positions[i] < min.x ? positions[i] : min.x; - min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; - } else { - max.x = positions[i] > max.x ? positions[i] : max.x; - max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; - max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z; - min.x = positions[i] < min.x ? positions[i] : min.x; - min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; - min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z; - } + Float32Array const *pPositions = nullptr; + switch (attri.format) { + case gfx::Format::RG32F: + case gfx::Format::RGB32F: { + pPositions = ccstd::get_if(&positionsVar); + if (pPositions == nullptr) { + return EMPTY_GEOMETRIC_INFO; + } + break; + } + case gfx::Format::RGBA32F: { + const auto *data = ccstd::get_if(&positionsVar); + if (data == nullptr) { + return EMPTY_GEOMETRIC_INFO; + } + const auto count = data->length() / 4; + auto *pos = ccnew Float32Array(count * 3); + for (uint32_t i = 0; i < count; i++) { + const auto dstPtr = i * 3; + const auto srcPtr = i * 4; + (*pos)[dstPtr] = (*data)[srcPtr]; + (*pos)[dstPtr + 1] = (*data)[srcPtr + 1]; + (*pos)[dstPtr + 2] = (*data)[srcPtr + 2]; + } + pPositions = pos; + break; + } + case gfx::Format::RG16F: + case gfx::Format::RGB16F: { + const auto *data = ccstd::get_if(&positionsVar); + if (data == nullptr) { + return EMPTY_GEOMETRIC_INFO; } + auto *pos = ccnew Float32Array(data->length()); + for (uint32_t i = 0; i < data->length(); ++i) { + (*pos)[i] = mathutils::halfToFloat((*data)[i]); + } + pPositions = pos; + break; + } + case gfx::Format::RGBA16F: { + const auto *data = ccstd::get_if(&positionsVar); + if (data == nullptr) { + return EMPTY_GEOMETRIC_INFO; + } + const auto count = data->length() / 4; + auto *pos = ccnew Float32Array(count * 3); + for (uint32_t i = 0; i < count; i++) { + const auto dstPtr = i * 3; + const auto srcPtr = i * 4; + (*pos)[dstPtr] = mathutils::halfToFloat((*data)[srcPtr]); + (*pos)[dstPtr + 1] = mathutils::halfToFloat((*data)[srcPtr + 1]); + (*pos)[dstPtr + 2] = mathutils::halfToFloat((*data)[srcPtr + 2]); + } + pPositions = pos; + break; + } + default: + return EMPTY_GEOMETRIC_INFO; + }; - IGeometricInfo info; - info.positions = positions; - info.indices = indicesVar; - info.boundingBox.max = max; - info.boundingBox.min = min; + const auto &positions = *pPositions; + const auto &indicesVar = _mesh->readIndices(index); - _geometricInfo = info; - return _geometricInfo.value(); + Vec3 max; + Vec3 min; + + if (count == 2) { + max.set(positions[0], positions[1], 0); + min.set(positions[0], positions[1], 0); + } else { + max.set(positions[0], positions[1], positions[2]); + min.set(positions[0], positions[1], positions[2]); + } + + for (int i = 0; i < positions.length(); i += static_cast(count)) { + if (count == 2) { + max.x = positions[i] > max.x ? positions[i] : max.x; + max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; + min.x = positions[i] < min.x ? positions[i] : min.x; + min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; + } else { + max.x = positions[i] > max.x ? positions[i] : max.x; + max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; + max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z; + min.x = positions[i] < min.x ? positions[i] : min.x; + min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y; + min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z; } } - return EMPTY_GEOMETRIC_INFO; + IGeometricInfo info; + info.positions = positions; + info.indices = indicesVar; + info.boundingBox.max = max; + info.boundingBox.min = min; + + _geometricInfo = info; + return _geometricInfo.value(); } void RenderingSubMesh::genFlatBuffers() { diff --git a/native/cocos/math/Utils.cpp b/native/cocos/math/Utils.cpp index f15622a569b..5fdb01b56a3 100644 --- a/native/cocos/math/Utils.cpp +++ b/native/cocos/math/Utils.cpp @@ -50,6 +50,63 @@ float maxComponent(const Vec3 &v) { return std::max(std::max(v.x, v.y), v.z); } +uint16_t floatToHalf(float fval) { + union { + float f; + unsigned int ui; + } u = {fval}; + unsigned int ui = u.ui; + + int s = (ui >> 16) & 0x8000; // NOLINT + int em = ui & 0x7fffffff; // NOLINT + + /* bias exponent and round to nearest; 112 is relative exponent bias (127-15) */ + int h = (em - (112 << 23) + (1 << 12)) >> 13; + + /* underflow: flush to zero; 113 encodes exponent -14 */ + h = (em < (113 << 23)) ? 0 : h; + + /* overflow: infinity; 143 encodes exponent 16 */ + h = (em >= (143 << 23)) ? 0x7c00 : h; + + /* NaN; note that we convert all types of NaN to qNaN */ + h = (em > (255 << 23)) ? 0x7e00 : h; + + return static_cast(s | h); +} + +float halfToFloat(uint16_t hval) { + union { + float f; + unsigned int ui; + } u; + + int s = (hval >> 15) & 0x00000001; + int em = hval & 0x00007fff; + int m = 0; + + if (em > 0) { + /* normalized */ + if (em > 30 << 10) { + /* overflow: infinity */ + em = 255 << 23; + } else { + em = (em + (112 << 10)) << 13; + } + } else { + /* denormalized */ + if (em > 25 << 10) { + /* underflow: flush to zero */ + em = 0; + } else { + em = (em + (113 << 10)) >> 1; + } + } + + u.ui = ((uint16_t)(s << 31)) | em | m; // NOLINT + return u.f; +} + } // namespace mathutils } // namespace cc diff --git a/native/cocos/math/Utils.h b/native/cocos/math/Utils.h index 909fd30f6eb..0e33763be6b 100644 --- a/native/cocos/math/Utils.h +++ b/native/cocos/math/Utils.h @@ -284,5 +284,9 @@ auto absMax(F a, F b) { return std::fabs(a) > std::fabs(b) ? a : b; } +uint16_t floatToHalf(float fval); + +float halfToFloat(uint16_t hval); + } // namespace mathutils } // namespace cc diff --git a/native/external-config.json b/native/external-config.json index 72909dbc542..9b92430ee9a 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-11" + "checkout": "v3.8.1-12" } -} +} \ No newline at end of file diff --git a/native/tests/unit-test/src/math_utils_test.cpp b/native/tests/unit-test/src/math_utils_test.cpp index db5cff1ca40..7f08b4381ce 100644 --- a/native/tests/unit-test/src/math_utils_test.cpp +++ b/native/tests/unit-test/src/math_utils_test.cpp @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include +#include #include #include "cocos/math/Math.h" #include "cocos/math/MathUtil.h" diff --git a/platforms/native/engine/jsb-physics.js b/platforms/native/engine/jsb-physics.js index 8b92d375ea9..89a488659c1 100644 --- a/platforms/native/engine/jsb-physics.js +++ b/platforms/native/engine/jsb-physics.js @@ -675,7 +675,7 @@ class PlaneShape extends Shape { function getConvexMesh (v) { if (!jsbPhy.CACHE.convex[v._uuid]) { - const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position')); + const posArr = cc.physics.utils.shrinkPositions(v.renderingSubMeshes[0].geometricInfo.positions); const world = cc.PhysicsSystem.instance.physicsWorld.impl; const convex = { positions: new Float32Array(posArr), positionLength: posArr.length / 3 }; jsbPhy.CACHE.convex[v._uuid] = world.createConvex(convex); @@ -685,9 +685,8 @@ function getConvexMesh (v) { function getTriangleMesh (v) { if (!jsbPhy.CACHE.trimesh[v._uuid]) { - const indArr = v.readIndices(0); - // const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position')); - const posArr = v.readAttribute(0, 'a_position'); + const posArr = v.renderingSubMeshes[0].geometricInfo.positions; + const indArr = v.renderingSubMeshes[0].geometricInfo.indices; const world = cc.PhysicsSystem.instance.physicsWorld.impl; const trimesh = { positions: new Float32Array(posArr), diff --git a/tests/init.ts b/tests/init.ts index 4e43708972d..cf8e31fe718 100644 --- a/tests/init.ts +++ b/tests/init.ts @@ -109,6 +109,14 @@ jest.mock( ); }); +jest.mock('external:emscripten/meshopt/meshopt_decoder.wasm.js', + () => ({ + __esModule: true, + default: function factory () { return Promise.resolve({}); }, + }), + { virtual: true, }, +); + jest.mock( 'external:emscripten/physx/physx.release.asm.js', () => jest.requireActual('../native/external/emscripten/physx/physx.release.asm.js'), @@ -122,6 +130,12 @@ jest.mock( { virtual: true }, ); +jest.mock( + 'external:emscripten/meshopt/meshopt_decoder.asm.js', + () => jest.requireActual('../native/external/emscripten/meshopt/meshopt_decoder.asm.js'), + { virtual: true }, +); + jest.mock( 'external:emscripten/spine/spine.asm.js', () => jest.requireActual('../native/external/emscripten/spine/spine.asm.js'), diff --git a/tsconfig.json b/tsconfig.json index be0012eabd6..a5c25c11c69 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -36,6 +36,7 @@ "./native/external/emscripten/physx/physx", "./native/external/emscripten/webgpu/webgpu", "./native/external/emscripten/spine/spine", + "./native/external/emscripten/meshopt/meshopt_decoder", "./native/external/emscripten/box2d/box2d", // pal From 63668b2a10db6b9db2803a92efcba9a35e5bd797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Mon, 21 Aug 2023 10:48:32 +0800 Subject: [PATCH 199/232] remember connected gamepad count (#16023) --- pal/input/web/gamepad-input.ts | 92 +++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 34 deletions(-) diff --git a/pal/input/web/gamepad-input.ts b/pal/input/web/gamepad-input.ts index 2b6f6561ccb..7d20b9df2b2 100644 --- a/pal/input/web/gamepad-input.ts +++ b/pal/input/web/gamepad-input.ts @@ -72,6 +72,8 @@ type WebGamepad = Gamepad; const XRLeftHandedness = 'left'; const XRRightHandedness = 'right'; +const devicesTmp: GamepadInputDevice[] = []; + enum Pose { HAND_LEFT = 1, HAND_RIGHT = 4, @@ -85,7 +87,7 @@ interface IPoseValue { } interface IPoseInfo { - readonly code: number; + readonly code: Pose; readonly position: DOMPointReadOnly; readonly orientation: DOMPointReadOnly; } @@ -184,7 +186,7 @@ export class GamepadInputDevice { [Pose.HAND_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, [Pose.AIM_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, [Pose.AIM_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - } + }; constructor (deviceId: number) { this._deviceId = deviceId; @@ -216,7 +218,7 @@ export class GamepadInputDevice { js.array.fastRemoveAt(GamepadInputDevice.all, removeIndex); } private static _getOrCreateInputDevice (id: number, connected: boolean): GamepadInputDevice { - let device = GamepadInputDevice.all.find((device) => device.deviceId === id); + let device = GamepadInputDevice.all.find((device) => device.deviceId === id); if (!device) { device = new GamepadInputDevice(id); GamepadInputDevice.all.push(device); @@ -225,29 +227,36 @@ export class GamepadInputDevice { return device; } - private static _ensureDirectorDefined (): Promise { - return new Promise((resolve) => { - GamepadInputDevice._intervalId = setInterval(() => { - if (legacyCC.director && legacyCC.Director) { - clearInterval(GamepadInputDevice._intervalId); - GamepadInputDevice._intervalId = -1; - resolve(); - } - }, 50); - }); + private static _ensureDirectorDefined (callback: () => void): void { + GamepadInputDevice._intervalId = setInterval(() => { + if (legacyCC.director && legacyCC.Director) { + clearInterval(GamepadInputDevice._intervalId); + GamepadInputDevice._intervalId = -1; + callback(); + } + }, 50); + } + + private static _totalGamepadCnt = 0; + private static _updateGamepadCnt (): void { + GamepadInputDevice._totalGamepadCnt = GamepadInputDevice._cachedWebGamepads.reduce((total, gamepad) => (gamepad ? total + 1 : total), 0); } private static _registerEvent (): void { - GamepadInputDevice._ensureDirectorDefined().then(() => { + GamepadInputDevice._ensureDirectorDefined(() => { + GamepadInputDevice._cachedWebGamepads = GamepadInputDevice._getWebGamePads(); + GamepadInputDevice._updateGamepadCnt(); legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, GamepadInputDevice._scanGamepads); - }).catch((e) => {}); + }); window.addEventListener('gamepadconnected', (e) => { GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = e.gamepad; + GamepadInputDevice._updateGamepadCnt(); const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, true); GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); }); window.addEventListener('gamepaddisconnected', (e) => { GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = null; + GamepadInputDevice._updateGamepadCnt(); const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, false); GamepadInputDevice._removeInputDevice(e.gamepad.index); GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); @@ -255,12 +264,15 @@ export class GamepadInputDevice { } private static _scanWebGamepads (devices: GamepadInputDevice[]): void { + const allDisconnected = GamepadInputDevice._totalGamepadCnt === 0; + if (allDisconnected) return; + const webGamepads = GamepadInputDevice._getWebGamePads(); if (!webGamepads) { return; } for (let i = 0; i < webGamepads.length; ++i) { - const webGamepad = webGamepads?.[i]; + const webGamepad = webGamepads[i]; if (!webGamepad) { continue; } @@ -302,12 +314,12 @@ export class GamepadInputDevice { } private static _scanGamepads (): void { - const devices: GamepadInputDevice[] = []; - GamepadInputDevice._scanWebGamepads(devices); - GamepadInputDevice._scanWebXRGamepads(devices); + devicesTmp.length = 0; + GamepadInputDevice._scanWebGamepads(devicesTmp); + GamepadInputDevice._scanWebXRGamepads(devicesTmp); // emit event - for (let i = 0; i < devices.length; ++i) { - const device = devices[i]; + for (let i = 0; i < devicesTmp.length; ++i) { + const device = devicesTmp[i]; GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device)); } GamepadInputDevice._scanWebXRGamepadsPose(); @@ -320,8 +332,10 @@ export class GamepadInputDevice { GamepadInputDevice._cachedWebXRGamepadMap = null; if (GamepadInputDevice.xr && GamepadInputDevice.xr._connected) { GamepadInputDevice.xr._connected = false; - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, - new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr)); + GamepadInputDevice._eventTarget.emit( + InputEventType.GAMEPAD_CHANGE, + new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr), + ); devices.push(GamepadInputDevice.xr); } return; @@ -337,20 +351,28 @@ export class GamepadInputDevice { if (!left && !right) { if (GamepadInputDevice.xr._connected) { GamepadInputDevice.xr._connected = false; - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, - new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr)); + GamepadInputDevice._eventTarget.emit( + InputEventType.GAMEPAD_CHANGE, + new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr), + ); } } else if (!GamepadInputDevice.xr._connected) { GamepadInputDevice.xr._connected = true; - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, - new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr)); + GamepadInputDevice._eventTarget.emit( + InputEventType.GAMEPAD_CHANGE, + new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr), + ); } - if (GamepadInputDevice.checkGamepadChanged(left, - GamepadInputDevice._cachedWebXRGamepadMap?.get(XRLeftHandedness))) { + if (GamepadInputDevice.checkGamepadChanged( + left, + GamepadInputDevice._cachedWebXRGamepadMap?.get(XRLeftHandedness), + )) { devices.push(GamepadInputDevice.xr); - } else if (GamepadInputDevice.checkGamepadChanged(right, - GamepadInputDevice._cachedWebXRGamepadMap?.get(XRRightHandedness))) { + } else if (GamepadInputDevice.checkGamepadChanged( + right, + GamepadInputDevice._cachedWebXRGamepadMap?.get(XRRightHandedness), + )) { devices.push(GamepadInputDevice.xr); } @@ -417,8 +439,10 @@ export class GamepadInputDevice { const info = infoList[i]; GamepadInputDevice.xr._updateWebPoseState(info); } - GamepadInputDevice._eventTarget.emit(InputEventType.HANDLE_POSE_INPUT, - new EventGamepad(InputEventType.HANDLE_POSE_INPUT, GamepadInputDevice.xr)); + GamepadInputDevice._eventTarget.emit( + InputEventType.HANDLE_POSE_INPUT, + new EventGamepad(InputEventType.HANDLE_POSE_INPUT, GamepadInputDevice.xr), + ); } private static _getWebXRGamepadMap (): (Map | undefined) { @@ -459,7 +483,7 @@ export class GamepadInputDevice { private _updateWebPoseState (info: IPoseInfo): void { if (info.code !== Pose.HAND_LEFT && info.code !== Pose.AIM_LEFT - && info.code !== Pose.HAND_RIGHT && info.code !== Pose.AIM_RIGHT) { + && info.code !== Pose.HAND_RIGHT && info.code !== Pose.AIM_RIGHT) { return; } From cfd5dc998b8040184ce7582bedfde02da42fdb91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Mon, 21 Aug 2023 10:59:03 +0800 Subject: [PATCH 200/232] add message protocol manager for node editing (#15963) * add message protocol manager * optimize switch message protocol when editing node * add optimize * again --- .../components/batched-skinning-model.js | 10 +- .../components/light-probe-group-footer.js | 17 +-- .../inspector/components/lod-group/index.js | 18 +-- .../components/lod-group/lod-item.js | 3 +- .../components/lod-group/multi-lod-group.js | 3 +- .../components/particle-system-2d.js | 4 +- .../inspector/components/particle-system.js | 10 +- .../inspector/components/polygon-collider.js | 10 +- editor/inspector/components/terrain.js | 9 +- editor/inspector/contributions/node.js | 132 ++++++++++++------ editor/inspector/utils/prop.js | 26 ++++ 11 files changed, 157 insertions(+), 85 deletions(-) diff --git a/editor/inspector/components/batched-skinning-model.js b/editor/inspector/components/batched-skinning-model.js index 6067c7d1448..ef0ad382a07 100644 --- a/editor/inspector/components/batched-skinning-model.js +++ b/editor/inspector/components/batched-skinning-model.js @@ -1,5 +1,7 @@ const { template, $, update, close } = require('./base'); +const { getMessageProtocolScene } = require('../utils/prop'); + exports.template = template; exports.$ = $; exports.update = update; @@ -22,9 +24,9 @@ exports.ready = function() { $button.addEventListener('confirm', async () => { const uuids = this.dump.value.uuid.values || [this.dump.value.uuid.value]; - const undoID = await Editor.Message.request('scene', 'begin-recording', uuids); + const undoID = await Editor.Message.request(getMessageProtocolScene(this.$this), 'begin-recording', uuids); for (const uuid of uuids) { - await Editor.Message.request('scene', 'execute-component-method', { + await Editor.Message.request(getMessageProtocolScene(this.$this), 'execute-component-method', { uuid: uuid, name: 'cook', args: [], @@ -32,12 +34,12 @@ exports.ready = function() { } for (const uuid of uuids) { - await Editor.Message.request('scene', 'execute-component-method', { + await Editor.Message.request(getMessageProtocolScene(this.$this), 'execute-component-method', { uuid: uuid, name: 'combine', args: [], }); } - await Editor.Message.request('scene', 'end-recording', undoID); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'end-recording', undoID); }); }; diff --git a/editor/inspector/components/light-probe-group-footer.js b/editor/inspector/components/light-probe-group-footer.js index 6ebcc7e25de..a7947207448 100644 --- a/editor/inspector/components/light-probe-group-footer.js +++ b/editor/inspector/components/light-probe-group-footer.js @@ -1,4 +1,5 @@ const { trackEventWithTimer } = require('../utils/metrics'); +const { getMessageProtocolScene } = require('../utils/prop'); exports.template = `
@@ -41,10 +42,10 @@ exports.update = async function(dump) { panel.dump = dump; } - const mode = await Editor.Message.request('scene', 'query-light-probe-edit-mode'); + const mode = await Editor.Message.request(getMessageProtocolScene(this.$this), 'query-light-probe-edit-mode'); panel.changeProbeMode(mode); - const boxMode = await Editor.Message.request('scene', 'query-light-probe-bounding-box-edit-mode'); + const boxMode = await Editor.Message.request(getMessageProtocolScene(this.$this), 'query-light-probe-bounding-box-edit-mode'); panel.changeProbeBoxMode(boxMode); }; @@ -61,14 +62,14 @@ exports.ready = function() { if (result.response === 0) { // 先关闭盒子模式 if (panel.sceneProbeBoxMode) { - await Editor.Message.request('scene', 'toggle-light-probe-bounding-box-edit-mode', !panel.sceneProbeBoxMode); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'toggle-light-probe-bounding-box-edit-mode', !panel.sceneProbeBoxMode); } const uuidObject = panel.dump.value.uuid; const uuids = uuidObject.values ? uuidObject.values : [uuidObject.value]; - const undoID = await Editor.Message.request('scene', 'begin-recording', uuids); + const undoID = await Editor.Message.request(getMessageProtocolScene(this.$this), 'begin-recording', uuids); for (const uuid of uuids) { - Editor.Message.send('scene', 'execute-component-method', { + Editor.Message.send(getMessageProtocolScene(this.$this), 'execute-component-method', { uuid: uuid, name: 'generateLightProbes', args: [], @@ -77,12 +78,12 @@ exports.ready = function() { trackEventWithTimer('bakingSystem', 'A100006'); - await Editor.Message.request('scene', 'end-recording', undoID); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'end-recording', undoID); } }); panel.$.edit.addEventListener('confirm', async () => { - await Editor.Message.request('scene', 'toggle-light-probe-edit-mode', !panel.sceneProbeMode); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'toggle-light-probe-edit-mode', !panel.sceneProbeMode); trackEventWithTimer('bakingSystem', 'A100008'); }); @@ -90,7 +91,7 @@ exports.ready = function() { Editor.Message.addBroadcastListener('scene:light-probe-edit-mode-changed', panel.changeProbeModeBind); panel.$.box.addEventListener('confirm', async () => { - await Editor.Message.request('scene', 'toggle-light-probe-bounding-box-edit-mode', !panel.sceneProbeBoxMode); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'toggle-light-probe-bounding-box-edit-mode', !panel.sceneProbeBoxMode); trackEventWithTimer('bakingSystem', 'A100007'); }); diff --git a/editor/inspector/components/lod-group/index.js b/editor/inspector/components/lod-group/index.js index 3fab395def8..ae9aea727aa 100644 --- a/editor/inspector/components/lod-group/index.js +++ b/editor/inspector/components/lod-group/index.js @@ -5,6 +5,7 @@ const { join } = require('path'); const lodItem = require('./lod-item'); const multiLodGroup = require('./multi-lod-group'); const { trackEventWithTimer } = require('../../utils/metrics'); +const { getMessageProtocolScene } = require('../../utils/prop'); module.paths.push(join(Editor.App.path, 'node_modules')); const Vue = require('vue/dist/vue.min.js'); @@ -236,7 +237,7 @@ exports.ready = function() { }, recalculateBounds() { const that = this; - Editor.Message.send('scene', 'execute-component-method', { + Editor.Message.send(getMessageProtocolScene(that.$el), 'execute-component-method', { uuid: that.dump.value.uuid.value, name: 'recalculateBounds', args: [], @@ -245,7 +246,7 @@ exports.ready = function() { }, resetObjectSize() { const that = this; - Editor.Message.send('scene', 'execute-component-method', { + Editor.Message.send(getMessageProtocolScene(that.$el), 'execute-component-method', { uuid: that.dump.value.uuid.value, name: 'resetObjectSize', args: [], @@ -264,21 +265,20 @@ exports.ready = function() { } const preValue = LODs[index].value.screenUsagePercentage.value; const nextValue = LODs[index + 1] ? LODs[index + 1].value.screenUsagePercentage.value : 0; - const undoID = await Editor.Message.request('scene', 'begin-recording', uuid); - await Editor.Message.request('scene', 'lod-insert', uuid, index + 1, (preValue + nextValue) / 2, null); - await Editor.Message.request('scene', 'end-recording', undoID); + const undoID = await Editor.Message.request(getMessageProtocolScene(that.$el), 'begin-recording', uuid); + await Editor.Message.request(getMessageProtocolScene(that.$el), 'lod-insert', uuid, index + 1, (preValue + nextValue) / 2, null); + await Editor.Message.request(getMessageProtocolScene(that.$el), 'end-recording', undoID); trackEventWithTimer('LOD', 'A100005'); } else if (operator === 'delete') { if (LODs.length === 1) { console.warn('At least one LOD, Can\'t delete any more'); return; } - const undoID = await Editor.Message.request('scene', 'begin-recording', uuid); - await Editor.Message.request('scene', 'lod-erase', uuid, index); - await Editor.Message.request('scene', 'end-recording', undoID); + const undoID = await Editor.Message.request(getMessageProtocolScene(that.$el), 'begin-recording', uuid); + await Editor.Message.request(getMessageProtocolScene(that.$el), 'lod-erase', uuid, index); + await Editor.Message.request(getMessageProtocolScene(that.$el), 'end-recording', undoID); trackEventWithTimer('LOD', 'A100006'); } - // Editor.Message.send('scene', 'snapshot'); }, }, }); diff --git a/editor/inspector/components/lod-group/lod-item.js b/editor/inspector/components/lod-group/lod-item.js index 999d7af91e4..d7e53836e55 100644 --- a/editor/inspector/components/lod-group/lod-item.js +++ b/editor/inspector/components/lod-group/lod-item.js @@ -1,6 +1,7 @@ 'use strict'; const { trackEventWithTimer } = require('../../utils/metrics'); +const { getMessageProtocolScene } = require('../../utils/prop'); exports.template = ` @@ -162,7 +163,7 @@ exports.methods = { }, async applyCameraSize() { const that = this; - let size = await Editor.Message.request('scene', 'lod-apply-current-camera-size', that.dump.value.uuid.value); + let size = await Editor.Message.request(getMessageProtocolScene(that.$el), 'lod-apply-current-camera-size', that.dump.value.uuid.value); if (that.$refs[that.screenUsagePercentageRef]) { const min = Editor.Utils.Math.divide(that.$refs[that.screenUsagePercentageRef].min, 100) || 0; let max = null; diff --git a/editor/inspector/components/lod-group/multi-lod-group.js b/editor/inspector/components/lod-group/multi-lod-group.js index 345574e2784..6976820fe6c 100644 --- a/editor/inspector/components/lod-group/multi-lod-group.js +++ b/editor/inspector/components/lod-group/multi-lod-group.js @@ -1,6 +1,7 @@ 'use strict'; const { trackEventWithTimer } = require('../../utils/metrics'); +const { getMessageProtocolScene } = require('../../utils/prop'); exports.template = `
@@ -114,7 +115,7 @@ exports.methods = { resetMultiObjectSize() { const that = this; that.dump.value.uuid.values.forEach((uuid) => { - Editor.Message.send('scene', 'execute-component-method', { + Editor.Message.send(getMessageProtocolScene(that.$el), 'execute-component-method', { uuid: uuid, name: 'resetObjectSize', args: [], diff --git a/editor/inspector/components/particle-system-2d.js b/editor/inspector/components/particle-system-2d.js index 45891d6e851..ce18062877c 100644 --- a/editor/inspector/components/particle-system-2d.js +++ b/editor/inspector/components/particle-system-2d.js @@ -1,4 +1,6 @@ const { template, $, update, close } = require('./base'); +const { getMessageProtocolScene } = require('../utils/prop'); + // 排列时,相邻元素的间隔间距 const MARGIN = '4px'; @@ -110,7 +112,7 @@ exports.ready = function() { $export.addEventListener('confirm', async (event) => { event.stopPropagation(); - let assetInfo = await Editor.Message.request('scene', 'export-particle-plist', this.dump.value.uuid.value); + let assetInfo = await Editor.Message.request(getMessageProtocolScene(this.$this), 'export-particle-plist', this.dump.value.uuid.value); if (assetInfo) { let values = [this.$this.dump.value]; if (this.$this.dump.values) { diff --git a/editor/inspector/components/particle-system.js b/editor/inspector/components/particle-system.js index 76a2cb3491f..b2a62d5d5cc 100644 --- a/editor/inspector/components/particle-system.js +++ b/editor/inspector/components/particle-system.js @@ -249,12 +249,12 @@ const uiElements = { const componentUUIDs = this.dump.value.uuid.values || [this.dump.value.uuid.value]; await Promise.all(componentUUIDs.map(uuid => { return new Promise((res) => { - Editor.Message.request('scene', 'execute-component-method', { + Editor.Message.request(propUtils.getMessageProtocolScene(this.$this), 'execute-component-method', { uuid, name: '_calculateBounding', args: [true], }).then(() => { - Editor.Message.request('scene', 'execute-component-method', { + Editor.Message.request(propUtils.getMessageProtocolScene(this.$this), 'execute-component-method', { uuid, name: 'gizmo.onNodeChanged', args: [], @@ -390,7 +390,7 @@ const uiElements = { this.$.showBounds.addEventListener('change', (event) => { const componentUUIDs = this.dump.value.uuid.values || [this.dump.value.uuid.value]; componentUUIDs.forEach(uuid => { - Editor.Message.send('scene', 'execute-component-method', { + Editor.Message.send(propUtils.getMessageProtocolScene(this.$this), 'execute-component-method', { uuid, name: 'gizmo.showBoundingBox', args: [event.target.value], @@ -407,7 +407,7 @@ const uiElements = { const componentUUIDs = this.dump.value.uuid.values || [this.dump.value.uuid.value]; const values = await Promise.all( componentUUIDs.map( - uuid => Editor.Message.request('scene', 'execute-component-method', { + uuid => Editor.Message.request(propUtils.getMessageProtocolScene(this.$this), 'execute-component-method', { uuid, name: 'gizmo.isShowBoundingBox', args: [], @@ -609,7 +609,7 @@ const uiElements = { if (!this.dump?.value?.uuid?.values && !this.dump?.value?.uuid?.value) { return; } let uuid = this.dump.value.uuid.values ? this.dump.value.uuid.values[0] : this.dump.value.uuid.value; if (!uuid) { return; } - let data = await Editor.Message.request('scene', 'execute-component-method', { + let data = await Editor.Message.request(propUtils.getMessageProtocolScene(this.$this), 'execute-component-method', { uuid, name: 'getNoisePreview', args: [100, 100], diff --git a/editor/inspector/components/polygon-collider.js b/editor/inspector/components/polygon-collider.js index e1811c7032c..6dae007c1fb 100644 --- a/editor/inspector/components/polygon-collider.js +++ b/editor/inspector/components/polygon-collider.js @@ -1,4 +1,5 @@ const { template, $, update, close } = require('./base'); +const { getMessageProtocolScene } = require('../utils/prop'); exports.template = template; exports.$ = $; @@ -21,20 +22,17 @@ exports.ready = function() { $button.addEventListener('change', (event) => { event.stopPropagation(); - // Editor.Message.send('scene', 'snapshot'); }); $button.addEventListener('confirm', async (event) => { event.stopPropagation(); const uuids = this.dump.value.uuid.values || [this.dump.value.uuid.value]; - const undoID = await Editor.Message.request('scene', 'begin-recording', uuids); + const undoID = await Editor.Message.request(getMessageProtocolScene(this.$this), 'begin-recording', uuids); for (const uuid of uuids) { - await Editor.Message.request('scene', 'regenerate-polygon-2d-points', uuid); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'regenerate-polygon-2d-points', uuid); } - await Editor.Message.request('scene', 'end-recording', undoID); - - // Editor.Message.send('scene', 'snapshot'); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'end-recording', undoID); }); }, }, diff --git a/editor/inspector/components/terrain.js b/editor/inspector/components/terrain.js index a4462d09b06..5b98f15a6a3 100644 --- a/editor/inspector/components/terrain.js +++ b/editor/inspector/components/terrain.js @@ -5,23 +5,22 @@ exports.$ = $; exports.update = update; exports.close = close; -const { setHidden } = require('../utils/prop'); +const { setHidden, getMessageProtocolScene } = require('../utils/prop'); exports.ready = function() { this.elements = { _asset: { ready(element) { element.addEventListener('change-dump', async (event) => { - // Editor.Message.send('scene', 'snapshot'); const uuid = this.dump.value.uuid.value; const dump = event.target.dump; - const undoID = await Editor.Message.request('scene', 'begin-recording', uuid); - Editor.Message.request('scene', 'execute-component-method', { + const undoID = await Editor.Message.request(getMessageProtocolScene(this.$this), 'begin-recording', uuid); + Editor.Message.request(getMessageProtocolScene(this.$this), 'execute-component-method', { uuid: this.dump.value.uuid.value, name: 'manager.addAssetToComp', args: [dump.value], }); - await Editor.Message.request('scene', 'end-recording', undoID); + await Editor.Message.request(getMessageProtocolScene(this.$this), 'end-recording', undoID); }); }, }, diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index cba64780a8c..7ddbbbec836 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -2,11 +2,17 @@ const fs = require('fs'); const path = require('path'); module.paths.push(path.join(Editor.App.path, 'node_modules')); +const Profile = require('@base/electron-profile'); const { throttle } = require('lodash'); const utils = require('./utils'); const { trackEventWithTimer } = require('../utils/metrics'); const { injectionStyle } = require('../utils/prop'); +// ipc messages protocol +const messageProtocol = { + scene: 'scene', +}; + const lockList = []; let lockPerform = false; let lastSnapShot = null; @@ -53,16 +59,16 @@ function snapshotLock(panel, lock, uuids, cancel = false) { // 不传options时,会自动记录到undo队列,不需要调用endRecording async function beginRecording(uuids, options) { if (!uuids) { return; } - const undoID = await Editor.Message.request('scene', 'begin-recording', uuids, options); + const undoID = await Editor.Message.request(messageProtocol.scene, 'begin-recording', uuids, options); return undoID; } async function endRecording(undoID, cancel) { if (!undoID) { return; } if (cancel) { - await Editor.Message.request('scene', 'cancel-recording', undoID); + await Editor.Message.request(messageProtocol.scene, 'cancel-recording', undoID); } else { - await Editor.Message.request('scene', 'end-recording', undoID); + await Editor.Message.request(messageProtocol.scene, 'end-recording', undoID); } } @@ -133,7 +139,7 @@ exports.listeners = { } if (setChildrenLayer) { - await Editor.Message.request('scene', 'set-node-and-children-layer', { + await Editor.Message.request(messageProtocol.scene, 'set-node-and-children-layer', { uuid, dump: { value, @@ -143,7 +149,7 @@ exports.listeners = { continue; } - await Editor.Message.request('scene', 'set-property', { + await Editor.Message.request(messageProtocol.scene, 'set-property', { uuid, path, dump: { @@ -167,7 +173,6 @@ exports.listeners = { clearTimeout(panel.previewTimeId); snapshotLock(panel, false); // In combination with change-dump, snapshot only generated once after ui-elements continuously changed. - // Editor.Message.send('scene', 'snapshot'); }, async 'create-dump'(event) { const panel = this; @@ -179,7 +184,6 @@ exports.listeners = { clearTimeout(panel.previewTimeId); - // Editor.Message.send('scene', 'snapshot'); const undoID = await beginRecording(panel.uuidList); const dump = target.dump; let cancel = false; @@ -190,13 +194,12 @@ exports.listeners = { dump.values[i] = dump.value; } - await Editor.Message.request('scene', 'update-property-from-null', { + await Editor.Message.request(messageProtocol.scene, 'update-property-from-null', { uuid, path: dump.path, }); } - // Editor.Message.send('scene', 'snapshot'); } catch (error) { cancel = true; console.error(error); @@ -222,7 +225,7 @@ exports.listeners = { dump.values[i] = dump.value; } - await Editor.Message.request('scene', 'reset-property', { + await Editor.Message.request(messageProtocol.scene, 'reset-property', { uuid, path: dump.path, }); @@ -277,7 +280,7 @@ exports.listeners = { // 预览新的值 value.uuid = assetUuid; - Editor.Message.send('scene', 'preview-set-property', { + Editor.Message.send(messageProtocol.scene, 'preview-set-property', { uuid, path, dump: { @@ -297,7 +300,7 @@ exports.listeners = { const uuid = panel.uuidList[i]; const { path } = dump; - Editor.Message.send('scene', 'cancel-preview-set-property', { + Editor.Message.send(messageProtocol.scene, 'cancel-preview-set-property', { uuid, path, }); @@ -527,6 +530,21 @@ const Elements = { Editor.Message.addBroadcastListener('project:setting-change', panel.__projectSettingChanged__); + panel.__throttleProfileChanged__ = throttle(async (protocol, file, key) => { + if (protocol === 'defaultPreferences' && file === 'packages/inspector.json' && key === 'message-protocol') { + await panel.__queryMessageProtocolScene__(); + + for (const prop in Elements) { + const element = Elements[prop]; + if (element.update) { + await element.update.call(panel); + } + } + } + }, 100, { leading: false, trailing: true }); + + Profile.on('change', panel.__throttleProfileChanged__); + // 识别拖入脚本资源 panel.$.container.addEventListener('dragover', (event) => { event.preventDefault(); @@ -587,7 +605,7 @@ const Elements = { try { dumps = await Promise.all( panel.uuidList.map((uuid) => { - return Editor.Message.request('scene', 'query-node', uuid); + return Editor.Message.request(messageProtocol.scene, 'query-node', uuid); }), ); } catch (err) { @@ -628,6 +646,10 @@ const Elements = { Editor.Message.removeBroadcastListener('scene:change-node', panel.__nodeChanged__); Editor.Message.removeBroadcastListener('scene:animation-time-change', panel.__animationTimeChange__); Editor.Message.removeBroadcastListener('project:setting-change', panel.__projectSettingChanged__); + + Profile.removeListener('change', panel.__throttleProfileChanged__); + panel.__throttleProfileChanged__.cancel(); + panel.__throttleProfileChanged__ = undefined; }, }, prefab: { @@ -656,7 +678,7 @@ const Elements = { break; } case 'unlink': { - await Editor.Message.request('scene', 'unlink-prefab', prefab.rootUuid, false); + await Editor.Message.request(messageProtocol.scene, 'unlink-prefab', prefab.rootUuid, false); break; } case 'local': { @@ -664,12 +686,12 @@ const Elements = { break; } case 'reset': { - await Editor.Message.request('scene', 'restore-prefab', prefab.rootUuid, prefab.uuid); + await Editor.Message.request(messageProtocol.scene, 'restore-prefab', prefab.rootUuid, prefab.uuid); break; } case 'save': { // apply-prefab是自定义的undo,在场景中实现了undo - await Editor.Message.request('scene', 'apply-prefab', prefab.rootUuid); + await Editor.Message.request(messageProtocol.scene, 'apply-prefab', prefab.rootUuid); break; } } @@ -967,13 +989,13 @@ const Elements = { // DIFFUSEMAP_WITH_REFLECTION 的枚举值为 2 if (envLightingType === 2) { - await Editor.Message.request('scene', 'execute-scene-script', { + await Editor.Message.request(messageProtocol.scene, 'execute-scene-script', { name: 'inspector', method: 'generateDiffuseMap', args: [envMapUuid], }); } else { - await Editor.Message.request('scene', 'execute-scene-script', { + await Editor.Message.request(messageProtocol.scene, 'execute-scene-script', { name: 'inspector', method: 'generateVector', args: [envMapUuid], @@ -981,13 +1003,13 @@ const Elements = { } }, async setEnvMapAndConvolutionMap(uuid) { - await Editor.Message.request('scene', 'execute-scene-script', { + await Editor.Message.request(messageProtocol.scene, 'execute-scene-script', { name: 'inspector', method: 'setSkyboxEnvMap', args: [uuid], }); if (uuid) { - await Editor.Message.request('scene', 'execute-scene-script', { + await Editor.Message.request(messageProtocol.scene, 'execute-scene-script', { name: 'inspector', method: 'setReflectionConvolutionMap', args: [uuid], @@ -1026,7 +1048,7 @@ const Elements = { panel.$.sceneSkyboxReflectionLoading.style.display = 'inline-flex'; panel.$.sceneSkyboxReflectionBake.style.display = 'none'; - await Editor.Message.request('scene', 'execute-scene-script', { + await Editor.Message.request(messageProtocol.scene, 'execute-scene-script', { name: 'inspector', method: 'bakeReflectionConvolution', args: [envMapData.value.uuid], @@ -1314,6 +1336,7 @@ const Elements = { $section.appendChild($panel); $section.__panels__.push($panel); $panel.dump = component; + $panel.messageProtocol = messageProtocol; $panel.update(component); }); @@ -1341,6 +1364,8 @@ const Elements = { panel.$.nodeSection.appendChild(array[index]); } array[index].setAttribute('src', file); + array[index].dump = panel.dump; + array[index].messageProtocol = messageProtocol; array[index].update(panel.dump); }); @@ -1408,11 +1433,11 @@ const Elements = { const uuidList = panel.uuidList; switch (type) { case 'save-o': { - Editor.Message.request('scene', 'apply-removed-component', uuidList[0], info.fileID); + Editor.Message.request(messageProtocol.scene, 'apply-removed-component', uuidList[0], info.fileID); break; } case 'reset': { - Editor.Message.request('scene', 'revert-removed-component', uuidList[0], info.fileID); + Editor.Message.request(messageProtocol.scene, 'revert-removed-component', uuidList[0], info.fileID); break; } } @@ -1498,7 +1523,7 @@ const Elements = { // 批量调用request意味着编辑操作在很多帧后才会完成,所以不能自动记录undo const undoID = await beginRecording(panel.uuidList); for (const uuid of panel.uuidList) { - await Editor.Message.request('scene', 'create-component', { + await Editor.Message.request(messageProtocol.scene, 'create-component', { uuid, component: detail.info.cid, }); @@ -1643,7 +1668,7 @@ exports.methods = { } } - Editor.Message.send('scene', cmd); + Editor.Message.send(messageProtocol.scene, cmd); }, /** @@ -1697,7 +1722,7 @@ exports.methods = { const values = dump.value.uuid.values || [dump.value.uuid.value]; const undoID = await beginRecording(values); for (const compUuid of values) { - await Editor.Message.request('scene', 'reset-component', { + await Editor.Message.request(messageProtocol.scene, 'reset-component', { uuid: compUuid, }); } @@ -1728,7 +1753,7 @@ exports.methods = { if (!uuids.length > 0) { return; } const undoID = await beginRecording(uuids); for (let i = 0; i < uuids.length; i++) { - await Editor.Message.request('scene', 'remove-array-element', { + await Editor.Message.request(messageProtocol.scene, 'remove-array-element', { uuid: uuids[i], path: '__comps__', index: indexes[i], @@ -1742,7 +1767,7 @@ exports.methods = { enabled: !isMultiple && index !== 0, async click() { const undoID = await beginRecording(uuid); - await Editor.Message.request('scene', 'move-array-element', { + await Editor.Message.request(messageProtocol.scene, 'move-array-element', { uuid, path: '__comps__', target: index, @@ -1756,7 +1781,7 @@ exports.methods = { enabled: !isMultiple && index !== total - 1, async click() { const undoID = await beginRecording(uuid); - await Editor.Message.request('scene', 'move-array-element', { + await Editor.Message.request(messageProtocol.scene, 'move-array-element', { uuid, path: '__comps__', target: index, @@ -1802,7 +1827,7 @@ exports.methods = { const index = indexes[i]; const nodeDump = nodeDumps.find(nodeDump => uuid === nodeDump.uuid.value); - await Editor.Message.request('scene', 'set-property', { + await Editor.Message.request(messageProtocol.scene, 'set-property', { uuid, path: nodeDump.__comps__[index].path, dump: clipboardComponentInfo.dump, @@ -1822,20 +1847,20 @@ exports.methods = { let index = 0; for (const dump of values) { const uuid = uuidList[index]; - await Editor.Message.request('scene', 'create-component', { + await Editor.Message.request(messageProtocol.scene, 'create-component', { uuid, component: clipboardComponentInfo.cid, }); // 检查是否创建成功,是的话,给赋值 - const nodeDump = await Editor.Message.request('scene', 'query-node', uuid); + const nodeDump = await Editor.Message.request(messageProtocol.scene, 'query-node', uuid); const length = nodeDump.__comps__ && nodeDump.__comps__.length; if (length) { const lastIndex = length - 1; const lastComp = nodeDump.__comps__[lastIndex]; if (lastComp?.cid === clipboardComponentInfo.cid) { - await Editor.Message.request('scene', 'set-property', { + await Editor.Message.request(messageProtocol.scene, 'set-property', { uuid, path: `__comps__.${lastIndex}`, dump: clipboardComponentInfo.dump, @@ -1876,7 +1901,7 @@ exports.methods = { async click() { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { - await Editor.Message.request('scene', 'reset-node', { + await Editor.Message.request(messageProtocol.scene, 'reset-node', { uuid, }); } @@ -1902,7 +1927,7 @@ exports.methods = { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { for (const attr of clipboardNodeInfo.attrs) { - await Editor.Message.request('scene', 'set-property', { + await Editor.Message.request(messageProtocol.scene, 'set-property', { uuid, path: attr, dump: clipboardNodeInfo.dump[attr], @@ -1917,7 +1942,7 @@ exports.methods = { label: Editor.I18n.t('ENGINE.menu.copy_node_world_transform'), enabled: !isMultiple, async click() { - const data = await Editor.Message.request('scene', 'execute-scene-script', { + const data = await Editor.Message.request(messageProtocol.scene, 'execute-scene-script', { name: 'inspector', method: 'queryNodeWorldTransform', args: [dump.uuid.value], @@ -1937,7 +1962,7 @@ exports.methods = { if (clipboardNodeWorldTransform.data) { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { - await Editor.Message.request('scene', 'execute-scene-script', { + await Editor.Message.request(messageProtocol.scene, 'execute-scene-script', { name: 'inspector', method: 'setNodeWorldTransform', args: [uuid, clipboardNodeWorldTransform.data], @@ -1954,20 +1979,20 @@ exports.methods = { async click() { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { - await Editor.Message.request('scene', 'create-component', { + await Editor.Message.request(messageProtocol.scene, 'create-component', { uuid, component: clipboardComponentInfo.cid, }); // 检查是否创建成功,是的话,给赋值 - const nodeDump = await Editor.Message.request('scene', 'query-node', uuid); + const nodeDump = await Editor.Message.request(messageProtocol.scene, 'query-node', uuid); const length = nodeDump.__comps__ && nodeDump.__comps__.length; if (length) { const lastIndex = length - 1; const lastComp = nodeDump.__comps__[lastIndex]; if (lastComp?.cid === clipboardComponentInfo.cid) { - await Editor.Message.request('scene', 'set-property', { + await Editor.Message.request(messageProtocol.scene, 'set-property', { uuid, path: `__comps__.${lastIndex}`, dump: clipboardComponentInfo.dump, @@ -1985,7 +2010,7 @@ exports.methods = { async click() { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { - await Editor.Message.request('scene', 'reset-property', { + await Editor.Message.request(messageProtocol.scene, 'reset-property', { uuid, path: 'position', }); @@ -1999,7 +2024,7 @@ exports.methods = { async click() { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { - await Editor.Message.request('scene', 'reset-property', { + await Editor.Message.request(messageProtocol.scene, 'reset-property', { uuid, path: 'rotation', }); @@ -2013,7 +2038,7 @@ exports.methods = { async click() { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { - await Editor.Message.request('scene', 'reset-property', { + await Editor.Message.request(messageProtocol.scene, 'reset-property', { uuid, path: 'scale', }); @@ -2027,7 +2052,7 @@ exports.methods = { async click() { const undoID = await beginRecording(uuidList); for (const uuid of uuidList) { - await Editor.Message.request('scene', 'reset-property', { + await Editor.Message.request(messageProtocol.scene, 'reset-property', { uuid, path: 'mobility', }); @@ -2052,7 +2077,7 @@ exports.methods = { const dumpData = materialUuids[assetUuid][dumpPath]; for (let i = 0; i < panel.uuidList.length; i++) { const nodeUuid = panel.uuidList[i]; - await Editor.Message.request('scene', 'set-property', { + await Editor.Message.request(messageProtocol.scene, 'set-property', { uuid: nodeUuid, path: dumpPath, dump: { @@ -2110,6 +2135,23 @@ exports.ready = async function ready() { // 为了避免把 ui-num-input, ui-color 的连续 change 进行 snapshot panel.snapshotLock = false; + // 节点的 ipc 协议,指向 scene 或 xr-scene 等进程 + panel.__queryMessageProtocolScene__ = async function() { + try { + if (!panel.messageProtocol) { + panel.messageProtocol = messageProtocol; + } + const config = await await Editor.Profile.getConfig('inspector', 'message-protocol'); + if (config) { + Object.assign(messageProtocol, config); + } + } catch (error) { + console.error(error); + messageProtocol.scene = 'scene'; + } + }; + await panel.__queryMessageProtocolScene__(); + for (const prop in Elements) { const element = Elements[prop]; if (element.ready) { diff --git a/editor/inspector/utils/prop.js b/editor/inspector/utils/prop.js index 6a7a0ad9692..ec76e9f7d52 100644 --- a/editor/inspector/utils/prop.js +++ b/editor/inspector/utils/prop.js @@ -184,6 +184,32 @@ exports.setHidden = function(data, element) { } }; +// In order to avoid a large number of operations in a short time, the function of returning the same operation result in a time period is added +let getMessageProtocolSceneResult = ''; +let getMessageProtocolSceneStartTime = Date.now(); +exports.getMessageProtocolScene = function(element) { + if (getMessageProtocolSceneResult && Date.now() - getMessageProtocolSceneStartTime < 1000) { + return getMessageProtocolSceneResult; + } + + getMessageProtocolSceneResult = ''; + getMessageProtocolSceneStartTime = Date.now(); + + while (element) { + element = element.parentElement || element.getRootNode().host; + if (element && element.messageProtocol) { + getMessageProtocolSceneResult = element.messageProtocol.scene; + break; + } + } + + if (!getMessageProtocolSceneResult) { + getMessageProtocolSceneResult = 'scene'; + } + + return getMessageProtocolSceneResult; +}; + exports.updatePropByDump = function(panel, dump) { panel.dump = dump; From 22c5bbc175d7d22c5b650edecf75bd8e642feb6f Mon Sep 17 00:00:00 2001 From: zxx43 Date: Mon, 21 Aug 2023 11:28:56 +0800 Subject: [PATCH 201/232] add a lot of missed functions for spine jsb (#16027) * add a lot of missed functions for spine jsb * change conversion type to number * check type is a number * change toNumber to toDouble --- .../cocos/bindings/manual/jsb_conversions.h | 30 +++++++++++ native/tools/swig-config/spine.i | 51 +++++++++++++++++-- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 9170e2ce8f4..580dbfb4d44 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -1441,6 +1441,36 @@ bool sevalue_to_native(const se::Value &v, spine::Vector *ret, se::Object * return true; } + +template >> +bool sevalue_to_native(const se::Value &v, spine::Vector *ret, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) + CC_ASSERT_NOT_NULL(ret); + CC_ASSERT(v.isObject()); + se::Object *obj = v.toObject(); + CC_ASSERT(obj->isArray()); + + bool ok = true; + uint32_t len = 0; + ok = obj->getArrayLength(&len); + if (!ok) { + ret->clear(); + return false; + } + + se::Value tmp; + for (uint32_t i = 0; i < len; ++i) { + ok = obj->getArrayElement(i, &tmp); + if (!ok || !tmp.isNumber()) { + ret->clear(); + return false; + } + + T nativeObj = static_cast(tmp.toDouble()); + ret->add(nativeObj); + } + + return true; +} #endif // CC_USE_SPINE /////////////////// shorter form diff --git a/native/tools/swig-config/spine.i b/native/tools/swig-config/spine.i index 9ffeb32ccbf..c8fa9127528 100644 --- a/native/tools/swig-config/spine.i +++ b/native/tools/swig-config/spine.i @@ -40,7 +40,6 @@ using namespace spine; // 1. 'Ignore Section' should be placed before attribute definition and %import/%include // 2. namespace is needed // -%ignore spine::MathUtil; %ignore cc::RefCounted; %ignore *::rtti; %ignore spine::SkeletonCache::SegmentData; @@ -48,6 +47,7 @@ using namespace spine; %ignore spine::SkeletonCache::FrameData; %ignore spine::SkeletonCache::AnimationData; %ignore spine::Skin::AttachmentMap::getEntries; +%ignore spine::AttachmentLoader::getRTTI; %ignore spine::Polygon::Polygon; %ignore spine::Polygon::_vertices; @@ -137,6 +137,13 @@ using namespace spine; %ignore spine::Bone::updateWorldTransform(float, float, float, float, float, float, float); %ignore spine::Skin::findAttachmentsForSlot; %ignore spine::SkeletonBinary::readSkeletonData(const unsigned char*, int); +%ignore spine::AttachmentLoader::newRegionAttachment(Skin&, const String&, const String&); +%ignore spine::AttachmentLoader::newMeshAttachment(Skin&, const String&, const String&); +%ignore spine::AttachmentLoader::newBoundingBoxAttachment(Skin&, const String&); +%ignore spine::AttachmentLoader::newPathAttachment(Skin&, const String&); +%ignore spine::AttachmentLoader::newPointAttachment(Skin&, const String&); +%ignore spine::AttachmentLoader::newClippingAttachment(Skin&, const String&); +%ignore spine::TextureLoader::load(AtlasPage&, const String&); // ----- Rename Section ------ // Brief: Classes, methods or attributes needs to be renamed @@ -205,6 +212,8 @@ using namespace spine; %rename(name) spine::Skin::AttachmentMap::Entry::_name; %rename(attachment) spine::Skin::AttachmentMap::Entry::_attachment; %rename(signum) spine::MathUtil::sign(float); +%rename(TextureAtlasPage) spine::AtlasPage; +%rename(TextureAtlasRegion) spine::AtlasRegion; // ----- Module Macro Section ------ // Brief: Generated code should be wrapped inside a macro @@ -407,7 +416,7 @@ using namespace spine; %attribute(spine::Skeleton, float, x, getX, setX); %attribute(spine::Skeleton, float, y, getY, setY); -%attribute(spine::SkeletonBinary, float, scale, setScale); +%attribute_writeonly(spine::SkeletonBinary, float, scale, setScale); %attribute(spine::SkeletonClipping, spine::Vector&, clippedVertices, getClippedVertices); %attribute(spine::SkeletonClipping, spine::Vector&, clippedTriangles, getClippedTriangles); @@ -594,6 +603,10 @@ using namespace spine; %include "editor-support/spine/SkeletonBounds.h" %include "editor-support/spine/SkeletonData.h" %include "editor-support/spine/SlotData.h" +%include "editor-support/spine/SkeletonBinary.h" +%include "editor-support/spine/AttachmentLoader.h" +%include "editor-support/spine/Atlas.h" +%include "editor-support/spine/TextureLoader.h" %include "editor-support/spine/TransformConstraint.h" %include "editor-support/spine/TransformConstraintData.h" @@ -750,11 +763,43 @@ using namespace spine; } %extend spine::SkeletonBinary { - SkeletonData *readSkeletonData(const std::vector& binary) { + spine::SkeletonData *readSkeletonData(const std::vector& binary) { std::vector input; for (int i = 0; i < binary.size(); ++i) { input.push_back(binary[i]); } return $self->readSkeletonData(input.data(), input.size()); } +} + +%extend spine::AttachmentLoader { + spine::RegionAttachment* newRegionAttachment(spine::Skin* skin, const spine::String& name, const spine::String& path) { + return $self->newRegionAttachment(*skin, name, path); + } + + spine::MeshAttachment* newMeshAttachment(spine::Skin* skin, const spine::String& name, const spine::String& path) { + return $self->newMeshAttachment(*skin, name, path); + } + + spine::BoundingBoxAttachment* newBoundingBoxAttachment(spine::Skin* skin, const spine::String& name) { + return $self->newBoundingBoxAttachment(*skin, name); + } + + spine::PathAttachment* newPathAttachment(spine::Skin* skin, const spine::String& name) { + return $self->newPathAttachment(*skin, name); + } + + spine::PointAttachment* newPointAttachment(spine::Skin* skin, const spine::String& name) { + return $self->newPointAttachment(*skin, name); + } + + spine::ClippingAttachment* newClippingAttachment(spine::Skin* skin, const spine::String& name) { + return $self->newClippingAttachment(*skin, name); + } +} + +%extend spine::TextureLoader { + void load(spine::AtlasPage* page, const spine::String& path) { + $self->load(*page, path); + } } \ No newline at end of file From ba93769911dbbd3b50e68c3bd093ea2d29c82658 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Mon, 21 Aug 2023 12:01:27 +0800 Subject: [PATCH 202/232] fix mask change sprite size mode Bug (#16047) --- cocos/2d/components/mask.ts | 79 ++++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 28 deletions(-) diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index afaf7dfb44a..a01247055d4 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -23,9 +23,10 @@ THE SOFTWARE. */ -import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, visible, serializable, range, slide, executeInEditMode } from 'cc.decorator'; +import { ccclass, help, executionOrder, menu, tooltip, displayOrder, + type, visible, serializable, range, slide, executeInEditMode } from 'cc.decorator'; import { JSB } from 'internal:constants'; -import { clamp, Color, Mat4, Vec2, Vec3, warnID, cclegacy, ccenum } from '../../core'; +import { clamp, Color, Mat4, Vec2, Vec3, warnID, cclegacy, ccenum, error } from '../../core'; import { Graphics } from './graphics'; import { TransformBit } from '../../scene-graph/node-enum'; import { Stage } from '../renderer/stencil-manager'; @@ -35,6 +36,7 @@ import { Sprite } from './sprite'; import { NodeEventType, Component } from '../../scene-graph'; import type { SpriteFrame } from '../assets'; import type { Material } from '../../asset/assets'; +import { MaterialInstance } from '../../render-scene'; const _worldMatrix = new Mat4(); const _vec2_temp = new Vec2(); @@ -45,8 +47,12 @@ function _calculateCircle (center: Vec3, radius: Vec3, segments: number): Vec3[] _circlePoints.length = 0; const anglePerStep = Math.PI * 2 / segments; for (let step = 0; step < segments; ++step) { - _circlePoints.push(new Vec3(radius.x * Math.cos(anglePerStep * step) + center.x, - radius.y * Math.sin(anglePerStep * step) + center.y, 0)); + _circlePoints.push(new Vec3( + radius.x * Math.cos(anglePerStep * step) + center.x, + radius.y * Math.sin(anglePerStep * step) + center.y, + + 0, + )); } return _circlePoints; @@ -224,7 +230,7 @@ export class Mask extends Component { if (this._sprite) { this._sprite.spriteFrame = value; } else { - console.error('please change type to sprite_stencil first'); + error('please change type to sprite_stencil first'); } } @@ -377,8 +383,6 @@ export class Mask extends Component { const node = this.node; sprite = this._sprite = node.addComponent(Sprite); } - sprite.color = Color.WHITE.clone(); - sprite.sizeMode = 0; } this._sprite!.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; this._sprite!.updateMaterial(); @@ -463,7 +467,8 @@ export class Mask extends Component { // deprecated interface /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ get customMaterial (): Material | null { warnID(9007); @@ -479,7 +484,8 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ get color (): Color | null { warnID(9007); @@ -495,7 +501,8 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public markForUpdateRenderData (enable = true): void { warnID(9007); @@ -504,20 +511,23 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public requestRenderData (any): void { warnID(9007); } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public destroyRenderData (): void { warnID(9007); } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public updateRenderer (): void { warnID(9007); @@ -527,19 +537,22 @@ export class Mask extends Component { } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public fillBuffers (render: any): void { warnID(9007); } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public postUpdateAssembler (render: any): void { warnID(9007); } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public setNodeDirty (): void { warnID(9007); @@ -548,7 +561,8 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public setTextureDirty (): void { warnID(9007); @@ -557,7 +571,8 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ get sharedMaterial (): Material | null { warnID(9007); @@ -567,7 +582,8 @@ export class Mask extends Component { return null; } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ get sharedMaterials (): (Material | null)[] | null { warnID(9007); @@ -583,7 +599,8 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ get material (): any { warnID(9007); @@ -599,7 +616,8 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ get materials (): (any)[] { warnID(9007); @@ -615,7 +633,8 @@ export class Mask extends Component { } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public getMaterial (idx: number): any { warnID(9007); @@ -625,16 +644,18 @@ export class Mask extends Component { return null; } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ - public setMaterial (material: any, index: number): void { + public setMaterial (material: Material | MaterialInstance | null, index: number): void { warnID(9007); if (this.subComp) { this.subComp.setMaterial(material, index); } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public getMaterialInstance (idx: number): any { warnID(9007); @@ -644,16 +665,18 @@ export class Mask extends Component { return null; } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ - public setMaterialInstance (matInst: any, index: number): void { + public setMaterialInstance (matInst: Material | MaterialInstance | null, index: number): void { warnID(9007); if (this.subComp) { this.subComp.setMaterialInstance(matInst, index); } } /** - * @deprecated Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation + * @deprecated Since v3.6, Because mask changes the inheritance relationship, + * you can directly manipulate the rendering components under the same node to complete the operation */ public getRenderMaterial (index: number): any { warnID(9007); From 20dd273ea7ac3d1d41c1db80c4c6ca351dd48223 Mon Sep 17 00:00:00 2001 From: Canvas Date: Mon, 21 Aug 2023 13:34:44 +0800 Subject: [PATCH 203/232] fix spine wasm api. (#16004) * fix spine wasm api. * fix code format. * remove new api. * remove private function. * add setSlotsRange return type. * add setSlotsRange parameter type. * fix setUV. * Fix code description problem. * remove new api $ fix complete listeners. * fix bone setter. * fix code format. * fix code format. * fix code format. * fix bind api. * remove test code. * fix code format. * add api any ignore. * update external-config checkout to v3.8.1-14. --- cocos/spine/lib/spine-core.d.ts | 211 +-- cocos/spine/lib/spine-define.ts | 170 ++- cocos/spine/skeleton.ts | 96 +- .../editor-support/spine-wasm/CMakeLists.txt | 4 +- .../spine-wasm/spine-skeleton-instance.cpp | 2 +- .../spine-wasm/spine-type-export.cpp | 1198 ++++++++++------- native/external-config.json | 2 +- 7 files changed, 992 insertions(+), 691 deletions(-) diff --git a/cocos/spine/lib/spine-core.d.ts b/cocos/spine/lib/spine-core.d.ts index acce177ea13..49265a616e7 100644 --- a/cocos/spine/lib/spine-core.d.ts +++ b/cocos/spine/lib/spine-core.d.ts @@ -21,18 +21,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* eslint @typescript-eslint/no-explicit-any: "off" */ declare namespace spine { class Animation { + constructor(name: string, timelines: Array, duration: number); + duration: number; name: string; timelines: Array; - timelineIds: Array; - duration: number; - constructor(name: string, timelines: Array, duration: number); - hasTimeline(id: number): boolean; apply(skeleton: Skeleton, lastTime: number, time: number, loop: boolean, events: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; - static binarySearch(values: ArrayLike, target: number, step?: number): number; - static linearSearch(values: ArrayLike, target: number, step: number): number; + hasTimeline(id: number): boolean; } interface Timeline { apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; @@ -66,11 +64,10 @@ declare namespace spine { twoColor = 14 } abstract class CurveTimeline implements Timeline { - static LINEAR: number; - static STEPPED: number; - static BEZIER: number; - static BEZIER_SIZE: number; - private curves; + static readonly LINEAR: number; + static readonly STEPPED: number; + static readonly BEZIER: number; + static readonly BEZIER_SIZE: number; abstract getPropertyId(): number; constructor(frameCount: number); getFrameCount(): number; @@ -94,13 +91,7 @@ declare namespace spine { apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; } class TranslateTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_X: number; - static PREV_Y: number; - static X: number; - static Y: number; - boneIndex: number; + static readonly ENTRIES: number; frames: ArrayLike; constructor(frameCount: number); getPropertyId(): number; @@ -119,43 +110,23 @@ declare namespace spine { } class ColorTimeline extends CurveTimeline { static ENTRIES: number; - static PREV_TIME: number; - static PREV_R: number; - static PREV_G: number; - static PREV_B: number; - static PREV_A: number; - static R: number; - static G: number; - static B: number; - static A: number; slotIndex: number; frames: ArrayLike; constructor(frameCount: number); getPropertyId(): number; + getSlotIndex(): number; + setSlotIndex(inValue: number): void; setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; } class TwoColorTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_R: number; - static PREV_G: number; - static PREV_B: number; - static PREV_A: number; - static PREV_R2: number; - static PREV_G2: number; - static PREV_B2: number; - static R: number; - static G: number; - static B: number; - static A: number; - static R2: number; - static G2: number; - static B2: number; + static readonly ENTRIES: number; slotIndex: number; frames: ArrayLike; constructor(frameCount: number); getPropertyId(): number; + getSlotIndex(): number; + setSlotIndex(inValue: number): void; setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number, r2: number, g2: number, b2: number): void; apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; } @@ -166,9 +137,11 @@ declare namespace spine { constructor(frameCount: number); getPropertyId(): number; getFrameCount(): number; + getSlotIndex(): number; + setSlotIndex(inValue: number): void; + getAttachmentNames(): Array; setFrame(frameIndex: number, time: number, attachmentName: string): void; apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; - setAttachment(skeleton: Skeleton, slot: Slot, attachmentName: string): void; } class DeformTimeline extends CurveTimeline { slotIndex: number; @@ -198,20 +171,8 @@ declare namespace spine { setFrame(frameIndex: number, time: number, drawOrder: Array): void; apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; } - class IkConstraintTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_MIX: number; - static PREV_SOFTNESS: number; - static PREV_BEND_DIRECTION: number; - static PREV_COMPRESS: number; - static PREV_STRETCH: number; - static MIX: number; - static SOFTNESS: number; - static BEND_DIRECTION: number; - static COMPRESS: number; - static STRETCH: number; - ikConstraintIndex: number; + class IkConstraintTimeline extends Updatable { + static readonly ENTRIES: number; frames: ArrayLike; constructor(frameCount: number); getPropertyId(): number; @@ -220,29 +181,13 @@ declare namespace spine { } class TransformConstraintTimeline extends CurveTimeline { static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATE: number; - static PREV_TRANSLATE: number; - static PREV_SCALE: number; - static PREV_SHEAR: number; - static ROTATE: number; - static TRANSLATE: number; - static SCALE: number; - static SHEAR: number; - transformConstraintIndex: number; - frames: ArrayLike; constructor(frameCount: number); getPropertyId(): number; setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number, scaleMix: number, shearMix: number): void; apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; } class PathConstraintPositionTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_VALUE: number; - static VALUE: number; - pathConstraintIndex: number; - frames: ArrayLike; + static readonly ENTRIES: number; constructor(frameCount: number); getPropertyId(): number; setFrame(frameIndex: number, time: number, value: number): void; @@ -254,13 +199,7 @@ declare namespace spine { apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; } class PathConstraintMixTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATE: number; - static PREV_TRANSLATE: number; - static ROTATE: number; - static TRANSLATE: number; - pathConstraintIndex: number; + static readonly ENTRIES: number; frames: ArrayLike; constructor(frameCount: number); getPropertyId(): number; @@ -268,36 +207,17 @@ declare namespace spine { apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, blend: MixBlend, direction: MixDirection): void; } class AnimationState { - static emptyAnimation: Animation; - static SUBSEQUENT: number; - static FIRST: number; - static HOLD_SUBSEQUENT: number; - static HOLD_FIRST: number; - static HOLD_MIX: number; - static SETUP: number; - static CURRENT: number; data: AnimationStateData; tracks: TrackEntry[]; timeScale: number; - unkeyedState: number; - events: Event[]; - listeners: AnimationStateListener[]; - queue: EventQueue; - propertyIDs: IntSet; - animationsChanged: boolean; - trackEntryPool: Pool; constructor(data: AnimationStateData); update(delta: number): void; - updateMixingFrom(to: TrackEntry, delta: number): boolean; apply(skeleton: Skeleton): boolean; - applyMixingFrom(to: TrackEntry, skeleton: Skeleton, blend: MixBlend): number; applyAttachmentTimeline(timeline: AttachmentTimeline, skeleton: Skeleton, time: number, blend: MixBlend, attachments: boolean): void; setAttachment(skeleton: Skeleton, slot: Slot, attachmentName: string, attachments: boolean): void; applyRotateTimeline(timeline: Timeline, skeleton: Skeleton, time: number, alpha: number, blend: MixBlend, timelinesRotation: Array, i: number, firstFrame: boolean): void; - queueEvents(entry: TrackEntry, animationTime: number): void; clearTracks(): void; clearTrack(trackIndex: number): void; - setCurrent(index: number, current: TrackEntry, interrupt: boolean): void; setAnimation(trackIndex: number, animationName: string, loop: boolean): TrackEntry; setAnimationWith(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; addAnimation(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; @@ -305,16 +225,10 @@ declare namespace spine { setEmptyAnimation(trackIndex: number, mixDuration: number): TrackEntry; addEmptyAnimation(trackIndex: number, mixDuration: number, delay: number): TrackEntry; setEmptyAnimations(mixDuration: number): void; - expandToIndex(index: number): TrackEntry; trackEntry(trackIndex: number, animation: Animation, loop: boolean, last: TrackEntry): TrackEntry; - disposeNext(entry: TrackEntry): void; - _animationsChanged(): void; - computeHold(entry: TrackEntry): void; getCurrent(trackIndex: number): TrackEntry; - addListener(listener: AnimationStateListener): void; - removeListener(listener: AnimationStateListener): void; + setListener(listener: AnimationStateListener): void; clearListeners(): void; - clearListenerNotifications(): void; } class TrackEntry { animation: Animation; @@ -480,7 +394,6 @@ declare namespace spine { getWorldRotationY(): number; getWorldScaleX(): number; getWorldScaleY(): number; - updateAppliedTransform(): void; worldToLocal(world: Vector2): Vector2; localToWorld(local: Vector2): Vector2; worldToLocalRotation(worldRotation: number): number; @@ -501,7 +414,6 @@ declare namespace spine { shearY: number; transformMode: TransformMode; skinRequired: boolean; - color: Color; constructor(index: number, name: string, parent: BoneData); } enum TransformMode { @@ -588,10 +500,6 @@ declare namespace spine { isActive(): boolean; apply(): void; update(): void; - computeWorldPositions(path: PathAttachment, spacesCount: number, tangents: boolean, percentPosition: boolean, percentSpacing: boolean): number[]; - addBeforePosition(p: number, temp: Array, i: number, out: Array, o: number): void; - addAfterPosition(p: number, temp: Array, i: number, out: Array, o: number): void; - addCurvePosition(p: number, x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, out: Array, o: number, tangents: boolean): void; } class PathConstraintData extends ConstraintData { bones: BoneData[]; @@ -657,13 +565,6 @@ declare namespace spine { y: number; constructor(data: SkeletonData); updateCache(): void; - sortIkConstraint(constraint: IkConstraint): void; - sortPathConstraint(constraint: PathConstraint): void; - sortTransformConstraint(constraint: TransformConstraint): void; - sortPathConstraintAttachment(skin: Skin, slotIndex: number, slotBone: Bone): void; - sortPathConstraintAttachmentWith(attachment: Attachment, slotBone: Bone): void; - sortBone(bone: Bone): void; - sortReset(bones: Array): void; updateWorldTransform(): void; setToSetupPose(): void; setBonesToSetupPose(): void; @@ -681,7 +582,7 @@ declare namespace spine { findIkConstraint(constraintName: string): IkConstraint; findTransformConstraint(constraintName: string): TransformConstraint; findPathConstraint(constraintName: string): PathConstraint; - getBounds(offset: Vector2, size: Vector2, temp?: Array): void; + //getBounds(offset: Vector2, size: Vector2, temp?: Array): void; update(delta: number): void; } class SkeletonBinary { @@ -719,15 +620,7 @@ declare namespace spine { setCurve(timeline: CurveTimeline, frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; } class SkeletonBounds { - minX: number; - minY: number; - maxX: number; - maxY: number; - boundingBoxes: BoundingBoxAttachment[]; - polygons: ArrayLike[]; - private polygonPool; update(skeleton: Skeleton, updateAabb: boolean): void; - aabbCompute(): void; aabbContainsPoint(x: number, y: number): boolean; aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; @@ -745,6 +638,7 @@ declare namespace spine { private clipOutput; clippedVertices: number[]; clippedTriangles: number[]; + clippedUVs: number[]; private scratch; private clipAttachment; private clippingPolygons; @@ -753,8 +647,6 @@ declare namespace spine { clipEnd(): void; isClipping(): boolean; clipTriangles(vertices: ArrayLike, verticesLength: number, triangles: ArrayLike, trianglesLength: number, uvs: ArrayLike, light: Color, dark: Color, twoColor: boolean, strideFloat?: number, offsetV?: number, offsetI?: number): void; - clip(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, clippingArea: Array, output: Array): boolean; - static makeClockwise(polygon: ArrayLike): void; } class SkeletonData { name: string; @@ -820,12 +712,13 @@ declare namespace spine { setAttachment(slotIndex: number, name: string, attachment: Attachment): void; addSkin(skin: Skin): void; copySkin(skin: Skin): void; + findNamesForSlot(slotIndex: number, names: Array): void; + getBones(): Array; + getConstraints(): Array; getAttachment(slotIndex: number, name: string): Attachment; removeAttachment(slotIndex: number, name: string): void; getAttachments(): Array; getAttachmentsForSlot(slotIndex: number, attachments: Array): void; - clear(): void; - attachAll(skeleton: Skeleton, oldSkin: Skin): void; } class Slot { data: SlotData; @@ -933,16 +826,11 @@ declare namespace spine { translateMix: number; scaleMix: number; shearMix: number; - temp: Vector2; active: boolean; constructor(data: TransformConstraintData, skeleton: Skeleton); isActive(): boolean; apply(): void; update(): void; - applyAbsoluteWorld(): void; - applyRelativeWorld(): void; - applyAbsoluteLocal(): void; - applyRelativeLocal(): void; } class TransformConstraintData extends ConstraintData { bones: BoneData[]; @@ -1015,20 +903,28 @@ declare namespace spine { static rgb888ToColor(color: Color, value: number): void; } class MathUtils { - static PI: number; - static PI2: number; - static radiansToDegrees: number; - static radDeg: number; - static degreesToRadians: number; - static degRad: number; + static readonly PI: number; + static readonly PI2: number; + static readonly radiansToDegrees: number; + static readonly radDeg: number; + static readonly degreesToRadians: number; + static readonly degRad: number; + static abs(value: number): number; + static signum(value: number): number; static clamp(value: number, min: number, max: number): number; - static cosDeg(degrees: number): number; + static fmod(a: number, b: number): number; + static atan2(y: number, x: number): number; + static cos(radians: number): number; + static sin(radians: number): number; + static sqrt(value: number): number; + static acos(value: number): number; static sinDeg(degrees: number): number; - static signum(value: number): number; - static toInt(x: number): number; - static cbrt(x: number): number; + static cosDeg(degrees: number): number; + static isNan(value: number): number; + static random(): number; static randomTriangular(min: number, max: number): number; static randomTriangularWith(min: number, max: number, mode: number): number; + static pow(a: number, b: number): number; } abstract class Interpolation { protected abstract applyInternal(a: number): number; @@ -1103,7 +999,7 @@ declare namespace spine { } abstract class VertexEffect { begin(skeleton: Skeleton): void; - transform(position: Vector2, uv: Vector2, light: Color, dark: Color): void; + transform(x: number, y: number): void; end(): void; } // interface Math { @@ -1143,18 +1039,15 @@ declare namespace spine { Clipping = 6 } class BoundingBoxAttachment extends VertexAttachment { - color: Color; constructor(name: string); copy(): Attachment; } class ClippingAttachment extends VertexAttachment { endSlot: SlotData; - color: Color; constructor(name: string); copy(): Attachment; } class MeshAttachment extends VertexAttachment { - region: TextureRegion; path: string; regionUVs: ArrayLike; uvs: ArrayLike; @@ -1165,7 +1058,6 @@ declare namespace spine { hullLength: number; edges: Array; private parentMesh; - tempColor: Color; constructor(name: string); updateUVs(): void; getParentMesh(): MeshAttachment; @@ -1177,7 +1069,6 @@ declare namespace spine { lengths: Array; closed: boolean; constantSpeed: boolean; - color: Color; constructor(name: string); copy(): Attachment; } @@ -1185,7 +1076,6 @@ declare namespace spine { x: number; y: number; rotation: number; - color: Color; constructor(name: string); computeWorldPosition(bone: Bone, point: Vector2): Vector2; computeWorldRotation(bone: Bone): number; @@ -1248,7 +1138,6 @@ declare namespace spine { tempColor: Color; constructor(name: string); updateOffset(): void; - setRegion(region: TextureRegion): void; computeWorldVertices(bone: Bone, worldVertices: ArrayLike, offset: number, stride: number): void; copy(): Attachment; } @@ -1257,7 +1146,7 @@ declare namespace spine { jitterY: number; constructor(jitterX: number, jitterY: number); begin(skeleton: Skeleton): void; - transform(position: Vector2, uv: Vector2, light: Color, dark: Color): void; + transform(x: number, y: number): void; end(): void; } class SwirlEffect implements VertexEffect { @@ -1266,11 +1155,11 @@ declare namespace spine { centerY: number; radius: number; angle: number; - private worldX; - private worldY; + worldX; + worldY; constructor(radius: number, interpolation?: Interpolation); begin(skeleton: Skeleton): void; - transform(position: Vector2, uv: Vector2, light: Color, dark: Color): void; + transform(x: number, y: number): void; end(): void; } diff --git a/cocos/spine/lib/spine-define.ts b/cocos/spine/lib/spine-define.ts index 4ad387b7e28..447df050ff7 100644 --- a/cocos/spine/lib/spine-define.ts +++ b/cocos/spine/lib/spine-define.ts @@ -21,11 +21,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* eslint @typescript-eslint/no-explicit-any: "off" */ import spine from './spine-core.js'; import { js } from '../../core'; -function overrideDefineArrayProp (prototype, getPropVector, name): void { +function overrideDefineArrayProp (prototype: any, getPropVector: any, name: string): void { Object.defineProperty(prototype, name, { get (): any[] { const array: any[] = []; @@ -41,7 +42,7 @@ function overrideDefineArrayProp (prototype, getPropVector, name): void { }); } -function overrideDefineArrayFunction (prototype, getPropVector, name): void { +function overrideDefineArrayFunction (prototype: any, getPropVector: any, name: string): void { Object.defineProperty(prototype, name, { value () { const array: any[] = []; @@ -151,60 +152,65 @@ function overrideProperty_BoneData (): void { proto: prototype, property: 'length', getter: prototype.getLength, + setter: prototype.setLength, }, { proto: prototype, property: 'x', getter: prototype.getX, + setter: prototype.setX, }, { proto: prototype, property: 'y', getter: prototype.getY, + setter: prototype.setY, }, { proto: prototype, property: 'rotation', getter: prototype.getRotation, + setter: prototype.setRotation, }, { proto: prototype, property: 'scaleX', getter: prototype.getScaleX, + setter: prototype.setScaleX, }, { proto: prototype, property: 'scaleY', getter: prototype.getScaleY, + setter: prototype.setScaleY, }, { proto: prototype, property: 'shearX', getter: prototype.getShearX, + setter: prototype.setShearX, }, { proto: prototype, property: 'shearY', getter: prototype.getShearY, + setter: prototype.setShearY, }, { proto: prototype, property: 'transformMode', getter: prototype.getTransformMode, + setter: prototype.setTransformMode, }, { proto: prototype, property: 'skinRequired', getter: prototype.getSkinRequired, + setter: prototype.setSkinRequired, }, - // { - // proto: spine.BoneData.prototype, - // property: 'color', - // getter: spine.BoneData.prototype.getProp_color, - // }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -376,16 +382,19 @@ function overrideProperty_Event (): void { proto: prototype, property: 'intValue', getter: prototype.getIntValue, + setter: prototype.setIntValue, }, { proto: prototype, property: 'floatValue', getter: prototype.getFloatValue, + setter: prototype.setFloatValue, }, { proto: prototype, property: 'stringValue', getter: prototype.getStringValue, + setter: prototype.setStringValue, }, { proto: prototype, @@ -396,15 +405,17 @@ function overrideProperty_Event (): void { proto: prototype, property: 'volume', getter: prototype.getVolume, + setter: prototype.setVolume, }, { proto: prototype, property: 'balance', getter: prototype.getBalance, + setter: prototype.setBalance, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -420,35 +431,78 @@ function overrideProperty_EventData (): void { proto: prototype, property: 'intValue', getter: prototype.getIntValue, + setter: prototype.setIntValue, }, { proto: prototype, property: 'floatValue', getter: prototype.getFloatValue, + setter: prototype.setFloatValue, }, { proto: prototype, property: 'stringValue', getter: prototype.getStringValue, + setter: prototype.setStringValue, }, { proto: prototype, property: 'audioPath', getter: prototype.getAudioPath, + setter: prototype.setAudioPath, }, { proto: prototype, property: 'volume', getter: prototype.getVolume, + setter: prototype.setVolume, }, { proto: prototype, property: 'balance', getter: prototype.getBalance, + setter: prototype.setBalance, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); + }); +} + +function overrideProperty_VertexAttachment (): void { + const prototype = spine.VertexAttachment.prototype as any; + const propertyPolyfills = [ + { + proto: prototype, + property: 'id', + getter: prototype.getId, + setter: prototype.setId, + }, + { + proto: prototype, + property: 'bones', + getter: prototype.getBones, + }, + { + proto: prototype, + property: 'vertices', + getter: prototype.getVertices, + }, + { + proto: prototype, + property: 'worldVerticesLength', + getter: prototype.getWorldVerticesLength, + setter: prototype.setWorldVerticesLength, + }, + { + proto: prototype, + property: 'deformAttachment', + getter: prototype.getDeformAttachment, + setter: prototype.setDeformAttachment, + }, + ]; + propertyPolyfills.forEach((prop): void => { + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -473,10 +527,11 @@ function overrideProperty_ClippingAttachment (): void { proto: prototype, property: 'endSlot', getter: prototype.getEndSlot, + setter: prototype.setEndSlot, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -487,6 +542,7 @@ function overrideProperty_MeshAttachment (): void { proto: prototype, property: 'path', getter: prototype.getPath, + setter: prototype.setPath, }, { proto: prototype, @@ -496,7 +552,7 @@ function overrideProperty_MeshAttachment (): void { { proto: prototype, property: 'uvs', - getter: prototype.getUvs, + getter: prototype.getUVs, }, { proto: prototype, @@ -512,16 +568,19 @@ function overrideProperty_MeshAttachment (): void { proto: prototype, property: 'width', getter: prototype.getWidth, + setter: prototype.setWidth, }, { proto: prototype, property: 'height', getter: prototype.getHeight, + setter: prototype.setHeight, }, { proto: prototype, property: 'hullLength', getter: prototype.getHullLength, + setter: prototype.setHullLength, }, { proto: prototype, @@ -530,7 +589,7 @@ function overrideProperty_MeshAttachment (): void { }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -541,11 +600,13 @@ function overrideProperty_PathAttachment (): void { proto: prototype, property: 'closed', getter: prototype.getClosed, + setter: prototype.setClosed, }, { proto: prototype, property: 'constantSpeed', getter: prototype.getConstantSpeed, + setter: prototype.setConstantSpeed, }, ]; propertyPolyfills.forEach((prop): void => { @@ -561,20 +622,23 @@ function overrideProperty_PointAttachment (): void { proto: prototype, property: 'x', getter: prototype.getX, + setter: prototype.setX, }, { proto: prototype, property: 'y', getter: prototype.getY, + setter: prototype.setY, }, { proto: prototype, property: 'rotation', getter: prototype.getRotation, + setter: prototype.setRotation, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -585,36 +649,43 @@ function overrideProperty_RegionAttachment (): void { proto: prototype, property: 'x', getter: prototype.getX, + setter: prototype.setX, }, { proto: prototype, property: 'y', getter: prototype.getY, + setter: prototype.setY, }, { proto: prototype, property: 'scaleX', getter: prototype.getScaleX, + setter: prototype.setScaleX, }, { proto: prototype, property: 'scaleY', getter: prototype.getScaleY, + setter: prototype.setScaleY, }, { proto: prototype, property: 'rotation', getter: prototype.getRotation, + setter: prototype.setRotation, }, { proto: prototype, property: 'width', getter: prototype.getWidth, + setter: prototype.setWidth, }, { proto: prototype, property: 'height', getter: prototype.getHeight, + setter: prototype.setHeight, }, { proto: prototype, @@ -625,17 +696,13 @@ function overrideProperty_RegionAttachment (): void { proto: prototype, property: 'path', getter: prototype.getPath, + setter: prototype.setPath, }, { proto: prototype, property: 'rendererObject', getter: prototype.getRendererObject, }, - // { - // proto: prototype, - // property: 'region', - // getter: prototype.getProp_region, - // }, { proto: prototype, property: 'offset', @@ -645,10 +712,11 @@ function overrideProperty_RegionAttachment (): void { proto: prototype, property: 'uvs', getter: prototype.getUVs, + setter: prototype.setUVs, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -703,10 +771,11 @@ function overrideProperty_SlotData (): void { proto: prototype, property: 'blendMode', getter: prototype.getBlendMode, + setter: prototype.setBlendMode, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); } @@ -910,30 +979,35 @@ function overrideProperty_TransformConstraint (): void { proto: prototype, property: 'rotateMix', getter: prototype.getRotateMix, + setter: prototype.setRotateMix, }, { proto: prototype, property: 'translateMix', getter: prototype.getTranslateMix, + setter: prototype.setTranslateMix, }, { proto: prototype, property: 'scaleMix', getter: prototype.getScaleMix, + setter: prototype.setScaleMix, }, { proto: prototype, property: 'shearMix', getter: prototype.getShearMix, + setter: prototype.setShearMix, }, { proto: prototype, property: 'active', getter: prototype.getActive, + setter: prototype.setActive, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); } @@ -1092,6 +1166,24 @@ function overrideProperty_Bone (): void { propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); + + const worldToLocal = prototype.worldToLocal; + Object.defineProperty(prototype, 'worldToLocal', { + value (vec2: spine.Vector2) { + const vectors = worldToLocal.call(this, vec2.x, vec2.y); + vec2.x = vectors.get(0); + vec2.y = vectors.get(1); + }, + }); + + const localToWorld = prototype.localToWorld; + Object.defineProperty(prototype, 'localToWorld', { + value (vec2: spine.Vector2) { + const vectors = localToWorld.call(this, vec2.x, vec2.y); + vec2.x = vectors.get(0); + vec2.y = vectors.get(1); + }, + }); } function overrideProperty_Slot (): void { @@ -1155,6 +1247,17 @@ function overrideProperty_Skin (): void { } }, }); + const originFindNamesForSlot = prototype.findNamesForSlot; + Object.defineProperty(prototype, 'findNamesForSlot', { + value (slotIndex: number, names: Array) { + const vectors = originFindNamesForSlot.call(this, slotIndex); + const count = vectors.size(); + for (let i = 0; i < count; i++) { + const objPtr = vectors.get(i); + names.push(objPtr); + } + }, + }); } function overrideProperty_SkinEntry (): void { @@ -1191,8 +1294,8 @@ function overrideProperty_SkeletonClipping (): void { }, { proto: prototype, - property: 'UVs', - getter: prototype.getUVs, + property: 'clippedUVs', + getter: prototype.getClippedUVs, }, ]; propertyPolyfills.forEach((prop): void => { @@ -1212,55 +1315,65 @@ function overrideProperty_SkeletonData (): void { proto: prototype, property: 'defaultSkin', getter: prototype.getDefaultSkin, + setter: prototype.setDefaultSkin, }, { proto: prototype, property: 'x', getter: prototype.getX, + setter: prototype.setX, }, { proto: prototype, property: 'y', getter: prototype.getY, + setter: prototype.setY, }, { proto: prototype, property: 'width', getter: prototype.getWidth, + setter: prototype.setWidth, }, { proto: prototype, property: 'height', getter: prototype.getHeight, + setter: prototype.setHeight, }, { proto: prototype, property: 'version', getter: prototype.getVersion, + setter: prototype.setVersion, }, { proto: prototype, property: 'hash', getter: prototype.getHash, + setter: prototype.setHash, }, { proto: prototype, property: 'fps', getter: prototype.getFps, + setter: prototype.setFps, }, { proto: prototype, property: 'imagesPath', getter: prototype.getImagesPath, + setter: prototype.setImagesPath, }, { proto: prototype, property: 'audioPath', getter: prototype.getAudioPath, + setter: prototype.setAudioPath, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); @@ -1601,25 +1714,29 @@ function overrideProperty_Skeleton (): void { proto: prototype, property: 'scaleX', getter: prototype.getScaleX, + setter: prototype.setScaleX, }, { proto: prototype, property: 'scaleY', getter: prototype.getScaleY, + setter: prototype.setScaleY, }, { proto: prototype, property: 'x', getter: prototype.getX, + setter: prototype.setX, }, { proto: prototype, property: 'y', getter: prototype.getY, + setter: prototype.setY, }, ]; propertyPolyfills.forEach((prop): void => { - js.getset(prop.proto, prop.property, prop.getter); + js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); @@ -1698,6 +1815,7 @@ export function overrideSpineDefine (wasm): void { overrideProperty_PathAttachment(); overrideProperty_PointAttachment(); overrideProperty_RegionAttachment(); + overrideProperty_VertexAttachment(); overrideProperty_TextureAtlas(); overrideProperty_SlotData(); overrideProperty_IkConstraint(); diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 08c61481ddd..90c375bb127 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -51,7 +51,7 @@ const CUSTOM_SLOT_TEXTURE_BEGIN = 10000; let _slotTextureID = CUSTOM_SLOT_TEXTURE_BEGIN; type TrackListener = (x: spine.TrackEntry) => void; -type TrackListener2 = (x: spine.TrackEntry, ev: spine.Event) => void; +type TrackListener2 = (x: spine.TrackEntry, ev: spine.Event | number) => void; /** * @en * Animation playback rate. @@ -290,6 +290,14 @@ export class Skeleton extends UIRenderer { * @engineInternal */ public _debugRenderer: Graphics | null = null; + /** + * @engineInternal + */ + public _startSlotIndex; + /** + * @engineInternal + */ + public _endSlotIndex; private _slotTextures: Map | null = null; @@ -298,7 +306,8 @@ export class Skeleton extends UIRenderer { this._useVertexOpacity = true; this._startEntry = { animation: { name: '' }, trackIndex: 0 } as spine.TrackEntry; this._endEntry = { animation: { name: '' }, trackIndex: 0 } as spine.TrackEntry; - + this._startSlotIndex = -1; + this._endSlotIndex = -1; if (!JSB) { this._instance = new spine.SkeletonInstance(); } @@ -626,8 +635,6 @@ export class Skeleton extends UIRenderer { this._updateDebugDraw(); } - // For Redo, Undo - // call markForUpdateRenderData to make sure renderData will be re-built. /** * @engineInternal */ @@ -750,6 +757,71 @@ export class Skeleton extends UIRenderer { this._flushAssembler(); } + /** + * @en Sets slots visible range. + * @zh 设置骨骼插槽可视范围。 + * @param {Number} startSlotIndex @en start slot index. @zh 开始插槽的索引。 + * @param {Number} endSlotIndex @en end slot index. @zh 结束插槽的索引。 + */ + public setSlotsRange (startSlotIndex: number, endSlotIndex: number): void { + if (this.isAnimationCached()) { + warn('Slots visible range can not be modified in cached mode.'); + } else { + this._startSlotIndex = startSlotIndex; + this._endSlotIndex = endSlotIndex; + } + } + + /** + * @en + * Returns the attachment for the slot and attachment name. + * The skeleton looks first in its skin, then in the skeleton data’s default skin.
+ * Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Attachment object. + * @zh + * 通过 slot 和 attachment 的名称获取 attachment。Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。
+ * 返回一个 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Attachment 对象。 + * + * @method getAttachment + * @param {String} slotName @en slot name. @zh 插槽的名字。 + * @param {String} attachmentName @en attachment name. @en 附件的名称。 + * @return {sp.spine.Attachment} + */ + public getAttachment (slotName: string, attachmentName: string): spine.Attachment | null { + if (this._skeleton) { + return this._skeleton.getAttachmentByName(slotName, attachmentName); + } + return null; + } + + /** + * @en + * Sets the attachment for the slot and attachment name. + * The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @zh + * 通过 slot 和 attachment 的名字来设置 attachment。 + * Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。 + * @method setAttachment + * @param {String} slotName @en slot name. @zh 插槽的名字。 + * @param {String} attachmentName @en attachment name. @en 附件的名称。 + */ + public setAttachment (slotName: string, attachmentName: string): void { + if (this._skeleton) { + this._skeleton.setAttachment(slotName, attachmentName); + } + this.invalidAnimationCache(); + } + + /** + * @en + * Get Texture Atlas used in attachments. + * @zh + * 获取附件图集。 + * @param regionAttachment @en An attachment type of RegionAttachment or BoundingBoxAttachment. @zh RegionAttachment 或 BoundingBoxAttachment 的附件。 + * @return @en TextureRegion contains texture and atlas text information. @zh TextureRegion包含纹理和图集文本信息。 + */ + public getTextureAtlas (regionAttachment: spine.RegionAttachment | spine.BoundingBoxAttachment): spine.TextureRegion { + return (regionAttachment as spine.RegionAttachment).region; + } /** * @en Set the current animation. Any queued animations are cleared.
* @zh 设置当前动画。队列中的任何的动画将被清除。
@@ -798,7 +870,6 @@ export class Skeleton extends UIRenderer { this.markForUpdateRenderData(); return trackEntry; } - /** * @en Adds an animation to be played delay seconds after the current or last queued animation.
* Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry object. @@ -1652,15 +1723,18 @@ export class Skeleton extends UIRenderer { /** * @en Sets the complete event listener for specified TrackEntry. * @zh 用来为指定的 TrackEntry 设置动画一次循环播放结束的事件监听。 - * @param entry + * @param entry @en AnimationState track. @zn 动画轨道属性。 * @param listener @en Listener for registering callback functions. @zh 监听器对象,可注册回调方法。 */ public setTrackCompleteListener (entry: spine.TrackEntry, listener: TrackListener2): void { - // TODO - // TrackEntryListeners.getListeners(entry).complete = function (trackEntry) { - // const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); - // listener(trackEntry, loopCount); - // }; + const onComplete = (trackEntry: spine.TrackEntry): void => { + const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); + const listenerID = TrackEntryListeners.addListener(listener); + listener(trackEntry, loopCount); + this._instance.setListener(listenerID, spine.EventType.event); + this._listener!.event = listener; + }; + TrackEntryListeners.getListeners(entry).complete = onComplete; } /** diff --git a/native/cocos/editor-support/spine-wasm/CMakeLists.txt b/native/cocos/editor-support/spine-wasm/CMakeLists.txt index d7884343b91..339864386b3 100644 --- a/native/cocos/editor-support/spine-wasm/CMakeLists.txt +++ b/native/cocos/editor-support/spine-wasm/CMakeLists.txt @@ -7,7 +7,7 @@ set(APP_NAME "spine" CACHE STRING "Project Name") project(${APP_NAME}_wasm) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions -fno-rtti -DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions -frtti -DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=1") include_directories(../ ../../) @@ -17,7 +17,7 @@ file(GLOB COCOS_ADAPTER_SRC "./*.cpp") add_executable(${APP_NAME} ${SPINE_CORE_SRC} ${COCOS_ADAPTER_SRC} ) #add_executable(${APP_NAME} ${COCOS_ADAPTER_SRC}) -set(EMS_LINK_FLAGS "-O3 -s WASM=0 -s INITIAL_MEMORY=33554432 -s ALLOW_MEMORY_GROWTH=1 -s DYNAMIC_EXECUTION=0 -s ERROR_ON_UNDEFINED_SYMBOLS=0 \ +set(EMS_LINK_FLAGS "-O3 -s WASM=1 -s INITIAL_MEMORY=33554432 -s ALLOW_MEMORY_GROWTH=1 -s DYNAMIC_EXECUTION=0 -s ERROR_ON_UNDEFINED_SYMBOLS=0 \ -flto --no-entry --bind -s USE_ES6_IMPORT_META=0 -s EXPORT_ES6=1 -s MODULARIZE=1 -s EXPORT_NAME='spineWasm' \ -s ENVIRONMENT=web -s FILESYSTEM=0 -s NO_EXIT_RUNTIME=1 -s LLD_REPORT_UNDEFINED \ -s MIN_SAFARI_VERSION=110000 \ diff --git a/native/cocos/editor-support/spine-wasm/spine-skeleton-instance.cpp b/native/cocos/editor-support/spine-wasm/spine-skeleton-instance.cpp index f9f48916691..00d0d2af986 100644 --- a/native/cocos/editor-support/spine-wasm/spine-skeleton-instance.cpp +++ b/native/cocos/editor-support/spine-wasm/spine-skeleton-instance.cpp @@ -57,7 +57,7 @@ TrackEntry *SpineSkeletonInstance::setAnimation(float trackIndex, const std::str _skeleton->setToSetupPose(); return nullptr; } - auto *trackEntry = _animState->setAnimation(0, animation, loop); + auto *trackEntry = _animState->setAnimation(trackIndex, animation, loop); _animState->apply(*_skeleton); _skeleton->updateWorldTransform(); return trackEntry; diff --git a/native/cocos/editor-support/spine-wasm/spine-type-export.cpp b/native/cocos/editor-support/spine-wasm/spine-type-export.cpp index b5c22169054..f8d7bf54def 100644 --- a/native/cocos/editor-support/spine-wasm/spine-type-export.cpp +++ b/native/cocos/editor-support/spine-wasm/spine-type-export.cpp @@ -30,6 +30,16 @@ std::vector VECTOR_SP2STD(Vector &container) { return stdVector; } +template +std::vector> VECTOR_2_SP2STD(Vector> &container) { + int count = container.size(); + std::vector> stdVector(count); + for (int i = 0; i < count; i++) { + stdVector[i] = VECTOR_SP2STD(container[i]); + } + return stdVector; +} + template std::vector VECTOR_SP2STD2(Vector container) { int count = container.size(); @@ -40,10 +50,42 @@ std::vector VECTOR_SP2STD2(Vector container) { return stdVector; } +template +Vector VECTOR_STD2SP(std::vector &container) { + int count = container.size(); + Vector vecSP = Vector(); + vecSP.setSize(count, 0); + for (int i = 0; i < count; i++) { + vecSP[i] = container[i]; + } + return vecSP; +} + +template +Vector VECTOR_STD2SP_POINTER(std::vector &container) { + int count = container.size(); + Vector vecSP = Vector(); + vecSP.setSize(count, nullptr); + for (int i = 0; i < count; i++) { + vecSP[i] = container[i]; + } + return vecSP; +} + +template +void VECTOR_STD_COPY_SP(std::vector &stdVector, Vector &spVector) { + int count = stdVector.size(); + for (int i = 0; i < count; i++) { + stdVector[i] = spVector[i]; + } +} + } // namespace EMSCRIPTEN_BINDINGS(spine) { register_vector("VectorFloat"); + register_vector("VectorUnsignedShort"); + register_vector("VectorString"); register_vector("VectorBoneData"); register_vector("VectorBone"); register_vector("VectorSkinEntry"); @@ -149,36 +191,36 @@ EMSCRIPTEN_BINDINGS(spine) { .value("Clipping", AttachmentType_Clipping); ////////////////////////////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // class_("Vector") - // .constructor<>() - // .constructor() - // .function("size", &Vector::size); - - // class_("Pool") - // .constructor<>(); + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// class_("MathUtils") .class_property("PI", &MathUtil::Pi) .class_property("PI2", &MathUtil::Pi_2) - //.class_property("radiansToDegrees", &MathUtil::radiansToDegrees) .class_property("radDeg", &MathUtil::Rad_Deg) - //.class_property("degreesToRadians", &MathUtil::degreesToRadians) + .class_property("degreesToRadians", &MathUtil::Rad_Deg) + .class_property("degRad", &MathUtil::Deg_Rad) + .class_property("degreesToRadians", &MathUtil::Deg_Rad) + .class_function("abs", &MathUtil::abs) + .class_function("signum", &MathUtil::sign) .class_function("clamp", &MathUtil::clamp) - .class_function("cosDeg", &MathUtil::cosDeg) - .class_function("cosDeg", &MathUtil::cosDeg) + .class_function("fmod", &MathUtil::fmod) + .class_function("atan2", &MathUtil::atan2) + .class_function("cos", &MathUtil::cos) + .class_function("sin", &MathUtil::sin) + .class_function("sqrt", &MathUtil::sqrt) + .class_function("acos", &MathUtil::acos) .class_function("sinDeg", &MathUtil::sinDeg) - .class_function("signum", &MathUtil::sign); - //.class_function("toInt", &MathUtil::toInt) - //.class_function("cbrt", &MathUtil::randomTriangular) - //.class_function("randomTriangular", &MathUtil::randomTriangular) - //.class_function("randomTriangularWith", &MathUtil::randomTriangular); + .class_function("cosDeg", &MathUtil::cosDeg) + .class_function("isNan", &MathUtil::isNan) + .class_function("random", &MathUtil::random) + .class_function("randomTriangular", select_overload(&MathUtil::randomTriangular)) + .class_function("randomTriangularWith", select_overload(&MathUtil::randomTriangular)) + .class_function("pow", &MathUtil::pow); class_("Color") .constructor<>() .constructor() .function("set", static_cast(&Color::set)) - //.function("setFromColor", static_cast(&Color::set)) //no need .function("add", static_cast(&Color::add)) .function("clamp", &Color::clamp) .property("r", &Color::r) @@ -243,144 +285,199 @@ EMSCRIPTEN_BINDINGS(spine) { .function("setTranslateMix", &PathConstraintData::setTranslateMix); class_("SkeletonBounds") - //.function("getProp_minX", &SkeletonBounds::minX) - //.function("getProp_minY", &SkeletonBounds::minY) - //.function("getProp_maxX", &SkeletonBounds::maxX) - //.function("getProp_maxY", &SkeletonBounds::maxY) - //.function("getProp_boundingBoxes", &SkeletonBounds::boundingBoxes) - //.function("getProp_polygons", &SkeletonBounds::polygons) .function("update", &SkeletonBounds::update) - //.function("aabbCompute", &SkeletonBounds::aabbCompute) // private .function("aabbContainsPoint", &SkeletonBounds::aabbcontainsPoint) .function("aabbIntersectsSegment", &SkeletonBounds::aabbintersectsSegment) .function("aabbIntersectsSkeleton", &SkeletonBounds::aabbIntersectsSkeleton) - //.function("containsPoint", select_overload(&SkeletonBounds::containsPoint), allow_raw_pointers()) - //.function("containsPointPolygon", select_overload(&SkeletonBounds::containsPoint), allow_raw_pointers()) - //.function("intersectsSegment", select_overload(&SkeletonBounds::intersectsSegment)) - //.function("intersectsSegmentPolygon", select_overload(&SkeletonBounds::intersectsSegment), allow_raw_pointers()) + .function("containsPoint", optional_override([](SkeletonBounds &obj, float x, float y) { + return obj.containsPoint(x, y); }),allow_raw_pointers()) + .function("containsPointPolygon", optional_override([](SkeletonBounds &obj,Polygon* polygon, float x, float y) { + return obj.containsPoint(polygon, x, y); }),allow_raw_pointers()) + .function("intersectsSegment", optional_override([](SkeletonBounds &obj, float x1, float y1, float x2, float y2){ + return obj.intersectsSegment(x1, y1, x2, y2); }),allow_raw_pointers()) + .function("intersectsSegmentPolygon", optional_override([](SkeletonBounds &obj,Polygon* polygon, + float x1, float y1, float x2, float y2){ + return obj.intersectsSegment(polygon, x1, y1, x2, y2); }),allow_raw_pointers()) .function("getPolygon", &SkeletonBounds::getPolygon, allow_raw_pointers()) .function("getWidth", &SkeletonBounds::getWidth) .function("getHeight", &SkeletonBounds::getHeight); class_("Event") .constructor() - .function("getData", &Event::getData) + .function("getData", optional_override([](Event &obj) { + return &obj.getData(); }), allow_raw_pointers()) .function("getIntValue", &Event::getIntValue) + .function("setIntValue", &Event::setIntValue) .function("getFloatValue", &Event::getFloatValue) - .function("getStringValue", optional_override([](Event &obj) { return STRING_SP2STD(obj.getStringValue()); })) + .function("setFloatValue", &Event::setFloatValue) + .function("getStringValue", optional_override([](Event &obj) { + return STRING_SP2STD(obj.getStringValue()); })) + .function("setStringValue", optional_override([](Event &obj, const std::string &name) { + return obj.setStringValue(STRING_STD2SP(name)); }), allow_raw_pointers()) .function("getTime", &Event::getTime) .function("getVolume", &Event::getVolume) - .function("getBalance", &Event::getBalance); + .function("setVolume", &Event::setVolume) + .function("getBalance", &Event::getBalance) + .function("setBalance", &Event::setBalance); class_("EventData") .constructor() - .function("getName", optional_override([](EventData &obj) { return STRING_SP2STD(obj.getName()); })) + .function("getName", optional_override([](EventData &obj) { + return STRING_SP2STD(obj.getName()); })) .function("getIntValue", &EventData::getIntValue) + .function("setIntValue", &EventData::setIntValue) .function("getFloatValue", &EventData::getFloatValue) - .function("getStringValue", optional_override([](EventData &obj) { return STRING_SP2STD(obj.getStringValue()); })) - .function("getAudioPath", optional_override([](EventData &obj) { return STRING_SP2STD(obj.getAudioPath()); })) + .function("setFloatValue", &EventData::setFloatValue) + .function("getStringValue", optional_override([](EventData &obj) { + return STRING_SP2STD(obj.getStringValue()); })) + .function("setStringValue", optional_override([](EventData &obj, const std::string &name) { + return obj.setStringValue(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("getAudioPath", optional_override([](EventData &obj) { + return STRING_SP2STD(obj.getAudioPath()); })) + .function("setAudioPath", optional_override([](EventData &obj, const std::string &name) { + return obj.setAudioPath(STRING_STD2SP(name)); }), allow_raw_pointers()) .function("getVolume", &EventData::getVolume) - .function("getBalance", &EventData::getBalance); + .function("setVolume", &EventData::setVolume) + .function("getBalance", &EventData::getBalance) + .function("setBalance", &EventData::setBalance); class_("Attachment") - .function("getName", optional_override([](Attachment &obj) { return STRING_SP2STD(obj.getName()); })); + .function("getName", optional_override([](Attachment &obj) { + return STRING_SP2STD(obj.getName()); })); // pure_virtual and raw pointer class_>("VertexAttachment") - //.constructor() - .function("getProp_id", &VertexAttachment::getId) - .function("getProp_bones", &VertexAttachment::getBones) - .function("getProp_vertices", &VertexAttachment::getVertices) - .function("getProp_worldVerticesLength", &VertexAttachment::getWorldVerticesLength) - .function("getProp_deformAttachment", &VertexAttachment::getDeformAttachment, allow_raw_pointer()) - .function("getProp_name", &VertexAttachment::getName) - //.function("computeWorldVertices", &VertexAttachment::computeWorldVertices); - .function("copy", &VertexAttachment::copy, allow_raw_pointer()) - .function("copyTo", &VertexAttachment::copyTo, allow_raw_pointer()); + .function("id", &VertexAttachment::getId) + .function("getBones", optional_override([](VertexAttachment &obj) { + return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) + .function("getVertices", optional_override([](VertexAttachment &obj) { + return VECTOR_SP2STD(obj.getVertices()); }), allow_raw_pointers()) + .function("getWorldVerticesLength", &VertexAttachment::getWorldVerticesLength) + .function("setWorldVerticesLength", &VertexAttachment::setWorldVerticesLength) + .function("getDeformAttachment", &VertexAttachment::getDeformAttachment, allow_raw_pointer()) + .function("setDeformAttachment", &VertexAttachment::setDeformAttachment, allow_raw_pointer()) + .function("computeWorldVertices", optional_override([](VertexAttachment &obj, Slot &slot, size_t start, size_t count, std::vector worldVertices, size_t offset, size_t stride){ + auto spWorldVertices = VECTOR_STD2SP(worldVertices); + obj.computeWorldVertices(slot, start, count, spWorldVertices, offset, stride); + VECTOR_STD_COPY_SP(worldVertices, spWorldVertices); + })) + .function("copyTo", &VertexAttachment::copyTo, allow_raw_pointers()); class_>("BoundingBoxAttachment") .constructor() - .function("getName", optional_override([](BoundingBoxAttachment &obj) { return STRING_SP2STD(obj.getName()); })) + .function("getName", optional_override([](BoundingBoxAttachment &obj) { + return STRING_SP2STD(obj.getName()); })) .function("copy", &BoundingBoxAttachment::copy, allow_raw_pointers()); - //.function("getProp_color", &BoundingBoxAttachment::getColor) class_>("ClippingAttachment") .constructor() - .function("getEndSlot", &ClippingAttachment::getEndSlot, allow_raw_pointer()) - .function("copy", &ClippingAttachment::copy, allow_raw_pointer()); - //.function("getProp_color", &ClippingAttachment::getColor) + .function("getEndSlot", &ClippingAttachment::getEndSlot, allow_raw_pointers()) + .function("setEndSlot", &ClippingAttachment::setEndSlot, allow_raw_pointers()) + .function("copy", &ClippingAttachment::copy, allow_raw_pointers()); class_>("MeshAttachment") .constructor() - //.function("getProp_region", &MeshAttachment::getRegion) - .function("getPath", optional_override([](MeshAttachment &obj) { return STRING_SP2STD(obj.getPath()); })) - .function("getRegionUVs", &MeshAttachment::getRegionUVs) - .function("getUVs", &MeshAttachment::getUVs) - .function("getTriangles", &MeshAttachment::getTriangles) - .function("getColor", &MeshAttachment::getColor) + .function("getPath", optional_override([](MeshAttachment &obj) { + return STRING_SP2STD(obj.getPath()); })) + .function("setPath", &MeshAttachment::setPath) + .function("getRegionUVs", optional_override([](MeshAttachment &obj) { + return VECTOR_SP2STD(obj.getRegionUVs());})) + .function("getUVs", optional_override([](MeshAttachment &obj) { + return VECTOR_SP2STD(obj.getUVs());}), allow_raw_pointers()) + .function("getTriangles", optional_override([](MeshAttachment &obj) { + return VECTOR_SP2STD(obj.getTriangles());}), allow_raw_pointers()) + .function("getColor", optional_override([](MeshAttachment &obj) { + return &obj.getColor(); }), allow_raw_pointers()) .function("getWidth", &MeshAttachment::getWidth) + .function("setWidth", &MeshAttachment::setWidth) .function("getHeight", &MeshAttachment::getHeight) + .function("setHeight", &MeshAttachment::setHeight) .function("getHullLength", &MeshAttachment::getHullLength) - .function("getEdges", &MeshAttachment::getEdges) - //.function("getProp_tempColor", &MeshAttachment::getTempColor) // no tempColor + .function("setHullLength", &MeshAttachment::setHullLength) + .function("getEdges", optional_override([](MeshAttachment &obj) { + return VECTOR_SP2STD(obj.getEdges());})) .function("updateUVs", &MeshAttachment::updateUVs) - .function("getParentMesh", &MeshAttachment::getParentMesh, allow_raw_pointer()) - .function("setParentMesh", &MeshAttachment::setParentMesh, allow_raw_pointer()) - .function("copy", &MeshAttachment::copy, allow_raw_pointer()) - .function("newLinkedMesh", &MeshAttachment::newLinkedMesh, allow_raw_pointer()); + .function("getParentMesh", &MeshAttachment::getParentMesh, allow_raw_pointers()) + .function("setParentMesh", &MeshAttachment::setParentMesh, allow_raw_pointers()) + .function("copy", &MeshAttachment::copy, allow_raw_pointers()) + .function("newLinkedMesh", &MeshAttachment::newLinkedMesh, allow_raw_pointers()); class_>("PathAttachment") .constructor() - .function("getLengths", optional_override([](PathAttachment &obj) { return VECTOR_SP2STD(obj.getLengths()); })) + .function("getLengths", optional_override([](PathAttachment &obj) { + return VECTOR_SP2STD(obj.getLengths()); })) .function("getClosed", &PathAttachment::isClosed) + .function("setClosed", &PathAttachment::setClosed) .function("getConstantSpeed", &PathAttachment::isConstantSpeed) - //.function("getProp_color", &MeshAttachment::getColor) // no color + .function("setConstantSpeed", &PathAttachment::setConstantSpeed) .function("copy", &PathAttachment::copy, allow_raw_pointers()); class_>("PointAttachment") .constructor() .function("getX", &PointAttachment::getX) + .function("setX", &PointAttachment::setX) .function("getY", &PointAttachment::getY) + .function("setY", &PointAttachment::setY) .function("getRotation", &PointAttachment::getRotation) - //.function("computeWorldPosition", &PointAttachment::computeWorldPosition) //reference type + .function("setRotation", &PointAttachment::setRotation) + .function("computeWorldPosition", optional_override([](PointAttachment &obj, Bone &bone, float ox, float oy) { + obj.computeWorldPosition(bone, ox, oy);})) .function("computeWorldRotation", &PointAttachment::computeWorldRotation) - //.function("getProp_color", &PointAttachment::getColor) // no color - .function("copy", &PointAttachment::copy, allow_raw_pointer()); - - //class_("HasRendererObject") - // .constructor<>(); + .function("copy", &PointAttachment::copy, allow_raw_pointers()); class_>("RegionAttachment") .constructor() - // static U4: number; - // static V4: number; - // ....... .function("getX", &RegionAttachment::getX) + .function("setX", &RegionAttachment::setX) .function("getY", &RegionAttachment::getY) + .function("setY", &RegionAttachment::setY) .function("getScaleX", &RegionAttachment::getScaleX) + .function("setScaleX", &RegionAttachment::setScaleX) .function("getScaleY", &RegionAttachment::getScaleY) + .function("setScaleY", &RegionAttachment::setScaleY) .function("getRotation", &RegionAttachment::getRotation) + .function("setRotation", &RegionAttachment::setRotation) .function("getWidth", &RegionAttachment::getWidth) + .function("setWidth", &RegionAttachment::setWidth) .function("getHeight", &RegionAttachment::getHeight) - .function("getColor", &RegionAttachment::getColor) - .function("getPath", optional_override([](RegionAttachment &obj) { return STRING_SP2STD(obj.getPath()); })) - .function("getRendererObject", &RegionAttachment::getRendererObject, allow_raw_pointer()) - //.function("getProp_region", &PointAttachment::getRegion) + .function("setHeight", &RegionAttachment::setHeight) + .function("getColor", optional_override([](RegionAttachment &obj) { + return &obj.getColor(); }), allow_raw_pointers()) + .function("getPath", optional_override([](RegionAttachment &obj) { + return STRING_SP2STD(obj.getPath()); })) + .function("setPath", &RegionAttachment::setPath) + .function("getRendererObject", &RegionAttachment::getRendererObject, allow_raw_pointers()) .function("getOffset", &RegionAttachment::getOffset) - .function("getUVs", &RegionAttachment::getUVs) - //.function("getProp_tempColor", &PointAttachment::getTempColor) // have no tempColor + .function("setUVs", optional_override([](RegionAttachment &obj, std::vector &data) { + auto uvs = obj.getUVs(); + int count = data.size(); + float u = count > 1 ? data[0] : uvs[0]; + float v = count > 2 ? data[1] : uvs[1]; + float u2 = count > 3 ? data[2] : uvs[2]; + float v2 = count > 4 ? data[3] : uvs[3]; + bool rotate = count > 5 ? (data[4] != 0) : false; + obj.setUVs(u, v, u2, v2, rotate); + }), allow_raw_pointers()) + .function("getUVs", optional_override([](RegionAttachment &obj) { + return VECTOR_SP2STD(obj.getUVs());}), allow_raw_pointers()) .function("updateOffset", &RegionAttachment::updateOffset) - //.function("setRegion", &RegionAttachment::setRegion) // have no setRegion + .function("computeWorldVertices", optional_override([]( + RegionAttachment &obj, Bone &bone, std::vector worldVertices, + size_t offset, size_t stride){ + auto spWorldVertices = VECTOR_STD2SP(worldVertices); + obj.computeWorldVertices(bone, spWorldVertices, offset, stride); + VECTOR_STD_COPY_SP(worldVertices, spWorldVertices); + })) .function("copy", &RegionAttachment::copy, allow_raw_pointer()); - // class_("AttachmentLoader") - // .constructor<>() - // .function("newClippingAttachment", &AttachmentLoader::newClippingAttachment, pure_virtual(), allow_raw_pointer()) - // .function("newPointAttachment", &AttachmentLoader::newPointAttachment, pure_virtual(), allow_raw_pointer()) - // .function("newPathAttachment", &AttachmentLoader::newPathAttachment, pure_virtual(), allow_raw_pointer()) - // .function("newBoundingBoxAttachment", &AttachmentLoader::newBoundingBoxAttachment, pure_virtual(), allow_raw_pointer()) - // .function("newMeshAttachment", &AttachmentLoader::newMeshAttachment, pure_virtual(), allow_raw_pointer()) - // .function("newRegionAttachment", &AttachmentLoader::newRegionAttachment, pure_virtual(), allow_raw_pointer()); + class_("AttachmentLoader") + //.constructor<>() + .function("newClippingAttachment", &AttachmentLoader::newClippingAttachment, pure_virtual(), allow_raw_pointers()) + .function("newPointAttachment", &AttachmentLoader::newPointAttachment, pure_virtual(), allow_raw_pointers()) + .function("newPathAttachment", &AttachmentLoader::newPathAttachment, pure_virtual(), allow_raw_pointers()) + .function("newBoundingBoxAttachment", &AttachmentLoader::newBoundingBoxAttachment, pure_virtual(), allow_raw_pointers()) + .function("newMeshAttachment", &AttachmentLoader::newMeshAttachment, pure_virtual(), allow_raw_pointers()) + .function("newRegionAttachment", &AttachmentLoader::newRegionAttachment, pure_virtual(), allow_raw_pointers()); class_>("AtlasAttachmentLoader") .constructor() @@ -390,11 +487,11 @@ EMSCRIPTEN_BINDINGS(spine) { .function("newPathAttachment", &AtlasAttachmentLoader::newPathAttachment, allow_raw_pointer()) .function("newPointAttachment", &AtlasAttachmentLoader::newPointAttachment, allow_raw_pointer()) .function("newClippingAttachment", &AtlasAttachmentLoader::newClippingAttachment, allow_raw_pointer()); - //.function("getProp_atlas") class_("TextureAtlasPage") .constructor() - .function("getName", optional_override([](AtlasPage &obj) { return STRING_SP2STD((const String)obj.name); })) + .function("getName", optional_override([](AtlasPage &obj) { + return STRING_SP2STD((const String)obj.name); })) .property("minFilter", &AtlasPage::minFilter) .property("magFilter", &AtlasPage::magFilter) .property("uWrap", &AtlasPage::uWrap) @@ -405,20 +502,19 @@ EMSCRIPTEN_BINDINGS(spine) { class_("TextureAtlasRegion") //.property("page", &AtlasRegion::page) - .function("getName", optional_override([](AtlasRegion &obj) { return STRING_SP2STD((const String)obj.name); })) + .function("getName", optional_override([](AtlasRegion &obj) { + return STRING_SP2STD((const String)obj.name); })) .property("x", &AtlasRegion::x) .property("y", &AtlasRegion::y) .property("index", &AtlasRegion::index) .property("rotate", &AtlasRegion::rotate) .property("degrees", &AtlasRegion::degrees); - //.property("texture", &AtlasRegion::height) + //.property("texture", &AtlasRegion::height) class_("TextureAtlas") .constructor() - //.function("getProp_pages") - //.function("getProp_regions") - .function("findRegion", optional_override([](Atlas &obj, const std::string &name) { return obj.findRegion(STRING_STD2SP(name)); }), allow_raw_pointers()); - //.function("dispose"); + .function("findRegion", optional_override([](Atlas &obj, const std::string &name) { + return obj.findRegion(STRING_STD2SP(name)); }), allow_raw_pointers()); class_>("Pow") .constructor() @@ -436,31 +532,19 @@ EMSCRIPTEN_BINDINGS(spine) { // .property("x", &Vector2::x) // .property("y", &Vector2::y); - class_("BoneData") - .constructor() - .function("getIndex", &BoneData::getIndex) - .function("getName", optional_override([](BoneData &obj) { return STRING_SP2STD(obj.getName()); })) - .function("getParent", &BoneData::getParent, allow_raw_pointer()) - .function("getLength", &BoneData::getLength) - .function("getX", &BoneData::getX) - .function("getY", &BoneData::getY) - .function("getRotation", &BoneData::getRotation) - .function("getScaleX", &BoneData::getScaleX) - .function("getScaleY", &BoneData::getScaleY) - .function("getShearX", &BoneData::getShearX) - .function("getShearY", &BoneData::getShearY) - .function("getTransformMode", &BoneData::getTransformMode) - .function("getSkinRequired", &BoneData::isSkinRequired); - //.function("getProp_color", &BoneData::isSkinRequired) // have no color - class_("SlotData") .constructor() .function("getIndex", &SlotData::getIndex) - .function("getName", optional_override([](SlotData &obj) { return STRING_SP2STD(obj.getName()); })) - .function("getBoneData", &SlotData::getBoneData) - .function("getColor", &SlotData::getColor) - .function("getDarkColor", &SlotData::getDarkColor) - .function("getBlendMode", &SlotData::getBlendMode); + .function("getName", optional_override([](SlotData &obj) { + return STRING_SP2STD(obj.getName()); })) + .function("getBoneData", optional_override([](SlotData &obj) { + return &obj.getBoneData(); }), allow_raw_pointers()) + .function("getColor", optional_override([](SlotData &obj) { + return &obj.getColor();}), allow_raw_pointers()) + .function("getDarkColor", optional_override([](SlotData &obj) { + return &obj.getDarkColor();}), allow_raw_pointers()) + .function("getBlendMode", &SlotData::getBlendMode) + .function("setBlendMode", &SlotData::setBlendMode); class_("Updatable") .function("update", &Updatable::update, pure_virtual()) @@ -468,8 +552,10 @@ EMSCRIPTEN_BINDINGS(spine) { class_>("IkConstraint") .constructor() - .function("getData", &IkConstraint::getData) - .function("getBones", optional_override([](IkConstraint &obj) { return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) + .function("getData", optional_override([](IkConstraint &obj){ + return &obj.getData(); }), allow_raw_pointers()) + .function("getBones", optional_override([](IkConstraint &obj) { + return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) .function("getTarget", &IkConstraint::getTarget, allow_raw_pointer()) .function("setTarget", &IkConstraint::setTarget, allow_raw_pointer()) .function("getBendDirection", &IkConstraint::getBendDirection) @@ -487,19 +573,23 @@ EMSCRIPTEN_BINDINGS(spine) { .function("isActive", &IkConstraint::isActive) .function("apply", static_cast(&IkConstraint::apply)) .function("update", &IkConstraint::update) - //.function("apply1", static_cast(&IkConstraint::apply)) - //.function("apply2", static_cast(&IkConstraint::apply)) - ; + .class_function("apply1", optional_override([]( + IkConstraint &obj, Bone &bone, float targetX, float targetY, + bool compress, bool stretch, bool uniform, float alpha){ + obj.apply(bone, targetX, targetY, compress, stretch, uniform, alpha); + })) + .class_function("apply2", optional_override([]( + IkConstraint &obj, Bone &parent, Bone &child, float targetX, float targetY, + int bendDir, bool stretch, float softness, float alpha){ + obj.apply(parent, child, targetX, targetY, bendDir, stretch, softness, alpha); + })); class_>("PathConstraint") .constructor() - // private but no need, just wrap in js - // static const float EPSILON; - // static const int NONE; - // static const int BEFORE; - // static const int AFTER; - .function("getData", &PathConstraint::getData) - .function("getBones", optional_override([](PathConstraint &obj) { return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) + .function("getData", optional_override([](PathConstraint &obj) { + return &obj.getData(); }), allow_raw_pointers()) + .function("getBones", optional_override([](PathConstraint &obj) { + return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) .function("getTarget", &PathConstraint::getTarget, allow_raw_pointer()) .function("setTarget", &PathConstraint::setTarget, allow_raw_pointer()) .function("getPosition", &PathConstraint::getPosition) @@ -510,27 +600,17 @@ EMSCRIPTEN_BINDINGS(spine) { .function("setRotateMix", &PathConstraint::setRotateMix) .function("getTranslateMix", &PathConstraint::getTranslateMix) .function("getTranslateMix", &PathConstraint::setTranslateMix) - //.function("getProp_spaces", &PathConstraint::spaces) - //.function("getProp_positions", &PathConstraint::positions) - //.function("getProp_world", &PathConstraint::world) - //.function("getProp_curves", &PathConstraint::curves) - //.function("getProp_lengths", &PathConstraint::lengths) - //.function("getProp_segments", &PathConstraint::segments) .function("getActive", &PathConstraint::isActive) .function("isActive", &PathConstraint::isActive) .function("setActive", &PathConstraint::setActive) .function("apply", &PathConstraint::apply) - .function("update", &PathConstraint::update) - //.function("computeWorldPositions", &PathConstraint::computeWorldPositions) - //.function("addBeforePosition", &PathConstraint::addBeforePosition) - //.function("addAfterPosition", &PathConstraint::addAfterPosition) - //.function("addCurvePosition", &PathConstraint::addCurvePosition) // private - ; + .function("update", &PathConstraint::update); class_>("TransformConstraintData") .constructor() - .function("getBones", optional_override([](TransformConstraintData &obj) { return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) - .function("getTarget", &TransformConstraintData::getTarget, allow_raw_pointer()) + .function("getBones", optional_override([](TransformConstraintData &obj) { + return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) + .function("getTarget", &TransformConstraintData::getTarget, allow_raw_pointers()) .function("getRotateMix", &TransformConstraintData::getRotateMix) .function("getTranslateMix", &TransformConstraintData::getTranslateMix) .function("getScaleMix", &TransformConstraintData::getScaleMix) @@ -546,52 +626,79 @@ EMSCRIPTEN_BINDINGS(spine) { class_>("TransformConstraint") .constructor() - .function("getData", &TransformConstraint::getData) - .function("getBones", optional_override([](TransformConstraint &obj) { return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) - .function("getTarget", &TransformConstraint::getTarget, allow_raw_pointer()) + .function("getData", optional_override([](TransformConstraint &obj){ + return &obj.getData();}), allow_raw_pointers()) + .function("getBones", optional_override([](TransformConstraint &obj) { + return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) + .function("getTarget", &TransformConstraint::getTarget, allow_raw_pointers()) .function("getRotateMix", &TransformConstraint::getRotateMix) + .function("setRotateMix", &TransformConstraint::setRotateMix) .function("getTranslateMix", &TransformConstraint::getTranslateMix) + .function("setTranslateMix", &TransformConstraint::setTranslateMix) .function("getScaleMix", &TransformConstraint::getScaleMix) + .function("setScaleMix", &TransformConstraint::setScaleMix) .function("getShearMix", &TransformConstraint::getShearMix) - //.function("getProp_temp") // no + .function("setShearMix", &TransformConstraint::setShearMix) .function("getActive", &TransformConstraint::isActive) + .function("setActive", &TransformConstraint::setActive) .function("isActive", &TransformConstraint::isActive) .function("apply", &TransformConstraint::apply) .function("update", &TransformConstraint::update); - //.function("applyAbsoluteWorld", &TransformConstraint::applyAbsoluteWorld) - //.function("applyRelativeWorld", &TransformConstraint::applyRelativeWorld) - //.function("applyAbsoluteLocal", &TransformConstraint::applyAbsoluteLocal) - //.function("applyRelativeLocal", &TransformConstraint::applyRelativeLocal) class_>("Bone") .constructor() - .function("getData", &Bone::getData) - .function("getSkeleton", &Bone::getSkeleton) - .function("getParent", &Bone::getParent, allow_raw_pointers()) - //.function("getProp_children", &Bone::getChildren) + .function("getData", optional_override([](Bone &obj) { + return &obj.getData(); }), allow_raw_pointers()) + .function("getSkeleton", optional_override([](Bone &obj) { + return &obj.getSkeleton(); }), allow_raw_pointers()) + .function("getParent", optional_override([](Bone &obj) { + return obj.getParent(); }), allow_raw_pointers()) + .function("getChildren", optional_override([](Bone &obj) { + return VECTOR_SP2STD(obj.getChildren()); }), allow_raw_pointers()) .function("getX", &Bone::getX) + .function("setX", &Bone::setX) .function("getY", &Bone::getY) + .function("setY", &Bone::setY) .function("getRotation", &Bone::getRotation) + .function("setRotation", &Bone::setRotation) .function("getScaleX", &Bone::getScaleX) + .function("setScaleX", &Bone::setScaleX) .function("getScaleY", &Bone::getScaleY) + .function("setScaleY", &Bone::setScaleY) .function("getShearX", &Bone::getShearX) + .function("setShearX", &Bone::setShearX) .function("getShearY", &Bone::getShearY) + .function("setShearY", &Bone::setShearY) .function("getAX", &Bone::getAX) + .function("setAX", &Bone::setAX) .function("getAY", &Bone::getAY) + .function("setAY", &Bone::setAY) .function("getARotation", &Bone::getAppliedRotation) + .function("setARotation", &Bone::setAppliedRotation) .function("getAScaleX", &Bone::getAScaleX) + .function("setAScaleX", &Bone::setAScaleX) .function("getAScaleY", &Bone::getAScaleY) + .function("setAScaleY", &Bone::setAScaleY) .function("getAShearX", &Bone::getAShearX) + .function("setAShearX", &Bone::setAShearX) .function("getAShearY", &Bone::getAShearY) + .function("setAShearY", &Bone::setAShearY) .function("getAppliedValid", &Bone::isAppliedValid) + .function("setAppliedValid", &Bone::setAppliedValid) .function("getA", &Bone::getA) + .function("setA", &Bone::setA) .function("getB", &Bone::getB) + .function("setB", &Bone::setB) .function("getC", &Bone::getC) + .function("setC", &Bone::setC) .function("getD", &Bone::getD) - .function("getWorldY", &Bone::getWorldY) + .function("setD", &Bone::setD) .function("getWorldX", &Bone::getWorldX) - //.function("getProp_sorted", &Bone::getSorted) + .function("setWorldX", &Bone::setWorldX) + .function("getWorldY", &Bone::getWorldY) + .function("setWorldY", &Bone::setWorldY) .function("getActive", &Bone::isActive) + .function("setActive", &Bone::setActive) .function("isActive", &Bone::isActive) .function("update", &Bone::update) .function("updateWorldTransform", select_overload(&Bone::updateWorldTransform)) @@ -600,44 +707,65 @@ EMSCRIPTEN_BINDINGS(spine) { .function("getWorldRotationX", &Bone::getWorldRotationX) .function("getWorldRotationY", &Bone::getWorldRotationY) .function("getWorldScaleX", &Bone::getWorldScaleX) - .function("getWorldScaleY", &Bone::getWorldScaleY) - //.function("updateAppliedTransform", &Bone::updateAppliedTransform) - //.function("worldToLocal", &Bone::worldToLocal) - //.function("localToWorld", &Bone::localToWorld) + .function("getWorldScaleY", &Bone::getWorldScaleY) + .function("worldToLocal", optional_override([](Bone &obj, float a, float b) { + std::vector vec2(2); + obj.worldToLocal(a, b, vec2[0], vec2[1]); + return vec2; + }), + allow_raw_pointers() + ) + .function("localToWorld", optional_override([](Bone &obj, float a, float b) { + std::vector vec2(2); + obj.localToWorld(a, b, vec2[0], vec2[1]); + return vec2; + }), + allow_raw_pointers() + ) .function("worldToLocalRotation", &Bone::worldToLocalRotation) .function("localToWorldRotation", &Bone::localToWorldRotation) - .function("rotateWorld", &Bone::rotateWorld) - .function("setX", &Bone::setX) - .function("setY", &Bone::setY) - .function("setRotation", &Bone::setRotation) - .function("setScaleX", &Bone::setScaleX) - .function("setScaleY", &Bone::setScaleY) - .function("setShearX", &Bone::setShearX) - .function("setShearY", &Bone::setShearY) - .function("setAX", &Bone::setAX) - .function("setAY", &Bone::setAY) - .function("setARotation", &Bone::setAppliedRotation) - .function("setAScaleX", &Bone::setAScaleX) - .function("setAScaleY", &Bone::setAScaleY) - .function("setAShearX", &Bone::setAShearX) - .function("setAShearY", &Bone::setAShearY) - .function("setAppliedValid", &Bone::setAppliedValid) - .function("setA", &Bone::setA) - .function("setB", &Bone::setB) - .function("setC", &Bone::setC) - .function("setD", &Bone::setD) - .function("setWorldX", &Bone::setWorldX) - .function("setWorldY", &Bone::setWorldY) - .function("setActive", &Bone::setActive); + .function("rotateWorld", &Bone::rotateWorld); + + class_("BoneData") + .constructor() + .function("getIndex", &BoneData::getIndex) + .function("getName", optional_override([](BoneData &obj) { return STRING_SP2STD(obj.getName()); })) + .function("getParent", &BoneData::getParent, allow_raw_pointer()) + .function("getLength", &BoneData::getLength) + .function("setLength", &BoneData::setLength) + .function("getX", &BoneData::getX) + .function("setX", &BoneData::setX) + .function("getY", &BoneData::getY) + .function("setY", &BoneData::setY) + .function("getRotation", &BoneData::getRotation) + .function("setRotation", &BoneData::setRotation) + .function("getScaleX", &BoneData::getScaleX) + .function("setScaleX", &BoneData::setScaleX) + .function("getScaleY", &BoneData::getScaleY) + .function("setScaleY", &BoneData::setScaleY) + .function("getShearX", &BoneData::getShearX) + .function("setShearX", &BoneData::setShearX) + .function("getShearY", &BoneData::getShearY) + .function("setShearY", &BoneData::setShearY) + .function("getTransformMode", &BoneData::getTransformMode) + .function("setTransformMode", &BoneData::setTransformMode) + .function("getSkinRequired", &BoneData::isSkinRequired) + .function("setShinRequired", &BoneData::setSkinRequired); class_("Slot") .constructor() - .function("getData", &Slot::getData) - .function("getBone", &Slot::getBone) - .function("getColor", &Slot::getColor) - .function("getDarkColor", &Slot::getDarkColor) - .function("getDeform", &Slot::getDeform) - .function("getSkeleton", &Slot::getSkeleton) + .function("getData", optional_override([](Slot &obj) { + return &obj.getData(); }), allow_raw_pointers()) + .function("getBone", optional_override([](Slot &obj) { + return &obj.getBone(); }), allow_raw_pointers()) + .function("getColor", optional_override([](Slot &obj) { + return &obj.getColor(); }), allow_raw_pointers()) + .function("getDarkColor", optional_override([](Slot &obj) { + return &obj.getDarkColor(); }), allow_raw_pointers()) + .function("getDeform", optional_override([](Slot &obj) { + return VECTOR_SP2STD(obj.getDeform());}), allow_raw_pointers()) + .function("getSkeleton", optional_override([](Slot &obj) { + return &obj.getSkeleton(); }), allow_raw_pointers()) .function("getAttachment", &Slot::getAttachment, allow_raw_pointers()) .function("setAttachment", &Slot::setAttachment, allow_raw_pointers()) .function("setAttachmentTime", &Slot::setAttachmentTime) @@ -646,39 +774,52 @@ EMSCRIPTEN_BINDINGS(spine) { class_("Skin") .constructor() - .function("getName", optional_override([](Skin &obj) { return STRING_SP2STD(obj.getName()); })) - .function("getBones", optional_override([](Skin &obj) { return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) - .function("getConstraints", optional_override([](Skin &obj) { return VECTOR_SP2STD(obj.getConstraints()); }), allow_raw_pointers()) - .function("setAttachment", optional_override([](Skin &obj, size_t index, const std::string &name, Attachment *attachment) { return obj.setAttachment(index, STRING_STD2SP(name), attachment); }), allow_raw_pointers()) + .function("getName", optional_override([](Skin &obj) { + return STRING_SP2STD(obj.getName()); })) + .function("getBones", optional_override([](Skin &obj) { + return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) + .function("getConstraints", optional_override([](Skin &obj) { + return VECTOR_SP2STD(obj.getConstraints()); }), allow_raw_pointers()) + .function("setAttachment", optional_override([](Skin &obj, size_t index, + const std::string &name, Attachment *attachment) { + return obj.setAttachment(index, STRING_STD2SP(name), attachment); + }), allow_raw_pointers()) .function("addSkin", select_overload(&Skin::addSkin), allow_raw_pointers()) .function("copySkin", select_overload(&Skin::copySkin), allow_raw_pointers()) - .function("getAttachment", optional_override([](Skin &obj, size_t slotIndex, const std::string &name) { - return obj.getAttachment(slotIndex, STRING_STD2SP(name)); - }), - allow_raw_pointers()) + .function("findNamesForSlot", optional_override([](Skin &obj, size_t slotIndex) { + std::vector vetNames; + std::vector entriesVector; + auto entries = obj.getAttachments(); + while (entries.hasNext()) { + Skin::AttachmentMap::Entry &entry = entries.next(); + if (entry._slotIndex == slotIndex) vetNames.push_back(STRING_SP2STD(entry._name)); + } + return vetNames; + }), allow_raw_pointers()) + .function("getAttachment", optional_override([](Skin &obj, size_t slotIndex, + const std::string &name) { + return obj.getAttachment(slotIndex, STRING_STD2SP(name)); + }), allow_raw_pointers()) .function("getAttachments", optional_override([](Skin &obj) { - std::vector entriesVector; - auto entries = obj.getAttachments(); - while (entries.hasNext()) { - entriesVector.push_back(&entries.next()); - } - return entriesVector; - }), - allow_raw_pointers()) - .function("removeAttachment", optional_override([](Skin &obj, size_t index, const std::string &name) { obj.removeAttachment(index, STRING_STD2SP(name)); })) + std::vector entriesVector; + auto entries = obj.getAttachments(); + while (entries.hasNext()) { + entriesVector.push_back(&entries.next()); + } + return entriesVector; + }),allow_raw_pointers()) + .function("removeAttachment", optional_override([](Skin &obj, size_t index, + const std::string &name) { + obj.removeAttachment(index, STRING_STD2SP(name)); })) .function("getAttachmentsForSlot", optional_override([](Skin &obj, size_t index) { - std::vector entriesVector; - auto entries = obj.getAttachments(); - while (entries.hasNext()) { - Skin::AttachmentMap::Entry &entry = entries.next(); - if (entry._slotIndex == index) entriesVector.push_back(&entry); - } - return entriesVector; - }), - allow_raw_pointers()) - //.function("clear", &Skin::clear); // have no clear - //.function("attachAll", &Skin::attachAll) - ; + std::vector entriesVector; + auto entries = obj.getAttachments(); + while (entries.hasNext()) { + Skin::AttachmentMap::Entry &entry = entries.next(); + if (entry._slotIndex == index) entriesVector.push_back(&entry); + } + return entriesVector; + }),allow_raw_pointers()); class_("SkinEntry") .constructor() @@ -690,200 +831,301 @@ EMSCRIPTEN_BINDINGS(spine) { .constructor<>() .function("getClippedVertices", &SkeletonClipping::getClippedVertices) .function("getClippedTriangles", &SkeletonClipping::getClippedTriangles) - .function("getUVs", &SkeletonClipping::getClippedUVs) + .function("getClippedUVs", &SkeletonClipping::getClippedUVs) .function("clipStart", &SkeletonClipping::clipStart, allow_raw_pointers()) .function("clipEndWithSlot", select_overload(&SkeletonClipping::clipEnd)) .function("clipEnd", select_overload(&SkeletonClipping::clipEnd)) .function("isClipping", &SkeletonClipping::isClipping); - //.function("clipTriangles", &SkeletonClipping::clipTriangles, allow_raw_pointers()); //paramters not match - //.function("clip", &SkeletonClipping::clip) - //.class_function("makeClockwise", &SkeletonClipping::makeClockwise) class_("SkeletonData") .constructor<>() - .function("getName", optional_override([](SkeletonData &obj) { return STRING_SP2STD(obj.getName()); })) - .function("getBones", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) - .function("getSlots", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getSlots()); }), allow_raw_pointers()) - .function("getSkins", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getSkins()); }), allow_raw_pointers()) - .function("getDefaultSkin", &SkeletonData::getDefaultSkin, allow_raw_pointer()) - .function("getEvents", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getEvents()); }), allow_raw_pointers()) - .function("getAnimations", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getAnimations()); }), allow_raw_pointers()) - .function("getIkConstraints", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getIkConstraints()); }), allow_raw_pointers()) - .function("getTransformConstraints", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getTransformConstraints()); }), allow_raw_pointers()) - .function("getPathConstraints", optional_override([](SkeletonData &obj) { return VECTOR_SP2STD(obj.getPathConstraints()); }), allow_raw_pointers()) + .function("getName", optional_override([](SkeletonData &obj) { + return STRING_SP2STD(obj.getName()); })) + .function("setName", &SkeletonData::setName) + .function("getBones", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getBones()); }), allow_raw_pointers()) + .function("getSlots", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getSlots()); }), allow_raw_pointers()) + .function("getSkins", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getSkins()); }), allow_raw_pointers()) + .function("getDefaultSkin", &SkeletonData::getDefaultSkin, allow_raw_pointers()) + .function("setDefaultSkin", &SkeletonData::setDefaultSkin, allow_raw_pointers()) + .function("getEvents", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getEvents()); }), allow_raw_pointers()) + .function("getAnimations", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getAnimations()); }), allow_raw_pointers()) + .function("getIkConstraints", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getIkConstraints()); }), allow_raw_pointers()) + .function("getTransformConstraints", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getTransformConstraints()); }), allow_raw_pointers()) + .function("getPathConstraints", optional_override([](SkeletonData &obj) { + return VECTOR_SP2STD(obj.getPathConstraints()); }), allow_raw_pointers()) .function("getX", &SkeletonData::getX) + .function("setX", &SkeletonData::setX) .function("getY", &SkeletonData::getY) + .function("setY", &SkeletonData::setY) .function("getWidth", &SkeletonData::getWidth) + .function("setWidth", &SkeletonData::setWidth) .function("getHeight", &SkeletonData::getHeight) - .function("getVersion", optional_override([](SkeletonData &obj) { return STRING_SP2STD(obj.getVersion()); })) - .function("getHash", optional_override([](SkeletonData &obj) { return STRING_SP2STD(obj.getHash()); })) + .function("setHeight", &SkeletonData::setHeight) + .function("getVersion", optional_override([](SkeletonData &obj) { + return STRING_SP2STD(obj.getVersion()); })) + .function("setVersion", &SkeletonData::setVersion) + .function("getHash", optional_override([](SkeletonData &obj) { + return STRING_SP2STD(obj.getHash()); })) + .function("setHash", &SkeletonData::setHash) .function("getFps", &SkeletonData::getFps) - .function("getImagesPath", optional_override([](SkeletonData &obj) { return STRING_SP2STD(obj.getImagesPath()); })) - .function("getAudioPath", optional_override([](SkeletonData &obj) { return STRING_SP2STD(obj.getAudioPath()); })) - .function("findBone", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findBone(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findBoneIndex", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findBoneIndex(STRING_STD2SP(name)); })) - .function("findSlot", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findSlot(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findSlotIndex", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findSlotIndex(STRING_STD2SP(name)); })) - .function("findSkin", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findSkin(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findEvent", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findEvent(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findAnimation", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findAnimation(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findIkConstraint", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findIkConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findTransformConstraint", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findTransformConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findPathConstraint", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findPathConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findPathConstraintIndex", optional_override([](SkeletonData &obj, const std::string &name) { return obj.findPathConstraintIndex(STRING_STD2SP(name)); })); + .function("setFps", &SkeletonData::setFps) + .function("getImagesPath", optional_override([](SkeletonData &obj) { + return STRING_SP2STD(obj.getImagesPath()); })) + .function("setImagesPath", &SkeletonData::setImagesPath) + .function("getAudioPath", optional_override([](SkeletonData &obj) { + return STRING_SP2STD(obj.getAudioPath()); })) + .function("setAudioPath", &SkeletonData::setAudioPath) + .function("findBone", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findBone(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findBoneIndex", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findBoneIndex(STRING_STD2SP(name)); })) + .function("findSlot", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findSlot(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findSlotIndex", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findSlotIndex(STRING_STD2SP(name)); })) + .function("findSkin", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findSkin(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findEvent", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findEvent(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findAnimation", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findAnimation(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findIkConstraint", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findIkConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findTransformConstraint", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findTransformConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findPathConstraint", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findPathConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findPathConstraintIndex", optional_override([](SkeletonData &obj, const std::string &name) { + return obj.findPathConstraintIndex(STRING_STD2SP(name)); })); + + class_("Animation") + .constructor &, float>() + .function("apply", &Animation::apply, allow_raw_pointers()) + .function("getName", optional_override([](Animation &obj) { return STRING_SP2STD(obj.getName()); })) + .function("getTimelines", optional_override([](Animation &obj) { return VECTOR_SP2STD(obj.getTimelines()); })) + .function("hasTimeline", &Animation::hasTimeline) + .function("getDuration", &Animation::getDuration) + .function("setDuration", &Animation::setDuration); class_("Timeline") // to fix apply - .function("apply", &Timeline::apply, allow_raw_pointers()) + //.function("apply", &Timeline::apply, allow_raw_pointers()) + .function("apply", optional_override([](Timeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()) .function("getPropertyId", &Timeline::getPropertyId); class_>("CurveTimeline") - // static const float LINEAR; - // static const float STEPPED; - // static const float BEZIER; - // static const int BEZIER_SIZE; .function("getPropertyId", &CurveTimeline::getPropertyId, pure_virtual()) .function("getFrameCount", &CurveTimeline::getFrameCount) .function("setLinear", &CurveTimeline::setLinear) .function("setStepped", &CurveTimeline::setStepped) - .function("getCurveType", &CurveTimeline::getCurveType) .function("setCurve", &CurveTimeline::setCurve) - .function("getCurvePercent", &CurveTimeline::getCurvePercent); + .function("getCurvePercent", &CurveTimeline::getCurvePercent) + .function("getCurveType", &CurveTimeline::getCurveType); class_>("TranslateTimeline") .constructor() - // will wrap in js - // static const int ENTRIES - // static const int PREV_TIME; - // static const int PREV_X; - // static const int PREV_Y; - // static const int X; - // static const int Y; - //.function("getProp_boneIndex", &TranslateTimeline::getBoneIndex) - //.function("getProp_frames", &TranslateTimeline::getFrames) + .class_property("ENTRIES", &TranslateTimeline::ENTRIES) .function("getPropertyId", &TranslateTimeline::getPropertyId) .function("setFrame", &TranslateTimeline::setFrame) - .function("apply", &TranslateTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](TranslateTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("ScaleTimeline") .constructor() .function("getPropertyId", &ScaleTimeline::getPropertyId) - .function("apply", &ScaleTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](ScaleTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("ShearTimeline") .constructor() .function("getPropertyId", &ShearTimeline::getPropertyId) - .function("apply", &ShearTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](ShearTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("RotateTimeline") .constructor() - // will wrap in js - //static const int PREV_TIME = -2; - //static const int PREV_ROTATION = -1; - //static const int ROTATION = 1; + //.class_property("ENTRIES", &RotateTimeline::ENTRIES) not bind .function("getBoneIndex", &RotateTimeline::getBoneIndex) - .function("getFrames", optional_override([](RotateTimeline &obj) { return VECTOR_SP2STD(obj.getFrames()); })) + .function("setBoneIndex", &RotateTimeline::setBoneIndex) + .function("getFrames", optional_override([](RotateTimeline &obj) { + return VECTOR_SP2STD( obj.getFrames()); }), allow_raw_pointers()) .function("getPropertyId", &RotateTimeline::getPropertyId) .function("setFrame", &RotateTimeline::setFrame) - .function("apply", &RotateTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](RotateTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("ColorTimeline") .constructor() - // will wrap in js - // static const int PREV_TIME; - // static const int PREV_R; - // static const int PREV_G; - // static const int PREV_B; - // static const int PREV_A; - // static const int R; - // static const int G; - // static const int B; - // static const int A; + .class_property("ENTRIES", &ColorTimeline::ENTRIES) .function("getSlotIndex", &ColorTimeline::getSlotIndex) - .function("getFrames", optional_override([](ColorTimeline &obj) { return VECTOR_SP2STD(obj.getFrames()); })) + .function("setSlotIndex", &ColorTimeline::setSlotIndex) + .function("getFrames", optional_override([](ColorTimeline &obj) { return VECTOR_SP2STD(obj.getFrames()); }), allow_raw_pointers()) .function("getPropertyId", &ColorTimeline::getPropertyId) .function("setFrame", &ColorTimeline::setFrame) - .function("apply", &ColorTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](ColorTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("TwoColorTimeline") .constructor() - // static variables + .class_property("ENTRIES", &ColorTimeline::ENTRIES) .function("getSlotIndex", &TwoColorTimeline::getSlotIndex) - //.function("getProp_frames", &TwoColorTimeline::getFrames) + .function("setSlotIndex", &TwoColorTimeline::setSlotIndex) .function("getPropertyId", &TwoColorTimeline::getPropertyId) .function("setFrame", &TwoColorTimeline::setFrame) - .function("apply", &TwoColorTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](TwoColorTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("AttachmentTimeline") .constructor() .function("getSlotIndex", &AttachmentTimeline::getSlotIndex) - .function("getFrames", optional_override([](AttachmentTimeline &obj) { return VECTOR_SP2STD((Vector &)obj.getFrames()); })) - //.function("getProp_attachmentNames", &AttachmentTimeline::getAttachmentNames) + .function("setSlotIndex", &AttachmentTimeline::setSlotIndex) + .function("getFrames", optional_override([](AttachmentTimeline &obj) { + return VECTOR_SP2STD((Vector &)obj.getFrames()); }), allow_raw_pointers()) + .function("getAttachmentNames",optional_override([](AttachmentTimeline &obj) { + auto names = obj.getAttachmentNames(); + return VECTOR_SP2STD(names); }), allow_raw_pointers()) .function("getPropertyId", &AttachmentTimeline::getPropertyId) .function("getFrameCount", &AttachmentTimeline::getFrameCount) .function("setFrame", &AttachmentTimeline::setFrame) - .function("apply", &AttachmentTimeline::apply, allow_raw_pointers()); - //.function("setAttachment", &AttachmentTimeline::setAttachment) //have no setAttachment + .function("apply", optional_override([](AttachmentTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("DeformTimeline") .constructor() .function("getSlotIndex", &DeformTimeline::getSlotIndex) - .function("getAttachment", &DeformTimeline::getAttachment, allow_raw_pointer()) + .function("setSlotIndex", &DeformTimeline::setSlotIndex) + .function("getAttachment", &DeformTimeline::getAttachment, allow_raw_pointers()) + .function("setAttachment", &DeformTimeline::setAttachment, allow_raw_pointers()) .function("getFrames", optional_override([](DeformTimeline &obj) { return VECTOR_SP2STD((Vector &)obj.getFrames()); })) .function("getFrameVertices", &DeformTimeline::getVertices) .function("getPropertyId", &DeformTimeline::getPropertyId) .function("setFrame", &DeformTimeline::setFrame) - .function("apply", &DeformTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](DeformTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("EventTimeline") .constructor() - .function("getFrames", optional_override([](EventTimeline &obj) { return VECTOR_SP2STD2(obj.getFrames()); })) - .function("getEvents", optional_override([](EventTimeline &obj) { return VECTOR_SP2STD(obj.getEvents()); }), allow_raw_pointers()) + .function("getFrames", optional_override([](EventTimeline &obj) { + return VECTOR_SP2STD2(obj.getFrames()); })) + .function("getEvents", optional_override([](EventTimeline &obj) { + return VECTOR_SP2STD(obj.getEvents()); }), allow_raw_pointers()) .function("getPropertyId", &EventTimeline::getPropertyId) .function("getFrameCount", &EventTimeline::getFrameCount) .function("setFrame", &EventTimeline::setFrame, allow_raw_pointers()) - .function("apply", &EventTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](EventTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("DrawOrderTimeline") .constructor() - .function("getFrames", optional_override([](DrawOrderTimeline &obj) { return VECTOR_SP2STD(obj.getFrames()); })) - //.function("getProp_drawOrders", &EventTimeline::getDrawOrders) + .function("getFrames", optional_override([](DrawOrderTimeline &obj) { return VECTOR_SP2STD(obj.getFrames()); })) .function("getPropertyId", &DrawOrderTimeline::getPropertyId) .function("getFrameCount", &DrawOrderTimeline::getFrameCount) + .function("getDrawOrders", optional_override([](DrawOrderTimeline &obj){ + auto drawOrders = obj.getDrawOrders(); + return VECTOR_2_SP2STD(drawOrders); + }), allow_raw_pointers()) .function("setFrame", &DrawOrderTimeline::setFrame, allow_raw_pointers()) - .function("apply", &DrawOrderTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](DrawOrderTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("IkConstraintTimeline") .constructor() - // static variables - // .function("getProp_ikConstraintIndex", &EventTimeline::getFrames) // private - // .function("getProp_frames", &IkConstraintTimeline::getFrames) + .class_property("ENTRIES", &IkConstraintTimeline::ENTRIES) .function("getPropertyId", &IkConstraintTimeline::getPropertyId) .function("setFrame", &IkConstraintTimeline::setFrame) - .function("apply", &IkConstraintTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](IkConstraintTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("TransformConstraintTimeline") .constructor() - // static variables - // .function("getProp_ikConstraintIndex", &TransformConstraintTimeline::getFrames) // private - //.function("getProp_frames", &TransformConstraintTimeline::getFrames) + .class_property("ENTRIES", &TransformConstraintTimeline::ENTRIES) .function("getPropertyId", &TransformConstraintTimeline::getPropertyId) .function("setFrame", &TransformConstraintTimeline::setFrame) - .function("apply", &TransformConstraintTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](TransformConstraintTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("PathConstraintPositionTimeline") .constructor() - // static variables - // .function("getProp_ikConstraintIndex", &TransformConstraintTimeline::getFrames) // private - //.function("getProp_frames", &TransformConstraintTimeline::getFrames) + .class_property("ENTRIES", &TransformConstraintTimeline::ENTRIES) .function("getPropertyId", &PathConstraintPositionTimeline::getPropertyId) .function("setFrame", &PathConstraintPositionTimeline::setFrame) - .function("apply", &PathConstraintPositionTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](PathConstraintPositionTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_>("PathConstraintMixTimeline") .constructor() + .class_property("ENTRIES", &PathConstraintMixTimeline::ENTRIES) .function("getPropertyId", &PathConstraintMixTimeline::getPropertyId) - .function("apply", &PathConstraintMixTimeline::apply, allow_raw_pointers()); + .function("apply", optional_override([](PathConstraintMixTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), allow_raw_pointers()); class_("TrackEntry") .constructor<>() @@ -941,6 +1183,7 @@ EMSCRIPTEN_BINDINGS(spine) { class_("AnimationStateData") .constructor() .function("getDefaultMix", &AnimationStateData::getDefaultMix) + .function("setDefaultMix", &AnimationStateData::setDefaultMix) .function("getSkeletonData", &AnimationStateData::getSkeletonData, allow_raw_pointers()) .function("setMix", optional_override([](AnimationStateData &obj, const std::string& fromName, const std::string& toName, float duration) { return obj.setMix(STRING_STD2SP(fromName), STRING_STD2SP(toName), duration);})) @@ -948,82 +1191,54 @@ EMSCRIPTEN_BINDINGS(spine) { return obj.setMix(from, to, duration);}), allow_raw_pointers()) .function("getMix", &AnimationStateData::getMix, allow_raw_pointers()); - // .function("setMixWith", &Skeleton::setMixWith_Export) - //.function("getMix", &Skeleton::setMix_Export); - - class_("AnimationState") - .constructor() - // static variables - // .class_function("getProp_emptyAnimation",&AnimationState::getEmptyAnimation, allow_raw_pointers()) // private - .function("getData", &AnimationState::getData, allow_raw_pointers()) - .function("getTracks", optional_override([](AnimationState &obj) { return VECTOR_SP2STD(obj.getTracks()); }), allow_raw_pointers()) - .function("getTimeScale", &AnimationState::getTimeScale) - .function("setTimeScale", &AnimationState::setTimeScale) - //.function("getProp_unkeyedState") - //.function("getProp_events") - //.function("getProp_listeners") - //.function("getProp_queue") - //.function("getProp_queue") - //.function("getProp_propertyIDs", &AnimationState::getPropertyIDs) - //.function("getProp_animationsChanged", &AnimationState::getAnimationsChanged) - //.function("getProp_trackEntryPool", &AnimationState::getTrackEntryPool) - .function("update", &AnimationState::update) - //.function("updateMixingFrom", &AnimationState::updateMixingFrom, allow_raw_pointers()) //private - .function("apply", &AnimationState::apply) - // .function("applyMixingFrom", &AnimationState::applyMixingFrom, allow_raw_pointers()) //private - //.function("applyAttachmentTimeline", &AnimationState::applyAttachmentTimeline) // have no - //.function("setAttachment", &AnimationState::setAttachment) // have no - // .class_function("applyRotateTimeline", &AnimationState::applyRotateTimeline, allow_raw_pointers()) - // .function("queueEvents", &AnimationState::queueEvents, allow_raw_pointers()) - .function("clearTracks", &AnimationState::clearTracks) - .function("clearTrack", &AnimationState::clearTrack) - //.function("setCurrent", &AnimationState::setCurrent, allow_raw_pointers()) // private - .function("setAnimation", optional_override([](AnimationState &obj, uint32_t trackIndex, const std::string &animName, bool loop) { return obj.setAnimation(trackIndex, STRING_STD2SP(animName), loop); }), allow_raw_pointers()) - .function("setAnimationWith", optional_override([](AnimationState &obj, uint32_t trackIndex, Animation *animation, bool loop) { return obj.setAnimation(trackIndex, animation, loop); }), allow_raw_pointers()) - .function("addAnimation", optional_override([](AnimationState &obj, uint32_t trackIndex, const std::string &animName, bool loop, float delay) { return obj.addAnimation(trackIndex, STRING_STD2SP(animName), loop, delay); }), allow_raw_pointers()) - .function("addAnimationWith", optional_override([](AnimationState &obj, uint32_t trackIndex, Animation *animation, bool loop, float delay) { return obj.addAnimation(trackIndex, animation, loop, delay); }), allow_raw_pointers()) - .function("setEmptyAnimation", &AnimationState::setEmptyAnimation, allow_raw_pointers()) - .function("addEmptyAnimation", &AnimationState::addEmptyAnimation, allow_raw_pointers()) - .function("setEmptyAnimations", &AnimationState::setEmptyAnimations) - //.function("expandToIndex", &AnimationState::expandToIndex, allow_raw_pointers()) // private - //.function("trackEntry", &AnimationState::newTrackEntry, allow_raw_pointers()) // private - //.function("disposeNext", &AnimationState::disposeNext) // private - //.function("_animationsChanged", &AnimationState::animationsChanged) // private - //.function("computeHold", &AnimationState::computeHold, allow_raw_pointer()) // private - .function("getCurrent", &AnimationState::getCurrent, allow_raw_pointer()); + class_("AnimationState") + .constructor() + .function("getData", &AnimationState::getData, allow_raw_pointers()) + .function("getTracks", optional_override([](AnimationState &obj) { + return VECTOR_SP2STD(obj.getTracks()); }), allow_raw_pointers()) + .function("getTimeScale", &AnimationState::getTimeScale) + .function("setTimeScale", &AnimationState::setTimeScale) + .function("update", &AnimationState::update) + .function("apply", &AnimationState::apply) + .function("clearTracks", &AnimationState::clearTracks) + .function("clearTrack", &AnimationState::clearTrack) + .function("setAnimation", optional_override([](AnimationState &obj, uint32_t trackIndex, const std::string &animName, bool loop) { return obj.setAnimation(trackIndex, STRING_STD2SP(animName), loop); }), allow_raw_pointers()) + .function("setAnimationWith", optional_override([](AnimationState &obj, uint32_t trackIndex, Animation *animation, bool loop) { return obj.setAnimation(trackIndex, animation, loop); }), allow_raw_pointers()) + .function("addAnimation", optional_override([](AnimationState &obj, uint32_t trackIndex, const std::string &animName, bool loop, float delay) { return obj.addAnimation(trackIndex, STRING_STD2SP(animName), loop, delay); }), allow_raw_pointers()) + .function("addAnimationWith", optional_override([](AnimationState &obj, uint32_t trackIndex, Animation *animation, bool loop, float delay) { return obj.addAnimation(trackIndex, animation, loop, delay); }), allow_raw_pointers()) + .function("setEmptyAnimation", &AnimationState::setEmptyAnimation, allow_raw_pointers()) + .function("addEmptyAnimation", &AnimationState::addEmptyAnimation, allow_raw_pointers()) + .function("setEmptyAnimations", &AnimationState::setEmptyAnimations) + .function("getCurrent", &AnimationState::getCurrent, allow_raw_pointer()) + .function("setListener", optional_override([](AnimationState &obj, AnimationStateListener inValue) { + obj.setListener(inValue); }),allow_raw_pointers()) + .function("setListenerObject", optional_override([](AnimationState &obj, AnimationStateListenerObject *inValue) { + obj.setListener(inValue); }),allow_raw_pointers()) + .function("disableQueue", &AnimationState::disableQueue) + .function("enableQueue", &AnimationState::enableQueue); //.function("addListener", &AnimationState::addListener) //.function("removeListener", &AnimationState::removeListener) //.function("clearListeners", &AnimationState::clearListeners) // no have clearListeners - // .function("clearListenerNotifications", &AnimationState::clearListenerNotifications); // no have clearListenerNotifications - - class_("Animation") - .constructor &, float>() - .function("getName", optional_override([](Animation &obj) { return STRING_SP2STD(obj.getName()); })) - .function("getTimelines", optional_override([](Animation &obj) { return VECTOR_SP2STD(obj.getTimelines()); })) - //.function("getProp_timelineIds", &Animation::getTimelines) - .function("getDuration", &Animation::getDuration) - .function("setDuration", &Animation::setDuration) - .function("hasTimeline", &Animation::hasTimeline) - .function("apply", &Animation::apply, allow_raw_pointers()) - // .class_function("binarySearch", &Animation::binarySearch) - // .class_function("linearSearch", &Animation::linearSearch) - ; - - // private - // class_("EventQueue") - // .constructor& >() - // .function("start", &EventQueue::start, allow_raw_pointers()) - // .function("interrupt", &EventQueue::interrupt, allow_raw_pointers()) - // .function("end", &EventQueue::end, allow_raw_pointers()) - // .function("dispose", &EventQueue::dispose, allow_raw_pointers()) - // .function("complete", &EventQueue::complete, allow_raw_pointers()) - // .function("event", &EventQueue::event, allow_raw_pointers()) - // .function("drain", &EventQueue::drain) - // //.function("clear") - - // class_("AnimationStateListener") - - // class_("AnimationStateAdapter") + + //private + // class_("EventQueue") + // .constructor& >() + // .function("start", &EventQueue::start, allow_raw_pointers()) + // .function("interrupt", &EventQueue::interrupt, allow_raw_pointers()) + // .function("end", &EventQueue::end, allow_raw_pointers()) + // .function("dispose", &EventQueue::dispose, allow_raw_pointers()) + // .function("complete", &EventQueue::complete, allow_raw_pointers()) + // .function("event", &EventQueue::event, allow_raw_pointers()) + // .function("drain", &EventQueue::drain) + // .function("clear"); + + //class_("AnimationStateListener") + + //class_("AnimationStateListenerObject") + // .constructor<>() + // .function("callback", &AnimationStateListenerObject::callback, pure_virtual()); + + //class_("AnimationStateAdapter") class_("Skeleton") .constructor() @@ -1041,22 +1256,20 @@ EMSCRIPTEN_BINDINGS(spine) { .function("getPathConstraints", optional_override([](Skeleton &obj) { return VECTOR_SP2STD(obj.getPathConstraints()); }), allow_raw_pointers()) .function("getUpdateCacheList", &Skeleton::getUpdateCacheList, allow_raw_pointer()) - //.function("getProp_updateCacheReset", Skeleton::) .function("getSkin", &Skeleton::getSkin, allow_raw_pointer()) - .function("getColor", &Skeleton::getColor) + .function("getColor", optional_override([](Skeleton &obj){ + return &obj.getColor(); }), allow_raw_pointers()) .function("getTime", &Skeleton::getTime) + .function("setTime", &Skeleton::setTime) .function("getScaleX", &Skeleton::getScaleX) + .function("setScaleX", &Skeleton::setScaleX) .function("getScaleY", &Skeleton::getScaleY) + .function("setScaleY", &Skeleton::setScaleY) .function("getX", &Skeleton::getX) + .function("setX", &Skeleton::setX) .function("getY", &Skeleton::getY) + .function("setY", &Skeleton::setY) .function("updateCache", &Skeleton::updateCache) - //.function("sortIkConstraint") - //.function("sortPathConstraint") - //.function("sortTransformConstraint") - //.function("sortPathConstraintAttachment") - //.function("sortPathConstraintAttachmentWith") - // .function("sortBone", &Skeleton::sortBone, allow_raw_pointer()) - // .function("sortReset", &Skeleton::sortReset, allow_raw_pointer()) .function("updateWorldTransform", &Skeleton::updateWorldTransform) .function("setToSetupPose", &Skeleton::setToSetupPose) .function("setBonesToSetupPose", &Skeleton::setBonesToSetupPose) @@ -1080,97 +1293,104 @@ EMSCRIPTEN_BINDINGS(spine) { .function("setAttachment", optional_override([](Skeleton &obj, const std::string& slotName, const std::string& attachmentName) { return obj.setAttachment(STRING_STD2SP(slotName), STRING_STD2SP(attachmentName));})) .function("findIkConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findIkConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findTransformConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findTransformConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - .function("findPathConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findPathConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) - //.function("getBounds", &Skeleton::getBounds) - .function("update", &Skeleton::update); - - // incomplete - // class_("SkeletonBinary") - // .constructor() - // .function("setProp_scale", &SkeletonBinary::setScale); - //.function("getProp_scale", &SkeletonBinary::getScale) - //.function("readSkeletonData", &SkeletonBinary::readSkeletonData) - //.function("setCurve", &SkeletonBinary::setCurve); - // incomplete - - // class_("SkeletonJson") - // .constructor() - // .constructor(); - //.function("readSkeletonData", &SkeletonJson::readSkeletonData) - //.function("getProp_scale", &SkeletonJson::getScale) - - class_("VertexEffect") - .function("begin", &VertexEffect::begin, pure_virtual()) - //.function("transform", &VertexEffect::transform, pure_virtual()) - .function("end", &VertexEffect::end, pure_virtual()); - - class_>("JitterEffect") - .constructor() - .function("getJitterX", &JitterVertexEffect::getJitterX) - .function("setJitterX", &JitterVertexEffect::setJitterX) - .function("getJitterY", &JitterVertexEffect::getJitterY) - .function("setJitterY", &JitterVertexEffect::setJitterY) - .function("begin", &JitterVertexEffect::begin) - //.function("transform", &JitterVertexEffect::transform) - .function("end", &JitterVertexEffect::end); - - class_>("SwirlEffect") - .constructor() - .function("getCenterX", &SwirlVertexEffect::getCenterX) - .function("setCenterX", &SwirlVertexEffect::setCenterX) - .function("getCenterY", &SwirlVertexEffect::getCenterY) - .function("setCenterY", &SwirlVertexEffect::setCenterY) - .function("getRadius", &SwirlVertexEffect::getRadius) - .function("setRadius", &SwirlVertexEffect::setRadius) - .function("getAngle", &SwirlVertexEffect::getAngle) - .function("setAngle", &SwirlVertexEffect::setAngle) - .function("begin", &SwirlVertexEffect::begin) - //.function("transform", &SwirlVertexEffect::transform) - .function("end", &SwirlVertexEffect::end); - - class_("SlotMesh") - .property("vCount", &SlotMesh::vCount) - .property("iCount", &SlotMesh::iCount) - .property("blendMode", &SlotMesh::blendMode) - .property("textureID", &SlotMesh::textureID); - - register_vector("VectorSlotMesh"); - class_("SpineModel") - .property("vCount", &SpineModel::vCount) - .property("iCount", &SpineModel::iCount) - .property("vPtr", &SpineModel::vPtr) - .property("iPtr", &SpineModel::iPtr) - .function("getMeshes", &SpineModel::getMeshes); - - class_("SpineDebugShape") - .property("type", &SpineDebugShape::type) - .property("vOffset", &SpineDebugShape::vOffset) - .property("vCount", &SpineDebugShape::vCount) - .property("iOffset", &SpineDebugShape::iOffset) - .property("iCount", &SpineDebugShape::iCount); - - register_vector("VectorDebugShape"); - class_("SkeletonInstance") - .constructor<>() - .function("initSkeleton", &SpineSkeletonInstance::initSkeleton, allow_raw_pointers()) - .function("setAnimation", &SpineSkeletonInstance::setAnimation, allow_raw_pointers()) - .function("setSkin", &SpineSkeletonInstance::setSkin) - .function("updateAnimation", &SpineSkeletonInstance::updateAnimation) - .function("updateRenderData", &SpineSkeletonInstance::updateRenderData, allow_raw_pointer()) - .function("setPremultipliedAlpha", &SpineSkeletonInstance::setPremultipliedAlpha) - .function("setUseTint", &SpineSkeletonInstance::setUseTint) - .function("setColor", &SpineSkeletonInstance::setColor) - .function("setJitterEffect", &SpineSkeletonInstance::setJitterEffect, allow_raw_pointer()) - .function("setSwirlEffect", &SpineSkeletonInstance::setSwirlEffect, allow_raw_pointer()) - .function("clearEffect", &SpineSkeletonInstance::clearEffect) - .function("getAnimationState", &SpineSkeletonInstance::getAnimationState, allow_raw_pointer()) - .function("setMix", &SpineSkeletonInstance::setMix) - .function("setListener", &SpineSkeletonInstance::setListener) - .function("setDebugMode", &SpineSkeletonInstance::setDebugMode) - .function("getDebugShapes", &SpineSkeletonInstance::getDebugShapes) - .function("resizeSlotRegion", &SpineSkeletonInstance::resizeSlotRegion) - .function("setSlotTexture", &SpineSkeletonInstance::setSlotTexture); + .function("findTransformConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findTransformConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + .function("findPathConstraint", optional_override([](Skeleton &obj, const std::string &name) { return obj.findPathConstraint(STRING_STD2SP(name)); }), allow_raw_pointers()) + //.function("getBounds", optional_override([](Skeleton &obj, &outX, ) {}), allow_raw_pointers()) + .function("update", &Skeleton::update); + + //incomplete + // class_("SkeletonBinary") + // .constructor() + // .constructor() + // .function("setScale", &SkeletonBinary::setScale) + // .function("getError", &SkeletonBinary::getError); + //.function("readSkeletonDataFile", optional_override([](SkeletonBinary &obj, const spine::String& path) { return obj.readSkeletonDataFile(path); })); + + // incomplete + //class_("SkeletonJson") + //.constructor() + //.constructor() + //.function("setScale", &SkeletonJson::setScale); + //.function("getError", &SkeletonJson::getError); + + class_("VertexEffect") + .function("begin", &VertexEffect::begin, pure_virtual()) + .function("transform", optional_override([](VertexEffect &obj, float x, float y) { + obj.transform(x, y); }), pure_virtual()) + .function("end", &VertexEffect::end, pure_virtual()); + + class_>("JitterEffect") + .constructor() + .function("getJitterX", &JitterVertexEffect::getJitterX) + .function("setJitterX", &JitterVertexEffect::setJitterX) + .function("getJitterY", &JitterVertexEffect::getJitterY) + .function("setJitterY", &JitterVertexEffect::setJitterY) + .function("begin", &JitterVertexEffect::begin) + .function("transform", optional_override([](VertexEffect &obj, float x, float y) { + obj.transform(x, y); }), pure_virtual()) + .function("end", &JitterVertexEffect::end); + + class_>("SwirlEffect") + .constructor() + .function("begin", &SwirlVertexEffect::begin) + .function("transform", optional_override([](VertexEffect &obj, float x, float y) { + obj.transform(x, y); }), pure_virtual()) + .function("end", &SwirlVertexEffect::end) + .function("getCenterX", &SwirlVertexEffect::getCenterX) + .function("setCenterX", &SwirlVertexEffect::setCenterX) + .function("getCenterY", &SwirlVertexEffect::getCenterY) + .function("setCenterY", &SwirlVertexEffect::setCenterY) + .function("getRadius", &SwirlVertexEffect::getRadius) + .function("setRadius", &SwirlVertexEffect::setRadius) + .function("getAngle", &SwirlVertexEffect::getAngle) + .function("setAngle", &SwirlVertexEffect::setAngle) + .function("getWorldX", &SwirlVertexEffect::getWorldX) + .function("setWorldX", &SwirlVertexEffect::setWorldX) + .function("getWorldY", &SwirlVertexEffect::getWorldY) + .function("setWorldY", &SwirlVertexEffect::setWorldY); + + class_("SlotMesh") + .property("vCount", &SlotMesh::vCount) + .property("iCount", &SlotMesh::iCount) + .property("blendMode", &SlotMesh::blendMode) + .property("textureID", &SlotMesh::textureID); + + register_vector("VectorSlotMesh"); + class_("SpineModel") + .property("vCount", &SpineModel::vCount) + .property("iCount", &SpineModel::iCount) + .property("vPtr", &SpineModel::vPtr) + .property("iPtr", &SpineModel::iPtr) + .function("getMeshes", &SpineModel::getMeshes); + + class_("SpineDebugShape") + .property("type", &SpineDebugShape::type) + .property("vOffset", &SpineDebugShape::vOffset) + .property("vCount", &SpineDebugShape::vCount) + .property("iOffset", &SpineDebugShape::iOffset) + .property("iCount", &SpineDebugShape::iCount); + + register_vector("VectorDebugShape"); + class_("SkeletonInstance") + .constructor<>() + .function("initSkeleton", &SpineSkeletonInstance::initSkeleton, allow_raw_pointers()) + .function("setAnimation", &SpineSkeletonInstance::setAnimation, allow_raw_pointers()) + .function("setSkin", &SpineSkeletonInstance::setSkin) + .function("updateAnimation", &SpineSkeletonInstance::updateAnimation) + .function("updateRenderData", &SpineSkeletonInstance::updateRenderData, allow_raw_pointer()) + .function("setPremultipliedAlpha", &SpineSkeletonInstance::setPremultipliedAlpha) + .function("setUseTint", &SpineSkeletonInstance::setUseTint) + .function("setColor", &SpineSkeletonInstance::setColor) + .function("setJitterEffect", &SpineSkeletonInstance::setJitterEffect, allow_raw_pointer()) + .function("setSwirlEffect", &SpineSkeletonInstance::setSwirlEffect, allow_raw_pointer()) + .function("clearEffect", &SpineSkeletonInstance::clearEffect) + .function("getAnimationState", &SpineSkeletonInstance::getAnimationState, allow_raw_pointer()) + .function("setMix", &SpineSkeletonInstance::setMix) + .function("setListener", &SpineSkeletonInstance::setListener) + .function("setDebugMode", &SpineSkeletonInstance::setDebugMode) + .function("getDebugShapes", &SpineSkeletonInstance::getDebugShapes) + .function("resizeSlotRegion", &SpineSkeletonInstance::resizeSlotRegion) + .function("setSlotTexture", &SpineSkeletonInstance::setSlotTexture); } EMSCRIPTEN_BINDINGS(cocos_spine) { diff --git a/native/external-config.json b/native/external-config.json index 9b92430ee9a..1ce55742884 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-12" + "checkout": "v3.8.1-14" } } \ No newline at end of file From 46592f013b3f7c3697fe4da33be5a153caef5a15 Mon Sep 17 00:00:00 2001 From: Cocos Robot <48829427+cocos-robot@users.noreply.github.com> Date: Mon, 21 Aug 2023 13:43:36 +0800 Subject: [PATCH 204/232] [ci skip][AUTO]: Automated code generating update: 0af68e43e95326958afc65ae5e6849ef8ac59c5d (#16023) (#16043) Co-authored-by: cocos-robot --- native/cocos/core/builtin/DebugInfos.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/native/cocos/core/builtin/DebugInfos.cpp b/native/cocos/core/builtin/DebugInfos.cpp index 8571eefcfa6..31ed13ab8ee 100644 --- a/native/cocos/core/builtin/DebugInfos.cpp +++ b/native/cocos/core/builtin/DebugInfos.cpp @@ -464,6 +464,9 @@ ccstd::unordered_map debugInfos = { { 14100, "Pool.destroy no longer take a function as parameter, Please specify destruct function in the construction of Pool instead" }, { 14200, "Can not update a static mesh." }, { 14201, "The primitiveIndex is out of range." }, +{ 14202, "meshopt asm decoder initialized" }, +{ 14203, "meshopt wasm decoder initialized" }, +{ 14204, "meshopt decoder error: %d" }, { 14300, "Can not keep world transform due to the zero scaling of parent node" }, { 14400, "Spline error: less than 2 knots." }, { 14401, "Spline error: less than 4 knots or not a multiple of 4.\n\n" }, From f55f423fe8695f51abffb82252d2b6d6d9ea5b7e Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Mon, 21 Aug 2023 14:54:32 +0800 Subject: [PATCH 205/232] update meta (#16051) --- editor/assets/default_prefab/2d/Camera.prefab.meta | 2 +- editor/assets/default_prefab/2d/ui/Canvas.prefab.meta | 2 +- editor/assets/default_prefab/3d/Capsule.prefab.meta | 2 +- editor/assets/default_prefab/3d/Cone.prefab.meta | 2 +- editor/assets/default_prefab/3d/Cube.prefab.meta | 2 +- editor/assets/default_prefab/3d/Cylinder.prefab.meta | 2 +- editor/assets/default_prefab/3d/Plane.prefab.meta | 2 +- editor/assets/default_prefab/3d/Quad.prefab.meta | 2 +- editor/assets/default_prefab/3d/Sphere.prefab.meta | 2 +- editor/assets/default_prefab/3d/Torus.prefab.meta | 2 +- editor/assets/default_prefab/Camera.prefab | 2 +- editor/assets/default_prefab/Camera.prefab.meta | 2 +- editor/assets/default_prefab/Terrain.prefab.meta | 2 +- .../assets/default_prefab/effects/Particle System.prefab.meta | 2 +- .../assets/default_prefab/light/Directional Light.prefab.meta | 2 +- .../assets/default_prefab/light/Light Probe Group.prefab.meta | 2 +- editor/assets/default_prefab/light/Point Light.prefab | 2 +- editor/assets/default_prefab/light/Point Light.prefab.meta | 2 +- .../default_prefab/light/Ranged Directional Light.prefab | 2 +- .../default_prefab/light/Ranged Directional Light.prefab.meta | 2 +- .../assets/default_prefab/light/Reflection Probe.prefab.meta | 2 +- editor/assets/default_prefab/light/Sphere Light.prefab.meta | 2 +- editor/assets/default_prefab/light/Spot Light.prefab.meta | 2 +- editor/assets/default_prefab/ui/Button.prefab.meta | 2 +- editor/assets/default_prefab/ui/Canvas.prefab.meta | 2 +- editor/assets/default_prefab/ui/EditBox.prefab | 2 +- editor/assets/default_prefab/ui/EditBox.prefab.meta | 2 +- editor/assets/default_prefab/ui/Graphics.prefab.meta | 2 +- editor/assets/default_prefab/ui/Label.prefab.meta | 2 +- editor/assets/default_prefab/ui/Layout.prefab.meta | 2 +- editor/assets/default_prefab/ui/Mask.prefab.meta | 2 +- editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta | 2 +- editor/assets/default_prefab/ui/ProgressBar.prefab | 4 ++-- editor/assets/default_prefab/ui/ProgressBar.prefab.meta | 2 +- editor/assets/default_prefab/ui/RichText.prefab.meta | 2 +- editor/assets/default_prefab/ui/ScrollView.prefab.meta | 2 +- editor/assets/default_prefab/ui/Slider.prefab | 4 ++-- editor/assets/default_prefab/ui/Slider.prefab.meta | 2 +- editor/assets/default_prefab/ui/Sprite.prefab.meta | 2 +- editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta | 2 +- editor/assets/default_prefab/ui/SpriteSplash.prefab.meta | 2 +- editor/assets/default_prefab/ui/TiledMap.prefab.meta | 2 +- editor/assets/default_prefab/ui/Toggle.prefab.meta | 2 +- editor/assets/default_prefab/ui/ToggleContainer.prefab.meta | 2 +- editor/assets/default_prefab/ui/VideoPlayer.prefab.meta | 2 +- editor/assets/default_prefab/ui/WebView.prefab.meta | 2 +- editor/assets/default_prefab/ui/Widget.prefab.meta | 2 +- editor/assets/default_prefab/ui/pageView.prefab.meta | 2 +- editor/assets/tools/debug-view-runtime-control.prefab.meta | 2 +- 49 files changed, 51 insertions(+), 51 deletions(-) diff --git a/editor/assets/default_prefab/2d/Camera.prefab.meta b/editor/assets/default_prefab/2d/Camera.prefab.meta index 9140b81984e..2a9efe9d3ad 100644 --- a/editor/assets/default_prefab/2d/Camera.prefab.meta +++ b/editor/assets/default_prefab/2d/Camera.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "3487d118-0158-4983-93fe-c3822790e7c5", diff --git a/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta b/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta index 955de65ec05..7a02f8602a3 100644 --- a/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta +++ b/editor/assets/default_prefab/2d/ui/Canvas.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "4c33600e-9ca9-483b-b734-946008261697", diff --git a/editor/assets/default_prefab/3d/Capsule.prefab.meta b/editor/assets/default_prefab/3d/Capsule.prefab.meta index a5a21cf019f..2cdc8360ae1 100644 --- a/editor/assets/default_prefab/3d/Capsule.prefab.meta +++ b/editor/assets/default_prefab/3d/Capsule.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "73ce1f7f-d1f4-4942-ad93-66ca3b3041ab", diff --git a/editor/assets/default_prefab/3d/Cone.prefab.meta b/editor/assets/default_prefab/3d/Cone.prefab.meta index 5b5113f9f0d..caef62b443a 100644 --- a/editor/assets/default_prefab/3d/Cone.prefab.meta +++ b/editor/assets/default_prefab/3d/Cone.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "6350d660-e888-4acf-a552-f3b719ae9110", diff --git a/editor/assets/default_prefab/3d/Cube.prefab.meta b/editor/assets/default_prefab/3d/Cube.prefab.meta index 12020ef451a..7a3b4277d85 100644 --- a/editor/assets/default_prefab/3d/Cube.prefab.meta +++ b/editor/assets/default_prefab/3d/Cube.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "30da77a1-f02d-4ede-aa56-403452ee7fde", diff --git a/editor/assets/default_prefab/3d/Cylinder.prefab.meta b/editor/assets/default_prefab/3d/Cylinder.prefab.meta index 6c5684fdca6..de6fd2091f3 100644 --- a/editor/assets/default_prefab/3d/Cylinder.prefab.meta +++ b/editor/assets/default_prefab/3d/Cylinder.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "ab3e16f9-671e-48a7-90b7-d0884d9cbb85", diff --git a/editor/assets/default_prefab/3d/Plane.prefab.meta b/editor/assets/default_prefab/3d/Plane.prefab.meta index d38151b7473..762d5e1c3cb 100644 --- a/editor/assets/default_prefab/3d/Plane.prefab.meta +++ b/editor/assets/default_prefab/3d/Plane.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "40563723-f8fc-4216-99ea-a81636435c10", diff --git a/editor/assets/default_prefab/3d/Quad.prefab.meta b/editor/assets/default_prefab/3d/Quad.prefab.meta index dc8e2b361b2..05f6a30a78f 100644 --- a/editor/assets/default_prefab/3d/Quad.prefab.meta +++ b/editor/assets/default_prefab/3d/Quad.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "34a07346-9f62-4a84-90ae-cb83f7a426c1", diff --git a/editor/assets/default_prefab/3d/Sphere.prefab.meta b/editor/assets/default_prefab/3d/Sphere.prefab.meta index ab4f2ec0c6f..379f0318d21 100644 --- a/editor/assets/default_prefab/3d/Sphere.prefab.meta +++ b/editor/assets/default_prefab/3d/Sphere.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "655c9519-1a37-472b-bae6-29fefac0b550", diff --git a/editor/assets/default_prefab/3d/Torus.prefab.meta b/editor/assets/default_prefab/3d/Torus.prefab.meta index eb825d2f575..1c916b0f66e 100644 --- a/editor/assets/default_prefab/3d/Torus.prefab.meta +++ b/editor/assets/default_prefab/3d/Torus.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "d47f5d5e-c931-4ff4-987b-cc818a728b82", diff --git a/editor/assets/default_prefab/Camera.prefab b/editor/assets/default_prefab/Camera.prefab index 8e18549598c..78c68520fcc 100644 --- a/editor/assets/default_prefab/Camera.prefab +++ b/editor/assets/default_prefab/Camera.prefab @@ -107,4 +107,4 @@ }, "fileId": "f8Nyw5r0hH9Zz+WrOqK1x/" } -] +] \ No newline at end of file diff --git a/editor/assets/default_prefab/Camera.prefab.meta b/editor/assets/default_prefab/Camera.prefab.meta index c59e4c5e4a4..647ff9aef3a 100644 --- a/editor/assets/default_prefab/Camera.prefab.meta +++ b/editor/assets/default_prefab/Camera.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "bb0a6472-cd67-4afb-a031-94fca8f4cc92", diff --git a/editor/assets/default_prefab/Terrain.prefab.meta b/editor/assets/default_prefab/Terrain.prefab.meta index 4cd34a340d4..66b2240a22e 100644 --- a/editor/assets/default_prefab/Terrain.prefab.meta +++ b/editor/assets/default_prefab/Terrain.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "90e8b0d4-12dc-412d-9156-ea1fdb18c15b", diff --git a/editor/assets/default_prefab/effects/Particle System.prefab.meta b/editor/assets/default_prefab/effects/Particle System.prefab.meta index 6623a93f2bb..fc311329e1c 100644 --- a/editor/assets/default_prefab/effects/Particle System.prefab.meta +++ b/editor/assets/default_prefab/effects/Particle System.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "f09a0597-10e6-49e5-8759-a148b5e85395", diff --git a/editor/assets/default_prefab/light/Directional Light.prefab.meta b/editor/assets/default_prefab/light/Directional Light.prefab.meta index 5294e53fb64..89d28c73bdc 100644 --- a/editor/assets/default_prefab/light/Directional Light.prefab.meta +++ b/editor/assets/default_prefab/light/Directional Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "a0e9756d-9128-4f49-8097-e041c8b733b8", diff --git a/editor/assets/default_prefab/light/Light Probe Group.prefab.meta b/editor/assets/default_prefab/light/Light Probe Group.prefab.meta index 91718973579..197281caacb 100644 --- a/editor/assets/default_prefab/light/Light Probe Group.prefab.meta +++ b/editor/assets/default_prefab/light/Light Probe Group.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.45", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "50dfda40-7c45-4868-a876-2fe2a4c782f4", diff --git a/editor/assets/default_prefab/light/Point Light.prefab b/editor/assets/default_prefab/light/Point Light.prefab index cb555e0070c..7f1cd6c7791 100644 --- a/editor/assets/default_prefab/light/Point Light.prefab +++ b/editor/assets/default_prefab/light/Point Light.prefab @@ -94,4 +94,4 @@ }, "fileId": "59eikBZx5K9aR06hUuVC37" } -] +] \ No newline at end of file diff --git a/editor/assets/default_prefab/light/Point Light.prefab.meta b/editor/assets/default_prefab/light/Point Light.prefab.meta index 54d9e7a4705..598d473c0e3 100644 --- a/editor/assets/default_prefab/light/Point Light.prefab.meta +++ b/editor/assets/default_prefab/light/Point Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "03029371-ee64-4f14-820a-d495ad7cdc29", diff --git a/editor/assets/default_prefab/light/Ranged Directional Light.prefab b/editor/assets/default_prefab/light/Ranged Directional Light.prefab index 73afa3b15ff..eaa64795ad6 100644 --- a/editor/assets/default_prefab/light/Ranged Directional Light.prefab +++ b/editor/assets/default_prefab/light/Ranged Directional Light.prefab @@ -92,4 +92,4 @@ }, "fileId": "aeyMch0nJBEbV/mk9CXYkW" } -] +] \ No newline at end of file diff --git a/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta b/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta index 9181f35f84d..69df4adf90d 100644 --- a/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta +++ b/editor/assets/default_prefab/light/Ranged Directional Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "df72d0f6-49d3-452a-b082-8b23d38b33af", diff --git a/editor/assets/default_prefab/light/Reflection Probe.prefab.meta b/editor/assets/default_prefab/light/Reflection Probe.prefab.meta index 872b7155bc6..0e0ab920114 100644 --- a/editor/assets/default_prefab/light/Reflection Probe.prefab.meta +++ b/editor/assets/default_prefab/light/Reflection Probe.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "d8b49b64-cfba-4cfa-be53-1e469547b28b", diff --git a/editor/assets/default_prefab/light/Sphere Light.prefab.meta b/editor/assets/default_prefab/light/Sphere Light.prefab.meta index f6235f6b6d1..1bebad0a135 100644 --- a/editor/assets/default_prefab/light/Sphere Light.prefab.meta +++ b/editor/assets/default_prefab/light/Sphere Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "4182ee46-ffa0-4de2-b66b-c93cc6c7e9b8", diff --git a/editor/assets/default_prefab/light/Spot Light.prefab.meta b/editor/assets/default_prefab/light/Spot Light.prefab.meta index 911d5933b42..d60bc004f17 100644 --- a/editor/assets/default_prefab/light/Spot Light.prefab.meta +++ b/editor/assets/default_prefab/light/Spot Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "7a49aa24-bd7a-40a8-b31a-b2a9da85abcd", diff --git a/editor/assets/default_prefab/ui/Button.prefab.meta b/editor/assets/default_prefab/ui/Button.prefab.meta index 6b0771367ba..22327fc1710 100644 --- a/editor/assets/default_prefab/ui/Button.prefab.meta +++ b/editor/assets/default_prefab/ui/Button.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "90bdd2a9-2838-4888-b66c-e94c8b7a5169", diff --git a/editor/assets/default_prefab/ui/Canvas.prefab.meta b/editor/assets/default_prefab/ui/Canvas.prefab.meta index 4384e4d0773..a398ec48963 100644 --- a/editor/assets/default_prefab/ui/Canvas.prefab.meta +++ b/editor/assets/default_prefab/ui/Canvas.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "f773db21-62b8-4540-956a-29bacf5ddbf5", diff --git a/editor/assets/default_prefab/ui/EditBox.prefab b/editor/assets/default_prefab/ui/EditBox.prefab index a7de7d3c8fb..300ba6dc4e3 100644 --- a/editor/assets/default_prefab/ui/EditBox.prefab +++ b/editor/assets/default_prefab/ui/EditBox.prefab @@ -379,7 +379,7 @@ }, "_type": 1, "_fillType": 0, - "_sizeMode": 1, + "_sizeMode": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, diff --git a/editor/assets/default_prefab/ui/EditBox.prefab.meta b/editor/assets/default_prefab/ui/EditBox.prefab.meta index f3ead2aa227..d72c1f6fb58 100644 --- a/editor/assets/default_prefab/ui/EditBox.prefab.meta +++ b/editor/assets/default_prefab/ui/EditBox.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "05e79121-8675-4551-9ad7-1b901a4025db", diff --git a/editor/assets/default_prefab/ui/Graphics.prefab.meta b/editor/assets/default_prefab/ui/Graphics.prefab.meta index 406c853a9f5..7c692252572 100644 --- a/editor/assets/default_prefab/ui/Graphics.prefab.meta +++ b/editor/assets/default_prefab/ui/Graphics.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "c96e159e-43ea-4a16-8279-05bc39119d1a", diff --git a/editor/assets/default_prefab/ui/Label.prefab.meta b/editor/assets/default_prefab/ui/Label.prefab.meta index 2c633805df3..6a5eacbd453 100644 --- a/editor/assets/default_prefab/ui/Label.prefab.meta +++ b/editor/assets/default_prefab/ui/Label.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "36008810-7ad3-47c0-8112-e30aee089e45", diff --git a/editor/assets/default_prefab/ui/Layout.prefab.meta b/editor/assets/default_prefab/ui/Layout.prefab.meta index ac6f83cd8ab..01428016c51 100644 --- a/editor/assets/default_prefab/ui/Layout.prefab.meta +++ b/editor/assets/default_prefab/ui/Layout.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "a9ef7dfc-ea8b-4cf8-918e-36da948c4de0", diff --git a/editor/assets/default_prefab/ui/Mask.prefab.meta b/editor/assets/default_prefab/ui/Mask.prefab.meta index 2b415c21c59..377ec5e6f5a 100644 --- a/editor/assets/default_prefab/ui/Mask.prefab.meta +++ b/editor/assets/default_prefab/ui/Mask.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "7fa63aed-f3e2-46a5-8a7c-c1a1adf6cea6", diff --git a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta index 4876341a321..7072bfdef2b 100644 --- a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta +++ b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "f396261e-3e06-41ec-bdd6-9a8b6d99026f", diff --git a/editor/assets/default_prefab/ui/ProgressBar.prefab b/editor/assets/default_prefab/ui/ProgressBar.prefab index f87bd959eea..55faf5852a9 100644 --- a/editor/assets/default_prefab/ui/ProgressBar.prefab +++ b/editor/assets/default_prefab/ui/ProgressBar.prefab @@ -165,7 +165,7 @@ }, "_type": 1, "_fillType": 0, - "_sizeMode": 1, + "_sizeMode": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, @@ -245,7 +245,7 @@ }, "_type": 1, "_fillType": 0, - "_sizeMode": 1, + "_sizeMode": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, diff --git a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta index 2f564bd5be8..e73a3746162 100644 --- a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta +++ b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "0d9353c4-6fb9-49bb-bc62-77f1750078c2", diff --git a/editor/assets/default_prefab/ui/RichText.prefab.meta b/editor/assets/default_prefab/ui/RichText.prefab.meta index 09136191923..262b90f4b93 100644 --- a/editor/assets/default_prefab/ui/RichText.prefab.meta +++ b/editor/assets/default_prefab/ui/RichText.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "fc6bfcfa-8086-4326-809b-0ba1226bac7d", diff --git a/editor/assets/default_prefab/ui/ScrollView.prefab.meta b/editor/assets/default_prefab/ui/ScrollView.prefab.meta index a54b724011e..98626d08d6f 100644 --- a/editor/assets/default_prefab/ui/ScrollView.prefab.meta +++ b/editor/assets/default_prefab/ui/ScrollView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "c1baa707-78d6-4b89-8d5d-0b7fdf0c39bc", diff --git a/editor/assets/default_prefab/ui/Slider.prefab b/editor/assets/default_prefab/ui/Slider.prefab index c33106ae8e8..b404e1bb6b3 100644 --- a/editor/assets/default_prefab/ui/Slider.prefab +++ b/editor/assets/default_prefab/ui/Slider.prefab @@ -170,7 +170,7 @@ }, "_type": 0, "_fillType": 0, - "_sizeMode": 1, + "_sizeMode": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, @@ -311,7 +311,7 @@ }, "_type": 1, "_fillType": 0, - "_sizeMode": 1, + "_sizeMode": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, diff --git a/editor/assets/default_prefab/ui/Slider.prefab.meta b/editor/assets/default_prefab/ui/Slider.prefab.meta index e74b124a086..70669c12858 100644 --- a/editor/assets/default_prefab/ui/Slider.prefab.meta +++ b/editor/assets/default_prefab/ui/Slider.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "2bd7e5b6-cd8c-41a1-8136-ddb8efbf6326", diff --git a/editor/assets/default_prefab/ui/Sprite.prefab.meta b/editor/assets/default_prefab/ui/Sprite.prefab.meta index da1efd5e39a..26cd9988001 100644 --- a/editor/assets/default_prefab/ui/Sprite.prefab.meta +++ b/editor/assets/default_prefab/ui/Sprite.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "9db8cd0b-cbe4-42e7-96a9-a239620c0a9d", diff --git a/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta index 40cf1cc1d08..a257d54f0a8 100644 --- a/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta +++ b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "279ed042-5a65-4efe-9afb-2fc23c61e15a", diff --git a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta index cbfcc852751..cb3d5a47078 100644 --- a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta +++ b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "e5f21aad-3a69-4011-ac62-b74352ac025e", diff --git a/editor/assets/default_prefab/ui/TiledMap.prefab.meta b/editor/assets/default_prefab/ui/TiledMap.prefab.meta index 4b1b2c4e25c..53301ade82b 100644 --- a/editor/assets/default_prefab/ui/TiledMap.prefab.meta +++ b/editor/assets/default_prefab/ui/TiledMap.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "3139fa4f-8c42-4ce6-98be-15e848d9734c", diff --git a/editor/assets/default_prefab/ui/Toggle.prefab.meta b/editor/assets/default_prefab/ui/Toggle.prefab.meta index bd92c9057e5..c05f65aa9f0 100644 --- a/editor/assets/default_prefab/ui/Toggle.prefab.meta +++ b/editor/assets/default_prefab/ui/Toggle.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "0e89afe7-56de-4f99-96a1-cba8a75bedd2", diff --git a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta index 311dc9b3c86..e3affc6f159 100644 --- a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta +++ b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "2af73429-41d1-4346-9062-7798e42945dd", diff --git a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta index 9f090bd41eb..24a28385ecc 100644 --- a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta +++ b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "7e089eaf-fa97-40d7-8a20-741a152585df", diff --git a/editor/assets/default_prefab/ui/WebView.prefab.meta b/editor/assets/default_prefab/ui/WebView.prefab.meta index a5df7884ecc..7ad242dfe02 100644 --- a/editor/assets/default_prefab/ui/WebView.prefab.meta +++ b/editor/assets/default_prefab/ui/WebView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "9c541fa2-1dc8-4d8b-813a-aec89133f5b1", diff --git a/editor/assets/default_prefab/ui/Widget.prefab.meta b/editor/assets/default_prefab/ui/Widget.prefab.meta index bcf252290f4..e1ed816df8a 100644 --- a/editor/assets/default_prefab/ui/Widget.prefab.meta +++ b/editor/assets/default_prefab/ui/Widget.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "36ed4422-3542-4cc4-bf02-dc4bfc590836", diff --git a/editor/assets/default_prefab/ui/pageView.prefab.meta b/editor/assets/default_prefab/ui/pageView.prefab.meta index 95d4ec9593f..3c4e7e8d451 100644 --- a/editor/assets/default_prefab/ui/pageView.prefab.meta +++ b/editor/assets/default_prefab/ui/pageView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "20a5d8cb-ccad-4543-a937-fccd98c9f3de", diff --git a/editor/assets/tools/debug-view-runtime-control.prefab.meta b/editor/assets/tools/debug-view-runtime-control.prefab.meta index 8ed35ee2c61..34527f2712b 100644 --- a/editor/assets/tools/debug-view-runtime-control.prefab.meta +++ b/editor/assets/tools/debug-view-runtime-control.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.46", + "ver": "1.1.48", "importer": "prefab", "imported": true, "uuid": "7f4ddeab-efa9-4b76-bf6a-029520f68461", From 62a9da122ec4b757adc21f803c791752946e2541 Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Mon, 21 Aug 2023 16:45:53 +0800 Subject: [PATCH 206/232] Use sdl2 on mac platform (#16030) * Use sdl2 on mac platform --- native/CMakeLists.txt | 2 +- native/cocos/engine/Engine.cpp | 2 +- native/cocos/platform/SDLHelper.cpp | 12 ++ native/cocos/platform/SDLHelper.h | 3 +- .../platform/linux/modules/SystemWindow.cpp | 2 +- native/cocos/platform/mac/AppDelegate.h | 5 - native/cocos/platform/mac/AppDelegate.mm | 69 -------- native/cocos/platform/mac/MacPlatform.h | 4 +- native/cocos/platform/mac/MacPlatform.mm | 113 ++++--------- native/cocos/platform/mac/View.mm | 159 ------------------ native/cocos/platform/mac/modules/Screen.mm | 8 +- .../cocos/platform/mac/modules/SystemWindow.h | 34 ++-- .../platform/mac/modules/SystemWindow.mm | 154 +++++++++-------- .../mac/modules/SystemWindowManager.h | 9 +- .../mac/modules/SystemWindowManager.mm | 67 +++++--- 15 files changed, 200 insertions(+), 443 deletions(-) diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 8e0e4296446..7125a5ff234 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -519,7 +519,7 @@ cocos_source_files( ) ############ main -if(NOT USE_SERVER_MODE AND (WINDOWS OR LINUX)) +if(NOT USE_SERVER_MODE AND (WINDOWS OR LINUX OR MACOSX)) cocos_source_files( cocos/platform/SDLHelper.h cocos/platform/SDLHelper.cpp diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index 86d7f48e69e..bae11828fdd 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -275,7 +275,7 @@ void Engine::tick() { // iOS/macOS use its own fps limitation algorithm. // Windows for Editor should not sleep,because Editor call tick function synchronously -#if (CC_PLATFORM == CC_PLATFORM_ANDROID || (CC_PLATFORM == CC_PLATFORM_WINDOWS && !CC_EDITOR) || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY) || (defined(CC_SERVER_MODE) && (CC_PLATFORM == CC_PLATFORM_MAC_OSX)) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || (CC_PLATFORM == CC_PLATFORM_WINDOWS && !CC_EDITOR) || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY || CC_PLATFORM == CC_PLATFORM_MACOS) if (dtNS < static_cast(_preferredNanosecondsPerFrame)) { CC_PROFILE(EngineSleep); std::this_thread::sleep_for( diff --git a/native/cocos/platform/SDLHelper.cpp b/native/cocos/platform/SDLHelper.cpp index 56e71618b8c..4c477471bf7 100644 --- a/native/cocos/platform/SDLHelper.cpp +++ b/native/cocos/platform/SDLHelper.cpp @@ -174,6 +174,8 @@ void SDLHelper::dispatchWindowEvent(uint32_t windowId, const SDL_WindowEvent &we events::WindowEvent::broadcast(ev); break; } +// On the mac platform this is done via setframesize int the view. +#if !(CC_PLATFORM == CC_PLATFORM_MACOS) case SDL_WINDOWEVENT_SIZE_CHANGED: { ev.type = WindowEvent::Type::SIZE_CHANGED; ev.width = wevent.data1; @@ -188,6 +190,7 @@ void SDLHelper::dispatchWindowEvent(uint32_t windowId, const SDL_WindowEvent &we events::WindowEvent::broadcast(ev); break; } +#endif case SDL_WINDOWEVENT_HIDDEN: { ev.type = WindowEvent::Type::HIDDEN; events::WindowEvent::broadcast(ev); @@ -371,9 +374,18 @@ uintptr_t SDLHelper::getWindowHandle(SDL_Window *window) { return reinterpret_cast(wmInfo.info.win.window); #elif (CC_PLATFORM == CC_PLATFORM_LINUX) return reinterpret_cast(wmInfo.info.x11.window); +#elif (CC_PLATFORM == CC_PLATFORM_MACOS) + return reinterpret_cast(wmInfo.info.cocoa.window); #endif CC_ABORT(); return 0; } +Vec2 SDLHelper::getWindowPosition(SDL_Window *window) { + int x = 0; + int y = 0; + SDL_GetWindowPosition(window, &x, &y); + return Vec2(x, y); +} + } // namespace cc diff --git a/native/cocos/platform/SDLHelper.h b/native/cocos/platform/SDLHelper.h index 2f368a00b95..4647f4d658b 100644 --- a/native/cocos/platform/SDLHelper.h +++ b/native/cocos/platform/SDLHelper.h @@ -25,6 +25,7 @@ #pragma once #include #include "engine/EngineEvents.h" +#include "math/Vec2.h" struct SDL_Window; union SDL_Event; @@ -52,7 +53,7 @@ class SDLHelper { static uintptr_t getDisplay(SDL_Window* window); #endif static void setCursorEnabled(bool value); - + static Vec2 getWindowPosition(SDL_Window *window); private: static void dispatchSDLEvent(uint32_t windowId, const SDL_Event& sdlEvent); static void dispatchWindowEvent(uint32_t windowId, const SDL_WindowEvent& wevent); diff --git a/native/cocos/platform/linux/modules/SystemWindow.cpp b/native/cocos/platform/linux/modules/SystemWindow.cpp index 7c3d280aa30..43ffcfdac60 100644 --- a/native/cocos/platform/linux/modules/SystemWindow.cpp +++ b/native/cocos/platform/linux/modules/SystemWindow.cpp @@ -80,7 +80,7 @@ void SystemWindow::closeWindow() { #ifndef CC_SERVER_MODE SDL_Event et; et.type = SDL_QUIT; - auto posted = SDL_PushEvent(&et); + SDL_PushEvent(&et); #endif } diff --git a/native/cocos/platform/mac/AppDelegate.h b/native/cocos/platform/mac/AppDelegate.h index 23ef37e266f..afe71490678 100644 --- a/native/cocos/platform/mac/AppDelegate.h +++ b/native/cocos/platform/mac/AppDelegate.h @@ -28,10 +28,5 @@ @interface AppDelegate : NSObject - (void)applicationDidFinishLaunching:(NSNotification*)aNotification; -- (void)windowWillMiniaturizeNotification; -- (void)windowDidDeminiaturizeNotification; -- (void)windowWillCloseNotification; -- (void)applicationWillTerminate:(NSNotification*)aNotification; - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication; -- (NSWindow*)getWindow; @end diff --git a/native/cocos/platform/mac/AppDelegate.mm b/native/cocos/platform/mac/AppDelegate.mm index 40b85baf1a8..91627d7dc00 100644 --- a/native/cocos/platform/mac/AppDelegate.mm +++ b/native/cocos/platform/mac/AppDelegate.mm @@ -32,76 +32,14 @@ of this software and associated engine source code (the "Software"), a limited, @interface AppDelegate () { NSWindow* _window; - // Game* _game; cc::MacPlatform* _platform; } @end @implementation AppDelegate -- (void)createLeftBottomWindow:(NSString*)title width:(int)w height:(int)h { - [self createWindow:title xPos:0 yPos:0 width:w height:h]; -} - -- (NSWindow*)createWindow:(NSString*)title xPos:(int)x yPos:(int)y width:(int)w height:(int)h { - //_window.title = title; - NSRect rect = NSMakeRect(x, y, w, h); - NSWindow* window = [[NSWindow alloc] initWithContentRect:rect - styleMask:NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable - backing:NSBackingStoreBuffered - defer:NO]; - if (!window) { - NSLog(@"Failed to allocated the window."); - return nullptr; - } - - ViewController* viewController = [[ViewController alloc] initWithSize:rect]; - window.contentViewController = viewController; - window.contentView = viewController.view; - [viewController release]; - viewController = nil; - - window.title = title; - [window.contentView setWantsBestResolutionOpenGLSurface:YES]; - [window makeKeyAndOrderFront:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowWillMiniaturizeNotification) - name:NSWindowWillMiniaturizeNotification - object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowDidDeminiaturizeNotification) - name:NSWindowDidDeminiaturizeNotification - object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowWillCloseNotification) - name:NSWindowWillCloseNotification - object:window]; - if (!_window) { - _window = window; - } - return window; -} - - (void)applicationDidFinishLaunching:(NSNotification*)aNotification { _platform = dynamic_cast(cc::BasePlatform::getPlatform()); - CC_ASSERT_NOT_NULL(_platform); - _platform->loop(); -} - -- (void)windowWillMiniaturizeNotification { - _platform->onPause(); -} - -- (void)windowDidDeminiaturizeNotification { - _platform->onResume(); -} - -- (void)windowWillCloseNotification { - _platform->onClose(); -} - -- (NSWindow*)getWindow { - return _window; } - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender @@ -109,13 +47,6 @@ - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sende return _platform->readyToExit() ? NSTerminateNow : NSTerminateLater; } -- (void)applicationWillTerminate:(NSNotification*)aNotification { - // delete _game; - //FIXME: will crash if relase it here. - // [_window release]; - _platform->onDestroy(); -} - - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication { return YES; } diff --git a/native/cocos/platform/mac/MacPlatform.h b/native/cocos/platform/mac/MacPlatform.h index 13485718cad..3b7da485c02 100644 --- a/native/cocos/platform/mac/MacPlatform.h +++ b/native/cocos/platform/mac/MacPlatform.h @@ -27,7 +27,7 @@ #include "platform/UniversalPlatform.h" namespace cc { - +class SystemWindowManager; class MacPlatform : public UniversalPlatform { public: MacPlatform() = default; @@ -58,8 +58,10 @@ class MacPlatform : public UniversalPlatform { void onPause() override; void onResume() override; void onClose() override; + void pollEvent() override; private: bool _readyToExit{false}; + std::shared_ptr _windowManager{nullptr}; }; } // namespace cc diff --git a/native/cocos/platform/mac/MacPlatform.mm b/native/cocos/platform/mac/MacPlatform.mm index 2266df306a8..722b358f2ed 100644 --- a/native/cocos/platform/mac/MacPlatform.mm +++ b/native/cocos/platform/mac/MacPlatform.mm @@ -32,7 +32,7 @@ of this software and associated engine source code (the "Software"), a limited, #include "modules/Network.h" #include "modules/System.h" #include "modules/Vibrator.h" - +#include "platform/SDLHelper.h" #if defined(CC_SERVER_MODE) #include "platform/empty/modules/Screen.h" #include "platform/empty/modules/SystemWindow.h" @@ -44,87 +44,26 @@ of this software and associated engine source code (the "Software"), a limited, #endif #import + #include "base/memory/Memory.h" extern int cocos_main(int argc, const char **argv); -@interface MyTimer : NSObject { - cc::MacPlatform *_platform; - NSTimer *_timer; -} -- (instancetype)initWithApp:(cc::MacPlatform *)platform fps:(int)fps; -- (void)start; -- (void)changeFPS; -- (void)pause; -- (void)resume; -@end - -@implementation MyTimer - -- (instancetype)initWithApp:(cc::MacPlatform *)platform fps:(int)fps { - if (self = [super init]) { - _platform = platform; - } - return self; -} -#if CC_EDITOR - - (void)start { } - - (void)changeFPS { } - - (void)pause { } - - (void)resume { } -#else -- (void)start { - int32_t fps = _platform->getFps(); - _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f / fps - target:self - selector:@selector(renderScene) - userInfo:nil - repeats:YES]; -} - -- (void)pause { - [_timer invalidate]; -} - -- (void)resume { - [self start]; -} - -- (void)changeFPS { - [self pause]; - [self resume]; -} - -- (void)renderScene { - _platform->runTask(); -} - -- (bool) isValid { - return [_timer valid]; -} -#endif -@end - -namespace { -MyTimer *_timer; -} - namespace cc { MacPlatform::~MacPlatform() { - [_timer release]; } int32_t MacPlatform::init() { - _timer = [[MyTimer alloc] initWithApp:this fps:60]; registerInterface(std::make_shared()); registerInterface(std::make_shared()); registerInterface(std::make_shared()); registerInterface(std::make_shared()); registerInterface(std::make_shared()); - registerInterface(std::make_shared()); + _windowManager = std::make_shared(); + registerInterface(_windowManager); registerInterface(std::make_shared()); - return 0; + return _windowManager->init(); } bool MacPlatform::readyToExit() { @@ -143,16 +82,12 @@ - (bool) isValid { runTask(); return 1; #else - [_timer start]; - NSArray *arguments = [[NSProcessInfo processInfo] arguments]; - int argc = static_cast(arguments.count); - std::vector argv; - argv.reserve(argc); - for (id arg in arguments) { - argv.emplace_back([arg UTF8String]); + while(!_readyToExit) { + pollEvent(); + runTask(); } - - return cocos_main(argc, argv.data()); + onDestroy(); + return 0; #endif } @@ -164,30 +99,38 @@ - (bool) isValid { } return 0; #else + NSArray *arguments = [[NSProcessInfo processInfo] arguments]; + argc = static_cast(arguments.count); + std::vector argVec; + argVec.reserve(argc); + for (id arg in arguments) { + argVec.emplace_back([arg UTF8String]); + } + id delegate = [[AppDelegate alloc] init]; - NSApplication.sharedApplication.delegate = delegate; - return NSApplicationMain(argc, argv); + [NSApp setDelegate:delegate]; + + if(cocos_main(argc, argVec.data()) != 0) { + return -1; + } + + return loop(); #endif } void MacPlatform::setFps(int32_t fps) { if(fps != getFps()) { UniversalPlatform::setFps(fps); - [_timer changeFPS]; } } void MacPlatform::onPause() { - [_timer pause]; - cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::HIDDEN; cc::events::WindowEvent::broadcast(ev); } void MacPlatform::onResume() { - [_timer resume]; - cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::SHOW; cc::events::WindowEvent::broadcast(ev); @@ -199,8 +142,12 @@ - (bool) isValid { cc::events::WindowEvent::broadcast(ev); } -cc::ISystemWindow *MacPlatform::createNativeWindow(uint32_t windowId, void *externalHandle) { +cc::ISystemWindow *MacPlatform::createNativeWindow(uint32_t windowId, void *externalHandle) { return ccnew SystemWindow(windowId, externalHandle); } +void MacPlatform::pollEvent() { + _windowManager->processEvent(); +} + } // namespace cc diff --git a/native/cocos/platform/mac/View.mm b/native/cocos/platform/mac/View.mm index 6fbb047f3aa..622a6097ae8 100644 --- a/native/cocos/platform/mac/View.mm +++ b/native/cocos/platform/mac/View.mm @@ -38,8 +38,6 @@ of this software and associated engine source code (the "Software"), a limited, @implementation View { cc::MouseEvent _mouseEvent; cc::KeyboardEvent _keyboardEvent; - NSRect _contentRect; - AppDelegate *_delegate; } - (CALayer *)makeBackingLayer { @@ -53,7 +51,6 @@ - (CALayer *)makeBackingLayer { - (instancetype)initWithFrame:(NSRect)frameRect { if (self = [super initWithFrame:frameRect]) { [self.window makeFirstResponder:self]; - _delegate = [[NSApplication sharedApplication] delegate]; int pixelRatio = [[NSScreen mainScreen] backingScaleFactor]; CGSize size = CGSizeMake(frameRect.size.width * pixelRatio, frameRect.size.height * pixelRatio); // Create CAMetalLayer @@ -74,11 +71,6 @@ - (instancetype)initWithFrame:(NSRect)frameRect { owner:self userInfo:nil] autorelease]; [self addTrackingArea:trackingArea]; - - NSWindow* window = self.window; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidMove:) name:NSWindowDidMoveNotification - object:window]; - [self updateContentRect]; } return self; } @@ -94,7 +86,6 @@ - (void)mtkView:(nonnull MTKView *)view drawableSizeWillChange:(CGSize)size { ev.width = static_cast(size.width); ev.height = static_cast(size.height); cc::events::WindowEvent::broadcast(ev); - [self updateContentRect]; } - (void)displayLayer:(CALayer *)layer { @@ -118,7 +109,6 @@ - (void)setFrameSize:(NSSize)newSize { cc::events::WindowEvent::broadcast(ev); } - [self updateContentRect]; } - (void)viewDidChangeBackingProperties { @@ -142,24 +132,6 @@ - (void)viewDidChangeBackingProperties { ev.height = static_cast(height); cc::events::WindowEvent::broadcast(ev); } - [self updateContentRect]; -} - -- (void)keyDown:(NSEvent *)event { - _keyboardEvent.windowId = [self getWindowId]; - _keyboardEvent.key = translateKeycode(event.keyCode); - _keyboardEvent.action = [event isARepeat] ? cc::KeyboardEvent::Action::REPEAT - : cc::KeyboardEvent::Action::PRESS; - [self setModifierFlags:event]; - cc::events::Keyboard::broadcast(_keyboardEvent); -} - -- (void)keyUp:(NSEvent *)event { - _keyboardEvent.windowId = [self getWindowId]; - _keyboardEvent.key = translateKeycode(event.keyCode); - _keyboardEvent.action = cc::KeyboardEvent::Action::RELEASE; - [self setModifierFlags:event]; - cc::events::Keyboard::broadcast(_keyboardEvent); } - (void)flagsChanged:(NSEvent *)event { @@ -204,141 +176,10 @@ - (void)setModifierFlags:(NSEvent *)event { _keyboardEvent.metaKeyActive = false; } -- (void)mouseDown:(NSEvent *)event { - [self sendMouseEvent:0 - type:cc::MouseEvent::Type::DOWN - event:event]; -} - -- (void)mouseUp:(NSEvent *)event { - [self sendMouseEvent:0 - type:cc::MouseEvent::Type::UP - event:event]; -} - -- (void)mouseDragged:(NSEvent *)event { - [self mouseMoved:event]; -} - -- (void)mouseMoved:(NSEvent *)event { - [self sendMouseEvent:0 - type:cc::MouseEvent::Type::MOVE - event:event]; -} - -- (void)otherMouseDown:(NSEvent *)event { - [self sendMouseEvent:[self translateButtonNumber:event.buttonNumber] - type:cc::MouseEvent::Type::DOWN - event:event]; -} - -- (void)otherMouseUp:(NSEvent *)event { - [self sendMouseEvent:[self translateButtonNumber:event.buttonNumber] - type:cc::MouseEvent::Type::UP - event:event]; -} - -- (int)translateButtonNumber:(NSInteger)buttonNumber { - if (buttonNumber == 1) // left - return 0; - else if (buttonNumber == 2) // right - return 2; - else - return 1; -} - -- (void)scrollWheel:(NSEvent *)event { - double deltaX = [event scrollingDeltaX]; - double deltaY = [event scrollingDeltaY]; - - if ([event hasPreciseScrollingDeltas]) { - deltaX *= 0.1; - deltaY *= 0.1; - } - - if (fabs(deltaX) > 0.0 || fabs(deltaY) > 0.0) { - _mouseEvent.type = cc::MouseEvent::Type::WHEEL; - _mouseEvent.button = 0; - _mouseEvent.x = deltaX; - _mouseEvent.y = deltaY; - _mouseEvent.windowId = [self getWindowId]; - cc::events::Mouse::broadcast(_mouseEvent); - } -} - -- (void)rightMouseDown:(NSEvent *)event { - [self sendMouseEvent:2 - type:cc::MouseEvent::Type::DOWN - event:event]; -} - -- (void)rightMouseUp:(NSEvent *)event { - [self sendMouseEvent:2 - type:cc::MouseEvent::Type::UP - event:event]; -} - - (BOOL)acceptsFirstResponder { return YES; } -- (void)updateContentRect { - NSWindow* window = self.window; - _contentRect = [window contentRectForFrameRect:[window frame]]; -} - -- (void)windowDidMove:(NSNotification *)aNotification { - [self updateContentRect]; -} - -- (void)sendMouseEvent:(int)button type:(cc::MouseEvent::Type)type event:(NSEvent *)event { - _mouseEvent.windowId = [self getWindowId]; - _mouseEvent.type = type; - _mouseEvent.button = button; - _mouseEvent.xDelta = [event deltaX]; - _mouseEvent.yDelta = [event deltaY]; - - auto *windowMgr = CC_GET_PLATFORM_INTERFACE(cc::SystemWindowManager); - auto *window = static_cast( windowMgr->getWindowFromNSWindow([self window])); - const NSRect contentRect = [self frame]; - if(!window->isPointerLock()) { - const NSPoint pos = [event locationInWindow]; - _mouseEvent.x = pos.x; - _mouseEvent.y = contentRect.size.height - pos.y; - } else { - if(type == cc::MouseEvent::Type::MOVE) { - // Out of window only happens when mouse is moved. - _mouseEvent.x = _mouseEvent.x + [event deltaX]; - _mouseEvent.y = _mouseEvent.y + [event deltaY]; - float xMin = 0, xMax = 0; - float yMin = 0, yMax = 0; - xMax = contentRect.size.width; - yMax = contentRect.size.height; - --xMax; - --yMax; - if (_mouseEvent.x > xMax) { - _mouseEvent.x = xMax; - } else if (_mouseEvent.x < xMin) { - _mouseEvent.x = xMin; - } - - if (_mouseEvent.y > yMax) { - _mouseEvent.y = yMax; - } else if (_mouseEvent.y < yMin) { - _mouseEvent.y = yMin; - } - } - - auto mainDisplayId = CGMainDisplayID(); - - float windowX = _contentRect.origin.x; - float windowY = - CGDisplayPixelsHigh(mainDisplayId) - _contentRect.origin.y - _contentRect.size.height; - - window->setLastMousePos(windowX + _mouseEvent.x, windowY + _mouseEvent.y); - } - cc::events::Mouse::broadcast(_mouseEvent); -} - (int)getWindowId { auto *windowMgr = CC_GET_PLATFORM_INTERFACE(cc::SystemWindowManager); auto *window = windowMgr->getWindowFromNSWindow([self window]); diff --git a/native/cocos/platform/mac/modules/Screen.mm b/native/cocos/platform/mac/modules/Screen.mm index cad4ed26f44..e2049c8f135 100644 --- a/native/cocos/platform/mac/modules/Screen.mm +++ b/native/cocos/platform/mac/modules/Screen.mm @@ -31,7 +31,9 @@ of this software and associated engine source code (the "Software"), a limited, #include "base/Macros.h" #include "cocos/bindings/jswrapper/SeApi.h" - +#include "platform/interfaces/modules/ISystemWindowManager.h" +#include "platform/interfaces/modules/ISystemWindow.h" +#include "application/ApplicationManager.h" namespace cc { int Screen::getDPI() const { @@ -50,7 +52,9 @@ of this software and associated engine source code (the "Software"), a limited, global->getProperty("devicePixelRatio", &devicePixelRatioVal); return devicePixelRatioVal.isNumber() ? devicePixelRatioVal.toFloat() : 1.F; #else - return [[[[NSApplication sharedApplication] delegate] getWindow] backingScaleFactor]; + auto* window = CC_GET_MAIN_SYSTEM_WINDOW(); + NSWindow* nsWindow = reinterpret_cast(window->getWindowHandle()) ; + return [nsWindow backingScaleFactor]; #endif } diff --git a/native/cocos/platform/mac/modules/SystemWindow.h b/native/cocos/platform/mac/modules/SystemWindow.h index 5a58f9c685b..8678c3e09ef 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.h +++ b/native/cocos/platform/mac/modules/SystemWindow.h @@ -24,23 +24,28 @@ #pragma once -#include #include +#include #include "platform/interfaces/modules/ISystemWindow.h" +struct SDL_Window; namespace cc { +class SDLHelper; +class CC_DLL SystemWindow : public ISystemWindow { + friend class SystemWindowManager; -class SystemWindow : public ISystemWindow { public: explicit SystemWindow(uint32_t windowId, void* externalHandle); ~SystemWindow() override; + bool createWindow(const char* title, + int w, int h, int flags) override; bool createWindow(const char* title, int x, int y, int w, int h, int flags) override; - bool createWindow(const char* title, - int w, int h, int flags) override; void closeWindow() override; + + virtual uint32_t getWindowId() const override { return _windowId; } uintptr_t getWindowHandle() const override; Size getViewSize() const override; @@ -48,27 +53,20 @@ class SystemWindow : public ISystemWindow { _width = w; _height = h; } - - uint32_t getWindowId() const override; - NSWindow* getNSWindow() const { return _window; } - /* @brief enable/disable(lock) the cursor, default is enabled */ void setCursorEnabled(bool value) override; - - bool isPointerLock() const; - void setLastMousePos(float x, float y); - + NSWindow* getNSWindow() const; private: - bool _pointerLock{false}; - float _lastMousePosX{0.0F}; - float _lastMousePosY{0.0F}; - int32_t _width{0}; - int32_t _height{0}; + SDL_Window* getSDLWindow() const { return _window; } + void initWindowProperty(SDL_Window* window, const char *title, int x, int y, int w, int h); + uint32_t _width{0}; + uint32_t _height{0}; uint32_t _windowId{0}; uintptr_t _windowHandle{0}; - NSWindow* _window{nullptr}; + SDL_Window* _window{nullptr}; }; + } // namespace cc diff --git a/native/cocos/platform/mac/modules/SystemWindow.mm b/native/cocos/platform/mac/modules/SystemWindow.mm index bb8d4760ac0..0b4bcc42863 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.mm +++ b/native/cocos/platform/mac/modules/SystemWindow.mm @@ -1,18 +1,17 @@ /**************************************************************************** - Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. http://www.cocos.com Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, @@ -24,41 +23,74 @@ of this software and associated engine source code (the "Software"), a limited, ****************************************************************************/ #include "platform/mac/modules/SystemWindow.h" -#import -#include "platform/BasePlatform.h" -#include "platform/interfaces/modules/IScreen.h" - -#if CC_EDITOR +#include "platform/mac/ViewController.h" +#include "base/Log.h" +#include "base/Macros.h" + +// SDL headers +#include +#include "SDL2/SDL.h" +#include "SDL2/SDL_main.h" +#include "SDL2/SDL_syswm.h" +#include "engine/EngineEvents.h" +#include "platform/SDLHelper.h" +#import +#import +#import #import -#else -#include "platform/mac/AppDelegate.h" -#endif +#include "platform/interfaces/modules/IScreen.h" +#include "platform/BasePlatform.h" namespace cc { - SystemWindow::SystemWindow(uint32_t windowId, void *externalHandle) - : _windowId(windowId) { +: _windowId(windowId) { if (externalHandle) { _windowHandle = reinterpret_cast(externalHandle); } } -SystemWindow::~SystemWindow() = default; +SystemWindow::~SystemWindow() { + _windowHandle = 0; + _windowId = 0; +} + +void SystemWindow::initWindowProperty(SDL_Window* window, const char *title, int x, int y, int w, int h) { + CC_ASSERT(window != nullptr); + auto* nsWindow = reinterpret_cast(SDLHelper::getWindowHandle(window)); + NSRect rect = NSMakeRect(x, y, w, h); + ViewController* viewController = [[ViewController alloc] initWithSize:rect]; + nsWindow.contentViewController = viewController; + nsWindow.contentView = viewController.view; + NSString *astring = [NSString stringWithUTF8String:title]; + nsWindow.title = astring; + [nsWindow.contentView setWantsBestResolutionOpenGLSurface:YES]; + [nsWindow makeKeyAndOrderFront:nil]; + + [viewController release]; + viewController = nil; + _windowHandle = reinterpret_cast(nsWindow.contentView) ; + + auto dpr = [nsWindow backingScaleFactor]; + _width = w * dpr; + _height = h * dpr; +} + +NSWindow* SystemWindow::getNSWindow() const { + CC_ASSERT(_window != nullptr); + return reinterpret_cast(SDLHelper::getWindowHandle(_window)); +} bool SystemWindow::createWindow(const char *title, int w, int h, int flags) { #if CC_EDITOR - return createWindow(title, 0, 0, w, h, flags); + return createWindow(title, 0, 0, w, h, flags); #else - AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; - NSString *aString = [NSString stringWithUTF8String:title]; - _window = [delegate createLeftBottomWindow:aString width:w height:h]; - NSView *view = [_window contentView]; - _windowHandle = reinterpret_cast(view); - - auto dpr = BasePlatform::getPlatform()->getInterface()->getDevicePixelRatio(); - _width = w * dpr; - _height = h * dpr; + _window = SDLHelper::createWindow(title, w, h, flags); + if (!_window) { + return false; + } + Vec2 pos = SDLHelper::getWindowPosition(_window); + initWindowProperty(_window, title, pos.x, pos.y, w, h); return true; #endif } @@ -76,67 +108,33 @@ of this software and associated engine source code (the "Software"), a limited, _windowHandle = reinterpret_cast(layer); return true; #else - AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; - NSString *aString = [NSString stringWithUTF8String:title]; - _window = [delegate createWindow:aString xPos:x yPos:y width:w height:h]; - NSView *view = [_window contentView]; - _windowHandle = reinterpret_cast(view); - - auto dpr = BasePlatform::getPlatform()->getInterface()->getDevicePixelRatio(); - _width = w * dpr; - _height = h * dpr; + _window = SDLHelper::createWindow(title, x, y, w, h, flags); + if (!_window) { + return false; + } + initWindowProperty(_window, title, x, y, w, h); return true; #endif } void SystemWindow::closeWindow() { - //id window = [[[NSApplication sharedApplication] delegate] getWindow]; - if (_window) { - [_window close]; - _window = nullptr; - } -} - -void SystemWindow::setCursorEnabled(bool value) { - CGError result; - if(value) { - result = CGAssociateMouseAndMouseCursorPosition(YES); - [NSCursor unhide]; - if(_pointerLock) { - CGPoint point = - CGPointMake((float)_lastMousePosX, _lastMousePosY); - CGWarpMouseCursorPosition(point); - } - _pointerLock = false; - } else { - result = CGAssociateMouseAndMouseCursorPosition(NO); - [NSCursor hide]; - _pointerLock = true; - } - CC_ASSERT(result == kCGErrorSuccess); - events::PointerLock::broadcast(!value); +#ifndef CC_SERVER_MODE + SDL_Event et; + et.type = SDL_QUIT; + SDL_PushEvent(&et); +#endif } uintptr_t SystemWindow::getWindowHandle() const { - //NSView *view = [[[[NSApplication sharedApplication] delegate] getWindow] contentView]; return _windowHandle; } -SystemWindow::Size SystemWindow::getViewSize() const { - return Size{static_cast(_width), static_cast(_height)}; -} - -uint32_t SystemWindow::getWindowId() const { - return _windowId; -} - -bool SystemWindow::isPointerLock() const { - return _pointerLock; +void SystemWindow::setCursorEnabled(bool value) { + SDLHelper::setCursorEnabled(value); } -void SystemWindow::setLastMousePos(float x, float y) { - _lastMousePosX = x; - _lastMousePosY = y; +SystemWindow::Size SystemWindow::getViewSize() const { + return Size{static_cast(_width), static_cast(_height)}; } } // namespace cc diff --git a/native/cocos/platform/mac/modules/SystemWindowManager.h b/native/cocos/platform/mac/modules/SystemWindowManager.h index b2fefa440ff..699832e0c9d 100644 --- a/native/cocos/platform/mac/modules/SystemWindowManager.h +++ b/native/cocos/platform/mac/modules/SystemWindowManager.h @@ -23,7 +23,6 @@ ****************************************************************************/ #pragma once - #include #include "base/std/container/unordered_map.h" #include "platform/interfaces/modules/ISystemWindowManager.h" @@ -36,17 +35,17 @@ class ISystemWindow; class SystemWindowManager : public ISystemWindowManager { public: - explicit SystemWindowManager() = default; + SystemWindowManager() = default; - int init() override { return 0; } - void processEvent() override {} + int init() override; + void processEvent() override; ISystemWindow *createWindow(const ISystemWindowInfo &info) override; ISystemWindow *getWindow(uint32_t windowId) const override; const SystemWindowMap &getWindows() const override { return _windows; } + ISystemWindow *getWindowFromSDLWindow(SDL_Window *window) const; ISystemWindow *getWindowFromNSWindow(NSWindow *window) const; - private: uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID SystemWindowMap _windows; diff --git a/native/cocos/platform/mac/modules/SystemWindowManager.mm b/native/cocos/platform/mac/modules/SystemWindowManager.mm index 61520c056f1..bcfe9f987b1 100644 --- a/native/cocos/platform/mac/modules/SystemWindowManager.mm +++ b/native/cocos/platform/mac/modules/SystemWindowManager.mm @@ -1,18 +1,17 @@ /**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. http://www.cocos.com Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, @@ -21,9 +20,10 @@ of this software and associated engine source code (the "Software"), a limited, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ****************************************************************************/ +****************************************************************************/ #include "SystemWindowManager.h" +#include "SDL2/SDL_events.h" #include "platform/BasePlatform.h" #include "platform/SDLHelper.h" #include "platform/interfaces/modules/ISystemWindowManager.h" @@ -31,19 +31,27 @@ of this software and associated engine source code (the "Software"), a limited, namespace cc { -ISystemWindow *SystemWindowManager::getWindow(uint32_t windowId) const { - if (windowId == 0) { - return nullptr; - } +int SystemWindowManager::init() { + return SDLHelper::init(); +} - auto iter = _windows.find(windowId); - if (iter != _windows.end()) { - return iter->second.get(); +void SystemWindowManager::processEvent() { + SDL_Event sdlEvent; + while (SDL_PollEvent(&sdlEvent) != 0) { + SDL_Window *sdlWindow = SDL_GetWindowFromID(sdlEvent.window.windowID); + // SDL_Event like SDL_QUIT does not associate a window + if (!sdlWindow) { + SDLHelper::dispatchSDLEvent(0, sdlEvent); + } else { + ISystemWindow *window = getWindowFromSDLWindow(sdlWindow); + CC_ASSERT(window); + uint32_t windowId = window->getWindowId(); + SDLHelper::dispatchSDLEvent(windowId, sdlEvent); + } } - return nullptr; } -ISystemWindow *SystemWindowManager::createWindow(const cc::ISystemWindowInfo &info) { +ISystemWindow *SystemWindowManager::createWindow(const ISystemWindowInfo &info) { ISystemWindow *window = BasePlatform::getPlatform()->createNativeWindow(_nextWindowId, info.externalHandle); if (window) { if (!info.externalHandle) { @@ -55,6 +63,27 @@ of this software and associated engine source code (the "Software"), a limited, return window; } +ISystemWindow *SystemWindowManager::getWindow(uint32_t windowId) const { + if (windowId == 0) + return nullptr; + + auto iter = _windows.find(windowId); + if (iter != _windows.end()) + return iter->second.get(); + return nullptr; +} + +cc::ISystemWindow *SystemWindowManager::getWindowFromSDLWindow(SDL_Window *window) const { + for (const auto &iter : _windows) { + SystemWindow *sysWindow = static_cast(iter.second.get()); + SDL_Window *sdlWindow = sysWindow->getSDLWindow(); + if (sdlWindow == window) { + return sysWindow; + } + } + return nullptr; +} + ISystemWindow *SystemWindowManager::getWindowFromNSWindow(NSWindow *window) const { for (const auto &iter : _windows) { SystemWindow *sysWindow = static_cast(iter.second.get()); From d78725eb3a5ca639ea3888e4f24fa462ccd91b79 Mon Sep 17 00:00:00 2001 From: fqamic Date: Mon, 21 Aug 2023 17:11:40 +0800 Subject: [PATCH 207/232] Adaptation of the xr platform 3.8.1 modification (#16056) * feat: xr sync android template for manifest * fix: for xr platform, compatible with historical packaging tool usage * improve: annotation optimization --- .../source/platforms/android.ts | 71 +++++++++++++++++++ .../template/app/AndroidManifest.xml | 4 +- .../template/instantapp/AndroidManifest.xml | 4 +- .../xr-meta/template/app/AndroidManifest.xml | 4 +- .../template/instantapp/AndroidManifest.xml | 4 +- .../template/app/AndroidManifest.xml | 4 +- .../template/instantapp/AndroidManifest.xml | 4 +- .../xr-pico/template/app/AndroidManifest.xml | 4 +- .../template/instantapp/AndroidManifest.xml | 4 +- .../xr-rokid/template/app/AndroidManifest.xml | 4 +- .../template/instantapp/AndroidManifest.xml | 4 +- .../template/app/AndroidManifest.xml | 4 +- .../template/instantapp/AndroidManifest.xml | 4 +- 13 files changed, 95 insertions(+), 24 deletions(-) diff --git a/scripts/native-pack-tool/source/platforms/android.ts b/scripts/native-pack-tool/source/platforms/android.ts index 6cb7d8f1260..03d3067a868 100644 --- a/scripts/native-pack-tool/source/platforms/android.ts +++ b/scripts/native-pack-tool/source/platforms/android.ts @@ -142,6 +142,46 @@ export class AndroidPackTool extends NativePackTool { return await this.copyToDist(); } + /** + * Deprecated, only be compatible with historical packaging tools + */ + protected async setOrientation() { + const cfg = this.params.platformParams.orientation; + const manifestPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'app/AndroidManifest.xml'); + const instantManifestPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'instantapp/AndroidManifest.xml'); + if (fs.existsSync(manifestPath) && fs.existsSync(instantManifestPath)) { + const pattern = /android:screenOrientation="[^"]*"/; + let replaceString = 'android:screenOrientation="unspecified"'; + + if (cfg.landscapeRight && cfg.landscapeLeft && (cfg.portrait || cfg.upsideDown)) { + replaceString = 'android:screenOrientation="fullSensor"'; + } else if ((cfg.landscapeRight || cfg.landscapeLeft) && (cfg.portrait || cfg.upsideDown)) { + replaceString = 'android:screenOrientation="unspecified"'; + } else if (cfg.landscapeRight && !cfg.landscapeLeft) { + replaceString = 'android:screenOrientation="landscape"'; + } else if (!cfg.landscapeRight && cfg.landscapeLeft) { + replaceString = 'android:screenOrientation="reverseLandscape"'; + } else if (cfg.landscapeRight && cfg.landscapeLeft) { + replaceString = 'android:screenOrientation="sensorLandscape"'; + } else if (cfg.portrait && !cfg.upsideDown) { + replaceString = 'android:screenOrientation="portrait"'; + } else if (!cfg.portrait && cfg.upsideDown) { + const oriValue = 'reversePortrait'; + replaceString = `android:screenOrientation="${oriValue}"`; + } else if (cfg.portrait && cfg.upsideDown) { + const oriValue = 'sensorPortrait'; + replaceString = `android:screenOrientation="${oriValue}"`; + } + + let content = await fs.readFile(manifestPath, 'utf8'); + content = content.replace(pattern, replaceString); + let instantContent = await fs.readFile(instantManifestPath, 'utf8'); + instantContent = instantContent.replace(pattern, replaceString); + await fs.writeFile(manifestPath, content); + await fs.writeFile(instantManifestPath, instantContent); + } + } + private mapOrientationValue() { const orientation = this.params.platformParams.orientation; let orientationValue = 'unspecified'; @@ -350,6 +390,37 @@ export class AndroidPackTool extends NativePackTool { } } + /** + * Deprecated, only be compatible with historical packaging tools + */ + protected async configAndroidInstant() { + if (!this.params.platformParams.androidInstant) { + console.log('android instant not configured'); + return; + } + const url = this.params.platformParams.remoteUrl; + if (!url) { + return; + } + const manifestPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'instantapp/AndroidManifest.xml'); + if (!fs.existsSync(manifestPath)) { + throw new Error(`${manifestPath} not found`); + } + const urlInfo = URL.parse(url); + if (!urlInfo.host) { + throw new Error(`parse url ${url} fail`); + } + let manifest = fs.readFileSync(manifestPath, 'utf8'); + manifest = manifest.replace(//, (str) => { + let newStr = ''; + newStr += `\n ` + + `\n `; + return newStr; + }); + + fs.writeFileSync(manifestPath, manifest, 'utf8'); + } + private async generateAppNameValues() { const valuesPath = cchelper.join(this.paths.platformTemplateDirInPrj, 'res/values/strings.xml'); const matchCnt = fs.readFileSync(valuesPath, 'utf8').toString().split('\n').map(x => x.trim()).filter(x => /name=\"app_name\"/.test(x)).length; diff --git a/templates/xr-huaweivr/template/app/AndroidManifest.xml b/templates/xr-huaweivr/template/app/AndroidManifest.xml index 89419ae2d12..cc51f13aec8 100644 --- a/templates/xr-huaweivr/template/app/AndroidManifest.xml +++ b/templates/xr-huaweivr/template/app/AndroidManifest.xml @@ -20,7 +20,7 @@ diff --git a/templates/xr-huaweivr/template/instantapp/AndroidManifest.xml b/templates/xr-huaweivr/template/instantapp/AndroidManifest.xml index aa061c55845..a122933bebc 100644 --- a/templates/xr-huaweivr/template/instantapp/AndroidManifest.xml +++ b/templates/xr-huaweivr/template/instantapp/AndroidManifest.xml @@ -25,7 +25,7 @@ diff --git a/templates/xr-meta/template/app/AndroidManifest.xml b/templates/xr-meta/template/app/AndroidManifest.xml index 89419ae2d12..cc51f13aec8 100644 --- a/templates/xr-meta/template/app/AndroidManifest.xml +++ b/templates/xr-meta/template/app/AndroidManifest.xml @@ -20,7 +20,7 @@ diff --git a/templates/xr-meta/template/instantapp/AndroidManifest.xml b/templates/xr-meta/template/instantapp/AndroidManifest.xml index aa061c55845..a122933bebc 100644 --- a/templates/xr-meta/template/instantapp/AndroidManifest.xml +++ b/templates/xr-meta/template/instantapp/AndroidManifest.xml @@ -25,7 +25,7 @@ diff --git a/templates/xr-monado/template/app/AndroidManifest.xml b/templates/xr-monado/template/app/AndroidManifest.xml index 89419ae2d12..cc51f13aec8 100644 --- a/templates/xr-monado/template/app/AndroidManifest.xml +++ b/templates/xr-monado/template/app/AndroidManifest.xml @@ -20,7 +20,7 @@ diff --git a/templates/xr-monado/template/instantapp/AndroidManifest.xml b/templates/xr-monado/template/instantapp/AndroidManifest.xml index aa061c55845..a122933bebc 100644 --- a/templates/xr-monado/template/instantapp/AndroidManifest.xml +++ b/templates/xr-monado/template/instantapp/AndroidManifest.xml @@ -25,7 +25,7 @@ diff --git a/templates/xr-pico/template/app/AndroidManifest.xml b/templates/xr-pico/template/app/AndroidManifest.xml index 89419ae2d12..cc51f13aec8 100644 --- a/templates/xr-pico/template/app/AndroidManifest.xml +++ b/templates/xr-pico/template/app/AndroidManifest.xml @@ -20,7 +20,7 @@ diff --git a/templates/xr-pico/template/instantapp/AndroidManifest.xml b/templates/xr-pico/template/instantapp/AndroidManifest.xml index aa061c55845..a122933bebc 100644 --- a/templates/xr-pico/template/instantapp/AndroidManifest.xml +++ b/templates/xr-pico/template/instantapp/AndroidManifest.xml @@ -25,7 +25,7 @@ diff --git a/templates/xr-rokid/template/app/AndroidManifest.xml b/templates/xr-rokid/template/app/AndroidManifest.xml index 89419ae2d12..cc51f13aec8 100644 --- a/templates/xr-rokid/template/app/AndroidManifest.xml +++ b/templates/xr-rokid/template/app/AndroidManifest.xml @@ -20,7 +20,7 @@ diff --git a/templates/xr-rokid/template/instantapp/AndroidManifest.xml b/templates/xr-rokid/template/instantapp/AndroidManifest.xml index aa061c55845..a122933bebc 100644 --- a/templates/xr-rokid/template/instantapp/AndroidManifest.xml +++ b/templates/xr-rokid/template/instantapp/AndroidManifest.xml @@ -25,7 +25,7 @@ diff --git a/templates/xr-spaces/template/app/AndroidManifest.xml b/templates/xr-spaces/template/app/AndroidManifest.xml index c98db30bb8c..2be341646f8 100644 --- a/templates/xr-spaces/template/app/AndroidManifest.xml +++ b/templates/xr-spaces/template/app/AndroidManifest.xml @@ -22,7 +22,7 @@ diff --git a/templates/xr-spaces/template/instantapp/AndroidManifest.xml b/templates/xr-spaces/template/instantapp/AndroidManifest.xml index aa061c55845..a122933bebc 100644 --- a/templates/xr-spaces/template/instantapp/AndroidManifest.xml +++ b/templates/xr-spaces/template/instantapp/AndroidManifest.xml @@ -25,7 +25,7 @@ From 5f61d2a112928e158f0503b6781d665bb5b85aa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Mon, 21 Aug 2023 19:28:33 +0800 Subject: [PATCH 208/232] fix fbx and widget bug in inspector (#16057) * optimize widget layout * fix bug of resizing panel , fbx event point would not update position * change method name --- editor/inspector/assets/fbx/preview.js | 7 +++++-- editor/inspector/components/widget.js | 26 ++++++++++++++------------ 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/editor/inspector/assets/fbx/preview.js b/editor/inspector/assets/fbx/preview.js index ad9b5fa0967..a19ecff5a3e 100644 --- a/editor/inspector/assets/fbx/preview.js +++ b/editor/inspector/assets/fbx/preview.js @@ -28,7 +28,7 @@ exports.template = /* html */`
- +
@@ -310,7 +310,10 @@ const Elements = { const panel = this; function observer() { - panel.isPreviewDataDirty = true; + window.requestAnimationFrame(() => { + panel.isPreviewDataDirty = true; + panel.updateEventInfo(); + }); } panel.resizeObserver = new window.ResizeObserver(observer); diff --git a/editor/inspector/components/widget.js b/editor/inspector/components/widget.js index 8c7b0b371a0..a4b52964acd 100644 --- a/editor/inspector/components/widget.js +++ b/editor/inspector/components/widget.js @@ -945,6 +945,16 @@ exports.methods = { const lockDirection = LockFlags[direction]; return lockValue & lockDirection; }, + setLayout() { + const rect = this.$this.getBoundingClientRect(); + if (rect.width) { + if (rect.width > cssMediaWidth) { + this.layout = 'horizontal'; + } else { + this.layout = 'vertical'; + } + } + }, }; const uiElements = { baseProps: { @@ -1213,12 +1223,7 @@ exports.ready = function() { return; } - const rect = this.$this.getBoundingClientRect(); - if (rect.width > cssMediaWidth) { - this.layout = 'horizontal'; - } else { - this.layout = 'vertical'; - } + this.setLayout(); }); }); @@ -1235,12 +1240,9 @@ exports.update = function(dump) { this.dump = dump; this.dimensionHorizontal = this.getDimensionHorizontal(); this.dimensionVertical = this.getDimensionVertical(); - const rect = this.$this.getBoundingClientRect(); - if (rect.width > cssMediaWidth) { - this.layout = 'horizontal'; - } else { - this.layout = 'vertical'; - } + + this.setLayout(); + if (!this.vm) { this.vm = new Vue({ el: this.$.app, From 13d01a4d79629021959baab0317b830c883a2e54 Mon Sep 17 00:00:00 2001 From: Zeqiang Li Date: Tue, 22 Aug 2023 12:44:18 +0800 Subject: [PATCH 209/232] mtl depth resolve feature query update (#16061) --- native/cocos/renderer/gfx-metal/MTLDevice.mm | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 097d14dd0b1..25a5887fc87 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -139,7 +139,18 @@ of this software and associated engine source code (the "Software"), a limited, _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = false; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; - _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = [mtlDevice supportsFamily: MTLGPUFamilyApple3]; + if (@available(iOS 13.0, macOS 10.15, *)) { + // detph resolve requires MTLGPUFamilyApple3 while stencil resolve requires MTLGPUFamilyApple5 + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = [mtlDevice supportsFamily:MTLGPUFamilyApple5]; + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] |= [mtlDevice supportsFamily:MTLGPUFamilyMac2]; + } else { +#if CC_PLATFOTM == CC_PLATFORM_IOS + id device = static_cast>(_mtlDevice); + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v4]; +#elif CC_PLATFOTM == CC_PLATFORM_MACOS + _features[toNumber(Feature::MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL)] = false; +#endif + } QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; From f330132aa3e739fab9f8a8c4cf6a98f6c690cc24 Mon Sep 17 00:00:00 2001 From: Gin Date: Tue, 22 Aug 2023 13:57:03 +0800 Subject: [PATCH 210/232] improve: effects list sorting in material panel (#16060) * improve: effects list ordering in material panel * fixup: set collator option `numeric` to `true` * fixup: use `Object.value` & filter * fixup: filter predicate function --- editor/inspector/assets/material.js | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/editor/inspector/assets/material.js b/editor/inspector/assets/material.js index 739914da483..5ca424d74e8 100644 --- a/editor/inspector/assets/material.js +++ b/editor/inspector/assets/material.js @@ -180,14 +180,12 @@ exports.methods = { async updateEffect() { const effectMap = await Editor.Message.request('scene', 'query-all-effects'); + // see: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator + const collator = new Intl.Collator(undefined, { numeric: true }); - this.effects = Object.keys(effectMap).sort().reduce((arr, name) => { - const effect = effectMap[name]; - if (!effect.hideInEditor) { - arr.push(effect); - } - return arr; - }, []); + this.effects = Object.values(effectMap) + .filter((effect) => !effect.hideInEditor) + .sort((a, b) => collator.compare(a.name, b.name)); const effectOptionsHTML = renderGroupEffectOptions(this.effects); From baea594f93d035e2bfd9eafc02cf274fa5b9c1fe Mon Sep 17 00:00:00 2001 From: Santy-Wang Date: Tue, 22 Aug 2023 15:15:35 +0800 Subject: [PATCH 211/232] bump external tag (#16066) --- native/external-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external-config.json b/native/external-config.json index 1ce55742884..e98b7dba9e9 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-14" + "checkout": "v3.8.1-15" } } \ No newline at end of file From 3febfab3101ae54ce789ab434b98fbcb35f4dae8 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Tue, 22 Aug 2023 15:40:18 +0800 Subject: [PATCH 212/232] fix rendering submesh typo (#16063) * fix rendering submesh typo * fix typo * sync external tag --- native/cocos/core/assets/RenderingSubMesh.cpp | 2 +- native/cocos/math/Utils.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/native/cocos/core/assets/RenderingSubMesh.cpp b/native/cocos/core/assets/RenderingSubMesh.cpp index de744d7d09a..f8e09cb85e8 100644 --- a/native/cocos/core/assets/RenderingSubMesh.cpp +++ b/native/cocos/core/assets/RenderingSubMesh.cpp @@ -95,7 +95,7 @@ const IGeometricInfo &RenderingSubMesh::getGeometricInfo() { auto iter = std::find_if(_attributes.cbegin(), _attributes.cend(), [](const gfx::Attribute &element) -> bool { return element.name == gfx::ATTR_NAME_POSITION; }); - if (iter != _attributes.end()) { + if (iter == _attributes.end()) { return EMPTY_GEOMETRIC_INFO; } diff --git a/native/cocos/math/Utils.cpp b/native/cocos/math/Utils.cpp index 5fdb01b56a3..285a8178b8b 100644 --- a/native/cocos/math/Utils.cpp +++ b/native/cocos/math/Utils.cpp @@ -103,7 +103,7 @@ float halfToFloat(uint16_t hval) { } } - u.ui = ((uint16_t)(s << 31)) | em | m; // NOLINT + u.ui = ((s << 31)) | em | m; // NOLINT return u.f; } From 5b5c3cf977bf9fb00802be5d02979123d671d5aa Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Wed, 23 Aug 2023 10:53:24 +0800 Subject: [PATCH 213/232] fix custom pipeline load float-output-process error (#16071) --- cocos/asset/assets/effect-asset.ts | 2 +- .../post-process/passes/float-output-process-pass.ts | 6 +++--- .../assets/effects/pipeline/float-output-process.effect | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos/asset/assets/effect-asset.ts b/cocos/asset/assets/effect-asset.ts index 5a51e03cc71..06d4fac7039 100644 --- a/cocos/asset/assets/effect-asset.ts +++ b/cocos/asset/assets/effect-asset.ts @@ -203,7 +203,7 @@ const legacyBuiltinEffectNames = [ 'geometry-renderer', 'debug-renderer', 'ssss-blur', - 'tone-mapping', + 'float-output-process', ]; /** diff --git a/cocos/rendering/post-process/passes/float-output-process-pass.ts b/cocos/rendering/post-process/passes/float-output-process-pass.ts index 4570061fe2e..29c554dfb45 100644 --- a/cocos/rendering/post-process/passes/float-output-process-pass.ts +++ b/cocos/rendering/post-process/passes/float-output-process-pass.ts @@ -33,9 +33,9 @@ import { SettingPass } from './setting-pass'; import { Root } from '../../../root'; export class FloatOutputProcessPass extends SettingPass { - name = 'FloatOutputProcessesPass'; - effectName = 'pipeline/float-output-processes'; - outputNames = ['FloatOutputProcesses']; + name = 'FloatOutputProcessPass'; + effectName = 'pipeline/float-output-process'; + outputNames = ['FloatOutputProcess']; enableInAllEditorCamera = true; enable = true; diff --git a/editor/assets/effects/pipeline/float-output-process.effect b/editor/assets/effects/pipeline/float-output-process.effect index 055d728a4e9..791a653a9bc 100644 --- a/editor/assets/effects/pipeline/float-output-process.effect +++ b/editor/assets/effects/pipeline/float-output-process.effect @@ -37,11 +37,11 @@ CCProgram tonemap-fs %{ layout(location = 0) out vec4 fragColor; vec3 HDR2LDR_PostProcess(vec3 color) { - vec3 tempColor = color.rgb; - #if CC_USE_HDR && CC_TONE_MAPPING_TYPE == HDR_TONE_MAPPING_ACES - tempColor.rgb = ACESToneMap(color.rgb); + #if CC_USE_HDR && CC_TONE_MAPPING_TYPE == TONE_MAPPING_ACES + return ACESToneMap(color.rgb); + #else + return color.rgb; #endif - return tempColor.rgb; } vec4 CCFragOutput_PostProcess(vec4 color) { From 563e9f780d824d6e6cd092e84e08ef9e735eec2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=A3=AE=E6=96=8C?= Date: Wed, 23 Aug 2023 11:08:57 +0800 Subject: [PATCH 214/232] fix change language would not update help doc link (#16067) --- editor/inspector/contributions/asset.js | 33 ++++++++-- editor/inspector/contributions/node.js | 81 ++++++++++++------------- 2 files changed, 66 insertions(+), 48 deletions(-) diff --git a/editor/inspector/contributions/asset.js b/editor/inspector/contributions/asset.js index 1482beec798..255b025959c 100644 --- a/editor/inspector/contributions/asset.js +++ b/editor/inspector/contributions/asset.js @@ -70,6 +70,9 @@ const Elements = { Editor.Message.addBroadcastListener('asset-db:asset-change', panel.__assetChanged__); + Elements.panel.i18nChangeBind = Elements.panel.i18nChange.bind(panel); + Editor.Message.addBroadcastListener('i18n:change', Elements.panel.i18nChangeBind); + panel.history = new History(); }, async update() { @@ -146,7 +149,7 @@ const Elements = { return JSON.stringify(meta); }); - panel.getHelpUrl(Editor.I18n.t(`ENGINE.help.assets.${panel.type}`)); + panel.setHelpUrl(panel.$.help, { help: panel.type }); }, close() { const panel = this; @@ -160,6 +163,12 @@ const Elements = { delete panel.history; }, + i18nChange() { + const panel = this; + + const $links = panel.$.container.querySelectorAll('ui-link'); + $links.forEach($link => panel.setHelpUrl($link)); + }, }, header: { ready() { @@ -572,16 +581,28 @@ exports.methods = { panel.$this.update(panel.uuidList, panel.renderMap); }, - getHelpUrl(url) { - const panel = this; + setHelpUrl($link, data) { + if (data) { + $link.helpData = data; + } else { + if (!$link.helpData) { + return; + } + data = $link.helpData; + } + + const url = this.getHelpUrl(data); if (url) { - panel.$.help.style.display = 'block'; - panel.$.help.value = url; + $link.style.display = 'block'; + $link.value = url; } else { - panel.$.help.style.display = 'none'; + $link.style.display = 'none'; } }, + getHelpUrl(data) { + return Editor.I18n.t(`ENGINE.help.assets.${data.help}`); + }, replaceContainerWithUISection(params) { const panel = this; const $containerDiv = panel.$.container; diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 7ddbbbec836..efd9c8c9279 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -847,7 +847,7 @@ const Elements = { const panel = this; const $help = panel.$.sceneSkybox.querySelector('ui-link'); - $help.value = panel.getHelpUrl({ help: 'i18n:cc.Skybox' }); + panel.setHelpUrl($help, { help: 'i18n:cc.Skybox' }); $help.addEventListener('click', (event) => { event.stopPropagation(); event.preventDefault(); @@ -878,15 +878,18 @@ const Elements = { // 由于场景属性对象不是继承于 Component 所以没有修饰器,displayName, help 数据在这里配置 panel.dump._globals.ambient.displayName = 'Ambient'; - panel.dump._globals.ambient.help = panel.getHelpUrl({ help: 'i18n:cc.Ambient' }); + panel.dump._globals.ambient.editor = { help: 'i18n:cc.Ambient' }; + panel.dump._globals.ambient.help = panel.getHelpUrl(panel.dump._globals.ambient.editor); panel.$.sceneAmbient.render(panel.dump._globals.ambient); panel.dump._globals.fog.displayName = 'Fog'; - panel.dump._globals.fog.help = panel.getHelpUrl({ help: 'i18n:cc.Fog' }); + panel.dump._globals.fog.editor = { help: 'i18n:cc.Fog' }; + panel.dump._globals.fog.help = panel.getHelpUrl(panel.dump._globals.fog.editor); panel.$.sceneFog.render(panel.dump._globals.fog); panel.dump._globals.shadows.displayName = 'Shadows'; - panel.dump._globals.shadows.help = panel.getHelpUrl({ help: 'i18n:cc.Shadow' }); + panel.dump._globals.shadows.editor = { help: 'i18n:cc.Shadow' }; + panel.dump._globals.shadows.help = panel.getHelpUrl(panel.dump._globals.shadows.editor); panel.$.sceneShadows.render(panel.dump._globals.shadows); // skyBox 逻辑 start @@ -952,11 +955,13 @@ const Elements = { // skyBox 逻辑 end panel.dump._globals.octree.displayName = 'Octree Scene Culling'; - panel.dump._globals.octree.help = panel.getHelpUrl({ help: 'i18n:cc.OctreeCulling' }); + panel.dump._globals.octree.editor = { help: 'i18n:cc.OctreeCulling' }; + panel.dump._globals.octree.help = panel.getHelpUrl(panel.dump._globals.octree.editor); panel.$.sceneOctree.render(panel.dump._globals.octree); panel.dump._globals.skin.displayName = 'Skin'; - panel.dump._globals.skin.help = panel.getHelpUrl({ help: 'i18n:cc.Skin' }); + panel.dump._globals.skin.editor = { help: 'i18n:cc.Skin' }; + panel.dump._globals.skin.help = panel.getHelpUrl(panel.dump._globals.skin.editor); panel.$.sceneSkin.render(panel.dump._globals.skin); panel.dump._globals.postSettings.displayName = 'PostSettings'; @@ -1119,7 +1124,7 @@ const Elements = { panel.$skyboxProps = {}; - panel.$.nodeLink.value = Editor.I18n.t('ENGINE.help.cc.Node'); + panel.setHelpUrl(panel.$.nodeLink, { help: 'i18n:cc.Node' }); panel.$.nodeMenu.addEventListener('click', (event) => { event.stopPropagation(); @@ -1193,13 +1198,8 @@ const Elements = { $active.invalid = false; } - const url = panel.getHelpUrl(dump.editor); const $link = $section.querySelector('ui-link'); - if (url) { - $link.setAttribute('value', url); - } else { - $link.removeAttribute('value'); - } + panel.setHelpUrl($link, dump.editor); await Promise.all($section.__panels__.map(($panel) => { return $panel.update(dump); @@ -1271,13 +1271,10 @@ const Elements = { }); const $link = $section.querySelector('.link'); - const url = panel.getHelpUrl(component.editor); - if (url) { - $link.setAttribute('value', url); - $link.addEventListener('click', (event) => { - event.stopPropagation(); - }); - } + $link.addEventListener('click', (event) => { + event.stopPropagation(); + }); + panel.setHelpUrl($link, component.editor); const $menu = $section.querySelector('.menu'); $menu.addEventListener('click', (event) => { @@ -1387,25 +1384,8 @@ const Elements = { i18nChange() { const panel = this; - panel.$.nodeLink.value = Editor.I18n.t('ENGINE.help.cc.Node'); - - const sectionBody = panel.$.sectionBody; - for (let index = 0; index < sectionBody.__sections__.length; index++) { - const $section = sectionBody.__sections__[index]; - const $link = $section.querySelector('ui-link'); - - if (!$link) { - continue; - } - - const dump = $section.dump; - const url = panel.getHelpUrl(dump.editor); - if (url) { - $link.setAttribute('value', url); - } else { - $link.removeAttribute('value'); - } - } + const $links = panel.$.container.querySelectorAll('ui-link'); + $links.forEach($link => panel.setHelpUrl($link)); }, }, missingComponent: { @@ -1671,16 +1651,33 @@ exports.methods = { Editor.Message.send(messageProtocol.scene, cmd); }, + setHelpUrl($link, data) { + if (data) { + $link.helpData = data; + } else { + if (!$link.helpData) { + return; + } + data = $link.helpData; + } + + const url = this.getHelpUrl(data); + if (url) { + $link.setAttribute('value', url); + } else { + $link.removeAttribute('value'); + } + }, /** * 获取组件帮助菜单的 url * @param editor */ - getHelpUrl(editor) { - if (!editor || !editor.help) { + getHelpUrl(data) { + if (!data || !data.help) { return ''; } - const help = editor.help; + const help = data.help; /** * 约定的规则 From aff8320359a08175fc0af082ce2184d443131657 Mon Sep 17 00:00:00 2001 From: dogeFu <609075410@qq.com> Date: Wed, 23 Aug 2023 11:57:46 +0800 Subject: [PATCH 215/232] Fix : editor preview set fps no working (#16054) --- pal/pacer/pacer-web.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pal/pacer/pacer-web.ts b/pal/pacer/pacer-web.ts index f24212984a2..488c0eeab74 100644 --- a/pal/pacer/pacer-web.ts +++ b/pal/pacer/pacer-web.ts @@ -85,8 +85,9 @@ export class Pacer { start (): void { if (this._isPlaying) return; - + const recordStartTime = EDITOR || this._rAF === undefined || globalThis.__globalXR?.isWebXR; const updateCallback = (): void => { + if (recordStartTime) this._startTime = performance.now(); if (this._isPlaying) { this._stHandle = this._stTime(updateCallback); } From 0f5609b96b01a043f7c2fbad3fb9c2df5c8a480d Mon Sep 17 00:00:00 2001 From: SijieWang Date: Wed, 23 Aug 2023 11:57:57 +0800 Subject: [PATCH 216/232] [Optimize] clear-platform supports passing arguments. (#16073) --- native/utils/clear-platform.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/native/utils/clear-platform.js b/native/utils/clear-platform.js index 0cba7d8934e..42aa9ea1576 100644 --- a/native/utils/clear-platform.js +++ b/native/utils/clear-platform.js @@ -14,7 +14,7 @@ const child_process = require('child_process'); const fetch = require('node-fetch'); // usage: npm run clear-platform -let externalDir = path.join(__dirname, "../external"); +let externalDir = process.env.ENGINE_PATH ? path.join(process.env.ENGINE_PATH, "./native/external") : path.join(__dirname, "../external"); let failed = false; let macUsefulDirs = ['android', 'cmake', 'emscripten', 'ios', 'ios-m1-simulator', 'mac', 'ohos', 'sources', 'openharmony']; @@ -95,7 +95,7 @@ function cleanPlatform(platform) { } else { // others console.log(chalk.red(`Platform ${platform} is not supported, skip`)); } - // abnormal exit + // abnormal exit if (failed) { process.exit(-1); } @@ -185,7 +185,7 @@ async function minimizeBoost() { const BOOST_VERSION_DOTTED = BOOST_VERSION.join('.'); const BOOST_VERSION_UNDERSCORE = BOOST_VERSION.join('_'); const BOOST_ZIP_FILE = `boost_${BOOST_VERSION_UNDERSCORE}.tar.gz`; - const EXTERNAL_SOURCE_DIR = path.join(__dirname, '..', 'external', 'sources'); + const EXTERNAL_SOURCE_DIR = path.join(externalDir, 'sources'); const BOOST_DOWNLOAD = path.join(EXTERNAL_SOURCE_DIR, 'boost-download'); const BOOST_ORIG_PATH = path.join(EXTERNAL_SOURCE_DIR, 'boost'); const BOOST_DEST = path.join(EXTERNAL_SOURCE_DIR, 'boost-minimized'); @@ -195,7 +195,7 @@ async function minimizeBoost() { const BOOST_URL_LOCAL = `http://ftp.cocos.org/TestBuilds/Editor-3d/tools/boost_${BOOST_VERSION_UNDERSCORE}.tar.gz` const BCP_PATH = path.join(BOOST_DECOMPRESSED_PATH, 'dist', 'bin', execName('bcp')); - const ENGINE_ROOT = path.normalize(path.join(__dirname, '../../')); + const ENGINE_ROOT = path.normalize(path.join(externalDir, '../../')); let headersUsedByEngine = []; @@ -385,4 +385,4 @@ async function minimizeBoost() { await fnCollectBoostHeaders(); await fnRunBCP(); await fnCleanUp(); // skip this step when debugging -} \ No newline at end of file +} From a4990ce4e6751b330626442f36682e9d4e2344f2 Mon Sep 17 00:00:00 2001 From: Yiwen <15225434259xue@gmail.com> Date: Wed, 23 Aug 2023 11:59:56 +0800 Subject: [PATCH 217/232] Fix meshopt wechat (#16069) * fix wechat wasm problem, sync external tag * fix formatting * fix tidy, unit test --- cocos/3d/misc/mesh-codec.ts | 7 ++++++- native/external-config.json | 2 +- tests/init.ts | 7 +++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/cocos/3d/misc/mesh-codec.ts b/cocos/3d/misc/mesh-codec.ts index 86094fce109..b6ed3862bc2 100644 --- a/cocos/3d/misc/mesh-codec.ts +++ b/cocos/3d/misc/mesh-codec.ts @@ -24,8 +24,10 @@ import meshopt_asm_factory from 'external:emscripten/meshopt/meshopt_decoder.asm.js'; import meshopt_wasm_factory from 'external:emscripten/meshopt/meshopt_decoder.wasm.js'; +import meshopt_wasm_url from 'external:emscripten/meshopt/meshopt_decoder.wasm.wasm'; import { WASM_SUPPORT_MODE } from 'internal:constants'; +import { instantiateWasm } from 'pal/wasm'; import { sys, logID } from '../../core'; @@ -51,7 +53,10 @@ function initDecoderASM (): Promise { function initDecoderWASM (): Promise { const Module = meshopt_wasm_factory; - return Promise.all([Module.ready]).then(() => { + function instantiate (importObject: WebAssembly.Imports): any { + return instantiateWasm(meshopt_wasm_url, importObject) as any; + } + return Promise.all([Module.ready(instantiate)]).then(() => { MeshoptDecoder.supported = true; MeshoptDecoder.ready = Promise.resolve(); MeshoptDecoder.decodeVertexBuffer = Module.decodeVertexBuffer; diff --git a/native/external-config.json b/native/external-config.json index e98b7dba9e9..788ca7be350 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-15" + "checkout": "v3.8.1-16" } } \ No newline at end of file diff --git a/tests/init.ts b/tests/init.ts index cf8e31fe718..1b826a307e0 100644 --- a/tests/init.ts +++ b/tests/init.ts @@ -91,6 +91,13 @@ jest.mock( ); }); +jest.mock('external:emscripten/meshopt/meshopt_decoder.wasm.wasm', + () => ({ + __esModule: true, + default: 'this should be a wasm url', + }), + { virtual: true, }, +); // Mock external wasm js module here [ From da507e4ba79467d981de3ea26d7bfabe04c88a5d Mon Sep 17 00:00:00 2001 From: Canvas Date: Wed, 23 Aug 2023 12:45:17 +0800 Subject: [PATCH 218/232] fix spine wasm api array bind (#16064) * fix some array type bindings. * change engine-native-external to v3.8.1-15. * revert v3.8.1-15 to v3.8.1-14. * fix code format. * fix code format. * fix getAttachmentNames api. * off no-unsafe-argument. * change engine-native-external checkout to v3.8.1-16. * optimize use vector set & fix edges prototype error. * add vector default value 0 annotation. --- cocos/spine/lib/spine-define.ts | 119 +++++++++--------- .../spine-wasm/spine-type-export.cpp | 51 ++++++-- 2 files changed, 101 insertions(+), 69 deletions(-) diff --git a/cocos/spine/lib/spine-define.ts b/cocos/spine/lib/spine-define.ts index 447df050ff7..28d53f939f2 100644 --- a/cocos/spine/lib/spine-define.ts +++ b/cocos/spine/lib/spine-define.ts @@ -22,6 +22,7 @@ THE SOFTWARE. */ /* eslint @typescript-eslint/no-explicit-any: "off" */ +/* eslint @typescript-eslint/no-unsafe-argument: "off" */ import spine from './spine-core.js'; import { js } from '../../core'; @@ -42,6 +43,53 @@ function overrideDefineArrayProp (prototype: any, getPropVector: any, name: stri }); } +function overrideDefineArrayArrayProp (prototype: any, getPropVector: any, name: string): void { + Object.defineProperty(prototype, name, { + get (): any[] { + const array: any[] = []; + const vectors = getPropVector.call(this); + const count = vectors.size(); + for (let i = 0; i < count; i++) { + const vectorI = vectors.get(i); + const countJ = vectorI.size(); + const arrayJ: any[] = []; + for (let j = 0; j < countJ; j++) { + arrayJ.push(vectorI.get(j)); + } + array.push(arrayJ); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return array; + }, + }); +} + +function overrideDefineArrayPropGetSet (prototype: any, getPropVector: any, setPropVector: any, Type: any, name: string): void { + Object.defineProperty(prototype, name, { + get (): any[] { + const array: any[] = []; + const vectors = getPropVector.call(this); + const count = vectors.size(); + for (let i = 0; i < count; i++) { + const objPtr = vectors.get(i); + array.push(objPtr); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return array; + }, + set (value: any[]) { + const vectors = new Type(); + const count = value.length; + // vector.resize(count, 0) default 0, because currently only the number type will use this function. + vectors.resize(count, 0); + for (let i = 0; i < count; i++) { + vectors.set(i, value[i]); + } + setPropVector.call(this, vectors); + }, + }); +} + function overrideDefineArrayFunction (prototype: any, getPropVector: any, name: string): void { Object.defineProperty(prototype, name, { value () { @@ -478,16 +526,6 @@ function overrideProperty_VertexAttachment (): void { getter: prototype.getId, setter: prototype.setId, }, - { - proto: prototype, - property: 'bones', - getter: prototype.getBones, - }, - { - proto: prototype, - property: 'vertices', - getter: prototype.getVertices, - }, { proto: prototype, property: 'worldVerticesLength', @@ -504,6 +542,8 @@ function overrideProperty_VertexAttachment (): void { propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); + overrideDefineArrayProp(prototype, prototype.getBones, 'bones'); + overrideDefineArrayProp(prototype, prototype.getVertices, 'vertices'); } function overrideProperty_BoundingBoxAttachment (): void { @@ -544,21 +584,6 @@ function overrideProperty_MeshAttachment (): void { getter: prototype.getPath, setter: prototype.setPath, }, - { - proto: prototype, - property: 'regionUVs', - getter: prototype.getRegionUVs, - }, - { - proto: prototype, - property: 'uvs', - getter: prototype.getUVs, - }, - { - proto: prototype, - property: 'triangles', - getter: prototype.getTriangles, - }, { proto: prototype, property: 'color', @@ -582,15 +607,14 @@ function overrideProperty_MeshAttachment (): void { getter: prototype.getHullLength, setter: prototype.setHullLength, }, - { - proto: prototype, - property: 'edges', - getter: prototype.getEdges, - }, ]; propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); + overrideDefineArrayProp(prototype, prototype.getRegionUVs, 'regionUVs'); + overrideDefineArrayProp(prototype, prototype.getUVs, 'uvs'); + overrideDefineArrayProp(prototype, prototype.getTriangles, 'triangles'); + overrideDefineArrayProp(prototype, prototype.getEdges, 'edges'); } function overrideProperty_PathAttachment (): void { @@ -708,16 +732,11 @@ function overrideProperty_RegionAttachment (): void { property: 'offset', getter: prototype.getOffset, }, - { - proto: prototype, - property: 'uvs', - getter: prototype.getUVs, - setter: prototype.setUVs, - }, ]; propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); + overrideDefineArrayPropGetSet(prototype, prototype.getUVs, prototype.setUVs, spine.wasmUtil.wasm.VectorFloat, 'uvs'); } function overrideProperty_TextureAtlas (): void { @@ -752,11 +771,6 @@ function overrideProperty_SlotData (): void { property: 'name', getter: prototype.getName, }, - { - proto: prototype, - property: 'boneData', - getter: prototype.getBoneData, - }, { proto: prototype, property: 'color', @@ -777,6 +791,8 @@ function overrideProperty_SlotData (): void { propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); + overrideDefineArrayProp(prototype, prototype.getBoneData, 'boneData'); + overrideDefineArrayProp(prototype, prototype.getDeform, 'deform'); } function overrideProperty_IkConstraint (): void { @@ -1166,7 +1182,7 @@ function overrideProperty_Bone (): void { propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); - + overrideDefineArrayProp(prototype, prototype.getChildren, 'children'); const worldToLocal = prototype.worldToLocal; Object.defineProperty(prototype, 'worldToLocal', { value (vec2: spine.Vector2) { @@ -1175,7 +1191,6 @@ function overrideProperty_Bone (): void { vec2.y = vectors.get(1); }, }); - const localToWorld = prototype.localToWorld; Object.defineProperty(prototype, 'localToWorld', { value (vec2: spine.Vector2) { @@ -1438,16 +1453,12 @@ function overrideProperty_AttachmentTimeline (): void { property: 'slotIndex', getter: prototype.getSlotIndex, }, - { - proto: prototype, - property: 'attachmentNames', - getter: prototype.getAttachmentNames, - }, ]; propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); + overrideDefineArrayProp(prototype, prototype.getAttachmentNames, 'attachmentNames'); } function overrideProperty_DeformTimeline (): void { @@ -1463,16 +1474,12 @@ function overrideProperty_DeformTimeline (): void { property: 'attachment', getter: prototype.getAttachment, }, - { - proto: prototype, - property: 'frameVertices', - getter: prototype.getFrameVertices, - }, ]; propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter); }); overrideDefineArrayProp(prototype, prototype.getFrames, 'frames'); + overrideDefineArrayArrayProp(prototype, prototype.getFrameVertices, 'frameVertices'); } function overrideProperty_EventTimeline (): void { @@ -1665,11 +1672,6 @@ function overrideProperty_Animation (): void { property: 'name', getter: prototype.getName, }, - // { - // proto: prototype, - // property: 'timelines', - // getter: prototype.getProp_timelines, - // }, { proto: prototype, property: 'duration', @@ -1680,6 +1682,7 @@ function overrideProperty_Animation (): void { propertyPolyfills.forEach((prop): void => { js.getset(prop.proto, prop.property, prop.getter, prop.setter); }); + overrideDefineArrayProp(prototype, prototype.getTimelines, 'timelines'); } function overrideProperty_Skeleton (): void { diff --git a/native/cocos/editor-support/spine-wasm/spine-type-export.cpp b/native/cocos/editor-support/spine-wasm/spine-type-export.cpp index f8d7bf54def..d612247558b 100644 --- a/native/cocos/editor-support/spine-wasm/spine-type-export.cpp +++ b/native/cocos/editor-support/spine-wasm/spine-type-export.cpp @@ -30,6 +30,15 @@ std::vector VECTOR_SP2STD(Vector &container) { return stdVector; } +const std::vector VECTOR_SP2STD_STRING(Vector &container) { + int count = container.size(); + std::vector stdVector(count); + for (int i = 0; i < count; i++) { + stdVector[i] = STRING_SP2STD(container[i]); + } + return stdVector; +} + template std::vector> VECTOR_2_SP2STD(Vector> &container) { int count = container.size(); @@ -84,6 +93,7 @@ void VECTOR_STD_COPY_SP(std::vector &stdVector, Vector &spVector) { EMSCRIPTEN_BINDINGS(spine) { register_vector("VectorFloat"); + register_vector>("VectorVectorFloat"); register_vector("VectorUnsignedShort"); register_vector("VectorString"); register_vector("VectorBoneData"); @@ -92,6 +102,7 @@ EMSCRIPTEN_BINDINGS(spine) { register_vector("VectorSlotData"); register_vector("VectorSlot"); register_vector("VectorAnimation"); + register_vector("VectorTimeline"); register_vector("VectorSkin"); register_vector("VectorEventData"); register_vector("VectorEvent"); @@ -907,25 +918,35 @@ EMSCRIPTEN_BINDINGS(spine) { class_("Animation") .constructor &, float>() - .function("apply", &Animation::apply, allow_raw_pointers()) + .function("apply", optional_override([](Animation &obj, Skeleton &skeleton, + float lastTime, float time, bool loop, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, loop, &pEvents, alpha, blend, direction); + })) .function("getName", optional_override([](Animation &obj) { return STRING_SP2STD(obj.getName()); })) - .function("getTimelines", optional_override([](Animation &obj) { return VECTOR_SP2STD(obj.getTimelines()); })) + .function("getTimelines", optional_override([](Animation &obj) { + return VECTOR_SP2STD(obj.getTimelines()); }), allow_raw_pointers()) .function("hasTimeline", &Animation::hasTimeline) .function("getDuration", &Animation::getDuration) .function("setDuration", &Animation::setDuration); class_("Timeline") - // to fix apply - //.function("apply", &Timeline::apply, allow_raw_pointers()) .function("apply", optional_override([](Timeline &obj, Skeleton &skeleton, float lastTime, float time, std::vector &stdPEvents, float alpha, MixBlend blend, MixDirection direction) { auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); - }), allow_raw_pointers()) - .function("getPropertyId", &Timeline::getPropertyId); + }), pure_virtual()) + .function("getPropertyId", &Timeline::getPropertyId, pure_virtual()); class_>("CurveTimeline") + .function("apply", optional_override([](CurveTimeline &obj, Skeleton &skeleton, + float lastTime, float time, std::vector &stdPEvents, float alpha, + MixBlend blend, MixDirection direction) { + auto pEvents = VECTOR_STD2SP_POINTER(stdPEvents); + obj.apply(skeleton, lastTime, time, &pEvents, alpha, blend, direction); + }), pure_virtual()) .function("getPropertyId", &CurveTimeline::getPropertyId, pure_virtual()) .function("getFrameCount", &CurveTimeline::getFrameCount) .function("setLinear", &CurveTimeline::setLinear) @@ -1018,11 +1039,14 @@ EMSCRIPTEN_BINDINGS(spine) { .function("getFrames", optional_override([](AttachmentTimeline &obj) { return VECTOR_SP2STD((Vector &)obj.getFrames()); }), allow_raw_pointers()) .function("getAttachmentNames",optional_override([](AttachmentTimeline &obj) { - auto names = obj.getAttachmentNames(); - return VECTOR_SP2STD(names); }), allow_raw_pointers()) + Vector attachmentNames = obj.getAttachmentNames(); + return VECTOR_SP2STD_STRING(attachmentNames); }), allow_raw_pointers()) .function("getPropertyId", &AttachmentTimeline::getPropertyId) .function("getFrameCount", &AttachmentTimeline::getFrameCount) - .function("setFrame", &AttachmentTimeline::setFrame) + .function("setFrame", optional_override([](AttachmentTimeline &obj, int frameIndex, float time, const std::string &attachmentName){ + const String attachmentNameSP = STRING_STD2SP(attachmentName); + obj.setFrame(frameIndex, time, attachmentNameSP); + }), allow_raw_pointers()) .function("apply", optional_override([](AttachmentTimeline &obj, Skeleton &skeleton, float lastTime, float time, std::vector &stdPEvents, float alpha, MixBlend blend, MixDirection direction) { @@ -1037,9 +1061,14 @@ EMSCRIPTEN_BINDINGS(spine) { .function("getAttachment", &DeformTimeline::getAttachment, allow_raw_pointers()) .function("setAttachment", &DeformTimeline::setAttachment, allow_raw_pointers()) .function("getFrames", optional_override([](DeformTimeline &obj) { return VECTOR_SP2STD((Vector &)obj.getFrames()); })) - .function("getFrameVertices", &DeformTimeline::getVertices) + .function("getFrameVertices", optional_override([](DeformTimeline &obj){ + return VECTOR_2_SP2STD(obj.getVertices()); + }), allow_raw_pointers()) .function("getPropertyId", &DeformTimeline::getPropertyId) - .function("setFrame", &DeformTimeline::setFrame) + .function("setFrame", optional_override([](DeformTimeline &obj, int frameIndex, float time, std::vector &vertices){ + Vector sp_vertices = VECTOR_STD2SP(vertices); + obj.setFrame(frameIndex, time, sp_vertices); + }), allow_raw_pointers()) .function("apply", optional_override([](DeformTimeline &obj, Skeleton &skeleton, float lastTime, float time, std::vector &stdPEvents, float alpha, MixBlend blend, MixDirection direction) { From e9ca89f73eef284786e4e1075e439bb7a2d0e05c Mon Sep 17 00:00:00 2001 From: Canvas Date: Wed, 23 Aug 2023 21:15:21 +0800 Subject: [PATCH 219/232] update external-config checkout to v3.8.1-17. (#16081) --- native/external-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/external-config.json b/native/external-config.json index 788ca7be350..ec906e37394 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.1-16" + "checkout": "v3.8.1-17" } } \ No newline at end of file From e86f6d27fdcdb8f1ac17c0b91479d5be1ab0f3dd Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Thu, 24 Aug 2023 10:47:45 +0800 Subject: [PATCH 220/232] Does not handle mismatched touchid (#16078) --- native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp index 7e47c1160d1..74211b5cc2b 100644 --- a/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp +++ b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp @@ -93,7 +93,10 @@ void dispatchTouchEventCB(OH_NativeXComponent* component, void* window) { ev->type = cc::TouchEvent::Type::CANCELLED; } for (int i = 0; i < touchEvent.numPoints; ++i) { - ev->touches.emplace_back(touchEvent.touchPoints[i].x, touchEvent.touchPoints[i].y, touchEvent.touchPoints[i].id); + int32_t id = touchEvent.touchPoints[i].id; + if (touchEvent.id == id) { + ev->touches.emplace_back(touchEvent.touchPoints[i].x, touchEvent.touchPoints[i].y, id); + } } sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_TOUCH_EVENT, reinterpret_cast(ev), window); } From dee666c994827581db01aaf93b1516c3f0da9356 Mon Sep 17 00:00:00 2001 From: fqamic Date: Thu, 24 Aug 2023 15:53:37 +0800 Subject: [PATCH 221/232] fix: xr platform crash with new material change (#16092) --- cocos/game/splash-screen.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/cocos/game/splash-screen.ts b/cocos/game/splash-screen.ts index 87ee4f71ff3..480f1c38953 100644 --- a/cocos/game/splash-screen.ts +++ b/cocos/game/splash-screen.ts @@ -496,11 +496,15 @@ export class SplashScreen { // keep scale to [-1, 1] only use offset this.projection.m00 = preTransforms[swapchain.surfaceTransform][0]; this.projection.m05 = preTransforms[swapchain.surfaceTransform][3] * device.capabilities.clipSpaceSignY; - this.bgMat.setProperty('u_projection', this.projection); - this.bgMat.passes[0].update(); - this.logoMat.setProperty('u_projection', this.projection); - this.logoMat.passes[0].update(); - if (this.watermarkMat) { + if (this.settings.background!.type === 'custom') { + this.bgMat.setProperty('u_projection', this.projection); + this.bgMat.passes[0].update(); + } + if (this.settings.logo!.type !== 'none') { + this.logoMat.setProperty('u_projection', this.projection); + this.logoMat.passes[0].update(); + } + if (this.settings.logo!.type === 'default' && this.watermarkMat) { this.watermarkMat.setProperty('u_projection', this.projection); this.watermarkMat.passes[0].update(); } From 16d720663a650623f5f9028a96117f1a17d78312 Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Fri, 25 Aug 2023 10:46:10 +0800 Subject: [PATCH 222/232] Fix hot update for pipeline effects and Float-output-process flow (#16084) --- cocos/render-scene/scene/fog.ts | 7 ++- cocos/render-scene/scene/index.jsb.ts | 1 + cocos/rendering/custom/builtin-pipelines.ts | 2 + cocos/rendering/custom/custom-pipeline.ts | 59 ++++++++++++++----- cocos/rendering/custom/pipeline.ts | 2 + cocos/rendering/custom/web-pipeline.ts | 7 ++- cocos/rendering/debug-view.ts | 8 +++ .../post-process/passes/base-pass.ts | 2 + .../passes/float-output-process-pass.ts | 40 +++++++++++-- .../post-process/passes/forward-pass.ts | 5 +- .../post-process/passes/hbao-pass.ts | 11 ++++ .../post-process/post-process-builder.ts | 12 ++++ cocos/root.jsb.ts | 11 ++++ editor/assets/effects/advanced/sky.effect | 14 ++--- .../pipeline/float-output-process.effect | 26 +++++++- editor/assets/effects/pipeline/skybox.effect | 13 +++- 16 files changed, 184 insertions(+), 36 deletions(-) diff --git a/cocos/render-scene/scene/fog.ts b/cocos/render-scene/scene/fog.ts index ed303ebb3cb..36a6f504ac5 100644 --- a/cocos/render-scene/scene/fog.ts +++ b/cocos/render-scene/scene/fog.ts @@ -25,6 +25,7 @@ import { Enum, Color, Vec4, cclegacy } from '../../core'; import { FogInfo } from '../../scene-graph/scene-globals'; import { SRGBToLinear } from '../../rendering/pipeline-funcs'; +import { Root } from '../../root'; const _v4 = new Vec4(); @@ -71,7 +72,7 @@ export const FogType = Enum({ LAYERED: 3, }); -const FOG_TYPE_NONE = FogType.LAYERED + 1; +export const FOG_TYPE_NONE = FogType.LAYERED + 1; /** * @en The fog representation in the render scene. @@ -229,7 +230,7 @@ export class Fog { protected _fogRange = 1.2; protected _activated = false; - public initialize (fogInfo : FogInfo): void { + public initialize (fogInfo: FogInfo): void { this._activated = false; this.fogColor = fogInfo.fogColor; this._enabled = fogInfo.enabled; @@ -249,7 +250,7 @@ export class Fog { } protected _updatePipeline (): void { - const root = cclegacy.director.root; + const root = cclegacy.director.root as Root; const value = this.enabled ? this.type : FOG_TYPE_NONE; const accurateValue = this.accurate ? 1 : 0; const pipeline = root.pipeline; diff --git a/cocos/render-scene/scene/index.jsb.ts b/cocos/render-scene/scene/index.jsb.ts index 9cdfcdbacc9..ca62fa94c93 100644 --- a/cocos/render-scene/scene/index.jsb.ts +++ b/cocos/render-scene/scene/index.jsb.ts @@ -171,6 +171,7 @@ export const FogType = Enum({ */ LAYERED: 3, }); +export const FOG_TYPE_NONE = FogType.LAYERED + 1; export const FogInfo: typeof JsbFogInfo = jsb.FogInfo; export type FogInfo = JsbFogInfo; diff --git a/cocos/rendering/custom/builtin-pipelines.ts b/cocos/rendering/custom/builtin-pipelines.ts index eafed239dbb..1403ee8d602 100644 --- a/cocos/rendering/custom/builtin-pipelines.ts +++ b/cocos/rendering/custom/builtin-pipelines.ts @@ -121,6 +121,7 @@ export class DeferredPipelineBuilder implements PipelineBuilder { setupForwardRes(ppl, cameraInfo); return; } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument if (!isUICamera(cameraInfo.camera)) { setupGBufferRes(ppl, cameraInfo); setupLightingRes(ppl, cameraInfo); @@ -134,6 +135,7 @@ export class DeferredPipelineBuilder implements PipelineBuilder { updateForwardRes(ppl, cameraInfo); return; } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument if (!isUICamera(cameraInfo.camera)) { updateGBufferRes(ppl, cameraInfo); updateLightingRes(ppl, cameraInfo); diff --git a/cocos/rendering/custom/custom-pipeline.ts b/cocos/rendering/custom/custom-pipeline.ts index 993f71c6b50..e68fbbd0039 100644 --- a/cocos/rendering/custom/custom-pipeline.ts +++ b/cocos/rendering/custom/custom-pipeline.ts @@ -127,6 +127,7 @@ export class TestPipelineBuilder implements PipelineBuilder { constructor (pipelineSceneData: PipelineSceneData) { this._sceneInfo = new SceneInfo(pipelineSceneData); } + // interface public setup (cameras: Camera[], ppl: BasicPipeline): void { for (let i = 0; i < cameras.length; i++) { @@ -141,14 +142,21 @@ export class TestPipelineBuilder implements PipelineBuilder { ppl.update(camera); const info = this.prepareGameCamera(ppl, camera); this.prepareSceneInfo(camera.scene, camera.frustum, this._sceneInfo); - this.buildForward(ppl, camera, - info.id, info.width, info.height); + this.buildForward( + ppl, + camera, + info.id, + info.width, + info.height, + ); } } // implementation - private prepareSceneInfo (scene: Readonly, + private prepareSceneInfo ( + scene: Readonly, frustum: geometry.Frustum, - sceneInfo: SceneInfo): void { + sceneInfo: SceneInfo, + ): void { // clear scene info sceneInfo.reset(); // spot lights @@ -259,9 +267,14 @@ export class TestPipelineBuilder implements PipelineBuilder { ppl.updateDepthStencil(`SpotLightShadowDepth${id}2`, shadowSize.x, shadowSize.y); ppl.updateDepthStencil(`SpotLightShadowDepth${id}3`, shadowSize.x, shadowSize.y); } - private buildForwardTiled (ppl: BasicPipeline, - camera: Camera, id: number, width: number, height: number, - sceneInfo: SceneInfo): void { + private buildForwardTiled ( + ppl: BasicPipeline, + camera: Camera, + id: number, + width: number, + height: number, + sceneInfo: SceneInfo, + ): void { assert(this._tiled); assert(camera.scene !== null); // init @@ -288,8 +301,13 @@ export class TestPipelineBuilder implements PipelineBuilder { .addSceneOfCamera(camera, new LightInfo(), SceneFlags.BLEND); } } - private buildForward (ppl: BasicPipeline, - camera: Camera, id: number, width: number, height: number): void { + private buildForward ( + ppl: BasicPipeline, + camera: Camera, + id: number, + width: number, + height: number, + ): void { assert(camera.scene !== null); if (camera.scene === null) { return; @@ -325,8 +343,11 @@ export class TestPipelineBuilder implements PipelineBuilder { // queue.addSceneCulledByDirectionalLight(camera, // SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.SHADOW_CASTER, // light, 0); - queue.addSceneOfCamera(camera, new LightInfo(light, 0), - SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.SHADOW_CASTER); + queue.addSceneOfCamera( + camera, + new LightInfo(light, 0), + SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.SHADOW_CASTER, + ); } else { const csmLevel = ppl.pipelineSceneData.csmSupported ? light.csmLevel : 1; @@ -337,8 +358,11 @@ export class TestPipelineBuilder implements PipelineBuilder { // queue.addSceneCulledByDirectionalLight(camera, // SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.SHADOW_CASTER, // light, level); - queue.addSceneOfCamera(camera, new LightInfo(light, level), - SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.SHADOW_CASTER); + queue.addSceneOfCamera( + camera, + new LightInfo(light, level), + SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.SHADOW_CASTER, + ); } } } @@ -352,8 +376,13 @@ export class TestPipelineBuilder implements PipelineBuilder { vp.width = Math.max(1, vp.width); vp.height = Math.max(1, vp.height); } - private getMainLightViewport (light: DirectionalLight, w: number, h: number, level: number, - vp: Viewport): void { + private getMainLightViewport ( + light: DirectionalLight, + w: number, + h: number, + level: number, + vp: Viewport, + ): void { if (light.shadowFixedArea || light.csmLevel === CSMLevel.LEVEL_1) { vp.left = 0; vp.top = 0; diff --git a/cocos/rendering/custom/pipeline.ts b/cocos/rendering/custom/pipeline.ts index 9635183715e..87172d5f715 100644 --- a/cocos/rendering/custom/pipeline.ts +++ b/cocos/rendering/custom/pipeline.ts @@ -1423,6 +1423,8 @@ export interface PipelineBuilder { * @param pipeline @en Current render pipeline @zh 当前管线 */ setup (cameras: Camera[], pipeline: BasicPipeline): void; + + onGlobalPipelineStateChanged?(): void; } /** diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index 31be6f797d7..316e90a2431 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -1828,7 +1828,12 @@ export class WebPipeline implements BasicPipeline { this._macros[name] = value; } public onGlobalPipelineStateChanged (): void { - // do nothing + const builder = cclegacy.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME); + if (builder) { + if (typeof builder.onGlobalPipelineStateChanged === 'function') { + builder.onGlobalPipelineStateChanged(); + } + } } beginSetup (): void { if (!this._renderGraph) this._renderGraph = new RenderGraph(); diff --git a/cocos/rendering/debug-view.ts b/cocos/rendering/debug-view.ts index 28d661ced23..ebf10db4629 100644 --- a/cocos/rendering/debug-view.ts +++ b/cocos/rendering/debug-view.ts @@ -161,6 +161,10 @@ export class DebugView { this._updatePipeline(); } + get debugViewType (): RenderingDebugViewType { + return this._getType(); + } + protected _singleMode = DebugViewSingleType.NONE; protected _compositeModeValue = 0; protected _lightingWithAlbedo = true; @@ -239,13 +243,16 @@ export class DebugView { private _enableCompositeMode (val: DebugViewCompositeType, enable: boolean): void { if (enable) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison this._compositeModeValue |= (1 << val); } else { + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison this._compositeModeValue &= (~(1 << val)); } } private _enableAllCompositeMode (enable: boolean): void { + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison for (let i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { if (enable) { this._compositeModeValue |= (1 << i); @@ -261,6 +268,7 @@ export class DebugView { } else if (this._lightingWithAlbedo !== true || this._csmLayerColoration !== false) { return RenderingDebugViewType.COMPOSITE_AND_MISC; } else { + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison for (let i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { if (!this.isCompositeModeEnabled(i)) { return RenderingDebugViewType.COMPOSITE_AND_MISC; diff --git a/cocos/rendering/post-process/passes/base-pass.ts b/cocos/rendering/post-process/passes/base-pass.ts index 3038bfaf661..54fecf11729 100644 --- a/cocos/rendering/post-process/passes/base-pass.ts +++ b/cocos/rendering/post-process/passes/base-pass.ts @@ -111,6 +111,8 @@ export abstract class BasePass { return this.enable; } + onGlobalPipelineStateChanged?(): void; + renderProfiler (camera): void { if (passContext.isFinalCamera && !EDITOR) { passContext.pass!.showStatistics = true; diff --git a/cocos/rendering/post-process/passes/float-output-process-pass.ts b/cocos/rendering/post-process/passes/float-output-process-pass.ts index 29c554dfb45..169d26d2afa 100644 --- a/cocos/rendering/post-process/passes/float-output-process-pass.ts +++ b/cocos/rendering/post-process/passes/float-output-process-pass.ts @@ -24,7 +24,7 @@ import { Vec4, cclegacy } from '../../../core'; import { ClearFlagBit, Format } from '../../../gfx'; -import { Camera } from '../../../render-scene/scene'; +import { Camera, FOG_TYPE_NONE } from '../../../render-scene/scene'; import { Pipeline } from '../../custom/pipeline'; import { getCameraUniqueID } from '../../custom/define'; import { passContext } from '../utils/pass-context'; @@ -44,23 +44,53 @@ export class FloatOutputProcessPass extends SettingPass { return ppl.getMacroBool('CC_USE_FLOAT_OUTPUT'); } + onGlobalPipelineStateChanged (): void { + passContext.material = this.material; + const passes = passContext.material.passes; + for (let i = 0; i < passes.length; i++) { + const pass = passes[i]; + pass.beginChangeStatesSilently(); + pass.tryCompile(); // force update shaders + pass.endChangeStatesSilently(); + } + } + needDepthInput (ppl: Pipeline): boolean { + return ppl.pipelineSceneData.fog.type !== FOG_TYPE_NONE; + } + public render (camera: Camera, ppl: Pipeline): void { const cameraID = getCameraUniqueID(camera); passContext.material = this.material; - const input = this.lastPass!.slotName(camera, 0); + let copyDS = ''; + let passIndx = 0; const inputDS = passContext.depthSlotName; + if (this.needDepthInput(ppl)) { + copyDS = 'floatOutputProcessCopyDS'; + // ==== Copy input DS === + const copyInputDSPassLayoutName = 'copy-pass'; + const copyInputDSPass = `floatOutputProcessCopyDS-pass${cameraID}`; + passContext.updatePassViewPort() + .addRenderPass(copyInputDSPassLayoutName, copyInputDSPass) + .setClearFlag(ClearFlagBit.COLOR) + .setClearColor(1.0, 0, 0, 0) + .setPassInput(inputDS, 'depthRaw') + .addRasterView(copyDS, Format.RGBA8) + .blitScreen(passIndx) + .version(); + } + + passIndx = 1; + const input = this.lastPass!.slotName(camera, 0); const output = this.slotName(camera, 0); const layoutName = 'tone-mapping'; const passName = `tone-mapping${cameraID}`; - const passIndx = 0; - passContext.clearFlag = ClearFlagBit.COLOR; Vec4.set(passContext.clearColor, camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w); passContext.updatePassViewPort() .addRenderPass(layoutName, passName) .setPassInput(input, 'u_texSampler') - .setPassInput(inputDS, 'DepthTex') + .setPassInput(copyDS, 'DepthTex') .addRasterView(output, Format.RGBA8) .blitScreen(passIndx) .version(); diff --git a/cocos/rendering/post-process/passes/forward-pass.ts b/cocos/rendering/post-process/passes/forward-pass.ts index e81630d80d2..fb73550de00 100644 --- a/cocos/rendering/post-process/passes/forward-pass.ts +++ b/cocos/rendering/post-process/passes/forward-pass.ts @@ -1,7 +1,7 @@ import { Vec4 } from '../../../core'; import { ClearFlagBit, Format } from '../../../gfx'; -import { Camera } from '../../../render-scene/scene'; +import { Camera, ShadowType } from '../../../render-scene/scene'; import { LightInfo, QueueHint, SceneFlags } from '../../custom/types'; import { getCameraUniqueID } from '../../custom/define'; import { Pipeline } from '../../custom/pipeline'; @@ -76,7 +76,8 @@ export class ForwardPass extends BasePass { SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.GEOMETRY, ); - if (camera.scene?.mainLight) { + const shadowInfo = ppl.pipelineSceneData.shadows; + if (camera.scene?.mainLight && shadowInfo.enabled && shadowInfo.type === ShadowType.Planar) { pass.addQueue(QueueHint.RENDER_TRANSPARENT, 'planar-shadow') .addSceneOfCamera( camera, diff --git a/cocos/rendering/post-process/passes/hbao-pass.ts b/cocos/rendering/post-process/passes/hbao-pass.ts index aea741f6d32..f6f0e8a5893 100644 --- a/cocos/rendering/post-process/passes/hbao-pass.ts +++ b/cocos/rendering/post-process/passes/hbao-pass.ts @@ -194,6 +194,17 @@ export class HBAOPass extends SettingPass { return enable; } + onGlobalPipelineStateChanged (): void { + passContext.material = this.material; + const passes = passContext.material.passes; + for (let i = 0; i < passes.length; i++) { + const pass = passes[i]; + pass.beginChangeStatesSilently(); + pass.tryCompile(); // force update shaders + pass.endChangeStatesSilently(); + } + } + public getSceneScale (camera: Camera): number { let sceneScale = camera.nearClip; if (!this.averageObjectSize.has(camera.node.scene)) { diff --git a/cocos/rendering/post-process/post-process-builder.ts b/cocos/rendering/post-process/post-process-builder.ts index 5dd938caef3..c9174157a04 100644 --- a/cocos/rendering/post-process/post-process-builder.ts +++ b/cocos/rendering/post-process/post-process-builder.ts @@ -29,6 +29,18 @@ export class PostProcessBuilder implements PipelineBuilder { this.init(); } + onGlobalPipelineStateChanged (): void { + const passes = this.pipelines.get('forward'); + if (passes !== undefined) { + for (let i = 0; i < passes.length; i++) { + const pass = passes[i]; + if (typeof pass.onGlobalPipelineStateChanged === 'function') { + pass.onGlobalPipelineStateChanged(); + } + } + } + } + init (): void { const forward = new ForwardPass(); const forwardFinal = new ForwardFinalPass(); diff --git a/cocos/root.jsb.ts b/cocos/root.jsb.ts index f1e25ef5aa2..2e3ce09e2a4 100644 --- a/cocos/root.jsb.ts +++ b/cocos/root.jsb.ts @@ -224,6 +224,17 @@ rootProto._onDirectorPipelineChanged = function () { } } +const oldOnGlobalPipelineStateChanged = rootProto.onGlobalPipelineStateChanged; +rootProto.onGlobalPipelineStateChanged = function() { + oldOnGlobalPipelineStateChanged.call(this); + const builder = legacyCC.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME); + if (builder) { + if (typeof builder.onGlobalPipelineStateChanged === 'function') { + builder.onGlobalPipelineStateChanged(); + } + } +} + const oldFrameMove = rootProto.frameMove; rootProto.frameMove = function (deltaTime: number) { oldFrameMove.call(this, deltaTime, legacyCC.director.getTotalFrames()); diff --git a/editor/assets/effects/advanced/sky.effect b/editor/assets/effects/advanced/sky.effect index c2f5232529f..ff98475005a 100644 --- a/editor/assets/effects/advanced/sky.effect +++ b/editor/assets/effects/advanced/sky.effect @@ -39,7 +39,7 @@ CCProgram surface-vertex %{ vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) { // Apply uniform scaling for atmosphere effects - return In.worldPos * params.w; + return cc_cameraPos.xyz + In.worldPos * params.w; } }% @@ -62,13 +62,11 @@ CCProgram surface-fragment %{ vec4 SurfacesFragmentModifyBaseColorAndTransparency() { vec3 c = vec3(1.0); - #if CC_USE_IBL - vec3 normal = normalize(FSInput_worldNormal); - vec3 rotationDir = RotationVecFromAxisY(normal.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); - c = sampleEnvMap(environmentMap, rotationDir); - #if BLEND_ENV_MAP - c = mix(c, sampleEnvMap(blendEnvironmentMap, rotationDir), params.x); - #endif + vec3 normal = normalize(FSInput_worldNormal); + vec3 rotationDir = RotationVecFromAxisY(normal.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); + c = sampleEnvMap(environmentMap, rotationDir); + #if BLEND_ENV_MAP + c = mix(c, sampleEnvMap(blendEnvironmentMap, rotationDir), params.x); #endif return vec4(c * cc_ambientSky.w * params.y, 1.0); } diff --git a/editor/assets/effects/pipeline/float-output-process.effect b/editor/assets/effects/pipeline/float-output-process.effect index 791a653a9bc..de8f2d61d44 100644 --- a/editor/assets/effects/pipeline/float-output-process.effect +++ b/editor/assets/effects/pipeline/float-output-process.effect @@ -3,6 +3,11 @@ CCEffect %{ techniques: - passes: + - vert: tonemap-vs + frag: copy-fs + pass: copy-pass + depthTest: false + depthWrite: false - vert: tonemap-vs frag: tonemap-fs pass: tone-mapping @@ -17,6 +22,24 @@ CCProgram tonemap-vs %{ #include <./post-process/chunks/vs> }% +CCProgram copy-fs %{ + precision highp float; + #include + #include + + #pragma rate depthRaw pass + uniform sampler2D depthRaw; + + in vec2 v_uv; + + layout(location = 0) out vec4 fragColor; + + void main() { + float depth = texture(depthRaw, v_uv).r; + fragColor = packDepthToRGBA(depth); + } +}% + CCProgram tonemap-fs %{ precision highp float; #include @@ -26,6 +49,7 @@ CCProgram tonemap-fs %{ #include #include #include + #include in vec2 v_uv; @@ -49,7 +73,7 @@ CCProgram tonemap-fs %{ // fog related vec4 worldPos = vec4(0.0); #if CC_USE_FOG != CC_FOG_NONE - float depth = texture(DepthTex, v_uv).r; + float depth = unpackRGBAToDepth(texture(DepthTex, v_uv)); vec3 posHS = vec3(v_uv, depth) * 2.0 - vec3(1.0); CC_HANDLE_GET_CLIP_FLIP(posHS.xy); worldPos = GetWorldPosFromNDCPosRH(posHS, cc_matProj, cc_matViewProjInv); diff --git a/editor/assets/effects/pipeline/skybox.effect b/editor/assets/effects/pipeline/skybox.effect index 04c16fc0bf1..d9b90812ab1 100644 --- a/editor/assets/effects/pipeline/skybox.effect +++ b/editor/assets/effects/pipeline/skybox.effect @@ -62,6 +62,7 @@ CCProgram sky-fs %{ #include #include #include + #include #include #include @@ -75,7 +76,17 @@ CCProgram sky-fs %{ #else vec3 c = SRGBToLinear(fragTextureLod(environmentMap, rotationDir.xyz, 0.0).rgb); #endif - vec4 color = CCFragOutput(vec4(c * cc_ambientSky.w, 1.0)); + + vec4 color = vec4(c * cc_ambientSky.w, 1.0); + #if CC_USE_RGBE_OUTPUT + color = packRGBE(color.rgb); + #else + color.rgb = HDRToLDR(color.rgb); + color.rgb = LinearToSRGB(color.rgb); + #endif + + //todo: change to CCFragOutput when sky render queue has been fixed with custom pipeline + //return CCFragOutput(color); return color; } }% From 5071624db86b910bfdaee5cafeb9dcf8a4b6c7e4 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 25 Aug 2023 10:47:24 +0800 Subject: [PATCH 223/232] sheen lighting model (#16058) --- .../chunks/common/graph-expression/base.chunk | 42 ++++++++++++----- .../assets/chunks/common/lighting/brdf.chunk | 47 ++++++++++++++++++- .../lighting-flow/common-flow.chunk | 26 +++++----- .../model-functions/standard.chunk | 31 ++++++++++++ .../default-functions/standard-fs.chunk | 4 +- .../module-functions/standard-fs.chunk | 4 +- editor/assets/effects/advanced/fabric.effect | 28 ++++++----- 7 files changed, 140 insertions(+), 42 deletions(-) diff --git a/editor/assets/chunks/common/graph-expression/base.chunk b/editor/assets/chunks/common/graph-expression/base.chunk index c3ef49a59df..6b565e91c63 100644 --- a/editor/assets/chunks/common/graph-expression/base.chunk +++ b/editor/assets/chunks/common/graph-expression/base.chunk @@ -18,19 +18,6 @@ vec2 Rotator(vec2 uv, vec2 centerUV, float time, float speed) return vec2(dir.x, dir.z) + centerUV; } -// tangent space -> world space -// same as TransformVector -vec3 TransformNormalMap(vec3 vectorFromNormalMap) -{ - vec3 vectorTS = normalize(vectorFromNormalMap - vec3(0.5)); - vec3 normal = normalize(FSInput_worldNormal); - vec3 tangent = normalize(FSInput_worldTangent); - vec3 binormal = CalculateBinormal(normal, tangent, FSInput_mirrorNormal); - vec3 vecWS = vectorTS.x * tangent + vectorTS.y * binormal + vectorTS.z * normal; - return vecWS * vec3(1.0, 1.0, -1.0); // inverse Z for RH -} - - // return 0.0 when out of range // hardness: 0 - 1 float SphereMask(vec2 center, vec2 point, float radius, float hardness) @@ -45,3 +32,32 @@ float SphereMask(vec3 center, vec3 point, float radius, float hardness) float coef = pow(saturate(length / radius), 1.0 / (1.0 - saturate(sqrt(hardness)) + EPSILON)); return length > radius ? 0.0 : 1.0 - coef; } + + +// For Fragment Shader + +// tangent space -> world space +// same as TransformVector +vec3 TransformNormalMap(vec3 vectorFromNormalMap) +{ + vec3 vectorTS = normalize(vectorFromNormalMap - vec3(0.5)); + vec3 normal = normalize(FSInput_worldNormal); + vec3 tangent = normalize(FSInput_worldTangent); + vec3 binormal = CalculateBinormal(normal, tangent, FSInput_mirrorNormal); + vec3 vecWS = vectorTS.x * tangent + vectorTS.y * binormal + vectorTS.z * normal; + return vecWS * vec3(1.0, 1.0, -1.0); // inverse Z for RH +} + +// WorldPos -> UV +vec2 GetTriplanarMappingUV() +{ + vec3 Up = vec3(0.0, 1.0, 0.0); + vec3 U = cross(Up, FSInput_worldNormal.xyz); + if (length(U) < 0.01) + U = vec3(1.0, 0.0, 0.0); + else + U = normalize(U); + vec3 V = cross(U, FSInput_worldNormal.xyz); + V = normalize(V); + return fract(vec2(dot(FSInput_worldPos.xyz, U), dot(FSInput_worldPos.xyz, V))); +} diff --git a/editor/assets/chunks/common/lighting/brdf.chunk b/editor/assets/chunks/common/lighting/brdf.chunk index ef4fea792a1..79405c200ab 100644 --- a/editor/assets/chunks/common/lighting/brdf.chunk +++ b/editor/assets/chunks/common/lighting/brdf.chunk @@ -116,5 +116,50 @@ void IntegratedGFMultiplier (out vec3 integratedGF, out vec3 integratedF, vec3 s integratedGF = max(vec3(0.0), vec3(AB.x) + vec3(AB.y) / (specular + EPSILON_LOWP)); } -//Diffuse_Lambert +// isotropic sheen +float Sheen_HorizonFading(float NoL) +{ + const float horizonFade = 1.3; + float horiz = saturate( 1.0 + horizonFade * NoL); + return horiz * horiz; +} + +float Sheen(float NoHSat, float NoL, float NoV, float roughness) +{ + if (NoL <= 0.0 || NoV <= 0.0) + return 0.0; + float NoH2 = NoHSat*NoHSat; + float NoL2 = NoL*NoL; + float NoV2 = NoV*NoV; + roughness += EPSILON_LOWP; + float r2 = roughness*roughness; + + float t = 1.0 - NoH2 + NoH2/r2; + float Pi_D = 1.0 / (roughness * t * t); + + float Li = sqrt(1.0 - NoL2 + r2*NoL2) / NoL; + float Lo = sqrt(1.0 - NoV2 + r2*NoV2) / NoV; + float G = (1.0 - exp(-(Li + Lo))) / (Li + Lo); + + return Sheen_HorizonFading(NoL) * Pi_D * G / NoV; +} +// simplify estimation for env lighting convolution +float Sheen(float NoV, float roughness) +{ + NoV *= NoV; + float NoV2 = NoV*NoV; + roughness += EPSILON_LOWP; + float r2 = roughness*roughness; + + float t = 1.0 - NoV2 + NoV2/r2; + float Pi_D = 1.0 / (roughness * t * t); + + float Lo = sqrt(1.0 - NoV2 + r2*NoV2) / NoV; + float G = (1.0 - exp(-Lo)) / Lo; + + float sheen = Pi_D * G / NoV; + return pow(max(0.0, sheen), 0.5); +} + +// Diffuse_Lambert #define DiffuseCoefficient_EnergyConservation INV_PI diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index 0324db26f35..14e26fb2c2b 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -109,11 +109,11 @@ LightingIntermediateData lightingData2ndSpecular; CCSurfacesInitializeLightingIntermediateData(lightingData2ndSpecular, surfaceData2ndSpecular); CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData2ndSpecular, surfaceData, lightDirWithLength); - CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); - CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, vec3(1.0)); - #if CC_SURFACES_LIGHTING_SHEEN - vec3 extraF = CCSurfaceLightingCalculateExtraFresnel(lightingData2ndSpecular); - lightingResult.directGF2ndSpecular *= extraF; + #if !CC_SURFACES_LIGHTING_SHEEN + CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, vec3(1.0)); + #else + CCSurfacesLightingCalculateDirectSheen(lightingResult.direct2ndSpecular, lightingResult.directGF2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular); #endif lightingResult.direct2ndSpecular *= multiplier; @@ -258,15 +258,15 @@ vec3 diff; CCSurfacesLightingInitializeColorWithLighting(diff, lightingResult.specularColorWithLighting2ndSpecular, surfaceData2ndSpecular, lightingData2ndSpecular); - CCSurfacesLightingCalculateEnvironment2ndSpecular(lightingResult.environment2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.environmentSpecular); - CCSurfaceLightingCalculateEnvironmentFresnel(lightingResult.environmentGF2ndSpecular, lightingResult.environmentSubLayerF, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular); + #if !CC_SURFACES_LIGHTING_SHEEN + CCSurfacesLightingCalculateEnvironment2ndSpecular(lightingResult.environment2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.environmentSpecular); + CCSurfaceLightingCalculateEnvironmentFresnel(lightingResult.environmentGF2ndSpecular, lightingResult.environmentSubLayerF, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular); - CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); - CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, lightingResult.environmentGF2ndSpecular); - #if CC_SURFACES_LIGHTING_SHEEN - vec3 extraF = CCSurfaceLightingCalculateExtraFresnel(lightingData2ndSpecular); - lightingResult.environmentGF2ndSpecular *= extraF; - lightingResult.directGF2ndSpecular *= extraF; + CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, lightingResult.environmentGF2ndSpecular); + #else + CCSurfacesLightingCalculateDirectSheen(lightingResult.direct2ndSpecular, lightingResult.directGF2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular); + CCSurfacesLightingCalculateEnvironmentSheen(lightingResult.environment2ndSpecular, lightingResult.environmentGF2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular); #endif #endif diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index a0a5054f127..3898c96d443 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -234,6 +234,37 @@ void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 in specularLighting = vec3(0.0); #endif } + + void CCSurfacesLightingCalculateDirectSheen(out vec3 specularLighting, out vec3 directGF, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity, float intensitySpecular) + { + #if !CC_SURFACES_LIGHTING_DISABLE_SPECULAR + float sheen = Sheen(lightingData.NoHSat, lightingData.NoL, lightingData.NoV, lightingData.specularParam); + specularLighting = vec3(sheen) * intensitySpecular * lightSourceColorAndIntensity.xyz * lightSourceColorAndIntensity.w; + directGF = vec3(1.0); + #else + specularLighting = vec3(0.0); + #endif + } + + void CCSurfacesLightingCalculateEnvironmentSheen(out vec3 specularLighting, out vec3 environmentGF, in LightingIntermediateData lightingData, float lightIntensity, float intensitySpecular) + { + #if !CC_SURFACES_LIGHTING_DISABLE_SPECULAR + LightingIntermediateData lightingDataSheen = lightingData; + float roughness = lightingData.specularParam; + + // sample max distribute normal-vertical-direction reflection with fixed roughness + vec3 L = normalize(mix(lightingDataSheen.B, lightingDataSheen.N, 0.3)); + lightingDataSheen.specularParam = mix(0.5, 0.9, roughness); + lightingDataSheen.V = lightingDataSheen.N = L; + specularLighting = CalculateEnvironmentSpecular(lightingDataSheen, lightIntensity); + specularLighting *= intensitySpecular; + + // range limitation + environmentGF = vec3(Sheen(lightingData.NoV, roughness)); + #else + specularLighting = vec3(0.0); + #endif + } #endif #if CC_SURFACES_LIGHTING_TT diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index 038a9e75993..8229737b289 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -220,8 +220,8 @@ vec3 SurfacesFragmentModifyClearCoatWorldNormal() vec4 SurfacesFragmentModifySheenParams() { //x: sheen roughness - //y: sheen ior - //z: sheen opacity + //y: sheen opacity + //z: unused //w: sheen intensity return vec4(0.7, 1.0, 1.0, 1.0); } diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index 86db9d4f507..d3deafc53c4 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -91,14 +91,14 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) // skip in shader graph, need extra code vec4 sheenParams = SurfacesFragmentModifySheenParams(); surfaceData.roughness2ndSpecular = saturate(sheenParams.x); - surfaceData.ior2ndSpecular = sheenParams.y; - surfaceData.intensity2ndSpecular = sheenParams.z * sheenParams.w; + surfaceData.intensity2ndSpecular = sheenParams.y * sheenParams.w; surfaceData.metallic2ndSpecular = 1.0; surfaceData.baseColor2ndSpecular = SurfacesFragmentModifySheenColor(); surfaceData.color2ndSpecular = vec3(1.0); // no extra coloration surfaceData.worldNormal2ndSpecular = surfaceData.worldNormal; surfaceData.worldTangent2ndSpecular = surfaceData.worldTangent; surfaceData.worldBinormal2ndSpecular = surfaceData.worldBinormal; + surfaceData.ior2ndSpecular = surfaceData.ior; //unused surfaceData.opacity2ndSpecular = 1.0; // unused #if CC_SURFACES_LIGHTING_ANISOTROPIC surfaceData.anisotropyShape2ndSpecular = surfaceData.anisotropyShape; diff --git a/editor/assets/effects/advanced/fabric.effect b/editor/assets/effects/advanced/fabric.effect index 4803793548b..c690c8ec884 100644 --- a/editor/assets/effects/advanced/fabric.effect +++ b/editor/assets/effects/advanced/fabric.effect @@ -27,9 +27,10 @@ CCEffect %{ anisotropyMap: { value: black, editor : { parent: IS_ANISOTROPY } } sheenColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { type: color } } sheenRoughness: { value: 1.0, target: emissiveScaleParam.x, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } - sheenIOR: { value: 1.0, target: emissiveScaleParam.y, editor: { slide: true, range: [1.0, 2.0], step: 0.001 } } - sheenOpacity: { value: 1.0, target: emissiveScaleParam.z, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } - sheenMap: { value: white, editor: { parent: USE_SHEEN_MAP, tooltips: 'r: sheen roughness g: sheen opacity' } } + sheenOpacity: { value: 1.0, target: emissiveScaleParam.y, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + sheenIntensity: { value: 1.0, target: emissiveScaleParam.w, editor: { slide: true, range: [1.0, 3.0], step: 0.001 } } + sheenColorMap: { value: white, editor: { parent: USE_SHEEN_COLOR_MAP } } + sheenDataMap: { value: white, editor: { parent: USE_SHEEN_DATA_MAP, tooltips: 'r: sheen roughness g: sheen opacity' } } - &forward-add vert: standard-vs frag: standard-fs @@ -145,10 +146,8 @@ CCProgram macro-remapping %{ #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR #define CC_SURFACES_LIGHTING_SHEEN 1 - // depend on UI macros -#if IS_ANISOTROPY || USE_NORMAL_MAP + // sheen need tangent #define CC_SURFACES_USE_TANGENT_SPACE 1 -#endif // functionality for each effect #define CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT 31 @@ -190,8 +189,11 @@ CCProgram surface-fragment %{ #if IS_ANISOTROPY && USE_ANISOTROPY_MAP uniform sampler2D anisotropyMap; #endif - #if USE_SHEEN_MAP - uniform sampler2D sheenMap; + #if USE_SHEEN_COLOR_MAP + uniform sampler2D sheenColorMap; + #endif + #if USE_SHEEN_DATA_MAP + uniform sampler2D sheenDataMap; #endif #pragma define OCCLUSION_CHANNEL r @@ -223,9 +225,9 @@ CCProgram surface-fragment %{ #define CC_SURFACES_FRAGMENT_MODIFY_SHEEN_PARAMS vec4 SurfacesFragmentModifySheenParams() { - vec4 param = vec4(emissiveScaleParam.x, emissiveScaleParam.y - 0.9, emissiveScaleParam.z, 1.0); - #if USE_SHEEN_MAP - param.xz *= texture(sheenMap, FSInput_texcoord).xy; + vec4 param = emissiveScaleParam; + #if USE_SHEEN_DATA_MAP + param.xy *= texture(sheenDataMap, FSInput_texcoord).xy; #endif return param; } @@ -233,7 +235,11 @@ CCProgram surface-fragment %{ #define CC_SURFACES_FRAGMENT_MODIFY_SHEEN_COLOR vec3 SurfacesFragmentModifySheenColor() { + #if USE_SHEEN_COLOR_MAP + return sheenColor.rgb * texture(sheenColorMap, FSInput_texcoord).rgb; + #else return sheenColor.rgb; + #endif } #include From 24848f45125df6203c445fe9a674bdcdf3bc5a5d Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 25 Aug 2023 16:28:34 +0800 Subject: [PATCH 224/232] Revert "sheen lighting model (#16058)" (#16103) --- .../chunks/common/graph-expression/base.chunk | 42 +++++------------ .../assets/chunks/common/lighting/brdf.chunk | 47 +------------------ .../lighting-flow/common-flow.chunk | 26 +++++----- .../model-functions/standard.chunk | 31 ------------ .../default-functions/standard-fs.chunk | 4 +- .../module-functions/standard-fs.chunk | 4 +- editor/assets/effects/advanced/fabric.effect | 28 +++++------ 7 files changed, 42 insertions(+), 140 deletions(-) diff --git a/editor/assets/chunks/common/graph-expression/base.chunk b/editor/assets/chunks/common/graph-expression/base.chunk index 6b565e91c63..c3ef49a59df 100644 --- a/editor/assets/chunks/common/graph-expression/base.chunk +++ b/editor/assets/chunks/common/graph-expression/base.chunk @@ -18,24 +18,6 @@ vec2 Rotator(vec2 uv, vec2 centerUV, float time, float speed) return vec2(dir.x, dir.z) + centerUV; } -// return 0.0 when out of range -// hardness: 0 - 1 -float SphereMask(vec2 center, vec2 point, float radius, float hardness) -{ - float length = length(center - point); - float coef = pow(saturate(length / radius), 1.0 / (1.0 - saturate(sqrt(hardness)) + EPSILON)); - return length > radius ? 0.0 : 1.0 - coef; -} -float SphereMask(vec3 center, vec3 point, float radius, float hardness) -{ - float length = length(center - point); - float coef = pow(saturate(length / radius), 1.0 / (1.0 - saturate(sqrt(hardness)) + EPSILON)); - return length > radius ? 0.0 : 1.0 - coef; -} - - -// For Fragment Shader - // tangent space -> world space // same as TransformVector vec3 TransformNormalMap(vec3 vectorFromNormalMap) @@ -48,16 +30,18 @@ vec3 TransformNormalMap(vec3 vectorFromNormalMap) return vecWS * vec3(1.0, 1.0, -1.0); // inverse Z for RH } -// WorldPos -> UV -vec2 GetTriplanarMappingUV() + +// return 0.0 when out of range +// hardness: 0 - 1 +float SphereMask(vec2 center, vec2 point, float radius, float hardness) { - vec3 Up = vec3(0.0, 1.0, 0.0); - vec3 U = cross(Up, FSInput_worldNormal.xyz); - if (length(U) < 0.01) - U = vec3(1.0, 0.0, 0.0); - else - U = normalize(U); - vec3 V = cross(U, FSInput_worldNormal.xyz); - V = normalize(V); - return fract(vec2(dot(FSInput_worldPos.xyz, U), dot(FSInput_worldPos.xyz, V))); + float length = length(center - point); + float coef = pow(saturate(length / radius), 1.0 / (1.0 - saturate(sqrt(hardness)) + EPSILON)); + return length > radius ? 0.0 : 1.0 - coef; +} +float SphereMask(vec3 center, vec3 point, float radius, float hardness) +{ + float length = length(center - point); + float coef = pow(saturate(length / radius), 1.0 / (1.0 - saturate(sqrt(hardness)) + EPSILON)); + return length > radius ? 0.0 : 1.0 - coef; } diff --git a/editor/assets/chunks/common/lighting/brdf.chunk b/editor/assets/chunks/common/lighting/brdf.chunk index 79405c200ab..ef4fea792a1 100644 --- a/editor/assets/chunks/common/lighting/brdf.chunk +++ b/editor/assets/chunks/common/lighting/brdf.chunk @@ -116,50 +116,5 @@ void IntegratedGFMultiplier (out vec3 integratedGF, out vec3 integratedF, vec3 s integratedGF = max(vec3(0.0), vec3(AB.x) + vec3(AB.y) / (specular + EPSILON_LOWP)); } -// isotropic sheen -float Sheen_HorizonFading(float NoL) -{ - const float horizonFade = 1.3; - float horiz = saturate( 1.0 + horizonFade * NoL); - return horiz * horiz; -} - -float Sheen(float NoHSat, float NoL, float NoV, float roughness) -{ - if (NoL <= 0.0 || NoV <= 0.0) - return 0.0; - float NoH2 = NoHSat*NoHSat; - float NoL2 = NoL*NoL; - float NoV2 = NoV*NoV; - roughness += EPSILON_LOWP; - float r2 = roughness*roughness; - - float t = 1.0 - NoH2 + NoH2/r2; - float Pi_D = 1.0 / (roughness * t * t); - - float Li = sqrt(1.0 - NoL2 + r2*NoL2) / NoL; - float Lo = sqrt(1.0 - NoV2 + r2*NoV2) / NoV; - float G = (1.0 - exp(-(Li + Lo))) / (Li + Lo); - - return Sheen_HorizonFading(NoL) * Pi_D * G / NoV; -} -// simplify estimation for env lighting convolution -float Sheen(float NoV, float roughness) -{ - NoV *= NoV; - float NoV2 = NoV*NoV; - roughness += EPSILON_LOWP; - float r2 = roughness*roughness; - - float t = 1.0 - NoV2 + NoV2/r2; - float Pi_D = 1.0 / (roughness * t * t); - - float Lo = sqrt(1.0 - NoV2 + r2*NoV2) / NoV; - float G = (1.0 - exp(-Lo)) / Lo; - - float sheen = Pi_D * G / NoV; - return pow(max(0.0, sheen), 0.5); -} - -// Diffuse_Lambert +//Diffuse_Lambert #define DiffuseCoefficient_EnergyConservation INV_PI diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index 14e26fb2c2b..0324db26f35 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -109,11 +109,11 @@ LightingIntermediateData lightingData2ndSpecular; CCSurfacesInitializeLightingIntermediateData(lightingData2ndSpecular, surfaceData2ndSpecular); CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData2ndSpecular, surfaceData, lightDirWithLength); - #if !CC_SURFACES_LIGHTING_SHEEN - CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); - CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, vec3(1.0)); - #else - CCSurfacesLightingCalculateDirectSheen(lightingResult.direct2ndSpecular, lightingResult.directGF2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular); + CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, attenuatedLightColorAndIntensity, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, vec3(1.0)); + #if CC_SURFACES_LIGHTING_SHEEN + vec3 extraF = CCSurfaceLightingCalculateExtraFresnel(lightingData2ndSpecular); + lightingResult.directGF2ndSpecular *= extraF; #endif lightingResult.direct2ndSpecular *= multiplier; @@ -258,15 +258,15 @@ vec3 diff; CCSurfacesLightingInitializeColorWithLighting(diff, lightingResult.specularColorWithLighting2ndSpecular, surfaceData2ndSpecular, lightingData2ndSpecular); - #if !CC_SURFACES_LIGHTING_SHEEN - CCSurfacesLightingCalculateEnvironment2ndSpecular(lightingResult.environment2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.environmentSpecular); - CCSurfaceLightingCalculateEnvironmentFresnel(lightingResult.environmentGF2ndSpecular, lightingResult.environmentSubLayerF, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular); + CCSurfacesLightingCalculateEnvironment2ndSpecular(lightingResult.environment2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.environmentSpecular); + CCSurfaceLightingCalculateEnvironmentFresnel(lightingResult.environmentGF2ndSpecular, lightingResult.environmentSubLayerF, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular); - CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); - CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, lightingResult.environmentGF2ndSpecular); - #else - CCSurfacesLightingCalculateDirectSheen(lightingResult.direct2ndSpecular, lightingResult.directGF2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular); - CCSurfacesLightingCalculateEnvironmentSheen(lightingResult.environment2ndSpecular, lightingResult.environmentGF2ndSpecular, lightingData2ndSpecular, cc_ambientSky.w, surfaceData2ndSpecular.intensity2ndSpecular); + CCSurfacesLightingCalculateDirect2ndSpecular(lightingResult.direct2ndSpecular, lightingData2ndSpecular, cc_mainLitColor, surfaceData2ndSpecular.intensity2ndSpecular, lightingResult.directSpecular); + CCSurfaceLightingCalculateDirectFresnel(lightingResult.directGF2ndSpecular, lightingData2ndSpecular, lightingResult.specularColorWithLighting2ndSpecular, lightingResult.environmentGF2ndSpecular); + #if CC_SURFACES_LIGHTING_SHEEN + vec3 extraF = CCSurfaceLightingCalculateExtraFresnel(lightingData2ndSpecular); + lightingResult.environmentGF2ndSpecular *= extraF; + lightingResult.directGF2ndSpecular *= extraF; #endif #endif diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index 3898c96d443..a0a5054f127 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -234,37 +234,6 @@ void CCSurfaceLightingCalculateEnvironmentFresnel(out vec3 integratedGF, vec3 in specularLighting = vec3(0.0); #endif } - - void CCSurfacesLightingCalculateDirectSheen(out vec3 specularLighting, out vec3 directGF, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity, float intensitySpecular) - { - #if !CC_SURFACES_LIGHTING_DISABLE_SPECULAR - float sheen = Sheen(lightingData.NoHSat, lightingData.NoL, lightingData.NoV, lightingData.specularParam); - specularLighting = vec3(sheen) * intensitySpecular * lightSourceColorAndIntensity.xyz * lightSourceColorAndIntensity.w; - directGF = vec3(1.0); - #else - specularLighting = vec3(0.0); - #endif - } - - void CCSurfacesLightingCalculateEnvironmentSheen(out vec3 specularLighting, out vec3 environmentGF, in LightingIntermediateData lightingData, float lightIntensity, float intensitySpecular) - { - #if !CC_SURFACES_LIGHTING_DISABLE_SPECULAR - LightingIntermediateData lightingDataSheen = lightingData; - float roughness = lightingData.specularParam; - - // sample max distribute normal-vertical-direction reflection with fixed roughness - vec3 L = normalize(mix(lightingDataSheen.B, lightingDataSheen.N, 0.3)); - lightingDataSheen.specularParam = mix(0.5, 0.9, roughness); - lightingDataSheen.V = lightingDataSheen.N = L; - specularLighting = CalculateEnvironmentSpecular(lightingDataSheen, lightIntensity); - specularLighting *= intensitySpecular; - - // range limitation - environmentGF = vec3(Sheen(lightingData.NoV, roughness)); - #else - specularLighting = vec3(0.0); - #endif - } #endif #if CC_SURFACES_LIGHTING_TT diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index 8229737b289..038a9e75993 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -220,8 +220,8 @@ vec3 SurfacesFragmentModifyClearCoatWorldNormal() vec4 SurfacesFragmentModifySheenParams() { //x: sheen roughness - //y: sheen opacity - //z: unused + //y: sheen ior + //z: sheen opacity //w: sheen intensity return vec4(0.7, 1.0, 1.0, 1.0); } diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index d3deafc53c4..86db9d4f507 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -91,14 +91,14 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) // skip in shader graph, need extra code vec4 sheenParams = SurfacesFragmentModifySheenParams(); surfaceData.roughness2ndSpecular = saturate(sheenParams.x); - surfaceData.intensity2ndSpecular = sheenParams.y * sheenParams.w; + surfaceData.ior2ndSpecular = sheenParams.y; + surfaceData.intensity2ndSpecular = sheenParams.z * sheenParams.w; surfaceData.metallic2ndSpecular = 1.0; surfaceData.baseColor2ndSpecular = SurfacesFragmentModifySheenColor(); surfaceData.color2ndSpecular = vec3(1.0); // no extra coloration surfaceData.worldNormal2ndSpecular = surfaceData.worldNormal; surfaceData.worldTangent2ndSpecular = surfaceData.worldTangent; surfaceData.worldBinormal2ndSpecular = surfaceData.worldBinormal; - surfaceData.ior2ndSpecular = surfaceData.ior; //unused surfaceData.opacity2ndSpecular = 1.0; // unused #if CC_SURFACES_LIGHTING_ANISOTROPIC surfaceData.anisotropyShape2ndSpecular = surfaceData.anisotropyShape; diff --git a/editor/assets/effects/advanced/fabric.effect b/editor/assets/effects/advanced/fabric.effect index c690c8ec884..4803793548b 100644 --- a/editor/assets/effects/advanced/fabric.effect +++ b/editor/assets/effects/advanced/fabric.effect @@ -27,10 +27,9 @@ CCEffect %{ anisotropyMap: { value: black, editor : { parent: IS_ANISOTROPY } } sheenColor: { value: [1.0, 1.0, 1.0, 1.0], linear: true, editor: { type: color } } sheenRoughness: { value: 1.0, target: emissiveScaleParam.x, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } - sheenOpacity: { value: 1.0, target: emissiveScaleParam.y, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } - sheenIntensity: { value: 1.0, target: emissiveScaleParam.w, editor: { slide: true, range: [1.0, 3.0], step: 0.001 } } - sheenColorMap: { value: white, editor: { parent: USE_SHEEN_COLOR_MAP } } - sheenDataMap: { value: white, editor: { parent: USE_SHEEN_DATA_MAP, tooltips: 'r: sheen roughness g: sheen opacity' } } + sheenIOR: { value: 1.0, target: emissiveScaleParam.y, editor: { slide: true, range: [1.0, 2.0], step: 0.001 } } + sheenOpacity: { value: 1.0, target: emissiveScaleParam.z, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + sheenMap: { value: white, editor: { parent: USE_SHEEN_MAP, tooltips: 'r: sheen roughness g: sheen opacity' } } - &forward-add vert: standard-vs frag: standard-fs @@ -146,8 +145,10 @@ CCProgram macro-remapping %{ #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR #define CC_SURFACES_LIGHTING_SHEEN 1 - // sheen need tangent + // depend on UI macros +#if IS_ANISOTROPY || USE_NORMAL_MAP #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif // functionality for each effect #define CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT 31 @@ -189,11 +190,8 @@ CCProgram surface-fragment %{ #if IS_ANISOTROPY && USE_ANISOTROPY_MAP uniform sampler2D anisotropyMap; #endif - #if USE_SHEEN_COLOR_MAP - uniform sampler2D sheenColorMap; - #endif - #if USE_SHEEN_DATA_MAP - uniform sampler2D sheenDataMap; + #if USE_SHEEN_MAP + uniform sampler2D sheenMap; #endif #pragma define OCCLUSION_CHANNEL r @@ -225,9 +223,9 @@ CCProgram surface-fragment %{ #define CC_SURFACES_FRAGMENT_MODIFY_SHEEN_PARAMS vec4 SurfacesFragmentModifySheenParams() { - vec4 param = emissiveScaleParam; - #if USE_SHEEN_DATA_MAP - param.xy *= texture(sheenDataMap, FSInput_texcoord).xy; + vec4 param = vec4(emissiveScaleParam.x, emissiveScaleParam.y - 0.9, emissiveScaleParam.z, 1.0); + #if USE_SHEEN_MAP + param.xz *= texture(sheenMap, FSInput_texcoord).xy; #endif return param; } @@ -235,11 +233,7 @@ CCProgram surface-fragment %{ #define CC_SURFACES_FRAGMENT_MODIFY_SHEEN_COLOR vec3 SurfacesFragmentModifySheenColor() { - #if USE_SHEEN_COLOR_MAP - return sheenColor.rgb * texture(sheenColorMap, FSInput_texcoord).rgb; - #else return sheenColor.rgb; - #endif } #include From d0ca802f0d7c1128f7b1af07f1d4615ac3e15df8 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 25 Aug 2023 17:30:29 +0800 Subject: [PATCH 225/232] fix glass material blend with fog (#16104) --- .../render-to-scene/pipeline/forward-fs.chunk | 7 +++++-- editor/assets/effects/advanced/glass.effect | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index 96fe6789df5..17565ac6f50 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -143,9 +143,12 @@ void main() { // todo: apply fogColorBrightness to fogColor for supporting scatter lighting with HDR #if CC_USE_FOG != CC_FOG_NONE && (!CC_USE_FLOAT_OUTPUT || CC_IS_TRANSPARENCY_PASS) #if !CC_FORWARD_ADD - CC_APPLY_FOG_BASE(color, fogFactor); + #ifdef CC_SURFACES_LIGHTING_MODIFY_FOG + color.rgb = CCSurfacesLightingModifyFog(fogFactor, color.rgb, surfaceData, lightingResult); + #else + CC_APPLY_FOG_BASE(color, fogFactor); + #endif #endif #endif - fragColorX = color; } diff --git a/editor/assets/effects/advanced/glass.effect b/editor/assets/effects/advanced/glass.effect index 5194b4fb3b4..7e5fbf68800 100644 --- a/editor/assets/effects/advanced/glass.effect +++ b/editor/assets/effects/advanced/glass.effect @@ -276,6 +276,14 @@ CCProgram surface-fragment %{ result.environmentSpecular = result.environmentSpecular / bright * threshold; #endif } + + #define CC_SURFACES_LIGHTING_MODIFY_FOG + vec3 CCSurfacesLightingModifyFog(float fogFactor, vec3 color, in SurfacesMaterialData surfaceData, in LightingResult lightingResult) + { + // according to blend mode is one + src_alpha, fogColor should apply inv_src_alpha while glass is fully fogged, otherwise glass will be much more brighter. + vec3 fogColor = cc_fogColor.rgb * (1.0 - surfaceData.baseColor.a); + return mix(fogColor.rgb, color.rgb, fogFactor); + } }% CCProgram standard-vs %{ From a6b5b61cc0eb71edf7deb6fe1e7b23c89ae7a2fa Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 25 Aug 2023 18:38:53 +0800 Subject: [PATCH 226/232] fix BlitScreen pass make tranparency with clear color (#16108) --- editor/assets/effects/advanced/glass.effect | 2 ++ 1 file changed, 2 insertions(+) diff --git a/editor/assets/effects/advanced/glass.effect b/editor/assets/effects/advanced/glass.effect index 7e5fbf68800..53ce75e4575 100644 --- a/editor/assets/effects/advanced/glass.effect +++ b/editor/assets/effects/advanced/glass.effect @@ -17,6 +17,8 @@ CCEffect %{ - blend: true blendSrc: one blendDst: src_alpha + blendSrcAlpha: zero + blendDstAlpha: one properties: &props tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } mainColor: { value: [0.05, 0.05, 0.05, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } From 88d585acc7aefc7a1f59b2149c521a71a5021fd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Mon, 28 Aug 2023 09:44:52 +0800 Subject: [PATCH 227/232] accept non array type (#16095) --- pal/input/web/gamepad-input.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pal/input/web/gamepad-input.ts b/pal/input/web/gamepad-input.ts index 7d20b9df2b2..15bdcd3f051 100644 --- a/pal/input/web/gamepad-input.ts +++ b/pal/input/web/gamepad-input.ts @@ -239,7 +239,11 @@ export class GamepadInputDevice { private static _totalGamepadCnt = 0; private static _updateGamepadCnt (): void { - GamepadInputDevice._totalGamepadCnt = GamepadInputDevice._cachedWebGamepads.reduce((total, gamepad) => (gamepad ? total + 1 : total), 0); + let cnt = 0; + for (let i = 0, l = GamepadInputDevice._cachedWebGamepads.length; i < l; i++) { + if (GamepadInputDevice._cachedWebGamepads[i]) cnt++; + } + GamepadInputDevice._totalGamepadCnt = cnt; } private static _registerEvent (): void { From 2ea26182e0ebd16242850799bfb1966d35946d20 Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Mon, 28 Aug 2023 09:46:21 +0800 Subject: [PATCH 228/232] Use the resize event of SDL (#16072) * 1. Use the resize event of SDL; 2. Fix the problem of not getting the button when SDL is moving. * 1.Remove redundant code. 2.Fixed compilation errors. * Avoiding repeated viewDidChangeBackingProperties function calls. * Fix the way buttons are fetched. --- native/cocos/platform/SDLHelper.cpp | 32 +++++++++++++++++++++-------- native/cocos/platform/mac/View.mm | 20 ------------------ 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/native/cocos/platform/SDLHelper.cpp b/native/cocos/platform/SDLHelper.cpp index 4c477471bf7..542057c693f 100644 --- a/native/cocos/platform/SDLHelper.cpp +++ b/native/cocos/platform/SDLHelper.cpp @@ -29,7 +29,9 @@ #include "base/Log.h" #include "engine/EngineEvents.h" #include "platform/interfaces/modules/ISystemWindow.h" -#include "platform/interfaces/modules/ISystemWindowManager.h" +#include "platform/BasePlatform.h" +#include "platform/interfaces/modules/ISystemWindow.h" +#include "platform/interfaces/modules/IScreen.h" namespace { std::unordered_map gKeyMap = { @@ -174,23 +176,24 @@ void SDLHelper::dispatchWindowEvent(uint32_t windowId, const SDL_WindowEvent &we events::WindowEvent::broadcast(ev); break; } -// On the mac platform this is done via setframesize int the view. -#if !(CC_PLATFORM == CC_PLATFORM_MACOS) case SDL_WINDOWEVENT_SIZE_CHANGED: { + auto *screen = BasePlatform::getPlatform()->getInterface(); + CC_ASSERT(screen != nullptr); ev.type = WindowEvent::Type::SIZE_CHANGED; - ev.width = wevent.data1; - ev.height = wevent.data2; + ev.width = wevent.data1 * screen->getDevicePixelRatio(); + ev.height = wevent.data2 * screen->getDevicePixelRatio(); events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT_RESIZED: { + auto *screen = BasePlatform::getPlatform()->getInterface(); + CC_ASSERT(screen != nullptr); ev.type = WindowEvent::Type::RESIZED; - ev.width = wevent.data1; - ev.height = wevent.data2; + ev.width = wevent.data1 * screen->getDevicePixelRatio(); + ev.height = wevent.data2 * screen->getDevicePixelRatio(); events::WindowEvent::broadcast(ev); break; } -#endif case SDL_WINDOWEVENT_HIDDEN: { ev.type = WindowEvent::Type::HIDDEN; events::WindowEvent::broadcast(ev); @@ -258,7 +261,18 @@ void SDLHelper::dispatchSDLEvent(uint32_t windowId, const SDL_Event &sdlEvent) { case SDL_MOUSEMOTION: { const SDL_MouseMotionEvent &event = sdlEvent.motion; mouse.type = MouseEvent::Type::MOVE; - mouse.button = 0; + mouse.button = -1; // BUTTON_MISSING + // Needs to be consistent with event-mouse.ts definition + // Multiple button presses at the same time are not supported. + // if we are pressed at the same time, the result is indeterminate. + if (event.state & SDL_BUTTON_LMASK) { + mouse.button |= 0x00; // BUTTON_LEFT + } else if (event.state & SDL_BUTTON_RMASK) { + mouse.button |= 0x02; // BUTTON_RGIHT + } else if (event.state & SDL_BUTTON_MIDDLE) { + mouse.button |= 0x01; // BUTTON_MIDDLE + } + mouse.x = static_cast(event.x); mouse.y = static_cast(event.y); mouse.xDelta = static_cast(event.xrel); diff --git a/native/cocos/platform/mac/View.mm b/native/cocos/platform/mac/View.mm index 622a6097ae8..31b631a5e05 100644 --- a/native/cocos/platform/mac/View.mm +++ b/native/cocos/platform/mac/View.mm @@ -98,17 +98,6 @@ - (void)setFrameSize:(NSSize)newSize { CGSize nativeSize = [self convertSizeToBacking:newSize]; [super setFrameSize:newSize]; layer.drawableSize = nativeSize; - [self viewDidChangeBackingProperties]; - - if (cc::EventDispatcher::initialized()) { - cc::WindowEvent ev; - ev.windowId = [self getWindowId]; - ev.type = cc::WindowEvent::Type::RESIZED; - ev.width = static_cast(nativeSize.width); - ev.height = static_cast(nativeSize.height); - cc::events::WindowEvent::broadcast(ev); - } - } - (void)viewDidChangeBackingProperties { @@ -123,15 +112,6 @@ - (void)viewDidChangeBackingProperties { [super setFrameSize:size]; layer.drawableSize = CGSizeMake(width, height); } - - if (cc::EventDispatcher::initialized()) { - cc::WindowEvent ev; - ev.windowId = [self getWindowId]; - ev.type = cc::WindowEvent::Type::RESIZED; - ev.width = static_cast(width); - ev.height = static_cast(height); - cc::events::WindowEvent::broadcast(ev); - } } - (void)flagsChanged:(NSEvent *)event { From 8da2d17c682c13d354ccbf414217c982f4a6cb3a Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Tue, 29 Aug 2023 10:17:18 +0800 Subject: [PATCH 229/232] fix window resize issue with legacy pipeline. (#16113) --- native/cocos/renderer/gfx-base/GFXDef.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/native/cocos/renderer/gfx-base/GFXDef.cpp b/native/cocos/renderer/gfx-base/GFXDef.cpp index 00a9bc6873e..986c28a1815 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.cpp +++ b/native/cocos/renderer/gfx-base/GFXDef.cpp @@ -129,12 +129,15 @@ ccstd::hash_t Hasher::operator()(const FramebufferInfo &info) c static_cast(info.depthStencilResolveTexture != nullptr); if (info.depthStencilTexture) { ccstd::hash_combine(seed, info.depthStencilTexture->getObjectID()); + ccstd::hash_combine(seed, info.depthStencilTexture->getHash()); } if (info.depthStencilResolveTexture) { ccstd::hash_combine(seed, info.depthStencilResolveTexture->getObjectID()); + ccstd::hash_combine(seed, info.depthStencilResolveTexture->getHash()); } for (auto *colorTexture : info.colorTextures) { ccstd::hash_combine(seed, colorTexture->getObjectID()); + ccstd::hash_combine(seed, colorTexture->getHash()); } ccstd::hash_combine(seed, info.renderPass->getHash()); return seed; From 630fcc95e4703c643267af209f2201a1f6ba053a Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Tue, 29 Aug 2023 10:18:04 +0800 Subject: [PATCH 230/232] fix xr interface framebuffer issue. (#16082) --- .../renderer/gfx-gles3/GLES3Commands.cpp | 32 ++++++++++--------- .../renderer/gfx-gles3/GLES3GPUObjects.h | 5 ++- .../renderer/gfx-gles3/GLES3Swapchain.cpp | 1 + 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 03a57149824..2498af22fe1 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -1519,14 +1519,16 @@ static void doResolve(GLES3Device *device, GLES3GPUFramebuffer *gpuFbo) { auto width = gpuFbo->width; auto height = gpuFbo->height; - if (cache->glReadFramebuffer != gpuFbo->framebuffer.handle) { - GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, gpuFbo->framebuffer.handle)); - cache->glReadFramebuffer = gpuFbo->framebuffer.handle; + const auto fbHandle = gpuFbo->framebuffer.getHandle(); + if (cache->glReadFramebuffer != fbHandle) { + GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, fbHandle)); + cache->glReadFramebuffer = fbHandle; } - if (cache->glDrawFramebuffer != gpuFbo->resolveFramebuffer.handle) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gpuFbo->resolveFramebuffer.handle)); - cache->glDrawFramebuffer = gpuFbo->resolveFramebuffer.handle; + const auto rsvHandle = gpuFbo->resolveFramebuffer.getHandle(); + if (cache->glDrawFramebuffer != rsvHandle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, rsvHandle)); + cache->glDrawFramebuffer = rsvHandle; } gpuFbo->resolveFramebuffer.processLoad(GL_DRAW_FRAMEBUFFER); @@ -1537,7 +1539,7 @@ static void doResolve(GLES3Device *device, GLES3GPUFramebuffer *gpuFbo) { for (auto &[src, dst] : gpuFbo->colorBlitPairs) { drawBuffers[dst] = GL_COLOR_ATTACHMENT0 + dst; GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0 + src)); - if (gpuFbo->resolveFramebuffer.handle != 0) { + if (rsvHandle != 0) { GL_CHECK(glDrawBuffers(resolveColorNum, drawBuffers.data())); } @@ -1548,7 +1550,7 @@ static void doResolve(GLES3Device *device, GLES3GPUFramebuffer *gpuFbo) { drawBuffers[dst] = GL_NONE; } } - if (gpuFbo->dsResolveMask != 0 && gpuFbo->resolveFramebuffer.handle != 0) { + if (gpuFbo->dsResolveMask != 0 && rsvHandle != 0) { GL_CHECK(glBlitFramebuffer( 0, 0, width, height, 0, 0, width, height, @@ -1839,10 +1841,10 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen device->context()->makeCurrent(framebuffer.swapchain); } - - if (cache->glDrawFramebuffer != framebuffer.handle) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer.handle)); - cache->glDrawFramebuffer = framebuffer.handle; + const auto fbHandle = framebuffer.getHandle(); + if (cache->glDrawFramebuffer != fbHandle) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbHandle)); + cache->glDrawFramebuffer = fbHandle; } if (cache->viewport.left != renderArea->x || @@ -1874,7 +1876,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRen } const Color &color = clearColors[attachmentIndex]; - if (framebuffer.handle) { + if (fbHandle) { fColors[0] = color.x; fColors[1] = color.y; fColors[2] = color.z; @@ -3065,7 +3067,7 @@ void GLES3GPUFramebufferObject::bindColorMultiSample(const GLES3GPUTextureView * if (colorIndex >= colors.size()) { colors.resize(colorIndex + 1); } - bool isDefaultFb = swapchain != nullptr; + bool isDefaultFb = swapchain != nullptr && !swapchain->isXR; if (attachment.loadOp == LoadOp::DISCARD) { loadInvalidates.emplace_back(isDefaultFb ? GL_COLOR : GL_COLOR_ATTACHMENT0 + colorIndex); @@ -3083,7 +3085,7 @@ void GLES3GPUFramebufferObject::bindDepthStencil(const GLES3GPUTextureView *text void GLES3GPUFramebufferObject::bindDepthStencilMultiSample(const GLES3GPUTextureView *texture, GLint samples, const DepthStencilAttachment &attachment) { const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(texture->gpuTexture->format)]; - bool isDefaultFb = swapchain != nullptr; + bool isDefaultFb = swapchain != nullptr && !swapchain->isXR; bool hasDepth = info.hasDepth; bool hasStencil = info.hasStencil; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 46332eee71f..4dabb15f051 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -173,6 +173,7 @@ struct GLES3GPUSwapchain { EGLint eglSwapInterval{0}; GLuint glFramebuffer{0}; GLES3GPUTexture *gpuColorTexture{nullptr}; + bool isXR{false}; }; class GLES3GPUSampler final { @@ -356,10 +357,10 @@ struct GLES3GPUFramebufferObject { void processLoad(GLenum target); void processStore(GLenum target); void destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap); + GLuint getHandle() const { return swapchain != nullptr ? swapchain->glFramebuffer : handle; } using Reference = std::pair; - GLuint handle{0}; GLES3GPUSwapchain *swapchain{nullptr}; ccstd::vector colors; @@ -368,6 +369,8 @@ struct GLES3GPUFramebufferObject { ccstd::vector loadInvalidates; ccstd::vector storeInvalidates; +private: + GLuint handle{0}; }; class GLES3GPUFramebuffer final { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp index a2e679c2d5b..49a652702dc 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp @@ -122,6 +122,7 @@ void GLES3Swapchain::doInit(const SwapchainInfo &info) { } if (_xr) { GLES3Device::getInstance()->context()->makeCurrent(_gpuSwapchain, _gpuSwapchain); + _gpuSwapchain->isXR = true; } switch (_vsyncMode) { From 3e34a4c1a28c1cd066cf98cbf21208939af4c994 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 29 Aug 2023 10:34:33 +0800 Subject: [PATCH 231/232] remove default setting --- .../post-process/components/post-process-setting.ts | 8 -------- cocos/rendering/post-process/passes/setting-pass.ts | 5 +---- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/cocos/rendering/post-process/components/post-process-setting.ts b/cocos/rendering/post-process/components/post-process-setting.ts index 9f27b5bc50e..90d60b12106 100644 --- a/cocos/rendering/post-process/components/post-process-setting.ts +++ b/cocos/rendering/post-process/components/post-process-setting.ts @@ -6,14 +6,6 @@ import { PostProcess } from './post-process'; @requireComponent(PostProcess) @executeInEditMode export class PostProcessSetting extends Component { - protected static _default: PostProcessSetting | undefined; - static get default (): PostProcessSetting { - if (!this._default) { - this._default = new this(); - } - return this._default; - } - onEnable (): void { const pp = this.getComponent(PostProcess); pp?.addSetting(this); diff --git a/cocos/rendering/post-process/passes/setting-pass.ts b/cocos/rendering/post-process/passes/setting-pass.ts index 66dd313f000..fe5f63d0f7a 100644 --- a/cocos/rendering/post-process/passes/setting-pass.ts +++ b/cocos/rendering/post-process/passes/setting-pass.ts @@ -6,10 +6,7 @@ import { BasePass } from './base-pass'; export function getSetting (settingClass: new () => T): T { const cls: typeof PostProcessSetting = settingClass as any; let setting = passContext.postProcess && passContext.postProcess.getSetting(cls) as T; - if (!setting) { - setting = cls.default as T; - } - return setting; + return setting!; } export abstract class SettingPass extends BasePass { From e1883761452a5294a780b05eab711511e51e1496 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 17 Jun 2025 11:16:38 +0800 Subject: [PATCH 232/232] enable msaa end fixed forward stage depth --- native/cocos/platform/android/AndroidPlatform.cpp | 2 +- native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp | 4 ++-- native/cocos/renderer/pipeline/forward/ForwardStage.cpp | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index b14f3e2732f..27b191a79b1 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -824,7 +824,7 @@ int32_t AndroidPlatform::loop() { struct android_poll_source *source; // suspend thread while _loopTimeOut set to -1 - while ((ALooper_pollAll(_loopTimeOut, nullptr, &events, + while ((ALooper_pollOnce(_loopTimeOut, nullptr, &events, reinterpret_cast(&source))) >= 0) { // process event if (source != nullptr) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp index 0e74d8081ce..680ff01a2b2 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp @@ -109,8 +109,8 @@ bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstan EGL_CHECK(eglBindAPI(EGL_OPENGL_ES_API)); - bool msaaEnabled{false}; - bool qualityPreferred{false}; + bool msaaEnabled{true}; + bool qualityPreferred{true}; EGLint redSize{8}; EGLint greenSize{8}; diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index 2a96e05caf2..6fa96e0e899 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -276,6 +276,7 @@ void ForwardStage::render(scene::Camera *camera) { // add pass pipeline->getFrameGraph().addPass(static_cast(ForwardInsertPoint::IP_FORWARD), ForwardPipeline::fgStrHandleForwardPass, forwardSetup, forwardExec); pipeline->getFrameGraph().presentFromBlackboard(RenderPipeline::fgStrHandleOutColorTexture, camera->getWindow()->getFramebuffer()->getColorTextures()[0], true); + pipeline->getFrameGraph().presentFromBlackboard(RenderPipeline::fgStrHandleOutDepthTexture, camera->getWindow()->getFramebuffer()->getDepthStencilTexture(), true); } } // namespace pipeline