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