Fix for[#24422] Crash when switching to Point Select Mode - particle hair
[blender-staging.git] / source / blender / editors / physics / particle_edit.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2007 by Janne Karhu.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdlib.h>
31 #include <math.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_scene_types.h"
37 #include "DNA_mesh_types.h"
38 #include "DNA_meshdata_types.h"
39 #include "DNA_view3d_types.h"
40 #include "DNA_screen_types.h"
41 #include "DNA_space_types.h"
42
43 #include "BKE_DerivedMesh.h"
44 #include "BKE_depsgraph.h"
45
46 #include "BKE_context.h"
47 #include "BKE_global.h"
48 #include "BKE_object.h"
49 #include "BKE_mesh.h"
50 #include "BKE_modifier.h"
51 #include "BKE_particle.h"
52 #include "BKE_report.h"
53 #include "BKE_scene.h"
54 #include "BKE_utildefines.h"
55 #include "BKE_pointcache.h"
56
57 #include "BLI_math.h"
58 #include "BLI_blenlib.h"
59 #include "BLI_dynstr.h"
60 #include "BLI_kdtree.h"
61 #include "BLI_rand.h"
62
63
64 #include "BIF_gl.h"
65 #include "BIF_glutil.h"
66
67 #include "ED_mesh.h"
68 #include "ED_particle.h"
69 #include "ED_view3d.h"
70
71 #include "UI_resources.h"
72
73 #include "WM_api.h"
74 #include "WM_types.h"
75
76 #include "RNA_access.h"
77 #include "RNA_define.h"
78
79 #include "physics_intern.h"
80
81 static void PE_create_particle_edit(Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys);
82 static void PTCacheUndo_clear(PTCacheEdit *edit);
83 static void recalc_emitter_field(Object *ob, ParticleSystem *psys);
84
85 #define KEY_K                                   PTCacheEditKey *key; int k
86 #define POINT_P                                 PTCacheEditPoint *point; int p
87 #define LOOP_POINTS                             for(p=0, point=edit->points; p<edit->totpoint; p++, point++)
88 #define LOOP_VISIBLE_POINTS             for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(!(point->flag & PEP_HIDE))
89 #define LOOP_SELECTED_POINTS    for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(point_is_selected(point))
90 #define LOOP_UNSELECTED_POINTS  for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(!point_is_selected(point))
91 #define LOOP_EDITED_POINTS              for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(point->flag & PEP_EDIT_RECALC)
92 #define LOOP_TAGGED_POINTS              for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(point->flag & PEP_TAG)
93 #define LOOP_KEYS                               for(k=0, key=point->keys; k<point->totkey; k++, key++)
94 #define LOOP_VISIBLE_KEYS               for(k=0, key=point->keys; k<point->totkey; k++, key++) if(!(key->flag & PEK_HIDE))
95 #define LOOP_SELECTED_KEYS              for(k=0, key=point->keys; k<point->totkey; k++, key++) if((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE))
96 #define LOOP_TAGGED_KEYS                for(k=0, key=point->keys; k<point->totkey; k++, key++) if(key->flag & PEK_TAG)
97
98 #define KEY_WCO                                 (key->flag & PEK_USE_WCO ? key->world_co : key->co)
99
100 /**************************** utilities *******************************/
101
102 int PE_poll(bContext *C)
103 {
104         Scene *scene= CTX_data_scene(C);
105         Object *ob= CTX_data_active_object(C);
106
107         if(!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT))
108                 return 0;
109         
110         return (PE_get_current(scene, ob) != NULL);
111 }
112
113 int PE_hair_poll(bContext *C)
114 {
115         Scene *scene= CTX_data_scene(C);
116         Object *ob= CTX_data_active_object(C);
117         PTCacheEdit *edit;
118
119         if(!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT))
120                 return 0;
121         
122         edit= PE_get_current(scene, ob);
123
124         return (edit && edit->psys);
125 }
126
127 int PE_poll_view3d(bContext *C)
128 {
129         return PE_poll(C) && CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
130                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
131 }
132
133 void PE_free_ptcache_edit(PTCacheEdit *edit)
134 {
135         POINT_P;
136
137         if(edit==0) return;
138
139         PTCacheUndo_clear(edit);
140
141         if(edit->points) {
142                 LOOP_POINTS {
143                         if(point->keys) 
144                                 MEM_freeN(point->keys);
145                 }
146
147                 MEM_freeN(edit->points);
148         }
149
150         if(edit->mirror_cache)
151                 MEM_freeN(edit->mirror_cache);
152
153         if(edit->emitter_cosnos) {
154                 MEM_freeN(edit->emitter_cosnos);
155                 edit->emitter_cosnos= 0;
156         }
157
158         if(edit->emitter_field) {
159                 BLI_kdtree_free(edit->emitter_field);
160                 edit->emitter_field= 0;
161         }
162
163         psys_free_path_cache(edit->psys, edit);
164
165         MEM_freeN(edit);
166 }
167
168 /************************************************/
169 /*                      Edit Mode Helpers                                       */
170 /************************************************/
171
172 int PE_start_edit(PTCacheEdit *edit)
173 {
174         if(edit) {
175                 edit->edited = 1;
176                 if(edit->psys)
177                         edit->psys->flag |= PSYS_EDITED;
178                 return 1;
179         }
180
181         return 0;
182 }
183
184 ParticleEditSettings *PE_settings(Scene *scene)
185 {
186         return scene->toolsettings ? &scene->toolsettings->particle : NULL;
187 }
188
189 /* always gets atleast the first particlesystem even if PSYS_CURRENT flag is not set
190  *
191  * note: this function runs on poll, therefor it can runs many times a second
192  * keep it fast! */
193 static PTCacheEdit *pe_get_current(Scene *scene, Object *ob, int create)
194 {
195         ParticleEditSettings *pset= PE_settings(scene);
196         PTCacheEdit *edit = NULL;
197         ListBase pidlist;
198         PTCacheID *pid;
199
200         if(pset==NULL || ob==NULL)
201                 return NULL;
202
203         pset->scene = scene;
204         pset->object = ob;
205
206         BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0);
207
208         /* in the case of only one editable thing, set pset->edittype accordingly */
209         if(pidlist.first && pidlist.first == pidlist.last) {
210                 pid = pidlist.first;
211                 switch(pid->type) {
212                         case PTCACHE_TYPE_PARTICLES:
213                                 pset->edittype = PE_TYPE_PARTICLES;
214                                 break;
215                         case PTCACHE_TYPE_SOFTBODY:
216                                 pset->edittype = PE_TYPE_SOFTBODY;
217                                 break;
218                         case PTCACHE_TYPE_CLOTH:
219                                 pset->edittype = PE_TYPE_CLOTH;
220                                 break;
221                 }
222         }
223
224         for(pid=pidlist.first; pid; pid=pid->next) {
225                 if(pset->edittype == PE_TYPE_PARTICLES && pid->type == PTCACHE_TYPE_PARTICLES) {
226                         ParticleSystem *psys = pid->calldata;
227
228                         if(psys->flag & PSYS_CURRENT) {
229                                 if(psys->part && psys->part->type == PART_HAIR) {
230                                         if(psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) {
231                                                 if(create && !psys->pointcache->edit)
232                                                         PE_create_particle_edit(scene, ob, pid->cache, NULL);
233                                                 edit = pid->cache->edit;
234                                         }
235                                         else {
236                                                 if(create && !psys->edit && psys->flag & PSYS_HAIR_DONE)
237                                                         PE_create_particle_edit(scene, ob, NULL, psys);
238                                                 edit = psys->edit;
239                                         }
240                                 }
241                                 else {
242                                         if(create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit)
243                                                 PE_create_particle_edit(scene, ob, pid->cache, psys);
244                                         edit = pid->cache->edit;
245                                 }
246
247                                 break;
248                         }
249                 }
250                 else if(pset->edittype == PE_TYPE_SOFTBODY && pid->type == PTCACHE_TYPE_SOFTBODY) {
251                         if(create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit)
252                                 PE_create_particle_edit(scene, ob, pid->cache, NULL);
253                         edit = pid->cache->edit;
254                         break;
255                 }
256                 else if(pset->edittype == PE_TYPE_CLOTH && pid->type == PTCACHE_TYPE_CLOTH) {
257                         if(create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit)
258                                 PE_create_particle_edit(scene, ob, pid->cache, NULL);
259                         edit = pid->cache->edit;
260                         break;
261                 }
262         }
263
264         if(edit)
265                 edit->pid = *pid;
266
267         BLI_freelistN(&pidlist);
268
269         return edit;
270 }
271
272 PTCacheEdit *PE_get_current(Scene *scene, Object *ob)
273 {
274         return pe_get_current(scene, ob, 0);
275 }
276
277 PTCacheEdit *PE_create_current(Scene *scene, Object *ob)
278 {
279         return pe_get_current(scene, ob, 1);
280 }
281
282 void PE_current_changed(Scene *scene, Object *ob)
283 {
284         if(ob->mode == OB_MODE_PARTICLE_EDIT)
285                 PE_create_current(scene, ob);
286 }
287
288 void PE_hide_keys_time(Scene *scene, PTCacheEdit *edit, float cfra)
289 {
290         ParticleEditSettings *pset=PE_settings(scene);
291         POINT_P; KEY_K;
292
293
294         if(pset->flag & PE_FADE_TIME && pset->selectmode==SCE_SELECT_POINT) {
295                 LOOP_POINTS {
296                         LOOP_KEYS {
297                                 if(fabs(cfra-*key->time) < pset->fade_frames)
298                                         key->flag &= ~PEK_HIDE;
299                                 else {
300                                         key->flag |= PEK_HIDE;
301                                         //key->flag &= ~PEK_SELECT;
302                                 }
303                         }
304                 }
305         }
306         else {
307                 LOOP_POINTS {
308                         LOOP_KEYS {
309                                 key->flag &= ~PEK_HIDE;
310                         }
311                 }
312         }
313 }
314
315 static int pe_x_mirror(Object *ob)
316 {
317         if(ob->type == OB_MESH)
318                 return (((Mesh*)ob->data)->editflag & ME_EDIT_MIRROR_X);
319         
320         return 0;
321 }
322
323 /****************** common struct passed to callbacks ******************/
324
325 typedef struct PEData {
326         ViewContext vc;
327         bglMats mats;
328         
329         Scene *scene;
330         Object *ob;
331         DerivedMesh *dm;
332         PTCacheEdit *edit;
333
334         short *mval;
335         rcti *rect;
336         float rad;
337         float dist;
338         float dval;
339         int select;
340
341         float *dvec;
342         float combfac;
343         float pufffac;
344         float cutfac;
345         float smoothfac;
346         float weightfac;
347         float growfac;
348         int totrekey;
349
350         int invert;
351         int tot;
352         float vec[3];
353 } PEData;
354
355 static void PE_set_data(bContext *C, PEData *data)
356 {
357         memset(data, 0, sizeof(*data));
358
359         data->scene= CTX_data_scene(C);
360         data->ob= CTX_data_active_object(C);
361         data->edit= PE_get_current(data->scene, data->ob);
362 }
363
364 static void PE_set_view3d_data(bContext *C, PEData *data)
365 {
366         PE_set_data(C, data);
367
368         view3d_set_viewcontext(C, &data->vc);
369         /* note, the object argument means the modelview matrix does not account for the objects matrix, use viewmat rather then (obmat * viewmat) */
370         view3d_get_transformation(data->vc.ar, data->vc.rv3d, NULL, &data->mats);
371
372         if((data->vc.v3d->drawtype>OB_WIRE) && (data->vc.v3d->flag & V3D_ZBUF_SELECT))
373                 view3d_validate_backbuf(&data->vc);
374 }
375
376 /*************************** selection utilities *******************************/
377
378 static int key_test_depth(PEData *data, float co[3])
379 {
380         View3D *v3d= data->vc.v3d;
381         double ux, uy, uz;
382         float depth;
383         short wco[3], x,y;
384
385         /* nothing to do */
386         if((v3d->drawtype<=OB_WIRE) || (v3d->flag & V3D_ZBUF_SELECT)==0)
387                 return 1;
388
389         project_short(data->vc.ar, co, wco);
390         
391         if(wco[0] == IS_CLIPPED)
392                 return 0;
393
394         gluProject(co[0],co[1],co[2], data->mats.modelview, data->mats.projection,
395                 (GLint *)data->mats.viewport, &ux, &uy, &uz);
396
397         x=wco[0];
398         y=wco[1];
399
400         x+= (short)data->vc.ar->winrct.xmin;
401         y+= (short)data->vc.ar->winrct.ymin;
402
403         /* PE_set_view3d_data calls this. no need to call here */
404         /* view3d_validate_backbuf(&data->vc); */
405         glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
406
407         if((float)uz - 0.0001 > depth)
408                 return 0;
409         else
410                 return 1;
411 }
412
413 static int key_inside_circle(PEData *data, float rad, float co[3], float *distance)
414 {
415         float dx, dy, dist;
416         short sco[2];
417
418         project_short(data->vc.ar, co, sco);
419         
420         if(sco[0] == IS_CLIPPED)
421                 return 0;
422         
423         dx= data->mval[0] - sco[0];
424         dy= data->mval[1] - sco[1];
425         dist= sqrt(dx*dx + dy*dy);
426
427         if(dist > rad)
428                 return 0;
429
430         if(key_test_depth(data, co)) {
431                 if(distance)
432                         *distance=dist;
433
434                 return 1;
435         }
436         
437         return 0;
438 }
439
440 static int key_inside_rect(PEData *data, float co[3])
441 {
442         short sco[2];
443
444         project_short(data->vc.ar, co,sco);
445
446         if(sco[0] == IS_CLIPPED)
447                 return 0;
448         
449         if(sco[0] > data->rect->xmin && sco[0] < data->rect->xmax &&
450            sco[1] > data->rect->ymin && sco[1] < data->rect->ymax)
451                 return key_test_depth(data, co);
452
453         return 0;
454 }
455
456 static int key_inside_test(PEData *data, float co[3])
457 {
458         if(data->mval)
459                 return key_inside_circle(data, data->rad, co, NULL);
460         else
461                 return key_inside_rect(data, co);
462 }
463
464 static int point_is_selected(PTCacheEditPoint *point)
465 {
466         KEY_K;
467         int sel;
468
469         if(point->flag & PEP_HIDE)
470                 return 0;
471
472         sel= 0;
473
474         LOOP_SELECTED_KEYS {
475                 return 1;
476         }
477         
478         return 0;
479 }
480
481 /*************************** iterators *******************************/
482
483 typedef void (*ForPointFunc)(PEData *data, int point_index);
484 typedef void (*ForKeyFunc)(PEData *data, int point_index, int key_index);
485 typedef void (*ForKeyMatFunc)(PEData *data, float mat[][4], float imat[][4], int point_index, int key_index, PTCacheEditKey *key);
486
487 static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, int nearest)
488 {
489         ParticleEditSettings *pset= PE_settings(data->scene);
490         PTCacheEdit *edit= data->edit;
491         POINT_P; KEY_K;
492         int nearest_point, nearest_key;
493         float dist= data->rad;
494
495         /* in path select mode we have no keys */
496         if(pset->selectmode==SCE_SELECT_PATH)
497                 return;
498
499         nearest_point= -1;
500         nearest_key= -1;
501
502         LOOP_VISIBLE_POINTS {
503                 if(pset->selectmode == SCE_SELECT_END) {
504                         /* only do end keys */
505                         key= point->keys + point->totkey-1;
506
507                         if(nearest) {
508                                 if(key_inside_circle(data, dist, KEY_WCO, &dist)) {
509                                         nearest_point= p;
510                                         nearest_key= point->totkey-1;
511                                 }
512                         }
513                         else if(key_inside_test(data, KEY_WCO))
514                                 func(data, p, point->totkey-1);
515                 }
516                 else {
517                         /* do all keys */
518                         LOOP_VISIBLE_KEYS {
519                                 if(nearest) {
520                                         if(key_inside_circle(data, dist, KEY_WCO, &dist)) {
521                                                 nearest_point= p;
522                                                 nearest_key= k;
523                                         }
524                                 }
525                                 else if(key_inside_test(data, KEY_WCO))
526                                         func(data, p, k);
527                         }
528                 }
529         }
530
531         /* do nearest only */
532         if(nearest && nearest_point > -1)
533                 func(data, nearest_point, nearest_key);
534 }
535
536 static void foreach_mouse_hit_point(PEData *data, ForPointFunc func, int selected)
537 {
538         ParticleEditSettings *pset= PE_settings(data->scene);
539         PTCacheEdit *edit= data->edit;
540         POINT_P; KEY_K;
541
542         /* all is selected in path mode */
543         if(pset->selectmode==SCE_SELECT_PATH)
544                 selected=0;
545
546         LOOP_VISIBLE_POINTS {
547                 if(pset->selectmode==SCE_SELECT_END) {
548                         /* only do end keys */
549                         key= point->keys + point->totkey - 1;
550
551                         if(selected==0 || key->flag & PEK_SELECT)
552                                 if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist))
553                                         func(data, p);
554                 }
555                 else {
556                         /* do all keys */
557                         LOOP_VISIBLE_KEYS {
558                                 if(selected==0 || key->flag & PEK_SELECT) {
559                                         if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
560                                                 func(data, p);
561                                                 break;
562                                         }
563                                 }
564                         }
565                 }
566         }
567 }
568
569 static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected)
570 {
571         PTCacheEdit *edit = data->edit;
572         ParticleSystem *psys = edit->psys;
573         ParticleSystemModifierData *psmd = NULL;
574         ParticleEditSettings *pset= PE_settings(data->scene);
575         POINT_P; KEY_K;
576         float mat[4][4], imat[4][4];
577
578         if(edit->psys)
579                 psmd= psys_get_modifier(data->ob, edit->psys);
580
581         /* all is selected in path mode */
582         if(pset->selectmode==SCE_SELECT_PATH)
583                 selected= 0;
584
585         unit_m4(imat);
586         unit_m4(mat);
587
588         LOOP_VISIBLE_POINTS {
589                 if(pset->selectmode==SCE_SELECT_END) {
590                         /* only do end keys */
591                         key= point->keys + point->totkey-1;
592
593                         if(selected==0 || key->flag & PEK_SELECT) {
594                                 if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
595                                         if(edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) {
596                                                 psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, psys->particles + p, mat);
597                                                 invert_m4_m4(imat,mat);
598                                         }
599
600                                         func(data, mat, imat, p, point->totkey-1, key);
601                                 }
602                         }
603                 }
604                 else {
605                         /* do all keys */
606                         LOOP_VISIBLE_KEYS {
607                                 if(selected==0 || key->flag & PEK_SELECT) {
608                                         if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
609                                                 if(edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) {
610                                                         psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, psys->particles + p, mat);
611                                                         invert_m4_m4(imat,mat);
612                                                 }
613
614                                                 func(data, mat, imat, p, k, key);
615                                         }
616                                 }
617                         }
618                 }
619         }
620 }
621
622 static void foreach_selected_point(PEData *data, ForPointFunc func)
623 {
624         PTCacheEdit *edit = data->edit;
625         POINT_P;
626
627         LOOP_SELECTED_POINTS {
628                 func(data, p);
629         }
630 }
631
632 static void foreach_selected_key(PEData *data, ForKeyFunc func)
633 {
634         PTCacheEdit *edit = data->edit;
635         POINT_P; KEY_K;
636
637         LOOP_VISIBLE_POINTS {
638                 LOOP_SELECTED_KEYS {
639                         func(data, p, k);
640                 }
641         }
642 }
643
644 static void foreach_point(PEData *data, ForPointFunc func)
645 {
646         PTCacheEdit *edit = data->edit;
647         POINT_P;
648
649         LOOP_POINTS { 
650                 func(data, p);
651         }
652 }
653
654 static int count_selected_keys(Scene *scene, PTCacheEdit *edit)
655 {
656         ParticleEditSettings *pset= PE_settings(scene);
657         POINT_P; KEY_K;
658         int sel= 0;
659
660         LOOP_VISIBLE_POINTS {
661                 if(pset->selectmode==SCE_SELECT_POINT) {
662                         LOOP_SELECTED_KEYS {
663                                 sel++;
664                         }
665                 }
666                 else if(pset->selectmode==SCE_SELECT_END) {
667                         key = point->keys + point->totkey - 1;
668                         if(key->flag & PEK_SELECT)
669                                 sel++;
670                 }
671         }
672
673         return sel;
674 }
675
676 /************************************************/
677 /*                      Particle Edit Mirroring                         */
678 /************************************************/
679
680 static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys)
681 {
682         PTCacheEdit *edit;
683         ParticleSystemModifierData *psmd;
684         KDTree *tree;
685         KDTreeNearest nearest;
686         HairKey *key;
687         PARTICLE_P;
688         float mat[4][4], co[3];
689         int index, totpart;
690
691         edit= psys->edit;
692         psmd= psys_get_modifier(ob, psys);
693         totpart= psys->totpart;
694
695         if(!psmd->dm)
696                 return;
697
698         tree= BLI_kdtree_new(totpart);
699
700         /* insert particles into kd tree */
701         LOOP_PARTICLES {
702                 key = pa->hair;
703                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
704                 VECCOPY(co, key->co);
705                 mul_m4_v3(mat, co);
706                 BLI_kdtree_insert(tree, p, co, NULL);
707         }
708
709         BLI_kdtree_balance(tree);
710
711         /* lookup particles and set in mirror cache */
712         if(!edit->mirror_cache)
713                 edit->mirror_cache= MEM_callocN(sizeof(int)*totpart, "PE mirror cache");
714         
715         LOOP_PARTICLES {
716                 key = pa->hair;
717                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
718                 VECCOPY(co, key->co);
719                 mul_m4_v3(mat, co);
720                 co[0]= -co[0];
721
722                 index= BLI_kdtree_find_nearest(tree, co, NULL, &nearest);
723
724                 /* this needs a custom threshold still, duplicated for editmode mirror */
725                 if(index != -1 && index != p && (nearest.dist <= 0.0002f))
726                         edit->mirror_cache[p]= index;
727                 else
728                         edit->mirror_cache[p]= -1;
729         }
730
731         /* make sure mirrors are in two directions */
732         LOOP_PARTICLES {
733                 if(edit->mirror_cache[p]) {
734                         index= edit->mirror_cache[p];
735                         if(edit->mirror_cache[index] != p)
736                                 edit->mirror_cache[p]= -1;
737                 }
738         }
739
740         BLI_kdtree_free(tree);
741 }
742
743 static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys, ParticleData *pa, ParticleData *mpa)
744 {
745         HairKey *hkey, *mhkey;
746         PTCacheEditPoint *point, *mpoint;
747         PTCacheEditKey *key, *mkey;
748         PTCacheEdit *edit;
749         float mat[4][4], mmat[4][4], immat[4][4];
750         int i, mi, k;
751
752         edit= psys->edit;
753         i= pa - psys->particles;
754
755         /* find mirrored particle if needed */
756         if(!mpa) {
757                 if(!edit->mirror_cache)
758                         PE_update_mirror_cache(ob, psys);
759
760                 mi= edit->mirror_cache[i];
761                 if(mi == -1)
762                         return;
763                 mpa= psys->particles + mi;
764         }
765         else
766                 mi= mpa - psys->particles;
767
768         point = edit->points + i;
769         mpoint = edit->points + mi;
770
771         /* make sure they have the same amount of keys */
772         if(pa->totkey != mpa->totkey) {
773                 if(mpa->hair) MEM_freeN(mpa->hair);
774                 if(mpoint->keys) MEM_freeN(mpoint->keys);
775
776                 mpa->hair= MEM_dupallocN(pa->hair);
777                 mpa->totkey= pa->totkey;
778                 mpoint->keys= MEM_dupallocN(point->keys);
779                 mpoint->totkey= point->totkey;
780
781                 mhkey= mpa->hair;
782                 mkey= mpoint->keys;
783                 for(k=0; k<mpa->totkey; k++, mkey++, mhkey++) {
784                         mkey->co= mhkey->co;
785                         mkey->time= &mhkey->time;
786                         mkey->flag &= ~PEK_SELECT;
787                 }
788         }
789
790         /* mirror positions and tags */
791         psys_mat_hair_to_orco(ob, dm, psys->part->from, pa, mat);
792         psys_mat_hair_to_orco(ob, dm, psys->part->from, mpa, mmat);
793         invert_m4_m4(immat, mmat);
794
795         hkey=pa->hair;
796         mhkey=mpa->hair;
797         key= point->keys;
798         mkey= mpoint->keys;
799         for(k=0; k<pa->totkey; k++, hkey++, mhkey++, key++, mkey++) {
800                 VECCOPY(mhkey->co, hkey->co);
801                 mul_m4_v3(mat, mhkey->co);
802                 mhkey->co[0]= -mhkey->co[0];
803                 mul_m4_v3(immat, mhkey->co);
804
805                 if(key->flag & PEK_TAG)
806                         mkey->flag |= PEK_TAG;
807         }
808
809         if(point->flag & PEP_TAG)
810                 mpoint->flag |= PEP_TAG;
811         if(point->flag & PEP_EDIT_RECALC)
812                 mpoint->flag |= PEP_EDIT_RECALC;
813 }
814
815 static void PE_apply_mirror(Object *ob, ParticleSystem *psys)
816 {
817         PTCacheEdit *edit;
818         ParticleSystemModifierData *psmd;
819         POINT_P;
820
821         if(!psys)
822                 return;
823
824         edit= psys->edit;
825         psmd= psys_get_modifier(ob, psys);
826
827         if(!psmd->dm)
828                 return;
829
830         if(!edit->mirror_cache)
831                 PE_update_mirror_cache(ob, psys);
832
833         /* we delay settings the PARS_EDIT_RECALC for mirrored particles
834          * to avoid doing mirror twice */
835         LOOP_POINTS {
836                 if(point->flag & PEP_EDIT_RECALC) {
837                         PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
838
839                         if(edit->mirror_cache[p] != -1)
840                                 edit->points[edit->mirror_cache[p]].flag &= ~PEP_EDIT_RECALC;
841                 }
842         }
843
844         LOOP_POINTS {
845                 if(point->flag & PEP_EDIT_RECALC)
846                         if(edit->mirror_cache[p] != -1)
847                                 edit->points[edit->mirror_cache[p]].flag |= PEP_EDIT_RECALC;
848         }
849 }
850
851 /************************************************/
852 /*                      Edit Calculation                                        */
853 /************************************************/
854 /* tries to stop edited particles from going through the emitter's surface */
855 static void pe_deflect_emitter(Scene *scene, Object *ob, PTCacheEdit *edit)
856 {
857         ParticleEditSettings *pset= PE_settings(scene);
858         ParticleSystem *psys;
859         ParticleSystemModifierData *psmd;
860         POINT_P; KEY_K;
861         int index;
862         float *vec, *nor, dvec[3], dot, dist_1st=0.0f;
863         float hairimat[4][4], hairmat[4][4];
864
865         if(edit==NULL || edit->psys==NULL || (pset->flag & PE_DEFLECT_EMITTER)==0 || (edit->psys->flag & PSYS_GLOBAL_HAIR))
866                 return;
867
868         psys = edit->psys;
869         psmd = psys_get_modifier(ob,psys);
870
871         if(!psmd->dm)
872                 return;
873
874         LOOP_EDITED_POINTS {
875                 psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles + p, hairmat);
876         
877                 LOOP_KEYS {
878                         mul_m4_v3(hairmat, key->co);
879                 }
880
881                 LOOP_KEYS {
882                         if(k==0) {
883                                 dist_1st = len_v3v3((key+1)->co, key->co);
884                                 dist_1st *= 0.75f * pset->emitterdist;
885                         }
886                         else {
887                                 index= BLI_kdtree_find_nearest(edit->emitter_field,key->co,NULL,NULL);
888                                 
889                                 vec=edit->emitter_cosnos +index*6;
890                                 nor=vec+3;
891
892                                 sub_v3_v3v3(dvec, key->co, vec);
893
894                                 dot=dot_v3v3(dvec,nor);
895                                 VECCOPY(dvec,nor);
896
897                                 if(dot>0.0f) {
898                                         if(dot<dist_1st) {
899                                                 normalize_v3(dvec);
900                                                 mul_v3_fl(dvec,dist_1st-dot);
901                                                 add_v3_v3(key->co, dvec);
902                                         }
903                                 }
904                                 else {
905                                         normalize_v3(dvec);
906                                         mul_v3_fl(dvec,dist_1st-dot);
907                                         add_v3_v3(key->co, dvec);
908                                 }
909                                 if(k==1)
910                                         dist_1st*=1.3333f;
911                         }
912                 }
913                 
914                 invert_m4_m4(hairimat,hairmat);
915
916                 LOOP_KEYS {
917                         mul_m4_v3(hairimat, key->co);
918                 }
919         }
920 }
921 /* force set distances between neighbouring keys */
922 void PE_apply_lengths(Scene *scene, PTCacheEdit *edit)
923 {
924         
925         ParticleEditSettings *pset=PE_settings(scene);
926         POINT_P; KEY_K;
927         float dv1[3];
928
929         if(edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0)
930                 return;
931
932         if(edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR)
933                 return;
934
935         LOOP_EDITED_POINTS {
936                 LOOP_KEYS {
937                         if(k) {
938                                 sub_v3_v3v3(dv1, key->co, (key - 1)->co);
939                                 normalize_v3(dv1);
940                                 mul_v3_fl(dv1, (key - 1)->length);
941                                 add_v3_v3v3(key->co, (key - 1)->co, dv1);
942                         }
943                 }
944         }
945 }
946 /* try to find a nice solution to keep distances between neighbouring keys */
947 static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit)
948 {
949         ParticleEditSettings *pset=PE_settings(scene);
950         POINT_P;
951         PTCacheEditKey *key;
952         int j, k;
953         float tlen;
954         float dv0[3]= {0.0f, 0.0f, 0.0f};
955         float dv1[3]= {0.0f, 0.0f, 0.0f};
956         float dv2[3]= {0.0f, 0.0f, 0.0f};
957
958         if(edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0)
959                 return;
960
961         if(edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR)
962                 return;
963
964         LOOP_EDITED_POINTS {
965                 for(j=1; j<point->totkey; j++) {
966                         float mul= 1.0f / (float)point->totkey;
967
968                         if(pset->flag & PE_LOCK_FIRST) {
969                                 key= point->keys + 1;
970                                 k= 1;
971                                 dv1[0]= dv1[1]= dv1[2]= 0.0;
972                         }
973                         else {
974                                 key= point->keys;
975                                 k= 0;
976                                 dv0[0]= dv0[1]= dv0[2]= 0.0;
977                         }
978
979                         for(; k<point->totkey; k++, key++) {
980                                 if(k) {
981                                         sub_v3_v3v3(dv0, (key - 1)->co, key->co);
982                                         tlen= normalize_v3(dv0);
983                                         mul_v3_fl(dv0, (mul * (tlen - (key - 1)->length)));
984                                 }
985
986                                 if(k < point->totkey - 1) {
987                                         sub_v3_v3v3(dv2, (key + 1)->co, key->co);
988                                         tlen= normalize_v3(dv2);
989                                         mul_v3_fl(dv2, mul * (tlen - key->length));
990                                 }
991
992                                 if(k) {
993                                         add_v3_v3((key-1)->co, dv1);
994                                 }
995
996                                 VECADD(dv1,dv0,dv2);
997                         }
998                 }
999         }
1000 }
1001 /* set current distances to be kept between neighbouting keys */
1002 static void recalc_lengths(PTCacheEdit *edit)
1003 {
1004         POINT_P; KEY_K;
1005
1006         if(edit==0)
1007                 return;
1008
1009         LOOP_EDITED_POINTS {
1010                 key= point->keys;
1011                 for(k=0; k<point->totkey-1; k++, key++) {
1012                         key->length= len_v3v3(key->co, (key + 1)->co);
1013                 }
1014         }
1015 }
1016
1017 /* calculate a tree for finding nearest emitter's vertice */
1018 static void recalc_emitter_field(Object *ob, ParticleSystem *psys)
1019 {
1020         DerivedMesh *dm=psys_get_modifier(ob,psys)->dm;
1021         PTCacheEdit *edit= psys->edit;
1022         MFace *mface;
1023         MVert *mvert;
1024         float *vec, *nor;
1025         int i, totface, totvert;
1026
1027         if(!dm)
1028                 return;
1029
1030         if(edit->emitter_cosnos)
1031                 MEM_freeN(edit->emitter_cosnos);
1032
1033         BLI_kdtree_free(edit->emitter_field);
1034
1035         totface=dm->getNumFaces(dm);
1036         totvert=dm->getNumVerts(dm);
1037
1038         edit->emitter_cosnos=MEM_callocN(totface*6*sizeof(float),"emitter cosnos");
1039
1040         edit->emitter_field= BLI_kdtree_new(totface);
1041
1042         vec=edit->emitter_cosnos;
1043         nor=vec+3;
1044
1045         mvert=dm->getVertDataArray(dm,CD_MVERT);
1046         for(i=0; i<totface; i++, vec+=6, nor+=6) {
1047                 mface=dm->getFaceData(dm,i,CD_MFACE);
1048
1049                 mvert=dm->getVertData(dm,mface->v1,CD_MVERT);
1050                 VECCOPY(vec,mvert->co);
1051                 VECCOPY(nor,mvert->no);
1052
1053                 mvert=dm->getVertData(dm,mface->v2,CD_MVERT);
1054                 VECADD(vec,vec,mvert->co);
1055                 VECADD(nor,nor,mvert->no);
1056
1057                 mvert=dm->getVertData(dm,mface->v3,CD_MVERT);
1058                 VECADD(vec,vec,mvert->co);
1059                 VECADD(nor,nor,mvert->no);
1060
1061                 if(mface->v4) {
1062                         mvert=dm->getVertData(dm,mface->v4,CD_MVERT);
1063                         VECADD(vec,vec,mvert->co);
1064                         VECADD(nor,nor,mvert->no);
1065                         
1066                         mul_v3_fl(vec,0.25);
1067                 }
1068                 else
1069                         mul_v3_fl(vec,0.3333f);
1070
1071                 normalize_v3(nor);
1072
1073                 BLI_kdtree_insert(edit->emitter_field, i, vec, NULL);
1074         }
1075
1076         BLI_kdtree_balance(edit->emitter_field);
1077 }
1078
1079 static void PE_update_selection(Scene *scene, Object *ob, int useflag)
1080 {
1081         PTCacheEdit *edit= PE_get_current(scene, ob);
1082         HairKey *hkey;
1083         POINT_P; KEY_K;
1084
1085         /* flag all particles to be updated if not using flag */
1086         if(!useflag)
1087                 LOOP_POINTS
1088                         point->flag |= PEP_EDIT_RECALC;
1089
1090         /* flush edit key flag to hair key flag to preserve selection 
1091          * on save */
1092         if(edit->psys) LOOP_POINTS {
1093                 hkey = edit->psys->particles[p].hair;
1094                 LOOP_KEYS {
1095                         hkey->editflag= key->flag;
1096                         hkey++;
1097                 }
1098         }
1099
1100         psys_cache_edit_paths(scene, ob, edit, CFRA);
1101
1102
1103         /* disable update flag */
1104         LOOP_POINTS
1105                 point->flag &= ~PEP_EDIT_RECALC;
1106 }
1107
1108 static void update_world_cos(Object *ob, PTCacheEdit *edit)
1109 {
1110         ParticleSystem *psys = edit->psys;
1111         ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
1112         POINT_P; KEY_K;
1113         float hairmat[4][4];
1114
1115         if(psys==0 || psys->edit==0 || psmd->dm==NULL)
1116                 return;
1117
1118         LOOP_POINTS {
1119                 if(!(psys->flag & PSYS_GLOBAL_HAIR))
1120                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles+p, hairmat);
1121
1122                 LOOP_KEYS {
1123                         VECCOPY(key->world_co,key->co);
1124                         if(!(psys->flag & PSYS_GLOBAL_HAIR))
1125                                 mul_m4_v3(hairmat, key->world_co);
1126                 }
1127         }
1128 }
1129 static void update_velocities(PTCacheEdit *edit)
1130 {
1131         /*TODO: get frs_sec properly */
1132         float vec1[3], vec2[3], frs_sec, dfra;
1133         POINT_P; KEY_K;
1134
1135         /* hair doesn't use velocities */
1136         if(edit->psys || !edit->points || !edit->points->keys->vel)
1137                 return;
1138
1139         frs_sec = edit->pid.flag & PTCACHE_VEL_PER_SEC ? 25.0f : 1.0f;
1140
1141         LOOP_EDITED_POINTS {
1142                 LOOP_KEYS {
1143                         if(k==0) {
1144                                 dfra = *(key+1)->time - *key->time;
1145
1146                                 if(dfra <= 0.0f)
1147                                         continue;
1148
1149                                 VECSUB(key->vel, (key+1)->co, key->co);
1150
1151                                 if(point->totkey>2) {
1152                                         VECSUB(vec1, (key+1)->co, (key+2)->co);
1153                                         project_v3_v3v3(vec2, vec1, key->vel);
1154                                         VECSUB(vec2, vec1, vec2);
1155                                         VECADDFAC(key->vel, key->vel, vec2, 0.5f);
1156                                 }
1157                         }
1158                         else if(k==point->totkey-1) {
1159                                 dfra = *key->time - *(key-1)->time;
1160
1161                                 if(dfra <= 0.0f)
1162                                         continue;
1163
1164                                 VECSUB(key->vel, key->co, (key-1)->co);
1165
1166                                 if(point->totkey>2) {
1167                                         VECSUB(vec1, (key-2)->co, (key-1)->co);
1168                                         project_v3_v3v3(vec2, vec1, key->vel);
1169                                         VECSUB(vec2, vec1, vec2);
1170                                         VECADDFAC(key->vel, key->vel, vec2, 0.5f);
1171                                 }
1172                         }
1173                         else {
1174                                 dfra = *(key+1)->time - *(key-1)->time;
1175                                 
1176                                 if(dfra <= 0.0f)
1177                                         continue;
1178
1179                                 VECSUB(key->vel, (key+1)->co, (key-1)->co);
1180                         }
1181                         mul_v3_fl(key->vel, frs_sec/dfra);
1182                 }
1183         }
1184 }
1185
1186 void PE_update_object(Scene *scene, Object *ob, int useflag)
1187 {
1188         /* use this to do partial particle updates, not usable when adding or
1189            removing, then a full redo is necessary and calling this may crash */
1190         ParticleEditSettings *pset= PE_settings(scene);
1191         PTCacheEdit *edit = PE_get_current(scene, ob);
1192         POINT_P;
1193
1194         if(!edit)
1195                 return;
1196
1197         /* flag all particles to be updated if not using flag */
1198         if(!useflag)
1199                 LOOP_POINTS {
1200                         point->flag |= PEP_EDIT_RECALC;
1201                 }
1202
1203         /* do post process on particle edit keys */
1204         pe_iterate_lengths(scene, edit);
1205         pe_deflect_emitter(scene, ob, edit);
1206         PE_apply_lengths(scene, edit);
1207         if(pe_x_mirror(ob))
1208                 PE_apply_mirror(ob,edit->psys);
1209         if(edit->psys)
1210                 update_world_cos(ob, edit);
1211         if(pset->flag & PE_AUTO_VELOCITY)
1212                 update_velocities(edit);
1213         PE_hide_keys_time(scene, edit, CFRA);
1214
1215         /* regenerate path caches */
1216         psys_cache_edit_paths(scene, ob, edit, CFRA);
1217
1218         /* disable update flag */
1219         LOOP_POINTS {
1220                 point->flag &= ~PEP_EDIT_RECALC;
1221         }
1222
1223         if(edit->psys)
1224                 edit->psys->flag &= ~PSYS_HAIR_UPDATED;
1225 }
1226
1227 /************************************************/
1228 /*                      Edit Selections                                         */
1229 /************************************************/
1230
1231 /*-----selection callbacks-----*/
1232
1233 static void select_key(PEData *data, int point_index, int key_index)
1234 {
1235         PTCacheEdit *edit = data->edit;
1236         PTCacheEditPoint *point = edit->points + point_index;
1237         PTCacheEditKey *key = point->keys + key_index;
1238
1239         if(data->select)
1240                 key->flag |= PEK_SELECT;
1241         else
1242                 key->flag &= ~PEK_SELECT;
1243
1244         point->flag |= PEP_EDIT_RECALC;
1245 }
1246
1247 static void select_keys(PEData *data, int point_index, int UNUSED(key_index))
1248 {
1249         PTCacheEdit *edit = data->edit;
1250         PTCacheEditPoint *point = edit->points + point_index;
1251         KEY_K;
1252
1253         LOOP_KEYS {
1254                 if(data->select)
1255                         key->flag |= PEK_SELECT;
1256                 else
1257                         key->flag &= ~PEK_SELECT;
1258         }
1259
1260         point->flag |= PEP_EDIT_RECALC;
1261 }
1262
1263 static void toggle_key_select(PEData *data, int point_index, int key_index)
1264 {
1265         PTCacheEdit *edit = data->edit;
1266         PTCacheEditPoint *point = edit->points + point_index;
1267         PTCacheEditKey *key = point->keys + key_index;
1268
1269         key->flag ^= PEK_SELECT;
1270         point->flag |= PEP_EDIT_RECALC;
1271 }
1272
1273 /************************ de select all operator ************************/
1274
1275 static int select_all_exec(bContext *C, wmOperator *op)
1276 {
1277         Scene *scene= CTX_data_scene(C);
1278         Object *ob= CTX_data_active_object(C);
1279         PTCacheEdit *edit= PE_get_current(scene, ob);
1280         POINT_P; KEY_K;
1281         int action = RNA_enum_get(op->ptr, "action");
1282
1283         if (action == SEL_TOGGLE) {
1284                 action = SEL_SELECT;
1285                 LOOP_VISIBLE_POINTS {
1286                         LOOP_SELECTED_KEYS {
1287                                 action = SEL_DESELECT;
1288                                 break;
1289                         }
1290
1291                         if (action == SEL_DESELECT)
1292                                 break;
1293                 }
1294         }
1295
1296         LOOP_VISIBLE_POINTS {
1297                 LOOP_VISIBLE_KEYS {
1298                         switch (action) {
1299                         case SEL_SELECT:
1300                                 if ((key->flag & PEK_SELECT) == 0) {
1301                                         key->flag |= PEK_SELECT;
1302                                         point->flag |= PEP_EDIT_RECALC;
1303                                 }
1304                                 break;
1305                         case SEL_DESELECT:
1306                                 if (key->flag & PEK_SELECT) {
1307                                         key->flag &= ~PEK_SELECT;
1308                                         point->flag |= PEP_EDIT_RECALC;
1309                                 }
1310                                 break;
1311                         case SEL_INVERT:
1312                                 if ((key->flag & PEK_SELECT) == 0) {
1313                                         key->flag |= PEK_SELECT;
1314                                         point->flag |= PEP_EDIT_RECALC;
1315                                 } else {
1316                                         key->flag &= ~PEK_SELECT;
1317                                         point->flag |= PEP_EDIT_RECALC;
1318                                 }
1319                                 break;
1320                         }
1321                 }
1322         }
1323
1324         PE_update_selection(scene, ob, 1);
1325         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1326
1327         return OPERATOR_FINISHED;
1328 }
1329
1330 void PARTICLE_OT_select_all(wmOperatorType *ot)
1331 {
1332         /* identifiers */
1333         ot->name= "Selection of all particles";
1334         ot->idname= "PARTICLE_OT_select_all";
1335         
1336         /* api callbacks */
1337         ot->exec= select_all_exec;
1338         ot->poll= PE_poll;
1339
1340         /* flags */
1341         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1342
1343         WM_operator_properties_select_all(ot);
1344 }
1345
1346 /************************ pick select operator ************************/
1347
1348 int PE_mouse_particles(bContext *C, short *mval, int extend)
1349 {
1350         PEData data;
1351         Scene *scene= CTX_data_scene(C);
1352         Object *ob= CTX_data_active_object(C);
1353         PTCacheEdit *edit= PE_get_current(scene, ob);
1354         POINT_P; KEY_K;
1355         
1356         if(!PE_start_edit(edit))
1357                 return OPERATOR_CANCELLED;
1358
1359         if(!extend) {
1360                 LOOP_VISIBLE_POINTS {
1361                         LOOP_SELECTED_KEYS {
1362                                 key->flag &= ~PEK_SELECT;
1363                                 point->flag |= PEP_EDIT_RECALC;
1364                         }
1365                 }
1366         }
1367
1368         PE_set_view3d_data(C, &data);
1369         data.mval= mval;
1370         data.rad= 75.0f;
1371
1372         for_mouse_hit_keys(&data, toggle_key_select, 1);  /* nearest only */
1373
1374         PE_update_selection(scene, ob, 1);
1375         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1376
1377         return OPERATOR_FINISHED;
1378 }
1379
1380 /************************ select first operator ************************/
1381
1382 static void select_root(PEData *data, int point_index)
1383 {
1384         if (data->edit->points[point_index].flag & PEP_HIDE)
1385                 return;
1386         
1387         data->edit->points[point_index].keys->flag |= PEK_SELECT;
1388         data->edit->points[point_index].flag |= PEP_EDIT_RECALC; /* redraw selection only */
1389 }
1390
1391 static int select_roots_exec(bContext *C, wmOperator *UNUSED(op))
1392 {
1393         PEData data;
1394
1395         PE_set_data(C, &data);
1396         foreach_point(&data, select_root);
1397
1398         PE_update_selection(data.scene, data.ob, 1);
1399         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1400
1401         return OPERATOR_FINISHED;
1402 }
1403
1404 void PARTICLE_OT_select_roots(wmOperatorType *ot)
1405 {
1406         /* identifiers */
1407         ot->name= "Select Roots";
1408         ot->idname= "PARTICLE_OT_select_roots";
1409         
1410         /* api callbacks */
1411         ot->exec= select_roots_exec;
1412         ot->poll= PE_poll;
1413
1414         /* flags */
1415         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1416 }
1417
1418 /************************ select last operator ************************/
1419
1420 static void select_tip(PEData *data, int point_index)
1421 {
1422         PTCacheEditPoint *point = data->edit->points + point_index;
1423         
1424         if (point->flag & PEP_HIDE)
1425                 return;
1426         
1427         point->keys[point->totkey - 1].flag |= PEK_SELECT;
1428         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1429 }
1430
1431 static int select_tips_exec(bContext *C, wmOperator *UNUSED(op))
1432 {
1433         PEData data;
1434
1435         PE_set_data(C, &data);
1436         foreach_point(&data, select_tip);
1437
1438         PE_update_selection(data.scene, data.ob, 1);
1439         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1440
1441         return OPERATOR_FINISHED;
1442 }
1443
1444 void PARTICLE_OT_select_tips(wmOperatorType *ot)
1445 {
1446         /* identifiers */
1447         ot->name= "Select Tips";
1448         ot->idname= "PARTICLE_OT_select_tips";
1449         
1450         /* api callbacks */
1451         ot->exec= select_tips_exec;
1452         ot->poll= PE_poll;
1453
1454         /* flags */
1455         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1456 }
1457
1458 /************************ select linked operator ************************/
1459
1460 static int select_linked_exec(bContext *C, wmOperator *op)
1461 {
1462         PEData data;
1463         short mval[2];
1464         int location[2];
1465
1466         RNA_int_get_array(op->ptr, "location", location);
1467         mval[0]= location[0];
1468         mval[1]= location[1];
1469
1470         view3d_operator_needs_opengl(C);
1471
1472         PE_set_view3d_data(C, &data);
1473         data.mval= mval;
1474         data.rad=75.0f;
1475         data.select= !RNA_boolean_get(op->ptr, "deselect");
1476
1477         for_mouse_hit_keys(&data, select_keys, 1);  /* nearest only */
1478         PE_update_selection(data.scene, data.ob, 1);
1479         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1480
1481         return OPERATOR_FINISHED;
1482 }
1483
1484 static int select_linked_invoke(bContext *C, wmOperator *op, wmEvent *event)
1485 {
1486         ARegion *ar= CTX_wm_region(C);
1487         int location[2];
1488
1489         location[0]= event->x - ar->winrct.xmin;
1490         location[1]= event->y - ar->winrct.ymin;
1491         RNA_int_set_array(op->ptr, "location", location);
1492
1493         return select_linked_exec(C, op);
1494 }
1495
1496 void PARTICLE_OT_select_linked(wmOperatorType *ot)
1497 {
1498         /* identifiers */
1499         ot->name= "Select Linked";
1500         ot->idname= "PARTICLE_OT_select_linked";
1501         
1502         /* api callbacks */
1503         ot->exec= select_linked_exec;
1504         ot->invoke= select_linked_invoke;
1505         ot->poll= PE_poll_view3d;
1506
1507         /* flags */
1508         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1509
1510         /* properties */
1511         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect linked keys rather than selecting them.");
1512         RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384);
1513 }
1514
1515 /************************ border select operator ************************/
1516
1517 int PE_border_select(bContext *C, rcti *rect, int select, int extend)
1518 {
1519         Scene *scene= CTX_data_scene(C);
1520         Object *ob= CTX_data_active_object(C);
1521         PTCacheEdit *edit= PE_get_current(scene, ob);
1522         PEData data;
1523
1524         if(!PE_start_edit(edit))
1525                 return OPERATOR_CANCELLED;
1526
1527         if (extend == 0 && select) {
1528                 POINT_P; KEY_K;
1529
1530                 LOOP_VISIBLE_POINTS {
1531                         LOOP_SELECTED_KEYS {
1532                                 key->flag &= ~PEK_SELECT;
1533                                 point->flag |= PEP_EDIT_RECALC;
1534                         }
1535                 }
1536         }
1537
1538         PE_set_view3d_data(C, &data);
1539         data.rect= rect;
1540         data.select= select;
1541
1542         for_mouse_hit_keys(&data, select_key, 0);
1543
1544         PE_update_selection(scene, ob, 1);
1545         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1546
1547         return OPERATOR_FINISHED;
1548 }
1549
1550 /************************ circle select operator ************************/
1551
1552 int PE_circle_select(bContext *C, int selecting, short *mval, float rad)
1553 {
1554         Scene *scene= CTX_data_scene(C);
1555         Object *ob= CTX_data_active_object(C);
1556         PTCacheEdit *edit= PE_get_current(scene, ob);
1557         PEData data;
1558
1559         if(!PE_start_edit(edit))
1560                 return OPERATOR_FINISHED;
1561
1562         PE_set_view3d_data(C, &data);
1563         data.mval= mval;
1564         data.rad= rad;
1565         data.select= selecting;
1566
1567         for_mouse_hit_keys(&data, select_key, 0);
1568
1569         PE_update_selection(scene, ob, 1);
1570         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1571
1572         return OPERATOR_FINISHED;
1573 }
1574
1575 /************************ lasso select operator ************************/
1576
1577 int PE_lasso_select(bContext *C, short mcords[][2], short moves, short select)
1578 {
1579         Scene *scene= CTX_data_scene(C);
1580         Object *ob= CTX_data_active_object(C);
1581         ARegion *ar= CTX_wm_region(C);
1582         ParticleEditSettings *pset= PE_settings(scene);
1583         PTCacheEdit *edit = PE_get_current(scene, ob);
1584         ParticleSystem *psys = edit->psys;
1585         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
1586         POINT_P; KEY_K;
1587         float co[3], mat[4][4];
1588         short vertco[2];
1589
1590         if(!PE_start_edit(edit))
1591                 return OPERATOR_CANCELLED;
1592
1593         unit_m4(mat);
1594
1595         LOOP_VISIBLE_POINTS {
1596                 if(edit->psys && !(psys->flag & PSYS_GLOBAL_HAIR))
1597                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles + p, mat);
1598
1599                 if(pset->selectmode==SCE_SELECT_POINT) {
1600                         LOOP_KEYS {
1601                                 VECCOPY(co, key->co);
1602                                 mul_m4_v3(mat, co);
1603                                 project_short(ar, co, vertco);
1604                                 if((vertco[0] != IS_CLIPPED) && lasso_inside(mcords,moves,vertco[0],vertco[1])) {
1605                                         if(select && !(key->flag & PEK_SELECT)) {
1606                                                 key->flag |= PEK_SELECT;
1607                                                 point->flag |= PEP_EDIT_RECALC;
1608                                         }
1609                                         else if(key->flag & PEK_SELECT) {
1610                                                 key->flag &= ~PEK_SELECT;
1611                                                 point->flag |= PEP_EDIT_RECALC;
1612                                         }
1613                                 }
1614                         }
1615                 }
1616                 else if(pset->selectmode==SCE_SELECT_END) {
1617                         key= point->keys + point->totkey - 1;
1618
1619                         VECCOPY(co, key->co);
1620                         mul_m4_v3(mat, co);
1621                         project_short(ar, co,vertco);
1622                         if((vertco[0] != IS_CLIPPED) && lasso_inside(mcords,moves,vertco[0],vertco[1])) {
1623                                 if(select && !(key->flag & PEK_SELECT)) {
1624                                         key->flag |= PEK_SELECT;
1625                                         point->flag |= PEP_EDIT_RECALC;
1626                                 }
1627                                 else if(key->flag & PEK_SELECT) {
1628                                         key->flag &= ~PEK_SELECT;
1629                                         point->flag |= PEP_EDIT_RECALC;
1630                                 }
1631                         }
1632                 }
1633         }
1634
1635         PE_update_selection(scene, ob, 1);
1636         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1637
1638         return OPERATOR_FINISHED;
1639 }
1640
1641 /*************************** hide operator **************************/
1642
1643 static int hide_exec(bContext *C, wmOperator *op)
1644 {
1645         Object *ob= CTX_data_active_object(C);
1646         Scene *scene= CTX_data_scene(C);
1647         PTCacheEdit *edit= PE_get_current(scene, ob);
1648         POINT_P; KEY_K;
1649         
1650         if(RNA_enum_get(op->ptr, "unselected")) {
1651                 LOOP_UNSELECTED_POINTS {
1652                         point->flag |= PEP_HIDE;
1653                         point->flag |= PEP_EDIT_RECALC;
1654
1655                         LOOP_KEYS
1656                                 key->flag &= ~PEK_SELECT;
1657                 }
1658         }
1659         else {
1660                 LOOP_SELECTED_POINTS {
1661                         point->flag |= PEP_HIDE;
1662                         point->flag |= PEP_EDIT_RECALC;
1663
1664                         LOOP_KEYS
1665                                 key->flag &= ~PEK_SELECT;
1666                 }
1667         }
1668
1669         PE_update_selection(scene, ob, 1);
1670         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1671
1672         return OPERATOR_FINISHED;
1673 }
1674
1675 void PARTICLE_OT_hide(wmOperatorType *ot)
1676 {
1677         /* identifiers */
1678         ot->name= "Hide Selected";
1679         ot->idname= "PARTICLE_OT_hide";
1680         
1681         /* api callbacks */
1682         ot->exec= hide_exec;
1683         ot->poll= PE_poll;
1684
1685         /* flags */
1686         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1687
1688         /* props */
1689         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected.");
1690 }
1691
1692 /*************************** reveal operator **************************/
1693
1694 static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
1695 {
1696         Object *ob= CTX_data_active_object(C);
1697         Scene *scene= CTX_data_scene(C);
1698         PTCacheEdit *edit= PE_get_current(scene, ob);
1699         POINT_P; KEY_K;
1700
1701         LOOP_POINTS {
1702                 if(point->flag & PEP_HIDE) {
1703                         point->flag &= ~PEP_HIDE;
1704                         point->flag |= PEP_EDIT_RECALC;
1705
1706                         LOOP_KEYS
1707                                 key->flag |= PEK_SELECT;
1708                 }
1709         }
1710
1711         PE_update_selection(scene, ob, 1);
1712         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1713
1714         return OPERATOR_FINISHED;
1715 }
1716
1717 void PARTICLE_OT_reveal(wmOperatorType *ot)
1718 {
1719         /* identifiers */
1720         ot->name= "Reveal";
1721         ot->idname= "PARTICLE_OT_reveal";
1722         
1723         /* api callbacks */
1724         ot->exec= reveal_exec;
1725         ot->poll= PE_poll;
1726
1727         /* flags */
1728         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1729 }
1730
1731 /************************ select less operator ************************/
1732
1733 static void select_less_keys(PEData *data, int point_index)
1734 {
1735         PTCacheEdit *edit= data->edit;
1736         PTCacheEditPoint *point = edit->points + point_index;
1737         KEY_K;
1738
1739         LOOP_SELECTED_KEYS {
1740                 if(k==0) {
1741                         if(((key+1)->flag&PEK_SELECT)==0)
1742                                 key->flag |= PEK_TAG;
1743                 }
1744                 else if(k==point->totkey-1) {
1745                         if(((key-1)->flag&PEK_SELECT)==0)
1746                                 key->flag |= PEK_TAG;
1747                 }
1748                 else {
1749                         if((((key-1)->flag & (key+1)->flag) & PEK_SELECT)==0)
1750                                 key->flag |= PEK_TAG;
1751                 }
1752         }
1753
1754         LOOP_KEYS {
1755                 if(key->flag&PEK_TAG) {
1756                         key->flag &= ~(PEK_TAG|PEK_SELECT);
1757                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1758                 }
1759         }
1760 }
1761
1762 static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
1763 {
1764         PEData data;
1765
1766         PE_set_data(C, &data);
1767         foreach_point(&data, select_less_keys);
1768
1769         PE_update_selection(data.scene, data.ob, 1);
1770         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1771
1772         return OPERATOR_FINISHED;
1773 }
1774
1775 void PARTICLE_OT_select_less(wmOperatorType *ot)
1776 {
1777         /* identifiers */
1778         ot->name= "Select Less";
1779         ot->idname= "PARTICLE_OT_select_less";
1780         
1781         /* api callbacks */
1782         ot->exec= select_less_exec;
1783         ot->poll= PE_poll;
1784
1785         /* flags */
1786         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1787 }
1788
1789 /************************ select more operator ************************/
1790
1791 static void select_more_keys(PEData *data, int point_index)
1792 {
1793         PTCacheEdit *edit= data->edit;
1794         PTCacheEditPoint *point = edit->points + point_index;
1795         KEY_K;
1796
1797         LOOP_KEYS {
1798                 if(key->flag & PEK_SELECT) continue;
1799
1800                 if(k==0) {
1801                         if((key+1)->flag&PEK_SELECT)
1802                                 key->flag |= PEK_TAG;
1803                 }
1804                 else if(k==point->totkey-1) {
1805                         if((key-1)->flag&PEK_SELECT)
1806                                 key->flag |= PEK_TAG;
1807                 }
1808                 else {
1809                         if(((key-1)->flag | (key+1)->flag) & PEK_SELECT)
1810                                 key->flag |= PEK_TAG;
1811                 }
1812         }
1813
1814         LOOP_KEYS {
1815                 if(key->flag&PEK_TAG) {
1816                         key->flag &= ~PEK_TAG;
1817                         key->flag |= PEK_SELECT;
1818                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1819                 }
1820         }
1821 }
1822
1823 static int select_more_exec(bContext *C, wmOperator *UNUSED(op))
1824 {
1825         PEData data;
1826
1827         PE_set_data(C, &data);
1828         foreach_point(&data, select_more_keys);
1829
1830         PE_update_selection(data.scene, data.ob, 1);
1831         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1832
1833         return OPERATOR_FINISHED;
1834 }
1835
1836 void PARTICLE_OT_select_more(wmOperatorType *ot)
1837 {
1838         /* identifiers */
1839         ot->name= "Select More";
1840         ot->idname= "PARTICLE_OT_select_more";
1841         
1842         /* api callbacks */
1843         ot->exec= select_more_exec;
1844         ot->poll= PE_poll;
1845
1846         /* flags */
1847         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1848 }
1849
1850 static int select_inverse_exec(bContext *C, wmOperator *UNUSED(op))
1851 {
1852         PEData data;
1853         PTCacheEdit *edit;
1854         POINT_P; KEY_K;
1855
1856         PE_set_data(C, &data);
1857
1858         edit= PE_get_current(data.scene, data.ob);
1859
1860         LOOP_VISIBLE_POINTS {
1861                 LOOP_KEYS {
1862                         key->flag ^= PEK_SELECT;
1863                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1864                 }
1865         }
1866
1867         PE_update_selection(data.scene, data.ob, 1);
1868         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1869
1870         return OPERATOR_FINISHED;
1871 }
1872
1873 void PARTICLE_OT_select_inverse(wmOperatorType *ot)
1874 {
1875         /* identifiers */
1876         ot->name= "Select Inverse";
1877         ot->idname= "PARTICLE_OT_select_inverse";
1878
1879         /* api callbacks */
1880         ot->exec= select_inverse_exec;
1881         ot->poll= PE_poll;
1882
1883         /* flags */
1884         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1885 }
1886
1887 /************************ rekey operator ************************/
1888
1889 static void rekey_particle(PEData *data, int pa_index)
1890 {
1891         PTCacheEdit *edit= data->edit;
1892         ParticleSystem *psys= edit->psys;
1893         ParticleSimulationData sim = {data->scene, data->ob, edit->psys, NULL};
1894         ParticleData *pa= psys->particles + pa_index;
1895         PTCacheEditPoint *point = edit->points + pa_index;
1896         ParticleKey state;
1897         HairKey *key, *new_keys, *okey;
1898         PTCacheEditKey *ekey;
1899         float dval, sta, end;
1900         int k;
1901
1902         pa->flag |= PARS_REKEY;
1903
1904         key= new_keys= MEM_callocN(data->totrekey * sizeof(HairKey),"Hair re-key keys");
1905
1906         okey = pa->hair;
1907         /* root and tip stay the same */
1908         VECCOPY(key->co, okey->co);
1909         VECCOPY((key + data->totrekey - 1)->co, (okey + pa->totkey - 1)->co);
1910
1911         sta= key->time= okey->time;
1912         end= (key + data->totrekey - 1)->time= (okey + pa->totkey - 1)->time;
1913         dval= (end - sta) / (float)(data->totrekey - 1);
1914
1915         /* interpolate new keys from old ones */
1916         for(k=1,key++; k<data->totrekey-1; k++,key++) {
1917                 state.time= (float)k / (float)(data->totrekey-1);
1918                 psys_get_particle_on_path(&sim, pa_index, &state, 0);
1919                 VECCOPY(key->co, state.co);
1920                 key->time= sta + k * dval;
1921         }
1922
1923         /* replace keys */
1924         if(pa->hair)
1925                 MEM_freeN(pa->hair);
1926         pa->hair= new_keys;
1927
1928         point->totkey=pa->totkey=data->totrekey;
1929
1930
1931         if(point->keys)
1932                 MEM_freeN(point->keys);
1933         ekey= point->keys= MEM_callocN(pa->totkey * sizeof(PTCacheEditKey),"Hair re-key edit keys");
1934                 
1935         for(k=0, key=pa->hair; k<pa->totkey; k++, key++, ekey++) {
1936                 ekey->co= key->co;
1937                 ekey->time= &key->time;
1938                 if(!(psys->flag & PSYS_GLOBAL_HAIR))
1939                         ekey->flag |= PEK_USE_WCO;
1940         }
1941
1942         pa->flag &= ~PARS_REKEY;
1943         point->flag |= PEP_EDIT_RECALC;
1944 }
1945
1946 static int rekey_exec(bContext *C, wmOperator *op)
1947 {
1948         PEData data;
1949
1950         PE_set_data(C, &data);
1951
1952         data.dval= 1.0f / (float)(data.totrekey-1);
1953         data.totrekey= RNA_int_get(op->ptr, "keys");
1954
1955         foreach_selected_point(&data, rekey_particle);
1956         
1957         recalc_lengths(data.edit);
1958         PE_update_object(data.scene, data.ob, 1);
1959         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
1960
1961         return OPERATOR_FINISHED;
1962 }
1963
1964 void PARTICLE_OT_rekey(wmOperatorType *ot)
1965 {
1966         /* identifiers */
1967         ot->name= "Rekey";
1968         ot->idname= "PARTICLE_OT_rekey";
1969         
1970         /* api callbacks */
1971         ot->exec= rekey_exec;
1972         ot->invoke= WM_operator_props_popup;
1973         ot->poll= PE_poll;
1974
1975         /* flags */
1976         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1977
1978         /* properties */
1979         RNA_def_int(ot->srna, "keys", 2, 2, INT_MAX, "Number of Keys", "", 2, 100);
1980 }
1981
1982 static void rekey_particle_to_time(Scene *scene, Object *ob, int pa_index, float path_time)
1983 {
1984         PTCacheEdit *edit= PE_get_current(scene, ob);
1985         ParticleSystem *psys;
1986         ParticleSimulationData sim = {scene, ob, edit ? edit->psys : NULL, NULL};
1987         ParticleData *pa;
1988         ParticleKey state;
1989         HairKey *new_keys, *key;
1990         PTCacheEditKey *ekey;
1991         int k;
1992
1993         if(!edit || !edit->psys) return;
1994
1995         psys = edit->psys;
1996
1997         pa= psys->particles + pa_index;
1998
1999         pa->flag |= PARS_REKEY;
2000
2001         key= new_keys= MEM_dupallocN(pa->hair);
2002         
2003         /* interpolate new keys from old ones (roots stay the same) */
2004         for(k=1, key++; k < pa->totkey; k++, key++) {
2005                 state.time= path_time * (float)k / (float)(pa->totkey-1);
2006                 psys_get_particle_on_path(&sim, pa_index, &state, 0);
2007                 VECCOPY(key->co, state.co);
2008         }
2009
2010         /* replace hair keys */
2011         if(pa->hair)
2012                 MEM_freeN(pa->hair);
2013         pa->hair= new_keys;
2014
2015         /* update edit pointers */
2016         for(k=0, key=pa->hair, ekey=edit->points[pa_index].keys; k<pa->totkey; k++, key++, ekey++) {
2017                 ekey->co= key->co;
2018                 ekey->time= &key->time;
2019         }
2020
2021         pa->flag &= ~PARS_REKEY;
2022 }
2023
2024 /************************* utilities **************************/
2025
2026 static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror)
2027 {
2028         PTCacheEdit *edit = psys->edit;
2029         ParticleData *pa, *npa=0, *new_pars=0;
2030         POINT_P;
2031         PTCacheEditPoint *npoint=0, *new_points=0;
2032         ParticleSystemModifierData *psmd;
2033         int i, totpart, new_totpart= psys->totpart, removed= 0;
2034
2035         if(mirror) {
2036                 /* mirror tags */
2037                 psmd= psys_get_modifier(ob, psys);
2038                 totpart= psys->totpart;
2039
2040                 LOOP_TAGGED_POINTS {
2041                         PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
2042                 }
2043         }
2044
2045         LOOP_TAGGED_POINTS {
2046                 new_totpart--;
2047                 removed++;
2048         }
2049
2050         if(new_totpart != psys->totpart) {
2051                 if(new_totpart) {
2052                         npa= new_pars= MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array");
2053                         npoint= new_points= MEM_callocN(new_totpart * sizeof(PTCacheEditPoint), "PTCacheEditKey array");
2054                 }
2055
2056                 pa= psys->particles;
2057                 point= edit->points;
2058                 for(i=0; i<psys->totpart; i++, pa++, point++) {
2059                         if(point->flag & PEP_TAG) {
2060                                 if(point->keys)
2061                                         MEM_freeN(point->keys);
2062                                 if(pa->hair)
2063                                         MEM_freeN(pa->hair);
2064                         }
2065                         else {
2066                                 memcpy(npa, pa, sizeof(ParticleData));
2067                                 memcpy(npoint, point, sizeof(PTCacheEditPoint));
2068                                 npa++;
2069                                 npoint++;
2070                         }
2071                 }
2072
2073                 if(psys->particles) MEM_freeN(psys->particles);
2074                 psys->particles= new_pars;
2075
2076                 if(edit->points) MEM_freeN(edit->points);
2077                 edit->points= new_points;
2078
2079                 if(edit->mirror_cache) {
2080                         MEM_freeN(edit->mirror_cache);
2081                         edit->mirror_cache= NULL;
2082                 }
2083
2084                 if(psys->child) {
2085                         MEM_freeN(psys->child);
2086                         psys->child= NULL;
2087                         psys->totchild=0;
2088                 }
2089
2090                 edit->totpoint= psys->totpart= new_totpart;
2091         }
2092
2093         return removed;
2094 }
2095
2096 static void remove_tagged_keys(Object *ob, ParticleSystem *psys)
2097 {
2098         PTCacheEdit *edit= psys->edit;
2099         ParticleData *pa;
2100         HairKey *hkey, *nhkey, *new_hkeys=0;
2101         POINT_P; KEY_K;
2102         PTCacheEditKey *nkey, *new_keys;
2103         ParticleSystemModifierData *psmd;
2104         short new_totkey;
2105
2106         if(pe_x_mirror(ob)) {
2107                 /* mirror key tags */
2108                 psmd= psys_get_modifier(ob, psys);
2109
2110                 LOOP_POINTS {
2111                         LOOP_TAGGED_KEYS {
2112                                 PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
2113                                 break;
2114                         }
2115                 }
2116         }
2117
2118         LOOP_POINTS {
2119                 new_totkey= point->totkey;
2120                 LOOP_TAGGED_KEYS {
2121                         new_totkey--;
2122                 }
2123                 /* we can't have elements with less than two keys*/
2124                 if(new_totkey < 2)
2125                         point->flag |= PEP_TAG;
2126         }
2127         remove_tagged_particles(ob, psys, pe_x_mirror(ob));
2128
2129         LOOP_POINTS {
2130                 pa = psys->particles + p;
2131                 new_totkey= pa->totkey;
2132
2133                 LOOP_TAGGED_KEYS {
2134                         new_totkey--;
2135                 }
2136
2137                 if(new_totkey != pa->totkey) {
2138                         nhkey= new_hkeys= MEM_callocN(new_totkey*sizeof(HairKey), "HairKeys");
2139                         nkey= new_keys= MEM_callocN(new_totkey*sizeof(PTCacheEditKey), "particle edit keys");
2140
2141                         hkey= pa->hair;
2142                         LOOP_KEYS {
2143                                 while(key->flag & PEK_TAG && hkey < pa->hair + pa->totkey) {
2144                                         key++;
2145                                         hkey++;
2146                                 }
2147
2148                                 if(hkey < pa->hair + pa->totkey) {
2149                                         VECCOPY(nhkey->co, hkey->co);
2150                                         nhkey->editflag = hkey->editflag;
2151                                         nhkey->time= hkey->time;
2152                                         nhkey->weight= hkey->weight;
2153                                         
2154                                         nkey->co= nhkey->co;
2155                                         nkey->time= &nhkey->time;
2156                                         /* these can be copied from old edit keys */
2157                                         nkey->flag = key->flag;
2158                                         nkey->ftime = key->ftime;
2159                                         nkey->length = key->length;
2160                                         VECCOPY(nkey->world_co, key->world_co);
2161                                 }
2162                                 nkey++;
2163                                 nhkey++;
2164                                 hkey++;
2165                         }
2166
2167                         if(pa->hair)
2168                                 MEM_freeN(pa->hair);
2169
2170                         if(point->keys)
2171                                 MEM_freeN(point->keys);
2172                         
2173                         pa->hair= new_hkeys;
2174                         point->keys= new_keys;
2175
2176                         point->totkey= pa->totkey= new_totkey;
2177
2178                         /* flag for recalculating length */
2179                         point->flag |= PEP_EDIT_RECALC;
2180                 }
2181         }
2182 }
2183
2184 /************************ subdivide opertor *********************/
2185
2186 /* works like normal edit mode subdivide, inserts keys between neighbouring selected keys */
2187 static void subdivide_particle(PEData *data, int pa_index)
2188 {
2189         PTCacheEdit *edit= data->edit;
2190         ParticleSystem *psys= edit->psys;
2191         ParticleSimulationData sim = {data->scene, data->ob, edit->psys, NULL};
2192         ParticleData *pa= psys->particles + pa_index;
2193         PTCacheEditPoint *point = edit->points + pa_index;
2194         ParticleKey state;
2195         HairKey *key, *nkey, *new_keys;
2196         PTCacheEditKey *ekey, *nekey, *new_ekeys;
2197
2198         int k;
2199         short totnewkey=0;
2200         float endtime;
2201
2202         for(k=0, ekey=point->keys; k<pa->totkey-1; k++,ekey++) {
2203                 if(ekey->flag&PEK_SELECT && (ekey+1)->flag&PEK_SELECT)
2204                         totnewkey++;
2205         }
2206
2207         if(totnewkey==0) return;
2208
2209         pa->flag |= PARS_REKEY;
2210
2211         nkey= new_keys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(HairKey)),"Hair subdivide keys");
2212         nekey= new_ekeys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(PTCacheEditKey)),"Hair subdivide edit keys");
2213         
2214         key = pa->hair;
2215         endtime= key[pa->totkey-1].time;
2216
2217         for(k=0, ekey=point->keys; k<pa->totkey-1; k++, key++, ekey++) {
2218
2219                 memcpy(nkey,key,sizeof(HairKey));
2220                 memcpy(nekey,ekey,sizeof(PTCacheEditKey));
2221
2222                 nekey->co= nkey->co;
2223                 nekey->time= &nkey->time;
2224
2225                 nkey++;
2226                 nekey++;
2227
2228                 if(ekey->flag & PEK_SELECT && (ekey+1)->flag & PEK_SELECT) {
2229                         nkey->time= (key->time + (key+1)->time)*0.5f;
2230                         state.time= (endtime != 0.0f)? nkey->time/endtime: 0.0f;
2231                         psys_get_particle_on_path(&sim, pa_index, &state, 0);
2232                         VECCOPY(nkey->co, state.co);
2233
2234                         nekey->co= nkey->co;
2235                         nekey->time= &nkey->time;
2236                         nekey->flag |= PEK_SELECT;
2237                         if(!(psys->flag & PSYS_GLOBAL_HAIR))
2238                                 nekey->flag |= PEK_USE_WCO;
2239
2240                         nekey++;
2241                         nkey++;
2242                 }
2243         }
2244         /*tip still not copied*/
2245         memcpy(nkey,key,sizeof(HairKey));
2246         memcpy(nekey,ekey,sizeof(PTCacheEditKey));
2247
2248         nekey->co= nkey->co;
2249         nekey->time= &nkey->time;
2250
2251         if(pa->hair)
2252                 MEM_freeN(pa->hair);
2253         pa->hair= new_keys;
2254
2255         if(point->keys)
2256                 MEM_freeN(point->keys);
2257         point->keys= new_ekeys;
2258
2259         point->totkey = pa->totkey = pa->totkey + totnewkey;
2260         point->flag |= PEP_EDIT_RECALC;
2261         pa->flag &= ~PARS_REKEY;
2262 }
2263
2264 static int subdivide_exec(bContext *C, wmOperator *UNUSED(op))
2265 {
2266         PEData data;
2267
2268         PE_set_data(C, &data);
2269         foreach_point(&data, subdivide_particle);
2270         
2271         recalc_lengths(data.edit);
2272         PE_update_object(data.scene, data.ob, 1);
2273         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
2274
2275         return OPERATOR_FINISHED;
2276 }
2277
2278 void PARTICLE_OT_subdivide(wmOperatorType *ot)
2279 {
2280         /* identifiers */
2281         ot->name= "Subdivide";
2282         ot->idname= "PARTICLE_OT_subdivide";
2283         
2284         /* api callbacks */
2285         ot->exec= subdivide_exec;
2286         ot->poll= PE_poll;
2287
2288         /* flags */
2289         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2290 }
2291
2292 /************************ remove doubles opertor *********************/
2293
2294 static int remove_doubles_exec(bContext *C, wmOperator *op)
2295 {
2296         Scene *scene= CTX_data_scene(C);
2297         Object *ob= CTX_data_active_object(C);
2298         PTCacheEdit *edit= PE_get_current(scene, ob);
2299         ParticleSystem *psys = edit->psys;
2300         ParticleSystemModifierData *psmd;
2301         KDTree *tree;
2302         KDTreeNearest nearest[10];
2303         POINT_P;
2304         float mat[4][4], co[3], threshold= RNA_float_get(op->ptr, "threshold");
2305         int n, totn, removed, totremoved;
2306
2307         if(psys->flag & PSYS_GLOBAL_HAIR)
2308                 return OPERATOR_CANCELLED;
2309
2310         edit= psys->edit;
2311         psmd= psys_get_modifier(ob, psys);
2312         totremoved= 0;
2313
2314         do {
2315                 removed= 0;
2316
2317                 tree=BLI_kdtree_new(psys->totpart);
2318                         
2319                 /* insert particles into kd tree */
2320                 LOOP_SELECTED_POINTS {
2321                         psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles+p, mat);
2322                         VECCOPY(co, point->keys->co);
2323                         mul_m4_v3(mat, co);
2324                         BLI_kdtree_insert(tree, p, co, NULL);
2325                 }
2326
2327                 BLI_kdtree_balance(tree);
2328
2329                 /* tag particles to be removed */
2330                 LOOP_SELECTED_POINTS {
2331                         psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles+p, mat);
2332                         VECCOPY(co, point->keys->co);
2333                         mul_m4_v3(mat, co);
2334
2335                         totn= BLI_kdtree_find_n_nearest(tree,10,co,NULL,nearest);
2336
2337                         for(n=0; n<totn; n++) {
2338                                 /* this needs a custom threshold still */
2339                                 if(nearest[n].index > p && nearest[n].dist < threshold) {
2340                                         if(!(point->flag & PEP_TAG)) {
2341                                                 point->flag |= PEP_TAG;
2342                                                 removed++;
2343                                         }
2344                                 }
2345                         }
2346                 }
2347
2348                 BLI_kdtree_free(tree);
2349
2350                 /* remove tagged particles - don't do mirror here! */
2351                 remove_tagged_particles(ob, psys, 0);
2352                 totremoved += removed;
2353         } while(removed);
2354
2355         if(totremoved == 0)
2356                 return OPERATOR_CANCELLED;
2357
2358         BKE_reportf(op->reports, RPT_INFO, "Remove %d double particles.", totremoved);
2359
2360         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
2361         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2362
2363         return OPERATOR_FINISHED;
2364 }
2365
2366 void PARTICLE_OT_remove_doubles(wmOperatorType *ot)
2367 {
2368         /* identifiers */
2369         ot->name= "Remove Doubles";
2370         ot->idname= "PARTICLE_OT_remove_doubles";
2371         
2372         /* api callbacks */
2373         ot->exec= remove_doubles_exec;
2374         ot->poll= PE_poll;
2375
2376         /* flags */
2377         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2378
2379         /* properties */
2380         RNA_def_float(ot->srna, "threshold", 0.0002f, 0.0f, FLT_MAX, "Threshold", "Threshold distance withing which particles are removed", 0.00001f, 0.1f);
2381 }
2382
2383
2384 static int weight_set_exec(bContext *C, wmOperator *op)
2385 {
2386         Scene *scene= CTX_data_scene(C);
2387         ParticleEditSettings *pset= PE_settings(scene);
2388         Object *ob= CTX_data_active_object(C);
2389         PTCacheEdit *edit= PE_get_current(scene, ob);
2390         ParticleSystem *psys = edit->psys;
2391         POINT_P;
2392         KEY_K;
2393         HairKey *hkey;
2394         float weight;
2395         ParticleBrushData *brush= &pset->brush[pset->brushtype];
2396     float factor= RNA_float_get(op->ptr, "factor");
2397
2398         weight= brush->strength;
2399         edit= psys->edit;
2400
2401         LOOP_SELECTED_POINTS {
2402                 ParticleData *pa= psys->particles + p;
2403
2404                 LOOP_SELECTED_KEYS {
2405                         hkey= pa->hair + k;
2406                         hkey->weight= interpf(weight, hkey->weight, factor);
2407                 }
2408         }
2409
2410         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
2411         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2412
2413         return OPERATOR_FINISHED;
2414 }
2415
2416 void PARTICLE_OT_weight_set(wmOperatorType *ot)
2417 {
2418         /* identifiers */
2419         ot->name= "Weight Set";
2420         ot->idname= "PARTICLE_OT_weight_set";
2421
2422         /* api callbacks */
2423         ot->exec= weight_set_exec;
2424         ot->poll= PE_poll;
2425
2426         /* flags */
2427         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2428     
2429     RNA_def_float(ot->srna, "factor", 1, 0, 1, "Factor", "", 0, 1);
2430 }
2431
2432 /************************ cursor drawing *******************************/
2433
2434 static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata))
2435 {
2436         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2437         ParticleBrushData *brush;
2438
2439         if(pset->brushtype < 0)
2440                 return;
2441
2442         brush= &pset->brush[pset->brushtype];
2443
2444         if(brush) {
2445                 glPushMatrix();
2446
2447                 glTranslatef((float)x, (float)y, 0.0f);
2448
2449                 glColor4ub(255, 255, 255, 128);
2450                 glEnable(GL_LINE_SMOOTH );
2451                 glEnable(GL_BLEND);
2452                 glutil_draw_lined_arc(0.0, M_PI*2.0, brush->size, 40);
2453                 glDisable(GL_BLEND);
2454                 glDisable(GL_LINE_SMOOTH );
2455                 
2456                 glPopMatrix();
2457         }
2458 }
2459
2460 static void toggle_particle_cursor(bContext *C, int enable)
2461 {
2462         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2463
2464         if(pset->paintcursor && !enable) {
2465                 WM_paint_cursor_end(CTX_wm_manager(C), pset->paintcursor);
2466                 pset->paintcursor = NULL;
2467         }
2468         else if(enable)
2469                 pset->paintcursor= WM_paint_cursor_activate(CTX_wm_manager(C), PE_poll_view3d, brush_drawcursor, NULL);
2470 }
2471
2472 /********************* radial control operator *********************/
2473
2474 static int brush_radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
2475 {
2476         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2477         ParticleBrushData *brush;
2478         int mode = RNA_enum_get(op->ptr, "mode");
2479         float original_value=1.0f;
2480
2481         if(pset->brushtype < 0)
2482                 return OPERATOR_CANCELLED;
2483
2484         brush= &pset->brush[pset->brushtype];
2485
2486         toggle_particle_cursor(C, 0);
2487
2488         if(mode == WM_RADIALCONTROL_SIZE)
2489                 original_value = brush->size;
2490         else if(mode == WM_RADIALCONTROL_STRENGTH)
2491                 original_value = brush->strength;
2492
2493         RNA_float_set(op->ptr, "initial_value", original_value);
2494
2495         return WM_radial_control_invoke(C, op, event);
2496 }
2497
2498 static int brush_radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
2499 {
2500         int ret = WM_radial_control_modal(C, op, event);
2501
2502         if(ret != OPERATOR_RUNNING_MODAL)
2503                 toggle_particle_cursor(C, 1);
2504
2505         return ret;
2506 }
2507
2508 static int brush_radial_control_exec(bContext *C, wmOperator *op)
2509 {
2510         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2511         ParticleBrushData *brush;
2512         int mode = RNA_enum_get(op->ptr, "mode");
2513         float new_value = RNA_float_get(op->ptr, "new_value");
2514
2515         if(pset->brushtype < 0)
2516                 return OPERATOR_CANCELLED;
2517
2518         brush= &pset->brush[pset->brushtype];
2519
2520         if(mode == WM_RADIALCONTROL_SIZE)
2521                 brush->size= new_value;
2522         else if(mode == WM_RADIALCONTROL_STRENGTH)
2523                 brush->strength= new_value;
2524
2525         WM_event_add_notifier(C, NC_WINDOW, NULL);
2526
2527         return OPERATOR_FINISHED;
2528 }
2529
2530 void PARTICLE_OT_brush_radial_control(wmOperatorType *ot)
2531 {
2532         WM_OT_radial_control_partial(ot);
2533
2534         ot->name= "Brush Radial Control";
2535         ot->idname= "PARTICLE_OT_brush_radial_control";
2536
2537         ot->invoke= brush_radial_control_invoke;
2538         ot->modal= brush_radial_control_modal;
2539         ot->exec= brush_radial_control_exec;
2540         ot->poll= PE_poll;
2541         
2542         /* flags */
2543         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2544 }
2545
2546 /*************************** delete operator **************************/
2547
2548 enum { DEL_PARTICLE, DEL_KEY };
2549
2550 static EnumPropertyItem delete_type_items[]= {
2551         {DEL_PARTICLE, "PARTICLE", 0, "Particle", ""},
2552         {DEL_KEY, "KEY", 0, "Key", ""},
2553         {0, NULL, 0, NULL, NULL}};
2554
2555 static void set_delete_particle(PEData *data, int pa_index)
2556 {
2557         PTCacheEdit *edit= data->edit;
2558
2559         edit->points[pa_index].flag |= PEP_TAG;
2560 }
2561
2562 static void set_delete_particle_key(PEData *data, int pa_index, int key_index)
2563 {
2564         PTCacheEdit *edit= data->edit;
2565
2566         edit->points[pa_index].keys[key_index].flag |= PEK_TAG;
2567 }
2568
2569 static int delete_exec(bContext *C, wmOperator *op)
2570 {
2571         PEData data;
2572         int type= RNA_enum_get(op->ptr, "type");
2573
2574         PE_set_data(C, &data);
2575
2576         if(type == DEL_KEY) {
2577                 foreach_selected_key(&data, set_delete_particle_key);
2578                 remove_tagged_keys(data.ob, data.edit->psys);
2579                 recalc_lengths(data.edit);
2580         }
2581         else if(type == DEL_PARTICLE) {
2582                 foreach_selected_point(&data, set_delete_particle);
2583                 remove_tagged_particles(data.ob, data.edit->psys, pe_x_mirror(data.ob));
2584                 recalc_lengths(data.edit);
2585         }
2586
2587         DAG_id_flush_update(&data.ob->id, OB_RECALC_DATA);
2588         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
2589
2590         return OPERATOR_FINISHED;
2591 }
2592
2593 void PARTICLE_OT_delete(wmOperatorType *ot)
2594 {
2595         /* identifiers */
2596         ot->name= "Delete";
2597         ot->idname= "PARTICLE_OT_delete";
2598         
2599         /* api callbacks */
2600         ot->exec= delete_exec;
2601         ot->invoke= WM_menu_invoke;
2602         ot->poll= PE_hair_poll;
2603
2604         /* flags */
2605         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2606
2607         /* properties */
2608         ot->prop= RNA_def_enum(ot->srna, "type", delete_type_items, DEL_PARTICLE, "Type", "Delete a full particle or only keys.");
2609 }
2610
2611 /*************************** mirror operator **************************/
2612
2613 static void PE_mirror_x(Scene *scene, Object *ob, int tagged)
2614 {
2615         Mesh *me= (Mesh*)(ob->data);
2616         ParticleSystemModifierData *psmd;
2617         PTCacheEdit *edit= PE_get_current(scene, ob);
2618         ParticleSystem *psys = edit->psys;
2619         ParticleData *pa, *newpa, *new_pars;
2620         PTCacheEditPoint *newpoint, *new_points;
2621         POINT_P; KEY_K;
2622         HairKey *hkey;
2623         int *mirrorfaces;
2624         int rotation, totpart, newtotpart;
2625
2626         if(psys->flag & PSYS_GLOBAL_HAIR)
2627                 return;
2628
2629         psmd= psys_get_modifier(ob, psys);
2630         if(!psmd->dm)
2631                 return;
2632
2633         mirrorfaces= mesh_get_x_mirror_faces(ob, NULL);
2634
2635         if(!edit->mirror_cache)
2636                 PE_update_mirror_cache(ob, psys);
2637
2638         totpart= psys->totpart;
2639         newtotpart= psys->totpart;
2640         LOOP_VISIBLE_POINTS {
2641                 pa = psys->particles + p;
2642                 if(!tagged) {
2643                         if(point_is_selected(point)) {
2644                                 if(edit->mirror_cache[p] != -1) {
2645                                         /* already has a mirror, don't need to duplicate */
2646                                         PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
2647                                         continue;
2648                                 }
2649                                 else
2650                                         point->flag |= PEP_TAG;
2651                         }
2652                 }
2653
2654                 if((point->flag & PEP_TAG) && mirrorfaces[pa->num*2] != -1)
2655                         newtotpart++;
2656         }
2657
2658         if(newtotpart != psys->totpart) {
2659                 /* allocate new arrays and copy existing */
2660                 new_pars= MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new");
2661                 new_points= MEM_callocN(newtotpart*sizeof(PTCacheEditPoint), "PTCacheEditPoint new");
2662
2663                 if(psys->particles) {
2664                         memcpy(new_pars, psys->particles, totpart*sizeof(ParticleData));
2665                         MEM_freeN(psys->particles);
2666                 }
2667                 psys->particles= new_pars;
2668
2669                 if(edit->points) {
2670                         memcpy(new_points, edit->points, totpart*sizeof(PTCacheEditPoint));
2671                         MEM_freeN(edit->points);
2672                 }
2673                 edit->points= new_points;
2674
2675                 if(edit->mirror_cache) {
2676                         MEM_freeN(edit->mirror_cache);
2677                         edit->mirror_cache= NULL;
2678                 }
2679
2680                 edit->totpoint= psys->totpart= newtotpart;
2681                         
2682                 /* create new elements */
2683                 newpa= psys->particles + totpart;
2684                 newpoint= edit->points + totpart;
2685
2686                 for(p=0, point=edit->points; p<totpart; p++, point++) {
2687                         pa = psys->particles + p;
2688
2689                         if(point->flag & PEP_HIDE)
2690                                 continue;
2691                         if(!(point->flag & PEP_TAG) || mirrorfaces[pa->num*2] == -1)
2692                                 continue;
2693
2694                         /* duplicate */
2695                         *newpa= *pa;
2696                         *newpoint= *point;
2697                         if(pa->hair) newpa->hair= MEM_dupallocN(pa->hair);
2698                         if(point->keys) newpoint->keys= MEM_dupallocN(point->keys);
2699
2700                         /* rotate weights according to vertex index rotation */
2701                         rotation= mirrorfaces[pa->num*2+1];
2702                         newpa->fuv[0]= pa->fuv[2];
2703                         newpa->fuv[1]= pa->fuv[1];
2704                         newpa->fuv[2]= pa->fuv[0];
2705                         newpa->fuv[3]= pa->fuv[3];
2706                         while(rotation-- > 0)
2707                                 if(me->mface[pa->num].v4)
2708                                         SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3])
2709                                 else
2710                                         SHIFT3(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2])
2711
2712                         /* assign face inddex */
2713                         newpa->num= mirrorfaces[pa->num*2];
2714                         newpa->num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,newpa->num,newpa->fuv, NULL);
2715
2716                         /* update edit key pointers */
2717                         key= newpoint->keys;
2718                         for(k=0, hkey=newpa->hair; k<newpa->totkey; k++, hkey++, key++) {
2719                                 key->co= hkey->co;
2720                                 key->time= &hkey->time;
2721                         }
2722
2723                         /* map key positions as mirror over x axis */
2724                         PE_mirror_particle(ob, psmd->dm, psys, pa, newpa);
2725
2726                         newpa++;
2727                         newpoint++;
2728                 }
2729         }
2730
2731         LOOP_POINTS {
2732                 point->flag &= ~PEP_TAG;
2733         }
2734
2735         MEM_freeN(mirrorfaces);
2736 }
2737
2738 static int mirror_exec(bContext *C, wmOperator *UNUSED(op))
2739 {
2740         Scene *scene= CTX_data_scene(C);
2741         Object *ob= CTX_data_active_object(C);
2742         PTCacheEdit *edit= PE_get_current(scene, ob);
2743         
2744         PE_mirror_x(scene, ob, 0);
2745
2746         update_world_cos(ob, edit);
2747         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2748         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
2749
2750         return OPERATOR_FINISHED;
2751 }
2752
2753 void PARTICLE_OT_mirror(wmOperatorType *ot)
2754 {
2755         /* identifiers */
2756         ot->name= "Mirror";
2757         ot->idname= "PARTICLE_OT_mirror";
2758         
2759         /* api callbacks */
2760         ot->exec= mirror_exec;
2761         ot->poll= PE_poll;
2762
2763         /* flags */
2764         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2765 }
2766
2767 /************************* brush edit callbacks ********************/
2768
2769 static void brush_comb(PEData *data, float UNUSED(mat[][4]), float imat[][4], int point_index, int key_index, PTCacheEditKey *key)
2770 {
2771         ParticleEditSettings *pset= PE_settings(data->scene);
2772         float cvec[3], fac;
2773
2774         if(pset->flag & PE_LOCK_FIRST && key_index == 0) return;
2775
2776         fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->combfac);
2777
2778         VECCOPY(cvec,data->dvec);
2779         mul_mat3_m4_v3(imat,cvec);
2780         mul_v3_fl(cvec, fac);
2781         VECADD(key->co, key->co, cvec);
2782
2783         (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
2784 }
2785
2786 static void brush_cut(PEData *data, int pa_index)
2787 {
2788         PTCacheEdit *edit = data->edit;
2789         ARegion *ar= data->vc.ar;
2790         Object *ob= data->ob;
2791         ParticleEditSettings *pset= PE_settings(data->scene);
2792         ParticleCacheKey *key= edit->pathcache[pa_index];
2793         float rad2, cut_time= 1.0;
2794         float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv;
2795         int k, cut, keys= (int)pow(2.0, (double)pset->draw_step);
2796         short vertco[2];
2797
2798         /* blunt scissors */
2799         if(BLI_frand() > data->cutfac) return;
2800
2801         /* don't cut hidden */
2802         if(edit->points[pa_index].flag & PEP_HIDE)
2803                 return;
2804
2805         rad2= data->rad * data->rad;
2806
2807         cut=0;
2808
2809         project_short_noclip(ar, key->co, vertco);
2810         x0= (float)vertco[0];
2811         x1= (float)vertco[1];
2812
2813         o0= (float)data->mval[0];
2814         o1= (float)data->mval[1];
2815         
2816         xo0= x0 - o0;
2817         xo1= x1 - o1;
2818
2819         /* check if root is inside circle */
2820         if(xo0*xo0 + xo1*xo1 < rad2 && key_test_depth(data, key->co)) {
2821                 cut_time= -1.0f;
2822                 cut= 1;
2823         }
2824         else {
2825                 /* calculate path time closest to root that was inside the circle */
2826                 for(k=1, key++; k<=keys; k++, key++) {
2827                         project_short_noclip(ar, key->co, vertco);
2828
2829                         if(key_test_depth(data, key->co) == 0) {
2830                                 x0= (float)vertco[0];
2831                                 x1= (float)vertco[1];
2832
2833                                 xo0= x0 - o0;
2834                                 xo1= x1 - o1;
2835                                 continue;
2836                         }
2837
2838                         v0= (float)vertco[0] - x0;
2839                         v1= (float)vertco[1] - x1;
2840
2841                         dv= v0*v0 + v1*v1;
2842
2843                         d= (v0*xo1 - v1*xo0);
2844                         
2845                         d= dv * rad2 - d*d;
2846
2847                         if(d > 0.0f) {
2848                                 d= sqrt(d);
2849
2850                                 cut_time= -(v0*xo0 + v1*xo1 + d);
2851
2852                                 if(cut_time > 0.0f) {
2853                                         cut_time /= dv;
2854
2855                                         if(cut_time < 1.0f) {
2856                                                 cut_time += (float)(k-1);
2857                                                 cut_time /= (float)keys;
2858                                                 cut= 1;
2859                                                 break;
2860                                         }
2861                                 }
2862                         }
2863
2864                         x0= (float)vertco[0];
2865                         x1= (float)vertco[1];
2866
2867                         xo0= x0 - o0;
2868                         xo1= x1 - o1;
2869                 }
2870         }
2871
2872         if(cut) {
2873                 if(cut_time < 0.0f) {
2874                         edit->points[pa_index].flag |= PEP_TAG;
2875                 }
2876                 else {
2877                         rekey_particle_to_time(data->scene, ob, pa_index, cut_time);
2878                         edit->points[pa_index].flag |= PEP_EDIT_RECALC;
2879                 }
2880         }
2881 }
2882
2883 static void brush_length(PEData *data, int point_index)
2884 {
2885         PTCacheEdit *edit= data->edit;
2886         PTCacheEditPoint *point = edit->points + point_index;
2887         KEY_K;
2888         float dvec[3],pvec[3] = {0.0f, 0.0f, 0.0f};
2889
2890         LOOP_KEYS {
2891                 if(k==0) {
2892                         VECCOPY(pvec,key->co);
2893                 }
2894                 else {
2895                         VECSUB(dvec,key->co,pvec);
2896                         VECCOPY(pvec,key->co);
2897                         mul_v3_fl(dvec,data->growfac);
2898                         VECADD(key->co,(key-1)->co,dvec);
2899                 }
2900         }
2901
2902         point->flag |= PEP_EDIT_RECALC;
2903 }
2904
2905 static void brush_puff(PEData *data, int point_index)
2906 {
2907         PTCacheEdit *edit = data->edit;
2908         ParticleSystem *psys = edit->psys;
2909         PTCacheEditPoint *point = edit->points + point_index;
2910         KEY_K;
2911         float mat[4][4], imat[4][4];
2912
2913         float lastco[3], rootco[3] = {0.0f, 0.0f, 0.0f}, co[3], nor[3], kco[3], dco[3], ofs[3] = {0.0f, 0.0f, 0.0f}, fac=0.0f, length=0.0f;
2914         int puff_volume = 0;
2915         int change= 0;
2916
2917         {
2918                 ParticleEditSettings *pset= PE_settings(data->scene);
2919                 ParticleBrushData *brush= &pset->brush[pset->brushtype];
2920                 puff_volume = brush->flag & PE_BRUSH_DATA_PUFF_VOLUME;
2921         }
2922
2923         if(psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
2924                 psys_mat_hair_to_global(data->ob, data->dm, psys->part->from, psys->particles + point_index, mat);
2925                 invert_m4_m4(imat,mat);
2926         }
2927         else {
2928                 unit_m4(mat);
2929                 unit_m4(imat);
2930         }
2931
2932         LOOP_KEYS {
2933                 if(k==0) {
2934                         /* find root coordinate and normal on emitter */
2935                         VECCOPY(co, key->co);
2936                         mul_m4_v3(mat, co);
2937                         mul_v3_m4v3(kco, data->ob->imat, co); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */
2938
2939                         point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL, NULL);
2940                         if(point_index == -1) return;
2941
2942                         VECCOPY(rootco, co);
2943                         copy_v3_v3(nor, &edit->emitter_cosnos[point_index*6+3]);
2944                         mul_mat3_m4_v3(data->ob->obmat, nor); /* normal into worldspace */
2945
2946                         normalize_v3(nor);
2947                         length= 0.0f;
2948
2949                         fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->pufffac);
2950                         fac *= 0.025f;
2951                         if(data->invert)
2952                                 fac= -fac;
2953                 }
2954                 else {
2955                         /* compute position as if hair was standing up straight.
2956                          * */
2957                         VECCOPY(lastco, co);
2958                         VECCOPY(co, key->co);
2959                         mul_m4_v3(mat, co);
2960                         length += len_v3v3(lastco, co);
2961                         if((data->select==0 || (key->flag & PEK_SELECT)) && !(key->flag & PEK_HIDE)) {
2962                                 VECADDFAC(kco, rootco, nor, length);
2963
2964                                 /* blend between the current and straight position */
2965                                 VECSUB(dco, kco, co);
2966                                 VECADDFAC(co, co, dco, fac);
2967
2968                                 /* re-use dco to compare before and after translation and add to the offset  */
2969                                 VECCOPY(dco, key->co);
2970
2971                                 mul_v3_m4v3(key->co, imat, co);
2972
2973                                 if(puff_volume) {
2974                                         /* accumulate the total distance moved to apply to unselected
2975                                          * keys that come after */
2976                                         ofs[0] += key->co[0] - dco[0];
2977                                         ofs[1] += key->co[1] - dco[1];
2978                                         ofs[2] += key->co[2] - dco[2];
2979                                 }
2980                                 change = 1;
2981                         }
2982                         else {
2983
2984                                 if(puff_volume) {
2985 #if 0
2986                                         /* this is simple but looks bad, adds annoying kinks */
2987                                         add_v3_v3(key->co, ofs);
2988 #else
2989                                         /* translate (not rotate) the rest of the hair if its not selected  */
2990                                         if(ofs[0] || ofs[1] || ofs[2]) {
2991 #if 0                                   /* kindof works but looks worse then whats below */
2992
2993                                                 /* Move the unselected point on a vector based on the
2994                                                  * hair direction and the offset */
2995                                                 float c1[3], c2[3];
2996                                                 VECSUB(dco, lastco, co);
2997                                                 mul_mat3_m4_v3(imat, dco); /* into particle space */
2998
2999                                                 /* move the point allong a vector perpendicular to the
3000                                                  * hairs direction, reduces odd kinks, */
3001                                                 cross_v3_v3v3(c1, ofs, dco);
3002                                                 cross_v3_v3v3(c2, c1, dco);
3003                                                 normalize_v3(c2);
3004                                                 mul_v3_fl(c2, len_v3(ofs));
3005                                                 add_v3_v3(key->co, c2);
3006 #else
3007                                                 /* Move the unselected point on a vector based on the
3008                                                  * the normal of the closest geometry */
3009                                                 float oco[3], onor[3];
3010                                                 VECCOPY(oco, key->co);
3011                                                 mul_m4_v3(mat, oco);
3012                                                 mul_v3_m4v3(kco, data->ob->imat, oco); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */
3013
3014                                                 point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL, NULL);
3015                                                 if(point_index != -1) {
3016                                                         copy_v3_v3(onor, &edit->emitter_cosnos[point_index*6+3]);
3017                                                         mul_mat3_m4_v3(data->ob->obmat, onor); /* normal into worldspace */
3018                                                         mul_mat3_m4_v3(imat, onor); /* worldspace into particle space */
3019                                                         normalize_v3(onor);
3020
3021
3022                                                         mul_v3_fl(onor, len_v3(ofs));
3023                                                         add_v3_v3(key->co, onor);
3024                                                 }
3025 #endif
3026                                         }
3027 #endif
3028                                 }
3029                         }
3030                 }
3031         }
3032
3033         if(change)
3034                 point->flag |= PEP_EDIT_RECALC;
3035 }
3036
3037
3038 static void brush_weight(PEData *data, float UNUSED(mat[][4]), float UNUSED(imat[][4]), int point_index, int key_index, PTCacheEditKey *UNUSED(key))
3039 {
3040         /* roots have full weight allways */
3041         if(key_index) {
3042                 PTCacheEdit *edit = data->edit;
3043                 ParticleSystem *psys = edit->psys;
3044
3045                 ParticleData *pa= psys->particles + point_index;
3046                 pa->hair[key_index].weight = data->weightfac;
3047
3048                 (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
3049         }
3050 }
3051
3052 static void brush_smooth_get(PEData *data, float mat[][4], float UNUSED(imat[][4]), int UNUSED(point_index), int key_index, PTCacheEditKey *key)
3053 {       
3054         if(key_index) {
3055                 float dvec[3];
3056
3057                 sub_v3_v3v3(dvec,key->co,(key-1)->co);
3058                 mul_mat3_m4_v3(mat,dvec);
3059                 VECADD(data->vec,data->vec,dvec);
3060                 data->tot++;
3061         }
3062 }
3063
3064 static void brush_smooth_do(PEData *data, float UNUSED(mat[][4]), float imat[][4], int point_index, int key_index, PTCacheEditKey *key)
3065 {
3066         float vec[3], dvec[3];
3067         
3068         if(key_index) {
3069                 VECCOPY(vec,data->vec);
3070                 mul_mat3_m4_v3(imat,vec);
3071
3072                 sub_v3_v3v3(dvec,key->co,(key-1)->co);
3073
3074                 VECSUB(dvec,vec,dvec);
3075                 mul_v3_fl(dvec,data->smoothfac);
3076                 
3077                 VECADD(key->co,key->co,dvec);
3078         }
3079
3080         (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
3081 }
3082
3083 static int brush_add(PEData *data, short number)
3084 {
3085         Scene *scene= data->scene;
3086         Object *ob= data->ob;
3087         PTCacheEdit *edit = data->edit;
3088         ParticleSystem *psys= edit->psys;
3089         ParticleData *add_pars= MEM_callocN(number*sizeof(ParticleData),"ParticleData add");
3090         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
3091         ParticleSimulationData sim = {scene, ob, psys, psmd};
3092         ParticleEditSettings *pset= PE_settings(scene);
3093         int i, k, n= 0, totpart= psys->totpart;
3094         float mco[2];
3095         short dmx= 0, dmy= 0;
3096         float co1[3], co2[3], min_d, imat[4][4];
3097         float framestep, timestep= psys_get_timestep(&sim);
3098         short size= pset->brush[PE_BRUSH_ADD].size;
3099         short size2= size*size;
3100         DerivedMesh *dm=0;
3101         invert_m4_m4(imat,ob->obmat);
3102
3103         if(psys->flag & PSYS_GLOBAL_HAIR)
3104                 return 0;
3105
3106         BLI_srandom(psys->seed+data->mval[0]+data->mval[1]);
3107         
3108         /* painting onto the deformed mesh, could be an option? */
3109         if(psmd->dm->deformedOnly)
3110                 dm= psmd->dm;
3111         else
3112                 dm= mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
3113
3114         for(i=0; i<number; i++) {
3115                 if(number>1) {
3116                         dmx=dmy=size;
3117                         while(dmx*dmx+dmy*dmy>size2) {
3118                                 dmx=(short)((2.0f*BLI_frand()-1.0f)*size);
3119                                 dmy=(short)((2.0f*BLI_frand()-1.0f)*size);
3120                         }
3121                 }
3122
3123                 mco[0]= data->mval[0] + dmx;
3124                 mco[1]= data->mval[1] + dmy;
3125                 viewline(data->vc.ar, data->vc.v3d, mco, co1, co2);
3126
3127                 mul_m4_v3(imat,co1);
3128                 mul_m4_v3(imat,co2);
3129                 min_d=2.0;
3130                 
3131                 /* warning, returns the derived mesh face */
3132                 if(psys_intersect_dm(scene, ob,dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)) {
3133                         add_pars[n].num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,add_pars[n].num,add_pars[n].fuv,NULL);
3134                         n++;
3135                 }
3136         }
3137         if(n) {
3138                 int newtotpart=totpart+n;
3139                 float hairmat[4][4], cur_co[3];
3140                 KDTree *tree=0;
3141                 ParticleData *pa, *new_pars= MEM_callocN(newtotpart*sizeof(ParticleData),"ParticleData new");
3142                 PTCacheEditPoint *point, *new_points= MEM_callocN(newtotpart*sizeof(PTCacheEditPoint),"PTCacheEditPoint array new");
3143                 PTCacheEditKey *key;
3144                 HairKey *hkey;
3145
3146                 /* save existing elements */
3147                 memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData));
3148                 memcpy(new_points, edit->points, totpart * sizeof(PTCacheEditPoint));
3149
3150                 /* change old arrays to new ones */
3151                 if(psys->particles) MEM_freeN(psys->particles);
3152                 psys->particles= new_pars;
3153
3154                 if(edit->points) MEM_freeN(edit->points);
3155                 edit->points= new_points;
3156
3157                 if(edit->mirror_cache) {
3158                         MEM_freeN(edit->mirror_cache);
3159                         edit->mirror_cache= NULL;
3160                 }
3161
3162                 /* create tree for interpolation */
3163                 if(pset->flag & PE_INTERPOLATE_ADDED && psys->totpart) {
3164                         tree=BLI_kdtree_new(psys->totpart);
3165                         
3166                         for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
3167                                 psys_particle_on_dm(psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,cur_co,0,0,0,0,0);
3168                                 BLI_kdtree_insert(tree, i, cur_co, NULL);
3169                         }
3170
3171                         BLI_kdtree_balance(tree);
3172                 }
3173
3174                 edit->totpoint= psys->totpart= newtotp