2016년 6월 30일 목요일

Unity Shader Function

엔비디아 사이트

floor : 내림 ( 0.1 -> 0, 0.9999 -> 0 )
frac  : 소수 에서 자연수 제거 ( 12.34 -> 0.34 )
clip  : frag 함수에서 value 가 음이면 즉각 랜더링 중지
reflect : view 와 normal을 이용해서 리플렉션 벡터를 구한다.
saturate : Returns x saturated to the range [0,1] as follows:
           1) Returns 0 if x is less than 0; else
           2) Returns 1 if x is greater than 1; else
           3) Returns x otherwise.
any : 



- 사용 방법( floor, frac, clip )
screenPos.xy = floor(screenPos.xy * 0.25) * 0.5;
//스크린 좌표를 정수로 만들고 인위적으로 끝이 .0 이나 .5로 끝나게 함
float checker = -frac(screenPos.x + screenPos.y);
//소수점 수치가 있다면 랜더링 중지
clip(checker);

- 사용 방법( reflect )
Pass
{
   CGPROGRAM
   #pragma vertex vert
   #pragma fragment frag
   #include "UnityCG.cginc"
   struct v2f
   {
      half3 worldRefl : NORMAL;
      fixed4 pos : SV_POSITION;
   };

   v2f vert(float4 vertex : POSITION, float3 normal : NORMAL)
  {
     v2f o;
     o.pos = mul(UNITY_MATRIX_MVP, vertex);
    // compute world space position of the vertex
    float3 worldPos = mul(_Object2World, vertex).xyz;
    // compute world space view direction
    float3 worldViewDir = normalize(UnityWorldSpaceViewDir(worldPos));
    // world space normal
    float3 worldNormal = UnityObjectToWorldNormal(normal);
    // world space reflection vector
    o.worldRefl = reflect(-worldViewDir, worldNormal);
    return o;
  }

   fixed4 frag(v2f i) : SV_Target
   {
      // sample the default reflection cubemap, using the reflection vector
      half4 skyData = UNITY_SAMPLE_TEXCUBE(unity_SpecCube0, i.worldRefl);
      // decode cubemap data into actual color
      half3 skyColor = DecodeHDR(skyData, unity_SpecCube0_HDR);
      // output it!
      fixed4 c = 0;
      c.rgb = skyColor;
       return c;
   }
    ENDCG

}

- 사용 방법( saturate )
half4 frag( v2f i ) : SV_Target
{
     half4 c = frac( i.uv );
     if (any(saturate(i.uv) - i.uv))
         c.b = 0.5;
     return c;
}




=================================================================================

5. 유니티 내장
#include "UnityCG.cginc"



- 함수

UnityWorldSpaceViewDir(worldPos) : 월드 포지션으로 뷰 벡터를 구한다.

UnityObjectToWorldNormal(i.normal) : 노말을 월드 노말로 

UNITY_SAMPLE_TEXCUBE(unity_SpecCube0, i.worldRefl) : 디폴트 리플렉션 큐브맵을 뽑는다.
half4 skyData = UNITY_SAMPLE_TEXCUBE(unity_SpecCube0, i.worldRefl);

- 변수
UNITY_MATRIX_MVP : vertex와 곱하면 스크린 스페이스의 포지션이 나오나 보다
_Object2World : vertex와 곱하면 월드 스페이스의 포지션이 나온다.

unity_SpecCube0 : 
unity_SpecCube0_HDR

Unity Shader vert and frag



vertex structures : 버텍스 하나에 담긴 정보를 나열한 스트럭트

기호에 맞게 정의하여 사용, 또는 UnityCG.cginc 을 include 하여
아래의 미리 정의된 형태 사용

appdata_base:    position,             normal, 1 texture coordinate.
appdata_tan:      position, tangent, normal, 1 texture coordinate.
appdata_full:      position, tangent, normal, 4 texture coordinates, color.



스스로 정의하여 사용한다면...

POSITION (vertex position) :               typically float3 or float4
NORMAL (vertex normal):                  typically a float3
TEXCOORD0 (first UV coordinate) :      typically float2, float3 or float4.
TEXCOORD1, TEXCOORD2 and TEXCOORD3 are the 2nd, 3rd and 4th UV coordinates
TANGENT (used for normal mapping) : typically a float4.
COLOR (per-vertex color) :                 typically a float4.

