Giter Site home page Giter Site logo

file-format-wavefront's Introduction

file-format-wavefront

A simple .NET library to load data from Wavefront *.obj and *.mlb files.

Deprecated - this library bas been deprecated. I recommened using the SharpGL.Serialization package which supports Wavefront, Discreet, and more.

Installation

You can use Nuget to install the library.

PM> Install-Package FileFormatWavefront

Usage

To load data from a Wavefront Object File, use the FileFormatObj class:

//  Use the File Format object to load the test data.
bool loadTextureImages = true;
var result = FileFormatObj.Load("MyFile.obj", loadTextureImages);

The object that is returned is a FileLoadResult object. The object contains a property Model which is the Scene of data loaded.

Texture map images can optionally be loaded, but you can skip this if you are not going to need the image or will load it yourself (whether or not the image is loaded, a TextureMap object is still created with the image path as part of it).

The object also contains a collection of Message objects describing any warnings or errors encountered loading the file. An example of iterating through the vertices and messages would look like this:

//  Show each vertex.
foreach(Vertex v in result.Model.Vertices)
{
    Console.Write("{0} {1} {2}", v.x, v.y, v.z);
}

//  Show each message.
foreach (var message in result.Messages)
{
    Console.WriteLine("{0}: {1}", message.MessageType, message.Details);
    Console.WriteLine("{0}: {1}", message.FileName, message.LineNumber);
}

The Model property is of type Scene and contains the following members:

  • Vertices all vertex data.
  • Uvs all material coordinate data.
  • Normals all normal data.
  • Materials all material data.
  • Groups all objects (groups of faces).
  • UngroupedFaces all faces not grouped into objects.

Associated *.mlb (material library) files are loaded automatically. If you want to load a material library only, you can use the FileFormatMlb class in the same way as the FileFormatObj class.

file-format-wavefront's People

Contributors

dwmkerr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

file-format-wavefront's Issues

Create Contents Viewer

It would be nice to have a little WPF or WinForms app that loads the file and shows the model as a graph in a tree view, as well as warnings and errors. This would allow users to quickly see the contents of files.

Add Visuals

Once the sharpgl sample is finished that loads the data, add a screenshot just to keep things looking nice.

Localisation Issues with Floats

Original issue:

https://sharpgl.codeplex.com/workitem/1114

I couldn't load ducky.obj from samples because serializator couldn't convert string to float (in obj file coordinates 1.0 in float type 1,0). I fixed it with this:

  for (int i = 0; i < values.Length; i++ )
                        {
                            string fixstring=values[i].Replace(".",",");
                            values[i] = fixstring;
                        }

Same problem with materials.
UV . In OpenGL UV coordinates differs from directX. V=1-V
Here is fix :

  if (line.StartsWith("vt"))
                    {
                        //  Get the texture coord strings.
                        string[] values = line.Substring(3).Split(split, StringSplitOptions.RemoveEmptyEntries);

                        for (int i = 0; i < values.Length; i++ )
                        {
                            string fixstring=values[i].Replace(".",",");
                            values[i] = fixstring;
                        }
                        //  Parse texture coordinates.
                        float u = float.Parse(values[0]);
                        float v = float.Parse(values[1]);

                        //  Add the texture coordinate.
                        polygon.UVs.Add(new UV(u, 1-v));

                        continue;
                    }

[PATCH] Use CultureInfo.InvariantCulture when parsing

This is very likely the cause of #5.

On locales where , is used for the decimal separator, float.Parse("1.23") fails with a FormatException. Specifying the InvariantCulture fixes the issue.

This can be verified in PowerShell:

C:\> [float]::Parse("1,23")
1,23
C:\> [float]::Parse("1.23")
Exception calling "Parse" with "1" argument(s): "Input string was not in a correct format."
At line:1 char:1
+ [float]::Parse("1.23")
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

C:\> [float]::Parse("1.23", [System.Globalization.CultureInfo]::InvariantCulture)
1,23
C:\>

