源程序下载
一、建立空窗体
新建一个工程,添加引用,并导入名称空间。
加入一个设备对象变量:
private Microsoft.DirectX.Direct3D.Device device = null;
添加初始化图形函数,并在这里面对设备对象进行实例化:
public void InitializeGraphics()
{
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Flip;
presentParams.AutoDepthStencilFormat = DepthFormat.D16;
presentParams.EnableAutoDepthStencil = true;
device = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, presentParams);
}
当程序执行时,需要绘制场景,代码在这个函数里:
public void Render()
{
// 清空设备,并准备显示下一帧。
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black , 1.0f, 0);
// 设置照相机的位置
SetupCamera();
//开始场景
device.BeginScene();
if(meshLoaded)
{
mesh.Render(meshLoc);
}
device.EndScene();
//显示设备内容。
device.Present();
}
设置照相机的位置:
private void SetupCamera()
{
device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1.0f, 1000.00f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0.0f ,0.0f, 20.0f), new Vector3(0.0f,0.0f, 0.0f), new Vector3(0,1,0));
}
现在改变主函数,调用我们写的初始化函数,并显示场景:
[STAThread]
static void Main()
{
using (Form1 EarthForm = new Form1())
{
EarthForm.InitializeGraphics();
EarthForm.Show();
while(EarthForm.Created)
{
EarthForm.Render();
Application.DoEvents();
}
EarthForm.Dispose();
}
运行程序,会显示一个空的窗体。
二、加入地球:
在这一步里需创建一个3D网格对象,来作为要显示的地球,为此,在工程中新加入一个类Earth,此类可以包含所创建的网格对象的信息。
加入一些相关变量,含义见注释:
public class Earth : BaseEarth
{
private Material[] mMaterials; //保存材质
private Texture[] mTextures; //保存纹理
private Matrix locationOffset; //用来保存网格对象的相对位置
private Mesh mMesh = null; //三角形网格对象
private Device meshDevice; //需要显示在哪个设备上。
}
在构造函数中,把Device设备拷贝到私有成员变量,这样就可以在这个类的其它方法内使用它,另外就是把位置变量进行赋值:
public Earth(ref Device device, Matrix location): base(ref device)
{
meshDevice = device;
locationOffset = location;
}
下面这个函数是装入.X文件。
public bool LoadMesh(string meshfile)
{
ExtendedMaterial[] mtrl;
try