Texture2D<float4> _StarsTex;
float _HaloThreshold;
float _MaxHalo;
float _StarScale;
float _HaloBrightness;

half _StarsExposure;

#ifdef ON_QUEST
#define MAX_STAR_SIZE 2
#else
#define MAX_STAR_SIZE 8
#endif
#define TEX_WIDTH 4096
#define TEX_HEIGHT 2048

half3 starPass(float3 rd) {
	if(_StarsExposure < 0.001) return 0;
	//Star pass
	half3 col = 0;
	{
		float2 uv;
		uv.y = acos(rd.y) / UNITY_PI;
		uv.x = (atan2(rd.z, rd.x) + UNITY_PI) / 2 / UNITY_PI;

		uint2 pixel_base;
		pixel_base.x = (uint)(uv.x * TEX_WIDTH);
		pixel_base.y = (uint)(uv.y * TEX_HEIGHT);

		int star_width = (int)(MAX_STAR_SIZE * (1 + abs(tan((uv.y - 0.5) * UNITY_PI))));
		if(star_width < 0 || star_width >= 256) return 0;

		float2 baseLL = float2(uv.y * UNITY_PI - UNITY_PI * 0.5, uv.x * UNITY_PI * 2 - UNITY_PI);

		for(int i = 0; i < star_width; i++) {
			for(int j = 0; j < MAX_STAR_SIZE; j++) {
				uint2 localuv = pixel_base + uint2(i - star_width / 2 + 1, j - MAX_STAR_SIZE / 2 + 1);
				localuv.x %= TEX_WIDTH;
				if(localuv.x < 0) localuv.x += TEX_WIDTH;
				float4 test = _StarsTex[localuv];
				if(test.a <= 0) continue;
				float2 pixelLL = float2((float)localuv.y / TEX_HEIGHT * UNITY_PI - UNITY_PI * 0.5, (float)localuv.x / TEX_WIDTH * UNITY_PI * 2 - UNITY_PI);
				float gcdist = gcDistance(baseLL, pixelLL);
				gcdist /= _StarScale;
				float magnitude = exp(test.a * 7) - 1;
				float brightness = min(1, magnitude);
				float dotRadius = 4000;
				brightness *= max(0, 1 - gcdist * dotRadius);
				col += test.rgb * brightness;
				#ifndef ON_QUEST
				if(magnitude >= _HaloThreshold) {
					float haloStr = min(1, (magnitude - _HaloThreshold) / (_MaxHalo - _HaloThreshold));
					col += test.rgb * _HaloBrightness * biasFunction(max(0, 1 - gcdist * (1000 + (1 - haloStr) * 2000)), 0.01) * (1 - brightness);
				}
				#endif
			}
		}
	}
	col *= _StarsExposure;
	return col;
}
