using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;
namespace 包围体
{
public partial class Form1 : Form
{
private Device device = null;
private CustomVertex.PositionTextured[] vertics;//点集合,用来绘制四边形
private float angleY = 0.1f;//绕y轴旋转变量
private Vector3 cameraPosition = new Vector3(8, 15, 8);//摄像机位置
private Vector3 cameraTarget = new Vector3(10, 10, 10);
private Vector3 camereUpVector = new Vector3(0, 1, 0);
private Mesh mesh;
private Material meshMaterial1;
private Material meshMaterial2;
// Texture texture;//图片纹理
/// <summary>
/// 是否暂停
/// </summary>
bool pause = false;
public Form1()
{
InitializeComponent();
} /// <summary>
/// 实例化device,在progress里调用
/// </summary>
/// <returns></returns>
public bool InitializeGraphics()
{
try
{
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;//窗口显示
presentParams.SwapEffect = SwapEffect.Discard;//后备缓存的交换方式
presentParams.EnableAutoDepthStencil = true;//自动深度测试
presentParams.AutoDepthStencilFormat = DepthFormat.D16;//缓冲区单元为16位二进制数
device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
device.DeviceReset += new EventHandler(this.OnResetDevice); this.OnCreateDevice(device, null);
this.OnResetDevice(device, null);
}
catch (DirectXException)
{
return false;
}
return true; }
public void OnResetDevice(object sender, EventArgs e)
{
VertexDeclaration();
device.Lights[0].Type = LightType.Directional;
device.Lights[0].Direction = new Vector3(0, 0, 1);
device.Lights[0].Diffuse = Color.Red;
device.Lights[0].Ambient = Color.Cyan;
device.Lights[0].Enabled = true;
device.Lights[0].Update();
} public void OnCreateDevice(object sender, EventArgs e)
{
// texture = TextureLoader.FromFile(device, "..\\..\\CTGU.jpg");
device.SamplerState[0].MagFilter = TextureFilter.Anisotropic;
mesh = Mesh.Teapot(device);
meshMaterial1 = new Material();
meshMaterial1.Diffuse = Color.White;
meshMaterial1.Ambient = Color.Green;
meshMaterial2 = new Material();
meshMaterial2.Diffuse = Color.White;
meshMaterial2.Ambient = Color.Blue;
} //生成点集合
private void VertexDeclaration()
{
vertics = new CustomVertex.PositionTextured[4];
vertics[0].Position = new Vector3(9, 9, 10);
vertics[0].Tu = 0;
vertics[0].Tv = 1f;
vertics[1].Position = new Vector3(9, 11, 10);
vertics[1].Tu = 0;
vertics[1].Tv = 0;
vertics[2].Position = new Vector3(11, 11, 10);
vertics[2].Tu = 1f;
vertics[2].Tv = 0;
vertics[3].Position = new Vector3(11, 9, 10);
vertics[3].Tu = 1f;
vertics[3].Tv = 1f;
} //设置视角
private void SetCamera()
{
device.Transform.View = Matrix.LookAtLH(cameraPosition, cameraTarget, camereUpVector);
device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, 1.33f, 1, 10000f);
} public void Render()
{ if (device == null)
{
return;
}
if (pause)
{
return;
}
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);//第一个参数,指定要初始化目标窗口和深度缓冲区
device.BeginScene();
/**** 开始渲染*************************************************************************/ SetCamera();//改变摄像机位置
device.RenderState.CullMode = Cull.None;
device.RenderState.Lighting = true ;
device.Transform.World = Matrix.Scaling(0.5f, 0.5f, 0.5f) * Matrix.Translation(cameraTarget.X, cameraTarget.Y, cameraTarget.Z);
device.Material = meshMaterial1;
mesh.DrawSubset(0);//绘制茶壶 //绘制包围盒
device.RenderState.FillMode = FillMode.WireFrame;
GraphicsStream gs = mesh.VertexBuffer.Lock(0, 0, LockFlags.None);
Vector3 minVector, maxVector;
Geometry.ComputeBoundingBox(gs, mesh.NumberVertices, mesh.VertexFormat, out minVector, out maxVector);
Mesh Box = Mesh.Box(device, maxVector.X - minVector.X, maxVector.Y - minVector.Y, maxVector.Z - minVector.Z);
// Box.DrawSubset(0); //绘制包围球
Vector3 center = new Vector3();
float radius = Geometry.ComputeBoundingSphere(gs, mesh.NumberVertices, mesh.VertexFormat, out center);
Mesh sphere = Mesh.Sphere(device, radius*100, 100, 100);
device.Material = meshMaterial2;
sphere.DrawSubset(0); // device.Transform.World = Matrix.Identity;
//device.SetTexture(0, texture);
//device.VertexFormat = CustomVertex.PositionTextured.Format;
//device.DrawUserPrimitives(PrimitiveType.TriangleFan, 2, vertics); /****结束渲染*************************************************************************/
device.EndScene();
device.Present();//更新显示缓冲区
}
protected override void OnPaint(PaintEventArgs e)
{
this.Render();
}
protected override void OnKeyDown(KeyEventArgs e)
{
Vector3 lastPosition = cameraPosition;//记录上一次摄像机的位置,即没旋转前的位置!
Vector4 tempV4;
Matrix currentView = device.Transform.View;//当前摄像机的视图矩阵
switch (e.KeyCode)
{
case Keys.Left://y轴旋转++
cameraPosition.Subtract(cameraTarget);//向量相减,得到以目标点为起点的向量
tempV4 = Vector3.Transform(cameraPosition, Matrix.RotationQuaternion(Quaternion.RotationAxis(new Vector3(currentView.M12, currentView.M22, currentView.M32), -angleY)));
cameraPosition.X = tempV4.X + cameraTarget.X;
cameraPosition.Y = tempV4.Y + cameraTarget.Y;
cameraPosition.Z = tempV4.Z + cameraTarget.Z;
break;
case Keys.Right://y轴旋转--
cameraPosition.Subtract(cameraTarget);
tempV4 = Vector3.Transform(cameraPosition, Matrix.RotationQuaternion(Quaternion.RotationAxis(new Vector3(currentView.M12, currentView.M22, currentView.M32), angleY)));
cameraPosition.X = tempV4.X + cameraTarget.X;
cameraPosition.Y = tempV4.Y + cameraTarget.Y;
cameraPosition.Z = tempV4.Z + cameraTarget.Z;
break;
case Keys.Up://x轴旋转++
cameraPosition.Subtract(cameraTarget);
tempV4 = Vector3.Transform(cameraPosition,
Matrix.RotationQuaternion(
Quaternion.RotationAxis(new
Vector3(device.Transform.View.M11
, device.Transform.View.M21, device.Transform.View.M31),
-angleY)));
cameraPosition.X = tempV4.X + cameraTarget.X;
cameraPosition.Y = tempV4.Y + cameraTarget.Y;
cameraPosition.Z = tempV4.Z + cameraTarget.Z;
Vector3 directionV3 = cameraPosition - lastPosition;//旋转方向
camereUpVector = -directionV3;//改变y方向位置
break;
case Keys.Down://x轴旋转--
cameraPosition.Subtract(cameraTarget);
tempV4 = Vector3.Transform(cameraPosition,
Matrix.RotationQuaternion(
Quaternion.RotationAxis(new
Vector3(device.Transform.View.M11
, device.Transform.View.M21, device.Transform.View.M31),
angleY)));
cameraPosition.X = tempV4.X + cameraTarget.X;
cameraPosition.Y = tempV4.Y + cameraTarget.Y;
cameraPosition.Z = tempV4.Z + cameraTarget.Z;
Vector3 direction2V3 = cameraPosition - lastPosition;//旋转方向
camereUpVector = direction2V3;
break;
case Keys.Add://放大,按加号键
cameraPosition.Subtract(cameraTarget);
cameraPosition.Scale(0.95f);
cameraPosition.Add(cameraTarget);
break;
case Keys.Subtract://缩小,减号键
cameraPosition.Subtract(cameraTarget);
cameraPosition.Scale(1.05f);
cameraPosition.Add(cameraTarget);
break;
}
Matrix viewMatrix = Matrix.LookAtLH(cameraPosition, cameraTarget, camereUpVector);
device.Transform.View = viewMatrix;
} private int mouseLastX, mouseLastY;//记录鼠标按下时的坐标位置
private bool isRotateByMouse = false;//记录是否由鼠标控制旋转
private bool isMoveByMouse = false;//记录是否由鼠标控制摄像机 移动 protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseLastX = e.X;
mouseLastY = e.Y;
isRotateByMouse = true;
}
else if (e.Button == MouseButtons.Middle)
{
mouseLastX = e.X;
mouseLastY = e.Y;
isMoveByMouse = true;
} } protected override void OnMouseMove(MouseEventArgs e)
{
if (isRotateByMouse)
{
Matrix currentView = device.Transform.View;//当前摄像机的视图矩阵
float tempAngleY = 2 * (float)(e.X - mouseLastX) / this.Width;
cameraPosition.Subtract(cameraTarget);
Vector4 tempV4 = Vector3.Transform(cameraPosition, Matrix.RotationQuaternion(Quaternion.RotationAxis(new Vector3(currentView.M12, currentView.M22, currentView.M32), tempAngleY)));
cameraPosition.X = tempV4.X;
cameraPosition.Y = tempV4.Y;
cameraPosition.Z = tempV4.Z;//旋转y轴得到新的摄像机临时坐标
Vector3 tempCameraPosition = cameraPosition;//记录一下上一次摄像机的位置
float tempAngleX = 4 * (float)(e.Y - mouseLastY) / this.Height;
tempV4 = Vector3.Transform(cameraPosition, Matrix.RotationQuaternion(Quaternion.RotationAxis(new Vector3(currentView.M11, currentView.M21, currentView.M31), tempAngleX)));
if (tempAngleX > 0)//大于零说明x轴左手系中,取负值旋转,因此摄像机向上方向与摄像机移动位置方向相反
{
camereUpVector = new Vector3(-cameraPosition.X + tempV4.X, -cameraPosition.Y + tempV4.Y, -cameraPosition.Z + tempV4.Z);
}
else if (tempAngleX < 0)
{
camereUpVector = new Vector3(cameraPosition.X - tempV4.X, cameraPosition.Y - tempV4.Y, cameraPosition.Z - tempV4.Z);
}
cameraPosition.X = tempV4.X + cameraTarget.X;
cameraPosition.Y = tempV4.Y + cameraTarget.Y;
cameraPosition.Z = tempV4.Z + cameraTarget.Z;
Matrix viewMatrix = Matrix.LookAtLH(cameraPosition, cameraTarget, camereUpVector);
device.Transform.View = viewMatrix;
mouseLastX = e.X;
mouseLastY = e.Y;
} else if (isMoveByMouse)
{
Matrix currentView = device.Transform.View;//当前摄像机的视图矩阵
float moveFactor = 0.01f;
cameraTarget.X += -moveFactor * ((e.X - mouseLastX) * currentView.M11
- (e.Y - mouseLastY) * currentView.M12);
cameraTarget.Y += -moveFactor * ((e.X - mouseLastX) * currentView.M21
- (e.Y - mouseLastY) * currentView.M22);
cameraTarget.Z += -moveFactor * ((e.X - mouseLastX) * currentView.M31
- (e.Y - mouseLastY) * currentView.M32);
Matrix viewMatrix = Matrix.LookAtLH(cameraPosition, cameraTarget, camereUpVector);
device.Transform.View = viewMatrix;
mouseLastX = e.X;
mouseLastY = e.Y;
}
} //鼠标滚轮控制摄像机放大缩小
protected override void OnMouseWheel(MouseEventArgs e)
{
float scaleFactor = -(float)e.Delta / 2000 + 1f;
cameraPosition.Subtract(cameraTarget);
cameraPosition.Scale(scaleFactor);
cameraPosition.Add(cameraTarget);
Matrix viewMatrix = Matrix.LookAtLH(cameraPosition, cameraTarget, camereUpVector);
device.Transform.View = viewMatrix;
}
protected override void OnMouseUp(MouseEventArgs e)
{
isRotateByMouse = false;
isMoveByMouse = false;
}
}
}
----------------------------------------

