Unity 검색

셰이더 그래프를 활용한 실험: 적은 리소스로 더 많은 작업 수행하기

2021년 2월 25일 엔진 & 플랫폼 | 12 분 소요
Mountains
Mountains
다루는 주제
공유

Is this article helpful for you?

Thank you for your feedback!

물리적 기반 렌더링(PBR) 머티리얼 정보를 단일 텍스처 맵으로 압축한 후 컴팩트 셰이더에 레이어링하면 그래픽의 품질을 손상시키지 않고도 셰이더의 런타임 효율성을 개선할 수 있습니다. 아래의 실험을 확인해 보세요.

 

본 실험은 유니버설 렌더 파이프라인(URP)과 고해상도 렌더 파이프라인(HDRP)을 모두 지원하며, 최대의 학습 효과를 얻으려면 셰이더 그래프에 어느 정도 익숙해야 합니다. 셰이더 그래프를 처음 사용해본다면, 셰이더를 시각적으로 구현하는 방법을 소개하는 페이지와 세부 정보를 먼저 살펴보세요. 터레인과 유사한 환경에서 아트 에셋으로 작업하는 경우, 일반적으로 더 나은 블렌딩 결과물을 만들어 내기 위해 타일화 가능한 머티리얼의 다중 레이어가 선호됩니다. 그러나 다중 텍스처 샘플의 GPU 성능 비용과 레이어가 셰이더에 추가될 때마다 늘어나는 메모리 사용량은 일부 기기에서는 감당할 수 없는 수준이며, 일반적으로 비효율적입니다.

이 실험을 통해 목표하는 바는 다음과 같습니다.

  • 적은 리소스로 더 많은 작업 수행
  • 메모리 사용량 최소화 및 PBR 머티리얼을 표현하기 위한 텍스처 샘플링 축소
  • 셰이더 명령 최소화
  • 최소한의 스플랫맵/버텍스 컬러 채널로 레이어 블렌딩
  • 스플랫맵/버텍스 컬러의 기능을 확장

 

이 실험의 목표를 달성하는 과정에서 몇 가지 주의 사항이 요구됩니다. 각자 프로젝트의 요구 사항에 따라 더 중요한 것과 희생해도 괜찮은 부분을 결정해야 합니다.

 

1. 단일 텍스처로 압축된 PBR 머티리얼

레이어링하기 전에 PBR 머티리얼 압축에 관해 먼저 알아야 합니다. PBR 머티리얼에는 일반적으로 알베도(BaseColor), 평활도 마스크, 앰비언트 오클루전, 금속성, 노멀에 대한 파라미터가 정의되어 있습니다. 일반적으로 전체 다섯 가지 맵은 세 가지의 텍스처 맵으로 표현됩니다. 텍스처 사용량을 최소화하기 위해 이 실험에서는 금속성과 앰비언트 오클루전을 배제했습니다.

나머지 맵인 알베도, 평활도, 노멀 정의는 최소 두 가지의 텍스처 맵으로 나타내는 것이 일반적입니다. 이를 하나의 맵으로 줄이기 위해서는 채널별로 전처리가 필요합니다. 하나의 텍스처로 압축된 PBR 머티리얼의 최종 결과는 다음과 같습니다. 빨간색 = 노멀 정의#에 대한 dHdu(U 방향에서 derivative의 상대적 높이) 녹색 = 노멀 정의#에 대한 dHdv(V 방향에서 derivative의 상대적 높이) 파란색 = 알베도를 나타내는 선형 그레이스케일 셰이드(셰이더에서 색상 재구성) 알파 = 선형 평활도 맵(표준 평활도 맵) 참고: 텍스처는 sRGB가 선택 해제된 상태로 Unity에 임포트되며 BC7 형식으로 압축됩니다. 다른 플랫폼으로 이식할 경우에는 플랫폼에서 지원되는 4채널 텍스처 형식으로 전환하세요.

 

맵 프로세싱

 

알베도

알베도는 보통 RGB 텍스처로 정의되지만 바위, 모래, 진흙, 잔디와 같은 터레인 유형의 머티리얼은 컬러 팔레트가 제한적인 경우가 많습니다. 알베도를 그레이스케일 그레디언트로 저장한 다음 셰이더에서 컬러를 다시 매핑하는 방식으로 이 속성을 활용할 수 있습니다.

