ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/bsdfmesh.c
Revision: 2.2
Committed: Sat Oct 20 07:02:00 2012 UTC (11 years, 6 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.1: +113 -116 lines
Log Message:
Bug fixes and minor improvements

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.2 static const char RCSid[] = "$Id: bsdfmesh.c,v 2.1 2012/10/19 04:14:29 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * Create BSDF advection mesh from radial basis functions.
6     *
7     * G. Ward
8     */
9    
10     #ifndef _WIN32
11     #include <unistd.h>
12     #include <sys/wait.h>
13     #include <sys/mman.h>
14     #endif
15     #define _USE_MATH_DEFINES
16     #include <stdio.h>
17     #include <stdlib.h>
18     #include <string.h>
19     #include <math.h>
20     #include "bsdfrep.h"
21     /* number of processes to run */
22     int nprocs = 1;
23     /* number of children (-1 in child) */
24     static int nchild = 0;
25    
26 greg 2.2 /* Create a new migration holder (sharing memory for multiprocessing) */
27     static MIGRATION *
28     new_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
29     {
30     size_t memlen = sizeof(MIGRATION) +
31     sizeof(float)*(from_rbf->nrbf*to_rbf->nrbf - 1);
32     MIGRATION *newmig;
33     #ifdef _WIN32
34     if (nprocs > 1)
35     fprintf(stderr, "%s: warning - multiprocessing not supported\n",
36     progname);
37     nprocs = 1;
38     newmig = (MIGRATION *)malloc(memlen);
39     #else
40     if (nprocs <= 1) { /* single process? */
41     newmig = (MIGRATION *)malloc(memlen);
42     } else { /* else need to share memory */
43     newmig = (MIGRATION *)mmap(NULL, memlen, PROT_READ|PROT_WRITE,
44     MAP_ANON|MAP_SHARED, -1, 0);
45     if ((void *)newmig == MAP_FAILED)
46     newmig = NULL;
47     }
48     #endif
49     if (newmig == NULL) {
50     fprintf(stderr, "%s: cannot allocate new migration\n", progname);
51     exit(1);
52     }
53     newmig->rbfv[0] = from_rbf;
54     newmig->rbfv[1] = to_rbf;
55     /* insert in edge lists */
56     newmig->enxt[0] = from_rbf->ejl;
57     from_rbf->ejl = newmig;
58     newmig->enxt[1] = to_rbf->ejl;
59     to_rbf->ejl = newmig;
60     newmig->next = mig_list; /* push onto global list */
61     return(mig_list = newmig);
62     }
63    
64     #ifdef _WIN32
65     #define await_children(n) (void)(n)
66     #define run_subprocess() 0
67     #define end_subprocess() (void)0
68     #else
69    
70     /* Wait for the specified number of child processes to complete */
71     static void
72     await_children(int n)
73     {
74     int exit_status = 0;
75    
76     if (n > nchild)
77     n = nchild;
78     while (n-- > 0) {
79     int status;
80     if (wait(&status) < 0) {
81     fprintf(stderr, "%s: missing child(ren)!\n", progname);
82     nchild = 0;
83     break;
84     }
85     --nchild;
86     if (status) { /* something wrong */
87     if ((status = WEXITSTATUS(status)))
88     exit_status = status;
89     else
90     exit_status += !exit_status;
91     fprintf(stderr, "%s: subprocess died\n", progname);
92     n = nchild; /* wait for the rest */
93     }
94     }
95     if (exit_status)
96     exit(exit_status);
97     }
98    
99     /* Start child process if multiprocessing selected */
100     static pid_t
101     run_subprocess(void)
102     {
103     int status;
104     pid_t pid;
105    
106     if (nprocs <= 1) /* any children requested? */
107     return(0);
108     await_children(nchild + 1 - nprocs); /* free up child process */
109     if ((pid = fork())) {
110     if (pid < 0) {
111     fprintf(stderr, "%s: cannot fork subprocess\n",
112     progname);
113     exit(1);
114     }
115     ++nchild; /* subprocess started */
116     return(pid);
117     }
118     nchild = -1;
119     return(0); /* put child to work */
120     }
121    
122     /* If we are in subprocess, call exit */
123     #define end_subprocess() if (nchild < 0) _exit(0); else
124    
125     #endif /* ! _WIN32 */
126    
127 greg 2.1 /* Compute (and allocate) migration price matrix for optimization */
128     static float *
129     price_routes(const RBFNODE *from_rbf, const RBFNODE *to_rbf)
130     {
131     float *pmtx = (float *)malloc(sizeof(float) *
132     from_rbf->nrbf * to_rbf->nrbf);
133     FVECT *vto = (FVECT *)malloc(sizeof(FVECT) * to_rbf->nrbf);
134     int i, j;
135    
136     if ((pmtx == NULL) | (vto == NULL)) {
137     fprintf(stderr, "%s: Out of memory in migration_costs()\n",
138     progname);
139     exit(1);
140     }
141     for (j = to_rbf->nrbf; j--; ) /* save repetitive ops. */
142     ovec_from_pos(vto[j], to_rbf->rbfa[j].gx, to_rbf->rbfa[j].gy);
143    
144     for (i = from_rbf->nrbf; i--; ) {
145     const double from_ang = R2ANG(from_rbf->rbfa[i].crad);
146     FVECT vfrom;
147     ovec_from_pos(vfrom, from_rbf->rbfa[i].gx, from_rbf->rbfa[i].gy);
148     for (j = to_rbf->nrbf; j--; )
149     pmtx[i*to_rbf->nrbf + j] = acos(DOT(vfrom, vto[j])) +
150     fabs(R2ANG(to_rbf->rbfa[j].crad) - from_ang);
151     }
152     free(vto);
153     return(pmtx);
154     }
155    
156     /* Comparison routine needed for sorting price row */
157     static const float *price_arr;
158     static int
159     msrt_cmp(const void *p1, const void *p2)
160     {
161     float c1 = price_arr[*(const int *)p1];
162     float c2 = price_arr[*(const int *)p2];
163    
164     if (c1 > c2) return(1);
165     if (c1 < c2) return(-1);
166     return(0);
167     }
168    
169     /* Compute minimum (optimistic) cost for moving the given source material */
170     static double
171     min_cost(double amt2move, const double *avail, const float *price, int n)
172     {
173     static int *price_sort = NULL;
174     static int n_alloc = 0;
175     double total_cost = 0;
176     int i;
177    
178     if (amt2move <= FTINY) /* pre-emptive check */
179     return(0.);
180     if (n > n_alloc) { /* (re)allocate sort array */
181     if (n_alloc) free(price_sort);
182     price_sort = (int *)malloc(sizeof(int)*n);
183     if (price_sort == NULL) {
184     fprintf(stderr, "%s: Out of memory in min_cost()\n",
185     progname);
186     exit(1);
187     }
188     n_alloc = n;
189     }
190     for (i = n; i--; )
191     price_sort[i] = i;
192     price_arr = price;
193     qsort(price_sort, n, sizeof(int), &msrt_cmp);
194     /* move cheapest first */
195     for (i = 0; i < n && amt2move > FTINY; i++) {
196     int d = price_sort[i];
197     double amt = (amt2move < avail[d]) ? amt2move : avail[d];
198    
199     total_cost += amt * price[d];
200     amt2move -= amt;
201     }
202     return(total_cost);
203     }
204    
205     /* Take a step in migration by choosing optimal bucket to transfer */
206     static double
207     migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, const float *pmtx)
208     {
209     const double maxamt = .1;
210 greg 2.2 const double minamt = maxamt*5e-6;
211 greg 2.1 static double *src_cost = NULL;
212     static int n_alloc = 0;
213     struct {
214     int s, d; /* source and destination */
215     double price; /* price estimate per amount moved */
216     double amt; /* amount we can move */
217     } cur, best;
218     int i;
219    
220     if (mtx_nrows(mig) > n_alloc) { /* allocate cost array */
221     if (n_alloc)
222     free(src_cost);
223     src_cost = (double *)malloc(sizeof(double)*mtx_nrows(mig));
224     if (src_cost == NULL) {
225     fprintf(stderr, "%s: Out of memory in migration_step()\n",
226     progname);
227     exit(1);
228     }
229     n_alloc = mtx_nrows(mig);
230     }
231     for (i = mtx_nrows(mig); i--; ) /* starting costs for diff. */
232     src_cost[i] = min_cost(src_rem[i], dst_rem,
233     pmtx+i*mtx_ncols(mig), mtx_ncols(mig));
234    
235     /* find best source & dest. */
236     best.s = best.d = -1; best.price = FHUGE; best.amt = 0;
237     for (cur.s = mtx_nrows(mig); cur.s--; ) {
238     const float *price = pmtx + cur.s*mtx_ncols(mig);
239     double cost_others = 0;
240 greg 2.2 if (src_rem[cur.s] <= minamt)
241 greg 2.1 continue;
242     cur.d = -1; /* examine cheapest dest. */
243     for (i = mtx_ncols(mig); i--; )
244     if (dst_rem[i] > minamt &&
245     (cur.d < 0 || price[i] < price[cur.d]))
246     cur.d = i;
247     if (cur.d < 0)
248     return(.0);
249     if ((cur.price = price[cur.d]) >= best.price)
250     continue; /* no point checking further */
251     cur.amt = (src_rem[cur.s] < dst_rem[cur.d]) ?
252     src_rem[cur.s] : dst_rem[cur.d];
253     if (cur.amt > maxamt) cur.amt = maxamt;
254     dst_rem[cur.d] -= cur.amt; /* add up differential costs */
255     for (i = mtx_nrows(mig); i--; )
256     if (i != cur.s)
257     cost_others += min_cost(src_rem[i], dst_rem,
258     price, mtx_ncols(mig))
259     - src_cost[i];
260     dst_rem[cur.d] += cur.amt; /* undo trial move */
261     cur.price += cost_others/cur.amt; /* adjust effective price */
262     if (cur.price < best.price) /* are we better than best? */
263     best = cur;
264     }
265     if ((best.s < 0) | (best.d < 0))
266     return(.0);
267     /* make the actual move */
268 greg 2.2 mtx_coef(mig,best.s,best.d) += best.amt;
269 greg 2.1 src_rem[best.s] -= best.amt;
270     dst_rem[best.d] -= best.amt;
271     return(best.amt);
272     }
273    
274     #ifdef DEBUG
275     static char *
276     thetaphi(const FVECT v)
277     {
278     static char buf[128];
279     double theta, phi;
280    
281     theta = 180./M_PI*acos(v[2]);
282     phi = 180./M_PI*atan2(v[1],v[0]);
283     sprintf(buf, "(%.0f,%.0f)", theta, phi);
284    
285     return(buf);
286     }
287     #endif
288    
289     /* Compute and insert migration along directed edge (may fork child) */
290     static MIGRATION *
291     create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
292     {
293 greg 2.2 const double end_thresh = 5e-6;
294 greg 2.1 float *pmtx;
295     MIGRATION *newmig;
296     double *src_rem, *dst_rem;
297     double total_rem = 1., move_amt;
298     int i;
299     /* check if exists already */
300     for (newmig = from_rbf->ejl; newmig != NULL;
301     newmig = nextedge(from_rbf,newmig))
302     if (newmig->rbfv[1] == to_rbf)
303     return(NULL);
304     /* else allocate */
305     newmig = new_migration(from_rbf, to_rbf);
306     if (run_subprocess())
307     return(newmig); /* child continues */
308     pmtx = price_routes(from_rbf, to_rbf);
309     src_rem = (double *)malloc(sizeof(double)*from_rbf->nrbf);
310     dst_rem = (double *)malloc(sizeof(double)*to_rbf->nrbf);
311     if ((src_rem == NULL) | (dst_rem == NULL)) {
312     fprintf(stderr, "%s: Out of memory in create_migration()\n",
313     progname);
314     exit(1);
315     }
316     #ifdef DEBUG
317     fprintf(stderr, "Building path from (theta,phi) %s ",
318     thetaphi(from_rbf->invec));
319 greg 2.2 fprintf(stderr, "to %s with %d x %d matrix\n",
320     thetaphi(to_rbf->invec),
321     from_rbf->nrbf, to_rbf->nrbf);
322 greg 2.1 #endif
323     /* starting quantities */
324     memset(newmig->mtx, 0, sizeof(float)*from_rbf->nrbf*to_rbf->nrbf);
325     for (i = from_rbf->nrbf; i--; )
326     src_rem[i] = rbf_volume(&from_rbf->rbfa[i]) / from_rbf->vtotal;
327     for (i = to_rbf->nrbf; i--; )
328     dst_rem[i] = rbf_volume(&to_rbf->rbfa[i]) / to_rbf->vtotal;
329     do { /* move a bit at a time */
330     move_amt = migration_step(newmig, src_rem, dst_rem, pmtx);
331     total_rem -= move_amt;
332     #ifdef DEBUG
333     if (!nchild)
334 greg 2.2 fprintf(stderr, "\r%.9f remaining...", total_rem);
335 greg 2.1 #endif
336 greg 2.2 } while ((total_rem > end_thresh) & (move_amt > 0));
337 greg 2.1 #ifdef DEBUG
338 greg 2.2 if (!nchild) fputs("done.\n", stderr);
339 greg 2.1 else fprintf(stderr, "finished with %.9f remaining\n", total_rem);
340     #endif
341     for (i = from_rbf->nrbf; i--; ) { /* normalize final matrix */
342     float nf = rbf_volume(&from_rbf->rbfa[i]);
343     int j;
344     if (nf <= FTINY) continue;
345     nf = from_rbf->vtotal / nf;
346     for (j = to_rbf->nrbf; j--; )
347 greg 2.2 mtx_coef(newmig,i,j) *= nf;
348 greg 2.1 }
349     end_subprocess(); /* exit here if subprocess */
350     free(pmtx); /* free working arrays */
351     free(src_rem);
352     free(dst_rem);
353     return(newmig);
354     }
355    
356     /* Check if prospective vertex would create overlapping triangle */
357     static int
358     overlaps_tri(const RBFNODE *bv0, const RBFNODE *bv1, const RBFNODE *pv)
359     {
360     const MIGRATION *ej;
361     RBFNODE *vother[2];
362     int im_rev;
363     /* find shared edge in mesh */
364     for (ej = pv->ejl; ej != NULL; ej = nextedge(pv,ej)) {
365     const RBFNODE *tv = opp_rbf(pv,ej);
366     if (tv == bv0) {
367     im_rev = is_rev_tri(ej->rbfv[0]->invec,
368     ej->rbfv[1]->invec, bv1->invec);
369     break;
370     }
371     if (tv == bv1) {
372     im_rev = is_rev_tri(ej->rbfv[0]->invec,
373     ej->rbfv[1]->invec, bv0->invec);
374     break;
375     }
376     }
377     if (!get_triangles(vother, ej)) /* triangle on same side? */
378     return(0);
379     return(vother[im_rev] != NULL);
380     }
381    
382     /* Find context hull vertex to complete triangle (oriented call) */
383     static RBFNODE *
384     find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rbf1)
385     {
386     FVECT vmid, vejn, vp;
387     RBFNODE *rbf, *rbfbest = NULL;
388     double dprod, area2, bestarea2 = FHUGE, bestdprod = -.5;
389    
390     VSUB(vejn, rbf1->invec, rbf0->invec);
391     VADD(vmid, rbf0->invec, rbf1->invec);
392     if (normalize(vejn) == 0 || normalize(vmid) == 0)
393     return(NULL);
394     /* XXX exhaustive search */
395     /* Find triangle with minimum rotation from perpendicular */
396     for (rbf = dsf_list; rbf != NULL; rbf = rbf->next) {
397     if ((rbf == rbf0) | (rbf == rbf1))
398     continue;
399     tri_orient(vp, rbf0->invec, rbf1->invec, rbf->invec);
400     if (DOT(vp, vmid) <= FTINY)
401     continue; /* wrong orientation */
402     area2 = .25*DOT(vp,vp);
403     VSUB(vp, rbf->invec, rbf0->invec);
404     dprod = -DOT(vp, vejn);
405     VSUM(vp, vp, vejn, dprod); /* above guarantees non-zero */
406     dprod = DOT(vp, vmid) / VLEN(vp);
407     if (dprod <= bestdprod + FTINY*(1 - 2*(area2 < bestarea2)))
408     continue; /* found better already */
409     if (overlaps_tri(rbf0, rbf1, rbf))
410     continue; /* overlaps another triangle */
411     rbfbest = rbf;
412     bestdprod = dprod; /* new one to beat */
413     bestarea2 = area2;
414     }
415     return(rbfbest);
416     }
417    
418     /* Create new migration edge and grow mesh recursively around it */
419     static void
420     mesh_from_edge(MIGRATION *edge)
421     {
422     MIGRATION *ej0, *ej1;
423     RBFNODE *tvert[2];
424    
425     if (edge == NULL)
426     return;
427     /* triangle on either side? */
428     get_triangles(tvert, edge);
429     if (tvert[0] == NULL) { /* grow mesh on right */
430     tvert[0] = find_chull_vert(edge->rbfv[0], edge->rbfv[1]);
431     if (tvert[0] != NULL) {
432     if (tvert[0]->ord > edge->rbfv[0]->ord)
433     ej0 = create_migration(edge->rbfv[0], tvert[0]);
434     else
435     ej0 = create_migration(tvert[0], edge->rbfv[0]);
436     if (tvert[0]->ord > edge->rbfv[1]->ord)
437     ej1 = create_migration(edge->rbfv[1], tvert[0]);
438     else
439     ej1 = create_migration(tvert[0], edge->rbfv[1]);
440     mesh_from_edge(ej0);
441     mesh_from_edge(ej1);
442     }
443     } else if (tvert[1] == NULL) { /* grow mesh on left */
444     tvert[1] = find_chull_vert(edge->rbfv[1], edge->rbfv[0]);
445     if (tvert[1] != NULL) {
446     if (tvert[1]->ord > edge->rbfv[0]->ord)
447     ej0 = create_migration(edge->rbfv[0], tvert[1]);
448     else
449     ej0 = create_migration(tvert[1], edge->rbfv[0]);
450     if (tvert[1]->ord > edge->rbfv[1]->ord)
451     ej1 = create_migration(edge->rbfv[1], tvert[1]);
452     else
453     ej1 = create_migration(tvert[1], edge->rbfv[1]);
454     mesh_from_edge(ej0);
455     mesh_from_edge(ej1);
456     }
457     }
458     }
459    
460     /* Build our triangle mesh from recorded RBFs */
461     void
462     build_mesh(void)
463     {
464     double best2 = M_PI*M_PI;
465     RBFNODE *shrt_edj[2];
466     RBFNODE *rbf0, *rbf1;
467     /* check if isotropic */
468     if (single_plane_incident) {
469     for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)
470     if (rbf0->next != NULL)
471     create_migration(rbf0, rbf0->next);
472     await_children(nchild);
473     return;
474     }
475     shrt_edj[0] = shrt_edj[1] = NULL; /* start w/ shortest edge */
476     for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)
477     for (rbf1 = rbf0->next; rbf1 != NULL; rbf1 = rbf1->next) {
478     double dist2 = 2. - 2.*DOT(rbf0->invec,rbf1->invec);
479     if (dist2 < best2) {
480     shrt_edj[0] = rbf0;
481     shrt_edj[1] = rbf1;
482     best2 = dist2;
483     }
484     }
485     if (shrt_edj[0] == NULL) {
486     fprintf(stderr, "%s: Cannot find shortest edge\n", progname);
487     exit(1);
488     }
489     /* build mesh from this edge */
490     if (shrt_edj[0]->ord < shrt_edj[1]->ord)
491     mesh_from_edge(create_migration(shrt_edj[0], shrt_edj[1]));
492     else
493     mesh_from_edge(create_migration(shrt_edj[1], shrt_edj[0]));
494     /* complete migrations */
495     await_children(nchild);
496     }