概要
cscの作法、調べてみた。
wpf3d、やってみた。
練習問題やってみた。
練習問題
objファイルを読み取って表示せよ。
写真
サンプルコード
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
class Main3d: Window {
public Main3d() {
var mesh = ObjLoader.Load(@"C:\Users\ore\csc\tetrahedron.obj");
var material = new DiffuseMaterial(new SolidColorBrush(Colors.Blue));
var geometry = new GeometryModel3D(mesh, material);
var modelVisual = new ModelVisual3D();
modelVisual.Content = geometry;
var cam = new PerspectiveCamera();
cam.Position = new Point3D(0, 0, 2);
var light = new DirectionalLight();
var vp3d = new Viewport3D();
vp3d.Camera = cam;
vp3d.Children.Add(modelVisual);
vp3d.Children.Add(new ModelVisual3D() {
Content = light
});
Width = 400;
Height = 400;
Content = vp3d;
}
public static class ObjLoader {
public static MeshGeometry3D Load(string path) {
var mesh = new MeshGeometry3D();
if (!File.Exists(path))
{
throw new FileNotFoundException("Unable to open \"" + path + "\", does not exist.");
}
else
{
Console.Write("ok");
}
using(StreamReader streamReader = new StreamReader(path))
{
while(!streamReader.EndOfStream)
{
List<string> words = new List<string>(streamReader.ReadLine().ToLower().Split(' '));
words.RemoveAll(s => s == string.Empty);
if (words.Count == 0)
continue;
string type = words[0];
words.RemoveAt(0);
switch(type)
{
case "v":
Console.Write("v");
mesh.Positions.Add(new Point3D(float.Parse(words[0]), float.Parse(words[1]), float.Parse(words[2])));
break;
case "vt":
break;
case "vn":
break;
case "f":
Console.Write("f");
foreach(string w in words)
{
if (w.Length == 0)
continue;
string[] comps = w.Split('/');
mesh.TriangleIndices.Add(int.Parse(comps[0]) - 1);
}
break;
default:
break;
}
}
}
return mesh;
}
}
[STAThread]
static void Main() {
var wnd = new Main3d();
wnd.ShowDialog();
}
}
以上。