-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMTLLoader.cs
More file actions
307 lines (257 loc) · 10.5 KB
/
Copy pathMTLLoader.cs
File metadata and controls
307 lines (257 loc) · 10.5 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
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
/*
* Copyright (c) 2019 Dummiesman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
using Dummiesman;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class MTLLoader {
public List<string> SearchPaths = new List<string>() { "%FileName%_Textures", string.Empty};
private FileInfo _objFileInfo = null;
/// <summary>
/// The texture loading function. Overridable for stream loading purposes.
/// </summary>
/// <param name="path">The path supplied by the OBJ file, converted to OS path seperation</param>
/// <param name="isNormalMap">Whether the loader is requesting we convert this into a normal map</param>
/// <returns>Texture2D if found, or NULL if missing</returns>
public virtual Texture2D TextureLoadFunction(string path, bool isNormalMap)
{
//find it
foreach (var searchPath in SearchPaths)
{
//replace varaibles and combine path
string processedPath = (_objFileInfo != null) ? searchPath.Replace("%FileName%", Path.GetFileNameWithoutExtension(_objFileInfo.Name))
: searchPath;
string filePath = Path.Combine(processedPath, path);
//return if eists
if (File.Exists(filePath))
{
var tex = ImageLoader.LoadTexture(filePath);
if(isNormalMap)
tex = ImageUtils.ConvertToNormalMap(tex);
return tex;
}
}
//not found
return null;
}
private Texture2D TryLoadTexture(string texturePath, bool normalMap = false)
{
//swap directory seperator char
texturePath = texturePath.Replace('\\', Path.DirectorySeparatorChar);
texturePath = texturePath.Replace('/', Path.DirectorySeparatorChar);
return TextureLoadFunction(texturePath, normalMap);
}
private int GetArgValueCount(string arg)
{
switch (arg)
{
case "-bm":
case "-clamp":
case "-blendu":
case "-blendv":
case "-imfchan":
case "-texres":
return 1;
case "-mm":
return 2;
case "-o":
case "-s":
case "-t":
return 3;
}
return -1;
}
private int GetTexNameIndex(string[] components)
{
for(int i=1; i < components.Length; i++)
{
var cmpSkip = GetArgValueCount(components[i]);
if(cmpSkip < 0)
{
return i;
}
i += cmpSkip;
}
return -1;
}
private float GetArgValue(string[] components, string arg, float fallback = 1f)
{
string argLower = arg.ToLower();
for(int i=1; i < components.Length - 1; i++)
{
var cmp = components[i].ToLower();
if(argLower == cmp)
{
return OBJLoaderHelper.FastFloatParse(components[i+1]);
}
}
return fallback;
}
private string GetTexPathFromMapStatement(string processedLine, string[] splitLine)
{
int texNameCmpIdx = GetTexNameIndex(splitLine);
if(texNameCmpIdx < 0)
{
Debug.LogError($"texNameCmpIdx < 0 on line {processedLine}. Texture not loaded.");
return null;
}
int texNameIdx = processedLine.IndexOf(splitLine[texNameCmpIdx]);
string texturePath = processedLine.Substring(texNameIdx);
return texturePath;
}
/// <summary>
/// Loads a *.mtl file
/// </summary>
/// <param name="input">The input stream from the MTL file</param>
/// <returns>Dictionary containing loaded materials</returns>
public Dictionary<string, Material> Load(Stream input)
{
var inputReader = new StreamReader(input);
var reader = new StringReader(inputReader.ReadToEnd());
Dictionary<string, Material> mtlDict = new Dictionary<string, Material>();
Material currentMaterial = null;
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
if (string.IsNullOrWhiteSpace(line))
continue;
string processedLine = line.Clean();
string[] splitLine = processedLine.Split(' ');
//blank or comment
if (splitLine.Length < 2 || processedLine[0] == '#')
continue;
//newmtl
if (splitLine[0] == "newmtl")
{
string materialName = processedLine.Substring(7);
var newMtl = new Material(Shader.Find("Standard (Specular setup)")) { name = materialName };
mtlDict[materialName] = newMtl;
currentMaterial = newMtl;
continue;
}
//anything past here requires a material instance
if (currentMaterial == null)
continue;
//diffuse color
if (splitLine[0] == "Kd" || splitLine[0] == "kd")
{
var currentColor = currentMaterial.GetColor("_Color");
var kdColor = OBJLoaderHelper.ColorFromStrArray(splitLine);
currentMaterial.SetColor("_Color", new Color(kdColor.r, kdColor.g, kdColor.b, currentColor.a));
continue;
}
//diffuse map
if (splitLine[0] == "map_Kd" || splitLine[0] == "map_kd")
{
string texturePath = GetTexPathFromMapStatement(processedLine, splitLine);
if(texturePath == null)
{
continue; //invalid args or sth
}
var KdTexture = TryLoadTexture(texturePath);
currentMaterial.SetTexture("_MainTex", KdTexture);
//set transparent mode if the texture has transparency
if(KdTexture != null && (KdTexture.format == TextureFormat.DXT5 || KdTexture.format == TextureFormat.ARGB32))
{
OBJLoaderHelper.EnableMaterialTransparency(currentMaterial);
}
//flip texture if this is a dds
if(Path.GetExtension(texturePath).ToLower() == ".dds")
{
currentMaterial.mainTextureScale = new Vector2(1f, -1f);
}
continue;
}
//bump map
if (splitLine[0] == "map_Bump" || splitLine[0] == "map_bump")
{
string texturePath = GetTexPathFromMapStatement(processedLine, splitLine);
if(texturePath == null)
{
continue; //invalid args or sth
}
var bumpTexture = TryLoadTexture(texturePath, true);
float bumpScale = GetArgValue(splitLine, "-bm", 1.0f);
if (bumpTexture != null) {
currentMaterial.SetTexture("_BumpMap", bumpTexture);
currentMaterial.SetFloat("_BumpScale", bumpScale);
currentMaterial.EnableKeyword("_NORMALMAP");
}
continue;
}
//specular color
if (splitLine[0] == "Ks" || splitLine[0] == "ks")
{
currentMaterial.SetColor("_SpecColor", OBJLoaderHelper.ColorFromStrArray(splitLine));
continue;
}
//emission color
if (splitLine[0] == "Ka" || splitLine[0] == "ka")
{
currentMaterial.SetColor("_EmissionColor", OBJLoaderHelper.ColorFromStrArray(splitLine, 0.05f));
currentMaterial.EnableKeyword("_EMISSION");
continue;
}
//emission map
if (splitLine[0] == "map_Ka" || splitLine[0] == "map_ka")
{
string texturePath = GetTexPathFromMapStatement(processedLine, splitLine);
if(texturePath == null)
{
continue; //invalid args or sth
}
currentMaterial.SetTexture("_EmissionMap", TryLoadTexture(texturePath));
continue;
}
//alpha
if (splitLine[0] == "d" || splitLine[0] == "Tr")
{
float visibility = OBJLoaderHelper.FastFloatParse(splitLine[1]);
//tr statement is just d inverted
if(splitLine[0] == "Tr")
visibility = 1f - visibility;
if(visibility < (1f - Mathf.Epsilon))
{
var currentColor = currentMaterial.GetColor("_Color");
currentColor.a = visibility;
currentMaterial.SetColor("_Color", currentColor);
OBJLoaderHelper.EnableMaterialTransparency(currentMaterial);
}
continue;
}
//glossiness
if (splitLine[0] == "Ns" || splitLine[0] == "ns")
{
float Ns = OBJLoaderHelper.FastFloatParse(splitLine[1]);
Ns = (Ns / 1000f);
currentMaterial.SetFloat("_Glossiness", Ns);
}
}
//return our dict
return mtlDict;
}
/// <summary>
/// Loads a *.mtl file
/// </summary>
/// <param name="path">The path to the MTL file</param>
/// <returns>Dictionary containing loaded materials</returns>
public Dictionary<string, Material> Load(string path)
{
_objFileInfo = new FileInfo(path); //get file info
SearchPaths.Add(_objFileInfo.Directory.FullName); //add root path to search dir
using (var fs = new FileStream(path, FileMode.Open))
{
return Load(fs); //actually load
}
}
}