float4 global_ambient;
float4 light_color;
float4 Ka;
float4 Ks;
float4 base_color;
float4 Kd;
float4 light_pos;
float noise_amplitude;
float sharpness;
float vein_frequency;
float4 vein_color;
sampler noise_volume;
float4 mix(float4 a, float4 b, float blendFactor)
{
   return lerp(b, a, blendFactor);  // a * blendFactor + b * (1-blendFactor);
}

float4 noise (float4 x)
{
    return tex3D (noise_volume, x);
}

float4 snoise (float4 x)
{
    return 2.0f * tex3D (noise_volume, x) - 1.0f;
}


float4 ambient(void)
{
   return global_ambient;
}

float4 soft_diffuse(float3 Neye, float3 Peye)
{
   // Compute normalized vector from vertex to light in eye space  (Leye)
   float3 Leye = (light_pos - Peye) / length(light_pos - Peye);

   float NdotL = dot(Neye, Leye) * 0.5f + 0.5f;

   // N.L
   return float4(NdotL, NdotL, NdotL, NdotL);
}


float4 specular(float3 NNeye, float3 Peye)
{
    // Compute normalized vector from vertex to light in eye space  (Leye)
    float3 Leye = (light_pos - Peye) / length(light_pos - Peye);

    // Compute Veye
    float3 Veye = -(Peye / length(Peye));

    // Compute half-angle
    float3 Heye = (Leye + Veye) / length(Leye + Veye);

    // Compute N.H
    float NdotH = clamp(dot(NNeye, Heye), 0.0f, 1.0f);

    float NdotH_2  = NdotH    * NdotH;
    float NdotH_4  = NdotH_2  * NdotH_2;
    float NdotH_8  = NdotH_4  * NdotH_4;
    float NdotH_16 = NdotH_8  * NdotH_8;
    float NdotH_32 = NdotH_16 * NdotH_16;

    return NdotH_32 * NdotH_32;
}


float4 hlsl_veinedmarble (float4 P : TEXCOORD0, float3 Peye : TEXCOORD1, float3 Neye : TEXCOORD2) : COLOR
{
   float i, turb, freq, j, turbsum;

   float4 PP = P + noise_amplitude * noise(P);

   // Now calculate the veining function for the lookup area
   turbsum = 0;
   freq = 1;
   PP *= vein_frequency;
   for (i = 0;  i < 2;  i++)
   {
      turb = abs (snoise (PP));
      turb = pow (smoothstep (0.8, 1, 1 - turb), sharpness) / freq;
      turbsum += (1-turbsum) * turb;
      freq *= 3;
      PP *= 3;
   }

   // Blend between the two colors
   float4 Ct = mix (vein_color, base_color, turbsum);
     
   return light_color * (Ct * ( Ka*ambient() + Kd * soft_diffuse(Neye, Peye)) + 
          Ks * specular(normalize(Neye), Peye));

}



