2016년 7월 12일 화요일

Unity Coroutine

애니메이션이 특정 부분 완료되기까지를 기다리는 코루틴의 예
출처

yield.

null - Update구문의 수행이 완료될 때까지 대기한다.

WaitForEndOfFrame - 현재 프레임의 렌더링 작업이 끝날 때까지 대기한다.

WaitForFixedUpdate - FixedUpdate구문의 수행이 완료될 때까지 대기한다.

WaitForSeconds - 지정한 초만큼 대기한다.

WWW - 웹에서 데이터의 전송이 완료될 때까지 대기한다.
(WaitForSeconds or null처럼 재시작한다.)

Another coroutine - 새로운 코루틴은 yielder가 재시작되기 전에 완료 될 것이다.




//Wait for an animation to be a certain amount complete
IEnumerator WaitForAnimation(string name, float ratio, bool play)
{
    //Get the animation state for the named animation
    var anim = animation[name];
    //Play the animation
    if(play) animation.Play(name);

    //Loop until the normalized time reports a value
    //greater than our ratio.  This method of waiting for
    //an animation accounts for the speed fluctuating as the
    //animation is played.
    while(anim.normalizedTime + float.Epsilon + Time.deltaTime < ratio)
        yield return new WaitForEndOfFrame();

}


애니메이션을 기다리는 코루틴을 다음과 같이 작성

IEnumerator Die()
{
       //Wait for the die animation to be 50% complete
       yield return StartCoroutine(WaitForAnimation("die",0.5f, true));
       //Drop the enemies on dying pickup
       DropPickupItem();
       //Wait for the animation to complete
       yield return StartCoroutine(WaitForAnimation("die",1f, false));
       Destroy(gameObject);

}

2016년 7월 3일 일요일

unity / shader / 테이터 타입 및 정밀도

유니티 사이트


float : High precision
generally 32 bits, used for world space positions, texture coordinates, or scalar computations involving complex functions such as trigonometry(삼각법) or power(제곱)/exponentiation(지수).


half : Medium precision
generally 16 bits (range of –60000 to +60000, with about 3 decimal digits of precision).
useful for short vectors, directions, object space positions, high dynamic range colors


fixed : Low precision
generally 11 bits, with a range of –2.0 to +2.0 and 1/256th precision.
useful for regular colors (as typically stored in regular textures) and performing simple operations on them.


Integer data types
often used as loop counters or array indices. For this purpose, they generally work fine across various platforms.


Composite vector/matrix types

HLSL has built-in vector and matrix types that are created from the basic types. For example, float3 is a 3D vector with .x, .y, .z components, and half4 is a medium precision 4D vector with .x, .y, .z, .w components. Alternatively, vectors can be indexed using .r, .g, .b, .a components, which is useful when working on colors.



Texture/Sampler types

Typically you declare textures in your HLSL code as follows:

sampler2D _MainTex;
samplerCUBE _Cubemap;


For mobile platforms, these translate into “low precision samplers”, i.e. the textures are expected to have low precision data in them. If you know your texture contains HDR colors, you might want to use half precision sampler:

sampler2D_half _MainTex;
samplerCUBE_half _Cubemap;


Or if your texture contains full float precision data (e.g. depth texture), use a full precision sampler:

sampler2D_float _MainTex;
samplerCUBE_float _Cubemap;



2016년 7월 1일 금요일

