From 84957145933bef171738d84cff8040fe09c51451 Mon Sep 17 00:00:00 2001 From: kpal Date: Tue, 6 Aug 2024 10:28:58 +0100 Subject: [PATCH] updated eslint config and applied quick fixes --- package-lock.json | 71 +- package.json | 2 +- rollup.config.mjs | 13 +- scripts/animation/tween.js | 72 +- scripts/camera/first-person-camera.js | 4 +- scripts/camera/fly-camera.js | 10 +- scripts/camera/orbit-camera.js | 18 +- scripts/parsers/obj-model.js | 36 +- scripts/physics/action-physics-reset.js | 2 +- scripts/physics/render-physics.js | 12 +- scripts/physics/vehicle.js | 8 +- scripts/posteffects/posteffect-blend.js | 32 +- scripts/posteffects/posteffect-bloom.js | 139 ++-- scripts/posteffects/posteffect-bokeh.js | 158 ++--- .../posteffect-brightnesscontrast.js | 40 +- scripts/posteffects/posteffect-edgedetect.js | 88 +-- scripts/posteffects/posteffect-fxaa.js | 116 ++-- .../posteffect-horizontaltiltshift.js | 52 +- .../posteffects/posteffect-huesaturation.js | 60 +- scripts/posteffects/posteffect-luminosity.js | 24 +- scripts/posteffects/posteffect-outline.js | 80 +-- scripts/posteffects/posteffect-sepia.js | 36 +- scripts/posteffects/posteffect-ssao.js | 625 +++++++++--------- .../posteffect-verticaltiltshift.js | 52 +- scripts/posteffects/posteffect-vignette.js | 30 +- scripts/textmesh/text-mesh.js | 4 +- scripts/utils/cubemap-renderer.js | 8 +- scripts/utils/download-texture.js | 37 +- scripts/utils/planar-renderer.js | 6 +- src/core/constants.js | 2 +- src/core/debug.js | 4 +- src/core/event-handler.js | 42 +- src/core/guid.js | 2 +- src/core/indexed-list.js | 2 +- src/core/math/blue-noise.js | 4 +- src/core/math/color.js | 4 +- src/core/math/curve-set.js | 2 +- src/core/math/mat3.js | 2 +- src/core/math/mat4.js | 5 +- src/core/math/math.js | 3 +- src/core/path.js | 12 +- src/core/platform.js | 4 +- src/core/preprocessor.js | 38 +- src/core/shape/bounding-box.js | 21 +- src/core/shape/bounding-sphere.js | 9 +- src/core/shape/frustum.js | 6 +- src/core/shape/oriented-box.js | 5 +- src/core/shape/plane.js | 6 +- src/core/shape/tri.js | 2 +- src/core/string.js | 3 +- src/core/tags-cache.js | 42 +- src/core/tags.js | 54 +- src/core/uri.js | 20 +- src/core/wasm-module.js | 5 +- src/deprecated/deprecated.js | 112 ++-- src/extras/exporters/core-exporter.js | 8 +- src/extras/exporters/gltf-exporter.js | 70 +- src/extras/exporters/usdz-exporter.js | 25 +- src/extras/gizmo/axis-shapes.js | 25 +- src/extras/gizmo/gizmo.js | 9 +- src/extras/gizmo/rotate-gizmo.js | 13 +- src/extras/gizmo/scale-gizmo.js | 5 +- src/extras/gizmo/transform-gizmo.js | 17 +- src/extras/gizmo/translate-gizmo.js | 5 +- src/extras/gizmo/tri-data.js | 4 +- src/extras/index.js | 12 +- src/extras/mini-stats/graph.js | 10 +- src/extras/mini-stats/mini-stats.js | 26 +- src/extras/mini-stats/render2d.js | 10 +- src/extras/mini-stats/stats-timer.js | 3 +- src/extras/mini-stats/word-atlas.js | 18 +- src/extras/render-passes/render-pass-bloom.js | 10 +- .../render-passes/render-pass-camera-frame.js | 19 +- .../render-passes/render-pass-compose.js | 20 +- .../render-pass-depth-aware-blur.js | 2 +- .../render-passes/render-pass-prepass.js | 6 +- src/extras/render-passes/render-pass-ssao.js | 32 +- src/extras/render-passes/render-pass-taa.js | 4 +- src/framework/anim/binder/anim-binder.js | 6 +- .../anim/binder/default-anim-binder.js | 15 +- .../anim/controller/anim-blend-tree-1d.js | 2 +- .../anim-blend-tree-2d-cartesian.js | 4 +- .../anim-blend-tree-2d-directional.js | 4 +- .../anim/controller/anim-controller.js | 32 +- src/framework/anim/controller/anim-node.js | 2 +- src/framework/anim/controller/anim-state.js | 14 +- src/framework/anim/controller/constants.js | 12 +- src/framework/anim/evaluator/anim-cache.js | 1 - .../anim/evaluator/anim-evaluator.js | 6 +- src/framework/anim/evaluator/anim-snapshot.js | 2 +- .../anim/evaluator/anim-target-value.js | 4 +- src/framework/app-base.js | 149 +++-- src/framework/application.js | 24 +- src/framework/asset/asset-list-loader.js | 34 +- src/framework/asset/asset-localized.js | 12 +- src/framework/asset/asset-reference.js | 28 +- src/framework/asset/asset-registry.js | 45 +- src/framework/asset/asset.js | 40 +- src/framework/asset/constants.js | 3 +- src/framework/bundle/bundle-registry.js | 17 +- src/framework/bundle/bundle.js | 6 +- .../components/anim/component-binder.js | 19 +- .../components/anim/component-layer.js | 2 +- src/framework/components/anim/component.js | 18 +- src/framework/components/anim/system.js | 6 +- .../components/animation/component.js | 29 +- src/framework/components/animation/system.js | 4 +- .../components/audio-listener/system.js | 6 +- src/framework/components/button/component.js | 18 +- src/framework/components/button/data.js | 2 +- src/framework/components/button/system.js | 2 +- src/framework/components/camera/component.js | 4 +- .../components/camera/post-effect-queue.js | 5 +- src/framework/components/camera/system.js | 6 +- src/framework/components/collision/system.js | 35 +- src/framework/components/component.js | 4 +- src/framework/components/element/component.js | 38 +- .../components/element/element-drag-helper.js | 8 +- .../components/element/image-element.js | 49 +- src/framework/components/element/markup.js | 22 +- src/framework/components/element/system.js | 14 +- .../components/element/text-element.js | 48 +- src/framework/components/gsplat/component.js | 8 +- src/framework/components/gsplat/system.js | 4 +- src/framework/components/joint/component.js | 18 +- src/framework/components/joint/system.js | 4 +- .../components/layout-child/system.js | 4 +- .../components/layout-group/component.js | 8 +- .../layout-group/layout-calculator.js | 17 +- .../components/layout-group/system.js | 6 +- src/framework/components/light/component.js | 9 +- src/framework/components/light/system.js | 16 +- src/framework/components/model/component.js | 66 +- src/framework/components/model/system.js | 7 +- .../components/particle-system/component.js | 4 +- .../components/particle-system/data.js | 2 +- .../components/particle-system/system.js | 9 +- src/framework/components/registry.js | 6 +- src/framework/components/render/component.js | 14 +- src/framework/components/render/system.js | 4 +- .../components/rigid-body/component.js | 6 +- src/framework/components/rigid-body/system.js | 13 +- src/framework/components/screen/component.js | 14 +- src/framework/components/screen/system.js | 4 +- src/framework/components/script/component.js | 64 +- src/framework/components/script/system.js | 7 +- .../components/scroll-view/component.js | 10 +- .../components/scroll-view/system.js | 4 +- .../components/scrollbar/component.js | 2 +- src/framework/components/scrollbar/system.js | 2 +- src/framework/components/sound/component.js | 8 +- src/framework/components/sound/slot.js | 30 +- src/framework/components/sound/system.js | 6 +- src/framework/components/sprite/component.js | 26 +- .../sprite/sprite-animation-clip.js | 18 +- src/framework/components/sprite/system.js | 4 +- src/framework/components/system.js | 4 +- src/framework/components/zone/component.js | 3 +- src/framework/components/zone/system.js | 4 +- src/framework/entity.js | 11 +- src/framework/font/canvas-font.js | 8 +- src/framework/font/font.js | 6 +- src/framework/graphics/picker.js | 13 +- src/framework/graphics/primitive-cache.js | 20 +- src/framework/graphics/render-pass-picker.js | 2 +- src/framework/handlers/anim-clip.js | 11 +- src/framework/handlers/anim-state-graph.js | 4 +- src/framework/handlers/animation.js | 6 +- src/framework/handlers/audio.js | 14 +- src/framework/handlers/basis-worker.js | 38 +- src/framework/handlers/basis.js | 61 +- src/framework/handlers/binary.js | 4 +- src/framework/handlers/bundle.js | 6 +- src/framework/handlers/container.js | 2 +- src/framework/handlers/css.js | 4 +- src/framework/handlers/cubemap.js | 26 +- src/framework/handlers/font.js | 13 +- src/framework/handlers/gsplat.js | 2 +- src/framework/handlers/hierarchy.js | 4 +- src/framework/handlers/html.js | 4 +- src/framework/handlers/json.js | 4 +- src/framework/handlers/loader.js | 14 +- src/framework/handlers/material.js | 9 +- src/framework/handlers/model.js | 22 +- src/framework/handlers/render.js | 17 +- src/framework/handlers/scene-settings.js | 2 +- src/framework/handlers/scene-utils.js | 10 +- src/framework/handlers/scene.js | 2 +- src/framework/handlers/script.js | 16 +- src/framework/handlers/shader.js | 4 +- src/framework/handlers/sprite.js | 18 +- src/framework/handlers/template.js | 6 +- src/framework/handlers/text.js | 4 +- src/framework/handlers/texture-atlas.js | 26 +- src/framework/handlers/texture.js | 11 +- src/framework/handlers/untar.js | 3 +- src/framework/i18n/i18n.js | 12 +- src/framework/i18n/utils.js | 16 +- src/framework/input/element-input.js | 65 +- .../lightmapper/bake-light-ambient.js | 8 +- .../lightmapper/bake-light-simple.js | 4 +- src/framework/lightmapper/bake-light.js | 3 +- src/framework/lightmapper/lightmap-filters.js | 4 +- src/framework/lightmapper/lightmapper.js | 42 +- src/framework/parsers/draco-decoder.js | 66 +- src/framework/parsers/draco-worker.js | 14 +- src/framework/parsers/glb-container-parser.js | 4 +- .../parsers/glb-container-resource.js | 16 +- src/framework/parsers/glb-parser.js | 125 ++-- src/framework/parsers/gsplat-resource.js | 4 +- src/framework/parsers/json-model.js | 9 +- .../material/json-standard-material.js | 9 +- src/framework/parsers/ply.js | 56 +- src/framework/parsers/scene.js | 6 +- src/framework/parsers/texture/basis.js | 3 +- src/framework/parsers/texture/dds.js | 4 +- src/framework/parsers/texture/hdr.js | 4 +- .../parsers/texture/img-alpha-test.js | 8 +- src/framework/parsers/texture/img.js | 15 +- src/framework/parsers/texture/ktx.js | 6 +- src/framework/parsers/texture/ktx2.js | 6 +- src/framework/scene-registry.js | 20 +- src/framework/script.js | 3 +- src/framework/script/script-attributes.js | 21 +- src/framework/script/script-create.js | 16 +- src/framework/script/script-registry.js | 24 +- src/framework/script/script-type.js | 6 +- src/framework/script/script.js | 13 +- src/framework/utils/entity-reference.js | 16 +- src/framework/xr/xr-anchor.js | 42 +- src/framework/xr/xr-anchors.js | 110 +-- src/framework/xr/xr-dom-overlay.js | 6 +- src/framework/xr/xr-hand.js | 9 +- src/framework/xr/xr-hit-test-source.js | 18 +- src/framework/xr/xr-hit-test.js | 10 +- src/framework/xr/xr-image-tracking.js | 16 +- src/framework/xr/xr-input-source.js | 14 +- src/framework/xr/xr-input.js | 8 +- src/framework/xr/xr-joint.js | 2 +- src/framework/xr/xr-light-estimation.js | 14 +- src/framework/xr/xr-manager.js | 105 +-- src/framework/xr/xr-mesh-detection.js | 12 +- src/framework/xr/xr-mesh.js | 6 +- src/framework/xr/xr-plane-detection.js | 7 +- src/framework/xr/xr-tracked-image.js | 16 +- src/framework/xr/xr-view.js | 29 +- src/framework/xr/xr-views.js | 15 +- src/platform/audio/channel.js | 8 +- src/platform/audio/channel3d.js | 6 +- src/platform/graphics/bind-group-format.js | 8 +- src/platform/graphics/bind-group.js | 4 +- src/platform/graphics/blend-state.js | 2 +- src/platform/graphics/constants.js | 84 +-- src/platform/graphics/debug-graphics.js | 2 +- src/platform/graphics/depth-state.js | 4 +- src/platform/graphics/dynamic-buffer.js | 2 +- src/platform/graphics/gpu-profiler.js | 6 +- .../graphics/graphics-device-create.js | 25 +- src/platform/graphics/graphics-device.js | 55 +- src/platform/graphics/index-buffer.js | 14 +- .../graphics/null/null-graphics-device.js | 11 +- src/platform/graphics/render-pass.js | 25 +- src/platform/graphics/render-target.js | 13 +- .../graphics/shader-processor-options.js | 2 +- src/platform/graphics/shader-processor.js | 19 +- src/platform/graphics/shader-utils.js | 39 +- src/platform/graphics/shader.js | 4 +- src/platform/graphics/storage-buffer.js | 4 +- src/platform/graphics/texture-utils.js | 2 +- src/platform/graphics/texture.js | 35 +- src/platform/graphics/transform-feedback.js | 10 +- .../graphics/uniform-buffer-format.js | 15 +- src/platform/graphics/uniform-buffer.js | 2 +- src/platform/graphics/vertex-buffer.js | 4 +- src/platform/graphics/vertex-format.js | 17 +- src/platform/graphics/vertex-iterator.js | 11 +- .../graphics/webgl/webgl-gpu-profiler.js | 2 +- .../graphics/webgl/webgl-graphics-device.js | 110 +-- .../graphics/webgl/webgl-index-buffer.js | 2 +- .../graphics/webgl/webgl-render-target.js | 38 +- .../graphics/webgl/webgl-shader-input.js | 4 +- src/platform/graphics/webgl/webgl-shader.js | 26 +- src/platform/graphics/webgl/webgl-texture.js | 66 +- .../graphics/webgl/webgl-vertex-buffer.js | 2 +- .../webgpu/webgpu-bind-group-format.js | 4 +- .../graphics/webgpu/webgpu-bind-group.js | 2 +- src/platform/graphics/webgpu/webgpu-buffer.js | 12 +- .../graphics/webgpu/webgpu-clear-renderer.js | 20 +- .../webgpu/webgpu-compute-pipeline.js | 8 +- .../graphics/webgpu/webgpu-compute.js | 8 +- src/platform/graphics/webgpu/webgpu-debug.js | 6 +- .../graphics/webgpu/webgpu-dynamic-buffer.js | 4 +- .../graphics/webgpu/webgpu-dynamic-buffers.js | 8 +- .../graphics/webgpu/webgpu-gpu-profiler.js | 4 +- .../graphics/webgpu/webgpu-graphics-device.js | 48 +- .../graphics/webgpu/webgpu-index-buffer.js | 6 +- .../graphics/webgpu/webgpu-mipmap-renderer.js | 8 +- .../graphics/webgpu/webgpu-query-set.js | 2 +- .../graphics/webgpu/webgpu-render-pipeline.js | 22 +- .../graphics/webgpu/webgpu-render-target.js | 2 +- .../graphics/webgpu/webgpu-resolver.js | 10 +- src/platform/graphics/webgpu/webgpu-shader.js | 2 +- .../graphics/webgpu/webgpu-texture.js | 6 +- .../graphics/webgpu/webgpu-uniform-buffer.js | 4 +- .../webgpu/webgpu-vertex-buffer-layout.js | 8 +- .../graphics/webgpu/webgpu-vertex-buffer.js | 4 +- src/platform/input/controller.js | 14 +- src/platform/input/game-pads.js | 8 +- src/platform/input/keyboard.js | 6 +- src/platform/input/mouse.js | 8 +- src/platform/input/touch-device.js | 2 +- src/platform/net/http.js | 9 +- src/platform/sound/instance.js | 57 +- src/platform/sound/instance3d.js | 7 +- src/platform/sound/manager.js | 2 +- src/platform/sound/sound.js | 10 +- src/scene/animation/skeleton.js | 6 +- src/scene/area-light-luts.js | 6 +- src/scene/batching/batch-manager.js | 33 +- src/scene/camera.js | 14 +- src/scene/composition/layer-composition.js | 28 +- src/scene/geometry/box-geometry.js | 2 +- src/scene/geometry/cone-base-geometry.js | 4 +- src/scene/geometry/dome-geometry.js | 2 +- src/scene/geometry/geometry-utils.js | 8 +- src/scene/geometry/geometry.js | 4 +- src/scene/geometry/plane-geometry.js | 2 +- src/scene/geometry/torus-geometry.js | 2 +- src/scene/graph-node.js | 87 ++- src/scene/graphics/env-lighting.js | 26 +- src/scene/graphics/light-cube.js | 4 +- src/scene/graphics/noise-textures.js | 10 +- src/scene/graphics/post-effect.js | 2 +- src/scene/graphics/quad-render-utils.js | 4 +- src/scene/graphics/quad-render.js | 18 +- src/scene/graphics/render-pass-color-grab.js | 13 +- src/scene/graphics/render-pass-depth-grab.js | 10 +- src/scene/graphics/render-pass-quad.js | 10 +- src/scene/graphics/render-pass-shader-quad.js | 15 +- src/scene/graphics/reproject-texture.js | 78 +-- src/scene/gsplat/gsplat-compressed-data.js | 2 +- .../gsplat/gsplat-compressed-material.js | 25 +- src/scene/gsplat/gsplat-compressed.js | 4 +- src/scene/gsplat/gsplat-instance.js | 6 +- src/scene/gsplat/gsplat-material.js | 12 +- src/scene/gsplat/gsplat-sorter.js | 4 +- src/scene/gsplat/gsplat.js | 12 +- src/scene/gsplat/shader-generator-gsplat.js | 18 +- src/scene/immediate/immediate-batch.js | 6 +- src/scene/immediate/immediate.js | 11 +- src/scene/layer.js | 13 +- src/scene/light.js | 65 +- src/scene/lighting/light-texture-atlas.js | 8 +- src/scene/lighting/lighting-params.js | 3 +- src/scene/lighting/lights-buffer.js | 11 +- src/scene/lighting/world-clusters-debug.js | 13 +- src/scene/lighting/world-clusters.js | 12 +- .../materials/lit-material-options-builder.js | 2 +- src/scene/materials/lit-material.js | 10 +- src/scene/materials/material.js | 4 +- src/scene/materials/shader-material.js | 2 +- .../standard-material-options-builder.js | 17 +- .../materials/standard-material-options.js | 2 +- .../materials/standard-material-validator.js | 5 +- src/scene/materials/standard-material.js | 26 +- src/scene/mesh-instance.js | 37 +- src/scene/mesh.js | 6 +- src/scene/morph-instance.js | 22 +- src/scene/morph-target.js | 3 +- src/scene/morph.js | 6 +- src/scene/particle-system/cpu-updater.js | 29 +- src/scene/particle-system/gpu-updater.js | 12 +- src/scene/particle-system/particle-emitter.js | 24 +- .../particle-system/particle-material.js | 2 +- src/scene/renderer/forward-renderer.js | 81 +-- src/scene/renderer/light-camera.js | 5 +- .../renderer/render-pass-cookie-renderer.js | 25 +- src/scene/renderer/render-pass-forward.js | 34 +- .../renderer/render-pass-postprocessing.js | 4 +- .../render-pass-shadow-directional.js | 6 +- .../render-pass-shadow-local-clustered.js | 2 +- .../render-pass-shadow-local-non-clustered.js | 4 +- .../renderer/render-pass-update-clustered.js | 8 +- src/scene/renderer/renderer.js | 65 +- src/scene/renderer/shadow-map-cache.js | 2 +- src/scene/renderer/shadow-map.js | 1 - .../renderer/shadow-renderer-directional.js | 12 +- src/scene/renderer/shadow-renderer-local.js | 4 +- src/scene/renderer/shadow-renderer.js | 27 +- src/scene/scene.js | 32 +- src/scene/shader-lib/chunk-builder.js | 4 +- .../shader-lib/chunks/chunk-validation.js | 4 +- .../shader-lib/chunks/chunks-lightmapper.js | 2 +- src/scene/shader-lib/chunks/chunks.js | 232 +++---- src/scene/shader-lib/program-library.js | 36 +- .../shader-lib/programs/lit-options-utils.js | 36 +- src/scene/shader-lib/programs/lit-shader.js | 463 ++++++------- src/scene/shader-lib/programs/lit.js | 20 +- src/scene/shader-lib/programs/particle.js | 42 +- .../programs/shader-generator-shader.js | 10 +- src/scene/shader-lib/programs/skybox.js | 7 +- src/scene/shader-lib/programs/standard.js | 308 ++++----- src/scene/shader-lib/utils.js | 6 +- src/scene/shader-pass.js | 6 +- src/scene/skin-instance-cache.js | 4 +- src/scene/skin-instance.js | 2 +- src/scene/skybox/sky-geometry.js | 10 +- src/scene/skybox/sky-mesh.js | 2 +- src/scene/skybox/sky.js | 8 +- src/scene/sprite.js | 12 +- test/core/core.test.mjs | 17 +- test/core/event-handler.test.mjs | 33 +- test/core/guid.test.mjs | 13 +- test/core/hash.test.mjs | 17 +- test/core/indexed-list.test.mjs | 39 +- test/core/math/bit-packing.test.mjs | 21 +- test/core/math/color.test.mjs | 63 +- test/core/math/curve-set.test.mjs | 51 +- test/core/math/curve.test.mjs | 53 +- test/core/math/mat3.test.mjs | 59 +- test/core/math/mat4.test.mjs | 267 ++++---- test/core/math/math.test.mjs | 123 ++-- test/core/math/quat.test.mjs | 195 +++--- test/core/math/vec2.test.mjs | 183 ++--- test/core/math/vec3.test.mjs | 191 +++--- test/core/math/vec4.test.mjs | 173 ++--- test/core/path.test.mjs | 61 +- test/core/preprocessor.test.mjs | 45 +- test/core/shape/plane.test.mjs | 17 +- test/core/sorted-loop-array.test.mjs | 63 +- test/core/string.test.mjs | 17 +- test/core/uri.test.mjs | 57 +- test/fixtures.mjs | 3 +- .../anim/controller/anim-blend-tree.test.mjs | 80 +-- .../anim/controller/anim-controller.test.mjs | 120 ++-- .../anim/controller/anim-node.test.mjs | 53 +- .../anim/controller/anim-state.test.mjs | 17 +- .../anim/controller/anim-transition.test.mjs | 9 +- .../anim/evaluator/anim-cache.test.mjs | 21 +- .../anim/evaluator/anim-clip.test.mjs | 52 +- .../anim/evaluator/anim-curve.test.mjs | 27 +- .../anim/evaluator/anim-data.test.mjs | 17 +- .../anim/evaluator/anim-evaluator.test.mjs | 20 +- .../anim/evaluator/anim-events.test.mjs | 17 +- .../anim/evaluator/anim-snapshot.test.mjs | 16 +- .../anim/evaluator/anim-target-value.test.mjs | 93 +-- .../anim/evaluator/anim-target.test.mjs | 13 +- .../anim/evaluator/anim-track.test.mjs | 26 +- .../state-graph/anim-state-graph.test.mjs | 11 +- test/framework/application.test.mjs | 30 +- .../asset/asset-list-loader.test.mjs | 58 +- test/framework/asset/asset-localized.test.mjs | 80 +-- test/framework/asset/asset-registry.test.mjs | 96 +-- test/framework/asset/asset.test.mjs | 32 +- .../components/element/component.test.mjs | 23 +- .../layout-group/component.test.mjs | 30 +- .../layout-group/layout-calculator.test.mjs | 107 ++- .../components/model/component.test.mjs | 92 +-- test/framework/components/system.test.mjs | 40 +- test/framework/entity.test.mjs | 144 ++-- test/framework/i18n/i18n.test.mjs | 210 +++--- test/framework/scene-registry.test.mjs | 56 +- test/framework/test-component/system.mjs | 4 +- .../framework/utils/entity-reference.test.mjs | 69 +- test/platform/graphics/blend-state.test.mjs | 17 +- test/platform/graphics/depth-state.test.mjs | 19 +- test/platform/input/keyboard.test.mjs | 43 +- test/platform/input/mouse.test.mjs | 43 +- test/platform/net/http.test.mjs | 28 +- test/scene/batching/batch-manager.test.mjs | 8 +- .../composition/layer-composition.test.mjs | 19 +- test/scene/graph-node.test.mjs | 231 +++---- test/scene/materials/shader-material.test.mjs | 17 +- .../materials/standard-material.test.mjs | 21 +- utils/plugins/rollup-dynamic.mjs | 2 +- utils/plugins/rollup-run-tsc.mjs | 2 +- utils/plugins/rollup-shader-chunks.mjs | 16 +- utils/plugins/rollup-spaces-to-tabs.mjs | 2 +- utils/plugins/rollup-types-fixup.mjs | 4 +- utils/rollup-build-target.mjs | 22 +- utils/rollup-script-target.mjs | 4 +- utils/rollup-version-revision.mjs | 2 +- utils/typedoc-plugin.mjs | 3 +- 483 files changed, 6579 insertions(+), 6029 deletions(-) diff --git a/package-lock.json b/package-lock.json index cd3f7bbdf14..781e4da004c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,7 @@ "@babel/eslint-parser": "^7.24.1", "@babel/preset-env": "^7.24.4", "@playcanvas/canvas-mock": "^1.0.1", - "@playcanvas/eslint-config": "^1.7.1", + "@playcanvas/eslint-config": "^1.7.4", "@rollup/plugin-babel": "^6.0.4", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-strip": "^3.0.4", @@ -2055,13 +2055,14 @@ "dev": true }, "node_modules/@playcanvas/eslint-config": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/@playcanvas/eslint-config/-/eslint-config-1.7.1.tgz", - "integrity": "sha512-/mLrTrWjEMkrY9N8DzhMkwPNBue88RsdVzmxh+Y0rmBScaUrTu1Cj8FA/r1Tw5tXlAvqic7hhvnpL/wxuQcq6A==", + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/@playcanvas/eslint-config/-/eslint-config-1.7.4.tgz", + "integrity": "sha512-vsjFX3aQ0Zn8LvVyoOvTAnT44qoXYmpbwPtOMuxhCJxMPaM4mWUVgDWBgt7/x32lhD+zKxHnZbHvYBs6d3FZ9g==", "dev": true, "dependencies": { "eslint-plugin-import": "^2.28.0", - "eslint-plugin-jsdoc": "^46.4.6" + "eslint-plugin-jsdoc": "^46.4.6", + "eslint-plugin-regexp": "^2.6.0" }, "peerDependencies": { "eslint": ">= 4" @@ -4390,6 +4391,27 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, + "node_modules/eslint-plugin-regexp": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-regexp/-/eslint-plugin-regexp-2.6.0.tgz", + "integrity": "sha512-FCL851+kislsTEQEMioAlpDuK5+E5vs0hi1bF8cFlPlHcEjeRhuAzEsGikXRreE+0j4WhW2uO54MqTjXtYOi3A==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.9.1", + "comment-parser": "^1.4.0", + "jsdoc-type-pratt-parser": "^4.0.0", + "refa": "^0.12.1", + "regexp-ast-analysis": "^0.7.1", + "scslre": "^0.3.0" + }, + "engines": { + "node": "^18 || >=20" + }, + "peerDependencies": { + "eslint": ">=8.44.0" + } + }, "node_modules/eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", @@ -7544,6 +7566,18 @@ "node": ">=8.10.0" } }, + "node_modules/refa": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/refa/-/refa-0.12.1.tgz", + "integrity": "sha512-J8rn6v4DBb2nnFqkqwy6/NnTYMcgLA+sLr0iIO41qpv0n+ngb7ksag2tMRl0inb1bbO/esUwzW1vbJi7K0sI0g==", + "dev": true, + "dependencies": { + "@eslint-community/regexpp": "^4.8.0" + }, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, "node_modules/regenerate": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", @@ -7577,6 +7611,19 @@ "@babel/runtime": "^7.8.4" } }, + "node_modules/regexp-ast-analysis": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/regexp-ast-analysis/-/regexp-ast-analysis-0.7.1.tgz", + "integrity": "sha512-sZuz1dYW/ZsfG17WSAG7eS85r5a0dDsvg+7BiiYR5o6lKCAtUrEwdmRmaGF6rwVj3LcmAeYkOWKEPlbPzN3Y3A==", + "dev": true, + "dependencies": { + "@eslint-community/regexpp": "^4.8.0", + "refa": "^0.12.1" + }, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, "node_modules/regexp.prototype.flags": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.2.tgz", @@ -7974,6 +8021,20 @@ "node": ">=v12.22.7" } }, + "node_modules/scslre": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/scslre/-/scslre-0.3.0.tgz", + "integrity": "sha512-3A6sD0WYP7+QrjbfNA2FN3FsOaGGFoekCVgTyypy53gPxhbkCIjtO6YWgdrfM+n/8sI8JeXZOIxsHjMTNxQ4nQ==", + "dev": true, + "dependencies": { + "@eslint-community/regexpp": "^4.8.0", + "refa": "^0.12.0", + "regexp-ast-analysis": "^0.7.0" + }, + "engines": { + "node": "^14.0.0 || >=16.0.0" + } + }, "node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", diff --git a/package.json b/package.json index 2db5ee36aa8..5bac3d84126 100644 --- a/package.json +++ b/package.json @@ -108,7 +108,7 @@ "@babel/eslint-parser": "^7.24.1", "@babel/preset-env": "^7.24.4", "@playcanvas/canvas-mock": "^1.0.1", - "@playcanvas/eslint-config": "^1.7.1", + "@playcanvas/eslint-config": "^1.7.4", "@rollup/plugin-babel": "^6.0.4", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-strip": "^3.0.4", diff --git a/rollup.config.mjs b/rollup.config.mjs index 1a08db51917..8e6540d76f9 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -1,6 +1,5 @@ import * as fs from 'node:fs'; -import { version, revision } from './utils/rollup-version-revision.mjs'; -import { buildTarget } from './utils/rollup-build-target.mjs'; + // unofficial package plugins import dts from 'rollup-plugin-dts'; @@ -8,14 +7,16 @@ import dts from 'rollup-plugin-dts'; // custom plugins import { runTsc } from './utils/plugins/rollup-run-tsc.mjs'; import { typesFixup } from './utils/plugins/rollup-types-fixup.mjs'; +import { buildTarget } from './utils/rollup-build-target.mjs'; +import { version, revision } from './utils/rollup-version-revision.mjs'; /** @typedef {import('rollup').RollupOptions} RollupOptions */ const BLUE_OUT = '\x1b[34m'; const RED_OUT = '\x1b[31m'; -const BOLD_OUT = `\x1b[1m`; -const REGULAR_OUT = `\x1b[22m`; -const RESET_OUT = `\x1b[0m`; +const BOLD_OUT = '\x1b[1m'; +const REGULAR_OUT = '\x1b[22m'; +const RESET_OUT = '\x1b[0m'; /** * @type {['release', 'debug', 'profiler', 'min']} @@ -53,7 +54,7 @@ const TYPES_TARGET = [{ const envTarget = process.env.target ? process.env.target.toLowerCase() : null; const title = [ - `Building PlayCanvas Engine`, + 'Building PlayCanvas Engine', `version ${BOLD_OUT}v${version}${REGULAR_OUT}`, `revision ${BOLD_OUT}${revision}${REGULAR_OUT}`, `target ${BOLD_OUT}${envTarget ?? 'all'}${REGULAR_OUT}` diff --git a/scripts/animation/tween.js b/scripts/animation/tween.js index 77c7c813956..6bd9402dceb 100644 --- a/scripts/animation/tween.js +++ b/scripts/animation/tween.js @@ -271,47 +271,47 @@ Tween.prototype.start = function (idx) { updateProperty(startValue); tweenInstances[idx] = new TWEEN.Tween(startValue) - .to(endValue, tween.duration) - .easing(easingFunc) - .onStart(function (obj) { - if (tween.startEvent !== '') { - app.fire(tween.startEvent); - } - }) - .onStop(function (obj) { - if (tween.stopEvent !== '') { - app.fire(tween.stopEvent); - } - tweenInstances[idx] = null; - }) - .onUpdate(function (obj) { - updateProperty(obj); + .to(endValue, tween.duration) + .easing(easingFunc) + .onStart((obj) => { + if (tween.startEvent !== '') { + app.fire(tween.startEvent); + } + }) + .onStop((obj) => { + if (tween.stopEvent !== '') { + app.fire(tween.stopEvent); + } + tweenInstances[idx] = null; + }) + .onUpdate((obj) => { + updateProperty(obj); - if (tween.updateEvent !== '') { - app.fire(tween.updateEvent); - } - }) - .onComplete(function (obj) { - if (tween.completeEvent !== '') { - app.fire(tween.completeEvent); - } - tweenInstances[idx] = null; - }) - .onRepeat(function (obj) { - if (tween.repeatEvent !== '') { - app.fire(tween.repeatEvent); - } - }) - .repeat(tween.repeat === -1 ? Infinity : tween.repeat) - .repeatDelay(tween.repeatDelay) - .yoyo(tween.yoyo) - .delay(tween.delay) - .start(); + if (tween.updateEvent !== '') { + app.fire(tween.updateEvent); + } + }) + .onComplete((obj) => { + if (tween.completeEvent !== '') { + app.fire(tween.completeEvent); + } + tweenInstances[idx] = null; + }) + .onRepeat((obj) => { + if (tween.repeatEvent !== '') { + app.fire(tween.repeatEvent); + } + }) + .repeat(tween.repeat === -1 ? Infinity : tween.repeat) + .repeatDelay(tween.repeatDelay) + .yoyo(tween.yoyo) + .delay(tween.delay) + .start(); }; // We have to update the tween.js engine somewhere once a frame... if (pc.Application.getApplication()) { - pc.Application.getApplication().on('update', function (dt) { + pc.Application.getApplication().on('update', (dt) => { TWEEN.update(); }); } diff --git a/scripts/camera/first-person-camera.js b/scripts/camera/first-person-camera.js index 7a472885b37..cd8d20d6fa5 100644 --- a/scripts/camera/first-person-camera.js +++ b/scripts/camera/first-person-camera.js @@ -844,7 +844,7 @@ GamePadInputScript.attributes.add('deadZoneLow', { title: 'Low Dead Zone', - description: "Radial thickness of inner dead zone of pad's joysticks. This dead zone ensures that all pads report a value of 0 for each joystick axis when untouched.", + description: 'Radial thickness of inner dead zone of pad\'s joysticks. This dead zone ensures that all pads report a value of 0 for each joystick axis when untouched.', type: 'number', min: 0, max: 0.4, @@ -852,7 +852,7 @@ }); GamePadInputScript.attributes.add('deadZoneHigh', { title: 'High Dead Zone', - description: "Radial thickness of outer dead zone of pad's joysticks. This dead zone ensures that all pads can reach the -1 and 1 limits of each joystick axis.", + description: 'Radial thickness of outer dead zone of pad\'s joysticks. This dead zone ensures that all pads can reach the -1 and 1 limits of each joystick axis.', type: 'number', min: 0, max: 0.4, diff --git a/scripts/camera/fly-camera.js b/scripts/camera/fly-camera.js index 322641086fe..66a7afab69b 100644 --- a/scripts/camera/fly-camera.js +++ b/scripts/camera/fly-camera.js @@ -14,9 +14,9 @@ FlyCamera.attributes.add('mode', { type: 'number', default: 0, enum: [{ - "Lock": 0 + 'Lock': 0 }, { - "Drag": 1 + 'Drag': 1 }] }); @@ -63,11 +63,13 @@ FlyCamera.prototype.update = function (dt) { FlyCamera.prototype.onMouseMove = function (event) { if (!this.mode) { - if (!pc.Mouse.isPointerLocked()) + if (!pc.Mouse.isPointerLocked()) { return; + } } else { - if (!this.lmbDown) + if (!this.lmbDown) { return; + } } diff --git a/scripts/camera/orbit-camera.js b/scripts/camera/orbit-camera.js index 80e273943e9..d2f7f78aed7 100644 --- a/scripts/camera/orbit-camera.js +++ b/scripts/camera/orbit-camera.js @@ -31,7 +31,7 @@ OrbitCamera.attributes.add('frameOnStart', { // Property to get and set the distance between the pivot point and camera // Clamped between this.distanceMin and this.distanceMax -Object.defineProperty(OrbitCamera.prototype, "distance", { +Object.defineProperty(OrbitCamera.prototype, 'distance', { get: function () { return this._targetDistance; }, @@ -43,7 +43,7 @@ Object.defineProperty(OrbitCamera.prototype, "distance", { // Property to get and set the camera orthoHeight // Clamped above 0 -Object.defineProperty(OrbitCamera.prototype, "orthoHeight", { +Object.defineProperty(OrbitCamera.prototype, 'orthoHeight', { get: function () { return this.entity.camera.orthoHeight; }, @@ -57,7 +57,7 @@ Object.defineProperty(OrbitCamera.prototype, "orthoHeight", { // Property to get and set the pitch of the camera around the pivot point (degrees) // Clamped between this.pitchAngleMin and this.pitchAngleMax // When set at 0, the camera angle is flat, looking along the horizon -Object.defineProperty(OrbitCamera.prototype, "pitch", { +Object.defineProperty(OrbitCamera.prototype, 'pitch', { get: function () { return this._targetPitch; }, @@ -69,7 +69,7 @@ Object.defineProperty(OrbitCamera.prototype, "pitch", { // Property to get and set the yaw of the camera around the pivot point (degrees) -Object.defineProperty(OrbitCamera.prototype, "yaw", { +Object.defineProperty(OrbitCamera.prototype, 'yaw', { get: function () { return this._targetYaw; }, @@ -94,7 +94,7 @@ Object.defineProperty(OrbitCamera.prototype, "yaw", { // Property to get and set the world position of the pivot point that the camera orbits around -Object.defineProperty(OrbitCamera.prototype, "pivotPoint", { +Object.defineProperty(OrbitCamera.prototype, 'pivotPoint', { get: function () { return this._pivotPoint; }, @@ -244,7 +244,7 @@ OrbitCamera.prototype.initialize = function () { } }); - this.on('destroy', function () { + this.on('destroy', () => { window.removeEventListener('resize', onWindowResize, false); }); }; @@ -294,7 +294,7 @@ OrbitCamera.prototype._checkAspectRatio = function () { OrbitCamera.prototype._buildAabb = function (entity) { var i, m, meshInstances = []; - var renders = entity.findComponents("render"); + var renders = entity.findComponents('render'); for (i = 0; i < renders.length; i++) { var render = renders[i]; for (m = 0; m < render.meshInstances.length; m++) { @@ -302,7 +302,7 @@ OrbitCamera.prototype._buildAabb = function (entity) { } } - var models = entity.findComponents("model"); + var models = entity.findComponents('model'); for (i = 0; i < models.length; i++) { var model = models[i]; for (m = 0; m < model.meshInstances.length; m++) { @@ -310,7 +310,7 @@ OrbitCamera.prototype._buildAabb = function (entity) { } } - var gsplats = entity.findComponents("gsplat"); + var gsplats = entity.findComponents('gsplat'); for (i = 0; i < gsplats.length; i++) { var gsplat = gsplats[i]; var instance = gsplat.instance; diff --git a/scripts/parsers/obj-model.js b/scripts/parsers/obj-model.js index 08dcd7827b6..2b97a1c061f 100644 --- a/scripts/parsers/obj-model.js +++ b/scripts/parsers/obj-model.js @@ -37,8 +37,8 @@ Object.assign(ObjModelParser.prototype, { indices: [] } }; - var group = "default"; // current group - var lines = input.split("\n"); + var group = 'default'; // current group + var lines = input.split('\n'); var verts = [], normals = [], uvs = []; var i; @@ -71,10 +71,12 @@ Object.assign(ObjModelParser.prototype, { for (p = 1; p < parts.length; p++) { r = this._parseIndices(parts[p]); parsed[group].verts.push(verts[r[0] * 3], verts[r[0] * 3 + 1], verts[r[0] * 3 + 2]); // expand uvs from indices - if (r[1] * 2 < uvs.length) - parsed[group].uvs.push(uvs[r[1] * 2], uvs[r[1] * 2 + 1]); // expand uvs from indices - if (r[2] * 3 < normals.length) - parsed[group].normals.push(normals[r[2] * 3], normals[r[2] * 3 + 1], normals[r[2] * 3 + 2]); // expand normals from indices + if (r[1] * 2 < uvs.length) { + parsed[group].uvs.push(uvs[r[1] * 2], uvs[r[1] * 2 + 1]); + } // expand uvs from indices + if (r[2] * 3 < normals.length) { + parsed[group].normals.push(normals[r[2] * 3], normals[r[2] * 3 + 1], normals[r[2] * 3 + 2]); + } // expand normals from indices } } else if (parts.length === 5) { @@ -84,13 +86,15 @@ Object.assign(ObjModelParser.prototype, { p = order[o]; r = this._parseIndices(parts[p]); parsed[group].verts.push(verts[r[0] * 3], verts[r[0] * 3 + 1], verts[r[0] * 3 + 2]); // expand uvs from indices - if (r[1] * 2 < uvs.length) - parsed[group].uvs.push(uvs[r[1] * 2], uvs[r[1] * 2 + 1]); // expand uvs from indices - if (r[2] * 3 < normals.length) - parsed[group].normals.push(normals[r[2] * 3], normals[r[2] * 3 + 1], normals[r[2] * 3 + 2]); // expand normals from indices + if (r[1] * 2 < uvs.length) { + parsed[group].uvs.push(uvs[r[1] * 2], uvs[r[1] * 2 + 1]); + } // expand uvs from indices + if (r[2] * 3 < normals.length) { + parsed[group].normals.push(normals[r[2] * 3], normals[r[2] * 3 + 1], normals[r[2] * 3 + 2]); + } // expand normals from indices } } else { - console.error(pc.string.format("OBJ uses unsupported {0}-gons", parts.length - 1)); + console.error(pc.string.format('OBJ uses unsupported {0}-gons', parts.length - 1)); } } } @@ -103,15 +107,17 @@ Object.assign(ObjModelParser.prototype, { var currentGroup = parsed[groupNames[i]]; if (!currentGroup.verts.length) continue; if (currentGroup.verts.length > 65535) { - console.warn("Warning: mesh with more than 65535 vertices"); + console.warn('Warning: mesh with more than 65535 vertices'); } var geom = new pc.Geometry(); geom.positions = currentGroup.verts; - if (currentGroup.normals.length > 0) + if (currentGroup.normals.length > 0) { geom.normals = currentGroup.normals; - if (currentGroup.uvs.length > 0) + } + if (currentGroup.uvs.length > 0) { geom.uvs = currentGroup.uvs; + } var mesh = pc.Mesh.fromGeometry(this._device, geom); @@ -126,7 +132,7 @@ Object.assign(ObjModelParser.prototype, { _parseIndices: function (str) { var result = []; - var indices = str.split("/"); + var indices = str.split('/'); for (var i = 0; i < 3; i++) { if (indices[i]) { result[i] = parseInt(indices[i], 10) - 1; // convert to 0-indexed diff --git a/scripts/physics/action-physics-reset.js b/scripts/physics/action-physics-reset.js index e13c1ee13fa..f4c33859784 100644 --- a/scripts/physics/action-physics-reset.js +++ b/scripts/physics/action-physics-reset.js @@ -28,7 +28,7 @@ ActionPhysicsReset.prototype.postInitialize = function () { app.on(this.event, reset); } - this.on('attr:event', function (value, prev) { + this.on('attr:event', (value, prev) => { if (prev && prev.length > 0) { app.off(prev, reset); } diff --git a/scripts/physics/render-physics.js b/scripts/physics/render-physics.js index e646013d194..b78aefd347e 100644 --- a/scripts/physics/render-physics.js +++ b/scripts/physics/render-physics.js @@ -25,13 +25,13 @@ RenderPhysics.attributes.add('castShadows', { RenderPhysics.prototype.initialize = function () { // Handle attribute change events this.on('attr:castShadows', function (value, prev) { - this.debugRoot.children.forEach(function (child) { + this.debugRoot.children.forEach((child) => { child.model.castShadows = value; }); }, this); this.on('attr:opacity', function (value, prev) { - this.debugRoot.children.forEach(function (child) { - child.model.meshInstances.forEach(function (meshInstance) { + this.debugRoot.children.forEach((child) => { + child.model.meshInstances.forEach((meshInstance) => { var material = meshInstance.material; material.opacity = value; material.update(); @@ -50,7 +50,7 @@ RenderPhysics.prototype.initialize = function () { this.on('disable', function () { var collisionComponents = this.app.root.findComponents('collision'); - collisionComponents.forEach(function (collision) { + collisionComponents.forEach((collision) => { if (collision.hasOwnProperty('_debugShape')) { delete collision._debugShape; } @@ -70,7 +70,7 @@ RenderPhysics.prototype.createModel = function (mesh, material) { RenderPhysics.prototype.postUpdate = function (dt) { // For any existing debug shapes, mark them as not updated (yet) - this.debugRoot.children.forEach(function (child) { + this.debugRoot.children.forEach((child) => { child.updated = false; }); @@ -217,7 +217,7 @@ RenderPhysics.prototype.postUpdate = function (dt) { // If a debug shape was not updated this frame, the source collision component // isn't around any more so we can delete it - this.debugRoot.children.forEach(function (child) { + this.debugRoot.children.forEach((child) => { if (!child.updated) { delete child._collision._debugShape; delete child._collision; diff --git a/scripts/physics/vehicle.js b/scripts/physics/vehicle.js index e104e5518aa..22316065d0a 100644 --- a/scripts/physics/vehicle.js +++ b/scripts/physics/vehicle.js @@ -47,7 +47,7 @@ Vehicle.prototype.initialize = function () { var wheelDirection = new Ammo.btVector3(0, -1, 0); var connectionPoint = new Ammo.btVector3(0, 0, 0); - this.wheels.forEach(function (wheelEntity) { + this.wheels.forEach((wheelEntity) => { var wheelScript = wheelEntity.script.vehicleWheel; var frictionSlip = wheelScript.frictionSlip; @@ -84,15 +84,15 @@ Vehicle.prototype.initialize = function () { this.steering = 0; // Event handling - this.on("enable", function () { + this.on('enable', () => { dynamicsWorld.addAction(vehicle); }); - this.on("disable", function () { + this.on('disable', () => { dynamicsWorld.removeAction(vehicle); }); - this.on("destroy", function () { + this.on('destroy', () => { dynamicsWorld.removeAction(vehicle); Ammo.destroy(vehicleRayCaster); diff --git a/scripts/posteffects/posteffect-blend.js b/scripts/posteffects/posteffect-blend.js index 9ce18649be1..ba262fe0ef9 100644 --- a/scripts/posteffects/posteffect-blend.js +++ b/scripts/posteffects/posteffect-blend.js @@ -13,19 +13,19 @@ function BlendEffect(graphicsDevice) { pc.PostEffect.call(this, graphicsDevice); var fshader = [ - "uniform float uMixRatio;", - "uniform sampler2D uColorBuffer;", - "uniform sampler2D uBlendMap;", - "", - "varying vec2 vUv0;", - "", - "void main(void)", - "{", - " vec4 texel1 = texture2D(uColorBuffer, vUv0);", - " vec4 texel2 = texture2D(uBlendMap, vUv0);", - " gl_FragColor = mix(texel1, texel2, uMixRatio);", - "}" - ].join("\n"); + 'uniform float uMixRatio;', + 'uniform sampler2D uColorBuffer;', + 'uniform sampler2D uBlendMap;', + '', + 'varying vec2 vUv0;', + '', + 'void main(void)', + '{', + ' vec4 texel1 = texture2D(uColorBuffer, vUv0);', + ' vec4 texel2 = texture2D(uBlendMap, vUv0);', + ' gl_FragColor = mix(texel1, texel2, uMixRatio);', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'BlendShader', { aPosition: pc.SEMANTIC_POSITION @@ -45,9 +45,9 @@ Object.assign(BlendEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uMixRatio").setValue(this.mixRatio); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); - scope.resolve("uBlendMap").setValue(this.blendMap); + scope.resolve('uMixRatio').setValue(this.mixRatio); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); + scope.resolve('uBlendMap').setValue(this.blendMap); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-bloom.js b/scripts/posteffects/posteffect-bloom.js index 74b0586c774..001ed24c17b 100644 --- a/scripts/posteffects/posteffect-bloom.js +++ b/scripts/posteffects/posteffect-bloom.js @@ -72,70 +72,70 @@ function BloomEffect(graphicsDevice) { // Pixel shader extracts the brighter areas of an image. // This is the first step in applying a bloom postprocess. var extractFrag = [ - "varying vec2 vUv0;", - "", - "uniform sampler2D uBaseTexture;", - "uniform float uBloomThreshold;", - "", - "void main(void)", - "{", - // Look up the original image color. - " vec4 color = texture2D(uBaseTexture, vUv0);", - "", - // Adjust it to keep only values brighter than the specified threshold. - " gl_FragColor = clamp((color - uBloomThreshold) / (1.0 - uBloomThreshold), 0.0, 1.0);", - "}" - ].join("\n"); + 'varying vec2 vUv0;', + '', + 'uniform sampler2D uBaseTexture;', + 'uniform float uBloomThreshold;', + '', + 'void main(void)', + '{', + // Look up the original image color. + ' vec4 color = texture2D(uBaseTexture, vUv0);', + '', + // Adjust it to keep only values brighter than the specified threshold. + ' gl_FragColor = clamp((color - uBloomThreshold) / (1.0 - uBloomThreshold), 0.0, 1.0);', + '}' + ].join('\n'); // Pixel shader applies a one dimensional gaussian blur filter. // This is used twice by the bloom postprocess, first to // blur horizontally, and then again to blur vertically. var gaussianBlurFrag = [ - "#define SAMPLE_COUNT " + SAMPLE_COUNT, - "", - "varying vec2 vUv0;", - "", - "uniform sampler2D uBloomTexture;", - "uniform vec2 uBlurOffsets[" + SAMPLE_COUNT + "];", - "uniform float uBlurWeights[" + SAMPLE_COUNT + "];", - "", - "void main(void)", - "{", - " vec4 color = vec4(0.0);", - // Combine a number of weighted image filter taps. - " for (int i = 0; i < SAMPLE_COUNT; i++)", - " {", - " color += texture2D(uBloomTexture, vUv0 + uBlurOffsets[i]) * uBlurWeights[i];", - " }", - "", - " gl_FragColor = color;", - "}" - ].join("\n"); + `#define SAMPLE_COUNT ${SAMPLE_COUNT}`, + '', + 'varying vec2 vUv0;', + '', + 'uniform sampler2D uBloomTexture;', + `uniform vec2 uBlurOffsets[${SAMPLE_COUNT}];`, + `uniform float uBlurWeights[${SAMPLE_COUNT}];`, + '', + 'void main(void)', + '{', + ' vec4 color = vec4(0.0);', + // Combine a number of weighted image filter taps. + ' for (int i = 0; i < SAMPLE_COUNT; i++)', + ' {', + ' color += texture2D(uBloomTexture, vUv0 + uBlurOffsets[i]) * uBlurWeights[i];', + ' }', + '', + ' gl_FragColor = color;', + '}' + ].join('\n'); // Pixel shader combines the bloom image with the original // scene, using tweakable intensity levels. // This is the final step in applying a bloom postprocess. var combineFrag = [ - "varying vec2 vUv0;", - "", - "uniform float uBloomEffectIntensity;", - "uniform sampler2D uBaseTexture;", - "uniform sampler2D uBloomTexture;", - "", - "void main(void)", - "{", - // Look up the bloom and original base image colors. - " vec4 bloom = texture2D(uBloomTexture, vUv0) * uBloomEffectIntensity;", - " vec4 base = texture2D(uBaseTexture, vUv0);", - "", - // Darken down the base image in areas where there is a lot of bloom, - // to prevent things looking excessively burned-out. - " base *= (1.0 - clamp(bloom, 0.0, 1.0));", - "", - // Combine the two images. - " gl_FragColor = base + bloom;", - "}" - ].join("\n"); + 'varying vec2 vUv0;', + '', + 'uniform float uBloomEffectIntensity;', + 'uniform sampler2D uBaseTexture;', + 'uniform sampler2D uBloomTexture;', + '', + 'void main(void)', + '{', + // Look up the bloom and original base image colors. + ' vec4 bloom = texture2D(uBloomTexture, vUv0) * uBloomEffectIntensity;', + ' vec4 base = texture2D(uBaseTexture, vUv0);', + '', + // Darken down the base image in areas where there is a lot of bloom, + // to prevent things looking excessively burned-out. + ' base *= (1.0 - clamp(bloom, 0.0, 1.0));', + '', + // Combine the two images. + ' gl_FragColor = base + bloom;', + '}' + ].join('\n'); this.extractShader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, extractFrag, 'BloomExtractShader', attributes); this.blurShader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, gaussianBlurFrag, 'BloomBlurShader', attributes); @@ -172,8 +172,9 @@ BloomEffect.prototype._resize = function (target) { var width = target.colorBuffer.width; var height = target.colorBuffer.height; - if (width === this.width && height === this.height) + if (width === this.width && height === this.height) { return; + } this.width = width; this.height = height; @@ -184,7 +185,7 @@ BloomEffect.prototype._resize = function (target) { var i; for (i = 0; i < 2; i++) { var colorBuffer = new pc.Texture(this.device, { - name: "Bloom Texture" + i, + name: `Bloom Texture${i}`, format: pc.PIXELFORMAT_RGBA8, width: width >> 1, height: height >> 1, @@ -194,9 +195,9 @@ BloomEffect.prototype._resize = function (target) { colorBuffer.magFilter = pc.FILTER_LINEAR; colorBuffer.addressU = pc.ADDRESS_CLAMP_TO_EDGE; colorBuffer.addressV = pc.ADDRESS_CLAMP_TO_EDGE; - colorBuffer.name = 'pe-bloom-' + i; + colorBuffer.name = `pe-bloom-${i}`; var bloomTarget = new pc.RenderTarget({ - name: "Bloom Render Target " + i, + name: `Bloom Render Target ${i}`, colorBuffer: colorBuffer, depth: false }); @@ -215,32 +216,32 @@ Object.assign(BloomEffect.prototype, { // Pass 1: draw the scene into rendertarget 1, using a // shader that extracts only the brightest parts of the image. - scope.resolve("uBloomThreshold").setValue(this.bloomThreshold); - scope.resolve("uBaseTexture").setValue(inputTarget.colorBuffer); + scope.resolve('uBloomThreshold').setValue(this.bloomThreshold); + scope.resolve('uBaseTexture').setValue(inputTarget.colorBuffer); this.drawQuad(this.targets[0], this.extractShader); // Pass 2: draw from rendertarget 1 into rendertarget 2, // using a shader to apply a horizontal gaussian blur filter. calculateBlurValues(this.sampleWeights, this.sampleOffsets, 1.0 / this.targets[1].width, 0, this.blurAmount); - scope.resolve("uBlurWeights[0]").setValue(this.sampleWeights); - scope.resolve("uBlurOffsets[0]").setValue(this.sampleOffsets); - scope.resolve("uBloomTexture").setValue(this.targets[0].colorBuffer); + scope.resolve('uBlurWeights[0]').setValue(this.sampleWeights); + scope.resolve('uBlurOffsets[0]').setValue(this.sampleOffsets); + scope.resolve('uBloomTexture').setValue(this.targets[0].colorBuffer); this.drawQuad(this.targets[1], this.blurShader); // Pass 3: draw from rendertarget 2 back into rendertarget 1, // using a shader to apply a vertical gaussian blur filter. calculateBlurValues(this.sampleWeights, this.sampleOffsets, 0, 1.0 / this.targets[0].height, this.blurAmount); - scope.resolve("uBlurWeights[0]").setValue(this.sampleWeights); - scope.resolve("uBlurOffsets[0]").setValue(this.sampleOffsets); - scope.resolve("uBloomTexture").setValue(this.targets[1].colorBuffer); + scope.resolve('uBlurWeights[0]').setValue(this.sampleWeights); + scope.resolve('uBlurOffsets[0]').setValue(this.sampleOffsets); + scope.resolve('uBloomTexture').setValue(this.targets[1].colorBuffer); this.drawQuad(this.targets[0], this.blurShader); // Pass 4: draw both rendertarget 1 and the original scene // image back into the main backbuffer, using a shader that // combines them to produce the final bloomed result. - scope.resolve("uBloomEffectIntensity").setValue(this.bloomIntensity); - scope.resolve("uBloomTexture").setValue(this.targets[0].colorBuffer); - scope.resolve("uBaseTexture").setValue(inputTarget.colorBuffer); + scope.resolve('uBloomEffectIntensity').setValue(this.bloomIntensity); + scope.resolve('uBloomTexture').setValue(this.targets[0].colorBuffer); + scope.resolve('uBaseTexture').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.combineShader, rect); } }); diff --git a/scripts/posteffects/posteffect-bokeh.js b/scripts/posteffects/posteffect-bokeh.js index c44bfff22f8..b74b4e871fe 100644 --- a/scripts/posteffects/posteffect-bokeh.js +++ b/scripts/posteffects/posteffect-bokeh.js @@ -21,80 +21,80 @@ function BokehEffect(graphicsDevice) { // http://artmartinsh.blogspot.com/2010/02/glsl-lens-blur-filter-with-bokeh.html var fshader = [ pc.shaderChunks.screenDepthPS, - "", - "varying vec2 vUv0;", - "", - "uniform sampler2D uColorBuffer;", - "", - "uniform float uMaxBlur;", // max blur amount - "uniform float uAperture;", // uAperture - bigger values for shallower depth of field - "", - "uniform float uFocus;", - "uniform float uAspect;", - "", - "void main()", - "{", - " vec2 aspectCorrect = vec2( 1.0, uAspect );", - "", - " float factor = ((getLinearScreenDepth(vUv0) * -1.0) - uFocus) / camera_params.y;", - "", - " vec2 dofblur = vec2 ( clamp( factor * uAperture, -uMaxBlur, uMaxBlur ) );", - "", - " vec2 dofblur9 = dofblur * 0.9;", - " vec2 dofblur7 = dofblur * 0.7;", - " vec2 dofblur4 = dofblur * 0.4;", - "", - " vec4 col;", - "", - " col = texture2D( uColorBuffer, vUv0 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, 0.4 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, 0.37 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, 0.29 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, 0.15 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.40, 0.0 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, -0.15 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, -0.29 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, -0.37 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, -0.4 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, 0.37 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, 0.29 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, 0.15 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.4, 0.0 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, -0.15 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, -0.29 ) * aspectCorrect ) * dofblur );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, -0.37 ) * aspectCorrect ) * dofblur );", - "", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, 0.37 ) * aspectCorrect ) * dofblur9 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, 0.15 ) * aspectCorrect ) * dofblur9 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, -0.15 ) * aspectCorrect ) * dofblur9 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, -0.37 ) * aspectCorrect ) * dofblur9 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, 0.37 ) * aspectCorrect ) * dofblur9 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, 0.15 ) * aspectCorrect ) * dofblur9 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, -0.15 ) * aspectCorrect ) * dofblur9 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, -0.37 ) * aspectCorrect ) * dofblur9 );", - "", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, 0.29 ) * aspectCorrect ) * dofblur7 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.40, 0.0 ) * aspectCorrect ) * dofblur7 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, -0.29 ) * aspectCorrect ) * dofblur7 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, -0.4 ) * aspectCorrect ) * dofblur7 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, 0.29 ) * aspectCorrect ) * dofblur7 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.4, 0.0 ) * aspectCorrect ) * dofblur7 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, -0.29 ) * aspectCorrect ) * dofblur7 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, 0.4 ) * aspectCorrect ) * dofblur7 );", - "", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, 0.29 ) * aspectCorrect ) * dofblur4 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.4, 0.0 ) * aspectCorrect ) * dofblur4 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, -0.29 ) * aspectCorrect ) * dofblur4 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, -0.4 ) * aspectCorrect ) * dofblur4 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, 0.29 ) * aspectCorrect ) * dofblur4 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.4, 0.0 ) * aspectCorrect ) * dofblur4 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, -0.29 ) * aspectCorrect ) * dofblur4 );", - " col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, 0.4 ) * aspectCorrect ) * dofblur4 );", - "", - " gl_FragColor = col / 41.0;", - " gl_FragColor.a = 1.0;", - "}" - ].join("\n"); + '', + 'varying vec2 vUv0;', + '', + 'uniform sampler2D uColorBuffer;', + '', + 'uniform float uMaxBlur;', // max blur amount + 'uniform float uAperture;', // uAperture - bigger values for shallower depth of field + '', + 'uniform float uFocus;', + 'uniform float uAspect;', + '', + 'void main()', + '{', + ' vec2 aspectCorrect = vec2( 1.0, uAspect );', + '', + ' float factor = ((getLinearScreenDepth(vUv0) * -1.0) - uFocus) / camera_params.y;', + '', + ' vec2 dofblur = vec2 ( clamp( factor * uAperture, -uMaxBlur, uMaxBlur ) );', + '', + ' vec2 dofblur9 = dofblur * 0.9;', + ' vec2 dofblur7 = dofblur * 0.7;', + ' vec2 dofblur4 = dofblur * 0.4;', + '', + ' vec4 col;', + '', + ' col = texture2D( uColorBuffer, vUv0 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, 0.4 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, 0.37 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, 0.29 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, 0.15 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.40, 0.0 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, -0.15 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, -0.29 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, -0.37 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, -0.4 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, 0.37 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, 0.29 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, 0.15 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.4, 0.0 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, -0.15 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, -0.29 ) * aspectCorrect ) * dofblur );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, -0.37 ) * aspectCorrect ) * dofblur );', + '', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, 0.37 ) * aspectCorrect ) * dofblur9 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, 0.15 ) * aspectCorrect ) * dofblur9 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, -0.15 ) * aspectCorrect ) * dofblur9 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, -0.37 ) * aspectCorrect ) * dofblur9 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.15, 0.37 ) * aspectCorrect ) * dofblur9 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.37, 0.15 ) * aspectCorrect ) * dofblur9 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.37, -0.15 ) * aspectCorrect ) * dofblur9 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.15, -0.37 ) * aspectCorrect ) * dofblur9 );', + '', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, 0.29 ) * aspectCorrect ) * dofblur7 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.40, 0.0 ) * aspectCorrect ) * dofblur7 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, -0.29 ) * aspectCorrect ) * dofblur7 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, -0.4 ) * aspectCorrect ) * dofblur7 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, 0.29 ) * aspectCorrect ) * dofblur7 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.4, 0.0 ) * aspectCorrect ) * dofblur7 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, -0.29 ) * aspectCorrect ) * dofblur7 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, 0.4 ) * aspectCorrect ) * dofblur7 );', + '', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, 0.29 ) * aspectCorrect ) * dofblur4 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.4, 0.0 ) * aspectCorrect ) * dofblur4 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.29, -0.29 ) * aspectCorrect ) * dofblur4 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, -0.4 ) * aspectCorrect ) * dofblur4 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, 0.29 ) * aspectCorrect ) * dofblur4 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.4, 0.0 ) * aspectCorrect ) * dofblur4 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( -0.29, -0.29 ) * aspectCorrect ) * dofblur4 );', + ' col += texture2D( uColorBuffer, vUv0 + ( vec2( 0.0, 0.4 ) * aspectCorrect ) * dofblur4 );', + '', + ' gl_FragColor = col / 41.0;', + ' gl_FragColor.a = 1.0;', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'BokehShader', { aPosition: pc.SEMANTIC_POSITION @@ -114,11 +114,11 @@ Object.assign(BokehEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uMaxBlur").setValue(this.maxBlur); - scope.resolve("uAperture").setValue(this.aperture); - scope.resolve("uFocus").setValue(this.focus); - scope.resolve("uAspect").setValue(device.width / device.height); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uMaxBlur').setValue(this.maxBlur); + scope.resolve('uAperture').setValue(this.aperture); + scope.resolve('uFocus').setValue(this.focus); + scope.resolve('uAspect').setValue(device.width / device.height); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.shader, rect); } diff --git a/scripts/posteffects/posteffect-brightnesscontrast.js b/scripts/posteffects/posteffect-brightnesscontrast.js index 036af667665..dd8b82d400f 100644 --- a/scripts/posteffects/posteffect-brightnesscontrast.js +++ b/scripts/posteffects/posteffect-brightnesscontrast.js @@ -14,23 +14,23 @@ function BrightnessContrastEffect(graphicsDevice) { // Shader author: tapio / http://tapio.github.com/ var fshader = [ - "uniform sampler2D uColorBuffer;", - "uniform float uBrightness;", - "uniform float uContrast;", - "", - "varying vec2 vUv0;", - "", - "void main() {", - " gl_FragColor = texture2D( uColorBuffer, vUv0 );", - " gl_FragColor.rgb += uBrightness;", - "", - " if (uContrast > 0.0) {", - " gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - uContrast) + 0.5;", - " } else {", - " gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + uContrast) + 0.5;", - " }", - "}" - ].join("\n"); + 'uniform sampler2D uColorBuffer;', + 'uniform float uBrightness;', + 'uniform float uContrast;', + '', + 'varying vec2 vUv0;', + '', + 'void main() {', + ' gl_FragColor = texture2D( uColorBuffer, vUv0 );', + ' gl_FragColor.rgb += uBrightness;', + '', + ' if (uContrast > 0.0) {', + ' gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - uContrast) + 0.5;', + ' } else {', + ' gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + uContrast) + 0.5;', + ' }', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'BrightnessContrastShader', { aPosition: pc.SEMANTIC_POSITION @@ -49,9 +49,9 @@ Object.assign(BrightnessContrastEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uBrightness").setValue(this.brightness); - scope.resolve("uContrast").setValue(this.contrast); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uBrightness').setValue(this.brightness); + scope.resolve('uContrast').setValue(this.contrast); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-edgedetect.js b/scripts/posteffects/posteffect-edgedetect.js index 2b8af125161..e651d31e81c 100644 --- a/scripts/posteffects/posteffect-edgedetect.js +++ b/scripts/posteffects/posteffect-edgedetect.js @@ -11,46 +11,46 @@ function EdgeDetectEffect(graphicsDevice) { pc.PostEffect.call(this, graphicsDevice); var fshader = [ - "uniform sampler2D uColorBuffer;", - "varying vec2 vUv0;", - "uniform vec2 uResolution;", - "uniform float uIntensity;", - "uniform vec4 uColor;", - "", - "mat3 G[2];", - "", - "const mat3 g0 = mat3( 1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0 );", - "const mat3 g1 = mat3( 1.0, 0.0, -1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0 );", - "", - "void main(void)", - "{", - " mat3 I;", - " float cnv[2];", - " vec3 sample;", - "", - " G[0] = g0;", - " G[1] = g1;", - "", - /* Fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ - " for (float i = 0.0; i < 3.0; i++)", - " {", - " for (float j = 0.0; j < 3.0; j++)", - " {", - " sample = texture2D(uColorBuffer, vUv0 + uResolution * vec2(i - 1.0, j - 1.0)).rgb;", - " I[int(i)][int(j)] = length(sample);", - " }", - " }", - "", - /* Calculate the convolution values for all the masks */ - " for (int i=0; i<2; i++)", - " {", - " float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);", - " cnv[i] = dp3 * dp3; ", - " }", - "", - " gl_FragColor = uIntensity * uColor * vec4(sqrt(cnv[0]*cnv[0]+cnv[1]*cnv[1]));", - "}" - ].join("\n"); + 'uniform sampler2D uColorBuffer;', + 'varying vec2 vUv0;', + 'uniform vec2 uResolution;', + 'uniform float uIntensity;', + 'uniform vec4 uColor;', + '', + 'mat3 G[2];', + '', + 'const mat3 g0 = mat3( 1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0 );', + 'const mat3 g1 = mat3( 1.0, 0.0, -1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0 );', + '', + 'void main(void)', + '{', + ' mat3 I;', + ' float cnv[2];', + ' vec3 sample;', + '', + ' G[0] = g0;', + ' G[1] = g1;', + '', + /* Fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ + ' for (float i = 0.0; i < 3.0; i++)', + ' {', + ' for (float j = 0.0; j < 3.0; j++)', + ' {', + ' sample = texture2D(uColorBuffer, vUv0 + uResolution * vec2(i - 1.0, j - 1.0)).rgb;', + ' I[int(i)][int(j)] = length(sample);', + ' }', + ' }', + '', + /* Calculate the convolution values for all the masks */ + ' for (int i=0; i<2; i++)', + ' {', + ' float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);', + ' cnv[i] = dp3 * dp3; ', + ' }', + '', + ' gl_FragColor = uIntensity * uColor * vec4(sqrt(cnv[0]*cnv[0]+cnv[1]*cnv[1]));', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'EdgeDetectShader', { aPosition: pc.SEMANTIC_POSITION @@ -72,10 +72,10 @@ Object.assign(EdgeDetectEffect.prototype, { this.resolution[0] = 1 / inputTarget.width; this.resolution[1] = 1 / inputTarget.height; - scope.resolve("uResolution").setValue(this.resolution); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); - scope.resolve("uColor").setValue(this.color.data); - scope.resolve("uIntensity").setValue(this.intensity); + scope.resolve('uResolution').setValue(this.resolution); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); + scope.resolve('uColor').setValue(this.color.data); + scope.resolve('uIntensity').setValue(this.intensity); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-fxaa.js b/scripts/posteffects/posteffect-fxaa.js index 99cf90d627c..5c0cc2f6f5d 100644 --- a/scripts/posteffects/posteffect-fxaa.js +++ b/scripts/posteffects/posteffect-fxaa.js @@ -13,62 +13,62 @@ function FxaaEffect(graphicsDevice) { // Shaders // TODO: this shader does not use UV coordinates from vertex shader, and might render upside down on WebGPU. Needs to be fixed. var fxaaFrag = [ - "uniform sampler2D uColorBuffer;", - "uniform vec2 uResolution;", - "", - "#define FXAA_REDUCE_MIN (1.0/128.0)", - "#define FXAA_REDUCE_MUL (1.0/8.0)", - "#define FXAA_SPAN_MAX 8.0", - "", - "void main()", - "{", - " vec3 rgbNW = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( -1.0, -1.0 ) ) * uResolution ).xyz;", - " vec3 rgbNE = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( 1.0, -1.0 ) ) * uResolution ).xyz;", - " vec3 rgbSW = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( -1.0, 1.0 ) ) * uResolution ).xyz;", - " vec3 rgbSE = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( 1.0, 1.0 ) ) * uResolution ).xyz;", - " vec4 rgbaM = texture2D( uColorBuffer, gl_FragCoord.xy * uResolution );", - " vec3 rgbM = rgbaM.xyz;", - " float opacity = rgbaM.w;", - "", - " vec3 luma = vec3( 0.299, 0.587, 0.114 );", - "", - " float lumaNW = dot( rgbNW, luma );", - " float lumaNE = dot( rgbNE, luma );", - " float lumaSW = dot( rgbSW, luma );", - " float lumaSE = dot( rgbSE, luma );", - " float lumaM = dot( rgbM, luma );", - " float lumaMin = min( lumaM, min( min( lumaNW, lumaNE ), min( lumaSW, lumaSE ) ) );", - " float lumaMax = max( lumaM, max( max( lumaNW, lumaNE) , max( lumaSW, lumaSE ) ) );", - "", - " vec2 dir;", - " dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));", - " dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));", - "", - " float dirReduce = max( ( lumaNW + lumaNE + lumaSW + lumaSE ) * ( 0.25 * FXAA_REDUCE_MUL ), FXAA_REDUCE_MIN );", - "", - " float rcpDirMin = 1.0 / ( min( abs( dir.x ), abs( dir.y ) ) + dirReduce );", - " dir = min( vec2( FXAA_SPAN_MAX, FXAA_SPAN_MAX), max( vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), dir * rcpDirMin)) * uResolution;", - "", - " vec3 rgbA = 0.5 * (", - " texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * ( 1.0 / 3.0 - 0.5 ) ).xyz +", - " texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * ( 2.0 / 3.0 - 0.5 ) ).xyz );", - "", - " vec3 rgbB = rgbA * 0.5 + 0.25 * (", - " texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * -0.5 ).xyz +", - " texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * 0.5 ).xyz );", - "", - " float lumaB = dot( rgbB, luma );", - "", - " if ( ( lumaB < lumaMin ) || ( lumaB > lumaMax ) )", - " {", - " gl_FragColor = vec4( rgbA, opacity );", - " }", - " else", - " {", - " gl_FragColor = vec4( rgbB, opacity );", - " }", - "}" - ].join("\n"); + 'uniform sampler2D uColorBuffer;', + 'uniform vec2 uResolution;', + '', + '#define FXAA_REDUCE_MIN (1.0/128.0)', + '#define FXAA_REDUCE_MUL (1.0/8.0)', + '#define FXAA_SPAN_MAX 8.0', + '', + 'void main()', + '{', + ' vec3 rgbNW = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( -1.0, -1.0 ) ) * uResolution ).xyz;', + ' vec3 rgbNE = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( 1.0, -1.0 ) ) * uResolution ).xyz;', + ' vec3 rgbSW = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( -1.0, 1.0 ) ) * uResolution ).xyz;', + ' vec3 rgbSE = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( 1.0, 1.0 ) ) * uResolution ).xyz;', + ' vec4 rgbaM = texture2D( uColorBuffer, gl_FragCoord.xy * uResolution );', + ' vec3 rgbM = rgbaM.xyz;', + ' float opacity = rgbaM.w;', + '', + ' vec3 luma = vec3( 0.299, 0.587, 0.114 );', + '', + ' float lumaNW = dot( rgbNW, luma );', + ' float lumaNE = dot( rgbNE, luma );', + ' float lumaSW = dot( rgbSW, luma );', + ' float lumaSE = dot( rgbSE, luma );', + ' float lumaM = dot( rgbM, luma );', + ' float lumaMin = min( lumaM, min( min( lumaNW, lumaNE ), min( lumaSW, lumaSE ) ) );', + ' float lumaMax = max( lumaM, max( max( lumaNW, lumaNE) , max( lumaSW, lumaSE ) ) );', + '', + ' vec2 dir;', + ' dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));', + ' dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));', + '', + ' float dirReduce = max( ( lumaNW + lumaNE + lumaSW + lumaSE ) * ( 0.25 * FXAA_REDUCE_MUL ), FXAA_REDUCE_MIN );', + '', + ' float rcpDirMin = 1.0 / ( min( abs( dir.x ), abs( dir.y ) ) + dirReduce );', + ' dir = min( vec2( FXAA_SPAN_MAX, FXAA_SPAN_MAX), max( vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), dir * rcpDirMin)) * uResolution;', + '', + ' vec3 rgbA = 0.5 * (', + ' texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * ( 1.0 / 3.0 - 0.5 ) ).xyz +', + ' texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * ( 2.0 / 3.0 - 0.5 ) ).xyz );', + '', + ' vec3 rgbB = rgbA * 0.5 + 0.25 * (', + ' texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * -0.5 ).xyz +', + ' texture2D( uColorBuffer, gl_FragCoord.xy * uResolution + dir * 0.5 ).xyz );', + '', + ' float lumaB = dot( rgbB, luma );', + '', + ' if ( ( lumaB < lumaMin ) || ( lumaB > lumaMax ) )', + ' {', + ' gl_FragColor = vec4( rgbA, opacity );', + ' }', + ' else', + ' {', + ' gl_FragColor = vec4( rgbB, opacity );', + ' }', + '}' + ].join('\n'); this.fxaaShader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fxaaFrag, 'FxaaShader', { aPosition: pc.SEMANTIC_POSITION @@ -88,8 +88,8 @@ Object.assign(FxaaEffect.prototype, { this.resolution[0] = 1 / inputTarget.width; this.resolution[1] = 1 / inputTarget.height; - scope.resolve("uResolution").setValue(this.resolution); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uResolution').setValue(this.resolution); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.fxaaShader, rect); } }); diff --git a/scripts/posteffects/posteffect-horizontaltiltshift.js b/scripts/posteffects/posteffect-horizontaltiltshift.js index edb99fee4ce..6583d693056 100644 --- a/scripts/posteffects/posteffect-horizontaltiltshift.js +++ b/scripts/posteffects/posteffect-horizontaltiltshift.js @@ -13,29 +13,29 @@ function HorizontalTiltShiftEffect(graphicsDevice) { // Shader author: alteredq / http://alteredqualia.com/ var fshader = [ - "uniform sampler2D uColorBuffer;", - "uniform float uH;", - "uniform float uR;", - "", - "varying vec2 vUv0;", - "", - "void main() {", - " vec4 sum = vec4( 0.0 );", - " float hh = uH * abs( uR - vUv0.x );", - "", - " sum += texture2D( uColorBuffer, vec2( vUv0.x - 4.0 * hh, vUv0.y ) ) * 0.051;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x - 3.0 * hh, vUv0.y ) ) * 0.0918;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x - 2.0 * hh, vUv0.y ) ) * 0.12245;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x - 1.0 * hh, vUv0.y ) ) * 0.1531;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y ) ) * 0.1633;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x + 1.0 * hh, vUv0.y ) ) * 0.1531;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x + 2.0 * hh, vUv0.y ) ) * 0.12245;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x + 3.0 * hh, vUv0.y ) ) * 0.0918;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x + 4.0 * hh, vUv0.y ) ) * 0.051;", - "", - " gl_FragColor = sum;", - "}" - ].join("\n"); + 'uniform sampler2D uColorBuffer;', + 'uniform float uH;', + 'uniform float uR;', + '', + 'varying vec2 vUv0;', + '', + 'void main() {', + ' vec4 sum = vec4( 0.0 );', + ' float hh = uH * abs( uR - vUv0.x );', + '', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x - 4.0 * hh, vUv0.y ) ) * 0.051;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x - 3.0 * hh, vUv0.y ) ) * 0.0918;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x - 2.0 * hh, vUv0.y ) ) * 0.12245;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x - 1.0 * hh, vUv0.y ) ) * 0.1531;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y ) ) * 0.1633;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x + 1.0 * hh, vUv0.y ) ) * 0.1531;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x + 2.0 * hh, vUv0.y ) ) * 0.12245;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x + 3.0 * hh, vUv0.y ) ) * 0.0918;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x + 4.0 * hh, vUv0.y ) ) * 0.051;', + '', + ' gl_FragColor = sum;', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'HorizontalTiltShiftShader', { aPosition: pc.SEMANTIC_POSITION @@ -53,9 +53,9 @@ Object.assign(HorizontalTiltShiftEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uH").setValue(1 / inputTarget.width); - scope.resolve("uR").setValue(this.focus); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uH').setValue(1 / inputTarget.width); + scope.resolve('uR').setValue(this.focus); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-huesaturation.js b/scripts/posteffects/posteffect-huesaturation.js index 3e3ab2cf21b..350b37daa18 100644 --- a/scripts/posteffects/posteffect-huesaturation.js +++ b/scripts/posteffects/posteffect-huesaturation.js @@ -14,35 +14,35 @@ function HueSaturationEffect(graphicsDevice) { // Shader author: tapio / http://tapio.github.com/ var fshader = [ - "uniform sampler2D uColorBuffer;", - "uniform float uHue;", - "uniform float uSaturation;", - "", - "varying vec2 vUv0;", - "", - "void main() {", - " gl_FragColor = texture2D( uColorBuffer, vUv0 );", - "", + 'uniform sampler2D uColorBuffer;', + 'uniform float uHue;', + 'uniform float uSaturation;', + '', + 'varying vec2 vUv0;', + '', + 'void main() {', + ' gl_FragColor = texture2D( uColorBuffer, vUv0 );', + '', // uHue - " float angle = uHue * 3.14159265;", - " float s = sin(angle), c = cos(angle);", - " vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;", - " float len = length(gl_FragColor.rgb);", - " gl_FragColor.rgb = vec3(", - " dot(gl_FragColor.rgb, weights.xyz),", - " dot(gl_FragColor.rgb, weights.zxy),", - " dot(gl_FragColor.rgb, weights.yzx)", - " );", - "", + ' float angle = uHue * 3.14159265;', + ' float s = sin(angle), c = cos(angle);', + ' vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;', + ' float len = length(gl_FragColor.rgb);', + ' gl_FragColor.rgb = vec3(', + ' dot(gl_FragColor.rgb, weights.xyz),', + ' dot(gl_FragColor.rgb, weights.zxy),', + ' dot(gl_FragColor.rgb, weights.yzx)', + ' );', + '', // uSaturation - " float average = (gl_FragColor.r + gl_FragColor.g + gl_FragColor.b) / 3.0;", - " if (uSaturation > 0.0) {", - " gl_FragColor.rgb += (average - gl_FragColor.rgb) * (1.0 - 1.0 / (1.001 - uSaturation));", - " } else {", - " gl_FragColor.rgb += (average - gl_FragColor.rgb) * (-uSaturation);", - " }", - "}" - ].join("\n"); + ' float average = (gl_FragColor.r + gl_FragColor.g + gl_FragColor.b) / 3.0;', + ' if (uSaturation > 0.0) {', + ' gl_FragColor.rgb += (average - gl_FragColor.rgb) * (1.0 - 1.0 / (1.001 - uSaturation));', + ' } else {', + ' gl_FragColor.rgb += (average - gl_FragColor.rgb) * (-uSaturation);', + ' }', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'HueSaturationShader', { aPosition: pc.SEMANTIC_POSITION @@ -61,9 +61,9 @@ Object.assign(HueSaturationEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uHue").setValue(this.hue); - scope.resolve("uSaturation").setValue(this.saturation); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uHue').setValue(this.hue); + scope.resolve('uSaturation').setValue(this.saturation); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-luminosity.js b/scripts/posteffects/posteffect-luminosity.js index cf1b9cb0990..65877b39a7a 100644 --- a/scripts/posteffects/posteffect-luminosity.js +++ b/scripts/posteffects/posteffect-luminosity.js @@ -11,17 +11,17 @@ function LuminosityEffect(graphicsDevice) { pc.PostEffect.call(this, graphicsDevice); var fshader = [ - "uniform sampler2D uColorBuffer;", - "", - "varying vec2 vUv0;", - "", - "void main() {", - " vec4 texel = texture2D(uColorBuffer, vUv0);", - " vec3 luma = vec3(0.299, 0.587, 0.114);", - " float v = dot(texel.xyz, luma);", - " gl_FragColor = vec4(v, v, v, texel.w);", - "}" - ].join("\n"); + 'uniform sampler2D uColorBuffer;', + '', + 'varying vec2 vUv0;', + '', + 'void main() {', + ' vec4 texel = texture2D(uColorBuffer, vUv0);', + ' vec3 luma = vec3(0.299, 0.587, 0.114);', + ' float v = dot(texel.xyz, luma);', + ' gl_FragColor = vec4(v, v, v, texel.w);', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'LuminosityShader', { aPosition: pc.SEMANTIC_POSITION @@ -36,7 +36,7 @@ Object.assign(LuminosityEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-outline.js b/scripts/posteffects/posteffect-outline.js index 2c39944702f..41c1b58ebd5 100644 --- a/scripts/posteffects/posteffect-outline.js +++ b/scripts/posteffects/posteffect-outline.js @@ -14,37 +14,37 @@ function OutlineEffect(graphicsDevice, thickness) { pc.PostEffect.call(this, graphicsDevice); var fshader = [ - "#define THICKNESS " + (thickness ? thickness.toFixed(0) : 1), - "uniform float uWidth;", - "uniform float uHeight;", - "uniform vec4 uOutlineCol;", - "uniform sampler2D uColorBuffer;", - "uniform sampler2D uOutlineTex;", - "", - "varying vec2 vUv0;", - "", - "void main(void)", - "{", - " vec4 texel1 = texture2D(uColorBuffer, vUv0);", - " float sample0 = texture2D(uOutlineTex, vUv0).a;", - " float outline = 0.0;", - " if (sample0==0.0)", - " {", - " for (int x=-THICKNESS;x<=THICKNESS;x++)", - " {", - " for (int y=-THICKNESS;y<=THICKNESS;y++)", - " { ", - " float tex=texture2DLodEXT(uOutlineTex, vUv0 + vec2(float(x)/uWidth, float(y)/uHeight), 0.0).a;", - " if (tex>0.0)", - " {", - " outline=1.0;", - " }", - " }", - " } ", - " }", - " gl_FragColor = mix(texel1, uOutlineCol, outline * uOutlineCol.a);", - "}" - ].join("\n"); + `#define THICKNESS ${thickness ? thickness.toFixed(0) : 1}`, + 'uniform float uWidth;', + 'uniform float uHeight;', + 'uniform vec4 uOutlineCol;', + 'uniform sampler2D uColorBuffer;', + 'uniform sampler2D uOutlineTex;', + '', + 'varying vec2 vUv0;', + '', + 'void main(void)', + '{', + ' vec4 texel1 = texture2D(uColorBuffer, vUv0);', + ' float sample0 = texture2D(uOutlineTex, vUv0).a;', + ' float outline = 0.0;', + ' if (sample0==0.0)', + ' {', + ' for (int x=-THICKNESS;x<=THICKNESS;x++)', + ' {', + ' for (int y=-THICKNESS;y<=THICKNESS;y++)', + ' { ', + ' float tex=texture2DLodEXT(uOutlineTex, vUv0 + vec2(float(x)/uWidth, float(y)/uHeight), 0.0).a;', + ' if (tex>0.0)', + ' {', + ' outline=1.0;', + ' }', + ' }', + ' } ', + ' }', + ' gl_FragColor = mix(texel1, uOutlineCol, outline * uOutlineCol.a);', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'OutlineShader', { aPosition: pc.SEMANTIC_POSITION @@ -70,11 +70,11 @@ Object.assign(OutlineEffect.prototype, { this._colorData[2] = this.color.b; this._colorData[3] = this.color.a; - scope.resolve("uWidth").setValue(inputTarget.width); - scope.resolve("uHeight").setValue(inputTarget.height); - scope.resolve("uOutlineCol").setValue(this._colorData); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); - scope.resolve("uOutlineTex").setValue(this.texture); + scope.resolve('uWidth').setValue(inputTarget.width); + scope.resolve('uHeight').setValue(inputTarget.height); + scope.resolve('uOutlineCol').setValue(this._colorData); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); + scope.resolve('uOutlineTex').setValue(this.texture); this.drawQuad(outputTarget, this.shader, rect); } }); @@ -88,14 +88,14 @@ Outline.attributes.add('color', { title: 'Color' }); -Outline.attributes.add("thickness", { - type: "number", +Outline.attributes.add('thickness', { + type: 'number', default: 1.0, min: 1.0, max: 10, precision: 0, - title: "Thickness", - description: "Note: Changing the thickness requires reloading the effect." + title: 'Thickness', + description: 'Note: Changing the thickness requires reloading the effect.' }); Outline.attributes.add('texture', { diff --git a/scripts/posteffects/posteffect-sepia.js b/scripts/posteffects/posteffect-sepia.js index dce9769aa9f..2e05b6e4bec 100644 --- a/scripts/posteffects/posteffect-sepia.js +++ b/scripts/posteffects/posteffect-sepia.js @@ -12,22 +12,22 @@ function SepiaEffect(graphicsDevice) { pc.PostEffect.call(this, graphicsDevice); var fshader = [ - "uniform float uAmount;", - "uniform sampler2D uColorBuffer;", - "", - "varying vec2 vUv0;", - "", - "void main() {", - " vec4 color = texture2D(uColorBuffer, vUv0);", - " vec3 c = color.rgb;", - "", - " color.r = dot(c, vec3(1.0 - 0.607 * uAmount, 0.769 * uAmount, 0.189 * uAmount));", - " color.g = dot(c, vec3(0.349 * uAmount, 1.0 - 0.314 * uAmount, 0.168 * uAmount));", - " color.b = dot(c, vec3(0.272 * uAmount, 0.534 * uAmount, 1.0 - 0.869 * uAmount));", - "", - " gl_FragColor = vec4(min(vec3(1.0), color.rgb), color.a);", - "}" - ].join("\n"); + 'uniform float uAmount;', + 'uniform sampler2D uColorBuffer;', + '', + 'varying vec2 vUv0;', + '', + 'void main() {', + ' vec4 color = texture2D(uColorBuffer, vUv0);', + ' vec3 c = color.rgb;', + '', + ' color.r = dot(c, vec3(1.0 - 0.607 * uAmount, 0.769 * uAmount, 0.189 * uAmount));', + ' color.g = dot(c, vec3(0.349 * uAmount, 1.0 - 0.314 * uAmount, 0.168 * uAmount));', + ' color.b = dot(c, vec3(0.272 * uAmount, 0.534 * uAmount, 1.0 - 0.869 * uAmount));', + '', + ' gl_FragColor = vec4(min(vec3(1.0), color.rgb), color.a);', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'SepiaShader', { aPosition: pc.SEMANTIC_POSITION @@ -45,8 +45,8 @@ Object.assign(SepiaEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uAmount").setValue(this.amount); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uAmount').setValue(this.amount); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-ssao.js b/scripts/posteffects/posteffect-ssao.js index 4f8d7983875..2b6f20038dc 100644 --- a/scripts/posteffects/posteffect-ssao.js +++ b/scripts/posteffects/posteffect-ssao.js @@ -19,298 +19,298 @@ function SSAOEffect(graphicsDevice, ssaoScript) { var fSsao = [ pc.shaderChunks.screenDepthPS, - "", - "varying vec2 vUv0;", - "", - "//uniform sampler2D uColorBuffer;", - "uniform vec4 uResolution;", - "", - "uniform float uAspect;", - "", - "#define saturate(x) clamp(x,0.0,1.0)", - "", - "// Largely based on 'Dominant Light Shadowing'", - "// 'Lighting Technology of The Last of Us Part II' by Hawar Doghramachi, Naughty Dog, LLC", - "", - "const float kSSCTLog2LodRate = 3.0;", - "", - "highp float getWFromProjectionMatrix(const mat4 p, const vec3 v) {", - " // this essentially returns (p * vec4(v, 1.0)).w, but we make some assumptions", - " // this assumes a perspective projection", - " return -v.z;", - " // this assumes a perspective or ortho projection", - " // return p[2][3] * v.z + p[3][3];", - "}", - "", - "highp float getViewSpaceZFromW(const mat4 p, const float w) {", - " // this assumes a perspective projection", - " return -w;", - " // this assumes a perspective or ortho projection", - " // return (w - p[3][3]) / p[2][3];", - "}", - "", - "", - "const float kLog2LodRate = 3.0;", - "", - "vec2 sq(const vec2 a) {", - " return a * a;", - "}", - "", - "uniform float uInvFarPlane;", - "", - "vec2 pack(highp float depth) {", - "// we need 16-bits of precision", - " highp float z = clamp(depth * uInvFarPlane, 0.0, 1.0);", - " highp float t = floor(256.0 * z);", - " mediump float hi = t * (1.0 / 256.0); // we only need 8-bits of precision", - " mediump float lo = (256.0 * z) - t; // we only need 8-bits of precision", - " return vec2(hi, lo);", - "}", - "", - "// random number between 0 and 1, using interleaved gradient noise", - "float random(const highp vec2 w) {", - " const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);", - " return fract(m.z * fract(dot(w, m.xy)));", - "}", - "", - "// returns the frag coord in the GL convention with (0, 0) at the bottom-left", - "highp vec2 getFragCoord() {", - " return gl_FragCoord.xy;", - "}", - "", - "highp vec3 computeViewSpacePositionFromDepth(highp vec2 uv, highp float linearDepth) {", - " return vec3((0.5 - uv) * vec2(uAspect, 1.0) * linearDepth, linearDepth);", - "}", - "", - "highp vec3 faceNormal(highp vec3 dpdx, highp vec3 dpdy) {", - " return normalize(cross(dpdx, dpdy));", - "}", - "", - "// Compute normals using derivatives, which essentially results in half-resolution normals", - "// this creates arifacts around geometry edges.", - "// Note: when using the spirv optimizer, this results in much slower execution time because", - "// this whole expression is inlined in the AO loop below.", - "highp vec3 computeViewSpaceNormal(const highp vec3 position) {", - " return faceNormal(dFdx(position), dFdy(position));", - "}", - "", - "// Compute normals directly from the depth texture, resulting in full resolution normals", - "// Note: This is actually as cheap as using derivatives because the texture fetches", - "// are essentially equivalent to textureGather (which we don't have on ES3.0),", - "// and this is executed just once.", - "highp vec3 computeViewSpaceNormal(const highp vec3 position, const highp vec2 uv) {", - " highp vec2 uvdx = uv + vec2(uResolution.z, 0.0);", - " highp vec2 uvdy = uv + vec2(0.0, uResolution.w);", - " highp vec3 px = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));", - " highp vec3 py = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));", - " highp vec3 dpdx = px - position;", - " highp vec3 dpdy = py - position;", - " return faceNormal(dpdx, dpdy);", - "}", - "", - "// Ambient Occlusion, largely inspired from:", - "// 'The Alchemy Screen-Space Ambient Obscurance Algorithm' by Morgan McGuire", - "// 'Scalable Ambient Obscurance' by Morgan McGuire, Michael Mara and David Luebke", - "", - "uniform vec2 uSampleCount;", - "uniform float uSpiralTurns;", - "", - "#define PI (3.14159)", - "", - "vec3 tapLocation(float i, const float noise) {", - " float offset = ((2.0 * PI) * 2.4) * noise;", - " float angle = ((i * uSampleCount.y) * uSpiralTurns) * (2.0 * PI) + offset;", - " float radius = (i + noise + 0.5) * uSampleCount.y;", - " return vec3(cos(angle), sin(angle), radius * radius);", - "}", - "", - "highp vec2 startPosition(const float noise) {", - " float angle = ((2.0 * PI) * 2.4) * noise;", - " return vec2(cos(angle), sin(angle));", - "}", - "", - "uniform vec2 uAngleIncCosSin;", - "", - "highp mat2 tapAngleStep() {", - " highp vec2 t = uAngleIncCosSin;", - " return mat2(t.x, t.y, -t.y, t.x);", - "}", - "", - "vec3 tapLocationFast(float i, vec2 p, const float noise) {", - " float radius = (i + noise + 0.5) * uSampleCount.y;", - " return vec3(p, radius * radius);", - "}", - "", - "uniform float uMaxLevel;", - "uniform float uInvRadiusSquared;", - "uniform float uMinHorizonAngleSineSquared;", - "uniform float uBias;", - "uniform float uPeak2;", - "", - "void computeAmbientOcclusionSAO(inout float occlusion, float i, float ssDiskRadius,", - " const highp vec2 uv, const highp vec3 origin, const vec3 normal,", - " const vec2 tapPosition, const float noise) {", - "", - " vec3 tap = tapLocationFast(i, tapPosition, noise);", - "", - " float ssRadius = max(1.0, tap.z * ssDiskRadius);", // at least 1 pixel screen-space radius - "", - " vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * uResolution.zw;", - "", - " float level = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, float(uMaxLevel));", - " highp float occlusionDepth = -getLinearScreenDepth(uvSamplePos);", - " highp vec3 p = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);", - "", - " // now we have the sample, compute AO", - " vec3 v = p - origin; // sample vector", - " float vv = dot(v, v); // squared distance", - " float vn = dot(v, normal); // distance * cos(v, normal)", - "", - " // discard samples that are outside of the radius, preventing distant geometry to", - " // cast shadows -- there are many functions that work and choosing one is an artistic", - " // decision.", - " float w = max(0.0, 1.0 - vv * uInvRadiusSquared);", - " w = w*w;", - "", - " // discard samples that are too close to the horizon to reduce shadows cast by geometry", - " // not sufficiently tessellated. The goal is to discard samples that form an angle 'beta'", - " // smaller than 'epsilon' with the horizon. We already have dot(v,n) which is equal to the", - " // sin(beta) * |v|. So the test simplifies to vn^2 < vv * sin(epsilon)^2.", - " w *= step(vv * uMinHorizonAngleSineSquared, vn * vn);", - "", - " occlusion += w * max(0.0, vn + origin.z * uBias) / (vv + uPeak2);", - "}", - "", - "uniform float uProjectionScaleRadius;", - "uniform float uIntensity;", - "", - "float scalableAmbientObscurance(highp vec2 uv, highp vec3 origin, vec3 normal) {", - " float noise = random(getFragCoord());", - " highp vec2 tapPosition = startPosition(noise);", - " highp mat2 angleStep = tapAngleStep();", - "", - " // Choose the screen-space sample radius", - " // proportional to the projected area of the sphere", - " float ssDiskRadius = -(uProjectionScaleRadius / origin.z);", - "", - " float occlusion = 0.0;", - " for (float i = 0.0; i < uSampleCount.x; i += 1.0) {", - " computeAmbientOcclusionSAO(occlusion, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);", - " tapPosition = angleStep * tapPosition;", - " }", - " return sqrt(occlusion * uIntensity);", - "}", - "", - "uniform float uPower;", - "", - "void main() {", - " highp vec2 uv = vUv0; //variable_vertex.xy; // interpolated to pixel center", - "", - " highp float depth = -getLinearScreenDepth(vUv0);", - " highp vec3 origin = computeViewSpacePositionFromDepth(uv, depth);", - " vec3 normal = computeViewSpaceNormal(origin, uv);", - "", - " float occlusion = 0.0;", - "", - " if (uIntensity > 0.0) {", - " occlusion = scalableAmbientObscurance(uv, origin, normal);", - " }", - "", - " // occlusion to visibility", - " float aoVisibility = pow(saturate(1.0 - occlusion), uPower);", - "", - " vec4 inCol = vec4(1.0, 1.0, 1.0, 1.0); //texture2D( uColorBuffer, uv );", - "", - " gl_FragColor.r = aoVisibility; //postProcess.color.rgb = vec3(aoVisibility, pack(origin.z));", - "}", - "", - "void main_old()", - "{", - " vec2 aspectCorrect = vec2( 1.0, uAspect );", - "", - " float depth = getLinearScreenDepth(vUv0);", - " gl_FragColor.r = fract(floor(depth*256.0*256.0)),fract(floor(depth*256.0)),fract(depth);", - "}" - ].join("\n"); + '', + 'varying vec2 vUv0;', + '', + '//uniform sampler2D uColorBuffer;', + 'uniform vec4 uResolution;', + '', + 'uniform float uAspect;', + '', + '#define saturate(x) clamp(x,0.0,1.0)', + '', + '// Largely based on \'Dominant Light Shadowing\'', + '// \'Lighting Technology of The Last of Us Part II\' by Hawar Doghramachi, Naughty Dog, LLC', + '', + 'const float kSSCTLog2LodRate = 3.0;', + '', + 'highp float getWFromProjectionMatrix(const mat4 p, const vec3 v) {', + ' // this essentially returns (p * vec4(v, 1.0)).w, but we make some assumptions', + ' // this assumes a perspective projection', + ' return -v.z;', + ' // this assumes a perspective or ortho projection', + ' // return p[2][3] * v.z + p[3][3];', + '}', + '', + 'highp float getViewSpaceZFromW(const mat4 p, const float w) {', + ' // this assumes a perspective projection', + ' return -w;', + ' // this assumes a perspective or ortho projection', + ' // return (w - p[3][3]) / p[2][3];', + '}', + '', + '', + 'const float kLog2LodRate = 3.0;', + '', + 'vec2 sq(const vec2 a) {', + ' return a * a;', + '}', + '', + 'uniform float uInvFarPlane;', + '', + 'vec2 pack(highp float depth) {', + '// we need 16-bits of precision', + ' highp float z = clamp(depth * uInvFarPlane, 0.0, 1.0);', + ' highp float t = floor(256.0 * z);', + ' mediump float hi = t * (1.0 / 256.0); // we only need 8-bits of precision', + ' mediump float lo = (256.0 * z) - t; // we only need 8-bits of precision', + ' return vec2(hi, lo);', + '}', + '', + '// random number between 0 and 1, using interleaved gradient noise', + 'float random(const highp vec2 w) {', + ' const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);', + ' return fract(m.z * fract(dot(w, m.xy)));', + '}', + '', + '// returns the frag coord in the GL convention with (0, 0) at the bottom-left', + 'highp vec2 getFragCoord() {', + ' return gl_FragCoord.xy;', + '}', + '', + 'highp vec3 computeViewSpacePositionFromDepth(highp vec2 uv, highp float linearDepth) {', + ' return vec3((0.5 - uv) * vec2(uAspect, 1.0) * linearDepth, linearDepth);', + '}', + '', + 'highp vec3 faceNormal(highp vec3 dpdx, highp vec3 dpdy) {', + ' return normalize(cross(dpdx, dpdy));', + '}', + '', + '// Compute normals using derivatives, which essentially results in half-resolution normals', + '// this creates arifacts around geometry edges.', + '// Note: when using the spirv optimizer, this results in much slower execution time because', + '// this whole expression is inlined in the AO loop below.', + 'highp vec3 computeViewSpaceNormal(const highp vec3 position) {', + ' return faceNormal(dFdx(position), dFdy(position));', + '}', + '', + '// Compute normals directly from the depth texture, resulting in full resolution normals', + '// Note: This is actually as cheap as using derivatives because the texture fetches', + '// are essentially equivalent to textureGather (which we don\'t have on ES3.0),', + '// and this is executed just once.', + 'highp vec3 computeViewSpaceNormal(const highp vec3 position, const highp vec2 uv) {', + ' highp vec2 uvdx = uv + vec2(uResolution.z, 0.0);', + ' highp vec2 uvdy = uv + vec2(0.0, uResolution.w);', + ' highp vec3 px = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));', + ' highp vec3 py = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));', + ' highp vec3 dpdx = px - position;', + ' highp vec3 dpdy = py - position;', + ' return faceNormal(dpdx, dpdy);', + '}', + '', + '// Ambient Occlusion, largely inspired from:', + '// \'The Alchemy Screen-Space Ambient Obscurance Algorithm\' by Morgan McGuire', + '// \'Scalable Ambient Obscurance\' by Morgan McGuire, Michael Mara and David Luebke', + '', + 'uniform vec2 uSampleCount;', + 'uniform float uSpiralTurns;', + '', + '#define PI (3.14159)', + '', + 'vec3 tapLocation(float i, const float noise) {', + ' float offset = ((2.0 * PI) * 2.4) * noise;', + ' float angle = ((i * uSampleCount.y) * uSpiralTurns) * (2.0 * PI) + offset;', + ' float radius = (i + noise + 0.5) * uSampleCount.y;', + ' return vec3(cos(angle), sin(angle), radius * radius);', + '}', + '', + 'highp vec2 startPosition(const float noise) {', + ' float angle = ((2.0 * PI) * 2.4) * noise;', + ' return vec2(cos(angle), sin(angle));', + '}', + '', + 'uniform vec2 uAngleIncCosSin;', + '', + 'highp mat2 tapAngleStep() {', + ' highp vec2 t = uAngleIncCosSin;', + ' return mat2(t.x, t.y, -t.y, t.x);', + '}', + '', + 'vec3 tapLocationFast(float i, vec2 p, const float noise) {', + ' float radius = (i + noise + 0.5) * uSampleCount.y;', + ' return vec3(p, radius * radius);', + '}', + '', + 'uniform float uMaxLevel;', + 'uniform float uInvRadiusSquared;', + 'uniform float uMinHorizonAngleSineSquared;', + 'uniform float uBias;', + 'uniform float uPeak2;', + '', + 'void computeAmbientOcclusionSAO(inout float occlusion, float i, float ssDiskRadius,', + ' const highp vec2 uv, const highp vec3 origin, const vec3 normal,', + ' const vec2 tapPosition, const float noise) {', + '', + ' vec3 tap = tapLocationFast(i, tapPosition, noise);', + '', + ' float ssRadius = max(1.0, tap.z * ssDiskRadius);', // at least 1 pixel screen-space radius + '', + ' vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * uResolution.zw;', + '', + ' float level = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, float(uMaxLevel));', + ' highp float occlusionDepth = -getLinearScreenDepth(uvSamplePos);', + ' highp vec3 p = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);', + '', + ' // now we have the sample, compute AO', + ' vec3 v = p - origin; // sample vector', + ' float vv = dot(v, v); // squared distance', + ' float vn = dot(v, normal); // distance * cos(v, normal)', + '', + ' // discard samples that are outside of the radius, preventing distant geometry to', + ' // cast shadows -- there are many functions that work and choosing one is an artistic', + ' // decision.', + ' float w = max(0.0, 1.0 - vv * uInvRadiusSquared);', + ' w = w*w;', + '', + ' // discard samples that are too close to the horizon to reduce shadows cast by geometry', + ' // not sufficiently tessellated. The goal is to discard samples that form an angle \'beta\'', + ' // smaller than \'epsilon\' with the horizon. We already have dot(v,n) which is equal to the', + ' // sin(beta) * |v|. So the test simplifies to vn^2 < vv * sin(epsilon)^2.', + ' w *= step(vv * uMinHorizonAngleSineSquared, vn * vn);', + '', + ' occlusion += w * max(0.0, vn + origin.z * uBias) / (vv + uPeak2);', + '}', + '', + 'uniform float uProjectionScaleRadius;', + 'uniform float uIntensity;', + '', + 'float scalableAmbientObscurance(highp vec2 uv, highp vec3 origin, vec3 normal) {', + ' float noise = random(getFragCoord());', + ' highp vec2 tapPosition = startPosition(noise);', + ' highp mat2 angleStep = tapAngleStep();', + '', + ' // Choose the screen-space sample radius', + ' // proportional to the projected area of the sphere', + ' float ssDiskRadius = -(uProjectionScaleRadius / origin.z);', + '', + ' float occlusion = 0.0;', + ' for (float i = 0.0; i < uSampleCount.x; i += 1.0) {', + ' computeAmbientOcclusionSAO(occlusion, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);', + ' tapPosition = angleStep * tapPosition;', + ' }', + ' return sqrt(occlusion * uIntensity);', + '}', + '', + 'uniform float uPower;', + '', + 'void main() {', + ' highp vec2 uv = vUv0; //variable_vertex.xy; // interpolated to pixel center', + '', + ' highp float depth = -getLinearScreenDepth(vUv0);', + ' highp vec3 origin = computeViewSpacePositionFromDepth(uv, depth);', + ' vec3 normal = computeViewSpaceNormal(origin, uv);', + '', + ' float occlusion = 0.0;', + '', + ' if (uIntensity > 0.0) {', + ' occlusion = scalableAmbientObscurance(uv, origin, normal);', + ' }', + '', + ' // occlusion to visibility', + ' float aoVisibility = pow(saturate(1.0 - occlusion), uPower);', + '', + ' vec4 inCol = vec4(1.0, 1.0, 1.0, 1.0); //texture2D( uColorBuffer, uv );', + '', + ' gl_FragColor.r = aoVisibility; //postProcess.color.rgb = vec3(aoVisibility, pack(origin.z));', + '}', + '', + 'void main_old()', + '{', + ' vec2 aspectCorrect = vec2( 1.0, uAspect );', + '', + ' float depth = getLinearScreenDepth(vUv0);', + ' gl_FragColor.r = fract(floor(depth*256.0*256.0)),fract(floor(depth*256.0)),fract(depth);', + '}' + ].join('\n'); var fblur = [ pc.shaderChunks.screenDepthPS, - "", - "varying vec2 vUv0;", - "", - "uniform sampler2D uSSAOBuffer;", - "uniform vec4 uResolution;", - "", - "uniform float uAspect;", - "", - "uniform int uBilatSampleCount;", - "uniform float uFarPlaneOverEdgeDistance;", - "uniform float uBrightness;", - "", - "float random(const highp vec2 w) {", - " const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);", - " return fract(m.z * fract(dot(w, m.xy)));", - "}", - "", - "float bilateralWeight(in float depth, in float sampleDepth) {", - " float diff = (sampleDepth - depth) * uFarPlaneOverEdgeDistance;", - " return max(0.0, 1.0 - diff * diff);", - "}", - "", - "void tap(inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {", - " // ambient occlusion sample", - " float ssao = texture2D( uSSAOBuffer, position ).r;", - " float tdepth = -getLinearScreenDepth( position );", - "", - " // bilateral sample", - " float bilateral = bilateralWeight(depth, tdepth);", - - " bilateral *= weight;", - " sum += ssao * bilateral;", - " totalWeight += bilateral;", - "}", - "", - "void main() {", - " highp vec2 uv = vUv0; // variable_vertex.xy; // interpolated at pixel's center", - "", - " // we handle the center pixel separately because it doesn't participate in bilateral filtering", - " float depth = -getLinearScreenDepth(vUv0); // unpack(data.gb);", - " float totalWeight = 0.0; // float(uBilatSampleCount*2+1)*float(uBilatSampleCount*2+1);", - " float ssao = texture2D( uSSAOBuffer, vUv0 ).r;", - " float sum = ssao * totalWeight;", - "", - " for (int x = -uBilatSampleCount; x <= uBilatSampleCount; x++) {", - " for (int y = -uBilatSampleCount; y < uBilatSampleCount; y++) {", - " float weight = 1.0;", - " vec2 offset = vec2(x,y)*uResolution.zw;", - " tap(sum, totalWeight, weight, depth, uv + offset);", - " }", - " }", - "", - " float ao = sum / totalWeight;", - "", - " // simple dithering helps a lot (assumes 8 bits target)", - " // this is most useful with high quality/large blurs", - " // ao += ((random(gl_FragCoord.xy) - 0.5) / 255.0);", - "", - " ao = mix(ao, 1.0, uBrightness);", - " gl_FragColor.a = ao;", - "}" - ].join("\n"); + '', + 'varying vec2 vUv0;', + '', + 'uniform sampler2D uSSAOBuffer;', + 'uniform vec4 uResolution;', + '', + 'uniform float uAspect;', + '', + 'uniform int uBilatSampleCount;', + 'uniform float uFarPlaneOverEdgeDistance;', + 'uniform float uBrightness;', + '', + 'float random(const highp vec2 w) {', + ' const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);', + ' return fract(m.z * fract(dot(w, m.xy)));', + '}', + '', + 'float bilateralWeight(in float depth, in float sampleDepth) {', + ' float diff = (sampleDepth - depth) * uFarPlaneOverEdgeDistance;', + ' return max(0.0, 1.0 - diff * diff);', + '}', + '', + 'void tap(inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {', + ' // ambient occlusion sample', + ' float ssao = texture2D( uSSAOBuffer, position ).r;', + ' float tdepth = -getLinearScreenDepth( position );', + '', + ' // bilateral sample', + ' float bilateral = bilateralWeight(depth, tdepth);', + + ' bilateral *= weight;', + ' sum += ssao * bilateral;', + ' totalWeight += bilateral;', + '}', + '', + 'void main() {', + ' highp vec2 uv = vUv0; // variable_vertex.xy; // interpolated at pixel\'s center', + '', + ' // we handle the center pixel separately because it doesn\'t participate in bilateral filtering', + ' float depth = -getLinearScreenDepth(vUv0); // unpack(data.gb);', + ' float totalWeight = 0.0; // float(uBilatSampleCount*2+1)*float(uBilatSampleCount*2+1);', + ' float ssao = texture2D( uSSAOBuffer, vUv0 ).r;', + ' float sum = ssao * totalWeight;', + '', + ' for (int x = -uBilatSampleCount; x <= uBilatSampleCount; x++) {', + ' for (int y = -uBilatSampleCount; y < uBilatSampleCount; y++) {', + ' float weight = 1.0;', + ' vec2 offset = vec2(x,y)*uResolution.zw;', + ' tap(sum, totalWeight, weight, depth, uv + offset);', + ' }', + ' }', + '', + ' float ao = sum / totalWeight;', + '', + ' // simple dithering helps a lot (assumes 8 bits target)', + ' // this is most useful with high quality/large blurs', + ' // ao += ((random(gl_FragCoord.xy) - 0.5) / 255.0);', + '', + ' ao = mix(ao, 1.0, uBrightness);', + ' gl_FragColor.a = ao;', + '}' + ].join('\n'); var foutput = [ - "varying vec2 vUv0;", - "uniform sampler2D uColorBuffer;", - "uniform sampler2D uSSAOBuffer;", - "", - "void main(void)", - "{", - " vec4 inCol = texture2D( uColorBuffer, vUv0 );", - " float ssao = texture2D( uSSAOBuffer, vUv0 ).a;", - " gl_FragColor.rgb = inCol.rgb * ssao;", - " gl_FragColor.a = inCol.a;", - "}" - ].join("\n"); + 'varying vec2 vUv0;', + 'uniform sampler2D uColorBuffer;', + 'uniform sampler2D uSSAOBuffer;', + '', + 'void main(void)', + '{', + ' vec4 inCol = texture2D( uColorBuffer, vUv0 );', + ' float ssao = texture2D( uSSAOBuffer, vUv0 ).a;', + ' gl_FragColor.rgb = inCol.rgb * ssao;', + ' gl_FragColor.a = inCol.a;', + '}' + ].join('\n'); var attributes = { aPosition: pc.SEMANTIC_POSITION @@ -351,8 +351,9 @@ SSAOEffect.prototype._resize = function (target) { var height = Math.ceil(target.colorBuffer.height / this.downscale); // If no change, skip resize - if (width === this.width && height === this.height) + if (width === this.width && height === this.height) { return; + } // Render targets this.width = width; @@ -372,7 +373,7 @@ SSAOEffect.prototype._resize = function (target) { }); ssaoResultBuffer.name = 'SSAO Result'; this.target = new pc.RenderTarget({ - name: "SSAO Result Render Target", + name: 'SSAO Result Render Target', colorBuffer: ssaoResultBuffer, depth: false }); @@ -389,7 +390,7 @@ SSAOEffect.prototype._resize = function (target) { }); ssaoBlurBuffer.name = 'SSAO Blur'; this.blurTarget = new pc.RenderTarget({ - name: "SSAO Blur Render Target", + name: 'SSAO Blur Render Target', colorBuffer: ssaoBlurBuffer, depth: false }); @@ -414,36 +415,36 @@ Object.assign(SSAOEffect.prototype, { var projectionScale = 0.5 * device.height; var cameraFarClip = this.ssaoScript.entity.camera.farClip; - scope.resolve("uAspect").setValue(this.width / this.height); - scope.resolve("uResolution").setValue([this.width, this.height, 1.0 / this.width, 1.0 / this.height]); - scope.resolve("uBrightness").setValue(this.brightness); - - scope.resolve("uInvFarPlane").setValue(1.0 / cameraFarClip); - scope.resolve("uSampleCount").setValue([sampleCount, 1.0 / sampleCount]); - scope.resolve("uSpiralTurns").setValue(spiralTurns); - scope.resolve("uAngleIncCosSin").setValue([Math.cos(step), Math.sin(step)]); - scope.resolve("uMaxLevel").setValue(0.0); - scope.resolve("uInvRadiusSquared").setValue(1.0 / (radius * radius)); - scope.resolve("uMinHorizonAngleSineSquared").setValue(0.0); - scope.resolve("uBias").setValue(bias); - scope.resolve("uPeak2").setValue(peak * peak); - scope.resolve("uIntensity").setValue(intensity); - scope.resolve("uPower").setValue(1.0); - scope.resolve("uProjectionScaleRadius").setValue(projectionScale * radius); + scope.resolve('uAspect').setValue(this.width / this.height); + scope.resolve('uResolution').setValue([this.width, this.height, 1.0 / this.width, 1.0 / this.height]); + scope.resolve('uBrightness').setValue(this.brightness); + + scope.resolve('uInvFarPlane').setValue(1.0 / cameraFarClip); + scope.resolve('uSampleCount').setValue([sampleCount, 1.0 / sampleCount]); + scope.resolve('uSpiralTurns').setValue(spiralTurns); + scope.resolve('uAngleIncCosSin').setValue([Math.cos(step), Math.sin(step)]); + scope.resolve('uMaxLevel').setValue(0.0); + scope.resolve('uInvRadiusSquared').setValue(1.0 / (radius * radius)); + scope.resolve('uMinHorizonAngleSineSquared').setValue(0.0); + scope.resolve('uBias').setValue(bias); + scope.resolve('uPeak2').setValue(peak * peak); + scope.resolve('uIntensity').setValue(intensity); + scope.resolve('uPower').setValue(1.0); + scope.resolve('uProjectionScaleRadius').setValue(projectionScale * radius); // Render SSAO this.drawQuad(this.target, this.ssaoShader, rect); - scope.resolve("uSSAOBuffer").setValue(this.target.colorBuffer); - scope.resolve("uFarPlaneOverEdgeDistance").setValue(1); - scope.resolve("uBilatSampleCount").setValue(4); + scope.resolve('uSSAOBuffer').setValue(this.target.colorBuffer); + scope.resolve('uFarPlaneOverEdgeDistance').setValue(1); + scope.resolve('uBilatSampleCount').setValue(4); // Perform the blur this.drawQuad(this.blurTarget, this.blurShader, rect); // Finally output to screen - scope.resolve("uSSAOBuffer").setValue(this.blurTarget.colorBuffer); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uSSAOBuffer').setValue(this.blurTarget.colorBuffer); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.outputShader, rect); } }); @@ -480,7 +481,7 @@ SSAO.attributes.add('downscale', { default: 1, min: 1, max: 4, - title: "Downscale" + title: 'Downscale' }); SSAO.prototype.initialize = function () { diff --git a/scripts/posteffects/posteffect-verticaltiltshift.js b/scripts/posteffects/posteffect-verticaltiltshift.js index 1d71127b57b..203fec6d4a4 100644 --- a/scripts/posteffects/posteffect-verticaltiltshift.js +++ b/scripts/posteffects/posteffect-verticaltiltshift.js @@ -13,29 +13,29 @@ function VerticalTiltShiftEffect(graphicsDevice) { // Shader author: alteredq / http://alteredqualia.com/ var fshader = [ - "uniform sampler2D uColorBuffer;", - "uniform float uV;", - "uniform float uR;", - "", - "varying vec2 vUv0;", - "", - "void main() {", - " vec4 sum = vec4( 0.0 );", - " float vv = uV * abs( uR - vUv0.y );", - "", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 4.0 * vv ) ) * 0.051;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 3.0 * vv ) ) * 0.0918;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 2.0 * vv ) ) * 0.12245;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 1.0 * vv ) ) * 0.1531;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y ) ) * 0.1633;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 1.0 * vv ) ) * 0.1531;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 2.0 * vv ) ) * 0.12245;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 3.0 * vv ) ) * 0.0918;", - " sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 4.0 * vv ) ) * 0.051;", - "", - " gl_FragColor = sum;", - "}" - ].join("\n"); + 'uniform sampler2D uColorBuffer;', + 'uniform float uV;', + 'uniform float uR;', + '', + 'varying vec2 vUv0;', + '', + 'void main() {', + ' vec4 sum = vec4( 0.0 );', + ' float vv = uV * abs( uR - vUv0.y );', + '', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 4.0 * vv ) ) * 0.051;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 3.0 * vv ) ) * 0.0918;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 2.0 * vv ) ) * 0.12245;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 1.0 * vv ) ) * 0.1531;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y ) ) * 0.1633;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 1.0 * vv ) ) * 0.1531;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 2.0 * vv ) ) * 0.12245;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 3.0 * vv ) ) * 0.0918;', + ' sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 4.0 * vv ) ) * 0.051;', + '', + ' gl_FragColor = sum;', + '}' + ].join('\n'); this.shader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fshader, 'VerticalTiltShiftShader', { aPosition: pc.SEMANTIC_POSITION @@ -53,9 +53,9 @@ Object.assign(VerticalTiltShiftEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uV").setValue(1 / inputTarget.height); - scope.resolve("uR").setValue(this.focus); - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); + scope.resolve('uV').setValue(1 / inputTarget.height); + scope.resolve('uR').setValue(this.focus); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.shader, rect); } }); diff --git a/scripts/posteffects/posteffect-vignette.js b/scripts/posteffects/posteffect-vignette.js index 93e7d744fe1..e4e8863f5e4 100644 --- a/scripts/posteffects/posteffect-vignette.js +++ b/scripts/posteffects/posteffect-vignette.js @@ -14,18 +14,18 @@ function VignetteEffect(graphicsDevice) { // Shaders var luminosityFrag = [ - "uniform sampler2D uColorBuffer;", - "uniform float uDarkness;", - "uniform float uOffset;", - "", - "varying vec2 vUv0;", - "", - "void main() {", - " vec4 texel = texture2D(uColorBuffer, vUv0);", - " vec2 uv = (vUv0 - vec2(0.5)) * vec2(uOffset);", - " gl_FragColor = vec4(mix(texel.rgb, vec3(1.0 - uDarkness), dot(uv, uv)), texel.a);", - "}" - ].join("\n"); + 'uniform sampler2D uColorBuffer;', + 'uniform float uDarkness;', + 'uniform float uOffset;', + '', + 'varying vec2 vUv0;', + '', + 'void main() {', + ' vec4 texel = texture2D(uColorBuffer, vUv0);', + ' vec2 uv = (vUv0 - vec2(0.5)) * vec2(uOffset);', + ' gl_FragColor = vec4(mix(texel.rgb, vec3(1.0 - uDarkness), dot(uv, uv)), texel.a);', + '}' + ].join('\n'); this.vignetteShader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, luminosityFrag, 'VignetteShader', { aPosition: pc.SEMANTIC_POSITION @@ -43,9 +43,9 @@ Object.assign(VignetteEffect.prototype, { var device = this.device; var scope = device.scope; - scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); - scope.resolve("uOffset").setValue(this.offset); - scope.resolve("uDarkness").setValue(this.darkness); + scope.resolve('uColorBuffer').setValue(inputTarget.colorBuffer); + scope.resolve('uOffset').setValue(this.offset); + scope.resolve('uDarkness').setValue(this.darkness); this.drawQuad(outputTarget, this.vignetteShader, rect); } }); diff --git a/scripts/textmesh/text-mesh.js b/scripts/textmesh/text-mesh.js index 42b0299402e..612befa6310 100644 --- a/scripts/textmesh/text-mesh.js +++ b/scripts/textmesh/text-mesh.js @@ -297,7 +297,7 @@ TextMesh.prototype.parseCommands = function (commands) { const p1 = poly.points[i]; const p2 = poly.points[i + 1]; vertices.push(p1.x * scalar, p1.y * scalar, this.depth, p2.x * scalar, p2.y * scalar, this.depth, - p1.x * scalar, p1.y * scalar, 0, p2.x * scalar, p2.y * scalar, 0); + p1.x * scalar, p1.y * scalar, 0, p2.x * scalar, p2.y * scalar, 0); indices.push(base, base + 1, base + 2, base + 1, base + 3, base + 2); } }); @@ -329,7 +329,7 @@ TextMesh.prototype.calculateWidth = function () { TextMesh.prototype.destroyCharacters = function () { // Destroy all existing characters - this.characters.forEach(function (character) { + this.characters.forEach((character) => { character.destroy(); }); this.characters.length = 0; diff --git a/scripts/utils/cubemap-renderer.js b/scripts/utils/cubemap-renderer.js index 2ddd66f94a7..782c96ec9df 100644 --- a/scripts/utils/cubemap-renderer.js +++ b/scripts/utils/cubemap-renderer.js @@ -34,7 +34,7 @@ CubemapRenderer.prototype.initialize = function () { // this entity needs to have camera component as well var camera = this.entity.camera; if (!camera) { - console.error("CubemapRenderer component requires Camera component to be created on the Entity."); + console.error('CubemapRenderer component requires Camera component to be created on the Entity.'); return; } @@ -46,7 +46,7 @@ CubemapRenderer.prototype.initialize = function () { // Create cubemap render target with specified resolution and mipmap generation this.cubeMap = new pc.Texture(this.app.graphicsDevice, { - name: this.entity.name + ':CubemapRenderer-' + resolution, + name: `${this.entity.name}:CubemapRenderer-${resolution}`, width: resolution, height: resolution, format: pc.PIXELFORMAT_SRGBA8, @@ -71,7 +71,7 @@ CubemapRenderer.prototype.initialize = function () { // render target, connected to cubemap texture face var renderTarget = new pc.RenderTarget({ - name: 'CubemapRenderer-Face' + i, + name: `CubemapRenderer-Face${i}`, colorBuffer: this.cubeMap, depth: this.depth, face: i, @@ -79,7 +79,7 @@ CubemapRenderer.prototype.initialize = function () { }); // create a child entity with the camera for this face - var e = new pc.Entity("CubeMapCamera_" + i); + var e = new pc.Entity(`CubeMapCamera_${i}`); e.addComponent('camera', { aspectRatio: 1, fov: 90, diff --git a/scripts/utils/download-texture.js b/scripts/utils/download-texture.js index c9200a0b720..bfc4bc3ded1 100644 --- a/scripts/utils/download-texture.js +++ b/scripts/utils/download-texture.js @@ -3,7 +3,7 @@ // Taken from https://rawgit.com/zholos/js_bitmap/master/bitmap.js function constructPngUrl(data, width, height) { var row = function (data, width, y) { - var result = "\0"; + var result = '\0'; var r = y * width * 4; for (var x = 0; x < width; x++) { result += String.fromCharCode(data[r], data[r + 1], data[r + 2], data[r + 3]); @@ -13,9 +13,10 @@ function constructPngUrl(data, width, height) { }; var rows = function (data, width, height) { - var result = ""; - for (var y = 0; y < height; y++) + var result = ''; + for (var y = 0; y < height; y++) { result += row(data, width, y); + } return result; }; @@ -33,7 +34,7 @@ function constructPngUrl(data, width, height) { }; var deflate = function (data) { - var compressed = "\x78\x01"; + var compressed = '\x78\x01'; var i = 0; do { var block = data.slice(i, i + 65535); @@ -48,9 +49,11 @@ function constructPngUrl(data, width, height) { var crc32 = function (data) { var c = ~0; - for (var i = 0; i < data.length; i++) - for (var b = data.charCodeAt(i) | 0x100; b !== 1; b >>>= 1) + for (var i = 0; i < data.length; i++) { + for (var b = data.charCodeAt(i) | 0x100; b !== 1; b >>>= 1) { c = (c >>> 1) ^ ((c ^ b) & 1 ? 0xedb88320 : 0); + } + } return ~c; }; @@ -58,12 +61,12 @@ function constructPngUrl(data, width, height) { return hton(data.length) + type + data + hton(crc32(type + data)); }; - var png = "\x89PNG\r\n\x1a\n" + - chunk("IHDR", hton(width) + hton(height) + "\x08\x06\0\0\0") + - chunk("IDAT", deflate(rows(data, width, height))) + - chunk("IEND", ""); + var png = `\x89PNG\r\n\x1a\n${ + chunk('IHDR', `${hton(width) + hton(height)}\x08\x06\0\0\0`) + }${chunk('IDAT', deflate(rows(data, width, height))) + }${chunk('IEND', '')}`; - return "data:image/png;base64," + btoa(png); + return `data:image/png;base64,${btoa(png)}`; } // Construct a PNG using canvas API. This function is much faster than the manual approach, @@ -76,7 +79,7 @@ var constructPngUrlOld = function (data, width, height) { // eslint-disabl var context = canvas.getContext('2d'); context.putImageData(new ImageData(data, width, height), 0, 0); - return canvas.toDataURL("image/png"); + return canvas.toDataURL('image/png'); }; // download the data uri @@ -87,14 +90,14 @@ function download(url, filename) { // create a "fake" click-event to trigger the download if (document.createEvent) { - var e = document.createEvent("MouseEvents"); - e.initMouseEvent("click", true, true, window, - 0, 0, 0, 0, 0, false, false, false, - false, 0, null); + var e = document.createEvent('MouseEvents'); + e.initMouseEvent('click', true, true, window, + 0, 0, 0, 0, 0, false, false, false, + false, 0, null); lnk.dispatchEvent(e); } else if (lnk.fireEvent) { - lnk.fireEvent("onclick"); + lnk.fireEvent('onclick'); } } diff --git a/scripts/utils/planar-renderer.js b/scripts/utils/planar-renderer.js index c5da419229e..c979c923384 100644 --- a/scripts/utils/planar-renderer.js +++ b/scripts/utils/planar-renderer.js @@ -55,14 +55,14 @@ PlanarRenderer.prototype.initialize = function () { // sceneCameraEntity needs to be set var sceneCamera = this.sceneCameraEntity.camera; if (!sceneCamera) { - console.error("PlanarRenderer component requires cameraEntity attribute to be set."); + console.error('PlanarRenderer component requires cameraEntity attribute to be set.'); return; } // this entity needs to have camera component as well var planarCamera = this.entity.camera; if (!planarCamera) { - console.error("PlanarRenderer component requires a camera component on the same entity."); + console.error('PlanarRenderer component requires a camera component on the same entity.'); return; } @@ -99,7 +99,7 @@ PlanarRenderer.prototype.updateRenderTarget = function () { // Create texture render target with specified resolution and mipmap generation this.texture = new pc.Texture(this.app.graphicsDevice, { - name: this.entity.name + ':PlanarRenderer-', + name: `${this.entity.name}:PlanarRenderer-`, width: width, height: height, format: pc.PIXELFORMAT_SRGBA8, diff --git a/src/core/constants.js b/src/core/constants.js index 7dd5392065a..4c56f7c375a 100644 --- a/src/core/constants.js +++ b/src/core/constants.js @@ -149,7 +149,7 @@ export const TRACEID_PIPELINELAYOUT_ALLOC = 'PipelineLayoutAlloc'; * @type {string} * @category Debug */ -export const TRACE_ID_ELEMENT = "Element"; +export const TRACE_ID_ELEMENT = 'Element'; /** * Logs the vram use by all textures in memory. diff --git a/src/core/debug.js b/src/core/debug.js index 9a7dbbfa1e6..5b213f0fd59 100644 --- a/src/core/debug.js +++ b/src/core/debug.js @@ -1,4 +1,4 @@ -import { Tracing } from "./tracing.js"; +import { Tracing } from './tracing.js'; /** * Engine debug log system. Note that the logging only executes in the debug build of the engine, @@ -21,7 +21,7 @@ class Debug { static deprecated(message) { if (!Debug._loggedMessages.has(message)) { Debug._loggedMessages.add(message); - console.warn('DEPRECATED: ' + message); + console.warn(`DEPRECATED: ${message}`); } } diff --git a/src/core/event-handler.js b/src/core/event-handler.js index 721330c56ed..be1f6d10c18 100644 --- a/src/core/event-handler.js +++ b/src/core/event-handler.js @@ -65,12 +65,14 @@ class EventHandler { */ _addCallback(name, callback, scope, once) { // #if _DEBUG - if (!name || typeof name !== 'string' || !callback) + if (!name || typeof name !== 'string' || !callback) { console.warn(`EventHandler: subscribing to an event (${name}) with missing arguments`, callback); + } // #endif - if (!this._callbacks.has(name)) + if (!this._callbacks.has(name)) { this._callbacks.set(name, []); + } // if we are adding a callback to the list that is executing right now // ensure we preserve initial list before modifications @@ -153,17 +155,20 @@ class EventHandler { if (name) { // if we are removing a callback from the list that is executing right now // ensure we preserve initial list before modifications - if (this._callbackActive.has(name) && this._callbackActive.get(name) === this._callbacks.get(name)) + if (this._callbackActive.has(name) && this._callbackActive.get(name) === this._callbacks.get(name)) { this._callbackActive.set(name, this._callbackActive.get(name).slice()); + } } else { // if we are removing a callback from any list that is executing right now // ensure we preserve these initial lists before modifications for (const [key, callbacks] of this._callbackActive) { - if (!this._callbacks.has(key)) + if (!this._callbacks.has(key)) { continue; + } - if (this._callbacks.get(key) !== callbacks) + if (this._callbacks.get(key) !== callbacks) { continue; + } this._callbackActive.set(key, callbacks.slice()); } @@ -188,25 +193,29 @@ class EventHandler { } } else { const callbacks = this._callbacks.get(name); - if (!callbacks) + if (!callbacks) { return this; + } for (let i = 0; i < callbacks.length; i++) { // remove all events with a specific name and a callback - if (callbacks[i].callback !== callback) + if (callbacks[i].callback !== callback) { continue; + } // could be a specific scope as well - if (scope && callbacks[i].scope !== scope) + if (scope && callbacks[i].scope !== scope) { continue; + } callbacks[i].removed = true; callbacks.splice(i, 1); i--; } - if (callbacks.length === 0) + if (callbacks.length === 0) { this._callbacks.delete(name); + } } return this; @@ -229,12 +238,14 @@ class EventHandler { * obj.fire('test', 'This is the message'); */ fire(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) { - if (!name) + if (!name) { return this; + } const callbacksInitial = this._callbacks.get(name); - if (!callbacksInitial) + if (!callbacksInitial) { return this; + } let callbacks; @@ -261,22 +272,25 @@ class EventHandler { const ind = existingCallback ? existingCallback.indexOf(evt) : -1; if (ind !== -1) { - if (this._callbackActive.get(name) === existingCallback) + if (this._callbackActive.get(name) === existingCallback) { this._callbackActive.set(name, this._callbackActive.get(name).slice()); + } const callbacks = this._callbacks.get(name); if (!callbacks) continue; callbacks[ind].removed = true; callbacks.splice(ind, 1); - if (callbacks.length === 0) + if (callbacks.length === 0) { this._callbacks.delete(name); + } } } } - if (!callbacks) + if (!callbacks) { this._callbackActive.delete(name); + } return this; } diff --git a/src/core/guid.js b/src/core/guid.js index 113d2897a84..968960e3e73 100644 --- a/src/core/guid.js +++ b/src/core/guid.js @@ -11,7 +11,7 @@ const guid = { * @returns {string} A new GUID. */ create() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = (c === 'x') ? r : (r & 0x3 | 0x8); return v.toString(16); diff --git a/src/core/indexed-list.js b/src/core/indexed-list.js index d88f42dbd65..84c47efd29f 100644 --- a/src/core/indexed-list.js +++ b/src/core/indexed-list.js @@ -24,7 +24,7 @@ class IndexedList { */ push(key, item) { if (this._index[key]) { - throw Error('Key already in index ' + key); + throw Error(`Key already in index ${key}`); } const location = this._list.push(item) - 1; this._index[key] = location; diff --git a/src/core/math/blue-noise.js b/src/core/math/blue-noise.js index 23d0099838a..b2be200dbc2 100644 --- a/src/core/math/blue-noise.js +++ b/src/core/math/blue-noise.js @@ -1,7 +1,7 @@ -import { Vec4 } from "./vec4.js"; +import { Vec4 } from './vec4.js'; // this is a 32x32 blue noise texture LDR_RGBA_53.png from the database mentioned here: https://momentsingraphics.de/BlueNoise.html -const base64String = "muPIHORMLNDCz4DxVR/ZvYfAUVEFR47KRIC4nwAAAAAP7WxlhD6Ci+2HCe7BF8jRAPZwdH2UPpI5PdLCJdkvG4UTaNDJ/0crAzne71GCrb4kbdMjjCEGzdX6fNxDMLJq5xkeoIVTdfiZkodEeArmZmp/FQzFjD4x8iOW7Dg64n+3mWqyEwLxXT8zoJXfbw8QJKDCaarUYyTlMzNFHbgUe9IQV7g4YOgtSKpIFZJ0qERm7u4PpmiF89ktHWCywaGmD6h+hfh2/Zd8KYlKqqo4Cem4T42bT/Z9FpCQF1hhSjfBzZ5XFn/y3jegWC6u86KuELRundQS/1Rp+XuKKGIgRv3CvP5y749yqLlFO495JOT3+f2CXgd71npU0/KjjpkZucbJ5m78IVyuSrSozc9jgBUhDrz0hFsyb7LFUH9//wJbBgLdNWJZObfKxrNt8TliLA9w9sXFv6g26iXpf6r/BqcAusj/QzGBZuoUGeEtw8BCXCZ3jUiw4hvM18ZVqlUD3C40LAFXW6FRjuAZGRNstb0/qVk4skwyT+MHrvRorI4rKHVMWZmKyAkzL/78u/9pMQuX14pZN50b2PHn6fRxeaCQLsfT4dpvIkWWFuFVENZIh+8xgR6lU+85W0PPdAu1j99kcCG40JBQa4JMyRzq6qriOBLtqF87vpCJan0WEduVr/mOYkS00urVA0mA6M3031+GmGmW48PaJDYOEIb3bIXWPaLoAOEinX1TN3+/vwhG6nqJu0TdHpedS7QsGZIoxH3nQYYjQP1jmbahlbNngw5ogsGk1y50XZyUmQBY+/JBJ3Unu4dApm+WmPwHPU9gLb+4mHh4BiY6M86pq+WeTyWdI3s0CXPEtHGXZ8zMZgUoyRomBi1VdazzuN+WOmQ9Pa0Z0tlNopUi8AJ4x2Xn4mmOKEbXLxlbVsWu8XhuDGYFOGCRVdSqDPXrHU5SDdUlti3k5///SBwzTMwK3L4a1H7w4lnpEas6////AfX8asyIBfeFXVJ3tgvxQ/blZuUKyIODIfr/UzdWNu7pciLBpdZRZ4pIfZ1R6szq+XNxkGG///8EZFpu7VHAhFWqHEOrB9unw+YQa5o8/9IR/V5/zq+986rJSyfgJKt2u9hxU1wzyQWPjJGvzG9+eWWxGFOHVKqI4jBQALwZZswesnvZ2UmmkEXdiRpz8B+oWE7PY70ZTMndisYSXg2TqoI+3y9BxbnY2Y4EfbdcRhAvG59NqDENNYbxKvK5HJfPG5M+Wi2AcpLVJrD6caiEOzgSoVNSgQK8fm2M3zGcF4xtClv/8Hs9oD7C3jitTATYNQxmKqKf1LhIxzf1bmfiNn7UKFmcJu4sLqVLwxGSue3taBEyknkw5hXTsUCvqmmL/f8n/w0giR7Hu/9EHvpkz3yuu64TioMkzdTJ30i0+hFnQqW1+v9mMwq+z9qGX0UFu9MomvVG2xod6vc12AAAAACq7sGa5qptFR0jF3nQt/D+7PibKYahaxP3hEixPbGi9nwNf2LAa7LkEZRKxzXeCD64Xpii5n+8Kpg8eHIv7AWXZltgMoGltmoJ0XGdOCL8WkzphvR9N2o3ARSZ42l5e5Pe4B58MCRlP3EKv+mcloknH+fto5BWsmEutW6KvjOVsznFCktkSczVk4aGvj9VXlRcLeDoKG8RkBgdcNG2bf8HUL4MT2DM+ar7NImJhKpxakX4Vk0CnP+/XNhl5UsP0lXgeZXPoDBMSW5An+DXlTCO5FQGwSPYwHLKYVIimEdAoVe49rQLaaNcye5LxU2/c5TijTgJtD5eQQIe1snxauj5jZsxJBUJdoP/zqpjqv8qBruoPsVsP8N44PCUW5Dd0DzqjSS/Dl5mI9cn1w2ndN/0KAEm1QAAAACwu6KM/083IBbH5bPa/9oHUwcU8I9v3j6/v18QYammrf+P6VL///8BrpuM3fOLCxaLNOFNF1zPbPYTP65ni6njft4eVcyrVXRQFrs52tr35StiSp55edVDCBC0H5rIfac6nzUwxQSt7y15QoKb+5zebEQUmVbrPjXuUa19Ey7sqXMiSUKHaw72PJKDdrutJoQr3u6lEYJ8K0MakWKj9zjTFi4X94TsKYco0GrLeB60M6D8M/80rhXUW8iMequg8y5F838WI0+gp3GBN5Kj/xIOxTWQuUaPV/LwvARr1VH93BFgGZR1MFW0Ua30GbYmdnAgo9VWy8SQtpDUgGE2r2zq2eTEMCL7sMKmE1hchVhuF/TCq9iXKEm86kzOf3Rp9ZnCxbpDUj+FKNxVyXe6pVZkRXv/m95SnB/EB8aME29N85MtAcDoXWlor8De2Q5Dg1tar+8wgiZufbMam81j//ASUohoR/zSh2KG4bvT6mkIPz6C5/98DC3LaWlaEZ1zA5JORZRu6J/a0GY285sEYzw71YqOT1ihAG0z5SDt1xNiDQWZdFpndArp6xWhqSDkRb4kSJEHb9liPvw7uLV/6i5MVf//A9Qjr8xkAEUh+KDI+zdtJ68d6MBOktg1iyp/SCq8O9f5pbamn1VVVQPRTWqNBvhQKa07s6P0lc9Luu/3gw4HeyOUfz8MxMwV4UQhua+t9cr4bz/nIB2wnDSK1K7I94M+s6C84htaX/CNlMQUSs2KJO+yaebfTbkNX5yWcqEJevo0vbKUiETuFXiL019A3E+lmsyZMwXrXLLiQAZ5t9+jI3JobhJTMiDH5ZOQ+8Jau5555NMjHSscP9qCVaa40doh+1a3Ukf6jqBmLddgh79/fwTfCyqiuldNkUoy+nUp+4nerwg0OjtGv2x485PJOJvUEokNhYIdWjpx7BWk0VZGWOp3jSFTJ2bnu6KCduZtG/UcBC9RZ3W/jMSfSMw4Etr/DoD/XYP2V5Ovw+YoM3F5g2dGLdvuG6ZkVGLE6Dk5Zr+sdSyGliJP1y2OFf/KFO0RWO+3gsGhesTnfZVpTd8/HwgO216gwaqo+vY3TljfJWowY+i0p0Os4SLn/1wLqDHMlszggmT/D8MRFzs+pLv6LNJSsNZ/r41mWi/rF6ZcKp/yzJdK0VU44hskq3RGpgO6mIpJDsf/mZkFrz0yYOMLbuaj/wp1v7JMFM5eqvBhmTd7U8frQAtHtys4zgpjZmzUhOVTfNNLifElGXADlqHGKrkBT/nYwX8ZRm3RjvyPvjKyEqEGKUpVnvOGx+NKPHiWM//ZDpDVGvvrjmk8RPF/wiYZD3+Us8YCXjrVOfjdd1UPAfjLp8jgSn4me7DPTpz1Ggy9XL80guFO7ECT10AvILKfD18Qx+KY/f8aRqu0oOO8hfKRFZa9PUJwCsp6VdZz6LFkm2b9Pl2LIifCwzRy7TpdG2uAtOxP2OemY26bJMa9ZGSLIRlMsgpDpnDJwd0oa5pQ13x1hrHf52HpulUWonGWsfXZbSQYKu9bnEN76ciQih0opN3deDVrbrxorfVlnCmL1R9zq3ePGWIv21c7pW8kEiFTM5JX8dAw867s/60cf79/BH+MDFCZBHlz1L+qGOJf/1txhhmrf3//As+RIJwevDb+fgNXVeHw67QptZegayhrEwr5Gy+EPo1RLaMtPbqOZYoVzXzwzjMFWZxyUG9YUIf6////AQWy84iAygLk9COtXt92+0mT/xg0zMzMBeLkb8y9SL2TDXgSX422hDgpGNLJyuPioA+YJ91G8znrpNqHkwYyscaJDEc9Vc+j4cXle3hvcd2JqDQH2lBZxDn6mUTs0b75raMvbs727codX01Anj8f3wir9P2xQaQ22v/TxCMglKDFoTjaP01XTLgxnTvPv02JgEUrW6UDgOnobFpLdvKdlypgIzPcq14fgXU5tvVW0FEs7VRlsG1IyA69fN4n+awHhT34cE+xUvdj86C8LgAsFheTjI9Ht9EyYAAAAAAVBVKRx2wLgUTI0/2QfyJo2riRw3JDqzEShmx/Lifo6mRkQVbS7X53t+EvKxcXogtdts31e9MRHdcHgsA8rt4/mt2unlzQ/wsU8Gu7+W6Oj7eD8EQdDp5XlCsVaS/AV/t5ZpPOHR3rGpyAJe9IPV+xMrBL1Oz/8MQhFs31h0N1cVnq371uqIJYHyafKH1jteAK3VpMXBcuC+yt0ZeKyRUY4QhdrJJ4tJ1wg3Hu6kDsbovxupTMkGdRrm8oZSoYPbJ+PwH/xotgTdkA1205vUEfnqkI04T/fnnd1fiZW5AwNcggd7fi4j5zasmcntZexIxqFZQMzMJpfndmI5jn17cgn5EV5t9XN0C///8Q9wlJpMGXdoiaMTG2sVyHQsn8mWRISCLNG777S0OuDRP2GlLcJ2UeOg7Fo8hTNPeJ//iTJhyqxhKRUntdXOihq2wfKfH///8B0GGrwT+fSOQRdctKxjjGCSS11d6BlQ9BDfE0J6Z25FaNTKGpFKNCMr2G/041KpWwBLVe1k08vncseQbKZdXi8x1t9XA45U/Wd43D9wAh3Tal0aiLVzGPusOZ1F+W3TWoqlX/A95+dNef11TsuGful+ctGssldk3fqpfqh+43XTxL42+leSHoF/dWHYGX6maqUEuLX7UB+r/6Llr4LKocbVIeu+hB9QTPfz9fCP8RyWmX4SmbhMFsNtCijV7lVcwejLKlvl0GfCndnWV7/39VBrtTRuUx92oke3GBgKkC5fdGK0YvNK+xenKaDmsHDjNFUM3NMz3ZiXXFuLgojosPVCDEl2W5BjX3Ms+j0GSqACHmh0+RPWyuNm/Qe8vFf9AW7N1uRaxWirrUytqEJnJ4/Flm8hSoiZ2NQBsS6w/yQlC4gCaFo8q4nyY6AFdo4hiwhBXzbNKKvZvktCjSCukRR/BbYVbNwZi2Yh3hGodEacLW8qijiWJODf0P2bhfaiPspPT4lYJBgi/KfcFwCfvyUIgkJOv///8CG/JEepRBLaMFE+2TgrqsJXOVOWHt6g/bFwVLLMVBsMR50dis/39/AlBX+/rMTJkUQrnlxpR2iu0Tp8tATkRYGmDIrcAiRP8PjoWIlb7/0ecTdSCE9Y58+a+n/FovJQTVF4F2jAxMZhTgrM/KVS5BQu6bVbkWY5HXnxRshks3urDdW4RkWp4M4TeLmFK5KF/uHkkiO5Kv96RioH984v/CSDBnG+BwlnU9B+o7Y+0X0Nob+0pLsStxjvPXMy2eCpzhOWV4XbObBHN4UE2sLQ/DIqXhOzxVf38GlTi6aG7EnePO7TRJm9yOfUUcqq1I2iQHrVDqn3TUNRi/lMw8KbMW/3/nqCz/Ef8PoW5Qxcz2yHR/f78EPB2Stbd+ZFmfNTUYILzsb9YNhpaHcaymYrBiNHmFE3Y4ccYJ25Prqm7zHobGHED8/93ZNlWro9vcKivGZs31UiK1k5zjUhexUgbqJb+fUTjxce/7Zly8a5KMC1fX5nfjPgibdvzbXV1jRT2asXvmSAusaLdq1TSIJ8fXINk5AtT34EWPAsfP9IFQqM5K11O6saoHJA=="; +const base64String = 'muPIHORMLNDCz4DxVR/ZvYfAUVEFR47KRIC4nwAAAAAP7WxlhD6Ci+2HCe7BF8jRAPZwdH2UPpI5PdLCJdkvG4UTaNDJ/0crAzne71GCrb4kbdMjjCEGzdX6fNxDMLJq5xkeoIVTdfiZkodEeArmZmp/FQzFjD4x8iOW7Dg64n+3mWqyEwLxXT8zoJXfbw8QJKDCaarUYyTlMzNFHbgUe9IQV7g4YOgtSKpIFZJ0qERm7u4PpmiF89ktHWCywaGmD6h+hfh2/Zd8KYlKqqo4Cem4T42bT/Z9FpCQF1hhSjfBzZ5XFn/y3jegWC6u86KuELRundQS/1Rp+XuKKGIgRv3CvP5y749yqLlFO495JOT3+f2CXgd71npU0/KjjpkZucbJ5m78IVyuSrSozc9jgBUhDrz0hFsyb7LFUH9//wJbBgLdNWJZObfKxrNt8TliLA9w9sXFv6g26iXpf6r/BqcAusj/QzGBZuoUGeEtw8BCXCZ3jUiw4hvM18ZVqlUD3C40LAFXW6FRjuAZGRNstb0/qVk4skwyT+MHrvRorI4rKHVMWZmKyAkzL/78u/9pMQuX14pZN50b2PHn6fRxeaCQLsfT4dpvIkWWFuFVENZIh+8xgR6lU+85W0PPdAu1j99kcCG40JBQa4JMyRzq6qriOBLtqF87vpCJan0WEduVr/mOYkS00urVA0mA6M3031+GmGmW48PaJDYOEIb3bIXWPaLoAOEinX1TN3+/vwhG6nqJu0TdHpedS7QsGZIoxH3nQYYjQP1jmbahlbNngw5ogsGk1y50XZyUmQBY+/JBJ3Unu4dApm+WmPwHPU9gLb+4mHh4BiY6M86pq+WeTyWdI3s0CXPEtHGXZ8zMZgUoyRomBi1VdazzuN+WOmQ9Pa0Z0tlNopUi8AJ4x2Xn4mmOKEbXLxlbVsWu8XhuDGYFOGCRVdSqDPXrHU5SDdUlti3k5///SBwzTMwK3L4a1H7w4lnpEas6////AfX8asyIBfeFXVJ3tgvxQ/blZuUKyIODIfr/UzdWNu7pciLBpdZRZ4pIfZ1R6szq+XNxkGG///8EZFpu7VHAhFWqHEOrB9unw+YQa5o8/9IR/V5/zq+986rJSyfgJKt2u9hxU1wzyQWPjJGvzG9+eWWxGFOHVKqI4jBQALwZZswesnvZ2UmmkEXdiRpz8B+oWE7PY70ZTMndisYSXg2TqoI+3y9BxbnY2Y4EfbdcRhAvG59NqDENNYbxKvK5HJfPG5M+Wi2AcpLVJrD6caiEOzgSoVNSgQK8fm2M3zGcF4xtClv/8Hs9oD7C3jitTATYNQxmKqKf1LhIxzf1bmfiNn7UKFmcJu4sLqVLwxGSue3taBEyknkw5hXTsUCvqmmL/f8n/w0giR7Hu/9EHvpkz3yuu64TioMkzdTJ30i0+hFnQqW1+v9mMwq+z9qGX0UFu9MomvVG2xod6vc12AAAAACq7sGa5qptFR0jF3nQt/D+7PibKYahaxP3hEixPbGi9nwNf2LAa7LkEZRKxzXeCD64Xpii5n+8Kpg8eHIv7AWXZltgMoGltmoJ0XGdOCL8WkzphvR9N2o3ARSZ42l5e5Pe4B58MCRlP3EKv+mcloknH+fto5BWsmEutW6KvjOVsznFCktkSczVk4aGvj9VXlRcLeDoKG8RkBgdcNG2bf8HUL4MT2DM+ar7NImJhKpxakX4Vk0CnP+/XNhl5UsP0lXgeZXPoDBMSW5An+DXlTCO5FQGwSPYwHLKYVIimEdAoVe49rQLaaNcye5LxU2/c5TijTgJtD5eQQIe1snxauj5jZsxJBUJdoP/zqpjqv8qBruoPsVsP8N44PCUW5Dd0DzqjSS/Dl5mI9cn1w2ndN/0KAEm1QAAAACwu6KM/083IBbH5bPa/9oHUwcU8I9v3j6/v18QYammrf+P6VL///8BrpuM3fOLCxaLNOFNF1zPbPYTP65ni6njft4eVcyrVXRQFrs52tr35StiSp55edVDCBC0H5rIfac6nzUwxQSt7y15QoKb+5zebEQUmVbrPjXuUa19Ey7sqXMiSUKHaw72PJKDdrutJoQr3u6lEYJ8K0MakWKj9zjTFi4X94TsKYco0GrLeB60M6D8M/80rhXUW8iMequg8y5F838WI0+gp3GBN5Kj/xIOxTWQuUaPV/LwvARr1VH93BFgGZR1MFW0Ua30GbYmdnAgo9VWy8SQtpDUgGE2r2zq2eTEMCL7sMKmE1hchVhuF/TCq9iXKEm86kzOf3Rp9ZnCxbpDUj+FKNxVyXe6pVZkRXv/m95SnB/EB8aME29N85MtAcDoXWlor8De2Q5Dg1tar+8wgiZufbMam81j//ASUohoR/zSh2KG4bvT6mkIPz6C5/98DC3LaWlaEZ1zA5JORZRu6J/a0GY285sEYzw71YqOT1ihAG0z5SDt1xNiDQWZdFpndArp6xWhqSDkRb4kSJEHb9liPvw7uLV/6i5MVf//A9Qjr8xkAEUh+KDI+zdtJ68d6MBOktg1iyp/SCq8O9f5pbamn1VVVQPRTWqNBvhQKa07s6P0lc9Luu/3gw4HeyOUfz8MxMwV4UQhua+t9cr4bz/nIB2wnDSK1K7I94M+s6C84htaX/CNlMQUSs2KJO+yaebfTbkNX5yWcqEJevo0vbKUiETuFXiL019A3E+lmsyZMwXrXLLiQAZ5t9+jI3JobhJTMiDH5ZOQ+8Jau5555NMjHSscP9qCVaa40doh+1a3Ukf6jqBmLddgh79/fwTfCyqiuldNkUoy+nUp+4nerwg0OjtGv2x485PJOJvUEokNhYIdWjpx7BWk0VZGWOp3jSFTJ2bnu6KCduZtG/UcBC9RZ3W/jMSfSMw4Etr/DoD/XYP2V5Ovw+YoM3F5g2dGLdvuG6ZkVGLE6Dk5Zr+sdSyGliJP1y2OFf/KFO0RWO+3gsGhesTnfZVpTd8/HwgO216gwaqo+vY3TljfJWowY+i0p0Os4SLn/1wLqDHMlszggmT/D8MRFzs+pLv6LNJSsNZ/r41mWi/rF6ZcKp/yzJdK0VU44hskq3RGpgO6mIpJDsf/mZkFrz0yYOMLbuaj/wp1v7JMFM5eqvBhmTd7U8frQAtHtys4zgpjZmzUhOVTfNNLifElGXADlqHGKrkBT/nYwX8ZRm3RjvyPvjKyEqEGKUpVnvOGx+NKPHiWM//ZDpDVGvvrjmk8RPF/wiYZD3+Us8YCXjrVOfjdd1UPAfjLp8jgSn4me7DPTpz1Ggy9XL80guFO7ECT10AvILKfD18Qx+KY/f8aRqu0oOO8hfKRFZa9PUJwCsp6VdZz6LFkm2b9Pl2LIifCwzRy7TpdG2uAtOxP2OemY26bJMa9ZGSLIRlMsgpDpnDJwd0oa5pQ13x1hrHf52HpulUWonGWsfXZbSQYKu9bnEN76ciQih0opN3deDVrbrxorfVlnCmL1R9zq3ePGWIv21c7pW8kEiFTM5JX8dAw867s/60cf79/BH+MDFCZBHlz1L+qGOJf/1txhhmrf3//As+RIJwevDb+fgNXVeHw67QptZegayhrEwr5Gy+EPo1RLaMtPbqOZYoVzXzwzjMFWZxyUG9YUIf6////AQWy84iAygLk9COtXt92+0mT/xg0zMzMBeLkb8y9SL2TDXgSX422hDgpGNLJyuPioA+YJ91G8znrpNqHkwYyscaJDEc9Vc+j4cXle3hvcd2JqDQH2lBZxDn6mUTs0b75raMvbs727codX01Anj8f3wir9P2xQaQ22v/TxCMglKDFoTjaP01XTLgxnTvPv02JgEUrW6UDgOnobFpLdvKdlypgIzPcq14fgXU5tvVW0FEs7VRlsG1IyA69fN4n+awHhT34cE+xUvdj86C8LgAsFheTjI9Ht9EyYAAAAAAVBVKRx2wLgUTI0/2QfyJo2riRw3JDqzEShmx/Lifo6mRkQVbS7X53t+EvKxcXogtdts31e9MRHdcHgsA8rt4/mt2unlzQ/wsU8Gu7+W6Oj7eD8EQdDp5XlCsVaS/AV/t5ZpPOHR3rGpyAJe9IPV+xMrBL1Oz/8MQhFs31h0N1cVnq371uqIJYHyafKH1jteAK3VpMXBcuC+yt0ZeKyRUY4QhdrJJ4tJ1wg3Hu6kDsbovxupTMkGdRrm8oZSoYPbJ+PwH/xotgTdkA1205vUEfnqkI04T/fnnd1fiZW5AwNcggd7fi4j5zasmcntZexIxqFZQMzMJpfndmI5jn17cgn5EV5t9XN0C///8Q9wlJpMGXdoiaMTG2sVyHQsn8mWRISCLNG777S0OuDRP2GlLcJ2UeOg7Fo8hTNPeJ//iTJhyqxhKRUntdXOihq2wfKfH///8B0GGrwT+fSOQRdctKxjjGCSS11d6BlQ9BDfE0J6Z25FaNTKGpFKNCMr2G/041KpWwBLVe1k08vncseQbKZdXi8x1t9XA45U/Wd43D9wAh3Tal0aiLVzGPusOZ1F+W3TWoqlX/A95+dNef11TsuGful+ctGssldk3fqpfqh+43XTxL42+leSHoF/dWHYGX6maqUEuLX7UB+r/6Llr4LKocbVIeu+hB9QTPfz9fCP8RyWmX4SmbhMFsNtCijV7lVcwejLKlvl0GfCndnWV7/39VBrtTRuUx92oke3GBgKkC5fdGK0YvNK+xenKaDmsHDjNFUM3NMz3ZiXXFuLgojosPVCDEl2W5BjX3Ms+j0GSqACHmh0+RPWyuNm/Qe8vFf9AW7N1uRaxWirrUytqEJnJ4/Flm8hSoiZ2NQBsS6w/yQlC4gCaFo8q4nyY6AFdo4hiwhBXzbNKKvZvktCjSCukRR/BbYVbNwZi2Yh3hGodEacLW8qijiWJODf0P2bhfaiPspPT4lYJBgi/KfcFwCfvyUIgkJOv///8CG/JEepRBLaMFE+2TgrqsJXOVOWHt6g/bFwVLLMVBsMR50dis/39/AlBX+/rMTJkUQrnlxpR2iu0Tp8tATkRYGmDIrcAiRP8PjoWIlb7/0ecTdSCE9Y58+a+n/FovJQTVF4F2jAxMZhTgrM/KVS5BQu6bVbkWY5HXnxRshks3urDdW4RkWp4M4TeLmFK5KF/uHkkiO5Kv96RioH984v/CSDBnG+BwlnU9B+o7Y+0X0Nob+0pLsStxjvPXMy2eCpzhOWV4XbObBHN4UE2sLQ/DIqXhOzxVf38GlTi6aG7EnePO7TRJm9yOfUUcqq1I2iQHrVDqn3TUNRi/lMw8KbMW/3/nqCz/Ef8PoW5Qxcz2yHR/f78EPB2Stbd+ZFmfNTUYILzsb9YNhpaHcaymYrBiNHmFE3Y4ccYJ25Prqm7zHobGHED8/93ZNlWro9vcKivGZs31UiK1k5zjUhexUgbqJb+fUTjxce/7Zly8a5KMC1fX5nfjPgibdvzbXV1jRT2asXvmSAusaLdq1TSIJ8fXINk5AtT34EWPAsfP9IFQqM5K11O6saoHJA=='; let data = null; const initData = () => { diff --git a/src/core/math/color.js b/src/core/math/color.js index 170f1ec7b6c..eb20a7f03b9 100644 --- a/src/core/math/color.js +++ b/src/core/math/color.js @@ -233,11 +233,11 @@ class Color { * console.log(c.toString()); */ toString(alpha) { - let s = '#' + ((1 << 24) + (Math.round(this.r * 255) << 16) + (Math.round(this.g * 255) << 8) + Math.round(this.b * 255)).toString(16).slice(1); + let s = `#${((1 << 24) + (Math.round(this.r * 255) << 16) + (Math.round(this.g * 255) << 8) + Math.round(this.b * 255)).toString(16).slice(1)}`; if (alpha === true) { const a = Math.round(this.a * 255).toString(16); if (this.a < 16 / 255) { - s += '0' + a; + s += `0${a}`; } else { s += a; } diff --git a/src/core/math/curve-set.js b/src/core/math/curve-set.js index 29a5f2702e8..8324d48e141 100644 --- a/src/core/math/curve-set.js +++ b/src/core/math/curve-set.js @@ -1,6 +1,6 @@ import { CURVE_SMOOTHSTEP } from './constants.js'; -import { Curve } from './curve.js'; import { CurveEvaluator } from './curve-evaluator.js'; +import { Curve } from './curve.js'; /** * A curve set is a collection of curves. diff --git a/src/core/math/mat3.js b/src/core/math/mat3.js index 6746d4b30de..4b2bd9da1f3 100644 --- a/src/core/math/mat3.js +++ b/src/core/math/mat3.js @@ -206,7 +206,7 @@ class Mat3 { * console.log(m.toString()); */ toString() { - return '[' + this.data.join(', ') + ']'; + return `[${this.data.join(', ')}]`; } /** diff --git a/src/core/math/mat4.js b/src/core/math/mat4.js index 22b50d9f27c..061106abc36 100644 --- a/src/core/math/mat4.js +++ b/src/core/math/mat4.js @@ -1242,8 +1242,9 @@ class Mat4 { const sy = scale.y; const sz = scale.z; - if (sx === 0 || sy === 0 || sz === 0) + if (sx === 0 || sy === 0 || sz === 0) { return eulers.set(0, 0, 0); + } const m = this.data; @@ -1280,7 +1281,7 @@ class Mat4 { * console.log(m.toString()); */ toString() { - return '[' + this.data.join(', ') + ']'; + return `[${this.data.join(', ')}]`; } /** diff --git a/src/core/math/math.js b/src/core/math/math.js index 601634a92ff..57f0fd6256a 100644 --- a/src/core/math/math.js +++ b/src/core/math/math.js @@ -258,8 +258,9 @@ const math = { * @returns {number} A number rounded up to nearest multiple. */ roundUp(numToRound, multiple) { - if (multiple === 0) + if (multiple === 0) { return numToRound; + } return Math.ceil(numToRound / multiple) * multiple; }, diff --git a/src/core/path.js b/src/core/path.js index c872e217705..6c93f455943 100644 --- a/src/core/path.js +++ b/src/core/path.js @@ -100,7 +100,7 @@ const path = { if (lastDelimiterIndex !== -1) { return [pathname.substring(0, lastDelimiterIndex), pathname.substring(lastDelimiterIndex + 1)]; } - return ["", pathname]; + return ['', pathname]; }, /** @@ -142,7 +142,7 @@ const path = { getExtension(pathname) { const ext = pathname.split('?')[0].split('.').pop(); if (ext !== pathname) { - return '.' + ext; + return `.${ext}`; } return ''; }, @@ -186,22 +186,22 @@ const path = { if (path.isRelativePath(pathname)) { if (parts[0] === '.') { for (i = 0; i < parts.length - 1; ++i) { - result += (i === 0) ? parts[i] : '/' + parts[i]; + result += (i === 0) ? parts[i] : `/${parts[i]}`; } } else if (parts[0] === '..') { for (i = 0; i < parts.length - 1; ++i) { - result += (i === 0) ? parts[i] : '/' + parts[i]; + result += (i === 0) ? parts[i] : `/${parts[i]}`; } } else { result = '.'; for (i = 0; i < parts.length - 1; ++i) { - result += '/' + parts[i]; + result += `/${parts[i]}`; } } } else { for (i = 0; i < parts.length - 1; ++i) { - result += (i === 0) ? parts[i] : '/' + parts[i]; + result += (i === 0) ? parts[i] : `/${parts[i]}`; } } } diff --git a/src/core/platform.js b/src/core/platform.js index ffb53900625..54aa89972af 100644 --- a/src/core/platform.js +++ b/src/core/platform.js @@ -23,7 +23,7 @@ const environment = typeof window !== 'undefined' ? 'browser' : // detect platform const platformName = (/android/i.test(ua) ? 'android' : - (/ip([ao]d|hone)/i.test(ua) ? 'ios' : + (/ip(?:[ao]d|hone)/i.test(ua) ? 'ios' : (/windows/i.test(ua) ? 'windows' : (/mac os/i.test(ua) ? 'osx' : (/linux/i.test(ua) ? 'linux' : @@ -32,7 +32,7 @@ const platformName = // detect browser const browserName = (environment !== 'browser') ? null : - (/(Chrome\/|Chromium\/|Edg.*\/)/.test(ua) ? 'chrome' : // chrome, chromium, edge + (/Chrome\/|Chromium\/|Edg.*\//.test(ua) ? 'chrome' : // chrome, chromium, edge (/Safari\//.test(ua) ? 'safari' : // safari, ios chrome/firefox (/Firefox\//.test(ua) ? 'firefox' : 'other'))); diff --git a/src/core/preprocessor.js b/src/core/preprocessor.js index 7e1d9768c60..3f5f271e64e 100644 --- a/src/core/preprocessor.js +++ b/src/core/preprocessor.js @@ -7,19 +7,22 @@ const TRACEID = 'Preprocessor'; const KEYWORD = /[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension|include)/g; // #define EXPRESSION +// eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/optimal-quantifier-concatenation const DEFINE = /define[ \t]+([^\n]+)\r?(?:\n|$)/g; // #extension IDENTIFIER : enabled const EXTENSION = /extension[ \t]+([\w-]+)[ \t]*:[ \t]*(enable|require)/g; // #undef EXPRESSION +// eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/optimal-quantifier-concatenation const UNDEF = /undef[ \t]+([^\n]+)\r?(?:\n|$)/g; // #ifdef/#ifndef SOMEDEFINE, #if EXPRESSION +// eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/no-unused-capturing-group const IF = /(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g; // #endif/#else or #elif EXPRESSION -const ENDIF = /(endif|else|elif)([ \t]+[^\r\n]+)?\r?(?:\n|$)/g; +const ENDIF = /(endif|else|elif)([ \t][^\r\n]+)?\r?(?:\n|$)/g; // identifier const IDENTIFIER = /([\w-]+)/; @@ -54,8 +57,8 @@ class Preprocessor { // right trim each line source = source.split(/\r?\n/) - .map(line => line.trimEnd()) - .join('\n'); + .map(line => line.trimEnd()) + .join('\n'); // generate defines to remove unused color attachments const defines = new Map(); @@ -123,12 +126,12 @@ class Preprocessor { if (source !== null) { source = source.split(/\r?\n/) - // convert lines with only white space into empty string - .map(line => (line.trim() === '' ? '' : line)) - .join('\n'); + // convert lines with only white space into empty string + .map(line => (line.trim() === '' ? '' : line)) + .join('\n'); // remove more than 1 consecutive empty lines - source = source.replace(/(\n\n){3,}/gm, '\n\n'); + source = source.replace(/(\n\n){3,}/g, '\n\n'); } return source; @@ -174,7 +177,7 @@ class Preprocessor { const identifierValue = IDENTIFIER.exec(expression); const identifier = identifierValue[1]; let value = expression.substring(identifier.length).trim(); - if (value === "") value = "true"; + if (value === '') value = 'true'; // are we inside if-blocks that are accepted const keep = Preprocessor._keep(stack); @@ -183,7 +186,7 @@ class Preprocessor { defines.set(identifier, value); } - Debug.trace(TRACEID, `${keyword}: [${identifier}] ${value} ${keep ? "" : "IGNORED"}`); + Debug.trace(TRACEID, `${keyword}: [${identifier}] ${value} ${keep ? '' : 'IGNORED'}`); // continue on the next line KEYWORD.lastIndex = define.index + define[0].length; @@ -205,7 +208,7 @@ class Preprocessor { defines.delete(identifier); } - Debug.trace(TRACEID, `${keyword}: [${identifier}] ${keep ? "" : "IGNORED"}`); + Debug.trace(TRACEID, `${keyword}: [${identifier}] ${keep ? '' : 'IGNORED'}`); // continue on the next line KEYWORD.lastIndex = undef.index + undef[0].length; @@ -224,10 +227,10 @@ class Preprocessor { const keep = Preprocessor._keep(stack); if (keep) { - defines.set(identifier, "true"); + defines.set(identifier, 'true'); } - Debug.trace(TRACEID, `${keyword}: [${identifier}] ${keep ? "" : "IGNORED"}`); + Debug.trace(TRACEID, `${keyword}: [${identifier}] ${keep ? '' : 'IGNORED'}`); } // continue on the next line @@ -278,8 +281,8 @@ class Preprocessor { const blockInfo = stack.pop(); // code between if and endif - const blockCode = blockInfo.keep ? source.substring(blockInfo.end, match.index) : ""; - Debug.trace(TRACEID, `${keyword}: [previous block] => ${blockCode !== ""}`); + const blockCode = blockInfo.keep ? source.substring(blockInfo.end, match.index) : ''; + Debug.trace(TRACEID, `${keyword}: [previous block] => ${blockCode !== ''}`); // cut out the IF and ENDIF lines, leave block if required source = source.substring(0, blockInfo.start) + blockCode + source.substring(ENDIF.lastIndex); @@ -340,14 +343,14 @@ class Preprocessor { } } - Debug.trace(TRACEID, `${keyword}: [${identifier}] ${keep ? "" : "IGNORED"}`); + Debug.trace(TRACEID, `${keyword}: [${identifier}] ${keep ? '' : 'IGNORED'}`); break; } } } if (error) { - console.warn("Failed to preprocess shader: ", { source: originalSource }); + console.warn('Failed to preprocess shader: ', { source: originalSource }); return originalSource; } @@ -357,8 +360,9 @@ class Preprocessor { // function returns true if the evaluation is inside keep branches static _keep(stack) { for (let i = 0; i < stack.length; i++) { - if (!stack[i].keep) + if (!stack[i].keep) { return false; + } } return true; diff --git a/src/core/shape/bounding-box.js b/src/core/shape/bounding-box.js index 379e59cd533..e2274f41267 100644 --- a/src/core/shape/bounding-box.js +++ b/src/core/shape/bounding-box.js @@ -186,8 +186,9 @@ class BoundingBox { const intersects = minMax >= maxMin && maxMin >= 0; - if (intersects) + if (intersects) { point.copy(ray.direction).mulScalar(maxMin).add(ray.origin); + } return intersects; } @@ -205,27 +206,33 @@ class BoundingBox { prod.mul2(diff, rayDir); - if (absDiff.x > this.halfExtents.x && prod.x >= 0) + if (absDiff.x > this.halfExtents.x && prod.x >= 0) { return false; + } - if (absDiff.y > this.halfExtents.y && prod.y >= 0) + if (absDiff.y > this.halfExtents.y && prod.y >= 0) { return false; + } - if (absDiff.z > this.halfExtents.z && prod.z >= 0) + if (absDiff.z > this.halfExtents.z && prod.z >= 0) { return false; + } absDir.set(Math.abs(rayDir.x), Math.abs(rayDir.y), Math.abs(rayDir.z)); cross.cross(rayDir, diff); cross.set(Math.abs(cross.x), Math.abs(cross.y), Math.abs(cross.z)); - if (cross.x > this.halfExtents.y * absDir.z + this.halfExtents.z * absDir.y) + if (cross.x > this.halfExtents.y * absDir.z + this.halfExtents.z * absDir.y) { return false; + } - if (cross.y > this.halfExtents.x * absDir.z + this.halfExtents.z * absDir.x) + if (cross.y > this.halfExtents.x * absDir.z + this.halfExtents.z * absDir.x) { return false; + } - if (cross.z > this.halfExtents.x * absDir.y + this.halfExtents.y * absDir.x) + if (cross.z > this.halfExtents.x * absDir.y + this.halfExtents.y * absDir.x) { return false; + } return true; } diff --git a/src/core/shape/bounding-sphere.js b/src/core/shape/bounding-sphere.js index bd145fc4321..7cccbc59094 100644 --- a/src/core/shape/bounding-sphere.js +++ b/src/core/shape/bounding-sphere.js @@ -66,20 +66,23 @@ class BoundingSphere { const c = m.dot(m) - this.radius * this.radius; // exit if ray's origin outside of sphere (c > 0) and ray pointing away from s (b > 0) - if (c > 0 && b > 0) + if (c > 0 && b > 0) { return false; + } const discr = b * b - c; // a negative discriminant corresponds to ray missing sphere - if (discr < 0) + if (discr < 0) { return false; + } // ray intersects sphere, compute smallest t value of intersection const t = Math.abs(-b - Math.sqrt(discr)); // if t is negative, ray started inside sphere so clamp t to zero - if (point) + if (point) { point.copy(ray.direction).mulScalar(t).add(ray.origin); + } return true; } diff --git a/src/core/shape/frustum.js b/src/core/shape/frustum.js index 6a4ffbc7c42..6fe3591bc7c 100644 --- a/src/core/shape/frustum.js +++ b/src/core/shape/frustum.js @@ -128,10 +128,12 @@ class Frustum { for (let p = 0; p < 6; p++) { const { normal, distance } = this.planes[p]; const d = normal.dot(center) + distance; - if (d <= -radius) + if (d <= -radius) { return 0; - if (d > radius) + } + if (d > radius) { c++; + } } return (c === 6) ? 2 : 1; diff --git a/src/core/shape/oriented-box.js b/src/core/shape/oriented-box.js index 25ea3c91be8..22fa0918077 100644 --- a/src/core/shape/oriented-box.js +++ b/src/core/shape/oriented-box.js @@ -1,9 +1,8 @@ -import { Mat4 } from '../math/mat4.js'; -import { Vec3 } from '../math/vec3.js'; - import { BoundingBox } from './bounding-box.js'; import { BoundingSphere } from './bounding-sphere.js'; import { Ray } from './ray.js'; +import { Mat4 } from '../math/mat4.js'; +import { Vec3 } from '../math/vec3.js'; const tmpRay = new Ray(); const tmpVec3 = new Vec3(); diff --git a/src/core/shape/plane.js b/src/core/shape/plane.js index 13f191b94ba..b780bb45758 100644 --- a/src/core/shape/plane.js +++ b/src/core/shape/plane.js @@ -77,8 +77,9 @@ class Plane { const t = d0 / (d0 - d1); const intersects = t >= 0 && t <= 1; - if (intersects && point) + if (intersects && point) { point.lerp(start, end, t); + } return intersects; } @@ -93,8 +94,9 @@ class Plane { */ intersectsRay(ray, point) { const denominator = this.normal.dot(ray.direction); - if (denominator === 0) + if (denominator === 0) { return false; + } const t = -(this.normal.dot(ray.origin) + this.distance) / denominator; if (t >= 0 && point) { diff --git a/src/core/shape/tri.js b/src/core/shape/tri.js index 5d11e8b097a..d87e51cefbb 100644 --- a/src/core/shape/tri.js +++ b/src/core/shape/tri.js @@ -135,7 +135,7 @@ class Tri { * console.log(t.toString()); */ toString() { - return '[' + this.v0.toString() + ', ' + this.v1.toString() + ', ' + this.v2.toString() + ']'; + return `[${this.v0.toString()}, ${this.v1.toString()}, ${this.v2.toString()}]`; } } diff --git a/src/core/string.js b/src/core/string.js index e2a7bfbce7b..aa6e4d6eca4 100644 --- a/src/core/string.js +++ b/src/core/string.js @@ -50,8 +50,9 @@ function getCodePointData(string, i = 0) { } function isCodeBetween(string, begin, end) { - if (!string) + if (!string) { return false; + } const codeData = getCodePointData(string); if (codeData) { const code = codeData.code; diff --git a/src/core/tags-cache.js b/src/core/tags-cache.js index b4c120eff1c..ab5f5722791 100644 --- a/src/core/tags-cache.js +++ b/src/core/tags-cache.js @@ -10,21 +10,24 @@ class TagsCache { addItem(item) { const tags = item.tags._list; - for (const tag of tags) + for (const tag of tags) { this.add(tag, item); + } } removeItem(item) { const tags = item.tags._list; - for (const tag of tags) + for (const tag of tags) { this.remove(tag, item); + } } add(tag, item) { // already in cache - if (this._index[tag] && this._index[tag].list.indexOf(item) !== -1) + if (this._index[tag] && this._index[tag].list.indexOf(item) !== -1) { return; + } // create index for tag if (!this._index[tag]) { @@ -32,45 +35,52 @@ class TagsCache { list: [] }; // key indexing is available - if (this._key) + if (this._key) { this._index[tag].keys = { }; + } } // add to index list this._index[tag].list.push(item); // add to index keys - if (this._key) + if (this._key) { this._index[tag].keys[item[this._key]] = item; + } } remove(tag, item) { // no index created for that tag - if (!this._index[tag]) + if (!this._index[tag]) { return; + } // check if item not in cache if (this._key) { // by key - if (!this._index[tag].keys[item[this._key]]) + if (!this._index[tag].keys[item[this._key]]) { return; + } } // by position in list const ind = this._index[tag].list.indexOf(item); - if (ind === -1) + if (ind === -1) { return; + } // remove item from index list this._index[tag].list.splice(ind, 1); // remove item from index keys - if (this._key) + if (this._key) { delete this._index[tag].keys[item[this._key]]; + } // if index empty, remove it - if (this._index[tag].list.length === 0) + if (this._index[tag].list.length === 0) { delete this._index[tag]; + } } find(args) { @@ -86,8 +96,9 @@ class TagsCache { tag = args[i]; if (tag instanceof Array) { - if (tag.length === 0) + if (tag.length === 0) { continue; + } if (tag.length === 1) { tag = tag[0]; @@ -100,22 +111,25 @@ class TagsCache { break; } } - if (missingIndex) + if (missingIndex) { continue; + } // sort tags by least number of matches first tags = tag.slice(0).sort(sort); // remainder of tags for `has` checks tagsRest = tags.slice(1); - if (tagsRest.length === 1) + if (tagsRest.length === 1) { tagsRest = tagsRest[0]; + } for (let n = 0; n < this._index[tags[0]].list.length; n++) { item = this._index[tags[0]].list[n]; if ((this._key ? !index[item[this._key]] : (items.indexOf(item) === -1)) && item.tags.has(tagsRest)) { - if (this._key) + if (this._key) { index[item[this._key]] = true; + } items.push(item); } } diff --git a/src/core/tags.js b/src/core/tags.js index 67b12c3bac9..22f2e4a453c 100644 --- a/src/core/tags.js +++ b/src/core/tags.js @@ -72,12 +72,14 @@ class Tags extends EventHandler { let changed = false; const tags = this._processArguments(args, true); - if (!tags.length) + if (!tags.length) { return changed; + } for (let i = 0; i < tags.length; i++) { - if (this._index[tags[i]]) + if (this._index[tags[i]]) { continue; + } changed = true; @@ -87,8 +89,9 @@ class Tags extends EventHandler { this.fire('add', tags[i], this._parent); } - if (changed) + if (changed) { this.fire('change', this._parent); + } return changed; } @@ -108,17 +111,20 @@ class Tags extends EventHandler { remove(...args) { let changed = false; - if (!this._list.length) + if (!this._list.length) { return changed; + } const tags = this._processArguments(args, true); - if (!tags.length) + if (!tags.length) { return changed; + } for (let i = 0; i < tags.length; i++) { - if (!this._index[tags[i]]) + if (!this._index[tags[i]]) { continue; + } changed = true; @@ -128,8 +134,9 @@ class Tags extends EventHandler { this.fire('remove', tags[i], this._parent); } - if (changed) + if (changed) { this.fire('change', this._parent); + } return changed; } @@ -141,15 +148,17 @@ class Tags extends EventHandler { * tags.clear(); */ clear() { - if (!this._list.length) + if (!this._list.length) { return; + } const tags = this._list.slice(0); this._list = []; this._index = { }; - for (let i = 0; i < tags.length; i++) + for (let i = 0; i < tags.length; i++) { this.fire('remove', tags[i], this._parent); + } this.fire('change', this._parent); } @@ -172,8 +181,9 @@ class Tags extends EventHandler { * tags.has(['ui', 'settings'], ['ui', 'levels']); // (ui AND settings) OR (ui AND levels) */ has(...query) { - if (!this._list.length) + if (!this._list.length) { return false; + } return this._has(this._processArguments(query)); } @@ -184,28 +194,32 @@ class Tags extends EventHandler { * @private */ _has(tags) { - if (!this._list.length || !tags.length) + if (!this._list.length || !tags.length) { return false; + } for (let i = 0; i < tags.length; i++) { if (tags[i].length === 1) { // single occurrence - if (this._index[tags[i][0]]) + if (this._index[tags[i][0]]) { return true; + } } else { // combined occurrence let multiple = true; for (let t = 0; t < tags[i].length; t++) { - if (this._index[tags[i][t]]) + if (this._index[tags[i][t]]) { continue; + } multiple = false; break; } - if (multiple) + if (multiple) { return true; + } } } @@ -231,17 +245,20 @@ class Tags extends EventHandler { const tags = []; let tmp = []; - if (!args || !args.length) + if (!args || !args.length) { return tags; + } for (let i = 0; i < args.length; i++) { if (args[i] instanceof Array) { - if (!flat) + if (!flat) { tmp = []; + } for (let t = 0; t < args[i].length; t++) { - if (typeof args[i][t] !== 'string') + if (typeof args[i][t] !== 'string') { continue; + } if (flat) { tags.push(args[i][t]); @@ -250,8 +267,9 @@ class Tags extends EventHandler { } } - if (!flat && tmp.length) + if (!flat && tmp.length) { tags.push(tmp); + } } else if (typeof args[i] === 'string') { if (flat) { tags.push(args[i]); diff --git a/src/core/uri.js b/src/core/uri.js index 531b13b56b4..efc029c7556 100644 --- a/src/core/uri.js +++ b/src/core/uri.js @@ -25,11 +25,11 @@ function createURI(options) { } if (options.scheme) { - s += options.scheme + ':'; + s += `${options.scheme}:`; } if (options.authority) { - s += '//' + options.authority; + s += `//${options.authority}`; } if (options.host) { @@ -45,18 +45,18 @@ function createURI(options) { } if (options.query) { - s += '?' + options.query; + s += `?${options.query}`; } if (options.fragment) { - s += '#' + options.fragment; + s += `#${options.fragment}`; } return s; } // See http://tools.ietf.org/html/rfc2396#appendix-B for details of RegExp -const re = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; +const re = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; /** * A URI object. @@ -122,21 +122,21 @@ class URI { let s = ''; if (this.scheme) { - s += this.scheme + ':'; + s += `${this.scheme}:`; } if (this.authority) { - s += '//' + this.authority; + s += `//${this.authority}`; } s += this.path; if (this.query) { - s += '?' + this.query; + s += `?${this.query}`; } if (this.fragment) { - s += '#' + this.fragment; + s += `#${this.fragment}`; } return s; @@ -188,7 +188,7 @@ class URI { if (q !== '') { q += '&'; } - q += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); + q += `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`; } } diff --git a/src/core/wasm-module.js b/src/core/wasm-module.js index efc44be0af8..c39909ee832 100644 --- a/src/core/wasm-module.js +++ b/src/core/wasm-module.js @@ -17,10 +17,11 @@ class Impl { // returns true if the running host supports wasm modules (all browsers except IE) static wasmSupported = cachedResult(() => { try { - if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") { + if (typeof WebAssembly === 'object' && typeof WebAssembly.instantiate === 'function') { const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00)); - if (module instanceof WebAssembly.Module) + if (module instanceof WebAssembly.Module) { return new WebAssembly.Instance(module) instanceof WebAssembly.Instance; + } } } catch (e) { } return false; diff --git a/src/deprecated/deprecated.js b/src/deprecated/deprecated.js index ebb90bae54f..762f4706062 100644 --- a/src/deprecated/deprecated.js +++ b/src/deprecated/deprecated.js @@ -1,9 +1,21 @@ import { Debug } from '../core/debug.js'; - import { Vec2 } from '../core/math/vec2.js'; import { Vec3 } from '../core/math/vec3.js'; import { Vec4 } from '../core/math/vec4.js'; - +import { AppBase } from '../framework/app-base.js'; +import { AssetRegistry } from '../framework/asset/asset-registry.js'; +import { ModelComponent } from '../framework/components/model/component.js'; +import { RigidBodyComponent } from '../framework/components/rigid-body/component.js'; +import { + BODYFLAG_KINEMATIC_OBJECT, BODYFLAG_NORESPONSE_OBJECT, BODYFLAG_STATIC_OBJECT, + BODYSTATE_ACTIVE_TAG, BODYSTATE_DISABLE_DEACTIVATION, BODYSTATE_DISABLE_SIMULATION, BODYSTATE_ISLAND_SLEEPING, BODYSTATE_WANTS_DEACTIVATION, + BODYTYPE_DYNAMIC, BODYTYPE_KINEMATIC, BODYTYPE_STATIC +} from '../framework/components/rigid-body/constants.js'; +import { RigidBodyComponentSystem } from '../framework/components/rigid-body/system.js'; +import { getApplication } from '../framework/globals.js'; +import { ElementInput } from '../framework/input/element-input.js'; +import { XrInputSource } from '../framework/xr/xr-input-source.js'; +import { BlendState } from '../platform/graphics/blend-state.js'; import { BLENDMODE_CONSTANT, BLENDMODE_ONE_MINUS_CONSTANT, PIXELFORMAT_LA8, PIXELFORMAT_RGB565, PIXELFORMAT_RGBA5551, PIXELFORMAT_RGBA4, PIXELFORMAT_RGB8, PIXELFORMAT_RGBA8, @@ -11,56 +23,37 @@ import { TEXTURETYPE_DEFAULT, TEXTURETYPE_RGBM, TEXTURETYPE_SWIZZLEGGGR, TYPE_INT8, TYPE_UINT8, TYPE_INT16, TYPE_UINT16, TYPE_INT32, TYPE_UINT32, TYPE_FLOAT32 } from '../platform/graphics/constants.js'; -import { drawQuadWithShader } from '../scene/graphics/quad-render-utils.js'; -import { shaderChunks } from '../scene/shader-lib/chunks/chunks.js'; +import { DepthState } from '../platform/graphics/depth-state.js'; import { GraphicsDevice } from '../platform/graphics/graphics-device.js'; -import { LayerComposition } from '../scene/composition/layer-composition.js'; import { RenderTarget } from '../platform/graphics/render-target.js'; import { Texture } from '../platform/graphics/texture.js'; import { VertexFormat } from '../platform/graphics/vertex-format.js'; -import { BlendState } from '../platform/graphics/blend-state.js'; -import { DepthState } from '../platform/graphics/depth-state.js'; - -import { CylinderGeometry } from '../scene/geometry/cylinder-geometry.js'; +import { MouseEvent } from '../platform/input/mouse-event.js'; +import { Batch } from '../scene/batching/batch.js'; +import { LayerComposition } from '../scene/composition/layer-composition.js'; import { BoxGeometry } from '../scene/geometry/box-geometry.js'; import { CapsuleGeometry } from '../scene/geometry/capsule-geometry.js'; import { ConeGeometry } from '../scene/geometry/cone-geometry.js'; +import { CylinderGeometry } from '../scene/geometry/cylinder-geometry.js'; +import { Geometry } from '../scene/geometry/geometry.js'; import { PlaneGeometry } from '../scene/geometry/plane-geometry.js'; import { SphereGeometry } from '../scene/geometry/sphere-geometry.js'; import { TorusGeometry } from '../scene/geometry/torus-geometry.js'; -import { ForwardRenderer } from '../scene/renderer/forward-renderer.js'; import { GraphNode } from '../scene/graph-node.js'; +import { drawQuadWithShader } from '../scene/graphics/quad-render-utils.js'; +import { Layer } from '../scene/layer.js'; +import { getDefaultMaterial } from '../scene/materials/default-material.js'; import { Material } from '../scene/materials/material.js'; +import { StandardMaterialOptions } from '../scene/materials/standard-material-options.js'; +import { StandardMaterial } from '../scene/materials/standard-material.js'; +import { MeshInstance } from '../scene/mesh-instance.js'; import { Mesh } from '../scene/mesh.js'; import { Morph } from '../scene/morph.js'; -import { MeshInstance } from '../scene/mesh-instance.js'; +import { ForwardRenderer } from '../scene/renderer/forward-renderer.js'; import { Scene } from '../scene/scene.js'; -import { StandardMaterial } from '../scene/materials/standard-material.js'; -import { Batch } from '../scene/batching/batch.js'; -import { getDefaultMaterial } from '../scene/materials/default-material.js'; -import { StandardMaterialOptions } from '../scene/materials/standard-material-options.js'; +import { shaderChunks } from '../scene/shader-lib/chunks/chunks.js'; import { LitShaderOptions } from '../scene/shader-lib/programs/lit-shader-options.js'; -import { Layer } from '../scene/layer.js'; - -import { AssetRegistry } from '../framework/asset/asset-registry.js'; - -import { XrInputSource } from '../framework/xr/xr-input-source.js'; - -import { ElementInput } from '../framework/input/element-input.js'; -import { MouseEvent } from '../platform/input/mouse-event.js'; - -import { AppBase } from '../framework/app-base.js'; -import { getApplication } from '../framework/globals.js'; -import { ModelComponent } from '../framework/components/model/component.js'; -import { - BODYFLAG_KINEMATIC_OBJECT, BODYFLAG_NORESPONSE_OBJECT, BODYFLAG_STATIC_OBJECT, - BODYSTATE_ACTIVE_TAG, BODYSTATE_DISABLE_DEACTIVATION, BODYSTATE_DISABLE_SIMULATION, BODYSTATE_ISLAND_SLEEPING, BODYSTATE_WANTS_DEACTIVATION, - BODYTYPE_DYNAMIC, BODYTYPE_KINEMATIC, BODYTYPE_STATIC -} from '../framework/components/rigid-body/constants.js'; -import { RigidBodyComponent } from '../framework/components/rigid-body/component.js'; -import { RigidBodyComponentSystem } from '../framework/components/rigid-body/system.js'; import { LitShader } from '../scene/shader-lib/programs/lit-shader.js'; -import { Geometry } from '../scene/geometry/geometry.js'; // CORE export const LINEBATCH_WORLD = 0; @@ -108,42 +101,42 @@ ContextCreationError.prototype = Error.prototype; const _viewport = new Vec4(); export function createSphere(device, opts) { - Debug.deprecated(`pc.createSphere is deprecated. Use 'pc.Mesh.fromGeometry(device, new SphereGeometry(options);' format instead.`); + Debug.deprecated('pc.createSphere is deprecated. Use \'pc.Mesh.fromGeometry(device, new SphereGeometry(options);\' format instead.'); return Mesh.fromGeometry(device, new SphereGeometry(opts)); } export function createPlane(device, opts) { - Debug.deprecated(`pc.createPlane is deprecated. Use 'pc.Mesh.fromGeometry(device, new PlaneGeometry(options);' format instead.`); + Debug.deprecated('pc.createPlane is deprecated. Use \'pc.Mesh.fromGeometry(device, new PlaneGeometry(options);\' format instead.'); return Mesh.fromGeometry(device, new PlaneGeometry(opts)); } export function createBox(device, opts) { - Debug.deprecated(`pc.createBox is deprecated. Use 'pc.Mesh.fromGeometry(device, new BoxGeometry(options);' format instead.`); + Debug.deprecated('pc.createBox is deprecated. Use \'pc.Mesh.fromGeometry(device, new BoxGeometry(options);\' format instead.'); return Mesh.fromGeometry(device, new BoxGeometry(opts)); } export function createTorus(device, opts) { - Debug.deprecated(`pc.createTorus is deprecated. Use 'pc.Mesh.fromGeometry(device, new TorusGeometry(options);' format instead.`); + Debug.deprecated('pc.createTorus is deprecated. Use \'pc.Mesh.fromGeometry(device, new TorusGeometry(options);\' format instead.'); return Mesh.fromGeometry(device, new TorusGeometry(opts)); } export function createCapsule(device, opts) { - Debug.deprecated(`pc.createCapsule is deprecated. Use 'pc.Mesh.fromGeometry(device, new CapsuleGeometry(options);' format instead.`); + Debug.deprecated('pc.createCapsule is deprecated. Use \'pc.Mesh.fromGeometry(device, new CapsuleGeometry(options);\' format instead.'); return Mesh.fromGeometry(device, new CapsuleGeometry(opts)); } export function createCone(device, opts) { - Debug.deprecated(`pc.createCone is deprecated. Use 'pc.Mesh.fromGeometry(device, new ConeGeometry(options);' format instead.`); + Debug.deprecated('pc.createCone is deprecated. Use \'pc.Mesh.fromGeometry(device, new ConeGeometry(options);\' format instead.'); return Mesh.fromGeometry(device, new ConeGeometry(opts)); } export function createCylinder(device, opts) { - Debug.deprecated(`pc.createCylinder is deprecated. Use 'pc.Mesh.fromGeometry(device, new CylinderGeometry(options);' format instead.`); + Debug.deprecated('pc.createCylinder is deprecated. Use \'pc.Mesh.fromGeometry(device, new CylinderGeometry(options);\' format instead.'); return Mesh.fromGeometry(device, new CylinderGeometry(opts)); } export function createMesh(device, positions, opts = {}) { - Debug.deprecated(`pc.createMesh is deprecated. Use 'pc.Mesh.fromGeometry(device, new Geometry();' format instead.`); + Debug.deprecated('pc.createMesh is deprecated. Use \'pc.Mesh.fromGeometry(device, new Geometry();\' format instead.'); const geom = new Geometry(); geom.positions = positions; @@ -161,7 +154,7 @@ export function createMesh(device, positions, opts = {}) { export function drawFullscreenQuad(device, target, vertexBuffer, shader, rect) { - Debug.deprecated(`pc.drawFullscreenQuad is deprecated. When used as part of PostEffect, use PostEffect#drawQuad instead.`); + Debug.deprecated('pc.drawFullscreenQuad is deprecated. When used as part of PostEffect, use PostEffect#drawQuad instead.'); // convert rect in normalized space to viewport in pixel space let viewport; @@ -216,8 +209,9 @@ Object.keys(deprecatedChunks).forEach((chunkName) => { */ function compatibilityForLitArgs(src) { if (src.includes('litShaderArgs')) { - src = src.replace(/litShaderArgs([\.a-zA-Z]+)+/g, (a, b) => { - const newSource = 'litArgs' + b.replace(/\./g, '_'); + // eslint-disable-next-line regexp/no-misleading-capturing-group + src = src.replace(/litShaderArgs([.a-zA-Z]+)+/g, (a, b) => { + const newSource = `litArgs${b.replace(/\./g, '_')}`; Debug.deprecated(`Nested struct property access is deprecated, because it's crashing some devices. Please update your custom chunks manually. In particular ${a} should be ${newSource} now.`); return newSource; }); @@ -393,7 +387,7 @@ const _tempBlendState = new BlendState(); const _tempDepthState = new DepthState(); GraphicsDevice.prototype.setBlendFunction = function (blendSrc, blendDst) { - Debug.deprecated(`pc.GraphicsDevice#setBlendFunction is deprecated, use pc.GraphicsDevice.setBlendState instead.`); + Debug.deprecated('pc.GraphicsDevice#setBlendFunction is deprecated, use pc.GraphicsDevice.setBlendState instead.'); const currentBlendState = this.blendState; _tempBlendState.copy(currentBlendState); _tempBlendState.setColorBlend(currentBlendState.colorOp, blendSrc, blendDst); @@ -402,7 +396,7 @@ GraphicsDevice.prototype.setBlendFunction = function (blendSrc, blendDst) { }; GraphicsDevice.prototype.setBlendFunctionSeparate = function (blendSrc, blendDst, blendSrcAlpha, blendDstAlpha) { - Debug.deprecated(`pc.GraphicsDevice#setBlendFunctionSeparate is deprecated, use pc.GraphicsDevice.setBlendState instead.`); + Debug.deprecated('pc.GraphicsDevice#setBlendFunctionSeparate is deprecated, use pc.GraphicsDevice.setBlendState instead.'); const currentBlendState = this.blendState; _tempBlendState.copy(currentBlendState); _tempBlendState.setColorBlend(currentBlendState.colorOp, blendSrc, blendDst); @@ -411,7 +405,7 @@ GraphicsDevice.prototype.setBlendFunctionSeparate = function (blendSrc, blendDst }; GraphicsDevice.prototype.setBlendEquation = function (blendEquation) { - Debug.deprecated(`pc.GraphicsDevice#setBlendEquation is deprecated, use pc.GraphicsDevice.setBlendState instead.`); + Debug.deprecated('pc.GraphicsDevice#setBlendEquation is deprecated, use pc.GraphicsDevice.setBlendState instead.'); const currentBlendState = this.blendState; _tempBlendState.copy(currentBlendState); _tempBlendState.setColorBlend(blendEquation, currentBlendState.colorSrcFactor, currentBlendState.colorDstFactor); @@ -420,7 +414,7 @@ GraphicsDevice.prototype.setBlendEquation = function (blendEquation) { }; GraphicsDevice.prototype.setBlendEquationSeparate = function (blendEquation, blendAlphaEquation) { - Debug.deprecated(`pc.GraphicsDevice#setBlendEquationSeparate is deprecated, use pc.GraphicsDevice.setBlendState instead.`); + Debug.deprecated('pc.GraphicsDevice#setBlendEquationSeparate is deprecated, use pc.GraphicsDevice.setBlendState instead.'); const currentBlendState = this.blendState; _tempBlendState.copy(currentBlendState); _tempBlendState.setColorBlend(blendEquation, currentBlendState.colorSrcFactor, currentBlendState.colorDstFactor); @@ -429,7 +423,7 @@ GraphicsDevice.prototype.setBlendEquationSeparate = function (blendEquation, ble }; GraphicsDevice.prototype.setColorWrite = function (redWrite, greenWrite, blueWrite, alphaWrite) { - Debug.deprecated(`pc.GraphicsDevice#setColorWrite is deprecated, use pc.GraphicsDevice.setBlendState instead.`); + Debug.deprecated('pc.GraphicsDevice#setColorWrite is deprecated, use pc.GraphicsDevice.setBlendState instead.'); const currentBlendState = this.blendState; _tempBlendState.copy(currentBlendState); _tempBlendState.setColorWrite(redWrite, greenWrite, blueWrite, alphaWrite); @@ -441,28 +435,28 @@ GraphicsDevice.prototype.getBlending = function () { }; GraphicsDevice.prototype.setBlending = function (blending) { - Debug.deprecated(`pc.GraphicsDevice#setBlending is deprecated, use pc.GraphicsDevice.setBlendState instead.`); + Debug.deprecated('pc.GraphicsDevice#setBlending is deprecated, use pc.GraphicsDevice.setBlendState instead.'); _tempBlendState.copy(this.blendState); _tempBlendState.blend = blending; this.setBlendState(_tempBlendState); }; GraphicsDevice.prototype.setDepthWrite = function (write) { - Debug.deprecated(`pc.GraphicsDevice#setDepthWrite is deprecated, use pc.GraphicsDevice.setDepthState instead.`); + Debug.deprecated('pc.GraphicsDevice#setDepthWrite is deprecated, use pc.GraphicsDevice.setDepthState instead.'); _tempDepthState.copy(this.depthState); _tempDepthState.write = write; this.setDepthState(_tempDepthState); }; GraphicsDevice.prototype.setDepthFunc = function (func) { - Debug.deprecated(`pc.GraphicsDevice#setDepthFunc is deprecated, use pc.GraphicsDevice.setDepthState instead.`); + Debug.deprecated('pc.GraphicsDevice#setDepthFunc is deprecated, use pc.GraphicsDevice.setDepthState instead.'); _tempDepthState.copy(this.depthState); _tempDepthState.func = func; this.setDepthState(_tempDepthState); }; GraphicsDevice.prototype.setDepthTest = function (test) { - Debug.deprecated(`pc.GraphicsDevice#setDepthTest is deprecated, use pc.GraphicsDevice.setDepthState instead.`); + Debug.deprecated('pc.GraphicsDevice#setDepthTest is deprecated, use pc.GraphicsDevice.setDepthState instead.'); _tempDepthState.copy(this.depthState); _tempDepthState.test = test; this.setDepthState(_tempDepthState); @@ -545,7 +539,7 @@ Object.defineProperty(Scene.prototype, 'models', { Object.defineProperty(Layer.prototype, 'renderTarget', { set: function (rt) { - Debug.deprecated(`pc.Layer#renderTarget is deprecated. Set the render target on the camera instead.`); + Debug.deprecated('pc.Layer#renderTarget is deprecated. Set the render target on the camera instead.'); this._renderTarget = rt; this._dirtyComposition = true; }, @@ -614,10 +608,10 @@ GraphNode.prototype.setName = function (name) { Object.defineProperty(Material.prototype, 'shader', { set: function (value) { - Debug.deprecated(`pc.Material#shader is deprecated, use pc.ShaderMaterial instead.`); + Debug.deprecated('pc.Material#shader is deprecated, use pc.ShaderMaterial instead.'); }, get: function () { - Debug.deprecated(`pc.Material#shader is deprecated, use pc.ShaderMaterial instead.`); + Debug.deprecated('pc.Material#shader is deprecated, use pc.ShaderMaterial instead.'); return null; } }); @@ -625,7 +619,7 @@ Object.defineProperty(Material.prototype, 'shader', { // Note: this is used by the Editor Object.defineProperty(Material.prototype, 'blend', { set: function (value) { - Debug.deprecated(`pc.Material#blend is deprecated, use pc.Material.blendState.`); + Debug.deprecated('pc.Material#blend is deprecated, use pc.Material.blendState.'); this.blendState.blend = value; }, get: function () { diff --git a/src/extras/exporters/core-exporter.js b/src/extras/exporters/core-exporter.js index 2516b08538e..7465742df6a 100644 --- a/src/extras/exporters/core-exporter.js +++ b/src/extras/exporters/core-exporter.js @@ -1,9 +1,9 @@ -import { createShaderFromCode } from '../../scene/shader-lib/utils.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { BlendState } from '../../platform/graphics/blend-state.js'; -import { drawQuadWithShader } from '../../scene/graphics/quad-render-utils.js'; -import { RenderTarget } from '../../platform/graphics/render-target.js'; import { FILTER_LINEAR, ADDRESS_CLAMP_TO_EDGE, isCompressedPixelFormat, PIXELFORMAT_RGBA8 } from '../../platform/graphics/constants.js'; +import { RenderTarget } from '../../platform/graphics/render-target.js'; +import { Texture } from '../../platform/graphics/texture.js'; +import { drawQuadWithShader } from '../../scene/graphics/quad-render-utils.js'; +import { createShaderFromCode } from '../../scene/shader-lib/utils.js'; /** * @import { Color } from '../../core/math/color.js' diff --git a/src/extras/exporters/gltf-exporter.js b/src/extras/exporters/gltf-exporter.js index a2ee2bfa5bc..3eec723238f 100644 --- a/src/extras/exporters/gltf-exporter.js +++ b/src/extras/exporters/gltf-exporter.js @@ -1,9 +1,9 @@ import { CoreExporter } from './core-exporter.js'; +import { Color } from '../../core/math/color.js'; import { math } from '../../core/math/math.js'; +import { Quat } from '../../core/math/quat.js'; import { Vec2 } from '../../core/math/vec2.js'; import { Vec3 } from '../../core/math/vec3.js'; -import { Quat } from '../../core/math/quat.js'; -import { Color } from '../../core/math/color.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; import { CULLFACE_NONE, @@ -19,8 +19,8 @@ import { } from '../../platform/graphics/constants.js'; import { IndexBuffer } from '../../platform/graphics/index-buffer.js'; import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; -import { StandardMaterial } from '../../scene/materials/standard-material.js'; import { BLEND_NONE, BLEND_NORMAL, PROJECTION_ORTHOGRAPHIC } from '../../scene/constants.js'; +import { StandardMaterial } from '../../scene/materials/standard-material.js'; /** * @import { Entity } from '../../framework/entity.js' @@ -626,41 +626,41 @@ class GltfExporter extends CoreExporter { promises.push( this.getBlob(canvas, mimeType) - .then((blob) => { - const reader = new FileReader(); - reader.readAsArrayBuffer(blob); - - return new Promise((resolve) => { - reader.onloadend = () => { - resolve(reader); - }; - }); - }) - .then((reader) => { - const buffer = this.getPaddedArrayBuffer(reader.result); - - GltfExporter.writeBufferView(resources, json, buffer); - resources.buffers.push(buffer); - - const bufferView = resources.bufferViewMap.get(buffer); - - json.images[i] = { - mimeType: mimeType, - bufferView: bufferView[0] - }; + .then((blob) => { + const reader = new FileReader(); + reader.readAsArrayBuffer(blob); - json.samplers[i] = { - minFilter: getFilter(texture.minFilter), - magFilter: getFilter(texture.magFilter), - wrapS: getWrap(texture.addressU), - wrapT: getWrap(texture.addressV) + return new Promise((resolve) => { + reader.onloadend = () => { + resolve(reader); }; + }); + }) + .then((reader) => { + const buffer = this.getPaddedArrayBuffer(reader.result); - json.textures[i] = { - sampler: i, - source: i - }; - }) + GltfExporter.writeBufferView(resources, json, buffer); + resources.buffers.push(buffer); + + const bufferView = resources.bufferViewMap.get(buffer); + + json.images[i] = { + mimeType: mimeType, + bufferView: bufferView[0] + }; + + json.samplers[i] = { + minFilter: getFilter(texture.minFilter), + magFilter: getFilter(texture.magFilter), + wrapS: getWrap(texture.addressU), + wrapT: getWrap(texture.addressV) + }; + + json.textures[i] = { + sampler: i, + source: i + }; + }) ); } diff --git a/src/extras/exporters/usdz-exporter.js b/src/extras/exporters/usdz-exporter.js index df923f50ea7..2ea9ade4758 100644 --- a/src/extras/exporters/usdz-exporter.js +++ b/src/extras/exporters/usdz-exporter.js @@ -1,13 +1,13 @@ -import { CoreExporter } from "./core-exporter.js"; import { zipSync, strToU8 } from 'fflate'; -import { Color } from '../../core/math/color.js'; +import { CoreExporter } from './core-exporter.js'; +import { Color } from '../../core/math/color.js'; import { SEMANTIC_POSITION, SEMANTIC_NORMAL, SEMANTIC_TEXCOORD0, SEMANTIC_TEXCOORD1 -} from "../../platform/graphics/constants.js"; +} from '../../platform/graphics/constants.js'; /** * @import { Entity } from '../../framework/entity.js' @@ -162,7 +162,7 @@ class UsdzExporter extends CoreExporter { // find all mesh instances const allMeshInstances = []; if (entity) { - const renders = entity.findComponents("render"); + const renders = entity.findComponents('render'); renders.forEach((render) => { allMeshInstances.push(...render.meshInstances); }); @@ -265,7 +265,7 @@ class UsdzExporter extends CoreExporter { getFileIds(category, name, ref, extension = 'usda') { // filename inside the zip archive - const fileName = (category ? `${category}/` : '') + `${name}.${extension}`; + const fileName = `${category ? `${category}/` : ''}${name}.${extension}`; // string representing a reference to the file and the refName object inside it const refName = `@./${fileName}@`; @@ -282,7 +282,7 @@ class UsdzExporter extends CoreExporter { // prepare the content with the header let contentU8 = null; if (content) { - content = header + '\n' + content; + content = `${header}\n${content}`; contentU8 = strToU8(content); } @@ -400,7 +400,7 @@ class UsdzExporter extends CoreExporter { const textureIds = this.getTextureFileIds(texture); this.textureMap.set(texture, textureIds.refName); - const channel = material[textureSlot + 'Channel'] || 'rgb'; + const channel = material[`${textureSlot}Channel`] || 'rgb'; const textureValue = materialPropertyPath(`/${textureIds.name}_${valueName}.outputs:${channel}`); inputs.push(materialValueTemplate(propType, `${propName}.connect`, textureValue)); @@ -411,12 +411,12 @@ class UsdzExporter extends CoreExporter { } } - const tiling = material[textureSlot + 'Tiling']; - const offset = material[textureSlot + 'Offset']; - const rotation = material[textureSlot + 'Rotation']; + const tiling = material[`${textureSlot}Tiling`]; + const offset = material[`${textureSlot}Offset`]; + const rotation = material[`${textureSlot}Rotation`]; // which texture coordinate set to use - const uvChannel = material[textureSlot + 'Uv'] === 1 ? 'st1' : 'st'; + const uvChannel = material[`${textureSlot}Uv`] === 1 ? 'st1' : 'st'; // texture tint const tintColor = tintTexture && uniform ? uniform : Color.WHITE; @@ -500,8 +500,9 @@ ${inputs.join('\n')} // face indices if no index buffer if (!indices.length) { - for (let i = 0; i < indicesCount; i++) + for (let i = 0; i < indicesCount; i++) { indices[i] = i; + } } // missing normals or uvs diff --git a/src/extras/gizmo/axis-shapes.js b/src/extras/gizmo/axis-shapes.js index e9733e4adc7..925efea5831 100644 --- a/src/extras/gizmo/axis-shapes.js +++ b/src/extras/gizmo/axis-shapes.js @@ -1,21 +1,20 @@ +import { COLOR_GRAY } from './color.js'; +import { TriData } from './tri-data.js'; import { Color } from '../../core/math/color.js'; -import { Vec3 } from '../../core/math/vec3.js'; import { Quat } from '../../core/math/quat.js'; -import { ShaderMaterial } from '../../scene/materials/shader-material.js'; -import { MeshInstance } from '../../scene/mesh-instance.js'; +import { Vec3 } from '../../core/math/vec3.js'; import { Entity } from '../../framework/entity.js'; import { CULLFACE_NONE, CULLFACE_BACK, SEMANTIC_POSITION, SEMANTIC_COLOR } from '../../platform/graphics/constants.js'; import { BLEND_NORMAL } from '../../scene/constants.js'; - -import { COLOR_GRAY } from './color.js'; -import { TriData } from './tri-data.js'; -import { Mesh } from '../../scene/mesh.js'; import { BoxGeometry } from '../../scene/geometry/box-geometry.js'; -import { CylinderGeometry } from '../../scene/geometry/cylinder-geometry.js'; import { ConeGeometry } from '../../scene/geometry/cone-geometry.js'; +import { CylinderGeometry } from '../../scene/geometry/cylinder-geometry.js'; import { PlaneGeometry } from '../../scene/geometry/plane-geometry.js'; import { SphereGeometry } from '../../scene/geometry/sphere-geometry.js'; import { TorusGeometry } from '../../scene/geometry/torus-geometry.js'; +import { ShaderMaterial } from '../../scene/materials/shader-material.js'; +import { MeshInstance } from '../../scene/mesh-instance.js'; +import { Mesh } from '../../scene/mesh.js'; // constants const SHADOW_DAMP_SCALE = 0.25; @@ -196,7 +195,7 @@ class AxisShape { } _createRoot(name) { - this.entity = new Entity(name + ':' + this.axis); + this.entity = new Entity(`${name}:${this.axis}`); this._updateRootTransform(); } @@ -332,13 +331,13 @@ class AxisArrow extends AxisShape { this._createRoot('arrow'); // head - this._head = new Entity('head:' + this.axis); + this._head = new Entity(`head:${this.axis}`); this.entity.addChild(this._head); this._updateHead(); this._addRenderShadowMesh(this._head, 'cone'); // line - this._line = new Entity('line:' + this.axis); + this._line = new Entity(`line:${this.axis}`); this.entity.addChild(this._line); this._updateLine(); this._addRenderShadowMesh(this._line, 'cylinder'); @@ -489,13 +488,13 @@ class AxisBoxLine extends AxisShape { this._createRoot('boxLine'); // box - this._box = new Entity('box:' + this.axis); + this._box = new Entity(`box:${this.axis}`); this.entity.addChild(this._box); this._updateBox(); this._addRenderShadowMesh(this._box, 'box'); // line - this._line = new Entity('line:' + this.axis); + this._line = new Entity(`line:${this.axis}`); this.entity.addChild(this._line); this._updateLine(); this._addRenderShadowMesh(this._line, 'cylinder'); diff --git a/src/extras/gizmo/gizmo.js b/src/extras/gizmo/gizmo.js index aa65cf53976..4e6ecb3766d 100644 --- a/src/extras/gizmo/gizmo.js +++ b/src/extras/gizmo/gizmo.js @@ -1,12 +1,11 @@ +import { GIZMOSPACE_LOCAL, GIZMOSPACE_WORLD } from './constants.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { Mat4 } from '../../core/math/mat4.js'; import { math } from '../../core/math/math.js'; import { Vec3 } from '../../core/math/vec3.js'; -import { Mat4 } from '../../core/math/mat4.js'; import { Ray } from '../../core/shape/ray.js'; -import { EventHandler } from '../../core/event-handler.js'; -import { PROJECTION_PERSPECTIVE } from '../../scene/constants.js'; import { Entity } from '../../framework/entity.js'; - -import { GIZMOSPACE_LOCAL, GIZMOSPACE_WORLD } from './constants.js'; +import { PROJECTION_PERSPECTIVE } from '../../scene/constants.js'; /** * @import { AppBase } from '../../framework/app-base.js' diff --git a/src/extras/gizmo/rotate-gizmo.js b/src/extras/gizmo/rotate-gizmo.js index 064318672a3..df11c7dcb36 100644 --- a/src/extras/gizmo/rotate-gizmo.js +++ b/src/extras/gizmo/rotate-gizmo.js @@ -1,14 +1,13 @@ -import { math } from '../../core/math/math.js'; +import { AxisDisk } from './axis-shapes.js'; +import { GIZMOSPACE_LOCAL, GIZMOAXIS_FACE, GIZMOAXIS_X, GIZMOAXIS_Y, GIZMOAXIS_Z } from './constants.js'; +import { TransformGizmo } from './transform-gizmo.js'; import { Color } from '../../core/math/color.js'; -import { Quat } from '../../core/math/quat.js'; import { Mat4 } from '../../core/math/mat4.js'; +import { math } from '../../core/math/math.js'; +import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; import { PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE } from '../../scene/constants.js'; -import { AxisDisk } from './axis-shapes.js'; -import { GIZMOSPACE_LOCAL, GIZMOAXIS_FACE, GIZMOAXIS_X, GIZMOAXIS_Y, GIZMOAXIS_Z } from './constants.js'; -import { TransformGizmo } from './transform-gizmo.js'; - /** * @import { AppBase } from '../../framework/app-base.js' * @import { CameraComponent } from '../../framework/components/camera/component.js' @@ -174,7 +173,7 @@ class RotateGizmo extends TransformGizmo { if (this._dragging) { const gizmoPos = this.root.getPosition(); this._drawGuideAngleLine(gizmoPos, this._selectedAxis, - this._guideAngleStart, this._guideAngleStartColor); + this._guideAngleStart, this._guideAngleStartColor); this._drawGuideAngleLine(gizmoPos, this._selectedAxis, this._guideAngleEnd); } }); diff --git a/src/extras/gizmo/scale-gizmo.js b/src/extras/gizmo/scale-gizmo.js index 572acb326cf..79ed2049c97 100644 --- a/src/extras/gizmo/scale-gizmo.js +++ b/src/extras/gizmo/scale-gizmo.js @@ -1,9 +1,8 @@ -import { Vec3 } from '../../core/math/vec3.js'; -import { Quat } from '../../core/math/quat.js'; - import { AxisBoxCenter, AxisBoxLine, AxisPlane } from './axis-shapes.js'; import { GIZMOSPACE_LOCAL, GIZMOAXIS_X, GIZMOAXIS_XYZ, GIZMOAXIS_Y, GIZMOAXIS_Z } from './constants.js'; import { TransformGizmo } from './transform-gizmo.js'; +import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; /** * @import { AppBase } from '../../framework/app-base.js' diff --git a/src/extras/gizmo/transform-gizmo.js b/src/extras/gizmo/transform-gizmo.js index dca4281623f..92c1dc5908e 100644 --- a/src/extras/gizmo/transform-gizmo.js +++ b/src/extras/gizmo/transform-gizmo.js @@ -1,11 +1,3 @@ -import { math } from '../../core/math/math.js'; -import { Color } from '../../core/math/color.js'; -import { Quat } from '../../core/math/quat.js'; -import { Vec3 } from '../../core/math/vec3.js'; -import { Ray } from '../../core/shape/ray.js'; -import { Plane } from '../../core/shape/plane.js'; -import { PROJECTION_PERSPECTIVE } from '../../scene/constants.js'; - import { COLOR_RED, COLOR_GREEN, @@ -17,6 +9,13 @@ import { } from './color.js'; import { GIZMOAXIS_X, GIZMOAXIS_XYZ, GIZMOAXIS_Y, GIZMOAXIS_Z } from './constants.js'; import { Gizmo } from './gizmo.js'; +import { Color } from '../../core/math/color.js'; +import { math } from '../../core/math/math.js'; +import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; +import { Plane } from '../../core/shape/plane.js'; +import { Ray } from '../../core/shape/ray.js'; +import { PROJECTION_PERSPECTIVE } from '../../scene/constants.js'; /** * @import { AppBase } from '../../framework/app-base.js' @@ -465,7 +464,7 @@ class TransformGizmo extends Gizmo { if (!meshInstance) { return ''; } - return meshInstance.node.name.split(":")[1]; + return meshInstance.node.name.split(':')[1]; } /** diff --git a/src/extras/gizmo/translate-gizmo.js b/src/extras/gizmo/translate-gizmo.js index b0f3bc6ba35..d5d29a68853 100644 --- a/src/extras/gizmo/translate-gizmo.js +++ b/src/extras/gizmo/translate-gizmo.js @@ -1,6 +1,3 @@ -import { Vec3 } from '../../core/math/vec3.js'; -import { Quat } from '../../core/math/quat.js'; - import { AxisArrow, AxisPlane, AxisSphereCenter } from './axis-shapes.js'; import { GIZMOSPACE_LOCAL, @@ -10,6 +7,8 @@ import { GIZMOAXIS_Z } from './constants.js'; import { TransformGizmo } from './transform-gizmo.js'; +import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; /** * @import { AppBase } from '../../framework/app-base.js' diff --git a/src/extras/gizmo/tri-data.js b/src/extras/gizmo/tri-data.js index b4da0fdf677..2997a779f87 100644 --- a/src/extras/gizmo/tri-data.js +++ b/src/extras/gizmo/tri-data.js @@ -1,6 +1,6 @@ -import { Vec3 } from '../../core/math/vec3.js'; -import { Quat } from '../../core/math/quat.js'; import { Mat4 } from '../../core/math/mat4.js'; +import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; import { Tri } from '../../core/shape/tri.js'; import { Geometry } from '../../scene/geometry/geometry.js'; diff --git a/src/extras/index.js b/src/extras/index.js index 1f344381234..288b8fb16b1 100644 --- a/src/extras/index.js +++ b/src/extras/index.js @@ -32,9 +32,9 @@ export { GIZMOAXIS_YZ, GIZMOAXIS_XYZ, GIZMOAXIS_FACE -} from "./gizmo/constants.js"; -export { Gizmo } from "./gizmo/gizmo.js"; -export { TransformGizmo } from "./gizmo/transform-gizmo.js"; -export { TranslateGizmo } from "./gizmo/translate-gizmo.js"; -export { RotateGizmo } from "./gizmo/rotate-gizmo.js"; -export { ScaleGizmo } from "./gizmo/scale-gizmo.js"; +} from './gizmo/constants.js'; +export { Gizmo } from './gizmo/gizmo.js'; +export { TransformGizmo } from './gizmo/transform-gizmo.js'; +export { TranslateGizmo } from './gizmo/translate-gizmo.js'; +export { RotateGizmo } from './gizmo/rotate-gizmo.js'; +export { ScaleGizmo } from './gizmo/scale-gizmo.js'; diff --git a/src/extras/mini-stats/graph.js b/src/extras/mini-stats/graph.js index 58db419b733..890bc9bf44e 100644 --- a/src/extras/mini-stats/graph.js +++ b/src/extras/mini-stats/graph.js @@ -83,11 +83,11 @@ class Graph { render(render2d, x, y, w, h) { render2d.quad(x + w, y, -w, h, - this.enabled ? this.cursor : 0, - this.enabled ? 0.5 + this.yOffset : this.texture.height - 1, - -w, 0, - this.texture, - 0); + this.enabled ? this.cursor : 0, + this.enabled ? 0.5 + this.yOffset : this.texture.height - 1, + -w, 0, + this.texture, + 0); } } diff --git a/src/extras/mini-stats/mini-stats.js b/src/extras/mini-stats/mini-stats.js index f01b78fe211..9aa87bcb182 100644 --- a/src/extras/mini-stats/mini-stats.js +++ b/src/extras/mini-stats/mini-stats.js @@ -1,13 +1,13 @@ -import { math } from '../../core/math/math.js'; -import { Texture } from '../../platform/graphics/texture.js'; -import { ADDRESS_REPEAT, FILTER_NEAREST } from '../../platform/graphics/constants.js'; -import { LAYERID_UI } from '../../scene/constants.js'; import { CpuTimer } from './cpu-timer.js'; import { GpuTimer } from './gpu-timer.js'; -import { StatsTimer } from './stats-timer.js'; import { Graph } from './graph.js'; -import { WordAtlas } from './word-atlas.js'; import { Render2d } from './render2d.js'; +import { StatsTimer } from './stats-timer.js'; +import { WordAtlas } from './word-atlas.js'; +import { math } from '../../core/math/math.js'; +import { ADDRESS_REPEAT, FILTER_NEAREST } from '../../platform/graphics/constants.js'; +import { Texture } from '../../platform/graphics/texture.js'; +import { LAYERID_UI } from '../../scene/constants.js'; /** * @import { AppBase } from '../../framework/app-base.js' @@ -64,9 +64,9 @@ class MiniStats { // extract list of words const words = new Set( ['', 'ms', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'] - .concat(this.graphs.map(graph => graph.name)) - .concat(options.stats ? options.stats.map(stat => stat.unitsName) : []) - .filter(item => !!item) + .concat(this.graphs.map(graph => graph.name)) + .concat(options.stats ? options.stats.map(stat => stat.unitsName) : []) + .filter(item => !!item) ); this.wordAtlas = new WordAtlas(device, words); @@ -408,10 +408,10 @@ class MiniStats { */ updateDiv() { const rect = this.device.canvas.getBoundingClientRect(); - this.div.style.left = rect.left + 'px'; - this.div.style.bottom = (window.innerHeight - rect.bottom) + 'px'; - this.div.style.width = this.width + 'px'; - this.div.style.height = this.overallHeight + 'px'; + this.div.style.left = `${rect.left}px`; + this.div.style.bottom = `${window.innerHeight - rect.bottom}px`; + this.div.style.width = `${this.width}px`; + this.div.style.height = `${this.overallHeight}px`; } /** diff --git a/src/extras/mini-stats/render2d.js b/src/extras/mini-stats/render2d.js index 5c775ad4096..3b95d7b2751 100644 --- a/src/extras/mini-stats/render2d.js +++ b/src/extras/mini-stats/render2d.js @@ -1,3 +1,4 @@ +import { BlendState } from '../../platform/graphics/blend-state.js'; import { BLENDEQUATION_ADD, BLENDMODE_SRC_ALPHA, BLENDMODE_ONE_MINUS_SRC_ALPHA, BLENDMODE_ONE, BUFFER_STATIC, @@ -10,14 +11,13 @@ import { TYPE_FLOAT32 } from '../../platform/graphics/constants.js'; import { DepthState } from '../../platform/graphics/depth-state.js'; -import { BlendState } from '../../platform/graphics/blend-state.js'; -import { GraphNode } from '../../scene/graph-node.js'; -import { MeshInstance } from '../../scene/mesh-instance.js'; -import { Mesh } from '../../scene/mesh.js'; import { IndexBuffer } from '../../platform/graphics/index-buffer.js'; import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; import { VertexFormat } from '../../platform/graphics/vertex-format.js'; +import { GraphNode } from '../../scene/graph-node.js'; import { ShaderMaterial } from '../../scene/materials/shader-material.js'; +import { MeshInstance } from '../../scene/mesh-instance.js'; +import { Mesh } from '../../scene/mesh.js'; const vertexShader = /* glsl */ ` attribute vec3 vertex_position; // unnormalized xy, word flag @@ -109,7 +109,7 @@ class Render2d { material.cull = CULLFACE_NONE; material.depthState = DepthState.NODEPTH; material.blendState = new BlendState(true, BLENDEQUATION_ADD, BLENDMODE_SRC_ALPHA, BLENDMODE_ONE_MINUS_SRC_ALPHA, - BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ONE); + BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ONE); material.update(); this.meshInstance = new MeshInstance(this.mesh, material, new GraphNode('MiniStatsMesh')); diff --git a/src/extras/mini-stats/stats-timer.js b/src/extras/mini-stats/stats-timer.js index c9d301fc968..7927ade9959 100644 --- a/src/extras/mini-stats/stats-timer.js +++ b/src/extras/mini-stats/stats-timer.js @@ -6,8 +6,9 @@ class StatsTimer { // supporting up to 3 stats this.statNames = statNames; - if (this.statNames.length > 3) + if (this.statNames.length > 3) { this.statNames.length = 3; + } this.unitsName = unitsName; this.decimalPlaces = decimalPlaces; diff --git a/src/extras/mini-stats/word-atlas.js b/src/extras/mini-stats/word-atlas.js index 70aaa5305d1..8c25ccc63cd 100644 --- a/src/extras/mini-stats/word-atlas.js +++ b/src/extras/mini-stats/word-atlas.js @@ -1,6 +1,6 @@ import { math } from '../../core/math/math.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { FILTER_NEAREST } from '../../platform/graphics/constants.js'; +import { Texture } from '../../platform/graphics/texture.js'; class WordAtlas { constructor(device, words) { @@ -95,14 +95,14 @@ class WordAtlas { if (p) { const padding = 1; render2d.quad(x + p.l - padding, - y - p.d + padding, - p.w + padding * 2, - p.h + padding * 2, - p.x - padding, - this.texture.height - p.y - p.h - padding, - undefined, undefined, - this.texture, - 1); + y - p.d + padding, + p.w + padding * 2, + p.h + padding * 2, + p.x - padding, + this.texture.height - p.y - p.h - padding, + undefined, undefined, + this.texture, + 1); return p.w; } return 0; diff --git a/src/extras/render-passes/render-pass-bloom.js b/src/extras/render-passes/render-pass-bloom.js index 53019903473..3e1379bf9d3 100644 --- a/src/extras/render-passes/render-pass-bloom.js +++ b/src/extras/render-passes/render-pass-bloom.js @@ -1,12 +1,12 @@ +import { RenderPassDownsample } from './render-pass-downsample.js'; +import { RenderPassUpsample } from './render-pass-upsample.js'; import { Color } from '../../core/math/color.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { BlendState } from '../../platform/graphics/blend-state.js'; -import { RenderTarget } from '../../platform/graphics/render-target.js'; -import { RenderPass } from '../../platform/graphics/render-pass.js'; import { FILTER_LINEAR, ADDRESS_CLAMP_TO_EDGE } from '../../platform/graphics/constants.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; +import { RenderTarget } from '../../platform/graphics/render-target.js'; +import { Texture } from '../../platform/graphics/texture.js'; -import { RenderPassDownsample } from './render-pass-downsample.js'; -import { RenderPassUpsample } from './render-pass-upsample.js'; // based on https://learnopengl.com/Guest-Articles/2022/Phys.-Based-Bloom /** diff --git a/src/extras/render-passes/render-pass-camera-frame.js b/src/extras/render-passes/render-pass-camera-frame.js index f5e7b1216a4..9d6215ac05a 100644 --- a/src/extras/render-passes/render-pass-camera-frame.js +++ b/src/extras/render-passes/render-pass-camera-frame.js @@ -1,4 +1,9 @@ -import { LAYERID_SKYBOX, LAYERID_IMMEDIATE, TONEMAP_NONE, GAMMA_NONE } from '../../scene/constants.js'; +import { RenderPassBloom } from './render-pass-bloom.js'; +import { RenderPassCompose } from './render-pass-compose.js'; +import { RenderPassPrepass } from './render-pass-prepass.js'; +import { RenderPassSsao } from './render-pass-ssao.js'; +import { RenderPassTAA } from './render-pass-taa.js'; +import { Debug } from '../../core/debug.js'; import { ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, @@ -6,19 +11,13 @@ import { PIXELFORMAT_DEPTH, PIXELFORMAT_RGBA8 } from '../../platform/graphics/constants.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { RenderPass } from '../../platform/graphics/render-pass.js'; +import { RenderTarget } from '../../platform/graphics/render-target.js'; +import { Texture } from '../../platform/graphics/texture.js'; +import { LAYERID_SKYBOX, LAYERID_IMMEDIATE, TONEMAP_NONE, GAMMA_NONE } from '../../scene/constants.js'; import { RenderPassColorGrab } from '../../scene/graphics/render-pass-color-grab.js'; import { RenderPassForward } from '../../scene/renderer/render-pass-forward.js'; -import { RenderTarget } from '../../platform/graphics/render-target.js'; - -import { RenderPassBloom } from './render-pass-bloom.js'; -import { RenderPassCompose } from './render-pass-compose.js'; -import { RenderPassTAA } from './render-pass-taa.js'; -import { RenderPassPrepass } from './render-pass-prepass.js'; -import { RenderPassSsao } from './render-pass-ssao.js'; import { RenderingParams } from '../../scene/renderer/rendering-params.js'; -import { Debug } from '../../core/debug.js'; /** * Render pass implementation of a common camera frame rendering with integrated post-processing diff --git a/src/extras/render-passes/render-pass-compose.js b/src/extras/render-passes/render-pass-compose.js index 8031adf2241..dd46afaf906 100644 --- a/src/extras/render-passes/render-pass-compose.js +++ b/src/extras/render-passes/render-pass-compose.js @@ -1,8 +1,8 @@ -import { math } from '../../core/math/math.js'; import { Color } from '../../core/math/color.js'; +import { math } from '../../core/math/math.js'; +import { TONEMAP_LINEAR } from '../../scene/constants.js'; import { RenderPassShaderQuad } from '../../scene/graphics/render-pass-shader-quad.js'; import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; -import { TONEMAP_LINEAR } from '../../scene/constants.js'; import { ShaderGenerator } from '../../scene/shader-lib/programs/shader-generator.js'; @@ -356,14 +356,14 @@ class RenderPassCompose extends RenderPassShaderQuad { this._key = key; const defines = - (this.bloomTexture ? `#define BLOOM\n` : '') + - (this.ssaoTexture ? `#define SSAO\n` : '') + - (this.gradingEnabled ? `#define GRADING\n` : '') + - (this.vignetteEnabled ? `#define VIGNETTE\n` : '') + - (this.fringingEnabled ? `#define FRINGING\n` : '') + - (this.taaEnabled ? `#define TAA\n` : '') + - (this.isSharpnessEnabled ? `#define CAS\n` : '') + - (this._srgb ? `` : '#define GAMMA_CORRECT_OUTPUT\n'); + (this.bloomTexture ? '#define BLOOM\n' : '') + + (this.ssaoTexture ? '#define SSAO\n' : '') + + (this.gradingEnabled ? '#define GRADING\n' : '') + + (this.vignetteEnabled ? '#define VIGNETTE\n' : '') + + (this.fringingEnabled ? '#define FRINGING\n' : '') + + (this.taaEnabled ? '#define TAA\n' : '') + + (this.isSharpnessEnabled ? '#define CAS\n' : '') + + (this._srgb ? '' : '#define GAMMA_CORRECT_OUTPUT\n'); const fsChunks = shaderChunks.decodePS + diff --git a/src/extras/render-passes/render-pass-depth-aware-blur.js b/src/extras/render-passes/render-pass-depth-aware-blur.js index 17160266d61..4a426daea69 100644 --- a/src/extras/render-passes/render-pass-depth-aware-blur.js +++ b/src/extras/render-passes/render-pass-depth-aware-blur.js @@ -12,7 +12,7 @@ class RenderPassDepthAwareBlur extends RenderPassShaderQuad { super(device); this.sourceTexture = sourceTexture; - this.shader = this.createQuadShader(`DepthAware${horizontal ? 'Horizontal' : 'Vertical'}BlurShader`, shaderChunks.screenDepthPS + /* glsl */` + this.shader = this.createQuadShader(`DepthAware${horizontal ? 'Horizontal' : 'Vertical'}BlurShader`, `${shaderChunks.screenDepthPS /* glsl */} ${horizontal ? '#define HORIZONTAL' : ''} diff --git a/src/extras/render-passes/render-pass-prepass.js b/src/extras/render-passes/render-pass-prepass.js index 1def214a14f..278182233cf 100644 --- a/src/extras/render-passes/render-pass-prepass.js +++ b/src/extras/render-passes/render-pass-prepass.js @@ -4,10 +4,9 @@ import { PIXELFORMAT_RGBA16F, ADDRESS_CLAMP_TO_EDGE } from '../../platform/graphics/constants.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { RenderPass } from '../../platform/graphics/render-pass.js'; import { RenderTarget } from '../../platform/graphics/render-target.js'; - +import { Texture } from '../../platform/graphics/texture.js'; import { LAYERID_DEPTH, SHADER_PREPASS_VELOCITY @@ -116,8 +115,9 @@ class RenderPassPrepass extends RenderPass { if (layer.camerasSet.has(camera)) { // only render the layers before the depth layer - if (layer.id === LAYERID_DEPTH) + if (layer.id === LAYERID_DEPTH) { break; + } const culledInstances = layer.getCulledInstances(camera); const meshInstances = isTransparent[i] ? culledInstances.transparent : culledInstances.opaque; diff --git a/src/extras/render-passes/render-pass-ssao.js b/src/extras/render-passes/render-pass-ssao.js index 395dfb6dd2f..8d1ffb0a1f8 100644 --- a/src/extras/render-passes/render-pass-ssao.js +++ b/src/extras/render-passes/render-pass-ssao.js @@ -1,9 +1,9 @@ +import { RenderPassDepthAwareBlur } from './render-pass-depth-aware-blur.js'; import { ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, PIXELFORMAT_R8 } from '../../platform/graphics/constants.js'; import { RenderTarget } from '../../platform/graphics/render-target.js'; import { Texture } from '../../platform/graphics/texture.js'; import { RenderPassShaderQuad } from '../../scene/graphics/render-pass-shader-quad.js'; import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; -import { RenderPassDepthAwareBlur } from './render-pass-depth-aware-blur.js'; const fs = /* glsl */` varying vec2 uv0; @@ -252,7 +252,7 @@ class RenderPassSsao extends RenderPassShaderQuad { // main SSAO render pass this.shader = this.createQuadShader('SsaoShader', shaderChunks.screenDepthPS + fs); - const rt = this.createRenderTarget(`SsaoFinalTexture`); + const rt = this.createRenderTarget('SsaoFinalTexture'); this.ssaoTexture = rt.colorBuffer; this.init(rt, { @@ -262,7 +262,7 @@ class RenderPassSsao extends RenderPassShaderQuad { // optional blur passes if (blurEnabled) { - const blurRT = this.createRenderTarget(`SsaoTempTexture`); + const blurRT = this.createRenderTarget('SsaoTempTexture'); const blurPassHorizontal = new RenderPassDepthAwareBlur(device, rt.colorBuffer, true); blurPassHorizontal.init(blurRT, { @@ -335,13 +335,13 @@ class RenderPassSsao extends RenderPassShaderQuad { const { width, height } = this.renderTarget.colorBuffer; const scope = device.scope; - scope.resolve("uAspect").setValue(width / height); - scope.resolve("uInvResolution").setValue([1.0 / width, 1.0 / height]); + scope.resolve('uAspect').setValue(width / height); + scope.resolve('uInvResolution').setValue([1.0 / width, 1.0 / height]); - scope.resolve("uSampleCount").setValue([sampleCount, 1.0 / sampleCount]); + scope.resolve('uSampleCount').setValue([sampleCount, 1.0 / sampleCount]); const minAngleSin = Math.sin(minAngle * Math.PI / 180.0); - scope.resolve("uMinHorizonAngleSineSquared").setValue(minAngleSin * minAngleSin); + scope.resolve('uMinHorizonAngleSineSquared').setValue(minAngleSin * minAngleSin); const spiralTurns = 10.0; const step = (1.0 / (sampleCount - 0.5)) * spiralTurns * 2.0 * 3.141; @@ -350,15 +350,15 @@ class RenderPassSsao extends RenderPassShaderQuad { const peak = 0.1 * radius; const intensity = 2 * (peak * 2.0 * 3.141) * this.intensity / sampleCount; const projectionScale = 0.5 * sourceTexture.height * scale; - scope.resolve("uSpiralTurns").setValue(spiralTurns); - scope.resolve("uAngleIncCosSin").setValue([Math.cos(step), Math.sin(step)]); - scope.resolve("uMaxLevel").setValue(0.0); - scope.resolve("uInvRadiusSquared").setValue(1.0 / (radius * radius)); - scope.resolve("uBias").setValue(bias); - scope.resolve("uPeak2").setValue(peak * peak); - scope.resolve("uIntensity").setValue(intensity); - scope.resolve("uPower").setValue(this.power); - scope.resolve("uProjectionScaleRadius").setValue(projectionScale * radius); + scope.resolve('uSpiralTurns').setValue(spiralTurns); + scope.resolve('uAngleIncCosSin').setValue([Math.cos(step), Math.sin(step)]); + scope.resolve('uMaxLevel').setValue(0.0); + scope.resolve('uInvRadiusSquared').setValue(1.0 / (radius * radius)); + scope.resolve('uBias').setValue(bias); + scope.resolve('uPeak2').setValue(peak * peak); + scope.resolve('uIntensity').setValue(intensity); + scope.resolve('uPower').setValue(this.power); + scope.resolve('uProjectionScaleRadius').setValue(projectionScale * radius); super.execute(); } diff --git a/src/extras/render-passes/render-pass-taa.js b/src/extras/render-passes/render-pass-taa.js index b12b9bbea3d..89b738bae7d 100644 --- a/src/extras/render-passes/render-pass-taa.js +++ b/src/extras/render-passes/render-pass-taa.js @@ -2,10 +2,10 @@ import { FILTER_LINEAR, ADDRESS_CLAMP_TO_EDGE } from '../../platform/graphics/constants.js'; +import { RenderTarget } from '../../platform/graphics/render-target.js'; import { Texture } from '../../platform/graphics/texture.js'; -import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; import { RenderPassShaderQuad } from '../../scene/graphics/render-pass-shader-quad.js'; -import { RenderTarget } from '../../platform/graphics/render-target.js'; +import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; const fs = /* glsl */ ` uniform highp sampler2D uSceneDepthMap; diff --git a/src/framework/anim/binder/anim-binder.js b/src/framework/anim/binder/anim-binder.js index 49f0f7a1f59..2634680071c 100644 --- a/src/framework/anim/binder/anim-binder.js +++ b/src/framework/anim/binder/anim-binder.js @@ -14,7 +14,7 @@ class AnimBinder { static joinPath(pathSegments, character) { character = character || '.'; const escape = function (string) { - return string.replace(/\\/g, '\\\\').replace(new RegExp('\\' + character, 'g'), '\\' + character); + return string.replace(/\\/g, '\\\\').replace(new RegExp(`\\${character}`, 'g'), `\\${character}`); }; return pathSegments.map(escape).join(character); } @@ -23,7 +23,7 @@ class AnimBinder { static splitPath(path, character) { character = character || '.'; const result = []; - let curr = ""; + let curr = ''; let i = 0; while (i < path.length) { let c = path[i++]; @@ -33,7 +33,7 @@ class AnimBinder { if (c === '\\' || c === character) { curr += c; } else { - curr += '\\' + c; + curr += `\\${c}`; } } else if (c === character) { result.push(curr); diff --git a/src/framework/anim/binder/default-anim-binder.js b/src/framework/anim/binder/default-anim-binder.js index 0babc193afc..dce9df2d11e 100644 --- a/src/framework/anim/binder/default-anim-binder.js +++ b/src/framework/anim/binder/default-anim-binder.js @@ -1,7 +1,7 @@ -import { Debug } from '../../../core/debug.js'; import { AnimBinder } from './anim-binder.js'; -import { AnimTarget } from '../evaluator/anim-target.js'; +import { Debug } from '../../../core/debug.js'; import { Entity } from '../../entity.js'; +import { AnimTarget } from '../evaluator/anim-target.js'; /** * Implementation of {@link AnimBinder} for animating a skeleton in the graph-node hierarchy. @@ -151,7 +151,7 @@ class DefaultAnimBinder { let currEntityPath = rootNodeNames[j]; if (this._isPathInMask(currEntityPath, path.entityPath.length === 1)) return true; for (let i = 1; i < path.entityPath.length; i++) { - currEntityPath += '/' + path.entityPath[i]; + currEntityPath += `/${path.entityPath[i]}`; if (this._isPathInMask(currEntityPath, i === path.entityPath.length - 1)) return true; } } @@ -172,10 +172,10 @@ class DefaultAnimBinder { } } if (!node) { - node = this.nodes[path.entityPath[path.entityPath.length - 1] || ""]; + node = this.nodes[path.entityPath[path.entityPath.length - 1] || '']; // #if _DEBUG - const fallbackGraphPath = AnimBinder.encode(path.entityPath[path.entityPath.length - 1] || "", 'graph', path.propertyPath); + const fallbackGraphPath = AnimBinder.encode(path.entityPath[path.entityPath.length - 1] || '', 'graph', path.propertyPath); if (this.visitedFallbackGraphPaths[fallbackGraphPath] === 1) { Debug.warn(`Anim Binder: Multiple animation curves with the path ${fallbackGraphPath} are present in the ${this.graph.path} graph which may result in the incorrect binding of animations`); } @@ -227,10 +227,11 @@ class DefaultAnimBinder { } unresolve(path) { - if (path.component !== 'graph') + if (path.component !== 'graph') { return; + } - const node = this.nodes[path.entityPath[path.entityPath.length - 1] || ""]; + const node = this.nodes[path.entityPath[path.entityPath.length - 1] || '']; this.nodeCounts[node.path]--; if (this.nodeCounts[node.path] === 0) { diff --git a/src/framework/anim/controller/anim-blend-tree-1d.js b/src/framework/anim/controller/anim-blend-tree-1d.js index f4adebaca73..3390bb53fc2 100644 --- a/src/framework/anim/controller/anim-blend-tree-1d.js +++ b/src/framework/anim/controller/anim-blend-tree-1d.js @@ -1,5 +1,5 @@ -import { math } from '../../../core/math/math.js'; import { AnimBlendTree } from './anim-blend-tree.js'; +import { math } from '../../../core/math/math.js'; /** * @import { AnimState } from './anim-state.js' diff --git a/src/framework/anim/controller/anim-blend-tree-2d-cartesian.js b/src/framework/anim/controller/anim-blend-tree-2d-cartesian.js index 4c18e9abf3a..88d0cd4cfae 100644 --- a/src/framework/anim/controller/anim-blend-tree-2d-cartesian.js +++ b/src/framework/anim/controller/anim-blend-tree-2d-cartesian.js @@ -1,7 +1,7 @@ -import { Vec2 } from '../../../core/math/vec2.js'; +import { AnimBlendTree } from './anim-blend-tree.js'; import { math } from '../../../core/math/math.js'; +import { Vec2 } from '../../../core/math/vec2.js'; -import { AnimBlendTree } from './anim-blend-tree.js'; /** * An AnimBlendTree that calculates its weights using a 2D Cartesian algorithm based on the thesis diff --git a/src/framework/anim/controller/anim-blend-tree-2d-directional.js b/src/framework/anim/controller/anim-blend-tree-2d-directional.js index ced6f849cb1..b62c1de2009 100644 --- a/src/framework/anim/controller/anim-blend-tree-2d-directional.js +++ b/src/framework/anim/controller/anim-blend-tree-2d-directional.js @@ -1,7 +1,7 @@ -import { Vec2 } from '../../../core/math/vec2.js'; +import { AnimBlendTree } from './anim-blend-tree.js'; import { math } from '../../../core/math/math.js'; +import { Vec2 } from '../../../core/math/vec2.js'; -import { AnimBlendTree } from './anim-blend-tree.js'; /** * An AnimBlendTree that calculates its weights using a 2D directional algorithm based on the thesis diff --git a/src/framework/anim/controller/anim-controller.js b/src/framework/anim/controller/anim-controller.js index 0e968529653..ccedb2cfa3b 100644 --- a/src/framework/anim/controller/anim-controller.js +++ b/src/framework/anim/controller/anim-controller.js @@ -1,15 +1,15 @@ -import { Debug } from '../../../core/debug.js'; -import { sortPriority } from '../../../core/sort.js'; -import { AnimClip } from '../evaluator/anim-clip.js'; +import { AnimNode } from './anim-node.js'; +import { AnimState } from './anim-state.js'; +import { AnimTransition } from './anim-transition.js'; import { ANIM_GREATER_THAN, ANIM_LESS_THAN, ANIM_GREATER_THAN_EQUAL_TO, ANIM_LESS_THAN_EQUAL_TO, ANIM_EQUAL_TO, ANIM_NOT_EQUAL_TO, ANIM_INTERRUPTION_NONE, ANIM_INTERRUPTION_PREV, ANIM_INTERRUPTION_NEXT, ANIM_INTERRUPTION_PREV_NEXT, ANIM_INTERRUPTION_NEXT_PREV, ANIM_PARAMETER_TRIGGER, ANIM_STATE_START, ANIM_STATE_END, ANIM_STATE_ANY, ANIM_CONTROL_STATES } from './constants.js'; -import { AnimState } from './anim-state.js'; -import { AnimNode } from './anim-node.js'; -import { AnimTransition } from './anim-transition.js'; +import { Debug } from '../../../core/debug.js'; +import { sortPriority } from '../../../core/sort.js'; +import { AnimClip } from '../evaluator/anim-clip.js'; /** * @import { AnimEvaluator } from '../evaluator/anim-evaluator.js' @@ -251,8 +251,9 @@ class AnimController { } _getActiveStateProgressForTime(time) { - if (this.activeStateName === ANIM_STATE_START || this.activeStateName === ANIM_STATE_END || this.activeStateName === ANIM_STATE_ANY) + if (this.activeStateName === ANIM_STATE_START || this.activeStateName === ANIM_STATE_END || this.activeStateName === ANIM_STATE_ANY) { return 1.0; + } const activeClip = this._animEvaluator.findClip(this.activeStateAnimations[0].name); if (activeClip) { @@ -273,7 +274,7 @@ class AnimController { _findTransitionsFromState(stateName) { let transitions = this._findTransitionsFromStateCache[stateName]; if (!transitions) { - transitions = this._transitions.filter(function (transition) { + transitions = this._transitions.filter((transition) => { return transition.from === stateName; }); @@ -295,16 +296,16 @@ class AnimController { * @private */ _findTransitionsBetweenStates(sourceStateName, destinationStateName) { - let transitions = this._findTransitionsBetweenStatesCache[sourceStateName + '->' + destinationStateName]; + let transitions = this._findTransitionsBetweenStatesCache[`${sourceStateName}->${destinationStateName}`]; if (!transitions) { - transitions = this._transitions.filter(function (transition) { + transitions = this._transitions.filter((transition) => { return transition.from === sourceStateName && transition.to === destinationStateName; }); // sort transitions in priority order sortPriority(transitions); - this._findTransitionsBetweenStatesCache[sourceStateName + '->' + destinationStateName] = transitions; + this._findTransitionsBetweenStatesCache[`${sourceStateName}->${destinationStateName}`] = transitions; } return transitions; } @@ -466,10 +467,10 @@ class AnimController { // to uniquely identify animations from the same state that were added during different transitions for (let j = 0; j < state.animations.length; j++) { animation = state.animations[j]; - clip = this._animEvaluator.findClip(animation.name + '.previous.' + i); + clip = this._animEvaluator.findClip(`${animation.name}.previous.${i}`); if (!clip) { clip = this._animEvaluator.findClip(animation.name); - clip.name = animation.name + '.previous.' + i; + clip.name = `${animation.name}.previous.${i}`; } // // pause previous animation clips to reduce their impact on performance if (i !== this._transitionPreviousStates.length - 1) { @@ -626,8 +627,9 @@ class AnimController { // transition between states if a transition is available from the active state const transition = this._findTransition(this._activeStateName); - if (transition) + if (transition) { this.updateStateFromTransition(transition); + } if (this._isTransitioning) { this._currTransitionTime += dt; @@ -639,7 +641,7 @@ class AnimController { const stateWeight = this._transitionPreviousStates[i].weight; for (let j = 0; j < state.animations.length; j++) { animation = state.animations[j]; - clip = this._animEvaluator.findClip(animation.name + '.previous.' + i); + clip = this._animEvaluator.findClip(`${animation.name}.previous.${i}`); if (clip) { clip.blendWeight = (1.0 - interpolatedTime) * animation.normalizedWeight * stateWeight; } diff --git a/src/framework/anim/controller/anim-node.js b/src/framework/anim/controller/anim-node.js index 3e3acd742e5..d29a8b1a9ee 100644 --- a/src/framework/anim/controller/anim-node.js +++ b/src/framework/anim/controller/anim-node.js @@ -50,7 +50,7 @@ class AnimNode { } get path() { - return this._parent ? this._parent.path + '.' + this._name : this._name; + return this._parent ? `${this._parent.path}.${this._name}` : this._name; } get point() { diff --git a/src/framework/anim/controller/anim-state.js b/src/framework/anim/controller/anim-state.js index ddee00bf10a..7c25654b5ca 100644 --- a/src/framework/anim/controller/anim-state.js +++ b/src/framework/anim/controller/anim-state.js @@ -1,13 +1,13 @@ -import { Debug } from '../../../core/debug.js'; -import { AnimTrack } from '../evaluator/anim-track.js'; -import { - ANIM_BLEND_1D, ANIM_BLEND_2D_CARTESIAN, ANIM_BLEND_2D_DIRECTIONAL, ANIM_BLEND_DIRECT, ANIM_CONTROL_STATES -} from './constants.js'; import { AnimBlendTree1D } from './anim-blend-tree-1d.js'; import { AnimBlendTreeCartesian2D } from './anim-blend-tree-2d-cartesian.js'; import { AnimBlendTreeDirectional2D } from './anim-blend-tree-2d-directional.js'; import { AnimBlendTreeDirect } from './anim-blend-tree-direct.js'; import { AnimNode } from './anim-node.js'; +import { + ANIM_BLEND_1D, ANIM_BLEND_2D_CARTESIAN, ANIM_BLEND_2D_DIRECTIONAL, ANIM_BLEND_DIRECT, ANIM_CONTROL_STATES +} from './constants.js'; +import { Debug } from '../../../core/debug.js'; +import { AnimTrack } from '../evaluator/anim-track.js'; /** * @import { AnimController } from './anim-controller.js' @@ -89,7 +89,7 @@ class AnimState { addAnimation(path, animTrack) { const pathString = path.join('.'); - const indexOfAnimation = this._animationList.findIndex(function (animation) { + const indexOfAnimation = this._animationList.findIndex((animation) => { return animation.path === pathString; }); if (indexOfAnimation >= 0) { @@ -150,7 +150,7 @@ class AnimState { get looping() { if (this.animations.length > 0) { - const trackClipName = this.name + '.' + this.animations[0].animTrack.name; + const trackClipName = `${this.name}.${this.animations[0].animTrack.name}`; const trackClip = this._controller.animEvaluator.findClip(trackClipName); if (trackClip) { return trackClip.loop; diff --git a/src/framework/anim/controller/constants.js b/src/framework/anim/controller/constants.js index 7b340e93b77..e9420bce432 100644 --- a/src/framework/anim/controller/constants.js +++ b/src/framework/anim/controller/constants.js @@ -88,12 +88,12 @@ export const ANIM_EQUAL_TO = 'EQUAL_TO'; */ export const ANIM_NOT_EQUAL_TO = 'NOT_EQUAL_TO'; - /** - * Used to set an anim state graph parameter as type integer. - * - * @type {string} - * @category Animation - */ +/** + * Used to set an anim state graph parameter as type integer. + * + * @type {string} + * @category Animation + */ export const ANIM_PARAMETER_INTEGER = 'INTEGER'; /** diff --git a/src/framework/anim/evaluator/anim-cache.js b/src/framework/anim/evaluator/anim-cache.js index 929aa50b4a1..5832823628c 100644 --- a/src/framework/anim/evaluator/anim-cache.js +++ b/src/framework/anim/evaluator/anim-cache.js @@ -1,5 +1,4 @@ import { math } from '../../../core/math/math.js'; - import { INTERPOLATION_CUBIC, INTERPOLATION_LINEAR, INTERPOLATION_STEP } from '../constants.js'; /** diff --git a/src/framework/anim/evaluator/anim-evaluator.js b/src/framework/anim/evaluator/anim-evaluator.js index 8baf3cd1774..b25e6be965a 100644 --- a/src/framework/anim/evaluator/anim-evaluator.js +++ b/src/framework/anim/evaluator/anim-evaluator.js @@ -1,5 +1,5 @@ -import { AnimTargetValue } from './anim-target-value.js'; import { AnimBlend } from './anim-blend.js'; +import { AnimTargetValue } from './anim-target-value.js'; /** * @import { AnimBinder } from '../binder/anim-binder.js' @@ -205,10 +205,10 @@ class AnimEvaluator { const clips = this._clips; // stable sort order - const order = clips.map(function (c, i) { + const order = clips.map((c, i) => { return i; }); - AnimBlend.stableSort(order, function (a, b) { + AnimBlend.stableSort(order, (a, b) => { return clips[a].blendOrder < clips[b].blendOrder; }); diff --git a/src/framework/anim/evaluator/anim-snapshot.js b/src/framework/anim/evaluator/anim-snapshot.js index 3ffc725aa7d..f705172fab8 100644 --- a/src/framework/anim/evaluator/anim-snapshot.js +++ b/src/framework/anim/evaluator/anim-snapshot.js @@ -16,7 +16,7 @@ class AnimSnapshot { * @param {AnimTrack} animTrack - The source track. */ constructor(animTrack) { - this._name = animTrack.name + 'Snapshot'; + this._name = `${animTrack.name}Snapshot`; this._time = -1; // per-curve input cache diff --git a/src/framework/anim/evaluator/anim-target-value.js b/src/framework/anim/evaluator/anim-target-value.js index d5ee88e5860..745c01c70f1 100644 --- a/src/framework/anim/evaluator/anim-target-value.js +++ b/src/framework/anim/evaluator/anim-target-value.js @@ -1,7 +1,7 @@ -import { Quat } from '../../../core/math/quat.js'; -import { ANIM_LAYER_ADDITIVE, ANIM_LAYER_OVERWRITE } from '../controller/constants.js'; import { AnimBlend } from './anim-blend.js'; import { math } from '../../../core/math/math.js'; +import { Quat } from '../../../core/math/quat.js'; +import { ANIM_LAYER_ADDITIVE, ANIM_LAYER_OVERWRITE } from '../controller/constants.js'; /** * @import { AnimComponent } from '../../components/anim/component.js' diff --git a/src/framework/app-base.js b/src/framework/app-base.js index 552278170da..1ccac9b60ea 100644 --- a/src/framework/app-base.js +++ b/src/framework/app-base.js @@ -1,10 +1,24 @@ // #if _DEBUG +import { AssetRegistry } from './asset/asset-registry.js'; +import { Asset } from './asset/asset.js'; +import { BundleRegistry } from './bundle/bundle-registry.js'; +import { ComponentSystemRegistry } from './components/registry.js'; +import { + FILLMODE_FILL_WINDOW, FILLMODE_KEEP_ASPECT, + RESOLUTION_AUTO, RESOLUTION_FIXED +} from './constants.js'; +import { Entity } from './entity.js'; +import { getApplication, setApplication } from './globals.js'; +import { BundleHandler } from './handlers/bundle.js'; +import { ResourceLoader } from './handlers/loader.js'; +import { I18n } from './i18n/i18n.js'; +import { SceneRegistry } from './scene-registry.js'; +import { ScriptRegistry } from './script/script-registry.js'; +import { script } from './script.js'; +import { ApplicationStats } from './stats.js'; +import { TRACEID_RENDER_FRAME, TRACEID_RENDER_FRAME_TIME } from '../core/constants.js'; import { version, revision } from '../core/core.js'; // #endif -import { platform } from '../core/platform.js'; -import { now } from '../core/time.js'; -import { path } from '../core/path.js'; -import { TRACEID_RENDER_FRAME, TRACEID_RENDER_FRAME_TIME } from '../core/constants.js'; import { Debug } from '../core/debug.js'; import { EventHandler } from '../core/event-handler.js'; import { Color } from '../core/math/color.js'; @@ -12,46 +26,29 @@ import { Mat4 } from '../core/math/mat4.js'; import { math } from '../core/math/math.js'; import { Quat } from '../core/math/quat.js'; import { Vec3 } from '../core/math/vec3.js'; - +import { path } from '../core/path.js'; +import { platform } from '../core/platform.js'; +import { now } from '../core/time.js'; import { PRIMITIVE_TRIANGLES, PRIMITIVE_TRIFAN, PRIMITIVE_TRISTRIP, CULLFACE_NONE } from '../platform/graphics/constants.js'; import { DebugGraphics } from '../platform/graphics/debug-graphics.js'; import { http } from '../platform/net/http.js'; - +import { AreaLightLuts } from '../scene/area-light-luts.js'; +import { LayerComposition } from '../scene/composition/layer-composition.js'; import { LAYERID_DEPTH, LAYERID_IMMEDIATE, LAYERID_SKYBOX, LAYERID_UI, LAYERID_WORLD, SORTMODE_NONE, SORTMODE_MANUAL } from '../scene/constants.js'; -import { setProgramLibrary } from '../scene/shader-lib/get-program-library.js'; -import { ProgramLibrary } from '../scene/shader-lib/program-library.js'; -import { ForwardRenderer } from '../scene/renderer/forward-renderer.js'; import { FrameGraph } from '../scene/frame-graph.js'; -import { AreaLightLuts } from '../scene/area-light-luts.js'; import { Layer } from '../scene/layer.js'; -import { LayerComposition } from '../scene/composition/layer-composition.js'; -import { Scene } from '../scene/scene.js'; +import { setDefaultMaterial } from '../scene/materials/default-material.js'; import { ShaderMaterial } from '../scene/materials/shader-material.js'; import { StandardMaterial } from '../scene/materials/standard-material.js'; -import { setDefaultMaterial } from '../scene/materials/default-material.js'; - -import { - FILLMODE_FILL_WINDOW, FILLMODE_KEEP_ASPECT, - RESOLUTION_AUTO, RESOLUTION_FIXED -} from './constants.js'; -import { Asset } from './asset/asset.js'; -import { AssetRegistry } from './asset/asset-registry.js'; -import { BundleRegistry } from './bundle/bundle-registry.js'; -import { ComponentSystemRegistry } from './components/registry.js'; -import { BundleHandler } from './handlers/bundle.js'; -import { ResourceLoader } from './handlers/loader.js'; -import { I18n } from './i18n/i18n.js'; -import { ScriptRegistry } from './script/script-registry.js'; -import { Entity } from './entity.js'; -import { SceneRegistry } from './scene-registry.js'; -import { script } from './script.js'; -import { ApplicationStats } from './stats.js'; -import { getApplication, setApplication } from './globals.js'; +import { ForwardRenderer } from '../scene/renderer/forward-renderer.js'; +import { Scene } from '../scene/scene.js'; +import { setProgramLibrary } from '../scene/shader-lib/get-program-library.js'; +import { ProgramLibrary } from '../scene/shader-lib/program-library.js'; /** * @import { AppOptions } from './app-options.js' @@ -489,7 +486,7 @@ class AppBase extends EventHandler { lightmapper, mouse, resourceHandlers, scriptsOrder, scriptPrefix, soundManager, touch, xr } = appOptions; - Debug.assert(graphicsDevice, "The application cannot be created without a valid GraphicsDevice"); + Debug.assert(graphicsDevice, 'The application cannot be created without a valid GraphicsDevice'); this.graphicsDevice = graphicsDevice; this._initDefaultMaterial(); @@ -506,13 +503,13 @@ class AppBase extends EventHandler { this.bundles = new BundleRegistry(this.assets); this.scriptsOrder = scriptsOrder || []; - this.defaultLayerWorld = new Layer({ name: "World", id: LAYERID_WORLD }); - this.defaultLayerDepth = new Layer({ name: "Depth", id: LAYERID_DEPTH, enabled: false, opaqueSortMode: SORTMODE_NONE }); - this.defaultLayerSkybox = new Layer({ name: "Skybox", id: LAYERID_SKYBOX, opaqueSortMode: SORTMODE_NONE }); - this.defaultLayerUi = new Layer({ name: "UI", id: LAYERID_UI, transparentSortMode: SORTMODE_MANUAL }); - this.defaultLayerImmediate = new Layer({ name: "Immediate", id: LAYERID_IMMEDIATE, opaqueSortMode: SORTMODE_NONE }); + this.defaultLayerWorld = new Layer({ name: 'World', id: LAYERID_WORLD }); + this.defaultLayerDepth = new Layer({ name: 'Depth', id: LAYERID_DEPTH, enabled: false, opaqueSortMode: SORTMODE_NONE }); + this.defaultLayerSkybox = new Layer({ name: 'Skybox', id: LAYERID_SKYBOX, opaqueSortMode: SORTMODE_NONE }); + this.defaultLayerUi = new Layer({ name: 'UI', id: LAYERID_UI, transparentSortMode: SORTMODE_MANUAL }); + this.defaultLayerImmediate = new Layer({ name: 'Immediate', id: LAYERID_IMMEDIATE, opaqueSortMode: SORTMODE_NONE }); - const defaultLayerComposition = new LayerComposition("default"); + const defaultLayerComposition = new LayerComposition('default'); defaultLayerComposition.pushOpaque(this.defaultLayerWorld); defaultLayerComposition.pushOpaque(this.defaultLayerDepth); defaultLayerComposition.pushOpaque(this.defaultLayerSkybox); @@ -553,7 +550,7 @@ class AppBase extends EventHandler { this._scriptPrefix = scriptPrefix || ''; if (this.enableBundles) { - this.loader.addHandler("bundle", new BundleHandler(this)); + this.loader.addHandler('bundle', new BundleHandler(this)); } // Create and register all required resource handlers @@ -613,7 +610,7 @@ class AppBase extends EventHandler { /** @private */ _initDefaultMaterial() { const material = new StandardMaterial(); - material.name = "Default Material"; + material.name = 'Default Material'; setDefaultMaterial(this.graphicsDevice, material); } @@ -638,7 +635,7 @@ class AppBase extends EventHandler { * @type {BatchManager} */ get batcher() { - Debug.assert(this._batcher, "BatchManager has not been created and is required for correct functionality."); + Debug.assert(this._batcher, 'BatchManager has not been created and is required for correct functionality.'); return this._batcher; } @@ -706,7 +703,7 @@ class AppBase extends EventHandler { * @param {PreloadAppCallback} callback - Function called when all assets are loaded. */ preload(callback) { - this.fire("preload:start"); + this.fire('preload:start'); // get list of assets to preload const assets = this.assets.list({ @@ -714,7 +711,7 @@ class AppBase extends EventHandler { }); if (assets.length === 0) { - this.fire("preload:end"); + this.fire('preload:end'); callback(); return; } @@ -726,7 +723,7 @@ class AppBase extends EventHandler { this.fire('preload:progress', loadedCount / assets.length); if (loadedCount === assets.length) { - this.fire("preload:end"); + this.fire('preload:end'); callback(); } }; @@ -755,12 +752,15 @@ class AppBase extends EventHandler { } // TODO: remove this temporary block after migrating properties - if (!props.useDevicePixelRatio) + if (!props.useDevicePixelRatio) { props.useDevicePixelRatio = props.use_device_pixel_ratio; - if (!props.resolutionMode) + } + if (!props.resolutionMode) { props.resolutionMode = props.resolution_mode; - if (!props.fillMode) + } + if (!props.fillMode) { props.fillMode = props.fill_mode; + } this._width = props.width; this._height = props.height; @@ -773,7 +773,7 @@ class AppBase extends EventHandler { // set up layers if (props.layers && props.layerOrder) { - const composition = new LayerComposition("application"); + const composition = new LayerComposition('application'); const layers = {}; for (const key in props.layers) { @@ -830,7 +830,7 @@ class AppBase extends EventHandler { const len = urls.length; let count = len; - const regex = /^http(s)?:\/\//; + const regex = /^https?:\/\//; if (len) { const onLoad = (err, script) => { @@ -846,8 +846,9 @@ class AppBase extends EventHandler { for (let i = 0; i < len; ++i) { let url = urls[i]; - if (!regex.test(url.toLowerCase()) && this._scriptPrefix) + if (!regex.test(url.toLowerCase()) && this._scriptPrefix) { url = path.join(this._scriptPrefix, url); + } this.loader.load(url, 'script', onLoad); } @@ -886,8 +887,9 @@ class AppBase extends EventHandler { // add scripts in order of loading first for (let i = 0; i < this.scriptsOrder.length; i++) { const id = this.scriptsOrder[i]; - if (!assets[id]) + if (!assets[id]) { continue; + } scriptsIndex[id] = true; list.push(assets[id]); @@ -905,8 +907,9 @@ class AppBase extends EventHandler { // then add rest of assets for (const id in assets) { - if (scriptsIndex[id] || bundlesIndex[id]) + if (scriptsIndex[id] || bundlesIndex[id]) { continue; + } list.push(assets[id]); } @@ -951,13 +954,13 @@ class AppBase extends EventHandler { start() { Debug.call(() => { - Debug.assert(!this._alreadyStarted, "The application can be started only one time."); + Debug.assert(!this._alreadyStarted, 'The application can be started only one time.'); this._alreadyStarted = true; }); this.frame = 0; - this.fire("start", { + this.fire('start', { timestamp: now(), target: this }); @@ -1019,7 +1022,7 @@ class AppBase extends EventHandler { this.systems.fire('postUpdate', dt); // fire update event - this.fire("update", dt); + this.fire('update', dt); // update input devices this.inputUpdate(dt); @@ -1264,8 +1267,9 @@ class AppBase extends EventHandler { if (!this._allowResize) return undefined; // prevent resizing (e.g. if presenting in VR HMD) // prevent resizing when in XR session - if (this.xr && this.xr.session) + if (this.xr && this.xr.session) { return undefined; + } const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; @@ -1287,8 +1291,8 @@ class AppBase extends EventHandler { } // OTHERWISE: FILLMODE_NONE use width and height that are provided - this.graphicsDevice.canvas.style.width = width + 'px'; - this.graphicsDevice.canvas.style.height = height + 'px'; + this.graphicsDevice.canvas.style.width = `${width}px`; + this.graphicsDevice.canvas.style.height = `${height}px`; this.updateCanvasSize(); @@ -1461,7 +1465,7 @@ class AppBase extends EventHandler { if (asset) { this.setSkybox(asset); } else { - this.assets.once('add:' + settings.render.skybox, this.setSkybox, this); + this.assets.once(`add:${settings.render.skybox}`, this.setSkybox, this); } } else { this.setSkybox(null); @@ -1480,7 +1484,7 @@ class AppBase extends EventHandler { if (ltcMat1 && ltcMat2) { AreaLightLuts.set(this.graphicsDevice, ltcMat1, ltcMat2); } else { - Debug.warn("setAreaLightLuts: LUTs for area light are not valid"); + Debug.warn('setAreaLightLuts: LUTs for area light are not valid'); } } @@ -1501,16 +1505,16 @@ class AppBase extends EventHandler { // cleanup previous asset if (this._skyboxAsset) { - this.assets.off('load:' + this._skyboxAsset.id, onSkyboxChanged, this); - this.assets.off('remove:' + this._skyboxAsset.id, onSkyboxRemoved, this); + this.assets.off(`load:${this._skyboxAsset.id}`, onSkyboxChanged, this); + this.assets.off(`remove:${this._skyboxAsset.id}`, onSkyboxRemoved, this); this._skyboxAsset.off('change', onSkyboxChanged, this); } // set new asset this._skyboxAsset = asset; if (this._skyboxAsset) { - this.assets.on('load:' + this._skyboxAsset.id, onSkyboxChanged, this); - this.assets.once('remove:' + this._skyboxAsset.id, onSkyboxRemoved, this); + this.assets.on(`load:${this._skyboxAsset.id}`, onSkyboxChanged, this); + this.assets.once(`remove:${this._skyboxAsset.id}`, onSkyboxRemoved, this); this._skyboxAsset.on('change', onSkyboxChanged, this); if (this.scene.skyboxMip === 0 && !this._skyboxAsset.loadFaces) { @@ -1761,8 +1765,9 @@ class AppBase extends EventHandler { // only WebGPU supports filterable parameter to be false, allowing a depth texture / shadow // map to be fetched (without filtering) and rendered - if (filterable === false && !this.graphicsDevice.isWebGPU) + if (filterable === false && !this.graphicsDevice.isWebGPU) { return; + } // TODO: if this is used for anything other than debug texture display, we should optimize this to avoid allocations const matrix = new Mat4(); @@ -1771,7 +1776,7 @@ class AppBase extends EventHandler { if (!material) { material = new ShaderMaterial(); material.cull = CULLFACE_NONE; - material.setParameter("colorMap", texture); + material.setParameter('colorMap', texture); material.shaderDesc = filterable ? this.scene.immediate.getTextureShaderDesc(texture.encoding) : this.scene.immediate.getUnfilterableTextureShaderDesc(); material.update(); } @@ -1995,8 +2000,9 @@ const makeTick = function (_app) { * @param {XRFrame} [frame] - XRFrame from requestAnimationFrame callback. */ return function (timestamp, frame) { - if (!application.graphicsDevice) + if (!application.graphicsDevice) { return; + } // cancel any hanging rAF to avoid multiple rAF callbacks per frame if (application.frameRequestId) { @@ -2027,8 +2033,9 @@ const makeTick = function (_app) { application.frameRequestId = platform.browser || platform.worker ? requestAnimationFrame(application.tick) : null; } - if (application.graphicsDevice.contextLost) + if (application.graphicsDevice.contextLost) { return; + } application._fillFrameStatsBasic(currentTime, dt, ms); @@ -2036,7 +2043,7 @@ const makeTick = function (_app) { application._fillFrameStats(); // #endif - application.fire("frameupdate", ms); + application.fire('frameupdate', ms); let shouldRenderFrame = true; @@ -2054,7 +2061,7 @@ const makeTick = function (_app) { application.update(dt); - application.fire("framerender"); + application.fire('framerender'); if (application.autoRender || application.renderNextFrame) { @@ -2074,7 +2081,7 @@ const makeTick = function (_app) { _frameEndData.timestamp = now(); _frameEndData.target = application; - application.fire("frameend", _frameEndData); + application.fire('frameend', _frameEndData); } application._inFrameUpdate = false; diff --git a/src/framework/application.js b/src/framework/application.js index 66684f86ecd..bac3da95fec 100644 --- a/src/framework/application.js +++ b/src/framework/application.js @@ -1,37 +1,31 @@ -import { platform } from '../core/platform.js'; -import { WebglGraphicsDevice } from '../platform/graphics/webgl/webgl-graphics-device.js'; -import { SoundManager } from '../platform/sound/manager.js'; -import { Lightmapper } from './lightmapper/lightmapper.js'; -import { BatchManager } from '../scene/batching/batch-manager.js'; import { AppBase } from './app-base.js'; import { AppOptions } from './app-options.js'; -import { AnimationComponentSystem } from './components/animation/system.js'; import { AnimComponentSystem } from './components/anim/system.js'; +import { AnimationComponentSystem } from './components/animation/system.js'; import { AudioListenerComponentSystem } from './components/audio-listener/system.js'; import { ButtonComponentSystem } from './components/button/system.js'; +import { CameraComponentSystem } from './components/camera/system.js'; import { CollisionComponentSystem } from './components/collision/system.js'; import { ElementComponentSystem } from './components/element/system.js'; +import { GSplatComponentSystem } from './components/gsplat/system.js'; import { JointComponentSystem } from './components/joint/system.js'; import { LayoutChildComponentSystem } from './components/layout-child/system.js'; import { LayoutGroupComponentSystem } from './components/layout-group/system.js'; +import { LightComponentSystem } from './components/light/system.js'; import { ModelComponentSystem } from './components/model/system.js'; import { ParticleSystemComponentSystem } from './components/particle-system/system.js'; import { RenderComponentSystem } from './components/render/system.js'; import { RigidBodyComponentSystem } from './components/rigid-body/system.js'; import { ScreenComponentSystem } from './components/screen/system.js'; +import { ScriptComponentSystem } from './components/script/system.js'; import { ScrollViewComponentSystem } from './components/scroll-view/system.js'; import { ScrollbarComponentSystem } from './components/scrollbar/system.js'; import { SoundComponentSystem } from './components/sound/system.js'; import { SpriteComponentSystem } from './components/sprite/system.js'; import { ZoneComponentSystem } from './components/zone/system.js'; -import { CameraComponentSystem } from './components/camera/system.js'; -import { LightComponentSystem } from './components/light/system.js'; -import { ScriptComponentSystem } from './components/script/system.js'; -import { GSplatComponentSystem } from './components/gsplat/system.js'; -import { RenderHandler } from './handlers/render.js'; -import { AnimationHandler } from './handlers/animation.js'; import { AnimClipHandler } from './handlers/anim-clip.js'; import { AnimStateGraphHandler } from './handlers/anim-state-graph.js'; +import { AnimationHandler } from './handlers/animation.js'; import { AudioHandler } from './handlers/audio.js'; import { BinaryHandler } from './handlers/binary.js'; import { ContainerHandler } from './handlers/container.js'; @@ -45,6 +39,7 @@ import { HtmlHandler } from './handlers/html.js'; import { JsonHandler } from './handlers/json.js'; import { MaterialHandler } from './handlers/material.js'; import { ModelHandler } from './handlers/model.js'; +import { RenderHandler } from './handlers/render.js'; import { SceneHandler } from './handlers/scene.js'; import { ScriptHandler } from './handlers/script.js'; import { ShaderHandler } from './handlers/shader.js'; @@ -53,7 +48,12 @@ import { TemplateHandler } from './handlers/template.js'; import { TextHandler } from './handlers/text.js'; import { TextureAtlasHandler } from './handlers/texture-atlas.js'; import { TextureHandler } from './handlers/texture.js'; +import { Lightmapper } from './lightmapper/lightmapper.js'; import { XrManager } from './xr/xr-manager.js'; +import { platform } from '../core/platform.js'; +import { WebglGraphicsDevice } from '../platform/graphics/webgl/webgl-graphics-device.js'; +import { SoundManager } from '../platform/sound/manager.js'; +import { BatchManager } from '../scene/batching/batch-manager.js'; /** * @import { ElementInput } from './input/element-input.js' diff --git a/src/framework/asset/asset-list-loader.js b/src/framework/asset/asset-list-loader.js index cda31f46eb0..9512e93b4ab 100644 --- a/src/framework/asset/asset-list-loader.js +++ b/src/framework/asset/asset-list-loader.js @@ -1,5 +1,5 @@ -import { EventHandler } from '../../core/event-handler.js'; import { Asset } from './asset.js'; +import { EventHandler } from '../../core/event-handler.js'; /** * @import { AssetRegistry } from './asset-registry.js' @@ -98,15 +98,15 @@ class AssetListLoader extends EventHandler { */ destroy() { // remove any outstanding listeners - this._registry.off("load", this._onLoad); - this._registry.off("error", this._onError); + this._registry.off('load', this._onLoad); + this._registry.off('error', this._onError); this._waitingAssets.forEach((id) => { - this._registry.off("add:" + id, this._onAddAsset); + this._registry.off(`add:${id}`, this._onAddAsset); }); - this.off("progress"); - this.off("load"); + this.off('progress'); + this.off('load'); } _assetHasDependencies(asset) { @@ -124,7 +124,7 @@ class AssetListLoader extends EventHandler { load(done, scope) { if (this._loading) { // #if _DEBUG - console.debug("AssetListLoader: Load function called multiple times."); + console.debug('AssetListLoader: Load function called multiple times.'); // #endif return; } @@ -132,8 +132,8 @@ class AssetListLoader extends EventHandler { this._callback = done; this._scope = scope; - this._registry.on("load", this._onLoad, this); - this._registry.on("error", this._onError, this); + this._registry.on('load', this._onLoad, this); + this._registry.on('error', this._onError, this); let loadingAssets = false; this._assets.forEach((asset) => { @@ -175,7 +175,7 @@ class AssetListLoader extends EventHandler { if (this._loaded) { done.call(scope, Array.from(this._assets)); } else { - this.once("load", (assets) => { + this.once('load', (assets) => { done.call(scope, assets); }); } @@ -185,19 +185,19 @@ class AssetListLoader extends EventHandler { _loadingComplete() { if (this._loaded) return; this._loaded = true; - this._registry.off("load", this._onLoad, this); - this._registry.off("error", this._onError, this); + this._registry.off('load', this._onLoad, this); + this._registry.off('error', this._onError, this); if (this._failed.length) { if (this._callback) { - this._callback.call(this._scope, "Failed to load some assets", this._failed); + this._callback.call(this._scope, 'Failed to load some assets', this._failed); } - this.fire("error", this._failed); + this.fire('error', this._failed); } else { if (this._callback) { this._callback.call(this._scope); } - this.fire("load", Array.from(this._assets)); + this.fire('load', Array.from(this._assets)); } } @@ -205,7 +205,7 @@ class AssetListLoader extends EventHandler { _onLoad(asset) { // check this is an asset we care about if (this._loadingAssets.has(asset)) { - this.fire("progress", asset); + this.fire('progress', asset); this._loadingAssets.delete(asset); } @@ -251,7 +251,7 @@ class AssetListLoader extends EventHandler { _waitForAsset(assetId) { this._waitingAssets.add(assetId); - this._registry.once('add:' + assetId, this._onAddAsset, this); + this._registry.once(`add:${assetId}`, this._onAddAsset, this); } } diff --git a/src/framework/asset/asset-localized.js b/src/framework/asset/asset-localized.js index 66f43b47034..bfca7a37081 100644 --- a/src/framework/asset/asset-localized.js +++ b/src/framework/asset/asset-localized.js @@ -1,6 +1,6 @@ +import { Asset } from './asset.js'; import { EventHandler } from '../../core/event-handler.js'; -import { Asset } from './asset.js'; class LocalizedAsset extends EventHandler { constructor(app) { @@ -54,7 +54,7 @@ class LocalizedAsset extends EventHandler { } if (this._localizedAsset) { - this._app.assets.off('add:' + this._localizedAsset, this._onLocalizedAssetAdd, this); + this._app.assets.off(`add:${this._localizedAsset}`, this._onLocalizedAssetAdd, this); this._unbindLocalizedAsset(); } @@ -63,7 +63,7 @@ class LocalizedAsset extends EventHandler { if (this._localizedAsset) { const asset = this._app.assets.get(this._localizedAsset); if (!asset) { - this._app.assets.once('add:' + this._localizedAsset, this._onLocalizedAssetAdd, this); + this._app.assets.once(`add:${this._localizedAsset}`, this._onLocalizedAssetAdd, this); } else { this._bindLocalizedAsset(); } @@ -105,7 +105,7 @@ class LocalizedAsset extends EventHandler { _bindDefaultAsset() { const asset = this._app.assets.get(this._defaultAsset); if (!asset) { - this._app.assets.once('add:' + this._defaultAsset, this._onDefaultAssetAdd, this); + this._app.assets.once(`add:${this._defaultAsset}`, this._onDefaultAssetAdd, this); } else { this._onDefaultAssetAdd(asset); } @@ -114,7 +114,7 @@ class LocalizedAsset extends EventHandler { _unbindDefaultAsset() { if (!this._defaultAsset) return; - this._app.assets.off('add:' + this._defaultAsset, this._onDefaultAssetAdd, this); + this._app.assets.off(`add:${this._defaultAsset}`, this._onDefaultAssetAdd, this); const asset = this._app.assets.get(this._defaultAsset); if (!asset) return; @@ -136,7 +136,7 @@ class LocalizedAsset extends EventHandler { if (this._defaultAsset !== asset.id) return; asset.off('add:localized', this._onLocaleAdd, this); asset.off('remove:localized', this._onLocaleAdd, this); - this._app.assets.once('add:' + this._defaultAsset, this._onDefaultAssetAdd, this); + this._app.assets.once(`add:${this._defaultAsset}`, this._onDefaultAssetAdd, this); } _bindLocalizedAsset() { diff --git a/src/framework/asset/asset-reference.js b/src/framework/asset/asset-reference.js index 6e54b56c392..6e826324a7d 100644 --- a/src/framework/asset/asset-reference.js +++ b/src/framework/asset/asset-reference.js @@ -109,30 +109,30 @@ class AssetReference { _bind() { if (this.id) { - if (this._onAssetLoad) this._registry.on('load:' + this.id, this._onLoad, this); - if (this._onAssetAdd) this._registry.once('add:' + this.id, this._onAdd, this); - if (this._onAssetRemove) this._registry.on('remove:' + this.id, this._onRemove, this); - if (this._onAssetUnload) this._registry.on('unload:' + this.id, this._onUnload, this); + if (this._onAssetLoad) this._registry.on(`load:${this.id}`, this._onLoad, this); + if (this._onAssetAdd) this._registry.once(`add:${this.id}`, this._onAdd, this); + if (this._onAssetRemove) this._registry.on(`remove:${this.id}`, this._onRemove, this); + if (this._onAssetUnload) this._registry.on(`unload:${this.id}`, this._onUnload, this); } if (this.url) { - if (this._onAssetLoad) this._registry.on('load:url:' + this.url, this._onLoad, this); - if (this._onAssetAdd) this._registry.once('add:url:' + this.url, this._onAdd, this); - if (this._onAssetRemove) this._registry.on('remove:url:' + this.url, this._onRemove, this); + if (this._onAssetLoad) this._registry.on(`load:url:${this.url}`, this._onLoad, this); + if (this._onAssetAdd) this._registry.once(`add:url:${this.url}`, this._onAdd, this); + if (this._onAssetRemove) this._registry.on(`remove:url:${this.url}`, this._onRemove, this); } } _unbind() { if (this.id) { - if (this._onAssetLoad) this._registry.off('load:' + this.id, this._onLoad, this); - if (this._onAssetAdd) this._registry.off('add:' + this.id, this._onAdd, this); - if (this._onAssetRemove) this._registry.off('remove:' + this.id, this._onRemove, this); - if (this._onAssetUnload) this._registry.off('unload:' + this.id, this._onUnload, this); + if (this._onAssetLoad) this._registry.off(`load:${this.id}`, this._onLoad, this); + if (this._onAssetAdd) this._registry.off(`add:${this.id}`, this._onAdd, this); + if (this._onAssetRemove) this._registry.off(`remove:${this.id}`, this._onRemove, this); + if (this._onAssetUnload) this._registry.off(`unload:${this.id}`, this._onUnload, this); } if (this.url) { - if (this._onAssetLoad) this._registry.off('load:' + this.url, this._onLoad, this); - if (this._onAssetAdd) this._registry.off('add:' + this.url, this._onAdd, this); - if (this._onAssetRemove) this._registry.off('remove:' + this.url, this._onRemove, this); + if (this._onAssetLoad) this._registry.off(`load:${this.url}`, this._onLoad, this); + if (this._onAssetAdd) this._registry.off(`add:${this.url}`, this._onAdd, this); + if (this._onAssetRemove) this._registry.off(`remove:${this.url}`, this._onRemove, this); } } diff --git a/src/framework/asset/asset-registry.js b/src/framework/asset/asset-registry.js index 26bcd1e2ef4..79f115d8b84 100644 --- a/src/framework/asset/asset-registry.js +++ b/src/framework/asset/asset-registry.js @@ -1,9 +1,9 @@ -import { path } from '../../core/path.js'; +import { Asset } from './asset.js'; import { Debug } from '../../core/debug.js'; import { EventHandler } from '../../core/event-handler.js'; +import { path } from '../../core/path.js'; import { TagsCache } from '../../core/tags-cache.js'; import { standardMaterialTextureParameters } from '../../scene/materials/standard-material-parameters.js'; -import { Asset } from './asset.js'; /** * @import { Bundle } from '../bundle/bundle.js' @@ -258,8 +258,9 @@ class AssetRegistry extends EventHandler { this._urlToAsset.set(asset.file.url, asset); } - if (!this._nameToAsset.has(asset.name)) + if (!this._nameToAsset.has(asset.name)) { this._nameToAsset.set(asset.name, new Set()); + } this._nameToAsset.get(asset.name).add(asset); @@ -273,13 +274,14 @@ class AssetRegistry extends EventHandler { asset.tags.on('remove', this._onTagRemove, this); this.fire('add', asset); - this.fire('add:' + asset.id, asset); + this.fire(`add:${asset.id}`, asset); if (asset.file?.url) { - this.fire('add:url:' + asset.file.url, asset); + this.fire(`add:url:${asset.file.url}`, asset); } - if (asset.preload) + if (asset.preload) { this.load(asset); + } } /** @@ -319,9 +321,9 @@ class AssetRegistry extends EventHandler { asset.fire('remove', asset); this.fire('remove', asset); - this.fire('remove:' + asset.id, asset); + this.fire(`remove:${asset.id}`, asset); if (asset.file?.url) { - this.fire('remove:url:' + asset.file.url, asset); + this.fire(`remove:url:${asset.file.url}`, asset); } return true; @@ -395,9 +397,10 @@ class AssetRegistry extends EventHandler { const _fireLoad = () => { this.fire('load', asset); - this.fire('load:' + asset.id, asset); - if (file && file.url) - this.fire('load:url:' + file.url, asset); + this.fire(`load:${asset.id}`, asset); + if (file && file.url) { + this.fire(`load:url:${file.url}`, asset); + } asset.fire('load', asset); }; @@ -425,9 +428,10 @@ class AssetRegistry extends EventHandler { _fireLoad(); } else { this.fire('load:start', asset); - this.fire('load:start:' + asset.id, asset); - if (file && file.url) - this.fire('load:start:url:' + file.url, asset); + this.fire(`load:start:${asset.id}`, asset); + if (file && file.url) { + this.fire(`load:start:url:${file.url}`, asset); + } asset.fire('load:start', asset); asset.resource.on('load', _fireLoad); } @@ -443,7 +447,7 @@ class AssetRegistry extends EventHandler { if (err) { this.fire('error', err, asset); - this.fire('error:' + asset.id, err, asset); + this.fire(`error:${asset.id}`, err, asset); asset.fire('error', err, asset); } else { if (asset.type === 'script') { @@ -462,7 +466,7 @@ class AssetRegistry extends EventHandler { if (file || asset.type === 'cubemap') { // start loading the resource this.fire('load:start', asset); - this.fire('load:' + asset.id + ':start', asset); + this.fire(`load:${asset.id}:start`, asset); asset.loading = true; @@ -473,11 +477,13 @@ class AssetRegistry extends EventHandler { const assetIds = asset.data.assets; for (let i = 0; i < assetIds.length; i++) { const assetInBundle = this._idToAsset.get(assetIds[i]); - if (!assetInBundle) + if (!assetInBundle) { continue; + } - if (assetInBundle.loaded || assetInBundle.resource || assetInBundle.loading) + if (assetInBundle.loaded || assetInBundle.resource || assetInBundle.loading) { continue; + } assetInBundle.loading = true; } @@ -685,8 +691,9 @@ class AssetRegistry extends EventHandler { } // add - if (!this._nameToAsset.has(asset.name)) + if (!this._nameToAsset.has(asset.name)) { this._nameToAsset.set(asset.name, new Set()); + } this._nameToAsset.get(asset.name).add(asset); } diff --git a/src/framework/asset/asset.js b/src/framework/asset/asset.js index 25b6275e7cc..4d902e00604 100644 --- a/src/framework/asset/asset.js +++ b/src/framework/asset/asset.js @@ -1,11 +1,11 @@ +import { AssetFile } from './asset-file.js'; +import { ABSOLUTE_URL } from './constants.js'; +import { EventHandler } from '../../core/event-handler.js'; import { path } from '../../core/path.js'; import { Tags } from '../../core/tags.js'; -import { EventHandler } from '../../core/event-handler.js'; -import { findAvailableLocale } from '../i18n/utils.js'; -import { ABSOLUTE_URL } from './constants.js'; -import { AssetFile } from './asset-file.js'; -import { getApplication } from '../globals.js'; import { http } from '../../platform/net/http.js'; +import { getApplication } from '../globals.js'; +import { findAvailableLocale } from '../i18n/utils.js'; /** * @import { AssetRegistry } from './asset-registry.js' @@ -253,8 +253,9 @@ class Asset extends EventHandler { * @type {string} */ set name(value) { - if (this._name === value) + if (this._name === value) { return; + } const old = this._name; this._name = value; this.fire('name', this, this._name, old); @@ -338,8 +339,9 @@ class Asset extends EventHandler { if (value !== old) { this.fire('change', this, 'data', value, old); - if (this.loaded) + if (this.loaded) { this.registry._loader.patch(this, this.registry); + } } } @@ -401,12 +403,14 @@ class Asset extends EventHandler { */ set preload(value) { value = !!value; - if (this._preload === value) + if (this._preload === value) { return; + } this._preload = value; - if (this._preload && !this.loaded && !this.loading && this.registry) + if (this._preload && !this.loaded && !this.loading && this.registry) { this.registry.load(this); + } } /** @@ -426,8 +430,9 @@ class Asset extends EventHandler { // the loadFaces property should be part of the asset data block // because changing the flag should result in asset patch being invoked. // here we must invoke it manually instead. - if (this.loaded) + if (this.loaded) { this.registry._loader.patch(this, this.registry); + } } } @@ -446,18 +451,20 @@ class Asset extends EventHandler { getFileUrl() { const file = this.file; - if (!file || !file.url) + if (!file || !file.url) { return null; + } let url = file.url; - if (this.registry && this.registry.prefix && !ABSOLUTE_URL.test(url)) + if (this.registry && this.registry.prefix && !ABSOLUTE_URL.test(url)) { url = this.registry.prefix + url; + } // add file hash to avoid hard-caching problems if (this.type !== 'script' && file.hash) { const separator = url.indexOf('?') !== -1 ? '&' : '?'; - url += separator + 't=' + file.hash; + url += `${separator}t=${file.hash}`; } return url; @@ -541,7 +548,7 @@ class Asset extends EventHandler { if (this.loaded) { callback.call(scope, this); } else { - this.once('load', function (asset) { + this.once('load', (asset) => { callback.call(scope, asset); }); } @@ -564,11 +571,12 @@ class Asset extends EventHandler { * // asset.resource is null */ unload() { - if (!this.loaded && this._resources.length === 0) + if (!this.loaded && this._resources.length === 0) { return; + } this.fire('unload', this); - this.registry.fire('unload:' + this.id, this); + this.registry.fire(`unload:${this.id}`, this); const old = this._resources; diff --git a/src/framework/asset/constants.js b/src/framework/asset/constants.js index 38c15b5c042..2f61395fe43 100644 --- a/src/framework/asset/constants.js +++ b/src/framework/asset/constants.js @@ -4,7 +4,8 @@ export const ABSOLUTE_URL = new RegExp( '(?:' + // beginning of a non-captured regex group // `{protocol}://` '(?:' + // beginning of protocol scheme (non-captured regex group) - '[a-z]+[a-z0-9\\-\\+\\.]*' + // protocol scheme must (RFC 3986) consist of "a letter and followed by any combination of letters, digits, plus ("+"), period ("."), or hyphen ("-")." + // eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/optimal-quantifier-concatenation + '[a-z]+[a-z0-9\\-+.]*' + // protocol scheme must (RFC 3986) consist of "a letter and followed by any combination of letters, digits, plus ("+"), period ("."), or hyphen ("-")." ':' + // protocol scheme must end with colon character ')?' + // end of optional scheme group, the group is optional since the string may be a protocol-relative absolute URL '//' + // an absolute url must always begin with two forward slash characters (ignoring any leading spaces and protocol scheme) diff --git a/src/framework/bundle/bundle-registry.js b/src/framework/bundle/bundle-registry.js index 2985c1f543f..d1f7279ff2d 100644 --- a/src/framework/bundle/bundle-registry.js +++ b/src/framework/bundle/bundle-registry.js @@ -77,9 +77,9 @@ class BundleRegistry { } _unbindAssetEvents(id) { - this._assets.off('load:start:' + id, this._onBundleLoadStart, this); - this._assets.off('load:' + id, this._onBundleLoad, this); - this._assets.off('error:' + id, this._onBundleError, this); + this._assets.off(`load:start:${id}`, this._onBundleLoadStart, this); + this._assets.off(`load:${id}`, this._onBundleLoad, this); + this._assets.off(`error:${id}`, this._onBundleError, this); } // Index the specified asset id and its file URLs so that @@ -123,7 +123,7 @@ class BundleRegistry { if (asset.type === 'font') { const numFiles = asset.data.info.maps.length; for (let i = 1; i < numFiles; i++) { - urls.push(url.replace('.png', i + '.png')); + urls.push(url.replace('.png', `${i}.png`)); } } @@ -149,8 +149,9 @@ class BundleRegistry { if (bundles.size === 0) { this._assetToBundles.delete(assetIds[i]); for (const [url, otherBundles] of this._urlsToBundles) { - if (otherBundles !== bundles) + if (otherBundles !== bundles) { continue; + } this._urlsToBundles.delete(url); } } @@ -196,8 +197,9 @@ class BundleRegistry { } // make sure the registry hasn't been destroyed already - if (!this._fileRequests) + if (!this._fileRequests) { return; + } for (const [url, requests] of this._fileRequests) { const bundles = this._urlsToBundles.get(url); @@ -231,8 +233,9 @@ class BundleRegistry { for (const [url, requests] of this._fileRequests) { const bundle = this._findLoadedOrLoadingBundleForUrl(url); if (!bundle) { - for (let i = 0; i < requests.length; i++) + for (let i = 0; i < requests.length; i++) { requests[i](err); + } this._fileRequests.delete(url); } diff --git a/src/framework/bundle/bundle.js b/src/framework/bundle/bundle.js index 475e3bdc72a..caeb65f7ab9 100644 --- a/src/framework/bundle/bundle.js +++ b/src/framework/bundle/bundle.js @@ -50,8 +50,9 @@ class Bundle extends EventHandler { * @ignore */ addFile(url, data) { - if (this._index.has(url)) + if (this._index.has(url)) { return; + } this._index.set(url, data); this.fire('add', url, data); } @@ -90,8 +91,9 @@ class Bundle extends EventHandler { * @type {boolean} */ set loaded(value) { - if (!value || this._loaded) + if (!value || this._loaded) { return; + } this._loaded = true; this.fire('load'); diff --git a/src/framework/components/anim/component-binder.js b/src/framework/components/anim/component-binder.js index 12817749e9e..f751a857960 100644 --- a/src/framework/components/anim/component-binder.js +++ b/src/framework/components/anim/component-binder.js @@ -1,12 +1,11 @@ -import { AnimTarget } from '../../anim/evaluator/anim-target.js'; -import { DefaultAnimBinder } from '../../anim/binder/default-anim-binder.js'; -import { AnimBinder } from '../../anim/binder/anim-binder.js'; - import { Color } from '../../../core/math/color.js'; import { Quat } from '../../../core/math/quat.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { Vec4 } from '../../../core/math/vec4.js'; +import { AnimBinder } from '../../anim/binder/anim-binder.js'; +import { DefaultAnimBinder } from '../../anim/binder/default-anim-binder.js'; +import { AnimTarget } from '../../anim/evaluator/anim-target.js'; const v2 = new Vec2(); const v3 = new Vec3(); @@ -99,8 +98,9 @@ class AnimComponentBinder extends DefaultAnimBinder { default: entity = this._getEntityFromHierarchy(path.entityPath); propertyComponent = entity.findComponent(path.component); - if (!propertyComponent) + if (!propertyComponent) { return null; + } targetPath = AnimBinder.encode( entity.path, path.component, @@ -154,10 +154,10 @@ class AnimComponentBinder extends DefaultAnimBinder { const key = path[path.length - 1]; // if the object has a setter function, use it - const setterFuncName = 'set' + key.substring(0, 1).toUpperCase() + key.substring(1); + const setterFuncName = `set${key.substring(0, 1).toUpperCase()}${key.substring(1)}`; if (obj[setterFuncName]) { // if the object has a setter function, use it - const getterFunc = obj['get' + key.substring(0, 1).toUpperCase() + key.substring(1)].bind(obj); + const getterFunc = obj[`get${key.substring(0, 1).toUpperCase()}${key.substring(1)}`].bind(obj); let baseValues = getterFunc(); baseValues = [baseValues.x, baseValues.y, baseValues.z, baseValues.w]; const setterFunc = obj[setterFuncName].bind(obj); @@ -210,8 +210,9 @@ class AnimComponentBinder extends DefaultAnimBinder { const property = this._resolvePath(propertyComponent, propertyHierarchy, true); - if (typeof property === 'undefined') + if (typeof property === 'undefined') { return null; + } let setter; let animDataType; @@ -259,7 +260,7 @@ class AnimComponentBinder extends DefaultAnimBinder { // materials must have update called after changing settings if (propertyHierarchy.indexOf('material') !== -1) { - return new AnimTarget(function (values) { + return new AnimTarget((values) => { setter(values); propertyComponent.material.update(); }, animDataType, animDataComponents, targetPath); diff --git a/src/framework/components/anim/component-layer.js b/src/framework/components/anim/component-layer.js index b724b45604d..a8496f40ae5 100644 --- a/src/framework/components/anim/component-layer.js +++ b/src/framework/components/anim/component-layer.js @@ -1,8 +1,8 @@ import { Debug } from '../../../core/debug.js'; import { math } from '../../../core/math/math.js'; -import { AnimTrack } from '../../anim/evaluator/anim-track.js'; import { AnimTransition } from '../../anim/controller/anim-transition.js'; import { ANIM_LAYER_OVERWRITE } from '../../anim/controller/constants.js'; +import { AnimTrack } from '../../anim/evaluator/anim-track.js'; /** * @import { AnimComponent } from './component.js' diff --git a/src/framework/components/anim/component.js b/src/framework/components/anim/component.js index 69486a1f2d4..34ed9c93da6 100644 --- a/src/framework/components/anim/component.js +++ b/src/framework/components/anim/component.js @@ -1,16 +1,16 @@ -import { Debug } from '../../../core/debug.js'; -import { Asset } from '../../asset/asset.js'; -import { AnimEvaluator } from '../../anim/evaluator/anim-evaluator.js'; -import { AnimController } from '../../anim/controller/anim-controller.js'; -import { Component } from '../component.js'; import { AnimComponentBinder } from './component-binder.js'; import { AnimComponentLayer } from './component-layer.js'; -import { AnimStateGraph } from '../../anim/state-graph/anim-state-graph.js'; -import { Entity } from '../../entity.js'; +import { Debug } from '../../../core/debug.js'; +import { AnimController } from '../../anim/controller/anim-controller.js'; import { ANIM_PARAMETER_BOOLEAN, ANIM_PARAMETER_FLOAT, ANIM_PARAMETER_INTEGER, ANIM_PARAMETER_TRIGGER, ANIM_CONTROL_STATES } from '../../anim/controller/constants.js'; +import { AnimEvaluator } from '../../anim/evaluator/anim-evaluator.js'; import { AnimTrack } from '../../anim/evaluator/anim-track.js'; +import { AnimStateGraph } from '../../anim/state-graph/anim-state-graph.js'; +import { Asset } from '../../asset/asset.js'; +import { Entity } from '../../entity.js'; +import { Component } from '../component.js'; /** * @import { AnimComponentSystem } from './system.js' @@ -420,7 +420,7 @@ class AnimComponent extends Component { for (let j = 0; j < layer.states.length; j++) { const stateName = layer.states[j]; if (ANIM_CONTROL_STATES.indexOf(stateName) === -1) { - const stateKey = layerName + ':' + stateName; + const stateKey = `${layerName}:${stateName}`; if (!this._animationAssets[stateKey]) { this._animationAssets[stateKey] = { asset: null @@ -438,7 +438,7 @@ class AnimComponent extends Component { for (let j = 0; j < layer.states.length; j++) { const stateName = layer.states[j]; if (ANIM_CONTROL_STATES.indexOf(stateName) !== -1) continue; - const animationAsset = this._animationAssets[layer.name + ':' + stateName]; + const animationAsset = this._animationAssets[`${layer.name}:${stateName}`]; if (!animationAsset || !animationAsset.asset) { this.findAnimationLayer(layer.name).assignAnimation(stateName, AnimTrack.EMPTY); continue; diff --git a/src/framework/components/anim/system.js b/src/framework/components/anim/system.js index a5eca8fdc09..3f7a0ff70c4 100644 --- a/src/framework/components/anim/system.js +++ b/src/framework/components/anim/system.js @@ -1,8 +1,8 @@ +import { AnimComponent } from './component.js'; +import { AnimComponentData } from './data.js'; import { AnimTrack } from '../../anim/evaluator/anim-track.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { AnimComponent } from './component.js'; -import { AnimComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -55,7 +55,7 @@ class AnimComponentSystem extends ComponentSystem { layer._controller.states.forEach((stateKey) => { layer._controller._states[stateKey]._animationList.forEach((node) => { if (!node.animTrack || node.animTrack === AnimTrack.EMPTY) { - const animationAsset = this.app.assets.get(layer._component._animationAssets[layer.name + ':' + node.name].asset); + const animationAsset = this.app.assets.get(layer._component._animationAssets[`${layer.name}:${node.name}`].asset); // If there is an animation asset that hasn't been loaded, assign it once it has loaded. If it is already loaded it will be assigned already. if (animationAsset && !animationAsset.loaded) { animationAsset.once('load', () => { diff --git a/src/framework/components/animation/component.js b/src/framework/components/animation/component.js index 51b964824dc..7b0fa3fdaac 100644 --- a/src/framework/components/animation/component.js +++ b/src/framework/components/animation/component.js @@ -1,9 +1,9 @@ import { Debug } from '../../../core/debug.js'; +import { Skeleton } from '../../../scene/animation/skeleton.js'; +import { DefaultAnimBinder } from '../../anim/binder/default-anim-binder.js'; import { AnimClip } from '../../anim/evaluator/anim-clip.js'; import { AnimEvaluator } from '../../anim/evaluator/anim-evaluator.js'; import { AnimTrack } from '../../anim/evaluator/anim-track.js'; -import { DefaultAnimBinder } from '../../anim/binder/default-anim-binder.js'; -import { Skeleton } from '../../../scene/animation/skeleton.js'; import { Asset } from '../../asset/asset.js'; import { Component } from '../component.js'; @@ -159,8 +159,9 @@ class AnimationComponent extends Component { const animName = this.animationsIndex[asset.id]; - if (this.currAnim === animName) + if (this.currAnim === animName) { this._stopCurrentAnimation(); + } delete this.animations[animName]; delete this.animationsIndex[asset.id]; @@ -239,7 +240,7 @@ class AnimationComponent extends Component { return this.animations[this.currAnim].duration; } - Debug.warn(`No animation is playing to get a duration. Returning 0.`); + Debug.warn('No animation is playing to get a duration. Returning 0.'); return 0; } @@ -436,8 +437,9 @@ class AnimationComponent extends Component { * @private */ loadAnimationAssets(ids) { - if (!ids || !ids.length) + if (!ids || !ids.length) { return; + } const assets = this.system.app.assets; @@ -467,8 +469,9 @@ class AnimationComponent extends Component { onAssetReady(asset); } else { asset.once('load', onAssetReady, this); - if (this.enabled && this.entity.enabled) + if (this.enabled && this.entity.enabled) { assets.load(asset); + } } }; @@ -477,7 +480,7 @@ class AnimationComponent extends Component { if (asset) { onAssetAdd(asset); } else { - assets.on('add:' + ids[i], onAssetAdd); + assets.on(`add:${ids[i]}`, onAssetAdd); } } } @@ -579,13 +582,15 @@ class AnimationComponent extends Component { if (asset.resources.length > 1) { for (let i = 0; i < asset.resources.length; i++) { delete this.animations[asset.resources[i].name]; - if (this.currAnim === asset.resources[i].name) + if (this.currAnim === asset.resources[i].name) { this._stopCurrentAnimation(); + } } } else { delete this.animations[asset.name]; - if (this.currAnim === asset.name) + if (this.currAnim === asset.name) { this._stopCurrentAnimation(); + } } delete this.animationsIndex[asset.id]; } @@ -618,11 +623,13 @@ class AnimationComponent extends Component { if (assets) { for (let i = 0, len = assets.length; i < len; i++) { let asset = assets[i]; - if (!(asset instanceof Asset)) + if (!(asset instanceof Asset)) { asset = registry.get(asset); + } - if (asset && !asset.resource) + if (asset && !asset.resource) { registry.load(asset); + } } } diff --git a/src/framework/components/animation/system.js b/src/framework/components/animation/system.js index d7f7ea37427..d6eaadbdcf5 100644 --- a/src/framework/components/animation/system.js +++ b/src/framework/components/animation/system.js @@ -1,7 +1,7 @@ -import { Component } from '../component.js'; -import { ComponentSystem } from '../system.js'; import { AnimationComponent } from './component.js'; import { AnimationComponentData } from './data.js'; +import { Component } from '../component.js'; +import { ComponentSystem } from '../system.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/audio-listener/system.js b/src/framework/components/audio-listener/system.js index 960b4cab2fc..14db171eb36 100644 --- a/src/framework/components/audio-listener/system.js +++ b/src/framework/components/audio-listener/system.js @@ -1,8 +1,8 @@ +import { AudioListenerComponent } from './component.js'; +import { AudioListenerComponentData } from './data.js'; import { Debug } from '../../../core/debug.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { AudioListenerComponent } from './component.js'; -import { AudioListenerComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -33,7 +33,7 @@ class AudioListenerComponentSystem extends ComponentSystem { this.schema = _schema; this.manager = app.soundManager; - Debug.assert(this.manager, "AudioListenerComponentSystem cannot be created without sound manager"); + Debug.assert(this.manager, 'AudioListenerComponentSystem cannot be created without sound manager'); this.current = null; diff --git a/src/framework/components/button/component.js b/src/framework/components/button/component.js index ad7d96133c5..ee32bfc8885 100644 --- a/src/framework/components/button/component.js +++ b/src/framework/components/button/component.js @@ -1,9 +1,9 @@ -import { now } from '../../../core/time.js'; -import { math } from '../../../core/math/math.js'; +import { BUTTON_TRANSITION_MODE_SPRITE_CHANGE, BUTTON_TRANSITION_MODE_TINT } from './constants.js'; import { Color } from '../../../core/math/color.js'; +import { math } from '../../../core/math/math.js'; +import { now } from '../../../core/time.js'; import { EntityReference } from '../../utils/entity-reference.js'; import { Component } from '../component.js'; -import { BUTTON_TRANSITION_MODE_SPRITE_CHANGE, BUTTON_TRANSITION_MODE_TINT } from './constants.js'; import { ELEMENTTYPE_GROUP } from '../element/constants.js'; /** @@ -942,18 +942,21 @@ class ButtonComponent extends Component { !tintColor || !this._imageReference.hasComponent('element') || this._imageReference.entity.element.type === ELEMENTTYPE_GROUP - ) + ) { return; + } const color3 = toColor3(tintColor); this._isApplyingTint = true; - if (!color3.equals(this._imageReference.entity.element.color)) + if (!color3.equals(this._imageReference.entity.element.color)) { this._imageReference.entity.element.color = color3; + } - if (this._imageReference.entity.element.opacity !== tintColor.a) + if (this._imageReference.entity.element.opacity !== tintColor.a) { this._imageReference.entity.element.opacity = tintColor.a; + } this._isApplyingTint = false; } @@ -963,8 +966,9 @@ class ButtonComponent extends Component { !tintColor || !this._imageReference.hasComponent('element') || this._imageReference.entity.element.type === ELEMENTTYPE_GROUP - ) + ) { return; + } const color3 = toColor3(tintColor); const color = this._imageReference.entity.element.color; diff --git a/src/framework/components/button/data.js b/src/framework/components/button/data.js index 300ee807aa8..3bed4982174 100644 --- a/src/framework/components/button/data.js +++ b/src/framework/components/button/data.js @@ -1,6 +1,6 @@ +import { BUTTON_TRANSITION_MODE_TINT } from './constants.js'; import { Color } from '../../../core/math/color.js'; import { Vec4 } from '../../../core/math/vec4.js'; -import { BUTTON_TRANSITION_MODE_TINT } from './constants.js'; /** * @import { Asset } from '../../../framework/asset/asset.js' diff --git a/src/framework/components/button/system.js b/src/framework/components/button/system.js index 4a3404010d0..1783b3f8174 100644 --- a/src/framework/components/button/system.js +++ b/src/framework/components/button/system.js @@ -1,6 +1,6 @@ -import { ComponentSystem } from '../system.js'; import { ButtonComponent } from './component.js'; import { ButtonComponentData } from './data.js'; +import { ComponentSystem } from '../system.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/camera/component.js b/src/framework/components/camera/component.js index f02c0422496..1c30d310d56 100644 --- a/src/framework/components/camera/component.js +++ b/src/framework/components/camera/component.js @@ -1,9 +1,9 @@ +import { PostEffectQueue } from './post-effect-queue.js'; import { Debug } from '../../../core/debug.js'; -import { ASPECT_AUTO, LAYERID_UI, LAYERID_DEPTH } from '../../../scene/constants.js'; import { Camera } from '../../../scene/camera.js'; +import { ASPECT_AUTO, LAYERID_UI, LAYERID_DEPTH } from '../../../scene/constants.js'; import { ShaderPass } from '../../../scene/shader-pass.js'; import { Component } from '../component.js'; -import { PostEffectQueue } from './post-effect-queue.js'; /** * @import { CameraComponentSystem } from './system.js' diff --git a/src/framework/components/camera/post-effect-queue.js b/src/framework/components/camera/post-effect-queue.js index ebf9c311b84..5c5c8e16fb3 100644 --- a/src/framework/components/camera/post-effect-queue.js +++ b/src/framework/components/camera/post-effect-queue.js @@ -116,7 +116,7 @@ class PostEffectQueue { const format = (hdr && device.getRenderableHdrFormat([PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F], true)) ?? (srgb ? PIXELFORMAT_SRGBA8 : PIXELFORMAT_RGBA8); - const name = this.camera.entity.name + '-posteffect-' + this.effects.length; + const name = `${this.camera.entity.name}-posteffect-${this.effects.length}`; const colorBuffer = this._allocateColorBuffer(format, name); @@ -233,8 +233,9 @@ class PostEffectQueue { _requestDepthMaps() { for (let i = 0, len = this.effects.length; i < len; i++) { const effect = this.effects[i].effect; - if (this._newPostEffect === effect) + if (this._newPostEffect === effect) { continue; + } if (effect.needsDepthBuffer) { this._requestDepthMap(); diff --git a/src/framework/components/camera/system.js b/src/framework/components/camera/system.js index 84d872a04f5..a1a3ba1e4a7 100644 --- a/src/framework/components/camera/system.js +++ b/src/framework/components/camera/system.js @@ -1,10 +1,10 @@ -import { sortPriority } from '../../../core/sort.js'; +import { CameraComponent } from './component.js'; +import { CameraComponentData } from './data.js'; import { Color } from '../../../core/math/color.js'; import { Vec4 } from '../../../core/math/vec4.js'; +import { sortPriority } from '../../../core/sort.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { CameraComponent } from './component.js'; -import { CameraComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/collision/system.js b/src/framework/components/collision/system.js index 2187aafce2b..bd070cbae3c 100644 --- a/src/framework/components/collision/system.js +++ b/src/framework/components/collision/system.js @@ -1,3 +1,6 @@ +import { CollisionComponent } from './component.js'; +import { CollisionComponentData } from './data.js'; +import { Trigger } from './trigger.js'; import { Debug } from '../../../core/debug.js'; import { Mat4 } from '../../../core/math/mat4.js'; import { Quat } from '../../../core/math/quat.js'; @@ -6,9 +9,6 @@ import { SEMANTIC_POSITION } from '../../../platform/graphics/constants.js'; import { GraphNode } from '../../../scene/graph-node.js'; import { Model } from '../../../scene/model.js'; import { ComponentSystem } from '../system.js'; -import { CollisionComponent } from './component.js'; -import { CollisionComponentData } from './data.js'; -import { Trigger } from './trigger.js'; /** * @import { AppBase } from '../../app-base.js' @@ -79,8 +79,9 @@ class CollisionSystemImpl { if (component._compoundParent) { this.system._removeCompoundChild(component._compoundParent, data.shape); - if (component._compoundParent.entity.rigidbody) + if (component._compoundParent.entity.rigidbody) { component._compoundParent.entity.rigidbody.activate(); + } } this.destroyShape(data); @@ -119,8 +120,9 @@ class CollisionSystemImpl { } else { this.system.updateCompoundChildTransform(entity); - if (component._compoundParent.entity.rigidbody) + if (component._compoundParent.entity.rigidbody) { component._compoundParent.entity.rigidbody.activate(); + } } } } @@ -167,8 +169,9 @@ class CollisionSystemImpl { if (component._compoundParent && !component._compoundParent.entity._destroying) { this.system._removeCompoundChild(component._compoundParent, component.data.shape); - if (component._compoundParent.entity.rigidbody) + if (component._compoundParent.entity.rigidbody) { component._compoundParent.entity.rigidbody.activate(); + } } component._compoundParent = null; @@ -292,8 +295,9 @@ class CollisionCylinderSystemImpl extends CollisionSystemImpl { } } - if (halfExtents) + if (halfExtents) { Ammo.destroy(halfExtents); + } return shape; } @@ -537,7 +541,7 @@ class CollisionMeshSystemImpl extends CollisionSystemImpl { if (asset) { loadAndHandleAsset(asset); } else { - assets.once('add:' + id, loadAndHandleAsset); + assets.once(`add:${id}`, loadAndHandleAsset); } } @@ -588,8 +592,9 @@ class CollisionMeshSystemImpl extends CollisionSystemImpl { } destroyShape(data) { - if (!data.shape) + if (!data.shape) { return; + } const numShapes = data.shape.getNumChildShapes(); for (let i = 0; i < numShapes; i++) { @@ -612,8 +617,9 @@ class CollisionCompoundSystemImpl extends CollisionSystemImpl { } _addEachDescendant(entity) { - if (!entity.collision || entity.rigidbody) + if (!entity.collision || entity.rigidbody) { return; + } entity.collision._compoundParent = this; @@ -623,11 +629,13 @@ class CollisionCompoundSystemImpl extends CollisionSystemImpl { } _updateEachDescendant(entity) { - if (!entity.collision) + if (!entity.collision) { return; + } - if (entity.collision._compoundParent !== this) + if (entity.collision._compoundParent !== this) { return; + } entity.collision._compoundParent = null; @@ -637,8 +645,9 @@ class CollisionCompoundSystemImpl extends CollisionSystemImpl { } _updateEachDescendantTransform(entity) { - if (!entity.collision || entity.collision._compoundParent !== this.collision._compoundParent) + if (!entity.collision || entity.collision._compoundParent !== this.collision._compoundParent) { return; + } this.collision.system.updateCompoundChildTransform(entity); } diff --git a/src/framework/components/component.js b/src/framework/components/component.js index 988d0be96b6..bf05a3b8cfa 100644 --- a/src/framework/components/component.js +++ b/src/framework/components/component.js @@ -50,7 +50,7 @@ class Component extends EventHandler { } this.on('set', function (name, oldValue, newValue) { - this.fire('set_' + name, name, oldValue, newValue); + this.fire(`set_${name}`, name, oldValue, newValue); }); this.on('set_enabled', this.onSetEnabled, this); @@ -59,7 +59,7 @@ class Component extends EventHandler { /** @ignore */ static _buildAccessors(obj, schema) { // Create getter/setter pairs for each property defined in the schema - schema.forEach(function (descriptor) { + schema.forEach((descriptor) => { // If the property descriptor is an object, it should have a `name` // member. If not, it should just be the plain property name. const name = (typeof descriptor === 'object') ? descriptor.name : descriptor; diff --git a/src/framework/components/element/component.js b/src/framework/components/element/component.js index 808cc61df76..e351cc1b26a 100644 --- a/src/framework/components/element/component.js +++ b/src/framework/components/element/component.js @@ -1,18 +1,18 @@ -import { Debug } from '../../../core/debug.js'; +import { ELEMENTTYPE_GROUP, ELEMENTTYPE_IMAGE, ELEMENTTYPE_TEXT, FITMODE_STRETCH } from './constants.js'; +import { ImageElement } from './image-element.js'; +import { TextElement } from './text-element.js'; import { TRACE_ID_ELEMENT } from '../../../core/constants.js'; +import { Debug } from '../../../core/debug.js'; import { Mat4 } from '../../../core/math/mat4.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { Vec4 } from '../../../core/math/vec4.js'; import { FUNC_ALWAYS, FUNC_EQUAL, STENCILOP_INCREMENT, STENCILOP_REPLACE } from '../../../platform/graphics/constants.js'; -import { LAYERID_UI } from '../../../scene/constants.js'; -import { BatchGroup } from '../../../scene/batching/batch-group.js'; import { StencilParameters } from '../../../platform/graphics/stencil-parameters.js'; +import { BatchGroup } from '../../../scene/batching/batch-group.js'; +import { LAYERID_UI } from '../../../scene/constants.js'; import { Entity } from '../../entity.js'; import { Component } from '../component.js'; -import { ELEMENTTYPE_GROUP, ELEMENTTYPE_IMAGE, ELEMENTTYPE_TEXT, FITMODE_STRETCH } from './constants.js'; -import { ImageElement } from './image-element.js'; -import { TextElement } from './text-element.js'; /** * @import { BoundingBox } from '../../../core/shape/bounding-box.js' @@ -603,7 +603,7 @@ class ElementComponent extends Component { } if (value > 0xFFFFFF) { - Debug.warn('Element.drawOrder larger than max size of: ' + 0xFFFFFF); + Debug.warn(`Element.drawOrder larger than max size of: ${0xFFFFFF}`); value = 0xFFFFFF; } @@ -2159,7 +2159,7 @@ class ElementComponent extends Component { // transform element hierarchy if (this._parent.element) { element._screenToWorld.mul2(this._parent.element._modelTransform, - element._anchorTransform); + element._anchorTransform); } else { element._screenToWorld.copy(element._anchorTransform); } @@ -2191,16 +2191,16 @@ class ElementComponent extends Component { const pivotOffset = vecB; pivotOffset.set(element._absLeft + element._pivot.x * element.calculatedWidth, - element._absBottom + element._pivot.y * element.calculatedHeight, 0); + element._absBottom + element._pivot.y * element.calculatedHeight, 0); matA.setTranslate(-pivotOffset.x, -pivotOffset.y, -pivotOffset.z); matB.setTRS(depthOffset, this.getLocalRotation(), this.getLocalScale()); matC.setTranslate(pivotOffset.x, pivotOffset.y, pivotOffset.z); element._screenTransform - .mul2(element._parentWorldTransform, matC) - .mul(matB) - .mul(matA); + .mul2(element._parentWorldTransform, matC) + .mul(matB) + .mul(matA); element._cornersDirty = true; element._canvasCornersDirty = true; @@ -2248,7 +2248,7 @@ class ElementComponent extends Component { if (j < 0) { this.system._prerender.push(current); } - Debug.trace(TRACE_ID_ELEMENT, 'set prerender root to: ' + current.name); + Debug.trace(TRACE_ID_ELEMENT, `set prerender root to: ${current.name}`); } current = next; @@ -2258,7 +2258,7 @@ class ElementComponent extends Component { _onPrerender() { for (let i = 0; i < this.system._prerender.length; i++) { const mask = this.system._prerender[i]; - Debug.trace(TRACE_ID_ELEMENT, 'prerender from: ' + mask.name); + Debug.trace(TRACE_ID_ELEMENT, `prerender from: ${mask.name}`); // prevent call if element has been removed since being added if (mask.element) { @@ -2329,7 +2329,7 @@ class ElementComponent extends Component { if (mask) { const ref = mask.element._image._maskRef; - Debug.trace(TRACE_ID_ELEMENT, 'masking: ' + this.entity.name + ' with ' + ref); + Debug.trace(TRACE_ID_ELEMENT, `masking: ${this.entity.name} with ${ref}`); // if this is image or text, set the stencil parameters renderableElement?._setStencil(new StencilParameters({ @@ -2339,7 +2339,7 @@ class ElementComponent extends Component { this._maskedBy = mask; } else { - Debug.trace(TRACE_ID_ELEMENT, 'no masking on: ' + this.entity.name); + Debug.trace(TRACE_ID_ELEMENT, `no masking on: ${this.entity.name}`); // remove stencil params if this is image or text renderableElement?._setStencil(null); @@ -2368,7 +2368,7 @@ class ElementComponent extends Component { // increment counter to count mask depth depth++; - Debug.trace(TRACE_ID_ELEMENT, 'masking from: ' + this.entity.name + ' with ' + (sp.ref + 1)); + Debug.trace(TRACE_ID_ELEMENT, `masking from: ${this.entity.name} with ${sp.ref + 1}`); Debug.trace(TRACE_ID_ELEMENT, 'depth++ to: ', depth); currentMask = this.entity; @@ -2398,7 +2398,7 @@ class ElementComponent extends Component { // increment mask counter to count depth of masks depth++; - Debug.trace(TRACE_ID_ELEMENT, 'masking from: ' + this.entity.name + ' with ' + sp.ref); + Debug.trace(TRACE_ID_ELEMENT, `masking from: ${this.entity.name} with ${sp.ref}`); Debug.trace(TRACE_ID_ELEMENT, 'depth++ to: ', depth); currentMask = this.entity; @@ -2486,7 +2486,7 @@ class ElementComponent extends Component { } this._localAnchor.set(this._anchor.x * resx, this._anchor.y * resy, this._anchor.z * resx, - this._anchor.w * resy); + this._anchor.w * resy); } // internal - apply offset x,y to local position and find point in world space diff --git a/src/framework/components/element/element-drag-helper.js b/src/framework/components/element/element-drag-helper.js index ec542d980ac..e287802859c 100644 --- a/src/framework/components/element/element-drag-helper.js +++ b/src/framework/components/element/element-drag-helper.js @@ -1,11 +1,11 @@ -import { platform } from '../../../core/platform.js'; +import { ElementComponent } from './component.js'; import { EventHandler } from '../../../core/event-handler.js'; import { Quat } from '../../../core/math/quat.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec3 } from '../../../core/math/vec3.js'; -import { ElementComponent } from './component.js'; -import { Ray } from '../../../core/shape/ray.js'; +import { platform } from '../../../core/platform.js'; import { Plane } from '../../../core/shape/plane.js'; +import { Ray } from '../../../core/shape/ray.js'; /** * @import { ElementMouseEvent, ElementSelectEvent, ElementTouchEvent } from '../../input/element-input.js' @@ -78,7 +78,7 @@ class ElementDragHelper extends EventHandler { } if (axis && axis !== 'x' && axis !== 'y') { - throw new Error('Unrecognized axis: ' + axis); + throw new Error(`Unrecognized axis: ${axis}`); } this._element = element; diff --git a/src/framework/components/element/image-element.js b/src/framework/components/element/image-element.js index ae2d4c0c003..34cdda1fa63 100644 --- a/src/framework/components/element/image-element.js +++ b/src/framework/components/element/image-element.js @@ -1,7 +1,8 @@ -import { Debug } from '../../../core/debug.js'; +import { FITMODE_STRETCH, FITMODE_CONTAIN, FITMODE_COVER } from './constants.js'; import { TRACE_ID_ELEMENT } from '../../../core/constants.js'; -import { math } from '../../../core/math/math.js'; +import { Debug } from '../../../core/debug.js'; import { Color } from '../../../core/math/color.js'; +import { math } from '../../../core/math/math.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { Vec4 } from '../../../core/math/vec4.js'; @@ -12,19 +13,18 @@ import { STENCILOP_DECREMENT, TYPE_FLOAT32 } from '../../../platform/graphics/constants.js'; +import { DeviceCache } from '../../../platform/graphics/device-cache.js'; +import { StencilParameters } from '../../../platform/graphics/stencil-parameters.js'; import { VertexBuffer } from '../../../platform/graphics/vertex-buffer.js'; import { VertexFormat } from '../../../platform/graphics/vertex-format.js'; -import { DeviceCache } from '../../../platform/graphics/device-cache.js'; import { LAYER_HUD, LAYER_WORLD, SPRITE_RENDERMODE_SIMPLE, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED } from '../../../scene/constants.js'; import { GraphNode } from '../../../scene/graph-node.js'; -import { Mesh } from '../../../scene/mesh.js'; import { MeshInstance } from '../../../scene/mesh-instance.js'; +import { Mesh } from '../../../scene/mesh.js'; import { Model } from '../../../scene/model.js'; -import { StencilParameters } from '../../../platform/graphics/stencil-parameters.js'; -import { FITMODE_STRETCH, FITMODE_CONTAIN, FITMODE_COVER } from './constants.js'; import { Asset } from '../../asset/asset.js'; /** @@ -48,7 +48,7 @@ class ImageRenderable { this.mesh = mesh; this.meshInstance = new MeshInstance(this.mesh, material, this.node); - this.meshInstance.name = 'ImageElement: ' + entity.name; + this.meshInstance.name = `ImageElement: ${entity.name}`; this.meshInstance.castShadow = false; this.meshInstance.receiveShadow = false; @@ -93,7 +93,7 @@ class ImageRenderable { if (mask) { this.unmaskMeshInstance = new MeshInstance(this.mesh, this.meshInstance.material, this.node); - this.unmaskMeshInstance.name = 'Unmask: ' + this._entity.name; + this.unmaskMeshInstance.name = `Unmask: ${this._entity.name}`; this.unmaskMeshInstance.castShadow = false; this.unmaskMeshInstance.receiveShadow = false; this.unmaskMeshInstance.pick = false; @@ -194,8 +194,9 @@ class ImageRenderable { } setDrawOrder(drawOrder) { - if (!this.meshInstance) + if (!this.meshInstance) { return; + } Debug.trace(TRACE_ID_ELEMENT, 'setDrawOrder: ', this.meshInstance.name, drawOrder); @@ -495,9 +496,9 @@ class ImageElement { const tex = this.sprite.atlas.texture; this._atlasRect.set(frameData.rect.x / tex.width, - frameData.rect.y / tex.height, - frameData.rect.z / tex.width, - frameData.rect.w / tex.height); + frameData.rect.y / tex.height, + frameData.rect.z / tex.width, + frameData.rect.w / tex.height); // scale: apply PPU const ppu = this._pixelsPerUnit !== null ? this._pixelsPerUnit : this.sprite.pixelsPerUnit; @@ -658,7 +659,7 @@ class ImageElement { } _onMaterialAdded(asset) { - this._system.app.assets.off('add:' + asset.id, this._onMaterialAdded, this); + this._system.app.assets.off(`add:${asset.id}`, this._onMaterialAdded, this); if (this._materialAsset === asset.id) { this._bindMaterialAsset(asset); } @@ -693,7 +694,7 @@ class ImageElement { } _onTextureAdded(asset) { - this._system.app.assets.off('add:' + asset.id, this._onTextureAdded, this); + this._system.app.assets.off(`add:${asset.id}`, this._onTextureAdded, this); if (this._textureAsset === asset.id) { this._bindTextureAsset(asset); } @@ -733,7 +734,7 @@ class ImageElement { // When sprite asset is added bind it _onSpriteAssetAdded(asset) { - this._system.app.assets.off('add:' + asset.id, this._onSpriteAssetAdded, this); + this._system.app.assets.off(`add:${asset.id}`, this._onSpriteAssetAdded, this); if (this._spriteAsset === asset.id) { this._bindSpriteAsset(asset); } @@ -760,7 +761,7 @@ class ImageElement { asset.off('remove', this._onSpriteAssetRemove, this); if (asset.data.textureAtlasAsset) { - this._system.app.assets.off('load:' + asset.data.textureAtlasAsset, this._onTextureAtlasLoad, this); + this._system.app.assets.off(`load:${asset.data.textureAtlasAsset}`, this._onTextureAtlasLoad, this); } } @@ -774,8 +775,8 @@ class ImageElement { const atlasAssetId = asset.data.textureAtlasAsset; if (atlasAssetId) { const assets = this._system.app.assets; - assets.off('load:' + atlasAssetId, this._onTextureAtlasLoad, this); - assets.once('load:' + atlasAssetId, this._onTextureAtlasLoad, this); + assets.off(`load:${atlasAssetId}`, this._onTextureAtlasLoad, this); + assets.once(`load:${atlasAssetId}`, this._onTextureAtlasLoad, this); } } else { this.sprite = asset.resource; @@ -995,7 +996,7 @@ class ImageElement { _removeMaterialAssetEvents() { if (this._materialAsset) { const assets = this._system.app.assets; - assets.off('add:' + this._materialAsset, this._onMaterialAdded, this); + assets.off(`add:${this._materialAsset}`, this._onMaterialAdded, this); const asset = assets.get(this._materialAsset); if (asset) { asset.off('load', this._onMaterialLoad, this); @@ -1066,7 +1067,7 @@ class ImageElement { this.material = null; this._materialAsset = _id; - assets.on('add:' + this._materialAsset, this._onMaterialAdded, this); + assets.on(`add:${this._materialAsset}`, this._onMaterialAdded, this); } else { this._bindMaterialAsset(asset); } @@ -1145,7 +1146,7 @@ class ImageElement { if (this._textureAsset !== _id) { if (this._textureAsset) { - assets.off('add:' + this._textureAsset, this._onTextureAdded, this); + assets.off(`add:${this._textureAsset}`, this._onTextureAdded, this); const _prev = assets.get(this._textureAsset); if (_prev) { _prev.off('load', this._onTextureLoad, this); @@ -1159,7 +1160,7 @@ class ImageElement { const asset = assets.get(this._textureAsset); if (!asset) { this.texture = null; - assets.on('add:' + this._textureAsset, this._onTextureAdded, this); + assets.on(`add:${this._textureAsset}`, this._onTextureAdded, this); } else { this._bindTextureAsset(asset); } @@ -1183,7 +1184,7 @@ class ImageElement { if (this._spriteAsset !== _id) { if (this._spriteAsset) { - assets.off('add:' + this._spriteAsset, this._onSpriteAssetAdded, this); + assets.off(`add:${this._spriteAsset}`, this._onSpriteAssetAdded, this); const _prev = assets.get(this._spriteAsset); if (_prev) { this._unbindSpriteAsset(_prev); @@ -1195,7 +1196,7 @@ class ImageElement { const asset = assets.get(this._spriteAsset); if (!asset) { this.sprite = null; - assets.on('add:' + this._spriteAsset, this._onSpriteAssetAdded, this); + assets.on(`add:${this._spriteAsset}`, this._onSpriteAssetAdded, this); } else { this._bindSpriteAsset(asset); } diff --git a/src/framework/components/element/markup.js b/src/framework/components/element/markup.js index 3fa4d1a5204..1fe9eb77338 100644 --- a/src/framework/components/element/markup.js +++ b/src/framework/components/element/markup.js @@ -11,7 +11,7 @@ const STRING_TOKEN = 6; const IDENTIFIER_TOKEN = 7; const WHITESPACE_TOKEN = 8; const WHITESPACE_CHARS = ' \t\n\r\v\f'; -const IDENTIFIER_REGEX = /[A-Z|a-z|0-9|_|-|/]/; +const IDENTIFIER_REGEX = /[\w|/]/; class Scanner { constructor(symbols) { @@ -57,9 +57,9 @@ class Scanner { let token = this.read(); let result = ''; while (true) { - result += (result.length > 0 ? '\n' : '') + - tokenStrings[token] + - ' \'' + this.buf().join('') + '\''; + result += `${(result.length > 0 ? '\n' : '') + + tokenStrings[token] + } '${this.buf().join('')}'`; if (token === EOF_TOKEN || token === ERROR_TOKEN) { break; } @@ -247,8 +247,8 @@ class Parser { // access an error message if the parser failed error() { - return 'Error evaluating markup at #' + this._scanner.last().toString() + - ' (' + (this._scanner.error() || this._error) + ')'; + return `Error evaluating markup at #${this._scanner.last().toString() + } (${this._scanner.error() || this._error})`; } _parseTag(symbols, tags) { @@ -264,7 +264,7 @@ class Parser { // handle close tags if (name[0] === '/') { for (let index = tags.length - 1; index >= 0; --index) { - if (name === '/' + tags[index].name && tags[index].end === null) { + if (name === `/${tags[index].name}` && tags[index].end === null) { tags[index].end = symbols.length; token = this._scanner.read(); if (token !== CLOSE_BRACKET_TOKEN) { @@ -405,8 +405,8 @@ function resolveMarkupTags(tags, numSymbols) { let tagStack = []; function removeTags(tags) { - tagStack = tagStack.filter(function (tag) { - return tags.find(function (t) { + tagStack = tagStack.filter((tag) => { + return tags.find((t) => { return t === tag; }) === undefined; }); @@ -418,7 +418,7 @@ function resolveMarkupTags(tags, numSymbols) { } } - const edgeKeys = Object.keys(edges).sort(function (a, b) { + const edgeKeys = Object.keys(edges).sort((a, b) => { return a - b; }); @@ -479,7 +479,7 @@ function evaluateMarkup(symbols) { } // if any tags were not correctly closed, return failure - const invalidTag = tags.find(function (t) { + const invalidTag = tags.find((t) => { return t.end === null; }); diff --git a/src/framework/components/element/system.js b/src/framework/components/element/system.js index a031d8d45d6..d9e092f724a 100644 --- a/src/framework/components/element/system.js +++ b/src/framework/components/element/system.js @@ -1,3 +1,6 @@ +import { ElementComponent } from './component.js'; +import { ELEMENTTYPE_IMAGE, ELEMENTTYPE_TEXT } from './constants.js'; +import { ElementComponentData } from './data.js'; import { Color } from '../../../core/math/color.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec4 } from '../../../core/math/vec4.js'; @@ -6,9 +9,6 @@ import { Texture } from '../../../platform/graphics/texture.js'; import { BLEND_PREMULTIPLIED, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED } from '../../../scene/constants.js'; import { StandardMaterial } from '../../../scene/materials/standard-material.js'; import { ComponentSystem } from '../system.js'; -import { ELEMENTTYPE_IMAGE, ELEMENTTYPE_TEXT } from './constants.js'; -import { ElementComponent } from './component.js'; -import { ElementComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -341,7 +341,7 @@ class ElementComponentSystem extends ComponentSystem { return material; } - let name = "TextMaterial"; + let name = 'TextMaterial'; material = new StandardMaterial(); @@ -350,7 +350,7 @@ class ElementComponentSystem extends ComponentSystem { material.msdfTextAttribute = textAttibutes; material.emissive.set(1, 1, 1); } else { - name = "Bitmap" + name; + name = `Bitmap${name}`; material.emissive.set(1, 1, 1); material.emissiveMap = this._defaultTexture; material.opacityMap = this._defaultTexture; @@ -358,7 +358,7 @@ class ElementComponentSystem extends ComponentSystem { } if (screenSpace) { - name = 'ScreenSpace' + name; + name = `ScreenSpace${name}`; material.depthTest = false; } @@ -367,7 +367,7 @@ class ElementComponentSystem extends ComponentSystem { // defaultBitmapTextMaterial // defaultScreenSpaceTextMaterial // defaultScreenSpaceBitmapTextMaterial - material.name = 'default' + name; + material.name = `default${name}`; material.useLighting = false; material.useTonemap = false; material.useFog = false; diff --git a/src/framework/components/element/text-element.js b/src/framework/components/element/text-element.js index 04eb662c086..540c8dc1570 100644 --- a/src/framework/components/element/text-element.js +++ b/src/framework/components/element/text-element.js @@ -1,18 +1,18 @@ +import { Markup } from './markup.js'; import { Debug } from '../../../core/debug.js'; -import { string } from '../../../core/string.js'; -import { math } from '../../../core/math/math.js'; import { Color } from '../../../core/math/color.js'; +import { math } from '../../../core/math/math.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { BoundingBox } from '../../../core/shape/bounding-box.js'; +import { string } from '../../../core/string.js'; import { SEMANTIC_POSITION, SEMANTIC_TEXCOORD0, SEMANTIC_COLOR, SEMANTIC_ATTR8, SEMANTIC_ATTR9, TYPE_FLOAT32 } from '../../../platform/graphics/constants.js'; import { VertexIterator } from '../../../platform/graphics/vertex-iterator.js'; import { GraphNode } from '../../../scene/graph-node.js'; import { MeshInstance } from '../../../scene/mesh-instance.js'; -import { Model } from '../../../scene/model.js'; import { Mesh } from '../../../scene/mesh.js'; +import { Model } from '../../../scene/model.js'; import { LocalizedAsset } from '../../asset/asset-localized.js'; import { FONT_BITMAP, FONT_MSDF } from '../../font/constants.js'; -import { Markup } from './markup.js'; /** * @import { CanvasFont } from '../../../framework/font/canvas-font.js' @@ -71,7 +71,7 @@ function createTextMesh(device, meshInfo) { const LINE_BREAK_CHAR = /^[\r\n]$/; const WHITESPACE_CHAR = /^[ \t]$/; -const WORD_BOUNDARY_CHAR = /^[ \t\-]|[\u200b]$/; // NB \u200b is zero width space +const WORD_BOUNDARY_CHAR = /^[ \t\-]|\u200b$/; // NB \u200b is zero width space const ALPHANUMERIC_CHAR = /^[a-z0-9]$/i; // 1100—11FF Hangul Jamo @@ -81,7 +81,7 @@ const ALPHANUMERIC_CHAR = /^[a-z0-9]$/i; // A960—A97F Hangul Jamo Extended-A // AC00—D7AF Hangul Syllables // D7B0—D7FF Hangul Jamo Extended-B -const CJK_CHAR = /^[\u1100-\u11ff]|[\u3000-\u9fff]|[\ua960-\ua97f]|[\uac00-\ud7ff]$/; +const CJK_CHAR = /^[\u1100-\u11ff]|[\u3000-\u9fff\ua960-\ua97f]|[\uac00-\ud7ff]$/; const NO_LINE_BREAK_CJK_CHAR = /^[〕〉》」』】〙〗〟ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻]$/; // unicode bidi control characters https://en.wikipedia.org/wiki/Unicode_control_characters @@ -273,8 +273,9 @@ class TextElement { } _onPivotChange(pivot) { - if (this._font) + if (this._font) { this._updateText(); + } } _onLocaleSet(locale) { @@ -365,7 +366,7 @@ class TextElement { // reorder tags if they exist, according to unicode reorder mapping if (tags) { - tags = results.mapping.map(function (v) { + tags = results.mapping.map((v) => { return tags[v]; }); } @@ -424,10 +425,10 @@ class TextElement { paletteMap[this._color.toString(false).toLowerCase()] = 0; outlinePaletteMap[ - getColorThicknessHash(this._outlineColor, this._outlineThickness) + getColorThicknessHash(this._outlineColor, this._outlineThickness) ] = 0; shadowPaletteMap[ - getColorOffsetHash(this._shadowColor, this._shadowOffset) + getColorOffsetHash(this._shadowColor, this._shadowOffset) ] = 0; for (let i = 0, len = this._symbols.length; i < len; ++i) { @@ -452,7 +453,7 @@ class TextElement { // color is already in the palette color = paletteMap[hex]; } else { - if (/^([0-9a-f]{2}){3}$/.test(hex)) { + if (/^[0-9a-f]{6}$/.test(hex)) { // new color color = this._colorPalette.length / 3; paletteMap[hex] = color; @@ -659,7 +660,7 @@ class TextElement { const mesh = createTextMesh(this._system.app.graphicsDevice, meshInfo); const mi = new MeshInstance(mesh, this._material, this._node); - mi.name = 'Text Element: ' + this._entity.name; + mi.name = `Text Element: ${this._entity.name}`; mi.castShadow = false; mi.receiveShadow = false; mi.cull = !screenSpace; @@ -722,8 +723,9 @@ class TextElement { meshInstance.destroy(); const idx = this._model.meshInstances.indexOf(meshInstance); - if (idx !== -1) + if (idx !== -1) { this._model.meshInstances.splice(idx, 1); + } } _setMaterial(material) { @@ -1352,15 +1354,15 @@ class TextElement { it.element[SEMANTIC_POSITION].set(this._meshInfo[i].positions[v * 3 + 0], this._meshInfo[i].positions[v * 3 + 1], this._meshInfo[i].positions[v * 3 + 2]); it.element[SEMANTIC_TEXCOORD0].set(this._meshInfo[i].uvs[v * 2 + 0], this._meshInfo[i].uvs[v * 2 + 1]); it.element[SEMANTIC_COLOR].set(this._meshInfo[i].colors[v * 4 + 0], - this._meshInfo[i].colors[v * 4 + 1], - this._meshInfo[i].colors[v * 4 + 2], - this._meshInfo[i].colors[v * 4 + 3]); + this._meshInfo[i].colors[v * 4 + 1], + this._meshInfo[i].colors[v * 4 + 2], + this._meshInfo[i].colors[v * 4 + 3]); it.element[SEMANTIC_ATTR8].set(this._meshInfo[i].outlines[v * 3 + 0], - this._meshInfo[i].outlines[v * 3 + 1], - this._meshInfo[i].outlines[v * 3 + 2]); + this._meshInfo[i].outlines[v * 3 + 1], + this._meshInfo[i].outlines[v * 3 + 2]); it.element[SEMANTIC_ATTR9].set(this._meshInfo[i].shadows[v * 3 + 0], - this._meshInfo[i].shadows[v * 3 + 1], - this._meshInfo[i].shadows[v * 3 + 2]); + this._meshInfo[i].shadows[v * 3 + 1], + this._meshInfo[i].shadows[v * 3 + 2]); } it.next(); } @@ -1805,8 +1807,9 @@ class TextElement { } } - if (this._meshInfo.length > this._font.textures.length) + if (this._meshInfo.length > this._font.textures.length) { this._meshInfo.length = this._font.textures.length; + } this._updateText(); } @@ -1822,8 +1825,9 @@ class TextElement { this._alignment.set(value[0], value[1]); } - if (this._font) + if (this._font) { this._updateText(); + } } get alignment() { diff --git a/src/framework/components/gsplat/component.js b/src/framework/components/gsplat/component.js index f9cb66e62f8..fd71836c1c2 100644 --- a/src/framework/components/gsplat/component.js +++ b/src/framework/components/gsplat/component.js @@ -1,6 +1,6 @@ import { LAYERID_WORLD } from '../../../scene/constants.js'; -import { Asset } from '../../asset/asset.js'; import { AssetReference } from '../../asset/asset-reference.js'; +import { Asset } from '../../asset/asset.js'; import { Component } from '../component.js'; /** @@ -187,8 +187,9 @@ class GSplatComponent extends Component { } // don't add into layers until we're enabled - if (!this.enabled || !this.entity.enabled) + if (!this.enabled || !this.entity.enabled) { return; + } // add the mesh instance to new layers this.addToLayers(); @@ -366,8 +367,9 @@ class GSplatComponent extends Component { } _onGSplatAssetAdded() { - if (!this._assetReference.asset) + if (!this._assetReference.asset) { return; + } if (this._assetReference.asset.resource) { this._onGSplatAssetLoad(); diff --git a/src/framework/components/gsplat/system.js b/src/framework/components/gsplat/system.js index 747beef34b1..747addaa377 100644 --- a/src/framework/components/gsplat/system.js +++ b/src/framework/components/gsplat/system.js @@ -1,9 +1,9 @@ +import { GSplatComponent } from './component.js'; +import { GSplatComponentData } from './data.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { BoundingBox } from '../../../core/shape/bounding-box.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { GSplatComponent } from './component.js'; -import { GSplatComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/joint/component.js b/src/framework/components/joint/component.js index 0b4307840ce..6bf2a439db7 100644 --- a/src/framework/components/joint/component.js +++ b/src/framework/components/joint/component.js @@ -1,10 +1,10 @@ +import { MOTION_FREE, MOTION_LIMITED, MOTION_LOCKED } from './constants.js'; import { Debug } from '../../../core/debug.js'; -import { math } from '../../../core/math/math.js'; import { Mat4 } from '../../../core/math/mat4.js'; +import { math } from '../../../core/math/math.js'; import { Quat } from '../../../core/math/quat.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Component } from '../component.js'; -import { MOTION_FREE, MOTION_LIMITED, MOTION_LOCKED } from './constants.js'; /** * @import { Entity } from '../../entity.js' @@ -418,10 +418,10 @@ class JointComponent extends Component { for (let i = 0; i < 6; i++) { const type = i < 3 ? '_linear' : '_angular'; - this._constraint.enableSpring(i, this[type + 'Spring' + axis[i]]); - this._constraint.setDamping(i, this[type + 'Damping' + axis[i]]); - this._constraint.setEquilibriumPoint(i, this[type + 'Equilibrium' + axis[i]]); - this._constraint.setStiffness(i, this[type + 'Stiffness' + axis[i]]); + this._constraint.enableSpring(i, this[`${type}Spring${axis[i]}`]); + this._constraint.setDamping(i, this[`${type}Damping${axis[i]}`]); + this._constraint.setEquilibriumPoint(i, this[`${type}Equilibrium${axis[i]}`]); + this._constraint.setStiffness(i, this[`${type}Stiffness${axis[i]}`]); } this._constraint.setBreakingImpulseThreshold(this._breakForce); @@ -450,9 +450,9 @@ class JointComponent extends Component { for (const prop of properties) { if (data.hasOwnProperty(prop)) { if (data[prop] instanceof Vec2) { - this['_' + prop].copy(data[prop]); + this[`_${prop}`].copy(data[prop]); } else { - this['_' + prop] = data[prop]; + this[`_${prop}`] = data[prop]; } } } @@ -488,7 +488,7 @@ const functionMap = { ['Damping', 'Equilibrium', 'Spring', 'Stiffness'].forEach((name) => { ['X', 'Y', 'Z'].forEach((axis) => { const prop = type + name + axis; - const propInternal = '_' + prop; + const propInternal = `_${prop}`; let index = (type === 'linear') ? 0 : 3; if (axis === 'Y') index += 1; diff --git a/src/framework/components/joint/system.js b/src/framework/components/joint/system.js index 5e8f0e7850e..2c2e30ee7ee 100644 --- a/src/framework/components/joint/system.js +++ b/src/framework/components/joint/system.js @@ -1,7 +1,7 @@ -import { Component } from '../component.js'; -import { ComponentSystem } from '../system.js'; import { JointComponent } from './component.js'; import { JointComponentData } from './data.js'; +import { Component } from '../component.js'; +import { ComponentSystem } from '../system.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/layout-child/system.js b/src/framework/components/layout-child/system.js index 48ee36fa270..84bd905b3df 100644 --- a/src/framework/components/layout-child/system.js +++ b/src/framework/components/layout-child/system.js @@ -1,7 +1,7 @@ -import { Component } from '../component.js'; -import { ComponentSystem } from '../system.js'; import { LayoutChildComponent } from './component.js'; import { LayoutChildComponentData } from './data.js'; +import { Component } from '../component.js'; +import { ComponentSystem } from '../system.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/layout-group/component.js b/src/framework/components/layout-group/component.js index 599c4123a0e..0b795dd07c1 100644 --- a/src/framework/components/layout-group/component.js +++ b/src/framework/components/layout-group/component.js @@ -1,10 +1,10 @@ +import { FITTING_NONE } from './constants.js'; +import { LayoutCalculator } from './layout-calculator.js'; import { Debug } from '../../../core/debug.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec4 } from '../../../core/math/vec4.js'; import { ORIENTATION_HORIZONTAL } from '../../../scene/constants.js'; -import { FITTING_NONE } from './constants.js'; import { Component } from '../component.js'; -import { LayoutCalculator } from './layout-calculator.js'; /** * @import { Entity } from '../../entity.js' @@ -71,11 +71,11 @@ class LayoutGroupComponent extends Component { // Listen for ElementComponents and LayoutChildComponents being added // to self or to children - covers cases where they are not already // present at the point when this component is constructed. - Debug.assert(system.app.systems.element, `System 'element' doesn't exist`); + Debug.assert(system.app.systems.element, 'System \'element\' doesn\'t exist'); system.app.systems.element.on('add', this._onElementOrLayoutComponentAdd, this); system.app.systems.element.on('beforeremove', this._onElementOrLayoutComponentRemove, this); - Debug.assert(system.app.systems.layoutchild, `System 'layoutchild' doesn't exist`); + Debug.assert(system.app.systems.layoutchild, 'System \'layoutchild\' doesn\'t exist'); system.app.systems.layoutchild.on('add', this._onElementOrLayoutComponentAdd, this); system.app.systems.layoutchild.on('beforeremove', this._onElementOrLayoutComponentRemove, this); } diff --git a/src/framework/components/layout-group/layout-calculator.js b/src/framework/components/layout-group/layout-calculator.js index 0019af38133..c60ed9b0da0 100644 --- a/src/framework/components/layout-group/layout-calculator.js +++ b/src/framework/components/layout-group/layout-calculator.js @@ -1,9 +1,8 @@ +import { FITTING_BOTH, FITTING_NONE, FITTING_SHRINK, FITTING_STRETCH } from './constants.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec4 } from '../../../core/math/vec4.js'; - import { ORIENTATION_HORIZONTAL, ORIENTATION_VERTICAL } from '../../../scene/constants.js'; -import { FITTING_BOTH, FITTING_NONE, FITTING_SHRINK, FITTING_STRETCH } from './constants.js'; const AXIS_MAPPINGS = {}; @@ -563,7 +562,7 @@ function createCalculator(orientation) { } function sumValues(items, propertyName) { - return items.reduce(function (accumulator, current) { + return items.reduce((accumulator, current) => { return accumulator + current[propertyName]; }, 0); } @@ -606,11 +605,11 @@ function createCalculator(orientation) { items.forEach(assignIndex); return items - .slice() - .sort(function (itemA, itemB) { - return descending ? itemB[orderBy] - itemA[orderBy] : itemA[orderBy] - itemB[orderBy]; - }) - .map(getIndex); + .slice() + .sort((itemA, itemB) => { + return descending ? itemB[orderBy] - itemA[orderBy] : itemA[orderBy] - itemB[orderBy]; + }) + .map(getIndex); } function assignIndex(item, index) { @@ -653,7 +652,7 @@ class LayoutCalculator { const calculateFn = CALCULATE_FNS[options.orientation]; if (!calculateFn) { - throw new Error('Unrecognized orientation value: ' + options.orientation); + throw new Error(`Unrecognized orientation value: ${options.orientation}`); } else { return calculateFn(elements, options); } diff --git a/src/framework/components/layout-group/system.js b/src/framework/components/layout-group/system.js index 1ae29509a6f..55e2e294782 100644 --- a/src/framework/components/layout-group/system.js +++ b/src/framework/components/layout-group/system.js @@ -1,9 +1,9 @@ +import { LayoutGroupComponent } from './component.js'; +import { LayoutGroupComponentData } from './data.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec4 } from '../../../core/math/vec4.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { LayoutGroupComponent } from './component.js'; -import { LayoutGroupComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -108,7 +108,7 @@ class LayoutGroupComponentSystem extends ComponentSystem { // Sort in ascending order of depth within the graph (i.e. outermost first), so that // any layout groups which are children of other layout groups will always have their // new size set before their own reflow is calculated. - queue.sort(function (componentA, componentB) { + queue.sort((componentA, componentB) => { return (componentA.entity.graphDepth - componentB.entity.graphDepth); }); diff --git a/src/framework/components/light/component.js b/src/framework/components/light/component.js index 63d9264dab5..5c169718be6 100644 --- a/src/framework/components/light/component.js +++ b/src/framework/components/light/component.js @@ -1,9 +1,9 @@ +import { properties } from './data.js'; import { math } from '../../../core/math/math.js'; import { Vec4 } from '../../../core/math/vec4.js'; import { MASK_AFFECT_LIGHTMAPPED, MASK_AFFECT_DYNAMIC, MASK_BAKE } from '../../../scene/constants.js'; import { Asset } from '../../asset/asset.js'; import { Component } from '../component.js'; -import { properties } from './data.js'; /** * @import { Color } from '../../../core/math/color.js' @@ -650,8 +650,9 @@ class LightComponent extends Component { if ( this._cookieAssetId && ((newValue instanceof Asset && newValue.id === this._cookieAssetId) || newValue === this._cookieAssetId) - ) + ) { return; + } this.onCookieAssetRemove(); this._cookieAssetId = null; if (newValue instanceof Asset) { @@ -665,7 +666,7 @@ class LightComponent extends Component { this.onCookieAssetAdd(asset); } else { this._cookieAssetAdd = true; - this.system.app.assets.on('add:' + this._cookieAssetId, this.onCookieAssetAdd, this); + this.system.app.assets.on(`add:${this._cookieAssetId}`, this.onCookieAssetAdd, this); } } }); @@ -1212,7 +1213,7 @@ class LightComponent extends Component { } if (this._cookieAssetAdd) { - this.system.app.assets.off('add:' + this._cookieAssetId, this.onCookieAssetAdd, this); + this.system.app.assets.off(`add:${this._cookieAssetId}`, this.onCookieAssetAdd, this); this._cookieAssetAdd = false; } diff --git a/src/framework/components/light/system.js b/src/framework/components/light/system.js index c04f8c7d916..b52516dbaf9 100644 --- a/src/framework/components/light/system.js +++ b/src/framework/components/light/system.js @@ -1,10 +1,10 @@ +import { LightComponent } from './component.js'; +import { properties, LightComponentData } from './data.js'; import { Color } from '../../../core/math/color.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { LIGHTSHAPE_PUNCTUAL } from '../../../scene/constants.js'; import { Light, lightTypes } from '../../../scene/light.js'; import { ComponentSystem } from '../system.js'; -import { LightComponent } from './component.js'; -import { properties, LightComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -36,8 +36,9 @@ class LightComponentSystem extends ComponentSystem { initializeComponentData(component, _data) { // duplicate because we're modifying the data const data = { ..._data }; - if (!data.type) + if (!data.type) { data.type = component.data.type; + } component.data.type = data.type; @@ -45,14 +46,17 @@ class LightComponentSystem extends ComponentSystem { data.layers = data.layers.slice(0); } - if (data.color && Array.isArray(data.color)) + if (data.color && Array.isArray(data.color)) { data.color = new Color(data.color[0], data.color[1], data.color[2]); + } - if (data.cookieOffset && data.cookieOffset instanceof Array) + if (data.cookieOffset && data.cookieOffset instanceof Array) { data.cookieOffset = new Vec2(data.cookieOffset[0], data.cookieOffset[1]); + } - if (data.cookieScale && data.cookieScale instanceof Array) + if (data.cookieScale && data.cookieScale instanceof Array) { data.cookieScale = new Vec2(data.cookieScale[0], data.cookieScale[1]); + } if (data.enable) { console.warn('WARNING: enable: Property is deprecated. Set enabled property instead.'); diff --git a/src/framework/components/model/component.js b/src/framework/components/model/component.js index 4c25e56d176..ac5ded4e1e4 100644 --- a/src/framework/components/model/component.js +++ b/src/framework/components/model/component.js @@ -1,11 +1,11 @@ import { Debug } from '../../../core/debug.js'; -import { LAYERID_WORLD } from '../../../scene/constants.js'; import { BatchGroup } from '../../../scene/batching/batch-group.js'; +import { LAYERID_WORLD } from '../../../scene/constants.js'; import { GraphNode } from '../../../scene/graph-node.js'; import { MeshInstance } from '../../../scene/mesh-instance.js'; import { Model } from '../../../scene/model.js'; -import { getShapePrimitive } from '../../graphics/primitive-cache.js'; import { Asset } from '../../asset/asset.js'; +import { getShapePrimitive } from '../../graphics/primitive-cache.js'; import { Component } from '../component.js'; /** @@ -153,8 +153,9 @@ class ModelComponent extends Component { * @type {MeshInstance[]|null} */ set meshInstances(value) { - if (!this._model) + if (!this._model) { return; + } this._model.meshInstances = value; } @@ -165,8 +166,9 @@ class ModelComponent extends Component { * @type {MeshInstance[]|null} */ get meshInstances() { - if (!this._model) + if (!this._model) { return null; + } return this._model.meshInstances; } @@ -274,7 +276,7 @@ class ModelComponent extends Component { if (this._asset !== _id) { if (this._asset) { // remove previous asset - assets.off('add:' + this._asset, this._onModelAssetAdded, this); + assets.off(`add:${this._asset}`, this._onModelAssetAdded, this); const _prev = assets.get(this._asset); if (_prev) { this._unbindModelAsset(_prev); @@ -287,7 +289,7 @@ class ModelComponent extends Component { const asset = assets.get(this._asset); if (!asset) { this.model = null; - assets.on('add:' + this._asset, this._onModelAssetAdded, this); + assets.on(`add:${this._asset}`, this._onModelAssetAdded, this); } else { this._bindModelAsset(asset); } @@ -312,8 +314,9 @@ class ModelComponent extends Component { * @type {Model} */ set model(value) { - if (this._model === value) + if (this._model === value) { return; + } // return if the model has been flagged as immutable if (value && value._immutable) { @@ -360,8 +363,9 @@ class ModelComponent extends Component { this._model._entity = this.entity; // Update any animation component - if (this.entity.animation) + if (this.entity.animation) { this.entity.animation.setModel(this._model); + } // Update any anim component if (this.entity.anim) { @@ -619,7 +623,7 @@ class ModelComponent extends Component { if (_id !== this._materialAsset) { if (this._materialAsset) { - assets.off('add:' + this._materialAsset, this._onMaterialAssetAdd, this); + assets.off(`add:${this._materialAsset}`, this._onMaterialAssetAdd, this); const _prev = assets.get(this._materialAsset); if (_prev) { this._unbindMaterialAsset(_prev); @@ -632,7 +636,7 @@ class ModelComponent extends Component { const asset = assets.get(this._materialAsset); if (!asset) { this._setMaterial(this.system.defaultMaterial); - assets.on('add:' + this._materialAsset, this._onMaterialAssetAdd, this); + assets.on(`add:${this._materialAsset}`, this._onMaterialAssetAdd, this); } else { this._bindMaterialAsset(asset); } @@ -658,8 +662,9 @@ class ModelComponent extends Component { * @type {Material} */ set material(value) { - if (this._material === value) + if (this._material === value) { return; + } this.materialAsset = null; @@ -683,15 +688,17 @@ class ModelComponent extends Component { * @type {Object} */ set mapping(value) { - if (this._type !== 'asset') + if (this._type !== 'asset') { return; + } // unsubscribe from old events this._unsetMaterialEvents(); // can't have a null mapping - if (!value) + if (!value) { value = {}; + } this._mapping = value; @@ -757,13 +764,15 @@ class ModelComponent extends Component { } onRemoveChild() { - if (this._model) + if (this._model) { this.removeModelFromLayers(); + } } onInsertChild() { - if (this._model && this.enabled && this.entity.enabled) + if (this._model && this.enabled && this.entity.enabled) { this.addModelToLayers(); + } } onRemove() { @@ -817,14 +826,16 @@ class ModelComponent extends Component { * @private */ _setMaterialEvent(index, event, id, handler) { - const evt = event + ':' + id; + const evt = `${event}:${id}`; this.system.app.assets.on(evt, handler, this); - if (!this._materialEvents) + if (!this._materialEvents) { this._materialEvents = []; + } - if (!this._materialEvents[index]) + if (!this._materialEvents[index]) { this._materialEvents[index] = { }; + } this._materialEvents[index][evt] = { id: id, @@ -836,8 +847,9 @@ class ModelComponent extends Component { _unsetMaterialEvents() { const assets = this.system.app.assets; const events = this._materialEvents; - if (!events) + if (!events) { return; + } for (let i = 0, len = events.length; i < len; i++) { if (!events[i]) continue; @@ -864,8 +876,9 @@ class ModelComponent extends Component { asset = this.system.app.assets.get(idOrPath); } else if (this.asset) { const url = this._getMaterialAssetUrl(idOrPath); - if (url) + if (url) { asset = this.system.app.assets.getByUrl(url); + } } return asset; @@ -893,8 +906,9 @@ class ModelComponent extends Component { _loadAndSetMeshInstanceMaterial(materialAsset, meshInstance, index) { const assets = this.system.app.assets; - if (!materialAsset) + if (!materialAsset) { return; + } if (materialAsset.resource) { meshInstance.material = materialAsset.resource; @@ -911,8 +925,9 @@ class ModelComponent extends Component { }); }); - if (this.enabled && this.entity.enabled) + if (this.enabled && this.entity.enabled) { assets.load(materialAsset); + } } } @@ -1066,7 +1081,7 @@ class ModelComponent extends Component { * @private */ _onMaterialAssetAdd(asset) { - this.system.app.assets.off('add:' + asset.id, this._onMaterialAssetAdd, this); + this.system.app.assets.off(`add:${asset.id}`, this._onMaterialAssetAdd, this); if (this._materialAsset === asset.id) { this._bindMaterialAsset(asset); } @@ -1141,7 +1156,7 @@ class ModelComponent extends Component { * @private */ _onModelAssetAdded(asset) { - this.system.app.assets.off('add:' + asset.id, this._onModelAssetAdded, this); + this.system.app.assets.off(`add:${asset.id}`, this._onModelAssetAdded, this); if (asset.id === this._asset) { this._bindModelAsset(asset); } @@ -1190,8 +1205,9 @@ class ModelComponent extends Component { * @private */ _setMaterial(material) { - if (this._material === material) + if (this._material === material) { return; + } this._material = material; diff --git a/src/framework/components/model/system.js b/src/framework/components/model/system.js index 419170b10dd..fc332ab0b4e 100644 --- a/src/framework/components/model/system.js +++ b/src/framework/components/model/system.js @@ -1,3 +1,5 @@ +import { ModelComponent } from './component.js'; +import { ModelComponentData } from './data.js'; import { extend } from '../../../core/core.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { BoundingBox } from '../../../core/shape/bounding-box.js'; @@ -5,8 +7,6 @@ import { getDefaultMaterial } from '../../../scene/materials/default-material.js import { Asset } from '../../asset/asset.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { ModelComponent } from './component.js'; -import { ModelComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -123,8 +123,9 @@ class ModelComponentSystem extends ComponentSystem { component._clonedModel = true; } - if (!data.materialAsset) + if (!data.materialAsset) { component.material = material; + } // TODO: we should copy all relevant mesh instance properties here if (entity.model.model) { diff --git a/src/framework/components/particle-system/component.js b/src/framework/components/particle-system/component.js index 99037d0cccc..ebfef4a01d6 100644 --- a/src/framework/components/particle-system/component.js +++ b/src/framework/components/particle-system/component.js @@ -1515,7 +1515,7 @@ class ParticleSystemComponent extends Component { if (asset) { this._bindColorMapAsset(asset); } else { - assets.once('add:' + newValue, (asset) => { + assets.once(`add:${newValue}`, (asset) => { this._bindColorMapAsset(asset); }); } @@ -1580,7 +1580,7 @@ class ParticleSystemComponent extends Component { if (asset) { this._bindNormalMapAsset(asset); } else { - assets.once('add:' + newValue, (asset) => { + assets.once(`add:${newValue}`, (asset) => { this._bindNormalMapAsset(asset); }); } diff --git a/src/framework/components/particle-system/data.js b/src/framework/components/particle-system/data.js index e495f79239c..5f253871f33 100644 --- a/src/framework/components/particle-system/data.js +++ b/src/framework/components/particle-system/data.js @@ -54,7 +54,7 @@ class ParticleSystemComponentData { this.meshAsset = null; /** @type {Mesh} */ this.mesh = null; // Mesh to be used as particle. Vertex buffer is supposed to hold vertex position in first 3 floats of each vertex - // Leave undefined to use simple quads + // Leave undefined to use simple quads this.depthWrite = false; this.noFog = false; diff --git a/src/framework/components/particle-system/system.js b/src/framework/components/particle-system/system.js index 1a819785be1..c730667a31f 100644 --- a/src/framework/components/particle-system/system.js +++ b/src/framework/components/particle-system/system.js @@ -1,10 +1,10 @@ -import { Curve } from '../../../core/math/curve.js'; +import { ParticleSystemComponent } from './component.js'; +import { ParticleSystemComponentData } from './data.js'; import { CurveSet } from '../../../core/math/curve-set.js'; +import { Curve } from '../../../core/math/curve.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { Asset } from '../../asset/asset.js'; import { ComponentSystem } from '../system.js'; -import { ParticleSystemComponent } from './component.js'; -import { ParticleSystemComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -224,8 +224,9 @@ class ParticleSystemComponentSystem extends ComponentSystem { const layers = data.layers; for (let i = 0; i < layers.length; i++) { const layer = composition.getLayerById(layers[i]); - if (layer) + if (layer) { layer.requiresLightCube = true; + } } } diff --git a/src/framework/components/registry.js b/src/framework/components/registry.js index e3c6a0f0b19..dabef21e870 100644 --- a/src/framework/components/registry.js +++ b/src/framework/components/registry.js @@ -207,9 +207,9 @@ class ComponentSystemRegistry extends EventHandler { */ zone; - /** - * Create a new ComponentSystemRegistry instance. - */ + /** + * Create a new ComponentSystemRegistry instance. + */ constructor() { super(); diff --git a/src/framework/components/render/component.js b/src/framework/components/render/component.js index f4eaf3a60f6..556647d680d 100644 --- a/src/framework/components/render/component.js +++ b/src/framework/components/render/component.js @@ -1,15 +1,15 @@ import { Debug } from '../../../core/debug.js'; -import { LAYERID_WORLD, RENDERSTYLE_SOLID } from '../../../scene/constants.js'; import { BatchGroup } from '../../../scene/batching/batch-group.js'; +import { LAYERID_WORLD, RENDERSTYLE_SOLID } from '../../../scene/constants.js'; +import { GraphNode } from '../../../scene/graph-node.js'; import { MeshInstance } from '../../../scene/mesh-instance.js'; import { MorphInstance } from '../../../scene/morph-instance.js'; -import { getShapePrimitive } from '../../graphics/primitive-cache.js'; -import { GraphNode } from '../../../scene/graph-node.js'; import { SkinInstanceCache } from '../../../scene/skin-instance-cache.js'; -import { Asset } from '../../asset/asset.js'; import { AssetReference } from '../../asset/asset-reference.js'; -import { Component } from '../component.js'; +import { Asset } from '../../asset/asset.js'; +import { getShapePrimitive } from '../../graphics/primitive-cache.js'; import { EntityReference } from '../../utils/entity-reference.js'; +import { Component } from '../component.js'; /** * @import { BoundingBox } from '../../../core/shape/bounding-box.js' @@ -291,7 +291,7 @@ class RenderComponent extends Component { */ set meshInstances(value) { - Debug.assert(Array.isArray(value), `MeshInstances set to a Render component must be an array.`); + Debug.assert(Array.isArray(value), 'MeshInstances set to a Render component must be an array.'); this.destroyMeshInstances(); this._meshInstances = value; @@ -633,7 +633,7 @@ class RenderComponent extends Component { * @type {Asset[]|number[]} */ get materialAssets() { - return this._materialReferences.map(function (ref) { + return this._materialReferences.map((ref) => { return ref.id; }); } diff --git a/src/framework/components/render/system.js b/src/framework/components/render/system.js index 9de0522aa80..34fcb2915a3 100644 --- a/src/framework/components/render/system.js +++ b/src/framework/components/render/system.js @@ -1,10 +1,10 @@ +import { RenderComponent } from './component.js'; +import { RenderComponentData } from './data.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { BoundingBox } from '../../../core/shape/bounding-box.js'; import { getDefaultMaterial } from '../../../scene/materials/default-material.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { RenderComponent } from './component.js'; -import { RenderComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/rigid-body/component.js b/src/framework/components/rigid-body/component.js index 65994a406ce..7cabc47370b 100644 --- a/src/framework/components/rigid-body/component.js +++ b/src/framework/components/rigid-body/component.js @@ -1,6 +1,3 @@ -import { Quat } from '../../../core/math/quat.js'; -import { Vec3 } from '../../../core/math/vec3.js'; -import { Component } from '../component.js'; import { BODYFLAG_KINEMATIC_OBJECT, BODYTYPE_STATIC, BODYGROUP_DYNAMIC, BODYGROUP_KINEMATIC, BODYGROUP_STATIC, @@ -8,6 +5,9 @@ import { BODYSTATE_ACTIVE_TAG, BODYSTATE_DISABLE_DEACTIVATION, BODYSTATE_DISABLE_SIMULATION, BODYTYPE_DYNAMIC, BODYTYPE_KINEMATIC } from './constants.js'; +import { Quat } from '../../../core/math/quat.js'; +import { Vec3 } from '../../../core/math/vec3.js'; +import { Component } from '../component.js'; /** * @import { Entity } from '../../entity.js' diff --git a/src/framework/components/rigid-body/system.js b/src/framework/components/rigid-body/system.js index 36856662795..b369fb84330 100644 --- a/src/framework/components/rigid-body/system.js +++ b/src/framework/components/rigid-body/system.js @@ -1,12 +1,12 @@ -import { now } from '../../../core/time.js'; -import { ObjectPool } from '../../../core/object-pool.js'; +import { RigidBodyComponent } from './component.js'; +import { BODYFLAG_NORESPONSE_OBJECT } from './constants.js'; +import { RigidBodyComponentData } from './data.js'; import { Debug } from '../../../core/debug.js'; import { Vec3 } from '../../../core/math/vec3.js'; +import { ObjectPool } from '../../../core/object-pool.js'; +import { now } from '../../../core/time.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { BODYFLAG_NORESPONSE_OBJECT } from './constants.js'; -import { RigidBodyComponent } from './component.js'; -import { RigidBodyComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -1025,8 +1025,9 @@ class RigidBodyComponentSystem extends ComponentSystem { dynamic[i]._updateDynamic(); } - if (!this.dynamicsWorld.setInternalTickCallback) + if (!this.dynamicsWorld.setInternalTickCallback) { this._checkForCollisions(Ammo.getPointer(this.dynamicsWorld), dt); + } // #if _PROFILER this._stats.physicsTime = now() - this._stats.physicsStart; diff --git a/src/framework/components/screen/component.js b/src/framework/components/screen/component.js index 00c6378f0be..3e2ccf1a53d 100644 --- a/src/framework/components/screen/component.js +++ b/src/framework/components/screen/component.js @@ -1,8 +1,8 @@ +import { SCALEMODE_BLEND, SCALEMODE_NONE } from './constants.js'; import { Debug } from '../../../core/debug.js'; import { Mat4 } from '../../../core/math/mat4.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Entity } from '../../entity.js'; -import { SCALEMODE_BLEND, SCALEMODE_NONE } from './constants.js'; import { Component } from '../component.js'; /** @@ -173,8 +173,9 @@ class ScreenComponent extends Component { this._calcProjectionMatrix(); - if (!this.entity._dirtyLocal) + if (!this.entity._dirtyLocal) { this.entity._dirtifyLocal(); + } this.fire('set:resolution', this._resolution); this._elements.forEach(element => element._onScreenResize(this._resolution)); @@ -202,8 +203,9 @@ class ScreenComponent extends Component { this._updateScale(); this._calcProjectionMatrix(); - if (!this.entity._dirtyLocal) + if (!this.entity._dirtyLocal) { this.entity._dirtifyLocal(); + } this.fire('set:referenceresolution', this._resolution); this._elements.forEach(element => element._onScreenResize(this._resolution)); @@ -234,8 +236,9 @@ class ScreenComponent extends Component { } this.resolution = this._resolution; // force update either way - if (!this.entity._dirtyLocal) + if (!this.entity._dirtyLocal) { this.entity._dirtifyLocal(); + } this.fire('set:screenspace', this._screenSpace); @@ -294,8 +297,9 @@ class ScreenComponent extends Component { this._updateScale(); this._calcProjectionMatrix(); - if (!this.entity._dirtyLocal) + if (!this.entity._dirtyLocal) { this.entity._dirtifyLocal(); + } this.fire('set:scaleblend', this._scaleBlend); diff --git a/src/framework/components/screen/system.js b/src/framework/components/screen/system.js index b7b23ee12c0..a5e820a24ca 100644 --- a/src/framework/components/screen/system.js +++ b/src/framework/components/screen/system.js @@ -1,9 +1,9 @@ +import { ScreenComponent } from './component.js'; +import { ScreenComponentData } from './data.js'; import { IndexedList } from '../../../core/indexed-list.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { ScreenComponent } from './component.js'; -import { ScreenComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/script/component.js b/src/framework/components/script/component.js index a3c4dad9d4c..59e19b3cd94 100644 --- a/src/framework/components/script/component.js +++ b/src/framework/components/script/component.js @@ -1,14 +1,14 @@ import { Debug } from '../../../core/debug.js'; import { SortedLoopArray } from '../../../core/sorted-loop-array.js'; -import { ScriptAttributes, assignAttributesToScript } from '../../script/script-attributes.js'; -import { Component } from '../component.js'; import { Entity } from '../../entity.js'; import { SCRIPT_INITIALIZE, SCRIPT_POST_INITIALIZE, SCRIPT_UPDATE, SCRIPT_POST_UPDATE, SCRIPT_SWAP } from '../../script/constants.js'; +import { ScriptAttributes, assignAttributesToScript } from '../../script/script-attributes.js'; import { ScriptType } from '../../script/script-type.js'; import { getScriptName } from '../../script/script.js'; +import { Component } from '../component.js'; /** * @import { ScriptComponentSystem } from './system.js' @@ -211,8 +211,9 @@ class ScriptComponent extends Component { this._scriptsData = value; for (const key in value) { - if (!value.hasOwnProperty(key)) + if (!value.hasOwnProperty(key)) { continue; + } const script = this._scriptsIndex[key]; if (script) { @@ -231,14 +232,16 @@ class ScriptComponent extends Component { // attributes if (typeof value[key].attributes === 'object') { for (const attr in value[key].attributes) { - if (ScriptAttributes.reservedNames.has(attr)) + if (ScriptAttributes.reservedNames.has(attr)) { continue; + } if (!script.__attributes.hasOwnProperty(attr)) { // new attribute const scriptType = this.system.app.scripts.get(key); - if (scriptType) + if (scriptType) { scriptType.attributes.add(attr, { }); + } } // update attribute @@ -296,8 +299,9 @@ class ScriptComponent extends Component { if (script._initialized && !script._postInitialized && script.enabled) { script._postInitialized = true; - if (script.postInitialize) + if (script.postInitialize) { this._scriptMethod(script, SCRIPT_POST_INITIALIZE); + } } } @@ -332,8 +336,9 @@ class ScriptComponent extends Component { _checkState() { const state = this.enabled && this.entity.enabled; - if (state === this._oldState) + if (state === this._oldState) { return; + } this._oldState = state; @@ -457,8 +462,9 @@ class ScriptComponent extends Component { const script = scripts[i]; if (!script._initialized && script.enabled) { script._initialized = true; - if (script.initialize) + if (script.initialize) { this._scriptMethod(script, SCRIPT_INITIALIZE); + } } } @@ -707,8 +713,9 @@ class ScriptComponent extends Component { const len = this._scripts.length; let ind = -1; - if (typeof args.ind === 'number' && args.ind !== -1 && len > args.ind) + if (typeof args.ind === 'number' && args.ind !== -1 && len > args.ind) { ind = args.ind; + } this._insertScriptInstance(scriptInstance, ind, len); @@ -721,27 +728,30 @@ class ScriptComponent extends Component { this[scriptName] = scriptInstance; - if (!args.preloading) + if (!args.preloading) { this.initializeAttributes(scriptInstance); + } this.fire('create', scriptName, scriptInstance); - this.fire('create:' + scriptName, scriptInstance); + this.fire(`create:${scriptName}`, scriptInstance); - this.system.app.scripts.on('swap:' + scriptName, this._scriptsIndex[scriptName].onSwap); + this.system.app.scripts.on(`swap:${scriptName}`, this._scriptsIndex[scriptName].onSwap); if (!args.preloading) { if (scriptInstance.enabled && !scriptInstance._initialized) { scriptInstance._initialized = true; - if (scriptInstance.initialize) + if (scriptInstance.initialize) { this._scriptMethod(scriptInstance, SCRIPT_INITIALIZE); + } } if (scriptInstance.enabled && !scriptInstance._postInitialized) { scriptInstance._postInitialized = true; - if (scriptInstance.postInitialize) + if (scriptInstance.postInitialize) { this._scriptMethod(scriptInstance, SCRIPT_POST_INITIALIZE); + } } } @@ -807,15 +817,16 @@ class ScriptComponent extends Component { } // remove swap event - this.system.app.scripts.off('swap:' + scriptName, scriptData.onSwap); + this.system.app.scripts.off(`swap:${scriptName}`, scriptData.onSwap); delete this[scriptName]; this.fire('destroy', scriptName, scriptInstance || null); - this.fire('destroy:' + scriptName, scriptInstance || null); + this.fire(`destroy:${scriptName}`, scriptInstance || null); - if (scriptInstance) + if (scriptInstance) { scriptInstance.fire('destroy'); + } return true; } @@ -851,8 +862,9 @@ class ScriptComponent extends Component { attributes: scriptInstanceOld.__attributes }); - if (!scriptInstance.swap) + if (!scriptInstance.swap) { return false; + } this.initializeAttributes(scriptInstance); @@ -881,7 +893,7 @@ class ScriptComponent extends Component { this._scriptMethod(scriptInstance, SCRIPT_SWAP, scriptInstanceOld); this.fire('swap', scriptName, scriptInstance); - this.fire('swap:' + scriptName, scriptInstance); + this.fire(`swap:${scriptName}`, scriptInstance); return true; } @@ -1001,8 +1013,9 @@ class ScriptComponent extends Component { */ move(nameOrType, ind) { const len = this._scripts.length; - if (ind >= len || ind < 0) + if (ind >= len || ind < 0) { return false; + } let scriptType = nameOrType; let scriptName = nameOrType; @@ -1014,17 +1027,20 @@ class ScriptComponent extends Component { } const scriptData = this._scriptsIndex[scriptName]; - if (!scriptData || !scriptData.instance) + if (!scriptData || !scriptData.instance) { return false; + } // if script type specified, make sure instance of said type const scriptInstance = scriptData.instance; - if (scriptType && !(scriptInstance instanceof scriptType)) + if (scriptType && !(scriptInstance instanceof scriptType)) { return false; + } const indOld = this._scripts.indexOf(scriptInstance); - if (indOld === -1 || indOld === ind) + if (indOld === -1 || indOld === ind) { return false; + } // move script to another position this._scripts.splice(ind, 0, this._scripts.splice(indOld, 1)[0]); @@ -1035,7 +1051,7 @@ class ScriptComponent extends Component { this._postUpdateList.sort(); this.fire('move', scriptName, scriptInstance, ind, indOld); - this.fire('move:' + scriptName, scriptInstance, ind, indOld); + this.fire(`move:${scriptName}`, scriptInstance, ind, indOld); return true; } diff --git a/src/framework/components/script/system.js b/src/framework/components/script/system.js index 180ccc5bd8f..f803df44401 100644 --- a/src/framework/components/script/system.js +++ b/src/framework/components/script/system.js @@ -1,7 +1,7 @@ -import { SortedLoopArray } from '../../../core/sorted-loop-array.js'; -import { ComponentSystem } from '../system.js'; import { ScriptComponent } from './component.js'; import { ScriptComponentData } from './data.js'; +import { SortedLoopArray } from '../../../core/sorted-loop-array.js'; +import { ComponentSystem } from '../system.js'; /** * @import { AppBase } from '../../app-base.js' @@ -110,8 +110,9 @@ class ScriptComponentSystem extends ComponentSystem { order.push(scriptName); const attributes = { }; - for (const key in scriptInstance.__attributes) + for (const key in scriptInstance.__attributes) { attributes[key] = scriptInstance.__attributes[key]; + } scripts[scriptName] = { enabled: scriptInstance._enabled, diff --git a/src/framework/components/scroll-view/component.js b/src/framework/components/scroll-view/component.js index b5c9321dc87..6597aa8bf48 100644 --- a/src/framework/components/scroll-view/component.js +++ b/src/framework/components/scroll-view/component.js @@ -1,13 +1,13 @@ +import { SCROLL_MODE_BOUNCE, SCROLL_MODE_CLAMP, SCROLL_MODE_INFINITE, SCROLLBAR_VISIBILITY_SHOW_ALWAYS, SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED } from './constants.js'; import { Debug } from '../../../core/debug.js'; import { math } from '../../../core/math/math.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec3 } from '../../../core/math/vec3.js'; +import { EVENT_MOUSEWHEEL } from '../../../platform/input/constants.js'; import { ORIENTATION_HORIZONTAL, ORIENTATION_VERTICAL } from '../../../scene/constants.js'; import { EntityReference } from '../../utils/entity-reference.js'; -import { ElementDragHelper } from '../element/element-drag-helper.js'; -import { SCROLL_MODE_BOUNCE, SCROLL_MODE_CLAMP, SCROLL_MODE_INFINITE, SCROLLBAR_VISIBILITY_SHOW_ALWAYS, SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED } from './constants.js'; import { Component } from '../component.js'; -import { EVENT_MOUSEWHEEL } from '../../../platform/input/constants.js'; +import { ElementDragHelper } from '../element/element-drag-helper.js'; /** * @import { Entity } from '../../entity.js' @@ -575,7 +575,7 @@ class ScrollViewComponent extends Component { return scrollValue; default: - console.warn('Unhandled scroll mode:' + this.scrollMode); + console.warn(`Unhandled scroll mode:${this.scrollMode}`); return scrollValue; } } @@ -656,7 +656,7 @@ class ScrollViewComponent extends Component { return; default: - console.warn('Unhandled scrollbar visibility:' + requestedVisibility); + console.warn(`Unhandled scrollbar visibility:${requestedVisibility}`); entity.enabled = isScrollingEnabled; } } diff --git a/src/framework/components/scroll-view/system.js b/src/framework/components/scroll-view/system.js index 2a74ab2beea..404bfc3745d 100644 --- a/src/framework/components/scroll-view/system.js +++ b/src/framework/components/scroll-view/system.js @@ -1,7 +1,7 @@ -import { Vec2 } from '../../../core/math/vec2.js'; -import { ComponentSystem } from '../system.js'; import { ScrollViewComponent } from './component.js'; import { ScrollViewComponentData } from './data.js'; +import { Vec2 } from '../../../core/math/vec2.js'; +import { ComponentSystem } from '../system.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/scrollbar/component.js b/src/framework/components/scrollbar/component.js index 713a50971b7..2c7b8d54708 100644 --- a/src/framework/components/scrollbar/component.js +++ b/src/framework/components/scrollbar/component.js @@ -1,8 +1,8 @@ import { math } from '../../../core/math/math.js'; import { ORIENTATION_HORIZONTAL } from '../../../scene/constants.js'; +import { EntityReference } from '../../utils/entity-reference.js'; import { Component } from '../component.js'; import { ElementDragHelper } from '../element/element-drag-helper.js'; -import { EntityReference } from '../../utils/entity-reference.js'; /** * @import { Entity } from '../../entity.js' diff --git a/src/framework/components/scrollbar/system.js b/src/framework/components/scrollbar/system.js index 3be71f2602a..4bd82e4af17 100644 --- a/src/framework/components/scrollbar/system.js +++ b/src/framework/components/scrollbar/system.js @@ -1,6 +1,6 @@ -import { ComponentSystem } from '../system.js'; import { ScrollbarComponent } from './component.js'; import { ScrollbarComponentData } from './data.js'; +import { ComponentSystem } from '../system.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/sound/component.js b/src/framework/components/sound/component.js index 03bf4a1c579..729e0d80e7b 100644 --- a/src/framework/components/sound/component.js +++ b/src/framework/components/sound/component.js @@ -1,7 +1,7 @@ +import { SoundSlot } from './slot.js'; import { Debug } from '../../../core/debug.js'; import { DISTANCE_LINEAR } from '../../../platform/audio/constants.js'; import { Component } from '../component.js'; -import { SoundSlot } from './slot.js'; /** * @import { Entity } from '../../entity.js' @@ -323,8 +323,9 @@ class SoundComponent extends Component { for (let i = oldLength - 1; i >= 0; i--) { const isPlaying = instances[i].isPlaying || instances[i].isSuspended; const currentTime = instances[i].currentTime; - if (isPlaying) + if (isPlaying) { instances[i].stop(); + } const instance = slot._createInstance(); if (isPlaying) { @@ -378,8 +379,9 @@ class SoundComponent extends Component { this._slots = slots; // call onEnable in order to start autoPlay slots - if (this.enabled && this.entity.enabled) + if (this.enabled && this.entity.enabled) { this.onEnable(); + } } /** diff --git a/src/framework/components/sound/slot.js b/src/framework/components/sound/slot.js index ebe51c5064d..1784e2efea1 100644 --- a/src/framework/components/sound/slot.js +++ b/src/framework/components/sound/slot.js @@ -1,10 +1,10 @@ -import { EventHandler } from '../../../core/event-handler.js'; import { Debug } from '../../../core/debug.js'; +import { EventHandler } from '../../../core/event-handler.js'; import { math } from '../../../core/math/math.js'; import { Vec3 } from '../../../core/math/vec3.js'; -import { Asset } from '../../asset/asset.js'; import { SoundInstance } from '../../../platform/sound/instance.js'; import { SoundInstance3d } from '../../../platform/sound/instance3d.js'; +import { Asset } from '../../asset/asset.js'; /** * @import { SoundComponent } from './component.js' @@ -233,8 +233,9 @@ class SoundSlot extends EventHandler { const instances = this.instances; for (let i = 0, len = instances.length; i < len; i++) { - if (instances[i].resume()) + if (instances[i].resume()) { resumed = true; + } } return resumed; @@ -267,13 +268,14 @@ class SoundSlot extends EventHandler { * Loads the asset assigned to this slot. */ load() { - if (!this._hasAsset()) + if (!this._hasAsset()) { return; + } const asset = this._assets.get(this._asset); if (!asset) { - this._assets.off('add:' + this._asset, this._onAssetAdd, this); - this._assets.once('add:' + this._asset, this._onAssetAdd, this); + this._assets.off(`add:${this._asset}`, this._onAssetAdd, this); + this._assets.once(`add:${this._asset}`, this._onAssetAdd, this); return; } @@ -489,7 +491,7 @@ class SoundSlot extends EventHandler { _onAssetRemoved(asset) { asset.off('remove', this._onAssetRemoved, this); - this._assets.off('add:' + asset.id, this._onAssetAdd, this); + this._assets.off(`add:${asset.id}`, this._onAssetAdd, this); this.stop(); } @@ -509,7 +511,7 @@ class SoundSlot extends EventHandler { const old = this._asset; if (old) { - this._assets.off('add:' + old, this._onAssetAdd, this); + this._assets.off(`add:${old}`, this._onAssetAdd, this); const oldAsset = this._assets.get(old); if (oldAsset) { oldAsset.off('remove', this._onAssetRemoved, this); @@ -614,12 +616,14 @@ class SoundSlot extends EventHandler { get isPaused() { const instances = this.instances; const len = instances.length; - if (len === 0) + if (len === 0) { return false; + } for (let i = 0; i < len; i++) { - if (!instances[i].isPaused) + if (!instances[i].isPaused) { return false; + } } return true; @@ -633,8 +637,9 @@ class SoundSlot extends EventHandler { get isPlaying() { const instances = this.instances; for (let i = 0, len = instances.length; i < len; i++) { - if (instances[i].isPlaying) + if (instances[i].isPlaying) { return true; + } } return false; @@ -648,8 +653,9 @@ class SoundSlot extends EventHandler { get isStopped() { const instances = this.instances; for (let i = 0, len = instances.length; i < len; i++) { - if (!instances[i].isStopped) + if (!instances[i].isStopped) { return false; + } } return true; diff --git a/src/framework/components/sound/system.js b/src/framework/components/sound/system.js index 3105976a4db..37b31dab722 100644 --- a/src/framework/components/sound/system.js +++ b/src/framework/components/sound/system.js @@ -1,9 +1,9 @@ +import { SoundComponent } from './component.js'; +import { SoundComponentData } from './data.js'; import { Debug } from '../../../core/debug.js'; import { hasAudioContext } from '../../../platform/audio/capabilities.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { SoundComponent } from './component.js'; -import { SoundComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' @@ -40,7 +40,7 @@ class SoundComponentSystem extends ComponentSystem { * @type {SoundManager} */ this.manager = app.soundManager; - Debug.assert(this.manager, "SoundComponentSystem cannot be created without sound manager"); + Debug.assert(this.manager, 'SoundComponentSystem cannot be created without sound manager'); this.app.systems.on('update', this.onUpdate, this); diff --git a/src/framework/components/sprite/component.js b/src/framework/components/sprite/component.js index ab332eae333..148ba64a9b5 100644 --- a/src/framework/components/sprite/component.js +++ b/src/framework/components/sprite/component.js @@ -1,19 +1,19 @@ +import { SPRITETYPE_SIMPLE, SPRITETYPE_ANIMATED } from './constants.js'; +import { SpriteAnimationClip } from './sprite-animation-clip.js'; import { Debug } from '../../../core/debug.js'; -import { math } from '../../../core/math/math.js'; import { Color } from '../../../core/math/color.js'; +import { math } from '../../../core/math/math.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec4 } from '../../../core/math/vec4.js'; +import { BatchGroup } from '../../../scene/batching/batch-group.js'; import { LAYERID_WORLD, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED } from '../../../scene/constants.js'; -import { BatchGroup } from '../../../scene/batching/batch-group.js'; import { GraphNode } from '../../../scene/graph-node.js'; import { MeshInstance } from '../../../scene/mesh-instance.js'; import { Model } from '../../../scene/model.js'; import { Component } from '../component.js'; -import { SPRITETYPE_SIMPLE, SPRITETYPE_ANIMATED } from './constants.js'; -import { SpriteAnimationClip } from './sprite-animation-clip.js'; /** * @import { Asset } from '../../asset/asset.js' @@ -194,8 +194,9 @@ class SpriteComponent extends Component { * @type {string} */ set type(value) { - if (this._type === value) + if (this._type === value) { return; + } this._type = value; if (this._type === SPRITETYPE_SIMPLE) { @@ -544,8 +545,9 @@ class SpriteComponent extends Component { * @type {number} */ set batchGroupId(value) { - if (this._batchGroupId === value) + if (this._batchGroupId === value) { return; + } const prev = this._batchGroupId; this._batchGroupId = value; @@ -666,8 +668,9 @@ class SpriteComponent extends Component { } this._showModel(); - if (this._autoPlayClip) + if (this._autoPlayClip) { this._tryAutoPlay(); + } if (this._batchGroupId >= 0) { app.batcher?.insert(BatchGroup.SPRITE, this._batchGroupId, this.entity); @@ -838,9 +841,9 @@ class SpriteComponent extends Component { const tex = this.sprite.atlas.texture; this._atlasRect.set(frameData.rect.x / tex.width, - frameData.rect.y / tex.height, - frameData.rect.z / tex.width, - frameData.rect.w / tex.height + frameData.rect.y / tex.height, + frameData.rect.z / tex.width, + frameData.rect.w / tex.height ); } else { @@ -1004,8 +1007,9 @@ class SpriteComponent extends Component { this._clips[data.name] = clip; - if (clip.name && clip.name === this._autoPlayClip) + if (clip.name && clip.name === this._autoPlayClip) { this._tryAutoPlay(); + } return clip; } diff --git a/src/framework/components/sprite/sprite-animation-clip.js b/src/framework/components/sprite/sprite-animation-clip.js index 700264a6e63..60870c5a8df 100644 --- a/src/framework/components/sprite/sprite-animation-clip.js +++ b/src/framework/components/sprite/sprite-animation-clip.js @@ -1,7 +1,7 @@ import { EventHandler } from '../../../core/event-handler.js'; import { math } from '../../../core/math/math.js'; -import { Asset } from '../../asset/asset.js'; import { SPRITE_RENDERMODE_SIMPLE } from '../../../scene/constants.js'; +import { Asset } from '../../asset/asset.js'; /** * @import { SpriteComponent } from './component.js' @@ -272,7 +272,7 @@ class SpriteAnimationClip extends EventHandler { const asset = assets.get(this._spriteAsset); if (!asset) { this.sprite = null; - assets.on('add:' + this._spriteAsset, this._onSpriteAssetAdded, this); + assets.on(`add:${this._spriteAsset}`, this._onSpriteAssetAdded, this); } else { this._bindSpriteAsset(asset); } @@ -317,7 +317,7 @@ class SpriteAnimationClip extends EventHandler { // When sprite asset is added bind it _onSpriteAssetAdded(asset) { - this._component.system.app.assets.off('add:' + asset.id, this._onSpriteAssetAdded, this); + this._component.system.app.assets.off(`add:${asset.id}`, this._onSpriteAssetAdded, this); if (this._spriteAsset === asset.id) { this._bindSpriteAsset(asset); } @@ -345,7 +345,7 @@ class SpriteAnimationClip extends EventHandler { // unbind atlas if (asset.resource && !asset.resource.atlas) { - this._component.system.app.assets.off('load:' + asset.data.textureAtlasAsset, this._onTextureAtlasLoad, this); + this._component.system.app.assets.off(`load:${asset.data.textureAtlasAsset}`, this._onTextureAtlasLoad, this); } } @@ -358,8 +358,8 @@ class SpriteAnimationClip extends EventHandler { if (!asset.resource.atlas) { const atlasAssetId = asset.data.textureAtlasAsset; const assets = this._component.system.app.assets; - assets.off('load:' + atlasAssetId, this._onTextureAtlasLoad, this); - assets.once('load:' + atlasAssetId, this._onTextureAtlasLoad, this); + assets.off(`load:${atlasAssetId}`, this._onTextureAtlasLoad, this); + assets.once(`load:${atlasAssetId}`, this._onTextureAtlasLoad, this); } else { this.sprite = asset.resource; } @@ -491,8 +491,9 @@ class SpriteAnimationClip extends EventHandler { * Plays the animation. If it's already playing then this does nothing. */ play() { - if (this._playing) + if (this._playing) { return; + } this._playing = true; this._paused = false; @@ -506,8 +507,9 @@ class SpriteAnimationClip extends EventHandler { * Pauses the animation. */ pause() { - if (!this._playing || this._paused) + if (!this._playing || this._paused) { return; + } this._paused = true; diff --git a/src/framework/components/sprite/system.js b/src/framework/components/sprite/system.js index 54ef83bef8f..7043c3bad01 100644 --- a/src/framework/components/sprite/system.js +++ b/src/framework/components/sprite/system.js @@ -1,3 +1,5 @@ +import { SpriteComponent } from './component.js'; +import { SpriteComponentData } from './data.js'; import { Color } from '../../../core/math/color.js'; import { CULLFACE_NONE, @@ -8,8 +10,6 @@ import { BLEND_PREMULTIPLIED, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED import { StandardMaterial } from '../../../scene/materials/standard-material.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { SpriteComponent } from './component.js'; -import { SpriteComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/components/system.js b/src/framework/components/system.js index d055bf39109..c556840c3dc 100644 --- a/src/framework/components/system.js +++ b/src/framework/components/system.js @@ -159,7 +159,7 @@ class ComponentSystem extends EventHandler { const matchingProperties = []; const schema = this.schema || []; - schema.forEach(function (descriptor) { + schema.forEach((descriptor) => { if (descriptor && typeof descriptor === 'object' && descriptor.type === type) { matchingProperties.push(descriptor); } @@ -211,7 +211,7 @@ function convertValue(value, type) { case 'entity': return value; // Entity fields should just be a string guid default: - throw new Error('Could not convert unhandled type: ' + type); + throw new Error(`Could not convert unhandled type: ${type}`); } } diff --git a/src/framework/components/zone/component.js b/src/framework/components/zone/component.js index 10dc2a4f3d7..dfe60121717 100644 --- a/src/framework/components/zone/component.js +++ b/src/framework/components/zone/component.js @@ -108,8 +108,9 @@ class ZoneComponent extends Component { _checkState() { const state = this.enabled && this.entity.enabled; - if (state === this._oldState) + if (state === this._oldState) { return; + } this._oldState = state; diff --git a/src/framework/components/zone/system.js b/src/framework/components/zone/system.js index b4d42bebc02..b23d046369a 100644 --- a/src/framework/components/zone/system.js +++ b/src/framework/components/zone/system.js @@ -1,8 +1,8 @@ +import { ZoneComponent } from './component.js'; +import { ZoneComponentData } from './data.js'; import { Vec3 } from '../../../core/math/vec3.js'; import { Component } from '../component.js'; import { ComponentSystem } from '../system.js'; -import { ZoneComponent } from './component.js'; -import { ZoneComponentData } from './data.js'; /** * @import { AppBase } from '../../app-base.js' diff --git a/src/framework/entity.js b/src/framework/entity.js index 6d4c1f253d4..4352084d149 100644 --- a/src/framework/entity.js +++ b/src/framework/entity.js @@ -1,7 +1,7 @@ +import { getApplication } from './globals.js'; import { Debug } from '../core/debug.js'; import { guid } from '../core/guid.js'; import { GraphNode } from '../scene/graph-node.js'; -import { getApplication } from './globals.js'; /** * @import { AnimComponent } from './components/anim/component.js' @@ -516,20 +516,23 @@ class Entity extends GraphNode { */ _notifyHierarchyStateChanged(node, enabled) { let enableFirst = false; - if (node === this && _enableList.length === 0) + if (node === this && _enableList.length === 0) { enableFirst = true; + } node._beingEnabled = true; node._onHierarchyStateChanged(enabled); - if (node._onHierarchyStatePostChanged) + if (node._onHierarchyStatePostChanged) { _enableList.push(node); + } const c = node._children; for (let i = 0, len = c.length; i < len; i++) { - if (c[i]._enabled) + if (c[i]._enabled) { this._notifyHierarchyStateChanged(c[i], enabled); + } } node._beingEnabled = false; diff --git a/src/framework/font/canvas-font.js b/src/framework/font/canvas-font.js index 64d701258da..670f29b045e 100644 --- a/src/framework/font/canvas-font.js +++ b/src/framework/font/canvas-font.js @@ -1,6 +1,6 @@ -import { string } from '../../core/string.js'; import { EventHandler } from '../../core/event-handler.js'; import { Color } from '../../core/math/color.js'; +import { string } from '../../core/string.js'; import { ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, FILTER_LINEAR_MIPMAP_LINEAR, @@ -270,7 +270,7 @@ class CanvasFont extends EventHandler { const code = string.getCodePoint(symbols[i]); let fs = this.fontSize; - atlas.ctx.font = this.fontWeight + ' ' + fs.toString() + 'px ' + this.fontName; + atlas.ctx.font = `${this.fontWeight} ${fs.toString()}px ${this.fontName}`; atlas.ctx.textAlign = TEXT_ALIGN; atlas.ctx.textBaseline = TEXT_BASELINE; @@ -278,7 +278,7 @@ class CanvasFont extends EventHandler { if (width > fs) { fs = this.fontSize * this.fontSize / width; - atlas.ctx.font = this.fontWeight + ' ' + fs.toString() + 'px ' + this.fontName; + atlas.ctx.font = `${this.fontWeight} ${fs.toString()}px ${this.fontName}`; width = this.fontSize; } @@ -430,7 +430,7 @@ class CanvasFont extends EventHandler { const div = document.createElement('div'); div.appendChild(textSpan); div.appendChild(block); - div.style.font = this.fontSize + 'px ' + this.fontName; + div.style.font = `${this.fontSize}px ${this.fontName}`; const body = document.body; body.appendChild(div); diff --git a/src/framework/font/font.js b/src/framework/font/font.js index cae741387f9..f49d3130e09 100644 --- a/src/framework/font/font.js +++ b/src/framework/font/font.js @@ -42,15 +42,17 @@ class Font { set data(value) { this._data = value; - if (!value) + if (!value) { return; + } if (this._data.intensity !== undefined) { this.intensity = this._data.intensity; } - if (!this._data.info) + if (!this._data.info) { this._data.info = {}; + } // check if we need to migrate to version 2 if (!this._data.version || this._data.version < 2) { diff --git a/src/framework/graphics/picker.js b/src/framework/graphics/picker.js index 5b3d23627ef..b5b58a2bf66 100644 --- a/src/framework/graphics/picker.js +++ b/src/framework/graphics/picker.js @@ -1,12 +1,12 @@ +import { RenderPassPicker } from './render-pass-picker.js'; +import { Debug } from '../../core/debug.js'; import { Color } from '../../core/math/color.js'; +import { math } from '../../core/math/math.js'; +import { Vec4 } from '../../core/math/vec4.js'; import { ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, PIXELFORMAT_RGBA8 } from '../../platform/graphics/constants.js'; import { RenderTarget } from '../../platform/graphics/render-target.js'; import { Texture } from '../../platform/graphics/texture.js'; import { Layer } from '../../scene/layer.js'; -import { Debug } from '../../core/debug.js'; -import { RenderPassPicker } from './render-pass-picker.js'; -import { math } from '../../core/math/math.js'; -import { Vec4 } from '../../core/math/vec4.js'; /** * @import { AppBase } from '../app-base.js' @@ -92,7 +92,7 @@ class Picker { return []; } - Debug.assert(typeof x !== 'object', `Picker.getSelection:param 'rect' is deprecated, use 'x, y, width, height' instead.`); + Debug.assert(typeof x !== 'object', 'Picker.getSelection:param \'rect\' is deprecated, use \'x, y, width, height\' instead.'); y = this.renderTarget.height - (y + height); const rect = this.sanitizeRect(x, y, width, height); @@ -178,8 +178,9 @@ class Picker { // return the content of the set as an array tempSet.forEach((meshInstance) => { - if (meshInstance) + if (meshInstance) { selection.push(meshInstance); + } }); tempSet.clear(); } diff --git a/src/framework/graphics/primitive-cache.js b/src/framework/graphics/primitive-cache.js index 2cb82c62be3..54514c8fbe4 100644 --- a/src/framework/graphics/primitive-cache.js +++ b/src/framework/graphics/primitive-cache.js @@ -1,12 +1,12 @@ -import { Vec2 } from "../../core/math/vec2.js"; -import { CapsuleGeometry } from "../../scene/geometry/capsule-geometry.js"; -import { ConeGeometry } from "../../scene/geometry/cone-geometry.js"; -import { CylinderGeometry } from "../../scene/geometry/cylinder-geometry.js"; -import { TorusGeometry } from "../../scene/geometry/torus-geometry.js"; -import { Mesh } from "../../scene/mesh.js"; -import { BoxGeometry } from "../../scene/geometry/box-geometry.js"; -import { SphereGeometry } from "../../scene/geometry/sphere-geometry.js"; -import { PlaneGeometry } from "../../scene/geometry/plane-geometry.js"; +import { Vec2 } from '../../core/math/vec2.js'; +import { BoxGeometry } from '../../scene/geometry/box-geometry.js'; +import { CapsuleGeometry } from '../../scene/geometry/capsule-geometry.js'; +import { ConeGeometry } from '../../scene/geometry/cone-geometry.js'; +import { CylinderGeometry } from '../../scene/geometry/cylinder-geometry.js'; +import { PlaneGeometry } from '../../scene/geometry/plane-geometry.js'; +import { SphereGeometry } from '../../scene/geometry/sphere-geometry.js'; +import { TorusGeometry } from '../../scene/geometry/torus-geometry.js'; +import { Mesh } from '../../scene/mesh.js'; // cached mesh primitives const shapePrimitives = []; @@ -64,7 +64,7 @@ function getShapePrimitive(device, type) { break; default: - throw new Error('Invalid primitive type: ' + type); + throw new Error(`Invalid primitive type: ${type}`); } // inc reference to keep primitive alive diff --git a/src/framework/graphics/render-pass-picker.js b/src/framework/graphics/render-pass-picker.js index 91468be0a24..3a8ea7c4018 100644 --- a/src/framework/graphics/render-pass-picker.js +++ b/src/framework/graphics/render-pass-picker.js @@ -1,5 +1,5 @@ -import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; import { BlendState } from '../../platform/graphics/blend-state.js'; +import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; import { RenderPass } from '../../platform/graphics/render-pass.js'; import { SHADER_PICK } from '../../scene/constants.js'; diff --git a/src/framework/handlers/anim-clip.js b/src/framework/handlers/anim-clip.js index d156cc82d69..2e20755d332 100644 --- a/src/framework/handlers/anim-clip.js +++ b/src/framework/handlers/anim-clip.js @@ -1,10 +1,9 @@ +import { ResourceHandler } from './handler.js'; import { http, Http } from '../../platform/net/http.js'; - import { AnimCurve } from '../anim/evaluator/anim-curve.js'; import { AnimData } from '../anim/evaluator/anim-data.js'; import { AnimTrack } from '../anim/evaluator/anim-track.js'; -import { ResourceHandler } from './handler.js'; /** * Resource handler used for loading {@link AnimClip} resources. @@ -34,7 +33,7 @@ class AnimClipHandler extends ResourceHandler { options.responseType = Http.ResponseType.JSON; } - http.get(url.load, options, function (err, response) { + http.get(url.load, options, (err, response) => { if (err) { callback(`Error loading animation clip resource: ${url.original} [${err}]`); } else { @@ -46,13 +45,13 @@ class AnimClipHandler extends ResourceHandler { open(url, data) { const name = data.name; const duration = data.duration; - const inputs = data.inputs.map(function (input) { + const inputs = data.inputs.map((input) => { return new AnimData(1, input); }); - const outputs = data.outputs.map(function (output) { + const outputs = data.outputs.map((output) => { return new AnimData(output.components, output.data); }); - const curves = data.curves.map(function (curve) { + const curves = data.curves.map((curve) => { return new AnimCurve( [curve.path], curve.inputIndex, diff --git a/src/framework/handlers/anim-state-graph.js b/src/framework/handlers/anim-state-graph.js index 709900b6fbb..d6523363a7b 100644 --- a/src/framework/handlers/anim-state-graph.js +++ b/src/framework/handlers/anim-state-graph.js @@ -1,7 +1,7 @@ +import { ResourceHandler } from './handler.js'; import { http, Http } from '../../platform/net/http.js'; import { AnimStateGraph } from '../anim/state-graph/anim-state-graph.js'; -import { ResourceHandler } from './handler.js'; /** * Resource handler used for loading {@link AnimStateGraph} resources. @@ -31,7 +31,7 @@ class AnimStateGraphHandler extends ResourceHandler { options.responseType = Http.ResponseType.JSON; } - http.get(url.load, options, function (err, response) { + http.get(url.load, options, (err, response) => { if (err) { callback(`Error loading animation state graph resource: ${url.original} [${err}]`); } else { diff --git a/src/framework/handlers/animation.js b/src/framework/handlers/animation.js index f4df5d9e313..858b8e241dc 100644 --- a/src/framework/handlers/animation.js +++ b/src/framework/handlers/animation.js @@ -1,11 +1,11 @@ -import { path } from '../../core/path.js'; +import { ResourceHandler } from './handler.js'; import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; +import { path } from '../../core/path.js'; import { http, Http } from '../../platform/net/http.js'; import { Animation, Key, Node } from '../../scene/animation/animation.js'; import { AnimEvents } from '../anim/evaluator/anim-events.js'; import { GlbParser } from '../parsers/glb-parser.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -71,7 +71,7 @@ class AnimationHandler extends ResourceHandler { } }); } else { - callback(null, this['_parseAnimationV' + response.animation.version](response)); + callback(null, this[`_parseAnimationV${response.animation.version}`](response)); } } }); diff --git a/src/framework/handlers/audio.js b/src/framework/handlers/audio.js index 61ba50b006e..661a5046403 100644 --- a/src/framework/handlers/audio.js +++ b/src/framework/handlers/audio.js @@ -1,9 +1,9 @@ -import { path } from '../../core/path.js'; +import { ResourceHandler } from './handler.js'; import { Debug } from '../../core/debug.js'; -import { http, Http } from '../../platform/net/http.js'; +import { path } from '../../core/path.js'; import { hasAudioContext } from '../../platform/audio/capabilities.js'; +import { http, Http } from '../../platform/net/http.js'; import { Sound } from '../../platform/sound/sound.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -60,7 +60,7 @@ class AudioHandler extends ResourceHandler { super(app, 'audio'); this.manager = app.soundManager; - Debug.assert(this.manager, "AudioHandler cannot be created without sound manager"); + Debug.assert(this.manager, 'AudioHandler cannot be created without sound manager'); } _isSupported(url) { @@ -82,9 +82,9 @@ class AudioHandler extends ResourceHandler { }; const error = function (err) { - let msg = 'Error loading audio url: ' + url.original; + let msg = `Error loading audio url: ${url.original}`; if (err) { - msg += ': ' + (err.message || err); + msg += `: ${err.message || err}`; } console.warn(msg); callback(msg); @@ -132,7 +132,7 @@ class AudioHandler extends ResourceHandler { options.responseType = Http.ResponseType.ARRAY_BUFFER; } - http.get(url, options, function (err, response) { + http.get(url, options, (err, response) => { if (err) { error(err); return; diff --git a/src/framework/handlers/basis-worker.js b/src/framework/handlers/basis-worker.js index 621061bd6b3..4d8b3e94e36 100644 --- a/src/framework/handlers/basis-worker.js +++ b/src/framework/handlers/basis-worker.js @@ -229,7 +229,7 @@ function BasisWorker() { if (!basisFile.startTranscoding()) { basisFile.close(); basisFile.delete(); - throw new Error('Failed to start transcoding url=' + url); + throw new Error(`Failed to start transcoding url=${url}`); } let i; @@ -242,7 +242,7 @@ function BasisWorker() { if (!basisFile.transcodeImage(dst, mip, 0, 0, basisFormat, 0, -1, -1)) { basisFile.close(); basisFile.delete(); - throw new Error('Failed to transcode image url=' + url); + throw new Error(`Failed to transcode image url=${url}`); } const is16BitFormat = (basisFormat === BASIS_FORMAT.cTFRGB565 || basisFormat === BASIS_FORMAT.cTFRGBA4444); @@ -315,7 +315,7 @@ function BasisWorker() { if (!basisFile.startTranscoding()) { basisFile.close(); basisFile.delete(); - throw new Error('Failed to start transcoding url=' + url); + throw new Error(`Failed to start transcoding url=${url}`); } let i; @@ -332,11 +332,11 @@ function BasisWorker() { // fails to transcode. this is a workaround which copies the previous mip // level data instead of failing. dst.set(new Uint8Array(levelData[mip - 1].buffer)); - console.warn('Failed to transcode last mipmap level, using previous level instead url=' + url); + console.warn(`Failed to transcode last mipmap level, using previous level instead url=${url}`); } else { basisFile.close(); basisFile.delete(); - throw new Error('Failed to transcode image url=' + url); + throw new Error(`Failed to transcode image url=${url}`); } } @@ -388,26 +388,26 @@ function BasisWorker() { // initialize the wasm module const instantiateWasmFunc = (imports, successCallback) => { WebAssembly.instantiate(config.module, imports) - .then((result) => { - successCallback(result); - }) - .catch((reason) => { - console.error('instantiate failed + ' + reason); - }); + .then((result) => { + successCallback(result); + }) + .catch((reason) => { + console.error(`instantiate failed + ${reason}`); + }); return {}; }; self.BASIS(config.module ? { instantiateWasm: instantiateWasmFunc } : null) - .then((instance) => { - instance.initializeBasis(); + .then((instance) => { + instance.initializeBasis(); - // set globals - basis = instance; - rgbPriority = config.rgbPriority; - rgbaPriority = config.rgbaPriority; + // set globals + basis = instance; + rgbPriority = config.rgbPriority; + rgbaPriority = config.rgbaPriority; - callback(null); - }); + callback(null); + }); }; // handle incoming worker requests diff --git a/src/framework/handlers/basis.js b/src/framework/handlers/basis.js index 48be738b4a7..f465e8519bb 100644 --- a/src/framework/handlers/basis.js +++ b/src/framework/handlers/basis.js @@ -1,7 +1,7 @@ -import { WasmModule } from "../../core/wasm-module.js"; +import { BasisWorker } from './basis-worker.js'; import { Debug } from '../../core/debug.js'; +import { WasmModule } from '../../core/wasm-module.js'; import { PIXELFORMAT_RGB565, PIXELFORMAT_RGBA4 } from '../../platform/graphics/constants.js'; -import { BasisWorker } from './basis-worker.js'; import { http } from '../../platform/net/http.js'; /** @@ -26,8 +26,8 @@ const prepareWorkerModules = (config, callback) => { const code = [ '/* basis */', basisCode, - "", - '(' + BasisWorker.toString() + ')()\n\n' + '', + `(${BasisWorker.toString()})()\n\n` ].join('\n'); return new Blob([code], { type: 'application/javascript' }); }; @@ -36,8 +36,9 @@ const prepareWorkerModules = (config, callback) => { try { if (typeof WebAssembly === 'object' && typeof WebAssembly.instantiate === 'function') { const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00)); - if (module instanceof WebAssembly.Module) + if (module instanceof WebAssembly.Module) { return new WebAssembly.Instance(module) instanceof WebAssembly.Instance; + } } } catch (e) { } return false; @@ -80,34 +81,34 @@ const prepareWorkerModules = (config, callback) => { const compileManual = () => { fetchPromise - .then(result => result.arrayBuffer()) - .then(buffer => WebAssembly.compile(buffer)) - .then((module_) => { - if (basisCode) { - sendResponse(basisCode, module_); - } else { - module = module_; - } - }) - .catch((err) => { - callback(err, null); - }); + .then(result => result.arrayBuffer()) + .then(buffer => WebAssembly.compile(buffer)) + .then((module_) => { + if (basisCode) { + sendResponse(basisCode, module_); + } else { + module = module_; + } + }) + .catch((err) => { + callback(err, null); + }); }; // download and compile wasm module if (WebAssembly.compileStreaming) { WebAssembly.compileStreaming(fetchPromise) - .then((module_) => { - if (basisCode) { - sendResponse(basisCode, module_); - } else { - module = module_; - } - }) - .catch((err) => { - Debug.warn(`compileStreaming() failed for ${config.wasmUrl} (${err}), falling back to arraybuffer download.`); - compileManual(); - }); + .then((module_) => { + if (basisCode) { + sendResponse(basisCode, module_); + } else { + module = module_; + } + }) + .catch((err) => { + Debug.warn(`compileStreaming() failed for ${config.wasmUrl} (${err}), falling back to arraybuffer download.`); + compileManual(); + }); } else { compileManual(); } @@ -171,12 +172,12 @@ class BasisQueue { // (re)create typed array from the returned array buffers if (data.format === PIXELFORMAT_RGB565 || data.format === PIXELFORMAT_RGBA4) { // handle 16 bit formats - data.levels = data.levels.map(function (v) { + data.levels = data.levels.map((v) => { return new Uint16Array(v); }); } else { // all other - data.levels = data.levels.map(function (v) { + data.levels = data.levels.map((v) => { return new Uint8Array(v); }); } diff --git a/src/framework/handlers/binary.js b/src/framework/handlers/binary.js index 9031046e3c7..a4fdef24777 100644 --- a/src/framework/handlers/binary.js +++ b/src/framework/handlers/binary.js @@ -1,5 +1,5 @@ -import { http, Http } from '../../platform/net/http.js'; import { ResourceHandler } from './handler.js'; +import { http, Http } from '../../platform/net/http.js'; class BinaryHandler extends ResourceHandler { constructor(app) { @@ -18,7 +18,7 @@ class BinaryHandler extends ResourceHandler { responseType: Http.ResponseType.ARRAY_BUFFER, retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { callback(null, response); } else { diff --git a/src/framework/handlers/bundle.js b/src/framework/handlers/bundle.js index ebf1579cd52..dd9443b556a 100644 --- a/src/framework/handlers/bundle.js +++ b/src/framework/handlers/bundle.js @@ -1,7 +1,7 @@ -import { Bundle } from '../bundle/bundle.js'; -import { Debug } from '../../core/debug.js'; -import { Untar } from './untar.js'; import { ResourceHandler } from './handler.js'; +import { Untar } from './untar.js'; +import { Debug } from '../../core/debug.js'; +import { Bundle } from '../bundle/bundle.js'; /** * @import { AppBase } from '../app-base.js' diff --git a/src/framework/handlers/container.js b/src/framework/handlers/container.js index 88f1fecfd76..5a8e3852df2 100644 --- a/src/framework/handlers/container.js +++ b/src/framework/handlers/container.js @@ -1,6 +1,6 @@ +import { ResourceHandler } from './handler.js'; import { path } from '../../core/path.js'; import { GlbContainerParser } from '../parsers/glb-container-parser.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' diff --git a/src/framework/handlers/css.js b/src/framework/handlers/css.js index b555e3e7c47..959b4dca61d 100644 --- a/src/framework/handlers/css.js +++ b/src/framework/handlers/css.js @@ -1,5 +1,5 @@ -import { http } from '../../platform/net/http.js'; import { ResourceHandler } from './handler.js'; +import { http } from '../../platform/net/http.js'; class CssHandler extends ResourceHandler { /** @@ -25,7 +25,7 @@ class CssHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { callback(null, response); } else { diff --git a/src/framework/handlers/cubemap.js b/src/framework/handlers/cubemap.js index 971d4cd6b30..fc5896b4e95 100644 --- a/src/framework/handlers/cubemap.js +++ b/src/framework/handlers/cubemap.js @@ -1,10 +1,10 @@ +import { ResourceHandler } from './handler.js'; import { ADDRESS_CLAMP_TO_EDGE, PIXELFORMAT_RGB8, PIXELFORMAT_RGBA8, TEXTURETYPE_DEFAULT, TEXTURETYPE_RGBM } from '../../platform/graphics/constants.js'; import { Texture } from '../../platform/graphics/texture.js'; import { Asset } from '../asset/asset.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -41,11 +41,11 @@ class CubemapHandler extends ResourceHandler { } patch(asset, registry) { - this.loadAssets(asset, function (err, result) { + this.loadAssets(asset, (err, result) => { if (err) { // fire error event if patch failed registry.fire('error', asset); - registry.fire('error:' + asset.id, err, asset); + registry.fire(`error:${asset.id}`, err, asset); asset.fire('error', asset); } // nothing to do since asset:change would have been raised if @@ -115,7 +115,7 @@ class CubemapHandler extends ResourceHandler { if (tex.cubemap) { for (i = 0; i < 6; ++i) { resources[i + 1] = new Texture(this._device, { - name: cubemapAsset.name + '_prelitCubemap' + (tex.width >> i), + name: `${cubemapAsset.name}_prelitCubemap${tex.width >> i}`, cubemap: true, // assume prefiltered data has same encoding as the faces asset type: getType() || tex.type, @@ -149,12 +149,12 @@ class CubemapHandler extends ResourceHandler { // face assets have changed if (faceAssets.indexOf(null) === -1) { // extract cubemap level data from face textures - const faceTextures = faceAssets.map(function (asset) { + const faceTextures = faceAssets.map((asset) => { return asset.resource; }); const faceLevels = []; for (mip = 0; mip < faceTextures[0]._levels.length; ++mip) { - faceLevels.push(faceTextures.map(function (faceTexture) { // eslint-disable-line no-loop-func + faceLevels.push(faceTextures.map((faceTexture) => { // eslint-disable-line no-loop-func return faceTexture._levels[mip]; })); } @@ -165,7 +165,7 @@ class CubemapHandler extends ResourceHandler { const format = faceTextures[0].format; const faces = new Texture(this._device, { - name: cubemapAsset.name + '_faces', + name: `${cubemapAsset.name}_faces`, cubemap: true, type: getType() || faceTextures[0].type, width: faceTextures[0].width, @@ -271,8 +271,8 @@ class CubemapHandler extends ResourceHandler { onLoad(index, texAsset); } else { // asset is not loaded, register for load and error events - registry.once('load:' + texAsset.id, onLoad.bind(self, index)); - registry.once('error:' + texAsset.id, onError.bind(self, index)); + registry.once(`load:${texAsset.id}`, onLoad.bind(self, index)); + registry.once(`error:${texAsset.id}`, onError.bind(self, index)); if (!texAsset.loading) { // kick off load if it's not already registry.load(texAsset); @@ -300,14 +300,14 @@ class CubemapHandler extends ResourceHandler { // asynchronous step. this gives the caller (for example the scene loader) // a chance to add the dependent scene texture to registry before we attempt // to get the asset again. - setTimeout(function (index, assetId_) { + setTimeout(((index, assetId_) => { const texAsset = registry.get(assetId_); if (texAsset) { processTexAsset(index, texAsset); } else { - onError(index, 'failed to find dependent cubemap asset=' + assetId_); + onError(index, `failed to find dependent cubemap asset=${assetId_}`); } - }.bind(null, i, assetId)); + }).bind(null, i, assetId)); } } else { // assetId is a url or file object and we're responsible for creating it @@ -325,7 +325,7 @@ class CubemapHandler extends ResourceHandler { mipmaps: false } : null; - texAsset = new Asset(cubemapAsset.name + '_part_' + i, 'texture', file, data); + texAsset = new Asset(`${cubemapAsset.name}_part_${i}`, 'texture', file, data); registry.add(texAsset); processTexAsset(i, texAsset); } diff --git a/src/framework/handlers/font.js b/src/framework/handlers/font.js index e280ee301eb..3f59d5372f3 100644 --- a/src/framework/handlers/font.js +++ b/src/framework/handlers/font.js @@ -1,8 +1,8 @@ +import { ResourceHandler } from './handler.js'; import { path } from '../../core/path.js'; import { string } from '../../core/string.js'; import { http } from '../../platform/net/http.js'; import { Font } from '../font/font.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -17,7 +17,7 @@ function upgradeDataSchema(data) { height: data.info.height }]; } - data.chars = Object.keys(data.chars || {}).reduce(function (newChars, key) { + data.chars = Object.keys(data.chars || {}).reduce((newChars, key) => { const existing = data.chars[key]; // key by letter instead of char code const newKey = existing.letter !== undefined ? existing.letter : string.fromCodePoint(key); @@ -65,11 +65,11 @@ class FontHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { // update asset data if (!err) { const data = upgradeDataSchema(response); - self._loadTextures(url.load.replace('.json', '.png'), data, function (err, textures) { + self._loadTextures(url.load.replace('.json', '.png'), data, (err, textures) => { if (err) { callback(err); } else { @@ -122,12 +122,13 @@ class FontHandler extends ResourceHandler { if (index === 0) { loader.load(url, 'texture', onLoaded); } else { - loader.load(url.replace('.png', index + '.png'), 'texture', onLoaded); + loader.load(url.replace('.png', `${index}.png`), 'texture', onLoaded); } }; - for (let i = 0; i < numTextures; i++) + for (let i = 0; i < numTextures; i++) { loadTexture(i); + } } open(url, data, asset) { diff --git a/src/framework/handlers/gsplat.js b/src/framework/handlers/gsplat.js index dd34a15768f..b2ea0fd6fee 100644 --- a/src/framework/handlers/gsplat.js +++ b/src/framework/handlers/gsplat.js @@ -1,5 +1,5 @@ -import { PlyParser } from '../parsers/ply.js'; import { ResourceHandler } from './handler.js'; +import { PlyParser } from '../parsers/ply.js'; /** * @import { AppBase } from '../app-base.js' diff --git a/src/framework/handlers/hierarchy.js b/src/framework/handlers/hierarchy.js index e5c47c2ca83..054e8022a91 100644 --- a/src/framework/handlers/hierarchy.js +++ b/src/framework/handlers/hierarchy.js @@ -1,6 +1,6 @@ -import { SceneParser } from '../parsers/scene.js'; -import { SceneUtils } from './scene-utils.js'; import { ResourceHandler } from './handler.js'; +import { SceneUtils } from './scene-utils.js'; +import { SceneParser } from '../parsers/scene.js'; /** * @import { AppBase } from '../app-base.js' diff --git a/src/framework/handlers/html.js b/src/framework/handlers/html.js index e6b24653e53..b96b9c39bca 100644 --- a/src/framework/handlers/html.js +++ b/src/framework/handlers/html.js @@ -1,5 +1,5 @@ -import { http } from '../../platform/net/http.js'; import { ResourceHandler } from './handler.js'; +import { http } from '../../platform/net/http.js'; class HtmlHandler extends ResourceHandler { /** @@ -25,7 +25,7 @@ class HtmlHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { callback(null, response); } else { diff --git a/src/framework/handlers/json.js b/src/framework/handlers/json.js index 7b16ed16228..d794d6508a0 100644 --- a/src/framework/handlers/json.js +++ b/src/framework/handlers/json.js @@ -1,5 +1,5 @@ -import { http, Http } from '../../platform/net/http.js'; import { ResourceHandler } from './handler.js'; +import { http, Http } from '../../platform/net/http.js'; class JsonHandler extends ResourceHandler { /** @@ -32,7 +32,7 @@ class JsonHandler extends ResourceHandler { options.responseType = Http.ResponseType.JSON; } - http.get(url.load, options, function (err, response) { + http.get(url.load, options, (err, response) => { if (!err) { callback(null, response); } else { diff --git a/src/framework/handlers/loader.js b/src/framework/handlers/loader.js index 114e836761b..b31984931bb 100644 --- a/src/framework/handlers/loader.js +++ b/src/framework/handlers/loader.js @@ -151,8 +151,9 @@ class ResourceLoader { if (urlObj.load instanceof DataView) { if (handler.openBinary) { - if (!self._requests[key]) + if (!self._requests[key]) { return; + } try { const data = handler.openBinary(urlObj.load); @@ -165,13 +166,14 @@ class ResourceLoader { urlObj.load = URL.createObjectURL(new Blob([urlObj.load])); if (asset) { - if (asset.urlObject) + if (asset.urlObject) { URL.revokeObjectURL(asset.urlObject); + } asset.urlObject = urlObj.load; } } - handler.load(urlObj, function (err, data, extra) { + handler.load(urlObj, (err, data, extra) => { // make sure key exists because loader // might have been destroyed by now if (!self._requests[key]) { @@ -213,7 +215,7 @@ class ResourceLoader { if (bundle) this._app.assets?.load(bundle); } - this._app.bundles.loadUrl(normalizedUrl, function (err, fileUrlFromBundle) { + this._app.bundles.loadUrl(normalizedUrl, (err, fileUrlFromBundle) => { handleLoad(err, { load: fileUrlFromBundle, original: normalizedUrl @@ -277,7 +279,7 @@ class ResourceLoader { open(type, data) { const handler = this._handlers[type]; if (!handler) { - console.warn('No resource handler found for: ' + type); + console.warn(`No resource handler found for: ${type}`); return data; } @@ -295,7 +297,7 @@ class ResourceLoader { patch(asset, assets) { const handler = this._handlers[asset.type]; if (!handler) { - console.warn('No resource handler found for: ' + asset.type); + console.warn(`No resource handler found for: ${asset.type}`); return; } diff --git a/src/framework/handlers/material.js b/src/framework/handlers/material.js index 87745fd294b..19527cb53f2 100644 --- a/src/framework/handlers/material.js +++ b/src/framework/handlers/material.js @@ -1,10 +1,10 @@ -import { http } from '../../platform/net/http.js'; +import { ResourceHandler } from './handler.js'; import { PIXELFORMAT_RGBA8 } from '../../platform/graphics/constants.js'; import { Texture } from '../../platform/graphics/texture.js'; +import { http } from '../../platform/net/http.js'; import { standardMaterialCubemapParameters, standardMaterialTextureParameters } from '../../scene/materials/standard-material-parameters.js'; import { AssetReference } from '../asset/asset-reference.js'; import { JsonStandardMaterialParser } from '../parsers/material/json-standard-material.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -66,7 +66,7 @@ class MaterialHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { if (callback) { response._engine = true; @@ -105,8 +105,9 @@ class MaterialHandler extends ResourceHandler { }; for (const key in textures) { - if (!textures.hasOwnProperty(key)) + if (!textures.hasOwnProperty(key)) { continue; + } // create texture this._placeholderTextures[key] = new Texture(this._device, { diff --git a/src/framework/handlers/model.js b/src/framework/handlers/model.js index 93892ad1be4..4dc1044a1df 100644 --- a/src/framework/handlers/model.js +++ b/src/framework/handlers/model.js @@ -1,9 +1,9 @@ +import { ResourceHandler } from './handler.js'; import { path } from '../../core/path.js'; import { http, Http } from '../../platform/net/http.js'; import { getDefaultMaterial } from '../../scene/materials/default-material.js'; import { GlbModelParser } from '../parsers/glb-model.js'; import { JsonModelParser } from '../parsers/json-model.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -39,10 +39,10 @@ class ModelHandler extends ResourceHandler { this.assets = app.assets; this.defaultMaterial = getDefaultMaterial(this.device); - this.addParser(new JsonModelParser(this), function (url, data) { + this.addParser(new JsonModelParser(this), (url, data) => { return (path.getExtension(url) === '.json'); }); - this.addParser(new GlbModelParser(this), function (url, data) { + this.addParser(new GlbModelParser(this), (url, data) => { return (path.getExtension(url) === '.glb'); }); } @@ -70,8 +70,9 @@ class ModelHandler extends ResourceHandler { } http.get(url.load, options, (err, response) => { - if (!callback) + if (!callback) { return; + } if (!err) { // parse the model @@ -89,7 +90,7 @@ class ModelHandler extends ResourceHandler { return; } } - callback("No parsers found"); + callback('No parsers found'); } else { callback(`Error loading model: ${url.original} [${err}]`); } @@ -102,13 +103,14 @@ class ModelHandler extends ResourceHandler { } patch(asset, assets) { - if (!asset.resource) + if (!asset.resource) { return; + } const data = asset.data; const self = this; - asset.resource.meshInstances.forEach(function (meshInstance, i) { + asset.resource.meshInstances.forEach((meshInstance, i) => { if (data.mapping) { const handleMaterial = function (asset) { if (asset.resource) { @@ -118,7 +120,7 @@ class ModelHandler extends ResourceHandler { assets.load(asset); } - asset.once('remove', function (asset) { + asset.once('remove', (asset) => { if (meshInstance.material === asset.resource) { meshInstance.material = self.defaultMaterial; } @@ -142,7 +144,7 @@ class ModelHandler extends ResourceHandler { if (material) { handleMaterial(material); } else { - assets.once('add:' + id, handleMaterial); + assets.once(`add:${id}`, handleMaterial); } } } else if (url) { @@ -153,7 +155,7 @@ class ModelHandler extends ResourceHandler { if (material) { handleMaterial(material); } else { - assets.once('add:url:' + path, handleMaterial); + assets.once(`add:url:${path}`, handleMaterial); } } } diff --git a/src/framework/handlers/render.js b/src/framework/handlers/render.js index e8c87e81f72..86d17cc8d9d 100644 --- a/src/framework/handlers/render.js +++ b/src/framework/handlers/render.js @@ -1,5 +1,5 @@ -import { Render } from '../../scene/render.js'; import { ResourceHandler } from './handler.js'; +import { Render } from '../../scene/render.js'; /** * @import { AppBase } from '../app-base.js' @@ -22,10 +22,10 @@ function onContainerAssetLoaded(containerAsset) { function onContainerAssetAdded(containerAsset) { const renderAsset = this; - renderAsset.registry.off('load:' + containerAsset.id, onContainerAssetLoaded, renderAsset); - renderAsset.registry.on('load:' + containerAsset.id, onContainerAssetLoaded, renderAsset); - renderAsset.registry.off('remove:' + containerAsset.id, onContainerAssetRemoved, renderAsset); - renderAsset.registry.once('remove:' + containerAsset.id, onContainerAssetRemoved, renderAsset); + renderAsset.registry.off(`load:${containerAsset.id}`, onContainerAssetLoaded, renderAsset); + renderAsset.registry.on(`load:${containerAsset.id}`, onContainerAssetLoaded, renderAsset); + renderAsset.registry.off(`remove:${containerAsset.id}`, onContainerAssetRemoved, renderAsset); + renderAsset.registry.once(`remove:${containerAsset.id}`, onContainerAssetRemoved, renderAsset); if (!containerAsset.resource) { renderAsset.registry.load(containerAsset); @@ -37,7 +37,7 @@ function onContainerAssetAdded(containerAsset) { function onContainerAssetRemoved(containerAsset) { const renderAsset = this; - renderAsset.registry.off('load:' + containerAsset.id, onContainerAssetLoaded, renderAsset); + renderAsset.registry.off(`load:${containerAsset.id}`, onContainerAssetLoaded, renderAsset); if (renderAsset.resource) { renderAsset.resource.destroy(); @@ -67,12 +67,13 @@ class RenderHandler extends ResourceHandler { } patch(asset, registry) { - if (!asset.data.containerAsset) + if (!asset.data.containerAsset) { return; + } const containerAsset = registry.get(asset.data.containerAsset); if (!containerAsset) { - registry.once('add:' + asset.data.containerAsset, onContainerAssetAdded, asset); + registry.once(`add:${asset.data.containerAsset}`, onContainerAssetAdded, asset); return; } diff --git a/src/framework/handlers/scene-settings.js b/src/framework/handlers/scene-settings.js index 000b62a36ba..dd8f9cbc512 100644 --- a/src/framework/handlers/scene-settings.js +++ b/src/framework/handlers/scene-settings.js @@ -1,6 +1,6 @@ +import { ResourceHandler } from './handler.js'; import { SceneUtils } from './scene-utils.js'; -import { ResourceHandler } from './handler.js'; class SceneSettingsHandler extends ResourceHandler { constructor(app) { diff --git a/src/framework/handlers/scene-utils.js b/src/framework/handlers/scene-utils.js index 7a277590c48..e6d9ad2ef7d 100644 --- a/src/framework/handlers/scene-utils.js +++ b/src/framework/handlers/scene-utils.js @@ -19,18 +19,18 @@ class SceneUtils { http.get(url.load, { retry: maxRetries > 0, maxRetries: maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { callback(err, response); } else { - let errMsg = 'Error while loading scene JSON ' + url.original; + let errMsg = `Error while loading scene JSON ${url.original}`; if (err.message) { - errMsg += ': ' + err.message; + errMsg += `: ${err.message}`; if (err.stack) { - errMsg += '\n' + err.stack; + errMsg += `\n${err.stack}`; } } else { - errMsg += ': ' + err; + errMsg += `: ${err}`; } callback(errMsg); diff --git a/src/framework/handlers/scene.js b/src/framework/handlers/scene.js index 64dcd14ec6c..21eea409acc 100644 --- a/src/framework/handlers/scene.js +++ b/src/framework/handlers/scene.js @@ -1,6 +1,6 @@ +import { ResourceHandler } from './handler.js'; import { SceneUtils } from './scene-utils.js'; import { SceneParser } from '../parsers/scene.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' diff --git a/src/framework/handlers/script.js b/src/framework/handlers/script.js index 20e028f1310..8b12660696c 100644 --- a/src/framework/handlers/script.js +++ b/src/framework/handlers/script.js @@ -1,10 +1,10 @@ +import { ResourceHandler } from './handler.js'; +import { ResourceLoader } from './loader.js'; import { platform } from '../../core/platform.js'; -import { script } from '../script.js'; -import { ScriptTypes } from '../script/script-types.js'; import { registerScript } from '../script/script-create.js'; -import { ResourceLoader } from './loader.js'; -import { ResourceHandler } from './handler.js'; +import { ScriptTypes } from '../script/script-types.js'; import { Script } from '../script/script.js'; +import { script } from '../script.js'; /** * @import { AppBase } from '../app-base.js' @@ -37,8 +37,9 @@ class ScriptHandler extends ResourceHandler { for (const key in this._cache) { const element = this._cache[key]; const parent = element.parentNode; - if (parent) + if (parent) { parent.removeChild(element); + } } this._cache = {}; } @@ -59,8 +60,9 @@ class ScriptHandler extends ResourceHandler { if (!err) { const obj = { }; - for (let i = 0; i < ScriptTypes._types.length; i++) + for (let i = 0; i < ScriptTypes._types.length; i++) { obj[ScriptTypes._types[i].name] = ScriptTypes._types[i]; + } ScriptTypes._types.length = 0; @@ -110,7 +112,7 @@ class ScriptHandler extends ResourceHandler { // use async=false to force scripts to execute in order element.async = false; - element.addEventListener('error', function (e) { + element.addEventListener('error', (e) => { callback(`Script: ${e.target.src} failed to load`); }, false); diff --git a/src/framework/handlers/shader.js b/src/framework/handlers/shader.js index c5a8840548b..6338e03b479 100644 --- a/src/framework/handlers/shader.js +++ b/src/framework/handlers/shader.js @@ -1,5 +1,5 @@ -import { http } from '../../platform/net/http.js'; import { ResourceHandler } from './handler.js'; +import { http } from '../../platform/net/http.js'; class ShaderHandler extends ResourceHandler { /** @@ -25,7 +25,7 @@ class ShaderHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { callback(null, response); } else { diff --git a/src/framework/handlers/sprite.js b/src/framework/handlers/sprite.js index a05d0843c3f..50c70fc44ce 100644 --- a/src/framework/handlers/sprite.js +++ b/src/framework/handlers/sprite.js @@ -1,7 +1,7 @@ +import { ResourceHandler } from './handler.js'; import { path } from '../../core/path.js'; import { http } from '../../platform/net/http.js'; import { Sprite } from '../../scene/sprite.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -53,7 +53,7 @@ class SpriteHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { callback(null, response); } else { @@ -91,7 +91,7 @@ class SpriteHandler extends ResourceHandler { if (atlas) { asset.data.textureAtlasAsset = atlas.id; } else { - console.warn('Could not find textureatlas with url: ' + sprite.__data.textureAtlasAsset); + console.warn(`Could not find textureatlas with url: ${sprite.__data.textureAtlasAsset}`); } } @@ -118,16 +118,16 @@ class SpriteHandler extends ResourceHandler { return; } - this._assets.off('load:' + asset.data.textureAtlasAsset, onTextureAtlasLoaded, asset); - this._assets.on('load:' + asset.data.textureAtlasAsset, onTextureAtlasLoaded, asset); + this._assets.off(`load:${asset.data.textureAtlasAsset}`, onTextureAtlasLoaded, asset); + this._assets.on(`load:${asset.data.textureAtlasAsset}`, onTextureAtlasLoaded, asset); const atlasAsset = this._assets.get(asset.data.textureAtlasAsset); if (atlasAsset && atlasAsset.resource) { sprite.atlas = atlasAsset.resource; } else { if (!atlasAsset) { - this._assets.off('add:' + asset.data.textureAtlasAsset, onTextureAtlasAdded, asset); - this._assets.on('add:' + asset.data.textureAtlasAsset, onTextureAtlasAdded, asset); + this._assets.off(`add:${asset.data.textureAtlasAsset}`, onTextureAtlasAdded, asset); + this._assets.on(`add:${asset.data.textureAtlasAsset}`, onTextureAtlasAdded, asset); } else { this._assets.load(atlasAsset); } @@ -138,8 +138,8 @@ class SpriteHandler extends ResourceHandler { if (attribute === 'data') { // if the texture atlas changed, clear events for old atlas asset if (value && value.textureAtlasAsset && oldValue && value.textureAtlasAsset !== oldValue.textureAtlasAsset) { - this._assets.off('load:' + oldValue.textureAtlasAsset, onTextureAtlasLoaded, asset); - this._assets.off('add:' + oldValue.textureAtlasAsset, onTextureAtlasAdded, asset); + this._assets.off(`load:${oldValue.textureAtlasAsset}`, onTextureAtlasLoaded, asset); + this._assets.off(`add:${oldValue.textureAtlasAsset}`, onTextureAtlasAdded, asset); } } } diff --git a/src/framework/handlers/template.js b/src/framework/handlers/template.js index 4ec1fc005ee..7e52109c22e 100644 --- a/src/framework/handlers/template.js +++ b/src/framework/handlers/template.js @@ -1,6 +1,6 @@ +import { ResourceHandler } from './handler.js'; import { http } from '../../platform/net/http.js'; import { Template } from '../template.js'; -import { ResourceHandler } from './handler.js'; class TemplateHandler extends ResourceHandler { /** @@ -29,9 +29,9 @@ class TemplateHandler extends ResourceHandler { maxRetries: this.maxRetries }; - http.get(url.load, options, function (err, response) { + http.get(url.load, options, (err, response) => { if (err) { - callback('Error requesting template: ' + url.original); + callback(`Error requesting template: ${url.original}`); } else { callback(err, response); } diff --git a/src/framework/handlers/text.js b/src/framework/handlers/text.js index 0e2698a6c40..b869931bcb4 100644 --- a/src/framework/handlers/text.js +++ b/src/framework/handlers/text.js @@ -1,5 +1,5 @@ -import { http } from '../../platform/net/http.js'; import { ResourceHandler } from './handler.js'; +import { http } from '../../platform/net/http.js'; class TextHandler extends ResourceHandler { /** @@ -25,7 +25,7 @@ class TextHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { callback(null, response); } else { diff --git a/src/framework/handlers/texture-atlas.js b/src/framework/handlers/texture-atlas.js index 62cbb36bb4b..86fc4dee2eb 100644 --- a/src/framework/handlers/texture-atlas.js +++ b/src/framework/handlers/texture-atlas.js @@ -1,6 +1,7 @@ -import { path } from '../../core/path.js'; +import { ResourceHandler } from './handler.js'; import { Vec2 } from '../../core/math/vec2.js'; import { Vec4 } from '../../core/math/vec4.js'; +import { path } from '../../core/path.js'; import { ADDRESS_CLAMP_TO_EDGE, ADDRESS_MIRRORED_REPEAT, ADDRESS_REPEAT, FILTER_LINEAR, FILTER_NEAREST, FILTER_NEAREST_MIPMAP_NEAREST, FILTER_NEAREST_MIPMAP_LINEAR, FILTER_LINEAR_MIPMAP_NEAREST, FILTER_LINEAR_MIPMAP_LINEAR, @@ -8,7 +9,6 @@ import { } from '../../platform/graphics/constants.js'; import { http } from '../../platform/net/http.js'; import { TextureAtlas } from '../../scene/texture-atlas.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -67,11 +67,11 @@ class TextureAtlasHandler extends ResourceHandler { http.get(url.load, { retry: this.maxRetries > 0, maxRetries: this.maxRetries - }, function (err, response) { + }, (err, response) => { if (!err) { // load texture const textureUrl = url.original.replace('.json', '.png'); - self._loader.load(textureUrl, 'texture', function (err, texture) { + self._loader.load(textureUrl, 'texture', (err, texture) => { if (err) { callback(err); } else { @@ -131,23 +131,29 @@ class TextureAtlasHandler extends ResourceHandler { if (texture) { texture.name = asset.name; - if (asset.data.hasOwnProperty('minfilter') && texture.minFilter !== JSON_FILTER_MODE[asset.data.minfilter]) + if (asset.data.hasOwnProperty('minfilter') && texture.minFilter !== JSON_FILTER_MODE[asset.data.minfilter]) { texture.minFilter = JSON_FILTER_MODE[asset.data.minfilter]; + } - if (asset.data.hasOwnProperty('magfilter') && texture.magFilter !== JSON_FILTER_MODE[asset.data.magfilter]) + if (asset.data.hasOwnProperty('magfilter') && texture.magFilter !== JSON_FILTER_MODE[asset.data.magfilter]) { texture.magFilter = JSON_FILTER_MODE[asset.data.magfilter]; + } - if (asset.data.hasOwnProperty('addressu') && texture.addressU !== JSON_ADDRESS_MODE[asset.data.addressu]) + if (asset.data.hasOwnProperty('addressu') && texture.addressU !== JSON_ADDRESS_MODE[asset.data.addressu]) { texture.addressU = JSON_ADDRESS_MODE[asset.data.addressu]; + } - if (asset.data.hasOwnProperty('addressv') && texture.addressV !== JSON_ADDRESS_MODE[asset.data.addressv]) + if (asset.data.hasOwnProperty('addressv') && texture.addressV !== JSON_ADDRESS_MODE[asset.data.addressv]) { texture.addressV = JSON_ADDRESS_MODE[asset.data.addressv]; + } - if (asset.data.hasOwnProperty('mipmaps') && texture.mipmaps !== asset.data.mipmaps) + if (asset.data.hasOwnProperty('mipmaps') && texture.mipmaps !== asset.data.mipmaps) { texture.mipmaps = asset.data.mipmaps; + } - if (asset.data.hasOwnProperty('anisotropy') && texture.anisotropy !== asset.data.anisotropy) + if (asset.data.hasOwnProperty('anisotropy') && texture.anisotropy !== asset.data.anisotropy) { texture.anisotropy = asset.data.anisotropy; + } if (asset.data.hasOwnProperty('rgbm')) { const type = asset.data.rgbm ? TEXTURETYPE_RGBM : TEXTURETYPE_DEFAULT; diff --git a/src/framework/handlers/texture.js b/src/framework/handlers/texture.js index 38f940012d8..3a933cf2870 100644 --- a/src/framework/handlers/texture.js +++ b/src/framework/handlers/texture.js @@ -1,3 +1,4 @@ +import { ResourceHandler } from './handler.js'; import { path } from '../../core/path.js'; import { TEXHINT_ASSET, @@ -6,15 +7,14 @@ import { PIXELFORMAT_RGB8, PIXELFORMAT_RGBA8, PIXELFORMAT_RGBA32F, TEXTURETYPE_DEFAULT, TEXTURETYPE_RGBE, TEXTURETYPE_RGBM, TEXTURETYPE_SWIZZLEGGGR, TEXTURETYPE_RGBP } from '../../platform/graphics/constants.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { TextureUtils } from '../../platform/graphics/texture-utils.js'; +import { Texture } from '../../platform/graphics/texture.js'; import { BasisParser } from '../parsers/texture/basis.js'; +import { DdsParser } from '../parsers/texture/dds.js'; +import { HdrParser } from '../parsers/texture/hdr.js'; import { ImgParser } from '../parsers/texture/img.js'; import { KtxParser } from '../parsers/texture/ktx.js'; import { Ktx2Parser } from '../parsers/texture/ktx2.js'; -import { DdsParser } from '../parsers/texture/dds.js'; -import { HdrParser } from '../parsers/texture/hdr.js'; -import { ResourceHandler } from './handler.js'; /** * @import { AppBase } from '../app-base.js' @@ -250,8 +250,9 @@ class TextureHandler extends ResourceHandler { } open(url, data, asset) { - if (!url) + if (!url) { return undefined; + } const textureOptions = this._getTextureOptions(asset); let texture = this._getParser(url).open(url, data, this._device, textureOptions); diff --git a/src/framework/handlers/untar.js b/src/framework/handlers/untar.js index 040478bc68a..97467153663 100644 --- a/src/framework/handlers/untar.js +++ b/src/framework/handlers/untar.js @@ -182,8 +182,9 @@ class Untar extends EventHandler { // bytes padding const bytesRemained = this.bytesRead % this.paddingSize; - if (bytesRemained !== 0) + if (bytesRemained !== 0) { this.bytesRead += this.paddingSize - bytesRemained; + } return true; } diff --git a/src/framework/i18n/i18n.js b/src/framework/i18n/i18n.js index 942c62a7f43..c29481d4a7a 100644 --- a/src/framework/i18n/i18n.js +++ b/src/framework/i18n/i18n.js @@ -1,8 +1,8 @@ -import { EventHandler } from '../../core/event-handler.js'; -import { Asset } from '../asset/asset.js'; import { DEFAULT_LOCALE, DEFAULT_LOCALE_FALLBACKS } from './constants.js'; -import { findAvailableLocale, getLang, getPluralFn, replaceLang } from './utils.js'; import { I18nParser } from './i18n-parser.js'; +import { findAvailableLocale, getLang, getPluralFn, replaceLang } from './utils.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { Asset } from '../asset/asset.js'; /** * @import { AppBase } from '../app-base.js' @@ -51,7 +51,7 @@ class I18n extends EventHandler { while (i--) { const id = this._assets[i]; if (!index[id]) { - this._app.assets.off('add:' + id, this._onAssetAdd, this); + this._app.assets.off(`add:${id}`, this._onAssetAdd, this); const asset = this._app.assets.get(id); if (asset) { this._onAssetRemove(asset); @@ -68,7 +68,7 @@ class I18n extends EventHandler { this._assets.push(idNum); const asset = this._app.assets.get(idNum); if (!asset) { - this._app.assets.once('add:' + idNum, this._onAssetAdd, this); + this._app.assets.once(`add:${idNum}`, this._onAssetAdd, this); } else { this._onAssetAdd(asset); } @@ -429,7 +429,7 @@ class I18n extends EventHandler { this.removeData(asset.resource); } - this._app.assets.once('add:' + asset.id, this._onAssetAdd, this); + this._app.assets.once(`add:${asset.id}`, this._onAssetAdd, this); } _onAssetUnload(asset) { diff --git a/src/framework/i18n/utils.js b/src/framework/i18n/utils.js index e41451e1364..610e3c72dd5 100644 --- a/src/framework/i18n/utils.js +++ b/src/framework/i18n/utils.js @@ -69,7 +69,7 @@ definePluralFn([ 'vi', 'zh', 'id' -], function (n) { +], (n) => { return 0; }); @@ -77,7 +77,7 @@ definePluralFn([ definePluralFn([ 'fa', 'hi' -], function (n) { +], (n) => { if (n >= 0 && n <= 1) { return 0; // one } @@ -89,7 +89,7 @@ definePluralFn([ definePluralFn([ 'fr', 'pt' -], function (n) { +], (n) => { if (n >= 0 && n < 2) { return 0; // one } @@ -100,7 +100,7 @@ definePluralFn([ // danish definePluralFn([ 'da' -], function (n) { +], (n) => { if (n === 1 || !Number.isInteger(n) && n >= 0 && n <= 1) { return 0; // one } @@ -120,7 +120,7 @@ definePluralFn([ 'nb', 'no', 'ur' -], function (n) { +], (n) => { if (n === 1) { return 0; // one } @@ -132,7 +132,7 @@ definePluralFn([ definePluralFn([ 'ru', 'uk' -], function (n) { +], (n) => { if (Number.isInteger(n)) { const mod10 = n % 10; const mod100 = n % 100; @@ -152,7 +152,7 @@ definePluralFn([ // polish definePluralFn([ 'pl' -], function (n) { +], (n) => { if (Number.isInteger(n)) { if (n === 1) { return 0; // one @@ -173,7 +173,7 @@ definePluralFn([ // ZERO, ONE, TWO, FEW, MANY, OTHER definePluralFn([ 'ar' -], function (n) { +], (n) => { if (n === 0) { return 0; // zero } else if (n === 1) { diff --git a/src/framework/input/element-input.js b/src/framework/input/element-input.js index 4b4ceea3b23..ad0d119ff6b 100644 --- a/src/framework/input/element-input.js +++ b/src/framework/input/element-input.js @@ -1,6 +1,6 @@ -import { platform } from '../../core/platform.js'; import { Vec3 } from '../../core/math/vec3.js'; import { Vec4 } from '../../core/math/vec4.js'; +import { platform } from '../../core/platform.js'; import { Ray } from '../../core/shape/ray.js'; import { Mouse } from '../../platform/input/mouse.js'; import { getApplication } from '../globals.js'; @@ -71,12 +71,14 @@ function intersectLineQuad(p, q, corners) { if (v >= 0) { // Test intersection against triangle abc u = -_pb.dot(_m); - if (u < 0) + if (u < 0) { return -1; + } w = scalarTriple(_pq, _pb, _pa); - if (w < 0) + if (w < 0) { return -1; + } const denom = 1.0 / (u + v + w); @@ -88,12 +90,14 @@ function intersectLineQuad(p, q, corners) { // Test intersection against triangle dac _pd.sub2(corners[3], p); u = _pd.dot(_m); - if (u < 0) + if (u < 0) { return -1; + } w = scalarTriple(_pq, _pa, _pd); - if (w < 0) + if (w < 0) { return -1; + } v = -v; @@ -387,8 +391,9 @@ class ElementInput { this._useXr = !options || options.useXr !== false; this._selectEventsAttached = false; - if (platform.touch) + if (platform.touch) { this._clickedEntities = {}; + } this.attach(domElement); } @@ -445,8 +450,9 @@ class ElementInput { attachSelectEvents() { if (!this._selectEventsAttached && this._useXr && this.app && this.app.xr && this.app.xr.supported) { - if (!this._clickedEntities) + if (!this._clickedEntities) { this._clickedEntities = {}; + } this._selectEventsAttached = true; this.app.xr.on('start', this._onXrStart, this); @@ -496,8 +502,9 @@ class ElementInput { * ElementComponent. */ addElement(element) { - if (this._elements.indexOf(element) === -1) + if (this._elements.indexOf(element) === -1) { this._elements.push(element); + } } /** @@ -509,15 +516,17 @@ class ElementInput { */ removeElement(element) { const idx = this._elements.indexOf(element); - if (idx !== -1) + if (idx !== -1) { this._elements.splice(idx, 1); + } } _handleUp(event) { if (!this._enabled) return; - if (Mouse.isPointerLocked()) + if (Mouse.isPointerLocked()) { return; + } this._calcMouseCoords(event); @@ -527,8 +536,9 @@ class ElementInput { _handleDown(event) { if (!this._enabled) return; - if (Mouse.isPointerLocked()) + if (Mouse.isPointerLocked()) { return; + } this._calcMouseCoords(event); @@ -631,8 +641,9 @@ class ElementInput { for (let i = 0, len = event.changedTouches.length; i < len; i++) { const touch = event.changedTouches[i]; const touchInfo = this._touchedElements[touch.identifier]; - if (!touchInfo) + if (!touchInfo) { continue; + } const element = touchInfo.element; const camera = touchInfo.camera; @@ -713,8 +724,9 @@ class ElementInput { camera = cameras[i]; element = this._getTargetElementByCoords(camera, targetX, targetY); - if (element) + if (element) { break; + } } // currently hovered element is whatever's being pointed by mouse (which may be null) @@ -829,8 +841,9 @@ class ElementInput { camera = cameras[i]; element = this._getTargetElementByRay(rayC, camera); - if (element) + if (element) { break; + } } } @@ -882,15 +895,18 @@ class ElementInput { let element = evt.element; while (true) { element.fire(name, evt); - if (evt._stopPropagation) + if (evt._stopPropagation) { break; + } - if (!element.entity.parent) + if (!element.entity.parent) { break; + } element = element.entity.parent.element; - if (!element) + if (!element) { break; + } } } @@ -928,17 +944,22 @@ class ElementInput { const layerOrder = this.app.scene.layers.sortTransparentLayers(a.layers, b.layers); if (layerOrder !== 0) return layerOrder; - if (a.screen && !b.screen) + if (a.screen && !b.screen) { return -1; - if (!a.screen && b.screen) + } + if (!a.screen && b.screen) { return 1; - if (!a.screen && !b.screen) + } + if (!a.screen && !b.screen) { return 0; + } - if (a.screen.screen.screenSpace && !b.screen.screen.screenSpace) + if (a.screen.screen.screenSpace && !b.screen.screen.screenSpace) { return -1; - if (b.screen.screen.screenSpace && !a.screen.screen.screenSpace) + } + if (b.screen.screen.screenSpace && !a.screen.screen.screenSpace) { return 1; + } return b.drawOrder - a.drawOrder; } diff --git a/src/framework/lightmapper/bake-light-ambient.js b/src/framework/lightmapper/bake-light-ambient.js index 152e3f19e5f..675fe723308 100644 --- a/src/framework/lightmapper/bake-light-ambient.js +++ b/src/framework/lightmapper/bake-light-ambient.js @@ -1,9 +1,9 @@ -import { Vec3 } from '../../core/math/vec3.js'; -import { random } from '../../core/math/random.js'; +import { BakeLight } from './bake-light.js'; import { Color } from '../../core/math/color.js'; -import { Entity } from '../entity.js'; +import { random } from '../../core/math/random.js'; +import { Vec3 } from '../../core/math/vec3.js'; import { SHADOW_PCF3 } from '../../scene/constants.js'; -import { BakeLight } from './bake-light.js'; +import { Entity } from '../entity.js'; const _tempPoint = new Vec3(); diff --git a/src/framework/lightmapper/bake-light-simple.js b/src/framework/lightmapper/bake-light-simple.js index 327fe578718..567b1107cce 100644 --- a/src/framework/lightmapper/bake-light-simple.js +++ b/src/framework/lightmapper/bake-light-simple.js @@ -1,7 +1,7 @@ -import { Vec2 } from '../../core/math/vec2.js'; +import { BakeLight } from './bake-light.js'; import { random } from '../../core/math/random.js'; +import { Vec2 } from '../../core/math/vec2.js'; import { LIGHTTYPE_DIRECTIONAL } from '../../scene/constants.js'; -import { BakeLight } from './bake-light.js'; const _tempPoint = new Vec2(); diff --git a/src/framework/lightmapper/bake-light.js b/src/framework/lightmapper/bake-light.js index cbed399bf50..7ca7c6d0cdf 100644 --- a/src/framework/lightmapper/bake-light.js +++ b/src/framework/lightmapper/bake-light.js @@ -74,8 +74,9 @@ class BakeLight { if (light.shadowMap) { // return shadow map to the cache - if (light.shadowMap.cached) + if (light.shadowMap.cached) { shadowMapCache.add(light, light.shadowMap); + } light.shadowMap = null; } diff --git a/src/framework/lightmapper/lightmap-filters.js b/src/framework/lightmapper/lightmap-filters.js index d529bdad399..865b691f7d7 100644 --- a/src/framework/lightmapper/lightmap-filters.js +++ b/src/framework/lightmapper/lightmap-filters.js @@ -1,6 +1,6 @@ -import { createShaderFromCode } from '../../scene/shader-lib/utils.js'; -import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; import { shaderChunksLightmapper } from '../../scene/shader-lib/chunks/chunks-lightmapper.js'; +import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; +import { createShaderFromCode } from '../../scene/shader-lib/utils.js'; // size of the kernel - needs to match the constant in the shader const DENOISE_FILTER_SIZE = 15; diff --git a/src/framework/lightmapper/lightmapper.js b/src/framework/lightmapper/lightmapper.js index e63450e4f2a..a51384d7307 100644 --- a/src/framework/lightmapper/lightmapper.js +++ b/src/framework/lightmapper/lightmapper.js @@ -1,9 +1,15 @@ +import { BakeLightAmbient } from './bake-light-ambient.js'; +import { BakeLightSimple } from './bake-light-simple.js'; +import { BakeMeshNode } from './bake-mesh-node.js'; +import { LightmapFilters } from './lightmap-filters.js'; +import { RenderPassLightmapper } from './render-pass-lightmapper.js'; import { Debug } from '../../core/debug.js'; -import { now } from '../../core/time.js'; import { Color } from '../../core/math/color.js'; import { math } from '../../core/math/math.js'; import { Vec3 } from '../../core/math/vec3.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; +import { now } from '../../core/time.js'; +import { BlendState } from '../../platform/graphics/blend-state.js'; import { ADDRESS_CLAMP_TO_EDGE, CHUNKAPI_1_65, @@ -14,9 +20,10 @@ import { TEXTURETYPE_DEFAULT, TEXTURETYPE_RGBM } from '../../platform/graphics/constants.js'; import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { DepthState } from '../../platform/graphics/depth-state.js'; import { RenderTarget } from '../../platform/graphics/render-target.js'; -import { drawQuadWithShader } from '../../scene/graphics/quad-render-utils.js'; import { Texture } from '../../platform/graphics/texture.js'; +import { Camera } from '../../scene/camera.js'; import { BAKE_COLORDIR, FOG_NONE, GAMMA_NONE, TONEMAP_LINEAR, @@ -27,23 +34,16 @@ import { SHADOWUPDATE_REALTIME, SHADOWUPDATE_THISFRAME, SHADER_FORWARD } from '../../scene/constants.js'; -import { MeshInstance } from '../../scene/mesh-instance.js'; +import { GraphNode } from '../../scene/graph-node.js'; +import { LightmapCache } from '../../scene/graphics/lightmap-cache.js'; +import { drawQuadWithShader } from '../../scene/graphics/quad-render-utils.js'; import { LightingParams } from '../../scene/lighting/lighting-params.js'; import { WorldClusters } from '../../scene/lighting/world-clusters.js'; +import { StandardMaterial } from '../../scene/materials/standard-material.js'; +import { MeshInstance } from '../../scene/mesh-instance.js'; import { RenderingParams } from '../../scene/renderer/rendering-params.js'; -import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; import { shaderChunksLightmapper } from '../../scene/shader-lib/chunks/chunks-lightmapper.js'; -import { Camera } from '../../scene/camera.js'; -import { GraphNode } from '../../scene/graph-node.js'; -import { StandardMaterial } from '../../scene/materials/standard-material.js'; -import { BakeLightSimple } from './bake-light-simple.js'; -import { BakeLightAmbient } from './bake-light-ambient.js'; -import { BakeMeshNode } from './bake-mesh-node.js'; -import { LightmapCache } from '../../scene/graphics/lightmap-cache.js'; -import { LightmapFilters } from './lightmap-filters.js'; -import { BlendState } from '../../platform/graphics/blend-state.js'; -import { DepthState } from '../../platform/graphics/depth-state.js'; -import { RenderPassLightmapper } from './render-pass-lightmapper.js'; +import { shaderChunks } from '../../scene/shader-lib/chunks/chunks.js'; /** * @import { AssetRegistry } from '../asset/asset-registry.js' @@ -250,7 +250,7 @@ class Lightmapper { dDiffuseLight += vec3(${scene.ambientBakeOcclusionBrightness.toFixed(1)}); dDiffuseLight = saturate(dDiffuseLight); dDiffuseLight *= dAmbientLight; - ` + bakeLmEndChunk; + ${bakeLmEndChunk}`; } else { material.ambient = new Color(0, 0, 0); // don't bake ambient } @@ -258,7 +258,7 @@ class Lightmapper { material.chunks.endPS = bakeLmEndChunk; material.lightMap = this.blackTex; } else { - material.chunks.basePS = shaderChunks.basePS + '\nuniform sampler2D texture_dirLightMap;\nuniform float bakeDir;\n'; + material.chunks.basePS = `${shaderChunks.basePS}\nuniform sampler2D texture_dirLightMap;\nuniform float bakeDir;\n`; material.chunks.endPS = shaderChunksLightmapper.bakeDirLmEndPS; } @@ -625,7 +625,7 @@ class Lightmapper { // texture and render target for each pass, stored per node for (let pass = 0; pass < passCount; pass++) { - const tex = this.createTexture(size, ('lightmapper_lightmap_' + i)); + const tex = this.createTexture(size, (`lightmapper_lightmap_${i}`)); LightmapCache.incRef(tex); bakeNode.renderTargets[pass] = new RenderTarget({ colorBuffer: tex, @@ -635,7 +635,7 @@ class Lightmapper { // single temporary render target of each size if (!this.renderTargets.has(size)) { - const tex = this.createTexture(size, ('lightmapper_temp_lightmap_' + size)); + const tex = this.createTexture(size, (`lightmapper_temp_lightmap_${size}`)); LightmapCache.incRef(tex); this.renderTargets.set(size, new RenderTarget({ colorBuffer: tex, @@ -1107,8 +1107,8 @@ class Lightmapper { // some global per frame / per camera constants are not set up or similar, that // renderForward sets up. const renderPass = new RenderPassLightmapper(device, this.renderer, this.camera, - clusteredLightingEnabled ? this.worldClusters : null, - rcv, lightArray); + clusteredLightingEnabled ? this.worldClusters : null, + rcv, lightArray); renderPass.init(tempRT); renderPass.render(); renderPass.destroy(); diff --git a/src/framework/parsers/draco-decoder.js b/src/framework/parsers/draco-decoder.js index 92fd20b4833..f74adf1af96 100644 --- a/src/framework/parsers/draco-decoder.js +++ b/src/framework/parsers/draco-decoder.js @@ -1,6 +1,6 @@ -import { WasmModule } from "../../core/wasm-module.js"; -import { DracoWorker } from "./draco-worker.js"; -import { Debug } from "../../core/debug.js"; +import { DracoWorker } from './draco-worker.js'; +import { Debug } from '../../core/debug.js'; +import { WasmModule } from '../../core/wasm-module.js'; import { http } from '../../platform/net/http.js'; const downloadMaxRetries = 3; @@ -123,16 +123,16 @@ const downloadScript = (url) => { const compileModule = (url) => { const compileManual = () => { return fetch(url) - .then(result => result.arrayBuffer()) - .then(buffer => WebAssembly.compile(buffer)); + .then(result => result.arrayBuffer()) + .then(buffer => WebAssembly.compile(buffer)); }; const compileStreaming = () => { return WebAssembly.compileStreaming(fetch(url)) - .catch((err) => { - Debug.warn(`compileStreaming() failed for ${url} (${err}), falling back to arraybuffer download.`); - return compileManual(); - }); + .catch((err) => { + Debug.warn(`compileStreaming() failed for ${url} (${err}), falling back to arraybuffer download.`); + return compileManual(); + }); }; // download and compile wasm module @@ -179,30 +179,30 @@ const initializeWorkers = (config) => { // worker urls must be absolute Promise.all([downloadScript(config.jsUrl), compileModule(config.wasmUrl)]) - .then(([dracoSource, dracoModule]) => { - // build worker source - const code = [ - '/* draco */', - dracoSource, - '/* worker */', - `(\n${DracoWorker.toString()}\n)()\n\n` - ].join('\n'); - const blob = new Blob([code], { type: 'application/javascript' }); - const workerUrl = URL.createObjectURL(blob); - const numWorkers = Math.max(1, Math.min(16, config.numWorkers || defaultNumWorkers)); - - // create worker instances - const workers = []; - for (let i = 0; i < numWorkers; ++i) { - const worker = new Worker(workerUrl); - worker.postMessage({ - type: 'init', - module: dracoModule - }); - workers.push(worker); - } - jobQueue.init(workers); - }); + .then(([dracoSource, dracoModule]) => { + // build worker source + const code = [ + '/* draco */', + dracoSource, + '/* worker */', + `(\n${DracoWorker.toString()}\n)()\n\n` + ].join('\n'); + const blob = new Blob([code], { type: 'application/javascript' }); + const workerUrl = URL.createObjectURL(blob); + const numWorkers = Math.max(1, Math.min(16, config.numWorkers || defaultNumWorkers)); + + // create worker instances + const workers = []; + for (let i = 0; i < numWorkers; ++i) { + const worker = new Worker(workerUrl); + worker.postMessage({ + type: 'init', + module: dracoModule + }); + workers.push(worker); + } + jobQueue.init(workers); + }); return true; }; diff --git a/src/framework/parsers/draco-worker.js b/src/framework/parsers/draco-worker.js index 12c7867881d..8674cf744f3 100644 --- a/src/framework/parsers/draco-worker.js +++ b/src/framework/parsers/draco-worker.js @@ -202,7 +202,7 @@ function DracoWorker(jsUrl, wasmUrl) { if (!hasNormals && attribute.attribute_type() === POSITION_ATTRIBUTE) { // generate normals just after position const normals = generateNormals(wrap(src, attribute.data_type()), - shortIndices ? new Uint16Array(result.indices) : new Uint32Array(result.indices)); + shortIndices ? new Uint16Array(result.indices) : new Uint32Array(result.indices)); // pack normals for (let j = 0; j < mesh.num_points(); ++j) { @@ -245,15 +245,15 @@ function DracoWorker(jsUrl, wasmUrl) { self.DracoDecoderModule({ instantiateWasm: (imports, successCallback) => { WebAssembly.instantiate(data.module, imports) - .then(result => successCallback(result)) - .catch(reason => console.error('instantiate failed + ' + reason)); + .then(result => successCallback(result)) + .catch(reason => console.error(`instantiate failed + ${reason}`)); return {}; } }) - .then((instance) => { - draco = instance; - workQueue.forEach(data => decode(data)); - }); + .then((instance) => { + draco = instance; + workQueue.forEach(data => decode(data)); + }); break; case 'decodeMesh': if (draco) { diff --git a/src/framework/parsers/glb-container-parser.js b/src/framework/parsers/glb-container-parser.js index a735c237679..3c070be8b3c 100644 --- a/src/framework/parsers/glb-container-parser.js +++ b/src/framework/parsers/glb-container-parser.js @@ -1,7 +1,7 @@ +import { GlbContainerResource } from './glb-container-resource.js'; +import { GlbParser } from './glb-parser.js'; import { path } from '../../core/path.js'; import { Asset } from '../../framework/asset/asset.js'; -import { GlbParser } from "./glb-parser.js"; -import { GlbContainerResource } from './glb-container-resource.js'; class GlbContainerParser { constructor(device, assets, maxRetries) { diff --git a/src/framework/parsers/glb-container-resource.js b/src/framework/parsers/glb-container-resource.js index c5d6daf89d5..95e8be9a065 100644 --- a/src/framework/parsers/glb-container-resource.js +++ b/src/framework/parsers/glb-container-resource.js @@ -1,16 +1,14 @@ import { Debug } from '../../core/debug.js'; - +import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; +import { VertexFormat } from '../../platform/graphics/vertex-format.js'; import { GraphNode } from '../../scene/graph-node.js'; import { MeshInstance } from '../../scene/mesh-instance.js'; import { Model } from '../../scene/model.js'; import { MorphInstance } from '../../scene/morph-instance.js'; -import { SkinInstance } from '../../scene/skin-instance.js'; import { SkinInstanceCache } from '../../scene/skin-instance-cache.js'; - -import { Entity } from '../entity.js'; +import { SkinInstance } from '../../scene/skin-instance.js'; import { Asset } from '../asset/asset.js'; -import { VertexFormat } from '../../platform/graphics/vertex-format.js'; -import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; +import { Entity } from '../entity.js'; // Container resource returned by the GlbParser. Implements the ContainerResource interface. class GlbContainerResource { @@ -62,7 +60,7 @@ class GlbContainerResource { } static createAsset(assetName, type, resource, index) { - const subAsset = new Asset(assetName + '/' + type + '/' + index, type, { + const subAsset = new Asset(`${assetName}/${type}/${index}`, type, { url: '' }); subAsset.resource = resource; @@ -224,7 +222,7 @@ class GlbContainerResource { Debug.warn(`No variant named ${name} exists in resource`); return; } - const renders = entity.findComponents("render"); + const renders = entity.findComponents('render'); for (let i = 0; i < renders.length; i++) { const renderComponent = renders[i]; this._applyMaterialVariant(variant, renderComponent.meshInstances); @@ -344,7 +342,7 @@ class GlbContainerResource { }; const destroyAssets = function (assets) { - assets.forEach(function (asset) { + assets.forEach((asset) => { destroyAsset(asset); }); }; diff --git a/src/framework/parsers/glb-parser.js b/src/framework/parsers/glb-parser.js index 231f61ac118..c221c4d547b 100644 --- a/src/framework/parsers/glb-parser.js +++ b/src/framework/parsers/glb-parser.js @@ -1,12 +1,13 @@ +import { dracoDecode } from './draco-decoder.js'; import { Debug } from '../../core/debug.js'; -import { path } from '../../core/path.js'; import { Color } from '../../core/math/color.js'; import { Mat4 } from '../../core/math/mat4.js'; import { math } from '../../core/math/math.js'; +import { Quat } from '../../core/math/quat.js'; import { Vec2 } from '../../core/math/vec2.js'; import { Vec3 } from '../../core/math/vec3.js'; +import { path } from '../../core/path.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; - import { typedArrayTypes, typedArrayTypesByteSize, ADDRESS_CLAMP_TO_EDGE, ADDRESS_MIRRORED_REPEAT, ADDRESS_REPEAT, @@ -24,32 +25,27 @@ import { Texture } from '../../platform/graphics/texture.js'; import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; import { VertexFormat } from '../../platform/graphics/vertex-format.js'; import { http } from '../../platform/net/http.js'; - import { BLEND_NONE, BLEND_NORMAL, LIGHTFALLOFF_INVERSESQUARED, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, ASPECT_MANUAL, ASPECT_AUTO, SPECOCC_AO } from '../../scene/constants.js'; +import { calculateNormals } from '../../scene/geometry/geometry-utils.js'; import { GraphNode } from '../../scene/graph-node.js'; import { Light, lightTypes } from '../../scene/light.js'; +import { StandardMaterial } from '../../scene/materials/standard-material.js'; import { Mesh } from '../../scene/mesh.js'; -import { Morph } from '../../scene/morph.js'; import { MorphTarget } from '../../scene/morph-target.js'; -import { calculateNormals } from '../../scene/geometry/geometry-utils.js'; +import { Morph } from '../../scene/morph.js'; import { Render } from '../../scene/render.js'; import { Skin } from '../../scene/skin.js'; -import { StandardMaterial } from '../../scene/materials/standard-material.js'; - -import { Entity } from '../entity.js'; import { INTERPOLATION_CUBIC, INTERPOLATION_LINEAR, INTERPOLATION_STEP } from '../anim/constants.js'; import { AnimCurve } from '../anim/evaluator/anim-curve.js'; import { AnimData } from '../anim/evaluator/anim-data.js'; import { AnimTrack } from '../anim/evaluator/anim-track.js'; import { Asset } from '../asset/asset.js'; import { ABSOLUTE_URL } from '../asset/constants.js'; - -import { dracoDecode } from './draco-decoder.js'; -import { Quat } from '../../core/math/quat.js'; +import { Entity } from '../entity.js'; // resources loaded from GLB file that the parser returns class GlbResources { @@ -92,7 +88,7 @@ class GlbResources { } const isDataURI = (uri) => { - return /^data:.*,.*$/i.test(uri); + return /^data:[^\n\r,\u2028\u2029]*,.*$/i.test(uri); }; const getDataURIMimeType = (uri) => { @@ -260,7 +256,7 @@ const getAccessorData = (gltfAccessor, bufferViews, flatten = false) => { } } } else { - if (gltfAccessor.hasOwnProperty("bufferView")) { + if (gltfAccessor.hasOwnProperty('bufferView')) { const bufferView = bufferViews[gltfAccessor.bufferView]; if (flatten && bufferView.hasOwnProperty('byteStride')) { // flatten stridden data @@ -280,8 +276,8 @@ const getAccessorData = (gltfAccessor, bufferViews, flatten = false) => { result = new dataType(storage); } else { result = new dataType(bufferView.buffer, - bufferView.byteOffset + (gltfAccessor.byteOffset || 0), - gltfAccessor.count * numComponents); + bufferView.byteOffset + (gltfAccessor.byteOffset || 0), + gltfAccessor.count * numComponents); } } else { result = new dataType(gltfAccessor.count * numComponents); @@ -424,11 +420,11 @@ const cloneTexture = (texture) => { // given a texture asset, clone it const cloneTextureAsset = (src) => { - const result = new Asset(src.name + '_clone', - src.type, - src.file, - src.data, - src.options); + const result = new Asset(`${src.name}_clone`, + src.type, + src.file, + src.data, + src.options); result.loaded = true; result.resource = cloneTexture(src.resource); src.registry.add(result); @@ -499,8 +495,8 @@ const createVertexBufferInternal = (device, sourceDesc) => { if (isCorrectlyInterleaved) { // copy data sourceArray = new Uint32Array(positionDesc.buffer, - positionDesc.offset, - numVertices * vertexBuffer.format.size / 4); + positionDesc.offset, + numVertices * vertexBuffer.format.size / 4); targetArray.set(sourceArray); } else { let targetStride, sourceStride; @@ -544,7 +540,7 @@ const createVertexBuffer = (device, attributes, indices, accessors, bufferViews, useAttributes[attrib] = attributes[attrib]; // build unique id for each attribute in format: Semantic:accessorIndex - attribIds.push(attrib + ':' + attributes[attrib]); + attribIds.push(`${attrib}:${attributes[attrib]}`); } } @@ -774,7 +770,7 @@ const createMesh = (device, gltfMesh, accessors, bufferViews, vertexBufferDict, mesh.primitive[0].count = vertexBuffer.numVertices; } - if (primitive.hasOwnProperty("extensions") && primitive.extensions.hasOwnProperty("KHR_materials_variants")) { + if (primitive.hasOwnProperty('extensions') && primitive.extensions.hasOwnProperty('KHR_materials_variants')) { const variants = primitive.extensions.KHR_materials_variants; const tempMapping = {}; variants.mappings.forEach((mapping) => { @@ -843,7 +839,7 @@ const extractTextureTransform = (source, material, maps) => { const texCoord = source.texCoord; if (texCoord) { for (map = 0; map < maps.length; ++map) { - material[maps[map] + 'MapUv'] = texCoord; + material[`${maps[map]}MapUv`] = texCoord; } } @@ -1241,17 +1237,17 @@ const createMaterial = (gltfMaterial, textures) => { // Provide list of supported extensions and their functions const extensions = { - "KHR_materials_clearcoat": extensionClearCoat, - "KHR_materials_emissive_strength": extensionEmissiveStrength, - "KHR_materials_ior": extensionIor, - "KHR_materials_dispersion": extensionDispersion, - "KHR_materials_iridescence": extensionIridescence, - "KHR_materials_pbrSpecularGlossiness": extensionPbrSpecGlossiness, - "KHR_materials_sheen": extensionSheen, - "KHR_materials_specular": extensionSpecular, - "KHR_materials_transmission": extensionTransmission, - "KHR_materials_unlit": extensionUnlit, - "KHR_materials_volume": extensionVolume + 'KHR_materials_clearcoat': extensionClearCoat, + 'KHR_materials_emissive_strength': extensionEmissiveStrength, + 'KHR_materials_ior': extensionIor, + 'KHR_materials_dispersion': extensionDispersion, + 'KHR_materials_iridescence': extensionIridescence, + 'KHR_materials_pbrSpecularGlossiness': extensionPbrSpecGlossiness, + 'KHR_materials_sheen': extensionSheen, + 'KHR_materials_specular': extensionSpecular, + 'KHR_materials_transmission': extensionTransmission, + 'KHR_materials_unlit': extensionUnlit, + 'KHR_materials_volume': extensionVolume }; // Handle extensions @@ -1497,7 +1493,7 @@ const createAnimation = (gltfAnimation, animationIndex, gltfAccessors, bufferVie } return new AnimTrack( - gltfAnimation.hasOwnProperty('name') ? gltfAnimation.name : ('animation_' + animationIndex), + gltfAnimation.hasOwnProperty('name') ? gltfAnimation.name : (`animation_${animationIndex}`), duration, inputs, outputs, @@ -1513,7 +1509,7 @@ const createNode = (gltfNode, nodeIndex, nodeInstancingMap) => { if (gltfNode.hasOwnProperty('name') && gltfNode.name.length > 0) { entity.name = gltfNode.name; } else { - entity.name = 'node_' + nodeIndex; + entity.name = `node_${nodeIndex}`; } // Parse transformation properties @@ -1614,7 +1610,7 @@ const createLight = (gltfLight, node) => { // glTF stores light already in energy/area, but we need to provide the light with only the energy parameter, // so we need the intensities in candela back to lumen - if (gltfLight.hasOwnProperty("intensity")) { + if (gltfLight.hasOwnProperty('intensity')) { lightProps.luminance = gltfLight.intensity * Light.getLightUnitConversion(lightTypes[lightProps.type], lightProps.outerConeAngle, lightProps.innerConeAngle); } @@ -1683,8 +1679,9 @@ const createMaterials = (gltf, textures, options) => { }; const createVariants = (gltf) => { - if (!gltf.hasOwnProperty("extensions") || !gltf.extensions.hasOwnProperty("KHR_materials_variants")) + if (!gltf.hasOwnProperty('extensions') || !gltf.extensions.hasOwnProperty('KHR_materials_variants')) { return null; + } const data = gltf.extensions.KHR_materials_variants.variants; const variants = {}; @@ -1767,8 +1764,9 @@ const createInstancing = (device, gltf, nodeInstancingMap, bufferViews) => { matrix.setTRS(pos, rot, scl); // copy matrix elements into array of floats - for (let m = 0; m < 16; m++) + for (let m = 0; m < 16; m++) { matrices[matrixIndex++] = matrix.data[m]; + } } data.matrices = matrices; @@ -1954,7 +1952,7 @@ const createResources = async (device, gltf, bufferViews, textures, options) => // Instead of bloating the engine forevermore with code to handle this case, // we now issue a warning and prompt user to reconvert their FBX. if (gltf.asset && gltf.asset.generator === 'PlayCanvas') { - Debug.warn(`glTF model may have been generated with flipped UVs. Please reconvert.`); + Debug.warn('glTF model may have been generated with flipped UVs. Please reconvert.'); } const nodeInstancingMap = new Map(); @@ -2091,7 +2089,7 @@ const createImages = (gltf, bufferViews, urlBase, registry, options) => { const loadTexture = (gltfImage, url, bufferView, mimeType, options, srgb) => { return new Promise((resolve, reject) => { const continuation = (bufferViewData) => { - const name = (gltfImage.name || 'gltf-texture') + '-' + gltfTextureUniqueId++; + const name = `${gltfImage.name || 'gltf-texture'}-${gltfTextureUniqueId++}`; // construct the asset file const file = { @@ -2103,7 +2101,7 @@ const createImages = (gltf, bufferViews, urlBase, registry, options) => { if (mimeType) { const extension = mimeTypeFileExtensions[mimeType]; if (extension) { - file.filename = file.url + '.' + extension; + file.filename = `${file.url}.${extension}`; } } @@ -2137,10 +2135,11 @@ const createImages = (gltf, bufferViews, urlBase, registry, options) => { if (processAsync) { promise = new Promise((resolve, reject) => { processAsync(gltfImage, (err, textureAsset) => { - if (err) + if (err) { reject(err); - else + } else { resolve(textureAsset); + } }); }); } else { @@ -2205,10 +2204,11 @@ const createTextures = (gltf, images, options) => { if (processAsync) { promise = new Promise((resolve, reject) => { processAsync(gltfTexture, gltf.images, (err, gltfImageIndex) => { - if (err) + if (err) { reject(err); - else + } else { resolve(gltfImageIndex); + } }); }); } else { @@ -2265,10 +2265,11 @@ const loadBuffers = (gltf, binaryChunk, urlBase, options) => { if (processAsync) { promise = new Promise((resolve, reject) => { processAsync(gltfBuffer, (err, arrayBuffer) => { - if (err) + if (err) { reject(err); - else + } else { resolve(arrayBuffer); + } }); }); } else { @@ -2302,10 +2303,11 @@ const loadBuffers = (gltf, binaryChunk, urlBase, options) => { ABSOLUTE_URL.test(gltfBuffer.uri) ? gltfBuffer.uri : path.join(urlBase, gltfBuffer.uri), { cache: true, responseType: 'arraybuffer', retry: false }, (err, result) => { // eslint-disable-line no-loop-func - if (err) + if (err) { reject(err); - else + } else { resolve(new Uint8Array(result)); + } } ); }); @@ -2363,17 +2365,17 @@ const parseGlb = (glbData, callback) => { const length = data.getUint32(8, true); if (magic !== 0x46546C67) { - callback('Invalid magic number found in glb header. Expected 0x46546C67, found 0x' + magic.toString(16)); + callback(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${magic.toString(16)}`); return; } if (version !== 2) { - callback('Invalid version number found in glb header. Expected 2, found ' + version); + callback(`Invalid version number found in glb header. Expected 2, found ${version}`); return; } if (length <= 0 || length > data.byteLength) { - callback('Invalid length found in glb header. Found ' + length); + callback(`Invalid length found in glb header. Found ${length}`); return; } @@ -2456,10 +2458,11 @@ const createBufferViews = (gltf, buffers, options) => { if (processAsync) { promise = new Promise((resolve, reject) => { processAsync(gltfBufferView, buffers, (err, result) => { - if (err) + if (err) { reject(err); - else + } else { resolve(result); + } }); }); } else { @@ -2476,8 +2479,8 @@ const createBufferViews = (gltf, buffers, options) => { // convert buffer to typed array return buffers[gltfBufferView.buffer].then((buffer) => { return new Uint8Array(buffer.buffer, - buffer.byteOffset + (gltfBufferView.byteOffset || 0), - gltfBufferView.byteLength); + buffer.byteOffset + (gltfBufferView.byteOffset || 0), + gltfBufferView.byteLength); }); }); @@ -2525,8 +2528,8 @@ class GlbParser { const textures = createTextures(gltf, images, options); createResources(device, gltf, bufferViews, textures, options) - .then(result => callback(null, result)) - .catch(err => callback(err)); + .then(result => callback(null, result)) + .catch(err => callback(err)); }); }); } diff --git a/src/framework/parsers/gsplat-resource.js b/src/framework/parsers/gsplat-resource.js index 5aa37192e1f..c71d6dc2131 100644 --- a/src/framework/parsers/gsplat-resource.js +++ b/src/framework/parsers/gsplat-resource.js @@ -1,7 +1,7 @@ -import { Entity } from '../entity.js'; +import { GSplatCompressed } from '../../scene/gsplat/gsplat-compressed.js'; import { GSplatInstance } from '../../scene/gsplat/gsplat-instance.js'; import { GSplat } from '../../scene/gsplat/gsplat.js'; -import { GSplatCompressed } from '../../scene/gsplat/gsplat-compressed.js'; +import { Entity } from '../entity.js'; /** * @import { GSplatData } from '../../scene/gsplat/gsplat-data.js' diff --git a/src/framework/parsers/json-model.js b/src/framework/parsers/json-model.js index 1ab019e4bdd..2df5c05c0e1 100644 --- a/src/framework/parsers/json-model.js +++ b/src/framework/parsers/json-model.js @@ -1,8 +1,6 @@ import { Mat4 } from '../../core/math/mat4.js'; import { Vec3 } from '../../core/math/vec3.js'; - import { BoundingBox } from '../../core/shape/bounding-box.js'; - import { INDEXFORMAT_UINT16, INDEXFORMAT_UINT32, PRIMITIVE_LINELOOP, PRIMITIVE_LINESTRIP, PRIMITIVE_LINES, PRIMITIVE_POINTS, PRIMITIVE_TRIANGLES, PRIMITIVE_TRIFAN, PRIMITIVE_TRISTRIP, @@ -14,16 +12,15 @@ import { IndexBuffer } from '../../platform/graphics/index-buffer.js'; import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; import { VertexFormat } from '../../platform/graphics/vertex-format.js'; import { VertexIterator } from '../../platform/graphics/vertex-iterator.js'; - import { GraphNode } from '../../scene/graph-node.js'; -import { Mesh } from '../../scene/mesh.js'; import { MeshInstance } from '../../scene/mesh-instance.js'; +import { Mesh } from '../../scene/mesh.js'; import { Model } from '../../scene/model.js'; -import { Morph } from '../../scene/morph.js'; import { MorphInstance } from '../../scene/morph-instance.js'; import { MorphTarget } from '../../scene/morph-target.js'; -import { Skin } from '../../scene/skin.js'; +import { Morph } from '../../scene/morph.js'; import { SkinInstance } from '../../scene/skin-instance.js'; +import { Skin } from '../../scene/skin.js'; const JSON_PRIMITIVE_TYPE = { 'points': PRIMITIVE_POINTS, diff --git a/src/framework/parsers/material/json-standard-material.js b/src/framework/parsers/material/json-standard-material.js index bdbbd2203bb..2b14a4d3f54 100644 --- a/src/framework/parsers/material/json-standard-material.js +++ b/src/framework/parsers/material/json-standard-material.js @@ -1,14 +1,11 @@ import { Color } from '../../../core/math/color.js'; import { Vec2 } from '../../../core/math/vec2.js'; import { Vec3 } from '../../../core/math/vec3.js'; - -import { Texture } from '../../../platform/graphics/texture.js'; - import { BoundingBox } from '../../../core/shape/bounding-box.js'; - -import { StandardMaterial } from '../../../scene/materials/standard-material.js'; -import { StandardMaterialValidator } from '../../../scene/materials/standard-material-validator.js'; +import { Texture } from '../../../platform/graphics/texture.js'; import { standardMaterialParameterTypes } from '../../../scene/materials/standard-material-parameters.js'; +import { StandardMaterialValidator } from '../../../scene/materials/standard-material-validator.js'; +import { StandardMaterial } from '../../../scene/materials/standard-material.js'; /** * Convert incoming JSON data into a {@link StandardMaterial}. diff --git a/src/framework/parsers/ply.js b/src/framework/parsers/ply.js index 862ae04d944..7d544026768 100644 --- a/src/framework/parsers/ply.js +++ b/src/framework/parsers/ply.js @@ -1,7 +1,7 @@ -import { GSplatData } from '../../scene/gsplat/gsplat-data.js'; -import { GSplatCompressedData } from '../../scene/gsplat/gsplat-compressed-data.js'; import { GSplatResource } from './gsplat-resource.js'; import { Mat4 } from '../../core/math/mat4.js'; +import { GSplatCompressedData } from '../../scene/gsplat/gsplat-compressed-data.js'; +import { GSplatData } from '../../scene/gsplat/gsplat-data.js'; /** * @import { AssetRegistry } from '../asset/asset-registry.js' @@ -379,9 +379,9 @@ const readPly = async (reader, propertyFilter = null) => { // decode buffer header text and split into lines and remove comments const lines = new TextDecoder('ascii') - .decode(streamBuf.data.subarray(0, headerLength)) - .split('\n') - .filter(line => !line.startsWith('comment ')); + .decode(streamBuf.data.subarray(0, headerLength)) + .split('\n') + .filter(line => !line.startsWith('comment ')); // decode header and build element and property list const { elements, format } = parseHeader(lines); @@ -508,35 +508,35 @@ class PlyParser { async load(url, callback, asset) { const response = await fetch(url.load); if (!response || !response.body) { - callback("Error loading resource", null); + callback('Error loading resource', null); } else { readPly(response.body.getReader(), asset.data.elementFilter ?? defaultElementFilter) - .then((gsplatData) => { - if (!gsplatData.isCompressed) { - - // perform Z scale - if (asset.data.performZScale ?? true) { - mat4.setScale(-1, -1, 1); - gsplatData.transform(mat4); - } + .then((gsplatData) => { + if (!gsplatData.isCompressed) { - // reorder data - if (asset.data.reorder ?? true) { - gsplatData.reorderData(); - } + // perform Z scale + if (asset.data.performZScale ?? true) { + mat4.setScale(-1, -1, 1); + gsplatData.transform(mat4); } - // construct the resource - const resource = new GSplatResource( - this.device, - gsplatData.isCompressed && asset.data.decompress ? gsplatData.decompress() : gsplatData - ); + // reorder data + if (asset.data.reorder ?? true) { + gsplatData.reorderData(); + } + } - callback(null, resource); - }) - .catch((err) => { - callback(err, null); - }); + // construct the resource + const resource = new GSplatResource( + this.device, + gsplatData.isCompressed && asset.data.decompress ? gsplatData.decompress() : gsplatData + ); + + callback(null, resource); + }) + .catch((err) => { + callback(err, null); + }); } } diff --git a/src/framework/parsers/scene.js b/src/framework/parsers/scene.js index aee875bc0c8..e0385d70946 100644 --- a/src/framework/parsers/scene.js +++ b/src/framework/parsers/scene.js @@ -1,8 +1,8 @@ -import { Entity } from '../entity.js'; - +import { Debug } from '../../core/debug.js'; import { CompressUtils } from '../../scene/compress/compress-utils.js'; import { Decompress } from '../../scene/compress/decompress.js'; -import { Debug } from "../../core/debug.js"; +import { Entity } from '../entity.js'; + class SceneParser { constructor(app, isTemplate) { diff --git a/src/framework/parsers/texture/basis.js b/src/framework/parsers/texture/basis.js index 1c5e0861a99..2755e646b2e 100644 --- a/src/framework/parsers/texture/basis.js +++ b/src/framework/parsers/texture/basis.js @@ -1,10 +1,9 @@ +import { TextureParser } from './texture.js'; import { ADDRESS_CLAMP_TO_EDGE, ADDRESS_REPEAT, TEXHINT_ASSET, pixelFormatLinearToGamma } from '../../../platform/graphics/constants.js'; import { Texture } from '../../../platform/graphics/texture.js'; - import { Asset } from '../../asset/asset.js'; import { basisTranscode } from '../../handlers/basis.js'; -import { TextureParser } from './texture.js'; /** * Parser for basis files. diff --git a/src/framework/parsers/texture/dds.js b/src/framework/parsers/texture/dds.js index d79b0b8d677..902a61a4d8a 100644 --- a/src/framework/parsers/texture/dds.js +++ b/src/framework/parsers/texture/dds.js @@ -1,5 +1,5 @@ +import { TextureParser } from './texture.js'; import { Debug } from '../../../core/debug.js'; - import { ADDRESS_CLAMP_TO_EDGE, ADDRESS_REPEAT, PIXELFORMAT_DXT1, PIXELFORMAT_DXT5, @@ -10,10 +10,8 @@ import { TEXHINT_ASSET } from '../../../platform/graphics/constants.js'; import { Texture } from '../../../platform/graphics/texture.js'; - import { Asset } from '../../asset/asset.js'; -import { TextureParser } from './texture.js'; /** * Legacy texture parser for dds files. diff --git a/src/framework/parsers/texture/hdr.js b/src/framework/parsers/texture/hdr.js index 293595f56aa..946e58f3bb6 100644 --- a/src/framework/parsers/texture/hdr.js +++ b/src/framework/parsers/texture/hdr.js @@ -1,6 +1,6 @@ +import { TextureParser } from './texture.js'; import { Debug } from '../../../core/debug.js'; import { ReadStream } from '../../../core/read-stream.js'; - import { TEXHINT_ASSET, ADDRESS_REPEAT, ADDRESS_CLAMP_TO_EDGE, @@ -9,10 +9,8 @@ import { TEXTURETYPE_RGBE } from '../../../platform/graphics/constants.js'; import { Texture } from '../../../platform/graphics/texture.js'; - import { Asset } from '../../asset/asset.js'; -import { TextureParser } from './texture.js'; /** * Texture parser for hdr files. diff --git a/src/framework/parsers/texture/img-alpha-test.js b/src/framework/parsers/texture/img-alpha-test.js index 16b405ad6f1..ef3aac39899 100644 --- a/src/framework/parsers/texture/img-alpha-test.js +++ b/src/framework/parsers/texture/img-alpha-test.js @@ -54,10 +54,10 @@ const testImageBitmapAlpha = (device) => { premultiplyAlpha: 'none', colorSpaceConversion: 'none' }) - .then((image) => { - return testAlpha(device, image); - }) - .catch(e => false); + .then((image) => { + return testAlpha(device, image); + }) + .catch(e => false); }; // Test whether image element correctly loads PNG alpha data. diff --git a/src/framework/parsers/texture/img.js b/src/framework/parsers/texture/img.js index 1ae7912c972..8f2bc75589c 100644 --- a/src/framework/parsers/texture/img.js +++ b/src/framework/parsers/texture/img.js @@ -1,16 +1,15 @@ +import { ImgAlphaTest } from './img-alpha-test.js'; +import { TextureParser } from './texture.js'; +import { Tracing } from '../../../core/tracing.js'; import { PIXELFORMAT_RGBA8, PIXELFORMAT_SRGBA8, TEXHINT_ASSET } from '../../../platform/graphics/constants.js'; import { Texture } from '../../../platform/graphics/texture.js'; import { http } from '../../../platform/net/http.js'; - import { ABSOLUTE_URL } from '../../asset/constants.js'; // #if _DEBUG -import { ImgAlphaTest } from './img-alpha-test.js'; -import { Tracing } from '../../../core/tracing.js'; // #endif -import { TextureParser } from './texture.js'; /** * Parser for browser-supported image formats. @@ -110,10 +109,10 @@ class ImgParser extends TextureParser { const idx = url.indexOf('?'); const separator = idx >= 0 ? '&' : '?'; - retryTimeout = setTimeout(function () { + retryTimeout = setTimeout(() => { // we need to add a cache busting argument if we are trying to re-load an image element // with the same URL - image.src = url + separator + 'retry=' + Date.now(); + image.src = `${url + separator}retry=${Date.now()}`; retryTimeout = null; }, retryDelay); } else { @@ -146,8 +145,8 @@ class ImgParser extends TextureParser { premultiplyAlpha: 'none', colorSpaceConversion: 'none' }) - .then(imageBitmap => callback(null, imageBitmap)) - .catch(e => callback(e)); + .then(imageBitmap => callback(null, imageBitmap)) + .catch(e => callback(e)); } } diff --git a/src/framework/parsers/texture/ktx.js b/src/framework/parsers/texture/ktx.js index 44f4957de04..4b8a5c2a0b1 100644 --- a/src/framework/parsers/texture/ktx.js +++ b/src/framework/parsers/texture/ktx.js @@ -1,5 +1,5 @@ +import { TextureParser } from './texture.js'; import { Debug } from '../../../core/debug.js'; - import { ADDRESS_CLAMP_TO_EDGE, ADDRESS_REPEAT, PIXELFORMAT_DXT1, PIXELFORMAT_DXT3, PIXELFORMAT_DXT5, @@ -11,10 +11,8 @@ import { pixelFormatLinearToGamma } from '../../../platform/graphics/constants.js'; import { Texture } from '../../../platform/graphics/texture.js'; - import { Asset } from '../../asset/asset.js'; -import { TextureParser } from './texture.js'; // Defined here: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ const IDENTIFIER = [0x58544BAB, 0xBB313120, 0x0A1A0A0D]; // «KTX 11»\r\n\x1A\n @@ -134,7 +132,7 @@ class KtxParser extends TextureParser { // only support subset of pixel formats if (format === undefined) { - Debug.warn('Unknown glInternalFormat: ' + header.glInternalFormat); + Debug.warn(`Unknown glInternalFormat: ${header.glInternalFormat}`); return null; } diff --git a/src/framework/parsers/texture/ktx2.js b/src/framework/parsers/texture/ktx2.js index 3d06d95d588..1bda4f7ab32 100644 --- a/src/framework/parsers/texture/ktx2.js +++ b/src/framework/parsers/texture/ktx2.js @@ -1,13 +1,11 @@ +import { TextureParser } from './texture.js'; import { Debug } from '../../../core/debug.js'; import { ReadStream } from '../../../core/read-stream.js'; - import { ADDRESS_CLAMP_TO_EDGE, ADDRESS_REPEAT, TEXHINT_ASSET, pixelFormatLinearToGamma } from '../../../platform/graphics/constants.js'; import { Texture } from '../../../platform/graphics/texture.js'; - import { Asset } from '../../asset/asset.js'; import { basisTranscode } from '../../handlers/basis.js'; -import { TextureParser } from './texture.js'; const KHRConstants = { KHR_DF_MODEL_ETC1S: 163, @@ -128,7 +126,7 @@ class Ktx2Parser extends TextureParser { ); if (!basisModuleFound) { - callback('Basis module not found. Asset "' + asset.name + '" basis texture variant will not be loaded.'); + callback(`Basis module not found. Asset "${asset.name}" basis texture variant will not be loaded.`); } } else { // TODO: load non-supercompressed formats diff --git a/src/framework/scene-registry.js b/src/framework/scene-registry.js index 23a5acc2d3d..c5f579f2142 100644 --- a/src/framework/scene-registry.js +++ b/src/framework/scene-registry.js @@ -1,7 +1,7 @@ -import { path } from '../core/path.js'; -import { Debug } from '../core/debug.js'; import { ABSOLUTE_URL } from './asset/constants.js'; import { SceneRegistryItem } from './scene-registry-item.js'; +import { Debug } from '../core/debug.js'; +import { path } from '../core/path.js'; /** * @import { AppBase } from './app-base.js' @@ -104,7 +104,7 @@ class SceneRegistry { */ add(name, url) { if (this._index.hasOwnProperty(name)) { - Debug.warn('pc.SceneRegistry: trying to add more than one scene called: ' + name); + Debug.warn(`pc.SceneRegistry: trying to add more than one scene called: ${name}`); return false; } @@ -201,7 +201,7 @@ class SceneRegistry { url = sceneItem.url; if (!url) { - callback("Cannot find scene to load"); + callback('Cannot find scene to load'); return; } @@ -221,7 +221,7 @@ class SceneRegistry { if (!sceneItem._loading) { // Because we need to load scripts before we instance the hierarchy (i.e. before we // create script components), split loading into load and open - const handler = app.loader.getHandler("hierarchy"); + const handler = app.loader.getHandler('hierarchy'); handler.load(url, (err, data) => { sceneItem.data = data; @@ -303,7 +303,7 @@ class SceneRegistry { const _loaded = () => { // Because we need to load scripts before we instance the hierarchy (i.e. before we create script components) // Split loading into load and open - const handler = app.loader.getHandler("hierarchy"); + const handler = app.loader.getHandler('hierarchy'); app.systems.script.preloading = true; const entity = handler.open(sceneItem.url, sceneItem.data); @@ -311,7 +311,7 @@ class SceneRegistry { app.systems.script.preloading = false; // clear from cache because this data is modified by entity operations (e.g. destroy) - app.loader.clearCache(sceneItem.url, "hierarchy"); + app.loader.clearCache(sceneItem.url, 'hierarchy'); // add to hierarchy app.root.addChild(entity); @@ -427,7 +427,7 @@ class SceneRegistry { loadScene(url, callback) { const app = this._app; - const handler = app.loader.getHandler("scene"); + const handler = app.loader.getHandler('scene'); // include asset prefix if present if (app.assets && app.assets.prefix && !ABSOLUTE_URL.test(url)) { @@ -451,11 +451,11 @@ class SceneRegistry { // clear scene from cache because we'll destroy it when we load another one // so data will be invalid - app.loader.clearCache(url, "scene"); + app.loader.clearCache(url, 'scene'); app.loader.patch({ resource: scene, - type: "scene" + type: 'scene' }, app.assets); app.root.addChild(scene.root); diff --git a/src/framework/script.js b/src/framework/script.js index a3dbee6ec59..8310678da73 100644 --- a/src/framework/script.js +++ b/src/framework/script.js @@ -54,8 +54,9 @@ const script = { * }); */ createLoadingScreen(callback) { - if (_createdLoadingScreen) + if (_createdLoadingScreen) { return; + } _createdLoadingScreen = true; diff --git a/src/framework/script/script-attributes.js b/src/framework/script/script-attributes.js index 45967d84c1e..50c2a2982d7 100644 --- a/src/framework/script/script-attributes.js +++ b/src/framework/script/script-attributes.js @@ -1,7 +1,7 @@ import { Debug } from '../../core/debug.js'; import { Color } from '../../core/math/color.js'; -import { Curve } from '../../core/math/curve.js'; import { CurveSet } from '../../core/math/curve-set.js'; +import { Curve } from '../../core/math/curve.js'; import { Vec2 } from '../../core/math/vec2.js'; import { Vec3 } from '../../core/math/vec3.js'; import { Vec4 } from '../../core/math/vec4.js'; @@ -89,8 +89,9 @@ function rawToValue(app, args, value, old) { return value.clone(); } else if (value instanceof Array && value.length >= 3 && value.length <= 4) { for (let i = 0; i < value.length; i++) { - if (typeof value[i] !== 'number') + if (typeof value[i] !== 'number') { return null; + } } if (!old) old = new Color(); @@ -100,9 +101,10 @@ function rawToValue(app, args, value, old) { old.a = (value.length === 3) ? 1 : value[3]; return old; - } else if (typeof value === 'string' && /#([0-9abcdef]{2}){3,4}/i.test(value)) { - if (!old) + } else if (typeof value === 'string' && /#(?:[0-9a-f]{2}){3,4}/i.test(value)) { + if (!old) { old = new Color(); + } old.fromString(value); return old; @@ -122,13 +124,15 @@ function rawToValue(app, args, value, old) { return value.clone(); } else if (value instanceof Array && value.length === len) { for (let i = 0; i < value.length; i++) { - if (typeof value[i] !== 'number') + if (typeof value[i] !== 'number') { return null; + } } if (!old) old = new vecType(); - for (let i = 0; i < len; i++) + for (let i = 0; i < len; i++) { old[components[i]] = value[i]; + } return old; } @@ -335,7 +339,7 @@ class ScriptAttributes { }, set: function (raw) { const evt = 'attr'; - const evtName = 'attr:' + name; + const evtName = `attr:${name}`; const old = this.__attributes[name]; // keep copy of old for the event below @@ -378,8 +382,9 @@ class ScriptAttributes { * PlayerController.attributes.remove('fullName'); */ remove(name) { - if (!this.index[name]) + if (!this.index[name]) { return false; + } delete this.index[name]; delete this.scriptType.prototype[name]; diff --git a/src/framework/script/script-create.js b/src/framework/script/script-create.js index 2a1c04fbf4b..18c488f6880 100644 --- a/src/framework/script/script-create.js +++ b/src/framework/script/script-create.js @@ -1,9 +1,9 @@ -import { EventHandler } from '../../core/event-handler.js'; -import { AppBase } from '../app-base.js'; import { ScriptAttributes } from './script-attributes.js'; import { ScriptType } from './script-type.js'; import { ScriptTypes } from './script-types.js'; import { Script } from './script.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { AppBase } from '../app-base.js'; const reservedScriptNames = new Set([ 'system', 'entity', 'create', 'destroy', 'swap', 'move', 'data', @@ -54,8 +54,9 @@ function getReservedScriptNames() { * @category Script */ function createScript(name, app) { - if (reservedScriptNames.has(name)) + if (reservedScriptNames.has(name)) { throw new Error(`Script name '${name}' is reserved, please rename the script`); + } const scriptType = function (args) { EventHandler.prototype.initEventHandler.call(this); @@ -119,16 +120,19 @@ createScript.reservedAttributes = reservedAttributes; * @category Script */ function registerScript(script, name, app) { - if (typeof script !== 'function') + if (typeof script !== 'function') { throw new Error(`script class: '${script}' must be a constructor function (i.e. class).`); + } - if (!(script.prototype instanceof Script)) + if (!(script.prototype instanceof Script)) { throw new Error(`script class: '${ScriptType.__getScriptName(script)}' does not extend pc.Script.`); + } name = name || script.__name || ScriptType.__getScriptName(script); - if (reservedScriptNames.has(name)) + if (reservedScriptNames.has(name)) { throw new Error(`script name: '${name}' is reserved, please change script name`); + } script.__name = name; diff --git a/src/framework/script/script-registry.js b/src/framework/script/script-registry.js index 2279953d696..99dae68301d 100644 --- a/src/framework/script/script-registry.js +++ b/src/framework/script/script-registry.js @@ -98,7 +98,7 @@ class ScriptRegistry extends EventHandler { this._scripts[scriptName] = script; this.fire('swap', scriptName, script); - this.fire('swap:' + scriptName, script); + this.fire(`swap:${scriptName}`, script); } else { console.warn(`script registry already has '${scriptName}' script, define 'swap' method for new script type to enable code hot swapping`); } @@ -110,13 +110,14 @@ class ScriptRegistry extends EventHandler { this._list.push(script); this.fire('add', scriptName, script); - this.fire('add:' + scriptName, script); + this.fire(`add:${scriptName}`, script); // for all components awaiting Script Type // create script instance setTimeout(() => { - if (!this._scripts.hasOwnProperty(scriptName)) + if (!this._scripts.hasOwnProperty(scriptName)) { return; + } // this is a check for a possible error // that might happen if the app has been destroyed before @@ -134,8 +135,9 @@ class ScriptRegistry extends EventHandler { const component = components.items[components.loopIndex]; // check if awaiting for script if (component._scriptsIndex[scriptName] && component._scriptsIndex[scriptName].awaiting) { - if (component._scriptsData && component._scriptsData[scriptName]) + if (component._scriptsData && component._scriptsData[scriptName]) { attributes = component._scriptsData[scriptName].attributes; + } const scriptInstance = component.create(scriptName, { preloading: true, @@ -143,8 +145,9 @@ class ScriptRegistry extends EventHandler { attributes: attributes }); - if (scriptInstance) + if (scriptInstance) { scriptInstances.push(scriptInstance); + } // initialize attributes for (const script of component.scripts) { @@ -160,8 +163,9 @@ class ScriptRegistry extends EventHandler { scriptInstancesInitialized.push(scriptInstances[i]); - if (scriptInstances[i].initialize) + if (scriptInstances[i].initialize) { scriptInstances[i].initialize(); + } } } @@ -173,8 +177,9 @@ class ScriptRegistry extends EventHandler { scriptInstancesInitialized[i]._postInitialized = true; - if (scriptInstancesInitialized[i].postInitialize) + if (scriptInstancesInitialized[i].postInitialize) { scriptInstancesInitialized[i].postInitialize(); + } } }); @@ -200,15 +205,16 @@ class ScriptRegistry extends EventHandler { scriptType = this.get(scriptName); } - if (this.get(scriptName) !== scriptType) + if (this.get(scriptName) !== scriptType) { return false; + } delete this._scripts[scriptName]; const ind = this._list.indexOf(scriptType); this._list.splice(ind, 1); this.fire('remove', scriptName, scriptType); - this.fire('remove:' + scriptName, scriptType); + this.fire(`remove:${scriptName}`, scriptType); return true; } diff --git a/src/framework/script/script-type.js b/src/framework/script/script-type.js index 19b93f924b5..891e4afabe5 100644 --- a/src/framework/script/script-type.js +++ b/src/framework/script/script-type.js @@ -58,8 +58,9 @@ class ScriptType extends Script { * @param {boolean} [force] - Set to true to force initialization of the attributes. */ __initializeAttributes(force) { - if (!force && !this.__attributesRaw) + if (!force && !this.__attributesRaw) { return; + } // set attributes values for (const key in this.__scriptType.attributes.index) { @@ -95,8 +96,9 @@ class ScriptType extends Script { */ static extend(methods) { for (const key in methods) { - if (!methods.hasOwnProperty(key)) + if (!methods.hasOwnProperty(key)) { continue; + } this.prototype[key] = methods[key]; } diff --git a/src/framework/script/script.js b/src/framework/script/script.js index 3e7bdb45502..24a6816bf1b 100644 --- a/src/framework/script/script.js +++ b/src/framework/script/script.js @@ -1,6 +1,6 @@ +import { SCRIPT_INITIALIZE, SCRIPT_POST_INITIALIZE } from './constants.js'; import { Debug } from '../..//core/debug.js'; import { EventHandler } from '../../core/event-handler.js'; -import { SCRIPT_INITIALIZE, SCRIPT_POST_INITIALIZE } from './constants.js'; /** * @import { AppBase } from '../app-base.js' @@ -229,8 +229,9 @@ export class Script extends EventHandler { this.fire('preInitialize'); - if (this.initialize) + if (this.initialize) { this.entity.script._scriptMethod(this, SCRIPT_INITIALIZE); + } } // post initialize script if not post initialized yet and still enabled @@ -241,8 +242,9 @@ export class Script extends EventHandler { if (this._initialized && !this._postInitialized && this.enabled && !this.entity.script._beingEnabled) { this._postInitialized = true; - if (this.postInitialize) + if (this.postInitialize) { this.entity.script._scriptMethod(this, SCRIPT_POST_INITIALIZE); + } } } @@ -336,7 +338,8 @@ export class Script extends EventHandler { */ } -const funcNameRegex = new RegExp('^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^\\(\\s\\/]*)\\s*'); +// eslint-disable-next-line regexp/no-super-linear-backtracking +const funcNameRegex = /^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s/]*)\s*/; /** * @param {Function} constructorFn - The constructor function of the script type. @@ -346,6 +349,6 @@ export function getScriptName(constructorFn) { if (typeof constructorFn !== 'function') return undefined; if ('name' in Function.prototype) return constructorFn.name; if (constructorFn === Function || constructorFn === Function.prototype.constructor) return 'Function'; - const match = ('' + constructorFn).match(funcNameRegex); + const match = (`${constructorFn}`).match(funcNameRegex); return match ? match[1] : undefined; } diff --git a/src/framework/utils/entity-reference.js b/src/framework/utils/entity-reference.js index 523dda80a30..2b3533ce026 100644 --- a/src/framework/utils/entity-reference.js +++ b/src/framework/utils/entity-reference.js @@ -1,7 +1,7 @@ +import { EventHandler } from '../../core/event-handler.js'; import { Component } from '../components/component.js'; import { Entity } from '../entity.js'; -import { EventHandler } from '../../core/event-handler.js'; /** * An EntityReference can be used in scenarios where a component has one or more properties that @@ -155,7 +155,7 @@ class EntityReference extends EventHandler { } _parseEventListenerConfig(eventConfig, prefix, scope) { - return Object.keys(eventConfig).map(function (listenerDescription, index) { + return Object.keys(eventConfig).map((listenerDescription, index) => { const listenerDescriptionParts = listenerDescription.split('#'); const sourceName = listenerDescriptionParts[0]; const eventName = listenerDescriptionParts[1]; @@ -164,15 +164,15 @@ class EntityReference extends EventHandler { if (listenerDescriptionParts.length !== 2 || typeof sourceName !== 'string' || sourceName.length === 0 || typeof eventName !== 'string' || eventName.length === 0) { - throw new Error('Invalid event listener description: `' + listenerDescription + '`'); + throw new Error(`Invalid event listener description: \`${listenerDescription}\``); } if (typeof callback !== 'function') { - throw new Error('Invalid or missing callback for event listener `' + listenerDescription + '`'); + throw new Error(`Invalid or missing callback for event listener \`${listenerDescription}\``); } return { - id: prefix + '_' + index + '_' + listenerDescription, + id: `${prefix}_${index}_${listenerDescription}`, sourceName: sourceName, eventName: eventName, callback: callback, @@ -182,7 +182,7 @@ class EntityReference extends EventHandler { } _toggleLifecycleListeners(onOrOff) { - this._parentComponent[onOrOff]('set_' + this._entityPropertyName, this._onSetEntity, this); + this._parentComponent[onOrOff](`set_${this._entityPropertyName}`, this._onSetEntity, this); this._parentComponent.system[onOrOff]('beforeremove', this._onParentComponentRemove, this); this._app.systems[onOrOff]('postPostInitialize', this._updateEntityReference, this); @@ -222,7 +222,7 @@ class EntityReference extends EventHandler { this._updateEntityReference(); } else { if (newValue !== null && newValue !== undefined && typeof newValue !== 'string') { - console.warn("Entity field `" + this._entityPropertyName + "` was set to unexpected type '" + (typeof newValue) + "'"); + console.warn(`Entity field \`${this._entityPropertyName}\` was set to unexpected type '${typeof newValue}'`); return; } @@ -378,7 +378,7 @@ class EntityReference extends EventHandler { } if (!isDestroying) { - console.warn('Entity has no component with name ' + sourceName); + console.warn(`Entity has no component with name ${sourceName}`); } return null; diff --git a/src/framework/xr/xr-anchor.js b/src/framework/xr/xr-anchor.js index 1322a0577b3..23769d59a04 100644 --- a/src/framework/xr/xr-anchor.js +++ b/src/framework/xr/xr-anchor.js @@ -1,6 +1,6 @@ import { EventHandler } from '../../core/event-handler.js'; -import { Vec3 } from '../../core/math/vec3.js'; import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; /** * @import { XrAnchors } from './xr-anchors.js' @@ -134,13 +134,15 @@ class XrAnchor extends EventHandler { * @ignore */ update(frame) { - if (!this._xrAnchor) + if (!this._xrAnchor) { return; + } const pose = frame.getPose(this._xrAnchor.anchorSpace, this._anchors.manager._referenceSpace); if (pose) { - if (this._position.equals(pose.transform.position) && this._rotation.equals(pose.transform.orientation)) + if (this._position.equals(pose.transform.position) && this._rotation.equals(pose.transform.orientation)) { return; + } this._position.copy(pose.transform.position); this._rotation.copy(pose.transform.orientation); @@ -203,23 +205,23 @@ class XrAnchor extends EventHandler { this._uuidRequests = []; this._xrAnchor.requestPersistentHandle() - .then((uuid) => { - this._uuid = uuid; - this._anchors._indexByUuid.set(this._uuid, this); - callback?.(null, uuid); - for (const uuidRequest of this._uuidRequests) { - uuidRequest(null, uuid); - } - this._uuidRequests = null; - this.fire('persist', uuid); - }) - .catch((ex) => { - callback?.(ex, null); - for (const uuidRequest of this._uuidRequests) { - uuidRequest(ex, null); - } - this._uuidRequests = null; - }); + .then((uuid) => { + this._uuid = uuid; + this._anchors._indexByUuid.set(this._uuid, this); + callback?.(null, uuid); + for (const uuidRequest of this._uuidRequests) { + uuidRequest(null, uuid); + } + this._uuidRequests = null; + this.fire('persist', uuid); + }) + .catch((ex) => { + callback?.(ex, null); + for (const uuidRequest of this._uuidRequests) { + uuidRequest(ex, null); + } + this._uuidRequests = null; + }); } /** diff --git a/src/framework/xr/xr-anchors.js b/src/framework/xr/xr-anchors.js index 8b89ad010ac..4409e52d975 100644 --- a/src/framework/xr/xr-anchors.js +++ b/src/framework/xr/xr-anchors.js @@ -1,6 +1,6 @@ +import { XrAnchor } from './xr-anchor.js'; import { EventHandler } from '../../core/event-handler.js'; import { platform } from '../../core/platform.js'; -import { XrAnchor } from './xr-anchor.js'; /** * @import { Quat } from '../../core/math/quat.js' @@ -191,8 +191,9 @@ class XrAnchors extends EventHandler { // clear anchor creation queue for (let i = 0; i < this._creationQueue.length; i++) { - if (!this._creationQueue[i].callback) + if (!this._creationQueue[i].callback) { continue; + } this._creationQueue[i].callback(new Error('session ended'), null); } @@ -286,15 +287,15 @@ class XrAnchors extends EventHandler { } hitResult.createAnchor() - .then((xrAnchor) => { - const anchor = this._createAnchor(xrAnchor); - callback?.(null, anchor); - this.fire('add', anchor); - }) - .catch((ex) => { - callback?.(ex, null); - this.fire('error', ex); - }); + .then((xrAnchor) => { + const anchor = this._createAnchor(xrAnchor); + callback?.(null, anchor); + this.fire('add', anchor); + }) + .catch((ex) => { + callback?.(ex, null); + this.fire('error', ex); + }); } else { this._creationQueue.push({ transform: new XRRigidTransform(position, rotation), @@ -340,15 +341,15 @@ class XrAnchors extends EventHandler { } this.manager.session.restorePersistentAnchor(uuid) - .then((xrAnchor) => { - const anchor = this._createAnchor(xrAnchor, uuid); - callback?.(null, anchor); - this.fire('add', anchor); - }) - .catch((ex) => { - callback?.(ex, null); - this.fire('error', ex); - }); + .then((xrAnchor) => { + const anchor = this._createAnchor(xrAnchor, uuid); + callback?.(null, anchor); + this.fire('add', anchor); + }) + .catch((ex) => { + callback?.(ex, null); + this.fire('error', ex); + }); } /** @@ -381,13 +382,13 @@ class XrAnchors extends EventHandler { } this.manager.session.deletePersistentAnchor(uuid) - .then(() => { - callback?.(null); - }) - .catch((ex) => { - callback?.(ex); - this.fire('error', ex); - }); + .then(() => { + callback?.(null); + }) + .catch((ex) => { + callback?.(ex); + this.fire('error', ex); + }); } /** @@ -401,15 +402,15 @@ class XrAnchors extends EventHandler { this._checkingAvailability = true; frame.createAnchor(new XRRigidTransform(), this.manager._referenceSpace) - .then((xrAnchor) => { - // successfully created an anchor - feature is available - xrAnchor.delete(); - if (this.manager.active) { - this._available = true; - this.fire('available'); - } - }) - .catch(() => { }); // stay unavailable + .then((xrAnchor) => { + // successfully created an anchor - feature is available + xrAnchor.delete(); + if (this.manager.active) { + this._available = true; + this.fire('available'); + } + }) + .catch(() => { }); // stay unavailable } return; } @@ -420,16 +421,18 @@ class XrAnchors extends EventHandler { const request = this._creationQueue[i]; frame.createAnchor(request.transform, this.manager._referenceSpace) - .then((xrAnchor) => { - if (request.callback) - this._callbacksAnchors.set(xrAnchor, request.callback); - }) - .catch((ex) => { - if (request.callback) - request.callback(ex, null); - - this.fire('error', ex); - }); + .then((xrAnchor) => { + if (request.callback) { + this._callbacksAnchors.set(xrAnchor, request.callback); + } + }) + .catch((ex) => { + if (request.callback) { + request.callback(ex, null); + } + + this.fire('error', ex); + }); } this._creationQueue.length = 0; @@ -437,8 +440,9 @@ class XrAnchors extends EventHandler { // check if destroyed for (const [xrAnchor, anchor] of this._index) { - if (frame.trackedAnchors.has(xrAnchor)) + if (frame.trackedAnchors.has(xrAnchor)) { continue; + } this._index.delete(xrAnchor); anchor.destroy(); @@ -451,8 +455,9 @@ class XrAnchors extends EventHandler { // check if added for (const xrAnchor of frame.trackedAnchors) { - if (this._index.has(xrAnchor)) + if (this._index.has(xrAnchor)) { continue; + } try { const tmp = xrAnchor.anchorSpace; // eslint-disable-line no-unused-vars @@ -508,14 +513,17 @@ class XrAnchors extends EventHandler { * @type {null|string[]} */ get uuids() { - if (!this._available) + if (!this._available) { return null; + } - if (!this._persistence) + if (!this._persistence) { return null; + } - if (!this.manager.active) + if (!this.manager.active) { return null; + } return this.manager.session.persistentAnchors; } diff --git a/src/framework/xr/xr-dom-overlay.js b/src/framework/xr/xr-dom-overlay.js index b8bca92a387..b7f934dd85c 100644 --- a/src/framework/xr/xr-dom-overlay.js +++ b/src/framework/xr/xr-dom-overlay.js @@ -88,8 +88,9 @@ class XrDomOverlay { * @type {"screen"|"floating"|"head-locked"|null} */ get state() { - if (!this._supported || !this._manager.active || !this._manager._session.domOverlayState) + if (!this._supported || !this._manager.active || !this._manager._session.domOverlayState) { return null; + } return this._manager._session.domOverlayState.type; } @@ -104,8 +105,9 @@ class XrDomOverlay { * app.xr.start(camera, pc.XRTYPE_AR, pc.XRSPACE_LOCALFLOOR); */ set root(value) { - if (!this._supported || this._manager.active) + if (!this._supported || this._manager.active) { return; + } this._root = value; } diff --git a/src/framework/xr/xr-hand.js b/src/framework/xr/xr-hand.js index eef7607857d..7639d662188 100644 --- a/src/framework/xr/xr-hand.js +++ b/src/framework/xr/xr-hand.js @@ -1,9 +1,9 @@ -import { EventHandler } from '../../core/event-handler.js'; -import { platform } from '../../core/platform.js'; -import { Vec3 } from '../../core/math/vec3.js'; import { XRHAND_LEFT } from './constants.js'; import { XrFinger } from './xr-finger.js'; import { XrJoint } from './xr-joint.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { Vec3 } from '../../core/math/vec3.js'; +import { platform } from '../../core/platform.js'; /** * @import { XrInputSource } from './xr-input-source.js' @@ -161,8 +161,9 @@ class XrHand extends EventHandler { if (jointSpace) { let pose; - if (frame.session.visibilityState !== 'hidden') + if (frame.session.visibilityState !== 'hidden') { pose = frame.getJointPose(jointSpace, this._manager._referenceSpace); + } if (pose) { joint.update(pose); diff --git a/src/framework/xr/xr-hit-test-source.js b/src/framework/xr/xr-hit-test-source.js index 60852ab6aa2..4e96a29bcfd 100644 --- a/src/framework/xr/xr-hit-test-source.js +++ b/src/framework/xr/xr-hit-test-source.js @@ -110,8 +110,9 @@ class XrHitTestSource extends EventHandler { * Stop and remove hit test source. */ remove() { - if (!this._xrHitTestSource) + if (!this._xrHitTestSource) { return; + } const sources = this.manager.hitTest.sources; const ind = sources.indexOf(this); @@ -139,20 +140,23 @@ class XrHitTestSource extends EventHandler { for (let i = 0; i < transientResults.length; i++) { const transientResult = transientResults[i]; - if (!transientResult.results.length) + if (!transientResult.results.length) { continue; + } let inputSource; - if (transientResult.inputSource) + if (transientResult.inputSource) { inputSource = this.manager.input._getByInputSource(transientResult.inputSource); + } this.updateHitResults(transientResult.results, inputSource); } } else { const results = frame.getHitTestResults(this._xrHitTestSource); - if (!results.length) + if (!results.length) { return; + } this.updateHitResults(results); } @@ -164,8 +168,9 @@ class XrHitTestSource extends EventHandler { * @private */ updateHitResults(results, inputSource) { - if (this._inputSource && this._inputSource !== inputSource) + if (this._inputSource && this._inputSource !== inputSource) { return; + } const origin = poolVec3.pop() ?? new Vec3(); @@ -185,8 +190,9 @@ class XrHitTestSource extends EventHandler { const pose = results[i].getPose(this.manager._referenceSpace); const distance = origin.distance(pose.transform.position); - if (distance >= candidateDistance) + if (distance >= candidateDistance) { continue; + } candidateDistance = distance; candidateHitTestResult = results[i]; diff --git a/src/framework/xr/xr-hit-test.js b/src/framework/xr/xr-hit-test.js index 6c43f5d955a..33e34853c4d 100644 --- a/src/framework/xr/xr-hit-test.js +++ b/src/framework/xr/xr-hit-test.js @@ -1,7 +1,7 @@ -import { platform } from '../../core/platform.js'; -import { EventHandler } from '../../core/event-handler.js'; import { XRSPACE_VIEWER } from './constants.js'; import { XrHitTestSource } from './xr-hit-test-source.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { platform } from '../../core/platform.js'; /** * @import { Ray } from '../../core/shape/ray.js' @@ -268,8 +268,9 @@ class XrHitTest extends EventHandler { return; } - if (!options.profile && !options.spaceType) + if (!options.profile && !options.spaceType) { options.spaceType = XRSPACE_VIEWER; + } let xrRay; const offsetRay = options.offsetRay; @@ -346,8 +347,9 @@ class XrHitTest extends EventHandler { * @ignore */ update(frame) { - if (!this._available) + if (!this._available) { return; + } for (let i = 0; i < this.sources.length; i++) { this.sources[i].update(frame); diff --git a/src/framework/xr/xr-image-tracking.js b/src/framework/xr/xr-image-tracking.js index d1bef8d9128..6a0453d5689 100644 --- a/src/framework/xr/xr-image-tracking.js +++ b/src/framework/xr/xr-image-tracking.js @@ -1,6 +1,6 @@ +import { XrTrackedImage } from './xr-tracked-image.js'; import { EventHandler } from '../../core/event-handler.js'; import { platform } from '../../core/platform.js'; -import { XrTrackedImage } from './xr-tracked-image.js'; /** * @import { XrManager } from './xr-manager.js' @@ -39,10 +39,10 @@ class XrImageTracking extends EventHandler { */ _supported = platform.browser && !!window.XRImageTrackingResult; - /** - * @type {boolean} - * @private - */ + /** + * @type {boolean} + * @private + */ _available = false; /** @@ -147,11 +147,11 @@ class XrImageTracking extends EventHandler { */ prepareImages(callback) { if (this._images.length) { - Promise.all(this._images.map(function (trackedImage) { + Promise.all(this._images.map((trackedImage) => { return trackedImage.prepare(); - })).then(function (bitmaps) { + })).then((bitmaps) => { callback(null, bitmaps); - }).catch(function (err) { + }).catch((err) => { callback(err, null); }); } else { diff --git a/src/framework/xr/xr-input-source.js b/src/framework/xr/xr-input-source.js index 9cd76f1f16c..d681e850e64 100644 --- a/src/framework/xr/xr-input-source.js +++ b/src/framework/xr/xr-input-source.js @@ -1,9 +1,9 @@ +import { XrHand } from './xr-hand.js'; import { EventHandler } from '../../core/event-handler.js'; import { Mat4 } from '../../core/math/mat4.js'; import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; import { Ray } from '../../core/shape/ray.js'; -import { XrHand } from './xr-hand.js'; import { now } from '../../core/time.js'; /** @@ -315,8 +315,9 @@ class XrInputSource extends EventHandler { this._manager = manager; this._xrInputSource = xrInputSource; - if (xrInputSource.hand) + if (xrInputSource.hand) { this._hand = new XrHand(this); + } } /** @@ -435,13 +436,15 @@ class XrInputSource extends EventHandler { * @type {boolean} */ set elementInput(value) { - if (this._elementInput === value) + if (this._elementInput === value) { return; + } this._elementInput = value; - if (!this._elementInput) + if (!this._elementInput) { this._elementEntity = null; + } } /** @@ -626,8 +629,9 @@ class XrInputSource extends EventHandler { * @returns {Vec3|null} The world space linear velocity of the handheld input source. */ getLinearVelocity() { - if (!this._velocitiesAvailable) + if (!this._velocitiesAvailable) { return null; + } return this._linearVelocity; } diff --git a/src/framework/xr/xr-input.js b/src/framework/xr/xr-input.js index 212b5867999..abe87c25caa 100644 --- a/src/framework/xr/xr-input.js +++ b/src/framework/xr/xr-input.js @@ -1,6 +1,6 @@ +import { XrInputSource } from './xr-input-source.js'; import { EventHandler } from '../../core/event-handler.js'; import { platform } from '../../core/platform.js'; -import { XrInputSource } from './xr-input-source.js'; /** * @import { XrManager } from './xr-manager.js' @@ -275,8 +275,9 @@ class XrInput extends EventHandler { * @private */ _addInputSource(xrInputSource) { - if (this._getByInputSource(xrInputSource)) + if (this._getByInputSource(xrInputSource)) { return; + } const inputSource = new XrInputSource(this.manager, xrInputSource); this._inputSources.push(inputSource); @@ -289,8 +290,9 @@ class XrInput extends EventHandler { */ _removeInputSource(xrInputSource) { for (let i = 0; i < this._inputSources.length; i++) { - if (this._inputSources[i].inputSource !== xrInputSource) + if (this._inputSources[i].inputSource !== xrInputSource) { continue; + } const inputSource = this._inputSources[i]; this._inputSources.splice(i, 1); diff --git a/src/framework/xr/xr-joint.js b/src/framework/xr/xr-joint.js index 35d980042b9..08b0437c03b 100644 --- a/src/framework/xr/xr-joint.js +++ b/src/framework/xr/xr-joint.js @@ -1,7 +1,7 @@ -import { platform } from '../../core/platform.js'; import { Mat4 } from '../../core/math/mat4.js'; import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; +import { platform } from '../../core/platform.js'; /** * @import { XrFinger } from './xr-finger.js' diff --git a/src/framework/xr/xr-light-estimation.js b/src/framework/xr/xr-light-estimation.js index 6b6dc7845d5..19761c3d89c 100644 --- a/src/framework/xr/xr-light-estimation.js +++ b/src/framework/xr/xr-light-estimation.js @@ -1,9 +1,9 @@ +import { XRTYPE_AR } from './constants.js'; import { EventHandler } from '../../core/event-handler.js'; import { Color } from '../../core/math/color.js'; import { Mat4 } from '../../core/math/mat4.js'; import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; -import { XRTYPE_AR } from './constants.js'; /** * @import { XrManager } from './xr-manager.js' @@ -147,17 +147,21 @@ class XrLightEstimation extends EventHandler { start() { let err; - if (!this._manager.session) + if (!this._manager.session) { err = new Error('XR session is not running'); + } - if (!err && this._manager.type !== XRTYPE_AR) + if (!err && this._manager.type !== XRTYPE_AR) { err = new Error('XR session type is not AR'); + } - if (!err && !this._supported) + if (!err && !this._supported) { err = new Error('light-estimation is not supported'); + } - if (!err && this._lightProbe || this._lightProbeRequested) + if (!err && this._lightProbe || this._lightProbeRequested) { err = new Error('light estimation is already requested'); + } if (err) { this.fire('error', err); diff --git a/src/framework/xr/xr-manager.js b/src/framework/xr/xr-manager.js index 0a069643a78..b7835548bac 100644 --- a/src/framework/xr/xr-manager.js +++ b/src/framework/xr/xr-manager.js @@ -1,19 +1,19 @@ -import { Debug } from "../../core/debug.js"; -import { EventHandler } from '../../core/event-handler.js'; -import { platform } from '../../core/platform.js'; -import { Mat4 } from '../../core/math/mat4.js'; -import { Quat } from '../../core/math/quat.js'; -import { Vec3 } from '../../core/math/vec3.js'; import { XRTYPE_INLINE, XRTYPE_VR, XRTYPE_AR, XRDEPTHSENSINGUSAGE_CPU, XRDEPTHSENSINGFORMAT_L8A8 } from './constants.js'; +import { XrAnchors } from './xr-anchors.js'; import { XrDomOverlay } from './xr-dom-overlay.js'; import { XrHitTest } from './xr-hit-test.js'; import { XrImageTracking } from './xr-image-tracking.js'; import { XrInput } from './xr-input.js'; import { XrLightEstimation } from './xr-light-estimation.js'; -import { XrPlaneDetection } from './xr-plane-detection.js'; -import { XrAnchors } from './xr-anchors.js'; import { XrMeshDetection } from './xr-mesh-detection.js'; +import { XrPlaneDetection } from './xr-plane-detection.js'; import { XrViews } from './xr-views.js'; +import { Debug } from '../../core/debug.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { Mat4 } from '../../core/math/mat4.js'; +import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; +import { platform } from '../../core/platform.js'; /** * @import { AppBase } from '../app-base.js' @@ -407,8 +407,9 @@ class XrManager extends EventHandler { start(camera, type, spaceType, options) { let callback = options; - if (typeof options === 'object') + if (typeof options === 'object') { callback = options.callback; + } if (!this._available[type]) { if (callback) callback(new Error('XR is not available')); @@ -449,14 +450,17 @@ class XrManager extends EventHandler { opts.optionalFeatures.push('hit-test'); if (options) { - if (options.imageTracking && this.imageTracking.supported) + if (options.imageTracking && this.imageTracking.supported) { opts.optionalFeatures.push('image-tracking'); + } - if (options.planeDetection) + if (options.planeDetection) { opts.optionalFeatures.push('plane-detection'); + } - if (options.meshDetection) + if (options.meshDetection) { opts.optionalFeatures.push('mesh-detection'); + } } if (this.domOverlay.supported && this.domOverlay.root) { @@ -504,8 +508,9 @@ class XrManager extends EventHandler { opts.optionalFeatures.push('hand-tracking'); - if (options && options.optionalFeatures) + if (options && options.optionalFeatures) { opts.optionalFeatures = opts.optionalFeatures.concat(options.optionalFeatures); + } if (this.imageTracking.supported && this.imageTracking.images.length) { this.imageTracking.prepareImages((err, trackedImages) => { @@ -515,8 +520,9 @@ class XrManager extends EventHandler { return; } - if (trackedImages !== null) + if (trackedImages !== null) { opts.trackedImages = trackedImages; + } this._onStartOptionsReady(type, spaceType, opts, callback); }); @@ -652,12 +658,12 @@ class XrManager extends EventHandler { } this._session.updateTargetFrameRate(frameRate) - .then(() => { - callback?.(); - }) - .catch((err) => { - callback?.(err); - }); + .then(() => { + callback?.(); + }) + .catch((err) => { + callback?.(err); + }); } /** @@ -666,12 +672,13 @@ class XrManager extends EventHandler { */ _sessionSupportCheck(type) { navigator.xr.isSessionSupported(type).then((available) => { - if (this._available[type] === available) + if (this._available[type] === available) { return; + } this._available[type] = available; this.fire('available', type, available); - this.fire('available:' + type, available); + this.fire(`available:${type}`, available); }).catch((ex) => { this.fire('error', ex); }); @@ -719,8 +726,9 @@ class XrManager extends EventHandler { // old requestAnimationFrame will never be triggered, // so queue up new tick - if (this.app.systems) + if (this.app.systems) { this.app.tick(); + } }; session.addEventListener('end', onEnd); @@ -770,14 +778,16 @@ class XrManager extends EventHandler { * @private */ _setClipPlanes(near, far) { - if (this._depthNear === near && this._depthFar === far) + if (this._depthNear === near && this._depthFar === far) { return; + } this._depthNear = near; this._depthFar = far; - if (!this._session) + if (!this._session) { return; + } // if session is available, // queue up render state update @@ -816,11 +826,13 @@ class XrManager extends EventHandler { /** @private */ _onDeviceLost() { - if (!this._session) + if (!this._session) { return; + } - if (this.webglBinding) + if (this.webglBinding) { this.webglBinding = null; + } this._baseLayer = null; @@ -833,17 +845,18 @@ class XrManager extends EventHandler { /** @private */ _onDeviceRestored() { - if (!this._session) + if (!this._session) { return; + } setTimeout(() => { this.app.graphicsDevice.gl.makeXRCompatible() - .then(() => { - this._createBaseLayer(); - }) - .catch((ex) => { - this.fire('error', ex); - }); + .then(() => { + this._createBaseLayer(); + }) + .catch((ex) => { + this.fire('error', ex); + }); }, 0); } @@ -910,26 +923,33 @@ class XrManager extends EventHandler { this.input.update(frame); if (this._type === XRTYPE_AR) { - if (this.hitTest.supported) + if (this.hitTest.supported) { this.hitTest.update(frame); + } - if (this.lightEstimation.supported) + if (this.lightEstimation.supported) { this.lightEstimation.update(frame); + } - if (this.imageTracking.supported) + if (this.imageTracking.supported) { this.imageTracking.update(frame); + } - if (this.anchors.supported) + if (this.anchors.supported) { this.anchors.update(frame); + } - if (this.planeDetection.supported) + if (this.planeDetection.supported) { this.planeDetection.update(frame); + } - if (this.depthSensing.supported) + if (this.depthSensing.supported) { this.depthSensing.update(); + } - if (this.meshDetection.supported) + if (this.meshDetection.supported) { this.meshDetection.update(frame); + } } this.fire('update', frame); @@ -1058,8 +1078,9 @@ class XrManager extends EventHandler { * @ignore */ get visibilityState() { - if (!this._session) + if (!this._session) { return null; + } return this._session.visibilityState; } diff --git a/src/framework/xr/xr-mesh-detection.js b/src/framework/xr/xr-mesh-detection.js index e7d041ea17b..66fdae84969 100644 --- a/src/framework/xr/xr-mesh-detection.js +++ b/src/framework/xr/xr-mesh-detection.js @@ -1,6 +1,6 @@ -import { platform } from "../../core/platform.js"; -import { EventHandler } from "../../core/event-handler.js"; -import { XrMesh } from "./xr-mesh.js"; +import { XrMesh } from './xr-mesh.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { platform } from '../../core/platform.js'; /** * @import { XrManager } from './xr-manager.js' @@ -149,8 +149,9 @@ class XrMeshDetection extends EventHandler { // remove meshes for (const mesh of this._index.values()) { - if (frame.detectedMeshes.has(mesh.xrMesh)) + if (frame.detectedMeshes.has(mesh.xrMesh)) { continue; + } this._removeMesh(mesh); } @@ -182,8 +183,9 @@ class XrMeshDetection extends EventHandler { if (!this._available) return; this._available = false; - for (const mesh of this._index.values()) + for (const mesh of this._index.values()) { this._removeMesh(mesh); + } this.fire('unavailable'); } diff --git a/src/framework/xr/xr-mesh.js b/src/framework/xr/xr-mesh.js index f1820325e07..aecc01827c4 100644 --- a/src/framework/xr/xr-mesh.js +++ b/src/framework/xr/xr-mesh.js @@ -1,6 +1,6 @@ -import { EventHandler } from "../../core/event-handler.js"; -import { Vec3 } from "../../core/math/vec3.js"; -import { Quat } from "../../core/math/quat.js"; +import { EventHandler } from '../../core/event-handler.js'; +import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; /** * @import { XrMeshDetection } from './xr-mesh-detection.js' diff --git a/src/framework/xr/xr-plane-detection.js b/src/framework/xr/xr-plane-detection.js index bb21cd3276c..95da8e4ea7e 100644 --- a/src/framework/xr/xr-plane-detection.js +++ b/src/framework/xr/xr-plane-detection.js @@ -1,6 +1,6 @@ -import { platform } from '../../core/platform.js'; -import { EventHandler } from '../../core/event-handler.js'; import { XrPlane } from './xr-plane.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { platform } from '../../core/platform.js'; /** * @import { XrManager } from './xr-manager.js' @@ -164,8 +164,9 @@ class XrPlaneDetection extends EventHandler { // iterate through indexed planes for (const [xrPlane, plane] of this._planesIndex) { - if (detectedPlanes.has(xrPlane)) + if (detectedPlanes.has(xrPlane)) { continue; + } // if indexed plane is not listed in detectedPlanes anymore // then remove it diff --git a/src/framework/xr/xr-tracked-image.js b/src/framework/xr/xr-tracked-image.js index 2744d2a5aa1..893b9cb849b 100644 --- a/src/framework/xr/xr-tracked-image.js +++ b/src/framework/xr/xr-tracked-image.js @@ -1,6 +1,6 @@ import { EventHandler } from '../../core/event-handler.js'; -import { Vec3 } from '../../core/math/vec3.js'; import { Quat } from '../../core/math/quat.js'; +import { Vec3 } from '../../core/math/vec3.js'; /** * The tracked image interface that is created by the Image Tracking system and is provided as a @@ -183,13 +183,13 @@ class XrTrackedImage extends EventHandler { } return createImageBitmap(this._image) - .then((bitmap) => { - this._bitmap = bitmap; - return { - image: this._bitmap, - widthInMeters: this._width - }; - }); + .then((bitmap) => { + this._bitmap = bitmap; + return { + image: this._bitmap, + widthInMeters: this._width + }; + }); } /** diff --git a/src/framework/xr/xr-view.js b/src/framework/xr/xr-view.js index 075c7cadd7b..a7db5ddad77 100644 --- a/src/framework/xr/xr-view.js +++ b/src/framework/xr/xr-view.js @@ -1,9 +1,9 @@ import { EventHandler } from '../../core/event-handler.js'; -import { Texture } from '../../platform/graphics/texture.js'; -import { Vec4 } from "../../core/math/vec4.js"; -import { Mat3 } from "../../core/math/mat3.js"; -import { Mat4 } from "../../core/math/mat4.js"; +import { Mat3 } from '../../core/math/mat3.js'; +import { Mat4 } from '../../core/math/mat4.js'; +import { Vec4 } from '../../core/math/vec4.js'; import { ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, FILTER_NEAREST, PIXELFORMAT_RGB8 } from '../../platform/graphics/constants.js'; +import { Texture } from '../../platform/graphics/texture.js'; /** * @import { XrManager } from './xr-manager.js' @@ -190,8 +190,9 @@ class XrView extends EventHandler { this._textureDepth.upload(); } - if (this._textureColor || this._textureDepth) + if (this._textureColor || this._textureDepth) { device.on('devicelost', this._onDeviceLost, this); + } } /** @@ -353,8 +354,9 @@ class XrView extends EventHandler { */ update(frame, xrView) { this._xrView = xrView; - if (this._manager.views.availableColor) + if (this._manager.views.availableColor) { this._xrCamera = this._xrView.camera; + } const layer = frame.session.renderState.baseLayer; @@ -378,16 +380,19 @@ class XrView extends EventHandler { * @private */ _updateTextureColor() { - if (!this._manager.views.availableColor || !this._xrCamera || !this._textureColor) + if (!this._manager.views.availableColor || !this._xrCamera || !this._textureColor) { return; + } const binding = this._manager.webglBinding; - if (!binding) + if (!binding) { return; + } const texture = binding.getCameraImage(this._xrCamera); - if (!texture) + if (!texture) { return; + } const device = this._manager.app.graphicsDevice; const gl = device.gl; @@ -437,8 +442,9 @@ class XrView extends EventHandler { * @private */ _updateDepth(frame) { - if (!this._manager.views.availableDepth || !this._textureDepth) + if (!this._manager.views.availableDepth || !this._textureDepth) { return; + } const gpu = this._manager.views.depthGpuOptimized; @@ -550,8 +556,9 @@ class XrView extends EventHandler { * } */ getDepth(u, v) { - if (this._manager.views.depthGpuOptimized) + if (this._manager.views.depthGpuOptimized) { return null; + } return this._depthInfo?.getDepthInMeters(u, v) ?? null; } diff --git a/src/framework/xr/xr-views.js b/src/framework/xr/xr-views.js index 44e3c9dca47..d1e45114e55 100644 --- a/src/framework/xr/xr-views.js +++ b/src/framework/xr/xr-views.js @@ -1,7 +1,7 @@ +import { XRTYPE_AR, XRDEPTHSENSINGUSAGE_GPU, XRDEPTHSENSINGFORMAT_L8A8, XRDEPTHSENSINGFORMAT_F32 } from './constants.js'; +import { XrView } from './xr-view.js'; +import { EventHandler } from '../../core/event-handler.js'; import { platform } from '../../core/platform.js'; -import { EventHandler } from "../../core/event-handler.js"; -import { XrView } from "./xr-view.js"; -import { XRTYPE_AR, XRDEPTHSENSINGUSAGE_GPU, XRDEPTHSENSINGFORMAT_L8A8, XRDEPTHSENSINGFORMAT_F32 } from "./constants.js"; import { PIXELFORMAT_LA8, PIXELFORMAT_R32F } from '../../platform/graphics/constants.js'; /** @@ -239,8 +239,9 @@ class XrViews extends EventHandler { // remove views for (const [eye, view] of this._index) { - if (this._indexTmp.has(eye)) + if (this._indexTmp.has(eye)) { continue; + } view.destroy(); this._index.delete(eye); @@ -266,11 +267,13 @@ class XrViews extends EventHandler { * @private */ _onSessionStart() { - if (this._manager.type !== XRTYPE_AR) + if (this._manager.type !== XRTYPE_AR) { return; + } - if (!this._manager.session.enabledFeatures) + if (!this._manager.session.enabledFeatures) { return; + } this._availableColor = this._manager.session.enabledFeatures.indexOf('camera-access') !== -1; this._availableDepth = this._manager.session.enabledFeatures.indexOf('depth-sensing') !== -1; diff --git a/src/platform/audio/channel.js b/src/platform/audio/channel.js index 5744e889b52..91644730271 100644 --- a/src/platform/audio/channel.js +++ b/src/platform/audio/channel.js @@ -1,5 +1,5 @@ -import { math } from '../../core/math/math.js'; import { hasAudioContext } from './capabilities.js'; +import { math } from '../../core/math/math.js'; /** * @import { SoundManager } from '../sound/manager.js' @@ -147,8 +147,9 @@ class Channel { this.manager.on('resume', this.onManagerResume, this); // suspend immediately if manager is suspended - if (this.manager.suspended) + if (this.manager.suspended) { this.onManagerSuspend(); + } } /** @@ -267,8 +268,9 @@ if (!hasAudioContext()) { this.manager.on('resume', this.onManagerResume, this); // suspend immediately if manager is suspended - if (this.manager.suspended) + if (this.manager.suspended) { this.onManagerSuspend(); + } }, diff --git a/src/platform/audio/channel3d.js b/src/platform/audio/channel3d.js index f4d7205b96a..7d3052511e1 100644 --- a/src/platform/audio/channel3d.js +++ b/src/platform/audio/channel3d.js @@ -1,9 +1,9 @@ +import { hasAudioContext } from './capabilities.js'; +import { Channel } from './channel.js'; +import { DISTANCE_EXPONENTIAL, DISTANCE_INVERSE, DISTANCE_LINEAR } from './constants.js'; import { Debug } from '../../core/debug.js'; import { math } from '../../core/math/math.js'; import { Vec3 } from '../../core/math/vec3.js'; -import { DISTANCE_EXPONENTIAL, DISTANCE_INVERSE, DISTANCE_LINEAR } from './constants.js'; -import { hasAudioContext } from './capabilities.js'; -import { Channel } from './channel.js'; /** * @import { SoundManager } from '../sound/manager.js' diff --git a/src/platform/graphics/bind-group-format.js b/src/platform/graphics/bind-group-format.js index 46fa04338df..68cf156d128 100644 --- a/src/platform/graphics/bind-group-format.js +++ b/src/platform/graphics/bind-group-format.js @@ -1,10 +1,10 @@ -import { TRACEID_BINDGROUPFORMAT_ALLOC } from '../../core/constants.js'; -import { Debug, DebugHelper } from '../../core/debug.js'; import { TEXTUREDIMENSION_2D, TEXTUREDIMENSION_CUBE, TEXTUREDIMENSION_3D, TEXTUREDIMENSION_2D_ARRAY, SAMPLETYPE_FLOAT, PIXELFORMAT_RGBA8, SAMPLETYPE_INT, SAMPLETYPE_UINT, SHADERSTAGE_COMPUTE, SHADERSTAGE_VERTEX } from './constants.js'; import { DebugGraphics } from './debug-graphics.js'; +import { TRACEID_BINDGROUPFORMAT_ALLOC } from '../../core/constants.js'; +import { Debug, DebugHelper } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' @@ -91,7 +91,7 @@ class BindStorageBufferFormat extends BindBaseFormat { // whether the buffer is read-only this.readOnly = readOnly; - Debug.assert(readOnly || !(visibility & SHADERSTAGE_VERTEX), "Storage buffer can only be used in read-only mode in SHADERSTAGE_VERTEX."); + Debug.assert(readOnly || !(visibility & SHADERSTAGE_VERTEX), 'Storage buffer can only be used in read-only mode in SHADERSTAGE_VERTEX.'); } } @@ -358,7 +358,7 @@ class BindGroupFormat { this.textureFormats.forEach((format) => { let textureType = textureDimensionInfo[format.textureDimension]; - Debug.assert(textureType, "Unsupported texture type", format.textureDimension); + Debug.assert(textureType, 'Unsupported texture type', format.textureDimension); // handle texture2DArray by renaming the texture object and defining a replacement macro let namePostfix = ''; diff --git a/src/platform/graphics/bind-group.js b/src/platform/graphics/bind-group.js index e8381a9f80f..311ebbd2f79 100644 --- a/src/platform/graphics/bind-group.js +++ b/src/platform/graphics/bind-group.js @@ -1,7 +1,7 @@ -import { Debug } from '../../core/debug.js'; -import { TRACEID_BINDGROUP_ALLOC } from '../../core/constants.js'; import { UNIFORM_BUFFER_DEFAULT_SLOT_NAME } from './constants.js'; import { DebugGraphics } from './debug-graphics.js'; +import { TRACEID_BINDGROUP_ALLOC } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; /** * @import { BindGroupFormat } from './bind-group-format.js' diff --git a/src/platform/graphics/blend-state.js b/src/platform/graphics/blend-state.js index 5406d3d91fa..a1693cdc7ef 100644 --- a/src/platform/graphics/blend-state.js +++ b/src/platform/graphics/blend-state.js @@ -1,4 +1,4 @@ -import { BitPacking } from "../../core/math/bit-packing.js"; +import { BitPacking } from '../../core/math/bit-packing.js'; import { BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ZERO, BLENDMODE_SRC_ALPHA, BLENDMODE_ONE_MINUS_SRC_ALPHA } from '../../platform/graphics/constants.js'; // masks (to only keep relevant bits) diff --git a/src/platform/graphics/constants.js b/src/platform/graphics/constants.js index 2746bf2a61a..25f259dc6a9 100644 --- a/src/platform/graphics/constants.js +++ b/src/platform/graphics/constants.js @@ -1264,7 +1264,7 @@ export const PRIMITIVE_TRIFAN = 6; * @type {string} * @category Graphics */ -export const SEMANTIC_POSITION = "POSITION"; +export const SEMANTIC_POSITION = 'POSITION'; /** * Vertex attribute to be treated as a normal. @@ -1272,7 +1272,7 @@ export const SEMANTIC_POSITION = "POSITION"; * @type {string} * @category Graphics */ -export const SEMANTIC_NORMAL = "NORMAL"; +export const SEMANTIC_NORMAL = 'NORMAL'; /** * Vertex attribute to be treated as a tangent. @@ -1280,7 +1280,7 @@ export const SEMANTIC_NORMAL = "NORMAL"; * @type {string} * @category Graphics */ -export const SEMANTIC_TANGENT = "TANGENT"; +export const SEMANTIC_TANGENT = 'TANGENT'; /** * Vertex attribute to be treated as skin blend weights. @@ -1288,7 +1288,7 @@ export const SEMANTIC_TANGENT = "TANGENT"; * @type {string} * @category Graphics */ -export const SEMANTIC_BLENDWEIGHT = "BLENDWEIGHT"; +export const SEMANTIC_BLENDWEIGHT = 'BLENDWEIGHT'; /** * Vertex attribute to be treated as skin blend indices. @@ -1296,7 +1296,7 @@ export const SEMANTIC_BLENDWEIGHT = "BLENDWEIGHT"; * @type {string} * @category Graphics */ -export const SEMANTIC_BLENDINDICES = "BLENDINDICES"; +export const SEMANTIC_BLENDINDICES = 'BLENDINDICES'; /** * Vertex attribute to be treated as a color. @@ -1304,10 +1304,10 @@ export const SEMANTIC_BLENDINDICES = "BLENDINDICES"; * @type {string} * @category Graphics */ -export const SEMANTIC_COLOR = "COLOR"; +export const SEMANTIC_COLOR = 'COLOR'; // private semantic used for programmatic construction of individual texcoord semantics -export const SEMANTIC_TEXCOORD = "TEXCOORD"; +export const SEMANTIC_TEXCOORD = 'TEXCOORD'; /** * Vertex attribute to be treated as a texture coordinate (set 0). @@ -1315,7 +1315,7 @@ export const SEMANTIC_TEXCOORD = "TEXCOORD"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD0 = "TEXCOORD0"; +export const SEMANTIC_TEXCOORD0 = 'TEXCOORD0'; /** * Vertex attribute to be treated as a texture coordinate (set 1). @@ -1323,7 +1323,7 @@ export const SEMANTIC_TEXCOORD0 = "TEXCOORD0"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD1 = "TEXCOORD1"; +export const SEMANTIC_TEXCOORD1 = 'TEXCOORD1'; /** * Vertex attribute to be treated as a texture coordinate (set 2). @@ -1331,7 +1331,7 @@ export const SEMANTIC_TEXCOORD1 = "TEXCOORD1"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD2 = "TEXCOORD2"; +export const SEMANTIC_TEXCOORD2 = 'TEXCOORD2'; /** * Vertex attribute to be treated as a texture coordinate (set 3). @@ -1339,7 +1339,7 @@ export const SEMANTIC_TEXCOORD2 = "TEXCOORD2"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD3 = "TEXCOORD3"; +export const SEMANTIC_TEXCOORD3 = 'TEXCOORD3'; /** * Vertex attribute to be treated as a texture coordinate (set 4). @@ -1347,7 +1347,7 @@ export const SEMANTIC_TEXCOORD3 = "TEXCOORD3"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD4 = "TEXCOORD4"; +export const SEMANTIC_TEXCOORD4 = 'TEXCOORD4'; /** * Vertex attribute to be treated as a texture coordinate (set 5). @@ -1355,7 +1355,7 @@ export const SEMANTIC_TEXCOORD4 = "TEXCOORD4"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD5 = "TEXCOORD5"; +export const SEMANTIC_TEXCOORD5 = 'TEXCOORD5'; /** * Vertex attribute to be treated as a texture coordinate (set 6). @@ -1363,7 +1363,7 @@ export const SEMANTIC_TEXCOORD5 = "TEXCOORD5"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD6 = "TEXCOORD6"; +export const SEMANTIC_TEXCOORD6 = 'TEXCOORD6'; /** * Vertex attribute to be treated as a texture coordinate (set 7). @@ -1371,7 +1371,7 @@ export const SEMANTIC_TEXCOORD6 = "TEXCOORD6"; * @type {string} * @category Graphics */ -export const SEMANTIC_TEXCOORD7 = "TEXCOORD7"; +export const SEMANTIC_TEXCOORD7 = 'TEXCOORD7'; /** * Vertex attribute with a user defined semantic. @@ -1379,7 +1379,7 @@ export const SEMANTIC_TEXCOORD7 = "TEXCOORD7"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR0 = "ATTR0"; +export const SEMANTIC_ATTR0 = 'ATTR0'; /** * Vertex attribute with a user defined semantic. @@ -1387,7 +1387,7 @@ export const SEMANTIC_ATTR0 = "ATTR0"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR1 = "ATTR1"; +export const SEMANTIC_ATTR1 = 'ATTR1'; /** * Vertex attribute with a user defined semantic. @@ -1395,7 +1395,7 @@ export const SEMANTIC_ATTR1 = "ATTR1"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR2 = "ATTR2"; +export const SEMANTIC_ATTR2 = 'ATTR2'; /** * Vertex attribute with a user defined semantic. @@ -1403,7 +1403,7 @@ export const SEMANTIC_ATTR2 = "ATTR2"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR3 = "ATTR3"; +export const SEMANTIC_ATTR3 = 'ATTR3'; /** * Vertex attribute with a user defined semantic. @@ -1411,7 +1411,7 @@ export const SEMANTIC_ATTR3 = "ATTR3"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR4 = "ATTR4"; +export const SEMANTIC_ATTR4 = 'ATTR4'; /** * Vertex attribute with a user defined semantic. @@ -1419,7 +1419,7 @@ export const SEMANTIC_ATTR4 = "ATTR4"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR5 = "ATTR5"; +export const SEMANTIC_ATTR5 = 'ATTR5'; /** * Vertex attribute with a user defined semantic. @@ -1427,7 +1427,7 @@ export const SEMANTIC_ATTR5 = "ATTR5"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR6 = "ATTR6"; +export const SEMANTIC_ATTR6 = 'ATTR6'; /** * Vertex attribute with a user defined semantic. @@ -1435,7 +1435,7 @@ export const SEMANTIC_ATTR6 = "ATTR6"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR7 = "ATTR7"; +export const SEMANTIC_ATTR7 = 'ATTR7'; /** * Vertex attribute with a user defined semantic. @@ -1443,7 +1443,7 @@ export const SEMANTIC_ATTR7 = "ATTR7"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR8 = "ATTR8"; +export const SEMANTIC_ATTR8 = 'ATTR8'; /** * Vertex attribute with a user defined semantic. @@ -1451,7 +1451,7 @@ export const SEMANTIC_ATTR8 = "ATTR8"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR9 = "ATTR9"; +export const SEMANTIC_ATTR9 = 'ATTR9'; /** * Vertex attribute with a user defined semantic. @@ -1459,7 +1459,7 @@ export const SEMANTIC_ATTR9 = "ATTR9"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR10 = "ATTR10"; +export const SEMANTIC_ATTR10 = 'ATTR10'; /** * Vertex attribute with a user defined semantic. @@ -1467,7 +1467,7 @@ export const SEMANTIC_ATTR10 = "ATTR10"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR11 = "ATTR11"; +export const SEMANTIC_ATTR11 = 'ATTR11'; /** * Vertex attribute with a user defined semantic. @@ -1475,7 +1475,7 @@ export const SEMANTIC_ATTR11 = "ATTR11"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR12 = "ATTR12"; +export const SEMANTIC_ATTR12 = 'ATTR12'; /** * Vertex attribute with a user defined semantic. @@ -1483,7 +1483,7 @@ export const SEMANTIC_ATTR12 = "ATTR12"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR13 = "ATTR13"; +export const SEMANTIC_ATTR13 = 'ATTR13'; /** * Vertex attribute with a user defined semantic. @@ -1491,7 +1491,7 @@ export const SEMANTIC_ATTR13 = "ATTR13"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR14 = "ATTR14"; +export const SEMANTIC_ATTR14 = 'ATTR14'; /** * Vertex attribute with a user defined semantic. @@ -1499,7 +1499,7 @@ export const SEMANTIC_ATTR14 = "ATTR14"; * @type {string} * @category Graphics */ -export const SEMANTIC_ATTR15 = "ATTR15"; +export const SEMANTIC_ATTR15 = 'ATTR15'; export const SHADERTAG_MATERIAL = 1; @@ -1733,7 +1733,7 @@ export const SAMPLETYPE_UINT = 4; * @type {string} * @category Graphics */ -export const TEXTUREPROJECTION_NONE = "none"; +export const TEXTUREPROJECTION_NONE = 'none'; /** * Texture data is stored in cubemap projection format. @@ -1741,7 +1741,7 @@ export const TEXTUREPROJECTION_NONE = "none"; * @type {string} * @category Graphics */ -export const TEXTUREPROJECTION_CUBE = "cube"; +export const TEXTUREPROJECTION_CUBE = 'cube'; /** * Texture data is stored in equirectangular projection format. @@ -1749,7 +1749,7 @@ export const TEXTUREPROJECTION_CUBE = "cube"; * @type {string} * @category Graphics */ -export const TEXTUREPROJECTION_EQUIRECT = "equirect"; +export const TEXTUREPROJECTION_EQUIRECT = 'equirect'; /** * Texture data is stored in octahedral projection format. @@ -1757,7 +1757,7 @@ export const TEXTUREPROJECTION_EQUIRECT = "equirect"; * @type {string} * @category Graphics */ -export const TEXTUREPROJECTION_OCTAHEDRAL = "octahedral"; +export const TEXTUREPROJECTION_OCTAHEDRAL = 'octahedral'; /** * Shader source code uses GLSL language. @@ -2241,13 +2241,13 @@ export const vertexTypesNames = ['INT8', 'UINT8', 'INT16', 'UINT16', 'INT32', 'U // map of typed array to engine TYPE_*** export const typedArrayToType = { - "Int8Array": TYPE_INT8, - "Uint8Array": TYPE_UINT8, - "Int16Array": TYPE_INT16, - "Uint16Array": TYPE_UINT16, - "Int32Array": TYPE_INT32, - "Uint32Array": TYPE_UINT32, - "Float32Array": TYPE_FLOAT32 + 'Int8Array': TYPE_INT8, + 'Uint8Array': TYPE_UINT8, + 'Int16Array': TYPE_INT16, + 'Uint16Array': TYPE_UINT16, + 'Int32Array': TYPE_INT32, + 'Uint32Array': TYPE_UINT32, + 'Float32Array': TYPE_FLOAT32 }; // map of engine INDEXFORMAT_*** to their corresponding typed array constructors and byte sizes diff --git a/src/platform/graphics/debug-graphics.js b/src/platform/graphics/debug-graphics.js index 50141c745d8..fafaf23f743 100644 --- a/src/platform/graphics/debug-graphics.js +++ b/src/platform/graphics/debug-graphics.js @@ -52,7 +52,7 @@ class DebugGraphics { * @returns {string} String representation of current markers. */ static toString() { - return DebugGraphics.markers.join(" | "); + return DebugGraphics.markers.join(' | '); } } diff --git a/src/platform/graphics/depth-state.js b/src/platform/graphics/depth-state.js index cb32fd4a670..0945ec5c25f 100644 --- a/src/platform/graphics/depth-state.js +++ b/src/platform/graphics/depth-state.js @@ -1,8 +1,8 @@ -import { BitPacking } from "../../core/math/bit-packing.js"; -import { StringIds } from "../../core/string-ids.js"; import { FUNC_LESSEQUAL, FUNC_ALWAYS } from './constants.js'; +import { BitPacking } from '../../core/math/bit-packing.js'; +import { StringIds } from '../../core/string-ids.js'; const stringIds = new StringIds(); diff --git a/src/platform/graphics/dynamic-buffer.js b/src/platform/graphics/dynamic-buffer.js index ddad6795974..15bc3cf240f 100644 --- a/src/platform/graphics/dynamic-buffer.js +++ b/src/platform/graphics/dynamic-buffer.js @@ -1,7 +1,7 @@ -import { DebugHelper } from '../../core/debug.js'; import { BindGroupFormat, BindUniformBufferFormat } from './bind-group-format.js'; import { BindGroup } from './bind-group.js'; import { SHADERSTAGE_FRAGMENT, SHADERSTAGE_VERTEX, UNIFORM_BUFFER_DEFAULT_SLOT_NAME } from './constants.js'; +import { DebugHelper } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' diff --git a/src/platform/graphics/gpu-profiler.js b/src/platform/graphics/gpu-profiler.js index 88d1ea091bd..400b8c8ca99 100644 --- a/src/platform/graphics/gpu-profiler.js +++ b/src/platform/graphics/gpu-profiler.js @@ -1,6 +1,6 @@ -import { TRACEID_GPU_TIMINGS } from "../../core/constants.js"; -import { Debug } from "../../core/debug.js"; -import { Tracing } from "../../core/tracing.js"; +import { TRACEID_GPU_TIMINGS } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; +import { Tracing } from '../../core/tracing.js'; /** * Base class of a simple GPU profiler. diff --git a/src/platform/graphics/graphics-device-create.js b/src/platform/graphics/graphics-device-create.js index f07172083c0..825a02f30ae 100644 --- a/src/platform/graphics/graphics-device-create.js +++ b/src/platform/graphics/graphics-device-create.js @@ -1,9 +1,8 @@ -import { platform } from '../../core/platform.js'; - import { DEVICETYPE_WEBGL2, DEVICETYPE_WEBGPU, DEVICETYPE_NULL } from './constants.js'; -import { WebgpuGraphicsDevice } from './webgpu/webgpu-graphics-device.js'; -import { WebglGraphicsDevice } from './webgl/webgl-graphics-device.js'; import { NullGraphicsDevice } from './null/null-graphics-device.js'; +import { WebglGraphicsDevice } from './webgl/webgl-graphics-device.js'; +import { WebgpuGraphicsDevice } from './webgpu/webgpu-graphics-device.js'; +import { platform } from '../../core/platform.js'; /** * Creates a graphics device. @@ -94,16 +93,16 @@ function createGraphicsDevice(canvas, options = {}) { reject(new Error('Failed to create a graphics device')); } else { Promise.resolve(deviceCreateFuncs[attempt++]()) - .then((device) => { - if (device) { - resolve(device); - } else { - next(); - } - }).catch((err) => { - console.log(err); + .then((device) => { + if (device) { + resolve(device); + } else { next(); - }); + } + }).catch((err) => { + console.log(err); + next(); + }); } }; next(); diff --git a/src/platform/graphics/graphics-device.js b/src/platform/graphics/graphics-device.js index 4475694dc00..3300c227eca 100644 --- a/src/platform/graphics/graphics-device.js +++ b/src/platform/graphics/graphics-device.js @@ -1,23 +1,23 @@ -import { Debug } from '../../core/debug.js'; -import { EventHandler } from '../../core/event-handler.js'; -import { platform } from '../../core/platform.js'; -import { now } from '../../core/time.js'; -import { Vec2 } from '../../core/math/vec2.js'; -import { Tracing } from '../../core/tracing.js'; -import { Color } from '../../core/math/color.js'; -import { TRACEID_TEXTURES } from '../../core/constants.js'; +import { BlendState } from './blend-state.js'; import { CULLFACE_BACK, CLEARFLAG_COLOR, CLEARFLAG_DEPTH, PRIMITIVE_POINTS, PRIMITIVE_TRIFAN, SEMANTIC_POSITION, TYPE_FLOAT32, PIXELFORMAT_111110F, PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F, DISPLAYFORMAT_LDR } from './constants.js'; -import { BlendState } from './blend-state.js'; import { DepthState } from './depth-state.js'; import { ScopeSpace } from './scope-space.js'; +import { StencilParameters } from './stencil-parameters.js'; import { VertexBuffer } from './vertex-buffer.js'; import { VertexFormat } from './vertex-format.js'; -import { StencilParameters } from './stencil-parameters.js'; +import { TRACEID_TEXTURES } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { Color } from '../../core/math/color.js'; +import { Vec2 } from '../../core/math/vec2.js'; +import { platform } from '../../core/platform.js'; +import { now } from '../../core/time.js'; +import { Tracing } from '../../core/tracing.js'; /** * @import { Compute } from './compute.js' @@ -267,12 +267,12 @@ class GraphicsDevice extends EventHandler { */ textureFloatRenderable; - /** - * True if 16-bit floating-point textures can be used as a frame buffer. - * - * @type {boolean} - * @readonly - */ + /** + * True if 16-bit floating-point textures can be used as a frame buffer. + * + * @type {boolean} + * @readonly + */ textureHalfFloatRenderable; /** @@ -284,12 +284,12 @@ class GraphicsDevice extends EventHandler { */ textureRG11B10Renderable = false; - /** - * True if filtering can be applied when sampling float textures. - * - * @type {boolean} - * @readonly - */ + /** + * True if filtering can be applied when sampling float textures. + * + * @type {boolean} + * @readonly + */ textureFloatFilterable = false; /** @@ -424,9 +424,9 @@ class GraphicsDevice extends EventHandler { this._renderTargetCreationTime = 0; // Create the ScopeNamespace for shader attributes and variables - this.scope = new ScopeSpace("Device"); + this.scope = new ScopeSpace('Device'); - this.textureBias = this.scope.resolve("textureBias"); + this.textureBias = this.scope.resolve('textureBias'); this.textureBias.setValue(0.0); } @@ -801,7 +801,7 @@ class GraphicsDevice extends EventHandler { * @type {boolean} */ set fullscreen(fullscreen) { - Debug.error("GraphicsDevice.fullscreen is not implemented on current device."); + Debug.error('GraphicsDevice.fullscreen is not implemented on current device.'); } /** @@ -810,7 +810,7 @@ class GraphicsDevice extends EventHandler { * @type {boolean} */ get fullscreen() { - Debug.error("GraphicsDevice.fullscreen is not implemented on current device."); + Debug.error('GraphicsDevice.fullscreen is not implemented on current device.'); return false; } @@ -928,8 +928,9 @@ class GraphicsDevice extends EventHandler { switch (format) { case PIXELFORMAT_111110F: { - if (this.textureRG11B10Renderable) + if (this.textureRG11B10Renderable) { return format; + } break; } diff --git a/src/platform/graphics/index-buffer.js b/src/platform/graphics/index-buffer.js index 510c31dd3ea..2c826348c75 100644 --- a/src/platform/graphics/index-buffer.js +++ b/src/platform/graphics/index-buffer.js @@ -1,13 +1,13 @@ -import { Debug } from '../../core/debug.js'; +import { + BUFFER_STATIC, INDEXFORMAT_UINT16, INDEXFORMAT_UINT32, typedArrayIndexFormatsByteSize +} from './constants.js'; import { TRACEID_VRAM_IB } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' */ -import { - BUFFER_STATIC, INDEXFORMAT_UINT16, INDEXFORMAT_UINT32, typedArrayIndexFormatsByteSize -} from './constants.js'; let id = 0; @@ -208,8 +208,9 @@ class IndexBuffer { indices.set(data); } else { // data is array, copy right amount manually - for (let i = 0; i < count; i++) + for (let i = 0; i < count; i++) { indices[i] = data[i]; + } } } else { // copy whole data @@ -237,8 +238,9 @@ class IndexBuffer { } else { // data is array, copy right amount manually data.length = 0; - for (let i = 0; i < count; i++) + for (let i = 0; i < count; i++) { data[i] = indices[i]; + } } return count; diff --git a/src/platform/graphics/null/null-graphics-device.js b/src/platform/graphics/null/null-graphics-device.js index 38138a0b5ab..75adcfbeb4d 100644 --- a/src/platform/graphics/null/null-graphics-device.js +++ b/src/platform/graphics/null/null-graphics-device.js @@ -1,14 +1,13 @@ -import { Debug } from '../../../core/debug.js'; -import { - DEVICETYPE_NULL -} from '../constants.js'; -import { GraphicsDevice } from '../graphics-device.js'; - import { NullIndexBuffer } from './null-index-buffer.js'; import { NullRenderTarget } from './null-render-target.js'; import { NullShader } from './null-shader.js'; import { NullTexture } from './null-texture.js'; import { NullVertexBuffer } from './null-vertex-buffer.js'; +import { Debug } from '../../../core/debug.js'; +import { + DEVICETYPE_NULL +} from '../constants.js'; +import { GraphicsDevice } from '../graphics-device.js'; class NullGraphicsDevice extends GraphicsDevice { constructor(canvas, options = {}) { diff --git a/src/platform/graphics/render-pass.js b/src/platform/graphics/render-pass.js index 8d422465262..e115f7016ce 100644 --- a/src/platform/graphics/render-pass.js +++ b/src/platform/graphics/render-pass.js @@ -1,7 +1,7 @@ +import { TRACEID_RENDER_PASS, TRACEID_RENDER_PASS_DETAIL } from '../../core/constants.js'; import { Debug } from '../../core/debug.js'; -import { Tracing } from '../../core/tracing.js'; import { Color } from '../../core/math/color.js'; -import { TRACEID_RENDER_PASS, TRACEID_RENDER_PASS_DETAIL } from '../../core/constants.js'; +import { Tracing } from '../../core/tracing.js'; /** * @import { GraphicsDevice } from '../graphics/graphics-device.js' @@ -214,8 +214,9 @@ class RenderPass { } get name() { - if (!this._name) + if (!this._name) { this._name = this.constructor.name; + } return this._name; } @@ -353,8 +354,9 @@ class RenderPass { * the existing content. */ setClearDepth(depthValue) { - if (depthValue) + if (depthValue) { this.depthStencilOps.clearDepthValue = depthValue; + } this.depthStencilOps.clearDepth = depthValue !== undefined; } @@ -365,8 +367,9 @@ class RenderPass { * preserve the existing content. */ setClearStencil(stencilValue) { - if (stencilValue) + if (stencilValue) { this.depthStencilOps.clearStencilValue = stencilValue; + } this.depthStencilOps.clearStencil = stencilValue !== undefined; } @@ -419,12 +422,12 @@ class RenderPass { `${hasDepth ? '[Depth]' : ''}` + `${hasStencil ? '[Stencil]' : ''}` + ` ${rt.width} x ${rt.height}` + - `${(this.samples > 0 ? ' samples: ' + this.samples : '')}`; + `${(this.samples > 0 ? ` samples: ${this.samples}` : '')}`; Debug.trace(TRACEID_RENDER_PASS, - `${index.toString().padEnd(2, ' ')}: ${this.name.padEnd(20, ' ')}` + - `${this.executeEnabled ? '' : ' DISABLED '}` + - rtInfo.padEnd(30)); + `${index.toString().padEnd(2, ' ')}: ${this.name.padEnd(20, ' ')}` + + `${this.executeEnabled ? '' : ' DISABLED '}${ + rtInfo.padEnd(30)}`); for (let i = 0; i < numColor; i++) { const colorOps = this.colorArrayOps[i]; @@ -438,13 +441,13 @@ class RenderPass { if (this.depthStencilOps) { if (hasDepth) { - Debug.trace(TRACEID_RENDER_PASS_DETAIL, ` depthOps: ` + + Debug.trace(TRACEID_RENDER_PASS_DETAIL, ' depthOps: ' + `${this.depthStencilOps.clearDepth ? 'clear' : 'load'}->` + `${this.depthStencilOps.storeDepth ? 'store' : 'discard'}`); } if (hasStencil) { - Debug.trace(TRACEID_RENDER_PASS_DETAIL, ` stencOps: ` + + Debug.trace(TRACEID_RENDER_PASS_DETAIL, ' stencOps: ' + `${this.depthStencilOps.clearStencil ? 'clear' : 'load'}->` + `${this.depthStencilOps.storeStencil ? 'store' : 'discard'}`); } diff --git a/src/platform/graphics/render-target.js b/src/platform/graphics/render-target.js index 093fc4981e4..3b9cbfa3bdd 100644 --- a/src/platform/graphics/render-target.js +++ b/src/platform/graphics/render-target.js @@ -1,8 +1,8 @@ -import { Debug } from '../../core/debug.js'; -import { TRACEID_RENDER_TARGET_ALLOC } from '../../core/constants.js'; import { PIXELFORMAT_DEPTH, PIXELFORMAT_DEPTHSTENCIL, isSrgbPixelFormat } from './constants.js'; import { DebugGraphics } from './debug-graphics.js'; import { GraphicsDevice } from './graphics-device.js'; +import { TRACEID_RENDER_TARGET_ALLOC } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; /** * @import { Texture } from './texture.js' @@ -177,7 +177,7 @@ class RenderTarget { // device, from one of the buffers const device = this._colorBuffer?.device || this._depthBuffer?.device || options.graphicsDevice; - Debug.assert(device, "Failed to obtain the device, colorBuffer nor depthBuffer store it."); + Debug.assert(device, 'Failed to obtain the device, colorBuffer nor depthBuffer store it.'); this._device = device; const { maxSamples } = this._device; @@ -199,7 +199,7 @@ class RenderTarget { this.name = this._depthBuffer?.name; } if (!this.name) { - this.name = "Untitled"; + this.name = 'Untitled'; } // render image flipped in Y @@ -383,7 +383,7 @@ class RenderTarget { if (source._device) { this._device = source._device; } else { - Debug.error("Render targets are not initialized"); + Debug.error('Render targets are not initialized'); return false; } } @@ -494,8 +494,9 @@ class RenderTarget { * @ignore */ isColorBufferSrgb(index = 0) { - if (this.device.backBuffer === this) + if (this.device.backBuffer === this) { return isSrgbPixelFormat(this.device.backBufferFormat); + } const colorBuffer = this.getColorBuffer(index); return colorBuffer ? isSrgbPixelFormat(colorBuffer.format) : false; diff --git a/src/platform/graphics/shader-processor-options.js b/src/platform/graphics/shader-processor-options.js index df7489a1092..e281f2932f0 100644 --- a/src/platform/graphics/shader-processor-options.js +++ b/src/platform/graphics/shader-processor-options.js @@ -1,4 +1,4 @@ -import { BINDGROUP_VIEW } from "./constants.js"; +import { BINDGROUP_VIEW } from './constants.js'; /** * @import { BindGroupFormat } from './bind-group-format.js' diff --git a/src/platform/graphics/shader-processor.js b/src/platform/graphics/shader-processor.js index 2998b0aedc0..4d7df54509a 100644 --- a/src/platform/graphics/shader-processor.js +++ b/src/platform/graphics/shader-processor.js @@ -1,4 +1,4 @@ -import { Debug } from '../../core/debug.js'; +import { BindGroupFormat, BindTextureFormat } from './bind-group-format.js'; import { BINDGROUP_MESH, uniformTypeToName, semanticToLocation, SHADERSTAGE_VERTEX, SHADERSTAGE_FRAGMENT, @@ -8,7 +8,7 @@ import { BINDGROUP_MESH_UB } from './constants.js'; import { UniformFormat, UniformBufferFormat } from './uniform-buffer-format.js'; -import { BindGroupFormat, BindTextureFormat } from './bind-group-format.js'; +import { Debug } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' @@ -22,7 +22,8 @@ import { BindGroupFormat, BindTextureFormat } from './bind-group-format.js'; const KEYWORD = /[ \t]*(\battribute\b|\bvarying\b|\buniform\b)/g; // match 'attribute' and anything else till ';' -const KEYWORD_LINE = /(\battribute\b|\bvarying\b|\bout\b|\buniform\b)[ \t]*([^;]+)([;]+)/g; +// eslint-disable-next-line regexp/no-unused-capturing-group, regexp/no-super-linear-backtracking +const KEYWORD_LINE = /(\battribute\b|\bvarying\b|\bout\b|\buniform\b)[ \t]*([^;]+)(;+)/g; // marker for a place in the source code to be replaced by code const MARKER = '@@@'; @@ -152,11 +153,11 @@ class ShaderProcessor { const uniformsData = ShaderProcessor.processUniforms(device, parsedUniforms, shaderDefinition.processingOptions, shader); // VS - insert the blocks to the source - const vBlock = attributesBlock + '\n' + vertexVaryingsBlock + '\n' + uniformsData.code; + const vBlock = `${attributesBlock}\n${vertexVaryingsBlock}\n${uniformsData.code}`; const vshader = vertexExtracted.src.replace(MARKER, vBlock); // FS - insert the blocks to the source - const fBlock = fragmentVaryingsBlock + '\n' + outBlock + '\n' + uniformsData.code; + const fBlock = `${fragmentVaryingsBlock}\n${outBlock}\n${uniformsData.code}`; const fshader = fragmentExtracted.src.replace(MARKER, fBlock); return { @@ -287,10 +288,12 @@ class ShaderProcessor { } else if (uniform.isUnsignedInt) { sampleType = SAMPLETYPE_UINT; } else { - if (uniform.precision === 'highp') + if (uniform.precision === 'highp') { sampleType = SAMPLETYPE_UNFILTERABLE_FLOAT; - if (shadowSamplers.has(uniform.type)) + } + if (shadowSamplers.has(uniform.type)) { sampleType = SAMPLETYPE_DEPTH; + } } // dimension @@ -387,7 +390,7 @@ class ShaderProcessor { Debug.assert(location !== undefined, `Semantic ${semantic} used by the attribute ${name} is not known - make sure it's one of the supported semantics.`); Debug.assert(!usedLocations.hasOwnProperty(location), - `WARNING: Two vertex attributes are mapped to the same location in a shader: ${usedLocations[location]} and ${semantic}`); + `WARNING: Two vertex attributes are mapped to the same location in a shader: ${usedLocations[location]} and ${semantic}`); usedLocations[location] = semantic; // if vertex format for this attribute is not of a float type, we need to adjust the attribute format, for example we convert diff --git a/src/platform/graphics/shader-utils.js b/src/platform/graphics/shader-utils.js index bc80b7ca590..845249d4a91 100644 --- a/src/platform/graphics/shader-utils.js +++ b/src/platform/graphics/shader-utils.js @@ -1,4 +1,3 @@ -import { Debug } from "../../core/debug.js"; import { SEMANTIC_POSITION, SEMANTIC_NORMAL, SEMANTIC_TANGENT, SEMANTIC_TEXCOORD0, SEMANTIC_TEXCOORD1, SEMANTIC_TEXCOORD2, SEMANTIC_TEXCOORD3, SEMANTIC_TEXCOORD4, SEMANTIC_TEXCOORD5, SEMANTIC_TEXCOORD6, SEMANTIC_TEXCOORD7, @@ -6,10 +5,11 @@ import { SHADERLANGUAGE_WGSL } from './constants.js'; import gles3FS from './shader-chunks/frag/gles3.js'; -import gles3VS from './shader-chunks/vert/gles3.js'; +import sharedFS from './shader-chunks/frag/shared.js'; import webgpuFS from './shader-chunks/frag/webgpu.js'; +import gles3VS from './shader-chunks/vert/gles3.js'; import webgpuVS from './shader-chunks/vert/webgpu.js'; -import sharedFS from './shader-chunks/frag/shared.js'; +import { Debug } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' @@ -114,23 +114,23 @@ class ShaderUtils { } else { // vertex code - vertCode = ShaderUtils.versionCode(device) + + vertCode = `${ShaderUtils.versionCode(device) + getDefines(webgpuVS, gles3VS, true, options) + ShaderUtils.getDefinesCode(options.vertexDefines) + - ShaderUtils.precisionCode(device) + '\n' + - sharedFS + - ShaderUtils.getShaderNameCode(name) + - options.vertexCode; + ShaderUtils.precisionCode(device)}\n${ + sharedFS + }${ShaderUtils.getShaderNameCode(name) + }${options.vertexCode}`; // fragment code - fragCode = (options.fragmentPreamble || '') + + fragCode = `${(options.fragmentPreamble || '') + ShaderUtils.versionCode(device) + getDefines(webgpuFS, gles3FS, false, options) + ShaderUtils.getDefinesCode(options.fragmentDefines) + - ShaderUtils.precisionCode(device) + '\n' + - sharedFS + - ShaderUtils.getShaderNameCode(name) + - (options.fragmentCode || ShaderUtils.dummyFragmentCode()); + ShaderUtils.precisionCode(device)}\n${ + sharedFS + }${ShaderUtils.getShaderNameCode(name) + }${options.fragmentCode || ShaderUtils.dummyFragmentCode()}`; } return { @@ -166,7 +166,7 @@ class ShaderUtils { } static dummyFragmentCode() { - return "void main(void) {gl_FragColor = vec4(0.0);}"; + return 'void main(void) {gl_FragColor = vec4(0.0);}'; } static versionCode(device) { @@ -213,9 +213,9 @@ class ShaderUtils { const attribs = {}; let attrs = 0; - let found = vsCode.indexOf("attribute"); + let found = vsCode.indexOf('attribute'); while (found >= 0) { - if (found > 0 && vsCode[found - 1] === "/") break; + if (found > 0 && vsCode[found - 1] === '/') break; // skip the 'attribute' word inside the #define which we add to the shader let ignore = false; @@ -223,8 +223,9 @@ class ShaderUtils { let startOfLine = vsCode.lastIndexOf('\n', found); startOfLine = startOfLine !== -1 ? startOfLine + 1 : 0; const lineStartString = vsCode.substring(startOfLine, found); - if (lineStartString.includes('#')) + if (lineStartString.includes('#')) { ignore = true; + } } if (!ignore) { @@ -240,13 +241,13 @@ class ShaderUtils { if (semantic !== undefined) { attribs[attribName] = semantic; } else { - attribs[attribName] = "ATTR" + attrs; + attribs[attribName] = `ATTR${attrs}`; attrs++; } } } - found = vsCode.indexOf("attribute", found + 1); + found = vsCode.indexOf('attribute', found + 1); } return attribs; diff --git a/src/platform/graphics/shader.js b/src/platform/graphics/shader.js index d3b5bab0119..52a433412ff 100644 --- a/src/platform/graphics/shader.js +++ b/src/platform/graphics/shader.js @@ -1,9 +1,9 @@ +import { DebugGraphics } from './debug-graphics.js'; +import { ShaderUtils } from './shader-utils.js'; import { TRACEID_SHADER_ALLOC } from '../../core/constants.js'; import { Debug } from '../../core/debug.js'; import { platform } from '../../core/platform.js'; import { Preprocessor } from '../../core/preprocessor.js'; -import { DebugGraphics } from './debug-graphics.js'; -import { ShaderUtils } from './shader-utils.js'; /** * @import { BindGroupFormat } from './bind-group-format.js' diff --git a/src/platform/graphics/storage-buffer.js b/src/platform/graphics/storage-buffer.js index 5e699bd542c..7fa08a0fff3 100644 --- a/src/platform/graphics/storage-buffer.js +++ b/src/platform/graphics/storage-buffer.js @@ -1,6 +1,6 @@ -import { Debug } from '../../core/debug.js'; -import { TRACEID_VRAM_SB } from '../../core/constants.js'; import { BUFFERUSAGE_STORAGE } from './constants.js'; +import { TRACEID_VRAM_SB } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' diff --git a/src/platform/graphics/texture-utils.js b/src/platform/graphics/texture-utils.js index 1407f944f9f..35cffe36a6b 100644 --- a/src/platform/graphics/texture-utils.js +++ b/src/platform/graphics/texture-utils.js @@ -1,8 +1,8 @@ -import { Debug } from '../../core/debug.js'; import { pixelFormatInfo, PIXELFORMAT_PVRTC_2BPP_RGB_1, PIXELFORMAT_PVRTC_2BPP_RGBA_1 } from './constants.js'; +import { Debug } from '../../core/debug.js'; /** * A class providing utility functions for textures. diff --git a/src/platform/graphics/texture.js b/src/platform/graphics/texture.js index d56fbe5e16b..a2889b822a9 100644 --- a/src/platform/graphics/texture.js +++ b/src/platform/graphics/texture.js @@ -1,6 +1,3 @@ -import { Debug } from '../../core/debug.js'; -import { TRACEID_TEXTURE_ALLOC, TRACEID_VRAM_TEXTURE } from '../../core/constants.js'; -import { math } from '../../core/math/math.js'; import { isCompressedPixelFormat, getPixelFormatArrayType, @@ -16,6 +13,9 @@ import { requiresManualGamma } from './constants.js'; import { TextureUtils } from './texture-utils.js'; +import { TRACEID_TEXTURE_ALLOC, TRACEID_VRAM_TEXTURE } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; +import { math } from '../../core/math/math.js'; /** * @import { GraphicsDevice } from './graphics-device.js' @@ -219,10 +219,10 @@ class Texture { */ constructor(graphicsDevice, options = {}) { this.device = graphicsDevice; - Debug.assert(this.device, "Texture constructor requires a graphicsDevice to be valid"); - Debug.assert(!options.width || Number.isInteger(options.width), "Texture width must be an integer number, got", options); - Debug.assert(!options.height || Number.isInteger(options.height), "Texture height must be an integer number, got", options); - Debug.assert(!options.depth || Number.isInteger(options.depth), "Texture depth must be an integer number, got", options); + Debug.assert(this.device, 'Texture constructor requires a graphicsDevice to be valid'); + Debug.assert(!options.width || Number.isInteger(options.width), 'Texture width must be an integer number, got', options); + Debug.assert(!options.height || Number.isInteger(options.height), 'Texture height must be an integer number, got', options); + Debug.assert(!options.depth || Number.isInteger(options.depth), 'Texture depth must be an integer number, got', options); this.name = options.name ?? ''; @@ -424,7 +424,7 @@ class Texture { set minFilter(v) { if (this._minFilter !== v) { if (isIntegerPixelFormat(this._format)) { - Debug.warn("Texture#minFilter: minFilter property cannot be changed on an integer texture, will remain FILTER_NEAREST", this); + Debug.warn('Texture#minFilter: minFilter property cannot be changed on an integer texture, will remain FILTER_NEAREST', this); } else { this._minFilter = v; this.propertyChanged(PROPERTY_MIN_FILTER); @@ -452,7 +452,7 @@ class Texture { set magFilter(v) { if (this._magFilter !== v) { if (isIntegerPixelFormat(this._format)) { - Debug.warn("Texture#magFilter: magFilter property cannot be changed on an integer texture, will remain FILTER_NEAREST", this); + Debug.warn('Texture#magFilter: magFilter property cannot be changed on an integer texture, will remain FILTER_NEAREST', this); } else { this._magFilter = v; this.propertyChanged(PROPERTY_MAG_FILTER); @@ -530,7 +530,7 @@ class Texture { */ set addressW(addressW) { if (!this._volume) { - Debug.warn("pc.Texture#addressW: Can't set W addressing mode for a non-3D texture."); + Debug.warn('pc.Texture#addressW: Can\'t set W addressing mode for a non-3D texture.'); return; } if (addressW !== this._addressW) { @@ -630,9 +630,9 @@ class Texture { if (this._mipmaps !== v) { if (this.device.isWebGPU) { - Debug.warn("Texture#mipmaps: mipmap property is currently not allowed to be changed on WebGPU, create the texture appropriately.", this); + Debug.warn('Texture#mipmaps: mipmap property is currently not allowed to be changed on WebGPU, create the texture appropriately.', this); } else if (isIntegerPixelFormat(this._format)) { - Debug.warn("Texture#mipmaps: mipmap property cannot be changed on an integer texture, will remain false", this); + Debug.warn('Texture#mipmaps: mipmap property cannot be changed on an integer texture, will remain false', this); } else { this._mipmaps = v; } @@ -917,19 +917,22 @@ class Texture { if (!invalid) { // mark levels as updated for (let i = 0; i < 6; i++) { - if (this._levels[mipLevel][i] !== source[i]) + if (this._levels[mipLevel][i] !== source[i]) { this._levelsUpdated[mipLevel][i] = true; + } } } } else { // check if source is valid type of element - if (!this.device._isBrowserInterface(source)) + if (!this.device._isBrowserInterface(source)) { invalid = true; + } if (!invalid) { // mark level as updated - if (source !== this._levels[mipLevel]) + if (source !== this._levels[mipLevel]) { this._levelsUpdated[mipLevel] = true; + } width = source.width; height = source.height; @@ -991,7 +994,7 @@ class Texture { */ unlock() { if (this._lockedMode === TEXTURELOCK_NONE) { - Debug.warn("pc.Texture#unlock: Attempting to unlock a texture that is not locked.", this); + Debug.warn('pc.Texture#unlock: Attempting to unlock a texture that is not locked.', this); } // Upload the new pixel data if locked in write mode (default) diff --git a/src/platform/graphics/transform-feedback.js b/src/platform/graphics/transform-feedback.js index 5c0258d3617..6f9b5c9c83a 100644 --- a/src/platform/graphics/transform-feedback.js +++ b/src/platform/graphics/transform-feedback.js @@ -1,9 +1,9 @@ -import { Debug } from '../../core/debug.js'; import { BUFFER_GPUDYNAMIC, PRIMITIVE_POINTS } from './constants.js'; -import { VertexBuffer } from './vertex-buffer.js'; import { DebugGraphics } from './debug-graphics.js'; -import { Shader } from './shader.js'; import { ShaderUtils } from './shader-utils.js'; +import { Shader } from './shader.js'; +import { VertexBuffer } from './vertex-buffer.js'; +import { Debug } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' @@ -96,7 +96,7 @@ class TransformFeedback { const gl = this.device.gl; Debug.assert(inputBuffer.format.interleaved || inputBuffer.format.elements.length <= 1, - "Vertex buffer used by TransformFeedback needs to be interleaved."); + 'Vertex buffer used by TransformFeedback needs to be interleaved.'); this._inputBuffer = inputBuffer; if (usage === BUFFER_GPUDYNAMIC && inputBuffer.usage !== usage) { @@ -146,7 +146,7 @@ class TransformFeedback { process(shader, swap = true) { const device = this.device; - DebugGraphics.pushGpuMarker(device, "TransformFeedback"); + DebugGraphics.pushGpuMarker(device, 'TransformFeedback'); const oldRt = device.getRenderTarget(); device.setRenderTarget(null); diff --git a/src/platform/graphics/uniform-buffer-format.js b/src/platform/graphics/uniform-buffer-format.js index c53985ae493..7fcda1e949f 100644 --- a/src/platform/graphics/uniform-buffer-format.js +++ b/src/platform/graphics/uniform-buffer-format.js @@ -1,5 +1,3 @@ -import { Debug } from '../../core/debug.js'; -import { math } from '../../core/math/math.js'; import { uniformTypeToName, bindGroupNames, UNIFORMTYPE_BOOL, UNIFORMTYPE_INT, UNIFORMTYPE_FLOAT, UNIFORMTYPE_UINT, UNIFORMTYPE_VEC2, @@ -11,6 +9,8 @@ import { UNIFORMTYPE_BVEC2ARRAY, UNIFORMTYPE_IVEC3ARRAY, UNIFORMTYPE_UVEC3ARRAY, UNIFORMTYPE_BVEC3ARRAY, UNIFORMTYPE_IVEC4ARRAY, UNIFORMTYPE_UVEC4ARRAY, UNIFORMTYPE_BVEC4ARRAY } from './constants.js'; +import { Debug } from '../../core/debug.js'; +import { math } from '../../core/math/math.js'; /** * @import { GraphicsDevice } from './graphics-device.js' @@ -161,8 +161,9 @@ class UniformFormat { this.count = count; Debug.assert(!isNaN(count), `Unsupported uniform: ${name}[${count}]`); Debug.call(() => { - if (isNaN(count)) + if (isNaN(count)) { this.invalid = true; + } }); let componentSize = this.numComponents; @@ -173,8 +174,9 @@ class UniformFormat { } this.byteSize = componentSize * 4; - if (count) + if (count) { this.byteSize *= count; + } Debug.assert(this.byteSize, `Unknown byte size for uniform format ${type} used for ${name}`); } @@ -187,8 +189,9 @@ class UniformFormat { let alignment = this.byteSize <= 8 ? this.byteSize : 16; // arrays have vec4 alignments - if (this.count) + if (this.count) { alignment = 16; + } // align the start offset offset = math.roundUp(offset, alignment); @@ -262,7 +265,7 @@ class UniformBufferFormat { code += ` ${typeString} ${uniform.shortName}${uniform.count ? `[${uniform.count}]` : ''};\n`; }); - return code + '};\n'; + return `${code}};\n`; } } diff --git a/src/platform/graphics/uniform-buffer.js b/src/platform/graphics/uniform-buffer.js index a501fa71d3e..24085f6bee3 100644 --- a/src/platform/graphics/uniform-buffer.js +++ b/src/platform/graphics/uniform-buffer.js @@ -1,4 +1,3 @@ -import { Debug } from '../../core/debug.js'; import { uniformTypeToName, UNIFORMTYPE_INT, UNIFORMTYPE_FLOAT, UNIFORMTYPE_VEC2, UNIFORMTYPE_VEC3, @@ -8,6 +7,7 @@ import { } from './constants.js'; import { DebugGraphics } from './debug-graphics.js'; import { DynamicBufferAllocation } from './dynamic-buffers.js'; +import { Debug } from '../../core/debug.js'; /** * @import { DynamicBindGroup } from './bind-group.js' diff --git a/src/platform/graphics/vertex-buffer.js b/src/platform/graphics/vertex-buffer.js index 74c4fb66e8f..38adc3b5c98 100644 --- a/src/platform/graphics/vertex-buffer.js +++ b/src/platform/graphics/vertex-buffer.js @@ -1,6 +1,6 @@ -import { Debug } from '../../core/debug.js'; -import { TRACEID_VRAM_VB } from '../../core/constants.js'; import { BUFFER_STATIC } from './constants.js'; +import { TRACEID_VRAM_VB } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; /** * @import { GraphicsDevice } from './graphics-device.js' diff --git a/src/platform/graphics/vertex-format.js b/src/platform/graphics/vertex-format.js index be05e473b27..6988007370c 100644 --- a/src/platform/graphics/vertex-format.js +++ b/src/platform/graphics/vertex-format.js @@ -1,12 +1,12 @@ -import { Debug } from '../../core/debug.js'; -import { hashCode } from '../../core/hash.js'; -import { math } from '../../core/math/math.js'; -import { StringIds } from '../../core/string-ids.js'; import { SEMANTIC_TEXCOORD0, SEMANTIC_TEXCOORD1, SEMANTIC_ATTR12, SEMANTIC_ATTR13, SEMANTIC_ATTR14, SEMANTIC_ATTR15, SEMANTIC_COLOR, SEMANTIC_TANGENT, TYPE_FLOAT32, typedArrayTypesByteSize, vertexTypesNames } from './constants.js'; import { DeviceCache } from './device-cache.js'; +import { Debug } from '../../core/debug.js'; +import { hashCode } from '../../core/hash.js'; +import { math } from '../../core/math/math.js'; +import { StringIds } from '../../core/string-ids.js'; /** * @import { GraphicsDevice } from './graphics-device.js' @@ -162,7 +162,7 @@ class VertexFormat { // WebGPU has limited element size support (for example uint16x3 is not supported) Debug.assert(VertexFormat.isElementValid(graphicsDevice, elementDesc), - `WebGPU does not support the format of vertex element ${elementDesc.semantic} : ${vertexTypesNames[elementDesc.type]} x ${elementDesc.components}`); + `WebGPU does not support the format of vertex element ${elementDesc.semantic} : ${vertexTypesNames[elementDesc.type]} x ${elementDesc.components}`); // align up the offset to elementSize (when vertexCount is specified only - case of non-interleaved format) if (vertexCount) { @@ -171,7 +171,7 @@ class VertexFormat { // non-interleaved format with elementSize not multiple of 4 might be slower on some platforms - padding is recommended to align its size // example: use 4 x TYPE_UINT8 instead of 3 x TYPE_UINT8 Debug.assert((elementSize % 4) === 0, - `Non-interleaved vertex format with element size not multiple of 4 can have performance impact on some platforms. Element size: ${elementSize}`); + `Non-interleaved vertex format with element size not multiple of 4 can have performance impact on some platforms. Element size: ${elementSize}`); } const asInt = elementDesc.asInt ?? false; @@ -238,8 +238,9 @@ class VertexFormat { static isElementValid(graphicsDevice, elementDesc) { const elementSize = elementDesc.components * typedArrayTypesByteSize[elementDesc.type]; - if (graphicsDevice.isWebGPU && !webgpuValidElementSizes.includes(elementSize)) + if (graphicsDevice.isWebGPU && !webgpuValidElementSizes.includes(elementSize)) { return false; + } return true; } @@ -250,7 +251,7 @@ class VertexFormat { */ update() { // Note that this is used only by vertex attribute morphing on the WebGL. - Debug.assert(!this.device.isWebGPU, `VertexFormat#update is not supported on WebGPU and VertexFormat cannot be modified.`); + Debug.assert(!this.device.isWebGPU, 'VertexFormat#update is not supported on WebGPU and VertexFormat cannot be modified.'); this._evaluateHash(); } diff --git a/src/platform/graphics/vertex-iterator.js b/src/platform/graphics/vertex-iterator.js index bf77cabfb26..425bd715fdd 100644 --- a/src/platform/graphics/vertex-iterator.js +++ b/src/platform/graphics/vertex-iterator.js @@ -1,5 +1,5 @@ -import { Debug } from '../../core/debug.js'; import { typedArrayTypes } from './constants.js'; +import { Debug } from '../../core/debug.js'; /** * @import { ScopeId } from './scope-id.js' @@ -343,8 +343,9 @@ class VertexIterator { element.array.set(data); } else { // data is array, copy right amount manually - for (let i = 0; i < copyCount; i++) + for (let i = 0; i < copyCount; i++) { element.array[i] = data[i]; + } } } else { // copy whole data @@ -376,8 +377,9 @@ class VertexIterator { if (this.vertexBuffer.getFormat().interleaved) { // extract data from interleaved buffer by looping over vertices and copying them manually - if (Array.isArray(data)) + if (Array.isArray(data)) { data.length = 0; + } element.index = 0; let offset = 0; @@ -393,8 +395,9 @@ class VertexIterator { // destination data is array data.length = 0; const copyCount = count * numComponents; - for (i = 0; i < copyCount; i++) + for (i = 0; i < copyCount; i++) { data[i] = element.array[i]; + } } } } diff --git a/src/platform/graphics/webgl/webgl-gpu-profiler.js b/src/platform/graphics/webgl/webgl-gpu-profiler.js index ad83e52d642..d8f70fb3198 100644 --- a/src/platform/graphics/webgl/webgl-gpu-profiler.js +++ b/src/platform/graphics/webgl/webgl-gpu-profiler.js @@ -1,4 +1,4 @@ -import { GpuProfiler } from "../gpu-profiler.js"; +import { GpuProfiler } from '../gpu-profiler.js'; /** * Class holding information about the queries for a single frame. diff --git a/src/platform/graphics/webgl/webgl-graphics-device.js b/src/platform/graphics/webgl/webgl-graphics-device.js index 96e0b5e6a74..2c7f647bbe2 100644 --- a/src/platform/graphics/webgl/webgl-graphics-device.js +++ b/src/platform/graphics/webgl/webgl-graphics-device.js @@ -1,7 +1,14 @@ -import { math } from '../../../core/math/math.js'; +import { WebglGpuProfiler } from './webgl-gpu-profiler.js'; +import { WebglIndexBuffer } from './webgl-index-buffer.js'; +import { WebglRenderTarget } from './webgl-render-target.js'; +import { WebglShader } from './webgl-shader.js'; +import { WebglTexture } from './webgl-texture.js'; +import { WebglVertexBuffer } from './webgl-vertex-buffer.js'; import { Debug } from '../../../core/debug.js'; -import { platform } from '../../../core/platform.js'; import { Color } from '../../../core/math/color.js'; +import { math } from '../../../core/math/math.js'; +import { platform } from '../../../core/platform.js'; +import { BlendState } from '../blend-state.js'; import { CLEARFLAG_COLOR, CLEARFLAG_DEPTH, CLEARFLAG_STENCIL, CULLFACE_NONE, @@ -24,22 +31,15 @@ import { UNIFORMTYPE_TEXTURE2D_ARRAY, DEVICETYPE_WEBGL2 } from '../constants.js'; +import { DebugGraphics } from '../debug-graphics.js'; +import { DepthState } from '../depth-state.js'; import { GraphicsDevice } from '../graphics-device.js'; import { RenderTarget } from '../render-target.js'; -import { Texture } from '../texture.js'; -import { DebugGraphics } from '../debug-graphics.js'; -import { WebglVertexBuffer } from './webgl-vertex-buffer.js'; -import { WebglIndexBuffer } from './webgl-index-buffer.js'; -import { WebglShader } from './webgl-shader.js'; -import { WebglTexture } from './webgl-texture.js'; -import { WebglRenderTarget } from './webgl-render-target.js'; import { ShaderUtils } from '../shader-utils.js'; import { Shader } from '../shader.js'; -import { BlendState } from '../blend-state.js'; -import { DepthState } from '../depth-state.js'; import { StencilParameters } from '../stencil-parameters.js'; -import { WebglGpuProfiler } from './webgl-gpu-profiler.js'; import { TextureUtils } from '../texture-utils.js'; +import { Texture } from '../texture.js'; /** * @import { RenderPass } from '../render-pass.js' @@ -148,7 +148,7 @@ class WebglGraphicsDevice extends GraphicsDevice { this.forceDisableMultisampling = ua && ua.includes('AppleWebKit') && (ua.includes('15.4') || ua.includes('15_4')); if (this.forceDisableMultisampling) { options.antialias = false; - Debug.log("Antialiasing has been turned off due to rendering issues on AppleWebKit 15.4"); + Debug.log('Antialiasing has been turned off due to rendering issues on AppleWebKit 15.4'); } // #5856 - turn off antialiasing on Windows Firefox @@ -160,7 +160,7 @@ class WebglGraphicsDevice extends GraphicsDevice { const version = parseFloat(firefoxVersion); if (version >= 120 || version === 115) { options.antialias = false; - Debug.log("Antialiasing has been turned off due to rendering issues on Windows Firefox esr115 and 120+. Current version: " + firefoxVersion); + Debug.log(`Antialiasing has been turned off due to rendering issues on Windows Firefox esr115 and 120+. Current version: ${firefoxVersion}`); } } } @@ -174,7 +174,7 @@ class WebglGraphicsDevice extends GraphicsDevice { const gl = options.gl ?? canvas.getContext('webgl2', options); if (!gl) { - throw new Error("WebGL not supported"); + throw new Error('WebGL not supported'); } this.gl = gl; @@ -186,7 +186,7 @@ class WebglGraphicsDevice extends GraphicsDevice { const isChrome = platform.browserName === 'chrome'; const isSafari = platform.browserName === 'safari'; - const isMac = platform.browser && navigator.appVersion.indexOf("Mac") !== -1; + const isMac = platform.browser && navigator.appVersion.indexOf('Mac') !== -1; // enable temporary texture unit workaround on desktop safari this._tempEnableSafariTextureUnitWorkaround = isSafari; @@ -194,8 +194,8 @@ class WebglGraphicsDevice extends GraphicsDevice { // enable temporary workaround for glBlitFramebuffer failing on Mac Chrome (#2504) this._tempMacChromeBlitFramebufferWorkaround = isMac && isChrome && !options.alpha; - canvas.addEventListener("webglcontextlost", this._contextLostHandler, false); - canvas.addEventListener("webglcontextrestored", this._contextRestoredHandler, false); + canvas.addEventListener('webglcontextlost', this._contextLostHandler, false); + canvas.addEventListener('webglcontextrestored', this._contextRestoredHandler, false); this.initializeExtensions(); this.initializeCapabilities(); @@ -577,7 +577,7 @@ class WebglGraphicsDevice extends GraphicsDevice { gl.uniformMatrix4fv(uniform.locationId, false, value); }; - this.constantTexSource = this.scope.resolve("source"); + this.constantTexSource = this.scope.resolve('source'); // In WebGL2 float texture renderability is dictated by the EXT_color_buffer_float extension this.textureFloatRenderable = !!this.extColorBufferFloat; @@ -693,10 +693,11 @@ class WebglGraphicsDevice extends GraphicsDevice { popMarker() { if (platform.browser && window.spector) { const label = DebugGraphics.toString(); - if (label.length) + if (label.length) { window.spector.setMarker(`${label} #`); - else + } else { window.spector.clearMarker(); + } } } // #endif @@ -711,7 +712,7 @@ class WebglGraphicsDevice extends GraphicsDevice { */ getPrecision() { const gl = this.gl; - let precision = "highp"; + let precision = 'highp'; if (gl.getShaderPrecisionFormat) { const vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT); @@ -727,11 +728,11 @@ class WebglGraphicsDevice extends GraphicsDevice { if (!highpAvailable) { if (mediumpAvailable) { - precision = "mediump"; - Debug.warn("WARNING: highp not supported, using mediump"); + precision = 'mediump'; + Debug.warn('WARNING: highp not supported, using mediump'); } else { - precision = "lowp"; - Debug.warn("WARNING: highp and mediump not supported, using lowp"); + precision = 'lowp'; + Debug.warn('WARNING: highp and mediump not supported, using lowp'); } } } @@ -774,10 +775,10 @@ class WebglGraphicsDevice extends GraphicsDevice { this.extDebugRendererInfo = this.getExtension('WEBGL_debug_renderer_info'); - this.extTextureFloatLinear = this.getExtension("OES_texture_float_linear"); + this.extTextureFloatLinear = this.getExtension('OES_texture_float_linear'); this.textureFloatFilterable = !!this.extTextureFloatLinear; - this.extFloatBlend = this.getExtension("EXT_float_blend"); + this.extFloatBlend = this.getExtension('EXT_float_blend'); this.extTextureFilterAnisotropic = this.getExtension('EXT_texture_filter_anisotropic', 'WEBKIT_EXT_texture_filter_anisotropic'); this.extParallelShaderCompile = this.getExtension('KHR_parallel_shader_compile'); @@ -790,7 +791,7 @@ class WebglGraphicsDevice extends GraphicsDevice { this.extCompressedTextureASTC = this.getExtension('WEBGL_compressed_texture_astc'); // iOS exposes this for half precision render targets on WebGL2 from iOS v 14.5beta - this.extColorBufferHalfFloat = this.getExtension("EXT_color_buffer_half_float"); + this.extColorBufferHalfFloat = this.getExtension('EXT_color_buffer_half_float'); } /** @@ -802,7 +803,7 @@ class WebglGraphicsDevice extends GraphicsDevice { const gl = this.gl; let ext; - const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : ""; + const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : ''; this.maxPrecision = this.precision = this.getPrecision(); @@ -1065,17 +1066,17 @@ class WebglGraphicsDevice extends GraphicsDevice { if (!dest) { // copying to backbuffer if (!source._colorBuffer) { - Debug.error("Can't copy empty color buffer to backbuffer"); + Debug.error('Can\'t copy empty color buffer to backbuffer'); return false; } } else if (source) { // copying to render target if (!source._colorBuffer || !dest._colorBuffer) { - Debug.error("Can't copy color buffer, because one of the render targets doesn't have it"); + Debug.error('Can\'t copy color buffer, because one of the render targets doesn\'t have it'); return false; } if (source._colorBuffer._format !== dest._colorBuffer._format) { - Debug.error("Can't copy render targets of different color formats"); + Debug.error('Can\'t copy render targets of different color formats'); return false; } } @@ -1083,11 +1084,11 @@ class WebglGraphicsDevice extends GraphicsDevice { if (depth && source) { if (!source._depth) { // when depth is automatic, we cannot test the buffer nor its format if (!source._depthBuffer || !dest._depthBuffer) { - Debug.error("Can't copy depth buffer, because one of the render targets doesn't have it"); + Debug.error('Can\'t copy depth buffer, because one of the render targets doesn\'t have it'); return false; } if (source._depthBuffer._format !== dest._depthBuffer._format) { - Debug.error("Can't copy render targets of different depth formats"); + Debug.error('Can\'t copy render targets of different depth formats'); return false; } } @@ -1111,9 +1112,9 @@ class WebglGraphicsDevice extends GraphicsDevice { const h = source ? source.height : dest ? dest.height : this.height; gl.blitFramebuffer(0, 0, w, h, - 0, 0, w, h, - (color ? gl.COLOR_BUFFER_BIT : 0) | (depth ? gl.DEPTH_BUFFER_BIT : 0), - gl.NEAREST); + 0, 0, w, h, + (color ? gl.COLOR_BUFFER_BIT : 0) | (depth ? gl.DEPTH_BUFFER_BIT : 0), + gl.NEAREST); // TODO: not sure we need to restore the prev target, as this only should run in-between render passes this.renderTarget = prevRt; @@ -1179,7 +1180,7 @@ class WebglGraphicsDevice extends GraphicsDevice { startRenderPass(renderPass) { DebugGraphics.pushGpuMarker(this, `Pass:${renderPass.name}`); - DebugGraphics.pushGpuMarker(this, `START-PASS`); + DebugGraphics.pushGpuMarker(this, 'START-PASS'); // set up render target const rt = renderPass.renderTarget ?? this.backBuffer; @@ -1239,7 +1240,7 @@ class WebglGraphicsDevice extends GraphicsDevice { */ endRenderPass(renderPass) { - DebugGraphics.pushGpuMarker(this, `END-PASS`); + DebugGraphics.pushGpuMarker(this, 'END-PASS'); this.unbindVertexArray(); @@ -1370,7 +1371,7 @@ class WebglGraphicsDevice extends GraphicsDevice { */ updateEnd() { - DebugGraphics.pushGpuMarker(this, `UPDATE-END`); + DebugGraphics.pushGpuMarker(this, 'UPDATE-END'); this.unbindVertexArray(); @@ -1540,8 +1541,9 @@ class WebglGraphicsDevice extends GraphicsDevice { setTexture(texture, textureUnit) { const impl = texture.impl; - if (!impl._glTexture) + if (!impl._glTexture) { impl.initialize(this, texture); + } if (impl.dirtyParameterFlags > 0 || texture._needsUpload || texture._needsMipmapsUpload) { @@ -1580,7 +1582,7 @@ class WebglGraphicsDevice extends GraphicsDevice { if (useCache) { // generate unique key for the vertex buffers - key = ""; + key = ''; for (let i = 0; i < vertexBuffers.length; i++) { const vertexBuffer = vertexBuffers[i]; key += vertexBuffer.id + vertexBuffer.format.renderingHash; @@ -1644,7 +1646,7 @@ class WebglGraphicsDevice extends GraphicsDevice { } if (!locZero) { - Debug.warn("No vertex attribute is mapped to location 0, which might cause compatibility issues on Safari on MacOS - please use attribute SEMANTIC_POSITION or SEMANTIC_ATTR15"); + Debug.warn('No vertex attribute is mapped to location 0, which might cause compatibility issues on Safari on MacOS - please use attribute SEMANTIC_POSITION or SEMANTIC_ATTR15'); } } @@ -1668,7 +1670,7 @@ class WebglGraphicsDevice extends GraphicsDevice { // single VB keeps its VAO const vertexBuffer = this.vertexBuffers[0]; - Debug.assert(vertexBuffer.device === this, "The VertexBuffer was not created using current GraphicsDevice"); + Debug.assert(vertexBuffer.device === this, 'The VertexBuffer was not created using current GraphicsDevice'); if (!vertexBuffer.impl.vao) { vertexBuffer.impl.vao = this.createVertexArray(this.vertexBuffers); } @@ -1732,14 +1734,16 @@ class WebglGraphicsDevice extends GraphicsDevice { const gl = this.gl; this.activateShader(this); - if (!this.shaderValid) + if (!this.shaderValid) { return; + } let sampler, samplerValue, texture, numTextures; // Samplers let uniform, scopeId, uniformVersion, programVersion; // Uniforms const shader = this.shader; - if (!shader) + if (!shader) { return; + } const samplers = shader.impl.samplers; const uniforms = shader.impl.uniforms; @@ -1758,8 +1762,8 @@ class WebglGraphicsDevice extends GraphicsDevice { // #if _DEBUG const samplerName = sampler.scopeId.name; - Debug.assert(samplerName !== 'texture_grabPass', `Engine provided texture with sampler name 'texture_grabPass' is not longer supported, use 'uSceneColorMap' instead`); - Debug.assert(samplerName !== 'uDepthMap', `Engine provided texture with sampler name 'uDepthMap' is not longer supported, use 'uSceneDepthMap' instead`); + Debug.assert(samplerName !== 'texture_grabPass', 'Engine provided texture with sampler name \'texture_grabPass\' is not longer supported, use \'uSceneColorMap\' instead'); + Debug.assert(samplerName !== 'uDepthMap', 'Engine provided texture with sampler name \'uDepthMap\' is not longer supported, use \'uSceneDepthMap\' instead'); if (samplerName === 'uSceneDepthMap') { Debug.warnOnce('A sampler uSceneDepthMap is used by the shader but a scene depth texture is not available. Use CameraComponent.requestSceneDepthMap / enable Depth Grabpass on the Camera Component to enable it.'); @@ -1784,9 +1788,9 @@ class WebglGraphicsDevice extends GraphicsDevice { // Set breakpoint here to debug "Source and destination textures of the draw are the same" errors if (this.renderTarget._samples < 2) { if (this.renderTarget.colorBuffer && this.renderTarget.colorBuffer === texture) { - Debug.error("Trying to bind current color buffer as a texture", { renderTarget: this.renderTarget, texture }); + Debug.error('Trying to bind current color buffer as a texture', { renderTarget: this.renderTarget, texture }); } else if (this.renderTarget.depthBuffer && this.renderTarget.depthBuffer === texture) { - Debug.error("Trying to bind current depth buffer as a texture", { texture }); + Debug.error('Trying to bind current depth buffer as a texture', { texture }); } } } @@ -1844,7 +1848,7 @@ class WebglGraphicsDevice extends GraphicsDevice { if (primitive.indexed) { const indexBuffer = this.indexBuffer; - Debug.assert(indexBuffer.device === this, "The IndexBuffer was not created using current GraphicsDevice"); + Debug.assert(indexBuffer.device === this, 'The IndexBuffer was not created using current GraphicsDevice'); const format = indexBuffer.impl.glFormat; const offset = primitive.base * indexBuffer.bytesPerIndex; @@ -2248,7 +2252,7 @@ class WebglGraphicsDevice extends GraphicsDevice { currentBlendState.alphaSrcFactor !== alphaSrcFactor || currentBlendState.alphaDstFactor !== alphaDstFactor) { gl.blendFuncSeparate(this.glBlendFunctionColor[colorSrcFactor], this.glBlendFunctionColor[colorDstFactor], - this.glBlendFunctionAlpha[alphaSrcFactor], this.glBlendFunctionAlpha[alphaDstFactor]); + this.glBlendFunctionAlpha[alphaSrcFactor], this.glBlendFunctionAlpha[alphaDstFactor]); } // color write diff --git a/src/platform/graphics/webgl/webgl-index-buffer.js b/src/platform/graphics/webgl/webgl-index-buffer.js index 94badaeaf25..0d223ac6e6b 100644 --- a/src/platform/graphics/webgl/webgl-index-buffer.js +++ b/src/platform/graphics/webgl/webgl-index-buffer.js @@ -1,5 +1,5 @@ +import { WebglBuffer } from './webgl-buffer.js'; import { INDEXFORMAT_UINT8, INDEXFORMAT_UINT16, INDEXFORMAT_UINT32 } from '../constants.js'; -import { WebglBuffer } from "./webgl-buffer.js"; /** * A WebGL implementation of the IndexBuffer. diff --git a/src/platform/graphics/webgl/webgl-render-target.js b/src/platform/graphics/webgl/webgl-render-target.js index 4078c0fb3eb..25012cfd4af 100644 --- a/src/platform/graphics/webgl/webgl-render-target.js +++ b/src/platform/graphics/webgl/webgl-render-target.js @@ -1,6 +1,6 @@ -import { Debug } from "../../../core/debug.js"; -import { PIXELFORMAT_RGBA8 } from "../constants.js"; -import { DebugGraphics } from "../debug-graphics.js"; +import { Debug } from '../../../core/debug.js'; +import { PIXELFORMAT_RGBA8 } from '../constants.js'; +import { DebugGraphics } from '../debug-graphics.js'; /** * @import { RenderTarget } from '../render-target.js' @@ -86,8 +86,9 @@ class WebglRenderTarget { this._isInitialized = false; if (this._glFrameBuffer) { - if (this._glFrameBuffer !== this.suppliedColorFramebuffer) + if (this._glFrameBuffer !== this.suppliedColorFramebuffer) { gl.deleteFramebuffer(this._glFrameBuffer); + } this._glFrameBuffer = null; } @@ -97,8 +98,9 @@ class WebglRenderTarget { } if (this._glResolveFrameBuffer) { - if (this._glResolveFrameBuffer !== this.suppliedColorFramebuffer) + if (this._glResolveFrameBuffer !== this.suppliedColorFramebuffer) { gl.deleteFramebuffer(this._glResolveFrameBuffer); + } this._glResolveFrameBuffer = null; } @@ -178,12 +180,12 @@ class WebglRenderTarget { // Attach if (target._stencil) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, - depthBuffer._cubemap ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + target._face : gl.TEXTURE_2D, - target._depthBuffer.impl._glTexture, 0); + depthBuffer._cubemap ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + target._face : gl.TEXTURE_2D, + target._depthBuffer.impl._glTexture, 0); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, - depthBuffer._cubemap ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + target._face : gl.TEXTURE_2D, - target._depthBuffer.impl._glTexture, 0); + depthBuffer._cubemap ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + target._face : gl.TEXTURE_2D, + target._depthBuffer.impl._glTexture, 0); } } else if (target._depth) { // --- Init a new depth/stencil buffer (optional) --- @@ -306,9 +308,9 @@ class WebglRenderTarget { const dstFramebuffer = gl.createFramebuffer(); device.setFramebuffer(dstFramebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, - colorBuffer._cubemap ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + target._face : gl.TEXTURE_2D, - colorBuffer.impl._glTexture, - 0 + colorBuffer._cubemap ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + target._face : gl.TEXTURE_2D, + colorBuffer.impl._glTexture, + 0 ); this.colorMrtFramebuffers[i] = new FramebufferPair(srcFramebuffer, dstFramebuffer); @@ -369,9 +371,9 @@ class WebglRenderTarget { gl.bindFramebuffer(gl.READ_FRAMEBUFFER, src); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, dst); gl.blitFramebuffer(0, 0, target.width, target.height, - 0, 0, target.width, target.height, - mask, - gl.NEAREST); + 0, 0, target.width, target.height, + mask, + gl.NEAREST); } resolve(device, target, color, depth) { @@ -393,15 +395,15 @@ class WebglRenderTarget { // depth if (depth) { - DebugGraphics.pushGpuMarker(device, `RESOLVE-MRT-DEPTH`); + DebugGraphics.pushGpuMarker(device, 'RESOLVE-MRT-DEPTH'); this.internalResolve(device, this._glFrameBuffer, this._glResolveFrameBuffer, target, gl.DEPTH_BUFFER_BIT); DebugGraphics.popGpuMarker(device); } } else { - DebugGraphics.pushGpuMarker(device, `RESOLVE`); + DebugGraphics.pushGpuMarker(device, 'RESOLVE'); this.internalResolve(device, this._glFrameBuffer, this._glResolveFrameBuffer, target, - (color ? gl.COLOR_BUFFER_BIT : 0) | (depth ? gl.DEPTH_BUFFER_BIT : 0)); + (color ? gl.COLOR_BUFFER_BIT : 0) | (depth ? gl.DEPTH_BUFFER_BIT : 0)); DebugGraphics.popGpuMarker(device); } diff --git a/src/platform/graphics/webgl/webgl-shader-input.js b/src/platform/graphics/webgl/webgl-shader-input.js index da0ad570a03..79de9dda451 100644 --- a/src/platform/graphics/webgl/webgl-shader-input.js +++ b/src/platform/graphics/webgl/webgl-shader-input.js @@ -1,4 +1,3 @@ -import { Version } from '../version.js'; import { UNIFORMTYPE_FLOAT, UNIFORMTYPE_FLOATARRAY, UNIFORMTYPE_VEC2, UNIFORMTYPE_VEC3, UNIFORMTYPE_VEC4, UNIFORMTYPE_VEC2ARRAY, UNIFORMTYPE_VEC3ARRAY, UNIFORMTYPE_VEC4ARRAY, UNIFORMTYPE_INT, @@ -9,6 +8,7 @@ import { UNIFORMTYPE_IVEC3ARRAY, UNIFORMTYPE_UVEC3ARRAY, UNIFORMTYPE_BVEC3ARRAY, UNIFORMTYPE_IVEC4ARRAY, UNIFORMTYPE_UVEC4ARRAY, UNIFORMTYPE_BVEC4ARRAY } from '../constants.js'; +import { Version } from '../version.js'; /** * @import { GraphicsDevice } from '../graphics-device.js' @@ -37,7 +37,7 @@ class WebglShaderInput { this.version = new Version(); // custom data type for arrays - if (name.substring(name.length - 3) === "[0]") { + if (name.substring(name.length - 3) === '[0]') { switch (type) { case UNIFORMTYPE_FLOAT: type = UNIFORMTYPE_FLOATARRAY; break; case UNIFORMTYPE_INT: type = UNIFORMTYPE_INTARRAY; break; diff --git a/src/platform/graphics/webgl/webgl-shader.js b/src/platform/graphics/webgl/webgl-shader.js index d88c0d8966c..659de79cbf2 100644 --- a/src/platform/graphics/webgl/webgl-shader.js +++ b/src/platform/graphics/webgl/webgl-shader.js @@ -1,10 +1,10 @@ -import { Debug } from '../../../core/debug.js'; +import { WebglShaderInput } from './webgl-shader-input.js'; import { TRACEID_SHADER_COMPILE } from '../../../core/constants.js'; +import { Debug } from '../../../core/debug.js'; import { now } from '../../../core/time.js'; -import { WebglShaderInput } from './webgl-shader-input.js'; import { SHADERTAG_MATERIAL, semanticToLocation } from '../constants.js'; -import { DeviceCache } from '../device-cache.js'; import { DebugGraphics } from '../debug-graphics.js'; +import { DeviceCache } from '../device-cache.js'; /** * @import { Shader } from '../shader.js' @@ -123,8 +123,9 @@ class WebglShader { link(device, shader) { // if the shader was already linked - if (this.glProgram) + if (this.glProgram) { return; + } // if the device is lost, silently ignore const gl = device.gl; @@ -151,7 +152,7 @@ class WebglShader { const outNames = []; for (const attr in attrs) { if (attrs.hasOwnProperty(attr)) { - outNames.push("out_" + attr); + outNames.push(`out_${attr}`); } } gl.transformFeedbackVaryings(glProgram, outNames, gl.INTERLEAVED_ATTRIBS); @@ -284,13 +285,15 @@ class WebglShader { if (!linkStatus) { // Check for compilation errors - if (!this._isCompiled(device, shader, this.glVertexShader, definition.vshader, "vertex")) + if (!this._isCompiled(device, shader, this.glVertexShader, definition.vshader, 'vertex')) { return false; + } - if (!this._isCompiled(device, shader, this.glFragmentShader, definition.fshader, "fragment")) + if (!this._isCompiled(device, shader, this.glFragmentShader, definition.fshader, 'fragment')) { return false; + } - const message = "Failed to link shader program. Error: " + gl.getProgramInfoLog(glProgram); + const message = `Failed to link shader program. Error: ${gl.getProgramInfoLog(glProgram)}`; // #if _DEBUG @@ -313,8 +316,9 @@ class WebglShader { const location = gl.getAttribLocation(glProgram, info.name); // a built-in attributes for which we do not need to provide any data - if (_vertexShaderBuiltins.has(info.name)) + if (_vertexShaderBuiltins.has(info.name)) { continue; + } // Check attributes are correctly linked up if (definition.attributes[info.name] === undefined) { @@ -431,7 +435,7 @@ class WebglShader { // if error is in the code, only show nearby lines instead of whole shader code if (infoLog && infoLog.startsWith('ERROR:')) { - const match = infoLog.match(/^ERROR:\s([0-9]+):([0-9]+):\s*(.+)/); + const match = infoLog.match(/^ERROR:\s(\d+):(\d+):\s*(.+)/); if (match) { error.message = match[3]; error.line = parseInt(match[2], 10); @@ -443,7 +447,7 @@ class WebglShader { // Chrome reports shader errors on lines indexed from 1 for (let i = from; i < to; i++) { - code += (i + 1) + ":\t" + lines[i] + '\n'; + code += `${i + 1}:\t${lines[i]}\n`; } error.source = src; diff --git a/src/platform/graphics/webgl/webgl-texture.js b/src/platform/graphics/webgl/webgl-texture.js index 703aac50bf2..1395a055845 100644 --- a/src/platform/graphics/webgl/webgl-texture.js +++ b/src/platform/graphics/webgl/webgl-texture.js @@ -166,10 +166,10 @@ class WebglTexture { break; case PIXELFORMAT_BGRA8: case PIXELFORMAT_SBGRA8: - Debug.error("BGRA8 and SBGRA8 texture formats are not supported by WebGL."); + Debug.error('BGRA8 and SBGRA8 texture formats are not supported by WebGL.'); break; - // compressed formats ---- + // compressed formats ---- case PIXELFORMAT_DXT1: this._glFormat = gl.RGB; @@ -224,7 +224,7 @@ class WebglTexture { this._glInternalFormat = device.extCompressedTextureATC.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL; break; - // compressed sRGB formats ---- + // compressed sRGB formats ---- case PIXELFORMAT_DXT1_SRGB: this._glFormat = gl.SRGB; @@ -267,7 +267,7 @@ class WebglTexture { this._glInternalFormat = device.extCompressedTextureASTC.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; break; - // ------------------ + // ------------------ case PIXELFORMAT_R16F: this._glFormat = gl.RED; @@ -436,11 +436,12 @@ class WebglTexture { */ upload(device, texture) { - Debug.assert(texture.device, "Attempting to use a texture that has been destroyed.", texture); + Debug.assert(texture.device, 'Attempting to use a texture that has been destroyed.', texture); const gl = device.gl; - if (!texture._needsUpload && ((texture._needsMipmapsUpload && texture._mipmapsUploaded) || !texture.pot)) + if (!texture._needsUpload && ((texture._needsMipmapsUpload && texture._mipmapsUploaded) || !texture.pot)) { return; + } let mipLevel = 0; let mipObject; @@ -451,11 +452,11 @@ class WebglTexture { if (texture.array) { // for texture arrays we reserve the space in advance gl.texStorage3D(gl.TEXTURE_2D_ARRAY, - requiredMipLevels, - this._glInternalFormat, - texture._width, - texture._height, - texture._arrayLength); + requiredMipLevels, + this._glInternalFormat, + texture._width, + texture._height, + texture._arrayLength); } // Upload all existing mip levels. Initialize 0 mip anyway. @@ -486,8 +487,9 @@ class WebglTexture { if (device._isBrowserInterface(mipObject[0])) { // Upload the image, canvas or video for (face = 0; face < 6; face++) { - if (!texture._levelsUpdated[0][face]) + if (!texture._levelsUpdated[0][face]) { continue; + } let src = mipObject[face]; // Downsize images that are too large to be used as cube maps @@ -528,8 +530,9 @@ class WebglTexture { // Upload the byte array resMult = 1 / Math.pow(2, mipLevel); for (face = 0; face < 6; face++) { - if (!texture._levelsUpdated[0][face]) + if (!texture._levelsUpdated[0][face]) { continue; + } const texData = mipObject[face]; if (texture._compressed) { @@ -589,28 +592,28 @@ class WebglTexture { // Upload the byte array if (texture._compressed) { gl.compressedTexImage3D(gl.TEXTURE_3D, - mipLevel, - this._glInternalFormat, - Math.max(texture._width * resMult, 1), - Math.max(texture._height * resMult, 1), - Math.max(texture._depth * resMult, 1), - 0, - mipObject); + mipLevel, + this._glInternalFormat, + Math.max(texture._width * resMult, 1), + Math.max(texture._height * resMult, 1), + Math.max(texture._depth * resMult, 1), + 0, + mipObject); } else { device.setUnpackFlipY(false); device.setUnpackPremultiplyAlpha(texture._premultiplyAlpha); gl.texImage3D(gl.TEXTURE_3D, - mipLevel, - this._glInternalFormat, - Math.max(texture._width * resMult, 1), - Math.max(texture._height * resMult, 1), - Math.max(texture._depth * resMult, 1), - 0, - this._glFormat, - this._glPixelType, - mipObject); + mipLevel, + this._glInternalFormat, + Math.max(texture._width * resMult, 1), + Math.max(texture._height * resMult, 1), + Math.max(texture._depth * resMult, 1), + 0, + this._glFormat, + this._glPixelType, + mipObject); } - } else if (texture.array && typeof mipObject === "object") { + } else if (texture.array && typeof mipObject === 'object') { if (texture._arrayLength === mipObject.length) { if (texture._compressed) { for (let index = 0; index < texture._arrayLength; index++) { @@ -758,8 +761,9 @@ class WebglTexture { if (texture._needsUpload) { if (texture._cubemap) { - for (let i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { texture._levelsUpdated[0][i] = false; + } } else { texture._levelsUpdated[0] = false; } diff --git a/src/platform/graphics/webgl/webgl-vertex-buffer.js b/src/platform/graphics/webgl/webgl-vertex-buffer.js index f2c1991ce65..c1d1c576db3 100644 --- a/src/platform/graphics/webgl/webgl-vertex-buffer.js +++ b/src/platform/graphics/webgl/webgl-vertex-buffer.js @@ -1,4 +1,4 @@ -import { WebglBuffer } from "./webgl-buffer.js"; +import { WebglBuffer } from './webgl-buffer.js'; /** * A WebGL implementation of the VertexBuffer. diff --git a/src/platform/graphics/webgpu/webgpu-bind-group-format.js b/src/platform/graphics/webgpu/webgpu-bind-group-format.js index 6d7e189fef3..8d672842ef2 100644 --- a/src/platform/graphics/webgpu/webgpu-bind-group-format.js +++ b/src/platform/graphics/webgpu/webgpu-bind-group-format.js @@ -1,8 +1,8 @@ +import { gpuTextureFormats } from './constants.js'; +import { WebgpuUtils } from './webgpu-utils.js'; import { Debug, DebugHelper } from '../../../core/debug.js'; import { StringIds } from '../../../core/string-ids.js'; import { SAMPLETYPE_FLOAT, SAMPLETYPE_UNFILTERABLE_FLOAT, SAMPLETYPE_DEPTH, SAMPLETYPE_INT, SAMPLETYPE_UINT } from '../constants.js'; -import { WebgpuUtils } from './webgpu-utils.js'; -import { gpuTextureFormats } from './constants.js'; /** * @import { BindGroupFormat } from '../bind-group-format.js' diff --git a/src/platform/graphics/webgpu/webgpu-bind-group.js b/src/platform/graphics/webgpu/webgpu-bind-group.js index bc663f9092f..177707c6c0a 100644 --- a/src/platform/graphics/webgpu/webgpu-bind-group.js +++ b/src/platform/graphics/webgpu/webgpu-bind-group.js @@ -1,5 +1,5 @@ -import { Debug, DebugHelper } from '../../../core/debug.js'; import { WebgpuDebug } from './webgpu-debug.js'; +import { Debug, DebugHelper } from '../../../core/debug.js'; /** * @import { BindGroup } from '../bind-group.js' diff --git a/src/platform/graphics/webgpu/webgpu-buffer.js b/src/platform/graphics/webgpu/webgpu-buffer.js index a0e9d693c78..246eab58f97 100644 --- a/src/platform/graphics/webgpu/webgpu-buffer.js +++ b/src/platform/graphics/webgpu/webgpu-buffer.js @@ -36,7 +36,7 @@ class WebgpuBuffer { } allocate(device, size) { - Debug.assert(!this.buffer, "Buffer already allocated"); + Debug.assert(!this.buffer, 'Buffer already allocated'); this.buffer = device.wgpu.createBuffer({ size, usage: this.usageFlags @@ -63,11 +63,11 @@ class WebgpuBuffer { this.allocate(device, size); DebugHelper.setLabel(this.buffer, - this.usageFlags & GPUBufferUsage.VERTEX ? 'VertexBuffer' : - this.usageFlags & GPUBufferUsage.INDEX ? 'IndexBuffer' : - this.usageFlags & GPUBufferUsage.UNIFORM ? "UniformBuffer" : - this.usageFlags & GPUBufferUsage.STORAGE ? "StorageBuffer" : - '' + this.usageFlags & GPUBufferUsage.VERTEX ? 'VertexBuffer' : + this.usageFlags & GPUBufferUsage.INDEX ? 'IndexBuffer' : + this.usageFlags & GPUBufferUsage.UNIFORM ? 'UniformBuffer' : + this.usageFlags & GPUBufferUsage.STORAGE ? 'StorageBuffer' : + '' ); diff --git a/src/platform/graphics/webgpu/webgpu-clear-renderer.js b/src/platform/graphics/webgpu/webgpu-clear-renderer.js index 1cdb977dbcf..75cf5186487 100644 --- a/src/platform/graphics/webgpu/webgpu-clear-renderer.js +++ b/src/platform/graphics/webgpu/webgpu-clear-renderer.js @@ -1,17 +1,17 @@ -import { Debug } from "../../../core/debug.js"; -import { UniformBufferFormat, UniformFormat } from "../uniform-buffer-format.js"; -import { BlendState } from "../blend-state.js"; +import { Debug } from '../../../core/debug.js'; +import { DynamicBindGroup } from '../bind-group.js'; +import { BlendState } from '../blend-state.js'; import { CULLFACE_NONE, PRIMITIVE_TRISTRIP, SHADERLANGUAGE_WGSL, UNIFORMTYPE_FLOAT, UNIFORMTYPE_VEC4, BINDGROUP_MESH, CLEARFLAG_COLOR, CLEARFLAG_DEPTH, CLEARFLAG_STENCIL, BINDGROUP_MESH_UB -} from "../constants.js"; -import { Shader } from "../shader.js"; -import { DynamicBindGroup } from "../bind-group.js"; -import { UniformBuffer } from "../uniform-buffer.js"; -import { DebugGraphics } from "../debug-graphics.js"; -import { DepthState } from "../depth-state.js"; +} from '../constants.js'; +import { DebugGraphics } from '../debug-graphics.js'; +import { DepthState } from '../depth-state.js'; +import { Shader } from '../shader.js'; +import { UniformBufferFormat, UniformFormat } from '../uniform-buffer-format.js'; +import { UniformBuffer } from '../uniform-buffer.js'; const primitive = { type: PRIMITIVE_TRISTRIP, @@ -129,7 +129,7 @@ class WebgpuClearRenderer { // setup stencil clear if ((flags & CLEARFLAG_STENCIL) && renderTarget.stencil) { - Debug.warnOnce("ClearRenderer does not support stencil clear at the moment"); + Debug.warnOnce('ClearRenderer does not support stencil clear at the moment'); } uniformBuffer.endUpdate(); diff --git a/src/platform/graphics/webgpu/webgpu-compute-pipeline.js b/src/platform/graphics/webgpu/webgpu-compute-pipeline.js index fb507fa7290..4fc61d9d8fd 100644 --- a/src/platform/graphics/webgpu/webgpu-compute-pipeline.js +++ b/src/platform/graphics/webgpu/webgpu-compute-pipeline.js @@ -1,7 +1,7 @@ -import { Debug, DebugHelper } from "../../../core/debug.js"; -import { TRACEID_COMPUTEPIPELINE_ALLOC } from "../../../core/constants.js"; -import { WebgpuDebug } from "./webgpu-debug.js"; -import { WebgpuPipeline } from "./webgpu-pipeline.js"; +import { WebgpuDebug } from './webgpu-debug.js'; +import { WebgpuPipeline } from './webgpu-pipeline.js'; +import { TRACEID_COMPUTEPIPELINE_ALLOC } from '../../../core/constants.js'; +import { Debug, DebugHelper } from '../../../core/debug.js'; /** * @import { WebgpuShader } from './webgpu-shader.js' diff --git a/src/platform/graphics/webgpu/webgpu-compute.js b/src/platform/graphics/webgpu/webgpu-compute.js index 131f6227c1e..6dcfaf6b357 100644 --- a/src/platform/graphics/webgpu/webgpu-compute.js +++ b/src/platform/graphics/webgpu/webgpu-compute.js @@ -1,7 +1,7 @@ -import { Debug, DebugHelper } from "../../../core/debug.js"; -import { BindGroup } from "../bind-group.js"; -import { DebugGraphics } from "../debug-graphics.js"; -import { UniformBuffer } from "../uniform-buffer.js"; +import { Debug, DebugHelper } from '../../../core/debug.js'; +import { BindGroup } from '../bind-group.js'; +import { DebugGraphics } from '../debug-graphics.js'; +import { UniformBuffer } from '../uniform-buffer.js'; /** * A WebGPU implementation of the Compute. diff --git a/src/platform/graphics/webgpu/webgpu-debug.js b/src/platform/graphics/webgpu/webgpu-debug.js index f42fa51ff7c..20587baa030 100644 --- a/src/platform/graphics/webgpu/webgpu-debug.js +++ b/src/platform/graphics/webgpu/webgpu-debug.js @@ -1,5 +1,5 @@ -import { Debug } from "../../../core/debug.js"; -import { DebugGraphics } from "../debug-graphics.js"; +import { Debug } from '../../../core/debug.js'; +import { DebugGraphics } from '../debug-graphics.js'; /** * @import { WebgpuGraphicsDevice } from './webgpu-graphics-device.js' @@ -70,7 +70,7 @@ class WebgpuDebug { if (count < MAX_DUPLICATES) { const tooMany = count === MAX_DUPLICATES - 1 ? ' (Too many errors, ignoring this one from now)' : ''; WebgpuDebug._loggedMessages.set(error.message, count + 1); - console.error(`WebGPU ${header} error: ${error.message}`, tooMany, "while rendering", marker, ...args); + console.error(`WebGPU ${header} error: ${error.message}`, tooMany, 'while rendering', marker, ...args); } } }); diff --git a/src/platform/graphics/webgpu/webgpu-dynamic-buffer.js b/src/platform/graphics/webgpu/webgpu-dynamic-buffer.js index 3f8640fc0d8..4f4e647c8d2 100644 --- a/src/platform/graphics/webgpu/webgpu-dynamic-buffer.js +++ b/src/platform/graphics/webgpu/webgpu-dynamic-buffer.js @@ -1,5 +1,5 @@ -import { DebugHelper } from "../../../core/debug.js"; -import { DynamicBuffer } from "../dynamic-buffer.js"; +import { DebugHelper } from '../../../core/debug.js'; +import { DynamicBuffer } from '../dynamic-buffer.js'; class WebgpuDynamicBuffer extends DynamicBuffer { /** diff --git a/src/platform/graphics/webgpu/webgpu-dynamic-buffers.js b/src/platform/graphics/webgpu/webgpu-dynamic-buffers.js index ea611d59632..7bd90cd4f97 100644 --- a/src/platform/graphics/webgpu/webgpu-dynamic-buffers.js +++ b/src/platform/graphics/webgpu/webgpu-dynamic-buffers.js @@ -1,7 +1,7 @@ -import { DebugHelper } from "../../../core/debug.js"; -import { DebugGraphics } from "../debug-graphics.js"; -import { DynamicBuffers } from "../dynamic-buffers.js"; -import { WebgpuDynamicBuffer } from "./webgpu-dynamic-buffer.js"; +import { WebgpuDynamicBuffer } from './webgpu-dynamic-buffer.js'; +import { DebugHelper } from '../../../core/debug.js'; +import { DebugGraphics } from '../debug-graphics.js'; +import { DynamicBuffers } from '../dynamic-buffers.js'; class WebgpuDynamicBuffers extends DynamicBuffers { /** diff --git a/src/platform/graphics/webgpu/webgpu-gpu-profiler.js b/src/platform/graphics/webgpu/webgpu-gpu-profiler.js index f12bf43d665..006d1158362 100644 --- a/src/platform/graphics/webgpu/webgpu-gpu-profiler.js +++ b/src/platform/graphics/webgpu/webgpu-gpu-profiler.js @@ -1,5 +1,5 @@ -import { GpuProfiler } from "../gpu-profiler.js"; -import { WebgpuQuerySet } from "./webgpu-query-set.js"; +import { WebgpuQuerySet } from './webgpu-query-set.js'; +import { GpuProfiler } from '../gpu-profiler.js'; class WebgpuGpuProfiler extends GpuProfiler { device; diff --git a/src/platform/graphics/webgpu/webgpu-graphics-device.js b/src/platform/graphics/webgpu/webgpu-graphics-device.js index b82ae0223f2..59fff30adc4 100644 --- a/src/platform/graphics/webgpu/webgpu-graphics-device.js +++ b/src/platform/graphics/webgpu/webgpu-graphics-device.js @@ -1,34 +1,34 @@ +import { WebgpuBindGroupFormat } from './webgpu-bind-group-format.js'; +import { WebgpuBindGroup } from './webgpu-bind-group.js'; +import { WebgpuBuffer } from './webgpu-buffer.js'; +import { WebgpuClearRenderer } from './webgpu-clear-renderer.js'; +import { WebgpuComputePipeline } from './webgpu-compute-pipeline.js'; +import { WebgpuCompute } from './webgpu-compute.js'; +import { WebgpuDebug } from './webgpu-debug.js'; +import { WebgpuDynamicBuffers } from './webgpu-dynamic-buffers.js'; +import { WebgpuGpuProfiler } from './webgpu-gpu-profiler.js'; +import { WebgpuIndexBuffer } from './webgpu-index-buffer.js'; +import { WebgpuMipmapRenderer } from './webgpu-mipmap-renderer.js'; +import { WebgpuRenderPipeline } from './webgpu-render-pipeline.js'; +import { WebgpuRenderTarget } from './webgpu-render-target.js'; +import { WebgpuResolver } from './webgpu-resolver.js'; +import { WebgpuShader } from './webgpu-shader.js'; +import { WebgpuTexture } from './webgpu-texture.js'; +import { WebgpuUniformBuffer } from './webgpu-uniform-buffer.js'; +import { WebgpuVertexBuffer } from './webgpu-vertex-buffer.js'; import { TRACEID_RENDER_QUEUE } from '../../../core/constants.js'; import { Debug, DebugHelper } from '../../../core/debug.js'; +import { BindGroupFormat } from '../bind-group-format.js'; +import { BindGroup } from '../bind-group.js'; import { PIXELFORMAT_RGBA8, PIXELFORMAT_BGRA8, DEVICETYPE_WEBGPU, BUFFERUSAGE_READ, BUFFERUSAGE_COPY_DST, semanticToLocation, PIXELFORMAT_SRGBA8, DISPLAYFORMAT_LDR_SRGB, PIXELFORMAT_SBGRA8 } from '../constants.js'; -import { BindGroupFormat } from '../bind-group-format.js'; -import { BindGroup } from '../bind-group.js'; import { DebugGraphics } from '../debug-graphics.js'; import { GraphicsDevice } from '../graphics-device.js'; import { RenderTarget } from '../render-target.js'; import { StencilParameters } from '../stencil-parameters.js'; -import { WebgpuBindGroup } from './webgpu-bind-group.js'; -import { WebgpuBindGroupFormat } from './webgpu-bind-group-format.js'; -import { WebgpuIndexBuffer } from './webgpu-index-buffer.js'; -import { WebgpuRenderPipeline } from './webgpu-render-pipeline.js'; -import { WebgpuComputePipeline } from './webgpu-compute-pipeline.js'; -import { WebgpuRenderTarget } from './webgpu-render-target.js'; -import { WebgpuShader } from './webgpu-shader.js'; -import { WebgpuTexture } from './webgpu-texture.js'; -import { WebgpuUniformBuffer } from './webgpu-uniform-buffer.js'; -import { WebgpuVertexBuffer } from './webgpu-vertex-buffer.js'; -import { WebgpuClearRenderer } from './webgpu-clear-renderer.js'; -import { WebgpuMipmapRenderer } from './webgpu-mipmap-renderer.js'; -import { WebgpuDebug } from './webgpu-debug.js'; -import { WebgpuDynamicBuffers } from './webgpu-dynamic-buffers.js'; -import { WebgpuGpuProfiler } from './webgpu-gpu-profiler.js'; -import { WebgpuResolver } from './webgpu-resolver.js'; -import { WebgpuCompute } from './webgpu-compute.js'; -import { WebgpuBuffer } from './webgpu-buffer.js'; /** * @import { BindGroup } from '../bind-group.js' @@ -177,7 +177,7 @@ class WebgpuGraphicsDevice extends GraphicsDevice { } // temporary message to confirm Webgpu is being used - Debug.log("WebgpuGraphicsDevice initialization .."); + Debug.log('WebgpuGraphicsDevice initialization ..'); // build a full URL from a relative or absolute path const buildUrl = (srcPath) => { @@ -232,7 +232,7 @@ class WebgpuGraphicsDevice extends GraphicsDevice { if (adapterLimits) { for (const limitName in adapterLimits) { // skip these as they fail on Windows Chrome and are not part of spec currently - if (limitName === "minSubgroupSize" || limitName === "maxSubgroupSize") { + if (limitName === 'minSubgroupSize' || limitName === 'maxSubgroupSize') { continue; } requiredLimits[limitName] = adapterLimits[limitName]; @@ -521,8 +521,8 @@ class WebgpuGraphicsDevice extends GraphicsDevice { // render pipeline const pipeline = this.renderPipeline.get(primitive, vb0?.format, vb1?.format, this.shader, this.renderTarget, - this.bindGroupFormats, this.blendState, this.depthState, this.cullMode, - this.stencilEnabled, this.stencilFront, this.stencilBack); + this.bindGroupFormats, this.blendState, this.depthState, this.cullMode, + this.stencilEnabled, this.stencilFront, this.stencilBack); Debug.assert(pipeline); if (this.pipeline !== pipeline) { diff --git a/src/platform/graphics/webgpu/webgpu-index-buffer.js b/src/platform/graphics/webgpu/webgpu-index-buffer.js index 2799d4aa148..a065ba980ad 100644 --- a/src/platform/graphics/webgpu/webgpu-index-buffer.js +++ b/src/platform/graphics/webgpu/webgpu-index-buffer.js @@ -1,6 +1,6 @@ +import { WebgpuBuffer } from './webgpu-buffer.js'; import { Debug } from '../../../core/debug.js'; import { INDEXFORMAT_UINT8, INDEXFORMAT_UINT16, BUFFERUSAGE_INDEX, BUFFERUSAGE_STORAGE } from '../constants.js'; -import { WebgpuBuffer } from "./webgpu-buffer.js"; /** * A WebGPU implementation of the IndexBuffer. @@ -11,8 +11,8 @@ class WebgpuIndexBuffer extends WebgpuBuffer { constructor(indexBuffer, options) { super(BUFFERUSAGE_INDEX | (options?.storage ? BUFFERUSAGE_STORAGE : 0)); - Debug.assert(indexBuffer.format !== INDEXFORMAT_UINT8, "WebGPU does not support 8-bit index buffer format"); - this.format = indexBuffer.format === INDEXFORMAT_UINT16 ? "uint16" : "uint32"; + Debug.assert(indexBuffer.format !== INDEXFORMAT_UINT8, 'WebGPU does not support 8-bit index buffer format'); + this.format = indexBuffer.format === INDEXFORMAT_UINT16 ? 'uint16' : 'uint32'; } unlock(indexBuffer) { diff --git a/src/platform/graphics/webgpu/webgpu-mipmap-renderer.js b/src/platform/graphics/webgpu/webgpu-mipmap-renderer.js index a5087f24d6a..1062be28b74 100644 --- a/src/platform/graphics/webgpu/webgpu-mipmap-renderer.js +++ b/src/platform/graphics/webgpu/webgpu-mipmap-renderer.js @@ -1,7 +1,7 @@ -import { Shader } from "../shader.js"; -import { SHADERLANGUAGE_WGSL } from "../constants.js"; -import { Debug, DebugHelper } from "../../../core/debug.js"; -import { DebugGraphics } from "../debug-graphics.js"; +import { Debug, DebugHelper } from '../../../core/debug.js'; +import { SHADERLANGUAGE_WGSL } from '../constants.js'; +import { DebugGraphics } from '../debug-graphics.js'; +import { Shader } from '../shader.js'; /** * @import { WebgpuGraphicsDevice } from './webgpu-graphics-device.js' diff --git a/src/platform/graphics/webgpu/webgpu-query-set.js b/src/platform/graphics/webgpu/webgpu-query-set.js index 46863075eee..4bde8168f51 100644 --- a/src/platform/graphics/webgpu/webgpu-query-set.js +++ b/src/platform/graphics/webgpu/webgpu-query-set.js @@ -1,4 +1,4 @@ -import { DebugHelper } from "../../../core/debug.js"; +import { DebugHelper } from '../../../core/debug.js'; /** * A wrapper over the GpuQuerySet object, allowing timestamp and occlusion queries. The results diff --git a/src/platform/graphics/webgpu/webgpu-render-pipeline.js b/src/platform/graphics/webgpu/webgpu-render-pipeline.js index d2dfca00a23..d2b68f48b3d 100644 --- a/src/platform/graphics/webgpu/webgpu-render-pipeline.js +++ b/src/platform/graphics/webgpu/webgpu-render-pipeline.js @@ -1,12 +1,12 @@ -import { Debug, DebugHelper } from "../../../core/debug.js"; -import { hash32Fnv1a } from "../../../core/hash.js"; -import { array } from "../../../core/array-utils.js"; -import { TRACEID_RENDERPIPELINE_ALLOC } from "../../../core/constants.js"; -import { WebgpuVertexBufferLayout } from "./webgpu-vertex-buffer-layout.js"; -import { WebgpuDebug } from "./webgpu-debug.js"; -import { WebgpuPipeline } from "./webgpu-pipeline.js"; -import { DebugGraphics } from "../debug-graphics.js"; -import { bindGroupNames } from "../constants.js"; +import { WebgpuDebug } from './webgpu-debug.js'; +import { WebgpuPipeline } from './webgpu-pipeline.js'; +import { WebgpuVertexBufferLayout } from './webgpu-vertex-buffer-layout.js'; +import { array } from '../../../core/array-utils.js'; +import { TRACEID_RENDERPIPELINE_ALLOC } from '../../../core/constants.js'; +import { Debug, DebugHelper } from '../../../core/debug.js'; +import { hash32Fnv1a } from '../../../core/hash.js'; +import { bindGroupNames } from '../constants.js'; +import { DebugGraphics } from '../debug-graphics.js'; /** * @import { BindGroupFormat } from '../bind-group-format.js' @@ -180,7 +180,7 @@ class WebgpuRenderPipeline extends WebgpuPipeline { // no match or a hash collision, so create a new pipeline const primitiveTopology = _primitiveTopology[primitive.type]; - Debug.assert(primitiveTopology, `Unsupported primitive topology`, primitive); + Debug.assert(primitiveTopology, 'Unsupported primitive topology', primitive); // pipeline layout const pipelineLayout = this.getPipelineLayout(bindGroupFormats); @@ -192,7 +192,7 @@ class WebgpuRenderPipeline extends WebgpuPipeline { const cacheEntry = new CacheEntry(); cacheEntry.hashes = new Uint32Array(lookupHashes); cacheEntry.pipeline = this.create(primitiveTopology, shader, renderTarget, pipelineLayout, blendState, - depthState, vertexBufferLayout, cullMode, stencilEnabled, stencilFront, stencilBack); + depthState, vertexBufferLayout, cullMode, stencilEnabled, stencilFront, stencilBack); // add to cache if (cacheEntries) { diff --git a/src/platform/graphics/webgpu/webgpu-render-target.js b/src/platform/graphics/webgpu/webgpu-render-target.js index 73f3d880105..b57cefeb239 100644 --- a/src/platform/graphics/webgpu/webgpu-render-target.js +++ b/src/platform/graphics/webgpu/webgpu-render-target.js @@ -1,6 +1,6 @@ +import { WebgpuDebug } from './webgpu-debug.js'; import { Debug, DebugHelper } from '../../../core/debug.js'; import { StringIds } from '../../../core/string-ids.js'; -import { WebgpuDebug } from './webgpu-debug.js'; /** * @import { RenderPass } from '../render-pass.js' diff --git a/src/platform/graphics/webgpu/webgpu-resolver.js b/src/platform/graphics/webgpu/webgpu-resolver.js index daa74aabc97..3432b204145 100644 --- a/src/platform/graphics/webgpu/webgpu-resolver.js +++ b/src/platform/graphics/webgpu/webgpu-resolver.js @@ -1,7 +1,7 @@ -import { Shader } from "../shader.js"; -import { SHADERLANGUAGE_WGSL } from "../constants.js"; -import { Debug, DebugHelper } from "../../../core/debug.js"; -import { DebugGraphics } from "../debug-graphics.js"; +import { Debug, DebugHelper } from '../../../core/debug.js'; +import { SHADERLANGUAGE_WGSL } from '../constants.js'; +import { DebugGraphics } from '../debug-graphics.js'; +import { Shader } from '../shader.js'; /** * @import { WebgpuGraphicsDevice } from './webgpu-graphics-device.js' @@ -160,7 +160,7 @@ class WebgpuResolver { storeOp: 'store' }] }); - DebugHelper.setLabel(passEncoder, `DepthResolve-PassEncoder`); + DebugHelper.setLabel(passEncoder, 'DepthResolve-PassEncoder'); // no need for a sampler when using textureLoad const bindGroup = wgpu.createBindGroup({ diff --git a/src/platform/graphics/webgpu/webgpu-shader.js b/src/platform/graphics/webgpu/webgpu-shader.js index 6ff1f568588..dbab572b5ac 100644 --- a/src/platform/graphics/webgpu/webgpu-shader.js +++ b/src/platform/graphics/webgpu/webgpu-shader.js @@ -1,8 +1,8 @@ +import { WebgpuDebug } from './webgpu-debug.js'; import { Debug, DebugHelper } from '../../../core/debug.js'; import { SHADERLANGUAGE_WGSL } from '../constants.js'; import { DebugGraphics } from '../debug-graphics.js'; import { ShaderProcessor } from '../shader-processor.js'; -import { WebgpuDebug } from './webgpu-debug.js'; /** * @import { GraphicsDevice } from '../graphics-device.js' diff --git a/src/platform/graphics/webgpu/webgpu-texture.js b/src/platform/graphics/webgpu/webgpu-texture.js index 3aad44bb7e2..d7bba5de2c3 100644 --- a/src/platform/graphics/webgpu/webgpu-texture.js +++ b/src/platform/graphics/webgpu/webgpu-texture.js @@ -1,3 +1,5 @@ +import { gpuTextureFormats } from './constants.js'; +import { WebgpuDebug } from './webgpu-debug.js'; import { TRACEID_RENDER_QUEUE } from '../../../core/constants.js'; import { Debug, DebugHelper } from '../../../core/debug.js'; import { math } from '../../../core/math/math.js'; @@ -12,8 +14,6 @@ import { BUFFERUSAGE_COPY_DST } from '../constants.js'; import { TextureUtils } from '../texture-utils.js'; -import { WebgpuDebug } from './webgpu-debug.js'; -import { gpuTextureFormats } from './constants.js'; /** * @import { Texture } from '../texture.js' @@ -457,7 +457,7 @@ class WebgpuTexture { // data sizes const byteSize = TextureUtils.calcLevelGpuSize(width, height, 1, texture.format); Debug.assert(byteSize === data.byteLength, - `Error uploading data to texture, the data byte size of ${data.byteLength} does not match required ${byteSize}`, texture); + `Error uploading data to texture, the data byte size of ${data.byteLength} does not match required ${byteSize}`, texture); const formatInfo = pixelFormatInfo.get(texture.format); Debug.assert(formatInfo); diff --git a/src/platform/graphics/webgpu/webgpu-uniform-buffer.js b/src/platform/graphics/webgpu/webgpu-uniform-buffer.js index c6d049a5422..e4ad75b4cc3 100644 --- a/src/platform/graphics/webgpu/webgpu-uniform-buffer.js +++ b/src/platform/graphics/webgpu/webgpu-uniform-buffer.js @@ -1,5 +1,5 @@ -import { BUFFERUSAGE_UNIFORM } from "../constants.js"; -import { WebgpuBuffer } from "./webgpu-buffer.js"; +import { WebgpuBuffer } from './webgpu-buffer.js'; +import { BUFFERUSAGE_UNIFORM } from '../constants.js'; /** * A WebGPU implementation of the UniformBuffer. diff --git a/src/platform/graphics/webgpu/webgpu-vertex-buffer-layout.js b/src/platform/graphics/webgpu/webgpu-vertex-buffer-layout.js index 7a26850d93f..5eb63f75316 100644 --- a/src/platform/graphics/webgpu/webgpu-vertex-buffer-layout.js +++ b/src/platform/graphics/webgpu/webgpu-vertex-buffer-layout.js @@ -86,7 +86,7 @@ class WebgpuVertexBufferLayout { attributes.push({ shaderLocation: location, offset: interleaved ? element.offset : 0, - format: `${formatTable[element.dataType]}${element.numComponents > 1 ? 'x' + element.numComponents : ''}` + format: `${formatTable[element.dataType]}${element.numComponents > 1 ? `x${element.numComponents}` : ''}` }); if (!interleaved || i === elementCount - 1) { @@ -100,11 +100,13 @@ class WebgpuVertexBufferLayout { } }; - if (vertexFormat0) + if (vertexFormat0) { addFormat(vertexFormat0); + } - if (vertexFormat1) + if (vertexFormat1) { addFormat(vertexFormat1); + } return layout; } diff --git a/src/platform/graphics/webgpu/webgpu-vertex-buffer.js b/src/platform/graphics/webgpu/webgpu-vertex-buffer.js index 4a7504c5b5b..c14ecd6f465 100644 --- a/src/platform/graphics/webgpu/webgpu-vertex-buffer.js +++ b/src/platform/graphics/webgpu/webgpu-vertex-buffer.js @@ -1,5 +1,5 @@ -import { BUFFERUSAGE_STORAGE, BUFFERUSAGE_VERTEX } from "../constants.js"; -import { WebgpuBuffer } from "./webgpu-buffer.js"; +import { WebgpuBuffer } from './webgpu-buffer.js'; +import { BUFFERUSAGE_STORAGE, BUFFERUSAGE_VERTEX } from '../constants.js'; /** * A WebGPU implementation of the VertexBuffer. diff --git a/src/platform/input/controller.js b/src/platform/input/controller.js index 9a483786157..41707297ce8 100644 --- a/src/platform/input/controller.js +++ b/src/platform/input/controller.js @@ -258,37 +258,37 @@ class Controller { const bind = function (controller, source, value, key) { switch (source) { case 'mousex': - controller._mouse.on(EVENT_MOUSEMOVE, function (e) { + controller._mouse.on(EVENT_MOUSEMOVE, (e) => { controller._axesValues[name][i] = e.dx / 10; }); break; case 'mousey': - controller._mouse.on(EVENT_MOUSEMOVE, function (e) { + controller._mouse.on(EVENT_MOUSEMOVE, (e) => { controller._axesValues[name][i] = e.dy / 10; }); break; case 'key': - controller._axes[name].push(function () { + controller._axes[name].push(() => { return controller._keyboard.isPressed(key) ? value : 0; }); break; case 'padrx': - controller._axes[name].push(function () { + controller._axes[name].push(() => { return controller._gamepads.getAxis(options.pad, PAD_R_STICK_X); }); break; case 'padry': - controller._axes[name].push(function () { + controller._axes[name].push(() => { return controller._gamepads.getAxis(options.pad, PAD_R_STICK_Y); }); break; case 'padlx': - controller._axes[name].push(function () { + controller._axes[name].push(() => { return controller._gamepads.getAxis(options.pad, PAD_L_STICK_X); }); break; case 'padly': - controller._axes[name].push(function () { + controller._axes[name].push(() => { return controller._gamepads.getAxis(options.pad, PAD_L_STICK_Y); }); break; diff --git a/src/platform/input/game-pads.js b/src/platform/input/game-pads.js index 4ea088d1a4b..0c22366f84b 100644 --- a/src/platform/input/game-pads.js +++ b/src/platform/input/game-pads.js @@ -1,5 +1,5 @@ -import { EventHandler } from '../../core/event-handler.js'; import { EVENT_GAMEPADCONNECTED, EVENT_GAMEPADDISCONNECTED, PAD_FACE_1, PAD_FACE_2, PAD_FACE_3, PAD_FACE_4, PAD_L_SHOULDER_1, PAD_R_SHOULDER_1, PAD_L_SHOULDER_2, PAD_R_SHOULDER_2, PAD_SELECT, PAD_START, PAD_L_STICK_BUTTON, PAD_R_STICK_BUTTON, PAD_UP, PAD_DOWN, PAD_LEFT, PAD_RIGHT, PAD_VENDOR, XRPAD_TRIGGER, XRPAD_SQUEEZE, XRPAD_TOUCHPAD_BUTTON, XRPAD_STICK_BUTTON, XRPAD_A, XRPAD_B, PAD_L_STICK_X, PAD_L_STICK_Y, PAD_R_STICK_X, PAD_R_STICK_Y, XRPAD_TOUCHPAD_X, XRPAD_TOUCHPAD_Y, XRPAD_STICK_X, XRPAD_STICK_Y } from './constants.js'; +import { EventHandler } from '../../core/event-handler.js'; import { math } from '../../core/math/math.js'; import { platform } from '../../core/platform.js'; @@ -84,7 +84,7 @@ const MAPS = { 'PAD_LEFT', 'PAD_RIGHT', - // Vendor specific button + // Vendor specific button 'PAD_VENDOR' ], @@ -117,7 +117,7 @@ const MAPS = { 'PAD_L_STICK_BUTTON', 'PAD_R_STICK_BUTTON', - // Vendor specific button + // Vendor specific button 'PAD_VENDOR' ], @@ -227,7 +227,7 @@ function getMap(pad) { const product = PRODUCT_CODES[code]; if (!pad.mapping) { - const raw = MAPS['RAW_' + product]; + const raw = MAPS[`RAW_${product}`]; if (raw) { return raw; diff --git a/src/platform/input/keyboard.js b/src/platform/input/keyboard.js index 41206edf43d..5cfe97a1b56 100644 --- a/src/platform/input/keyboard.js +++ b/src/platform/input/keyboard.js @@ -1,7 +1,7 @@ +import { KeyboardEvent } from './keyboard-event.js'; import { Debug } from '../../core/debug.js'; import { EventHandler } from '../../core/event-handler.js'; -import { KeyboardEvent } from './keyboard-event.js'; // internal global keyboard events const _keyboardEvent = new KeyboardEvent(); @@ -189,10 +189,10 @@ class Keyboard extends EventHandler { let hex = keyCode.toString(16).toUpperCase(); const length = hex.length; for (let count = 0; count < (4 - length); count++) { - hex = '0' + hex; + hex = `0${hex}`; } - return 'U+' + hex; + return `U+${hex}`; } /** diff --git a/src/platform/input/mouse.js b/src/platform/input/mouse.js index 21efc26388b..6a4beb09566 100644 --- a/src/platform/input/mouse.js +++ b/src/platform/input/mouse.js @@ -1,8 +1,7 @@ -import { platform } from '../../core/platform.js'; -import { EventHandler } from '../../core/event-handler.js'; - import { EVENT_MOUSEDOWN, EVENT_MOUSEMOVE, EVENT_MOUSEUP, EVENT_MOUSEWHEEL } from './constants.js'; import { isMousePointerLocked, MouseEvent } from './mouse-event.js'; +import { EventHandler } from '../../core/event-handler.js'; +import { platform } from '../../core/platform.js'; /** * Callback used by {@link Mouse#enablePointerLock} and {@link Application#disablePointerLock}. @@ -178,8 +177,9 @@ class Mouse extends EventHandler { */ enablePointerLock(success, error) { if (!document.body.requestPointerLock) { - if (error) + if (error) { error(); + } return; } diff --git a/src/platform/input/touch-device.js b/src/platform/input/touch-device.js index 82dde2749f2..da3497fe189 100644 --- a/src/platform/input/touch-device.js +++ b/src/platform/input/touch-device.js @@ -1,6 +1,6 @@ +import { TouchEvent } from './touch-event.js'; import { EventHandler } from '../../core/event-handler.js'; -import { TouchEvent } from './touch-event.js'; /** * Attach a TouchDevice to an element and it will receive and fire events when the element is diff --git a/src/platform/net/http.js b/src/platform/net/http.js index fe8c9db8f6f..e1459858409 100644 --- a/src/platform/net/http.js +++ b/src/platform/net/http.js @@ -1,10 +1,9 @@ import { extend } from '../../core/core.js'; -import { now } from '../../core/time.js'; +import { math } from '../../core/math/math.js'; import { path } from '../../core/path.js'; +import { now } from '../../core/time.js'; import { URI } from '../../core/uri.js'; -import { math } from '../../core/math/math.js'; - /** * Callback used by {@link Http#get}, {@link Http#post}, {@link Http#put}, {@link Http#del}, and * {@link Http#request}. @@ -349,9 +348,9 @@ class Http { uri = new URI(url); if (!uri.query) { - uri.query = 'ts=' + timestamp; + uri.query = `ts=${timestamp}`; } else { - uri.query = uri.query + '&ts=' + timestamp; + uri.query = `${uri.query}&ts=${timestamp}`; } url = uri.toString(); } diff --git a/src/platform/sound/instance.js b/src/platform/sound/instance.js index 43ad513dff1..c6e97689cce 100644 --- a/src/platform/sound/instance.js +++ b/src/platform/sound/instance.js @@ -547,32 +547,36 @@ class SoundInstance extends EventHandler { _onPlay() { this.fire('play'); - if (this._onPlayCallback) + if (this._onPlayCallback) { this._onPlayCallback(this); + } } /** @private */ _onPause() { this.fire('pause'); - if (this._onPauseCallback) + if (this._onPauseCallback) { this._onPauseCallback(this); + } } /** @private */ _onResume() { this.fire('resume'); - if (this._onResumeCallback) + if (this._onResumeCallback) { this._onResumeCallback(this); + } } /** @private */ _onStop() { this.fire('stop'); - if (this._onStopCallback) + if (this._onStopCallback) { this._onStopCallback(this); + } } /** @private */ @@ -587,8 +591,9 @@ class SoundInstance extends EventHandler { this.fire('end'); - if (this._onEndCallback) + if (this._onEndCallback) { this._onEndCallback(this); + } this.stop(); } @@ -735,8 +740,9 @@ class SoundInstance extends EventHandler { // no need for this anymore this._playWhenLoaded = false; - if (this._state !== STATE_PLAYING) + if (this._state !== STATE_PLAYING) { return false; + } // set state to paused this._state = STATE_PAUSED; @@ -758,8 +764,9 @@ class SoundInstance extends EventHandler { // reset user-set start offset this._startOffset = null; - if (!this._suspendInstanceEvents) + if (!this._suspendInstanceEvents) { this._onPause(); + } return true; } @@ -815,8 +822,9 @@ class SoundInstance extends EventHandler { this.pitch = this._pitch; this._playWhenLoaded = false; - if (!this._suspendInstanceEvents) + if (!this._suspendInstanceEvents) { this._onResume(); + } return true; } @@ -830,8 +838,9 @@ class SoundInstance extends EventHandler { stop() { this._playWhenLoaded = false; - if (this._state === STATE_STOPPED) + if (this._state === STATE_STOPPED) { return false; + } // set state to stopped const wasPlaying = this._state === STATE_PLAYING; @@ -861,8 +870,9 @@ class SoundInstance extends EventHandler { } this.source = null; - if (!this._suspendInstanceEvents) + if (!this._suspendInstanceEvents) { this._onStop(); + } return true; } @@ -1043,19 +1053,22 @@ if (!hasAudioContext()) { this._manager.on('destroy', this._onManagerDestroy, this); // suspend immediately if manager is suspended - if (this._manager.suspended) + if (this._manager.suspended) { this._onManagerSuspend(); + } - if (!this._suspendInstanceEvents) + if (!this._suspendInstanceEvents) { this._onPlay(); + } return true; }, pause: function () { - if (!this.source || this._state !== STATE_PLAYING) + if (!this.source || this._state !== STATE_PLAYING) { return false; + } this._suspendEndEvent++; this.source.pause(); @@ -1063,31 +1076,35 @@ if (!hasAudioContext()) { this._state = STATE_PAUSED; this._startOffset = null; - if (!this._suspendInstanceEvents) + if (!this._suspendInstanceEvents) { this._onPause(); + } return true; }, resume: function () { - if (!this.source || this._state !== STATE_PAUSED) + if (!this.source || this._state !== STATE_PAUSED) { return false; + } this._state = STATE_PLAYING; this._playWhenLoaded = false; if (this.source.paused) { this.source.play(); - if (!this._suspendInstanceEvents) + if (!this._suspendInstanceEvents) { this._onResume(); + } } return true; }, stop: function () { - if (!this.source || this._state === STATE_STOPPED) + if (!this.source || this._state === STATE_STOPPED) { return false; + } this._manager.off('volumechange', this._onManagerVolumeChange, this); this._manager.off('suspend', this._onManagerSuspend, this); @@ -1100,8 +1117,9 @@ if (!hasAudioContext()) { this._state = STATE_STOPPED; this._startOffset = null; - if (!this._suspendInstanceEvents) + if (!this._suspendInstanceEvents) { this._onStop(); + } return true; }, @@ -1152,8 +1170,9 @@ if (!hasAudioContext()) { // called every time the 'currentTime' is changed _onTimeUpdate: function () { - if (!this._duration) + if (!this._duration) { return; + } // if the currentTime passes the end then if looping go back to the beginning // otherwise manually stop diff --git a/src/platform/sound/instance3d.js b/src/platform/sound/instance3d.js index c5b51b30bdb..301b300a69b 100644 --- a/src/platform/sound/instance3d.js +++ b/src/platform/sound/instance3d.js @@ -1,9 +1,9 @@ +import { SoundInstance } from './instance.js'; import { Debug } from '../../core/debug.js'; import { math } from '../../core/math/math.js'; import { Vec3 } from '../../core/math/vec3.js'; -import { DISTANCE_EXPONENTIAL, DISTANCE_INVERSE, DISTANCE_LINEAR } from '../audio/constants.js'; import { hasAudioContext } from '../audio/capabilities.js'; -import { SoundInstance } from './instance.js'; +import { DISTANCE_EXPONENTIAL, DISTANCE_INVERSE, DISTANCE_LINEAR } from '../audio/constants.js'; /** * @import { SoundManager } from './manager.js' @@ -65,8 +65,9 @@ class SoundInstance3d extends SoundInstance { constructor(manager, sound, options = {}) { super(manager, sound, options); - if (options.position) + if (options.position) { this.position = options.position; + } this.maxDistance = options.maxDistance !== undefined ? Number(options.maxDistance) : MAX_DISTANCE; this.refDistance = options.refDistance !== undefined ? Number(options.refDistance) : 1; diff --git a/src/platform/sound/manager.js b/src/platform/sound/manager.js index ffea521e2e6..aa9ca605fdb 100644 --- a/src/platform/sound/manager.js +++ b/src/platform/sound/manager.js @@ -1,9 +1,9 @@ +import { Listener } from './listener.js'; import { Debug } from '../../core/debug.js'; import { EventHandler } from '../../core/event-handler.js'; import { math } from '../../core/math/math.js'; import { Channel } from '../audio/channel.js'; import { Channel3d } from '../audio/channel3d.js'; -import { Listener } from './listener.js'; /** * @import { Sound } from './sound.js' diff --git a/src/platform/sound/sound.js b/src/platform/sound/sound.js index 944e45ca04f..96dd65c470c 100644 --- a/src/platform/sound/sound.js +++ b/src/platform/sound/sound.js @@ -11,11 +11,11 @@ class Sound { */ audio; - /** - * If the Web Audio API is supported this contains the audio data. - * - * @type {AudioBuffer|undefined} - */ + /** + * If the Web Audio API is supported this contains the audio data. + * + * @type {AudioBuffer|undefined} + */ buffer; /** diff --git a/src/scene/animation/skeleton.js b/src/scene/animation/skeleton.js index 5792293e0f1..84bbed4ccd7 100644 --- a/src/scene/animation/skeleton.js +++ b/src/scene/animation/skeleton.js @@ -70,8 +70,9 @@ class Skeleton { this._interpolatedKeyDict[node.name] = interpKey; this._currKeyIndices[node.name] = 0; - for (let i = 0; i < node._children.length; i++) + for (let i = 0; i < node._children.length; i++) { addInterpolatedKeys(node._children[i]); + } }; addInterpolatedKeys(graph); @@ -293,8 +294,9 @@ class Skeleton { transform.localRotation.copy(interpKey._quat); transform.localScale.copy(interpKey._scale); - if (!transform._dirtyLocal) + if (!transform._dirtyLocal) { transform._dirtifyLocal(); + } interpKey._written = false; } diff --git a/src/scene/area-light-luts.js b/src/scene/area-light-luts.js index be3e7b61291..09c4829027f 100644 --- a/src/scene/area-light-luts.js +++ b/src/scene/area-light-luts.js @@ -1,13 +1,13 @@ import { FloatPacking } from '../core/math/float-packing.js'; -import { Texture } from '../platform/graphics/texture.js'; -import { DeviceCache } from '../platform/graphics/device-cache.js'; - import { ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, FILTER_NEAREST, PIXELFORMAT_RGBA16F, TEXTURETYPE_DEFAULT } from '../platform/graphics/constants.js'; +import { DeviceCache } from '../platform/graphics/device-cache.js'; +import { Texture } from '../platform/graphics/texture.js'; + // class used to hold LUT textures in the device cache class AreaLightCacheEntry { diff --git a/src/scene/batching/batch-manager.js b/src/scene/batching/batch-manager.js index ba2d59e7416..50a57f38727 100644 --- a/src/scene/batching/batch-manager.js +++ b/src/scene/batching/batch-manager.js @@ -1,8 +1,11 @@ +import { BatchGroup } from './batch-group.js'; +import { Batch } from './batch.js'; +import { SkinBatchInstance } from './skin-batch-instance.js'; import { Debug } from '../../core/debug.js'; -import { now } from '../../core/time.js'; import { Mat3 } from '../../core/math/mat3.js'; import { Vec3 } from '../../core/math/vec3.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; +import { now } from '../../core/time.js'; import { PRIMITIVE_TRIANGLES, PRIMITIVE_TRIFAN, PRIMITIVE_TRISTRIP, SEMANTIC_POSITION, SEMANTIC_NORMAL, SEMANTIC_TANGENT, SEMANTIC_BLENDINDICES, @@ -10,11 +13,8 @@ import { typedArrayIndexFormats, typedArrayTypes, typedArrayTypesByteSize } from '../../platform/graphics/constants.js'; import { SPRITE_RENDERMODE_SIMPLE } from '../constants.js'; -import { Mesh } from '../mesh.js'; import { MeshInstance } from '../mesh-instance.js'; -import { Batch } from './batch.js'; -import { BatchGroup } from './batch-group.js'; -import { SkinBatchInstance } from './skin-batch-instance.js'; +import { Mesh } from '../mesh.js'; /** * @import { Entity } from '../../framework/entity.js' @@ -45,12 +45,14 @@ function paramsIdentical(a, b) { function equalParamSets(params1, params2) { for (const param in params1) { // compare A -> B - if (params1.hasOwnProperty(param) && !paramsIdentical(params1[param], params2[param])) + if (params1.hasOwnProperty(param) && !paramsIdentical(params1[param], params2[param])) { return false; + } } for (const param in params2) { // compare B -> A - if (params2.hasOwnProperty(param) && !paramsIdentical(params2[param], params1[param])) + if (params2.hasOwnProperty(param) && !paramsIdentical(params2[param], params1[param])) { return false; + } } return true; } @@ -449,7 +451,7 @@ class BatchManager { const lists = []; let j = 0; if (translucent) { - meshInstances.sort(function (a, b) { + meshInstances.sort((a, b) => { return a.drawOrder - b.drawOrder; }); } @@ -569,8 +571,9 @@ class BatchManager { // special case of fan / strip non-indexed primitive used by UI const primitiveType = mesh.primitive[0].type; if (primitiveType === PRIMITIVE_TRIFAN || primitiveType === PRIMITIVE_TRISTRIP) { - if (mesh.primitive[0].count === 4) + if (mesh.primitive[0].count === 4) { batchNumIndices += 6; + } } } @@ -676,8 +679,9 @@ class BatchManager { // build vertex and index data for final mesh for (let i = 0; i < meshInstances.length; i++) { - if (!meshInstances[i].visible) + if (!meshInstances[i].visible) { continue; + } mesh = meshInstances[i].mesh; numVerts = mesh.vertexBuffer.numVertices; @@ -726,8 +730,9 @@ class BatchManager { // bone index is mesh index if (dynamic) { stream = streams[SEMANTIC_BLENDINDICES]; - for (let j = 0; j < numVerts; j++) + for (let j = 0; j < numVerts; j++) { stream.buffer[stream.count++] = i; + } } // index buffer @@ -769,8 +774,9 @@ class BatchManager { mesh.setVertexStream(semantic, stream.buffer, stream.numComponents, undefined, stream.dataType, stream.normalize); } - if (indices.length > 0) + if (indices.length > 0) { mesh.setIndices(indices); + } mesh.update(PRIMITIVE_TRIANGLES, false); @@ -791,8 +797,9 @@ class BatchManager { // meshInstance culling - don't cull UI elements, as they use custom culling Component.isVisibleForCamera meshInstance.cull = batch.origMeshInstances[0].cull; const batchGroup = this._batchGroups[batchGroupId]; - if (batchGroup && batchGroup._ui) + if (batchGroup && batchGroup._ui) { meshInstance.cull = false; + } if (dynamic) { // Create skinInstance diff --git a/src/scene/camera.js b/src/scene/camera.js index b36e865958c..2dcc86b9614 100644 --- a/src/scene/camera.js +++ b/src/scene/camera.js @@ -1,15 +1,15 @@ -import { Color } from '../core/math/color.js'; -import { Mat4 } from '../core/math/mat4.js'; -import { Vec3 } from '../core/math/vec3.js'; -import { Vec4 } from '../core/math/vec4.js'; -import { math } from '../core/math/math.js'; -import { Frustum } from '../core/shape/frustum.js'; import { ASPECT_AUTO, PROJECTION_PERSPECTIVE, LAYERID_WORLD, LAYERID_DEPTH, LAYERID_SKYBOX, LAYERID_UI, LAYERID_IMMEDIATE } from './constants.js'; import { RenderPassColorGrab } from './graphics/render-pass-color-grab.js'; import { RenderPassDepthGrab } from './graphics/render-pass-depth-grab.js'; +import { Color } from '../core/math/color.js'; +import { Mat4 } from '../core/math/mat4.js'; +import { math } from '../core/math/math.js'; +import { Vec3 } from '../core/math/vec3.js'; +import { Vec4 } from '../core/math/vec4.js'; +import { Frustum } from '../core/shape/frustum.js'; /** * @import { RenderPass } from '../platform/graphics/render-pass.js' @@ -593,7 +593,7 @@ class Camera { this._updateViewProjMat(); _invViewProjMat.copy(this._viewProjMat).invert(); - // Transform to world space + // Transform to world space _invViewProjMat.transformPoint(_deviceCoord, worldCoord); } diff --git a/src/scene/composition/layer-composition.js b/src/scene/composition/layer-composition.js index 97d71bd79c5..77f7944382d 100644 --- a/src/scene/composition/layer-composition.js +++ b/src/scene/composition/layer-composition.js @@ -1,10 +1,10 @@ +import { RenderAction } from './render-action.js'; import { TRACEID_RENDER_ACTION } from '../../core/constants.js'; import { Debug } from '../../core/debug.js'; -import { Tracing } from '../../core/tracing.js'; import { EventHandler } from '../../core/event-handler.js'; import { sortPriority } from '../../core/sort.js'; +import { Tracing } from '../../core/tracing.js'; import { LAYERID_DEPTH } from '../constants.js'; -import { RenderAction } from './render-action.js'; /** * @import { CameraComponent } from '../../framework/components/camera/component.js' @@ -236,7 +236,7 @@ class LayerComposition extends EventHandler { // add render action to describe rendering step const isTransparent = this.subLayerList[j]; lastRenderAction = this.addRenderAction(renderActionCount, layer, isTransparent, camera, - cameraFirstRenderAction, postProcessMarked); + cameraFirstRenderAction, postProcessMarked); renderActionCount++; cameraFirstRenderAction = false; } @@ -371,28 +371,28 @@ class LayerComposition extends EventHandler { // #if _DEBUG if (Tracing.get(TRACEID_RENDER_ACTION)) { - Debug.trace(TRACEID_RENDER_ACTION, 'Render Actions for composition: ' + this.name); + Debug.trace(TRACEID_RENDER_ACTION, `Render Actions for composition: ${this.name}`); for (let i = 0; i < this._renderActions.length; i++) { const ra = this._renderActions[i]; const camera = ra.camera; if (ra.useCameraPasses) { - Debug.trace(TRACEID_RENDER_ACTION, i + - ('CustomPasses Cam: ' + (camera ? camera.entity.name : '-'))); + Debug.trace(TRACEID_RENDER_ACTION, `${i + }CustomPasses Cam: ${camera ? camera.entity.name : '-'}`); } else { const layer = ra.layer; const enabled = layer.enabled && this.isEnabled(layer, ra.transparent); const clear = (ra.clearColor ? 'Color ' : '..... ') + (ra.clearDepth ? 'Depth ' : '..... ') + (ra.clearStencil ? 'Stencil' : '.......'); - Debug.trace(TRACEID_RENDER_ACTION, i + - (' Cam: ' + (camera ? camera.entity.name : '-')).padEnd(22, ' ') + - (' Lay: ' + layer.name).padEnd(22, ' ') + + Debug.trace(TRACEID_RENDER_ACTION, `${i + + (` Cam: ${camera ? camera.entity.name : '-'}`).padEnd(22, ' ') + + (` Lay: ${layer.name}`).padEnd(22, ' ') + (ra.transparent ? ' TRANSP' : ' OPAQUE') + (enabled ? ' ENABLED ' : ' DISABLED') + - (' RT: ' + (ra.renderTarget ? ra.renderTarget.name : '-')).padEnd(30, ' ') + - ' Clear: ' + clear + - (ra.firstCameraUse ? ' CAM-FIRST' : '') + - (ra.lastCameraUse ? ' CAM-LAST' : '') + - (ra.triggerPostprocess ? ' POSTPROCESS' : '') + (` RT: ${ra.renderTarget ? ra.renderTarget.name : '-'}`).padEnd(30, ' ') + } Clear: ${clear + }${ra.firstCameraUse ? ' CAM-FIRST' : '' + }${ra.lastCameraUse ? ' CAM-LAST' : '' + }${ra.triggerPostprocess ? ' POSTPROCESS' : ''}` ); } } diff --git a/src/scene/geometry/box-geometry.js b/src/scene/geometry/box-geometry.js index 5ac264f116b..1761518186b 100644 --- a/src/scene/geometry/box-geometry.js +++ b/src/scene/geometry/box-geometry.js @@ -1,6 +1,6 @@ -import { Vec3 } from '../../core/math/vec3.js'; import { calculateTangents } from './geometry-utils.js'; import { Geometry } from './geometry.js'; +import { Vec3 } from '../../core/math/vec3.js'; const primitiveUv1Padding = 4.0 / 64; const primitiveUv1PaddingScale = 1.0 - primitiveUv1Padding * 2; diff --git a/src/scene/geometry/cone-base-geometry.js b/src/scene/geometry/cone-base-geometry.js index 5fb6922dc21..1af31dc2991 100644 --- a/src/scene/geometry/cone-base-geometry.js +++ b/src/scene/geometry/cone-base-geometry.js @@ -1,5 +1,5 @@ -import { Vec3 } from "../../core/math/vec3.js"; -import { Geometry } from "./geometry.js"; +import { Geometry } from './geometry.js'; +import { Vec3 } from '../../core/math/vec3.js'; const primitiveUv1Padding = 4.0 / 64; const primitiveUv1PaddingScale = 1.0 - primitiveUv1Padding * 2; diff --git a/src/scene/geometry/dome-geometry.js b/src/scene/geometry/dome-geometry.js index 514f6fcd42f..a8c405b93ba 100644 --- a/src/scene/geometry/dome-geometry.js +++ b/src/scene/geometry/dome-geometry.js @@ -1,4 +1,4 @@ -import { SphereGeometry } from "./sphere-geometry.js"; +import { SphereGeometry } from './sphere-geometry.js'; /** * A procedural dome-shaped geometry. diff --git a/src/scene/geometry/geometry-utils.js b/src/scene/geometry/geometry-utils.js index 56a4ee2c0d7..9cd624212b7 100644 --- a/src/scene/geometry/geometry-utils.js +++ b/src/scene/geometry/geometry-utils.js @@ -133,11 +133,11 @@ const calculateTangents = (positions, normals, uvs, indices) => { } else { const r = 1 / area; sdir.set((t2 * x1 - t1 * x2) * r, - (t2 * y1 - t1 * y2) * r, - (t2 * z1 - t1 * z2) * r); + (t2 * y1 - t1 * y2) * r, + (t2 * z1 - t1 * z2) * r); tdir.set((s1 * x2 - s2 * x1) * r, - (s1 * y2 - s2 * y1) * r, - (s1 * z2 - s2 * z1) * r); + (s1 * y2 - s2 * y1) * r, + (s1 * z2 - s2 * z1) * r); } tan1[i1 * 3 + 0] += sdir.x; diff --git a/src/scene/geometry/geometry.js b/src/scene/geometry/geometry.js index 449fd75c493..09ee4e5133f 100644 --- a/src/scene/geometry/geometry.js +++ b/src/scene/geometry/geometry.js @@ -1,5 +1,5 @@ -import { Debug } from "../../core/debug.js"; -import { calculateNormals, calculateTangents } from "./geometry-utils.js"; +import { calculateNormals, calculateTangents } from './geometry-utils.js'; +import { Debug } from '../../core/debug.js'; /** * The Geometry class serves as a container for storing geometric information. It encapsulates data diff --git a/src/scene/geometry/plane-geometry.js b/src/scene/geometry/plane-geometry.js index d4dbbf9396d..5a9c2ff451b 100644 --- a/src/scene/geometry/plane-geometry.js +++ b/src/scene/geometry/plane-geometry.js @@ -1,6 +1,6 @@ -import { Vec2 } from '../../core/math/vec2.js'; import { calculateTangents } from './geometry-utils.js'; import { Geometry } from './geometry.js'; +import { Vec2 } from '../../core/math/vec2.js'; /** * A procedural plane-shaped geometry. diff --git a/src/scene/geometry/torus-geometry.js b/src/scene/geometry/torus-geometry.js index 44956d7ad9c..55842c813aa 100644 --- a/src/scene/geometry/torus-geometry.js +++ b/src/scene/geometry/torus-geometry.js @@ -1,6 +1,6 @@ -import { math } from '../../core/math/math.js'; import { calculateTangents } from './geometry-utils.js'; import { Geometry } from './geometry.js'; +import { math } from '../../core/math/math.js'; /** * A procedural torus-shaped geometry. diff --git a/src/scene/graph-node.js b/src/scene/graph-node.js index 44dc6df3aac..b3e5e686904 100644 --- a/src/scene/graph-node.js +++ b/src/scene/graph-node.js @@ -1,11 +1,10 @@ -import { EventHandler } from '../core/event-handler.js'; -import { Tags } from '../core/tags.js'; import { Debug } from '../core/debug.js'; - +import { EventHandler } from '../core/event-handler.js'; import { Mat3 } from '../core/math/mat3.js'; import { Mat4 } from '../core/math/mat4.js'; import { Quat } from '../core/math/quat.js'; import { Vec3 } from '../core/math/vec3.js'; +import { Tags } from '../core/tags.js'; const scaleCompensatePosTransform = new Mat4(); const scaleCompensatePos = new Vec3(); @@ -52,15 +51,17 @@ function createTest(attr, value) { * node is found. */ function findNode(node, test) { - if (test(node)) + if (test(node)) { return node; + } const children = node._children; const len = children.length; for (let i = 0; i < len; ++i) { const result = findNode(children[i], test); - if (result) + if (result) { return result; + } } return null; @@ -450,8 +451,9 @@ class GraphNode extends EventHandler { const c = node._children; for (let i = 0, len = c.length; i < len; i++) { - if (c[i]._enabled) + if (c[i]._enabled) { this._notifyHierarchyStateChanged(c[i], enabled); + } } } @@ -464,8 +466,9 @@ class GraphNode extends EventHandler { _onHierarchyStateChanged(enabled) { // Override in derived classes this._enabledInHierarchy = enabled; - if (enabled && !this._frozen) + if (enabled && !this._frozen) { this._unfreezeParentToRoot(); + } } /** @@ -477,8 +480,9 @@ class GraphNode extends EventHandler { const tags = this.tags._list; clone.tags.clear(); - for (let i = 0; i < tags.length; i++) + for (let i = 0; i < tags.length; i++) { clone.tags.add(tags[i]); + } clone.localPosition.copy(this.localPosition); clone.localRotation.copy(this.localRotation); @@ -590,8 +594,9 @@ class GraphNode extends EventHandler { const test = createTest(attr, value); this.forEach((node) => { - if (test(node)) + if (test(node)) { results.push(node); + } }); return results; @@ -742,8 +747,9 @@ class GraphNode extends EventHandler { isDescendantOf(node) { let parent = this._parent; while (parent) { - if (parent === node) + if (parent === node) { return true; + } parent = parent._parent; } @@ -914,11 +920,13 @@ class GraphNode extends EventHandler { * const transform = this.entity.getWorldTransform(); */ getWorldTransform() { - if (!this._dirtyLocal && !this._dirtyWorld) + if (!this._dirtyLocal && !this._dirtyWorld) { return this.worldTransform; + } - if (this._parent) + if (this._parent) { this._parent.getWorldTransform(); + } this._sync(); @@ -985,8 +993,9 @@ class GraphNode extends EventHandler { setLocalEulerAngles(x, y, z) { this.localRotation.setFromEulerAngles(x, y, z); - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1013,8 +1022,9 @@ class GraphNode extends EventHandler { this.localPosition.set(x, y, z); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1042,8 +1052,9 @@ class GraphNode extends EventHandler { this.localRotation.set(x, y, z, w); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1069,16 +1080,18 @@ class GraphNode extends EventHandler { this.localScale.set(x, y, z); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @private */ _dirtifyLocal() { if (!this._dirtyLocal) { this._dirtyLocal = true; - if (!this._dirtyWorld) + if (!this._dirtyWorld) { this._dirtifyWorld(); + } } } @@ -1093,8 +1106,9 @@ class GraphNode extends EventHandler { /** @private */ _dirtifyWorld() { - if (!this._dirtyWorld) + if (!this._dirtyWorld) { this._unfreezeParentToRoot(); + } this._dirtifyWorldInternal(); } @@ -1104,8 +1118,9 @@ class GraphNode extends EventHandler { this._frozen = false; this._dirtyWorld = true; for (let i = 0; i < this._children.length; i++) { - if (!this._children[i]._dirtyWorld) + if (!this._children[i]._dirtyWorld) { this._children[i]._dirtifyWorldInternal(); + } } } this._dirtyNormal = true; @@ -1144,8 +1159,9 @@ class GraphNode extends EventHandler { invParentWtm.transformPoint(position, this.localPosition); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1181,8 +1197,9 @@ class GraphNode extends EventHandler { this.localRotation.copy(invParentRot).mul(rotation); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1207,8 +1224,9 @@ class GraphNode extends EventHandler { this.localRotation.setFromMat4(invParentWtm).mul(rotation); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1238,8 +1256,9 @@ class GraphNode extends EventHandler { this.localRotation.mul2(invParentRot, this.localRotation); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1358,8 +1377,9 @@ class GraphNode extends EventHandler { // The child (plus subhierarchy) will need world transforms to be recalculated node._dirtifyWorld(); // node might be already marked as dirty, in that case the whole chain stays frozen, so let's enforce unfreeze - if (this._frozen) + if (this._frozen) { node._unfreezeParentToRoot(); + } // alert an entity hierarchy that it has been inserted node._fireOnHierarchy('insert', 'inserthierarchy', this); @@ -1457,8 +1477,8 @@ class GraphNode extends EventHandler { if (parent.scaleCompensation) { scaleCompensateScaleForParent.mul2(parentWorldScale, parent.getLocalScale()); scaleCompensatePosTransform.setTRS(parent.worldTransform.getTranslation(scaleCompensatePos), - scaleCompensateRot2, - scaleCompensateScaleForParent); + scaleCompensateRot2, + scaleCompensateScaleForParent); tmatrix = scaleCompensatePosTransform; } tmatrix.transformPoint(this.localPosition, scaleCompensatePos); @@ -1480,11 +1500,13 @@ class GraphNode extends EventHandler { * @ignore */ syncHierarchy() { - if (!this._enabled) + if (!this._enabled) { return; + } - if (this._frozen) + if (this._frozen) { return; + } this._frozen = true; if (this._dirtyLocal || this._dirtyWorld) { @@ -1601,8 +1623,9 @@ class GraphNode extends EventHandler { this.localRotation.transformVector(position, position); this.localPosition.add(position); - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1636,8 +1659,9 @@ class GraphNode extends EventHandler { this.localRotation.mul2(rotation, rot); } - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } /** @@ -1662,8 +1686,9 @@ class GraphNode extends EventHandler { this.localRotation.mul(rotation); - if (!this._dirtyLocal) + if (!this._dirtyLocal) { this._dirtifyLocal(); + } } } diff --git a/src/scene/graphics/env-lighting.js b/src/scene/graphics/env-lighting.js index dd6d9956616..db13704c2b8 100644 --- a/src/scene/graphics/env-lighting.js +++ b/src/scene/graphics/env-lighting.js @@ -1,6 +1,5 @@ -import { Vec4 } from '../../core/math/vec4.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { reprojectTexture } from './reproject-texture.js'; +import { Vec4 } from '../../core/math/vec4.js'; import { TEXTURETYPE_DEFAULT, TEXTURETYPE_RGBP as RGBA8_TYPE, TEXTUREPROJECTION_EQUIRECT, @@ -8,6 +7,7 @@ import { PIXELFORMAT_RGBA8, PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F } from '../../platform/graphics/constants.js'; import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { Texture } from '../../platform/graphics/texture.js'; // calculate the number of mipmap levels given texture dimensions const calcLevels = (width, height = 0) => { @@ -65,7 +65,7 @@ class EnvLighting { static generateSkyboxCubemap(source, size) { const device = source.device; - DebugGraphics.pushGpuMarker(device, "genSkyboxCubemap"); + DebugGraphics.pushGpuMarker(device, 'genSkyboxCubemap'); const result = createCubemap(device, size || (source.cubemap ? source.width : source.width / 4), PIXELFORMAT_RGBA8, false); @@ -93,11 +93,11 @@ class EnvLighting { static generateLightingSource(source, options) { const device = source.device; - DebugGraphics.pushGpuMarker(device, "genLightingSource"); + DebugGraphics.pushGpuMarker(device, 'genLightingSource'); const format = lightingSourcePixelFormat(device); const result = options?.target || new Texture(device, { - name: `lighting-source`, + name: 'lighting-source', cubemap: true, width: options?.size || 128, height: options?.size || 128, @@ -138,7 +138,7 @@ class EnvLighting { const device = source.device; const format = lightingPixelFormat(device); - DebugGraphics.pushGpuMarker(device, "genAtlas"); + DebugGraphics.pushGpuMarker(device, 'genAtlas'); const result = options?.target || new Texture(device, { name: 'envAtlas', @@ -152,7 +152,7 @@ class EnvLighting { mipmaps: false }); - DebugGraphics.pushGpuMarker(device, "mipmaps"); + DebugGraphics.pushGpuMarker(device, 'mipmaps'); const s = result.width / 512; @@ -173,7 +173,7 @@ class EnvLighting { } DebugGraphics.popGpuMarker(device); - DebugGraphics.pushGpuMarker(device, "reflections"); + DebugGraphics.pushGpuMarker(device, 'reflections'); // generate blurry reflections rect.set(0, 256 * s, 256 * s, 128 * s); @@ -191,7 +191,7 @@ class EnvLighting { } DebugGraphics.popGpuMarker(device); - DebugGraphics.pushGpuMarker(device, "ambient"); + DebugGraphics.pushGpuMarker(device, 'ambient'); // generate ambient rect.set(128 * s, (256 + 128) * s, 64 * s, 32 * s); @@ -228,7 +228,7 @@ class EnvLighting { const format = sources[0].format; const type = sources[0].type; - DebugGraphics.pushGpuMarker(device, "genPrefilteredAtlas"); + DebugGraphics.pushGpuMarker(device, 'genPrefilteredAtlas'); const result = options?.target || new Texture(device, { name: 'envPrefilteredAtlas', @@ -242,7 +242,7 @@ class EnvLighting { mipmaps: false }); - DebugGraphics.pushGpuMarker(device, "mipmaps"); + DebugGraphics.pushGpuMarker(device, 'mipmaps'); const s = result.width / 512; @@ -263,7 +263,7 @@ class EnvLighting { } DebugGraphics.popGpuMarker(device); - DebugGraphics.pushGpuMarker(device, "reflections"); + DebugGraphics.pushGpuMarker(device, 'reflections'); // copy blurry reflections rect.set(0, 256 * s, 256 * s, 128 * s); @@ -279,7 +279,7 @@ class EnvLighting { } DebugGraphics.popGpuMarker(device); - DebugGraphics.pushGpuMarker(device, "ambient"); + DebugGraphics.pushGpuMarker(device, 'ambient'); // generate ambient rect.set(128 * s, (256 + 128) * s, 64 * s, 32 * s); diff --git a/src/scene/graphics/light-cube.js b/src/scene/graphics/light-cube.js index 673c30b45f7..b85eb47d89e 100644 --- a/src/scene/graphics/light-cube.js +++ b/src/scene/graphics/light-cube.js @@ -1,5 +1,5 @@ -import { Vec3 } from "../../core/math/vec3.js"; -import { LIGHTTYPE_DIRECTIONAL } from "../constants.js"; +import { Vec3 } from '../../core/math/vec3.js'; +import { LIGHTTYPE_DIRECTIONAL } from '../constants.js'; const lightCubeDir = [ new Vec3(-1, 0, 0), diff --git a/src/scene/graphics/noise-textures.js b/src/scene/graphics/noise-textures.js index b24ee0d069b..fe52ebcedb8 100644 --- a/src/scene/graphics/noise-textures.js +++ b/src/scene/graphics/noise-textures.js @@ -1,7 +1,7 @@ -import { blueNoiseData } from "../../core/math/blue-noise.js"; -import { ADDRESS_REPEAT, FILTER_NEAREST, PIXELFORMAT_RGBA8, TEXTURETYPE_DEFAULT } from "../../platform/graphics/constants.js"; -import { DeviceCache } from "../../platform/graphics/device-cache.js"; -import { Texture } from "../../platform/graphics/texture.js"; +import { blueNoiseData } from '../../core/math/blue-noise.js'; +import { ADDRESS_REPEAT, FILTER_NEAREST, PIXELFORMAT_RGBA8, TEXTURETYPE_DEFAULT } from '../../platform/graphics/constants.js'; +import { DeviceCache } from '../../platform/graphics/device-cache.js'; +import { Texture } from '../../platform/graphics/texture.js'; const createTexture = (device, namePrefix, size, data) => { const texture = new Texture(device, { @@ -32,7 +32,7 @@ const getBlueNoiseTexture = (device) => { const data = blueNoiseData(); const size = Math.sqrt(data.length / 4); - return createTexture(device, "BlueNoise", size, data); + return createTexture(device, 'BlueNoise', size, data); }); }; diff --git a/src/scene/graphics/post-effect.js b/src/scene/graphics/post-effect.js index 215254666a9..30341e24ffb 100644 --- a/src/scene/graphics/post-effect.js +++ b/src/scene/graphics/post-effect.js @@ -1,6 +1,6 @@ +import { drawQuadWithShader } from './quad-render-utils.js'; import { Vec4 } from '../../core/math/vec4.js'; import { BlendState } from '../../platform/graphics/blend-state.js'; -import { drawQuadWithShader } from './quad-render-utils.js'; /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' diff --git a/src/scene/graphics/quad-render-utils.js b/src/scene/graphics/quad-render-utils.js index f50520272f8..91193aa7641 100644 --- a/src/scene/graphics/quad-render-utils.js +++ b/src/scene/graphics/quad-render-utils.js @@ -1,7 +1,7 @@ -import { Debug } from '../../core/debug.js'; -import { Vec4 } from '../../core/math/vec4.js'; import { QuadRender } from './quad-render.js'; import { RenderPassQuad } from './render-pass-quad.js'; +import { Debug } from '../../core/debug.js'; +import { Vec4 } from '../../core/math/vec4.js'; /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' diff --git a/src/scene/graphics/quad-render.js b/src/scene/graphics/quad-render.js index eb9ed8f3daf..cfd78623b1b 100644 --- a/src/scene/graphics/quad-render.js +++ b/src/scene/graphics/quad-render.js @@ -1,11 +1,11 @@ -import { Debug, DebugHelper } from "../../core/debug.js"; -import { Vec4 } from "../../core/math/vec4.js"; -import { BindGroup, DynamicBindGroup } from "../../platform/graphics/bind-group.js"; -import { BINDGROUP_MESH, BINDGROUP_MESH_UB, BINDGROUP_VIEW, PRIMITIVE_TRISTRIP } from "../../platform/graphics/constants.js"; -import { DebugGraphics } from "../../platform/graphics/debug-graphics.js"; -import { ShaderProcessorOptions } from "../../platform/graphics/shader-processor-options.js"; -import { UniformBuffer } from "../../platform/graphics/uniform-buffer.js"; -import { processShader } from "../shader-lib/utils.js"; +import { Debug, DebugHelper } from '../../core/debug.js'; +import { Vec4 } from '../../core/math/vec4.js'; +import { BindGroup, DynamicBindGroup } from '../../platform/graphics/bind-group.js'; +import { BINDGROUP_MESH, BINDGROUP_MESH_UB, BINDGROUP_VIEW, PRIMITIVE_TRISTRIP } from '../../platform/graphics/constants.js'; +import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; +import { UniformBuffer } from '../../platform/graphics/uniform-buffer.js'; +import { processShader } from '../shader-lib/utils.js'; /** * @import { Shader } from '../../platform/graphics/shader.js' @@ -103,7 +103,7 @@ class QuadRender { render(viewport, scissor) { const device = this.shader.device; - DebugGraphics.pushGpuMarker(device, "QuadRender"); + DebugGraphics.pushGpuMarker(device, 'QuadRender'); // only modify viewport or scissor if viewport supplied if (viewport) { diff --git a/src/scene/graphics/render-pass-color-grab.js b/src/scene/graphics/render-pass-color-grab.js index d928cb88617..83ed3e07c00 100644 --- a/src/scene/graphics/render-pass-color-grab.js +++ b/src/scene/graphics/render-pass-color-grab.js @@ -1,8 +1,8 @@ -import { ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, FILTER_LINEAR_MIPMAP_LINEAR } from "../../platform/graphics/constants.js"; -import { DebugGraphics } from "../../platform/graphics/debug-graphics.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; -import { RenderTarget } from "../../platform/graphics/render-target.js"; -import { Texture } from "../../platform/graphics/texture.js"; +import { ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, FILTER_LINEAR_MIPMAP_LINEAR } from '../../platform/graphics/constants.js'; +import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; +import { RenderTarget } from '../../platform/graphics/render-target.js'; +import { Texture } from '../../platform/graphics/texture.js'; // uniform name const _colorUniformName = 'uSceneColorMap'; @@ -31,8 +31,9 @@ class RenderPassColorGrab extends RenderPass { // need to reallocate if format does not match const targetFormat = targetRT?.colorBuffer.format; - if (targetFormat !== sourceFormat) + if (targetFormat !== sourceFormat) { return true; + } // need to reallocate if dimensions don't match const width = sourceTexture?.width || this.device.width; diff --git a/src/scene/graphics/render-pass-depth-grab.js b/src/scene/graphics/render-pass-depth-grab.js index 764014e5ad5..158d60d7646 100644 --- a/src/scene/graphics/render-pass-depth-grab.js +++ b/src/scene/graphics/render-pass-depth-grab.js @@ -1,8 +1,8 @@ -import { ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, PIXELFORMAT_DEPTH, PIXELFORMAT_DEPTHSTENCIL, PIXELFORMAT_R32F } from "../../platform/graphics/constants.js"; -import { DebugGraphics } from "../../platform/graphics/debug-graphics.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; -import { RenderTarget } from "../../platform/graphics/render-target.js"; -import { Texture } from "../../platform/graphics/texture.js"; +import { ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, PIXELFORMAT_DEPTH, PIXELFORMAT_DEPTHSTENCIL, PIXELFORMAT_R32F } from '../../platform/graphics/constants.js'; +import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; +import { RenderTarget } from '../../platform/graphics/render-target.js'; +import { Texture } from '../../platform/graphics/texture.js'; // uniform name const _depthUniformName = 'uSceneDepthMap'; diff --git a/src/scene/graphics/render-pass-quad.js b/src/scene/graphics/render-pass-quad.js index abf74c708da..2ba23b0c815 100644 --- a/src/scene/graphics/render-pass-quad.js +++ b/src/scene/graphics/render-pass-quad.js @@ -1,7 +1,7 @@ -import { CULLFACE_NONE } from "../../platform/graphics/constants.js"; -import { DebugGraphics } from "../../platform/graphics/debug-graphics.js"; -import { DepthState } from "../../platform/graphics/depth-state.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; +import { CULLFACE_NONE } from '../../platform/graphics/constants.js'; +import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { DepthState } from '../../platform/graphics/depth-state.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; /** * A render pass implementing rendering of a QuadRender. @@ -17,7 +17,7 @@ class RenderPassQuad extends RenderPass { execute() { const { device } = this; - DebugGraphics.pushGpuMarker(device, "drawQuadWithShader"); + DebugGraphics.pushGpuMarker(device, 'drawQuadWithShader'); device.setCullMode(CULLFACE_NONE); device.setDepthState(DepthState.NODEPTH); diff --git a/src/scene/graphics/render-pass-shader-quad.js b/src/scene/graphics/render-pass-shader-quad.js index aa71f64fbc0..a608fa75f52 100644 --- a/src/scene/graphics/render-pass-shader-quad.js +++ b/src/scene/graphics/render-pass-shader-quad.js @@ -1,9 +1,9 @@ -import { QuadRender } from "./quad-render.js"; -import { BlendState } from "../../platform/graphics/blend-state.js"; -import { CULLFACE_NONE, SEMANTIC_POSITION } from "../../platform/graphics/constants.js"; -import { DepthState } from "../../platform/graphics/depth-state.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; -import { createShaderFromCode } from "../shader-lib/utils.js"; +import { QuadRender } from './quad-render.js'; +import { BlendState } from '../../platform/graphics/blend-state.js'; +import { CULLFACE_NONE, SEMANTIC_POSITION } from '../../platform/graphics/constants.js'; +import { DepthState } from '../../platform/graphics/depth-state.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; +import { createShaderFromCode } from '../shader-lib/utils.js'; /** * @import { Shader } from '../../platform/graphics/shader.js' @@ -86,8 +86,9 @@ class RenderPassShaderQuad extends RenderPass { // handle new this._shader = shader; - if (shader) + if (shader) { this.quadRender = new QuadRender(shader); + } } get shader() { diff --git a/src/scene/graphics/reproject-texture.js b/src/scene/graphics/reproject-texture.js index d143e5834bf..6c62b7706a4 100644 --- a/src/scene/graphics/reproject-texture.js +++ b/src/scene/graphics/reproject-texture.js @@ -1,6 +1,8 @@ +import { drawQuadWithShader } from './quad-render-utils.js'; import { Debug } from '../../core/debug.js'; import { random } from '../../core/math/random.js'; import { Vec3 } from '../../core/math/vec3.js'; +import { BlendState } from '../../platform/graphics/blend-state.js'; import { FILTER_NEAREST, TEXTUREPROJECTION_OCTAHEDRAL, TEXTUREPROJECTION_CUBE @@ -13,8 +15,6 @@ import { ChunkUtils } from '../shader-lib/chunk-utils.js'; import { shaderChunks } from '../shader-lib/chunks/chunks.js'; import { getProgramLibrary } from '../shader-lib/get-program-library.js'; import { createShaderFromCode } from '../shader-lib/utils.js'; -import { BlendState } from '../../platform/graphics/blend-state.js'; -import { drawQuadWithShader } from './quad-render-utils.js'; /** * @import { Vec4 } from '../../core/math/vec4.js' @@ -23,11 +23,11 @@ import { drawQuadWithShader } from './quad-render-utils.js'; const getProjectionName = (projection) => { switch (projection) { case TEXTUREPROJECTION_CUBE: - return "Cubemap"; + return 'Cubemap'; case TEXTUREPROJECTION_OCTAHEDRAL: - return "Octahedral"; + return 'Octahedral'; default: // for anything else, assume equirect - return "Equirect"; + return 'Equirect'; } }; @@ -219,33 +219,33 @@ const calculateRequiredSamplesGGX = () => { // required for the sets of (numSamples, specularPowers) pairs we expect to // encounter at runtime. const requiredSamplesGGX = { - "16": { - "2": 26, - "8": 20, - "32": 17, - "128": 16, - "512": 16 + '16': { + '2': 26, + '8': 20, + '32': 17, + '128': 16, + '512': 16 }, - "32": { - "2": 53, - "8": 40, - "32": 34, - "128": 32, - "512": 32 + '32': { + '2': 53, + '8': 40, + '32': 34, + '128': 32, + '512': 32 }, - "128": { - "2": 214, - "8": 163, - "32": 139, - "128": 130, - "512": 128 + '128': { + '2': 214, + '8': 163, + '32': 139, + '128': 130, + '512': 128 }, - "1024": { - "2": 1722, - "8": 1310, - "32": 1114, - "128": 1041, - "512": 1025 + '1024': { + '2': 1722, + '8': 1310, + '32': 1114, + '128': 1041, + '512': 1025 } }; @@ -441,10 +441,10 @@ function reprojectTexture(source, target, options = {}) { let shader = getProgramLibrary(device).getCachedShader(shaderKey); if (!shader) { const defines = - `#define PROCESS_FUNC ${processFunc}\n` + - (prefilterSamples ? `#define USE_SAMPLES_TEX\n` : '') + - (source.cubemap ? `#define CUBEMAP_SOURCE\n` : '') + - `#define DECODE_FUNC ${decodeFunc}\n` + + `#define PROCESS_FUNC ${processFunc}\n${ + prefilterSamples ? '#define USE_SAMPLES_TEX\n' : '' + }${source.cubemap ? '#define CUBEMAP_SOURCE\n' : '' + }#define DECODE_FUNC ${decodeFunc}\n` + `#define ENCODE_FUNC ${encodeFunc}\n` + `#define SOURCE_FUNC ${sourceFunc}\n` + `#define TARGET_FUNC ${targetFunc}\n` + @@ -459,19 +459,19 @@ function reprojectTexture(source, target, options = {}) { ); } - DebugGraphics.pushGpuMarker(device, "ReprojectTexture"); + DebugGraphics.pushGpuMarker(device, 'ReprojectTexture'); // render state // TODO: set up other render state here to expected state device.setBlendState(BlendState.NOBLEND); - const constantSource = device.scope.resolve(source.cubemap ? "sourceCube" : "sourceTex"); + const constantSource = device.scope.resolve(source.cubemap ? 'sourceCube' : 'sourceTex'); Debug.assert(constantSource); constantSource.setValue(source); - const constantParams = device.scope.resolve("params"); + const constantParams = device.scope.resolve('params'); - const uvModParam = device.scope.resolve("uvMod"); + const uvModParam = device.scope.resolve('uvMod'); if (seamPixels > 0) { uvModParam.setValue([ (innerWidth + seamPixels * 2) / innerWidth, @@ -497,8 +497,8 @@ function reprojectTexture(source, target, options = {}) { (distribution === 'ggx') ? generateGGXSamplesTex(device, numSamples, specularPower, sourceTotalPixels) : ((distribution === 'lambert') ? generateLambertSamplesTex(device, numSamples, sourceTotalPixels) : generatePhongSamplesTex(device, numSamples, specularPower)); - device.scope.resolve("samplesTex").setValue(samplesTex); - device.scope.resolve("samplesTexInverseSize").setValue([1.0 / samplesTex.width, 1.0 / samplesTex.height]); + device.scope.resolve('samplesTex').setValue(samplesTex); + device.scope.resolve('samplesTexInverseSize').setValue([1.0 / samplesTex.width, 1.0 / samplesTex.height]); } for (let f = 0; f < (target.cubemap ? 6 : 1); f++) { diff --git a/src/scene/gsplat/gsplat-compressed-data.js b/src/scene/gsplat/gsplat-compressed-data.js index 692e028ceb3..541d7acb3e7 100644 --- a/src/scene/gsplat/gsplat-compressed-data.js +++ b/src/scene/gsplat/gsplat-compressed-data.js @@ -1,7 +1,7 @@ +import { GSplatData } from './gsplat-data.js'; import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; import { Vec4 } from '../../core/math/vec4.js'; -import { GSplatData } from './gsplat-data.js'; /** * @import { BoundingBox } from '../../core/shape/bounding-box.js' diff --git a/src/scene/gsplat/gsplat-compressed-material.js b/src/scene/gsplat/gsplat-compressed-material.js index 1ce0a6723de..97b2e081653 100644 --- a/src/scene/gsplat/gsplat-compressed-material.js +++ b/src/scene/gsplat/gsplat-compressed-material.js @@ -1,14 +1,13 @@ -import { CULLFACE_NONE, SEMANTIC_ATTR13, SEMANTIC_POSITION } from "../../platform/graphics/constants.js"; -import { ShaderProcessorOptions } from "../../platform/graphics/shader-processor-options.js"; -import { BLEND_NONE, BLEND_NORMAL, DITHER_NONE, TONEMAP_LINEAR } from "../constants.js"; -import { ShaderMaterial } from "../materials/shader-material.js"; -import { getProgramLibrary } from "../shader-lib/get-program-library.js"; - -import { hashCode } from "../../core/hash.js"; -import { ShaderUtils } from "../../platform/graphics/shader-utils.js"; -import { shaderChunks } from "../shader-lib/chunks/chunks.js"; -import { ShaderGenerator } from "../shader-lib/programs/shader-generator.js"; -import { ShaderPass } from "../shader-pass.js"; +import { hashCode } from '../../core/hash.js'; +import { CULLFACE_NONE, SEMANTIC_ATTR13, SEMANTIC_POSITION } from '../../platform/graphics/constants.js'; +import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; +import { ShaderUtils } from '../../platform/graphics/shader-utils.js'; +import { BLEND_NONE, BLEND_NORMAL, DITHER_NONE, TONEMAP_LINEAR } from '../constants.js'; +import { ShaderMaterial } from '../materials/shader-material.js'; +import { shaderChunks } from '../shader-lib/chunks/chunks.js'; +import { getProgramLibrary } from '../shader-lib/get-program-library.js'; +import { ShaderGenerator } from '../shader-lib/programs/shader-generator.js'; +import { ShaderPass } from '../shader-pass.js'; const splatCoreVS = /* glsl */ ` uniform mat4 matrix_model; @@ -281,8 +280,8 @@ class GSplatCompressedShaderGenerator { const shaderPassDefines = shaderPassInfo.shaderDefines; const defines = - shaderPassDefines + - `#define DITHER_${options.dither.toUpperCase()}\n` + + `${shaderPassDefines + }#define DITHER_${options.dither.toUpperCase()}\n` + `#define TONEMAP_${options.toneMapping === TONEMAP_LINEAR ? 'DISABLED' : 'ENABLED'}\n`; const vs = defines + splatCoreVS + options.vertex; diff --git a/src/scene/gsplat/gsplat-compressed.js b/src/scene/gsplat/gsplat-compressed.js index b0e68fd4fb9..af6587a63dd 100644 --- a/src/scene/gsplat/gsplat-compressed.js +++ b/src/scene/gsplat/gsplat-compressed.js @@ -1,10 +1,10 @@ +import { createGSplatCompressedMaterial } from './gsplat-compressed-material.js'; import { Vec2 } from '../../core/math/vec2.js'; -import { Texture } from '../../platform/graphics/texture.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; import { ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, PIXELFORMAT_RGBA32F, PIXELFORMAT_RGBA32U } from '../../platform/graphics/constants.js'; -import { createGSplatCompressedMaterial } from './gsplat-compressed-material.js'; +import { Texture } from '../../platform/graphics/texture.js'; /** * @import { BoundingBox } from '../../core/shape/bounding-box.js' diff --git a/src/scene/gsplat/gsplat-instance.js b/src/scene/gsplat/gsplat-instance.js index c8d1e69f853..53d1efb9561 100644 --- a/src/scene/gsplat/gsplat-instance.js +++ b/src/scene/gsplat/gsplat-instance.js @@ -1,12 +1,12 @@ +import { GSplatSorter } from './gsplat-sorter.js'; import { Mat4 } from '../../core/math/mat4.js'; import { Vec3 } from '../../core/math/vec3.js'; import { BUFFER_STATIC, PIXELFORMAT_R32U, SEMANTIC_ATTR13, TYPE_UINT32 } from '../../platform/graphics/constants.js'; +import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; +import { VertexFormat } from '../../platform/graphics/vertex-format.js'; import { DITHER_NONE } from '../constants.js'; import { MeshInstance } from '../mesh-instance.js'; import { Mesh } from '../mesh.js'; -import { GSplatSorter } from './gsplat-sorter.js'; -import { VertexFormat } from '../../platform/graphics/vertex-format.js'; -import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; /** * @import { Camera } from '../camera.js' diff --git a/src/scene/gsplat/gsplat-material.js b/src/scene/gsplat/gsplat-material.js index 7e9ce350f12..ac75a13e37c 100644 --- a/src/scene/gsplat/gsplat-material.js +++ b/src/scene/gsplat/gsplat-material.js @@ -1,9 +1,9 @@ -import { CULLFACE_NONE } from "../../platform/graphics/constants.js"; -import { ShaderProcessorOptions } from "../../platform/graphics/shader-processor-options.js"; -import { BLEND_NONE, BLEND_NORMAL, DITHER_NONE } from "../constants.js"; -import { ShaderMaterial } from "../materials/shader-material.js"; -import { getProgramLibrary } from "../shader-lib/get-program-library.js"; -import { gsplat } from "./shader-generator-gsplat.js"; +import { gsplat } from './shader-generator-gsplat.js'; +import { CULLFACE_NONE } from '../../platform/graphics/constants.js'; +import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; +import { BLEND_NONE, BLEND_NORMAL, DITHER_NONE } from '../constants.js'; +import { ShaderMaterial } from '../materials/shader-material.js'; +import { getProgramLibrary } from '../shader-lib/get-program-library.js'; const splatMainVS = ` vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0); diff --git a/src/scene/gsplat/gsplat-sorter.js b/src/scene/gsplat/gsplat-sorter.js index 4c580fbc78b..bdecc363977 100644 --- a/src/scene/gsplat/gsplat-sorter.js +++ b/src/scene/gsplat/gsplat-sorter.js @@ -1,5 +1,5 @@ -import { EventHandler } from "../../core/event-handler.js"; -import { TEXTURELOCK_READ } from "../../platform/graphics/constants.js"; +import { EventHandler } from '../../core/event-handler.js'; +import { TEXTURELOCK_READ } from '../../platform/graphics/constants.js'; // sort blind set of data function SortWorker() { diff --git a/src/scene/gsplat/gsplat.js b/src/scene/gsplat/gsplat.js index 6d568e43510..618f9cc6fd6 100644 --- a/src/scene/gsplat/gsplat.js +++ b/src/scene/gsplat/gsplat.js @@ -1,17 +1,17 @@ +import { createGSplatMaterial } from './gsplat-material.js'; import { FloatPacking } from '../../core/math/float-packing.js'; +import { Mat3 } from '../../core/math/mat3.js'; import { math } from '../../core/math/math.js'; import { Quat } from '../../core/math/quat.js'; import { Vec2 } from '../../core/math/vec2.js'; import { Vec3 } from '../../core/math/vec3.js'; import { Vec4 } from '../../core/math/vec4.js'; -import { Mat3 } from '../../core/math/mat3.js'; +import { BoundingBox } from '../../core/shape/bounding-box.js'; import { ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, PIXELFORMAT_R16F, PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F, PIXELFORMAT_RGBA8 } from '../../platform/graphics/constants.js'; import { Texture } from '../../platform/graphics/texture.js'; -import { BoundingBox } from '../../core/shape/bounding-box.js'; -import { createGSplatMaterial } from './gsplat-material.js'; /** * @import { GSplatData } from './gsplat-data.js' @@ -143,8 +143,9 @@ class GSplat { */ updateColorData(gsplatData) { const texture = this.colorTexture; - if (!texture) + if (!texture) { return; + } const data = texture.lock(); const c = new Vec4(); @@ -169,8 +170,9 @@ class GSplat { const float2Half = FloatPacking.float2Half; - if (!this.transformATexture) + if (!this.transformATexture) { return; + } const dataA = this.transformATexture.lock(); const dataB = this.transformBTexture.lock(); diff --git a/src/scene/gsplat/shader-generator-gsplat.js b/src/scene/gsplat/shader-generator-gsplat.js index 600e690726c..98261fddc8b 100644 --- a/src/scene/gsplat/shader-generator-gsplat.js +++ b/src/scene/gsplat/shader-generator-gsplat.js @@ -1,10 +1,10 @@ -import { hashCode } from "../../core/hash.js"; -import { SEMANTIC_ATTR13, SEMANTIC_POSITION } from "../../platform/graphics/constants.js"; -import { ShaderUtils } from "../../platform/graphics/shader-utils.js"; -import { DITHER_NONE, TONEMAP_LINEAR } from "../constants.js"; -import { shaderChunks } from "../shader-lib/chunks/chunks.js"; -import { ShaderGenerator } from "../shader-lib/programs/shader-generator.js"; -import { ShaderPass } from "../shader-pass.js"; +import { hashCode } from '../../core/hash.js'; +import { SEMANTIC_ATTR13, SEMANTIC_POSITION } from '../../platform/graphics/constants.js'; +import { ShaderUtils } from '../../platform/graphics/shader-utils.js'; +import { DITHER_NONE, TONEMAP_LINEAR } from '../constants.js'; +import { shaderChunks } from '../shader-lib/chunks/chunks.js'; +import { ShaderGenerator } from '../shader-lib/programs/shader-generator.js'; +import { ShaderPass } from '../shader-pass.js'; const splatCoreVS = /* glsl */ ` uniform mat4 matrix_model; @@ -186,8 +186,8 @@ class GSplatShaderGenerator { const shaderPassDefines = shaderPassInfo.shaderDefines; const defines = - shaderPassDefines + - `#define DITHER_${options.dither.toUpperCase()}\n` + + `${shaderPassDefines + }#define DITHER_${options.dither.toUpperCase()}\n` + `#define TONEMAP_${options.toneMapping === TONEMAP_LINEAR ? 'DISABLED' : 'ENABLED'}\n`; const vs = defines + splatCoreVS + options.vertex; diff --git a/src/scene/immediate/immediate-batch.js b/src/scene/immediate/immediate-batch.js index 26113dbdefd..fd7bff69da1 100644 --- a/src/scene/immediate/immediate-batch.js +++ b/src/scene/immediate/immediate-batch.js @@ -1,10 +1,8 @@ import { Mat4 } from '../../core/math/mat4.js'; - import { PRIMITIVE_LINES } from '../../platform/graphics/constants.js'; - -import { Mesh } from '../mesh.js'; -import { MeshInstance } from '../mesh-instance.js'; import { GraphNode } from '../graph-node.js'; +import { MeshInstance } from '../mesh-instance.js'; +import { Mesh } from '../mesh.js'; const identityGraphNode = new GraphNode(); identityGraphNode.worldTransform = Mat4.IDENTITY; diff --git a/src/scene/immediate/immediate.js b/src/scene/immediate/immediate.js index feb3aed69bf..7c1cb3e859f 100644 --- a/src/scene/immediate/immediate.js +++ b/src/scene/immediate/immediate.js @@ -1,15 +1,14 @@ +import { ImmediateBatches } from './immediate-batches.js'; +import { Vec3 } from '../../core/math/vec3.js'; import { PRIMITIVE_TRISTRIP, SEMANTIC_COLOR, SEMANTIC_POSITION } from '../../platform/graphics/constants.js'; - import { BLEND_NORMAL } from '../constants.js'; import { GraphNode } from '../graph-node.js'; -import { Mesh } from '../mesh.js'; -import { MeshInstance } from '../mesh-instance.js'; import { ShaderMaterial } from '../materials/shader-material.js'; +import { MeshInstance } from '../mesh-instance.js'; +import { Mesh } from '../mesh.js'; +import { ChunkUtils } from '../shader-lib/chunk-utils.js'; import { shaderChunks } from '../shader-lib/chunks/chunks.js'; -import { ImmediateBatches } from './immediate-batches.js'; -import { Vec3 } from '../../core/math/vec3.js'; -import { ChunkUtils } from '../shader-lib/chunk-utils.js'; const tempPoints = []; const vec = new Vec3(); diff --git a/src/scene/layer.js b/src/scene/layer.js index 82ef4023e81..28df81417a0 100644 --- a/src/scene/layer.js +++ b/src/scene/layer.js @@ -1,5 +1,3 @@ -import { Debug } from '../core/debug.js'; -import { hash32Fnv1a } from '../core/hash.js'; import { LIGHTTYPE_DIRECTIONAL, LAYER_FX, @@ -7,6 +5,8 @@ import { SORTMODE_BACK2FRONT, SORTMODE_CUSTOM, SORTMODE_FRONT2BACK, SORTMODE_MATERIALMESH, SORTMODE_NONE } from './constants.js'; import { Material } from './materials/material.js'; +import { Debug } from '../core/debug.js'; +import { hash32Fnv1a } from '../core/hash.js'; /** * @import { Camera } from './camera.js' @@ -779,8 +779,9 @@ class Layer { this._splitLightsDirty = false; const splitLights = this._splitLights; - for (let i = 0; i < splitLights.length; i++) + for (let i = 0; i < splitLights.length; i++) { splitLights[i].length = 0; + } const lights = this._lights; for (let i = 0; i < lights.length; i++) { @@ -792,8 +793,9 @@ class Layer { // sort the lights by their key, as the order of lights is used to generate shader generation key, // and this avoids new shaders being generated when lights are reordered - for (let i = 0; i < splitLights.length; i++) + for (let i = 0; i < splitLights.length; i++) { splitLights[i].sort((a, b) => a.key - b.key); + } } return this._splitLights; @@ -935,8 +937,9 @@ class Layer { */ sortVisible(camera, transparent) { const sortMode = transparent ? this.transparentSortMode : this.opaqueSortMode; - if (sortMode === SORTMODE_NONE) + if (sortMode === SORTMODE_NONE) { return; + } const culledInstances = this.getCulledInstances(camera); const instances = transparent ? culledInstances.transparent : culledInstances.opaque; diff --git a/src/scene/light.js b/src/scene/light.js index 163dc044bfd..a1d8206469c 100644 --- a/src/scene/light.js +++ b/src/scene/light.js @@ -1,9 +1,3 @@ -import { math } from '../core/math/math.js'; -import { Color } from '../core/math/color.js'; -import { Mat4 } from '../core/math/mat4.js'; -import { Vec2 } from '../core/math/vec2.js'; -import { Vec3 } from '../core/math/vec3.js'; -import { Vec4 } from '../core/math/vec4.js'; import { BLUR_GAUSSIAN, LIGHTTYPE_DIRECTIONAL, LIGHTTYPE_OMNI, LIGHTTYPE_SPOT, @@ -13,6 +7,12 @@ import { LIGHTSHAPE_PUNCTUAL, LIGHTFALLOFF_LINEAR } from './constants.js'; import { ShadowRenderer } from './renderer/shadow-renderer.js'; +import { Color } from '../core/math/color.js'; +import { Mat4 } from '../core/math/mat4.js'; +import { math } from '../core/math/math.js'; +import { Vec2 } from '../core/math/vec2.js'; +import { Vec3 } from '../core/math/vec3.js'; +import { Vec4 } from '../core/math/vec4.js'; import { DepthState } from '../platform/graphics/depth-state.js'; /** @@ -335,8 +335,9 @@ class Light { } set type(value) { - if (this._type === value) + if (this._type === value) { return; + } this._type = value; this._destroyShadowMap(); @@ -354,8 +355,9 @@ class Light { } set shape(value) { - if (this._shape === value) + if (this._shape === value) { return; + } this._shape = value; this._destroyShadowMap(); @@ -382,21 +384,25 @@ class Light { } set shadowType(value) { - if (this._shadowType === value) + if (this._shadowType === value) { return; + } const device = this.device; - if (this._type === LIGHTTYPE_OMNI && value !== SHADOW_PCF3 && value !== SHADOW_PCSS) - value = SHADOW_PCF3; // VSM or HW PCF for omni lights is not supported yet + if (this._type === LIGHTTYPE_OMNI && value !== SHADOW_PCF3 && value !== SHADOW_PCSS) { + value = SHADOW_PCF3; + } // VSM or HW PCF for omni lights is not supported yet // fallback from vsm32 to vsm16 - if (value === SHADOW_VSM32 && (!device.textureFloatRenderable || !device.textureFloatFilterable)) + if (value === SHADOW_VSM32 && (!device.textureFloatRenderable || !device.textureFloatFilterable)) { value = SHADOW_VSM16; + } // fallback from vsm16 to vsm8 - if (value === SHADOW_VSM16 && !device.textureHalfFloatRenderable) + if (value === SHADOW_VSM16 && !device.textureHalfFloatRenderable) { value = SHADOW_VSM8; + } this._isVsm = value >= SHADOW_VSM8 && value <= SHADOW_VSM32; this._isPcf = value === SHADOW_PCF1 || value === SHADOW_PCF3 || value === SHADOW_PCF5; @@ -451,8 +457,9 @@ class Light { } set vsmBlurSize(value) { - if (this._vsmBlurSize === value) + if (this._vsmBlurSize === value) { return; + } if (value % 2 === 0) value++; // don't allow even size this._vsmBlurSize = value; @@ -463,8 +470,9 @@ class Light { } set normalOffsetBias(value) { - if (this._normalOffsetBias === value) + if (this._normalOffsetBias === value) { return; + } if ((!this._normalOffsetBias && value) || (this._normalOffsetBias && !value)) { this.updateKey(); @@ -477,8 +485,9 @@ class Light { } set falloffMode(value) { - if (this._falloffMode === value) + if (this._falloffMode === value) { return; + } this._falloffMode = value; this.updateKey(); @@ -489,8 +498,9 @@ class Light { } set innerConeAngle(value) { - if (this._innerConeAngle === value) + if (this._innerConeAngle === value) { return; + } this._innerConeAngle = value; this._innerConeAngleCos = Math.cos(value * Math.PI / 180); @@ -504,8 +514,9 @@ class Light { } set outerConeAngle(value) { - if (this._outerConeAngle === value) + if (this._outerConeAngle === value) { return; + } this._outerConeAngle = value; this._updateOuterAngle(value); @@ -581,8 +592,9 @@ class Light { } set cookie(value) { - if (this._cookie === value) + if (this._cookie === value) { return; + } this._cookie = value; this.updateKey(); @@ -593,8 +605,9 @@ class Light { } set cookieFalloff(value) { - if (this._cookieFalloff === value) + if (this._cookieFalloff === value) { return; + } this._cookieFalloff = value; this.updateKey(); @@ -605,14 +618,16 @@ class Light { } set cookieChannel(value) { - if (this._cookieChannel === value) + if (this._cookieChannel === value) { return; + } if (value.length < 3) { const chr = value.charAt(value.length - 1); const addLen = 3 - value.length; - for (let i = 0; i < addLen; i++) + for (let i = 0; i < addLen; i++) { value += chr; + } } this._cookieChannel = value; this.updateKey(); @@ -623,8 +638,9 @@ class Light { } set cookieTransform(value) { - if (this._cookieTransform === value) + if (this._cookieTransform === value) { return; + } this._cookieTransform = value; this._cookieTransformSet = !!value; @@ -640,8 +656,9 @@ class Light { } set cookieOffset(value) { - if (this._cookieOffset === value) + if (this._cookieOffset === value) { return; + } const xformNew = !!(this._cookieTransformSet || value); if (xformNew && !value && this._cookieOffset) { diff --git a/src/scene/lighting/light-texture-atlas.js b/src/scene/lighting/light-texture-atlas.js index e9f4a545fab..b5b712b1da3 100644 --- a/src/scene/lighting/light-texture-atlas.js +++ b/src/scene/lighting/light-texture-atlas.js @@ -1,10 +1,8 @@ import { Vec2 } from '../../core/math/vec2.js'; import { Vec4 } from '../../core/math/vec4.js'; - import { ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, PIXELFORMAT_RGBA8 } from '../../platform/graphics/constants.js'; import { RenderTarget } from '../../platform/graphics/render-target.js'; import { Texture } from '../../platform/graphics/texture.js'; - import { LIGHTTYPE_OMNI, LIGHTTYPE_SPOT, SHADOW_PCF3 } from '../constants.js'; import { ShadowMap } from '../renderer/shadow-map.js'; @@ -356,8 +354,9 @@ class LightTextureAtlas { for (let i = 0; i < assignCount; i++) { const light = lights[i]; - if (light.castShadows) + if (light.castShadows) { light._shadowMap = this.shadowAtlas; + } // if currently assigned slot is the same size as what is needed, and was last used by this light, reuse it const previousSlot = slots[light.atlasSlotIndex]; @@ -374,8 +373,9 @@ class LightTextureAtlas { for (let i = 0; i < assignCount; i++) { // skip already used slots - while (usedCount < slots.length && slots[usedCount].used) + while (usedCount < slots.length && slots[usedCount].used) { usedCount++; + } const light = lights[i]; if (!light.atlasViewportAllocated) { diff --git a/src/scene/lighting/lighting-params.js b/src/scene/lighting/lighting-params.js index 723f122d0b4..08a9a8b3e21 100644 --- a/src/scene/lighting/lighting-params.js +++ b/src/scene/lighting/lighting-params.js @@ -70,8 +70,9 @@ class LightingParams { this.cookieAtlasResolution = render.lightingCookieAtlasResolution ?? this.cookieAtlasResolution; this.maxLightsPerCell = render.lightingMaxLightsPerCell ?? this.maxLightsPerCell; this.shadowType = render.lightingShadowType ?? this.shadowType; - if (render.lightingCells) + if (render.lightingCells) { this.cell = new Vec3(render.lightingCells); + } } /** diff --git a/src/scene/lighting/lights-buffer.js b/src/scene/lighting/lights-buffer.js index 0b3ad3b6c5d..96c92643fc6 100644 --- a/src/scene/lighting/lights-buffer.js +++ b/src/scene/lighting/lights-buffer.js @@ -1,8 +1,8 @@ +import { FloatPacking } from '../../core/math/float-packing.js'; import { Vec3 } from '../../core/math/vec3.js'; import { PIXELFORMAT_RGBA8, PIXELFORMAT_RGBA32F, ADDRESS_CLAMP_TO_EDGE, TEXTURETYPE_DEFAULT, FILTER_NEAREST } from '../../platform/graphics/constants.js'; -import { FloatPacking } from '../../core/math/float-packing.js'; -import { LIGHTSHAPE_PUNCTUAL, LIGHTTYPE_SPOT, MASK_AFFECT_LIGHTMAPPED, MASK_AFFECT_DYNAMIC } from '../constants.js'; import { Texture } from '../../platform/graphics/texture.js'; +import { LIGHTSHAPE_PUNCTUAL, LIGHTTYPE_SPOT, MASK_AFFECT_LIGHTMAPPED, MASK_AFFECT_DYNAMIC } from '../constants.js'; import { LightCamera } from '../renderer/light-camera.js'; const epsilon = 0.000001; @@ -57,8 +57,8 @@ class LightsBuffer { // converts object with properties to a list of these as an example: "#define CLUSTER_TEXTURE_8_BLAH 1" const buildShaderDefines = (object, prefix) => { return Object.keys(object) - .map(key => `#define ${prefix}${key} ${object[key]}`) - .join('\n'); + .map(key => `#define ${prefix}${key} ${object[key]}`) + .join('\n'); }; if (!_defines) { @@ -309,8 +309,9 @@ class LightsBuffer { // light projection matrix if (lightProjectionMatrix) { const matData = lightProjectionMatrix.data; - for (let m = 0; m < 16; m++) + for (let m = 0; m < 16; m++) { dataFloat[dataFloatStart + 4 * TextureIndexFloat.PROJ_MAT_0 + m] = matData[m]; + } } if (atlasViewport) { diff --git a/src/scene/lighting/world-clusters-debug.js b/src/scene/lighting/world-clusters-debug.js index db3a431ad9c..fb14b9eca53 100644 --- a/src/scene/lighting/world-clusters-debug.js +++ b/src/scene/lighting/world-clusters-debug.js @@ -1,14 +1,12 @@ import { Color } from '../../core/math/color.js'; import { Mat4 } from '../../core/math/mat4.js'; import { Vec3 } from '../../core/math/vec3.js'; - import { PRIMITIVE_TRIANGLES } from '../../platform/graphics/constants.js'; - import { BLEND_ADDITIVEALPHA } from '../constants.js'; import { GraphNode } from '../graph-node.js'; -import { Mesh } from '../mesh.js'; -import { MeshInstance } from '../mesh-instance.js'; import { StandardMaterial } from '../materials/standard-material.js'; +import { MeshInstance } from '../mesh-instance.js'; +import { Mesh } from '../mesh.js'; class WorldClustersDebug { static gridPositions = []; @@ -43,12 +41,13 @@ class WorldClustersDebug { for (let b = 0; b <= countB; b++) { const aa = minA + a * deltaA; const bb = minB + b * deltaB; - if (order === 0) + if (order === 0) { gridPositions.push(aa, minC, bb, aa, maxC, bb); - else if (order === 1) + } else if (order === 1) { gridPositions.push(aa, bb, minC, aa, bb, maxC); - else if (order === 2) + } else if (order === 2) { gridPositions.push(minC, aa, bb, maxC, aa, bb); + } } } }; diff --git a/src/scene/lighting/world-clusters.js b/src/scene/lighting/world-clusters.js index a64e92a0dea..fae329ef5e9 100644 --- a/src/scene/lighting/world-clusters.js +++ b/src/scene/lighting/world-clusters.js @@ -1,10 +1,10 @@ -import { Vec3 } from '../../core/math/vec3.js'; +import { LightsBuffer } from './lights-buffer.js'; +import { Debug } from '../../core/debug.js'; import { math } from '../../core/math/math.js'; +import { Vec3 } from '../../core/math/vec3.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; import { PIXELFORMAT_R8 } from '../../platform/graphics/constants.js'; import { LIGHTTYPE_DIRECTIONAL, LIGHTTYPE_SPOT, MASK_AFFECT_DYNAMIC, MASK_AFFECT_LIGHTMAPPED } from '../constants.js'; -import { LightsBuffer } from './lights-buffer.js'; -import { Debug } from '../../core/debug.js'; /** * @import { Texture } from '../../platform/graphics/texture.js' @@ -179,7 +179,7 @@ class WorldClusters { // if the texture is allowed size Debug.assert(width <= maxTextureSize && height <= maxTextureSize, - 'Clustered lights parameters cause the texture size to be over the limit, please adjust them.'); + 'Clustered lights parameters cause the texture size to be over the limit, please adjust them.'); // maximum range of cells this._clusterCellsMaxData[0] = cx; @@ -433,8 +433,8 @@ class WorldClusters { if (tooManyLights) { const reportLimit = 5; if (this.reportCount < reportLimit) { - console.warn('Too many lights in light cluster ' + this.name + ', please adjust parameters.' + - (this.reportCount === reportLimit - 1 ? ' Giving up on reporting it.' : '')); + console.warn(`Too many lights in light cluster ${this.name}, please adjust parameters.${ + this.reportCount === reportLimit - 1 ? ' Giving up on reporting it.' : ''}`); this.reportCount++; } } diff --git a/src/scene/materials/lit-material-options-builder.js b/src/scene/materials/lit-material-options-builder.js index 21351591586..13f27e1a647 100644 --- a/src/scene/materials/lit-material-options-builder.js +++ b/src/scene/materials/lit-material-options-builder.js @@ -5,7 +5,7 @@ import { SHADERDEF_NOSHADOW, SHADERDEF_TANGENTS, SPRITE_RENDERMODE_SIMPLE, SHADERDEF_MORPH_TEXTURE_BASED_INT, FOG_NONE -} from "../constants.js"; +} from '../constants.js'; class LitMaterialOptionsBuilder { static update(litOptions, material, scene, renderParams, objDefs, pass, sortedLights) { diff --git a/src/scene/materials/lit-material.js b/src/scene/materials/lit-material.js index f77c223335e..a6cf034dcb3 100644 --- a/src/scene/materials/lit-material.js +++ b/src/scene/materials/lit-material.js @@ -1,9 +1,9 @@ -import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; -import { DITHER_NONE, FRESNEL_SCHLICK, SPECOCC_AO } from "../constants.js"; -import { Material } from './material.js'; -import { LitMaterialOptions } from './lit-material-options.js'; import { LitMaterialOptionsBuilder } from './lit-material-options-builder.js'; -import { getProgramLibrary } from "../shader-lib/get-program-library.js"; +import { LitMaterialOptions } from './lit-material-options.js'; +import { Material } from './material.js'; +import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; +import { DITHER_NONE, FRESNEL_SCHLICK, SPECOCC_AO } from '../constants.js'; +import { getProgramLibrary } from '../shader-lib/get-program-library.js'; import { lit } from '../shader-lib/programs/lit.js'; const options = new LitMaterialOptions(); diff --git a/src/scene/materials/material.js b/src/scene/materials/material.js index e970c11b6db..e9b040c8076 100644 --- a/src/scene/materials/material.js +++ b/src/scene/materials/material.js @@ -1,4 +1,6 @@ +import { getDefaultMaterial } from './default-material.js'; import { Debug } from '../../core/debug.js'; +import { BlendState } from '../../platform/graphics/blend-state.js'; import { BLENDMODE_ZERO, BLENDMODE_ONE, BLENDMODE_SRC_COLOR, BLENDMODE_DST_COLOR, BLENDMODE_ONE_MINUS_DST_COLOR, BLENDMODE_SRC_ALPHA, @@ -7,14 +9,12 @@ import { BLENDEQUATION_MIN, BLENDEQUATION_MAX, CULLFACE_BACK } from '../../platform/graphics/constants.js'; -import { BlendState } from '../../platform/graphics/blend-state.js'; import { DepthState } from '../../platform/graphics/depth-state.js'; import { BLEND_ADDITIVE, BLEND_NORMAL, BLEND_NONE, BLEND_PREMULTIPLIED, BLEND_MULTIPLICATIVE, BLEND_ADDITIVEALPHA, BLEND_MULTIPLICATIVE2X, BLEND_SCREEN, BLEND_MIN, BLEND_MAX, BLEND_SUBTRACTIVE } from '../constants.js'; -import { getDefaultMaterial } from './default-material.js'; /** * @import { BindGroupFormat } from '../../platform/graphics/bind-group-format.js'; diff --git a/src/scene/materials/shader-material.js b/src/scene/materials/shader-material.js index ff217f7c824..6416de59739 100644 --- a/src/scene/materials/shader-material.js +++ b/src/scene/materials/shader-material.js @@ -1,8 +1,8 @@ +import { Material } from './material.js'; import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; import { SHADERDEF_INSTANCING, SHADERDEF_MORPH_NORMAL, SHADERDEF_MORPH_POSITION, SHADERDEF_MORPH_TEXTURE_BASED_INT, SHADERDEF_SKIN } from '../constants.js'; import { getProgramLibrary } from '../shader-lib/get-program-library.js'; import { shaderGeneratorShader } from '../shader-lib/programs/shader-generator-shader.js'; -import { Material } from './material.js'; /** * @typedef {object} ShaderDesc - The description of the shader used by the {@link ShaderMaterial}. diff --git a/src/scene/materials/standard-material-options-builder.js b/src/scene/materials/standard-material-options-builder.js index 19b3bf191bb..cb3d93c05b5 100644 --- a/src/scene/materials/standard-material-options-builder.js +++ b/src/scene/materials/standard-material-options-builder.js @@ -1,7 +1,7 @@ +import { LitMaterialOptionsBuilder } from './lit-material-options-builder.js'; import { PIXELFORMAT_DXT5, PIXELFORMAT_RGBA8, TEXTURETYPE_SWIZZLEGGGR } from '../../platform/graphics/constants.js'; - import { BLEND_NONE, LIGHTTYPE_DIRECTIONAL, LIGHTTYPE_OMNI, LIGHTTYPE_SPOT, @@ -15,7 +15,6 @@ import { FOG_NONE } from '../constants.js'; import { _matTex2D } from '../shader-lib/programs/standard.js'; -import { LitMaterialOptionsBuilder } from './lit-material-options-builder.js'; const arraysEqual = (a, b) => { if (a.length !== b.length) { @@ -129,13 +128,13 @@ class StandardMaterialOptionsBuilder { const isOpacity = p === 'opacity'; if (!minimalOptions || isOpacity) { - const mname = p + 'Map'; - const vname = p + 'VertexColor'; - const vcname = p + 'VertexColorChannel'; - const cname = mname + 'Channel'; - const tname = mname + 'Transform'; - const uname = mname + 'Uv'; - const iname = mname + 'Identifier'; + const mname = `${p}Map`; + const vname = `${p}VertexColor`; + const vcname = `${p}VertexColorChannel`; + const cname = `${mname}Channel`; + const tname = `${mname}Transform`; + const uname = `${mname}Uv`; + const iname = `${mname}Identifier`; // Avoid overriding previous lightMap properties if (p !== 'light') { diff --git a/src/scene/materials/standard-material-options.js b/src/scene/materials/standard-material-options.js index f579af82c21..88a329d96f1 100644 --- a/src/scene/materials/standard-material-options.js +++ b/src/scene/materials/standard-material-options.js @@ -1,4 +1,4 @@ -import { LitShaderOptions } from "../shader-lib/programs/lit-shader-options.js"; +import { LitShaderOptions } from '../shader-lib/programs/lit-shader-options.js'; /** * The standard material options define a set of options used to control the shader frontend shader diff --git a/src/scene/materials/standard-material-validator.js b/src/scene/materials/standard-material-validator.js index da4a80ba203..5822eff909d 100644 --- a/src/scene/materials/standard-material-validator.js +++ b/src/scene/materials/standard-material-validator.js @@ -1,3 +1,4 @@ +import { standardMaterialParameterTypes, standardMaterialRemovedParameters } from './standard-material-parameters.js'; import { Debug } from '../../core/debug.js'; import { CULLFACE_BACK, CULLFACE_FRONT, CULLFACE_FRONTANDBACK, CULLFACE_NONE, @@ -5,7 +6,6 @@ import { FUNC_GREATEREQUAL, FUNC_ALWAYS } from '../../platform/graphics/constants.js'; import { Texture } from '../../platform/graphics/texture.js'; - import { SPECOCC_AO, SPECOCC_GLOSSDEPENDENT, SPECOCC_NONE, BLEND_SUBTRACTIVE, BLEND_ADDITIVE, BLEND_NORMAL, BLEND_NONE, BLEND_PREMULTIPLIED, @@ -13,7 +13,6 @@ import { BLEND_MIN, BLEND_MAX } from '../constants.js'; -import { standardMaterialParameterTypes, standardMaterialRemovedParameters } from './standard-material-parameters.js'; class StandardMaterialValidator { constructor() { @@ -163,7 +162,7 @@ class StandardMaterialValidator { } } else { - console.error('Unknown material type: ' + type); + console.error(`Unknown material type: ${type}`); } } diff --git a/src/scene/materials/standard-material.js b/src/scene/materials/standard-material.js index 9e8404714fb..197a7bf80e0 100644 --- a/src/scene/materials/standard-material.js +++ b/src/scene/materials/standard-material.js @@ -1,7 +1,11 @@ +import { Material } from './material.js'; +import { StandardMaterialOptionsBuilder } from './standard-material-options-builder.js'; +import { standardMaterialCubemapParameters, standardMaterialTextureParameters } from './standard-material-parameters.js'; import { Debug } from '../../core/debug.js'; import { Color } from '../../core/math/color.js'; import { math } from '../../core/math/math.js'; import { Vec2 } from '../../core/math/vec2.js'; +import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; import { CUBEPROJ_BOX, CUBEPROJ_NONE, @@ -12,14 +16,10 @@ import { SHADER_PREPASS_VELOCITY, SPECOCC_AO } from '../constants.js'; -import { ShaderPass } from '../shader-pass.js'; import { EnvLighting } from '../graphics/env-lighting.js'; import { getProgramLibrary } from '../shader-lib/get-program-library.js'; import { _matTex2D, standard } from '../shader-lib/programs/standard.js'; -import { Material } from './material.js'; -import { StandardMaterialOptionsBuilder } from './standard-material-options-builder.js'; -import { standardMaterialCubemapParameters, standardMaterialTextureParameters } from './standard-material-parameters.js'; -import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { ShaderPass } from '../shader-pass.js'; /** * @import { BoundingBox } from '../../core/shape/bounding-box.js' @@ -626,8 +626,9 @@ class StandardMaterial extends Material { // clone chunks for (const p in source._chunks) { - if (source._chunks.hasOwnProperty(p)) + if (source._chunks.hasOwnProperty(p)) { this._chunks[p] = source._chunks[p]; + } } // clone user attributes @@ -675,12 +676,12 @@ class StandardMaterial extends Material { } _updateMap(p) { - const mname = p + 'Map'; + const mname = `${p}Map`; const map = this[mname]; if (map) { - this._setParameter('texture_' + mname, map); + this._setParameter(`texture_${mname}`, map); - const tname = mname + 'Transform'; + const tname = `${mname}Transform`; const uniform = this.getUniform(tname); if (uniform) { this._setParameters(uniform); @@ -860,10 +861,11 @@ class StandardMaterial extends Material { let options = minimalOptions ? standard.optionsContextMin : standard.optionsContext; options.defines = this.defines; - if (minimalOptions) + if (minimalOptions) { this.shaderOptBuilder.updateMinRef(options, scene, this, objDefs, pass, sortedLights); - else + } else { this.shaderOptBuilder.updateRef(options, scene, renderParams, this, objDefs, pass, sortedLights); + } // execute user callback to modify the options if (this.onUpdateShader) { @@ -950,7 +952,7 @@ const defineProp = (prop) => { return prop.defaultValue && prop.defaultValue.clone ? defineAggProp(prop) : defineValueProp(prop); }; -function _defineTex2D(name, channel = "rgb", vertexColor = true, uv = 0) { +function _defineTex2D(name, channel = 'rgb', vertexColor = true, uv = 0) { // store texture name _matTex2D[name] = channel.length || -1; diff --git a/src/scene/mesh-instance.js b/src/scene/mesh-instance.js index 867e866b6ce..a510300ab0b 100644 --- a/src/scene/mesh-instance.js +++ b/src/scene/mesh-instance.js @@ -1,8 +1,3 @@ -import { Debug, DebugHelper } from '../core/debug.js'; -import { BoundingBox } from '../core/shape/bounding-box.js'; -import { BoundingSphere } from '../core/shape/bounding-sphere.js'; -import { BindGroup } from '../platform/graphics/bind-group.js'; -import { UniformBuffer } from '../platform/graphics/uniform-buffer.js'; import { BLEND_NONE, BLEND_NORMAL, LAYER_WORLD, @@ -14,11 +9,16 @@ import { SORTKEY_FORWARD } from './constants.js'; import { GraphNode } from './graph-node.js'; -import { getDefaultMaterial } from './materials/default-material.js'; import { LightmapCache } from './graphics/lightmap-cache.js'; -import { DebugGraphics } from '../platform/graphics/debug-graphics.js'; -import { hash32Fnv1a } from '../core/hash.js'; +import { getDefaultMaterial } from './materials/default-material.js'; import { array } from '../core/array-utils.js'; +import { Debug, DebugHelper } from '../core/debug.js'; +import { hash32Fnv1a } from '../core/hash.js'; +import { BoundingBox } from '../core/shape/bounding-box.js'; +import { BoundingSphere } from '../core/shape/bounding-sphere.js'; +import { BindGroup } from '../platform/graphics/bind-group.js'; +import { DebugGraphics } from '../platform/graphics/debug-graphics.js'; +import { UniformBuffer } from '../platform/graphics/uniform-buffer.js'; /** * @import { BindGroupFormat } from '../platform/graphics/bind-group-format.js' @@ -400,7 +400,7 @@ class MeshInstance { * this.app.scene.root.addChild(entity); */ constructor(mesh, material, node = null) { - Debug.assert(!(mesh instanceof GraphNode), "Incorrect parameters for MeshInstance's constructor. Use new MeshInstance(mesh, material, node)"); + Debug.assert(!(mesh instanceof GraphNode), 'Incorrect parameters for MeshInstance\'s constructor. Use new MeshInstance(mesh, material, node)'); this.node = node; // The node that defines the transform of the mesh instance this._mesh = mesh; // The mesh that this instance renders @@ -451,8 +451,9 @@ class MeshInstance { */ set mesh(mesh) { - if (mesh === this._mesh) + if (mesh === this._mesh) { return; + } if (this._mesh) { this._mesh.decRefCount(); @@ -860,8 +861,9 @@ class MeshInstance { * @type {number} */ set instancingCount(value) { - if (this.instancingData) + if (this.instancingData) { this.instancingData.count = value; + } } /** @@ -1084,8 +1086,9 @@ class MeshInstance { setRealtimeLightmap(name, texture) { // no change const old = this.getParameter(name); - if (old === texture) + if (old === texture) { return; + } // remove old if (old) { @@ -1101,11 +1104,11 @@ class MeshInstance { } } - /** - * Deletes a shader parameter on a mesh instance. - * - * @param {string} name - The name of the parameter to delete. - */ + /** + * Deletes a shader parameter on a mesh instance. + * + * @param {string} name - The name of the parameter to delete. + */ deleteParameter(name) { if (this.parameters[name]) { delete this.parameters[name]; diff --git a/src/scene/mesh.js b/src/scene/mesh.js index 5699608eb00..3583af5d7eb 100644 --- a/src/scene/mesh.js +++ b/src/scene/mesh.js @@ -1,6 +1,7 @@ +import { RENDERSTYLE_SOLID, RENDERSTYLE_WIREFRAME, RENDERSTYLE_POINTS } from './constants.js'; import { Debug } from '../core/debug.js'; -import { RefCountedObject } from '../core/ref-counted-object.js'; import { Vec3 } from '../core/math/vec3.js'; +import { RefCountedObject } from '../core/ref-counted-object.js'; import { BoundingBox } from '../core/shape/bounding-box.js'; import { BUFFER_DYNAMIC, BUFFER_STATIC, @@ -15,7 +16,6 @@ import { IndexBuffer } from '../platform/graphics/index-buffer.js'; import { VertexBuffer } from '../platform/graphics/vertex-buffer.js'; import { VertexFormat } from '../platform/graphics/vertex-format.js'; import { VertexIterator } from '../platform/graphics/vertex-iterator.js'; -import { RENDERSTYLE_SOLID, RENDERSTYLE_WIREFRAME, RENDERSTYLE_POINTS } from './constants.js'; /** * @import { Geometry } from './geometry/geometry.js' @@ -284,7 +284,7 @@ class Mesh extends RefCountedObject { constructor(graphicsDevice, options) { super(); this.id = id++; - Debug.assert(graphicsDevice, "Mesh constructor takes a GraphicsDevice as a parameter, and it was not provided."); + Debug.assert(graphicsDevice, 'Mesh constructor takes a GraphicsDevice as a parameter, and it was not provided.'); this.device = graphicsDevice; this._storageIndex = options?.storageIndex || false; diff --git a/src/scene/morph-instance.js b/src/scene/morph-instance.js index 5d21057d02d..e4cdfffecc1 100644 --- a/src/scene/morph-instance.js +++ b/src/scene/morph-instance.js @@ -1,10 +1,10 @@ -import { Debug } from '../core/debug.js'; -import { BLENDEQUATION_ADD, BLENDMODE_ONE } from '../platform/graphics/constants.js'; import { drawQuadWithShader } from './graphics/quad-render-utils.js'; -import { RenderTarget } from '../platform/graphics/render-target.js'; -import { DebugGraphics } from '../platform/graphics/debug-graphics.js'; import { createShaderFromCode } from './shader-lib/utils.js'; +import { Debug } from '../core/debug.js'; import { BlendState } from '../platform/graphics/blend-state.js'; +import { BLENDEQUATION_ADD, BLENDMODE_ONE } from '../platform/graphics/constants.js'; +import { DebugGraphics } from '../platform/graphics/debug-graphics.js'; +import { RenderTarget } from '../platform/graphics/render-target.js'; /** * @import { Morph } from './morph.js' @@ -106,7 +106,7 @@ class MorphInstance { // resolve possible texture names for (let i = 0; i < this.maxSubmitCount; i++) { - this['morphBlendTex' + i] = this.device.scope.resolve('morphBlendTex' + i); + this[`morphBlendTex${i}`] = this.device.scope.resolve(`morphBlendTex${i}`); } this.morphFactor = this.device.scope.resolve('morphFactor[0]'); @@ -263,7 +263,7 @@ class MorphInstance { if (!shader) { const fs = this._getFragmentShader(count); const outputType = this.morph.intRenderFormat ? 'uvec4' : 'vec4'; - shader = createShaderFromCode(this.device, textureMorphVertexShader, fs, 'textureMorph' + count, undefined, { fragmentOutputTypes: [outputType] }); + shader = createShaderFromCode(this.device, textureMorphVertexShader, fs, `textureMorph${count}`, undefined, { fragmentOutputTypes: [outputType] }); this.shaderCache[count] = shader; } @@ -300,7 +300,7 @@ class MorphInstance { if (tex) { // texture - this['morphBlendTex' + usedCount].setValue(tex); + this[`morphBlendTex${usedCount}`].setValue(tex); // weight this._shaderMorphWeights[usedCount] = activeTarget.weight; @@ -332,11 +332,13 @@ class MorphInstance { if (this._activeTargets.length > 0 || !this.zeroTextures) { // blend morph targets into render targets - if (this.rtPositions) + if (this.rtPositions) { this._updateTextureRenderTarget(this.rtPositions, 'texturePositions', true); + } - if (this.rtNormals) + if (this.rtNormals) { this._updateTextureRenderTarget(this.rtNormals, 'textureNormals', false); + } // textures were cleared if no active targets this.zeroTextures = this._activeTargets.length === 0; @@ -389,7 +391,7 @@ class MorphInstance { if (this._activeTargets.length > this.maxSubmitCount) { // sort them by absWeight - this._activeTargets.sort(function (l, r) { + this._activeTargets.sort((l, r) => { return (l.absWeight < r.absWeight) ? 1 : (r.absWeight < l.absWeight ? -1 : 0); }); diff --git a/src/scene/morph-target.js b/src/scene/morph-target.js index eb19142050d..057cd1bf618 100644 --- a/src/scene/morph-target.js +++ b/src/scene/morph-target.js @@ -75,8 +75,9 @@ class MorphTarget { // lazy evaluation, which allows us to skip this completely if customAABB is used if (!this._aabb) { this._aabb = new BoundingBox(); - if (this.deltaPositions) + if (this.deltaPositions) { this._aabb.compute(this.deltaPositions); + } } return this._aabb; diff --git a/src/scene/morph.js b/src/scene/morph.js index c1931291b6f..f15082aef1b 100644 --- a/src/scene/morph.js +++ b/src/scene/morph.js @@ -1,7 +1,7 @@ import { Debug } from '../core/debug.js'; -import { RefCountedObject } from '../core/ref-counted-object.js'; -import { Vec3 } from '../core/math/vec3.js'; import { FloatPacking } from '../core/math/float-packing.js'; +import { Vec3 } from '../core/math/vec3.js'; +import { RefCountedObject } from '../core/ref-counted-object.js'; import { BoundingBox } from '../core/shape/bounding-box.js'; import { TYPE_UINT32, SEMANTIC_ATTR15, ADDRESS_CLAMP_TO_EDGE, FILTER_NEAREST, @@ -45,7 +45,7 @@ class Morph extends RefCountedObject { constructor(targets, graphicsDevice, { preferHighPrecision = false } = {}) { super(); - Debug.assert(graphicsDevice, "Morph constructor takes a GraphicsDevice as a parameter, and it was not provided."); + Debug.assert(graphicsDevice, 'Morph constructor takes a GraphicsDevice as a parameter, and it was not provided.'); this.device = graphicsDevice; this.preferHighPrecision = preferHighPrecision; diff --git a/src/scene/particle-system/cpu-updater.js b/src/scene/particle-system/cpu-updater.js index 978dd7440c2..265e3aa5a37 100644 --- a/src/scene/particle-system/cpu-updater.js +++ b/src/scene/particle-system/cpu-updater.js @@ -1,7 +1,6 @@ -import { math } from '../../core/math/math.js'; import { Mat4 } from '../../core/math/mat4.js'; +import { math } from '../../core/math/math.js'; import { Vec3 } from '../../core/math/vec3.js'; - import { EMITTERSHAPE_BOX, EMITTERSHAPE_SPHERE, PARTICLESORT_NONE } from '../constants.js'; let nonUniformScale; @@ -96,18 +95,20 @@ class ParticleCPUUpdater { randomPos.y = edgeY * (max === Math.abs(randomPos.y) ? Math.sign(randomPos.y) : 2 * randomPos.y); randomPos.z = edgeZ * (max === Math.abs(randomPos.z) ? Math.sign(randomPos.z) : 2 * randomPos.z); - if (!emitter.localSpace) + if (!emitter.localSpace) { randomPosTformed.copy(emitterPos).add(spawnMatrix.transformPoint(randomPos)); - else + } else { randomPosTformed.copy(spawnMatrix.transformPoint(randomPos)); + } } else { randomPos.normalize(); const spawnBoundsSphereInnerRatio = (emitter.emitterRadius === 0) ? 0 : emitter.emitterRadiusInner / emitter.emitterRadius; const r = rW * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio; - if (!emitter.localSpace) + if (!emitter.localSpace) { randomPosTformed.copy(emitterPos).add(randomPos.mulScalar(r * emitter.emitterRadius)); - else + } else { randomPosTformed.copy(randomPos.mulScalar(r * emitter.emitterRadius)); + } } const particleRate = math.lerp(emitter.rate, emitter.rate2, rX); @@ -258,10 +259,11 @@ class ParticleCPUUpdater { particlePosPrev.y = particleTex[id * particleTexChannels + 1]; particlePosPrev.z = particleTex[id * particleTexChannels + 2]; - if (!emitter.localSpace) + if (!emitter.localSpace) { radialVelocityVec.copy(particlePosPrev).sub(emitterPos); - else + } else { radialVelocityVec.copy(particlePosPrev); + } radialVelocityVec.normalize().mulScalar(radialSpeed); cf *= 3; @@ -361,13 +363,15 @@ class ParticleCPUUpdater { particleTex[id * particleTexChannels + 3] += rotSpeed * delta; if (emitter.wrap && emitter.wrapBounds) { - if (!emitter.localSpace) + if (!emitter.localSpace) { particleFinalPos.sub(emitterPos); + } particleFinalPos.x = glMod(particleFinalPos.x, emitter.wrapBounds.x) - emitter.wrapBounds.x * 0.5; particleFinalPos.y = glMod(particleFinalPos.y, emitter.wrapBounds.y) - emitter.wrapBounds.y * 0.5; particleFinalPos.z = glMod(particleFinalPos.z, emitter.wrapBounds.z) - emitter.wrapBounds.z * 0.5; - if (!emitter.localSpace) + if (!emitter.localSpace) { particleFinalPos.add(emitterPos); + } } if (emitter.sort > 0) { @@ -402,8 +406,9 @@ class ParticleCPUUpdater { particleTex[id * particleTexChannels + 3 + emitter.numParticlesPot * 2 * particleTexChannels] = 1; } } - if (particleTex[id * particleTexChannels + 3 + emitter.numParticlesPot * 2 * particleTexChannels] < 0) + if (particleTex[id * particleTexChannels + 3 + emitter.numParticlesPot * 2 * particleTexChannels] < 0) { particleEnabled = false; + } particleTex[id * particleTexChannels + 3 + emitter.numParticlesPot * particleTexChannels] = life; for (let v = 0; v < emitter.numParticleVerts; v++) { @@ -449,7 +454,7 @@ class ParticleCPUUpdater { emitter.vbOld.set(emitter.vbCPU); - vbToSort.sort(function (p1, p2) { + vbToSort.sort((p1, p2) => { return p1[1] - p2[1]; }); diff --git a/src/scene/particle-system/gpu-updater.js b/src/scene/particle-system/gpu-updater.js index 4e5a8759ea5..c4b2f67d8a2 100644 --- a/src/scene/particle-system/gpu-updater.js +++ b/src/scene/particle-system/gpu-updater.js @@ -1,16 +1,13 @@ -import { math } from '../../core/math/math.js'; import { Mat3 } from '../../core/math/mat3.js'; import { Mat4 } from '../../core/math/mat4.js'; +import { math } from '../../core/math/math.js'; import { Vec3 } from '../../core/math/vec3.js'; - +import { BlendState } from '../../platform/graphics/blend-state.js'; import { CULLFACE_NONE } from '../../platform/graphics/constants.js'; import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; -import { BlendState } from '../../platform/graphics/blend-state.js'; import { DepthState } from '../../platform/graphics/depth-state.js'; - -import { drawQuadWithShader } from '../graphics/quad-render-utils.js'; - import { EMITTERSHAPE_BOX } from '../constants.js'; +import { drawQuadWithShader } from '../graphics/quad-render-utils.js'; const spawnMatrix3 = new Mat3(); const emitterMatrix3 = new Mat3(); @@ -186,8 +183,9 @@ class ParticleGPUUpdater { emitter.prevWorldBoundsSize.copy(emitter.worldBoundsSize); emitter.prevWorldBoundsCenter.copy(emitter.worldBounds.center); - if (emitter.pack8) + if (emitter.pack8) { this._setInputBounds(); + } DebugGraphics.popGpuMarker(device); } diff --git a/src/scene/particle-system/particle-emitter.js b/src/scene/particle-system/particle-emitter.js index 5c0518b9132..31b78a88b60 100644 --- a/src/scene/particle-system/particle-emitter.js +++ b/src/scene/particle-system/particle-emitter.js @@ -1,13 +1,15 @@ +import { ParticleCPUUpdater } from './cpu-updater.js'; +import { ParticleGPUUpdater } from './gpu-updater.js'; +import { ParticleMaterial } from './particle-material.js'; import { Debug } from '../../core/debug.js'; -import { now } from '../../core/time.js'; -import { Curve } from '../../core/math/curve.js'; import { CurveSet } from '../../core/math/curve-set.js'; +import { Curve } from '../../core/math/curve.js'; import { Mat4 } from '../../core/math/mat4.js'; import { math } from '../../core/math/math.js'; import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; - +import { now } from '../../core/time.js'; import { ADDRESS_CLAMP_TO_EDGE, BUFFER_DYNAMIC, @@ -28,7 +30,6 @@ import { RenderTarget } from '../../platform/graphics/render-target.js'; import { Texture } from '../../platform/graphics/texture.js'; import { VertexBuffer } from '../../platform/graphics/vertex-buffer.js'; import { VertexFormat } from '../../platform/graphics/vertex-format.js'; - import { BLEND_NORMAL, EMITTERSHAPE_BOX, @@ -36,13 +37,10 @@ import { PARTICLEORIENTATION_SCREEN, PARTICLEORIENTATION_WORLD, PARTICLESORT_NONE } from '../constants.js'; -import { Mesh } from '../mesh.js'; import { MeshInstance } from '../mesh-instance.js'; -import { createShaderFromCode } from '../shader-lib/utils.js'; +import { Mesh } from '../mesh.js'; import { shaderChunks } from '../shader-lib/chunks/chunks.js'; -import { ParticleCPUUpdater } from './cpu-updater.js'; -import { ParticleGPUUpdater } from './gpu-updater.js'; -import { ParticleMaterial } from './particle-material.js'; +import { createShaderFromCode } from '../shader-lib/utils.js'; const particleVerts = [ [-1, -1], @@ -54,8 +52,9 @@ const particleVerts = [ function _createTexture(device, width, height, pixelData, format = PIXELFORMAT_RGBA32F, mult8Bit, filter) { let mipFilter = FILTER_NEAREST; - if (filter && (format === PIXELFORMAT_RGBA8 || format === PIXELFORMAT_SRGBA8)) + if (filter && (format === PIXELFORMAT_RGBA8 || format === PIXELFORMAT_SRGBA8)) { mipFilter = FILTER_LINEAR; + } const texture = new Texture(device, { width: width, @@ -277,7 +276,7 @@ class ParticleEmitter { setProperty('alignToMotion', false); setProperty('depthSoftening', 0); setProperty('mesh', null); // Mesh to be used as particle. Vertex buffer is supposed to hold vertex position in first 3 floats of each vertex - // Leave undefined to use simple quads + // Leave undefined to use simple quads setProperty('particleNormal', new Vec3(0, 1, 0)); setProperty('orientation', PARTICLEORIENTATION_SCREEN); @@ -894,8 +893,9 @@ class ParticleEmitter { n = emitterMat.transformVector(this.particleNormal).normalize(); } const t = new Vec3(1, 0, 0); - if (Math.abs(t.dot(n)) === 1) + if (Math.abs(t.dot(n)) === 1) { t.set(0, 0, 1); + } const b = new Vec3().cross(n, t).normalize(); t.cross(b, n).normalize(); tangent = new Float32Array([t.x, t.y, t.z]); diff --git a/src/scene/particle-system/particle-material.js b/src/scene/particle-system/particle-material.js index dbf7cce5dcf..fea61684d74 100644 --- a/src/scene/particle-system/particle-material.js +++ b/src/scene/particle-system/particle-material.js @@ -6,8 +6,8 @@ import { SHADER_FORWARD, TONEMAP_LINEAR } from '../constants.js'; -import { getProgramLibrary } from '../shader-lib/get-program-library.js'; import { Material } from '../materials/material.js'; +import { getProgramLibrary } from '../shader-lib/get-program-library.js'; import { particle } from '../shader-lib/programs/particle.js'; /** diff --git a/src/scene/renderer/forward-renderer.js b/src/scene/renderer/forward-renderer.js index f1e038b8ded..0aa8b6cd547 100644 --- a/src/scene/renderer/forward-renderer.js +++ b/src/scene/renderer/forward-renderer.js @@ -1,7 +1,11 @@ -import { now } from '../../core/time.js'; +import { LightCamera } from './light-camera.js'; +import { RenderPassForward } from './render-pass-forward.js'; +import { RenderPassPostprocessing } from './render-pass-postprocessing.js'; +import { Renderer } from './renderer.js'; import { Debug } from '../../core/debug.js'; -import { Vec3 } from '../../core/math/vec3.js'; import { Color } from '../../core/math/color.js'; +import { Vec3 } from '../../core/math/vec3.js'; +import { now } from '../../core/time.js'; import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; import { FOG_NONE, FOG_LINEAR, @@ -10,10 +14,6 @@ import { LAYERID_DEPTH } from '../constants.js'; import { WorldClustersDebug } from '../lighting/world-clusters-debug.js'; -import { Renderer } from './renderer.js'; -import { LightCamera } from './light-camera.js'; -import { RenderPassForward } from './render-pass-forward.js'; -import { RenderPassPostprocessing } from './render-pass-postprocessing.js'; /** * @import { BindGroup } from '../../platform/graphics/bind-group.js' @@ -174,34 +174,34 @@ class ForwardRenderer extends Renderer { } _resolveLight(scope, i) { - const light = 'light' + i; - this.lightColorId[i] = scope.resolve(light + '_color'); + const light = `light${i}`; + this.lightColorId[i] = scope.resolve(`${light}_color`); this.lightDir[i] = new Float32Array(3); - this.lightDirId[i] = scope.resolve(light + '_direction'); - this.lightShadowMapId[i] = scope.resolve(light + '_shadowMap'); - this.lightShadowMatrixId[i] = scope.resolve(light + '_shadowMatrix'); - this.lightShadowParamsId[i] = scope.resolve(light + '_shadowParams'); - this.lightShadowIntensity[i] = scope.resolve(light + '_shadowIntensity'); - this.lightShadowSearchAreaId[i] = scope.resolve(light + '_shadowSearchArea'); - this.lightRadiusId[i] = scope.resolve(light + '_radius'); + this.lightDirId[i] = scope.resolve(`${light}_direction`); + this.lightShadowMapId[i] = scope.resolve(`${light}_shadowMap`); + this.lightShadowMatrixId[i] = scope.resolve(`${light}_shadowMatrix`); + this.lightShadowParamsId[i] = scope.resolve(`${light}_shadowParams`); + this.lightShadowIntensity[i] = scope.resolve(`${light}_shadowIntensity`); + this.lightShadowSearchAreaId[i] = scope.resolve(`${light}_shadowSearchArea`); + this.lightRadiusId[i] = scope.resolve(`${light}_radius`); this.lightPos[i] = new Float32Array(3); - this.lightPosId[i] = scope.resolve(light + '_position'); + this.lightPosId[i] = scope.resolve(`${light}_position`); this.lightWidth[i] = new Float32Array(3); - this.lightWidthId[i] = scope.resolve(light + '_halfWidth'); + this.lightWidthId[i] = scope.resolve(`${light}_halfWidth`); this.lightHeight[i] = new Float32Array(3); - this.lightHeightId[i] = scope.resolve(light + '_halfHeight'); - this.lightInAngleId[i] = scope.resolve(light + '_innerConeAngle'); - this.lightOutAngleId[i] = scope.resolve(light + '_outerConeAngle'); - this.lightCookieId[i] = scope.resolve(light + '_cookie'); - this.lightCookieIntId[i] = scope.resolve(light + '_cookieIntensity'); - this.lightCookieMatrixId[i] = scope.resolve(light + '_cookieMatrix'); - this.lightCookieOffsetId[i] = scope.resolve(light + '_cookieOffset'); - this.lightCameraParamsId[i] = scope.resolve(light + '_cameraParams'); + this.lightHeightId[i] = scope.resolve(`${light}_halfHeight`); + this.lightInAngleId[i] = scope.resolve(`${light}_innerConeAngle`); + this.lightOutAngleId[i] = scope.resolve(`${light}_outerConeAngle`); + this.lightCookieId[i] = scope.resolve(`${light}_cookie`); + this.lightCookieIntId[i] = scope.resolve(`${light}_cookieIntensity`); + this.lightCookieMatrixId[i] = scope.resolve(`${light}_cookieMatrix`); + this.lightCookieOffsetId[i] = scope.resolve(`${light}_cookieOffset`); + this.lightCameraParamsId[i] = scope.resolve(`${light}_cameraParams`); // shadow cascades - this.shadowMatrixPaletteId[i] = scope.resolve(light + '_shadowMatrixPalette[0]'); - this.shadowCascadeDistancesId[i] = scope.resolve(light + '_shadowCascadeDistances[0]'); - this.shadowCascadeCountId[i] = scope.resolve(light + '_shadowCascadeCount'); + this.shadowMatrixPaletteId[i] = scope.resolve(`${light}_shadowMatrixPalette[0]`); + this.shadowCascadeDistancesId[i] = scope.resolve(`${light}_shadowCascadeDistances[0]`); + this.shadowCascadeCountId[i] = scope.resolve(`${light}_shadowCascadeCount`); } setLTCDirectionalLight(wtm, cnt, dir, campos, far) { @@ -504,13 +504,15 @@ class ForwardRenderer extends Renderer { // #if _PROFILER if (camera === ForwardRenderer.skipRenderCamera) { - if (ForwardRenderer._skipRenderCounter >= ForwardRenderer.skipRenderAfter) + if (ForwardRenderer._skipRenderCounter >= ForwardRenderer.skipRenderAfter) { continue; + } ForwardRenderer._skipRenderCounter++; } if (layer) { - if (layer._skipRenderCounter >= layer.skipRenderAfter) + if (layer._skipRenderCounter >= layer.skipRenderAfter) { continue; + } layer._skipRenderCounter++; } // #endif @@ -773,16 +775,17 @@ class ForwardRenderer extends Renderer { const forwardDrawCalls = this._forwardDrawCalls; this.renderForward(camera, - renderTarget, - visible, - splitLights, - shaderPass, - layer?.onDrawCall, - layer, - flipFaces); - - if (layer) + renderTarget, + visible, + splitLights, + shaderPass, + layer?.onDrawCall, + layer, + flipFaces); + + if (layer) { layer._forwardDrawCalls += this._forwardDrawCalls - forwardDrawCalls; + } } setSceneConstants() { diff --git a/src/scene/renderer/light-camera.js b/src/scene/renderer/light-camera.js index 160283c0cf8..35b191ad41b 100644 --- a/src/scene/renderer/light-camera.js +++ b/src/scene/renderer/light-camera.js @@ -1,9 +1,8 @@ +import { Mat4 } from '../../core/math/mat4.js'; import { Quat } from '../../core/math/quat.js'; import { Vec3 } from '../../core/math/vec3.js'; -import { Mat4 } from '../../core/math/mat4.js'; - -import { ASPECT_MANUAL, LIGHTTYPE_DIRECTIONAL, LIGHTTYPE_OMNI, LIGHTTYPE_SPOT, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE } from '../constants.js'; import { Camera } from '../camera.js'; +import { ASPECT_MANUAL, LIGHTTYPE_DIRECTIONAL, LIGHTTYPE_OMNI, LIGHTTYPE_SPOT, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE } from '../constants.js'; import { GraphNode } from '../graph-node.js'; const _viewMat = new Mat4(); diff --git a/src/scene/renderer/render-pass-cookie-renderer.js b/src/scene/renderer/render-pass-cookie-renderer.js index 22af89d4135..e7b9dbdc9dc 100644 --- a/src/scene/renderer/render-pass-cookie-renderer.js +++ b/src/scene/renderer/render-pass-cookie-renderer.js @@ -1,15 +1,15 @@ +import { LightCamera } from './light-camera.js'; import { Debug } from '../../core/debug.js'; -import { Vec4 } from '../../core/math/vec4.js'; import { Mat4 } from '../../core/math/mat4.js'; +import { Vec4 } from '../../core/math/vec4.js'; +import { BlendState } from '../../platform/graphics/blend-state.js'; import { CULLFACE_NONE } from '../../platform/graphics/constants.js'; import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { DepthState } from '../../platform/graphics/depth-state.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; import { LIGHTTYPE_DIRECTIONAL, LIGHTTYPE_OMNI } from '../constants.js'; -import { createShaderFromCode } from '../shader-lib/utils.js'; -import { LightCamera } from './light-camera.js'; -import { BlendState } from '../../platform/graphics/blend-state.js'; import { QuadRender } from '../graphics/quad-render.js'; -import { DepthState } from '../../platform/graphics/depth-state.js'; -import { RenderPass } from "../../platform/graphics/render-pass.js"; +import { createShaderFromCode } from '../shader-lib/utils.js'; const textureBlitVertexShader = /* glsl */ ` attribute vec2 vertex_position; @@ -104,16 +104,19 @@ class RenderPassCookieRenderer extends RenderPass { const light = lights[i]; // skip directional lights - if (light._type === LIGHTTYPE_DIRECTIONAL) + if (light._type === LIGHTTYPE_DIRECTIONAL) { continue; + } // skip clustered cookies with no assigned atlas slot - if (!light.atlasViewportAllocated) + if (!light.atlasViewportAllocated) { continue; + } // only render cookie when the slot is reassigned (assuming the cookie texture is static) - if (!light.atlasSlotUpdated) + if (!light.atlasSlotUpdated) { continue; + } if (light.enabled && light.cookie && light.visibleThisFrame) { filteredLights.push(light); @@ -134,7 +137,7 @@ class RenderPassCookieRenderer extends RenderPass { get quadRenderer2D() { if (!this._quadRenderer2D) { - const shader = createShaderFromCode(this.device, textureBlitVertexShader, textureBlitFragmentShader, `cookieRenderer2d`); + const shader = createShaderFromCode(this.device, textureBlitVertexShader, textureBlitFragmentShader, 'cookieRenderer2d'); this._quadRenderer2D = new QuadRender(shader); } return this._quadRenderer2D; @@ -142,7 +145,7 @@ class RenderPassCookieRenderer extends RenderPass { get quadRendererCube() { if (!this._quadRendererCube) { - const shader = createShaderFromCode(this.device, textureBlitVertexShader, textureCubeBlitFragmentShader, `cookieRendererCube`); + const shader = createShaderFromCode(this.device, textureBlitVertexShader, textureCubeBlitFragmentShader, 'cookieRendererCube'); this._quadRendererCube = new QuadRender(shader); } return this._quadRendererCube; diff --git a/src/scene/renderer/render-pass-forward.js b/src/scene/renderer/render-pass-forward.js index 20108ca6b7b..1d5f432f512 100644 --- a/src/scene/renderer/render-pass-forward.js +++ b/src/scene/renderer/render-pass-forward.js @@ -1,12 +1,12 @@ -import { TRACEID_RENDER_PASS_DETAIL } from "../../core/constants.js"; -import { Debug } from "../../core/debug.js"; -import { now } from "../../core/time.js"; -import { Tracing } from "../../core/tracing.js"; -import { BlendState } from "../../platform/graphics/blend-state.js"; -import { DebugGraphics } from "../../platform/graphics/debug-graphics.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; -import { RenderAction } from "../composition/render-action.js"; -import { SHADER_FORWARD } from "../constants.js"; +import { TRACEID_RENDER_PASS_DETAIL } from '../../core/constants.js'; +import { Debug } from '../../core/debug.js'; +import { now } from '../../core/time.js'; +import { Tracing } from '../../core/tracing.js'; +import { BlendState } from '../../platform/graphics/blend-state.js'; +import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; +import { RenderAction } from '../composition/render-action.js'; +import { SHADER_FORWARD } from '../constants.js'; /** * @import { CameraComponent } from '../../framework/components/camera/component.js' @@ -75,7 +75,7 @@ class RenderPassForward extends RenderPass { addLayer(cameraComponent, layer, transparent, autoClears = true) { Debug.assert(cameraComponent); - Debug.assert(this.renderTarget !== undefined, `Render pass needs to be initialized before adding layers`); + Debug.assert(this.renderTarget !== undefined, 'Render pass needs to be initialized before adding layers'); Debug.assert(cameraComponent.camera.layersSet.has(layer.id), `Camera ${cameraComponent.entity.name} does not render layer ${layer.name}.`); const ra = new RenderAction(); @@ -284,7 +284,7 @@ class RenderPassForward extends RenderPass { const renderTarget = renderAction.renderTarget ?? device.backBuffer; renderer.renderForwardLayer(camera.camera, renderTarget, layer, transparent, - shaderPass, renderAction.viewBindGroups, options); + shaderPass, renderAction.viewBindGroups, options); // Revert temp frame stuff // TODO: this should not be here, as each rendering / clearing should explicitly set up what @@ -329,12 +329,12 @@ class RenderPassForward extends RenderPass { const enabled = layer.enabled && layerComposition.isEnabled(layer, ra.transparent); const camera = ra.camera; - Debug.trace(TRACEID_RENDER_PASS_DETAIL, ` ${index}:` + - (' Cam: ' + (camera ? camera.entity.name : '-')).padEnd(22, ' ') + - (' Lay: ' + layer.name).padEnd(22, ' ') + - (ra.transparent ? ' TRANSP' : ' OPAQUE') + - (enabled ? ' ENABLED' : ' DISABLED') + - (' Meshes: ' + layer.meshInstances.length).padEnd(5, ' ') + Debug.trace(TRACEID_RENDER_PASS_DETAIL, ` ${index}:${ + (` Cam: ${camera ? camera.entity.name : '-'}`).padEnd(22, ' ') + }${(` Lay: ${layer.name}`).padEnd(22, ' ') + }${ra.transparent ? ' TRANSP' : ' OPAQUE' + }${enabled ? ' ENABLED' : ' DISABLED' + }${(` Meshes: ${layer.meshInstances.length}`).padEnd(5, ' ')}` ); }); } diff --git a/src/scene/renderer/render-pass-postprocessing.js b/src/scene/renderer/render-pass-postprocessing.js index ebb466d0628..0927451281a 100644 --- a/src/scene/renderer/render-pass-postprocessing.js +++ b/src/scene/renderer/render-pass-postprocessing.js @@ -1,5 +1,5 @@ -import { Debug } from "../../core/debug.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; +import { Debug } from '../../core/debug.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; /** * A render pass used to render post-effects. diff --git a/src/scene/renderer/render-pass-shadow-directional.js b/src/scene/renderer/render-pass-shadow-directional.js index 890388dd6a3..91d0623ec40 100644 --- a/src/scene/renderer/render-pass-shadow-directional.js +++ b/src/scene/renderer/render-pass-shadow-directional.js @@ -1,6 +1,6 @@ -import { DebugHelper } from "../../core/debug.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; -import { SHADOWUPDATE_NONE, SHADOWUPDATE_THISFRAME } from "../constants.js"; +import { DebugHelper } from '../../core/debug.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; +import { SHADOWUPDATE_NONE, SHADOWUPDATE_THISFRAME } from '../constants.js'; /** * A render pass used to render directional shadows. diff --git a/src/scene/renderer/render-pass-shadow-local-clustered.js b/src/scene/renderer/render-pass-shadow-local-clustered.js index 67e12d71a02..f453b193c71 100644 --- a/src/scene/renderer/render-pass-shadow-local-clustered.js +++ b/src/scene/renderer/render-pass-shadow-local-clustered.js @@ -1,4 +1,4 @@ -import { RenderPass } from "../../platform/graphics/render-pass.js"; +import { RenderPass } from '../../platform/graphics/render-pass.js'; /** * A render pass used to render local clustered shadows. This is done inside a single render pass, diff --git a/src/scene/renderer/render-pass-shadow-local-non-clustered.js b/src/scene/renderer/render-pass-shadow-local-non-clustered.js index af76125bcd5..3499b88c8d1 100644 --- a/src/scene/renderer/render-pass-shadow-local-non-clustered.js +++ b/src/scene/renderer/render-pass-shadow-local-non-clustered.js @@ -1,5 +1,5 @@ -import { DebugHelper } from "../../core/debug.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; +import { DebugHelper } from '../../core/debug.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; /** * A render pass used to render local non-clustered shadows. It represents rendering to a single diff --git a/src/scene/renderer/render-pass-update-clustered.js b/src/scene/renderer/render-pass-update-clustered.js index b36c3db0520..d8ad385d831 100644 --- a/src/scene/renderer/render-pass-update-clustered.js +++ b/src/scene/renderer/render-pass-update-clustered.js @@ -1,7 +1,7 @@ -import { now } from "../../core/time.js"; -import { RenderPass } from "../../platform/graphics/render-pass.js"; -import { RenderPassCookieRenderer } from "./render-pass-cookie-renderer.js"; -import { RenderPassShadowLocalClustered } from "./render-pass-shadow-local-clustered.js"; +import { RenderPassCookieRenderer } from './render-pass-cookie-renderer.js'; +import { RenderPassShadowLocalClustered } from './render-pass-shadow-local-clustered.js'; +import { now } from '../../core/time.js'; +import { RenderPass } from '../../platform/graphics/render-pass.js'; /** * A render pass used to update clustered lighting data - shadows, cookies, world clusters. diff --git a/src/scene/renderer/renderer.js b/src/scene/renderer/renderer.js index 2f94d027a9c..b545740b9d3 100644 --- a/src/scene/renderer/renderer.js +++ b/src/scene/renderer/renderer.js @@ -1,12 +1,20 @@ +import { RenderPassUpdateClustered } from './render-pass-update-clustered.js'; +import { ShadowMapCache } from './shadow-map-cache.js'; +import { ShadowRendererDirectional } from './shadow-renderer-directional.js'; +import { ShadowRendererLocal } from './shadow-renderer-local.js'; +import { ShadowRenderer } from './shadow-renderer.js'; +import { WorldClustersAllocator } from './world-clusters-allocator.js'; import { Debug, DebugHelper } from '../../core/debug.js'; -import { now } from '../../core/time.js'; import { BlueNoise } from '../../core/math/blue-noise.js'; +import { Mat3 } from '../../core/math/mat3.js'; +import { Mat4 } from '../../core/math/mat4.js'; import { Vec2 } from '../../core/math/vec2.js'; import { Vec3 } from '../../core/math/vec3.js'; import { Vec4 } from '../../core/math/vec4.js'; -import { Mat3 } from '../../core/math/mat3.js'; -import { Mat4 } from '../../core/math/mat4.js'; import { BoundingSphere } from '../../core/shape/bounding-sphere.js'; +import { now } from '../../core/time.js'; +import { BindGroupFormat, BindUniformBufferFormat, BindTextureFormat } from '../../platform/graphics/bind-group-format.js'; +import { BindGroup, DynamicBindGroup } from '../../platform/graphics/bind-group.js'; import { CLEARFLAG_COLOR, CLEARFLAG_DEPTH, CLEARFLAG_STENCIL, BINDGROUP_MESH, BINDGROUP_VIEW, UNIFORM_BUFFER_DEFAULT_SLOT_NAME, @@ -17,10 +25,8 @@ import { BINDGROUP_MESH_UB } from '../../platform/graphics/constants.js'; import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; -import { UniformBuffer } from '../../platform/graphics/uniform-buffer.js'; -import { BindGroup, DynamicBindGroup } from '../../platform/graphics/bind-group.js'; import { UniformFormat, UniformBufferFormat } from '../../platform/graphics/uniform-buffer-format.js'; -import { BindGroupFormat, BindUniformBufferFormat, BindTextureFormat } from '../../platform/graphics/bind-group-format.js'; +import { UniformBuffer } from '../../platform/graphics/uniform-buffer.js'; import { SORTKEY_DEPTH, SORTKEY_FORWARD, VIEW_CENTER, PROJECTION_ORTHOGRAPHIC, @@ -31,12 +37,6 @@ import { LightCube } from '../graphics/light-cube.js'; import { getBlueNoiseTexture } from '../graphics/noise-textures.js'; import { LightTextureAtlas } from '../lighting/light-texture-atlas.js'; import { Material } from '../materials/material.js'; -import { ShadowMapCache } from './shadow-map-cache.js'; -import { ShadowRendererLocal } from './shadow-renderer-local.js'; -import { ShadowRendererDirectional } from './shadow-renderer-directional.js'; -import { ShadowRenderer } from './shadow-renderer.js'; -import { WorldClustersAllocator } from './world-clusters-allocator.js'; -import { RenderPassUpdateClustered } from './render-pass-update-clustered.js'; /** * @import { Camera } from '../camera.js' @@ -181,7 +181,7 @@ class Renderer { // clustered passes this._renderPassUpdateClustered = new RenderPassUpdateClustered(this.device, this, this.shadowRenderer, - this._shadowRendererLocal, this.lightTextureAtlas); + this._shadowRendererLocal, this.lightTextureAtlas); // view bind group format with its uniform buffer format this.viewUniformFormat = null; @@ -759,26 +759,26 @@ class Renderer { // format of the view uniform buffer const uniforms = [ - new UniformFormat("matrix_viewProjection", UNIFORMTYPE_MAT4), - new UniformFormat("cubeMapRotationMatrix", UNIFORMTYPE_MAT3), - new UniformFormat("view_position", UNIFORMTYPE_VEC3), - new UniformFormat("skyboxIntensity", UNIFORMTYPE_FLOAT), - new UniformFormat("exposure", UNIFORMTYPE_FLOAT), - new UniformFormat("textureBias", UNIFORMTYPE_FLOAT) + new UniformFormat('matrix_viewProjection', UNIFORMTYPE_MAT4), + new UniformFormat('cubeMapRotationMatrix', UNIFORMTYPE_MAT3), + new UniformFormat('view_position', UNIFORMTYPE_VEC3), + new UniformFormat('skyboxIntensity', UNIFORMTYPE_FLOAT), + new UniformFormat('exposure', UNIFORMTYPE_FLOAT), + new UniformFormat('textureBias', UNIFORMTYPE_FLOAT) ]; if (isClustered) { uniforms.push(...[ - new UniformFormat("clusterCellsCountByBoundsSize", UNIFORMTYPE_VEC3), - new UniformFormat("clusterTextureSize", UNIFORMTYPE_VEC3), - new UniformFormat("clusterBoundsMin", UNIFORMTYPE_VEC3), - new UniformFormat("clusterBoundsDelta", UNIFORMTYPE_VEC3), - new UniformFormat("clusterCellsDot", UNIFORMTYPE_VEC3), - new UniformFormat("clusterCellsMax", UNIFORMTYPE_VEC3), - new UniformFormat("clusterCompressionLimit0", UNIFORMTYPE_VEC2), - new UniformFormat("shadowAtlasParams", UNIFORMTYPE_VEC2), - new UniformFormat("clusterMaxCells", UNIFORMTYPE_INT), - new UniformFormat("clusterSkip", UNIFORMTYPE_FLOAT) + new UniformFormat('clusterCellsCountByBoundsSize', UNIFORMTYPE_VEC3), + new UniformFormat('clusterTextureSize', UNIFORMTYPE_VEC3), + new UniformFormat('clusterBoundsMin', UNIFORMTYPE_VEC3), + new UniformFormat('clusterBoundsDelta', UNIFORMTYPE_VEC3), + new UniformFormat('clusterCellsDot', UNIFORMTYPE_VEC3), + new UniformFormat('clusterCellsMax', UNIFORMTYPE_VEC3), + new UniformFormat('clusterCompressionLimit0', UNIFORMTYPE_VEC2), + new UniformFormat('shadowAtlasParams', UNIFORMTYPE_VEC2), + new UniformFormat('clusterMaxCells', UNIFORMTYPE_INT), + new UniformFormat('clusterSkip', UNIFORMTYPE_FLOAT) ]); } @@ -811,10 +811,10 @@ class Renderer { setupViewUniformBuffers(viewBindGroups, viewUniformFormat, viewBindGroupFormat, viewCount) { - Debug.assert(Array.isArray(viewBindGroups), "viewBindGroups must be an array"); + Debug.assert(Array.isArray(viewBindGroups), 'viewBindGroups must be an array'); const device = this.device; - Debug.assert(viewCount === 1, "This code does not handle the viewCount yet"); + Debug.assert(viewCount === 1, 'This code does not handle the viewCount yet'); while (viewBindGroups.length < viewCount) { const ub = new UniformBuffer(device, viewUniformFormat, false); @@ -1204,8 +1204,9 @@ class Renderer { if (onlyLitShaders) { // skip materials not using lighting - if (!mat.useLighting || (mat.emitter && !mat.emitter.lighting)) + if (!mat.useLighting || (mat.emitter && !mat.emitter.lighting)) { continue; + } } // clear shader variants on the material and also on mesh instances that use it diff --git a/src/scene/renderer/shadow-map-cache.js b/src/scene/renderer/shadow-map-cache.js index ad9b9738026..1d686b07c1f 100644 --- a/src/scene/renderer/shadow-map-cache.js +++ b/src/scene/renderer/shadow-map-cache.js @@ -1,7 +1,7 @@ +import { ShadowMap } from './shadow-map.js'; import { LIGHTTYPE_OMNI } from '../constants.js'; -import { ShadowMap } from './shadow-map.js'; // In the normal case where the light renders a shadow, the light has a unique shadow map. // ShadowMapCache is used in two cases: diff --git a/src/scene/renderer/shadow-map.js b/src/scene/renderer/shadow-map.js index cb08ba0fad3..3d7fb44e13f 100644 --- a/src/scene/renderer/shadow-map.js +++ b/src/scene/renderer/shadow-map.js @@ -8,7 +8,6 @@ import { } from '../../platform/graphics/constants.js'; import { RenderTarget } from '../../platform/graphics/render-target.js'; import { Texture } from '../../platform/graphics/texture.js'; - import { LIGHTTYPE_OMNI, SHADOW_PCF1, SHADOW_PCF3, SHADOW_PCF5, SHADOW_VSM16, SHADOW_VSM32, SHADOW_PCSS diff --git a/src/scene/renderer/shadow-renderer-directional.js b/src/scene/renderer/shadow-renderer-directional.js index 0ae7145714e..709e49fa15e 100644 --- a/src/scene/renderer/shadow-renderer-directional.js +++ b/src/scene/renderer/shadow-renderer-directional.js @@ -1,13 +1,13 @@ +import { RenderPassShadowDirectional } from './render-pass-shadow-directional.js'; +import { ShadowMap } from './shadow-map.js'; import { Debug } from '../../core/debug.js'; +import { Mat4 } from '../../core/math/mat4.js'; import { math } from '../../core/math/math.js'; import { Vec3 } from '../../core/math/vec3.js'; -import { Mat4 } from '../../core/math/mat4.js'; import { BoundingBox } from '../../core/shape/bounding-box.js'; import { LIGHTTYPE_DIRECTIONAL, SHADOWUPDATE_NONE } from '../constants.js'; -import { ShadowMap } from './shadow-map.js'; -import { RenderPassShadowDirectional } from './render-pass-shadow-directional.js'; /** * @import { Camera } from '../camera.js' @@ -127,8 +127,9 @@ class ShadowRendererDirectional { let radius = 0; for (let i = 0; i < 8; i++) { const dist = frustumPoints[i].sub(center).length(); - if (dist > radius) + if (dist > radius) { radius = dist; + } } // axis of light coordinate system @@ -226,8 +227,9 @@ class ShadowRendererDirectional { let shadowCamera; for (let face = 0; face < faceCount; face++) { - if (shadowUpdateOverrides?.[face] === SHADOWUPDATE_NONE) + if (shadowUpdateOverrides?.[face] === SHADOWUPDATE_NONE) { allCascadesRendering = false; + } shadowCamera = this.shadowRenderer.prepareFace(light, camera, face); } diff --git a/src/scene/renderer/shadow-renderer-local.js b/src/scene/renderer/shadow-renderer-local.js index d18cd923f7b..ca3f0c3fb73 100644 --- a/src/scene/renderer/shadow-renderer-local.js +++ b/src/scene/renderer/shadow-renderer-local.js @@ -1,9 +1,9 @@ +import { RenderPassShadowLocalNonClustered } from './render-pass-shadow-local-non-clustered.js'; +import { ShadowMap } from './shadow-map.js'; import { math } from '../../core/math/math.js'; import { LIGHTTYPE_OMNI, LIGHTTYPE_SPOT } from '../constants.js'; -import { ShadowMap } from './shadow-map.js'; -import { RenderPassShadowLocalNonClustered } from './render-pass-shadow-local-non-clustered.js'; /** * @import { FrameGraph } from '../../scene/frame-graph.js' diff --git a/src/scene/renderer/shadow-renderer.js b/src/scene/renderer/shadow-renderer.js index 1f8d1ee4cfa..e187d3e4909 100644 --- a/src/scene/renderer/shadow-renderer.js +++ b/src/scene/renderer/shadow-renderer.js @@ -1,12 +1,16 @@ +import { LightCamera } from './light-camera.js'; +import { RenderingParams } from './rendering-params.js'; import { Debug } from '../../core/debug.js'; -import { now } from '../../core/time.js'; import { Color } from '../../core/math/color.js'; import { Mat4 } from '../../core/math/mat4.js'; import { Vec3 } from '../../core/math/vec3.js'; import { Vec4 } from '../../core/math/vec4.js'; +import { now } from '../../core/time.js'; +import { BindUniformBufferFormat, BindGroupFormat } from '../../platform/graphics/bind-group-format.js'; +import { BlendState } from '../../platform/graphics/blend-state.js'; import { SHADERSTAGE_FRAGMENT, SHADERSTAGE_VERTEX, UNIFORMTYPE_MAT4, UNIFORM_BUFFER_DEFAULT_SLOT_NAME } from '../../platform/graphics/constants.js'; import { DebugGraphics } from '../../platform/graphics/debug-graphics.js'; -import { drawQuadWithShader } from '../graphics/quad-render-utils.js'; +import { UniformBufferFormat, UniformFormat } from '../../platform/graphics/uniform-buffer-format.js'; import { BLUR_GAUSSIAN, LIGHTTYPE_DIRECTIONAL, LIGHTTYPE_OMNI, @@ -15,14 +19,10 @@ import { SHADOWUPDATE_NONE, SHADOWUPDATE_THISFRAME, SORTKEY_DEPTH } from '../constants.js'; -import { ShaderPass } from '../shader-pass.js'; +import { drawQuadWithShader } from '../graphics/quad-render-utils.js'; import { shaderChunks } from '../shader-lib/chunks/chunks.js'; import { createShaderFromCode } from '../shader-lib/utils.js'; -import { LightCamera } from './light-camera.js'; -import { UniformBufferFormat, UniformFormat } from '../../platform/graphics/uniform-buffer-format.js'; -import { BindUniformBufferFormat, BindGroupFormat } from '../../platform/graphics/bind-group-format.js'; -import { BlendState } from '../../platform/graphics/blend-state.js'; -import { RenderingParams } from './rendering-params.js'; +import { ShaderPass } from '../shader-pass.js'; /** * @import { Camera } from '../camera.js' @@ -90,7 +90,7 @@ class ShadowRenderer { this.sourceId = scope.resolve('source'); this.pixelOffsetId = scope.resolve('pixelOffset'); this.weightId = scope.resolve('weight[0]'); - this.blurVsmShaderCode = [shaderChunks.blurVSMPS, '#define GAUSS\n' + shaderChunks.blurVSMPS]; + this.blurVsmShaderCode = [shaderChunks.blurVSMPS, `#define GAUSS\n${shaderChunks.blurVSMPS}`]; const packed = '#define PACKED\n'; this.blurPackedVsmShaderCode = [packed + this.blurVsmShaderCode[0], packed + this.blurVsmShaderCode[1]]; @@ -268,8 +268,9 @@ class ShadowRenderer { }); // add it to the cache - if (!this.shadowPassCache[lightType]) + if (!this.shadowPassCache[lightType]) { this.shadowPassCache[lightType] = []; + } this.shadowPassCache[lightType][shadowType] = shadowPassInfo; } @@ -490,13 +491,13 @@ class ShadowRenderer { this.blurVsmWeights[filterSize] = gaussWeights(filterSize); const blurVS = shaderChunks.fullscreenQuadVS; - let blurFS = '#define SAMPLES ' + filterSize + '\n'; + let blurFS = `#define SAMPLES ${filterSize}\n`; if (isVsm8) { blurFS += this.blurPackedVsmShaderCode[blurMode]; } else { blurFS += this.blurVsmShaderCode[blurMode]; } - const blurShaderName = 'blurVsm' + blurMode + '' + filterSize + '' + isVsm8; + const blurShaderName = `blurVsm${blurMode}${filterSize}${isVsm8}`; blurShader = createShaderFromCode(this.device, blurVS, blurFS, blurShaderName); if (isVsm8) { @@ -563,7 +564,7 @@ class ShadowRenderer { // format of the view uniform buffer this.viewUniformFormat = new UniformBufferFormat(this.device, [ - new UniformFormat("matrix_viewProjection", UNIFORMTYPE_MAT4) + new UniformFormat('matrix_viewProjection', UNIFORMTYPE_MAT4) ]); // format of the view bind group - contains single uniform buffer, and no textures diff --git a/src/scene/scene.js b/src/scene/scene.js index 2fbc4828536..06fd61dddee 100644 --- a/src/scene/scene.js +++ b/src/scene/scene.js @@ -1,18 +1,18 @@ +import { BAKE_COLORDIR, FOG_NONE, LAYERID_IMMEDIATE } from './constants.js'; +import { EnvLighting } from './graphics/env-lighting.js'; +import { Immediate } from './immediate/immediate.js'; +import { LightingParams } from './lighting/lighting-params.js'; +import { RenderingParams } from './renderer/rendering-params.js'; +import { Sky } from './skybox/sky.js'; import { Debug } from '../core/debug.js'; import { EventHandler } from '../core/event-handler.js'; import { Color } from '../core/math/color.js'; -import { Vec3 } from '../core/math/vec3.js'; -import { Quat } from '../core/math/quat.js'; -import { math } from '../core/math/math.js'; import { Mat3 } from '../core/math/mat3.js'; import { Mat4 } from '../core/math/mat4.js'; +import { math } from '../core/math/math.js'; +import { Quat } from '../core/math/quat.js'; +import { Vec3 } from '../core/math/vec3.js'; import { PIXELFORMAT_RGBA8, ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR } from '../platform/graphics/constants.js'; -import { BAKE_COLORDIR, FOG_NONE, LAYERID_IMMEDIATE } from './constants.js'; -import { LightingParams } from './lighting/lighting-params.js'; -import { Sky } from './skybox/sky.js'; -import { Immediate } from './immediate/immediate.js'; -import { EnvLighting } from './graphics/env-lighting.js'; -import { RenderingParams } from './renderer/rendering-params.js'; /** * @import { Entity } from '../framework/entity.js' @@ -83,12 +83,12 @@ class Scene extends EventHandler { */ ambientBakeOcclusionBrightness = 0; - /** - * If {@link Scene#ambientBake} is true, this specifies the contrast of ambient occlusion. - * Typical range is -1 to 1. Defaults to 0, representing no change to contrast. - * - * @type {number} - */ + /** + * If {@link Scene#ambientBake} is true, this specifies the contrast of ambient occlusion. + * Typical range is -1 to 1. Defaults to 0, representing no change to contrast. + * + * @type {number} + */ ambientBakeOcclusionContrast = 0; /** @@ -238,7 +238,7 @@ class Scene extends EventHandler { constructor(graphicsDevice) { super(); - Debug.assert(graphicsDevice, "Scene constructor takes a GraphicsDevice as a parameter, and it was not provided."); + Debug.assert(graphicsDevice, 'Scene constructor takes a GraphicsDevice as a parameter, and it was not provided.'); this.device = graphicsDevice; this._gravity = new Vec3(0, -9.8, 0); diff --git a/src/scene/shader-lib/chunk-builder.js b/src/scene/shader-lib/chunk-builder.js index b1ab3747828..2922469f516 100644 --- a/src/scene/shader-lib/chunk-builder.js +++ b/src/scene/shader-lib/chunk-builder.js @@ -8,7 +8,7 @@ class ChunkBuilder { if (chunk.endsWith('\n')) { this.code += chunk; } else { - this.code += chunk + '\n'; + this.code += `${chunk}\n`; } }); } @@ -18,7 +18,7 @@ class ChunkBuilder { if (chunk.endsWith('\n')) { this.code = chunk + this.code; } else { - this.code = chunk + '\n' + this.code; + this.code = `${chunk}\n${this.code}`; } }); } diff --git a/src/scene/shader-lib/chunks/chunk-validation.js b/src/scene/shader-lib/chunks/chunk-validation.js index 1a11aa9b6d1..92c6ec88e6b 100644 --- a/src/scene/shader-lib/chunks/chunk-validation.js +++ b/src/scene/shader-lib/chunks/chunk-validation.js @@ -1,6 +1,6 @@ -import { CHUNKAPI_1_51, CHUNKAPI_1_55, CHUNKAPI_1_56, CHUNKAPI_1_57, CHUNKAPI_1_60, CHUNKAPI_1_62, CHUNKAPI_1_65, CHUNKAPI_1_70 } from '../../../platform/graphics/constants.js'; -import { Debug } from '../../../core/debug.js'; import { shaderChunks } from './chunks.js'; +import { Debug } from '../../../core/debug.js'; +import { CHUNKAPI_1_51, CHUNKAPI_1_55, CHUNKAPI_1_56, CHUNKAPI_1_57, CHUNKAPI_1_60, CHUNKAPI_1_62, CHUNKAPI_1_65, CHUNKAPI_1_70 } from '../../../platform/graphics/constants.js'; const chunkVersions = { // frontend diff --git a/src/scene/shader-lib/chunks/chunks-lightmapper.js b/src/scene/shader-lib/chunks/chunks-lightmapper.js index b155b5f67ed..5502287383f 100644 --- a/src/scene/shader-lib/chunks/chunks-lightmapper.js +++ b/src/scene/shader-lib/chunks/chunks-lightmapper.js @@ -1,7 +1,7 @@ import bakeDirLmEndPS from './lightmapper/frag/bakeDirLmEnd.js'; import bakeLmEndPS from './lightmapper/frag/bakeLmEnd.js'; -import dilatePS from './lightmapper/frag/dilate.js'; import bilateralDeNoisePS from './lightmapper/frag/bilateralDeNoise.js'; +import dilatePS from './lightmapper/frag/dilate.js'; const shaderChunksLightmapper = { bakeDirLmEndPS, diff --git a/src/scene/shader-lib/chunks/chunks.js b/src/scene/shader-lib/chunks/chunks.js index 00a81c575bc..ae9eb263c31 100644 --- a/src/scene/shader-lib/chunks/chunks.js +++ b/src/scene/shader-lib/chunks/chunks.js @@ -1,28 +1,52 @@ -import alphaTestPS from './standard/frag/alphaTest.js'; +import bayerPS from './common/frag/bayer.js'; +import decodePS from './common/frag/decode.js'; +import encodePS from './common/frag/encode.js'; +import envAtlasPS from './common/frag/envAtlas.js'; +import envConstPS from './common/frag/envConst.js'; +import envMultiplyPS from './common/frag/envMultiply.js'; +import fullscreenQuadPS from './common/frag/fullscreenQuad.js'; +import gamma1_0PS from './common/frag/gamma1_0.js'; +import gamma2_2PS from './common/frag/gamma2_2.js'; +import linearizeDepthPS from './common/frag/linearizeDepth.js'; +import msdfPS from './common/frag/msdf.js'; +import outputTex2DPS from './common/frag/outputTex2D.js'; +import packDepthPS from './common/frag/packDepth.js'; +import pickPS from './common/frag/pick.js'; +import reprojectPS from './common/frag/reproject.js'; +import sampleCatmullRomPS from './common/frag/sampleCatmullRom.js'; +import screenDepthPS from './common/frag/screenDepth.js'; +import sphericalPS from './common/frag/spherical.js'; +import tonemappingAcesPS from './common/frag/tonemappingAces.js'; +import tonemappingAces2PS from './common/frag/tonemappingAces2.js'; +import tonemappingFilmicPS from './common/frag/tonemappingFilmic.js'; +import tonemappingHejlPS from './common/frag/tonemappingHejl.js'; +import tonemappingLinearPS from './common/frag/tonemappingLinear.js'; +import tonemappingNeutralPS from './common/frag/tonemappingNeutral.js'; +import tonemappingNonePS from './common/frag/tonemappingNone.js'; +import fullscreenQuadVS from './common/vert/fullscreenQuad.js'; +import msdfVS from './common/vert/msdf.js'; +import normalCoreVS from './common/vert/normalCore.js'; +import skinBatchTexVS from './common/vert/skinBatchTex.js'; +import skinTexVS from './common/vert/skinTex.js'; +import transformVS from './common/vert/transform.js'; +import transformCoreVS from './common/vert/transformCore.js'; +import transformInstancingVS from './common/vert/transformInstancing.js'; import ambientConstantPS from './lit/frag/ambientConstant.js'; import ambientEnvPS from './lit/frag/ambientEnv.js'; import ambientSHPS from './lit/frag/ambientSH.js'; -import aoPS from './standard/frag/ao.js'; -import aoDetailMapPS from './standard/frag/aoDetailMap.js'; import aoDiffuseOccPS from './lit/frag/aoDiffuseOcc.js'; import aoSpecOccPS from './lit/frag/aoSpecOcc.js'; import aoSpecOccConstPS from './lit/frag/aoSpecOccConst.js'; import aoSpecOccConstSimplePS from './lit/frag/aoSpecOccConstSimple.js'; import aoSpecOccSimplePS from './lit/frag/aoSpecOccSimple.js'; import basePS from './lit/frag/base.js'; -import baseVS from './lit/vert/base.js'; import baseNineSlicedPS from './lit/frag/baseNineSliced.js'; -import baseNineSlicedVS from './lit/vert/baseNineSliced.js'; import baseNineSlicedTiledPS from './lit/frag/baseNineSlicedTiled.js'; -import bayerPS from './common/frag/bayer.js'; import blurVSMPS from './lit/frag/blurVSM.js'; -import clearCoatPS from './standard/frag/clearCoat.js'; -import clearCoatGlossPS from './standard/frag/clearCoatGloss.js'; -import clearCoatNormalPS from './standard/frag/clearCoatNormal.js'; -import clusteredLightUtilsPS from './lit/frag/clusteredLightUtils.js'; +import clusteredLightPS from './lit/frag/clusteredLight.js'; import clusteredLightCookiesPS from './lit/frag/clusteredLightCookies.js'; import clusteredLightShadowsPS from './lit/frag/clusteredLightShadows.js'; -import clusteredLightPS from './lit/frag/clusteredLight.js'; +import clusteredLightUtilsPS from './lit/frag/clusteredLightUtils.js'; import combinePS from './lit/frag/combine.js'; import cookiePS from './lit/frag/cookie.js'; import cubeMapProjectBoxPS from './lit/frag/cubeMapProjectBox.js'; @@ -30,17 +54,7 @@ import cubeMapProjectNonePS from './lit/frag/cubeMapProjectNone.js'; import cubeMapRotatePS from './lit/frag/cubeMapRotate.js'; import debugOutputPS from './lit/frag/debug-output.js'; import debugProcessFrontendPS from './lit/frag/debug-process-frontend.js'; -import decodePS from './common/frag/decode.js'; -import detailModesPS from './standard/frag/detailModes.js'; -import diffusePS from './standard/frag/diffuse.js'; -import diffuseDetailMapPS from './standard/frag/diffuseDetailMap.js'; -import emissivePS from './standard/frag/emissive.js'; -import encodePS from './common/frag/encode.js'; import endPS from './lit/frag/end.js'; -import endVS from './lit/vert/end.js'; -import envAtlasPS from './common/frag/envAtlas.js'; -import envConstPS from './common/frag/envConst.js'; -import envMultiplyPS from './common/frag/envMultiply.js'; import falloffInvSquaredPS from './lit/frag/falloffInvSquared.js'; import falloffLinearPS from './lit/frag/falloffLinear.js'; import floatUnpackingPS from './lit/frag/float-unpacking.js'; @@ -49,55 +63,68 @@ import fogExp2PS from './lit/frag/fogExp2.js'; import fogLinearPS from './lit/frag/fogLinear.js'; import fogNonePS from './lit/frag/fogNone.js'; import fresnelSchlickPS from './lit/frag/fresnelSchlick.js'; -import fullscreenQuadPS from './common/frag/fullscreenQuad.js'; -import fullscreenQuadVS from './common/vert/fullscreenQuad.js'; -import gamma1_0PS from './common/frag/gamma1_0.js'; -import gamma2_2PS from './common/frag/gamma2_2.js'; -import gles3PS from '../../../platform/graphics/shader-chunks/frag/gles3.js'; -import gles3VS from '../../../platform/graphics/shader-chunks/vert/gles3.js'; -import glossPS from './standard/frag/gloss.js'; import iridescenceDiffractionPS from './lit/frag/iridescenceDiffraction.js'; -import iridescencePS from './standard/frag/iridescence.js'; -import iridescenceThicknessPS from './standard/frag/iridescenceThickness.js'; -import iorPS from './standard/frag/ior.js'; import lightDiffuseLambertPS from './lit/frag/lightDiffuseLambert.js'; import lightDirPointPS from './lit/frag/lightDirPoint.js'; import lightmapAddPS from './lit/frag/lightmapAdd.js'; import lightmapDirAddPS from './lit/frag/lightmapDirAdd.js'; -import lightmapDirPS from './standard/frag/lightmapDir.js'; -import lightmapSinglePS from './standard/frag/lightmapSingle.js'; +import lightSheenPS from './lit/frag/lightSheen.js'; import lightSpecularAnisoGGXPS from './lit/frag/lightSpecularAnisoGGX.js'; import lightSpecularBlinnPS from './lit/frag/lightSpecularBlinn.js'; -import lightSheenPS from './lit/frag/lightSheen.js'; -import linearizeDepthPS from './common/frag/linearizeDepth.js'; -import litShaderArgsPS from './standard/frag/litShaderArgs.js'; import ltcPS from './lit/frag/ltc.js'; -import metalnessPS from './standard/frag/metalness.js'; -import msdfPS from './common/frag/msdf.js'; import metalnessModulatePS from './lit/frag/metalnessModulate.js'; -import msdfVS from './common/vert/msdf.js'; -import normalVS from './lit/vert/normal.js'; -import normalCoreVS from './common/vert/normalCore.js'; -import normalDetailMapPS from './standard/frag/normalDetailMap.js'; -import normalMapPS from './standard/frag/normalMap.js'; -import normalXYPS from './standard/frag/normalXY.js'; -import normalXYZPS from './standard/frag/normalXYZ.js'; -import opacityPS from './standard/frag/opacity.js'; -import opacityDitherPS from './standard/frag/opacity-dither.js'; import outputPS from './lit/frag/output.js'; import outputAlphaPS from './lit/frag/outputAlpha.js'; import outputAlphaOpaquePS from './lit/frag/outputAlphaOpaque.js'; import outputAlphaPremulPS from './lit/frag/outputAlphaPremul.js'; -import outputTex2DPS from './common/frag/outputTex2D.js'; -import packDepthPS from './common/frag/packDepth.js'; -import sheenPS from './standard/frag/sheen.js'; -import sheenGlossPS from './standard/frag/sheenGloss.js'; -import parallaxPS from './standard/frag/parallax.js'; +import reflDirPS from './lit/frag/reflDir.js'; +import reflDirAnisoPS from './lit/frag/reflDirAniso.js'; +import reflectionCCPS from './lit/frag/reflectionCC.js'; +import reflectionCubePS from './lit/frag/reflectionCube.js'; +import reflectionEnvPS from './lit/frag/reflectionEnv.js'; +import reflectionEnvHQPS from './lit/frag/reflectionEnvHQ.js'; +import reflectionSheenPS from './lit/frag/reflectionSheen.js'; +import reflectionSpherePS from './lit/frag/reflectionSphere.js'; +import refractionCubePS from './lit/frag/refractionCube.js'; +import refractionDynamicPS from './lit/frag/refractionDynamic.js'; +import shadowCascadesPS from './lit/frag/shadowCascades.js'; +import shadowEVSMPS from './lit/frag/shadowEVSM.js'; +import shadowEVSMnPS from './lit/frag/shadowEVSMn.js'; +import shadowPCSSPS from './lit/frag/shadowPCSS.js'; +import shadowSampleCoordPS from './lit/frag/shadowSampleCoord.js'; +import shadowStandardPS from './lit/frag/shadowStandard.js'; +import shadowStandardGL2PS from './lit/frag/shadowStandardGL2.js'; +import shadowVSM8PS from './lit/frag/shadowVSM8.js'; +import shadowVSM_commonPS from './lit/frag/shadowVSM_common.js'; +import spotPS from './lit/frag/spot.js'; +import startPS from './lit/frag/start.js'; +import startNineSlicedPS from './lit/frag/startNineSliced.js'; +import startNineSlicedTiledPS from './lit/frag/startNineSlicedTiled.js'; +import storeEVSMPS from './lit/frag/storeEVSM.js'; +import TBNPS from './lit/frag/TBN.js'; +import TBNderivativePS from './lit/frag/TBNderivative.js'; +import TBNObjectSpacePS from './lit/frag/TBNObjectSpace.js'; +import twoSidedLightingPS from './lit/frag/twoSidedLighting.js'; +import viewDirPS from './lit/frag/viewDir.js'; +import baseVS from './lit/vert/base.js'; +import baseNineSlicedVS from './lit/vert/baseNineSliced.js'; +import endVS from './lit/vert/end.js'; +import normalVS from './lit/vert/normal.js'; +import startVS from './lit/vert/start.js'; +import tangentBinormalVS from './lit/vert/tangentBinormal.js'; +import uv0VS from './lit/vert/uv0.js'; +import uv1VS from './lit/vert/uv1.js'; +import viewNormalVS from './lit/vert/viewNormal.js'; import particlePS from './particle/frag/particle.js'; -import particleVS from './particle/vert/particle.js'; -import particleAnimFrameClampVS from './particle/vert/particleAnimFrameClamp.js'; -import particleAnimFrameLoopVS from './particle/vert/particleAnimFrameLoop.js'; -import particleAnimTexVS from './particle/vert/particleAnimTex.js'; +import particle_blendAddPS from './particle/frag/particle_blendAdd.js'; +import particle_blendMultiplyPS from './particle/frag/particle_blendMultiply.js'; +import particle_blendNormalPS from './particle/frag/particle_blendNormal.js'; +import particle_endPS from './particle/frag/particle_end.js'; +import particle_halflambertPS from './particle/frag/particle_halflambert.js'; +import particle_lambertPS from './particle/frag/particle_lambert.js'; +import particle_lightingPS from './particle/frag/particle_lighting.js'; +import particle_normalMapPS from './particle/frag/particle_normalMap.js'; +import particle_softPS from './particle/frag/particle_soft.js'; import particleInputFloatPS from './particle/frag/particleInputFloat.js'; import particleInputRgba8PS from './particle/frag/particleInputRgba8.js'; import particleOutputFloatPS from './particle/frag/particleOutputFloat.js'; @@ -110,88 +137,61 @@ import particleUpdaterOnStopPS from './particle/frag/particleUpdaterOnStop.js'; import particleUpdaterRespawnPS from './particle/frag/particleUpdaterRespawn.js'; import particleUpdaterSpherePS from './particle/frag/particleUpdaterSphere.js'; import particleUpdaterStartPS from './particle/frag/particleUpdaterStart.js'; +import particleVS from './particle/vert/particle.js'; import particle_billboardVS from './particle/vert/particle_billboard.js'; -import particle_blendAddPS from './particle/frag/particle_blendAdd.js'; -import particle_blendMultiplyPS from './particle/frag/particle_blendMultiply.js'; -import particle_blendNormalPS from './particle/frag/particle_blendNormal.js'; import particle_cpuVS from './particle/vert/particle_cpu.js'; import particle_cpu_endVS from './particle/vert/particle_cpu_end.js'; import particle_customFaceVS from './particle/vert/particle_customFace.js'; -import particle_endPS from './particle/frag/particle_end.js'; import particle_endVS from './particle/vert/particle_end.js'; -import particle_halflambertPS from './particle/frag/particle_halflambert.js'; import particle_initVS from './particle/vert/particle_init.js'; -import particle_lambertPS from './particle/frag/particle_lambert.js'; -import particle_lightingPS from './particle/frag/particle_lighting.js'; import particle_localShiftVS from './particle/vert/particle_localShift.js'; import particle_meshVS from './particle/vert/particle_mesh.js'; import particle_normalVS from './particle/vert/particle_normal.js'; -import particle_normalMapPS from './particle/frag/particle_normalMap.js'; import particle_pointAlongVS from './particle/vert/particle_pointAlong.js'; -import particle_softPS from './particle/frag/particle_soft.js'; import particle_softVS from './particle/vert/particle_soft.js'; import particle_stretchVS from './particle/vert/particle_stretch.js'; import particle_TBNVS from './particle/vert/particle_TBN.js'; import particle_wrapVS from './particle/vert/particle_wrap.js'; -import pickPS from './common/frag/pick.js'; -import reflDirPS from './lit/frag/reflDir.js'; -import reflDirAnisoPS from './lit/frag/reflDirAniso.js'; -import reflectionCCPS from './lit/frag/reflectionCC.js'; -import reflectionCubePS from './lit/frag/reflectionCube.js'; -import reflectionEnvHQPS from './lit/frag/reflectionEnvHQ.js'; -import reflectionEnvPS from './lit/frag/reflectionEnv.js'; -import reflectionSpherePS from './lit/frag/reflectionSphere.js'; -import reflectionSheenPS from './lit/frag/reflectionSheen.js'; -import refractionCubePS from './lit/frag/refractionCube.js'; -import refractionDynamicPS from './lit/frag/refractionDynamic.js'; -import reprojectPS from './common/frag/reproject.js'; -import sampleCatmullRomPS from './common/frag/sampleCatmullRom.js'; -import screenDepthPS from './common/frag/screenDepth.js'; -import shadowCascadesPS from './lit/frag/shadowCascades.js'; -import shadowEVSMPS from './lit/frag/shadowEVSM.js'; -import shadowEVSMnPS from './lit/frag/shadowEVSMn.js'; -import shadowPCSSPS from './lit/frag/shadowPCSS.js'; -import shadowSampleCoordPS from './lit/frag/shadowSampleCoord.js'; -import shadowStandardPS from './lit/frag/shadowStandard.js'; -import shadowStandardGL2PS from './lit/frag/shadowStandardGL2.js'; -import shadowVSM8PS from './lit/frag/shadowVSM8.js'; -import shadowVSM_commonPS from './lit/frag/shadowVSM_common.js'; -import skinBatchTexVS from './common/vert/skinBatchTex.js'; -import skinTexVS from './common/vert/skinTex.js'; +import particleAnimFrameClampVS from './particle/vert/particleAnimFrameClamp.js'; +import particleAnimFrameLoopVS from './particle/vert/particleAnimFrameLoop.js'; +import particleAnimTexVS from './particle/vert/particleAnimTex.js'; import skyboxEnvPS from './skybox/frag/skyboxEnv.js'; import skyboxHDRPS from './skybox/frag/skyboxHDR.js'; import skyboxVS from './skybox/vert/skybox.js'; +import alphaTestPS from './standard/frag/alphaTest.js'; +import aoPS from './standard/frag/ao.js'; +import aoDetailMapPS from './standard/frag/aoDetailMap.js'; +import clearCoatPS from './standard/frag/clearCoat.js'; +import clearCoatGlossPS from './standard/frag/clearCoatGloss.js'; +import clearCoatNormalPS from './standard/frag/clearCoatNormal.js'; +import detailModesPS from './standard/frag/detailModes.js'; +import diffusePS from './standard/frag/diffuse.js'; +import diffuseDetailMapPS from './standard/frag/diffuseDetailMap.js'; +import emissivePS from './standard/frag/emissive.js'; +import glossPS from './standard/frag/gloss.js'; +import iorPS from './standard/frag/ior.js'; +import iridescencePS from './standard/frag/iridescence.js'; +import iridescenceThicknessPS from './standard/frag/iridescenceThickness.js'; +import lightmapDirPS from './standard/frag/lightmapDir.js'; +import lightmapSinglePS from './standard/frag/lightmapSingle.js'; +import litShaderArgsPS from './standard/frag/litShaderArgs.js'; +import metalnessPS from './standard/frag/metalness.js'; +import normalDetailMapPS from './standard/frag/normalDetailMap.js'; +import normalMapPS from './standard/frag/normalMap.js'; +import normalXYPS from './standard/frag/normalXY.js'; +import normalXYZPS from './standard/frag/normalXYZ.js'; +import opacityDitherPS from './standard/frag/opacity-dither.js'; +import opacityPS from './standard/frag/opacity.js'; +import parallaxPS from './standard/frag/parallax.js'; +import sheenPS from './standard/frag/sheen.js'; +import sheenGlossPS from './standard/frag/sheenGloss.js'; import specularPS from './standard/frag/specular.js'; -import sphericalPS from './common/frag/spherical.js'; import specularityFactorPS from './standard/frag/specularityFactor.js'; -import spotPS from './lit/frag/spot.js'; -import startPS from './lit/frag/start.js'; -import startVS from './lit/vert/start.js'; -import startNineSlicedPS from './lit/frag/startNineSliced.js'; -import startNineSlicedTiledPS from './lit/frag/startNineSlicedTiled.js'; -import storeEVSMPS from './lit/frag/storeEVSM.js'; -import tangentBinormalVS from './lit/vert/tangentBinormal.js'; -import TBNPS from './lit/frag/TBN.js'; -import TBNderivativePS from './lit/frag/TBNderivative.js'; -import TBNObjectSpacePS from './lit/frag/TBNObjectSpace.js'; import thicknessPS from './standard/frag/thickness.js'; -import tonemappingAcesPS from './common/frag/tonemappingAces.js'; -import tonemappingAces2PS from './common/frag/tonemappingAces2.js'; -import tonemappingFilmicPS from './common/frag/tonemappingFilmic.js'; -import tonemappingHejlPS from './common/frag/tonemappingHejl.js'; -import tonemappingLinearPS from './common/frag/tonemappingLinear.js'; -import tonemappingNeutralPS from './common/frag/tonemappingNeutral.js'; -import tonemappingNonePS from './common/frag/tonemappingNone.js'; -import transformVS from './common/vert/transform.js'; -import transformCoreVS from './common/vert/transformCore.js'; -import transformInstancingVS from './common/vert/transformInstancing.js'; import transmissionPS from './standard/frag/transmission.js'; -import twoSidedLightingPS from './lit/frag/twoSidedLighting.js'; -import uv0VS from './lit/vert/uv0.js'; -import uv1VS from './lit/vert/uv1.js'; -import viewDirPS from './lit/frag/viewDir.js'; -import viewNormalVS from './lit/vert/viewNormal.js'; +import gles3PS from '../../../platform/graphics/shader-chunks/frag/gles3.js'; import webgpuPS from '../../../platform/graphics/shader-chunks/frag/webgpu.js'; +import gles3VS from '../../../platform/graphics/shader-chunks/vert/gles3.js'; import webgpuVS from '../../../platform/graphics/shader-chunks/vert/webgpu.js'; /** diff --git a/src/scene/shader-lib/program-library.js b/src/scene/shader-lib/program-library.js index 8606a1215bf..c1b99e85e6a 100644 --- a/src/scene/shader-lib/program-library.js +++ b/src/scene/shader-lib/program-library.js @@ -1,11 +1,11 @@ +import { version, revision } from '../../core/core.js'; import { Debug } from '../../core/debug.js'; import { hashCode } from '../../core/hash.js'; -import { version, revision } from '../../core/core.js'; import { Shader } from '../../platform/graphics/shader.js'; import { SHADER_FORWARD, SHADER_DEPTH, SHADER_PICK, SHADER_SHADOW, SHADER_PREPASS_VELOCITY } from '../constants.js'; -import { ShaderPass } from '../shader-pass.js'; import { StandardMaterialOptions } from '../materials/standard-material-options.js'; import { RenderingParams } from '../renderer/rendering-params.js'; +import { ShaderPass } from '../shader-pass.js'; /** * @import { ShaderGenerator } from './programs/shader-generator.js' @@ -98,7 +98,7 @@ class ProgramLibrary { let lights; if (options.litOptions?.lights) { lights = options.litOptions.lights; - options.litOptions.lights = lights.map(function (l) { + options.litOptions.lights = lights.map((l) => { // TODO: refactor this to avoid creating a clone of the light. const lcopy = l.clone ? l.clone() : l; lcopy.key = l.key; @@ -108,11 +108,13 @@ class ProgramLibrary { this.storeNewProgram(name, options); - if (options.litOptions?.lights) + if (options.litOptions?.lights) { options.litOptions.lights = lights; + } - if (this._precached) + if (this._precached) { Debug.log(`ProgramLibrary#getProgram: Cache miss for shader ${name} key ${key} after shaders precaching`); + } const device = this._device; def = generator.createShaderDefinition(device, options); @@ -202,13 +204,14 @@ class ProgramLibrary { storeNewProgram(name, options) { let opt = {}; - if (name === "standard") { + if (name === 'standard') { // For standard material saving all default values is overkill, so we store only diff const defaultMat = this._getDefaultStdMatOptions(options.pass); for (const p in options) { - if ((options.hasOwnProperty(p) && defaultMat[p] !== options[p]) || p === "pass") + if ((options.hasOwnProperty(p) && defaultMat[p] !== options[p]) || p === 'pass') { opt[p] = options[p]; + } } // Note: this was added in #4792 and it does not filter out the default values, like the loop above @@ -227,18 +230,19 @@ class ProgramLibrary { dumpPrograms() { let text = 'let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\n'; text += 'let shaders = ['; - if (this._programsCollection[0]) - text += '\n\t' + this._programsCollection[0]; + if (this._programsCollection[0]) { + text += `\n\t${this._programsCollection[0]}`; + } for (let i = 1; i < this._programsCollection.length; ++i) { - text += ',\n\t' + this._programsCollection[i]; + text += `,\n\t${this._programsCollection[i]}`; } text += '\n];\n'; text += 'pc.getProgramLibrary(device).precompile(shaders);\n'; - text += 'if (pc.version != \"' + version + '\" || pc.revision != \"' + revision + '\")\n'; + text += `if (pc.version != \"${version}\" || pc.revision != \"${revision}\")\n`; text += '\tconsole.warn(\"precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine\");'; const element = document.createElement('a'); - element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); + element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`); element.setAttribute('download', 'precompile-shaders.js'); element.style.display = 'none'; document.body.appendChild(element); @@ -265,8 +269,9 @@ class ProgramLibrary { */ removeFromCache(shader) { // don't delete by one when clearing whole cache - if (this._isClearingCache) + if (this._isClearingCache) { return; + } this.processedCache.forEach((cachedShader, key) => { if (shader === cachedShader) { @@ -288,12 +293,13 @@ class ProgramLibrary { // default options for the standard materials are not stored, and so they are inserted // back into the loaded options - if (cache[i].name === "standard") { + if (cache[i].name === 'standard') { const opt = cache[i].options; const defaultMat = this._getDefaultStdMatOptions(opt.pass); for (const p in defaultMat) { - if (defaultMat.hasOwnProperty(p) && opt[p] === undefined) + if (defaultMat.hasOwnProperty(p) && opt[p] === undefined) { opt[p] = defaultMat[p]; + } } } diff --git a/src/scene/shader-lib/programs/lit-options-utils.js b/src/scene/shader-lib/programs/lit-options-utils.js index 332a6cd46b9..9d7b3ab594e 100644 --- a/src/scene/shader-lib/programs/lit-options-utils.js +++ b/src/scene/shader-lib/programs/lit-options-utils.js @@ -1,33 +1,33 @@ -import { LIGHTTYPE_DIRECTIONAL } from "../../constants.js"; +import { LIGHTTYPE_DIRECTIONAL } from '../../constants.js'; const LitOptionsUtils = { // generate a key for the lit options generateKey(options) { - return "lit" + Object.keys(options) - .sort() - .map((key) => { - if (key === "chunks") { - return LitOptionsUtils.generateChunksKey(options); - } else if (key === "lights") { - return LitOptionsUtils.generateLightsKey(options); - } - return key + options[key]; - }) - .join("\n"); + return `lit${Object.keys(options) + .sort() + .map((key) => { + if (key === 'chunks') { + return LitOptionsUtils.generateChunksKey(options); + } else if (key === 'lights') { + return LitOptionsUtils.generateLightsKey(options); + } + return key + options[key]; + }) + .join('\n')}`; }, generateLightsKey(options) { - return 'lights:' + options.lights.map((light) => { + return `lights:${options.lights.map((light) => { return (!options.clusteredLightingEnabled || light._type === LIGHTTYPE_DIRECTIONAL) ? `${light.key},` : ''; - }).join(""); + }).join('')}`; }, generateChunksKey(options) { - return 'chunks:\n' + Object.keys(options.chunks ?? {}) - .sort() - .map(key => key + options.chunks[key]) - .join(""); + return `chunks:\n${Object.keys(options.chunks ?? {}) + .sort() + .map(key => key + options.chunks[key]) + .join('')}`; } }; diff --git a/src/scene/shader-lib/programs/lit-shader.js b/src/scene/shader-lib/programs/lit-shader.js index 66469f80330..136846663c5 100644 --- a/src/scene/shader-lib/programs/lit-shader.js +++ b/src/scene/shader-lib/programs/lit-shader.js @@ -1,9 +1,12 @@ +import { ShaderGenerator } from './shader-generator.js'; +import { Debug } from '../../../core/debug.js'; import { SEMANTIC_ATTR8, SEMANTIC_ATTR9, SEMANTIC_ATTR12, SEMANTIC_ATTR13, SEMANTIC_ATTR14, SEMANTIC_ATTR15, SEMANTIC_BLENDINDICES, SEMANTIC_BLENDWEIGHT, SEMANTIC_COLOR, SEMANTIC_NORMAL, SEMANTIC_POSITION, SEMANTIC_TANGENT, SEMANTIC_TEXCOORD0, SEMANTIC_TEXCOORD1, SHADERTAG_MATERIAL } from '../../../platform/graphics/constants.js'; +import { ShaderUtils } from '../../../platform/graphics/shader-utils.js'; import { BLEND_ADDITIVEALPHA, BLEND_NORMAL, BLEND_PREMULTIPLIED, FRESNEL_SCHLICK, @@ -15,15 +18,12 @@ import { SPECOCC_AO, SPECOCC_GLOSSDEPENDENT, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED, shadowTypeToString, SHADER_PREPASS_VELOCITY } from '../../constants.js'; -import { shaderChunks } from '../chunks/chunks.js'; -import { ChunkUtils } from '../chunk-utils.js'; import { LightsBuffer } from '../../lighting/lights-buffer.js'; import { ShaderPass } from '../../shader-pass.js'; -import { validateUserChunks } from '../chunks/chunk-validation.js'; -import { ShaderUtils } from '../../../platform/graphics/shader-utils.js'; import { ChunkBuilder } from '../chunk-builder.js'; -import { ShaderGenerator } from './shader-generator.js'; -import { Debug } from '../../../core/debug.js'; +import { ChunkUtils } from '../chunk-utils.js'; +import { validateUserChunks } from '../chunks/chunk-validation.js'; +import { shaderChunks } from '../chunks/chunks.js'; /** * @import { GraphicsDevice } from '../../../platform/graphics/graphics-device.js' @@ -41,15 +41,15 @@ const builtinAttributes = { }; const builtinVaryings = { - vVertexColor: "vec4", - vPositionW: "vec3", - vNormalV: "vec3", - vNormalW: "vec3", - vTangentW: "vec3", - vBinormalW: "vec3", - vObjectSpaceUpW: "vec3", - vUv0: "vec2", - vUv1: "vec2" + vVertexColor: 'vec4', + vPositionW: 'vec3', + vNormalV: 'vec3', + vNormalW: 'vec3', + vTangentW: 'vec3', + vBinormalW: 'vec3', + vObjectSpaceUpW: 'vec3', + vUv0: 'vec2', + vUv1: 'vec2' }; class LitShader { @@ -115,8 +115,8 @@ class LitShader { this.needsTransforms = options.useDynamicRefraction; // generated by vshader - this.varyings = ""; - this.varyingDefines = ""; + this.varyings = ''; + this.varyingDefines = ''; this.vshader = null; // supplied by caller @@ -203,7 +203,7 @@ class LitShader { code = this._vsAddBaseCode(code, chunks, options); - codeBody += " vPositionW = getWorldPosition();\n"; + codeBody += ' vPositionW = getWorldPosition();\n'; if (this.options.pass === SHADER_DEPTH || this.options.pass === SHADER_PREPASS_VELOCITY) { code += 'varying float vDepth;\n'; @@ -215,11 +215,11 @@ class LitShader { code += '#define CAMERAPLANES\n'; code += 'uniform vec4 camera_params;\n\n'; code += '#endif\n'; - codeBody += " vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"; + codeBody += ' vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n'; } if (this.options.pass === SHADER_PREPASS_VELOCITY) { - Debug.warnOnce("SHADER_PREPASS_VELOCITY not implemented"); + Debug.warnOnce('SHADER_PREPASS_VELOCITY not implemented'); } if (this.options.useInstancing) { @@ -243,20 +243,20 @@ class LitShader { if (this.needsNormal) { this.attributes.vertex_normal = SEMANTIC_NORMAL; - codeBody += " vNormalW = getNormal();\n"; + codeBody += ' vNormalW = getNormal();\n'; if (options.reflectionSource === 'sphereMap' && device.fragmentUniformsCount <= 16) { code += chunks.viewNormalVS; - codeBody += " vNormalV = getViewNormal();\n"; + codeBody += ' vNormalV = getViewNormal();\n'; } if (options.hasTangents && (options.useHeights || options.useNormals || options.enableGGXSpecular)) { this.attributes.vertex_tangent = SEMANTIC_TANGENT; code += chunks.tangentBinormalVS; - codeBody += " vTangentW = getTangent();\n"; - codeBody += " vBinormalW = getBinormal();\n"; + codeBody += ' vTangentW = getTangent();\n'; + codeBody += ' vBinormalW = getBinormal();\n'; } else if (options.enableGGXSpecular) { - codeBody += " vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));\n"; + codeBody += ' vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));\n'; } } @@ -264,12 +264,12 @@ class LitShader { for (let i = 0; i < maxUvSets; i++) { if (useUv[i]) { - this.attributes["vertex_texCoord" + i] = "TEXCOORD" + i; - code += chunks["uv" + i + "VS"]; - codeBody += " vec2 uv" + i + " = getUv" + i + "();\n"; + this.attributes[`vertex_texCoord${i}`] = `TEXCOORD${i}`; + code += chunks[`uv${i}VS`]; + codeBody += ` vec2 uv${i} = getUv${i}();\n`; } if (useUnmodifiedUv[i]) { - codeBody += " vUv" + i + " = uv" + i + ";\n"; + codeBody += ` vUv${i} = uv${i};\n`; } } @@ -285,14 +285,14 @@ class LitShader { if (options.vertexColors) { this.attributes.vertex_color = SEMANTIC_COLOR; - codeBody += " vVertexColor = vertex_color;\n"; + codeBody += ' vVertexColor = vertex_color;\n'; } if (options.useMsdf && options.msdfTextAttribute) { this.attributes.vertex_outlineParameters = SEMANTIC_ATTR8; this.attributes.vertex_shadowParameters = SEMANTIC_ATTR9; - codeBody += " unpackMsdfParams();\n"; + codeBody += ' unpackMsdfParams();\n'; code += chunks.msdfVS; } @@ -300,18 +300,18 @@ class LitShader { // morphing if (options.useMorphPosition || options.useMorphNormal) { - codeDefines += "#define MORPHING\n"; + codeDefines += '#define MORPHING\n'; if (options.useMorphTextureBasedInt) { - codeDefines += "#define MORPHING_INT\n"; + codeDefines += '#define MORPHING_INT\n'; } if (options.useMorphPosition) { - codeDefines += "#define MORPHING_POSITION\n"; + codeDefines += '#define MORPHING_POSITION\n'; } if (options.useMorphNormal) { - codeDefines += "#define MORPHING_NORMAL\n"; + codeDefines += '#define MORPHING_NORMAL\n'; } // vertex ids attributes @@ -323,26 +323,26 @@ class LitShader { this.attributes.vertex_boneIndices = SEMANTIC_BLENDINDICES; if (options.batch) { - codeDefines += "#define BATCH\n"; + codeDefines += '#define BATCH\n'; } else { this.attributes.vertex_boneWeights = SEMANTIC_BLENDWEIGHT; - codeDefines += "#define SKIN\n"; + codeDefines += '#define SKIN\n'; } } else if (options.useInstancing) { - codeDefines += "#define INSTANCING\n"; + codeDefines += '#define INSTANCING\n'; } if (options.screenSpace) { - codeDefines += "#define SCREENSPACE\n"; + codeDefines += '#define SCREENSPACE\n'; } if (options.pixelSnap) { - codeDefines += "#define PIXELSNAP\n"; + codeDefines += '#define PIXELSNAP\n'; } - code += "\n"; + code += '\n'; code += chunks.startVS; code += codeBody; code += chunks.endVS; - code += "}"; + code += '}'; // build varyings Object.keys(builtinVaryings).forEach((v) => { @@ -395,7 +395,7 @@ class LitShader { code += this.frontendCode; code += ShaderGenerator.begin(); code += this.frontendFunc; - code += " gl_FragColor = packFloat(vDepth);\n"; + code += ' gl_FragColor = packFloat(vDepth);\n'; code += ShaderGenerator.end(); return code; @@ -444,12 +444,12 @@ class LitShader { if (usePackedDepth) { code += chunks.packDepthPS; } else if (shadowType === SHADOW_VSM8) { - code += "vec2 encodeFloatRG( float v ) {\n"; - code += " vec2 enc = vec2(1.0, 255.0) * v;\n"; - code += " enc = fract(enc);\n"; - code += " enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n"; - code += " return enc;\n"; - code += "}\n\n"; + code += 'vec2 encodeFloatRG( float v ) {\n'; + code += ' vec2 enc = vec2(1.0, 255.0) * v;\n'; + code += ' enc = fract(enc);\n'; + code += ' enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n'; + code += ' return enc;\n'; + code += '}\n\n'; } if (shadowType === SHADOW_PCSS) { @@ -471,29 +471,29 @@ class LitShader { // Flag if we are using non-standard depth, i.e gl_FragCoord.z let hasModifiedDepth = false; if (usePerspectiveDepth) { - code += " float depth = gl_FragCoord.z;\n"; + code += ' float depth = gl_FragCoord.z;\n'; } else { - code += " float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n"; + code += ' float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n'; hasModifiedDepth = true; } if (usePackedDepth) { - code += " gl_FragColor = packFloat(depth);\n"; + code += ' gl_FragColor = packFloat(depth);\n'; } else if (!isVsm) { const exportR32 = shadowType === SHADOW_PCSS; if (exportR32) { - code += " gl_FragColor.r = depth;\n"; + code += ' gl_FragColor.r = depth;\n'; } else { // If we end up using modified depth, it needs to be explicitly written to gl_FragDepth if (hasModifiedDepth) { - code += " gl_FragDepth = depth;\n"; + code += ' gl_FragDepth = depth;\n'; } - code += " gl_FragColor = vec4(1.0);\n"; // just the simplest code, color is not written anyway + code += ' gl_FragColor = vec4(1.0);\n'; // just the simplest code, color is not written anyway } } else if (shadowType === SHADOW_VSM8) { - code += " gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n"; + code += ' gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n'; } else { code += chunks.storeEVSMPS; } @@ -519,26 +519,26 @@ class LitShader { } if (options.useSpecular) { - this.defines.push("LIT_SPECULAR"); + this.defines.push('LIT_SPECULAR'); if (this.reflections) { - this.defines.push("LIT_REFLECTIONS"); + this.defines.push('LIT_REFLECTIONS'); } if (options.useClearCoat) { - this.defines.push("LIT_CLEARCOAT"); + this.defines.push('LIT_CLEARCOAT'); } if (options.fresnelModel > 0) { - this.defines.push("LIT_SPECULAR_FRESNEL"); + this.defines.push('LIT_SPECULAR_FRESNEL'); } if (options.useSheen) { - this.defines.push("LIT_SHEEN"); + this.defines.push('LIT_SHEEN'); } if (options.useIridescence) { - this.defines.push("LIT_IRIDESCENCE"); + this.defines.push('LIT_IRIDESCENCE'); } } @@ -549,7 +549,7 @@ class LitShader { let useVsm = false; let usePcss = false; - let hasAreaLights = options.lights.some(function (light) { + let hasAreaLights = options.lights.some((light) => { return light._shape && light._shape !== LIGHTSHAPE_PUNCTUAL; }); @@ -560,9 +560,9 @@ class LitShader { } if (hasAreaLights || options.clusteredLightingEnabled) { - decl.append("#define AREA_LIGHTS"); - decl.append(`uniform highp sampler2D areaLightsLutTex1;`); - decl.append(`uniform highp sampler2D areaLightsLutTex2;`); + decl.append('#define AREA_LIGHTS'); + decl.append('uniform highp sampler2D areaLightsLutTex1;'); + decl.append('uniform highp sampler2D areaLightsLutTex2;'); } for (let i = 0; i < options.lights.length; i++) { @@ -570,12 +570,13 @@ class LitShader { const lightType = light._type; // skip uniform generation for local lights if clustered lighting is enabled - if (options.clusteredLightingEnabled && lightType !== LIGHTTYPE_DIRECTIONAL) + if (options.clusteredLightingEnabled && lightType !== LIGHTTYPE_DIRECTIONAL) { continue; + } const lightShape = (hasAreaLights && light._shape) ? light._shape : LIGHTSHAPE_PUNCTUAL; - decl.append("uniform vec3 light" + i + "_color;"); + decl.append(`uniform vec3 light${i}_color;`); if (light._shadowType === SHADOW_PCSS && light.castShadows && !options.noShadow) { decl.append(`uniform float light${i}_shadowSearchArea;`); @@ -583,44 +584,44 @@ class LitShader { } if (lightType === LIGHTTYPE_DIRECTIONAL) { - decl.append("uniform vec3 light" + i + "_direction;"); + decl.append(`uniform vec3 light${i}_direction;`); } else { - decl.append("uniform vec3 light" + i + "_position;"); - decl.append("uniform float light" + i + "_radius;"); + decl.append(`uniform vec3 light${i}_position;`); + decl.append(`uniform float light${i}_radius;`); if (lightType === LIGHTTYPE_SPOT) { - decl.append("uniform vec3 light" + i + "_direction;"); - decl.append("uniform float light" + i + "_innerConeAngle;"); - decl.append("uniform float light" + i + "_outerConeAngle;"); + decl.append(`uniform vec3 light${i}_direction;`); + decl.append(`uniform float light${i}_innerConeAngle;`); + decl.append(`uniform float light${i}_outerConeAngle;`); } } if (lightShape !== LIGHTSHAPE_PUNCTUAL) { if (lightType === LIGHTTYPE_DIRECTIONAL) { - decl.append("uniform vec3 light" + i + "_position;"); + decl.append(`uniform vec3 light${i}_position;`); } - decl.append("uniform vec3 light" + i + "_halfWidth;"); - decl.append("uniform vec3 light" + i + "_halfHeight;"); + decl.append(`uniform vec3 light${i}_halfWidth;`); + decl.append(`uniform vec3 light${i}_halfHeight;`); } if (light.castShadows && !options.noShadow) { - decl.append("uniform mat4 light" + i + "_shadowMatrix;"); - decl.append("uniform float light" + i + "_shadowIntensity;"); + decl.append(`uniform mat4 light${i}_shadowMatrix;`); + decl.append(`uniform float light${i}_shadowIntensity;`); // directional (cascaded) shadows if (lightType === LIGHTTYPE_DIRECTIONAL) { - decl.append("uniform mat4 light" + i + "_shadowMatrixPalette[4];"); - decl.append("uniform float light" + i + "_shadowCascadeDistances[4];"); - decl.append("uniform float light" + i + "_shadowCascadeCount;"); + decl.append(`uniform mat4 light${i}_shadowMatrixPalette[4];`); + decl.append(`uniform float light${i}_shadowCascadeDistances[4];`); + decl.append(`uniform float light${i}_shadowCascadeCount;`); } - decl.append("uniform vec4 light" + i + "_shadowParams;"); // Width, height, bias, radius + decl.append(`uniform vec4 light${i}_shadowParams;`); // Width, height, bias, radius if (lightType === LIGHTTYPE_DIRECTIONAL) { shadowedDirectionalLightUsed = true; } if (lightType === LIGHTTYPE_OMNI) { - decl.append("uniform samplerCube light" + i + "_shadowMap;"); + decl.append(`uniform samplerCube light${i}_shadowMap;`); } else { if (light._isPcf) { - decl.append("uniform sampler2DShadow light" + i + "_shadowMap;"); + decl.append(`uniform sampler2DShadow light${i}_shadowMap;`); } else { - decl.append("uniform sampler2D light" + i + "_shadowMap;"); + decl.append(`uniform sampler2D light${i}_shadowMap;`); } } numShadowLights++; @@ -631,22 +632,22 @@ class LitShader { if (light._cookie) { if (light._cookie._cubemap) { if (lightType === LIGHTTYPE_OMNI) { - decl.append("uniform samplerCube light" + i + "_cookie;"); - decl.append("uniform float light" + i + "_cookieIntensity;"); + decl.append(`uniform samplerCube light${i}_cookie;`); + decl.append(`uniform float light${i}_cookieIntensity;`); if (!light.castShadows || options.noShadow) { - decl.append("uniform mat4 light" + i + "_shadowMatrix;"); + decl.append(`uniform mat4 light${i}_shadowMatrix;`); } } } else { if (lightType === LIGHTTYPE_SPOT) { - decl.append("uniform sampler2D light" + i + "_cookie;"); - decl.append("uniform float light" + i + "_cookieIntensity;"); + decl.append(`uniform sampler2D light${i}_cookie;`); + decl.append(`uniform float light${i}_cookieIntensity;`); if (!light.castShadows || options.noShadow) { - decl.append("uniform mat4 light" + i + "_shadowMatrix;"); + decl.append(`uniform mat4 light${i}_shadowMatrix;`); } if (light._cookieTransform) { - decl.append("uniform vec4 light" + i + "_cookieMatrix;"); - decl.append("uniform vec2 light" + i + "_cookieOffset;"); + decl.append(`uniform vec4 light${i}_cookieMatrix;`); + decl.append(`uniform vec2 light${i}_cookieOffset;`); } } } @@ -682,7 +683,7 @@ class LitShader { func.append(this.frontendCode); if (options.useCubeMapRotation) { - decl.append("#define CUBEMAP_ROTATION"); + decl.append('#define CUBEMAP_ROTATION'); } if (this.needsNormal) { @@ -722,8 +723,8 @@ class LitShader { if (options.reflectionSource === 'envAtlasHQ') { func.append(chunks.envAtlasPS); func.append(chunks.reflectionEnvHQPS - .replace(/\$DECODE_CUBEMAP/g, ChunkUtils.decodeFunc(options.reflectionCubemapEncoding)) - .replace(/\$DECODE/g, ChunkUtils.decodeFunc(options.reflectionEncoding)) + .replace(/\$DECODE_CUBEMAP/g, ChunkUtils.decodeFunc(options.reflectionCubemapEncoding)) + .replace(/\$DECODE/g, ChunkUtils.decodeFunc(options.reflectionEncoding)) ); } else if (options.reflectionSource === 'envAtlas') { func.append(chunks.envAtlasPS); @@ -746,7 +747,7 @@ class LitShader { if (options.useRefraction) { if (options.useDynamicRefraction) { if (options.dispersion) { - decl.append("uniform float material_dispersion;"); + decl.append('uniform float material_dispersion;'); decl.append('#define DISPERSION\n'); } func.append(chunks.refractionDynamicPS); @@ -764,8 +765,9 @@ class LitShader { // include this before shadow / cookie code func.append(chunks.clusteredLightUtilsPS); - if (options.clusteredLightingCookiesEnabled) + if (options.clusteredLightingCookiesEnabled) { func.append(chunks.clusteredLightCookiesPS); + } // include shadow chunks clustered lights support if (options.clusteredLightingShadowsEnabled && !options.noShadow) { @@ -791,10 +793,10 @@ class LitShader { func.append(chunks.shadowVSM8PS); } if (shadowTypeUsed[SHADOW_VSM16]) { - func.append(chunks.shadowEVSMPS.replace(/\$/g, "16")); + func.append(chunks.shadowEVSMPS.replace(/\$/g, '16')); } if (shadowTypeUsed[SHADOW_VSM32]) { - func.append(device.extTextureFloatLinear ? chunks.shadowEVSMPS.replace(/\$/g, "32") : chunks.shadowEVSMnPS.replace(/\$/g, "32")); + func.append(device.extTextureFloatLinear ? chunks.shadowEVSMPS.replace(/\$/g, '32') : chunks.shadowEVSMnPS.replace(/\$/g, '32')); } } if (usePcss) { @@ -803,7 +805,7 @@ class LitShader { } } - if (options.enableGGXSpecular) func.append("uniform float material_anisotropy;"); + if (options.enableGGXSpecular) func.append('uniform float material_anisotropy;'); if (this.lighting) { func.append(chunks.lightDiffuseLambertPS); @@ -820,8 +822,8 @@ class LitShader { } if (!options.fresnelModel && !this.reflections && !options.diffuseMapEnabled) { - decl.append("uniform vec3 material_ambient;"); - decl.append("#define LIT_OLD_AMBIENT"); + decl.append('uniform vec3 material_ambient;'); + decl.append('#define LIT_OLD_AMBIENT'); useOldAmbient = true; } } @@ -849,12 +851,12 @@ class LitShader { } if (!useOldAmbient) { - decl.append("uniform vec3 material_ambient;"); + decl.append('uniform vec3 material_ambient;'); } if (options.useMsdf) { if (!options.msdfTextAttribute) { - decl.append("#define UNIFORM_TEXT_PARAMETERS"); + decl.append('#define UNIFORM_TEXT_PARAMETERS'); } func.append(chunks.msdfPS); } @@ -883,18 +885,21 @@ class LitShader { func.append(chunks.floatUnpackingPS); - if (options.lightMaskDynamic) - decl.append("#define CLUSTER_MESH_DYNAMIC_LIGHTS"); + if (options.lightMaskDynamic) { + decl.append('#define CLUSTER_MESH_DYNAMIC_LIGHTS'); + } - if (options.clusteredLightingCookiesEnabled) - decl.append("#define CLUSTER_COOKIES"); + if (options.clusteredLightingCookiesEnabled) { + decl.append('#define CLUSTER_COOKIES'); + } if (options.clusteredLightingShadowsEnabled && !options.noShadow) { - decl.append("#define CLUSTER_SHADOWS"); - decl.append("#define CLUSTER_SHADOW_TYPE_" + shadowTypeToString[options.clusteredLightingShadowType]); + decl.append('#define CLUSTER_SHADOWS'); + decl.append(`#define CLUSTER_SHADOW_TYPE_${shadowTypeToString[options.clusteredLightingShadowType]}`); } - if (options.clusteredLightingAreaLightsEnabled) - decl.append("#define CLUSTER_AREALIGHTS"); + if (options.clusteredLightingAreaLightsEnabled) { + decl.append('#define CLUSTER_AREALIGHTS'); + } decl.append(LightsBuffer.getShaderDefines()); @@ -910,18 +915,18 @@ class LitShader { code.append(this._fsGetStartCode(code, device, chunks, options)); if (this.needsNormal) { - code.append(" dVertexNormalW = normalize(vNormalW);"); + code.append(' dVertexNormalW = normalize(vNormalW);'); if ((options.useHeights || options.useNormals) && options.hasTangents) { - code.append(" dTangentW = vTangentW;"); - code.append(" dBinormalW = vBinormalW;"); + code.append(' dTangentW = vTangentW;'); + code.append(' dBinormalW = vBinormalW;'); } - code.append(" getViewDir();"); + code.append(' getViewDir();'); if (hasTBN) { - code.append(" getTBN(dTangentW, dBinormalW, dVertexNormalW);"); + code.append(' getTBN(dTangentW, dBinormalW, dVertexNormalW);'); if (options.twoSidedLighting) { - code.append(" handleTwoSidedLighting();"); + code.append(' handleTwoSidedLighting();'); } } } @@ -932,30 +937,30 @@ class LitShader { // transform tangent space normals to world space if (this.needsNormal) { if (options.useSpecular) { - backend.append(" getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);"); + backend.append(' getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);'); } if (options.useClearCoat) { - backend.append(" ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));"); + backend.append(' ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));'); } } if ((this.lighting && options.useSpecular) || this.reflections) { if (options.useMetalness) { - backend.append(" float f0 = 1.0 / litArgs_ior; f0 = (f0 - 1.0) / (f0 + 1.0); f0 *= f0;"); - backend.append(" litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);"); - backend.append(" litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);"); + backend.append(' float f0 = 1.0 / litArgs_ior; f0 = (f0 - 1.0) / (f0 + 1.0); f0 *= f0;'); + backend.append(' litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);'); + backend.append(' litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);'); } if (options.useIridescence) { - backend.append(" vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);"); + backend.append(' vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);'); } } if (addAmbient) { - backend.append(" addAmbient(litArgs_worldNormal);"); + backend.append(' addAmbient(litArgs_worldNormal);'); if (options.useSpecular) { - backend.append(` dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);`); + backend.append(' dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);'); } // move ambient color out of diffuse (used by Lightmapper, to multiply ambient color by accumulated AO) @@ -968,11 +973,11 @@ class LitShader { } if (!useOldAmbient) { - backend.append(" dDiffuseLight *= material_ambient;"); + backend.append(' dDiffuseLight *= material_ambient;'); } if (options.useAo && !options.occludeDirect) { - backend.append(" occludeDiffuse(litArgs_ao);"); + backend.append(' occludeDiffuse(litArgs_ao);'); } if (options.lightMapEnabled) { @@ -996,24 +1001,24 @@ class LitShader { if (this.lighting || this.reflections) { if (this.reflections) { if (options.useClearCoat) { - backend.append(" addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);"); + backend.append(' addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);'); if (options.fresnelModel > 0) { - backend.append(" ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));"); - backend.append(" ccReflection.rgb *= ccFresnel;"); + backend.append(' ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));'); + backend.append(' ccReflection.rgb *= ccFresnel;'); } else { - backend.append(" ccFresnel = 0.0;"); + backend.append(' ccFresnel = 0.0;'); } } if (options.useSpecularityFactor) { - backend.append(" ccReflection.rgb *= litArgs_specularityFactor;"); + backend.append(' ccReflection.rgb *= litArgs_specularityFactor;'); } if (options.useSheen) { - backend.append(" addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);"); + backend.append(' addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);'); } // Fresnel has to be applied to reflections - backend.append(" addReflection(dReflDirW, litArgs_gloss);"); + backend.append(' addReflection(dReflDirW, litArgs_gloss);'); if (options.fresnelModel > 0) { backend.append(` dReflection.rgb *= @@ -1027,21 +1032,21 @@ class LitShader { #endif );`); } else { - backend.append(" dReflection.rgb *= litArgs_specularity;"); + backend.append(' dReflection.rgb *= litArgs_specularity;'); } if (options.useSpecularityFactor) { - backend.append(" dReflection.rgb *= litArgs_specularityFactor;"); + backend.append(' dReflection.rgb *= litArgs_specularityFactor;'); } } if (hasAreaLights) { // specular has to be accumulated differently if we want area lights to look correct - backend.append(" dSpecularLight *= litArgs_specularity;"); + backend.append(' dSpecularLight *= litArgs_specularity;'); // code += " float roughness = max((1.0 - dGlossiness) * (1.0 - dGlossiness), 0.001);\n"; // evaluate material based area lights data, shared by all area lights if (options.useSpecular) { - backend.append(" calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);"); + backend.append(' calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);'); } } @@ -1068,13 +1073,13 @@ class LitShader { const shapeString = (hasAreaLights && light._shape) ? this._getLightSourceShapeString(lightShape) : ''; if (lightShape !== LIGHTSHAPE_PUNCTUAL) { - backend.append(" calc" + shapeString + "LightValues(light" + i + "_position, light" + i + "_halfWidth, light" + i + "_halfHeight);"); + backend.append(` calc${shapeString}LightValues(light${i}_position, light${i}_halfWidth, light${i}_halfHeight);`); } if (lightType === LIGHTTYPE_DIRECTIONAL) { // directional - backend.append(" dLightDirNormW = light" + i + "_direction;"); - backend.append(" dAtten = 1.0;"); + backend.append(` dLightDirNormW = light${i}_direction;`); + backend.append(' dAtten = 1.0;'); } else { if (light._cookie) { @@ -1087,36 +1092,36 @@ class LitShader { } } - backend.append(" getLightDirPoint(light" + i + "_position);"); + backend.append(` getLightDirPoint(light${i}_position);`); hasPointLights = true; if (usesCookieNow) { if (lightType === LIGHTTYPE_SPOT) { - backend.append(" dAtten3 = getCookie2D" + (light._cookieFalloff ? "" : "Clip") + (light._cookieTransform ? "Xform" : "") + "(light" + i + "_cookie, light" + i + "_shadowMatrix, light" + i + "_cookieIntensity" + (light._cookieTransform ? ", light" + i + "_cookieMatrix, light" + i + "_cookieOffset" : "") + ")." + light._cookieChannel + ";"); + backend.append(` dAtten3 = getCookie2D${light._cookieFalloff ? '' : 'Clip'}${light._cookieTransform ? 'Xform' : ''}(light${i}_cookie, light${i}_shadowMatrix, light${i}_cookieIntensity${light._cookieTransform ? `, light${i}_cookieMatrix, light${i}_cookieOffset` : ''}).${light._cookieChannel};`); } else { - backend.append(" dAtten3 = getCookieCube(light" + i + "_cookie, light" + i + "_shadowMatrix, light" + i + "_cookieIntensity)." + light._cookieChannel + ";"); + backend.append(` dAtten3 = getCookieCube(light${i}_cookie, light${i}_shadowMatrix, light${i}_cookieIntensity).${light._cookieChannel};`); } } if (lightShape === LIGHTSHAPE_PUNCTUAL) { if (light._falloffMode === LIGHTFALLOFF_LINEAR) { - backend.append(" dAtten = getFalloffLinear(light" + i + "_radius, dLightDirW);"); + backend.append(` dAtten = getFalloffLinear(light${i}_radius, dLightDirW);`); usesLinearFalloff = true; } else { - backend.append(" dAtten = getFalloffInvSquared(light" + i + "_radius, dLightDirW);"); + backend.append(` dAtten = getFalloffInvSquared(light${i}_radius, dLightDirW);`); usesInvSquaredFalloff = true; } } else { // non punctual lights only gets the range window here - backend.append(" dAtten = getFalloffWindow(light" + i + "_radius, dLightDirW);"); + backend.append(` dAtten = getFalloffWindow(light${i}_radius, dLightDirW);`); usesInvSquaredFalloff = true; } - backend.append(" if (dAtten > 0.00001) {"); // BRANCH START + backend.append(' if (dAtten > 0.00001) {'); // BRANCH START if (lightType === LIGHTTYPE_SPOT) { if (!(usesCookieNow && !light._cookieFalloff)) { - backend.append(" dAtten *= getSpotEffect(light" + i + "_direction, light" + i + "_innerConeAngle, light" + i + "_outerConeAngle, dLightDirNormW);"); + backend.append(` dAtten *= getSpotEffect(light${i}_direction, light${i}_innerConeAngle, light${i}_outerConeAngle, dLightDirNormW);`); usesSpot = true; } } @@ -1126,13 +1131,13 @@ class LitShader { if (lightShape !== LIGHTSHAPE_PUNCTUAL) { if (lightType === LIGHTTYPE_DIRECTIONAL) { // NB: A better aproximation perhaps using wrap lighting could be implemented here - backend.append(" dAttenD = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"); + backend.append(' dAttenD = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);'); } else { // 16.0 is a constant that is in getFalloffInvSquared() - backend.append(" dAttenD = get" + shapeString + "LightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW) * 16.0;"); + backend.append(` dAttenD = get${shapeString}LightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW) * 16.0;`); } } else { - backend.append(" dAtten *= getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"); + backend.append(' dAtten *= getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);'); } if (light.castShadows && !options.noShadow) { @@ -1143,61 +1148,61 @@ class LitShader { let evsmExp; switch (light._shadowType) { case SHADOW_VSM8: - shadowReadMode = "VSM8"; - evsmExp = "0.0"; + shadowReadMode = 'VSM8'; + evsmExp = '0.0'; break; case SHADOW_VSM16: - shadowReadMode = "VSM16"; - evsmExp = "5.54"; + shadowReadMode = 'VSM16'; + evsmExp = '5.54'; break; case SHADOW_VSM32: - shadowReadMode = "VSM32"; - evsmExp = "15.0"; + shadowReadMode = 'VSM32'; + evsmExp = '15.0'; break; case SHADOW_PCF1: - shadowReadMode = "PCF1x1"; + shadowReadMode = 'PCF1x1'; break; case SHADOW_PCF5: - shadowReadMode = "PCF5x5"; + shadowReadMode = 'PCF5x5'; break; case SHADOW_PCSS: - shadowReadMode = "PCSS"; + shadowReadMode = 'PCSS'; break; case SHADOW_PCF3: default: - shadowReadMode = "PCF3x3"; + shadowReadMode = 'PCF3x3'; break; } if (shadowReadMode !== null) { if (light._normalOffsetBias && !light._isVsm) { - func.append("#define SHADOW_SAMPLE_NORMAL_OFFSET"); + func.append('#define SHADOW_SAMPLE_NORMAL_OFFSET'); } if (lightType === LIGHTTYPE_DIRECTIONAL) { - func.append("#define SHADOW_SAMPLE_ORTHO"); + func.append('#define SHADOW_SAMPLE_ORTHO'); } if ((pcfShadows || pcssShadows) || device.isWebGPU) { - func.append("#define SHADOW_SAMPLE_SOURCE_ZBUFFER"); + func.append('#define SHADOW_SAMPLE_SOURCE_ZBUFFER'); } if (lightType === LIGHTTYPE_OMNI) { - func.append("#define SHADOW_SAMPLE_POINT"); + func.append('#define SHADOW_SAMPLE_POINT'); } // Create shadow coord sampler function for this light const coordCode = chunks.shadowSampleCoordPS; - func.append(coordCode.replace("$LIGHT", i)); + func.append(coordCode.replace('$LIGHT', i)); // Make sure to undefine the shadow sampler defines - func.append("#undef SHADOW_SAMPLE_NORMAL_OFFSET"); - func.append("#undef SHADOW_SAMPLE_ORTHO"); - func.append("#undef SHADOW_SAMPLE_SOURCE_ZBUFFER"); - func.append("#undef SHADOW_SAMPLE_POINT"); + func.append('#undef SHADOW_SAMPLE_NORMAL_OFFSET'); + func.append('#undef SHADOW_SAMPLE_ORTHO'); + func.append('#undef SHADOW_SAMPLE_SOURCE_ZBUFFER'); + func.append('#undef SHADOW_SAMPLE_POINT'); let shadowMatrix = `light${i}_shadowMatrix`; if (lightType === LIGHTTYPE_DIRECTIONAL && light.numCascades > 1) { // compute which cascade matrix needs to be used backend.append(` getShadowCascadeMatrix(light${i}_shadowMatrixPalette, light${i}_shadowCascadeDistances, light${i}_shadowCascadeCount);`); - shadowMatrix = `cascadeShadowMat`; + shadowMatrix = 'cascadeShadowMat'; } backend.append(` dShadowCoord = getShadowSampleCoord${i}(${shadowMatrix}, light${i}_shadowParams, vPositionW, dLightPosW, dLightDirW, dLightDirNormW, dVertexNormalW);`); @@ -1238,22 +1243,22 @@ class LitShader { // area light - they do not mix diffuse lighting into specular attenuation if (options.useSpecular) { - backend.append(" dDiffuseLight += ((dAttenD * dAtten) * light" + i + "_color" + (usesCookieNow ? " * dAtten3" : "") + ") * (1.0 - dLTCSpecFres);"); + backend.append(` dDiffuseLight += ((dAttenD * dAtten) * light${i}_color${usesCookieNow ? ' * dAtten3' : ''}) * (1.0 - dLTCSpecFres);`); } else { - backend.append(" dDiffuseLight += (dAttenD * dAtten) * light" + i + "_color" + (usesCookieNow ? " * dAtten3" : "") + ";"); + backend.append(` dDiffuseLight += (dAttenD * dAtten) * light${i}_color${usesCookieNow ? ' * dAtten3' : ''};`); } } else { // punctual light if (hasAreaLights && options.useSpecular) { - backend.append(" dDiffuseLight += (dAtten * light" + i + "_color" + (usesCookieNow ? " * dAtten3" : "") + ") * (1.0 - litArgs_specularity);"); + backend.append(` dDiffuseLight += (dAtten * light${i}_color${usesCookieNow ? ' * dAtten3' : ''}) * (1.0 - litArgs_specularity);`); } else { - backend.append(" dDiffuseLight += dAtten * light" + i + "_color" + (usesCookieNow ? " * dAtten3" : "") + ";"); + backend.append(` dDiffuseLight += dAtten * light${i}_color${usesCookieNow ? ' * dAtten3' : ''};`); } } if (options.useSpecular) { - backend.append(" dHalfDirW = normalize(-dLightDirNormW + dViewDirW);"); + backend.append(' dHalfDirW = normalize(-dLightDirNormW + dViewDirW);'); } // specular / clear coat @@ -1262,10 +1267,10 @@ class LitShader { // area light if (options.useClearCoat) { - backend.append(` ccSpecularLight += ccLTCSpecFres * get${shapeString}LightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * light${i}_color` + (usesCookieNow ? " * dAtten3" : "") + ";"); + backend.append(` ccSpecularLight += ccLTCSpecFres * get${shapeString}LightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * light${i}_color${usesCookieNow ? ' * dAtten3' : ''};`); } if (options.useSpecular) { - backend.append(` dSpecularLight += dLTCSpecFres * get${shapeString}LightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * light${i}_color` + (usesCookieNow ? " * dAtten3" : "") + ";"); + backend.append(` dSpecularLight += dLTCSpecFres * get${shapeString}LightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * light${i}_color${usesCookieNow ? ' * dAtten3' : ''};`); } } else { @@ -1276,18 +1281,18 @@ class LitShader { // if LTC lights are present, specular must be accumulated with specularity (specularity is pre multiplied by punctual light fresnel) if (options.useClearCoat) { - backend.append(` ccSpecularLight += getLightSpecular(dHalfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * light${i}_color` + - (usesCookieNow ? " * dAtten3" : "") + - (calcFresnel ? " * getFresnelCC(dot(dViewDirW, dHalfDirW));" : ";")); + backend.append(` ccSpecularLight += getLightSpecular(dHalfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * light${i}_color${ + usesCookieNow ? ' * dAtten3' : '' + }${calcFresnel ? ' * getFresnelCC(dot(dViewDirW, dHalfDirW));' : ';'}`); } if (options.useSheen) { - backend.append(` sSpecularLight += getLightSpecularSheen(dHalfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * light${i}_color` + - (usesCookieNow ? " * dAtten3;" : ";")); + backend.append(` sSpecularLight += getLightSpecularSheen(dHalfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * light${i}_color${ + usesCookieNow ? ' * dAtten3;' : ';'}`); } if (options.useSpecular) { - backend.append(` dSpecularLight += getLightSpecular(dHalfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * light${i}_color` + - (usesCookieNow ? " * dAtten3" : "") + - (calcFresnel ? ` + backend.append(` dSpecularLight += getLightSpecular(dHalfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * light${i}_color${ + usesCookieNow ? ' * dAtten3' : '' + }${calcFresnel ? ` * getFresnel( dot(dViewDirW, dHalfDirW), litArgs_gloss, @@ -1296,13 +1301,13 @@ class LitShader { , iridescenceFresnel, litArgs_iridescence_intensity #endif - );` : `* litArgs_specularity;`)); + );` : '* litArgs_specularity;'}`); } } } if (lightType !== LIGHTTYPE_DIRECTIONAL) { - backend.append(" }"); // BRANCH END + backend.append(' }'); // BRANCH END } } @@ -1335,10 +1340,10 @@ class LitShader { if (hasAreaLights) { // specular has to be accumulated differently if we want area lights to look correct if (options.useClearCoat) { - backend.append(" litArgs_clearcoat_specularity = 1.0;"); + backend.append(' litArgs_clearcoat_specularity = 1.0;'); } if (options.useSpecular) { - backend.append(" litArgs_specularity = vec3(1);"); + backend.append(' litArgs_specularity = vec3(1);'); } } @@ -1363,24 +1368,24 @@ class LitShader { if (options.useAo) { if (options.occludeDirect) { - backend.append(" occludeDiffuse(litArgs_ao);"); + backend.append(' occludeDiffuse(litArgs_ao);'); } if (options.occludeSpecular === SPECOCC_AO || options.occludeSpecular === SPECOCC_GLOSSDEPENDENT) { - backend.append(" occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);"); + backend.append(' occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);'); } } if (options.useSpecularityFactor) { - backend.append(" dSpecularLight *= litArgs_specularityFactor;"); + backend.append(' dSpecularLight *= litArgs_specularityFactor;'); } if (options.opacityFadesSpecular === false) { if (options.blendType === BLEND_NORMAL || options.blendType === BLEND_PREMULTIPLIED) { - backend.append("float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));"); - backend.append("#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection.rgb * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif"); - backend.append("litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);"); + backend.append('float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));'); + backend.append('#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection.rgb * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif'); + backend.append('litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);'); } - backend.append("litArgs_opacity *= material_alphaFade;"); + backend.append('litArgs_opacity *= material_alphaFade;'); } backend.append(chunks.endPS); @@ -1393,7 +1398,7 @@ class LitShader { } if (options.useMsdf) { - backend.append(" gl_FragColor = applyMsdf(gl_FragColor);"); + backend.append(' gl_FragColor = applyMsdf(gl_FragColor);'); } backend.append(chunks.outputPS); @@ -1415,49 +1420,49 @@ class LitShader { // non-clustered lights cookie code func.prepend(chunks.cookiePS); } - let structCode = ""; + let structCode = ''; const backendCode = `void evaluateBackend() {\n${backend.code}\n}`; func.append(backendCode); code.append(chunks.debugProcessFrontendPS); - code.append(" evaluateBackend();"); + code.append(' evaluateBackend();'); code.append(ShaderGenerator.end()); const mergedCode = decl.code + func.code + code.code; // Light inputs - if (mergedCode.includes("dTBN")) structCode += "mat3 dTBN;\n"; - if (mergedCode.includes("dVertexNormalW")) structCode += "vec3 dVertexNormalW;\n"; - if (mergedCode.includes("dTangentW")) structCode += "vec3 dTangentW;\n"; - if (mergedCode.includes("dBinormalW")) structCode += "vec3 dBinormalW;\n"; - if (mergedCode.includes("dViewDirW")) structCode += "vec3 dViewDirW;\n"; - if (mergedCode.includes("dReflDirW")) structCode += "vec3 dReflDirW;\n"; - if (mergedCode.includes("dHalfDirW")) structCode += "vec3 dHalfDirW;\n"; - if (mergedCode.includes("ccReflDirW")) structCode += "vec3 ccReflDirW;\n"; + if (mergedCode.includes('dTBN')) structCode += 'mat3 dTBN;\n'; + if (mergedCode.includes('dVertexNormalW')) structCode += 'vec3 dVertexNormalW;\n'; + if (mergedCode.includes('dTangentW')) structCode += 'vec3 dTangentW;\n'; + if (mergedCode.includes('dBinormalW')) structCode += 'vec3 dBinormalW;\n'; + if (mergedCode.includes('dViewDirW')) structCode += 'vec3 dViewDirW;\n'; + if (mergedCode.includes('dReflDirW')) structCode += 'vec3 dReflDirW;\n'; + if (mergedCode.includes('dHalfDirW')) structCode += 'vec3 dHalfDirW;\n'; + if (mergedCode.includes('ccReflDirW')) structCode += 'vec3 ccReflDirW;\n'; // Per-light temporaries - if (mergedCode.includes("dLightDirNormW")) structCode += "vec3 dLightDirNormW;\n"; - if (mergedCode.includes("dLightDirW")) structCode += "vec3 dLightDirW;\n"; - if (mergedCode.includes("dLightPosW")) structCode += "vec3 dLightPosW;\n"; - if (mergedCode.includes("dShadowCoord")) structCode += "vec3 dShadowCoord;\n"; + if (mergedCode.includes('dLightDirNormW')) structCode += 'vec3 dLightDirNormW;\n'; + if (mergedCode.includes('dLightDirW')) structCode += 'vec3 dLightDirW;\n'; + if (mergedCode.includes('dLightPosW')) structCode += 'vec3 dLightPosW;\n'; + if (mergedCode.includes('dShadowCoord')) structCode += 'vec3 dShadowCoord;\n'; // Outputs - if (mergedCode.includes("dReflection")) structCode += "vec4 dReflection;\n"; - if (mergedCode.includes("dDiffuseLight")) structCode += "vec3 dDiffuseLight;\n"; - if (mergedCode.includes("dSpecularLight")) structCode += "vec3 dSpecularLight;\n"; - if (mergedCode.includes("dAtten")) structCode += "float dAtten;\n"; - if (mergedCode.includes("dAttenD")) structCode += "float dAttenD;\n"; // separate diffuse attenuation for non-punctual light sources - if (mergedCode.includes("dAtten3")) structCode += "vec3 dAtten3;\n"; - if (mergedCode.includes("dMsdf")) structCode += "vec4 dMsdf;\n"; - if (mergedCode.includes("ccFresnel")) structCode += "float ccFresnel;\n"; - if (mergedCode.includes("ccReflection")) structCode += "vec3 ccReflection;\n"; - if (mergedCode.includes("ccSpecularLight")) structCode += "vec3 ccSpecularLight;\n"; - if (mergedCode.includes("ccSpecularityNoFres")) structCode += "float ccSpecularityNoFres;\n"; - if (mergedCode.includes("sSpecularLight")) structCode += "vec3 sSpecularLight;\n"; - if (mergedCode.includes("sReflection")) structCode += "vec3 sReflection;\n"; + if (mergedCode.includes('dReflection')) structCode += 'vec4 dReflection;\n'; + if (mergedCode.includes('dDiffuseLight')) structCode += 'vec3 dDiffuseLight;\n'; + if (mergedCode.includes('dSpecularLight')) structCode += 'vec3 dSpecularLight;\n'; + if (mergedCode.includes('dAtten')) structCode += 'float dAtten;\n'; + if (mergedCode.includes('dAttenD')) structCode += 'float dAttenD;\n'; // separate diffuse attenuation for non-punctual light sources + if (mergedCode.includes('dAtten3')) structCode += 'vec3 dAtten3;\n'; + if (mergedCode.includes('dMsdf')) structCode += 'vec4 dMsdf;\n'; + if (mergedCode.includes('ccFresnel')) structCode += 'float ccFresnel;\n'; + if (mergedCode.includes('ccReflection')) structCode += 'vec3 ccReflection;\n'; + if (mergedCode.includes('ccSpecularLight')) structCode += 'vec3 ccSpecularLight;\n'; + if (mergedCode.includes('ccSpecularityNoFres')) structCode += 'float ccSpecularityNoFres;\n'; + if (mergedCode.includes('sSpecularLight')) structCode += 'vec3 sSpecularLight;\n'; + if (mergedCode.includes('sReflection')) structCode += 'vec3 sReflection;\n'; const result = this._fsGetBeginCode() + this.varyings + diff --git a/src/scene/shader-lib/programs/lit.js b/src/scene/shader-lib/programs/lit.js index 80339e5d2bf..072b9803621 100644 --- a/src/scene/shader-lib/programs/lit.js +++ b/src/scene/shader-lib/programs/lit.js @@ -1,7 +1,7 @@ -import { ChunkBuilder } from '../chunk-builder.js'; -import { LitShader } from './lit-shader.js'; import { LitOptionsUtils } from './lit-options-utils.js'; +import { LitShader } from './lit-shader.js'; import { ShaderGenerator } from './shader-generator.js'; +import { ChunkBuilder } from '../chunk-builder.js'; /** * @import { GraphicsDevice } from '../../../platform/graphics/graphics-device.js' @@ -11,12 +11,12 @@ const dummyUvs = [0, 1, 2, 3, 4, 5, 6, 7]; class ShaderGeneratorLit extends ShaderGenerator { generateKey(options) { - const key = "lit" + + const key = `lit${ dummyUvs.map((dummy, index) => { - return options.usedUvs[index] ? "1" : "0"; - }).join("") + - options.shaderChunk + - LitOptionsUtils.generateKey(options.litOptions); + return options.usedUvs[index] ? '1' : '0'; + }).join('') + }${options.shaderChunk + }${LitOptionsUtils.generateKey(options.litOptions)}`; return key; } @@ -34,17 +34,17 @@ class ShaderGeneratorLit extends ShaderGenerator { const func = new ChunkBuilder(); // global texture bias for standard textures - decl.append(`uniform float textureBias;`); + decl.append('uniform float textureBias;'); decl.append(litShader.chunks.litShaderArgsPS); code.append(options.shaderChunk); - func.code = `evaluateFrontend();`; + func.code = 'evaluateFrontend();'; func.code = `\n${func.code.split('\n').map(l => ` ${l}`).join('\n')}\n\n`; const usedUvSets = options.usedUvs || [true]; const mapTransforms = []; litShader.generateVertexShader(usedUvSets, usedUvSets, mapTransforms); - litShader.generateFragmentShader(decl.code, code.code, func.code, "vUv0"); + litShader.generateFragmentShader(decl.code, code.code, func.code, 'vUv0'); return litShader.getDefinition(options); } diff --git a/src/scene/shader-lib/programs/particle.js b/src/scene/shader-lib/programs/particle.js index 07db592174f..0bd8075aae5 100644 --- a/src/scene/shader-lib/programs/particle.js +++ b/src/scene/shader-lib/programs/particle.js @@ -1,11 +1,11 @@ +import { ShaderGenerator } from './shader-generator.js'; import { ShaderUtils } from '../../../platform/graphics/shader-utils.js'; import { BLEND_ADDITIVE, BLEND_MULTIPLICATIVE, BLEND_NORMAL } from '../../constants.js'; import { shaderChunks } from '../chunks/chunks.js'; -import { ShaderGenerator } from './shader-generator.js'; class ShaderGeneratorParticle extends ShaderGenerator { generateKey(options) { - let key = "particle"; + let key = 'particle'; for (const prop in options) { if (options.hasOwnProperty(prop)) { key += options[prop]; @@ -15,7 +15,7 @@ class ShaderGeneratorParticle extends ShaderGenerator { } _animTex(options) { - let vshader = ""; + let vshader = ''; vshader += options.animTexLoop ? shaderChunks.particleAnimFrameLoopVS : shaderChunks.particleAnimFrameClampVS; vshader += shaderChunks.particleAnimTexVS; return vshader; @@ -25,19 +25,19 @@ class ShaderGeneratorParticle extends ShaderGenerator { const executionDefine = `#define PARTICLE_${options.useCpu ? 'CPU' : 'GPU'}\n`; - let fshader = '#define PARTICLE\n' + executionDefine; - let vshader = "#define VERTEXSHADER\n" + executionDefine; + let fshader = `#define PARTICLE\n${executionDefine}`; + let vshader = `#define VERTEXSHADER\n${executionDefine}`; - if (options.mesh) vshader += "#define USE_MESH\n"; - if (options.localSpace) vshader += "#define LOCAL_SPACE\n"; - if (options.screenSpace) vshader += "#define SCREEN_SPACE\n"; + if (options.mesh) vshader += '#define USE_MESH\n'; + if (options.localSpace) vshader += '#define LOCAL_SPACE\n'; + if (options.screenSpace) vshader += '#define SCREEN_SPACE\n'; - if (options.animTex) vshader += "\nuniform vec2 animTexTilesParams;\n"; - if (options.animTex) vshader += "\nuniform vec4 animTexParams;\n"; - if (options.animTex) vshader += "\nuniform vec2 animTexIndexParams;\n"; - if (options.normal === 2) vshader += "\nvarying mat3 ParticleMat;\n"; - if (options.normal === 1) vshader += "\nvarying vec3 Normal;\n"; - if (options.soft) vshader += "\nvarying float vDepth;\n"; + if (options.animTex) vshader += '\nuniform vec2 animTexTilesParams;\n'; + if (options.animTex) vshader += '\nuniform vec4 animTexParams;\n'; + if (options.animTex) vshader += '\nuniform vec2 animTexIndexParams;\n'; + if (options.normal === 2) vshader += '\nvarying mat3 ParticleMat;\n'; + if (options.normal === 1) vshader += '\nvarying vec3 Normal;\n'; + if (options.soft) vshader += '\nvarying float vDepth;\n'; const faceVS = options.customFace ? shaderChunks.particle_customFaceVS : shaderChunks.particle_billboardVS; @@ -70,28 +70,28 @@ class ShaderGeneratorParticle extends ShaderGenerator { vshader += shaderChunks.particle_cpu_endVS; if (options.soft > 0) vshader += shaderChunks.particle_softVS; } - vshader += "}\n"; + vshader += '}\n'; if (options.normal > 0) { if (options.normal === 1) { - fshader += "\nvarying vec3 Normal;\n"; + fshader += '\nvarying vec3 Normal;\n'; } else if (options.normal === 2) { - fshader += "\nvarying mat3 ParticleMat;\n"; + fshader += '\nvarying mat3 ParticleMat;\n'; } - fshader += "\nuniform vec3 lightCube[6];\n"; + fshader += '\nuniform vec3 lightCube[6];\n'; } - if (options.soft) fshader += "\nvarying float vDepth;\n"; + if (options.soft) fshader += '\nvarying float vDepth;\n'; fshader += shaderChunks.decodePS; fshader += ShaderGenerator.gammaCode(options.gamma); fshader += ShaderGenerator.tonemapCode(options.toneMap); fshader += ShaderGenerator.fogCode(options.fog); - if (options.normal === 2) fshader += "\nuniform sampler2D normalMap;\n"; + if (options.normal === 2) fshader += '\nuniform sampler2D normalMap;\n'; if (options.soft > 0) fshader += shaderChunks.screenDepthPS; fshader += shaderChunks.particlePS; if (options.soft > 0) fshader += shaderChunks.particle_softPS; - if (options.normal === 1) fshader += "\nvec3 normal = Normal;\n"; + if (options.normal === 1) fshader += '\nvec3 normal = Normal;\n'; if (options.normal === 2) fshader += shaderChunks.particle_normalMapPS; if (options.normal > 0) fshader += options.halflambert ? shaderChunks.particle_halflambertPS : shaderChunks.particle_lambertPS; if (options.normal > 0) fshader += shaderChunks.particle_lightingPS; diff --git a/src/scene/shader-lib/programs/shader-generator-shader.js b/src/scene/shader-lib/programs/shader-generator-shader.js index ef82294ecf1..92fa4e6b848 100644 --- a/src/scene/shader-lib/programs/shader-generator-shader.js +++ b/src/scene/shader-lib/programs/shader-generator-shader.js @@ -1,9 +1,9 @@ +import { ShaderGenerator } from './shader-generator.js'; import { hashCode } from '../../../core/hash.js'; import { SEMANTIC_ATTR15, SEMANTIC_BLENDINDICES, SEMANTIC_BLENDWEIGHT, SHADERLANGUAGE_WGSL } from '../../../platform/graphics/constants.js'; import { ShaderUtils } from '../../../platform/graphics/shader-utils.js'; import { ShaderPass } from '../../shader-pass.js'; import { shaderChunks } from '../chunks/chunks.js'; -import { ShaderGenerator } from './shader-generator.js'; const vShader = ` #include "shaderPassDefines" @@ -27,10 +27,10 @@ class ShaderGeneratorShader extends ShaderGenerator { const definesHash = ShaderGenerator.definesHash(options.defines); let key = `${desc.uniqueName}_${vsHash}_${fsHash}_${definesHash}`; - key += '_' + options.pass; - key += '_' + options.gamma; - key += '_' + options.toneMapping; - key += '_' + options.fog; + key += `_${options.pass}`; + key += `_${options.gamma}`; + key += `_${options.toneMapping}`; + key += `_${options.fog}`; if (options.skin) key += '_skin'; if (options.useInstancing) key += '_inst'; diff --git a/src/scene/shader-lib/programs/skybox.js b/src/scene/shader-lib/programs/skybox.js index 6b32c7f40db..c4164202492 100644 --- a/src/scene/shader-lib/programs/skybox.js +++ b/src/scene/shader-lib/programs/skybox.js @@ -1,10 +1,9 @@ +import { ShaderGenerator } from './shader-generator.js'; import { SEMANTIC_POSITION } from '../../../platform/graphics/constants.js'; -import { shaderChunks } from '../chunks/chunks.js'; -import { ChunkUtils } from '../chunk-utils.js'; - import { ShaderUtils } from '../../../platform/graphics/shader-utils.js'; -import { ShaderGenerator } from './shader-generator.js'; import { SKYTYPE_INFINITE } from '../../constants.js'; +import { ChunkUtils } from '../chunk-utils.js'; +import { shaderChunks } from '../chunks/chunks.js'; const fShader = ` #include "decodePS" diff --git a/src/scene/shader-lib/programs/standard.js b/src/scene/shader-lib/programs/standard.js index 1ad9624ab99..50a55e3321b 100644 --- a/src/scene/shader-lib/programs/standard.js +++ b/src/scene/shader-lib/programs/standard.js @@ -1,16 +1,16 @@ +import { LitOptionsUtils } from './lit-options-utils.js'; +import { LitShader } from './lit-shader.js'; +import { ShaderGenerator } from './shader-generator.js'; import { Debug } from '../../../core/debug.js'; import { BLEND_NONE, DITHER_BAYER8, DITHER_NONE, FRESNEL_SCHLICK, SHADER_FORWARD, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED } from '../../constants.js'; +import { StandardMaterialOptions } from '../../materials/standard-material-options.js'; import { ShaderPass } from '../../shader-pass.js'; -import { LitShader } from './lit-shader.js'; import { ChunkBuilder } from '../chunk-builder.js'; import { ChunkUtils } from '../chunk-utils.js'; -import { StandardMaterialOptions } from '../../materials/standard-material-options.js'; -import { LitOptionsUtils } from './lit-options-utils.js'; -import { ShaderGenerator } from './shader-generator.js'; /** * @import { GraphicsDevice } from '../../../platform/graphics/graphics-device.js' @@ -20,8 +20,8 @@ const _matTex2D = []; const buildPropertiesList = (options) => { return Object.keys(options) - .filter(key => key !== "litOptions") - .sort(); + .filter(key => key !== 'litOptions') + .sort(); }; class ShaderGeneratorStandard extends ShaderGenerator { @@ -43,9 +43,9 @@ class ShaderGeneratorStandard extends ShaderGenerator { } const definesHash = ShaderGenerator.definesHash(options.defines); - const key = "standard:\n" + definesHash + "\n" + - props.map(prop => prop + options[prop]).join('\n') + - LitOptionsUtils.generateKey(options.litOptions); + const key = `standard:\n${definesHash}\n${ + props.map(prop => prop + options[prop]).join('\n') + }${LitOptionsUtils.generateKey(options.litOptions)}`; return key; } @@ -68,20 +68,20 @@ class ShaderGeneratorStandard extends ShaderGenerator { let expression; if (isMainPass && options.litOptions.nineSlicedMode === SPRITE_RENDERMODE_SLICED) { - expression = "nineSlicedUv"; + expression = 'nineSlicedUv'; } else if (isMainPass && options.litOptions.nineSlicedMode === SPRITE_RENDERMODE_TILED) { - expression = "nineSlicedUv"; + expression = 'nineSlicedUv'; } else { if (transformId === 0) { - expression = "vUv" + uvChannel; + expression = `vUv${uvChannel}`; } else { // note: different capitalization! - expression = "vUV" + uvChannel + "_" + transformId; + expression = `vUV${uvChannel}_${transformId}`; } // if heightmap is enabled all maps except the heightmap are offset - if (options.heightMap && transformPropName !== "heightMapTransform") { - expression += " + dUvOffset"; + if (options.heightMap && transformPropName !== 'heightMapTransform') { + expression += ' + dUvOffset'; } } @@ -93,11 +93,11 @@ class ShaderGeneratorStandard extends ShaderGenerator { } _addMapDefs(float, color, vertex, map, invert) { - return this._addMapDef("MAPFLOAT", float) + - this._addMapDef("MAPCOLOR", color) + - this._addMapDef("MAPVERTEX", vertex) + - this._addMapDef("MAPTEXTURE", map) + - this._addMapDef("MAPINVERT", invert); + return this._addMapDef('MAPFLOAT', float) + + this._addMapDef('MAPCOLOR', color) + + this._addMapDef('MAPVERTEX', vertex) + + this._addMapDef('MAPTEXTURE', map) + + this._addMapDef('MAPINVERT', invert); } /** @@ -113,16 +113,16 @@ class ShaderGeneratorStandard extends ShaderGenerator { * @private */ _addMap(propName, chunkName, options, chunks, mapping, encoding = null) { - const mapPropName = propName + "Map"; - const uVPropName = mapPropName + "Uv"; - const identifierPropName = mapPropName + "Identifier"; - const transformPropName = mapPropName + "Transform"; - const channelPropName = mapPropName + "Channel"; - const vertexColorChannelPropName = propName + "VertexColorChannel"; - const tintPropName = propName + "Tint"; - const vertexColorPropName = propName + "VertexColor"; - const detailModePropName = propName + "Mode"; - const invertName = propName + "Invert"; + const mapPropName = `${propName}Map`; + const uVPropName = `${mapPropName}Uv`; + const identifierPropName = `${mapPropName}Identifier`; + const transformPropName = `${mapPropName}Transform`; + const channelPropName = `${mapPropName}Channel`; + const vertexColorChannelPropName = `${propName}VertexColorChannel`; + const tintPropName = `${propName}Tint`; + const vertexColorPropName = `${propName}VertexColor`; + const detailModePropName = `${propName}Mode`; + const invertName = `${propName}Invert`; const tintOption = options[tintPropName]; const vertexColorOption = options[vertexColorPropName]; @@ -138,7 +138,7 @@ class ShaderGeneratorStandard extends ShaderGenerator { subCode = subCode.replace(/\$UV/g, uv).replace(/\$CH/g, options[channelPropName]); if (mapping && subCode.search(/\$SAMPLER/g) !== -1) { - let samplerName = "texture_" + mapPropName; + let samplerName = `texture_${mapPropName}`; const alias = mapping[textureIdentifier]; if (alias) { samplerName = alias; @@ -184,7 +184,7 @@ class ShaderGeneratorStandard extends ShaderGenerator { const invertOption = !!(options[invertName]); subCode = this._addMapDefs(isFloatTint, isVecTint, vertexColorOption, textureOption, invertOption) + subCode; - return subCode.replace(/\$/g, ""); + return subCode.replace(/\$/g, ''); } _correctChannel(p, chan, _matTex2D) { @@ -221,17 +221,17 @@ class ShaderGeneratorStandard extends ShaderGenerator { const textureMapping = {}; for (const p in _matTex2D) { - const mname = p + "Map"; + const mname = `${p}Map`; - if (options[p + "VertexColor"]) { - const cname = p + "VertexColorChannel"; + if (options[`${p}VertexColor`]) { + const cname = `${p}VertexColorChannel`; options[cname] = this._correctChannel(p, options[cname], _matTex2D); } if (options[mname]) { - const cname = mname + "Channel"; - const tname = mname + "Transform"; - const uname = mname + "Uv"; + const cname = `${mname}Channel`; + const tname = `${mname}Transform`; + const uname = `${mname}Uv`; options[uname] = Math.min(options[uname], maxUvSets - 1); options[cname] = this._correctChannel(p, options[cname], _matTex2D); @@ -265,13 +265,13 @@ class ShaderGeneratorStandard extends ShaderGenerator { const code = new ChunkBuilder(); const func = new ChunkBuilder(); const args = new ChunkBuilder(); - let lightingUv = ""; + let lightingUv = ''; // global texture bias for standard textures if (options.litOptions.nineSlicedMode === SPRITE_RENDERMODE_TILED) { - decl.append(`const float textureBias = -1000.0;`); + decl.append('const float textureBias = -1000.0;'); } else { - decl.append(`uniform float textureBias;`); + decl.append('uniform float textureBias;'); } if (isForwardPass) { @@ -282,33 +282,34 @@ class ShaderGeneratorStandard extends ShaderGenerator { // if (!options.hasTangents) tbn = tbn.replace(/\$UV/g, transformedHeightMapUv); // code += tbn; // } - decl.append("vec2 dUvOffset;"); - code.append(this._addMap("height", "parallaxPS", options, litShader.chunks, textureMapping)); - func.append("getParallax();"); + decl.append('vec2 dUvOffset;'); + code.append(this._addMap('height', 'parallaxPS', options, litShader.chunks, textureMapping)); + func.append('getParallax();'); } // opacity if (options.litOptions.blendType !== BLEND_NONE || options.litOptions.alphaTest || options.litOptions.alphaToCoverage || options.litOptions.opacityDither !== DITHER_NONE) { - decl.append("float dAlpha;"); - code.append(this._addMap("opacity", "opacityPS", options, litShader.chunks, textureMapping)); - func.append("getOpacity();"); - args.append("litArgs_opacity = dAlpha;"); + decl.append('float dAlpha;'); + code.append(this._addMap('opacity', 'opacityPS', options, litShader.chunks, textureMapping)); + func.append('getOpacity();'); + args.append('litArgs_opacity = dAlpha;'); if (options.litOptions.alphaTest) { code.append(litShader.chunks.alphaTestPS); - func.append("alphaTest(dAlpha);"); + func.append('alphaTest(dAlpha);'); } const opacityDither = options.litOptions.opacityDither; if (opacityDither !== DITHER_NONE) { - if (opacityDither === DITHER_BAYER8) + if (opacityDither === DITHER_BAYER8) { decl.append(litShader.chunks.bayerPS); + } decl.append(`#define DITHER_${opacityDither.toUpperCase()}\n`); decl.append(litShader.chunks.opacityDitherPS); - func.append("opacityDither(dAlpha, 0.0);"); + func.append('opacityDither(dAlpha, 0.0);'); } } else { - decl.append("float dAlpha = 1.0;"); + decl.append('float dAlpha = 1.0;'); } // normal @@ -319,27 +320,27 @@ class ShaderGeneratorStandard extends ShaderGenerator { if (!options.litOptions.hasTangents) { // TODO: generalize to support each normalmap input (normalMap, normalDetailMap, clearCoatNormalMap) independently - const baseName = options.normalMap ? "normalMap" : "clearCoatNormalMap"; + const baseName = options.normalMap ? 'normalMap' : 'clearCoatNormalMap'; lightingUv = this._getUvSourceExpression(`${baseName}Transform`, `${baseName}Uv`, options); } } - decl.append("vec3 dNormalW;"); - code.append(this._addMap("normalDetail", "normalDetailMapPS", options, litShader.chunks, textureMapping)); - code.append(this._addMap("normal", "normalMapPS", options, litShader.chunks, textureMapping)); - func.append("getNormal();"); - args.append("litArgs_worldNormal = dNormalW;"); + decl.append('vec3 dNormalW;'); + code.append(this._addMap('normalDetail', 'normalDetailMapPS', options, litShader.chunks, textureMapping)); + code.append(this._addMap('normal', 'normalMapPS', options, litShader.chunks, textureMapping)); + func.append('getNormal();'); + args.append('litArgs_worldNormal = dNormalW;'); } if (litShader.needsSceneColor) { - decl.append("uniform sampler2D uSceneColorMap;"); + decl.append('uniform sampler2D uSceneColorMap;'); } if (litShader.needsScreenSize) { - decl.append("uniform vec4 uScreenSize;"); + decl.append('uniform vec4 uScreenSize;'); } if (litShader.needsTransforms) { - decl.append("uniform mat4 matrix_viewProjection;"); - decl.append("uniform mat4 matrix_model;"); + decl.append('uniform mat4 matrix_viewProjection;'); + decl.append('uniform mat4 matrix_model;'); } // support for diffuse & ao detail modes @@ -348,138 +349,138 @@ class ShaderGeneratorStandard extends ShaderGenerator { } // albedo - decl.append("vec3 dAlbedo;"); + decl.append('vec3 dAlbedo;'); if (options.diffuseDetail) { - code.append(this._addMap("diffuseDetail", "diffuseDetailMapPS", options, litShader.chunks, textureMapping, options.diffuseDetailEncoding)); + code.append(this._addMap('diffuseDetail', 'diffuseDetailMapPS', options, litShader.chunks, textureMapping, options.diffuseDetailEncoding)); } - code.append(this._addMap("diffuse", "diffusePS", options, litShader.chunks, textureMapping, options.diffuseEncoding)); - func.append("getAlbedo();"); - args.append("litArgs_albedo = dAlbedo;"); + code.append(this._addMap('diffuse', 'diffusePS', options, litShader.chunks, textureMapping, options.diffuseEncoding)); + func.append('getAlbedo();'); + args.append('litArgs_albedo = dAlbedo;'); if (options.litOptions.useRefraction) { - decl.append("float dTransmission;"); - code.append(this._addMap("refraction", "transmissionPS", options, litShader.chunks, textureMapping)); - func.append("getRefraction();"); - args.append("litArgs_transmission = dTransmission;"); + decl.append('float dTransmission;'); + code.append(this._addMap('refraction', 'transmissionPS', options, litShader.chunks, textureMapping)); + func.append('getRefraction();'); + args.append('litArgs_transmission = dTransmission;'); - decl.append("float dThickness;"); - code.append(this._addMap("thickness", "thicknessPS", options, litShader.chunks, textureMapping)); - func.append("getThickness();"); - args.append("litArgs_thickness = dThickness;"); + decl.append('float dThickness;'); + code.append(this._addMap('thickness', 'thicknessPS', options, litShader.chunks, textureMapping)); + func.append('getThickness();'); + args.append('litArgs_thickness = dThickness;'); if (options.litOptions.dispersion) { - args.append("litArgs_dispersion = material_dispersion;"); + args.append('litArgs_dispersion = material_dispersion;'); } } if (options.litOptions.useIridescence) { - decl.append("float dIridescence;"); - code.append(this._addMap("iridescence", "iridescencePS", options, litShader.chunks, textureMapping)); - func.append("getIridescence();"); - args.append("litArgs_iridescence_intensity = dIridescence;"); - - decl.append("float dIridescenceThickness;"); - code.append(this._addMap("iridescenceThickness", "iridescenceThicknessPS", options, litShader.chunks, textureMapping)); - func.append("getIridescenceThickness();"); - args.append("litArgs_iridescence_thickness = dIridescenceThickness;"); + decl.append('float dIridescence;'); + code.append(this._addMap('iridescence', 'iridescencePS', options, litShader.chunks, textureMapping)); + func.append('getIridescence();'); + args.append('litArgs_iridescence_intensity = dIridescence;'); + + decl.append('float dIridescenceThickness;'); + code.append(this._addMap('iridescenceThickness', 'iridescenceThicknessPS', options, litShader.chunks, textureMapping)); + func.append('getIridescenceThickness();'); + args.append('litArgs_iridescence_thickness = dIridescenceThickness;'); } // specularity & glossiness if ((litShader.lighting && options.litOptions.useSpecular) || litShader.reflections) { - decl.append("vec3 dSpecularity;"); - decl.append("float dGlossiness;"); + decl.append('vec3 dSpecularity;'); + decl.append('float dGlossiness;'); if (options.litOptions.useSheen) { - decl.append("vec3 sSpecularity;"); - code.append(this._addMap("sheen", "sheenPS", options, litShader.chunks, textureMapping, options.sheenEncoding)); - func.append("getSheen();"); - args.append("litArgs_sheen_specularity = sSpecularity;"); - - decl.append("float sGlossiness;"); - code.append(this._addMap("sheenGloss", "sheenGlossPS", options, litShader.chunks, textureMapping)); - func.append("getSheenGlossiness();"); - args.append("litArgs_sheen_gloss = sGlossiness;"); + decl.append('vec3 sSpecularity;'); + code.append(this._addMap('sheen', 'sheenPS', options, litShader.chunks, textureMapping, options.sheenEncoding)); + func.append('getSheen();'); + args.append('litArgs_sheen_specularity = sSpecularity;'); + + decl.append('float sGlossiness;'); + code.append(this._addMap('sheenGloss', 'sheenGlossPS', options, litShader.chunks, textureMapping)); + func.append('getSheenGlossiness();'); + args.append('litArgs_sheen_gloss = sGlossiness;'); } if (options.litOptions.useMetalness) { - decl.append("float dMetalness;"); - code.append(this._addMap("metalness", "metalnessPS", options, litShader.chunks, textureMapping)); - func.append("getMetalness();"); - args.append("litArgs_metalness = dMetalness;"); - - decl.append("float dIor;"); - code.append(this._addMap("ior", "iorPS", options, litShader.chunks, textureMapping)); - func.append("getIor();"); - args.append("litArgs_ior = dIor;"); + decl.append('float dMetalness;'); + code.append(this._addMap('metalness', 'metalnessPS', options, litShader.chunks, textureMapping)); + func.append('getMetalness();'); + args.append('litArgs_metalness = dMetalness;'); + + decl.append('float dIor;'); + code.append(this._addMap('ior', 'iorPS', options, litShader.chunks, textureMapping)); + func.append('getIor();'); + args.append('litArgs_ior = dIor;'); } if (options.litOptions.useSpecularityFactor) { - decl.append("float dSpecularityFactor;"); - code.append(this._addMap("specularityFactor", "specularityFactorPS", options, litShader.chunks, textureMapping)); - func.append("getSpecularityFactor();"); - args.append("litArgs_specularityFactor = dSpecularityFactor;"); + decl.append('float dSpecularityFactor;'); + code.append(this._addMap('specularityFactor', 'specularityFactorPS', options, litShader.chunks, textureMapping)); + func.append('getSpecularityFactor();'); + args.append('litArgs_specularityFactor = dSpecularityFactor;'); } if (options.useSpecularColor) { - code.append(this._addMap("specular", "specularPS", options, litShader.chunks, textureMapping, options.specularEncoding)); + code.append(this._addMap('specular', 'specularPS', options, litShader.chunks, textureMapping, options.specularEncoding)); } else { - code.append("void getSpecularity() { dSpecularity = vec3(1); }"); + code.append('void getSpecularity() { dSpecularity = vec3(1); }'); } - code.append(this._addMap("gloss", "glossPS", options, litShader.chunks, textureMapping)); - func.append("getGlossiness();"); - func.append("getSpecularity();"); - args.append("litArgs_specularity = dSpecularity;"); - args.append("litArgs_gloss = dGlossiness;"); + code.append(this._addMap('gloss', 'glossPS', options, litShader.chunks, textureMapping)); + func.append('getGlossiness();'); + func.append('getSpecularity();'); + args.append('litArgs_specularity = dSpecularity;'); + args.append('litArgs_gloss = dGlossiness;'); } else { - decl.append("vec3 dSpecularity = vec3(0.0);"); - decl.append("float dGlossiness = 0.0;"); + decl.append('vec3 dSpecularity = vec3(0.0);'); + decl.append('float dGlossiness = 0.0;'); } // ao if (options.aoDetail) { - code.append(this._addMap("aoDetail", "aoDetailMapPS", options, litShader.chunks, textureMapping)); + code.append(this._addMap('aoDetail', 'aoDetailMapPS', options, litShader.chunks, textureMapping)); } if (options.aoMap || options.aoVertexColor) { - decl.append("float dAo;"); - code.append(this._addMap("ao", "aoPS", options, litShader.chunks, textureMapping)); - func.append("getAO();"); - args.append("litArgs_ao = dAo;"); + decl.append('float dAo;'); + code.append(this._addMap('ao', 'aoPS', options, litShader.chunks, textureMapping)); + func.append('getAO();'); + args.append('litArgs_ao = dAo;'); } // emission - decl.append("vec3 dEmission;"); - code.append(this._addMap("emissive", "emissivePS", options, litShader.chunks, textureMapping, options.emissiveEncoding)); - func.append("getEmission();"); - args.append("litArgs_emission = dEmission;"); + decl.append('vec3 dEmission;'); + code.append(this._addMap('emissive', 'emissivePS', options, litShader.chunks, textureMapping, options.emissiveEncoding)); + func.append('getEmission();'); + args.append('litArgs_emission = dEmission;'); // clearcoat if (options.litOptions.useClearCoat) { - decl.append("float ccSpecularity;"); - decl.append("float ccGlossiness;"); - decl.append("vec3 ccNormalW;"); + decl.append('float ccSpecularity;'); + decl.append('float ccGlossiness;'); + decl.append('vec3 ccNormalW;'); - code.append(this._addMap("clearCoat", "clearCoatPS", options, litShader.chunks, textureMapping)); - code.append(this._addMap("clearCoatGloss", "clearCoatGlossPS", options, litShader.chunks, textureMapping)); - code.append(this._addMap("clearCoatNormal", "clearCoatNormalPS", options, litShader.chunks, textureMapping)); + code.append(this._addMap('clearCoat', 'clearCoatPS', options, litShader.chunks, textureMapping)); + code.append(this._addMap('clearCoatGloss', 'clearCoatGlossPS', options, litShader.chunks, textureMapping)); + code.append(this._addMap('clearCoatNormal', 'clearCoatNormalPS', options, litShader.chunks, textureMapping)); - func.append("getClearCoat();"); - func.append("getClearCoatGlossiness();"); - func.append("getClearCoatNormal();"); + func.append('getClearCoat();'); + func.append('getClearCoatGlossiness();'); + func.append('getClearCoatNormal();'); - args.append("litArgs_clearcoat_specularity = ccSpecularity;"); - args.append("litArgs_clearcoat_gloss = ccGlossiness;"); - args.append("litArgs_clearcoat_worldNormal = ccNormalW;"); + args.append('litArgs_clearcoat_specularity = ccSpecularity;'); + args.append('litArgs_clearcoat_gloss = ccGlossiness;'); + args.append('litArgs_clearcoat_worldNormal = ccNormalW;'); } // lightmap if (options.lightMap || options.lightVertexColor) { const lightmapDir = (options.dirLightMap && options.litOptions.useSpecular); const lightmapChunkPropName = lightmapDir ? 'lightmapDirPS' : 'lightmapSinglePS'; - decl.append("vec3 dLightmap;"); + decl.append('vec3 dLightmap;'); if (lightmapDir) { - decl.append("vec3 dLightmapDir;"); + decl.append('vec3 dLightmapDir;'); } - code.append(this._addMap("light", lightmapChunkPropName, options, litShader.chunks, textureMapping, options.lightMapEncoding)); - func.append("getLightMap();"); - args.append("litArgs_lightmap = dLightmap;"); + code.append(this._addMap('light', lightmapChunkPropName, options, litShader.chunks, textureMapping, options.lightMapEncoding)); + func.append('getLightMap();'); + args.append('litArgs_lightmap = dLightmap;'); if (lightmapDir) { - args.append("litArgs_lightmapDir = dLightmapDir;"); + args.append('litArgs_lightmapDir = dLightmapDir;'); } } @@ -491,27 +492,28 @@ class ShaderGeneratorStandard extends ShaderGenerator { // all other passes require only opacity const opacityShadowDither = options.litOptions.opacityShadowDither; if (options.litOptions.alphaTest || opacityShadowDither) { - decl.append("float dAlpha;"); - code.append(this._addMap("opacity", "opacityPS", options, litShader.chunks, textureMapping)); - func.append("getOpacity();"); - args.append("litArgs_opacity = dAlpha;"); + decl.append('float dAlpha;'); + code.append(this._addMap('opacity', 'opacityPS', options, litShader.chunks, textureMapping)); + func.append('getOpacity();'); + args.append('litArgs_opacity = dAlpha;'); if (options.litOptions.alphaTest) { code.append(litShader.chunks.alphaTestPS); - func.append("alphaTest(dAlpha);"); + func.append('alphaTest(dAlpha);'); } if (opacityShadowDither !== DITHER_NONE) { - if (opacityShadowDither === DITHER_BAYER8) + if (opacityShadowDither === DITHER_BAYER8) { decl.append(litShader.chunks.bayerPS); + } decl.append(`#define DITHER_${opacityShadowDither.toUpperCase()}\n`); decl.append(litShader.chunks.opacityDitherPS); - func.append("opacityDither(dAlpha, 0.0);"); + func.append('opacityDither(dAlpha, 0.0);'); } } } decl.append(litShader.chunks.litShaderArgsPS); code.append(`void evaluateFrontend() { \n${func.code}\n${args.code}\n }\n`); - func.code = `evaluateFrontend();`; + func.code = 'evaluateFrontend();'; for (const texture in textureMapping) { decl.append(`uniform sampler2D ${textureMapping[texture]};`); diff --git a/src/scene/shader-lib/utils.js b/src/scene/shader-lib/utils.js index 61ded8cbc7a..3ea9a73f427 100644 --- a/src/scene/shader-lib/utils.js +++ b/src/scene/shader-lib/utils.js @@ -1,10 +1,10 @@ -import { Shader } from '../../platform/graphics/shader.js'; -import { ShaderUtils } from '../../platform/graphics/shader-utils.js'; import { shaderChunks } from './chunks/chunks.js'; import { getProgramLibrary } from './get-program-library.js'; -import { Debug } from '../../core/debug.js'; import { ShaderGenerator } from './programs/shader-generator.js'; +import { Debug } from '../../core/debug.js'; import { SHADERLANGUAGE_WGSL } from '../../platform/graphics/constants.js'; +import { ShaderUtils } from '../../platform/graphics/shader-utils.js'; +import { Shader } from '../../platform/graphics/shader.js'; /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' diff --git a/src/scene/shader-pass.js b/src/scene/shader-pass.js index ec30da1ae60..ca53f3db339 100644 --- a/src/scene/shader-pass.js +++ b/src/scene/shader-pass.js @@ -1,8 +1,8 @@ -import { Debug } from '../core/debug.js'; -import { DeviceCache } from '../platform/graphics/device-cache.js'; import { SHADER_FORWARD, SHADER_DEPTH, SHADER_PICK, SHADER_SHADOW, SHADER_PREPASS_VELOCITY } from './constants.js'; +import { Debug } from '../core/debug.js'; +import { DeviceCache } from '../platform/graphics/device-cache.js'; /** * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' @@ -38,7 +38,7 @@ class ShaderPassInfo { */ constructor(name, index, options = {}) { - Debug.assert(/^[a-zA-Z][_a-zA-Z0-9]*$/.test(name), `ShaderPass name can only contain letters, numbers and underscores and start with a letter: ${name}`); + Debug.assert(/^[a-z]\w*$/i.test(name), `ShaderPass name can only contain letters, numbers and underscores and start with a letter: ${name}`); this.name = name; this.index = index; diff --git a/src/scene/skin-instance-cache.js b/src/scene/skin-instance-cache.js index c261f06ef02..da75eb0b33f 100644 --- a/src/scene/skin-instance-cache.js +++ b/src/scene/skin-instance-cache.js @@ -1,5 +1,5 @@ -import { RefCountedObject } from '../core/ref-counted-object.js'; import { SkinInstance } from './skin-instance.js'; +import { RefCountedObject } from '../core/ref-counted-object.js'; // Class used as an entry in the ref-counted skin instance cache class SkinInstanceCachedObject extends RefCountedObject { @@ -22,7 +22,7 @@ class SkinInstanceCache { // function that logs out the state of the skin instances cache static logCachedSkinInstances() { console.log('CachedSkinInstances'); - SkinInstanceCache._skinInstanceCache.forEach(function (array, rootBone) { + SkinInstanceCache._skinInstanceCache.forEach((array, rootBone) => { console.log(`${rootBone.name}: Array(${array.length})`); for (let i = 0; i < array.length; i++) { console.log(` ${i}: RefCount ${array[i].refCount}`); diff --git a/src/scene/skin-instance.js b/src/scene/skin-instance.js index 2821ae8737e..fc60dc4f442 100644 --- a/src/scene/skin-instance.js +++ b/src/scene/skin-instance.js @@ -1,6 +1,6 @@ import { Debug } from '../core/debug.js'; -import { math } from '../core/math/math.js'; import { Mat4 } from '../core/math/mat4.js'; +import { math } from '../core/math/math.js'; import { FILTER_NEAREST, PIXELFORMAT_RGBA32F, TEXTURELOCK_READ } from '../platform/graphics/constants.js'; import { Texture } from '../platform/graphics/texture.js'; diff --git a/src/scene/skybox/sky-geometry.js b/src/scene/skybox/sky-geometry.js index b53f1d4ec10..dfb0cc61f09 100644 --- a/src/scene/skybox/sky-geometry.js +++ b/src/scene/skybox/sky-geometry.js @@ -1,8 +1,8 @@ -import { Debug } from "../../core/debug.js"; -import { SKYTYPE_BOX, SKYTYPE_DOME, SKYTYPE_INFINITE } from "../constants.js"; -import { Mesh } from "../mesh.js"; -import { BoxGeometry } from "../geometry/box-geometry.js"; -import { DomeGeometry } from "../geometry/dome-geometry.js"; +import { Debug } from '../../core/debug.js'; +import { SKYTYPE_BOX, SKYTYPE_DOME, SKYTYPE_INFINITE } from '../constants.js'; +import { BoxGeometry } from '../geometry/box-geometry.js'; +import { DomeGeometry } from '../geometry/dome-geometry.js'; +import { Mesh } from '../mesh.js'; class SkyGeometry { static create(device, type) { diff --git a/src/scene/skybox/sky-mesh.js b/src/scene/skybox/sky-mesh.js index 3c80586b128..bae1e1bf54f 100644 --- a/src/scene/skybox/sky-mesh.js +++ b/src/scene/skybox/sky-mesh.js @@ -1,3 +1,4 @@ +import { SkyGeometry } from './sky-geometry.js'; import { CULLFACE_FRONT } from '../../platform/graphics/constants.js'; import { ShaderProcessorOptions } from '../../platform/graphics/shader-processor-options.js'; import { LAYERID_SKYBOX } from '../constants.js'; @@ -5,7 +6,6 @@ import { ShaderMaterial } from '../materials/shader-material.js'; import { MeshInstance } from '../mesh-instance.js'; import { getProgramLibrary } from '../shader-lib/get-program-library.js'; import { skybox } from '../shader-lib/programs/skybox.js'; -import { SkyGeometry } from './sky-geometry.js'; /** * @import { GraphNode } from '../graph-node.js' diff --git a/src/scene/skybox/sky.js b/src/scene/skybox/sky.js index 604f490424e..c3a7333af39 100644 --- a/src/scene/skybox/sky.js +++ b/src/scene/skybox/sky.js @@ -1,7 +1,7 @@ -import { Vec3 } from "../../core/math/vec3.js"; -import { SKYTYPE_INFINITE } from "../constants.js"; -import { GraphNode } from "../graph-node.js"; -import { SkyMesh } from "./sky-mesh.js"; +import { SkyMesh } from './sky-mesh.js'; +import { Vec3 } from '../../core/math/vec3.js'; +import { SKYTYPE_INFINITE } from '../constants.js'; +import { GraphNode } from '../graph-node.js'; /** * @import { Scene } from '../scene.js' diff --git a/src/scene/sprite.js b/src/scene/sprite.js index 7e07c9b4da9..dccbee8756e 100644 --- a/src/scene/sprite.js +++ b/src/scene/sprite.js @@ -1,8 +1,8 @@ -import { EventHandler } from '../core/event-handler.js'; -import { Vec2 } from '../core/math/vec2.js'; import { SPRITE_RENDERMODE_SIMPLE, SPRITE_RENDERMODE_SLICED, SPRITE_RENDERMODE_TILED } from './constants.js'; -import { Mesh } from './mesh.js'; import { Geometry } from './geometry/geometry.js'; +import { Mesh } from './mesh.js'; +import { EventHandler } from '../core/event-handler.js'; +import { Vec2 } from '../core/math/vec2.js'; /** * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' @@ -177,8 +177,9 @@ class Sprite extends EventHandler { * @type {number} */ set renderMode(value) { - if (this._renderMode === value) + if (this._renderMode === value) { return; + } const prev = this._renderMode; this._renderMode = value; @@ -388,8 +389,9 @@ class Sprite extends EventHandler { */ destroy() { for (const mesh of this._meshes) { - if (mesh) + if (mesh) { mesh.destroy(); + } } this._meshes.length = 0; } diff --git a/test/core/core.test.mjs b/test/core/core.test.mjs index 8786dd0d5d6..d5a3e8b3a24 100644 --- a/test/core/core.test.mjs +++ b/test/core/core.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { extend } from '../../src/core/core.js'; -import { expect } from 'chai'; -describe('core', function () { +describe('core', () => { - describe('#extend', function () { + describe('#extend', () => { - it('combines two objects', function () { + it('combines two objects', () => { const o1 = { a: 'a', b: 'b' @@ -24,7 +25,7 @@ describe('core', function () { expect(o3.d).to.equal('d'); }); - it('combines two arrays', function () { + it('combines two arrays', () => { const a1 = [1, 2, 3]; const a2 = [4, 5, 6]; @@ -35,7 +36,7 @@ describe('core', function () { expect(a3[2]).to.equal(a2[2]); }); - it('combines and object and an array', function () { + it('combines and object and an array', () => { const o1 = { a: 'a' }; const a1 = [1, 2]; @@ -45,7 +46,7 @@ describe('core', function () { expect(o2[1]).to.equal(2); }); - it('deep combines two objects', function () { + it('deep combines two objects', () => { const o1 = { A: 'A' }; @@ -62,7 +63,7 @@ describe('core', function () { expect(o3.A).to.equal('A'); }); - it('deep combines two objects and does not copy references', function () { + it('deep combines two objects and does not copy references', () => { const o1 = { A: 'A' }; diff --git a/test/core/event-handler.test.mjs b/test/core/event-handler.test.mjs index f8ba77441cc..72e67427749 100644 --- a/test/core/event-handler.test.mjs +++ b/test/core/event-handler.test.mjs @@ -1,28 +1,29 @@ +import { expect } from 'chai'; + import { EventHandler } from '../../src/core/event-handler.js'; -import { expect } from 'chai'; -describe('EventHandler', function () { +describe('EventHandler', () => { - describe('#hasEvent', function () { + describe('#hasEvent', () => { - it('returns true if the event is registered', function () { + it('returns true if the event is registered', () => { const e = new EventHandler(); - e.on('test', function () { }); + e.on('test', () => { }); expect(e.hasEvent('test')).to.be.true; }); - it('returns false if the event is not registered', function () { + it('returns false if the event is not registered', () => { const e = new EventHandler(); - e.on('test', function () { }); + e.on('test', () => { }); expect(e.hasEvent('hello')).to.be.false; }); }); - describe('#on', function () { + describe('#on', () => { - it('calls handler on fire', function () { + it('calls handler on fire', () => { const e = new EventHandler(); let called = false; e.on('test', () => { @@ -32,7 +33,7 @@ describe('EventHandler', function () { expect(called).to.be.true; }); - it('calls handler with up to 8 arguments on fire', function () { + it('calls handler with up to 8 arguments on fire', () => { const e = new EventHandler(); let called = false; e.on('test', (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) => { @@ -53,9 +54,9 @@ describe('EventHandler', function () { }); - describe('#once', function () { + describe('#once', () => { - it('unregisters itself after the first fire', function () { + it('unregisters itself after the first fire', () => { const e = new EventHandler(); let count = 0; e.once('test', () => { @@ -70,7 +71,7 @@ describe('EventHandler', function () { }); - describe('#off', function () { + describe('#off', () => { it('unregisters event handler with specified callback and scope', function () { const e = new EventHandler(); @@ -86,7 +87,7 @@ describe('EventHandler', function () { expect(called).to.be.false; }); - it('unregisters event handler with specified callback', function () { + it('unregisters event handler with specified callback', () => { const e = new EventHandler(); let called = false; const callback = function () { @@ -100,10 +101,10 @@ describe('EventHandler', function () { expect(called).to.be.false; }); - it('unregisters all event handlers', function () { + it('unregisters all event handlers', () => { const e = new EventHandler(); let called = false; - e.on('test', function () { + e.on('test', () => { called = true; }); expect(e.hasEvent('test')).to.be.true; diff --git a/test/core/guid.test.mjs b/test/core/guid.test.mjs index f810a80ff9a..7af1baf5114 100644 --- a/test/core/guid.test.mjs +++ b/test/core/guid.test.mjs @@ -1,20 +1,21 @@ +import { expect } from 'chai'; + import { guid } from '../../src/core/guid.js'; -import { expect } from 'chai'; -describe('guid', function () { +describe('guid', () => { - describe('#create', function () { + describe('#create', () => { - it('returns a string', function () { + it('returns a string', () => { expect(guid.create()).to.be.a('string'); }); - it('returns a string of length 36', function () { + it('returns a string of length 36', () => { expect(guid.create()).to.have.length(36); }); - it('returns different values each time', function () { + it('returns different values each time', () => { expect(guid.create()).to.not.equal(guid.create()); }); diff --git a/test/core/hash.test.mjs b/test/core/hash.test.mjs index 2243313105d..f30a03cb1f7 100644 --- a/test/core/hash.test.mjs +++ b/test/core/hash.test.mjs @@ -1,30 +1,31 @@ +import { expect } from 'chai'; + import { hashCode, hash32Fnv1a } from '../../src/core/hash.js'; -import { expect } from 'chai'; -describe('hashCode', function () { +describe('hashCode', () => { - it('returns 0 for the empty string', function () { + it('returns 0 for the empty string', () => { expect(hashCode('')).to.equal(0); }); - it('returns the same hash for the same string', function () { + it('returns the same hash for the same string', () => { expect(hashCode('abc')).to.equal(hashCode('abc')); }); - it('returns different hashes for different strings', function () { + it('returns different hashes for different strings', () => { expect(hashCode('abc')).to.not.equal(hashCode('def')); }); }); -describe('[1, 2, 3]', function () { +describe('[1, 2, 3]', () => { - it('returns the same hash for the same arrays', function () { + it('returns the same hash for the same arrays', () => { expect(hash32Fnv1a([1, 2, 3])).to.equal(hash32Fnv1a([1, 2, 3])); }); - it('returns different hashes for different arrays', function () { + it('returns different hashes for different arrays', () => { expect(hash32Fnv1a([1, 2, 3])).to.not.equal(hash32Fnv1a([3, 2, 1])); }); diff --git a/test/core/indexed-list.test.mjs b/test/core/indexed-list.test.mjs index 9bddf49c972..1b48569a6ee 100644 --- a/test/core/indexed-list.test.mjs +++ b/test/core/indexed-list.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { IndexedList } from '../../src/core/indexed-list.js'; -import { expect } from 'chai'; -describe('IndexedList', function () { +describe('IndexedList', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('creates an empty list', function () { + it('creates an empty list', () => { const list = new IndexedList(); expect(list.list().length).to.equal(0); @@ -14,9 +15,9 @@ describe('IndexedList', function () { }); - describe('#clear', function () { + describe('#clear', () => { - it('removes all values', function () { + it('removes all values', () => { const list = new IndexedList(); const key1 = 'key1'; @@ -58,9 +59,9 @@ describe('IndexedList', function () { }); - describe('#has', function () { + describe('#has', () => { - it('returns true if the key exists', function () { + it('returns true if the key exists', () => { const list = new IndexedList(); const key1 = 'key1'; @@ -88,7 +89,7 @@ describe('IndexedList', function () { expect(list.has(key5)).to.equal(true); }); - it('returns false if the key does not exist', function () { + it('returns false if the key does not exist', () => { const list = new IndexedList(); const key1 = 'key1'; @@ -118,9 +119,9 @@ describe('IndexedList', function () { }); - describe('#push', function () { + describe('#push', () => { - it('adds an key-value pair to the list', function () { + it('adds an key-value pair to the list', () => { const list = new IndexedList(); const key = 'key'; @@ -136,9 +137,9 @@ describe('IndexedList', function () { }); - describe('#get', function () { + describe('#get', () => { - it('returns the value for the key', function () { + it('returns the value for the key', () => { const list = new IndexedList(); const key = 'key'; @@ -149,7 +150,7 @@ describe('IndexedList', function () { expect(list.get(key)).to.equal(value); }); - it('returns null if the key does not exist', function () { + it('returns null if the key does not exist', () => { const list = new IndexedList(); const key = 'key'; @@ -163,9 +164,9 @@ describe('IndexedList', function () { }); - describe('#list', function () { + describe('#list', () => { - it('returns list in order', function () { + it('returns list in order', () => { const list = new IndexedList(); const key1 = 'key1'; @@ -197,9 +198,9 @@ describe('IndexedList', function () { }); - describe('#remove', function () { + describe('#remove', () => { - it('removes the key', function () { + it('removes the key', () => { const list = new IndexedList(); const key = 'key'; @@ -213,7 +214,7 @@ describe('IndexedList', function () { }); - it('does not affect surrounding keys', function () { + it('does not affect surrounding keys', () => { const list = new IndexedList(); const key1 = 'key1'; diff --git a/test/core/math/bit-packing.test.mjs b/test/core/math/bit-packing.test.mjs index 9a690d80f63..95aaf82ad85 100644 --- a/test/core/math/bit-packing.test.mjs +++ b/test/core/math/bit-packing.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { BitPacking } from '../../../src/core/math/bit-packing.js'; -import { expect } from 'chai'; -describe('BitPacking', function () { +describe('BitPacking', () => { - describe('#set', function () { + describe('#set', () => { - it('sets bits', function () { + it('sets bits', () => { let d = 0; d = BitPacking.set(d, 0b11, 1, 0b11); @@ -18,8 +19,8 @@ describe('BitPacking', function () { }); }); - describe('#get', function () { - it('gets bits', function () { + describe('#get', () => { + it('gets bits', () => { const d = 0b110011; expect(BitPacking.get(d, 0, 0b111111)).to.equal(d); @@ -29,8 +30,8 @@ describe('BitPacking', function () { }); }); - describe('#any', function () { - it('any', function () { + describe('#any', () => { + it('any', () => { const d = 0b110011; expect(BitPacking.any(d, 0, 0b111111)).to.equal(true); @@ -39,8 +40,8 @@ describe('BitPacking', function () { }); }); - describe('#all', function () { - it('all', function () { + describe('#all', () => { + it('all', () => { const d = 0b110011; expect(BitPacking.all(d, 0, 0b111111)).to.equal(false); diff --git a/test/core/math/color.test.mjs b/test/core/math/color.test.mjs index 7a8aae275a9..4b94037f78f 100644 --- a/test/core/math/color.test.mjs +++ b/test/core/math/color.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { Color } from '../../../src/core/math/color.js'; -import { expect } from 'chai'; -describe('Color', function () { +describe('Color', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const c = new Color(); expect(c.r).to.equal(0); expect(c.g).to.equal(0); @@ -14,7 +15,7 @@ describe('Color', function () { expect(c.a).to.equal(1); }); - it('supports number arguments', function () { + it('supports number arguments', () => { const c = new Color(0.1, 0.2, 0.3, 0.4); expect(c.r).to.equal(0.1); expect(c.g).to.equal(0.2); @@ -22,7 +23,7 @@ describe('Color', function () { expect(c.a).to.equal(0.4); }); - it('supports a 3 element array argument', function () { + it('supports a 3 element array argument', () => { const c = new Color([0.1, 0.2, 0.3]); expect(c.r).to.equal(0.1); expect(c.g).to.equal(0.2); @@ -30,7 +31,7 @@ describe('Color', function () { expect(c.a).to.equal(1); }); - it('supports a 4 element array argument', function () { + it('supports a 4 element array argument', () => { const c = new Color([0.1, 0.2, 0.3, 0.4]); expect(c.r).to.equal(0.1); expect(c.g).to.equal(0.2); @@ -40,9 +41,9 @@ describe('Color', function () { }); - describe('#clone', function () { + describe('#clone', () => { - it('clones a color', function () { + it('clones a color', () => { const c1 = new Color(0.1, 0.2, 0.3, 0.4); const c2 = c1.clone(); expect(c2).to.not.equal(c1); @@ -52,7 +53,7 @@ describe('Color', function () { expect(c2.a).to.equal(0.4); }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserColor extends Color {} const a = new UserColor(); const b = a.clone(); @@ -61,9 +62,9 @@ describe('Color', function () { }); - describe('#copy', function () { + describe('#copy', () => { - it('copies a color', function () { + it('copies a color', () => { const c1 = new Color(0.1, 0.2, 0.3, 0.4); const c2 = new Color(); c2.copy(c1); @@ -76,15 +77,15 @@ describe('Color', function () { }); - describe('#equals', function () { + describe('#equals', () => { - it('returns true if colors are equal', function () { + it('returns true if colors are equal', () => { const c1 = new Color(0.1, 0.2, 0.3, 0.4); const c2 = new Color(0.1, 0.2, 0.3, 0.4); expect(c1.equals(c2)).to.be.true; }); - it('returns false if colors are not equal', function () { + it('returns false if colors are not equal', () => { const c1 = new Color(0.1, 0.2, 0.3, 0.4); const c2 = new Color(0.5, 0.6, 0.7, 0.8); expect(c1.equals(c2)).to.be.false; @@ -92,9 +93,9 @@ describe('Color', function () { }); - describe('#fromString', function () { + describe('#fromString', () => { - it('parses a lower case hex string', function () { + it('parses a lower case hex string', () => { const c = new Color(); c.fromString('#ff00ff'); expect(c.r).to.equal(1); @@ -103,7 +104,7 @@ describe('Color', function () { expect(c.a).to.equal(1); }); - it('parses a lower case hex string with alpha', function () { + it('parses a lower case hex string with alpha', () => { const c = new Color(); c.fromString('#ff00ff80'); expect(c.r).to.equal(1); @@ -112,7 +113,7 @@ describe('Color', function () { expect(c.a).to.closeTo(0.5019607843137255, 0.0001); }); - it('parses a upper case hex string with alpha', function () { + it('parses a upper case hex string with alpha', () => { const c = new Color(); c.fromString('#FF00FF80'); expect(c.r).to.equal(1); @@ -123,9 +124,9 @@ describe('Color', function () { }); - describe('#lerp', function () { + describe('#lerp', () => { - it('linearly interpolates between two colors with alpha of 0', function () { + it('linearly interpolates between two colors with alpha of 0', () => { const c1 = new Color(0.1, 0.2, 0.3, 0.4); const c2 = new Color(0.5, 0.6, 0.7, 0.8); const c3 = new Color(); @@ -136,7 +137,7 @@ describe('Color', function () { expect(c3.a).to.equal(0.4); }); - it('linearly interpolates between two colors with alpha of 0.5', function () { + it('linearly interpolates between two colors with alpha of 0.5', () => { const c1 = new Color(0.1, 0.2, 0.3, 0.4); const c2 = new Color(0.5, 0.6, 0.7, 0.8); const c3 = new Color(); @@ -147,7 +148,7 @@ describe('Color', function () { expect(c3.a).to.be.closeTo(0.6, 0.0001); }); - it('linearly interpolates between two colors with alpha of 1', function () { + it('linearly interpolates between two colors with alpha of 1', () => { const c1 = new Color(0.1, 0.2, 0.3, 0.4); const c2 = new Color(0.5, 0.6, 0.7, 0.8); const c3 = new Color(); @@ -160,9 +161,9 @@ describe('Color', function () { }); - describe('#set', function () { + describe('#set', () => { - it('sets a color', function () { + it('sets a color', () => { const c = new Color(); c.set(0.1, 0.2, 0.3, 0.4); expect(c.r).to.equal(0.1); @@ -173,27 +174,27 @@ describe('Color', function () { }); - describe('#toString', function () { + describe('#toString', () => { - it('returns a string representation of black (no alpha)', function () { + it('returns a string representation of black (no alpha)', () => { expect(Color.BLACK.toString()).to.equal('#000000'); }); - it('returns a string representation of white (no alpha)', function () { + it('returns a string representation of white (no alpha)', () => { expect(Color.WHITE.toString()).to.equal('#ffffff'); }); - it('returns a string representation of an arbitrary color (no alpha)', function () { + it('returns a string representation of an arbitrary color (no alpha)', () => { const c = new Color(0.1, 0.2, 0.3, 0.4); expect(c.toString()).to.equal('#1a334d'); }); - it('returns a string representation of an arbitrary color (with single digit alpha)', function () { + it('returns a string representation of an arbitrary color (with single digit alpha)', () => { const c = new Color(0.1, 0.2, 0.3, 0.05); expect(c.toString(true)).to.equal('#1a334d0d'); }); - it('returns a string representation of an arbitrary color (with double digit alpha)', function () { + it('returns a string representation of an arbitrary color (with double digit alpha)', () => { const c = new Color(0.1, 0.2, 0.3, 0.4); expect(c.toString(true)).to.equal('#1a334d66'); }); diff --git a/test/core/math/curve-set.test.mjs b/test/core/math/curve-set.test.mjs index 74a1655a23f..9ae2e76e1d4 100644 --- a/test/core/math/curve-set.test.mjs +++ b/test/core/math/curve-set.test.mjs @@ -1,27 +1,28 @@ +import { expect } from 'chai'; + import { CURVE_LINEAR, CURVE_SMOOTHSTEP, CURVE_SPLINE, CURVE_STEP } from '../../../src/core/math/constants.js'; import { CurveSet } from '../../../src/core/math/curve-set.js'; -import { expect } from 'chai'; -describe('CurveSet', function () { +describe('CurveSet', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const curveSet = new CurveSet(); expect(curveSet.length).to.equal(1); expect(curveSet.type).to.equal(CURVE_SMOOTHSTEP); }); - it('supports one number argument', function () { + it('supports one number argument', () => { const curveSet = new CurveSet(3); expect(curveSet.length).to.equal(3); expect(curveSet.type).to.equal(CURVE_SMOOTHSTEP); }); - it('supports one array argument', function () { + it('supports one array argument', () => { const curveSet = new CurveSet([ [ 0, 0, // At 0 time, value of 0 @@ -43,15 +44,15 @@ describe('CurveSet', function () { }); - describe('#type', function () { + describe('#type', () => { - it('is CURVE_SMOOTHSTEP by default', function () { + it('is CURVE_SMOOTHSTEP by default', () => { const curveSet = new CurveSet(); expect(curveSet.type).to.equal(CURVE_SMOOTHSTEP); }); - it('can be set to CURVE_LINEAR', function () { + it('can be set to CURVE_LINEAR', () => { const curveSet = new CurveSet(); curveSet.type = CURVE_LINEAR; @@ -59,7 +60,7 @@ describe('CurveSet', function () { expect(curveSet.type).to.equal(CURVE_LINEAR); }); - it('can be set to CURVE_SMOOTHSTEP', function () { + it('can be set to CURVE_SMOOTHSTEP', () => { const curveSet = new CurveSet(); curveSet.type = CURVE_SMOOTHSTEP; @@ -67,7 +68,7 @@ describe('CurveSet', function () { expect(curveSet.type).to.equal(CURVE_SMOOTHSTEP); }); - it('can be set to CURVE_SPLINE', function () { + it('can be set to CURVE_SPLINE', () => { const curveSet = new CurveSet(); curveSet.type = CURVE_SPLINE; @@ -75,7 +76,7 @@ describe('CurveSet', function () { expect(curveSet.type).to.equal(CURVE_SPLINE); }); - it('can be set to CURVE_STEP', function () { + it('can be set to CURVE_STEP', () => { const curveSet = new CurveSet(); curveSet.type = CURVE_STEP; @@ -83,7 +84,7 @@ describe('CurveSet', function () { expect(curveSet.type).to.equal(CURVE_STEP); }); - it('sets the type property of all curves in the curve set', function () { + it('sets the type property of all curves in the curve set', () => { const curveSet = new CurveSet([ [ 0, 0, // At 0 time, value of 0 @@ -130,9 +131,9 @@ describe('CurveSet', function () { }); - describe('#clone()', function () { + describe('#clone()', () => { - it('clones a simple curve set', function () { + it('clones a simple curve set', () => { const curveSet = new CurveSet(); const clone = curveSet.clone(); @@ -141,7 +142,7 @@ describe('CurveSet', function () { expect(clone.type).to.equal(curveSet.type); }); - it('clones a complex curve set', function () { + it('clones a complex curve set', () => { const curveSet = new CurveSet([ [ 0, 0, // At 0 time, value of 0 @@ -181,7 +182,7 @@ describe('CurveSet', function () { } }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserCurveSet extends CurveSet {} const a = new UserCurveSet(); const b = a.clone(); @@ -189,9 +190,9 @@ describe('CurveSet', function () { }); }); - describe('#get()', function () { + describe('#get()', () => { - it('returns the curve at the given index', function () { + it('returns the curve at the given index', () => { const curveSet = new CurveSet([ [ 0, 0, // At 0 time, value of 0 @@ -225,9 +226,9 @@ describe('CurveSet', function () { }); - describe('#value()', function () { + describe('#value()', () => { - it('returns the optional array parameter', function () { + it('returns the optional array parameter', () => { const curveSet = new CurveSet([ [ 0, 0, @@ -246,7 +247,7 @@ describe('CurveSet', function () { expect(input).to.equal(output); }); - it('fills a supplied array with interpolated values based on the specified time (linear)', function () { + it('fills a supplied array with interpolated values based on the specified time (linear)', () => { const curveSet = new CurveSet([ [ 0, 0, @@ -279,7 +280,7 @@ describe('CurveSet', function () { expect(result).to.deep.equal([0, 1]); }); - it('fills a supplied array with interpolated values based on the specified time (smoothstep)', function () { + it('fills a supplied array with interpolated values based on the specified time (smoothstep)', () => { const curveSet = new CurveSet([ [ 0, 0, @@ -308,7 +309,7 @@ describe('CurveSet', function () { expect(result).to.deep.equal([0.5, 0.5]); }); - it('fills a supplied array with interpolated values based on the specified time (spline)', function () { + it('fills a supplied array with interpolated values based on the specified time (spline)', () => { const curveSet = new CurveSet([ [ 0, 0, @@ -341,7 +342,7 @@ describe('CurveSet', function () { expect(result).to.deep.equal([0, 1]); }); - it('fills a supplied array with interpolated values based on the specified time (step)', function () { + it('fills a supplied array with interpolated values based on the specified time (step)', () => { const curveSet = new CurveSet([ [ 0, 0, diff --git a/test/core/math/curve.test.mjs b/test/core/math/curve.test.mjs index c41932d9058..b7b0edefb9f 100644 --- a/test/core/math/curve.test.mjs +++ b/test/core/math/curve.test.mjs @@ -1,18 +1,19 @@ +import { expect } from 'chai'; + import { CURVE_LINEAR, CURVE_SMOOTHSTEP, CURVE_SPLINE, CURVE_STEP } from '../../../src/core/math/constants.js'; import { Curve } from '../../../src/core/math/curve.js'; -import { expect } from 'chai'; -describe('Curve', function () { +describe('Curve', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const c = new Curve(); expect(c.keys.length).to.equal(0); }); - it('supports array argument already sorted by time', function () { + it('supports array argument already sorted by time', () => { const c = new Curve([ 0, 0, // At 0 time, value of 0 0.33, 2, // At 0.33 time, value of 2 @@ -32,7 +33,7 @@ describe('Curve', function () { expect(c.keys[3][1]).to.equal(3); }); - it('supports array argument not sorted by time', function () { + it('supports array argument not sorted by time', () => { const c = new Curve([ 0, 0, // At 0 time, value of 0 0.33, 2, // At 0.33 time, value of 2 @@ -54,9 +55,9 @@ describe('Curve', function () { }); - describe('#add', function () { + describe('#add', () => { - it('adds a new key to an empty curve', function () { + it('adds a new key to an empty curve', () => { const c = new Curve(); c.add(0.5, 1); expect(c.length).to.equal(1); @@ -64,7 +65,7 @@ describe('Curve', function () { expect(c.keys[0][1]).to.equal(1); }); - it('inserts a new key to a curve with existing keys at the correct index', function () { + it('inserts a new key to a curve with existing keys at the correct index', () => { const c = new Curve([ 0, 0, // At 0 time, value of 0 0.33, 2, // At 0.33 time, value of 2 @@ -87,9 +88,9 @@ describe('Curve', function () { }); - describe('#clone', function () { + describe('#clone', () => { - it('clones an empty curve', function () { + it('clones an empty curve', () => { const c = new Curve(); const clone = c.clone(); expect(clone.length).to.equal(c.length); @@ -97,7 +98,7 @@ describe('Curve', function () { expect(clone.tension).to.equal(c.tension); }); - it('clones a curve with keys', function () { + it('clones a curve with keys', () => { const c = new Curve([ 0, 0, // At 0 time, value of 0 0.33, 2, // At 0.33 time, value of 2 @@ -113,7 +114,7 @@ describe('Curve', function () { } }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserCurve extends Curve {} const a = new UserCurve(); const b = a.clone(); @@ -122,9 +123,9 @@ describe('Curve', function () { }); - describe('#get', function () { + describe('#get', () => { - it('returns the key at the given index', function () { + it('returns the key at the given index', () => { const c = new Curve([ 0, 0, // At 0 time, value of 0 0.33, 2, // At 0.33 time, value of 2 @@ -138,7 +139,7 @@ describe('Curve', function () { expect(c.get(3)).to.deep.equal([1, 3]); }); - it('returns undefined if the index is out of range', function () { + it('returns undefined if the index is out of range', () => { const c = new Curve([ 0, 0, // At 0 time, value of 0 0.33, 2, // At 0.33 time, value of 2 @@ -152,9 +153,9 @@ describe('Curve', function () { }); - describe('#quantize', function () { + describe('#quantize', () => { - it('returns the interpolated values at the given intervals (CURVE_LINEAR)', function () { + it('returns the interpolated values at the given intervals (CURVE_LINEAR)', () => { const c = new Curve([ 0, 0, 0.25, 1, @@ -178,7 +179,7 @@ describe('Curve', function () { expect(values[10]).to.be.closeTo(0, 0.00001); }); - it('returns the interpolated values at the given intervals (CURVE_SMOOTHSTEP)', function () { + it('returns the interpolated values at the given intervals (CURVE_SMOOTHSTEP)', () => { const c = new Curve([ 0, 0, 0.25, 1, @@ -201,7 +202,7 @@ describe('Curve', function () { expect(values[10]).to.be.closeTo(0, 0.00001); }); - it('returns the interpolated values at the given intervals (CURVE_SPLINE})', function () { + it('returns the interpolated values at the given intervals (CURVE_SPLINE})', () => { const c = new Curve([ 0, 0, 0.25, 1, @@ -225,7 +226,7 @@ describe('Curve', function () { expect(values[10]).to.be.closeTo(0, 0.00001); }); - it('returns the interpolated values at the given intervals (CURVE_STEP)', function () { + it('returns the interpolated values at the given intervals (CURVE_STEP)', () => { const c = new Curve([ 0, 0, 0.25, 1, @@ -251,9 +252,9 @@ describe('Curve', function () { }); - describe('#value', function () { + describe('#value', () => { - it('returns the interpolated value at the given time (CURVE_LINEAR)', function () { + it('returns the interpolated value at the given time (CURVE_LINEAR)', () => { const c = new Curve([ 0, 0, 0.25, 1, @@ -275,7 +276,7 @@ describe('Curve', function () { expect(c.value(1)).to.be.closeTo(0, 0.00001); }); - it('returns the interpolated value at the given time (CURVE_SMOOTHSTEP)', function () { + it('returns the interpolated value at the given time (CURVE_SMOOTHSTEP)', () => { const c = new Curve([ 0, 0, 0.25, 1, @@ -296,7 +297,7 @@ describe('Curve', function () { expect(c.value(1)).to.be.closeTo(0, 0.00001); }); - it('returns the interpolated value at the given time (CURVE_SPLINE})', function () { + it('returns the interpolated value at the given time (CURVE_SPLINE})', () => { const c = new Curve([ 0, 0, 0.25, 1, @@ -318,7 +319,7 @@ describe('Curve', function () { expect(c.value(1)).to.be.closeTo(0, 0.00001); }); - it('returns the interpolated value at the given time (CURVE_STEP)', function () { + it('returns the interpolated value at the given time (CURVE_STEP)', () => { const c = new Curve([ 0, 0, 0.25, 1, diff --git a/test/core/math/mat3.test.mjs b/test/core/math/mat3.test.mjs index efaee0fea98..019fcacc196 100644 --- a/test/core/math/mat3.test.mjs +++ b/test/core/math/mat3.test.mjs @@ -1,8 +1,9 @@ +import { expect } from 'chai'; + import { Mat3 } from '../../../src/core/math/mat3.js'; import { Mat4 } from '../../../src/core/math/mat4.js'; import { Vec3 } from '../../../src/core/math/vec3.js'; -import { expect } from 'chai'; const identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; const increasing = [1, 2, 3, 4, 5, 6, 7, 8, 9]; @@ -11,24 +12,24 @@ const increasingTransposed = [1, 4, 7, 2, 5, 8, 3, 6, 9]; const increasingMat4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; -describe('Mat3', function () { +describe('Mat3', () => { - describe('#data', function () { - it('is a Float32Array of length 9', function () { + describe('#data', () => { + it('is a Float32Array of length 9', () => { const m = new Mat3(); expect(m.data).to.be.an.instanceof(Float32Array); expect(m.data).to.have.length(9); }); - it('is initialized to the identity matrix', function () { + it('is initialized to the identity matrix', () => { const m = new Mat3(); expect(m.data).to.deep.equal(new Float32Array(identity)); }); }); - describe('#equals', function () { + describe('#equals', () => { - it('returns true for the same matrix', function () { + it('returns true for the same matrix', () => { const m = new Mat3(); m.data.set(increasing); const n = new Mat3(); @@ -36,7 +37,7 @@ describe('Mat3', function () { expect(m.equals(n)).to.be.true; }); - it('returns false for different matrices', function () { + it('returns false for different matrices', () => { const m = new Mat3(); m.data.set(increasing); const n = new Mat3(); @@ -46,8 +47,8 @@ describe('Mat3', function () { }); - describe('#clone', function () { - it('clones correctly', function () { + describe('#clone', () => { + it('clones correctly', () => { const m = new Mat3(); m.data.set(increasing); const n = m.clone(); @@ -55,8 +56,8 @@ describe('Mat3', function () { }); }); - describe('#copy', function () { - it('copies correctly', function () { + describe('#copy', () => { + it('copies correctly', () => { const m = new Mat3(); m.data.set(increasing); const n = new Mat3(); @@ -65,8 +66,8 @@ describe('Mat3', function () { }); }); - describe('#set', function () { - it('sets the matrix correctly', function () { + describe('#set', () => { + it('sets the matrix correctly', () => { const m = new Mat3(); m.set(increasing); const n = new Mat3(); @@ -75,21 +76,21 @@ describe('Mat3', function () { }); }); - describe('#isIdentity', function () { - it('is true for the identity matrix', function () { + describe('#isIdentity', () => { + it('is true for the identity matrix', () => { const m = new Mat3(); expect(m.isIdentity()).to.be.true; }); - it('is false for a non-identity matrix', function () { + it('is false for a non-identity matrix', () => { const m = new Mat3(); m.data.set([1, 2, 3, 4, 5, 6, 7, 8, 9]); expect(m.isIdentity()).to.be.false; }); }); - describe('#setIdentity', function () { - it('sets the matrix to the identity matrix', function () { + describe('#setIdentity', () => { + it('sets the matrix to the identity matrix', () => { const m = new Mat3(); m.set(increasing); expect(m.isIdentity()).to.be.false; @@ -98,15 +99,15 @@ describe('Mat3', function () { }); }); - describe('#transpose', function () { + describe('#transpose', () => { - it('transposes the identity matrix to the identity matrix', function () { + it('transposes the identity matrix to the identity matrix', () => { const m = new Mat3(); m.transpose(); expect(m.isIdentity()).to.be.true; }); - it('transposes a non-identity matrix correctly', function () { + it('transposes a non-identity matrix correctly', () => { const m = new Mat3(); m.set(increasing); m.transpose(); @@ -114,7 +115,7 @@ describe('Mat3', function () { expect(m.data).to.deep.equal(new Float32Array(increasingTransposed)); }); - it('transposes a non-identity matrix correctly given a source matrix', function () { + it('transposes a non-identity matrix correctly given a source matrix', () => { const m = new Mat3(); m.set(increasing); const n = new Mat3(); @@ -123,8 +124,8 @@ describe('Mat3', function () { }); }); - describe('#setFromMat4', function () { - it('sets the matrix correctly', function () { + describe('#setFromMat4', () => { + it('sets the matrix correctly', () => { const m = new Mat4(); m.set(increasingMat4); @@ -135,8 +136,8 @@ describe('Mat3', function () { }); }); - describe('#invertMat4', function () { - it('inverts the matrix correctly', function () { + describe('#invertMat4', () => { + it('inverts the matrix correctly', () => { const m = new Mat4(); m.set([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1]); @@ -147,8 +148,8 @@ describe('Mat3', function () { }); }); - describe('#transformVector', function () { - it('transforms a vector correctly', function () { + describe('#transformVector', () => { + it('transforms a vector correctly', () => { const m = new Mat4(); m.setScale(2, 2, 2); diff --git a/test/core/math/mat4.test.mjs b/test/core/math/mat4.test.mjs index 0f116ee3ff0..93914463d05 100644 --- a/test/core/math/mat4.test.mjs +++ b/test/core/math/mat4.test.mjs @@ -1,15 +1,16 @@ +import { expect } from 'chai'; + import { Mat4 } from '../../../src/core/math/mat4.js'; import { Quat } from '../../../src/core/math/quat.js'; import { Vec3 } from '../../../src/core/math/vec3.js'; import { Vec4 } from '../../../src/core/math/vec4.js'; -import { expect } from 'chai'; -describe('Mat4', function () { +describe('Mat4', () => { - describe('#data', function () { + describe('#data', () => { - it('is a Float32Array of length 16', function () { + it('is a Float32Array of length 16', () => { const m = new Mat4(); expect(m.data).to.be.an.instanceof(Float32Array); expect(m.data).to.have.length(16); @@ -17,9 +18,9 @@ describe('Mat4', function () { }); - describe('#constructor()', function () { + describe('#constructor()', () => { - it('creates an identity matrix', function () { + it('creates an identity matrix', () => { const m = new Mat4(); const identity = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); expect(m.data).to.deep.equal(identity); @@ -27,9 +28,9 @@ describe('Mat4', function () { }); - describe('#add()', function () { + describe('#add()', () => { - it('adds one matrix to another in place', function () { + it('adds one matrix to another in place', () => { const m1 = new Mat4(); m1.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const m2 = new Mat4(); @@ -39,7 +40,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(result); }); - it('returns this', function () { + it('returns this', () => { const m1 = new Mat4(); const m2 = new Mat4(); expect(m1.add(m2)).to.equal(m1); @@ -47,9 +48,9 @@ describe('Mat4', function () { }); - describe('#add2()', function () { + describe('#add2()', () => { - it('adds two matrices together and writes result to a third matrix', function () { + it('adds two matrices together and writes result to a third matrix', () => { const m1 = new Mat4(); m1.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const m2 = new Mat4(); @@ -60,7 +61,7 @@ describe('Mat4', function () { expect(m3.data).to.deep.equal(result); }); - it('returns this', function () { + it('returns this', () => { const m1 = new Mat4(); const m2 = new Mat4(); const m3 = new Mat4(); @@ -69,16 +70,16 @@ describe('Mat4', function () { }); - describe('#clone()', function () { + describe('#clone()', () => { - it('clones a matrix', function () { + it('clones a matrix', () => { const m1 = new Mat4(); m1.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const m2 = m1.clone(); expect(m2.data).to.deep.equal(m1.data); }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserMat4 extends Mat4 {} const a = new UserMat4(); const b = a.clone(); @@ -87,9 +88,9 @@ describe('Mat4', function () { }); - describe('#copy()', function () { + describe('#copy()', () => { - it('copies a matrix', function () { + it('copies a matrix', () => { const m1 = new Mat4(); m1.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const m2 = new Mat4(); @@ -97,7 +98,7 @@ describe('Mat4', function () { expect(m2.data).to.deep.equal(m1.data); }); - it('returns this', function () { + it('returns this', () => { const m1 = new Mat4(); const m2 = new Mat4(); expect(m2.copy(m1)).to.equal(m2); @@ -105,9 +106,9 @@ describe('Mat4', function () { }); - describe('#equals()', function () { + describe('#equals()', () => { - it('checks for equality', function () { + it('checks for equality', () => { const m1 = new Mat4(); m1.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const m2 = new Mat4(); @@ -120,9 +121,9 @@ describe('Mat4', function () { }); - describe('#getEulerAngles()', function () { + describe('#getEulerAngles()', () => { - it('gets euler angles from an identity matrix', function () { + it('gets euler angles from an identity matrix', () => { const m = new Mat4(); const angles = m.getEulerAngles(); expect(angles.x).to.equal(0); @@ -130,7 +131,7 @@ describe('Mat4', function () { expect(angles.z).to.equal(0); }); - it('gets euler angles from an identity matrix (no allocation)', function () { + it('gets euler angles from an identity matrix (no allocation)', () => { const m = new Mat4(); const angles = new Vec3(); m.getEulerAngles(angles); @@ -139,7 +140,7 @@ describe('Mat4', function () { expect(angles.z).to.equal(0); }); - it('gets a 90 rotation around x', function () { + it('gets a 90 rotation around x', () => { const m = new Mat4(); m.set([1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1]); const angles = m.getEulerAngles(); @@ -148,7 +149,7 @@ describe('Mat4', function () { expect(angles.z).to.equal(0); }); - it('gets a -45 rotation around x', function () { + it('gets a -45 rotation around x', () => { const m = new Mat4(); m.set([1, 0, 0, 0, 0, 0.7071067811865476, -0.7071067811865476, 0, 0, 0.7071067811865476, 0.7071067811865476, 0, 0, 0, 0, 1]); const angles = m.getEulerAngles(); @@ -157,7 +158,7 @@ describe('Mat4', function () { expect(angles.z).to.be.closeTo(0, 0.00001); }); - it('gets a -45 rotation around y', function () { + it('gets a -45 rotation around y', () => { const m = new Mat4(); m.set([0.7071067811865476, 0, 0.7071067811865476, 0, 0, 1, 0, 0, -0.7071067811865476, 0, 0.7071067811865476, 0, 0, 0, 0, 1]); const angles = m.getEulerAngles(); @@ -166,7 +167,7 @@ describe('Mat4', function () { expect(angles.z).to.be.closeTo(0, 0.00001); }); - it('gets a -45 rotation around z', function () { + it('gets a -45 rotation around z', () => { const m = new Mat4(); m.set([0.7071067811865476, -0.7071067811865476, 0, 0, 0.7071067811865476, 0.7071067811865476, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); const angles = m.getEulerAngles(); @@ -177,9 +178,9 @@ describe('Mat4', function () { }); - describe('#getScale()', function () { + describe('#getScale()', () => { - it('gets scale from an identity matrix', function () { + it('gets scale from an identity matrix', () => { const m = new Mat4(); const scale = m.getScale(); expect(scale.x).to.equal(1); @@ -187,7 +188,7 @@ describe('Mat4', function () { expect(scale.z).to.equal(1); }); - it('gets scale from an identity matrix (no allocation)', function () { + it('gets scale from an identity matrix (no allocation)', () => { const m = new Mat4(); const scale = new Vec3(); m.getScale(scale); @@ -196,7 +197,7 @@ describe('Mat4', function () { expect(scale.z).to.equal(1); }); - it('gets scale from a scaled matrix', function () { + it('gets scale from a scaled matrix', () => { const m = new Mat4(); m.set([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1]); const scale = m.getScale(); @@ -205,7 +206,7 @@ describe('Mat4', function () { expect(scale.z).to.equal(2); }); - it('gets scale from a scaled matrix (no allocation)', function () { + it('gets scale from a scaled matrix (no allocation)', () => { const m = new Mat4(); m.set([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1]); const scale = new Vec3(); @@ -217,9 +218,9 @@ describe('Mat4', function () { }); - describe('#getTranslation()', function () { + describe('#getTranslation()', () => { - it('gets translation from an identity matrix', function () { + it('gets translation from an identity matrix', () => { const m = new Mat4(); const translation = m.getTranslation(); expect(translation.x).to.equal(0); @@ -227,7 +228,7 @@ describe('Mat4', function () { expect(translation.z).to.equal(0); }); - it('gets translation from an identity matrix (no allocation)', function () { + it('gets translation from an identity matrix (no allocation)', () => { const m = new Mat4(); const translation = new Vec3(); m.getTranslation(translation); @@ -236,7 +237,7 @@ describe('Mat4', function () { expect(translation.z).to.equal(0); }); - it('gets translation from a translated matrix', function () { + it('gets translation from a translated matrix', () => { const m = new Mat4(); m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]); const translation = m.getTranslation(); @@ -245,7 +246,7 @@ describe('Mat4', function () { expect(translation.z).to.equal(30); }); - it('gets translation from a translated matrix (no allocation)', function () { + it('gets translation from a translated matrix (no allocation)', () => { const m = new Mat4(); m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]); const translation = new Vec3(); @@ -257,9 +258,9 @@ describe('Mat4', function () { }); - describe('#getX()', function () { + describe('#getX()', () => { - it('gets x axis from a matrix', function () { + it('gets x axis from a matrix', () => { const m = new Mat4(); m.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const axis = m.getX(); @@ -268,7 +269,7 @@ describe('Mat4', function () { expect(axis.z).to.equal(2); }); - it('gets x axis from a matrix (no allocation)', function () { + it('gets x axis from a matrix (no allocation)', () => { const m = new Mat4(); m.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const axis = new Vec3(); @@ -280,9 +281,9 @@ describe('Mat4', function () { }); - describe('#getY()', function () { + describe('#getY()', () => { - it('gets y axis from a matrix', function () { + it('gets y axis from a matrix', () => { const m = new Mat4(); m.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const axis = m.getY(); @@ -291,7 +292,7 @@ describe('Mat4', function () { expect(axis.z).to.equal(6); }); - it('gets y axis from a matrix (no allocation)', function () { + it('gets y axis from a matrix (no allocation)', () => { const m = new Mat4(); m.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const axis = new Vec3(); @@ -303,9 +304,9 @@ describe('Mat4', function () { }); - describe('#getZ()', function () { + describe('#getZ()', () => { - it('gets z axis from a matrix', function () { + it('gets z axis from a matrix', () => { const m = new Mat4(); m.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const axis = m.getZ(); @@ -314,7 +315,7 @@ describe('Mat4', function () { expect(axis.z).to.equal(10); }); - it('gets z axis from a matrix (no allocation)', function () { + it('gets z axis from a matrix (no allocation)', () => { const m = new Mat4(); m.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); const axis = new Vec3(); @@ -326,15 +327,15 @@ describe('Mat4', function () { }); - describe('#invert()', function () { + describe('#invert()', () => { - it('inverts an identity matrix to the identity matrix', function () { + it('inverts an identity matrix to the identity matrix', () => { const m = new Mat4(); m.invert(); expect(m.isIdentity()).to.be.true; }); - it('inverts a translation matrix to the inverse translation matrix', function () { + it('inverts a translation matrix to the inverse translation matrix', () => { const m = new Mat4(); m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]); m.invert(); @@ -343,7 +344,7 @@ describe('Mat4', function () { expect(m.data).to.deep.equal(new Float32Array(result)); }); - it('inverts a translation matrix to the inverse translation matrix given a source matrix', function () { + it('inverts a translation matrix to the inverse translation matrix given a source matrix', () => { const m = new Mat4(); m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]); @@ -354,21 +355,21 @@ describe('Mat4', function () { expect(n.data).to.deep.equal(new Float32Array(result)); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.invert()).to.equal(m); }); }); - describe('#isIdentity()', function () { + describe('#isIdentity()', () => { - it('returns true for an identity matrix', function () { + it('returns true for an identity matrix', () => { const m = new Mat4(); expect(m.isIdentity()).to.be.true; }); - it('returns false for a non-identity matrix', function () { + it('returns false for a non-identity matrix', () => { const m = new Mat4(); m.set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); expect(m.isIdentity()).to.be.false; @@ -376,16 +377,16 @@ describe('Mat4', function () { }); - describe('#mul()', function () { + describe('#mul()', () => { - it('sets the identity when multiplying the identity by the identity (I * I = I)', function () { + it('sets the identity when multiplying the identity by the identity (I * I = I)', () => { const m1 = new Mat4(); const m2 = new Mat4(); m1.mul(m2); expect(m1.isIdentity()).to.be.true; }); - it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', function () { + it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', () => { const m1 = new Mat4(); const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; m1.set(data); @@ -394,7 +395,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(data)); }); - it('sets a matrix to the right hand side when left hand side is identity ( I * A = A )', function () { + it('sets a matrix to the right hand side when left hand side is identity ( I * A = A )', () => { const m1 = new Mat4(); const m2 = new Mat4(); const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; @@ -403,7 +404,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(data)); }); - it('multiplies an arbitrary matrix with another in place', function () { + it('multiplies an arbitrary matrix with another in place', () => { const m1 = new Mat4(); m1.set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); const m2 = new Mat4(); @@ -413,7 +414,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(result)); }); - it('returns this', function () { + it('returns this', () => { const m1 = new Mat4(); const m2 = new Mat4(); expect(m1.mul(m2)).to.equal(m1); @@ -421,9 +422,9 @@ describe('Mat4', function () { }); - describe('#mul2()', function () { + describe('#mul2()', () => { - it('sets the identity when multiplying the identity by the identity (I * I = I)', function () { + it('sets the identity when multiplying the identity by the identity (I * I = I)', () => { const m1 = new Mat4(); const m2 = new Mat4(); const m3 = new Mat4(); @@ -431,7 +432,7 @@ describe('Mat4', function () { expect(m1.isIdentity()).to.be.true; }); - it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', function () { + it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', () => { const m1 = new Mat4(); const m2 = new Mat4(); const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; @@ -441,7 +442,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(data)); }); - it('sets a matrix to the right hand side when left hand side is identity ( I * A = A )', function () { + it('sets a matrix to the right hand side when left hand side is identity ( I * A = A )', () => { const m1 = new Mat4(); const m2 = new Mat4(); const m3 = new Mat4(); @@ -451,7 +452,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(data)); }); - it('multiplies two arbitrary matrices together and writes result to a third', function () { + it('multiplies two arbitrary matrices together and writes result to a third', () => { const m1 = new Mat4(); const m2 = new Mat4(); m2.set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); @@ -462,7 +463,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(result)); }); - it('returns this', function () { + it('returns this', () => { const m1 = new Mat4(); const m2 = new Mat4(); const m3 = new Mat4(); @@ -471,9 +472,9 @@ describe('Mat4', function () { }); - describe('#mulAffine2()', function () { + describe('#mulAffine2()', () => { - it('sets the identity when multiplying the identity by the identity (I * I = I)', function () { + it('sets the identity when multiplying the identity by the identity (I * I = I)', () => { const m1 = new Mat4(); const m2 = new Mat4(); const m3 = new Mat4(); @@ -481,7 +482,7 @@ describe('Mat4', function () { expect(m1.isIdentity()).to.be.true; }); - it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', function () { + it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', () => { const m1 = new Mat4(); const m2 = new Mat4(); const data = [1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 0, 13, 14, 15, 1]; @@ -491,7 +492,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(data)); }); - it('sets a matrix to the right hand side when left hand side is identity ( I * A = A )', function () { + it('sets a matrix to the right hand side when left hand side is identity ( I * A = A )', () => { const m1 = new Mat4(); const m2 = new Mat4(); const m3 = new Mat4(); @@ -501,7 +502,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(data)); }); - it('multiplies two arbitrary matrices together and writes result to a third', function () { + it('multiplies two arbitrary matrices together and writes result to a third', () => { const m1 = new Mat4(); const m2 = new Mat4(); m2.set([1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 0, 13, 14, 15, 1]); @@ -512,7 +513,7 @@ describe('Mat4', function () { expect(m1.data).to.deep.equal(new Float32Array(result)); }); - it('returns this', function () { + it('returns this', () => { const m1 = new Mat4(); const m2 = new Mat4(); const m3 = new Mat4(); @@ -521,16 +522,16 @@ describe('Mat4', function () { }); - describe('#set()', function () { + describe('#set()', () => { - it('sets a matrix', function () { + it('sets a matrix', () => { const m = new Mat4(); const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; m.set(data); expect(m.data).to.deep.equal(new Float32Array(data)); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; expect(m.set(data)).to.equal(m); @@ -538,15 +539,15 @@ describe('Mat4', function () { }); - describe('#setFromAxisAngle()', function () { + describe('#setFromAxisAngle()', () => { - it('sets the identity matrix when passing a zero angle', function () { + it('sets the identity matrix when passing a zero angle', () => { const m = new Mat4(); m.setFromAxisAngle(Vec3.UP, 0); expect(m.isIdentity()).to.be.true; }); - it('sets an approximation of the identity matrix when passing a multiple of 360', function () { + it('sets an approximation of the identity matrix when passing a multiple of 360', () => { const m = new Mat4(); m.setFromAxisAngle(Vec3.UP, 360); expect(m.data[0]).to.be.closeTo(1, 0.001); @@ -567,7 +568,7 @@ describe('Mat4', function () { expect(m.data[15]).to.be.closeTo(1, 0.001); }); - it('set a rotation matrix of 90 around the x axis', function () { + it('set a rotation matrix of 90 around the x axis', () => { const m = new Mat4(); m.setFromAxisAngle(Vec3.RIGHT, 90); expect(m.data[0]).to.be.closeTo(1, 0.001); @@ -588,22 +589,22 @@ describe('Mat4', function () { expect(m.data[15]).to.be.closeTo(1, 0.001); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.setFromAxisAngle(Vec3.UP, 0)).to.equal(m); }); }); - describe('#setFromEulerAngles()', function () { + describe('#setFromEulerAngles()', () => { - it('sets the identity matrix when zeros are passed', function () { + it('sets the identity matrix when zeros are passed', () => { const m = new Mat4(); m.setFromEulerAngles(0, 0, 0); expect(m.isIdentity()).to.be.true; }); - it('set a rotation matrix from arbitrary euler angles', function () { + it('set a rotation matrix from arbitrary euler angles', () => { const m = new Mat4(); m.setFromEulerAngles(10, 20, 30); expect(m.data[0]).to.be.closeTo(0.813797652721405, 0.00001); @@ -624,16 +625,16 @@ describe('Mat4', function () { expect(m.data[15]).to.equal(1); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.setFromEulerAngles(0, 0, 0)).to.equal(m); }); }); - describe('#setIdentity()', function () { + describe('#setIdentity()', () => { - it('sets an identity matrix', function () { + it('sets an identity matrix', () => { const m = new Mat4(); m.setIdentity(); @@ -641,22 +642,22 @@ describe('Mat4', function () { expect(m.data).to.deep.equal(identity); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.setIdentity()).to.equal(m); }); }); - describe('#setLookAt()', function () { + describe('#setLookAt()', () => { - it('sets the identity matrix when eye is at origin looking down negative z', function () { + it('sets the identity matrix when eye is at origin looking down negative z', () => { const m = new Mat4(); m.setLookAt(Vec3.ZERO, Vec3.FORWARD, Vec3.UP); expect(m.isIdentity()).to.be.true; }); - it('sets matrix translation to eye position', function () { + it('sets matrix translation to eye position', () => { const m = new Mat4(); m.setLookAt(new Vec3(10, 20, 30), Vec3.FORWARD, Vec3.UP); expect(m.data[12]).to.equal(10); @@ -664,7 +665,7 @@ describe('Mat4', function () { expect(m.data[14]).to.equal(30); }); - it('sets matrix from arbitrary inputs', function () { + it('sets matrix from arbitrary inputs', () => { const m = new Mat4(); m.setLookAt(new Vec3(10, 20, 30), new Vec3(40, 50, 60), Vec3.RIGHT); expect(m.data[0]).to.equal(0); @@ -685,22 +686,22 @@ describe('Mat4', function () { expect(m.data[15]).to.equal(1); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.setLookAt(Vec3.ZERO, Vec3.FORWARD, Vec3.UP)).to.equal(m); }); }); - describe('#setOrtho()', function () { + describe('#setOrtho()', () => { - it('sets a normalized orthographic matrix', function () { + it('sets a normalized orthographic matrix', () => { const m = new Mat4(); m.setOrtho(-1, 1, -1, 1, 1, -1); expect(m.isIdentity()).to.be.true; }); - it('sets a non-normalized orthographic matrix', function () { + it('sets a non-normalized orthographic matrix', () => { const m = new Mat4(); m.setOrtho(-10, 10, -5, 5, 2, -2); expect(m.data[0]).to.be.closeTo(0.1, 0.001); @@ -723,9 +724,9 @@ describe('Mat4', function () { }); - describe('#setPerspective()', function () { + describe('#setPerspective()', () => { - it('sets a perspective matrix', function () { + it('sets a perspective matrix', () => { const m = new Mat4(); m.setPerspective(90, 1, 1, 10); expect(m.data[0]).to.equal(1); @@ -748,15 +749,15 @@ describe('Mat4', function () { }); - describe('#setScale()', function () { + describe('#setScale()', () => { - it('sets an identity matrix when ones are passed in', function () { + it('sets an identity matrix when ones are passed in', () => { const m = new Mat4(); m.setScale(1, 1, 1); expect(m.isIdentity()).to.be.true; }); - it('sets a scale matrix', function () { + it('sets a scale matrix', () => { const m = new Mat4(); m.setScale(10, 20, 30); @@ -764,22 +765,22 @@ describe('Mat4', function () { expect(m.data).to.deep.equal(result); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.setScale(1, 2, 3)).to.equal(m); }); }); - describe('#setTranslate()', function () { + describe('#setTranslate()', () => { - it('sets an identity matrix when zeros are passed in', function () { + it('sets an identity matrix when zeros are passed in', () => { const m = new Mat4(); m.setTranslate(0, 0, 0); expect(m.isIdentity()).to.be.true; }); - it('sets a translation matrix', function () { + it('sets a translation matrix', () => { const m = new Mat4(); m.setTranslate(1, 2, 3); @@ -787,22 +788,22 @@ describe('Mat4', function () { expect(m.data).to.deep.equal(result); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.setTranslate(1, 2, 3)).to.equal(m); }); }); - describe('#setTRS()', function () { + describe('#setTRS()', () => { - it('sets a matrix from identity translation, rotation and scale', function () { + it('sets a matrix from identity translation, rotation and scale', () => { const m = new Mat4(); m.setTRS(Vec3.ZERO, Quat.IDENTITY, Vec3.ONE); expect(m.equals(Mat4.IDENTITY)).to.be.true; }); - it('sets a matrix from translation, rotation and scale', function () { + it('sets a matrix from translation, rotation and scale', () => { const m = new Mat4(); const t = new Vec3(1, 2, 3); const r = new Quat().setFromEulerAngles(10, 20, 30); @@ -826,32 +827,32 @@ describe('Mat4', function () { expect(m.data[15]).to.equal(1); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.setTRS(Vec3.ZERO, Quat.IDENTITY, Vec3.ONE)).to.equal(m); }); }); - describe('#toString()', function () { + describe('#toString()', () => { - it('returns a string representation of a matrix', function () { + it('returns a string representation of a matrix', () => { const m = new Mat4(); expect(m.toString()).to.equal('[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]'); }); }); - describe('#transformPoint()', function () { + describe('#transformPoint()', () => { - it('leaves point unchanged when transforming by the identity matrix', function () { + it('leaves point unchanged when transforming by the identity matrix', () => { const p = new Vec3(1, 2, 3); const m = new Mat4(); const r = m.transformPoint(p); expect(p.equals(r)).to.be.true; }); - it('leaves point unchanged when transforming by the identity matrix (no allocation)', function () { + it('leaves point unchanged when transforming by the identity matrix (no allocation)', () => { const p = new Vec3(1, 2, 3); const m = new Mat4(); const r = new Vec3(); @@ -859,7 +860,7 @@ describe('Mat4', function () { expect(p.equals(r)).to.be.true; }); - it('transforms a point by a 90 degree rotation around the z axis', function () { + it('transforms a point by a 90 degree rotation around the z axis', () => { const p = new Vec3(1, 0, 0); const m = new Mat4(); const r = new Vec3(); @@ -872,7 +873,7 @@ describe('Mat4', function () { expect(r.z).to.be.closeTo(0, 0.00001); }); - it('transforms a point by a 90 degree rotation around the z axis (input and output vectors are the same)', function () { + it('transforms a point by a 90 degree rotation around the z axis (input and output vectors are the same)', () => { const p = new Vec3(1, 0, 0); const m = new Mat4(); @@ -884,7 +885,7 @@ describe('Mat4', function () { expect(p.z).to.be.closeTo(0, 0.00001); }); - it('takes translation component of a matrix into account', function () { + it('takes translation component of a matrix into account', () => { const p = new Vec3(1, 2, 3); const m = new Mat4(); m.setTranslate(10, 20, 30); @@ -896,16 +897,16 @@ describe('Mat4', function () { }); - describe('#transformVec4()', function () { + describe('#transformVec4()', () => { - it('leaves vector unchanged when transforming by the identity matrix', function () { + it('leaves vector unchanged when transforming by the identity matrix', () => { const v = new Vec4(1, 2, 3, 4); const m = new Mat4(); const r = m.transformVec4(v); expect(v.equals(r)).to.be.true; }); - it('leaves vector unchanged when transforming by the identity matrix (no allocation)', function () { + it('leaves vector unchanged when transforming by the identity matrix (no allocation)', () => { const v = new Vec4(1, 2, 3, 4); const m = new Mat4(); const r = new Vec4(); @@ -913,7 +914,7 @@ describe('Mat4', function () { expect(v.equals(r)).to.be.true; }); - it('transforms a vector by a 90 degree rotation around the z axis', function () { + it('transforms a vector by a 90 degree rotation around the z axis', () => { const v = new Vec4(1, 0, 0, 0); const m = new Mat4(); const r = new Vec4(); @@ -927,7 +928,7 @@ describe('Mat4', function () { expect(r.w).to.equal(0); }); - it('transforms a vector by a 90 degree rotation around the z axis (input and output vectors are the same)', function () { + it('transforms a vector by a 90 degree rotation around the z axis (input and output vectors are the same)', () => { const v = new Vec4(1, 0, 0, 0); const m = new Mat4(); @@ -942,16 +943,16 @@ describe('Mat4', function () { }); - describe('#transformVector()', function () { + describe('#transformVector()', () => { - it('leaves vector unchanged when transforming by the identity matrix', function () { + it('leaves vector unchanged when transforming by the identity matrix', () => { const v = new Vec3(1, 2, 3); const m = new Mat4(); const r = m.transformVector(v); expect(v.equals(r)).to.be.true; }); - it('leaves vector unchanged when transforming by the identity matrix (no allocation)', function () { + it('leaves vector unchanged when transforming by the identity matrix (no allocation)', () => { const v = new Vec3(1, 2, 3); const m = new Mat4(); const r = new Vec3(); @@ -959,7 +960,7 @@ describe('Mat4', function () { expect(v.equals(r)).to.be.true; }); - it('transforms a vector by a 90 degree rotation around the z axis', function () { + it('transforms a vector by a 90 degree rotation around the z axis', () => { const v = new Vec3(1, 0, 0); const m = new Mat4(); const r = new Vec3(); @@ -972,7 +973,7 @@ describe('Mat4', function () { expect(r.z).to.be.closeTo(0, 0.00001); }); - it('transforms a vector by a 90 degree rotation around the z axis (input and output vectors are the same)', function () { + it('transforms a vector by a 90 degree rotation around the z axis (input and output vectors are the same)', () => { const v = new Vec3(1, 0, 0); const m = new Mat4(); @@ -984,7 +985,7 @@ describe('Mat4', function () { expect(v.z).to.be.closeTo(0, 0.00001); }); - it('ignores the translation component of a matrix', function () { + it('ignores the translation component of a matrix', () => { const v = new Vec3(1, 2, 3); const m = new Mat4(); m.setTranslate(10, 20, 30); @@ -994,15 +995,15 @@ describe('Mat4', function () { }); - describe('#transpose()', function () { + describe('#transpose()', () => { - it('transposes the identity matrix to the identity matrix', function () { + it('transposes the identity matrix to the identity matrix', () => { const m = new Mat4(); m.transpose(); expect(m.isIdentity()).to.be.true; }); - it('flips a matrix along its top-left to bottom-right diagonal', function () { + it('flips a matrix along its top-left to bottom-right diagonal', () => { const m = new Mat4(); m.set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); m.transpose(); @@ -1010,7 +1011,7 @@ describe('Mat4', function () { expect(m.data).to.deep.equal(new Float32Array(result)); }); - it('flips a matrix along its top-left to bottom-right diagonal given a source matrix', function () { + it('flips a matrix along its top-left to bottom-right diagonal given a source matrix', () => { const m = new Mat4(); m.set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); @@ -1021,7 +1022,7 @@ describe('Mat4', function () { expect(n.data).to.deep.equal(new Float32Array(result)); }); - it('returns this', function () { + it('returns this', () => { const m = new Mat4(); expect(m.transpose()).to.equal(m); }); diff --git a/test/core/math/math.test.mjs b/test/core/math/math.test.mjs index 69a9647ebb5..b7b3399e46c 100644 --- a/test/core/math/math.test.mjs +++ b/test/core/math/math.test.mjs @@ -1,119 +1,120 @@ +import { expect } from 'chai'; + import { math } from '../../../src/core/math/math.js'; -import { expect } from 'chai'; -describe('math', function () { +describe('math', () => { - describe('#DEG_TO_RAD', function () { + describe('#DEG_TO_RAD', () => { - it('converts degrees to radians', function () { + it('converts degrees to radians', () => { const deg = 180; expect(deg * math.DEG_TO_RAD).to.equal(Math.PI); }); }); - describe('#RAD_TO_DEG', function () { + describe('#RAD_TO_DEG', () => { - it('converts radians to degrees', function () { + it('converts radians to degrees', () => { const rad = Math.PI; expect(rad * math.RAD_TO_DEG).to.equal(180); }); }); - describe('#between', function () { + describe('#between', () => { - it('returns true if value is between min and max inclusive', function () { + it('returns true if value is between min and max inclusive', () => { expect(math.between(0, 0, 1, true)).to.be.true; expect(math.between(0.5, 0, 1, true)).to.be.true; expect(math.between(1, 0, 1, true)).to.be.true; }); - it('returns false if value is not between min and max inclusive', function () { + it('returns false if value is not between min and max inclusive', () => { expect(math.between(-1, 0, 1, true)).to.be.false; expect(math.between(2, 0, 1, true)).to.be.false; }); - it('returns false if value is between min and max exclusive', function () { + it('returns false if value is between min and max exclusive', () => { expect(math.between(0, 0, 1, false)).to.be.false; expect(math.between(1, 0, 1, false)).to.be.false; }); - it('returns false if value is not between min and max exclusive', function () { + it('returns false if value is not between min and max exclusive', () => { expect(math.between(-1, 0, 1, false)).to.be.false; expect(math.between(2, 0, 1, false)).to.be.false; }); }); - describe('#bytesToInt24', function () { + describe('#bytesToInt24', () => { - it('packs 3 unsigned bytes into a 24-bit unsigned int', function () { + it('packs 3 unsigned bytes into a 24-bit unsigned int', () => { const uint24 = math.bytesToInt24(0xaa, 0xbb, 0xcc); expect(uint24).to.equal(0xaabbcc); }); - it('packs an array of 3 unsigned bytes into a 24-bit unsigned int', function () { + it('packs an array of 3 unsigned bytes into a 24-bit unsigned int', () => { const uint24 = math.bytesToInt24([0xaa, 0xbb, 0xcc]); expect(uint24).to.equal(0xaabbcc); }); - it('returns 0 when all supplied bytes are 0', function () { + it('returns 0 when all supplied bytes are 0', () => { const uint24 = math.bytesToInt24(0, 0, 0); expect(uint24).to.equal(0); }); - it('returns 2 ^ 24 - 1 when all supplied bytes are 255', function () { + it('returns 2 ^ 24 - 1 when all supplied bytes are 255', () => { const uint24 = math.bytesToInt24(255, 255, 255); expect(uint24).to.equal(Math.pow(2, 24) - 1); }); }); - describe('#bytesToInt32', function () { + describe('#bytesToInt32', () => { - it('packs 4 unsigned bytes into a 32-bit unsigned int', function () { + it('packs 4 unsigned bytes into a 32-bit unsigned int', () => { const uint32 = math.bytesToInt32(0xaa, 0xbb, 0xcc, 0xdd); expect(uint32).to.equal(0xaabbccdd); }); - it('packs an array of 4 unsigned bytes into a 32-bit unsigned int', function () { + it('packs an array of 4 unsigned bytes into a 32-bit unsigned int', () => { const uint32 = math.bytesToInt32([0xaa, 0xbb, 0xcc, 0xdd]); expect(uint32).to.equal(0xaabbccdd); }); - it('returns 0 when all supplied bytes are 0', function () { + it('returns 0 when all supplied bytes are 0', () => { const uint32 = math.bytesToInt32(0, 0, 0, 0); expect(uint32).to.equal(0); }); - it('returns 2 ^ 32 - 1 when all supplied bytes are 255', function () { + it('returns 2 ^ 32 - 1 when all supplied bytes are 255', () => { const uint32 = math.bytesToInt32(255, 255, 255, 255); expect(uint32).to.equal(Math.pow(2, 32) - 1); }); }); - describe('#clamp', function () { + describe('#clamp', () => { - it('returns the value when it is between min and max', function () { + it('returns the value when it is between min and max', () => { expect(math.clamp(5, 0, 10)).to.equal(5); }); - it('returns the minimum value when it is less than min', function () { + it('returns the minimum value when it is less than min', () => { expect(math.clamp(-5, 0, 10)).to.equal(0); }); - it('returns the maximum value when it is greater than max', function () { + it('returns the maximum value when it is greater than max', () => { expect(math.clamp(15, 0, 10)).to.equal(10); }); }); - describe('#intToBytes24', function () { + describe('#intToBytes24', () => { - it('converts an integer to a 3-element byte array', function () { + it('converts an integer to a 3-element byte array', () => { const i = 0x112233; const b = math.intToBytes24(i); expect(b[0]).to.equal(0x11); @@ -123,9 +124,9 @@ describe('math', function () { }); - describe('#intToBytes32', function () { + describe('#intToBytes32', () => { - it('converts an integer to a 4-element byte array', function () { + it('converts an integer to a 4-element byte array', () => { const i = 0x11223344; const b = math.intToBytes32(i); expect(b[0]).to.equal(0x11); @@ -136,57 +137,57 @@ describe('math', function () { }); - describe('#lerp', function () { + describe('#lerp', () => { - it('returns a when alpha is 0', function () { + it('returns a when alpha is 0', () => { expect(math.lerp(0, 1, 0)).to.equal(0); }); - it('returns b when alpha is 1', function () { + it('returns b when alpha is 1', () => { expect(math.lerp(0, 1, 1)).to.equal(1); }); - it('returns a + alpha * (b - a) when alpha is 0.5', function () { + it('returns a + alpha * (b - a) when alpha is 0.5', () => { expect(math.lerp(0, 1, 0.5)).to.equal(0.5); }); }); - describe('#lerpAngle', function () { + describe('#lerpAngle', () => { - it('returns 0 when a is 0 and b is 360 and alpha is 0', function () { + it('returns 0 when a is 0 and b is 360 and alpha is 0', () => { expect(math.lerpAngle(0, 360, 0)).to.equal(0); }); - it('returns 0 when a is 0 and b is 360 and alpha is 0.5', function () { + it('returns 0 when a is 0 and b is 360 and alpha is 0.5', () => { expect(math.lerpAngle(0, 360, 0.5)).to.equal(0); }); - it('returns 0 when a is 0 and b is 360 and alpha is 1', function () { + it('returns 0 when a is 0 and b is 360 and alpha is 1', () => { expect(math.lerpAngle(0, 360, 1)).to.equal(0); }); - it('returns 0 when a is -90 and b is 90 and alpha is 0.5', function () { + it('returns 0 when a is -90 and b is 90 and alpha is 0.5', () => { expect(math.lerpAngle(-90, 90, 0.5)).to.equal(0); }); - it('returns 180 when a is 90 and b is2790 and alpha is 0.5', function () { + it('returns 180 when a is 90 and b is2790 and alpha is 0.5', () => { expect(math.lerpAngle(90, 270, 0.5)).to.equal(180); }); - it('crosses the 360 to 0 degree boundary correctly (anticlockwise)', function () { + it('crosses the 360 to 0 degree boundary correctly (anticlockwise)', () => { expect(math.lerpAngle(10, 350, 0.75)).to.equal(-5); }); - it('crosses the 360 to 0 degree boundary correctly (clockwise)', function () { + it('crosses the 360 to 0 degree boundary correctly (clockwise)', () => { expect(math.lerpAngle(350, 10, 0.75)).to.equal(365); }); }); - describe('#nextPowerOfTwo', function () { + describe('#nextPowerOfTwo', () => { - it('returns the next power of two', function () { + it('returns the next power of two', () => { expect(math.nextPowerOfTwo(0)).to.equal(0); expect(math.nextPowerOfTwo(1)).to.equal(1); expect(math.nextPowerOfTwo(2)).to.equal(2); @@ -201,9 +202,9 @@ describe('math', function () { }); - describe('#nearestPowerOfTwo', function () { + describe('#nearestPowerOfTwo', () => { - it('returns the nearest power of two', function () { + it('returns the nearest power of two', () => { expect(math.nearestPowerOfTwo(0)).to.equal(0); expect(math.nearestPowerOfTwo(1)).to.equal(1); expect(math.nearestPowerOfTwo(2)).to.equal(2); @@ -218,9 +219,9 @@ describe('math', function () { }); - describe('#powerOfTwo', function () { + describe('#powerOfTwo', () => { - it('returns true when the value is a power of two', function () { + it('returns true when the value is a power of two', () => { expect(math.powerOfTwo(1)).to.be.true; expect(math.powerOfTwo(2)).to.be.true; expect(math.powerOfTwo(4)).to.be.true; @@ -233,7 +234,7 @@ describe('math', function () { expect(math.powerOfTwo(512)).to.be.true; }); - it('returns false when the value is not a power of two', function () { + it('returns false when the value is not a power of two', () => { expect(math.powerOfTwo(0)).to.be.false; expect(math.powerOfTwo(3)).to.be.false; expect(math.powerOfTwo(5)).to.be.false; @@ -248,9 +249,9 @@ describe('math', function () { }); - describe('#random', function () { + describe('#random', () => { - it('returns a random number between 0 and 1', function () { + it('returns a random number between 0 and 1', () => { const r = math.random(100, 101); expect(r).to.be.at.least(100); expect(r).to.be.at.most(101); @@ -258,9 +259,9 @@ describe('math', function () { }); - describe('#roundUp', function () { + describe('#roundUp', () => { - it('rounds a number up to the nearest multiple', function () { + it('rounds a number up to the nearest multiple', () => { expect(math.roundUp(0, 2)).to.equal(0); expect(math.roundUp(0.5, 2)).to.equal(2); expect(math.roundUp(1, 2)).to.equal(2); @@ -272,7 +273,7 @@ describe('math', function () { expect(math.roundUp(4, 2)).to.equal(4); }); - it('returns number unchanged for multiples of 0', function () { + it('returns number unchanged for multiples of 0', () => { expect(math.roundUp(0, 0)).to.equal(0); expect(math.roundUp(0.5, 0)).to.equal(0.5); expect(math.roundUp(1, 0)).to.equal(1); @@ -286,33 +287,33 @@ describe('math', function () { }); - describe('#smootherstep', function () { + describe('#smootherstep', () => { - it('returns 0 when x equals min', function () { + it('returns 0 when x equals min', () => { expect(math.smootherstep(0, 10, 0)).to.equal(0); }); - it('returns 0.5 when x is midway between min and max', function () { + it('returns 0.5 when x is midway between min and max', () => { expect(math.smootherstep(0, 10, 5)).to.equal(0.5); }); - it('returns 1 when x equals max', function () { + it('returns 1 when x equals max', () => { expect(math.smootherstep(0, 10, 10)).to.equal(1); }); }); - describe('#smoothstep', function () { + describe('#smoothstep', () => { - it('returns 0 when x equals a', function () { + it('returns 0 when x equals a', () => { expect(math.smoothstep(0, 10, 0)).to.equal(0); }); - it('returns 0.5 when x is midway between a and b', function () { + it('returns 0.5 when x is midway between a and b', () => { expect(math.smoothstep(0, 10, 5)).to.equal(0.5); }); - it('returns 1 when x equals b', function () { + it('returns 1 when x equals b', () => { expect(math.smoothstep(0, 10, 10)).to.equal(1); }); diff --git a/test/core/math/quat.test.mjs b/test/core/math/quat.test.mjs index 4f57546131e..49992d9b394 100644 --- a/test/core/math/quat.test.mjs +++ b/test/core/math/quat.test.mjs @@ -1,14 +1,15 @@ +import { expect } from 'chai'; + import { Mat4 } from '../../../src/core/math/mat4.js'; import { Quat } from '../../../src/core/math/quat.js'; import { Vec3 } from '../../../src/core/math/vec3.js'; -import { expect } from 'chai'; -describe('Quat', function () { +describe('Quat', () => { - describe('#constructor()', function () { + describe('#constructor()', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const q = new Quat(); expect(q.x).to.equal(0); expect(q.y).to.equal(0); @@ -16,7 +17,7 @@ describe('Quat', function () { expect(q.w).to.equal(1); }); - it('supports number arguments', function () { + it('supports number arguments', () => { const q = new Quat(0.1, 0.2, 0.3, 0.4); expect(q.x).to.equal(0.1); expect(q.y).to.equal(0.2); @@ -24,7 +25,7 @@ describe('Quat', function () { expect(q.w).to.equal(0.4); }); - it('supports a 4 element array argument', function () { + it('supports a 4 element array argument', () => { const q = new Quat([0.1, 0.2, 0.3, 0.4]); expect(q.x).to.equal(0.1); expect(q.y).to.equal(0.2); @@ -34,9 +35,9 @@ describe('Quat', function () { }); - describe('#clone()', function () { + describe('#clone()', () => { - it('clones a quaternion', function () { + it('clones a quaternion', () => { const q1 = new Quat(0.1, 0.2, 0.3, 0.4); const q2 = q1.clone(); expect(q2).to.not.equal(q1); @@ -46,7 +47,7 @@ describe('Quat', function () { expect(q2.w).to.equal(0.4); }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserQuat extends Quat {} const a = new UserQuat(); const b = a.clone(); @@ -55,9 +56,9 @@ describe('Quat', function () { }); - describe('#copy()', function () { + describe('#copy()', () => { - it('copies a quaternion', function () { + it('copies a quaternion', () => { const q1 = new Quat(0.1, 0.2, 0.3, 0.4); const q2 = new Quat(); q2.copy(q1); @@ -68,7 +69,7 @@ describe('Quat', function () { expect(q2.w).to.equal(0.4); }); - it('returns this', function () { + it('returns this', () => { const q1 = new Quat(); const q2 = new Quat(); expect(q1.copy(q2)).to.equal(q1); @@ -76,26 +77,26 @@ describe('Quat', function () { }); - describe('#equals()', function () { + describe('#equals()', () => { - it('checks for equality of the same quaternion', function () { + it('checks for equality of the same quaternion', () => { const q = new Quat(0.1, 0.2, 0.3, 0.4); expect(q.equals(q)).to.be.true; }); - it('checks for equality of two different quaternions with the same values', function () { + it('checks for equality of two different quaternions with the same values', () => { const q1 = new Quat(0.1, 0.2, 0.3, 0.4); const q2 = new Quat(0.1, 0.2, 0.3, 0.4); expect(q1.equals(q2)).to.be.true; }); - it('checks for equality of two different quaternions with different values', function () { + it('checks for equality of two different quaternions with different values', () => { const q1 = new Quat(0.1, 0.2, 0.3, 0.4); const q2 = new Quat(0.5, 0.6, 0.7, 0.8); expect(q1.equals(q2)).to.be.false; }); - it('checks for equality of different quaternions that are close enough', function () { + it('checks for equality of different quaternions that are close enough', () => { const q1 = new Quat(0.1, 0.2, 0.3, 0.4); const q2 = new Quat(0.10000000000000001, 0.2, 0.3, 0.4); const epsilon = 0.000001; @@ -111,9 +112,9 @@ describe('Quat', function () { }); - describe('#getAxisAngle()', function () { + describe('#getAxisAngle()', () => { - it('returns the x axis and 0 angle for an identity quaternion', function () { + it('returns the x axis and 0 angle for an identity quaternion', () => { const q = new Quat(); const axis = new Vec3(); const angle = q.getAxisAngle(axis); @@ -123,7 +124,7 @@ describe('Quat', function () { expect(axis.z).to.equal(0); }); - it('returns what is set with setFromAxisAngle', function () { + it('returns what is set with setFromAxisAngle', () => { const q = new Quat(); q.setFromAxisAngle(Vec3.UP, Math.PI / 2); const axis = new Vec3(); @@ -136,9 +137,9 @@ describe('Quat', function () { }); - describe('#getEulerAngles()', function () { + describe('#getEulerAngles()', () => { - it('returns zeroes for an identity quaternion', function () { + it('returns zeroes for an identity quaternion', () => { const q = new Quat(); const eulers = q.getEulerAngles(); expect(eulers.x).to.equal(0); @@ -146,7 +147,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(0); }); - it('returns zeroes for an identity quaternion (no allocation)', function () { + it('returns zeroes for an identity quaternion (no allocation)', () => { const q = new Quat(); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -155,7 +156,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(0); }); - it('extracts a 180° turn around x axis', function () { + it('extracts a 180° turn around x axis', () => { const q = new Quat(1, 0, 0, 0); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -164,7 +165,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(0); }); - it('extracts a 180° turn around y axis', function () { + it('extracts a 180° turn around y axis', () => { const q = new Quat(0, 1, 0, 0); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -174,7 +175,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(180); }); - it('extracts a 180° turn around z axis', function () { + it('extracts a 180° turn around z axis', () => { const q = new Quat(0, 0, 1, 0); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -183,7 +184,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(180); }); - it('extracts a 90° turn around z axis', function () { + it('extracts a 90° turn around z axis', () => { const q = new Quat(Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -192,7 +193,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(0); }); - it('extracts a 90° turn around y axis', function () { + it('extracts a 90° turn around y axis', () => { const q = new Quat(0, Math.sqrt(0.5), 0, Math.sqrt(0.5)); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -201,7 +202,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(0); }); - it('extracts a 90° turn around z axis', function () { + it('extracts a 90° turn around z axis', () => { const q = new Quat(0, 0, Math.sqrt(0.5), Math.sqrt(0.5)); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -210,7 +211,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(90, 0.00001); }); - it('extracts a -90° turn around x axis', function () { + it('extracts a -90° turn around x axis', () => { const q = new Quat(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -219,7 +220,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(0); }); - it('extracts a -90° turn around y axis', function () { + it('extracts a -90° turn around y axis', () => { const q = new Quat(0, -Math.sqrt(0.5), 0, Math.sqrt(0.5)); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -228,7 +229,7 @@ describe('Quat', function () { expect(eulers.z).to.equal(0); }); - it('extracts a -90° turn around z axis', function () { + it('extracts a -90° turn around z axis', () => { const q = new Quat(0, 0, -Math.sqrt(0.5), Math.sqrt(0.5)); const eulers = new Vec3(); q.getEulerAngles(eulers); @@ -239,15 +240,15 @@ describe('Quat', function () { }); - describe('#invert()', function () { + describe('#invert()', () => { - it('leaves the identity quaternion unchanged', function () { + it('leaves the identity quaternion unchanged', () => { const q = new Quat(); q.invert(); expect(q.equals(Quat.IDENTITY)).to.be.true; }); - it('leaves the quaternion unchanged if applied twice', function () { + it('leaves the quaternion unchanged if applied twice', () => { const q = new Quat(); q.setFromEulerAngles(10, 20, 30); const original = q.clone(); @@ -256,51 +257,51 @@ describe('Quat', function () { expect(q.equals(original)).to.be.true; }); - it('returns this', function () { + it('returns this', () => { const q = new Quat(); expect(q.invert()).to.equal(q); }); }); - describe('#length()', function () { + describe('#length()', () => { - it('returns 1 for the identity quaternion', function () { + it('returns 1 for the identity quaternion', () => { const q = new Quat(); expect(q.length()).to.equal(1); }); - it('returns the correct length for a non-identity quaternion', function () { + it('returns the correct length for a non-identity quaternion', () => { const q = new Quat(1, 2, 3, 4); expect(q.length()).to.equal(Math.sqrt(30)); }); }); - describe('#lengthSq()', function () { + describe('#lengthSq()', () => { - it('returns 1 for the identity quaternion', function () { + it('returns 1 for the identity quaternion', () => { const q = new Quat(); expect(q.lengthSq()).to.equal(1); }); - it('returns the correct squared length for a non-identity quaternion', function () { + it('returns the correct squared length for a non-identity quaternion', () => { const q = new Quat(1, 2, 3, 4); expect(q.lengthSq()).to.equal(30); }); }); - describe('#mul()', function () { + describe('#mul()', () => { - it('sets the identity when multiplying the identity by the identity (I * I = I)', function () { + it('sets the identity when multiplying the identity by the identity (I * I = I)', () => { const q1 = new Quat(); const q2 = new Quat(); q1.mul(q2); expect(q1.equals(Quat.IDENTITY)).to.be.true; }); - it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', function () { + it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', () => { const q1 = new Quat(); q1.setFromEulerAngles(10, 20, 30); const q2 = new Quat(); @@ -311,7 +312,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(30, 0.00001); }); - it('sets a quaternion to the right hand side when left hand side is identity ( I * A = A )', function () { + it('sets a quaternion to the right hand side when left hand side is identity ( I * A = A )', () => { const q1 = new Quat(); const q2 = new Quat(); q2.setFromEulerAngles(10, 20, 30); @@ -322,7 +323,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(30, 0.00001); }); - it('multiplies an arbitrary quaternion with another in place', function () { + it('multiplies an arbitrary quaternion with another in place', () => { const q1 = new Quat(); q1.setFromEulerAngles(10, 20, 30); const q2 = new Quat(); @@ -334,7 +335,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(113.547040698283, 0.00001); }); - it('sets the identity quaternion when multiplying by the inverse', function () { + it('sets the identity quaternion when multiplying by the inverse', () => { const q1 = new Quat(); q1.setFromEulerAngles(10, 20, 30); const q2 = q1.clone().invert(); @@ -345,7 +346,7 @@ describe('Quat', function () { expect(q1.w).to.be.closeTo(1, 0.00001); }); - it('returns this', function () { + it('returns this', () => { const q1 = new Quat(); const q2 = new Quat(); expect(q1.mul(q2)).to.equal(q1); @@ -353,9 +354,9 @@ describe('Quat', function () { }); - describe('#mul2()', function () { + describe('#mul2()', () => { - it('sets the identity when multiplying the identity by the identity (I * I = I)', function () { + it('sets the identity when multiplying the identity by the identity (I * I = I)', () => { const q1 = new Quat(); const q2 = new Quat(); const q3 = new Quat(); @@ -363,7 +364,7 @@ describe('Quat', function () { expect(q1.equals(Quat.IDENTITY)).to.be.true; }); - it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', function () { + it('leaves matrix unchanged when multiplying by the identity ( A * I = A )', () => { const q1 = new Quat(); const q2 = new Quat(); q2.setFromEulerAngles(10, 20, 30); @@ -375,7 +376,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(30, 0.00001); }); - it('sets a quaternion to the right hand side when left hand side is identity ( I * A = A )', function () { + it('sets a quaternion to the right hand side when left hand side is identity ( I * A = A )', () => { const q1 = new Quat(); const q2 = new Quat(); const q3 = new Quat(); @@ -387,7 +388,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(30, 0.00001); }); - it('multiplies an arbitrary quaternion with another in place', function () { + it('multiplies an arbitrary quaternion with another in place', () => { const q1 = new Quat(); const q2 = new Quat(); q2.setFromEulerAngles(10, 20, 30); @@ -400,7 +401,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(113.547040698283, 0.00001); }); - it('sets the identity quaternion when multiplying by the inverse', function () { + it('sets the identity quaternion when multiplying by the inverse', () => { const q1 = new Quat(); const q2 = new Quat(); q2.setFromEulerAngles(10, 20, 30); @@ -412,7 +413,7 @@ describe('Quat', function () { expect(q1.w).to.be.closeTo(1, 0.00001); }); - it('returns this', function () { + it('returns this', () => { const q1 = new Quat(); const q2 = new Quat(); const q3 = new Quat(); @@ -421,30 +422,30 @@ describe('Quat', function () { }); - describe('#normalize()', function () { + describe('#normalize()', () => { - it('leaves the identity quaternion unchanged', function () { + it('leaves the identity quaternion unchanged', () => { const q = new Quat(); q.normalize(); expect(q.equals(Quat.IDENTITY)).to.be.true; }); - it('makes an arbitrary quaternion have length 1', function () { + it('makes an arbitrary quaternion have length 1', () => { const q = new Quat(1, 2, 3, 4); q.normalize(); expect(q.length()).to.be.closeTo(1, 0.00001); }); - it('returns this', function () { + it('returns this', () => { const q = new Quat(); expect(q.normalize()).to.equal(q); }); }); - describe('#set()', function () { + describe('#set()', () => { - it('sets the quaternion', function () { + it('sets the quaternion', () => { const q = new Quat(); q.set(0.1, 0.2, 0.3, 0.4); expect(q.x).to.equal(0.1); @@ -453,22 +454,22 @@ describe('Quat', function () { expect(q.w).to.equal(0.4); }); - it('returns this', function () { + it('returns this', () => { const q = new Quat(); expect(q.set(0.1, 0.2, 0.3, 0.4)).to.equal(q); }); }); - describe('#setFromAxisAngle()', function () { + describe('#setFromAxisAngle()', () => { - it('sets the identity quaternion when passing a zero angle', function () { + it('sets the identity quaternion when passing a zero angle', () => { const q = new Quat(); q.setFromAxisAngle(Vec3.UP, 0); expect(q.equals(Quat.IDENTITY)).to.be.true; }); - it('sets an approximation of the identity quaternion when passing a multiple of 360', function () { + it('sets an approximation of the identity quaternion when passing a multiple of 360', () => { const q = new Quat(); q.setFromAxisAngle(Vec3.UP, 720); expect(q.x).to.be.closeTo(0, 0.00001); @@ -477,7 +478,7 @@ describe('Quat', function () { expect(q.w).to.be.closeTo(1, 0.00001); }); - it('set a quaternion of 90 around the x axis', function () { + it('set a quaternion of 90 around the x axis', () => { const q = new Quat(); q.setFromAxisAngle(Vec3.RIGHT, 90); expect(q.x).to.be.closeTo(0.7071067811865475, 0.00001); @@ -486,14 +487,14 @@ describe('Quat', function () { expect(q.w).to.be.closeTo(0.7071067811865476, 0.00001); }); - it('returns this', function () { + it('returns this', () => { const q = new Quat(); expect(q.setFromAxisAngle(Vec3.UP, 0)).to.equal(q); }); }); - describe('#setFromEulerAngles()', function () { + describe('#setFromEulerAngles()', () => { [ [0, 0, 0], @@ -503,8 +504,8 @@ describe('Quat', function () { [0, 0, 0.3], [1, 2, 3], [10, 10, 0] - ].forEach(function ([x, y, z]) { - it('sets the quaternion from ' + x + '°, ' + y + '°, ' + z + '°', function () { + ].forEach(([x, y, z]) => { + it(`sets the quaternion from ${x}°, ${y}°, ${z}°`, () => { const q1 = new Quat(); const q2 = new Quat(); const q3 = new Quat(); @@ -527,16 +528,16 @@ describe('Quat', function () { }); }); - it('returns this', function () { + it('returns this', () => { const q = new Quat(); expect(q.setFromEulerAngles(0, 0, 0)).to.equal(q); }); }); - describe('#setFromMat4()', function () { + describe('#setFromMat4()', () => { - it('set the identity quaternion from an identity matrix', function () { + it('set the identity quaternion from an identity matrix', () => { const q = new Quat(); const m = new Mat4(); q.setFromMat4(m); @@ -569,7 +570,7 @@ describe('Quat', function () { return result; }; - it('set the quaternion from a non-identity matrix', function () { + it('set the quaternion from a non-identity matrix', () => { const q = new Quat(); const m = new Mat4(); m.setFromEulerAngles(10, 20, 30); @@ -580,14 +581,14 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(30, 0.00001); }); - it('converts rot180', function () { + it('converts rot180', () => { expect(quatToMatToQuat(1, 0, 0, 0)).to.be.true; expect(quatToMatToQuat(0, 1, 0, 0)).to.be.true; expect(quatToMatToQuat(0, 0, 1, 0)).to.be.true; expect(quatToMatToQuat(0, 0, 0, 1)).to.be.true; }); - it('converts rot180n', function () { + it('converts rot180n', () => { expect(quatToMatToQuat(-1, 0, 0, 0)).to.be.true; expect(quatToMatToQuat(-1e-20, -1, 0, 0)).to.be.true; expect(quatToMatToQuat(-1e-20, 0, -1, 0)).to.be.true; @@ -596,7 +597,7 @@ describe('Quat', function () { const s2 = 1 / Math.sqrt(2); - it('converts rot90', function () { + it('converts rot90', () => { expect(quatToMatToQuat(s2, s2, 0, 0)).to.be.true; expect(quatToMatToQuat(s2, -s2, 0, 0)).to.be.true; expect(quatToMatToQuat(s2, 0, s2, 0)).to.be.true; @@ -605,7 +606,7 @@ describe('Quat', function () { expect(quatToMatToQuat(s2, 0, 0, -s2)).to.be.true; }); - it('converts rot90n', function () { + it('converts rot90n', () => { expect(quatToMatToQuat(-s2, s2, 0, 0)).to.be.true; expect(quatToMatToQuat(-s2, -s2, 0, 0)).to.be.true; expect(quatToMatToQuat(-s2, 0, s2, 0)).to.be.true; @@ -614,7 +615,7 @@ describe('Quat', function () { expect(quatToMatToQuat(-s2, 0, 0, -s2)).to.be.true; }); - it('converts suit', function () { + it('converts suit', () => { const vals = [0.9999, -0.002, -0.999, 0.01, 0, 1]; vals.forEach((x) => { @@ -628,7 +629,7 @@ describe('Quat', function () { }); }); - it('returns this', function () { + it('returns this', () => { const q = new Quat(); const m = new Mat4(); expect(q.setFromMat4(m)).to.equal(q); @@ -636,9 +637,9 @@ describe('Quat', function () { }); - describe('#setFromDirections()', function () { + describe('#setFromDirections()', () => { - it('set the identity quaternion from equal directions', function () { + it('set the identity quaternion from equal directions', () => { const v1 = new Vec3(1, 0, 0); const v2 = new Vec3(1, 0, 0); @@ -653,7 +654,7 @@ describe('Quat', function () { expect(q2.equals(Quat.IDENTITY)).to.be.true; }); - it('set a quaternion from different directions', function () { + it('set a quaternion from different directions', () => { const v1 = new Vec3(1, 0, 0); const v2 = new Vec3(0, 1, 0); @@ -675,7 +676,7 @@ describe('Quat', function () { }); - it('returns this', function () { + it('returns this', () => { const q = new Quat(); const v1 = new Vec3(); const v2 = new Vec3(); @@ -684,9 +685,9 @@ describe('Quat', function () { }); - describe('#slerp()', function () { + describe('#slerp()', () => { - it('return first quaternion when alpha is 0', function () { + it('return first quaternion when alpha is 0', () => { const q1 = new Quat(); q1.setFromEulerAngles(10, 20, 30); const q2 = new Quat(); @@ -699,7 +700,7 @@ describe('Quat', function () { expect(q.w).to.be.closeTo(q1.w, 0.00001); }); - it('return second quaternion when alpha is 1', function () { + it('return second quaternion when alpha is 1', () => { const q1 = new Quat(); q1.setFromEulerAngles(10, 20, 30); const q2 = new Quat(); @@ -712,7 +713,7 @@ describe('Quat', function () { expect(q.w).to.be.closeTo(q2.w, 0.00001); }); - it('returns the correct quaternion when alpha is 0.5', function () { + it('returns the correct quaternion when alpha is 0.5', () => { const q1 = new Quat(); q1.setFromEulerAngles(0, 0, 10); const q2 = new Quat(); @@ -725,7 +726,7 @@ describe('Quat', function () { expect(eulers.z).to.be.closeTo(15, 0.00001); }); - it('returns this', function () { + it('returns this', () => { const q1 = new Quat(); const q2 = new Quat(); const q = new Quat(); @@ -734,25 +735,25 @@ describe('Quat', function () { }); - describe('#toString()', function () { + describe('#toString()', () => { - it('returns a string representation of the quaternion', function () { + it('returns a string representation of the quaternion', () => { const q = new Quat(0.1, 0.2, 0.3, 0.4); expect(q.toString()).to.equal('[0.1, 0.2, 0.3, 0.4]'); }); }); - describe('#transformVector()', function () { + describe('#transformVector()', () => { - it('leaves vector unchanged when transforming by the identity quaternion', function () { + it('leaves vector unchanged when transforming by the identity quaternion', () => { const v = new Vec3(1, 2, 3); const q = new Quat(); const r = q.transformVector(v); expect(v.equals(r)).to.be.true; }); - it('leaves vector unchanged when transforming by the identity quaternion (no allocation)', function () { + it('leaves vector unchanged when transforming by the identity quaternion (no allocation)', () => { const v = new Vec3(1, 2, 3); const q = new Quat(); const r = new Vec3(); @@ -760,7 +761,7 @@ describe('Quat', function () { expect(v.equals(r)).to.be.true; }); - it('transforms a vector by a 90 degree rotation around the z axis', function () { + it('transforms a vector by a 90 degree rotation around the z axis', () => { const v = new Vec3(1, 0, 0); const q = new Quat(); const r = new Vec3(); @@ -773,7 +774,7 @@ describe('Quat', function () { expect(r.z).to.be.closeTo(0, 0.00001); }); - it('transforms a vector by a 90 degree rotation around the z axis (input and output vectors are the same)', function () { + it('transforms a vector by a 90 degree rotation around the z axis (input and output vectors are the same)', () => { const v = new Vec3(1, 0, 0); const q = new Quat(); diff --git a/test/core/math/vec2.test.mjs b/test/core/math/vec2.test.mjs index 9aa91803b82..3fbfcd7856b 100644 --- a/test/core/math/vec2.test.mjs +++ b/test/core/math/vec2.test.mjs @@ -1,24 +1,25 @@ +import { expect } from 'chai'; + import { Vec2 } from '../../../src/core/math/vec2.js'; -import { expect } from 'chai'; -describe('Vec2', function () { +describe('Vec2', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const v = new Vec2(); expect(v.x).to.equal(0); expect(v.y).to.equal(0); }); - it('supports number arguments', function () { + it('supports number arguments', () => { const v = new Vec2(1, 2); expect(v.x).to.equal(1); expect(v.y).to.equal(2); }); - it('supports an array argument', function () { + it('supports an array argument', () => { const v = new Vec2([1, 2]); expect(v.x).to.equal(1); expect(v.y).to.equal(2); @@ -26,9 +27,9 @@ describe('Vec2', function () { }); - describe('#add', function () { + describe('#add', () => { - it('adds a vector to another in place', function () { + it('adds a vector to another in place', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); v1.add(v2); @@ -36,7 +37,7 @@ describe('Vec2', function () { expect(v1.y).to.equal(6); }); - it('adds a vector to itself in place', function () { + it('adds a vector to itself in place', () => { const v1 = new Vec2(1, 2); v1.add(v1); expect(v1.x).to.equal(2); @@ -45,9 +46,9 @@ describe('Vec2', function () { }); - describe('#add2', function () { + describe('#add2', () => { - it('adds two vectors together and writes result to a third vector', function () { + it('adds two vectors together and writes result to a third vector', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); const v3 = new Vec2(); @@ -56,7 +57,7 @@ describe('Vec2', function () { expect(v3.y).to.equal(6); }); - it('adds a vector to itself and writes result to itself', function () { + it('adds a vector to itself and writes result to itself', () => { const v1 = new Vec2(1, 2); v1.add2(v1, v1); expect(v1.x).to.equal(2); @@ -65,9 +66,9 @@ describe('Vec2', function () { }); - describe('#addScalar', function () { + describe('#addScalar', () => { - it('adds a scalar in place', function () { + it('adds a scalar in place', () => { const v = new Vec2(1, 2); v.addScalar(2); expect(v.x).to.equal(3); @@ -76,9 +77,9 @@ describe('Vec2', function () { }); - describe('#addScaled', function () { + describe('#addScaled', () => { - it('adds a scaled vector', function () { + it('adds a scaled vector', () => { const v = new Vec2(1, 2); v.addScaled(Vec2.UP, 2); expect(v.x).to.equal(1); @@ -87,16 +88,16 @@ describe('Vec2', function () { }); - describe('#ceil', function () { + describe('#ceil', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec2(1, 2); v.ceil(); expect(v.x).to.equal(1); expect(v.y).to.equal(2); }); - it('calculates the ceil of all components', function () { + it('calculates the ceil of all components', () => { const v = new Vec2(1.1, 2.2); v.ceil(); expect(v.x).to.equal(2); @@ -105,9 +106,9 @@ describe('Vec2', function () { }); - describe('#clone', function () { + describe('#clone', () => { - it('clones a vector', function () { + it('clones a vector', () => { const v1 = new Vec2(1, 2); const v2 = v1.clone(); expect(v2).to.be.instanceof(Vec2); @@ -115,7 +116,7 @@ describe('Vec2', function () { expect(v2.y).to.equal(2); }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserVec2 extends Vec2 {} const a = new UserVec2(); const b = a.clone(); @@ -124,9 +125,9 @@ describe('Vec2', function () { }); - describe('#copy', function () { + describe('#copy', () => { - it('copies a vector', function () { + it('copies a vector', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(); v2.copy(v1); @@ -136,9 +137,9 @@ describe('Vec2', function () { }); - describe('#cross', function () { + describe('#cross', () => { - it('calculates cross product of two vectors', function () { + it('calculates cross product of two vectors', () => { const v1 = new Vec2(1, 0); const v2 = new Vec2(0, 1); expect(v1.cross(v2)).to.equal(1); @@ -146,16 +147,16 @@ describe('Vec2', function () { }); - describe('#distance', function () { + describe('#distance', () => { - it('calculates the distance between two vectors', function () { + it('calculates the distance between two vectors', () => { const v1 = new Vec2(); const v2 = new Vec2(10, 0); const distance = v1.distance(v2); expect(distance).to.equal(10); }); - it('returns zero for the distance between the same vector', function () { + it('returns zero for the distance between the same vector', () => { const v1 = new Vec2(10, 0); const distance = v1.distance(v1); expect(distance).to.equal(0); @@ -163,9 +164,9 @@ describe('Vec2', function () { }); - describe('#div', function () { + describe('#div', () => { - it('divides a vector by another in place', function () { + it('divides a vector by another in place', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); v1.div(v2); @@ -173,7 +174,7 @@ describe('Vec2', function () { expect(v1.y).to.equal(0.5); }); - it('divides a vector by itself in place', function () { + it('divides a vector by itself in place', () => { const v1 = new Vec2(1, 2); v1.div(v1); expect(v1.x).to.equal(1); @@ -182,9 +183,9 @@ describe('Vec2', function () { }); - describe('#div2', function () { + describe('#div2', () => { - it('divides a vector by another vector and writes the result to a third vector', function () { + it('divides a vector by another vector and writes the result to a third vector', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); const v3 = new Vec2(); @@ -193,7 +194,7 @@ describe('Vec2', function () { expect(v3.y).to.equal(0.5); }); - it('divides a vector by itself and writes the result to itself', function () { + it('divides a vector by itself and writes the result to itself', () => { const v1 = new Vec2(1, 2); v1.div2(v1, v1); expect(v1.x).to.equal(1); @@ -202,9 +203,9 @@ describe('Vec2', function () { }); - describe('#divScalar', function () { + describe('#divScalar', () => { - it('divides a vector by a scalar in place', function () { + it('divides a vector by a scalar in place', () => { const v = new Vec2(1, 2); v.divScalar(2); expect(v.x).to.equal(0.5); @@ -213,21 +214,21 @@ describe('Vec2', function () { }); - describe('#dot', function () { + describe('#dot', () => { - it('calculates dot product of two arbitrary non-unit vectors', function () { + it('calculates dot product of two arbitrary non-unit vectors', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); expect(v1.dot(v2)).to.equal(11); }); - it('calculates dot product of two parallel unit vectors', function () { + it('calculates dot product of two parallel unit vectors', () => { const v1 = new Vec2(1, 0); const v2 = new Vec2(1, 0); expect(v1.dot(v2)).to.equal(1); }); - it('calculates dot product of two perpendicular unit vectors', function () { + it('calculates dot product of two perpendicular unit vectors', () => { const v1 = new Vec2(1, 0); const v2 = new Vec2(0, 1); expect(v1.dot(v2)).to.equal(0); @@ -235,26 +236,26 @@ describe('Vec2', function () { }); - describe('#equals', function () { + describe('#equals', () => { - it('checks for equality of the same vector', function () { + it('checks for equality of the same vector', () => { const v = new Vec2(1, 2); expect(v.equals(v)).to.be.true; }); - it('checks for equality of two different vectors with the same values', function () { + it('checks for equality of two different vectors with the same values', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(1, 2); expect(v1.equals(v2)).to.be.true; }); - it('checks for equality of two different vectors with different values', function () { + it('checks for equality of two different vectors with different values', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); expect(v1.equals(v2)).to.be.false; }); - it('checks for equality of different vectors that are close enough', function () { + it('checks for equality of different vectors that are close enough', () => { const v1 = new Vec2(0.1, 0.2); const v2 = new Vec2(0.10000000000000001, 0.2); const epsilon = 0.000001; @@ -270,16 +271,16 @@ describe('Vec2', function () { }); - describe('#floor', function () { + describe('#floor', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec2(1, 2); v.floor(); expect(v.x).to.equal(1); expect(v.y).to.equal(2); }); - it('rounds down floating point numbers', function () { + it('rounds down floating point numbers', () => { const v = new Vec2(1.1, 2.2); v.floor(); expect(v.x).to.equal(1); @@ -288,37 +289,37 @@ describe('Vec2', function () { }); - describe('#length', function () { + describe('#length', () => { - it('calculates the length of a zero length vector', function () { + it('calculates the length of a zero length vector', () => { const v = new Vec2(); expect(v.length()).to.equal(0); }); - it('calculates the length of a vector', function () { + it('calculates the length of a vector', () => { const v = new Vec2(3, 4); expect(v.length()).to.equal(5); }); }); - describe('#lengthSq', function () { + describe('#lengthSq', () => { - it('calculates the length squared of a zero length vector', function () { + it('calculates the length squared of a zero length vector', () => { const v = new Vec2(); expect(v.length()).to.equal(0); }); - it('calculates the length squared of a vector', function () { + it('calculates the length squared of a vector', () => { const v = new Vec2(3, 4); expect(v.lengthSq()).to.equal(25); }); }); - describe('#lerp', function () { + describe('#lerp', () => { - it('linearly interpolates between two vectors with alpha of 0', function () { + it('linearly interpolates between two vectors with alpha of 0', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); const v3 = new Vec2(); @@ -327,7 +328,7 @@ describe('Vec2', function () { expect(v3.y).to.equal(2); }); - it('linearly interpolates between two vectors with alpha of 0.5', function () { + it('linearly interpolates between two vectors with alpha of 0.5', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); const v3 = new Vec2(); @@ -336,7 +337,7 @@ describe('Vec2', function () { expect(v3.y).to.equal(3); }); - it('linearly interpolates between two vectors with alpha of 1', function () { + it('linearly interpolates between two vectors with alpha of 1', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); const v3 = new Vec2(); @@ -347,9 +348,9 @@ describe('Vec2', function () { }); - describe('#max', function () { + describe('#max', () => { - it('handles left hand larger than right hand', function () { + it('handles left hand larger than right hand', () => { const v1 = new Vec2(3, 4); const v2 = new Vec2(1, 2); v1.max(v2); @@ -357,7 +358,7 @@ describe('Vec2', function () { expect(v1.y).to.equal(4); }); - it('handles right hand larger than left hand', function () { + it('handles right hand larger than left hand', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); v1.max(v2); @@ -367,9 +368,9 @@ describe('Vec2', function () { }); - describe('#min', function () { + describe('#min', () => { - it('handles left hand larger than right hand', function () { + it('handles left hand larger than right hand', () => { const v1 = new Vec2(3, 4); const v2 = new Vec2(1, 2); v1.min(v2); @@ -377,7 +378,7 @@ describe('Vec2', function () { expect(v1.y).to.equal(2); }); - it('handles right hand larger than left hand', function () { + it('handles right hand larger than left hand', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); v1.min(v2); @@ -387,9 +388,9 @@ describe('Vec2', function () { }); - describe('#mul', function () { + describe('#mul', () => { - it('multiplies a vector by another in place', function () { + it('multiplies a vector by another in place', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); v1.mul(v2); @@ -397,7 +398,7 @@ describe('Vec2', function () { expect(v1.y).to.equal(8); }); - it('multiplies a vector by itself in place', function () { + it('multiplies a vector by itself in place', () => { const v1 = new Vec2(1, 2); v1.mul(v1); expect(v1.x).to.equal(1); @@ -406,9 +407,9 @@ describe('Vec2', function () { }); - describe('#mul2', function () { + describe('#mul2', () => { - it('multiplies a vector by another vector and writes the result to a third vector', function () { + it('multiplies a vector by another vector and writes the result to a third vector', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); const v3 = new Vec2(); @@ -417,7 +418,7 @@ describe('Vec2', function () { expect(v3.y).to.equal(8); }); - it('multiplies a vector by itself and writes the result to itself', function () { + it('multiplies a vector by itself and writes the result to itself', () => { const v1 = new Vec2(1, 2); v1.mul2(v1, v1); expect(v1.x).to.equal(1); @@ -426,9 +427,9 @@ describe('Vec2', function () { }); - describe('#mulScalar', function () { + describe('#mulScalar', () => { - it('multiplies a vector by a scalar in place', function () { + it('multiplies a vector by a scalar in place', () => { const v = new Vec2(1, 2); v.mulScalar(2); expect(v.x).to.equal(2); @@ -437,16 +438,16 @@ describe('Vec2', function () { }); - describe('#normalize', function () { + describe('#normalize', () => { - it('handles a zero length vector', function () { + it('handles a zero length vector', () => { const v = new Vec2(); v.normalize(); expect(v.x).to.equal(0); expect(v.y).to.equal(0); }); - it('handles a non-zero length vector', function () { + it('handles a non-zero length vector', () => { const v = new Vec2(1, 2); v.normalize(); expect(v.length()).to.be.closeTo(1, 0.00001); @@ -454,16 +455,16 @@ describe('Vec2', function () { }); - describe('#round', function () { + describe('#round', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec2(1, 2); v.round(); expect(v.x).to.equal(1); expect(v.y).to.equal(2); }); - it('rounds floating point numbers to the nearest integer', function () { + it('rounds floating point numbers to the nearest integer', () => { const v = new Vec2(1.1, 2.2); v.round(); expect(v.x).to.equal(1); @@ -472,9 +473,9 @@ describe('Vec2', function () { }); - describe('#set', function () { + describe('#set', () => { - it('sets a vector to number values', function () { + it('sets a vector to number values', () => { const v = new Vec2(); v.set(1, 2); expect(v.x).to.equal(1); @@ -483,9 +484,9 @@ describe('Vec2', function () { }); - describe('#sub', function () { + describe('#sub', () => { - it('subtracts a vector from another in place', function () { + it('subtracts a vector from another in place', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); v1.sub(v2); @@ -493,7 +494,7 @@ describe('Vec2', function () { expect(v1.y).to.equal(-2); }); - it('subtracts a vector from itself in place', function () { + it('subtracts a vector from itself in place', () => { const v1 = new Vec2(1, 2); v1.sub(v1); expect(v1.x).to.equal(0); @@ -502,9 +503,9 @@ describe('Vec2', function () { }); - describe('#sub2', function () { + describe('#sub2', () => { - it('subtracts a vector from another vector and writes the result to a third vector', function () { + it('subtracts a vector from another vector and writes the result to a third vector', () => { const v1 = new Vec2(1, 2); const v2 = new Vec2(3, 4); const v3 = new Vec2(); @@ -513,7 +514,7 @@ describe('Vec2', function () { expect(v3.y).to.equal(-2); }); - it('subtracts a vector from itself and writes the result to itself', function () { + it('subtracts a vector from itself and writes the result to itself', () => { const v1 = new Vec2(1, 2); v1.sub2(v1, v1); expect(v1.x).to.equal(0); @@ -522,9 +523,9 @@ describe('Vec2', function () { }); - describe('#subScalar', function () { + describe('#subScalar', () => { - it('subtracts a scalar from a vector in place', function () { + it('subtracts a scalar from a vector in place', () => { const v = new Vec2(1, 2); v.subScalar(2); expect(v.x).to.equal(-1); @@ -533,9 +534,9 @@ describe('Vec2', function () { }); - describe('#toString', function () { + describe('#toString', () => { - it('returns a string representation of a vector', function () { + it('returns a string representation of a vector', () => { const v = new Vec2(1, 2); expect(v.toString()).to.equal('[1, 2]'); }); diff --git a/test/core/math/vec3.test.mjs b/test/core/math/vec3.test.mjs index 6678dbf3fe2..217b58999dd 100644 --- a/test/core/math/vec3.test.mjs +++ b/test/core/math/vec3.test.mjs @@ -1,26 +1,27 @@ +import { expect } from 'chai'; + import { Vec3 } from '../../../src/core/math/vec3.js'; -import { expect } from 'chai'; -describe('Vec3', function () { +describe('Vec3', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const v = new Vec3(); expect(v.x).to.equal(0); expect(v.y).to.equal(0); expect(v.z).to.equal(0); }); - it('supports number arguments', function () { + it('supports number arguments', () => { const v = new Vec3(1, 2, 3); expect(v.x).to.equal(1); expect(v.y).to.equal(2); expect(v.z).to.equal(3); }); - it('supports an array argument', function () { + it('supports an array argument', () => { const v = new Vec3([1, 2, 3]); expect(v.x).to.equal(1); expect(v.y).to.equal(2); @@ -29,9 +30,9 @@ describe('Vec3', function () { }); - describe('#add', function () { + describe('#add', () => { - it('adds a vector to another in place', function () { + it('adds a vector to another in place', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); v1.add(v2); @@ -40,7 +41,7 @@ describe('Vec3', function () { expect(v1.z).to.equal(9); }); - it('adds a vector to itself in place', function () { + it('adds a vector to itself in place', () => { const v1 = new Vec3(1, 2, 3); v1.add(v1); expect(v1.x).to.equal(2); @@ -50,9 +51,9 @@ describe('Vec3', function () { }); - describe('#add2', function () { + describe('#add2', () => { - it('adds two vectors together and writes result to a third vector', function () { + it('adds two vectors together and writes result to a third vector', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); const v3 = new Vec3(); @@ -62,7 +63,7 @@ describe('Vec3', function () { expect(v3.z).to.equal(9); }); - it('adds a vector to itself and writes result to itself', function () { + it('adds a vector to itself and writes result to itself', () => { const v1 = new Vec3(1, 2, 3); v1.add2(v1, v1); expect(v1.x).to.equal(2); @@ -72,9 +73,9 @@ describe('Vec3', function () { }); - describe('#addScalar', function () { + describe('#addScalar', () => { - it('adds a scalar in place', function () { + it('adds a scalar in place', () => { const v = new Vec3(1, 2, 3); v.addScalar(2); expect(v.x).to.equal(3); @@ -84,9 +85,9 @@ describe('Vec3', function () { }); - describe('#addScaled', function () { + describe('#addScaled', () => { - it('adds a scaled vector', function () { + it('adds a scaled vector', () => { const v = new Vec3(1, 2, 3); v.addScaled(Vec3.UP, 2); expect(v.x).to.equal(1); @@ -96,9 +97,9 @@ describe('Vec3', function () { }); - describe('#ceil', function () { + describe('#ceil', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec3(1, 2, 3); v.ceil(); expect(v.x).to.equal(1); @@ -106,7 +107,7 @@ describe('Vec3', function () { expect(v.z).to.equal(3); }); - it('calculates the ceil of all components', function () { + it('calculates the ceil of all components', () => { const v = new Vec3(1.1, 2.2, 3.3); v.ceil(); expect(v.x).to.equal(2); @@ -116,9 +117,9 @@ describe('Vec3', function () { }); - describe('#clone', function () { + describe('#clone', () => { - it('clones a vector', function () { + it('clones a vector', () => { const v1 = new Vec3(1, 2, 3); const v2 = v1.clone(); expect(v2).to.be.instanceof(Vec3); @@ -127,7 +128,7 @@ describe('Vec3', function () { expect(v2.z).to.equal(3); }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserVec3 extends Vec3 {} const a = new UserVec3(); const b = a.clone(); @@ -136,9 +137,9 @@ describe('Vec3', function () { }); - describe('#copy', function () { + describe('#copy', () => { - it('copies a vector', function () { + it('copies a vector', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(); v2.copy(v1); @@ -149,9 +150,9 @@ describe('Vec3', function () { }); - describe('#cross', function () { + describe('#cross', () => { - it('calculates cross product of two vectors', function () { + it('calculates cross product of two vectors', () => { const v1 = new Vec3(1, 0, 0); const v2 = new Vec3(0, 1, 0); const v3 = new Vec3(); @@ -161,7 +162,7 @@ describe('Vec3', function () { expect(v3.z).to.equal(1); }); - it('handles first vector also as the result', function () { + it('handles first vector also as the result', () => { const v1 = new Vec3(1, 0, 0); const v2 = new Vec3(0, 1, 0); v1.cross(v1, v2); @@ -170,7 +171,7 @@ describe('Vec3', function () { expect(v1.z).to.equal(1); }); - it('handles second vector also as the result', function () { + it('handles second vector also as the result', () => { const v1 = new Vec3(1, 0, 0); const v2 = new Vec3(0, 1, 0); v2.cross(v1, v2); @@ -181,16 +182,16 @@ describe('Vec3', function () { }); - describe('#distance', function () { + describe('#distance', () => { - it('calculates the distance between two vectors', function () { + it('calculates the distance between two vectors', () => { const v1 = new Vec3(); const v2 = new Vec3(10, 0, 0); const distance = v1.distance(v2); expect(distance).to.equal(10); }); - it('returns zero for the distance between the same vector', function () { + it('returns zero for the distance between the same vector', () => { const v1 = new Vec3(10, 0, 0); const distance = v1.distance(v1); expect(distance).to.equal(0); @@ -198,9 +199,9 @@ describe('Vec3', function () { }); - describe('#div', function () { + describe('#div', () => { - it('divides a vector by another in place', function () { + it('divides a vector by another in place', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); v1.div(v2); @@ -209,7 +210,7 @@ describe('Vec3', function () { expect(v1.z).to.equal(0.5); }); - it('divides a vector by itself in place', function () { + it('divides a vector by itself in place', () => { const v1 = new Vec3(1, 2, 3); v1.div(v1); expect(v1.x).to.equal(1); @@ -219,9 +220,9 @@ describe('Vec3', function () { }); - describe('#div2', function () { + describe('#div2', () => { - it('divides a vector by another vector and writes the result to a third vector', function () { + it('divides a vector by another vector and writes the result to a third vector', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); const v3 = new Vec3(); @@ -231,7 +232,7 @@ describe('Vec3', function () { expect(v3.z).to.equal(0.5); }); - it('divides a vector by itself and writes the result to itself', function () { + it('divides a vector by itself and writes the result to itself', () => { const v1 = new Vec3(1, 2, 3); v1.div2(v1, v1); expect(v1.x).to.equal(1); @@ -241,9 +242,9 @@ describe('Vec3', function () { }); - describe('#divScalar', function () { + describe('#divScalar', () => { - it('divides a vector by a scalar in place', function () { + it('divides a vector by a scalar in place', () => { const v = new Vec3(1, 2, 3); v.divScalar(2); expect(v.x).to.equal(0.5); @@ -253,21 +254,21 @@ describe('Vec3', function () { }); - describe('#dot', function () { + describe('#dot', () => { - it('calculates dot product of two arbitrary non-unit vectors', function () { + it('calculates dot product of two arbitrary non-unit vectors', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); expect(v1.dot(v2)).to.equal(32); }); - it('calculates dot product of two parallel unit vectors', function () { + it('calculates dot product of two parallel unit vectors', () => { const v1 = new Vec3(1, 0, 0); const v2 = new Vec3(1, 0, 0); expect(v1.dot(v2)).to.equal(1); }); - it('calculates dot product of two perpendicular unit vectors', function () { + it('calculates dot product of two perpendicular unit vectors', () => { const v1 = new Vec3(0, 1, 0); const v2 = new Vec3(0, 0, 1); expect(v1.dot(v2)).to.equal(0); @@ -275,26 +276,26 @@ describe('Vec3', function () { }); - describe('#equals', function () { + describe('#equals', () => { - it('checks for equality of the same vector', function () { + it('checks for equality of the same vector', () => { const v = new Vec3(1, 2, 3); expect(v.equals(v)).to.be.true; }); - it('checks for equality of two different vectors with the same values', function () { + it('checks for equality of two different vectors with the same values', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(1, 2, 3); expect(v1.equals(v2)).to.be.true; }); - it('checks for equality of two different vectors with different values', function () { + it('checks for equality of two different vectors with different values', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); expect(v1.equals(v2)).to.be.false; }); - it('checks for equality of different vectors that are close enough', function () { + it('checks for equality of different vectors that are close enough', () => { const v1 = new Vec3(0.1, 0.2, 0.3); const v2 = new Vec3(0.10000000000000001, 0.2, 0.3); const epsilon = 0.000001; @@ -310,9 +311,9 @@ describe('Vec3', function () { }); - describe('#floor', function () { + describe('#floor', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec3(1, 2, 3); v.floor(); expect(v.x).to.equal(1); @@ -320,7 +321,7 @@ describe('Vec3', function () { expect(v.z).to.equal(3); }); - it('rounds down floating point numbers', function () { + it('rounds down floating point numbers', () => { const v = new Vec3(1.1, 2.2, 3.3); v.floor(); expect(v.x).to.equal(1); @@ -330,37 +331,37 @@ describe('Vec3', function () { }); - describe('#length', function () { + describe('#length', () => { - it('calculates the length of a zero length vector', function () { + it('calculates the length of a zero length vector', () => { const v = new Vec3(); expect(v.length()).to.equal(0); }); - it('calculates the length of a vector', function () { + it('calculates the length of a vector', () => { const v = new Vec3(0, 3, 4); expect(v.length()).to.equal(5); }); }); - describe('#lengthSq', function () { + describe('#lengthSq', () => { - it('calculates the length squared of a zero length vector', function () { + it('calculates the length squared of a zero length vector', () => { const v = new Vec3(); expect(v.lengthSq()).to.equal(0); }); - it('calculates the length squared of a vector', function () { + it('calculates the length squared of a vector', () => { const v = new Vec3(0, 3, 4); expect(v.lengthSq()).to.equal(25); }); }); - describe('#lerp', function () { + describe('#lerp', () => { - it('linearly interpolates between two vectors with alpha of 0', function () { + it('linearly interpolates between two vectors with alpha of 0', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); const v3 = new Vec3(); @@ -370,7 +371,7 @@ describe('Vec3', function () { expect(v3.z).to.equal(3); }); - it('linearly interpolates between two vectors with alpha of 0.5', function () { + it('linearly interpolates between two vectors with alpha of 0.5', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); const v3 = new Vec3(); @@ -380,7 +381,7 @@ describe('Vec3', function () { expect(v3.z).to.equal(4.5); }); - it('linearly interpolates between two vectors with alpha of 1', function () { + it('linearly interpolates between two vectors with alpha of 1', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); const v3 = new Vec3(); @@ -392,9 +393,9 @@ describe('Vec3', function () { }); - describe('#max', function () { + describe('#max', () => { - it('handles left hand larger than right hand', function () { + it('handles left hand larger than right hand', () => { const v1 = new Vec3(4, 5, 6); const v2 = new Vec3(1, 2, 3); v1.max(v2); @@ -403,7 +404,7 @@ describe('Vec3', function () { expect(v1.z).to.equal(6); }); - it('handles right hand larger than left hand', function () { + it('handles right hand larger than left hand', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); v1.max(v2); @@ -414,9 +415,9 @@ describe('Vec3', function () { }); - describe('#min', function () { + describe('#min', () => { - it('handles left hand larger than right hand', function () { + it('handles left hand larger than right hand', () => { const v1 = new Vec3(4, 5, 6); const v2 = new Vec3(1, 2, 3); v1.min(v2); @@ -425,7 +426,7 @@ describe('Vec3', function () { expect(v1.z).to.equal(3); }); - it('handles right hand larger than left hand', function () { + it('handles right hand larger than left hand', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); v1.min(v2); @@ -436,9 +437,9 @@ describe('Vec3', function () { }); - describe('#mul', function () { + describe('#mul', () => { - it('multiplies a vector by another in place', function () { + it('multiplies a vector by another in place', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); v1.mul(v2); @@ -447,7 +448,7 @@ describe('Vec3', function () { expect(v1.z).to.equal(18); }); - it('multiplies a vector by itself in place', function () { + it('multiplies a vector by itself in place', () => { const v1 = new Vec3(1, 2, 3); v1.mul(v1); expect(v1.x).to.equal(1); @@ -457,9 +458,9 @@ describe('Vec3', function () { }); - describe('#mul2', function () { + describe('#mul2', () => { - it('multiplies a vector by another vector and writes the result to a third vector', function () { + it('multiplies a vector by another vector and writes the result to a third vector', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); const v3 = new Vec3(); @@ -469,7 +470,7 @@ describe('Vec3', function () { expect(v3.z).to.equal(18); }); - it('multiplies a vector by itself and writes the result to itself', function () { + it('multiplies a vector by itself and writes the result to itself', () => { const v1 = new Vec3(1, 2, 3); v1.mul2(v1, v1); expect(v1.x).to.equal(1); @@ -479,9 +480,9 @@ describe('Vec3', function () { }); - describe('#mulScalar', function () { + describe('#mulScalar', () => { - it('multiplies a vector by a scalar in place', function () { + it('multiplies a vector by a scalar in place', () => { const v = new Vec3(1, 2, 3); v.mulScalar(2); expect(v.x).to.equal(2); @@ -491,9 +492,9 @@ describe('Vec3', function () { }); - describe('#normalize', function () { + describe('#normalize', () => { - it('handles a zero length vector', function () { + it('handles a zero length vector', () => { const v = new Vec3(); v.normalize(); expect(v.x).to.equal(0); @@ -501,7 +502,7 @@ describe('Vec3', function () { expect(v.z).to.equal(0); }); - it('handles a non-zero length vector', function () { + it('handles a non-zero length vector', () => { const v = new Vec3(1, 2, 3); v.normalize(); expect(v.length()).to.equal(1); @@ -509,9 +510,9 @@ describe('Vec3', function () { }); - describe('#project', function () { + describe('#project', () => { - it('projects a vector onto another vector', function () { + it('projects a vector onto another vector', () => { const v1 = new Vec3(5, 5, 5); const v2 = new Vec3(1, 0, 0); v1.project(v2); @@ -522,9 +523,9 @@ describe('Vec3', function () { }); - describe('#round', function () { + describe('#round', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec3(1, 2, 3); v.round(); expect(v.x).to.equal(1); @@ -532,7 +533,7 @@ describe('Vec3', function () { expect(v.z).to.equal(3); }); - it('rounds floating point numbers to the nearest integer', function () { + it('rounds floating point numbers to the nearest integer', () => { const v = new Vec3(1.1, 2.2, 3.3); v.round(); expect(v.x).to.equal(1); @@ -542,9 +543,9 @@ describe('Vec3', function () { }); - describe('#set', function () { + describe('#set', () => { - it('sets a vector to number values', function () { + it('sets a vector to number values', () => { const v = new Vec3(); v.set(1, 2, 3); expect(v.x).to.equal(1); @@ -554,9 +555,9 @@ describe('Vec3', function () { }); - describe('#sub', function () { + describe('#sub', () => { - it('subtracts a vector from another in place', function () { + it('subtracts a vector from another in place', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); v1.sub(v2); @@ -565,7 +566,7 @@ describe('Vec3', function () { expect(v1.z).to.equal(-3); }); - it('subtracts a vector from itself in place', function () { + it('subtracts a vector from itself in place', () => { const v1 = new Vec3(1, 2, 3); v1.sub(v1); expect(v1.x).to.equal(0); @@ -575,9 +576,9 @@ describe('Vec3', function () { }); - describe('#sub2', function () { + describe('#sub2', () => { - it('subtracts a vector from another vector and writes the result to a third vector', function () { + it('subtracts a vector from another vector and writes the result to a third vector', () => { const v1 = new Vec3(1, 2, 3); const v2 = new Vec3(4, 5, 6); const v3 = new Vec3(); @@ -587,7 +588,7 @@ describe('Vec3', function () { expect(v3.z).to.equal(-3); }); - it('subtracts a vector from itself and writes the result to itself', function () { + it('subtracts a vector from itself and writes the result to itself', () => { const v1 = new Vec3(1, 2, 3); v1.sub2(v1, v1); expect(v1.x).to.equal(0); @@ -597,9 +598,9 @@ describe('Vec3', function () { }); - describe('#subScalar', function () { + describe('#subScalar', () => { - it('subtracts a scalar from a vector in place', function () { + it('subtracts a scalar from a vector in place', () => { const v = new Vec3(1, 2, 3); v.subScalar(2); expect(v.x).to.equal(-1); @@ -609,9 +610,9 @@ describe('Vec3', function () { }); - describe('#toString', function () { + describe('#toString', () => { - it('returns a string representation of a vector', function () { + it('returns a string representation of a vector', () => { const v = new Vec3(1, 2, 3); expect(v.toString()).to.equal('[1, 2, 3]'); }); diff --git a/test/core/math/vec4.test.mjs b/test/core/math/vec4.test.mjs index 166ddbaae9f..9cc2fb79a48 100644 --- a/test/core/math/vec4.test.mjs +++ b/test/core/math/vec4.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { Vec4 } from '../../../src/core/math/vec4.js'; -import { expect } from 'chai'; -describe('Vec4', function () { +describe('Vec4', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const v = new Vec4(); expect(v.x).to.equal(0); expect(v.y).to.equal(0); @@ -14,7 +15,7 @@ describe('Vec4', function () { expect(v.w).to.equal(0); }); - it('supports number arguments', function () { + it('supports number arguments', () => { const v = new Vec4(1, 2, 3, 4); expect(v.x).to.equal(1); expect(v.y).to.equal(2); @@ -22,7 +23,7 @@ describe('Vec4', function () { expect(v.w).to.equal(4); }); - it('supports an array argument', function () { + it('supports an array argument', () => { const v = new Vec4([1, 2, 3, 4]); expect(v.x).to.equal(1); expect(v.y).to.equal(2); @@ -32,9 +33,9 @@ describe('Vec4', function () { }); - describe('#add', function () { + describe('#add', () => { - it('adds a vector to another in place', function () { + it('adds a vector to another in place', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); v1.add(v2); @@ -44,7 +45,7 @@ describe('Vec4', function () { expect(v1.w).to.equal(12); }); - it('adds a vector to itself in place', function () { + it('adds a vector to itself in place', () => { const v1 = new Vec4(1, 2, 3, 4); v1.add(v1); expect(v1.x).to.equal(2); @@ -55,9 +56,9 @@ describe('Vec4', function () { }); - describe('#add2', function () { + describe('#add2', () => { - it('adds two vectors together and writes result to a third vector', function () { + it('adds two vectors together and writes result to a third vector', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); const v3 = new Vec4(); @@ -68,7 +69,7 @@ describe('Vec4', function () { expect(v3.w).to.equal(12); }); - it('adds a vector to itself and writes result to itself', function () { + it('adds a vector to itself and writes result to itself', () => { const v1 = new Vec4(1, 2, 3, 4); v1.add2(v1, v1); expect(v1.x).to.equal(2); @@ -79,9 +80,9 @@ describe('Vec4', function () { }); - describe('#addScalar', function () { + describe('#addScalar', () => { - it('adds a scalar in place', function () { + it('adds a scalar in place', () => { const v = new Vec4(1, 2, 3, 4); v.addScalar(2); expect(v.x).to.equal(3); @@ -92,9 +93,9 @@ describe('Vec4', function () { }); - describe('#addScaled', function () { + describe('#addScaled', () => { - it('adds a scaled vector', function () { + it('adds a scaled vector', () => { const v = new Vec4(1, 2, 3, 4); v.addScaled(Vec4.ONE, 2); expect(v.x).to.equal(3); @@ -105,9 +106,9 @@ describe('Vec4', function () { }); - describe('#ceil', function () { + describe('#ceil', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec4(1, 2, 3, 4); v.ceil(); expect(v.x).to.equal(1); @@ -116,7 +117,7 @@ describe('Vec4', function () { expect(v.w).to.equal(4); }); - it('calculates the ceil of all components', function () { + it('calculates the ceil of all components', () => { const v = new Vec4(1.1, 2.2, 3.3, 4.4); v.ceil(); expect(v.x).to.equal(2); @@ -127,9 +128,9 @@ describe('Vec4', function () { }); - describe('#clone', function () { + describe('#clone', () => { - it('clones a vector', function () { + it('clones a vector', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = v1.clone(); expect(v2).to.be.instanceof(Vec4); @@ -139,7 +140,7 @@ describe('Vec4', function () { expect(v2.w).to.equal(4); }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserVec4 extends Vec4 {} const a = new UserVec4(); const b = a.clone(); @@ -148,9 +149,9 @@ describe('Vec4', function () { }); - describe('#copy', function () { + describe('#copy', () => { - it('copies a vector', function () { + it('copies a vector', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(); v2.copy(v1); @@ -162,9 +163,9 @@ describe('Vec4', function () { }); - describe('#div', function () { + describe('#div', () => { - it('divides a vector by another in place', function () { + it('divides a vector by another in place', () => { const v1 = new Vec4(12, 12, 12, 12); const v2 = new Vec4(4, 3, 2, 1); v1.div(v2); @@ -174,7 +175,7 @@ describe('Vec4', function () { expect(v1.w).to.equal(12); }); - it('divides a vector by itself in place', function () { + it('divides a vector by itself in place', () => { const v1 = new Vec4(12, 12, 12, 12); v1.div(v1); expect(v1.x).to.equal(1); @@ -185,9 +186,9 @@ describe('Vec4', function () { }); - describe('#div2', function () { + describe('#div2', () => { - it('divides a vector by another vector and writes the result to a third vector', function () { + it('divides a vector by another vector and writes the result to a third vector', () => { const v1 = new Vec4(12, 12, 12, 12); const v2 = new Vec4(4, 3, 2, 1); const v3 = new Vec4(); @@ -198,7 +199,7 @@ describe('Vec4', function () { expect(v3.w).to.equal(12); }); - it('divides a vector by itself and writes the result to itself', function () { + it('divides a vector by itself and writes the result to itself', () => { const v1 = new Vec4(12, 12, 12, 12); v1.div2(v1, v1); expect(v1.x).to.equal(1); @@ -209,9 +210,9 @@ describe('Vec4', function () { }); - describe('#divScalar', function () { + describe('#divScalar', () => { - it('divides a vector by a scalar in place', function () { + it('divides a vector by a scalar in place', () => { const v = new Vec4(1, 2, 3, 4); v.divScalar(2); expect(v.x).to.equal(0.5); @@ -222,23 +223,23 @@ describe('Vec4', function () { }); - describe('#dot', function () { + describe('#dot', () => { - it('calculates dot product of two arbitrary non-unit vectors', function () { + it('calculates dot product of two arbitrary non-unit vectors', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); const dot = v1.dot(v2); expect(dot).to.equal(70); }); - it('calculates dot product of two parallel unit vectors', function () { + it('calculates dot product of two parallel unit vectors', () => { const v1 = new Vec4(1, 0, 0, 0); const v2 = new Vec4(1, 0, 0, 0); const dot = v1.dot(v2); expect(dot).to.equal(1); }); - it('calculates dot product of two perpendicular unit vectors', function () { + it('calculates dot product of two perpendicular unit vectors', () => { const v1 = new Vec4(0, 1, 0, 0); const v2 = new Vec4(0, 0, 1, 0); expect(v1.dot(v2)).to.equal(0); @@ -246,26 +247,26 @@ describe('Vec4', function () { }); - describe('#equals', function () { + describe('#equals', () => { - it('checks for equality of the same vector', function () { + it('checks for equality of the same vector', () => { const v = new Vec4(1, 2, 3, 4); expect(v.equals(v)).to.be.true; }); - it('checks for equality of two different vectors with the same values', function () { + it('checks for equality of two different vectors with the same values', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(1, 2, 3, 4); expect(v1.equals(v2)).to.be.true; }); - it('checks for equality of two different vectors with different values', function () { + it('checks for equality of two different vectors with different values', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); expect(v1.equals(v2)).to.be.false; }); - it('checks for equality of different vectors that are close enough', function () { + it('checks for equality of different vectors that are close enough', () => { const v1 = new Vec4(0.1, 0.2, 0.3, 0.4); const v2 = new Vec4(0.10000000000000001, 0.2, 0.3, 0.4); const epsilon = 0.000001; @@ -281,9 +282,9 @@ describe('Vec4', function () { }); - describe('#floor', function () { + describe('#floor', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec4(1, 2, 3, 4); v.floor(); expect(v.x).to.equal(1); @@ -292,7 +293,7 @@ describe('Vec4', function () { expect(v.w).to.equal(4); }); - it('rounds down floating point numbers', function () { + it('rounds down floating point numbers', () => { const v = new Vec4(1.1, 2.2, 3.3, 4.4); v.floor(); expect(v.x).to.equal(1); @@ -303,37 +304,37 @@ describe('Vec4', function () { }); - describe('#length', function () { + describe('#length', () => { - it('calculates the length of a zero length vector', function () { + it('calculates the length of a zero length vector', () => { const v = new Vec4(); expect(v.length()).to.equal(0); }); - it('calculates the length of a vector', function () { + it('calculates the length of a vector', () => { const v = new Vec4(0, 3, 4, 0); expect(v.length()).to.equal(5); }); }); - describe('#lengthSq', function () { + describe('#lengthSq', () => { - it('calculates the length squared of a zero length vector', function () { + it('calculates the length squared of a zero length vector', () => { const v = new Vec4(); expect(v.length()).to.equal(0); }); - it('calculates the length squared of a vector', function () { + it('calculates the length squared of a vector', () => { const v = new Vec4(0, 3, 4, 0); expect(v.lengthSq()).to.equal(25); }); }); - describe('#lerp', function () { + describe('#lerp', () => { - it('linearly interpolates between two vectors with alpha of 0', function () { + it('linearly interpolates between two vectors with alpha of 0', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); const v3 = new Vec4(); @@ -344,7 +345,7 @@ describe('Vec4', function () { expect(v3.w).to.equal(4); }); - it('linearly interpolates between two vectors with alpha of 0.5', function () { + it('linearly interpolates between two vectors with alpha of 0.5', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); const v3 = new Vec4(); @@ -355,7 +356,7 @@ describe('Vec4', function () { expect(v3.w).to.equal(6); }); - it('linearly interpolates between two vectors with alpha of 1', function () { + it('linearly interpolates between two vectors with alpha of 1', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); const v3 = new Vec4(); @@ -368,9 +369,9 @@ describe('Vec4', function () { }); - describe('#max', function () { + describe('#max', () => { - it('handles left hand larger than right hand', function () { + it('handles left hand larger than right hand', () => { const v1 = new Vec4(5, 6, 7, 8); const v2 = new Vec4(1, 2, 3, 4); v1.max(v2); @@ -380,7 +381,7 @@ describe('Vec4', function () { expect(v1.w).to.equal(8); }); - it('handles right hand larger than left hand', function () { + it('handles right hand larger than left hand', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); v1.max(v2); @@ -392,9 +393,9 @@ describe('Vec4', function () { }); - describe('#min', function () { + describe('#min', () => { - it('handles left hand larger than right hand', function () { + it('handles left hand larger than right hand', () => { const v1 = new Vec4(5, 6, 7, 8); const v2 = new Vec4(1, 2, 3, 4); v1.min(v2); @@ -404,7 +405,7 @@ describe('Vec4', function () { expect(v1.w).to.equal(4); }); - it('handles right hand larger than left hand', function () { + it('handles right hand larger than left hand', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); v1.min(v2); @@ -416,9 +417,9 @@ describe('Vec4', function () { }); - describe('#mul', function () { + describe('#mul', () => { - it('multiplies a vector by another in place', function () { + it('multiplies a vector by another in place', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); v1.mul(v2); @@ -428,7 +429,7 @@ describe('Vec4', function () { expect(v1.w).to.equal(32); }); - it('multiplies a vector by itself in place', function () { + it('multiplies a vector by itself in place', () => { const v1 = new Vec4(1, 2, 3, 4); v1.mul(v1); expect(v1.x).to.equal(1); @@ -439,9 +440,9 @@ describe('Vec4', function () { }); - describe('#mul2', function () { + describe('#mul2', () => { - it('multiplies a vector by another vector and writes the result to a third vector', function () { + it('multiplies a vector by another vector and writes the result to a third vector', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); const v3 = new Vec4(); @@ -452,7 +453,7 @@ describe('Vec4', function () { expect(v3.w).to.equal(32); }); - it('multiplies a vector by itself and writes the result to itself', function () { + it('multiplies a vector by itself and writes the result to itself', () => { const v1 = new Vec4(1, 2, 3, 4); v1.mul2(v1, v1); expect(v1.x).to.equal(1); @@ -463,9 +464,9 @@ describe('Vec4', function () { }); - describe('#mulScalar', function () { + describe('#mulScalar', () => { - it('multiplies a vector by a scalar in place', function () { + it('multiplies a vector by a scalar in place', () => { const v = new Vec4(1, 2, 3, 4); v.mulScalar(2); expect(v.x).to.equal(2); @@ -476,9 +477,9 @@ describe('Vec4', function () { }); - describe('#normalize', function () { + describe('#normalize', () => { - it('handles a zero length vector', function () { + it('handles a zero length vector', () => { const v = new Vec4(); v.normalize(); expect(v.x).to.equal(0); @@ -487,7 +488,7 @@ describe('Vec4', function () { expect(v.w).to.equal(0); }); - it('handles a non-zero length vector', function () { + it('handles a non-zero length vector', () => { const v = new Vec4(1, 2, 3, 4); v.normalize(); expect(v.length()).to.be.closeTo(1, 0.00001); @@ -495,9 +496,9 @@ describe('Vec4', function () { }); - describe('#round', function () { + describe('#round', () => { - it('leaves integers unchanged', function () { + it('leaves integers unchanged', () => { const v = new Vec4(1, 2, 3, 4); v.round(); expect(v.x).to.equal(1); @@ -506,7 +507,7 @@ describe('Vec4', function () { expect(v.w).to.equal(4); }); - it('rounds floating point numbers to the nearest integer', function () { + it('rounds floating point numbers to the nearest integer', () => { const v = new Vec4(1.1, 2.2, 3.3, 4.4); v.round(); expect(v.x).to.equal(1); @@ -517,9 +518,9 @@ describe('Vec4', function () { }); - describe('#set', function () { + describe('#set', () => { - it('sets a vector to number values', function () { + it('sets a vector to number values', () => { const v = new Vec4(); v.set(1, 2, 3, 4); expect(v.x).to.equal(1); @@ -530,9 +531,9 @@ describe('Vec4', function () { }); - describe('#sub', function () { + describe('#sub', () => { - it('subtracts a vector from another in place', function () { + it('subtracts a vector from another in place', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); v1.sub(v2); @@ -542,7 +543,7 @@ describe('Vec4', function () { expect(v1.w).to.equal(-4); }); - it('subtracts a vector from itself in place', function () { + it('subtracts a vector from itself in place', () => { const v1 = new Vec4(1, 2, 3, 4); v1.sub(v1); expect(v1.x).to.equal(0); @@ -553,9 +554,9 @@ describe('Vec4', function () { }); - describe('#sub2', function () { + describe('#sub2', () => { - it('subtracts a vector from another vector and writes the result to a third vector', function () { + it('subtracts a vector from another vector and writes the result to a third vector', () => { const v1 = new Vec4(1, 2, 3, 4); const v2 = new Vec4(5, 6, 7, 8); const v3 = new Vec4(); @@ -566,7 +567,7 @@ describe('Vec4', function () { expect(v3.w).to.equal(-4); }); - it('subtracts a vector from itself and writes the result to itself', function () { + it('subtracts a vector from itself and writes the result to itself', () => { const v1 = new Vec4(1, 2, 3, 4); v1.sub2(v1, v1); expect(v1.x).to.equal(0); @@ -577,9 +578,9 @@ describe('Vec4', function () { }); - describe('#subScalar', function () { + describe('#subScalar', () => { - it('subtracts a scalar from a vector in place', function () { + it('subtracts a scalar from a vector in place', () => { const v = new Vec4(1, 2, 3, 4); v.subScalar(2); expect(v.x).to.equal(-1); @@ -590,9 +591,9 @@ describe('Vec4', function () { }); - describe('#toString', function () { + describe('#toString', () => { - it('returns a string representation of a vector', function () { + it('returns a string representation of a vector', () => { const v = new Vec4(1, 2, 3, 4); expect(v.toString()).to.equal('[1, 2, 3, 4]'); }); diff --git a/test/core/path.test.mjs b/test/core/path.test.mjs index 3f45cd7ddf2..a4d0127f200 100644 --- a/test/core/path.test.mjs +++ b/test/core/path.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { path } from '../../src/core/path.js'; -import { expect } from 'chai'; -describe('path', function () { +describe('path', () => { - describe('#extractPath', function () { + describe('#extractPath', () => { - it('removes from filename from paths', function () { + it('removes from filename from paths', () => { expect(path.extractPath('path/to/file')).to.equal('./path/to'); expect(path.extractPath('./path/to/file')).to.equal('./path/to'); expect(path.extractPath('../path/to/file')).to.equal('../path/to'); @@ -16,9 +17,9 @@ describe('path', function () { }); - describe('#getBasename', function () { + describe('#getBasename', () => { - it('returns basename from filename', function () { + it('returns basename from filename', () => { expect(path.getBasename('path/to/file.txt')).to.equal('file.txt'); expect(path.getBasename('path/to/directory')).to.equal('directory'); @@ -27,9 +28,9 @@ describe('path', function () { }); - describe('#getDirectory', function () { + describe('#getDirectory', () => { - it('handles various paths', function () { + it('handles various paths', () => { expect(path.getDirectory('folder/file.txt')).to.equal('folder'); expect(path.getDirectory('folder/another')).to.equal('folder'); expect(path.getDirectory('folder/another/')).to.equal('folder/another'); @@ -40,45 +41,45 @@ describe('path', function () { }); - describe('#getExtension', function () { + describe('#getExtension', () => { - it('returns the extension of a file', function () { + it('returns the extension of a file', () => { expect(path.getExtension('file.txt')).to.equal('.txt'); }); - it('returns the extension of a file with a path', function () { + it('returns the extension of a file with a path', () => { expect(path.getExtension('path/to/file.txt')).to.equal('.txt'); }); - it('returns the extension of a file with a path and query string', function () { + it('returns the extension of a file with a path and query string', () => { expect(path.getExtension('path/to/file.txt?query=string')).to.equal('.txt'); }); - it('returns the empty string if the file has no extension', function () { + it('returns the empty string if the file has no extension', () => { expect(path.getExtension('file')).to.equal(''); }); }); - describe('#isRelativePath', function () { + describe('#isRelativePath', () => { - it('returns true for relative paths', function () { + it('returns true for relative paths', () => { expect(path.isRelativePath('path/to/file')).to.be.true; expect(path.isRelativePath('./path/to/file')).to.be.true; expect(path.isRelativePath('../path/to/file')).to.be.true; expect(path.isRelativePath('path/../path/to/file.txt')).to.be.true; }); - it('returns false for absolute paths', function () { + it('returns false for absolute paths', () => { expect(path.isRelativePath('/path/to/file')).to.be.false; expect(path.isRelativePath('/path/../path/to/file.txt')).to.be.false; }); }); - describe('#join', function () { + describe('#join', () => { - it('handles two path sections', function () { + it('handles two path sections', () => { expect(path.join('a', 'b')).to.equal('a/b'); expect(path.join('a', '/b')).to.equal('/b'); expect(path.join('/a', 'b')).to.equal('/a/b'); @@ -92,7 +93,7 @@ describe('path', function () { expect(path.join('a/b', '')).to.equal('a/b'); }); - it('handles more than two path sections', function () { + it('handles more than two path sections', () => { expect(path.join('a', 'b', 'c')).to.equal('a/b/c'); expect(path.join('a', '/b', 'c')).to.equal('/b/c'); expect(path.join('/a', 'b', 'c')).to.equal('/a/b/c'); @@ -108,17 +109,17 @@ describe('path', function () { expect(path.join('a', 'b', 'c', 'd')).to.equal('a/b/c/d'); }); - it('handles invalid values', function () { - expect(function () { + it('handles invalid values', () => { + expect(() => { path.join('a', undefined); }).to.throw(); }); }); - describe('#normalize', function () { + describe('#normalize', () => { - it('normalizes any path', function () { + it('normalizes any path', () => { expect(path.normalize('a/b/c')).to.equal('a/b/c'); expect(path.normalize('/a/b/c')).to.equal('/a/b/c'); expect(path.normalize('a//b/c')).to.equal('a/b/c'); @@ -127,21 +128,21 @@ describe('path', function () { expect(path.normalize('a/b/c/..')).to.equal('a/b'); expect(path.normalize('a/b/c/')).to.equal('a/b/c/'); expect(path.normalize('../a/b/c/')).to.equal('../a/b/c/'); -// expect(path.normalize('../../a/b/c')).to.equal('../../a/b/c'); + // expect(path.normalize('../../a/b/c')).to.equal('../../a/b/c'); expect(path.normalize('/')).to.equal('/'); expect(path.normalize('../')).to.equal('../'); -// expect(path.normalize('./')).to.equal('./'); -// expect(path.normalize('././')).to.equal('./'); -// expect(path.normalize('../../')).to.equal('../../'); -// expect(path.normalize('.')).to.equal('.'); + // expect(path.normalize('./')).to.equal('./'); + // expect(path.normalize('././')).to.equal('./'); + // expect(path.normalize('../../')).to.equal('../../'); + // expect(path.normalize('.')).to.equal('.'); expect(path.normalize('./../.')).to.equal('..'); }); }); - describe('#split', function () { + describe('#split', () => { - it('splits a path into path and filename', function () { + it('splits a path into path and filename', () => { expect(path.split('path/to/file.txt')).to.deep.equal(['path/to', 'file.txt']); }); diff --git a/test/core/preprocessor.test.mjs b/test/core/preprocessor.test.mjs index 79503ca4b23..87c91a2d561 100644 --- a/test/core/preprocessor.test.mjs +++ b/test/core/preprocessor.test.mjs @@ -1,8 +1,9 @@ +import { expect } from 'chai'; + import { Preprocessor } from '../../src/core/preprocessor.js'; -import { expect } from 'chai'; -describe('Preprocessor', function () { +describe('Preprocessor', () => { const includes = new Map([ ['inc1', ` @@ -75,83 +76,83 @@ describe('Preprocessor', function () { #endif `; - it('returns false for MORPH_A', function () { + it('returns false for MORPH_A', () => { expect(Preprocessor.run(srcData, includes).includes('MORPH_A')).to.equal(false); }); - it('returns false for MORPH_B', function () { + it('returns false for MORPH_B', () => { expect(Preprocessor.run(srcData, includes).includes('MORPH_B')).to.equal(false); }); - it('returns true for $', function () { + it('returns true for $', () => { expect(Preprocessor.run(srcData, includes).includes('$')).to.equal(true); }); - it('returns true for TEST1', function () { + it('returns true for TEST1', () => { expect(Preprocessor.run(srcData, includes).includes('TEST1')).to.equal(true); }); - it('returns true for TEST2', function () { + it('returns true for TEST2', () => { expect(Preprocessor.run(srcData, includes).includes('TEST2')).to.equal(true); }); - it('returns true for TEST3', function () { + it('returns true for TEST3', () => { expect(Preprocessor.run(srcData, includes).includes('TEST3')).to.equal(true); }); - it('returns true for TEST4', function () { + it('returns true for TEST4', () => { expect(Preprocessor.run(srcData, includes).includes('TEST4')).to.equal(true); }); - it('returns false for TEST5', function () { + it('returns false for TEST5', () => { expect(Preprocessor.run(srcData, includes).includes('TEST5')).to.equal(false); }); - it('returns true for TEST6', function () { + it('returns true for TEST6', () => { expect(Preprocessor.run(srcData, includes).includes('TEST6')).to.equal(true); }); - it('returns false for TEST7', function () { + it('returns false for TEST7', () => { expect(Preprocessor.run(srcData, includes).includes('TEST7')).to.equal(false); }); - it('returns false for TEST8', function () { + it('returns false for TEST8', () => { expect(Preprocessor.run(srcData, includes).includes('TEST8')).to.equal(false); }); - it('returns false for TEST9', function () { + it('returns false for TEST9', () => { expect(Preprocessor.run(srcData, includes).includes('TEST9')).to.equal(false); }); - it('returns true for TEST10', function () { + it('returns true for TEST10', () => { expect(Preprocessor.run(srcData, includes).includes('TEST10')).to.equal(true); }); - it('returns false for TEST11', function () { + it('returns false for TEST11', () => { expect(Preprocessor.run(srcData, includes).includes('TEST11')).to.equal(false); }); - it('returns false for TEST12', function () { + it('returns false for TEST12', () => { expect(Preprocessor.run(srcData, includes).includes('TEST12')).to.equal(false); }); - it('returns true for TEST13', function () { + it('returns true for TEST13', () => { expect(Preprocessor.run(srcData, includes).includes('TEST13')).to.equal(true); }); - it('returns false for TEST14', function () { + it('returns false for TEST14', () => { expect(Preprocessor.run(srcData, includes).includes('TEST14')).to.equal(false); }); - it('returns true for INC1', function () { + it('returns true for INC1', () => { expect(Preprocessor.run(srcData, includes).includes('block1')).to.equal(true); }); - it('returns false for INC2', function () { + it('returns false for INC2', () => { expect(Preprocessor.run(srcData, includes).includes('block2')).to.equal(false); }); - it('returns true for nested', function () { + it('returns true for nested', () => { expect(Preprocessor.run(srcData, includes).includes('nested')).to.equal(true); }); }); diff --git a/test/core/shape/plane.test.mjs b/test/core/shape/plane.test.mjs index 54318012d00..026ca470014 100644 --- a/test/core/shape/plane.test.mjs +++ b/test/core/shape/plane.test.mjs @@ -1,13 +1,14 @@ -import { Plane } from '../../../src/core/shape/plane.js'; +import { expect } from 'chai'; + import { Vec3 } from '../../../src/core/math/vec3.js'; +import { Plane } from '../../../src/core/shape/plane.js'; -import { expect } from 'chai'; -describe('Plane', function () { +describe('Plane', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const p = new Plane(); expect(p.normal.x).to.equal(Vec3.UP.x); expect(p.normal.y).to.equal(Vec3.UP.y); @@ -15,7 +16,7 @@ describe('Plane', function () { expect(p.distance).to.equal(0); }); - it('supports arguments', function () { + it('supports arguments', () => { const p = new Plane(Vec3.UP, 5); expect(p.normal.x).to.equal(0); expect(p.normal.y).to.equal(1); @@ -25,7 +26,7 @@ describe('Plane', function () { }); - describe('#setFromPointNormal', function () { + describe('#setFromPointNormal', () => { const p = new Plane(); p.setFromPointNormal(new Vec3(1, 2, 3), Vec3.UP); @@ -36,7 +37,7 @@ describe('Plane', function () { }); - describe('#intersectsLine', function () { + describe('#intersectsLine', () => { const p = new Plane(); p.setFromPointNormal(new Vec3(0, 5, 0), Vec3.UP); diff --git a/test/core/sorted-loop-array.test.mjs b/test/core/sorted-loop-array.test.mjs index 4d0608e7f7f..adeec9794ef 100644 --- a/test/core/sorted-loop-array.test.mjs +++ b/test/core/sorted-loop-array.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { SortedLoopArray } from '../../src/core/sorted-loop-array.js'; -import { expect } from 'chai'; -describe('SortedLoopArray', function () { +describe('SortedLoopArray', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('creates a new sorted loop array', function () { + it('creates a new sorted loop array', () => { const array = new SortedLoopArray({ sortBy: 'priority' }); @@ -17,9 +18,9 @@ describe('SortedLoopArray', function () { }); - describe('#append()', function () { + describe('#append()', () => { - it('adds item to array', function () { + it('adds item to array', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); expect(arr.items.length).to.equal(0); @@ -32,14 +33,14 @@ describe('SortedLoopArray', function () { expect(arr.items[0]).to.equal(item); }); - it('increases length', function () { + it('increases length', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); expect(arr.length).to.equal(0); arr.append({ priority: 1 }); expect(arr.length).to.equal(1); }); - it('does not modify loopIndex', function () { + it('does not modify loopIndex', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -59,7 +60,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(1); }); - it('always adds item to the end', function () { + it('always adds item to the end', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -82,9 +83,9 @@ describe('SortedLoopArray', function () { }); - describe('#insert()', function () { + describe('#insert()', () => { - it('adds item to array', function () { + it('adds item to array', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); expect(arr.items.length).to.equal(0); @@ -97,7 +98,7 @@ describe('SortedLoopArray', function () { expect(arr.items[0]).to.equal(item); }); - it('adds item after items with lower priority', function () { + it('adds item after items with lower priority', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -113,7 +114,7 @@ describe('SortedLoopArray', function () { expect(arr.items[1]).to.equal(b); }); - it('adds item after items with equal priority', function () { + it('adds item after items with equal priority', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -129,7 +130,7 @@ describe('SortedLoopArray', function () { expect(arr.items[1]).to.equal(b); }); - it('adds item between items with lower and higher priority', function () { + it('adds item between items with lower and higher priority', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -150,7 +151,7 @@ describe('SortedLoopArray', function () { expect(arr.items[2]).to.equal(c); }); - it('adds item after items with lower and equal priority', function () { + it('adds item after items with lower and equal priority', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -171,7 +172,7 @@ describe('SortedLoopArray', function () { expect(arr.items[2]).to.equal(c); }); - it('adds item before items with higher priority', function () { + it('adds item before items with higher priority', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -192,7 +193,7 @@ describe('SortedLoopArray', function () { expect(arr.items[2]).to.equal(c); }); - it('does not modify loopIndex for item added after it', function () { + it('does not modify loopIndex for item added after it', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -212,7 +213,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(1); }); - it('modifies loopIndex for item added before it', function () { + it('modifies loopIndex for item added before it', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -232,7 +233,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(2); }); - it('modifies loopIndex for item added on the same slot', function () { + it('modifies loopIndex for item added on the same slot', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -252,7 +253,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(1); }); - it('increases length', function () { + it('increases length', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); expect(arr.length).to.equal(0); arr.insert({ priority: 1 }); @@ -261,9 +262,9 @@ describe('SortedLoopArray', function () { }); - describe('#remove()', function () { + describe('#remove()', () => { - it('removes item from array', function () { + it('removes item from array', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); expect(arr.items.length).to.equal(0); @@ -280,7 +281,7 @@ describe('SortedLoopArray', function () { expect(arr.items.length).to.equal(0); }); - it('decreases length', function () { + it('decreases length', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const item = { priority: 1 }; expect(arr.length).to.equal(0); @@ -294,7 +295,7 @@ describe('SortedLoopArray', function () { expect(arr.length).to.equal(0); }); - it('does not modify loopIndex for item removed after it', function () { + it('does not modify loopIndex for item removed after it', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -315,7 +316,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(1); }); - it('modifies loopIndex for item removed before it', function () { + it('modifies loopIndex for item removed before it', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -336,7 +337,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(0); }); - it('modifies loopIndex when item it points to was removed', function () { + it('modifies loopIndex when item it points to was removed', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -357,7 +358,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(0); }); - it('does not modify loopIndex if element does not exist', function () { + it('does not modify loopIndex if element does not exist', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -379,9 +380,9 @@ describe('SortedLoopArray', function () { }); - describe('#sort', function () { + describe('#sort', () => { - it('sorts items', function () { + it('sorts items', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -401,7 +402,7 @@ describe('SortedLoopArray', function () { expect(arr.items[2]).to.equal(c); }); - it('updates loopIndex', function () { + it('updates loopIndex', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 @@ -419,7 +420,7 @@ describe('SortedLoopArray', function () { expect(arr.loopIndex).to.equal(2); }); - it('does not update loopIndex if it cannot find element it\'s pointing to', function () { + it('does not update loopIndex if it cannot find element it\'s pointing to', () => { const arr = new SortedLoopArray({ sortBy: 'priority' }); const a = { priority: 1 diff --git a/test/core/string.test.mjs b/test/core/string.test.mjs index f1a69789ecb..ff3311a7adf 100644 --- a/test/core/string.test.mjs +++ b/test/core/string.test.mjs @@ -1,26 +1,27 @@ +import { expect } from 'chai'; + import { string } from '../../src/core/string.js'; -import { expect } from 'chai'; -describe('string', function () { +describe('string', () => { - describe('#format', function () { + describe('#format', () => { - it('handles no args', function () { + it('handles no args', () => { const src = 'a string'; const result = string.format(src); expect(result).to.equal('a string'); }); - it('handles one arg', function () { + it('handles one arg', () => { const src = 'a string {0}'; const result = string.format(src, 'abc'); expect(result).to.equal('a string abc'); }); - it('handles two args', function () { + it('handles two args', () => { const src = '{0} a string {1}'; const result = string.format(src, 'abc', 'def'); @@ -29,9 +30,9 @@ describe('string', function () { }); - describe('#getSymbols', function () { + describe('#getSymbols', () => { - it('returns an array of the expected length', function () { + it('returns an array of the expected length', () => { expect(string.getSymbols('ABC').length).to.equal(3); expect(string.getSymbols('A🇺🇸').length).to.equal(2); expect(string.getSymbols('👨🏿').length).to.equal(1); diff --git a/test/core/uri.test.mjs b/test/core/uri.test.mjs index 42050eb2ade..3d1e6b3d806 100644 --- a/test/core/uri.test.mjs +++ b/test/core/uri.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { createURI, URI } from '../../src/core/uri.js'; -import { expect } from 'chai'; -describe('URI', function () { +describe('URI', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('handles all sections', function () { + it('handles all sections', () => { const s = 'http://a/b/c/d;p?q=r#l'; const uri = new URI(s); @@ -18,7 +19,7 @@ describe('URI', function () { expect(uri.fragment).to.equal('l'); }); - it('handles no scheme', function () { + it('handles no scheme', () => { const s = '//a/b/c/d;p?q=r#l'; const uri = new URI(s); @@ -29,7 +30,7 @@ describe('URI', function () { expect(uri.fragment).to.equal('l'); }); - it('handles no authority', function () { + it('handles no authority', () => { const s = '/b/c/d;p?q=r#l'; const uri = new URI(s); @@ -40,7 +41,7 @@ describe('URI', function () { expect(uri.fragment).to.equal('l'); }); - it('handles no query', function () { + it('handles no query', () => { const s = 'http://a/b/c/d;p#l'; const uri = new URI(s); @@ -51,7 +52,7 @@ describe('URI', function () { expect(uri.fragment).to.equal('l'); }); - it('handles no fragment', function () { + it('handles no fragment', () => { const s = 'http://a/b/c/d;p?q=r'; const uri = new URI(s); @@ -64,9 +65,9 @@ describe('URI', function () { }); - describe('#toString', function () { + describe('#toString', () => { - it('matches the URI passed to the constructor', function () { + it('matches the URI passed to the constructor', () => { const s = 'http://a/b/c/d;p?q=r#l'; const uri = new URI(s); const r = uri.toString(); @@ -74,7 +75,7 @@ describe('URI', function () { expect(s).to.equal(r); }); - it('handles an edit to the query', function () { + it('handles an edit to the query', () => { const s = 'http://example.com'; const uri = new URI(s); uri.query = 'q=abc'; @@ -87,9 +88,9 @@ describe('URI', function () { }); - describe('#getQuery', function () { + describe('#getQuery', () => { - it('correctly parses the query string', function () { + it('correctly parses the query string', () => { const s = 'http://example.com/test?a=1&b=string&c=something%20spaced'; const uri = new URI(s); @@ -100,7 +101,7 @@ describe('URI', function () { expect(q.c).to.equal('something spaced'); }); - it('handles an empty query string', function () { + it('handles an empty query string', () => { const s = 'http://example.com/test'; const uri = new URI(s); @@ -111,9 +112,9 @@ describe('URI', function () { }); - describe('#setQuery', function () { + describe('#setQuery', () => { - it('adds a query string', function () { + it('adds a query string', () => { const uri = new URI('http://example.com/test'); const q = { key: 'value' @@ -124,7 +125,7 @@ describe('URI', function () { }); - it('adds a query string with spaces and quotes', function () { + it('adds a query string with spaces and quotes', () => { const uri = new URI('http://example.com/test'); const q = { 'key': 'value', @@ -138,9 +139,9 @@ describe('URI', function () { }); -describe('createURI', function () { +describe('createURI', () => { - it('correctly constructs URIs', function () { + it('correctly constructs URIs', () => { let uri; uri = createURI({ @@ -170,36 +171,36 @@ describe('createURI', function () { }); - it('throws exceptions', function () { - expect(function () { + it('throws exceptions', () => { + expect(() => { createURI({ scheme: 'http', host: 'http://test.com' }); }).to.throw(); - expect(function () { + expect(() => { createURI({ authority: 'http', host: 'http://test.com' }); }).to.throw(); - expect(function () { + expect(() => { createURI({ scheme: 'http', hostpath: 'http://test.com' }); }).to.throw(); - expect(function () { + expect(() => { createURI({ authority: 'http', hostpath: 'http://test.com' }); }).to.throw(); - expect(function () { + expect(() => { createURI({ scheme: 'http', authority: 'e.com', @@ -207,7 +208,7 @@ describe('createURI', function () { }); }).to.throw(); - expect(function () { + expect(() => { createURI({ scheme: 'abc', authority: 'http', @@ -215,14 +216,14 @@ describe('createURI', function () { }); }).to.throw(); - expect(function () { + expect(() => { createURI({ host: 'http://test.com', hostpath: 'http://test.com' }); }).to.throw(); - expect(function () { + expect(() => { createURI({ path: '/abc', hostpath: 'http://test.com/abc' diff --git a/test/fixtures.mjs b/test/fixtures.mjs index dea35e4c36d..9eb595b8869 100644 --- a/test/fixtures.mjs +++ b/test/fixtures.mjs @@ -1,5 +1,6 @@ -import handler from 'serve-handler'; import http from 'http'; + +import handler from 'serve-handler'; import XMLHttpRequest from 'xhr2'; import 'global-jsdom/register'; // eslint-disable-line import/no-unresolved,import/extensions diff --git a/test/framework/anim/controller/anim-blend-tree.test.mjs b/test/framework/anim/controller/anim-blend-tree.test.mjs index 0be40d9499d..fb39ad96077 100644 --- a/test/framework/anim/controller/anim-blend-tree.test.mjs +++ b/test/framework/anim/controller/anim-blend-tree.test.mjs @@ -1,12 +1,14 @@ -import { AnimBlendTree } from '../../../../src/framework/anim/controller/anim-blend-tree.js'; +import { expect } from 'chai'; + import { AnimBlendTree1D } from '../../../../src/framework/anim/controller/anim-blend-tree-1d.js'; -import { AnimBlendTreeDirect } from '../../../../src/framework/anim/controller/anim-blend-tree-direct.js'; import { AnimBlendTreeCartesian2D } from '../../../../src/framework/anim/controller/anim-blend-tree-2d-cartesian.js'; import { AnimBlendTreeDirectional2D } from '../../../../src/framework/anim/controller/anim-blend-tree-2d-directional.js'; +import { AnimBlendTreeDirect } from '../../../../src/framework/anim/controller/anim-blend-tree-direct.js'; +import { AnimBlendTree } from '../../../../src/framework/anim/controller/anim-blend-tree.js'; import { AnimState } from '../../../../src/framework/anim/controller/anim-state.js'; -import { expect } from 'chai'; -describe('AnimBlendTree', function () { + +describe('AnimBlendTree', () => { const findParameter = () => {}; const animState = new AnimState({ findParameter }, 'state', 1, true, null); const animBlendTree = new AnimBlendTree(animState, null, 'blendTree', 1, ['blendParam'], [ @@ -20,38 +22,38 @@ describe('AnimBlendTree', function () { } ], false, animState._createTree, findParameter); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animBlendTree).to.be.ok; }); }); - describe('#getChild', function () { + describe('#getChild', () => { - it('can retrieve a child by name', function () { + it('can retrieve a child by name', () => { expect(animBlendTree.getChild('child1').name).to.equal('child1'); expect(animBlendTree.getChild('child2').name).to.equal('child2'); }); - it('returns null when a child is not found', function () { + it('returns null when a child is not found', () => { expect(animBlendTree.getChild('child3')).to.equal(null); }); }); - describe('#getNodeCount', function () { + describe('#getNodeCount', () => { - it('returns the count of children in the blend tree', function () { + it('returns the count of children in the blend tree', () => { expect(animBlendTree.getNodeCount()).to.equal(2); }); }); - describe('#updateParameterValues', function () { + describe('#updateParameterValues', () => { - it('parameters are not set before it is called', function () { + it('parameters are not set before it is called', () => { const params = { 'param1': { value: 'value1' @@ -70,7 +72,7 @@ describe('AnimBlendTree', function () { expect(animBlendTree._parameterValues[1]).to.not.be.equal('value2'); }); - it('can set any updated parameters in the blend tree', function () { + it('can set any updated parameters in the blend tree', () => { const params = { 'param1': { value: 'value1' @@ -93,7 +95,7 @@ describe('AnimBlendTree', function () { expect(animBlendTree._parameterValues[1]).to.equal('value3'); }); - it('returns false when stored parameters are already up to date', function () { + it('returns false when stored parameters are already up to date', () => { const params = { 'param1': { value: 'value1' @@ -112,7 +114,7 @@ describe('AnimBlendTree', function () { expect(result).to.equal(false); }); - it('returns true when stored parameters are already up to date', function () { + it('returns true when stored parameters are already up to date', () => { const params = { 'param1': { value: 'value1' @@ -137,7 +139,7 @@ describe('AnimBlendTree', function () { }); -describe('AnimBlendTree1D', function () { +describe('AnimBlendTree1D', () => { const params = { 'blendParam': { value: 0.5 @@ -158,22 +160,22 @@ describe('AnimBlendTree1D', function () { } ], false, animState._createTree, findParameter); - describe('#calculateWeights', function () { + describe('#calculateWeights', () => { - it('produces equal weights when the parameter is at the midpoint of both children', function () { + it('produces equal weights when the parameter is at the midpoint of both children', () => { animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(0.5); expect(animBlendTree.getChild('child2').weight).to.equal(0.5); }); - it('produces unequal weights when the parameter is not the midpoint of both children', function () { + it('produces unequal weights when the parameter is not the midpoint of both children', () => { params.blendParam.value = 0.25; animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(0.75); expect(animBlendTree.getChild('child2').weight).to.equal(0.25); }); - it('produces correct results when a parameter is the same as a childs point', function () { + it('produces correct results when a parameter is the same as a childs point', () => { params.blendParam.value = 1; animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(0); @@ -183,7 +185,7 @@ describe('AnimBlendTree1D', function () { }); }); -describe('AnimBlendTreeDirect', function () { +describe('AnimBlendTreeDirect', () => { const params = { 'blendParam1': { value: 0.5 @@ -205,15 +207,15 @@ describe('AnimBlendTreeDirect', function () { } ], false, animState._createTree, findParameter); - describe('#calculateWeights', function () { + describe('#calculateWeights', () => { - it('produces equal weights when the parameters are equal', function () { + it('produces equal weights when the parameters are equal', () => { animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(0.5); expect(animBlendTree.getChild('child2').weight).to.equal(0.5); }); - it('produces unequal weights when the parameters are not equal', function () { + it('produces unequal weights when the parameters are not equal', () => { params.blendParam1.value = 0.75; params.blendParam2.value = 0.25; animBlendTree.calculateWeights(); @@ -221,7 +223,7 @@ describe('AnimBlendTreeDirect', function () { expect(animBlendTree.getChild('child2').weight).to.equal(0.25); }); - it('produces a zero weight for single parameters that are zero', function () { + it('produces a zero weight for single parameters that are zero', () => { params.blendParam1.value = 1; params.blendParam2.value = 0; animBlendTree.calculateWeights(); @@ -229,7 +231,7 @@ describe('AnimBlendTreeDirect', function () { expect(animBlendTree.getChild('child2').weight).to.equal(0); }); - it('produces zero weights when all parameters are zero', function () { + it('produces zero weights when all parameters are zero', () => { params.blendParam1.value = 0; params.blendParam2.value = 0; animBlendTree.calculateWeights(); @@ -241,7 +243,7 @@ describe('AnimBlendTreeDirect', function () { }); -describe('AnimBlendTreeCartesian2D', function () { +describe('AnimBlendTreeCartesian2D', () => { const params = { 'blendParam1': { value: 0 @@ -265,29 +267,29 @@ describe('AnimBlendTreeCartesian2D', function () { } ], false, animState._createTree, findParameter); - describe('#calculateWeights', function () { + describe('#calculateWeights', () => { - it('produces equal weights when the parameters are equal', function () { + it('produces equal weights when the parameters are equal', () => { animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(0.5); expect(animBlendTree.getChild('child2').weight).to.equal(0.5); }); - it('produces unequal weights when the parameters are not equal', function () { + it('produces unequal weights when the parameters are not equal', () => { params.blendParam2.value = 0.5; animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(0.75); expect(animBlendTree.getChild('child2').weight).to.equal(0.25); }); - it('produces a zero weight for single parameters that are zero', function () { + it('produces a zero weight for single parameters that are zero', () => { params.blendParam2.value = 1; animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(1); expect(animBlendTree.getChild('child2').weight).to.equal(0); }); - it('produces a zero weights when all parameters are zero', function () { + it('produces a zero weights when all parameters are zero', () => { params.blendParam1.value = 0; params.blendParam2.value = 0; animBlendTree._children[0]._point = [0, 0]; @@ -301,7 +303,7 @@ describe('AnimBlendTreeCartesian2D', function () { }); -describe('AnimBlendTreeDirectional2D', function () { +describe('AnimBlendTreeDirectional2D', () => { const params = { 'blendParam1': { value: 0 @@ -325,29 +327,29 @@ describe('AnimBlendTreeDirectional2D', function () { } ], false, animState._createTree, findParameter); - describe('#calculateWeights', function () { + describe('#calculateWeights', () => { - it('produces equal weights when the parameters are equal', function () { + it('produces equal weights when the parameters are equal', () => { animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(0.5); expect(animBlendTree.getChild('child2').weight).to.equal(0.5); }); - it('produces unequal weights when the parameters are not equal', function () { + it('produces unequal weights when the parameters are not equal', () => { params.blendParam2.value = 0.5; animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(1); expect(animBlendTree.getChild('child2').weight).to.equal(0); }); - it('produces a zero weight for single parameters that are zero', function () { + it('produces a zero weight for single parameters that are zero', () => { params.blendParam2.value = 1; animBlendTree.calculateWeights(); expect(animBlendTree.getChild('child1').weight).to.equal(1); expect(animBlendTree.getChild('child2').weight).to.equal(0); }); - it('produces a zero weights when all parameters are zero', function () { + it('produces a zero weights when all parameters are zero', () => { params.blendParam1.value = 0; params.blendParam2.value = 0; animBlendTree._children[0]._point = [0, 0]; diff --git a/test/framework/anim/controller/anim-controller.test.mjs b/test/framework/anim/controller/anim-controller.test.mjs index 7f5e6eaeb4b..368704ced75 100644 --- a/test/framework/anim/controller/anim-controller.test.mjs +++ b/test/framework/anim/controller/anim-controller.test.mjs @@ -1,23 +1,25 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + +import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; import { AnimController } from '../../../../src/framework/anim/controller/anim-controller.js'; -import { Entity } from '../../../../src/framework/entity.js'; -import { AnimComponentBinder } from '../../../../src/framework/components/anim/component-binder.js'; +import { ANIM_LESS_THAN } from '../../../../src/framework/anim/controller/constants.js'; +import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; +import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; import { AnimEvaluator } from '../../../../src/framework/anim/evaluator/anim-evaluator.js'; -import { Application } from '../../../../src/framework/application.js'; import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; -import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; -import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; -import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; -import { ANIM_LESS_THAN } from '../../../../src/framework/anim/controller/constants.js'; +import { Application } from '../../../../src/framework/application.js'; +import { AnimComponentBinder } from '../../../../src/framework/components/anim/component-binder.js'; +import { Entity } from '../../../../src/framework/entity.js'; import { NullGraphicsDevice } from '../../../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; -import { expect } from 'chai'; -describe('AnimController', function () { + +describe('AnimController', () => { let app; let controller; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); const states = [ @@ -99,64 +101,64 @@ describe('AnimController', function () { controller.assignAnimation('Other State 2', new AnimTrack('otherState2Track', 4, inputs, outputs, curves), 1, true); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(controller).to.be.ok; }); }); - describe('#_getActiveStateProgressForTime', function () { + describe('#_getActiveStateProgressForTime', () => { - it('returns 1 when the controller is in the START state', function () { + it('returns 1 when the controller is in the START state', () => { controller.activeState = 'START'; expect(controller._getActiveStateProgressForTime(0)).to.equal(1); }); - it('returns 1 when the controller is in the ANY state', function () { + it('returns 1 when the controller is in the ANY state', () => { controller.activeState = 'ANY'; expect(controller._getActiveStateProgressForTime(0)).to.equal(1); }); - it('returns 1 when the controller is in the END state', function () { + it('returns 1 when the controller is in the END state', () => { controller.activeState = 'END'; expect(controller._getActiveStateProgressForTime(0)).to.equal(1); }); - it('returns a progress of 0 when the controller is at the start of a states timeline', function () { + it('returns a progress of 0 when the controller is at the start of a states timeline', () => { controller.update(0); expect(controller._getActiveStateProgressForTime(0)).to.equal(0); }); - it('returns a progress of 0.5 when the controller is halfway through a states duration', function () { + it('returns a progress of 0.5 when the controller is halfway through a states duration', () => { controller.update(0); expect(controller._getActiveStateProgressForTime(2)).to.equal(0.5); }); - it('returns a progress of 1 when the controller is at the end of a states timeline', function () { + it('returns a progress of 1 when the controller is at the end of a states timeline', () => { controller.update(0); expect(controller._getActiveStateProgressForTime(4)).to.equal(1); }); }); - describe('#_findTransitionsFromState', function () { + describe('#_findTransitionsFromState', () => { - it('returns the transitions for a given state', function () { + it('returns the transitions for a given state', () => { expect(controller._findTransitionsFromState('START').length).to.equal(1); expect(controller._findTransitionsFromState('START')[0].to).to.equal('Initial State'); }); - it('returns an empty array when a state has no transitions', function () { + it('returns an empty array when a state has no transitions', () => { expect(controller._findTransitionsFromState('Initial State').length).to.equal(0); }); - it('returns transitions sorted by priority', function () { + it('returns transitions sorted by priority', () => { expect(controller._findTransitionsFromState('Other State 1').length).to.equal(2); expect(controller._findTransitionsFromState('Other State 1')[0].priority).to.equal(1); expect(controller._findTransitionsFromState('Other State 1')[1].priority).to.equal(2); @@ -164,13 +166,13 @@ describe('AnimController', function () { }); - describe('#_findTransitionsBetweenStates', function () { + describe('#_findTransitionsBetweenStates', () => { - it('returns the transitions between two states', function () { + it('returns the transitions between two states', () => { expect(controller._findTransitionsBetweenStates('Other State 1', 'Other State 2').length).to.equal(2); }); - it('returns transitions sorted by priority', function () { + it('returns transitions sorted by priority', () => { expect(controller._findTransitionsBetweenStates('Other State 1', 'Other State 2').length).to.equal(2); expect(controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0].priority).to.equal(1); expect(controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[1].priority).to.equal(2); @@ -178,46 +180,46 @@ describe('AnimController', function () { }); - describe('#_transitionHasConditionsMet', function () { + describe('#_transitionHasConditionsMet', () => { - it('returns true when no conditions are present', function () { + it('returns true when no conditions are present', () => { expect(controller._transitionHasConditionsMet(controller._findTransitionsBetweenStates('START', 'Initial State')[0])).to.equal(true); }); - it('returns true when a condition is present and met', function () { + it('returns true when a condition is present and met', () => { expect(controller._transitionHasConditionsMet(controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[1])).to.equal(true); }); - it('returns false when a condition is present but not met', function () { + it('returns false when a condition is present but not met', () => { expect(controller._transitionHasConditionsMet(controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0])).to.equal(false); }); }); - describe('#_findTransition', function () { + describe('#_findTransition', () => { - it('returns a transition with the correct from state when from and to are supplied', function () { + it('returns a transition with the correct from state when from and to are supplied', () => { const transition = controller._findTransition('START', 'Initial State'); expect(transition.from).to.equal('START'); }); - it('returns a transition with the correct source state when from and to are supplied', function () { + it('returns a transition with the correct source state when from and to are supplied', () => { const transition = controller._findTransition('START', 'Initial State'); expect(transition.from).to.equal('START'); }); - it('returns a transition with the correct destination state when from and to are supplied', function () { + it('returns a transition with the correct destination state when from and to are supplied', () => { const transition = controller._findTransition('START', 'Initial State'); expect(transition.to).to.equal('Initial State'); }); - it('returns a transition when the from param is given and the controller is not transitioning', function () { + it('returns a transition when the from param is given and the controller is not transitioning', () => { expect(controller._isTransitioning).to.equal(false); const transition = controller._findTransition('START'); expect(transition.from).to.equal('START'); }); - it('returns null when controller is transitioning and the interruption source is "none"', function () { + it('returns null when controller is transitioning and the interruption source is "none"', () => { controller._isTransitioning = true; expect(controller._isTransitioning).to.equal(true); expect(controller._transitionInterruptionSource).to.equal('NONE'); @@ -225,7 +227,7 @@ describe('AnimController', function () { expect(transition).to.equal(null); }); - it('returns null when controller is transitioning and the interruption source is "none"', function () { + it('returns null when controller is transitioning and the interruption source is "none"', () => { controller._isTransitioning = true; expect(controller._isTransitioning).to.equal(true); expect(controller._transitionInterruptionSource).to.equal('NONE'); @@ -233,7 +235,7 @@ describe('AnimController', function () { expect(transition).to.equal(null); }); - it('returns a transition from the previous state when controller is transitioning and the interruption source is "PREV_STATE"', function () { + it('returns a transition from the previous state when controller is transitioning and the interruption source is "PREV_STATE"', () => { controller._isTransitioning = true; controller._transitionInterruptionSource = 'PREV_STATE'; controller._previousStateName = 'Other State 1'; @@ -243,7 +245,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('Other State 1'); }); - it('returns a transition from the ANY state when controller is transitioning and the interruption source is "PREV_STATE" with no matching previous state', function () { + it('returns a transition from the ANY state when controller is transitioning and the interruption source is "PREV_STATE" with no matching previous state', () => { controller._isTransitioning = true; controller._transitionInterruptionSource = 'PREV_STATE'; expect(controller._isTransitioning).to.equal(true); @@ -252,7 +254,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('ANY'); }); - it('returns a transition from the next state when controller is transitioning and the interruption source is "NEXT_STATE"', function () { + it('returns a transition from the next state when controller is transitioning and the interruption source is "NEXT_STATE"', () => { controller._isTransitioning = true; controller._transitionInterruptionSource = 'NEXT_STATE'; controller._activeStateName = 'Other State 1'; @@ -262,7 +264,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('Other State 1'); }); - it('returns a transition from the ANY state when controller is transitioning and the interruption source is "NEXT_STATE" with no matching next state', function () { + it('returns a transition from the ANY state when controller is transitioning and the interruption source is "NEXT_STATE" with no matching next state', () => { controller.update(0); controller._isTransitioning = true; controller._transitionInterruptionSource = 'NEXT_STATE'; @@ -272,7 +274,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('ANY'); }); - it('returns a transition from the next state when controller is transitioning and the interruption source is "PREV_STATE_NEXT_STATE"', function () { + it('returns a transition from the next state when controller is transitioning and the interruption source is "PREV_STATE_NEXT_STATE"', () => { controller._isTransitioning = true; controller._transitionInterruptionSource = 'PREV_STATE_NEXT_STATE'; controller._activeStateName = 'Other State 1'; @@ -282,7 +284,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('Other State 1'); }); - it('returns a transition from the previous state when controller is transitioning and the interruption source is "PREV_STATE_NEXT_STATE"', function () { + it('returns a transition from the previous state when controller is transitioning and the interruption source is "PREV_STATE_NEXT_STATE"', () => { controller._isTransitioning = true; controller._transitionInterruptionSource = 'PREV_STATE_NEXT_STATE'; controller._previousStateName = 'Other State 1'; @@ -292,7 +294,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('Other State 1'); }); - it('returns a transition from the ANY state when controller is transitioning and the interruption source is "PREV_STATE_NEXT_STATE"', function () { + it('returns a transition from the ANY state when controller is transitioning and the interruption source is "PREV_STATE_NEXT_STATE"', () => { controller.update(0); controller._isTransitioning = true; controller._transitionInterruptionSource = 'PREV_STATE_NEXT_STATE'; @@ -302,7 +304,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('ANY'); }); - it('returns a transition from the next state when controller is transitioning and the interruption source is "NEXT_STATE_PREV_STATE"', function () { + it('returns a transition from the next state when controller is transitioning and the interruption source is "NEXT_STATE_PREV_STATE"', () => { controller._isTransitioning = true; controller._transitionInterruptionSource = 'NEXT_STATE_PREV_STATE'; controller._activeStateName = 'Other State 1'; @@ -312,7 +314,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('Other State 1'); }); - it('returns a transition from the previous state when controller is transitioning and the interruption source is "NEXT_STATE_PREV_STATE"', function () { + it('returns a transition from the previous state when controller is transitioning and the interruption source is "NEXT_STATE_PREV_STATE"', () => { controller._isTransitioning = true; controller._transitionInterruptionSource = 'NEXT_STATE_PREV_STATE'; controller._previousStateName = 'Other State 1'; @@ -323,7 +325,7 @@ describe('AnimController', function () { expect(transition.from).to.equal('Other State 1'); }); - it('returns a transition from the ANY state when controller is transitioning and the interruption source is "NEXT_STATE_PREV_STATE"', function () { + it('returns a transition from the ANY state when controller is transitioning and the interruption source is "NEXT_STATE_PREV_STATE"', () => { controller.update(0); controller._isTransitioning = true; controller._transitionInterruptionSource = 'NEXT_STATE_PREV_STATE'; @@ -335,62 +337,62 @@ describe('AnimController', function () { }); - describe('#updateStateFromTransition', function () { + describe('#updateStateFromTransition', () => { - it('begins transitions to the destination state', function () { + it('begins transitions to the destination state', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; controller.updateStateFromTransition(transition); expect(controller.activeStateName).to.equal('Other State 2'); }); - it('sets the currently active state as the previous state', function () { + it('sets the currently active state as the previous state', () => { const previousActiveState = controller.activeStateName; const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; controller.updateStateFromTransition(transition); expect(controller.previousStateName).to.equal(previousActiveState); }); - it('adds a new clip for the newly active state to the evaluator', function () { + it('adds a new clip for the newly active state to the evaluator', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; controller.updateStateFromTransition(transition); expect(controller._animEvaluator.clips[0].track.name).to.equal('otherState2Track'); }); - it('sets the controller _isTransitoning property to true', function () { + it('sets the controller _isTransitoning property to true', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; expect(controller._isTransitioning).to.equal(false); controller.updateStateFromTransition(transition); expect(controller._isTransitioning).to.equal(true); }); - it('sets the current transition time to 0', function () { + it('sets the current transition time to 0', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; controller.updateStateFromTransition(transition); expect(controller._currTransitionTime).to.equal(0); }); - it('sets the time in state correctly if a transition offset is supplied', function () { + it('sets the time in state correctly if a transition offset is supplied', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; transition._transitionOffset = 0.5; controller.updateStateFromTransition(transition); expect(controller._timeInState).to.equal(2); }); - it('sets the time in state before correctly if a transition offset is supplied', function () { + it('sets the time in state before correctly if a transition offset is supplied', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; transition._transitionOffset = 0.5; controller.updateStateFromTransition(transition); expect(controller._timeInStateBefore).to.equal(2); }); - it('sets the new clips time correctly if a transition offset is supplied', function () { + it('sets the new clips time correctly if a transition offset is supplied', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; transition._transitionOffset = 0.5; controller.updateStateFromTransition(transition); expect(controller._animEvaluator.clips[0].time).to.equal(2); }); - it('sets the new clips time correctly if a transition offset is not supplied', function () { + it('sets the new clips time correctly if a transition offset is not supplied', () => { const transition = controller._findTransitionsBetweenStates('Other State 1', 'Other State 2')[0]; controller.updateStateFromTransition(transition); expect(controller._animEvaluator.clips[0].time).to.equal(0); diff --git a/test/framework/anim/controller/anim-node.test.mjs b/test/framework/anim/controller/anim-node.test.mjs index 13868a71a46..577009b1e60 100644 --- a/test/framework/anim/controller/anim-node.test.mjs +++ b/test/framework/anim/controller/anim-node.test.mjs @@ -1,12 +1,13 @@ +import { expect } from 'chai'; + import { AnimNode } from '../../../../src/framework/anim/controller/anim-node.js'; import { AnimState } from '../../../../src/framework/anim/controller/anim-state.js'; -import { expect } from 'chai'; -describe('AnimNode', function () { +describe('AnimNode', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1); expect(animNode).to.be.ok; @@ -14,9 +15,9 @@ describe('AnimNode', function () { }); - describe('#name', function () { + describe('#name', () => { - it('returns the name of the AnimNode', function () { + it('returns the name of the AnimNode', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1); expect(animNode.name).to.equal('node'); @@ -24,9 +25,9 @@ describe('AnimNode', function () { }); - describe('#parent', function () { + describe('#parent', () => { - it('returns the parent of the AnimNode', function () { + it('returns the parent of the AnimNode', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNodeParent = new AnimNode(animState, null, 'parent', 1); const animNode = new AnimNode(animState, animNodeParent, 'node', 1); @@ -35,15 +36,15 @@ describe('AnimNode', function () { }); - describe('#path', function () { + describe('#path', () => { - it('returns the name of the AnimNode when it has no parent', function () { + it('returns the name of the AnimNode when it has no parent', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1); expect(animNode.path).to.equal('node'); }); - it('returns a path representing a node and its hierarchy', function () { + it('returns a path representing a node and its hierarchy', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNodeParent = new AnimNode(animState, null, 'parent', 1); const animNode = new AnimNode(animState, animNodeParent, 'node', 1); @@ -52,15 +53,15 @@ describe('AnimNode', function () { }); - describe('#pointLength', function () { + describe('#pointLength', () => { - it('returns the correct point length when the point is 1 dimensional', function () { + it('returns the correct point length when the point is 1 dimensional', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1); expect(animNode.pointLength).to.equal(1); }); - it('returns the correct point length when the point is 2 dimensional', function () { + it('returns the correct point length when the point is 2 dimensional', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', [5, 2]); expect(animNode.pointLength).to.equal(Math.sqrt(5 * 5 + 2 * 2)); @@ -68,23 +69,23 @@ describe('AnimNode', function () { }); - describe('#weight', function () { + describe('#weight', () => { - it('can set the weight of the AnimNode', function () { + it('can set the weight of the AnimNode', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1); animNode.weight = 0.5; expect(animNode._weight).to.equal(0.5); }); - it('can get the weight of the AnimNode when no parent is present', function () { + it('can get the weight of the AnimNode when no parent is present', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1); expect(animNode.parent).to.equal(null); expect(animNode.weight).to.equal(1.0); }); - it('can get the correct weight of the AnimNode when a parent is present', function () { + it('can get the correct weight of the AnimNode when a parent is present', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNodeParent = new AnimNode(animState, null, 'parent', 1); animNodeParent.weight = 0.5; @@ -96,9 +97,9 @@ describe('AnimNode', function () { }); - describe('#normalizedWeight', function () { + describe('#normalizedWeight', () => { - it('can get the normalized weight when the AnimNode\'s state total weight is non zero', function () { + it('can get the normalized weight when the AnimNode\'s state total weight is non zero', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); animState.animations = [ { @@ -115,7 +116,7 @@ describe('AnimNode', function () { expect(animNode.normalizedWeight).to.equal(0.5); }); - it('can get the normalized weight when the AnimNode\'s state total weight is zero', function () { + it('can get the normalized weight when the AnimNode\'s state total weight is zero', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1); animNode.weight = 2.5; @@ -124,16 +125,16 @@ describe('AnimNode', function () { }); - describe('#absoluteSpeed', function () { + describe('#absoluteSpeed', () => { - it('returns an absolue speed when speed is negative', function () { + it('returns an absolue speed when speed is negative', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1, -5); expect(animNode.speed).to.equal(-5); expect(animNode.absoluteSpeed).to.equal(5); }); - it('returns an absolue speed when speed is positive', function () { + it('returns an absolue speed when speed is positive', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1, 5); expect(animNode.speed).to.equal(5); @@ -142,9 +143,9 @@ describe('AnimNode', function () { }); - describe('#speed', function () { + describe('#speed', () => { - it('returns a speed value thats weighted by the weightedSpeed value', function () { + it('returns a speed value thats weighted by the weightedSpeed value', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); const animNode = new AnimNode(animState, null, 'node', 1, 0.5); animNode.weightedSpeed = 0.5; diff --git a/test/framework/anim/controller/anim-state.test.mjs b/test/framework/anim/controller/anim-state.test.mjs index d0517b22dd2..d75614b439d 100644 --- a/test/framework/anim/controller/anim-state.test.mjs +++ b/test/framework/anim/controller/anim-state.test.mjs @@ -1,23 +1,24 @@ -import { AnimState } from '../../../../src/framework/anim/controller/anim-state.js'; import { expect } from 'chai'; -import { ANIM_BLEND_1D } from '../../../../src/framework/anim/controller/constants.js'; + import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; +import { AnimState } from '../../../../src/framework/anim/controller/anim-state.js'; +import { ANIM_BLEND_1D } from '../../../../src/framework/anim/controller/constants.js'; import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; -describe('AnimState', function () { +describe('AnimState', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, null); expect(animState).to.be.ok; expect(animState.name).to.equal('state'); expect(animState.nodeCount).to.equal(1); }); - it('instansiates correctly with a blend tree', function () { + it('instansiates correctly with a blend tree', () => { const animState = new AnimState({ findParameter: () => {} }, 'state', 1, true, { type: ANIM_BLEND_1D, parameter: 'param', @@ -30,9 +31,9 @@ describe('AnimState', function () { }); - describe('#addAnimation', function () { + describe('#addAnimation', () => { - it('can add an animation to the AnimState instance', function () { + it('can add an animation to the AnimState instance', () => { const curves = [new AnimCurve(['path/to/entity'], 0, 0, INTERPOLATION_LINEAR)]; const inputs = [new AnimData(1, [0, 1, 2])]; diff --git a/test/framework/anim/controller/anim-transition.test.mjs b/test/framework/anim/controller/anim-transition.test.mjs index d78f46d013e..1f46cae0b7e 100644 --- a/test/framework/anim/controller/anim-transition.test.mjs +++ b/test/framework/anim/controller/anim-transition.test.mjs @@ -1,11 +1,12 @@ -import { AnimTransition } from '../../../../src/framework/anim/controller/anim-transition.js'; import { expect } from 'chai'; -describe('AnimTransition', function () { +import { AnimTransition } from '../../../../src/framework/anim/controller/anim-transition.js'; + +describe('AnimTransition', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { const animTransition = new AnimTransition({ from: 'fromState', to: 'toState' diff --git a/test/framework/anim/evaluator/anim-cache.test.mjs b/test/framework/anim/evaluator/anim-cache.test.mjs index feef4e16c31..9d13cf7f29c 100644 --- a/test/framework/anim/evaluator/anim-cache.test.mjs +++ b/test/framework/anim/evaluator/anim-cache.test.mjs @@ -1,33 +1,34 @@ +import { expect } from 'chai'; + +import { INTERPOLATION_STEP, INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; import { AnimCache } from '../../../../src/framework/anim/evaluator/anim-cache.js'; import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; -import { INTERPOLATION_STEP, INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; -import { expect } from 'chai'; -describe('AnimCache', function () { +describe('AnimCache', () => { const animCache = new AnimCache(); const input = new AnimData(1, [0, 1, 2]); const output = new AnimData(3, [0, 0, 0, 1, 2, 3, 2, 4, 6]); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animCache).to.be.ok; }); }); - describe('#update', function () { + describe('#update', () => { - it('can update the normalized time of the cache', function () { + it('can update the normalized time of the cache', () => { animCache.update(1.25, input.data); expect(animCache._t).to.equal(0.25); }); }); - describe('#eval', function () { + describe('#eval', () => { - it('can retrieve the step output keyframe value for a given input key', function () { + it('can retrieve the step output keyframe value for a given input key', () => { const result = [0, 0, 0]; animCache.update(0, input.data); animCache.eval(result, INTERPOLATION_STEP, output); @@ -43,7 +44,7 @@ describe('AnimCache', function () { expect(result).to.deep.equal([1, 2, 3]); }); - it('can retrieve the linear output keyframe value for a given input key', function () { + it('can retrieve the linear output keyframe value for a given input key', () => { const result = [0, 0, 0]; animCache.update(0, input.data); animCache.eval(result, INTERPOLATION_LINEAR, output); diff --git a/test/framework/anim/evaluator/anim-clip.test.mjs b/test/framework/anim/evaluator/anim-clip.test.mjs index a70458bb1c0..c3fa62d6225 100644 --- a/test/framework/anim/evaluator/anim-clip.test.mjs +++ b/test/framework/anim/evaluator/anim-clip.test.mjs @@ -1,15 +1,17 @@ -import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; -import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; -import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; +import { expect } from 'chai'; + +import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; import { AnimClip } from '../../../../src/framework/anim/evaluator/anim-clip.js'; +import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; +import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; import { AnimEvents } from '../../../../src/framework/anim/evaluator/anim-events.js'; -import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; -import { expect } from 'chai'; +import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; + -describe('AnimClip', function () { +describe('AnimClip', () => { let animClip; - beforeEach(function () { + beforeEach(() => { const curves = [new AnimCurve(['path/to/entity'], 0, 0, INTERPOLATION_LINEAR)]; const inputs = [new AnimData(1, [0, 1, 2])]; const outputs = [new AnimData(3, [0, 0, 0, 1, 2, 3, 2, 4, 6])]; @@ -24,9 +26,9 @@ describe('AnimClip', function () { }); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animClip).to.be.ok; expect(animClip.name).to.equal('track'); expect(animClip.track.name).to.equal('track'); @@ -38,18 +40,18 @@ describe('AnimClip', function () { }); - describe('#_update', function () { + describe('#_update', () => { - it('can update the clip\'s snapshot by a given deltaTime', function () { + it('can update the clip\'s snapshot by a given deltaTime', () => { animClip._update(0.5); expect(animClip.snapshot._results[0]).to.deep.equal([0.5, 1, 1.5]); }); }); - describe('#pause', function () { + describe('#pause', () => { - it('can stop the clip from updating', function () { + it('can stop the clip from updating', () => { animClip.pause(); animClip._update(0.5); expect(animClip.snapshot._results[0]).to.deep.equal([0, 0, 0]); @@ -57,9 +59,9 @@ describe('AnimClip', function () { }); - describe('#stop', function () { + describe('#stop', () => { - it('pauses the clip and moves the cursor to the start', function () { + it('pauses the clip and moves the cursor to the start', () => { animClip._update(0.5); animClip.stop(); animClip._update(0.5); @@ -68,9 +70,9 @@ describe('AnimClip', function () { }); - describe('#reset', function () { + describe('#reset', () => { - it('moves the cursor to the start', function () { + it('moves the cursor to the start', () => { animClip._update(0.5); animClip.reset(); animClip._update(0); @@ -79,9 +81,9 @@ describe('AnimClip', function () { }); - describe('#resume', function () { + describe('#resume', () => { - it('moves the cursor to the start', function () { + it('moves the cursor to the start', () => { animClip.pause(); animClip.resume(); animClip._update(0.5); @@ -90,9 +92,9 @@ describe('AnimClip', function () { }); - describe('#play', function () { + describe('#play', () => { - it('plays the clip from the beginning', function () { + it('plays the clip from the beginning', () => { animClip._update(0.5); animClip.pause(); animClip.play(); @@ -102,9 +104,9 @@ describe('AnimClip', function () { }); - describe('#time', function () { + describe('#time', () => { - it('aligns the clips eventCursor property when setting the time', function () { + it('aligns the clips eventCursor property when setting the time', () => { expect(animClip.eventCursor).to.equal(0); animClip.time = 1.1; expect(animClip.eventCursor).to.equal(2); @@ -114,7 +116,7 @@ describe('AnimClip', function () { expect(animClip.eventCursor).to.equal(0); }); - it('updates the clips eventCursor property as the clip updates forwards', function () { + it('updates the clips eventCursor property as the clip updates forwards', () => { expect(animClip.time).to.equal(0); expect(animClip.eventCursor).to.equal(0); animClip._update(0.55); @@ -131,7 +133,7 @@ describe('AnimClip', function () { expect(animClip.eventCursor).to.equal(0); }); - it('updates the clips eventCursor property as the clip updates backwards', function () { + it('updates the clips eventCursor property as the clip updates backwards', () => { animClip.speed = -1; animClip.time = 2; expect(animClip.time).to.equal(2); diff --git a/test/framework/anim/evaluator/anim-curve.test.mjs b/test/framework/anim/evaluator/anim-curve.test.mjs index 2e39838e286..5dca48c5859 100644 --- a/test/framework/anim/evaluator/anim-curve.test.mjs +++ b/test/framework/anim/evaluator/anim-curve.test.mjs @@ -1,8 +1,9 @@ -import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; -import { INTERPOLATION_CUBIC } from '../../../../src/framework/anim/constants.js'; import { expect } from 'chai'; -describe('AnimCurve', function () { +import { INTERPOLATION_CUBIC } from '../../../../src/framework/anim/constants.js'; +import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; + +describe('AnimCurve', () => { const animCurve = new AnimCurve( ['path/to/entity1', 'path/to/entity2'], 1, @@ -10,42 +11,42 @@ describe('AnimCurve', function () { INTERPOLATION_CUBIC ); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animCurve).to.be.ok; }); }); - describe('#paths', function () { + describe('#paths', () => { - it('can retrieve the curve paths', function () { + it('can retrieve the curve paths', () => { expect(animCurve.paths.length).to.equal(2); expect(animCurve.paths).to.deep.equal(['path/to/entity1', 'path/to/entity2']); }); }); - describe('#input', function () { + describe('#input', () => { - it('can retrieve the input value', function () { + it('can retrieve the input value', () => { expect(animCurve.input).to.equal(1); }); }); - describe('#output', function () { + describe('#output', () => { - it('can retrieve the output value', function () { + it('can retrieve the output value', () => { expect(animCurve.output).to.equal(2); }); }); - describe('#interpolation', function () { + describe('#interpolation', () => { - it('can retrieve the interpolation value', function () { + it('can retrieve the interpolation value', () => { expect(animCurve.interpolation).to.equal(INTERPOLATION_CUBIC); }); diff --git a/test/framework/anim/evaluator/anim-data.test.mjs b/test/framework/anim/evaluator/anim-data.test.mjs index 1f4522c45f3..d66fe3b301e 100644 --- a/test/framework/anim/evaluator/anim-data.test.mjs +++ b/test/framework/anim/evaluator/anim-data.test.mjs @@ -1,30 +1,31 @@ -import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; import { expect } from 'chai'; -describe('AnimData', function () { +import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; + +describe('AnimData', () => { - describe('#constructor', function () { + describe('#constructor', () => { const animData = new AnimData(1, [0, 1, 2]); - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animData).to.be.ok; }); }); - describe('#components', function () { + describe('#components', () => { const animData = new AnimData(1, [0, 1, 2]); - it('can retrieve the number of components', function () { + it('can retrieve the number of components', () => { expect(animData.components).to.equal(1); }); }); - describe('#data', function () { + describe('#data', () => { const animData = new AnimData(1, [0, 1, 2]); - it('can retrieve the number of components', function () { + it('can retrieve the number of components', () => { expect(animData.data.length).to.equal(3); expect(animData.data).to.deep.equal([0, 1, 2]); }); diff --git a/test/framework/anim/evaluator/anim-evaluator.test.mjs b/test/framework/anim/evaluator/anim-evaluator.test.mjs index b6e086615e1..fe8a48bc04f 100644 --- a/test/framework/anim/evaluator/anim-evaluator.test.mjs +++ b/test/framework/anim/evaluator/anim-evaluator.test.mjs @@ -1,22 +1,22 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + +import { DefaultAnimBinder } from '../../../../src/framework/anim/binder/default-anim-binder.js'; import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; -import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; import { AnimClip } from '../../../../src/framework/anim/evaluator/anim-clip.js'; +import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; import { AnimEvaluator } from '../../../../src/framework/anim/evaluator/anim-evaluator.js'; -import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; import { AnimEvents } from '../../../../src/framework/anim/evaluator/anim-events.js'; +import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; import { Application } from '../../../../src/framework/application.js'; -import { DefaultAnimBinder } from '../../../../src/framework/anim/binder/default-anim-binder.js'; -import { GraphNode } from '../../../../src/scene/graph-node.js'; import { NullGraphicsDevice } from '../../../../src/platform/graphics/null/null-graphics-device.js'; +import { GraphNode } from '../../../../src/scene/graph-node.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('AnimEvaluator', function () { +describe('AnimEvaluator', () => { - it('AnimEvaluator: update with clip blending', function () { + it('AnimEvaluator: update with clip blending', () => { const canvas = new HTMLCanvasElement(500, 500); const app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); @@ -89,7 +89,7 @@ describe('AnimEvaluator', function () { expect(child1.localPosition.z).to.equal(0); }); - it('AnimEvaluator: update without clip blending', function () { + it('AnimEvaluator: update without clip blending', () => { const canvas = new HTMLCanvasElement(500, 500); const app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); diff --git a/test/framework/anim/evaluator/anim-events.test.mjs b/test/framework/anim/evaluator/anim-events.test.mjs index 2905d63e963..fb4e5ca15d0 100644 --- a/test/framework/anim/evaluator/anim-events.test.mjs +++ b/test/framework/anim/evaluator/anim-events.test.mjs @@ -1,7 +1,8 @@ -import { AnimEvents } from '../../../../src/framework/anim/evaluator/anim-events.js'; import { expect } from 'chai'; -describe('AnimEvents', function () { +import { AnimEvents } from '../../../../src/framework/anim/evaluator/anim-events.js'; + +describe('AnimEvents', () => { const animEvents = new AnimEvents([ { name: 'event2', @@ -15,26 +16,26 @@ describe('AnimEvents', function () { } ]); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animEvents).to.be.ok; }); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('sorts the events', function () { + it('sorts the events', () => { expect(animEvents.events[0].name).to.equal('event1'); expect(animEvents.events[1].name).to.equal('event2'); }); }); - describe('#events', function () { + describe('#events', () => { - it('returns the events stored in the instance', function () { + it('returns the events stored in the instance', () => { expect(animEvents.events[0].name).to.equal('event1'); expect(animEvents.events[0].time).to.equal(0.5); expect(animEvents.events[0].property).to.equal(false); diff --git a/test/framework/anim/evaluator/anim-snapshot.test.mjs b/test/framework/anim/evaluator/anim-snapshot.test.mjs index ab823883735..27703a223af 100644 --- a/test/framework/anim/evaluator/anim-snapshot.test.mjs +++ b/test/framework/anim/evaluator/anim-snapshot.test.mjs @@ -1,20 +1,22 @@ -import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; -import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; +import { expect } from 'chai'; + +import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; +import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; import { AnimSnapshot } from '../../../../src/framework/anim/evaluator/anim-snapshot.js'; -import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; -import { expect } from 'chai'; +import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; + -describe('AnimSnapshot', function () { +describe('AnimSnapshot', () => { const curves = [new AnimCurve(['path/to/entity'], 0, 0, INTERPOLATION_LINEAR)]; const inputs = [new AnimData(1, [0, 1, 2])]; const outputs = [new AnimData(3, [0, 0, 0, 1, 2, 3, 2, 4, 6])]; const animTrack = new AnimTrack('track', 2, inputs, outputs, curves); const animSnapshot = new AnimSnapshot(animTrack); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animSnapshot).to.be.ok; expect(animSnapshot._name).to.equal('trackSnapshot'); expect(animSnapshot._time).to.equal(-1); diff --git a/test/framework/anim/evaluator/anim-target-value.test.mjs b/test/framework/anim/evaluator/anim-target-value.test.mjs index 0b841ca2664..147a2a67572 100644 --- a/test/framework/anim/evaluator/anim-target-value.test.mjs +++ b/test/framework/anim/evaluator/anim-target-value.test.mjs @@ -1,12 +1,13 @@ -import { AnimTargetValue } from '../../../../src/framework/anim/evaluator/anim-target-value.js'; -import { ANIM_LAYER_ADDITIVE, ANIM_LAYER_OVERWRITE } from '../../../../src/framework/anim/controller/constants.js'; import { expect } from 'chai'; -describe('AnimTargetValue', function () { +import { ANIM_LAYER_ADDITIVE, ANIM_LAYER_OVERWRITE } from '../../../../src/framework/anim/controller/constants.js'; +import { AnimTargetValue } from '../../../../src/framework/anim/evaluator/anim-target-value.js'; + +describe('AnimTargetValue', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly with an object', function () { + it('instantiates correctly with an object', () => { const mockComponent = { layers: [ { @@ -25,9 +26,9 @@ describe('AnimTargetValue', function () { }); - describe('#setMask', function () { + describe('#setMask', () => { - it('sets dirty to true if normalizeWeights is true', function () { + it('sets dirty to true if normalizeWeights is true', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -47,7 +48,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.dirty).to.equal(true); }); - it('doesn\'t set dirty to true if normalizeWeights is false', function () { + it('doesn\'t set dirty to true if normalizeWeights is false', () => { const mockComponent = { normalizeWeights: false, layers: [ @@ -67,7 +68,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.dirty).to.equal(false); }); - it('sets the indexed mask value to the given value', function () { + it('sets the indexed mask value to the given value', () => { const mockComponent = { normalizeWeights: false, layers: [ @@ -87,7 +88,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.mask[0]).to.equal(1); }); - it('sets the previous mask values to 0 if normalizeWeights is true and the layers blend type is overwrite', function () { + it('sets the previous mask values to 0 if normalizeWeights is true and the layers blend type is overwrite', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -107,7 +108,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.mask[0]).to.equal(0); }); - it('doesn\'t set the previous mask value to 0 if normalizeWeights is true and the layers blend type is additive', function () { + it('doesn\'t set the previous mask value to 0 if normalizeWeights is true and the layers blend type is additive', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -127,7 +128,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.mask[0]).to.equal(1); }); - it('doesn\'t set the previous mask value to 0 if normalizeWeights is false and the layers blend type is overwrite', function () { + it('doesn\'t set the previous mask value to 0 if normalizeWeights is false and the layers blend type is overwrite', () => { const mockComponent = { normalizeWeights: false, layers: [ @@ -147,7 +148,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.mask[0]).to.equal(1); }); - it('doesn\'t set the previous mask value to 0 if normalizeWeights is false and the layers blend type is additive', function () { + it('doesn\'t set the previous mask value to 0 if normalizeWeights is false and the layers blend type is additive', () => { const mockComponent = { normalizeWeights: false, layers: [ @@ -169,9 +170,9 @@ describe('AnimTargetValue', function () { }); - describe('#updateWeights', function () { + describe('#updateWeights', () => { - it('sets the instances weights to that of the component\'s layers weights', function () { + it('sets the instances weights to that of the component\'s layers weights', () => { const mockComponent = { layers: [ { @@ -190,7 +191,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.weights).to.deep.equal(new Float32Array([1, 2])); }); - it('sets the total weight to the sum of all the component\'s layers weights and their masks', function () { + it('sets the total weight to the sum of all the component\'s layers weights and their masks', () => { const mockComponent = { layers: [ { @@ -215,9 +216,9 @@ describe('AnimTargetValue', function () { }); - describe('#getWeight', function () { + describe('#getWeight', () => { - it('calls updateWeights if dirty is true', function () { + it('calls updateWeights if dirty is true', () => { const mockComponent = { layers: [ { @@ -240,7 +241,7 @@ describe('AnimTargetValue', function () { expect(updateWeightsCalled).to.equal(true); }); - it('does not call updateWeights if dirty is false', function () { + it('does not call updateWeights if dirty is false', () => { const mockComponent = { layers: [ { @@ -263,7 +264,7 @@ describe('AnimTargetValue', function () { expect(updateWeightsCalled).to.equal(false); }); - it('returns 0 when the indexed mask is 0', function () { + it('returns 0 when the indexed mask is 0', () => { const mockComponent = { layers: [ { @@ -281,7 +282,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.getWeight(0)).to.equal(0); }); - it('returns 1 when the indexed mask is 1', function () { + it('returns 1 when the indexed mask is 1', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -300,7 +301,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.getWeight(0)).to.equal(1); }); - it('returns 0 when normalizeWeights is true and totalWeight is 0', function () { + it('returns 0 when normalizeWeights is true and totalWeight is 0', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -322,7 +323,7 @@ describe('AnimTargetValue', function () { expect(weight).to.equal(0); }); - it('returns a normalized weight when normalizeWeights is true and totalWeight is non 0', function () { + it('returns a normalized weight when normalizeWeights is true and totalWeight is non 0', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -344,7 +345,7 @@ describe('AnimTargetValue', function () { expect(weight).to.equal(0.2); }); - it('returns a weight when normalizeWeights is false and totalWeight is non 0', function () { + it('returns a weight when normalizeWeights is false and totalWeight is non 0', () => { const mockComponent = { normalizeWeights: false, layers: [ @@ -368,9 +369,9 @@ describe('AnimTargetValue', function () { }); - describe('#updateValue', function () { + describe('#updateValue', () => { - it('can set a vector', function () { + it('can set a vector', () => { const mockComponent = { layers: [ { @@ -386,7 +387,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([1, 1, 1]); }); - it('can set a normalized vector', function () { + it('can set a normalized vector', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -403,7 +404,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([1, 1, 1]); }); - it('can set a quat', function () { + it('can set a quat', () => { const mockComponent = { layers: [ { @@ -419,7 +420,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([1, 0, 0, 0]); }); - it('can set a normalized quat', function () { + it('can set a normalized quat', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -436,7 +437,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([1, 0, 0, 0]); }); - it('can blend two additive vectors together', function () { + it('can blend two additive vectors together', () => { const mockComponent = { layers: [ { @@ -459,7 +460,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([3, 3, 3]); }); - it('can blend two additive vectors together with normalized weights', function () { + it('can blend two additive vectors together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -483,7 +484,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([1.25, 1.25, 1.25]); }); - it('can blend two additive quats together', function () { + it('can blend two additive quats together', () => { const mockComponent = { layers: [ { @@ -506,7 +507,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([0, 0, 1, 0]); }); - it('can blend two additive quats together with normalized weights', function () { + it('can blend two additive quats together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -536,7 +537,7 @@ describe('AnimTargetValue', function () { }); - it('can blend two overwrite vectors together', function () { + it('can blend two overwrite vectors together', () => { const mockComponent = { layers: [ { @@ -559,7 +560,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([2, 2, 2]); }); - it('can blend two overwrite vectors together with normalized weights', function () { + it('can blend two overwrite vectors together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -583,7 +584,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([2, 2, 2]); }); - it('can blend two overwrite quats together', function () { + it('can blend two overwrite quats together', () => { const mockComponent = { layers: [ { @@ -606,7 +607,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([0, 1, 0, 0]); }); - it('can blend two overwrite quats together with normalized weights', function () { + it('can blend two overwrite quats together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -630,7 +631,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([0, 1, 0, 0]); }); - it('can blend one additive and one overwrite vector together', function () { + it('can blend one additive and one overwrite vector together', () => { const mockComponent = { layers: [ { @@ -653,7 +654,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([2, 2, 2]); }); - it('can blend one additive and one overwrite vector together', function () { + it('can blend one additive and one overwrite vector together', () => { const mockComponent = { layers: [ { @@ -676,7 +677,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([2, 2, 2]); }); - it('can blend one additive and one overwrite vector together with normalized weights', function () { + it('can blend one additive and one overwrite vector together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -700,7 +701,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([2, 2, 2]); }); - it('can blend one additive and one overwrite quat together', function () { + it('can blend one additive and one overwrite quat together', () => { const mockComponent = { layers: [ { @@ -723,7 +724,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([0, 1, 0, 0]); }); - it('can blend one additive and one overwrite quat together with normalized weights', function () { + it('can blend one additive and one overwrite quat together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -747,7 +748,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([0, 1, 0, 0]); }); - it('can blend one overwrite and one additive vector together', function () { + it('can blend one overwrite and one additive vector together', () => { const mockComponent = { layers: [ { @@ -770,7 +771,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([3, 3, 3]); }); - it('can blend one overwrite and one additive vector together with normalized weights', function () { + it('can blend one overwrite and one additive vector together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ @@ -794,7 +795,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([1.25, 1.25, 1.25]); }); - it('can blend one overwrite and one additive quat together', function () { + it('can blend one overwrite and one additive quat together', () => { const mockComponent = { layers: [ { @@ -817,7 +818,7 @@ describe('AnimTargetValue', function () { expect(animTargetValue.value).to.deep.equal([0, 0, 1, 0]); }); - it('can blend one overwrite and one additive quat together with normalized weights', function () { + it('can blend one overwrite and one additive quat together with normalized weights', () => { const mockComponent = { normalizeWeights: true, layers: [ diff --git a/test/framework/anim/evaluator/anim-target.test.mjs b/test/framework/anim/evaluator/anim-target.test.mjs index 7df50812dc3..a9dc6cb436b 100644 --- a/test/framework/anim/evaluator/anim-target.test.mjs +++ b/test/framework/anim/evaluator/anim-target.test.mjs @@ -1,11 +1,12 @@ -import { AnimTarget } from '../../../../src/framework/anim/evaluator/anim-target.js'; import { expect } from 'chai'; -describe('AnimTarget', function () { +import { AnimTarget } from '../../../../src/framework/anim/evaluator/anim-target.js'; + +describe('AnimTarget', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly with an object', function () { + it('instantiates correctly with an object', () => { const func = { set: 'set', get: 'get' @@ -21,7 +22,7 @@ describe('AnimTarget', function () { expect(animTarget.isTransform).to.equal(false); }); - it('instantiates correctly with a function', function () { + it('instantiates correctly with a function', () => { const func = () => {}; const animTarget = new AnimTarget(func, 'vector', 3, 'path/to/entity'); @@ -34,7 +35,7 @@ describe('AnimTarget', function () { expect(animTarget.isTransform).to.equal(false); }); - it('instantiates correctly with a transform path', function () { + it('instantiates correctly with a transform path', () => { const func = () => {}; const animTarget = new AnimTarget(func, 'vector', 3, 'path/to/entity/localScale'); diff --git a/test/framework/anim/evaluator/anim-track.test.mjs b/test/framework/anim/evaluator/anim-track.test.mjs index e63095300f0..2497bd61dfa 100644 --- a/test/framework/anim/evaluator/anim-track.test.mjs +++ b/test/framework/anim/evaluator/anim-track.test.mjs @@ -1,19 +1,21 @@ -import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; -import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; +import { expect } from 'chai'; + +import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; import { AnimCurve } from '../../../../src/framework/anim/evaluator/anim-curve.js'; +import { AnimData } from '../../../../src/framework/anim/evaluator/anim-data.js'; import { AnimSnapshot } from '../../../../src/framework/anim/evaluator/anim-snapshot.js'; -import { INTERPOLATION_LINEAR } from '../../../../src/framework/anim/constants.js'; -import { expect } from 'chai'; +import { AnimTrack } from '../../../../src/framework/anim/evaluator/anim-track.js'; + -describe('AnimTrack', function () { +describe('AnimTrack', () => { const curves = [new AnimCurve(['path/to/entity'], 0, 0, INTERPOLATION_LINEAR)]; const inputs = [new AnimData(1, [0, 1, 2])]; const outputs = [new AnimData(3, [0, 0, 0, 1, 2, 3, 2, 4, 6])]; const animTrack = new AnimTrack('track', 2, inputs, outputs, curves); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(animTrack).to.be.ok; expect(animTrack.name).to.equal('track'); expect(animTrack.duration).to.equal(2); @@ -24,9 +26,9 @@ describe('AnimTrack', function () { }); - describe('#eval', function () { + describe('#eval', () => { - it('correctly updates a given snapshot', function () { + it('correctly updates a given snapshot', () => { const snapshot = new AnimSnapshot(animTrack); animTrack.eval(0, snapshot); expect(snapshot._results[0]).to.deep.equal([0, 0, 0]); @@ -40,12 +42,12 @@ describe('AnimTrack', function () { }); -describe('EmptyAnimTrack', function () { +describe('EmptyAnimTrack', () => { const emptyAnimTrack = AnimTrack.EMPTY; - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { expect(emptyAnimTrack).to.be.ok; expect(emptyAnimTrack.name).to.equal('empty'); expect(emptyAnimTrack.duration).to.equal(Number.MAX_VALUE); diff --git a/test/framework/anim/state-graph/anim-state-graph.test.mjs b/test/framework/anim/state-graph/anim-state-graph.test.mjs index a7cc0b12cd5..5e6d0a0c552 100644 --- a/test/framework/anim/state-graph/anim-state-graph.test.mjs +++ b/test/framework/anim/state-graph/anim-state-graph.test.mjs @@ -1,11 +1,12 @@ -import { AnimStateGraph } from '../../../../src/framework/anim/state-graph/anim-state-graph.js'; import { expect } from 'chai'; -describe('AnimStateGraph', function () { +import { AnimStateGraph } from '../../../../src/framework/anim/state-graph/anim-state-graph.js'; + +describe('AnimStateGraph', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly with data layers as an object', function () { + it('instantiates correctly with data layers as an object', () => { const data = { 'layers': { '0': { @@ -42,7 +43,7 @@ describe('AnimStateGraph', function () { expect(animStateGraph.layers[0].states[1].name).to.equal('New State'); }); - it('instantiates correctly with data layers as an array', function () { + it('instantiates correctly with data layers as an array', () => { const data = { 'layers': [ { diff --git a/test/framework/application.test.mjs b/test/framework/application.test.mjs index af1276270a8..a583b56bf60 100644 --- a/test/framework/application.test.mjs +++ b/test/framework/application.test.mjs @@ -1,28 +1,28 @@ -import { FILLMODE_KEEP_ASPECT, RESOLUTION_FIXED } from '../../src/framework/constants.js'; +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../src/framework/application.js'; import { AssetRegistry } from '../../src/framework/asset/asset-registry.js'; -import { BatchManager } from '../../src/scene/batching/batch-manager.js'; import { ComponentSystemRegistry } from '../../src/framework/components/registry.js'; +import { FILLMODE_KEEP_ASPECT, RESOLUTION_FIXED } from '../../src/framework/constants.js'; import { Entity } from '../../src/framework/entity.js'; -import { GraphicsDevice } from '../../src/platform/graphics/graphics-device.js'; +import { ResourceLoader } from '../../src/framework/handlers/loader.js'; import { I18n } from '../../src/framework/i18n/i18n.js'; import { Lightmapper } from '../../src/framework/lightmapper/lightmapper.js'; -import { ResourceLoader } from '../../src/framework/handlers/loader.js'; -import { Scene } from '../../src/scene/scene.js'; import { SceneRegistry } from '../../src/framework/scene-registry.js'; import { ScriptRegistry } from '../../src/framework/script/script-registry.js'; import { XrManager } from '../../src/framework/xr/xr-manager.js'; +import { GraphicsDevice } from '../../src/platform/graphics/graphics-device.js'; import { NullGraphicsDevice } from '../../src/platform/graphics/null/null-graphics-device.js'; +import { BatchManager } from '../../src/scene/batching/batch-manager.js'; +import { Scene } from '../../src/scene/scene.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('Application', function () { +describe('Application', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('support no options', function () { + it('support no options', () => { const canvas = new HTMLCanvasElement(500, 500); const app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); @@ -53,14 +53,14 @@ describe('Application', function () { }); - describe('#destroy', function () { + describe('#destroy', () => { - it('destroys the application', function () { + it('destroys the application', () => { const canvas = new HTMLCanvasElement(500, 500); const app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); app.destroy(); -// expect(app.assets).to.be.null; + // expect(app.assets).to.be.null; expect(app.batcher).to.be.null; expect(app.elementInput).to.be.null; expect(app.gamepads).to.be.null; @@ -76,7 +76,7 @@ describe('Application', function () { expect(app.scripts).to.be.null; expect(app.systems).to.be.null; expect(app.touch).to.be.null; -// expect(app.xr).to.be.null; + // expect(app.xr).to.be.null; }); }); diff --git a/test/framework/asset/asset-list-loader.test.mjs b/test/framework/asset/asset-list-loader.test.mjs index 254e11740c7..ec9f626e18f 100644 --- a/test/framework/asset/asset-list-loader.test.mjs +++ b/test/framework/asset/asset-list-loader.test.mjs @@ -1,34 +1,34 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../../src/framework/application.js'; import { AssetListLoader } from '../../../src/framework/asset/asset-list-loader.js'; import { Asset } from '../../../src/framework/asset/asset.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('AssetListLoader', function () { +describe('AssetListLoader', () => { let app; const assetPath = 'http://localhost:3000/test/test-assets/'; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { const assetListLoader = new AssetListLoader([], app.assets); expect(assetListLoader).to.be.ok; }); - it('stores a single asset', function () { + it('stores a single asset', () => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }) ]; @@ -36,7 +36,7 @@ describe('AssetListLoader', function () { expect(assetListLoader._assets.has(assets[0])).to.equal(true); }); - it('stores multiple assets', function () { + it('stores multiple assets', () => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) @@ -46,7 +46,7 @@ describe('AssetListLoader', function () { expect(assetListLoader._assets.has(assets[1])).to.equal(true); }); - it('stores single copies of duplicated assets', function () { + it('stores single copies of duplicated assets', () => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }) ]; @@ -54,7 +54,7 @@ describe('AssetListLoader', function () { expect(assetListLoader._assets.size).to.equal(1); }); - it('adds the supplied registry to any assets that do not have one', function () { + it('adds the supplied registry to any assets that do not have one', () => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }) ]; @@ -67,9 +67,9 @@ describe('AssetListLoader', function () { }); - describe('#ready', function () { + describe('#ready', () => { - it('can return a single loaded asset', function (done) { + it('can return a single loaded asset', (done) => { const asset = new Asset('model', 'container', { url: `${assetPath}test.glb` }); const assetListLoader = new AssetListLoader([asset], app.assets); assetListLoader.ready((assets) => { @@ -81,7 +81,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can return multiple loaded assets', function (done) { + it('can return multiple loaded assets', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) @@ -98,7 +98,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can return a single duplicated loaded asset', function (done) { + it('can return a single duplicated loaded asset', (done) => { const asset = new Asset('model', 'container', { url: `${assetPath}test.glb` }); const assetListLoader = new AssetListLoader([asset, asset], app.assets); assetListLoader.ready((assets) => { @@ -112,9 +112,9 @@ describe('AssetListLoader', function () { }); - describe('#load', function () { + describe('#load', () => { - it('can call the ready callback if an asset is already loaded', function (done) { + it('can call the ready callback if an asset is already loaded', (done) => { const asset = new Asset('model', 'container', { url: `${assetPath}test.glb` }); const assetListLoader = new AssetListLoader([asset], app.assets); asset.on('load', (asset) => { @@ -131,7 +131,7 @@ describe('AssetListLoader', function () { app.assets.load(asset); }); - it('can call the load callback if an asset is already loaded', function (done) { + it('can call the load callback if an asset is already loaded', (done) => { const asset = new Asset('model', 'container', { url: `${assetPath}test.glb` }); const assetListLoader = new AssetListLoader([asset], app.assets); asset.on('load', (asset) => { @@ -144,7 +144,7 @@ describe('AssetListLoader', function () { app.assets.load(asset); }); - it('can succeed if one asset is already loaded and another is not', function (done) { + it('can succeed if one asset is already loaded and another is not', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) @@ -167,7 +167,7 @@ describe('AssetListLoader', function () { app.assets.load(assets[0]); }); - it('can succeed if an asset is already loading', function (done) { + it('can succeed if an asset is already loading', (done) => { const asset = new Asset('model', 'container', { url: `${assetPath}test.glb` }); const assetListLoader = new AssetListLoader([asset], app.assets); app.assets.add(asset); @@ -182,7 +182,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can succeed if one asset is already loading and another is not', function (done) { + it('can succeed if one asset is already loading and another is not', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) @@ -202,7 +202,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can succeed if one asset is already loaded, another is loading and one is not loaded', function (done) { + it('can succeed if one asset is already loaded, another is loading and one is not loaded', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }), @@ -231,7 +231,7 @@ describe('AssetListLoader', function () { app.assets.load(assets[0]); }); - it('can succeed if multiple assets load the same url', function (done) { + it('can succeed if multiple assets load the same url', (done) => { const assets = [ new Asset('model1', 'container', { url: `${assetPath}test.glb` }), new Asset('model2', 'container', { url: `${assetPath}test.glb` }) @@ -248,7 +248,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can succeed if an empty list is passed in', function (done) { + it('can succeed if an empty list is passed in', (done) => { const assetListLoader = new AssetListLoader([], app.assets); assetListLoader.ready((assets) => { expect(assets.length).to.equal(0); @@ -257,7 +257,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can successfully load assets from ids that are in the registry', function (done) { + it('can successfully load assets from ids that are in the registry', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) @@ -272,7 +272,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can successfully load assets from ids that are not yet in the registry', function (done) { + it('can successfully load assets from ids that are not yet in the registry', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) @@ -287,7 +287,7 @@ describe('AssetListLoader', function () { app.assets.add(assets[1]); }); - it('can be called multiple times', function (done) { + it('can be called multiple times', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) @@ -301,7 +301,7 @@ describe('AssetListLoader', function () { assetListLoader.load(); }); - it('can fail gracefully', function (done) { + it('can fail gracefully', (done) => { const assets = [ new Asset('model', 'container', { url: `${assetPath}test.glb` }), new Asset('styling', 'css', { url: `${assetPath}test.css` }) diff --git a/test/framework/asset/asset-localized.test.mjs b/test/framework/asset/asset-localized.test.mjs index 87257f07803..794f03bf3d1 100644 --- a/test/framework/asset/asset-localized.test.mjs +++ b/test/framework/asset/asset-localized.test.mjs @@ -1,26 +1,26 @@ -import { LocalizedAsset } from '../../../src/framework/asset/asset-localized.js'; +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../../src/framework/application.js'; +import { LocalizedAsset } from '../../../src/framework/asset/asset-localized.js'; import { Asset } from '../../../src/framework/asset/asset.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('LocalizedAsset', function () { +describe('LocalizedAsset', () => { let app; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); - it('sets defaultAsset and localizedAsset to the same id if defaultAsset has no localization', function () { + it('sets defaultAsset and localizedAsset to the same id if defaultAsset has no localization', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); @@ -32,7 +32,7 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset.id); }); - it('does not add load and change events to the asset when autoLoad is false', function () { + it('does not add load and change events to the asset when autoLoad is false', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); @@ -44,7 +44,7 @@ describe('LocalizedAsset', function () { expect(asset.hasEvent('change')).to.equal(false); }); - it('adds load, change and remove events to the asset when autoLoad is true', function () { + it('adds load, change and remove events to the asset when autoLoad is true', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); @@ -58,7 +58,7 @@ describe('LocalizedAsset', function () { expect(asset.hasEvent('remove')).to.equal(true); }); - it('adds events to the asset when autoLoad becomes true later', function () { + it('adds events to the asset when autoLoad becomes true later', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); @@ -73,7 +73,7 @@ describe('LocalizedAsset', function () { expect(asset.hasEvent('remove')).to.equal(true); }); - it('picks the correct localizedAsset when the locale is already different', function () { + it('picks the correct localizedAsset when the locale is already different', () => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); @@ -91,7 +91,7 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset2.id); }); - it('changes the localized asset after defaultAsset and then the locale change', function () { + it('changes the localized asset after defaultAsset and then the locale change', () => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); @@ -110,7 +110,7 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset2.id); }); - it('removes events from the defaultAsset and localizedAsset is changed', function () { + it('removes events from the defaultAsset and localizedAsset is changed', () => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); @@ -142,7 +142,7 @@ describe('LocalizedAsset', function () { expect(asset2.hasEvent('remove')).to.equal(true); }); - it('propagates asset events to LocalizedAsset', function () { + it('propagates asset events to LocalizedAsset', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); @@ -155,15 +155,15 @@ describe('LocalizedAsset', function () { let changeFired = false; let removeFired = false; - la.on('load', function () { + la.on('load', () => { loadFired = true; }); - la.on('change', function () { + la.on('change', () => { changeFired = true; }); - la.on('remove', function () { + la.on('remove', () => { removeFired = true; }); @@ -176,7 +176,7 @@ describe('LocalizedAsset', function () { expect(removeFired).to.equal(true); }); - it('uses only the defaultAsset when disableLocalization is true', function () { + it('uses only the defaultAsset when disableLocalization is true', () => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); @@ -195,7 +195,7 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset.id); }); - it('falls back to defaultAsset when a null asset is set for a locale', function () { + it('falls back to defaultAsset when a null asset is set for a locale', () => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); @@ -213,11 +213,11 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset.id); }); - it('fires add:localized on setting a new locale', function (done) { + it('fires add:localized on setting a new locale', (done) => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); - asset.on('add:localized', function (locale, assetId) { + asset.on('add:localized', (locale, assetId) => { expect(locale).to.equal('fr'); expect(assetId).to.equal(asset2.id); done(); @@ -226,13 +226,13 @@ describe('LocalizedAsset', function () { asset.addLocalizedAssetId('fr', asset2.id); }); - it('fires remove:localized on removing a locale', function (done) { + it('fires remove:localized on removing a locale', (done) => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); asset.addLocalizedAssetId('fr', asset2.id); - asset.on('remove:localized', function (locale, assetId) { + asset.on('remove:localized', (locale, assetId) => { expect(locale).to.equal('fr'); expect(assetId).to.equal(asset2.id); done(); @@ -241,7 +241,7 @@ describe('LocalizedAsset', function () { asset.removeLocalizedAssetId('fr'); }); - it('updates the localizedAsset on setting a localized asset for the current locale', function () { + it('updates the localizedAsset on setting a localized asset for the current locale', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); const asset2 = new Asset('Localized Asset', 'texture'); @@ -256,7 +256,7 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset2.id); }); - it('updates the localizedAsset to the defaultAsset on removing a localized asset for the current locale', function () { + it('updates the localizedAsset to the defaultAsset on removing a localized asset for the current locale', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); const asset2 = new Asset('Localized Asset', 'texture'); @@ -273,7 +273,7 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset.id); }); - it('updates the localizedAsset on setting a localized asset for the current locale even if defaultAsset is added to the registry later', function () { + it('updates the localizedAsset on setting a localized asset for the current locale even if defaultAsset is added to the registry later', () => { const asset = new Asset('Default Asset', 'texture'); const asset2 = new Asset('Localized Asset', 'texture'); app.assets.add(asset2); @@ -290,7 +290,7 @@ describe('LocalizedAsset', function () { }); - it('switches LocalizedAsset to the defaultAsset by removing a localized asset from the registry', function () { + it('switches LocalizedAsset to the defaultAsset by removing a localized asset from the registry', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); const asset2 = new Asset('Localized Asset', 'texture'); @@ -308,7 +308,7 @@ describe('LocalizedAsset', function () { expect(la.localizedAsset).to.equal(asset.id); }); - it('keeps same localizedAsset and adds "add" event handler on removing the defaultAsset from the registry', function () { + it('keeps same localizedAsset and adds "add" event handler on removing the defaultAsset from the registry', () => { const asset = new Asset('Default Asset', 'texture'); app.assets.add(asset); const asset2 = new Asset('Localized Asset', 'texture'); @@ -322,34 +322,34 @@ describe('LocalizedAsset', function () { la.defaultAsset = asset; expect(la.localizedAsset).to.equal(asset2.id); - expect(app.assets.hasEvent('add:' + asset.id)).to.equal(false); + expect(app.assets.hasEvent(`add:${asset.id}`)).to.equal(false); app.assets.remove(asset); expect(la.localizedAsset).to.equal(asset2.id); - expect(app.assets.hasEvent('add:' + asset.id)).to.equal(true); + expect(app.assets.hasEvent(`add:${asset.id}`)).to.equal(true); }); - describe('#destroy', function () { + describe('#destroy', () => { - it('removes asset references and events', function () { + it('removes asset references and events', () => { const asset = new Asset('Default Asset', 'texture'); const la = new LocalizedAsset(app); la.defaultAsset = asset.id; - la.on('load', function () {}); - la.on('change', function () {}); - la.on('remove', function () {}); + la.on('load', () => {}); + la.on('change', () => {}); + la.on('remove', () => {}); - expect(app.assets.hasEvent('add:' + asset.id)).to.equal(true); + expect(app.assets.hasEvent(`add:${asset.id}`)).to.equal(true); expect(la.hasEvent('load')).to.equal(true); expect(la.hasEvent('change')).to.equal(true); expect(la.hasEvent('remove')).to.equal(true); la.destroy(); - expect(app.assets.hasEvent('add:' + asset.id)).to.equal(false); + expect(app.assets.hasEvent(`add:${asset.id}`)).to.equal(false); expect(la.hasEvent('load')).to.equal(false); expect(la.hasEvent('change')).to.equal(false); expect(la.hasEvent('remove')).to.equal(false); @@ -358,11 +358,11 @@ describe('LocalizedAsset', function () { la2.defaultAsset = asset.id; la2.autoLoad = true; - expect(app.assets.hasEvent('add:' + asset.id)).to.equal(true); + expect(app.assets.hasEvent(`add:${asset.id}`)).to.equal(true); app.assets.add(asset); - expect(app.assets.hasEvent('add:' + asset.id)).to.equal(false); + expect(app.assets.hasEvent(`add:${asset.id}`)).to.equal(false); expect(asset.hasEvent('load')).to.equal(true); expect(asset.hasEvent('change')).to.equal(true); diff --git a/test/framework/asset/asset-registry.test.mjs b/test/framework/asset/asset-registry.test.mjs index 694ec461347..feb91a7fec4 100644 --- a/test/framework/asset/asset-registry.test.mjs +++ b/test/framework/asset/asset-registry.test.mjs @@ -1,37 +1,37 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; +import { restore, spy } from 'sinon'; + import { Application } from '../../../src/framework/application.js'; -import { Asset } from '../../../src/framework/asset/asset.js'; import { AssetRegistry } from '../../../src/framework/asset/asset-registry.js'; -import { GlbContainerResource } from '../../../src/framework/parsers/glb-container-resource.js'; +import { Asset } from '../../../src/framework/asset/asset.js'; import { ResourceLoader } from '../../../src/framework/handlers/loader.js'; -import { http, Http } from '../../../src/platform/net/http.js'; +import { GlbContainerResource } from '../../../src/framework/parsers/glb-container-resource.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; +import { http, Http } from '../../../src/platform/net/http.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -import { restore, spy } from 'sinon'; -describe('AssetRegistry', function () { +describe('AssetRegistry', () => { let app; let retryDelay; - beforeEach(function () { + beforeEach(() => { retryDelay = Http.retryDelay; Http.retryDelay = 1; const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); }); - afterEach(function () { + afterEach(() => { app.destroy(); Http.retryDelay = retryDelay; restore(); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('instantiates correctly', function () { + it('instantiates correctly', () => { const resourceLoader = new ResourceLoader(app); const assetRegistry = new AssetRegistry(resourceLoader); @@ -40,9 +40,9 @@ describe('AssetRegistry', function () { }); - describe('#add', function () { + describe('#add', () => { - it('adds an asset', function () { + it('adds an asset', () => { const asset = new Asset('Test Asset', 'text', { url: 'fake/url/file.txt' }); @@ -55,9 +55,9 @@ describe('AssetRegistry', function () { }); - describe('#find', function () { + describe('#find', () => { - it('works after removing an asset', function () { + it('works after removing an asset', () => { const asset1 = new Asset('Asset 1', 'text', { url: 'fake/one/file.txt' }); @@ -81,9 +81,9 @@ describe('AssetRegistry', function () { }); - describe('#find + rename', function () { + describe('#find + rename', () => { - it('works after renaming an asset', function () { + it('works after renaming an asset', () => { const asset1 = new Asset('Asset 1', 'text', { url: 'fake/one/file.txt' }); @@ -105,9 +105,9 @@ describe('AssetRegistry', function () { }); - describe('#find + type', function () { + describe('#find + type', () => { - it('finds assets by name filtered by type', function () { + it('finds assets by name filtered by type', () => { const asset1 = new Asset('Asset 1', 'text', { url: 'fake/one/file.txt' }); @@ -124,9 +124,9 @@ describe('AssetRegistry', function () { }); - describe('#findAll + type', function () { + describe('#findAll + type', () => { - it('finds all assets by name filtered by type', function () { + it('finds all assets by name filtered by type', () => { const asset1 = new Asset('Asset 1', 'text', { url: 'fake/one/file.txt' }); @@ -156,9 +156,9 @@ describe('AssetRegistry', function () { }); - describe('#get', function () { + describe('#get', () => { - it('retrieves an asset by id', function () { + it('retrieves an asset by id', () => { const asset = new Asset('Test Asset', 'text', { url: 'fake/url/file.txt' }); @@ -171,9 +171,9 @@ describe('AssetRegistry', function () { }); - describe('#getByUrl', function () { + describe('#getByUrl', () => { - it('retrieves an asset by url', function () { + it('retrieves an asset by url', () => { const asset = new Asset('Test Asset', 'text', { url: 'fake/url/file.txt' }); @@ -184,7 +184,7 @@ describe('AssetRegistry', function () { expect(asset).to.equal(assetFromRegistry); }); - it('works after removing an asset', function () { + it('works after removing an asset', () => { const asset1 = new Asset('Asset 1', 'text', { url: 'fake/one/file.txt' }); @@ -208,9 +208,9 @@ describe('AssetRegistry', function () { }); - describe('#list', function () { + describe('#list', () => { - it('lists all assets', function () { + it('lists all assets', () => { const asset1 = new Asset('Asset 1', 'text', { url: 'fake/one/file.txt' }); @@ -234,12 +234,12 @@ describe('AssetRegistry', function () { }); - describe('#loadFromUrl', function () { + describe('#loadFromUrl', () => { const assetPath = 'http://localhost:3000/test/test-assets/'; - it('loads binary assets', function (done) { - app.assets.loadFromUrl(`${assetPath}test.bin`, 'binary', function (err, asset) { + it('loads binary assets', (done) => { + app.assets.loadFromUrl(`${assetPath}test.bin`, 'binary', (err, asset) => { expect(err).to.be.null; expect(asset).to.be.instanceof(Asset); expect(asset.resource).to.be.instanceof(ArrayBuffer); @@ -252,8 +252,8 @@ describe('AssetRegistry', function () { }); }); - it('loads container assets', function (done) { - app.assets.loadFromUrl(`${assetPath}test.glb`, 'container', function (err, asset) { + it('loads container assets', (done) => { + app.assets.loadFromUrl(`${assetPath}test.glb`, 'container', (err, asset) => { expect(err).to.be.null; expect(asset).to.be.instanceof(Asset); expect(asset.resource).to.be.instanceof(GlbContainerResource); @@ -261,17 +261,17 @@ describe('AssetRegistry', function () { }); }); - it('supports retry loading of container assets', function (done) { + it('supports retry loading of container assets', (done) => { spy(http, 'request'); app.loader.enableRetry(2); - app.assets.loadFromUrl(`${assetPath}someurl.glb`, 'container', function (err, asset) { + app.assets.loadFromUrl(`${assetPath}someurl.glb`, 'container', (err, asset) => { expect(http.request.callCount).to.equal(3); done(); }); }); - it('loads css assets', function (done) { - app.assets.loadFromUrl(`${assetPath}test.css`, 'css', function (err, asset) { + it('loads css assets', (done) => { + app.assets.loadFromUrl(`${assetPath}test.css`, 'css', (err, asset) => { expect(err).to.be.null; expect(asset).to.be.instanceof(Asset); expect(asset.resource).to.be.a('string'); @@ -280,8 +280,8 @@ describe('AssetRegistry', function () { }); }); - it.skip('loads html assets', function (done) { - app.assets.loadFromUrl(`${assetPath}test.html`, 'html', function (err, asset) { + it.skip('loads html assets', (done) => { + app.assets.loadFromUrl(`${assetPath}test.html`, 'html', (err, asset) => { expect(err).to.be.null; expect(asset).to.be.instanceof(Asset); expect(asset.resource).to.be.a('string'); @@ -289,8 +289,8 @@ describe('AssetRegistry', function () { }); }); - it('loads json assets', function (done) { - app.assets.loadFromUrl(`${assetPath}test.json`, 'json', function (err, asset) { + it('loads json assets', (done) => { + app.assets.loadFromUrl(`${assetPath}test.json`, 'json', (err, asset) => { expect(err).to.be.null; expect(asset).to.be.instanceof(Asset); expect(asset.resource).to.be.an.instanceof(Object); @@ -301,8 +301,8 @@ describe('AssetRegistry', function () { }); }); - it('loads shader assets', function (done) { - app.assets.loadFromUrl(`${assetPath}test.glsl`, 'shader', function (err, asset) { + it('loads shader assets', (done) => { + app.assets.loadFromUrl(`${assetPath}test.glsl`, 'shader', (err, asset) => { expect(err).to.be.null; expect(asset).to.be.instanceof(Asset); expect(asset.resource).to.be.a('string'); @@ -310,8 +310,8 @@ describe('AssetRegistry', function () { }); }); - it('loads text assets', function (done) { - app.assets.loadFromUrl(`${assetPath}test.txt`, 'text', function (err, asset) { + it('loads text assets', (done) => { + app.assets.loadFromUrl(`${assetPath}test.txt`, 'text', (err, asset) => { expect(err).to.be.null; expect(asset).to.be.instanceof(Asset); expect(asset.resource).to.be.a('string'); @@ -322,9 +322,9 @@ describe('AssetRegistry', function () { }); - describe('#remove', function () { + describe('#remove', () => { - it('removes by id', function () { + it('removes by id', () => { const asset1 = new Asset('Asset 1', 'text', { url: 'fake/one/file.txt' }); diff --git a/test/framework/asset/asset.test.mjs b/test/framework/asset/asset.test.mjs index 3e29ed8afae..c42396afa77 100644 --- a/test/framework/asset/asset.test.mjs +++ b/test/framework/asset/asset.test.mjs @@ -1,21 +1,21 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../../src/framework/application.js'; import { Asset } from '../../../src/framework/asset/asset.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('Asset', function () { +describe('Asset', () => { let app; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); @@ -30,15 +30,15 @@ describe('Asset', function () { 'ja': 'ja-JP' }; - describe('#getLocalizedAssetId', function () { + describe('#getLocalizedAssetId', () => { - it('should return null if no localizations exist', function () { + it('should return null if no localizations exist', () => { const asset = new Asset('asset', 'font'); asset.id = 1000; expect(asset.getLocalizedAssetId('en')).to.equal(null); }); - it('should return fallback language if available', function () { + it('should return fallback language if available', () => { const asset = new Asset('asset', 'font'); let id = 1000; @@ -54,7 +54,7 @@ describe('Asset', function () { } }); - it('should return fallback language if available', function () { + it('should return fallback language if available', () => { const asset = new Asset('asset', 'font'); let id = 1000; @@ -70,12 +70,12 @@ describe('Asset', function () { } }); - it('should return fallback language if available', function () { + it('should return fallback language if available', () => { const asset = new Asset('asset', 'font'); let id = 1; for (const key in DEFAULT_LOCALE_FALLBACKS) { - asset.addLocalizedAssetId(key + '-test', 1000 + id); // add other locale with same language which shouldn't be used + asset.addLocalizedAssetId(`${key}-test`, 1000 + id); // add other locale with same language which shouldn't be used asset.addLocalizedAssetId(DEFAULT_LOCALE_FALLBACKS[key], 2000 + id); id++; } @@ -87,7 +87,7 @@ describe('Asset', function () { } }); - it('zh-HK should return zh-HK if it exists', function () { + it('zh-HK should return zh-HK if it exists', () => { const asset = new Asset('asset', 'font'); asset.addLocalizedAssetId('zh-CN', 1); @@ -97,7 +97,7 @@ describe('Asset', function () { expect(asset.getLocalizedAssetId('zh-HK')).to.equal(2); }); - it('zh-HK should fallback to zh-TW', function () { + it('zh-HK should fallback to zh-TW', () => { const asset = new Asset('asset', 'font'); asset.addLocalizedAssetId('zh-CN', 1); @@ -106,7 +106,7 @@ describe('Asset', function () { expect(asset.getLocalizedAssetId('zh-HK')).to.equal(2); }); - it('zh-TW should fallback to zh-HK', function () { + it('zh-TW should fallback to zh-HK', () => { const asset = new Asset('asset', 'font'); asset.addLocalizedAssetId('zh-CN', 1); @@ -115,7 +115,7 @@ describe('Asset', function () { expect(asset.getLocalizedAssetId('zh-TW')).to.equal(2); }); - it('zh-SG should fallback to zh-CN', function () { + it('zh-SG should fallback to zh-CN', () => { const asset = new Asset('asset', 'font'); asset.addLocalizedAssetId('zh-HK', 1); diff --git a/test/framework/components/element/component.test.mjs b/test/framework/components/element/component.test.mjs index 9306cfb1ca7..5f02a2f2230 100644 --- a/test/framework/components/element/component.test.mjs +++ b/test/framework/components/element/component.test.mjs @@ -1,27 +1,26 @@ -import { LAYERID_UI } from '../../../../src/scene/constants.js'; +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../../../src/framework/application.js'; import { Entity } from '../../../../src/framework/entity.js'; import { NullGraphicsDevice } from '../../../../src/platform/graphics/null/null-graphics-device.js'; +import { LAYERID_UI } from '../../../../src/scene/constants.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; - -describe('ElementComponent', function () { +describe('ElementComponent', () => { let app; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('creates a default element component', function () { + it('creates a default element component', () => { const e = new Entity(); e.addComponent('element'); @@ -123,7 +122,7 @@ describe('ElementComponent', function () { }); - it('unbinds screen component on reparent', function () { + it('unbinds screen component on reparent', () => { const screen = new Entity(); screen.addComponent('screen'); app.root.addChild(screen); @@ -140,7 +139,7 @@ describe('ElementComponent', function () { expect(screen.screen._elements).to.not.include(e.element); }); - it('unbinds screen component on destroy', function () { + it('unbinds screen component on destroy', () => { const screen = new Entity(); screen.addComponent('screen'); app.root.addChild(screen); diff --git a/test/framework/components/layout-group/component.test.mjs b/test/framework/components/layout-group/component.test.mjs index 9f5daa4af52..3e3871799ff 100644 --- a/test/framework/components/layout-group/component.test.mjs +++ b/test/framework/components/layout-group/component.test.mjs @@ -1,16 +1,16 @@ -import { ELEMENTTYPE_GROUP } from '../../../../src/framework/components/element/constants.js'; +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; +import { restore, spy, stub } from 'sinon'; + import { Application } from '../../../../src/framework/application.js'; +import { ELEMENTTYPE_GROUP } from '../../../../src/framework/components/element/constants.js'; import { Entity } from '../../../../src/framework/entity.js'; import { NullGraphicsDevice } from '../../../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -import { restore, spy, stub } from 'sinon'; /** @typedef {import('../../../../src/framework/components/layout-group/system.js').LayoutGroupComponentSystem} LayoutGroupComponentSystem */ -describe('LayoutGroupComponent', function () { +describe('LayoutGroupComponent', () => { /** @type {Application} */ let app; /** @type {LayoutGroupComponentSystem} */ @@ -23,7 +23,7 @@ describe('LayoutGroupComponent', function () { let entity0_0_0; const buildLayoutGroupEntity = function (name) { - const entity = new Entity('myEntity' + name, app); + const entity = new Entity(`myEntity${name}`, app); app.systems.element.addComponent(entity, { type: ELEMENTTYPE_GROUP }); app.systems.layoutgroup.addComponent(entity); @@ -31,7 +31,7 @@ describe('LayoutGroupComponent', function () { return entity; }; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); system = app.systems.layoutgroup; @@ -51,12 +51,12 @@ describe('LayoutGroupComponent', function () { spy(entity0_0_0.layoutgroup, 'reflow'); }); - afterEach(function () { + afterEach(() => { restore(); app.destroy(); }); - it('reflows in ascending order of graph depth', function () { + it('reflows in ascending order of graph depth', () => { system.scheduleReflow(entity0_0.layoutgroup); system.scheduleReflow(entity0.layoutgroup); system.scheduleReflow(entity0_0_0.layoutgroup); @@ -71,13 +71,13 @@ describe('LayoutGroupComponent', function () { expect(entity0_0.layoutgroup.reflow.calledBefore(entity0_0_0.layoutgroup.reflow)).to.be.true; }); - it('reflows additional groups that are pushed during the reflow', function () { + it('reflows additional groups that are pushed during the reflow', () => { system.scheduleReflow(entity0.layoutgroup); let done = false; entity0.layoutgroup.reflow.restore(); - stub(entity0.layoutgroup, 'reflow').callsFake(function () { + stub(entity0.layoutgroup, 'reflow').callsFake(() => { if (!done) { done = true; system.scheduleReflow(entity0_0_0.layoutgroup); @@ -95,7 +95,7 @@ describe('LayoutGroupComponent', function () { expect(entity0_0.layoutgroup.reflow.calledBefore(entity0_0_0.layoutgroup.reflow)).to.be.true; }); - it('does not allow the same group to be pushed to the queue twice', function () { + it('does not allow the same group to be pushed to the queue twice', () => { system.scheduleReflow(entity0.layoutgroup); system.scheduleReflow(entity0.layoutgroup); @@ -104,13 +104,13 @@ describe('LayoutGroupComponent', function () { expect(entity0.layoutgroup.reflow.callCount).to.equal(1); }); - it('bails if the maximum iteration count is reached', function () { + it('bails if the maximum iteration count is reached', () => { stub(console, 'warn'); system.scheduleReflow(entity0.layoutgroup); entity0.layoutgroup.reflow.restore(); - stub(entity0.layoutgroup, 'reflow').callsFake(function () { + stub(entity0.layoutgroup, 'reflow').callsFake(() => { system.scheduleReflow(entity0.layoutgroup); }); diff --git a/test/framework/components/layout-group/layout-calculator.test.mjs b/test/framework/components/layout-group/layout-calculator.test.mjs index 3adcd0aadb2..8666ab672ed 100644 --- a/test/framework/components/layout-group/layout-calculator.test.mjs +++ b/test/framework/components/layout-group/layout-calculator.test.mjs @@ -1,20 +1,19 @@ -import { ORIENTATION_HORIZONTAL, ORIENTATION_VERTICAL } from '../../../../src/scene/constants.js'; +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + +import { Vec2 } from '../../../../src/core/math/vec2.js'; +import { Vec4 } from '../../../../src/core/math/vec4.js'; +import { Application } from '../../../../src/framework/application.js'; import { ELEMENTTYPE_GROUP } from '../../../../src/framework/components/element/constants.js'; import { FITTING_BOTH, FITTING_NONE, FITTING_SHRINK, FITTING_STRETCH } from '../../../../src/framework/components/layout-group/constants.js'; -import { Application } from '../../../../src/framework/application.js'; -import { Entity } from '../../../../src/framework/entity.js'; import { LayoutCalculator } from '../../../../src/framework/components/layout-group/layout-calculator.js'; -import { Vec2 } from '../../../../src/core/math/vec2.js'; -import { Vec4 } from '../../../../src/core/math/vec4.js'; +import { Entity } from '../../../../src/framework/entity.js'; import { NullGraphicsDevice } from '../../../../src/platform/graphics/null/null-graphics-device.js'; - -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; +import { ORIENTATION_HORIZONTAL, ORIENTATION_VERTICAL } from '../../../../src/scene/constants.js'; /** @typedef {import('../../../../src/framework/components/element/component.js').ElementComponent} ElementComponent */ -describe('LayoutCalculator', function () { +describe('LayoutCalculator', () => { /** @type {Application} */ let app; /** @type {LayoutCalculator} */ @@ -32,7 +31,7 @@ describe('LayoutCalculator', function () { let mixedHeightElementsWithLayoutChildComponents; // eslint-disable-line no-unused-vars const applyProperties = function (object, properties) { - Object.keys(properties).forEach(function (propertyName) { + Object.keys(properties).forEach((propertyName) => { object[propertyName] = properties[propertyName]; }); }; @@ -56,12 +55,12 @@ describe('LayoutCalculator', function () { }; const buildElements = function (elementSpecs) { - return elementSpecs.map(function (properties) { + return elementSpecs.map((properties) => { return buildElement(properties); }); }; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); calculator = new LayoutCalculator(); @@ -242,7 +241,7 @@ describe('LayoutCalculator', function () { ]); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); @@ -253,7 +252,7 @@ describe('LayoutCalculator', function () { const assertValues = function (property, values, options) { options = options || {}; - elements.forEach(function (element, i) { + elements.forEach((element, i) => { let propertyValue; if (property === 'x' || property === 'y') { propertyValue = element.entity.localPosition[property]; @@ -269,15 +268,15 @@ describe('LayoutCalculator', function () { }); }; - it('throws an error if provided with an unrecognized orientation', function () { - expect(function () { + it('throws an error if provided with an unrecognized orientation', () => { + expect(() => { elements = mixedWidthElements; options.orientation = 42; calculate(); }).to.throw('Unrecognized orientation value: 42'); }); - it('lays children out horizontally when orientation is ORIENTATION_HORIZONTAL', function () { + it('lays children out horizontally when orientation is ORIENTATION_HORIZONTAL', () => { elements = mixedWidthElements; options.orientation = ORIENTATION_HORIZONTAL; @@ -287,7 +286,7 @@ describe('LayoutCalculator', function () { assertValues('y', [0, 0, 0, 0, 0]); }); - it('lays children out vertically when orientation is ORIENTATION_VERTICAL', function () { + it('lays children out vertically when orientation is ORIENTATION_VERTICAL', () => { elements = mixedHeightElements; options.orientation = ORIENTATION_VERTICAL; @@ -297,7 +296,7 @@ describe('LayoutCalculator', function () { assertValues('y', [0, 100, 150, 250, 270]); }); - it('takes into account each element\'s pivot when calculating horizontal positions', function () { + it('takes into account each element\'s pivot when calculating horizontal positions', () => { elements = mixedWidthElements; options.orientation = ORIENTATION_HORIZONTAL; @@ -310,7 +309,7 @@ describe('LayoutCalculator', function () { assertValues('y', [10, 10, 0, 0, 0], { approx: true }); }); - it('takes into account each element\'s pivot when calculating vertical positions', function () { + it('takes into account each element\'s pivot when calculating vertical positions', () => { elements = mixedHeightElements; options.orientation = ORIENTATION_VERTICAL; @@ -323,7 +322,7 @@ describe('LayoutCalculator', function () { assertValues('y', [50, 110, 150, 250, 270], { approx: true }); }); - it('returns a layoutInfo object containing the layout bounds', function () { + it('returns a layoutInfo object containing the layout bounds', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -363,7 +362,7 @@ describe('LayoutCalculator', function () { expect(layoutInfo.bounds.w).to.equal(100); }); - it('{ wrap: false } FITTING_NONE does not adjust the size or position of elements to match the container size', function () { + it('{ wrap: false } FITTING_NONE does not adjust the size or position of elements to match the container size', () => { elements = mixedWidthElements; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_NONE; @@ -377,7 +376,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_STRETCH uses natural widths when total is larger than container size', function () { + it('{ wrap: false } FITTING_STRETCH uses natural widths when total is larger than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_STRETCH; @@ -392,7 +391,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_STRETCH stretches elements proportionally when natural widths are less than container size', function () { + it('{ wrap: false } FITTING_STRETCH stretches elements proportionally when natural widths are less than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_STRETCH; @@ -407,7 +406,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_STRETCH does not make any elements wider than their maxWidth when increasing widths', function () { + it('{ wrap: false } FITTING_STRETCH does not make any elements wider than their maxWidth when increasing widths', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_STRETCH; @@ -422,7 +421,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_STRETCH distributes additional space among remaining elements when one element\'s maxWidth is very small', function () { + it('{ wrap: false } FITTING_STRETCH distributes additional space among remaining elements when one element\'s maxWidth is very small', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_STRETCH; @@ -444,7 +443,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_STRETCH includes spacing and padding in calculations', function () { + it('{ wrap: false } FITTING_STRETCH includes spacing and padding in calculations', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_STRETCH; @@ -462,7 +461,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_SHRINK uses natural widths when total is less than container size', function () { + it('{ wrap: false } FITTING_SHRINK uses natural widths when total is less than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_SHRINK; @@ -477,7 +476,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_SHRINK shrinks elements proportionally when natural widths are greater than than container size', function () { + it('{ wrap: false } FITTING_SHRINK shrinks elements proportionally when natural widths are greater than than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_SHRINK; @@ -492,7 +491,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_SHRINK does not make any elements smaller than their minWidth when reducing widths', function () { + it('{ wrap: false } FITTING_SHRINK does not make any elements smaller than their minWidth when reducing widths', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_SHRINK; @@ -507,7 +506,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_SHRINK distributes additional size reduction among remaining elements when one element\'s minWidth is very large', function () { + it('{ wrap: false } FITTING_SHRINK distributes additional size reduction among remaining elements when one element\'s minWidth is very large', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_SHRINK; @@ -528,7 +527,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_SHRINK includes spacing and padding in calculations', function () { + it('{ wrap: false } FITTING_SHRINK includes spacing and padding in calculations', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_SHRINK; @@ -546,7 +545,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_BOTH stretches elements proportionally when natural widths are less than container size', function () { + it('{ wrap: false } FITTING_BOTH stretches elements proportionally when natural widths are less than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_BOTH; @@ -561,7 +560,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } FITTING_BOTH shrinks elements proportionally when natural widths are greater than than container size', function () { + it('{ wrap: false } FITTING_BOTH shrinks elements proportionally when natural widths are greater than than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_BOTH; @@ -576,7 +575,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: false } can reverse elements on the x axis', function () { + it('{ wrap: false } can reverse elements on the x axis', () => { elements = mixedWidthElements; options.reverseX = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -589,7 +588,7 @@ describe('LayoutCalculator', function () { assertValues('y', [0, 0, 0, 0, 0]); }); - it('{ wrap: false } can reverse elements on the y axis', function () { + it('{ wrap: false } can reverse elements on the y axis', () => { elements = mixedHeightElements; options.reverseY = true; options.orientation = ORIENTATION_VERTICAL; @@ -602,7 +601,7 @@ describe('LayoutCalculator', function () { assertValues('y', [200, 150, 50, 30, 0]); }); - it('{ wrap: false } can align to [1, 0.5]', function () { + it('{ wrap: false } can align to [1, 0.5]', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_NONE; @@ -617,7 +616,7 @@ describe('LayoutCalculator', function () { assertValues('y', [150, 150, 150, 150, 150]); }); - it('{ wrap: false } can align to [0.5, 1]', function () { + it('{ wrap: false } can align to [0.5, 1]', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; options.widthFitting = FITTING_NONE; @@ -632,7 +631,7 @@ describe('LayoutCalculator', function () { assertValues('y', [300, 300, 300, 300, 300]); }); - it('{ wrap: false } can exclude elements from the layout', function () { + it('{ wrap: false } can exclude elements from the layout', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.orientation = ORIENTATION_HORIZONTAL; @@ -644,7 +643,7 @@ describe('LayoutCalculator', function () { assertValues('y', [0, 0, 0, 0, 0]); }); - it('{ wrap: true } FITTING_NONE does not adjust the size or position of elements to match the container size', function () { + it('{ wrap: true } FITTING_NONE does not adjust the size or position of elements to match the container size', () => { elements = mixedWidthElements; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -660,7 +659,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: true } FITTING_NONE calculates line positions based on the largest element on the line', function () { + it('{ wrap: true } FITTING_NONE calculates line positions based on the largest element on the line', () => { elements = mixedWidthElements; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -678,7 +677,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 200, 100, 100]); }); - it('{ wrap: true } FITTING_NONE does not adjust the size or position of elements to match the container size', function () { + it('{ wrap: true } FITTING_NONE does not adjust the size or position of elements to match the container size', () => { elements = mixedWidthElements; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -694,7 +693,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: true } FITTING_NONE includes spacing and padding in calculations', function () { + it('{ wrap: true } FITTING_NONE includes spacing and padding in calculations', () => { elements = mixedWidthElements; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -714,7 +713,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: true } FITTING_NONE includes spacing when calculating line breaks', function () { + it('{ wrap: true } FITTING_NONE includes spacing when calculating line breaks', () => { elements = mixedWidthElements; elements[0].width = 100; elements[1].width = 100; @@ -734,7 +733,7 @@ describe('LayoutCalculator', function () { assertValues('y', [0, 0, 0, 0, 100]); }); - it('{ wrap: true } FITTING_STRETCH stretches elements proportionally when natural widths are less than container size', function () { + it('{ wrap: true } FITTING_STRETCH stretches elements proportionally when natural widths are less than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -750,7 +749,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: true } FITTING_SHRINK stretches elements proportionally when natural widths are less than container size', function () { + it('{ wrap: true } FITTING_SHRINK stretches elements proportionally when natural widths are less than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -766,7 +765,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: true } FITTING_BOTH stretches elements proportionally when natural widths are less than container size', function () { + it('{ wrap: true } FITTING_BOTH stretches elements proportionally when natural widths are less than container size', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -782,7 +781,7 @@ describe('LayoutCalculator', function () { assertValues('calculatedHeight', [100, 100, 100, 100, 100]); }); - it('{ wrap: true } can reverse elements on the x axis', function () { + it('{ wrap: true } can reverse elements on the x axis', () => { elements = mixedWidthElements; options.wrap = true; options.reverseX = true; @@ -796,7 +795,7 @@ describe('LayoutCalculator', function () { assertValues('y', [0, 0, 0, 100, 100]); }); - it('{ wrap: true } can reverse elements on the y axis', function () { + it('{ wrap: true } can reverse elements on the y axis', () => { elements = mixedWidthElements; options.wrap = true; options.reverseY = true; @@ -810,7 +809,7 @@ describe('LayoutCalculator', function () { assertValues('y', [100, 100, 100, 0, 0]); }); - it('{ wrap: true } can reverse elements both axes', function () { + it('{ wrap: true } can reverse elements both axes', () => { elements = mixedWidthElements; options.wrap = true; options.reverseX = true; @@ -825,7 +824,7 @@ describe('LayoutCalculator', function () { assertValues('y', [100, 100, 100, 0, 0]); }); - it('{ wrap: true } can align to [1, 0.5]', function () { + it('{ wrap: true } can align to [1, 0.5]', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -842,7 +841,7 @@ describe('LayoutCalculator', function () { assertValues('y', [100, 100, 100, 200, 200]); }); - it('{ wrap: true } can align to [0.5, 1]', function () { + it('{ wrap: true } can align to [0.5, 1]', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; @@ -859,7 +858,7 @@ describe('LayoutCalculator', function () { assertValues('y', [200, 200, 200, 300, 300]); }); - it('{ wrap: false } can exclude elements from the layout', function () { + it('{ wrap: false } can exclude elements from the layout', () => { elements = mixedWidthElementsWithLayoutChildComponents; options.wrap = true; options.orientation = ORIENTATION_HORIZONTAL; diff --git a/test/framework/components/model/component.test.mjs b/test/framework/components/model/component.test.mjs index 011844536c7..ae997a9907b 100644 --- a/test/framework/components/model/component.test.mjs +++ b/test/framework/components/model/component.test.mjs @@ -1,21 +1,21 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../../../src/framework/application.js'; import { Asset } from '../../../../src/framework/asset/asset.js'; import { Entity } from '../../../../src/framework/entity.js'; -import { LAYERID_WORLD, LAYERID_UI } from '../../../../src/scene/constants.js'; import { NullGraphicsDevice } from '../../../../src/platform/graphics/null/null-graphics-device.js'; +import { LAYERID_WORLD, LAYERID_UI } from '../../../../src/scene/constants.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('ModelComponent', function () { +describe('ModelComponent', () => { let app; let assets = {}; const loadAssetList = function (list, cb) { // listen for asset load events and fire cb() when all assets are loaded let count = 0; - app.assets.on('load', function (asset) { + app.assets.on('load', (asset) => { count++; if (count === list.length) { cb(); @@ -39,28 +39,28 @@ describe('ModelComponent', function () { }) ]; - loadAssetList(assetlist, function () { + loadAssetList(assetlist, () => { assets.model = assetlist[0]; assets.material = assetlist[1]; cb(); }); }; - beforeEach(function (done) { + beforeEach((done) => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); - loadAssets(function () { + loadAssets(() => { done(); }); }); - afterEach(function () { + afterEach(() => { app.destroy(); assets = {}; }); - it('Create default model component', function () { + it('Create default model component', () => { const e = new Entity(); e.addComponent('model'); @@ -79,7 +79,7 @@ describe('ModelComponent', function () { }); - it('Set modelAsset and model', function () { + it('Set modelAsset and model', () => { const e = new Entity(); e.addComponent('model', { asset: assets.model @@ -91,7 +91,7 @@ describe('ModelComponent', function () { expect(e.model.model).to.not.be.null; }); - it('Default cloned model component is identical', function () { + it('Default cloned model component is identical', () => { const e = new Entity(); e.addComponent('model', { asset: assets.model @@ -115,7 +115,7 @@ describe('ModelComponent', function () { }); - it('Cloned model component with flags set has correct meshinstance flags', function () { + it('Cloned model component with flags set has correct meshinstance flags', () => { const e = new Entity(); e.addComponent('model', { asset: assets.model, @@ -144,7 +144,7 @@ describe('ModelComponent', function () { }); - it('Cloned model component with flags set directly on mesh instance is identical', function () { + it('Cloned model component with flags set directly on mesh instance is identical', () => { const e = new Entity(); e.addComponent('model', { asset: assets.model @@ -173,7 +173,7 @@ describe('ModelComponent', function () { } }); - it('ModelAsset unbinds on destroy', function () { + it('ModelAsset unbinds on destroy', () => { const e = new Entity(); app.root.addChild(e); e.addComponent('model', { @@ -193,7 +193,7 @@ describe('ModelComponent', function () { expect(assets.model.hasEvent('unload')).to.be.false; }); - it('ModelAsset unbinds on reset', function () { + it('ModelAsset unbinds on reset', () => { const e = new Entity(); app.root.addChild(e); e.addComponent('model', { @@ -213,7 +213,7 @@ describe('ModelComponent', function () { expect(assets.model.hasEvent('unload')).to.be.false; }); - it('Material Asset unbinds on destroy', function () { + it('Material Asset unbinds on destroy', () => { const e = new Entity(); app.root.addChild(e); e.addComponent('model', { @@ -234,7 +234,7 @@ describe('ModelComponent', function () { expect(assets.material.hasEvent('remove')).to.be.false; }); - it('Material Asset unbinds on reset', function () { + it('Material Asset unbinds on reset', () => { const e = new Entity(); app.root.addChild(e); e.addComponent('model', { @@ -255,7 +255,7 @@ describe('ModelComponent', function () { expect(assets.material._callbacks.get('unload').length).to.equal(1); }); - it('Materials applied when loading asynchronously', function (done) { + it('Materials applied when loading asynchronously', (done) => { const boxAsset = new Asset('Box', 'model', { url: 'http://localhost:3000/test/test-assets/box/box.json' }, { @@ -276,20 +276,20 @@ describe('ModelComponent', function () { app.assets.load(boxAsset); - boxAsset.on('load', function () { + boxAsset.on('load', () => { const e = new Entity(); e.addComponent('model', { asset: boxAsset }); app.root.addChild(e); - expect(app.assets.hasEvent('load:' + materialAsset.id)).to.be.true; + expect(app.assets.hasEvent(`load:${materialAsset.id}`)).to.be.true; done(); }); }); - it('Materials applied when added later', function (done) { + it('Materials applied when added later', (done) => { const boxAsset = new Asset('Box', 'model', { url: 'http://localhost:3000/test/test-assets/box/box.json' }); @@ -301,7 +301,7 @@ describe('ModelComponent', function () { app.assets.add(boxAsset); app.assets.load(boxAsset); - boxAsset.on('load', function () { + boxAsset.on('load', () => { const e = new Entity(); e.addComponent('model', { asset: boxAsset @@ -309,13 +309,13 @@ describe('ModelComponent', function () { app.root.addChild(e); e.model.materialAsset = materialAsset; - expect(app.assets.hasEvent('add:' + materialAsset.id)).to.be.true; + expect(app.assets.hasEvent(`add:${materialAsset.id}`)).to.be.true; - materialAsset.on('load', function () { + materialAsset.on('load', () => { // do checks after the 'load' handler on the asset has been executed // by other engine event handlers - setTimeout(function () { - expect(app.assets.hasEvent('add:' + materialAsset.id)).to.be.false; + setTimeout(() => { + expect(app.assets.hasEvent(`add:${materialAsset.id}`)).to.be.false; expect(e.model.material).to.not.be.null; expect(e.model.material).to.equal(materialAsset.resource); done(); @@ -326,7 +326,7 @@ describe('ModelComponent', function () { }); }); - it('Material add events unbound on destroy', function (done) { + it('Material add events unbound on destroy', (done) => { const boxAsset = new Asset('Box', 'model', { url: 'http://localhost:3000/test/test-assets/box/box.json' }); @@ -338,7 +338,7 @@ describe('ModelComponent', function () { app.assets.add(boxAsset); app.assets.load(boxAsset); - boxAsset.on('load', function () { + boxAsset.on('load', () => { const e = new Entity(); e.addComponent('model', { asset: boxAsset @@ -346,11 +346,11 @@ describe('ModelComponent', function () { app.root.addChild(e); e.model.materialAsset = materialAsset; - expect(app.assets.hasEvent('add:' + materialAsset.id)).to.be.true; + expect(app.assets.hasEvent(`add:${materialAsset.id}`)).to.be.true; e.destroy(); - expect(app.assets.hasEvent('add:' + materialAsset.id)).to.be.false; + expect(app.assets.hasEvent(`add:${materialAsset.id}`)).to.be.false; done(); @@ -358,7 +358,7 @@ describe('ModelComponent', function () { }); }); - it('Layers are initialized before model is set', function () { + it('Layers are initialized before model is set', () => { const e = new Entity(); e.addComponent('model', { layers: [LAYERID_UI] @@ -374,7 +374,7 @@ describe('ModelComponent', function () { }); - it('Asset materials unbound on destroy', function (done) { + it('Asset materials unbound on destroy', (done) => { const modelAsset = new Asset('box.json', 'model', { url: 'http://localhost:3000/test/test-assets/box/box.json' }, { @@ -385,24 +385,24 @@ describe('ModelComponent', function () { app.assets.add(modelAsset); app.assets.load(modelAsset); - modelAsset.ready(function () { + modelAsset.ready(() => { const e = new Entity(); e.addComponent('model', { asset: modelAsset }); app.root.addChild(e); - expect(app.assets.hasEvent('remove:' + assets.material.id)).to.be.true; - expect(e.model._materialEvents[0]['remove:' + assets.material.id]).to.exist; + expect(app.assets.hasEvent(`remove:${assets.material.id}`)).to.be.true; + expect(e.model._materialEvents[0][`remove:${assets.material.id}`]).to.exist; e.destroy(); - expect(app.assets.hasEvent('remove:' + assets.material.id)).to.be.false; + expect(app.assets.hasEvent(`remove:${assets.material.id}`)).to.be.false; done(); }); }); - it('Asset materials unbound on change model', function (done) { + it('Asset materials unbound on change model', (done) => { const modelAsset = new Asset('plane.json', 'model', { url: 'http://localhost:3000/test/test-assets/plane/plane.json' }, { @@ -429,22 +429,22 @@ describe('ModelComponent', function () { app.assets.add(materialAsset2); app.assets.load(materialAsset2); - materialAsset2.ready(function () { - modelAsset.ready(function () { + materialAsset2.ready(() => { + modelAsset.ready(() => { const e = new Entity(); e.addComponent('model', { asset: modelAsset }); app.root.addChild(e); - expect(app.assets.hasEvent('remove:' + assets.material.id)).to.be.true; - expect(e.model._materialEvents[0]['remove:' + assets.material.id]).to.exist; + expect(app.assets.hasEvent(`remove:${assets.material.id}`)).to.be.true; + expect(e.model._materialEvents[0][`remove:${assets.material.id}`]).to.exist; - modelAsset2.ready(function () { + modelAsset2.ready(() => { e.model.asset = modelAsset2; - expect(app.assets.hasEvent('remove:' + assets.material.id)).to.be.false; - expect(app.assets.hasEvent('remove:' + materialAsset2.id)).to.be.true; + expect(app.assets.hasEvent(`remove:${assets.material.id}`)).to.be.false; + expect(app.assets.hasEvent(`remove:${materialAsset2.id}`)).to.be.true; done(); }); diff --git a/test/framework/components/system.test.mjs b/test/framework/components/system.test.mjs index e872a177dd9..eb6e5cee746 100644 --- a/test/framework/components/system.test.mjs +++ b/test/framework/components/system.test.mjs @@ -1,35 +1,35 @@ -import { Application } from '../../../src/framework/application.js'; +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Color } from '../../../src/core/math/color.js'; -import { ComponentSystem } from '../../../src/framework/components/system.js'; import { Vec2 } from '../../../src/core/math/vec2.js'; import { Vec3 } from '../../../src/core/math/vec3.js'; import { Vec4 } from '../../../src/core/math/vec4.js'; +import { Application } from '../../../src/framework/application.js'; +import { ComponentSystem } from '../../../src/framework/components/system.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('ComponentSystem', function () { +describe('ComponentSystem', () => { /** @type {Application} */ let app; /** @type {ComponentSystem} */ let system; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); system = new ComponentSystem(app); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); - describe('#initializeComponentData()', function () { + describe('#initializeComponentData()', () => { - it('works with a flat list of property names', function () { + it('works with a flat list of property names', () => { const component = {}; const data = { foo: 42, @@ -43,7 +43,7 @@ describe('ComponentSystem', function () { expect(component.bar).to.equal(84); }); - it('works with a list of property descriptor objects', function () { + it('works with a list of property descriptor objects', () => { const component = {}; const data = { rgbProperty: new Color(1, 2, 3), @@ -102,7 +102,7 @@ describe('ComponentSystem', function () { expect(component.entityProperty).to.equal('abcde-12345'); }); - it('handles nulls', function () { + it('handles nulls', () => { const component = {}; const data = { rgbProperty: null, @@ -140,7 +140,7 @@ describe('ComponentSystem', function () { expect(component.entityProperty).to.be.null; }); - it('handles vec values being delivered as arrays', function () { + it('handles vec values being delivered as arrays', () => { const component = {}; const data = { rgbProperty: [1, 2, 3], @@ -165,7 +165,7 @@ describe('ComponentSystem', function () { expect(component.vec4Property).to.not.equal(data.vec4Property); }); - it('works if a normal value comes after an object value', function () { + it('works if a normal value comes after an object value', () => { const component = {}; const data = { vec: [1, 2, 3, 4], @@ -185,7 +185,7 @@ describe('ComponentSystem', function () { expect(component.num).to.equal(42); }); - it('throws if provided an unknown type', function () { + it('throws if provided an unknown type', () => { const component = {}; const data = { foo: 42 @@ -194,16 +194,16 @@ describe('ComponentSystem', function () { { name: 'foo', type: 'something' } ]; - expect(function () { + expect(() => { system.initializeComponentData(component, data, properties); }).to.throw('Could not convert unhandled type: something'); }); }); - describe('#getPropertiesOfType()', function () { + describe('#getPropertiesOfType()', () => { - it('returns properties of the specified type', function () { + it('returns properties of the specified type', () => { system.schema = [ { name: 'foo', type: 'typeA' }, { name: 'bar', type: 'typeA' }, @@ -217,7 +217,7 @@ describe('ComponentSystem', function () { ]); }); - it('returns an empty array if no properties match the specified type', function () { + it('returns an empty array if no properties match the specified type', () => { system.schema = [ { name: 'foo', type: 'typeA' }, { name: 'bar', type: 'typeA' }, @@ -228,7 +228,7 @@ describe('ComponentSystem', function () { expect(system.getPropertiesOfType('typeC')).to.deep.equal([]); }); - it('doesn\'t throw an error if the system doesn\'t have a schema', function () { + it('doesn\'t throw an error if the system doesn\'t have a schema', () => { system.schema = null; expect(system.getPropertiesOfType('typeA')).to.deep.equal([]); diff --git a/test/framework/entity.test.mjs b/test/framework/entity.test.mjs index 44d162be150..4fe03c211b2 100644 --- a/test/framework/entity.test.mjs +++ b/test/framework/entity.test.mjs @@ -1,15 +1,17 @@ -import { createScript } from '../../src/framework/script/script-create.js'; -import { Color } from '../../src/core/math/color.js'; +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; +import { stub } from 'sinon'; +import { DummyComponentSystem } from './test-component/system.mjs'; +import { Color } from '../../src/core/math/color.js'; +import { Application } from '../../src/framework/application.js'; import { AnimComponent } from '../../src/framework/components/anim/component.js'; import { AnimationComponent } from '../../src/framework/components/animation/component.js'; -import { Application } from '../../src/framework/application.js'; import { AudioListenerComponent } from '../../src/framework/components/audio-listener/component.js'; import { ButtonComponent } from '../../src/framework/components/button/component.js'; import { CameraComponent } from '../../src/framework/components/camera/component.js'; import { CollisionComponent } from '../../src/framework/components/collision/component.js'; import { ElementComponent } from '../../src/framework/components/element/component.js'; -import { Entity } from '../../src/framework/entity.js'; import { JointComponent } from '../../src/framework/components/joint/component.js'; import { LayoutChildComponent } from '../../src/framework/components/layout-child/component.js'; import { LayoutGroupComponent } from '../../src/framework/components/layout-group/component.js'; @@ -20,32 +22,28 @@ import { RenderComponent } from '../../src/framework/components/render/component import { RigidBodyComponent } from '../../src/framework/components/rigid-body/component.js'; import { ScreenComponent } from '../../src/framework/components/screen/component.js'; import { ScriptComponent } from '../../src/framework/components/script/component.js'; -import { ScrollbarComponent } from '../../src/framework/components/scrollbar/component.js'; import { ScrollViewComponent } from '../../src/framework/components/scroll-view/component.js'; +import { ScrollbarComponent } from '../../src/framework/components/scrollbar/component.js'; import { SoundComponent } from '../../src/framework/components/sound/component.js'; import { SpriteComponent } from '../../src/framework/components/sprite/component.js'; import { ZoneComponent } from '../../src/framework/components/zone/component.js'; +import { Entity } from '../../src/framework/entity.js'; +import { createScript } from '../../src/framework/script/script-create.js'; import { NullGraphicsDevice } from '../../src/platform/graphics/null/null-graphics-device.js'; -import { DummyComponentSystem } from './test-component/system.mjs'; - -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -import { stub } from 'sinon'; -describe('Entity', function () { +describe('Entity', () => { let app; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); app.systems.add(new DummyComponentSystem(app)); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); @@ -74,21 +72,21 @@ describe('Entity', function () { zone: ZoneComponent }; - describe('#constructor', function () { + describe('#constructor', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const entity = new Entity(); expect(entity).to.be.an.instanceof(Entity); expect(entity.name).to.equal('Untitled'); }); - it('supports one argument', function () { + it('supports one argument', () => { const entity = new Entity('Test'); expect(entity).to.be.an.instanceof(Entity); expect(entity.name).to.equal('Test'); }); - it('supports two arguments', function () { + it('supports two arguments', () => { const entity = new Entity('Test', app); expect(entity).to.be.an.instanceof(Entity); expect(entity.name).to.equal('Test'); @@ -96,10 +94,10 @@ describe('Entity', function () { }); - describe('#addComponent', function () { + describe('#addComponent', () => { for (const name in components) { - it(`adds a ${name} component`, function () { + it(`adds a ${name} component`, () => { // Create an entity and verify that it does not already have the component const entity = new Entity(); expect(entity[name]).to.be.undefined; @@ -122,7 +120,7 @@ describe('Entity', function () { }); } - it('respects components order on disable', function () { + it('respects components order on disable', () => { const entity = new Entity(); entity.enabled = true; @@ -150,7 +148,7 @@ describe('Entity', function () { entity.destroy(); }); - it('respects components order on enable', function () { + it('respects components order on enable', () => { const entity = new Entity('Child'); const parent = new Entity('Parent'); @@ -233,9 +231,9 @@ describe('Entity', function () { }; }; - describe('#clone', function () { + describe('#clone', () => { - it('clones an entity', function () { + it('clones an entity', () => { const entity = new Entity('Test'); for (const name in components) { entity.addComponent(name); @@ -250,7 +248,7 @@ describe('Entity', function () { } }); - it('clones an entity hierarchy', function () { + it('clones an entity hierarchy', () => { const root = new Entity('Test'); const child = new Entity('Child'); root.addChild(child); @@ -277,7 +275,7 @@ describe('Entity', function () { root.destroy(); }); - it('returns a deep clone of the entity\'s subtree, including all components', function () { + it('returns a deep clone of the entity\'s subtree, including all components', () => { const subtree1 = createSubtree(); const subtree2 = cloneSubtree(subtree1); @@ -332,7 +330,7 @@ describe('Entity', function () { expect(subtree1.a_a_b.getGuid()).to.not.equal(subtree2.a_a_b.getGuid()); }); - it('resolves entity property references that refer to entities within the duplicated subtree', function () { + it('resolves entity property references that refer to entities within the duplicated subtree', () => { const subtree1 = createSubtree(); subtree1.a.addComponent('dummy', { myEntity1: subtree1.a_a.getGuid(), myEntity2: subtree1.a_a_b.getGuid() }); subtree1.a_a_a.addComponent('dummy', { myEntity1: subtree1.a.getGuid(), myEntity2: subtree1.a_b.getGuid() }); @@ -344,7 +342,7 @@ describe('Entity', function () { expect(subtree2.a_a_a.dummy.myEntity2).to.equal(subtree2.a_b.getGuid()); }); - it('resolves entity property references that refer to the cloned entity itself', function () { + it('resolves entity property references that refer to the cloned entity itself', () => { const subtree1 = createSubtree(); subtree1.a.addComponent('dummy', { myEntity1: subtree1.a.getGuid() }); subtree1.a_a_a.addComponent('dummy', { myEntity1: subtree1.a_a_a.getGuid() }); @@ -354,7 +352,7 @@ describe('Entity', function () { expect(subtree2.a_a_a.dummy.myEntity1).to.equal(subtree2.a_a_a.getGuid()); }); - it('does not attempt to resolve entity property references that refer to entities outside of the duplicated subtree', function () { + it('does not attempt to resolve entity property references that refer to entities outside of the duplicated subtree', () => { const root = new Entity('root', app); const sibling = new Entity('sibling', app); @@ -369,7 +367,7 @@ describe('Entity', function () { expect(subtree2.a.dummy.myEntity2).to.equal(sibling.getGuid()); }); - it('ignores null and undefined entity property references', function () { + it('ignores null and undefined entity property references', () => { const subtree1 = createSubtree(); subtree1.a.addComponent('dummy', { myEntity1: null, myEntity2: undefined }); @@ -378,7 +376,7 @@ describe('Entity', function () { expect(subtree2.a.dummy.myEntity2).to.be.undefined; }); - it('resolves entity script attributes that refer to entities within the duplicated subtree', function () { + it('resolves entity script attributes that refer to entities within the duplicated subtree', () => { const TestScript = createScript('test'); TestScript.attributes.add('entityAttr', { type: 'entity' }); TestScript.attributes.add('entityArrayAttr', { type: 'entity', array: true }); @@ -425,7 +423,7 @@ describe('Entity', function () { expect(subtree2.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree2.a_a_a.getGuid()); }); - it('resolves entity script attributes that refer to entities within the duplicated subtree after preloading has finished', function () { + it('resolves entity script attributes that refer to entities within the duplicated subtree after preloading has finished', () => { const TestScript = createScript('test'); TestScript.attributes.add('entityAttr', { type: 'entity' }); TestScript.attributes.add('entityArrayAttr', { type: 'entity', array: true }); @@ -475,7 +473,7 @@ describe('Entity', function () { expect(subtree2.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(subtree2.a_a_a.getGuid()); }); - it('does not attempt to resolve entity script attributes that refer to entities outside of the duplicated subtree', function () { + it('does not attempt to resolve entity script attributes that refer to entities outside of the duplicated subtree', () => { const TestScript = createScript('test'); TestScript.attributes.add('entityAttr', { type: 'entity' }); TestScript.attributes.add('entityArrayAttr', { type: 'entity', array: true }); @@ -506,7 +504,7 @@ describe('Entity', function () { expect(subtree2.a_a.script.test.entityArrayAttr[1].getGuid()).to.equal(app.root.getGuid()); }); - it('ensures that an instance of a subclass keeps its class prototype', function () { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserEntity extends Entity {} const a = new UserEntity(); const b = a.clone(); @@ -514,13 +512,13 @@ describe('Entity', function () { }); }); - describe('#destroy', function () { + describe('#destroy', () => { - it('destroys the entity', function () { + it('destroys the entity', () => { const entity = new Entity(); let destroyed = false; - entity.on('destroy', function () { + entity.on('destroy', () => { destroyed = true; }); entity.destroy(); @@ -530,21 +528,21 @@ describe('Entity', function () { }); - describe('#findByGuid', function () { + describe('#findByGuid', () => { - it('returns same entity', function () { + it('returns same entity', () => { const e = new Entity(); expect(e.findByGuid(e.getGuid())).to.equal(e); }); - it('returns direct child entity', function () { + it('returns direct child entity', () => { const e = new Entity(); const c = new Entity(); e.addChild(c); expect(e.findByGuid(c.getGuid())).to.equal(c); }); - it('returns child of child entity', function () { + it('returns child of child entity', () => { const e = new Entity(); const c = new Entity(); const c2 = new Entity(); @@ -553,14 +551,14 @@ describe('Entity', function () { expect(e.findByGuid(c2.getGuid())).to.equal(c2); }); - it('does not return parent', function () { + it('does not return parent', () => { const e = new Entity(); const c = new Entity(); e.addChild(c); expect(c.findByGuid(e.getGuid())).to.equal(null); }); - it('does not return destroyed entity', function () { + it('does not return destroyed entity', () => { const e = new Entity(); const c = new Entity(); e.addChild(c); @@ -568,7 +566,7 @@ describe('Entity', function () { expect(e.findByGuid(c.getGuid())).to.equal(null); }); - it('does not return entity that was removed from hierarchy', function () { + it('does not return entity that was removed from hierarchy', () => { const e = new Entity(); const c = new Entity(); e.addChild(c); @@ -576,29 +574,29 @@ describe('Entity', function () { expect(e.findByGuid(c.getGuid())).to.equal(null); }); - it('does not return entity that does not exist', function () { + it('does not return entity that does not exist', () => { expect(app.root.findByGuid('missing')).to.equal(null); }); }); - describe('#findComponent', function () { + describe('#findComponent', () => { - it('finds component on single entity', function () { + it('finds component on single entity', () => { const e = new Entity(); e.addComponent('anim'); const component = e.findComponent('anim'); expect(component).to.be.an.instanceof(AnimComponent); }); - it('returns null when component is not found', function () { + it('returns null when component is not found', () => { const e = new Entity(); e.addComponent('anim'); const component = e.findComponent('render'); expect(component).to.be.null; }); - it('finds component on child entity', function () { + it('finds component on child entity', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -607,7 +605,7 @@ describe('Entity', function () { expect(component).to.be.an.instanceof(AnimComponent); }); - it('finds component on grandchild entity', function () { + it('finds component on grandchild entity', () => { const root = new Entity(); const child = new Entity(); const grandchild = new Entity(); @@ -618,7 +616,7 @@ describe('Entity', function () { expect(component).to.be.an.instanceof(AnimComponent); }); - it('does not find component on parent entity', function () { + it('does not find component on parent entity', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -629,9 +627,9 @@ describe('Entity', function () { }); - describe('#findComponents', function () { + describe('#findComponents', () => { - it('finds components on single entity', function () { + it('finds components on single entity', () => { const e = new Entity(); e.addComponent('anim'); const components = e.findComponents('anim'); @@ -640,7 +638,7 @@ describe('Entity', function () { expect(components[0]).to.be.an.instanceof(AnimComponent); }); - it('returns empty array when no components are found', function () { + it('returns empty array when no components are found', () => { const e = new Entity(); e.addComponent('anim'); const components = e.findComponents('render'); @@ -648,7 +646,7 @@ describe('Entity', function () { expect(components.length).to.equal(0); }); - it('finds components on child entity', function () { + it('finds components on child entity', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -659,7 +657,7 @@ describe('Entity', function () { expect(components[0]).to.be.an.instanceof(AnimComponent); }); - it('finds components on 3 entity hierarchy', function () { + it('finds components on 3 entity hierarchy', () => { const root = new Entity(); const child = new Entity(); const grandchild = new Entity(); @@ -676,7 +674,7 @@ describe('Entity', function () { expect(components[2]).to.be.an.instanceof(AnimComponent); }); - it('does not find components on parent entity', function () { + it('does not find components on parent entity', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -688,9 +686,9 @@ describe('Entity', function () { }); - describe('#findScript', function () { + describe('#findScript', () => { - it('finds script on single entity', function () { + it('finds script on single entity', () => { const MyScript = createScript('myScript'); const e = new Entity(); e.addComponent('script'); @@ -699,7 +697,7 @@ describe('Entity', function () { expect(script).to.be.an.instanceof(MyScript); }); - it('returns undefined when script is not found', function () { + it('returns undefined when script is not found', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -708,7 +706,7 @@ describe('Entity', function () { expect(script).to.be.undefined; }); - it('returns undefined when script component is not found', function () { + it('returns undefined when script component is not found', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -716,7 +714,7 @@ describe('Entity', function () { expect(script).to.be.undefined; }); - it('finds script on child entity', function () { + it('finds script on child entity', () => { const MyScript = createScript('myScript'); const root = new Entity(); const child = new Entity(); @@ -727,7 +725,7 @@ describe('Entity', function () { expect(script).to.be.an.instanceof(MyScript); }); - it('finds script on grandchild entity', function () { + it('finds script on grandchild entity', () => { const MyScript = createScript('myScript'); const root = new Entity(); const child = new Entity(); @@ -740,7 +738,7 @@ describe('Entity', function () { expect(script).to.be.an.instanceof(MyScript); }); - it('does not find script on parent entity', function () { + it('does not find script on parent entity', () => { createScript('myScript'); const root = new Entity(); const child = new Entity(); @@ -753,9 +751,9 @@ describe('Entity', function () { }); - describe('#findScripts', function () { + describe('#findScripts', () => { - it('finds scripts on single entity', function () { + it('finds scripts on single entity', () => { const MyScript = createScript('myScript'); const e = new Entity(); e.addComponent('script'); @@ -766,7 +764,7 @@ describe('Entity', function () { expect(scripts[0]).to.be.an.instanceof(MyScript); }); - it('returns empty array when no scripts are found', function () { + it('returns empty array when no scripts are found', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -776,7 +774,7 @@ describe('Entity', function () { expect(scripts.length).to.equal(0); }); - it('returns empty array when no script component are found', function () { + it('returns empty array when no script component are found', () => { const root = new Entity(); const child = new Entity(); root.addChild(child); @@ -785,7 +783,7 @@ describe('Entity', function () { expect(scripts.length).to.equal(0); }); - it('finds scripts on child entity', function () { + it('finds scripts on child entity', () => { const MyScript = createScript('myScript'); const root = new Entity(); const child = new Entity(); @@ -798,7 +796,7 @@ describe('Entity', function () { expect(scripts[0]).to.be.an.instanceof(MyScript); }); - it('finds scripts on 3 entity hierarchy', function () { + it('finds scripts on 3 entity hierarchy', () => { const MyScript = createScript('myScript'); const root = new Entity(); const child = new Entity(); @@ -819,7 +817,7 @@ describe('Entity', function () { expect(scripts[2]).to.be.an.instanceof(MyScript); }); - it('does not find scripts on parent entity', function () { + it('does not find scripts on parent entity', () => { createScript('myScript'); const root = new Entity(); const child = new Entity(); @@ -833,9 +831,9 @@ describe('Entity', function () { }); - describe('#removeComponent', function () { + describe('#removeComponent', () => { - it('removes a component from the entity', function () { + it('removes a component from the entity', () => { const entity = new Entity(); expect(entity.anim).to.be.undefined; entity.addComponent('anim'); diff --git a/test/framework/i18n/i18n.test.mjs b/test/framework/i18n/i18n.test.mjs index 6d459df6a40..8a096424f7d 100644 --- a/test/framework/i18n/i18n.test.mjs +++ b/test/framework/i18n/i18n.test.mjs @@ -1,23 +1,23 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; +import { restore, stub } from 'sinon'; + import { Application } from '../../../src/framework/application.js'; import { Asset } from '../../../src/framework/asset/asset.js'; import { JsonHandler } from '../../../src/framework/handlers/json.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -import { restore, stub } from 'sinon'; -describe('I18n', function () { +describe('I18n', () => { let app; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); }); - afterEach(function () { + afterEach(() => { app.destroy(); restore(); }); @@ -60,21 +60,21 @@ describe('I18n', function () { return data; }; - describe('#assets', function () { + describe('#assets', () => { - it('returns same ids for assets after setting array of asset ids', function () { + it('returns same ids for assets after setting array of asset ids', () => { app.i18n.assets = [1, 2]; expect(app.i18n.assets).to.deep.equal([1, 2]); }); - it('returns same ids for assets after setting array of assets', function () { + it('returns same ids for assets after setting array of assets', () => { const a1 = new Asset('a1', 'json'); const a2 = new Asset('a2', 'json'); app.i18n.assets = [a1, a2]; expect(app.i18n.assets).to.deep.equal([a1.id, a2.id]); }); - it('removes old assets when setting new array', function () { + it('removes old assets when setting new array', () => { app.i18n.assets = [1, 2]; app.i18n.assets = [2, 3]; expect(app.i18n.assets).to.deep.equal([2, 3]); @@ -82,67 +82,67 @@ describe('I18n', function () { }); - describe('#findAvailableLocale', function () { + describe('#findAvailableLocale', () => { - it('should find locale if translations have been provided for it', function () { + it('should find locale if translations have been provided for it', () => { addText('no-IT', 'key', 'norwegian'); expect(app.i18n.findAvailableLocale('no-IT')).to.equal('no-IT'); }); - it('should fallback to en-US if translations have not been provided for the desired locale', function () { + it('should fallback to en-US if translations have not been provided for the desired locale', () => { addText('no-IT', 'key', 'norwegian'); expect(app.i18n.findAvailableLocale('de-DE')).to.equal('en-US'); }); - it('should fallback to zh-CN if translations are provided and zh-SG is the desired locale', function () { + it('should fallback to zh-CN if translations are provided and zh-SG is the desired locale', () => { addText('zh-CN', 'key', 'Chinese'); expect(app.i18n.findAvailableLocale('zh-SG')).to.equal('zh-CN'); }); - it('should fallback to en-GB if translations are provided and en-US is the desired locale', function () { + it('should fallback to en-GB if translations are provided and en-US is the desired locale', () => { addText('en-GB', 'key', 'British'); expect(app.i18n.findAvailableLocale('en-US')).to.equal('en-GB'); }); }); - describe('#getPluralText', function () { + describe('#getPluralText', () => { - it('should return key when no translations exist for that locale', function () { + it('should return key when no translations exist for that locale', () => { expect(app.i18n.getPluralText('key')).to.equal('key'); addText('no-NO', 'key', ['translated']); expect(app.i18n.getPluralText('key')).to.equal('key'); }); - it('should return key if the desired locale has other translations but not that key', function () { + it('should return key if the desired locale has other translations but not that key', () => { addText('no-NO', 'key', ['norwegian']); expect(app.i18n.getPluralText('key2', 'no-NO')).to.equal('key2'); app.i18n.locale = 'no-NO'; expect(app.i18n.getPluralText('key2')).to.equal('key2'); }); - it('should return en-US translation if the desired locale has no translations', function () { + it('should return en-US translation if the desired locale has no translations', () => { addText('en-US', 'key', ['english one', 'english other']); expect(app.i18n.getPluralText('key', 1, 'no-NO')).to.equal('english one'); app.i18n.locale = 'no-NO'; expect(app.i18n.getPluralText('key', 1)).to.equal('english one'); }); - it('should return en-US plural form if the desired locale does not exist', function () { + it('should return en-US plural form if the desired locale does not exist', () => { addText('en-US', 'key', ['english one', 'english other']); expect(app.i18n.getPluralText('key', 1, 'ar')).to.equal('english one'); app.i18n.locale = 'ar'; expect(app.i18n.getPluralText('key', 1)).to.equal('english one'); }); - it('returns empty string if the empty string is a valid translation', function () { + it('returns empty string if the empty string is a valid translation', () => { addText('en-US', 'key', ['', '']); expect(app.i18n.getPluralText('key', 0)).to.equal(''); expect(app.i18n.getPluralText('key', 1)).to.equal(''); expect(app.i18n.getPluralText('key', 2)).to.equal(''); - ['no-NO', 'ar'].forEach(function (locale) { + ['no-NO', 'ar'].forEach((locale) => { expect(app.i18n.getPluralText('key', 0, locale)).to.equal(''); expect(app.i18n.getPluralText('key', 1, locale)).to.equal(''); expect(app.i18n.getPluralText('key', 2, locale)).to.equal(''); @@ -159,13 +159,13 @@ describe('I18n', function () { }); }); - it('returns key is translation is null', function () { + it('returns key is translation is null', () => { addText('en-US', 'key', [null, null]); expect(app.i18n.getPluralText('key', 0)).to.equal('key'); expect(app.i18n.getPluralText('key', 1)).to.equal('key'); expect(app.i18n.getPluralText('key', 2)).to.equal('key'); - ['no-NO', 'ar'].forEach(function (locale) { + ['no-NO', 'ar'].forEach((locale) => { expect(app.i18n.getPluralText('key', 0, locale)).to.equal('key'); expect(app.i18n.getPluralText('key', 1, locale)).to.equal('key'); expect(app.i18n.getPluralText('key', 2, locale)).to.equal('key'); @@ -185,16 +185,16 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key', 2, 'es-ES')).to.equal('key'); }); - it('should fall back to default locale for that language if the specific locale does not exist', function () { + it('should fall back to default locale for that language if the specific locale does not exist', () => { for (const lang in DEFAULT_LOCALE_FALLBACKS) { - addText(DEFAULT_LOCALE_FALLBACKS[lang], 'key', ['language ' + lang]); + addText(DEFAULT_LOCALE_FALLBACKS[lang], 'key', [`language ${lang}`]); } addText('no-NO', 'key', ['language no']); for (const lang in DEFAULT_LOCALE_FALLBACKS) { - expect(app.i18n.getPluralText('key', 1, lang + '-alt')).to.equal('language ' + lang); - app.i18n.locale = lang + '-alt'; - expect(app.i18n.getPluralText('key', 1)).to.equal('language ' + lang); + expect(app.i18n.getPluralText('key', 1, `${lang}-alt`)).to.equal(`language ${lang}`); + app.i18n.locale = `${lang}-alt`; + expect(app.i18n.getPluralText('key', 1)).to.equal(`language ${lang}`); } expect(app.i18n.getPluralText('key', 1, 'no-alt')).to.equal('language no'); @@ -203,16 +203,16 @@ describe('I18n', function () { }); - it('should fall back to default locale for that language if you just pass the language', function () { + it('should fall back to default locale for that language if you just pass the language', () => { for (const lang in DEFAULT_LOCALE_FALLBACKS) { - addText(DEFAULT_LOCALE_FALLBACKS[lang], 'key', ['language ' + lang]); + addText(DEFAULT_LOCALE_FALLBACKS[lang], 'key', [`language ${lang}`]); } addText('no-NO', 'key', ['language no']); for (const lang in DEFAULT_LOCALE_FALLBACKS) { - expect(app.i18n.getPluralText('key', 1, lang)).to.equal('language ' + lang); + expect(app.i18n.getPluralText('key', 1, lang)).to.equal(`language ${lang}`); app.i18n.locale = lang; - expect(app.i18n.getPluralText('key', 1)).to.equal('language ' + lang); + expect(app.i18n.getPluralText('key', 1)).to.equal(`language ${lang}`); } expect(app.i18n.getPluralText('key', 1, 'no')).to.equal('language no'); @@ -220,20 +220,20 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key', 1)).to.equal('language no'); }); - it('should fall back to first available locale for that language if no default fallback exists', function () { + it('should fall back to first available locale for that language if no default fallback exists', () => { addText('no-IT', 'key', ['norwegian']); expect(app.i18n.getPluralText('key', 1, 'no-NO')).to.equal('norwegian'); app.i18n.locale = 'no-NO'; expect(app.i18n.getPluralText('key', 1)).to.equal('norwegian'); }); - it('should return correct plural forms for \"ja, ko, th, vi, zh\"', function () { + it('should return correct plural forms for \"ja, ko, th, vi, zh\"', () => { const locales = ['ja-JP', 'ko-KO', 'th-TH', 'vi-VI', 'zh-ZH']; - locales.forEach(function (locale) { + locales.forEach((locale) => { addText(locale, 'key', ['other']); }); - locales.forEach(function (locale) { + locales.forEach((locale) => { expect(app.i18n.getPluralText('key', 0, locale)).to.equal('other'); expect(app.i18n.getPluralText('key', 1, locale)).to.equal('other'); @@ -243,9 +243,9 @@ describe('I18n', function () { }); }); - it('should return correct plural forms for \"fa, hi\"', function () { + it('should return correct plural forms for \"fa, hi\"', () => { const locales = ['fa-FA', 'hi-HI']; - locales.forEach(function (locale) { + locales.forEach((locale) => { addText(locale, 'key', ['one', 'other']); }); @@ -258,16 +258,16 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key', 2, locale)).to.equal('other'); }; - locales.forEach(function (locale) { + locales.forEach((locale) => { testLocale(locale); app.i18n.locale = locale; testLocale(); }); }); - it('should return correct plural forms for \"fr\"', function () { + it('should return correct plural forms for \"fr\"', () => { const locales = ['fr-FR']; - locales.forEach(function (locale) { + locales.forEach((locale) => { addText(locale, 'key', ['one', 'other']); }); @@ -279,7 +279,7 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key', 2, locale)).to.equal('other'); }; - locales.forEach(function (locale) { + locales.forEach((locale) => { testLocale(locale); app.i18n.locale = locale; testLocale(); @@ -287,9 +287,9 @@ describe('I18n', function () { }); - it('should return correct plural forms for \"en, de, it, el, es, tr\"', function () { + it('should return correct plural forms for \"en, de, it, el, es, tr\"', () => { const locales = ['en-US', 'en-GB', 'de-DE', 'it-IT', 'el-GR', 'es-ES', 'tr-TR']; - locales.forEach(function (locale) { + locales.forEach((locale) => { addText(locale, 'key', ['one', 'other']); }); @@ -301,16 +301,16 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key', 1.5, locale)).to.equal('other'); }; - locales.forEach(function (locale) { + locales.forEach((locale) => { testLocale(locale); app.i18n.locale = locale; testLocale(); }); }); - it('should return correct plural forms for \"ru, uk\"', function () { + it('should return correct plural forms for \"ru, uk\"', () => { const locales = ['ru-RU', 'uk-UK']; - locales.forEach(function (locale) { + locales.forEach((locale) => { addText(locale, 'key', ['one', 'few', 'many', 'other']); }); @@ -339,7 +339,7 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key', 1000.5, locale)).to.equal('other'); }; - locales.forEach(function (locale) { + locales.forEach((locale) => { testLocale(locale); app.i18n.locale = locale; testLocale(); @@ -347,9 +347,9 @@ describe('I18n', function () { }); }); - it('should return correct plural forms for \"ar\"', function () { + it('should return correct plural forms for \"ar\"', () => { const locales = ['ar-AR']; - locales.forEach(function (locale) { + locales.forEach((locale) => { addText(locale, 'key', ['zero', 'one', 'two', 'few', 'many', 'other']); }); @@ -378,7 +378,7 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key', 10.1, locale)).to.equal('other'); }; - locales.forEach(function (locale) { + locales.forEach((locale) => { testLocale(locale); app.i18n.locale = locale; testLocale(); @@ -386,7 +386,7 @@ describe('I18n', function () { }); }); - it('zh-HK should use zh-HK if it exists', function () { + it('zh-HK should use zh-HK if it exists', () => { addText('zh-CN', 'key', ['cn']); addText('zh-HK', 'key', ['hk']); addText('zh-TW', 'key', ['tw']); @@ -394,21 +394,21 @@ describe('I18n', function () { expect(app.i18n.getPluralText('key')).to.equal('hk'); }); - it('zh-HK should fall back to zh-TW', function () { + it('zh-HK should fall back to zh-TW', () => { addText('zh-CN', 'key', ['cn']); addText('zh-TW', 'key', ['hk']); app.i18n.locale = 'zh-HK'; expect(app.i18n.getPluralText('key')).to.equal('hk'); }); - it('zh-TW should fall back to zh-HK', function () { + it('zh-TW should fall back to zh-HK', () => { addText('zh-CN', 'key', ['cn']); addText('zh-HK', 'key', ['tw']); app.i18n.locale = 'zh-TW'; expect(app.i18n.getPluralText('key')).to.equal('tw'); }); - it('zh-SG should fall back to zh-CN', function () { + it('zh-SG should fall back to zh-CN', () => { addText('zh-HK', 'key', ['hk']); addText('zh-CN', 'key', ['cn']); addText('zh-TW', 'key', ['tw']); @@ -418,23 +418,23 @@ describe('I18n', function () { }); - describe('#getText', function () { + describe('#getText', () => { - it('should return key when no translations exist for that locale', function () { + it('should return key when no translations exist for that locale', () => { expect(app.i18n.getText('key')).to.equal('key'); addText('no-NO', 'key', 'translated'); expect(app.i18n.getText('key')).to.equal('key'); }); - it('should return localized text when translation exists', function () { + it('should return localized text when translation exists', () => { addText('no-NO', 'key', 'translated'); expect(app.i18n.getText('key', 'no-NO')).to.equal('translated'); app.i18n.locale = 'no-NO'; expect(app.i18n.getText('key')).to.equal('translated'); }); - it('should return en-US translation if the desired locale has no translations', function () { + it('should return en-US translation if the desired locale has no translations', () => { addText('en-US', 'key', 'english'); expect(app.i18n.getText('key', 'no-NO')).to.equal('english'); app.i18n.locale = 'no-NO'; @@ -445,42 +445,42 @@ describe('I18n', function () { expect(app.i18n.getText('key')).to.equal('norwegian'); }); - it('should return key if the desired locale has other translations but not that key', function () { + it('should return key if the desired locale has other translations but not that key', () => { addText('no-NO', 'key', 'norwegian'); expect(app.i18n.getText('key2', 'no-NO')).to.equal('key2'); app.i18n.locale = 'no-NO'; expect(app.i18n.getText('key2')).to.equal('key2'); }); - it('should fall back to default locale for that language if the specific locale does not exist', function () { + it('should fall back to default locale for that language if the specific locale does not exist', () => { addText('no-NO', 'key', 'norwegian'); expect(app.i18n.getText('key', 'no-IT')).to.equal('norwegian'); app.i18n.locale = 'no-IT'; expect(app.i18n.getText('key')).to.equal('norwegian'); }); - it('should fall back to default locale for that language if you just pass the language', function () { + it('should fall back to default locale for that language if you just pass the language', () => { addText('no-NO', 'key', 'norwegian'); expect(app.i18n.getText('key', 'no')).to.equal('norwegian'); app.i18n.locale = 'no'; expect(app.i18n.getText('key')).to.equal('norwegian'); }); - it('should fall back to first available locale for that language if no default fallback exists', function () { + it('should fall back to first available locale for that language if no default fallback exists', () => { addText('no-IT', 'key', 'norwegian'); expect(app.i18n.getText('key', 'no-NO')).to.equal('norwegian'); app.i18n.locale = 'no-NO'; expect(app.i18n.getText('key')).to.equal('norwegian'); }); - it('when called on plural key should return the first entry', function () { + it('when called on plural key should return the first entry', () => { addText('no-IT', 'key', ['one', 'other']); expect(app.i18n.getText('key', 'no-NO')).to.equal('one'); app.i18n.locale = 'no-NO'; expect(app.i18n.getText('key')).to.equal('one'); }); - it('returns empty string if the empty string is a valid translation', function () { + it('returns empty string if the empty string is a valid translation', () => { addText('en-US', 'key', ''); expect(app.i18n.getText('key')).to.equal(''); expect(app.i18n.getText('key', 'no-NO')).to.equal(''); @@ -488,7 +488,7 @@ describe('I18n', function () { expect(app.i18n.getText('key')).to.equal(''); }); - it('returns key if the translation is null', function () { + it('returns key if the translation is null', () => { addText('en-US', 'key', null); expect(app.i18n.getText('key')).to.equal('key'); expect(app.i18n.getText('key', 'no-NO')).to.equal('key'); @@ -496,7 +496,7 @@ describe('I18n', function () { expect(app.i18n.getText('key')).to.equal('key'); }); - it('zh-HK should use zh-HK if it exists', function () { + it('zh-HK should use zh-HK if it exists', () => { addText('zh-CN', 'key', 'cn'); addText('zh-HK', 'key', 'hk'); addText('zh-TW', 'key', 'tw'); @@ -504,21 +504,21 @@ describe('I18n', function () { expect(app.i18n.getText('key')).to.equal('hk'); }); - it('zh-HK should fall back to zh-TW', function () { + it('zh-HK should fall back to zh-TW', () => { addText('zh-CN', 'key', 'cn'); addText('zh-TW', 'key', 'hk'); app.i18n.locale = 'zh-HK'; expect(app.i18n.getText('key')).to.equal('hk'); }); - it('zh-TW should fall back to zh-HK', function () { + it('zh-TW should fall back to zh-HK', () => { addText('zh-CN', 'key', 'cn'); addText('zh-HK', 'key', 'tw'); app.i18n.locale = 'zh-TW'; expect(app.i18n.getText('key')).to.equal('tw'); }); - it('zh-SG should fall back to zh-CN', function () { + it('zh-SG should fall back to zh-CN', () => { addText('zh-HK', 'key', 'hk'); addText('zh-CN', 'key', 'cn'); addText('zh-TW', 'key', 'tw'); @@ -528,9 +528,9 @@ describe('I18n', function () { }); - describe('#locale', function () { + describe('#locale', () => { - it('ensures locale for Indonesian always starts with "id"', function () { + it('ensures locale for Indonesian always starts with "id"', () => { app.i18n.locale = 'id'; expect(app.i18n.locale).to.equal('id'); @@ -553,9 +553,9 @@ describe('I18n', function () { }); - describe('removeData', function () { + describe('removeData', () => { - it('removes all data correctly', function () { + it('removes all data correctly', () => { const data1 = addText('en-US', 'key', 'translation'); const data2 = addText('en-US', 'key2', 'translation2'); const data3 = addText('no-IT', 'key3', 'translation3'); @@ -583,15 +583,15 @@ describe('I18n', function () { }); - it.skip('assets not in asset registry get loaded after they are added to the registry', function (done) { - stub(JsonHandler.prototype, 'load').callsFake(function (url, callback) { + it.skip('assets not in asset registry get loaded after they are added to the registry', (done) => { + stub(JsonHandler.prototype, 'load').callsFake((url, callback) => { callback(null, createTranslation('en-US', 'key', 'translation')); }); const asset = new Asset('a1', 'json', { url: '/fake/url.json' }); app.i18n.assets = [asset]; - app.i18n.on('data:add', function () { + app.i18n.on('data:add', () => { expect(app.i18n.getText('key')).to.equal('translation'); done(); }); @@ -600,8 +600,8 @@ describe('I18n', function () { app.assets.load(asset); }); - it.skip('assets in asset registry get loaded when passed to i18n', function (done) { - stub(JsonHandler.prototype, 'load').callsFake(function (url, callback) { + it.skip('assets in asset registry get loaded when passed to i18n', (done) => { + stub(JsonHandler.prototype, 'load').callsFake((url, callback) => { callback(null, createTranslation('en-US', 'key', 'translation')); }); @@ -610,7 +610,7 @@ describe('I18n', function () { app.i18n.assets = [asset]; - app.i18n.on('data:add', function () { + app.i18n.on('data:add', () => { expect(app.i18n.getText('key')).to.equal('translation'); done(); }); @@ -618,18 +618,18 @@ describe('I18n', function () { app.assets.load(asset); }); - it('assets already loaded are parsed when passed to i18n', function (done) { - stub(JsonHandler.prototype, 'load').callsFake(function (url, callback) { + it('assets already loaded are parsed when passed to i18n', (done) => { + stub(JsonHandler.prototype, 'load').callsFake((url, callback) => { callback(null, createTranslation('en-US', 'key', 'translation')); }); - app.i18n.on('data:add', function () { + app.i18n.on('data:add', () => { expect(app.i18n.getText('key')).to.equal('translation'); done(); }); const asset = new Asset('a1', 'json', { url: '/fake/url.json' }); - asset.on('load', function () { + asset.on('load', () => { app.i18n.assets = [asset]; }); @@ -637,20 +637,20 @@ describe('I18n', function () { app.assets.load(asset); }); - it('translations are unloaded when the asset is unloaded', function (done) { - stub(JsonHandler.prototype, 'load').callsFake(function (url, callback) { + it('translations are unloaded when the asset is unloaded', (done) => { + stub(JsonHandler.prototype, 'load').callsFake((url, callback) => { callback(null, createTranslation('en-US', 'key', 'translation')); }); const asset = new Asset('a1', 'json', { url: '/fake/url.json' }); - app.i18n.on('data:add', function () { + app.i18n.on('data:add', () => { asset.unload(); expect(app.i18n.getText('key')).to.equal('key'); done(); }); - asset.on('load', function () { + asset.on('load', () => { app.i18n.assets = [asset]; }); @@ -658,20 +658,20 @@ describe('I18n', function () { app.assets.load(asset); }); - it('translations are unloaded when the asset is removed', function (done) { - stub(JsonHandler.prototype, 'load').callsFake(function (url, callback) { + it('translations are unloaded when the asset is removed', (done) => { + stub(JsonHandler.prototype, 'load').callsFake((url, callback) => { callback(null, createTranslation('en-US', 'key', 'translation')); }); const asset = new Asset('a1', 'json', { url: '/fake/url.json' }); - app.i18n.on('data:add', function () { + app.i18n.on('data:add', () => { app.assets.remove(asset); expect(app.i18n.getText('key')).to.equal('key'); done(); }); - asset.on('load', function () { + asset.on('load', () => { app.i18n.assets = [asset]; }); @@ -679,24 +679,24 @@ describe('I18n', function () { app.assets.load(asset); }); - it('translations are re-loaded when the asset is removed and then added again', function (done) { - stub(JsonHandler.prototype, 'load').callsFake(function (url, callback) { + it('translations are re-loaded when the asset is removed and then added again', (done) => { + stub(JsonHandler.prototype, 'load').callsFake((url, callback) => { callback(null, createTranslation('en-US', 'key', 'translation')); }); const asset = new Asset('a1', 'json', { url: '/fake/url.json' }); - app.i18n.once('data:add', function () { + app.i18n.once('data:add', () => { app.assets.remove(asset); - setTimeout(function () { + setTimeout(() => { app.assets.add(asset); expect(app.i18n.getText('key')).to.equal('translation'); done(); }); }); - asset.once('load', function () { + asset.once('load', () => { app.i18n.assets = [asset]; }); @@ -704,18 +704,18 @@ describe('I18n', function () { app.assets.load(asset); }); - it('translations are re-loaded when the contents of the asset change', function (done) { - stub(JsonHandler.prototype, 'load').callsFake(function (url, callback) { + it('translations are re-loaded when the contents of the asset change', (done) => { + stub(JsonHandler.prototype, 'load').callsFake((url, callback) => { callback(null, createTranslation('en-US', 'key', 'translation')); }); const asset = new Asset('a1', 'json', { url: '/fake/url.json' }); - app.i18n.once('data:add', function () { + app.i18n.once('data:add', () => { expect(app.i18n.getText('key')).to.equal('translation'); - setTimeout(function () { - app.i18n.once('data:add', function () { + setTimeout(() => { + app.i18n.once('data:add', () => { expect(app.i18n.getText('key')).to.equal('changed'); done(); }); @@ -724,7 +724,7 @@ describe('I18n', function () { }); }); - asset.once('load', function () { + asset.once('load', () => { app.i18n.assets = [asset]; }); diff --git a/test/framework/scene-registry.test.mjs b/test/framework/scene-registry.test.mjs index c009e6ae000..539b6d94ce7 100644 --- a/test/framework/scene-registry.test.mjs +++ b/test/framework/scene-registry.test.mjs @@ -1,27 +1,27 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../src/framework/application.js'; import { SceneRegistry } from '../../src/framework/scene-registry.js'; import { NullGraphicsDevice } from '../../src/platform/graphics/null/null-graphics-device.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('SceneRegistry', function () { +describe('SceneRegistry', () => { let app; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); }); - afterEach(function () { + afterEach(() => { app.destroy(); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('creates a new scene registry', function () { + it('creates a new scene registry', () => { const registry = new SceneRegistry(app); expect(registry.list().length).to.equal(0); @@ -29,9 +29,9 @@ describe('SceneRegistry', function () { }); - describe('#add', function () { + describe('#add', () => { - it('adds a single scene to the registry', function () { + it('adds a single scene to the registry', () => { const registry = new SceneRegistry(app); registry.add('New Scene', '/test.json'); @@ -39,7 +39,7 @@ describe('SceneRegistry', function () { expect(registry.list().length).to.equal(1); }); - it('adds multiple scenes to the registry', function () { + it('adds multiple scenes to the registry', () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', '/test1.json'); registry.add('New Scene 2', '/test2.json'); @@ -57,9 +57,9 @@ describe('SceneRegistry', function () { }); - describe('#find', function () { + describe('#find', () => { - it('find', function () { + it('find', () => { const registry = new SceneRegistry(app); registry.add('New Scene', '/test.json'); @@ -71,9 +71,9 @@ describe('SceneRegistry', function () { }); - describe('#findByUrl', function () { + describe('#findByUrl', () => { - it('url index', function () { + it('url index', () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', '/test1.json'); @@ -84,9 +84,9 @@ describe('SceneRegistry', function () { }); - describe('#list', function () { + describe('#list', () => { - it('lists the scenes in the registry', function () { + it('lists the scenes in the registry', () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', '/test1.json'); registry.add('New Scene 2', '/test2.json'); @@ -101,8 +101,8 @@ describe('SceneRegistry', function () { }); const promisedLoadSceneData = function (registry, sceneItemOrNameOrUrl) { - return new Promise(function (resolve, reject) { - registry.loadSceneData(sceneItemOrNameOrUrl, function (err, sceneItem) { + return new Promise((resolve, reject) => { + registry.loadSceneData(sceneItemOrNameOrUrl, (err, sceneItem) => { if (err) { resolve(err); } @@ -112,11 +112,11 @@ describe('SceneRegistry', function () { }); }; - describe('#loadSceneData', function () { + describe('#loadSceneData', () => { const assetPath = 'http://localhost:3000/test/test-assets/'; - it('load and cache, check data is valid, unload data, check data is removed with SceneItem', async function () { + it('load and cache, check data is valid, unload data, check data is removed with SceneItem', async () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', `${assetPath}scene.json`); @@ -132,7 +132,7 @@ describe('SceneRegistry', function () { expect(sceneItem._loading).to.equal(false); }); - it('load and cache, check data is valid, unload data, check data is removed with Urls', async function () { + it('load and cache, check data is valid, unload data, check data is removed with Urls', async () => { const registry = new SceneRegistry(app); const sceneUrl = `${assetPath}scene.json`; registry.add('New Scene 1', sceneUrl); @@ -147,7 +147,7 @@ describe('SceneRegistry', function () { expect(sceneItem._loading).to.equal(false); }); - it('try to load scene data that by name', async function () { + it('try to load scene data that by name', async () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', `${assetPath}scene.json`); @@ -158,7 +158,7 @@ describe('SceneRegistry', function () { expect(sceneItem._loading).to.equal(false); }); - it('try to load scene data that by URL', async function () { + it('try to load scene data that by URL', async () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', `${assetPath}scene.json`); @@ -170,9 +170,9 @@ describe('SceneRegistry', function () { }); }); - describe('#remove', function () { + describe('#remove', () => { - it('remove', function () { + it('remove', () => { const registry = new SceneRegistry(app); registry.add('New Scene', '/test.json'); @@ -182,7 +182,7 @@ describe('SceneRegistry', function () { expect(registry.find('New Scene')).to.equal(null); }); - it('remove middle value', function () { + it('remove middle value', () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', '/test1.json'); registry.add('New Scene 2', '/test2.json'); @@ -198,7 +198,7 @@ describe('SceneRegistry', function () { expect(registry.find('New Scene 3').url).to.equal('/test3.json'); }); - it('remove middle, url index', function () { + it('remove middle, url index', () => { const registry = new SceneRegistry(app); registry.add('New Scene 1', '/test1.json'); registry.add('New Scene 2', '/test2.json'); diff --git a/test/framework/test-component/system.mjs b/test/framework/test-component/system.mjs index 3ac49f48e61..1f569b1e392 100644 --- a/test/framework/test-component/system.mjs +++ b/test/framework/test-component/system.mjs @@ -1,8 +1,8 @@ +import { DummyComponent } from './component.mjs'; +import { DummyComponentData } from './data.mjs'; import { Component } from '../../../src/framework/components/component.js'; import { ComponentSystem } from '../../../src/framework/components/system.js'; -import { DummyComponent } from './component.mjs'; -import { DummyComponentData } from './data.mjs'; const dummySchema = [ 'enabled', diff --git a/test/framework/utils/entity-reference.test.mjs b/test/framework/utils/entity-reference.test.mjs index 494d6339513..bc2bc39ed87 100644 --- a/test/framework/utils/entity-reference.test.mjs +++ b/test/framework/utils/entity-reference.test.mjs @@ -1,18 +1,17 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; +import { restore, spy, stub } from 'sinon'; + import { Application } from '../../../src/framework/application.js'; import { Entity } from '../../../src/framework/entity.js'; import { EntityReference } from '../../../src/framework/utils/entity-reference.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; - import { DummyComponentSystem } from '../test-component/system.mjs'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -import { restore, spy, stub } from 'sinon'; /** @typedef {import('../../../../src/framework/components/component.js').Component} Component */ -describe('EntityReference', function () { +describe('EntityReference', () => { /** @type {Application} */ let app; /** @type {Entity} */ @@ -24,7 +23,7 @@ describe('EntityReference', function () { /** @type {Entity} */ let otherEntity2; - beforeEach(function () { + beforeEach(() => { const canvas = new HTMLCanvasElement(500, 500); app = new Application(canvas, { graphicsDevice: new NullGraphicsDevice(canvas) }); @@ -42,7 +41,7 @@ describe('EntityReference', function () { app.root.addChild(otherEntity2); }); - afterEach(function () { + afterEach(() => { restore(); app.destroy(); }); @@ -67,7 +66,7 @@ describe('EntityReference', function () { return entity._callbacks.get(eventName)?.length || 0; } - it('provides a reference to the entity once the guid is populated', function () { + it('provides a reference to the entity once the guid is populated', () => { const reference = new EntityReference(testComponent, 'myEntity1'); expect(reference.entity).to.equal(null); @@ -75,7 +74,7 @@ describe('EntityReference', function () { expect(reference.entity).to.equal(otherEntity1); }); - it('does not attempt to resolve the entity reference if the parent component is not on the scene graph yet', function () { + it('does not attempt to resolve the entity reference if the parent component is not on the scene graph yet', () => { app.root.removeChild(testEntity); spy(app.root, 'findByGuid'); @@ -87,7 +86,7 @@ describe('EntityReference', function () { expect(app.root.findByGuid.callCount).to.equal(0); }); - it('resolves the entity reference when onParentComponentEnable() is called', function () { + it('resolves the entity reference when onParentComponentEnable() is called', () => { app.root.removeChild(testEntity); const reference = new EntityReference(testComponent, 'myEntity1'); @@ -100,7 +99,7 @@ describe('EntityReference', function () { expect(reference.entity).to.equal(otherEntity1); }); - it('nullifies the reference when the guid is nullified', function () { + it('nullifies the reference when the guid is nullified', () => { const reference = new EntityReference(testComponent, 'myEntity1'); testComponent.myEntity1 = otherEntity1.getGuid(); expect(reference.entity).to.equal(otherEntity1); @@ -109,7 +108,7 @@ describe('EntityReference', function () { expect(reference.entity).to.equal(null); }); - it('nullifies the reference when the referenced entity is destroyed', function () { + it('nullifies the reference when the referenced entity is destroyed', () => { const reference = new EntityReference(testComponent, 'myEntity1'); testComponent.myEntity1 = otherEntity1.getGuid(); expect(reference.entity).to.equal(otherEntity1); @@ -118,7 +117,7 @@ describe('EntityReference', function () { expect(reference.entity).to.equal(null); }); - it('removes all entity and component listeners when the guid is reassigned', function () { + it('removes all entity and component listeners when the guid is reassigned', () => { const reference = new EntityReference(testComponent, 'myEntity1', { 'entity#foo': stub(), 'dummy#bar': stub() @@ -134,7 +133,7 @@ describe('EntityReference', function () { expect(getNumListenersForEvent(otherEntity1.dummy, 'bar')).to.equal(0); }); - it('removes all entity and component listeners when the parent component is removed', function () { + it('removes all entity and component listeners when the parent component is removed', () => { const reference = new EntityReference(testComponent, 'myEntity1', { 'entity#foo': stub(), 'dummy#bar': stub() @@ -154,7 +153,7 @@ describe('EntityReference', function () { expect(getNumListenersForEvent(app.systems.dummy, 'beforeremove')).to.equal(0); }); - it('removes all entity and component listeners when the parent component\'s entity is destroyed', function () { + it('removes all entity and component listeners when the parent component\'s entity is destroyed', () => { const reference = new EntityReference(testComponent, 'myEntity1', { 'entity#foo': stub(), 'dummy#bar': stub() @@ -174,7 +173,7 @@ describe('EntityReference', function () { expect(getNumListenersForEvent(app.systems.dummy, 'beforeremove')).to.equal(0); }); - it('fires component gain events when a guid is first assigned, if the referenced entity already has the component', function () { + it('fires component gain events when a guid is first assigned, if the referenced entity already has the component', () => { const gainListener = stub(); const reference = new EntityReference(testComponent, 'myEntity1', { @@ -187,7 +186,7 @@ describe('EntityReference', function () { expect(gainListener.callCount).to.equal(1); }); - it('fires component gain events once a component is added', function () { + it('fires component gain events once a component is added', () => { const gainListener = stub(); const reference = new EntityReference(testComponent, 'myEntity2', { @@ -204,7 +203,7 @@ describe('EntityReference', function () { expect(gainListener.callCount).to.equal(1); }); - it('fires component lose and gain events when a component is removed and re-added', function () { + it('fires component lose and gain events when a component is removed and re-added', () => { const gainListener = stub(); const loseListener = stub(); @@ -230,7 +229,7 @@ describe('EntityReference', function () { expect(loseListener.callCount).to.equal(1); }); - it('fires component lose events when the guid is reassigned, but only for component types that the entity had', function () { + it('fires component lose events when the guid is reassigned, but only for component types that the entity had', () => { const dummyLoseListener = stub(); const lightLoseListener = stub(); @@ -251,7 +250,7 @@ describe('EntityReference', function () { expect(lightLoseListener.callCount).to.equal(0); }); - it('forwards any events dispatched by a component', function () { + it('forwards any events dispatched by a component', () => { const fooListener = stub(); const barListener = stub(); @@ -276,7 +275,7 @@ describe('EntityReference', function () { expect(barListener.getCall(0).args[1]).to.equal('d'); }); - it('correctly handles component event forwarding across component removal and subsequent re-addition', function () { + it('correctly handles component event forwarding across component removal and subsequent re-addition', () => { const fooListener = stub(); const barListener = stub(); @@ -305,7 +304,7 @@ describe('EntityReference', function () { expect(barListener.callCount).to.equal(1); }); - it('forwards any events dispatched by the entity', function () { + it('forwards any events dispatched by the entity', () => { const fooListener = stub(); const barListener = stub(); @@ -330,7 +329,7 @@ describe('EntityReference', function () { expect(barListener.getCall(0).args[1]).to.equal('d'); }); - it('correctly handles entity event forwarding across entity nullification and subsequent reassignment', function () { + it('correctly handles entity event forwarding across entity nullification and subsequent reassignment', () => { const fooListener = stub(); const barListener = stub(); @@ -357,7 +356,7 @@ describe('EntityReference', function () { expect(barListener.callCount).to.equal(1); }); - it('validates the event map', function () { + it('validates the event map', () => { function testEventMap(eventMap) { const reference = new EntityReference(testComponent, 'myEntity1', eventMap); expect(reference).to.be.ok; @@ -365,24 +364,24 @@ describe('EntityReference', function () { const callback = stub(); - expect(function () { + expect(() => { testEventMap({ 'foo': callback }); }).to.throw('Invalid event listener description: `foo`'); - expect(function () { + expect(() => { testEventMap({ 'foo#': callback }); }).to.throw('Invalid event listener description: `foo#`'); - expect(function () { + expect(() => { testEventMap({ '#foo': callback }); }).to.throw('Invalid event listener description: `#foo`'); - expect(function () { + expect(() => { testEventMap({ 'foo#bar': null }); }).to.throw('Invalid or missing callback for event listener `foo#bar`'); }); - it('logs a warning if the entity property is set to anything other than a string, undefined or null', function () { + it('logs a warning if the entity property is set to anything other than a string, undefined or null', () => { stub(console, 'warn'); const reference = new EntityReference(testComponent, 'myEntity1'); @@ -400,7 +399,7 @@ describe('EntityReference', function () { expect(console.warn.getCall(0).args[0]).to.equal('Entity field `myEntity1` was set to unexpected type \'object\''); }); - it('set reference to a Entity instead of guid, converts property to guid', function () { + it('set reference to a Entity instead of guid, converts property to guid', () => { const reference = new EntityReference(testComponent, 'myEntity1'); testComponent.myEntity1 = otherEntity1; @@ -408,7 +407,7 @@ describe('EntityReference', function () { expect(reference.entity).to.equal(otherEntity1); }); - it('set reference to a Entity that is not in hierarchy, converts property to guid', function () { + it('set reference to a Entity that is not in hierarchy, converts property to guid', () => { const reference = new EntityReference(testComponent, 'myEntity1'); const entity = new Entity(); testComponent.myEntity1 = entity; @@ -417,13 +416,13 @@ describe('EntityReference', function () { expect(reference.entity).to.equal(entity); }); - it('hasComponent() returns false if the entity is not present', function () { + it('hasComponent() returns false if the entity is not present', () => { const reference = new EntityReference(testComponent, 'myEntity1'); expect(reference.hasComponent('dummy')).to.equal(false); }); - it('hasComponent() returns false if the entity is present but does not have a component of the provided type', function () { + it('hasComponent() returns false if the entity is present but does not have a component of the provided type', () => { const reference = new EntityReference(testComponent, 'myEntity1'); testComponent.myEntity1 = otherEntity1.getGuid(); otherEntity1.removeComponent('dummy'); @@ -431,7 +430,7 @@ describe('EntityReference', function () { expect(reference.hasComponent('dummy')).to.equal(false); }); - it('hasComponent() returns true if the entity is present and has a component of the provided type', function () { + it('hasComponent() returns true if the entity is present and has a component of the provided type', () => { const reference = new EntityReference(testComponent, 'myEntity1'); testComponent.myEntity1 = otherEntity1.getGuid(); diff --git a/test/platform/graphics/blend-state.test.mjs b/test/platform/graphics/blend-state.test.mjs index f036d122539..eb8b289b479 100644 --- a/test/platform/graphics/blend-state.test.mjs +++ b/test/platform/graphics/blend-state.test.mjs @@ -1,16 +1,17 @@ +import { expect } from 'chai'; + import { BlendState } from '../../../src/platform/graphics/blend-state.js'; import { BLENDEQUATION_ADD, BLENDEQUATION_MAX, BLENDEQUATION_MIN, BLENDMODE_ONE, BLENDMODE_ZERO, BLENDMODE_ONE_MINUS_DST_COLOR, BLENDMODE_SRC_ALPHA_SATURATE } from '../../../src/platform/graphics/constants.js'; -import { expect } from 'chai'; -describe('BlendState', function () { +describe('BlendState', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('empty', function () { + it('empty', () => { const bs = new BlendState(); expect(bs.blend).to.equal(false); expect(bs.colorOp).to.equal(BLENDEQUATION_ADD); @@ -25,7 +26,7 @@ describe('BlendState', function () { expect(bs.alphaWrite).to.equal(true); }); - it('minimal parameters', function () { + it('minimal parameters', () => { const bs = new BlendState(true, BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ZERO); expect(bs.blend).to.equal(true); expect(bs.colorOp).to.equal(BLENDEQUATION_ADD); @@ -40,10 +41,10 @@ describe('BlendState', function () { expect(bs.alphaWrite).to.equal(true); }); - it('full parameters', function () { + it('full parameters', () => { const bs = new BlendState(true, BLENDEQUATION_MIN, BLENDMODE_ONE, BLENDMODE_ZERO, - BLENDEQUATION_MAX, BLENDMODE_ONE_MINUS_DST_COLOR, BLENDMODE_SRC_ALPHA_SATURATE, - false, false, false, false); + BLENDEQUATION_MAX, BLENDMODE_ONE_MINUS_DST_COLOR, BLENDMODE_SRC_ALPHA_SATURATE, + false, false, false, false); expect(bs.blend).to.equal(true); expect(bs.colorOp).to.equal(BLENDEQUATION_MIN); expect(bs.colorSrcFactor).to.equal(BLENDMODE_ONE); diff --git a/test/platform/graphics/depth-state.test.mjs b/test/platform/graphics/depth-state.test.mjs index 62a99ae7688..194e0f5bae5 100644 --- a/test/platform/graphics/depth-state.test.mjs +++ b/test/platform/graphics/depth-state.test.mjs @@ -1,21 +1,22 @@ -import { DepthState } from '../../../src/platform/graphics/depth-state.js'; +import { expect } from 'chai'; + import { FUNC_LESSEQUAL, FUNC_ALWAYS, FUNC_NOTEQUAL } from '../../../src/platform/graphics/constants.js'; +import { DepthState } from '../../../src/platform/graphics/depth-state.js'; -import { expect } from 'chai'; -describe('DepthState', function () { +describe('DepthState', () => { - describe('#constructor', function () { + describe('#constructor', () => { - it('empty', function () { + it('empty', () => { const ds = new DepthState(); expect(ds.func).to.equal(FUNC_LESSEQUAL); expect(ds.write).to.equal(true); }); - it('full parameters', function () { + it('full parameters', () => { const ds = new DepthState(FUNC_NOTEQUAL, false); expect(ds.func).to.equal(FUNC_NOTEQUAL); expect(ds.write).to.equal(false); @@ -23,16 +24,16 @@ describe('DepthState', function () { }); - describe('#test property', function () { + describe('#test property', () => { - it('test enabled', function () { + it('test enabled', () => { const ds = new DepthState(); ds.test = true; expect(ds.func).to.equal(FUNC_LESSEQUAL); expect(ds.test).to.equal(true); }); - it('test disabled', function () { + it('test disabled', () => { const ds = new DepthState(); ds.test = false; expect(ds.func).to.equal(FUNC_ALWAYS); diff --git a/test/platform/input/keyboard.test.mjs b/test/platform/input/keyboard.test.mjs index cfb6a0c00ff..fa0365205e7 100644 --- a/test/platform/input/keyboard.test.mjs +++ b/test/platform/input/keyboard.test.mjs @@ -1,37 +1,38 @@ -import { Keyboard } from '../../../src/platform/input/keyboard.js'; +import { expect } from 'chai'; + import { EVENT_KEYDOWN, EVENT_KEYUP, KEY_UP } from '../../../src/platform/input/constants.js'; +import { Keyboard } from '../../../src/platform/input/keyboard.js'; -import { expect } from 'chai'; -describe('Keyboard', function () { +describe('Keyboard', () => { /** @type { Keyboard } */ let keyboard; - beforeEach(function () { + beforeEach(() => { keyboard = new Keyboard(); keyboard.attach(window); }); - afterEach(function () { + afterEach(() => { keyboard.detach(); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('should create a new instance', function () { + it('should create a new instance', () => { expect(keyboard).to.be.an.instanceOf(Keyboard); }); }); - describe('#isPressed', function () { + describe('#isPressed', () => { - it('should return false for a key that is not pressed', function () { + it('should return false for a key that is not pressed', () => { expect(keyboard.isPressed(KEY_UP)).to.be.false; }); - it('should return true for a key that is pressed', function () { + it('should return true for a key that is pressed', () => { const keyDownEvent = new KeyboardEvent('keydown', { keyCode: 38 // Up arrow }); @@ -53,10 +54,10 @@ describe('Keyboard', function () { }); - describe('#on', function () { + describe('#on', () => { - it('should handle keydown events', function (done) { - keyboard.on(EVENT_KEYDOWN, function (event) { + it('should handle keydown events', (done) => { + keyboard.on(EVENT_KEYDOWN, (event) => { expect(event.key).to.equal(KEY_UP); expect(event.element).to.equal(window); expect(event.event).to.be.an.instanceOf(KeyboardEvent); @@ -70,8 +71,8 @@ describe('Keyboard', function () { window.dispatchEvent(keyDownEvent); }); - it('should handle keyup events', function (done) { - keyboard.on(EVENT_KEYUP, function (event) { + it('should handle keyup events', (done) => { + keyboard.on(EVENT_KEYUP, (event) => { expect(event.key).to.equal(KEY_UP); expect(event.element).to.equal(window); expect(event.event).to.be.an.instanceOf(KeyboardEvent); @@ -87,13 +88,13 @@ describe('Keyboard', function () { }); - describe('#wasPressed', function () { + describe('#wasPressed', () => { - it('should return false for a key that was not pressed', function () { + it('should return false for a key that was not pressed', () => { expect(keyboard.wasPressed(KEY_UP)).to.be.false; }); - it('should return true for a key that was pressed since the last update', function () { + it('should return true for a key that was pressed since the last update', () => { const keyDownEvent = new KeyboardEvent('keydown', { keyCode: 38 // Up arrow }); @@ -108,13 +109,13 @@ describe('Keyboard', function () { }); - describe('#wasReleased', function () { + describe('#wasReleased', () => { - it('should return false for a key that was not released', function () { + it('should return false for a key that was not released', () => { expect(keyboard.wasReleased(KEY_UP)).to.be.false; }); - it('should return true for a key that was released since the last update', function () { + it('should return true for a key that was released since the last update', () => { const keyDownEvent = new KeyboardEvent('keydown', { keyCode: 38 // Up arrow }); diff --git a/test/platform/input/mouse.test.mjs b/test/platform/input/mouse.test.mjs index 9d0eb29f058..19f4c7913c9 100644 --- a/test/platform/input/mouse.test.mjs +++ b/test/platform/input/mouse.test.mjs @@ -1,10 +1,11 @@ -import { Mouse } from '../../../src/platform/input/mouse.js'; +import { expect } from 'chai'; + import { EVENT_MOUSEDOWN, EVENT_MOUSEUP, MOUSEBUTTON_LEFT, MOUSEBUTTON_MIDDLE, MOUSEBUTTON_RIGHT } from '../../../src/platform/input/constants.js'; +import { Mouse } from '../../../src/platform/input/mouse.js'; -import { expect } from 'chai'; const buttons = [MOUSEBUTTON_LEFT, MOUSEBUTTON_MIDDLE, MOUSEBUTTON_RIGHT]; @@ -13,36 +14,36 @@ Mouse.prototype._getTargetCoords = function (event) { return { x: 0, y: 0 }; }; -describe('Mouse', function () { +describe('Mouse', () => { /** @type { Mouse } */ let mouse; - beforeEach(function () { + beforeEach(() => { mouse = new Mouse(document.body); }); - afterEach(function () { + afterEach(() => { mouse.detach(); }); - describe('#constructor', function () { + describe('#constructor', () => { - it('should create a new instance', function () { + it('should create a new instance', () => { expect(mouse).to.be.an.instanceOf(Mouse); }); }); - describe('#isPressed', function () { + describe('#isPressed', () => { - it('should return false for all buttons by default', function () { + it('should return false for all buttons by default', () => { for (const button of buttons) { expect(mouse.isPressed(button)).to.be.false; } }); - it('should return true for a mouse button that is pressed', function () { + it('should return true for a mouse button that is pressed', () => { for (const button of buttons) { const mouseDownEvent = new MouseEvent('mousedown', { button }); window.dispatchEvent(mouseDownEvent); @@ -58,10 +59,10 @@ describe('Mouse', function () { }); - describe('#on', function () { + describe('#on', () => { - it('should handle mousedown events', function (done) { - mouse.on(EVENT_MOUSEDOWN, function (event) { + it('should handle mousedown events', (done) => { + mouse.on(EVENT_MOUSEDOWN, (event) => { expect(event.button).to.equal(MOUSEBUTTON_LEFT); expect(event.event).to.be.an.instanceOf(MouseEvent); @@ -72,8 +73,8 @@ describe('Mouse', function () { window.dispatchEvent(mouseDownEvent); }); - it('should handle mouseup events', function (done) { - mouse.on(EVENT_MOUSEUP, function (event) { + it('should handle mouseup events', (done) => { + mouse.on(EVENT_MOUSEUP, (event) => { expect(event.button).to.equal(MOUSEBUTTON_LEFT); expect(event.event).to.be.an.instanceOf(MouseEvent); @@ -86,15 +87,15 @@ describe('Mouse', function () { }); - describe('#wasPressed', function () { + describe('#wasPressed', () => { - it('should return false for all buttons by default', function () { + it('should return false for all buttons by default', () => { for (const button of buttons) { expect(mouse.wasPressed(button)).to.be.false; } }); - it('should return true for a mouse button that was pressed', function () { + it('should return true for a mouse button that was pressed', () => { for (const button of buttons) { const mouseDownEvent = new MouseEvent('mousedown', { button }); window.dispatchEvent(mouseDownEvent); @@ -109,15 +110,15 @@ describe('Mouse', function () { }); - describe('#wasReleased', function () { + describe('#wasReleased', () => { - it('should return false for all buttons by default', function () { + it('should return false for all buttons by default', () => { for (const button of buttons) { expect(mouse.wasReleased(button)).to.be.false; } }); - it('should return true for a mouse button that was released', function () { + it('should return true for a mouse button that was released', () => { for (const button of buttons) { const mouseDownEvent = new MouseEvent('mousedown', { button }); window.dispatchEvent(mouseDownEvent); diff --git a/test/platform/net/http.test.mjs b/test/platform/net/http.test.mjs index 850ae3a4843..c47cf09ee19 100644 --- a/test/platform/net/http.test.mjs +++ b/test/platform/net/http.test.mjs @@ -1,25 +1,25 @@ -import { http, Http } from '../../../src/platform/net/http.js'; - import { expect } from 'chai'; import { restore, spy } from 'sinon'; -describe('Http', function () { +import { http, Http } from '../../../src/platform/net/http.js'; + +describe('Http', () => { let retryDelay; - beforeEach(function () { + beforeEach(() => { retryDelay = Http.retryDelay; Http.retryDelay = 1; }); - afterEach(function () { + afterEach(() => { Http.retryDelay = retryDelay; restore(); }); - describe('#get()', function () { + describe('#get()', () => { - it('returns resource', function (done) { - http.get('http://localhost:3000/test/test-assets/test.json', function (err, data) { + it('returns resource', (done) => { + http.get('http://localhost:3000/test/test-assets/test.json', (err, data) => { expect(err).to.equal(null); expect(data).to.deep.equal({ a: 1, @@ -30,32 +30,32 @@ describe('Http', function () { }); }); - it('does not retry if retry is false', function (done) { + it('does not retry if retry is false', (done) => { spy(http, 'request'); - http.get('http://localhost:3000/someurl.json', function (err, data) { + http.get('http://localhost:3000/someurl.json', (err, data) => { expect(err).to.equal(404); expect(http.request.callCount).to.equal(1); done(); }); }); - it('retries resource and returns 404 in the end if not found', function (done) { + it('retries resource and returns 404 in the end if not found', (done) => { spy(http, 'request'); http.get('http://localhost:3000/someurl.json', { retry: true, maxRetries: 2 - }, function (err) { + }, (err) => { expect(err).to.equal(404); expect(http.request.callCount).to.equal(3); done(); }); }); - it('retries resource 5 times by default', function (done) { + it('retries resource 5 times by default', (done) => { spy(http, 'request'); http.get('http://localhost:3000/someurl.json', { retry: true - }, function (err) { + }, (err) => { expect(http.request.callCount).to.equal(6); done(); }); diff --git a/test/scene/batching/batch-manager.test.mjs b/test/scene/batching/batch-manager.test.mjs index 24f66ac35f2..7ba59a41051 100644 --- a/test/scene/batching/batch-manager.test.mjs +++ b/test/scene/batching/batch-manager.test.mjs @@ -1,13 +1,13 @@ +import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; +import { expect } from 'chai'; + import { Application } from '../../../src/framework/application.js'; import { Entity } from '../../../src/framework/entity.js'; import { NullGraphicsDevice } from '../../../src/platform/graphics/null/null-graphics-device.js'; import { LAYERID_WORLD } from '../../../src/scene/constants.js'; -import { HTMLCanvasElement } from '@playcanvas/canvas-mock'; - -import { expect } from 'chai'; -describe('BatchManager', function () { +describe('BatchManager', () => { beforeEach(function () { const canvas = new HTMLCanvasElement(500, 500); diff --git a/test/scene/composition/layer-composition.test.mjs b/test/scene/composition/layer-composition.test.mjs index 068cdf8698e..2999b7fefca 100644 --- a/test/scene/composition/layer-composition.test.mjs +++ b/test/scene/composition/layer-composition.test.mjs @@ -1,7 +1,8 @@ -import { Layer } from '../../../src/scene/layer.js'; +import { expect } from 'chai'; + import { LayerComposition } from '../../../src/scene/composition/layer-composition.js'; +import { Layer } from '../../../src/scene/layer.js'; -import { expect } from 'chai'; describe('LayerComposition', function () { @@ -18,7 +19,7 @@ describe('LayerComposition', function () { this.composition = null; }); - describe('#constructor', function () { + describe('#constructor', () => { it('creates a new LayerComposition', function () { expect(this.composition).to.be.an.instanceof(LayerComposition); @@ -26,7 +27,7 @@ describe('LayerComposition', function () { }); - describe('#getLayerById', function () { + describe('#getLayerById', () => { it('should work after push()', function () { this.composition.push(this.layer); @@ -78,7 +79,7 @@ describe('LayerComposition', function () { }); - describe('#getOpaqueIndex', function () { + describe('#getOpaqueIndex', () => { it('should return correct index after push()', function () { this.composition.push(this.layer); @@ -103,7 +104,7 @@ describe('LayerComposition', function () { }); - describe('#getTransparentIndex', function () { + describe('#getTransparentIndex', () => { it('should return correct index after push()', function () { this.composition.push(this.layer); @@ -128,7 +129,7 @@ describe('LayerComposition', function () { }); - describe('#getLayerByName', function () { + describe('#getLayerByName', () => { it('should return layer', function () { this.composition.push(this.layer); @@ -141,7 +142,7 @@ describe('LayerComposition', function () { }); - describe('#sortTransparentLayers', function () { + describe('#sortTransparentLayers', () => { it('should return negative if the first layers are on top of the second layers', function () { const layerFront = new Layer({ id: 2 }); @@ -259,7 +260,7 @@ describe('LayerComposition', function () { }); - describe('#sortOpaqueLayers', function () { + describe('#sortOpaqueLayers', () => { it('should return negative if the first layers are on top of the second layers', function () { const layerFront = new Layer({ id: 2 }); diff --git a/test/scene/graph-node.test.mjs b/test/scene/graph-node.test.mjs index a534ba447ea..f8c831cbb41 100644 --- a/test/scene/graph-node.test.mjs +++ b/test/scene/graph-node.test.mjs @@ -1,22 +1,23 @@ -import { GraphNode } from '../../src/scene/graph-node.js'; +import { expect } from 'chai'; + import { Mat4 } from '../../src/core/math/mat4.js'; import { Quat } from '../../src/core/math/quat.js'; -import { Tags } from '../../src/core/tags.js'; import { Vec3 } from '../../src/core/math/vec3.js'; +import { Tags } from '../../src/core/tags.js'; +import { GraphNode } from '../../src/scene/graph-node.js'; -import { expect } from 'chai'; -describe('GraphNode', function () { +describe('GraphNode', () => { - describe('#children', function () { + describe('#children', () => { - it('should be an empty array by default', function () { + it('should be an empty array by default', () => { const root = new GraphNode(); expect(root.children).to.be.an('array'); expect(root.children).to.be.empty; }); - it('should be an array of GraphNode', function () { + it('should be an array of GraphNode', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); @@ -26,30 +27,30 @@ describe('GraphNode', function () { }); - describe('#enabled', function () { + describe('#enabled', () => { - it('should be false by default', function () { + it('should be false by default', () => { const root = new GraphNode(); expect(root.enabled).to.be.false; }); }); - describe('#graphDepth', function () { + describe('#graphDepth', () => { - it('should be 0 by default', function () { + it('should be 0 by default', () => { const root = new GraphNode(); expect(root.graphDepth).to.equal(0); }); - it('should be 1 if the node is a child', function () { + it('should be 1 if the node is a child', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); expect(child.graphDepth).to.equal(1); }); - it('should be 2 if the node is a grandchild', function () { + it('should be 2 if the node is a grandchild', () => { const root = new GraphNode(); const child = new GraphNode(); const grandChild = new GraphNode(); @@ -60,14 +61,14 @@ describe('GraphNode', function () { }); - describe('#parent', function () { + describe('#parent', () => { - it('should be null by default', function () { + it('should be null by default', () => { const node = new GraphNode(); expect(node.parent).to.be.null; }); - it('should be set to the parent node', function () { + it('should be set to the parent node', () => { const parent = new GraphNode(); const child = new GraphNode(); parent.addChild(child); @@ -76,19 +77,19 @@ describe('GraphNode', function () { }); - describe('#name', function () { + describe('#name', () => { - it('should be an \'Untitled\' by default', function () { + it('should be an \'Untitled\' by default', () => { const node = new GraphNode(); expect(node.name).to.equal('Untitled'); }); - it('can be set via the constructor', function () { + it('can be set via the constructor', () => { const node = new GraphNode('root'); expect(node.name).to.equal('root'); }); - it('can be set to a new name', function () { + it('can be set to a new name', () => { const node = new GraphNode('node'); node.name = 'root'; expect(node.name).to.equal('root'); @@ -96,21 +97,21 @@ describe('GraphNode', function () { }); - describe('#path', function () { + describe('#path', () => { - it('returns empty string for root node', function () { + it('returns empty string for root node', () => { const root = new GraphNode('root'); expect(root.path).to.equal(''); }); - it('returns path to child node', function () { + it('returns path to child node', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); expect(child.path).to.equal('child'); }); - it('returns path to grandchild node', function () { + it('returns path to grandchild node', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); const grandchild = new GraphNode('grandchild'); @@ -121,21 +122,21 @@ describe('GraphNode', function () { }); - describe('#root', function () { + describe('#root', () => { - it('returns itself for root node', function () { + it('returns itself for root node', () => { const root = new GraphNode('root'); expect(root.root).to.equal(root); }); - it('returns root node for child node', function () { + it('returns root node for child node', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); expect(child.root).to.equal(root); }); - it('returns root node for grandchild node', function () { + it('returns root node for grandchild node', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); const grandchild = new GraphNode('grandchild'); @@ -146,9 +147,9 @@ describe('GraphNode', function () { }); - describe('#tags', function () { + describe('#tags', () => { - it('should be empty by default', function () { + it('should be empty by default', () => { const node = new GraphNode(); expect(node.tags).to.be.an.instanceof(Tags); expect(node.tags.size).to.equal(0); @@ -156,9 +157,9 @@ describe('GraphNode', function () { }); - describe('#constructor()', function () { + describe('#constructor()', () => { - it('supports zero arguments', function () { + it('supports zero arguments', () => { const node = new GraphNode(); expect(node.children).to.be.an('array').with.lengthOf(0); expect(node.enabled).to.equal(false); @@ -171,7 +172,7 @@ describe('GraphNode', function () { expect(node.up).to.be.an.instanceof(Vec3); }); - it('supports one argument', function () { + it('supports one argument', () => { const node = new GraphNode('root'); expect(node.children).to.be.an('array').with.lengthOf(0); expect(node.enabled).to.equal(false); @@ -185,9 +186,9 @@ describe('GraphNode', function () { }); }); - describe('#addChild()', function () { + describe('#addChild()', () => { - it('adds a child node', function () { + it('adds a child node', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); @@ -198,8 +199,8 @@ describe('GraphNode', function () { }); - describe('#clone', function () { - it('ensures that an instance of a subclass keeps its class prototype', function () { + describe('#clone', () => { + it('ensures that an instance of a subclass keeps its class prototype', () => { class UserGraphNode extends GraphNode {} const a = new UserGraphNode(); const b = a.clone(); @@ -207,9 +208,9 @@ describe('GraphNode', function () { }); }); - describe('#find()', function () { + describe('#find()', () => { - it('finds a node by property', function () { + it('finds a node by property', () => { const root = new GraphNode(); const child = new GraphNode('Child'); root.addChild(child); @@ -227,25 +228,25 @@ describe('GraphNode', function () { expect(res).to.be.an('array').with.lengthOf(0); }); - it('finds a node by filter function', function () { + it('finds a node by filter function', () => { const root = new GraphNode(); const child = new GraphNode('Child'); root.addChild(child); let res; - res = root.find(function (node) { + res = root.find((node) => { return node.name === 'Untitled'; }); expect(res).to.be.an('array').with.lengthOf(1); expect(res[0]).to.equal(root); - res = root.find(function (node) { + res = root.find((node) => { return node.name === 'Child'; }); expect(res).to.be.an('array').with.lengthOf(1); expect(res[0]).to.equal(child); - res = root.find(function (node) { + res = root.find((node) => { return node.name === 'Not Found'; }); expect(res).to.be.an('array').with.lengthOf(0); @@ -253,23 +254,23 @@ describe('GraphNode', function () { }); - describe('#findByName()', function () { + describe('#findByName()', () => { - it('finds root by name', function () { + it('finds root by name', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); expect(root.findByName('root')).to.equal(root); }); - it('finds child by name', function () { + it('finds child by name', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); expect(root.findByName('child')).to.equal(child); }); - it('returns null if no node is found', function () { + it('returns null if no node is found', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); @@ -278,16 +279,16 @@ describe('GraphNode', function () { }); - describe('#findByPath()', function () { + describe('#findByPath()', () => { - it('finds a child by path', function () { + it('finds a child by path', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); expect(root.findByPath('child')).to.equal(child); }); - it('finds a grandchild by path (string argument)', function () { + it('finds a grandchild by path (string argument)', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); const grandchild = new GraphNode('grandchild'); @@ -296,7 +297,7 @@ describe('GraphNode', function () { expect(root.findByPath('child/grandchild')).to.equal(grandchild); }); - it('finds a grandchild by path (array argument)', function () { + it('finds a grandchild by path (array argument)', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); const grandchild = new GraphNode('grandchild'); @@ -305,7 +306,7 @@ describe('GraphNode', function () { expect(root.findByPath(['child', 'grandchild'])).to.equal(grandchild); }); - it('returns null if no node is found', function () { + it('returns null if no node is found', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); @@ -314,16 +315,16 @@ describe('GraphNode', function () { }); - describe('#findByTag()', function () { + describe('#findByTag()', () => { - it('does not search the root node', function () { + it('does not search the root node', () => { const root = new GraphNode('root'); root.tags.add('tag'); const result = root.findByTag('tag'); expect(result).to.be.an('array').with.lengthOf(0); }); - it('returns an array of nodes that have the query tag', function () { + it('returns an array of nodes that have the query tag', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); @@ -333,7 +334,7 @@ describe('GraphNode', function () { expect(result[0]).to.equal(child); }); - it('returns an array of nodes that have at least one of the query tags', function () { + it('returns an array of nodes that have at least one of the query tags', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); const grandchild = new GraphNode('grandchild'); @@ -347,7 +348,7 @@ describe('GraphNode', function () { expect(result[0]).to.equal(grandchild); }); - it('returns an array of nodes that have all of the supplied tags', function () { + it('returns an array of nodes that have all of the supplied tags', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); const grandchild = new GraphNode('grandchild'); @@ -361,7 +362,7 @@ describe('GraphNode', function () { expect(result[0]).to.equal(grandchild); }); - it('returns an empty array if the search fails', function () { + it('returns an empty array if the search fails', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); @@ -371,9 +372,9 @@ describe('GraphNode', function () { }); - describe('#findOne()', function () { + describe('#findOne()', () => { - it('finds a node by property', function () { + it('finds a node by property', () => { const root = new GraphNode(); const child = new GraphNode('Child'); root.addChild(child); @@ -389,23 +390,23 @@ describe('GraphNode', function () { expect(res).to.be.null; }); - it('finds a node by filter function', function () { + it('finds a node by filter function', () => { const root = new GraphNode(); const child = new GraphNode('Child'); root.addChild(child); let res; - res = root.findOne(function (node) { + res = root.findOne((node) => { return node.name === 'Untitled'; }); expect(res).to.equal(root); - res = root.findOne(function (node) { + res = root.findOne((node) => { return node.name === 'Child'; }); expect(res).to.equal(child); - res = root.findOne(function (node) { + res = root.findOne((node) => { return node.name === 'Not Found'; }); expect(res).to.be.null; @@ -413,9 +414,9 @@ describe('GraphNode', function () { }); - describe('#forEach()', function () { + describe('#forEach()', () => { - it('iterates over all nodes', function () { + it('iterates over all nodes', () => { const root = new GraphNode(); const child1 = new GraphNode(); const child2 = new GraphNode(); @@ -433,9 +434,9 @@ describe('GraphNode', function () { }); - describe('#getEulerAngles()', function () { + describe('#getEulerAngles()', () => { - it('returns the euler angles', function () { + it('returns the euler angles', () => { const node = new GraphNode(); const angles = node.getEulerAngles(); expect(angles).to.be.an.instanceof(Vec3); @@ -446,9 +447,9 @@ describe('GraphNode', function () { }); - describe('#getLocalScale()', function () { + describe('#getLocalScale()', () => { - it('returns the default local scale of a node', function () { + it('returns the default local scale of a node', () => { const node = new GraphNode(); const scale = node.getLocalScale(); expect(scale).to.be.an.instanceof(Vec3); @@ -457,7 +458,7 @@ describe('GraphNode', function () { expect(scale.z).to.equal(1); }); - it('returns the local scale last set on a node', function () { + it('returns the local scale last set on a node', () => { const node = new GraphNode(); node.setLocalScale(2, 3, 4); const scale = node.getLocalScale(); @@ -469,16 +470,16 @@ describe('GraphNode', function () { }); - describe('#getLocalTransform()', function () { + describe('#getLocalTransform()', () => { - it('returns an identity matrix for a newly created node', function () { + it('returns an identity matrix for a newly created node', () => { const node = new GraphNode(); const transform = node.getLocalTransform(); expect(transform).to.be.an.instanceof(Mat4); expect(transform.equals(Mat4.IDENTITY)).to.be.true; }); - it('returns the local transform matrix of a transformed node', function () { + it('returns the local transform matrix of a transformed node', () => { const node = new GraphNode(); node.setLocalPosition(1, 2, 3); node.setLocalScale(4, 5, 6); @@ -489,16 +490,16 @@ describe('GraphNode', function () { }); - describe('#getWorldTransform()', function () { + describe('#getWorldTransform()', () => { - it('returns an identity matrix for a newly created node', function () { + it('returns an identity matrix for a newly created node', () => { const node = new GraphNode(); const transform = node.getWorldTransform(); expect(transform).to.be.an.instanceof(Mat4); expect(transform.equals(Mat4.IDENTITY)).to.be.true; }); - it('returns the world transform matrix of a transformed node', function () { + it('returns the world transform matrix of a transformed node', () => { const node = new GraphNode(); node.setLocalPosition(1, 2, 3); node.setLocalScale(4, 5, 6); @@ -507,7 +508,7 @@ describe('GraphNode', function () { expect(transform.data).to.deep.equal(expected); }); - it('returns the world transform matrix of a transformed child node', function () { + it('returns the world transform matrix of a transformed child node', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); @@ -533,9 +534,9 @@ describe('GraphNode', function () { }); - describe('#insertChild()', function () { + describe('#insertChild()', () => { - it('inserts a single child node', function () { + it('inserts a single child node', () => { const root = new GraphNode(); const child = new GraphNode(); root.insertChild(child, 0); @@ -544,7 +545,7 @@ describe('GraphNode', function () { expect(child.parent).to.equal(root); }); - it('inserts a child node at the beginning', function () { + it('inserts a child node at the beginning', () => { const root = new GraphNode(); const child1 = new GraphNode(); const child2 = new GraphNode(); @@ -557,7 +558,7 @@ describe('GraphNode', function () { expect(child2.parent).to.equal(root); }); - it('inserts a child node at the end', function () { + it('inserts a child node at the end', () => { const root = new GraphNode(); const child1 = new GraphNode(); const child2 = new GraphNode(); @@ -572,16 +573,16 @@ describe('GraphNode', function () { }); - describe('#isAncestorOf()', function () { + describe('#isAncestorOf()', () => { - it('returns true if a parent node is an ancestor of a child node', function () { + it('returns true if a parent node is an ancestor of a child node', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); expect(root.isAncestorOf(child)).to.be.true; }); - it('returns true if a grandparent node is an ancestor of a grandchild node', function () { + it('returns true if a grandparent node is an ancestor of a grandchild node', () => { const root = new GraphNode(); const child = new GraphNode(); const grandchild = new GraphNode(); @@ -590,29 +591,29 @@ describe('GraphNode', function () { expect(root.isAncestorOf(grandchild)).to.be.true; }); - it('returns false if a node is not an ancestor of another node', function () { + it('returns false if a node is not an ancestor of another node', () => { const root = new GraphNode(); const child = new GraphNode(); expect(root.isAncestorOf(child)).to.be.false; }); - it('asserts that nodes are not ancestors of themselves', function () { + it('asserts that nodes are not ancestors of themselves', () => { const node = new GraphNode(); expect(node.isAncestorOf(node)).to.be.false; }); }); - describe('#isDescendantOf()', function () { + describe('#isDescendantOf()', () => { - it('returns true if a child node is a descendant of a parent node', function () { + it('returns true if a child node is a descendant of a parent node', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); expect(child.isDescendantOf(root)).to.be.true; }); - it('returns true if a grandchild node is an descendant of a grandparent node', function () { + it('returns true if a grandchild node is an descendant of a grandparent node', () => { const root = new GraphNode(); const child = new GraphNode(); const grandchild = new GraphNode(); @@ -621,22 +622,22 @@ describe('GraphNode', function () { expect(grandchild.isDescendantOf(root)).to.be.true; }); - it('returns false if a node is not a descendant of another node', function () { + it('returns false if a node is not a descendant of another node', () => { const root = new GraphNode(); const child = new GraphNode(); expect(child.isDescendantOf(root)).to.be.false; }); - it('asserts that nodes are not descendants of themselves', function () { + it('asserts that nodes are not descendants of themselves', () => { const node = new GraphNode(); expect(node.isDescendantOf(node)).to.be.false; }); }); - describe('#remove', function () { + describe('#remove', () => { - it('removes the node from its parent, unparenting it', function () { + it('removes the node from its parent, unparenting it', () => { const node = new GraphNode(); const child = new GraphNode(); node.addChild(child); @@ -647,9 +648,9 @@ describe('GraphNode', function () { }); - describe('#removeChild()', function () { + describe('#removeChild()', () => { - it('removes a child node', function () { + it('removes a child node', () => { const node = new GraphNode(); const child = new GraphNode(); node.addChild(child); @@ -660,9 +661,9 @@ describe('GraphNode', function () { }); - describe('#reparent()', function () { + describe('#reparent()', () => { - it('reparents a child node', function () { + it('reparents a child node', () => { const node = new GraphNode(); const child = new GraphNode(); node.addChild(child); @@ -676,9 +677,9 @@ describe('GraphNode', function () { }); - describe('#rotate()', function () { + describe('#rotate()', () => { - it('leaves rotation unchanged for a zero rotation (number inputs)', function () { + it('leaves rotation unchanged for a zero rotation (number inputs)', () => { const node = new GraphNode(); const anglesPre = node.getEulerAngles().clone(); node.rotate(0, 0, 0); @@ -686,7 +687,7 @@ describe('GraphNode', function () { expect(anglesPre.equals(anglesPost)).to.be.true; }); - it('leaves rotation unchanged for a zero rotation (vector input)', function () { + it('leaves rotation unchanged for a zero rotation (vector input)', () => { const node = new GraphNode(); const anglesPre = node.getEulerAngles().clone(); node.rotate(Vec3.ZERO); @@ -694,7 +695,7 @@ describe('GraphNode', function () { expect(anglesPre.equals(anglesPost)).to.be.true; }); - it('accumulates rotations in a node', function () { + it('accumulates rotations in a node', () => { const node = new GraphNode(); node.rotate(1, 0, 0); node.rotate(2, 0, 0); @@ -706,7 +707,7 @@ describe('GraphNode', function () { expect(angles.z).to.be.closeTo(0, 0.00001); }); - it('accumulates rotations in a hierarchy', function () { + it('accumulates rotations in a hierarchy', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); @@ -727,9 +728,9 @@ describe('GraphNode', function () { }); - describe('#rotateLocal()', function () { + describe('#rotateLocal()', () => { - it('leaves rotation unchanged for a zero rotation (number inputs)', function () { + it('leaves rotation unchanged for a zero rotation (number inputs)', () => { const node = new GraphNode(); const anglesPre = node.getEulerAngles().clone(); node.rotateLocal(0, 0, 0); @@ -737,7 +738,7 @@ describe('GraphNode', function () { expect(anglesPre.equals(anglesPost)).to.be.true; }); - it('leaves rotation unchanged for a zero rotation (vector input)', function () { + it('leaves rotation unchanged for a zero rotation (vector input)', () => { const node = new GraphNode(); const anglesPre = node.getEulerAngles().clone(); node.rotateLocal(Vec3.ZERO); @@ -745,7 +746,7 @@ describe('GraphNode', function () { expect(anglesPre.equals(anglesPost)).to.be.true; }); - it('accumulates rotations in a node', function () { + it('accumulates rotations in a node', () => { const node = new GraphNode(); node.rotateLocal(1, 0, 0); node.rotateLocal(2, 0, 0); @@ -757,7 +758,7 @@ describe('GraphNode', function () { expect(angles.z).to.be.closeTo(0, 0.00001); }); - it('accumulates rotations in a hierarchy', function () { + it('accumulates rotations in a hierarchy', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); @@ -778,9 +779,9 @@ describe('GraphNode', function () { }); - describe('#translate()', function () { + describe('#translate()', () => { - it('translates hierarchical nodes with number arguments', function () { + it('translates hierarchical nodes with number arguments', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); @@ -802,7 +803,7 @@ describe('GraphNode', function () { expect(pos.z).to.equal(9); }); - it('translates hierarchical nodes with a vector argument', function () { + it('translates hierarchical nodes with a vector argument', () => { const root = new GraphNode(); const child = new GraphNode(); root.addChild(child); @@ -826,9 +827,9 @@ describe('GraphNode', function () { }); - describe('#translateLocal()', function () { + describe('#translateLocal()', () => { - it('GraphNode: translateLocal in hierarchy', function () { + it('GraphNode: translateLocal in hierarchy', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); @@ -851,8 +852,8 @@ describe('GraphNode', function () { }); - describe('#setPositionAndRotation()', function () { - it('setPositionAndRotation is the same as setPosition and setRotation', function () { + describe('#setPositionAndRotation()', () => { + it('setPositionAndRotation is the same as setPosition and setRotation', () => { const root = new GraphNode('root'); const child = new GraphNode('child'); root.addChild(child); diff --git a/test/scene/materials/shader-material.test.mjs b/test/scene/materials/shader-material.test.mjs index eaa882d5a10..bb38830f9e3 100644 --- a/test/scene/materials/shader-material.test.mjs +++ b/test/scene/materials/shader-material.test.mjs @@ -1,10 +1,11 @@ +import { expect } from 'chai'; + import { CULLFACE_BACK, FUNC_LESSEQUAL } from '../../../src/platform/graphics/constants.js'; import { BLEND_NONE } from '../../../src/scene/constants.js'; import { ShaderMaterial } from '../../../src/scene/materials/shader-material.js'; -import { expect } from 'chai'; -describe('Material', function () { +describe('Material', () => { function checkDefaultMaterial(material) { expect(material).to.be.an.instanceof(ShaderMaterial); @@ -26,18 +27,18 @@ describe('Material', function () { expect(material.stencilFront).to.not.exist; } - describe('#constructor()', function () { + describe('#constructor()', () => { - it('should create a new instance', function () { + it('should create a new instance', () => { const material = new ShaderMaterial(); checkDefaultMaterial(material); }); }); - describe('#clone()', function () { + describe('#clone()', () => { - it('should clone a material', function () { + it('should clone a material', () => { const material = new ShaderMaterial(); const clone = material.clone(); checkDefaultMaterial(clone); @@ -45,9 +46,9 @@ describe('Material', function () { }); - describe('#copy()', function () { + describe('#copy()', () => { - it('should copy a material', function () { + it('should copy a material', () => { const src = new ShaderMaterial(); const dst = new ShaderMaterial(); dst.copy(src); diff --git a/test/scene/materials/standard-material.test.mjs b/test/scene/materials/standard-material.test.mjs index a1aff4a6887..fbf186bc8f0 100644 --- a/test/scene/materials/standard-material.test.mjs +++ b/test/scene/materials/standard-material.test.mjs @@ -1,12 +1,13 @@ -import { CUBEPROJ_NONE, DETAILMODE_MUL, DITHER_NONE, FRESNEL_SCHLICK, SPECOCC_AO } from '../../../src/scene/constants.js'; +import { expect } from 'chai'; + import { Color } from '../../../src/core/math/color.js'; +import { Vec2 } from '../../../src/core/math/vec2.js'; +import { CUBEPROJ_NONE, DETAILMODE_MUL, DITHER_NONE, FRESNEL_SCHLICK, SPECOCC_AO } from '../../../src/scene/constants.js'; import { Material } from '../../../src/scene/materials/material.js'; import { StandardMaterial } from '../../../src/scene/materials/standard-material.js'; -import { Vec2 } from '../../../src/core/math/vec2.js'; -import { expect } from 'chai'; -describe('StandardMaterial', function () { +describe('StandardMaterial', () => { function checkDefaultMaterial(material) { expect(material).to.be.an.instanceof(StandardMaterial); @@ -282,18 +283,18 @@ describe('StandardMaterial', function () { expect(material.useSkybox).to.equal(true); } - describe('#constructor()', function () { + describe('#constructor()', () => { - it('should create a new instance', function () { + it('should create a new instance', () => { const material = new StandardMaterial(); checkDefaultMaterial(material); }); }); - describe('#clone()', function () { + describe('#clone()', () => { - it('should clone a material', function () { + it('should clone a material', () => { const material = new StandardMaterial(); const clone = material.clone(); checkDefaultMaterial(clone); @@ -301,9 +302,9 @@ describe('StandardMaterial', function () { }); - describe('#copy()', function () { + describe('#copy()', () => { - it('should copy a material', function () { + it('should copy a material', () => { const src = new StandardMaterial(); const dst = new StandardMaterial(); dst.copy(src); diff --git a/utils/plugins/rollup-dynamic.mjs b/utils/plugins/rollup-dynamic.mjs index 78ff529e5a4..e7271b6ad95 100644 --- a/utils/plugins/rollup-dynamic.mjs +++ b/utils/plugins/rollup-dynamic.mjs @@ -12,7 +12,7 @@ export function dynamicImportLegacyBrowserSupport() { name: 'dynamic-import-old-browsers', transform(code, id) { return { - code: code.replace(/([^\w])import\(/g, '$1new Function("modulePath", "return import(modulePath)")('), + code: code.replace(/(\W)import\(/g, '$1new Function("modulePath", "return import(modulePath)")('), map: null }; } diff --git a/utils/plugins/rollup-run-tsc.mjs b/utils/plugins/rollup-run-tsc.mjs index 710f976dcec..5804ed4e578 100644 --- a/utils/plugins/rollup-run-tsc.mjs +++ b/utils/plugins/rollup-run-tsc.mjs @@ -1,5 +1,5 @@ -import * as fs from 'node:fs'; import { execSync } from 'node:child_process'; +import * as fs from 'node:fs'; const GREEN_OUT = '\x1b[32m'; diff --git a/utils/plugins/rollup-shader-chunks.mjs b/utils/plugins/rollup-shader-chunks.mjs index 36f36bc8719..7a975d6f93d 100644 --- a/utils/plugins/rollup-shader-chunks.mjs +++ b/utils/plugins/rollup-shader-chunks.mjs @@ -29,15 +29,15 @@ export function shaderChunks({ transform(source, shader) { if (!filter(shader)) return; - source = source.replace(/\/\* *glsl *\*\/\s*(`.*?`)/gs, function (match, glsl) { + source = source.replace(/\/\* *glsl *\*\/\s*(`.*?`)/gs, (match, glsl) => { return glsl - .trim() // trim whitespace - .replace(/\r/g, '') // Remove carriage returns - .replace(/ {4}/g, '\t') // 4 spaces to tabs - .replace(/[ \t]*\/\/.*/g, '') // remove single line comments - .replace(/[ \t]*\/\*[\s\S]*?\*\//g, '') // remove multi line comments - .concat('\n') // ensure final new line - .replace(/\n{2,}/g, '\n'); // condense 2 or more empty lines to 1 + .trim() // trim whitespace + .replace(/\r/g, '') // Remove carriage returns + .replace(/ {4}/g, '\t') // 4 spaces to tabs + .replace(/[ \t]*\/\/.*/g, '') // remove single line comments + .replace(/[ \t]*\/\*[\s\S]*?\*\//g, '') // remove multi line comments + .concat('\n') // ensure final new line + .replace(/\n{2,}/g, '\n'); // condense 2 or more empty lines to 1 }); return { diff --git a/utils/plugins/rollup-spaces-to-tabs.mjs b/utils/plugins/rollup-spaces-to-tabs.mjs index 15f2a6dff9f..2092452ecce 100644 --- a/utils/plugins/rollup-spaces-to-tabs.mjs +++ b/utils/plugins/rollup-spaces-to-tabs.mjs @@ -14,7 +14,7 @@ export function spacesToTabs() { ], []); return { - name: "spacesToTabs", + name: 'spacesToTabs', transform(code, id) { if (!filter(id)) return undefined; // ^ = start of line diff --git a/utils/plugins/rollup-types-fixup.mjs b/utils/plugins/rollup-types-fixup.mjs index ec7b3203d26..cb554a09cd5 100644 --- a/utils/plugins/rollup-types-fixup.mjs +++ b/utils/plugins/rollup-types-fixup.mjs @@ -1,8 +1,8 @@ import * as fs from 'node:fs'; const GREEN_OUT = '\x1b[32m'; -const BOLD_OUT = `\x1b[1m`; -const REGULAR_OUT = `\x1b[22m`; +const BOLD_OUT = '\x1b[1m'; +const REGULAR_OUT = '\x1b[22m'; const TYPES_PATH = './build/playcanvas/src'; diff --git a/utils/rollup-build-target.mjs b/utils/rollup-build-target.mjs index 0f97e6990de..535cf530ea1 100644 --- a/utils/rollup-build-target.mjs +++ b/utils/rollup-build-target.mjs @@ -1,26 +1,22 @@ -// official package plugins +import { dirname, resolve as pathResolve } from 'path'; +import { fileURLToPath } from 'url'; + import { babel } from '@rollup/plugin-babel'; import resolve from '@rollup/plugin-node-resolve'; import strip from '@rollup/plugin-strip'; import terser from '@rollup/plugin-terser'; - -// unoffical package plugins import jscc from 'rollup-plugin-jscc'; import { visualizer } from 'rollup-plugin-visualizer'; -// custom plugins -import { shaderChunks } from './plugins/rollup-shader-chunks.mjs'; +import { dynamicImportLegacyBrowserSupport, dynamicImportBundlerSuppress } from './plugins/rollup-dynamic.mjs'; import { engineLayerImportValidation } from './plugins/rollup-import-validation.mjs'; +import { shaderChunks } from './plugins/rollup-shader-chunks.mjs'; import { spacesToTabs } from './plugins/rollup-spaces-to-tabs.mjs'; -import { dynamicImportLegacyBrowserSupport, dynamicImportBundlerSuppress } from './plugins/rollup-dynamic.mjs'; import { treeshakeIgnore } from './plugins/rollup-treeshake-ignore.mjs'; - -import { version, revision } from './rollup-version-revision.mjs'; -import { getBanner } from './rollup-get-banner.mjs'; import { babelOptions } from './rollup-babel-options.mjs'; +import { getBanner } from './rollup-get-banner.mjs'; +import { version, revision } from './rollup-version-revision.mjs'; -import { dirname, resolve as pathResolve } from 'path'; -import { fileURLToPath } from 'url'; // Find path to the repo root // @ts-ignore import.meta not allowed by tsconfig module:es6, but it works @@ -52,7 +48,7 @@ const STRIP_FUNCTIONS = [ 'Debug.trace', 'DebugHelper.setName', 'DebugHelper.setLabel', - `DebugHelper.setDestroyed`, + 'DebugHelper.setDestroyed', 'DebugGraphics.toString', 'DebugGraphics.clearGpuMarkers', 'DebugGraphics.pushGpuMarker', @@ -210,7 +206,7 @@ function buildTarget({ moduleFormat, buildType, bundleState, input = 'src/index. plugins: getOutPlugins(), file: `${dir}/${OUT_PREFIX[buildType]}${isUMD ? '.js' : '.mjs'}` }, - context: isUMD ? "this" : undefined + context: isUMD ? 'this' : undefined }; HISTORY.set(`${buildType}-${moduleFormat}-${bundled}`, target); diff --git a/utils/rollup-script-target.mjs b/utils/rollup-script-target.mjs index 4401661b3c0..1df4ab1cf3f 100644 --- a/utils/rollup-script-target.mjs +++ b/utils/rollup-script-target.mjs @@ -2,9 +2,9 @@ import { babel } from '@rollup/plugin-babel'; import resolve from '@rollup/plugin-node-resolve'; -import { getBanner } from './rollup-get-banner.mjs'; -import { babelOptions } from './rollup-babel-options.mjs'; import { spacesToTabs } from './plugins/rollup-spaces-to-tabs.mjs'; +import { babelOptions } from './rollup-babel-options.mjs'; +import { getBanner } from './rollup-get-banner.mjs'; /** @typedef {import('rollup').RollupOptions} RollupOptions */ diff --git a/utils/rollup-version-revision.mjs b/utils/rollup-version-revision.mjs index fb170f150a6..9bb67c92aa0 100644 --- a/utils/rollup-version-revision.mjs +++ b/utils/rollup-version-revision.mjs @@ -1,5 +1,5 @@ -import { readFileSync } from 'node:fs'; import { execSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; /** * @returns {string} Version string like `1.58.0-dev` diff --git a/utils/typedoc-plugin.mjs b/utils/typedoc-plugin.mjs index a7046669236..14b430a68b0 100644 --- a/utils/typedoc-plugin.mjs +++ b/utils/typedoc-plugin.mjs @@ -12,12 +12,13 @@ import { ArrayType, Converter, DeclarationReflection, IntrinsicType, ReflectionF */ function getProperties(filePath) { const data = readFileSync(resolve(process.cwd(), filePath), 'utf-8'); + // eslint-disable-next-line regexp/no-dupe-disjunctions const docBlocks = data.match(/\/\*\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//g); const properties = new Map(); if (docBlocks) { docBlocks.forEach((block) => { - const propertyLines = block.match(/@property\s*\{[^}]+\}\s*[^*]*/g); + const propertyLines = block.match(/@property\s*\{[^}]+\}[^*]*/g); if (propertyLines) { propertyLines.forEach((line) => {