#include <metal_stdlib>
using namespace metal;
struct Vertex { float4 p; float4 n; float4 color; };
struct Uniforms { float4x4 matrix; float4 eye; float4 effect; };
struct Out { float4 clip [[position]]; float3 p; float3 n; float4 color; };
vertex Out crystalVertex(uint id [[vertex_id]], const device Vertex *v [[buffer(0)]], constant Uniforms &u [[buffer(1)]]) {
 Out o; float4 p=v[id].p; p.xyz += v[id].n.xyz*u.effect.y; o.clip=u.matrix*p; o.p=v[id].p.xyz; o.n=v[id].n.xyz; o.color=v[id].color; return o;
}
// HDR lighting environment. Broad sky, dark horizon and rectangular bright sources
// produce sharp reflected shapes; these are not painted onto the car's surface.
float3 environment(float3 d) {
 d=normalize(d);
 // Neutral studio horizon and broad softboxes provide readable moving reflections.
 float horizon=smoothstep(-.25,.15,d.z);
 float3 col=mix(float3(.028,.032,.04),float3(.26,.28,.31),horizon);
 float band=exp(-pow((d.z-.48)/.18,2.0));
 float key=pow(max(0.0,dot(d,normalize(float3(-.55,-.45,.7)))),9.0);
 float fill=pow(max(0.0,dot(d,normalize(float3(.65,.45,.35)))),16.0);
 return col+float3(1.6)*band+float3(3.4)*key+float3(1.8)*fill;
}
// Nearby studio strip gives flat metal panels a finite, moving reflection.
float3 metalEnvironment(float3 p,float3 d) {
 d=normalize(d);
 float3 c=float3(.035,.038,.043)+environment(d)*.12;
 // Broad finite softboxes, including a low side reflection so doors do not
 // collapse to black. The reflected bands move with the viewing angle.
 if(d.z>.025) {
  float2 q=(p+d*((5.0-p.z)/d.z)).xy;
  float stripe=exp(-pow((q.y+q.x*.26-.4)/.42,4.0))*exp(-pow(q.x/8.0,4.0));
  c+=float3(7.0)*stripe;
 }
 if(abs(d.y)>.025) {
  float plane=d.y>0?4.0:-4.0;
  float3 q=p+d*((plane-p.y)/d.y);
  float stripe=exp(-pow((q.z+q.x*.12+.25)/.72,4.0))*exp(-pow(q.x/8.0,4.0));
  c+=float3(4.5)*stripe;
 }
 return c;
}
// High-contrast lighting reserved for the clear crystal finish.
float3 crystalEnvironment(float3 d) {
 d=normalize(d);
 float3 c=mix(float3(.12,.16,.24),float3(.24,.32,.48),smoothstep(-.4,.8,d.z));
 float strip=exp(-pow((d.z-.38)/.028,2.0));
 float strip2=exp(-pow((dot(d,normalize(float3(.6,-.7,.4)))-.15)/.045,2.0));
 float key=pow(max(0.0,dot(d,normalize(float3(-.55,-.45,.7)))),48.0);
 float rim=pow(max(0.0,dot(d,normalize(float3(.65,.45,.35)))),70.0);
 float floorStrip=exp(-pow((d.z+.35)/.07,2.0));
 return c+float3(3.5)*floorStrip+float3(10.0)*strip+float3(5.0)*strip2+float3(22.0)*key+float3(14.0)*rim;
}
float4 shadeSurface(Out in, constant Uniforms &u, texture2d<float> brushedNormal) {
 float3 n=normalize(in.n),incident=normalize(in.p-u.eye.xyz);
 if(dot(n,incident)>0)n=-n;
 int finish=int(u.eye.w+.1),part=int(in.color.w+.1);
 // Windows and tires share the selected body finish.
 part=0; // Every surface shares its car finish.
 float3 col;
 float opacity=1.0;
 float time=u.effect.x;
 if(part==3) col=float3(5.0,3.4,1.25);
 else if(part==5) col=float3(3.2,.018,.025);
 else if(part==2 && finish!=3) {
  float facing=saturate(-dot(incident,n));
  float reflectance=.035+.24*pow(1-facing,5.0);
  col=float3(.012,.019,.026)+environment(reflect(incident,n))*reflectance;
 }
 else if(part==1) {
  float diffuse=.35+.65*max(0.0,dot(n,normalize(float3(-.3,-.4,1))));
  col=float3(.017,.018,.019)*diffuse+environment(reflect(incident,n))*.004;
 }
 else if(part==4) {
  col=float3(.018,.022,.027)+environment(reflect(incident,n))*.035;
 }
 else if(part==6) {
  col=environment(reflect(incident,n))*float3(.62,.65,.70);
 }
 else if(finish==3) {
  // These are the actual flat normals of the mirrored, crowned Blender panels.
  // No screen-space tiles or artificial replacement facet normals.
  float3 facet=n;
  float3 t=normalize(cross(n,abs(n.z)<.9?float3(0,0,1):float3(0,1,0)));
  float seed=dot(float3(in.p.x,abs(in.p.y),in.p.z),float3(17.13,41.71,9.2));
  float3 r=reflect(incident,facet);
  float3 spectrum=float3(crystalEnvironment(r+t*.13).r,crystalEnvironment(r).g,crystalEnvironment(r-t*.13).b);
  float fr=.17+.83*pow(1-saturate(-dot(incident,facet)),5.0);
  float3 back=normalize(-n+t*.48);
  float3 inner=float3(
    crystalEnvironment(reflect(refract(incident,facet,1.0/2.36),back)).r,
    crystalEnvironment(reflect(refract(incident,facet,1.0/2.417),back)).g,
    crystalEnvironment(reflect(refract(incident,facet,1.0/2.49),back)).b);
  float3 prism=.5+.5*cos(seed+float3(0,2.1,4.2));
  // Stationary, isolated glints. Time changes brightness, never position;
  // a spatial sine wave here creates moving stripes across every facet.
  float2 sparkUV=(abs(n.z)>.6?float2(in.p.x,abs(in.p.y)):float2(in.p.x,in.p.z))*3.0;
  float2 cell=floor(sparkUV);
  float hash=fract(sin(dot(cell,float2(127.1,311.7)))*43758.5453);
  float other=fract(sin(dot(cell,float2(269.5,183.3)))*43758.5453);
  float2 center=.25+.5*float2(hash,other);
  float2 delta=fract(sparkUV)-center;
  float2 pixelWidth=fwidth(sparkUV);
  float radius=max(.028,max(pixelWidth.x,pixelWidth.y)*.65);
  float spot=exp(-dot(delta,delta)/(2*radius*radius))*(.028*.028)/(radius*radius);
  float pulse=pow(.5+.5*sin(time*.75+hash*31.0),12.0);
  float sparkle=spot*pulse*step(.8,hash)*pow(saturate(dot(r,normalize(float3(-.5,-.4,.7)))),8.0);
  col=spectrum*(.8+fr*1.7)+inner*.72+sparkle*float3(8.0);
  opacity=part==2?.84:.94;

 }else {
  float3 tint=finish==0?float3(.72,.26,.075):finish==1?float3(.91,.93,.96):float3(1.0,.56,.075);
  // The same baked normal map embedded in the Blender/glTF materials.
  constexpr sampler brushSampler(filter::linear,mip_filter::linear,address::repeat);
  float2 uv=in.color.xy;
  float3 dpdx=dfdx(in.p),dpdy=dfdy(in.p);
  float2 duvdx=dfdx(uv),duvdy=dfdy(uv);
  float determinant=duvdx.x*duvdy.y-duvdx.y*duvdy.x;
  if(abs(determinant)>.00000001) {
   float3 tangent=(dpdx*duvdy.y-dpdy*duvdx.y)/determinant;
   tangent=normalize(tangent-n*dot(n,tangent));
   float3 bitangent=(dpdy*duvdx.x-dpdx*duvdy.x)/determinant;
   float handedness=dot(cross(n,tangent),bitangent)<0?-1.0:1.0;
   bitangent=cross(n,tangent)*handedness;
   float3 mapNormal=brushedNormal.sample(brushSampler,uv).xyz*2-1;
   n=normalize(tangent*mapNormal.x*.08+bitangent*mapNormal.y*.08+n*mapNormal.z);
  }
  float3 reflected=reflect(incident,n);
  // Mirror polish shared by all three metals.
  float blur=.002;
  float3 tangent=normalize(cross(n,abs(n.z)<.9?float3(0,0,1):float3(0,1,0)));
  float3 bitangent=normalize(cross(reflected,tangent));
  float3 env=metalEnvironment(in.p,reflected)*.28
    +(metalEnvironment(in.p,reflected+tangent*blur)+metalEnvironment(in.p,reflected-tangent*blur)
    +metalEnvironment(in.p,reflected+bitangent*blur)+metalEnvironment(in.p,reflected-bitangent*blur))*.18;

  float facing=saturate(-dot(incident,n));
  float3 fresnel=mix(tint,float3(1.0),pow(1-facing,5.0));
  col=env*fresnel*1.5+tint*.008;

 }
 col=col/(1.0+col);col=pow(max(col,0.0),float3(1.0/2.2));
 return float4(col,opacity);
}

