|
|
using System;
using System.Drawing;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace WindowsApplication1
{
/// <summary>
/// D3D 的摘要说明。
/// </summary>
public class D3D
{
public D3D()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
private Device device=null;
private Mesh mesh=null;
private Material [] meshMaterials=null;
private Texture [] meshTextures;
private float angle=0.0f;
public bool Init(IntPtr handle)
{
PresentParameters pp =new PresentParameters();
pp.Windowed=true;
pp.SwapEffect=SwapEffect.Discard;
pp.AutoDepthStencilFormat=DepthFormat.D16;
pp.EnableAutoDepthStencil=true;
try
{
device=new Device(0,DeviceType.Hardware,handle,CreateFlags.SoftwareVertexProcessing,pp);
return true;
}
catch
{
return false;
}
LoadMesh("Loopy.X");
}
public void LoadMesh(string file)
{
ExtendedMaterial[] mtrl;
mesh=Mesh.FromFile(file,MeshFlags.Managed,device,out mtrl);
//if have any Material store them
if((mtrl!=null)&&(mtrl.Length>0))
{
meshMaterials=new Material[mtrl.Length];
meshTextures=new Texture[mtrl.Length];
//store each Material and Texture
for(int i=0;i<mtrl.Length;i++)
{
meshMaterials=mtrl.Material3D;
if((mtrl.TextureFilename!=null)&&(mtrl.TextureFilename!=string.Empty))
{
meshTextures=TextureLoader.FromFile(device,mtrl.TextureFilename);
}
}
}
}
public void SetCamera()
{
this.device.Transform.Projection=Matrix.PerspectiveFovLH((float)Math.PI/4,1.0f,1.0f,10000.0f);
this.device.Transform.View=Matrix.LookAtLH(new Vector3(0,0, 50.0f), new Vector3(), new Vector3(0,1,0));
this.device.Lights[0].Type=LightType.Directional;
this.device.Lights[0].Diffuse=Color.White;
this.device.Lights[0].Direction=new Vector3(0,-1,-1);
this.device.Lights[0].Update();
this.device.Lights[0].Enabled=true;
}
public void Render()
{
this.device.Clear(ClearFlags.Target|ClearFlags.ZBuffer,Color.CornflowerBlue,1.0f,0);
SetCamera();
this.device.BeginScene();
this.DrawMesh(angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle / (float)Math.PI / 4.0f, 0.0f, 0.0f, 0.0f);
this.device.EndScene();
this.device.Present();
}
public void DrawMesh(float yaw,float pitch,float roll,float x,float y,float z )
{
angle+=0.1f;
this.device.Transform.World=Matrix.RotationYawPitchRoll(yaw,pitch,roll)*Matrix.Translation(x,y,z);
for(int i=0;i<meshMaterials.Length;i++)
{
this.device.Material=meshMaterials;
this.device.SetTexture(0,meshTextures);
mesh.DrawSubset(i);
}
}
public void DisposeD3D()
{
if(this.device!=null)
{
this.device.Dispose();
}
}
}
}
一个工程中导入模型的D3D.CS文件。请问为什么调试运行时出现:
未处理的“System.NullReferenceException”类型的异常出现在 WindowsApplication1.exe 中。
其他信息: 未将对象引用设置到对象的实例。
请问怎么办
谢谢 |
|