RGB 알베도를 그레이스케일 그레디언트로 변환하는 방법은 따로 정해진 것이 없습니다. 이 실험에서는 기존 알베도 맵 채널과 앰비언트 오클루전의 선택적 마스킹을 통해 그레이스케일 알베도를 만들었습니다. 셰이더 컬러를 재구성할 때 주요 색상을 일치시키려면 수동 조정을 고려해 보세요.

RampContrast, Highlight Color, DarkColor를 조절하여 알베도를 재구성합니다.

평활도

평활도는 PBR 머티리얼 정의에서 매우 중요한 요소로 평활도를 보다 정확하게 정의하기 위해 자체 채널이 마련되어 있습니다. 머티리얼의 배리에이션을 위해 간단한 멀티플라이어가 셰이더의 평활도에 추가되었습니다. (평활도 멀티플라이어를 건너뛰면 셰이더 명령을 줄일 수 있습니다.)

 

노멀 정의

 

노멀 맵은 표면의 세부적인 특징을 보여주는 데 중요합니다. 일반적인 PBR 머티리얼은 탄젠트 공간 노멀 맵을 사용합니다. 이 실험에서는 아래와 같은 이유로 표면 그레디언트 프레임워크를 사용하여 사전 변환된 derivative 맵을 선택했습니다. (자세한 정보는 Morten Mikkelsen의 표면 그레디언트 프레임워크 참조).

탄젠트 공간 노멀 맵을 derivative로 사전 변환하려면 이 Photoshop 액션 파일을 사용하세요.

사전 변환된 derivative 맵을 사용하면 다음과 같은 여러 가지 이점이 있습니다.

  • 셰이더에서 derivative 변환을 필요로 하는 표준 탄젠트 공간 노멀 맵에 비해 더 적은 명령을 사용하여 표면 그레디언트로 직접 변환할 수 있습니다.
  • 두 채널(dHdu 및 dHdv)에 저장할 수 있으므로 런타임에 메모리와 텍스처 캐시 사용량이 줄어듭니다.
  • 표면 그레디언트 프레임워크에서 노멀 재구성을 처리하므로(셰이더 명령을 더 적게 사용) 셰이더에서 탄젠트 공간 노멀 맵을 처리할 때 일반적으로 사용하는 파란색 채널 재구성이 필요하지 않습니다.
  • 블렌딩, 마스킹, 또는 텍스처의 강도를 줄이는 방식으로 Photoshop에서 조정할 경우 제대로 작동하며 재정규화가 필요하지 않습니다. 예를 들어 텍스처 강도를 줄이려면 RGB(128,128,0)에 맵을 블렌딩하면 됩니다.

표면 그레디언트 프레임워크와 관련하여 다음과 같은 추가적인 이점이 있습니다.

  • 노멀 범프 맵의 정보가 알베도 블렌드/합성과 같은 방식으로 셰이더에서 블렌딩 및 합성될 수 있으며 올바른 결과가 도출됩니다.
  • 간단하고 정확하게 범프 기여도를 늘리고 줄이고 반전할 수 있습니다.

하지만 탄젠트 공간 노멀 맵의 사전 변환된 derivative에도 다음과 같은 몇 가지 단점은 있습니다.

  • Photoshop 변환을 사용하는 경우, 8비트 텍스처로 정밀도의 균형을 맞추기 위해 노멀 정의가 45도 이상의 각도에서 고정됩니다.
  • 탄젠트 공간 노멀 맵으로 작업하는 데 익숙한 아티스트는 Photoshop을 통해 맵을 사전 변환해야 합니다.

참고: 45도 이상의 각도 고정은 셰이더 기반 derivative 변환에 적용되지 않습니다.

사용 사례에 따라 이 제한의 효과가 더 크거나 작을 수 있습니다. 이 실험에서는 45도 미만인 노멀 방향이 최종 결과에 눈에 띄게 부정적인 효과를 미치지 않습니다. 실제로 이 사용 사례에서는 극단적인 노멀 방향의 원치 않는 반사를 줄이는 방식으로 이점을 제공합니다.

사전 변환된 derivative 맵 텍스처와 탄젠트 공간 노멀 맵 텍스처의 비교

 

사전 변환된 derivative와 탄젠트 공간 노멀 맵 사이의 성능 테스트 차이. 구 모양 범프는 사전 변환된 derivative 맵의 45도 고정으로 인해 일부 아티팩트를 드러냅니다.

 