fragment float4 crystalFragment(Out in [[stage_in]], constant Uniforms &u [[buffer(1)]], texture2d<float> brushedNormal [[texture(0)]]) { return shadeSurface(in,u,brushedNormal); }

// Extract actual bright surface pixels for the quarter-resolution bloom buffer.
fragment float4 bloomMaskFragment(Out in [[stage_in]], constant Uniforms &u [[buffer(1)]], texture2d<float> brushedNormal [[texture(0)]]) {
 float4 c=shadeSurface(in,u,brushedNormal);
 float bright=max(c.r,max(c.g,c.b));
 return float4(c.rgb*smoothstep(.60,.95,bright),1);
}
struct ScreenOut { float4 clip [[position]]; float2 uv; };
vertex ScreenOut bloomScreenVertex(uint id [[vertex_id]]) {
 const float2 corners[3]={float2(-1,-1),float2(3,-1),float2(-1,3)};
 ScreenOut o;o.clip=float4(corners[id],0,1);o.uv=float2((corners[id].x+1)*.5,(1-corners[id].y)*.5);return o;
}
fragment float4 bloomBlurFragment(ScreenOut in [[stage_in]], texture2d<float> tex [[texture(0)]], constant float2 &direction [[buffer(0)]]) {
 constexpr sampler smp(filter::linear,address::clamp_to_edge);
 // Contiguous Gaussian samples prevent visible shifted copies of the car.
 float4 c=tex.sample(smp,in.uv)*0.0446149999;
 c+=(tex.sample(smp,in.uv+direction*1.49537050)+tex.sample(smp,in.uv-direction*1.49537050))*0.0878673306;
 c+=(tex.sample(smp,in.uv+direction*3.48919921)+tex.sample(smp,in.uv-direction*3.48919921))*0.0826231723;
 c+=(tex.sample(smp,in.uv+direction*5.48303121)+tex.sample(smp,in.uv-direction*5.48303121))*0.0739598153;
 c+=(tex.sample(smp,in.uv+direction*7.47686838)+tex.sample(smp,in.uv-direction*7.47686838))*0.0630244762;
 c+=(tex.sample(smp,in.uv+direction*9.47071258)+tex.sample(smp,in.uv-direction*9.47071258))*0.0511260312;
 c+=(tex.sample(smp,in.uv+direction*11.46456567)+tex.sample(smp,in.uv-direction*11.46456567))*0.0394815541;
 c+=(tex.sample(smp,in.uv+direction*13.45842952)+tex.sample(smp,in.uv-direction*13.45842952))*0.0290245581;
 c+=(tex.sample(smp,in.uv+direction*15.45230594)+tex.sample(smp,in.uv-direction*15.45230594))*0.0203121590;
 c+=(tex.sample(smp,in.uv+direction*17.44619677)+tex.sample(smp,in.uv-direction*17.44619677))*0.0135321096;
 c+=(tex.sample(smp,in.uv+direction*19.44010381)+tex.sample(smp,in.uv-direction*19.44010381))*0.0085821027;
 c+=(tex.sample(smp,in.uv+direction*21.43402885)+tex.sample(smp,in.uv-direction*21.43402885))*0.0051813212;
 c+=(tex.sample(smp,in.uv+direction*23.42797364)+tex.sample(smp,in.uv-direction*23.42797364))*0.0029778699;
 return c;
}
// The isolated car pass already contains premultiplied surface color and glow.
fragment float4 carOverlayFragment(ScreenOut in [[stage_in]], texture2d<float> tex [[texture(0)]]) {
 constexpr sampler smp(filter::linear,address::clamp_to_edge);
 return tex.sample(smp,in.uv);
}
fragment float4 bloomCompositeFragment(ScreenOut in [[stage_in]], texture2d<float> tex [[texture(0)]], texture2d<float> sharp [[texture(1)]], constant Uniforms &u [[buffer(1)]]) {
 constexpr sampler smp(filter::linear,address::clamp_to_edge);
 int finish=int(u.eye.w+.1);
 float power=finish==3?.4:.22;
 float3 spill=max(float3(0),tex.sample(smp,in.uv).rgb-sharp.sample(smp,in.uv).rgb*.85);
 float outside=1-sharp.sample(smp,in.uv).a;
 return float4(spill*power*5.0*outside,0);
}

// Retained ground light spill; the silhouette itself uses blurred highlight bloom.
vertex Out glowGroundVertex(uint id [[vertex_id]], constant Uniforms &u [[buffer(1)]]) {
 const float2 corners[6]={float2(-1,-1),float2(1,-1),float2(-1,1),float2(-1,1),float2(1,-1),float2(1,1)};
 Out o; float2 c=corners[id]; o.p=float3(c,0);o.n=float3(0,0,1);o.color=0;
 float g=u.effect.z>0.01?u.effect.z:1.0;
 o.clip=u.matrix*float4(c.x*6.8*g,c.y*4.05*g,.012,1); return o;
}
fragment float4 glowGroundFragment(Out in [[stage_in]],constant Uniforms &u [[buffer(1)]]) {
 int finish=int(u.eye.w+.1);
 float falloff=exp(-dot(in.p.xy,in.p.xy)*4.5)*(1-smoothstep(.7,1.0,length(in.p.xy)));
 float3 tint=finish==0?float3(1,.35,.06):finish==1?float3(.6,.8,1):finish==2?float3(1,.62,.08):float3(.55,.8,1);
 float strength=finish==3?.46:.29;
 return float4(tint,falloff*strength*5.0*.4);
}
