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