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