par_shapes.h 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  1. // SHAPES :: https://github.com/prideout/par
  2. // Simple C library for creation and manipulation of triangle meshes.
  3. //
  4. // The API is divided into three sections:
  5. //
  6. // - Generators. Create parametric surfaces, platonic solids, etc.
  7. // - Queries. Ask a mesh for its axis-aligned bounding box, etc.
  8. // - Transforms. Rotate a mesh, merge it with another, add normals, etc.
  9. //
  10. // In addition to the comment block above each function declaration, the API
  11. // has informal documentation here:
  12. //
  13. // http://github.prideout.net/shapes/
  14. //
  15. // For our purposes, a "mesh" is a list of points and a list of triangles; the
  16. // former is a flattened list of three-tuples (32-bit floats) and the latter is
  17. // also a flattened list of three-tuples (16-bit uints). Triangles are always
  18. // oriented such that their front face winds counter-clockwise.
  19. //
  20. // Optionally, meshes can contain 3D normals (one per vertex), and 2D texture
  21. // coordinates (one per vertex). That's it! If you need something fancier,
  22. // look elsewhere.
  23. //
  24. // The MIT License
  25. // Copyright (c) 2015 Philip Rideout
  26. #ifndef PAR_SHAPES_H
  27. #define PAR_SHAPES_H
  28. #ifdef __cplusplus
  29. extern "C" {
  30. #endif
  31. #include <stdint.h>
  32. #include <stdbool.h>
  33. #ifndef PAR_SHAPES_T
  34. #define PAR_SHAPES_T uint16_t
  35. #endif
  36. typedef struct par_shapes_mesh_s {
  37. float* points; // Flat list of 3-tuples (X Y Z X Y Z...)
  38. int npoints; // Number of points
  39. PAR_SHAPES_T* triangles; // Flat list of 3-tuples (I J K I J K...)
  40. int ntriangles; // Number of triangles
  41. float* normals; // Optional list of 3-tuples (X Y Z X Y Z...)
  42. float* tcoords; // Optional list of 2-tuples (U V U V U V...)
  43. } par_shapes_mesh;
  44. void par_shapes_free_mesh(par_shapes_mesh*);
  45. // Generators ------------------------------------------------------------------
  46. // Instance a cylinder that sits on the Z=0 plane using the given tessellation
  47. // levels across the UV domain. Think of "slices" like a number of pizza
  48. // slices, and "stacks" like a number of stacked rings. Height and radius are
  49. // both 1.0, but they can easily be changed with par_shapes_scale.
  50. par_shapes_mesh* par_shapes_create_cylinder(int slices, int stacks);
  51. // Create a donut that sits on the Z=0 plane with the specified inner radius.
  52. // The outer radius can be controlled with par_shapes_scale.
  53. par_shapes_mesh* par_shapes_create_torus(int slices, int stacks, float radius);
  54. // Create a sphere with texture coordinates and small triangles near the poles.
  55. par_shapes_mesh* par_shapes_create_parametric_sphere(int slices, int stacks);
  56. // Approximate a sphere with a subdivided icosahedron, which produces a nice
  57. // distribution of triangles, but no texture coordinates. Each subdivision
  58. // level scales the number of triangles by four, so use a very low number.
  59. par_shapes_mesh* par_shapes_create_subdivided_sphere(int nsubdivisions);
  60. // More parametric surfaces.
  61. par_shapes_mesh* par_shapes_create_klein_bottle(int slices, int stacks);
  62. par_shapes_mesh* par_shapes_create_trefoil_knot(int slices, int stacks,
  63. float radius);
  64. par_shapes_mesh* par_shapes_create_hemisphere(int slices, int stacks);
  65. par_shapes_mesh* par_shapes_create_plane(int slices, int stacks);
  66. // Create a parametric surface from a callback function that consumes a 2D
  67. // point in [0,1] and produces a 3D point.
  68. typedef void (*par_shapes_fn)(float const*, float*, void*);
  69. par_shapes_mesh* par_shapes_create_parametric(par_shapes_fn, int slices,
  70. int stacks, void* userdata);
  71. // Generate points for a 20-sided polyhedron that fits in the unit sphere.
  72. // Texture coordinates and normals are not generated.
  73. par_shapes_mesh* par_shapes_create_icosahedron();
  74. // Generate points for a 12-sided polyhedron that fits in the unit sphere.
  75. // Again, texture coordinates and normals are not generated.
  76. par_shapes_mesh* par_shapes_create_dodecahedron();
  77. // More platonic solids.
  78. par_shapes_mesh* par_shapes_create_octohedron();
  79. par_shapes_mesh* par_shapes_create_tetrahedron();
  80. par_shapes_mesh* par_shapes_create_cube();
  81. // Generate an orientable disk shape in 3-space. Does not include normals or
  82. // texture coordinates.
  83. par_shapes_mesh* par_shapes_create_disk(float radius, int slices,
  84. float const* center, float const* normal);
  85. // Create an empty shape. Useful for building scenes with merge_and_free.
  86. par_shapes_mesh* par_shapes_create_empty();
  87. // Generate a rock shape that sits on the Y=0 plane, and sinks into it a bit.
  88. // This includes smooth normals but no texture coordinates. Each subdivision
  89. // level scales the number of triangles by four, so use a very low number.
  90. par_shapes_mesh* par_shapes_create_rock(int seed, int nsubdivisions);
  91. // Create trees or vegetation by executing a recursive turtle graphics program.
  92. // The program is a list of command-argument pairs. See the unit test for
  93. // an example. Texture coordinates and normals are not generated.
  94. par_shapes_mesh* par_shapes_create_lsystem(char const* program, int slices,
  95. int maxdepth);
  96. // Queries ---------------------------------------------------------------------
  97. // Dump out a text file conforming to the venerable OBJ format.
  98. void par_shapes_export(par_shapes_mesh const*, char const* objfile);
  99. // Take a pointer to 6 floats and set them to min xyz, max xyz.
  100. void par_shapes_compute_aabb(par_shapes_mesh const* mesh, float* aabb);
  101. // Make a deep copy of a mesh. To make a brand new copy, pass null to "target".
  102. // To avoid memory churn, pass an existing mesh to "target".
  103. par_shapes_mesh* par_shapes_clone(par_shapes_mesh const* mesh,
  104. par_shapes_mesh* target);
  105. // Transformations -------------------------------------------------------------
  106. void par_shapes_merge(par_shapes_mesh* dst, par_shapes_mesh const* src);
  107. void par_shapes_translate(par_shapes_mesh*, float x, float y, float z);
  108. void par_shapes_rotate(par_shapes_mesh*, float radians, float const* axis);
  109. void par_shapes_scale(par_shapes_mesh*, float x, float y, float z);
  110. void par_shapes_merge_and_free(par_shapes_mesh* dst, par_shapes_mesh* src);
  111. // Reverse the winding of a run of faces. Useful when drawing the inside of
  112. // a Cornell Box. Pass 0 for nfaces to reverse every face in the mesh.
  113. void par_shapes_invert(par_shapes_mesh*, int startface, int nfaces);
  114. // Remove all triangles whose area is less than minarea.
  115. void par_shapes_remove_degenerate(par_shapes_mesh*, float minarea);
  116. // Dereference the entire index buffer and replace the point list.
  117. // This creates an inefficient structure, but is useful for drawing facets.
  118. // If create_indices is true, a trivial "0 1 2 3..." index buffer is generated.
  119. void par_shapes_unweld(par_shapes_mesh* mesh, bool create_indices);
  120. // Merge colocated verts, build a new index buffer, and return the
  121. // optimized mesh. Epsilon is the maximum distance to consider when
  122. // welding vertices. The mapping argument can be null, or a pointer to
  123. // npoints integers, which gets filled with the mapping from old vertex
  124. // indices to new indices.
  125. par_shapes_mesh* par_shapes_weld(par_shapes_mesh const*, float epsilon,
  126. PAR_SHAPES_T* mapping);
  127. // Compute smooth normals by averaging adjacent facet normals.
  128. void par_shapes_compute_normals(par_shapes_mesh* m);
  129. #ifndef PAR_PI
  130. #define PAR_PI (3.14159265359)
  131. #define PAR_MIN(a, b) (a > b ? b : a)
  132. #define PAR_MAX(a, b) (a > b ? a : b)
  133. #define PAR_CLAMP(v, lo, hi) PAR_MAX(lo, PAR_MIN(hi, v))
  134. #define PAR_SWAP(T, A, B) { T tmp = B; B = A; A = tmp; }
  135. #define PAR_SQR(a) ((a) * (a))
  136. #endif
  137. #ifndef PAR_MALLOC
  138. #define PAR_MALLOC(T, N) ((T*) malloc(N * sizeof(T)))
  139. #define PAR_CALLOC(T, N) ((T*) calloc(N * sizeof(T), 1))
  140. #define PAR_REALLOC(T, BUF, N) ((T*) realloc(BUF, sizeof(T) * N))
  141. #define PAR_FREE(BUF) free(BUF)
  142. #endif
  143. #ifdef __cplusplus
  144. }
  145. #endif
  146. #endif // PAR_SHAPES_H
  147. // -----------------------------------------------------------------------------
  148. // END PUBLIC API
  149. // -----------------------------------------------------------------------------
  150. #ifdef PAR_SHAPES_IMPLEMENTATION
  151. #include <stdlib.h>
  152. #include <stdio.h>
  153. #include <assert.h>
  154. #include <float.h>
  155. #include <string.h>
  156. #include <math.h>
  157. #include <errno.h>
  158. static void par_shapes__sphere(float const* uv, float* xyz, void*);
  159. static void par_shapes__hemisphere(float const* uv, float* xyz, void*);
  160. static void par_shapes__plane(float const* uv, float* xyz, void*);
  161. static void par_shapes__klein(float const* uv, float* xyz, void*);
  162. static void par_shapes__cylinder(float const* uv, float* xyz, void*);
  163. static void par_shapes__torus(float const* uv, float* xyz, void*);
  164. static void par_shapes__trefoil(float const* uv, float* xyz, void*);
  165. struct osn_context;
  166. static int par__simplex_noise(int64_t seed, struct osn_context** ctx);
  167. static void par__simplex_noise_free(struct osn_context* ctx);
  168. static double par__simplex_noise2(struct osn_context* ctx, double x, double y);
  169. static void par_shapes__copy3(float* result, float const* a)
  170. {
  171. result[0] = a[0];
  172. result[1] = a[1];
  173. result[2] = a[2];
  174. }
  175. static float par_shapes__dot3(float const* a, float const* b)
  176. {
  177. return b[0] * a[0] + b[1] * a[1] + b[2] * a[2];
  178. }
  179. static void par_shapes__transform3(float* p, float const* x, float const* y,
  180. float const* z)
  181. {
  182. float px = par_shapes__dot3(p, x);
  183. float py = par_shapes__dot3(p, y);
  184. float pz = par_shapes__dot3(p, z);
  185. p[0] = px;
  186. p[1] = py;
  187. p[2] = pz;
  188. }
  189. static void par_shapes__cross3(float* result, float const* a, float const* b)
  190. {
  191. float x = (a[1] * b[2]) - (a[2] * b[1]);
  192. float y = (a[2] * b[0]) - (a[0] * b[2]);
  193. float z = (a[0] * b[1]) - (a[1] * b[0]);
  194. result[0] = x;
  195. result[1] = y;
  196. result[2] = z;
  197. }
  198. static void par_shapes__mix3(float* d, float const* a, float const* b, float t)
  199. {
  200. float x = b[0] * t + a[0] * (1 - t);
  201. float y = b[1] * t + a[1] * (1 - t);
  202. float z = b[2] * t + a[2] * (1 - t);
  203. d[0] = x;
  204. d[1] = y;
  205. d[2] = z;
  206. }
  207. static void par_shapes__scale3(float* result, float a)
  208. {
  209. result[0] *= a;
  210. result[1] *= a;
  211. result[2] *= a;
  212. }
  213. static void par_shapes__normalize3(float* v)
  214. {
  215. float lsqr = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
  216. if (lsqr > 0) {
  217. par_shapes__scale3(v, 1.0f / lsqr);
  218. }
  219. }
  220. static void par_shapes__subtract3(float* result, float const* a)
  221. {
  222. result[0] -= a[0];
  223. result[1] -= a[1];
  224. result[2] -= a[2];
  225. }
  226. static void par_shapes__add3(float* result, float const* a)
  227. {
  228. result[0] += a[0];
  229. result[1] += a[1];
  230. result[2] += a[2];
  231. }
  232. static float par_shapes__sqrdist3(float const* a, float const* b)
  233. {
  234. float dx = a[0] - b[0];
  235. float dy = a[1] - b[1];
  236. float dz = a[2] - b[2];
  237. return dx * dx + dy * dy + dz * dz;
  238. }
  239. static void par_shapes__compute_welded_normals(par_shapes_mesh* m)
  240. {
  241. m->normals = PAR_MALLOC(float, m->npoints * 3);
  242. PAR_SHAPES_T* weldmap = PAR_MALLOC(PAR_SHAPES_T, m->npoints);
  243. par_shapes_mesh* welded = par_shapes_weld(m, 0.01, weldmap);
  244. par_shapes_compute_normals(welded);
  245. float* pdst = m->normals;
  246. for (int i = 0; i < m->npoints; i++, pdst += 3) {
  247. int d = weldmap[i];
  248. float const* pnormal = welded->normals + d * 3;
  249. pdst[0] = pnormal[0];
  250. pdst[1] = pnormal[1];
  251. pdst[2] = pnormal[2];
  252. }
  253. PAR_FREE(weldmap);
  254. par_shapes_free_mesh(welded);
  255. }
  256. par_shapes_mesh* par_shapes_create_cylinder(int slices, int stacks)
  257. {
  258. if (slices < 3 || stacks < 1) {
  259. return 0;
  260. }
  261. return par_shapes_create_parametric(par_shapes__cylinder, slices,
  262. stacks, 0);
  263. }
  264. par_shapes_mesh* par_shapes_create_parametric_sphere(int slices, int stacks)
  265. {
  266. if (slices < 3 || stacks < 3) {
  267. return 0;
  268. }
  269. par_shapes_mesh* m = par_shapes_create_parametric(par_shapes__sphere,
  270. slices, stacks, 0);
  271. par_shapes_remove_degenerate(m, 0.0001);
  272. return m;
  273. }
  274. par_shapes_mesh* par_shapes_create_hemisphere(int slices, int stacks)
  275. {
  276. if (slices < 3 || stacks < 3) {
  277. return 0;
  278. }
  279. par_shapes_mesh* m = par_shapes_create_parametric(par_shapes__hemisphere,
  280. slices, stacks, 0);
  281. par_shapes_remove_degenerate(m, 0.0001);
  282. return m;
  283. }
  284. par_shapes_mesh* par_shapes_create_torus(int slices, int stacks, float radius)
  285. {
  286. if (slices < 3 || stacks < 3) {
  287. return 0;
  288. }
  289. assert(radius <= 1.0 && "Use smaller radius to avoid self-intersection.");
  290. assert(radius >= 0.1 && "Use larger radius to avoid self-intersection.");
  291. void* userdata = (void*) &radius;
  292. return par_shapes_create_parametric(par_shapes__torus, slices,
  293. stacks, userdata);
  294. }
  295. par_shapes_mesh* par_shapes_create_klein_bottle(int slices, int stacks)
  296. {
  297. if (slices < 3 || stacks < 3) {
  298. return 0;
  299. }
  300. par_shapes_mesh* mesh = par_shapes_create_parametric(
  301. par_shapes__klein, slices, stacks, 0);
  302. int face = 0;
  303. for (int stack = 0; stack < stacks; stack++) {
  304. for (int slice = 0; slice < slices; slice++, face += 2) {
  305. if (stack < 27 * stacks / 32) {
  306. par_shapes_invert(mesh, face, 2);
  307. }
  308. }
  309. }
  310. par_shapes__compute_welded_normals(mesh);
  311. return mesh;
  312. }
  313. par_shapes_mesh* par_shapes_create_trefoil_knot(int slices, int stacks,
  314. float radius)
  315. {
  316. if (slices < 3 || stacks < 3) {
  317. return 0;
  318. }
  319. assert(radius <= 3.0 && "Use smaller radius to avoid self-intersection.");
  320. assert(radius >= 0.5 && "Use larger radius to avoid self-intersection.");
  321. void* userdata = (void*) &radius;
  322. return par_shapes_create_parametric(par_shapes__trefoil, slices,
  323. stacks, userdata);
  324. }
  325. par_shapes_mesh* par_shapes_create_plane(int slices, int stacks)
  326. {
  327. if (slices < 1 || stacks < 1) {
  328. return 0;
  329. }
  330. return par_shapes_create_parametric(par_shapes__plane, slices,
  331. stacks, 0);
  332. }
  333. par_shapes_mesh* par_shapes_create_parametric(par_shapes_fn fn,
  334. int slices, int stacks, void* userdata)
  335. {
  336. par_shapes_mesh* mesh = PAR_CALLOC(par_shapes_mesh, 1);
  337. // Generate verts.
  338. mesh->npoints = (slices + 1) * (stacks + 1);
  339. mesh->points = PAR_CALLOC(float, 3 * mesh->npoints);
  340. float uv[2];
  341. float xyz[3];
  342. float* points = mesh->points;
  343. for (int stack = 0; stack < stacks + 1; stack++) {
  344. uv[0] = (float) stack / stacks;
  345. for (int slice = 0; slice < slices + 1; slice++) {
  346. uv[1] = (float) slice / slices;
  347. fn(uv, xyz, userdata);
  348. *points++ = xyz[0];
  349. *points++ = xyz[1];
  350. *points++ = xyz[2];
  351. }
  352. }
  353. // Generate texture coordinates.
  354. mesh->tcoords = PAR_CALLOC(float, 2 * mesh->npoints);
  355. float* uvs = mesh->tcoords;
  356. for (int stack = 0; stack < stacks + 1; stack++) {
  357. uv[0] = (float) stack / stacks;
  358. for (int slice = 0; slice < slices + 1; slice++) {
  359. uv[1] = (float) slice / slices;
  360. *uvs++ = uv[0];
  361. *uvs++ = uv[1];
  362. }
  363. }
  364. // Generate faces.
  365. mesh->ntriangles = 2 * slices * stacks;
  366. mesh->triangles = PAR_CALLOC(PAR_SHAPES_T, 3 * mesh->ntriangles);
  367. int v = 0;
  368. PAR_SHAPES_T* face = mesh->triangles;
  369. for (int stack = 0; stack < stacks; stack++) {
  370. for (int slice = 0; slice < slices; slice++) {
  371. int next = slice + 1;
  372. *face++ = v + slice + slices + 1;
  373. *face++ = v + next;
  374. *face++ = v + slice;
  375. *face++ = v + slice + slices + 1;
  376. *face++ = v + next + slices + 1;
  377. *face++ = v + next;
  378. }
  379. v += slices + 1;
  380. }
  381. par_shapes__compute_welded_normals(mesh);
  382. return mesh;
  383. }
  384. void par_shapes_free_mesh(par_shapes_mesh* mesh)
  385. {
  386. PAR_FREE(mesh->points);
  387. PAR_FREE(mesh->triangles);
  388. PAR_FREE(mesh->normals);
  389. PAR_FREE(mesh->tcoords);
  390. PAR_FREE(mesh);
  391. }
  392. void par_shapes_export(par_shapes_mesh const* mesh, char const* filename)
  393. {
  394. FILE* objfile = fopen(filename, "wt");
  395. float const* points = mesh->points;
  396. float const* tcoords = mesh->tcoords;
  397. float const* norms = mesh->normals;
  398. PAR_SHAPES_T const* indices = mesh->triangles;
  399. if (tcoords && norms) {
  400. for (int nvert = 0; nvert < mesh->npoints; nvert++) {
  401. fprintf(objfile, "v %f %f %f\n", points[0], points[1], points[2]);
  402. fprintf(objfile, "vt %f %f\n", tcoords[0], tcoords[1]);
  403. fprintf(objfile, "vn %f %f %f\n", norms[0], norms[1], norms[2]);
  404. points += 3;
  405. norms += 3;
  406. tcoords += 2;
  407. }
  408. for (int nface = 0; nface < mesh->ntriangles; nface++) {
  409. int a = 1 + *indices++;
  410. int b = 1 + *indices++;
  411. int c = 1 + *indices++;
  412. fprintf(objfile, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
  413. a, a, a, b, b, b, c, c, c);
  414. }
  415. } else if (norms) {
  416. for (int nvert = 0; nvert < mesh->npoints; nvert++) {
  417. fprintf(objfile, "v %f %f %f\n", points[0], points[1], points[2]);
  418. fprintf(objfile, "vn %f %f %f\n", norms[0], norms[1], norms[2]);
  419. points += 3;
  420. norms += 3;
  421. }
  422. for (int nface = 0; nface < mesh->ntriangles; nface++) {
  423. int a = 1 + *indices++;
  424. int b = 1 + *indices++;
  425. int c = 1 + *indices++;
  426. fprintf(objfile, "f %d//%d %d//%d %d//%d\n", a, a, b, b, c, c);
  427. }
  428. } else if (tcoords) {
  429. for (int nvert = 0; nvert < mesh->npoints; nvert++) {
  430. fprintf(objfile, "v %f %f %f\n", points[0], points[1], points[2]);
  431. fprintf(objfile, "vt %f %f\n", tcoords[0], tcoords[1]);
  432. points += 3;
  433. tcoords += 2;
  434. }
  435. for (int nface = 0; nface < mesh->ntriangles; nface++) {
  436. int a = 1 + *indices++;
  437. int b = 1 + *indices++;
  438. int c = 1 + *indices++;
  439. fprintf(objfile, "f %d/%d %d/%d %d/%d\n", a, a, b, b, c, c);
  440. }
  441. } else {
  442. for (int nvert = 0; nvert < mesh->npoints; nvert++) {
  443. fprintf(objfile, "v %f %f %f\n", points[0], points[1], points[2]);
  444. points += 3;
  445. }
  446. for (int nface = 0; nface < mesh->ntriangles; nface++) {
  447. int a = 1 + *indices++;
  448. int b = 1 + *indices++;
  449. int c = 1 + *indices++;
  450. fprintf(objfile, "f %d %d %d\n", a, b, c);
  451. }
  452. }
  453. fclose(objfile);
  454. }
  455. static void par_shapes__sphere(float const* uv, float* xyz, void* userdata)
  456. {
  457. float phi = uv[0] * PAR_PI;
  458. float theta = uv[1] * 2 * PAR_PI;
  459. xyz[0] = cosf(theta) * sinf(phi);
  460. xyz[1] = sinf(theta) * sinf(phi);
  461. xyz[2] = cosf(phi);
  462. }
  463. static void par_shapes__hemisphere(float const* uv, float* xyz, void* userdata)
  464. {
  465. float phi = uv[0] * PAR_PI;
  466. float theta = uv[1] * PAR_PI;
  467. xyz[0] = cosf(theta) * sinf(phi);
  468. xyz[1] = sinf(theta) * sinf(phi);
  469. xyz[2] = cosf(phi);
  470. }
  471. static void par_shapes__plane(float const* uv, float* xyz, void* userdata)
  472. {
  473. xyz[0] = uv[0];
  474. xyz[1] = uv[1];
  475. xyz[2] = 0;
  476. }
  477. static void par_shapes__klein(float const* uv, float* xyz, void* userdata)
  478. {
  479. float u = uv[0] * PAR_PI;
  480. float v = uv[1] * 2 * PAR_PI;
  481. u = u * 2;
  482. if (u < PAR_PI) {
  483. xyz[0] = 3 * cosf(u) * (1 + sinf(u)) + (2 * (1 - cosf(u) / 2)) *
  484. cosf(u) * cosf(v);
  485. xyz[2] = -8 * sinf(u) - 2 * (1 - cosf(u) / 2) * sinf(u) * cosf(v);
  486. } else {
  487. xyz[0] = 3 * cosf(u) * (1 + sinf(u)) + (2 * (1 - cosf(u) / 2)) *
  488. cosf(v + PAR_PI);
  489. xyz[2] = -8 * sinf(u);
  490. }
  491. xyz[1] = -2 * (1 - cosf(u) / 2) * sinf(v);
  492. }
  493. static void par_shapes__cylinder(float const* uv, float* xyz, void* userdata)
  494. {
  495. float theta = uv[1] * 2 * PAR_PI;
  496. xyz[0] = sinf(theta);
  497. xyz[1] = cosf(theta);
  498. xyz[2] = uv[0];
  499. }
  500. static void par_shapes__torus(float const* uv, float* xyz, void* userdata)
  501. {
  502. float major = 1;
  503. float minor = *((float*) userdata);
  504. float theta = uv[0] * 2 * PAR_PI;
  505. float phi = uv[1] * 2 * PAR_PI;
  506. float beta = major + minor * cosf(phi);
  507. xyz[0] = cosf(theta) * beta;
  508. xyz[1] = sinf(theta) * beta;
  509. xyz[2] = sinf(phi) * minor;
  510. }
  511. static void par_shapes__trefoil(float const* uv, float* xyz, void* userdata)
  512. {
  513. float minor = *((float*) userdata);
  514. const float a = 0.5f;
  515. const float b = 0.3f;
  516. const float c = 0.5f;
  517. const float d = minor * 0.1f;
  518. const float u = (1 - uv[0]) * 4 * PAR_PI;
  519. const float v = uv[1] * 2 * PAR_PI;
  520. const float r = a + b * cos(1.5f * u);
  521. const float x = r * cos(u);
  522. const float y = r * sin(u);
  523. const float z = c * sin(1.5f * u);
  524. float q[3];
  525. q[0] =
  526. -1.5f * b * sin(1.5f * u) * cos(u) - (a + b * cos(1.5f * u)) * sin(u);
  527. q[1] =
  528. -1.5f * b * sin(1.5f * u) * sin(u) + (a + b * cos(1.5f * u)) * cos(u);
  529. q[2] = 1.5f * c * cos(1.5f * u);
  530. par_shapes__normalize3(q);
  531. float qvn[3] = {q[1], -q[0], 0};
  532. par_shapes__normalize3(qvn);
  533. float ww[3];
  534. par_shapes__cross3(ww, q, qvn);
  535. xyz[0] = x + d * (qvn[0] * cos(v) + ww[0] * sin(v));
  536. xyz[1] = y + d * (qvn[1] * cos(v) + ww[1] * sin(v));
  537. xyz[2] = z + d * ww[2] * sin(v);
  538. }
  539. void par_shapes_merge(par_shapes_mesh* dst, par_shapes_mesh const* src)
  540. {
  541. PAR_SHAPES_T offset = dst->npoints;
  542. int npoints = dst->npoints + src->npoints;
  543. int vecsize = sizeof(float) * 3;
  544. dst->points = PAR_REALLOC(float, dst->points, 3 * npoints);
  545. memcpy(dst->points + 3 * dst->npoints, src->points, vecsize * src->npoints);
  546. dst->npoints = npoints;
  547. if (src->normals || dst->normals) {
  548. dst->normals = PAR_REALLOC(float, dst->normals, 3 * npoints);
  549. if (src->normals) {
  550. memcpy(dst->normals + 3 * offset, src->normals,
  551. vecsize * src->npoints);
  552. }
  553. }
  554. if (src->tcoords || dst->tcoords) {
  555. int uvsize = sizeof(float) * 2;
  556. dst->tcoords = PAR_REALLOC(float, dst->tcoords, 2 * npoints);
  557. if (src->tcoords) {
  558. memcpy(dst->tcoords + 2 * offset, src->tcoords,
  559. uvsize * src->npoints);
  560. }
  561. }
  562. int ntriangles = dst->ntriangles + src->ntriangles;
  563. dst->triangles = PAR_REALLOC(PAR_SHAPES_T, dst->triangles, 3 * ntriangles);
  564. PAR_SHAPES_T* ptriangles = dst->triangles + 3 * dst->ntriangles;
  565. PAR_SHAPES_T const* striangles = src->triangles;
  566. for (int i = 0; i < src->ntriangles; i++) {
  567. *ptriangles++ = offset + *striangles++;
  568. *ptriangles++ = offset + *striangles++;
  569. *ptriangles++ = offset + *striangles++;
  570. }
  571. dst->ntriangles = ntriangles;
  572. }
  573. par_shapes_mesh* par_shapes_create_disk(float radius, int slices,
  574. float const* center, float const* normal)
  575. {
  576. par_shapes_mesh* mesh = PAR_CALLOC(par_shapes_mesh, 1);
  577. mesh->npoints = slices + 1;
  578. mesh->points = PAR_MALLOC(float, 3 * mesh->npoints);
  579. float* points = mesh->points;
  580. *points++ = 0;
  581. *points++ = 0;
  582. *points++ = 0;
  583. for (int i = 0; i < slices; i++) {
  584. float theta = i * PAR_PI * 2 / slices;
  585. *points++ = radius * cos(theta);
  586. *points++ = radius * sin(theta);
  587. *points++ = 0;
  588. }
  589. float nnormal[3] = {normal[0], normal[1], normal[2]};
  590. par_shapes__normalize3(nnormal);
  591. mesh->normals = PAR_MALLOC(float, 3 * mesh->npoints);
  592. float* norms = mesh->normals;
  593. for (int i = 0; i < mesh->npoints; i++) {
  594. *norms++ = nnormal[0];
  595. *norms++ = nnormal[1];
  596. *norms++ = nnormal[2];
  597. }
  598. mesh->ntriangles = slices;
  599. mesh->triangles = PAR_MALLOC(PAR_SHAPES_T, 3 * mesh->ntriangles);
  600. PAR_SHAPES_T* triangles = mesh->triangles;
  601. for (int i = 0; i < slices; i++) {
  602. *triangles++ = 0;
  603. *triangles++ = 1 + i;
  604. *triangles++ = 1 + (i + 1) % slices;
  605. }
  606. float k[3] = {0, 0, -1};
  607. float axis[3];
  608. par_shapes__cross3(axis, nnormal, k);
  609. par_shapes__normalize3(axis);
  610. par_shapes_rotate(mesh, acos(nnormal[2]), axis);
  611. par_shapes_translate(mesh, center[0], center[1], center[2]);
  612. return mesh;
  613. }
  614. par_shapes_mesh* par_shapes_create_empty()
  615. {
  616. return PAR_CALLOC(par_shapes_mesh, 1);
  617. }
  618. void par_shapes_translate(par_shapes_mesh* m, float x, float y, float z)
  619. {
  620. float* points = m->points;
  621. for (int i = 0; i < m->npoints; i++) {
  622. *points++ += x;
  623. *points++ += y;
  624. *points++ += z;
  625. }
  626. }
  627. void par_shapes_rotate(par_shapes_mesh* mesh, float radians, float const* axis)
  628. {
  629. float s = sinf(radians);
  630. float c = cosf(radians);
  631. float x = axis[0];
  632. float y = axis[1];
  633. float z = axis[2];
  634. float xy = x * y;
  635. float yz = y * z;
  636. float zx = z * x;
  637. float oneMinusC = 1.0f - c;
  638. float col0[3] = {
  639. (((x * x) * oneMinusC) + c),
  640. ((xy * oneMinusC) + (z * s)), ((zx * oneMinusC) - (y * s))
  641. };
  642. float col1[3] = {
  643. ((xy * oneMinusC) - (z * s)),
  644. (((y * y) * oneMinusC) + c), ((yz * oneMinusC) + (x * s))
  645. };
  646. float col2[3] = {
  647. ((zx * oneMinusC) + (y * s)),
  648. ((yz * oneMinusC) - (x * s)), (((z * z) * oneMinusC) + c)
  649. };
  650. float* p = mesh->points;
  651. for (int i = 0; i < mesh->npoints; i++, p += 3) {
  652. float x = col0[0] * p[0] + col1[0] * p[1] + col2[0] * p[2];
  653. float y = col0[1] * p[0] + col1[1] * p[1] + col2[1] * p[2];
  654. float z = col0[2] * p[0] + col1[2] * p[1] + col2[2] * p[2];
  655. p[0] = x;
  656. p[1] = y;
  657. p[2] = z;
  658. }
  659. p = mesh->normals;
  660. if (p) {
  661. for (int i = 0; i < mesh->npoints; i++, p += 3) {
  662. float x = col0[0] * p[0] + col1[0] * p[1] + col2[0] * p[2];
  663. float y = col0[1] * p[0] + col1[1] * p[1] + col2[1] * p[2];
  664. float z = col0[2] * p[0] + col1[2] * p[1] + col2[2] * p[2];
  665. p[0] = x;
  666. p[1] = y;
  667. p[2] = z;
  668. }
  669. }
  670. }
  671. void par_shapes_scale(par_shapes_mesh* m, float x, float y, float z)
  672. {
  673. float* points = m->points;
  674. for (int i = 0; i < m->npoints; i++) {
  675. *points++ *= x;
  676. *points++ *= y;
  677. *points++ *= z;
  678. }
  679. }
  680. void par_shapes_merge_and_free(par_shapes_mesh* dst, par_shapes_mesh* src)
  681. {
  682. par_shapes_merge(dst, src);
  683. par_shapes_free_mesh(src);
  684. }
  685. void par_shapes_compute_aabb(par_shapes_mesh const* m, float* aabb)
  686. {
  687. float* points = m->points;
  688. aabb[0] = aabb[3] = points[0];
  689. aabb[1] = aabb[4] = points[1];
  690. aabb[2] = aabb[5] = points[2];
  691. points += 3;
  692. for (int i = 1; i < m->npoints; i++, points += 3) {
  693. aabb[0] = PAR_MIN(points[0], aabb[0]);
  694. aabb[1] = PAR_MIN(points[1], aabb[1]);
  695. aabb[2] = PAR_MIN(points[2], aabb[2]);
  696. aabb[3] = PAR_MAX(points[0], aabb[3]);
  697. aabb[4] = PAR_MAX(points[1], aabb[4]);
  698. aabb[5] = PAR_MAX(points[2], aabb[5]);
  699. }
  700. }
  701. void par_shapes_invert(par_shapes_mesh* m, int face, int nfaces)
  702. {
  703. nfaces = nfaces ? nfaces : m->ntriangles;
  704. PAR_SHAPES_T* tri = m->triangles + face * 3;
  705. for (int i = 0; i < nfaces; i++) {
  706. PAR_SWAP(PAR_SHAPES_T, tri[0], tri[2]);
  707. tri += 3;
  708. }
  709. }
  710. par_shapes_mesh* par_shapes_create_icosahedron()
  711. {
  712. static float verts[] = {
  713. 0.000, 0.000, 1.000,
  714. 0.894, 0.000, 0.447,
  715. 0.276, 0.851, 0.447,
  716. -0.724, 0.526, 0.447,
  717. -0.724, -0.526, 0.447,
  718. 0.276, -0.851, 0.447,
  719. 0.724, 0.526, -0.447,
  720. -0.276, 0.851, -0.447,
  721. -0.894, 0.000, -0.447,
  722. -0.276, -0.851, -0.447,
  723. 0.724, -0.526, -0.447,
  724. 0.000, 0.000, -1.000
  725. };
  726. static PAR_SHAPES_T faces[] = {
  727. 0,1,2,
  728. 0,2,3,
  729. 0,3,4,
  730. 0,4,5,
  731. 0,5,1,
  732. 7,6,11,
  733. 8,7,11,
  734. 9,8,11,
  735. 10,9,11,
  736. 6,10,11,
  737. 6,2,1,
  738. 7,3,2,
  739. 8,4,3,
  740. 9,5,4,
  741. 10,1,5,
  742. 6,7,2,
  743. 7,8,3,
  744. 8,9,4,
  745. 9,10,5,
  746. 10,6,1
  747. };
  748. par_shapes_mesh* mesh = PAR_CALLOC(par_shapes_mesh, 1);
  749. mesh->npoints = sizeof(verts) / sizeof(verts[0]) / 3;
  750. mesh->points = PAR_MALLOC(float, sizeof(verts) / 4);
  751. memcpy(mesh->points, verts, sizeof(verts));
  752. mesh->ntriangles = sizeof(faces) / sizeof(faces[0]) / 3;
  753. mesh->triangles = PAR_MALLOC(PAR_SHAPES_T, sizeof(faces) / 2);
  754. memcpy(mesh->triangles, faces, sizeof(faces));
  755. return mesh;
  756. }
  757. par_shapes_mesh* par_shapes_create_dodecahedron()
  758. {
  759. static float verts[20 * 3] = {
  760. 0.607, 0.000, 0.795,
  761. 0.188, 0.577, 0.795,
  762. -0.491, 0.357, 0.795,
  763. -0.491, -0.357, 0.795,
  764. 0.188, -0.577, 0.795,
  765. 0.982, 0.000, 0.188,
  766. 0.304, 0.934, 0.188,
  767. -0.795, 0.577, 0.188,
  768. -0.795, -0.577, 0.188,
  769. 0.304, -0.934, 0.188,
  770. 0.795, 0.577, -0.188,
  771. -0.304, 0.934, -0.188,
  772. -0.982, 0.000, -0.188,
  773. -0.304, -0.934, -0.188,
  774. 0.795, -0.577, -0.188,
  775. 0.491, 0.357, -0.795,
  776. -0.188, 0.577, -0.795,
  777. -0.607, 0.000, -0.795,
  778. -0.188, -0.577, -0.795,
  779. 0.491, -0.357, -0.795,
  780. };
  781. static PAR_SHAPES_T pentagons[12 * 5] = {
  782. 0,1,2,3,4,
  783. 5,10,6,1,0,
  784. 6,11,7,2,1,
  785. 7,12,8,3,2,
  786. 8,13,9,4,3,
  787. 9,14,5,0,4,
  788. 15,16,11,6,10,
  789. 16,17,12,7,11,
  790. 17,18,13,8,12,
  791. 18,19,14,9,13,
  792. 19,15,10,5,14,
  793. 19,18,17,16,15
  794. };
  795. int npentagons = sizeof(pentagons) / sizeof(pentagons[0]) / 5;
  796. par_shapes_mesh* mesh = PAR_CALLOC(par_shapes_mesh, 1);
  797. int ncorners = sizeof(verts) / sizeof(verts[0]) / 3;
  798. mesh->npoints = ncorners;
  799. mesh->points = PAR_MALLOC(float, mesh->npoints * 3);
  800. memcpy(mesh->points, verts, sizeof(verts));
  801. PAR_SHAPES_T const* pentagon = pentagons;
  802. mesh->ntriangles = npentagons * 3;
  803. mesh->triangles = PAR_MALLOC(PAR_SHAPES_T, mesh->ntriangles * 3);
  804. PAR_SHAPES_T* tris = mesh->triangles;
  805. for (int p = 0; p < npentagons; p++, pentagon += 5) {
  806. *tris++ = pentagon[0];
  807. *tris++ = pentagon[1];
  808. *tris++ = pentagon[2];
  809. *tris++ = pentagon[0];
  810. *tris++ = pentagon[2];
  811. *tris++ = pentagon[3];
  812. *tris++ = pentagon[0];
  813. *tris++ = pentagon[3];
  814. *tris++ = pentagon[4];
  815. }
  816. return mesh;
  817. }
  818. par_shapes_mesh* par_shapes_create_octohedron()
  819. {
  820. static float verts[6 * 3] = {
  821. 0.000, 0.000, 1.000,
  822. 1.000, 0.000, 0.000,
  823. 0.000, 1.000, 0.000,
  824. -1.000, 0.000, 0.000,
  825. 0.000, -1.000, 0.000,
  826. 0.000, 0.000, -1.000
  827. };
  828. static PAR_SHAPES_T triangles[8 * 3] = {
  829. 0,1,2,
  830. 0,2,3,
  831. 0,3,4,
  832. 0,4,1,
  833. 2,1,5,
  834. 3,2,5,
  835. 4,3,5,
  836. 1,4,5,
  837. };
  838. int ntris = sizeof(triangles) / sizeof(triangles[0]) / 3;
  839. par_shapes_mesh* mesh = PAR_CALLOC(par_shapes_mesh, 1);
  840. int ncorners = sizeof(verts) / sizeof(verts[0]) / 3;
  841. mesh->npoints = ncorners;
  842. mesh->points = PAR_MALLOC(float, mesh->npoints * 3);
  843. memcpy(mesh->points, verts, sizeof(verts));
  844. PAR_SHAPES_T const* triangle = triangles;
  845. mesh->ntriangles = ntris;
  846. mesh->triangles = PAR_MALLOC(PAR_SHAPES_T, mesh->ntriangles * 3);
  847. PAR_SHAPES_T* tris = mesh->triangles;
  848. for (int p = 0; p < ntris; p++) {
  849. *tris++ = *triangle++;
  850. *tris++ = *triangle++;
  851. *tris++ = *triangle++;
  852. }
  853. return mesh;
  854. }
  855. par_shapes_mesh* par_shapes_create_tetrahedron()
  856. {
  857. static float verts[4 * 3] = {
  858. 0.000, 1.333, 0,
  859. 0.943, 0, 0,
  860. -0.471, 0, 0.816,
  861. -0.471, 0, -0.816,
  862. };
  863. static PAR_SHAPES_T triangles[4 * 3] = {
  864. 2,1,0,
  865. 3,2,0,
  866. 1,3,0,
  867. 1,2,3,
  868. };
  869. int ntris = sizeof(triangles) / sizeof(triangles[0]) / 3;
  870. par_shapes_mesh* mesh = PAR_CALLOC(par_shapes_mesh, 1);
  871. int ncorners = sizeof(verts) / sizeof(verts[0]) / 3;
  872. mesh->npoints = ncorners;
  873. mesh->points = PAR_MALLOC(float, mesh->npoints * 3);
  874. memcpy(mesh->points, verts, sizeof(verts));
  875. PAR_SHAPES_T const* triangle = triangles;
  876. mesh->ntriangles = ntris;
  877. mesh->triangles = PAR_MALLOC(PAR_SHAPES_T, mesh->ntriangles * 3);
  878. PAR_SHAPES_T* tris = mesh->triangles;
  879. for (int p = 0; p < ntris; p++) {
  880. *tris++ = *triangle++;
  881. *tris++ = *triangle++;
  882. *tris++ = *triangle++;
  883. }
  884. return mesh;
  885. }
  886. par_shapes_mesh* par_shapes_create_cube()
  887. {
  888. static float verts[8 * 3] = {
  889. 0, 0, 0, // 0
  890. 0, 1, 0, // 1
  891. 1, 1, 0, // 2
  892. 1, 0, 0, // 3
  893. 0, 0, 1, // 4
  894. 0, 1, 1, // 5
  895. 1, 1, 1, // 6
  896. 1, 0, 1, // 7
  897. };
  898. static PAR_SHAPES_T quads[6 * 4] = {
  899. 7,6,5,4, // front
  900. 0,1,2,3, // back
  901. 6,7,3,2, // right
  902. 5,6,2,1, // top
  903. 4,5,1,0, // left
  904. 7,4,0,3, // bottom
  905. };
  906. int nquads = sizeof(quads) / sizeof(quads[0]) / 4;
  907. par_shapes_mesh* mesh = PAR_CALLOC(par_shapes_mesh, 1);
  908. int ncorners = sizeof(verts) / sizeof(verts[0]) / 3;
  909. mesh->npoints = ncorners;
  910. mesh->points = PAR_MALLOC(float, mesh->npoints * 3);
  911. memcpy(mesh->points, verts, sizeof(verts));
  912. PAR_SHAPES_T const* quad = quads;
  913. mesh->ntriangles = nquads * 2;
  914. mesh->triangles = PAR_MALLOC(PAR_SHAPES_T, mesh->ntriangles * 3);
  915. PAR_SHAPES_T* tris = mesh->triangles;
  916. for (int p = 0; p < nquads; p++, quad += 4) {
  917. *tris++ = quad[0];
  918. *tris++ = quad[1];
  919. *tris++ = quad[2];
  920. *tris++ = quad[2];
  921. *tris++ = quad[3];
  922. *tris++ = quad[0];
  923. }
  924. return mesh;
  925. }
  926. typedef struct {
  927. char* cmd;
  928. char* arg;
  929. } par_shapes__command;
  930. typedef struct {
  931. char const* name;
  932. int weight;
  933. int ncommands;
  934. par_shapes__command* commands;
  935. } par_shapes__rule;
  936. typedef struct {
  937. int pc;
  938. float position[3];
  939. float scale[3];
  940. par_shapes_mesh* orientation;
  941. par_shapes__rule* rule;
  942. } par_shapes__stackframe;
  943. static par_shapes__rule* par_shapes__pick_rule(const char* name,
  944. par_shapes__rule* rules, int nrules)
  945. {
  946. par_shapes__rule* rule = 0;
  947. int total = 0;
  948. for (int i = 0; i < nrules; i++) {
  949. rule = rules + i;
  950. if (!strcmp(rule->name, name)) {
  951. total += rule->weight;
  952. }
  953. }
  954. float r = (float) rand() / RAND_MAX;
  955. float t = 0;
  956. for (int i = 0; i < nrules; i++) {
  957. rule = rules + i;
  958. if (!strcmp(rule->name, name)) {
  959. t += (float) rule->weight / total;
  960. if (t >= r) {
  961. return rule;
  962. }
  963. }
  964. }
  965. return rule;
  966. }
  967. static par_shapes_mesh* par_shapes__create_turtle()
  968. {
  969. const float xaxis[] = {1, 0, 0};
  970. const float yaxis[] = {0, 1, 0};
  971. const float zaxis[] = {0, 0, 1};
  972. par_shapes_mesh* turtle = PAR_CALLOC(par_shapes_mesh, 1);
  973. turtle->npoints = 3;
  974. turtle->points = PAR_CALLOC(float, turtle->npoints * 3);
  975. par_shapes__copy3(turtle->points + 0, xaxis);
  976. par_shapes__copy3(turtle->points + 3, yaxis);
  977. par_shapes__copy3(turtle->points + 6, zaxis);
  978. return turtle;
  979. }
  980. static par_shapes_mesh* par_shapes__apply_turtle(par_shapes_mesh* mesh,
  981. par_shapes_mesh* turtle, float const* pos, float const* scale)
  982. {
  983. par_shapes_mesh* m = par_shapes_clone(mesh, 0);
  984. for (int p = 0; p < m->npoints; p++) {
  985. float* pt = m->points + p * 3;
  986. pt[0] *= scale[0];
  987. pt[1] *= scale[1];
  988. pt[2] *= scale[2];
  989. par_shapes__transform3(pt,
  990. turtle->points + 0, turtle->points + 3, turtle->points + 6);
  991. pt[0] += pos[0];
  992. pt[1] += pos[1];
  993. pt[2] += pos[2];
  994. }
  995. return m;
  996. }
  997. static void par_shapes__connect(par_shapes_mesh* scene,
  998. par_shapes_mesh* cylinder, int slices)
  999. {
  1000. int stacks = 1;
  1001. int npoints = (slices + 1) * (stacks + 1);
  1002. assert(scene->npoints >= npoints && "Cannot connect to empty scene.");
  1003. // Create the new point list.
  1004. npoints = scene->npoints + (slices + 1);
  1005. float* points = PAR_MALLOC(float, npoints * 3);
  1006. memcpy(points, scene->points, sizeof(float) * scene->npoints * 3);
  1007. float* newpts = points + scene->npoints * 3;
  1008. memcpy(newpts, cylinder->points + (slices + 1) * 3,
  1009. sizeof(float) * (slices + 1) * 3);
  1010. PAR_FREE(scene->points);
  1011. scene->points = points;
  1012. // Create the new triangle list.
  1013. int ntriangles = scene->ntriangles + 2 * slices * stacks;
  1014. PAR_SHAPES_T* triangles = PAR_MALLOC(PAR_SHAPES_T, ntriangles * 3);
  1015. memcpy(triangles, scene->triangles, 2 * scene->ntriangles * 3);
  1016. int v = scene->npoints - (slices + 1);
  1017. PAR_SHAPES_T* face = triangles + scene->ntriangles * 3;
  1018. for (int stack = 0; stack < stacks; stack++) {
  1019. for (int slice = 0; slice < slices; slice++) {
  1020. int next = slice + 1;
  1021. *face++ = v + slice + slices + 1;
  1022. *face++ = v + next;
  1023. *face++ = v + slice;
  1024. *face++ = v + slice + slices + 1;
  1025. *face++ = v + next + slices + 1;
  1026. *face++ = v + next;
  1027. }
  1028. v += slices + 1;
  1029. }
  1030. PAR_FREE(scene->triangles);
  1031. scene->triangles = triangles;
  1032. scene->npoints = npoints;
  1033. scene->ntriangles = ntriangles;
  1034. }
  1035. par_shapes_mesh* par_shapes_create_lsystem(char const* text, int slices,
  1036. int maxdepth)
  1037. {
  1038. char* program;
  1039. program = PAR_MALLOC(char, strlen(text) + 1);
  1040. // The first pass counts the number of rules and commands.
  1041. strcpy(program, text);
  1042. char *cmd = strtok(program, " ");
  1043. int nrules = 1;
  1044. int ncommands = 0;
  1045. while (cmd) {
  1046. char *arg = strtok(0, " ");
  1047. if (!arg) {
  1048. puts("lsystem error: unexpected end of program.");
  1049. break;
  1050. }
  1051. if (!strcmp(cmd, "rule")) {
  1052. nrules++;
  1053. } else {
  1054. ncommands++;
  1055. }
  1056. cmd = strtok(0, " ");
  1057. }
  1058. // Allocate space.
  1059. par_shapes__rule* rules = PAR_MALLOC(par_shapes__rule, nrules);
  1060. par_shapes__command* commands = PAR_MALLOC(par_shapes__command, ncommands);
  1061. // Initialize the entry rule.
  1062. par_shapes__rule* current_rule = &rules[0];
  1063. par_shapes__command* current_command = &commands[0];
  1064. current_rule->name = "entry";
  1065. current_rule->weight = 1;
  1066. current_rule->ncommands = 0;
  1067. current_rule->commands = current_command;
  1068. // The second pass fills in the structures.
  1069. strcpy(program, text);
  1070. cmd = strtok(program, " ");
  1071. while (cmd) {
  1072. char *arg = strtok(0, " ");
  1073. if (!strcmp(cmd, "rule")) {
  1074. current_rule++;
  1075. // Split the argument into a rule name and weight.
  1076. char* dot = strchr(arg, '.');
  1077. if (dot) {
  1078. current_rule->weight = atoi(dot + 1);
  1079. *dot = 0;
  1080. } else {
  1081. current_rule->weight = 1;
  1082. }
  1083. current_rule->name = arg;
  1084. current_rule->ncommands = 0;
  1085. current_rule->commands = current_command;
  1086. } else {
  1087. current_rule->ncommands++;
  1088. current_command->cmd = cmd;
  1089. current_command->arg = arg;
  1090. current_command++;
  1091. }
  1092. cmd = strtok(0, " ");
  1093. }
  1094. // For testing purposes, dump out the parsed program.
  1095. #ifdef TEST_PARSE
  1096. for (int i = 0; i < nrules; i++) {
  1097. par_shapes__rule rule = rules[i];
  1098. printf("rule %s.%d\n", rule.name, rule.weight);
  1099. for (int c = 0; c < rule.ncommands; c++) {
  1100. par_shapes__command cmd = rule.commands[c];
  1101. printf("\t%s %s\n", cmd.cmd, cmd.arg);
  1102. }
  1103. }
  1104. #endif
  1105. // Instantiate the aggregated shape and the template shapes.
  1106. par_shapes_mesh* scene = PAR_CALLOC(par_shapes_mesh, 1);
  1107. par_shapes_mesh* tube = par_shapes_create_cylinder(slices, 1);
  1108. par_shapes_mesh* turtle = par_shapes__create_turtle();
  1109. // We're not attempting to support texture coordinates and normals
  1110. // with L-systems, so remove them from the template shape.
  1111. PAR_FREE(tube->normals);
  1112. PAR_FREE(tube->tcoords);
  1113. tube->normals = 0;
  1114. tube->tcoords = 0;
  1115. const float xaxis[] = {1, 0, 0};
  1116. const float yaxis[] = {0, 1, 0};
  1117. const float zaxis[] = {0, 0, 1};
  1118. const float units[] = {1, 1, 1};
  1119. // Execute the L-system program until the stack size is 0.
  1120. par_shapes__stackframe* stack =
  1121. PAR_CALLOC(par_shapes__stackframe, maxdepth);
  1122. int stackptr = 0;
  1123. stack[0].orientation = turtle;
  1124. stack[0].rule = &rules[0];
  1125. par_shapes__copy3(stack[0].scale, units);
  1126. while (stackptr >= 0) {
  1127. par_shapes__stackframe* frame = &stack[stackptr];
  1128. par_shapes__rule* rule = frame->rule;
  1129. par_shapes_mesh* turtle = frame->orientation;
  1130. float* position = frame->position;
  1131. float* scale = frame->scale;
  1132. if (frame->pc >= rule->ncommands) {
  1133. par_shapes_free_mesh(turtle);
  1134. stackptr--;
  1135. continue;
  1136. }
  1137. par_shapes__command* cmd = rule->commands + (frame->pc++);
  1138. #ifdef DUMP_TRACE
  1139. printf("%5s %5s %5s:%d %03d\n", cmd->cmd, cmd->arg, rule->name,
  1140. frame->pc - 1, stackptr);
  1141. #endif
  1142. float value;
  1143. if (!strcmp(cmd->cmd, "shape")) {
  1144. par_shapes_mesh* m = par_shapes__apply_turtle(tube, turtle,
  1145. position, scale);
  1146. if (!strcmp(cmd->arg, "connect")) {
  1147. par_shapes__connect(scene, m, slices);
  1148. } else {
  1149. par_shapes_merge(scene, m);
  1150. }
  1151. par_shapes_free_mesh(m);
  1152. } else if (!strcmp(cmd->cmd, "call") && stackptr < maxdepth - 1) {
  1153. rule = par_shapes__pick_rule(cmd->arg, rules, nrules);
  1154. frame = &stack[++stackptr];
  1155. frame->rule = rule;
  1156. frame->orientation = par_shapes_clone(turtle, 0);
  1157. frame->pc = 0;
  1158. par_shapes__copy3(frame->scale, scale);
  1159. par_shapes__copy3(frame->position, position);
  1160. continue;
  1161. } else {
  1162. value = atof(cmd->arg);
  1163. if (!strcmp(cmd->cmd, "rx")) {
  1164. par_shapes_rotate(turtle, value * PAR_PI / 180.0, xaxis);
  1165. } else if (!strcmp(cmd->cmd, "ry")) {
  1166. par_shapes_rotate(turtle, value * PAR_PI / 180.0, yaxis);
  1167. } else if (!strcmp(cmd->cmd, "rz")) {
  1168. par_shapes_rotate(turtle, value * PAR_PI / 180.0, zaxis);
  1169. } else if (!strcmp(cmd->cmd, "tx")) {
  1170. float vec[3] = {value, 0, 0};
  1171. float t[3] = {
  1172. par_shapes__dot3(turtle->points + 0, vec),
  1173. par_shapes__dot3(turtle->points + 3, vec),
  1174. par_shapes__dot3(turtle->points + 6, vec)
  1175. };
  1176. par_shapes__add3(position, t);
  1177. } else if (!strcmp(cmd->cmd, "ty")) {
  1178. float vec[3] = {0, value, 0};
  1179. float t[3] = {
  1180. par_shapes__dot3(turtle->points + 0, vec),
  1181. par_shapes__dot3(turtle->points + 3, vec),
  1182. par_shapes__dot3(turtle->points + 6, vec)
  1183. };
  1184. par_shapes__add3(position, t);
  1185. } else if (!strcmp(cmd->cmd, "tz")) {
  1186. float vec[3] = {0, 0, value};
  1187. float t[3] = {
  1188. par_shapes__dot3(turtle->points + 0, vec),
  1189. par_shapes__dot3(turtle->points + 3, vec),
  1190. par_shapes__dot3(turtle->points + 6, vec)
  1191. };
  1192. par_shapes__add3(position, t);
  1193. } else if (!strcmp(cmd->cmd, "sx")) {
  1194. scale[0] *= value;
  1195. } else if (!strcmp(cmd->cmd, "sy")) {
  1196. scale[1] *= value;
  1197. } else if (!strcmp(cmd->cmd, "sz")) {
  1198. scale[2] *= value;
  1199. } else if (!strcmp(cmd->cmd, "sa")) {
  1200. scale[0] *= value;
  1201. scale[1] *= value;
  1202. scale[2] *= value;
  1203. }
  1204. }
  1205. }
  1206. PAR_FREE(stack);
  1207. PAR_FREE(program);
  1208. PAR_FREE(rules);
  1209. PAR_FREE(commands);
  1210. return scene;
  1211. }
  1212. void par_shapes_unweld(par_shapes_mesh* mesh, bool create_indices)
  1213. {
  1214. int npoints = mesh->ntriangles * 3;
  1215. float* points = PAR_MALLOC(float, 3 * npoints);
  1216. float* dst = points;
  1217. PAR_SHAPES_T const* index = mesh->triangles;
  1218. for (int i = 0; i < npoints; i++) {
  1219. float const* src = mesh->points + 3 * (*index++);
  1220. *dst++ = src[0];
  1221. *dst++ = src[1];
  1222. *dst++ = src[2];
  1223. }
  1224. PAR_FREE(mesh->points);
  1225. mesh->points = points;
  1226. mesh->npoints = npoints;
  1227. if (create_indices) {
  1228. PAR_SHAPES_T* tris = PAR_MALLOC(PAR_SHAPES_T, 3 * mesh->ntriangles);
  1229. PAR_SHAPES_T* index = tris;
  1230. for (int i = 0; i < mesh->ntriangles * 3; i++) {
  1231. *index++ = i;
  1232. }
  1233. PAR_FREE(mesh->triangles);
  1234. mesh->triangles = tris;
  1235. }
  1236. }
  1237. void par_shapes_compute_normals(par_shapes_mesh* m)
  1238. {
  1239. PAR_FREE(m->normals);
  1240. m->normals = PAR_CALLOC(float, m->npoints * 3);
  1241. PAR_SHAPES_T const* triangle = m->triangles;
  1242. float next[3], prev[3], cp[3];
  1243. for (int f = 0; f < m->ntriangles; f++, triangle += 3) {
  1244. float const* pa = m->points + 3 * triangle[0];
  1245. float const* pb = m->points + 3 * triangle[1];
  1246. float const* pc = m->points + 3 * triangle[2];
  1247. par_shapes__copy3(next, pb);
  1248. par_shapes__subtract3(next, pa);
  1249. par_shapes__copy3(prev, pc);
  1250. par_shapes__subtract3(prev, pa);
  1251. par_shapes__cross3(cp, next, prev);
  1252. par_shapes__add3(m->normals + 3 * triangle[0], cp);
  1253. par_shapes__copy3(next, pc);
  1254. par_shapes__subtract3(next, pb);
  1255. par_shapes__copy3(prev, pa);
  1256. par_shapes__subtract3(prev, pb);
  1257. par_shapes__cross3(cp, next, prev);
  1258. par_shapes__add3(m->normals + 3 * triangle[1], cp);
  1259. par_shapes__copy3(next, pa);
  1260. par_shapes__subtract3(next, pc);
  1261. par_shapes__copy3(prev, pb);
  1262. par_shapes__subtract3(prev, pc);
  1263. par_shapes__cross3(cp, next, prev);
  1264. par_shapes__add3(m->normals + 3 * triangle[2], cp);
  1265. }
  1266. float* normal = m->normals;
  1267. for (int p = 0; p < m->npoints; p++, normal += 3) {
  1268. par_shapes__normalize3(normal);
  1269. }
  1270. }
  1271. static void par_shapes__subdivide(par_shapes_mesh* mesh)
  1272. {
  1273. assert(mesh->npoints == mesh->ntriangles * 3 && "Must be unwelded.");
  1274. int ntriangles = mesh->ntriangles * 4;
  1275. int npoints = ntriangles * 3;
  1276. float* points = PAR_CALLOC(float, npoints * 3);
  1277. float* dpoint = points;
  1278. float const* spoint = mesh->points;
  1279. for (int t = 0; t < mesh->ntriangles; t++, spoint += 9, dpoint += 3) {
  1280. float const* a = spoint;
  1281. float const* b = spoint + 3;
  1282. float const* c = spoint + 6;
  1283. float const* p0 = dpoint;
  1284. float const* p1 = dpoint + 3;
  1285. float const* p2 = dpoint + 6;
  1286. par_shapes__mix3(dpoint, a, b, 0.5);
  1287. par_shapes__mix3(dpoint += 3, b, c, 0.5);
  1288. par_shapes__mix3(dpoint += 3, a, c, 0.5);
  1289. par_shapes__add3(dpoint += 3, a);
  1290. par_shapes__add3(dpoint += 3, p0);
  1291. par_shapes__add3(dpoint += 3, p2);
  1292. par_shapes__add3(dpoint += 3, p0);
  1293. par_shapes__add3(dpoint += 3, b);
  1294. par_shapes__add3(dpoint += 3, p1);
  1295. par_shapes__add3(dpoint += 3, p2);
  1296. par_shapes__add3(dpoint += 3, p1);
  1297. par_shapes__add3(dpoint += 3, c);
  1298. }
  1299. PAR_FREE(mesh->points);
  1300. mesh->points = points;
  1301. mesh->npoints = npoints;
  1302. mesh->ntriangles = ntriangles;
  1303. }
  1304. par_shapes_mesh* par_shapes_create_subdivided_sphere(int nsubd)
  1305. {
  1306. par_shapes_mesh* mesh = par_shapes_create_icosahedron();
  1307. par_shapes_unweld(mesh, false);
  1308. PAR_FREE(mesh->triangles);
  1309. mesh->triangles = 0;
  1310. while (nsubd--) {
  1311. par_shapes__subdivide(mesh);
  1312. }
  1313. for (int i = 0; i < mesh->npoints; i++) {
  1314. par_shapes__normalize3(mesh->points + i * 3);
  1315. }
  1316. mesh->triangles = PAR_MALLOC(PAR_SHAPES_T, 3 * mesh->ntriangles);
  1317. for (int i = 0; i < mesh->ntriangles * 3; i++) {
  1318. mesh->triangles[i] = i;
  1319. }
  1320. par_shapes_mesh* tmp = mesh;
  1321. mesh = par_shapes_weld(mesh, 0.01, 0);
  1322. par_shapes_free_mesh(tmp);
  1323. par_shapes_compute_normals(mesh);
  1324. return mesh;
  1325. }
  1326. par_shapes_mesh* par_shapes_create_rock(int seed, int subd)
  1327. {
  1328. par_shapes_mesh* mesh = par_shapes_create_subdivided_sphere(subd);
  1329. struct osn_context* ctx;
  1330. par__simplex_noise(seed, &ctx);
  1331. for (int p = 0; p < mesh->npoints; p++) {
  1332. float* pt = mesh->points + p * 3;
  1333. float a = 0.25, f = 1.0;
  1334. double n = a * par__simplex_noise2(ctx, f * pt[0], f * pt[2]);
  1335. a *= 0.5; f *= 2;
  1336. n += a * par__simplex_noise2(ctx, f * pt[0], f * pt[2]);
  1337. pt[0] *= 1 + 2 * n;
  1338. pt[1] *= 1 + n;
  1339. pt[2] *= 1 + 2 * n;
  1340. if (pt[1] < 0) {
  1341. pt[1] = -pow(-pt[1], 0.5) / 2;
  1342. }
  1343. }
  1344. par__simplex_noise_free(ctx);
  1345. par_shapes_compute_normals(mesh);
  1346. return mesh;
  1347. }
  1348. par_shapes_mesh* par_shapes_clone(par_shapes_mesh const* mesh,
  1349. par_shapes_mesh* clone)
  1350. {
  1351. if (!clone) {
  1352. clone = PAR_CALLOC(par_shapes_mesh, 1);
  1353. }
  1354. clone->npoints = mesh->npoints;
  1355. clone->points = PAR_REALLOC(float, clone->points, 3 * clone->npoints);
  1356. memcpy(clone->points, mesh->points, sizeof(float) * 3 * clone->npoints);
  1357. clone->ntriangles = mesh->ntriangles;
  1358. clone->triangles = PAR_REALLOC(PAR_SHAPES_T, clone->triangles, 3 *
  1359. clone->ntriangles);
  1360. memcpy(clone->triangles, mesh->triangles,
  1361. sizeof(PAR_SHAPES_T) * 3 * clone->ntriangles);
  1362. if (mesh->normals) {
  1363. clone->normals = PAR_REALLOC(float, clone->normals, 3 * clone->npoints);
  1364. memcpy(clone->normals, mesh->normals,
  1365. sizeof(float) * 3 * clone->npoints);
  1366. }
  1367. if (mesh->tcoords) {
  1368. clone->tcoords = PAR_REALLOC(float, clone->tcoords, 2 * clone->npoints);
  1369. memcpy(clone->tcoords, mesh->tcoords,
  1370. sizeof(float) * 2 * clone->npoints);
  1371. }
  1372. return clone;
  1373. }
  1374. static struct {
  1375. float const* points;
  1376. int gridsize;
  1377. } par_shapes__sort_context;
  1378. static int par_shapes__cmp1(const void *arg0, const void *arg1)
  1379. {
  1380. const int g = par_shapes__sort_context.gridsize;
  1381. // Convert arg0 into a flattened grid index.
  1382. PAR_SHAPES_T d0 = *(const PAR_SHAPES_T*) arg0;
  1383. float const* p0 = par_shapes__sort_context.points + d0 * 3;
  1384. int i0 = (int) p0[0];
  1385. int j0 = (int) p0[1];
  1386. int k0 = (int) p0[2];
  1387. int index0 = i0 + g * j0 + g * g * k0;
  1388. // Convert arg1 into a flattened grid index.
  1389. PAR_SHAPES_T d1 = *(const PAR_SHAPES_T*) arg1;
  1390. float const* p1 = par_shapes__sort_context.points + d1 * 3;
  1391. int i1 = (int) p1[0];
  1392. int j1 = (int) p1[1];
  1393. int k1 = (int) p1[2];
  1394. int index1 = i1 + g * j1 + g * g * k1;
  1395. // Return the ordering.
  1396. if (index0 < index1) return -1;
  1397. if (index0 > index1) return 1;
  1398. return 0;
  1399. }
  1400. static void par_shapes__sort_points(par_shapes_mesh* mesh, int gridsize,
  1401. PAR_SHAPES_T* sortmap)
  1402. {
  1403. // Run qsort over a list of consecutive integers that get deferenced
  1404. // within the comparator function; this creates a reorder mapping.
  1405. for (int i = 0; i < mesh->npoints; i++) {
  1406. sortmap[i] = i;
  1407. }
  1408. par_shapes__sort_context.gridsize = gridsize;
  1409. par_shapes__sort_context.points = mesh->points;
  1410. qsort(sortmap, mesh->npoints, sizeof(PAR_SHAPES_T), par_shapes__cmp1);
  1411. // Apply the reorder mapping to the XYZ coordinate data.
  1412. float* newpts = PAR_MALLOC(float, mesh->npoints * 3);
  1413. PAR_SHAPES_T* invmap = PAR_MALLOC(PAR_SHAPES_T, mesh->npoints);
  1414. float* dstpt = newpts;
  1415. for (int i = 0; i < mesh->npoints; i++) {
  1416. invmap[sortmap[i]] = i;
  1417. float const* srcpt = mesh->points + 3 * sortmap[i];
  1418. *dstpt++ = *srcpt++;
  1419. *dstpt++ = *srcpt++;
  1420. *dstpt++ = *srcpt++;
  1421. }
  1422. PAR_FREE(mesh->points);
  1423. mesh->points = newpts;
  1424. // Apply the inverse reorder mapping to the triangle indices.
  1425. PAR_SHAPES_T* newinds = PAR_MALLOC(PAR_SHAPES_T, mesh->ntriangles * 3);
  1426. PAR_SHAPES_T* dstind = newinds;
  1427. PAR_SHAPES_T const* srcind = mesh->triangles;
  1428. for (int i = 0; i < mesh->ntriangles * 3; i++) {
  1429. *dstind++ = invmap[*srcind++];
  1430. }
  1431. PAR_FREE(mesh->triangles);
  1432. mesh->triangles = newinds;
  1433. // Cleanup.
  1434. memcpy(sortmap, invmap, sizeof(PAR_SHAPES_T) * mesh->npoints);
  1435. PAR_FREE(invmap);
  1436. }
  1437. static void par_shapes__weld_points(par_shapes_mesh* mesh, int gridsize,
  1438. float epsilon, PAR_SHAPES_T* weldmap)
  1439. {
  1440. // Each bin contains a "pointer" (really an index) to its first point.
  1441. // We add 1 because 0 is reserved to mean that the bin is empty.
  1442. // Since the points are spatially sorted, there's no need to store
  1443. // a point count in each bin.
  1444. PAR_SHAPES_T* bins = PAR_CALLOC(PAR_SHAPES_T,
  1445. gridsize * gridsize * gridsize);
  1446. int prev_binindex = -1;
  1447. for (int p = 0; p < mesh->npoints; p++) {
  1448. float const* pt = mesh->points + p * 3;
  1449. int i = (int) pt[0];
  1450. int j = (int) pt[1];
  1451. int k = (int) pt[2];
  1452. int this_binindex = i + gridsize * j + gridsize * gridsize * k;
  1453. if (this_binindex != prev_binindex) {
  1454. bins[this_binindex] = 1 + p;
  1455. }
  1456. prev_binindex = this_binindex;
  1457. }
  1458. // Examine all bins that intersect the epsilon-sized cube centered at each
  1459. // point, and check for colocated points within those bins.
  1460. float const* pt = mesh->points;
  1461. int nremoved = 0;
  1462. for (int p = 0; p < mesh->npoints; p++, pt += 3) {
  1463. // Skip if this point has already been welded.
  1464. if (weldmap[p] != p) {
  1465. continue;
  1466. }
  1467. // Build a list of bins that intersect the epsilon-sized cube.
  1468. int nearby[8];
  1469. int nbins = 0;
  1470. int minp[3], maxp[3];
  1471. for (int c = 0; c < 3; c++) {
  1472. minp[c] = (int) (pt[c] - epsilon);
  1473. maxp[c] = (int) (pt[c] + epsilon);
  1474. }
  1475. for (int i = minp[0]; i <= maxp[0]; i++) {
  1476. for (int j = minp[1]; j <= maxp[1]; j++) {
  1477. for (int k = minp[2]; k <= maxp[2]; k++) {
  1478. int binindex = i + gridsize * j + gridsize * gridsize * k;
  1479. PAR_SHAPES_T binvalue = *(bins + binindex);
  1480. if (binvalue > 0) {
  1481. if (nbins == 8) {
  1482. printf("Epsilon value is too large.\n");
  1483. break;
  1484. }
  1485. nearby[nbins++] = binindex;
  1486. }
  1487. }
  1488. }
  1489. }
  1490. // Check for colocated points in each nearby bin.
  1491. for (int b = 0; b < nbins; b++) {
  1492. int binindex = nearby[b];
  1493. PAR_SHAPES_T binvalue = *(bins + binindex);
  1494. PAR_SHAPES_T nindex = binvalue - 1;
  1495. while (true) {
  1496. // If this isn't "self" and it's colocated, then weld it!
  1497. if (nindex != p && weldmap[nindex] == nindex) {
  1498. float const* thatpt = mesh->points + nindex * 3;
  1499. float dist2 = par_shapes__sqrdist3(thatpt, pt);
  1500. if (dist2 < epsilon) {
  1501. weldmap[nindex] = p;
  1502. nremoved++;
  1503. }
  1504. }
  1505. // Advance to the next point if possible.
  1506. if (++nindex >= mesh->npoints) {
  1507. break;
  1508. }
  1509. // If the next point is outside the bin, then we're done.
  1510. float const* nextpt = mesh->points + nindex * 3;
  1511. int i = (int) nextpt[0];
  1512. int j = (int) nextpt[1];
  1513. int k = (int) nextpt[2];
  1514. int nextbinindex = i + gridsize * j + gridsize * gridsize * k;
  1515. if (nextbinindex != binindex) {
  1516. break;
  1517. }
  1518. }
  1519. }
  1520. }
  1521. PAR_FREE(bins);
  1522. // Apply the weldmap to the vertices.
  1523. int npoints = mesh->npoints - nremoved;
  1524. float* newpts = PAR_MALLOC(float, 3 * npoints);
  1525. float* dst = newpts;
  1526. PAR_SHAPES_T* condensed_map = PAR_MALLOC(PAR_SHAPES_T, mesh->npoints);
  1527. PAR_SHAPES_T* cmap = condensed_map;
  1528. float const* src = mesh->points;
  1529. int ci = 0;
  1530. for (int p = 0; p < mesh->npoints; p++, src += 3) {
  1531. if (weldmap[p] == p) {
  1532. *dst++ = src[0];
  1533. *dst++ = src[1];
  1534. *dst++ = src[2];
  1535. *cmap++ = ci++;
  1536. } else {
  1537. *cmap++ = condensed_map[weldmap[p]];
  1538. }
  1539. }
  1540. assert(ci == npoints);
  1541. PAR_FREE(mesh->points);
  1542. memcpy(weldmap, condensed_map, mesh->npoints * sizeof(PAR_SHAPES_T));
  1543. PAR_FREE(condensed_map);
  1544. mesh->points = newpts;
  1545. mesh->npoints = npoints;
  1546. // Apply the weldmap to the triangle indices and skip the degenerates.
  1547. PAR_SHAPES_T const* tsrc = mesh->triangles;
  1548. PAR_SHAPES_T* tdst = mesh->triangles;
  1549. int ntriangles = 0;
  1550. for (int i = 0; i < mesh->ntriangles; i++, tsrc += 3) {
  1551. PAR_SHAPES_T a = weldmap[tsrc[0]];
  1552. PAR_SHAPES_T b = weldmap[tsrc[1]];
  1553. PAR_SHAPES_T c = weldmap[tsrc[2]];
  1554. if (a != b && a != c && b != c) {
  1555. *tdst++ = a;
  1556. *tdst++ = b;
  1557. *tdst++ = c;
  1558. ntriangles++;
  1559. }
  1560. }
  1561. mesh->ntriangles = ntriangles;
  1562. }
  1563. par_shapes_mesh* par_shapes_weld(par_shapes_mesh const* mesh, float epsilon,
  1564. PAR_SHAPES_T* weldmap)
  1565. {
  1566. par_shapes_mesh* clone = par_shapes_clone(mesh, 0);
  1567. float aabb[6];
  1568. int gridsize = 20;
  1569. float maxcell = gridsize - 1;
  1570. par_shapes_compute_aabb(clone, aabb);
  1571. float scale[3] = {
  1572. maxcell / (aabb[3] - aabb[0]),
  1573. maxcell / (aabb[4] - aabb[1]),
  1574. maxcell / (aabb[5] - aabb[2]),
  1575. };
  1576. par_shapes_translate(clone, -aabb[0], -aabb[1], -aabb[2]);
  1577. par_shapes_scale(clone, scale[0], scale[1], scale[2]);
  1578. PAR_SHAPES_T* sortmap = PAR_MALLOC(PAR_SHAPES_T, mesh->npoints);
  1579. par_shapes__sort_points(clone, gridsize, sortmap);
  1580. bool owner = false;
  1581. if (!weldmap) {
  1582. owner = true;
  1583. weldmap = PAR_MALLOC(PAR_SHAPES_T, mesh->npoints);
  1584. }
  1585. for (int i = 0; i < mesh->npoints; i++) {
  1586. weldmap[i] = i;
  1587. }
  1588. par_shapes__weld_points(clone, gridsize, epsilon, weldmap);
  1589. if (owner) {
  1590. PAR_FREE(weldmap);
  1591. } else {
  1592. PAR_SHAPES_T* newmap = PAR_MALLOC(PAR_SHAPES_T, mesh->npoints);
  1593. for (int i = 0; i < mesh->npoints; i++) {
  1594. newmap[i] = weldmap[sortmap[i]];
  1595. }
  1596. memcpy(weldmap, newmap, sizeof(PAR_SHAPES_T) * mesh->npoints);
  1597. PAR_FREE(newmap);
  1598. }
  1599. PAR_FREE(sortmap);
  1600. par_shapes_scale(clone, 1.0 / scale[0], 1.0 / scale[1], 1.0 / scale[2]);
  1601. par_shapes_translate(clone, aabb[0], aabb[1], aabb[2]);
  1602. return clone;
  1603. }
  1604. // -----------------------------------------------------------------------------
  1605. // BEGIN OPEN SIMPLEX NOISE
  1606. // -----------------------------------------------------------------------------
  1607. #define STRETCH_CONSTANT_2D (-0.211324865405187) // (1 / sqrt(2 + 1) - 1 ) / 2;
  1608. #define SQUISH_CONSTANT_2D (0.366025403784439) // (sqrt(2 + 1) -1) / 2;
  1609. #define STRETCH_CONSTANT_3D (-1.0 / 6.0) // (1 / sqrt(3 + 1) - 1) / 3;
  1610. #define SQUISH_CONSTANT_3D (1.0 / 3.0) // (sqrt(3+1)-1)/3;
  1611. #define STRETCH_CONSTANT_4D (-0.138196601125011) // (1 / sqrt(4 + 1) - 1) / 4;
  1612. #define SQUISH_CONSTANT_4D (0.309016994374947) // (sqrt(4 + 1) - 1) / 4;
  1613. #define NORM_CONSTANT_2D (47.0)
  1614. #define NORM_CONSTANT_3D (103.0)
  1615. #define NORM_CONSTANT_4D (30.0)
  1616. #define DEFAULT_SEED (0LL)
  1617. struct osn_context {
  1618. int16_t* perm;
  1619. int16_t* permGradIndex3D;
  1620. };
  1621. #define ARRAYSIZE(x) (sizeof((x)) / sizeof((x)[0]))
  1622. /*
  1623. * Gradients for 2D. They approximate the directions to the
  1624. * vertices of an octagon from the center.
  1625. */
  1626. static const int8_t gradients2D[] = {
  1627. 5, 2, 2, 5, -5, 2, -2, 5, 5, -2, 2, -5, -5, -2, -2, -5,
  1628. };
  1629. /*
  1630. * Gradients for 3D. They approximate the directions to the
  1631. * vertices of a rhombicuboctahedron from the center, skewed so
  1632. * that the triangular and square facets can be inscribed inside
  1633. * circles of the same radius.
  1634. */
  1635. static const signed char gradients3D[] = {
  1636. -11, 4, 4, -4, 11, 4, -4, 4, 11, 11, 4, 4, 4, 11, 4, 4, 4, 11, -11, -4, 4,
  1637. -4, -11, 4, -4, -4, 11, 11, -4, 4, 4, -11, 4, 4, -4, 11, -11, 4, -4, -4, 11,
  1638. -4, -4, 4, -11, 11, 4, -4, 4, 11, -4, 4, 4, -11, -11, -4, -4, -4, -11, -4,
  1639. -4, -4, -11, 11, -4, -4, 4, -11, -4, 4, -4, -11,
  1640. };
  1641. /*
  1642. * Gradients for 4D. They approximate the directions to the
  1643. * vertices of a disprismatotesseractihexadecachoron from the center,
  1644. * skewed so that the tetrahedral and cubic facets can be inscribed inside
  1645. * spheres of the same radius.
  1646. */
  1647. static const signed char gradients4D[] = {
  1648. 3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, -3, 1, 1, 1, -1, 3, 1, 1,
  1649. -1, 1, 3, 1, -1, 1, 1, 3, 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, 1, 1, -1, 1,
  1650. 3, -3, -1, 1, 1, -1, -3, 1, 1, -1, -1, 3, 1, -1, -1, 1, 3, 3, 1, -1, 1, 1,
  1651. 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, -3, 1, -1, 1, -1, 3, -1, 1, -1, 1, -3,
  1652. 1, -1, 1, -1, 3, 3, -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, 1, 1, -1, -1, 3, -3,
  1653. -1, -1, 1, -1, -3, -1, 1, -1, -1, -3, 1, -1, -1, -1, 3, 3, 1, 1, -1, 1, 3,
  1654. 1, -1, 1, 1, 3, -1, 1, 1, 1, -3, -3, 1, 1, -1, -1, 3, 1, -1, -1, 1, 3, -1,
  1655. -1, 1, 1, -3, 3, -1, 1, -1, 1, -3, 1, -1, 1, -1, 3, -1, 1, -1, 1, -3, -3,
  1656. -1, 1, -1, -1, -3, 1, -1, -1, -1, 3, -1, -1, -1, 1, -3, 3, 1, -1, -1, 1, 3,
  1657. -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, -3, 1, -1, -1, -1, 3, -1, -1, -1, 1, -3,
  1658. -1, -1, 1, -1, -3, 3, -1, -1, -1, 1, -3, -1, -1, 1, -1, -3, -1, 1, -1, -1,
  1659. -3, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3,
  1660. };
  1661. static double extrapolate2(
  1662. struct osn_context* ctx, int xsb, int ysb, double dx, double dy)
  1663. {
  1664. int16_t* perm = ctx->perm;
  1665. int index = perm[(perm[xsb & 0xFF] + ysb) & 0xFF] & 0x0E;
  1666. return gradients2D[index] * dx + gradients2D[index + 1] * dy;
  1667. }
  1668. static inline int fastFloor(double x)
  1669. {
  1670. int xi = (int) x;
  1671. return x < xi ? xi - 1 : xi;
  1672. }
  1673. static int allocate_perm(struct osn_context* ctx, int nperm, int ngrad)
  1674. {
  1675. PAR_FREE(ctx->perm);
  1676. PAR_FREE(ctx->permGradIndex3D);
  1677. ctx->perm = PAR_MALLOC(int16_t, nperm);
  1678. if (!ctx->perm) {
  1679. return -ENOMEM;
  1680. }
  1681. ctx->permGradIndex3D = PAR_MALLOC(int16_t, ngrad);
  1682. if (!ctx->permGradIndex3D) {
  1683. PAR_FREE(ctx->perm);
  1684. return -ENOMEM;
  1685. }
  1686. return 0;
  1687. }
  1688. static int par__simplex_noise(int64_t seed, struct osn_context** ctx)
  1689. {
  1690. int rc;
  1691. int16_t source[256];
  1692. int i;
  1693. int16_t* perm;
  1694. int16_t* permGradIndex3D;
  1695. *ctx = PAR_MALLOC(struct osn_context, 1);
  1696. if (!(*ctx)) {
  1697. return -ENOMEM;
  1698. }
  1699. (*ctx)->perm = NULL;
  1700. (*ctx)->permGradIndex3D = NULL;
  1701. rc = allocate_perm(*ctx, 256, 256);
  1702. if (rc) {
  1703. PAR_FREE(*ctx);
  1704. return rc;
  1705. }
  1706. perm = (*ctx)->perm;
  1707. permGradIndex3D = (*ctx)->permGradIndex3D;
  1708. for (i = 0; i < 256; i++) {
  1709. source[i] = (int16_t) i;
  1710. }
  1711. seed = seed * 6364136223846793005LL + 1442695040888963407LL;
  1712. seed = seed * 6364136223846793005LL + 1442695040888963407LL;
  1713. seed = seed * 6364136223846793005LL + 1442695040888963407LL;
  1714. for (i = 255; i >= 0; i--) {
  1715. seed = seed * 6364136223846793005LL + 1442695040888963407LL;
  1716. int r = (int) ((seed + 31) % (i + 1));
  1717. if (r < 0)
  1718. r += (i + 1);
  1719. perm[i] = source[r];
  1720. permGradIndex3D[i] =
  1721. (short) ((perm[i] % (ARRAYSIZE(gradients3D) / 3)) * 3);
  1722. source[r] = source[i];
  1723. }
  1724. return 0;
  1725. }
  1726. static void par__simplex_noise_free(struct osn_context* ctx)
  1727. {
  1728. if (!ctx)
  1729. return;
  1730. if (ctx->perm) {
  1731. PAR_FREE(ctx->perm);
  1732. ctx->perm = NULL;
  1733. }
  1734. if (ctx->permGradIndex3D) {
  1735. PAR_FREE(ctx->permGradIndex3D);
  1736. ctx->permGradIndex3D = NULL;
  1737. }
  1738. PAR_FREE(ctx);
  1739. }
  1740. static double par__simplex_noise2(struct osn_context* ctx, double x, double y)
  1741. {
  1742. // Place input coordinates onto grid.
  1743. double stretchOffset = (x + y) * STRETCH_CONSTANT_2D;
  1744. double xs = x + stretchOffset;
  1745. double ys = y + stretchOffset;
  1746. // Floor to get grid coordinates of rhombus (stretched square) super-cell
  1747. // origin.
  1748. int xsb = fastFloor(xs);
  1749. int ysb = fastFloor(ys);
  1750. // Skew out to get actual coordinates of rhombus origin. We'll need these
  1751. // later.
  1752. double squishOffset = (xsb + ysb) * SQUISH_CONSTANT_2D;
  1753. double xb = xsb + squishOffset;
  1754. double yb = ysb + squishOffset;
  1755. // Compute grid coordinates relative to rhombus origin.
  1756. double xins = xs - xsb;
  1757. double yins = ys - ysb;
  1758. // Sum those together to get a value that determines which region we're in.
  1759. double inSum = xins + yins;
  1760. // Positions relative to origin point.
  1761. double dx0 = x - xb;
  1762. double dy0 = y - yb;
  1763. // We'll be defining these inside the next block and using them afterwards.
  1764. double dx_ext, dy_ext;
  1765. int xsv_ext, ysv_ext;
  1766. double value = 0;
  1767. // Contribution (1,0)
  1768. double dx1 = dx0 - 1 - SQUISH_CONSTANT_2D;
  1769. double dy1 = dy0 - 0 - SQUISH_CONSTANT_2D;
  1770. double attn1 = 2 - dx1 * dx1 - dy1 * dy1;
  1771. if (attn1 > 0) {
  1772. attn1 *= attn1;
  1773. value += attn1 * attn1 * extrapolate2(ctx, xsb + 1, ysb + 0, dx1, dy1);
  1774. }
  1775. // Contribution (0,1)
  1776. double dx2 = dx0 - 0 - SQUISH_CONSTANT_2D;
  1777. double dy2 = dy0 - 1 - SQUISH_CONSTANT_2D;
  1778. double attn2 = 2 - dx2 * dx2 - dy2 * dy2;
  1779. if (attn2 > 0) {
  1780. attn2 *= attn2;
  1781. value += attn2 * attn2 * extrapolate2(ctx, xsb + 0, ysb + 1, dx2, dy2);
  1782. }
  1783. if (inSum <= 1) { // We're inside the triangle (2-Simplex) at (0,0)
  1784. double zins = 1 - inSum;
  1785. if (zins > xins || zins > yins) {
  1786. if (xins > yins) {
  1787. xsv_ext = xsb + 1;
  1788. ysv_ext = ysb - 1;
  1789. dx_ext = dx0 - 1;
  1790. dy_ext = dy0 + 1;
  1791. } else {
  1792. xsv_ext = xsb - 1;
  1793. ysv_ext = ysb + 1;
  1794. dx_ext = dx0 + 1;
  1795. dy_ext = dy0 - 1;
  1796. }
  1797. } else { //(1,0) and (0,1) are the closest two vertices.
  1798. xsv_ext = xsb + 1;
  1799. ysv_ext = ysb + 1;
  1800. dx_ext = dx0 - 1 - 2 * SQUISH_CONSTANT_2D;
  1801. dy_ext = dy0 - 1 - 2 * SQUISH_CONSTANT_2D;
  1802. }
  1803. } else { // We're inside the triangle (2-Simplex) at (1,1)
  1804. double zins = 2 - inSum;
  1805. if (zins < xins || zins < yins) {
  1806. if (xins > yins) {
  1807. xsv_ext = xsb + 2;
  1808. ysv_ext = ysb + 0;
  1809. dx_ext = dx0 - 2 - 2 * SQUISH_CONSTANT_2D;
  1810. dy_ext = dy0 + 0 - 2 * SQUISH_CONSTANT_2D;
  1811. } else {
  1812. xsv_ext = xsb + 0;
  1813. ysv_ext = ysb + 2;
  1814. dx_ext = dx0 + 0 - 2 * SQUISH_CONSTANT_2D;
  1815. dy_ext = dy0 - 2 - 2 * SQUISH_CONSTANT_2D;
  1816. }
  1817. } else { //(1,0) and (0,1) are the closest two vertices.
  1818. dx_ext = dx0;
  1819. dy_ext = dy0;
  1820. xsv_ext = xsb;
  1821. ysv_ext = ysb;
  1822. }
  1823. xsb += 1;
  1824. ysb += 1;
  1825. dx0 = dx0 - 1 - 2 * SQUISH_CONSTANT_2D;
  1826. dy0 = dy0 - 1 - 2 * SQUISH_CONSTANT_2D;
  1827. }
  1828. // Contribution (0,0) or (1,1)
  1829. double attn0 = 2 - dx0 * dx0 - dy0 * dy0;
  1830. if (attn0 > 0) {
  1831. attn0 *= attn0;
  1832. value += attn0 * attn0 * extrapolate2(ctx, xsb, ysb, dx0, dy0);
  1833. }
  1834. // Extra Vertex
  1835. double attn_ext = 2 - dx_ext * dx_ext - dy_ext * dy_ext;
  1836. if (attn_ext > 0) {
  1837. attn_ext *= attn_ext;
  1838. value += attn_ext * attn_ext *
  1839. extrapolate2(ctx, xsv_ext, ysv_ext, dx_ext, dy_ext);
  1840. }
  1841. return value / NORM_CONSTANT_2D;
  1842. }
  1843. void par_shapes_remove_degenerate(par_shapes_mesh* mesh, float mintriarea)
  1844. {
  1845. int ntriangles = 0;
  1846. PAR_SHAPES_T* triangles = PAR_MALLOC(PAR_SHAPES_T, mesh->ntriangles * 3);
  1847. PAR_SHAPES_T* dst = triangles;
  1848. PAR_SHAPES_T const* src = mesh->triangles;
  1849. float next[3], prev[3], cp[3];
  1850. float mincplen2 = (mintriarea * 2) * (mintriarea * 2);
  1851. for (int f = 0; f < mesh->ntriangles; f++, src += 3) {
  1852. float const* pa = mesh->points + 3 * src[0];
  1853. float const* pb = mesh->points + 3 * src[1];
  1854. float const* pc = mesh->points + 3 * src[2];
  1855. par_shapes__copy3(next, pb);
  1856. par_shapes__subtract3(next, pa);
  1857. par_shapes__copy3(prev, pc);
  1858. par_shapes__subtract3(prev, pa);
  1859. par_shapes__cross3(cp, next, prev);
  1860. float cplen2 = par_shapes__dot3(cp, cp);
  1861. if (cplen2 >= mincplen2) {
  1862. *dst++ = src[0];
  1863. *dst++ = src[1];
  1864. *dst++ = src[2];
  1865. ntriangles++;
  1866. }
  1867. }
  1868. mesh->ntriangles = ntriangles;
  1869. PAR_FREE(mesh->triangles);
  1870. mesh->triangles = triangles;
  1871. }
  1872. #endif // PAR_SHAPES_IMPLEMENTATION