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