ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/bsdfmesh.c
Revision: 2.1
Committed: Fri Oct 19 04:14:29 2012 UTC (11 years, 6 months ago) by greg
Content type: text/plain
Branch: MAIN
Log Message:
Broke pabopto2xml into pabopto2bsdf and bsdf2ttree

File Contents

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