Enabled the missing features (not tested)
[blender.git] / source / blender / render / intern / source / rayshade.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) 1990-1998 NeoGeo BV.
21  * All rights reserved.
22  *
23  * Contributors: 2004/2005 Blender Foundation, full recode
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <math.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <float.h>
32 #include <assert.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_material_types.h"
37 #include "DNA_lamp_types.h"
38
39 #include "BKE_global.h"
40 #include "BKE_node.h"
41 #include "BKE_utildefines.h"
42
43 #include "BLI_arithb.h"
44 #include "BLI_blenlib.h"
45 #include "BLI_jitter.h"
46 #include "BLI_rand.h"
47
48 #include "PIL_time.h"
49
50 #include "render_types.h"
51 #include "renderpipeline.h"
52 #include "rendercore.h"
53 #include "renderdatabase.h"
54 #include "pixelblending.h"
55 #include "pixelshading.h"
56 #include "shading.h"
57 #include "texture.h"
58
59 #include "RE_raytrace.h"
60 #include "rayobject.h"
61
62 #define RAY_TRA         1
63 #define RAY_TRAFLIP     2
64
65 #define DEPTH_SHADOW_TRA  10
66
67 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
68 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
69 /* only to be used here in this file, it's for speed */
70 extern struct Render R;
71 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
72
73 #if 0
74 static int vlr_check_intersect(Isect *is, int ob, RayFace *face)
75 {
76         ObjectInstanceRen *obi= RAY_OBJECT_GET((Render*)is->userdata, ob);
77         VlakRen *vlr = (VlakRen*)face;
78
79         /* for baking selected to active non-traceable materials might still
80          * be in the raytree */
81         if(!(vlr->mat->mode & MA_TRACEBLE))
82                 return 0;
83
84         /* I know... cpu cycle waste, might do smarter once */
85         if(is->mode==RE_RAY_MIRROR)
86                 return !(vlr->mat->mode & MA_ONLYCAST);
87         else
88                 return (is->lay & obi->lay);
89 }
90 #endif
91
92 void freeraytree(Render *re)
93 {
94         ObjectInstanceRen *obi;
95         
96         if(re->raytree)
97         {
98                 RE_rayobject_free(re->raytree);
99                 re->raytree = NULL;
100         }
101         if(re->rayfaces)
102         {
103                 MEM_freeN(re->rayfaces);
104                 re->rayfaces = NULL;
105         }
106
107         for(obi=re->instancetable.first; obi; obi=obi->next)
108         {
109                 ObjectRen *obr = obi->obr;
110                 if(obr->raytree)
111                 {
112                         RE_rayobject_free(obr->raytree);
113                         obr->raytree = NULL;
114                 }
115                 if(obr->rayfaces)
116                 {
117                         MEM_freeN(obr->rayfaces);
118                         obr->rayfaces = NULL;
119                 }
120                 if(obi->raytree)
121                 {
122                         RE_rayobject_free(obi->raytree);
123                         obi->raytree = NULL;
124                 }
125         }
126 }
127
128 static int is_raytraceable_vlr(Render *re, VlakRen *vlr)
129 {
130         if((re->flag & R_BAKE_TRACE) || (vlr->mat->mode & MA_TRACEBLE))
131         if((vlr->mat->mode & MA_WIRE)==0)
132                 return 1;
133         return 0;
134 }
135
136 static int is_raytraceable(Render *re, ObjectInstanceRen *obi)
137 {
138         int v;
139         ObjectRen *obr = obi->obr;
140
141         if(re->excludeob && obr->ob == re->excludeob)
142                 return 0;
143
144         for(v=0;v<obr->totvlak;v++)
145         {
146                 VlakRen *vlr = obr->vlaknodes[v>>8].vlak + (v&255);
147                 if(is_raytraceable_vlr(re, vlr))
148                         return 1;
149         }
150         return 0;
151 }
152
153 RayObject* makeraytree_object(Render *re, ObjectInstanceRen *obi)
154 {
155         //TODO
156         // out-of-memory safeproof
157         // break render
158         // update render stats
159         ObjectRen *obr = obi->obr;
160         
161         if(obr->raytree == NULL)
162         {
163                 RayObject *raytree;
164                 RayFace *face;
165                 int v;
166                 
167                 //Count faces
168                 int faces = 0;
169                 for(v=0;v<obr->totvlak;v++)
170                 {
171                         VlakRen *vlr = obr->vlaknodes[v>>8].vlak + (v&255);
172                         if(is_raytraceable_vlr(re, vlr))
173                                 faces++;
174                 }
175                 assert( faces > 0 );
176
177                 //Create Ray cast accelaration structure
178
179                 //TODO dynamic ocres
180 //              raytree = obr->raytree = RE_rayobject_octree_create( re->r.ocres, faces );
181                 raytree = obr->raytree = RE_rayobject_bvh_create( faces );
182                 face = obr->rayfaces = (RayFace*)MEM_callocN(faces*sizeof(RayFace), "ObjectRen faces");
183                 obr->rayobi = obi;
184                 
185                 for(v=0;v<obr->totvlak;v++)
186                 {
187                         VlakRen *vlr = obr->vlaknodes[v>>8].vlak + (v&255);
188                         if(is_raytraceable_vlr(re, vlr))
189                         {
190                                 face->v1 = vlr->v1->co;
191                                 face->v2 = vlr->v2->co;
192                                 face->v3 = vlr->v3->co;
193                                 face->v4 = vlr->v4 ? vlr->v4->co : NULL;
194                                 
195                                 face->ob   = obi;
196                                 face->face = vlr;
197                                 
198                                 RE_rayobject_add( raytree, (RayObject*)face++ );
199                         }
200                 }
201                 RE_rayobject_done( raytree );
202         }
203
204
205         if(obi->flag & R_TRANSFORMED)
206         {
207                 obi->raytree = RE_rayobject_instance_create( obr->raytree, obi->mat, obi, obi->obr->rayobi );
208         }
209         
210         if(obi->raytree) return obi->raytree;
211         return obi->obr->raytree;
212 }
213
214 /*
215  * create an hierarchic raytrace structure with all objects
216  *
217  * R_TRANSFORMED objects instances reuse the same tree by using the rayobject_instance
218  */
219 static void makeraytree_hier(Render *re)
220 {
221         //TODO
222         // out-of-memory safeproof
223         // break render
224         // update render stats
225
226         ObjectInstanceRen *obi;
227         int num_objects = 0;
228
229         re->i.infostr="Creating raytrace structure";
230         re->stats_draw(re->sdh, &re->i);
231
232         //Count number of objects
233         for(obi=re->instancetable.first; obi; obi=obi->next)
234         if(is_raytraceable(re, obi))
235                 num_objects++;
236
237         //Create raytree
238         re->raytree = RE_rayobject_bvh_create( num_objects );
239         
240         for(obi=re->instancetable.first; obi; obi=obi->next)
241         if(is_raytraceable(re, obi))
242         {
243                 RayObject *obj = makeraytree_object(re, obi);
244                 RE_rayobject_add( re->raytree, obj );
245
246                 if(re->test_break(re->tbh))
247                         break;
248         }
249
250         if(!re->test_break(re->tbh))
251         {
252                 RE_rayobject_done( re->raytree );
253         }
254
255         re->i.infostr= NULL;
256         re->stats_draw(re->sdh, &re->i);
257 }
258
259 /*
260  * create a single raytrace structure with all faces
261  */
262 static void makeraytree_single(Render *re)
263 {
264         ObjectInstanceRen *obi;
265         RayObject *raytree;
266         RayFace *face;
267         int faces = 0, obs = 0;
268
269         for(obi=re->instancetable.first; obi; obi=obi->next)
270         if(is_raytraceable(re, obi))
271         {
272                 int v;
273                 ObjectRen *obr = obi->obr;
274                 obs++;
275                 
276                 assert((obi->flag & R_TRANSFORMED) == 0); //Not suported
277         
278                 for(v=0;v<obr->totvlak;v++)
279                 {
280                         VlakRen *vlr = obr->vlaknodes[v>>8].vlak + (v&255);
281                         if(is_raytraceable_vlr(re, vlr))
282                                 faces++;
283                 }
284         }
285         
286         //Create raytree
287 //      raytree = re->raytree   = RE_rayobject_octree_create(re->r.ocres, faces);
288         raytree = re->raytree   = RE_rayobject_bvh_create(faces);
289         face    = re->rayfaces  = (RayFace*)MEM_callocN(faces*sizeof(RayFace), "Render ray faces");
290         
291         for(obi=re->instancetable.first; obi; obi=obi->next)
292         if(is_raytraceable(re, obi))
293         {
294                 int v;
295                 ObjectRen *obr = obi->obr;
296
297                 for(v=0;v<obr->totvlak;v++)
298                 {
299                         VlakRen *vlr = obr->vlaknodes[v>>8].vlak + (v&255);
300                         face->v1 = vlr->v1->co;
301                         face->v2 = vlr->v2->co;
302                         face->v3 = vlr->v3->co;
303                         face->v4 = vlr->v4 ? vlr->v4->co : NULL;
304                         
305                         face->ob   = obi;
306                         face->face = vlr;
307                         
308                         RE_rayobject_add( raytree, (RayObject*)face++ );
309                 }
310         }
311         RE_rayobject_done( raytree );   
312 }
313
314 void makeraytree(Render *re)
315 {
316         if(1)
317                 makeraytree_hier(re);
318         else
319                 makeraytree_single(re);
320 }
321
322
323
324 static void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr)
325 {
326         ObjectInstanceRen *obi= (ObjectInstanceRen*)is->hit.ob;
327         VlakRen *vlr= (VlakRen*)is->hit.face;
328         int osatex= 0;
329         
330         /* set up view vector */
331         VECCOPY(shi->view, is->vec);
332
333         /* render co */
334         shi->co[0]= is->start[0]+is->labda*(shi->view[0]);
335         shi->co[1]= is->start[1]+is->labda*(shi->view[1]);
336         shi->co[2]= is->start[2]+is->labda*(shi->view[2]);
337         
338         Normalize(shi->view);
339
340         shi->obi= obi;
341         shi->obr= obi->obr;
342         shi->vlr= vlr;
343         shi->mat= vlr->mat;
344         memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));        // note, keep this synced with render_types.h
345         shi->har= shi->mat->har;
346         
347         // Osa structs we leave unchanged now
348         SWAP(int, osatex, shi->osatex);
349         
350         shi->dxco[0]= shi->dxco[1]= shi->dxco[2]= 0.0f;
351         shi->dyco[0]= shi->dyco[1]= shi->dyco[2]= 0.0f;
352         
353         // but, set Osa stuff to zero where it can confuse texture code
354         if(shi->mat->texco & (TEXCO_NORM|TEXCO_REFL) ) {
355                 shi->dxno[0]= shi->dxno[1]= shi->dxno[2]= 0.0f;
356                 shi->dyno[0]= shi->dyno[1]= shi->dyno[2]= 0.0f;
357         }
358
359         if(vlr->v4) {
360                 if(is->isect==2) 
361                         shade_input_set_triangle_i(shi, obi, vlr, 2, 1, 3);
362                 else
363                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 3);
364         }
365         else {
366                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
367         }
368
369         shi->u= is->u;
370         shi->v= is->v;
371         shi->dx_u= shi->dx_v= shi->dy_u= shi->dy_v=  0.0f;
372
373         shade_input_set_normals(shi);
374
375         /* point normals to viewing direction */
376         if(INPR(shi->facenor, shi->view) < 0.0f)
377                 shade_input_flip_normals(shi);
378
379         shade_input_set_shade_texco(shi);
380         
381         if(is->mode==RE_RAY_SHADOW_TRA) {
382                 /* temp hack to prevent recursion */
383                 if(shi->nodes==0 && shi->mat->nodetree && shi->mat->use_nodes) {
384                         ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
385                         shi->mat= vlr->mat;             /* shi->mat is being set in nodetree */
386                 }
387                 else
388                         shade_color(shi, shr);
389         }
390         else {
391                 if(shi->mat->nodetree && shi->mat->use_nodes) {
392                         ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
393                         shi->mat= vlr->mat;             /* shi->mat is being set in nodetree */
394                 }
395                 else
396                         shade_material_loop(shi, shr);
397                 
398                 /* raytrace likes to separate the spec color */
399                 VECSUB(shr->diff, shr->combined, shr->spec);
400         }       
401         
402         SWAP(int, osatex, shi->osatex);  // XXXXX!!!!
403
404 }
405
406 static int refraction(float *refract, float *n, float *view, float index)
407 {
408         float dot, fac;
409
410         VECCOPY(refract, view);
411         
412         dot= view[0]*n[0] + view[1]*n[1] + view[2]*n[2];
413
414         if(dot>0.0f) {
415                 index = 1.0f/index;
416                 fac= 1.0f - (1.0f - dot*dot)*index*index;
417                 if(fac<= 0.0f) return 0;
418                 fac= -dot*index + sqrt(fac);
419         }
420         else {
421                 fac= 1.0f - (1.0f - dot*dot)*index*index;
422                 if(fac<= 0.0f) return 0;
423                 fac= -dot*index - sqrt(fac);
424         }
425
426         refract[0]= index*view[0] + fac*n[0];
427         refract[1]= index*view[1] + fac*n[1];
428         refract[2]= index*view[2] + fac*n[2];
429
430         return 1;
431 }
432
433 /* orn = original face normal */
434 static void reflection(float *ref, float *n, float *view, float *orn)
435 {
436         float f1;
437         
438         f1= -2.0f*(n[0]*view[0]+ n[1]*view[1]+ n[2]*view[2]);
439         
440         ref[0]= (view[0]+f1*n[0]);
441         ref[1]= (view[1]+f1*n[1]);
442         ref[2]= (view[2]+f1*n[2]);
443
444         if(orn) {
445                 /* test phong normals, then we should prevent vector going to the back */
446                 f1= ref[0]*orn[0]+ ref[1]*orn[1]+ ref[2]*orn[2];
447                 if(f1>0.0f) {
448                         f1+= .01f;
449                         ref[0]-= f1*orn[0];
450                         ref[1]-= f1*orn[1];
451                         ref[2]-= f1*orn[2];
452                 }
453         }
454 }
455
456 #if 0
457 static void color_combine(float *result, float fac1, float fac2, float *col1, float *col2)
458 {
459         float col1t[3], col2t[3];
460         
461         col1t[0]= sqrt(col1[0]);
462         col1t[1]= sqrt(col1[1]);
463         col1t[2]= sqrt(col1[2]);
464         col2t[0]= sqrt(col2[0]);
465         col2t[1]= sqrt(col2[1]);
466         col2t[2]= sqrt(col2[2]);
467
468         result[0]= (fac1*col1t[0] + fac2*col2t[0]);
469         result[0]*= result[0];
470         result[1]= (fac1*col1t[1] + fac2*col2t[1]);
471         result[1]*= result[1];
472         result[2]= (fac1*col1t[2] + fac2*col2t[2]);
473         result[2]*= result[2];
474 }
475 #endif
476
477 static float shade_by_transmission(Isect *is, ShadeInput *shi, ShadeResult *shr)
478 {
479         float dx, dy, dz, d, p;
480
481         if (0 == (shi->mat->mode & (MA_RAYTRANSP|MA_ZTRA)))
482                 return -1;
483            
484         if (shi->mat->tx_limit <= 0.0f) {
485                 d= 1.0f;
486         } 
487         else {
488                 /* shi.co[] calculated by shade_ray() */
489                 dx= shi->co[0] - is->start[0];
490                 dy= shi->co[1] - is->start[1];
491                 dz= shi->co[2] - is->start[2];
492                 d= sqrt(dx*dx+dy*dy+dz*dz);
493                 if (d > shi->mat->tx_limit)
494                         d= shi->mat->tx_limit;
495
496                 p = shi->mat->tx_falloff;
497                 if(p < 0.0f) p= 0.0f;
498                 else if (p > 10.0f) p= 10.0f;
499
500                 shr->alpha *= pow(d, p);
501                 if (shr->alpha > 1.0f)
502                         shr->alpha= 1.0f;
503         }
504
505         return d;
506 }
507
508 static void ray_fadeout_endcolor(float *col, ShadeInput *origshi, ShadeInput *shi, ShadeResult *shr, Isect *isec, float *vec)
509 {
510         /* un-intersected rays get either rendered material color or sky color */
511         if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOMAT) {
512                 VECCOPY(col, shr->combined);
513         } else if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOSKY) {
514                 VECCOPY(shi->view, vec);
515                 Normalize(shi->view);
516                 
517                 shadeSkyView(col, isec->start, shi->view, NULL, shi->thread);
518                 shadeSunView(col, shi->view);
519         }
520 }
521
522 static void ray_fadeout(Isect *is, ShadeInput *shi, float *col, float *blendcol, float dist_mir)
523 {
524         /* if fading out, linear blend against fade color */
525         float blendfac;
526
527         blendfac = 1.0 - VecLenf(shi->co, is->start)/dist_mir;
528         
529         col[0] = col[0]*blendfac + (1.0 - blendfac)*blendcol[0];
530         col[1] = col[1]*blendfac + (1.0 - blendfac)*blendcol[1];
531         col[2] = col[2]*blendfac + (1.0 - blendfac)*blendcol[2];
532 }
533
534 /* the main recursive tracer itself */
535 static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, float *start, float *vec, float *col, ObjectInstanceRen *obi, VlakRen *vlr, int traflag)
536 {
537         ShadeInput shi;
538         ShadeResult shr;
539         Isect isec;
540         float f, f1, fr, fg, fb;
541         float ref[3];
542         float dist_mir = origshi->mat->dist_mir;
543
544         /* Warning, This is not that nice, and possibly a bit slow for every ray,
545         however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
546         memset(&shi, 0, sizeof(ShadeInput)); 
547         /* end warning! - Campbell */
548         
549         VECCOPY(isec.start, start);
550         VECCOPY(isec.vec, vec );
551         isec.labda = dist_mir > 0 ? dist_mir : RE_RAYTRACE_MAXDIST;
552         isec.mode= RE_RAY_MIRROR;
553         isec.skip = RE_SKIP_VLR_NEIGHBOUR;
554
555         isec.orig.ob   = obi;
556         isec.orig.face = vlr;
557
558         if(RE_rayobject_raycast(R.raytree, &isec)) {
559                 float d= 1.0f;
560                 
561                 shi.mask= origshi->mask;
562                 shi.osatex= origshi->osatex;
563                 shi.depth= 1;                                   /* only used to indicate tracing */
564                 shi.thread= origshi->thread;
565                 //shi.sample= 0; // memset above, so dont need this
566                 shi.xs= origshi->xs;
567                 shi.ys= origshi->ys;
568                 shi.lay= origshi->lay;
569                 shi.passflag= SCE_PASS_COMBINED; /* result of tracing needs no pass info */
570                 shi.combinedflag= 0xFFFFFF;              /* ray trace does all options */
571                 //shi.do_preview= 0; // memset above, so dont need this
572                 shi.light_override= origshi->light_override;
573                 shi.mat_override= origshi->mat_override;
574                 
575                 memset(&shr, 0, sizeof(ShadeResult));
576                 
577                 shade_ray(&isec, &shi, &shr);
578                 if (traflag & RAY_TRA)
579                         d= shade_by_transmission(&isec, &shi, &shr);
580                 
581                 if(depth>0) {
582
583                         if(shi.mat->mode_l & (MA_RAYTRANSP|MA_ZTRA) && shr.alpha < 1.0f) {
584                                 float nf, f, f1, refract[3], tracol[4];
585                                 
586                                 tracol[0]= shi.r;
587                                 tracol[1]= shi.g;
588                                 tracol[2]= shi.b;
589                                 tracol[3]= col[3];      // we pass on and accumulate alpha
590                                 
591                                 if(shi.mat->mode & MA_RAYTRANSP) {
592                                         /* odd depths: use normal facing viewer, otherwise flip */
593                                         if(traflag & RAY_TRAFLIP) {
594                                                 float norm[3];
595                                                 norm[0]= - shi.vn[0];
596                                                 norm[1]= - shi.vn[1];
597                                                 norm[2]= - shi.vn[2];
598                                                 if (!refraction(refract, norm, shi.view, shi.ang))
599                                                         reflection(refract, norm, shi.view, shi.vn);
600                                         }
601                                         else {
602                                                 if (!refraction(refract, shi.vn, shi.view, shi.ang))
603                                                         reflection(refract, shi.vn, shi.view, shi.vn);
604                                         }
605                                         traflag |= RAY_TRA;
606                                         traceray(origshi, origshr, depth-1, shi.co, refract, tracol, shi.obi, shi.vlr, traflag ^ RAY_TRAFLIP);
607                                 }
608                                 else
609                                         traceray(origshi, origshr, depth-1, shi.co, shi.view, tracol, shi.obi, shi.vlr, 0);
610                                 
611                                 f= shr.alpha; f1= 1.0f-f;
612                                 nf= d * shi.mat->filter;
613                                 fr= 1.0f+ nf*(shi.r-1.0f);
614                                 fg= 1.0f+ nf*(shi.g-1.0f);
615                                 fb= 1.0f+ nf*(shi.b-1.0f);
616                                 shr.diff[0]= f*shr.diff[0] + f1*fr*tracol[0];
617                                 shr.diff[1]= f*shr.diff[1] + f1*fg*tracol[1];
618                                 shr.diff[2]= f*shr.diff[2] + f1*fb*tracol[2];
619                                 
620                                 shr.spec[0] *=f;
621                                 shr.spec[1] *=f;
622                                 shr.spec[2] *=f;
623
624                                 col[3]= f1*tracol[3] + f;
625                         }
626                         else 
627                                 col[3]= 1.0f;
628
629                         if(shi.mat->mode_l & MA_RAYMIRROR) {
630                                 f= shi.ray_mirror;
631                                 if(f!=0.0f) f*= fresnel_fac(shi.view, shi.vn, shi.mat->fresnel_mir_i, shi.mat->fresnel_mir);
632                         }
633                         else f= 0.0f;
634                         
635                         if(f!=0.0f) {
636                                 float mircol[4];
637                                 
638                                 reflection(ref, shi.vn, shi.view, NULL);                        
639                                 traceray(origshi, origshr, depth-1, shi.co, ref, mircol, shi.obi, shi.vlr, 0);
640                         
641                                 f1= 1.0f-f;
642
643                                 /* combine */
644                                 //color_combine(col, f*fr*(1.0f-shr.spec[0]), f1, col, shr.diff);
645                                 //col[0]+= shr.spec[0];
646                                 //col[1]+= shr.spec[1];
647                                 //col[2]+= shr.spec[2];
648                                 
649                                 fr= shi.mirr;
650                                 fg= shi.mirg;
651                                 fb= shi.mirb;
652                 
653                                 col[0]= f*fr*(1.0f-shr.spec[0])*mircol[0] + f1*shr.diff[0] + shr.spec[0];
654                                 col[1]= f*fg*(1.0f-shr.spec[1])*mircol[1] + f1*shr.diff[1] + shr.spec[1];
655                                 col[2]= f*fb*(1.0f-shr.spec[2])*mircol[2] + f1*shr.diff[2] + shr.spec[2];
656                         }
657                         else {
658                                 col[0]= shr.diff[0] + shr.spec[0];
659                                 col[1]= shr.diff[1] + shr.spec[1];
660                                 col[2]= shr.diff[2] + shr.spec[2];
661                         }
662                         
663                         if (dist_mir > 0.0) {
664                                 float blendcol[3];
665                                 
666                                 /* max ray distance set, but found an intersection, so fade this color
667                                  * out towards the sky/material color for a smooth transition */
668                                 ray_fadeout_endcolor(blendcol, origshi, &shi, origshr, &isec, vec);
669                                 ray_fadeout(&isec, &shi, col, blendcol, dist_mir);
670                         }
671                 }
672                 else {
673                         col[0]= shr.diff[0] + shr.spec[0];
674                         col[1]= shr.diff[1] + shr.spec[1];
675                         col[2]= shr.diff[2] + shr.spec[2];
676                 }
677                 
678         }
679         else {
680                 ray_fadeout_endcolor(col, origshi, &shi, origshr, &isec, vec);
681         }
682 }
683
684 /* **************** jitter blocks ********** */
685
686 /* calc distributed planar energy */
687
688 static void DP_energy(float *table, float *vec, int tot, float xsize, float ysize)
689 {
690         int x, y, a;
691         float *fp, force[3], result[3];
692         float dx, dy, dist, min;
693         
694         min= MIN2(xsize, ysize);
695         min*= min;
696         result[0]= result[1]= 0.0f;
697         
698         for(y= -1; y<2; y++) {
699                 dy= ysize*y;
700                 for(x= -1; x<2; x++) {
701                         dx= xsize*x;
702                         fp= table;
703                         for(a=0; a<tot; a++, fp+= 2) {
704                                 force[0]= vec[0] - fp[0]-dx;
705                                 force[1]= vec[1] - fp[1]-dy;
706                                 dist= force[0]*force[0] + force[1]*force[1];
707                                 if(dist < min && dist>0.0f) {
708                                         result[0]+= force[0]/dist;
709                                         result[1]+= force[1]/dist;
710                                 }
711                         }
712                 }
713         }
714         vec[0] += 0.1*min*result[0]/(float)tot;
715         vec[1] += 0.1*min*result[1]/(float)tot;
716         // cyclic clamping
717         vec[0]= vec[0] - xsize*floor(vec[0]/xsize + 0.5);
718         vec[1]= vec[1] - ysize*floor(vec[1]/ysize + 0.5);
719 }
720
721 // random offset of 1 in 2
722 static void jitter_plane_offset(float *jitter1, float *jitter2, int tot, float sizex, float sizey, float ofsx, float ofsy)
723 {
724         float dsizex= sizex*ofsx;
725         float dsizey= sizey*ofsy;
726         float hsizex= 0.5*sizex, hsizey= 0.5*sizey;
727         int x;
728         
729         for(x=tot; x>0; x--, jitter1+=2, jitter2+=2) {
730                 jitter2[0]= jitter1[0] + dsizex;
731                 jitter2[1]= jitter1[1] + dsizey;
732                 if(jitter2[0] > hsizex) jitter2[0]-= sizex;
733                 if(jitter2[1] > hsizey) jitter2[1]-= sizey;
734         }
735 }
736
737 /* called from convertBlenderScene.c */
738 /* we do this in advance to get consistant random, not alter the render seed, and be threadsafe */
739 void init_jitter_plane(LampRen *lar)
740 {
741         float *fp;
742         int x, iter=12, tot= lar->ray_totsamp;
743         
744         /* test if already initialized */
745         if(lar->jitter) return;
746         
747         /* at least 4, or max threads+1 tables */
748         if(BLENDER_MAX_THREADS < 4) x= 4;
749         else x= BLENDER_MAX_THREADS+1;
750         fp= lar->jitter= MEM_callocN(x*tot*2*sizeof(float), "lamp jitter tab");
751         
752         /* if 1 sample, we leave table to be zero's */
753         if(tot>1) {
754                 
755                 /* set per-lamp fixed seed */
756                 BLI_srandom(tot);
757                 
758                 /* fill table with random locations, area_size large */
759                 for(x=0; x<tot; x++, fp+=2) {
760                         fp[0]= (BLI_frand()-0.5)*lar->area_size;
761                         fp[1]= (BLI_frand()-0.5)*lar->area_sizey;
762                 }
763                 
764                 while(iter--) {
765                         fp= lar->jitter;
766                         for(x=tot; x>0; x--, fp+=2) {
767                                 DP_energy(lar->jitter, fp, tot, lar->area_size, lar->area_sizey);
768                         }
769                 }
770         }       
771         /* create the dithered tables (could just check lamp type!) */
772         jitter_plane_offset(lar->jitter, lar->jitter+2*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.0f);
773         jitter_plane_offset(lar->jitter, lar->jitter+4*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.5f);
774         jitter_plane_offset(lar->jitter, lar->jitter+6*tot, tot, lar->area_size, lar->area_sizey, 0.0f, 0.5f);
775 }
776
777 /* table around origin, -0.5*size to 0.5*size */
778 static float *give_jitter_plane(LampRen *lar, int thread, int xs, int ys)
779 {
780         int tot;
781         
782         tot= lar->ray_totsamp;
783                         
784         if(lar->ray_samp_type & LA_SAMP_JITTER) {
785                 /* made it threadsafe */
786                 
787                 if(lar->xold[thread]!=xs || lar->yold[thread]!=ys) {
788                         jitter_plane_offset(lar->jitter, lar->jitter+2*(thread+1)*tot, tot, lar->area_size, lar->area_sizey, BLI_thread_frand(thread), BLI_thread_frand(thread));
789                         lar->xold[thread]= xs; 
790                         lar->yold[thread]= ys;
791                 }
792                 return lar->jitter+2*(thread+1)*tot;
793         }
794         if(lar->ray_samp_type & LA_SAMP_DITHER) {
795                 return lar->jitter + 2*tot*((xs & 1)+2*(ys & 1));
796         }
797         
798         return lar->jitter;
799 }
800
801
802 /* **************** QMC sampling *************** */
803
804 static void halton_sample(double *ht_invprimes, double *ht_nums, double *v)
805 {
806         // incremental halton sequence generator, from:
807         // "Instant Radiosity", Keller A.
808         unsigned int i;
809         
810         for (i = 0; i < 2; i++)
811         {
812                 double r = fabs((1.0 - ht_nums[i]) - 1e-10);
813                 
814                 if (ht_invprimes[i] >= r)
815                 {
816                         double lasth;
817                         double h = ht_invprimes[i];
818                         
819                         do {
820                                 lasth = h;
821                                 h *= ht_invprimes[i];
822                         } while (h >= r);
823                         
824                         ht_nums[i] += ((lasth + h) - 1.0);
825                 }
826                 else
827                         ht_nums[i] += ht_invprimes[i];
828                 
829                 v[i] = (float)ht_nums[i];
830         }
831 }
832
833 /* Generate Hammersley points in [0,1)^2
834  * From Lucille renderer */
835 static void hammersley_create(double *out, int n)
836 {
837         double p, t;
838         int k, kk;
839
840         for (k = 0; k < n; k++) {
841                 t = 0;
842                 for (p = 0.5, kk = k; kk; p *= 0.5, kk >>= 1) {
843                         if (kk & 1) {           /* kk mod 2 = 1         */
844                                 t += p;
845                         }
846                 }
847         
848                 out[2 * k + 0] = (double)k / (double)n;
849                 out[2 * k + 1] = t;
850         }
851 }
852
853 static struct QMCSampler *QMC_initSampler(int type, int tot)
854 {       
855         QMCSampler *qsa = MEM_callocN(sizeof(QMCSampler), "qmc sampler");
856         qsa->samp2d = MEM_callocN(2*sizeof(double)*tot, "qmc sample table");
857
858         qsa->tot = tot;
859         qsa->type = type;
860         
861         if (qsa->type==SAMP_TYPE_HAMMERSLEY) 
862                 hammersley_create(qsa->samp2d, qsa->tot);
863                 
864         return qsa;
865 }
866
867 static void QMC_initPixel(QMCSampler *qsa, int thread)
868 {
869         if (qsa->type==SAMP_TYPE_HAMMERSLEY)
870         {
871                 /* hammersley sequence is fixed, already created in QMCSampler init.
872                  * per pixel, gets a random offset. We create separate offsets per thread, for write-safety */
873                 qsa->offs[thread][0] = 0.5 * BLI_thread_frand(thread);
874                 qsa->offs[thread][1] = 0.5 * BLI_thread_frand(thread);
875         }
876         else {  /* SAMP_TYPE_HALTON */
877                 
878                 /* generate a new randomised halton sequence per pixel
879                  * to alleviate qmc artifacts and make it reproducable 
880                  * between threads/frames */
881                 double ht_invprimes[2], ht_nums[2];
882                 double r[2];
883                 int i;
884         
885                 ht_nums[0] = BLI_thread_frand(thread);
886                 ht_nums[1] = BLI_thread_frand(thread);
887                 ht_invprimes[0] = 0.5;
888                 ht_invprimes[1] = 1.0/3.0;
889                 
890                 for (i=0; i< qsa->tot; i++) {
891                         halton_sample(ht_invprimes, ht_nums, r);
892                         qsa->samp2d[2*i+0] = r[0];
893                         qsa->samp2d[2*i+1] = r[1];
894                 }
895         }
896 }
897
898 static void QMC_freeSampler(QMCSampler *qsa)
899 {
900         MEM_freeN(qsa->samp2d);
901         MEM_freeN(qsa);
902 }
903
904 static void QMC_getSample(double *s, QMCSampler *qsa, int thread, int num)
905 {
906         if (qsa->type == SAMP_TYPE_HAMMERSLEY) {
907                 s[0] = fmod(qsa->samp2d[2*num+0] + qsa->offs[thread][0], 1.0f);
908                 s[1] = fmod(qsa->samp2d[2*num+1] + qsa->offs[thread][1], 1.0f);
909         }
910         else { /* SAMP_TYPE_HALTON */
911                 s[0] = qsa->samp2d[2*num+0];
912                 s[1] = qsa->samp2d[2*num+1];
913         }
914 }
915
916 /* phong weighted disc using 'blur' for exponent, centred on 0,0 */
917 static void QMC_samplePhong(float *vec, QMCSampler *qsa, int thread, int num, float blur)
918 {
919         double s[2];
920         float phi, pz, sqr;
921         
922         QMC_getSample(s, qsa, thread, num);
923
924         phi = s[0]*2*M_PI;
925         pz = pow(s[1], blur);
926         sqr = sqrt(1.0f-pz*pz);
927
928         vec[0] = cos(phi)*sqr;
929         vec[1] = sin(phi)*sqr;
930         vec[2] = 0.0f;
931 }
932
933 /* rect of edge lengths sizex, sizey, centred on 0.0,0.0 i.e. ranging from -sizex/2 to +sizey/2 */
934 static void QMC_sampleRect(float *vec, QMCSampler *qsa, int thread, int num, float sizex, float sizey)
935 {
936         double s[2];
937
938         QMC_getSample(s, qsa, thread, num);
939                 
940         vec[0] = (s[0] - 0.5) * sizex;
941         vec[1] = (s[1] - 0.5) * sizey;
942         vec[2] = 0.0f;
943 }
944
945 /* disc of radius 'radius', centred on 0,0 */
946 static void QMC_sampleDisc(float *vec, QMCSampler *qsa, int thread, int num, float radius)
947 {
948         double s[2];
949         float phi, sqr;
950         
951         QMC_getSample(s, qsa, thread, num);
952         
953         phi = s[0]*2*M_PI;
954         sqr = sqrt(s[1]);
955
956         vec[0] = cos(phi)*sqr* radius/2.0;
957         vec[1] = sin(phi)*sqr* radius/2.0;
958         vec[2] = 0.0f;
959 }
960
961 /* uniform hemisphere sampling */
962 static void QMC_sampleHemi(float *vec, QMCSampler *qsa, int thread, int num)
963 {
964         double s[2];
965         float phi, sqr;
966         
967         QMC_getSample(s, qsa, thread, num);
968         
969         phi = s[0]*2.f*M_PI;    
970         sqr = sqrt(s[1]);
971
972         vec[0] = cos(phi)*sqr;
973         vec[1] = sin(phi)*sqr;
974         vec[2] = 1.f - s[1]*s[1];
975 }
976
977 #if 0 /* currently not used */
978 /* cosine weighted hemisphere sampling */
979 static void QMC_sampleHemiCosine(float *vec, QMCSampler *qsa, int thread, int num)
980 {
981         double s[2];
982         float phi, sqr;
983         
984         QMC_getSample(s, qsa, thread, num);
985         
986         phi = s[0]*2.f*M_PI;    
987         sqr = s[1]*sqrt(2-s[1]*s[1]);
988
989         vec[0] = cos(phi)*sqr;
990         vec[1] = sin(phi)*sqr;
991         vec[2] = 1.f - s[1]*s[1];
992
993 }
994 #endif
995
996 /* called from convertBlenderScene.c */
997 void init_render_qmcsampler(Render *re)
998 {
999         re->qmcsamplers= MEM_callocN(sizeof(ListBase)*BLENDER_MAX_THREADS, "QMCListBase");
1000 }
1001
1002 static QMCSampler *get_thread_qmcsampler(Render *re, int thread, int type, int tot)
1003 {
1004         QMCSampler *qsa;
1005
1006         /* create qmc samplers as needed, since recursion makes it hard to
1007          * predict how many are needed */
1008
1009         for(qsa=re->qmcsamplers[thread].first; qsa; qsa=qsa->next) {
1010                 if(qsa->type == type && qsa->tot == tot && !qsa->used) {
1011                         qsa->used= 1;
1012                         return qsa;
1013                 }
1014         }
1015
1016         qsa= QMC_initSampler(type, tot);
1017         qsa->used= 1;
1018         BLI_addtail(&re->qmcsamplers[thread], qsa);
1019
1020         return qsa;
1021 }
1022
1023 static void release_thread_qmcsampler(Render *re, int thread, QMCSampler *qsa)
1024 {
1025         qsa->used= 0;
1026 }
1027
1028 void free_render_qmcsampler(Render *re)
1029 {
1030         QMCSampler *qsa, *next;
1031         int a;
1032
1033         if(re->qmcsamplers) {
1034                 for(a=0; a<BLENDER_MAX_THREADS; a++) {
1035                         for(qsa=re->qmcsamplers[a].first; qsa; qsa=next) {
1036                                 next= qsa->next;
1037                                 QMC_freeSampler(qsa);
1038                         }
1039
1040                         re->qmcsamplers[a].first= re->qmcsamplers[a].last= NULL;
1041                 }
1042
1043                 MEM_freeN(re->qmcsamplers);
1044                 re->qmcsamplers= NULL;
1045         }
1046 }
1047
1048 static int adaptive_sample_variance(int samples, float *col, float *colsq, float thresh)
1049 {
1050         float var[3], mean[3];
1051
1052         /* scale threshold just to give a bit more precision in input rather than dealing with 
1053          * tiny tiny numbers in the UI */
1054         thresh /= 2;
1055         
1056         mean[0] = col[0] / (float)samples;
1057         mean[1] = col[1] / (float)samples;
1058         mean[2] = col[2] / (float)samples;
1059
1060         var[0] = (colsq[0] / (float)samples) - (mean[0]*mean[0]);
1061         var[1] = (colsq[1] / (float)samples) - (mean[1]*mean[1]);
1062         var[2] = (colsq[2] / (float)samples) - (mean[2]*mean[2]);
1063         
1064         if ((var[0] * 0.4 < thresh) && (var[1] * 0.3 < thresh) && (var[2] * 0.6 < thresh))
1065                 return 1;
1066         else
1067                 return 0;
1068 }
1069
1070 static int adaptive_sample_contrast_val(int samples, float prev, float val, float thresh)
1071 {
1072         /* if the last sample's contribution to the total value was below a small threshold
1073          * (i.e. the samples taken are very similar), then taking more samples that are probably 
1074          * going to be the same is wasting effort */
1075         if (fabs( prev/(float)(samples-1) - val/(float)samples ) < thresh) {
1076                 return 1;
1077         } else
1078                 return 0;
1079 }
1080
1081 static float get_avg_speed(ShadeInput *shi)
1082 {
1083         float pre_x, pre_y, post_x, post_y, speedavg;
1084         
1085         pre_x = (shi->winspeed[0] == PASS_VECTOR_MAX)?0.0:shi->winspeed[0];
1086         pre_y = (shi->winspeed[1] == PASS_VECTOR_MAX)?0.0:shi->winspeed[1];
1087         post_x = (shi->winspeed[2] == PASS_VECTOR_MAX)?0.0:shi->winspeed[2];
1088         post_y = (shi->winspeed[3] == PASS_VECTOR_MAX)?0.0:shi->winspeed[3];
1089         
1090         speedavg = (sqrt(pre_x*pre_x + pre_y*pre_y) + sqrt(post_x*post_x + post_y*post_y)) / 2.0;
1091         
1092         return speedavg;
1093 }
1094
1095 /* ***************** main calls ************** */
1096
1097
1098 static void trace_refract(float *col, ShadeInput *shi, ShadeResult *shr)
1099 {
1100         QMCSampler *qsa=NULL;
1101         int samp_type;
1102         
1103         float samp3d[3], orthx[3], orthy[3];
1104         float v_refract[3], v_refract_new[3];
1105         float sampcol[4], colsq[4];
1106         
1107         float blur = pow(1.0 - shi->mat->gloss_tra, 3);
1108         short max_samples = shi->mat->samp_gloss_tra;
1109         float adapt_thresh = shi->mat->adapt_thresh_tra;
1110         
1111         int samples=0;
1112         
1113         colsq[0] = colsq[1] = colsq[2] = 0.0;
1114         col[0] = col[1] = col[2] = 0.0;
1115         col[3]= shr->alpha;
1116         
1117         if (blur > 0.0) {
1118                 if (adapt_thresh != 0.0) samp_type = SAMP_TYPE_HALTON;
1119                 else samp_type = SAMP_TYPE_HAMMERSLEY;
1120                         
1121                 /* all samples are generated per pixel */
1122                 qsa = get_thread_qmcsampler(&R, shi->thread, samp_type, max_samples);
1123                 QMC_initPixel(qsa, shi->thread);
1124         } else 
1125                 max_samples = 1;
1126         
1127
1128         while (samples < max_samples) {         
1129                 refraction(v_refract, shi->vn, shi->view, shi->ang);
1130                 
1131                 if (max_samples > 1) {
1132                         /* get a quasi-random vector from a phong-weighted disc */
1133                         QMC_samplePhong(samp3d, qsa, shi->thread, samples, blur);
1134                                                 
1135                         VecOrthoBasisf(v_refract, orthx, orthy);
1136                         VecMulf(orthx, samp3d[0]);
1137                         VecMulf(orthy, samp3d[1]);
1138                                 
1139                         /* and perturb the refraction vector in it */
1140                         VecAddf(v_refract_new, v_refract, orthx);
1141                         VecAddf(v_refract_new, v_refract_new, orthy);
1142                         
1143                         Normalize(v_refract_new);
1144                 } else {
1145                         /* no blurriness, use the original normal */
1146                         VECCOPY(v_refract_new, v_refract);
1147                 }
1148         
1149                 traceray(shi, shr, shi->mat->ray_depth_tra, shi->co, v_refract_new, sampcol, shi->obi, shi->vlr, RAY_TRA|RAY_TRAFLIP);
1150         
1151                 col[0] += sampcol[0];
1152                 col[1] += sampcol[1];
1153                 col[2] += sampcol[2];
1154                 col[3] += sampcol[3];
1155                 
1156                 /* for variance calc */
1157                 colsq[0] += sampcol[0]*sampcol[0];
1158                 colsq[1] += sampcol[1]*sampcol[1];
1159                 colsq[2] += sampcol[2]*sampcol[2];
1160                 
1161                 samples++;
1162                 
1163                 /* adaptive sampling */
1164                 if (adapt_thresh < 1.0 && samples > max_samples/2) 
1165                 {
1166                         if (adaptive_sample_variance(samples, col, colsq, adapt_thresh))
1167                                 break;
1168                         
1169                         /* if the pixel so far is very dark, we can get away with less samples */
1170                         if ( (col[0] + col[1] + col[2])/3.0/(float)samples < 0.01 )
1171                                 max_samples--;
1172                 }
1173         }
1174         
1175         col[0] /= (float)samples;
1176         col[1] /= (float)samples;
1177         col[2] /= (float)samples;
1178         col[3] /= (float)samples;
1179         
1180         if (qsa)
1181                 release_thread_qmcsampler(&R, shi->thread, qsa);
1182 }
1183
1184 static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float fresnelfac)
1185 {
1186         QMCSampler *qsa=NULL;
1187         int samp_type;
1188         
1189         float samp3d[3], orthx[3], orthy[3];
1190         float v_nor_new[3], v_reflect[3];
1191         float sampcol[4], colsq[4];
1192                 
1193         float blur = pow(1.0 - shi->mat->gloss_mir, 3);
1194         short max_samples = shi->mat->samp_gloss_mir;
1195         float adapt_thresh = shi->mat->adapt_thresh_mir;
1196         float aniso = 1.0 - shi->mat->aniso_gloss_mir;
1197         
1198         int samples=0;
1199         
1200         col[0] = col[1] = col[2] = 0.0;
1201         colsq[0] = colsq[1] = colsq[2] = 0.0;
1202         
1203         if (blur > 0.0) {
1204                 if (adapt_thresh != 0.0) samp_type = SAMP_TYPE_HALTON;
1205                 else samp_type = SAMP_TYPE_HAMMERSLEY;
1206                         
1207                 /* all samples are generated per pixel */
1208                 qsa = get_thread_qmcsampler(&R, shi->thread, samp_type, max_samples);
1209                 QMC_initPixel(qsa, shi->thread);
1210         } else 
1211                 max_samples = 1;
1212         
1213         while (samples < max_samples) {
1214                                 
1215                 if (max_samples > 1) {
1216                         /* get a quasi-random vector from a phong-weighted disc */
1217                         QMC_samplePhong(samp3d, qsa, shi->thread, samples, blur);
1218
1219                         /* find the normal's perpendicular plane, blurring along tangents
1220                          * if tangent shading enabled */
1221                         if (shi->mat->mode & (MA_TANGENT_V)) {
1222                                 Crossf(orthx, shi->vn, shi->tang);      // bitangent
1223                                 VECCOPY(orthy, shi->tang);
1224                                 VecMulf(orthx, samp3d[0]);
1225                                 VecMulf(orthy, samp3d[1]*aniso);
1226                         } else {
1227                                 VecOrthoBasisf(shi->vn, orthx, orthy);
1228                                 VecMulf(orthx, samp3d[0]);
1229                                 VecMulf(orthy, samp3d[1]);
1230                         }
1231
1232                         /* and perturb the normal in it */
1233                         VecAddf(v_nor_new, shi->vn, orthx);
1234                         VecAddf(v_nor_new, v_nor_new, orthy);
1235                         Normalize(v_nor_new);
1236                 } else {
1237                         /* no blurriness, use the original normal */
1238                         VECCOPY(v_nor_new, shi->vn);
1239                 }
1240                 
1241                 if((shi->vlr->flag & R_SMOOTH)) 
1242                         reflection(v_reflect, v_nor_new, shi->view, shi->facenor);
1243                 else
1244                         reflection(v_reflect, v_nor_new, shi->view, NULL);
1245                 
1246                 traceray(shi, shr, shi->mat->ray_depth, shi->co, v_reflect, sampcol, shi->obi, shi->vlr, 0);
1247
1248                 
1249                 col[0] += sampcol[0];
1250                 col[1] += sampcol[1];
1251                 col[2] += sampcol[2];
1252         
1253                 /* for variance calc */
1254                 colsq[0] += sampcol[0]*sampcol[0];
1255                 colsq[1] += sampcol[1]*sampcol[1];
1256                 colsq[2] += sampcol[2]*sampcol[2];
1257                 
1258                 samples++;
1259
1260                 /* adaptive sampling */
1261                 if (adapt_thresh > 0.0 && samples > max_samples/3) 
1262                 {
1263                         if (adaptive_sample_variance(samples, col, colsq, adapt_thresh))
1264                                 break;
1265                         
1266                         /* if the pixel so far is very dark, we can get away with less samples */
1267                         if ( (col[0] + col[1] + col[2])/3.0/(float)samples < 0.01 )
1268                                 max_samples--;
1269                 
1270                         /* reduce samples when reflection is dim due to low ray mirror blend value or fresnel factor
1271                          * and when reflection is blurry */
1272                         if (fresnelfac < 0.1 * (blur+1)) {
1273                                 max_samples--;
1274                                 
1275                                 /* even more for very dim */
1276                                 if (fresnelfac < 0.05 * (blur+1)) 
1277                                         max_samples--;
1278                         }
1279                 }
1280         }
1281         
1282         col[0] /= (float)samples;
1283         col[1] /= (float)samples;
1284         col[2] /= (float)samples;
1285         
1286         if (qsa)
1287                 release_thread_qmcsampler(&R, shi->thread, qsa);
1288 }
1289
1290 /* extern call from render loop */
1291 void ray_trace(ShadeInput *shi, ShadeResult *shr)
1292 {
1293         float i, f, f1, fr, fg, fb;
1294         float mircol[4], tracol[4];
1295         float diff[3];
1296         int do_tra, do_mir;
1297         
1298         do_tra= ((shi->mat->mode & (MA_RAYTRANSP)) && shr->alpha!=1.0f);
1299         do_mir= ((shi->mat->mode & MA_RAYMIRROR) && shi->ray_mirror!=0.0f);
1300
1301         
1302         /* raytrace mirror amd refract like to separate the spec color */
1303         if(shi->combinedflag & SCE_PASS_SPEC)
1304                 VECSUB(diff, shr->combined, shr->spec) /* no ; */
1305         else
1306                 VECCOPY(diff, shr->combined);
1307         
1308         if(do_tra) {
1309                 float olddiff[3];
1310                 
1311                 trace_refract(tracol, shi, shr);
1312                 
1313                 f= shr->alpha; f1= 1.0f-f;
1314                 fr= 1.0f+ shi->mat->filter*(shi->r-1.0f);
1315                 fg= 1.0f+ shi->mat->filter*(shi->g-1.0f);
1316                 fb= 1.0f+ shi->mat->filter*(shi->b-1.0f);
1317                 
1318                 /* for refract pass */
1319                 VECCOPY(olddiff, diff);
1320                 
1321                 diff[0]= f*diff[0] + f1*fr*tracol[0];
1322                 diff[1]= f*diff[1] + f1*fg*tracol[1];
1323                 diff[2]= f*diff[2] + f1*fb*tracol[2];
1324                 
1325                 if(shi->passflag & SCE_PASS_REFRACT)
1326                         VECSUB(shr->refr, diff, olddiff);
1327                 
1328                 if(!(shi->combinedflag & SCE_PASS_REFRACT))
1329                         VECSUB(diff, diff, shr->refr);
1330                 
1331                 shr->alpha= tracol[3];
1332         }
1333         
1334         if(do_mir) {
1335         
1336                 i= shi->ray_mirror*fresnel_fac(shi->view, shi->vn, shi->mat->fresnel_mir_i, shi->mat->fresnel_mir);
1337                 if(i!=0.0f) {
1338                 
1339                         trace_reflect(mircol, shi, shr, i);
1340                         
1341                         fr= i*shi->mirr;
1342                         fg= i*shi->mirg;
1343                         fb= i*shi->mirb;
1344
1345                         if(shi->passflag & SCE_PASS_REFLECT) {
1346                                 /* mirror pass is not blocked out with spec */
1347                                 shr->refl[0]= fr*mircol[0] - fr*diff[0];
1348                                 shr->refl[1]= fg*mircol[1] - fg*diff[1];
1349                                 shr->refl[2]= fb*mircol[2] - fb*diff[2];
1350                         }
1351                         
1352                         if(shi->combinedflag & SCE_PASS_REFLECT) {
1353                                 
1354                                 f= fr*(1.0f-shr->spec[0]);      f1= 1.0f-i;
1355                                 diff[0]= f*mircol[0] + f1*diff[0];
1356                                 
1357                                 f= fg*(1.0f-shr->spec[1]);      f1= 1.0f-i;
1358                                 diff[1]= f*mircol[1] + f1*diff[1];
1359                                 
1360                                 f= fb*(1.0f-shr->spec[2]);      f1= 1.0f-i;
1361                                 diff[2]= f*mircol[2] + f1*diff[2];
1362                         }
1363                 }
1364         }
1365         /* put back together */
1366         if(shi->combinedflag & SCE_PASS_SPEC)
1367                 VECADD(shr->combined, diff, shr->spec) /* no ; */
1368         else
1369                 VECCOPY(shr->combined, diff);
1370 }
1371
1372 /* color 'shadfac' passes through 'col' with alpha and filter */
1373 /* filter is only applied on alpha defined transparent part */
1374 static void addAlphaLight(float *shadfac, float *col, float alpha, float filter)
1375 {
1376         float fr, fg, fb;
1377         
1378         fr= 1.0f+ filter*(col[0]-1.0f);
1379         fg= 1.0f+ filter*(col[1]-1.0f);
1380         fb= 1.0f+ filter*(col[2]-1.0f);
1381         
1382         shadfac[0]= alpha*col[0] + fr*(1.0f-alpha)*shadfac[0];
1383         shadfac[1]= alpha*col[1] + fg*(1.0f-alpha)*shadfac[1];
1384         shadfac[2]= alpha*col[2] + fb*(1.0f-alpha)*shadfac[2];
1385         
1386         shadfac[3]= (1.0f-alpha)*shadfac[3];
1387 }
1388
1389 static void ray_trace_shadow_tra(Isect *is, ShadeInput *origshi, int depth, int traflag)
1390 {
1391         /* ray to lamp, find first face that intersects, check alpha properties,
1392            if it has col[3]>0.0f  continue. so exit when alpha is full */
1393         ShadeInput shi;
1394         ShadeResult shr;
1395         
1396         if(RE_rayobject_raycast(R.raytree, is)) {
1397                 float d= 1.0f;
1398                 /* we got a face */
1399                 
1400                 /* Warning, This is not that nice, and possibly a bit slow for every ray,
1401                 however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
1402                 memset(&shi, 0, sizeof(ShadeInput)); 
1403                 /* end warning! - Campbell */
1404                 
1405                 shi.depth= 1;                                   /* only used to indicate tracing */
1406                 shi.mask= origshi->mask;
1407                 shi.thread= origshi->thread;
1408                 shi.passflag= SCE_PASS_COMBINED;
1409                 shi.combinedflag= 0xFFFFFF;              /* ray trace does all options */
1410         
1411                 shi.xs= origshi->xs;
1412                 shi.ys= origshi->ys;
1413                 shi.lay= origshi->lay;
1414                 shi.nodes= origshi->nodes;
1415                 
1416                 shade_ray(is, &shi, &shr);
1417                 if (traflag & RAY_TRA)
1418                         d= shade_by_transmission(is, &shi, &shr);
1419                 
1420                 /* mix colors based on shadfac (rgb + amount of light factor) */
1421                 addAlphaLight(is->col, shr.diff, shr.alpha, d*shi.mat->filter);
1422                 
1423                 if(depth>0 && is->col[3]>0.0f) {
1424                         
1425                         /* adapt isect struct */
1426                         VECCOPY(is->start, shi.co);
1427
1428                         is->orig.ob   = shi.obi;
1429                         is->orig.face = shi.vlr;
1430
1431                         ray_trace_shadow_tra(is, origshi, depth-1, traflag | RAY_TRA);
1432                 }
1433         }
1434 }
1435
1436 /* not used, test function for ambient occlusion (yaf: pathlight) */
1437 /* main problem; has to be called within shading loop, giving unwanted recursion */
1438 int ray_trace_shadow_rad(ShadeInput *ship, ShadeResult *shr)
1439 {
1440         static int counter=0, only_one= 0;
1441         extern float hashvectf[];
1442         Isect isec;
1443         ShadeInput shi;
1444         ShadeResult shr_t;
1445         float vec[3], accum[3], div= 0.0f;
1446         int a;
1447         
1448         assert(0);
1449         
1450         if(only_one) {
1451                 return 0;
1452         }
1453         only_one= 1;
1454         
1455         accum[0]= accum[1]= accum[2]= 0.0f;
1456         isec.mode= RE_RAY_MIRROR;
1457         isec.orig.ob   = ship->obi;
1458         isec.orig.face = ship->vlr;
1459         
1460         for(a=0; a<8*8; a++) {
1461                 
1462                 counter+=3;
1463                 counter %= 768;
1464                 VECCOPY(vec, hashvectf+counter);
1465                 if(ship->vn[0]*vec[0]+ship->vn[1]*vec[1]+ship->vn[2]*vec[2]>0.0f) {
1466                         vec[0]-= vec[0];
1467                         vec[1]-= vec[1];
1468                         vec[2]-= vec[2];
1469                 }
1470
1471                 VECCOPY(isec.start, ship->co);
1472                 VECCOPY(isec.vec, vec );
1473                 isec.labda = RE_RAYTRACE_MAXDIST;
1474
1475                 if(RE_rayobject_raycast(R.raytree, &isec)) {
1476                         float fac;
1477                         
1478                         /* Warning, This is not that nice, and possibly a bit slow for every ray,
1479                         however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
1480                         memset(&shi, 0, sizeof(ShadeInput)); 
1481                         /* end warning! - Campbell */
1482                         
1483                         shade_ray(&isec, &shi, &shr_t);
1484                         fac= isec.labda*isec.labda;
1485                         fac= 1.0f;
1486                         accum[0]+= fac*(shr_t.diff[0]+shr_t.spec[0]);
1487                         accum[1]+= fac*(shr_t.diff[1]+shr_t.spec[1]);
1488                         accum[2]+= fac*(shr_t.diff[2]+shr_t.spec[2]);
1489                         div+= fac;
1490                 }
1491                 else div+= 1.0f;
1492         }
1493         
1494         if(div!=0.0f) {
1495                 shr->diff[0]+= accum[0]/div;
1496                 shr->diff[1]+= accum[1]/div;
1497                 shr->diff[2]+= accum[2]/div;
1498         }
1499         shr->alpha= 1.0f;
1500         
1501         only_one= 0;
1502         return 1;
1503 }
1504
1505 /* aolight: function to create random unit sphere vectors for total random sampling */
1506 static void RandomSpherical(float *v)
1507 {
1508         float r;
1509         v[2] = 2.f*BLI_frand()-1.f;
1510         if ((r = 1.f - v[2]*v[2])>0.f) {
1511                 float a = 6.283185307f*BLI_frand();
1512                 r = sqrt(r);
1513                 v[0] = r * cos(a);
1514                 v[1] = r * sin(a);
1515         }
1516         else v[2] = 1.f;
1517 }
1518
1519 /* calc distributed spherical energy */
1520 static void DS_energy(float *sphere, int tot, float *vec)
1521 {
1522         float *fp, fac, force[3], res[3];
1523         int a;
1524         
1525         res[0]= res[1]= res[2]= 0.0f;
1526         
1527         for(a=0, fp=sphere; a<tot; a++, fp+=3) {
1528                 VecSubf(force, vec, fp);
1529                 fac= force[0]*force[0] + force[1]*force[1] + force[2]*force[2];
1530                 if(fac!=0.0f) {
1531                         fac= 1.0f/fac;
1532                         res[0]+= fac*force[0];
1533                         res[1]+= fac*force[1];
1534                         res[2]+= fac*force[2];
1535                 }
1536         }
1537
1538         VecMulf(res, 0.5);
1539         VecAddf(vec, vec, res);
1540         Normalize(vec);
1541         
1542 }
1543
1544 /* called from convertBlenderScene.c */
1545 /* creates an equally distributed spherical sample pattern */
1546 /* and allocates threadsafe memory */
1547 void init_ao_sphere(World *wrld)
1548 {
1549         float *fp;
1550         int a, tot, iter= 16;
1551
1552         /* we make twice the amount of samples, because only a hemisphere is used */
1553         tot= 2*wrld->aosamp*wrld->aosamp;
1554         
1555         wrld->aosphere= MEM_mallocN(3*tot*sizeof(float), "AO sphere");
1556         
1557         /* fixed random */
1558         BLI_srandom(tot);
1559         
1560         /* init */
1561         fp= wrld->aosphere;
1562         for(a=0; a<tot; a++, fp+= 3) {
1563                 RandomSpherical(fp);
1564         }
1565         
1566         while(iter--) {
1567                 for(a=0, fp= wrld->aosphere; a<tot; a++, fp+= 3) {
1568                         DS_energy(wrld->aosphere, tot, fp);
1569                 }
1570         }
1571         
1572         /* tables */
1573         wrld->aotables= MEM_mallocN(BLENDER_MAX_THREADS*3*tot*sizeof(float), "AO tables");
1574 }
1575
1576 /* give per thread a table, we have to compare xs ys because of way OSA works... */
1577 static float *threadsafe_table_sphere(int test, int thread, int xs, int ys, int tot)
1578 {
1579         static int xso[BLENDER_MAX_THREADS], yso[BLENDER_MAX_THREADS];
1580         static int firsttime= 1;
1581         
1582         if(firsttime) {
1583                 memset(xso, 255, sizeof(xso));
1584                 memset(yso, 255, sizeof(yso));
1585                 firsttime= 0;
1586         }
1587         
1588         if(xs==xso[thread] && ys==yso[thread]) return R.wrld.aotables+ thread*tot*3;
1589         if(test) return NULL;
1590         xso[thread]= xs; yso[thread]= ys;
1591         return R.wrld.aotables+ thread*tot*3;
1592 }
1593
1594 static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
1595 {
1596         int tot;
1597         float *vec;
1598         
1599         tot= 2*resol*resol;
1600
1601         if (type & WO_AORNDSMP) {
1602                 float *sphere;
1603                 int a;
1604                 
1605                 // always returns table
1606                 sphere= threadsafe_table_sphere(0, thread, xs, ys, tot);
1607
1608                 /* total random sampling. NOT THREADSAFE! (should be removed, is not useful) */
1609                 vec= sphere;
1610                 for (a=0; a<tot; a++, vec+=3) {
1611                         RandomSpherical(vec);
1612                 }
1613                 
1614                 return sphere;
1615         } 
1616         else {
1617                 float *sphere;
1618                 float cosfi, sinfi, cost, sint;
1619                 float ang, *vec1;
1620                 int a;
1621                 
1622                 // returns table if xs and ys were equal to last call
1623                 sphere= threadsafe_table_sphere(1, thread, xs, ys, tot);
1624                 if(sphere==NULL) {
1625                         sphere= threadsafe_table_sphere(0, thread, xs, ys, tot);
1626                         
1627                         // random rotation
1628                         ang= BLI_thread_frand(thread);
1629                         sinfi= sin(ang); cosfi= cos(ang);
1630                         ang= BLI_thread_frand(thread);
1631                         sint= sin(ang); cost= cos(ang);
1632                         
1633                         vec= R.wrld.aosphere;
1634                         vec1= sphere;
1635                         for (a=0; a<tot; a++, vec+=3, vec1+=3) {
1636                                 vec1[0]= cost*cosfi*vec[0] - sinfi*vec[1] + sint*cosfi*vec[2];
1637                                 vec1[1]= cost*sinfi*vec[0] + cosfi*vec[1] + sint*sinfi*vec[2];
1638                                 vec1[2]= -sint*vec[0] + cost*vec[2];                    
1639                         }
1640                 }
1641                 return sphere;
1642         }
1643 }
1644
1645 static void ray_ao_qmc(ShadeInput *shi, float *shadfac)
1646 {
1647         Isect isec;
1648         QMCSampler *qsa=NULL;
1649         float samp3d[3];
1650         float up[3], side[3], dir[3], nrm[3];
1651         
1652         float maxdist = R.wrld.aodist;
1653         float fac=0.0f, prev=0.0f;
1654         float adapt_thresh = R.wrld.ao_adapt_thresh;
1655         float adapt_speed_fac = R.wrld.ao_adapt_speed_fac;
1656         
1657         int samples=0;
1658         int max_samples = R.wrld.aosamp*R.wrld.aosamp;
1659         
1660         float dxyview[3], skyadded=0, div;
1661         int aocolor;
1662         
1663         isec.orig.ob   = shi->obi;
1664         isec.orig.face = shi->vlr;
1665
1666         isec.hit.ob   = 0;
1667         isec.hit.face = 0;
1668
1669         isec.last_hit = NULL;
1670         
1671         isec.mode= (R.wrld.aomode & WO_AODIST)?RE_RAY_SHADOW_TRA:RE_RAY_SHADOW;
1672         isec.lay= -1;
1673         
1674         shadfac[0]= shadfac[1]= shadfac[2]= 0.0f;
1675         
1676         /* prevent sky colors to be added for only shadow (shadow becomes alpha) */
1677         aocolor= R.wrld.aocolor;
1678         if(shi->mat->mode & MA_ONLYSHADOW)
1679                 aocolor= WO_AOPLAIN;
1680         
1681         if(aocolor == WO_AOSKYTEX) {
1682                 dxyview[0]= 1.0f/(float)R.wrld.aosamp;
1683                 dxyview[1]= 1.0f/(float)R.wrld.aosamp;
1684                 dxyview[2]= 0.0f;
1685         }
1686         
1687         if(shi->vlr->flag & R_SMOOTH) {
1688                 VECCOPY(nrm, shi->vn);
1689         }
1690         else {
1691                 VECCOPY(nrm, shi->facenor);
1692         }
1693         
1694         VecOrthoBasisf(nrm, up, side);
1695         
1696         /* sampling init */
1697         if (R.wrld.ao_samp_method==WO_AOSAMP_HALTON) {
1698                 float speedfac;
1699                 
1700                 speedfac = get_avg_speed(shi) * adapt_speed_fac;
1701                 CLAMP(speedfac, 1.0, 1000.0);
1702                 max_samples /= speedfac;
1703                 if (max_samples < 5) max_samples = 5;
1704                 
1705                 qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HALTON, max_samples);
1706         } else if (R.wrld.ao_samp_method==WO_AOSAMP_HAMMERSLEY)
1707                 qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HAMMERSLEY, max_samples);
1708
1709         QMC_initPixel(qsa, shi->thread);
1710         
1711         while (samples < max_samples) {
1712
1713                 /* sampling, returns quasi-random vector in unit hemisphere */
1714                 QMC_sampleHemi(samp3d, qsa, shi->thread, samples);
1715
1716                 dir[0] = (samp3d[0]*up[0] + samp3d[1]*side[0] + samp3d[2]*nrm[0]);
1717                 dir[1] = (samp3d[0]*up[1] + samp3d[1]*side[1] + samp3d[2]*nrm[1]);
1718                 dir[2] = (samp3d[0]*up[2] + samp3d[1]*side[2] + samp3d[2]*nrm[2]);
1719                 
1720                 Normalize(dir);
1721                         
1722                 VECCOPY(isec.start, shi->co);
1723                 isec.vec[0] = -dir[0];
1724                 isec.vec[1] = -dir[1];
1725                 isec.vec[2] = -dir[2];
1726                 isec.labda = maxdist;
1727                 
1728                 prev = fac;
1729                 
1730                 if(RE_rayobject_raycast(R.raytree, &isec)) {
1731                         if (R.wrld.aomode & WO_AODIST) fac+= exp(-isec.labda*R.wrld.aodistfac); 
1732                         else fac+= 1.0f;
1733                 }
1734                 else if(aocolor!=WO_AOPLAIN) {
1735                         float skycol[4];
1736                         float skyfac, view[3];
1737                         
1738                         view[0]= -dir[0];
1739                         view[1]= -dir[1];
1740                         view[2]= -dir[2];
1741                         Normalize(view);
1742                         
1743                         if(aocolor==WO_AOSKYCOL) {
1744                                 skyfac= 0.5*(1.0f+view[0]*R.grvec[0]+ view[1]*R.grvec[1]+ view[2]*R.grvec[2]);
1745                                 shadfac[0]+= (1.0f-skyfac)*R.wrld.horr + skyfac*R.wrld.zenr;
1746                                 shadfac[1]+= (1.0f-skyfac)*R.wrld.horg + skyfac*R.wrld.zeng;
1747                                 shadfac[2]+= (1.0f-skyfac)*R.wrld.horb + skyfac*R.wrld.zenb;
1748                         }
1749                         else {  /* WO_AOSKYTEX */
1750                                 shadeSkyView(skycol, isec.start, view, dxyview, shi->thread);
1751                                 shadeSunView(skycol, shi->view);
1752                                 shadfac[0]+= skycol[0];
1753                                 shadfac[1]+= skycol[1];
1754                                 shadfac[2]+= skycol[2];
1755                         }
1756                         skyadded++;
1757                 }
1758                 
1759                 samples++;
1760                 
1761                 if (qsa->type == SAMP_TYPE_HALTON) {
1762                         /* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */          
1763                         if (adapt_thresh > 0.0 && (samples > max_samples/2) ) {
1764                                 
1765                                 if (adaptive_sample_contrast_val(samples, prev, fac, adapt_thresh)) {
1766                                         break;
1767                                 }
1768                         }
1769                 }
1770         }
1771         
1772         if(aocolor!=WO_AOPLAIN && skyadded) {
1773                 div= (1.0f - fac/(float)samples)/((float)skyadded);
1774                 
1775                 shadfac[0]*= div;       // average color times distances/hits formula
1776                 shadfac[1]*= div;       // average color times distances/hits formula
1777                 shadfac[2]*= div;       // average color times distances/hits formula
1778         } else {
1779                 shadfac[0]= shadfac[1]= shadfac[2]= 1.0f - fac/(float)samples;
1780         }
1781         
1782         if (qsa)
1783                 release_thread_qmcsampler(&R, shi->thread, qsa);
1784 }
1785
1786 /* extern call from shade_lamp_loop, ambient occlusion calculus */
1787 static void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
1788 {
1789         Isect isec;
1790         float *vec, *nrm, div, bias, sh=0.0f;
1791         float maxdist = R.wrld.aodist;
1792         float dxyview[3];
1793         int j= -1, tot, actual=0, skyadded=0, aocolor, resol= R.wrld.aosamp;
1794         
1795         isec.orig.ob   = shi->obi;
1796         isec.orig.face = shi->vlr;
1797
1798         isec.hit.ob   = 0;
1799         isec.hit.face = 0;
1800         
1801         isec.last_hit = NULL;
1802         
1803         isec.mode= (R.wrld.aomode & WO_AODIST)?RE_RAY_SHADOW_TRA:RE_RAY_SHADOW;
1804         isec.lay= -1;
1805
1806
1807         shadfac[0]= shadfac[1]= shadfac[2]= 0.0f;
1808
1809         /* bias prevents smoothed faces to appear flat */
1810         if(shi->vlr->flag & R_SMOOTH) {
1811                 bias= R.wrld.aobias;
1812                 nrm= shi->vn;
1813         }
1814         else {
1815                 bias= 0.0f;
1816                 nrm= shi->facenor;
1817         }
1818
1819         /* prevent sky colors to be added for only shadow (shadow becomes alpha) */
1820         aocolor= R.wrld.aocolor;
1821         if(shi->mat->mode & MA_ONLYSHADOW)
1822                 aocolor= WO_AOPLAIN;
1823         
1824         if(resol>32) resol= 32;
1825         
1826         vec= sphere_sampler(R.wrld.aomode, resol, shi->thread, shi->xs, shi->ys);
1827         
1828         // warning: since we use full sphere now, and dotproduct is below, we do twice as much
1829         tot= 2*resol*resol;
1830
1831         if(aocolor == WO_AOSKYTEX) {
1832                 dxyview[0]= 1.0f/(float)resol;
1833                 dxyview[1]= 1.0f/(float)resol;
1834                 dxyview[2]= 0.0f;
1835         }
1836         
1837         while(tot--) {
1838                 
1839                 if ((vec[0]*nrm[0] + vec[1]*nrm[1] + vec[2]*nrm[2]) > bias) {
1840                         /* only ao samples for mask */
1841                         if(R.r.mode & R_OSA) {
1842                                 j++;
1843                                 if(j==R.osa) j= 0;
1844                                 if(!(shi->mask & (1<<j))) {
1845                                         vec+=3;
1846                                         continue;
1847                                 }
1848                         }
1849                         
1850                         actual++;
1851                         
1852                         /* always set start/vec/labda */
1853                         VECCOPY(isec.start, shi->co);
1854                         isec.vec[0] = -vec[0];
1855                         isec.vec[1] = -vec[1];
1856                         isec.vec[2] = -vec[2];
1857                         isec.labda = maxdist;
1858                         
1859                         /* do the trace */
1860                         if(RE_rayobject_raycast(R.raytree, &isec)) {
1861                                 if (R.wrld.aomode & WO_AODIST) sh+= exp(-isec.labda*R.wrld.aodistfac); 
1862                                 else sh+= 1.0f;
1863                         }
1864                         else if(aocolor!=WO_AOPLAIN) {
1865                                 float skycol[4];
1866                                 float fac, view[3];
1867                                 
1868                                 view[0]= -vec[0];
1869                                 view[1]= -vec[1];
1870                                 view[2]= -vec[2];
1871                                 Normalize(view);
1872                                 
1873                                 if(aocolor==WO_AOSKYCOL) {
1874                                         fac= 0.5*(1.0f+view[0]*R.grvec[0]+ view[1]*R.grvec[1]+ view[2]*R.grvec[2]);
1875                                         shadfac[0]+= (1.0f-fac)*R.wrld.horr + fac*R.wrld.zenr;
1876                                         shadfac[1]+= (1.0f-fac)*R.wrld.horg + fac*R.wrld.zeng;
1877                                         shadfac[2]+= (1.0f-fac)*R.wrld.horb + fac*R.wrld.zenb;
1878                                 }
1879                                 else {  /* WO_AOSKYTEX */
1880                                         shadeSkyView(skycol, isec.start, view, dxyview, shi->thread);
1881                                         shadeSunView(skycol, shi->view);
1882                                         shadfac[0]+= skycol[0];
1883                                         shadfac[1]+= skycol[1];
1884                                         shadfac[2]+= skycol[2];
1885                                 }
1886                                 skyadded++;
1887                         }
1888                 }
1889                 // samples
1890                 vec+= 3;
1891         }
1892         
1893         if(actual==0) sh= 1.0f;
1894         else sh = 1.0f - sh/((float)actual);
1895         
1896         if(aocolor!=WO_AOPLAIN && skyadded) {
1897                 div= sh/((float)skyadded);
1898                 
1899                 shadfac[0]*= div;       // average color times distances/hits formula
1900                 shadfac[1]*= div;       // average color times distances/hits formula
1901                 shadfac[2]*= div;       // average color times distances/hits formula
1902         }
1903         else {
1904                 shadfac[0]= shadfac[1]= shadfac[2]= sh;
1905         }
1906 }
1907
1908 void ray_ao(ShadeInput *shi, float *shadfac)
1909 {
1910         /* Unfortunately, the unusual way that the sphere sampler calculates roughly twice as many
1911          * samples as are actually traced, and skips them based on bias and OSA settings makes it very difficult
1912          * to reuse code between these two functions. This is the easiest way I can think of to do it
1913          * --broken */
1914         if (ELEM(R.wrld.ao_samp_method, WO_AOSAMP_HAMMERSLEY, WO_AOSAMP_HALTON))
1915                 ray_ao_qmc(shi, shadfac);
1916         else if (R.wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
1917                 ray_ao_spheresamp(shi, shadfac);
1918 }
1919
1920 static void ray_shadow_jittered_coords(ShadeInput *shi, int max, float jitco[RE_MAX_OSA][3], int *totjitco)
1921 {
1922         /* magic numbers for reordering sample positions to give better
1923          * results with adaptive sample, when it usually only takes 4 samples */
1924         int order8[8] = {0, 1, 5, 6, 2, 3, 4, 7};
1925         int order11[11] = {1, 3, 8, 10, 0, 2, 4, 5, 6, 7, 9};
1926         int order16[16] = {1, 3, 9, 12, 0, 6, 7, 8, 13, 2, 4, 5, 10, 11, 14, 15};
1927         int count = count_mask(shi->mask);
1928
1929         /* for better antialising shadow samples are distributed over the subpixel
1930          * sample coordinates, this only works for raytracing depth 0 though */
1931         if(!shi->strand && shi->depth == 0 && count > 1 && count <= max) {
1932                 float xs, ys, zs, view[3];
1933                 int samp, ordsamp, tot= 0;
1934
1935                 for(samp=0; samp<R.osa; samp++) {
1936                         if(R.osa == 8) ordsamp = order8[samp];
1937                         else if(R.osa == 11) ordsamp = order11[samp];
1938                         else if(R.osa == 16) ordsamp = order16[samp];
1939                         else ordsamp = samp;
1940
1941                         if(shi->mask & (1<<ordsamp)) {
1942                                 /* zbuffer has this inverse corrected, ensures xs,ys are inside pixel */
1943                                 xs= (float)shi->scanco[0] + R.jit[ordsamp][0] + 0.5f;
1944                                 ys= (float)shi->scanco[1] + R.jit[ordsamp][1] + 0.5f;
1945                                 zs= shi->scanco[2];
1946
1947                                 shade_input_calc_viewco(shi, xs, ys, zs, view, NULL, jitco[tot], NULL, NULL);
1948                                 tot++;
1949                         }
1950                 }
1951
1952                 *totjitco= tot;
1953         }
1954         else {
1955                 VECCOPY(jitco[0], shi->co);
1956                 *totjitco= 1;
1957         }
1958 }
1959
1960 static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
1961 {
1962         QMCSampler *qsa=NULL;
1963         int samples=0;
1964         float samp3d[3];
1965
1966         float fac=0.0f, vec[3], end[3];
1967         float colsq[4];
1968         float adapt_thresh = lar->adapt_thresh;
1969         int min_adapt_samples=4, max_samples = lar->ray_totsamp;
1970         float *co;
1971         int do_soft=1, full_osa=0;
1972
1973         float jitco[RE_MAX_OSA][3];
1974         int totjitco;
1975
1976         colsq[0] = colsq[1] = colsq[2] = 0.0;
1977         if(isec->mode==RE_RAY_SHADOW_TRA) {
1978                 shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 0.0f;
1979         } else
1980                 shadfac[3]= 1.0f;
1981         
1982         if (lar->ray_totsamp < 2) do_soft = 0;
1983         if ((R.r.mode & R_OSA) && (R.osa > 0) && (shi->vlr->flag & R_FULL_OSA)) full_osa = 1;
1984         
1985         if (full_osa) {
1986                 if (do_soft) max_samples  = max_samples/R.osa + 1;
1987                 else max_samples = 1;
1988         } else {
1989                 if (do_soft) max_samples = lar->ray_totsamp;
1990                 else max_samples = (R.osa > 4)?R.osa:5;
1991         }
1992         
1993         ray_shadow_jittered_coords(shi, max_samples, jitco, &totjitco);
1994
1995         /* sampling init */
1996         if (lar->ray_samp_method==LA_SAMP_HALTON)
1997                 qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HALTON, max_samples);
1998         else if (lar->ray_samp_method==LA_SAMP_HAMMERSLEY)
1999                 qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HAMMERSLEY, max_samples);
2000         
2001         QMC_initPixel(qsa, shi->thread);
2002         
2003         VECCOPY(vec, lampco);
2004         
2005         isec->skip = RE_SKIP_VLR_NEIGHBOUR;
2006         while (samples < max_samples) {
2007
2008                 isec->orig.ob   = shi->obi;
2009                 isec->orig.face = shi->vlr;
2010
2011                 /* manually jitter the start shading co-ord per sample
2012                  * based on the pre-generated OSA texture sampling offsets, 
2013                  * for anti-aliasing sharp shadow edges. */
2014                 co = jitco[samples % totjitco];
2015
2016                 if (do_soft) {
2017                         /* sphere shadow source */
2018                         if (lar->type == LA_LOCAL) {
2019                                 float ru[3], rv[3], v[3], s[3];
2020                                 
2021                                 /* calc tangent plane vectors */
2022                                 v[0] = co[0] - lampco[0];
2023                                 v[1] = co[1] - lampco[1];
2024                                 v[2] = co[2] - lampco[2];
2025                                 Normalize(v);
2026                                 VecOrthoBasisf(v, ru, rv);
2027                                 
2028                                 /* sampling, returns quasi-random vector in area_size disc */
2029                                 QMC_sampleDisc(samp3d, qsa, shi->thread, samples,lar->area_size);
2030
2031                                 /* distribute disc samples across the tangent plane */
2032                                 s[0] = samp3d[0]*ru[0] + samp3d[1]*rv[0];
2033                                 s[1] = samp3d[0]*ru[1] + samp3d[1]*rv[1];
2034                                 s[2] = samp3d[0]*ru[2] + samp3d[1]*rv[2];
2035                                 
2036                                 VECCOPY(samp3d, s);
2037                         }
2038                         else {
2039                                 /* sampling, returns quasi-random vector in [sizex,sizey]^2 plane */
2040                                 QMC_sampleRect(samp3d, qsa, shi->thread, samples, lar->area_size, lar->area_sizey);
2041                                                                 
2042                                 /* align samples to lamp vector */
2043                                 Mat3MulVecfl(lar->mat, samp3d);
2044                         }
2045                         end[0] = vec[0]+samp3d[0];
2046                         end[1] = vec[1]+samp3d[1];
2047                         end[2] = vec[2]+samp3d[2];
2048                 } else {
2049                         VECCOPY(end, vec);
2050                 }
2051
2052                 if(shi->strand) {
2053                         /* bias away somewhat to avoid self intersection */
2054                         float jitbias= 0.5f*(VecLength(shi->dxco) + VecLength(shi->dyco));
2055                         float v[3];
2056
2057                         VECSUB(v, co, end);
2058                         Normalize(v);
2059
2060                         co[0] -= jitbias*v[0];
2061                         co[1] -= jitbias*v[1];
2062                         co[2] -= jitbias*v[2];
2063                 }
2064
2065                 VECCOPY(isec->start, co);
2066                 isec->vec[0] = end[0]-isec->start[0];
2067                 isec->vec[1] = end[1]-isec->start[1];
2068                 isec->vec[2] = end[2]-isec->start[2];
2069                 isec->labda = 1.0f; // * Normalize(isec->vec);
2070                 
2071                 /* trace the ray */
2072                 if(isec->mode==RE_RAY_SHADOW_TRA) {
2073                         isec->col[0]= isec->col[1]= isec->col[2]=  1.0f;
2074                         isec->col[3]= 1.0f;
2075                         
2076                         ray_trace_shadow_tra(isec, shi, DEPTH_SHADOW_TRA, 0);
2077                         shadfac[0] += isec->col[0];
2078                         shadfac[1] += isec->col[1];
2079                         shadfac[2] += isec->col[2];
2080                         shadfac[3] += isec->col[3];
2081                         
2082                         /* for variance calc */
2083                         colsq[0] += isec->col[0]*isec->col[0];
2084                         colsq[1] += isec->col[1]*isec->col[1];
2085                         colsq[2] += isec->col[2]*isec->col[2];
2086                 }
2087                 else {
2088                         if( RE_rayobject_raycast(R.raytree, isec) ) fac+= 1.0f;
2089                 }
2090                 
2091                 samples++;
2092                 
2093                 if ((lar->ray_samp_method == LA_SAMP_HALTON)) {
2094                 
2095                         /* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */
2096                         if ((max_samples > min_adapt_samples) && (adapt_thresh > 0.0) && (samples > max_samples / 3)) {
2097                                 if (isec->mode==RE_RAY_SHADOW_TRA) {
2098                                         if ((shadfac[3] / samples > (1.0-adapt_thresh)) || (shadfac[3] / samples < adapt_thresh))
2099                                                 break;
2100                                         else if (adaptive_sample_variance(samples, shadfac, colsq, adapt_thresh))
2101                                                 break;
2102                                 } else {
2103                                         if ((fac / samples > (1.0-adapt_thresh)) || (fac / samples < adapt_thresh))
2104                                                 break;
2105                                 }
2106                         }
2107                 }
2108         }
2109         
2110         if(isec->mode==RE_RAY_SHADOW_TRA) {
2111                 shadfac[0] /= samples;
2112                 shadfac[1] /= samples;
2113                 shadfac[2] /= samples;
2114                 shadfac[3] /= samples;
2115         } else
2116                 shadfac[3]= 1.0f-fac/samples;
2117
2118         if (qsa)
2119                 release_thread_qmcsampler(&R, shi->thread, qsa);
2120 }
2121
2122 static void ray_shadow_jitter(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
2123 {
2124         /* area soft shadow */
2125         float *jitlamp;
2126         float fac=0.0f, div=0.0f, vec[3];
2127         int a, j= -1, mask;
2128         
2129         if(isec->mode==RE_RAY_SHADOW_TRA) {
2130                 shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 0.0f;
2131         }
2132         else shadfac[3]= 1.0f;
2133         
2134         fac= 0.0f;
2135         jitlamp= give_jitter_plane(lar, shi->thread, shi->xs, shi->ys);
2136
2137         a= lar->ray_totsamp;
2138         
2139         /* this correction to make sure we always take at least 1 sample */
2140         mask= shi->mask;
2141         if(a==4) mask |= (mask>>4)|(mask>>8);
2142         else if(a==9) mask |= (mask>>9);
2143         
2144         while(a--) {
2145                 
2146                 if(R.r.mode & R_OSA) {
2147                         j++;
2148                         if(j>=R.osa) j= 0;
2149                         if(!(mask & (1<<j))) {
2150                                 jitlamp+= 2;
2151                                 continue;
2152                         }
2153                 }
2154                 
2155                 isec->orig.ob   = shi->obi;
2156                 isec->orig.face = shi->vlr;
2157                 
2158                 vec[0]= jitlamp[0];
2159                 vec[1]= jitlamp[1];
2160                 vec[2]= 0.0f;
2161                 Mat3MulVecfl(lar->mat, vec);
2162                 
2163                 /* set start and vec */
2164                 VECCOPY(isec->start, shi->co);
2165                 VECCOPY(isec->vec, vec);
2166                 isec->labda = 1.0f;
2167                 isec->skip = RE_SKIP_VLR_NEIGHBOUR;
2168                 
2169                 if(isec->mode==RE_RAY_SHADOW_TRA) {
2170                         /* isec.col is like shadfac, so defines amount of light (0.0 is full shadow) */
2171                         isec->col[0]= isec->col[1]= isec->col[2]=  1.0f;
2172                         isec->col[3]= 1.0f;
2173                         
2174                         ray_trace_shadow_tra(isec, shi, DEPTH_SHADOW_TRA, 0);
2175                         shadfac[0] += isec->col[0];
2176                         shadfac[1] += isec->col[1];
2177                         shadfac[2] += isec->col[2];
2178                         shadfac[3] += isec->col[3];
2179                 }
2180                 else if( RE_rayobject_raycast(R.raytree, isec) ) fac+= 1.0f;
2181                 
2182                 div+= 1.0f;
2183                 jitlamp+= 2;
2184         }
2185         
2186         if(isec->mode==RE_RAY_SHADOW_TRA) {
2187                 shadfac[0] /= div;
2188                 shadfac[1] /= div;
2189                 shadfac[2] /= div;
2190                 shadfac[3] /= div;
2191         }
2192         else {
2193                 // sqrt makes nice umbra effect
2194                 if(lar->ray_samp_type & LA_SAMP_UMBRA)
2195                         shadfac[3]= sqrt(1.0f-fac/div);
2196                 else
2197                         shadfac[3]= 1.0f-fac/div;
2198         }
2199 }
2200 /* extern call from shade_lamp_loop */
2201 void ray_shadow(ShadeInput *shi, LampRen *lar, float *shadfac)
2202 {
2203         Isect isec;
2204         float lampco[3];
2205
2206         /* setup isec */
2207         if(shi->mat->mode & MA_SHADOW_TRA) isec.mode= RE_RAY_SHADOW_TRA;
2208         else isec.mode= RE_RAY_SHADOW;
2209         
2210         if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW))
2211                 isec.lay= lar->lay;
2212         else
2213                 isec.lay= -1;
2214
2215         /* only when not mir tracing, first hit optimm */
2216         if(shi->depth==0) {
2217                 isec.last_hit = lar->last_hit[shi->thread];
2218         }
2219         else {
2220                 isec.last_hit = NULL;
2221         }
2222         
2223         if(lar->type==LA_SUN || lar->type==LA_HEMI) {
2224                 lampco[0]= shi->co[0] - RE_RAYTRACE_MAXDIST*lar->vec[0];
2225                 lampco[1]= shi->co[1] - RE_RAYTRACE_MAXDIST*lar->vec[1];
2226                 lampco[2]= shi->co[2] - RE_RAYTRACE_MAXDIST*lar->vec[2];
2227         }
2228         else {
2229                 VECCOPY(lampco, lar->co);
2230         }
2231         
2232         if (ELEM(lar->ray_samp_method, LA_SAMP_HALTON, LA_SAMP_HAMMERSLEY)) {
2233                 
2234                 ray_shadow_qmc(shi, lar, lampco, shadfac, &isec);
2235                 
2236         } else {
2237                 if(lar->ray_totsamp<2) {
2238                         
2239                         isec.orig.ob   = shi->obi;
2240                         isec.orig.face = shi->vlr;
2241                         
2242                         shadfac[3]= 1.0f; // 1.0=full light
2243                         
2244                         /* set up isec vec */
2245                         VECCOPY(isec.start, shi->co);
2246                         VECSUB(isec.vec, lampco, isec.start);
2247                         isec.labda = 1.0f;
2248
2249                         if(isec.mode==RE_RAY_SHADOW_TRA) {
2250                                 /* isec.col is like shadfac, so defines amount of light (0.0 is full shadow) */
2251                                 isec.col[0]= isec.col[1]= isec.col[2]=  1.0f;
2252                                 isec.col[3]= 1.0f;
2253
2254                                 ray_trace_shadow_tra(&isec, shi, DEPTH_SHADOW_TRA, 0);
2255                                 QUATCOPY(shadfac, isec.col);
2256                         }
2257                         else if(RE_rayobject_raycast(R.raytree, &isec))
2258                                 shadfac[3]= 0.0f;
2259                 }
2260                 else {
2261                         ray_shadow_jitter(shi, lar, lampco, shadfac, &isec);
2262                 }
2263         }
2264                 
2265         /* for first hit optim, set last interesected shadow face */
2266         if(shi->depth==0) {
2267                 lar->last_hit[shi->thread] = isec.last_hit;
2268         }
2269
2270 }
2271
2272 #if 0
2273 /* only when face points away from lamp, in direction of lamp, trace ray and find first exit point */
2274 static void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co)
2275 {
2276         Isect isec;
2277         float lampco[3];
2278         
2279         assert(0);
2280         
2281         /* setup isec */
2282         isec.mode= RE_RAY_SHADOW_TRA;
2283         
2284         if(lar->mode & LA_LAYER) isec.lay= lar->lay; else isec.lay= -1;
2285         
2286         if(lar->type==LA_SUN || lar->type==LA_HEMI) {
2287                 lampco[0]= shi->co[0] - RE_RAYTRACE_MAXDIST*lar->vec[0];
2288                 lampco[1]= shi->co[1] - RE_RAYTRACE_MAXDIST*lar->vec[1];
2289                 lampco[2]= shi->co[2] - RE_RAYTRACE_MAXDIST*lar->vec[2];
2290         }
2291         else {
2292                 VECCOPY(lampco, lar->co);
2293         }
2294         
2295         isec.orig.ob   = shi->obi;
2296         isec.orig.face = shi->vlr;
2297         
2298         /* set up isec vec */
2299         VECCOPY(isec.start, shi->co);
2300         VECCOPY(isec.end, lampco);
2301         
2302         if(RE_rayobject_raycast(R.raytree, &isec)) {
2303                 /* we got a face */
2304                 
2305                 /* render co */
2306                 co[0]= isec.start[0]+isec.labda*(isec.vec[0]);
2307                 co[1]= isec.start[1]+isec.labda*(isec.vec[1]);
2308                 co[2]= isec.start[2]+isec.labda*(isec.vec[2]);
2309                 
2310                 *distfac= VecLength(isec.vec);
2311         }
2312         else
2313                 *distfac= 0.0f;
2314 }
2315
2316 #endif
2317