66c62d47340e949e747b3e91adf0128da5b9484f
[blender.git] / source / blender / editors / physics / particle_object.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) 2009 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/physics/particle_object.c
27  *  \ingroup edphys
28  */
29
30
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_meshdata_types.h"
37 #include "DNA_modifier_types.h"
38 #include "DNA_scene_types.h"
39
40 #include "BLI_math.h"
41 #include "BLI_listbase.h"
42 #include "BLI_utildefines.h"
43 #include "BLI_string.h"
44
45 #include "BKE_context.h"
46 #include "BKE_depsgraph.h"
47 #include "BKE_DerivedMesh.h"
48 #include "BKE_cdderivedmesh.h"
49 #include "BKE_global.h"
50 #include "BKE_library.h"
51 #include "BKE_main.h"
52 #include "BKE_modifier.h"
53 #include "BKE_object.h"
54 #include "BKE_particle.h"
55 #include "BKE_pointcache.h"
56 #include "BKE_report.h"
57
58 #include "RNA_access.h"
59 #include "RNA_define.h"
60
61 #include "WM_api.h"
62 #include "WM_types.h"
63
64 #include "ED_particle.h"
65 #include "ED_screen.h"
66 #include "ED_object.h"
67
68 #include "UI_resources.h"
69
70 #include "particle_edit_utildefines.h"
71
72 #include "physics_intern.h"
73
74 static float I[4][4] = {{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}};
75
76 /********************** particle system slot operators *********************/
77
78 static int particle_system_add_exec(bContext *C, wmOperator *UNUSED(op))
79 {
80         Main *bmain = CTX_data_main(C);
81         Object *ob= ED_object_context(C);
82         Scene *scene = CTX_data_scene(C);
83
84         if (!scene || !ob)
85                 return OPERATOR_CANCELLED;
86
87         object_add_particle_system(bmain, scene, ob, NULL);
88
89         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
90         WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob);
91
92         return OPERATOR_FINISHED;
93 }
94
95 void OBJECT_OT_particle_system_add(wmOperatorType *ot)
96 {
97         /* identifiers */
98         ot->name = "Add Particle System Slot";
99         ot->idname = "OBJECT_OT_particle_system_add";
100         ot->description = "Add a particle system";
101
102         /* api callbacks */
103         ot->poll = ED_operator_object_active_editable;
104         ot->exec = particle_system_add_exec;
105
106         /* flags */
107         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
108 }
109
110 static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op))
111 {
112         Main *bmain = CTX_data_main(C);
113         Object *ob = ED_object_context(C);
114         Scene *scene = CTX_data_scene(C);
115         int mode_orig;
116
117         if (!scene || !ob)
118                 return OPERATOR_CANCELLED;
119
120         mode_orig = ob->mode;
121         object_remove_particle_system(bmain, scene, ob);
122
123         /* possible this isn't the active object
124          * object_remove_particle_system() clears the mode on the last psys
125          */
126         if (mode_orig & OB_MODE_PARTICLE_EDIT) {
127                 if ((ob->mode & OB_MODE_PARTICLE_EDIT) == 0) {
128                         if (scene->basact && scene->basact->object == ob) {
129                                 WM_event_add_notifier(C, NC_SCENE|ND_MODE|NS_MODE_OBJECT, NULL);
130                         }
131                 }
132         }
133
134         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
135         WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob);
136
137         return OPERATOR_FINISHED;
138 }
139
140 void OBJECT_OT_particle_system_remove(wmOperatorType *ot)
141 {
142         /* identifiers */
143         ot->name = "Remove Particle System Slot";
144         ot->idname = "OBJECT_OT_particle_system_remove";
145         ot->description = "Remove the selected particle system";
146
147         /* api callbacks */
148         ot->poll = ED_operator_object_active_editable;
149         ot->exec = particle_system_remove_exec;
150
151         /* flags */
152         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
153 }
154
155 /********************** new particle settings operator *********************/
156
157 static int psys_poll(bContext *C)
158 {
159         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
160         return (ptr.data != NULL);
161 }
162
163 static int new_particle_settings_exec(bContext *C, wmOperator *UNUSED(op))
164 {
165         Main *bmain= CTX_data_main(C);
166         ParticleSystem *psys;
167         ParticleSettings *part = NULL;
168         Object *ob;
169         PointerRNA ptr;
170
171         ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
172
173         psys = ptr.data;
174
175         /* add or copy particle setting */
176         if (psys->part)
177                 part= BKE_particlesettings_copy(bmain, psys->part);
178         else
179                 part= BKE_particlesettings_add(bmain, "ParticleSettings");
180
181         ob= ptr.id.data;
182
183         if (psys->part)
184                 id_us_min(&psys->part->id);
185
186         psys->part = part;
187
188         psys_check_boid_data(psys);
189
190         DAG_relations_tag_update(bmain);
191         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
192
193         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
194
195         return OPERATOR_FINISHED;
196 }
197
198 void PARTICLE_OT_new(wmOperatorType *ot)
199 {
200         /* identifiers */
201         ot->name = "New Particle Settings";
202         ot->idname = "PARTICLE_OT_new";
203         ot->description = "Add new particle settings";
204
205         /* api callbacks */
206         ot->exec = new_particle_settings_exec;
207         ot->poll = psys_poll;
208
209         /* flags */
210         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
211 }
212
213 /********************** keyed particle target operators *********************/
214
215 static int new_particle_target_exec(bContext *C, wmOperator *UNUSED(op))
216 {
217         Main *bmain = CTX_data_main(C);
218         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
219         ParticleSystem *psys= ptr.data;
220         Object *ob = ptr.id.data;
221
222         ParticleTarget *pt;
223
224         if (!psys)
225                 return OPERATOR_CANCELLED;
226
227         pt = psys->targets.first;
228         for (; pt; pt=pt->next)
229                 pt->flag &= ~PTARGET_CURRENT;
230
231         pt = MEM_callocN(sizeof(ParticleTarget), "keyed particle target");
232
233         pt->flag |= PTARGET_CURRENT;
234         pt->psys = 1;
235
236         BLI_addtail(&psys->targets, pt);
237
238         DAG_relations_tag_update(bmain);
239         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
240
241         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
242
243         return OPERATOR_FINISHED;
244 }
245
246 void PARTICLE_OT_new_target(wmOperatorType *ot)
247 {
248         /* identifiers */
249         ot->name = "New Particle Target";
250         ot->idname = "PARTICLE_OT_new_target";
251         ot->description = "Add a new particle target";
252
253         /* api callbacks */
254         ot->exec = new_particle_target_exec;
255
256         /* flags */
257         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
258 }
259
260 static int remove_particle_target_exec(bContext *C, wmOperator *UNUSED(op))
261 {
262         Main *bmain = CTX_data_main(C);
263         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
264         ParticleSystem *psys= ptr.data;
265         Object *ob = ptr.id.data;
266
267         ParticleTarget *pt;
268
269         if (!psys)
270                 return OPERATOR_CANCELLED;
271
272         pt = psys->targets.first;
273         for (; pt; pt=pt->next) {
274                 if (pt->flag & PTARGET_CURRENT) {
275                         BLI_remlink(&psys->targets, pt);
276                         MEM_freeN(pt);
277                         break;
278                 }
279
280         }
281         pt = psys->targets.last;
282
283         if (pt)
284                 pt->flag |= PTARGET_CURRENT;
285
286         DAG_relations_tag_update(bmain);
287         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
288
289         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
290
291         return OPERATOR_FINISHED;
292 }
293
294 void PARTICLE_OT_target_remove(wmOperatorType *ot)
295 {
296         /* identifiers */
297         ot->name = "Remove Particle Target";
298         ot->idname = "PARTICLE_OT_target_remove";
299         ot->description = "Remove the selected particle target";
300
301         /* api callbacks */
302         ot->exec = remove_particle_target_exec;
303
304         /* flags */
305         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
306 }
307
308 /************************ move up particle target operator *********************/
309
310 static int target_move_up_exec(bContext *C, wmOperator *UNUSED(op))
311 {
312         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
313         ParticleSystem *psys= ptr.data;
314         Object *ob = ptr.id.data;
315         ParticleTarget *pt;
316
317         if (!psys)
318                 return OPERATOR_CANCELLED;
319
320         pt = psys->targets.first;
321         for (; pt; pt=pt->next) {
322                 if (pt->flag & PTARGET_CURRENT && pt->prev) {
323                         BLI_remlink(&psys->targets, pt);
324                         BLI_insertlinkbefore(&psys->targets, pt->prev, pt);
325
326                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
327                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
328                         break;
329                 }
330         }
331
332         return OPERATOR_FINISHED;
333 }
334
335 void PARTICLE_OT_target_move_up(wmOperatorType *ot)
336 {
337         ot->name = "Move Up Target";
338         ot->idname = "PARTICLE_OT_target_move_up";
339         ot->description = "Move particle target up in the list";
340
341         ot->exec = target_move_up_exec;
342
343         /* flags */
344         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
345 }
346
347 /************************ move down particle target operator *********************/
348
349 static int target_move_down_exec(bContext *C, wmOperator *UNUSED(op))
350 {
351         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
352         ParticleSystem *psys= ptr.data;
353         Object *ob = ptr.id.data;
354         ParticleTarget *pt;
355
356         if (!psys)
357                 return OPERATOR_CANCELLED;
358         pt = psys->targets.first;
359         for (; pt; pt=pt->next) {
360                 if (pt->flag & PTARGET_CURRENT && pt->next) {
361                         BLI_remlink(&psys->targets, pt);
362                         BLI_insertlinkafter(&psys->targets, pt->next, pt);
363
364                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
365                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
366                         break;
367                 }
368         }
369
370         return OPERATOR_FINISHED;
371 }
372
373 void PARTICLE_OT_target_move_down(wmOperatorType *ot)
374 {
375         ot->name = "Move Down Target";
376         ot->idname = "PARTICLE_OT_target_move_down";
377         ot->description = "Move particle target down in the list";
378
379         ot->exec = target_move_down_exec;
380
381         /* flags */
382         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
383 }
384
385 /************************ move up particle dupliweight operator *********************/
386
387 static int dupliob_move_up_exec(bContext *C, wmOperator *UNUSED(op))
388 {
389         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
390         ParticleSystem *psys= ptr.data;
391         ParticleSettings *part;
392         ParticleDupliWeight *dw;
393
394         if (!psys)
395                 return OPERATOR_CANCELLED;
396
397         part = psys->part;
398         for (dw=part->dupliweights.first; dw; dw=dw->next) {
399                 if (dw->flag & PART_DUPLIW_CURRENT && dw->prev) {
400                         BLI_remlink(&part->dupliweights, dw);
401                         BLI_insertlinkbefore(&part->dupliweights, dw->prev, dw);
402
403                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
404                         break;
405                 }
406         }
407
408         return OPERATOR_FINISHED;
409 }
410
411 void PARTICLE_OT_dupliob_move_up(wmOperatorType *ot)
412 {
413         ot->name = "Move Up Dupli Object";
414         ot->idname = "PARTICLE_OT_dupliob_move_up";
415         ot->description = "Move dupli object up in the list";
416
417         ot->exec = dupliob_move_up_exec;
418
419         /* flags */
420         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
421 }
422
423 /********************** particle dupliweight operators *********************/
424
425 static int copy_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op))
426 {
427         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
428         ParticleSystem *psys= ptr.data;
429         ParticleSettings *part;
430         ParticleDupliWeight *dw;
431
432         if (!psys)
433                 return OPERATOR_CANCELLED;
434         part = psys->part;
435         for (dw=part->dupliweights.first; dw; dw=dw->next) {
436                 if (dw->flag & PART_DUPLIW_CURRENT) {
437                         dw->flag &= ~PART_DUPLIW_CURRENT;
438                         dw = MEM_dupallocN(dw);
439                         dw->flag |= PART_DUPLIW_CURRENT;
440                         BLI_addhead(&part->dupliweights, dw);
441
442                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
443                         break;
444                 }
445         }
446
447         return OPERATOR_FINISHED;
448 }
449
450 void PARTICLE_OT_dupliob_copy(wmOperatorType *ot)
451 {
452         /* identifiers */
453         ot->name = "Copy Particle Dupliob";
454         ot->idname = "PARTICLE_OT_dupliob_copy";
455         ot->description = "Duplicate the current dupliobject";
456
457         /* api callbacks */
458         ot->exec = copy_particle_dupliob_exec;
459
460         /* flags */
461         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
462 }
463
464 static int remove_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op))
465 {
466         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
467         ParticleSystem *psys= ptr.data;
468         ParticleSettings *part;
469         ParticleDupliWeight *dw;
470
471         if (!psys)
472                 return OPERATOR_CANCELLED;
473
474         part = psys->part;
475         for (dw=part->dupliweights.first; dw; dw=dw->next) {
476                 if (dw->flag & PART_DUPLIW_CURRENT) {
477                         BLI_remlink(&part->dupliweights, dw);
478                         MEM_freeN(dw);
479                         break;
480                 }
481
482         }
483         dw = part->dupliweights.last;
484
485         if (dw)
486                 dw->flag |= PART_DUPLIW_CURRENT;
487
488         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
489
490         return OPERATOR_FINISHED;
491 }
492
493 void PARTICLE_OT_dupliob_remove(wmOperatorType *ot)
494 {
495         /* identifiers */
496         ot->name = "Remove Particle Dupliobject";
497         ot->idname = "PARTICLE_OT_dupliob_remove";
498         ot->description = "Remove the selected dupliobject";
499
500         /* api callbacks */
501         ot->exec = remove_particle_dupliob_exec;
502
503         /* flags */
504         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
505 }
506
507 /************************ move down particle dupliweight operator *********************/
508
509 static int dupliob_move_down_exec(bContext *C, wmOperator *UNUSED(op))
510 {
511         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
512         ParticleSystem *psys= ptr.data;
513         ParticleSettings *part;
514         ParticleDupliWeight *dw;
515
516         if (!psys)
517                 return OPERATOR_CANCELLED;
518
519         part = psys->part;
520         for (dw=part->dupliweights.first; dw; dw=dw->next) {
521                 if (dw->flag & PART_DUPLIW_CURRENT && dw->next) {
522                         BLI_remlink(&part->dupliweights, dw);
523                         BLI_insertlinkafter(&part->dupliweights, dw->next, dw);
524
525                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
526                         break;
527                 }
528         }
529
530         return OPERATOR_FINISHED;
531 }
532
533 void PARTICLE_OT_dupliob_move_down(wmOperatorType *ot)
534 {
535         ot->name = "Move Down Dupli Object";
536         ot->idname = "PARTICLE_OT_dupliob_move_down";
537         ot->description = "Move dupli object down in the list";
538
539         ot->exec = dupliob_move_down_exec;
540
541         /* flags */
542         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
543 }
544
545 /************************ connect/disconnect hair operators *********************/
546
547 static void disconnect_hair(Scene *scene, Object *ob, ParticleSystem *psys)
548 {
549         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
550         ParticleEditSettings *pset= PE_settings(scene);
551         ParticleData *pa;
552         PTCacheEdit *edit;
553         PTCacheEditPoint *point;
554         PTCacheEditKey *ekey = NULL;
555         HairKey *key;
556         int i, k;
557         float hairmat[4][4];
558
559         if (!ob || !psys || psys->flag & PSYS_GLOBAL_HAIR)
560                 return;
561
562         if (!psys->part || psys->part->type != PART_HAIR)
563                 return;
564
565         edit = psys->edit;
566         point= edit ? edit->points : NULL;
567
568         for (i=0, pa=psys->particles; i<psys->totpart; i++, pa++) {
569                 if (point) {
570                         ekey = point->keys;
571                         point++;
572                 }
573
574                 psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, pa, hairmat);
575
576                 for (k=0, key=pa->hair; k<pa->totkey; k++, key++) {
577                         mul_m4_v3(hairmat, key->co);
578
579                         if (ekey) {
580                                 ekey->flag &= ~PEK_USE_WCO;
581                                 ekey++;
582                         }
583                 }
584         }
585
586         psys_free_path_cache(psys, psys->edit);
587
588         psys->flag |= PSYS_GLOBAL_HAIR;
589
590         if (ELEM(pset->brushtype, PE_BRUSH_ADD, PE_BRUSH_PUFF))
591                 pset->brushtype = PE_BRUSH_NONE;
592
593         PE_update_object(scene, ob, 0);
594 }
595
596 static int disconnect_hair_exec(bContext *C, wmOperator *op)
597 {
598         Scene *scene= CTX_data_scene(C);
599         Object *ob= ED_object_context(C);
600         ParticleSystem *psys= NULL;
601         const bool all = RNA_boolean_get(op->ptr, "all");
602
603         if (!ob)
604                 return OPERATOR_CANCELLED;
605
606         if (all) {
607                 for (psys=ob->particlesystem.first; psys; psys=psys->next) {
608                         disconnect_hair(scene, ob, psys);
609                 }
610         }
611         else {
612                 psys = psys_get_current(ob);
613                 disconnect_hair(scene, ob, psys);
614         }
615
616         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
617         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
618
619         return OPERATOR_FINISHED;
620 }
621
622 void PARTICLE_OT_disconnect_hair(wmOperatorType *ot)
623 {
624         ot->name = "Disconnect Hair";
625         ot->description = "Disconnect hair from the emitter mesh";
626         ot->idname = "PARTICLE_OT_disconnect_hair";
627
628         ot->exec = disconnect_hair_exec;
629
630         /* flags */
631         ot->flag = OPTYPE_UNDO;  /* No REGISTER, redo does not work due to missing update, see T47750. */
632
633         RNA_def_boolean(ot->srna, "all", 0, "All hair", "Disconnect all hair systems from the emitter mesh");
634 }
635
636 /* from/to_world_space : whether from/to particles are in world or hair space
637  * from/to_mat : additional transform for from/to particles (e.g. for using object space copying)
638  */
639 static bool remap_hair_emitter(Scene *scene, Object *ob, ParticleSystem *psys,
640                                Object *target_ob, ParticleSystem *target_psys, PTCacheEdit *target_edit,
641                                float from_mat[4][4], float to_mat[4][4], bool from_global, bool to_global)
642 {
643         ParticleSystemModifierData *target_psmd = psys_get_modifier(target_ob, target_psys);
644         ParticleData *pa, *tpa;
645         PTCacheEditPoint *edit_point;
646         PTCacheEditKey *ekey;
647         BVHTreeFromMesh bvhtree= {NULL};
648         MFace *mface = NULL, *mf;
649         MEdge *medge = NULL, *me;
650         MVert *mvert;
651         DerivedMesh *dm, *target_dm;
652         int numverts;
653         int i, k;
654         float from_ob_imat[4][4], to_ob_imat[4][4];
655         float from_imat[4][4], to_imat[4][4];
656
657         if (!target_psmd->dm_final)
658                 return false;
659         if (!psys->part || psys->part->type != PART_HAIR)
660                 return false;
661         if (!target_psys->part || target_psys->part->type != PART_HAIR)
662                 return false;
663
664         edit_point = target_edit ? target_edit->points : NULL;
665
666         invert_m4_m4(from_ob_imat, ob->obmat);
667         invert_m4_m4(to_ob_imat, target_ob->obmat);
668         invert_m4_m4(from_imat, from_mat);
669         invert_m4_m4(to_imat, to_mat);
670
671         if (target_psmd->dm_final->deformedOnly) {
672                 /* we don't want to mess up target_psmd->dm when converting to global coordinates below */
673                 dm = target_psmd->dm_final;
674         }
675         else {
676                 dm = target_psmd->dm_deformed;
677         }
678         target_dm = target_psmd->dm_final;
679         if (dm == NULL) {
680                 return false;
681         }
682         /* don't modify the original vertices */
683         dm = CDDM_copy(dm);
684
685         /* BMESH_ONLY, deform dm may not have tessface */
686         DM_ensure_tessface(dm);
687
688         numverts = dm->getNumVerts(dm);
689         mvert = dm->getVertArray(dm);
690
691         /* convert to global coordinates */
692         for (i=0; i<numverts; i++)
693                 mul_m4_v3(to_mat, mvert[i].co);
694
695         if (dm->getNumTessFaces(dm) != 0) {
696                 mface = dm->getTessFaceArray(dm);
697                 bvhtree_from_mesh_get(&bvhtree, dm, BVHTREE_FROM_FACES, 2);
698         }
699         else if (dm->getNumEdges(dm) != 0) {
700                 medge = dm->getEdgeArray(dm);
701                 bvhtree_from_mesh_get(&bvhtree, dm, BVHTREE_FROM_EDGES, 2);
702         }
703         else {
704                 dm->release(dm);
705                 return false;
706         }
707
708         for (i = 0, tpa = target_psys->particles, pa = psys->particles;
709              i < target_psys->totpart;
710              i++, tpa++, pa++)
711         {
712                 float from_co[3];
713                 BVHTreeNearest nearest;
714
715                 if (from_global)
716                         mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].co);
717                 else
718                         mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].world_co);
719                 mul_m4_v3(from_mat, from_co);
720
721                 nearest.index = -1;
722                 nearest.dist_sq = FLT_MAX;
723
724                 BLI_bvhtree_find_nearest(bvhtree.tree, from_co, &nearest, bvhtree.nearest_callback, &bvhtree);
725
726                 if (nearest.index == -1) {
727                         if (G.debug & G_DEBUG)
728                                 printf("No nearest point found for hair root!");
729                         continue;
730                 }
731
732                 if (mface) {
733                         float v[4][3];
734
735                         mf = &mface[nearest.index];
736
737                         copy_v3_v3(v[0], mvert[mf->v1].co);
738                         copy_v3_v3(v[1], mvert[mf->v2].co);
739                         copy_v3_v3(v[2], mvert[mf->v3].co);
740                         if (mf->v4) {
741                                 copy_v3_v3(v[3], mvert[mf->v4].co);
742                                 interp_weights_poly_v3(tpa->fuv, v, 4, nearest.co);
743                         }
744                         else
745                                 interp_weights_poly_v3(tpa->fuv, v, 3, nearest.co);
746                         tpa->foffset = 0.0f;
747
748                         tpa->num = nearest.index;
749                         tpa->num_dmcache = psys_particle_dm_face_lookup(target_dm, dm, tpa->num, tpa->fuv, NULL);
750                 }
751                 else {
752                         me = &medge[nearest.index];
753
754                         tpa->fuv[1] = line_point_factor_v3(nearest.co,
755                                                            mvert[me->v1].co,
756                                                            mvert[me->v2].co);
757                         tpa->fuv[0] = 1.0f - tpa->fuv[1];
758                         tpa->fuv[2] = tpa->fuv[3] = 0.0f;
759                         tpa->foffset = 0.0f;
760
761                         tpa->num = nearest.index;
762                         tpa->num_dmcache = -1;
763                 }
764
765                 /* translate hair keys */
766                 {
767                         HairKey *key, *tkey;
768                         float hairmat[4][4], imat[4][4];
769                         float offset[3];
770
771                         if (to_global)
772                                 copy_m4_m4(imat, target_ob->obmat);
773                         else {
774                                 /* note: using target_dm here, which is in target_ob object space and has full modifiers */
775                                 psys_mat_hair_to_object(target_ob, target_dm, target_psys->part->from, tpa, hairmat);
776                                 invert_m4_m4(imat, hairmat);
777                         }
778                         mul_m4_m4m4(imat, imat, to_imat);
779
780                         /* offset in world space */
781                         sub_v3_v3v3(offset, nearest.co, from_co);
782
783                         if (edit_point) {
784                                 for (k=0, key=pa->hair, tkey=tpa->hair, ekey = edit_point->keys; k<tpa->totkey; k++, key++, tkey++, ekey++) {
785                                         float co_orig[3];
786
787                                         if (from_global)
788                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->co);
789                                         else
790                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->world_co);
791                                         mul_m4_v3(from_mat, co_orig);
792
793                                         add_v3_v3v3(tkey->co, co_orig, offset);
794
795                                         mul_m4_v3(imat, tkey->co);
796
797                                         ekey->flag |= PEK_USE_WCO;
798                                 }
799
800                                 edit_point++;
801                         }
802                         else {
803                                 for (k=0, key=pa->hair, tkey=tpa->hair; k<tpa->totkey; k++, key++, tkey++) {
804                                         float co_orig[3];
805
806                                         if (from_global)
807                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->co);
808                                         else
809                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->world_co);
810                                         mul_m4_v3(from_mat, co_orig);
811
812                                         add_v3_v3v3(tkey->co, co_orig, offset);
813
814                                         mul_m4_v3(imat, tkey->co);
815                                 }
816                         }
817                 }
818         }
819
820         free_bvhtree_from_mesh(&bvhtree);
821         dm->release(dm);
822
823         psys_free_path_cache(target_psys, target_edit);
824
825         PE_update_object(scene, target_ob, 0);
826
827         return true;
828 }
829
830 static bool connect_hair(Scene *scene, Object *ob, ParticleSystem *psys)
831 {
832         bool ok;
833
834         if (!psys)
835                 return false;
836
837         ok = remap_hair_emitter(scene, ob, psys, ob, psys, psys->edit, ob->obmat, ob->obmat, psys->flag & PSYS_GLOBAL_HAIR, false);
838         psys->flag &= ~PSYS_GLOBAL_HAIR;
839
840         return ok;
841 }
842
843 static int connect_hair_exec(bContext *C, wmOperator *op)
844 {
845         Scene *scene= CTX_data_scene(C);
846         Object *ob= ED_object_context(C);
847         ParticleSystem *psys= NULL;
848         const bool all = RNA_boolean_get(op->ptr, "all");
849         bool any_connected = false;
850
851         if (!ob)
852                 return OPERATOR_CANCELLED;
853
854         if (all) {
855                 for (psys=ob->particlesystem.first; psys; psys=psys->next) {
856                         any_connected |= connect_hair(scene, ob, psys);
857                 }
858         }
859         else {
860                 psys = psys_get_current(ob);
861                 any_connected |= connect_hair(scene, ob, psys);
862         }
863
864         if (!any_connected) {
865                 BKE_report(op->reports, RPT_WARNING,
866                            "No hair connected (can't connect hair if particle system modifier is disabled)");
867                 return OPERATOR_CANCELLED;
868         }
869
870         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
871         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
872
873         return OPERATOR_FINISHED;
874 }
875
876 void PARTICLE_OT_connect_hair(wmOperatorType *ot)
877 {
878         ot->name = "Connect Hair";
879         ot->description = "Connect hair to the emitter mesh";
880         ot->idname = "PARTICLE_OT_connect_hair";
881
882         ot->exec = connect_hair_exec;
883
884         /* flags */
885         ot->flag = OPTYPE_UNDO;  /* No REGISTER, redo does not work due to missing update, see T47750. */
886
887         RNA_def_boolean(ot->srna, "all", 0, "All hair", "Connect all hair systems to the emitter mesh");
888 }
889
890 /************************ particle system copy operator *********************/
891
892 typedef enum eCopyParticlesSpace {
893         PAR_COPY_SPACE_OBJECT   = 0,
894         PAR_COPY_SPACE_WORLD    = 1,
895 } eCopyParticlesSpace;
896
897 static void copy_particle_edit(Scene *scene, Object *ob, ParticleSystem *psys, ParticleSystem *psys_from)
898 {
899         PTCacheEdit *edit_from = psys_from->edit, *edit;
900         ParticleData *pa;
901         KEY_K;
902         POINT_P;
903
904         if (!edit_from)
905                 return;
906
907         edit = MEM_dupallocN(edit_from);
908         edit->psys = psys;
909         psys->edit = edit;
910
911         edit->pathcache = NULL;
912         BLI_listbase_clear(&edit->pathcachebufs);
913
914         edit->emitter_field = NULL;
915         edit->emitter_cosnos = NULL;
916
917         edit->points = MEM_dupallocN(edit_from->points);
918         pa = psys->particles;
919         LOOP_POINTS {
920                 HairKey *hkey = pa->hair;
921
922                 point->keys= MEM_dupallocN(point->keys);
923                 LOOP_KEYS {
924                         key->co = hkey->co;
925                         key->time = &hkey->time;
926                         key->flag = hkey->editflag;
927                         if (!(psys->flag & PSYS_GLOBAL_HAIR)) {
928                                 key->flag |= PEK_USE_WCO;
929                                 hkey->editflag |= PEK_USE_WCO;
930                         }
931
932                         hkey++;
933                 }
934
935                 pa++;
936         }
937         update_world_cos(ob, edit);
938
939         UI_GetThemeColor3ubv(TH_EDGE_SELECT, edit->sel_col);
940         UI_GetThemeColor3ubv(TH_WIRE, edit->nosel_col);
941
942         recalc_lengths(edit);
943         recalc_emitter_field(ob, psys);
944         PE_update_object(scene, ob, true);
945 }
946
947 static void remove_particle_systems_from_object(Object *ob_to)
948 {
949         ModifierData *md, *md_next;
950
951         if (ob_to->type != OB_MESH)
952                 return;
953         if (!ob_to->data || ID_IS_LINKED(ob_to->data))
954                 return;
955
956         for (md = ob_to->modifiers.first; md; md = md_next) {
957                 md_next = md->next;
958
959                 /* remove all particle system modifiers as well,
960                  * these need to sync to the particle system list
961                  */
962                 if (ELEM(md->type, eModifierType_ParticleSystem, eModifierType_DynamicPaint, eModifierType_Smoke)) {
963                         BLI_remlink(&ob_to->modifiers, md);
964                         modifier_free(md);
965                 }
966         }
967
968         BKE_object_free_particlesystems(ob_to);
969 }
970
971 /* single_psys_from is optional, if NULL all psys of ob_from are copied */
972 static bool copy_particle_systems_to_object(Main *bmain,
973                                             Scene *scene,
974                                             Object *ob_from,
975                                             ParticleSystem *single_psys_from,
976                                             Object *ob_to,
977                                             int space,
978                                             bool duplicate_settings)
979 {
980         ModifierData *md;
981         ParticleSystem *psys_start = NULL, *psys, *psys_from;
982         ParticleSystem **tmp_psys;
983         DerivedMesh *final_dm;
984         CustomDataMask cdmask;
985         int i, totpsys;
986
987         if (ob_to->type != OB_MESH)
988                 return false;
989         if (!ob_to->data || ID_IS_LINKED(ob_to->data))
990                 return false;
991
992         /* For remapping we need a valid DM.
993          * Because the modifiers are appended at the end it's safe to use
994          * the final DM of the object without particles.
995          * However, when evaluating the DM all the particle modifiers must be valid,
996          * i.e. have the psys assigned already.
997          * To break this hen/egg problem we create all psys separately first (to collect required customdata masks),
998          * then create the DM, then add them to the object and make the psys modifiers ...
999          */
1000         #define PSYS_FROM_FIRST (single_psys_from ? single_psys_from : ob_from->particlesystem.first)
1001         #define PSYS_FROM_NEXT(cur) (single_psys_from ? NULL : (cur)->next)
1002         totpsys = single_psys_from ? 1 : BLI_listbase_count(&ob_from->particlesystem);
1003
1004         tmp_psys = MEM_mallocN(sizeof(ParticleSystem*) * totpsys, "temporary particle system array");
1005
1006         cdmask = 0;
1007         for (psys_from = PSYS_FROM_FIRST, i = 0;
1008              psys_from;
1009              psys_from = PSYS_FROM_NEXT(psys_from), ++i)
1010         {
1011                 psys = BKE_object_copy_particlesystem(psys_from, 0);
1012                 tmp_psys[i] = psys;
1013
1014                 if (psys_start == NULL)
1015                         psys_start = psys;
1016
1017                 cdmask |= psys_emitter_customdata_mask(psys);
1018         }
1019         /* to iterate source and target psys in sync,
1020          * we need to know where the newly added psys start
1021          */
1022         psys_start = totpsys > 0 ? tmp_psys[0] : NULL;
1023
1024         /* get the DM (psys and their modifiers have not been appended yet) */
1025         final_dm = mesh_get_derived_final(scene, ob_to, cdmask);
1026
1027         /* now append psys to the object and make modifiers */
1028         for (i = 0, psys_from = PSYS_FROM_FIRST;
1029              i < totpsys;
1030              ++i, psys_from = PSYS_FROM_NEXT(psys_from))
1031         {
1032                 ParticleSystemModifierData *psmd;
1033
1034                 psys = tmp_psys[i];
1035
1036                 /* append to the object */
1037                 BLI_addtail(&ob_to->particlesystem, psys);
1038
1039                 /* add a particle system modifier for each system */
1040                 md = modifier_new(eModifierType_ParticleSystem);
1041                 psmd = (ParticleSystemModifierData *)md;
1042                 /* push on top of the stack, no use trying to reproduce old stack order */
1043                 BLI_addtail(&ob_to->modifiers, md);
1044
1045                 BLI_snprintf(md->name, sizeof(md->name), "ParticleSystem %i", i);
1046                 modifier_unique_name(&ob_to->modifiers, (ModifierData *)psmd);
1047
1048                 psmd->psys = psys;
1049                 psmd->dm_final = CDDM_copy(final_dm);
1050                 CDDM_calc_normals(psmd->dm_final);
1051                 DM_ensure_tessface(psmd->dm_final);
1052
1053                 if (psys_from->edit)
1054                         copy_particle_edit(scene, ob_to, psys, psys_from);
1055
1056                 if (duplicate_settings) {
1057                         id_us_min(&psys->part->id);
1058                         psys->part = BKE_particlesettings_copy(bmain, psys->part);
1059                 }
1060         }
1061         MEM_freeN(tmp_psys);
1062
1063         /* note: do this after creating DM copies for all the particle system modifiers,
1064          * the remapping otherwise makes final_dm invalid!
1065          */
1066         for (psys = psys_start, psys_from = PSYS_FROM_FIRST, i = 0;
1067              psys;
1068              psys = psys->next, psys_from = PSYS_FROM_NEXT(psys_from), ++i)
1069         {
1070                 float (*from_mat)[4], (*to_mat)[4];
1071
1072                 switch (space) {
1073                         case PAR_COPY_SPACE_OBJECT:
1074                                 from_mat = I;
1075                                 to_mat = I;
1076                                 break;
1077                         case PAR_COPY_SPACE_WORLD:
1078                                 from_mat = ob_from->obmat;
1079                                 to_mat = ob_to->obmat;
1080                                 break;
1081                         default:
1082                                 /* should not happen */
1083                                 from_mat = to_mat = NULL;
1084                                 BLI_assert(false);
1085                                 break;
1086                 }
1087                 if (ob_from != ob_to) {
1088                         remap_hair_emitter(scene, ob_from, psys_from, ob_to, psys, psys->edit, from_mat, to_mat, psys_from->flag & PSYS_GLOBAL_HAIR, psys->flag & PSYS_GLOBAL_HAIR);
1089                 }
1090
1091                 /* tag for recalc */
1092 //              psys->recalc |= PSYS_RECALC_RESET;
1093         }
1094
1095         #undef PSYS_FROM_FIRST
1096         #undef PSYS_FROM_NEXT
1097
1098         DAG_id_tag_update(&ob_to->id, OB_RECALC_DATA);
1099         WM_main_add_notifier(NC_OBJECT | ND_PARTICLE | NA_EDITED, ob_to);
1100         return true;
1101 }
1102
1103 static int copy_particle_systems_poll(bContext *C)
1104 {
1105         Object *ob;
1106         if (!ED_operator_object_active_editable(C))
1107                 return false;
1108
1109         ob = ED_object_active_context(C);
1110         if (BLI_listbase_is_empty(&ob->particlesystem))
1111                 return false;
1112
1113         return true;
1114 }
1115
1116 static int copy_particle_systems_exec(bContext *C, wmOperator *op)
1117 {
1118         const int space = RNA_enum_get(op->ptr, "space");
1119         const bool remove_target_particles = RNA_boolean_get(op->ptr, "remove_target_particles");
1120         const bool use_active = RNA_boolean_get(op->ptr, "use_active");
1121         Main *bmain = CTX_data_main(C);
1122         Scene *scene = CTX_data_scene(C);
1123         Object *ob_from = ED_object_active_context(C);
1124         ParticleSystem *psys_from = use_active ? CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data : NULL;
1125
1126         int changed_tot = 0;
1127         int fail = 0;
1128
1129         CTX_DATA_BEGIN (C, Object *, ob_to, selected_editable_objects)
1130         {
1131                 if (ob_from != ob_to) {
1132                         bool changed = false;
1133                         if (remove_target_particles) {
1134                                 remove_particle_systems_from_object(ob_to);
1135                                 changed = true;
1136                         }
1137                         if (copy_particle_systems_to_object(bmain, scene, ob_from, psys_from, ob_to, space, false))
1138                                 changed = true;
1139                         else
1140                                 fail++;
1141
1142                         if (changed)
1143                                 changed_tot++;
1144                 }
1145         }
1146         CTX_DATA_END;
1147
1148         if ((changed_tot == 0 && fail == 0) || fail) {
1149                 BKE_reportf(op->reports, RPT_ERROR,
1150                             "Copy particle systems to selected: %d done, %d failed",
1151                             changed_tot, fail);
1152         }
1153
1154         return OPERATOR_FINISHED;
1155 }
1156
1157 void PARTICLE_OT_copy_particle_systems(wmOperatorType *ot)
1158 {
1159         static const EnumPropertyItem space_items[] = {
1160                 {PAR_COPY_SPACE_OBJECT, "OBJECT", 0, "Object", "Copy inside each object's local space"},
1161                 {PAR_COPY_SPACE_WORLD, "WORLD", 0, "World", "Copy in world space"},
1162                 {0, NULL, 0, NULL, NULL}
1163         };
1164
1165         ot->name = "Copy Particle Systems";
1166         ot->description = "Copy particle systems from the active object to selected objects";
1167         ot->idname = "PARTICLE_OT_copy_particle_systems";
1168
1169         ot->poll = copy_particle_systems_poll;
1170         ot->exec = copy_particle_systems_exec;
1171
1172         /* flags */
1173         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1174
1175         RNA_def_enum(ot->srna, "space", space_items, PAR_COPY_SPACE_OBJECT, "Space", "Space transform for copying from one object to another");
1176         RNA_def_boolean(ot->srna, "remove_target_particles", true, "Remove Target Particles", "Remove particle systems on the target objects");
1177         RNA_def_boolean(ot->srna, "use_active", false, "Use Active", "Use the active particle system from the context");
1178 }
1179
1180 static int duplicate_particle_systems_poll(bContext *C)
1181 {
1182         if (!ED_operator_object_active_editable(C)) {
1183                 return false;
1184         }
1185         Object *ob = ED_object_active_context(C);
1186         if (BLI_listbase_is_empty(&ob->particlesystem)) {
1187                 return false;
1188         }
1189         return true;
1190 }
1191
1192 static int duplicate_particle_systems_exec(bContext *C, wmOperator *op)
1193 {
1194         const bool duplicate_settings = RNA_boolean_get(op->ptr, "use_duplicate_settings");
1195         Scene *scene = CTX_data_scene(C);
1196         Object *ob = ED_object_active_context(C);
1197         ParticleSystem *psys = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data;
1198         copy_particle_systems_to_object(CTX_data_main(C), scene, ob, psys, ob,
1199                                         PAR_COPY_SPACE_OBJECT, duplicate_settings);
1200         return OPERATOR_FINISHED;
1201 }
1202
1203 void PARTICLE_OT_duplicate_particle_system(wmOperatorType *ot)
1204 {
1205         ot->name = "Duplicate Particle Systems";
1206         ot->description = "Duplicate particle system within the active object";
1207         ot->idname = "PARTICLE_OT_duplicate_particle_system";
1208
1209         ot->poll = duplicate_particle_systems_poll;
1210         ot->exec = duplicate_particle_systems_exec;
1211
1212         /* flags */
1213         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1214
1215         RNA_def_boolean(ot->srna, "use_duplicate_settings", false, "Duplicate Settings",
1216                         "Duplicate settings as well, so new particle system uses own settings");
1217 }