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