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