사전 변환된 derivative 맵을 표면 그레디언트로 다시 매핑하는 그래프

 

참고: 마스터 스택의 Fragment Normal Space에서 Tangent 대신 World로 설정되었는지 확인하세요.

전체 압축 해제 프로세스 

컴팩트 PBR 텍스처를 압축 해제하여 컬러 알베도, 평활도, 표면 그레디언트를 출력하는 전체 서브 그래프. 참고: 표면 그레디언트의 노멀 변환은 서브 그래프 외부에서 이루어지므로 UnpackedSubGraph 출력을 기반으로 머티리얼을 손쉽게 블렌딩할 수 있습니다.

압축 해제된 셰이더의 머티리얼 샘플. 

광원에 대한 각 머티리얼의 반응을 더 정확하게 보여주는 다양한 각도.

2. 머티리얼 레이어링

 

이 실험에서는 단일 채널 Remap의 계층 기반 레이어링 방식을 선택했습니다. 서브 그래프는 다섯 번의 선형 보간(베이스 포함, 레이어 여섯 개 형성)을 수행합니다. 다양한 방법으로 레이어 가중치를 블렌딩할 수 있습니다. 이 방식은 단일 벡터 입력이 단순하므로 실험 목표에 적합합니다. 따라서 여러 스플랫맵/버텍스 채널을 많이 사용하지 않고도 수많은 레이어링이 가능해집니다.

하지만 이 방법의 단점은 개별 레이어의 가중치를 제어할 수 없다는 점입니다. 블렌딩은 항상 이전 레이어에서의 전환을 통해 이루어집니다. 사용 사례에 따라 이 부분은 기존의 채널별 블렌딩에 비해 제한적인 요소로 작용할 수 있습니다.

 

단일 채널을 다시 매핑하여 여섯 개의 레이어를 나타내는 서브 그래프.

 

위에 표시된 서브 그래프는 계층 기반 블렌딩의 여섯 개 레이어를 사전 정의합니다. 더 많은 레이어를 만들기 위해서는 1을 원하는 블렌드된 레이어의 수에서 1을 뺀 수로 나누고 해당 값 범위를 기준으로 각 레이어를 다시 매핑하면 됩니다. 예를 들어 레이어가 아홉 개인 블렌드 머티리얼의 경우 각 레이어의 Remap 범위는 1/(9-1) = 0.125입니다.

 

레이어 최소 최대

100.125

20.125.25

3.25.375

4.375.5

5.5.625

6.625.75

7.75.875

8.8751

단일 채널을 여러 개로 나누므로 셰이딩 범위가 작아집니다.

블렌딩 특징을 보여주기 위해 컬러를 사용하여 테스트된 레이어링 방법.

 

하나의 버텍스 컬러(이 경우, 빨간색 채널)로 압축 해제된 머리티얼의 6개 레이어를 합성하는 머티리얼

 

참고: PBR 텍스처 3개를 블렌딩하는 것보다 셰이더 그래프에서 샘플로 채워진 PBR 머티리얼 하나의 레이어를 블렌딩하는 것이 더 간단합니다. 레이어 블렌딩은 계층 기반이므로 블렌딩 머티리얼을 설정하기 전에 먼저 레이어의 순서를 계획해 두는 것이 좋습니다.

3. 머티리얼의 기능 확장

레이어 블렌딩에는 채널이 하나만 필요하며(빨간색 버텍스 채널), 나머지 세 가지 버텍스 채널은 추가적인 기능을 제공합니다.

나머지 버텍스 채널을 사용하여 결과를 생성하는 최종 셰이더 그래프

 

이 실험에서는 Unity 에디터 내에서 Polybrush(패키지 관리자에서 제공)를 사용하여 버텍스 페인팅을 수행했습니다.

이 셰이더에 추천하는 버텍스 페인트 컬러 팔레트.

 

빨간색: 레이어 기여도에 가중치를 적용하는 데 사용됩니다.

빨간색 버텍스 채널 페인팅 데모

녹색: 노멀 범프 기여도를 뒤집거나 줄이거나 추가하기 위해 표면 그레디언트 속성을 설정합니다(-1과 1로 다시 매핑됨).

  • 0은 노멀 범프를 반전합니다(-1)
  • 0.5 값은 노멀 범프를 줄입니다(0)
  • 1은 노멀 범프를 원래 값으로 설정합니다(+1)

