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