style cleanup, brackets in else/if, some indentation.
[blender.git] / source / blender / blenkernel / intern / smoke.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) Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Daniel Genrich
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/smoke.c
29  *  \ingroup bke
30  */
31
32
33 /* Part of the code copied from elbeem fluid library, copyright by Nils Thuerey */
34
35 #include <GL/glew.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include <float.h>
40 #include <math.h>
41 #include <stdio.h>
42 #include <string.h> /* memset */
43
44 #include "BLI_linklist.h"
45 #include "BLI_rand.h"
46 #include "BLI_jitter.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_math.h"
49 #include "BLI_edgehash.h"
50 #include "BLI_kdtree.h"
51 #include "BLI_kdopbvh.h"
52 #include "BLI_utildefines.h"
53
54 #include "BKE_bvhutils.h"
55 #include "BKE_cdderivedmesh.h"
56 #include "BKE_customdata.h"
57 #include "BKE_DerivedMesh.h"
58 #include "BKE_effect.h"
59 #include "BKE_modifier.h"
60 #include "BKE_particle.h"
61 #include "BKE_pointcache.h"
62 #include "BKE_smoke.h"
63
64
65 #include "DNA_customdata_types.h"
66 #include "DNA_group_types.h"
67 #include "DNA_lamp_types.h"
68 #include "DNA_mesh_types.h"
69 #include "DNA_meshdata_types.h"
70 #include "DNA_modifier_types.h"
71 #include "DNA_object_types.h"
72 #include "DNA_particle_types.h"
73 #include "DNA_scene_types.h"
74 #include "DNA_smoke_types.h"
75
76 #include "smoke_API.h"
77
78 #include "BKE_smoke.h"
79
80 /* UNUSED so far, may be enabled later */
81 /* #define USE_SMOKE_COLLISION_DM */
82
83 #ifdef WITH_SMOKE
84
85 #ifdef _WIN32
86 #include <time.h>
87 #include <stdio.h>
88 #include <conio.h>
89 #include <windows.h>
90
91 static LARGE_INTEGER liFrequency;
92 static LARGE_INTEGER liStartTime;
93 static LARGE_INTEGER liCurrentTime;
94
95 static void tstart ( void )
96 {
97         QueryPerformanceFrequency ( &liFrequency );
98         QueryPerformanceCounter ( &liStartTime );
99 }
100 static void tend ( void )
101 {
102         QueryPerformanceCounter ( &liCurrentTime );
103 }
104 static double tval( void )
105 {
106         return ((double)( (liCurrentTime.QuadPart - liStartTime.QuadPart)* (double)1000.0/(double)liFrequency.QuadPart ));
107 }
108 #else
109 #include <sys/time.h>
110 static struct timeval _tstart, _tend;
111 static struct timezone tz;
112 static void tstart ( void )
113 {
114         gettimeofday ( &_tstart, &tz );
115 }
116 static void tend ( void )
117 {
118         gettimeofday ( &_tend,&tz );
119 }
120
121 #if 0 // unused
122 static double tval()
123 {
124         double t1, t2;
125         t1 = ( double ) _tstart.tv_sec*1000 + ( double ) _tstart.tv_usec/ ( 1000 );
126         t2 = ( double ) _tend.tv_sec*1000 + ( double ) _tend.tv_usec/ ( 1000 );
127         return t2-t1;
128 }
129 #endif
130 #endif
131
132 struct Object;
133 struct Scene;
134 struct DerivedMesh;
135 struct SmokeModifierData;
136
137 #define TRI_UVOFFSET (1./4.)
138
139 /* forward declerations */
140 static void calcTriangleDivs(Object *ob, MVert *verts, int numverts, MFace *tris, int numfaces, int numtris, int **tridivs, float cell_len);
141 static void get_cell(float *p0, int res[3], float dx, float *pos, int *cell, int correct);
142 static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs);
143
144 #else /* WITH_SMOKE */
145
146 /* Stubs to use when smoke is disabled */
147 struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype)) { return NULL; }
148 struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(p0)) { return NULL; }
149 void smoke_free(struct FLUID_3D *UNUSED(fluid)) {}
150 void smoke_turbulence_free(struct WTURBULENCE *UNUSED(wt)) {}
151 void smoke_initWaveletBlenderRNA(struct WTURBULENCE *UNUSED(wt), float *UNUSED(strength)) {}
152 void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity), int *UNUSED(border_colli)) {}
153 long long smoke_get_mem_req(int UNUSED(xres), int UNUSED(yres), int UNUSED(zres), int UNUSED(amplify)) { return 0; }
154 void smokeModifier_do(SmokeModifierData *UNUSED(smd), Scene *UNUSED(scene), Object *UNUSED(ob), DerivedMesh *UNUSED(dm)) {}
155
156 #endif /* WITH_SMOKE */
157
158 #ifdef WITH_SMOKE
159
160 static int smokeModifier_init (SmokeModifierData *smd, Object *ob, Scene *scene, DerivedMesh *dm)
161 {
162         if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid)
163         {
164                 size_t i;
165                 float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
166                 float size[3];
167                 MVert *verts = dm->getVertArray(dm);
168                 float scale = 0.0;
169                 int res;                
170
171                 res = smd->domain->maxres;
172
173                 // get BB of domain
174                 for(i = 0; i < dm->getNumVerts(dm); i++)
175                 {
176                         float tmp[3];
177
178                         copy_v3_v3(tmp, verts[i].co);
179                         mul_m4_v3(ob->obmat, tmp);
180
181                         // min BB
182                         min[0] = MIN2(min[0], tmp[0]);
183                         min[1] = MIN2(min[1], tmp[1]);
184                         min[2] = MIN2(min[2], tmp[2]);
185
186                         // max BB
187                         max[0] = MAX2(max[0], tmp[0]);
188                         max[1] = MAX2(max[1], tmp[1]);
189                         max[2] = MAX2(max[2], tmp[2]);
190                 }
191
192                 copy_v3_v3(smd->domain->p0, min);
193                 copy_v3_v3(smd->domain->p1, max);
194
195                 // calc other res with max_res provided
196                 sub_v3_v3v3(size, max, min);
197
198                 // printf("size: %f, %f, %f\n", size[0], size[1], size[2]);
199
200                 // prevent crash when initializing a plane as domain
201                 if((size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON))
202                         return 0;
203
204                 if(size[0] > size[1])
205                 {
206                         if(size[0] > size[2])
207                         {
208                                 scale = res / size[0];
209                                 smd->domain->dx = size[0] / res;
210                                 smd->domain->res[0] = res;
211                                 smd->domain->res[1] = (int)(size[1] * scale + 0.5);
212                                 smd->domain->res[2] = (int)(size[2] * scale + 0.5);
213                         }
214                         else {
215                                 scale = res / size[2];
216                                 smd->domain->dx = size[2] / res;
217                                 smd->domain->res[2] = res;
218                                 smd->domain->res[0] = (int)(size[0] * scale + 0.5);
219                                 smd->domain->res[1] = (int)(size[1] * scale + 0.5);
220                         }
221                 }
222                 else {
223                         if(size[1] > size[2])
224                         {
225                                 scale = res / size[1];
226                                 smd->domain->dx = size[1] / res;
227                                 smd->domain->res[1] = res;
228                                 smd->domain->res[0] = (int)(size[0] * scale + 0.5);
229                                 smd->domain->res[2] = (int)(size[2] * scale + 0.5);
230                         }
231                         else {
232                                 scale = res / size[2];
233                                 smd->domain->dx = size[2] / res;
234                                 smd->domain->res[2] = res;
235                                 smd->domain->res[0] = (int)(size[0] * scale + 0.5);
236                                 smd->domain->res[1] = (int)(size[1] * scale + 0.5);
237                         }
238                 }
239
240                 // printf("smd->domain->dx: %f\n", smd->domain->dx);
241
242                 // TODO: put in failsafe if res<=0 - dg
243
244                 // printf("res[0]: %d, res[1]: %d, res[2]: %d\n", smd->domain->res[0], smd->domain->res[1], smd->domain->res[2]);
245                 // dt max is 0.1
246                 smd->domain->fluid = smoke_init(smd->domain->res, smd->domain->p0);
247                 smd->time = scene->r.cfra;
248
249                 if(smd->domain->flags & MOD_SMOKE_HIGHRES)
250                 {
251                         smd->domain->wt = smoke_turbulence_init(smd->domain->res, smd->domain->amplify + 1, smd->domain->noise);
252                         smd->domain->res_wt[0] = smd->domain->res[0] * (smd->domain->amplify + 1);
253                         smd->domain->res_wt[1] = smd->domain->res[1] * (smd->domain->amplify + 1);                      
254                         smd->domain->res_wt[2] = smd->domain->res[2] * (smd->domain->amplify + 1);                      
255                         smd->domain->dx_wt = smd->domain->dx / (smd->domain->amplify + 1);              
256                         // printf("smd->domain->amplify: %d\n",  smd->domain->amplify);
257                         // printf("(smd->domain->flags & MOD_SMOKE_HIGHRES)\n");
258                 }
259
260                 if(!smd->domain->shadow)
261                         smd->domain->shadow = MEM_callocN(sizeof(float) * smd->domain->res[0] * smd->domain->res[1] * smd->domain->res[2], "SmokeDomainShadow");
262
263                 smoke_initBlenderRNA(smd->domain->fluid, &(smd->domain->alpha), &(smd->domain->beta), &(smd->domain->time_scale), &(smd->domain->vorticity), &(smd->domain->border_collisions));
264
265                 if(smd->domain->wt)     
266                 {
267                         smoke_initWaveletBlenderRNA(smd->domain->wt, &(smd->domain->strength));
268                         // printf("smoke_initWaveletBlenderRNA\n");
269                 }
270                 return 1;
271         }
272         else if((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
273         {
274                 // handle flow object here
275                 // XXX TODO
276
277                 smd->time = scene->r.cfra;
278
279                 // update particle lifetime to be one frame
280                 // smd->flow->psys->part->lifetime = scene->r.efra + 1;
281 /*
282                 if(!smd->flow->bvh)
283                 {
284                         // smd->flow->bvh = MEM_callocN(sizeof(BVHTreeFromMesh), "smoke_bvhfromfaces");
285                         // bvhtree_from_mesh_faces(smd->flow->bvh, dm, 0.0, 2, 6);
286
287                         // copy obmat
288                         // copy_m4_m4(smd->flow->mat, ob->obmat);
289                         // copy_m4_m4(smd->flow->mat_old, ob->obmat);
290                 }
291 */
292
293                 return 1;
294         }
295         else if((smd->type & MOD_SMOKE_TYPE_COLL))
296         {
297                 smd->time = scene->r.cfra;
298
299                 // todo: delete this when loading colls work -dg
300                 if(!smd->coll)
301                         smokeModifier_createType(smd);
302
303                 if(!smd->coll->points)
304                 {
305                         // init collision points
306                         SmokeCollSettings *scs = smd->coll;
307
308                         // copy obmat
309                         copy_m4_m4(scs->mat, ob->obmat);
310                         copy_m4_m4(scs->mat_old, ob->obmat);
311
312                         fill_scs_points(ob, dm, scs);
313                 }
314
315                 if(!smd->coll->bvhtree)
316                 {
317                         smd->coll->bvhtree = NULL; // bvhtree_build_from_smoke ( ob->obmat, dm->getTessFaceArray(dm), dm->getNumTessFaces(dm), dm->getVertArray(dm), dm->getNumVerts(dm), 0.0 );
318                 }
319                 return 1;
320         }
321
322         return 2;
323 }
324
325 static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs)
326 {
327         MVert *mvert = dm->getVertArray(dm);
328         MFace *mface = dm->getTessFaceArray(dm);
329         int i = 0, divs = 0;
330         int *tridivs = NULL;
331         float cell_len = 1.0 / 50.0; // for res = 50
332         int newdivs = 0;
333         int quads = 0, facecounter = 0;
334
335         // count quads
336         for(i = 0; i < dm->getNumTessFaces(dm); i++)
337         {
338                 if(mface[i].v4)
339                         quads++;
340         }
341
342         calcTriangleDivs(ob, mvert, dm->getNumVerts(dm), mface,  dm->getNumTessFaces(dm), dm->getNumTessFaces(dm) + quads, &tridivs, cell_len);
343
344         // count triangle divisions
345         for(i = 0; i < dm->getNumTessFaces(dm) + quads; i++)
346         {
347                 divs += (tridivs[3 * i] + 1) * (tridivs[3 * i + 1] + 1) * (tridivs[3 * i + 2] + 1);
348         }
349
350         // printf("divs: %d\n", divs);
351
352         scs->points = MEM_callocN(sizeof(float) * (dm->getNumVerts(dm) + divs) * 3, "SmokeCollPoints");
353
354         for(i = 0; i < dm->getNumVerts(dm); i++)
355         {
356                 float tmpvec[3];
357                 copy_v3_v3(tmpvec, mvert[i].co);
358                 mul_m4_v3(ob->obmat, tmpvec);
359                 copy_v3_v3(&scs->points[i * 3], tmpvec);
360         }
361         
362         for(i = 0, facecounter = 0; i < dm->getNumTessFaces(dm); i++)
363         {
364                 int again = 0;
365                 do
366                 {
367                         int j, k;
368                         int divs1 = tridivs[3 * facecounter + 0];
369                         int divs2 = tridivs[3 * facecounter + 1];
370                         //int divs3 = tridivs[3 * facecounter + 2];
371                         float side1[3], side2[3], trinormorg[3], trinorm[3];
372                         
373                         if(again == 1 && mface[i].v4)
374                         {
375                                 sub_v3_v3v3(side1,  mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co);
376                                 sub_v3_v3v3(side2,  mvert[ mface[i].v4 ].co, mvert[ mface[i].v1 ].co);
377                         }
378                         else {
379                                 sub_v3_v3v3(side1,  mvert[ mface[i].v2 ].co, mvert[ mface[i].v1 ].co);
380                                 sub_v3_v3v3(side2,  mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co);
381                         }
382
383                         cross_v3_v3v3(trinormorg, side1, side2);
384                         normalize_v3(trinormorg);
385                         copy_v3_v3(trinorm, trinormorg);
386                         mul_v3_fl(trinorm, 0.25 * cell_len);
387
388                         for(j = 0; j <= divs1; j++)
389                         {
390                                 for(k = 0; k <= divs2; k++)
391                                 {
392                                         float p1[3], p2[3], p3[3], p[3]={0,0,0}; 
393                                         const float uf = (float)(j + TRI_UVOFFSET) / (float)(divs1 + 0.0);
394                                         const float vf = (float)(k + TRI_UVOFFSET) / (float)(divs2 + 0.0);
395                                         float tmpvec[3];
396                                         
397                                         if(uf+vf > 1.0) 
398                                         {
399                                                 // printf("bigger - divs1: %d, divs2: %d\n", divs1, divs2);
400                                                 continue;
401                                         }
402
403                                         copy_v3_v3(p1, mvert[ mface[i].v1 ].co);
404                                         if(again == 1 && mface[i].v4)
405                                         {
406                                                 copy_v3_v3(p2, mvert[ mface[i].v3 ].co);
407                                                 copy_v3_v3(p3, mvert[ mface[i].v4 ].co);
408                                         }
409                                         else {
410                                                 copy_v3_v3(p2, mvert[ mface[i].v2 ].co);
411                                                 copy_v3_v3(p3, mvert[ mface[i].v3 ].co);
412                                         }
413
414                                         mul_v3_fl(p1, (1.0-uf-vf));
415                                         mul_v3_fl(p2, uf);
416                                         mul_v3_fl(p3, vf);
417                                         
418                                         add_v3_v3v3(p, p1, p2);
419                                         add_v3_v3(p, p3);
420
421                                         if(newdivs > divs)
422                                                 printf("mem problem\n");
423
424                                         // mMovPoints.push_back(p + trinorm);
425                                         add_v3_v3v3(tmpvec, p, trinorm);
426                                         mul_m4_v3(ob->obmat, tmpvec);
427                                         copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec);
428                                         newdivs++;
429
430                                         if(newdivs > divs)
431                                                 printf("mem problem\n");
432
433                                         // mMovPoints.push_back(p - trinorm);
434                                         copy_v3_v3(tmpvec, p);
435                                         sub_v3_v3(tmpvec, trinorm);
436                                         mul_m4_v3(ob->obmat, tmpvec);
437                                         copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec);
438                                         newdivs++;
439                                 }
440                         }
441
442                         if(again == 0 && mface[i].v4)
443                                 again++;
444                         else
445                                 again = 0;
446
447                         facecounter++;
448
449                 } while(again!=0);
450         }
451
452         scs->numpoints = dm->getNumVerts(dm) + newdivs;
453
454         MEM_freeN(tridivs);
455 }
456
457 /*! init triangle divisions */
458 static void calcTriangleDivs(Object *ob, MVert *verts, int UNUSED(numverts), MFace *faces, int numfaces, int numtris, int **tridivs, float cell_len)
459 {
460         // mTriangleDivs1.resize( faces.size() );
461         // mTriangleDivs2.resize( faces.size() );
462         // mTriangleDivs3.resize( faces.size() );
463
464         size_t i = 0, facecounter = 0;
465         float maxscale[3] = {1,1,1}; // = channelFindMaxVf(mcScale);
466         float maxpart = ABS(maxscale[0]);
467         float scaleFac = 0;
468         float fsTri = 0;
469         if(ABS(maxscale[1])>maxpart) maxpart = ABS(maxscale[1]);
470         if(ABS(maxscale[2])>maxpart) maxpart = ABS(maxscale[2]);
471         scaleFac = 1.0 / maxpart;
472         // featureSize = mLevel[mMaxRefine].nodeSize
473         fsTri = cell_len * 0.5 * scaleFac;
474
475         if(*tridivs)
476                 MEM_freeN(*tridivs);
477
478         *tridivs = MEM_callocN(sizeof(int) * numtris * 3, "Smoke_Tridivs");
479
480         for(i = 0, facecounter = 0; i < numfaces; i++) 
481         {
482                 float p0[3], p1[3], p2[3];
483                 float side1[3];
484                 float side2[3];
485                 float side3[3];
486                 int divs1=0, divs2=0, divs3=0;
487
488                 copy_v3_v3(p0, verts[faces[i].v1].co);
489                 mul_m4_v3(ob->obmat, p0);
490                 copy_v3_v3(p1, verts[faces[i].v2].co);
491                 mul_m4_v3(ob->obmat, p1);
492                 copy_v3_v3(p2, verts[faces[i].v3].co);
493                 mul_m4_v3(ob->obmat, p2);
494
495                 sub_v3_v3v3(side1, p1, p0);
496                 sub_v3_v3v3(side2, p2, p0);
497                 sub_v3_v3v3(side3, p1, p2);
498
499                 if(dot_v3v3(side1, side1) > fsTri*fsTri)
500                 { 
501                         float tmp = normalize_v3(side1);
502                         divs1 = (int)ceil(tmp/fsTri); 
503                 }
504                 if(dot_v3v3(side2, side2) > fsTri*fsTri)
505                 { 
506                         float tmp = normalize_v3(side2);
507                         divs2 = (int)ceil(tmp/fsTri); 
508                         
509                         /*
510                         // debug
511                         if(i==0)
512                                 printf("b tmp: %f, fsTri: %f, divs2: %d\n", tmp, fsTri, divs2);
513                         */
514                 }
515
516                 (*tridivs)[3 * facecounter + 0] = divs1;
517                 (*tridivs)[3 * facecounter + 1] = divs2;
518                 (*tridivs)[3 * facecounter + 2] = divs3;
519
520                 // TODO quad case
521                 if(faces[i].v4)
522                 {
523                         divs1=0, divs2=0, divs3=0;
524
525                         facecounter++;
526                         
527                         copy_v3_v3(p0, verts[faces[i].v3].co);
528                         mul_m4_v3(ob->obmat, p0);
529                         copy_v3_v3(p1, verts[faces[i].v4].co);
530                         mul_m4_v3(ob->obmat, p1);
531                         copy_v3_v3(p2, verts[faces[i].v1].co);
532                         mul_m4_v3(ob->obmat, p2);
533
534                         sub_v3_v3v3(side1, p1, p0);
535                         sub_v3_v3v3(side2, p2, p0);
536                         sub_v3_v3v3(side3, p1, p2);
537
538                         if(dot_v3v3(side1, side1) > fsTri*fsTri)
539                         { 
540                                 float tmp = normalize_v3(side1);
541                                 divs1 = (int)ceil(tmp/fsTri); 
542                         }
543                         if(dot_v3v3(side2, side2) > fsTri*fsTri)
544                         { 
545                                 float tmp = normalize_v3(side2);
546                                 divs2 = (int)ceil(tmp/fsTri); 
547                         }
548
549                         (*tridivs)[3 * facecounter + 0] = divs1;
550                         (*tridivs)[3 * facecounter + 1] = divs2;
551                         (*tridivs)[3 * facecounter + 2] = divs3;
552                 }
553                 facecounter++;
554         }
555 }
556
557 #endif /* WITH_SMOKE */
558
559 static void smokeModifier_freeDomain(SmokeModifierData *smd)
560 {
561         if(smd->domain)
562         {
563                 if(smd->domain->shadow)
564                                 MEM_freeN(smd->domain->shadow);
565                         smd->domain->shadow = NULL;
566
567                 if(smd->domain->fluid)
568                         smoke_free(smd->domain->fluid);
569
570                 if(smd->domain->wt)
571                         smoke_turbulence_free(smd->domain->wt);
572
573                 if(smd->domain->effector_weights)
574                                 MEM_freeN(smd->domain->effector_weights);
575                 smd->domain->effector_weights = NULL;
576
577                 BKE_ptcache_free_list(&(smd->domain->ptcaches[0]));
578                 smd->domain->point_cache[0] = NULL;
579
580                 MEM_freeN(smd->domain);
581                 smd->domain = NULL;
582         }
583 }
584
585 static void smokeModifier_freeFlow(SmokeModifierData *smd)
586 {
587         if(smd->flow)
588         {
589 /*
590                 if(smd->flow->bvh)
591                 {
592                         free_bvhtree_from_mesh(smd->flow->bvh);
593                         MEM_freeN(smd->flow->bvh);
594                 }
595                 smd->flow->bvh = NULL;
596 */
597                 MEM_freeN(smd->flow);
598                 smd->flow = NULL;
599         }
600 }
601
602 static void smokeModifier_freeCollision(SmokeModifierData *smd)
603 {
604         if(smd->coll)
605         {
606                 if(smd->coll->points)
607                 {
608                         MEM_freeN(smd->coll->points);
609                         smd->coll->points = NULL;
610                 }
611
612                 if(smd->coll->bvhtree)
613                 {
614                         BLI_bvhtree_free(smd->coll->bvhtree);
615                         smd->coll->bvhtree = NULL;
616                 }
617
618 #ifdef USE_SMOKE_COLLISION_DM
619                 if(smd->coll->dm)
620                         smd->coll->dm->release(smd->coll->dm);
621                 smd->coll->dm = NULL;
622 #endif
623
624                 MEM_freeN(smd->coll);
625                 smd->coll = NULL;
626         }
627 }
628
629 void smokeModifier_reset_turbulence(struct SmokeModifierData *smd)
630 {
631         if(smd && smd->domain && smd->domain->wt)
632         {
633                 smoke_turbulence_free(smd->domain->wt);
634                 smd->domain->wt = NULL;
635         }
636 }
637
638 void smokeModifier_reset(struct SmokeModifierData *smd)
639 {
640         if(smd)
641         {
642                 if(smd->domain)
643                 {
644                         if(smd->domain->shadow)
645                                 MEM_freeN(smd->domain->shadow);
646                         smd->domain->shadow = NULL;
647
648                         if(smd->domain->fluid)
649                         {
650                                 smoke_free(smd->domain->fluid);
651                                 smd->domain->fluid = NULL;
652                         }
653
654                         smokeModifier_reset_turbulence(smd);
655
656                         smd->time = -1;
657
658                         // printf("reset domain end\n");
659                 }
660                 else if(smd->flow)
661                 {
662                         /*
663                         if(smd->flow->bvh)
664                         {
665                                 free_bvhtree_from_mesh(smd->flow->bvh);
666                                 MEM_freeN(smd->flow->bvh);
667                         }
668                         smd->flow->bvh = NULL;
669                         */
670                 }
671                 else if(smd->coll)
672                 {
673                         if(smd->coll->points)
674                         {
675                                 MEM_freeN(smd->coll->points);
676                                 smd->coll->points = NULL;
677                         }
678
679                         if(smd->coll->bvhtree)
680                         {
681                                 BLI_bvhtree_free(smd->coll->bvhtree);
682                                 smd->coll->bvhtree = NULL;
683                         }
684
685 #ifdef USE_SMOKE_COLLISION_DM
686                         if(smd->coll->dm)
687                                 smd->coll->dm->release(smd->coll->dm);
688                         smd->coll->dm = NULL;
689 #endif
690
691                 }
692         }
693 }
694
695 void smokeModifier_free (SmokeModifierData *smd)
696 {
697         if(smd)
698         {
699                 smokeModifier_freeDomain(smd);
700                 smokeModifier_freeFlow(smd);
701                 smokeModifier_freeCollision(smd);
702         }
703 }
704
705 void smokeModifier_createType(struct SmokeModifierData *smd)
706 {
707         if(smd)
708         {
709                 if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
710                 {
711                         if(smd->domain)
712                                 smokeModifier_freeDomain(smd);
713
714                         smd->domain = MEM_callocN(sizeof(SmokeDomainSettings), "SmokeDomain");
715
716                         smd->domain->smd = smd;
717
718                         smd->domain->point_cache[0] = BKE_ptcache_add(&(smd->domain->ptcaches[0]));
719                         smd->domain->point_cache[0]->flag |= PTCACHE_DISK_CACHE;
720                         smd->domain->point_cache[0]->step = 1;
721
722                         /* Deprecated */
723                         smd->domain->point_cache[1] = NULL;
724                         smd->domain->ptcaches[1].first = smd->domain->ptcaches[1].last = NULL;
725                         /* set some standard values */
726                         smd->domain->fluid = NULL;
727                         smd->domain->wt = NULL;                 
728                         smd->domain->eff_group = NULL;
729                         smd->domain->fluid_group = NULL;
730                         smd->domain->coll_group = NULL;
731                         smd->domain->maxres = 32;
732                         smd->domain->amplify = 1;                       
733                         smd->domain->omega = 1.0;                       
734                         smd->domain->alpha = -0.001;
735                         smd->domain->beta = 0.1;
736                         smd->domain->time_scale = 1.0;
737                         smd->domain->vorticity = 2.0;
738                         smd->domain->border_collisions = 1;             // vertically non-colliding
739                         smd->domain->flags = MOD_SMOKE_DISSOLVE_LOG | MOD_SMOKE_HIGH_SMOOTH;
740                         smd->domain->strength = 2.0;
741                         smd->domain->noise = MOD_SMOKE_NOISEWAVE;
742                         smd->domain->diss_speed = 5;
743                         // init 3dview buffer
744
745                         smd->domain->viewsettings = MOD_SMOKE_VIEW_SHOWBIG;
746                         smd->domain->effector_weights = BKE_add_effector_weights(NULL);
747                 }
748                 else if(smd->type & MOD_SMOKE_TYPE_FLOW)
749                 {
750                         if(smd->flow)
751                                 smokeModifier_freeFlow(smd);
752
753                         smd->flow = MEM_callocN(sizeof(SmokeFlowSettings), "SmokeFlow");
754
755                         smd->flow->smd = smd;
756
757                         /* set some standard values */
758                         smd->flow->density = 1.0;
759                         smd->flow->temp = 1.0;
760                         smd->flow->flags = MOD_SMOKE_FLOW_ABSOLUTE;
761                         smd->flow->vel_multi = 1.0;
762
763                         smd->flow->psys = NULL;
764
765                 }
766                 else if(smd->type & MOD_SMOKE_TYPE_COLL)
767                 {
768                         if(smd->coll)
769                                 smokeModifier_freeCollision(smd);
770
771                         smd->coll = MEM_callocN(sizeof(SmokeCollSettings), "SmokeColl");
772
773                         smd->coll->smd = smd;
774                         smd->coll->points = NULL;
775                         smd->coll->numpoints = 0;
776                         smd->coll->bvhtree = NULL;
777
778 #ifdef USE_SMOKE_COLLISION_DM
779                         smd->coll->dm = NULL;
780 #endif
781                 }
782         }
783 }
784
785 void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData *tsmd)
786 {
787         tsmd->type = smd->type;
788         tsmd->time = smd->time;
789         
790         smokeModifier_createType(tsmd);
791
792         if (tsmd->domain) {
793                 tsmd->domain->maxres = smd->domain->maxres;
794                 tsmd->domain->amplify = smd->domain->amplify;
795                 tsmd->domain->omega = smd->domain->omega;
796                 tsmd->domain->alpha = smd->domain->alpha;
797                 tsmd->domain->beta = smd->domain->beta;
798                 tsmd->domain->flags = smd->domain->flags;
799                 tsmd->domain->strength = smd->domain->strength;
800                 tsmd->domain->noise = smd->domain->noise;
801                 tsmd->domain->diss_speed = smd->domain->diss_speed;
802                 tsmd->domain->viewsettings = smd->domain->viewsettings;
803                 tsmd->domain->fluid_group = smd->domain->fluid_group;
804                 tsmd->domain->coll_group = smd->domain->coll_group;
805                 tsmd->domain->vorticity = smd->domain->vorticity;
806                 tsmd->domain->time_scale = smd->domain->time_scale;
807                 tsmd->domain->border_collisions = smd->domain->border_collisions;
808                 
809                 MEM_freeN(tsmd->domain->effector_weights);
810                 tsmd->domain->effector_weights = MEM_dupallocN(smd->domain->effector_weights);
811         } else if (tsmd->flow) {
812                 tsmd->flow->density = smd->flow->density;
813                 tsmd->flow->temp = smd->flow->temp;
814                 tsmd->flow->psys = smd->flow->psys;
815                 tsmd->flow->type = smd->flow->type;
816                 tsmd->flow->flags = smd->flow->flags;
817                 tsmd->flow->vel_multi = smd->flow->vel_multi;
818         } else if (tsmd->coll) {
819                 ;
820                 /* leave it as initialised, collision settings is mostly caches */
821         }
822 }
823
824 #ifdef WITH_SMOKE
825
826 // forward decleration
827 static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct);
828 static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct);
829
830 static int get_lamp(Scene *scene, float *light)
831 {       
832         Base *base_tmp = NULL;  
833         int found_lamp = 0;
834
835         // try to find a lamp, preferably local
836         for(base_tmp = scene->base.first; base_tmp; base_tmp= base_tmp->next) {
837                 if(base_tmp->object->type == OB_LAMP) {
838                         Lamp *la = base_tmp->object->data;
839
840                         if(la->type == LA_LOCAL) {
841                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
842                                 return 1;
843                         }
844                         else if(!found_lamp) {
845                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
846                                 found_lamp = 1;
847                         }
848                 }
849         }
850
851         return found_lamp;
852 }
853
854 static void smoke_calc_domain(Scene *scene, Object *ob, SmokeModifierData *smd)
855 {
856         SmokeDomainSettings *sds = smd->domain;
857         GroupObject *go = NULL;                 
858         Base *base = NULL;      
859
860         // do collisions, needs to be done before emission, so that smoke isn't emitted inside collision cells
861         if(1)
862         {
863                 Object *otherobj = NULL;
864                 ModifierData *md = NULL;
865
866                 if(sds->coll_group) // we use groups since we have 2 domains
867                         go = sds->coll_group->gobject.first;
868                 else
869                         base = scene->base.first;
870
871                 while(base || go)
872                 {
873                         otherobj = NULL;
874                         if(sds->coll_group) 
875                         {                                               
876                                 if(go->ob)                                                      
877                                         otherobj = go->ob;                                      
878                         }                                       
879                         else                                            
880                                 otherobj = base->object;                                        
881                         if(!otherobj)                                   
882                         {                                               
883                                 if(sds->coll_group)                                                     
884                                         go = go->next;                                          
885                                 else                                                    
886                                         base= base->next;                                               
887                                 continue;                                       
888                         }                       
889                         md = modifiers_findByType(otherobj, eModifierType_Smoke);
890                         
891                         // check for active smoke modifier
892                         if(md && md->mode & (eModifierMode_Realtime | eModifierMode_Render))                                    
893                         {
894                                 SmokeModifierData *smd2 = (SmokeModifierData *)md;
895
896                                 if((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll && smd2->coll->points)
897                                 {
898                                         // we got nice collision object
899                                         SmokeCollSettings *scs = smd2->coll;
900                                         size_t i, j;
901                                         unsigned char *obstacles = smoke_get_obstacle(smd->domain->fluid);
902
903                                         for(i = 0; i < scs->numpoints; i++)
904                                         {
905                                                 int badcell = 0;
906                                                 size_t index = 0;
907                                                 int cell[3];
908
909                                                 // 1. get corresponding cell
910                                                 get_cell(smd->domain->p0, smd->domain->res, smd->domain->dx, &scs->points[3 * i], cell, 0);
911                                         
912                                                 // check if cell is valid (in the domain boundary)
913                                                 for(j = 0; j < 3; j++)
914                                                         if((cell[j] > sds->res[j] - 1) || (cell[j] < 0))
915                                                         {
916                                                                 badcell = 1;
917                                                                 break;
918                                                         }
919                                                                                                                                 
920                                                         if(badcell)                                                                     
921                                                                 continue;
922                                                 // 2. set cell values (heat, density and velocity)
923                                                 index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]);
924                                                                                                                 
925                                                 // printf("cell[0]: %d, cell[1]: %d, cell[2]: %d\n", cell[0], cell[1], cell[2]);                                                                
926                                                 // printf("res[0]: %d, res[1]: %d, res[2]: %d, index: %d\n\n", sds->res[0], sds->res[1], sds->res[2], index);                                                                                                                                   
927                                                 obstacles[index] = 1;
928                                                 // for moving gobstacles                                                                
929                                                 /*
930                                                 const LbmFloat maxVelVal = 0.1666;
931                                                 const LbmFloat maxusqr = maxVelVal*maxVelVal*3. *1.5;
932
933                                                 LbmVec objvel = vec2L((mMOIVertices[n]-mMOIVerticesOld[n]) /dvec); 
934                                                 {                                                               
935                                                 const LbmFloat usqr = (objvel[0]*objvel[0]+objvel[1]*objvel[1]+objvel[2]*objvel[2])*1.5;                                                                
936                                                 USQRMAXCHECK(usqr, objvel[0],objvel[1],objvel[2], mMaxVlen, mMxvx,mMxvy,mMxvz);                                                                 
937                                                 if(usqr>maxusqr) {                                                                      
938                                                 // cutoff at maxVelVal                                                                  
939                                                 for(int jj=0; jj<3; jj++) {                                                                             
940                                                 if(objvel[jj]>0.) objvel[jj] =  maxVelVal;                                                                              
941                                                 if(objvel[jj]<0.) objvel[jj] = -maxVelVal;                                                                      
942                                                 }                                                               
943                                                 } 
944                                                 }                                                               
945                                                 const LbmFloat dp=dot(objvel, vec2L((*pNormals)[n]) );                                                          
946                                                 const LbmVec oldov=objvel; // debug                                                             
947                                                 objvel = vec2L((*pNormals)[n]) *dp;                                                             
948                                                 */
949                                         }
950                                 }
951                         }
952
953                         if(sds->coll_group)
954                                 go = go->next;
955                         else
956                                 base= base->next;
957                 }
958         }
959
960         // do flows and fluids
961         if(1)                   
962         {
963                 Object *otherobj = NULL;                                
964                 ModifierData *md = NULL;
965                 if(sds->fluid_group) // we use groups since we have 2 domains
966                         go = sds->fluid_group->gobject.first;                           
967                 else                                    
968                         base = scene->base.first;
969                 while(base || go)
970                 {                                       
971                         otherobj = NULL;
972                         if(sds->fluid_group) 
973                         {
974                                 if(go->ob)                                                      
975                                         otherobj = go->ob;                                      
976                         }                                       
977                         else                                            
978                                 otherobj = base->object;
979                         if(!otherobj)
980                         {
981                                 if(sds->fluid_group)
982                                         go = go->next;
983                                 else
984                                         base= base->next;
985
986                                 continue;
987                         }
988
989                         md = modifiers_findByType(otherobj, eModifierType_Smoke);
990                         
991                         // check for active smoke modifier
992                         if(md && md->mode & (eModifierMode_Realtime | eModifierMode_Render))
993                         {
994                                 SmokeModifierData *smd2 = (SmokeModifierData *)md;
995                                 
996                                 // check for initialized smoke object
997                                 if((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)                                            
998                                 {
999                                         // we got nice flow object
1000                                         SmokeFlowSettings *sfs = smd2->flow;
1001                                         
1002                                         if(sfs && sfs->psys && sfs->psys->part && sfs->psys->part->type==PART_EMITTER) // is particle system selected
1003                                         {
1004                                                 ParticleSimulationData sim;
1005                                                 ParticleSystem *psys = sfs->psys;
1006                                                 int totpart=psys->totpart, totchild;
1007                                                 int p = 0;                                                              
1008                                                 float *density = smoke_get_density(sds->fluid);                                                         
1009                                                 float *bigdensity = smoke_turbulence_get_density(sds->wt);                                                              
1010                                                 float *heat = smoke_get_heat(sds->fluid);                                                               
1011                                                 float *velocity_x = smoke_get_velocity_x(sds->fluid);                                                           
1012                                                 float *velocity_y = smoke_get_velocity_y(sds->fluid);                                                           
1013                                                 float *velocity_z = smoke_get_velocity_z(sds->fluid);                                                           
1014                                                 unsigned char *obstacle = smoke_get_obstacle(sds->fluid);                                                               
1015                                                 int bigres[3];
1016                                                 short absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE);
1017                                                 short high_emission_smoothing = bigdensity ? (smd->domain->flags & MOD_SMOKE_HIGH_SMOOTH) : 0;
1018
1019                                                 /*
1020                                                 * A temporary volume map used to store whole emissive
1021                                                 * area to be added to smoke density and interpolated
1022                                                 * for high resolution smoke.
1023                                                 */
1024                                                 float *temp_emission_map = NULL;
1025
1026                                                 sim.scene = scene;
1027                                                 sim.ob = otherobj;
1028                                                 sim.psys = psys;
1029
1030                                                 // initialize temp emission map
1031                                                 if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW))
1032                                                 {
1033                                                         int i;
1034                                                         temp_emission_map = MEM_callocN(sizeof(float) * sds->res[0]*sds->res[1]*sds->res[2], "SmokeTempEmission");
1035                                                         // set whole volume to 0.0f
1036                                                         for (i=0; i<sds->res[0]*sds->res[1]*sds->res[2]; i++) {
1037                                                                 temp_emission_map[i] = 0.0f;
1038                                                         }
1039                                                 }
1040                                                                                                                 
1041                                                 // mostly copied from particle code                                                             
1042                                                 if(psys->part->type==PART_HAIR)
1043                                                 {
1044                                                         /*
1045                                                         if(psys->childcache)
1046                                                         {
1047                                                                 totchild = psys->totchildcache;
1048                                                         }
1049                                                         else
1050                                                         */
1051
1052                                                         // TODO: PART_HAIR not supported whatsoever
1053                                                         totchild=0;
1054                                                 }
1055                                                 else
1056                                                         totchild=psys->totchild*psys->part->disp/100;
1057                                                 
1058                                                 for(p=0; p<totpart+totchild; p++)                                                               
1059                                                 {
1060                                                         int cell[3];
1061                                                         size_t i = 0;
1062                                                         size_t index = 0;
1063                                                         int badcell = 0;
1064                                                         ParticleKey state;
1065
1066                                                         if(p < totpart)
1067                                                         {
1068                                                                 if(psys->particles[p].flag & (PARS_NO_DISP|PARS_UNEXIST))
1069                                                                         continue;
1070                                                         }
1071                                                         else {
1072                                                                 /* handle child particle */
1073                                                                 ChildParticle *cpa = &psys->child[p - totpart];
1074                                         
1075                                                                 if(psys->particles[cpa->parent].flag & (PARS_NO_DISP|PARS_UNEXIST))
1076                                                                         continue;
1077                                                         }
1078
1079                                                         state.time = smd->time;
1080                                                         if(psys_get_particle_state(&sim, p, &state, 0) == 0)
1081                                                                 continue;
1082                                                                                                 
1083                                                         // copy_v3_v3(pos, pa->state.co);
1084                                                         // mul_m4_v3(ob->imat, pos);
1085                                                         // 1. get corresponding cell
1086                                                         get_cell(smd->domain->p0, smd->domain->res, smd->domain->dx, state.co, cell, 0);                                                                                                                                        
1087                                                         // check if cell is valid (in the domain boundary)                                                                      
1088                                                         for(i = 0; i < 3; i++)                                                                  
1089                                                         {                                                                               
1090                                                                 if((cell[i] > sds->res[i] - 1) || (cell[i] < 0))                                                                                
1091                                                                 {                                                                                       
1092                                                                         badcell = 1;                                                                                    
1093                                                                         break;                                                                          
1094                                                                 }                                                                       
1095                                                         }                                                                                                                                                       
1096                                                         if(badcell)                                                                             
1097                                                                 continue;                                                                                                                                               
1098                                                         // 2. set cell values (heat, density and velocity)                                                                      
1099                                                         index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]);                                                                                                                                           
1100                                                         if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) && !(obstacle[index])) // this is inflow
1101                                                         {                                                                               
1102                                                                 // heat[index] += sfs->temp * 0.1;                                                                              
1103                                                                 // density[index] += sfs->density * 0.1;
1104                                                                 heat[index] = sfs->temp;
1105                                                                 
1106                                                                 // Add emitter density to temp emission map
1107                                                                 temp_emission_map[index] = sfs->density;
1108
1109                                                                 // Uses particle velocity as initial velocity for smoke
1110                                                                 if(sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
1111                                                                 {
1112                                                                         velocity_x[index] = state.vel[0]*sfs->vel_multi;
1113                                                                         velocity_y[index] = state.vel[1]*sfs->vel_multi;
1114                                                                         velocity_z[index] = state.vel[2]*sfs->vel_multi;
1115                                                                 }                                                                               
1116                                                         }                                                                       
1117                                                         else if(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) // outflow                                                                     
1118                                                         {                                                                               
1119                                                                 heat[index] = 0.f;                                                                              
1120                                                                 density[index] = 0.f;                                                                           
1121                                                                 velocity_x[index] = 0.f;                                                                                
1122                                                                 velocity_y[index] = 0.f;                                                                                
1123                                                                 velocity_z[index] = 0.f;
1124                                                                 // we need different handling for the high-res feature
1125                                                                 if(bigdensity)
1126                                                                 {
1127                                                                         // init all surrounding cells according to amplification, too                                                                                   
1128                                                                         int i, j, k;
1129                                                                         smoke_turbulence_get_res(smd->domain->wt, bigres);
1130
1131                                                                         for(i = 0; i < smd->domain->amplify + 1; i++)
1132                                                                                 for(j = 0; j < smd->domain->amplify + 1; j++)
1133                                                                                         for(k = 0; k < smd->domain->amplify + 1; k++)
1134                                                                                         {                                                                                                               
1135                                                                                                 index = smoke_get_index((smd->domain->amplify + 1)* cell[0] + i, bigres[0], (smd->domain->amplify + 1)* cell[1] + j, bigres[1], (smd->domain->amplify + 1)* cell[2] + k);                                                                                                               
1136                                                                                                 bigdensity[index] = 0.f;                                                                                                        
1137                                                                                         }                                                                               
1138                                                                 }
1139                                                         }
1140                                                         }       // particles loop
1141
1142
1143                                                         // apply emission values
1144                                                         if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW)) {
1145
1146                                                                 // initialize variables
1147                                                                 int ii, jj, kk, x, y, z, block_size;
1148                                                                 size_t index, index_big;
1149
1150                                                                 smoke_turbulence_get_res(smd->domain->wt, bigres);
1151                                                                 block_size = smd->domain->amplify + 1;  // high res block size
1152
1153
1154                                                                         // loop through every low res cell
1155                                                                         for(x = 0; x < sds->res[0]; x++)
1156                                                                                 for(y = 0; y < sds->res[1]; y++)
1157                                                                                         for(z = 0; z < sds->res[2]; z++)                                                                                                        
1158                                                                                         {
1159
1160                                                                                                 // neighbor cell emission densities (for high resolution smoke smooth interpolation)
1161                                                                                                 float c000, c001, c010, c011,  c100, c101, c110, c111;
1162
1163                                                                                                 c000 = (x>0 && y>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z-1)] : 0;
1164                                                                                                 c001 = (x>0 && y>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z)] : 0;
1165                                                                                                 c010 = (x>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z-1)] : 0;
1166                                                                                                 c011 = (x>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z)] : 0;
1167
1168                                                                                                 c100 = (y>0 && z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z-1)] : 0;
1169                                                                                                 c101 = (y>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z)] : 0;
1170                                                                                                 c110 = (z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z-1)] : 0;
1171                                                                                                 c111 = temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z)];                   // this cell
1172
1173
1174
1175                                                                                                 // get cell index
1176                                                                                                 index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
1177
1178                                                                                                 // add emission to low resolution density
1179                                                                                                 if (absolute_flow) {if (temp_emission_map[index]>0) density[index] = temp_emission_map[index];}
1180                                                                                                 else {
1181                                                                                                         density[index] += temp_emission_map[index];
1182                                                                                                         if (density[index]>1) density[index]=1.0f;
1183                                                                                                 }
1184
1185                                                                                                 smoke_turbulence_get_res(smd->domain->wt, bigres);
1186
1187
1188
1189                                                                                                 /*
1190                                                                                                 loop through high res blocks if high res enabled
1191                                                                                                 */
1192                                                                                                 if (bigdensity)
1193                                                                                                 for(ii = 0; ii < block_size; ii++)
1194                                                                                                         for(jj = 0; jj < block_size; jj++)
1195                                                                                                                 for(kk = 0; kk < block_size; kk++)                                                                                                      
1196                                                                                                                 {
1197
1198                                                                                                                 float fx,fy,fz, interpolated_value;
1199                                                                                                                 int shift_x, shift_y, shift_z;
1200
1201
1202                                                                                                                 /*
1203                                                                                                                 * Do volume interpolation if emitter smoothing
1204                                                                                                                 * is enabled
1205                                                                                                                 */
1206                                                                                                                 if (high_emission_smoothing) {
1207                                                                                                                         // convert block position to relative
1208                                                                                                                         // for interpolation smoothing
1209                                                                                                                         fx = (float)ii/block_size + 0.5f/block_size;
1210                                                                                                                         fy = (float)jj/block_size + 0.5f/block_size;
1211                                                                                                                         fz = (float)kk/block_size + 0.5f/block_size;
1212
1213                                                                                                                         // calculate trilinear interpolation
1214                                                                                                                         interpolated_value = c000 * (1-fx) * (1-fy) * (1-fz) +
1215                                                                                                                         c100 * fx * (1-fy) * (1-fz) +
1216                                                                                                                         c010 * (1-fx) * fy * (1-fz) +
1217                                                                                                                         c001 * (1-fx) * (1-fy) * fz +
1218                                                                                                                         c101 * fx * (1-fy) * fz +
1219                                                                                                                         c011 * (1-fx) * fy * fz +
1220                                                                                                                         c110 * fx * fy * (1-fz) +
1221                                                                                                                         c111 * fx * fy * fz;
1222
1223
1224                                                                                                                         // add some contrast / sharpness
1225                                                                                                                         // depending on hi-res block size
1226
1227                                                                                                                         interpolated_value = (interpolated_value-0.4f*sfs->density)*(block_size/2) + 0.4f*sfs->density;
1228                                                                                                                         if (interpolated_value<0.0f) interpolated_value = 0.0f;
1229                                                                                                                         if (interpolated_value>1.0f) interpolated_value = 1.0f;
1230
1231                                                                                                                         // shift smoke block index
1232                                                                                                                         // (because pixel center is actually
1233                                                                                                                         // in halfway of the low res block)
1234                                                                                                                         shift_x = (x < 1) ? 0 : block_size/2;
1235                                                                                                                         shift_y = (y < 1) ? 0 : block_size/2;
1236                                                                                                                         shift_z = (z < 1) ? 0 : block_size/2;
1237                                                                                                                 }
1238                                                                                                                 else {
1239                                                                                                                         // without interpolation use same low resolution
1240                                                                                                                         // block value for all hi-res blocks
1241                                                                                                                         interpolated_value = c111;
1242                                                                                                                         shift_x = 0;
1243                                                                                                                         shift_y = 0;
1244                                                                                                                         shift_z = 0;
1245                                                                                                                 }
1246
1247                                                                                                                 // get shifted index for current high resolution block
1248                                                                                                                 index_big = smoke_get_index(block_size * x + ii - shift_x, bigres[0], block_size * y + jj - shift_y, bigres[1], block_size * z + kk - shift_z);                                                                                                         
1249                                                                                                                 
1250                                                                                                                 // add emission data to high resolution density
1251                                                                                                                 if (absolute_flow) {if (interpolated_value > 0) bigdensity[index_big] = interpolated_value;}
1252                                                                                                                 else {
1253                                                                                                                         bigdensity[index_big] += interpolated_value;
1254                                                                                                                         if (bigdensity[index_big]>1) bigdensity[index_big]=1.0f;
1255                                                                                                                 }
1256
1257                                                                                                                 } // end of hires loop
1258
1259                                                                         }       // end of low res loop
1260
1261                                                                 // free temporary emission map
1262                                                         if (temp_emission_map) MEM_freeN(temp_emission_map);
1263
1264                                                         }       // end emission
1265
1266
1267                                                                                 
1268                                 }                                                       
1269                                 else {                                                          
1270                                         /*                                                              
1271                                         for()                                                           
1272                                         {                                                                       
1273                                                 // no psys                                                                      
1274                                                 BVHTreeNearest nearest;
1275                                                 nearest.index = -1;
1276                                                 nearest.dist = FLT_MAX;
1277
1278                                                 BLI_bvhtree_find_nearest(sfs->bvh->tree, pco, &nearest, sfs->bvh->nearest_callback, sfs->bvh);
1279                                         }*/                                                     
1280                                 }
1281                         }                                               
1282                 }
1283                         if(sds->fluid_group)
1284                                 go = go->next;
1285                         else
1286                                 base= base->next;
1287                 }
1288         }
1289
1290         // do effectors
1291         {
1292                 ListBase *effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights);
1293
1294                 if(effectors)
1295                 {
1296                         float *density = smoke_get_density(sds->fluid);
1297                         float *force_x = smoke_get_force_x(sds->fluid);
1298                         float *force_y = smoke_get_force_y(sds->fluid);
1299                         float *force_z = smoke_get_force_z(sds->fluid);
1300                         float *velocity_x = smoke_get_velocity_x(sds->fluid);
1301                         float *velocity_y = smoke_get_velocity_y(sds->fluid);
1302                         float *velocity_z = smoke_get_velocity_z(sds->fluid);
1303                         int x, y, z;
1304
1305                         // precalculate wind forces
1306                         for(x = 0; x < sds->res[0]; x++)
1307                                 for(y = 0; y < sds->res[1]; y++)
1308                                         for(z = 0; z < sds->res[2]; z++)
1309                         {       
1310                                 EffectedPoint epoint;
1311                                 float voxelCenter[3] = {0,0,0} , vel[3] = {0,0,0} , retvel[3] = {0,0,0};
1312                                 unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
1313
1314                                 if(density[index] < FLT_EPSILON)                                        
1315                                         continue;       
1316
1317                                 vel[0] = velocity_x[index];
1318                                 vel[1] = velocity_y[index];
1319                                 vel[2] = velocity_z[index];
1320
1321                                 voxelCenter[0] = sds->p0[0] + sds->dx *  x + sds->dx * 0.5;
1322                                 voxelCenter[1] = sds->p0[1] + sds->dx *  y + sds->dx * 0.5;
1323                                 voxelCenter[2] = sds->p0[2] + sds->dx *  z + sds->dx * 0.5;
1324
1325                                 pd_point_from_loc(scene, voxelCenter, vel, index, &epoint);
1326                                 pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
1327
1328                                 // TODO dg - do in force!
1329                                 force_x[index] = MIN2(MAX2(-1.0, retvel[0] * 0.2), 1.0); 
1330                                 force_y[index] = MIN2(MAX2(-1.0, retvel[1] * 0.2), 1.0); 
1331                                 force_z[index] = MIN2(MAX2(-1.0, retvel[2] * 0.2), 1.0);
1332                         }
1333                 }
1334
1335                 pdEndEffectors(&effectors);
1336         }
1337
1338 }
1339 void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm)
1340 {       
1341         if((smd->type & MOD_SMOKE_TYPE_FLOW))
1342         {
1343                 if(scene->r.cfra >= smd->time)
1344                         smokeModifier_init(smd, ob, scene, dm);
1345
1346                 if(scene->r.cfra > smd->time)
1347                 {
1348                         // XXX TODO
1349                         smd->time = scene->r.cfra;
1350
1351                         // rigid movement support
1352                         /*
1353                         copy_m4_m4(smd->flow->mat_old, smd->flow->mat);
1354                         copy_m4_m4(smd->flow->mat, ob->obmat);
1355                         */
1356                 }
1357                 else if(scene->r.cfra < smd->time)
1358                 {
1359                         smd->time = scene->r.cfra;
1360                         smokeModifier_reset(smd);
1361                 }
1362         }
1363         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1364         {
1365                 if(scene->r.cfra >= smd->time)
1366                         smokeModifier_init(smd, ob, scene, dm);
1367
1368                 if(scene->r.cfra > smd->time)
1369                 {
1370                         // XXX TODO
1371                         smd->time = scene->r.cfra;
1372
1373 #ifdef USE_SMOKE_COLLISION_DM
1374                         if(smd->coll->dm)
1375                                 smd->coll->dm->release(smd->coll->dm);
1376
1377                         smd->coll->dm = CDDM_copy_from_tessface(dm);
1378 #endif
1379
1380                         // rigid movement support
1381                         copy_m4_m4(smd->coll->mat_old, smd->coll->mat);
1382                         copy_m4_m4(smd->coll->mat, ob->obmat);
1383                 }
1384                 else if(scene->r.cfra < smd->time)
1385                 {
1386                         smd->time = scene->r.cfra;
1387                         smokeModifier_reset(smd);
1388                 }
1389         }
1390         else if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1391         {
1392                 SmokeDomainSettings *sds = smd->domain;
1393                 float light[3]; 
1394                 PointCache *cache = NULL;
1395                 PTCacheID pid;
1396                 int startframe, endframe, framenr;
1397                 float timescale;
1398
1399                 framenr = scene->r.cfra;
1400
1401                 //printf("time: %d\n", scene->r.cfra);
1402
1403                 cache = sds->point_cache[0];
1404                 BKE_ptcache_id_from_smoke(&pid, ob, smd);
1405                 BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
1406
1407                 if(!smd->domain->fluid || framenr == startframe)
1408                 {
1409                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1410                         BKE_ptcache_validate(cache, framenr);
1411                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1412                 }
1413
1414                 if(!smd->domain->fluid && (framenr != startframe) && (smd->domain->flags & MOD_SMOKE_FILE_LOAD)==0 && (cache->flag & PTCACHE_BAKED)==0)
1415                         return;
1416
1417                 smd->domain->flags &= ~MOD_SMOKE_FILE_LOAD;
1418
1419                 CLAMP(framenr, startframe, endframe);
1420
1421                 /* If already viewing a pre/after frame, no need to reload */
1422                 if ((smd->time == framenr) && (framenr != scene->r.cfra))
1423                         return;
1424
1425                 // printf("startframe: %d, framenr: %d\n", startframe, framenr);
1426
1427                 if(smokeModifier_init(smd, ob, scene, dm)==0)
1428                 {
1429                         printf("bad smokeModifier_init\n");
1430                         return;
1431                 }
1432
1433                 /* try to read from cache */
1434                 if(BKE_ptcache_read(&pid, (float)framenr) == PTCACHE_READ_EXACT) {
1435                         BKE_ptcache_validate(cache, framenr);
1436                         smd->time = framenr;
1437                         return;
1438                 }
1439                 
1440                 /* only calculate something when we advanced a single frame */
1441                 if(framenr != (int)smd->time+1)
1442                         return;
1443
1444                 /* don't simulate if viewing start frame, but scene frame is not real start frame */
1445                 if (framenr != scene->r.cfra)
1446                         return;
1447
1448                 tstart();
1449
1450                 smoke_calc_domain(scene, ob, smd);
1451
1452                 /* if on second frame, write cache for first frame */
1453                 if((int)smd->time == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0)) {
1454                         // create shadows straight after domain initialization so we get nice shadows for startframe, too
1455                         if(get_lamp(scene, light))
1456                                 smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx);
1457
1458                         if(sds->wt)
1459                         {
1460                                 if(sds->flags & MOD_SMOKE_DISSOLVE)
1461                                         smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1462                                 smoke_turbulence_step(sds->wt, sds->fluid);
1463                         }
1464
1465                         BKE_ptcache_write(&pid, startframe);
1466                 }
1467                 
1468                 // set new time
1469                 smd->time = scene->r.cfra;
1470
1471                 /* do simulation */
1472
1473                 // low res
1474
1475                 // simulate the actual smoke (c++ code in intern/smoke)
1476                 // DG: interesting commenting this line + deactivating loading of noise files
1477                 if(framenr!=startframe)
1478                 {
1479                         if(sds->flags & MOD_SMOKE_DISSOLVE)
1480                                 smoke_dissolve(sds->fluid, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1481                         smoke_step(sds->fluid, smd->time, scene->r.frs_sec / scene->r.frs_sec_base);
1482                 }
1483
1484                 // create shadows before writing cache so they get stored
1485                 if(get_lamp(scene, light))
1486                         smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx);
1487
1488                 if(sds->wt)
1489                 {
1490                         if(sds->flags & MOD_SMOKE_DISSOLVE)
1491                                 smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1492                         smoke_turbulence_step(sds->wt, sds->fluid);
1493                 }
1494         
1495                 BKE_ptcache_validate(cache, framenr);
1496                 if(framenr != startframe)
1497                         BKE_ptcache_write(&pid, framenr);
1498
1499                 tend();
1500                 //printf ( "Frame: %d, Time: %f\n", (int)smd->time, ( float ) tval() );
1501         }
1502 }
1503
1504 static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct)
1505 {
1506         const size_t index = smoke_get_index(pixel[0], res[0], pixel[1], res[1], pixel[2]);
1507
1508         // T_ray *= T_vox
1509         *tRay *= exp(input[index]*correct);
1510         
1511         if(result[index] < 0.0f)        
1512         {
1513 #pragma omp critical            
1514                 result[index] = *tRay;  
1515         }       
1516
1517         return *tRay;
1518 }
1519
1520 long long smoke_get_mem_req(int xres, int yres, int zres, int amplify)
1521 {
1522         int totalCells = xres * yres * zres;
1523         int amplifiedCells = totalCells * amplify * amplify * amplify;
1524
1525         // print out memory requirements
1526         long long int coarseSize = sizeof(float) * totalCells * 22 +
1527         sizeof(unsigned char) * totalCells;
1528
1529         long long int fineSize = sizeof(float) * amplifiedCells * 7 + // big grids
1530         sizeof(float) * totalCells * 8 +     // small grids
1531         sizeof(float) * 128 * 128 * 128;     // noise tile
1532
1533         long long int totalMB = (coarseSize + fineSize) / (1024 * 1024);
1534
1535         return totalMB;
1536 }
1537
1538 static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, float *tRay, bresenham_callback cb, float *result, float *input, int res[3], float correct)
1539 {
1540         int dx, dy, dz, i, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2;
1541         int pixel[3];
1542
1543         pixel[0] = x1;
1544         pixel[1] = y1;
1545         pixel[2] = z1;
1546
1547         dx = x2 - x1;
1548         dy = y2 - y1;
1549         dz = z2 - z1;
1550
1551         x_inc = (dx < 0) ? -1 : 1;
1552         l = abs(dx);
1553         y_inc = (dy < 0) ? -1 : 1;
1554         m = abs(dy);
1555         z_inc = (dz < 0) ? -1 : 1;
1556         n = abs(dz);
1557         dx2 = l << 1;
1558         dy2 = m << 1;
1559         dz2 = n << 1;
1560
1561         if ((l >= m) && (l >= n)) {
1562                 err_1 = dy2 - l;
1563                 err_2 = dz2 - l;
1564                 for (i = 0; i < l; i++) {
1565                         if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1566                                 break;
1567                         if (err_1 > 0) {
1568                                 pixel[1] += y_inc;
1569                                 err_1 -= dx2;
1570                         }
1571                         if (err_2 > 0) {
1572                                 pixel[2] += z_inc;
1573                                 err_2 -= dx2;
1574                         }
1575                         err_1 += dy2;
1576                         err_2 += dz2;
1577                         pixel[0] += x_inc;
1578                 }
1579         } else if ((m >= l) && (m >= n)) {
1580                 err_1 = dx2 - m;
1581                 err_2 = dz2 - m;
1582                 for (i = 0; i < m; i++) {
1583                         if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1584                                 break;
1585                         if (err_1 > 0) {
1586                                 pixel[0] += x_inc;
1587                                 err_1 -= dy2;
1588                         }
1589                         if (err_2 > 0) {
1590                                 pixel[2] += z_inc;
1591                                 err_2 -= dy2;
1592                         }
1593                         err_1 += dx2;
1594                         err_2 += dz2;
1595                         pixel[1] += y_inc;
1596                 }
1597         } else {
1598                 err_1 = dy2 - n;
1599                 err_2 = dx2 - n;
1600                 for (i = 0; i < n; i++) {
1601                         if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1602                                 break;
1603                         if (err_1 > 0) {
1604                                 pixel[1] += y_inc;
1605                                 err_1 -= dz2;
1606                         }
1607                         if (err_2 > 0) {
1608                                 pixel[0] += x_inc;
1609                                 err_2 -= dz2;
1610                         }
1611                         err_1 += dy2;
1612                         err_2 += dx2;
1613                         pixel[2] += z_inc;
1614                 }
1615         }
1616         cb(result, input, res, pixel, tRay, correct);
1617 }
1618
1619 static void get_cell(float *p0, int res[3], float dx, float *pos, int *cell, int correct)
1620 {
1621         float tmp[3];
1622
1623         sub_v3_v3v3(tmp, pos, p0);
1624         mul_v3_fl(tmp, 1.0 / dx);
1625
1626         if (correct) {
1627                 cell[0] = MIN2(res[0] - 1, MAX2(0, (int)floor(tmp[0])));
1628                 cell[1] = MIN2(res[1] - 1, MAX2(0, (int)floor(tmp[1])));
1629                 cell[2] = MIN2(res[2] - 1, MAX2(0, (int)floor(tmp[2])));
1630         }
1631         else {
1632                 cell[0] = (int)floor(tmp[0]);
1633                 cell[1] = (int)floor(tmp[1]);
1634                 cell[2] = (int)floor(tmp[2]);
1635         }
1636 }
1637
1638 static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct)
1639 {
1640         float bv[6];
1641         int a, z, slabsize=res[0]*res[1], size= res[0]*res[1]*res[2];
1642
1643         for(a=0; a<size; a++)
1644                 result[a]= -1.0f;
1645
1646         bv[0] = p0[0];
1647         bv[1] = p1[0];
1648         // y
1649         bv[2] = p0[1];
1650         bv[3] = p1[1];
1651         // z
1652         bv[4] = p0[2];
1653         bv[5] = p1[2];
1654
1655 #pragma omp parallel for schedule(static,1)
1656         for(z = 0; z < res[2]; z++)
1657         {
1658                 size_t index = z*slabsize;
1659                 int x,y;
1660
1661                 for(y = 0; y < res[1]; y++)
1662                         for(x = 0; x < res[0]; x++, index++)
1663                         {
1664                                 float voxelCenter[3];
1665                                 float pos[3];
1666                                 int cell[3];
1667                                 float tRay = 1.0;
1668
1669                                 if(result[index] >= 0.0f)                                       
1670                                         continue;                                                               
1671                                 voxelCenter[0] = p0[0] + dx *  x + dx * 0.5;
1672                                 voxelCenter[1] = p0[1] + dx *  y + dx * 0.5;
1673                                 voxelCenter[2] = p0[2] + dx *  z + dx * 0.5;
1674
1675                                 // get starting position (in voxel coords)
1676                                 if(BLI_bvhtree_bb_raycast(bv, light, voxelCenter, pos) > FLT_EPSILON)
1677                                 {
1678                                         // we're ouside
1679                                         get_cell(p0, res, dx, pos, cell, 1);
1680                                 }
1681                                 else {
1682                                         // we're inside
1683                                         get_cell(p0, res, dx, light, cell, 1);
1684                                 }
1685
1686                                 bresenham_linie_3D(cell[0], cell[1], cell[2], x, y, z, &tRay, cb, result, input, res, correct);
1687
1688                                 // convention -> from a RGBA float array, use G value for tRay
1689 // #pragma omp critical
1690                                 result[index] = tRay;                   
1691                         }
1692         }
1693 }
1694
1695 #endif /* WITH_SMOKE */