녹색 버텍스 채널 페인팅 데모

 

파란색: 물기가 있는 것처럼 보이기 위해 평활도와 표면 그레디언트 범프 스케일을 제어합니다

  • 0 = 변경 없음
  • 255 = 최대 평활도 및 평평한 노멀 맵(물기가 있는 것처럼 보임)

파란색 버텍스 채널 페인팅 데모

 

알파: 알베도 레이어의 가중치를 제어하며, 기여도를 표면 노멀의 Y축을 기준으로 하고 기본 컬러를 흰색으로 설정합니다. 평활도를 변경하지 않으며 기존 표면 레이어 평활도와 범프 속성을 활용합니다.

  • 0 = 눈 없음
  • 255 = 쌓인 눈

전체 레이어가 눈과 상호 작용하는 방식을 보여주기 위해 이전 채널과 결합된 알파 버텍스 채널 페인팅

서로 다른 버텍스 페인팅 채널이 결합된 결과:

프로젝트의 요구 사항에 따라 셰이더 블렌딩 방법과 여러 가지 버텍스 채널/스플랫맵 기능의 설정을 조정할 수 있습니다.

4. 성능 비교

이 실험의 목적은 리소스를 최소화하면서 셰이더 그래프의 기능을 확장하는 것이었습니다. 텍스처가 전처리되고 압축 해제되었는데, 그렇다면 런타임 효율성에는 어떤 결과가 있을까요? 성능 프로파일링은 이런 변화가 낳은 효율성을 보여줍니다. 

6개 레이어가 있는 컴팩트 블렌드 셰이더와 비교하기 위해 6개 레이어를 가진 표준 블렌드 셰이더가 생성되었습니다. 두 셰이더 모두 동일한 기능을 갖춘 동일한 블렌딩 방법을 사용하여 생성되었습니다. 주된 차이점은 스탠다드 셰이더에서는 단일 레이어를 표현하기 위해 세 가지의 서로 다른 텍스처를 사용한다는 것입니다. 프로파일링을 위해 대상 플랫폼의 유니버설 렌더 파이프라인을 사용하여 단일 메시가 블렌드 머티리얼과 함께 화면에 렌더링되었습니다.

모바일 메모리 및 성능 프로파일

모바일(Android)을 위한 텍스처 압축:

 

모바일용 1024×1024에서 알베도, 마스크, 노멀 맵을 사용하는 표준 PBR:

  • 6x 알베도 맵 ASTC 10×10 = 6x 222.4 KB
  • 6x 마스크맵 ASTC 8×8 = 6x 341.4 KB
  • 6x 노멀 맵 ASTC 8×8 = 6x 341.4 KB

총 텍스처 메모리 사용량 5.431 MB

 

모바일용 1024×1024에서 컴팩트 PBR:

  • 6x PackedPBR 텍스처 ASTC 8×8 = 6x 341.4 KB 

총 텍스처 메모리 사용량 2.048 MB

 

6개 레이어가 있는 컴팩트 머티리얼을 사용할 경우 모바일(Android)에서의 텍스처 메모리 소비량이 약 62% 감소되어, 절반 이상의 절감 효과가 있습니다. Adreno 630(Snapdragon 845) 탑재 모바일 Android/Vulcan, Snapdragon 프로파일 결과:

  • 런타임에서 텍스처 메모리 읽기 약 70% 감소.
  • 표준의 경우 렌더링에 9971020클럭 소요.
  • 컴팩트의 경우 렌더링에 6951439클럭 소요.

컴팩트 머티리얼은 화면상에서 약 30% 더 빠르게 렌더링됩니다.

Snapdragon Profiler의 프로파일링 결과입니다.

 

PC 메모리 및 성능 프로파일

1024×1024에서 알베도, 마스크, 노멀 맵을 사용하는 표준 PBR:

  • 6x 알베도 맵 DTX1 = 6x 0.7 MB
  • 6x 마스크맵 DXT5/BC7 = 6x 1.3 MB
  • 6x 노멀 맵 DXT5/BC7 = 6x 1.3 MB 총 텍스처 메모리 사용량 19.8 MB

 

1024×1024에서 컴팩트 PBR:

  • 6x PackedPBR 텍스처 BC7 = 6x 1.3 MB 

