Microsoft MVP성태의 닷넷 이야기
Graphics: 8. Unity Shader - Texture의 UV 좌표에 대응하는 Pixel 좌표 [링크 복사], [링크+제목 복사]
조회: 17536
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 13개 있습니다.)
Graphics: 2. Unity로 실습하는 Shader
; https://www.sysnet.pe.kr/2/0/11607

Graphics: 3. Unity로 실습하는 Shader (1) - 컬러 반전 및 상하/좌우 뒤집기
; https://www.sysnet.pe.kr/2/0/11608

Graphics: 4. Unity로 실습하는 Shader (2) - 고로 셰이딩(gouraud shading) + 퐁 모델(Phong model)
; https://www.sysnet.pe.kr/2/0/11609

Graphics: 5. Unity로 실습하는 Shader (3) - 고로 셰이딩(gouraud shading) + 퐁 모델(Phong model) + Texture
; https://www.sysnet.pe.kr/2/0/11610

Graphics: 6. Unity로 실습하는 Shader (4) - 퐁 셰이딩(phong shading)
; https://www.sysnet.pe.kr/2/0/11611

Graphics: 7. Unity로 실습하는 Shader (5) - Flat Shading
; https://www.sysnet.pe.kr/2/0/11613

Graphics: 8. Unity Shader - Texture의 UV 좌표에 대응하는 Pixel 좌표
; https://www.sysnet.pe.kr/2/0/11614

Graphics: 9. Unity Shader - 전역 변수의 초기화
; https://www.sysnet.pe.kr/2/0/11616

Graphics: 10. Unity로 실습하는 Shader (6) - Mosaic Shading
; https://www.sysnet.pe.kr/2/0/11619

Graphics: 11. Unity로 실습하는 Shader (7) - Blur (평균값, 가우스, 중간값) 필터
; https://www.sysnet.pe.kr/2/0/11620

Graphics: 12. Unity로 실습하는 Shader (8) - 다중 패스(Multi-Pass Shader)
; https://www.sysnet.pe.kr/2/0/11628

Graphics: 13. Unity로 실습하는 Shader (9) - 투명 배경이 있는 텍스처 입히기
; https://www.sysnet.pe.kr/2/0/11631

Graphics: 19. Unity로 실습하는 Shader (10) - 빌보드 구현
; https://www.sysnet.pe.kr/2/0/11641




Unity Shader - Texture의 UV 좌표에 대응하는 Pixel 좌표

간단하게 예를 들어서, 0 ~ 1 사이로 정규화되어 있는 UV 좌표계에서 0.1에 해당하는 texture의 pixel(x,y) 위치를 알고 싶다는 것입니다. 이것은 UV 좌표계의 의미를 알면 유추해 낼 수 있습니다.

가령, 가로 1024 * 세로 768 이미지의 texture를 (0,0) ~ (1,1) UV 좌표로 매핑한 경우 다음과 같은 의미를 갖게 됩니다.

u    pixel
0 -> 0
1 -> 1024

v    pixel
0 -> 0
1 -> 768

따라서, 다음과 같은 비율로 알아낼 수 있습니다.

u:x = 1:1024
v:y = 1:768

만약 그중에 (0.1, 0.7) uv 좌표 값을 가지고 있다면 이것을 pixel 위치로 환산하면 다음과 같이 계산할 수 있습니다.

0.1:x = 1:1024
x = 1024 * 0.1 = 102.4
   = width of texture * u

0.7:y = 1:768
y = 768 * 0.7 = 537.6
   = height of texture * v

uv(0.1, 0.7) == xy(102.4, 537.6) ≈ (102, 538)


실제로 그런지 Unity에서 지구본을 texture로 사용했던 예제를 보겠습니다.

Unity로 실습하는 Shader
; https://www.sysnet.pe.kr/2/0/11607

Shader "My/basicShader"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
    }
    SubShader
    {
        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;
            };

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

