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