총 텍스처 메모리 사용량 7.8 MB 

 

6개 레이어를 사용하는 컴팩트 머티리얼의 경우 PC에서 텍스처 메모리 사용량이 60% 감소(절반 이상 절감)합니다.

 

2880×1800로 렌더링하는 Radeon 460 Pro 탑재 PC 노트북, RenderDoc 프로파일 결과:

  • 6개 레이어 표준 블렌드의 불투명 오브젝트 드로우: 5.186ms.
  • 6개 레이어 컴팩트 블렌드의 불투명 오브젝트 드로우: 3.632 ms. 컴팩트 머티리얼은 화면상에서 약 30%* 더 빠르게 렌더링됩니다. *RenderDoc 프로파일 값은 변동될 수 있으며, 30%는 샘플의 평균입니다.

 

2560×1440로 렌더링하는 nVidia GTX 1080 탑재 PC 데스크톱, nSight 프로파일 결과:

  • 6개 레이어 표준 머티리얼을 위한 불투명 오브젝트 렌더링: 0.87 ms
  • 6개 레이어 컴팩트 머티리얼을 위한 불투명 오브젝트 렌더링: 0.48 ms

컴팩트 머티리얼은 화면상에서 약 45% 더 빠르게 렌더링됩니다.

nSight의 프로파일링 결과.

 

콘솔 성능 프로파일

PlayStation 4에서 컴팩트 머티리얼을 사용하면60%의 메모리 절감효과가 있으며 PS4에서 PC와 동일한 압축을 사용하므로PC에서의 효과도 동일합니다.

 

1920x 1080에서의 PS4 기본 렌더링, Razer 프로파일 결과:

  • 6개 레이어 표준 머티리얼을 위한 불투명 오브젝트 렌더링: 2.11 ms
  • 6개 레이어 컴팩트 머티리얼을 위한 불투명 오브젝트 렌더링: 1.59 ms
  • 컴팩트 머티리얼은 화면상에서 약 24.5% 더 빠르게 렌더링됩니다.

PS4 Razor Profiler의 프로파일링 결과.

요약하자면, 6개 레이어를 가진 컴팩트 PBR 셰이더를 사용할 경우 성능상 이점이 있으며 상당한 양의 메모리가 절감됩니다. 머티리얼 압축 해제 시 더 많은 텍스처를 샘플링하는 경우보다 ALU가 더 많이 사용되므로 GPU 성능의 변화는 흥미롭지만 예상한 대로였습니다.

 

샘플 프로젝트 다운로드

셰이더 그래프와 서브 그래프가 포함된 이 샘플 프로젝트는 아래에서 다운로드할 수 있습니다. [여기에서 다운로드], Unity 2020.2.5f1, HDRP 10.3.1 [여기에서 다운로드], Unity 2020.2.5f1, URP 10.3. [여기에서 다운로드], 탄젠트 공간 노멀 맵을 derivative로 사전 변환하는 Photoshop 액션 파일.

 

요약

프로젝트의 유니버설 렌더 파이프라인 버전 스크린샷.

이 실험의 주요 구성 요소는 다음과 같습니다.

  • 커스텀 머티리얼을 위한 셰이더 그래프
  • 사전 변환된 derivative
  • 표면 그레디언트 프레임워크
  • 알베도 컬러 재구성
  • 단일 채널 레이어 블렌딩
  • UpVector 블렌딩 기법, 버텍스 채널 블렌딩을 통한 평활도 및 범프 제어

이 실험은 셰이더 그래프를 사용하여 아름다운 그래픽을 효율적으로 만드는 방법을 보여줍니다. 이 사례를 통해 아티스트와 개발자가 Unity 프로젝트에서 미적인 경계를 넓혀 가는 데 영감을 얻을 수 있기를 바랍니다.

 

작성자 소개

리날도 챤(테크니컬 아트 디렉터, R&D, Spotlight 팀)은 실시간 조명 및 렌더링 시스템에 대한 열정이 많은 실시간 3D 아티스트입니다.

PlayStation 2 시절에 해당 분야의 업무를 시작한 리날도는 텍스처링부터 최종 렌더링된 씬 생성에 이르기까지 포괄적인 아티스트 워크플로에 관한 지식을 10년 이상 쌓아 왔습니다. 유니티 테크놀로지스에 합류하기 전에는 BioShock 2The Bureau: XCOM Declassified마피아 III 같은 AAA 게임 개발에 참여했습니다.