이런 식으로 커스텀 버텍스 스트럭트를 정의 한다.(필요 없는건 뺀다)
struct appdata
{
    float4 vertex : POSITION;
    float4 texcoord : TEXCOORD0;
    fixed4 color : COLOR;
    float3 normal : NORMAL;
    float4 tangent : TANGENT;
};

참고 :
calculate bitangent ->
float3 bitangent = cross( v.normal, v.tangent.xyz ) * v.tangent.w;
두 백터에 수직인 벡터는 방향이 정 반대인 벡터 두개가 나오는데 * v.tangent.w 가
둘중 하나를 고르는 역할을 하는 듯 하다. w의 의미를 알아내야 한다.











=======================================================

Unity Shader Properties


Accessing shader properties

Properties 정의

_MyColor ("Some Color", Color) = (1,1,1,1)
_MyVector ("Some Vector", Vector) = (0,0,0,0)
_MyFloat ("My float", Float) = 0.5
_MyTexture ("Texture", 2D) = "white" {}
_MyCubemap ("Cubemap", CUBE) = "" {}

Properties 엑세스를 위한 선언

fixed4 _MyColor; // low precision type is usually enough for colors
float4 _MyVector;
float _MyFloat;
sampler2D _MyTexture;
samplerCUBE _MyCubemap;

-> uniform keyword is not necessary:
uniform float4 _MyColor;

Color, Vector -> float4, half4, fixed4
Range, Float -> float, half, fixed
2D textures -> sampler2D
3D textures -> sampler3D
Cubemaps -> samplerCUBE











=====================================================

2016년 6월 29일 수요일

Unity Shader Tags

+1, -1 등으로 그리는 순서를 인위적으로 배치할 수 있다.

ZWrite Off 상태가 차이점을 확인하기 가장 좋다.
ZWrite On 의 경우 Z buffer를 참고하기 때문에 + - 의 효과가 없다.


+1 -1 했다면 쉐이더를 다른 것( 스텐다스 쉐이더 등)으로 교체했다가 다시 원래것으로 해야 적용이 된다.

======================================================


Queue

Background - ( 1000 ) this render queue is rendered before any others. You’d typically use this for things that really need to be in the background.

Geometry (default) - ( 2000 ) this is used for most objects. Opaque geometry uses this queue.

AlphaTest - (2450) alpha tested geometry uses this queue. It’s a separate queue from Geometry one since it’s more efficient to render alpha-tested objects after all solid ones are drawn.

Transparent - ( 3000 ) this render queue is rendered after Geometry and AlphaTest, in back-to-front order. Anything alpha-blended (i.e. shaders that don’t write to depth buffer) should go here (glass, particle effects).

Overlay - ( 4000 ) this render queue is meant for overlay effects. Anything rendered last should go here (e.g. lens flares).

======================================================


RenderType

Opaque: most of the shaders (Normal, Self Illuminated, Reflective, terrain shaders).

Transparent: most semitransparent shaders (Transparent, Particle, Font, terrain additive pass shaders).

TransparentCutout: masked transparency shaders (Transparent Cutout, two pass vegetation shaders).

Background: Skybox shaders.

Overlay: GUITexture, Halo, Flare shaders.

TreeOpaque: terrain engine tree bark.

TreeTransparentCutout: terrain engine tree leaves.

TreeBillboard: terrain engine billboarded trees.

Grass: terrain engine grass.

GrassBillboard: terrain engine billboarded grass.

======================================================


IgnoreProjector

If IgnoreProjector tag is given and has a value of “True”, then an object that uses this shader will not be affected by Projectors. This is mostly useful on semitransparent objects, because there is no good way for Projectors to affect them.



======================================================
======================================================
======================================================
======================================================


dd



2016년 6월 28일 화요일

Unity Shader - Stencil

====================================================

Comparison Function ( ex: Comp always )

Greater
Only render pixels whose reference value is greater than the value in the buffer.

GEqual
Only render pixels whose reference value is greater than or equal to the value in the buffer.

Less
Only render pixels whose reference value is less than the value in the buffer.

LEqual
Only render pixels whose reference value is less than or equal to the value in the buffer.

