Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using SharpDX;
- using SharpDX.Direct3D11;
- using System;
- using System.Collections.Generic;
- using System.IO;
- namespace VoidwalkerEngine.Framework.DirectX.Rendering
- {
- public class WavefrontModel
- {
- public string Name { get; set; }
- public List<Vertex> Vertices { get; set; }
- public WavefrontModel()
- {
- this.Vertices = new List<Vertex>();
- }
- public static WavefrontModel Load(string filePath)
- {
- if (File.Exists(filePath))
- {
- return Load(File.ReadAllBytes(filePath));
- }
- else
- {
- throw new FileNotFoundException("Could not locate: " + filePath);
- }
- }
- public static WavefrontModel Load(byte[] bytes)
- {
- using (MemoryStream memoryStream = new MemoryStream(bytes))
- {
- using (StreamReader reader = new StreamReader(memoryStream))
- {
- WavefrontModel model = new WavefrontModel();
- List<Vector3> parsedVertices = new List<Vector3>();
- List<Vector2> parsedTexCoords = new List<Vector2>();
- List<Vector3> parsedNormals = new List<Vector3>();
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- if (line.Length > 0)
- {
- string[] segments = line.Split(' ');
- if (line.StartsWith("o "))
- {
- Console.WriteLine(line);
- }
- if (line.StartsWith("v "))
- {
- /**
- * Fix Precision Errors
- */
- string xComponent = segments[1];
- string yComponent = segments[2];
- string zComponent = segments[3];
- if (xComponent.StartsWith("-0.00") || xComponent.StartsWith("0.00"))
- {
- xComponent = "0";
- }
- if (yComponent.StartsWith("-0.00") || yComponent.StartsWith("0.00"))
- {
- yComponent = "0";
- }
- if (zComponent.StartsWith("-0.00") || zComponent.StartsWith("0.00"))
- {
- zComponent = "0";
- }
- Vector3 location = new Vector3(
- float.Parse(xComponent),
- float.Parse(yComponent),
- float.Parse(zComponent));
- parsedVertices.Add(location);
- }
- else if (line.StartsWith("vt "))
- {
- parsedTexCoords.Add(
- new Vector2(
- Single.Parse(segments[1]),
- 1 - Single.Parse(segments[2])));
- }
- else if (line.StartsWith("vn "))
- {
- parsedNormals.Add(
- new Vector3(
- Single.Parse(segments[1]),
- Single.Parse(segments[2]),
- Single.Parse(segments[3])));
- }
- else if (line.StartsWith("f "))
- {
- for (int i = 1; i <= 3; i++)
- {
- string[] faceSegments = segments[i].Split('/');
- int verticeIndex = Int32.Parse(faceSegments[0]) - 1;
- int texCoordIndex = Int32.Parse(faceSegments[1]) - 1;
- int normalIndex = Int32.Parse(faceSegments[2]) - 1;
- Vertex vertex = new Vertex
- {
- Location = parsedVertices[verticeIndex],
- TexCoords = parsedTexCoords[texCoordIndex],
- Normal = parsedNormals[normalIndex]
- };
- model.Vertices.Add(vertex);
- }
- }
- }
- }
- reader.Close();
- return model;
- }
- }
- }
- public GraphicsMesh ToModelMesh(Device device)
- {
- return new GraphicsMesh(device, this.Vertices.ToArray());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement