forked from veldrid/veldrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMtlParser.cs
354 lines (318 loc) · 13.2 KB
/
MtlParser.cs
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
namespace Veldrid.Utilities
{
/// <summary>
/// A parser for Wavefront MTL files.
/// </summary>
public class MtlParser
{
private static readonly string[] s_newline = new string[] { "\n" };
private readonly ParseContext _pc = new ParseContext();
/// <summary>
/// Parses a <see cref="MtlFile"/> from the given array of text lines.
/// </summary>
/// <param name="lines">The raw text lines of the MTL file.</param>
/// <returns>A new <see cref="MtlFile"/>.</returns>
public MtlFile Parse(string[] lines)
{
foreach (string line in lines)
{
_pc.Process(line);
}
_pc.EndOfFileReached();
return _pc.FinalizeFile();
}
/// <summary>
/// Parses a <see cref="MtlFile"/> from the given stream
/// </summary>
/// <param name="s">The stream to parse from.</param>
/// <returns>A new <see cref="MtlFile"/>.</returns>
public MtlFile Parse(Stream s)
{
string text;
using (StreamReader sr = new StreamReader(s))
{
text = sr.ReadToEnd();
}
int lineStart = 0;
int lineEnd = -1;
while ((lineEnd = text.IndexOf('\n', lineStart)) != -1)
{
string line;
if (lineEnd != 0 && text[lineEnd - 1] == '\r')
{
line = text.Substring(lineStart, lineEnd - lineStart - 1);
}
else
{
line = text.Substring(lineStart, lineEnd - lineStart);
}
_pc.Process(line);
lineStart = lineEnd + 1;
}
_pc.EndOfFileReached();
return _pc.FinalizeFile();
}
private class ParseContext
{
private static readonly char[] s_whitespaceChars = new char[] { ' ' };
private readonly List<MaterialDefinition> _definitions = new List<MaterialDefinition>();
private MaterialDefinition _currentDefinition;
private int _currentLine;
private string _currentLineText;
public void Process(string line)
{
_currentLine++;
_currentLineText = line;
string[] pieces = line.Split(s_whitespaceChars, StringSplitOptions.RemoveEmptyEntries);
if (pieces.Length == 0 || pieces[0].StartsWith("#"))
{
return;
}
switch (pieces[0].ToLowerInvariant().Trim())
{
case "newmtl":
ExpectExactly(pieces, 1, "newmtl");
FinalizeCurrentMaterial();
_currentDefinition = new MaterialDefinition(pieces[1]);
break;
case "ka":
ExpectExactly(pieces, 3, "Ka");
_currentDefinition.AmbientReflectivity = ParseVector3(pieces[1], pieces[2], pieces[3], "Ka");
break;
case "kd":
ExpectExactly(pieces, 3, "Kd");
_currentDefinition.DiffuseReflectivity = ParseVector3(pieces[1], pieces[2], pieces[3], "Kd");
break;
case "ks":
ExpectExactly(pieces, 3, "Ks");
_currentDefinition.SpecularReflectivity = ParseVector3(pieces[1], pieces[2], pieces[3], "Ks");
break;
case "ke": // Non-standard?
ExpectExactly(pieces, 3, "Ke");
_currentDefinition.EmissiveCoefficient = ParseVector3(pieces[1], pieces[2], pieces[3], "Ks");
break;
case "tf":
ExpectExactly(pieces, 3, "Tf");
_currentDefinition.TransmissionFilter = ParseVector3(pieces[1], pieces[2], pieces[3], "Tf");
break;
case "illum":
ExpectExactly(pieces, 1, "illum");
_currentDefinition.IlluminationModel = ParseInt(pieces[1], "illum");
break;
case "d": // "Dissolve", or opacity
ExpectExactly(pieces, 1, "d");
_currentDefinition.Opacity = ParseFloat(pieces[1], "d");
break;
case "tr": // Transparency
ExpectExactly(pieces, 1, "Tr");
_currentDefinition.Opacity = 1 - ParseFloat(pieces[1], "Tr");
break;
case "ns":
ExpectExactly(pieces, 1, "Ns");
_currentDefinition.SpecularExponent = ParseFloat(pieces[1], "Ns");
break;
case "sharpness":
ExpectExactly(pieces, 1, "sharpness");
_currentDefinition.Sharpness = ParseFloat(pieces[1], "sharpness");
break;
case "ni": // "Index of refraction"
ExpectExactly(pieces, 1, "Ni");
_currentDefinition.OpticalDensity = ParseFloat(pieces[1], "Ni");
break;
case "map_ka":
ExpectExactly(pieces, 1, "map_ka");
_currentDefinition.AmbientTexture = pieces[1];
break;
case "map_kd":
ExpectExactly(pieces, 1, "map_kd");
_currentDefinition.DiffuseTexture = pieces[1];
break;
case "map_ks":
ExpectExactly (pieces, 1, "map_ks");
_currentDefinition.SpecularColorTexture = pieces [1];
break;
case "map_bump":
case "bump":
ExpectExactly(pieces, 1, "map_bump");
_currentDefinition.BumpMap = pieces[1];
break;
case "map_d":
ExpectExactly(pieces, 1, "map_d");
_currentDefinition.AlphaMap = pieces[1];
break;
case "map_ns":
ExpectExactly(pieces, 1, "map_ns");
_currentDefinition.SpecularHighlightTexture = pieces[1];
break;
default:
throw new ObjParseException(
string.Format("An unsupported line-type specifier, '{0}', was used on line {1}, \"{2}\"",
pieces[0],
_currentLine,
_currentLineText));
}
}
private void FinalizeCurrentMaterial()
{
if (_currentDefinition != null)
{
_definitions.Add(_currentDefinition);
_currentDefinition = null;
}
}
public void EndOfFileReached()
{
FinalizeCurrentMaterial();
}
public MtlFile FinalizeFile()
{
return new MtlFile(_definitions);
}
private Vector3 ParseVector3(string xStr, string yStr, string zStr, string location)
{
try
{
float x = float.Parse(xStr, CultureInfo.InvariantCulture);
float y = float.Parse(yStr, CultureInfo.InvariantCulture);
float z = float.Parse(zStr, CultureInfo.InvariantCulture);
return new Vector3(x, y, z);
}
catch (FormatException fe)
{
throw CreateParseException(location, fe);
}
}
private Vector2 ParseVector2(string xStr, string yStr, string location)
{
try
{
float x = float.Parse(xStr, CultureInfo.InvariantCulture);
float y = float.Parse(yStr, CultureInfo.InvariantCulture);
return new Vector2(x, y);
}
catch (FormatException fe)
{
throw CreateParseException(location, fe);
}
}
private int ParseInt(string intStr, string location)
{
try
{
int i = int.Parse(intStr, CultureInfo.InvariantCulture);
return i;
}
catch (FormatException fe)
{
throw CreateParseException(location, fe);
}
}
private float ParseFloat(string intStr, string location)
{
try
{
float f = float.Parse(intStr, CultureInfo.InvariantCulture);
return f;
}
catch (FormatException fe)
{
throw CreateParseException(location, fe);
}
}
private void ExpectExactly(string[] pieces, int count, string name)
{
if (pieces.Length != count + 1)
{
string message = string.Format(
"Expected exactly {0} components to a line starting with {1}, on line {2}, \"{3}\".",
count,
name,
_currentLine,
_currentLineText);
throw new MtlParseException(message);
}
}
private void ExpectAtLeast(string[] pieces, int count, string name)
{
if (pieces.Length < count + 1)
{
string message = string.Format(
"Expected at least {0} components to a line starting with {1}, on line {2}, \"{3}\".",
count,
name,
_currentLine,
_currentLineText);
throw new MtlParseException(message);
}
}
private MtlParseException CreateParseException(string location, Exception e)
{
string message = string.Format("An error ocurred while parsing {0} on line {1}, \"{2}\"", location, _currentLine, _currentLineText);
return new MtlParseException(message, e);
}
}
}
public class MtlParseException : Exception
{
public MtlParseException(string message) : base(message)
{
}
public MtlParseException(string message, Exception innerException) : base(message, innerException)
{
}
}
/// <summary>
/// Represents a parsed MTL definition file.
/// </summary>
public class MtlFile
{
/// <summary>
/// Gets a mapping of all <see cref="MaterialDefinition"/>s contained in this <see cref="MtlFile"/>.
/// </summary>
public IReadOnlyDictionary<string, MaterialDefinition> Definitions { get; }
/// <summary>
/// Constructs a new <see cref="MtlFile"/> from pre-parsed material definitions.
/// </summary>
/// <param name="definitions">A collection of material definitions.</param>
public MtlFile(IEnumerable<MaterialDefinition> definitions)
{
Definitions = definitions.ToDictionary(def => def.Name);
}
}
/// <summary>
/// An individual material definition from a Wavefront MTL file.
/// </summary>
public class MaterialDefinition
{
internal MaterialDefinition(string name)
{
Name = name;
}
public string Name { get; }
public Vector3 AmbientReflectivity { get; internal set; }
public Vector3 DiffuseReflectivity { get; internal set; }
public Vector3 SpecularReflectivity { get; internal set; }
public Vector3 EmissiveCoefficient { get; internal set; }
public Vector3 TransmissionFilter { get; internal set; }
public int IlluminationModel { get; internal set; }
public float Opacity { get; internal set; }
public float Transparency => 1 - Opacity;
public float SpecularExponent { get; internal set; }
public float Sharpness { get; internal set; }
public float OpticalDensity { get; internal set; }
public string AmbientTexture { get; internal set; }
public string DiffuseTexture { get; internal set; }
public string SpecularColorTexture { get; internal set; }
public string SpecularHighlightTexture { get; internal set; }
public string AlphaMap { get; internal set; }
public string BumpMap { get; internal set; }
public string DisplacementMap { get; internal set; }
public string StencilDecalTexture { get; internal set; }
}
}