Equal
Only render pixels whose reference value equals the value in the buffer.

NotEqual
Only render pixels whose reference value differs from the value in the buffer.

Always
Make the stencil test always pass.

Never
Make the stencil test always fail.


====================================================

Stencil Operation ( ex: Pass replace )
ex: ZFail decrWrap -> comp에 실패한 경우 Ref를 낮춘다.

Keep
Keep the current contents of the buffer.

Zero
Write 0 into the buffer.

Replace
Write the reference value into the buffer.

IncrSat
Increment the current value in the buffer. If the value is 255 already, it stays at 255.

DecrSat
Decrement the current value in the buffer. If the value is 0 already, it stays at 0.

Invert
Negate all the bits.


IncrWrap
Increment the current value in the buffer. If the value is 255 already, it becomes 0.


DecrWrap
Decrement the current value in the buffer. If the value is 0 already, it becomes 255.





2016년 6월 27일 월요일

Unity Shader Blend

=======================================================
blending types

Blend SrcAlpha OneMinusSrcAlpha // Traditional transparency
Blend One OneMinusSrcAlpha // Premultiplied transparency
Blend One One // Additive
Blend OneMinusDstColor One // Soft Additive
Blend DstColor Zero // Multiplicative
Blend DstColor SrcColor // 2x Multiplicative


========================================================

Blending : 경계선이 interpolated

// inside SubShader
Tags { "Queue"="Transparent" "RenderType"="Transparent" "IgnoreProjector"="True" }

// inside Pass
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha


========================================================

Testing / Cutout : 경계선이 필셀 수준에서 컷아웃, clip()

// inside SubShader
Tags { "Queue"="AlphaTest" "RenderType"="TransparentCutout" "IgnoreProjector"="True" }

// inside CGPROGRAM in the fragment shader:
clip(textureColor.a - alphaCutoffValue);


========================================================

Coverage : multisample anti-aliasing (MSAA, see QualitySettings)
               AlphaToMask On, at 4xMSAA

// inside SubShader
Tags { "Queue"="AlphaTest" "RenderType"="TransparentCutout" "IgnoreProjector"="True" }

// inside Pass
AlphaToMask On


========================================================

Example

Shader "Simple Additive" {
    Properties {
        _MainTex ("Texture to blend", 2D) = "black" {}
    }
    SubShader {
        Tags { "Queue" = "Transparent" }
        Pass {
            Blend One One
            SetTexture [_MainTex] { combine texture }
        }
    }
}





Unity Text

///////////////////////////////////////////////////////////////////////////////////////////////////

변수.ToString("F2"); --> 소수점 둘째자리 까지 표시

2016년 6월 16일 목요일

Unity Reset Preferance External Tool

using UnityEditor;
using UnityEngine;

public class ResetExternalTool : MonoBehaviour
{
    [MenuItem ("Edit/Reset Preferences")]
    static void ResetPrefs()
    {
        if(EditorUtility.DisplayDialog("Reset editor preferences?", "Reset all editor preferences? This cannot be undone.", "Yes", "No"))
        {
            EditorPrefs.DeleteAll();
        }
    }
}

2016년 6월 14일 화요일

Unity Shader Code - Unlit Transparent

Shader "Custom/UnlitTransparent"
{
/*Properties{
_Color("Color & Transparency", Color) = (0, 0, 0, 0.5)
_Alpha("Alpha", Range(0.0, 1.0)) = 1.0
}
SubShader{
Lighting Off
ZWrite Off
Cull Back
Blend SrcAlpha OneMinusSrcAlpha
Tags{ "Queue" = "Transparent" }
Color[_Color]

Pass{


}
}*/


Properties
{
_MainTex("Texture", 2D) = "white"{}
_Color("Color & Transparency", Color) = (0, 0, 0, 0.5)
_Alpha("Alpha", Range(0,1)) = 1

}

SubShader
{
Tags{ Queue = Transparent }
ZWrite Off
Lighting off
Cull Back
Blend SrcAlpha OneMinusSrcAlpha

Pass
{
SetTexture[_MainTex]
{
ConstantColor(1, 1, 1,[_Alpha])
Combine texture * constant
//Combine texture * constant DOUBLE
}
}
}


FallBack "Unlit/Transparent"
}