copying 2.5 over to trunk
[blender.git] / source / blender / editors / mesh / meshtools.c
1 /**
2  * $Id: 
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2004 by Blender Foundation
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /*
31         meshtools.c: no editmode (violated already :), tools operating on meshes
32 */
33
34 #include <stdlib.h>
35 #include <string.h>
36 #include <math.h>
37 #include <float.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_image_types.h"
42 #include "DNA_key_types.h"
43 #include "DNA_material_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_mesh_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_screen_types.h"
49 #include "DNA_space_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_windowmanager_types.h"
52 #include "DNA_world_types.h"
53
54 #include "BLI_arithb.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_editVert.h"
57 #include "BLI_ghash.h"
58 #include "BLI_rand.h" /* for randome face sorting */
59 #include "BLI_threads.h"
60
61
62 #include "BKE_blender.h"
63 #include "BKE_context.h"
64 #include "BKE_depsgraph.h"
65 #include "BKE_customdata.h"
66 #include "BKE_global.h"
67 #include "BKE_image.h"
68 #include "BKE_key.h"
69 #include "BKE_library.h"
70 #include "BKE_main.h"
71 #include "BKE_mesh.h"
72 #include "BKE_material.h"
73 #include "BKE_object.h"
74 #include "BKE_utildefines.h"
75 #include "BKE_report.h"
76
77 #include "RE_pipeline.h"
78 #include "RE_shader_ext.h"
79
80 #include "PIL_time.h"
81
82 #include "IMB_imbuf_types.h"
83 #include "IMB_imbuf.h"
84
85 #include "GPU_draw.h"
86
87 #include "BLO_sys_types.h" // for intptr_t support
88
89 #include "ED_mesh.h"
90 #include "ED_object.h"
91 #include "ED_view3d.h"
92
93 #include "WM_api.h"
94 #include "WM_types.h"
95
96 /* own include */
97 #include "mesh_intern.h"
98
99 /* XXX */
100 static void waitcursor(int val) {}
101 static void error() {}
102 static int pupmenu() {return 0;}
103 /* XXX */
104
105
106 /* * ********************** no editmode!!! *********** */
107
108 /*********************** JOIN ***************************/
109
110 /* join selected meshes into the active mesh, context sensitive
111 return 0 if no join is made (error) and 1 of the join is done */
112
113 int join_mesh_exec(bContext *C, wmOperator *op)
114 {
115         Scene *scene= CTX_data_scene(C);
116         Object *ob= CTX_data_active_object(C);
117         Material **matar, *ma;
118         Mesh *me;
119         MVert *mvert, *mv, *mvertmain;
120         MEdge *medge = NULL, *medgemain;
121         MFace *mface = NULL, *mfacemain;
122         Key *key, *nkey=NULL;
123         KeyBlock *kb, *okb, *kbn;
124         float imat[4][4], cmat[4][4], *fp1, *fp2, curpos;
125         int a, b, totcol, totmat=0, totedge=0, totvert=0, totface=0, ok=0;
126         int vertofs, *matmap;
127         int     i, j, index, haskey=0, edgeofs, faceofs;
128         bDeformGroup *dg, *odg;
129         MDeformVert *dvert;
130         CustomData vdata, edata, fdata;
131
132         if(scene->obedit)
133                 return OPERATOR_CANCELLED;
134         
135         /* ob is the object we are adding geometry to */
136         if(!ob || ob->type!=OB_MESH)
137                 return OPERATOR_CANCELLED;
138         
139         /* count & check */
140         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
141                 if(base->object->type==OB_MESH) {
142                         me= base->object->data;
143                         
144                         totvert+= me->totvert;
145                         totedge+= me->totedge;
146                         totface+= me->totface;
147                         totmat+= base->object->totcol;
148                         
149                         if(base->object == ob)
150                                 ok= 1;
151                         
152                         /* check for shapekeys */
153                         if(me->key)
154                                 haskey++;
155                 }
156         }
157         CTX_DATA_END;
158         
159         /* that way the active object is always selected */ 
160         if(ok==0)
161                 return OPERATOR_CANCELLED;
162         
163         /* only join meshes if there are verts to join, there aren't too many, and we only had one mesh selected */
164         me= (Mesh *)ob->data;
165         key= me->key;
166         if(totvert==0 || totvert>MESH_MAX_VERTS || totvert==me->totvert) 
167                 return OPERATOR_CANCELLED;
168         
169         /* new material indices and material array */
170         matar= MEM_callocN(sizeof(void*)*totmat, "join_mesh matar");
171         matmap= MEM_callocN(sizeof(int)*totmat, "join_mesh matmap");
172         totcol= ob->totcol;
173         
174         /* obact materials in new main array, is nicer start! */
175         for(a=0; a<ob->totcol; a++) {
176                 matar[a]= give_current_material(ob, a+1);
177                 id_us_plus((ID *)matar[a]);
178                 /* increase id->us : will be lowered later */
179         }
180         
181         /* - if destination mesh had shapekeys, move them somewhere safe, and set up placeholders
182          *      with arrays that are large enough to hold shapekey data for all meshes
183          * -    if destination mesh didn't have shapekeys, but we encountered some in the meshes we're 
184          *      joining, set up a new keyblock and assign to the mesh
185          */
186         if(key) {
187                 /* make a duplicate copy that will only be used here... (must remember to free it!) */
188                 nkey= copy_key(key);
189                 
190                 /* for all keys in old block, clear data-arrays */
191                 for(kb= key->block.first; kb; kb= kb->next) {
192                         if(kb->data) MEM_freeN(kb->data);
193                         kb->data= MEM_callocN(sizeof(float)*3*totvert, "join_shapekey");
194                         kb->totelem= totvert;
195                         kb->weights= NULL;
196                 }
197         }
198         else if(haskey) {
199                 /* add a new key-block and add to the mesh */
200                 key= me->key= add_key((ID *)me);
201                 key->type = KEY_RELATIVE;
202         }
203         
204         /* first pass over objects - copying materials and vertexgroups across */
205         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
206                 /* only act if a mesh, and not the one we're joining to */
207                 if((ob!=base->object) && (base->object->type==OB_MESH)) {
208                         me= base->object->data;
209                         
210                         /* Join this object's vertex groups to the base one's */
211                         for(dg=base->object->defbase.first; dg; dg=dg->next) {
212                                 /* See if this group exists in the object (if it doesn't, add it to the end) */
213                                 for(odg=ob->defbase.first; odg; odg=odg->next) {
214                                         if(!strcmp(odg->name, dg->name)) {
215                                                 break;
216                                         }
217                                 }
218                                 if(!odg) {
219                                         odg = MEM_callocN(sizeof(bDeformGroup), "join deformGroup");
220                                         memcpy(odg, dg, sizeof(bDeformGroup));
221                                         BLI_addtail(&ob->defbase, odg);
222                                 }
223                         }
224                         if(ob->defbase.first && ob->actdef==0)
225                                 ob->actdef=1;
226                         
227                         
228                         if(me->totvert) {
229                                 /* Add this object's materials to the base one's if they don't exist already (but only if limits not exceeded yet) */
230                                 if(totcol < MAXMAT-1) {
231                                         for(a=1; a<=base->object->totcol; a++) {
232                                                 ma= give_current_material(base->object, a);
233
234                                                 for(b=0; b<totcol; b++) {
235                                                         if(ma == matar[b]) break;
236                                                 }
237                                                 if(b==totcol) {
238                                                         matar[b]= ma;
239                                                         if(ma)
240                                                                 ma->id.us++;
241                                                         totcol++;
242                                                 }
243                                                 if(totcol>=MAXMAT-1) 
244                                                         break;
245                                         }
246                                 }
247                                 
248                                 /* if this mesh has shapekeys, check if destination mesh already has matching entries too */
249                                 if(me->key && key) {
250                                         for(kb= me->key->block.first; kb; kb= kb->next) {
251                                                 /* if key doesn't exist in destination mesh, add it */
252                                                 if(key_get_named_keyblock(key, kb->name) == NULL) {
253                                                         /* copy this existing one over to the new shapekey block */
254                                                         kbn= MEM_dupallocN(kb);
255                                                         kbn->prev= kbn->next= NULL;
256                                                         
257                                                         /* adjust adrcode and other settings to fit (allocate a new data-array) */
258                                                         kbn->data= MEM_callocN(sizeof(float)*3*totvert, "joined_shapekey");
259                                                         kbn->totelem= totvert;
260                                                         kbn->weights= NULL;
261                                                         
262                                                         okb= key->block.last;
263                                                         curpos= (okb) ? okb->pos : -0.1f;
264                                                         if(key->type == KEY_RELATIVE)
265                                                                 kbn->pos= curpos + 0.1f;
266                                                         else
267                                                                 kbn->pos= curpos;
268                                                         
269                                                         BLI_addtail(&key->block, kbn);
270                                                         kbn->adrcode= key->totkey;
271                                                         key->totkey++;
272                                                         if(key->totkey==1) key->refkey= kbn;
273                                                         
274                                                         // XXX 2.5 Animato
275 #if 0
276                                                         /* also, copy corresponding ipo-curve to ipo-block if applicable */
277                                                         if(me->key->ipo && key->ipo) {
278                                                                 // FIXME... this is a luxury item!
279                                                                 puts("FIXME: ignoring IPO's when joining shapekeys on Meshes for now...");
280                                                         }
281 #endif
282                                                 }
283                                         }
284                                 }
285                         }
286                 }
287         }
288         CTX_DATA_END;
289         
290         /* setup new data for destination mesh */
291         memset(&vdata, 0, sizeof(vdata));
292         memset(&edata, 0, sizeof(edata));
293         memset(&fdata, 0, sizeof(fdata));
294         
295         mvert= CustomData_add_layer(&vdata, CD_MVERT, CD_CALLOC, NULL, totvert);
296         medge= CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge);
297         mface= CustomData_add_layer(&fdata, CD_MFACE, CD_CALLOC, NULL, totface);
298         
299         mvertmain= mvert;
300         medgemain= medge;
301         mfacemain= mface;
302         
303         vertofs= 0;
304         edgeofs= 0;
305         faceofs= 0;
306         
307         /* inverse transform for all selected meshes in this object */
308         Mat4Invert(imat, ob->obmat);
309         
310         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
311                 /* only join if this is a mesh */
312                 if(base->object->type==OB_MESH) {
313                         me= base->object->data;
314                         
315                         if(me->totvert) {
316                                 /* standard data */
317                                 CustomData_merge(&me->vdata, &vdata, CD_MASK_MESH, CD_DEFAULT, totvert);
318                                 CustomData_copy_data(&me->vdata, &vdata, 0, vertofs, me->totvert);
319                                 
320                                 /* vertex groups */
321                                 dvert= CustomData_get(&vdata, vertofs, CD_MDEFORMVERT);
322                                 
323                                 /* NB: vertex groups here are new version */
324                                 if(dvert) {
325                                         for(i=0; i<me->totvert; i++) {
326                                                 for(j=0; j<dvert[i].totweight; j++) {
327                                                         /*      Find the old vertex group */
328                                                         odg = BLI_findlink(&base->object->defbase, dvert[i].dw[j].def_nr);
329                                                         if(odg) {
330                                                                 /*      Search for a match in the new object, and set new index */
331                                                                 for(dg=ob->defbase.first, index=0; dg; dg=dg->next, index++) {
332                                                                         if(!strcmp(dg->name, odg->name)) {
333                                                                                 dvert[i].dw[j].def_nr = index;
334                                                                                 break;
335                                                                         }
336                                                                 }
337                                                         }
338                                                 }
339                                         }
340                                 }
341                                 
342                                 /* if this is the object we're merging into, no need to do anything */
343                                 if(base->object != ob) {
344                                         /* watch this: switch matmul order really goes wrong */
345                                         Mat4MulMat4(cmat, base->object->obmat, imat);
346                                         
347                                         /* transform vertex coordinates into new space */
348                                         for(a=0, mv=mvert; a < me->totvert; a++, mv++) {
349                                                 Mat4MulVecfl(cmat, mv->co);
350                                         }
351                                         
352                                         /* for each shapekey in destination mesh:
353                                          *      - if there's a matching one, copy it across (will need to transform vertices into new space...)
354                                          *      - otherwise, just copy own coordinates of mesh (no need to transform vertex coordinates into new space)
355                                          */
356                                         if(key) {
357                                                 /* if this mesh has any shapekeys, check first, otherwise just copy coordinates */
358                                                 for(kb= key->block.first; kb; kb= kb->next) {
359                                                         /* get pointer to where to write data for this mesh in shapekey's data array */
360                                                         fp1= ((float *)kb->data) + (vertofs*3); 
361                                                         
362                                                         /* check if this mesh has such a shapekey */
363                                                         okb= key_get_named_keyblock(me->key, kb->name);
364                                                         if(okb) {
365                                                                 /* copy this mesh's shapekey to the destination shapekey (need to transform first) */
366                                                                 fp2= ((float *)(okb->data));
367                                                                 for(a=0; a < me->totvert; a++, fp1+=3, fp2+=3) {
368                                                                         VECCOPY(fp1, fp2);
369                                                                         Mat4MulVecfl(cmat, fp1);
370                                                                 }
371                                                         }
372                                                         else {
373                                                                 /* copy this mesh's vertex coordinates to the destination shapekey */
374                                                                 mv= mvert;
375                                                                 for(a=0; a < me->totvert; a++, fp1+=3, mv++) {
376                                                                         VECCOPY(fp1, mv->co);
377                                                                 }
378                                                         }
379                                                 }
380                                         }
381                                 }
382                                 else {
383                                         /* for each shapekey in destination mesh:
384                                          *      - if it was an 'original', copy the appropriate data from nkey
385                                          *      - otherwise, copy across plain coordinates (no need to transform coordinates)
386                                          */
387                                         if(key) {
388                                                 for(kb= key->block.first; kb; kb= kb->next) {
389                                                         /* get pointer to where to write data for this mesh in shapekey's data array */
390                                                         fp1= ((float *)kb->data) + (vertofs*3); 
391                                                         
392                                                         /* check if this was one of the original shapekeys */
393                                                         okb= key_get_named_keyblock(nkey, kb->name);
394                                                         if(okb) {
395                                                                 /* copy this mesh's shapekey to the destination shapekey */
396                                                                 fp2= ((float *)(okb->data));
397                                                                 for(a=0; a < me->totvert; a++, fp1+=3, fp2+=3) {
398                                                                         VECCOPY(fp1, fp2);
399                                                                 }
400                                                         }
401                                                         else {
402                                                                 /* copy base-coordinates to the destination shapekey */
403                                                                 mv= mvert;
404                                                                 for(a=0; a < me->totvert; a++, fp1+=3, mv++) {
405                                                                         VECCOPY(fp1, mv->co);
406                                                                 }
407                                                         }
408                                                 }
409                                         }
410                                 }
411                                 
412                                 /* advance mvert pointer to end of base mesh's data */
413                                 mvert+= me->totvert;
414                         }
415                         
416                         if(me->totface) {
417                                 /* make mapping for materials */
418                                 for(a=1; a<=base->object->totcol; a++) {
419                                         ma= give_current_material(base->object, a);
420
421                                         for(b=0; b<totcol; b++) {
422                                                 if(ma == matar[b]) {
423                                                         matmap[a-1]= b;
424                                                         break;
425                                                 }
426                                         }
427                                 }
428                                 
429                                 CustomData_merge(&me->fdata, &fdata, CD_MASK_MESH, CD_DEFAULT, totface);
430                                 CustomData_copy_data(&me->fdata, &fdata, 0, faceofs, me->totface);
431                                 
432                                 for(a=0; a<me->totface; a++, mface++) {
433                                         mface->v1+= vertofs;
434                                         mface->v2+= vertofs;
435                                         mface->v3+= vertofs;
436                                         if(mface->v4) mface->v4+= vertofs;
437                                         
438                                         mface->mat_nr= matmap[(int)mface->mat_nr];
439                                 }
440                                 
441                                 faceofs += me->totface;
442                         }
443                         
444                         if(me->totedge) {
445                                 CustomData_merge(&me->edata, &edata, CD_MASK_MESH, CD_DEFAULT, totedge);
446                                 CustomData_copy_data(&me->edata, &edata, 0, edgeofs, me->totedge);
447                                 
448                                 for(a=0; a<me->totedge; a++, medge++) {
449                                         medge->v1+= vertofs;
450                                         medge->v2+= vertofs;
451                                 }
452                                 
453                                 edgeofs += me->totedge;
454                         }
455                         
456                         /* vertofs is used to help newly added verts be reattached to their edge/face 
457                          * (cannot be set earlier, or else reattaching goes wrong)
458                          */
459                         vertofs += me->totvert;
460                         
461                         /* free base, now that data is merged */
462                         if(base->object != ob)
463                                 ED_base_object_free_and_unlink(scene, base);
464                 }
465         }
466         CTX_DATA_END;
467         
468         /* return to mesh we're merging to */
469         me= ob->data;
470         
471         CustomData_free(&me->vdata, me->totvert);
472         CustomData_free(&me->edata, me->totedge);
473         CustomData_free(&me->fdata, me->totface);
474
475         me->totvert= totvert;
476         me->totedge= totedge;
477         me->totface= totface;
478         
479         me->vdata= vdata;
480         me->edata= edata;
481         me->fdata= fdata;
482
483         mesh_update_customdata_pointers(me);
484         
485         /* old material array */
486         for(a=1; a<=ob->totcol; a++) {
487                 ma= ob->mat[a-1];
488                 if(ma) ma->id.us--;
489         }
490         for(a=1; a<=me->totcol; a++) {
491                 ma= me->mat[a-1];
492                 if(ma) ma->id.us--;
493         }
494         if(ob->mat) MEM_freeN(ob->mat);
495         if(ob->matbits) MEM_freeN(ob->matbits);
496         if(me->mat) MEM_freeN(me->mat);
497         ob->mat= me->mat= NULL;
498         ob->matbits= NULL;
499         
500         if(totcol) {
501                 me->mat= matar;
502                 ob->mat= MEM_callocN(sizeof(void *)*totcol, "join obmatar");
503                 ob->matbits= MEM_callocN(sizeof(char)*totcol, "join obmatbits");
504         }
505         else
506                 MEM_freeN(matar);
507         
508         ob->totcol= me->totcol= totcol;
509         ob->colbits= 0;
510
511         MEM_freeN(matmap);
512         
513         /* other mesh users */
514         test_object_materials((ID *)me);
515         
516         /* free temp copy of destination shapekeys (if applicable) */
517         if(nkey) {
518                 // XXX 2.5 Animato
519 #if 0
520                 /* free it's ipo too - both are not actually freed from memory yet as ID-blocks */
521                 if(nkey->ipo) {
522                         free_ipo(nkey->ipo);
523                         BLI_remlink(&G.main->ipo, nkey->ipo);
524                         MEM_freeN(nkey->ipo);
525                 }
526 #endif
527                 
528                 free_key(nkey);
529                 BLI_remlink(&G.main->key, nkey);
530                 MEM_freeN(nkey);
531         }
532         
533         DAG_scene_sort(scene);  // removed objects, need to rebuild dag before editmode call
534         
535         ED_object_enter_editmode(C, EM_WAITCURSOR);
536         ED_object_exit_editmode(C, EM_FREEDATA|EM_WAITCURSOR);
537
538         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
539
540         return OPERATOR_FINISHED;
541 }
542
543 /* ********************** SORT FACES ******************* */
544
545 static void permutate(void *list, int num, int size, int *index)
546 {
547         void *buf;
548         int len;
549         int i;
550
551         len = num * size;
552
553         buf = MEM_mallocN(len, "permutate");
554         memcpy(buf, list, len);
555         
556         for (i = 0; i < num; i++) {
557                 memcpy((char *)list + (i * size), (char *)buf + (index[i] * size), size);
558         }
559         MEM_freeN(buf);
560 }
561
562 /* sort faces on view axis */
563 static float *face_sort_floats;
564 static int float_sort(const void *v1, const void *v2)
565 {
566         float x1, x2;
567         
568         x1 = face_sort_floats[((int *) v1)[0]];
569         x2 = face_sort_floats[((int *) v2)[0]];
570         
571         if( x1 > x2 ) return 1;
572         else if( x1 < x2 ) return -1;
573         return 0;
574 }
575
576
577 void sort_faces(Scene *scene, View3D *v3d)
578 {
579         RegionView3D *rv3d= NULL; // get from context 
580         Object *ob= OBACT;
581         Mesh *me;
582         CustomDataLayer *layer;
583         int i, *index;
584         short event;
585         float reverse = 1;
586         int ctrl= 0;    // XXX
587         
588         if(!ob) return;
589         if(scene->obedit) return;
590         if(ob->type!=OB_MESH) return;
591         if (!v3d) return;
592         
593         me= ob->data;
594         if(me->totface==0) return;
595         
596         event = pupmenu(
597         "Sort Faces (Ctrl to reverse)%t|"
598         "View Axis%x1|"
599         "Cursor Distance%x2|"
600         "Material%x3|"
601         "Selection%x4|"
602         "Randomize%x5");
603         
604         if (event==-1) return;
605         
606         if(ctrl)
607                 reverse = -1;
608         
609 /*      create index list */
610         index = (int *) MEM_mallocN(sizeof(int) * me->totface, "sort faces");
611         for (i = 0; i < me->totface; i++) {
612                 index[i] = i;
613         }
614         
615         face_sort_floats = (float *) MEM_mallocN(sizeof(float) * me->totface, "sort faces float");
616         
617 /* sort index list instead of faces itself 
618    and apply this permutation to all face layers */
619    
620         if (event == 5) {
621                 /* Random */
622                 for(i=0; i<me->totface; i++) {
623                         face_sort_floats[i] = BLI_frand();
624                 }
625                 qsort(index, me->totface, sizeof(int), float_sort);             
626         } else {
627                 MFace *mf;
628                 float vec[3];
629                 float mat[4][4];
630                 float cur[3];
631                 
632                 if (event == 1)
633                         Mat4MulMat4(mat, OBACT->obmat, rv3d->viewmat); /* apply the view matrix to the object matrix */
634                 else if (event == 2) { /* sort from cursor */
635                         if( v3d && v3d->localview ) {
636                                 VECCOPY(cur, v3d->cursor);
637                         } else {
638                                 VECCOPY(cur, scene->cursor);
639                         }
640                         Mat4Invert(mat, OBACT->obmat);
641                         Mat4MulVecfl(mat, cur);
642                 }
643                 
644                 mf= me->mface;
645                 for(i=0; i<me->totface; i++, mf++) {
646                         
647                         if (event==3) {
648                                 face_sort_floats[i] = ((float)mf->mat_nr)*reverse;
649                         } else if (event==4) {
650                                 /*selected first*/
651                                 if (mf->flag & ME_FACE_SEL)     face_sort_floats[i] = 0.0;
652                                 else                                            face_sort_floats[i] = reverse;
653                         } else {
654                                 /* find the faces center */
655                                 VecAddf(vec, (me->mvert+mf->v1)->co, (me->mvert+mf->v2)->co);
656                                 if (mf->v4) {
657                                         VecAddf(vec, vec, (me->mvert+mf->v3)->co);
658                                         VecAddf(vec, vec, (me->mvert+mf->v4)->co);
659                                         VecMulf(vec, 0.25f);
660                                 } else {
661                                         VecAddf(vec, vec, (me->mvert+mf->v3)->co);
662                                         VecMulf(vec, 1.0f/3.0f);
663                                 } /* done */
664                                 
665                                 if (event == 1) { /* sort on view axis */
666                                         Mat4MulVecfl(mat, vec);
667                                         face_sort_floats[i] = vec[2] * reverse;
668                                 } else { /* distance from cursor*/
669                                         face_sort_floats[i] = VecLenf(cur, vec) * reverse; /* back to front */
670                                 }
671                         }
672                 }
673                 qsort(index, me->totface, sizeof(int), float_sort);
674         }
675         
676         MEM_freeN(face_sort_floats);
677         
678         for(i = 0; i < me->fdata.totlayer; i++) {
679                 layer = &me->fdata.layers[i];
680                 permutate(layer->data, me->totface, CustomData_sizeof(layer->type), index);
681         }
682
683         MEM_freeN(index);
684
685         DAG_id_flush_update(ob->data, OB_RECALC_DATA);
686 }
687
688
689
690 /* ********************* MESH VERTEX OCTREE LOOKUP ************* */
691
692 /* important note; this is unfinished, needs better API for editmode, and custom threshold */
693
694 #define MOC_RES                 8
695 #define MOC_NODE_RES    8
696 #define MOC_THRESH              0.0002f
697
698 typedef struct MocNode {
699         struct MocNode *next;
700         intptr_t index[MOC_NODE_RES];
701 } MocNode;
702
703 static int mesh_octree_get_base_offs(float *co, float *offs, float *div)
704 {
705         int vx, vy, vz;
706         
707         vx= floor( (co[0]-offs[0])/div[0] );
708         vy= floor( (co[1]-offs[1])/div[1] );
709         vz= floor( (co[2]-offs[2])/div[2] );
710         
711         CLAMP(vx, 0, MOC_RES-1);
712         CLAMP(vy, 0, MOC_RES-1);
713         CLAMP(vz, 0, MOC_RES-1);
714
715         return (vx*MOC_RES*MOC_RES) + vy*MOC_RES + vz;
716 }
717
718 static void mesh_octree_add_node(MocNode **bt, intptr_t index)
719 {
720         if(*bt==NULL) {
721                 *bt= MEM_callocN(sizeof(MocNode), "MocNode");
722                 (*bt)->index[0]= index;
723         }
724         else {
725                 int a;
726                 for(a=0; a<MOC_NODE_RES; a++) {
727                         if((*bt)->index[a]==index)
728                                 return;
729                         else if((*bt)->index[a]==0) {
730                                 (*bt)->index[a]= index;
731                                 return;
732                         }
733                 }
734                 mesh_octree_add_node(&(*bt)->next, index);
735         }
736 }
737
738 static void mesh_octree_free_node(MocNode **bt)
739 {
740         if( (*bt)->next ) {
741                 mesh_octree_free_node(&(*bt)->next);
742         }
743         MEM_freeN(*bt);
744 }
745
746
747 /* temporal define, just to make nicer code below */
748 #define MOC_ADDNODE(vx, vy, vz) mesh_octree_add_node(basetable + ((vx)*MOC_RES*MOC_RES) + (vy)*MOC_RES + (vz), index)
749
750 static void mesh_octree_add_nodes(MocNode **basetable, float *co, float *offs, float *div, intptr_t index)
751 {
752         float fx, fy, fz;
753         int vx, vy, vz;
754         
755         if (!finite(co[0]) ||
756                 !finite(co[1]) ||
757                 !finite(co[2])
758         ) {
759                 return;
760         }
761         
762         fx= (co[0]-offs[0])/div[0];
763         fy= (co[1]-offs[1])/div[1];
764         fz= (co[2]-offs[2])/div[2];
765         CLAMP(fx, 0.0f, MOC_RES-MOC_THRESH);
766         CLAMP(fy, 0.0f, MOC_RES-MOC_THRESH);
767         CLAMP(fz, 0.0f, MOC_RES-MOC_THRESH);
768         
769         vx= floor(fx);
770         vy= floor(fy);
771         vz= floor(fz);
772         
773         MOC_ADDNODE(vx, vy, vz);
774         
775         if( vx>0 )
776                 if( fx-((float)vx)-MOC_THRESH < 0.0f)
777                         MOC_ADDNODE(vx-1, vy, vz);
778         if( vx<MOC_RES-2 )
779                 if( fx-((float)vx)+MOC_THRESH > 1.0f)
780                         MOC_ADDNODE(vx+1, vy, vz);
781
782         if( vy>0 )
783                 if( fy-((float)vy)-MOC_THRESH < 0.0f) 
784                         MOC_ADDNODE(vx, vy-1, vz);
785         if( vy<MOC_RES-2 )
786                 if( fy-((float)vy)+MOC_THRESH > 1.0f) 
787                         MOC_ADDNODE(vx, vy+1, vz);
788
789         if( vz>0 )
790                 if( fz-((float)vz)-MOC_THRESH < 0.0f) 
791                         MOC_ADDNODE(vx, vy, vz-1);
792         if( vz<MOC_RES-2 )
793                 if( fz-((float)vz)+MOC_THRESH > 1.0f) 
794                         MOC_ADDNODE(vx, vy, vz+1);
795         
796 }
797
798 static intptr_t mesh_octree_find_index(MocNode **bt, float (*orco)[3], MVert *mvert, float *co)
799 {
800         float *vec;
801         int a;
802         
803         if(*bt==NULL)
804                 return -1;
805         
806         for(a=0; a<MOC_NODE_RES; a++) {
807                 if((*bt)->index[a]) {
808                         /* does mesh verts and editmode, code looks potential dangerous, octree should really be filled OK! */
809                         if(orco) {
810                                 vec= orco[(*bt)->index[a]-1];
811                                 if(FloatCompare(vec, co, MOC_THRESH))
812                                         return (*bt)->index[a]-1;
813                         }
814                         else if(mvert) {
815                                 vec= (mvert+(*bt)->index[a]-1)->co;
816                                 if(FloatCompare(vec, co, MOC_THRESH))
817                                         return (*bt)->index[a]-1;
818                         }
819                         else {
820                                 EditVert *eve= (EditVert *)((*bt)->index[a]);
821                                 if(FloatCompare(eve->co, co, MOC_THRESH))
822                                         return (*bt)->index[a];
823                         }
824                 }
825                 else return -1;
826         }
827         if( (*bt)->next)
828                 return mesh_octree_find_index(&(*bt)->next, orco, mvert, co);
829         
830         return -1;
831 }
832
833 static struct {
834         MocNode **table;
835         float offs[3], div[3];
836         float (*orco)[3];
837         float orcoloc[3];
838 } MeshOctree = {NULL, {0, 0, 0}, {0, 0, 0}, NULL};
839
840 /* mode is 's' start, or 'e' end, or 'u' use */
841 /* if end, ob can be NULL */
842 intptr_t mesh_octree_table(Object *ob, EditMesh *em, float *co, char mode)
843 {
844         MocNode **bt;
845         
846         if(mode=='u') {         /* use table */
847                 if(MeshOctree.table==NULL)
848                         mesh_octree_table(ob, em, NULL, 's');
849            
850                 if(MeshOctree.table) {
851                         Mesh *me= ob->data;
852                         bt= MeshOctree.table + mesh_octree_get_base_offs(co, MeshOctree.offs, MeshOctree.div);
853                         if(em)
854                                 return mesh_octree_find_index(bt, NULL, NULL, co);
855                         else
856                                 return mesh_octree_find_index(bt, MeshOctree.orco, me->mvert, co);
857                 }
858                 return -1;
859         }
860         else if(mode=='s') {    /* start table */
861                 Mesh *me= ob->data;
862                 float min[3], max[3];
863
864                 /* we compute own bounding box and don't reuse ob->bb because
865                  * we are using the undeformed coordinates*/
866                 INIT_MINMAX(min, max);
867
868                 if(em && me->edit_mesh==em) {
869                         EditVert *eve;
870                         
871                         for(eve= em->verts.first; eve; eve= eve->next)
872                                 DO_MINMAX(eve->co, min, max)
873                 }
874                 else {          
875                         MVert *mvert;
876                         float *vco;
877                         int a, totvert;
878                         
879                         MeshOctree.orco= mesh_getRefKeyCos(me, &totvert);
880                         mesh_get_texspace(me, MeshOctree.orcoloc, NULL, NULL);
881                         
882                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++) {
883                                 vco= (MeshOctree.orco)? MeshOctree.orco[a]: mvert->co;
884                                 DO_MINMAX(vco, min, max);
885                         }
886                 }
887                 
888                 /* for quick unit coordinate calculus */
889                 VECCOPY(MeshOctree.offs, min);
890                 MeshOctree.offs[0]-= MOC_THRESH;                /* we offset it 1 threshold unit extra */
891                 MeshOctree.offs[1]-= MOC_THRESH;
892                 MeshOctree.offs[2]-= MOC_THRESH;
893                 
894                 VecSubf(MeshOctree.div, max, min);
895                 MeshOctree.div[0]+= 2*MOC_THRESH;       /* and divide with 2 threshold unit more extra (try 8x8 unit grid on paint) */
896                 MeshOctree.div[1]+= 2*MOC_THRESH;
897                 MeshOctree.div[2]+= 2*MOC_THRESH;
898                 
899                 VecMulf(MeshOctree.div, 1.0f/MOC_RES);
900                 if(MeshOctree.div[0]==0.0f) MeshOctree.div[0]= 1.0f;
901                 if(MeshOctree.div[1]==0.0f) MeshOctree.div[1]= 1.0f;
902                 if(MeshOctree.div[2]==0.0f) MeshOctree.div[2]= 1.0f;
903                         
904                 if(MeshOctree.table) /* happens when entering this call without ending it */
905                         mesh_octree_table(ob, em, co, 'e');
906                 
907                 MeshOctree.table= MEM_callocN(MOC_RES*MOC_RES*MOC_RES*sizeof(void *), "sym table");
908                 
909                 if(em && me->edit_mesh==em) {
910                         EditVert *eve;
911
912                         for(eve= em->verts.first; eve; eve= eve->next) {
913                                 mesh_octree_add_nodes(MeshOctree.table, eve->co, MeshOctree.offs, MeshOctree.div, (intptr_t)(eve));
914                         }
915                 }
916                 else {          
917                         MVert *mvert;
918                         float *vco;
919                         int a;
920                         
921                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++) {
922                                 vco= (MeshOctree.orco)? MeshOctree.orco[a]: mvert->co;
923                                 mesh_octree_add_nodes(MeshOctree.table, vco, MeshOctree.offs, MeshOctree.div, a+1);
924                         }
925                 }
926         }
927         else if(mode=='e') { /* end table */
928                 if(MeshOctree.table) {
929                         int a;
930                         
931                         for(a=0, bt=MeshOctree.table; a<MOC_RES*MOC_RES*MOC_RES; a++, bt++) {
932                                 if(*bt) mesh_octree_free_node(bt);
933                         }
934                         MEM_freeN(MeshOctree.table);
935                         MeshOctree.table= NULL;
936                 }
937                 if(MeshOctree.orco) {
938                         MEM_freeN(MeshOctree.orco);
939                         MeshOctree.orco= NULL;
940                 }
941         }
942         return 0;
943 }
944
945 int mesh_get_x_mirror_vert(Object *ob, int index)
946 {
947         Mesh *me= ob->data;
948         MVert *mvert;
949         float vec[3];
950         
951         if(MeshOctree.orco) {
952                 float *loc= MeshOctree.orcoloc;
953
954                 vec[0]= -(MeshOctree.orco[index][0] + loc[0]) - loc[0];
955                 vec[1]= MeshOctree.orco[index][1];
956                 vec[2]= MeshOctree.orco[index][2];
957         }
958         else {
959                 mvert= me->mvert+index;
960                 vec[0]= -mvert->co[0];
961                 vec[1]= mvert->co[1];
962                 vec[2]= mvert->co[2];
963         }
964         
965         return mesh_octree_table(ob, NULL, vec, 'u');
966 }
967
968 EditVert *editmesh_get_x_mirror_vert(Object *ob, EditMesh *em, float *co)
969 {
970         float vec[3];
971         intptr_t poinval;
972         
973         /* ignore nan verts */
974         if (!finite(co[0]) ||
975                 !finite(co[1]) ||
976                 !finite(co[2])
977            )
978                 return NULL;
979         
980         vec[0]= -co[0];
981         vec[1]= co[1];
982         vec[2]= co[2];
983         
984         poinval= mesh_octree_table(ob, em, vec, 'u');
985         if(poinval != -1)
986                 return (EditVert *)(poinval);
987         return NULL;
988 }
989
990 static unsigned int mirror_facehash(void *ptr)
991 {
992         MFace *mf= ptr;
993         int v0, v1;
994
995         if(mf->v4) {
996                 v0= MIN4(mf->v1, mf->v2, mf->v3, mf->v4);
997                 v1= MAX4(mf->v1, mf->v2, mf->v3, mf->v4);
998         }
999         else {
1000                 v0= MIN3(mf->v1, mf->v2, mf->v3);
1001                 v1= MAX3(mf->v1, mf->v2, mf->v3);
1002         }
1003
1004         return ((v0*39)^(v1*31));
1005 }
1006
1007 static int mirror_facerotation(MFace *a, MFace *b)
1008 {
1009         if(b->v4) {
1010                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3 && a->v4==b->v4)
1011                         return 0;
1012                 else if(a->v4==b->v1 && a->v1==b->v2 && a->v2==b->v3 && a->v3==b->v4)
1013                         return 1;
1014                 else if(a->v3==b->v1 && a->v4==b->v2 && a->v1==b->v3 && a->v2==b->v4)
1015                         return 2;
1016                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v4==b->v3 && a->v1==b->v4)
1017                         return 3;
1018         }
1019         else {
1020                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3)
1021                         return 0;
1022                 else if(a->v3==b->v1 && a->v1==b->v2 && a->v2==b->v3)
1023                         return 1;
1024                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v1==b->v3)
1025                         return 2;
1026         }
1027         
1028         return -1;
1029 }
1030
1031 static int mirror_facecmp(void *a, void *b)
1032 {
1033         return (mirror_facerotation((MFace*)a, (MFace*)b) == -1);
1034 }
1035
1036 int *mesh_get_x_mirror_faces(Object *ob, EditMesh *em)
1037 {
1038         Mesh *me= ob->data;
1039         MVert *mv, *mvert= me->mvert;
1040         MFace mirrormf, *mf, *hashmf, *mface= me->mface;
1041         GHash *fhash;
1042         int *mirrorverts, *mirrorfaces;
1043         int a;
1044
1045         mirrorverts= MEM_callocN(sizeof(int)*me->totvert, "MirrorVerts");
1046         mirrorfaces= MEM_callocN(sizeof(int)*2*me->totface, "MirrorFaces");
1047
1048         mesh_octree_table(ob, em, NULL, 's');
1049
1050         for(a=0, mv=mvert; a<me->totvert; a++, mv++)
1051                 mirrorverts[a]= mesh_get_x_mirror_vert(ob, a);
1052
1053         mesh_octree_table(ob, em, NULL, 'e');
1054
1055         fhash= BLI_ghash_new(mirror_facehash, mirror_facecmp);
1056         for(a=0, mf=mface; a<me->totface; a++, mf++)
1057                 BLI_ghash_insert(fhash, mf, mf);
1058
1059         for(a=0, mf=mface; a<me->totface; a++, mf++) {
1060                 mirrormf.v1= mirrorverts[mf->v3];
1061                 mirrormf.v2= mirrorverts[mf->v2];
1062                 mirrormf.v3= mirrorverts[mf->v1];
1063                 mirrormf.v4= (mf->v4)? mirrorverts[mf->v4]: 0;
1064
1065                 /* make sure v4 is not 0 if a quad */
1066                 if(mf->v4 && mirrormf.v4==0) {
1067                         SWAP(int, mirrormf.v1, mirrormf.v3);
1068                         SWAP(int, mirrormf.v2, mirrormf.v4);
1069                 }
1070
1071                 hashmf= BLI_ghash_lookup(fhash, &mirrormf);
1072                 if(hashmf) {
1073                         mirrorfaces[a*2]= hashmf - mface;
1074                         mirrorfaces[a*2+1]= mirror_facerotation(&mirrormf, hashmf);
1075                 }
1076                 else
1077                         mirrorfaces[a*2]= -1;
1078         }
1079
1080         BLI_ghash_free(fhash, NULL, NULL);
1081         MEM_freeN(mirrorverts);
1082         
1083         return mirrorfaces;
1084 }
1085
1086 /* ****************** render BAKING ********************** */
1087
1088 /* threaded break test */
1089 static int thread_break(void *unused)
1090 {
1091         return G.afbreek;
1092 }
1093
1094 static ScrArea *biggest_image_area(bScreen *screen)
1095 {
1096         ScrArea *sa, *big= NULL;
1097         int size, maxsize= 0;
1098         
1099         for(sa= screen->areabase.first; sa; sa= sa->next) {
1100                 if(sa->spacetype==SPACE_IMAGE) {
1101                         size= sa->winx*sa->winy;
1102                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
1103                                 maxsize= size;
1104                                 big= sa;
1105                         }
1106                 }
1107         }
1108         return big;
1109 }
1110
1111
1112 typedef struct BakeRender {
1113         Render *re;
1114         struct Object *actob;
1115         int event, tot, ready;
1116 } BakeRender;
1117
1118 static void *do_bake_render(void *bake_v)
1119 {
1120         BakeRender *bkr= bake_v;
1121         
1122         bkr->tot= RE_bake_shade_all_selected(bkr->re, bkr->event, bkr->actob);
1123         bkr->ready= 1;
1124         
1125         return NULL;
1126 }
1127
1128
1129 void objects_bake_render(Scene *scene, short event, char **error_msg)
1130 {
1131         Object *actob= OBACT;
1132         int active= scene->r.bake_flag & R_BAKE_TO_ACTIVE;
1133         short prev_r_raytrace= 0, prev_wo_amb_occ= 0;
1134         
1135         if(event==0) event= scene->r.bake_mode;
1136         
1137         if(scene->r.renderer!=R_INTERN) {        
1138                 *error_msg = "Bake only supported for Internal Renderer";
1139                 return;
1140         }        
1141         
1142         if(active && !actob) {
1143                 *error_msg = "No active object";
1144                 return;
1145         }
1146         
1147         if(event>0) {
1148                 bScreen *screen= NULL; // XXX CTX
1149                 Render *re= RE_NewRender("_Bake View_");
1150                 ScrArea *area= biggest_image_area(screen);
1151                 ListBase threads;
1152                 BakeRender bkr;
1153                 int timer=0, tot; // XXX, sculptmode= G.f & G_SCULPTMODE;
1154
1155 // XXX          if(sculptmode) set_sculptmode();
1156                 
1157                 if(event==1) event= RE_BAKE_ALL;
1158                 else if(event==2) event= RE_BAKE_AO;
1159                 else if(event==3) event= RE_BAKE_NORMALS;
1160                 else if(event==4) event= RE_BAKE_TEXTURE;
1161                 else if(event==5) event= RE_BAKE_DISPLACEMENT;
1162                 else event= RE_BAKE_SHADOW;
1163
1164                 if(event==RE_BAKE_AO) {
1165                         if(scene->world==NULL) {
1166                                 *error_msg = "No world set up";
1167                                 return;
1168                         }
1169
1170                         /* If raytracing or AO is disabled, switch it on temporarily for baking. */
1171                         prev_wo_amb_occ = (scene->world->mode & WO_AMB_OCC) != 0;
1172                         scene->world->mode |= WO_AMB_OCC;
1173                 }
1174                 if(event==RE_BAKE_AO || active) {
1175                         prev_r_raytrace = (scene->r.mode & R_RAYTRACE) != 0;
1176                         scene->r.mode |= R_RAYTRACE;
1177                 }
1178                 
1179                 waitcursor(1);
1180                 RE_test_break_cb(re, NULL, thread_break);
1181                 G.afbreek= 0;   /* blender_test_break uses this global */
1182                 
1183                 RE_Database_Baking(re, scene, event, (active)? actob: NULL);
1184                 
1185                 /* baking itself is threaded, cannot use test_break in threads. we also update optional imagewindow */
1186         
1187                 BLI_init_threads(&threads, do_bake_render, 1);
1188                 bkr.re= re;
1189                 bkr.event= event;
1190                 bkr.ready= 0;
1191                 bkr.actob= (active)? actob: NULL;
1192                 BLI_insert_thread(&threads, &bkr);
1193                 
1194                 while(bkr.ready==0) {
1195                         PIL_sleep_ms(50);
1196                         if(bkr.ready)
1197                                 break;
1198                         
1199                         if (!G.background) {
1200                                 blender_test_break();
1201                                 
1202                                 timer++;
1203                                 if(area && timer==20) {
1204                                         Image *ima= RE_bake_shade_get_image();
1205                                         if(ima) ((SpaceImage *)area->spacedata.first)->image= ima;
1206 // XX                                   scrarea_do_windraw(area);
1207 //                                      myswapbuffers();        
1208                                         timer= 0;
1209                                 }
1210                         }
1211                 }
1212                 BLI_end_threads(&threads);
1213                 tot= bkr.tot;
1214                 
1215                 RE_Database_Free(re);
1216                 waitcursor(0);
1217                 
1218                 if(tot==0) *error_msg = "No Images found to bake to";
1219                 else {
1220                         Image *ima;
1221                         /* force OpenGL reload and mipmap recalc */
1222                         for(ima= G.main->image.first; ima; ima= ima->id.next) {
1223                                 if(ima->ok==IMA_OK_LOADED) {
1224                                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1225                                         if(ibuf && (ibuf->userflags & IB_BITMAPDIRTY)) {
1226                                                 GPU_free_image(ima); 
1227                                                 imb_freemipmapImBuf(ibuf);
1228                                         }
1229                                 }
1230                         }
1231                 }
1232                 
1233                 /* restore raytrace and AO */
1234                 if(event==RE_BAKE_AO)
1235                         if(prev_wo_amb_occ == 0)
1236                                 scene->world->mode &= ~WO_AMB_OCC;
1237
1238                 if(event==RE_BAKE_AO || active)
1239                         if(prev_r_raytrace == 0)
1240                                 scene->r.mode &= ~R_RAYTRACE;
1241                 
1242 // XXX          if(sculptmode) set_sculptmode();
1243                 
1244         }
1245 }
1246
1247 /* all selected meshes with UV maps are rendered for current scene visibility */
1248 static void objects_bake_render_ui(Scene *scene, short event)
1249 {
1250         char *error_msg = NULL;
1251 //      int is_editmode = (obedit!=NULL);
1252         
1253         /* Deal with editmode, this is a bit clunky but since UV's are in editmode, users are likely to bake from their */
1254 // XXX  if (is_editmode) exit_editmode(0);
1255         
1256         objects_bake_render(scene, event, &error_msg);
1257         
1258 // XXX  if (is_editmode) enter_editmode(0);
1259         
1260         if (error_msg)
1261                 error(error_msg);
1262 }
1263
1264 void objects_bake_render_menu(Scene *scene)
1265 {
1266         short event;
1267         
1268         event= pupmenu("Bake Selected Meshes %t|Full Render %x1|Ambient Occlusion %x2|Normals %x3|Texture Only %x4|Displacement %x5|Shadow %x6");
1269         if (event < 1) return;
1270         objects_bake_render_ui(scene, event);
1271 }
1272