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