Get it on Google Play


Wm뮤 :: 'Unity/shader' 카테고리의 글 목록

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
퇴직한 전자과 게임프로그래머
2020.3.48f1 , 2022.3.6f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


2023. 12. 18. 13:42 Unity/shader

 

 

Shader error in 'Ahzkwid/Toon': Output variable vert contains a system-interpreted value (SV_RenderTargetArrayIndex) which must be written in every execution path of the shader.  Unconditional initialization may help. at line 586 (on d3d11)

유니티 2019에서는 발생 안 하다가 2022에서 급작스럽게 발생했다.

원인은 struct v2f의 UNITY_VERTEX_OUTPUT_STEREO 구조변경 때문이다.

 

appdata와 vert에 아래구문을 추가한다

struct appdata
{
    UNITY_VERTEX_INPUT_INSTANCE_ID
};
v2f vert (appdata v)
{
    v2f o;

    UNITY_SETUP_INSTANCE_ID(v);
    UNITY_INITIALIZE_OUTPUT(v2f, o); 
    UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
}

 

참고링크 : https://docs.unity3d.com/kr/2019.4/Manual/SinglePassInstancing.html

 

 

 

 

 

Shader error in 'Ahzkwid/KotatsuFuton': invalid subscript 'instanceID' at line 339 (on d3d11)
Compiling Subshader: 0, Pass: FORWARD, Vertex program with DIRECTIONAL STEREO_INSTANCING_ON VERTEXLIGHT_ON

 

위와 같은 문제이다.

위와 다른점은 위에건 버텍스 프래그 쉐이더를 썼지만 이건 서피스와 버텍스 혼합 쉐이더에서 발생한 차이점이 있다.

내 경우엔 프래그를 안 가져와서 void vert이기 때문에 appdata에 아래 구문 추가하는거로 끝났다.

struct appdata
{
    UNITY_VERTEX_INPUT_INSTANCE_ID
};

'Unity > shader' 카테고리의 다른 글

DepthCameraTexture를 _CameraDepthTexture처럼 쓰기  (0) 2023.10.14
PerlinNoise HLSL  (0) 2023.04.25
스크린 오버레이 샘플  (0) 2023.01.20
posted by 모카쨩
2023. 10. 14. 12:29 Unity/shader

 

 

Shader "Unlit/AndroidDepth"
{
    Properties
    {
		_DepthTex("_DepthTex", 2D) = "white" {}
    }
    SubShader
    {
        Tags { 
		"RenderType" = "Transparent"
		"Queue" = "Transparent"
        }
        LOD 100
        
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;

				float4 screenPos : TEXCOORD1;
            };

            
			sampler2D _DepthTex;
			float4 _DepthTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _DepthTex);
				o.screenPos = ComputeScreenPos(o.vertex);//면이 닿는 부분
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {



                
				
				float4 screenPos = float4(i.screenPos.xyz, i.screenPos.w);
				float4 screenPosNorm = screenPos / screenPos.w;


				
				screenPosNorm.x*= _ScreenParams.x/ _ScreenParams.y;
				screenPosNorm.x+= 0.5;
				screenPosNorm.x-= _ScreenParams.x/ _ScreenParams.y/2;


				screenPosNorm.y*=_DepthTex_ST.y;
				screenPosNorm.x*=_DepthTex_ST.y;
				
				screenPosNorm.x+=0.5;
				screenPosNorm.x-=_DepthTex_ST.y/2;
				
				
				float depCol= tex2D(_DepthTex, screenPosNorm.xy);
				
				 fixed4 col=0;
				col.a=1;
				col.r=depCol*2;



                return col;
            }
            ENDCG
        }
    }
}

단 처음에 Rect사이즈를 가져와야 한다

이걸

이렇게 넣으면 끝

내가 이걸 왜 만들었냐 하면 안드로이드에선

정확히는 안드로이드의 OpenGLES3에서 _CameraDepthTexture를 가져올때 문제가 발생하기 때문

