Cleanup: shadowing (blenkernel)
[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  *                 Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/blenkernel/intern/smoke.c
30  *  \ingroup bke
31  */
32
33
34 /* Part of the code copied from elbeem fluid library, copyright by Nils Thuerey */
35
36 #include "MEM_guardedalloc.h"
37
38 #include <float.h>
39 #include <math.h>
40 #include <stdio.h>
41 #include <string.h> /* memset */
42
43 #include "BLI_blenlib.h"
44 #include "BLI_math.h"
45 #include "BLI_kdtree.h"
46 #include "BLI_kdopbvh.h"
47 #include "BLI_threads.h"
48 #include "BLI_utildefines.h"
49 #include "BLI_voxel.h"
50
51 #include "DNA_anim_types.h"
52 #include "DNA_armature_types.h"
53 #include "DNA_constraint_types.h"
54 #include "DNA_customdata_types.h"
55 #include "DNA_lamp_types.h"
56 #include "DNA_meshdata_types.h"
57 #include "DNA_modifier_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_particle_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_smoke_types.h"
62
63 #include "BKE_appdir.h"
64 #include "BKE_animsys.h"
65 #include "BKE_armature.h"
66 #include "BKE_bvhutils.h"
67 #include "BKE_cdderivedmesh.h"
68 #include "BKE_collision.h"
69 #include "BKE_colortools.h"
70 #include "BKE_constraint.h"
71 #include "BKE_customdata.h"
72 #include "BKE_deform.h"
73 #include "BKE_DerivedMesh.h"
74 #include "BKE_global.h"
75 #include "BKE_effect.h"
76 #include "BKE_main.h"
77 #include "BKE_modifier.h"
78 #include "BKE_object.h"
79 #include "BKE_particle.h"
80 #include "BKE_pointcache.h"
81 #include "BKE_scene.h"
82 #include "BKE_smoke.h"
83 #include "BKE_texture.h"
84
85 #include "RE_shader_ext.h"
86
87 #include "GPU_glew.h"
88
89 /* UNUSED so far, may be enabled later */
90 /* #define USE_SMOKE_COLLISION_DM */
91
92 #include "smoke_API.h"
93
94 #ifdef WITH_SMOKE
95
96 static ThreadMutex object_update_lock = BLI_MUTEX_INITIALIZER;
97
98 #ifdef _WIN32
99 #include <time.h>
100 #include <stdio.h>
101 #include <conio.h>
102 #include <windows.h>
103
104 static LARGE_INTEGER liFrequency;
105 static LARGE_INTEGER liStartTime;
106 static LARGE_INTEGER liCurrentTime;
107
108 static void tstart(void)
109 {
110         QueryPerformanceFrequency(&liFrequency);
111         QueryPerformanceCounter(&liStartTime);
112 }
113 static void tend(void)
114 {
115         QueryPerformanceCounter(&liCurrentTime);
116 }
117 static double UNUSED_FUNCTION(tval) (void)
118 {
119         return ((double)( (liCurrentTime.QuadPart - liStartTime.QuadPart) * (double)1000.0 / (double)liFrequency.QuadPart));
120 }
121 #else
122 #include <sys/time.h>
123 static struct timeval _tstart, _tend;
124 static struct timezone tz;
125 static void tstart(void)
126 {
127         gettimeofday(&_tstart, &tz);
128 }
129 static void tend(void)
130 {
131         gettimeofday(&_tend, &tz);
132 }
133
134 static double UNUSED_FUNCTION(tval) (void)
135 {
136         double t1, t2;
137         t1 = ( double ) _tstart.tv_sec * 1000 + ( double ) _tstart.tv_usec / (1000);
138         t2 = ( double ) _tend.tv_sec * 1000 + ( double ) _tend.tv_usec / (1000);
139         return t2 - t1;
140 }
141 #endif
142
143 struct Object;
144 struct Scene;
145 struct DerivedMesh;
146 struct SmokeModifierData;
147
148 // timestep default value for nice appearance 0.1f
149 #define DT_DEFAULT 0.1f
150
151 #define ADD_IF_LOWER_POS(a, b) (min_ff((a) + (b), max_ff((a), (b))))
152 #define ADD_IF_LOWER_NEG(a, b) (max_ff((a) + (b), min_ff((a), (b))))
153 #define ADD_IF_LOWER(a, b) (((b) > 0) ? ADD_IF_LOWER_POS((a), (b)) : ADD_IF_LOWER_NEG((a), (b)))
154
155 #else /* WITH_SMOKE */
156
157 /* Stubs to use when smoke is disabled */
158 struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype), const char *UNUSED(noisefile_path), int UNUSED(use_fire), int UNUSED(use_colors)) { return NULL; }
159 //struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(dx), float *UNUSED(dtdef), int UNUSED(use_heat), int UNUSED(use_fire), int UNUSED(use_colors)) { return NULL; }
160 void smoke_free(struct FLUID_3D *UNUSED(fluid)) {}
161 float *smoke_get_density(struct FLUID_3D *UNUSED(fluid)) { return NULL; }
162 void smoke_turbulence_free(struct WTURBULENCE *UNUSED(wt)) {}
163 void smoke_initWaveletBlenderRNA(struct WTURBULENCE *UNUSED(wt), float *UNUSED(strength)) {}
164 void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity),
165                           int *UNUSED(border_colli), float *UNUSED(burning_rate), float *UNUSED(flame_smoke), float *UNUSED(flame_smoke_color),
166                           float *UNUSED(flame_vorticity), float *UNUSED(flame_ignition_temp), float *UNUSED(flame_max_temp)) {}
167 struct DerivedMesh *smokeModifier_do(SmokeModifierData *UNUSED(smd), Scene *UNUSED(scene), Object *UNUSED(ob), DerivedMesh *UNUSED(dm), bool UNUSED(for_render)) { return NULL; }
168 float smoke_get_velocity_at(struct Object *UNUSED(ob), float UNUSED(position[3]), float UNUSED(velocity[3])) { return 0.0f; }
169 void flame_get_spectrum(unsigned char *UNUSED(spec), int UNUSED(width), float UNUSED(t1), float UNUSED(t2)) {}
170
171 #endif /* WITH_SMOKE */
172
173 #ifdef WITH_SMOKE
174
175 void smoke_reallocate_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old)
176 {
177         int use_heat = (sds->active_fields & SM_ACTIVE_HEAT);
178         int use_fire = (sds->active_fields & SM_ACTIVE_FIRE);
179         int use_colors = (sds->active_fields & SM_ACTIVE_COLORS);
180
181         if (free_old && sds->fluid)
182                 smoke_free(sds->fluid);
183         if (!min_iii(res[0], res[1], res[2])) {
184                 sds->fluid = NULL;
185                 return;
186         }
187         sds->fluid = smoke_init(res, dx, DT_DEFAULT, use_heat, use_fire, use_colors);
188         smoke_initBlenderRNA(sds->fluid, &(sds->alpha), &(sds->beta), &(sds->time_scale), &(sds->vorticity), &(sds->border_collisions),
189                              &(sds->burning_rate), &(sds->flame_smoke), sds->flame_smoke_color, &(sds->flame_vorticity), &(sds->flame_ignition), &(sds->flame_max_temp));
190
191         /* reallocate shadow buffer */
192         if (sds->shadow)
193                 MEM_freeN(sds->shadow);
194         sds->shadow = MEM_callocN(sizeof(float) * res[0] * res[1] * res[2], "SmokeDomainShadow");
195 }
196
197 void smoke_reallocate_highres_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old)
198 {
199         int use_fire = (sds->active_fields & (SM_ACTIVE_HEAT | SM_ACTIVE_FIRE));
200         int use_colors = (sds->active_fields & SM_ACTIVE_COLORS);
201
202         if (free_old && sds->wt)
203                 smoke_turbulence_free(sds->wt);
204         if (!min_iii(res[0], res[1], res[2])) {
205                 sds->wt = NULL;
206                 return;
207         }
208
209         /* smoke_turbulence_init uses non-threadsafe functions from fftw3 lib (like fftw_plan & co). */
210         BLI_lock_thread(LOCK_FFTW);
211
212         sds->wt = smoke_turbulence_init(res, sds->amplify + 1, sds->noise, BKE_tempdir_session(), use_fire, use_colors);
213
214         BLI_unlock_thread(LOCK_FFTW);
215
216         sds->res_wt[0] = res[0] * (sds->amplify + 1);
217         sds->res_wt[1] = res[1] * (sds->amplify + 1);
218         sds->res_wt[2] = res[2] * (sds->amplify + 1);
219         sds->dx_wt = dx / (sds->amplify + 1);
220         smoke_initWaveletBlenderRNA(sds->wt, &(sds->strength));
221 }
222
223 /* convert global position to domain cell space */
224 static void smoke_pos_to_cell(SmokeDomainSettings *sds, float pos[3])
225 {
226         mul_m4_v3(sds->imat, pos);
227         sub_v3_v3(pos, sds->p0);
228         pos[0] *= 1.0f / sds->cell_size[0];
229         pos[1] *= 1.0f / sds->cell_size[1];
230         pos[2] *= 1.0f / sds->cell_size[2];
231 }
232
233 /* set domain transformations and base resolution from object derivedmesh */
234 static void smoke_set_domain_from_derivedmesh(SmokeDomainSettings *sds, Object *ob, DerivedMesh *dm, bool init_resolution)
235 {
236         size_t i;
237         float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
238         float size[3];
239         MVert *verts = dm->getVertArray(dm);
240         float scale = 0.0;
241         int res;
242
243         res = sds->maxres;
244
245         // get BB of domain
246         for (i = 0; i < dm->getNumVerts(dm); i++)
247         {
248                 // min BB
249                 min[0] = MIN2(min[0], verts[i].co[0]);
250                 min[1] = MIN2(min[1], verts[i].co[1]);
251                 min[2] = MIN2(min[2], verts[i].co[2]);
252
253                 // max BB
254                 max[0] = MAX2(max[0], verts[i].co[0]);
255                 max[1] = MAX2(max[1], verts[i].co[1]);
256                 max[2] = MAX2(max[2], verts[i].co[2]);
257         }
258
259         /* set domain bounds */
260         copy_v3_v3(sds->p0, min);
261         copy_v3_v3(sds->p1, max);
262         sds->dx = 1.0f / res;
263
264         /* calculate domain dimensions */
265         sub_v3_v3v3(size, max, min);
266         if (init_resolution) {
267                 zero_v3_int(sds->base_res);
268                 copy_v3_v3(sds->cell_size, size);
269         }
270         /* apply object scale */
271         for (i = 0; i < 3; i++) {
272                 size[i] = fabsf(size[i] * ob->size[i]);
273         }
274         copy_v3_v3(sds->global_size, size);
275         copy_v3_v3(sds->dp0, min);
276
277         invert_m4_m4(sds->imat, ob->obmat);
278
279         // prevent crash when initializing a plane as domain
280         if (!init_resolution || (size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON))
281                 return;
282
283         /* define grid resolutions from longest domain side */
284         if (size[0] >= MAX2(size[1], size[2])) {
285                 scale = res / size[0];
286                 sds->scale = size[0] / fabsf(ob->size[0]);
287                 sds->base_res[0] = res;
288                 sds->base_res[1] = (int)(size[1] * scale + 0.5f);
289                 sds->base_res[2] = (int)(size[2] * scale + 0.5f);
290         }
291         else if (size[1] >= MAX2(size[0], size[2])) {
292                 scale = res / size[1];
293                 sds->scale = size[1] / fabsf(ob->size[1]);
294                 sds->base_res[0] = (int)(size[0] * scale + 0.5f);
295                 sds->base_res[1] = res;
296                 sds->base_res[2] = (int)(size[2] * scale + 0.5f);
297         }
298         else {
299                 scale = res / size[2];
300                 sds->scale = size[2] / fabsf(ob->size[2]);
301                 sds->base_res[0] = (int)(size[0] * scale + 0.5f);
302                 sds->base_res[1] = (int)(size[1] * scale + 0.5f);
303                 sds->base_res[2] = res;
304         }
305
306         /* set cell size */
307         sds->cell_size[0] /= (float)sds->base_res[0];
308         sds->cell_size[1] /= (float)sds->base_res[1];
309         sds->cell_size[2] /= (float)sds->base_res[2];
310 }
311
312 static int smokeModifier_init(SmokeModifierData *smd, Object *ob, Scene *scene, DerivedMesh *dm)
313 {
314         if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid)
315         {
316                 SmokeDomainSettings *sds = smd->domain;
317                 int res[3];
318                 /* set domain dimensions from derivedmesh */
319                 smoke_set_domain_from_derivedmesh(sds, ob, dm, true);
320                 /* reset domain values */
321                 zero_v3_int(sds->shift);
322                 zero_v3(sds->shift_f);
323                 add_v3_fl(sds->shift_f, 0.5f);
324                 zero_v3(sds->prev_loc);
325                 mul_m4_v3(ob->obmat, sds->prev_loc);
326
327                 /* set resolutions */
328                 if (smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
329                         res[0] = res[1] = res[2] = 1; /* use minimum res for adaptive init */
330                 }
331                 else {
332                         VECCOPY(res, sds->base_res);
333                 }
334                 VECCOPY(sds->res, res);
335                 sds->total_cells = sds->res[0] * sds->res[1] * sds->res[2];
336                 sds->res_min[0] = sds->res_min[1] = sds->res_min[2] = 0;
337                 VECCOPY(sds->res_max, res);
338
339                 /* allocate fluid */
340                 smoke_reallocate_fluid(sds, sds->dx, sds->res, 0);
341
342                 smd->time = scene->r.cfra;
343
344                 /* allocate highres fluid */
345                 if (sds->flags & MOD_SMOKE_HIGHRES) {
346                         smoke_reallocate_highres_fluid(sds, sds->dx, sds->res, 0);
347                 }
348                 /* allocate shadow buffer */
349                 if (!sds->shadow)
350                         sds->shadow = MEM_callocN(sizeof(float) * sds->res[0] * sds->res[1] * sds->res[2], "SmokeDomainShadow");
351
352                 return 1;
353         }
354         else if ((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
355         {
356                 smd->time = scene->r.cfra;
357
358                 return 1;
359         }
360         else if ((smd->type & MOD_SMOKE_TYPE_COLL))
361         {
362                 if (!smd->coll)
363                 {
364                         smokeModifier_createType(smd);
365                 }
366
367                 smd->time = scene->r.cfra;
368
369                 return 1;
370         }
371
372         return 2;
373 }
374
375 #endif /* WITH_SMOKE */
376
377 static void smokeModifier_freeDomain(SmokeModifierData *smd)
378 {
379         if (smd->domain)
380         {
381                 if (smd->domain->shadow)
382                         MEM_freeN(smd->domain->shadow);
383                 smd->domain->shadow = NULL;
384
385                 if (smd->domain->fluid)
386                         smoke_free(smd->domain->fluid);
387
388                 if (smd->domain->fluid_mutex)
389                         BLI_rw_mutex_free(smd->domain->fluid_mutex);
390
391                 if (smd->domain->wt)
392                         smoke_turbulence_free(smd->domain->wt);
393
394                 if (smd->domain->effector_weights)
395                         MEM_freeN(smd->domain->effector_weights);
396                 smd->domain->effector_weights = NULL;
397
398                 BKE_ptcache_free_list(&(smd->domain->ptcaches[0]));
399                 smd->domain->point_cache[0] = NULL;
400
401                 MEM_freeN(smd->domain);
402                 smd->domain = NULL;
403         }
404 }
405
406 static void smokeModifier_freeFlow(SmokeModifierData *smd)
407 {
408         if (smd->flow)
409         {
410                 if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm);
411                 if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old);
412                 MEM_freeN(smd->flow);
413                 smd->flow = NULL;
414         }
415 }
416
417 static void smokeModifier_freeCollision(SmokeModifierData *smd)
418 {
419         if (smd->coll)
420         {
421                 SmokeCollSettings *scs = smd->coll;
422
423                 if (scs->numverts)
424                 {
425                         if (scs->verts_old)
426                         {
427                                 MEM_freeN(scs->verts_old);
428                                 scs->verts_old = NULL;
429                         }
430                 }
431
432                 if (smd->coll->dm)
433                         smd->coll->dm->release(smd->coll->dm);
434                 smd->coll->dm = NULL;
435
436                 MEM_freeN(smd->coll);
437                 smd->coll = NULL;
438         }
439 }
440
441 void smokeModifier_reset_turbulence(struct SmokeModifierData *smd)
442 {
443         if (smd && smd->domain && smd->domain->wt)
444         {
445                 smoke_turbulence_free(smd->domain->wt);
446                 smd->domain->wt = NULL;
447         }
448 }
449
450 static void smokeModifier_reset_ex(struct SmokeModifierData *smd, bool need_lock)
451 {
452         if (smd)
453         {
454                 if (smd->domain)
455                 {
456                         if (smd->domain->shadow)
457                                 MEM_freeN(smd->domain->shadow);
458                         smd->domain->shadow = NULL;
459
460                         if (smd->domain->fluid)
461                         {
462                                 if (need_lock)
463                                         BLI_rw_mutex_lock(smd->domain->fluid_mutex, THREAD_LOCK_WRITE);
464
465                                 smoke_free(smd->domain->fluid);
466                                 smd->domain->fluid = NULL;
467
468                                 if (need_lock)
469                                         BLI_rw_mutex_unlock(smd->domain->fluid_mutex);
470                         }
471
472                         smokeModifier_reset_turbulence(smd);
473
474                         smd->time = -1;
475                         smd->domain->total_cells = 0;
476                         smd->domain->active_fields = 0;
477                 }
478                 else if (smd->flow)
479                 {
480                         if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old);
481                         smd->flow->verts_old = NULL;
482                         smd->flow->numverts = 0;
483                 }
484                 else if (smd->coll)
485                 {
486                         SmokeCollSettings *scs = smd->coll;
487
488                         if (scs->numverts && scs->verts_old)
489                         {
490                                 MEM_freeN(scs->verts_old);
491                                 scs->verts_old = NULL;
492                         }
493                 }
494         }
495 }
496
497 void smokeModifier_reset(struct SmokeModifierData *smd)
498 {
499         smokeModifier_reset_ex(smd, true);
500 }
501
502 void smokeModifier_free(SmokeModifierData *smd)
503 {
504         if (smd)
505         {
506                 smokeModifier_freeDomain(smd);
507                 smokeModifier_freeFlow(smd);
508                 smokeModifier_freeCollision(smd);
509         }
510 }
511
512 void smokeModifier_createType(struct SmokeModifierData *smd)
513 {
514         if (smd)
515         {
516                 if (smd->type & MOD_SMOKE_TYPE_DOMAIN)
517                 {
518                         if (smd->domain)
519                                 smokeModifier_freeDomain(smd);
520
521                         smd->domain = MEM_callocN(sizeof(SmokeDomainSettings), "SmokeDomain");
522
523                         smd->domain->smd = smd;
524
525                         smd->domain->point_cache[0] = BKE_ptcache_add(&(smd->domain->ptcaches[0]));
526                         smd->domain->point_cache[0]->flag |= PTCACHE_DISK_CACHE;
527                         smd->domain->point_cache[0]->step = 1;
528
529                         /* Deprecated */
530                         smd->domain->point_cache[1] = NULL;
531                         BLI_listbase_clear(&smd->domain->ptcaches[1]);
532                         /* set some standard values */
533                         smd->domain->fluid = NULL;
534                         smd->domain->fluid_mutex = BLI_rw_mutex_alloc();
535                         smd->domain->wt = NULL;
536                         smd->domain->eff_group = NULL;
537                         smd->domain->fluid_group = NULL;
538                         smd->domain->coll_group = NULL;
539                         smd->domain->maxres = 32;
540                         smd->domain->amplify = 1;
541                         smd->domain->alpha = -0.001;
542                         smd->domain->beta = 0.1;
543                         smd->domain->time_scale = 1.0;
544                         smd->domain->vorticity = 2.0;
545                         smd->domain->border_collisions = SM_BORDER_OPEN; // open domain
546                         smd->domain->flags = MOD_SMOKE_DISSOLVE_LOG;
547                         smd->domain->highres_sampling = SM_HRES_FULLSAMPLE;
548                         smd->domain->strength = 2.0;
549                         smd->domain->noise = MOD_SMOKE_NOISEWAVE;
550                         smd->domain->diss_speed = 5;
551                         smd->domain->active_fields = 0;
552
553                         smd->domain->adapt_margin = 4;
554                         smd->domain->adapt_res = 0;
555                         smd->domain->adapt_threshold = 0.02f;
556
557                         smd->domain->burning_rate = 0.75f;
558                         smd->domain->flame_smoke = 1.0f;
559                         smd->domain->flame_vorticity = 0.5f;
560                         smd->domain->flame_ignition = 1.25f;
561                         smd->domain->flame_max_temp = 1.75f;
562                         /* color */
563                         smd->domain->flame_smoke_color[0] = 0.7f;
564                         smd->domain->flame_smoke_color[1] = 0.7f;
565                         smd->domain->flame_smoke_color[2] = 0.7f;
566
567                         smd->domain->viewsettings = MOD_SMOKE_VIEW_SHOWBIG;
568                         smd->domain->effector_weights = BKE_add_effector_weights(NULL);
569                 }
570                 else if (smd->type & MOD_SMOKE_TYPE_FLOW)
571                 {
572                         if (smd->flow)
573                                 smokeModifier_freeFlow(smd);
574
575                         smd->flow = MEM_callocN(sizeof(SmokeFlowSettings), "SmokeFlow");
576
577                         smd->flow->smd = smd;
578
579                         /* set some standard values */
580                         smd->flow->density = 1.0f;
581                         smd->flow->fuel_amount = 1.0f;
582                         smd->flow->temp = 1.0f;
583                         smd->flow->flags = MOD_SMOKE_FLOW_ABSOLUTE | MOD_SMOKE_FLOW_USE_PART_SIZE;
584                         smd->flow->vel_multi = 1.0f;
585                         smd->flow->volume_density = 0.0f;
586                         smd->flow->surface_distance = 1.5f;
587                         smd->flow->source = MOD_SMOKE_FLOW_SOURCE_MESH;
588                         smd->flow->texture_size = 1.0f;
589                         smd->flow->particle_size = 1.0f;
590                         smd->flow->subframes = 0;
591
592                         smd->flow->color[0] = 0.7f;
593                         smd->flow->color[1] = 0.7f;
594                         smd->flow->color[2] = 0.7f;
595
596                         smd->flow->dm = NULL;
597                         smd->flow->psys = NULL;
598
599                 }
600                 else if (smd->type & MOD_SMOKE_TYPE_COLL)
601                 {
602                         if (smd->coll)
603                                 smokeModifier_freeCollision(smd);
604
605                         smd->coll = MEM_callocN(sizeof(SmokeCollSettings), "SmokeColl");
606
607                         smd->coll->smd = smd;
608                         smd->coll->verts_old = NULL;
609                         smd->coll->numverts = 0;
610                         smd->coll->type = 0; // static obstacle
611                         smd->coll->dm = NULL;
612
613 #ifdef USE_SMOKE_COLLISION_DM
614                         smd->coll->dm = NULL;
615 #endif
616                 }
617         }
618 }
619
620 void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData *tsmd)
621 {
622         tsmd->type = smd->type;
623         tsmd->time = smd->time;
624
625         smokeModifier_createType(tsmd);
626
627         if (tsmd->domain) {
628                 tsmd->domain->fluid_group = smd->domain->fluid_group;
629                 tsmd->domain->coll_group = smd->domain->coll_group;
630
631                 tsmd->domain->adapt_margin = smd->domain->adapt_margin;
632                 tsmd->domain->adapt_res = smd->domain->adapt_res;
633                 tsmd->domain->adapt_threshold = smd->domain->adapt_threshold;
634
635                 tsmd->domain->alpha = smd->domain->alpha;
636                 tsmd->domain->beta = smd->domain->beta;
637                 tsmd->domain->amplify = smd->domain->amplify;
638                 tsmd->domain->maxres = smd->domain->maxres;
639                 tsmd->domain->flags = smd->domain->flags;
640                 tsmd->domain->highres_sampling = smd->domain->highres_sampling;
641                 tsmd->domain->viewsettings = smd->domain->viewsettings;
642                 tsmd->domain->noise = smd->domain->noise;
643                 tsmd->domain->diss_speed = smd->domain->diss_speed;
644                 tsmd->domain->strength = smd->domain->strength;
645
646                 tsmd->domain->border_collisions = smd->domain->border_collisions;
647                 tsmd->domain->vorticity = smd->domain->vorticity;
648                 tsmd->domain->time_scale = smd->domain->time_scale;
649
650                 tsmd->domain->burning_rate = smd->domain->burning_rate;
651                 tsmd->domain->flame_smoke = smd->domain->flame_smoke;
652                 tsmd->domain->flame_vorticity = smd->domain->flame_vorticity;
653                 tsmd->domain->flame_ignition = smd->domain->flame_ignition;
654                 tsmd->domain->flame_max_temp = smd->domain->flame_max_temp;
655                 copy_v3_v3(tsmd->domain->flame_smoke_color, smd->domain->flame_smoke_color);
656
657                 MEM_freeN(tsmd->domain->effector_weights);
658                 tsmd->domain->effector_weights = MEM_dupallocN(smd->domain->effector_weights);
659         }
660         else if (tsmd->flow) {
661                 tsmd->flow->psys = smd->flow->psys;
662                 tsmd->flow->noise_texture = smd->flow->noise_texture;
663
664                 tsmd->flow->vel_multi = smd->flow->vel_multi;
665                 tsmd->flow->vel_normal = smd->flow->vel_normal;
666                 tsmd->flow->vel_random = smd->flow->vel_random;
667
668                 tsmd->flow->density = smd->flow->density;
669                 copy_v3_v3(tsmd->flow->color, smd->flow->color);
670                 tsmd->flow->fuel_amount = smd->flow->fuel_amount;
671                 tsmd->flow->temp = smd->flow->temp;
672                 tsmd->flow->volume_density = smd->flow->volume_density;
673                 tsmd->flow->surface_distance = smd->flow->surface_distance;
674                 tsmd->flow->particle_size = smd->flow->particle_size;
675                 tsmd->flow->subframes = smd->flow->subframes;
676
677                 tsmd->flow->texture_size = smd->flow->texture_size;
678                 tsmd->flow->texture_offset = smd->flow->texture_offset;
679                 BLI_strncpy(tsmd->flow->uvlayer_name, tsmd->flow->uvlayer_name, sizeof(tsmd->flow->uvlayer_name));
680                 tsmd->flow->vgroup_density = smd->flow->vgroup_density;
681
682                 tsmd->flow->type = smd->flow->type;
683                 tsmd->flow->source = smd->flow->source;
684                 tsmd->flow->texture_type = smd->flow->texture_type;
685                 tsmd->flow->flags = smd->flow->flags;
686         }
687         else if (tsmd->coll) {
688                 /* leave it as initialized, collision settings is mostly caches */
689         }
690 }
691
692 #ifdef WITH_SMOKE
693
694 // forward decleration
695 static void smoke_calc_transparency(SmokeDomainSettings *sds, Scene *scene);
696 static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct);
697
698 static int get_lamp(Scene *scene, float *light)
699 {
700         Base *base_tmp = NULL;
701         int found_lamp = 0;
702
703         // try to find a lamp, preferably local
704         for (base_tmp = scene->base.first; base_tmp; base_tmp = base_tmp->next) {
705                 if (base_tmp->object->type == OB_LAMP) {
706                         Lamp *la = base_tmp->object->data;
707
708                         if (la->type == LA_LOCAL) {
709                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
710                                 return 1;
711                         }
712                         else if (!found_lamp) {
713                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
714                                 found_lamp = 1;
715                         }
716                 }
717         }
718
719         return found_lamp;
720 }
721
722 /**********************************************************
723  *      Obstacles
724  **********************************************************/
725
726 static void obstacles_from_derivedmesh(Object *coll_ob, SmokeDomainSettings *sds, SmokeCollSettings *scs, unsigned char *obstacle_map, float *velocityX, float *velocityY, float *velocityZ, float dt)
727 {
728         if (!scs->dm) return;
729         {
730                 DerivedMesh *dm = NULL;
731                 MVert *mvert = NULL;
732                 const MLoopTri *looptri;
733                 const MLoop *mloop;
734                 BVHTreeFromMesh treeData = {NULL};
735                 int numverts, i, z;
736
737                 /* slightly rounded-up sqrt(3 * (0.5)^2) == max. distance of cell boundary along the diagonal */
738                 const float surface_distance = 0.867f;
739
740                 float *vert_vel = NULL;
741                 int has_velocity = 0;
742
743                 tstart();
744
745                 dm = CDDM_copy(scs->dm);
746                 CDDM_calc_normals(dm);
747                 mvert = dm->getVertArray(dm);
748                 mloop = dm->getLoopArray(dm);
749                 looptri = dm->getLoopTriArray(dm);
750                 numverts = dm->getNumVerts(dm);
751
752                 // DG TODO
753                 // if (scs->type > SM_COLL_STATIC)
754                 // if line above is used, the code is in trouble if the object moves but is declared as "does not move"
755
756                 {
757                         vert_vel = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_velocity");
758
759                         if (scs->numverts != numverts || !scs->verts_old) {
760                                 if (scs->verts_old) MEM_freeN(scs->verts_old);
761
762                                 scs->verts_old = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_verts_old");
763                                 scs->numverts = numverts;
764                         }
765                         else {
766                                 has_velocity = 1;
767                         }
768                 }
769
770                 /*      Transform collider vertices to
771                  *   domain grid space for fast lookups */
772                 for (i = 0; i < numverts; i++) {
773                         float n[3];
774                         float co[3];
775
776                         /* vert pos */
777                         mul_m4_v3(coll_ob->obmat, mvert[i].co);
778                         smoke_pos_to_cell(sds, mvert[i].co);
779
780                         /* vert normal */
781                         normal_short_to_float_v3(n, mvert[i].no);
782                         mul_mat3_m4_v3(coll_ob->obmat, n);
783                         mul_mat3_m4_v3(sds->imat, n);
784                         normalize_v3(n);
785                         normal_float_to_short_v3(mvert[i].no, n);
786
787                         /* vert velocity */
788                         VECADD(co, mvert[i].co, sds->shift);
789                         if (has_velocity)
790                         {
791                                 sub_v3_v3v3(&vert_vel[i * 3], co, &scs->verts_old[i * 3]);
792                                 mul_v3_fl(&vert_vel[i * 3], sds->dx / dt);
793                         }
794                         copy_v3_v3(&scs->verts_old[i * 3], co);
795                 }
796
797                 if (bvhtree_from_mesh_looptri(&treeData, dm, 0.0f, 4, 6)) {
798 #pragma omp parallel for schedule(static)
799                         for (z = sds->res_min[2]; z < sds->res_max[2]; z++) {
800                                 int x, y;
801                                 for (x = sds->res_min[0]; x < sds->res_max[0]; x++)
802                                         for (y = sds->res_min[1]; y < sds->res_max[1]; y++) {
803                                                 int index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]);
804
805                                                 float ray_start[3] = {(float)x + 0.5f, (float)y + 0.5f, (float)z + 0.5f};
806                                                 BVHTreeNearest nearest = {0};
807                                                 nearest.index = -1;
808                                                 nearest.dist_sq = surface_distance * surface_distance; /* find_nearest uses squared distance */
809
810                                                 /* find the nearest point on the mesh */
811                                                 if (BLI_bvhtree_find_nearest(treeData.tree, ray_start, &nearest, treeData.nearest_callback, &treeData) != -1) {
812                                                         const MLoopTri *lt = &looptri[nearest.index];
813                                                         float weights[4];
814                                                         int v1, v2, v3;
815
816                                                         /* calculate barycentric weights for nearest point */
817                                                         v1 = mloop[lt->tri[0]].v;
818                                                         v2 = mloop[lt->tri[1]].v;
819                                                         v3 = mloop[lt->tri[2]].v;
820                                                         interp_weights_face_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, NULL, nearest.co);
821
822                                                         // DG TODO
823                                                         if (has_velocity)
824                                                         {
825                                                                 /* apply object velocity */
826                                                                 {
827                                                                         float hit_vel[3];
828                                                                         interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights);
829                                                                         velocityX[index] += hit_vel[0];
830                                                                         velocityY[index] += hit_vel[1];
831                                                                         velocityZ[index] += hit_vel[2];
832                                                                 }
833                                                         }
834
835                                                         /* tag obstacle cells */
836                                                         obstacle_map[index] = 1;
837
838                                                         if (has_velocity)
839                                                                 obstacle_map[index] |= 8;
840                                                 }
841                                         }
842                         }
843                 }
844                 /* free bvh tree */
845                 free_bvhtree_from_mesh(&treeData);
846                 dm->release(dm);
847
848                 if (vert_vel) MEM_freeN(vert_vel);
849         }
850 }
851
852 /* Animated obstacles: dx_step = ((x_new - x_old) / totalsteps) * substep */
853 static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt,
854                              int UNUSED(substep), int UNUSED(totalsteps))
855 {
856         Object **collobjs = NULL;
857         unsigned int numcollobj = 0;
858
859         unsigned int collIndex;
860         unsigned char *obstacles = smoke_get_obstacle(sds->fluid);
861         float *velx = NULL;
862         float *vely = NULL;
863         float *velz = NULL;
864         float *velxOrig = smoke_get_velocity_x(sds->fluid);
865         float *velyOrig = smoke_get_velocity_y(sds->fluid);
866         float *velzOrig = smoke_get_velocity_z(sds->fluid);
867         float *density = smoke_get_density(sds->fluid);
868         float *fuel = smoke_get_fuel(sds->fluid);
869         float *flame = smoke_get_flame(sds->fluid);
870         float *r = smoke_get_color_r(sds->fluid);
871         float *g = smoke_get_color_g(sds->fluid);
872         float *b = smoke_get_color_b(sds->fluid);
873         unsigned int z;
874
875         smoke_get_ob_velocity(sds->fluid, &velx, &vely, &velz);
876
877         // TODO: delete old obstacle flags
878         for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++)
879         {
880                 if (obstacles[z] & 8) // Do not delete static obstacles
881                 {
882                         obstacles[z] = 0;
883                 }
884
885                 velx[z] = 0;
886                 vely[z] = 0;
887                 velz[z] = 0;
888         }
889
890
891         collobjs = get_collisionobjects(scene, ob, sds->coll_group, &numcollobj, eModifierType_Smoke);
892
893         // update obstacle tags in cells
894         for (collIndex = 0; collIndex < numcollobj; collIndex++)
895         {
896                 Object *collob = collobjs[collIndex];
897                 SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
898
899                 // DG TODO: check if modifier is active?
900
901                 if ((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll)
902                 {
903                         SmokeCollSettings *scs = smd2->coll;
904                         obstacles_from_derivedmesh(collob, sds, scs, obstacles, velx, vely, velz, dt);
905                 }
906         }
907
908         if (collobjs)
909                 MEM_freeN(collobjs);
910
911         /* obstacle cells should not contain any velocity from the smoke simulation */
912         for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++)
913         {
914                 if (obstacles[z])
915                 {
916                         velxOrig[z] = 0;
917                         velyOrig[z] = 0;
918                         velzOrig[z] = 0;
919                         density[z] = 0;
920                         if (fuel) {
921                                 fuel[z] = 0;
922                                 flame[z] = 0;
923                         }
924                         if (r) {
925                                 r[z] = 0;
926                                 g[z] = 0;
927                                 b[z] = 0;
928                         }
929                 }
930         }
931 }
932
933
934 /**********************************************************
935  *      Object subframe update method from dynamicpaint.c
936  **********************************************************/
937
938 /* set "ignore cache" flag for all caches on this object */
939 static void object_cacheIgnoreClear(Object *ob, bool state)
940 {
941         ListBase pidlist;
942         PTCacheID *pid;
943         BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0);
944
945         for (pid = pidlist.first; pid; pid = pid->next) {
946                 if (pid->cache) {
947                         if (state)
948                                 pid->cache->flag |= PTCACHE_IGNORE_CLEAR;
949                         else
950                                 pid->cache->flag &= ~PTCACHE_IGNORE_CLEAR;
951                 }
952         }
953
954         BLI_freelistN(&pidlist);
955 }
956
957 static bool subframe_updateObject(Scene *scene, Object *ob, int update_mesh, int parent_recursion, float frame, bool for_render)
958 {
959         SmokeModifierData *smd = (SmokeModifierData *)modifiers_findByType(ob, eModifierType_Smoke);
960         bConstraint *con;
961
962         /* if other is dynamic paint canvas, don't update */
963         if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN))
964                 return true;
965
966         /* if object has parents, update them too */
967         if (parent_recursion) {
968                 int recursion = parent_recursion - 1;
969                 bool is_domain = false;
970                 if (ob->parent) is_domain |= subframe_updateObject(scene, ob->parent, 0, recursion, frame, for_render);
971                 if (ob->track) is_domain |= subframe_updateObject(scene, ob->track, 0, recursion, frame, for_render);
972
973                 /* skip subframe if object is parented
974                  *  to vertex of a dynamic paint canvas */
975                 if (is_domain && (ob->partype == PARVERT1 || ob->partype == PARVERT3))
976                         return false;
977
978                 /* also update constraint targets */
979                 for (con = ob->constraints.first; con; con = con->next) {
980                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
981                         ListBase targets = {NULL, NULL};
982
983                         if (cti && cti->get_constraint_targets) {
984                                 bConstraintTarget *ct;
985                                 cti->get_constraint_targets(con, &targets);
986                                 for (ct = targets.first; ct; ct = ct->next) {
987                                         if (ct->tar)
988                                                 subframe_updateObject(scene, ct->tar, 0, recursion, frame, for_render);
989                                 }
990                                 /* free temp targets */
991                                 if (cti->flush_constraint_targets)
992                                         cti->flush_constraint_targets(con, &targets, 0);
993                         }
994                 }
995         }
996
997         /* was originally OB_RECALC_ALL - TODO - which flags are really needed??? */
998         ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
999         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, frame, ADT_RECALC_ANIM);
1000         if (update_mesh) {
1001                 /* ignore cache clear during subframe updates
1002                  *  to not mess up cache validity */
1003                 object_cacheIgnoreClear(ob, 1);
1004                 BKE_object_handle_update(G.main->eval_ctx, scene, ob);
1005                 object_cacheIgnoreClear(ob, 0);
1006         }
1007         else
1008                 BKE_object_where_is_calc_time(scene, ob, frame);
1009
1010         /* for curve following objects, parented curve has to be updated too */
1011         if (ob->type == OB_CURVE) {
1012                 Curve *cu = ob->data;
1013                 BKE_animsys_evaluate_animdata(scene, &cu->id, cu->adt, frame, ADT_RECALC_ANIM);
1014         }
1015         /* and armatures... */
1016         if (ob->type == OB_ARMATURE) {
1017                 bArmature *arm = ob->data;
1018                 BKE_animsys_evaluate_animdata(scene, &arm->id, arm->adt, frame, ADT_RECALC_ANIM);
1019                 BKE_pose_where_is(scene, ob);
1020         }
1021
1022         return false;
1023 }
1024
1025 /**********************************************************
1026  *      Flow emission code
1027  **********************************************************/
1028
1029 typedef struct EmissionMap {
1030         float *influence;
1031         float *influence_high;
1032         float *velocity;
1033         int min[3], max[3], res[3];
1034         int hmin[3], hmax[3], hres[3];
1035         int total_cells, valid;
1036 } EmissionMap;
1037
1038 static void em_boundInsert(EmissionMap *em, float point[3])
1039 {
1040         int i = 0;
1041         if (!em->valid) {
1042                 for (; i < 3; i++) {
1043                         em->min[i] = (int)floor(point[i]);
1044                         em->max[i] = (int)ceil(point[i]);
1045                 }
1046                 em->valid = 1;
1047         }
1048         else {
1049                 for (; i < 3; i++) {
1050                         if (point[i] < em->min[i]) em->min[i] = (int)floor(point[i]);
1051                         if (point[i] > em->max[i]) em->max[i] = (int)ceil(point[i]);
1052                 }
1053         }
1054 }
1055
1056 static void clampBoundsInDomain(SmokeDomainSettings *sds, int min[3], int max[3], float *min_vel, float *max_vel, int margin, float dt)
1057 {
1058         int i;
1059         for (i = 0; i < 3; i++) {
1060                 int adapt = (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) ? sds->adapt_res : 0;
1061                 /* add margin */
1062                 min[i] -= margin;
1063                 max[i] += margin;
1064
1065                 /* adapt to velocity */
1066                 if (min_vel && min_vel[i] < 0.0f) {
1067                         min[i] += (int)floor(min_vel[i] * dt);
1068                 }
1069                 if (max_vel && max_vel[i] > 0.0f) {
1070                         max[i] += (int)ceil(max_vel[i] * dt);
1071                 }
1072
1073                 /* clamp within domain max size */
1074                 CLAMP(min[i], -adapt, sds->base_res[i] + adapt);
1075                 CLAMP(max[i], -adapt, sds->base_res[i] + adapt);
1076         }
1077 }
1078
1079 static void em_allocateData(EmissionMap *em, bool use_velocity, int hires_mul)
1080 {
1081         int i, res[3];
1082
1083         for (i = 0; i < 3; i++) {
1084                 res[i] = em->max[i] - em->min[i];
1085                 if (res[i] <= 0)
1086                         return;
1087         }
1088         em->total_cells = res[0] * res[1] * res[2];
1089         copy_v3_v3_int(em->res, res);
1090
1091
1092         em->influence = MEM_callocN(sizeof(float) * em->total_cells, "smoke_flow_influence");
1093         if (use_velocity)
1094                 em->velocity = MEM_callocN(sizeof(float) * em->total_cells * 3, "smoke_flow_velocity");
1095
1096         /* allocate high resolution map if required */
1097         if (hires_mul > 1) {
1098                 int total_cells_high = em->total_cells * (hires_mul * hires_mul * hires_mul);
1099
1100                 for (i = 0; i < 3; i++) {
1101                         em->hmin[i] = em->min[i] * hires_mul;
1102                         em->hmax[i] = em->max[i] * hires_mul;
1103                         em->hres[i] = em->res[i] * hires_mul;
1104                 }
1105
1106                 em->influence_high = MEM_callocN(sizeof(float) * total_cells_high, "smoke_flow_influence_high");
1107         }
1108         em->valid = 1;
1109 }
1110
1111 static void em_freeData(EmissionMap *em)
1112 {
1113         if (em->influence)
1114                 MEM_freeN(em->influence);
1115         if (em->influence_high)
1116                 MEM_freeN(em->influence_high);
1117         if (em->velocity)
1118                 MEM_freeN(em->velocity);
1119 }
1120
1121 static void em_combineMaps(EmissionMap *output, EmissionMap *em2, int hires_multiplier, int additive, float sample_size)
1122 {
1123         int i, x, y, z;
1124
1125         /* copyfill input 1 struct and clear output for new allocation */
1126         EmissionMap em1;
1127         memcpy(&em1, output, sizeof(EmissionMap));
1128         memset(output, 0, sizeof(EmissionMap));
1129
1130         for (i = 0; i < 3; i++) {
1131                 if (em1.valid) {
1132                         output->min[i] = MIN2(em1.min[i], em2->min[i]);
1133                         output->max[i] = MAX2(em1.max[i], em2->max[i]);
1134                 }
1135                 else {
1136                         output->min[i] = em2->min[i];
1137                         output->max[i] = em2->max[i];
1138                 }
1139         }
1140         /* allocate output map */
1141         em_allocateData(output, (em1.velocity || em2->velocity), hires_multiplier);
1142
1143         /* base resolution inputs */
1144         for (x = output->min[0]; x < output->max[0]; x++)
1145                 for (y = output->min[1]; y < output->max[1]; y++)
1146                         for (z = output->min[2]; z < output->max[2]; z++) {
1147                                 int index_out = smoke_get_index(x - output->min[0], output->res[0], y - output->min[1], output->res[1], z - output->min[2]);
1148
1149                                 /* initialize with first input if in range */
1150                                 if (x >= em1.min[0] && x < em1.max[0] &&
1151                                         y >= em1.min[1] && y < em1.max[1] &&
1152                                         z >= em1.min[2] && z < em1.max[2]) {
1153                                         int index_in = smoke_get_index(x - em1.min[0], em1.res[0], y - em1.min[1], em1.res[1], z - em1.min[2]);
1154
1155                                         /* values */
1156                                         output->influence[index_out] = em1.influence[index_in];
1157                                         if (output->velocity && em1.velocity) {
1158                                                 copy_v3_v3(&output->velocity[index_out * 3], &em1.velocity[index_in * 3]);
1159                                         }
1160                                 }
1161
1162                                 /* apply second input if in range */
1163                                 if (x >= em2->min[0] && x < em2->max[0] &&
1164                                         y >= em2->min[1] && y < em2->max[1] &&
1165                                         z >= em2->min[2] && z < em2->max[2]) {
1166                                         int index_in = smoke_get_index(x - em2->min[0], em2->res[0], y - em2->min[1], em2->res[1], z - em2->min[2]);
1167
1168                                         /* values */
1169                                         if (additive) {
1170                                                 output->influence[index_out] += em2->influence[index_in] * sample_size;
1171                                         }
1172                                         else {
1173                                                 output->influence[index_out] = MAX2(em2->influence[index_in], output->influence[index_out]);
1174                                         }
1175                                         if (output->velocity && em2->velocity) {
1176                                                 /* last sample replaces the velocity */
1177                                                 output->velocity[index_out * 3]         = ADD_IF_LOWER(output->velocity[index_out * 3], em2->velocity[index_in * 3]);
1178                                                 output->velocity[index_out * 3 + 1] = ADD_IF_LOWER(output->velocity[index_out * 3 + 1], em2->velocity[index_in * 3 + 1]);
1179                                                 output->velocity[index_out * 3 + 2] = ADD_IF_LOWER(output->velocity[index_out * 3 + 2], em2->velocity[index_in * 3 + 2]);
1180                                         }
1181                                 }
1182         } // low res loop
1183
1184
1185
1186         /* initialize high resolution input if available */
1187         if (output->influence_high) {
1188                 for (x = output->hmin[0]; x < output->hmax[0]; x++)
1189                         for (y = output->hmin[1]; y < output->hmax[1]; y++)
1190                                 for (z = output->hmin[2]; z < output->hmax[2]; z++) {
1191                                         int index_out = smoke_get_index(x - output->hmin[0], output->hres[0], y - output->hmin[1], output->hres[1], z - output->hmin[2]);
1192
1193                                         /* initialize with first input if in range */
1194                                         if (x >= em1.hmin[0] && x < em1.hmax[0] &&
1195                                                 y >= em1.hmin[1] && y < em1.hmax[1] &&
1196                                                 z >= em1.hmin[2] && z < em1.hmax[2]) {
1197                                                 int index_in = smoke_get_index(x - em1.hmin[0], em1.hres[0], y - em1.hmin[1], em1.hres[1], z - em1.hmin[2]);
1198                                                 /* values */
1199                                                 output->influence_high[index_out] = em1.influence_high[index_in];
1200                                         }
1201
1202                                         /* apply second input if in range */
1203                                         if (x >= em2->hmin[0] && x < em2->hmax[0] &&
1204                                                 y >= em2->hmin[1] && y < em2->hmax[1] &&
1205                                                 z >= em2->hmin[2] && z < em2->hmax[2]) {
1206                                                 int index_in = smoke_get_index(x - em2->hmin[0], em2->hres[0], y - em2->hmin[1], em2->hres[1], z - em2->hmin[2]);
1207
1208                                                 /* values */
1209                                                 if (additive) {
1210                                                         output->influence_high[index_out] += em2->influence_high[index_in] * sample_size;
1211                                                 }
1212                                                 else {
1213                                                         output->influence_high[index_out] = MAX2(em2->influence_high[index_in], output->influence_high[index_out]);
1214                                                 }
1215                                         }
1216                 } // high res loop
1217         }
1218
1219         /* free original data */
1220         em_freeData(&em1);
1221 }
1222
1223
1224 static void emit_from_particles(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, Scene *scene, float dt)
1225 {
1226         if (sfs && sfs->psys && sfs->psys->part && ELEM(sfs->psys->part->type, PART_EMITTER, PART_FLUID)) // is particle system selected
1227         {
1228                 ParticleSimulationData sim;
1229                 ParticleSystem *psys = sfs->psys;
1230                 float *particle_pos;
1231                 float *particle_vel;
1232                 int totpart = psys->totpart, totchild;
1233                 int p = 0;
1234                 int valid_particles = 0;
1235                 int bounds_margin = 1;
1236
1237                 /* radius based flow */
1238                 float solid = sfs->particle_size * 0.5f;
1239                 float smooth = 0.5f; /* add 0.5 cells of linear falloff to reduce aliasing */
1240                 int hires_multiplier = 1;
1241                 int z;
1242                 KDTree *tree;
1243
1244                 sim.scene = scene;
1245                 sim.ob = flow_ob;
1246                 sim.psys = psys;
1247
1248                 /* prepare curvemapping tables */
1249                 if ((psys->part->child_flag & PART_CHILD_USE_CLUMP_CURVE) && psys->part->clumpcurve)
1250                         curvemapping_changed_all(psys->part->clumpcurve);
1251                 if ((psys->part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && psys->part->roughcurve)
1252                         curvemapping_changed_all(psys->part->roughcurve);
1253
1254                 /* initialize particle cache */
1255                 if (psys->part->type == PART_HAIR) {
1256                         // TODO: PART_HAIR not supported whatsoever
1257                         totchild = 0;
1258                 }
1259                 else {
1260                         totchild = psys->totchild * psys->part->disp / 100;
1261                 }
1262
1263                 particle_pos = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
1264                 particle_vel = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
1265
1266                 /* setup particle radius emission if enabled */
1267                 if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1268                         tree = BLI_kdtree_new(psys->totpart + psys->totchild);
1269
1270                         /* check need for high resolution map */
1271                         if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
1272                                 hires_multiplier = sds->amplify + 1;
1273                         }
1274
1275                         bounds_margin = (int)ceil(solid + smooth);
1276                 }
1277
1278                 /* calculate local position for each particle */
1279                 for (p = 0; p < totpart + totchild; p++)
1280                 {
1281                         ParticleKey state;
1282                         float *pos;
1283                         if (p < totpart) {
1284                                 if (psys->particles[p].flag & (PARS_NO_DISP | PARS_UNEXIST))
1285                                         continue;
1286                         }
1287                         else {
1288                                 /* handle child particle */
1289                                 ChildParticle *cpa = &psys->child[p - totpart];
1290                                 if (psys->particles[cpa->parent].flag & (PARS_NO_DISP | PARS_UNEXIST))
1291                                         continue;
1292                         }
1293
1294                         state.time = BKE_scene_frame_get(scene); /* use scene time */
1295                         if (psys_get_particle_state(&sim, p, &state, 0) == 0)
1296                                 continue;
1297
1298                         /* location */
1299                         pos = &particle_pos[valid_particles * 3];
1300                         copy_v3_v3(pos, state.co);
1301                         smoke_pos_to_cell(sds, pos);
1302
1303                         /* velocity */
1304                         copy_v3_v3(&particle_vel[valid_particles * 3], state.vel);
1305                         mul_mat3_m4_v3(sds->imat, &particle_vel[valid_particles * 3]);
1306
1307                         if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1308                                 BLI_kdtree_insert(tree, valid_particles, pos);
1309                         }
1310
1311                         /* calculate emission map bounds */
1312                         em_boundInsert(em, pos);
1313                         valid_particles++;
1314                 }
1315
1316                 /* set emission map */
1317                 clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, bounds_margin, dt);
1318                 em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY, hires_multiplier);
1319
1320                 if (!(sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE)) {
1321                         for (p = 0; p < valid_particles; p++)
1322                         {
1323                                 int cell[3];
1324                                 size_t i = 0;
1325                                 size_t index = 0;
1326                                 int badcell = 0;
1327
1328                                 /* 1. get corresponding cell */
1329                                 cell[0] = floor(particle_pos[p * 3]) - em->min[0];
1330                                 cell[1] = floor(particle_pos[p * 3 + 1]) - em->min[1];
1331                                 cell[2] = floor(particle_pos[p * 3 + 2]) - em->min[2];
1332                                 /* check if cell is valid (in the domain boundary) */
1333                                 for (i = 0; i < 3; i++) {
1334                                         if ((cell[i] > em->res[i] - 1) || (cell[i] < 0)) {
1335                                                 badcell = 1;
1336                                                 break;
1337                                         }
1338                                 }
1339                                 if (badcell)
1340                                         continue;
1341                                 /* get cell index */
1342                                 index = smoke_get_index(cell[0], em->res[0], cell[1], em->res[1], cell[2]);
1343                                 /* Add influence to emission map */
1344                                 em->influence[index] = 1.0f;
1345                                 /* Uses particle velocity as initial velocity for smoke */
1346                                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
1347                                 {
1348                                         VECADDFAC(&em->velocity[index * 3], &em->velocity[index * 3], &particle_vel[p * 3], sfs->vel_multi);
1349                                 }
1350                         }   // particles loop
1351                 }
1352                 else if (valid_particles > 0) { // MOD_SMOKE_FLOW_USE_PART_SIZE
1353
1354                         int min[3], max[3], res[3];
1355                         float hr = 1.0f / ((float)hires_multiplier);
1356                         /* slightly adjust high res antialias smoothness based on number of divisions
1357                          * to allow smaller details but yet not differing too much from the low res size */
1358                         const float hr_smooth = smooth * powf(hr, 1.0f / 3.0f);
1359
1360                         /* setup loop bounds */
1361                         for (int i = 0; i < 3; i++) {
1362                                 min[i] = em->min[i] * hires_multiplier;
1363                                 max[i] = em->max[i] * hires_multiplier;
1364                                 res[i] = em->res[i] * hires_multiplier;
1365                         }
1366
1367                         BLI_kdtree_balance(tree);
1368
1369                         /* begin thread safe malloc */
1370                         BLI_begin_threaded_malloc();
1371
1372 #pragma omp parallel for schedule(static)
1373                         for (z = min[2]; z < max[2]; z++) {
1374                                 int x, y;
1375                                 for (x = min[0]; x < max[0]; x++)
1376                                         for (y = min[1]; y < max[1]; y++) {
1377                                                 /* take low res samples where possible */
1378                                                 if (hires_multiplier <= 1 || !(x % hires_multiplier || y % hires_multiplier || z % hires_multiplier)) {
1379                                                         /* get low res space coordinates */
1380                                                         int lx = x / hires_multiplier;
1381                                                         int ly = y / hires_multiplier;
1382                                                         int lz = z / hires_multiplier;
1383
1384                                                         int index = smoke_get_index(lx - em->min[0], em->res[0], ly - em->min[1], em->res[1], lz - em->min[2]);
1385                                                         float ray_start[3] = {((float)lx) + 0.5f, ((float)ly) + 0.5f, ((float)lz) + 0.5f};
1386
1387                                                         /* find particle distance from the kdtree */
1388                                                         KDTreeNearest nearest;
1389                                                         float range = solid + smooth;
1390                                                         BLI_kdtree_find_nearest(tree, ray_start, &nearest);
1391
1392                                                         if (nearest.dist < range) {
1393                                                                 em->influence[index] = (nearest.dist < solid) ? 1.0f : (1.0f - (nearest.dist-solid) / smooth);
1394                                                                 /* Uses particle velocity as initial velocity for smoke */
1395                                                                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
1396                                                                 {
1397                                                                         VECADDFAC(&em->velocity[index * 3], &em->velocity[index * 3], &particle_vel[nearest.index * 3], sfs->vel_multi);
1398                                                                 }
1399                                                         }
1400                                                 }
1401
1402                                                 /* take high res samples if required */
1403                                                 if (hires_multiplier > 1) {
1404                                                         /* get low res space coordinates */
1405                                                         float lx = ((float)x) * hr;
1406                                                         float ly = ((float)y) * hr;
1407                                                         float lz = ((float)z) * hr;
1408
1409                                                         int index = smoke_get_index(x - min[0], res[0], y - min[1], res[1], z - min[2]);
1410                                                         float ray_start[3] = {lx + 0.5f*hr, ly + 0.5f*hr, lz + 0.5f*hr};
1411
1412                                                         /* find particle distance from the kdtree */
1413                                                         KDTreeNearest nearest;
1414                                                         float range = solid + hr_smooth;
1415                                                         BLI_kdtree_find_nearest(tree, ray_start, &nearest);
1416
1417                                                         if (nearest.dist < range) {
1418                                                                 em->influence_high[index] = (nearest.dist < solid) ? 1.0f : (1.0f - (nearest.dist-solid) / smooth);
1419                                                         }
1420                                                 }
1421
1422                                         }
1423                         }
1424                         BLI_end_threaded_malloc();
1425                 }
1426
1427                 if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1428                         BLI_kdtree_free(tree);
1429                 }
1430
1431                 /* free data */
1432                 if (particle_pos)
1433                         MEM_freeN(particle_pos);
1434                 if (particle_vel)
1435                         MEM_freeN(particle_vel);
1436         }
1437 }
1438
1439 static void sample_derivedmesh(
1440         SmokeFlowSettings *sfs,
1441         const MVert *mvert, const MLoop *mloop, const MLoopTri *mlooptri, const MLoopUV *mloopuv,
1442         float *influence_map, float *velocity_map, int index, const int base_res[3], float flow_center[3],
1443         BVHTreeFromMesh *treeData, const float ray_start[3], const float *vert_vel,
1444         bool has_velocity, int defgrp_index, MDeformVert *dvert,
1445         float x, float y, float z)
1446 {
1447         float ray_dir[3] = {1.0f, 0.0f, 0.0f};
1448         BVHTreeRayHit hit = {0};
1449         BVHTreeNearest nearest = {0};
1450
1451         float volume_factor = 0.0f;
1452         float sample_str = 0.0f;
1453
1454         hit.index = -1;
1455         hit.dist = 9999;
1456         nearest.index = -1;
1457         nearest.dist_sq = sfs->surface_distance * sfs->surface_distance; /* find_nearest uses squared distance */
1458
1459         /* Check volume collision */
1460         if (sfs->volume_density) {
1461                 if (BLI_bvhtree_ray_cast(treeData->tree, ray_start, ray_dir, 0.0f, &hit, treeData->raycast_callback, treeData) != -1) {
1462                         float dot = ray_dir[0] * hit.no[0] + ray_dir[1] * hit.no[1] + ray_dir[2] * hit.no[2];
1463                         /*  If ray and hit face normal are facing same direction
1464                          *      hit point is inside a closed mesh. */
1465                         if (dot >= 0) {
1466                                 /* Also cast a ray in opposite direction to make sure
1467                                  * point is at least surrounded by two faces */
1468                                 negate_v3(ray_dir);
1469                                 hit.index = -1;
1470                                 hit.dist = 9999;
1471
1472                                 BLI_bvhtree_ray_cast(treeData->tree, ray_start, ray_dir, 0.0f, &hit, treeData->raycast_callback, treeData);
1473                                 if (hit.index != -1) {
1474                                         volume_factor = sfs->volume_density;
1475                                 }
1476                         }
1477                 }
1478         }
1479
1480         /* find the nearest point on the mesh */
1481         if (BLI_bvhtree_find_nearest(treeData->tree, ray_start, &nearest, treeData->nearest_callback, treeData) != -1) {
1482                 float weights[4];
1483                 int v1, v2, v3, f_index = nearest.index;
1484                 float n1[3], n2[3], n3[3], hit_normal[3];
1485
1486                 /* emit from surface based on distance */
1487                 if (sfs->surface_distance) {
1488                         sample_str = sqrtf(nearest.dist_sq) / sfs->surface_distance;
1489                         CLAMP(sample_str, 0.0f, 1.0f);
1490                         sample_str = pow(1.0f - sample_str, 0.5f);
1491                 }
1492                 else
1493                         sample_str = 0.0f;
1494
1495                 /* calculate barycentric weights for nearest point */
1496                 v1 = mloop[mlooptri[f_index].tri[0]].v;
1497                 v2 = mloop[mlooptri[f_index].tri[1]].v;
1498                 v3 = mloop[mlooptri[f_index].tri[2]].v;
1499                 interp_weights_face_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, NULL, nearest.co);
1500
1501                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && velocity_map) {
1502                         /* apply normal directional velocity */
1503                         if (sfs->vel_normal) {
1504                                 /* interpolate vertex normal vectors to get nearest point normal */
1505                                 normal_short_to_float_v3(n1, mvert[v1].no);
1506                                 normal_short_to_float_v3(n2, mvert[v2].no);
1507                                 normal_short_to_float_v3(n3, mvert[v3].no);
1508                                 interp_v3_v3v3v3(hit_normal, n1, n2, n3, weights);
1509                                 normalize_v3(hit_normal);
1510                                 /* apply normal directional and random velocity
1511                                  * - TODO: random disabled for now since it doesnt really work well as pressure calc smoothens it out... */
1512                                 velocity_map[index * 3]   += hit_normal[0] * sfs->vel_normal * 0.25f;
1513                                 velocity_map[index * 3 + 1] += hit_normal[1] * sfs->vel_normal * 0.25f;
1514                                 velocity_map[index * 3 + 2] += hit_normal[2] * sfs->vel_normal * 0.25f;
1515                                 /* TODO: for fire emitted from mesh surface we can use
1516                                  *  Vf = Vs + (Ps/Pf - 1)*S to model gaseous expansion from solid to fuel */
1517                         }
1518                         /* apply object velocity */
1519                         if (has_velocity && sfs->vel_multi) {
1520                                 float hit_vel[3];
1521                                 interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights);
1522                                 velocity_map[index * 3]   += hit_vel[0] * sfs->vel_multi;
1523                                 velocity_map[index * 3 + 1] += hit_vel[1] * sfs->vel_multi;
1524                                 velocity_map[index * 3 + 2] += hit_vel[2] * sfs->vel_multi;
1525                         }
1526                 }
1527
1528                 /* apply vertex group influence if used */
1529                 if (defgrp_index != -1 && dvert) {
1530                         float weight_mask = defvert_find_weight(&dvert[v1], defgrp_index) * weights[0] +
1531                                             defvert_find_weight(&dvert[v2], defgrp_index) * weights[1] +
1532                                             defvert_find_weight(&dvert[v3], defgrp_index) * weights[2];
1533                         sample_str *= weight_mask;
1534                 }
1535
1536                 /* apply emission texture */
1537                 if ((sfs->flags & MOD_SMOKE_FLOW_TEXTUREEMIT) && sfs->noise_texture) {
1538                         float tex_co[3] = {0};
1539                         TexResult texres;
1540
1541                         if (sfs->texture_type == MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO) {
1542                                 tex_co[0] = ((x - flow_center[0]) / base_res[0]) / sfs->texture_size;
1543                                 tex_co[1] = ((y - flow_center[1]) / base_res[1]) / sfs->texture_size;
1544                                 tex_co[2] = ((z - flow_center[2]) / base_res[2] - sfs->texture_offset) / sfs->texture_size;
1545                         }
1546                         else if (mloopuv) {
1547                                 const float *uv[3];
1548                                 uv[0] = mloopuv[mlooptri[f_index].tri[0]].uv;
1549                                 uv[1] = mloopuv[mlooptri[f_index].tri[1]].uv;
1550                                 uv[2] = mloopuv[mlooptri[f_index].tri[2]].uv;
1551
1552                                 interp_v2_v2v2v2(tex_co, UNPACK3(uv), weights);
1553
1554                                 /* map between -1.0f and 1.0f */
1555                                 tex_co[0] = tex_co[0] * 2.0f - 1.0f;
1556                                 tex_co[1] = tex_co[1] * 2.0f - 1.0f;
1557                                 tex_co[2] = sfs->texture_offset;
1558                         }
1559                         texres.nor = NULL;
1560                         BKE_texture_get_value(NULL, sfs->noise_texture, tex_co, &texres, false);
1561                         sample_str *= texres.tin;
1562                 }
1563         }
1564
1565         /* multiply initial velocity by emitter influence */
1566         if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && velocity_map) {
1567                 mul_v3_fl(&velocity_map[index * 3], sample_str);
1568         }
1569
1570         /* apply final influence based on volume factor */
1571         influence_map[index] = MAX2(volume_factor, sample_str);
1572 }
1573
1574 static void emit_from_derivedmesh(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, float dt)
1575 {
1576         if (sfs->dm) {
1577                 DerivedMesh *dm;
1578                 int defgrp_index = sfs->vgroup_density - 1;
1579                 MDeformVert *dvert = NULL;
1580                 MVert *mvert = NULL;
1581                 MVert *mvert_orig = NULL;
1582                 const MLoopTri *mlooptri = NULL;
1583                 const MLoopUV *mloopuv = NULL;
1584                 const MLoop *mloop = NULL;
1585                 BVHTreeFromMesh treeData = {NULL};
1586                 int numOfVerts, i, z;
1587                 float flow_center[3] = {0};
1588
1589                 float *vert_vel = NULL;
1590                 int has_velocity = 0;
1591                 int min[3], max[3], res[3];
1592                 int hires_multiplier = 1;
1593
1594                 /* copy derivedmesh for thread safety because we modify it,
1595                  * main issue is its VertArray being modified, then replaced and freed
1596                  */
1597                 dm = CDDM_copy(sfs->dm);
1598
1599                 CDDM_calc_normals(dm);
1600                 mvert = dm->getVertArray(dm);
1601                 mvert_orig = dm->dupVertArray(dm);  /* copy original mvert and restore when done */
1602                 numOfVerts = dm->getNumVerts(dm);
1603                 dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
1604                 mloopuv = CustomData_get_layer_named(&dm->loopData, CD_MLOOPUV, sfs->uvlayer_name);
1605                 mloop = dm->getLoopArray(dm);
1606                 mlooptri = dm->getLoopTriArray(dm);
1607
1608                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
1609                         vert_vel = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_velocity");
1610
1611                         if (sfs->numverts != numOfVerts || !sfs->verts_old) {
1612                                 if (sfs->verts_old) MEM_freeN(sfs->verts_old);
1613                                 sfs->verts_old = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_verts_old");
1614                                 sfs->numverts = numOfVerts;
1615                         }
1616                         else {
1617                                 has_velocity = 1;
1618                         }
1619                 }
1620
1621                 /*      Transform dm vertices to
1622                  *   domain grid space for fast lookups */
1623                 for (i = 0; i < numOfVerts; i++) {
1624                         float n[3];
1625                         /* vert pos */
1626                         mul_m4_v3(flow_ob->obmat, mvert[i].co);
1627                         smoke_pos_to_cell(sds, mvert[i].co);
1628                         /* vert normal */
1629                         normal_short_to_float_v3(n, mvert[i].no);
1630                         mul_mat3_m4_v3(flow_ob->obmat, n);
1631                         mul_mat3_m4_v3(sds->imat, n);
1632                         normalize_v3(n);
1633                         normal_float_to_short_v3(mvert[i].no, n);
1634                         /* vert velocity */
1635                         if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
1636                                 float co[3];
1637                                 VECADD(co, mvert[i].co, sds->shift);
1638                                 if (has_velocity) {
1639                                         sub_v3_v3v3(&vert_vel[i * 3], co, &sfs->verts_old[i * 3]);
1640                                         mul_v3_fl(&vert_vel[i * 3], sds->dx / dt);
1641                                 }
1642                                 copy_v3_v3(&sfs->verts_old[i * 3], co);
1643                         }
1644
1645                         /* calculate emission map bounds */
1646                         em_boundInsert(em, mvert[i].co);
1647                 }
1648                 mul_m4_v3(flow_ob->obmat, flow_center);
1649                 smoke_pos_to_cell(sds, flow_center);
1650
1651                 /* check need for high resolution map */
1652                 if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
1653                         hires_multiplier = sds->amplify + 1;
1654                 }
1655
1656                 /* set emission map */
1657                 clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, (int)ceil(sfs->surface_distance), dt);
1658                 em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY, hires_multiplier);
1659
1660                 /* setup loop bounds */
1661                 for (i = 0; i < 3; i++) {
1662                         min[i] = em->min[i] * hires_multiplier;
1663                         max[i] = em->max[i] * hires_multiplier;
1664                         res[i] = em->res[i] * hires_multiplier;
1665                 }
1666
1667                 if (bvhtree_from_mesh_looptri(&treeData, dm, 0.0f, 4, 6)) {
1668 #pragma omp parallel for schedule(static)
1669                         for (z = min[2]; z < max[2]; z++) {
1670                                 int x, y;
1671                                 for (x = min[0]; x < max[0]; x++)
1672                                         for (y = min[1]; y < max[1]; y++) {
1673                                                 /* take low res samples where possible */
1674                                                 if (hires_multiplier <= 1 || !(x % hires_multiplier || y % hires_multiplier || z % hires_multiplier)) {
1675                                                         /* get low res space coordinates */
1676                                                         int lx = x / hires_multiplier;
1677                                                         int ly = y / hires_multiplier;
1678                                                         int lz = z / hires_multiplier;
1679
1680                                                         int index = smoke_get_index(lx - em->min[0], em->res[0], ly - em->min[1], em->res[1], lz - em->min[2]);
1681                                                         float ray_start[3] = {((float)lx) + 0.5f, ((float)ly) + 0.5f, ((float)lz) + 0.5f};
1682
1683                                                         sample_derivedmesh(
1684                                                                 sfs, mvert, mloop, mlooptri, mloopuv,
1685                                                                 em->influence, em->velocity, index, sds->base_res, flow_center,
1686                                                                 &treeData, ray_start,vert_vel, has_velocity, defgrp_index, dvert,
1687                                                                 (float)lx, (float)ly, (float)lz);
1688                                                 }
1689
1690                                                 /* take high res samples if required */
1691                                                 if (hires_multiplier > 1) {
1692                                                         /* get low res space coordinates */
1693                                                         float hr = 1.0f / ((float)hires_multiplier);
1694                                                         float lx = ((float)x) * hr;
1695                                                         float ly = ((float)y) * hr;
1696                                                         float lz = ((float)z) * hr;
1697
1698                                                         int index = smoke_get_index(x - min[0], res[0], y - min[1], res[1], z - min[2]);
1699                                                         float ray_start[3] = {lx + 0.5f*hr, ly + 0.5f*hr, lz + 0.5f*hr};
1700
1701                                                         sample_derivedmesh(
1702                                                                 sfs, mvert, mloop, mlooptri, mloopuv,
1703                                                                 em->influence_high, NULL, index, sds->base_res, flow_center,
1704                                                                 &treeData, ray_start, vert_vel, has_velocity, defgrp_index, dvert,
1705                                                                 /* x,y,z needs to be always lowres */
1706                                                                 lx, ly, lz);
1707                                                 }
1708
1709                                         }
1710                         }
1711                 }
1712                 /* free bvh tree */
1713                 free_bvhtree_from_mesh(&treeData);
1714                 /* restore original mverts */
1715                 CustomData_set_layer(&dm->vertData, CD_MVERT, mvert_orig);
1716
1717                 if (mvert) {
1718                         MEM_freeN(mvert);
1719                 }
1720                 if (vert_vel) {
1721                         MEM_freeN(vert_vel);
1722                 }
1723
1724                 dm->needsFree = 1;
1725                 dm->release(dm);
1726         }
1727 }
1728
1729 /**********************************************************
1730  *      Smoke step
1731  **********************************************************/
1732
1733 static void adjustDomainResolution(SmokeDomainSettings *sds, int new_shift[3], EmissionMap *emaps, unsigned int numflowobj, float dt)
1734 {
1735         const int block_size = sds->amplify + 1;
1736         int min[3] = {32767, 32767, 32767}, max[3] = {-32767, -32767, -32767}, res[3];
1737         int total_cells = 1, res_changed = 0, shift_changed = 0;
1738         float min_vel[3], max_vel[3];
1739         int x, y, z;
1740         float *density = smoke_get_density(sds->fluid);
1741         float *fuel = smoke_get_fuel(sds->fluid);
1742         float *bigdensity = smoke_turbulence_get_density(sds->wt);
1743         float *bigfuel = smoke_turbulence_get_fuel(sds->wt);
1744         float *vx = smoke_get_velocity_x(sds->fluid);
1745         float *vy = smoke_get_velocity_y(sds->fluid);
1746         float *vz = smoke_get_velocity_z(sds->fluid);
1747         int wt_res[3];
1748
1749         if (sds->flags & MOD_SMOKE_HIGHRES && sds->wt) {
1750                 smoke_turbulence_get_res(sds->wt, wt_res);
1751         }
1752
1753         INIT_MINMAX(min_vel, max_vel);
1754
1755         /* Calculate bounds for current domain content */
1756         for (x = sds->res_min[0]; x <  sds->res_max[0]; x++)
1757                 for (y =  sds->res_min[1]; y <  sds->res_max[1]; y++)
1758                         for (z =  sds->res_min[2]; z <  sds->res_max[2]; z++)
1759                         {
1760                                 int xn = x - new_shift[0];
1761                                 int yn = y - new_shift[1];
1762                                 int zn = z - new_shift[2];
1763                                 int index;
1764                                 float max_den;
1765                                 
1766                                 /* skip if cell already belongs to new area */
1767                                 if (xn >= min[0] && xn <= max[0] && yn >= min[1] && yn <= max[1] && zn >= min[2] && zn <= max[2])
1768                                         continue;
1769
1770                                 index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]);
1771                                 max_den = (fuel) ? MAX2(density[index], fuel[index]) : density[index];
1772
1773                                 /* check high resolution bounds if max density isnt already high enough */
1774                                 if (max_den < sds->adapt_threshold && sds->flags & MOD_SMOKE_HIGHRES && sds->wt) {
1775                                         int i, j, k;
1776                                         /* high res grid index */
1777                                         int xx = (x - sds->res_min[0]) * block_size;
1778                                         int yy = (y - sds->res_min[1]) * block_size;
1779                                         int zz = (z - sds->res_min[2]) * block_size;
1780
1781                                         for (i = 0; i < block_size; i++)
1782                                                 for (j = 0; j < block_size; j++)
1783                                                         for (k = 0; k < block_size; k++)
1784                                                         {
1785                                                                 int big_index = smoke_get_index(xx + i, wt_res[0], yy + j, wt_res[1], zz + k);
1786                                                                 float den = (bigfuel) ? MAX2(bigdensity[big_index], bigfuel[big_index]) : bigdensity[big_index];
1787                                                                 if (den > max_den) {
1788                                                                         max_den = den;
1789                                                                 }
1790                                                         }
1791                                 }
1792
1793                                 /* content bounds (use shifted coordinates) */
1794                                 if (max_den >= sds->adapt_threshold) {
1795                                         if (min[0] > xn) min[0] = xn;
1796                                         if (min[1] > yn) min[1] = yn;
1797                                         if (min[2] > zn) min[2] = zn;
1798                                         if (max[0] < xn) max[0] = xn;
1799                                         if (max[1] < yn) max[1] = yn;
1800                                         if (max[2] < zn) max[2] = zn;
1801                                 }
1802
1803                                 /* velocity bounds */
1804                                 if (min_vel[0] > vx[index]) min_vel[0] = vx[index];
1805                                 if (min_vel[1] > vy[index]) min_vel[1] = vy[index];
1806                                 if (min_vel[2] > vz[index]) min_vel[2] = vz[index];
1807                                 if (max_vel[0] < vx[index]) max_vel[0] = vx[index];
1808                                 if (max_vel[1] < vy[index]) max_vel[1] = vy[index];
1809                                 if (max_vel[2] < vz[index]) max_vel[2] = vz[index];
1810                         }
1811
1812         /* also apply emission maps */
1813         for (int i = 0; i < numflowobj; i++) {
1814                 EmissionMap *em = &emaps[i];
1815
1816                 for (x = em->min[0]; x < em->max[0]; x++)
1817                         for (y = em->min[1]; y < em->max[1]; y++)
1818                                 for (z = em->min[2]; z < em->max[2]; z++)
1819                                 {
1820                                         int index = smoke_get_index(x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]);
1821                                         float max_den = em->influence[index];
1822
1823                                         /* density bounds */
1824                                         if (max_den >= sds->adapt_threshold) {
1825                                                 if (min[0] > x) min[0] = x;
1826                                                 if (min[1] > y) min[1] = y;
1827                                                 if (min[2] > z) min[2] = z;
1828                                                 if (max[0] < x) max[0] = x;
1829                                                 if (max[1] < y) max[1] = y;
1830                                                 if (max[2] < z) max[2] = z;
1831                                         }
1832                                 }
1833         }
1834
1835         /* calculate new bounds based on these values */
1836         mul_v3_fl(min_vel, 1.0f / sds->dx);
1837         mul_v3_fl(max_vel, 1.0f / sds->dx);
1838         clampBoundsInDomain(sds, min, max, min_vel, max_vel, sds->adapt_margin + 1, dt);
1839
1840         for (int i = 0; i < 3; i++) {
1841                 /* calculate new resolution */
1842                 res[i] = max[i] - min[i];
1843                 total_cells *= res[i];
1844
1845                 if (new_shift[i])
1846                         shift_changed = 1;
1847
1848                 /* if no content set minimum dimensions */
1849                 if (res[i] <= 0) {
1850                         int j;
1851                         for (j = 0; j < 3; j++) {
1852                                 min[j] = 0;
1853                                 max[j] = 1;
1854                                 res[j] = 1;
1855                         }
1856                         res_changed = 1;
1857                         total_cells = 1;
1858                         break;
1859                 }
1860                 if (min[i] != sds->res_min[i] || max[i] != sds->res_max[i])
1861                         res_changed = 1;
1862         }
1863
1864         if (res_changed || shift_changed) {
1865                 struct FLUID_3D *fluid_old = sds->fluid;
1866                 struct WTURBULENCE *turb_old = sds->wt;
1867                 /* allocate new fluid data */
1868                 smoke_reallocate_fluid(sds, sds->dx, res, 0);
1869                 if (sds->flags & MOD_SMOKE_HIGHRES) {
1870                         smoke_reallocate_highres_fluid(sds, sds->dx, res, 0);
1871                 }
1872
1873                 /* copy values from old fluid to new */
1874                 if (sds->total_cells > 1 && total_cells > 1) {
1875                         /* low res smoke */
1876                         float *o_dens, *o_react, *o_flame, *o_fuel, *o_heat, *o_heatold, *o_vx, *o_vy, *o_vz, *o_r, *o_g, *o_b;
1877                         float *n_dens, *n_react, *n_flame, *n_fuel, *n_heat, *n_heatold, *n_vx, *n_vy, *n_vz, *n_r, *n_g, *n_b;
1878                         float dummy;
1879                         unsigned char *dummy_p;
1880                         /* high res smoke */
1881                         int wt_res_old[3];
1882                         float *o_wt_dens, *o_wt_react, *o_wt_flame, *o_wt_fuel, *o_wt_tcu, *o_wt_tcv, *o_wt_tcw, *o_wt_r, *o_wt_g, *o_wt_b;
1883                         float *n_wt_dens, *n_wt_react, *n_wt_flame, *n_wt_fuel, *n_wt_tcu, *n_wt_tcv, *n_wt_tcw, *n_wt_r, *n_wt_g, *n_wt_b;
1884
1885                         smoke_export(fluid_old, &dummy, &dummy, &o_dens, &o_react, &o_flame, &o_fuel, &o_heat, &o_heatold, &o_vx, &o_vy, &o_vz, &o_r, &o_g, &o_b, &dummy_p);
1886                         smoke_export(sds->fluid, &dummy, &dummy, &n_dens, &n_react, &n_flame, &n_fuel, &n_heat, &n_heatold, &n_vx, &n_vy, &n_vz, &n_r, &n_g, &n_b, &dummy_p);
1887
1888                         if (sds->flags & MOD_SMOKE_HIGHRES) {
1889                                 smoke_turbulence_export(turb_old, &o_wt_dens, &o_wt_react, &o_wt_flame, &o_wt_fuel, &o_wt_r, &o_wt_g, &o_wt_b, &o_wt_tcu, &o_wt_tcv, &o_wt_tcw);
1890                                 smoke_turbulence_get_res(turb_old, wt_res_old);
1891                                 smoke_turbulence_export(sds->wt, &n_wt_dens, &n_wt_react, &n_wt_flame, &n_wt_fuel, &n_wt_r, &n_wt_g, &n_wt_b, &n_wt_tcu, &n_wt_tcv, &n_wt_tcw);
1892                         }
1893
1894
1895                         for (x = sds->res_min[0]; x < sds->res_max[0]; x++)
1896                                 for (y = sds->res_min[1]; y < sds->res_max[1]; y++)
1897                                         for (z = sds->res_min[2]; z < sds->res_max[2]; z++)
1898                                         {
1899                                                 /* old grid index */
1900                                                 int xo = x - sds->res_min[0];
1901                                                 int yo = y - sds->res_min[1];
1902                                                 int zo = z - sds->res_min[2];
1903                                                 int index_old = smoke_get_index(xo, sds->res[0], yo, sds->res[1], zo);
1904                                                 /* new grid index */
1905                                                 int xn = x - min[0] - new_shift[0];
1906                                                 int yn = y - min[1] - new_shift[1];
1907                                                 int zn = z - min[2] - new_shift[2];
1908                                                 int index_new = smoke_get_index(xn, res[0], yn, res[1], zn);
1909
1910                                                 /* skip if outside new domain */
1911                                                 if (xn < 0 || xn >= res[0] ||
1912                                                     yn < 0 || yn >= res[1] ||
1913                                                     zn < 0 || zn >= res[2])
1914                                                         continue;
1915
1916                                                 /* copy data */
1917                                                 n_dens[index_new] = o_dens[index_old];
1918                                                 /* heat */
1919                                                 if (n_heat && o_heat) {
1920                                                         n_heat[index_new] = o_heat[index_old];
1921                                                         n_heatold[index_new] = o_heatold[index_old];
1922                                                 }
1923                                                 /* fuel */
1924                                                 if (n_fuel && o_fuel) {
1925                                                         n_flame[index_new] = o_flame[index_old];
1926                                                         n_fuel[index_new] = o_fuel[index_old];
1927                                                         n_react[index_new] = o_react[index_old];
1928                                                 }
1929                                                 /* color */
1930                                                 if (o_r && n_r) {
1931                                                         n_r[index_new] = o_r[index_old];
1932                                                         n_g[index_new] = o_g[index_old];
1933                                                         n_b[index_new] = o_b[index_old];
1934                                                 }
1935                                                 n_vx[index_new] = o_vx[index_old];
1936                                                 n_vy[index_new] = o_vy[index_old];
1937                                                 n_vz[index_new] = o_vz[index_old];
1938
1939                                                 if (sds->flags & MOD_SMOKE_HIGHRES && turb_old) {
1940                                                         int i, j, k;
1941                                                         /* old grid index */
1942                                                         int xx_o = xo * block_size;
1943                                                         int yy_o = yo * block_size;
1944                                                         int zz_o = zo * block_size;
1945                                                         /* new grid index */
1946                                                         int xx_n = xn * block_size;
1947                                                         int yy_n = yn * block_size;
1948                                                         int zz_n = zn * block_size;
1949
1950                                                         n_wt_tcu[index_new] = o_wt_tcu[index_old];
1951                                                         n_wt_tcv[index_new] = o_wt_tcv[index_old];
1952                                                         n_wt_tcw[index_new] = o_wt_tcw[index_old];
1953
1954                                                         for (i = 0; i < block_size; i++)
1955                                                                 for (j = 0; j < block_size; j++)
1956                                                                         for (k = 0; k < block_size; k++)
1957                                                                         {
1958                                                                                 int big_index_old = smoke_get_index(xx_o + i, wt_res_old[0], yy_o + j, wt_res_old[1], zz_o + k);
1959                                                                                 int big_index_new = smoke_get_index(xx_n + i, sds->res_wt[0], yy_n + j, sds->res_wt[1], zz_n + k);
1960                                                                                 /* copy data */
1961                                                                                 n_wt_dens[big_index_new] = o_wt_dens[big_index_old];
1962                                                                                 if (n_wt_flame && o_wt_flame) {
1963                                                                                         n_wt_flame[big_index_new] = o_wt_flame[big_index_old];
1964                                                                                         n_wt_fuel[big_index_new] = o_wt_fuel[big_index_old];
1965                                                                                         n_wt_react[big_index_new] = o_wt_react[big_index_old];
1966                                                                                 }
1967                                                                                 if (n_wt_r && o_wt_r) {
1968                                                                                         n_wt_r[big_index_new] = o_wt_r[big_index_old];
1969                                                                                         n_wt_g[big_index_new] = o_wt_g[big_index_old];
1970                                                                                         n_wt_b[big_index_new] = o_wt_b[big_index_old];
1971                                                                                 }
1972                                                                         }
1973                                                 }
1974                                         }
1975                 }
1976                 smoke_free(fluid_old);
1977                 if (turb_old)
1978                         smoke_turbulence_free(turb_old);
1979
1980                 /* set new domain dimensions */
1981                 VECCOPY(sds->res_min, min);
1982                 VECCOPY(sds->res_max, max);
1983                 VECCOPY(sds->res, res);
1984                 sds->total_cells = total_cells;
1985         }
1986 }
1987
1988 BLI_INLINE void apply_outflow_fields(int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b)
1989 {
1990         density[index] = 0.f;
1991         if (heat) {
1992                 heat[index] = 0.f;
1993         }
1994         if (fuel) {
1995                 fuel[index] = 0.f;
1996                 react[index] = 0.f;
1997         }
1998         if (color_r) {
1999                 color_r[index] = 0.f;
2000                 color_g[index] = 0.f;
2001                 color_b[index] = 0.f;
2002         }
2003 }
2004
2005 BLI_INLINE void apply_inflow_fields(SmokeFlowSettings *sfs, float emission_value, int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b)
2006 {
2007         int absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE);
2008         float dens_old = density[index];
2009         // float fuel_old = (fuel) ? fuel[index] : 0.0f;  /* UNUSED */
2010         float dens_flow = (sfs->type == MOD_SMOKE_FLOW_TYPE_FIRE) ? 0.0f : emission_value * sfs->density;
2011         float fuel_flow = emission_value * sfs->fuel_amount;
2012         /* add heat */
2013         if (heat && emission_value > 0.0f) {
2014                 heat[index] = ADD_IF_LOWER(heat[index], sfs->temp);
2015         }
2016         /* absolute */
2017         if (absolute_flow) {
2018                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
2019                         if (dens_flow > density[index])
2020                                 density[index] = dens_flow;
2021                 }
2022                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && fuel_flow) {
2023                         if (fuel_flow > fuel[index])
2024                                 fuel[index] = fuel_flow;
2025                 }
2026         }
2027         /* additive */
2028         else {
2029                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
2030                         density[index] += dens_flow;
2031                         CLAMP(density[index], 0.0f, 1.0f);
2032                 }
2033                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && sfs->fuel_amount) {
2034                         fuel[index] += fuel_flow;
2035                         CLAMP(fuel[index], 0.0f, 10.0f);
2036                 }
2037         }
2038
2039         /* set color */
2040         if (color_r && dens_flow) {
2041                 float total_dens = density[index] / (dens_old + dens_flow);
2042                 color_r[index] = (color_r[index] + sfs->color[0] * dens_flow) * total_dens;
2043                 color_g[index] = (color_g[index] + sfs->color[1] * dens_flow) * total_dens;
2044                 color_b[index] = (color_b[index] + sfs->color[2] * dens_flow) * total_dens;
2045         }
2046
2047         /* set fire reaction coordinate */
2048         if (fuel && fuel[index] > FLT_EPSILON) {
2049                 /* instead of using 1.0 for all new fuel add slight falloff
2050                  * to reduce flow blockiness */
2051                 float value = 1.0f - pow2f(1.0f - emission_value);
2052
2053                 if (value > react[index]) {
2054                         float f = fuel_flow / fuel[index];
2055                         react[index] = value * f + (1.0f - f) * react[index];
2056                         CLAMP(react[index], 0.0f, value);
2057                 }
2058         }
2059 }
2060
2061 static void update_flowsfluids(Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt, bool for_render)
2062 {
2063         Object **flowobjs = NULL;
2064         EmissionMap *emaps = NULL;
2065         unsigned int numflowobj = 0;
2066         unsigned int flowIndex;
2067         int new_shift[3] = {0};
2068         int active_fields = sds->active_fields;
2069
2070         /* calculate domain shift for current frame if using adaptive domain */
2071         if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
2072                 int total_shift[3];
2073                 float frame_shift_f[3];
2074                 float ob_loc[3] = {0};
2075
2076                 mul_m4_v3(ob->obmat, ob_loc);
2077
2078                 VECSUB(frame_shift_f, ob_loc, sds->prev_loc);
2079                 copy_v3_v3(sds->prev_loc, ob_loc);
2080                 /* convert global space shift to local "cell" space */
2081                 mul_mat3_m4_v3(sds->imat, frame_shift_f);
2082                 frame_shift_f[0] = frame_shift_f[0] / sds->cell_size[0];
2083                 frame_shift_f[1] = frame_shift_f[1] / sds->cell_size[1];
2084                 frame_shift_f[2] = frame_shift_f[2] / sds->cell_size[2];
2085                 /* add to total shift */
2086                 VECADD(sds->shift_f, sds->shift_f, frame_shift_f);
2087                 /* convert to integer */
2088                 total_shift[0] = floor(sds->shift_f[0]);
2089                 total_shift[1] = floor(sds->shift_f[1]);
2090                 total_shift[2] = floor(sds->shift_f[2]);
2091                 VECSUB(new_shift, total_shift, sds->shift);
2092                 copy_v3_v3_int(sds->shift, total_shift);
2093
2094                 /* calculate new domain boundary points so that smoke doesnt slide on sub-cell movement */
2095                 sds->p0[0] = sds->dp0[0] - sds->cell_size[0] * (sds->shift_f[0] - total_shift[0] - 0.5f);
2096                 sds->p0[1] = sds->dp0[1] - sds->cell_size[1] * (sds->shift_f[1] - total_shift[1] - 0.5f);
2097                 sds->p0[2] = sds->dp0[2] - sds->cell_size[2] * (sds->shift_f[2] - total_shift[2] - 0.5f);
2098                 sds->p1[0] = sds->p0[0] + sds->cell_size[0] * sds->base_res[0];
2099                 sds->p1[1] = sds->p0[1] + sds->cell_size[1] * sds->base_res[1];
2100                 sds->p1[2] = sds->p0[2] + sds->cell_size[2] * sds->base_res[2];
2101         }
2102
2103         flowobjs = get_collisionobjects(scene, ob, sds->fluid_group, &numflowobj, eModifierType_Smoke);
2104
2105         /* init emission maps for each flow */
2106         emaps = MEM_callocN(sizeof(struct EmissionMap) * numflowobj, "smoke_flow_maps");
2107
2108         /* Prepare flow emission maps */
2109         for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
2110         {
2111                 Object *collob = flowobjs[flowIndex];
2112                 SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
2113
2114                 // check for initialized smoke object
2115                 if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
2116                 {
2117                         // we got nice flow object
2118                         SmokeFlowSettings *sfs = smd2->flow;
2119                         int subframes = sfs->subframes;
2120                         EmissionMap *em = &emaps[flowIndex];
2121
2122                         /* just sample flow directly to emission map if no subframes */
2123                         if (!subframes) {
2124                                 if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) {
2125                                         emit_from_particles(collob, sds, sfs, em, scene, dt);
2126                                 }
2127                                 else {
2128                                         emit_from_derivedmesh(collob, sds, sfs, em, dt);
2129                                 }
2130                         }
2131                         /* sample subframes */
2132                         else {
2133                                 int scene_frame = scene->r.cfra;
2134                                 // float scene_subframe = scene->r.subframe;  // UNUSED
2135                                 int subframe;
2136                                 for (subframe = 0; subframe <= subframes; subframe++) {
2137                                         EmissionMap em_temp = {NULL};
2138                                         float sample_size = 1.0f / (float)(subframes+1);
2139                                         float prev_frame_pos = sample_size * (float)(subframe+1);
2140                                         float sdt = dt * sample_size;
2141                                         int hires_multiplier = 1;
2142
2143                                         if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
2144                                                 hires_multiplier = sds->amplify + 1;
2145                                         }
2146
2147                                         /* set scene frame to match previous frame + subframe
2148                                          * or use current frame for last sample */
2149                                         if (subframe < subframes) {
2150                                                 scene->r.cfra = scene_frame - 1;
2151                                                 scene->r.subframe = prev_frame_pos;
2152                                         }
2153                                         else {
2154                                                 scene->r.cfra = scene_frame;
2155                                                 scene->r.subframe = 0.0f;
2156                                         }
2157
2158                                         if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) {
2159                                                 /* emit_from_particles() updates timestep internally */
2160                                                 emit_from_particles(collob, sds, sfs, &em_temp, scene, sdt);
2161                                                 if (!(sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE)) {
2162                                                         hires_multiplier = 1;
2163                                                 }
2164                                         }
2165                                         else { /* MOD_SMOKE_FLOW_SOURCE_MESH */
2166                                                 /* update flow object frame */
2167                                                 BLI_mutex_lock(&object_update_lock);
2168                                                 subframe_updateObject(scene, collob, 1, 5, BKE_scene_frame_get(scene), for_render);
2169                                                 BLI_mutex_unlock(&object_update_lock);
2170
2171                                                 /* apply flow */
2172                                                 emit_from_derivedmesh(collob, sds, sfs, &em_temp, sdt);
2173                                         }
2174
2175                                         /* combine emission maps */
2176                                         em_combineMaps(em, &em_temp, hires_multiplier, !(sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE), sample_size);
2177                                         em_freeData(&em_temp);
2178                                 }
2179                         }
2180
2181                         /* update required data fields */
2182                         if (em->total_cells && sfs->type != MOD_SMOKE_FLOW_TYPE_OUTFLOW) {
2183                                 /* activate heat field if flow produces any heat */
2184                                 if (sfs->temp) {
2185                                         active_fields |= SM_ACTIVE_HEAT;
2186                                 }
2187                                 /* activate fuel field if flow adds any fuel */
2188                                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && sfs->fuel_amount) {
2189                                         active_fields |= SM_ACTIVE_FIRE;
2190                                 }
2191                                 /* activate color field if flows add smoke with varying colors */
2192                                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE && sfs->density) {
2193                                         if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
2194                                                 copy_v3_v3(sds->active_color, sfs->color);
2195                                                 active_fields |= SM_ACTIVE_COLOR_SET;
2196                                         }
2197                                         else if (!equals_v3v3(sds->active_color, sfs->color)) {
2198                                                 active_fields |= SM_ACTIVE_COLORS;
2199                                         }
2200                                 }
2201                         }
2202                 }
2203         }
2204
2205         /* monitor active fields based on domain settings */
2206         /* if domain has fire, activate new fields if required */
2207         if (active_fields & SM_ACTIVE_FIRE) {
2208                 /* heat is always needed for fire */
2209                 active_fields |= SM_ACTIVE_HEAT;
2210                 /* also activate colors if domain smoke color differs from active color */
2211                 if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
2212                         copy_v3_v3(sds->active_color, sds->flame_smoke_color);
2213                         active_fields |= SM_ACTIVE_COLOR_SET;
2214                 }
2215                 else if (!equals_v3v3(sds->active_color, sds->flame_smoke_color)) {
2216                         active_fields |= SM_ACTIVE_COLORS;
2217                 }
2218         }
2219
2220         /* Adjust domain size if needed */
2221         if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
2222                 adjustDomainResolution(sds, new_shift, emaps, numflowobj, dt);
2223         }
2224
2225         /* Initialize new data fields if any */
2226         if (active_fields & SM_ACTIVE_HEAT) {
2227                 smoke_ensure_heat(sds->fluid);
2228         }
2229         if (active_fields & SM_ACTIVE_FIRE) {
2230                 smoke_ensure_fire(sds->fluid, sds->wt);
2231         }
2232         if (active_fields & SM_ACTIVE_COLORS) {
2233                 /* initialize all smoke with "active_color" */
2234                 smoke_ensure_colors(sds->fluid, sds->wt, sds->active_color[0], sds->active_color[1], sds->active_color[2]);
2235         }
2236         sds->active_fields = active_fields;
2237
2238         /* Apply emission data */
2239         if (sds->fluid) {
2240                 for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
2241                 {
2242                         Object *collob = flowobjs[flowIndex];
2243                         SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
2244
2245                         // check for initialized smoke object
2246                         if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
2247                         {
2248                                 // we got nice flow object
2249                                 SmokeFlowSettings *sfs = smd2->flow;
2250                                 EmissionMap *em = &emaps[flowIndex];
2251
2252                                 float *density = smoke_get_density(sds->fluid);
2253                                 float *color_r = smoke_get_color_r(sds->fluid);
2254                                 float *color_g = smoke_get_color_g(sds->fluid);
2255                                 float *color_b = smoke_get_color_b(sds->fluid);
2256                                 float *fuel = smoke_get_fuel(sds->fluid);
2257                                 float *react = smoke_get_react(sds->fluid);
2258                                 float *bigdensity = smoke_turbulence_get_density(sds->wt);
2259                                 float *bigfuel = smoke_turbulence_get_fuel(sds->wt);
2260                                 float *bigreact = smoke_turbulence_get_react(sds->wt);
2261                                 float *bigcolor_r = smoke_turbulence_get_color_r(sds->wt);
2262                                 float *bigcolor_g = smoke_turbulence_get_color_g(sds->wt);
2263                                 float *bigcolor_b = smoke_turbulence_get_color_b(sds->wt);
2264                                 float *heat = smoke_get_heat(sds->fluid);
2265                                 float *velocity_x = smoke_get_velocity_x(sds->fluid);
2266                                 float *velocity_y = smoke_get_velocity_y(sds->fluid);
2267                                 float *velocity_z = smoke_get_velocity_z(sds->fluid);
2268                                 //unsigned char *obstacle = smoke_get_obstacle(sds->fluid);
2269                                 // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid);
2270                                 int bigres[3];
2271                                 float *velocity_map = em->velocity;
2272                                 float *emission_map = em->influence;
2273                                 float *emission_map_high = em->influence_high;
2274
2275                                 int ii, jj, kk, gx, gy, gz, ex, ey, ez, dx, dy, dz, block_size;
2276                                 size_t e_index, d_index, index_big;
2277
2278                                 // loop through every emission map cell
2279                                 for (gx = em->min[0]; gx < em->max[0]; gx++)
2280                                         for (gy = em->min[1]; gy < em->max[1]; gy++)
2281                                                 for (gz = em->min[2]; gz < em->max[2]; gz++)
2282                                                 {
2283                                                         /* get emission map index */
2284                                                         ex = gx - em->min[0];
2285                                                         ey = gy - em->min[1];
2286                                                         ez = gz - em->min[2];
2287                                                         e_index = smoke_get_index(ex, em->res[0], ey, em->res[1], ez);
2288
2289                                                         /* get domain index */
2290                                                         dx = gx - sds->res_min[0];
2291                                                         dy = gy - sds->res_min[1];
2292                                                         dz = gz - sds->res_min[2];
2293                                                         d_index = smoke_get_index(dx, sds->res[0], dy, sds->res[1], dz);
2294                                                         /* make sure emission cell is inside the new domain boundary */
2295                                                         if (dx < 0 || dy < 0 || dz < 0 || dx >= sds->res[0] || dy >= sds->res[1] || dz >= sds->res[2]) continue;
2296
2297                                                         if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
2298                                                                 apply_outflow_fields(d_index, density, heat, fuel, react, color_r, color_g, color_b);
2299                                                         }
2300                                                         else { // inflow
2301                                                                 apply_inflow_fields(sfs, emission_map[e_index], d_index, density, heat, fuel, react, color_r, color_g, color_b);
2302
2303                                                                 /* initial velocity */
2304                                                                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
2305                                                                         velocity_x[d_index] = ADD_IF_LOWER(velocity_x[d_index], velocity_map[e_index * 3]);
2306                                                                         velocity_y[d_index] = ADD_IF_LOWER(velocity_y[d_index], velocity_map[e_index * 3 + 1]);
2307                                                                         velocity_z[d_index] = ADD_IF_LOWER(velocity_z[d_index], velocity_map[e_index * 3 + 2]);
2308                                                                 }
2309                                                         }
2310
2311                                                         /* loop through high res blocks if high res enabled */
2312                                                         if (bigdensity) {
2313                                                                 // neighbor cell emission densities (for high resolution smoke smooth interpolation)
2314                                                                 float c000, c001, c010, c011,  c100, c101, c110, c111;
2315
2316                                                                 smoke_turbulence_get_res(sds->wt, bigres);
2317                                                                 block_size = sds->amplify + 1;  // high res block size
2318
2319                                                                 c000 = (ex > 0 && ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez - 1)] : 0;
2320                                                                 c001 = (ex > 0 && ey > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez)] : 0;
2321                                                                 c010 = (ex > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez - 1)] : 0;
2322                                                                 c011 = (ex > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez)] : 0;
2323
2324                                                                 c100 = (ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez - 1)] : 0;
2325                                                                 c101 = (ey > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez)] : 0;
2326                                                                 c110 = (ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez - 1)] : 0;
2327                                                                 c111 = emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez)]; // this cell
2328
2329                                                                 for (ii = 0; ii < block_size; ii++)
2330                                                                         for (jj = 0; jj < block_size; jj++)
2331                                                                                 for (kk = 0; kk < block_size; kk++)
2332                                                                                 {
2333
2334                                                                                         float fx, fy, fz, interpolated_value;
2335                                                                                         int shift_x = 0, shift_y = 0, shift_z = 0;
2336
2337
2338                                                                                         /* Use full sample emission map if enabled and available */
2339                                                                                         if ((sds->highres_sampling == SM_HRES_FULLSAMPLE) && emission_map_high) {
2340                                                                                                 interpolated_value = emission_map_high[smoke_get_index(ex * block_size + ii, em->res[0] * block_size, ey * block_size + jj, em->res[1] * block_size, ez * block_size + kk)]; // this cell
2341                                                                                         }
2342                                                                                         else if (sds->highres_sampling == SM_HRES_NEAREST) {
2343                                                                                                 /* without interpolation use same low resolution
2344                                                                                                  * block value for all hi-res blocks */
2345                                                                                                 interpolated_value = c111;
2346                                                                                         }
2347                                                                                         /* Fall back to interpolated */
2348                                                                                         else
2349                                                                                         {
2350                                                                                                 /* get relative block position
2351                                                                                                  * for interpolation smoothing */
2352                                                                                                 fx = (float)ii / block_size + 0.5f / block_size;
2353                                                                                                 fy = (float)jj / block_size + 0.5f / block_size;
2354                                                                                                 fz = (float)kk / block_size + 0.5f / block_size;
2355
2356                                                                                                 /* calculate trilinear interpolation */
2357                                                                                                 interpolated_value = c000 * (1 - fx) * (1 - fy) * (1 - fz) +
2358                                                                                                                      c100 * fx * (1 - fy) * (1 - fz) +
2359                                                                                                                      c010 * (1 - fx) * fy * (1 - fz) +
2360                                                                                                                      c001 * (1 - fx) * (1 - fy) * fz +
2361                                                                                                                      c101 * fx * (1 - fy) * fz +
2362                                                                                                                      c011 * (1 - fx) * fy * fz +
2363                                                                                                                      c110 * fx * fy * (1 - fz) +
2364                                                                                                                      c111 * fx * fy * fz;
2365
2366
2367                                                                                                 /* add some contrast / sharpness
2368                                                                                                  * depending on hi-res block size */
2369                                                                                                 interpolated_value = (interpolated_value - 0.4f) * (block_size / 2) + 0.4f;
2370                                                                                                 CLAMP(interpolated_value, 0.0f, 1.0f);
2371
2372                                                                                                 /* shift smoke block index
2373                                                                                                  * (because pixel center is actually
2374                                                                                                  * in halfway of the low res block) */
2375                                                                                                 shift_x = (dx < 1) ? 0 : block_size / 2;
2376                                                                                                 shift_y = (dy < 1) ? 0 : block_size / 2;
2377                                                                                                 shift_z = (dz < 1) ? 0 : block_size / 2;
2378                                                                                         }
2379
2380                                                                                         /* get shifted index for current high resolution block */
2381                                                                                         index_big = smoke_get_index(block_size * dx + ii - shift_x, bigres[0], block_size * dy + jj - shift_y, bigres[1], block_size * dz + kk - shift_z);
2382
2383                                                                                         if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
2384                                                                                                 if (interpolated_value) {
2385                                                                                                         apply_outflow_fields(index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
2386                                                                                                 }
2387                                                                                         }
2388                                                                                         else { // inflow
2389                                                                                                 apply_inflow_fields(sfs, interpolated_value, index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
2390                                                                                         }
2391                                                                                 } // hires loop
2392                                                         }  // bigdensity
2393                                                 } // low res loop
2394
2395                                 // free emission maps
2396                                 em_freeData(em);
2397
2398                         } // end emission
2399                 }
2400         }
2401
2402         if (flowobjs)
2403                 MEM_freeN(flowobjs);
2404         if (emaps)
2405                 MEM_freeN(emaps);
2406 }
2407
2408 static void update_effectors(Scene *scene, Object *ob, SmokeDomainSettings *sds, float UNUSED(dt))
2409 {
2410         ListBase *effectors;
2411         /* make sure smoke flow influence is 0.0f */
2412         sds->effector_weights->weight[PFIELD_SMOKEFLOW] = 0.0f;
2413         effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights, true);
2414
2415         if (effectors)
2416         {
2417                 float *density = smoke_get_density(sds->fluid);
2418                 float *fuel = smoke_get_fuel(sds->fluid);
2419                 float *force_x = smoke_get_force_x(sds->fluid);
2420                 float *force_y = smoke_get_force_y(sds->fluid);
2421                 float *force_z = smoke_get_force_z(sds->fluid);
2422                 float *velocity_x = smoke_get_velocity_x(sds->fluid);
2423                 float *velocity_y = smoke_get_velocity_y(sds->fluid);
2424                 float *velocity_z = smoke_get_velocity_z(sds->fluid);
2425                 unsigned char *obstacle = smoke_get_obstacle(sds->fluid);
2426                 int x;
2427
2428                 // precalculate wind forces
2429 #pragma omp parallel for schedule(static)
2430                 for (x = 0; x < sds->res[0]; x++)
2431                 {
2432                         int y, z;
2433                         for (y = 0; y < sds->res[1]; y++)
2434                                 for (z = 0; z < sds->res[2]; z++)
2435                                 {
2436                                         EffectedPoint epoint;
2437                                         float mag;
2438                                         float voxelCenter[3] = {0, 0, 0}, vel[3] = {0, 0, 0}, retvel[3] = {0, 0, 0};
2439                                         unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
2440
2441                                         if (((fuel ? MAX2(density[index], fuel[index]) : density[index]) < FLT_EPSILON) || obstacle[index])
2442                                                 continue;
2443
2444                                         vel[0] = velocity_x[index];
2445                                         vel[1] = velocity_y[index];
2446                                         vel[2] = velocity_z[index];
2447
2448                                         /* convert vel to global space */
2449                                         mag = len_v3(vel);
2450                                         mul_mat3_m4_v3(sds->obmat, vel);
2451                                         normalize_v3(vel);
2452                                         mul_v3_fl(vel, mag);
2453
2454                                         voxelCenter[0] = sds->p0[0] + sds->cell_size[0] * ((float)(x + sds->res_min[0]) + 0.5f);
2455                                         voxelCenter[1] = sds->p0[1] + sds->cell_size[1] * ((float)(y + sds->res_min[1]) + 0.5f);
2456                                         voxelCenter[2] = sds->p0[2] + sds->cell_size[2] * ((float)(z + sds->res_min[2]) + 0.5f);
2457                                         mul_m4_v3(sds->obmat, voxelCenter);
2458
2459                                         pd_point_from_loc(scene, voxelCenter, vel, index, &epoint);
2460                                         pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
2461
2462                                         /* convert retvel to local space */
2463                                         mag = len_v3(retvel);
2464                                         mul_mat3_m4_v3(sds->imat, retvel);
2465                                         normalize_v3(retvel);
2466                                         mul_v3_fl(retvel, mag);
2467
2468                                         // TODO dg - do in force!
2469                                         force_x[index] = min_ff(max_ff(-1.0f, retvel[0] * 0.2f), 1.0f);
2470                                         force_y[index] = min_ff(max_ff(-1.0f, retvel[1] * 0.2f), 1.0f);
2471                                         force_z[index] = min_ff(max_ff(-1.0f, retvel[2] * 0.2f), 1.0f);
2472                                 }
2473                 }
2474         }
2475
2476         pdEndEffectors(&effectors);
2477 }
2478
2479 static void step(Scene *scene, Object *ob, SmokeModifierData *smd, DerivedMesh *domain_dm, float fps, bool for_render)
2480 {
2481         SmokeDomainSettings *sds = smd->domain;
2482         /* stability values copied from wturbulence.cpp */
2483         const int maxSubSteps = 25;
2484         float maxVel;
2485         // maxVel should be 1.5 (1.5 cell max movement) * dx (cell size)
2486
2487         float dt;
2488         float maxVelMag = 0.0f;
2489         int totalSubsteps;
2490         int substep = 0;
2491         float dtSubdiv;
2492         float gravity[3] = {0.0f, 0.0f, -1.0f};
2493         float gravity_mag;
2494
2495 #if 0  /* UNUSED */
2496            /* get max velocity and lower the dt value if it is too high */
2497         size_t size = sds->res[0] * sds->res[1] * sds->res[2];
2498         float *velX = smoke_get_velocity_x(sds->fluid);
2499         float *velY = smoke_get_velocity_y(sds->fluid);
2500         float *velZ = smoke_get_velocity_z(sds->fluid);
2501         size_t i;
2502 #endif
2503
2504         /* update object state */
2505         invert_m4_m4(sds->imat, ob->obmat);
2506         copy_m4_m4(sds->obmat, ob->obmat);
2507         smoke_set_domain_from_derivedmesh(sds, ob, domain_dm, (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) != 0);
2508
2509         /* use global gravity if enabled */
2510         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
2511                 copy_v3_v3(gravity, scene->physics_settings.gravity);
2512                 /* map default value to 1.0 */
2513                 mul_v3_fl(gravity, 1.0f / 9.810f);
2514         }
2515         /* convert gravity to domain space */
2516         gravity_mag = len_v3(gravity);
2517         mul_mat3_m4_v3(sds->imat, gravity);
2518         normalize_v3(gravity);
2519         mul_v3_fl(gravity, gravity_mag);
2520
2521         /* adapt timestep for different framerates, dt = 0.1 is at 25fps */
2522         dt = DT_DEFAULT * (25.0f / fps);
2523         // maximum timestep/"CFL" constraint: dt < 5.0 *dx / maxVel
2524         maxVel = (sds->dx * 5.0f);
2525
2526 #if 0
2527         for (i = 0; i < size; i++) {
2528                 float vtemp = (velX[i] * velX[i] + velY[i] * velY[i] + velZ[i] * velZ[i]);
2529                 if (vtemp > maxVelMag)
2530                         maxVelMag = vtemp;
2531         }
2532 #endif
2533
2534         maxVelMag = sqrtf(maxVelMag) * dt * sds->time_scale;
2535         totalSubsteps = (int)((maxVelMag / maxVel) + 1.0f); /* always round up */
2536         totalSubsteps = (totalSubsteps < 1) ? 1 : totalSubsteps;
2537         totalSubsteps = (totalSubsteps > maxSubSteps) ? maxSubSteps : totalSubsteps;
2538
2539         /* Disable substeps for now, since it results in numerical instability */
2540         totalSubsteps = 1.0f;
2541
2542         dtSubdiv = (float)dt / (float)totalSubsteps;
2543
2544         // printf("totalSubsteps: %d, maxVelMag: %f, dt: %f\n", totalSubsteps, maxVelMag, dt);
2545
2546         for (substep = 0; substep < totalSubsteps; substep++)
2547         {
2548                 // calc animated obstacle velocities
2549                 update_flowsfluids(scene, ob, sds, dtSubdiv, for_render);
2550                 update_obstacles(scene, ob, sds, dtSubdiv, substep, totalSubsteps);
2551
2552                 if (sds->total_cells > 1) {
2553                         update_effectors(scene, ob, sds, dtSubdiv); // DG TODO? problem --> uses forces instead of velocity, need to check how they need to be changed with variable dt
2554                         smoke_step(sds->fluid, gravity, dtSubdiv);
2555                 }
2556         }
2557 }
2558
2559 static DerivedMesh *createDomainGeometry(SmokeDomainSettings *sds, Object *ob)
2560 {
2561         DerivedMesh *result;
2562         MVert *mverts;
2563         MPoly *mpolys;
2564         MLoop *mloops;
2565         float min[3];
2566         float max[3];
2567         float *co;
2568         MPoly *mp;
2569         MLoop *ml;
2570
2571         int num_verts = 8;
2572         int num_faces = 6;
2573         int i;
2574         float ob_loc[3] = {0};
2575         float ob_cache_loc[3] = {0};
2576
2577         /* dont generate any mesh if there isnt any content */
2578         if (sds->total_cells <= 1) {
2579                 num_verts = 0;
2580                 num_faces = 0;
2581         }
2582
2583         result = CDDM_new(num_verts, 0, 0, num_faces * 4, num_faces);
2584         mverts = CDDM_get_verts(result);
2585         mpolys = CDDM_get_polys(result);
2586         mloops = CDDM_get_loops(result);
2587
2588
2589         if (num_verts) {
2590                 /* volume bounds */
2591                 VECMADD(min, sds->p0, sds->cell_size, sds->res_min);
2592                 VECMADD(max, sds->p0, sds->cell_size, sds->res_max);
2593
2594                 /* set vertices */
2595                 /* top slab */
2596                 co = mverts[0].co; co[0] = min[0]; co[1] = min[1]; co[2] = max[2];
2597                 co = mverts[1].co; co[0] = max[0]; co[1] = min[1]; co[2] = max[2];
2598                 co = mverts[2].co; co[0] = max[0]; co[1] = max[1]; co[2] = max[2];
2599                 co = mverts[3].co; co[0] = min[0]; co[1] = max[1]; co[2] = max[2];
2600                 /* bottom slab */
2601                 co = mverts[4].co; co[0] = min[0]; co[1] = min[1]; co[2] = min[2];
2602                 co = mverts[5].co; co[0] = max[0]; co[1] = min[1]; co[2] = min[2];
2603                 co = mverts[6].co; co[0] = max[0]; co[1] = max[1]; co[2] = min[2];
2604                 co = mverts[7].co; co[0] = min[0]; co[1] = max[1]; co[2] = min[2];
2605
2606                 /* create faces */
2607                 /* top */
2608                 mp = &mpolys[0]; ml = &mloops[0 * 4]; mp->loopstart = 0 * 4; mp->totloop = 4;
2609                 ml[0].v = 0; ml[1].v = 1; ml[2].v = 2; ml[3].v = 3;
2610                 /* right */
2611                 mp = &mpolys[1]; ml = &mloops[1 * 4]; mp->loopstart = 1 * 4; mp->totloop = 4;
2612                 ml[0].v = 2; ml[1].v = 1; ml[2].v = 5; ml[3].v = 6;
2613                 /* bottom */
2614                 mp = &mpolys[2]; ml = &mloops[2 * 4]; mp->loopstart = 2 * 4; mp->totloop = 4;
2615                 ml[0].v = 7; ml[1].v = 6; ml[2].v = 5; ml[3].v = 4;
2616                 /* left */
2617                 mp = &mpolys[3]; ml = &mloops[3 * 4]; mp->loopstart = 3 * 4; mp->totloop = 4;
2618                 ml[0].v = 0; ml[1].v = 3; ml[2].v = 7; ml[3].v = 4;
2619                 /* front */
2620                 mp = &mpolys[4]; ml = &mloops[4 * 4]; mp->loopstart = 4 * 4; mp->totloop = 4;
2621                 ml[0].v = 3; ml[1].v = 2; ml[2].v = 6; ml[3].v = 7;
2622                 /* back */
2623                 mp = &mpolys[5]; ml = &mloops[5 * 4]; mp->loopstart = 5 * 4; mp->totloop = 4;
2624                 ml[0].v = 1; ml[1].v = 0; ml[2].v = 4; ml[3].v = 5;
2625
2626                 /* calculate required shift to match domain's global position
2627                  *  it was originally simulated at (if object moves without smoke step) */
2628                 invert_m4_m4(ob->imat, ob->obmat);
2629                 mul_m4_v3(ob->obmat, ob_loc);
2630                 mul_m4_v3(sds->obmat, ob_cache_loc);
2631                 VECSUB(sds->obj_shift_f, ob_cache_loc, ob_loc);
2632                 /* convert shift to local space and apply to vertices */
2633                 mul_mat3_m4_v3(ob->imat, sds->obj_shift_f);
2634                 /* apply */
2635                 for (i = 0; i < num_verts; i++) {
2636                         add_v3_v3(mverts[i].co, sds->obj_shift_f);
2637                 }
2638         }
2639
2640
2641         CDDM_calc_edges(result);
2642         result->dirty |= DM_DIRTY_NORMALS;
2643         return result;
2644 }
2645
2646 static void smokeModifier_process(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm, bool for_render)
2647 {
2648         if ((smd->type & MOD_SMOKE_TYPE_FLOW))
2649         {
2650                 if (scene->r.cfra >= smd->time)
2651                         smokeModifier_init(smd, ob, scene, dm);
2652
2653                 if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm);
2654                 smd->flow->dm = CDDM_copy(dm);
2655                 DM_ensure_looptri(smd->flow->dm);
2656
2657                 if (scene->r.cfra > smd->time)
2658                 {
2659                         smd->time = scene->r.cfra;
2660                 }
2661                 else if (scene->r.cfra < smd->time)
2662                 {
2663                         smd->time = scene->r.cfra;
2664                         smokeModifier_reset_ex(smd, false);
2665                 }
2666         }
2667         else if (smd->type & MOD_SMOKE_TYPE_COLL)
2668         {
2669                 if (scene->r.cfra >= smd->time)
2670                         smokeModifier_init(smd, ob, scene, dm);
2671
2672                 if (smd->coll)
2673                 {
2674                         if (smd->coll->dm)
2675                                 smd->coll->dm->release(smd->coll->dm);
2676
2677                         smd->coll->dm = CDDM_copy(dm);
2678                         DM_ensure_looptri(smd->coll->dm);
2679                 }
2680
2681                 smd->time = scene->r.cfra;
2682                 if (scene->r.cfra < smd->time)
2683                 {
2684                         smokeModifier_reset_ex(smd, false);
2685                 }
2686         }
2687         else if (smd->type & MOD_SMOKE_TYPE_DOMAIN)
2688         {
2689                 SmokeDomainSettings *sds = smd->domain;
2690                 PointCache *cache = NULL;
2691                 PTCacheID pid;
2692                 int startframe, endframe, framenr;
2693                 float timescale;
2694
2695                 framenr = scene->r.cfra;
2696
2697                 //printf("time: %d\n", scene->r.cfra);
2698
2699                 cache = sds->point_cache[0];
2700                 BKE_ptcache_id_from_smoke(&pid, ob, smd);
2701                 BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
2702
2703                 if (!smd->domain->fluid || framenr == startframe)
2704                 {
2705                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
2706                         smokeModifier_reset_ex(smd, false);
2707                         BKE_ptcache_validate(cache, framenr);
2708                         cache->flag &= ~PTCACHE_REDO_NEEDED;
2709                 }
2710
2711                 if (!smd->domain->fluid && (framenr != startframe) && (smd->domain->flags & MOD_SMOKE_FILE_LOAD) == 0 && (cache->flag & PTCACHE_BAKED) == 0)
2712                         return;
2713
2714                 smd->domain->flags &= ~MOD_SMOKE_FILE_LOAD;
2715                 CLAMP(framenr, startframe, endframe);
2716
2717                 /* If already viewing a pre/after frame, no need to reload */
2718                 if ((smd->time == framenr) && (framenr != scene->r.cfra))
2719                         return;
2720
2721                 if (smokeModifier_init(smd, ob, scene, dm) == 0)
2722                 {
2723                         printf("bad smokeModifier_init\n");
2724                         return;
2725                 }
2726
2727                 /* try to read from cache */
2728                 if (BKE_ptcache_read(&pid, (float)framenr) == PTCACHE_READ_EXACT) {
2729                         BKE_ptcache_validate(cache, framenr);
2730                         smd->time = f