浏览代码

simplify shader to hell and ability to have one material per scene or per object

/batch_rendering
Arnaud Carre 8 年前
当前提交
a98e1734
共有 8 个文件被更改,包括 259 次插入132 次删除
  1. 24
      Assets/BasicRenderBatching/BasicBatching.unity
  2. 134
      Assets/BasicRenderBatching/BasicRenderBatchingShader.shader
  3. 27
      Assets/BasicRenderBatching/Scripts/PopulateScene.cs
  4. 2
      ProjectSettings/ProjectSettings.asset
  5. 74
      Assets/BasicRenderBatching/BasicMat_ColorsFlat.mat
  6. 8
      Assets/BasicRenderBatching/BasicMat_ColorsFlat.mat.meta
  7. 110
      Assets/BasicRenderBatching/Scripts/MiniProfiler.cs
  8. 12
      Assets/BasicRenderBatching/Scripts/MiniProfiler.cs.meta

24
Assets/BasicRenderBatching/BasicBatching.unity


m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.18028378, g: 0.22571412, b: 0.30692285, a: 1}
m_IndirectSpecularColor: {r: 0.18323539, g: 0.22689644, b: 0.29487598, a: 1}
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0

m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 431751544}
m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}
m_LocalRotation: {x: 0.30016837, y: 0.23065634, z: 0.29749814, w: 0.8764653}
m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}
m_LocalEulerAnglesHint: {x: 22.888, y: 39.253002, z: 45.755}
--- !u!1 &870320112
GameObject:
m_ObjectHideFlags: 0

- component: {fileID: 870320114}
- component: {fileID: 870320113}
- component: {fileID: 870320118}
- component: {fileID: 870320119}
m_Layer: 0
m_Name: Main Camera
m_TagString: MainCamera

m_ObjectPrefab: {fileID: 1877103646185790, guid: b764b667902787f459cc591ec15679db,
type: 2}
m_CenterPoint: {fileID: 970523335}
m_GridWidth: 64
m_Spacing: 0.7
m_Material: {fileID: 2100000, guid: 4c676c131a81b634988506c3023ea7a5, type: 2}
m_GridWidth: 32
m_Spacing: 0.4
--- !u!114 &870320119
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 870320112}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: dd3f3fa5c40a66f44a9444b42845b28f, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Enable: 1
--- !u!1 &970523334
GameObject:
m_ObjectHideFlags: 0

