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