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