현재는 Unity 렌더링 기능의 내부 개발과 표준 구축을 지원하는 한편 고객과의 협업을 바탕으로 프로젝트를 진행하여 고객이 진정한 잠재력을 실현하도록 지원하고 있습니다.

1. Single texture-packed PBR material

Before layering, the first thing you need to do is figure out the PBR material packing. PBR material typically comes with the parameters for Albedo (BaseColor), Smoothness mask, Ambient Occlusion, Metalness, and Normal defined.

Usually, all five maps are represented in three texture maps. To minimize texture usage, I decided to sacrifice Metalness and Ambient Occlusion for this experiment.

The remaining maps – Albedo, Smoothness and Normal Definition – would traditionally be represented by at least two texture maps. To reduce it to a single map requires some preprocessing of each individual channel.

Texture-packed PBR material

The final result of the PBR Material packed into a single texture. Red = dHdu (Derivatives Height Relative to the U direction) for Normal Definition#. Green = dHdv (Derivatives Height Relative to the V direction) for Normal Definition#. Blue = Linear Grayscale shade representing Albedo (color reconstructed in shader). Alpha = Linear Smoothness map (standard Smoothness map). Note: The texture is imported into Unity with sRGB unchecked and compressed with BC7 format. When porting to other platforms, switch to the platform-supported equivalent 4-channel texture format.

Processing the maps

Albedo

Albedo is normally defined as an RGB texture; however, many terrain-like materials (rock, sand, mud, grass, etc.) consist of a limited color palette. You can exploit this property by storing Albedo as a grayscale gradient and then color remapping it in the shader. 

There is no set method for converting the RGB albedo to a grayscale gradient. For this experiment, The grayscale Albedo was created through selective masking of the original Albedo map channels and Ambient occlusion; to match the prominent color in the shader color reconstruction, just eyeball any manual adjustments. 

Highlight and Dark coloring with ramp contrast adjustment for Albedo reconstruction.
Highlight and Dark coloring with ramp contrast adjustment for Albedo reconstruction.
Smoothness

Smoothness is considered very important for PBR material definition. To define smoothness more precisely, it has its own channel.

A simple multiplier was added to the smoothness in the shader for some variation in the material.

Smoothness multiplier
(You can choose to skip smoothness multiplier to reduce shader instruction.)
Normal definition

The Normal map is important for showing the detailed characteristics of a surface. A typical PBR Material uses a tangent space normal map. In this experiment, I chose a pre-converted derivatives map using surface gradient framework for the reasons below. (SeeMorten Mikkelsen’s surface gradient framework for more information).

To pre-convert tangent space normal maps to derivatives, use this Photoshop action.

Using a pre-converted Derivatives map has several advantages:

  • Can be directly converted to surface gradient, using fewer instructions than a standard tangent space normal map, which requires derivatives conversion in the shader
  • Can be stored in two channels (dHdu and dHdv), resulting in a lower memory and texture cache footprint in runtime 
  • Does not require blue channel reconstruction in the shader, which is typical when processing tangent space normal maps, since the surface gradient framework takes care of the normal reconstruction (fewer shader instructions)
  • Works correctly when adjusted in Photoshop – that is, by blending, masking or reducing intensity – and does not require renormalization. For example, to reduce intensity, simply blend the map against RGB(128,128,0).

In conjunction with the surface gradient framework, the advantages further include:

  • Normal bump information can be blended and composited in the shader the same way as albedo blend/composite, with the correct result.
  • Increasing, reducing and reversing bump contributions is trivial and accurate.

But pre-converted derivatives from tangent space normal map also have some disadvantages:

  • Using Photoshop conversion, normal definition gets clamped at an angle greater than 45 degrees, to balance precision in an 8-bit texture.
  • Artists are used to working with tangent space normal maps and require the maps to be pre-converted via Photoshop as part of their workflow.

Note: Clamping at an angle greater than 45 degrees does not apply to shader-based derivatives conversion.

Depending on your use case, the limitation may have a lesser or greater effect. In this experiment, a normal direction less than 45 degrees does not have a noticeable negative impact on the end result. In fact, in this case it provides a benefit by reducing unwanted reflection from extreme normal direction.