Pasting this into git apply will apply the change.

From 0be785fb81799a5d42f95c13d88ebf977b5e0270 Mon Sep 17 00:00:00 2001
From: Yuki Izumi <[email protected]>
Date: Sat, 10 May 2014 16:04:25 +1000
Subject: [PATCH] Use CultureInfo.InvariantCulture when parsing.

---
 source/FileFormatWavefront/FileFormatMtl.cs | 19 ++++++++++---------
 source/FileFormatWavefront/FileFormatObj.cs | 25 +++++++++++++------------
 2 files changed, 23 insertions(+), 21 deletions(-)

diff --git a/source/FileFormatWavefront/FileFormatMtl.cs b/source/FileFormatWavefront/FileFormatMtl.cs
index 368b334..e744ade 100644
--- a/source/FileFormatWavefront/FileFormatMtl.cs
+++ b/source/FileFormatWavefront/FileFormatMtl.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.Drawing;
+using System.Globalization;
 using System.IO;
 using System.Linq;
 using FileFormatWavefront.Extensions;
@@ -87,15 +88,15 @@ private static FileLoadResult<List<Material>> Read(TextReader reader, string pat
                     }
                     else if (lineType.IsLineType(LineTypeMaterialShininess))
                     {
-                        currentMaterial.Shininess = float.Parse(lineData);
+                        currentMaterial.Shininess = float.Parse(lineData, CultureInfo.InvariantCulture);
                     }
                     else if (lineType.IsLineType(LineTypeOpticalDensity))
                     {
-                        currentMaterial.OpticalDensity = float.Parse(lineData);
+                        currentMaterial.OpticalDensity = float.Parse(lineData, CultureInfo.InvariantCulture);
                     }
                     else if (lineType.IsLineType(LineTypeBumpStrength))
                     {
-                        currentMaterial.BumpStrength = float.Parse(lineData);
+                        currentMaterial.BumpStrength = float.Parse(lineData, CultureInfo.InvariantCulture);
                     }
                     else if (lineType.IsLineType(LineTypeTextureMapAmbient))
                     {
@@ -124,11 +125,11 @@ private static FileLoadResult<List<Material>> Read(TextReader reader, string pat
                     else if (lineType.IsLineType(LineTypeDissolve) || lineType.IsLineType(LineTypeTransparent))
                     {
                         //  Read the transparency.
-                        currentMaterial.Transparency = float.Parse(lineData);
+                        currentMaterial.Transparency = float.Parse(lineData, CultureInfo.InvariantCulture);
                     }
                     else if(lineType.IsLineType(LineTypeIlluminationModel))
                     {
-                        currentMaterial.IlluminationModel = int.Parse(lineData);
+                        currentMaterial.IlluminationModel = int.Parse(lineData, CultureInfo.InvariantCulture);
                     }
                     else
                     {
@@ -197,10 +198,10 @@ private static Colour ReadColour(string lineData)
             var colourParts = lineData.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
             return new Colour
             {
-                r = float.Parse(colourParts[0]),
-                g = float.Parse(colourParts[1]),
-                b = float.Parse(colourParts[2]),
-                a = colourParts.Length == 4 ? float.Parse(colourParts[3]) : 1.0f,
+                r = float.Parse(colourParts[0], CultureInfo.InvariantCulture),
+                g = float.Parse(colourParts[1], CultureInfo.InvariantCulture),
+                b = float.Parse(colourParts[2], CultureInfo.InvariantCulture),
+                a = colourParts.Length == 4 ? float.Parse(colourParts[3], CultureInfo.InvariantCulture) : 1.0f,
             };
         }

diff --git a/source/FileFormatWavefront/FileFormatObj.cs b/source/FileFormatWavefront/FileFormatObj.cs
index 178accf..ed64712 100644
--- a/source/FileFormatWavefront/FileFormatObj.cs
+++ b/source/FileFormatWavefront/FileFormatObj.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Globalization;
 using System.IO;
 using System.Linq;
 using FileFormatWavefront.Extensions;
@@ -90,8 +91,8 @@ private static FileLoadResult<Scene> ReadScene(StreamReader reader, string path,
                         //  Add the UV.
                         uvs.Add(new UV
                                 {
-                                    u = float.Parse(dataStrings[0]),
-                                    v = float.Parse(dataStrings[1])
+                                    u = float.Parse(dataStrings[0], CultureInfo.InvariantCulture),
+                                    v = float.Parse(dataStrings[1], CultureInfo.InvariantCulture)
                                 });
                     }
                     catch (Exception exception)
@@ -108,9 +109,9 @@ private static FileLoadResult<Scene> ReadScene(StreamReader reader, string path,
                         var dataStrings = lineData.Split(dataSeparators, StringSplitOptions.RemoveEmptyEntries);
                         normals.Add(new Vertex
                                 {
-                                    x = float.Parse(dataStrings[0]),
-                                    y = float.Parse(dataStrings[1]),
-                                    z = float.Parse(dataStrings[2])
+                                    x = float.Parse(dataStrings[0], CultureInfo.InvariantCulture),
+                                    y = float.Parse(dataStrings[1], CultureInfo.InvariantCulture),
+                                    z = float.Parse(dataStrings[2], CultureInfo.InvariantCulture)
                                 });
                     }
                     catch (Exception exception)
@@ -127,9 +128,9 @@ private static FileLoadResult<Scene> ReadScene(StreamReader reader, string path,
                         var dataStrings = lineData.Split(dataSeparators, StringSplitOptions.RemoveEmptyEntries);
                         vertices.Add(new Vertex
                                 {
-                                    x = float.Parse(dataStrings[0]),
-                                    y = float.Parse(dataStrings[1]),
-                                    z = float.Parse(dataStrings[2])
+                                    x = float.Parse(dataStrings[0], CultureInfo.InvariantCulture),
+                                    y = float.Parse(dataStrings[1], CultureInfo.InvariantCulture),
+                                    z = float.Parse(dataStrings[2], CultureInfo.InvariantCulture)
                                 });
                     }
                     catch (Exception exception)
@@ -150,9 +151,9 @@ private static FileLoadResult<Scene> ReadScene(StreamReader reader, string path,
                         {
                             //  Split the parts.
                             var parts = indexString.Split(new[] { '/' }, StringSplitOptions.None);
-                            var vertex = MapIndex(vertices.Count, int.Parse(parts[0]));
-                            var uv = (parts.Length > 1 && parts[1].Length > 0) ? (int?)MapIndex(uvs.Count, int.Parse(parts[1])) : null;
-                            var normal = (parts.Length > 2 && parts[2].Length > 0) ? (int?)MapIndex(normals.Count, int.Parse(parts[2])) : null;
+                            var vertex = MapIndex(vertices.Count, int.Parse(parts[0], CultureInfo.InvariantCulture));
+                            var uv = (parts.Length > 1 && parts[1].Length > 0) ? (int?)MapIndex(uvs.Count, int.Parse(parts[1], CultureInfo.InvariantCulture)) : null;
+                            var normal = (parts.Length > 2 && parts[2].Length > 0) ? (int?)MapIndex(normals.Count, int.Parse(parts[2], CultureInfo.InvariantCulture)) : null;
                             indices.Add(new Index
                                         {
                                             vertex = vertex,
@@ -219,7 +220,7 @@ private static FileLoadResult<Scene> ReadScene(StreamReader reader, string path,
                     {
                         //  The smoothing group is an int, if we can get it.
                         int smoothingGroup;
-                        if(int.TryParse(lineData, out smoothingGroup))
+                        if(int.TryParse(lineData, NumberStyles.Integer, CultureInfo.InvariantCulture, out smoothingGroup))
                             currentGroup.SetSmoothingGroup(smoothingGroup);
                         currentGroup.SetSmoothingGroup(null);
                     }
-- 
1.8.4.msysgit.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.