2017-10-16 15 views
1

Blender3D의 "컬러 램프"노드와 같은 기능을하는 쉐이더 기능이 있습니다. 이 입력으로 0과 1 사이의 유동을 취하고 지정된 순서 색상 임의 수의 혼합 인 색상을 출력한다 :컬러 램프 쉐이더 (cg/shaderlab)

blender3D 색 램프 여기
blender3D color ramp

내 코드 :

fixed4 ColorRamp(float factor){ 
      float positions[5] = {_Pos0, _Pos1, _Pos2, _Pos3, _Pos4}; 
      fixed4 colors[5] = {_Color0, _Color1, _Color2, _Color3, _Color4}; 

      fixed4 outColor = _Color0; 

      for(int i = 0; i <4; i++){ 

       if(factor >= positions[i] && factor <positions[i+1]){ 
        fixed localFactor = (factor - positions[i])/(positions[i+1] - positions[i]); 
        outColor = lerp(colors[i], colors[i+1], localFactor); 
       }else if (factor > positions [_NumColors-1]){ 
        outColor = colors[_NumColors -1]; 
       } 
      } 
      return outColor; 
     } 

작동합니다. 하지만 몇 가지 이유가 있습니다.

  1. 램프의 색상 수는 하드 코드되어 있습니다. Unity 에디터에서 그것들의 목록을 추가하는 것이 훨씬 더 좋을 것입니다.
  2. if/else 문. 나는 이것이 성능면에서 끔찍하고 피해야한다는 것을 이해합니다.
  3. 색상 배열은 함수에서 선언됩니다. 즉, 모든 조각에 대해 새로운 배열을 만들어야합니다 (필자는 생각합니다).

내 주요 질문은 첫 번째 질문입니다. 하드 코딩 된 값을 편집하지 않고 램프의 색상 수를 어떻게 바꿀 수 있습니까?

답변

0
  1. 불가능합니다. 셰이더가 자동으로 컴파일됩니다. 그리고 컴파일러는 순환을 지원하지 않습니다. 당신의 순환은 단지 통사론적인 설탕이고, 컴파일하는 동안 결정된 반복 횟수로 확장됩니다.
  2. 성능면에서/else는 그리 좋지 않습니다. 그것은 순환 적 복잡성을 증가시키기 때문에 테스트에 대해서만 나쁩니다.
  3. "속성"블록에서 배열을 선언 할 수 있습니다.

죄송하지만 속성 블록에서 배열을 사용하지 마십시오. 메소드 밖에서 선언 할 것입니다.

float positions[5]; 
fixed4 colors[5]; 

fixed4 ColorRamp(float factor){ 
    positions[0] = _Pos0; 
    positions[0] = _Pos2; 
    positions[0] = _Pos3; 
    positions[0] = _Pos4; 
    positions[0] = _Pos5; 

    colors[0] = _Color0; 
    colors[1] = _Color1; 
    colors[2] = _Color2; 
    colors[3] = _Color3; 
    colors[4] = _Color4; 

    fixed4 outColor = _Color0; 

    for(int i = 0; i <4; i++) 
    { 
     if(factor >= positions[i] && factor <positions[i+1]) 
     { 
      fixed localFactor = (factor - positions[i])/(positions[i+1] - positions[i]); 
      outColor = lerp(colors[i], colors[i+1], localFactor); 
     } 
     else if (factor > positions [_NumColors-1]) 
     { 
      outColor = colors[_NumColors -1]; 
     } 
    } 
    return outColor; 
} 

그러나 단합 scritpt에서 외부 배열을 초기화해야합니다.

float[] array = new float[] {1, 2, 3, 4, 5} 
material.SetFloatArray("positions", array); 
Vector4[] colors = new Vector4[] { new Vector4(), new Vector4(), new Vector4(), new Vector4(), new Vector4() }; 
material.SetVectorArray("colors", colors); 
+0

감사합니다 텍스처로! Property 블록에 배열을 선언하는 예제를 제공해 주시겠습니까? 유니티 에디터에서 배열을 전달할 때와 유니티 에디터에서 전달할 수있는 프로퍼티로 배열을 만들 때 문제가 발생했습니다. – dixiepig

0

쉬운 대답은 : 당신의 그라데이션 굽는