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