-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjLoader.cs
More file actions
77 lines (64 loc) · 1.97 KB
/
Copy pathObjLoader.cs
File metadata and controls
77 lines (64 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Collections.Generic;
using System.IO;
using OpenTK.Mathematics;
namespace MedViewer
{
public static class ObjLoader
{
public static Mesh Load(string path)
{
List<Vector3> vertices = new List<Vector3>();
List<Vector3> normals = new List<Vector3>();
List<uint> vertexIndices = new List<uint>();
List<uint> normalIndices = new List<uint>();
if (!File.Exists(path))
{
throw new FileNotFoundException("Unable to open \"" + path + "\", does not exist.");
}
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)
{
// vertex
case "v":
vertices.Add(new Vector3(
float.Parse(words[0], System.Globalization.CultureInfo.InvariantCulture),
float.Parse(words[1], System.Globalization.CultureInfo.InvariantCulture),
float.Parse(words[2], System.Globalization.CultureInfo.InvariantCulture)));
break;
case "vn":
normals.Add(new Vector3(
float.Parse(words[0], System.Globalization.CultureInfo.InvariantCulture),
float.Parse(words[1], System.Globalization.CultureInfo.InvariantCulture),
float.Parse(words[2], System.Globalization.CultureInfo.InvariantCulture)));
break;
// face
case "f":
foreach (string w in words)
{
if (w.Length == 0)
continue;
string[] comps = w.Split('/');
// subtract 1: indices start from 1, not 0
vertexIndices.Add(uint.Parse(comps[0]) - 1);
if (comps.Length > 2)
normalIndices.Add(uint.Parse(comps[2]) - 1);
}
break;
default:
break;
}
}
}
return new Mesh(vertices, normals, vertexIndices, normalIndices);
}
}
}