ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/bsdfmesh.c
Revision: 2.3
Committed: Thu Nov 8 22:05:04 2012 UTC (11 years, 5 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.2: +62 -57 lines
Log Message:
Took sort out so it is done only once

File Contents

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