Create a SkyBox with a shader

Introduction

A Skybox is a standard technique to render a background, visible in all directions. This backdrop is not part of the playing area, but provides 'filler' images for sky and horizon.

The skybox is often rendered as a textured unit cube centered on the viewpoint. In order not to occlude everything else in the scene, the Depthbuffer is turned off during rendering of a skybox. Skyboxes behave as if their faces were infinitely far away

A basic skybox can be rendered by attaching 6 textures (top, bottom, front, right and left) to a cube.

Shader model 2.0 provides support for a cube texture, this can be used to easily implement a skybox.

Cube textures are 6 sided textures, normally stored in .dds format. DDS files can be created with the DirectX texture tool (See the DirectX SDK utilities). These textures are accessed not by texture coordinates, but by direction.

A vector from the viewpoint to a point on the surface of the cube, is used to determine the texture at that point on the cube.

struct VS_SKY_OUTPUT{
	vector pos:POSITION;
	float3 dir:TEXCOORD0; // use a texture coord to pass the  direction vector
};


VS_SKY_OUTPUT vs_main_Skybox(vector pos:POSITION){
	VS_SKY_OUTPUT Out;
	
	//center the box to the eye position	
	Out.pos=mul(float4(view_position+pos.xyz,1),view_proj_matrix);
	
	// the direction vector is the same as the original position vector (because it is a unit cube)	
	Out.dir=pos.xyz;
	
	return Out;
}


vector ps_main_Skybox(float3 dir:TEXCOORD0):COLOR
{
	// the the cube texture in the interpolated direction for the pixel


	return texCUBE(textureSampler,dir);
	
	
}
   
technique SkyBox{
	pass P0
	{
		ZENABLE = FALSE; // don't write to the depth buffer
      CULLMODE = NONE; // don't cull
	    vertexShader = compile vs_2_0 vs_main_Skybox();
      pixelShader = compile ps_2_0 ps_main_Skybox();

	}
}

 

This project demonstrates the use of a skybox, with a skybox class.