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

Comparing ray/src/cv/bsdfrbf.c (file contents):
Revision 2.7 by greg, Wed Sep 25 17:42:45 2013 UTC vs.
Revision 2.18 by greg, Tue Feb 18 16:42:16 2014 UTC

# Line 7 | Line 7 | static const char RCSid[] = "$Id$";
7   *      G. Ward
8   */
9  
10 + /****************************************************************
11 + 1) Collect samples into a grid using the Shirley-Chiu
12 +        angular mapping from a hemisphere to a square.
13 +
14 + 2) Compute an adaptive quadtree by subdividing the grid so that
15 +        each leaf node has at least one sample up to as many
16 +        samples as fit nicely on a plane to within a certain
17 +        MSE tolerance.
18 +
19 + 3) Place one Gaussian lobe at each leaf node in the quadtree,
20 +        sizing it to have a radius equal to the leaf size and
21 +        a volume equal to the energy in that node.
22 + *****************************************************************/
23 +
24   #define _USE_MATH_DEFINES
25   #include <stdio.h>
26   #include <stdlib.h>
# Line 15 | Line 29 | static const char RCSid[] = "$Id$";
29   #include "bsdfrep.h"
30  
31   #ifndef RSCA
32 < #define RSCA            2.7             /* radius scaling factor (empirical) */
32 > #define RSCA            2.2             /* radius scaling factor (empirical) */
33   #endif
34 < #ifndef MAXFRAC
35 < #define MAXFRAC         0.5             /* maximum contribution to neighbor */
34 > #ifndef SMOOTH_MSE
35 > #define SMOOTH_MSE      2e-5            /* acceptable mean squared error */
36   #endif
37 < #ifndef NNEIGH
38 < #define NNEIGH          10              /* number of neighbors to consider */
37 > #ifndef SMOOTH_MSER
38 > #define SMOOTH_MSER     0.03            /* acceptable relative MSE */
39   #endif
40 + #define MAX_RAD         (GRIDRES/8)     /* maximum lobe radius */
41 +
42 + #define RBFALLOCB       10              /* RBF allocation block size */
43 +
44                                  /* our loaded grid for this incident angle */
45   GRIDVAL                 dsf_grid[GRIDRES][GRIDRES];
46  
# Line 54 | Line 72 | add_bsdf_data(double theta_out, double phi_out, double
72          ovec[1] = sin((M_PI/180.)*phi_out) * ovec[2];
73          ovec[2] = sqrt(1. - ovec[2]*ovec[2]);
74  
75 <        if (!isDSF)
75 >        if (val <= 0)                   /* truncate to zero */
76 >                val = 0;
77 >        else if (!isDSF)
78                  val *= ovec[2];         /* convert from BSDF to DSF */
79  
80                                          /* update BSDF histogram */
# Line 67 | Line 87 | add_bsdf_data(double theta_out, double phi_out, double
87          dsf_grid[pos[0]][pos[1]].nval++;
88   }
89  
90 < /* Compute radii for non-empty bins */
71 < /* (distance to furthest empty bin for which non-empty bin is the closest) */
90 > /* Compute minimum BSDF from histogram (does not clear) */
91   static void
73 compute_radii(void)
74 {
75        unsigned int    fill_grid[GRIDRES][GRIDRES];
76        unsigned short  fill_cnt[GRIDRES][GRIDRES];
77        FVECT           ovec0, ovec1;
78        double          ang2, lastang2;
79        int             r, i, j, jn, ii, jj, inear, jnear;
80
81        r = GRIDRES/2;                          /* proceed in zig-zag */
82        for (i = 0; i < GRIDRES; i++)
83            for (jn = 0; jn < GRIDRES; jn++) {
84                j = (i&1) ? jn : GRIDRES-1-jn;
85                if (dsf_grid[i][j].nval)        /* find empty grid pos. */
86                        continue;
87                ovec_from_pos(ovec0, i, j);
88                inear = jnear = -1;             /* find nearest non-empty */
89                lastang2 = M_PI*M_PI;
90                for (ii = i-r; ii <= i+r; ii++) {
91                    if (ii < 0) continue;
92                    if (ii >= GRIDRES) break;
93                    for (jj = j-r; jj <= j+r; jj++) {
94                        if (jj < 0) continue;
95                        if (jj >= GRIDRES) break;
96                        if (!dsf_grid[ii][jj].nval)
97                                continue;
98                        ovec_from_pos(ovec1, ii, jj);
99                        ang2 = 2. - 2.*DOT(ovec0,ovec1);
100                        if (ang2 >= lastang2)
101                                continue;
102                        lastang2 = ang2;
103                        inear = ii; jnear = jj;
104                    }
105                }
106                if (inear < 0) {
107                        fprintf(stderr,
108                                "%s: Could not find non-empty neighbor!\n",
109                                        progname);
110                        exit(1);
111                }
112                ang2 = sqrt(lastang2);
113                r = ANG2R(ang2);                /* record if > previous */
114                if (r > dsf_grid[inear][jnear].crad)
115                        dsf_grid[inear][jnear].crad = r;
116                                                /* next search radius */
117                r = ang2*(2.*GRIDRES/M_PI) + 3;
118            }
119                                                /* blur radii over hemisphere */
120        memset(fill_grid, 0, sizeof(fill_grid));
121        memset(fill_cnt, 0, sizeof(fill_cnt));
122        for (i = 0; i < GRIDRES; i++)
123            for (j = 0; j < GRIDRES; j++) {
124                if (!dsf_grid[i][j].crad)
125                        continue;               /* missing distance */
126                r = R2ANG(dsf_grid[i][j].crad)*(2.*RSCA*GRIDRES/M_PI);
127                for (ii = i-r; ii <= i+r; ii++) {
128                    if (ii < 0) continue;
129                    if (ii >= GRIDRES) break;
130                    for (jj = j-r; jj <= j+r; jj++) {
131                        if (jj < 0) continue;
132                        if (jj >= GRIDRES) break;
133                        if ((ii-i)*(ii-i) + (jj-j)*(jj-j) > r*r)
134                                continue;
135                        fill_grid[ii][jj] += dsf_grid[i][j].crad;
136                        fill_cnt[ii][jj]++;
137                    }
138                }
139            }
140                                                /* copy back blurred radii */
141        for (i = 0; i < GRIDRES; i++)
142            for (j = 0; j < GRIDRES; j++)
143                if (fill_cnt[i][j])
144                        dsf_grid[i][j].crad = fill_grid[i][j]/fill_cnt[i][j];
145 }
146
147 /* Cull points for more uniform distribution, leave all nval 0 or 1 */
148 static void
149 cull_values(void)
150 {
151        FVECT   ovec0, ovec1;
152        double  maxang, maxang2;
153        int     i, j, ii, jj, r;
154                                                /* simple greedy algorithm */
155        for (i = 0; i < GRIDRES; i++)
156            for (j = 0; j < GRIDRES; j++) {
157                if (!dsf_grid[i][j].nval)
158                        continue;
159                if (!dsf_grid[i][j].crad)
160                        continue;               /* shouldn't happen */
161                ovec_from_pos(ovec0, i, j);
162                maxang = 2.*R2ANG(dsf_grid[i][j].crad);
163                if (maxang > ovec0[2])          /* clamp near horizon */
164                        maxang = ovec0[2];
165                r = maxang*(2.*GRIDRES/M_PI) + 1;
166                maxang2 = maxang*maxang;
167                for (ii = i-r; ii <= i+r; ii++) {
168                    if (ii < 0) continue;
169                    if (ii >= GRIDRES) break;
170                    for (jj = j-r; jj <= j+r; jj++) {
171                        if (jj < 0) continue;
172                        if (jj >= GRIDRES) break;
173                        if (!dsf_grid[ii][jj].nval)
174                                continue;
175                        if ((ii == i) & (jj == j))
176                                continue;       /* don't get self-absorbed */
177                        ovec_from_pos(ovec1, ii, jj);
178                        if (2. - 2.*DOT(ovec0,ovec1) >= maxang2)
179                                continue;
180                                                /* absorb sum */
181                        dsf_grid[i][j].vsum += dsf_grid[ii][jj].vsum;
182                        dsf_grid[i][j].nval += dsf_grid[ii][jj].nval;
183                                                /* keep value, though */
184                        dsf_grid[ii][jj].vsum /= (float)dsf_grid[ii][jj].nval;
185                        dsf_grid[ii][jj].nval = 0;
186                    }
187                }
188            }
189                                                /* final averaging pass */
190        for (i = 0; i < GRIDRES; i++)
191            for (j = 0; j < GRIDRES; j++)
192                if (dsf_grid[i][j].nval > 1) {
193                        dsf_grid[i][j].vsum /= (float)dsf_grid[i][j].nval;
194                        dsf_grid[i][j].nval = 1;
195                }
196 }
197
198 /* Compute minimum BSDF from histogram and clear it */
199 static void
92   comp_bsdf_min()
93   {
94 <        int     cnt;
95 <        int     i, target;
94 >        unsigned long   cnt, target;
95 >        int             i;
96  
97          cnt = 0;
98          for (i = HISTLEN; i--; )
# Line 214 | Line 106 | comp_bsdf_min()
106          for (i = 0; cnt <= target; i++)
107                  cnt += bsdf_hist[i];
108          bsdf_min = histval(i-1);
217        memset(bsdf_hist, 0, sizeof(bsdf_hist));
109   }
110  
111 < /* Find n nearest sub-sampled neighbors to the given grid position */
111 > /* Determine if the given region is empty of grid samples */
112   static int
113 < get_neighbors(int neigh[][2], int n, const int i, const int j)
113 > empty_region(int x0, int x1, int y0, int y1)
114   {
115 <        int     k = 0;
116 <        int     r;
117 <                                                /* search concentric squares */
118 <        for (r = 1; r < GRIDRES; r++) {
119 <                int     ii, jj;
120 <                for (ii = i-r; ii <= i+r; ii++) {
121 <                        int     jstep = 1;
122 <                        if (ii < 0) continue;
123 <                        if (ii >= GRIDRES) break;
124 <                        if ((i-r < ii) & (ii < i+r))
125 <                                jstep = r<<1;
126 <                        for (jj = j-r; jj <= j+r; jj += jstep) {
127 <                                if (jj < 0) continue;
128 <                                if (jj >= GRIDRES) break;
129 <                                if (dsf_grid[ii][jj].nval) {
130 <                                        neigh[k][0] = ii;
131 <                                        neigh[k][1] = jj;
132 <                                        if (++k >= n)
133 <                                                return(n);
134 <                                }
135 <                        }
115 >        int     x, y;
116 >
117 >        for (x = x0; x < x1; x++)
118 >            for (y = y0; y < y1; y++)
119 >                if (dsf_grid[x][y].nval)
120 >                        return(0);
121 >        return(1);
122 > }
123 >
124 > /* Determine if the given region is smooth enough to be a single lobe */
125 > static int
126 > smooth_region(int x0, int x1, int y0, int y1)
127 > {
128 >        RREAL   rMtx[3][3];
129 >        FVECT   xvec;
130 >        double  A, B, C, nvs, sqerr;
131 >        int     x, y, n;
132 >                                        /* compute planar regression */
133 >        memset(rMtx, 0, sizeof(rMtx));
134 >        memset(xvec, 0, sizeof(xvec));
135 >        for (x = x0; x < x1; x++)
136 >            for (y = y0; y < y1; y++)
137 >                if ((n = dsf_grid[x][y].nval) > 0) {
138 >                        double  z = dsf_grid[x][y].vsum;
139 >                        rMtx[0][0] += x*x*(double)n;
140 >                        rMtx[0][1] += x*y*(double)n;
141 >                        rMtx[0][2] += x*(double)n;
142 >                        rMtx[1][1] += y*y*(double)n;
143 >                        rMtx[1][2] += y*(double)n;
144 >                        rMtx[2][2] += (double)n;
145 >                        xvec[0] += x*z;
146 >                        xvec[1] += y*z;
147 >                        xvec[2] += z;
148                  }
149 +        rMtx[1][0] = rMtx[0][1];
150 +        rMtx[2][0] = rMtx[0][2];
151 +        rMtx[2][1] = rMtx[1][2];
152 +        nvs = rMtx[2][2];
153 +        if (SDinvXform(rMtx, rMtx) != SDEnone)
154 +                return(1);              /* colinear values */
155 +        A = DOT(rMtx[0], xvec);
156 +        B = DOT(rMtx[1], xvec);
157 +        C = DOT(rMtx[2], xvec);
158 +        sqerr = 0.0;                    /* compute mean squared error */
159 +        for (x = x0; x < x1; x++)
160 +            for (y = y0; y < y1; y++)
161 +                if ((n = dsf_grid[x][y].nval) > 0) {
162 +                        double  d = A*x + B*y + C - dsf_grid[x][y].vsum/n;
163 +                        sqerr += n*d*d;
164 +                }
165 +        if (sqerr <= nvs*SMOOTH_MSE)    /* below absolute MSE threshold? */
166 +                return(1);
167 +                                        /* OR below relative MSE threshold? */
168 +        return(sqerr*nvs <= xvec[2]*xvec[2]*SMOOTH_MSER);
169 + }
170 +
171 + /* Create new lobe based on integrated samples in region */
172 + static void
173 + create_lobe(RBFVAL *rvp, int x0, int x1, int y0, int y1)
174 + {
175 +        double  vtot = 0.0;
176 +        int     nv = 0;
177 +        double  rad;
178 +        int     x, y;
179 +                                        /* compute average for region */
180 +        for (x = x0; x < x1; x++)
181 +            for (y = y0; y < y1; y++) {
182 +                vtot += dsf_grid[x][y].vsum;
183 +                nv += dsf_grid[x][y].nval;
184 +            }
185 +        if (!nv) {
186 +                fprintf(stderr, "%s: internal - missing samples in create_lobe\n",
187 +                                progname);
188 +                exit(1);
189          }
190 <        return(k);
190 >                                        /* peak value based on integral */
191 >        vtot *= (x1-x0)*(y1-y0)*(2.*M_PI/GRIDRES/GRIDRES)/(double)nv;
192 >        rad = (RSCA/(double)GRIDRES)*(x1-x0);
193 >        rvp->peak =  vtot / ((2.*M_PI) * rad*rad);
194 >        rvp->crad = ANG2R(rad);
195 >        rvp->gx = (x0+x1)>>1;
196 >        rvp->gy = (y0+y1)>>1;
197   }
198  
199 < /* Adjust coded radius for the given grid position based on neighborhood */
199 > /* Recursive function to build radial basis function representation */
200   static int
201 < adj_coded_radius(const int i, const int j)
201 > build_rbfrep(RBFVAL **arp, int *np, int x0, int x1, int y0, int y1)
202   {
203 <        const double    rad0 = R2ANG(dsf_grid[i][j].crad);
204 <        double          currad = RSCA * rad0;
205 <        int             neigh[NNEIGH][2];
206 <        int             n;
207 <        FVECT           our_dir;
208 <
209 <        ovec_from_pos(our_dir, i, j);
210 <        n = get_neighbors(neigh, NNEIGH, i, j);
211 <        while (n--) {
212 <                FVECT   their_dir;
213 <                double  max_ratio, rad_ok2;
214 <                                                /* check our value at neighbor */
215 <                ovec_from_pos(their_dir, neigh[n][0], neigh[n][1]);
216 <                max_ratio = MAXFRAC * dsf_grid[neigh[n][0]][neigh[n][1]].vsum
217 <                                / dsf_grid[i][j].vsum;
218 <                if (max_ratio >= 1)
219 <                        continue;
220 <                rad_ok2 = (DOT(their_dir,our_dir) - 1.)/log(max_ratio);
221 <                if (rad_ok2 >= currad*currad)
222 <                        continue;               /* value fraction OK */
223 <                currad = sqrt(rad_ok2);         /* else reduce lobe radius */
224 <                if (currad <= rad0)             /* limit how small we'll go */
225 <                        return(dsf_grid[i][j].crad);
203 >        int     xmid = (x0+x1)>>1;
204 >        int     ymid = (y0+y1)>>1;
205 >        int     branched[4];
206 >        int     nadded, nleaves;
207 >                                        /* need to make this a leaf? */
208 >        if (empty_region(x0, xmid, y0, ymid) ||
209 >                        empty_region(xmid, x1, y0, ymid) ||
210 >                        empty_region(x0, xmid, ymid, y1) ||
211 >                        empty_region(xmid, x1, ymid, y1))
212 >                return(0);
213 >                                        /* add children (branches+leaves) */
214 >        if ((branched[0] = build_rbfrep(arp, np, x0, xmid, y0, ymid)) < 0)
215 >                return(-1);
216 >        if ((branched[1] = build_rbfrep(arp, np, xmid, x1, y0, ymid)) < 0)
217 >                return(-1);
218 >        if ((branched[2] = build_rbfrep(arp, np, x0, xmid, ymid, y1)) < 0)
219 >                return(-1);
220 >        if ((branched[3] = build_rbfrep(arp, np, xmid, x1, ymid, y1)) < 0)
221 >                return(-1);
222 >        nadded = branched[0] + branched[1] + branched[2] + branched[3];
223 >        nleaves = !branched[0] + !branched[1] + !branched[2] + !branched[3];
224 >        if (!nleaves)                   /* nothing but branches? */
225 >                return(nadded);
226 >                                        /* combine 4 leaves into 1? */
227 >        if ((nleaves == 4) & (x1-x0 <= MAX_RAD) &&
228 >                        smooth_region(x0, x1, y0, y1))
229 >                return(0);
230 >                                        /* need more array space? */
231 >        if ((*np+nleaves-1)>>RBFALLOCB != (*np-1)>>RBFALLOCB) {
232 >                *arp = (RBFVAL *)realloc(*arp,
233 >                                sizeof(RBFVAL)*(*np+nleaves-1+(1<<RBFALLOCB)));
234 >                if (*arp == NULL)
235 >                        return(-1);
236          }
237 <        return(ANG2R(currad));                  /* encode selected radius */
237 >                                        /* create lobes for leaves */
238 >        if (!branched[0])
239 >                create_lobe(*arp+(*np)++, x0, xmid, y0, ymid);
240 >        if (!branched[1])
241 >                create_lobe(*arp+(*np)++, xmid, x1, y0, ymid);
242 >        if (!branched[2])
243 >                create_lobe(*arp+(*np)++, x0, xmid, ymid, y1);
244 >        if (!branched[3])
245 >                create_lobe(*arp+(*np)++, xmid, x1, ymid, y1);
246 >        nadded += nleaves;
247 >        return(nadded);
248   }
249  
250   /* Count up filled nodes and build RBF representation from current grid */
251   RBFNODE *
252 < make_rbfrep(void)
252 > make_rbfrep()
253   {
285        int     niter = 16;
286        double  lastVar, thisVar = 100.;
287        int     nn;
254          RBFNODE *newnode;
255 <        RBFVAL  *itera;
256 <        int     i, j;
291 <                                /* compute RBF radii */
292 <        compute_radii();
293 <                                /* coagulate lobes */
294 <        cull_values();
295 <        nn = 0;                 /* count selected bins */
296 <        for (i = 0; i < GRIDRES; i++)
297 <            for (j = 0; j < GRIDRES; j++)
298 <                nn += dsf_grid[i][j].nval;
255 >        RBFVAL  *rbfarr;
256 >        int     nn;
257                                  /* compute minimum BSDF */
258          comp_bsdf_min();
259 <                                /* allocate RBF array */
260 <        newnode = (RBFNODE *)malloc(sizeof(RBFNODE) + sizeof(RBFVAL)*(nn-1));
259 >                                /* create RBF node list */
260 >        rbfarr = NULL; nn = 0;
261 >        if (build_rbfrep(&rbfarr, &nn, 0, GRIDRES, 0, GRIDRES) <= 0)
262 >                goto memerr;
263 >                                /* (re)allocate RBF array */
264 >        newnode = (RBFNODE *)realloc(rbfarr,
265 >                        sizeof(RBFNODE) + sizeof(RBFVAL)*(nn-1));
266          if (newnode == NULL)
267                  goto memerr;
268 +                                /* copy computed lobes into RBF node */
269 +        memmove(newnode->rbfa, newnode, sizeof(RBFVAL)*nn);
270          newnode->ord = -1;
271          newnode->next = NULL;
272          newnode->ejl = NULL;
# Line 309 | Line 274 | make_rbfrep(void)
274          newnode->invec[0] = cos((M_PI/180.)*phi_in_deg)*newnode->invec[2];
275          newnode->invec[1] = sin((M_PI/180.)*phi_in_deg)*newnode->invec[2];
276          newnode->invec[2] = input_orient*sqrt(1. - newnode->invec[2]*newnode->invec[2]);
277 <        newnode->vtotal = 0;
277 >        newnode->vtotal = .0;
278          newnode->nrbf = nn;
279 <        nn = 0;                 /* fill RBF array */
280 <        for (i = 0; i < GRIDRES; i++)
281 <            for (j = 0; j < GRIDRES; j++)
317 <                if (dsf_grid[i][j].nval) {
318 <                        newnode->rbfa[nn].peak = dsf_grid[i][j].vsum;
319 <                        newnode->rbfa[nn].crad = adj_coded_radius(i, j);
320 <                        newnode->rbfa[nn].gx = i;
321 <                        newnode->rbfa[nn].gy = j;
322 <                        ++nn;
323 <                }
324 <                                /* iterate to improve interpolation accuracy */
325 <        itera = (RBFVAL *)malloc(sizeof(RBFVAL)*newnode->nrbf);
326 <        if (itera == NULL)
327 <                goto memerr;
328 <        memcpy(itera, newnode->rbfa, sizeof(RBFVAL)*newnode->nrbf);
329 <        do {
330 <                double  dsum = 0, dsum2 = 0;
331 <                nn = 0;
332 <                for (i = 0; i < GRIDRES; i++)
333 <                    for (j = 0; j < GRIDRES; j++)
334 <                        if (dsf_grid[i][j].nval) {
335 <                                FVECT   odir;
336 <                                double  corr;
337 <                                ovec_from_pos(odir, i, j);
338 <                                itera[nn++].peak *= corr =
339 <                                        dsf_grid[i][j].vsum /
340 <                                                eval_rbfrep(newnode, odir);
341 <                                dsum += 1. - corr;
342 <                                dsum2 += (1.-corr)*(1.-corr);
343 <                        }
344 <                memcpy(newnode->rbfa, itera, sizeof(RBFVAL)*newnode->nrbf);
345 <                lastVar = thisVar;
346 <                thisVar = dsum2/(double)nn;
279 >                                /* compute sum for normalization */
280 >        while (nn-- > 0)
281 >                newnode->vtotal += rbf_volume(&newnode->rbfa[nn]);
282   #ifdef DEBUG
283 <                fprintf(stderr, "Avg., RMS error: %.1f%%  %.1f%%\n",
349 <                                        100.*dsum/(double)nn,
350 <                                        100.*sqrt(thisVar));
351 < #endif
352 <        } while (--niter > 0 && lastVar-thisVar > 0.02*lastVar);
353 <
354 <        free(itera);
355 <        nn = 0;                 /* compute sum for normalization */
356 <        while (nn < newnode->nrbf)
357 <                newnode->vtotal += rbf_volume(&newnode->rbfa[nn++]);
358 < #ifdef DEBUG
283 >        fprintf(stderr, "Built RBF with %d lobes\n", newnode->nrbf);
284          fprintf(stderr, "Integrated DSF at (%.1f,%.1f) deg. is %.2f\n",
285                          get_theta180(newnode->invec), get_phi360(newnode->invec),
286                          newnode->vtotal);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines