Browse Source

WebGPURenderPipelines: Make shader attributes parsing more robust.

Mugen87 4 years ago
parent
commit
dfe538e053
1 changed files with 41 additions and 17 deletions
  1. 41 17
      examples/jsm/renderers/webgpu/WebGPURenderPipelines.js

+ 41 - 17
examples/jsm/renderers/webgpu/WebGPURenderPipelines.js

@@ -98,28 +98,19 @@ class WebGPURenderPipelines {
 			const bindLayout = this.bindings.get( object ).layout;
 			const layout = device.createPipelineLayout( { bindGroupLayouts: [ bindLayout ] } );
 
-			// vertex buffers
-
-			const vertexBuffers = [];
-			const shaderAttributes = [];
+			// determine shader attributes
 
-			// find "layout (location = num) in type name" in vertex shader
+			const shaderAttributes = this._parseShaderAttributes( shader.vertexShader );
 
-			const regex = /^\s*layout\s*\(\s*location\s*=\s*(?<location>[0-9]+)\s*\)\s*in\s+(?<type>\w+)\s+(?<name>\w+)\s*;/gmi;
-
-			let shaderAttribute = null;
-
-			while ( shaderAttribute = regex.exec( shader.vertexShader ) ) {
+			// vertex buffers
 
-				const shaderLocation = parseInt( shaderAttribute.groups.location );
-				const arrayStride = this._getArrayStride( shaderAttribute.groups.type );
-				const vertexFormat = this._getVertexFormat( shaderAttribute.groups.type );
+			const vertexBuffers = [];
 
-				shaderAttributes.push( { name: shaderAttribute.groups.name, slot: shaderLocation } );
+			for ( const attribute of shaderAttributes ) {
 
 				vertexBuffers.push( {
-					arrayStride: arrayStride,
-					attributes: [ { shaderLocation: shaderLocation, offset: 0, format: vertexFormat } ]
+					arrayStride: attribute.arrayStride,
+					attributes: [ { shaderLocation: attribute.slot, offset: 0, format: attribute.format } ]
 				} );
 
 			}
@@ -202,7 +193,6 @@ class WebGPURenderPipelines {
 			this.pipelines.set( object, pipeline );
 			this.shaderAttributes.set( pipeline, shaderAttributes );
 
-
 		}
 
 		return pipeline;
@@ -707,6 +697,40 @@ class WebGPURenderPipelines {
 
 	}
 
+	_parseShaderAttributes( shader ) {
+
+		// find "layout (location = num) in type name" in vertex shader
+
+		const regex = /^\s*layout\s*\(\s*location\s*=\s*(?<location>[0-9]+)\s*\)\s*in\s+(?<type>\w+)\s+(?<name>\w+)\s*;/gmi;
+		let shaderAttribute = null;
+
+		const attributes = [];
+
+		while ( shaderAttribute = regex.exec( shader ) ) {
+
+			const shaderLocation = parseInt( shaderAttribute.groups.location );
+			const arrayStride = this._getArrayStride( shaderAttribute.groups.type );
+			const vertexFormat = this._getVertexFormat( shaderAttribute.groups.type );
+
+			attributes.push( {
+				name: shaderAttribute.groups.name,
+				arrayStride: arrayStride,
+				slot: shaderLocation,
+				format: vertexFormat
+			} );
+
+		}
+
+		// the sort ensures to setup vertex buffers in the correct order
+
+		return attributes.sort( function ( a, b ) {
+
+			return a.slot - b.slot;
+
+		} );
+
+	}
+
 }
 
 const ShaderLib = {