Ambient Occlusion split up into:
[blender.git] / source / blender / render / intern / source / rendercore.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributors: Hos, Robert Wenzlaff.
24  * Contributors: 2004/2005/2006 Blender Foundation, full recode
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /* system includes */
30 #include <stdio.h>
31 #include <math.h>
32 #include <float.h>
33 #include <string.h>
34 #include <assert.h>
35
36 /* External modules: */
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_math.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_jitter.h"
42 #include "BLI_rand.h"
43 #include "BLI_threads.h"
44
45 #include "BKE_utildefines.h"
46
47 #include "DNA_image_types.h"
48 #include "DNA_lamp_types.h"
49 #include "DNA_material_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_group_types.h"
52
53 #include "BKE_global.h"
54 #include "BKE_image.h"
55 #include "BKE_main.h"
56 #include "BKE_node.h"
57 #include "BKE_texture.h"
58
59 #include "IMB_imbuf_types.h"
60 #include "IMB_imbuf.h"
61
62 /* local include */
63 #include "renderpipeline.h"
64 #include "render_types.h"
65 #include "renderdatabase.h"
66 #include "occlusion.h"
67 #include "pixelblending.h"
68 #include "pixelshading.h"
69 #include "shadbuf.h"
70 #include "shading.h"
71 #include "sss.h"
72 #include "zbuf.h"
73 #include "RE_raytrace.h"
74
75 #include "PIL_time.h"
76
77 /* own include */
78 #include "rendercore.h"
79
80
81 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
82 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
83 /* only to be used here in this file, it's for speed */
84 extern struct Render R;
85 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
86
87 /* x and y are current pixels in rect to be rendered */
88 /* do not normalize! */
89 void calc_view_vector(float *view, float x, float y)
90 {
91
92         view[2]= -ABS(R.clipsta);
93         
94         if(R.r.mode & R_ORTHO) {
95                 view[0]= view[1]= 0.0f;
96         }
97         else {
98                 
99                 if(R.r.mode & R_PANORAMA)
100                         x-= R.panodxp;
101                 
102                 /* move x and y to real viewplane coords */
103                 x= (x/(float)R.winx);
104                 view[0]= R.viewplane.xmin + x*(R.viewplane.xmax - R.viewplane.xmin);
105                 
106                 y= (y/(float)R.winy);
107                 view[1]= R.viewplane.ymin + y*(R.viewplane.ymax - R.viewplane.ymin);
108                 
109 //              if(R.flag & R_SEC_FIELD) {
110 //                      if(R.r.mode & R_ODDFIELD) view[1]= (y+R.ystart)*R.ycor;
111 //                      else view[1]= (y+R.ystart+1.0)*R.ycor;
112 //              }
113 //              else view[1]= (y+R.ystart+R.bluroffsy+0.5)*R.ycor;
114         
115                 if(R.r.mode & R_PANORAMA) {
116                         float u= view[0] + R.panodxv; float v= view[2];
117                         view[0]= R.panoco*u + R.panosi*v;
118                         view[2]= -R.panosi*u + R.panoco*v;
119                 }
120         }
121 }
122
123 void calc_renderco_ortho(float *co, float x, float y, int z)
124 {
125         /* x and y 3d coordinate can be derived from pixel coord and winmat */
126         float fx= 2.0f/(R.winx*R.winmat[0][0]);
127         float fy= 2.0f/(R.winy*R.winmat[1][1]);
128         float zco;
129         
130         co[0]= (x - 0.5f*R.winx)*fx - R.winmat[3][0]/R.winmat[0][0];
131         co[1]= (y - 0.5f*R.winy)*fy - R.winmat[3][1]/R.winmat[1][1];
132         
133         zco= ((float)z)/2147483647.0f;
134         co[2]= R.winmat[3][2]/( R.winmat[2][3]*zco - R.winmat[2][2] );
135 }
136
137 void calc_renderco_zbuf(float *co, float *view, int z)
138 {
139         float fac, zco;
140         
141         /* inverse of zbuf calc: zbuf = MAXZ*hoco_z/hoco_w */
142         zco= ((float)z)/2147483647.0f;
143         co[2]= R.winmat[3][2]/( R.winmat[2][3]*zco - R.winmat[2][2] );
144
145         fac= co[2]/view[2];
146         co[0]= fac*view[0];
147         co[1]= fac*view[1];
148 }
149
150 /* also used in zbuf.c and shadbuf.c */
151 int count_mask(unsigned short mask)
152 {
153         if(R.samples)
154                 return (R.samples->cmask[mask & 255]+R.samples->cmask[mask>>8]);
155         return 0;
156 }
157
158 static int calchalo_z(HaloRen *har, int zz)
159 {
160         
161         if(har->type & HA_ONLYSKY) {
162                 if(zz < 0x7FFFFFF0) zz= - 0x7FFFFF;     /* edge render messes zvalues */
163         }
164         else {
165                 zz= (zz>>8);
166         }
167         return zz;
168 }
169
170
171
172 static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, int od, float dist, float xn, float yn, PixStr *ps)
173 {
174         float col[4], accol[4], fac;
175         int amount, amountm, zz, flarec, sample, fullsample, mask=0;
176         
177         fullsample= (totsample > 1);
178         amount= 0;
179         accol[0]=accol[1]=accol[2]=accol[3]= 0.0f;
180         flarec= har->flarec;
181         
182         while(ps) {
183                 amountm= count_mask(ps->mask);
184                 amount+= amountm;
185                 
186                 zz= calchalo_z(har, ps->z);
187                 if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
188                         if(shadeHaloFloat(har, col, zz, dist, xn, yn, flarec)) {
189                                 flarec= 0;
190
191                                 if(fullsample) {
192                                         for(sample=0; sample<totsample; sample++)
193                                                 if(ps->mask & (1 << sample))
194                                                         addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
195                                 }
196                                 else {
197                                         fac= ((float)amountm)/(float)R.osa;
198                                         accol[0]+= fac*col[0];
199                                         accol[1]+= fac*col[1];
200                                         accol[2]+= fac*col[2];
201                                         accol[3]+= fac*col[3];
202                                 }
203                         }
204                 }
205                 
206                 mask |= ps->mask;
207                 ps= ps->next;
208         }
209
210         /* now do the sky sub-pixels */
211         amount= R.osa-amount;
212         if(amount) {
213                 if(shadeHaloFloat(har, col, 0x7FFFFF, dist, xn, yn, flarec)) {
214                         if(!fullsample) {
215                                 fac= ((float)amount)/(float)R.osa;
216                                 accol[0]+= fac*col[0];
217                                 accol[1]+= fac*col[1];
218                                 accol[2]+= fac*col[2];
219                                 accol[3]+= fac*col[3];
220                         }
221                 }
222         }
223
224         if(fullsample) {
225                 for(sample=0; sample<totsample; sample++)
226                         if(!(mask & (1 << sample)))
227                                 addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
228         }
229         else {
230                 col[0]= accol[0];
231                 col[1]= accol[1];
232                 col[2]= accol[2];
233                 col[3]= accol[3];
234                 
235                 for(sample=0; sample<totsample; sample++)
236                         addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
237         }
238 }
239
240 static void halo_tile(RenderPart *pa, RenderLayer *rl)
241 {
242         RenderLayer *rlpp[RE_MAX_OSA];
243         HaloRen *har;
244         rcti disprect= pa->disprect, testrect= pa->disprect;
245         float dist, xsq, ysq, xn, yn;
246         float col[4];
247         intptr_t *rd= NULL;
248         int a, *rz, zz, y, sample, totsample, od;
249         short minx, maxx, miny, maxy, x;
250         unsigned int lay= rl->lay;
251
252         /* we don't render halos in the cropped area, gives errors in flare counter */
253         if(pa->crop) {
254                 testrect.xmin+= pa->crop;
255                 testrect.xmax-= pa->crop;
256                 testrect.ymin+= pa->crop;
257                 testrect.ymax-= pa->crop;
258         }
259         
260         totsample= get_sample_layers(pa, rl, rlpp);
261
262         for(a=0; a<R.tothalo; a++) {
263                 har= R.sortedhalos[a];
264
265                 /* layer test, clip halo with y */
266                 if((har->lay & lay)==0);
267                 else if(testrect.ymin > har->maxy);
268                 else if(testrect.ymax < har->miny);
269                 else {
270                         
271                         minx= floor(har->xs-har->rad);
272                         maxx= ceil(har->xs+har->rad);
273                         
274                         if(testrect.xmin > maxx);
275                         else if(testrect.xmax < minx);
276                         else {
277                                 
278                                 minx= MAX2(minx, testrect.xmin);
279                                 maxx= MIN2(maxx, testrect.xmax);
280                         
281                                 miny= MAX2(har->miny, testrect.ymin);
282                                 maxy= MIN2(har->maxy, testrect.ymax);
283                         
284                                 for(y=miny; y<maxy; y++) {
285                                         int rectofs= (y-disprect.ymin)*pa->rectx + (minx - disprect.xmin);
286                                         rz= pa->rectz + rectofs;
287                                         od= rectofs;
288                                         
289                                         if(pa->rectdaps)
290                                                 rd= pa->rectdaps + rectofs;
291                                         
292                                         yn= (y-har->ys)*R.ycor;
293                                         ysq= yn*yn;
294                                         
295                                         for(x=minx; x<maxx; x++, rz++, od++) {
296                                                 xn= x- har->xs;
297                                                 xsq= xn*xn;
298                                                 dist= xsq+ysq;
299                                                 if(dist<har->radsq) {
300                                                         if(rd && *rd) {
301                                                                 halo_pixelstruct(har, rlpp, totsample, od, dist, xn, yn, (PixStr *)*rd);
302                                                         }
303                                                         else {
304                                                                 zz= calchalo_z(har, *rz);
305                                                                 if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
306                                                                         if(shadeHaloFloat(har, col, zz, dist, xn, yn, har->flarec)) {
307                                                                                 for(sample=0; sample<totsample; sample++)
308                                                                                         addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
309                                                                         }
310                                                                 }
311                                                         }
312                                                 }
313                                                 if(rd) rd++;
314                                         }
315                                 }
316                         }
317                 }
318                 if(R.test_break(R.tbh) ) break; 
319         }
320 }
321
322 static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
323 {
324         RenderLayer *rlpp[RE_MAX_OSA];
325         ShadeInput shi;
326         float *pass;
327         float fac, col[4];
328         intptr_t *rd= pa->rectdaps;
329         int *rz= pa->rectz;
330         int x, y, sample, totsample, fullsample, od;
331         
332         totsample= get_sample_layers(pa, rl, rlpp);
333         fullsample= (totsample > 1);
334
335         shade_input_initialize(&shi, pa, rl, 0); /* this zero's ShadeInput for us */
336         
337         for(od=0, y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
338                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, rz++, od++) {
339                         
340                         calc_view_vector(shi.view, x, y);
341                         
342                         if(rd && *rd) {
343                                 PixStr *ps= (PixStr *)*rd;
344                                 int count, totsamp= 0, mask= 0;
345                                 
346                                 while(ps) {
347                                         if(R.r.mode & R_ORTHO)
348                                                 calc_renderco_ortho(shi.co, (float)x, (float)y, ps->z);
349                                         else
350                                                 calc_renderco_zbuf(shi.co, shi.view, ps->z);
351                                         
352                                         totsamp+= count= count_mask(ps->mask);
353                                         mask |= ps->mask;
354
355                                         col[0]= col[1]= col[2]= col[3]= 0.0f;
356                                         renderspothalo(&shi, col, 1.0f);
357
358                                         if(fullsample) {
359                                                 for(sample=0; sample<totsample; sample++) {
360                                                         if(ps->mask & (1 << sample)) {
361                                                                 pass= rlpp[sample]->rectf + od*4;
362                                                                 pass[0]+= col[0];
363                                                                 pass[1]+= col[1];
364                                                                 pass[2]+= col[2];
365                                                                 pass[3]+= col[3];
366                                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
367                                                         }
368                                                 }
369                                         }
370                                         else {
371                                                 fac= ((float)count)/(float)R.osa;
372                                                 pass= rl->rectf + od*4;
373                                                 pass[0]+= fac*col[0];
374                                                 pass[1]+= fac*col[1];
375                                                 pass[2]+= fac*col[2];
376                                                 pass[3]+= fac*col[3];
377                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
378                                         }
379
380                                         ps= ps->next;
381                                 }
382
383                                 if(totsamp<R.osa) {
384                                         shi.co[2]= 0.0f;
385
386                                         col[0]= col[1]= col[2]= col[3]= 0.0f;
387                                         renderspothalo(&shi, col, 1.0f);
388
389                                         if(fullsample) {
390                                                 for(sample=0; sample<totsample; sample++) {
391                                                         if(!(mask & (1 << sample))) {
392                                                                 pass= rlpp[sample]->rectf + od*4;
393                                                                 pass[0]+= col[0];
394                                                                 pass[1]+= col[1];
395                                                                 pass[2]+= col[2];
396                                                                 pass[3]+= col[3];
397                                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
398                                                         }
399                                                 }
400                                         }
401                                         else {
402                                                 fac= ((float)R.osa-totsamp)/(float)R.osa;
403                                                 pass= rl->rectf + od*4;
404                                                 pass[0]+= fac*col[0];
405                                                 pass[1]+= fac*col[1];
406                                                 pass[2]+= fac*col[2];
407                                                 pass[3]+= fac*col[3];
408                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
409                                         }
410                                 }
411                         }
412                         else {
413                                 if(R.r.mode & R_ORTHO)
414                                         calc_renderco_ortho(shi.co, (float)x, (float)y, *rz);
415                                 else
416                                         calc_renderco_zbuf(shi.co, shi.view, *rz);
417                                 
418                                 col[0]= col[1]= col[2]= col[3]= 0.0f;
419                                 renderspothalo(&shi, col, 1.0f);
420
421                                 for(sample=0; sample<totsample; sample++) {
422                                         pass= rlpp[sample]->rectf + od*4;
423                                         pass[0]+= col[0];
424                                         pass[1]+= col[1];
425                                         pass[2]+= col[2];
426                                         pass[3]+= col[3];
427                                         if(pass[3]>1.0f) pass[3]= 1.0f;
428                                 }
429                         }
430                         
431                         if(rd) rd++;
432                 }
433                 if(y&1)
434                         if(R.test_break(R.tbh)) break; 
435         }
436 }                               
437
438
439 /* ********************* MAINLOOPS ******************** */
440
441 /* osa version */
442 static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset, ShadeInput *shi, ShadeResult *shr)
443 {
444         RenderPass *rpass;
445
446         /* combined rgb */
447         add_filt_fmask(curmask, shr->combined, rl->rectf + 4*offset, rectx);
448         
449         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
450                 float *fp, *col= NULL;
451                 int pixsize= 3;
452                 
453                 switch(rpass->passtype) {
454                         case SCE_PASS_Z:
455                                 fp= rpass->rect + offset;
456                                 *fp= shr->z;
457                                 break;
458                         case SCE_PASS_RGBA:
459                                 col= shr->col;
460                                 pixsize= 4;
461                                 break;
462                         case SCE_PASS_EMIT:
463                                 col= shr->emit;
464                                 break;
465                         case SCE_PASS_DIFFUSE:
466                                 col= shr->diff;
467                                 break;
468                         case SCE_PASS_SPEC:
469                                 col= shr->spec;
470                                 break;
471                         case SCE_PASS_SHADOW:
472                                 col= shr->shad;
473                                 break;
474                         case SCE_PASS_AO:
475                                 col= shr->ao;
476                                 break;
477                         case SCE_PASS_ENVIRONMENT:
478                                 col= shr->env;
479                                 break;
480                         case SCE_PASS_INDIRECT:
481                                 col= shr->indirect;
482                                 break;
483                         case SCE_PASS_REFLECT:
484                                 col= shr->refl;
485                                 break;
486                         case SCE_PASS_REFRACT:
487                                 col= shr->refr;
488                                 break;
489                         case SCE_PASS_RADIO:
490                                 col= NULL; // removed shr->rad;
491                                 break;
492                         case SCE_PASS_NORMAL:
493                                 col= shr->nor;
494                                 break;
495                         case SCE_PASS_UV:
496                                 /* box filter only, gauss will screwup UV too much */
497                                 if(shi->totuv) {
498                                         float mult= (float)count_mask(curmask)/(float)R.osa;
499                                         fp= rpass->rect + 3*offset;
500                                         fp[0]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[0]);
501                                         fp[1]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[1]);
502                                         fp[2]+= mult;
503                                 }
504                                 break;
505                         case SCE_PASS_INDEXOB:
506                                 /* no filter */
507                                 if(shi->vlr) {
508                                         fp= rpass->rect + offset;
509                                         if(*fp==0.0f)
510                                                 *fp= (float)shi->obr->ob->index;
511                                 }
512                                 break;
513                         case SCE_PASS_MIST:
514                                 /*  */
515                                 col= &shr->mist;
516                                 pixsize= 1;
517                                 break;
518                         
519                         case SCE_PASS_VECTOR:
520                         {
521                                 /* add minimum speed in pixel, no filter */
522                                 fp= rpass->rect + 4*offset;
523                                 if( (ABS(shr->winspeed[0]) + ABS(shr->winspeed[1]))< (ABS(fp[0]) + ABS(fp[1])) ) {
524                                         fp[0]= shr->winspeed[0];
525                                         fp[1]= shr->winspeed[1];
526                                 }
527                                 if( (ABS(shr->winspeed[2]) + ABS(shr->winspeed[3]))< (ABS(fp[2]) + ABS(fp[3])) ) {
528                                         fp[2]= shr->winspeed[2];
529                                         fp[3]= shr->winspeed[3];
530                                 }
531                         }
532                                 break;
533
534                         case SCE_PASS_RAYHITS:
535                                 /*  */
536                                 col= shr->rayhits;
537                                 pixsize= 4;
538                                 break;
539                 }
540                 if(col) {
541                         fp= rpass->rect + pixsize*offset;
542                         add_filt_fmask_pixsize(curmask, col, fp, rectx, pixsize);
543                 }
544         }
545 }
546
547 /* non-osa version */
548 static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult *shr)
549 {
550         RenderPass *rpass;
551         float *fp;
552         
553         fp= rl->rectf + 4*offset;
554         QUATCOPY(fp, shr->combined);
555         
556         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
557                 float *col= NULL, uvcol[3];
558                 int a, pixsize= 3;
559                 
560                 switch(rpass->passtype) {
561                         case SCE_PASS_Z:
562                                 fp= rpass->rect + offset;
563                                 *fp= shr->z;
564                                 break;
565                         case SCE_PASS_RGBA:
566                                 col= shr->col;
567                                 pixsize= 4;
568                                 break;
569                         case SCE_PASS_EMIT:
570                                 col= shr->emit;
571                                 break;
572                         case SCE_PASS_DIFFUSE:
573                                 col= shr->diff;
574                                 break;
575                         case SCE_PASS_SPEC:
576                                 col= shr->spec;
577                                 break;
578                         case SCE_PASS_SHADOW:
579                                 col= shr->shad;
580                                 break;
581                         case SCE_PASS_AO:
582                                 col= shr->ao;
583                                 break;
584                         case SCE_PASS_ENVIRONMENT:
585                                 col= shr->env;
586                                 break;
587                         case SCE_PASS_INDIRECT:
588                                 col= shr->indirect;
589                                 break;
590                         case SCE_PASS_REFLECT:
591                                 col= shr->refl;
592                                 break;
593                         case SCE_PASS_REFRACT:
594                                 col= shr->refr;
595                                 break;
596                         case SCE_PASS_RADIO:
597                                 col= NULL; // removed shr->rad;
598                                 break;
599                         case SCE_PASS_NORMAL:
600                                 col= shr->nor;
601                                 break;
602                         case SCE_PASS_UV:
603                                 if(shi->totuv) {
604                                         uvcol[0]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[0];
605                                         uvcol[1]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[1];
606                                         uvcol[2]= 1.0f;
607                                         col= uvcol;
608                                 }
609                                 break;
610                         case SCE_PASS_VECTOR:
611                                 col= shr->winspeed;
612                                 pixsize= 4;
613                                 break;
614                         case SCE_PASS_INDEXOB:
615                                 if(shi->vlr) {
616                                         fp= rpass->rect + offset;
617                                         *fp= (float)shi->obr->ob->index;
618                                 }
619                                 break;
620                         case SCE_PASS_MIST:
621                                 fp= rpass->rect + offset;
622                                 *fp= shr->mist;
623                                 break;
624                         case SCE_PASS_RAYHITS:
625                                 col= shr->rayhits;
626                                 pixsize= 4;
627                                 break;
628                 }
629                 if(col) {
630                         fp= rpass->rect + pixsize*offset;
631                         for(a=0; a<pixsize; a++)
632                                 fp[a]= col[a];
633                 }
634         }
635 }
636
637 int get_sample_layers(RenderPart *pa, RenderLayer *rl, RenderLayer **rlpp)
638 {
639         
640         if(pa->fullresult.first) {
641                 int sample, nr= BLI_findindex(&pa->result->layers, rl);
642                 
643                 for(sample=0; sample<R.osa; sample++) {
644                         RenderResult *rr= BLI_findlink(&pa->fullresult, sample);
645                 
646                         rlpp[sample]= BLI_findlink(&rr->layers, nr);
647                 }               
648                 return R.osa;
649         }
650         else {
651                 rlpp[0]= rl;
652                 return 1;
653         }
654 }
655
656
657 /* only do sky, is default in the solid layer (shade_tile) btw */
658 static void sky_tile(RenderPart *pa, RenderLayer *rl)
659 {
660         RenderLayer *rlpp[RE_MAX_OSA];
661         int x, y, od=0, totsample;
662         
663         if(R.r.alphamode!=R_ADDSKY)
664                 return;
665         
666         totsample= get_sample_layers(pa, rl, rlpp);
667         
668         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
669                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od+=4) {
670                         float col[4];
671                         int sample, done= 0;
672                         
673                         for(sample= 0; sample<totsample; sample++) {
674                                 float *pass= rlpp[sample]->rectf + od;
675                                 
676                                 if(pass[3]<1.0f) {
677                                         
678                                         if(done==0) {
679                                                 shadeSkyPixel(col, x, y, pa->thread);
680                                                 done= 1;
681                                         }
682                                         
683                                         if(pass[3]==0.0f) {
684                                                 QUATCOPY(pass, col);
685                                         }
686                                         else {
687                                                 addAlphaUnderFloat(pass, col);
688                                         }
689                                 }
690                         }                       
691                 }
692                 
693                 if(y&1)
694                         if(R.test_break(R.tbh)) break; 
695         }
696 }
697
698 static void atm_tile(RenderPart *pa, RenderLayer *rl)
699 {
700         RenderPass *zpass;
701         GroupObject *go;
702         LampRen *lar;
703         RenderLayer *rlpp[RE_MAX_OSA];
704         int totsample;
705         int x, y, od= 0;
706         
707         totsample= get_sample_layers(pa, rl, rlpp);
708
709         /* check that z pass is enabled */
710         if(pa->rectz==NULL) return;
711         for(zpass= rl->passes.first; zpass; zpass= zpass->next)
712                 if(zpass->passtype==SCE_PASS_Z)
713                         break;
714         
715         if(zpass==NULL) return;
716
717         /* check for at least one sun lamp that its atmosphere flag is is enabled */
718         for(go=R.lights.first; go; go= go->next) {
719                 lar= go->lampren;
720                 if(lar->type==LA_SUN && lar->sunsky && (lar->sunsky->effect_type & LA_SUN_EFFECT_AP))
721                         break;
722         }
723         /* do nothign and return if there is no sun lamp */
724         if(go==NULL)
725                 return;
726         
727         /* for each x,y and each sample, and each sun lamp*/
728         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
729                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od++) {
730                         int sample;
731                         
732                         for(sample=0; sample<totsample; sample++) {
733                                 float *zrect= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_Z) + od;
734                                 float *rgbrect = rlpp[sample]->rectf + 4*od;
735                                 float rgb[3] = {0};
736                                 int done= 0;
737                                 
738                                 for(go=R.lights.first; go; go= go->next) {
739                                 
740                                         
741                                         lar= go->lampren;
742                                         if(lar->type==LA_SUN && lar->sunsky) {
743                                                 
744                                                 /* if it's sky continue and don't apply atmosphere effect on it */
745                                                 if(*zrect >= 9.9e10 || rgbrect[3]==0.0f) {
746                                                         continue;
747                                                 }
748                                                 
749                                                 if((lar->sunsky->effect_type & LA_SUN_EFFECT_AP)) {     
750                                                         float tmp_rgb[3];
751                                                         
752                                                         VECCOPY(tmp_rgb, rgbrect);
753                                                         if(rgbrect[3]!=1.0f) {  /* de-premul */
754                                                                 float div= 1.0f/rgbrect[3];
755                                                                 VECMUL(tmp_rgb, div);
756                                                         }
757                                                         shadeAtmPixel(lar->sunsky, tmp_rgb, x, y, *zrect);
758                                                         if(rgbrect[3]!=1.0f) {  /* premul */
759                                                                 VECMUL(tmp_rgb, rgbrect[3]);
760                                                         }
761                                                         
762                                                         if(done==0) {
763                                                                 VECCOPY(rgb, tmp_rgb);
764                                                                 done = 1;                                               
765                                                         }
766                                                         else{
767                                                                 rgb[0] = 0.5f*rgb[0] + 0.5f*tmp_rgb[0];
768                                                                 rgb[1] = 0.5f*rgb[1] + 0.5f*tmp_rgb[1];
769                                                                 rgb[2] = 0.5f*rgb[2] + 0.5f*tmp_rgb[2];
770                                                         }
771                                                 }
772                                         }
773                                 }
774
775                                 /* if at least for one sun lamp aerial perspective was applied*/
776                                 if(done) {
777                                         VECCOPY(rgbrect, rgb);
778                                 }
779                         }
780                 }
781         }
782 }
783
784 static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
785 {
786         RenderResult *rr= pa->result;
787         ShadeSample ssamp;
788         intptr_t *rd, *rectdaps= pa->rectdaps;
789         int samp;
790         int x, y, seed, crop=0, offs=0, od;
791         
792         if(R.test_break(R.tbh)) return; 
793         
794         /* irregular shadowb buffer creation */
795         if(R.r.mode & R_SHADOW)
796                 ISB_create(pa, NULL);
797         
798         /* we set per pixel a fixed seed, for random AO and shadow samples */
799         seed= pa->rectx*pa->disprect.ymin;
800         
801         /* general shader info, passes */
802         shade_sample_initialize(&ssamp, pa, rl);
803
804         /* occlusion caching */
805         if(R.occlusiontree)
806                 cache_occ_samples(&R, pa, &ssamp);
807                 
808         /* filtered render, for now we assume only 1 filter size */
809         if(pa->crop) {
810                 crop= 1;
811                 rectdaps+= pa->rectx + 1;
812                 offs= pa->rectx + 1;
813         }
814         
815         /* scanline updates have to be 2 lines behind */
816         rr->renrect.ymin= 0;
817         rr->renrect.ymax= -2*crop;
818         rr->renlay= rl;
819                                 
820         for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
821                 rd= rectdaps;
822                 od= offs;
823                 
824                 for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, rd++, od++) {
825                         BLI_thread_srandom(pa->thread, seed++);
826                         
827                         if(*rd) {
828                                 if(shade_samples(&ssamp, (PixStr *)(*rd), x, y)) {
829                                         
830                                         /* multisample buffers or filtered mask filling? */
831                                         if(pa->fullresult.first) {
832                                                 int a;
833                                                 for(samp=0; samp<ssamp.tot; samp++) {
834                                                         int smask= ssamp.shi[samp].mask;
835                                                         for(a=0; a<R.osa; a++) {
836                                                                 int mask= 1<<a;
837                                                                 if(smask & mask)
838                                                                         add_passes(ssamp.rlpp[a], od, &ssamp.shi[samp], &ssamp.shr[samp]);
839                                                         }
840                                                 }
841                                         }
842                                         else {
843                                                 for(samp=0; samp<ssamp.tot; samp++)
844                                                         add_filt_passes(rl, ssamp.shi[samp].mask, pa->rectx, od, &ssamp.shi[samp], &ssamp.shr[samp]);
845                                         }
846                                 }
847                         }
848                 }
849                 
850                 rectdaps+= pa->rectx;
851                 offs+= pa->rectx;
852                 
853                 if(y&1) if(R.test_break(R.tbh)) break; 
854         }
855         
856         /* disable scanline updating */
857         rr->renlay= NULL;
858         
859         if(R.r.mode & R_SHADOW)
860                 ISB_free(pa);
861
862         if(R.occlusiontree)
863                 free_occ_samples(&R, pa);
864 }
865
866 /* ************* pixel struct ******** */
867
868
869 static PixStrMain *addpsmain(ListBase *lb)
870 {
871         PixStrMain *psm;
872         
873         psm= (PixStrMain *)MEM_mallocN(sizeof(PixStrMain),"pixstrMain");
874         BLI_addtail(lb, psm);
875         
876         psm->ps= (PixStr *)MEM_mallocN(4096*sizeof(PixStr),"pixstr");
877         psm->counter= 0;
878         
879         return psm;
880 }
881
882 static void freeps(ListBase *lb)
883 {
884         PixStrMain *psm, *psmnext;
885         
886         for(psm= lb->first; psm; psm= psmnext) {
887                 psmnext= psm->next;
888                 if(psm->ps)
889                         MEM_freeN(psm->ps);
890                 MEM_freeN(psm);
891         }
892         lb->first= lb->last= NULL;
893 }
894
895 static void addps(ListBase *lb, intptr_t *rd, int obi, int facenr, int z, int maskz, unsigned short mask)
896 {
897         PixStrMain *psm;
898         PixStr *ps, *last= NULL;
899         
900         if(*rd) {       
901                 ps= (PixStr *)(*rd);
902                 
903                 while(ps) {
904                         if( ps->obi == obi && ps->facenr == facenr ) {
905                                 ps->mask |= mask;
906                                 return;
907                         }
908                         last= ps;
909                         ps= ps->next;
910                 }
911         }
912         
913         /* make new PS (pixel struct) */
914         psm= lb->last;
915         
916         if(psm->counter==4095)
917                 psm= addpsmain(lb);
918         
919         ps= psm->ps + psm->counter++;
920         
921         if(last) last->next= ps;
922         else *rd= (intptr_t)ps;
923         
924         ps->next= NULL;
925         ps->obi= obi;
926         ps->facenr= facenr;
927         ps->z= z;
928         ps->maskz= maskz;
929         ps->mask = mask;
930         ps->shadfac= 0;
931 }
932
933 static void edge_enhance_add(RenderPart *pa, float *rectf, float *arect)
934 {
935         float addcol[4];
936         int pix;
937         
938         if(arect==NULL)
939                 return;
940         
941         for(pix= pa->rectx*pa->recty; pix>0; pix--, arect++, rectf+=4) {
942                 if(*arect != 0.0f) {
943                         addcol[0]= *arect * R.r.edgeR;
944                         addcol[1]= *arect * R.r.edgeG;
945                         addcol[2]= *arect * R.r.edgeB;
946                         addcol[3]= *arect;
947                         addAlphaOverFloat(rectf, addcol);
948                 }
949         }
950 }
951
952 static void convert_to_key_alpha(RenderPart *pa, RenderLayer *rl)
953 {
954         RenderLayer *rlpp[RE_MAX_OSA];
955         int y, sample, totsample;
956         
957         totsample= get_sample_layers(pa, rl, rlpp);
958         
959         for(sample= 0; sample<totsample; sample++) {
960                 float *rectf= rlpp[sample]->rectf;
961                 
962                 for(y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
963                         if(rectf[3] >= 1.0f);
964                         else if(rectf[3] > 0.0f) {
965                                 rectf[0] /= rectf[3];
966                                 rectf[1] /= rectf[3];
967                                 rectf[2] /= rectf[3];
968                         }
969                 }
970         }
971 }
972
973 /* adds only alpha values */
974 void edge_enhance_tile(RenderPart *pa, float *rectf, int *rectz)
975 {
976         /* use zbuffer to define edges, add it to the image */
977         int y, x, col, *rz, *rz1, *rz2, *rz3;
978         int zval1, zval2, zval3;
979         float *rf;
980         
981         /* shift values in zbuffer 4 to the right (anti overflows), for filter we need multiplying with 12 max */
982         rz= rectz;
983         if(rz==NULL) return;
984         
985         for(y=0; y<pa->recty; y++)
986                 for(x=0; x<pa->rectx; x++, rz++) (*rz)>>= 4;
987         
988         rz1= rectz;
989         rz2= rz1+pa->rectx;
990         rz3= rz2+pa->rectx;
991         
992         rf= rectf+pa->rectx+1;
993         
994         for(y=0; y<pa->recty-2; y++) {
995                 for(x=0; x<pa->rectx-2; x++, rz1++, rz2++, rz3++, rf++) {
996                         
997                         /* prevent overflow with sky z values */
998                         zval1=   rz1[0] + 2*rz1[1] +   rz1[2];
999                         zval2=  2*rz2[0]           + 2*rz2[2];
1000                         zval3=   rz3[0] + 2*rz3[1] +   rz3[2];
1001                         
1002                         col= ( 4*rz2[1] - (zval1 + zval2 + zval3)/3 );
1003                         if(col<0) col= -col;
1004                         
1005                         col >>= 5;
1006                         if(col > (1<<16)) col= (1<<16);
1007                         else col= (R.r.edgeint*col)>>8;
1008                         
1009                         if(col>0) {
1010                                 float fcol;
1011                                 
1012                                 if(col>255) fcol= 1.0f;
1013                                 else fcol= (float)col/255.0f;
1014                                 
1015                                 if(R.osa)
1016                                         *rf+= fcol/(float)R.osa;
1017                                 else
1018                                         *rf= fcol;
1019                         }
1020                 }
1021                 rz1+= 2;
1022                 rz2+= 2;
1023                 rz3+= 2;
1024                 rf+= 2;
1025         }
1026         
1027         /* shift back zbuf values, we might need it still */
1028         rz= rectz;
1029         for(y=0; y<pa->recty; y++)
1030                 for(x=0; x<pa->rectx; x++, rz++) (*rz)<<= 4;
1031         
1032 }
1033
1034 static void reset_sky_speed(RenderPart *pa, RenderLayer *rl)
1035 {
1036         /* for all pixels with max speed, set to zero */
1037     RenderLayer *rlpp[RE_MAX_OSA];
1038         float *fp;
1039         int a, sample, totsample;
1040         
1041         totsample= get_sample_layers(pa, rl, rlpp);
1042
1043         for(sample= 0; sample<totsample; sample++) {
1044                 fp= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_VECTOR);
1045                 if(fp==NULL) break;
1046
1047                 for(a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
1048                         if(fp[a] == PASS_VECTOR_MAX) fp[a]= 0.0f;
1049         }
1050 }
1051
1052 static unsigned short *make_solid_mask(RenderPart *pa)
1053
1054         intptr_t *rd= pa->rectdaps;
1055         unsigned short *solidmask, *sp;
1056         int x;
1057         
1058         if(rd==NULL) return NULL;
1059         
1060         sp=solidmask= MEM_mallocN(sizeof(short)*pa->rectx*pa->recty, "solidmask");
1061         
1062         for(x=pa->rectx*pa->recty; x>0; x--, rd++, sp++) {
1063                 if(*rd) {
1064                         PixStr *ps= (PixStr *)*rd;
1065                         
1066                         *sp= ps->mask;
1067                         for(ps= ps->next; ps; ps= ps->next)
1068                                 *sp |= ps->mask;
1069                 }
1070                 else
1071                         *sp= 0;
1072         }
1073                         
1074         return solidmask;
1075 }
1076
1077 static void addAlphaOverFloatMask(float *dest, float *source, unsigned short dmask, unsigned short smask)
1078 {
1079         unsigned short shared= dmask & smask;
1080         float mul= 1.0 - source[3];
1081         
1082         if(shared) {    /* overlapping masks */
1083                 
1084                 /* masks differ, we make a mixture of 'add' and 'over' */
1085                 if(shared!=dmask) {
1086                         float shared_bits= (float)count_mask(shared);           /* alpha over */
1087                         float tot_bits= (float)count_mask(smask|dmask);         /* alpha add */
1088                         
1089                         float add= (tot_bits - shared_bits)/tot_bits;           /* add level */
1090                         mul= add + (1.0f-add)*mul;
1091                 }
1092         }
1093         else if(dmask && smask) {
1094                 /* works for premul only, of course */
1095                 dest[0]+= source[0];
1096                 dest[1]+= source[1];
1097                 dest[2]+= source[2];
1098                 dest[3]+= source[3];
1099                 
1100                 return;
1101         }
1102
1103         dest[0]= (mul*dest[0]) + source[0];
1104         dest[1]= (mul*dest[1]) + source[1];
1105         dest[2]= (mul*dest[2]) + source[2];
1106         dest[3]= (mul*dest[3]) + source[3];
1107 }
1108
1109 typedef struct ZbufSolidData {
1110         RenderLayer *rl;
1111         ListBase *psmlist;
1112         float *edgerect;
1113 } ZbufSolidData;
1114
1115 void make_pixelstructs(RenderPart *pa, ZSpan *zspan, int sample, void *data)
1116 {
1117         ZbufSolidData *sdata= (ZbufSolidData*)data;
1118         ListBase *lb= sdata->psmlist;
1119         intptr_t *rd= pa->rectdaps;
1120         int *ro= zspan->recto;
1121         int *rp= zspan->rectp;
1122         int *rz= zspan->rectz;
1123         int *rm= zspan->rectmask;
1124         int x, y;
1125         int mask= 1<<sample;
1126
1127         for(y=0; y<pa->recty; y++) {
1128                 for(x=0; x<pa->rectx; x++, rd++, rp++, ro++, rz++, rm++) {
1129                         if(*rp) {
1130                                 addps(lb, rd, *ro, *rp, *rz, (zspan->rectmask)? *rm: 0, mask);
1131                         }
1132                 }
1133         }
1134
1135         if(sdata->rl->layflag & SCE_LAY_EDGE) 
1136                 if(R.r.mode & R_EDGE) 
1137                         edge_enhance_tile(pa, sdata->edgerect, zspan->rectz);
1138 }
1139
1140 /* main call for shading Delta Accum, for OSA */
1141 /* supposed to be fully threadable! */
1142 void zbufshadeDA_tile(RenderPart *pa)
1143 {
1144         RenderResult *rr= pa->result;
1145         RenderLayer *rl;
1146         ListBase psmlist= {NULL, NULL};
1147         float *edgerect= NULL;
1148         
1149         /* allocate the necessary buffers */
1150                                 /* zbuffer inits these rects */
1151         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1152         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1153         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1154         for(rl= rr->layers.first; rl; rl= rl->next) {
1155                 if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
1156                         pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
1157         
1158                 /* initialize pixelstructs and edge buffer */
1159                 addpsmain(&psmlist);
1160                 pa->rectdaps= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "zbufDArectd");
1161                 
1162                 if(rl->layflag & SCE_LAY_EDGE) 
1163                         if(R.r.mode & R_EDGE) 
1164                                 edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
1165                 
1166                 /* always fill visibility */
1167                 for(pa->sample=0; pa->sample<R.osa; pa->sample+=4) {
1168                         ZbufSolidData sdata;
1169
1170                         sdata.rl= rl;
1171                         sdata.psmlist= &psmlist;
1172                         sdata.edgerect= edgerect;
1173                         zbuffer_solid(pa, rl, make_pixelstructs, &sdata);
1174                         if(R.test_break(R.tbh)) break; 
1175                 }
1176                 
1177                 /* shades solid */
1178                 if(rl->layflag & SCE_LAY_SOLID) 
1179                         shadeDA_tile(pa, rl);
1180                 
1181                 /* lamphalo after solid, before ztra, looks nicest because ztra does own halo */
1182                 if(R.flag & R_LAMPHALO)
1183                         if(rl->layflag & SCE_LAY_HALO)
1184                                 lamphalo_tile(pa, rl);
1185                 
1186                 /* halo before ztra, because ztra fills in zbuffer now */
1187                 if(R.flag & R_HALO)
1188                         if(rl->layflag & SCE_LAY_HALO)
1189                                 halo_tile(pa, rl);
1190
1191                 /* transp layer */
1192                 if(R.flag & R_ZTRA || R.totstrand) {
1193                         if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
1194                                 if(pa->fullresult.first) {
1195                                         zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
1196                                 }
1197                                 else {
1198                                         unsigned short *ztramask, *solidmask= NULL; /* 16 bits, MAX_OSA */
1199                                         
1200                                         /* allocate, but not free here, for asynchronous display of this rect in main thread */
1201                                         rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
1202                                         
1203                                         /* swap for live updates, and it is used in zbuf.c!!! */
1204                                         SWAP(float *, rl->acolrect, rl->rectf);
1205                                         ztramask= zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
1206                                         SWAP(float *, rl->acolrect, rl->rectf);
1207                                         
1208                                         /* zbuffer transp only returns ztramask if there's solid rendered */
1209                                         if(ztramask)
1210                                                 solidmask= make_solid_mask(pa);
1211
1212                                         if(ztramask && solidmask) {
1213                                                 unsigned short *sps= solidmask, *spz= ztramask;
1214                                                 unsigned short fullmask= (1<<R.osa)-1;
1215                                                 float *fcol= rl->rectf; float *acol= rl->acolrect;
1216                                                 int x;
1217                                                 
1218                                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4, sps++, spz++) {
1219                                                         if(*sps == fullmask)
1220                                                                 addAlphaOverFloat(fcol, acol);
1221                                                         else
1222                                                                 addAlphaOverFloatMask(fcol, acol, *sps, *spz);
1223                                                 }
1224                                         }
1225                                         else {
1226                                                 float *fcol= rl->rectf; float *acol= rl->acolrect;
1227                                                 int x;
1228                                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
1229                                                         addAlphaOverFloat(fcol, acol);
1230                                                 }
1231                                         }
1232                                         if(solidmask) MEM_freeN(solidmask);
1233                                         if(ztramask) MEM_freeN(ztramask);
1234                                 }
1235                         }
1236                 }
1237
1238                 /* sun/sky */
1239                 if(rl->layflag & SCE_LAY_SKY)
1240                         atm_tile(pa, rl);
1241                 
1242                 /* sky before edge */
1243                 if(rl->layflag & SCE_LAY_SKY)
1244                         sky_tile(pa, rl);
1245
1246                 /* extra layers */
1247                 if(rl->layflag & SCE_LAY_EDGE) 
1248                         if(R.r.mode & R_EDGE) 
1249                                 edge_enhance_add(pa, rl->rectf, edgerect);
1250                 
1251                 if(rl->passflag & SCE_PASS_VECTOR)
1252                         reset_sky_speed(pa, rl);
1253                 
1254                 /* de-premul alpha */
1255                 if(R.r.alphamode & R_ALPHAKEY)
1256                         convert_to_key_alpha(pa, rl);
1257                 
1258                 /* free stuff within loop! */
1259                 MEM_freeN(pa->rectdaps); pa->rectdaps= NULL;
1260                 freeps(&psmlist);
1261                 
1262                 if(edgerect) MEM_freeN(edgerect);
1263                 edgerect= NULL;
1264
1265                 if(pa->rectmask) {
1266                         MEM_freeN(pa->rectmask);
1267                         pa->rectmask= NULL;
1268                 }
1269         }
1270         
1271         /* free all */
1272         MEM_freeN(pa->recto); pa->recto= NULL;
1273         MEM_freeN(pa->rectp); pa->rectp= NULL;
1274         MEM_freeN(pa->rectz); pa->rectz= NULL;
1275         
1276         /* display active layer */
1277         rr->renrect.ymin=rr->renrect.ymax= 0;
1278         rr->renlay= render_get_active_layer(&R, rr);
1279 }
1280
1281
1282 /* ------------------------------------------------------------------------ */
1283
1284 /* non OSA case, full tile render */
1285 /* supposed to be fully threadable! */
1286 void zbufshade_tile(RenderPart *pa)
1287 {
1288         ShadeSample ssamp;
1289         RenderResult *rr= pa->result;
1290         RenderLayer *rl;
1291         PixStr ps;
1292         float *edgerect= NULL;
1293         
1294         /* fake pixel struct, to comply to osa render */
1295         ps.next= NULL;
1296         ps.mask= 0xFFFF;
1297         
1298         /* zbuffer code clears/inits rects */
1299         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1300         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1301         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1302
1303         for(rl= rr->layers.first; rl; rl= rl->next) {
1304                 if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
1305                         pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
1306
1307                 /* general shader info, passes */
1308                 shade_sample_initialize(&ssamp, pa, rl);
1309                 
1310                 zbuffer_solid(pa, rl, NULL, NULL);
1311                 
1312                 if(!R.test_break(R.tbh)) {      /* NOTE: this if() is not consistent */
1313                         
1314                         /* edges only for solid part, ztransp doesn't support it yet anti-aliased */
1315                         if(rl->layflag & SCE_LAY_EDGE) {
1316                                 if(R.r.mode & R_EDGE) {
1317                                         edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
1318                                         edge_enhance_tile(pa, edgerect, pa->rectz);
1319                                 }
1320                         }
1321                         
1322                         /* initialize scanline updates for main thread */
1323                         rr->renrect.ymin= 0;
1324                         rr->renlay= rl;
1325                         
1326                         if(rl->layflag & SCE_LAY_SOLID) {
1327                                 float *fcol= rl->rectf;
1328                                 int *ro= pa->recto, *rp= pa->rectp, *rz= pa->rectz;
1329                                 int x, y, offs=0, seed;
1330                                 
1331                                 /* we set per pixel a fixed seed, for random AO and shadow samples */
1332                                 seed= pa->rectx*pa->disprect.ymin;
1333                                 
1334                                 /* irregular shadowb buffer creation */
1335                                 if(R.r.mode & R_SHADOW)
1336                                         ISB_create(pa, NULL);
1337
1338                                 if(R.occlusiontree)
1339                                         cache_occ_samples(&R, pa, &ssamp);
1340                                 
1341                                 for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
1342                                         for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, ro++, rz++, rp++, fcol+=4, offs++) {
1343                                                 /* per pixel fixed seed */
1344                                                 BLI_thread_srandom(pa->thread, seed++);
1345                                                 
1346                                                 if(*rp) {
1347                                                         ps.obi= *ro;
1348                                                         ps.facenr= *rp;
1349                                                         ps.z= *rz;
1350                                                         if(shade_samples(&ssamp, &ps, x, y)) {
1351                                                                 /* combined and passes */
1352                                                                 add_passes(rl, offs, ssamp.shi, ssamp.shr);
1353                                                         }
1354                                                 }
1355                                         }
1356                                         if(y&1)
1357                                                 if(R.test_break(R.tbh)) break; 
1358                                 }
1359                                 
1360                                 if(R.occlusiontree)
1361                                         free_occ_samples(&R, pa);
1362                                 
1363                                 if(R.r.mode & R_SHADOW)
1364                                         ISB_free(pa);
1365                         }
1366                         
1367                         /* disable scanline updating */
1368                         rr->renlay= NULL;
1369                 }
1370                 
1371                 /* lamphalo after solid, before ztra, looks nicest because ztra does own halo */
1372                 if(R.flag & R_LAMPHALO)
1373                         if(rl->layflag & SCE_LAY_HALO)
1374                                 lamphalo_tile(pa, rl);
1375                 
1376                 /* halo before ztra, because ztra fills in zbuffer now */
1377                 if(R.flag & R_HALO)
1378                         if(rl->layflag & SCE_LAY_HALO)
1379                                 halo_tile(pa, rl);
1380                 
1381                 if(R.flag & R_ZTRA || R.totstrand) {
1382                         if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
1383                                 float *fcol, *acol;
1384                                 int x;
1385                                 
1386                                 /* allocate, but not free here, for asynchronous display of this rect in main thread */
1387                                 rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
1388                                 
1389                                 /* swap for live updates */
1390                                 SWAP(float *, rl->acolrect, rl->rectf);
1391                                 zbuffer_transp_shade(pa, rl, rl->rectf, NULL);
1392                                 SWAP(float *, rl->acolrect, rl->rectf);
1393                                 
1394                                 fcol= rl->rectf; acol= rl->acolrect;
1395                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
1396                                         addAlphaOverFloat(fcol, acol);
1397                                 }
1398                         }
1399                 }
1400                 
1401                 /* sun/sky */
1402                 if(rl->layflag & SCE_LAY_SKY)
1403                         atm_tile(pa, rl);
1404                 
1405                 /* sky before edge */
1406                 if(rl->layflag & SCE_LAY_SKY)
1407                         sky_tile(pa, rl);
1408                 
1409                 if(!R.test_break(R.tbh)) {
1410                         if(rl->layflag & SCE_LAY_EDGE) 
1411                                 if(R.r.mode & R_EDGE)
1412                                         edge_enhance_add(pa, rl->rectf, edgerect);
1413                 }
1414                 
1415                 if(rl->passflag & SCE_PASS_VECTOR)
1416                         reset_sky_speed(pa, rl);
1417                 
1418                 /* de-premul alpha */
1419                 if(R.r.alphamode & R_ALPHAKEY)
1420                         convert_to_key_alpha(pa, rl);
1421                 
1422                 if(edgerect) MEM_freeN(edgerect);
1423                 edgerect= NULL;
1424
1425                 if(pa->rectmask) {
1426                         MEM_freeN(pa->rectmask);
1427                         pa->rectmask= NULL;
1428                 }
1429         }
1430
1431         /* display active layer */
1432         rr->renrect.ymin=rr->renrect.ymax= 0;
1433         rr->renlay= render_get_active_layer(&R, rr);
1434         
1435         MEM_freeN(pa->recto); pa->recto= NULL;
1436         MEM_freeN(pa->rectp); pa->rectp= NULL;
1437         MEM_freeN(pa->rectz); pa->rectz= NULL;
1438 }
1439
1440 /* SSS preprocess tile render, fully threadable */
1441 typedef struct ZBufSSSHandle {
1442         RenderPart *pa;
1443         ListBase psmlist;
1444         int totps;
1445 } ZBufSSSHandle;
1446
1447 static void addps_sss(void *cb_handle, int obi, int facenr, int x, int y, int z)
1448 {
1449         ZBufSSSHandle *handle = cb_handle;
1450         RenderPart *pa= handle->pa;
1451
1452         /* extra border for filter gives double samples on part edges,
1453            don't use those */
1454         if(x<pa->crop || x>=pa->rectx-pa->crop)
1455                 return;
1456         if(y<pa->crop || y>=pa->recty-pa->crop)
1457                 return;
1458         
1459         if(pa->rectall) {
1460                 intptr_t *rs= pa->rectall + pa->rectx*y + x;
1461
1462                 addps(&handle->psmlist, rs, obi, facenr, z, 0, 0);
1463                 handle->totps++;
1464         }
1465         if(pa->rectz) {
1466                 int *rz= pa->rectz + pa->rectx*y + x;
1467                 int *rp= pa->rectp + pa->rectx*y + x;
1468                 int *ro= pa->recto + pa->rectx*y + x;
1469
1470                 if(z < *rz) {
1471                         if(*rp == 0)
1472                                 handle->totps++;
1473                         *rz= z;
1474                         *rp= facenr;
1475                         *ro= obi;
1476                 }
1477         }
1478         if(pa->rectbackz) {
1479                 int *rz= pa->rectbackz + pa->rectx*y + x;
1480                 int *rp= pa->rectbackp + pa->rectx*y + x;
1481                 int *ro= pa->rectbacko + pa->rectx*y + x;
1482
1483                 if(z >= *rz) {
1484                         if(*rp == 0)
1485                                 handle->totps++;
1486                         *rz= z;
1487                         *rp= facenr;
1488                         *ro= obi;
1489                 }
1490         }
1491 }
1492
1493 static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRen *obi, VlakRen *vlr, int quad, float x, float y, float z, float *co, float *color, float *area)
1494 {
1495         ShadeInput *shi= ssamp->shi;
1496         ShadeResult shr;
1497         float texfac, orthoarea, nor[3], alpha, sx, sy;
1498
1499         /* cache for shadow */
1500         shi->samplenr= R.shadowsamplenr[shi->thread]++;
1501         
1502         if(quad) 
1503                 shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
1504         else
1505                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
1506
1507         /* center pixel */
1508         sx = x + 0.5f;
1509         sy = y + 0.5f;
1510
1511         /* we estimate the area here using shi->dxco and shi->dyco. we need to
1512            enabled shi->osatex these are filled. we compute two areas, one with
1513            the normal pointed at the camera and one with the original normal, and
1514            then clamp to avoid a too large contribution from a single pixel */
1515         shi->osatex= 1;
1516
1517         VECCOPY(nor, shi->facenor);
1518         calc_view_vector(shi->facenor, sx, sy);
1519         normalize_v3(shi->facenor);
1520         shade_input_set_viewco(shi, x, y, sx, sy, z);
1521         orthoarea= len_v3(shi->dxco)*len_v3(shi->dyco);
1522
1523         VECCOPY(shi->facenor, nor);
1524         shade_input_set_viewco(shi, x, y, sx, sy, z);
1525         *area= len_v3(shi->dxco)*len_v3(shi->dyco);
1526         *area= MIN2(*area, 2.0f*orthoarea);
1527
1528         shade_input_set_uv(shi);
1529         shade_input_set_normals(shi);
1530
1531         /* we don't want flipped normals, they screw up back scattering */
1532         if(shi->flippednor)
1533                 shade_input_flip_normals(shi);
1534
1535         /* not a pretty solution, but fixes common cases */
1536         if(shi->obr->ob && shi->obr->ob->transflag & OB_NEG_SCALE) {
1537                 negate_v3(shi->vn);
1538                 negate_v3(shi->vno);
1539         }
1540
1541         /* if nodetree, use the material that we are currently preprocessing
1542            instead of the node material */
1543         if(shi->mat->nodetree && shi->mat->use_nodes)
1544                 shi->mat= mat;
1545
1546         /* init material vars */
1547         shade_input_init_material(shi);
1548         
1549         /* render */
1550         shade_input_set_shade_texco(shi);
1551         
1552         shade_samples_do_AO(ssamp);
1553         shade_material_loop(shi, &shr);
1554         
1555         VECCOPY(co, shi->co);
1556         VECCOPY(color, shr.combined);
1557
1558         /* texture blending */
1559         texfac= shi->mat->sss_texfac;
1560
1561         alpha= shr.combined[3];
1562         *area *= alpha;
1563 }
1564
1565 static void zbufshade_sss_free(RenderPart *pa)
1566 {
1567 #if 0
1568         MEM_freeN(pa->rectall); pa->rectall= NULL;
1569         freeps(&handle.psmlist);
1570 #else
1571         MEM_freeN(pa->rectz); pa->rectz= NULL;
1572         MEM_freeN(pa->rectp); pa->rectp= NULL;
1573         MEM_freeN(pa->recto); pa->recto= NULL;
1574         MEM_freeN(pa->rectbackz); pa->rectbackz= NULL;
1575         MEM_freeN(pa->rectbackp); pa->rectbackp= NULL;
1576         MEM_freeN(pa->rectbacko); pa->rectbacko= NULL;
1577 #endif
1578 }
1579
1580 void zbufshade_sss_tile(RenderPart *pa)
1581 {
1582         Render *re= &R;
1583         ShadeSample ssamp;
1584         ZBufSSSHandle handle;
1585         RenderResult *rr= pa->result;
1586         RenderLayer *rl;
1587         VlakRen *vlr;
1588         Material *mat= re->sss_mat;
1589         float (*co)[3], (*color)[3], *area, *fcol;
1590         int x, y, seed, quad, totpoint, display = !(re->r.scemode & R_PREVIEWBUTS);
1591         int *ro, *rz, *rp, *rbo, *rbz, *rbp, lay;
1592 #if 0
1593         PixStr *ps;
1594         intptr_t *rs;
1595         int z;
1596 #endif
1597
1598         /* setup pixelstr list and buffer for zbuffering */
1599         handle.pa= pa;
1600         handle.totps= 0;
1601
1602 #if 0
1603         handle.psmlist.first= handle.psmlist.last= NULL;
1604         addpsmain(&handle.psmlist);
1605
1606         pa->rectall= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "rectall");
1607 #else
1608         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1609         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1610         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1611         pa->rectbacko= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbacko");
1612         pa->rectbackp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackp");
1613         pa->rectbackz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackz");
1614 #endif
1615
1616         /* setup shade sample with correct passes */
1617         memset(&ssamp, 0, sizeof(ssamp));
1618         shade_sample_initialize(&ssamp, pa, rr->layers.first);
1619         ssamp.tot= 1;
1620         
1621         for(rl=rr->layers.first; rl; rl=rl->next) {
1622                 ssamp.shi[0].lay |= rl->lay;
1623                 ssamp.shi[0].layflag |= rl->layflag;
1624                 ssamp.shi[0].passflag |= rl->passflag;
1625                 ssamp.shi[0].combinedflag |= ~rl->pass_xor;
1626         }
1627
1628         rl= rr->layers.first;
1629         ssamp.shi[0].passflag |= SCE_PASS_RGBA|SCE_PASS_COMBINED;
1630         ssamp.shi[0].combinedflag &= ~(SCE_PASS_SPEC);
1631         ssamp.shi[0].mat_override= NULL;
1632         ssamp.shi[0].light_override= NULL;
1633         lay= ssamp.shi[0].lay;
1634
1635         /* create the pixelstrs to be used later */
1636         zbuffer_sss(pa, lay, &handle, addps_sss);
1637
1638         if(handle.totps==0) {
1639                 zbufshade_sss_free(pa);
1640                 return;
1641         }
1642         
1643         fcol= rl->rectf;
1644
1645         co= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSCo");
1646         color= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSColor");
1647         area= MEM_mallocN(sizeof(float)*handle.totps, "SSSArea");
1648
1649 #if 0
1650         /* create ISB (does not work currently!) */
1651         if(re->r.mode & R_SHADOW)
1652                 ISB_create(pa, NULL);
1653 #endif
1654
1655         if(display) {
1656                 /* initialize scanline updates for main thread */
1657                 rr->renrect.ymin= 0;
1658                 rr->renlay= rl;
1659         }
1660         
1661         seed= pa->rectx*pa->disprect.ymin;
1662 #if 0
1663         rs= pa->rectall;
1664 #else
1665         rz= pa->rectz;
1666         rp= pa->rectp;
1667         ro= pa->recto;
1668         rbz= pa->rectbackz;
1669         rbp= pa->rectbackp;
1670         rbo= pa->rectbacko;
1671 #endif
1672         totpoint= 0;
1673
1674         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
1675                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, fcol+=4) {
1676                         /* per pixel fixed seed */
1677                         BLI_thread_srandom(pa->thread, seed++);
1678                         
1679 #if 0
1680                         if(rs) {
1681                                 /* for each sample in this pixel, shade it */
1682                                 for(ps=(PixStr*)*rs; ps; ps=ps->next) {
1683                                         ObjectInstanceRen *obi= &re->objectinstance[ps->obi];
1684                                         ObjectRen *obr= obi->obr;
1685                                         vlr= RE_findOrAddVlak(obr, (ps->facenr-1) & RE_QUAD_MASK);
1686                                         quad= (ps->facenr & RE_QUAD_OFFS);
1687                                         z= ps->z;
1688
1689                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, z,
1690                                                 co[totpoint], color[totpoint], &area[totpoint]);
1691
1692                                         totpoint++;
1693
1694                                         VECADD(fcol, fcol, color);
1695                                         fcol[3]= 1.0f;
1696                                 }
1697
1698                                 rs++;
1699                         }
1700 #else
1701                         if(rp) {
1702                                 if(*rp != 0) {
1703                                         ObjectInstanceRen *obi= &re->objectinstance[*ro];
1704                                         ObjectRen *obr= obi->obr;
1705
1706                                         /* shade front */
1707                                         vlr= RE_findOrAddVlak(obr, (*rp-1) & RE_QUAD_MASK);
1708                                         quad= ((*rp) & RE_QUAD_OFFS);
1709
1710                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, *rz,
1711                                                 co[totpoint], color[totpoint], &area[totpoint]);
1712                                         
1713                                         VECADD(fcol, fcol, color[totpoint]);
1714                                         fcol[3]= 1.0f;
1715                                         totpoint++;
1716                                 }
1717
1718                                 rp++; rz++; ro++;
1719                         }
1720
1721                         if(rbp) {
1722                                 if(*rbp != 0 && !(*rbp == *(rp-1) && *rbo == *(ro-1))) {
1723                                         ObjectInstanceRen *obi= &re->objectinstance[*rbo];
1724                                         ObjectRen *obr= obi->obr;
1725
1726                                         /* shade back */
1727                                         vlr= RE_findOrAddVlak(obr, (*rbp-1) & RE_QUAD_MASK);
1728                                         quad= ((*rbp) & RE_QUAD_OFFS);
1729
1730                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, *rbz,
1731                                                 co[totpoint], color[totpoint], &area[totpoint]);
1732                                         
1733                                         /* to indicate this is a back sample */
1734                                         area[totpoint]= -area[totpoint];
1735
1736                                         VECADD(fcol, fcol, color[totpoint]);
1737                                         fcol[3]= 1.0f;
1738                                         totpoint++;
1739                                 }
1740
1741                                 rbz++; rbp++; rbo++;
1742                         }
1743 #endif
1744                 }
1745
1746                 if(y&1)
1747                         if(re->test_break(re->tbh)) break; 
1748         }
1749
1750         /* note: after adding we do not free these arrays, sss keeps them */
1751         if(totpoint > 0) {
1752                 sss_add_points(re, co, color, area, totpoint);
1753         }
1754         else {
1755                 MEM_freeN(co);
1756                 MEM_freeN(color);
1757                 MEM_freeN(area);
1758         }
1759         
1760 #if 0
1761         if(re->r.mode & R_SHADOW)
1762                 ISB_free(pa);
1763 #endif
1764                 
1765         if(display) {
1766                 /* display active layer */
1767                 rr->renrect.ymin=rr->renrect.ymax= 0;
1768                 rr->renlay= render_get_active_layer(&R, rr);
1769         }
1770         
1771         zbufshade_sss_free(pa);
1772 }
1773
1774 /* ------------------------------------------------------------------------ */
1775
1776 static void renderhalo_post(RenderResult *rr, float *rectf, HaloRen *har)       /* postprocess version */
1777 {
1778         float dist, xsq, ysq, xn, yn, colf[4], *rectft, *rtf;
1779         float haloxs, haloys;
1780         int minx, maxx, miny, maxy, x, y;
1781
1782         /* calculate the disprect mapped coordinate for halo. note: rectx is disprect corrected */
1783         haloxs= har->xs - R.disprect.xmin;
1784         haloys= har->ys - R.disprect.ymin;
1785         
1786         har->miny= miny= haloys - har->rad/R.ycor;
1787         har->maxy= maxy= haloys + har->rad/R.ycor;
1788         
1789         if(maxy<0);
1790         else if(rr->recty<miny);
1791         else {
1792                 minx= floor(haloxs-har->rad);
1793                 maxx= ceil(haloxs+har->rad);
1794                         
1795                 if(maxx<0);
1796                 else if(rr->rectx<minx);
1797                 else {
1798                 
1799                         if(minx<0) minx= 0;
1800                         if(maxx>=rr->rectx) maxx= rr->rectx-1;
1801                         if(miny<0) miny= 0;
1802                         if(maxy>rr->recty) maxy= rr->recty;
1803         
1804                         rectft= rectf+ 4*rr->rectx*miny;
1805
1806                         for(y=miny; y<maxy; y++) {
1807         
1808                                 rtf= rectft+4*minx;
1809                                 
1810                                 yn= (y - haloys)*R.ycor;
1811                                 ysq= yn*yn;
1812                                 
1813                                 for(x=minx; x<=maxx; x++) {
1814                                         xn= x - haloxs;
1815                                         xsq= xn*xn;
1816                                         dist= xsq+ysq;
1817                                         if(dist<har->radsq) {
1818                                                 
1819                                                 if(shadeHaloFloat(har, colf, 0x7FFFFF, dist, xn, yn, har->flarec))
1820                                                         addalphaAddfacFloat(rtf, colf, har->add);
1821                                         }
1822                                         rtf+=4;
1823                                 }
1824         
1825                                 rectft+= 4*rr->rectx;
1826                                 
1827                                 if(R.test_break(R.tbh)) break; 
1828                         }
1829                 }
1830         }
1831
1832 /* ------------------------------------------------------------------------ */
1833
1834 static void renderflare(RenderResult *rr, float *rectf, HaloRen *har)
1835 {
1836         extern float hashvectf[];
1837         HaloRen fla;
1838         Material *ma;
1839         float *rc, rad, alfa, visifac, vec[3];
1840         int b, type;
1841         
1842         fla= *har;
1843         fla.linec= fla.ringc= fla.flarec= 0;
1844         
1845         rad= har->rad;
1846         alfa= har->alfa;
1847         
1848         visifac= R.ycor*(har->pixels);
1849         /* all radials added / r^3  == 1.0f! */
1850         visifac /= (har->rad*har->rad*har->rad);
1851         visifac*= visifac;
1852
1853         ma= har->mat;
1854         
1855         /* first halo: just do */
1856         
1857         har->rad= rad*ma->flaresize*visifac;
1858         har->radsq= har->rad*har->rad;
1859         har->zs= fla.zs= 0;
1860         
1861         har->alfa= alfa*visifac;
1862
1863         renderhalo_post(rr, rectf, har);
1864         
1865         /* next halo's: the flares */
1866         rc= hashvectf + ma->seed2;
1867         
1868         for(b=1; b<har->flarec; b++) {
1869                 
1870                 fla.r= fabs(rc[0]);
1871                 fla.g= fabs(rc[1]);
1872                 fla.b= fabs(rc[2]);
1873                 fla.alfa= ma->flareboost*fabs(alfa*visifac*rc[3]);
1874                 fla.hard= 20.0f + fabs(70*rc[7]);
1875                 fla.tex= 0;
1876                 
1877                 type= (int)(fabs(3.9*rc[6]));
1878
1879                 fla.rad= ma->subsize*sqrt(fabs(2.0f*har->rad*rc[4]));
1880                 
1881                 if(type==3) {
1882                         fla.rad*= 3.0f;
1883                         fla.rad+= R.rectx/10;
1884                 }
1885                 
1886                 fla.radsq= fla.rad*fla.rad;
1887                 
1888                 vec[0]= 1.4*rc[5]*(har->xs-R.winx/2);
1889                 vec[1]= 1.4*rc[5]*(har->ys-R.winy/2);
1890                 vec[2]= 32.0f*sqrt(vec[0]*vec[0] + vec[1]*vec[1] + 1.0f);
1891                 
1892                 fla.xs= R.winx/2 + vec[0] + (1.2+rc[8])*R.rectx*vec[0]/vec[2];
1893                 fla.ys= R.winy/2 + vec[1] + (1.2+rc[8])*R.rectx*vec[1]/vec[2];
1894
1895                 if(R.flag & R_SEC_FIELD) {
1896                         if(R.r.mode & R_ODDFIELD) fla.ys += 0.5;
1897                         else fla.ys -= 0.5;
1898                 }
1899                 if(type & 1) fla.type= HA_FLARECIRC;
1900                 else fla.type= 0;
1901                 renderhalo_post(rr, rectf, &fla);
1902
1903                 fla.alfa*= 0.5;
1904                 if(type & 2) fla.type= HA_FLARECIRC;
1905                 else fla.type= 0;
1906                 renderhalo_post(rr, rectf, &fla);
1907                 
1908                 rc+= 7;
1909         }
1910 }
1911
1912 /* needs recode... integrate this better! */
1913 void add_halo_flare(Render *re)
1914 {
1915         RenderResult *rr= re->result;
1916         RenderLayer *rl;
1917         HaloRen *har;
1918         int a, mode, do_draw=0;
1919         
1920         /* for now, we get the first renderlayer in list with halos set */
1921         for(rl= rr->layers.first; rl; rl= rl->next)
1922                 if(rl->layflag & SCE_LAY_HALO)
1923                         break;
1924
1925         if(rl==NULL || rl->rectf==NULL)
1926                 return;
1927         
1928         mode= R.r.mode;
1929         R.r.mode &= ~R_PANORAMA;
1930         
1931         project_renderdata(&R, projectverto, 0, 0, 0);
1932         
1933         for(a=0; a<R.tothalo; a++) {
1934                 har= R.sortedhalos[a];
1935                 
1936                 if(har->flarec) {
1937                         do_draw= 1;
1938                         renderflare(rr, rl->rectf, har);
1939                 }
1940         }
1941
1942         if(do_draw) {
1943                 /* weak... the display callback wants an active renderlayer pointer... */
1944                 rr->renlay= rl;
1945                 re->display_draw(re->ddh, rr, NULL);
1946         }
1947         
1948         R.r.mode= mode; 
1949 }
1950
1951 /* ************************* used for shaded view ************************ */
1952
1953 /* if *re, then initialize, otherwise execute */
1954 void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
1955 {
1956         static VlakRen vlr;
1957         static ObjectRen obr;
1958         static ObjectInstanceRen obi;
1959         
1960         /* init */
1961         if(re) {
1962                 R= *re;
1963                 
1964                 /* fake render face */
1965                 memset(&vlr, 0, sizeof(VlakRen));
1966                 memset(&obr, 0, sizeof(ObjectRen));
1967                 memset(&obi, 0, sizeof(ObjectInstanceRen));
1968                 obr.lay= -1;
1969                 obi.obr= &obr;
1970                 
1971                 return;
1972         }
1973         shi->vlr= &vlr;
1974         shi->obr= &obr;
1975         shi->obi= &obi;
1976         
1977         if(shi->mat->nodetree && shi->mat->use_nodes)
1978                 ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
1979         else {
1980                 shade_input_init_material(shi);
1981                 shade_material_loop(shi, shr);
1982         }
1983 }
1984
1985 /* ************************* bake ************************ */
1986
1987
1988 typedef struct BakeShade {
1989         ShadeSample ssamp;
1990         ObjectInstanceRen *obi;
1991         VlakRen *vlr;
1992         
1993         ZSpan *zspan;
1994         Image *ima;
1995         ImBuf *ibuf;
1996         
1997         int rectx, recty, quad, type, vdone, ready;
1998
1999         float dir[3];
2000         Object *actob;
2001         
2002         unsigned int *rect;
2003         float *rect_float;
2004         
2005         int usemask;
2006         char *rect_mask; /* bake pixel mask */
2007
2008         float dxco[3], dyco[3];
2009
2010         short *do_update;
2011 } BakeShade;
2012
2013 /* bake uses a char mask to know what has been baked */
2014 #define BAKE_MASK_NULL          0
2015 #define BAKE_MASK_MARGIN        1
2016 #define BAKE_MASK_BAKED         2
2017 static void bake_mask_filter_extend( char *mask, int width, int height )
2018 {
2019         char *row1, *row2, *row3;
2020         int rowlen, x, y;
2021         char *temprect;
2022         
2023         rowlen= width;
2024         
2025         /* make a copy, to prevent flooding */
2026         temprect= MEM_dupallocN(mask);
2027         
2028         for(y=1; y<=height; y++) {
2029                 /* setup rows */
2030                 row1= (char *)(temprect + (y-2)*rowlen);
2031                 row2= row1 + rowlen;
2032                 row3= row2 + rowlen;
2033                 if(y==1)
2034                         row1= row2;
2035                 else if(y==height)
2036                         row3= row2;
2037                 
2038                 for(x=0; x<rowlen; x++) {
2039                         if (mask[((y-1)*rowlen)+x]==0) {
2040                                 if (*row1 || *row2 || *row3 || *(row1+1) || *(row3+1) ) {
2041                                         mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
2042                                 } else if((x!=rowlen-1) && (*(row1+2) || *(row2+2) || *(row3+2)) ) {
2043                                         mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
2044                                 }
2045                         }
2046                         
2047                         if(x!=0) {
2048                                 row1++; row2++; row3++;
2049                         }
2050                 }
2051         }
2052         MEM_freeN(temprect);
2053 }
2054
2055 static void bake_mask_clear( ImBuf *ibuf, char *mask, char val )
2056 {
2057         int x,y;
2058         if (ibuf->rect_float) {
2059                 for(x=0; x<ibuf->x; x++) {
2060                         for(y=0; y<ibuf->y; y++) {
2061                                 if (mask[ibuf->x*y + x] == val) {
2062                                         float *col= ibuf->rect_float + 4*(ibuf->x*y + x);
2063                                         col[0] = col[1] = col[2] = col[3] = 0.0f;
2064                                 }
2065                         }
2066                 }
2067                 
2068         } else {
2069                 /* char buffer */
2070                 for(x=0; x<ibuf->x; x++) {
2071                         for(y=0; y<ibuf->y; y++) {
2072                                 if (mask[ibuf->x*y + x] == val) {
2073                                         char *col= (char *)(ibuf->rect + ibuf->x*y + x);
2074                                         col[0] = col[1] = col[2] = col[3] = 0;
2075                                 }
2076                         }
2077                 }
2078         }
2079 }
2080
2081 static void bake_set_shade_input(ObjectInstanceRen *obi, VlakRen *vlr, ShadeInput *shi, int quad, int isect, int x, int y, float u, float v)
2082 {
2083         if(isect) {
2084                 /* raytrace intersection with different u,v than scanconvert */
2085                 if(vlr->v4) {
2086                         if(quad)
2087                                 shade_input_set_triangle_i(shi, obi, vlr, 2, 1, 3);
2088                         else
2089                                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 3);
2090                 }
2091                 else
2092                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
2093         }
2094         else {
2095                 /* regular scanconvert */
2096                 if(quad) 
2097                         shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
2098                 else
2099                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
2100         }
2101                 
2102         /* cache for shadow */
2103         shi->samplenr= R.shadowsamplenr[shi->thread]++;
2104
2105         shi->mask= 0xFFFF; /* all samples */
2106         
2107         shi->u= -u;
2108         shi->v= -v;
2109         shi->xs= x;
2110         shi->ys= y;
2111         
2112         shade_input_set_uv(shi);
2113         shade_input_set_normals(shi);
2114
2115         /* no normal flip */
2116         if(shi->flippednor)
2117                 shade_input_flip_normals(shi);
2118
2119         /* set up view vector to look right at the surface (note that the normal
2120          * is negated in the renderer so it does not need to be done here) */
2121         shi->view[0]= shi->vn[0];
2122         shi->view[1]= shi->vn[1];
2123         shi->view[2]= shi->vn[2];
2124 }
2125
2126 static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int x, int y, float u, float v, float *tvn, float *ttang)
2127 {
2128         BakeShade *bs= handle;
2129         ShadeSample *ssamp= &bs->ssamp;
2130         ShadeResult shr;
2131         VlakRen *vlr= shi->vlr;
2132         
2133         shade_input_init_material(shi);
2134         
2135         if(bs->type==RE_BAKE_AO) {
2136                 ambient_occlusion(shi);
2137
2138                 VECCOPY(shr.combined, shi->ao)
2139         }
2140         else {
2141                 if (bs->type==RE_BAKE_SHADOW) /* Why do shadows set the color anyhow?, ignore material color for baking */
2142                         shi->r = shi->g = shi->b = 1.0f;
2143         
2144                 shade_input_set_shade_texco(shi);
2145                 
2146                 if(!ELEM3(bs->type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_SHADOW))
2147                         shade_samples_do_AO(ssamp);
2148                 
2149                 if(shi->mat->nodetree && shi->mat->use_nodes) {
2150                         ntreeShaderExecTree(shi->mat->nodetree, shi, &shr);
2151                         shi->mat= vlr->mat;             /* shi->mat is being set in nodetree */
2152                 }
2153                 else
2154                         shade_material_loop(shi, &shr);
2155                 
2156                 if(bs->type==RE_BAKE_NORMALS) {
2157                         float nor[3];
2158
2159                         VECCOPY(nor, shi->vn);
2160
2161                         if(R.r.bake_normal_space == R_BAKE_SPACE_CAMERA);
2162                         else if(R.r.bake_normal_space == R_BAKE_SPACE_TANGENT) {
2163                                 float mat[3][3], imat[3][3];
2164
2165                                 /* bitangent */
2166                                 if(tvn && ttang) {
2167                                         VECCOPY(mat[0], ttang);
2168                                         cross_v3_v3v3(mat[1], tvn, ttang);
2169                                         VECCOPY(mat[2], tvn);
2170                                 }
2171                                 else {
2172                                         VECCOPY(mat[0], shi->nmaptang);
2173                                         cross_v3_v3v3(mat[1], shi->vn, shi->nmaptang);
2174                                         VECCOPY(mat[2], shi->vn);
2175                                 }
2176
2177                                 invert_m3_m3(imat, mat);
2178                                 mul_m3_v3(imat, nor);
2179                         }
2180                         else if(R.r.bake_normal_space == R_BAKE_SPACE_OBJECT)
2181                                 mul_mat3_m4_v3(ob->imat, nor); /* ob->imat includes viewinv! */
2182                         else if(R.r.bake_normal_space == R_BAKE_SPACE_WORLD)
2183                                 mul_mat3_m4_v3(R.viewinv, nor);
2184
2185                         normalize_v3(nor); /* in case object has scaling */
2186
2187                         shr.combined[0]= nor[0]/2.0f + 0.5f;
2188                         shr.combined[1]= 0.5f - nor[1]/2.0f;
2189                         shr.combined[2]= nor[2]/2.0f + 0.5f;
2190                 }
2191                 else if(bs->type==RE_BAKE_TEXTURE) {
2192                         shr.combined[0]= shi->r;
2193                         shr.combined[1]= shi->g;
2194                         shr.combined[2]= shi->b;
2195                         shr.alpha = shi->alpha;
2196                 }
2197                 else if(bs->type==RE_BAKE_SHADOW) {
2198                         VECCOPY(shr.combined, shr.shad);
2199                         shr.alpha = shi->alpha;
2200                 }
2201         }
2202         
2203         if(bs->rect_float) {
2204                 float *col= bs->rect_float + 4*(bs->rectx*y + x);
2205                 VECCOPY(col, shr.combined);
2206                 if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
2207                         col[3]= shr.alpha;
2208                 } else {
2209                         col[3]= 1.0;
2210                 }
2211         }
2212         else {
2213                 char *col= (char *)(bs->rect + bs->rectx*y + x);
2214                 col[0]= FTOCHAR(shr.combined[0]);
2215                 col[1]= FTOCHAR(shr.combined[1]);
2216                 col[2]= FTOCHAR(shr.combined[2]);
2217                 
2218                 
2219                 if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
2220                         col[3]= FTOCHAR(shr.alpha);
2221                 } else {
2222                         col[3]= 255;
2223                 }
2224         }
2225         
2226         if (bs->rect_mask) {
2227                 bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
2228         }
2229 }
2230
2231 static void bake_displacement(void *handle, ShadeInput *shi, float dist, int x, int y)
2232 {
2233         BakeShade *bs= handle;
2234         float disp;
2235         
2236         if(R.r.bake_flag & R_BAKE_NORMALIZE && R.r.bake_maxdist) {
2237                 disp = (dist+R.r.bake_maxdist) / (R.r.bake_maxdist*2); /* alter the range from [-bake_maxdist, bake_maxdist] to [0, 1]*/
2238         } else {
2239                 disp = 0.5 + dist; /* alter the range from [-0.5,0.5] to [0,1]*/
2240         }
2241         
2242         if(bs->rect_float) {
2243                 float *col= bs->rect_float + 4*(bs->rectx*y + x);
2244                 col[0] = col[1] = col[2] = disp;
2245                 col[3]= 1.0f;
2246         } else {        
2247                 char *col= (char *)(bs->rect + bs->rectx*y + x);
2248                 col[0]= FTOCHAR(disp);
2249                 col[1]= FTOCHAR(disp);
2250                 col[2]= FTOCHAR(disp);
2251                 col[3]= 255;
2252         }
2253         if (bs->rect_mask) {
2254                 bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
2255         }
2256 }
2257
2258 #if 0
2259 static int bake_check_intersect(Isect *is, int ob, RayFace *face)
2260 {
2261         BakeShade *bs = (BakeShade*)is->userdata;
2262         
2263         /* no direction checking for now, doesn't always improve the result
2264          * (INPR(shi->facenor, bs->dir) > 0.0f); */
2265
2266         return (R.objectinstance[ob & ~RE_RAY_TRANSFORM_OFFS].obr->ob != bs->actob);
2267 }
2268 #endif
2269
2270 static int bake_intersect_tree(RayObject* raytree, Isect* isect, float *start, float *dir, float sign, float *hitco, float *dist)
2271 {
2272         //TODO, validate against blender 2.4x, results may have changed.
2273         float maxdist;
2274         int hit;
2275
2276         /* might be useful to make a user setting for maxsize*/
2277         if(R.r.bake_maxdist > 0.0f)
2278                 maxdist= R.r.bake_maxdist;
2279         else
2280                 maxdist= FLT_MAX + R.r.bake_biasdist;
2281         
2282         /* 'dir' is always normalized */
2283         VECADDFAC(isect->start, start, dir, -R.r.bake_biasdist);                                        
2284
2285         isect->vec[0] = dir[0]*maxdist*sign;
2286         isect->vec[1] = dir[1]*maxdist*sign;
2287         isect->vec[2] = dir[2]*maxdist*sign;
2288
2289         isect->labda = maxdist;
2290
2291         /* TODO, 2.4x had this...
2292         hit = RE_ray_tree_intersect_check(R.raytree, isect, bake_check_intersect);
2293         ...the active object may NOT be ignored in some cases.
2294         */
2295         hit = RE_rayobject_raycast(raytree, isect);
2296         if(hit) {
2297                 hitco[0] = isect->start[0] + isect->labda*isect->vec[0];
2298                 hitco[1] = isect->start[1] + isect->labda*isect->vec[1];
2299                 hitco[2] = isect->start[2] + isect->labda*isect->vec[2];
2300
2301                 *dist= len_v3v3(start, hitco);
2302         }
2303
2304         return hit;
2305 }
2306
2307 static void bake_set_vlr_dxyco(BakeShade *bs, float *uv1, float *uv2, float *uv3)
2308 {
2309         VlakRen *vlr= bs->vlr;
2310         float A, d1, d2, d3, *v1, *v2, *v3;
2311
2312         if(bs->quad) {
2313                 v1= vlr->v1->co;
2314                 v2= vlr->v3->co;
2315                 v3= vlr->v4->co;
2316         }
2317         else {
2318                 v1= vlr->v1->co;
2319                 v2= vlr->v2->co;
2320                 v3= vlr->v3->co;
2321         }
2322
2323         /* formula derived from barycentric coordinates:
2324          * (uvArea1*v1 + uvArea2*v2 + uvArea3*v3)/uvArea
2325          * then taking u and v partial derivatives to get dxco and dyco */
2326         A= (uv2[0] - uv1[0])*(uv3[1] - uv1[1]) - (uv3[0] - uv1[0])*(uv2[1] - uv1[1]);
2327
2328         if(fabs(A) > FLT_EPSILON) {
2329                 A= 0.5f/A;
2330
2331                 d1= uv2[1] - uv3[1];
2332                 d2= uv3[1] - uv1[1];
2333                 d3= uv1[1] - uv2[1];
2334                 bs->dxco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
2335                 bs->dxco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
2336                 bs->dxco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
2337
2338                 d1= uv3[0] - uv2[0];
2339                 d2= uv1[0] - uv3[0];
2340                 d3= uv2[0] - uv1[0];
2341                 bs->dyco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
2342                 bs->dyco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
2343                 bs->dyco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
2344         }
2345         else {
2346                 bs->dxco[0]= bs->dxco[1]= bs->dxco[2]= 0.0f;
2347                 bs->dyco[0]= bs->dyco[1]= bs->dyco[2]= 0.0f;
2348         }
2349
2350         if(bs->obi->flag & R_TRANSFORMED) {
2351                 mul_m3_v3(bs->obi->nmat, bs->dxco);
2352                 mul_m3_v3(bs->obi->nmat, bs->dyco);
2353         }
2354 }
2355
2356 static void do_bake_shade(void *handle, int x, int y, float u, float v)
2357 {
2358         BakeShade *bs= handle;
2359         VlakRen *vlr= bs->vlr;
2360         ObjectInstanceRen *obi= bs->obi;
2361         Object *ob= obi->obr->ob;
2362         float l, *v1, *v2, *v3, tvn[3], ttang[3];
2363         int quad;
2364         ShadeSample *ssamp= &bs->ssamp;
2365         ShadeInput *shi= ssamp->shi;
2366         
2367         /* fast threadsafe break test */
2368         if(R.test_break(R.tbh))
2369                 return;
2370         
2371         /* setup render coordinates */
2372         if(bs->quad) {
2373                 v1= vlr->v1->co;
2374                 v2= vlr->v3->co;
2375                 v3= vlr->v4->co;
2376         }
2377         else {
2378                 v1= vlr->v1->co;
2379                 v2= vlr->v2->co;
2380                 v3= vlr->v3->co;
2381         }
2382         
2383         /* renderco */
2384         l= 1.0f-u-v;
2385         
2386         shi->co[0]= l*v3[0]+u*v1[0]+v*v2[0];
2387         shi->co[1]= l*v3[1]+u*v1[1]+v*v2[1];
2388         shi->co[2]= l*v3[2]+u*v1[2]+v*v2[2];
2389         
2390         if(obi->flag & R_TRANSFORMED)
2391                 mul_m4_v3(obi->mat, shi->co);
2392         
2393         VECCOPY(shi->dxco, bs->dxco);
2394         VECCOPY(shi->dyco, bs->dyco);
2395
2396         quad= bs->quad;
2397         bake_set_shade_input(obi, vlr, shi, quad, 0, x, y, u, v);
2398
2399         if(bs->type==RE_BAKE_NORMALS && R.r.bake_normal_space==R_BAKE_SPACE_TANGENT) {
2400                 shade_input_set_shade_texco(shi);
2401                 VECCOPY(tvn, shi->vn);
2402                 VECCOPY(ttang, shi->nmaptang);
2403         }
2404
2405         /* if we are doing selected to active baking, find point on other face */
2406         if(bs->actob) {
2407                 Isect isec, minisec;
2408                 float co[3], minco[3], dist, mindist=0.0f;
2409                 int hit, sign, dir=1;
2410                 
2411                 /* intersect with ray going forward and backward*/
2412                 hit= 0;
2413                 memset(&minisec, 0, sizeof(minisec));
2414                 minco[0]= minco[1]= minco[2]= 0.0f;
2415                 
2416                 VECCOPY(bs->dir, shi->vn);
2417                 
2418                 for(sign=-1; sign<=1; sign+=2) {
2419                         memset(&isec, 0, sizeof(isec));
2420                         isec.mode= RE_RAY_MIRROR;
2421
2422                         isec.orig.ob   = obi;
2423                         isec.orig.face = vlr;
2424                         isec.userdata= bs;
2425                         
2426                         if(bake_intersect_tree(R.raytree, &isec, shi->co, shi->vn, sign, co, &dist)) {
2427                                 if(!hit || len_v3v3(shi->co, co) < len_v3v3(shi->co, minco)) {
2428                                         minisec= isec;
2429                                         mindist= dist;
2430                                         VECCOPY(minco, co);
2431                                         hit= 1;
2432                                         dir = sign;
2433                                 }
2434                         }
2435                 }
2436
2437                 if (bs->type==RE_BAKE_DISPLACEMENT) {
2438                         if(hit)
2439                                 bake_displacement(handle, shi, (dir==-1)? mindist:-mindist, x, y);
2440                         else
2441                                 bake_displacement(handle, shi, 0.0f, x, y);
2442                         return;
2443                 }
2444
2445                 /* if hit, we shade from the new point, otherwise from point one starting face */
2446                 if(hit) {
2447                         obi= (ObjectInstanceRen*)minisec.hit.ob;
2448                         vlr= (VlakRen*)minisec.hit.face;
2449                         quad= (minisec.isect == 2);
2450                         VECCOPY(shi->co, minco);
2451                         
2452                         u= -minisec.u;
2453                         v= -minisec.v;
2454                         bake_set_shade_input(obi, vlr, shi, quad, 1, x, y, u, v);
2455                 }
2456         }
2457
2458         if(bs->type==RE_BAKE_NORMALS && R.r.bake_normal_space==R_BAKE_SPACE_TANGENT)
2459                 bake_shade(handle, ob, shi, quad, x, y, u, v, tvn, ttang);
2460         else
2461                 bake_shade(handle, ob, shi, quad, x, y, u, v, 0, 0);
2462 }
2463
2464 static int get_next_bake_face(BakeShade *bs)
2465 {
2466         ObjectRen *obr;
2467         VlakRen *vlr;
2468         MTFace *tface;
2469         static int v= 0, vdone= 0;
2470         static ObjectInstanceRen *obi= NULL;
2471         
2472         if(bs==NULL) {
2473                 vlr= NULL;
2474                 v= vdone= 0;
2475                 obi= R.instancetable.first;
2476                 return 0;
2477         }
2478         
2479         BLI_lock_thread(LOCK_CUSTOM1);  
2480
2481         for(; obi; obi=obi->next, v=0) {
2482                 obr= obi->obr;
2483
2484                 for(; v<obr->totvlak; v++) {
2485                         vlr= RE_findOrAddVlak(obr, v);
2486
2487                         if((bs->actob && bs->actob == obr->ob) || (!bs->actob && (obr->ob->flag & SELECT))) {
2488                                 tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
2489
2490                                 if(tface && tface->tpage) {
2491                                         Image *ima= tface->tpage;
2492                                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
2493                                         float vec[4]= {0.0f, 0.0f, 0.0f, 0.0f};
2494                                         
2495                                         if(ibuf==NULL)
2496                                                 continue;
2497                                         
2498                                         if(ibuf->rect==NULL && ibuf->rect_float==NULL)
2499                                                 continue;
2500                                         
2501                                         if(ibuf->rect_float && !(ibuf->channels==0 || ibuf->channels==4))
2502                                                 continue;
2503                                         
2504                                         /* find the image for the first time? */
2505                                         if(ima->id.flag & LIB_DOIT) {
2506                                                 ima->id.flag &= ~LIB_DOIT;
2507                                                 
2508                                                 /* we either fill in float or char, this ensures things go fine */
2509                                                 if(ibuf->rect_float)
2510                                                         imb_freerectImBuf(ibuf);
2511                                                 /* clear image */
2512                                                 if(R.r.bake_flag & R_BAKE_CLEAR)
2513                                                         IMB_rectfill(ibuf, vec);
2514                                         
2515                                                 /* might be read by UI to set active image for display */
2516                                                 R.bakebuf= ima;
2517                                         }                               
2518                                         
2519                                         bs->obi= obi;
2520                                         bs->vlr= vlr;
2521                                         
2522                                         bs->vdone++;    /* only for error message if nothing was rendered */
2523                                         v++;
2524                                         
2525                                         BLI_unlock_thread(LOCK_CUSTOM1);
2526                                         return 1;
2527                                 }
2528                         }
2529                 }
2530         }
2531         
2532         BLI_unlock_thread(LOCK_CUSTOM1);
2533         return 0;
2534 }
2535
2536 /* already have tested for tface and ima and zspan */
2537 static void shade_tface(BakeShade *bs)
2538 {
2539         VlakRen *vlr= bs->vlr;
2540         ObjectInstanceRen *obi= bs->obi;
2541         ObjectRen *obr= obi->obr;
2542         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
2543         Image *ima= tface->tpage;
2544         float vec[4][2];
2545         int a, i1, i2, i3;
2546         
2547         /* check valid zspan */
2548         if(ima!=bs->ima) {
2549                 bs->ima= ima;
2550                 bs->ibuf= BKE_image_get_ibuf(ima, NULL);
2551                 /* note, these calls only free/fill contents of zspan struct, not zspan itself */
2552                 zbuf_free_span(bs->zspan);
2553                 zbuf_alloc_span(bs->zspan, bs->ibuf->x, bs->ibuf->y, R.clipcrop);
2554         }                               
2555         
2556         bs->rectx= bs->ibuf->x;
2557         bs->recty= bs->ibuf->y;
2558         bs->rect= bs->ibuf->rect;
2559         bs->rect_float= bs->ibuf->rect_float;
2560         bs->quad= 0;
2561         
2562         if (bs->usemask) {
2563                 if (bs->ibuf->userdata==NULL) {
2564                         BLI_lock_thread(LOCK_CUSTOM1);
2565                         if (bs->ibuf->userdata==NULL) { /* since the thread was locked, its possible another thread alloced the value */
2566                                 bs->ibuf->userdata = (void *)MEM_callocN(sizeof(char)*bs->rectx*bs->recty, "BakeMask");
2567                                 bs->rect_mask= (char *)bs->ibuf->userdata;
2568                         }
2569                         BLI_unlock_thread(LOCK_CUSTOM1);
2570                 } else {
2571                         bs->rect_mask= (char *)bs->ibuf->userdata;
2572                 }
2573         }
2574         
2575         /* get pixel level vertex coordinates */
2576         for(a=0; a<4; a++) {
2577                 /* Note, workaround for pixel aligned UVs which are common and can screw up our intersection tests
2578                  * where a pixel gets inbetween 2 faces or the middle of a quad,
2579                  * camera aligned quads also have this problem but they are less common.
2580                  * Add a small offset to the UVs, fixes bug #18685 - Campbell */
2581                 vec[a][0]= tface->uv[a][0]*(float)bs->rectx - (0.5f + 0.001);
2582                 vec[a][1]= tface->uv[a][1]*(float)bs->recty - (0.5f + 0.002);
2583         }
2584         
2585         /* UV indices have to be corrected for possible quad->tria splits */
2586         i1= 0; i2= 1; i3= 2;
2587         vlr_set_uv_indices(vlr, &i1, &i2, &i3);
2588         bake_set_vlr_dxyco(bs, vec[i1], vec[i2], vec[i3]);
2589         zspan_scanconvert(bs->zspan, bs, vec[i1], vec[i2], vec[i3], do_bake_shade);
2590         
2591         if(vlr->v4) {
2592                 bs->quad= 1;
2593                 bake_set_vlr_dxyco(bs, vec[0], vec[2], vec[3]);
2594                 zspan_scanconvert(bs->zspan, bs, vec[0], vec[2], vec[3], do_bake_shade);
2595         }
2596 }
2597
2598 static void *do_bake_thread(void *bs_v)
2599 {
2600         BakeShade *bs= bs_v;
2601         
2602         while(get_next_bake_face(bs)) {
2603                 shade_tface(bs);
2604                 
2605                 /* fast threadsafe break test */
2606                 if(R.test_break(R.tbh))
2607                         break;
2608
2609                 /* access is not threadsafe but since its just true/false probably ok
2610                  * only used for interactive baking */
2611                 if(bs->do_update)
2612                         *bs->do_update= TRUE;
2613         }
2614         bs->ready= 1;
2615         
2616         return NULL;
2617 }
2618
2619 /* using object selection tags, the faces with UV maps get baked */
2620 /* render should have been setup */
2621 /* returns 0 if nothing was handled */
2622 int RE_bake_shade_all_selected(Render *re, int type, Object *actob, short *do_update)
2623 {
2624         BakeShade handles[BLENDER_MAX_THREADS];
2625         ListBase threads;
2626         Image *ima;
2627         int a, vdone=0, usemask=0;
2628         
2629         /* initialize render global */
2630         R= *re;
2631         R.bakebuf= NULL;
2632         
2633         /* initialize static vars */
2634         get_next_bake_face(NULL);
2635         
2636         /* do we need a mask? */
2637         if (re->r.bake_filter && (re->r.bake_flag & R_BAKE_CLEAR)==0)
2638                 usemask = 1;
2639         
2640         /* baker uses this flag to detect if image was initialized */
2641         for(ima= G.main->image.first; ima; ima= ima->id.next) {
2642                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
2643                 ima->id.flag |= LIB_DOIT;
2644                 if (ibuf)
2645                         ibuf->userdata = NULL; /* use for masking if needed */
2646         }
2647         
2648         BLI_init_threads(&threads, do_bake_thread, re->r.threads);
2649
2650         /* get the threads running */
2651         for(a=0; a<re->r.threads; a++) {
2652                 /* set defaults in handles */
2653                 memset(&handles[a], 0, sizeof(BakeShade));
2654                 
2655                 handles[a].ssamp.shi[0].lay= re->scene->lay;
2656                 
2657                 if (type==RE_BAKE_SHADOW) {
2658                         handles[a].ssamp.shi[0].passflag= SCE_PASS_SHADOW;
2659                 } else {
2660                         handles[a].ssamp.shi[0].passflag= SCE_PASS_COMBINED;
2661                 }
2662                 handles[a].ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
2663                 handles[a].ssamp.shi[0].thread= a;
2664                 handles[a].ssamp.tot= 1;
2665                 
2666                 handles[a].type= type;
2667                 handles[a].actob= actob;
2668                 handles[a].zspan= MEM_callocN(sizeof(ZSpan), "zspan for bake");
2669                 
2670                 handles[a].usemask = usemask;
2671
2672                 handles[a].do_update = do_update; /* use to tell the view to update */
2673                 
2674                 BLI_insert_thread(&threads, &handles[a]);
2675         }
2676         
2677         /* wait for everything to be done */
2678         a= 0;
2679         while(a!=re->r.threads) {
2680                 
2681                 PIL_sleep_ms(50);
2682
2683                 for(a=0; a<re->r.threads; a++)
2684                         if(handles[a].ready==0)
2685                                 break;
2686         }
2687         
2688         /* filter and refresh images */
2689         for(ima= G.main->image.first; ima; ima= ima->id.next) {
2690                 if((ima->id.flag & LIB_DOIT)==0) {
2691                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
2692                         if (re->r.bake_filter) {
2693                                 if (usemask) {
2694                                         /* extend the mask +2 pixels from the image,
2695                                          * this is so colors dont blend in from outside */
2696                                         char *temprect;
2697                                         
2698                                         for(a=0; a<re->r.bake_filter; a++)
2699                                                 bake_mask_filter_extend((char *)ibuf->userdata, ibuf->x, ibuf->y);
2700                                         
2701                                         temprect = MEM_dupallocN(ibuf->userdata);
2702                                         
2703                                         /* expand twice to clear this many pixels, so they blend back in */
2704                                         bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
2705                                         bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
2706                                         
2707                                         /* clear all pixels in the margin*/
2708                                         bake_mask_clear(ibuf, temprect, BAKE_MASK_MARGIN);
2709                                         MEM_freeN(temprect);
2710                                 }
2711                                 
2712                                 for(a=0; a<re->r.bake_filter; a++) {
2713                                         /*the mask, ibuf->userdata - can be null, in this case only zero alpha is used */
2714                                         IMB_filter_extend(ibuf, (char *)ibuf->userdata);
2715                                 }
2716                                 
2717                                 if (ibuf->userdata) {
2718                                         MEM_freeN(ibuf->userdata);
2719                                         ibuf->userdata= NULL;
2720                                 }
2721                         }
2722                         ibuf->userflags |= IB_BITMAPDIRTY;
2723                         if (ibuf->rect_float) IMB_rect_from_float(ibuf);
2724                 }
2725         }
2726         
2727         /* calculate return value */
2728         for(a=0; a<re->r.threads; a++) {
2729                 vdone+= handles[a].vdone;
2730                 
2731                 zbuf_free_span(handles[a].zspan);
2732                 MEM_freeN(handles[a].zspan);
2733         }
2734         
2735         BLI_end_threads(&threads);
2736         return vdone;
2737 }
2738
2739 struct Image *RE_bake_shade_get_image(void)
2740 {
2741         return R.bakebuf;
2742 }
2743