diff --git a/.gitignore b/.gitignore
index 226b822..2c87b15 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,9 +1,24 @@
node_modules
-npm-debug.log
+dist
+
public/workers
*.mp4
*.flv
*.rar
*.zip
*.7z
-.catch/**
\ No newline at end of file
+.catch/**
+
+.DS_Store
+
+# Log files
+npm-debug.log*
+pnpm-debug.log*
+
+# Editor directories and files
+.idea
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 0000000..2b3b7b2
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1,2 @@
+auto-install-peers=true
+registry=https://registry.npmmirror.com
diff --git a/.nvmrc b/.nvmrc
new file mode 100644
index 0000000..b1215e8
--- /dev/null
+++ b/.nvmrc
@@ -0,0 +1 @@
+v18.16.0
\ No newline at end of file
diff --git a/.prettierrc b/.prettierrc
index bf0361b..705970b 100644
--- a/.prettierrc
+++ b/.prettierrc
@@ -11,6 +11,7 @@
"quoteProps": "as-needed",
"requirePragma": false,
"semi": true,
+ "singleAttributePerLine": false,
"singleQuote": false,
"tabWidth": 4,
"trailingComma": "none",
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 0000000..0555c66
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,3 @@
+{
+ "recommendations": ["PolyMeilex.wgsl", "ritwickdey.LiveServer", "esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
+}
diff --git a/README.md b/README.md
index ef997e7..bf2a65b 100644
--- a/README.md
+++ b/README.md
@@ -1,117 +1,135 @@
-## Note:
+# GEngine.js
-- WebGPU Engine
+WebGPU Engine
## install
-- `npm i @gengine-js/gengine`
+```shell
+$ yarn add @gengine-js/gengine
+```
-## build
+## develop
-- `npm install`
+```shell
+# install
+$ yarn
-- `npm run build`
+# dev
+$ yarn dev
-## Usage
+# build
+$ yarn build
+```
-
+ function onWindowResize() {
+ camera.aspect = window.innerWidth / window.innerHeight;
+ scene.resize(window.innerWidth, window.innerHeight);
+ }
+ function animate() {
+ control.update();
+ requestAnimationFrame(animate);
+ scene.render();
+ }
+ animate();
+ };
+ init();
+
+```
## Native
-
+ vertexBuffers: [
+ {
+ stepMode: "vertex", //optional
+ uid: "vertAttr", //must
+ attributes: {
+ position: { size: 4, value: positions },
+ color: { size: 4, value: colors }
+ }
+ }
+ ],
+ uniformBuffers: [
+ {
+ type: "uniform",
+ uid: "systemMatrix",
+ uniforms: {
+ modelViewProjectionMatrix: {
+ type: "mat4",
+ value: () => {
+ let viewMatrix = mat4.identity([]);
+ mat4.translate(viewMatrix, viewMatrix, vec3.fromValues(0, 0, -4));
+ const now = Date.now() / 1000;
+ mat4.rotate(
+ viewMatrix,
+ viewMatrix,
+ 1,
+ vec3.fromValues(Math.sin(now), Math.cos(now), 0)
+ );
+ mat4.multiply(modelViewProjectionMatrix, projectionMatrix, viewMatrix);
+ return modelViewProjectionMatrix;
+ }
+ }
+ }
+ }
+ ],
+ renderState: {
+ targets: [
+ {
+ format: presentationFormat
+ }
+ ],
+ primitive: {
+ topology: "triangle-list",
+ cullMode: "back"
+ },
+ depthStencil: {
+ depthWriteEnabled: true,
+ depthCompare: "less",
+ format: "depth24plus"
+ }
+ },
+ count: 36,
+ instances: 1
+ });
+
+ function animate() {
+ requestAnimationFrame(animate);
+ const passEncoder = canvasRenderTarget.beginRenderPass(context.device);
+ model.render({ device: context.device, passEncoder });
+ canvasRenderTarget.endRenderPass();
+ }
+ animate();
+ };
+ init();
+
+```
## feature
diff --git a/build/@rollup/plugin-wgsl/index.js b/build/@rollup/plugin-wgsl/index.js
new file mode 100644
index 0000000..f26af8e
--- /dev/null
+++ b/build/@rollup/plugin-wgsl/index.js
@@ -0,0 +1,22 @@
+// https://github.com/c8n1ao/rollup-plugin-wgsl
+import { readFile } from "node:fs/promises";
+
+export default function wgsl(options) {
+ options = {
+ ...{ fileTypes: ["frag", "vert", "wgsl", "glsl"] },
+ ...options
+ };
+
+ return {
+ name: "wgsl",
+
+ async load(id) {
+ const isTargetSuffix = options.fileTypes.some((type) => id.endsWith(`.${type}`));
+
+ if (isTargetSuffix) {
+ const code = await readFile(id, "utf-8");
+ return `export default ${JSON.stringify(code)};`;
+ }
+ }
+ };
+}
diff --git a/dist/index.js b/dist/index.js
deleted file mode 100644
index b54833b..0000000
--- a/dist/index.js
+++ /dev/null
@@ -1,16723 +0,0 @@
-/** @internal */
-var PredefinedColorSpace;
-(function (PredefinedColorSpace) {
- PredefinedColorSpace["SRGB"] = "srgb";
-})(PredefinedColorSpace || (PredefinedColorSpace = {}));
-/** @internal */
-var PowerPreference;
-(function (PowerPreference) {
- PowerPreference["LowPower"] = "low-power";
- PowerPreference["HighPerformance"] = "high-performance";
-})(PowerPreference || (PowerPreference = {}));
-/** @internal */
-var FeatureName;
-(function (FeatureName) {
- FeatureName["DepthClipControl"] = "depth-clip-control";
- FeatureName["Depth24UnormStencil8"] = "depth24unorm-stencil8";
- FeatureName["Depth32FloatStencil8"] = "depth32float-stencil8";
- FeatureName["TextureCompressionBC"] = "texture-compression-bc";
- FeatureName["TextureCompressionETC2"] = "texture-compression-etc2";
- FeatureName["TextureCompressionASTC"] = "texture-compression-astc";
- FeatureName["TimestampQuery"] = "timestamp-query";
- FeatureName["IndirectFirstInstance"] = "indirect-first-instance";
- FeatureName["ShaderF16"] = "shader-f16";
- FeatureName["BGRA8UnormStorage"] = "bgra8unorm-storage";
-})(FeatureName || (FeatureName = {}));
-/** @internal */
-var BufferUsage;
-(function (BufferUsage) {
- BufferUsage[(BufferUsage["MapRead"] = 1)] = "MapRead";
- BufferUsage[(BufferUsage["MapWrite"] = 2)] = "MapWrite";
- BufferUsage[(BufferUsage["CopySrc"] = 4)] = "CopySrc";
- BufferUsage[(BufferUsage["CopyDst"] = 8)] = "CopyDst";
- BufferUsage[(BufferUsage["Index"] = 16)] = "Index";
- BufferUsage[(BufferUsage["Vertex"] = 32)] = "Vertex";
- BufferUsage[(BufferUsage["Uniform"] = 64)] = "Uniform";
- BufferUsage[(BufferUsage["Storage"] = 128)] = "Storage";
- BufferUsage[(BufferUsage["Indirect"] = 256)] = "Indirect";
- BufferUsage[(BufferUsage["QueryResolve"] = 512)] = "QueryResolve";
-})(BufferUsage || (BufferUsage = {}));
-/** @internal */
-var MapMode;
-(function (MapMode) {
- MapMode[(MapMode["Read"] = 1)] = "Read";
- MapMode[(MapMode["Write"] = 2)] = "Write";
-})(MapMode || (MapMode = {}));
-/** @internal */
-var TextureDimension;
-(function (TextureDimension) {
- TextureDimension["E1d"] = "1d";
- TextureDimension["E2d"] = "2d";
- TextureDimension["E3d"] = "3d";
-})(TextureDimension || (TextureDimension = {}));
-/** @internal */
-var TextureUsage;
-(function (TextureUsage) {
- TextureUsage[(TextureUsage["CopySrc"] = 1)] = "CopySrc";
- TextureUsage[(TextureUsage["CopyDst"] = 2)] = "CopyDst";
- TextureUsage[(TextureUsage["TextureBinding"] = 4)] = "TextureBinding";
- TextureUsage[(TextureUsage["StorageBinding"] = 8)] = "StorageBinding";
- TextureUsage[(TextureUsage["RenderAttachment"] = 16)] = "RenderAttachment";
-})(TextureUsage || (TextureUsage = {}));
-/** @internal */
-var TextureViewDimension;
-(function (TextureViewDimension) {
- TextureViewDimension["E1d"] = "1d";
- TextureViewDimension["E2d"] = "2d";
- TextureViewDimension["E2dArray"] = "2d-array";
- TextureViewDimension["Cube"] = "cube";
- TextureViewDimension["CubeArray"] = "cube-array";
- TextureViewDimension["E3d"] = "3d";
-})(TextureViewDimension || (TextureViewDimension = {}));
-/** @internal */
-var TextureAspect;
-(function (TextureAspect) {
- TextureAspect["All"] = "all";
- TextureAspect["StencilOnly"] = "stencil-only";
- TextureAspect["DepthOnly"] = "depth-only";
-})(TextureAspect || (TextureAspect = {}));
-/**
- * Comments taken from https://github.com/gfx-rs/wgpu/blob/master/wgpu-types/src/lib.rs
- * @internal
- */
-var TextureFormat;
-(function (TextureFormat) {
- // 8-bit formats
- TextureFormat["R8Unorm"] = "r8unorm";
- TextureFormat["R8Snorm"] = "r8snorm";
- TextureFormat["R8Uint"] = "r8uint";
- TextureFormat["R8Sint"] = "r8sint";
- // 16-bit formats
- TextureFormat["R16Uint"] = "r16uint";
- TextureFormat["R16Sint"] = "r16sint";
- TextureFormat["R16Float"] = "r16float";
- TextureFormat["RG8Unorm"] = "rg8unorm";
- TextureFormat["RG8Snorm"] = "rg8snorm";
- TextureFormat["RG8Uint"] = "rg8uint";
- TextureFormat["RG8Sint"] = "rg8sint";
- // 32-bit formats
- TextureFormat["R32Uint"] = "r32uint";
- TextureFormat["R32Sint"] = "r32sint";
- TextureFormat["R32Float"] = "r32float";
- TextureFormat["RG16Uint"] = "rg16uint";
- TextureFormat["RG16Sint"] = "rg16sint";
- TextureFormat["RG16Float"] = "rg16float";
- TextureFormat["RGBA8Unorm"] = "rgba8unorm";
- TextureFormat["RGBA8UnormSRGB"] = "rgba8unorm-srgb";
- TextureFormat["RGBA8Snorm"] = "rgba8snorm";
- TextureFormat["RGBA8Uint"] = "rgba8uint";
- TextureFormat["RGBA8Sint"] = "rgba8sint";
- TextureFormat["BGRA8Unorm"] = "bgra8unorm";
- TextureFormat["BGRA8UnormSRGB"] = "bgra8unorm-srgb";
- // Packed 32-bit formats
- TextureFormat["RGB9E5UFloat"] = "rgb9e5ufloat";
- TextureFormat["RGB10A2Unorm"] = "rgb10a2unorm";
- TextureFormat["RG11B10UFloat"] = "rg11b10ufloat";
- // 64-bit formats
- TextureFormat["RG32Uint"] = "rg32uint";
- TextureFormat["RG32Sint"] = "rg32sint";
- TextureFormat["RG32Float"] = "rg32float";
- TextureFormat["RGBA16Uint"] = "rgba16uint";
- TextureFormat["RGBA16Sint"] = "rgba16sint";
- TextureFormat["RGBA16Float"] = "rgba16float";
- // 128-bit formats
- TextureFormat["RGBA32Uint"] = "rgba32uint";
- TextureFormat["RGBA32Sint"] = "rgba32sint";
- TextureFormat["RGBA32Float"] = "rgba32float";
- // Depth and stencil formats
- TextureFormat["Stencil8"] = "stencil8";
- TextureFormat["Depth16Unorm"] = "depth16unorm";
- TextureFormat["Depth24Plus"] = "depth24plus";
- TextureFormat["Depth24PlusStencil8"] = "depth24plus-stencil8";
- TextureFormat["Depth32Float"] = "depth32float";
- // BC compressed formats usable if "texture-compression-bc" is both
- // supported by the device/user agent and enabled in requestDevice.
- TextureFormat["BC1RGBAUnorm"] = "bc1-rgba-unorm";
- TextureFormat["BC1RGBAUnormSRGB"] = "bc1-rgba-unorm-srgb";
- TextureFormat["BC2RGBAUnorm"] = "bc2-rgba-unorm";
- TextureFormat["BC2RGBAUnormSRGB"] = "bc2-rgba-unorm-srgb";
- TextureFormat["BC3RGBAUnorm"] = "bc3-rgba-unorm";
- TextureFormat["BC3RGBAUnormSRGB"] = "bc3-rgba-unorm-srgb";
- TextureFormat["BC4RUnorm"] = "bc4-r-unorm";
- TextureFormat["BC4RSnorm"] = "bc4-r-snorm";
- TextureFormat["BC5RGUnorm"] = "bc5-rg-unorm";
- TextureFormat["BC5RGSnorm"] = "bc5-rg-snorm";
- TextureFormat["BC6HRGBUFloat"] = "bc6h-rgb-ufloat";
- TextureFormat["BC6HRGBFloat"] = "bc6h-rgb-float";
- TextureFormat["BC7RGBAUnorm"] = "bc7-rgba-unorm";
- TextureFormat["BC7RGBAUnormSRGB"] = "bc7-rgba-unorm-srgb";
- // ETC2 compressed formats usable if "texture-compression-etc2" is both
- // supported by the device/user agent and enabled in requestDevice.
- TextureFormat["ETC2RGB8Unorm"] = "etc2-rgb8unorm";
- TextureFormat["ETC2RGB8UnormSRGB"] = "etc2-rgb8unorm-srgb";
- TextureFormat["ETC2RGB8A1Unorm"] = "etc2-rgb8a1unorm";
- TextureFormat["ETC2RGB8A1UnormSRGB"] = "etc2-rgb8a1unorm-srgb";
- TextureFormat["ETC2RGBA8Unorm"] = "etc2-rgba8unorm";
- TextureFormat["ETC2RGBA8UnormSRGB"] = "etc2-rgba8unorm-srgb";
- TextureFormat["EACR11Unorm"] = "eac-r11unorm";
- TextureFormat["EACR11Snorm"] = "eac-r11snorm";
- TextureFormat["EACRG11Unorm"] = "eac-rg11unorm";
- TextureFormat["EACRG11Snorm"] = "eac-rg11snorm";
- // ASTC compressed formats usable if "texture-compression-astc" is both
- // supported by the device/user agent and enabled in requestDevice.
- TextureFormat["ASTC4x4Unorm"] = "astc-4x4-unorm";
- TextureFormat["ASTC4x4UnormSRGB"] = "astc-4x4-unorm-srgb";
- TextureFormat["ASTC5x4Unorm"] = "astc-5x4-unorm";
- TextureFormat["ASTC5x4UnormSRGB"] = "astc-5x4-unorm-srgb";
- TextureFormat["ASTC5x5Unorm"] = "astc-5x5-unorm";
- TextureFormat["ASTC5x5UnormSRGB"] = "astc-5x5-unorm-srgb";
- TextureFormat["ASTC6x5Unorm"] = "astc-6x5-unorm";
- TextureFormat["ASTC6x5UnormSRGB"] = "astc-6x5-unorm-srgb";
- TextureFormat["ASTC6x6Unorm"] = "astc-6x6-unorm";
- TextureFormat["ASTC6x6UnormSRGB"] = "astc-6x6-unorm-srgb";
- TextureFormat["ASTC8x5Unorm"] = "astc-8x5-unorm";
- TextureFormat["ASTC8x5UnormSRGB"] = "astc-8x5-unorm-srgb";
- TextureFormat["ASTC8x6Unorm"] = "astc-8x6-unorm";
- TextureFormat["ASTC8x6UnormSRGB"] = "astc-8x6-unorm-srgb";
- TextureFormat["ASTC8x8Unorm"] = "astc-8x8-unorm";
- TextureFormat["ASTC8x8UnormSRGB"] = "astc-8x8-unorm-srgb";
- TextureFormat["ASTC10x5Unorm"] = "astc-10x5-unorm";
- TextureFormat["ASTC10x5UnormSRGB"] = "astc-10x5-unorm-srgb";
- TextureFormat["ASTC10x6Unorm"] = "astc-10x6-unorm";
- TextureFormat["ASTC10x6UnormSRGB"] = "astc-10x6-unorm-srgb";
- TextureFormat["ASTC10x8Unorm"] = "astc-10x8-unorm";
- TextureFormat["ASTC10x8UnormSRGB"] = "astc-10x8-unorm-srgb";
- TextureFormat["ASTC10x10Unorm"] = "astc-10x10-unorm";
- TextureFormat["ASTC10x10UnormSRGB"] = "astc-10x10-unorm-srgb";
- TextureFormat["ASTC12x10Unorm"] = "astc-12x10-unorm";
- TextureFormat["ASTC12x10UnormSRGB"] = "astc-12x10-unorm-srgb";
- TextureFormat["ASTC12x12Unorm"] = "astc-12x12-unorm";
- TextureFormat["ASTC12x12UnormSRGB"] = "astc-12x12-unorm-srgb";
- // "depth24unorm-stencil8" feature
- TextureFormat["Depth24UnormStencil8"] = "depth24unorm-stencil8";
- // "depth32float-stencil8" feature
- TextureFormat["Depth32FloatStencil8"] = "depth32float-stencil8";
-})(TextureFormat || (TextureFormat = {}));
-/** @internal */
-var AddressMode;
-(function (AddressMode) {
- AddressMode["ClampToEdge"] = "clamp-to-edge";
- AddressMode["Repeat"] = "repeat";
- AddressMode["MirrorRepeat"] = "mirror-repeat";
-})(AddressMode || (AddressMode = {}));
-/** @internal */
-var FilterMode;
-(function (FilterMode) {
- FilterMode["Nearest"] = "nearest";
- FilterMode["Linear"] = "linear";
-})(FilterMode || (FilterMode = {}));
-/** @internal */
-var CompareFunction;
-(function (CompareFunction) {
- CompareFunction["Never"] = "never";
- CompareFunction["Less"] = "less";
- CompareFunction["Equal"] = "equal";
- CompareFunction["LessEqual"] = "less-equal";
- CompareFunction["Greater"] = "greater";
- CompareFunction["NotEqual"] = "not-equal";
- CompareFunction["GreaterEqual"] = "greater-equal";
- CompareFunction["Always"] = "always";
-})(CompareFunction || (CompareFunction = {}));
-/** @internal */
-var ShaderStage;
-(function (ShaderStage) {
- ShaderStage[(ShaderStage["Vertex"] = 1)] = "Vertex";
- ShaderStage[(ShaderStage["Fragment"] = 2)] = "Fragment";
- ShaderStage[(ShaderStage["Compute"] = 4)] = "Compute";
-})(ShaderStage || (ShaderStage = {}));
-/** @internal */
-var BufferBindingType;
-(function (BufferBindingType) {
- BufferBindingType["Uniform"] = "uniform";
- BufferBindingType["Storage"] = "storage";
- BufferBindingType["ReadOnlyStorage"] = "read-only-storage";
-})(BufferBindingType || (BufferBindingType = {}));
-/** @internal */
-var SamplerBindingType;
-(function (SamplerBindingType) {
- SamplerBindingType["Filtering"] = "filtering";
- SamplerBindingType["NonFiltering"] = "non-filtering";
- SamplerBindingType["Comparison"] = "comparison";
-})(SamplerBindingType || (SamplerBindingType = {}));
-/** @internal */
-var TextureSampleType;
-(function (TextureSampleType) {
- TextureSampleType["Float"] = "float";
- TextureSampleType["UnfilterableFloat"] = "unfilterable-float";
- TextureSampleType["Depth"] = "depth";
- TextureSampleType["Sint"] = "sint";
- TextureSampleType["Uint"] = "uint";
-})(TextureSampleType || (TextureSampleType = {}));
-/** @internal */
-var StorageTextureAccess;
-(function (StorageTextureAccess) {
- StorageTextureAccess["WriteOnly"] = "write-only";
-})(StorageTextureAccess || (StorageTextureAccess = {}));
-/** @internal */
-var CompilationMessageType;
-(function (CompilationMessageType) {
- CompilationMessageType["Error"] = "error";
- CompilationMessageType["Warning"] = "warning";
- CompilationMessageType["Info"] = "info";
-})(CompilationMessageType || (CompilationMessageType = {}));
-/** @internal */
-var AutoLayoutMode;
-(function (AutoLayoutMode) {
- AutoLayoutMode["Auto"] = "auto";
-})(AutoLayoutMode || (AutoLayoutMode = {}));
-/** @internal */
-var PrimitiveTopology;
-(function (PrimitiveTopology) {
- PrimitiveTopology["PointList"] = "point-list";
- PrimitiveTopology["LineList"] = "line-list";
- PrimitiveTopology["LineStrip"] = "line-strip";
- PrimitiveTopology["TriangleList"] = "triangle-list";
- PrimitiveTopology["TriangleStrip"] = "triangle-strip";
-})(PrimitiveTopology || (PrimitiveTopology = {}));
-/** @internal */
-var FrontFace;
-(function (FrontFace) {
- FrontFace["CCW"] = "ccw";
- FrontFace["CW"] = "cw";
-})(FrontFace || (FrontFace = {}));
-/** @internal */
-var CullMode;
-(function (CullMode) {
- CullMode["None"] = "none";
- CullMode["Front"] = "front";
- CullMode["Back"] = "back";
-})(CullMode || (CullMode = {}));
-/** @internal */
-var ColorWriteFlags;
-(function (ColorWriteFlags) {
- ColorWriteFlags[(ColorWriteFlags["Red"] = 1)] = "Red";
- ColorWriteFlags[(ColorWriteFlags["Green"] = 2)] = "Green";
- ColorWriteFlags[(ColorWriteFlags["Blue"] = 4)] = "Blue";
- ColorWriteFlags[(ColorWriteFlags["Alpha"] = 8)] = "Alpha";
- ColorWriteFlags[(ColorWriteFlags["All"] = 15)] = "All";
-})(ColorWriteFlags || (ColorWriteFlags = {}));
-/** @internal */
-var BlendFactor;
-(function (BlendFactor) {
- BlendFactor["Zero"] = "zero";
- BlendFactor["One"] = "one";
- BlendFactor["Src"] = "src";
- BlendFactor["OneMinusSrc"] = "one-minus-src";
- BlendFactor["SrcAlpha"] = "src-alpha";
- BlendFactor["OneMinusSrcAlpha"] = "one-minus-src-alpha";
- BlendFactor["Dst"] = "dst";
- BlendFactor["OneMinusDst"] = "one-minus-dst";
- BlendFactor["DstAlpha"] = "dst-alpha";
- BlendFactor["OneMinusDstAlpha"] = "one-minus-dst-alpha";
- BlendFactor["SrcAlphaSaturated"] = "src-alpha-saturated";
- BlendFactor["Constant"] = "constant";
- BlendFactor["OneMinusConstant"] = "one-minus-constant";
-})(BlendFactor || (BlendFactor = {}));
-/** @internal */
-var BlendOperation;
-(function (BlendOperation) {
- BlendOperation["Add"] = "add";
- BlendOperation["Subtract"] = "subtract";
- BlendOperation["ReverseSubtract"] = "reverse-subtract";
- BlendOperation["Min"] = "min";
- BlendOperation["Max"] = "max";
-})(BlendOperation || (BlendOperation = {}));
-/** @internal */
-var StencilOperation;
-(function (StencilOperation) {
- StencilOperation["Keep"] = "keep";
- StencilOperation["Zero"] = "zero";
- StencilOperation["Replace"] = "replace";
- StencilOperation["Invert"] = "invert";
- StencilOperation["IncrementClamp"] = "increment-clamp";
- StencilOperation["DecrementClamp"] = "decrement-clamp";
- StencilOperation["IncrementWrap"] = "increment-wrap";
- StencilOperation["DecrementWrap"] = "decrement-wrap";
-})(StencilOperation || (StencilOperation = {}));
-/** @internal */
-var IndexFormat;
-(function (IndexFormat) {
- IndexFormat["Uint16"] = "uint16";
- IndexFormat["Uint32"] = "uint32";
-})(IndexFormat || (IndexFormat = {}));
-/** @internal */
-var VertexFormat;
-(function (VertexFormat) {
- VertexFormat["Uint8x2"] = "uint8x2";
- VertexFormat["Uint8x4"] = "uint8x4";
- VertexFormat["Sint8x2"] = "sint8x2";
- VertexFormat["Sint8x4"] = "sint8x4";
- VertexFormat["Unorm8x2"] = "unorm8x2";
- VertexFormat["Unorm8x4"] = "unorm8x4";
- VertexFormat["Snorm8x2"] = "snorm8x2";
- VertexFormat["Snorm8x4"] = "snorm8x4";
- VertexFormat["Uint16x2"] = "uint16x2";
- VertexFormat["Uint16x4"] = "uint16x4";
- VertexFormat["Sint16x2"] = "sint16x2";
- VertexFormat["Sint16x4"] = "sint16x4";
- VertexFormat["Unorm16x2"] = "unorm16x2";
- VertexFormat["Unorm16x4"] = "unorm16x4";
- VertexFormat["Snorm16x2"] = "snorm16x2";
- VertexFormat["Snorm16x4"] = "snorm16x4";
- VertexFormat["Float16x2"] = "float16x2";
- VertexFormat["Float16x4"] = "float16x4";
- VertexFormat["Float32"] = "float32";
- VertexFormat["Float32x2"] = "float32x2";
- VertexFormat["Float32x3"] = "float32x3";
- VertexFormat["Float32x4"] = "float32x4";
- VertexFormat["Uint32"] = "uint32";
- VertexFormat["Uint32x2"] = "uint32x2";
- VertexFormat["Uint32x3"] = "uint32x3";
- VertexFormat["Uint32x4"] = "uint32x4";
- VertexFormat["Sint32"] = "sint32";
- VertexFormat["Sint32x2"] = "sint32x2";
- VertexFormat["Sint32x3"] = "sint32x3";
- VertexFormat["Sint32x4"] = "sint32x4";
-})(VertexFormat || (VertexFormat = {}));
-/** @internal */
-var InputStepMode;
-(function (InputStepMode) {
- InputStepMode["Vertex"] = "vertex";
- InputStepMode["Instance"] = "instance";
-})(InputStepMode || (InputStepMode = {}));
-/** @internal */
-var ComputePassTimestampLocation;
-(function (ComputePassTimestampLocation) {
- ComputePassTimestampLocation["Beginning"] = "beginning";
- ComputePassTimestampLocation["End"] = "end";
-})(ComputePassTimestampLocation || (ComputePassTimestampLocation = {}));
-/** @internal */
-var RenderPassTimestampLocation;
-(function (RenderPassTimestampLocation) {
- RenderPassTimestampLocation["Beginning"] = "beginning";
- RenderPassTimestampLocation["End"] = "end";
-})(RenderPassTimestampLocation || (RenderPassTimestampLocation = {}));
-/** @internal */
-var LoadOp;
-(function (LoadOp) {
- LoadOp["Load"] = "load";
- LoadOp["Clear"] = "clear";
-})(LoadOp || (LoadOp = {}));
-/** @internal */
-var StoreOp;
-(function (StoreOp) {
- StoreOp["Store"] = "store";
- StoreOp["Discard"] = "discard";
-})(StoreOp || (StoreOp = {}));
-/** @internal */
-var QueryType;
-(function (QueryType) {
- QueryType["Occlusion"] = "occlusion";
- QueryType["Timestamp"] = "timestamp";
-})(QueryType || (QueryType = {}));
-/** @internal */
-var CanvasAlphaMode;
-(function (CanvasAlphaMode) {
- CanvasAlphaMode["Opaque"] = "opaque";
- CanvasAlphaMode["Premultiplied"] = "premultiplied";
-})(CanvasAlphaMode || (CanvasAlphaMode = {}));
-/** @internal */
-var DeviceLostReason;
-(function (DeviceLostReason) {
- DeviceLostReason["Destroyed"] = "destroyed";
-})(DeviceLostReason || (DeviceLostReason = {}));
-/** @internal */
-var ErrorFilter;
-(function (ErrorFilter) {
- ErrorFilter["OutOfMemory"] = "out-of-memory";
- ErrorFilter["Validation"] = "validation";
-})(ErrorFilter || (ErrorFilter = {}));
-var GPUColorWrite;
-(function (GPUColorWrite) {
- GPUColorWrite[(GPUColorWrite["Red"] = 1)] = "Red";
- GPUColorWrite[(GPUColorWrite["Green"] = 2)] = "Green";
- GPUColorWrite[(GPUColorWrite["Blue"] = 4)] = "Blue";
- GPUColorWrite[(GPUColorWrite["Alpha"] = 8)] = "Alpha";
- GPUColorWrite[(GPUColorWrite["All"] = 15)] = "All";
-})(GPUColorWrite || (GPUColorWrite = {}));
-var CommandSubType;
-(function (CommandSubType) {
- CommandSubType["Shadow"] = "shadow";
- CommandSubType["Pick"] = "pick";
-})(CommandSubType || (CommandSubType = {}));
-var Intersect;
-(function (Intersect) {
- Intersect[(Intersect["OUTSIDE"] = -1)] = "OUTSIDE";
- Intersect[(Intersect["INTERSECTING"] = 0)] = "INTERSECTING";
- Intersect[(Intersect["INSIDE"] = 1)] = "INSIDE";
-})(Intersect || (Intersect = {}));
-
-class Buffer {
- constructor(label, device, usage, data, size) {
- this.device = device;
- this.usage = usage;
- this.data = data;
- this.size = size != undefined ? (size + 3) & ~3 : (data.byteLength + 3) & ~3; // 4 bytes alignments (because of the upload which requires this)
- this.gpuBuffer = device.createBuffer({
- label: label || "",
- size: this.size,
- usage
- });
- if (data) this.setSubData(0, data, this.size);
- }
- static create(label, device, usage, data, size) {
- return new Buffer(label, device, usage, data, size);
- }
- static createVertexBuffer(label, device, data) {
- return new Buffer(label, device, BufferUsage.Vertex | BufferUsage.CopyDst, data, data.byteLength);
- }
- static createIndexBuffer(label, device, data) {
- return new Buffer(label, device, BufferUsage.Index | BufferUsage.CopyDst, data);
- }
- static createUniformBuffer(label, device, size, usage) {
- return new Buffer(label, device, usage, null, size);
- }
- static createStorageBuffer(label, device, size, usage = BufferUsage.Storage) {
- return new Buffer(label, device, usage, null, size);
- }
- // https://github.com/gpuweb/gpuweb/blob/main/design/BufferOperations.md
- setSubData(offset, data, size) {
- const srcArrayBuffer = data.buffer;
- const byteCount = size ?? srcArrayBuffer.byteLength;
- const srcBuffer = this.device.createBuffer({
- mappedAtCreation: true,
- size: byteCount,
- usage: GPUBufferUsage.COPY_SRC
- });
- const arrayBuffer = srcBuffer.getMappedRange();
- new Uint16Array(arrayBuffer).set(new Uint16Array(srcArrayBuffer)); // memcpy
- srcBuffer.unmap();
- this.copyToBuffer(srcBuffer, offset, byteCount);
- srcBuffer.destroy();
- }
- copyToBuffer(srcBuffer, offset, byteCount) {
- const commandEncoder = this.device.createCommandEncoder();
- commandEncoder.copyBufferToBuffer(srcBuffer, 0, this.gpuBuffer, offset, byteCount);
- this.device.queue.submit([commandEncoder.finish()]);
- }
- copyToTexture(bytesPerRow, rowsPerImage, destination, extent) {
- const commandEncoder = this.device.createCommandEncoder();
- commandEncoder.copyBufferToTexture(
- {
- buffer: this.gpuBuffer,
- bytesPerRow,
- rowsPerImage
- },
- destination,
- extent
- );
- this.device.queue.submit([commandEncoder.finish()]);
- }
- destroy() {
- this.gpuBuffer.destroy();
- }
-}
-
-const pipelineLayoutCache = new Map();
-class PipelineLayout {
- constructor(device, label, groupLayouts = [], index) {
- this.groupLayouts = groupLayouts;
- this.index = index || 0;
- this.gpuPipelineLayout = device.createPipelineLayout({
- label: label,
- bindGroupLayouts: groupLayouts.map((layout) => {
- return layout.gpuBindGroupLayout;
- })
- });
- }
- static getPipelineLayoutFromCache(device, label, groupLayouts) {
- if (pipelineLayoutCache.has(label)) {
- return pipelineLayoutCache.get(label);
- } else {
- const bindGroupLayout = new PipelineLayout(device, label, groupLayouts);
- pipelineLayoutCache.set(label, bindGroupLayout);
- return bindGroupLayout;
- }
- }
-}
-
-const renderPipelines = new Map();
-const computePipelines = new Map();
-class Pipeline {
- constructor(type, device, descriptor) {
- this.type = type;
- this.descriptor = descriptor;
- this.device = device;
- this.createPipeline();
- }
- createPipeline() {
- if (this.type == "render") {
- this.gpuPipeline = this.device.createRenderPipeline(this.descriptor);
- } else {
- this.gpuPipeline = this.device.createComputePipeline(this.descriptor);
- }
- }
- bind(passEncoder) {
- if (this.type == "render") {
- passEncoder.setPipeline(this.gpuPipeline);
- } else {
- passEncoder.setPipeline(this.gpuPipeline);
- }
- }
- static getRenderPipelineFromCache(device, drawComand, groupLayouts) {
- const { renderState, shaderSource } = drawComand;
- const rsStr = JSON.stringify(renderState);
- const combineStr = shaderSource.uid.concat(rsStr);
- const hashId = stringToHash(combineStr);
- const combineLayouts = groupLayouts
- ?.filter((layout) => layout != undefined)
- ?.sort((layout1, layout2) => layout1.index - layout2.index);
- let pipeline = renderPipelines.get(hashId);
- if (!pipeline) {
- const descriptor = Pipeline.getPipelineDescriptor(
- device,
- drawComand,
- renderState,
- combineLayouts,
- hashId.toString()
- );
- pipeline = new Pipeline("render", device, descriptor);
- renderPipelines.set(hashId, pipeline);
- }
- return pipeline;
- }
- static getComputePipelineFromCache(device, computeCommad, groupLayouts) {
- const { shaderSource } = computeCommad;
- const hashId = stringToHash(shaderSource.uid);
- let pipeline = computePipelines.get(hashId);
- if (!pipeline) {
- pipeline = new Pipeline("compute", device, {
- layout: PipelineLayout.getPipelineLayoutFromCache(device, hashId.toString(), groupLayouts)
- .gpuPipelineLayout,
- compute: {
- module: shaderSource.getShaderModule(device).compute,
- entryPoint: shaderSource?.compute?.computeMain || "main"
- }
- });
- computePipelines.set(hashId, pipeline);
- }
- return pipeline;
- }
- static getPipelineDescriptor(device, drawComand, renderState, groupLayouts, hashId) {
- const { vertexBuffers, shaderSource } = drawComand;
- const { vert, frag } = shaderSource.getShaderModule(device);
- const pipelineDec = {
- layout: PipelineLayout.getPipelineLayoutFromCache(device, hashId, groupLayouts).gpuPipelineLayout
- };
- if (vert)
- pipelineDec.vertex = {
- module: vert,
- entryPoint: shaderSource?.render?.vertMain || "main",
- buffers: vertexBuffers.map((vertexBuffer) => vertexBuffer.getBufferDes())
- };
- if (renderState.primitive) pipelineDec.primitive = renderState.primitive.getGPUPrimitiveDec();
- if (renderState.depthStencil) pipelineDec.depthStencil = renderState.depthStencil.getGPUDepthStencilDec();
- if (renderState.multisample) pipelineDec.multisample = renderState.multisample.getMultiSampleDec();
- if (frag)
- pipelineDec.fragment = {
- module: frag,
- entryPoint: shaderSource?.render?.fragMain || "main",
- targets: renderState.targets.map((target) => {
- return target.getGPUTargetDec();
- })
- };
- return pipelineDec;
- }
-}
-// Borrowed from https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
-function stringToHash(str) {
- let hash = 0;
- if (str.length == 0) return hash;
- for (let i = 0; i < str.length; i++) {
- const char = str.charCodeAt(i);
- hash = (hash << 5) - hash + char;
- hash = hash & hash; // Convert to 32bit integer
- }
- return hash;
-}
-
-class DrawCommand {
- constructor(options) {
- this.shaderData = options.shaderData;
- this.renderTarget = options.renderTarget;
- this.useLight = options.useLight;
- this.vertexBuffers = options.vertexBuffers;
- this.indexBuffer = options.indexBuffer;
- this.renderState = options.renderState;
- this.queryIndex = options.queryIndex;
- this.count = options.count;
- this.instances = options.instances;
- this.shaderSource = options.shaderSource;
- this.dirty = options.dirty;
- this.lightShaderData = options.lightShaderData;
- }
- shallowClone(material) {
- if (!material) return;
- return new DrawCommand({
- vertexBuffers: this.vertexBuffers,
- indexBuffer: this.indexBuffer,
- shaderData: material.shaderData,
- instances: this.instances,
- count: this.count,
- renderState: material.renderState,
- shaderSource: material.shaderSource,
- lightShaderData: material.light ? this.lightShaderData : undefined,
- useLight: material.light
- });
- }
- render(params) {
- const { device, passEncoder, camera, querySet, viewPort, scissorTest } = params || {};
- const {
- shaderData,
- renderState,
- vertexBuffers,
- indexBuffer,
- lightShaderData,
- shaderSource,
- count,
- instances,
- renderTarget,
- useLight,
- indirectOffset,
- indirectBuffer,
- queryIndex
- } = this;
- const currentPassEncoder = renderTarget?.beginRenderPass?.(device) ?? passEncoder;
- const defines = Object.assign({}, lightShaderData?.defines ?? {}, camera?.shaderData?.defines ?? {});
- shaderData?.bind?.(device, currentPassEncoder);
- camera?.shaderData?.bind(device, currentPassEncoder);
- useLight && lightShaderData?.bind?.(device, currentPassEncoder);
- renderState?.bind?.({
- passEncoder: currentPassEncoder,
- viewPort: viewPort,
- scissorTest: scissorTest
- });
- vertexBuffers?.forEach?.((vertexBuffer) => vertexBuffer?.bind?.(device, currentPassEncoder));
- indexBuffer?.bind?.(device, currentPassEncoder);
- shaderSource?.setDefines?.(defines);
- const pipeline = Pipeline.getRenderPipelineFromCache(device, this, [
- shaderData?.groupLayout,
- lightShaderData?.groupLayout,
- camera?.shaderData?.groupLayout
- ]);
- if (queryIndex != undefined) querySet?.beginQuery(currentPassEncoder, queryIndex);
- pipeline.bind(currentPassEncoder);
- if (indexBuffer) {
- if (indirectBuffer) {
- currentPassEncoder.drawIndexedIndirect(indirectBuffer.gpuBuffer, indirectOffset || 0);
- } else {
- currentPassEncoder.drawIndexed(count || 0, instances || 1, 0, 0, 0);
- }
- } else if (count) {
- if (indirectBuffer) {
- currentPassEncoder.drawIndirect(indirectBuffer.gpuBuffer, indirectOffset);
- } else {
- currentPassEncoder.draw(count, instances || 1, 0, 0);
- }
- }
- if (queryIndex != undefined) querySet?.endQuery(currentPassEncoder);
- renderTarget?.endRenderPass?.();
- }
-}
-
-const GPUCanvasCompositingAlphaMode = {
- Opaque: "opaque",
- Premultiplied: "premultiplied"
-};
-var RenderObjectType;
-(function (RenderObjectType) {
- RenderObjectType["Camera"] = "camera";
- RenderObjectType["Light"] = "light";
- RenderObjectType["Mesh"] = "mesh";
- RenderObjectType["SkinMesh"] = "skinMesh";
- RenderObjectType["Node"] = "node";
- RenderObjectType["Axes"] = "axes";
- RenderObjectType["Skybox"] = "skyBox";
- RenderObjectType["PostEffect"] = "postEffect";
- RenderObjectType["Debug"] = "debug";
-})(RenderObjectType || (RenderObjectType = {}));
-var LightType;
-(function (LightType) {
- LightType["SpotLight"] = "spotLight";
- LightType["PointLight"] = "pointLight";
- LightType["AmbientLight"] = "ambientLight";
- LightType["DirectionalLight"] = "directionalLight";
-})(LightType || (LightType = {}));
-var UniformEnum;
-(function (UniformEnum) {
- UniformEnum["Float"] = "f32";
- UniformEnum["FloatVec2"] = "vec2";
- UniformEnum["FloatVec3"] = "vec3";
- UniformEnum["FloatVec4"] = "vec4";
- UniformEnum["FloatArray"] = "array";
- UniformEnum["Mat2"] = "mat2x2";
- UniformEnum["Mat3"] = "mat3x3";
- UniformEnum["Mat4"] = "mat4x4";
- UniformEnum["Color"] = "color";
- UniformEnum["Mat4Array"] = "array>";
- UniformEnum["Vec2Array"] = "array>";
- UniformEnum["Vec3Array"] = "array>";
- UniformEnum["Vec4Array"] = "array>";
- UniformEnum["UniformUint"] = "u32";
- UniformEnum["PointLights"] = "pointLights";
- UniformEnum["PointLightShadows"] = "pointLightShadows";
- UniformEnum["SpotLights"] = "spotLights";
- UniformEnum["SpotLightShadows"] = "spotLightShadows";
- UniformEnum["DirtectLights"] = "dirtectLights";
- UniformEnum["DirtectLightShadows"] = "dirtectLightShadows";
- UniformEnum["UniformStructArray"] = "StructArray";
-})(UniformEnum || (UniformEnum = {}));
-var ShaderLanguage;
-(function (ShaderLanguage) {
- ShaderLanguage["WGSL"] = "wgsl";
- ShaderLanguage["GLSL"] = "glsl";
-})(ShaderLanguage || (ShaderLanguage = {}));
-var ShaderMainStage;
-(function (ShaderMainStage) {
- ShaderMainStage["VERT"] = "vertex";
- ShaderMainStage["FRAG"] = "fragment";
- ShaderMainStage["COMPUTE"] = "compute";
-})(ShaderMainStage || (ShaderMainStage = {}));
-
-// import Color from "../../math/Color";
-var colorFrag = `
- struct VertexOutput {
- @builtin(position) position: vec4,
- @location(0) color: vec4,
- };
- @fragment
- fn main(input:VertexOutput) -> @location(0) vec4 {
- return input.color;
- }
- `;
-
-var colorVert = `
- struct VertexInput {
- @location(positionLocation) position: vec3,
- @location(colorLocation) color: vec4,
- }
- struct VertexOutput {
- @builtin(position) position: vec4,
- @location(0) color: vec4,
- };
- struct SelfUniform {
- modelMatrix: mat4x4,
- }
- struct SystemUniform {
- projectionMatrix: mat4x4,
- viewMatrix: mat4x4,
- inverseViewMatrix: mat4x4,
- cameraPosition: vec3,
- };
- @binding(colorBinding) @group(0) var selfUniform : SelfUniform;
- @binding(cameraBinding) @group(1) var systemUniform : SystemUniform;
- @vertex
- fn main(input: VertexInput) -> VertexOutput {
- var output:VertexOutput;
- output.color=input.color;
- output.position = systemUniform.projectionMatrix * systemUniform.viewMatrix *selfUniform.modelMatrix*vec4(input.position,1.0);
- return output;
- }
- `;
-
-var pbr_fs = `
- // reference: https://github.com/KhronosGroup/glTF-WebGL-PBR/blob/master/shaders/pbr-frag.glsl
- #include
- #include
- #include
- #include
- #include
- #include
- struct PhysicalMaterial {
- diffuseColor:vec3,
- roughness:f32,
- specularColor:vec3,
- #if USE_CLEARCOAT
- clearcoat:f32,
- clearcoatRoughness:f32,
- clearcoatF0:vec3,
- clearcoatF90:f32,
- #endif
-
- #if USE_IRIDESCENCE
- iridescence:f32,
- iridescenceIOR:f32,
- iridescenceThickness:f32,
- iridescenceFresnel:vec3,
- iridescenceF0:vec3,
- #endif
-
- #if USE_SHEEN
- sheenColor:vec3,
- sheenRoughness:f32,
- #endif
-
- #if IOR
- ior:f32,
- #endif
-
- #if USE_TRANSMISSION
- transmission:f32,
- transmissionAlpha:f32,
- thickness:f32,
- attenuationDistance:f32,
- attenuationColor:vec3,
- #endif
- };
- const M_PI:f32 = 3.141592653589793;
- const c_MinRoughness:f32 = 0.04;
- #include
- #if USE_IBL
- #include
- #endif
- @binding(pbrBinding) @group(0) var materialUniform : MaterialUniform;
- @binding(cameraBinding) @group(1) var systemUniform : SystemUniform;
- @fragment
- fn main(input:FragInput) -> @location(0) vec4
- {
- var perceptualRoughness:f32 = materialUniform.roughness;
- var metallic:f32 = materialUniform.metallic;
-
- #if USE_METALNESSTEXTURE
- let mrSample:vec4 = textureSample(metalnessRoughnessTexture,metalnessRoughnessSampler, input.uv);
- perceptualRoughness = mrSample.g * perceptualRoughness;
- metallic = mrSample.b * metallic;
- #endif
- perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
- metallic = clamp(metallic, 0.0, 1.0);
- let alphaRoughness:f32 = perceptualRoughness * perceptualRoughness;
-
-
- // The albedo may be defined from a base texture or a flat color
- #if USE_TEXTURE
- let baseColor:vec4 = textureSample(baseColorTexture,baseColorSampler, input.uv) ;
- #else
- let baseColor:vec4 = vec4(materialUniform.color,1.0);
- #endif
-
- #if USE_NORMALTEXTURE
- let n:vec3 = getNormalByNormalTexture(input);
- #else
- let n:vec3 = getNormal(input);
- #endif
- var material:PhysicalMaterial;
- material.diffuseColor=baseColor.rgb*( 1.0 - metallic );
- material.roughness=perceptualRoughness;
- material.specularColor=mix( vec3( 0.04), baseColor.rgb, metallic );
- var geometry:Geometry;
- geometry.normal=n;
- geometry.viewDir=normalize(systemUniform.cameraPosition - input.worldPos);
- geometry.position=input.worldPos;
- geometry.dotNV = saturate(dot(geometry.normal, geometry.viewDir) );
- //light shading
- var reflectedLight=parseLights(geometry,material);
- var color=reflectedLight.directDiffuse+reflectedLight.directSpecular;
- //ibl
- #if USE_IBL&&HAS_UV
- var reflectedLightDiffuse=indirectDiffuse_Physical(geometry,material);
- var reflectedLightSpecular=indirectSpecular_Physical(geometry,material);
- color+=reflectedLightDiffuse.indirectDiffuse;
- color+=reflectedLightSpecular.indirectSpecular;
- #endif
- #if USE_AOTEXTURE
- let ao:f32 = textureSample(aoTexture,aoSampler, input.uv).r;
- color = mix(color, color * ao, materialUniform.occlusionStrength);
- #endif
-
- #if USE_EMISSIVETEXTURE
- let emissive:vec3 = textureSample(emissiveTexture, emissiveSampler,input.uv).rgb ;
- color += emissive;
- #endif
- return vec4(color, baseColor.a);
- }
- `;
-
-var pbr_vs = `
- #include
- #include
- #include
- #include
- #include
- #include
- @binding(pbrBinding) @group(0) var materialUniform : MaterialUniform;
- @binding(cameraBinding) @group(1) var systemUniform : SystemUniform;
- @vertex
- fn main(input: VertexInput)-> VertexOutput
- {
- var output: VertexOutput;
- #if HAS_UV
- output.uv = input.uv;
- #endif
- var modelMatrix:mat4x4;
- var vNormalView:vec3;
- vNormalView = normalize(materialUniform.normalMatrix * vec4(input.normal,0.0)).xyz;
- modelMatrix=materialUniform.modelMatrix;
- #include
- #include
- output.normal = vNormalView.xyz;
- output.position = systemUniform.projectionMatrix * systemUniform.viewMatrix *modelMatrix* vec4(input.position, 1.0);
- let modelPos=modelMatrix *vec4(input.position,1.0);
- output.worldPos = modelPos.xyz/modelPos.w;
- return output;
- }
- `;
-
-const preprocessorSymbols$1 = /#([^\s]*)(\s*)/gm;
-// Template literal tag that handles simple preprocessor symbols for WGSL
-// shaders. Supports #if/elif/else/endif statements.
-function wgslParseDefines(strings, ...values) {
- const stateStack = [];
- let state = { frag: "", elseIsValid: false, expression: true };
- let depth = 1;
- for (let i = 0; i < strings.length; ++i) {
- const frag = strings[i];
- const matchedSymbols = frag.matchAll(preprocessorSymbols$1);
- let lastIndex = 0;
- let valueConsumed = false;
- for (const match of matchedSymbols) {
- state.frag += frag.substring(lastIndex, match.index);
- switch (match[1]) {
- case "if":
- if (match.index + match[0].length != frag.length) {
- throw new Error("#if must be immediately followed by a template expression (ie: ${value})");
- }
- valueConsumed = true;
- stateStack.push(state);
- depth++;
- state = { frag: "", elseIsValid: true, expression: !!values[i] };
- break;
- case "elif":
- if (match.index + match[0].length != frag.length) {
- throw new Error("#elif must be immediately followed by a template expression (ie: ${value})");
- } else if (!state.elseIsValid) {
- throw new Error("#elif not preceeded by an #if or #elif");
- }
- valueConsumed = true;
- if (state.expression && stateStack.length != depth) {
- stateStack.push(state);
- }
- state = { frag: "", elseIsValid: true, expression: !!values[i] };
- break;
- case "else":
- if (!state.elseIsValid) {
- throw new Error("#else not preceeded by an #if or #elif");
- }
- if (state.expression && stateStack.length != depth) {
- stateStack.push(state);
- }
- state = { frag: match[2], elseIsValid: false, expression: true };
- break;
- case "endif":
- if (!stateStack.length) {
- throw new Error("#endif not preceeded by an #if");
- }
- // eslint-disable-next-line no-case-declarations
- const branchState = stateStack.length == depth ? stateStack.pop() : state;
- state = stateStack.pop();
- depth--;
- if (branchState.expression) {
- state.frag += branchState.frag;
- }
- state.frag += match[2];
- break;
- default:
- // Unknown preprocessor symbol. Emit it back into the output frag unchanged.
- state.frag += match[0];
- break;
- }
- lastIndex = match.index + match[0].length;
- }
- // If the frag didn't end on one of the preprocessor symbols append the rest of it here.
- if (lastIndex != frag.length) {
- state.frag += frag.substring(lastIndex, frag.length);
- }
- // If the next value wasn't consumed by the preprocessor symbol, append it here.
- if (!valueConsumed && values.length > i) {
- state.frag += values[i];
- }
- }
- if (stateStack.length) {
- throw new Error("Mismatched #if/#endif count");
- }
- return state.frag;
-}
-
-function pbrFrag(defines) {
- return wgslParseDefines`
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- struct SystemUniform {
- projectionMatrix: mat4x4,
- viewMatrix: mat4x4,
- inverseViewMatrix: mat4x4,
- cameraPosition: vec3,
- };
- // uniform vec3 lightProbe[9],
-////////////////////////////////////
-struct VertexOutput {
- @builtin(position) position: vec4,
- @builtin(front_facing) is_front: bool,
- @location(0) vUv: vec2,
- @location(1) vViewPosition: vec3, // Vector from vertex to camera.
- @location(2) vWorldPosition: vec3,
- @location(3) vNormal: vec3,
- // 可选
- #if ${defines.USE_LIGHTTEXTURE || defines.USE_AOTEXTURE}
- @location(${defines.vUv2OutLocation}) vUv2: vec2,
- #endif
-
- #if ${defines.USE_COLOR_ALPHA}
- @location(${defines.vColorOutLocation}) vColor: vec4,
- #elif ${defines.USE_COLOR || defines.USE_INSTANCING_COLOR}
- @location(${defines.vColorOutLocation}) vColor: vec3,
- #endif
-
- #if ${defines.USE_TANGENT}
- @location(${defines.vTangentOutLocation}) vTangent: vec3,
- @location(${defines.vBitangentOutLocation}) vBitangent: vec3,
- #endif
-};
- struct PhysicalMaterial {
- diffuseColor:vec3,
- roughness:f32,
- specularColor:vec3,
- specularF90:f32,
- #if ${defines.USE_CLEARCOAT}
- clearcoat:f32,
- clearcoatRoughness:f32,
- clearcoatF0:vec3,
- clearcoatF90:f32,
- #endif
-
- #if ${defines.USE_IRIDESCENCE}
- iridescence:f32,
- iridescenceIOR:f32,
- iridescenceThickness:f32,
- iridescenceFresnel:vec3,
- iridescenceF0:vec3,
- #endif
-
- #if ${defines.USE_SHEEN}
- sheenColor:vec3,
- sheenRoughness:f32,
- #endif
-
- #if ${defines.IOR}
- ior:f32,
- #endif
-
- #if ${defines.USE_TRANSMISSION}
- transmission:f32,
- transmissionAlpha:f32,
- thickness:f32,
- attenuationDistance:f32,
- attenuationColor:vec3,
- #endif
- };
-@binding(0) @group(0) var materialUniform : MaterialUniform;
-@binding(0) @group(1) var systemUniform : SystemUniform;
-@fragment
-fn main(input:VertexOutput)-> @location(0) vec4 {
- var diffuseColor:vec4 = vec4(materialUniform.diffuse, materialUniform.opacity );
- // ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- var reflectedLight:ReflectedLight;
- var totalEmissiveRadiance:vec3 = materialUniform.emissive;
- #if ${defines.USE_TEXTURE}
- var sampledDiffuseColor:vec4 =textureSample(baseTexture, baseSampler, input.vUv);
- #if ${defines.DECODE_VIDEO_TEXTURE}
- sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );
- #endif
-
- diffuseColor *= sampledDiffuseColor;
- #endif
-
- var roughnessFactor:f32 = materialUniform.roughness;
-
- #if ${defines.USE_ROUGHNESSTEXTURE}
- let texelRoughness:vec4=textureSample(roughnessTexture, baseSampler, input.vUv);
- roughnessFactor *= texelRoughness.g;
- #endif
-
- var metalnessFactor:f32 = materialUniform.metalness;
-
- #if ${defines.USE_METALNESSTEXTURE}
- let texelMetalness:vec4 =textureSample(metalnessTexture, baseSampler, input.vUv);
- metalnessFactor *= texelMetalness.b;
- #endif
-
- let faceDirection:f32 =select(-1.0,1.0,input.is_front);
- #if ${defines.FLAT_SHADED}
- let fdx:vec3 = dpdx( input.vViewPosition );
- let fdy:vec3 = dpdy( input.vViewPosition );
- let normal:vec3 = normalize( cross( fdy, fdx ) );
- #else
- let normal:vec3 = normalize( input.vNormal );
- #if ${defines.DOUBLE_SIDED}
- normal = normal * faceDirection;
- #endif
- #if ${defines.USE_TANGENT}
- let tangent:vec3 = normalize( input.vTangent );
- let bitangent:vec3 = normalize( input.vBitangent );
- #if ${defines.DOUBLE_SIDED}
- tangent = tangent * faceDirection;
- bitangent = bitangent * faceDirection;
- #endif
- #if ${defines.TANGENTSPACE_NORMALTEXTURE || defines.USE_CLEARCOAT_NORMALTEXTURE}
- let vTBN:mat3x3 = mat3x3( tangent, bitangent, normal );
- #endif
- #endif
- #endif
-
- let geometryNormal:vec3 = normal;
-
- #if ${defines.OBJECTSPACE_NORMALTEXTURE}
- normal =textureSample(normalTexture, baseSampler, input.vUv).xyz * 2.0 - 1.0;
- #if ${defines.FLIP_SIDED}
- normal = - normal;
- #endif
- #if ${defines.DOUBLE_SIDED}
- normal = normal * faceDirection;
- #endif
-
- normal = normalize(materialUniform.normalMatrix * normal );
-
- #elif ${defines.TANGENTSPACE_NORMALTEXTURE}
- let tempMapN:vec3 =textureSample(normalTexture, baseSampler, input.vUv).xyz * 2.0 - 1.0;
- let mapN:vec3 =tempMapN.xy *= materialUniform.normalScale;
- #if ${defines.USE_TANGENT}
- normal = normalize( vTBN * mapN );
- #else
- normal = perturbNormal2Arb( - input.vViewPosition, normal, mapN, faceDirection );
- #endif
-
- #elif ${defines.USE_BUMPTEXTURE}
-
- normal = perturbNormalArb( - input.vViewPosition, normal, dHdxy_fwd(), faceDirection );
- #endif
-
- #if ${defines.USE_CLEARCOAT}
- var clearcoatNormal:vec3 = geometryNormal;
- #endif
- #if ${defines.USE_CLEARCOAT_NORMALTEXTURE}
- var clearcoatMapN:vec3 =textureSample(clearcoatNormalTexture, baseSampler, input.vUv).xyz * 2.0 - 1.0;
- clearcoatMapN.xy *= materialUniform.clearcoatNormalScale;
- #if ${defines.USE_TANGENT}
- clearcoatNormal = normalize( vTBN * clearcoatMapN );
- #else
- clearcoatNormal = perturbNormal2Arb( - input.vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );
- #endif
- #endif
- #if ${defines.USE_EMISSIVETEXTURE}
- let emissiveColor:vec4 =textureSample(emissiveTexture, baseSampler, input.vUv);
- totalEmissiveRadiance *= emissiveColor.rgb;
- #endif
-
- var material:PhysicalMaterial;
- material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
- let dxy:vec3 = max( abs( dpdx( geometryNormal ) ), abs( dpdy( geometryNormal ) ) );
- let geometryRoughness:f32 = max( max( dxy.x, dxy.y ), dxy.z );
- material.roughness = max( roughnessFactor, 0.0525 );
- material.roughness += geometryRoughness;
- material.roughness = min( material.roughness, 1.0 );
-
- #if ${defines.IOR}
- material.ior = materialUniform.ior;
- #if ${defines.SPECULAR}
- let specularIntensityFactor:f32 = materialUniform.specularIntensity;
- let specularColorFactor:vec3 = materialUniform.specularColor;
- #if ${defines.USE_SPECULARINTENSITYTEXTURE}
- specularIntensityFactor *=textureSample(specularIntensityTexture, baseSampler, input.vUv).a;
- #endif
-
- #if ${defines.USE_SPECULARCOLORTEXTURE}
- specularColorFactor *=textureSample(specularColorTexture, baseSampler, input.vUv).rgb;
- #endif
-
- material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
- #else
- let specularIntensityFactor:f32 = 1.0;
- let specularColorFactor:vec3 = vec3( 1.0 );
- material.specularF90 = 1.0;
- #endif
- material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
- #else
- material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
- material.specularF90 = 1.0;
- #endif
- #if ${defines.USE_CLEARCOAT}
- material.clearcoat = materialUniform.clearcoat;
- material.clearcoatRoughness = materialUniform.clearcoatRoughness;
- material.clearcoatF0 = vec3( 0.04 );
- material.clearcoatF90 = 1.0;
- #if ${defines.USE_CLEARCOATTEXTURE}
- material.clearcoat *=textureSample(clearcoatTexture, baseSampler, input.vUv).x;
- #endif
- #if ${defines.USE_CLEARCOAT_ROUGHNESSTEXTURE}
- material.clearcoatRoughness *=textureSample(clearcoatRoughnessTexture, baseSampler, input.vUv).y;
- #endif
- material.clearcoat = saturate( material.clearcoat );
- material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
- material.clearcoatRoughness += geometryRoughness;
- material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
- #endif
- #if ${defines.USE_IRIDESCENCE}
- material.iridescence = materialUniform.iridescence;
- material.iridescenceIOR = materialUniform.iridescenceIOR;
- #if ${defines.USE_IRIDESCENCETEXTURE}
- material.iridescence *=textureSample(iridescenceTexture, baseSampler, input.vUv).r;
- #endif
- #if ${defines.USE_IRIDESCENCE_THICKNESSTEXTURE}
- material.iridescenceThickness = (materialUniform.iridescenceThicknessMaximum - materialUniform.iridescenceThicknessMinimum) * textureSample(iridescenceThicknessTexture, baseSampler, input.vUv).g + materialUniform.iridescenceThicknessMinimum;
- #else
- material.iridescenceThickness = materialUniform.iridescenceThicknessMaximum;
- #endif
- #endif
- #if ${defines.USE_SHEEN}
- material.sheenColor = materialUniform.sheenColor;
- #if ${defines.USE_SHEENCOLORTEXTURE}
- material.sheenColor *=textureSample(sheenColorTexture, baseSampler, input.vUv).rgb;
- #endif
- material.sheenRoughness = clamp( materialUniform.sheenRoughness, 0.07, 1.0 );
- #if ${defines.USE_SHEENROUGHNESSTEXTURE}
- material.sheenRoughness *=textureSample(sheenRoughnessTexture, baseSampler, input.vUv).a;
- #endif
- #endif
-
- var geometry:GeometricContext;
- geometry.position = - input.vViewPosition;
- geometry.normal = normal;
- // geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( input.vViewPosition );
- geometry.viewDir = normalize( input.vViewPosition);
-
- #if ${defines.USE_CLEARCOAT}
- geometry.clearcoatNormal = clearcoatNormal;
- #endif
-
- #if ${defines.USE_IRIDESCENCE}
- let dotNVi:f32 = saturate( dot( normal, geometry.viewDir ) );
- if ( material.iridescenceThickness == 0.0 ) {
- material.iridescence = 0.0;
- }
- else {
- material.iridescence = saturate( material.iridescence );
- }
- if ( material.iridescence > 0.0 ) {
- material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
- material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
- }
- #endif
-
- var iblIrradiance:vec3 = vec3( 0.0 );
- var irradiance:vec3 = getAmbientLightIrradiance(commonLightsParms.ambient);
- //irradiance += getLightProbeIrradiance( lightProbe, geometry.normal,systemUniform.viewMatrix );
-
- var radiance:vec3 = vec3( 0.0 );
- var clearcoatRadiance:vec3 = vec3( 0.0 );
-
- #if ${defines.USE_LIGHTTEXTURE}
- let lightMapTexel:vec4 =textureSample(lightTexture, baseSampler, input.vUv2);
- let lightMapIrradiance:vec3 = lightMapTexel.rgb * materialUniform.lightTextureIntensity;
- irradiance += lightMapIrradiance;
- #endif
- //&& defines.STANDARD&&defines.ENVTEXTURE_TYPE_CUBE_UV
- #if ${defines.USE_ENVTEXTURE}
- iblIrradiance += getIBLIrradiance( geometry.normal,baseSampler,systemUniform.viewMatrix );
- #endif
- #if ${defines.USE_ENVTEXTURE}
- radiance += getIBLRadiance( geometry.viewDir,baseSampler,systemUniform.viewMatrix, geometry.normal, materialUniform.roughness );
- #if ${defines.USE_CLEARCOAT}
- clearcoatRadiance += getIBLRadiance( geometry.viewDir,baseSampler,systemUniform.viewMatrix, geometry.clearcoatNormal, material.clearcoatRoughness );
- #endif
- #endif
- //直接光照
- let dirReflectedLight:ReflectedLight= parseLights(geometry,material);
- reflectedLight.directDiffuse +=dirReflectedLight.directDiffuse;
- reflectedLight.directSpecular +=dirReflectedLight.directSpecular;
- //间接漫反射
- let indirectDiffuseLight:ReflectedLight= RE_IndirectDiffuse_Physical( irradiance, geometry, material);
- reflectedLight.directDiffuse +=indirectDiffuseLight.indirectDiffuse;
- reflectedLight.directSpecular +=indirectDiffuseLight.indirectSpecular;
- //间接高光
- let indirectSpecularLight:ReflectedLight=RE_IndirectSpecular_Physical( radiance, iblIrradiance, clearcoatRadiance, geometry, material);
- reflectedLight.directDiffuse +=indirectSpecularLight.indirectDiffuse;
- reflectedLight.directSpecular +=indirectSpecularLight.indirectSpecular;
- //环境光遮蔽
- #if ${defines.USE_AOTEXTURE}
- let ambientOcclusion:f32 = (textureSample(aoTexture, baseSampler, input.vUv2).r - 1.0 ) * materialUniform.aoTextureIntensity + 1.0;
-
- reflectedLight.indirectDiffuse *= ambientOcclusion;
- //&&defines.STANDARD
- #if ${defines.USE_ENVTEXTURE}
- let dotNV:f32 = saturate( dot( geometry.normal, geometry.viewDir ) );
- reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
- #endif
- #endif
-
- var totalDiffuse:vec3 = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
- var totalSpecular:vec3 = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
- //透射
- #if ${defines.USE_TRANSMISSION}
- material.transmission = materialUniform.transmission;
- material.transmissionAlpha = 1.0;
- material.thickness = materialUniform.thickness;
- material.attenuationDistance = materialUniform.attenuationDistance;
- material.attenuationColor = materialUniform.attenuationColor;
- #if ${defines.USE_TRANSMISSIONTEXTURE}
- material.transmission *=textureSample(transmissionTexture, baseSampler, input.vUv).r;
- #endif
- #if ${defines.USE_THICKNESSTEXTURE}
- material.thickness *=textureSample(thicknessTexture, baseSampler, input.vUv).g;
- #endif
- let pos:vec3 = vWorldPosition;
- let v:vec3 = normalize( cameraPosition - pos );
- let n:vec3 = inverseTransformDirection( normal, systemUniform.viewMatrix );
- let transmission:vec4 = getIBLVolumeRefraction(
- n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, systemUniform.viewMatrix, systemUniform.projectionMatrix, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance );
- material.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );
- totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );
- #endif
-
- let outgoingLight:vec3 = totalDiffuse + totalSpecular + totalEmissiveRadiance;
-
- #if ${defines.USE_SHEEN}
- let sheenEnergyComp:f32 = 1.0 - 0.157 * max3( material.sheenColor );
- outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;
- #endif
-
- #if ${defines.USE_CLEARCOAT}
- let dotNVcc:f32 = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );
- let Fcc:vec3 = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
- outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;
- #endif
-
- #if ${defines.USE_TRANSMISSION}
- diffuseColor.a *= material.transmissionAlpha + 0.1;
- #endif
-
- var finnalColor:vec4;
- finnalColor = vec4( outgoingLight, diffuseColor.a );
- #if ${defines.TONE_MAPPING}
- finnalColor.rgb = toneMapping( finnalColor.rgb,materialUniform.toneMappingExposure );
- #endif
-
- finnalColor = linearToOutputTexel( finnalColor);
-
- #if ${defines.PREMULTIPLIED_ALPHA}
- finnalColor.rgb *= finnalColor.a;
- #endif
- #if ${defines.DITHERING}
- finnalColor.rgb = dithering( finnalColor.rgb );
- #endif
- return finnalColor;
- }`;
-}
-
-function pbrVert(defines) {
- return wgslParseDefines`
- #include
- struct VertexOutput {
- @builtin(position) position: vec4,
- @location(0) vUv: vec2,
- @location(1) vViewPosition: vec3, // Vector from vertex to camera.
- @location(2) vWorldPosition: vec3,
- @location(3) vNormal: vec3,
- // 可选
- #if ${defines.USE_LIGHTTEXTURE || defines.USE_AOTEXTURE}
- @location(${defines.vUv2OutLocation}) vUv2: vec2,
- #endif
-
- #if ${defines.USE_COLOR_ALPHA}
- @location(${defines.vColorOutLocation}) vColor: vec4,
- #elif ${defines.USE_COLOR || defines.USE_INSTANCING_COLOR}
- @location(${defines.vColorOutLocation}) vColor: vec3,
- #endif
-
- #if ${defines.USE_TANGENT}
- @location(${defines.vTangentOutLocation}) vTangent: vec3,
- @location(${defines.vBitangentOutLocation}) vBitangent: vec3,
- #endif
- };
- struct GlobalUniform {
- projectionMatrix: mat4x4,
- viewMatrix: mat4x4,
- inverseViewMatrix: mat4x4,
- cameraPosition: vec3,
- };
-
- //texture and sampler
- // @group(0) @binding(${defines.samplerBinding}) var baseSampler: sampler;
- #if ${defines.USE_SKINNING}
- //uniform highp sampler2D boneTexture;
- @group(0) @binding(${defines.boneTextureBinding}) var boneTexture: texture_2d;
- #endif
-
- #if ${defines.USE_DISPLACEMENTTEXTURE}
- //uniform sampler2D displacementMap;
- @group(0) @binding(${defines.displacementTextureBinding}) var displacementMap: texture_2d;
- #endif
-
- #if ${defines.MORPHTARGETS_TEXTURE}
- //uniform sampler2DArray morphTargetsTexture;
- @group(0) @binding(${defines.morphTargetsTextureBinding}) var morphTargetsTexture: texture_2d_array;
- #endif
-
- struct VertexInput {
- @location(0) position: vec3,
-
- @location(1) normal: vec3,
-
- @location(2) uv: vec2,
- #if ${defines.USE_LIGHTTEXTURE || defines.USE_AOTEXTURE}
- @location(${defines.uv2Location}) uv2:vec2,
- #endif
- #if ${defines.USE_INSTANCING}
- @location(${defines.instanceMatrixLocation}) instanceMatrix:mat4x4,
- #endif
- #if ${defines.USE_INSTANCING_COLOR}
- @location(${defines.instanceColorLocation}) instanceColor:vec3,
- #endif
-
- #if ${defines.USE_TANGENT}
- @location(${defines.tangentLocation}) tangent:vec4,
- #endif
- #if ${defines.USE_COLOR_ALPHA}
- @location(${defines.colorLocation}) color:vec4,
- #elif ${defines.USE_COLOR}
- @location(${defines.colorLocation}) color:vec3,
- #endif
-
- #if ${defines.USE_MORPHTARGETS && !defines.MORPHTARGETS_TEXTURE}
- @location(${defines.morphTarget0Location}) morphTarget0:vec3,
-
- @location(${defines.morphTarget1Location}) morphTarget1:vec3,
-
- @location(${defines.morphTarget2Location}) morphTarget2:vec3,
-
- @location(${defines.morphTarget3Location}) morphTarget3:vec3,
- #if ${defines.USE_MORPHNORMALS}
- @location(${defines.morphNormal0Location}) morphNormal0:vec3,
-
- @location(${defines.morphNormal1Location}) morphNormal1:vec3,
-
- @location(${defines.morphNormal2Location}) morphNormal2:vec3,
-
- @location(${defines.morphNormal3Location}) morphNormal3:vec3,
- #else
- @location(${defines.morphTarget4Location}) morphTarget4:vec3,
-
- @location(${defines.morphTarget5Location}) morphTarget5:vec3,
-
- @location(${defines.morphTarget6Location}) morphTarget6:vec3,
-
- @location(${defines.morphTarget7Location}) morphTarget7:vec3,
- #endif
- #endif
- #if ${defines.USE_SKINNING}
- @location(${defines.skinIndexLocation}) skinIndex:vec4,
- @location(${defines.skinWeightLocation}) skinWeight:vec4,
- #endif
- }
-
- #if ${defines.MORPHTARGETS_TEXTURE}
- fn getMorph( vertexIndex:u32, morphTargetIndex:u32,offset:u32 )->vec4 {
- let texelIndex:u32 = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
- let y:u32 = texelIndex / materialUniform.morphTargetsTextureSize.x;
- let x:u32 = texelIndex - y * materialUniform.morphTargetsTextureSize.x;
- let morphUV:vec3 = vec3( x, y, morphTargetIndex );
- //textureLoad
- //return texelFetch( morphTargetsTexture, morphUV, 0 );
- return textureLoad( morphTargetsTexture, morphUV, 0 );
- }
- #endif
- #if ${defines.USE_SKINNING}
- fn getBoneMatrix( i:f32 )->mat4x4 {
- let j:f32 = i * 4.0;
- let x:f32 = j%f32( materialUniform.boneTextureSize );
- let y:f32 = floor( j / f32( materialUniform.boneTextureSize ) );
- let dx:f32 = 1.0 / f32( materialUniform.boneTextureSize );
- let dy:f32 = 1.0 / f32( materialUniform.boneTextureSize );
- y = dy * ( y + 0.5 );
-
- let v1:vec4 = textureSample(boneTexture, baseSampler, vec2( dx * ( x + 0.5 ), y ) );
- let v2:vec4 = textureSample(boneTexture, baseSampler, vec2( dx * ( x + 1.5 ), y ) );
- let v3:vec4 = textureSample(boneTexture, baseSampler, vec2( dx * ( x + 2.5 ), y ) );
- let v4:vec4 = textureSample(boneTexture, baseSampler, vec2( dx * ( x + 3.5 ), y ) );
- let bone:mat4x4 = mat4x4( v1, v2, v3, v4 );
- return bone;
- }
- #endif
-
- @binding(0) @group(0) var materialUniform : MaterialUniform;
- @binding(0) @group(1) var globalUniform : GlobalUniform;
- @vertex
- fn main(input:VertexInput)->VertexOutput {
- var vertexOutput:VertexOutput;
- #if ${defines.USE_TEXTURE}
- vertexOutput.vUv = input.uv;
- #endif
- #if ${defines.USE_LIGHTTEXTURE || defines.USE_AOTEXTURE}
- vertexOutput.vUv2 input.uv2;
- #endif
- #if ${defines.USE_COLOR_ALPHA}
- vertexOutput.vColor = vec4( 1.0 );
- #elif ${defines.USE_COLOR || defines.USE_INSTANCING_COLOR}
- vertexOutput.vColor = vec3( 1.0 );
- #endif
- #if ${defines.USE_COLOR}
- vertexOutput.vColor *= input.color;
- #endif
- #if ${defines.USE_INSTANCING_COLOR}
- vertexOutput.vColor.xyz *= input.instanceColor.xyz;
- #endif
- #if ${defines.USE_MORPHCOLORS && defines.MORPHTARGETS_TEXTURE}
- vertexOutput.vColor *= materialUniform.morphTargetBaseInfluence;
- for (let i : u32 = 0u; i < materialUniform.MORPHTARGETS_COUNT; i = i + 1u ) {
- #if ${defines.USE_COLOR_ALPHA}
- if ( materialUniform.morphTargetInfluences[ i ] ! = 0.0 ) vertexOutput.vColor += getMorph( gl_VertexID, i, 2 ) * materialUniform.morphTargetInfluences[ i ];
- #elif ${defines.USE_COLOR}
- if ( materialUniform.morphTargetInfluences[ i ] ! = 0.0 ) vertexOutput.vColor += getMorph( gl_VertexID, i, 2 ).rgb * materialUniform.morphTargetInfluences[ i ];
- #endif
- }
- #endif
- var objectNormal:vec3 = vec3(input.normal);
- #if ${defines.USE_TANGENT}
- let objectTangent:vec3 = vec3( input.tangent.xyz );
- #endif
- #if ${defines.USE_MORPHNORMALS}
- objectNormal *= materialUniform.morphTargetBaseInfluence;
- #if ${defines.MORPHTARGETS_TEXTURE}
- for ( let i : u32 = 0u; i < materialUniform.MORPHTARGETS_COUNT; i = i + 1u) {
- if ( materialUniform.morphTargetInfluences[ i ] ! = 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * materialUniform.morphTargetInfluences[ i ];
- }
- #else
- objectNormal += morphNormal0 * materialUniform.morphTargetInfluences[ 0 ];
- objectNormal += morphNormal1 * materialUniform.morphTargetInfluences[ 1 ];
- objectNormal += morphNormal2 * materialUniform.morphTargetInfluences[ 2 ];
- objectNormal += morphNormal3 * materialUniform.morphTargetInfluences[ 3 ];
- #endif
- #endif
- #if ${defines.USE_SKINNING}
- let boneMatX:mat4x4 = getBoneMatrix( input.skinIndex.x );
- let boneMatY:mat4x4 = getBoneMatrix( input.skinIndex.y );
- let boneMatZ:mat4x4 = getBoneMatrix( input.skinIndex.z );
- let boneMatW:mat4x4 = getBoneMatrix( input.skinIndex.w );
- #endif
- #if ${defines.USE_SKINNING}
- let skinMatrix:mat4x4 = mat4x4( 0.0 );
- skinMatrix += input.skinWeight.x * boneMatX;
- skinMatrix += input.skinWeight.y * boneMatY;
- skinMatrix += input.skinWeight.z * boneMatZ;
- skinMatrix += input.skinWeight.w * boneMatW;
- skinMatrix = materialUniform.bindMatrixInverse * skinMatrix * materialUniform.bindMatrix;
- objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
- #if ${defines.USE_TANGENT}
- objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
- #endif
- #endif
- var transformedNormal:vec3 = objectNormal;
- // transformedNormal+=vec3(0.0);
- #if ${defines.USE_INSTANCING}
- let m:mat3x3 = mat3x3( input.instanceMatrix );
- transformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );
- transformedNormal = m * transformedNormal;
- #endif
- transformedNormal = materialUniform.normalMatrix * transformedNormal;
- #if ${defines.FLIP_SIDED}
- transformedNormal = - transformedNormal;
- #endif
- #if ${defines.USE_TANGENT}
- let transformedTangent:vec3 = (globalUniform.viewMatrix*materialUniform.modelMatrix * vec4( objectTangent, 0.0 ) ).xyz;
- #if ${defines.FLIP_SIDED}
- transformedTangent = - transformedTangent;
- #endif
- #endif
- vertexOutput.vNormal = normalize( transformedNormal );
- #if ${defines.FLAT_SHADED}
- #if ${defines.USE_TANGENT}
- vTangent = normalize( transformedTangent );
- vBitangent = normalize( cross( vNormal, vTangent ) * input.tangent.w );
- #endif
- #endif
- let transformed:vec3 = vec3( input.position );
- #if ${defines.USE_MORPHTARGETS}
- transformed *= materialUniform.morphTargetBaseInfluence;
- #if ${defines.MORPHTARGETS_TEXTURE}
- for ( let i : u32 = 0u; i < materialUniform.MORPHTARGETS_COUNT; i = i + 1u ) {
- if ( materialUniform.morphTargetInfluences[ i ] ! = 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
- }
- #else
- transformed += input.morphTarget0 * materialUniform.morphTargetInfluences[ 0 ];
- transformed += input.morphTarget1 * materialUniform.morphTargetInfluences[ 1 ];
- transformed += input.morphTarget2 * materialUniform.morphTargetInfluences[ 2 ];
- transformed += input.morphTarget3 * materialUniform.morphTargetInfluences[ 3 ];
- #if ${defines.USE_MORPHNORMALS}
- transformed += input.morphTarget4 * materialUniform.morphTargetInfluences[ 4 ];
- transformed += input.morphTarget5 * materialUniform.morphTargetInfluences[ 5 ];
- transformed += input.morphTarget6 * materialUniform.morphTargetInfluences[ 6 ];
- transformed += input.morphTarget7 * materialUniform.morphTargetInfluences[ 7 ];
- #endif
- #endif
- #endif
- #if ${defines.USE_SKINNING}
- let skinVertex:vec4 = materialUniform.bindMatrix * vec4( transformed, 1.0 );
- let skinned:vec4 = vec4( 0.0 );
- skinned += boneMatX * skinVertex * input.skinWeight.x;
- skinned += boneMatY * skinVertex * input.skinWeight.y;
- skinned += boneMatZ * skinVertex * input.skinWeight.z;
- skinned += boneMatW * skinVertex * input.skinWeight.w;
- transformed = ( materialUniform.bindMatrixInverse * skinned ).xyz;
- #endif
- #if ${defines.USE_DISPLACEMENTTEXTURE}
- transformed += normalize( objectNormal ) * (textureSample(displacementMap, baseSampler, vUv).x * materialUniform.displacementScale + materialUniform.displacementBias );
- #endif
- var mvPosition:vec4 = vec4( transformed, 1.0 );
- #if ${defines.USE_INSTANCING}
- mvPosition = input.instanceMatrix * mvPosition;
- #endif
- mvPosition = globalUniform.viewMatrix*materialUniform.modelMatrix * mvPosition;
- vertexOutput.position = globalUniform.projectionMatrix * mvPosition;
- vertexOutput.vViewPosition = - mvPosition.xyz/mvPosition.w;
- #if ${defines.USE_ENVTEXTURE || defines.DISTANCE || defines.USE_TRANSMISSION}
- var worldPosition:vec4 = vec4( transformed, 1.0 );
- #if ${defines.USE_INSTANCING}
- worldPosition = input.instanceMatrix * worldPosition;
- #endif
- worldPosition = materialUniform.modelMatrix * worldPosition;
- #endif
- #if ${defines.USE_TRANSMISSION}
- vertexOutput.vWorldPosition = worldPosition.xyz;
- #endif
- return vertexOutput;
- }
- `;
-}
-
-var phongFrag = `
- struct MaterialUniform {
- modelMatrix: mat4x4,
- color: vec3,
- opacity:f32,
- normalMatrix: mat4x4,
- emissive:vec3,
- shininess:f32,
- specular:vec3,
- }
- #include
- #include
- #include
- #include
- @binding(phongBinding) @group(0) var materialUniform : MaterialUniform;
- @binding(cameraBinding) @group(1) var systemUniform : SystemUniform;
- @fragment
- fn main(input:FragInput) -> @location(0) vec4 {
- var totalEmissiveRadiance:vec3 = materialUniform.emissive;
- var color:vec4;
- #if USE_COLORTEXTURE
- color= vec4(textureSample(baseColorTexture, baseColorSampler, input.uv).rgb+materialUniform.color,materialUniform.opacity);
- #else
- color=vec4(materialUniform.color,materialUniform.opacity);
- #endif
- let v:vec3 = normalize( systemUniform.cameraPosition - input.worldPos);
- #if USE_NORMALTEXTURE
- let n:vec3