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