Просмотр исходного кода

Merge branch 'master' into gltf

danaugrs 7 лет назад
Родитель
Сommit
3fe10b2826

+ 10 - 6
gls/uniform.go

@@ -25,9 +25,14 @@ func (u *Uniform) Init(name string) {
 	u.lastIndex = -1 // invalid index
 }
 
-// Location returns the location of this uniform for
-// the current shader program
-// The returned location can be -1 if not found
+// Name returns the uniform name.
+func (u *Uniform) Name() string {
+
+	return u.name
+}
+
+// Location returns the location of this uniform for the current shader program.
+// The returned location can be -1 if not found.
 func (u *Uniform) Location(gs *GLS) int32 {
 
 	handle := gs.prog.Handle()
@@ -38,9 +43,8 @@ func (u *Uniform) Location(gs *GLS) int32 {
 	return u.location
 }
 
-// LocationIdx returns the location of this indexed uniform for
-// the current shader program
-// The returned location can be -1 if not found
+// LocationIdx returns the location of this indexed uniform for the current shader program.
+// The returned location can be -1 if not found.
 func (u *Uniform) LocationIdx(gs *GLS, idx int32) int32 {
 
 	if idx != u.lastIndex {

+ 4 - 15
light/spot.go

@@ -17,12 +17,11 @@ type Spot struct {
 	core.Node                // Embedded node
 	color     math32.Color   // Light color
 	intensity float32        // Light intensity
-	direction math32.Vector3 // Direction in world coordinates
 	uni       gls.Uniform    // Uniform location cache
 	udata     struct {       // Combined uniform data in 5 vec3:
 		color          math32.Color   // Light color
 		position       math32.Vector3 // Light position
-		direction      math32.Vector3 // Light position
+		direction      math32.Vector3 // Light direction
 		angularDecay   float32        // Angular decay factor
 		cutoffAngle    float32        // Cut off angle
 		linearDecay    float32        // Distance linear decay
@@ -76,18 +75,6 @@ func (l *Spot) Intensity() float32 {
 	return l.intensity
 }
 
-// SetDirection sets the direction of the spot light in world coordinates
-func (l *Spot) SetDirection(direction *math32.Vector3) {
-
-	l.direction = *direction
-}
-
-// Direction returns the current direction of this spot light in world coordinates
-func (l *Spot) Direction(direction *math32.Vector3) math32.Vector3 {
-
-	return l.direction
-}
-
 // SetCutoffAngle sets the cutoff angle in degrees from 0 to 90
 func (l *Spot) SetCutoffAngle(angle float32) {
 
@@ -150,7 +137,9 @@ func (l *Spot) RenderSetup(gs *gls.GLS, rinfo *core.RenderInfo, idx int) {
 	l.udata.position.Z = pos4.Z
 
 	// Calculates and updates light direction uniform in camera coordinates
-	pos4.SetVector3(&l.direction, 0.0)
+	var dir math32.Vector3
+	l.WorldDirection(&dir)
+	pos4.SetVector3(&dir, 0.0)
 	pos4.ApplyMatrix4(&rinfo.ViewMatrix)
 	l.udata.direction.X = pos4.X
 	l.udata.direction.Y = pos4.Y

+ 35 - 3
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
@@ -77,6 +77,7 @@ type Material struct {
 	lineWidth        float32              // line width for lines and mesh wireframe
 	polyOffsetFactor float32              // polygon offset factor
 	polyOffsetUnits  float32              // polygon offset units
+	defines          map[string]string    // shader defines
 	textures         []*texture.Texture2D // List of textures
 }
 
@@ -232,6 +233,32 @@ func (mat *Material) SetPolygonOffset(factor, units float32) {
 	mat.polyOffsetUnits = units
 }
 
+// SetShaderDefine defines a name with the specified value which are
+// passed to this material shader.
+func (mat *Material) SetShaderDefine(name, value string) {
+
+	if mat.defines == nil {
+		mat.defines = make(map[string]string)
+	}
+	mat.defines[name] = value
+}
+
+// UnsetShaderDefines removes the specified name from the defines which
+// are passed to this material shader.
+func (mat *Material) UnsetShaderDefine(name string) {
+
+	if mat.defines == nil {
+		return
+	}
+	delete(mat.defines, name)
+}
+
+// ShaderDefines returns this material map of shader defines.
+func (mat *Material) ShaderDefines() map[string]string {
+
+	return mat.defines
+}
+
 func (mat *Material) RenderSetup(gs *gls.GLS) {
 
 	// Sets triangle side view mode
@@ -298,8 +325,13 @@ func (mat *Material) RenderSetup(gs *gls.GLS) {
 	}
 
 	// Render textures
-	for idx, tex := range mat.textures {
-		tex.RenderSetup(gs, idx)
+	// Keep track of counts of unique sampler names to correctly index sampler arrays
+	samplerCounts := make(map[string]int)
+	for slotIdx, tex := range mat.textures {
+		samplerName, _ := tex.GetUniformNames()
+		uniIdx, _ := samplerCounts[samplerName]
+		tex.RenderSetup(gs, slotIdx, uniIdx)
+		samplerCounts[samplerName] = uniIdx+1
 	}
 }
 

+ 176 - 0
material/physical.go

@@ -0,0 +1,176 @@
+// Copyright 2016 The G3N Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package material
+
+import (
+	"unsafe"
+
+	"github.com/g3n/engine/gls"
+	"github.com/g3n/engine/math32"
+	"github.com/g3n/engine/texture"
+)
+
+// Physical is a physically based rendered material which uses the metallic-roughness model.
+type Physical struct {
+	Material                                // Embedded material
+	baseColorTex         *texture.Texture2D // Optional base color texture
+	metallicRoughnessTex *texture.Texture2D // Optional metallic-roughness
+	normalTex            *texture.Texture2D // Optional normal texture
+	occlusionTex         *texture.Texture2D // Optional occlusion texture
+	emissiveTex          *texture.Texture2D // Optional emissive texture
+	uni                  gls.Uniform        // Uniform location cache
+	udata                struct {           // Combined uniform data
+		baseColorFactor math32.Color4
+		emissiveFactor  math32.Color4
+		metallicFactor  float32
+		roughnessFactor float32
+	}
+}
+
+// Number of glsl shader vec4 elements used by uniform data
+const physicalVec4Count = 3
+
+// NewPhysical creates and returns a pointer to a new Physical material.
+func NewPhysical() *Physical {
+
+	m := new(Physical)
+	m.Material.Init()
+	m.SetShader("physical")
+
+	// 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, 1}
+	m.udata.metallicFactor = 1
+	m.udata.roughnessFactor = 1
+	return m
+}
+
+// SetBaseColorFactor sets this material base color.
+// Its default value is {1,1,1,1}.
+// Returns pointer to this updated material.
+func (m *Physical) SetBaseColorFactor(c *math32.Color4) *Physical {
+
+	m.udata.baseColorFactor = *c
+	return m
+}
+
+// SetMetallicFactor sets this material metallic factor.
+// Its default value is 1.
+// Returns pointer to this updated material.
+func (m *Physical) SetMetallicFactor(v float32) *Physical {
+
+	m.udata.metallicFactor = v
+	return m
+}
+
+// SetRoughnessFactor sets this material roughness factor.
+// Its default value is 1.
+// Returns pointer to this updated material.
+func (m *Physical) SetRoughnessFactor(v float32) *Physical {
+
+	m.udata.roughnessFactor = v
+	return m
+}
+
+// SetEmissiveFactor sets the emissive color of the material.
+// Its default is {1, 1, 1}.
+// Returns pointer to this updated material.
+func (m *Physical) SetEmissiveFactor(c *math32.Color) *Physical {
+
+	m.udata.emissiveFactor.R = c.R
+	m.udata.emissiveFactor.G = c.G
+	m.udata.emissiveFactor.B = c.B
+	return m
+}
+
+// SetBaseColorMap sets this material optional texture base color.
+// Returns pointer to this updated material.
+func (m *Physical) SetBaseColorMap(tex *texture.Texture2D) *Physical {
+
+	m.baseColorTex = tex
+	if m.baseColorTex != nil {
+		m.baseColorTex.SetUniformNames("uBaseColorSampler", "uBaseColorTexParams")
+		m.SetShaderDefine("HAS_BASECOLORMAP", "")
+		m.AddTexture(m.baseColorTex)
+	} else {
+		m.UnsetShaderDefine("HAS_BASECOLORMAP")
+		m.RemoveTexture(m.baseColorTex)
+	}
+	return m
+}
+
+// SetMetallicRoughnessMap sets this material optional metallic-roughness texture.
+// Returns pointer to this updated material.
+func (m *Physical) SetMetallicRoughnessMap(tex *texture.Texture2D) *Physical {
+
+	m.metallicRoughnessTex = tex
+	if m.metallicRoughnessTex != nil {
+		m.metallicRoughnessTex.SetUniformNames("uMetallicRoughnessSampler", "uMetallicRoughnessTexParams")
+		m.SetShaderDefine("HAS_METALROUGHNESSMAP", "")
+		m.AddTexture(m.metallicRoughnessTex)
+	} else {
+		m.UnsetShaderDefine("HAS_METALROUGHNESSMAP")
+		m.RemoveTexture(m.metallicRoughnessTex)
+	}
+	return m
+}
+
+// TODO add SetNormalMap (and SetSpecularMap) to StandardMaterial.
+// SetNormalMap sets this material optional normal texture.
+// Returns pointer to this updated material.
+func (m *Physical) SetNormalMap(tex *texture.Texture2D) *Physical {
+
+	m.normalTex = tex
+	if m.normalTex != nil {
+		m.normalTex.SetUniformNames("uNormalSampler", "uNormalTexParams")
+		m.SetShaderDefine("HAS_NORMALMAP", "")
+		m.AddTexture(m.normalTex)
+	} else {
+		m.UnsetShaderDefine("HAS_NORMALMAP")
+		m.RemoveTexture(m.normalTex)
+	}
+	return m
+}
+
+// SetOcclusionMap sets this material optional occlusion texture.
+// Returns pointer to this updated material.
+func (m *Physical) SetOcclusionMap(tex *texture.Texture2D) *Physical {
+
+	m.occlusionTex = tex
+	if m.occlusionTex != nil {
+		m.occlusionTex.SetUniformNames("uOcclusionSampler", "uOcclusionTexParams")
+		m.SetShaderDefine("HAS_OCCLUSIONMAP", "")
+		m.AddTexture(m.occlusionTex)
+	} else {
+		m.UnsetShaderDefine("HAS_OCCLUSIONMAP")
+		m.RemoveTexture(m.occlusionTex)
+	}
+	return m
+}
+
+// SetEmissiveMap sets this material optional emissive texture.
+// Returns pointer to this updated material.
+func (m *Physical) SetEmissiveMap(tex *texture.Texture2D) *Physical {
+
+	m.emissiveTex = tex
+	if m.emissiveTex != nil {
+		m.emissiveTex.SetUniformNames("uEmissiveSampler", "uEmissiveTexParams")
+		m.SetShaderDefine("HAS_EMISSIVEMAP", "")
+		m.AddTexture(m.emissiveTex)
+	} else {
+		m.UnsetShaderDefine("HAS_EMISSIVEMAP")
+		m.RemoveTexture(m.emissiveTex)
+	}
+	return m
+}
+
+// RenderSetup transfer this material uniforms and textures to the shader
+func (m *Physical) RenderSetup(gl *gls.GLS) {
+
+	m.Material.RenderSetup(gl)
+	location := m.uni.Location(gl)
+	gl.Uniform4fvUP(location, physicalVec4Count, unsafe.Pointer(&m.udata))
+}

+ 1 - 0
renderer/renderer.go

@@ -364,6 +364,7 @@ func (r *Renderer) renderScene(iscene core.INode, icam camera.ICamera) error {
 			r.specs.ShaderUnique = mat.ShaderUnique()
 			r.specs.UseLights = mat.UseLights()
 			r.specs.MatTexturesMax = mat.TextureCount()
+			r.specs.Defines = mat.ShaderDefines()
 			_, err = r.shaman.SetProgram(&r.specs)
 			if err != nil {
 				return

+ 7 - 0
renderer/shaders/include/material.glsl

@@ -41,3 +41,10 @@ uniform vec3 Material[6];
         }                                                                                    \
     }
 
+// TODO for alpha blending dont use mix use implementation below (similar to one in panel shader)
+            //vec4 prevTexPre = texMixed;                                                      \
+            //prevTexPre.rgb *= prevTexPre.a;                                                  \
+            //vec4 currTexPre = texColor;                                                      \
+            //currTexPre.rgb *= currTexPre.a;                                                  \
+            //texMixed = currTexPre + prevTexPre * (1 - currTexPre.a);                         \
+            //texMixed.rgb /= texMixed.a;                                                      \

+ 415 - 0
renderer/shaders/physical_fragment.glsl

@@ -0,0 +1,415 @@
+//
+// 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
+
+#ifdef HAS_BASECOLORMAP
+uniform sampler2D uBaseColorSampler;
+#endif
+#ifdef HAS_METALROUGHNESSMAP
+uniform sampler2D uMetallicRoughnessSampler;
+#endif
+#ifdef HAS_NORMALMAP
+uniform sampler2D uNormalSampler;
+//uniform float uNormalScale;
+#endif
+#ifdef HAS_EMISSIVEMAP
+uniform sampler2D uEmissiveSampler;
+#endif
+#ifdef HAS_OCCLUSIONMAP
+uniform sampler2D uOcclusionSampler;
+uniform float uOcclusionStrength;
+#endif
+
+// Material parameters uniform array
+uniform vec4 Material[3];
+// Macros to access elements inside the Material array
+#define uBaseColor		    Material[0]
+#define uEmissiveColor      Material[1]
+#define uMetallicFactor     Material[2].x
+#define uRoughnessFactor    Material[2].y
+
+#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 PBRLightInfo
+{
+    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
+};
+
+struct PBRInfo
+{
+    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
+    float uNormalScale = 1.0;
+    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, PBRLightInfo pbrLight, 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 = vec3(0.5,0.5,0.5);//SRGBtoLINEAR(texture2D(u_brdfLUT, vec2(pbrLight.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
+    vec3 diffuseLight = vec3(0.5,0.5,0.5);//SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
+
+//#ifdef USE_TEX_LOD
+//    vec3 specularLight = SRGBtoLINEAR(textureCubeLodEXT(u_SpecularEnvSampler, reflection, lod)).rgb;
+//#else
+    vec3 specularLight = vec3(0.5,0.5,0.5);//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, PBRLightInfo pbrLight)
+{
+    return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrLight.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, PBRLightInfo pbrLight)
+{
+    float NdotL = pbrLight.NdotL;
+    float NdotV = pbrLight.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, PBRLightInfo pbrLight)
+{
+    float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
+    float f = (pbrLight.NdotH * roughnessSq - pbrLight.NdotH) * pbrLight.NdotH + 1.0;
+    return roughnessSq / (M_PI * f * f);
+}
+
+vec3 pbrModel(PBRInfo pbrInputs, vec3 lightColor, vec3 lightDir) {
+
+    vec3 n = getNormal();                             // normal at surface point
+    vec3 v = normalize(CamDir);                       // Vector from surface point to camera
+    vec3 l = normalize(lightDir);                     // 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);
+
+    PBRLightInfo pbrLight = PBRLightInfo(
+        NdotL,
+        NdotV,
+        NdotH,
+        LdotH,
+        VdotH
+    );
+
+    // Calculate the shading terms for the microfacet specular shading model
+    vec3 F = specularReflection(pbrInputs, pbrLight);
+    float G = geometricOcclusion(pbrInputs, pbrLight);
+    float D = microfacetDistribution(pbrInputs, pbrLight);
+
+    // 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 * lightColor * (diffuseContrib + specContrib);
+
+    return color;
+}
+
+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;
+
+    // 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 reflectance 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;
+
+    PBRInfo pbrInputs = PBRInfo(
+        perceptualRoughness,
+        metallic,
+        specularEnvironmentR0,
+        specularEnvironmentR90,
+        alphaRoughness,
+        diffuseColor,
+        specularColor
+    );
+
+//    vec3 normal = getNormal();
+    vec3 color = vec3(0.0);
+
+#if AMB_LIGHTS>0
+    // Ambient lights
+    for (int i = 0; i < AMB_LIGHTS; i++) {
+        color += AmbientLightColor[i] * pbrInputs.diffuseColor;
+    }
+#endif
+
+#if DIR_LIGHTS>0
+    // Directional lights
+    for (int i = 0; i < DIR_LIGHTS; i++) {
+        // Diffuse reflection
+        // DirLightPosition is the direction of the current light
+        vec3 lightDirection = normalize(DirLightPosition(i));
+        // PBR
+        color += pbrModel(pbrInputs, DirLightColor(i), lightDirection);
+    }
+#endif
+
+#if POINT_LIGHTS>0
+    // Point lights
+    for (int i = 0; i < POINT_LIGHTS; i++) {
+        // Common calculations
+        // Calculates the direction and distance from the current vertex to this point light.
+        vec3 lightDirection = PointLightPosition(i) - vec3(Position);
+        float lightDistance = length(lightDirection);
+        // Normalizes the lightDirection
+        lightDirection = lightDirection / lightDistance;
+        // Calculates the attenuation due to the distance of the light
+        float attenuation = 1.0 / (1.0 + PointLightLinearDecay(i) * lightDistance +
+            PointLightQuadraticDecay(i) * lightDistance * lightDistance);
+        vec3 attenuatedColor = PointLightColor(i) * attenuation;
+        // PBR
+        color += pbrModel(pbrInputs, attenuatedColor, lightDirection);
+    }
+#endif
+
+#if SPOT_LIGHTS>0
+    for (int i = 0; i < SPOT_LIGHTS; i++) {
+
+        // Calculates the direction and distance from the current vertex to this spot light.
+        vec3 lightDirection = SpotLightPosition(i) - vec3(Position);
+        float lightDistance = length(lightDirection);
+        lightDirection = lightDirection / lightDistance;
+
+        // Calculates the attenuation due to the distance of the light
+        float attenuation = 1.0 / (1.0 + SpotLightLinearDecay(i) * lightDistance +
+            SpotLightQuadraticDecay(i) * lightDistance * lightDistance);
+
+        // Calculates the angle between the vertex direction and spot direction
+        // If this angle is greater than the cutoff the spotlight will not contribute
+        // to the final color.
+        float angle = acos(dot(-lightDirection, SpotLightDirection(i)));
+        float cutoff = radians(clamp(SpotLightCutoffAngle(i), 0.0, 90.0));
+
+        if (angle < cutoff) {
+            float spotFactor = pow(dot(-lightDirection, SpotLightDirection(i)), SpotLightAngularDecay(i));
+            vec3 attenuatedColor = SpotLightColor(i) * attenuation * spotFactor;
+            // PBR
+            color += pbrModel(pbrInputs, attenuatedColor, lightDirection);
+        }
+    }
+#endif
+
+    // 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, FragTexcoord).r;
+    color = mix(color, color * ao, 1.0);//, uOcclusionStrength);
+#endif
+
+#ifdef HAS_EMISSIVEMAP
+    vec3 emissive = SRGBtoLINEAR(texture2D(uEmissiveSampler, FragTexcoord)).rgb * vec3(uEmissiveColor);
+#else
+    vec3 emissive = vec3(uEmissiveColor);
+#endif
+    color += emissive;
+
+    // Base Color
+//    FragColor = baseColor;
+
+    // Normal
+//    FragColor = vec4(n, 1.0);
+
+    // Emissive Color
+//    FragColor = vec4(emissive, 1.0);
+
+    // F
+//    color = F;
+
+    // G
+//    color = vec3(G);
+
+    // D
+//    color = vec3(D);
+
+    // Specular
+//    color = specContrib;
+
+    // Diffuse
+//    color = diffuseContrib;
+
+    // Roughness
+//    color = vec3(perceptualRoughness);
+
+    // Metallic
+//    color = vec3(metallic);
+
+    // Final fragment color
+    FragColor = vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
+}
+
+

+ 42 - 0
renderer/shaders/physical_vertex.glsl

@@ -0,0 +1,42 @@
+//
+// Physically Based Shading of a microfacet surface material - Vertex Shader
+// Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
+//
+#include <attributes>
+
+// Model uniforms
+uniform mat4 ModelViewMatrix;
+uniform mat3 NormalMatrix;
+uniform mat4 MVP;
+
+// Output variables for Fragment shader
+out vec3 Position;
+out vec3 Normal;
+out vec3 CamDir;
+out vec2 FragTexcoord;
+
+void main() {
+
+    // Transform this vertex position to camera coordinates.
+    Position = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0));
+
+    // Transform this vertex normal to camera coordinates.
+    Normal = normalize(NormalMatrix * VertexNormal);
+
+    // Calculate the direction vector from the vertex to the camera
+    // 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
+    FragTexcoord = texcoord;
+
+    gl_Position = MVP * vec4(VertexPosition, 1.0);
+}
+
+

+ 471 - 0
renderer/shaders/sources.go

@@ -103,6 +103,13 @@ uniform vec3 Material[6];
         }                                                                                    \
     }
 
+// TODO for alpha blending dont use mix use implementation below (similar to one in panel shader)
+            //vec4 prevTexPre = texMixed;                                                      \
+            //prevTexPre.rgb *= prevTexPre.a;                                                  \
+            //vec4 currTexPre = texColor;                                                      \
+            //currTexPre.rgb *= currTexPre.a;                                                  \
+            //texMixed = currTexPre + prevTexPre * (1 - currTexPre.a);                         \
+            //texMixed.rgb /= texMixed.a;                                                      \
 `
 
 const include_phong_model_source = `/***
@@ -505,6 +512,467 @@ void main() {
     gl_Position = MVP * vec4(VertexPosition, 1.0);
 }
 
+`
+
+const physical_fragment_source = `//
+// 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
+
+#ifdef HAS_BASECOLORMAP
+uniform sampler2D uBaseColorSampler;
+#endif
+#ifdef HAS_METALROUGHNESSMAP
+uniform sampler2D uMetallicRoughnessSampler;
+#endif
+#ifdef HAS_NORMALMAP
+uniform sampler2D uNormalSampler;
+//uniform float uNormalScale;
+#endif
+#ifdef HAS_EMISSIVEMAP
+uniform sampler2D uEmissiveSampler;
+#endif
+#ifdef HAS_OCCLUSIONMAP
+uniform sampler2D uOcclusionSampler;
+uniform float uOcclusionStrength;
+#endif
+
+// Material parameters uniform array
+uniform vec4 Material[3];
+// Macros to access elements inside the Material array
+#define uBaseColor		    Material[0]
+#define uEmissiveColor      Material[1]
+#define uMetallicFactor     Material[2].x
+#define uRoughnessFactor    Material[2].y
+
+#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 PBRLightInfo
+{
+    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
+};
+
+struct PBRInfo
+{
+    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
+    float uNormalScale = 1.0;
+    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, PBRLightInfo pbrLight, 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 = vec3(0.5,0.5,0.5);//SRGBtoLINEAR(texture2D(u_brdfLUT, vec2(pbrLight.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
+    vec3 diffuseLight = vec3(0.5,0.5,0.5);//SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
+
+//#ifdef USE_TEX_LOD
+//    vec3 specularLight = SRGBtoLINEAR(textureCubeLodEXT(u_SpecularEnvSampler, reflection, lod)).rgb;
+//#else
+    vec3 specularLight = vec3(0.5,0.5,0.5);//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, PBRLightInfo pbrLight)
+{
+    return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrLight.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, PBRLightInfo pbrLight)
+{
+    float NdotL = pbrLight.NdotL;
+    float NdotV = pbrLight.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, PBRLightInfo pbrLight)
+{
+    float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
+    float f = (pbrLight.NdotH * roughnessSq - pbrLight.NdotH) * pbrLight.NdotH + 1.0;
+    return roughnessSq / (M_PI * f * f);
+}
+
+vec3 pbrModel(PBRInfo pbrInputs, vec3 lightColor, vec3 lightDir) {
+
+    vec3 n = getNormal();                             // normal at surface point
+    vec3 v = normalize(CamDir);                       // Vector from surface point to camera
+    vec3 l = normalize(lightDir);                     // 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);
+
+    PBRLightInfo pbrLight = PBRLightInfo(
+        NdotL,
+        NdotV,
+        NdotH,
+        LdotH,
+        VdotH
+    );
+
+    // Calculate the shading terms for the microfacet specular shading model
+    vec3 F = specularReflection(pbrInputs, pbrLight);
+    float G = geometricOcclusion(pbrInputs, pbrLight);
+    float D = microfacetDistribution(pbrInputs, pbrLight);
+
+    // 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 * lightColor * (diffuseContrib + specContrib);
+
+    return color;
+}
+
+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;
+
+    // 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 reflectance 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;
+
+    PBRInfo pbrInputs = PBRInfo(
+        perceptualRoughness,
+        metallic,
+        specularEnvironmentR0,
+        specularEnvironmentR90,
+        alphaRoughness,
+        diffuseColor,
+        specularColor
+    );
+
+//    vec3 normal = getNormal();
+    vec3 color = vec3(0.0);
+
+#if AMB_LIGHTS>0
+    // Ambient lights
+    for (int i = 0; i < AMB_LIGHTS; i++) {
+        color += AmbientLightColor[i] * pbrInputs.diffuseColor;
+    }
+#endif
+
+#if DIR_LIGHTS>0
+    // Directional lights
+    for (int i = 0; i < DIR_LIGHTS; i++) {
+        // Diffuse reflection
+        // DirLightPosition is the direction of the current light
+        vec3 lightDirection = normalize(DirLightPosition(i));
+        // PBR
+        color += pbrModel(pbrInputs, DirLightColor(i), lightDirection);
+    }
+#endif
+
+#if POINT_LIGHTS>0
+    // Point lights
+    for (int i = 0; i < POINT_LIGHTS; i++) {
+        // Common calculations
+        // Calculates the direction and distance from the current vertex to this point light.
+        vec3 lightDirection = PointLightPosition(i) - vec3(Position);
+        float lightDistance = length(lightDirection);
+        // Normalizes the lightDirection
+        lightDirection = lightDirection / lightDistance;
+        // Calculates the attenuation due to the distance of the light
+        float attenuation = 1.0 / (1.0 + PointLightLinearDecay(i) * lightDistance +
+            PointLightQuadraticDecay(i) * lightDistance * lightDistance);
+        vec3 attenuatedColor = PointLightColor(i) * attenuation;
+        // PBR
+        color += pbrModel(pbrInputs, attenuatedColor, lightDirection);
+    }
+#endif
+
+#if SPOT_LIGHTS>0
+    for (int i = 0; i < SPOT_LIGHTS; i++) {
+
+        // Calculates the direction and distance from the current vertex to this spot light.
+        vec3 lightDirection = SpotLightPosition(i) - vec3(Position);
+        float lightDistance = length(lightDirection);
+        lightDirection = lightDirection / lightDistance;
+
+        // Calculates the attenuation due to the distance of the light
+        float attenuation = 1.0 / (1.0 + SpotLightLinearDecay(i) * lightDistance +
+            SpotLightQuadraticDecay(i) * lightDistance * lightDistance);
+
+        // Calculates the angle between the vertex direction and spot direction
+        // If this angle is greater than the cutoff the spotlight will not contribute
+        // to the final color.
+        float angle = acos(dot(-lightDirection, SpotLightDirection(i)));
+        float cutoff = radians(clamp(SpotLightCutoffAngle(i), 0.0, 90.0));
+
+        if (angle < cutoff) {
+            float spotFactor = pow(dot(-lightDirection, SpotLightDirection(i)), SpotLightAngularDecay(i));
+            vec3 attenuatedColor = SpotLightColor(i) * attenuation * spotFactor;
+            // PBR
+            color += pbrModel(pbrInputs, attenuatedColor, lightDirection);
+        }
+    }
+#endif
+
+    // 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, FragTexcoord).r;
+    color = mix(color, color * ao, 1.0);//, uOcclusionStrength);
+#endif
+
+#ifdef HAS_EMISSIVEMAP
+    vec3 emissive = SRGBtoLINEAR(texture2D(uEmissiveSampler, FragTexcoord)).rgb * vec3(uEmissiveColor);
+#else
+    vec3 emissive = vec3(uEmissiveColor);
+#endif
+    color += emissive;
+
+    // Base Color
+//    FragColor = baseColor;
+
+    // Normal
+//    FragColor = vec4(n, 1.0);
+
+    // Emissive Color
+//    FragColor = vec4(emissive, 1.0);
+
+    // F
+//    color = F;
+
+    // G
+//    color = vec3(G);
+
+    // D
+//    color = vec3(D);
+
+    // Specular
+//    color = specContrib;
+
+    // Diffuse
+//    color = diffuseContrib;
+
+    // Roughness
+//    color = vec3(perceptualRoughness);
+
+    // Metallic
+//    color = vec3(metallic);
+
+    // Final fragment color
+    FragColor = vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
+}
+
+
+`
+
+const physical_vertex_source = `//
+// Physically Based Shading of a microfacet surface material - Vertex Shader
+// Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
+//
+#include <attributes>
+
+// Model uniforms
+uniform mat4 ModelViewMatrix;
+uniform mat3 NormalMatrix;
+uniform mat4 MVP;
+
+// Output variables for Fragment shader
+out vec3 Position;
+out vec3 Normal;
+out vec3 CamDir;
+out vec2 FragTexcoord;
+
+void main() {
+
+    // Transform this vertex position to camera coordinates.
+    Position = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0));
+
+    // Transform this vertex normal to camera coordinates.
+    Normal = normalize(NormalMatrix * VertexNormal);
+
+    // Calculate the direction vector from the vertex to the camera
+    // 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
+    FragTexcoord = texcoord;
+
+    gl_Position = MVP * vec4(VertexPosition, 1.0);
+}
+
+
 `
 
 const point_fragment_source = `#include <material>
@@ -769,6 +1237,8 @@ var shaderMap = map[string]string{
 	"panel_vertex":      panel_vertex_source,
 	"phong_fragment":    phong_fragment_source,
 	"phong_vertex":      phong_vertex_source,
+	"physical_fragment": physical_fragment_source,
+	"physical_vertex":   physical_vertex_source,
 	"point_fragment":    point_fragment_source,
 	"point_vertex":      point_vertex_source,
 	"sprite_fragment":   sprite_fragment_source,
@@ -783,6 +1253,7 @@ var programMap = map[string]ProgramInfo{
 	"basic":    {"basic_vertex", "basic_fragment", ""},
 	"panel":    {"panel_vertex", "panel_fragment", ""},
 	"phong":    {"phong_vertex", "phong_fragment", ""},
+	"physical": {"physical_vertex", "physical_fragment", ""},
 	"point":    {"point_vertex", "point_fragment", ""},
 	"sprite":   {"sprite_vertex", "sprite_fragment", ""},
 	"standard": {"standard_vertex", "standard_fragment", ""},

+ 48 - 5
renderer/shaman.go

@@ -34,6 +34,7 @@ type ShaderSpecs struct {
 	PointLightsMax   int                // Current Number of point lights
 	SpotLightsMax    int                // Current Number of spot lights
 	MatTexturesMax   int                // Current Number of material textures
+	Defines          map[string]string  // Additional shader defines
 }
 
 // ProgSpecs represents a compiled shader program along with its specs
@@ -122,7 +123,8 @@ func (sm *Shaman) AddProgram(name, vertexName, fragName string, others ...string
 func (sm *Shaman) SetProgram(s *ShaderSpecs) (bool, error) {
 
 	// Checks material use lights bit mask
-	specs := *s
+	var specs ShaderSpecs
+	specs.copy(s)
 	if (specs.UseLights & material.UseLightAmbient) == 0 {
 		specs.AmbientLightsMax = 0
 	}
@@ -137,13 +139,13 @@ func (sm *Shaman) SetProgram(s *ShaderSpecs) (bool, error) {
 	}
 
 	// If current shader specs are the same as the specified specs, nothing to do.
-	if sm.specs.Compare(&specs) {
+	if sm.specs.compare(&specs) {
 		return false, nil
 	}
 
 	// Search for compiled program with the specified specs
 	for _, pinfo := range sm.programs {
-		if pinfo.specs.Compare(&specs) {
+		if pinfo.specs.compare(&specs) {
 			sm.gs.UseProgram(pinfo.program)
 			sm.specs = specs
 			return true, nil
@@ -181,6 +183,10 @@ func (sm *Shaman) GenProgram(specs *ShaderSpecs) (*gls.Program, error) {
 	defines["POINT_LIGHTS"] = strconv.FormatUint(uint64(specs.PointLightsMax), 10)
 	defines["SPOT_LIGHTS"] = strconv.FormatUint(uint64(specs.SpotLightsMax), 10)
 	defines["MAT_TEXTURES"] = strconv.FormatUint(uint64(specs.MatTexturesMax), 10)
+	// Adds additional material defines from the specs parameter
+	for name, value := range specs.Defines {
+		defines[name] = value
+	}
 
 	// Get vertex shader source
 	vertexSource, ok := sm.shadersm[progInfo.Vertex]
@@ -232,6 +238,7 @@ func (sm *Shaman) GenProgram(specs *ShaderSpecs) (*gls.Program, error) {
 	if err != nil {
 		return nil, err
 	}
+
 	return prog, nil
 }
 
@@ -279,8 +286,20 @@ func (sm *Shaman) preprocess(source string, defines map[string]string) (string,
 	return prefix + newSource, nil
 }
 
+// copy copies other spec into this
+func (ss *ShaderSpecs) copy(other *ShaderSpecs) {
+
+	*ss = *other
+	if other.Defines != nil {
+		ss.Defines = make(map[string]string)
+		for k, v := range other.Defines {
+			ss.Defines[k] = v
+		}
+	}
+}
+
 // Compare compares two shaders specifications structures
-func (ss *ShaderSpecs) Compare(other *ShaderSpecs) bool {
+func (ss *ShaderSpecs) compare(other *ShaderSpecs) bool {
 
 	if ss.Name != other.Name {
 		return false
@@ -292,8 +311,32 @@ func (ss *ShaderSpecs) Compare(other *ShaderSpecs) bool {
 		ss.DirLightsMax == other.DirLightsMax &&
 		ss.PointLightsMax == other.PointLightsMax &&
 		ss.SpotLightsMax == other.SpotLightsMax &&
-		ss.MatTexturesMax == other.MatTexturesMax {
+		ss.MatTexturesMax == other.MatTexturesMax &&
+		ss.compareDefines(other) {
+		return true
+	}
+	return false
+}
+
+// compareDefines compares two shaders specification define maps.
+func (ss *ShaderSpecs) compareDefines(other *ShaderSpecs) bool {
+
+	if ss.Defines == nil && other.Defines == nil {
+		return true
+	}
+	if ss.Defines != nil && other.Defines != nil {
+		if len(ss.Defines) != len(other.Defines) {
+			return false
+		}
+		for k, _ := range ss.Defines {
+			v1, ok1 := ss.Defines[k]
+			v2, ok2 := other.Defines[k]
+			if v1 != v2 || ok1 != ok2 {
+				return false
+			}
+		}
 		return true
 	}
+	// One is nil and the other is not nil
 	return false
 }

+ 27 - 12
texture/texture2D.go

@@ -54,7 +54,7 @@ func newTexture2D() *Texture2D {
 	t.refcount = 1
 	t.texname = 0
 	t.magFilter = gls.LINEAR
-	t.minFilter = gls.LINEAR
+	t.minFilter = gls.LINEAR_MIPMAP_LINEAR
 	t.wrapS = gls.CLAMP_TO_EDGE
 	t.wrapT = gls.CLAMP_TO_EDGE
 	t.updateData = false
@@ -128,6 +128,19 @@ func (t *Texture2D) Dispose() {
 	}
 }
 
+// SetUniformNames sets the names of the uniforms in the shader for sampler and texture info.
+func (t *Texture2D) SetUniformNames(sampler, info string) {
+
+	t.uniUnit.Init(sampler)
+	t.uniInfo.Init(info)
+}
+
+// GetUniformNames returns the names of the uniforms in the shader for sampler and texture info.
+func (t *Texture2D) GetUniformNames() (sampler, info string) {
+
+	return t.uniUnit.Name(), t.uniInfo.Name()
+}
+
 // SetImage sets a new image for this texture
 func (t *Texture2D) SetImage(imgfile string) error {
 
@@ -292,7 +305,7 @@ func DecodeImage(imgfile string) (*image.RGBA, error) {
 }
 
 // RenderSetup is called by the material render setup
-func (t *Texture2D) RenderSetup(gs *gls.GLS, idx int) {
+func (t *Texture2D) RenderSetup(gs *gls.GLS, slotIdx, uniIdx int) { // Could have as input - TEXTURE0 (slot) and uni location
 
 	// One time initialization
 	if t.gs == nil {
@@ -300,11 +313,12 @@ func (t *Texture2D) RenderSetup(gs *gls.GLS, idx int) {
 		t.gs = gs
 	}
 
+	// Sets the texture unit for this texture
+	gs.ActiveTexture(uint32(gls.TEXTURE0 + slotIdx))
+	gs.BindTexture(gls.TEXTURE_2D, t.texname)
+
 	// Transfer texture data to OpenGL if necessary
 	if t.updateData {
-		// Sets the texture unit for this texture
-		gs.ActiveTexture(uint32(gls.TEXTURE0 + idx))
-		gs.BindTexture(gls.TEXTURE_2D, t.texname)
 		gs.TexImage2D(
 			gls.TEXTURE_2D, // texture type
 			0,              // level of detail
@@ -324,10 +338,6 @@ func (t *Texture2D) RenderSetup(gs *gls.GLS, idx int) {
 		t.updateData = false
 	}
 
-	// Sets the texture unit for this texture
-	gs.ActiveTexture(uint32(gls.TEXTURE0 + idx))
-	gs.BindTexture(gls.TEXTURE_2D, t.texname)
-
 	// Sets texture parameters if needed
 	if t.updateParams {
 		gs.TexParameteri(gls.TEXTURE_2D, gls.TEXTURE_MAG_FILTER, int32(t.magFilter))
@@ -338,11 +348,16 @@ func (t *Texture2D) RenderSetup(gs *gls.GLS, idx int) {
 	}
 
 	// Transfer texture unit uniform
-	location := t.uniUnit.LocationIdx(gs, int32(idx))
-	gs.Uniform1i(location, int32(idx))
+	var location int32
+	if uniIdx == 0 {
+		location = t.uniUnit.Location(gs)
+	} else {
+		location = t.uniUnit.LocationIdx(gs, int32(uniIdx))
+	}
+	gs.Uniform1i(location, int32(slotIdx))
 
 	// Transfer texture info combined uniform
 	const vec2count = 3
-	location = t.uniInfo.LocationIdx(gs, vec2count*int32(idx))
+	location = t.uniInfo.LocationIdx(gs, vec2count*int32(uniIdx))
 	gs.Uniform2fvUP(location, vec2count, unsafe.Pointer(&t.udata))
 }