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