Merge branch 'master' into blender2.8
[blender.git] / source / blender / modifiers / intern / MOD_particleinstance.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) 2005 by the Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Dunbar
22  *                 Ton Roosendaal,
23  *                 Ben Batt,
24  *                 Brecht Van Lommel,
25  *                 Campbell Barton
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 /** \file blender/modifiers/intern/MOD_particleinstance.c
32  *  \ingroup modifiers
33  */
34
35
36 #include "DNA_meshdata_types.h"
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_math.h"
41 #include "BLI_listbase.h"
42 #include "BLI_rand.h"
43 #include "BLI_string.h"
44 #include "BLI_utildefines.h"
45
46 #include "BKE_cdderivedmesh.h"
47 #include "BKE_effect.h"
48 #include "BKE_global.h"
49 #include "BKE_lattice.h"
50 #include "BKE_library_query.h"
51 #include "BKE_modifier.h"
52 #include "BKE_particle.h"
53 #include "BKE_pointcache.h"
54
55 #include "DEG_depsgraph_build.h"
56
57 static void initData(ModifierData *md)
58 {
59         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
60
61         pimd->flag = eParticleInstanceFlag_Parents | eParticleInstanceFlag_Unborn |
62                      eParticleInstanceFlag_Alive | eParticleInstanceFlag_Dead;
63         pimd->psys = 1;
64         pimd->position = 1.0f;
65         pimd->axis = 2;
66         pimd->space = eParticleInstanceSpace_World;
67         pimd->particle_amount = 1.0f;
68         pimd->particle_offset = 0.0f;
69
70         STRNCPY(pimd->index_layer_name, "");
71         STRNCPY(pimd->value_layer_name, "");
72 }
73
74 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
75 {
76         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
77         CustomDataMask dataMask = 0;
78
79         if (pimd->index_layer_name[0] != '\0' ||
80             pimd->value_layer_name[0] != '\0')
81         {
82                 dataMask |= CD_MASK_MLOOPCOL;
83         }
84
85         return dataMask;
86
87 }
88
89 static bool isDisabled(ModifierData *md, int useRenderParams)
90 {
91         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
92         ParticleSystem *psys;
93         ModifierData *ob_md;
94
95         if (!pimd->ob)
96                 return true;
97
98         psys = BLI_findlink(&pimd->ob->particlesystem, pimd->psys - 1);
99         if (psys == NULL)
100                 return true;
101
102         /* If the psys modifier is disabled we cannot use its data.
103          * First look up the psys modifier from the object, then check if it is enabled.
104          */
105         for (ob_md = pimd->ob->modifiers.first; ob_md; ob_md = ob_md->next) {
106                 if (ob_md->type == eModifierType_ParticleSystem) {
107                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)ob_md;
108                         if (psmd->psys == psys) {
109                                 int required_mode;
110
111                                 if (useRenderParams) required_mode = eModifierMode_Render;
112                                 else required_mode = eModifierMode_Realtime;
113
114                                 if (!modifier_isEnabled(md->scene, ob_md, required_mode))
115                                         return true;
116
117                                 break;
118                         }
119                 }
120         }
121
122         return false;
123 }
124
125 static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
126 {
127         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
128         if (pimd->ob != NULL) {
129                 DEG_add_object_relation(ctx->node, pimd->ob, DEG_OB_COMP_TRANSFORM, "Particle Instance Modifier");
130                 DEG_add_object_relation(ctx->node, pimd->ob, DEG_OB_COMP_GEOMETRY, "Particle Instance Modifier");
131         }
132 }
133
134 static void foreachObjectLink(ModifierData *md, Object *ob,
135                               ObjectWalkFunc walk, void *userData)
136 {
137         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
138
139         walk(userData, ob, &pimd->ob, IDWALK_CB_NOP);
140 }
141
142 static bool particle_skip(ParticleInstanceModifierData *pimd, ParticleSystem *psys, int p)
143 {
144         const bool between = (psys->part->childtype == PART_CHILD_FACES);
145         ParticleData *pa;
146         int totpart, randp, minp, maxp;
147
148         if (p >= psys->totpart) {
149                 ChildParticle *cpa = psys->child + (p - psys->totpart);
150                 pa = psys->particles + (between? cpa->pa[0]: cpa->parent);
151         }
152         else {
153                 pa = psys->particles + p;
154         }
155
156         if (pa) {
157                 if (pa->alive == PARS_UNBORN && (pimd->flag & eParticleInstanceFlag_Unborn) == 0) return true;
158                 if (pa->alive == PARS_ALIVE && (pimd->flag & eParticleInstanceFlag_Alive) == 0) return true;
159                 if (pa->alive == PARS_DEAD && (pimd->flag & eParticleInstanceFlag_Dead) == 0) return true;
160         }
161
162         if (pimd->particle_amount == 1.0f) {
163                 /* Early output, all particles are to be instanced. */
164                 return false;
165         }
166
167         /* Randomly skip particles based on desired amount of visible particles. */
168
169         totpart = psys->totpart + psys->totchild;
170
171         /* TODO make randomization optional? */
172         randp = (int)(psys_frand(psys, 3578 + p) * totpart) % totpart;
173
174         minp = (int)(totpart * pimd->particle_offset) % (totpart+1);
175         maxp = (int)(totpart * (pimd->particle_offset + pimd->particle_amount)) % (totpart+1);
176
177         if (maxp > minp) {
178                 return randp < minp || randp >= maxp;
179         }
180         else if (maxp < minp) {
181                 return randp < minp && randp >= maxp;
182         }
183         else {
184                 return true;
185         }
186
187         return false;
188 }
189
190 static void store_float_in_vcol(MLoopCol *vcol, float float_value)
191 {
192         const uchar value = unit_float_to_uchar_clamp(float_value);
193         vcol->r = vcol->g = vcol->b = value;
194         vcol->a = 1.0f;
195 }
196
197 static DerivedMesh *applyModifier(ModifierData *md, const ModifierEvalContext *ctx,
198                                   DerivedMesh *derivedData)
199 {
200         DerivedMesh *dm = derivedData, *result;
201         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
202         ParticleSimulationData sim;
203         ParticleSystem *psys = NULL;
204         ParticleData *pa = NULL;
205         MPoly *mpoly, *orig_mpoly;
206         MLoop *mloop, *orig_mloop;
207         MVert *mvert, *orig_mvert;
208         int totvert, totpoly, totloop , totedge;
209         int maxvert, maxpoly, maxloop, maxedge, part_end = 0, part_start;
210         int k, p, p_skip;
211         short track = ctx->object->trackflag % 3, trackneg, axis = pimd->axis;
212         float max_co = 0.0, min_co = 0.0, temp_co[3];
213         float *size = NULL;
214         float spacemat[4][4];
215         const bool use_parents = pimd->flag & eParticleInstanceFlag_Parents;
216         const bool use_children = pimd->flag & eParticleInstanceFlag_Children;
217         bool between;
218
219         trackneg = ((ctx->object->trackflag > 2) ? 1 : 0);
220
221         if (pimd->ob == ctx->object) {
222                 pimd->ob = NULL;
223                 return derivedData;
224         }
225
226         if (pimd->ob) {
227                 psys = BLI_findlink(&pimd->ob->particlesystem, pimd->psys - 1);
228                 if (psys == NULL || psys->totpart == 0)
229                         return derivedData;
230         }
231         else {
232                 return derivedData;
233         }
234
235         part_start = use_parents ? 0 : psys->totpart;
236
237         part_end = 0;
238         if (use_parents)
239                 part_end += psys->totpart;
240         if (use_children)
241                 part_end += psys->totchild;
242
243         if (part_end == 0)
244                 return derivedData;
245
246         sim.depsgraph = ctx->depsgraph;
247         sim.scene = md->scene;
248         sim.ob = pimd->ob;
249         sim.psys = psys;
250         sim.psmd = psys_get_modifier(pimd->ob, psys);
251         between = (psys->part->childtype == PART_CHILD_FACES);
252
253         if (pimd->flag & eParticleInstanceFlag_UseSize) {
254                 float *si;
255                 si = size = MEM_calloc_arrayN(part_end, sizeof(float), "particle size array");
256
257                 if (pimd->flag & eParticleInstanceFlag_Parents) {
258                         for (p = 0, pa = psys->particles; p < psys->totpart; p++, pa++, si++)
259                                 *si = pa->size;
260                 }
261
262                 if (pimd->flag & eParticleInstanceFlag_Children) {
263                         ChildParticle *cpa = psys->child;
264
265                         for (p = 0; p < psys->totchild; p++, cpa++, si++) {
266                                 *si = psys_get_child_size(psys, cpa, 0.0f, NULL);
267                         }
268                 }
269         }
270
271         switch (pimd->space) {
272                 case eParticleInstanceSpace_World:
273                         /* particle states are in world space already */
274                         unit_m4(spacemat);
275                         break;
276                 case eParticleInstanceSpace_Local:
277                         /* get particle states in the particle object's local space */
278                         invert_m4_m4(spacemat, pimd->ob->obmat);
279                         break;
280                 default:
281                         /* should not happen */
282                         BLI_assert(false);
283                         break;
284         }
285
286         totvert = dm->getNumVerts(dm);
287         totpoly = dm->getNumPolys(dm);
288         totloop = dm->getNumLoops(dm);
289         totedge = dm->getNumEdges(dm);
290
291         /* count particles */
292         maxvert = 0;
293         maxpoly = 0;
294         maxloop = 0;
295         maxedge = 0;
296
297         for (p = part_start; p < part_end; p++) {
298                 if (particle_skip(pimd, psys, p))
299                         continue;
300
301                 maxvert += totvert;
302                 maxpoly += totpoly;
303                 maxloop += totloop;
304                 maxedge += totedge;
305         }
306
307         psys->lattice_deform_data = psys_create_lattice_deform_data(&sim);
308
309         if (psys->flag & (PSYS_HAIR_DONE | PSYS_KEYED) || psys->pointcache->flag & PTCACHE_BAKED) {
310                 float min[3], max[3];
311                 INIT_MINMAX(min, max);
312                 dm->getMinMax(dm, min, max);
313                 min_co = min[track];
314                 max_co = max[track];
315         }
316
317         result = CDDM_from_template(dm, maxvert, maxedge, 0, maxloop, maxpoly);
318
319         mvert = result->getVertArray(result);
320         orig_mvert = dm->getVertArray(dm);
321         mpoly = result->getPolyArray(result);
322         orig_mpoly = dm->getPolyArray(dm);
323         mloop = result->getLoopArray(result);
324         orig_mloop = dm->getLoopArray(dm);
325
326         MLoopCol *mloopcols_index = CustomData_get_layer_named(&result->loopData, CD_MLOOPCOL, pimd->index_layer_name);
327         MLoopCol *mloopcols_value = CustomData_get_layer_named(&result->loopData, CD_MLOOPCOL, pimd->value_layer_name);
328         int *vert_part_index = NULL;
329         float *vert_part_value = NULL;
330         if (mloopcols_index != NULL) {
331                 vert_part_index = MEM_calloc_arrayN(maxvert, sizeof(int), "vertex part index array");
332         }
333         if (mloopcols_value) {
334                 vert_part_value = MEM_calloc_arrayN(maxvert, sizeof(float), "vertex part value array");
335         }
336
337         for (p = part_start, p_skip = 0; p < part_end; p++) {
338                 float prev_dir[3];
339                 float frame[4]; /* frame orientation quaternion */
340                 float p_random = psys_frand(psys, 77091 + 283*p);
341
342                 /* skip particle? */
343                 if (particle_skip(pimd, psys, p))
344                         continue;
345
346                 /* set vertices coordinates */
347                 for (k = 0; k < totvert; k++) {
348                         ParticleKey state;
349                         MVert *inMV;
350                         int vindex = p_skip * totvert + k;
351                         MVert *mv = mvert + vindex;
352
353                         inMV = orig_mvert + k;
354                         DM_copy_vert_data(dm, result, k, p_skip * totvert + k, 1);
355                         *mv = *inMV;
356
357                         if (vert_part_index != NULL) {
358                                 vert_part_index[vindex] = p;
359                         }
360                         if (vert_part_value != NULL) {
361                                 vert_part_value[vindex] = p_random;
362                         }
363
364                         /*change orientation based on object trackflag*/
365                         copy_v3_v3(temp_co, mv->co);
366                         mv->co[axis] = temp_co[track];
367                         mv->co[(axis + 1) % 3] = temp_co[(track + 1) % 3];
368                         mv->co[(axis + 2) % 3] = temp_co[(track + 2) % 3];
369
370                         /* get particle state */
371                         if ((psys->flag & (PSYS_HAIR_DONE | PSYS_KEYED) || psys->pointcache->flag & PTCACHE_BAKED) &&
372                             (pimd->flag & eParticleInstanceFlag_Path))
373                         {
374                                 float ran = 0.0f;
375                                 if (pimd->random_position != 0.0f) {
376                                         ran = pimd->random_position * BLI_hash_frand(psys->seed + p);
377                                 }
378
379                                 if (pimd->flag & eParticleInstanceFlag_KeepShape) {
380                                         state.time = pimd->position * (1.0f - ran);
381                                 }
382                                 else {
383                                         state.time = (mv->co[axis] - min_co) / (max_co - min_co) * pimd->position * (1.0f - ran);
384
385                                         if (trackneg)
386                                                 state.time = 1.0f - state.time;
387
388                                         mv->co[axis] = 0.0;
389                                 }
390
391                                 psys_get_particle_on_path(&sim, p, &state, 1);
392
393                                 normalize_v3(state.vel);
394
395                                 /* Incrementally Rotating Frame (Bishop Frame) */
396                                 if (k == 0) {
397                                         float hairmat[4][4];
398                                         float mat[3][3];
399
400                                         if (p < psys->totpart)
401                                                 pa = psys->particles + p;
402                                         else {
403                                                 ChildParticle *cpa = psys->child + (p - psys->totpart);
404                                                 pa = psys->particles + (between? cpa->pa[0]: cpa->parent);
405                                         }
406                                         psys_mat_hair_to_global(sim.ob, sim.psmd->dm_final, sim.psys->part->from, pa, hairmat);
407                                         copy_m3_m4(mat, hairmat);
408                                         /* to quaternion */
409                                         mat3_to_quat(frame, mat);
410
411                                         if (pimd->rotation > 0.0f || pimd->random_rotation > 0.0f) {
412                                                 float angle = 2.0f*M_PI * (pimd->rotation + pimd->random_rotation * (psys_frand(psys, 19957323 + p) - 0.5f));
413                                                 float eul[3] = { 0.0f, 0.0f, angle };
414                                                 float rot[4];
415
416                                                 eul_to_quat(rot, eul);
417                                                 mul_qt_qtqt(frame, frame, rot);
418                                         }
419
420                                         /* note: direction is same as normal vector currently,
421                                          * but best to keep this separate so the frame can be
422                                          * rotated later if necessary
423                                          */
424                                         copy_v3_v3(prev_dir, state.vel);
425                                 }
426                                 else {
427                                         float rot[4];
428
429                                         /* incrementally rotate along bend direction */
430                                         rotation_between_vecs_to_quat(rot, prev_dir, state.vel);
431                                         mul_qt_qtqt(frame, rot, frame);
432
433                                         copy_v3_v3(prev_dir, state.vel);
434                                 }
435
436                                 copy_qt_qt(state.rot, frame);
437 #if 0
438                                 /* Absolute Frame (Frenet Frame) */
439                                 if (state.vel[axis] < -0.9999f || state.vel[axis] > 0.9999f) {
440                                         unit_qt(state.rot);
441                                 }
442                                 else {
443                                         float cross[3];
444                                         float temp[3] = {0.0f, 0.0f, 0.0f};
445                                         temp[axis] = 1.0f;
446
447                                         cross_v3_v3v3(cross, temp, state.vel);
448
449                                         /* state.vel[axis] is the only component surviving from a dot product with the axis */
450                                         axis_angle_to_quat(state.rot, cross, saacos(state.vel[axis]));
451                                 }
452 #endif
453                         }
454                         else {
455                                 state.time = -1.0;
456                                 psys_get_particle_state(&sim, p, &state, 1);
457                         }
458
459                         mul_qt_v3(state.rot, mv->co);
460                         if (pimd->flag & eParticleInstanceFlag_UseSize)
461                                 mul_v3_fl(mv->co, size[p]);
462                         add_v3_v3(mv->co, state.co);
463
464                         mul_m4_v3(spacemat, mv->co);
465                 }
466
467                 /* create edges and adjust edge vertex indices*/
468                 DM_copy_edge_data(dm, result, 0, p_skip * totedge, totedge);
469                 MEdge *me = CDDM_get_edges(result) + p_skip * totedge;
470                 for (k = 0; k < totedge; k++, me++) {
471                         me->v1 += p_skip * totvert;
472                         me->v2 += p_skip * totvert;
473                 }
474
475                 /* create polys and loops */
476                 for (k = 0; k < totpoly; k++) {
477
478                         MPoly *inMP = orig_mpoly + k;
479                         MPoly *mp = mpoly + p_skip * totpoly + k;
480
481                         DM_copy_poly_data(dm, result, k, p_skip * totpoly + k, 1);
482                         *mp = *inMP;
483                         mp->loopstart += p_skip * totloop;
484
485                         {
486                                 MLoop *inML = orig_mloop + inMP->loopstart;
487                                 MLoop *ml = mloop + mp->loopstart;
488                                 int j = mp->totloop;
489
490                                 DM_copy_loop_data(dm, result, inMP->loopstart, mp->loopstart, j);
491                                 for (; j; j--, ml++, inML++) {
492                                         ml->v = inML->v + (p_skip * totvert);
493                                         ml->e = inML->e + (p_skip * totedge);
494                                         const int ml_index = (ml - mloop);
495                                         if (mloopcols_index != NULL) {
496                                                 const int part_index = vert_part_index[ml->v];
497                                                 store_float_in_vcol(&mloopcols_index[ml_index], (float)part_index / psys->totpart);
498                                         }
499                                         if (mloopcols_value != NULL) {
500                                                 const float part_value = vert_part_value[ml->v];
501                                                 store_float_in_vcol(&mloopcols_value[ml_index], part_value);
502                                         }
503                                 }
504                         }
505                 }
506                 p_skip++;
507         }
508
509         if (psys->lattice_deform_data) {
510                 end_latt_deform(psys->lattice_deform_data);
511                 psys->lattice_deform_data = NULL;
512         }
513
514         if (size)
515                 MEM_freeN(size);
516
517         MEM_SAFE_FREE(vert_part_index);
518         MEM_SAFE_FREE(vert_part_value);
519
520         result->dirty |= DM_DIRTY_NORMALS;
521
522         return result;
523 }
524 ModifierTypeInfo modifierType_ParticleInstance = {
525         /* name */              "ParticleInstance",
526         /* structName */        "ParticleInstanceModifierData",
527         /* structSize */        sizeof(ParticleInstanceModifierData),
528         /* type */              eModifierTypeType_Constructive,
529         /* flags */             eModifierTypeFlag_AcceptsMesh |
530                                 eModifierTypeFlag_SupportsMapping |
531                                 eModifierTypeFlag_SupportsEditmode |
532                                 eModifierTypeFlag_EnableInEditmode,
533
534         /* copyData */          modifier_copyData_generic,
535
536         /* deformVerts_DM */    NULL,
537         /* deformMatrices_DM */ NULL,
538         /* deformVertsEM_DM */  NULL,
539         /* deformMatricesEM_DM*/NULL,
540         /* applyModifier_DM */  applyModifier,
541         /* applyModifierEM_DM */NULL,
542
543         /* deformVerts */       NULL,
544         /* deformMatrices */    NULL,
545         /* deformVertsEM */     NULL,
546         /* deformMatricesEM */  NULL,
547         /* applyModifier */     NULL,
548         /* applyModifierEM */   NULL,
549
550         /* initData */          initData,
551         /* requiredDataMask */  requiredDataMask,
552         /* freeData */          NULL,
553         /* isDisabled */        isDisabled,
554         /* updateDepsgraph */   updateDepsgraph,
555         /* dependsOnTime */     NULL,
556         /* dependsOnNormals */  NULL,
557         /* foreachObjectLink */ foreachObjectLink,
558         /* foreachIDLink */     NULL,
559         /* foreachTexLink */    NULL,
560 };