polyadvent

A game engine from scratch in C
git clone git://jb55.com/polyadvent
Log | Files | Refs | README

procmesh.c (1723B)


      1 
      2 #include "quickhull.h"
      3 #include "geometry.h"
      4 #include "util.h"
      5 
      6 
      7 static void qh_mesh_to_geom(qh_mesh_t *qh, struct make_geometry *geom) {
      8     assert(!geom->vertices);
      9     assert(!geom->indices);
     10     float *new_normals = malloc(sizeof(float) * 3 * qh->nvertices);
     11 
     12     geom->vertices = (float*)qh->vertices;
     13     geom->normals = (float*)qh->normals;
     14     geom->indices = qh->indices;
     15     geom->num_verts = qh->nvertices;
     16     geom->num_indices = qh->nindices;
     17 
     18     for (u32 i = 0; i < qh->nnormals; i++) {
     19         int ndv = i * 9;
     20 
     21         qh_vertex_t *n = &qh->normals[i];
     22         for (int j = 0; j < 9; j++) {
     23             new_normals[ndv+j] = n->v[j%3];
     24         }
     25     }
     26 
     27     geom->normals = new_normals;
     28 }
     29 
     30 
     31 void proc_sphere(struct geometry *geom) {
     32     struct make_geometry mkgeom;
     33     init_make_geometry(&mkgeom);
     34 
     35     const int n = 50;
     36     qh_vertex_t *vertices = malloc(n*sizeof(qh_vertex_t));
     37     const float radius = 2.0;
     38     float *colors;
     39 
     40     for (int i = 0; i < n; ++i) {
     41         float a0 = (rand_0to1() * TAU);
     42         float a1 = (rand_0to1() * TAU);
     43         vertices[i].z = sin(a0) * radius;
     44         vertices[i].x = cos(a1) * cos(a0) * rand_0to1() * radius;
     45         vertices[i].y = sin(a1) * cos(a0) * rand_0to1() * radius;
     46 
     47     }
     48 
     49     qh_mesh_t mesh = qh_quickhull3d(vertices, n);
     50 
     51     assert(mesh.nvertices);
     52     colors = malloc(mesh.nvertices * 3 * sizeof(*colors));
     53     assert(colors);
     54     for (u32 i = 0; i < mesh.nvertices; i++) {
     55         for (int j = 0; j < 3; j++)
     56             colors[i*3+j] = 0.5;
     57     }
     58     mkgeom.colors = colors;
     59 
     60     qh_mesh_to_geom(&mesh, &mkgeom);
     61 
     62     make_buffer_geometry(&mkgeom, geom);
     63 
     64     free(vertices);
     65     free(colors);
     66     free(mkgeom.normals);
     67     qh_free_mesh(mesh);
     68 }
     69