感谢每一位阅读此篇文章的人,希望可以帮到你。

Directx3d绘制包围体并控制光照效果的更多相关文章

  1. 制作Kinect体感控制小车教程 &lt;一&gt;

    转载请注明出处:http://blog.csdn.net/lxk7280                                        Kinect体感控制小车        Kine ...

  2. U3D学习09-物体简单控制及视角观察

    一.Character Control非刚体 1.场景初始化,注意调整CC的轴心,不需要碰撞,且删除CC子物体的碰撞.2.移动:       获取X,Z轴变化,定义变量h,v:        定义移动 ...

  3. arduino体感控制简单版

    https://learn.sparkfun.com/tutorials/apds-9960-rgb-and-gesture-sensor-hookup-guide/all 硬件连线 关键 VCC=  ...

  4. OpenGL 遮挡查询

    原文地址:http://www.linuxidc.com/Linux/2015-02/114036.htm 在一个场景中,如果有有些物体被其他物体遮住了不可见.那么我们就不需要绘制它.在复杂的场景中, ...

  5. OpenGL遮挡查询

    转自:http://www.cnblogs.com/mazhenyu/p/5083026.html 在一个场景中,如果有有些物体被其他物体遮住了不可见.那么我们就不需要绘制它.在复杂的场景中,这可以减 ...

  6. OpenGL超级宝典笔记——遮挡查询 [转]

    目录[-] 遮挡查询之前 包围体 遮挡查询 在一个场景中,如果有有些物体被其他物体遮住了不可见.那么我们就不需要绘制它.在复杂的场景中,这可以减少大量的顶点和像素的处理,大幅度的提高帧率.遮挡查询就是 ...

  7. Light Pre-Pass 渲染器----为多光源设计一个渲染器

    http://blog.csdn.net/xoyojank/article/details/4460953 作者: Wolfgang Engel, 原文: http://www.wolfgang-en ...

  8. D3D的绘制

    一.D3D中的绘制 顶点缓存和索引缓存:IDirect3DVertexBuffer9 IDirect3DIndexBuffer 使用这两缓存而不是用数组来存储数据的原因是,缓存可以被放置在显存中,进行 ...

  9. p2 钢体

    钢体可以控制沿x方向移动,沿y方向移动, 不旋转等. fixedX, fixedY, fixedRotaion 1)addBody和removeBody:World类中的addBody()和remov ...