그리고 만약 멀티플랫폼을 지원해야 한다면 아래와같은 분기처리를 해줘야 한다

 #if UNITY_IOS || UNITY_STANDALONE
 //기존코드
#else
//커스텀 뎁스
#endif

그리고 당연히 카메라설정도 반영해야 하는데 난 FOV만 바꿔서 FOV만 설정함

using UnityEngine;

public class CameraCopy : MonoBehaviour
{
    void Update()
    {
        var camMain = Camera.main;
        var camThis = GetComponent<Camera>();
        camThis.fieldOfView = camMain.fieldOfView;
    }
}

뎁스 카메라에 이걸 넣어줌

 

결과물

근데 빌드하고 보니 뎁스 카메라도 안 되더라

찌발

 

 

왠지 렌더텍스처를 동적으로 생성하면 될거같기도 한데

이러면 생성할때마다 마테리얼에 하나하나 할당해줄거 생각하니 끔찍해서

결국 분기처리해서 안드로이드쓸때만 작동 안 하게 함

(어차피 아이폰은 된다고)

'Unity > shader' 카테고리의 다른 글

유니티 쉐이더 오류 모음  (0) 2023.12.18
PerlinNoise HLSL  (0) 2023.04.25
스크린 오버레이 샘플  (0) 2023.01.20
posted by 모카쨩
2023. 4. 25. 03:07 Unity/shader

 

Shader "Perlin/Noise"
{
    Properties
    {
        [HideInInspector]_MainTex ("Texture", 2D) = "white" {}
		[PowerSlider(4)]_Scale("Scale", Range(0,8192)) = 1000
		_Speed("Speed", Range(0,8)) = 0
		//[HideInInspector]
        _Key("Key", float) = 0
    }
    SubShader
    {
		Tags{
			"RenderType" = "Transparent"
			"Queue" = "Transparent"
            "IgnoreProjector"="True"
		}

        LOD 100
        
		blend srcalpha oneminussrcalpha
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"
            float _Speed;
            float _Key;
            float interpolate(float a0, float a1, float w) {
                /* // You may want clamping by inserting:
                 * if (0.0 > w) return a0;
                 * if (1.0 < w) return a1;
                 */
                return (a1 - a0) * w + a0;
                /* // Use this cubic interpolation [[Smoothstep]] instead, for a smooth appearance:
                 * return (a1 - a0) * (3.0 - w * 2.0) * w * w + a0;
                 *
                 * // Use [[Smootherstep]] for an even smoother result with a second derivative equal to zero on boundaries:
                 * return (a1 - a0) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a0;
                 */
            }
            float2 randomGradient(int ix, int iy) {
                // No precomputed gradients mean this works for any number of grid coordinates
                uint w = 8 * (4294967295+1);
                uint s = w / 2; // rotation width
                uint a = ix, b = iy;
                a *= 3284157443; 
                b ^= a << s | a >> w-s;
                b *= 1911520717; 
                a ^= b << s | b >> w-s;
                a *= 2048419325;
                float random = a * (3.14159265 / ~(~0u >> 1)); // in [0, 2*Pi]
                random += _Time.y*_Speed;
                random += _Key;
                float2 v;
                v.x = cos(random); v.y = sin(random);
                return v;
            }
            // Computes the dot product of the distance and gradient vectors.
            float dotGridGradient(int ix, int iy, float x, float y) {
                // Get gradient from integer coordinates
                float2 gradient = randomGradient(ix, iy);

                // Compute the distance vector
                float dx = x - (float)ix;
                float dy = y - (float)iy;

                // Compute the dot-product
                return (dx*gradient.x + dy*gradient.y);
            }
            // Compute Perlin noise at coordinates x, y
            float perlin(float x, float y) {
                // Determine grid cell coordinates
                int x0 = (int)floor(x);
                int x1 = x0 + 1;
                int y0 = (int)floor(y);
                int y1 = y0 + 1;

                // Determine interpolation weights
                // Could also use higher order polynomial/s-curve here
                float sx = x - (float)x0;
                float sy = y - (float)y0;

                // Interpolate between grid point gradients
                float n0, n1, ix0, ix1, value;

                n0 = dotGridGradient(x0, y0, x, y);
                n1 = dotGridGradient(x1, y0, x, y);
                ix0 = interpolate(n0, n1, sx);

                n0 = dotGridGradient(x0, y1, x, y);
                n1 = dotGridGradient(x1, y1, x, y);
                ix1 = interpolate(n0, n1, sx);

                value = interpolate(ix0, ix1, sy);
                return value; // Will return in range -1 to 1. To make it in range 0 to 1, multiply by 0.5 and add 0.5
            }
            float perlin(float2 uv) {
                return perlin(uv.x,uv.y)*0.5+0.5; 
            }
            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _Scale;
            
            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }


            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = 1;
                col.rgb = perlin(i.uv*_Scale);
                return col;
            }
            ENDCG
        }
    }
}

 

