Ver código fonte

improved pbr shaders

danaugrs 7 anos atrás
pai
commit
9516690de4

+ 1 - 1
material/material.go

@@ -66,7 +66,7 @@ type Material struct {
 	wireframe        bool                 // show as wirefrme
 	depthMask        bool                 // Enable writing into the depth buffer
 	depthTest        bool                 // Enable depth buffer test
-	depthFunc        uint32               // Actvie depth test function
+	depthFunc        uint32               // Active depth test function
 	blending         Blending             // blending mode
 	blendRGB         uint32               // separate blend equation for RGB
 	blendAlpha       uint32               // separate blend equation for Alpha

+ 34 - 33
material/physical.go

@@ -39,12 +39,12 @@ func NewPhysical() *Physical {
 	m.Material.Init()
 	m.SetShader("physical")
 
-	// Creates uniform and set defaulf values
+	// Creates uniform and set default values
 	m.uni.Init("Material")
 	m.udata.baseColorFactor = math32.Color4{1, 1, 1, 1}
 	m.udata.emissiveFactor = math32.Color4{0, 0, 0, 0}
-	m.udata.metallicFactor = 1.0
-	m.udata.roughnessFactor = 1.0
+	m.udata.metallicFactor = 0.5
+	m.udata.roughnessFactor = 0.5
 	return m
 }
 
@@ -57,17 +57,21 @@ func (m *Physical) SetBaseColorFactor(c *math32.Color4) *Physical {
 	return m
 }
 
-// SetBaseColorTexture sets this material optional texture base color.
+// SetMetallicFactor sets this material metallic factor.
+// Its default value is 1.0
 // Returns pointer to this updated material.
-func (m *Physical) SetBaseColorTexture(tex *texture.Texture2D) *Physical {
+func (m *Physical) SetMetallicFactor(v float32) *Physical {
 
-	m.baseColorTex = tex
-	if m.baseColorTex != nil {
-		m.baseColorTex.SetUniformNames("uBaseColorSampler", "uBaseColorTexParams")
-		m.SetShaderDefine("HAS_BASECOLORMAP", "")
-	} else {
-		m.UnsetShaderDefine("HAS_BASECOLORMAP")
-	}
+	m.udata.metallicFactor = v
+	return m
+}
+
+// SetRoughnessFactor sets this material roughness factor.
+// Its default value is 1.0
+// Returns pointer to this updated material.
+func (m *Physical) SetRoughnessFactor(v float32) *Physical {
+
+	m.udata.roughnessFactor = v
 	return m
 }
 
@@ -82,18 +86,23 @@ func (m *Physical) SetEmissiveFactor(c *math32.Color) *Physical {
 	return m
 }
 
-// SetMetallicFactor sets this material metallic factor.
-// Its default value is 1.0
+// SetBaseColorMap sets this material optional texture base color.
 // Returns pointer to this updated material.
-func (m *Physical) SetMetallicFactor(v float32) *Physical {
+func (m *Physical) SetBaseColorMap(tex *texture.Texture2D) *Physical {
 
-	m.udata.metallicFactor = v
+	m.baseColorTex = tex
+	if m.baseColorTex != nil {
+		m.baseColorTex.SetUniformNames("uBaseColorSampler", "uBaseColorTexParams")
+		m.SetShaderDefine("HAS_BASECOLORMAP", "")
+	} else {
+		m.UnsetShaderDefine("HAS_BASECOLORMAP")
+	}
 	return m
 }
 
-// SetMetallicRoughnessTexture sets this material optional metallic-roughness texture.
+// SetMetallicRoughnessMap sets this material optional metallic-roughness texture.
 // Returns pointer to this updated material.
-func (m *Physical) SetMetallicRoughnessTexture(tex *texture.Texture2D) *Physical {
+func (m *Physical) SetMetallicRoughnessMap(tex *texture.Texture2D) *Physical {
 
 	m.metallicRoughnessTex = tex
 	if m.metallicRoughnessTex != nil {
@@ -105,9 +114,10 @@ func (m *Physical) SetMetallicRoughnessTexture(tex *texture.Texture2D) *Physical
 	return m
 }
 
-// SetNormalTexture sets this material optional normal texture.
+// TODO add SetNormalMap (and SetSpecularMap) to StandardMaterial.
+// SetNormalMap sets this material optional normal texture.
 // Returns pointer to this updated material.
-func (m *Physical) SetNormalTexture(tex *texture.Texture2D) *Physical {
+func (m *Physical) SetNormalMap(tex *texture.Texture2D) *Physical {
 
 	m.normalTex = tex
 	if m.normalTex != nil {
@@ -119,9 +129,9 @@ func (m *Physical) SetNormalTexture(tex *texture.Texture2D) *Physical {
 	return m
 }
 
-// SetOcclusionTexture sets this material optional occlusion texture.
+// SetOcclusionMap sets this material optional occlusion texture.
 // Returns pointer to this updated material.
-func (m *Physical) SetOcclusionTexture(tex *texture.Texture2D) *Physical {
+func (m *Physical) SetOcclusionMap(tex *texture.Texture2D) *Physical {
 
 	m.occlusionTex = tex
 	if m.occlusionTex != nil {
@@ -133,9 +143,9 @@ func (m *Physical) SetOcclusionTexture(tex *texture.Texture2D) *Physical {
 	return m
 }
 
-// SetEmissiveTexture sets this material optional emissive texture.
+// SetEmissiveMap sets this material optional emissive texture.
 // Returns pointer to this updated material.
-func (m *Physical) SetEmissiveTexture(tex *texture.Texture2D) *Physical {
+func (m *Physical) SetEmissiveMap(tex *texture.Texture2D) *Physical {
 
 	m.emissiveTex = tex
 	if m.emissiveTex != nil {
@@ -147,15 +157,6 @@ func (m *Physical) SetEmissiveTexture(tex *texture.Texture2D) *Physical {
 	return m
 }
 
-// SetRoughnessFactor sets this material roughness factor.
-// Its default value is 1.0
-// Returns pointer to this updated material.
-func (m *Physical) SetRoughnessFactor(v float32) *Physical {
-
-	m.udata.roughnessFactor = v
-	return m
-}
-
 // RenderSetup transfer this material uniforms and textures to the shader
 func (m *Physical) RenderSetup(gl *gls.GLS) {
 

+ 283 - 12
renderer/shaders/physical_fragment.glsl

@@ -1,12 +1,49 @@
 //
-// Physical material fragment shader
+// Physically Based Shading of a microfacet surface material - Fragment Shader
+// Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
 //
+// References:
+// [1] Real Shading in Unreal Engine 4
+//     http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
+// [2] Physically Based Shading at Disney
+//     http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf
+// [3] README.md - Environment Maps
+//     https://github.com/KhronosGroup/glTF-WebGL-PBR/#environment-maps
+// [4] "An Inexpensive BRDF Model for Physically based Rendering" by Christophe Schlick
+//     https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf
 
-// Inputs from vertex shader
-in vec4 Position;       // Vertex position in camera coordinates.
-in vec3 Normal;         // Vertex normal in camera coordinates.
-in vec3 CamDir;         // Direction from vertex to camera
-in vec2 FragTexcoord;
+//#extension GL_EXT_shader_texture_lod: enable
+//#extension GL_OES_standard_derivatives : enable
+
+precision highp float;
+
+//uniform vec3 u_LightDirection;
+//uniform vec3 u_LightColor;
+
+//#ifdef USE_IBL
+//uniform samplerCube u_DiffuseEnvSampler;
+//uniform samplerCube u_SpecularEnvSampler;
+//uniform sampler2D u_brdfLUT;
+//#endif
+
+#ifdef HAS_BASECOLORMAP
+uniform sampler2D u_BaseColorSampler;
+#endif
+#ifdef HAS_NORMALMAP
+uniform sampler2D u_NormalSampler;
+uniform float u_NormalScale;
+#endif
+#ifdef HAS_EMISSIVEMAP
+uniform sampler2D u_EmissiveSampler;
+uniform vec3 u_EmissiveFactor;
+#endif
+#ifdef HAS_METALROUGHNESSMAP
+uniform sampler2D u_MetallicRoughnessSampler;
+#endif
+#ifdef HAS_OCCLUSIONMAP
+uniform sampler2D u_OcclusionSampler;
+uniform float u_OcclusionStrength;
+#endif
 
 // Material parameters uniform array
 uniform vec4 Material[3];
@@ -18,21 +55,255 @@ uniform vec4 Material[3];
 
 #include <lights>
 
+// Inputs from vertex shader
+in vec3 Position;       // Vertex position in camera coordinates.
+in vec3 Normal;         // Vertex normal in camera coordinates.
+in vec3 CamDir;         // Direction from vertex to camera
+in vec2 FragTexcoord;
+
 // Final fragment color
 out vec4 FragColor;
 
+// Encapsulate the various inputs used by the various functions in the shading equation
+// We store values in this struct to simplify the integration of alternative implementations
+// of the shading terms, outlined in the Readme.MD Appendix.
+struct PBRInfo
+{
+    float NdotL;                  // cos angle between normal and light direction
+    float NdotV;                  // cos angle between normal and view direction
+    float NdotH;                  // cos angle between normal and half vector
+    float LdotH;                  // cos angle between light direction and half vector
+    float VdotH;                  // cos angle between view direction and half vector
+    float perceptualRoughness;    // roughness value, as authored by the model creator (input to shader)
+    float metalness;              // metallic value at the surface
+    vec3 reflectance0;            // full reflectance color (normal incidence angle)
+    vec3 reflectance90;           // reflectance color at grazing angle
+    float alphaRoughness;         // roughness mapped to a more linear change in the roughness (proposed by [2])
+    vec3 diffuseColor;            // color contribution from diffuse lighting
+    vec3 specularColor;           // color contribution from specular lighting
+};
+
+const float M_PI = 3.141592653589793;
+const float c_MinRoughness = 0.04;
+
+vec4 SRGBtoLINEAR(vec4 srgbIn) {
+//#ifdef MANUAL_SRGB
+//    #ifdef SRGB_FAST_APPROXIMATION
+//        vec3 linOut = pow(srgbIn.xyz,vec3(2.2));
+//    #else //SRGB_FAST_APPROXIMATION
+//        vec3 bLess = step(vec3(0.04045),srgbIn.xyz);
+//        vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );
+//    #endif //SRGB_FAST_APPROXIMATION
+//        return vec4(linOut,srgbIn.w);
+//#else //MANUAL_SRGB
+    return srgbIn;
+//#endif //MANUAL_SRGB
+}
+
+// Find the normal for this fragment, pulling either from a predefined normal map
+// or from the interpolated mesh normal and tangent attributes.
+vec3 getNormal()
+{
+    // Retrieve the tangent space matrix
+//#ifndef HAS_TANGENTS
+    vec3 pos_dx = dFdx(Position);
+    vec3 pos_dy = dFdy(Position);
+    vec3 tex_dx = dFdx(vec3(FragTexcoord, 0.0));
+    vec3 tex_dy = dFdy(vec3(FragTexcoord, 0.0));
+    vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
+
+#ifdef HAS_NORMALS
+    vec3 ng = normalize(Normal);
+#else
+    vec3 ng = cross(pos_dx, pos_dy);
+#endif
+
+    t = normalize(t - ng * dot(ng, t));
+    vec3 b = normalize(cross(ng, t));
+    mat3 tbn = mat3(t, b, ng);
+//#else // HAS_TANGENTS
+//    mat3 tbn = v_TBN;
+//#endif
+
+#ifdef HAS_NORMALMAP
+    vec3 n = texture2D(uNormalSampler, FragTexcoord).rgb;
+    n = normalize(tbn * ((2.0 * n - 1.0) * vec3(uNormalScale, uNormalScale, 1.0)));
+#else
+    // The tbn matrix is linearly interpolated, so we need to re-normalize
+    vec3 n = normalize(tbn[2].xyz);
+#endif
+
+    return n;
+}
+
+//// Calculation of the lighting contribution from an optional Image Based Light source.
+//// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].
+//// See our README.md on Environment Maps [3] for additional discussion.
+//vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection)
+//{
+//    float mipCount = 9.0; // resolution of 512x512
+//    float lod = (pbrInputs.perceptualRoughness * mipCount);
+//    // retrieve a scale and bias to F0. See [1], Figure 3
+//    vec3 brdf = SRGBtoLINEAR(texture2D(u_brdfLUT, vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
+//    vec3 diffuseLight = SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
+//
+////#ifdef USE_TEX_LOD
+////    vec3 specularLight = SRGBtoLINEAR(textureCubeLodEXT(u_SpecularEnvSampler, reflection, lod)).rgb;
+////#else
+//    vec3 specularLight = SRGBtoLINEAR(textureCube(u_SpecularEnvSampler, reflection)).rgb;
+////#endif
+//
+//    vec3 diffuse = diffuseLight * pbrInputs.diffuseColor;
+//    vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y);
+//
+//    // For presentation, this allows us to disable IBL terms
+//    diffuse *= u_ScaleIBLAmbient.x;
+//    specular *= u_ScaleIBLAmbient.y;
+//
+//    return diffuse + specular;
+//}
+
+// Basic Lambertian diffuse
+// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog
+// See also [1], Equation 1
+vec3 diffuse(PBRInfo pbrInputs)
+{
+    return pbrInputs.diffuseColor / M_PI;
+}
+
+// The following equation models the Fresnel reflectance term of the spec equation (aka F())
+// Implementation of fresnel from [4], Equation 15
+vec3 specularReflection(PBRInfo pbrInputs)
+{
+    return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);
+}
+
+// This calculates the specular geometric attenuation (aka G()),
+// where rougher material will reflect less light back to the viewer.
+// This implementation is based on [1] Equation 4, and we adopt their modifications to
+// alphaRoughness as input as originally proposed in [2].
+float geometricOcclusion(PBRInfo pbrInputs)
+{
+    float NdotL = pbrInputs.NdotL;
+    float NdotV = pbrInputs.NdotV;
+    float r = pbrInputs.alphaRoughness;
+
+    float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));
+    float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));
+    return attenuationL * attenuationV;
+}
+
+// The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D())
+// Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz
+// Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3.
+float microfacetDistribution(PBRInfo pbrInputs)
+{
+    float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
+    float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0;
+    return roughnessSq / (M_PI * f * f);
+}
+
 void main() {
 
+    float perceptualRoughness = uRoughnessFactor;
+    float metallic = uMetallicFactor;
+
+#ifdef HAS_METALROUGHNESSMAP
+    // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
+    // This layout intentionally reserves the 'r' channel for (optional) occlusion map data
+    vec4 mrSample = texture2D(uMetallicRoughnessSampler, FragTexcoord);
+    perceptualRoughness = mrSample.g * perceptualRoughness;
+    metallic = mrSample.b * metallic;
+#endif
+
+    perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
+    metallic = clamp(metallic, 0.0, 1.0);
+    // Roughness is authored as perceptual roughness; as is convention,
+    // convert to material roughness by squaring the perceptual roughness [2].
+    float alphaRoughness = perceptualRoughness * perceptualRoughness;
 
-    // Inverts the fragment normal if not FrontFacing
-    vec3 fragNormal = Normal;
-    if (!gl_FrontFacing) {
-        fragNormal = -fragNormal;
-    }
+    // The albedo may be defined from a base texture or a flat color
+#ifdef HAS_BASECOLORMAP
+    vec4 baseColor = SRGBtoLINEAR(texture2D(uBaseColorSampler, FragTexcoord)) * uBaseColor;
+#else
+    vec4 baseColor = uBaseColor;
+#endif
 
+    vec3 f0 = vec3(0.04);
+    vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);
+    diffuseColor *= 1.0 - metallic;
+    vec3 specularColor = mix(f0, baseColor.rgb, uMetallicFactor);
+
+    // Compute reflectance.
+    float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
+
+    // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect.
+    // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflecance to 0%.
+    float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
+    vec3 specularEnvironmentR0 = specularColor.rgb;
+    vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;
+
+    // TODO These are not currently uniforms - and need to support all kinds of lights!
+    vec3 u_LightColor = vec3(1,1,1);
+    vec3 u_LightDirection = vec3(1,0,0);
+
+    vec3 n = getNormal();                             // normal at surface point
+    vec3 v = normalize(CamDir);                       // Vector from surface point to camera
+    vec3 l = normalize(u_LightDirection);             // Vector from surface point to light
+    vec3 h = normalize(l+v);                          // Half vector between both l and v
+    vec3 reflection = -normalize(reflect(v, n));
+
+    float NdotL = clamp(dot(n, l), 0.001, 1.0);
+    float NdotV = abs(dot(n, v)) + 0.001;
+    float NdotH = clamp(dot(n, h), 0.0, 1.0);
+    float LdotH = clamp(dot(l, h), 0.0, 1.0);
+    float VdotH = clamp(dot(v, h), 0.0, 1.0);
+
+    PBRInfo pbrInputs = PBRInfo(
+        NdotL,
+        NdotV,
+        NdotH,
+        LdotH,
+        VdotH,
+        perceptualRoughness,
+        metallic,
+        specularEnvironmentR0,
+        specularEnvironmentR90,
+        alphaRoughness,
+        diffuseColor,
+        specularColor
+    );
+
+    // Calculate the shading terms for the microfacet specular shading model
+    vec3 F = specularReflection(pbrInputs);
+    float G = geometricOcclusion(pbrInputs);
+    float D = microfacetDistribution(pbrInputs);
+
+    // Calculation of analytical lighting contribution
+    vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);
+    vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV);
+    // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)
+    vec3 color = NdotL * u_LightColor * (diffuseContrib + specContrib);
+
+    // Calculate lighting contribution from image based lighting source (IBL)
+//#ifdef USE_IBL
+//    color += getIBLContribution(pbrInputs, n, reflection);
+//#endif
+
+    // Apply optional PBR terms for additional (optional) shading
+#ifdef HAS_OCCLUSIONMAP
+    float ao = texture2D(uOcclusionSampler, v_UV).r;
+    color = mix(color, color * ao, u_OcclusionStrength);
+#endif
+
+#ifdef HAS_EMISSIVEMAP
+    vec3 emissive = SRGBtoLINEAR(texture2D(u_EmissiveSampler, v_UV)).rgb * u_EmissiveFactor;
+    color += emissive;
+#endif
 
     // Final fragment color
-    FragColor = uBaseColor;
+    FragColor = vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
+
 }
 
 

+ 11 - 10
renderer/shaders/physical_vertex.glsl

@@ -1,5 +1,6 @@
 //
-// Physical maiterial vertex shader
+// Physically Based Shading of a microfacet surface material - Vertex Shader
+// Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
 //
 #include <attributes>
 
@@ -9,7 +10,7 @@ uniform mat3 NormalMatrix;
 uniform mat4 MVP;
 
 // Output variables for Fragment shader
-out vec4 Position;
+out vec3 Position;
 out vec3 Normal;
 out vec3 CamDir;
 out vec2 FragTexcoord;
@@ -17,7 +18,7 @@ out vec2 FragTexcoord;
 void main() {
 
     // Transform this vertex position to camera coordinates.
-    Position = ModelViewMatrix * vec4(VertexPosition, 1.0);
+    Position = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0));
 
     // Transform this vertex normal to camera coordinates.
     Normal = normalize(NormalMatrix * VertexNormal);
@@ -26,13 +27,13 @@ void main() {
     // The camera is at 0,0,0
     CamDir = normalize(-Position.xyz);
 
-//    // Flips texture coordinate Y if requested.
-   vec2 texcoord = VertexTexcoord;
-//#if MAT_TEXTURES>0
-//    if (MatTexFlipY(0)) {
-//        texcoord.y = 1 - texcoord.y;
-//    }
-//#endif
+    // Flips texture coordinate Y if requested.
+    vec2 texcoord = VertexTexcoord;
+    // #if MAT_TEXTURES>0
+    //     if (MatTexFlipY(0)) {
+    //         texcoord.y = 1 - texcoord.y;
+    //     }
+    // #endif
     FragTexcoord = texcoord;
 
     gl_Position = MVP * vec4(VertexPosition, 1.0);

+ 294 - 22
renderer/shaders/sources.go

@@ -508,14 +508,51 @@ void main() {
 `
 
 const physical_fragment_source = `//
-// Physical material fragment shader
+// Physically Based Shading of a microfacet surface material - Fragment Shader
+// Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
 //
+// References:
+// [1] Real Shading in Unreal Engine 4
+//     http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
+// [2] Physically Based Shading at Disney
+//     http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf
+// [3] README.md - Environment Maps
+//     https://github.com/KhronosGroup/glTF-WebGL-PBR/#environment-maps
+// [4] "An Inexpensive BRDF Model for Physically based Rendering" by Christophe Schlick
+//     https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf
+
+//#extension GL_EXT_shader_texture_lod: enable
+//#extension GL_OES_standard_derivatives : enable
+
+precision highp float;
+
+//uniform vec3 u_LightDirection;
+//uniform vec3 u_LightColor;
+
+//#ifdef USE_IBL
+//uniform samplerCube u_DiffuseEnvSampler;
+//uniform samplerCube u_SpecularEnvSampler;
+//uniform sampler2D u_brdfLUT;
+//#endif
 
-// Inputs from vertex shader
-in vec4 Position;       // Vertex position in camera coordinates.
-in vec3 Normal;         // Vertex normal in camera coordinates.
-in vec3 CamDir;         // Direction from vertex to camera
-in vec2 FragTexcoord;
+#ifdef HAS_BASECOLORMAP
+uniform sampler2D u_BaseColorSampler;
+#endif
+#ifdef HAS_NORMALMAP
+uniform sampler2D u_NormalSampler;
+uniform float u_NormalScale;
+#endif
+#ifdef HAS_EMISSIVEMAP
+uniform sampler2D u_EmissiveSampler;
+uniform vec3 u_EmissiveFactor;
+#endif
+#ifdef HAS_METALROUGHNESSMAP
+uniform sampler2D u_MetallicRoughnessSampler;
+#endif
+#ifdef HAS_OCCLUSIONMAP
+uniform sampler2D u_OcclusionSampler;
+uniform float u_OcclusionStrength;
+#endif
 
 // Material parameters uniform array
 uniform vec4 Material[3];
@@ -527,28 +564,263 @@ uniform vec4 Material[3];
 
 #include <lights>
 
+// Inputs from vertex shader
+in vec3 Position;       // Vertex position in camera coordinates.
+in vec3 Normal;         // Vertex normal in camera coordinates.
+in vec3 CamDir;         // Direction from vertex to camera
+in vec2 FragTexcoord;
+
 // Final fragment color
 out vec4 FragColor;
 
+// Encapsulate the various inputs used by the various functions in the shading equation
+// We store values in this struct to simplify the integration of alternative implementations
+// of the shading terms, outlined in the Readme.MD Appendix.
+struct PBRInfo
+{
+    float NdotL;                  // cos angle between normal and light direction
+    float NdotV;                  // cos angle between normal and view direction
+    float NdotH;                  // cos angle between normal and half vector
+    float LdotH;                  // cos angle between light direction and half vector
+    float VdotH;                  // cos angle between view direction and half vector
+    float perceptualRoughness;    // roughness value, as authored by the model creator (input to shader)
+    float metalness;              // metallic value at the surface
+    vec3 reflectance0;            // full reflectance color (normal incidence angle)
+    vec3 reflectance90;           // reflectance color at grazing angle
+    float alphaRoughness;         // roughness mapped to a more linear change in the roughness (proposed by [2])
+    vec3 diffuseColor;            // color contribution from diffuse lighting
+    vec3 specularColor;           // color contribution from specular lighting
+};
+
+const float M_PI = 3.141592653589793;
+const float c_MinRoughness = 0.04;
+
+vec4 SRGBtoLINEAR(vec4 srgbIn) {
+//#ifdef MANUAL_SRGB
+//    #ifdef SRGB_FAST_APPROXIMATION
+//        vec3 linOut = pow(srgbIn.xyz,vec3(2.2));
+//    #else //SRGB_FAST_APPROXIMATION
+//        vec3 bLess = step(vec3(0.04045),srgbIn.xyz);
+//        vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );
+//    #endif //SRGB_FAST_APPROXIMATION
+//        return vec4(linOut,srgbIn.w);
+//#else //MANUAL_SRGB
+    return srgbIn;
+//#endif //MANUAL_SRGB
+}
+
+// Find the normal for this fragment, pulling either from a predefined normal map
+// or from the interpolated mesh normal and tangent attributes.
+vec3 getNormal()
+{
+    // Retrieve the tangent space matrix
+//#ifndef HAS_TANGENTS
+    vec3 pos_dx = dFdx(Position);
+    vec3 pos_dy = dFdy(Position);
+    vec3 tex_dx = dFdx(vec3(FragTexcoord, 0.0));
+    vec3 tex_dy = dFdy(vec3(FragTexcoord, 0.0));
+    vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
+
+#ifdef HAS_NORMALS
+    vec3 ng = normalize(Normal);
+#else
+    vec3 ng = cross(pos_dx, pos_dy);
+#endif
+
+    t = normalize(t - ng * dot(ng, t));
+    vec3 b = normalize(cross(ng, t));
+    mat3 tbn = mat3(t, b, ng);
+//#else // HAS_TANGENTS
+//    mat3 tbn = v_TBN;
+//#endif
+
+#ifdef HAS_NORMALMAP
+    vec3 n = texture2D(uNormalSampler, FragTexcoord).rgb;
+    n = normalize(tbn * ((2.0 * n - 1.0) * vec3(uNormalScale, uNormalScale, 1.0)));
+#else
+    // The tbn matrix is linearly interpolated, so we need to re-normalize
+    vec3 n = normalize(tbn[2].xyz);
+#endif
+
+    return n;
+}
+
+//// Calculation of the lighting contribution from an optional Image Based Light source.
+//// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].
+//// See our README.md on Environment Maps [3] for additional discussion.
+//vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection)
+//{
+//    float mipCount = 9.0; // resolution of 512x512
+//    float lod = (pbrInputs.perceptualRoughness * mipCount);
+//    // retrieve a scale and bias to F0. See [1], Figure 3
+//    vec3 brdf = SRGBtoLINEAR(texture2D(u_brdfLUT, vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
+//    vec3 diffuseLight = SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
+//
+////#ifdef USE_TEX_LOD
+////    vec3 specularLight = SRGBtoLINEAR(textureCubeLodEXT(u_SpecularEnvSampler, reflection, lod)).rgb;
+////#else
+//    vec3 specularLight = SRGBtoLINEAR(textureCube(u_SpecularEnvSampler, reflection)).rgb;
+////#endif
+//
+//    vec3 diffuse = diffuseLight * pbrInputs.diffuseColor;
+//    vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y);
+//
+//    // For presentation, this allows us to disable IBL terms
+//    diffuse *= u_ScaleIBLAmbient.x;
+//    specular *= u_ScaleIBLAmbient.y;
+//
+//    return diffuse + specular;
+//}
+
+// Basic Lambertian diffuse
+// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog
+// See also [1], Equation 1
+vec3 diffuse(PBRInfo pbrInputs)
+{
+    return pbrInputs.diffuseColor / M_PI;
+}
+
+// The following equation models the Fresnel reflectance term of the spec equation (aka F())
+// Implementation of fresnel from [4], Equation 15
+vec3 specularReflection(PBRInfo pbrInputs)
+{
+    return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);
+}
+
+// This calculates the specular geometric attenuation (aka G()),
+// where rougher material will reflect less light back to the viewer.
+// This implementation is based on [1] Equation 4, and we adopt their modifications to
+// alphaRoughness as input as originally proposed in [2].
+float geometricOcclusion(PBRInfo pbrInputs)
+{
+    float NdotL = pbrInputs.NdotL;
+    float NdotV = pbrInputs.NdotV;
+    float r = pbrInputs.alphaRoughness;
+
+    float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));
+    float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));
+    return attenuationL * attenuationV;
+}
+
+// The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D())
+// Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz
+// Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3.
+float microfacetDistribution(PBRInfo pbrInputs)
+{
+    float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
+    float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0;
+    return roughnessSq / (M_PI * f * f);
+}
+
 void main() {
 
+    float perceptualRoughness = uRoughnessFactor;
+    float metallic = uMetallicFactor;
 
-    // Inverts the fragment normal if not FrontFacing
-    vec3 fragNormal = Normal;
-    if (!gl_FrontFacing) {
-        fragNormal = -fragNormal;
-    }
+#ifdef HAS_METALROUGHNESSMAP
+    // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
+    // This layout intentionally reserves the 'r' channel for (optional) occlusion map data
+    vec4 mrSample = texture2D(uMetallicRoughnessSampler, FragTexcoord);
+    perceptualRoughness = mrSample.g * perceptualRoughness;
+    metallic = mrSample.b * metallic;
+#endif
+
+    perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
+    metallic = clamp(metallic, 0.0, 1.0);
+    // Roughness is authored as perceptual roughness; as is convention,
+    // convert to material roughness by squaring the perceptual roughness [2].
+    float alphaRoughness = perceptualRoughness * perceptualRoughness;
+
+    // The albedo may be defined from a base texture or a flat color
+#ifdef HAS_BASECOLORMAP
+    vec4 baseColor = SRGBtoLINEAR(texture2D(uBaseColorSampler, FragTexcoord)) * uBaseColor;
+#else
+    vec4 baseColor = uBaseColor;
+#endif
+
+    vec3 f0 = vec3(0.04);
+    vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);
+    diffuseColor *= 1.0 - metallic;
+    vec3 specularColor = mix(f0, baseColor.rgb, uMetallicFactor);
+
+    // Compute reflectance.
+    float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
+
+    // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect.
+    // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflecance to 0%.
+    float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
+    vec3 specularEnvironmentR0 = specularColor.rgb;
+    vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;
+
+    // TODO These are not currently uniforms - and need to support all kinds of lights!
+    vec3 u_LightColor = vec3(1,1,1);
+    vec3 u_LightDirection = vec3(1,0,0);
+
+    vec3 n = getNormal();                             // normal at surface point
+    vec3 v = normalize(CamDir);                       // Vector from surface point to camera
+    vec3 l = normalize(u_LightDirection);             // Vector from surface point to light
+    vec3 h = normalize(l+v);                          // Half vector between both l and v
+    vec3 reflection = -normalize(reflect(v, n));
+
+    float NdotL = clamp(dot(n, l), 0.001, 1.0);
+    float NdotV = abs(dot(n, v)) + 0.001;
+    float NdotH = clamp(dot(n, h), 0.0, 1.0);
+    float LdotH = clamp(dot(l, h), 0.0, 1.0);
+    float VdotH = clamp(dot(v, h), 0.0, 1.0);
+
+    PBRInfo pbrInputs = PBRInfo(
+        NdotL,
+        NdotV,
+        NdotH,
+        LdotH,
+        VdotH,
+        perceptualRoughness,
+        metallic,
+        specularEnvironmentR0,
+        specularEnvironmentR90,
+        alphaRoughness,
+        diffuseColor,
+        specularColor
+    );
+
+    // Calculate the shading terms for the microfacet specular shading model
+    vec3 F = specularReflection(pbrInputs);
+    float G = geometricOcclusion(pbrInputs);
+    float D = microfacetDistribution(pbrInputs);
+
+    // Calculation of analytical lighting contribution
+    vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);
+    vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV);
+    // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)
+    vec3 color = NdotL * u_LightColor * (diffuseContrib + specContrib);
+
+    // Calculate lighting contribution from image based lighting source (IBL)
+//#ifdef USE_IBL
+//    color += getIBLContribution(pbrInputs, n, reflection);
+//#endif
+
+    // Apply optional PBR terms for additional (optional) shading
+#ifdef HAS_OCCLUSIONMAP
+    float ao = texture2D(uOcclusionSampler, v_UV).r;
+    color = mix(color, color * ao, u_OcclusionStrength);
+#endif
 
+#ifdef HAS_EMISSIVEMAP
+    vec3 emissive = SRGBtoLINEAR(texture2D(u_EmissiveSampler, v_UV)).rgb * u_EmissiveFactor;
+    color += emissive;
+#endif
 
     // Final fragment color
-    FragColor = uBaseColor;
+    FragColor = vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
+
 }
 
 
 `
 
 const physical_vertex_source = `//
