style cleanup: follow style guide for formatting of if/for/while loops, and else...
[blender.git] / source / blender / render / intern / source / volume_precache.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Matt Ebb, Ra˙l Fern·ndez Hern·ndez (Farsthary).
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/render/intern/source/volume_precache.c
29  *  \ingroup render
30  */
31
32
33 #include <math.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_blenlib.h"
41 #include "BLI_math.h"
42 #include "BLI_threads.h"
43 #include "BLI_voxel.h"
44 #include "BLI_utildefines.h"
45
46 #include "PIL_time.h"
47
48 #include "RE_shader_ext.h"
49
50 #include "DNA_material_types.h"
51
52 #include "rayintersection.h"
53 #include "rayobject.h"
54 #include "render_types.h"
55 #include "rendercore.h"
56 #include "renderdatabase.h"
57 #include "volumetric.h"
58 #include "volume_precache.h"
59
60 #if defined( _MSC_VER ) && !defined( __cplusplus )
61 # define inline __inline
62 #endif // defined( _MSC_VER ) && !defined( __cplusplus )
63
64 #include "BKE_global.h"
65
66 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
67 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
68 /* only to be used here in this file, it's for speed */
69 extern struct Render R;
70 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
71
72 /* *** utility code to set up an individual raytree for objectinstance, for checking inside/outside *** */
73
74 /* Recursive test for intersections, from a point inside the mesh, to outside
75  * Number of intersections (depth) determine if a point is inside or outside the mesh */
76 static int intersect_outside_volume(RayObject *tree, Isect *isect, float *offset, int limit, int depth)
77 {
78         if (limit == 0) return depth;
79         
80         if (RE_rayobject_raycast(tree, isect)) {
81                 
82                 isect->start[0] = isect->start[0] + isect->dist*isect->dir[0];
83                 isect->start[1] = isect->start[1] + isect->dist*isect->dir[1];
84                 isect->start[2] = isect->start[2] + isect->dist*isect->dir[2];
85                 
86                 isect->dist = FLT_MAX;
87                 isect->skip = RE_SKIP_VLR_NEIGHBOUR;
88                 isect->orig.face= isect->hit.face;
89                 isect->orig.ob= isect->hit.ob;
90                 
91                 return intersect_outside_volume(tree, isect, offset, limit-1, depth+1);
92         }
93         else {
94                 return depth;
95         }
96 }
97
98 /* Uses ray tracing to check if a point is inside or outside an ObjectInstanceRen */
99 static int point_inside_obi(RayObject *tree, ObjectInstanceRen *UNUSED(obi), float *co)
100 {
101         Isect isect= {{0}};
102         float dir[3] = {0.0f,0.0f,1.0f};
103         int final_depth=0, depth=0, limit=20;
104         
105         /* set up the isect */
106         copy_v3_v3(isect.start, co);
107         copy_v3_v3(isect.dir, dir);
108         isect.mode= RE_RAY_MIRROR;
109         isect.last_hit= NULL;
110         isect.lay= -1;
111         
112         isect.dist = FLT_MAX;
113         isect.orig.face= NULL;
114         isect.orig.ob = NULL;
115
116         final_depth = intersect_outside_volume(tree, &isect, dir, limit, depth);
117         
118         /* even number of intersections: point is outside
119          * odd number: point is inside */
120         if (final_depth % 2 == 0) return 0;
121         else return 1;
122 }
123
124 /* find the bounding box of an objectinstance in global space */
125 void global_bounds_obi(Render *re, ObjectInstanceRen *obi, float *bbmin, float *bbmax)
126 {
127         ObjectRen *obr = obi->obr;
128         VolumePrecache *vp = obi->volume_precache;
129         VertRen *ver= NULL;
130         float co[3];
131         int a;
132         
133         if (vp->bbmin != NULL && vp->bbmax != NULL) {
134                 copy_v3_v3(bbmin, vp->bbmin);
135                 copy_v3_v3(bbmax, vp->bbmax);
136                 return;
137         }
138         
139         vp->bbmin = MEM_callocN(sizeof(float)*3, "volume precache min boundbox corner");
140         vp->bbmax = MEM_callocN(sizeof(float)*3, "volume precache max boundbox corner");
141         
142         INIT_MINMAX(bbmin, bbmax);
143         
144         for (a=0; a<obr->totvert; a++) {
145                 if ((a & 255)==0) ver= obr->vertnodes[a>>8].vert;
146                 else ver++;
147                 
148                 copy_v3_v3(co, ver->co);
149                 
150                 /* transformed object instance in camera space */
151                 if (obi->flag & R_TRANSFORMED)
152                         mul_m4_v3(obi->mat, co);
153                 
154                 /* convert to global space */
155                 mul_m4_v3(re->viewinv, co);
156                 
157                 DO_MINMAX(co, vp->bbmin, vp->bbmax);
158         }
159         
160         copy_v3_v3(bbmin, vp->bbmin);
161         copy_v3_v3(bbmax, vp->bbmax);
162         
163 }
164
165 /* *** light cache filtering *** */
166
167 static float get_avg_surrounds(float *cache, int *res, int xx, int yy, int zz)
168 {
169         int x, y, z, x_, y_, z_;
170         int added=0;
171         float tot=0.0f;
172         
173         for (z=-1; z <= 1; z++) {
174                 z_ = zz+z;
175                 if (z_ >= 0 && z_ <= res[2]-1) {
176                 
177                         for (y=-1; y <= 1; y++) {
178                                 y_ = yy+y;
179                                 if (y_ >= 0 && y_ <= res[1]-1) {
180                                 
181                                         for (x=-1; x <= 1; x++) {
182                                                 x_ = xx+x;
183                                                 if (x_ >= 0 && x_ <= res[0]-1) {
184                                                         const int i= V_I(x_, y_, z_, res);
185                                                         
186                                                         if (cache[i] > 0.0f) {
187                                                                 tot += cache[i];
188                                                                 added++;
189                                                         }
190                                                         
191                                                 }
192                                         }
193                                 }
194                         }
195                 }
196         }
197         
198         if (added > 0) tot /= added;
199         
200         return tot;
201 }
202
203 /* function to filter the edges of the light cache, where there was no volume originally.
204  * For each voxel which was originally external to the mesh, it finds the average values of
205  * the surrounding internal voxels and sets the original external voxel to that average amount.
206  * Works almost a bit like a 'dilate' filter */
207 static void lightcache_filter(VolumePrecache *vp)
208 {
209         int x, y, z;
210
211         for (z=0; z < vp->res[2]; z++) {
212                 for (y=0; y < vp->res[1]; y++) {
213                         for (x=0; x < vp->res[0]; x++) {
214                                 /* trigger for outside mesh */
215                                 const int i= V_I(x, y, z, vp->res);
216                                 
217                                 if (vp->data_r[i] < -0.f)
218                                         vp->data_r[i] = get_avg_surrounds(vp->data_r, vp->res, x, y, z);
219                                 if (vp->data_g[i] < -0.f)
220                                         vp->data_g[i] = get_avg_surrounds(vp->data_g, vp->res, x, y, z);
221                                 if (vp->data_b[i] < -0.f)
222                                         vp->data_b[i] = get_avg_surrounds(vp->data_b, vp->res, x, y, z);
223                         }
224                 }
225         }
226 }
227
228 #if 0
229 static void lightcache_filter2(VolumePrecache *vp)
230 {
231         int x, y, z;
232         float *new_r, *new_g, *new_b;
233         int field_size = vp->res[0]*vp->res[1]*vp->res[2]*sizeof(float);
234         
235         new_r = MEM_mallocN(field_size, "temp buffer for light cache filter r channel");
236         new_g = MEM_mallocN(field_size, "temp buffer for light cache filter g channel");
237         new_b = MEM_mallocN(field_size, "temp buffer for light cache filter b channel");
238         
239         memcpy(new_r, vp->data_r, field_size);
240         memcpy(new_g, vp->data_g, field_size);
241         memcpy(new_b, vp->data_b, field_size);
242         
243         for (z=0; z < vp->res[2]; z++) {
244                 for (y=0; y < vp->res[1]; y++) {
245                         for (x=0; x < vp->res[0]; x++) {
246                                 /* trigger for outside mesh */
247                                 const int i= V_I(x, y, z, vp->res);
248                                 if (vp->data_r[i] < -0.f)
249                                         new_r[i] = get_avg_surrounds(vp->data_r, vp->res, x, y, z);
250                                 if (vp->data_g[i] < -0.f)
251                                         new_g[i] = get_avg_surrounds(vp->data_g, vp->res, x, y, z);
252                                 if (vp->data_b[i] < -0.f)
253                                         new_b[i] = get_avg_surrounds(vp->data_b, vp->res, x, y, z);
254                         }
255                 }
256         }
257         
258         SWAP(float *, vp->data_r, new_r);
259         SWAP(float *, vp->data_g, new_g);
260         SWAP(float *, vp->data_b, new_b);
261         
262         if (new_r) { MEM_freeN(new_r); new_r=NULL; }
263         if (new_g) { MEM_freeN(new_g); new_g=NULL; }
264         if (new_b) { MEM_freeN(new_b); new_b=NULL; }
265 }
266 #endif
267
268 static inline int ms_I(int x, int y, int z, int *n) //has a pad of 1 voxel surrounding the core for boundary simulation
269
270         /* different ordering to light cache */
271         return x*(n[1]+2)*(n[2]+2) + y*(n[2]+2) + z;    
272 }
273
274 static inline int v_I_pad(int x, int y, int z, int *n) //has a pad of 1 voxel surrounding the core for boundary simulation
275
276         /* same ordering to light cache, with padding */
277         return z*(n[1]+2)*(n[0]+2) + y*(n[0]+2) + x;    
278 }
279
280 static inline int lc_to_ms_I(int x, int y, int z, int *n)
281
282         /* converting light cache index to multiple scattering index */
283         return (x-1)*(n[1]*n[2]) + (y-1)*(n[2]) + z-1;
284 }
285
286 /* *** multiple scattering approximation *** */
287
288 /* get the total amount of light energy in the light cache. used to normalize after multiple scattering */
289 static float total_ss_energy(Render *re, int do_test_break, VolumePrecache *vp)
290 {
291         int x, y, z;
292         int *res = vp->res;
293         float energy=0.f;
294         
295         for (z=0; z < res[2]; z++) {
296                 for (y=0; y < res[1]; y++) {
297                         for (x=0; x < res[0]; x++) {
298                                 const int i=V_I(x, y, z, res);
299                         
300                                 if (vp->data_r[i] > 0.f) energy += vp->data_r[i];
301                                 if (vp->data_g[i] > 0.f) energy += vp->data_g[i];
302                                 if (vp->data_b[i] > 0.f) energy += vp->data_b[i];
303                         }
304                 }
305
306                 if (do_test_break && re->test_break(re->tbh)) break;
307         }
308         
309         return energy;
310 }
311
312 static float total_ms_energy(Render *re, int do_test_break, float *sr, float *sg, float *sb, int *res)
313 {
314         int x, y, z;
315         float energy=0.f;
316         
317         for (z=1;z<=res[2];z++) {
318                 for (y=1;y<=res[1];y++) {
319                         for (x=1;x<=res[0];x++) {
320                                 const int i = ms_I(x,y,z,res);
321                                 
322                                 if (sr[i] > 0.f) energy += sr[i];
323                                 if (sg[i] > 0.f) energy += sg[i];
324                                 if (sb[i] > 0.f) energy += sb[i];
325                         }
326                 }
327
328                 if (do_test_break && re->test_break(re->tbh)) break;
329         }
330         
331         return energy;
332 }
333
334 static void ms_diffuse(Render *re, int do_test_break, float *x0, float *x, float diff, int *n) //n is the unpadded resolution
335 {
336         int i, j, k, l;
337         const float dt = VOL_MS_TIMESTEP;
338         size_t size = n[0]*n[1]*n[2];
339         const float a = dt*diff*size;
340         
341         for (l=0; l<20; l++)
342         {
343                 for (k=1; k<=n[2]; k++)
344                 {
345                         for (j=1; j<=n[1]; j++)
346                         {
347                                 for (i=1; i<=n[0]; i++)
348                                 {
349                                    x[v_I_pad(i,j,k,n)] = (x0[v_I_pad(i,j,k,n)]) + a*(   x0[v_I_pad(i-1,j,k,n)]+ x0[v_I_pad(i+1,j,k,n)]+ x0[v_I_pad(i,j-1,k,n)]+
350                                                                                                                                                 x0[v_I_pad(i,j+1,k,n)]+ x0[v_I_pad(i,j,k-1,n)]+x0[v_I_pad(i,j,k+1,n)]
351                                                                                                                                                 ) / (1+6*a);
352                                 }
353                         }
354
355                         if (do_test_break && re->test_break(re->tbh)) break;
356                 }
357
358                 if (re->test_break(re->tbh)) break;
359         }
360 }
361
362 static void multiple_scattering_diffusion(Render *re, VolumePrecache *vp, Material *ma)
363 {
364         const float diff = ma->vol.ms_diff * 0.001f;    /* compensate for scaling for a nicer UI range */
365         const int simframes = (int)(ma->vol.ms_spread * (float)MAX3(vp->res[0], vp->res[1], vp->res[2]));
366         const int shade_type = ma->vol.shade_type;
367         float fac = ma->vol.ms_intensity;
368         
369         int x, y, z, m;
370         int *n = vp->res;
371         const int size = (n[0]+2)*(n[1]+2)*(n[2]+2);
372         const int do_test_break = (size > 100000);
373         double time, lasttime= PIL_check_seconds_timer();
374         float total;
375         float c=1.0f;
376         float origf;    /* factor for blending in original light cache */
377         float energy_ss, energy_ms;
378
379         float *sr0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
380         float *sr=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
381         float *sg0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
382         float *sg=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
383         float *sb0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
384         float *sb=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
385
386         total = (float)(n[0]*n[1]*n[2]*simframes);
387         
388         energy_ss = total_ss_energy(re, do_test_break, vp);
389         
390         /* Scattering as diffusion pass */
391         for (m=0; m<simframes; m++)
392         {
393                 /* add sources */
394                 for (z=1; z<=n[2]; z++)
395                 {
396                         for (y=1; y<=n[1]; y++)
397                         {
398                                 for (x=1; x<=n[0]; x++)
399                                 {
400                                         const int i = lc_to_ms_I(x, y ,z, n);   //lc index                                      
401                                         const int j = ms_I(x, y, z, n);                 //ms index
402                                         
403                                         time= PIL_check_seconds_timer();
404                                         c++;                                                                            
405                                         if (vp->data_r[i] > 0.0f)
406                                                 sr[j] += vp->data_r[i];
407                                         if (vp->data_g[i] > 0.0f)
408                                                 sg[j] += vp->data_g[i];
409                                         if (vp->data_b[i] > 0.0f)
410                                                 sb[j] += vp->data_b[i];
411                                         
412                                         /* Displays progress every second */
413                                         if (time-lasttime>1.0) {
414                                                 char str[64];
415                                                 BLI_snprintf(str, sizeof(str), "Simulating multiple scattering: %d%%", (int)(100.0f * (c / total)));
416                                                 re->i.infostr= str;
417                                                 re->stats_draw(re->sdh, &re->i);
418                                                 re->i.infostr= NULL;
419                                                 lasttime= time;
420                                         }
421                                 }
422                         }
423
424                         if (do_test_break && re->test_break(re->tbh)) break;
425                 }
426
427                 if (re->test_break(re->tbh)) break;
428
429                 SWAP(float *,sr,sr0);
430                 SWAP(float *,sg,sg0);
431                 SWAP(float *,sb,sb0);
432
433                 /* main diffusion simulation */
434                 ms_diffuse(re, do_test_break, sr0, sr, diff, n);
435                 ms_diffuse(re, do_test_break, sg0, sg, diff, n);
436                 ms_diffuse(re, do_test_break, sb0, sb, diff, n);
437                 
438                 if (re->test_break(re->tbh)) break;
439         }
440         
441         /* normalization factor to conserve energy */
442         energy_ms = total_ms_energy(re, do_test_break, sr, sg, sb, n);
443         fac *= (energy_ss / energy_ms);
444         
445         /* blend multiple scattering back in the light cache */
446         if (shade_type == MA_VOL_SHADE_SHADEDPLUSMULTIPLE) {
447                 /* conserve energy - half single, half multiple */
448                 origf = 0.5f;
449                 fac *= 0.5f;
450         }
451         else {
452                 origf = 0.0f;
453         }
454
455         for (z=1;z<=n[2];z++)
456         {
457                 for (y=1;y<=n[1];y++)
458                 {
459                         for (x=1;x<=n[0];x++)
460                         {
461                                 const int i = lc_to_ms_I(x, y ,z, n);   //lc index                                      
462                                 const int j = ms_I(x, y, z, n);                 //ms index
463                                 
464                                 vp->data_r[i] = origf * vp->data_r[i] + fac * sr[j];
465                                 vp->data_g[i] = origf * vp->data_g[i] + fac * sg[j];
466                                 vp->data_b[i] = origf * vp->data_b[i] + fac * sb[j];
467                         }
468                 }
469
470                 if (do_test_break && re->test_break(re->tbh)) break;
471         }
472
473         MEM_freeN(sr0);
474         MEM_freeN(sr);
475         MEM_freeN(sg0);
476         MEM_freeN(sg);
477         MEM_freeN(sb0);
478         MEM_freeN(sb);
479 }
480
481
482
483 #if 0 // debug stuff
484 static void *vol_precache_part_test(void *data)
485 {
486         VolPrecachePart *pa = data;
487
488         printf("part number: %d \n", pa->num);
489         printf("done: %d \n", pa->done);
490         printf("x min: %d   x max: %d \n", pa->minx, pa->maxx);
491         printf("y min: %d   y max: %d \n", pa->miny, pa->maxy);
492         printf("z min: %d   z max: %d \n", pa->minz, pa->maxz);
493
494         return NULL;
495 }
496 #endif
497
498 typedef struct VolPrecacheQueue {
499         ThreadQueue *work;
500         ThreadQueue *done;
501 } VolPrecacheQueue;
502
503 /* Iterate over the 3d voxel grid, and fill the voxels with scattering information
504  *
505  * It's stored in memory as 3 big float grids next to each other, one for each RGB channel.
506  * I'm guessing the memory alignment may work out better this way for the purposes
507  * of doing linear interpolation, but I haven't actually tested this theory! :)
508  */
509 static void *vol_precache_part(void *data)
510 {
511         VolPrecacheQueue *queue = (VolPrecacheQueue*)data;
512         VolPrecachePart *pa;
513
514         while ((pa = BLI_thread_queue_pop(queue->work))) {
515                 ObjectInstanceRen *obi = pa->obi;
516                 RayObject *tree = pa->tree;
517                 ShadeInput *shi = pa->shi;
518                 float scatter_col[3] = {0.f, 0.f, 0.f};
519                 float co[3], cco[3], view[3];
520                 int x, y, z, i;
521                 int res[3];
522
523                 if (pa->re->test_break && pa->re->test_break(pa->re->tbh))
524                         break;
525
526                 res[0]= pa->res[0];
527                 res[1]= pa->res[1];
528                 res[2]= pa->res[2];
529
530                 for (z= pa->minz; z < pa->maxz; z++) {
531                         co[2] = pa->bbmin[2] + (pa->voxel[2] * (z + 0.5f));
532                         
533                         for (y= pa->miny; y < pa->maxy; y++) {
534                                 co[1] = pa->bbmin[1] + (pa->voxel[1] * (y + 0.5f));
535                                 
536                                 for (x=pa->minx; x < pa->maxx; x++) {
537                                         co[0] = pa->bbmin[0] + (pa->voxel[0] * (x + 0.5f));
538                                         
539                                         if (pa->re->test_break && pa->re->test_break(pa->re->tbh))
540                                                 break;
541                                         
542                                         /* convert from world->camera space for shading */
543                                         mul_v3_m4v3(cco, pa->viewmat, co);
544                                         
545                                         i= V_I(x, y, z, res);
546                                         
547                                         // don't bother if the point is not inside the volume mesh
548                                         if (!point_inside_obi(tree, obi, cco)) {
549                                                 obi->volume_precache->data_r[i] = -1.0f;
550                                                 obi->volume_precache->data_g[i] = -1.0f;
551                                                 obi->volume_precache->data_b[i] = -1.0f;
552                                                 continue;
553                                         }
554                                         
555                                         copy_v3_v3(view, cco);
556                                         normalize_v3(view);
557                                         vol_get_scattering(shi, scatter_col, cco, view);
558                                 
559                                         obi->volume_precache->data_r[i] = scatter_col[0];
560                                         obi->volume_precache->data_g[i] = scatter_col[1];
561                                         obi->volume_precache->data_b[i] = scatter_col[2];
562                                         
563                                 }
564                         }
565                 }
566
567                 BLI_thread_queue_push(queue->done, pa);
568         }
569         
570         return NULL;
571 }
572
573
574 static void precache_setup_shadeinput(Render *re, ObjectInstanceRen *obi, Material *ma, ShadeInput *shi)
575 {
576         memset(shi, 0, sizeof(ShadeInput)); 
577         shi->depth= 1;
578         shi->mask= 1;
579         shi->mat = ma;
580         shi->vlr = NULL;
581         memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));        // note, keep this synced with render_types.h
582         shi->har= shi->mat->har;
583         shi->obi= obi;
584         shi->obr= obi->obr;
585         shi->lay = re->lay;
586 }
587
588 static void precache_init_parts(Render *re, RayObject *tree, ShadeInput *shi, ObjectInstanceRen *obi, int totthread, int *parts)
589 {
590         VolumePrecache *vp = obi->volume_precache;
591         int i=0, x, y, z;
592         float voxel[3];
593         int sizex, sizey, sizez;
594         float bbmin[3], bbmax[3];
595         int *res;
596         int minx, maxx;
597         int miny, maxy;
598         int minz, maxz;
599         
600         if (!vp) return;
601
602         BLI_freelistN(&re->volume_precache_parts);
603         
604         /* currently we just subdivide the box, number of threads per side */
605         parts[0] = parts[1] = parts[2] = totthread;
606         res = vp->res;
607         
608         /* using boundbox in worldspace */
609         global_bounds_obi(re, obi, bbmin, bbmax);
610         sub_v3_v3v3(voxel, bbmax, bbmin);
611         
612         voxel[0] /= (float)res[0];
613         voxel[1] /= (float)res[1];
614         voxel[2] /= (float)res[2];
615
616         for (x=0; x < parts[0]; x++) {
617                 sizex = ceil(res[0] / (float)parts[0]);
618                 minx = x * sizex;
619                 maxx = minx + sizex;
620                 maxx = (maxx>res[0])?res[0]:maxx;
621                 
622                 for (y=0; y < parts[1]; y++) {
623                         sizey = ceil(res[1] / (float)parts[1]);
624                         miny = y * sizey;
625                         maxy = miny + sizey;
626                         maxy = (maxy>res[1])?res[1]:maxy;
627                         
628                         for (z=0; z < parts[2]; z++) {
629                                 VolPrecachePart *pa= MEM_callocN(sizeof(VolPrecachePart), "new precache part");
630                                 
631                                 sizez = ceil(res[2] / (float)parts[2]);
632                                 minz = z * sizez;
633                                 maxz = minz + sizez;
634                                 maxz = (maxz>res[2])?res[2]:maxz;
635                                 
636                                 pa->re = re;
637                                 pa->num = i;
638                                 pa->tree = tree;
639                                 pa->shi = shi;
640                                 pa->obi = obi;
641                                 copy_m4_m4(pa->viewmat, re->viewmat);
642                                 
643                                 copy_v3_v3(pa->bbmin, bbmin);
644                                 copy_v3_v3(pa->voxel, voxel);
645                                 copy_v3_v3_int(pa->res, res);
646                                 
647                                 pa->minx = minx; pa->maxx = maxx;
648                                 pa->miny = miny; pa->maxy = maxy;
649                                 pa->minz = minz; pa->maxz = maxz;
650                                 
651                                 
652                                 BLI_addtail(&re->volume_precache_parts, pa);
653                                 
654                                 i++;
655                         }
656                 }
657         }
658 }
659
660 /* calculate resolution from bounding box in world space */
661 static int precache_resolution(Render *re, VolumePrecache *vp, ObjectInstanceRen *obi, int res)
662 {
663         float dim[3], div;
664         float bbmin[3], bbmax[3];
665         
666         /* bound box in global space */
667         global_bounds_obi(re, obi, bbmin, bbmax);
668         sub_v3_v3v3(dim, bbmax, bbmin);
669         
670         div = MAX3(dim[0], dim[1], dim[2]);
671         dim[0] /= div;
672         dim[1] /= div;
673         dim[2] /= div;
674         
675         vp->res[0] = ceil(dim[0] * res);
676         vp->res[1] = ceil(dim[1] * res);
677         vp->res[2] = ceil(dim[2] * res);
678         
679         if ((vp->res[0] < 1) || (vp->res[1] < 1) || (vp->res[2] < 1))
680                 return 0;
681         
682         return 1;
683 }
684
685 /* Precache a volume into a 3D voxel grid.
686  * The voxel grid is stored in the ObjectInstanceRen, 
687  * in camera space, aligned with the ObjectRen's bounding box.
688  * Resolution is defined by the user.
689  */
690 static void vol_precache_objectinstance_threads(Render *re, ObjectInstanceRen *obi, Material *ma)
691 {
692         VolumePrecache *vp;
693         VolPrecachePart *pa;
694         RayObject *tree;
695         ShadeInput shi;
696         ListBase threads;
697         VolPrecacheQueue queue;
698         int parts[3] = {1, 1, 1}, totparts;
699         
700         int counter=0;
701         int totthread = re->r.threads, thread;
702         
703         double time, lasttime= PIL_check_seconds_timer();
704         
705         R = *re;
706
707         /* create a raytree with just the faces of the instanced ObjectRen, 
708          * used for checking if the cached point is inside or outside. */
709         tree = makeraytree_object(&R, obi);
710         if (!tree) return;
711
712         vp = MEM_callocN(sizeof(VolumePrecache), "volume light cache");
713         obi->volume_precache = vp;
714         
715         if (!precache_resolution(re, vp, obi, ma->vol.precache_resolution)) {
716                 MEM_freeN(vp);
717                 vp = NULL;
718                 return;
719         }
720
721         vp->data_r = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data red channel");
722         vp->data_g = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data green channel");
723         vp->data_b = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data blue channel");
724         if (vp->data_r==NULL || vp->data_g==NULL || vp->data_b==NULL) {
725                 MEM_freeN(vp);
726                 return;
727         }
728
729         /* Need a shadeinput to calculate scattering */
730         precache_setup_shadeinput(re, obi, ma, &shi);
731         
732         precache_init_parts(re, tree, &shi, obi, totthread, parts);
733         totparts = parts[0] * parts[1] * parts[2];
734
735         /* setup work and done queues */
736         queue.work = BLI_thread_queue_init();
737         queue.done = BLI_thread_queue_init();
738         BLI_thread_queue_nowait(queue.work);
739
740         for (pa= re->volume_precache_parts.first; pa; pa= pa->next)
741                 BLI_thread_queue_push(queue.work, pa);
742         
743         /* launch threads */
744         BLI_init_threads(&threads, vol_precache_part, totthread);
745
746         for (thread= 0; thread<totthread; thread++)
747                 BLI_insert_thread(&threads, &queue);
748         
749         /* loop waiting for work to be done */
750         while (counter < totparts) {
751                 if (re->test_break && re->test_break(re->tbh))
752                         break;
753
754                 if (BLI_thread_queue_pop_timeout(queue.done, 50))
755                         counter++;
756
757                 time= PIL_check_seconds_timer();
758                 if (time-lasttime>1.0) {
759                         char str[64];
760                         BLI_snprintf(str, sizeof(str), "Precaching volume: %d%%", (int)(100.0f * ((float)counter / (float)totparts)));
761                         re->i.infostr= str;
762                         re->stats_draw(re->sdh, &re->i);
763                         re->i.infostr= NULL;
764                         lasttime= time;
765                 }
766         }
767         
768         /* free */
769         BLI_end_threads(&threads);
770         BLI_thread_queue_free(queue.work);
771         BLI_thread_queue_free(queue.done);
772         BLI_freelistN(&re->volume_precache_parts);
773         
774         if (tree) {
775                 //TODO: makeraytree_object creates a tree and saves it on OBI, if we free this tree we should also clear other pointers to it
776                 //RE_rayobject_free(tree);
777                 //tree= NULL;
778         }
779         
780         if (ELEM(ma->vol.shade_type, MA_VOL_SHADE_MULTIPLE, MA_VOL_SHADE_SHADEDPLUSMULTIPLE)) {
781                 /* this should be before the filtering */
782                 multiple_scattering_diffusion(re, obi->volume_precache, ma);
783         }
784                 
785         lightcache_filter(obi->volume_precache);
786 }
787
788 static int using_lightcache(Material *ma)
789 {
790         return (((ma->vol.shadeflag & MA_VOL_PRECACHESHADING) && (ma->vol.shade_type == MA_VOL_SHADE_SHADED))
791                 || (ELEM(ma->vol.shade_type, MA_VOL_SHADE_MULTIPLE, MA_VOL_SHADE_SHADEDPLUSMULTIPLE)));
792 }
793
794 /* loop through all objects (and their associated materials)
795  * marked for pre-caching in convertblender.c, and pre-cache them */
796 void volume_precache(Render *re)
797 {
798         ObjectInstanceRen *obi;
799         VolumeOb *vo;
800
801         re->i.infostr= "Volume preprocessing";
802         re->stats_draw(re->sdh, &re->i);
803
804         for (vo= re->volumes.first; vo; vo= vo->next) {
805                 if (using_lightcache(vo->ma)) {
806                         for (obi= re->instancetable.first; obi; obi= obi->next) {
807                                 if (obi->obr == vo->obr) {
808                                         vol_precache_objectinstance_threads(re, obi, vo->ma);
809
810                                         if (re->test_break && re->test_break(re->tbh))
811                                                 break;
812                                 }
813                         }
814
815                         if (re->test_break && re->test_break(re->tbh))
816                                 break;
817                 }
818         }
819         
820         re->i.infostr= NULL;
821         re->stats_draw(re->sdh, &re->i);
822 }
823
824 void free_volume_precache(Render *re)
825 {
826         ObjectInstanceRen *obi;
827         
828         for (obi= re->instancetable.first; obi; obi= obi->next) {
829                 if (obi->volume_precache != NULL) {
830                         MEM_freeN(obi->volume_precache->data_r);
831                         MEM_freeN(obi->volume_precache->data_g);
832                         MEM_freeN(obi->volume_precache->data_b);
833                         MEM_freeN(obi->volume_precache->bbmin);
834                         MEM_freeN(obi->volume_precache->bbmax);
835                         MEM_freeN(obi->volume_precache);
836                         obi->volume_precache = NULL;
837                 }
838         }
839         
840         BLI_freelistN(&re->volumes);
841 }
842
843 int point_inside_volume_objectinstance(Render *re, ObjectInstanceRen *obi, float *co)
844 {
845         RayObject *tree;
846         int inside=0;
847         
848         tree = makeraytree_object(re, obi);
849         if (!tree) return 0;
850         
851         inside = point_inside_obi(tree, obi, co);
852         
853         //TODO: makeraytree_object creates a tree and saves it on OBI, if we free this tree we should also clear other pointers to it
854         //RE_rayobject_free(tree);
855         //tree= NULL;
856         
857         return inside;
858 }
859