134
Assets/BasicRenderBatching/BasicRenderBatchingShader.shader


Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
_GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0
[Enum(Metallic Alpha,0,Albedo Alpha,1)] _SmoothnessTextureChannel ("Smoothness texture channel", Float) = 0
[Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
_MetallicGlossMap("Metallic", 2D) = "white" {}
[ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
[ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0
_BumpScale("Scale", Float) = 1.0
_BumpMap("Normal Map", 2D) = "bump" {}
_Parallax ("Height Scale", Range (0.005, 0.08)) = 0.02
_ParallaxMap ("Height Map", 2D) = "black" {}
_OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
_OcclusionMap("Occlusion", 2D) = "white" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
_DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec("UV Set for secondary textures", Float) = 0
[HideInInspector] _Mode("__mode", Float) = 0.0
[HideInInspector] _SrcBlend("__src", Float) = 1.0
[HideInInspector] _DstBlend("__dst", Float) = 0.0

Tags { "RenderType" = "Opaque" "PerformanceChecks" = "False" }
LOD 300
// Include forward (base + additive) pass from regular Standard shader.
// They are not used by the scriptable render loop; only here so that
// if we turn off our example loop, then regular forward rendering kicks in
// and objects look just like with a Standard shader.
UsePass "Standard/FORWARD"
UsePass "Standard/FORWARD_DELTA"
// Multiple lights at once pass, for our example Basic render loop.
Pass
{

#pragma fragment frag
#pragma shader_feature _METALLICGLOSSMAP
#include "UnityCG.cginc"
#include "UnityStandardBRDF.cginc"
#include "UnityStandardUtils.cginc"
float4 _Color;
CBUFFER_START(GlobalLightData)
// The variables are very similar to built-in unity_LightColor, unity_LightPosition,
// unity_LightAtten, unity_SpotDirection as used by the VertexLit shaders, except here

float4 globalSH[7];
CBUFFER_END
// Surface inputs for evaluating Standard BRDF
struct SurfaceInputData
{
half3 diffColor, specColor;
half oneMinusReflectivity, smoothness;
};
half3 EvaluateOneLight(int idx, float3 positionWS, half3 normalWS, half3 eyeVec, SurfaceInputData s)
half3 EvaluateOneLight(int idx, float3 positionWS, half3 normalWS, float3 vAlbedo)
{
// direction to light
float3 dirToLight = globalLightPos[idx].xyz;

if (globalLightPos[idx].w != 0 && distSqr > globalLightAtten[idx].w) att = 0.0; // set to 0 if outside of range
distSqr = max(distSqr, 0.000001); // don't produce NaNs if some vertex position overlaps with the light
dirToLight *= rsqrt(distSqr);
// spotlight angular attenuation
float rho = max(dot(dirToLight, globalLightSpotDir[idx].xyz), 0.0);
float spotAtt = (rho - globalLightAtten[idx].x) * globalLightAtten[idx].y;
att *= saturate(spotAtt);
// Super simple diffuse lighting instead of PBR would be this:
//half ndotl = max(dot(normalWS, dirToLight), 0.0);
//half3 color = ndotl * s.diffColor * globalLightColor[idx].rgb;
//return color * att;
// spotlight angular attenuation
UnityLight light;
light.color = globalLightColor[idx].rgb * att;
light.dir = dirToLight;
UnityIndirect indirect;
indirect.diffuse = 0;
indirect.specular = 0;
half4 c = BRDF1_Unity_PBS(s.diffColor, s.specColor, s.oneMinusReflectivity, s.smoothness, normalWS, -eyeVec, light, indirect);
return c.rgb;
}
// Evaluate 2nd order spherical harmonics, given normalized world space direction.
// Similar to ShadeSH9 in UnityCG.cginc
half3 EvaluateSH(half3 n)
{
half3 res;
half4 normal = half4(n, 1);
// Linear (L1) + constant (L0) polynomial terms
res.r = dot(globalSH[0], normal);
res.g = dot(globalSH[1], normal);
res.b = dot(globalSH[2], normal);
// 4 of the quadratic (L2) polynomials
half4 vB = normal.xyzz * normal.yzzx;
res.r += dot(globalSH[3], vB);
res.g += dot(globalSH[4], vB);
res.b += dot(globalSH[5], vB);
// Final (5th) quadratic (L2) polynomial
half vC = normal.x*normal.x - normal.y*normal.y;
res += globalSH[6].rgb * vC;
return res;
half3 light = globalLightColor[idx].rgb * att;
half3 c = dot(dirToLight, normalWS) * light * vAlbedo;
return c;
// Vertex shader
struct v2f

float4 hpos : SV_POSITION;
};
float4 _MainTex_ST;
o.uv = TRANSFORM_TEX(v.texcoord,_MainTex);
o.hpos = UnityObjectToClipPos(v.vertex);
o.positionWS = mul(unity_ObjectToWorld, v.vertex).xyz;
o.normalWS = UnityObjectToWorldNormal(v.normal);

sampler2D _MainTex;
sampler2D _MetallicGlossMap;
float _Metallic;
float _Glossiness;
half3 eyeVec = normalize(i.positionWS - _WorldSpaceCameraPos);
// Sample textures
half4 diffuseAlbedo = tex2D(_MainTex, i.uv);
half2 metalSmooth;
#ifdef _METALLICGLOSSMAP
metalSmooth = tex2D(_MetallicGlossMap, i.uv).ra;
#else
metalSmooth.r = _Metallic;
metalSmooth.g = _Glossiness;
#endif
// Fill in surface input structure
SurfaceInputData s;
s.diffColor = DiffuseAndSpecularFromMetallic(diffuseAlbedo.rgb, metalSmooth.x, s.specColor, s.oneMinusReflectivity);
s.smoothness = metalSmooth.y;
// Ambient lighting
half4 color = half4(0,0,0, diffuseAlbedo.a);
UnityLight light;
light.color = 0;
light.dir = 0;
UnityIndirect indirect;
indirect.diffuse = EvaluateSH(i.normalWS);
indirect.specular = 0;
color.rgb += BRDF1_Unity_PBS(s.diffColor, s.specColor, s.oneMinusReflectivity, s.smoothness, i.normalWS, -eyeVec, light, indirect);
// Add illumination from all lights
for (int il = 0; il < globalLightCount.x; ++il)
{
color.rgb += EvaluateOneLight(il, i.positionWS, i.normalWS, eyeVec, s);
}
float4 color;
color.rgb = EvaluateOneLight(0, i.positionWS, i.normalWS, _Color.rgb);
return color;
}

27
Assets/BasicRenderBatching/Scripts/PopulateScene.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PopulateScene : MonoBehaviour {

public Material m_Material;
public static bool m_DifferentColors = true;
private GameObject[] m_Objects; //

vPos += m_CenterPoint.position;
m_Objects[iIndex] = Instantiate(m_ObjectPrefab, vPos, m_CenterPoint.rotation) as GameObject;
iIndex++;
if (m_DifferentColors)
{
Renderer renderer = m_Objects[iIndex].GetComponent<Renderer>();
Material mat = Instantiate(m_Material);
Color oColor = new Color(Random.value, Random.value, Random.value, 1.0f);
mat.color = oColor;
renderer.material = mat;
}
iIndex++;
}
}
}

{
}
void OnGUI()
{
GUI.changed = false;
m_DifferentColors = GUI.Toggle(new Rect(10, 10, 200, 20), m_DifferentColors, "One color per object");
if (GUI.changed)
{
SceneManager.LoadScene("BasicBatching");
}
}
}

