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