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