The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

373 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2015 by ROLI Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.juce.com for more information.
  16. ==============================================================================
  17. */
  18. #include <map>
  19. //==============================================================================
  20. /**
  21. This is a quick-and-dirty parser for the 3D OBJ file format.
  22. Just call load() and if there aren't any errors, the 'shapes' array should
  23. be filled with all the shape objects that were loaded from the file.
  24. */
  25. class WavefrontObjFile
  26. {
  27. public:
  28. WavefrontObjFile() {}
  29. Result load (const String& objFileContent)
  30. {
  31. shapes.clear();
  32. return parseObjFile (StringArray::fromLines (objFileContent));
  33. }
  34. Result load (const File& file)
  35. {
  36. sourceFile = file;
  37. return load (file.loadFileAsString());
  38. }
  39. //==============================================================================
  40. typedef juce::uint32 Index;
  41. struct Vertex { float x, y, z; };
  42. struct TextureCoord { float x, y; };
  43. struct Mesh
  44. {
  45. Array<Vertex> vertices, normals;
  46. Array<TextureCoord> textureCoords;
  47. Array<Index> indices;
  48. };
  49. struct Material
  50. {
  51. Material() noexcept : shininess (1.0f), refractiveIndex (0.0f)
  52. {
  53. zerostruct (ambient);
  54. zerostruct (diffuse);
  55. zerostruct (specular);
  56. zerostruct (transmittance);
  57. zerostruct (emission);
  58. }
  59. String name;
  60. Vertex ambient, diffuse, specular, transmittance, emission;
  61. float shininess, refractiveIndex;
  62. String ambientTextureName, diffuseTextureName,
  63. specularTextureName, normalTextureName;
  64. StringPairArray parameters;
  65. };
  66. struct Shape
  67. {
  68. String name;
  69. Mesh mesh;
  70. Material material;
  71. };
  72. OwnedArray<Shape> shapes;
  73. private:
  74. //==============================================================================
  75. File sourceFile;
  76. struct TripleIndex
  77. {
  78. TripleIndex() noexcept : vertexIndex (-1), textureIndex (-1), normalIndex (-1) {}
  79. bool operator< (const TripleIndex& other) const noexcept
  80. {
  81. if (this == &other)
  82. return false;
  83. if (vertexIndex != other.vertexIndex)
  84. return vertexIndex < other.vertexIndex;
  85. if (textureIndex != other.textureIndex)
  86. return textureIndex < other.textureIndex;
  87. return normalIndex < other.normalIndex;
  88. }
  89. int vertexIndex, textureIndex, normalIndex;
  90. };
  91. struct IndexMap
  92. {
  93. std::map<TripleIndex, Index> map;
  94. Index getIndexFor (TripleIndex i, Mesh& newMesh, const Mesh& srcMesh)
  95. {
  96. const std::map<TripleIndex, Index>::iterator it (map.find (i));
  97. if (it != map.end())
  98. return it->second;
  99. const Index index = (Index) newMesh.vertices.size();
  100. if (isPositiveAndBelow (i.vertexIndex, srcMesh.vertices.size()))
  101. newMesh.vertices.add (srcMesh.vertices.getReference (i.vertexIndex));
  102. if (isPositiveAndBelow (i.normalIndex, srcMesh.normals.size()))
  103. newMesh.normals.add (srcMesh.normals.getReference (i.normalIndex));
  104. if (isPositiveAndBelow (i.textureIndex, srcMesh.textureCoords.size()))
  105. newMesh.textureCoords.add (srcMesh.textureCoords.getReference (i.textureIndex));
  106. map[i] = index;
  107. return index;
  108. }
  109. };
  110. static float parseFloat (String::CharPointerType& t)
  111. {
  112. t = t.findEndOfWhitespace();
  113. return (float) CharacterFunctions::readDoubleValue (t);
  114. }
  115. static Vertex parseVertex (String::CharPointerType t)
  116. {
  117. Vertex v;
  118. v.x = parseFloat (t);
  119. v.y = parseFloat (t);
  120. v.z = parseFloat (t);
  121. return v;
  122. }
  123. static TextureCoord parseTextureCoord (String::CharPointerType t)
  124. {
  125. TextureCoord tc;
  126. tc.x = parseFloat (t);
  127. tc.y = parseFloat (t);
  128. return tc;
  129. }
  130. static bool matchToken (String::CharPointerType& t, const char* token)
  131. {
  132. const int len = (int) strlen (token);
  133. if (CharacterFunctions::compareUpTo (CharPointer_ASCII (token), t, len) == 0)
  134. {
  135. String::CharPointerType end = t + len;
  136. if (end.isEmpty() || end.isWhitespace())
  137. {
  138. t = end.findEndOfWhitespace();
  139. return true;
  140. }
  141. }
  142. return false;
  143. }
  144. struct Face
  145. {
  146. Face (String::CharPointerType t)
  147. {
  148. while (! t.isEmpty())
  149. triples.add (parseTriple (t));
  150. }
  151. Array<TripleIndex> triples;
  152. void addIndices (Mesh& newMesh, const Mesh& srcMesh, IndexMap& indexMap)
  153. {
  154. TripleIndex i0 (triples[0]), i1, i2 (triples[1]);
  155. for (int i = 2; i < triples.size(); ++i)
  156. {
  157. i1 = i2;
  158. i2 = triples.getReference (i);
  159. newMesh.indices.add (indexMap.getIndexFor (i0, newMesh, srcMesh));
  160. newMesh.indices.add (indexMap.getIndexFor (i1, newMesh, srcMesh));
  161. newMesh.indices.add (indexMap.getIndexFor (i2, newMesh, srcMesh));
  162. }
  163. }
  164. static TripleIndex parseTriple (String::CharPointerType& t)
  165. {
  166. TripleIndex i;
  167. t = t.findEndOfWhitespace();
  168. i.vertexIndex = t.getIntValue32() - 1;
  169. t = findEndOfFaceToken (t);
  170. if (t.isEmpty() || t.getAndAdvance() != '/')
  171. return i;
  172. if (*t == '/')
  173. {
  174. ++t;
  175. }
  176. else
  177. {
  178. i.textureIndex = t.getIntValue32() - 1;
  179. t = findEndOfFaceToken (t);
  180. if (t.isEmpty() || t.getAndAdvance() != '/')
  181. return i;
  182. }
  183. i.normalIndex = t.getIntValue32() - 1;
  184. t = findEndOfFaceToken (t);
  185. return i;
  186. }
  187. static String::CharPointerType findEndOfFaceToken (String::CharPointerType t) noexcept
  188. {
  189. return CharacterFunctions::findEndOfToken (t, CharPointer_ASCII ("/ \t"), String().getCharPointer());
  190. }
  191. };
  192. static Shape* parseFaceGroup (const Mesh& srcMesh,
  193. const Array<Face>& faceGroup,
  194. const Material& material,
  195. const String& name)
  196. {
  197. if (faceGroup.size() == 0)
  198. return nullptr;
  199. ScopedPointer<Shape> shape (new Shape());
  200. shape->name = name;
  201. shape->material = material;
  202. IndexMap indexMap;
  203. for (int i = 0; i < faceGroup.size(); ++i)
  204. faceGroup.getReference(i).addIndices (shape->mesh, srcMesh, indexMap);
  205. return shape.release();
  206. }
  207. Result parseObjFile (const StringArray& lines)
  208. {
  209. Mesh mesh;
  210. Array<Face> faceGroup;
  211. Array<Material> knownMaterials;
  212. Material lastMaterial;
  213. String lastName;
  214. for (int lineNum = 0; lineNum < lines.size(); ++lineNum)
  215. {
  216. String::CharPointerType l = lines[lineNum].getCharPointer().findEndOfWhitespace();
  217. if (matchToken (l, "v")) { mesh.vertices.add (parseVertex (l)); continue; }
  218. if (matchToken (l, "vn")) { mesh.normals.add (parseVertex (l)); continue; }
  219. if (matchToken (l, "vt")) { mesh.textureCoords.add (parseTextureCoord (l)); continue; }
  220. if (matchToken (l, "f")) { faceGroup.add (Face (l)); continue; }
  221. if (matchToken (l, "usemtl"))
  222. {
  223. const String name (String (l).trim());
  224. for (int i = knownMaterials.size(); --i >= 0;)
  225. {
  226. if (knownMaterials.getReference(i).name == name)
  227. {
  228. lastMaterial = knownMaterials.getReference(i);
  229. break;
  230. }
  231. }
  232. continue;
  233. }
  234. if (matchToken (l, "mtllib"))
  235. {
  236. Result r = parseMaterial (knownMaterials, String (l).trim());
  237. continue;
  238. }
  239. if (matchToken (l, "g") || matchToken (l, "o"))
  240. {
  241. if (Shape* shape = parseFaceGroup (mesh, faceGroup, lastMaterial, lastName))
  242. shapes.add (shape);
  243. faceGroup.clear();
  244. lastName = StringArray::fromTokens (l, " \t", "")[0];
  245. continue;
  246. }
  247. }
  248. if (Shape* shape = parseFaceGroup (mesh, faceGroup, lastMaterial, lastName))
  249. shapes.add (shape);
  250. return Result::ok();
  251. }
  252. Result parseMaterial (Array<Material>& materials, const String& filename)
  253. {
  254. jassert (sourceFile.exists());
  255. File f (sourceFile.getSiblingFile (filename));
  256. if (! f.exists())
  257. return Result::fail ("Cannot open file: " + filename);
  258. StringArray lines;
  259. lines.addLines (f.loadFileAsString());
  260. materials.clear();
  261. Material material;
  262. for (int i = 0; i < lines.size(); ++i)
  263. {
  264. String::CharPointerType l (lines[i].getCharPointer().findEndOfWhitespace());
  265. if (matchToken (l, "newmtl")) { materials.add (material); material.name = String (l).trim(); continue; }
  266. if (matchToken (l, "Ka")) { material.ambient = parseVertex (l); continue; }
  267. if (matchToken (l, "Kd")) { material.diffuse = parseVertex (l); continue; }
  268. if (matchToken (l, "Ks")) { material.specular = parseVertex (l); continue; }
  269. if (matchToken (l, "Kt")) { material.transmittance = parseVertex (l); continue; }
  270. if (matchToken (l, "Ke")) { material.emission = parseVertex (l); continue; }
  271. if (matchToken (l, "Ni")) { material.refractiveIndex = parseFloat (l); continue; }
  272. if (matchToken (l, "Ns")) { material.shininess = parseFloat (l); continue; }
  273. if (matchToken (l, "map_Ka")) { material.ambientTextureName = String (l).trim(); continue; }
  274. if (matchToken (l, "map_Kd")) { material.diffuseTextureName = String (l).trim(); continue; }
  275. if (matchToken (l, "map_Ks")) { material.specularTextureName = String (l).trim(); continue; }
  276. if (matchToken (l, "map_Ns")) { material.normalTextureName = String (l).trim(); continue; }
  277. StringArray tokens;
  278. tokens.addTokens (l, " \t", "");
  279. if (tokens.size() >= 2)
  280. material.parameters.set (tokens[0].trim(), tokens[1].trim());
  281. }
  282. materials.add (material);
  283. return Result::ok();
  284. }
  285. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavefrontObjFile)
  286. };