Fix #21211: new indirect/environment/emit passes weren't showing up
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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_NORMAL:
490                                 col= shr->nor;
491                                 break;
492                         case SCE_PASS_UV:
493                                 /* box filter only, gauss will screwup UV too much */
494                                 if(shi->totuv) {
495                                         float mult= (float)count_mask(curmask)/(float)R.osa;
496                                         fp= rpass->rect + 3*offset;
497                                         fp[0]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[0]);
498                                         fp[1]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[1]);
499                                         fp[2]+= mult;
500                                 }
501                                 break;
502                         case SCE_PASS_INDEXOB:
503                                 /* no filter */
504                                 if(shi->vlr) {
505                                         fp= rpass->rect + offset;
506                                         if(*fp==0.0f)
507                                                 *fp= (float)shi->obr->ob->index;
508                                 }
509                                 break;
510                         case SCE_PASS_MIST:
511                                 /*  */
512                                 col= &shr->mist;
513                                 pixsize= 1;
514                                 break;
515                         
516                         case SCE_PASS_VECTOR:
517                         {
518                                 /* add minimum speed in pixel, no filter */
519                                 fp= rpass->rect + 4*offset;
520                                 if( (ABS(shr->winspeed[0]) + ABS(shr->winspeed[1]))< (ABS(fp[0]) + ABS(fp[1])) ) {
521                                         fp[0]= shr->winspeed[0];
522                                         fp[1]= shr->winspeed[1];
523                                 }
524                                 if( (ABS(shr->winspeed[2]) + ABS(shr->winspeed[3]))< (ABS(fp[2]) + ABS(fp[3])) ) {
525                                         fp[2]= shr->winspeed[2];
526                                         fp[3]= shr->winspeed[3];
527                                 }
528                         }
529                                 break;
530
531                         case SCE_PASS_RAYHITS:
532                                 /*  */
533                                 col= shr->rayhits;
534                                 pixsize= 4;
535                                 break;
536                 }
537                 if(col) {
538                         fp= rpass->rect + pixsize*offset;
539                         add_filt_fmask_pixsize(curmask, col, fp, rectx, pixsize);
540                 }
541         }
542 }
543
544 /* non-osa version */
545 static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult *shr)
546 {
547         RenderPass *rpass;
548         float *fp;
549         
550         fp= rl->rectf + 4*offset;
551         QUATCOPY(fp, shr->combined);
552         
553         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
554                 float *col= NULL, uvcol[3];
555                 int a, pixsize= 3;
556                 
557                 switch(rpass->passtype) {
558                         case SCE_PASS_Z:
559                                 fp= rpass->rect + offset;
560                                 *fp= shr->z;
561                                 break;
562                         case SCE_PASS_RGBA:
563                                 col= shr->col;
564                                 pixsize= 4;
565                                 break;
566                         case SCE_PASS_EMIT:
567                                 col= shr->emit;
568                                 break;
569                         case SCE_PASS_DIFFUSE:
570                                 col= shr->diff;
571                                 break;
572                         case SCE_PASS_SPEC:
573                                 col= shr->spec;
574                                 break;
575                         case SCE_PASS_SHADOW:
576                                 col= shr->shad;
577                                 break;
578                         case SCE_PASS_AO:
579                                 col= shr->ao;
580                                 break;
581                         case SCE_PASS_ENVIRONMENT:
582                                 col= shr->env;
583                                 break;
584                         case SCE_PASS_INDIRECT:
585                                 col= shr->indirect;
586                                 break;
587                         case SCE_PASS_REFLECT:
588                                 col= shr->refl;
589                                 break;
590                         case SCE_PASS_REFRACT:
591                                 col= shr->refr;
592                                 break;
593                         case SCE_PASS_NORMAL:
594                                 col= shr->nor;
595                                 break;
596                         case SCE_PASS_UV:
597                                 if(shi->totuv) {
598                                         uvcol[0]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[0];
599                                         uvcol[1]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[1];
600                                         uvcol[2]= 1.0f;
601                                         col= uvcol;
602                                 }
603                                 break;
604                         case SCE_PASS_VECTOR:
605                                 col= shr->winspeed;
606                                 pixsize= 4;
607                                 break;
608                         case SCE_PASS_INDEXOB:
609                                 if(shi->vlr) {
610                                         fp= rpass->rect + offset;
611                                         *fp= (float)shi->obr->ob->index;
612                                 }
613                                 break;
614                         case SCE_PASS_MIST:
615                                 fp= rpass->rect + offset;
616                                 *fp= shr->mist;
617                                 break;
618                         case SCE_PASS_RAYHITS:
619                                 col= shr->rayhits;
620                                 pixsize= 4;
621                                 break;
622                 }
623                 if(col) {
624                         fp= rpass->rect + pixsize*offset;
625                         for(a=0; a<pixsize; a++)
626                                 fp[a]= col[a];
627                 }
628         }
629 }
630
631 int get_sample_layers(RenderPart *pa, RenderLayer *rl, RenderLayer **rlpp)
632 {
633         
634         if(pa->fullresult.first) {
635                 int sample, nr= BLI_findindex(&pa->result->layers, rl);
636                 
637                 for(sample=0; sample<R.osa; sample++) {
638                         RenderResult *rr= BLI_findlink(&pa->fullresult, sample);
639                 
640                         rlpp[sample]= BLI_findlink(&rr->layers, nr);
641                 }               
642                 return R.osa;
643         }
644         else {
645                 rlpp[0]= rl;
646                 return 1;
647         }
648 }
649
650
651 /* only do sky, is default in the solid layer (shade_tile) btw */
652 static void sky_tile(RenderPart *pa, RenderLayer *rl)
653 {
654         RenderLayer *rlpp[RE_MAX_OSA];
655         int x, y, od=0, totsample;
656         
657         if(R.r.alphamode!=R_ADDSKY)
658                 return;
659         
660         totsample= get_sample_layers(pa, rl, rlpp);
661         
662         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
663                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od+=4) {
664                         float col[4];
665                         int sample, done= 0;
666                         
667                         for(sample= 0; sample<totsample; sample++) {
668                                 float *pass= rlpp[sample]->rectf + od;
669                                 
670                                 if(pass[3]<1.0f) {
671                                         
672                                         if(done==0) {
673                                                 shadeSkyPixel(col, x, y, pa->thread);
674                                                 done= 1;
675                                         }
676                                         
677                                         if(pass[3]==0.0f) {
678                                                 QUATCOPY(pass, col);
679                                         }
680                                         else {
681                                                 addAlphaUnderFloat(pass, col);
682                                         }
683                                 }
684                         }                       
685                 }
686                 
687                 if(y&1)
688                         if(R.test_break(R.tbh)) break; 
689         }
690 }
691
692 static void atm_tile(RenderPart *pa, RenderLayer *rl)
693 {
694         RenderPass *zpass;
695         GroupObject *go;
696         LampRen *lar;
697         RenderLayer *rlpp[RE_MAX_OSA];
698         int totsample;
699         int x, y, od= 0;
700         
701         totsample= get_sample_layers(pa, rl, rlpp);
702
703         /* check that z pass is enabled */
704         if(pa->rectz==NULL) return;
705         for(zpass= rl->passes.first; zpass; zpass= zpass->next)
706                 if(zpass->passtype==SCE_PASS_Z)
707                         break;
708         
709         if(zpass==NULL) return;
710
711         /* check for at least one sun lamp that its atmosphere flag is is enabled */
712         for(go=R.lights.first; go; go= go->next) {
713                 lar= go->lampren;
714                 if(lar->type==LA_SUN && lar->sunsky && (lar->sunsky->effect_type & LA_SUN_EFFECT_AP))
715                         break;
716         }
717         /* do nothign and return if there is no sun lamp */
718         if(go==NULL)
719                 return;
720         
721         /* for each x,y and each sample, and each sun lamp*/
722         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
723                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od++) {
724                         int sample;
725                         
726                         for(sample=0; sample<totsample; sample++) {
727                                 float *zrect= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_Z) + od;
728                                 float *rgbrect = rlpp[sample]->rectf + 4*od;
729                                 float rgb[3] = {0};
730                                 int done= 0;
731                                 
732                                 for(go=R.lights.first; go; go= go->next) {
733                                 
734                                         
735                                         lar= go->lampren;
736                                         if(lar->type==LA_SUN && lar->sunsky) {
737                                                 
738                                                 /* if it's sky continue and don't apply atmosphere effect on it */
739                                                 if(*zrect >= 9.9e10 || rgbrect[3]==0.0f) {
740                                                         continue;
741                                                 }
742                                                 
743                                                 if((lar->sunsky->effect_type & LA_SUN_EFFECT_AP)) {     
744                                                         float tmp_rgb[3];
745                                                         
746                                                         VECCOPY(tmp_rgb, rgbrect);
747                                                         if(rgbrect[3]!=1.0f) {  /* de-premul */
748                                                                 float div= 1.0f/rgbrect[3];
749                                                                 VECMUL(tmp_rgb, div);
750                                                         }
751                                                         shadeAtmPixel(lar->sunsky, tmp_rgb, x, y, *zrect);
752                                                         if(rgbrect[3]!=1.0f) {  /* premul */
753                                                                 VECMUL(tmp_rgb, rgbrect[3]);
754                                                         }
755                                                         
756                                                         if(done==0) {
757                                                                 VECCOPY(rgb, tmp_rgb);
758                                                                 done = 1;                                               
759                                                         }
760                                                         else{
761                                                                 rgb[0] = 0.5f*rgb[0] + 0.5f*tmp_rgb[0];
762                                                                 rgb[1] = 0.5f*rgb[1] + 0.5f*tmp_rgb[1];
763                                                                 rgb[2] = 0.5f*rgb[2] + 0.5f*tmp_rgb[2];
764                                                         }
765                                                 }
766                                         }
767                                 }
768
769                                 /* if at least for one sun lamp aerial perspective was applied*/
770                                 if(done) {
771                                         VECCOPY(rgbrect, rgb);
772                                 }
773                         }
774                 }
775         }
776 }
777
778 static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
779 {
780         RenderResult *rr= pa->result;
781         ShadeSample ssamp;
782         intptr_t *rd, *rectdaps= pa->rectdaps;
783         int samp;
784         int x, y, seed, crop=0, offs=0, od;
785         
786         if(R.test_break(R.tbh)) return; 
787         
788         /* irregular shadowb buffer creation */
789         if(R.r.mode & R_SHADOW)
790                 ISB_create(pa, NULL);
791         
792         /* we set per pixel a fixed seed, for random AO and shadow samples */
793         seed= pa->rectx*pa->disprect.ymin;
794         
795         /* general shader info, passes */
796         shade_sample_initialize(&ssamp, pa, rl);
797
798         /* occlusion caching */
799         if(R.occlusiontree)
800                 cache_occ_samples(&R, pa, &ssamp);
801                 
802         /* filtered render, for now we assume only 1 filter size */
803         if(pa->crop) {
804                 crop= 1;
805                 rectdaps+= pa->rectx + 1;
806                 offs= pa->rectx + 1;
807         }
808         
809         /* scanline updates have to be 2 lines behind */
810         rr->renrect.ymin= 0;
811         rr->renrect.ymax= -2*crop;
812         rr->renlay= rl;
813                                 
814         for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
815                 rd= rectdaps;
816                 od= offs;
817                 
818                 for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, rd++, od++) {
819                         BLI_thread_srandom(pa->thread, seed++);
820                         
821                         if(*rd) {
822                                 if(shade_samples(&ssamp, (PixStr *)(*rd), x, y)) {
823                                         
824                                         /* multisample buffers or filtered mask filling? */
825                                         if(pa->fullresult.first) {
826                                                 int a;
827                                                 for(samp=0; samp<ssamp.tot; samp++) {
828                                                         int smask= ssamp.shi[samp].mask;
829                                                         for(a=0; a<R.osa; a++) {
830                                                                 int mask= 1<<a;
831                                                                 if(smask & mask)
832                                                                         add_passes(ssamp.rlpp[a], od, &ssamp.shi[samp], &ssamp.shr[samp]);
833                                                         }
834                                                 }
835                                         }
836                                         else {
837                                                 for(samp=0; samp<ssamp.tot; samp++)
838                                                         add_filt_passes(rl, ssamp.shi[samp].mask, pa->rectx, od, &ssamp.shi[samp], &ssamp.shr[samp]);
839                                         }
840                                 }
841                         }
842                 }
843                 
844                 rectdaps+= pa->rectx;
845                 offs+= pa->rectx;
846                 
847                 if(y&1) if(R.test_break(R.tbh)) break; 
848         }
849         
850         /* disable scanline updating */
851         rr->renlay= NULL;
852         
853         if(R.r.mode & R_SHADOW)
854                 ISB_free(pa);
855
856         if(R.occlusiontree)
857                 free_occ_samples(&R, pa);
858 }
859
860 /* ************* pixel struct ******** */
861
862
863 static PixStrMain *addpsmain(ListBase *lb)
864 {
865         PixStrMain *psm;
866         
867         psm= (PixStrMain *)MEM_mallocN(sizeof(PixStrMain),"pixstrMain");
868         BLI_addtail(lb, psm);
869         
870         psm->ps= (PixStr *)MEM_mallocN(4096*sizeof(PixStr),"pixstr");
871         psm->counter= 0;
872         
873         return psm;
874 }
875
876 static void freeps(ListBase *lb)
877 {
878         PixStrMain *psm, *psmnext;
879         
880         for(psm= lb->first; psm; psm= psmnext) {
881                 psmnext= psm->next;
882                 if(psm->ps)
883                         MEM_freeN(psm->ps);
884                 MEM_freeN(psm);
885         }
886         lb->first= lb->last= NULL;
887 }
888
889 static void addps(ListBase *lb, intptr_t *rd, int obi, int facenr, int z, int maskz, unsigned short mask)
890 {
891         PixStrMain *psm;
892         PixStr *ps, *last= NULL;
893         
894         if(*rd) {       
895                 ps= (PixStr *)(*rd);
896                 
897                 while(ps) {
898                         if( ps->obi == obi && ps->facenr == facenr ) {
899                                 ps->mask |= mask;
900                                 return;
901                         }
902                         last= ps;
903                         ps= ps->next;
904                 }
905         }
906         
907         /* make new PS (pixel struct) */
908         psm= lb->last;
909         
910         if(psm->counter==4095)
911                 psm= addpsmain(lb);
912         
913         ps= psm->ps + psm->counter++;
914         
915         if(last) last->next= ps;
916         else *rd= (intptr_t)ps;
917         
918         ps->next= NULL;
919         ps->obi= obi;
920         ps->facenr= facenr;
921         ps->z= z;
922         ps->maskz= maskz;
923         ps->mask = mask;
924         ps->shadfac= 0;
925 }
926
927 static void edge_enhance_add(RenderPart *pa, float *rectf, float *arect)
928 {
929         float addcol[4];
930         int pix;
931         
932         if(arect==NULL)
933                 return;
934         
935         for(pix= pa->rectx*pa->recty; pix>0; pix--, arect++, rectf+=4) {
936                 if(*arect != 0.0f) {
937                         addcol[0]= *arect * R.r.edgeR;
938                         addcol[1]= *arect * R.r.edgeG;
939                         addcol[2]= *arect * R.r.edgeB;
940                         addcol[3]= *arect;
941                         addAlphaOverFloat(rectf, addcol);
942                 }
943         }
944 }
945
946 static void convert_to_key_alpha(RenderPart *pa, RenderLayer *rl)
947 {
948         RenderLayer *rlpp[RE_MAX_OSA];
949         int y, sample, totsample;
950         
951         totsample= get_sample_layers(pa, rl, rlpp);
952         
953         for(sample= 0; sample<totsample; sample++) {
954                 float *rectf= rlpp[sample]->rectf;
955                 
956                 for(y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
957                         if(rectf[3] >= 1.0f);
958                         else if(rectf[3] > 0.0f) {
959                                 rectf[0] /= rectf[3];
960                                 rectf[1] /= rectf[3];
961                                 rectf[2] /= rectf[3];
962                         }
963                 }
964         }
965 }
966
967 /* adds only alpha values */
968 void edge_enhance_tile(RenderPart *pa, float *rectf, int *rectz)
969 {
970         /* use zbuffer to define edges, add it to the image */
971         int y, x, col, *rz, *rz1, *rz2, *rz3;
972         int zval1, zval2, zval3;
973         float *rf;
974         
975         /* shift values in zbuffer 4 to the right (anti overflows), for filter we need multiplying with 12 max */
976         rz= rectz;
977         if(rz==NULL) return;
978         
979         for(y=0; y<pa->recty; y++)
980                 for(x=0; x<pa->rectx; x++, rz++) (*rz)>>= 4;
981         
982         rz1= rectz;
983         rz2= rz1+pa->rectx;
984         rz3= rz2+pa->rectx;
985         
986         rf= rectf+pa->rectx+1;
987         
988         for(y=0; y<pa->recty-2; y++) {
989                 for(x=0; x<pa->rectx-2; x++, rz1++, rz2++, rz3++, rf++) {
990                         
991                         /* prevent overflow with sky z values */
992                         zval1=   rz1[0] + 2*rz1[1] +   rz1[2];
993                         zval2=  2*rz2[0]           + 2*rz2[2];
994                         zval3=   rz3[0] + 2*rz3[1] +   rz3[2];
995                         
996                         col= ( 4*rz2[1] - (zval1 + zval2 + zval3)/3 );
997                         if(col<0) col= -col;
998                         
999                         col >>= 5;
1000                         if(col > (1<<16)) col= (1<<16);
1001                         else col= (R.r.edgeint*col)>>8;
1002                         
1003                         if(col>0) {
1004                                 float fcol;
1005                                 
1006                                 if(col>255) fcol= 1.0f;
1007                                 else fcol= (float)col/255.0f;
1008                                 
1009                                 if(R.osa)
1010                                         *rf+= fcol/(float)R.osa;
1011                                 else
1012                                         *rf= fcol;
1013                         }
1014                 }
1015                 rz1+= 2;
1016                 rz2+= 2;
1017                 rz3+= 2;
1018                 rf+= 2;
1019         }
1020         
1021         /* shift back zbuf values, we might need it still */
1022         rz= rectz;
1023         for(y=0; y<pa->recty; y++)
1024                 for(x=0; x<pa->rectx; x++, rz++) (*rz)<<= 4;
1025         
1026 }
1027
1028 static void reset_sky_speed(RenderPart *pa, RenderLayer *rl)
1029 {
1030         /* for all pixels with max speed, set to zero */
1031     RenderLayer *rlpp[RE_MAX_OSA];
1032         float *fp;
1033         int a, sample, totsample;
1034         
1035         totsample= get_sample_layers(pa, rl, rlpp);
1036
1037         for(sample= 0; sample<totsample; sample++) {
1038                 fp= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_VECTOR);
1039                 if(fp==NULL) break;
1040
1041                 for(a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
1042                         if(fp[a] == PASS_VECTOR_MAX) fp[a]= 0.0f;
1043         }
1044 }
1045
1046 static unsigned short *make_solid_mask(RenderPart *pa)
1047
1048         intptr_t *rd= pa->rectdaps;
1049         unsigned short *solidmask, *sp;
1050         int x;
1051         
1052         if(rd==NULL) return NULL;
1053         
1054         sp=solidmask= MEM_mallocN(sizeof(short)*pa->rectx*pa->recty, "solidmask");
1055         
1056         for(x=pa->rectx*pa->recty; x>0; x--, rd++, sp++) {
1057                 if(*rd) {
1058                         PixStr *ps= (PixStr *)*rd;
1059                         
1060                         *sp= ps->mask;
1061                         for(ps= ps->next; ps; ps= ps->next)
1062                                 *sp |= ps->mask;
1063                 }
1064                 else
1065                         *sp= 0;
1066         }
1067                         
1068         return solidmask;
1069 }
1070
1071 static void addAlphaOverFloatMask(float *dest, float *source, unsigned short dmask, unsigned short smask)
1072 {
1073         unsigned short shared= dmask & smask;
1074         float mul= 1.0 - source[3];
1075         
1076         if(shared) {    /* overlapping masks */
1077                 
1078                 /* masks differ, we make a mixture of 'add' and 'over' */
1079                 if(shared!=dmask) {
1080                         float shared_bits= (float)count_mask(shared);           /* alpha over */
1081                         float tot_bits= (float)count_mask(smask|dmask);         /* alpha add */
1082                         
1083                         float add= (tot_bits - shared_bits)/tot_bits;           /* add level */
1084                         mul= add + (1.0f-add)*mul;
1085                 }
1086         }
1087         else if(dmask && smask) {
1088                 /* works for premul only, of course */
1089                 dest[0]+= source[0];
1090                 dest[1]+= source[1];
1091                 dest[2]+= source[2];
1092                 dest[3]+= source[3];
1093                 
1094                 return;
1095         }
1096
1097         dest[0]= (mul*dest[0]) + source[0];
1098         dest[1]= (mul*dest[1]) + source[1];
1099         dest[2]= (mul*dest[2]) + source[2];
1100         dest[3]= (mul*dest[3]) + source[3];
1101 }
1102
1103 typedef struct ZbufSolidData {
1104         RenderLayer *rl;
1105         ListBase *psmlist;
1106         float *edgerect;
1107 } ZbufSolidData;
1108
1109 void make_pixelstructs(RenderPart *pa, ZSpan *zspan, int sample, void *data)
1110 {
1111         ZbufSolidData *sdata= (ZbufSolidData*)data;
1112         ListBase *lb= sdata->psmlist;
1113         intptr_t *rd= pa->rectdaps;
1114         int *ro= zspan->recto;
1115         int *rp= zspan->rectp;
1116         int *rz= zspan->rectz;
1117         int *rm= zspan->rectmask;
1118         int x, y;
1119         int mask= 1<<sample;
1120
1121         for(y=0; y<pa->recty; y++) {
1122                 for(x=0; x<pa->rectx; x++, rd++, rp++, ro++, rz++, rm++) {
1123                         if(*rp) {
1124                                 addps(lb, rd, *ro, *rp, *rz, (zspan->rectmask)? *rm: 0, mask);
1125                         }
1126                 }
1127         }
1128
1129         if(sdata->rl->layflag & SCE_LAY_EDGE) 
1130                 if(R.r.mode & R_EDGE) 
1131                         edge_enhance_tile(pa, sdata->edgerect, zspan->rectz);
1132 }
1133
1134 /* main call for shading Delta Accum, for OSA */
1135 /* supposed to be fully threadable! */
1136 void zbufshadeDA_tile(RenderPart *pa)
1137 {
1138         RenderResult *rr= pa->result;
1139         RenderLayer *rl;
1140         ListBase psmlist= {NULL, NULL};
1141         float *edgerect= NULL;
1142         
1143         /* allocate the necessary buffers */
1144                                 /* zbuffer inits these rects */
1145         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1146         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1147         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1148         for(rl= rr->layers.first; rl; rl= rl->next) {
1149                 if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
1150                         pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
1151         
1152                 /* initialize pixelstructs and edge buffer */
1153                 addpsmain(&psmlist);
1154                 pa->rectdaps= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "zbufDArectd");
1155                 
1156                 if(rl->layflag & SCE_LAY_EDGE) 
1157                         if(R.r.mode & R_EDGE) 
1158                                 edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
1159                 
1160                 /* always fill visibility */
1161                 for(pa->sample=0; pa->sample<R.osa; pa->sample+=4) {
1162                         ZbufSolidData sdata;
1163
1164                         sdata.rl= rl;
1165                         sdata.psmlist= &psmlist;
1166                         sdata.edgerect= edgerect;
1167                         zbuffer_solid(pa, rl, make_pixelstructs, &sdata);
1168                         if(R.test_break(R.tbh)) break; 
1169                 }
1170                 
1171                 /* shades solid */
1172                 if(rl->layflag & SCE_LAY_SOLID) 
1173                         shadeDA_tile(pa, rl);
1174                 
1175                 /* lamphalo after solid, before ztra, looks nicest because ztra does own halo */
1176                 if(R.flag & R_LAMPHALO)
1177                         if(rl->layflag & SCE_LAY_HALO)
1178                                 lamphalo_tile(pa, rl);
1179                 
1180                 /* halo before ztra, because ztra fills in zbuffer now */
1181                 if(R.flag & R_HALO)
1182                         if(rl->layflag & SCE_LAY_HALO)
1183                                 halo_tile(pa, rl);
1184
1185                 /* transp layer */
1186                 if(R.flag & R_ZTRA || R.totstrand) {
1187                         if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
1188                                 if(pa->fullresult.first) {
1189                                         zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
1190                                 }
1191                                 else {
1192                                         unsigned short *ztramask, *solidmask= NULL; /* 16 bits, MAX_OSA */
1193                                         
1194                                         /* allocate, but not free here, for asynchronous display of this rect in main thread */
1195                                         rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
1196                                         
1197                                         /* swap for live updates, and it is used in zbuf.c!!! */
1198                                         SWAP(float *, rl->acolrect, rl->rectf);
1199                                         ztramask= zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
1200                                         SWAP(float *, rl->acolrect, rl->rectf);
1201                                         
1202                                         /* zbuffer transp only returns ztramask if there's solid rendered */
1203                                         if(ztramask)
1204                                                 solidmask= make_solid_mask(pa);
1205
1206                                         if(ztramask && solidmask) {
1207                                                 unsigned short *sps= solidmask, *spz= ztramask;
1208                                                 unsigned short fullmask= (1<<R.osa)-1;
1209                                                 float *fcol= rl->rectf; float *acol= rl->acolrect;
1210                                                 int x;
1211                                                 
1212                                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4, sps++, spz++) {
1213                                                         if(*sps == fullmask)
1214                                                                 addAlphaOverFloat(fcol, acol);
1215                                                         else
1216                                                                 addAlphaOverFloatMask(fcol, acol, *sps, *spz);
1217                                                 }
1218                                         }
1219                                         else {
1220                                                 float *fcol= rl->rectf; float *acol= rl->acolrect;
1221                                                 int x;
1222                                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
1223                                                         addAlphaOverFloat(fcol, acol);
1224                                                 }
1225                                         }
1226                                         if(solidmask) MEM_freeN(solidmask);
1227                                         if(ztramask) MEM_freeN(ztramask);
1228                                 }
1229                         }
1230                 }
1231
1232                 /* sun/sky */
1233                 if(rl->layflag & SCE_LAY_SKY)
1234                         atm_tile(pa, rl);
1235                 
1236                 /* sky before edge */
1237                 if(rl->layflag & SCE_LAY_SKY)
1238                         sky_tile(pa, rl);
1239
1240                 /* extra layers */
1241                 if(rl->layflag & SCE_LAY_EDGE) 
1242                         if(R.r.mode & R_EDGE) 
1243                                 edge_enhance_add(pa, rl->rectf, edgerect);
1244                 
1245                 if(rl->passflag & SCE_PASS_VECTOR)
1246                         reset_sky_speed(pa, rl);
1247                 
1248                 /* de-premul alpha */
1249                 if(R.r.alphamode & R_ALPHAKEY)
1250                         convert_to_key_alpha(pa, rl);
1251                 
1252                 /* free stuff within loop! */
1253                 MEM_freeN(pa->rectdaps); pa->rectdaps= NULL;
1254                 freeps(&psmlist);
1255                 
1256                 if(edgerect) MEM_freeN(edgerect);
1257                 edgerect= NULL;
1258
1259                 if(pa->rectmask) {
1260                         MEM_freeN(pa->rectmask);
1261                         pa->rectmask= NULL;
1262                 }
1263         }
1264         
1265         /* free all */
1266         MEM_freeN(pa->recto); pa->recto= NULL;
1267         MEM_freeN(pa->rectp); pa->rectp= NULL;
1268         MEM_freeN(pa->rectz); pa->rectz= NULL;
1269         
1270         /* display active layer */
1271         rr->renrect.ymin=rr->renrect.ymax= 0;
1272         rr->renlay= render_get_active_layer(&R, rr);
1273 }
1274
1275
1276 /* ------------------------------------------------------------------------ */
1277
1278 /* non OSA case, full tile render */
1279 /* supposed to be fully threadable! */
1280 void zbufshade_tile(RenderPart *pa)
1281 {
1282         ShadeSample ssamp;
1283         RenderResult *rr= pa->result;
1284         RenderLayer *rl;
1285         PixStr ps;
1286         float *edgerect= NULL;
1287         
1288         /* fake pixel struct, to comply to osa render */
1289         ps.next= NULL;
1290         ps.mask= 0xFFFF;
1291         
1292         /* zbuffer code clears/inits rects */
1293         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1294         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1295         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1296
1297         for(rl= rr->layers.first; rl; rl= rl->next) {
1298                 if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
1299                         pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
1300
1301                 /* general shader info, passes */
1302                 shade_sample_initialize(&ssamp, pa, rl);
1303                 
1304                 zbuffer_solid(pa, rl, NULL, NULL);
1305                 
1306                 if(!R.test_break(R.tbh)) {      /* NOTE: this if() is not consistent */
1307                         
1308                         /* edges only for solid part, ztransp doesn't support it yet anti-aliased */
1309                         if(rl->layflag & SCE_LAY_EDGE) {
1310                                 if(R.r.mode & R_EDGE) {
1311                                         edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
1312                                         edge_enhance_tile(pa, edgerect, pa->rectz);
1313                                 }
1314                         }
1315                         
1316                         /* initialize scanline updates for main thread */
1317                         rr->renrect.ymin= 0;
1318                         rr->renlay= rl;
1319                         
1320                         if(rl->layflag & SCE_LAY_SOLID) {
1321                                 float *fcol= rl->rectf;
1322                                 int *ro= pa->recto, *rp= pa->rectp, *rz= pa->rectz;
1323                                 int x, y, offs=0, seed;
1324                                 
1325                                 /* we set per pixel a fixed seed, for random AO and shadow samples */
1326                                 seed= pa->rectx*pa->disprect.ymin;
1327                                 
1328                                 /* irregular shadowb buffer creation */
1329                                 if(R.r.mode & R_SHADOW)
1330                                         ISB_create(pa, NULL);
1331
1332                                 if(R.occlusiontree)
1333                                         cache_occ_samples(&R, pa, &ssamp);
1334                                 
1335                                 for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
1336                                         for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, ro++, rz++, rp++, fcol+=4, offs++) {
1337                                                 /* per pixel fixed seed */
1338                                                 BLI_thread_srandom(pa->thread, seed++);
1339                                                 
1340                                                 if(*rp) {
1341                                                         ps.obi= *ro;
1342                                                         ps.facenr= *rp;
1343                                                         ps.z= *rz;
1344                                                         if(shade_samples(&ssamp, &ps, x, y)) {
1345                                                                 /* combined and passes */
1346                                                                 add_passes(rl, offs, ssamp.shi, ssamp.shr);
1347                                                         }
1348                                                 }
1349                                         }
1350                                         if(y&1)
1351                                                 if(R.test_break(R.tbh)) break; 
1352                                 }
1353                                 
1354                                 if(R.occlusiontree)
1355                                         free_occ_samples(&R, pa);
1356                                 
1357                                 if(R.r.mode & R_SHADOW)
1358                                         ISB_free(pa);
1359                         }
1360                         
1361                         /* disable scanline updating */
1362                         rr->renlay= NULL;
1363                 }
1364                 
1365                 /* lamphalo after solid, before ztra, looks nicest because ztra does own halo */
1366                 if(R.flag & R_LAMPHALO)
1367                         if(rl->layflag & SCE_LAY_HALO)
1368                                 lamphalo_tile(pa, rl);
1369                 
1370                 /* halo before ztra, because ztra fills in zbuffer now */
1371                 if(R.flag & R_HALO)
1372                         if(rl->layflag & SCE_LAY_HALO)
1373                                 halo_tile(pa, rl);
1374                 
1375                 if(R.flag & R_ZTRA || R.totstrand) {
1376                         if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
1377                                 float *fcol, *acol;
1378                                 int x;
1379                                 
1380                                 /* allocate, but not free here, for asynchronous display of this rect in main thread */
1381                                 rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
1382                                 
1383                                 /* swap for live updates */
1384                                 SWAP(float *, rl->acolrect, rl->rectf);
1385                                 zbuffer_transp_shade(pa, rl, rl->rectf, NULL);
1386                                 SWAP(float *, rl->acolrect, rl->rectf);
1387                                 
1388                                 fcol= rl->rectf; acol= rl->acolrect;
1389                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
1390                                         addAlphaOverFloat(fcol, acol);
1391                                 }
1392                         }
1393                 }
1394                 
1395                 /* sun/sky */
1396                 if(rl->layflag & SCE_LAY_SKY)
1397                         atm_tile(pa, rl);
1398                 
1399                 /* sky before edge */
1400                 if(rl->layflag & SCE_LAY_SKY)
1401                         sky_tile(pa, rl);
1402                 
1403                 if(!R.test_break(R.tbh)) {
1404                         if(rl->layflag & SCE_LAY_EDGE) 
1405                                 if(R.r.mode & R_EDGE)
1406                                         edge_enhance_add(pa, rl->rectf, edgerect);
1407                 }
1408                 
1409                 if(rl->passflag & SCE_PASS_VECTOR)
1410                         reset_sky_speed(pa, rl);
1411                 
1412                 /* de-premul alpha */
1413                 if(R.r.alphamode & R_ALPHAKEY)
1414                         convert_to_key_alpha(pa, rl);
1415                 
1416                 if(edgerect) MEM_freeN(edgerect);
1417                 edgerect= NULL;
1418
1419                 if(pa->rectmask) {
1420                         MEM_freeN(pa->rectmask);
1421                         pa->rectmask= NULL;
1422                 }
1423         }
1424
1425         /* display active layer */
1426         rr->renrect.ymin=rr->renrect.ymax= 0;
1427         rr->renlay= render_get_active_layer(&R, rr);
1428         
1429         MEM_freeN(pa->recto); pa->recto= NULL;
1430         MEM_freeN(pa->rectp); pa->rectp= NULL;
1431         MEM_freeN(pa->rectz); pa->rectz= NULL;
1432 }
1433
1434 /* SSS preprocess tile render, fully threadable */
1435 typedef struct ZBufSSSHandle {
1436         RenderPart *pa;
1437         ListBase psmlist;
1438         int totps;
1439 } ZBufSSSHandle;
1440
1441 static void addps_sss(void *cb_handle, int obi, int facenr, int x, int y, int z)
1442 {
1443         ZBufSSSHandle *handle = cb_handle;
1444         RenderPart *pa= handle->pa;
1445
1446         /* extra border for filter gives double samples on part edges,
1447            don't use those */
1448         if(x<pa->crop || x>=pa->rectx-pa->crop)
1449                 return;
1450         if(y<pa->crop || y>=pa->recty-pa->crop)
1451                 return;
1452         
1453         if(pa->rectall) {
1454                 intptr_t *rs= pa->rectall + pa->rectx*y + x;
1455
1456                 addps(&handle->psmlist, rs, obi, facenr, z, 0, 0);
1457                 handle->totps++;
1458         }
1459         if(pa->rectz) {
1460                 int *rz= pa->rectz + pa->rectx*y + x;
1461                 int *rp= pa->rectp + pa->rectx*y + x;
1462                 int *ro= pa->recto + pa->rectx*y + x;
1463
1464                 if(z < *rz) {
1465                         if(*rp == 0)
1466                                 handle->totps++;
1467                         *rz= z;
1468                         *rp= facenr;
1469                         *ro= obi;
1470                 }
1471         }
1472         if(pa->rectbackz) {
1473                 int *rz= pa->rectbackz + pa->rectx*y + x;
1474                 int *rp= pa->rectbackp + pa->rectx*y + x;
1475                 int *ro= pa->rectbacko + pa->rectx*y + x;
1476
1477                 if(z >= *rz) {
1478                         if(*rp == 0)
1479                                 handle->totps++;
1480                         *rz= z;
1481                         *rp= facenr;
1482                         *ro= obi;
1483                 }
1484         }
1485 }
1486
1487 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)
1488 {
1489         ShadeInput *shi= ssamp->shi;
1490         ShadeResult shr;
1491         float texfac, orthoarea, nor[3], alpha, sx, sy;
1492
1493         /* cache for shadow */
1494         shi->samplenr= R.shadowsamplenr[shi->thread]++;
1495         
1496         if(quad) 
1497                 shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
1498         else
1499                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
1500
1501         /* center pixel */
1502         sx = x + 0.5f;
1503         sy = y + 0.5f;
1504
1505         /* we estimate the area here using shi->dxco and shi->dyco. we need to
1506            enabled shi->osatex these are filled. we compute two areas, one with
1507            the normal pointed at the camera and one with the original normal, and
1508            then clamp to avoid a too large contribution from a single pixel */
1509         shi->osatex= 1;
1510
1511         VECCOPY(nor, shi->facenor);
1512         calc_view_vector(shi->facenor, sx, sy);
1513         normalize_v3(shi->facenor);
1514         shade_input_set_viewco(shi, x, y, sx, sy, z);
1515         orthoarea= len_v3(shi->dxco)*len_v3(shi->dyco);
1516
1517         VECCOPY(shi->facenor, nor);
1518         shade_input_set_viewco(shi, x, y, sx, sy, z);
1519         *area= len_v3(shi->dxco)*len_v3(shi->dyco);
1520         *area= MIN2(*area, 2.0f*orthoarea);
1521
1522         shade_input_set_uv(shi);
1523         shade_input_set_normals(shi);
1524
1525         /* we don't want flipped normals, they screw up back scattering */
1526         if(shi->flippednor)
1527                 shade_input_flip_normals(shi);
1528
1529         /* not a pretty solution, but fixes common cases */
1530         if(shi->obr->ob && shi->obr->ob->transflag & OB_NEG_SCALE) {
1531                 negate_v3(shi->vn);
1532                 negate_v3(shi->vno);
1533         }
1534
1535         /* if nodetree, use the material that we are currently preprocessing
1536            instead of the node material */
1537         if(shi->mat->nodetree && shi->mat->use_nodes)
1538                 shi->mat= mat;
1539
1540         /* init material vars */
1541         shade_input_init_material(shi);
1542         
1543         /* render */
1544         shade_input_set_shade_texco(shi);
1545         
1546         shade_samples_do_AO(ssamp);
1547         shade_material_loop(shi, &shr);
1548         
1549         VECCOPY(co, shi->co);
1550         VECCOPY(color, shr.combined);
1551
1552         /* texture blending */
1553         texfac= shi->mat->sss_texfac;
1554
1555         alpha= shr.combined[3];
1556         *area *= alpha;
1557 }
1558
1559 static void zbufshade_sss_free(RenderPart *pa)
1560 {
1561 #if 0
1562         MEM_freeN(pa->rectall); pa->rectall= NULL;
1563         freeps(&handle.psmlist);
1564 #else
1565         MEM_freeN(pa->rectz); pa->rectz= NULL;
1566         MEM_freeN(pa->rectp); pa->rectp= NULL;
1567         MEM_freeN(pa->recto); pa->recto= NULL;
1568         MEM_freeN(pa->rectbackz); pa->rectbackz= NULL;
1569         MEM_freeN(pa->rectbackp); pa->rectbackp= NULL;
1570         MEM_freeN(pa->rectbacko); pa->rectbacko= NULL;
1571 #endif
1572 }
1573
1574 void zbufshade_sss_tile(RenderPart *pa)
1575 {
1576         Render *re= &R;
1577         ShadeSample ssamp;
1578         ZBufSSSHandle handle;
1579         RenderResult *rr= pa->result;
1580         RenderLayer *rl;
1581         VlakRen *vlr;
1582         Material *mat= re->sss_mat;
1583         float (*co)[3], (*color)[3], *area, *fcol;
1584         int x, y, seed, quad, totpoint, display = !(re->r.scemode & R_PREVIEWBUTS);
1585         int *ro, *rz, *rp, *rbo, *rbz, *rbp, lay;
1586 #if 0
1587         PixStr *ps;
1588         intptr_t *rs;
1589         int z;
1590 #endif
1591
1592         /* setup pixelstr list and buffer for zbuffering */
1593         handle.pa= pa;
1594         handle.totps= 0;
1595
1596 #if 0
1597         handle.psmlist.first= handle.psmlist.last= NULL;
1598         addpsmain(&handle.psmlist);
1599
1600         pa->rectall= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "rectall");
1601 #else
1602         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1603         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1604         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1605         pa->rectbacko= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbacko");
1606         pa->rectbackp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackp");
1607         pa->rectbackz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackz");
1608 #endif
1609
1610         /* setup shade sample with correct passes */
1611         memset(&ssamp, 0, sizeof(ssamp));
1612         shade_sample_initialize(&ssamp, pa, rr->layers.first);
1613         ssamp.tot= 1;
1614         
1615         for(rl=rr->layers.first; rl; rl=rl->next) {
1616                 ssamp.shi[0].lay |= rl->lay;
1617                 ssamp.shi[0].layflag |= rl->layflag;
1618                 ssamp.shi[0].passflag |= rl->passflag;
1619                 ssamp.shi[0].combinedflag |= ~rl->pass_xor;
1620         }
1621
1622         rl= rr->layers.first;
1623         ssamp.shi[0].passflag |= SCE_PASS_RGBA|SCE_PASS_COMBINED;
1624         ssamp.shi[0].combinedflag &= ~(SCE_PASS_SPEC);
1625         ssamp.shi[0].mat_override= NULL;
1626         ssamp.shi[0].light_override= NULL;
1627         lay= ssamp.shi[0].lay;
1628
1629         /* create the pixelstrs to be used later */
1630         zbuffer_sss(pa, lay, &handle, addps_sss);
1631
1632         if(handle.totps==0) {
1633                 zbufshade_sss_free(pa);
1634                 return;
1635         }
1636         
1637         fcol= rl->rectf;
1638
1639         co= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSCo");
1640         color= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSColor");
1641         area= MEM_mallocN(sizeof(float)*handle.totps, "SSSArea");
1642
1643 #if 0
1644         /* create ISB (does not work currently!) */
1645         if(re->r.mode & R_SHADOW)
1646                 ISB_create(pa, NULL);
1647 #endif
1648
1649         if(display) {
1650                 /* initialize scanline updates for main thread */
1651                 rr->renrect.ymin= 0;
1652                 rr->renlay= rl;
1653         }
1654         
1655         seed= pa->rectx*pa->disprect.ymin;
1656 #if 0
1657         rs= pa->rectall;
1658 #else
1659         rz= pa->rectz;
1660         rp= pa->rectp;
1661         ro= pa->recto;
1662         rbz= pa->rectbackz;
1663         rbp= pa->rectbackp;
1664         rbo= pa->rectbacko;
1665 #endif
1666         totpoint= 0;
1667
1668         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
1669                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, fcol+=4) {
1670                         /* per pixel fixed seed */
1671                         BLI_thread_srandom(pa->thread, seed++);
1672                         
1673 #if 0
1674                         if(rs) {
1675                                 /* for each sample in this pixel, shade it */
1676                                 for(ps=(PixStr*)*rs; ps; ps=ps->next) {
1677                                         ObjectInstanceRen *obi= &re->objectinstance[ps->obi];
1678                                         ObjectRen *obr= obi->obr;
1679                                         vlr= RE_findOrAddVlak(obr, (ps->facenr-1) & RE_QUAD_MASK);
1680                                         quad= (ps->facenr & RE_QUAD_OFFS);
1681                                         z= ps->z;
1682
1683                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, z,
1684                                                 co[totpoint], color[totpoint], &area[totpoint]);
1685
1686                                         totpoint++;
1687
1688                                         VECADD(fcol, fcol, color);
1689                                         fcol[3]= 1.0f;
1690                                 }
1691
1692                                 rs++;
1693                         }
1694 #else
1695                         if(rp) {
1696                                 if(*rp != 0) {
1697                                         ObjectInstanceRen *obi= &re->objectinstance[*ro];
1698                                         ObjectRen *obr= obi->obr;
1699
1700                                         /* shade front */
1701                                         vlr= RE_findOrAddVlak(obr, (*rp-1) & RE_QUAD_MASK);
1702                                         quad= ((*rp) & RE_QUAD_OFFS);
1703
1704                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, *rz,
1705                                                 co[totpoint], color[totpoint], &area[totpoint]);
1706                                         
1707                                         VECADD(fcol, fcol, color[totpoint]);
1708                                         fcol[3]= 1.0f;
1709                                         totpoint++;
1710                                 }
1711
1712                                 rp++; rz++; ro++;
1713                         }
1714
1715                         if(rbp) {
1716                                 if(*rbp != 0 && !(*rbp == *(rp-1) && *rbo == *(ro-1))) {
1717                                         ObjectInstanceRen *obi= &re->objectinstance[*rbo];
1718                                         ObjectRen *obr= obi->obr;
1719
1720                                         /* shade back */
1721                                         vlr= RE_findOrAddVlak(obr, (*rbp-1) & RE_QUAD_MASK);
1722                                         quad= ((*rbp) & RE_QUAD_OFFS);
1723
1724                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, *rbz,
1725                                                 co[totpoint], color[totpoint], &area[totpoint]);
1726                                         
1727                                         /* to indicate this is a back sample */
1728                                         area[totpoint]= -area[totpoint];
1729
1730                                         VECADD(fcol, fcol, color[totpoint]);
1731                                         fcol[3]= 1.0f;
1732                                         totpoint++;
1733                                 }
1734
1735                                 rbz++; rbp++; rbo++;
1736                         }
1737 #endif
1738                 }
1739
1740                 if(y&1)
1741                         if(re->test_break(re->tbh)) break; 
1742         }
1743
1744         /* note: after adding we do not free these arrays, sss keeps them */
1745         if(totpoint > 0) {
1746                 sss_add_points(re, co, color, area, totpoint);
1747         }
1748         else {
1749                 MEM_freeN(co);
1750                 MEM_freeN(color);
1751                 MEM_freeN(area);
1752         }
1753         
1754 #if 0
1755         if(re->r.mode & R_SHADOW)
1756                 ISB_free(pa);
1757 #endif
1758                 
1759         if(display) {
1760                 /* display active layer */
1761                 rr->renrect.ymin=rr->renrect.ymax= 0;
1762                 rr->renlay= render_get_active_layer(&R, rr);
1763         }
1764         
1765         zbufshade_sss_free(pa);
1766 }
1767
1768 /* ------------------------------------------------------------------------ */
1769
1770 static void renderhalo_post(RenderResult *rr, float *rectf, HaloRen *har)       /* postprocess version */
1771 {
1772         float dist, xsq, ysq, xn, yn, colf[4], *rectft, *rtf;
1773         float haloxs, haloys;
1774         int minx, maxx, miny, maxy, x, y;
1775
1776         /* calculate the disprect mapped coordinate for halo. note: rectx is disprect corrected */
1777         haloxs= har->xs - R.disprect.xmin;
1778         haloys= har->ys - R.disprect.ymin;
1779         
1780         har->miny= miny= haloys - har->rad/R.ycor;
1781         har->maxy= maxy= haloys + har->rad/R.ycor;
1782         
1783         if(maxy<0);
1784         else if(rr->recty<miny);
1785         else {
1786                 minx= floor(haloxs-har->rad);
1787                 maxx= ceil(haloxs+har->rad);
1788                         
1789                 if(maxx<0);
1790                 else if(rr->rectx<minx);
1791                 else {
1792                 
1793                         if(minx<0) minx= 0;
1794                         if(maxx>=rr->rectx) maxx= rr->rectx-1;
1795                         if(miny<0) miny= 0;
1796                         if(maxy>rr->recty) maxy= rr->recty;
1797         
1798                         rectft= rectf+ 4*rr->rectx*miny;
1799
1800                         for(y=miny; y<maxy; y++) {
1801         
1802                                 rtf= rectft+4*minx;
1803                                 
1804                                 yn= (y - haloys)*R.ycor;
1805                                 ysq= yn*yn;
1806                                 
1807                                 for(x=minx; x<=maxx; x++) {
1808                                         xn= x - haloxs;
1809                                         xsq= xn*xn;
1810                                         dist= xsq+ysq;
1811                                         if(dist<har->radsq) {
1812                                                 
1813                                                 if(shadeHaloFloat(har, colf, 0x7FFFFF, dist, xn, yn, har->flarec))
1814                                                         addalphaAddfacFloat(rtf, colf, har->add);
1815                                         }
1816                                         rtf+=4;
1817                                 }
1818         
1819                                 rectft+= 4*rr->rectx;
1820                                 
1821                                 if(R.test_break(R.tbh)) break; 
1822                         }
1823                 }
1824         }
1825
1826 /* ------------------------------------------------------------------------ */
1827
1828 static void renderflare(RenderResult *rr, float *rectf, HaloRen *har)
1829 {
1830         extern float hashvectf[];
1831         HaloRen fla;
1832         Material *ma;
1833         float *rc, rad, alfa, visifac, vec[3];
1834         int b, type;
1835         
1836         fla= *har;
1837         fla.linec= fla.ringc= fla.flarec= 0;
1838         
1839         rad= har->rad;
1840         alfa= har->alfa;
1841         
1842         visifac= R.ycor*(har->pixels);
1843         /* all radials added / r^3  == 1.0f! */
1844         visifac /= (har->rad*har->rad*har->rad);
1845         visifac*= visifac;
1846
1847         ma= har->mat;
1848         
1849         /* first halo: just do */
1850         
1851         har->rad= rad*ma->flaresize*visifac;
1852         har->radsq= har->rad*har->rad;
1853         har->zs= fla.zs= 0;
1854         
1855         har->alfa= alfa*visifac;
1856
1857         renderhalo_post(rr, rectf, har);
1858         
1859         /* next halo's: the flares */
1860         rc= hashvectf + ma->seed2;
1861         
1862         for(b=1; b<har->flarec; b++) {
1863                 
1864                 fla.r= fabs(rc[0]);
1865                 fla.g= fabs(rc[1]);
1866                 fla.b= fabs(rc[2]);
1867                 fla.alfa= ma->flareboost*fabs(alfa*visifac*rc[3]);
1868                 fla.hard= 20.0f + fabs(70*rc[7]);
1869                 fla.tex= 0;
1870                 
1871                 type= (int)(fabs(3.9*rc[6]));
1872
1873                 fla.rad= ma->subsize*sqrt(fabs(2.0f*har->rad*rc[4]));
1874                 
1875                 if(type==3) {
1876                         fla.rad*= 3.0f;
1877                         fla.rad+= R.rectx/10;
1878                 }
1879                 
1880                 fla.radsq= fla.rad*fla.rad;
1881                 
1882                 vec[0]= 1.4*rc[5]*(har->xs-R.winx/2);
1883                 vec[1]= 1.4*rc[5]*(har->ys-R.winy/2);
1884                 vec[2]= 32.0f*sqrt(vec[0]*vec[0] + vec[1]*vec[1] + 1.0f);
1885                 
1886                 fla.xs= R.winx/2 + vec[0] + (1.2+rc[8])*R.rectx*vec[0]/vec[2];
1887                 fla.ys= R.winy/2 + vec[1] + (1.2+rc[8])*R.rectx*vec[1]/vec[2];
1888
1889                 if(R.flag & R_SEC_FIELD) {
1890                         if(R.r.mode & R_ODDFIELD) fla.ys += 0.5;
1891                         else fla.ys -= 0.5;
1892                 }
1893                 if(type & 1) fla.type= HA_FLARECIRC;
1894                 else fla.type= 0;
1895                 renderhalo_post(rr, rectf, &fla);
1896
1897                 fla.alfa*= 0.5;
1898                 if(type & 2) fla.type= HA_FLARECIRC;
1899                 else fla.type= 0;
1900                 renderhalo_post(rr, rectf, &fla);
1901                 
1902                 rc+= 7;
1903         }
1904 }
1905
1906 /* needs recode... integrate this better! */
1907 void add_halo_flare(Render *re)
1908 {
1909         RenderResult *rr= re->result;
1910         RenderLayer *rl;
1911         HaloRen *har;
1912         int a, mode, do_draw=0;
1913         
1914         /* for now, we get the first renderlayer in list with halos set */
1915         for(rl= rr->layers.first; rl; rl= rl->next)
1916                 if(rl->layflag & SCE_LAY_HALO)
1917                         break;
1918
1919         if(rl==NULL || rl->rectf==NULL)
1920                 return;
1921         
1922         mode= R.r.mode;
1923         R.r.mode &= ~R_PANORAMA;
1924         
1925         project_renderdata(&R, projectverto, 0, 0, 0);
1926         
1927         for(a=0; a<R.tothalo; a++) {
1928                 har= R.sortedhalos[a];
1929                 
1930                 if(har->flarec) {
1931                         do_draw= 1;
1932                         renderflare(rr, rl->rectf, har);
1933                 }
1934         }
1935
1936         if(do_draw) {
1937                 /* weak... the display callback wants an active renderlayer pointer... */
1938                 rr->renlay= rl;
1939                 re->display_draw(re->ddh, rr, NULL);
1940         }
1941         
1942         R.r.mode= mode; 
1943 }
1944
1945 /* ************************* used for shaded view ************************ */
1946
1947 /* if *re, then initialize, otherwise execute */
1948 void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
1949 {
1950         static VlakRen vlr;
1951         static ObjectRen obr;
1952         static ObjectInstanceRen obi;
1953         
1954         /* init */
1955         if(re) {
1956                 R= *re;
1957                 
1958                 /* fake render face */
1959                 memset(&vlr, 0, sizeof(VlakRen));
1960                 memset(&obr, 0, sizeof(ObjectRen));
1961                 memset(&obi, 0, sizeof(ObjectInstanceRen));
1962                 obr.lay= -1;
1963                 obi.obr= &obr;
1964                 
1965                 return;
1966         }
1967         shi->vlr= &vlr;
1968         shi->obr= &obr;
1969         shi->obi= &obi;
1970         
1971         if(shi->mat->nodetree && shi->mat->use_nodes)
1972                 ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
1973         else {
1974                 shade_input_init_material(shi);
1975                 shade_material_loop(shi, shr);
1976         }
1977 }
1978
1979 /* ************************* bake ************************ */
1980
1981
1982 typedef struct BakeShade {
1983         ShadeSample ssamp;
1984         ObjectInstanceRen *obi;
1985         VlakRen *vlr;
1986         
1987         ZSpan *zspan;
1988         Image *ima;
1989         ImBuf *ibuf;
1990         
1991         int rectx, recty, quad, type, vdone, ready;
1992
1993         float dir[3];
1994         Object *actob;
1995         
1996         unsigned int *rect;
1997         float *rect_float;
1998         
1999         int usemask;
2000         char *rect_mask; /* bake pixel mask */
2001
2002         float dxco[3], dyco[3];
2003
2004         short *do_update;
2005 } BakeShade;
2006
2007 /* bake uses a char mask to know what has been baked */
2008 #define BAKE_MASK_NULL          0
2009 #define BAKE_MASK_MARGIN        1
2010 #define BAKE_MASK_BAKED         2
2011 static void bake_mask_filter_extend( char *mask, int width, int height )
2012 {
2013         char *row1, *row2, *row3;
2014         int rowlen, x, y;
2015         char *temprect;
2016         
2017         rowlen= width;
2018         
2019         /* make a copy, to prevent flooding */
2020         temprect= MEM_dupallocN(mask);
2021         
2022         for(y=1; y<=height; y++) {
2023                 /* setup rows */
2024                 row1= (char *)(temprect + (y-2)*rowlen);
2025                 row2= row1 + rowlen;
2026                 row3= row2 + rowlen;
2027                 if(y==1)
2028                         row1= row2;
2029                 else if(y==height)
2030                         row3= row2;
2031                 
2032                 for(x=0; x<rowlen; x++) {
2033                         if (mask[((y-1)*rowlen)+x]==0) {
2034                                 if (*row1 || *row2 || *row3 || *(row1+1) || *(row3+1) ) {
2035                                         mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
2036                                 } else if((x!=rowlen-1) && (*(row1+2) || *(row2+2) || *(row3+2)) ) {
2037                                         mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
2038                                 }
2039                         }
2040                         
2041                         if(x!=0) {
2042                                 row1++; row2++; row3++;
2043                         }
2044                 }
2045         }
2046         MEM_freeN(temprect);
2047 }
2048
2049 static void bake_mask_clear( ImBuf *ibuf, char *mask, char val )
2050 {
2051         int x,y;
2052         if (ibuf->rect_float) {
2053                 for(x=0; x<ibuf->x; x++) {
2054                         for(y=0; y<ibuf->y; y++) {
2055                                 if (mask[ibuf->x*y + x] == val) {
2056                                         float *col= ibuf->rect_float + 4*(ibuf->x*y + x);
2057                                         col[0] = col[1] = col[2] = col[3] = 0.0f;
2058                                 }
2059                         }
2060                 }
2061                 
2062         } else {
2063                 /* char buffer */
2064                 for(x=0; x<ibuf->x; x++) {
2065                         for(y=0; y<ibuf->y; y++) {
2066                                 if (mask[ibuf->x*y + x] == val) {
2067                                         char *col= (char *)(ibuf->rect + ibuf->x*y + x);
2068                                         col[0] = col[1] = col[2] = col[3] = 0;
2069                                 }
2070                         }
2071                 }
2072         }
2073 }
2074
2075 static void bake_set_shade_input(ObjectInstanceRen *obi, VlakRen *vlr, ShadeInput *shi, int quad, int isect, int x, int y, float u, float v)
2076 {
2077         if(isect) {
2078                 /* raytrace intersection with different u,v than scanconvert */
2079                 if(vlr->v4) {
2080                         if(quad)
2081                                 shade_input_set_triangle_i(shi, obi, vlr, 2, 1, 3);
2082                         else
2083                                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 3);
2084                 }
2085                 else
2086                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
2087         }
2088         else {
2089                 /* regular scanconvert */
2090                 if(quad) 
2091                         shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
2092                 else
2093                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
2094         }
2095                 
2096         /* cache for shadow */
2097         shi->samplenr= R.shadowsamplenr[shi->thread]++;
2098
2099         shi->mask= 0xFFFF; /* all samples */
2100         
2101         shi->u= -u;
2102         shi->v= -v;
2103         shi->xs= x;
2104         shi->ys= y;
2105         
2106         shade_input_set_uv(shi);
2107         shade_input_set_normals(shi);
2108
2109         /* no normal flip */
2110         if(shi->flippednor)
2111                 shade_input_flip_normals(shi);
2112
2113         /* set up view vector to look right at the surface (note that the normal
2114          * is negated in the renderer so it does not need to be done here) */
2115         shi->view[0]= shi->vn[0];
2116         shi->view[1]= shi->vn[1];
2117         shi->view[2]= shi->vn[2];
2118 }
2119
2120 static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int x, int y, float u, float v, float *tvn, float *ttang)
2121 {
2122         BakeShade *bs= handle;
2123         ShadeSample *ssamp= &bs->ssamp;
2124         ShadeResult shr;
2125         VlakRen *vlr= shi->vlr;
2126         
2127         shade_input_init_material(shi);
2128         
2129         if(bs->type==RE_BAKE_AO) {
2130                 ambient_occlusion(shi);
2131
2132                 if(R.r.bake_flag & R_BAKE_NORMALIZE) {
2133                         copy_v3_v3(shr.combined, shi->ao);
2134                 }
2135                 else {
2136                         zero_v3(shr.combined);
2137                         environment_lighting_apply(shi, &shr);
2138                 }
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;
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         handles= MEM_callocN(sizeof(BakeShade)*re->r.threads, "BakeShade");
2651
2652         /* get the threads running */
2653         for(a=0; a<re->r.threads; a++) {
2654                 /* set defaults in handles */
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         MEM_freeN(handles);
2736         
2737         BLI_end_threads(&threads);
2738
2739         return vdone;
2740 }
2741
2742 struct Image *RE_bake_shade_get_image(void)
2743 {
2744         return R.bakebuf;
2745 }
2746