그러니까, 위의 tex2D 함수는 2048 * 1024 크기의 지구 이미지를 texture로 사용했을 때, uv 좌표에 해당하는 texture의 컬러를 구해주고 있는 것입니다.

fixed4 frag(v2f i) : SV_Target
{
    fixed4 col = tex2D(_MainTex, i.uv);
    return col;
}

만약, 현재의 i.uv가 가리키고 있는 좌표보다 u 값으로 +10 pixel에 해당하는 컬러 값을 사용하고 싶다면 다음과 같이 하면 됩니다.

fixed4 frag(v2f i) : SV_Target
{
    float uPerX = 1.0 / 2048; // 1 / width
    float vPerY = 1.0 / 1024; // 1 / height

    float uOffset = 10 * uPerX;
    float vOffset = 0 * vPerY;

    float2 nextUVOffset = float2(uOffset, vOffset);
    fixed4 col = tex2D(_MainTex, i.uv + nextUVOffset);

    return col;
}

저렇게 하면, 지구본이 +10 픽셀만큼 회전한 것처럼 보입니다. 또는, u 값으로 +2048 pixel을 준다면 어떻게 될까요?

float uOffset = 2048 * xPerU;

결국 제자리로 오기 때문에 화면에는 아무런 변화가 없습니다.




그런데, shader 코드에 2048, 1024이라고 하드 코딩을 하는 것이 좀 그렇군요. ^^ 이것을 없애려면 Properties 영역으로 옮겨 변수 처리를 하면 됩니다. 물론 그래도 되지만, Unity에서는 "_TexelSize"라는 접미사를 붙이면 해당 텍스처의 width, height를 담고 있는 값을 알아서 전달해 줍니다.

예를 들어, 위의 코드에서는 텍스처 변수 명이 "_MainTex"였으므로 다음과 같이 선언해 주면 됩니다.

float2 _MainTex_TexelSize;

그리고 그 변수의 값은 각각 다음과 같이 설정이 됩니다.

Accessing shader properties in Cg/HLSL
; https://docs.unity3d.com/Manual/SL-PropertiesInPrograms.html

x contains 1.0/width
y contains 1.0/height
z contains width
w contains height

결국 이를 반영하면 다음과 같이 하드 코딩 없이 작성할 수 있습니다.

fixed4 frag(v2f i) : SV_Target
{
    float uPerX = _MainTex_TexelSize.x;
    float vPerY = _MainTex_TexelSize.y;

    float uOffset = 10 * uPerX; // x축으로 +10 pixel 위치
    float vOffset = 10 * vPerY; // y축으로 +10 pixel 위치

    float2 nextUVOffset = float2(uOffset, vOffset);
    fixed4 col = tex2D(_MainTex, i.uv + nextUVOffset);

    return col;
}

float2 UVtoXY(float2 uv, float2 texelSize)
{
    return float2(uv.x / texelSize.x, uv.y / texelSize.y);
}

float2 XYtoUV(float2 pos, float2 texelSize)
{
    return float2(pos.x * texelSize.x, pos.y * texelSize.y);
}




다음의 링크를 보면,

D3D이용 2D출력시 마법의 숫자 -0.5 에 대하여  
; http://blog.daum.net/gamza-net/16

실수 보정을 하는데 아마 이 때문인지 다음의 답글을 보면,

How to get precise pixel values form a Texture2D using uv coordinates.
; https://answers.unity.com/questions/1106031/how-to-get-precise-pixel-values-for-a-texture2d-us.html

(0.5를 빼지 않고) 더하는 것이 나옵니다.

u = x / width + 0.5 / width;
v = y / height + 0.5 / height;

pixel shader에서 저 작업이 필요한지는... 혹시 아시는 분은 덧글 부탁드립니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/21/2018]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12404정성태11/7/202010942.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202011005.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202011589.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010518VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207550오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011193.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/20209641오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/20209779.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208172VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209473오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20207899오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208372오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012510.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202010632디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010550.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/20209930오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202010657.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202010920Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20208651오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/20209912오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202010908.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208521오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010163VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207654오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010604.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010083.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...