随机推荐

  1. sql万能密码

    输入1'or'2这样就会引起sql注入,因为username=password admin adn admin,所以我们能够进去 必须要做好过滤措施

  2. 【转载】Java 内存分配全面浅析

    本文将由浅入深详细介绍Java内存分配的原理,以帮助新手更轻松的学习Java.这类文章网上有很多,但大多比较零碎.本文从认知过程角度出发,将带给读者一个系统的介绍. 本文转载自袭烽大神的博客,原文链接 ...

  3. BZOJ 1257: [CQOI2007]余数之和sum【神奇的做法,思维题】

    1257: [CQOI2007]余数之和sum Time Limit: 5 Sec  Memory Limit: 162 MBSubmit: 4474  Solved: 2083[Submit][St ...

  4. Codeforces 626E Simple Skewness(暴力枚举+二分)

    E. Simple Skewness time limit per test:3 seconds memory limit per test:256 megabytes input:standard ...

  5. 数值积分之Simpson公式与梯形公式

    Simpson(辛普森)公式和梯形公式是求数值积分中很重要的两个公式,可以帮助我们使用计算机求解数值积分,而在使用过程中也有多种方式,比如复合公式和变步长公式.这里分别给出其简单实现(C++版): 1 ...

  6. Angular(2+) 国际化方案(ngx-translate)

    本文只针对ngx-translate/core 6.x版本,如果你使用的是5.x或者更低的版本,请参照以下链接. https://github.com/ngx-translate/core/blob/ ...

  7. Linq 实例

    1.分页 ).Take(); 2.分组 1)一般分组 //根据顾客的国家分组,查询顾客数大于5的国家名和顾客数var 一般分组 = from c in ctx.Customers group c by ...

  8. php中使用head进行二进制流输出,让用户下载PDF等附件的方法

    http://blog.csdn.net/jallin2001/article/details/6872951 在PHP的手册中,有如下的方法,可以让用户方便的下载pdf或者其他类似的附件形式,不过这 ...

  9. file_get_contents("php://input")的使用方法

    $data = file_get_contents("php://input"); //input 是个可以访问请求的原始数据的只读流. POST 请求的情况下,最好使用 php: ...

  10. thinkphp5z

    解决验证类下找不到指定的类,就在D:\phpStudy\www\vuethink\php\application\admin\validate\service.php,缺少验证类文件service.p ...