View Javadoc
1   /*
2    * Copyright (C) 2012 Alberto Irurueta Carro (alberto@irurueta.com)
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.irurueta.geometry.io;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.util.HashSet;
21  import java.util.Set;
22  import java.util.StringTokenizer;
23  
24  /**
25   * MaterialLoader implementation for OBJ files, which is capable of reading its
26   * associated MTL file.
27   */
28  public class MaterialLoaderOBJ extends MaterialLoader {
29  
30      /**
31       * Maximum allowed color value.
32       */
33      public static final short MAX_COLOR_VALUE = 255;
34  
35      /**
36       * Set of materials loaded in MTL file.
37       */
38      private final Set<Material> materials = new HashSet<>();
39  
40      /**
41       * Current material being loaded.
42       */
43      private MaterialOBJ currentMaterial = null;
44  
45      /**
46       * Number of textures that have been found in MTL file.
47       */
48      private int textureCounter;
49  
50      /**
51       * Default Constructor.
52       */
53      public MaterialLoaderOBJ() {
54          super();
55      }
56  
57      /**
58       * Constructor.
59       *
60       * @param f material file to be read.
61       * @throws IOException raised if provided file does not exist or an I/O
62       *                     exception occurs.
63       */
64      public MaterialLoaderOBJ(final File f) throws IOException {
65          super(f);
66      }
67  
68      /**
69       * Constructor.
70       *
71       * @param listener material listener to notify start, end and progress
72       *                 events.
73       */
74      public MaterialLoaderOBJ(final MaterialLoaderListener listener) {
75          super(listener);
76      }
77  
78      /**
79       * Constructor.
80       *
81       * @param f        material file to be read.
82       * @param listener material listener to notify start, end and progress
83       *                 events.
84       * @throws IOException raised if provided file does not exist or an I/O
85       *                     exception occurs.
86       */
87      public MaterialLoaderOBJ(final File f, final MaterialLoaderListener listener) throws IOException {
88          super(f, listener);
89      }
90  
91      /**
92       * Indicates if material loader is ready to be used because a file has
93       * already been provided.
94       *
95       * @return true if material loader is ready, false otherwise.
96       */
97      @Override
98      public boolean isReady() {
99          return hasFile();
100     }
101 
102     /**
103      * Starts the loading process of provided file.
104      * This method returns a set containing all the materials that have been
105      * loaded.
106      *
107      * @return a set containing all the materials that have been loaded.
108      * @throws LockedException   raised if this instance is already locked.
109      * @throws NotReadyException raised if this instance is not yet ready.
110      * @throws IOException       if an I/O error occurs.
111      * @throws LoaderException   if file is corrupted or cannot be interpreted.
112      */
113     @Override
114     public Set<Material> load() throws LockedException, NotReadyException, IOException, LoaderException {
115         if (!isReady()) {
116             throw new NotReadyException();
117         }
118         if (isLocked()) {
119             throw new LockedException();
120         }
121 
122         setLocked(true);
123 
124         materials.clear();
125         textureCounter = 0;
126         currentMaterial = null;
127 
128         if (listener != null) {
129             listener.onLoadStart(this);
130         }
131 
132         // do not leave this loader locked if file cannot be loaded
133         loadReleasingLockOnFailure(() -> {
134             String line;
135             do {
136                 line = reader.readLine();
137                 if (line != null) {
138                     parseLine(line);
139                 }
140             } while (line != null);
141             return null;
142         });
143 
144         // files without any material definition produce an empty set
145         if (currentMaterial != null) {
146             currentMaterial.setId(materials.size());
147             materials.add(currentMaterial);
148         }
149 
150         if (listener != null) {
151             listener.onLoadEnd(this);
152         }
153 
154         setLocked(false);
155 
156         return materials;
157     }
158 
159     /**
160      * Parses a line in an MTL file.
161      *
162      * @param line line being parsed.
163      * @throws LoaderException if line cannot be interpreted.
164      */
165     @SuppressWarnings({"DuplicateExpressions", "DuplicatedCode"})
166     private void parseLine(final String line) throws LoaderException {
167         if (line == null || line.isEmpty()) {
168             return;
169         }
170 
171         try {
172             final var tokenizer = new StringTokenizer(line);
173             if (!tokenizer.hasMoreTokens()) {
174                 // empty line or simply
175                 // containing separators (tabs, line feeds, etc)
176                 return;
177             }
178 
179             final var command = tokenizer.nextToken();
180 
181             // search for command position
182             final var commandPos = line.indexOf(command);
183 
184             if ("newmtl".equalsIgnoreCase(command)) {
185                 if (currentMaterial != null) {
186                     currentMaterial.setId(materials.size());
187                     materials.add(currentMaterial);
188                 }
189                 final var name = line.substring(commandPos + command.length()).trim();
190                 currentMaterial = new MaterialOBJ(name);
191 
192             } else if ("ka".equalsIgnoreCase(command)) {
193                 if (currentMaterial == null) {
194                     throw new LoaderException();
195                 }
196                 currentMaterial.setAmbientColor(
197                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE),
198                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE),
199                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE));
200 
201             } else if ("kd".equalsIgnoreCase(command)) {
202                 if (currentMaterial == null) {
203                     throw new LoaderException();
204                 }
205                 currentMaterial.setDiffuseColor(
206                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE),
207                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE),
208                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE));
209 
210             } else if ("Ks".equalsIgnoreCase(command)) {
211                 if (currentMaterial == null) {
212                     throw new LoaderException();
213                 }
214                 currentMaterial.setSpecularColor(
215                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE),
216                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE),
217                         (short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE));
218 
219             } else if ("Ns".equalsIgnoreCase(command) || "Ni".equalsIgnoreCase(command)) {
220                 if (currentMaterial == null) {
221                     throw new LoaderException();
222                 }
223                 currentMaterial.setSpecularCoefficient(Float.parseFloat(tokenizer.nextToken()));
224 
225             } else if ("d".equalsIgnoreCase(command) || "Tr".equalsIgnoreCase(command)) {
226                 if (currentMaterial == null) {
227                     throw new LoaderException();
228                 }
229                 currentMaterial.setTransparency((short) (Float.parseFloat(tokenizer.nextToken()) * MAX_COLOR_VALUE));
230 
231             } else if ("illum".equalsIgnoreCase(command)) {
232                 if (currentMaterial == null) {
233                     throw new LoaderException();
234                 }
235                 currentMaterial.setIllumination(Illumination.forValue(Integer.parseInt(tokenizer.nextToken())));
236 
237             } else if ("map_Kd".equalsIgnoreCase(command)) {
238                 final var textureName = line.substring(commandPos + command.length()).trim();
239                 final var tex = new Texture(textureName, textureCounter);
240                 textureCounter++;
241 
242                 var valid = true;
243                 if (textureValidationEnabled && listener != null) {
244                     valid = listener.onValidateTexture(this, tex);
245                 }
246                 if (!valid) {
247                     throw new InvalidTextureException();
248                 }
249 
250                 currentMaterial.setDiffuseTextureMap(tex);
251 
252             } else if ("map_Ka".equalsIgnoreCase(command)) {
253                 final var textureName = line.substring(commandPos + command.length()).trim();
254                 final var tex = new Texture(textureName, textureCounter);
255                 textureCounter++;
256 
257                 var valid = true;
258                 if (textureValidationEnabled && listener != null) {
259                     valid = listener.onValidateTexture(this, tex);
260                 }
261                 if (!valid) throw new InvalidTextureException();
262 
263                 currentMaterial.setAmbientTextureMap(tex);
264 
265             } else if ("map_Ks".equalsIgnoreCase(command)) {
266                 final var textureName = line.substring(commandPos + command.length()).trim();
267                 final var tex = new Texture(textureName, textureCounter);
268                 textureCounter++;
269 
270                 var valid = true;
271                 if (textureValidationEnabled && listener != null) {
272                     valid = listener.onValidateTexture(this, tex);
273                 }
274                 if (!valid) {
275                     throw new InvalidTextureException();
276                 }
277 
278                 currentMaterial.setSpecularTextureMap(tex);
279 
280             } else if ("map_d".equalsIgnoreCase(command)) {
281                 final var textureName = line.substring(commandPos + command.length()).trim();
282                 final var tex = new Texture(textureName, textureCounter);
283                 textureCounter++;
284 
285                 var valid = true;
286                 if (textureValidationEnabled && listener != null) {
287                     valid = listener.onValidateTexture(this, tex);
288                 }
289                 if (!valid) {
290                     throw new InvalidTextureException();
291                 }
292 
293                 currentMaterial.setAlphaTextureMap(tex);
294 
295             } else if ("map_bump".equalsIgnoreCase(command) || "bump".equalsIgnoreCase(command)) {
296                 final var textureName = line.substring(commandPos + command.length()).trim();
297                 final var tex = new Texture(textureName, textureCounter);
298                 textureCounter++;
299 
300                 var valid = true;
301                 if (textureValidationEnabled && listener != null) {
302                     valid = listener.onValidateTexture(this, tex);
303                 }
304                 if (!valid) {
305                     throw new InvalidTextureException();
306                 }
307 
308                 currentMaterial.setBumpTextureMap(tex);
309             }
310         } catch (final Exception t) {
311             throw new LoaderException(t);
312         }
313     }
314 
315     /**
316      * Indicates if any material has been loaded already.
317      *
318      * @return true if materials have been loaded, false otherwise.
319      */
320     public boolean areMaterialsAvailable() {
321         return !materials.isEmpty();
322     }
323 
324     /**
325      * Returns set of materials that have been read.
326      *
327      * @return set of materials that have been read.
328      */
329     public Set<Material> getMaterials() {
330         return materials;
331     }
332 
333     /**
334      * Gets a material by its name, or null if material is not found.
335      *
336      * @param name name of material to be found.
337      * @return a material having provided name or null if none is found.
338      */
339     public MaterialOBJ getMaterialByName(final String name) {
340         if (name == null) {
341             return null;
342         }
343 
344         for (final var m : this.materials) {
345             if (m instanceof MaterialOBJ m2) {
346 
347                 if (m2.getMaterialName() == null) {
348                     continue;
349                 }
350 
351                 if (m2.getMaterialName().equals(name)) {
352                     return m2;
353                 }
354             }
355         }
356         return null;
357     }
358 
359     /**
360      * Indicates if material having provided name has been loaded or not.
361      *
362      * @param name name to search material by.
363      * @return true if material having provided name exists, false otherwise.
364      */
365     public boolean containsMaterial(final String name) {
366         return getMaterialByName(name) != null;
367     }
368 
369     /**
370      * Returns material by texture name.
371      *
372      * @param name name of texture.
373      * @return texture that has been found or null if none has been found.
374      */
375     public Material getMaterialByTextureMapName(final String name) {
376         if (name == null) {
377             return null;
378         }
379 
380         for (final Material m : this.materials) {
381             if (m.getAlphaTextureMap() != null && m.getAlphaTextureMap().getFileName() != null
382                     && m.getAlphaTextureMap().getFileName().equals(name)) {
383                 return m;
384             }
385 
386             if (m.getAmbientTextureMap() != null && m.getAmbientTextureMap().getFileName() != null
387                     && m.getAmbientTextureMap().getFileName().equals(name)) {
388                 return m;
389             }
390 
391             if (m.getDiffuseTextureMap() != null && m.getDiffuseTextureMap().getFileName() != null
392                     && m.getDiffuseTextureMap().getFileName().equals(name)) {
393                 return m;
394             }
395 
396             if (m.getSpecularTextureMap() != null && m.getSpecularTextureMap().getFileName() != null
397                     && m.getSpecularTextureMap().getFileName().equals(name)) {
398                 return m;
399             }
400         }
401         return null;
402     }
403 }