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