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.

374 lines
12KB

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