-// Physical maiterial vertex shader
+// Physically Based Shading of a microfacet surface material - Vertex Shader
+// Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
 //
 #include <attributes>
 
@@ -558,7 +830,7 @@ uniform mat3 NormalMatrix;
 uniform mat4 MVP;
 
 // Output variables for Fragment shader
-out vec4 Position;
+out vec3 Position;
 out vec3 Normal;
 out vec3 CamDir;
 out vec2 FragTexcoord;
@@ -566,7 +838,7 @@ out vec2 FragTexcoord;
 void main() {
 
     // Transform this vertex position to camera coordinates.
-    Position = ModelViewMatrix * vec4(VertexPosition, 1.0);
+    Position = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0));
 
     // Transform this vertex normal to camera coordinates.
     Normal = normalize(NormalMatrix * VertexNormal);
@@ -575,13 +847,13 @@ void main() {
     // The camera is at 0,0,0
     CamDir = normalize(-Position.xyz);
 
-//    // Flips texture coordinate Y if requested.
-   vec2 texcoord = VertexTexcoord;
-//#if MAT_TEXTURES>0
-//    if (MatTexFlipY(0)) {
-//        texcoord.y = 1 - texcoord.y;
-//    }
-//#endif
+    // Flips texture coordinate Y if requested.
+    vec2 texcoord = VertexTexcoord;
+    // #if MAT_TEXTURES>0
+    //     if (MatTexFlipY(0)) {
+    //         texcoord.y = 1 - texcoord.y;
+    //     }
+    // #endif
     FragTexcoord = texcoord;
 
     gl_Position = MVP * vec4(VertexPosition, 1.0);