Unity shader Built-in include files ( #include "UnityCG.cginc")

유니티 사이트

CGPROGRAM
// ...
#include "UnityCG.cginc"  <---
// ...

ENDCG

Data structures in UnityCG.cginc
struct appdata_base: position, normal, one texture coordinate.
struct appdata_tan:  position, normal, tangent, one texture coordinate.
struct appdata_full: position, normal, tangent, vertex color and two texture coordinates.

struct appdata_img:  position and one texture coordinate.



Vertex transformation functions in UnityCG.cginc

- float4 UnityObjectToClipPos(float3 pos)
Transforms a point from object space to the camera’s clip space in homogeneous coordinates.
This is the equivalent of mul(UNITY_MATRIX_MVP, float4(pos, 1.0)),
and should be used in its place.

- float3 UnityObjectToViewPos(float3 pos)
Transforms a point from object space to view space.
This is the equivalent of mul(UNITY_MATRIX_MV, float4(pos, 1.0)).xyz,
and should be used in its place.


Generic helper functions in UnityCG.cginc

- float3 WorldSpaceViewDir (float4 v) : UnityWorldSpaceViewDir(worldPos)
Returns world space direction (not normalized) from given object space vertex position towards 
the camera.

- float3 ObjSpaceViewDir (float4 v)
Returns object space direction (not normalized) from given object space vertex position towards
the camera.

- float2 ParallaxOffset (half h, half height, half3 viewDir)
calculates UV offset for parallax normal mapping.

- fixed Luminance (fixed3 c)
Converts color to luminance (grayscale).

- fixed3 DecodeLightmap (fixed4 color)
Decodes color from Unity lightmap (RGBM or dLDR depending on platform).

- float4 EncodeFloatRGBA (float v)
Encodes [0..1) range float into RGBA color, for storage in low precision render target.

- float DecodeFloatRGBA (float4 enc)
Decodes RGBA color into a float.

- float2 EncodeFloatRG (float v) Encodes [0..1)
range float into a float2.

- float DecodeFloatRG (float2 enc)
Decodes a previously-encoded RG float.

- float2 EncodeViewNormalStereo (float3 n)
Encodes view space normal into two numbers in 0..1 range.

- float3 DecodeViewNormalStereo (float4 enc4)
Decodes view space normal from enc4.xy.

-> 찾아봐야 할 것

- UnityObjectToWorldNormal(i.normal) : 노말을 월드 노말로 
- UNITY_SAMPLE_TEXCUBE(unity_SpecCube0, i.worldRefl) : 디폴트 리플렉션 큐브맵을 뽑는다.
half4 skyData = UNITY_SAMPLE_TEXCUBE(unity_SpecCube0, i.worldRefl);


Forward rendering helper functions in UnityCG.cginc

These functions are only useful when using forward rendering
(ForwardBase or ForwardAdd pass types).

- float3 WorldSpaceLightDir (float4 v)
Computes world space direction (not normalized) to light, given object space vertex position.

- float3 ObjSpaceLightDir (float4 v)
Computes object space direction (not normalized) to light, given object space vertex position.


- float3 Shade4PointLights (...)
Computes illumination from four point lights, with light data tightly packed into vectors.
Forward rendering uses this to compute per-vertex lighting.


Vertex-lit helper functions in UnityCG.cginc

These functions are only useful when using per-vertex lit shaders (“Vertex” pass type).

- float3 ShadeVertexLights (float4 vertex, float3 normal)
Computes illumination from four per-vertex lights and ambient,
given object space position & normal.


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

Built-in shader variables



Transformations


All these matrices are float4x4 type.

UNITY_MATRIX_MVP Current model * view * projection matrix.
UNITY_MATRIX_MV        Current model * view matrix.
UNITY_MATRIX_V         Current view matrix.
UNITY_MATRIX_P         Current projection matrix.
UNITY_MATRIX_VP        Current view * projection matrix.
UNITY_MATRIX_T_MV Transpose of model * view matrix.
UNITY_MATRIX_IT_MV Inverse transpose of model * view matrix.

_Object2World          Current model matrix. vertex와 곱하면 월드 스페이스의 포지션
                       float3 worldPosition = mul(_Object2World, v.vertex).xyz;

_World2Object          Inverse of current world matrix.


Camera and screen

These variables will correspond to the Camera that is rendering.
For example during shadowmap rendering, they will still refer to the Camera component values,
and not the “virtual camera” that is used for the shadowmap projection.


- _WorldSpaceCameraPos : float3
World space position of the camera.

- _ProjectionParams :float4
x is 1.0 (or –1.0 if currently rendering with a flipped projection matrix),
y is the camera’s near plane,
z is the camera’s far plane and w is 1/FarPlane.

- _ScreenParams : float4
x is the camera’s render target width in pixels,
y is the camera’s render target height in pixels,
z is 1.0 + 1.0/width
w is 1.0 + 1.0/height.

- _ZBufferParams : float4 ( Used to linearize Z buffer values. )
x is (1-far/near),
y is (far/near),
z is (x/far),
w is (y/far).

- unity_OrthoParams : float4
x is orthographic camera’s width,
y is orthographic camera’s height,
z is unused
w is 1.0 when camera is orthographic, 0.0 when perspective.

- unity_CameraProjection : float4x4
Camera’s projection matrix.

- unity_CameraInvProjection : float4x4
Inverse of camera’s projection matrix.


- unity_CameraWorldClipPlanes[6] : float4
Camera frustum plane world space equations, in this order: left, right, bottom, top, near, far.


Time

- _Time : float4
Time since level load (t/20, t, t*2, t*3), use to animate things inside the shaders.

- _SinTime : float4
Sine of time: (t/8, t/4, t/2, t).

- _CosTime : float4
Cosine of time: (t/8, t/4, t/2, t).


- unity_DeltaTime : float4
Delta time: (dt, 1/dt, smoothDt, 1/smoothDt).


Lighting

Light parameters are passed to shaders in different ways
depending on which Rendering Path is used, and which LightMode Pass Tag is used in the shader.


Forward rendering (ForwardBase and ForwardAdd pass types):

_LightColor0 (declared in Lighting.cginc) : fixed4
Light color.

_WorldSpaceLightPos0 : float4
Directional lights: (world space direction, 0). Other lights: (world space position, 1).

_LightMatrix0 (declared in AutoLight.cginc) : float4x4
World-to-light matrix. Used to sample cookie & attenuation textures.

unity_4LightPosX0, unity_4LightPosY0, unity_4LightPosZ0 : float4 (ForwardBase pass only)
world space positions of first four non-important point lights.

unity_4LightAtten0 : float4 (ForwardBase pass only)
attenuation factors of first four non-important point lights.


unity_LightColor : half4[4] (ForwardBase pass only)
colors of of first four non-important point lights.



Deferred shading and deferred lighting, used in the lighting pass shader
(all declared in UnityDeferredLibrary.cginc):

_LightColor : float4
Light color.

_LightMatrix0 :float4x4
World-to-light matrix. Used to sample cookie & attenuation textures.


Fog and Ambient


unity_AmbientSky : fixed4
Sky ambient lighting color in gradient ambient lighting case.

unity_AmbientEquator : fixed4
Equator ambient lighting color in gradient ambient lighting case.

unity_AmbientGround : fixed4
Ground ambient lighting color in gradient ambient lighting case.

UNITY_LIGHTMODEL_AMBIENT : fixed4
Ambient lighting color (sky color in gradient ambient case). Legacy variable.

unity_FogColor : fixed4
Fog color.

unity_FogParams : float4
Parameters for fog calculation:(density/sqrt(ln(2)),density/ln(2),–1/(end-start),end/(end-start))
x is useful for Exp2 fog mode, y for Exp mode, z and w for Linear mode.




Ti







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