2
ProjectSettings/ProjectSettings.asset


resizableWindow: 1
useMacAppStoreValidation: 0
gpuSkinning: 0
graphicsJobs: 1
graphicsJobs: 0
xboxPIXTextureCapture: 0
xboxEnableAvatar: 0
xboxEnableKinect: 0

74
Assets/BasicRenderBatching/BasicMat_ColorsFlat.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: BasicMat_ColorsFlat
m_Shader: {fileID: 4800000, guid: 88dc421b065e08e4caeb32d940c57312, type: 3}
m_ShaderKeywords: _EMISSION
m_LightmapFlags: 1
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.474
- _GlossyReflections: 1
- _Metallic: 0.194
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 0.97794116, g: 0, b: 0, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

8
Assets/BasicRenderBatching/BasicMat_ColorsFlat.mat.meta


fileFormatVersion: 2
guid: 4c676c131a81b634988506c3023ea7a5
timeCreated: 1481127206
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

110
Assets/BasicRenderBatching/Scripts/MiniProfiler.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
public class MiniProfiler : MonoBehaviour {
public bool m_Enable = false;
private int frameCount = 0;
private const int kAverageFrameCount = 64;
private float m_AccDeltaTime;
private float m_AvgDeltaTime;
internal class RecorderEntry
{
public string name;
public float time;
public int count;
public float avgTime;
public float avgCount;
public float accTime;
public int accCount;
public Recorder recorder;
};
RecorderEntry[] recordersList =
{
new RecorderEntry() { name="Camera.Render" },
new RecorderEntry() { name="GUI.Repaint" },
new RecorderEntry() { name="PrepareValues" },
new RecorderEntry() { name="ApplyGpuProgram" },
new RecorderEntry() { name="WriteParameters" },
new RecorderEntry() { name="FlushBuffers" },
new RecorderEntry() { name="BindBuffers" },
new RecorderEntry() { name="Gfx.ProcessCommand" },
};
void Awake()
{
for (int i=0;i<recordersList.Length;i++)
{
var sampler = Sampler.Get(recordersList[i].name);
if ( sampler != null )
{
recordersList[i].recorder = sampler.GetRecorder();
}
}
}
void Update()
{
if (m_Enable)
{
// get timing & update average accumulators
for (int i = 0; i < recordersList.Length; i++)
{
recordersList[i].time = recordersList[i].recorder.elapsedNanoseconds / 1000000.0f;
recordersList[i].count = recordersList[i].recorder.sampleBlockCount;
recordersList[i].accTime += recordersList[i].time;
recordersList[i].accCount += recordersList[i].count;
}
m_AccDeltaTime += Time.deltaTime;
frameCount++;
// time to time, update average values & reset accumulators
if (frameCount >= kAverageFrameCount)
{
for (int i = 0; i < recordersList.Length; i++)
{
recordersList[i].avgTime = recordersList[i].accTime * (1.0f / kAverageFrameCount);
recordersList[i].avgCount = recordersList[i].accCount * (1.0f / kAverageFrameCount);
recordersList[i].accTime = 0.0f;
recordersList[i].accCount = 0;
}
m_AvgDeltaTime = m_AccDeltaTime / kAverageFrameCount;
m_AccDeltaTime = 0.0f;
frameCount = 0;
}
}
}
void OnGUI()
{
if (m_Enable)
{
GUI.color = new Color(1, 1, 1, .75f);
float w = 500, h = 204;
GUILayout.BeginArea(new Rect(10, 150, w, h), "Mini Profiler", GUI.skin.window);
string sLabel = System.String.Format("<b>{0:F2} FPS ({1:F2}ms)</b>\n", 1.0f / m_AvgDeltaTime, Time.deltaTime * 1000.0f);
for (int i = 0; i < recordersList.Length; i++)
{
sLabel += string.Format("{0:F2}ms (*{1:F2})\t({2:F2}ms *{3:F2})\t<b>{4}</b>\n", recordersList[i].avgTime, recordersList[i].avgCount, recordersList[i].time, recordersList[i].count, recordersList[i].name);
}
GUILayout.Label(sLabel);
GUILayout.EndArea();
}
}
}

12
Assets/BasicRenderBatching/Scripts/MiniProfiler.cs.meta


fileFormatVersion: 2
guid: dd3f3fa5c40a66f44a9444b42845b28f
timeCreated: 1481192301
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存