ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/pabopto2xml.c
Revision: 2.16
Committed: Sun Oct 14 22:31:20 2012 UTC (11 years, 7 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.15: +166 -49 lines
Log Message:
Added multi-processing option

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: pabopto2xml.c,v 2.15 2012/09/23 16:45:20 greg Exp $";
3 #endif
4 /*
5 * Convert PAB-Opto measurements to XML format using tensor tree representation
6 * Employs Bonneel et al. Earth Mover's Distance interpolant.
7 *
8 * G.Ward
9 */
10
11 #ifndef _WIN32
12 #include <unistd.h>
13 #include <sys/wait.h>
14 #include <sys/mman.h>
15 #endif
16 #define _USE_MATH_DEFINES
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <ctype.h>
21 #include <math.h>
22 #include "bsdf.h"
23
24 #define DEBUG 1
25
26 #ifndef GRIDRES
27 #define GRIDRES 200 /* grid resolution per side */
28 #endif
29
30 #define RSCA 2.7 /* radius scaling factor (empirical) */
31
32 /* convert to/from coded radians */
33 #define ANG2R(r) (int)((r)*((1<<16)/M_PI))
34 #define R2ANG(c) (((c)+.5)*(M_PI/(1<<16)))
35
36 typedef struct {
37 float vsum; /* DSF sum */
38 unsigned short nval; /* number of values in sum */
39 unsigned short crad; /* radius (coded angle) */
40 } GRIDVAL; /* grid value */
41
42 typedef struct {
43 float peak; /* lobe value at peak */
44 unsigned short crad; /* radius (coded angle) */
45 unsigned char gx, gy; /* grid position */
46 } RBFVAL; /* radial basis function value */
47
48 struct s_rbfnode; /* forward declaration of RBF struct */
49
50 typedef struct s_migration {
51 struct s_migration *next; /* next in global edge list */
52 struct s_rbfnode *rbfv[2]; /* from,to vertex */
53 struct s_migration *enxt[2]; /* next from,to sibling */
54 float mtx[1]; /* matrix (extends struct) */
55 } MIGRATION; /* migration link (winged edge structure) */
56
57 typedef struct s_rbfnode {
58 struct s_rbfnode *next; /* next in global RBF list */
59 MIGRATION *ejl; /* edge list for this vertex */
60 FVECT invec; /* incident vector direction */
61 double vtotal; /* volume for normalization */
62 int nrbf; /* number of RBFs */
63 RBFVAL rbfa[1]; /* RBF array (extends struct) */
64 } RBFNODE; /* RBF representation of DSF @ 1 incidence */
65
66 /* our loaded grid for this incident angle */
67 static double theta_in_deg, phi_in_deg;
68 static GRIDVAL dsf_grid[GRIDRES][GRIDRES];
69
70 /* all incident angles in-plane so far? */
71 static int single_plane_incident = -1;
72
73 /* input/output orientations */
74 static int input_orient = 0;
75 static int output_orient = 0;
76
77 /* processed incident DSF measurements */
78 static RBFNODE *dsf_list = NULL;
79
80 /* RBF-linking matrices (edges) */
81 static MIGRATION *mig_list = NULL;
82
83 /* migration edges drawn in raster fashion */
84 static MIGRATION *mig_grid[GRIDRES][GRIDRES];
85
86 #define mtx_nrows(m) ((m)->rbfv[0]->nrbf)
87 #define mtx_ncols(m) ((m)->rbfv[1]->nrbf)
88 #define mtx_ndx(m,i,j) ((i)*mtx_ncols(m) + (j))
89 #define is_src(rbf,m) ((rbf) == (m)->rbfv[0])
90 #define is_dest(rbf,m) ((rbf) == (m)->rbfv[1])
91 #define nextedge(rbf,m) (m)->enxt[is_dest(rbf,m)]
92 #define opp_rbf(rbf,m) (m)->rbfv[is_src(rbf,m)]
93
94 #define round(v) (int)((v) + .5 - ((v) < -.5))
95
96 char *progname;
97
98 #ifdef DEBUG /* percentage to cull (<0 to turn off) */
99 int pctcull = -1;
100 #else
101 int pctcull = 90;
102 #endif
103 /* number of processes to run */
104 int nprocs = 1;
105 /* number of children (-1 in child) */
106 int nchild = 0;
107
108 /* sampling order (set by data density) */
109 int samp_order = 0;
110
111 /* Compute volume associated with Gaussian lobe */
112 static double
113 rbf_volume(const RBFVAL *rbfp)
114 {
115 double rad = R2ANG(rbfp->crad);
116
117 return((2.*M_PI) * rbfp->peak * rad*rad);
118 }
119
120 /* Compute outgoing vector from grid position */
121 static void
122 ovec_from_pos(FVECT vec, int xpos, int ypos)
123 {
124 double uv[2];
125 double r2;
126
127 SDsquare2disk(uv, (1./GRIDRES)*(xpos+.5), (1./GRIDRES)*(ypos+.5));
128 /* uniform hemispherical projection */
129 r2 = uv[0]*uv[0] + uv[1]*uv[1];
130 vec[0] = vec[1] = sqrt(2. - r2);
131 vec[0] *= uv[0];
132 vec[1] *= uv[1];
133 vec[2] = output_orient*(1. - r2);
134 }
135
136 /* Compute grid position from normalized input/output vector */
137 static void
138 pos_from_vec(int pos[2], const FVECT vec)
139 {
140 double sq[2]; /* uniform hemispherical projection */
141 double norm = 1./sqrt(1. + fabs(vec[2]));
142
143 SDdisk2square(sq, vec[0]*norm, vec[1]*norm);
144
145 pos[0] = (int)(sq[0]*GRIDRES);
146 pos[1] = (int)(sq[1]*GRIDRES);
147 }
148
149 /* Evaluate RBF for DSF at the given normalized outgoing direction */
150 static double
151 eval_rbfrep(const RBFNODE *rp, const FVECT outvec)
152 {
153 double res = .0;
154 const RBFVAL *rbfp;
155 FVECT odir;
156 double sig2;
157 int n;
158
159 if (rp == NULL)
160 return(.0);
161 rbfp = rp->rbfa;
162 for (n = rp->nrbf; n--; rbfp++) {
163 ovec_from_pos(odir, rbfp->gx, rbfp->gy);
164 sig2 = R2ANG(rbfp->crad);
165 sig2 = (DOT(odir,outvec) - 1.) / (sig2*sig2);
166 if (sig2 > -19.)
167 res += rbfp->peak * exp(sig2);
168 }
169 return(res);
170 }
171
172 /* Insert a new directional scattering function in our global list */
173 static void
174 insert_dsf(RBFNODE *newrbf)
175 {
176 RBFNODE *rbf, *rbf_last;
177 /* check for redundant meas. */
178 for (rbf = dsf_list; rbf != NULL; rbf = rbf->next)
179 if (DOT(rbf->invec, newrbf->invec) >= 1.-FTINY) {
180 fputs("Duplicate incident measurement (ignored)\n", stderr);
181 free(newrbf);
182 return;
183 }
184 /* keep in ascending theta order */
185 for (rbf_last = NULL, rbf = dsf_list;
186 single_plane_incident & (rbf != NULL);
187 rbf_last = rbf, rbf = rbf->next)
188 if (input_orient*rbf->invec[2] < input_orient*newrbf->invec[2])
189 break;
190 if (rbf_last == NULL) {
191 newrbf->next = dsf_list;
192 dsf_list = newrbf;
193 return;
194 }
195 newrbf->next = rbf;
196 rbf_last->next = newrbf;
197 }
198
199 /* Count up filled nodes and build RBF representation from current grid */
200 static RBFNODE *
201 make_rbfrep(void)
202 {
203 int niter = 16;
204 int minrad = ANG2R(pow(2., 1.-samp_order));
205 double lastVar, thisVar = 100.;
206 int nn;
207 RBFNODE *newnode;
208 int i, j;
209
210 nn = 0; /* count selected bins */
211 for (i = 0; i < GRIDRES; i++)
212 for (j = 0; j < GRIDRES; j++)
213 nn += dsf_grid[i][j].nval;
214 /* allocate RBF array */
215 newnode = (RBFNODE *)malloc(sizeof(RBFNODE) + sizeof(RBFVAL)*(nn-1));
216 if (newnode == NULL) {
217 fputs("Out of memory in make_rbfrep()\n", stderr);
218 exit(1);
219 }
220 newnode->next = NULL;
221 newnode->ejl = NULL;
222 newnode->invec[2] = sin(M_PI/180.*theta_in_deg);
223 newnode->invec[0] = cos(M_PI/180.*phi_in_deg)*newnode->invec[2];
224 newnode->invec[1] = sin(M_PI/180.*phi_in_deg)*newnode->invec[2];
225 newnode->invec[2] = input_orient*sqrt(1. - newnode->invec[2]*newnode->invec[2]);
226 newnode->vtotal = 0;
227 newnode->nrbf = nn;
228 nn = 0; /* fill RBF array */
229 for (i = 0; i < GRIDRES; i++)
230 for (j = 0; j < GRIDRES; j++)
231 if (dsf_grid[i][j].nval) {
232 newnode->rbfa[nn].peak = dsf_grid[i][j].vsum;
233 newnode->rbfa[nn].crad = RSCA*dsf_grid[i][j].crad + .5;
234 newnode->rbfa[nn].gx = i;
235 newnode->rbfa[nn].gy = j;
236 if (newnode->rbfa[nn].crad < minrad)
237 minrad = newnode->rbfa[nn].crad;
238 ++nn;
239 }
240 /* iterate to improve interpolation accuracy */
241 do {
242 double dsum = 0, dsum2 = 0;
243 nn = 0;
244 for (i = 0; i < GRIDRES; i++)
245 for (j = 0; j < GRIDRES; j++)
246 if (dsf_grid[i][j].nval) {
247 FVECT odir;
248 double corr;
249 ovec_from_pos(odir, i, j);
250 newnode->rbfa[nn++].peak *= corr =
251 dsf_grid[i][j].vsum /
252 eval_rbfrep(newnode, odir);
253 dsum += corr - 1.;
254 dsum2 += (corr-1.)*(corr-1.);
255 }
256 lastVar = thisVar;
257 thisVar = dsum2/(double)nn;
258 #ifdef DEBUG
259 fprintf(stderr, "Avg., RMS error: %.1f%% %.1f%%\n",
260 100.*dsum/(double)nn,
261 100.*sqrt(thisVar));
262 #endif
263 } while (--niter > 0 && lastVar-thisVar > 0.02*lastVar);
264
265 nn = 0; /* compute sum for normalization */
266 while (nn < newnode->nrbf)
267 newnode->vtotal += rbf_volume(&newnode->rbfa[nn++]);
268
269 insert_dsf(newnode);
270 /* adjust sampling resolution */
271 samp_order = log(2./R2ANG(minrad))/M_LN2 + .5;
272
273 return(newnode);
274 }
275
276 /* Load a set of measurements corresponding to a particular incident angle */
277 static int
278 load_pabopto_meas(const char *fname)
279 {
280 FILE *fp = fopen(fname, "r");
281 int inp_is_DSF = -1;
282 double new_phi, theta_out, phi_out, val;
283 char buf[2048];
284 int n, c;
285
286 if (fp == NULL) {
287 fputs(fname, stderr);
288 fputs(": cannot open\n", stderr);
289 return(0);
290 }
291 memset(dsf_grid, 0, sizeof(dsf_grid));
292 #ifdef DEBUG
293 fprintf(stderr, "Loading measurement file '%s'...\n", fname);
294 #endif
295 /* read header information */
296 while ((c = getc(fp)) == '#' || c == EOF) {
297 if (fgets(buf, sizeof(buf), fp) == NULL) {
298 fputs(fname, stderr);
299 fputs(": unexpected EOF\n", stderr);
300 fclose(fp);
301 return(0);
302 }
303 if (!strcmp(buf, "format: theta phi DSF\n")) {
304 inp_is_DSF = 1;
305 continue;
306 }
307 if (!strcmp(buf, "format: theta phi BSDF\n")) {
308 inp_is_DSF = 0;
309 continue;
310 }
311 if (sscanf(buf, "intheta %lf", &theta_in_deg) == 1)
312 continue;
313 if (sscanf(buf, "inphi %lf", &new_phi) == 1)
314 continue;
315 if (sscanf(buf, "incident_angle %lf %lf",
316 &theta_in_deg, &new_phi) == 2)
317 continue;
318 }
319 if (inp_is_DSF < 0) {
320 fputs(fname, stderr);
321 fputs(": unknown format\n", stderr);
322 fclose(fp);
323 return(0);
324 }
325 if (!input_orient) /* check input orientation */
326 input_orient = 1 - 2*(theta_in_deg > 90.);
327 else if (input_orient > 0 ^ theta_in_deg < 90.) {
328 fputs("Cannot handle input angles on both sides of surface\n",
329 stderr);
330 exit(1);
331 }
332 if (single_plane_incident > 0) /* check if still in plane */
333 single_plane_incident = (round(new_phi) == round(phi_in_deg));
334 else if (single_plane_incident < 0)
335 single_plane_incident = 1;
336 phi_in_deg = new_phi;
337 ungetc(c, fp); /* read actual data */
338 while (fscanf(fp, "%lf %lf %lf\n", &theta_out, &phi_out, &val) == 3) {
339 FVECT ovec;
340 int pos[2];
341
342 if (!output_orient) /* check output orientation */
343 output_orient = 1 - 2*(theta_out > 90.);
344 else if (output_orient > 0 ^ theta_out < 90.) {
345 fputs("Cannot handle output angles on both sides of surface\n",
346 stderr);
347 exit(1);
348 }
349 ovec[2] = sin(M_PI/180.*theta_out);
350 ovec[0] = cos(M_PI/180.*phi_out) * ovec[2];
351 ovec[1] = sin(M_PI/180.*phi_out) * ovec[2];
352 ovec[2] = sqrt(1. - ovec[2]*ovec[2]);
353
354 if (!inp_is_DSF)
355 val *= ovec[2]; /* convert from BSDF to DSF */
356
357 pos_from_vec(pos, ovec);
358
359 dsf_grid[pos[0]][pos[1]].vsum += val;
360 dsf_grid[pos[0]][pos[1]].nval++;
361 }
362 n = 0;
363 while ((c = getc(fp)) != EOF)
364 n += !isspace(c);
365 if (n)
366 fprintf(stderr,
367 "%s: warning: %d unexpected characters past EOD\n",
368 fname, n);
369 fclose(fp);
370 return(1);
371 }
372
373 /* Compute radii for non-empty bins */
374 /* (distance to furthest empty bin for which non-empty bin is the closest) */
375 static void
376 compute_radii(void)
377 {
378 unsigned int fill_grid[GRIDRES][GRIDRES];
379 unsigned short fill_cnt[GRIDRES][GRIDRES];
380 FVECT ovec0, ovec1;
381 double ang2, lastang2;
382 int r, i, j, jn, ii, jj, inear, jnear;
383
384 r = GRIDRES/2; /* proceed in zig-zag */
385 for (i = 0; i < GRIDRES; i++)
386 for (jn = 0; jn < GRIDRES; jn++) {
387 j = (i&1) ? jn : GRIDRES-1-jn;
388 if (dsf_grid[i][j].nval) /* find empty grid pos. */
389 continue;
390 ovec_from_pos(ovec0, i, j);
391 inear = jnear = -1; /* find nearest non-empty */
392 lastang2 = M_PI*M_PI;
393 for (ii = i-r; ii <= i+r; ii++) {
394 if (ii < 0) continue;
395 if (ii >= GRIDRES) break;
396 for (jj = j-r; jj <= j+r; jj++) {
397 if (jj < 0) continue;
398 if (jj >= GRIDRES) break;
399 if (!dsf_grid[ii][jj].nval)
400 continue;
401 ovec_from_pos(ovec1, ii, jj);
402 ang2 = 2. - 2.*DOT(ovec0,ovec1);
403 if (ang2 >= lastang2)
404 continue;
405 lastang2 = ang2;
406 inear = ii; jnear = jj;
407 }
408 }
409 if (inear < 0) {
410 fputs("Could not find non-empty neighbor!\n", stderr);
411 exit(1);
412 }
413 ang2 = sqrt(lastang2);
414 r = ANG2R(ang2); /* record if > previous */
415 if (r > dsf_grid[inear][jnear].crad)
416 dsf_grid[inear][jnear].crad = r;
417 /* next search radius */
418 r = ang2*(2.*GRIDRES/M_PI) + 3;
419 }
420 /* blur radii over hemisphere */
421 memset(fill_grid, 0, sizeof(fill_grid));
422 memset(fill_cnt, 0, sizeof(fill_cnt));
423 for (i = 0; i < GRIDRES; i++)
424 for (j = 0; j < GRIDRES; j++) {
425 if (!dsf_grid[i][j].crad)
426 continue; /* missing distance */
427 r = R2ANG(dsf_grid[i][j].crad)*(2.*RSCA*GRIDRES/M_PI);
428 for (ii = i-r; ii <= i+r; ii++) {
429 if (ii < 0) continue;
430 if (ii >= GRIDRES) break;
431 for (jj = j-r; jj <= j+r; jj++) {
432 if (jj < 0) continue;
433 if (jj >= GRIDRES) break;
434 if ((ii-i)*(ii-i) + (jj-j)*(jj-j) > r*r)
435 continue;
436 fill_grid[ii][jj] += dsf_grid[i][j].crad;
437 fill_cnt[ii][jj]++;
438 }
439 }
440 }
441 /* copy back blurred radii */
442 for (i = 0; i < GRIDRES; i++)
443 for (j = 0; j < GRIDRES; j++)
444 if (fill_cnt[i][j])
445 dsf_grid[i][j].crad = fill_grid[i][j]/fill_cnt[i][j];
446 }
447
448 /* Cull points for more uniform distribution, leave all nval 0 or 1 */
449 static void
450 cull_values(void)
451 {
452 FVECT ovec0, ovec1;
453 double maxang, maxang2;
454 int i, j, ii, jj, r;
455 /* simple greedy algorithm */
456 for (i = 0; i < GRIDRES; i++)
457 for (j = 0; j < GRIDRES; j++) {
458 if (!dsf_grid[i][j].nval)
459 continue;
460 if (!dsf_grid[i][j].crad)
461 continue; /* shouldn't happen */
462 ovec_from_pos(ovec0, i, j);
463 maxang = 2.*R2ANG(dsf_grid[i][j].crad);
464 if (maxang > ovec0[2]) /* clamp near horizon */
465 maxang = ovec0[2];
466 r = maxang*(2.*GRIDRES/M_PI) + 1;
467 maxang2 = maxang*maxang;
468 for (ii = i-r; ii <= i+r; ii++) {
469 if (ii < 0) continue;
470 if (ii >= GRIDRES) break;
471 for (jj = j-r; jj <= j+r; jj++) {
472 if (jj < 0) continue;
473 if (jj >= GRIDRES) break;
474 if (!dsf_grid[ii][jj].nval)
475 continue;
476 if ((ii == i) & (jj == j))
477 continue; /* don't get self-absorbed */
478 ovec_from_pos(ovec1, ii, jj);
479 if (2. - 2.*DOT(ovec0,ovec1) >= maxang2)
480 continue;
481 /* absorb sum */
482 dsf_grid[i][j].vsum += dsf_grid[ii][jj].vsum;
483 dsf_grid[i][j].nval += dsf_grid[ii][jj].nval;
484 /* keep value, though */
485 dsf_grid[ii][jj].vsum /= (float)dsf_grid[ii][jj].nval;
486 dsf_grid[ii][jj].nval = 0;
487 }
488 }
489 }
490 /* final averaging pass */
491 for (i = 0; i < GRIDRES; i++)
492 for (j = 0; j < GRIDRES; j++)
493 if (dsf_grid[i][j].nval > 1) {
494 dsf_grid[i][j].vsum /= (float)dsf_grid[i][j].nval;
495 dsf_grid[i][j].nval = 1;
496 }
497 }
498
499 /* Compute (and allocate) migration price matrix for optimization */
500 static float *
501 price_routes(const RBFNODE *from_rbf, const RBFNODE *to_rbf)
502 {
503 float *pmtx = (float *)malloc(sizeof(float) *
504 from_rbf->nrbf * to_rbf->nrbf);
505 FVECT *vto = (FVECT *)malloc(sizeof(FVECT) * to_rbf->nrbf);
506 int i, j;
507
508 if ((pmtx == NULL) | (vto == NULL)) {
509 fputs("Out of memory in migration_costs()\n", stderr);
510 exit(1);
511 }
512 for (j = to_rbf->nrbf; j--; ) /* save repetitive ops. */
513 ovec_from_pos(vto[j], to_rbf->rbfa[j].gx, to_rbf->rbfa[j].gy);
514
515 for (i = from_rbf->nrbf; i--; ) {
516 const double from_ang = R2ANG(from_rbf->rbfa[i].crad);
517 FVECT vfrom;
518 ovec_from_pos(vfrom, from_rbf->rbfa[i].gx, from_rbf->rbfa[i].gy);
519 for (j = to_rbf->nrbf; j--; )
520 pmtx[i*to_rbf->nrbf + j] = acos(DOT(vfrom, vto[j])) +
521 fabs(R2ANG(to_rbf->rbfa[j].crad) - from_ang);
522 }
523 free(vto);
524 return(pmtx);
525 }
526
527 /* Comparison routine needed for sorting price row */
528 static const float *price_arr;
529 static int
530 msrt_cmp(const void *p1, const void *p2)
531 {
532 float c1 = price_arr[*(const int *)p1];
533 float c2 = price_arr[*(const int *)p2];
534
535 if (c1 > c2) return(1);
536 if (c1 < c2) return(-1);
537 return(0);
538 }
539
540 /* Compute minimum (optimistic) cost for moving the given source material */
541 static double
542 min_cost(double amt2move, const double *avail, const float *price, int n)
543 {
544 static int *price_sort = NULL;
545 static int n_alloc = 0;
546 double total_cost = 0;
547 int i;
548
549 if (amt2move <= FTINY) /* pre-emptive check */
550 return(0.);
551 if (n > n_alloc) { /* (re)allocate sort array */
552 if (n_alloc) free(price_sort);
553 price_sort = (int *)malloc(sizeof(int)*n);
554 if (price_sort == NULL) {
555 fputs("Out of memory in min_cost()\n", stderr);
556 exit(1);
557 }
558 n_alloc = n;
559 }
560 for (i = n; i--; )
561 price_sort[i] = i;
562 price_arr = price;
563 qsort(price_sort, n, sizeof(int), &msrt_cmp);
564 /* move cheapest first */
565 for (i = 0; i < n && amt2move > FTINY; i++) {
566 int d = price_sort[i];
567 double amt = (amt2move < avail[d]) ? amt2move : avail[d];
568
569 total_cost += amt * price[d];
570 amt2move -= amt;
571 }
572 return(total_cost);
573 }
574
575 /* Take a step in migration by choosing optimal bucket to transfer */
576 static double
577 migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, const float *pmtx)
578 {
579 static double *src_cost = NULL;
580 int n_alloc = 0;
581 const double maxamt = .1; /* 2./(mtx_nrows(mig)*mtx_ncols(mig)); */
582 double amt = 0;
583 struct {
584 int s, d; /* source and destination */
585 double price; /* price estimate per amount moved */
586 double amt; /* amount we can move */
587 } cur, best;
588 int i;
589
590 if (mtx_nrows(mig) > n_alloc) { /* allocate cost array */
591 if (n_alloc)
592 free(src_cost);
593 src_cost = (double *)malloc(sizeof(double)*mtx_nrows(mig));
594 if (src_cost == NULL) {
595 fputs("Out of memory in migration_step()\n", stderr);
596 exit(1);
597 }
598 n_alloc = mtx_nrows(mig);
599 }
600 for (i = mtx_nrows(mig); i--; ) /* starting costs for diff. */
601 src_cost[i] = min_cost(src_rem[i], dst_rem,
602 pmtx+i*mtx_ncols(mig), mtx_ncols(mig));
603
604 /* find best source & dest. */
605 best.s = best.d = -1; best.price = FHUGE; best.amt = 0;
606 for (cur.s = mtx_nrows(mig); cur.s--; ) {
607 const float *price = pmtx + cur.s*mtx_ncols(mig);
608 double cost_others = 0;
609 if (src_rem[cur.s] <= FTINY)
610 continue;
611 cur.d = -1; /* examine cheapest dest. */
612 for (i = mtx_ncols(mig); i--; )
613 if (dst_rem[i] > FTINY &&
614 (cur.d < 0 || price[i] < price[cur.d]))
615 cur.d = i;
616 if (cur.d < 0)
617 return(.0);
618 if ((cur.price = price[cur.d]) >= best.price)
619 continue; /* no point checking further */
620 cur.amt = (src_rem[cur.s] < dst_rem[cur.d]) ?
621 src_rem[cur.s] : dst_rem[cur.d];
622 if (cur.amt > maxamt) cur.amt = maxamt;
623 dst_rem[cur.d] -= cur.amt; /* add up differential costs */
624 for (i = mtx_nrows(mig); i--; ) {
625 if (i == cur.s) continue;
626 cost_others += min_cost(src_rem[i], dst_rem, price, mtx_ncols(mig))
627 - src_cost[i];
628 }
629 dst_rem[cur.d] += cur.amt; /* undo trial move */
630 cur.price += cost_others/cur.amt; /* adjust effective price */
631 if (cur.price < best.price) /* are we better than best? */
632 best = cur;
633 }
634 if ((best.s < 0) | (best.d < 0))
635 return(.0);
636 /* make the actual move */
637 mig->mtx[mtx_ndx(mig,best.s,best.d)] += best.amt;
638 src_rem[best.s] -= best.amt;
639 dst_rem[best.d] -= best.amt;
640 return(best.amt);
641 }
642
643 #ifdef DEBUG
644 static char *
645 thetaphi(const FVECT v)
646 {
647 static char buf[128];
648 double theta, phi;
649
650 theta = 180./M_PI*acos(v[2]);
651 phi = 180./M_PI*atan2(v[1],v[0]);
652 sprintf(buf, "(%.0f,%.0f)", theta, phi);
653
654 return(buf);
655 }
656 #endif
657
658 /* Create a new migration holder (sharing memory for multiprocessing) */
659 static MIGRATION *
660 new_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
661 {
662 size_t memlen = sizeof(MIGRATION) +
663 sizeof(float)*(from_rbf->nrbf*to_rbf->nrbf - 1);
664 MIGRATION *newmig;
665 #ifdef _WIN32
666 newmig = (MIGRATION *)malloc(memlen);
667 #else
668 if (nprocs <= 1) { /* single process? */
669 newmig = (MIGRATION *)malloc(memlen);
670 } else { /* else need to share memory */
671 newmig = (MIGRATION *)mmap(NULL, memlen, PROT_READ|PROT_WRITE,
672 MAP_ANON|MAP_SHARED, -1, 0);
673 if ((void *)newmig == MAP_FAILED)
674 newmig = NULL;
675 }
676 #endif
677 if (newmig == NULL) {
678 fprintf(stderr, "%s: cannot allocate new migration\n", progname);
679 exit(1);
680 }
681 newmig->rbfv[0] = from_rbf;
682 newmig->rbfv[1] = to_rbf;
683 /* insert in edge lists */
684 newmig->enxt[0] = from_rbf->ejl;
685 from_rbf->ejl = newmig;
686 newmig->enxt[1] = to_rbf->ejl;
687 to_rbf->ejl = newmig;
688 newmig->next = mig_list; /* push onto global list */
689 return(mig_list = newmig);
690 }
691
692 #ifdef _WIN32
693 #define await_children(n) (void)(n)
694 #define run_subprocess() 0
695 #define end_subprocess() (void)0
696 #else
697
698 /* Wait for the specified number of child processes to complete */
699 static void
700 await_children(int n)
701 {
702 if (n > nchild)
703 n = nchild;
704 while (n-- > 0) {
705 int status;
706 if (wait(&status) < 0) {
707 fprintf(stderr, "%s: missing child(ren)!\n", progname);
708 nchild = 0;
709 break;
710 }
711 --nchild;
712 if (status) {
713 if ((status = WEXITSTATUS(status)))
714 exit(status);
715 fprintf(stderr, "%s: subprocess died\n", progname);
716 exit(1);
717 }
718 }
719 }
720
721 /* Start child process if multiprocessing selected */
722 static pid_t
723 run_subprocess(void)
724 {
725 int status;
726 pid_t pid;
727
728 if (nprocs <= 1) /* any children requested? */
729 return(0);
730 await_children(nchild + 1 - nprocs); /* free up child process */
731 if ((pid = fork())) {
732 if (pid < 0) {
733 fprintf(stderr, "%s: cannot fork subprocess\n",
734 progname);
735 exit(1);
736 }
737 ++nchild; /* subprocess started */
738 return(pid);
739 }
740 nchild = -1;
741 return(0); /* put child to work */
742 }
743
744 /* If we are in subprocess, call exit */
745 #define end_subprocess() if (nchild < 0) _exit(0); else
746
747 #endif /* ! _WIN32 */
748
749 /* Compute and insert migration along directed edge (may fork child) */
750 static MIGRATION *
751 create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
752 {
753 const double end_thresh = 0.02/(from_rbf->nrbf*to_rbf->nrbf);
754 float *pmtx;
755 MIGRATION *newmig;
756 double *src_rem, *dst_rem;
757 double total_rem = 1.;
758 int i;
759 /* check if exists already */
760 for (newmig = from_rbf->ejl; newmig != NULL;
761 newmig = nextedge(from_rbf,newmig))
762 if (newmig->rbfv[1] == to_rbf)
763 return(NULL);
764 /* else allocate */
765 newmig = new_migration(from_rbf, to_rbf);
766 if (run_subprocess())
767 return(newmig); /* child continues */
768 pmtx = price_routes(from_rbf, to_rbf);
769 src_rem = (double *)malloc(sizeof(double)*from_rbf->nrbf);
770 dst_rem = (double *)malloc(sizeof(double)*to_rbf->nrbf);
771 if ((src_rem == NULL) | (dst_rem == NULL)) {
772 fputs("Out of memory in create_migration()\n", stderr);
773 exit(1);
774 }
775 #ifdef DEBUG
776 fprintf(stderr, "Building path from (theta,phi) %s ",
777 thetaphi(from_rbf->invec));
778 fprintf(stderr, "to %s", thetaphi(to_rbf->invec));
779 /* if (nchild) */ fputc('\n', stderr);
780 #endif
781 /* starting quantities */
782 memset(newmig->mtx, 0, sizeof(float)*from_rbf->nrbf*to_rbf->nrbf);
783 for (i = from_rbf->nrbf; i--; )
784 src_rem[i] = rbf_volume(&from_rbf->rbfa[i]) / from_rbf->vtotal;
785 for (i = to_rbf->nrbf; i--; )
786 dst_rem[i] = rbf_volume(&to_rbf->rbfa[i]) / to_rbf->vtotal;
787 /* move a bit at a time */
788 while (total_rem > end_thresh) {
789 total_rem -= migration_step(newmig, src_rem, dst_rem, pmtx);
790 #ifdef DEBUG
791 if (!nchild)
792 /* fputc('.', stderr); */
793 fprintf(stderr, "%.9f remaining...\r", total_rem);
794 #endif
795 }
796 #ifdef DEBUG
797 if (!nchild) fputs("done.\n", stderr);
798 #endif
799
800 free(pmtx); /* free working arrays */
801 free(src_rem);
802 free(dst_rem);
803 for (i = from_rbf->nrbf; i--; ) { /* normalize final matrix */
804 float nf = rbf_volume(&from_rbf->rbfa[i]);
805 int j;
806 if (nf <= FTINY) continue;
807 nf = from_rbf->vtotal / nf;
808 for (j = to_rbf->nrbf; j--; )
809 newmig->mtx[mtx_ndx(newmig,i,j)] *= nf;
810 }
811 end_subprocess(); /* exit here if subprocess */
812 return(newmig);
813 }
814
815 /* Get triangle surface orientation (unnormalized) */
816 static void
817 tri_orient(FVECT vres, const FVECT v1, const FVECT v2, const FVECT v3)
818 {
819 FVECT v2minus1, v3minus2;
820
821 VSUB(v2minus1, v2, v1);
822 VSUB(v3minus2, v3, v2);
823 VCROSS(vres, v2minus1, v3minus2);
824 }
825
826 /* Determine if vertex order is reversed (inward normal) */
827 static int
828 is_rev_tri(const FVECT v1, const FVECT v2, const FVECT v3)
829 {
830 FVECT tor;
831
832 tri_orient(tor, v1, v2, v3);
833
834 return(DOT(tor, v2) < 0.);
835 }
836
837 /* Find vertices completing triangles on either side of the given edge */
838 static int
839 get_triangles(RBFNODE *rbfv[2], const MIGRATION *mig)
840 {
841 const MIGRATION *ej, *ej2;
842 RBFNODE *tv;
843
844 rbfv[0] = rbfv[1] = NULL;
845 if (mig == NULL)
846 return(0);
847 for (ej = mig->rbfv[0]->ejl; ej != NULL;
848 ej = nextedge(mig->rbfv[0],ej)) {
849 if (ej == mig)
850 continue;
851 tv = opp_rbf(mig->rbfv[0],ej);
852 for (ej2 = tv->ejl; ej2 != NULL; ej2 = nextedge(tv,ej2))
853 if (opp_rbf(tv,ej2) == mig->rbfv[1]) {
854 rbfv[is_rev_tri(mig->rbfv[0]->invec,
855 mig->rbfv[1]->invec,
856 tv->invec)] = tv;
857 break;
858 }
859 }
860 return((rbfv[0] != NULL) + (rbfv[1] != NULL));
861 }
862
863 /* Check if prospective vertex would create overlapping triangle */
864 static int
865 overlaps_tri(const RBFNODE *bv0, const RBFNODE *bv1, const RBFNODE *pv)
866 {
867 const MIGRATION *ej;
868 RBFNODE *vother[2];
869 int im_rev;
870 /* find shared edge in mesh */
871 for (ej = pv->ejl; ej != NULL; ej = nextedge(pv,ej)) {
872 const RBFNODE *tv = opp_rbf(pv,ej);
873 if (tv == bv0) {
874 im_rev = is_rev_tri(ej->rbfv[0]->invec,
875 ej->rbfv[1]->invec, bv1->invec);
876 break;
877 }
878 if (tv == bv1) {
879 im_rev = is_rev_tri(ej->rbfv[0]->invec,
880 ej->rbfv[1]->invec, bv0->invec);
881 break;
882 }
883 }
884 if (!get_triangles(vother, ej)) /* triangle on same side? */
885 return(0);
886 return(vother[im_rev] != NULL);
887 }
888
889 /* Find context hull vertex to complete triangle (oriented call) */
890 static RBFNODE *
891 find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rbf1)
892 {
893 FVECT vmid, vejn, vp;
894 RBFNODE *rbf, *rbfbest = NULL;
895 double dprod, area2, bestarea2 = FHUGE, bestdprod = -.5;
896
897 VSUB(vejn, rbf1->invec, rbf0->invec);
898 VADD(vmid, rbf0->invec, rbf1->invec);
899 if (normalize(vejn) == 0 || normalize(vmid) == 0)
900 return(NULL);
901 /* XXX exhaustive search */
902 /* Find triangle with minimum rotation from perpendicular */
903 for (rbf = dsf_list; rbf != NULL; rbf = rbf->next) {
904 if ((rbf == rbf0) | (rbf == rbf1))
905 continue;
906 tri_orient(vp, rbf0->invec, rbf1->invec, rbf->invec);
907 if (DOT(vp, vmid) <= FTINY)
908 continue; /* wrong orientation */
909 area2 = .25*DOT(vp,vp);
910 VSUB(vp, rbf->invec, rbf0->invec);
911 dprod = -DOT(vp, vejn);
912 VSUM(vp, vp, vejn, dprod); /* above guarantees non-zero */
913 dprod = DOT(vp, vmid) / VLEN(vp);
914 if (dprod <= bestdprod + FTINY*(1 - 2*(area2 < bestarea2)))
915 continue; /* found better already */
916 if (overlaps_tri(rbf0, rbf1, rbf))
917 continue; /* overlaps another triangle */
918 rbfbest = rbf;
919 bestdprod = dprod; /* new one to beat */
920 bestarea2 = area2;
921 }
922 return(rbfbest);
923 }
924
925 /* Create new migration edge and grow mesh recursively around it */
926 static void
927 mesh_from_edge(MIGRATION *edge)
928 {
929 MIGRATION *ej0, *ej1;
930 RBFNODE *tvert[2];
931
932 if (edge == NULL)
933 return;
934 /* triangle on either side? */
935 get_triangles(tvert, edge);
936 if (tvert[0] == NULL) { /* grow mesh on right */
937 tvert[0] = find_chull_vert(edge->rbfv[0], edge->rbfv[1]);
938 if (tvert[0] != NULL) {
939 if (tvert[0] > edge->rbfv[0])
940 ej0 = create_migration(edge->rbfv[0], tvert[0]);
941 else
942 ej0 = create_migration(tvert[0], edge->rbfv[0]);
943 if (tvert[0] > edge->rbfv[1])
944 ej1 = create_migration(edge->rbfv[1], tvert[0]);
945 else
946 ej1 = create_migration(tvert[0], edge->rbfv[1]);
947 mesh_from_edge(ej0);
948 mesh_from_edge(ej1);
949 }
950 } else if (tvert[1] == NULL) { /* grow mesh on left */
951 tvert[1] = find_chull_vert(edge->rbfv[1], edge->rbfv[0]);
952 if (tvert[1] != NULL) {
953 if (tvert[1] > edge->rbfv[0])
954 ej0 = create_migration(edge->rbfv[0], tvert[1]);
955 else
956 ej0 = create_migration(tvert[1], edge->rbfv[0]);
957 if (tvert[1] > edge->rbfv[1])
958 ej1 = create_migration(edge->rbfv[1], tvert[1]);
959 else
960 ej1 = create_migration(tvert[1], edge->rbfv[1]);
961 mesh_from_edge(ej0);
962 mesh_from_edge(ej1);
963 }
964 }
965 }
966
967 #ifdef DEBUG
968 #include "random.h"
969 #include "bmpfile.h"
970 /* Hash pointer to byte value (must return 0 for NULL) */
971 static int
972 byte_hash(const void *p)
973 {
974 size_t h = (size_t)p;
975 h ^= (size_t)p >> 8;
976 h ^= (size_t)p >> 16;
977 h ^= (size_t)p >> 24;
978 return(h & 0xff);
979 }
980 /* Write out BMP image showing edges */
981 static void
982 write_edge_image(const char *fname)
983 {
984 BMPHeader *hdr = BMPmappedHeader(GRIDRES, GRIDRES, 0, 256);
985 BMPWriter *wtr;
986 int i, j;
987
988 fprintf(stderr, "Writing incident mesh drawing to '%s'\n", fname);
989 hdr->compr = BI_RLE8;
990 for (i = 256; --i; ) { /* assign random color map */
991 hdr->palette[i].r = random() & 0xff;
992 hdr->palette[i].g = random() & 0xff;
993 hdr->palette[i].b = random() & 0xff;
994 /* reject dark colors */
995 i += (hdr->palette[i].r + hdr->palette[i].g +
996 hdr->palette[i].b < 128);
997 }
998 hdr->palette[0].r = hdr->palette[0].g = hdr->palette[0].b = 0;
999 /* open output */
1000 wtr = BMPopenOutputFile(fname, hdr);
1001 if (wtr == NULL) {
1002 free(hdr);
1003 return;
1004 }
1005 for (i = 0; i < GRIDRES; i++) { /* write scanlines */
1006 for (j = 0; j < GRIDRES; j++)
1007 wtr->scanline[j] = byte_hash(mig_grid[i][j]);
1008 if (BMPwriteScanline(wtr) != BIR_OK)
1009 break;
1010 }
1011 BMPcloseOutput(wtr); /* close & clean up */
1012 }
1013 #endif
1014
1015 /* Draw edge list into mig_grid array */
1016 static void
1017 draw_edges()
1018 {
1019 int nnull = 0, ntot = 0;
1020 MIGRATION *ej;
1021 int p0[2], p1[2];
1022
1023 /* memset(mig_grid, 0, sizeof(mig_grid)); */
1024 for (ej = mig_list; ej != NULL; ej = ej->next) {
1025 ++ntot;
1026 pos_from_vec(p0, ej->rbfv[0]->invec);
1027 pos_from_vec(p1, ej->rbfv[1]->invec);
1028 if ((p0[0] == p1[0]) & (p0[1] == p1[1])) {
1029 ++nnull;
1030 mig_grid[p0[0]][p0[1]] = ej;
1031 continue;
1032 }
1033 if (abs(p1[0]-p0[0]) > abs(p1[1]-p0[1])) {
1034 const int xstep = 2*(p1[0] > p0[0]) - 1;
1035 const double ystep = (double)((p1[1]-p0[1])*xstep) /
1036 (double)(p1[0]-p0[0]);
1037 int x;
1038 double y;
1039 for (x = p0[0], y = p0[1]+.5; x != p1[0];
1040 x += xstep, y += ystep)
1041 mig_grid[x][(int)y] = ej;
1042 mig_grid[x][(int)y] = ej;
1043 } else {
1044 const int ystep = 2*(p1[1] > p0[1]) - 1;
1045 const double xstep = (double)((p1[0]-p0[0])*ystep) /
1046 (double)(p1[1]-p0[1]);
1047 int y;
1048 double x;
1049 for (y = p0[1], x = p0[0]+.5; y != p1[1];
1050 y += ystep, x += xstep)
1051 mig_grid[(int)x][y] = ej;
1052 mig_grid[(int)x][y] = ej;
1053 }
1054 }
1055 if (nnull)
1056 fprintf(stderr, "Warning: %d of %d edges are null\n",
1057 nnull, ntot);
1058 #ifdef DEBUG
1059 write_edge_image("bsdf_edges.bmp");
1060 #endif
1061 }
1062
1063 /* Build our triangle mesh from recorded RBFs */
1064 static void
1065 build_mesh()
1066 {
1067 double best2 = M_PI*M_PI;
1068 RBFNODE *shrt_edj[2];
1069 RBFNODE *rbf0, *rbf1;
1070 /* check if isotropic */
1071 if (single_plane_incident) {
1072 for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)
1073 if (rbf0->next != NULL)
1074 create_migration(rbf0, rbf0->next);
1075 await_children(nchild);
1076 return;
1077 }
1078 /* start w/ shortest edge */
1079 shrt_edj[0] = shrt_edj[1] = NULL;
1080 for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)
1081 for (rbf1 = rbf0->next; rbf1 != NULL; rbf1 = rbf1->next) {
1082 double dist2 = 2. - 2.*DOT(rbf0->invec,rbf1->invec);
1083 if (dist2 < best2) {
1084 shrt_edj[0] = rbf0;
1085 shrt_edj[1] = rbf1;
1086 best2 = dist2;
1087 }
1088 }
1089 if (shrt_edj[0] == NULL) {
1090 fputs("Cannot find shortest edge\n", stderr);
1091 exit(1);
1092 }
1093 /* build mesh from this edge */
1094 if (shrt_edj[0] < shrt_edj[1])
1095 mesh_from_edge(create_migration(shrt_edj[0], shrt_edj[1]));
1096 else
1097 mesh_from_edge(create_migration(shrt_edj[1], shrt_edj[0]));
1098 /* complete migrations */
1099 await_children(nchild);
1100 /* draw edge list into grid */
1101 draw_edges();
1102 }
1103
1104 /* Identify enclosing triangle for this position (flood fill raster check) */
1105 static int
1106 identify_tri(MIGRATION *miga[3], unsigned char vmap[GRIDRES][(GRIDRES+7)/8],
1107 int px, int py)
1108 {
1109 const int btest = 1<<(py&07);
1110
1111 if (vmap[px][py>>3] & btest) /* already visited here? */
1112 return(1);
1113 /* else mark it */
1114 vmap[px][py>>3] |= btest;
1115
1116 if (mig_grid[px][py] != NULL) { /* are we on an edge? */
1117 int i;
1118 for (i = 0; i < 3; i++) {
1119 if (miga[i] == mig_grid[px][py])
1120 return(1);
1121 if (miga[i] != NULL)
1122 continue;
1123 miga[i] = mig_grid[px][py];
1124 return(1);
1125 }
1126 return(0); /* outside triangle! */
1127 }
1128 /* check neighbors (flood) */
1129 if (px > 0 && !identify_tri(miga, vmap, px-1, py))
1130 return(0);
1131 if (px < GRIDRES-1 && !identify_tri(miga, vmap, px+1, py))
1132 return(0);
1133 if (py > 0 && !identify_tri(miga, vmap, px, py-1))
1134 return(0);
1135 if (py < GRIDRES-1 && !identify_tri(miga, vmap, px, py+1))
1136 return(0);
1137 return(1); /* this neighborhood done */
1138 }
1139
1140 /* Insert vertex in ordered list */
1141 static void
1142 insert_vert(RBFNODE **vlist, RBFNODE *v)
1143 {
1144 int i, j;
1145
1146 for (i = 0; vlist[i] != NULL; i++) {
1147 if (v == vlist[i])
1148 return;
1149 if (v < vlist[i])
1150 break;
1151 }
1152 for (j = i; vlist[j] != NULL; j++)
1153 ;
1154 while (j > i) {
1155 vlist[j] = vlist[j-1];
1156 --j;
1157 }
1158 vlist[i] = v;
1159 }
1160
1161 /* Sort triangle edges in standard order */
1162 static int
1163 order_triangle(MIGRATION *miga[3])
1164 {
1165 RBFNODE *vert[7];
1166 MIGRATION *ord[3];
1167 int i;
1168 /* order vertices, first */
1169 memset(vert, 0, sizeof(vert));
1170 for (i = 3; i--; ) {
1171 if (miga[i] == NULL)
1172 return(0);
1173 insert_vert(vert, miga[i]->rbfv[0]);
1174 insert_vert(vert, miga[i]->rbfv[1]);
1175 }
1176 /* should be just 3 vertices */
1177 if ((vert[3] == NULL) | (vert[4] != NULL))
1178 return(0);
1179 /* identify edge 0 */
1180 for (i = 3; i--; )
1181 if (miga[i]->rbfv[0] == vert[0] &&
1182 miga[i]->rbfv[1] == vert[1]) {
1183 ord[0] = miga[i];
1184 break;
1185 }
1186 if (i < 0)
1187 return(0);
1188 /* identify edge 1 */
1189 for (i = 3; i--; )
1190 if (miga[i]->rbfv[0] == vert[1] &&
1191 miga[i]->rbfv[1] == vert[2]) {
1192 ord[1] = miga[i];
1193 break;
1194 }
1195 if (i < 0)
1196 return(0);
1197 /* identify edge 2 */
1198 for (i = 3; i--; )
1199 if (miga[i]->rbfv[0] == vert[0] &&
1200 miga[i]->rbfv[1] == vert[2]) {
1201 ord[2] = miga[i];
1202 break;
1203 }
1204 if (i < 0)
1205 return(0);
1206 /* reassign order */
1207 miga[0] = ord[0]; miga[1] = ord[1]; miga[2] = ord[2];
1208 return(1);
1209 }
1210
1211 /* Find edge(s) for interpolating the given incident vector */
1212 static int
1213 get_interp(MIGRATION *miga[3], const FVECT invec)
1214 {
1215 miga[0] = miga[1] = miga[2] = NULL;
1216 if (single_plane_incident) { /* isotropic BSDF? */
1217 RBFNODE *rbf; /* find edge we're on */
1218 for (rbf = dsf_list; rbf != NULL; rbf = rbf->next) {
1219 if (input_orient*rbf->invec[2] < input_orient*invec[2])
1220 break;
1221 if (rbf->next != NULL &&
1222 input_orient*rbf->next->invec[2] <
1223 input_orient*invec[2]) {
1224 for (miga[0] = rbf->ejl; miga[0] != NULL;
1225 miga[0] = nextedge(rbf,miga[0]))
1226 if (opp_rbf(rbf,miga[0]) == rbf->next)
1227 return(1);
1228 break;
1229 }
1230 }
1231 return(0); /* outside range! */
1232 }
1233 { /* else use triangle mesh */
1234 unsigned char floodmap[GRIDRES][(GRIDRES+7)/8];
1235 int pstart[2];
1236 RBFNODE *vother;
1237 MIGRATION *ej;
1238 int i;
1239
1240 pos_from_vec(pstart, invec);
1241 memset(floodmap, 0, sizeof(floodmap));
1242 /* call flooding function */
1243 if (!identify_tri(miga, floodmap, pstart[0], pstart[1]))
1244 return(0); /* outside mesh */
1245 if ((miga[0] == NULL) | (miga[2] == NULL))
1246 return(0); /* should never happen */
1247 if (miga[1] == NULL)
1248 return(1); /* on edge */
1249 /* verify triangle */
1250 if (!order_triangle(miga)) {
1251 #ifdef DEBUG
1252 fputs("Munged triangle in get_interp()\n", stderr);
1253 #endif
1254 vother = NULL; /* find triangle from edge */
1255 for (i = 3; i--; ) {
1256 RBFNODE *tpair[2];
1257 if (get_triangles(tpair, miga[i]) &&
1258 (vother = tpair[ is_rev_tri(
1259 miga[i]->rbfv[0]->invec,
1260 miga[i]->rbfv[1]->invec,
1261 invec) ]) != NULL)
1262 break;
1263 }
1264 if (vother == NULL) { /* couldn't find 3rd vertex */
1265 #ifdef DEBUG
1266 fputs("No triangle in get_interp()\n", stderr);
1267 #endif
1268 return(0);
1269 }
1270 /* reassign other two edges */
1271 for (ej = vother->ejl; ej != NULL;
1272 ej = nextedge(vother,ej)) {
1273 RBFNODE *vorig = opp_rbf(vother,ej);
1274 if (vorig == miga[i]->rbfv[0])
1275 miga[(i+1)%3] = ej;
1276 else if (vorig == miga[i]->rbfv[1])
1277 miga[(i+2)%3] = ej;
1278 }
1279 if (!order_triangle(miga)) {
1280 #ifdef DEBUG
1281 fputs("Bad triangle in get_interp()\n", stderr);
1282 #endif
1283 return(0);
1284 }
1285 }
1286 return(3); /* return in standard order */
1287 }
1288 }
1289
1290 /* Advect and allocate new RBF along edge */
1291 static RBFNODE *
1292 e_advect_rbf(const MIGRATION *mig, const FVECT invec)
1293 {
1294 RBFNODE *rbf;
1295 int n, i, j;
1296 double t, full_dist;
1297 /* get relative position */
1298 t = acos(DOT(invec, mig->rbfv[0]->invec));
1299 if (t < M_PI/GRIDRES) { /* near first DSF */
1300 n = sizeof(RBFNODE) + sizeof(RBFVAL)*(mig->rbfv[0]->nrbf-1);
1301 rbf = (RBFNODE *)malloc(n);
1302 if (rbf == NULL)
1303 goto memerr;
1304 memcpy(rbf, mig->rbfv[0], n); /* just duplicate */
1305 return(rbf);
1306 }
1307 full_dist = acos(DOT(mig->rbfv[0]->invec, mig->rbfv[1]->invec));
1308 if (t > full_dist-M_PI/GRIDRES) { /* near second DSF */
1309 n = sizeof(RBFNODE) + sizeof(RBFVAL)*(mig->rbfv[1]->nrbf-1);
1310 rbf = (RBFNODE *)malloc(n);
1311 if (rbf == NULL)
1312 goto memerr;
1313 memcpy(rbf, mig->rbfv[1], n); /* just duplicate */
1314 return(rbf);
1315 }
1316 t /= full_dist;
1317 n = 0; /* count migrating particles */
1318 for (i = 0; i < mtx_nrows(mig); i++)
1319 for (j = 0; j < mtx_ncols(mig); j++)
1320 n += (mig->mtx[mtx_ndx(mig,i,j)] > FTINY);
1321 #ifdef DEBUG
1322 fprintf(stderr, "Input RBFs have %d, %d nodes -> output has %d\n",
1323 mig->rbfv[0]->nrbf, mig->rbfv[1]->nrbf, n);
1324 #endif
1325 rbf = (RBFNODE *)malloc(sizeof(RBFNODE) + sizeof(RBFVAL)*(n-1));
1326 if (rbf == NULL)
1327 goto memerr;
1328 rbf->next = NULL; rbf->ejl = NULL;
1329 VCOPY(rbf->invec, invec);
1330 rbf->nrbf = n;
1331 rbf->vtotal = 1.-t + t*mig->rbfv[1]->vtotal/mig->rbfv[0]->vtotal;
1332 n = 0; /* advect RBF lobes */
1333 for (i = 0; i < mtx_nrows(mig); i++) {
1334 const RBFVAL *rbf0i = &mig->rbfv[0]->rbfa[i];
1335 const float peak0 = rbf0i->peak;
1336 const double rad0 = R2ANG(rbf0i->crad);
1337 FVECT v0;
1338 float mv;
1339 ovec_from_pos(v0, rbf0i->gx, rbf0i->gy);
1340 for (j = 0; j < mtx_ncols(mig); j++)
1341 if ((mv = mig->mtx[mtx_ndx(mig,i,j)]) > FTINY) {
1342 const RBFVAL *rbf1j = &mig->rbfv[1]->rbfa[j];
1343 double rad1 = R2ANG(rbf1j->crad);
1344 FVECT v;
1345 int pos[2];
1346 rbf->rbfa[n].peak = peak0 * mv * rbf->vtotal;
1347 rbf->rbfa[n].crad = ANG2R(sqrt(rad0*rad0*(1.-t) +
1348 rad1*rad1*t));
1349 ovec_from_pos(v, rbf1j->gx, rbf1j->gy);
1350 geodesic(v, v0, v, t, GEOD_REL);
1351 pos_from_vec(pos, v);
1352 rbf->rbfa[n].gx = pos[0];
1353 rbf->rbfa[n].gy = pos[1];
1354 ++n;
1355 }
1356 }
1357 rbf->vtotal *= mig->rbfv[0]->vtotal; /* turn ratio into actual */
1358 return(rbf);
1359 memerr:
1360 fputs("Out of memory in e_advect_rbf()\n", stderr);
1361 exit(1);
1362 return(NULL); /* pro forma return */
1363 }
1364
1365 /* Partially advect between recorded incident angles and allocate new RBF */
1366 static RBFNODE *
1367 advect_rbf(const FVECT invec)
1368 {
1369 MIGRATION *miga[3];
1370 RBFNODE *rbf;
1371 float mbfact, mcfact;
1372 int n, i, j, k;
1373 FVECT v0, v1, v2;
1374 double s, t;
1375
1376 if (!get_interp(miga, invec)) /* can't interpolate? */
1377 return(NULL);
1378 if (miga[1] == NULL) /* advect along edge? */
1379 return(e_advect_rbf(miga[0], invec));
1380 #ifdef DEBUG
1381 if (miga[0]->rbfv[0] != miga[2]->rbfv[0] |
1382 miga[0]->rbfv[1] != miga[1]->rbfv[0] |
1383 miga[1]->rbfv[1] != miga[2]->rbfv[1]) {
1384 fputs("Triangle vertex screw-up!\n", stderr);
1385 exit(1);
1386 }
1387 #endif
1388 /* figure out position */
1389 fcross(v0, miga[2]->rbfv[0]->invec, miga[2]->rbfv[1]->invec);
1390 normalize(v0);
1391 fcross(v2, miga[1]->rbfv[0]->invec, miga[1]->rbfv[1]->invec);
1392 normalize(v2);
1393 fcross(v1, invec, miga[1]->rbfv[1]->invec);
1394 normalize(v1);
1395 s = acos(DOT(v0,v1)) / acos(DOT(v0,v2));
1396 geodesic(v1, miga[0]->rbfv[0]->invec, miga[0]->rbfv[1]->invec,
1397 s, GEOD_REL);
1398 t = acos(DOT(v1,invec)) / acos(DOT(v1,miga[1]->rbfv[1]->invec));
1399 n = 0; /* count migrating particles */
1400 for (i = 0; i < mtx_nrows(miga[0]); i++)
1401 for (j = 0; j < mtx_ncols(miga[0]); j++)
1402 for (k = (miga[0]->mtx[mtx_ndx(miga[0],i,j)] > FTINY) *
1403 mtx_ncols(miga[2]); k--; )
1404 n += (miga[2]->mtx[mtx_ndx(miga[2],i,k)] > FTINY &&
1405 miga[1]->mtx[mtx_ndx(miga[1],j,k)] > FTINY);
1406 #ifdef DEBUG
1407 fprintf(stderr, "Input RBFs have %d, %d, %d nodes -> output has %d\n",
1408 miga[0]->rbfv[0]->nrbf, miga[0]->rbfv[1]->nrbf,
1409 miga[2]->rbfv[1]->nrbf, n);
1410 #endif
1411 rbf = (RBFNODE *)malloc(sizeof(RBFNODE) + sizeof(RBFVAL)*(n-1));
1412 if (rbf == NULL) {
1413 fputs("Out of memory in advect_rbf()\n", stderr);
1414 exit(1);
1415 }
1416 rbf->next = NULL; rbf->ejl = NULL;
1417 VCOPY(rbf->invec, invec);
1418 rbf->nrbf = n;
1419 n = 0; /* compute RBF lobes */
1420 mbfact = s * miga[0]->rbfv[1]->vtotal/miga[0]->rbfv[0]->vtotal *
1421 (1.-t + t*miga[1]->rbfv[1]->vtotal/miga[1]->rbfv[0]->vtotal);
1422 mcfact = (1.-s) *
1423 (1.-t + t*miga[2]->rbfv[1]->vtotal/miga[2]->rbfv[0]->vtotal);
1424 for (i = 0; i < mtx_nrows(miga[0]); i++) {
1425 const RBFVAL *rbf0i = &miga[0]->rbfv[0]->rbfa[i];
1426 const float w0i = rbf0i->peak;
1427 const double rad0i = R2ANG(rbf0i->crad);
1428 ovec_from_pos(v0, rbf0i->gx, rbf0i->gy);
1429 for (j = 0; j < mtx_ncols(miga[0]); j++) {
1430 const float ma = miga[0]->mtx[mtx_ndx(miga[0],i,j)];
1431 const RBFVAL *rbf1j;
1432 double rad1j, srad2;
1433 if (ma <= FTINY)
1434 continue;
1435 rbf1j = &miga[0]->rbfv[1]->rbfa[j];
1436 rad1j = R2ANG(rbf1j->crad);
1437 srad2 = (1.-s)*(1.-t)*rad0i*rad0i + s*(1.-t)*rad1j*rad1j;
1438 ovec_from_pos(v1, rbf1j->gx, rbf1j->gy);
1439 geodesic(v1, v0, v1, s, GEOD_REL);
1440 for (k = 0; k < mtx_ncols(miga[2]); k++) {
1441 float mb = miga[1]->mtx[mtx_ndx(miga[1],j,k)];
1442 float mc = miga[2]->mtx[mtx_ndx(miga[2],i,k)];
1443 const RBFVAL *rbf2k;
1444 double rad2k;
1445 FVECT vout;
1446 int pos[2];
1447 if ((mb <= FTINY) | (mc <= FTINY))
1448 continue;
1449 rbf2k = &miga[2]->rbfv[1]->rbfa[k];
1450 rbf->rbfa[n].peak = w0i * ma * (mb*mbfact + mc*mcfact);
1451 rad2k = R2ANG(rbf2k->crad);
1452 rbf->rbfa[n].crad = ANG2R(sqrt(srad2 + t*rad2k*rad2k));
1453 ovec_from_pos(v2, rbf2k->gx, rbf2k->gy);
1454 geodesic(vout, v1, v2, t, GEOD_REL);
1455 pos_from_vec(pos, vout);
1456 rbf->rbfa[n].gx = pos[0];
1457 rbf->rbfa[n].gy = pos[1];
1458 ++n;
1459 }
1460 }
1461 }
1462 rbf->vtotal = miga[0]->rbfv[0]->vtotal * (mbfact + mcfact);
1463 return(rbf);
1464 }
1465
1466 /* Interpolate and output isotropic BSDF data */
1467 static void
1468 interp_isotropic()
1469 {
1470 const int sqres = 1<<samp_order;
1471 FILE *ofp = NULL;
1472 char cmd[128];
1473 int ix, ox, oy;
1474 FVECT ivec, ovec;
1475 double bsdf;
1476 #if DEBUG
1477 fprintf(stderr, "Writing isotropic order %d ", samp_order);
1478 if (pctcull >= 0) fprintf(stderr, "data with %d%% culling\n", pctcull);
1479 else fputs("raw data\n", stderr);
1480 #endif
1481 if (pctcull >= 0) { /* begin output */
1482 sprintf(cmd, "rttree_reduce -h -a -fd -r 3 -t %d -g %d",
1483 pctcull, samp_order);
1484 fflush(stdout);
1485 ofp = popen(cmd, "w");
1486 if (ofp == NULL) {
1487 fprintf(stderr, "%s: cannot create pipe to rttree_reduce\n",
1488 progname);
1489 exit(1);
1490 }
1491 } else
1492 fputs("{\n", stdout);
1493 /* run through directions */
1494 for (ix = 0; ix < sqres/2; ix++) {
1495 RBFNODE *rbf;
1496 SDsquare2disk(ivec, (ix+.5)/sqres, .5);
1497 ivec[2] = input_orient *
1498 sqrt(1. - ivec[0]*ivec[0] - ivec[1]*ivec[1]);
1499 rbf = advect_rbf(ivec);
1500 for (ox = 0; ox < sqres; ox++)
1501 for (oy = 0; oy < sqres; oy++) {
1502 SDsquare2disk(ovec, (ox+.5)/sqres, (oy+.5)/sqres);
1503 ovec[2] = output_orient *
1504 sqrt(1. - ovec[0]*ovec[0] - ovec[1]*ovec[1]);
1505 bsdf = eval_rbfrep(rbf, ovec) / fabs(ovec[2]);
1506 if (pctcull >= 0)
1507 fwrite(&bsdf, sizeof(bsdf), 1, ofp);
1508 else
1509 printf("\t%.3e\n", bsdf);
1510 }
1511 free(rbf);
1512 }
1513 if (pctcull >= 0) { /* finish output */
1514 if (pclose(ofp)) {
1515 fprintf(stderr, "%s: error running '%s'\n",
1516 progname, cmd);
1517 exit(1);
1518 }
1519 } else {
1520 for (ix = sqres*sqres*sqres/2; ix--; )
1521 fputs("\t0\n", stdout);
1522 fputs("}\n", stdout);
1523 }
1524 }
1525
1526 /* Interpolate and output anisotropic BSDF data */
1527 static void
1528 interp_anisotropic()
1529 {
1530 const int sqres = 1<<samp_order;
1531 FILE *ofp = NULL;
1532 char cmd[128];
1533 int ix, iy, ox, oy;
1534 FVECT ivec, ovec;
1535 double bsdf;
1536 #if DEBUG
1537 fprintf(stderr, "Writing anisotropic order %d ", samp_order);
1538 if (pctcull >= 0) fprintf(stderr, "data with %d%% culling\n", pctcull);
1539 else fputs("raw data\n", stderr);
1540 #endif
1541 if (pctcull >= 0) { /* begin output */
1542 sprintf(cmd, "rttree_reduce -h -a -fd -r 4 -t %d -g %d",
1543 pctcull, samp_order);
1544 fflush(stdout);
1545 ofp = popen(cmd, "w");
1546 if (ofp == NULL) {
1547 fprintf(stderr, "%s: cannot create pipe to rttree_reduce\n",
1548 progname);
1549 exit(1);
1550 }
1551 } else
1552 fputs("{\n", stdout);
1553 /* run through directions */
1554 for (ix = 0; ix < sqres; ix++)
1555 for (iy = 0; iy < sqres; iy++) {
1556 RBFNODE *rbf;
1557 SDsquare2disk(ivec, (ix+.5)/sqres, (iy+.5)/sqres);
1558 ivec[2] = input_orient *
1559 sqrt(1. - ivec[0]*ivec[0] - ivec[1]*ivec[1]);
1560 rbf = advect_rbf(ivec);
1561 for (ox = 0; ox < sqres; ox++)
1562 for (oy = 0; oy < sqres; oy++) {
1563 SDsquare2disk(ovec, (ox+.5)/sqres, (oy+.5)/sqres);
1564 ovec[2] = output_orient *
1565 sqrt(1. - ovec[0]*ovec[0] - ovec[1]*ovec[1]);
1566 bsdf = eval_rbfrep(rbf, ovec) / fabs(ovec[2]);
1567 if (pctcull >= 0)
1568 fwrite(&bsdf, sizeof(bsdf), 1, ofp);
1569 else
1570 printf("\t%.3e\n", bsdf);
1571 }
1572 free(rbf);
1573 }
1574 if (pctcull >= 0) { /* finish output */
1575 if (pclose(ofp)) {
1576 fprintf(stderr, "%s: error running '%s'\n",
1577 progname, cmd);
1578 exit(1);
1579 }
1580 } else
1581 fputs("}\n", stdout);
1582 }
1583
1584 #if 1
1585 /* Read in BSDF files and interpolate as tensor tree representation */
1586 int
1587 main(int argc, char *argv[])
1588 {
1589 RBFNODE *rbf;
1590 double bsdf;
1591 int i;
1592
1593 progname = argv[0]; /* get options */
1594 while (argc > 2 && argv[1][0] == '-') {
1595 switch (argv[1][1]) {
1596 case 'n':
1597 nprocs = atoi(argv[2]);
1598 break;
1599 case 't':
1600 pctcull = atoi(argv[2]);
1601 break;
1602 default:
1603 goto userr;
1604 }
1605 argv += 2; argc -= 2;
1606 }
1607 if (argc < 3)
1608 goto userr;
1609 #ifdef _WIN32
1610 if (nprocs > 1) {
1611 fprintf(stderr, "%s: multiprocessing not supported\n",
1612 progname);
1613 return(1);
1614 }
1615 #endif
1616 for (i = 1; i < argc; i++) { /* compile measurements */
1617 if (!load_pabopto_meas(argv[i]))
1618 return(1);
1619 compute_radii();
1620 cull_values();
1621 make_rbfrep();
1622 }
1623 build_mesh(); /* create interpolation */
1624 /* xml_prologue(); /* start XML output */
1625 if (single_plane_incident) /* resample dist. */
1626 interp_isotropic();
1627 else
1628 interp_anisotropic();
1629 /* xml_epilogue(); /* finish XML output */
1630 return(0);
1631 userr:
1632 fprintf(stderr,
1633 "Usage: %s [-n nprocs][-t pctcull] meas1.dat meas2.dat .. > bsdf.xml\n",
1634 progname);
1635 return(1);
1636 }
1637 #else
1638 /* Test main produces a Radiance model from the given input file */
1639 int
1640 main(int argc, char *argv[])
1641 {
1642 char buf[128];
1643 FILE *pfp;
1644 double bsdf;
1645 FVECT dir;
1646 int i, j, n;
1647
1648 if (argc != 2) {
1649 fprintf(stderr, "Usage: %s input.dat > output.rad\n", argv[0]);
1650 return(1);
1651 }
1652 if (!load_pabopto_meas(argv[1]))
1653 return(1);
1654
1655 compute_radii();
1656 cull_values();
1657 make_rbfrep();
1658 /* produce spheres at meas. */
1659 puts("void plastic yellow\n0\n0\n5 .6 .4 .01 .04 .08\n");
1660 puts("void plastic pink\n0\n0\n5 .5 .05 .9 .04 .08\n");
1661 n = 0;
1662 for (i = 0; i < GRIDRES; i++)
1663 for (j = 0; j < GRIDRES; j++)
1664 if (dsf_grid[i][j].vsum > .0f) {
1665 ovec_from_pos(dir, i, j);
1666 bsdf = dsf_grid[i][j].vsum / dir[2];
1667 if (dsf_grid[i][j].nval) {
1668 printf("pink cone c%04d\n0\n0\n8\n", ++n);
1669 printf("\t%.6g %.6g %.6g\n",
1670 dir[0]*bsdf, dir[1]*bsdf, dir[2]*bsdf);
1671 printf("\t%.6g %.6g %.6g\n",
1672 dir[0]*(bsdf+.005), dir[1]*(bsdf+.005),
1673 dir[2]*(bsdf+.005));
1674 puts("\t.003\t0\n");
1675 } else {
1676 ovec_from_pos(dir, i, j);
1677 printf("yellow sphere s%04d\n0\n0\n", ++n);
1678 printf("4 %.6g %.6g %.6g .0015\n\n",
1679 dir[0]*bsdf, dir[1]*bsdf, dir[2]*bsdf);
1680 }
1681 }
1682 /* output continuous surface */
1683 puts("void trans tgreen\n0\n0\n7 .7 1 .7 .04 .04 .9 .9\n");
1684 fflush(stdout);
1685 sprintf(buf, "gensurf tgreen bsdf - - - %d %d", GRIDRES-1, GRIDRES-1);
1686 pfp = popen(buf, "w");
1687 if (pfp == NULL) {
1688 fputs(buf, stderr);
1689 fputs(": cannot start command\n", stderr);
1690 return(1);
1691 }
1692 for (i = 0; i < GRIDRES; i++)
1693 for (j = 0; j < GRIDRES; j++) {
1694 ovec_from_pos(dir, i, j);
1695 bsdf = eval_rbfrep(dsf_list, dir) / dir[2];
1696 fprintf(pfp, "%.8e %.8e %.8e\n",
1697 dir[0]*bsdf, dir[1]*bsdf, dir[2]*bsdf);
1698 }
1699 return(pclose(pfp)==0 ? 0 : 1);
1700 }
1701 #endif