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

Comparing ray/src/common/interp2d.c (file contents):
Revision 2.1 by greg, Sat Feb 9 00:55:40 2013 UTC vs.
Revision 2.12 by greg, Fri Feb 15 19:15:16 2013 UTC

# Line 9 | Line 9 | static const char RCSid[] = "$Id$";
9  
10   #include "copyright.h"
11  
12 < /*************************************************************
12 > /***************************************************************
13   * This is a general method for 2-D interpolation similar to
14   * radial basis functions but allowing for a good deal of local
15   * anisotropy in the point distribution.  Each sample point
16   * is examined to determine the closest neighboring samples in
17   * each of NI2DIR surrounding directions.  To speed this
18 < * calculation, we sort the data into 3 half-planes and
19 < * perform simple tests to see which neighbor is closest in
20 < * a each direction.  Once we have our approximate neighborhood
21 < * for a sample, we can use it in a Gaussian weighting scheme
22 < * with anisotropic surround.  This gives us a fairly smooth
23 < * interpolation however the sample points may be initially
24 < * distributed.  Evaluation is accelerated by use of a fast
25 < * approximation to the atan2(y,x) function.
26 < **************************************************************/
18 > * calculation, we sort the data into half-planes and apply
19 > * simple tests to see which neighbor is closest in each
20 > * angular slice.  Once we have our approximate neighborhood
21 > * for a sample, we can use it in a modified Gaussian weighting
22 > * with allowing local anisotropy.  Harmonic weighting is added
23 > * to reduce the influence of distant neighbors.  This yields a
24 > * smooth interpolation regardless of how the sample points are
25 > * initially distributed.  Evaluation is accelerated by use of
26 > * a fast approximation to the atan2(y,x) function and an array
27 > * of flags indicating where weights are (nearly) zero.
28 > ****************************************************************/
29  
30   #include <stdio.h>
31   #include <stdlib.h>
32   #include "rtmath.h"
33   #include "interp2d.h"
34  
35 < #define DECODE_RAD(ip,er)       ((ip)->rmin*(1. + .5*(er)))
36 < #define ENCODE_RAD(ip,r)        ((int)(2.*(r)/(ip)->rmin) - 2)
35 > #define DECODE_DIA(ip,ed)       ((ip)->dmin*(1. + .5*(ed)))
36 > #define ENCODE_DIA(ip,d)        ((int)(2.*(d)/(ip)->dmin) - 2)
37  
38   /* Sample order (private) */
39   typedef struct {
# Line 39 | Line 41 | typedef struct {
41          float   dm;             /* distance measure in this direction */
42   } SAMPORD;
43  
44 < /* Allocate a new set of interpolation samples */
44 > /* Allocate a new set of interpolation samples (caller assigns spt[] array) */
45   INTERP2 *
46   interp2_alloc(int nsamps)
47   {
# Line 53 | Line 55 | interp2_alloc(int nsamps)
55                  return(NULL);
56  
57          nip->ns = nsamps;
58 <        nip->rmin = .5;         /* default radius minimum */
58 >        nip->dmin = 1;          /* default minimum diameter */
59          nip->smf = NI2DSMF;     /* default smoothing factor */
60 <        nip->ra = NULL;
60 >        nip->da = NULL;
61                                  /* caller must assign spt[] array */
62          return(nip);
63   }
64  
65 + /* Resize interpolation array (caller must assign any new values) */
66 + INTERP2 *
67 + interp2_realloc(INTERP2 *ip, int nsamps)
68 + {
69 +        if (ip == NULL)
70 +                return(interp2_alloc(nsamps));
71 +        if (nsamps <= 1) {
72 +                interp2_free(ip);
73 +                return(NULL);
74 +        }
75 +        if (nsamps == ip->ns)
76 +                return(ip);
77 +        if (ip->da != NULL) {   /* will need to recompute distribution */
78 +                free(ip->da);
79 +                ip->da = NULL;
80 +        }
81 +        ip = (INTERP2 *)realloc(ip, sizeof(INTERP2)+sizeof(float)*2*(nsamps-1));
82 +        if (ip == NULL)
83 +                return(NULL);
84 +        ip->ns = nsamps;
85 +        return(ip);
86 + }
87 +
88 + /* Set minimum distance under which samples will start to merge */
89 + void
90 + interp2_spacing(INTERP2 *ip, double mind)
91 + {
92 +        if (mind <= 0)
93 +                return;
94 +        if ((.998*ip->dmin <= mind) & (mind <= 1.002*ip->dmin))
95 +                return;
96 +        if (ip->da != NULL) {   /* will need to recompute distribution */
97 +                free(ip->da);
98 +                ip->da = NULL;
99 +        }
100 +        ip->dmin = mind;
101 + }
102 +
103 + /* Modify smoothing parameter by the given factor */
104 + void
105 + interp2_smooth(INTERP2 *ip, double sf)
106 + {
107 +        if ((ip->smf *= sf) < NI2DSMF)
108 +                ip->smf = NI2DSMF;
109 + }
110 +
111   /* private call-back to sort position index */
112   static int
113   cmp_spos(const void *p1, const void *p2)
# Line 74 | Line 122 | cmp_spos(const void *p1, const void *p2)
122          return 0;
123   }
124  
125 < /* private routine to encode radius with range checks */
125 > /* private routine to order samples in a particular direction */
126 > static void
127 > sort_samples(SAMPORD *sord, const INTERP2 *ip, double ang)
128 > {
129 >        const double    cosd = cos(ang);
130 >        const double    sind = sin(ang);
131 >        int             i;
132 >
133 >        for (i = ip->ns; i--; ) {
134 >                sord[i].si = i;
135 >                sord[i].dm = cosd*ip->spt[i][0] + sind*ip->spt[i][1];
136 >        }
137 >        qsort(sord, ip->ns, sizeof(SAMPORD), &cmp_spos);
138 > }
139 >
140 > /* private routine to encode sample diameter with range checks */
141   static int
142 < encode_radius(const INTERP2 *ip, double r)
142 > encode_diameter(const INTERP2 *ip, double d)
143   {
144 <        const int       er = ENCODE_RAD(ip, r);
144 >        const int       ed = ENCODE_DIA(ip, d);
145  
146 <        if (er <= 0)
146 >        if (ed <= 0)
147                  return(0);
148 <        if (er >= 0xffff)
148 >        if (ed >= 0xffff)
149                  return(0xffff);
150 <        return(er);
150 >        return(ed);
151   }
152  
153 < /* Compute anisotropic Gaussian basis function interpolant */
153 > /* Compute unnormalized weight for a position relative to a sample */
154 > double
155 > interp2_wti(INTERP2 *ip, const int i, double x, double y)
156 > {
157 >        double          dir, rd, r2, d2;
158 >        int             ri;
159 >                                /* get relative direction */
160 >        x -= ip->spt[i][0];
161 >        y -= ip->spt[i][1];
162 >        dir = atan2a(y, x);
163 >        dir += 2.*PI*(dir < 0);
164 >                                /* linear radius interpolation */
165 >        rd = dir * (NI2DIR/2./PI);
166 >        ri = (int)rd;
167 >        rd -= (double)ri;
168 >        rd = (1.-rd)*ip->da[i].dia[ri] + rd*ip->da[i].dia[(ri+1)%NI2DIR];
169 >        rd = ip->smf * DECODE_DIA(ip, rd);
170 >        r2 = 2.*rd*rd;
171 >        d2 = x*x + y*y;
172 >        if (d2 > 21.*r2)        /* result would be < 1e-9 */
173 >                return(.0);
174 >                                /* Gaussian times harmonic weighting */
175 >        return( exp(-d2/r2) * ip->dmin/(ip->dmin + sqrt(d2)) );
176 > }
177 >
178 > /* private call to get grid flag index */
179   static int
180 < interp2_compute(INTERP2 *ip)
180 > interp2_flagpos(int fgi[2], INTERP2 *ip, double x, double y)
181   {
182 +        int     inbounds = 0;
183 +
184 +        if (ip == NULL)         /* paranoia */
185 +                return(-1);
186 +                                /* need to compute interpolant? */
187 +        if (ip->da == NULL && !interp2_analyze(ip))
188 +                return(-1);
189 +                                /* get x & y grid positions */
190 +        fgi[0] = (x - ip->smin[0]) * NI2DIM / (ip->smax[0] - ip->smin[0]);
191 +
192 +        if (fgi[0] >= NI2DIM)
193 +                fgi[0] = NI2DIM-1;
194 +        else if (fgi[0] < 0)
195 +                fgi[0] = 0;
196 +        else
197 +                ++inbounds;
198 +
199 +        fgi[1] = (y - ip->smin[1]) * NI2DIM / (ip->smax[1] - ip->smin[1]);
200 +
201 +        if (fgi[1] >= NI2DIM)
202 +                fgi[1] = NI2DIM-1;
203 +        else if (fgi[1] < 0)
204 +                fgi[1] = 0;
205 +        else
206 +                ++inbounds;
207 +
208 +        return(inbounds == 2);
209 + }
210 +
211 + #define setflg(fl,xi,yi)        ((fl)[yi] |= 1<<(xi))
212 +
213 + #define chkflg(fl,xi,yi)        ((fl)[yi]>>(xi) & 1)
214 +
215 + /* private flood function to determine sample influence */
216 + static void
217 + influence_flood(INTERP2 *ip, const int i, unsigned short visited[NI2DIM],
218 +                        int xfi, int yfi)
219 + {
220 +        double  gx = (xfi+.5)*(1./NI2DIM)*(ip->smax[0] - ip->smin[0]) +
221 +                                        ip->smin[0];
222 +        double  gy = (yfi+.5)*(1./NI2DIM)*(ip->smax[1] - ip->smin[1]) +
223 +                                        ip->smin[1];
224 +        double  dx = gx - ip->spt[i][0];
225 +        double  dy = gy - ip->spt[i][1];
226 +
227 +        setflg(visited, xfi, yfi);
228 +
229 +        if (dx*dx + dy*dy > 2.*ip->grid2 && interp2_wti(ip, i, gx, gy) <= 1e-7)
230 +                return;
231 +
232 +        setflg(ip->da[i].infl, xfi, yfi);
233 +
234 +        if (xfi > 0 && !chkflg(visited, xfi-1, yfi))
235 +                influence_flood(ip, i, visited, xfi-1, yfi);
236 +
237 +        if (yfi > 0 && !chkflg(visited, xfi, yfi-1))
238 +                influence_flood(ip, i, visited, xfi, yfi-1);
239 +
240 +        if (xfi < NI2DIM-1 && !chkflg(visited, xfi+1, yfi))
241 +                influence_flood(ip, i, visited, xfi+1, yfi);
242 +
243 +        if (yfi < NI2DIM-1 && !chkflg(visited, xfi, yfi+1))
244 +                influence_flood(ip, i, visited, xfi, yfi+1);
245 + }
246 +
247 + /* (Re)compute anisotropic basis function interpolant (normally automatic) */
248 + int
249 + interp2_analyze(INTERP2 *ip)
250 + {
251          SAMPORD *sortord;
252 <        int     *rightrndx, *leftrndx;
253 <        int     bd;
252 >        int     *rightrndx, *leftrndx, *endrndx;
253 >        int     i, j, bd;
254                                          /* sanity checks */
255 <        if (ip == NULL || (ip->ns <= 1) | (ip->rmin <= 0))
255 >        if (ip == NULL)
256                  return(0);
257 <                                        /* need to allocate? */
258 <        if (ip->ra == NULL) {
259 <                ip->ra = (unsigned short (*)[NI2DIR])malloc(
103 <                                sizeof(unsigned short)*NI2DIR*ip->ns);
104 <                if (ip->ra == NULL)
105 <                        return(0);
257 >        if (ip->da != NULL) {           /* free previous data if any */
258 >                free(ip->da);
259 >                ip->da = NULL;
260          }
261 <                                        /* get temporary arrays */
261 >        if ((ip->ns <= 1) | (ip->dmin <= 0))
262 >                return(0);
263 >                                        /* compute sample domain */
264 >        ip->smin[0] = ip->smin[1] = FHUGE;
265 >        ip->smax[0] = ip->smax[1] = -FHUGE;
266 >        for (i = ip->ns; i--; ) {
267 >                if (ip->spt[i][0] < ip->smin[0]) ip->smin[0] = ip->spt[i][0];
268 >                if (ip->spt[i][0] > ip->smax[0]) ip->smax[0] = ip->spt[i][0];
269 >                if (ip->spt[i][1] < ip->smin[1]) ip->smin[1] = ip->spt[i][1];
270 >                if (ip->spt[i][1] > ip->smax[1]) ip->smax[1] = ip->spt[i][1];
271 >        }
272 >        ip->grid2 = ((ip->smax[0]-ip->smin[0])*(ip->smax[0]-ip->smin[0]) +
273 >                        (ip->smax[1]-ip->smin[1])*(ip->smax[1]-ip->smin[1])) *
274 >                                (1./NI2DIM/NI2DIM);
275 >        if (ip->grid2 <= FTINY*ip->dmin*ip->dmin)
276 >                return(0);
277 >                                        /* allocate analysis data */
278 >        ip->da = (struct interp2_samp *)calloc( ip->ns,
279 >                                        sizeof(struct interp2_samp) );
280 >        if (ip->da == NULL)
281 >                return(0);
282 >                                        /* allocate temporary arrays */
283          sortord = (SAMPORD *)malloc(sizeof(SAMPORD)*ip->ns);
284          rightrndx = (int *)malloc(sizeof(int)*ip->ns);
285          leftrndx = (int *)malloc(sizeof(int)*ip->ns);
286 <        if ((sortord == NULL) | (rightrndx == NULL) | (leftrndx == NULL))
286 >        endrndx = (int *)malloc(sizeof(int)*ip->ns);
287 >        if ((sortord == NULL) | (rightrndx == NULL) |
288 >                        (leftrndx == NULL) | (endrndx == NULL))
289                  return(0);
290                                          /* run through bidirections */
291          for (bd = 0; bd < NI2DIR/2; bd++) {
292              const double        ang = 2.*PI/NI2DIR*bd;
293 <            double              cosd, sind;
117 <            int                 i;
293 >            int                 *sptr;
294                                          /* create right reverse index */
295 <            if (bd) {                   /* re-use from prev. iteration? */
296 <                int     *sptr = rightrndx;
295 >            if (bd) {                   /* re-use from previous iteration? */
296 >                sptr = rightrndx;
297                  rightrndx = leftrndx;
298                  leftrndx = sptr;
299 <            } else {                    /* else compute it */
300 <                cosd = cos(ang + (PI/2. - PI/NI2DIR));
301 <                sind = sin(ang + (PI/2. - PI/NI2DIR));
126 <                for (i = 0; i < ip->ns; i++) {
127 <                    sortord[i].si = i;
128 <                    sortord[i].dm = cosd*ip->spt[i][0] + sind*ip->spt[i][1];
129 <                }
130 <                qsort(sortord, ip->ns, sizeof(SAMPORD), &cmp_spos);
131 <                for (i = 0; i < ip->ns; i++)
299 >            } else {                    /* else sort first half-plane */
300 >                sort_samples(sortord, ip, PI/2. - PI/NI2DIR);
301 >                for (i = ip->ns; i--; )
302                      rightrndx[sortord[i].si] = i;
303 +                                        /* & store reverse order for later */
304 +                for (i = ip->ns; i--; )
305 +                    endrndx[sortord[i].si] = ip->ns-1 - i;
306              }
307                                          /* create new left reverse index */
308 <            cosd = cos(ang + (PI/2. + PI/NI2DIR));
309 <            sind = sin(ang + (PI/2. + PI/NI2DIR));
310 <            for (i = 0; i < ip->ns; i++) {
311 <                    sortord[i].si = i;
312 <                    sortord[i].dm = cosd*ip->spt[i][0] + sind*ip->spt[i][1];
313 <            }
314 <            qsort(sortord, ip->ns, sizeof(SAMPORD), &cmp_spos);
142 <            for (i = 0; i < ip->ns; i++)
308 >            if (bd == NI2DIR/2 - 1) {   /* use order from first iteration? */
309 >                sptr = leftrndx;
310 >                leftrndx = endrndx;
311 >                endrndx = sptr;
312 >            } else {                    /* else compute new half-plane */
313 >                sort_samples(sortord, ip, ang + (PI/2. + PI/NI2DIR));
314 >                for (i = ip->ns; i--; )
315                      leftrndx[sortord[i].si] = i;
144                                        /* sort grid values in this direction */
145            cosd = cos(ang);
146            sind = sin(ang);
147            for (i = 0; i < ip->ns; i++) {
148                    sortord[i].si = i;
149                    sortord[i].dm = cosd*ip->spt[i][0] + sind*ip->spt[i][1];
316              }
317 <            qsort(sortord, ip->ns, sizeof(SAMPORD), &cmp_spos);
317 >                                        /* sort grid values in this direction */
318 >            sort_samples(sortord, ip, ang);
319                                          /* find nearest neighbors each side */
320 <            for (i = 0; i < ip->ns; i++) {
321 <                const int       rpos = rightrndx[sortord[i].si];
322 <                const int       lpos = leftrndx[sortord[i].si];
323 <                int             j;
324 <                                        /* preload with large radius */
325 <                ip->ra[i][bd] = ip->ra[i][bd+NI2DIR/2] = encode_radius(ip,
159 <                            .25*(sortord[ip->ns-1].dm - sortord[0].dm));
320 >            for (i = ip->ns; i--; ) {
321 >                const int       ii = sortord[i].si;
322 >                                        /* preload with large radii */
323 >                ip->da[ii].dia[bd] =
324 >                ip->da[ii].dia[bd+NI2DIR/2] = encode_diameter(ip,
325 >                                .5*(sortord[ip->ns-1].dm - sortord[0].dm));
326                  for (j = i; ++j < ip->ns; )     /* nearest above */
327 <                    if (rightrndx[sortord[j].si] > rpos &&
328 <                                    leftrndx[sortord[j].si] < lpos) {
329 <                        ip->ra[i][bd] = encode_radius(ip,
330 <                                        .5*(sortord[j].dm - sortord[i].dm));
327 >                    if (rightrndx[sortord[j].si] > rightrndx[ii] &&
328 >                                    leftrndx[sortord[j].si] < leftrndx[ii]) {
329 >                        ip->da[ii].dia[bd] = encode_diameter(ip,
330 >                                                sortord[j].dm - sortord[i].dm);
331                          break;
332                      }
333                  for (j = i; j-- > 0; )          /* nearest below */
334 <                    if (rightrndx[sortord[j].si] < rpos &&
335 <                                    leftrndx[sortord[j].si] > lpos) {
336 <                        ip->ra[i][bd+NI2DIR/2] = encode_radius(ip,
337 <                                        .5*(sortord[i].dm - sortord[j].dm));
334 >                    if (rightrndx[sortord[j].si] < rightrndx[ii] &&
335 >                                    leftrndx[sortord[j].si] > leftrndx[ii]) {
336 >                        ip->da[ii].dia[bd+NI2DIR/2] = encode_diameter(ip,
337 >                                                sortord[i].dm - sortord[j].dm);
338                          break;
339                      }
340              }
341          }
342 <        free(sortord);                  /* clean up */
342 >        free(sortord);                  /* release temp arrays */
343          free(rightrndx);
344          free(leftrndx);
345 <        return(1);
346 < }
345 >        free(endrndx);
346 >                                        /* fill influence maps */
347 >        for (i = ip->ns; i--; ) {
348 >                unsigned short  visited[NI2DIM];
349 >                int             fgi[2];
350  
351 < /* private call returns log of raw weight for a particular sample */
352 < static double
353 < get_ln_wt(const INTERP2 *ip, const int i, double x, double y)
354 < {
355 <        double  dir, rd;
187 <        int     ri;
188 <                                /* get relative direction */
189 <        x -= ip->spt[i][0];
190 <        y -= ip->spt[i][1];
191 <        dir = atan2a(y, x);
192 <        dir += 2.*PI*(dir < 0);
193 <                                /* linear radius interpolation */
194 <        rd = dir * (NI2DIR/2./PI);
195 <        ri = (int)rd;
196 <        rd -= (double)ri;
197 <        rd = (1.-rd)*ip->ra[i][ri] + rd*ip->ra[i][(ri+1)%NI2DIR];
198 <        rd = ip->smf * DECODE_RAD(ip, rd);
199 <                                /* return log of Gaussian weight */
200 <        return( (x*x + y*y) / (-2.*rd*rd) );
351 >                for (j = NI2DIM; j--; ) visited[j] = 0;
352 >                interp2_flagpos(fgi, ip, ip->spt[i][0], ip->spt[i][1]);
353 >                influence_flood(ip, i, visited, fgi[0], fgi[1]);
354 >        }
355 >        return(1);                      /* all done */
356   }
357  
358   /* Assign full set of normalized weights to interpolate the given position */
# Line 205 | Line 360 | int
360   interp2_weights(float wtv[], INTERP2 *ip, double x, double y)
361   {
362          double  wnorm;
363 +        int     fgi[2];
364          int     i;
365  
366 <        if ((wtv == NULL) | (ip == NULL))
366 >        if (wtv == NULL)
367                  return(0);
368 <                                        /* need to compute interpolant? */
369 <        if (ip->ra == NULL && !interp2_compute(ip))
368 >                                        /* get flag position */
369 >        if (interp2_flagpos(fgi, ip, x, y) < 0)
370                  return(0);
371  
372          wnorm = 0;                      /* compute raw weights */
373 <        for (i = ip->ns; i--; ) {
374 <                double  wt = get_ln_wt(ip, i, x, y);
375 <                if (wt < -21.) {
220 <                        wtv[i] = 0;     /* ignore weights < 1e-9 */
221 <                        continue;
222 <                }
223 <                wt = exp(wt);           /* Gaussian weight */
373 >        for (i = ip->ns; i--; )
374 >            if (chkflg(ip->da[i].infl, fgi[0], fgi[1])) {
375 >                double  wt = interp2_wti(ip, i, x, y);
376                  wtv[i] = wt;
377                  wnorm += wt;
378 <        }
378 >            } else
379 >                wtv[i] = 0;
380          if (wnorm <= 0)                 /* too far from all our samples! */
381                  return(0);
382          wnorm = 1./wnorm;               /* normalize weights */
# Line 238 | Line 391 | int
391   interp2_topsamp(float wt[], int si[], const int n, INTERP2 *ip, double x, double y)
392   {
393          int     nn = 0;
394 +        int     fgi[2];
395          double  wnorm;
396          int     i, j;
397  
398 <        if ((n <= 0) | (wt == NULL) | (si == NULL) | (ip == NULL))
398 >        if ((n <= 0) | (wt == NULL) | (si == NULL))
399                  return(0);
400 <                                        /* need to compute interpolant? */
401 <        if (ip->ra == NULL && !interp2_compute(ip))
400 >                                        /* get flag position */
401 >        if (interp2_flagpos(fgi, ip, x, y) < 0)
402                  return(0);
403                                          /* identify top n weights */
404 <        for (i = ip->ns; i--; ) {
405 <                const double    lnwt = get_ln_wt(ip, i, x, y);
404 >        for (i = ip->ns; i--; )
405 >            if (chkflg(ip->da[i].infl, fgi[0], fgi[1])) {
406 >                const double    wti = interp2_wti(ip, i, x, y);
407                  for (j = nn; j > 0; j--) {
408 <                        if (wt[j-1] >= lnwt)
408 >                        if (wt[j-1] >= wti)
409                                  break;
410                          if (j < n) {
411                                  wt[j] = wt[j-1];
# Line 258 | Line 413 | interp2_topsamp(float wt[], int si[], const int n, INT
413                          }
414                  }
415                  if (j < n) {            /* add/insert sample */
416 <                        wt[j] = lnwt;
416 >                        wt[j] = wti;
417                          si[j] = i;
418                          nn += (nn < n);
419                  }
420 <        }
421 <        wnorm = 0;                      /* exponentiate and normalize */
422 <        for (j = nn; j--; ) {
423 <                double  dwt = exp(wt[j]);
269 <                wt[j] = dwt;
270 <                wnorm += dwt;
271 <        }
420 >            }
421 >        wnorm = 0;                      /* normalize sample weights */
422 >        for (j = nn; j--; )
423 >                wnorm += wt[j];
424          if (wnorm <= 0)
425                  return(0);
426          wnorm = 1./wnorm;
# Line 283 | Line 435 | interp2_free(INTERP2 *ip)
435   {
436          if (ip == NULL)
437                  return;
438 <        if (ip->ra != NULL)
439 <                free(ip->ra);
438 >        if (ip->da != NULL)
439 >                free(ip->da);
440          free(ip);
441   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines