ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/bsdfmesh.c
(Generate patch)

Comparing ray/src/cv/bsdfmesh.c (file contents):
Revision 2.1 by greg, Fri Oct 19 04:14:29 2012 UTC vs.
Revision 2.29 by greg, Thu Mar 27 03:49:14 2014 UTC

# Line 18 | Line 18 | static const char RCSid[] = "$Id$";
18   #include <string.h>
19   #include <math.h>
20   #include "bsdfrep.h"
21 +
22 + #ifndef NEIGH_FACT2
23 + #define NEIGH_FACT2     0.1     /* empirical neighborhood distance weight */
24 + #endif
25                                  /* number of processes to run */
26   int                     nprocs = 1;
27                                  /* number of children (-1 in child) */
28   static int              nchild = 0;
29  
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
30   /* Create a new migration holder (sharing memory for multiprocessing) */
31   static MIGRATION *
32   new_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
# Line 272 | Line 114 | run_subprocess(void)
114                  if (pid < 0) {
115                          fprintf(stderr, "%s: cannot fork subprocess\n",
116                                          progname);
117 +                        await_children(nchild);
118                          exit(1);
119                  }
120                  ++nchild;                       /* subprocess started */
# Line 286 | Line 129 | run_subprocess(void)
129  
130   #endif  /* ! _WIN32 */
131  
132 + /* Compute normalized distribution scattering functions for comparison */
133 + static void
134 + compute_nDSFs(const RBFNODE *rbf0, const RBFNODE *rbf1)
135 + {
136 +        const double    nf0 = (GRIDRES*GRIDRES) / rbf0->vtotal;
137 +        const double    nf1 = (GRIDRES*GRIDRES) / rbf1->vtotal;
138 +        int             x, y;
139 +        FVECT           dv;
140 +
141 +        for (x = GRIDRES; x--; )
142 +            for (y = GRIDRES; y--; ) {
143 +                ovec_from_pos(dv, x, y);        /* cube root (brightness) */
144 +                dsf_grid[x][y].val[0] = pow(nf0*eval_rbfrep(rbf0, dv), .3333);
145 +                dsf_grid[x][y].val[1] = pow(nf1*eval_rbfrep(rbf1, dv), .3333);
146 +            }
147 + }      
148 +
149 + /* Compute neighborhood distance-squared (dissimilarity) */
150 + static double
151 + neighborhood_dist2(int x0, int y0, int x1, int y1)
152 + {
153 +        int     rad = GRIDRES>>5;
154 +        double  sum2 = 0.;
155 +        double  d;
156 +        int     p[4];
157 +        int     i, j;
158 +                                                /* check radius */
159 +        p[0] = x0; p[1] = y0; p[2] = x1; p[3] = y1;
160 +        for (i = 4; i--; ) {
161 +                if (p[i] < rad) rad = p[i];
162 +                if (GRIDRES-1-p[i] < rad) rad = GRIDRES-1-p[i];
163 +        }
164 +        for (i = -rad; i <= rad; i++)
165 +            for (j = -rad; j <= rad; j++) {
166 +                d = dsf_grid[x0+i][y0+j].val[0] -
167 +                        dsf_grid[x1+i][y1+j].val[1];
168 +                sum2 += d*d;
169 +            }
170 +        return(sum2 / (4*rad*(rad+1) + 1));
171 + }
172 +
173 + /* Compute distance between two RBF lobes */
174 + double
175 + lobe_distance(RBFVAL *rbf1, RBFVAL *rbf2)
176 + {
177 +        FVECT   vfrom, vto;
178 +        double  d, res;
179 +                                        /* quadratic cost function */
180 +        ovec_from_pos(vfrom, rbf1->gx, rbf1->gy);
181 +        ovec_from_pos(vto, rbf2->gx, rbf2->gy);
182 +        d = Acos(DOT(vfrom, vto));
183 +        res = d*d;
184 +        d = R2ANG(rbf2->crad) - R2ANG(rbf1->crad);
185 +        res += d*d;
186 +                                        /* neighborhood difference */
187 +        res += NEIGH_FACT2 * neighborhood_dist2( rbf1->gx, rbf1->gy,
188 +                                                rbf2->gx, rbf2->gy );
189 +        return(res);
190 + }
191 +
192 +
193   /* Compute and insert migration along directed edge (may fork child) */
194   static MIGRATION *
195   create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
196   {
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;
197          MIGRATION       *newmig;
198 <        double          *src_rem, *dst_rem;
299 <        double          total_rem = 1., move_amt;
300 <        int             i;
198 >        int             i, j;
199                                                  /* check if exists already */
200          for (newmig = from_rbf->ejl; newmig != NULL;
201                          newmig = nextedge(from_rbf,newmig))
202                  if (newmig->rbfv[1] == to_rbf)
203                          return(NULL);
204                                                  /* else allocate */
205 + #ifdef DEBUG
206 +        fprintf(stderr, "Building path from (theta,phi) (%.1f,%.1f) ",
207 +                        get_theta180(from_rbf->invec),
208 +                        get_phi360(from_rbf->invec));
209 +        fprintf(stderr, "to (%.1f,%.1f) with %d x %d matrix\n",
210 +                        get_theta180(to_rbf->invec),
211 +                        get_phi360(to_rbf->invec),
212 +                        from_rbf->nrbf, to_rbf->nrbf);
213 + #endif
214          newmig = new_migration(from_rbf, to_rbf);
215          if (run_subprocess())
216                  return(newmig);                 /* child continues */
217 <        pmtx = price_routes(from_rbf, to_rbf);
218 <        src_rem = (double *)malloc(sizeof(double)*from_rbf->nrbf);
219 <        dst_rem = (double *)malloc(sizeof(double)*to_rbf->nrbf);
220 <        if ((src_rem == NULL) | (dst_rem == NULL)) {
221 <                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
217 >
218 >                                                /* compute transport plan */
219 >        compute_nDSFs(from_rbf, to_rbf);
220 >        plan_transport(newmig);
221 >
222          for (i = from_rbf->nrbf; i--; ) {       /* normalize final matrix */
223 <            float       nf = rbf_volume(&from_rbf->rbfa[i]);
346 <            int         j;
223 >            double      nf = rbf_volume(&from_rbf->rbfa[i]);
224              if (nf <= FTINY) continue;
225              nf = from_rbf->vtotal / nf;
226              for (j = to_rbf->nrbf; j--; )
227 <                newmig->mtx[mtx_ndx(newmig,i,j)] *= nf;
227 >                mtx_coef(newmig,i,j) *= nf;     /* row now sums to 1.0 */
228          }
229          end_subprocess();                       /* exit here if subprocess */
353        free(pmtx);                             /* free working arrays */
354        free(src_rem);
355        free(dst_rem);
230          return(newmig);
231   }
232  
# Line 382 | Line 256 | overlaps_tri(const RBFNODE *bv0, const RBFNODE *bv1, c
256          return(vother[im_rev] != NULL);
257   }
258  
259 < /* Find context hull vertex to complete triangle (oriented call) */
259 > /* Find convex hull vertex to complete triangle (oriented call) */
260   static RBFNODE *
261   find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rbf1)
262   {
# Line 403 | Line 277 | find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rb
277                  if (DOT(vp, vmid) <= FTINY)
278                          continue;               /* wrong orientation */
279                  area2 = .25*DOT(vp,vp);
280 <                VSUB(vp, rbf->invec, rbf0->invec);
280 >                VSUB(vp, rbf->invec, vmid);
281                  dprod = -DOT(vp, vejn);
282                  VSUM(vp, vp, vejn, dprod);      /* above guarantees non-zero */
283                  dprod = DOT(vp, vmid) / VLEN(vp);
# Line 442 | Line 316 | mesh_from_edge(MIGRATION *edge)
316                                  ej1 = create_migration(tvert[0], edge->rbfv[1]);
317                          mesh_from_edge(ej0);
318                          mesh_from_edge(ej1);
319 +                        return;
320                  }
321 <        } else if (tvert[1] == NULL) {          /* grow mesh on left */
321 >        }
322 >        if (tvert[1] == NULL) {                 /* grow mesh on left */
323                  tvert[1] = find_chull_vert(edge->rbfv[1], edge->rbfv[0]);
324                  if (tvert[1] != NULL) {
325                          if (tvert[1]->ord > edge->rbfv[0]->ord)
# Line 459 | Line 335 | mesh_from_edge(MIGRATION *edge)
335                  }
336          }
337   }
338 +
339 + /* Add normal direction if missing */
340 + static void
341 + check_normal_incidence(void)
342 + {
343 +        static FVECT            norm_vec = {.0, .0, 1.};
344 +        const int               saved_nprocs = nprocs;
345 +        RBFNODE                 *near_rbf, *mir_rbf, *rbf;
346 +        double                  bestd;
347 +        int                     n;
348 +
349 +        if (dsf_list == NULL)
350 +                return;                         /* XXX should be error? */
351 +        near_rbf = dsf_list;
352 +        bestd = input_orient*near_rbf->invec[2];
353 +        if (single_plane_incident) {            /* ordered plane incidence? */
354 +                if (bestd >= 1.-2.*FTINY)
355 +                        return;                 /* already have normal */
356 +        } else {
357 +                switch (inp_coverage) {
358 +                case INP_QUAD1:
359 +                case INP_QUAD2:
360 +                case INP_QUAD3:
361 +                case INP_QUAD4:
362 +                        break;                  /* quadrilateral symmetry? */
363 +                default:
364 +                        return;                 /* else we can interpolate */
365 +                }
366 +                for (rbf = near_rbf->next; rbf != NULL; rbf = rbf->next) {
367 +                        const double    d = input_orient*rbf->invec[2];
368 +                        if (d >= 1.-2.*FTINY)
369 +                                return;         /* seems we have normal */
370 +                        if (d > bestd) {
371 +                                near_rbf = rbf;
372 +                                bestd = d;
373 +                        }
374 +                }
375 +        }
376 +        if (mig_list != NULL) {                 /* need to be called first */
377 +                fprintf(stderr, "%s: Late call to check_normal_incidence()\n",
378 +                                progname);
379 +                exit(1);
380 +        }
381 + #ifdef DEBUG
382 +        fprintf(stderr, "Interpolating normal incidence by mirroring (%.1f,%.1f)\n",
383 +                        get_theta180(near_rbf->invec), get_phi360(near_rbf->invec));
384 + #endif
385 +                                                /* mirror nearest incidence */
386 +        n = sizeof(RBFNODE) + sizeof(RBFVAL)*(near_rbf->nrbf-1);
387 +        mir_rbf = (RBFNODE *)malloc(n);
388 +        if (mir_rbf == NULL)
389 +                goto memerr;
390 +        memcpy(mir_rbf, near_rbf, n);
391 +        mir_rbf->ord = near_rbf->ord - 1;       /* not used, I think */
392 +        mir_rbf->next = NULL;
393 +        mir_rbf->ejl = NULL;
394 +        rev_rbf_symmetry(mir_rbf, MIRROR_X|MIRROR_Y);
395 +        nprocs = 1;                             /* compute migration matrix */
396 +        if (create_migration(mir_rbf, near_rbf) == NULL)
397 +                exit(1);                        /* XXX should never happen! */
398 +        norm_vec[2] = input_orient;             /* interpolate normal dist. */
399 +        rbf = e_advect_rbf(mig_list, norm_vec, 0);
400 +        nprocs = saved_nprocs;                  /* final clean-up */
401 +        free(mir_rbf);
402 +        free(mig_list);
403 +        mig_list = near_rbf->ejl = NULL;
404 +        insert_dsf(rbf);                        /* insert interpolated normal */
405 +        return;
406 + memerr:
407 +        fprintf(stderr, "%s: Out of memory in check_normal_incidence()\n",
408 +                                progname);
409 +        exit(1);
410 + }
411          
412   /* Build our triangle mesh from recorded RBFs */
413   void
# Line 467 | Line 416 | build_mesh(void)
416          double          best2 = M_PI*M_PI;
417          RBFNODE         *shrt_edj[2];
418          RBFNODE         *rbf0, *rbf1;
419 +                                                /* add normal if needed */
420 +        check_normal_incidence();
421                                                  /* check if isotropic */
422          if (single_plane_incident) {
423                  for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines