doxygen: prevent GPL license block from being parsed as doxygen comment.
[blender.git] / source / blender / nodes / intern / CMP_nodes / CMP_defocus.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2006 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include "../CMP_util.h"
31
32 /* ************ qdn: Defocus node ****************** */
33 static bNodeSocketType cmp_node_defocus_in[]= {
34         {       SOCK_RGBA, 1, "Image",                  0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
35         {       SOCK_VALUE, 1, "Z",                     0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
36         {       -1, 0, ""       }
37 };
38 static bNodeSocketType cmp_node_defocus_out[]= {
39         {       SOCK_RGBA, 0, "Image",                  0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
40         {       -1, 0, ""       }
41 };
42
43
44 // line coefs for point sampling & scancon. data.
45 typedef struct BokehCoeffs {
46         float x0, y0, dx, dy;
47         float ls_x, ls_y;
48         float min_x, min_y, max_x, max_y;
49 } BokehCoeffs;
50
51 // returns array of BokehCoeffs
52 // returns length of array in 'len_bkh',
53 // radius squared of inscribed disk in 'inradsq', needed in getWeight() test,
54 // BKH[8] is the data returned for the bokeh shape & bkh_b[4] is it's 2d bound
55 static void makeBokeh(char bktype, char ro, int* len_bkh, float* inradsq, BokehCoeffs BKH[8], float bkh_b[4])
56 {
57         float x0, x1, y0, y1, dx, dy, iDxy;
58         float w = MAX2(1e-5f, ro)*M_PI/180.f;   // never reported stangely enough, but a zero offset causes missing center line...
59         float wi = (360.f/bktype)*M_PI/180.f;
60         int i, ov, nv;
61         
62         // bktype must be at least 3 & <= 8
63         bktype = (bktype<3) ? 3 : ((bktype>8) ? 8 : bktype);
64         *len_bkh = bktype;
65         *inradsq = -1.f;
66
67         for (i=0; i<(*len_bkh); i++) {
68                 x0 = cos(w);
69                 y0 = sin(w);
70                 w += wi;
71                 x1 = cos(w);
72                 y1 = sin(w);
73                 if ((*inradsq)<0.f) {
74                         // radius squared of inscribed disk
75                         float idx=(x0+x1)*0.5f, idy=(y0+y1)*0.5f;
76                         *inradsq = idx*idx + idy*idy;
77                 }
78                 BKH[i].x0 = x0;
79                 BKH[i].y0 = y0;
80                 dx = x1-x0, dy = y1-y0;
81                 iDxy = 1.f / sqrt(dx*dx + dy*dy);
82                 dx *= iDxy;
83                 dy *= iDxy;
84                 BKH[i].dx = dx;
85                 BKH[i].dy = dy;
86         }
87
88         // precalc scanconversion data
89         // bokeh bound, not transformed, for scanconvert
90         bkh_b[0] = bkh_b[2] = 1e10f;    // xmin/ymin
91         bkh_b[1] = bkh_b[3] = -1e10f;   // xmax/ymax
92         ov = (*len_bkh) - 1;
93         for (nv=0; nv<(*len_bkh); nv++) {
94                 bkh_b[0] = MIN2(bkh_b[0], BKH[nv].x0);  // xmin
95                 bkh_b[1] = MAX2(bkh_b[1], BKH[nv].x0);  // xmax
96                 bkh_b[2] = MIN2(bkh_b[2], BKH[nv].y0);  // ymin
97                 bkh_b[3] = MAX2(bkh_b[3], BKH[nv].y0);  // ymax
98                 BKH[nv].min_x = MIN2(BKH[ov].x0, BKH[nv].x0);
99                 BKH[nv].max_x = MAX2(BKH[ov].x0, BKH[nv].x0);
100                 BKH[nv].min_y = MIN2(BKH[ov].y0, BKH[nv].y0);
101                 BKH[nv].max_y = MAX2(BKH[ov].y0, BKH[nv].y0);
102                 dy = BKH[nv].y0 - BKH[ov].y0;
103                 BKH[nv].ls_x = (BKH[nv].x0 - BKH[ov].x0) / ((dy==0.f) ? 1.f : dy);
104                 BKH[nv].ls_y = (BKH[nv].ls_x==0.f) ? 1.f : (1.f/BKH[nv].ls_x);
105                 ov = nv;
106         }
107 }
108
109 // test if u/v inside shape & returns weight value
110 static float getWeight(BokehCoeffs* BKH, int len_bkh, float u, float v, float rad, float inradsq)
111 {
112         BokehCoeffs* bc = BKH;
113         float cdist, irad = (rad==0.f) ? 1.f : (1.f/rad);
114         u *= irad;
115         v *= irad;
116  
117         // early out test1: if point outside outer unit disk, it cannot be inside shape
118         cdist = u*u + v*v;
119         if (cdist>1.f) return 0.f;
120         
121         // early out test2: if point inside or on inner disk, point must be inside shape
122         if (cdist<=inradsq) return 1.f;
123         
124         while (len_bkh--) {
125                 if ((bc->dy*(u - bc->x0) - bc->dx*(v - bc->y0)) > 0.f) return 0.f;
126                 bc++;
127         }
128         return 1.f;
129 }
130
131 // QMC.seq. for sampling, A.Keller, EMS
132 static float RI_vdC(unsigned int bits, unsigned int r)
133 {
134         bits = ( bits << 16) | ( bits >> 16);
135         bits = ((bits & 0x00ff00ff) << 8) | ((bits & 0xff00ff00) >> 8);
136         bits = ((bits & 0x0f0f0f0f) << 4) | ((bits & 0xf0f0f0f0) >> 4);
137         bits = ((bits & 0x33333333) << 2) | ((bits & 0xcccccccc) >> 2);
138         bits = ((bits & 0x55555555) << 1) | ((bits & 0xaaaaaaaa) >> 1);
139         bits ^= r;
140         return (float)((double)bits / 4294967296.0);
141 }
142
143 // single channel IIR gaussian filtering
144 // much faster than anything else, constant time independent of width
145 // should extend to multichannel and make this a node, could be useful
146 static void IIR_gauss_single(CompBuf* buf, float sigma)
147 {
148         double q, q2, sc, cf[4], tsM[9], tsu[3], tsv[3];
149         float *X, *Y, *W;
150         int i, x, y, sz;
151
152         // single channel only for now
153         if (buf->type != CB_VAL) return;
154
155         // <0.5 not valid, though can have a possibly useful sort of sharpening effect
156         if (sigma < 0.5) return;
157         
158         // see "Recursive Gabor Filtering" by Young/VanVliet
159         // all factors here in double.prec. Required, because for single.prec it seems to blow up if sigma > ~200
160         if (sigma >= 3.556)
161                 q = 0.9804*(sigma - 3.556) + 2.5091;
162         else // sigma >= 0.5
163                 q = (0.0561*sigma + 0.5784)*sigma - 0.2568;
164         q2 = q*q;
165         sc = (1.1668 + q)*(3.203729649  + (2.21566 + q)*q);
166         // no gabor filtering here, so no complex multiplies, just the regular coefs.
167         // all negated here, so as not to have to recalc Triggs/Sdika matrix
168         cf[1] = q*(5.788961737 + (6.76492 + 3.0*q)*q)/ sc;
169         cf[2] = -q2*(3.38246 + 3.0*q)/sc;
170         // 0 & 3 unchanged
171         cf[3] = q2*q/sc;
172         cf[0] = 1.0 - cf[1] - cf[2] - cf[3];
173
174         // Triggs/Sdika border corrections,
175         // it seems to work, not entirely sure if it is actually totally correct,
176         // Besides J.M.Geusebroek's anigauss.c (see http://www.science.uva.nl/~mark),
177         // found one other implementation by Cristoph Lampert,
178         // but neither seem to be quite the same, result seems to be ok sofar anyway.
179         // Extra scale factor here to not have to do it in filter,
180         // though maybe this had something to with the precision errors
181         sc = cf[0]/((1.0 + cf[1] - cf[2] + cf[3])*(1.0 - cf[1] - cf[2] - cf[3])*(1.0 + cf[2] + (cf[1] - cf[3])*cf[3]));
182         tsM[0] = sc*(-cf[3]*cf[1] + 1.0 - cf[3]*cf[3] - cf[2]);
183         tsM[1] = sc*((cf[3] + cf[1])*(cf[2] + cf[3]*cf[1]));
184         tsM[2] = sc*(cf[3]*(cf[1] + cf[3]*cf[2]));
185         tsM[3] = sc*(cf[1] + cf[3]*cf[2]);
186         tsM[4] = sc*(-(cf[2] - 1.0)*(cf[2] + cf[3]*cf[1]));
187         tsM[5] = sc*(-(cf[3]*cf[1] + cf[3]*cf[3] + cf[2] - 1.0)*cf[3]);
188         tsM[6] = sc*(cf[3]*cf[1] + cf[2] + cf[1]*cf[1] - cf[2]*cf[2]);
189         tsM[7] = sc*(cf[1]*cf[2] + cf[3]*cf[2]*cf[2] - cf[1]*cf[3]*cf[3] - cf[3]*cf[3]*cf[3] - cf[3]*cf[2] + cf[3]);
190         tsM[8] = sc*(cf[3]*(cf[1] + cf[3]*cf[2]));
191
192 #define YVV(L)\
193 {\
194         W[0] = cf[0]*X[0] + cf[1]*X[0] + cf[2]*X[0] + cf[3]*X[0];\
195         W[1] = cf[0]*X[1] + cf[1]*W[0] + cf[2]*X[0] + cf[3]*X[0];\
196         W[2] = cf[0]*X[2] + cf[1]*W[1] + cf[2]*W[0] + cf[3]*X[0];\
197         for (i=3; i<L; i++)\
198                 W[i] = cf[0]*X[i] + cf[1]*W[i-1] + cf[2]*W[i-2] + cf[3]*W[i-3];\
199         tsu[0] = W[L-1] - X[L-1];\
200         tsu[1] = W[L-2] - X[L-1];\
201         tsu[2] = W[L-3] - X[L-1];\
202         tsv[0] = tsM[0]*tsu[0] + tsM[1]*tsu[1] + tsM[2]*tsu[2] + X[L-1];\
203         tsv[1] = tsM[3]*tsu[0] + tsM[4]*tsu[1] + tsM[5]*tsu[2] + X[L-1];\
204         tsv[2] = tsM[6]*tsu[0] + tsM[7]*tsu[1] + tsM[8]*tsu[2] + X[L-1];\
205         Y[L-1] = cf[0]*W[L-1] + cf[1]*tsv[0] + cf[2]*tsv[1] + cf[3]*tsv[2];\
206         Y[L-2] = cf[0]*W[L-2] + cf[1]*Y[L-1] + cf[2]*tsv[0] + cf[3]*tsv[1];\
207         Y[L-3] = cf[0]*W[L-3] + cf[1]*Y[L-2] + cf[2]*Y[L-1] + cf[3]*tsv[0];\
208         for (i=L-4; i>=0; i--)\
209                 Y[i] = cf[0]*W[i] + cf[1]*Y[i+1] + cf[2]*Y[i+2] + cf[3]*Y[i+3];\
210 }
211
212         // intermediate buffers
213         sz = MAX2(buf->x, buf->y);
214         Y = MEM_callocN(sz*sizeof(float), "IIR_gauss Y buf");
215         W = MEM_callocN(sz*sizeof(float), "IIR_gauss W buf");
216         // H
217         for (y=0; y<buf->y; y++) {
218                 X = &buf->rect[y*buf->x];
219                 YVV(buf->x);
220                 memcpy(X, Y, sizeof(float)*buf->x);
221         }
222         // V
223         X = MEM_callocN(buf->y*sizeof(float), "IIR_gauss X buf");
224         for (x=0; x<buf->x; x++) {
225                 for (y=0; y<buf->y; y++)
226                         X[y] = buf->rect[x + y*buf->x];
227                 YVV(buf->y);
228                 for (y=0; y<buf->y; y++)
229                         buf->rect[x + y*buf->x] = Y[y];
230         }
231         MEM_freeN(X);
232
233         MEM_freeN(W);
234         MEM_freeN(Y);
235 #undef YVV
236 }
237
238 static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf, float inpval, int no_zbuf)
239 {
240         NodeDefocus *nqd = node->storage;
241         CompBuf *wts;           // weights buffer
242         CompBuf *crad;          // CoC radius buffer
243         BokehCoeffs BKH[8];     // bokeh shape data, here never > 8 pts.
244         float bkh_b[4] = {0};   // shape 2D bound
245         float cam_fdist=1, cam_invfdist=1, cam_lens=35;
246         float dof_sp, maxfgc, bk_hn_theta=0, inradsq=0;
247         int y, len_bkh=0, ydone=0;
248         float aspect, aperture;
249         int minsz;
250         //float bcrad, nmaxc, scf;
251         
252         // get some required params from the current scene camera
253         // (ton) this is wrong, needs fixed
254         Scene *scene= (Scene*)node->id;
255         Object* camob = (scene)? scene->camera: NULL;
256         if (camob && camob->type==OB_CAMERA) {
257                 Camera* cam = (Camera*)camob->data;
258                 cam_lens = cam->lens;
259                 cam_fdist = dof_camera(camob);
260                 if (cam_fdist==0.0) cam_fdist = 1e10f; /* if the dof is 0.0 then set it be be far away */ 
261                 cam_invfdist = 1.f/cam_fdist;
262         }
263
264         // guess work here.. best match with raytraced result
265         minsz = MIN2(img->x, img->y);
266         dof_sp = (float)minsz / (16.f / cam_lens);      // <- == aspect * MIN2(img->x, img->y) / tan(0.5f * fov);
267         
268         // aperture
269         aspect = (img->x > img->y) ? (img->y / (float)img->x) : (img->x / (float)img->y);
270         aperture = 0.5f*(cam_lens / (aspect*32.f)) / nqd->fstop;
271         
272         // if not disk, make bokeh coefficients and other needed data
273         if (nqd->bktype!=0) {
274                 makeBokeh(nqd->bktype, nqd->rotation, &len_bkh, &inradsq, BKH, bkh_b);
275                 bk_hn_theta = 0.5 * nqd->bktype * sin(2.0 * M_PI / nqd->bktype);        // weight factor
276         }
277         
278         // accumulated weights
279         wts = alloc_compbuf(img->x, img->y, CB_VAL, 1);
280         // CoC radius buffer
281         crad = alloc_compbuf(img->x, img->y, CB_VAL, 1);
282
283         // if 'no_zbuf' flag set (which is always set if input is not an image),
284         // values are instead interpreted directly as blur radius values
285         if (no_zbuf) {
286                 // to prevent *reaaallly* big radius values and impossible calculation times,
287                 // limit the maximum to half the image width or height, whichever is smaller
288                 float maxr = 0.5f*(float)MIN2(img->x, img->y);
289                 unsigned int p;
290
291                 for (p=0; p<(unsigned int)(img->x*img->y); p++) {
292                         crad->rect[p] = zbuf ? (zbuf->rect[p]*nqd->scale) : inpval;
293                         // bug #5921, limit minimum
294                         crad->rect[p] = MAX2(1e-5f, crad->rect[p]);
295                         crad->rect[p] = MIN2(crad->rect[p], maxr);
296                         // if maxblur!=0, limit maximum
297                         if (nqd->maxblur != 0.f) crad->rect[p] = MIN2(crad->rect[p], nqd->maxblur);
298                 }
299         }
300         else {
301                 float wt;
302
303                 // actual zbuffer.
304                 // separate foreground from background CoC's
305                 // then blur background and blend in again with foreground,
306                 // improves the 'blurred foreground overlapping in-focus midground' sharp boundary problem.
307                 // wts buffer here used for blendmask
308                 maxfgc = 0.f; // maximum foreground CoC radius
309                 for (y=0; y<img->y; y++) {
310                         unsigned int p = y * img->x;
311                         int x;
312                         for (x=0; x<img->x; x++) {
313                                 unsigned int px = p + x;
314                                 float iZ = (zbuf->rect[px]==0.f) ? 0.f : (1.f/zbuf->rect[px]);
315                                 crad->rect[px] = 0.5f*(aperture*(dof_sp*(cam_invfdist - iZ) - 1.f));
316                                 if (crad->rect[px] <= 0.f) {
317                                         wts->rect[px] = 1.f;
318                                         crad->rect[px] = -crad->rect[px];
319                                         if (crad->rect[px] > maxfgc) maxfgc = crad->rect[px];
320                                 }
321                                 else crad->rect[px] = wts->rect[px] = 0;
322                         }
323                 }
324                 
325                 // fast blur...
326                 // bug #6656 part 1, probably when previous node_composite.c was split into separate files, it was not properly updated
327                 // to include recent cvs commits (well, at least not defocus node), so this part was missing...
328                 wt = aperture*128.f;
329                 IIR_gauss_single(crad, wt);
330                 IIR_gauss_single(wts, wt);
331                 
332                 // bug #6656 part 2a, although foreground blur is not based anymore on closest object,
333                 // the rescaling op below was still based on that anyway, and unlike the comment in below code,
334                 // the difference is therefore not always that small at all...
335                 // so for now commented out, not sure if this is going to cause other future problems, lets just wait and see...
336                 /*
337                 // find new maximum to scale it back to original
338                 // (could skip this, not strictly necessary, in general, difference is quite small, but just in case...)
339                 nmaxc = 0;
340                 for (p=0; p<(img->x*img->y); p++)
341                         if (crad->rect[p] > nmaxc) nmaxc = crad->rect[p];
342                 // rescale factor
343                 scf = (nmaxc==0.f) ? 1.f: (maxfgc / nmaxc);
344                 */
345
346                 // and blend...
347                 for (y=0; y<img->y; y++) {
348                         unsigned int p = y*img->x;
349                         int x;
350
351                         for (x=0; x<img->x; x++) {
352                                 unsigned px = p + x;
353                                 if (zbuf->rect[px]!=0.f) {
354                                         float iZ = (zbuf->rect[px]==0.f) ? 0.f : (1.f/zbuf->rect[px]);
355                                         
356                                         // bug #6656 part 2b, do not rescale
357                                         /*
358                                         bcrad = 0.5f*fabs(aperture*(dof_sp*(cam_invfdist - iZ) - 1.f));
359                                         // scale crad back to original maximum and blend
360                                         crad->rect[px] = bcrad + wts->rect[px]*(scf*crad->rect[px] - bcrad);
361                                         */
362                                         crad->rect[px] = 0.5f*fabs(aperture*(dof_sp*(cam_invfdist - iZ) - 1.f));
363                                         
364                                         // 'bug' #6615, limit minimum radius to 1 pixel, not really a solution, but somewhat mitigates the problem
365                                         crad->rect[px] = MAX2(crad->rect[px], 0.5f);
366                                         // if maxblur!=0, limit maximum
367                                         if (nqd->maxblur != 0.f) crad->rect[px] = MIN2(crad->rect[px], nqd->maxblur);
368                                 }
369                                 else crad->rect[px] = 0.f;
370                                 // clear weights for next part
371                                 wts->rect[px] = 0.f;
372                         }
373                         // esc set by main calling process
374                         if(node->exec & NODE_BREAK)
375                                 break;
376                 }
377         }
378
379         //------------------------------------------------------------------
380         // main loop
381 #ifndef __APPLE__ /* can crash on Mac, see bug #22856, disabled for now */
382 #ifdef __INTEL_COMPILER /* icc doesn't like the compound statement -- internal error: 0_1506 */
383         #pragma omp parallel for private(y) if(!nqd->preview) schedule(guided)
384 #else
385         #pragma omp parallel for private(y) if(!nqd->preview && img->y*img->x > 16384) schedule(guided)
386 #endif
387 #endif
388         for (y=0; y<img->y; y++) {
389                 unsigned int p, p4, zp, cp, cp4;
390                 float *ctcol, u, v, ct_crad, cR2=0;
391                 int x, sx, sy;
392
393                 // some sort of visual feedback would be nice, or at least this text in the renderwin header
394                 // but for now just print some info in the console every 8 scanlines.
395                 #pragma omp critical
396                 {
397                         if (((ydone & 7)==0) || (ydone==(img->y-1))) {
398                                 if(G.background==0) {
399                                         printf("\rdefocus: Processing Line %d of %d ... ", ydone+1, img->y);
400                                         fflush(stdout);
401                                 }
402                         }
403
404                         ydone++;
405                 }
406
407                 // esc set by main calling process. don't break because openmp doesn't
408                 // allow it, just continue and do nothing 
409                 if(node->exec & NODE_BREAK)
410                         continue;
411
412                 zp = y * img->x;
413                 for (x=0; x<img->x; x++) {
414                         cp = zp + x;
415                         cp4 = cp * img->type;
416
417                         // Circle of Confusion radius for current pixel
418                         cR2 = ct_crad = crad->rect[cp];
419                         // skip if zero (border render)
420                         if (ct_crad==0.f) {
421                                 // related to bug #5921, forgot output image when skipping 0 radius values
422                                 new->rect[cp4] = img->rect[cp4];
423                                 if (new->type != CB_VAL) {
424                                         new->rect[cp4+1] = img->rect[cp4+1];
425                                         new->rect[cp4+2] = img->rect[cp4+2];
426                                         new->rect[cp4+3] = img->rect[cp4+3];
427                                 }
428                                 continue;
429                         }
430                         cR2 *= cR2;
431                         
432                         // pixel color
433                         ctcol = &img->rect[cp4];
434                         
435                         if (!nqd->preview) {
436                                 int xs, xe, ys, ye;
437                                 float lwt, wtcol[4] = {0}, aacol[4] = {0};
438                                 float wt;
439
440                                 // shape weight
441                                 if (nqd->bktype==0)     // disk
442                                         wt = 1.f/((float)M_PI*cR2);
443                                 else
444                                         wt = 1.f/(cR2*bk_hn_theta);
445
446                                 // weighted color
447                                 wtcol[0] = wt*ctcol[0];
448                                 if (new->type != CB_VAL) {
449                                         wtcol[1] = wt*ctcol[1];
450                                         wtcol[2] = wt*ctcol[2];
451                                         wtcol[3] = wt*ctcol[3];
452                                 }
453
454                                 // macro for background blur overlap test
455                                 // unfortunately, since this is done per pixel,
456                                 // it has a very significant negative impact on processing time...
457                                 // (eg. aa disk blur without test: 112 sec, vs with test: 176 sec...)
458                                 // iff center blur radius > threshold
459                                 // and if overlap pixel in focus, do nothing, else add color/weigbt
460                                 // (threshold constant is dependant on amount of blur)
461                                 #define TESTBG1(c, w) {\
462                                         if (ct_crad > nqd->bthresh) {\
463                                                 if (crad->rect[p] > nqd->bthresh) {\
464                                                         new->rect[p] += c[0];\
465                                                         wts->rect[p] += w;\
466                                                 }\
467                                         }\
468                                         else {\
469                                                 new->rect[p] += c[0];\
470                                                 wts->rect[p] += w;\
471                                         }\
472                                 }
473                                 #define TESTBG4(c, w) {\
474                                         if (ct_crad > nqd->bthresh) {\
475                                                 if (crad->rect[p] > nqd->bthresh) {\
476                                                         new->rect[p4] += c[0];\
477                                                         new->rect[p4+1] += c[1];\
478                                                         new->rect[p4+2] += c[2];\
479                                                         new->rect[p4+3] += c[3];\
480                                                         wts->rect[p] += w;\
481                                                 }\
482                                         }\
483                                         else {\
484                                                 new->rect[p4] += c[0];\
485                                                 new->rect[p4+1] += c[1];\
486                                                 new->rect[p4+2] += c[2];\
487                                                 new->rect[p4+3] += c[3];\
488                                                 wts->rect[p] += w;\
489                                         }\
490                                 }
491                                 if (nqd->bktype == 0) {
492                                         // Disk
493                                         int _x, i, j, di;
494                                         float Dj, T;
495                                         // AA pixel
496                                         #define AAPIX(a, b) {\
497                                                 int _ny = b;\
498                                                 if ((_ny >= 0) && (_ny < new->y)) {\
499                                                         int _nx = a;\
500                                                         if ((_nx >=0) && (_nx < new->x)) {\
501                                                                 p = _ny*new->x + _nx;\
502                                                                 if (new->type==CB_VAL) {\
503                                                                         TESTBG1(aacol, lwt);\
504                                                                 }\
505                                                                 else {\
506                                                                         p4 = p * new->type;\
507                                                                         TESTBG4(aacol, lwt);\
508                                                                 }\
509                                                         }\
510                                                 }\
511                                         }
512                                         // circle scanline
513                                         #define CSCAN(a, b) {\
514                                                 int _ny = y + b;\
515                                                 if ((_ny >= 0) && (_ny < new->y)) {\
516                                                         xs = x - a + 1;\
517                                                         if (xs < 0) xs = 0;\
518                                                         xe = x + a;\
519                                                         if (xe > new->x) xe = new->x;\
520                                                         p = _ny*new->x + xs;\
521                                                         if (new->type==CB_VAL) {\
522                                                                 for (_x=xs; _x<xe; _x++, p++) TESTBG1(wtcol, wt);\
523                                                         }\
524                                                         else {\
525                                                                 p4 = p * new->type;\
526                                                                 for (_x=xs; _x<xe; _x++, p++, p4+=new->type) TESTBG4(wtcol, wt);\
527                                                         }\
528                                                 }\
529                                         }
530                                         i = ceil(ct_crad);
531                                         j = 0;
532                                         T = 0;
533                                         while (i > j) {
534                                                 Dj = sqrt(cR2 - j*j);
535                                                 Dj -= floor(Dj);
536                                                 di = 0;
537                                                 if (Dj > T) { i--;  di = 1; }
538                                                 T = Dj;
539                                                 aacol[0] = wtcol[0]*Dj;
540                                                 if (new->type != CB_VAL) {
541                                                         aacol[1] = wtcol[1]*Dj;
542                                                         aacol[2] = wtcol[2]*Dj;
543                                                         aacol[3] = wtcol[3]*Dj;
544                                                 }
545                                                 lwt = wt*Dj;
546                                                 if (i!=j) {
547                                                         // outer pixels
548                                                         AAPIX(x+j, y+i);
549                                                         AAPIX(x+j, y-i);
550                                                         if (j) {
551                                                                 AAPIX(x-j, y+i); // BL
552                                                                 AAPIX(x-j, y-i); // TL
553                                                         }
554                                                         if (di) { // only when i changed, interior of outer section
555                                                                 CSCAN(j, i); // bottom
556                                                                 CSCAN(j, -i); // top
557                                                         }
558                                                 }
559                                                 // lower mid section
560                                                 AAPIX(x+i, y+j);
561                                                 if (i) AAPIX(x-i, y+j);
562                                                 CSCAN(i, j);
563                                                 // upper mid section
564                                                 if (j) {
565                                                         AAPIX(x+i, y-j);
566                                                         if (i) AAPIX(x-i, y-j);
567                                                         CSCAN(i, -j);
568                                                 }
569                                                 j++;
570                                         }
571                                         #undef CSCAN
572                                         #undef AAPIX
573                                 }
574                                 else {
575                                         // n-agonal
576                                         int ov, nv;
577                                         float mind, maxd, lwt;
578                                         ys = MAX2((int)floor(bkh_b[2]*ct_crad + y), 0);
579                                         ye = MIN2((int)ceil(bkh_b[3]*ct_crad + y), new->y - 1);
580                                         for (sy=ys; sy<=ye; sy++) {
581                                                 float fxs = 1e10f, fxe = -1e10f;
582                                                 float yf = (sy - y)/ct_crad;
583                                                 int found = 0;
584                                                 ov = len_bkh - 1;
585                                                 mind = maxd = 0;
586                                                 for (nv=0; nv<len_bkh; nv++) {
587                                                         if ((BKH[nv].max_y >= yf) && (BKH[nv].min_y <= yf)) {
588                                                                 float tx = BKH[ov].x0 + BKH[nv].ls_x*(yf - BKH[ov].y0);
589                                                                 if (tx < fxs) { fxs = tx;  mind = BKH[nv].ls_x; }
590                                                                 if (tx > fxe) { fxe = tx;  maxd = BKH[nv].ls_x; }
591                                                                 if (++found == 2) break;
592                                                         }
593                                                         ov = nv;
594                                                 }
595                                                 if (found) {
596                                                         fxs = fxs*ct_crad + x;
597                                                         fxe = fxe*ct_crad + x;
598                                                         xs = (int)floor(fxs), xe = (int)ceil(fxe);
599                                                         // AA hack for first and last x pixel, near vertical edges only
600                                                         if (fabs(mind) <= 1.f) {
601                                                                 if ((xs >= 0) && (xs < new->x)) {
602                                                                         lwt = 1.f-(fxs - xs);
603                                                                         aacol[0] = wtcol[0]*lwt;
604                                                                         p = xs + sy*new->x;
605                                                                         if (new->type==CB_VAL) {
606                                                                                 lwt *= wt;
607                                                                                 TESTBG1(aacol, lwt);
608                                                                         }
609                                                                         else {
610                                                                                 p4 = p * new->type;
611                                                                                 aacol[1] = wtcol[1]*lwt;
612                                                                                 aacol[2] = wtcol[2]*lwt;
613                                                                                 aacol[3] = wtcol[3]*lwt;
614                                                                                 lwt *= wt;
615                                                                                 TESTBG4(aacol, lwt);
616                                                                         }
617                                                                 }
618                                                         }
619                                                         if (fabs(maxd) <= 1.f) {
620                                                                 if ((xe >= 0) && (xe < new->x)) {
621                                                                         lwt = 1.f-(xe - fxe);
622                                                                         aacol[0] = wtcol[0]*lwt;
623                                                                         p = xe + sy*new->x;
624                                                                         if (new->type==CB_VAL) {
625                                                                                 lwt *= wt;
626                                                                                 TESTBG1(aacol, lwt);
627                                                                         }
628                                                                         else {
629                                                                                 p4 = p * new->type;
630                                                                                 aacol[1] = wtcol[1]*lwt;
631                                                                                 aacol[2] = wtcol[2]*lwt;
632                                                                                 aacol[3] = wtcol[3]*lwt;
633                                                                                 lwt *= wt;
634                                                                                 TESTBG4(aacol, lwt);
635                                                                         }
636                                                                 }
637                                                         }
638                                                         xs = MAX2(xs+1, 0);
639                                                         xe = MIN2(xe, new->x);
640                                                         // remaining interior scanline
641                                                         p = sy*new->x + xs;
642                                                         if (new->type==CB_VAL) {
643                                                                 for (sx=xs; sx<xe; sx++, p++) TESTBG1(wtcol, wt);
644                                                         }
645                                                         else {
646                                                                 p4 = p * new->type;
647                                                                 for (sx=xs; sx<xe; sx++, p++, p4+=new->type) TESTBG4(wtcol, wt);
648                                                         }
649                                                 }
650                                         }
651
652                                         // now traverse in opposite direction, y scanlines,
653                                         // but this time only draw the near horizontal edges,
654                                         // applying same AA hack as above
655                                         xs = MAX2((int)floor(bkh_b[0]*ct_crad + x), 0);
656                                         xe = MIN2((int)ceil(bkh_b[1]*ct_crad + x), img->x - 1);
657                                         for (sx=xs; sx<=xe; sx++) {
658                                                 float xf = (sx - x)/ct_crad;
659                                                 float fys = 1e10f, fye = -1e10f;
660                                                 int found = 0;
661                                                 ov = len_bkh - 1;
662                                                 mind = maxd = 0;
663                                                 for (nv=0; nv<len_bkh; nv++) {
664                                                         if ((BKH[nv].max_x >= xf) && (BKH[nv].min_x <= xf)) {
665                                                                 float ty = BKH[ov].y0 + BKH[nv].ls_y*(xf - BKH[ov].x0);
666                                                                 if (ty < fys) { fys = ty;  mind = BKH[nv].ls_y; }
667                                                                 if (ty > fye) { fye = ty;  maxd = BKH[nv].ls_y; }
668                                                                 if (++found == 2) break;
669                                                         }
670                                                         ov = nv;
671                                                 }
672                                                 if (found) {
673                                                         fys = fys*ct_crad + y;
674                                                         fye = fye*ct_crad + y;
675                                                         // near horizontal edges only, line slope <= 1
676                                                         if (fabs(mind) <= 1.f) {
677                                                                 int iys = (int)floor(fys);
678                                                                 if ((iys >= 0) && (iys < new->y)) {
679                                                                         lwt = 1.f - (fys - iys);
680                                                                         aacol[0] = wtcol[0]*lwt;
681                                                                         p = sx + iys*new->x;
682                                                                         if (new->type==CB_VAL) {
683                                                                                 lwt *= wt;
684                                                                                 TESTBG1(aacol, lwt);
685                                                                         }
686                                                                         else {
687                                                                                 p4 = p * new->type;
688                                                                                 aacol[1] = wtcol[1]*lwt;
689                                                                                 aacol[2] = wtcol[2]*lwt;
690                                                                                 aacol[3] = wtcol[3]*lwt;
691                                                                                 lwt *= wt;
692                                                                                 TESTBG4(aacol, lwt);
693                                                                         }
694                                                                 }
695                                                         }
696                                                         if (fabs(maxd) <= 1.f) {
697                                                                 int iye = ceil(fye);
698                                                                 if ((iye >= 0) && (iye < new->y)) {
699                                                                         lwt = 1.f - (iye - fye);
700                                                                         aacol[0] = wtcol[0]*lwt;
701                                                                         p = sx + iye*new->x;
702                                                                         if (new->type==CB_VAL) {
703                                                                                 lwt *= wt;
704                                                                                 TESTBG1(aacol, lwt);
705                                                                         }
706                                                                         else {
707                                                                                 p4 = p * new->type;
708                                                                                 aacol[1] = wtcol[1]*lwt;
709                                                                                 aacol[2] = wtcol[2]*lwt;
710                                                                                 aacol[3] = wtcol[3]*lwt;
711                                                                                 lwt *= wt;
712                                                                                 TESTBG4(aacol, lwt);
713                                                                         }
714                                                                 }
715                                                         }
716                                                 }
717                                         }
718
719                                 }
720                                 #undef TESTBG4
721                                 #undef TESTBG1
722
723                         }
724                         else {
725                                 // sampled, simple rejection sampling here, good enough
726                                 unsigned int maxsam, s, ui = BLI_rand()*BLI_rand();
727                                 float wcor, cpr = BLI_frand(), lwt;
728                                 if (no_zbuf)
729                                         maxsam = nqd->samples;  // no zbuffer input, use sample value directly
730                                 else {
731                                         // depth adaptive sampling hack, the more out of focus, the more samples taken, 16 minimum.
732                                         maxsam = (int)(0.5f + nqd->samples*(1.f-(float)exp(-fabs(zbuf->rect[cp] - cam_fdist))));
733                                         if (maxsam < 16) maxsam = 16;
734                                 }
735                                 wcor = 1.f/(float)maxsam;
736                                 for (s=0; s<maxsam; ++s) {
737                                         u = ct_crad*(2.f*RI_vdC(s, ui) - 1.f);
738                                         v = ct_crad*(2.f*(s + cpr)/(float)maxsam - 1.f);
739                                         sx = (int)(x + u + 0.5f), sy = (int)(y + v + 0.5f);
740                                         if ((sx<0) || (sx >= new->x) || (sy<0) || (sy >= new->y)) continue;
741                                         p = sx + sy*new->x;
742                                         p4 = p * new->type;
743                                         if (nqd->bktype==0)     // Disk
744                                                 lwt = ((u*u + v*v)<=cR2) ? wcor : 0.f;
745                                         else    // AA not needed here
746                                                 lwt = wcor * getWeight(BKH, len_bkh, u, v, ct_crad, inradsq);
747                                         // prevent background bleeding onto in-focus pixels, user-option
748                                         if (ct_crad > nqd->bthresh) {  // if center blur > threshold
749                                                 if (crad->rect[p] > nqd->bthresh) { // if overlap pixel in focus, do nothing, else add color/weigbt
750                                                         new->rect[p4] += ctcol[0] * lwt;
751                                                         if (new->type != CB_VAL) {
752                                                                 new->rect[p4+1] += ctcol[1] * lwt;
753                                                                 new->rect[p4+2] += ctcol[2] * lwt;
754                                                                 new->rect[p4+3] += ctcol[3] * lwt;
755                                                         }
756                                                         wts->rect[p] += lwt;
757                                                 }
758                                         }
759                                         else {
760                                                 new->rect[p4] += ctcol[0] * lwt;
761                                                 if (new->type != CB_VAL) {
762                                                         new->rect[p4+1] += ctcol[1] * lwt;
763                                                         new->rect[p4+2] += ctcol[2] * lwt;
764                                                         new->rect[p4+3] += ctcol[3] * lwt;
765                                                 }
766                                                 wts->rect[p] += lwt;
767                                         }
768                                 }
769                         }
770
771                 }
772         }
773         
774         // finally, normalize
775         for (y=0; y<new->y; y++) {
776                 unsigned int p = y * new->x;
777                 unsigned int p4 = p * new->type;
778                 int x;
779
780                 for (x=0; x<new->x; x++) {
781                         float dv = (wts->rect[p]==0.f) ? 1.f : (1.f/wts->rect[p]);
782                         new->rect[p4] *= dv;
783                         if (new->type!=CB_VAL) {
784                                 new->rect[p4+1] *= dv;
785                                 new->rect[p4+2] *= dv;
786                                 new->rect[p4+3] *= dv;
787                         }
788                         p++;
789                         p4 += new->type;
790                 }
791         }
792
793         free_compbuf(crad);
794         free_compbuf(wts);
795         
796         printf("Done\n");
797 }
798
799
800 static void node_composit_exec_defocus(void *UNUSED(data), bNode *node, bNodeStack **in, bNodeStack **out)
801 {
802         CompBuf *new, *old, *zbuf_use = NULL, *img = in[0]->data, *zbuf = in[1]->data;
803         NodeDefocus *nqd = node->storage;
804         int no_zbuf = nqd->no_zbuf;
805         
806         if ((img==NULL) || (out[0]->hasoutput==0)) return;
807         
808         // if image not valid type or fstop==infinite (128), nothing to do, pass in to out
809         if (((img->type!=CB_RGBA) && (img->type!=CB_VAL)) || ((no_zbuf==0) && (nqd->fstop==128.f))) {
810                 out[0]->data = pass_on_compbuf(img);
811                 return;
812         }
813         
814         if (zbuf!=NULL) {
815                 // Zbuf input, check to make sure, single channel, same size
816                 // doesn't have to be actual zbuffer, but must be value type
817                 if ((zbuf->x != img->x) || (zbuf->y != img->y)) {
818                         // could do a scale here instead...
819                         printf("Z input must be same size as image !\n");
820                         return;
821                 }
822                 zbuf_use = typecheck_compbuf(zbuf, CB_VAL);
823         }
824         else no_zbuf = 1;       // no zbuffer input
825                 
826         // ok, process
827         old = img;
828         if (nqd->gamco) {
829                 // gamma correct, blender func is simplified, fixed value & RGBA only,
830                 // should make user param. also depremul and premul afterwards, gamma
831                 // correction can't work with premul alpha
832                 old = dupalloc_compbuf(img);
833                 premul_compbuf(old, 1);
834                 gamma_correct_compbuf(old, 0);
835                 premul_compbuf(old, 0);
836         }
837         
838         new = alloc_compbuf(old->x, old->y, old->type, 1);
839         defocus_blur(node, new, old, zbuf_use, in[1]->vec[0]*nqd->scale, no_zbuf);
840         
841         if (nqd->gamco) {
842                 premul_compbuf(new, 1);
843                 gamma_correct_compbuf(new, 1);
844                 premul_compbuf(new, 0);
845                 free_compbuf(old);
846         }
847         if(node->exec & NODE_BREAK) {
848                 free_compbuf(new);
849                 new= NULL;
850         }       
851         out[0]->data = new;
852         if (zbuf_use && (zbuf_use != zbuf)) free_compbuf(zbuf_use);
853 }
854
855 static void node_composit_init_defocus(bNode* node)
856 {
857    /* qdn: defocus node */
858    NodeDefocus *nbd = MEM_callocN(sizeof(NodeDefocus), "node defocus data");
859    nbd->bktype = 0;
860    nbd->rotation = 0.f;
861    nbd->preview = 1;
862    nbd->gamco = 0;
863    nbd->samples = 16;
864    nbd->fstop = 128.f;
865    nbd->maxblur = 0;
866    nbd->bthresh = 1.f;
867    nbd->scale = 1.f;
868    nbd->no_zbuf = 1;
869    node->storage = nbd;
870 }
871
872 void register_node_type_cmp_defocus(ListBase *lb)
873 {
874         static bNodeType ntype;
875
876         node_type_base(&ntype, CMP_NODE_DEFOCUS, "Defocus", NODE_CLASS_OP_FILTER, NODE_OPTIONS,
877                 cmp_node_defocus_in, cmp_node_defocus_out);
878         node_type_size(&ntype, 150, 120, 200);
879         node_type_init(&ntype, node_composit_init_defocus);
880         node_type_storage(&ntype, "NodeDefocus", node_free_standard_storage, node_copy_standard_storage);
881         node_type_exec(&ntype, node_composit_exec_defocus);
882
883         nodeRegisterType(lb, &ntype);
884 }
885
886
887