내가 포팅한 펄린노이즈임

원문은 https://en.wikipedia.org/wiki/Perlin_noise 에서 가져왔고

포팅만 했을뿐 만든건 Ken Perlin이므로 어떻게 쓰던 알바아님😜

자기가 포팅했다고 하는 노양심짓만 안 해주면 좋을듯

'Unity > shader' 카테고리의 다른 글

DepthCameraTexture를 _CameraDepthTexture처럼 쓰기  (0) 2023.10.14
스크린 오버레이 샘플  (0) 2023.01.20
유니티 스카이박스 관련  (0) 2023.01.16
posted by 모카쨩
2023. 1. 20. 07:49 Unity/shader

 

1:1

 

2:1 크롭

 

 

Shader "Ahzkwid/ScreenOverlay"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;
            

            v2f vert (appdata v)
            {
                v2f o;
				o.uv = float4(TRANSFORM_TEX(v.uv, _MainTex),1,1);
				o.vertex.xy = o.uv;
				o.vertex.xy -= 0.5;
				o.vertex.xy *= 2;
				o.vertex.y = -o.vertex.y;
				o.vertex.zw = 1;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed2 uv=i.uv;
                
				float screenWid = _ScreenParams.x / _ScreenParams.y;
				float texelWid = _MainTex_TexelSize.z / _MainTex_TexelSize.w;
                if(screenWid>texelWid)
                {
                    uv.x*=screenWid;
			        uv.x -= screenWid / 2;
			        uv.x += texelWid / 2;
                    uv.x/=texelWid;
                }
                else
                {

				    float screenHei = 1/screenWid;
				    float texelHei = 1/texelWid;

                    uv.y*=screenHei;
			        uv.y -= screenHei / 2;
			        uv.y += texelHei / 2;
                    uv.y/=texelHei;
                }

                fixed4 col = tex2D(_MainTex, uv);
                col.a*=all(uv==saturate(uv));
                return lerp(0,col,col.a);
            }
            ENDCG
        }
    }
}

'Unity > shader' 카테고리의 다른 글

PerlinNoise HLSL  (0) 2023.04.25
유니티 스카이박스 관련  (0) 2023.01.16
함수 그래프 모음  (0) 2022.01.15
posted by 모카쨩
2023. 1. 16. 21:41 Unity/shader
Shader "Skybox/Sample"
{
    Properties
    {
        [NoScaleOffset] _Tex ("Cubemap   (HDR)", Cube) = "grey" {}
    }
    SubShader
    {
        Tags { "Queue"="Background" "RenderType"="Background" "PreviewType"="Skybox" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float3 texcoord : TEXCOORD0;
                UNITY_VERTEX_OUTPUT_STEREO
            };
            
            samplerCUBE _Tex;
            half4 _Tex_HDR;

            v2f vert (appdata v)
            {
                v2f o;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.texcoord = v.vertex.xyz;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                half4 tex = texCUBE (_Tex, i.texcoord);
                fixed3 col = DecodeHDR (tex, _Tex_HDR);
                return half4(col, 1);
            }
            ENDCG
        }
    }
}

샘플코드

 

 

 

'Unity > shader' 카테고리의 다른 글

스크린 오버레이 샘플  (0) 2023.01.20
함수 그래프 모음  (0) 2022.01.15
Decal Shader  (0) 2022.01.13
posted by 모카쨩
2022. 1. 15. 13:14 Unity/shader

쉐이더 짜면서 만들었던 그래프들

 

 

 

 

사이트는 이곳을 사용했다

https://www.mathway.com/ko/Graph

 

Mathway | 그래프 계산기

 

www.mathway.com

https://www.desmos.com/calculator?lang=ko 

 

Desmos | 그래핑 계산기

 

www.desmos.com

 

 

 

로그

 

 

 

y=x*x

 

y=1-x*x

 

 

y=sqrt(x)

 

sqrt(1-x)

 

y=sqrt(1-abs(x))

안 쓸거 같았는데 의외로 스카이박스 쉐이더 만들때 썼다

 

 

y=sqrt(1-abs(x))*x/abs(x)

 

 

y=sqrt(x)*sqrt(1-x)

 

y=sqrt(1-x/2)*sqrt(x*2)

 

y=sqrt(1-x)*sqrt(x+1)

 

 

 

 

y=sqrt(x+1)*-sqrt(1-x)

 

그냥 위에서 +1을 했을뿐

y=sqrt(x+1)*-sqrt(1-x)+1

 

 

y=sqrt(x+1)*sqrt(1-x)*x/abs(x)

 

 

 

g=(1+sqrt(5))/2   //황금비

y=(1/(x+g-1))-g+1

 

위공식에 1-x 했을경우

 

 

 

g=(1+sqrt(5))/2   //황금비

y=(1/(x-g))+g

 

 

g=(1+sqrt(5))/2   //황금비

y=abs((1/(abs(x)-g))+g)*x/abs(x)

 

 

 

a=2

b=x*a-1

y=(b*abs(b))/a+1/a

 

 

a=2

b=1/a

c=x-b

d=abs(c)

y=sqrt(d)*c/d/sqrt(2)+b

정리가 다 안되었다

일단 sqrt(2)는 앞에 sqrt안에 넣을수 있을듯

 

 

y=sqrt(abs(x))*x/abs(x)

 

a=2

b=x*a-1

y=b*(b*b+1)/a*a+1/a

 

 

 

 

 

y=(sqrt(x)-sqrt(1-x)+1)/2

위와는 곡선모양이 조금 다르다

 

y=(sqrt(1-x)-sqrt(x)+1)/2

위에걸 좌우 뒤집음

 

 

y=x*x-x+1

 

y=-(x*x-x)

 

 

y=pow(x,1/x)

 

 

 

 

y=sqrt((x-0.5)*0.5/(x*x))

 

y=x*x+sqrt(x)

 

 

 

y=x*x-sqrt(x)+1

 

 

y=log(x)+1

 

 

 

y=log(x)*log(x)

 

 

 

y=(log(x)+1)*0.9

대각선 대칭처럼 보이지만 대칭은 아니다

 

 

 

특수한 함수들

sqrt(x*-x*x*-x) = x*x는 동일하다

동일해서 그래프가 겹치다보니 식별하기 쉽게 위의 파란색은 x*-x 로 했다

 

 

 

 

 

 

 

 

 

 

 

 

 

y=abs(1-abs(x))

 

y=-x+x/abs(x)

 

 

 

 

 

 

 

 

태그: 수학

'Unity > shader' 카테고리의 다른 글

유니티 스카이박스 관련  (0) 2023.01.16
Decal Shader  (0) 2022.01.13
shader pixel broken  (0) 2022.01.12
posted by 모카쨩
2022. 1. 13. 11:06

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2022. 1. 12. 12:32

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.


  • total
  • today
  • yesterday

Recent Post

저사양 유저용 블로그 진입