A comparison of a pre-converted derivatives map texture and a tangent space normal map texture.
A comparison of a pre-converted derivatives map texture and a tangent space normal map texture.
Stress test differences between pre-converted derivatives and tangent space normal map. Notice that the Spherical bump exhibits some artifact due to the 45-degree clamping in the pre-converted derivatives map.
Stress test differences between pre-converted derivatives and tangent space normal map. Notice that the Spherical bump exhibits some artifact due to the 45-degree clamping in the pre-converted derivatives map.
Graph
The graph to remap the pre-converted derivatives map to surface gradient.
Graph
The graph to convert surface gradient to normal definition.
Graph
Note: Make sure the Master stack fragment normal space accepts world space normal instead of the default tangent space normal.
The full unpacking process 
Graph

The complete Sub Graph to unpack the Compact PBR texture to output colored Albedo, smoothness and surface gradient.

Note: Surface gradient conversion to Normal is done outside the Sub Graph so that the material can be easily blended based on the output of the UnpackedSubGraph.

Materials
The materials sample from the unpacked shader.
Materials
Different angles to better showcase each material’s responses to light.

2. Layering the material

For this experiment, I chose a tier-based layering method on a single channel remap. The Sub Graph does five linear interpolations (plus the base, forming six layers).

There are many ways to blend layer weights. This method has the simplicity of a single vector input, which suits the experiment goal. This allowed lots of layering without burning through multiple channels in splat maps or vertex channels.

The drawback of this method is that you cannot control the weight of an individual layer’s contribution. The blending will always be a transition from the previous layer. Depending on the use case, this can be a limiting factor compared to a traditional per-channel blend.

Graph

The Sub Graph to remap a single channel to represent the six layers.

The Sub Graph shown above is predefined for six layers of tier-based blending. To create more layers, divide 1 by the desired number of layers blended, subtract 1, and then remap each layer based on that value range.

For example, for a nine-layer blend material, each layer remap range is 1/(9-1) = 0.125.

Be aware that as you divide the single channel into smaller portions, you have less shading range.

Layering
The layering method tested using color to showcase the blending characteristic.
Graph
The material to composite the 6 layers of the unpacked material with a single vertex color (in this case, the red channel).
Materials
Since layer blending is tier-based, it’s a good idea to plan the order of the layers before you set up the blend material.

3. Extending the functionality of material

Layer blending requires only a single channel (the red vertex channel). The remaining three vertex channels offer extra functionalities. The final Shader Graph produces results using the remaining vertex channels.

In this experiment, vertex painting was done inside Unity Editor using Polybrush (available from the Package Manager). Suggested Vertex Paint color palette for this shader.

Red: Used to weight the layer contribution. Red vertex channel painting demo

Green: Sets the surface gradient property, to flip, reduce or add normal bump contribution (remapped to -1 and 1).

  • 0 reverses the normal bump (-1)
  • 0.5 value zeroes out the normal bump (0)
  • 1 sets the normal bump to the original value (+1).

Green vertex channel painting demo

Blue: Controls smoothness and surface gradient bump scale to create a wet water look

  • 0 = no alteration
  • 255 = maximum smoothness and flat normal map (wet look)

Blue vertex channel painting demo

Alpha: Controls the weight of the Albedo layer, setting the base color to white,with the contribution based on the y axis of the surface normal. It does not alter the smoothness and takes advantage of the original surface layer smoothness and bump property.

  • 0 = no snow
  • 255 = solid snow

Alpha vertex channel painting combined with previous channels to showcase how the whole layers interact with the snow

The combined results of the different vertex painting channels:

You can adjust the shader blending method and the settings for the various vertex channel/splat map functionalities according to your project’s requirements.

4. Comparing performance

The purpose of this experiment was to extend the functionality of the Shader Graph while minimizing resources. The texture was preprocessed and unpacked, but is there a payoff in runtime efficiency?

Performance profiling shows the efficiencies these efforts produced. 

A standard six-layer blend shader was created for comparison with the compact six-layer blend shader. Both shaders were created using an identical blending method with the same functionalities. The main difference is that the standard shader uses three different textures to represent a single layer.

For profiling, a single mesh was rendered on screen with blend material using the Universal Render Pipeline in the targeted platform.

Mobile memory and performance profile

Texture compression for mobile (Android):

