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