C#在3D领域的简单使用总结及示例
·
C#在3D开发领域有着广泛的应用,从游戏开发到科学可视化,再到工业设计等领域。本文将总结C#在3D开发中的主要应用方式,并提供实用的代码示例。
主要的3D开发框架
1. Unity3D - 最流行的选择
Unity3D是目前C#在3D领域最主流的应用平台,提供了完整的3D开发环境。
using UnityEngine;
using System.Collections;
public class Basic3DExample : MonoBehaviour
{
public float rotationSpeed = 30f;
public float moveSpeed = 2f;
private void Update()
{
// 旋转物体
transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime);
// 移动控制
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0, vertical) * moveSpeed * Time.deltaTime;
transform.Translate(movement);
}
private void OnCollisionEnter(Collision collision)
{
// 碰撞检测
Debug.Log($"碰撞到: {collision.gameObject.name}");
// 改变颜色
GetComponent<Renderer>().material.color = Color.red;
}
}
// 简单的3D对象生成器
public class ObjectSpawner : MonoBehaviour
{
public GameObject cubePrefab;
public int gridSize = 5;
public float spacing = 2f;
void Start()
{
GenerateGrid();
}
void GenerateGrid()
{
for (int x = 0; x < gridSize; x++)
{
for (int z = 0; z < gridSize; z++)
{
Vector3 position = new Vector3(x * spacing, 0, z * spacing);
GameObject cube = Instantiate(cubePrefab, position, Quaternion.identity);
// 设置随机颜色
Renderer renderer = cube.GetComponent<Renderer>();
renderer.material.color = new Color(
Random.value,
Random.value,
Random.value
);
}
}
}
}
2. 使用SharpDX进行底层3D开发
SharpDX提供了对DirectX的.NET封装,适合需要更底层控制的3D应用。
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using System;
using System.Windows.Forms;
public class SharpDXBasicExample : IDisposable
{
private RenderForm renderForm;
private SharpDX.Direct3D11.Device device;
private SwapChain swapChain;
private RenderTargetView renderTargetView;
public void Run()
{
renderForm = new RenderForm("SharpDX 3D示例");
renderForm.Width = 800;
renderForm.Height = 600;
InitializeDevice();
RenderLoop.Run(renderForm, RenderCallback);
}
private void InitializeDevice()
{
ModeDescription bufferDescription = new ModeDescription(
renderForm.ClientSize.Width,
renderForm.ClientSize.Height,
new Rational(60, 1), // 刷新率
Format.R8G8B8A8_UNorm);
SwapChainDescription swapChainDescription = new SwapChainDescription()
{
ModeDescription = bufferDescription,
SampleDescription = new SampleDescription(1, 0),
Usage = Usage.RenderTargetOutput,
BufferCount = 1,
OutputHandle = renderForm.Handle,
IsWindowed = true
};
SharpDX.Direct3D11.Device.CreateWithSwapChain(
DriverType.Hardware,
DeviceCreationFlags.None,
swapChainDescription,
out device,
out swapChain);
// 创建渲染目标视图
using (var backBuffer = swapChain.GetBackBuffer<Texture2D>(0))
{
renderTargetView = new RenderTargetView(device, backBuffer);
}
// 设置视图端口
device.ImmediateContext.Rasterizer.SetViewport(
new Viewport(0, 0, renderForm.ClientSize.Width, renderForm.ClientSize.Height, 0.0f, 1.0f));
}
private void RenderCallback()
{
// 清除为蓝色
device.ImmediateContext.ClearRenderTargetView(renderTargetView, Color.CornflowerBlue);
// 在这里添加3D渲染代码
swapChain.Present(0, PresentFlags.None);
}
public void Dispose()
{
renderTargetView?.Dispose();
swapChain?.Dispose();
device?.Dispose();
renderForm?.Dispose();
}
}
3. 使用OpenTK进行跨平台3D开发
OpenTK是OpenGL的.NET封装,支持跨平台3D开发。
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using System;
public class OpenTK3DExample : GameWindow
{
private float rotation = 0.0f;
private int vertexBufferObject;
private int vertexArrayObject;
private int shaderProgram;
// 立方体顶点数据
private readonly float[] vertices = {
// 前面
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
// 后面
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f
};
private readonly uint[] indices = {
// 前面
0, 1, 2, 2, 3, 0,
// 右面
1, 5, 6, 6, 2, 1,
// 后面
7, 6, 5, 5, 4, 7,
// 左面
4, 0, 3, 3, 7, 4,
// 上面
3, 2, 6, 6, 7, 3,
// 下面
4, 5, 1, 1, 0, 4
};
public OpenTK3DExample() : base(800, 600,
GraphicsMode.Default, "OpenTK 3D示例") { }
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
GL.ClearColor(0.2f, 0.3f, 0.3f, 1.0f);
GL.Enable(EnableCap.DepthTest);
InitializeBuffers();
CompileShaders();
}
private void InitializeBuffers()
{
// 生成顶点数组对象
vertexArrayObject = GL.GenVertexArray();
GL.BindVertexArray(vertexArrayObject);
// 生成顶点缓冲对象
vertexBufferObject = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferObject);
GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float),
vertices, BufferUsageHint.StaticDraw);
// 生成元素缓冲对象
int elementBufferObject = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ElementArrayBuffer, elementBufferObject);
GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Length * sizeof(uint),
indices, BufferUsageHint.StaticDraw);
// 设置顶点属性指针
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0);
GL.EnableVertexAttribArray(0);
}
private void CompileShaders()
{
// 顶点着色器
string vertexShaderSource = @"
#version 330 core
layout (location = 0) in vec3 aPosition;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPosition, 1.0);
}";
// 片段着色器
string fragmentShaderSource = @"
#version 330 core
out vec4 FragColor;
void main()
{
FragColor = vec4(0.8, 0.3, 0.2, 1.0);
}";
// 编译着色器
int vertexShader = CompileShader(ShaderType.VertexShader, vertexShaderSource);
int fragmentShader = CompileShader(ShaderType.FragmentShader, fragmentShaderSource);
// 创建着色器程序
shaderProgram = GL.CreateProgram();
GL.AttachShader(shaderProgram, vertexShader);
GL.AttachShader(shaderProgram, fragmentShader);
GL.LinkProgram(shaderProgram);
// 清理着色器
GL.DeleteShader(vertexShader);
GL.DeleteShader(fragmentShader);
}
private int CompileShader(ShaderType type, string source)
{
int shader = GL.CreateShader(type);
GL.ShaderSource(shader, source);
GL.CompileShader(shader);
// 检查编译错误
GL.GetShader(shader, ShaderParameter.CompileStatus, out int success);
if (success == 0)
{
string infoLog = GL.GetShaderInfoLog(shader);
throw new Exception($"着色器编译错误: {infoLog}");
}
return shader;
}
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.UseProgram(shaderProgram);
// 设置变换矩阵
Matrix4 model = Matrix4.CreateRotationY(rotation);
Matrix4 view = Matrix4.CreateTranslation(0.0f, 0.0f, -3.0f);
Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(
MathHelper.DegreesToRadians(45.0f),
(float)Width / Height, 0.1f, 100.0f);
// 传递矩阵到着色器
int modelLocation = GL.GetUniformLocation(shaderProgram, "model");
int viewLocation = GL.GetUniformLocation(shaderProgram, "view");
int projectionLocation = GL.GetUniformLocation(shaderProgram, "projection");
GL.UniformMatrix4(modelLocation, false, ref model);
GL.UniformMatrix4(viewLocation, false, ref view);
GL.UniformMatrix4(projectionLocation, false, ref projection);
// 渲染立方体
GL.BindVertexArray(vertexArrayObject);
GL.DrawElements(PrimitiveType.Triangles, indices.Length,
DrawElementsType.UnsignedInt, 0);
SwapBuffers();
}
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
rotation += (float)e.Time;
// 退出控制
if (Keyboard[Key.Escape])
{
Exit();
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
GL.Viewport(0, 0, Width, Height);
}
}
// 程序入口
class Program
{
static void Main()
{
using (var game = new OpenTK3DExample())
{
game.Run(60.0);
}
}
}
3D数学计算库
4. 实现3D向量和矩阵运算
public struct Vector3
{
public float X, Y, Z;
public Vector3(float x, float y, float z)
{
X = x; Y = y; Z = z;
}
public static Vector3 Zero => new Vector3(0, 0, 0);
public static Vector3 One => new Vector3(1, 1, 1);
public static Vector3 UnitX => new Vector3(1, 0, 0);
public static Vector3 UnitY => new Vector3(0, 1, 0);
public static Vector3 UnitZ => new Vector3(0, 0, 1);
public float Length => (float)Math.Sqrt(X * X + Y * Y + Z * Z);
public float LengthSquared => X * X + Y * Y + Z * Z;
public Vector3 Normalized()
{
float length = Length;
if (length > float.Epsilon)
{
return new Vector3(X / length, Y / length, Z / length);
}
return Zero;
}
public static Vector3 operator +(Vector3 a, Vector3 b)
=> new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
public static Vector3 operator -(Vector3 a, Vector3 b)
=> new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
public static Vector3 operator *(Vector3 v, float scalar)
=> new Vector3(v.X * scalar, v.Y * scalar, v.Z * scalar);
public static Vector3 operator *(float scalar, Vector3 v)
=> v * scalar;
public static float Dot(Vector3 a, Vector3 b)
=> a.X * b.X + a.Y * b.Y + a.Z * b.Z;
public static Vector3 Cross(Vector3 a, Vector3 b)
=> new Vector3(
a.Y * b.Z - a.Z * b.Y,
a.Z * b.X - a.X * b.Z,
a.X * b.Y - a.Y * b.X
);
public static float Distance(Vector3 a, Vector3 b)
{
float dx = a.X - b.X;
float dy = a.Y - b.Y;
float dz = a.Z - b.Z;
return (float)Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
public override string ToString() => $"({X:F2}, {Y:F2}, {Z:F2})";
}
public struct Matrix4x4
{
public float M11, M12, M13, M14;
public float M21, M22, M23, M24;
public float M31, M32, M33, M34;
public float M41, M42, M43, M44;
public static Matrix4x4 Identity => new Matrix4x4
{
M11 = 1, M22 = 1, M33 = 1, M44 = 1
};
public static Matrix4x4 CreateTranslation(float x, float y, float z)
{
return new Matrix4x4
{
M11 = 1, M22 = 1, M33 = 1, M44 = 1,
M41 = x, M42 = y, M43 = z
};
}
public static Matrix4x4 CreateScale(float scale)
{
return new Matrix4x4
{
M11 = scale, M22 = scale, M33 = scale, M44 = 1
};
}
public static Matrix4x4 CreateRotationX(float radians)
{
float cos = (float)Math.Cos(radians);
float sin = (float)Math.Sin(radians);
return new Matrix4x4
{
M11 = 1, M22 = cos, M23 = -sin,
M32 = sin, M33 = cos, M44 = 1
};
}
public static Matrix4x4 CreateRotationY(float radians)
{
float cos = (float)Math.Cos(radians);
float sin = (float)Math.Sin(radians);
return new Matrix4x4
{
M11 = cos, M13 = sin,
M22 = 1,
M31 = -sin, M33 = cos, M44 = 1
};
}
public static Matrix4x4 CreatePerspectiveFieldOfView(float fov, float aspectRatio,
float nearPlane, float farPlane)
{
float tanFov = (float)Math.Tan(fov / 2);
float depth = farPlane - nearPlane;
return new Matrix4x4
{
M11 = 1 / (aspectRatio * tanFov),
M22 = 1 / tanFov,
M33 = -(farPlane + nearPlane) / depth,
M34 = -1,
M43 = -(2 * farPlane * nearPlane) / depth
};
}
public static Vector3 operator *(Matrix4x4 matrix, Vector3 vector)
{
return new Vector3(
matrix.M11 * vector.X + matrix.M21 * vector.Y + matrix.M31 * vector.Z + matrix.M41,
matrix.M12 * vector.X + matrix.M22 * vector.Y + matrix.M32 * vector.Z + matrix.M42,
matrix.M13 * vector.X + matrix.M23 * vector.Y + matrix.M33 * vector.Z + matrix.M43
);
}
public static Matrix4x4 operator *(Matrix4x4 a, Matrix4x4 b)
{
return new Matrix4x4
{
M11 = a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31 + a.M14 * b.M41,
M12 = a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32 + a.M14 * b.M42,
M13 = a.M11 * b.M13 + a.M12 * b.M23 + a.M13 * b.M33 + a.M14 * b.M43,
M14 = a.M11 * b.M14 + a.M12 * b.M24 + a.M13 * b.M34 + a.M14 * b.M44,
M21 = a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31 + a.M24 * b.M41,
M22 = a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32 + a.M24 * b.M42,
M23 = a.M21 * b.M13 + a.M22 * b.M23 + a.M23 * b.M33 + a.M24 * b.M43,
M24 = a.M21 * b.M14 + a.M22 * b.M24 + a.M23 * b.M34 + a.M24 * b.M44,
M31 = a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31 + a.M34 * b.M41,
M32 = a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32 + a.M34 * b.M42,
M33 = a.M31 * b.M13 + a.M32 * b.M23 + a.M33 * b.M33 + a.M34 * b.M43,
M34 = a.M31 * b.M14 + a.M32 * b.M24 + a.M33 * b.M34 + a.M34 * b.M44,
M41 = a.M41 * b.M11 + a.M42 * b.M21 + a.M43 * b.M31 + a.M44 * b.M41,
M42 = a.M41 * b.M12 + a.M42 * b.M22 + a.M43 * b.M32 + a.M44 * b.M42,
M43 = a.M41 * b.M13 + a.M42 * b.M23 + a.M43 * b.M33 + a.M44 * b.M43,
M44 = a.M41 * b.M14 + a.M42 * b.M24 + a.M43 * b.M34 + a.M44 * b.M44
};
}
}
3D模型处理和文件格式
5. 简单的OBJ文件加载器
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class ObjModelLoader
{
public class Mesh
{
public List<Vector3> Vertices { get; set; } = new List<Vector3>();
public List<Vector3> Normals { get; set; } = new List<Vector3>();
public List<Vector2> TexCoords { get; set; } = new List<Vector2>();
public List<Face> Faces { get; set; } = new List<Face>();
}
public class Face
{
public List<VertexIndex> VertexIndices { get; set; } = new List<VertexIndex>();
}
public struct VertexIndex
{
public int Vertex;
public int TexCoord;
public int Normal;
public VertexIndex(int v, int vt, int vn)
{
Vertex = v;
TexCoord = vt;
Normal = vn;
}
}
public static Mesh LoadObjFile(string filePath)
{
var mesh = new Mesh();
var lines = File.ReadAllLines(filePath);
foreach (var line in lines)
{
var parts = line.Trim().Split(' ').Where(p => !string.IsNullOrEmpty(p)).ToArray();
if (parts.Length == 0) continue;
switch (parts[0])
{
case "v": // 顶点
if (parts.Length >= 4)
{
float x = float.Parse(parts[1]);
float y = float.Parse(parts[2]);
float z = float.Parse(parts[3]);
mesh.Vertices.Add(new Vector3(x, y, z));
}
break;
case "vt": // 纹理坐标
if (parts.Length >= 3)
{
float u = float.Parse(parts[1]);
float v = float.Parse(parts[2]);
// 注意:OBJ的v坐标是从上到下的,可能需要翻转
mesh.TexCoords.Add(new Vector2(u, 1 - v));
}
break;
case "vn": // 法线
if (parts.Length >= 4)
{
float x = float.Parse(parts[1]);
float y = float.Parse(parts[2]);
float z = float.Parse(parts[3]);
mesh.Normals.Add(new Vector3(x, y, z));
}
break;
case "f": // 面
var face = new Face();
for (int i = 1; i < parts.Length; i++)
{
var indices = parts[i].Split('/');
int v = int.Parse(indices[0]) - 1; // OBJ索引从1开始
int vt = indices.Length > 1 && !string.IsNullOrEmpty(indices[1]) ?
int.Parse(indices[1]) - 1 : -1;
int vn = indices.Length > 2 && !string.IsNullOrEmpty(indices[2]) ?
int.Parse(indices[2]) - 1 : -1;
face.VertexIndices.Add(new VertexIndex(v, vt, vn));
}
mesh.Faces.Add(face);
break;
}
}
return mesh;
}
}
// 使用示例
public class ModelRenderer
{
public void RenderModel(string objFilePath)
{
var mesh = ObjModelLoader.LoadObjFile(objFilePath);
Console.WriteLine($"加载模型: {Path.GetFileName(objFilePath)}");
Console.WriteLine($"顶点数: {mesh.Vertices.Count}");
Console.WriteLine($"面数: {mesh.Faces.Count}");
// 这里可以添加渲染逻辑
foreach (var face in mesh.Faces)
{
// 处理每个面
RenderFace(face, mesh);
}
}
private void RenderFace(ObjModelLoader.Face face, ObjModelLoader.Mesh mesh)
{
// 简化的面渲染逻辑
for (int i = 0; i < face.VertexIndices.Count; i++)
{
var vertexIndex = face.VertexIndices[i];
var vertex = mesh.Vertices[vertexIndex.Vertex];
// 在实际渲染中,这里会将顶点数据传递给GPU
// Console.WriteLine($"顶点 {i}: {vertex}");
}
}
}
3D物理模拟
6. 简单的3D物理引擎
public class SimplePhysicsEngine
{
private List<RigidBody> bodies = new List<RigidBody>();
private Vector3 gravity = new Vector3(0, -9.81f, 0);
public class RigidBody
{
public Vector3 Position { get; set; }
public Vector3 Velocity { get; set; }
public Vector3 Acceleration { get; set; }
public float Mass { get; set; } = 1.0f;
public float Bounciness { get; set; } = 0.5f; // 弹性系数
public Vector3 Size { get; set; } = new Vector3(1, 1, 1);
public void ApplyForce(Vector3 force)
{
Acceleration += force / Mass;
}
}
public void AddBody(RigidBody body)
{
bodies.Add(body);
}
public void Update(float deltaTime)
{
foreach (var body in bodies)
{
// 应用重力
body.ApplyForce(gravity * body.Mass);
// 更新速度
body.Velocity += body.Acceleration * deltaTime;
// 更新位置
body.Position += body.Velocity * deltaTime;
// 重置加速度
body.Acceleration = Vector3.Zero;
// 简单的边界碰撞检测
CheckBoundaryCollisions(body);
}
// 检测物体间碰撞
CheckCollisions();
}
private void CheckBoundaryCollisions(RigidBody body)
{
// 简单的边界框碰撞(假设边界为-10到10)
float boundary = 10.0f;
if (body.Position.X - body.Size.X / 2 < -boundary)
{
body.Position = new Vector3(-boundary + body.Size.X / 2, body.Position.Y, body.Position.Z);
body.Velocity = new Vector3(-body.Velocity.X * body.Bounciness, body.Velocity.Y, body.Velocity.Z);
}
else if (body.Position.X + body.Size.X / 2 > boundary)
{
body.Position = new Vector3(boundary - body.Size.X / 2, body.Position.Y, body.Position.Z);
body.Velocity = new Vector3(-body.Velocity.X * body.Bounciness, body.Velocity.Y, body.Velocity.Z);
}
// 类似处理Y和Z轴...
}
private void CheckCollisions()
{
for (int i = 0; i < bodies.Count; i++)
{
for (int j = i + 1; j < bodies.Count; j++)
{
if (CheckAABBCollision(bodies[i], bodies[j]))
{
ResolveCollision(bodies[i], bodies[j]);
}
}
}
}
private bool CheckAABBCollision(RigidBody a, RigidBody b)
{
// 轴对齐边界框碰撞检测
return Math.Abs(a.Position.X - b.Position.X) < (a.Size.X + b.Size.X) / 2 &&
Math.Abs(a.Position.Y - b.Position.Y) < (a.Size.Y + b.Size.Y) / 2 &&
Math.Abs(a.Position.Z - b.Position.Z) < (a.Size.Z + b.Size.Z) / 2;
}
private void ResolveCollision(RigidBody a, RigidBody b)
{
// 简化的碰撞响应
Vector3 collisionNormal = (a.Position - b.Position).Normalized();
// 分离物体
float overlap = (a.Size.X + b.Size.X) / 2 - Vector3.Distance(a.Position, b.Position);
a.Position += collisionNormal * overlap * 0.5f;
b.Position -= collisionNormal * overlap * 0.5f;
// 更新速度
float totalBounciness = (a.Bounciness + b.Bounciness) / 2;
a.Velocity = collisionNormal * a.Velocity.Length * totalBounciness;
b.Velocity = -collisionNormal * b.Velocity.Length * totalBounciness;
}
}
C#在3D开发领域具有强大的能力,主要应用方式包括:
-
Unity3D:最流行的选择,适合游戏开发和交互式3D应用
-
SharpDX:适合需要DirectX底层控制的Windows应用
-
OpenTK:跨平台的OpenGL开发方案
-
自定义引擎:用于学习或特殊需求
开发建议:
-
初学者:从Unity3D开始,学习曲线平缓,资源丰富
-
性能敏感应用:考虑SharpDX或OpenTK进行底层优化
-
跨平台需求:选择OpenTK或Unity的跨平台能力
-
科学计算/可视化:可以考虑使用HelixToolkit等专业库
无论选择哪种方案,掌握3D数学基础(向量、矩阵、变换)和图形学原理都是成功的关键。C#的强类型特性和丰富的生态系统使其成为3D开发的优秀选择。
更多推荐



所有评论(0)