Standard PBR with Albedo, Mask and Normal map at 1024x1024 for mobile:

  • 6x Albedo map ASTC 10x10 = 6x 222.4 KB
  • 6x Mask map ASTC 8x8 = 6x 341.4 KB
  • 6x Normal map ASTC 8x8 = 6x 341.4 KB

Total Texture memory usage 5.431 MB

Compact PBR at 1024x1024 for mobile:

  • 6x PackedPBR Texture ASTC 8x8 = 6x 341.4 KB 

Total Texture memory usage 2.048 MB 

With the compact six-layer material, there is approximately 62% Less texture memory consumption on Mobile (Android), savings of more than half. Mobile Android/Vulcan with Adreno 630 (Snapdragon 845); Snapdragon profile results:

  • Approximately 70% less texture memory read in runtime.
  • Standard took 9971020 clocks to render.
  • Compact took 6951439 clocks to render.

Compact material renders on screen approximately 30% faster. Profiling result from Snapdragon Profiler.

PC memory and performance profile

Standard PBR with Albedo, Mask and Normal map at 1024x1024:

  • 6x Albedo map DTX1 = 6x 0.7 MB
  • 6x Mask map DXT5/BC7 = 6x 1.3 MB
  • 6x Normal map DXT5/BC7 = 6x 1.3 MB Total Texture memory usage 19.8 MB

Compact PBR at 1024x1024:

  • 6x PackedPBR Texture BC7 = 6x 1.3 MB 

Total Texture memory usage 7.8 MB 

The compact six-layer material uses 60% less texture memory consumption on PC (savings of more than half).

PC laptop with Radeon 460 Pro rendering at 2880x1800; RenderDoc profile results:

  • Draw Opaques for standard 6-layer blend: 5.186 ms.
  • Draw Opaques for compact 6-layer blend: 3.632 ms. Compact material renders on screen approximately 30%* faster. *RenderDoc profile value fluctuates; 30% is an average of samples.

PC desktop with nVidia GTX 1080 rendering at 2560x1440; nSight profile results:

  • Render Opaques for standard 6-layer material: 0.87 ms
  • Render Opaques for compact 6-layer material: 0.48 ms

Compact material renders on screen approximately 45% faster. Profiling results from nSight.

Console performance profile

On PlayStation 4, using compact material yields 60% memory savings, identical to that for PC as the PS4 uses the same compression.

PS4 base rendering at 1920x 1080; Razer profile results:

  • Render Opaques for standard 6-layer material: 2.11 ms
  • Render Opaques for compact 6-layer material: 1.59 ms

Compact material renders on screen approximately 24.5% faster.

Profiling result from PS4 Razor profiler.

In summary, using a compact six-layer PBR shader offers performance gain and significant memory savings. The variation of GPU performance is interesting but expected, as unpacking the material consumes more ALUs than sampling more textures.

Download the sample project

This sample project with Shader Graphs and Sub Graphs can be downloaded here:

[DOWNLOAD HERE], Unity 2020.2.5f1 with HDRP 10.3.1

[DOWNLOAD HERE], Unity 2020.2.5f1 with URP 10.3.1

[DOWNLOAD HERE], Photoshop action to pre-convert tangent space normal map to derivatives.

Takeaway

Screenshot from Universal Render Pipeline version of the project.

The main components of this experiment are:

  • Shader Graph for custom material
  • Pre-converted Derivatives
  • Surface gradient framework
  • Albedo color reconstruction
  • Single-channel layer blending
  • UpVector blend technique, smoothness and bump control via vertex channel blend

This experiment showcases how you can use Shader Graph to produce beautiful graphics that are also efficient. Hopefully, this example can inspire artists and developers to push aesthetic boundaries with their Unity projects.

About the author

Rinaldo Tjan (Technical Art Director, R&D, Spotlight Team) is a real-time 3D artist with an extreme passion for real-time lighting and rendering systems.

Having started his career in the PlayStation 2 days, he has more than a decade of end-to-end artist workflow knowledge, from texturing to final rendered scene creation. Prior to joining Unity Technologies, he helped deliver AAA games such as BioShock 2, The Bureau: XCOM Declassified, and Mafia III.

He currently works with Unity clients to help them augment their projects and realize their true potential using Unity, while helping drive the internal development and standards of Unity rendering features.

 

2021년 2월 25일 엔진 & 플랫폼 | 12 분 소요

Is this article helpful for you?

Thank you for your feedback!

다루는 주제