2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2007 by Janne Karhu.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): Raul Fernandez Hernandez (Farsthary), Stephen Swhitehorn.
27 * Copyright 2011-2012 AutoCRC
29 * ***** END GPL LICENSE BLOCK *****
32 /** \file blender/blenkernel/intern/particle_system.c
47 #include "MEM_guardedalloc.h"
49 #include "DNA_anim_types.h"
50 #include "DNA_boid_types.h"
51 #include "DNA_particle_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_modifier_types.h"
55 #include "DNA_object_force.h"
56 #include "DNA_object_types.h"
57 #include "DNA_curve_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_texture_types.h"
60 #include "DNA_listBase.h"
62 #include "BLI_utildefines.h"
63 #include "BLI_edgehash.h"
65 #include "BLI_jitter.h"
67 #include "BLI_blenlib.h"
68 #include "BLI_kdtree.h"
69 #include "BLI_kdopbvh.h"
72 #include "BLI_threads.h"
73 #include "BLI_linklist.h"
75 #include "BKE_animsys.h"
76 #include "BKE_boids.h"
77 #include "BKE_cdderivedmesh.h"
78 #include "BKE_collision.h"
79 #include "BKE_effect.h"
80 #include "BKE_library_query.h"
81 #include "BKE_particle.h"
82 #include "BKE_global.h"
84 #include "BKE_DerivedMesh.h"
85 #include "BKE_object.h"
86 #include "BKE_material.h"
87 #include "BKE_cloth.h"
88 #include "BKE_lattice.h"
89 #include "BKE_pointcache.h"
91 #include "BKE_modifier.h"
92 #include "BKE_scene.h"
93 #include "BKE_bvhutils.h"
94 #include "BKE_depsgraph.h"
98 #include "RE_shader_ext.h"
100 /* fluid sim particle import */
101 #ifdef WITH_MOD_FLUID
102 #include "DNA_object_fluidsim.h"
103 #include "LBM_fluidsim.h"
107 #endif // WITH_MOD_FLUID
109 static ThreadRWMutex psys_bvhtree_rwlock = BLI_RWLOCK_INITIALIZER;
111 /************************************************/
112 /* Reacting to system events */
113 /************************************************/
115 static int particles_are_dynamic(ParticleSystem *psys)
117 if (psys->pointcache->flag & PTCACHE_BAKED)
120 if (psys->part->type == PART_HAIR)
121 return psys->flag & PSYS_HAIR_DYNAMICS;
123 return ELEM(psys->part->phystype, PART_PHYS_NEWTON, PART_PHYS_BOIDS, PART_PHYS_FLUID);
126 float psys_get_current_display_percentage(ParticleSystem *psys)
128 ParticleSettings *part=psys->part;
130 if ((psys->renderdata && !particles_are_dynamic(psys)) || /* non-dynamic particles can be rendered fully */
131 (part->child_nbr && part->childtype) || /* display percentage applies to children */
132 (psys->pointcache->flag & PTCACHE_BAKING)) /* baking is always done with full amount */
137 return psys->part->disp/100.0f;
140 static int tot_particles(ParticleSystem *psys, PTCacheID *pid)
142 if (pid && psys->pointcache->flag & PTCACHE_EXTERNAL)
143 return pid->cache->totpoint;
144 else if (psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT)
145 return psys->part->grid_res * psys->part->grid_res * psys->part->grid_res - psys->totunexist;
147 return psys->part->totpart - psys->totunexist;
150 void psys_reset(ParticleSystem *psys, int mode)
154 if (ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
155 if (mode == PSYS_RESET_ALL || !(psys->flag & PSYS_EDITED)) {
156 /* don't free if not absolutely necessary */
157 if (psys->totpart != tot_particles(psys, NULL)) {
158 psys_free_particles(psys);
163 psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
165 if (psys->edit && psys->free_edit) {
166 psys->free_edit(psys->edit);
168 psys->free_edit = NULL;
172 else if (mode == PSYS_RESET_CACHE_MISS) {
173 /* set all particles to be skipped */
175 pa->flag |= PARS_NO_DISP;
180 MEM_freeN(psys->child);
186 /* reset path cache */
187 psys_free_path_cache(psys, psys->edit);
189 /* reset point cache */
190 BKE_ptcache_invalidate(psys->pointcache);
192 if (psys->fluid_springs) {
193 MEM_freeN(psys->fluid_springs);
194 psys->fluid_springs = NULL;
197 psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
200 static void realloc_particles(ParticleSimulationData *sim, int new_totpart)
202 ParticleSystem *psys = sim->psys;
203 ParticleSettings *part = psys->part;
204 ParticleData *newpars = NULL;
205 BoidParticle *newboids = NULL;
207 int totpart, totsaved = 0;
210 if ((part->distr == PART_DISTR_GRID) && (part->from != PART_FROM_VERT)) {
211 totpart= part->grid_res;
212 totpart*=totpart*totpart;
215 totpart=part->totpart;
220 if (totpart != psys->totpart) {
221 if (psys->edit && psys->free_edit) {
222 psys->free_edit(psys->edit);
224 psys->free_edit = NULL;
228 newpars= MEM_callocN(totpart*sizeof(ParticleData), "particles");
232 if (psys->part->phystype == PART_PHYS_BOIDS) {
233 newboids= MEM_callocN(totpart*sizeof(BoidParticle), "boid particles");
235 if (newboids == NULL) {
236 /* allocation error! */
244 if (psys->particles) {
245 totsaved=MIN2(psys->totpart,totpart);
248 memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
250 if (psys->particles->boid)
251 memcpy(newboids, psys->particles->boid, totsaved*sizeof(BoidParticle));
254 if (psys->particles->keys)
255 MEM_freeN(psys->particles->keys);
257 if (psys->particles->boid)
258 MEM_freeN(psys->particles->boid);
260 for (p=0, pa=newpars; p<totsaved; p++, pa++) {
267 for (p=totsaved, pa=psys->particles+totsaved; p<psys->totpart; p++, pa++)
268 if (pa->hair) MEM_freeN(pa->hair);
270 MEM_freeN(psys->particles);
274 psys->particles=newpars;
275 psys->totpart=totpart;
279 pa->boid = newboids++;
284 MEM_freeN(psys->child);
290 int psys_get_child_number(Scene *scene, ParticleSystem *psys)
294 if (!psys->part->childtype)
297 if (psys->renderdata)
298 nbr= psys->part->ren_child_nbr;
300 nbr= psys->part->child_nbr;
302 return get_render_child_particle_number(&scene->r, nbr, psys->renderdata != NULL);
305 int psys_get_tot_child(Scene *scene, ParticleSystem *psys)
307 return psys->totpart*psys_get_child_number(scene, psys);
310 /************************************************/
312 /************************************************/
314 void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
316 /* use for building derived mesh mapping info:
318 * node: the allocated links - total derived mesh element count
319 * nodearray: the array of nodes aligned with the base mesh's elements, so
320 * each original elements can reference its derived elements
322 Mesh *me= (Mesh*)ob->data;
323 bool use_modifier_stack= psys->part->use_modifier_stack;
326 /* CACHE LOCATIONS */
327 if (!dm->deformedOnly) {
328 /* Will use later to speed up subsurf/derivedmesh */
329 LinkNode *node, *nodedmelem, **nodearray;
330 int totdmelem, totelem, i, *origindex, *origindex_poly = NULL;
332 if (psys->part->from == PART_FROM_VERT) {
333 totdmelem= dm->getNumVerts(dm);
335 if (use_modifier_stack) {
340 totelem= me->totvert;
341 origindex= dm->getVertDataArray(dm, CD_ORIGINDEX);
344 else { /* FROM_FACE/FROM_VOLUME */
345 totdmelem= dm->getNumTessFaces(dm);
347 if (use_modifier_stack) {
350 origindex_poly= NULL;
353 totelem= me->totpoly;
354 origindex= dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
356 /* for face lookups we need the poly origindex too */
357 origindex_poly= dm->getPolyDataArray(dm, CD_ORIGINDEX);
358 if (origindex_poly == NULL) {
364 nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
365 nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
367 for (i=0, node=nodedmelem; i<totdmelem; i++, node++) {
369 node->link = SET_INT_IN_POINTER(i);
371 /* may be vertex or face origindex */
372 if (use_modifier_stack) {
376 origindex_final = origindex ? origindex[i] : ORIGINDEX_NONE;
378 /* if we have a poly source, do an index lookup */
379 if (origindex_poly && origindex_final != ORIGINDEX_NONE) {
380 origindex_final = origindex_poly[origindex_final];
384 if (origindex_final != ORIGINDEX_NONE && origindex_final < totelem) {
385 if (nodearray[origindex_final]) {
387 node->next = nodearray[origindex_final];
388 nodearray[origindex_final] = node;
391 nodearray[origindex_final] = node;
396 /* cache the verts/faces! */
399 pa->num_dmcache = DMCACHE_NOTFOUND;
403 if (use_modifier_stack) {
404 if (pa->num < totelem)
405 pa->num_dmcache = DMCACHE_ISCHILD;
407 pa->num_dmcache = DMCACHE_NOTFOUND;
410 if (psys->part->from == PART_FROM_VERT) {
411 if (pa->num < totelem && nodearray[pa->num])
412 pa->num_dmcache= GET_INT_FROM_POINTER(nodearray[pa->num]->link);
414 pa->num_dmcache = DMCACHE_NOTFOUND;
416 else { /* FROM_FACE/FROM_VOLUME */
417 /* Note that sometimes the pa->num is over the nodearray size, this is bad, maybe there is a better place to fix this,
418 * but for now passing NULL is OK. every face will be searched for the particle so its slower - Campbell */
419 pa->num_dmcache= psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, pa->num < totelem ? nodearray[pa->num] : NULL);
424 MEM_freeN(nodearray);
425 MEM_freeN(nodedmelem);
428 /* TODO PARTICLE, make the following line unnecessary, each function
429 * should know to use the num or num_dmcache, set the num_dmcache to
430 * an invalid value, just in case */
433 pa->num_dmcache = DMCACHE_NOTFOUND;
437 /* threaded child particle distribution and path caching */
438 void psys_thread_context_init(ParticleThreadContext *ctx, ParticleSimulationData *sim)
440 memset(ctx, 0, sizeof(ParticleThreadContext));
442 ctx->dm = ctx->sim.psmd->dm;
443 ctx->ma = give_current_material(sim->ob, sim->psys->part->omat);
446 #define MAX_PARTICLES_PER_TASK 256 /* XXX arbitrary - maybe use at least number of points instead for better balancing? */
448 BLI_INLINE int ceil_ii(int a, int b)
450 return (a + b - 1) / b;
453 void psys_tasks_create(ParticleThreadContext *ctx, int startpart, int endpart, ParticleTask **r_tasks, int *r_numtasks)
456 int numtasks = ceil_ii((endpart - startpart), MAX_PARTICLES_PER_TASK);
457 float particles_per_task = (float)(endpart - startpart) / (float)numtasks, p, pnext;
460 tasks = MEM_callocN(sizeof(ParticleTask) * numtasks, "ParticleThread");
461 *r_numtasks = numtasks;
464 p = (float)startpart;
465 for (i = 0; i < numtasks; i++, p = pnext) {
466 pnext = p + particles_per_task;
469 tasks[i].begin = (int)p;
470 tasks[i].end = min_ii((int)pnext, endpart);
474 void psys_tasks_free(ParticleTask *tasks, int numtasks)
479 for (i = 0; i < numtasks; ++i) {
481 BLI_rng_free(tasks[i].rng);
482 if (tasks[i].rng_path)
483 BLI_rng_free(tasks[i].rng_path);
489 void psys_thread_context_free(ParticleThreadContext *ctx)
493 MEM_freeN(ctx->vg_length);
495 MEM_freeN(ctx->vg_clump);
497 MEM_freeN(ctx->vg_kink);
499 MEM_freeN(ctx->vg_rough1);
501 MEM_freeN(ctx->vg_rough2);
503 MEM_freeN(ctx->vg_roughe);
505 if (ctx->sim.psys->lattice_deform_data) {
506 end_latt_deform(ctx->sim.psys->lattice_deform_data);
507 ctx->sim.psys->lattice_deform_data = NULL;
511 if (ctx->jit) MEM_freeN(ctx->jit);
512 if (ctx->jitoff) MEM_freeN(ctx->jitoff);
513 if (ctx->weight) MEM_freeN(ctx->weight);
514 if (ctx->index) MEM_freeN(ctx->index);
515 if (ctx->skip) MEM_freeN(ctx->skip);
516 if (ctx->seams) MEM_freeN(ctx->seams);
517 //if (ctx->vertpart) MEM_freeN(ctx->vertpart);
518 BLI_kdtree_free(ctx->tree);
521 static void initialize_particle_texture(ParticleSimulationData *sim, ParticleData *pa, int p)
523 ParticleSystem *psys = sim->psys;
524 ParticleSettings *part = psys->part;
525 ParticleTexture ptex;
527 psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f);
529 switch (part->type) {
531 if (ptex.exist < psys_frand(psys, p+125))
532 pa->flag |= PARS_UNEXIST;
533 pa->time = part->sta + (part->end - part->sta)*ptex.time;
536 if (ptex.exist < psys_frand(psys, p+125))
537 pa->flag |= PARS_UNEXIST;
545 /* set particle parameters that don't change during particle's life */
546 void initialize_particle(ParticleSimulationData *sim, ParticleData *pa)
548 ParticleSettings *part = sim->psys->part;
549 float birth_time = (float)(pa - sim->psys->particles) / (float)sim->psys->totpart;
551 pa->flag &= ~PARS_UNEXIST;
552 pa->time = part->sta + (part->end - part->sta) * birth_time;
555 /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
556 /* usage other than straight after distribute has to handle this index by itself - jahka*/
557 //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we don't have a derived mesh face */
560 static void initialize_all_particles(ParticleSimulationData *sim)
562 ParticleSystem *psys = sim->psys;
563 ParticleSettings *part = psys->part;
564 /* Grid distributionsets UNEXIST flag, need to take care of
565 * it here because later this flag is being reset.
567 * We can't do it for any distribution, because it'll then
568 * conflict with texture influence, which does not free
569 * unexisting particles and only sets flag.
571 * It's not so bad, because only grid distribution sets
574 const bool emit_from_volume_grid = (part->distr == PART_DISTR_GRID) &&
575 (!ELEM(part->from, PART_FROM_VERT, PART_FROM_CHILD));
578 if (!(emit_from_volume_grid && (pa->flag & PARS_UNEXIST) != 0)) {
579 initialize_particle(sim, pa);
584 static void free_unexisting_particles(ParticleSimulationData *sim)
586 ParticleSystem *psys = sim->psys;
589 psys->totunexist = 0;
592 if (pa->flag & PARS_UNEXIST) {
597 if (psys->totpart && psys->totunexist == psys->totpart) {
598 if (psys->particles->boid)
599 MEM_freeN(psys->particles->boid);
601 MEM_freeN(psys->particles);
602 psys->particles = NULL;
603 psys->totpart = psys->totunexist = 0;
606 if (psys->totunexist) {
607 int newtotpart = psys->totpart - psys->totunexist;
608 ParticleData *npa, *newpars;
610 npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles");
612 for (p=0, pa=psys->particles; p<newtotpart; p++, pa++, npa++) {
613 while (pa->flag & PARS_UNEXIST)
616 memcpy(npa, pa, sizeof(ParticleData));
619 if (psys->particles->boid)
620 MEM_freeN(psys->particles->boid);
621 MEM_freeN(psys->particles);
622 psys->particles = newpars;
623 psys->totpart -= psys->totunexist;
625 if (psys->particles->boid) {
626 BoidParticle *newboids = MEM_callocN(psys->totpart * sizeof(BoidParticle), "boid particles");
629 pa->boid = newboids++;
636 static void get_angular_velocity_vector(short avemode, ParticleKey *state, float vec[3])
639 case PART_AVE_VELOCITY:
640 copy_v3_v3(vec, state->vel);
642 case PART_AVE_HORIZONTAL:
645 zvec[0] = zvec[1] = 0;
647 cross_v3_v3v3(vec, state->vel, zvec);
650 case PART_AVE_VERTICAL:
652 float zvec[3], temp[3];
653 zvec[0] = zvec[1] = 0;
655 cross_v3_v3v3(temp, state->vel, zvec);
656 cross_v3_v3v3(vec, temp, state->vel);
659 case PART_AVE_GLOBAL_X:
663 case PART_AVE_GLOBAL_Y:
667 case PART_AVE_GLOBAL_Z:
674 void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, float dtime, float cfra)
676 Object *ob = sim->ob;
677 ParticleSystem *psys = sim->psys;
678 ParticleSettings *part = psys->part;
679 ParticleTexture ptex;
680 float fac, phasefac, nor[3] = {0,0,0},loc[3],vel[3] = {0.0,0.0,0.0},rot[4],q2[4];
681 float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3] = {0.0,0.0,0.0};
682 float x_vec[3] = {1.0,0.0,0.0}, utan[3] = {0.0,1.0,0.0}, vtan[3] = {0.0,0.0,1.0}, rot_vec[3] = {0.0,0.0,0.0};
685 const bool use_boids = ((part->phystype == PART_PHYS_BOIDS) &&
687 const bool use_tangents = ((use_boids == false) &&
688 ((part->tanfac != 0.0f) || (part->rotmode == PART_ROT_NOR_TAN)));
690 int p = pa - psys->particles;
692 /* get birth location from object */
694 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
696 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0,0);
698 /* get possible textural influence */
699 psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra);
701 /* particles live in global space so */
704 mul_m4_v3(ob->obmat, loc);
707 mul_mat3_m4_v3(ob->obmat, nor);
712 //float phase=vg_rot?2.0f*(psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
714 mul_v3_fl(vtan,-cosf((float)M_PI*(part->tanphase+phase)));
715 fac= -sinf((float)M_PI*(part->tanphase+phase));
716 madd_v3_v3fl(vtan, utan, fac);
718 mul_mat3_m4_v3(ob->obmat,vtan);
720 copy_v3_v3(utan, nor);
721 mul_v3_fl(utan,dot_v3v3(vtan,nor));
722 sub_v3_v3(vtan, utan);
728 /* -velocity (boids need this even if there's no random velocity) */
729 if (part->randfac != 0.0f || (part->phystype==PART_PHYS_BOIDS && pa->boid)) {
730 r_vel[0] = 2.0f * (psys_frand(psys, p + 10) - 0.5f);
731 r_vel[1] = 2.0f * (psys_frand(psys, p + 11) - 0.5f);
732 r_vel[2] = 2.0f * (psys_frand(psys, p + 12) - 0.5f);
734 mul_mat3_m4_v3(ob->obmat, r_vel);
738 /* -angular velocity */
739 if (part->avemode==PART_AVE_RAND) {
740 r_ave[0] = 2.0f * (psys_frand(psys, p + 13) - 0.5f);
741 r_ave[1] = 2.0f * (psys_frand(psys, p + 14) - 0.5f);
742 r_ave[2] = 2.0f * (psys_frand(psys, p + 15) - 0.5f);
744 mul_mat3_m4_v3(ob->obmat,r_ave);
749 if (part->randrotfac != 0.0f) {
750 r_rot[0] = 2.0f * (psys_frand(psys, p + 16) - 0.5f);
751 r_rot[1] = 2.0f * (psys_frand(psys, p + 17) - 0.5f);
752 r_rot[2] = 2.0f * (psys_frand(psys, p + 18) - 0.5f);
753 r_rot[3] = 2.0f * (psys_frand(psys, p + 19) - 0.5f);
756 mat4_to_quat(rot,ob->obmat);
757 mul_qt_qtqt(r_rot,r_rot,rot);
761 float dvec[3], q[4], mat[3][3];
763 copy_v3_v3(state->co,loc);
765 /* boids don't get any initial velocity */
768 /* boids store direction in ave */
769 if (fabsf(nor[2])==1.0f) {
770 sub_v3_v3v3(state->ave, loc, ob->obmat[3]);
771 normalize_v3(state->ave);
774 copy_v3_v3(state->ave, nor);
777 /* calculate rotation matrix */
778 project_v3_v3v3(dvec, r_vel, state->ave);
779 sub_v3_v3v3(mat[0], state->ave, dvec);
780 normalize_v3(mat[0]);
781 negate_v3_v3(mat[2], r_vel);
782 normalize_v3(mat[2]);
783 cross_v3_v3v3(mat[1], mat[2], mat[0]);
786 mat3_to_quat_is_ok( q,mat);
787 copy_qt_qt(state->rot, q);
790 /* conversion done so now we apply new: */
791 /* -velocity from: */
795 sub_v3_v3v3(vel, pa->state.vel, pa->prev_state.vel);
798 /* *emitter velocity */
799 if (dtime != 0.f && part->obfac != 0.f) {
800 sub_v3_v3v3(vel, loc, state->co);
801 mul_v3_fl(vel, part->obfac/dtime);
804 /* *emitter normal */
805 if (part->normfac != 0.f)
806 madd_v3_v3fl(vel, nor, part->normfac);
808 /* *emitter tangent */
809 if (sim->psmd && part->tanfac != 0.f)
810 madd_v3_v3fl(vel, vtan, part->tanfac);
812 /* *emitter object orientation */
813 if (part->ob_vel[0] != 0.f) {
814 normalize_v3_v3(vec, ob->obmat[0]);
815 madd_v3_v3fl(vel, vec, part->ob_vel[0]);
817 if (part->ob_vel[1] != 0.f) {
818 normalize_v3_v3(vec, ob->obmat[1]);
819 madd_v3_v3fl(vel, vec, part->ob_vel[1]);
821 if (part->ob_vel[2] != 0.f) {
822 normalize_v3_v3(vec, ob->obmat[2]);
823 madd_v3_v3fl(vel, vec, part->ob_vel[2]);
830 if (part->randfac != 0.f)
831 madd_v3_v3fl(vel, r_vel, part->randfac);
834 if (part->partfac != 0.f)
835 madd_v3_v3fl(vel, p_vel, part->partfac);
837 mul_v3_v3fl(state->vel, vel, ptex.ivel);
839 /* -location from emitter */
840 copy_v3_v3(state->co,loc);
846 bool use_global_space;
848 /* create vector into which rotation is aligned */
849 switch (part->rotmode) {
851 case PART_ROT_NOR_TAN:
852 copy_v3_v3(rot_vec, nor);
853 use_global_space = false;
856 copy_v3_v3(rot_vec, vel);
857 use_global_space = true;
859 case PART_ROT_GLOB_X:
860 case PART_ROT_GLOB_Y:
861 case PART_ROT_GLOB_Z:
862 rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
863 use_global_space = true;
868 copy_v3_v3(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
869 use_global_space = false;
872 use_global_space = true;
876 /* create rotation quat */
879 if (use_global_space) {
881 vec_to_quat(q2, rot_vec, OB_POSX, OB_POSZ);
883 /* randomize rotation quat */
884 if (part->randrotfac != 0.0f) {
885 interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
892 /* calculate rotation in local-space */
896 mat4_to_quat(q_obmat, ob->obmat);
897 invert_qt_qt_normalized(q_imat, q_obmat);
900 if (part->rotmode != PART_ROT_NOR_TAN) {
901 float rot_vec_local[3];
905 copy_v3_v3(rot_vec_local, rot_vec);
906 mul_qt_v3(q_imat, rot_vec_local);
907 normalize_v3(rot_vec_local);
909 vec_to_quat(q2, rot_vec_local, OB_POSX, OB_POSZ);
912 /* (part->rotmode == PART_ROT_NOR_TAN) */
915 /* note: utan_local is not taken from 'utan', we calculate from rot_vec/vtan */
916 /* note: it looks like rotation phase may be applied twice (once with vtan, again below)
917 * however this isn't the case - campbell */
918 float *rot_vec_local = tmat[0];
919 float *vtan_local = tmat[1];
920 float *utan_local = tmat[2];
923 BLI_assert(use_tangents == true);
926 copy_v3_v3(rot_vec_local, rot_vec);
927 mul_qt_v3(q_imat, rot_vec_local);
930 copy_v3_v3(vtan_local, vtan); /* flips, cant use */
931 mul_qt_v3(q_imat, vtan_local);
933 /* ensure orthogonal matrix (rot_vec aligned) */
934 cross_v3_v3v3(utan_local, vtan_local, rot_vec_local);
935 cross_v3_v3v3(vtan_local, utan_local, rot_vec_local);
937 /* note: no need to normalize */
938 mat3_to_quat(q2, tmat);
941 /* randomize rotation quat */
942 if (part->randrotfac != 0.0f) {
943 mul_qt_qtqt(r_rot, r_rot, q_imat);
944 interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
950 mul_qt_qtqt(rot, q_obmat, rot);
954 phasefac = part->phasefac;
955 if (part->randphasefac != 0.0f)
956 phasefac += part->randphasefac * psys_frand(psys, p + 20);
957 axis_angle_to_quat( q_phase,x_vec, phasefac*(float)M_PI);
959 /* combine base rotation & phase */
960 mul_qt_qtqt(state->rot, rot, q_phase);
963 /* -angular velocity */
968 if (part->avemode == PART_AVE_RAND)
969 copy_v3_v3(state->ave, r_ave);
971 get_angular_velocity_vector(part->avemode, state, state->ave);
973 normalize_v3(state->ave);
974 mul_v3_fl(state->ave, part->avefac);
979 /* recursively evaluate emitter parent anim at cfra */
980 static void evaluate_emitter_anim(Scene *scene, Object *ob, float cfra)
983 evaluate_emitter_anim(scene, ob->parent, cfra);
985 /* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */
986 BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, cfra, ADT_RECALC_ANIM);
987 BKE_object_where_is_calc_time(scene, ob, cfra);
990 /* sets particle to the emitter surface with initial velocity & rotation */
991 void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, float cfra)
993 ParticleSystem *psys = sim->psys;
994 ParticleSettings *part;
995 ParticleTexture ptex;
996 int p = pa - psys->particles;
999 /* get precise emitter matrix if particle is born */
1000 if (part->type!=PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) {
1001 evaluate_emitter_anim(sim->scene, sim->ob, pa->time);
1003 psys->flag |= PSYS_OB_ANIM_RESTORE;
1006 psys_get_birth_coords(sim, pa, &pa->state, dtime, cfra);
1008 /* Initialize particle settings which depends on texture.
1010 * We could only do it now because we'll need to know coordinate
1011 * before sampling the texture.
1013 initialize_particle_texture(sim, pa, p);
1015 if (part->phystype==PART_PHYS_BOIDS && pa->boid) {
1016 BoidParticle *bpa = pa->boid;
1018 /* and gravity in r_ve */
1019 bpa->gravity[0] = bpa->gravity[1] = 0.0f;
1020 bpa->gravity[2] = -1.0f;
1021 if ((sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) &&
1022 (sim->scene->physics_settings.gravity[2] != 0.0f))
1024 bpa->gravity[2] = sim->scene->physics_settings.gravity[2];
1027 bpa->data.health = part->boids->health;
1028 bpa->data.mode = eBoidMode_InAir;
1029 bpa->data.state_id = ((BoidState*)part->boids->states.first)->id;
1030 bpa->data.acc[0]=bpa->data.acc[1]=bpa->data.acc[2]=0.0f;
1033 if (part->type == PART_HAIR) {
1034 pa->lifetime = 100.0f;
1037 /* initialize the lifetime, in case the texture coordinates
1038 * are from Particles/Strands, which would cause undefined values
1040 pa->lifetime = part->lifetime * (1.0f - part->randlife * psys_frand(psys, p + 21));
1041 pa->dietime = pa->time + pa->lifetime;
1043 /* get possible textural influence */
1044 psys_get_texture(sim, pa, &ptex, PAMAP_LIFE, cfra);
1046 pa->lifetime = part->lifetime * ptex.life;
1048 if (part->randlife != 0.0f)
1049 pa->lifetime *= 1.0f - part->randlife * psys_frand(psys, p + 21);
1052 pa->dietime = pa->time + pa->lifetime;
1054 if (sim->psys->pointcache && sim->psys->pointcache->flag & PTCACHE_BAKED &&
1055 sim->psys->pointcache->mem_cache.first) {
1056 float dietime = psys_get_dietime_from_cache(sim->psys->pointcache, p);
1057 pa->dietime = MIN2(pa->dietime, dietime);
1060 if (pa->time > cfra)
1061 pa->alive = PARS_UNBORN;
1062 else if (pa->dietime <= cfra)
1063 pa->alive = PARS_DEAD;
1065 pa->alive = PARS_ALIVE;
1067 pa->state.time = cfra;
1069 static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
1072 int p, totpart=sim->psys->totpart;
1074 for (p=from, pa=sim->psys->particles+from; p<totpart; p++, pa++)
1075 reset_particle(sim, pa, dtime, cfra);
1077 /************************************************/
1078 /* Particle targets */
1079 /************************************************/
1080 ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt)
1082 ParticleSystem *psys = NULL;
1084 if (pt->ob == NULL || pt->ob == ob)
1085 psys = BLI_findlink(&ob->particlesystem, pt->psys-1);
1087 psys = BLI_findlink(&pt->ob->particlesystem, pt->psys-1);
1090 pt->flag |= PTARGET_VALID;
1092 pt->flag &= ~PTARGET_VALID;
1096 /************************************************/
1097 /* Keyed particles */
1098 /************************************************/
1099 /* Counts valid keyed targets */
1100 void psys_count_keyed_targets(ParticleSimulationData *sim)
1102 ParticleSystem *psys = sim->psys, *kpsys;
1103 ParticleTarget *pt = psys->targets.first;
1107 for (; pt; pt=pt->next) {
1108 kpsys = psys_get_target_system(sim->ob, pt);
1110 if (kpsys && kpsys->totpart) {
1111 psys->totkeyed += keys_valid;
1112 if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
1113 psys->totkeyed += 1;
1120 psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
1123 static void set_keyed_keys(ParticleSimulationData *sim)
1125 ParticleSystem *psys = sim->psys;
1126 ParticleSimulationData ksim= {0};
1130 int totpart = psys->totpart, k, totkeys = psys->totkeyed;
1133 ksim.scene= sim->scene;
1135 /* no proper targets so let's clear and bail out */
1136 if (psys->totkeyed==0) {
1137 free_keyed_keys(psys);
1138 psys->flag &= ~PSYS_KEYED;
1142 if (totpart && psys->particles->totkey != totkeys) {
1143 free_keyed_keys(psys);
1145 key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
1149 pa->totkey = totkeys;
1154 psys->flag &= ~PSYS_KEYED;
1157 pt = psys->targets.first;
1158 for (k=0; k<totkeys; k++) {
1159 ksim.ob = pt->ob ? pt->ob : sim->ob;
1160 ksim.psys = BLI_findlink(&ksim.ob->particlesystem, pt->psys - 1);
1161 keyed_flag = (ksim.psys->flag & PSYS_KEYED);
1162 ksim.psys->flag &= ~PSYS_KEYED;
1166 key->time = -1.0; /* use current time */
1168 psys_get_particle_state(&ksim, p%ksim.psys->totpart, key, 1);
1170 if (psys->flag & PSYS_KEYED_TIMING) {
1171 key->time = pa->time + pt->time;
1172 if (pt->duration != 0.0f && k+1 < totkeys) {
1173 copy_particle_key(key+1, key, 1);
1174 (key+1)->time = pa->time + pt->time + pt->duration;
1177 else if (totkeys > 1)
1178 key->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
1180 key->time = pa->time;
1183 if (psys->flag & PSYS_KEYED_TIMING && pt->duration!=0.0f)
1186 ksim.psys->flag |= keyed_flag;
1188 pt = (pt->next && pt->next->flag & PTARGET_VALID) ? pt->next : psys->targets.first;
1191 psys->flag |= PSYS_KEYED;
1194 /************************************************/
1196 /************************************************/
1197 void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys)
1199 PointCache *cache = psys->pointcache;
1201 if (cache->flag & PTCACHE_DISK_CACHE && BLI_listbase_is_empty(&cache->mem_cache)) {
1203 BKE_ptcache_id_from_particles(&pid, ob, psys);
1204 cache->flag &= ~PTCACHE_DISK_CACHE;
1205 BKE_ptcache_disk_to_mem(&pid);
1206 cache->flag |= PTCACHE_DISK_CACHE;
1209 static void psys_clear_temp_pointcache(ParticleSystem *psys)
1211 if (psys->pointcache->flag & PTCACHE_DISK_CACHE)
1212 BKE_ptcache_free_mem(&psys->pointcache->mem_cache);
1214 void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
1216 ParticleSettings *part = psys->part;
1218 *sfra = max_ii(1, (int)part->sta);
1219 *efra = min_ii((int)(part->end + part->lifetime + 1.0f), max_ii(scene->r.pefra, scene->r.efra));
1222 /************************************************/
1224 /************************************************/
1225 static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra)
1232 BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ);
1233 need_rebuild = !psys->bvhtree || psys->bvhtree_frame != cfra;
1234 BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1237 LOOP_SHOWN_PARTICLES {
1241 BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_WRITE);
1243 BLI_bvhtree_free(psys->bvhtree);
1244 psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6);
1246 LOOP_SHOWN_PARTICLES {
1247 if (pa->alive == PARS_ALIVE) {
1248 if (pa->state.time == cfra)
1249 BLI_bvhtree_insert(psys->bvhtree, p, pa->prev_state.co, 1);
1251 BLI_bvhtree_insert(psys->bvhtree, p, pa->state.co, 1);
1254 BLI_bvhtree_balance(psys->bvhtree);
1256 psys->bvhtree_frame = cfra;
1258 BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1262 void psys_update_particle_tree(ParticleSystem *psys, float cfra)
1268 if (!psys->tree || psys->tree_frame != cfra) {
1269 LOOP_SHOWN_PARTICLES {
1273 BLI_kdtree_free(psys->tree);
1274 psys->tree = BLI_kdtree_new(psys->totpart);
1276 LOOP_SHOWN_PARTICLES {
1277 if (pa->alive == PARS_ALIVE) {
1278 if (pa->state.time == cfra)
1279 BLI_kdtree_insert(psys->tree, p, pa->prev_state.co);
1281 BLI_kdtree_insert(psys->tree, p, pa->state.co);
1284 BLI_kdtree_balance(psys->tree);
1286 psys->tree_frame = cfra;
1291 static void psys_update_effectors(ParticleSimulationData *sim)
1293 pdEndEffectors(&sim->psys->effectors);
1294 sim->psys->effectors = pdInitEffectors(sim->scene, sim->ob, sim->psys,
1295 sim->psys->part->effector_weights, true);
1296 precalc_guides(sim, sim->psys->effectors);
1299 static void integrate_particle(ParticleSettings *part, ParticleData *pa, float dtime, float *external_acceleration,
1300 void (*force_func)(void *forcedata, ParticleKey *state, float *force, float *impulse),
1303 #define ZERO_F43 {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}}
1305 ParticleKey states[5];
1306 float force[3], acceleration[3], impulse[3], dx[4][3] = ZERO_F43, dv[4][3] = ZERO_F43, oldpos[3];
1307 float pa_mass= (part->flag & PART_SIZEMASS ? part->mass * pa->size : part->mass);
1309 int integrator = part->integrator;
1313 copy_v3_v3(oldpos, pa->state.co);
1315 /* Verlet integration behaves strangely with moving emitters, so do first step with euler. */
1316 if (pa->prev_state.time < 0.f && integrator == PART_INT_VERLET)
1317 integrator = PART_INT_EULER;
1319 switch (integrator) {
1320 case PART_INT_EULER:
1323 case PART_INT_MIDPOINT:
1329 case PART_INT_VERLET:
1334 for (i=0; i<steps; i++) {
1335 copy_particle_key(states + i, &pa->state, 1);
1340 for (i=0; i<steps; i++) {
1344 force_func(forcedata, states+i, force, impulse);
1346 /* force to acceleration*/
1347 mul_v3_v3fl(acceleration, force, 1.0f/pa_mass);
1349 if (external_acceleration)
1350 add_v3_v3(acceleration, external_acceleration);
1352 /* calculate next state */
1353 add_v3_v3(states[i].vel, impulse);
1355 switch (integrator) {
1356 case PART_INT_EULER:
1357 madd_v3_v3v3fl(pa->state.co, states->co, states->vel, dtime);
1358 madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1360 case PART_INT_MIDPOINT:
1362 madd_v3_v3v3fl(states[1].co, states->co, states->vel, dtime*0.5f);
1363 madd_v3_v3v3fl(states[1].vel, states->vel, acceleration, dtime*0.5f);
1364 states[1].time = dtime*0.5f;
1365 /*fra=sim->psys->cfra+0.5f*dfra;*/
1368 madd_v3_v3v3fl(pa->state.co, states->co, states[1].vel, dtime);
1369 madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1375 copy_v3_v3(dx[0], states->vel);
1376 mul_v3_fl(dx[0], dtime);
1377 copy_v3_v3(dv[0], acceleration);
1378 mul_v3_fl(dv[0], dtime);
1380 madd_v3_v3v3fl(states[1].co, states->co, dx[0], 0.5f);
1381 madd_v3_v3v3fl(states[1].vel, states->vel, dv[0], 0.5f);
1382 states[1].time = dtime*0.5f;
1383 /*fra=sim->psys->cfra+0.5f*dfra;*/
1386 madd_v3_v3v3fl(dx[1], states->vel, dv[0], 0.5f);
1387 mul_v3_fl(dx[1], dtime);
1388 copy_v3_v3(dv[1], acceleration);
1389 mul_v3_fl(dv[1], dtime);
1391 madd_v3_v3v3fl(states[2].co, states->co, dx[1], 0.5f);
1392 madd_v3_v3v3fl(states[2].vel, states->vel, dv[1], 0.5f);
1393 states[2].time = dtime*0.5f;
1396 madd_v3_v3v3fl(dx[2], states->vel, dv[1], 0.5f);
1397 mul_v3_fl(dx[2], dtime);
1398 copy_v3_v3(dv[2], acceleration);
1399 mul_v3_fl(dv[2], dtime);
1401 add_v3_v3v3(states[3].co, states->co, dx[2]);
1402 add_v3_v3v3(states[3].vel, states->vel, dv[2]);
1403 states[3].time = dtime;
1407 add_v3_v3v3(dx[3], states->vel, dv[2]);
1408 mul_v3_fl(dx[3], dtime);
1409 copy_v3_v3(dv[3], acceleration);
1410 mul_v3_fl(dv[3], dtime);
1412 madd_v3_v3v3fl(pa->state.co, states->co, dx[0], 1.0f/6.0f);
1413 madd_v3_v3fl(pa->state.co, dx[1], 1.0f/3.0f);
1414 madd_v3_v3fl(pa->state.co, dx[2], 1.0f/3.0f);
1415 madd_v3_v3fl(pa->state.co, dx[3], 1.0f/6.0f);
1417 madd_v3_v3v3fl(pa->state.vel, states->vel, dv[0], 1.0f/6.0f);
1418 madd_v3_v3fl(pa->state.vel, dv[1], 1.0f/3.0f);
1419 madd_v3_v3fl(pa->state.vel, dv[2], 1.0f/3.0f);
1420 madd_v3_v3fl(pa->state.vel, dv[3], 1.0f/6.0f);
1423 case PART_INT_VERLET: /* Verlet integration */
1424 madd_v3_v3v3fl(pa->state.vel, pa->prev_state.vel, acceleration, dtime);
1425 madd_v3_v3v3fl(pa->state.co, pa->prev_state.co, pa->state.vel, dtime);
1427 sub_v3_v3v3(pa->state.vel, pa->state.co, oldpos);
1428 mul_v3_fl(pa->state.vel, 1.0f/dtime);
1434 /*********************************************************************************************************
1437 * In theory, there could be unlimited implementation of SPH simulators
1439 * This code uses in some parts adapted algorithms from the pseudo code as outlined in the Research paper:
1441 * Titled: Particle-based Viscoelastic Fluid Simulation.
1442 * Authors: Simon Clavet, Philippe Beaudoin and Pierre Poulin
1443 * Website: http://www.iro.umontreal.ca/labs/infographie/papers/Clavet-2005-PVFS/
1445 * Presented at Siggraph, (2005)
1447 * ********************************************************************************************************/
1448 #define PSYS_FLUID_SPRINGS_INITIAL_SIZE 256
1449 static ParticleSpring *sph_spring_add(ParticleSystem *psys, ParticleSpring *spring)
1451 /* Are more refs required? */
1452 if (psys->alloc_fluidsprings == 0 || psys->fluid_springs == NULL) {
1453 psys->alloc_fluidsprings = PSYS_FLUID_SPRINGS_INITIAL_SIZE;
1454 psys->fluid_springs = (ParticleSpring*)MEM_callocN(psys->alloc_fluidsprings * sizeof(ParticleSpring), "Particle Fluid Springs");
1456 else if (psys->tot_fluidsprings == psys->alloc_fluidsprings) {
1457 /* Double the number of refs allocated */
1458 psys->alloc_fluidsprings *= 2;
1459 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring));
1462 memcpy(psys->fluid_springs + psys->tot_fluidsprings, spring, sizeof(ParticleSpring));
1463 psys->tot_fluidsprings++;
1465 return psys->fluid_springs + psys->tot_fluidsprings - 1;
1467 static void sph_spring_delete(ParticleSystem *psys, int j)
1469 if (j != psys->tot_fluidsprings - 1)
1470 psys->fluid_springs[j] = psys->fluid_springs[psys->tot_fluidsprings - 1];
1472 psys->tot_fluidsprings--;
1474 if (psys->tot_fluidsprings < psys->alloc_fluidsprings/2 && psys->alloc_fluidsprings > PSYS_FLUID_SPRINGS_INITIAL_SIZE) {
1475 psys->alloc_fluidsprings /= 2;
1476 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring));
1479 static void sph_springs_modify(ParticleSystem *psys, float dtime)
1481 SPHFluidSettings *fluid = psys->part->fluid;
1482 ParticleData *pa1, *pa2;
1483 ParticleSpring *spring = psys->fluid_springs;
1485 float h, d, Rij[3], rij, Lij;
1488 float yield_ratio = fluid->yield_ratio;
1489 float plasticity = fluid->plasticity_constant;
1490 /* scale things according to dtime */
1491 float timefix = 25.f * dtime;
1493 if ((fluid->flag & SPH_VISCOELASTIC_SPRINGS)==0 || fluid->spring_k == 0.f)
1496 /* Loop through the springs */
1497 for (i=0; i<psys->tot_fluidsprings; i++, spring++) {
1498 pa1 = psys->particles + spring->particle_index[0];
1499 pa2 = psys->particles + spring->particle_index[1];
1501 sub_v3_v3v3(Rij, pa2->prev_state.co, pa1->prev_state.co);
1502 rij = normalize_v3(Rij);
1504 /* adjust rest length */
1505 Lij = spring->rest_length;
1506 d = yield_ratio * timefix * Lij;
1508 if (rij > Lij + d) // Stretch
1509 spring->rest_length += plasticity * (rij - Lij - d) * timefix;
1510 else if (rij < Lij - d) // Compress
1511 spring->rest_length -= plasticity * (Lij - d - rij) * timefix;
1515 if (spring->rest_length > h)
1516 spring->delete_flag = 1;
1519 /* Loop through springs backwaqrds - for efficient delete function */
1520 for (i=psys->tot_fluidsprings-1; i >= 0; i--) {
1521 if (psys->fluid_springs[i].delete_flag)
1522 sph_spring_delete(psys, i);
1525 static EdgeHash *sph_springhash_build(ParticleSystem *psys)
1527 EdgeHash *springhash = NULL;
1528 ParticleSpring *spring;
1531 springhash = BLI_edgehash_new_ex(__func__, psys->tot_fluidsprings);
1533 for (i=0, spring=psys->fluid_springs; i<psys->tot_fluidsprings; i++, spring++)
1534 BLI_edgehash_insert(springhash, spring->particle_index[0], spring->particle_index[1], SET_INT_IN_POINTER(i+1));
1539 #define SPH_NEIGHBORS 512
1540 typedef struct SPHNeighbor {
1541 ParticleSystem *psys;
1545 typedef struct SPHRangeData {
1546 SPHNeighbor neighbors[SPH_NEIGHBORS];
1551 ParticleSystem *npsys;
1560 static void sph_evaluate_func(BVHTree *tree, ParticleSystem **psys, float co[3], SPHRangeData *pfr, float interaction_radius, BVHTree_RangeQuery callback)
1564 pfr->tot_neighbors = 0;
1566 for (i=0; i < 10 && psys[i]; i++) {
1567 pfr->npsys = psys[i];
1568 pfr->massfac = psys[i]->part->mass / pfr->mass;
1569 pfr->use_size = psys[i]->part->flag & PART_SIZEMASS;
1572 BLI_bvhtree_range_query(tree, co, interaction_radius, callback, pfr);
1576 BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ);
1578 BLI_bvhtree_range_query(psys[i]->bvhtree, co, interaction_radius, callback, pfr);
1580 BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1584 static void sph_density_accum_cb(void *userdata, int index, float squared_dist)
1586 SPHRangeData *pfr = (SPHRangeData *)userdata;
1587 ParticleData *npa = pfr->npsys->particles + index;
1591 if (npa == pfr->pa || squared_dist < FLT_EPSILON)
1594 /* Ugh! One particle has too many neighbors! If some aren't taken into
1595 * account, the forces will be biased by the tree search order. This
1596 * effectively adds enery to the system, and results in a churning motion.
1597 * But, we have to stop somewhere, and it's not the end of the world.
1600 if (pfr->tot_neighbors >= SPH_NEIGHBORS)
1603 pfr->neighbors[pfr->tot_neighbors].index = index;
1604 pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1605 pfr->tot_neighbors++;
1607 dist = sqrtf(squared_dist);
1608 q = (1.f - dist/pfr->h) * pfr->massfac;
1613 pfr->data[0] += q*q;
1614 pfr->data[1] += q*q*q;
1618 * Find the Courant number for an SPH particle (used for adaptive time step).
1620 static void sph_particle_courant(SPHData *sphdata, SPHRangeData *pfr)
1622 ParticleData *pa, *npa;
1624 float flow[3], offset[3], dist;
1629 if (pfr->tot_neighbors > 0) {
1631 for (i=0; i < pfr->tot_neighbors; i++) {
1632 npa = pfr->neighbors[i].psys->particles + pfr->neighbors[i].index;
1633 sub_v3_v3v3(offset, pa->prev_state.co, npa->prev_state.co);
1634 dist += len_v3(offset);
1635 add_v3_v3(flow, npa->prev_state.vel);
1637 dist += sphdata->psys[0]->part->fluid->radius; // TODO: remove this? - z0r
1638 sphdata->element_size = dist / pfr->tot_neighbors;
1639 mul_v3_v3fl(sphdata->flow, flow, 1.0f / pfr->tot_neighbors);
1642 sphdata->element_size = FLT_MAX;
1643 copy_v3_v3(sphdata->flow, flow);
1646 static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
1648 SPHData *sphdata = (SPHData *)sphdata_v;
1649 ParticleSystem **psys = sphdata->psys;
1650 ParticleData *pa = sphdata->pa;
1651 SPHFluidSettings *fluid = psys[0]->part->fluid;
1652 ParticleSpring *spring = NULL;
1655 float *gravity = sphdata->gravity;
1656 EdgeHash *springhash = sphdata->eh;
1658 float q, u, rij, dv[3];
1659 float pressure, near_pressure;
1661 float visc = fluid->viscosity_omega;
1662 float stiff_visc = fluid->viscosity_beta * (fluid->flag & SPH_FAC_VISCOSITY ? fluid->viscosity_omega : 1.f);
1664 float inv_mass = 1.0f / sphdata->mass;
1665 float spring_constant = fluid->spring_k;
1667 /* 4.0 seems to be a pretty good value */
1668 float interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1669 float h = interaction_radius * sphdata->hfac;
1670 float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.f); /* 4.77 is an experimentally determined density factor */
1671 float rest_length = fluid->rest_length * (fluid->flag & SPH_FAC_REST_LENGTH ? 2.588f * pa->size : 1.f);
1673 float stiffness = fluid->stiffness_k;
1674 float stiffness_near_fac = fluid->stiffness_knear * (fluid->flag & SPH_FAC_REPULSION ? fluid->stiffness_k : 1.f);
1681 float density, near_density;
1683 int i, spring_index, index = pa - psys[0]->particles;
1685 data[0] = data[1] = 0;
1689 pfr.mass = sphdata->mass;
1691 sph_evaluate_func( NULL, psys, state->co, &pfr, interaction_radius, sph_density_accum_cb);
1694 near_density = data[1];
1696 pressure = stiffness * (density - rest_density);
1697 near_pressure = stiffness_near_fac * near_density;
1699 pfn = pfr.neighbors;
1700 for (i=0; i<pfr.tot_neighbors; i++, pfn++) {
1701 npa = pfn->psys->particles + pfn->index;
1703 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1705 sub_v3_v3v3(vec, co, state->co);
1706 rij = normalize_v3(vec);
1708 q = (1.f - rij/h) * pfn->psys->part->mass * inv_mass;
1710 if (pfn->psys->part->flag & PART_SIZEMASS)
1713 copy_v3_v3(vel, npa->prev_state.vel);
1715 /* Double Density Relaxation */
1716 madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q);
1719 if (visc > 0.f || stiff_visc > 0.f) {
1720 sub_v3_v3v3(dv, vel, state->vel);
1721 u = dot_v3v3(vec, dv);
1723 if (u < 0.f && visc > 0.f)
1724 madd_v3_v3fl(force, vec, 0.5f * q * visc * u );
1726 if (u > 0.f && stiff_visc > 0.f)
1727 madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u );
1730 if (spring_constant > 0.f) {
1731 /* Viscoelastic spring force */
1732 if (pfn->psys == psys[0] && fluid->flag & SPH_VISCOELASTIC_SPRINGS && springhash) {
1733 /* BLI_edgehash_lookup appears to be thread-safe. - z0r */
1734 spring_index = GET_INT_FROM_POINTER(BLI_edgehash_lookup(springhash, index, pfn->index));
1737 spring = psys[0]->fluid_springs + spring_index - 1;
1739 madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (spring->rest_length - rij));
1741 else if (fluid->spring_frames == 0 || (pa->prev_state.time-pa->time) <= fluid->spring_frames) {
1742 ParticleSpring temp_spring;
1743 temp_spring.particle_index[0] = index;
1744 temp_spring.particle_index[1] = pfn->index;
1745 temp_spring.rest_length = (fluid->flag & SPH_CURRENT_REST_LENGTH) ? rij : rest_length;
1746 temp_spring.delete_flag = 0;
1748 /* sph_spring_add is not thread-safe. - z0r */
1749 #pragma omp critical
1750 sph_spring_add(psys[0], &temp_spring);
1753 else {/* PART_SPRING_HOOKES - Hooke's spring force */
1754 madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (rest_length - rij));
1759 /* Artificial buoyancy force in negative gravity direction */
1760 if (fluid->buoyancy > 0.f && gravity)
1761 madd_v3_v3fl(force, gravity, fluid->buoyancy * (density-rest_density));
1763 if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1764 sph_particle_courant(sphdata, &pfr);
1768 static void sphclassical_density_accum_cb(void *userdata, int index, float UNUSED(squared_dist))
1770 SPHRangeData *pfr = (SPHRangeData *)userdata;
1771 ParticleData *npa = pfr->npsys->particles + index;
1773 float qfac = 21.0f / (256.f * (float)M_PI);
1777 /* Exclude particles that are more than 2h away. Can't use squared_dist here
1778 * because it is not accurate enough. Use current state, i.e. the output of
1779 * basic_integrate() - z0r */
1780 sub_v3_v3v3(vec, npa->state.co, pfr->pa->state.co);
1782 rij_h = rij / pfr->h;
1786 /* Smoothing factor. Utilise the Wendland kernel. gnuplot:
1787 * q1(x) = (2.0 - x)**4 * ( 1.0 + 2.0 * x)
1788 * plot [0:2] q1(x) */
1789 q = qfac / pow3f(pfr->h) * pow4f(2.0f - rij_h) * ( 1.0f + 2.0f * rij_h);
1790 q *= pfr->npsys->part->mass;
1796 pfr->data[1] += q / npa->sphdensity;
1799 static void sphclassical_neighbour_accum_cb(void *userdata, int index, float UNUSED(squared_dist))
1801 SPHRangeData *pfr = (SPHRangeData *)userdata;
1802 ParticleData *npa = pfr->npsys->particles + index;
1806 if (pfr->tot_neighbors >= SPH_NEIGHBORS)
1809 /* Exclude particles that are more than 2h away. Can't use squared_dist here
1810 * because it is not accurate enough. Use current state, i.e. the output of
1811 * basic_integrate() - z0r */
1812 sub_v3_v3v3(vec, npa->state.co, pfr->pa->state.co);
1814 rij_h = rij / pfr->h;
1818 pfr->neighbors[pfr->tot_neighbors].index = index;
1819 pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1820 pfr->tot_neighbors++;
1822 static void sphclassical_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
1824 SPHData *sphdata = (SPHData *)sphdata_v;
1825 ParticleSystem **psys = sphdata->psys;
1826 ParticleData *pa = sphdata->pa;
1827 SPHFluidSettings *fluid = psys[0]->part->fluid;
1830 float *gravity = sphdata->gravity;
1832 float dq, u, rij, dv[3];
1833 float pressure, npressure;
1835 float visc = fluid->viscosity_omega;
1837 float interaction_radius;
1839 /* 4.77 is an experimentally determined density factor */
1840 float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.0f);
1842 // Use speed of sound squared
1843 float stiffness = pow2f(fluid->stiffness_k);
1852 float qfac2 = 42.0f / (256.0f * (float)M_PI);
1855 /* 4.0 here is to be consistent with previous formulation/interface */
1856 interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1857 h = interaction_radius * sphdata->hfac;
1863 sph_evaluate_func(NULL, psys, state->co, &pfr, interaction_radius, sphclassical_neighbour_accum_cb);
1864 pressure = stiffness * (pow7f(pa->sphdensity / rest_density) - 1.0f);
1866 /* multiply by mass so that we return a force, not accel */
1867 qfac2 *= sphdata->mass / pow3f(pfr.h);
1869 pfn = pfr.neighbors;
1870 for (i = 0; i < pfr.tot_neighbors; i++, pfn++) {
1871 npa = pfn->psys->particles + pfn->index;
1873 /* we do not contribute to ourselves */
1877 /* Find vector to neighbor. Exclude particles that are more than 2h
1878 * away. Can't use current state here because it may have changed on
1879 * another thread - so do own mini integration. Unlike basic_integrate,
1880 * SPH integration depends on neighboring particles. - z0r */
1881 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1882 sub_v3_v3v3(vec, co, state->co);
1883 rij = normalize_v3(vec);
1884 rij_h = rij / pfr.h;
1888 npressure = stiffness * (pow7f(npa->sphdensity / rest_density) - 1.0f);
1890 /* First derivative of smoothing factor. Utilise the Wendland kernel.
1892 * q2(x) = 2.0 * (2.0 - x)**4 - 4.0 * (2.0 - x)**3 * (1.0 + 2.0 * x)
1894 * Particles > 2h away are excluded above. */
1895 dq = qfac2 * (2.0f * pow4f(2.0f - rij_h) - 4.0f * pow3f(2.0f - rij_h) * (1.0f + 2.0f * rij_h) );
1897 if (pfn->psys->part->flag & PART_SIZEMASS)
1900 pressureTerm = pressure / pow2f(pa->sphdensity) + npressure / pow2f(npa->sphdensity);
1902 /* Note that 'minus' is removed, because vec = vecBA, not vecAB.
1903 * This applies to the viscosity calculation below, too. */
1904 madd_v3_v3fl(force, vec, pressureTerm * dq);
1908 sub_v3_v3v3(dv, npa->prev_state.vel, pa->prev_state.vel);
1909 u = dot_v3v3(vec, dv);
1910 /* Apply parameters */
1911 u *= -dq * hinv * visc / (0.5f * npa->sphdensity + 0.5f * pa->sphdensity);
1912 madd_v3_v3fl(force, vec, u);
1916 /* Artificial buoyancy force in negative gravity direction */
1917 if (fluid->buoyancy > 0.f && gravity)
1918 madd_v3_v3fl(force, gravity, fluid->buoyancy * (pa->sphdensity - rest_density));
1920 if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1921 sph_particle_courant(sphdata, &pfr);
1925 static void sphclassical_calc_dens(ParticleData *pa, float UNUSED(dfra), SPHData *sphdata)
1927 ParticleSystem **psys = sphdata->psys;
1928 SPHFluidSettings *fluid = psys[0]->part->fluid;
1929 /* 4.0 seems to be a pretty good value */
1930 float interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
1937 pfr.h = interaction_radius * sphdata->hfac;
1939 pfr.mass = sphdata->mass;
1941 sph_evaluate_func( NULL, psys, pa->state.co, &pfr, interaction_radius, sphclassical_density_accum_cb);
1942 pa->sphdensity = min_ff(max_ff(data[0], fluid->rest_density * 0.9f), fluid->rest_density * 1.1f);
1945 void psys_sph_init(ParticleSimulationData *sim, SPHData *sphdata)
1950 // Add other coupled particle systems.
1951 sphdata->psys[0] = sim->psys;
1952 for (i=1, pt=sim->psys->targets.first; i<10; i++, pt=(pt?pt->next:NULL))
1953 sphdata->psys[i] = pt ? psys_get_target_system(sim->ob, pt) : NULL;
1955 if (psys_uses_gravity(sim))
1956 sphdata->gravity = sim->scene->physics_settings.gravity;
1958 sphdata->gravity = NULL;
1959 sphdata->eh = sph_springhash_build(sim->psys);
1961 // These per-particle values should be overridden later, but just for
1962 // completeness we give them default values now.
1964 sphdata->mass = 1.0f;
1966 if (sim->psys->part->fluid->solver == SPH_SOLVER_DDR) {
1967 sphdata->force_cb = sph_force_cb;
1968 sphdata->density_cb = sph_density_accum_cb;
1969 sphdata->hfac = 1.0f;
1972 /* SPH_SOLVER_CLASSICAL */
1973 sphdata->force_cb = sphclassical_force_cb;
1974 sphdata->density_cb = sphclassical_density_accum_cb;
1975 sphdata->hfac = 0.5f;
1980 void psys_sph_finalise(SPHData *sphdata)
1983 BLI_edgehash_free(sphdata->eh, NULL);
1987 /* Sample the density field at a point in space. */
1988 void psys_sph_density(BVHTree *tree, SPHData *sphdata, float co[3], float vars[2])
1990 ParticleSystem **psys = sphdata->psys;
1991 SPHFluidSettings *fluid = psys[0]->part->fluid;
1992 /* 4.0 seems to be a pretty good value */
1993 float interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
1997 density[0] = density[1] = 0.0f;
1999 pfr.h = interaction_radius * sphdata->hfac;
2000 pfr.mass = sphdata->mass;
2002 sph_evaluate_func(tree, psys, co, &pfr, interaction_radius, sphdata->density_cb);
2004 vars[0] = pfr.data[0];
2005 vars[1] = pfr.data[1];
2008 static void sph_integrate(ParticleSimulationData *sim, ParticleData *pa, float dfra, SPHData *sphdata)
2010 ParticleSettings *part = sim->psys->part;
2011 // float timestep = psys_get_timestep(sim); // UNUSED
2012 float pa_mass = part->mass * (part->flag & PART_SIZEMASS ? pa->size : 1.f);
2013 float dtime = dfra*psys_get_timestep(sim);
2014 // int steps = 1; // UNUSED
2015 float effector_acceleration[3];
2018 sphdata->mass = pa_mass;
2020 //sphdata.element_size and sphdata.flow are set in the callback.
2022 /* restore previous state and treat gravity & effectors as external acceleration*/
2023 sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel);
2024 mul_v3_fl(effector_acceleration, 1.f/dtime);
2026 copy_particle_key(&pa->state, &pa->prev_state, 0);
2028 integrate_particle(part, pa, dtime, effector_acceleration, sphdata->force_cb, sphdata);
2031 /************************************************/
2033 /************************************************/
2034 typedef struct EfData {
2035 ParticleTexture ptex;
2036 ParticleSimulationData *sim;
2039 static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
2041 EfData *efdata = (EfData *)efdata_v;
2042 ParticleSimulationData *sim = efdata->sim;
2043 ParticleSettings *part = sim->psys->part;
2044 ParticleData *pa = efdata->pa;
2045 EffectedPoint epoint;
2048 pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint);
2049 if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)
2050 pdDoEffectors(sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse);
2052 mul_v3_fl(force, efdata->ptex.field);
2053 mul_v3_fl(impulse, efdata->ptex.field);
2055 /* calculate air-particle interaction */
2056 if (part->dragfac != 0.0f)
2057 madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel));
2059 /* brownian force */
2060 if (part->brownfac != 0.0f) {
2061 force[0] += (BLI_frand()-0.5f) * part->brownfac;
2062 force[1] += (BLI_frand()-0.5f) * part->brownfac;
2063 force[2] += (BLI_frand()-0.5f) * part->brownfac;
2066 if (part->flag & PART_ROT_DYN && epoint.ave)
2067 copy_v3_v3(pa->state.ave, epoint.ave);
2069 /* gathers all forces that effect particles and calculates a new state for the particle */
2070 static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
2072 ParticleSettings *part = sim->psys->part;
2073 ParticleData *pa = sim->psys->particles + p;
2075 float dtime=dfra*psys_get_timestep(sim), time;
2076 float *gravity = NULL, gr[3];
2079 psys_get_texture(sim, pa, &efdata.ptex, PAMAP_PHYSICS, cfra);
2084 /* add global acceleration (gravitation) */
2085 if (psys_uses_gravity(sim) &&
2086 /* normal gravity is too strong for hair so it's disabled by default */
2087 (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR))
2090 madd_v3_v3fl(gr, sim->scene->physics_settings.gravity, part->effector_weights->global_gravity * efdata.ptex.gravity);
2094 /* maintain angular velocity */
2095 copy_v3_v3(pa->state.ave, pa->prev_state.ave);
2097 integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata);
2099 /* damp affects final velocity */
2100 if (part->dampfac != 0.f)
2101 mul_v3_fl(pa->state.vel, 1.f - part->dampfac * efdata.ptex.damp * 25.f * dtime);
2103 //copy_v3_v3(pa->state.ave, states->ave);
2105 /* finally we do guides */
2106 time=(cfra-pa->time)/pa->lifetime;
2107 CLAMP(time, 0.0f, 1.0f);
2109 copy_v3_v3(tkey.co,pa->state.co);
2110 copy_v3_v3(tkey.vel,pa->state.vel);
2111 tkey.time=pa->state.time;
2113 if (part->type != PART_HAIR) {
2114 if (do_guides(sim->psys->part, sim->psys->effectors, &tkey, p, time)) {
2115 copy_v3_v3(pa->state.co,tkey.co);
2116 /* guides don't produce valid velocity */
2117 sub_v3_v3v3(pa->state.vel, tkey.co, pa->prev_state.co);
2118 mul_v3_fl(pa->state.vel,1.0f/dtime);
2119 pa->state.time=tkey.time;
2123 static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
2125 float rotfac, rot1[4], rot2[4] = {1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac;
2127 if ((part->flag & PART_ROTATIONS) == 0) {
2128 unit_qt(pa->state.rot);
2132 if (part->flag & PART_ROT_DYN) {
2133 extrotfac = len_v3(pa->state.ave);
2139 if ((part->flag & PART_ROT_DYN) && ELEM(part->avemode, PART_AVE_VELOCITY, PART_AVE_HORIZONTAL, PART_AVE_VERTICAL)) {
2141 float len1 = len_v3(pa->prev_state.vel);
2142 float len2 = len_v3(pa->state.vel);
2145 if (len1 == 0.0f || len2 == 0.0f) {
2146 zero_v3(pa->state.ave);
2149 cross_v3_v3v3(pa->state.ave, pa->prev_state.vel, pa->state.vel);
2150 normalize_v3(pa->state.ave);
2151 angle = dot_v3v3(pa->prev_state.vel, pa->state.vel) / (len1 * len2);
2152 mul_v3_fl(pa->state.ave, saacos(angle) / dtime);
2155 get_angular_velocity_vector(part->avemode, &pa->state, vec);
2156 axis_angle_to_quat(rot2, vec, dtime*part->avefac);
2159 rotfac = len_v3(pa->state.ave);
2160 if (rotfac == 0.0f || (part->flag & PART_ROT_DYN)==0 || extrotfac == 0.0f) {
2164 axis_angle_to_quat(rot1,pa->state.ave,rotfac*dtime);
2166 mul_qt_qtqt(pa->state.rot,rot1,pa->prev_state.rot);
2167 mul_qt_qtqt(pa->state.rot,rot2,pa->state.rot);
2169 /* keep rotation quat in good health */
2170 normalize_qt(pa->state.rot);
2173 /************************************************
2176 * The algorithm is roughly:
2177 * 1. Use a BVH tree to search for faces that a particle may collide with.
2178 * 2. Use Newton's method to find the exact time at which the collision occurs.
2179 * http://en.wikipedia.org/wiki/Newton's_method
2181 ************************************************/
2182 #define COLLISION_MAX_COLLISIONS 10
2183 #define COLLISION_MIN_RADIUS 0.001f
2184 #define COLLISION_MIN_DISTANCE 0.0001f
2185 #define COLLISION_ZERO 0.00001f
2186 #define COLLISION_INIT_STEP 0.00008f
2187 typedef float (*NRDistanceFunc)(float *p, float radius, ParticleCollisionElement *pce, float *nor);
2188 static float nr_signed_distance_to_plane(float *p, float radius, ParticleCollisionElement *pce, float *nor)
2190 float p0[3], e1[3], e2[3], d;
2192 sub_v3_v3v3(e1, pce->x1, pce->x0);
2193 sub_v3_v3v3(e2, pce->x2, pce->x0);
2194 sub_v3_v3v3(p0, p, pce->x0);
2196 cross_v3_v3v3(nor, e1, e2);
2199 d = dot_v3v3(p0, nor);
2201 if (pce->inv_nor == -1) {
2208 if (pce->inv_nor == 1) {
2215 static float nr_distance_to_edge(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2217 float v0[3], v1[3], v2[3], c[3];
2219 sub_v3_v3v3(v0, pce->x1, pce->x0);
2220 sub_v3_v3v3(v1, p, pce->x0);
2221 sub_v3_v3v3(v2, p, pce->x1);
2223 cross_v3_v3v3(c, v1, v2);
2225 return fabsf(len_v3(c)/len_v3(v0)) - radius;
2227 static float nr_distance_to_vert(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2229 return len_v3v3(p, pce->x0) - radius;
2231 static void collision_interpolate_element(ParticleCollisionElement *pce, float t, float fac, ParticleCollision *col)
2233 /* t is the current time for newton rhapson */
2234 /* fac is the starting factor for current collision iteration */
2235 /* the col->fac's are factors for the particle subframe step start and end during collision modifier step */
2236 float f = fac + t*(1.f-fac);
2237 float mul = col->fac1 + f * (col->fac2-col->fac1);
2239 madd_v3_v3v3fl(pce->x0, pce->x[0], pce->v[0], mul);
2242 madd_v3_v3v3fl(pce->x1, pce->x[1], pce->v[1], mul);
2245 madd_v3_v3v3fl(pce->x2, pce->x[2], pce->v[2], mul);
2249 static void collision_point_velocity(ParticleCollisionElement *pce)
2253 copy_v3_v3(pce->vel, pce->v[0]);
2256 sub_v3_v3v3(v, pce->v[1], pce->v[0]);
2257 madd_v3_v3fl(pce->vel, v, pce->uv[0]);
2260 sub_v3_v3v3(v, pce->v[2], pce->v[0]);
2261 madd_v3_v3fl(pce->vel, v, pce->uv[1]);
2265 static float collision_point_distance_with_normal(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor)
2268 collision_interpolate_element(pce, 0.f, fac, col);
2273 sub_v3_v3v3(nor, p, pce->x0);
2274 return normalize_v3(nor);
2278 float u, e[3], vec[3];
2279 sub_v3_v3v3(e, pce->x1, pce->x0);
2280 sub_v3_v3v3(vec, p, pce->x0);
2281 u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2283 madd_v3_v3v3fl(nor, vec, e, -u);
2284 return normalize_v3(nor);
2287 return nr_signed_distance_to_plane(p, 0.f, pce, nor);
2291 static void collision_point_on_surface(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *co)
2293 collision_interpolate_element(pce, 0.f, fac, col);
2298 sub_v3_v3v3(co, p, pce->x0);
2300 madd_v3_v3v3fl(co, pce->x0, co, col->radius);
2305 float u, e[3], vec[3], nor[3];
2306 sub_v3_v3v3(e, pce->x1, pce->x0);
2307 sub_v3_v3v3(vec, p, pce->x0);
2308 u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2310 madd_v3_v3v3fl(nor, vec, e, -u);
2313 madd_v3_v3v3fl(co, pce->x0, e, pce->uv[0]);
2314 madd_v3_v3fl(co, nor, col->radius);
2319 float p0[3], e1[3], e2[3], nor[3];
2321 sub_v3_v3v3(e1, pce->x1, pce->x0);
2322 sub_v3_v3v3(e2, pce->x2, pce->x0);
2323 sub_v3_v3v3(p0, p, pce->x0);
2325 cross_v3_v3v3(nor, e1, e2);
2328 if (pce->inv_nor == 1)
2331 madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
2332 madd_v3_v3fl(co, e1, pce->uv[0]);
2333 madd_v3_v3fl(co, e2, pce->uv[1]);
2338 /* find first root in range [0-1] starting from 0 */
2339 static float collision_newton_rhapson(ParticleCollision *col, float radius, ParticleCollisionElement *pce, NRDistanceFunc distance_func)
2341 float t0, t1, dt_init, d0, d1, dd, n[3];
2346 if (col->inv_total_time > 0.0f) {
2347 /* Initial step size should be small, but not too small or floating point
2348 * precision errors will appear. - z0r */
2349 dt_init = COLLISION_INIT_STEP * col->inv_total_time;
2355 /* start from the beginning */
2357 collision_interpolate_element(pce, t0, col->f, col);
2358 d0 = distance_func(col->co1, radius, pce, n);
2362 for (iter=0; iter<10; iter++) {//, itersum++) {
2363 /* get current location */
2364 collision_interpolate_element(pce, t1, col->f, col);
2365 interp_v3_v3v3(pce->p, col->co1, col->co2, t1);
2367 d1 = distance_func(pce->p, radius, pce, n);
2369 /* particle already inside face, so report collision */
2370 if (iter == 0 && d0 < 0.f && d0 > -radius) {
2371 copy_v3_v3(pce->p, col->co1);
2372 copy_v3_v3(pce->nor, n);
2377 /* Zero gradient (no movement relative to element). Can't step from
2380 /* If first iteration, try from other end where the gradient may be
2381 * greater. Note: code duplicated below. */
2384 collision_interpolate_element(pce, t0, col->f, col);
2385 d0 = distance_func(col->co2, radius, pce, n);
2386 t1 = 1.0f - dt_init;
2394 dd = (t1-t0)/(d1-d0);
2401 /* Particle moving away from plane could also mean a strangely rotating
2402 * face, so check from end. Note: code duplicated above. */
2403 if (iter == 0 && t1 < 0.f) {
2405 collision_interpolate_element(pce, t0, col->f, col);
2406 d0 = distance_func(col->co2, radius, pce, n);
2407 t1 = 1.0f - dt_init;
2411 else if (iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.f))
2414 if (d1 <= COLLISION_ZERO && d1 >= -COLLISION_ZERO) {
2415 if (t1 >= -COLLISION_ZERO && t1 <= 1.f) {
2416 if (distance_func == nr_signed_distance_to_plane)
2417 copy_v3_v3(pce->nor, n);
2419 CLAMP(t1, 0.f, 1.f);
2429 static int collision_sphere_to_tri(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2431 ParticleCollisionElement *result = &col->pce;
2437 ct = collision_newton_rhapson(col, radius, pce, nr_signed_distance_to_plane);
2439 if (ct >= 0.f && ct < *t && (result->inside==0 || pce->inside==1) ) {
2440 float e1[3], e2[3], p0[3];
2441 float e1e1, e1e2, e1p0, e2e2, e2p0, inv;
2443 sub_v3_v3v3(e1, pce->x1, pce->x0);
2444 sub_v3_v3v3(e2, pce->x2, pce->x0);
2445 /* XXX: add radius correction here? */
2446 sub_v3_v3v3(p0, pce->p, pce->x0);
2448 e1e1 = dot_v3v3(e1, e1);
2449 e1e2 = dot_v3v3(e1, e2);
2450 e1p0 = dot_v3v3(e1, p0);
2451 e2e2 = dot_v3v3(e2, e2);
2452 e2p0 = dot_v3v3(e2, p0);
2454 inv = 1.f/(e1e1 * e2e2 - e1e2 * e1e2);
2455 u = (e2e2 * e1p0 - e1e2 * e2p0) * inv;
2456 v = (e1e1 * e2p0 - e1e2 * e1p0) * inv;
2458 if (u>=0.f && u<=1.f && v>=0.f && u+v<=1.f) {
2461 /* normal already calculated in pce */
2472 static int collision_sphere_to_edges(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2474 ParticleCollisionElement edge[3], *cur = NULL, *hit = NULL;
2475 ParticleCollisionElement *result = &col->pce;
2480 for (i=0; i<3; i++) {
2482 cur->x[0] = pce->x[i]; cur->x[1] = pce->x[(i+1)%3];
2483 cur->v[0] = pce->v[i]; cur->v[1] = pce->v[(i+1)%3];
2487 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_edge);
2489 if (ct >= 0.f && ct < *t) {
2490 float u, e[3], vec[3];
2492 sub_v3_v3v3(e, cur->x1, cur->x0);
2493 sub_v3_v3v3(vec, cur->p, cur->x0);
2494 u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2496 if (u < 0.f || u > 1.f)
2501 madd_v3_v3v3fl(result->nor, vec, e, -u);
2502 normalize_v3(result->nor);
2515 static int collision_sphere_to_verts(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2517 ParticleCollisionElement vert[3], *cur = NULL, *hit = NULL;
2518 ParticleCollisionElement *result = &col->pce;
2523 for (i=0; i<3; i++) {
2525 cur->x[0] = pce->x[i];
2526 cur->v[0] = pce->v[i];
2530 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert);
2532 if (ct >= 0.f && ct < *t) {
2535 sub_v3_v3v3(result->nor, cur->p, cur->x0);
2536 normalize_v3(result->nor);
2546 /* Callback for BVHTree near test */
2547 void BKE_psys_collision_neartest_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
2549 ParticleCollision *col = (ParticleCollision *) userdata;
2550 ParticleCollisionElement pce;
2551 const MVertTri *vt = &col->md->tri[index];
2552 MVert *x = col->md->x;
2553 MVert *v = col->md->current_v;
2554 float t = hit->dist/col->original_ray_length;
2557 pce.x[0] = x[vt->tri[0]].co;
2558 pce.x[1] = x[vt->tri[1]].co;
2559 pce.x[2] = x[vt->tri[2]].co;
2561 pce.v[0] = v[vt->tri[0]].co;
2562 pce.v[1] = v[vt->tri[1]].co;
2563 pce.v[2] = v[vt->tri[2]].co;
2569 /* don't collide with same face again */
2570 if (col->hit == col->current && col->pce.index == index && col->pce.tot == 3)
2573 collision = collision_sphere_to_tri(col, ray->radius, &pce, &t);
2574 if (col->pce.inside == 0) {
2575 collision += collision_sphere_to_edges(col, ray->radius, &pce, &t);
2576 collision += collision_sphere_to_verts(col, ray->radius, &pce, &t);
2580 hit->dist = col->original_ray_length * t;
2583 collision_point_velocity(&col->pce);
2585 col->hit = col->current;
2588 static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, ListBase *colliders)
2590 const int raycast_flag = BVH_RAYCAST_DEFAULT & ~(BVH_RAYCAST_WATERTIGHT);
2591 ColliderCache *coll;
2594 if (BLI_listbase_is_empty(colliders))
2597 sub_v3_v3v3(ray_dir, col->co2, col->co1);
2599 hit->dist = col->original_ray_length = normalize_v3(ray_dir);
2600 col->pce.inside = 0;
2602 /* even if particle is stationary we want to check for moving colliders */
2603 /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
2604 if (hit->dist == 0.0f)
2605 hit->dist = col->original_ray_length = 0.000001f;
2607 for (coll = colliders->first; coll; coll=coll->next) {
2608 /* for boids: don't check with current ground object */
2609 if (coll->ob == col->skip)
2612 /* particles should not collide with emitter at birth */
2613 if (coll->ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra)
2616 col->current = coll->ob;
2617 col->md = coll->collmd;
2618 col->fac1 = (col->old_cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2619 col->fac2 = (col->cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2621 if (col->md && col->md->bvhtree) {
2622 BLI_bvhtree_ray_cast_ex(
2623 col->md->bvhtree, col->co1, ray_dir, col->radius, hit,
2624 BKE_psys_collision_neartest_cb, col, raycast_flag);
2628 return hit->index >= 0;
2630 static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation)
2632 ParticleCollisionElement *pce = &col->pce;
2633 PartDeflect *pd = col->hit->pd;
2634 float co[3]; /* point of collision */
2635 float x = hit->dist/col->original_ray_length; /* location factor of collision between this iteration */
2636 float f = col->f + x * (1.0f - col->f); /* time factor of collision between timestep */
2637 float dt1 = (f - col->f) * col->total_time; /* time since previous collision (in seconds) */
2638 float dt2 = (1.0f - f) * col->total_time; /* time left after collision (in seconds) */
2639 int through = (BLI_frand() < pd->pdef_perm) ? 1 : 0; /* did particle pass through the collision surface? */
2641 /* calculate exact collision location */
2642 interp_v3_v3v3(co, col->co1, col->co2, x);
2644 /* particle dies in collision */
2645 if (through == 0 && (kill || pd->flag & PDEFLE_KILL_PART)) {
2646 pa->alive = PARS_DYING;
2647 pa->dietime = col->old_cfra + (col->cfra - col->old_cfra) * f;
2649 copy_v3_v3(pa->state.co, co);
2650 interp_v3_v3v3(pa->state.vel, pa->prev_state.vel, pa->state.vel, f);
2651 interp_qt_qtqt(pa->state.rot, pa->prev_state.rot, pa->state.rot, f);
2652 interp_v3_v3v3(pa->state.ave, pa->prev_state.ave, pa->state.ave, f);
2654 /* particle is dead so we don't need to calculate further */
2657 /* figure out velocity and other data after collision */
2659 float v0[3]; /* velocity directly before collision to be modified into velocity directly after collision */
2660 float v0_nor[3];/* normal component of v0 */
2661 float v0_tan[3];/* tangential component of v0 */
2662 float vc_tan[3];/* tangential component of collision surface velocity */
2663 float v0_dot, vc_dot;
2664 float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_frand() - 0.5f);
2665 float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_frand() - 0.5f);
2666 float distance, nor[3], dot;
2668 CLAMP(damp,0.0f, 1.0f);
2669 CLAMP(frict,0.0f, 1.0f);
2671 /* get exact velocity right before collision */
2672 madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1);
2674 /* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */
2675 mul_v3_fl(pce->vel, col->inv_timestep);
2677 /* calculate tangential particle velocity */
2678 v0_dot = dot_v3v3(pce->nor, v0);
2679 madd_v3_v3v3fl(v0_tan, v0, pce->nor, -v0_dot);
2681 /* calculate tangential collider velocity */
2682 vc_dot = dot_v3v3(pce->nor, pce->vel);
2683 madd_v3_v3v3fl(vc_tan, pce->vel, pce->nor, -vc_dot);
2685 /* handle friction effects (tangential and angular velocity) */
2687 /* angular <-> linear velocity */
2688 if (dynamic_rotation) {
2689 float vr_tan[3], v1_tan[3], ave[3];
2691 /* linear velocity of particle surface */
2692 cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave);
2693 mul_v3_fl(vr_tan, pa->size);
2695 /* change to coordinates that move with the collision plane */
2696 sub_v3_v3v3(v1_tan, v0_tan, vc_tan);
2698 /* The resulting velocity is a weighted average of particle cm & surface
2699 * velocity. This weight (related to particle's moment of inertia) could
2700 * be made a parameter for angular <-> linear conversion.
2702 madd_v3_v3fl(v1_tan, vr_tan, -0.4);
2703 mul_v3_fl(v1_tan, 1.0f/1.4f); /* 1/(1+0.4) */
2705 /* rolling friction is around 0.01 of sliding friction (could be made a parameter) */
2706 mul_v3_fl(v1_tan, 1.0f - 0.01f * frict);
2708 /* surface_velocity is opposite to cm velocity */
2709 negate_v3_v3(vr_tan, v1_tan);
2711 /* get back to global coordinates */
2712 add_v3_v3(v1_tan, vc_tan);
2714 /* convert to angular velocity*/
2715 cross_v3_v3v3(ave, vr_tan, pce->nor);
2716 mul_v3_fl(ave, 1.0f/MAX2(pa->size, 0.001f));
2718 /* only friction will cause change in linear & angular velocity */
2719 interp_v3_v3v3(pa->state.ave, pa->state.ave, ave, frict);
2720 interp_v3_v3v3(v0_tan, v0_tan, v1_tan, frict);
2723 /* just basic friction (unphysical due to the friction model used in Blender) */
2724 interp_v3_v3v3(v0_tan, v0_tan, vc_tan, frict);
2728 /* stickiness was possibly added before, so cancel that before calculating new normal velocity */
2729 /* otherwise particles go flying out of the surface because of high reversed sticky velocity */
2730 if (v0_dot < 0.0f) {
2731 v0_dot += pd->pdef_stickness;
2736 /* damping and flipping of velocity around normal */
2737 v0_dot *= 1.0f - damp;
2738 vc_dot *= through ? damp : 1.0f;
2740 /* calculate normal particle velocity */
2741 /* special case for object hitting the particle from behind */
2742 if (through==0 && ((vc_dot>0.0f && v0_dot>0.0f && vc_dot>v0_dot) || (vc_dot<0.0f && v0_dot<0.0f && vc_dot<v0_dot)))
2743 mul_v3_v3fl(v0_nor, pce->nor, vc_dot);
2744 else if (v0_dot > 0.f)
2745 mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? -1.0f : 1.0f) * v0_dot);
2747 mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? 1.0f : -1.0f) * v0_dot);
2749 /* combine components together again */
2750 add_v3_v3v3(v0, v0_nor, v0_tan);
2753 /* keep boids above ground */
2754 BoidParticle *bpa = pa->boid;
2755 if (bpa->data.mode == eBoidMode_OnLand || co[2] <= col->boid_z) {
2756 co[2] = col->boid_z;
2761 /* re-apply acceleration to final location and velocity */
2762 madd_v3_v3v3fl(pa->state.co, co, v0, dt2);
2763 madd_v3_v3fl(pa->state.co, col->acc, 0.5f*dt2*dt2);
2764 madd_v3_v3v3fl(pa->state.vel, v0, col->acc, dt2);
2766 /* make sure particle stays on the right side of the surface */
2768 distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor);
2770 if (distance < col->radius + COLLISION_MIN_DISTANCE)
2771 madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2773 dot = dot_v3v3(nor, v0);
2775 madd_v3_v3fl(v0, nor, -dot);
2777 distance = collision_point_distance_with_normal(pa->state.co, pce, 1.f, col, nor);
2779 if (distance < col->radius + COLLISION_MIN_DISTANCE)
2780 madd_v3_v3fl(pa->state.co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2782 dot = dot_v3v3(nor, pa->state.vel);
2784 madd_v3_v3fl(pa->state.vel, nor, -dot);
2787 /* add stickiness to surface */
2788 madd_v3_v3fl(pa->state.vel, pce->nor, -pd->pdef_stickness);
2790 /* set coordinates for next iteration */
2791 copy_v3_v3(col->co1, co);
2792 copy_v3_v3(col->co2, pa->state.co);
2794 copy_v3_v3(col->ve1, v0);
2795 copy_v3_v3(col->ve2, pa->state.vel);
2800 col->prev = col->hit;
2801 col->prev_index = hit->index;
2805 static void collision_fail(ParticleData *pa, ParticleCollision *col)
2807 /* final chance to prevent total failure, so stick to the surface and hope for the best */
2808 collision_point_on_surface(col->co1, &col->pce, 1.f, col, pa->state.co);
2810 copy_v3_v3(pa->state.vel, col->pce.vel);
2811 mul_v3_fl(pa->state.vel, col->inv_timestep);
2814 /* printf("max iterations\n"); */
2817 /* Particle - Mesh collision detection and response
2819 * -friction and damping
2820 * -angular momentum <-> linear momentum
2821 * -high accuracy by re-applying particle acceleration after collision
2822 * -handles moving, rotating and deforming meshes
2823 * -uses Newton-Rhapson iteration to find the collisions
2824 * -handles spherical particles and (nearly) point like particles
2826 static void collision_check(ParticleSimulationData *sim, int p, float dfra, float cfra)
2828 ParticleSettings *part = sim->psys->part;
2829 ParticleData *pa = sim->psys->particles + p;
2830 ParticleCollision col;
2832 int collision_count=0;
2834 float timestep = psys_get_timestep(sim);
2836 memset(&col, 0, sizeof(ParticleCollision));
2838 col.total_time = timestep * dfra;
2839 col.inv_total_time = 1.0f/col.total_time;
2840 col.inv_timestep = 1.0f/timestep;
2843 col.old_cfra = sim->psys->cfra;
2845 /* get acceleration (from gravity, forcefields etc. to be re-applied in collision response) */
2846 sub_v3_v3v3(col.acc, pa->state.vel, pa->prev_state.vel);
2847 mul_v3_fl(col.acc, 1.f/col.total_time);
2849 /* set values for first iteration */
2850 copy_v3_v3(col.co1, pa->prev_state.co);
2851 copy_v3_v3(col.co2, pa->state.co);
2852 copy_v3_v3(col.ve1, pa->prev_state.vel);
2853 copy_v3_v3(col.ve2, pa->state.vel);
2856 col.radius = ((part->flag & PART_SIZE_DEFL) || (part->phystype == PART_PHYS_BOIDS)) ? pa->size : COLLISION_MIN_RADIUS;
2858 /* override for boids */
2859 if (part->phystype == PART_PHYS_BOIDS && part->boids->options & BOID_ALLOW_LAND) {
2861 col.boid_z = pa->state.co[2];
2862 col.skip = pa->boid->ground;
2865 /* 10 iterations to catch multiple collisions */
2866 while (collision_count < COLLISION_MAX_COLLISIONS) {
2867 if (collision_detect(pa, &col, &hit, sim->colliders)) {
2871 if (collision_count == COLLISION_MAX_COLLISIONS)
2872 collision_fail(pa, &col);
2873 else if (collision_response(pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0)
2880 /************************************************/
2882 /************************************************/
2883 /* check if path cache or children need updating and do it if needed */
2884 static void psys_update_path_cache(ParticleSimulationData *sim, float cfra)
2886 ParticleSystem *psys = sim->psys;
2887 ParticleSettings *part = psys->part;
2888 ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
2890 int distr=0, alloc=0, skip=0;
2892 if ((psys->part->childtype && psys->totchild != psys_get_tot_child(sim->scene, psys)) || psys->recalc&PSYS_RECALC_RESET)
2895 if (alloc || psys->recalc&PSYS_RECALC_CHILD || (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT)))
2900 realloc_particles(sim, sim->psys->totpart);
2902 if (psys_get_tot_child(sim->scene, psys)) {
2903 /* don't generate children while computing the hair keys */
2904 if (!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
2905 distribute_particles(sim, PART_FROM_CHILD);
2907 if (part->childtype==PART_CHILD_FACES && part->parents != 0.0f)
2908 psys_find_parents(sim);
2912 psys_free_children(psys);
2915 if ((part->type==PART_HAIR || psys->flag&PSYS_KEYED || psys->pointcache->flag & PTCACHE_BAKED)==0)
2916 skip = 1; /* only hair, keyed and baked stuff can have paths */
2917 else if (part->ren_as != PART_DRAW_PATH && !(part->type==PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)))
2918 skip = 1; /* particle visualization must be set as path */
2919 else if (!psys->renderdata) {
2920 if (part->draw_as != PART_DRAW_REND)
2921 skip = 1; /* draw visualization */
2922 else if (psys->pointcache->flag & PTCACHE_BAKING)
2923 skip = 1; /* no need to cache paths while baking dynamics */
2924 else if (psys_in_edit_mode(sim->scene, psys)) {
2925 if ((pset->flag & PE_DRAW_PART)==0)
2927 else if (part->childtype==0 && (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED)==0)
2928 skip = 1; /* in edit mode paths are needed for child particles and dynamic hair */
2933 /* particle instance modifier with "path" option need cached paths even if particle system doesn't */
2934 for (base = sim->scene->base.first; base; base= base->next) {
2935 ModifierData *md = modifiers_findByType(base->object, eModifierType_ParticleInstance);
2937 ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
2938 if (pimd->flag & eParticleInstanceFlag_Path && pimd->ob == sim->ob && pimd->psys == (psys - (ParticleSystem*)sim->ob->particlesystem.first)) {
2946 psys_cache_paths(sim, cfra);
2948 /* for render, child particle paths are computed on the fly */
2949 if (part->childtype) {
2950 if (!psys->totchild)
2952 else if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE)==0)
2956 psys_cache_child_paths(sim, cfra, 0);
2959 else if (psys->pathcache)
2960 psys_free_path_cache(psys, NULL);
2963 static bool psys_hair_use_simulation(ParticleData *pa, float max_length)
2965 /* Minimum segment length relative to average length.
2966 * Hairs with segments below this length will be excluded from the simulation,
2967 * because otherwise the solver will become unstable.
2968 * The hair system should always make sure the hair segments have reasonable length ratios,
2969 * but this can happen in old files when e.g. cutting hair.
2971 const float min_length = 0.1f * max_length;
2979 for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) {
2980 float length = len_v3v3(key->co, (key-1)->co);
2981 if (length < min_length)
2988 static MDeformVert *hair_set_pinning(MDeformVert *dvert, float weight)
2991 if (!dvert->totweight) {
2992 dvert->dw = MEM_callocN(sizeof(MDeformWeight), "deformWeight");
2993 dvert->totweight = 1;
2996 dvert->dw->weight = weight;
3002 static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int totedge, DerivedMesh **r_dm, ClothHairData **r_hairdata)
3004 ParticleSystem *psys = sim->psys;
3005 ParticleSettings *part = psys->part;
3007 ClothHairData *hairdata;
3014 float hairmat[4][4];
3020 *r_dm = dm = CDDM_new(totpoint, totedge, 0, 0, 0);
3021 DM_add_vert_layer(dm, CD_MDEFORMVERT, CD_CALLOC, NULL);
3023 mvert = CDDM_get_verts(dm);
3024 medge = CDDM_get_edges(dm);