
import { Texture } from "../../2d/texture";
import { RenderSideType } from "./BaseMaterial";
import { ShaderMaterial, UniformType } from "./ShaderMaterial";


const skyboxVertexShader =
    `precision mediump float;
attribute vec3 aPosition;

uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;
uniform mat4 uModelMatrix;

varying vec3 vWorldPosition;

void main() {
    vWorldPosition = normalize( ( uModelMatrix * vec4( aPosition, 0.0 ) ).xyz );

    gl_Position = uProjectionMatrix* uViewMatrix * uModelMatrix * vec4( vec3( aPosition ), 1.0 );

    gl_Position.z = gl_Position.w;
}`;
const skyboxFragmentShader =
    `precision mediump float;
    varying vec3 vWorldPosition;
    uniform sampler2D map;
void main() {
    vec2 uv;
    //1/PI
    uv.y = 0.5 - asin( clamp( vWorldPosition.y, - 1.0, 1.0 ) ) * 0.31830988618;
    //1/PI/2
    uv.x = atan( vWorldPosition.z, vWorldPosition.x ) * 0.15915494 + 0.5;
    gl_FragColor = texture2D( map, uv);
}`;
/**
 * 天空盒材质，由于暂时用球做天空盒，所以side设置背面，对应的着色器有修改，深度值最大，且相机距离不影响天空盒
 * 还有问题，再说
 */
export class SkyboxMaterial extends ShaderMaterial {
    constructor() {
        super(skyboxVertexShader, skyboxFragmentShader, {
            map: { type: UniformType.texture, value: Texture.WHITE },
        });
        this._instanceType = "SkyboxMaterial";
        this.side =RenderSideType.BackSide
    }
    get map() {
        return this.uniforms.map.value;
    }
    set map(v: Texture) {
        this.uniforms.map.value = v;
    }
}