Render Baking candy: while baking, the UV Image window shows the progress
[blender.git] / source / blender / src / meshtools.c
1 /**
2  * $Id: 
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2004 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 /*
34
35 meshtools.c: no editmode, tools operating on meshes
36
37 int join_mesh(void);
38
39 void fasterdraw(void);
40 void slowerdraw(void);
41
42 void sort_faces(void);
43
44 */
45
46 #include <stdlib.h>
47 #include <string.h>
48 #include <math.h>
49
50 #ifdef HAVE_CONFIG_H
51 #include <config.h>
52 #endif
53
54 #include "MEM_guardedalloc.h"
55
56 #include "DNA_image_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meshdata_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_material_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_screen_types.h"
63 #include "DNA_space_types.h"
64 #include "DNA_view3d_types.h"
65 #include "DNA_world_types.h"
66
67 #include "BLI_blenlib.h"
68 #include "BLI_arithb.h"
69
70 #include "BKE_depsgraph.h"
71 #include "BKE_customdata.h"
72 #include "BKE_global.h"
73 #include "BKE_library.h"
74 #include "BKE_main.h"
75 #include "BKE_mesh.h"
76 #include "BKE_material.h"
77 #include "BKE_object.h"
78 #include "BKE_utildefines.h"
79
80 #include "BIF_editmesh.h"
81 #include "BIF_graphics.h"
82 #include "BIF_interface.h"
83 #include "BIF_mywindow.h"
84 #include "BIF_screen.h"
85 #include "BIF_space.h"
86 #include "BIF_toolbox.h"
87 #include "BIF_editconstraint.h"
88
89 #include "BDR_drawmesh.h" 
90 #include "BDR_editobject.h" 
91 #include "BDR_editface.h" 
92
93 #include "BLI_editVert.h"
94 #include "BLI_threads.h"
95
96 #include "mydevice.h"
97 #include "blendef.h"
98
99 #include "BIF_meshtools.h" /* include ourself for prototypes */
100
101 #include "RE_pipeline.h"
102 #include "RE_shader_ext.h"
103
104 #include "PIL_time.h"
105
106 #include "IMB_imbuf_types.h"
107
108 /* * ********************** no editmode!!! *********** */
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 int join_mesh(void)
113 {
114         Base *base, *nextb;
115         Object *ob;
116         Material **matar, *ma;
117         Mesh *me;
118         MVert *mvert, *mvertmain;
119         MEdge *medge = NULL, *medgemain;
120         MFace *mface = NULL, *mfacemain;
121         float imat[4][4], cmat[4][4];
122         int a, b, totcol, totedge=0, totvert=0, totface=0, ok=0, vertofs, map[MAXMAT];
123         int     i, j, index, haskey=0, edgeofs, faceofs;
124         bDeformGroup *dg, *odg;
125         MDeformVert *dvert;
126         CustomData vdata, edata, fdata;
127
128         if(G.obedit) return 0;
129         
130         ob= OBACT;
131         if(!ob || ob->type!=OB_MESH) return 0;
132
133 #ifdef WITH_VERSE
134         /* it isn't allowed to join shared object at verse server
135          * this function will be implemented as soon as possible */
136         base= FIRSTBASE;
137         while(base) {
138                 if TESTBASELIB(base) {
139                         if(base->object->type==OB_MESH) {
140                                 if(base->object->vnode) {
141                                         haskey= 1;
142                                         break;
143                                 }
144                         }
145                 }
146                 base= base->next;
147         }
148         if(haskey) {
149                 error("Can't join meshes shared at verse server");
150                 return 0;
151         }
152 #endif
153
154         /* count */
155         base= FIRSTBASE;
156         while(base) {
157                 if TESTBASELIB(base) {
158                         if(base->object->type==OB_MESH) {
159                                 me= base->object->data;
160                                 totvert+= me->totvert;
161                                 totface+= me->totface;
162
163                                 if(base->object == ob) ok= 1;
164
165                                 if(me->key) {
166                                         haskey= 1;
167                                         break;
168                                 }
169                         }
170                 }
171                 base= base->next;
172         }
173         
174         if(haskey) {
175                 error("Can't join meshes with vertex keys");
176                 return 0;
177         }
178         /* that way the active object is always selected */ 
179         if(ok==0) return 0;
180         
181         if(totvert==0 || totvert>MESH_MAX_VERTS) return 0;
182         
183
184
185         /* if needed add edges to other meshes */
186         for(base= FIRSTBASE; base; base= base->next) {
187                 if TESTBASELIB(base) {
188                         if(base->object->type==OB_MESH) {
189                                 me= base->object->data;
190                                 totedge += me->totedge;
191                         }
192                 }
193         }
194         
195         /* new material indices and material array */
196         matar= MEM_callocN(sizeof(void *)*MAXMAT, "join_mesh");
197         totcol= ob->totcol;
198         
199         /* obact materials in new main array, is nicer start! */
200         for(a=1; a<=ob->totcol; a++) {
201                 matar[a-1]= give_current_material(ob, a);
202                 id_us_plus((ID *)matar[a-1]);
203                 /* increase id->us : will be lowered later */
204         }
205         
206         base= FIRSTBASE;
207         while(base) {
208                 if TESTBASELIB(base) {
209                         if(ob!=base->object && base->object->type==OB_MESH) {
210                                 me= base->object->data;
211
212                                 // Join this object's vertex groups to the base one's
213                                 for (dg=base->object->defbase.first; dg; dg=dg->next){
214                                         /* See if this group exists in the object */
215                                         for (odg=ob->defbase.first; odg; odg=odg->next){
216                                                 if (!strcmp(odg->name, dg->name)){
217                                                         break;
218                                                 }
219                                         }
220                                         if (!odg){
221                                                 odg = MEM_callocN (sizeof(bDeformGroup), "join deformGroup");
222                                                 memcpy (odg, dg, sizeof(bDeformGroup));
223                                                 BLI_addtail(&ob->defbase, odg);
224                                         }
225
226                                 }
227                                 if (ob->defbase.first && ob->actdef==0)
228                                         ob->actdef=1;
229
230                                 if(me->totvert) {
231                                         for(a=1; a<=base->object->totcol; a++) {
232                                                 ma= give_current_material(base->object, a);
233                                                 if(ma) {
234                                                         for(b=0; b<totcol; b++) {
235                                                                 if(ma == matar[b]) break;
236                                                         }
237                                                         if(b==totcol) {
238                                                                 matar[b]= ma;
239                                                                 ma->id.us++;
240                                                                 totcol++;
241                                                         }
242                                                         if(totcol>=MAXMAT-1) break;
243                                                 }
244                                         }
245                                 }
246                         }
247                         if(totcol>=MAXMAT-1) break;
248                 }
249                 base= base->next;
250         }
251
252         me= ob->data;
253
254         memset(&vdata, 0, sizeof(vdata));
255         memset(&edata, 0, sizeof(edata));
256         memset(&fdata, 0, sizeof(fdata));
257         
258         mvertmain= mvert= CustomData_add_layer(&vdata, CD_MVERT, 0, NULL, totvert);
259         medgemain= medge= CustomData_add_layer(&edata, CD_MEDGE, 0, NULL, totedge);
260         mfacemain= mface= CustomData_add_layer(&fdata, CD_MFACE, 0, NULL, totface);
261
262
263         /* inverse transorm all selected meshes in this object */
264         Mat4Invert(imat, ob->obmat);
265         
266         vertofs= 0;
267         edgeofs= 0;
268         faceofs= 0;
269         base= FIRSTBASE;
270         while(base) {
271                 nextb= base->next;
272                 if TESTBASELIB(base) {
273                         if(base->object->type==OB_MESH) {
274                                 
275                                 me= base->object->data;
276                                 
277                                 if(me->totvert) {
278                                         CustomData_merge(&me->vdata, &vdata, CD_MASK_MESH, CD_DEFAULT, totvert);
279                                         CustomData_copy_data(&me->vdata, &vdata, 0, vertofs, me->totvert);
280                                         
281                                         dvert= CustomData_get(&vdata, vertofs, CD_MDEFORMVERT);
282
283                                         /* NEW VERSION */
284                                         if (dvert){
285                                                 for (i=0; i<me->totvert; i++){
286                                                         for (j=0; j<dvert[i].totweight; j++){
287                                                                 //      Find the old vertex group
288                                                                 odg = BLI_findlink (&base->object->defbase, dvert[i].dw[j].def_nr);
289                                                                 if(odg) {
290                                                                         //      Search for a match in the new object
291                                                                         for (dg=ob->defbase.first, index=0; dg; dg=dg->next, index++){
292                                                                                 if (!strcmp(dg->name, odg->name)){
293                                                                                         dvert[i].dw[j].def_nr = index;
294                                                                                         break;
295                                                                                 }
296                                                                         }
297                                                                 }
298                                                         }
299                                                 }
300                                         }
301
302                                         if(base->object != ob) {
303                                                 /* watch this: switch matmul order really goes wrong */
304                                                 Mat4MulMat4(cmat, base->object->obmat, imat);
305                                                 
306                                                 a= me->totvert;
307                                                 while(a--) {
308                                                         Mat4MulVecfl(cmat, mvert->co);
309                                                         mvert++;
310                                                 }
311                                         }
312                                         else mvert+= me->totvert;
313                                 }
314                                 if(me->totface) {
315                                 
316                                         /* make mapping for materials */
317                                         memset(map, 0, 4*MAXMAT);
318                                         for(a=1; a<=base->object->totcol; a++) {
319                                                 ma= give_current_material(base->object, a);
320                                                 if(ma) {
321                                                         for(b=0; b<totcol; b++) {
322                                                                 if(ma == matar[b]) {
323                                                                         map[a-1]= b;
324                                                                         break;
325                                                                 }
326                                                         }
327                                                 }
328                                         }
329
330                                         CustomData_merge(&me->fdata, &fdata, CD_MASK_MESH, CD_DEFAULT, totface);
331                                         CustomData_copy_data(&me->fdata, &fdata, 0, faceofs, me->totface);
332
333                                         for(a=0; a<me->totface; a++, mface++) {
334                                                 mface->v1+= vertofs;
335                                                 mface->v2+= vertofs;
336                                                 mface->v3+= vertofs;
337                                                 if(mface->v4) mface->v4+= vertofs;
338                                                 
339                                                 mface->mat_nr= map[(int)mface->mat_nr];
340                                         }
341
342                                         faceofs += me->totface;
343                                 }
344                                 
345                                 if(me->totedge) {
346                                         CustomData_merge(&me->edata, &edata, CD_MASK_MESH, CD_DEFAULT, totedge);
347                                         CustomData_copy_data(&me->edata, &edata, 0, edgeofs, me->totedge);
348
349                                         for(a=0; a<me->totedge; a++, medge++) {
350                                                 medge->v1+= vertofs;
351                                                 medge->v2+= vertofs;
352                                         }
353
354                                         edgeofs += me->totedge;
355                                 }
356                                 
357                                 vertofs += me->totvert;
358                                 
359                                 if(base->object!=ob)
360                                         free_and_unlink_base(base);
361                         }
362                 }
363                 base= nextb;
364         }
365         
366         me= ob->data;
367         
368         CustomData_free(&me->vdata, me->totvert);
369         CustomData_free(&me->edata, me->totedge);
370         CustomData_free(&me->fdata, me->totface);
371
372         me->totvert= totvert;
373         me->totedge= totedge;
374         me->totface= totface;
375         
376         me->vdata= vdata;
377         me->edata= edata;
378         me->fdata= fdata;
379
380         mesh_update_customdata_pointers(me);
381         
382         /* old material array */
383         for(a=1; a<=ob->totcol; a++) {
384                 ma= ob->mat[a-1];
385                 if(ma) ma->id.us--;
386         }
387         for(a=1; a<=me->totcol; a++) {
388                 ma= me->mat[a-1];
389                 if(ma) ma->id.us--;
390         }
391         if(ob->mat) MEM_freeN(ob->mat);
392         if(me->mat) MEM_freeN(me->mat);
393         ob->mat= me->mat= 0;
394         
395         if(totcol) {
396                 me->mat= matar;
397                 ob->mat= MEM_callocN(sizeof(void *)*totcol, "join obmatar");
398         }
399         else MEM_freeN(matar);
400         
401         ob->totcol= me->totcol= totcol;
402         ob->colbits= 0;
403         
404         /* other mesh users */
405         test_object_materials((ID *)me);
406         
407         DAG_scene_sort(G.scene);        // removed objects, need to rebuild dag before editmode call
408         
409         enter_editmode(EM_WAITCURSOR);
410         exit_editmode(EM_FREEDATA|EM_WAITCURSOR);       // freedata, but no undo
411         
412         allqueue(REDRAWVIEW3D, 0);
413         allqueue(REDRAWBUTSSHADING, 0);
414
415         BIF_undo_push("Join Mesh");
416         return 1;
417 }
418
419
420 void fasterdraw(void)
421 {
422         Base *base;
423         Mesh *me;
424         int toggle, a;
425
426         if(G.obedit || G.vd==NULL) return;
427
428         /* reset flags */
429         me= G.main->mesh.first;
430         while(me) {
431                 me->flag &= ~ME_ISDONE;
432                 me= me->id.next;
433         }
434
435         base= FIRSTBASE;
436         while(base) {
437                 if( TESTBASELIB(base) && (base->object->type==OB_MESH)) {
438                         me= base->object->data;
439                         if(me->id.lib==0 && (me->flag & ME_ISDONE)==0) {
440                                 me->flag |= ME_ISDONE;
441                                 toggle= 0;
442                                 for(a=0; a<me->totedge; a++) {
443                                         MEdge *med = &me->medge[a];
444
445                                         if( (med->flag & ME_EDGEDRAW) && !( (toggle++) & 3) ) {
446                                                 med->flag ^= ME_EDGEDRAW;
447                                         }
448                                 }
449                         }
450                 }
451                 base= base->next;
452         }
453
454         /* important?: reset flags again */
455         me= G.main->mesh.first;
456         while(me) {
457                 me->flag &= ~ME_ISDONE;
458                 me= me->id.next;
459         }
460
461         allqueue(REDRAWVIEW3D, 0);
462 }
463
464 void slowerdraw(void)           /* reset fasterdraw */
465 {
466         Base *base;
467         Mesh *me;
468         int a;
469
470         if(G.obedit || G.vd==NULL) return;
471
472         base= FIRSTBASE;
473         while(base) {
474                 if( TESTBASELIB(base) && (base->object->type==OB_MESH)) {
475                         me= base->object->data;
476                         if(me->id.lib==0) {
477                                 for(a=0; a<me->totedge; a++) {
478                                         me->medge[a].flag |= ME_EDGEDRAW;
479                                 }
480                         }
481                 }
482                 base= base->next;
483         }
484
485         allqueue(REDRAWVIEW3D, 0);
486 }
487
488 /* ********************** SORT FACES ******************* */
489
490 static void permutate(void *list, int num, int size, int *index)
491 {
492         void *buf;
493         int len;
494         int i;
495
496         len = num * size;
497
498         buf = MEM_mallocN(len, "permutate");
499         memcpy(buf, list, len);
500         
501         for (i = 0; i < num; i++) {
502                 memcpy((char *)list + (i * size), (char *)buf + (index[i] * size), size);
503         }
504         MEM_freeN(buf);
505 }
506
507 static MVert *mvertbase;
508 static MFace *mfacebase;
509
510 static int verg_mface(const void *v1, const void *v2)
511 {
512         MFace *x1, *x2;
513
514         MVert *ve1, *ve2;
515         int i1, i2;
516
517         i1 = ((int *) v1)[0];
518         i2 = ((int *) v2)[0];
519         
520         x1 = mfacebase + i1;
521         x2 = mfacebase + i2;
522
523         ve1= mvertbase+x1->v1;
524         ve2= mvertbase+x2->v1;
525         
526         if( ve1->co[2] > ve2->co[2] ) return 1;
527         else if( ve1->co[2] < ve2->co[2]) return -1;
528         return 0;
529 }
530
531
532 void sort_faces(void)
533 {
534         Object *ob= OBACT;
535         Mesh *me;
536         CustomDataLayer *layer;
537         int i, *index;
538         
539         if(ob==0) return;
540         if(G.obedit) return;
541         if(ob->type!=OB_MESH) return;
542         
543         if(okee("Sort faces in Z axis")==0) return;
544         me= ob->data;
545         if(me->totface==0) return;
546
547 /*      create index list */
548         index = (int *) MEM_mallocN(sizeof(int) * me->totface, "sort faces");
549         for (i = 0; i < me->totface; i++) {
550                 index[i] = i;
551         }
552         mvertbase= me->mvert;
553         mfacebase = me->mface;
554
555 /* sort index list instead of faces itself 
556    and apply this permutation to all face layers */
557         qsort(index, me->totface, sizeof(int), verg_mface);
558
559         for(i = 0; i < me->fdata.totlayer; i++) {
560                 layer = &me->fdata.layers[i];
561                 permutate(layer->data, me->totface, CustomData_sizeof(layer->type), index);
562         }
563
564         MEM_freeN(index);
565
566         allqueue(REDRAWVIEW3D, 0);
567         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
568 }
569
570 /* ********************* MESH VERTEX OCTREE LOOKUP ************* */
571
572 /* important note; this is unfinished, needs better API for editmode, and custom threshold */
573
574 #define MOC_RES                 8
575 #define MOC_NODE_RES    8
576 #define MOC_THRESH              0.0002f
577
578 typedef struct MocNode {
579         struct MocNode *next;
580         long index[MOC_NODE_RES];
581 } MocNode;
582
583 static int mesh_octree_get_base_offs(float *co, float *offs, float *div)
584 {
585         int vx, vy, vz;
586         
587         vx= floor( (co[0]-offs[0])/div[0] );
588         vy= floor( (co[1]-offs[1])/div[1] );
589         vz= floor( (co[2]-offs[2])/div[2] );
590         
591         CLAMP(vx, 0, MOC_RES-1);
592         CLAMP(vy, 0, MOC_RES-1);
593         CLAMP(vz, 0, MOC_RES-1);
594
595         return (vx*MOC_RES*MOC_RES) + vy*MOC_RES + vz;
596 }
597
598 static void mesh_octree_add_node(MocNode **bt, long index)
599 {
600         if(*bt==NULL) {
601                 *bt= MEM_callocN(sizeof(MocNode), "MocNode");
602                 (*bt)->index[0]= index;
603         }
604         else {
605                 int a;
606                 for(a=0; a<MOC_NODE_RES; a++) {
607                         if((*bt)->index[a]==index)
608                                 return;
609                         else if((*bt)->index[a]==0) {
610                                 (*bt)->index[a]= index;
611                                 return;
612                         }
613                 }
614                 mesh_octree_add_node(&(*bt)->next, index);
615         }
616 }
617
618 static void mesh_octree_free_node(MocNode **bt)
619 {
620         if( (*bt)->next ) {
621                 mesh_octree_free_node(&(*bt)->next);
622         }
623         MEM_freeN(*bt);
624 }
625
626
627 /* temporal define, just to make nicer code below */
628 #define MOC_ADDNODE(vx, vy, vz) mesh_octree_add_node(basetable + ((vx)*MOC_RES*MOC_RES) + (vy)*MOC_RES + (vz), index)
629
630 static void mesh_octree_add_nodes(MocNode **basetable, float *co, float *offs, float *div, long index)
631 {
632         float fx, fy, fz;
633         int vx, vy, vz;
634         
635         fx= (co[0]-offs[0])/div[0];
636         fy= (co[1]-offs[1])/div[1];
637         fz= (co[2]-offs[2])/div[2];
638         CLAMP(fx, 0.0f, MOC_RES-MOC_THRESH);
639         CLAMP(fy, 0.0f, MOC_RES-MOC_THRESH);
640         CLAMP(fz, 0.0f, MOC_RES-MOC_THRESH);
641         
642         vx= floor(fx);
643         vy= floor(fy);
644         vz= floor(fz);
645         
646         MOC_ADDNODE(vx, vy, vz);
647         
648         if( vx>0 )
649                 if( fx-((float)vx)-MOC_THRESH < 0.0f)
650                         MOC_ADDNODE(vx-1, vy, vz);
651         if( vx<MOC_RES-2 )
652                 if( fx-((float)vx)+MOC_THRESH > 1.0f)
653                         MOC_ADDNODE(vx+1, vy, vz);
654
655         if( vy>0 )
656                 if( fy-((float)vy)-MOC_THRESH < 0.0f) 
657                         MOC_ADDNODE(vx, vy-1, vz);
658         if( vy<MOC_RES-2 )
659                 if( fy-((float)vy)+MOC_THRESH > 1.0f) 
660                         MOC_ADDNODE(vx, vy+1, vz);
661
662         if( vz>0 )
663                 if( fz-((float)vz)-MOC_THRESH < 0.0f) 
664                         MOC_ADDNODE(vx, vy, vz-1);
665         if( vz<MOC_RES-2 )
666                 if( fz-((float)vz)+MOC_THRESH > 1.0f) 
667                         MOC_ADDNODE(vx, vy, vz+1);
668         
669 }
670
671 static long mesh_octree_find_index(MocNode **bt, MVert *mvert, float *co)
672 {
673         float *vec;
674         int a;
675         
676         if(*bt==NULL)
677                 return -1;
678         
679         for(a=0; a<MOC_NODE_RES; a++) {
680                 if((*bt)->index[a]) {
681                         /* does mesh verts and editmode, code looks potential dangerous, octree should really be filled OK! */
682                         if(mvert) {
683                                 vec= (mvert+(*bt)->index[a]-1)->co;
684                                 if(FloatCompare(vec, co, MOC_THRESH))
685                                         return (*bt)->index[a]-1;
686                         }
687                         else {
688                                 EditVert *eve= (EditVert *)((*bt)->index[a]);
689                                 if(FloatCompare(eve->co, co, MOC_THRESH))
690                                         return (*bt)->index[a];
691                         }
692                 }
693                 else return -1;
694         }
695         if( (*bt)->next)
696                 return mesh_octree_find_index(&(*bt)->next, mvert, co);
697         
698         return -1;
699 }
700
701
702 /* mode is 's' start, or 'e' end, or 'u' use */
703 /* if end, ob can be NULL */
704 long mesh_octree_table(Object *ob, float *co, char mode)
705 {
706         MocNode **bt;
707         static MocNode **basetable= NULL;
708         static float offs[3], div[3];
709         
710         if(mode=='u') {         /* use table */
711                 if(basetable==NULL)
712                         mesh_octree_table(ob, NULL, 's');
713            
714                 if(basetable) {
715                         Mesh *me= ob->data;
716                         bt= basetable + mesh_octree_get_base_offs(co, offs, div);
717                         if(ob==G.obedit)
718                                 return mesh_octree_find_index(bt, NULL, co);
719                         else
720                                 return mesh_octree_find_index(bt, me->mvert, co);
721                 }
722                 return -1;
723         }
724         else if(mode=='s') {    /* start table */
725                 Mesh *me= ob->data;
726                 BoundBox *bb = mesh_get_bb(me);
727                 
728                 /* for quick unit coordinate calculus */
729                 VECCOPY(offs, bb->vec[0]);
730                 offs[0]-= MOC_THRESH;           /* we offset it 1 threshold unit extra */
731                 offs[1]-= MOC_THRESH;
732                 offs[2]-= MOC_THRESH;
733                         
734                 VecSubf(div, bb->vec[6], bb->vec[0]);
735                 div[0]+= 2*MOC_THRESH;          /* and divide with 2 threshold unit more extra (try 8x8 unit grid on paint) */
736                 div[1]+= 2*MOC_THRESH;
737                 div[2]+= 2*MOC_THRESH;
738                 
739                 VecMulf(div, 1.0f/MOC_RES);
740                 if(div[0]==0.0f) div[0]= 1.0f;
741                 if(div[1]==0.0f) div[1]= 1.0f;
742                 if(div[2]==0.0f) div[2]= 1.0f;
743                         
744                 if(basetable) /* happens when entering this call without ending it */
745                         mesh_octree_table(ob, co, 'e');
746                 
747                 basetable= MEM_callocN(MOC_RES*MOC_RES*MOC_RES*sizeof(void *), "sym table");
748                 
749                 if(ob==G.obedit) {
750                         EditVert *eve;
751                         
752                         for(eve= G.editMesh->verts.first; eve; eve= eve->next) {
753                                 mesh_octree_add_nodes(basetable, eve->co, offs, div, (long)(eve));
754                         }
755                 }
756                 else {          
757                         MVert *mvert;
758                         long a;
759                         
760                         for(a=1, mvert= me->mvert; a<=me->totvert; a++, mvert++) {
761                                 mesh_octree_add_nodes(basetable, mvert->co, offs, div, a);
762                         }
763                 }
764         }
765         else if(mode=='e') { /* end table */
766                 if(basetable) {
767                         int a;
768                         
769                         for(a=0, bt=basetable; a<MOC_RES*MOC_RES*MOC_RES; a++, bt++) {
770                                 if(*bt) mesh_octree_free_node(bt);
771                         }
772                         MEM_freeN(basetable);
773                         basetable= NULL;
774                 }
775         }
776         return 0;
777 }
778
779 int mesh_get_x_mirror_vert(Object *ob, int index)
780 {
781         Mesh *me= ob->data;
782         MVert *mvert= me->mvert+index;
783         float vec[3];
784         
785         vec[0]= -mvert->co[0];
786         vec[1]= mvert->co[1];
787         vec[2]= mvert->co[2];
788         
789         return mesh_octree_table(ob, vec, 'u');
790 }
791
792 EditVert *editmesh_get_x_mirror_vert(Object *ob, float *co)
793 {
794         float vec[3];
795         long poinval;
796         
797         vec[0]= -co[0];
798         vec[1]= co[1];
799         vec[2]= co[2];
800         
801         poinval= mesh_octree_table(ob, vec, 'u');
802         if(poinval != -1)
803                 return (EditVert *)(poinval);
804         return NULL;
805 }
806
807
808 /* ****************** render BAKING ********************** */
809
810
811 static ScrArea *biggest_image_area(void)
812 {
813         ScrArea *sa, *big= NULL;
814         int size, maxsize= 0;
815         
816         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
817                 if(sa->spacetype==SPACE_IMAGE) {
818                         size= sa->winx*sa->winy;
819                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
820                                 maxsize= size;
821                                 big= sa;
822                         }
823                 }
824         }
825         return big;
826 }
827
828
829 typedef struct BakeRender {
830         Render *re;
831         int event, tot, ready;
832 } BakeRender;
833
834 static void *do_bake_render(void *bake_v)
835 {
836         BakeRender *bkr= bake_v;
837         
838         bkr->tot= RE_bake_shade_all_selected(bkr->re, bkr->event);
839         bkr->ready= 1;
840         
841         return NULL;
842 }
843
844 /* all selected meshes with UV maps are rendered for current scene visibility */
845 void objects_bake_render(void)
846 {
847         short event;
848         
849         event= pupmenu("Bake Selected Meshes %t|Full Render %x1|Ambient Occlusion %x2|Normals %x3|Texture Only %x4");
850         if(event>0) {
851                 Render *re= RE_NewRender("_Bake View_");
852                 ScrArea *area;
853                 int tot;
854                 
855                 if(event==1) event= RE_BAKE_ALL;
856                 else if(event==2) event= RE_BAKE_AO;
857                 else if(event==3) event= RE_BAKE_NORMALS;
858                 else event= RE_BAKE_TEXTURE;
859                 
860                 if(event==RE_BAKE_AO) {
861                         if((G.scene->r.mode & R_RAYTRACE)==0 || G.scene->world==NULL
862                            || (G.scene->world->mode & WO_AMB_OCC)==0) {
863                                 error("No ray-trace or AO set up");
864                                 return;
865                         }
866                 }
867                 
868                 waitcursor(1);
869                 RE_timecursor_cb(re, set_timecursor);
870                 RE_test_break_cb(re, blender_test_break);
871                 G.afbreek= 0;   /* blender_test_break uses this global */
872                 
873                 RE_Database_Baking(re, G.scene, event);
874                 
875                 /* live updates, threaded */
876                 area= biggest_image_area();
877                 if(area) {
878                         ListBase threads;
879                         BakeRender bkr;
880                         int timer;
881                         
882                         BLI_init_threads(&threads, do_bake_render, 1);
883                         bkr.re= re;
884                         bkr.event= event;
885                         bkr.ready= 0;
886                         BLI_insert_thread(&threads, &bkr);
887                         
888                         while(bkr.ready==0) {
889                                 PIL_sleep_ms(50);
890                                 if(bkr.ready)
891                                         break;
892                                 timer++;
893                                 if(timer==20) {
894                                         Image *ima= RE_bake_shade_get_image();
895                                         if(ima) ((SpaceImage *)area->spacedata.first)->image= ima;
896                                         scrarea_do_windraw(area);
897                                         myswapbuffers();        
898                                         timer= 0;
899                                 }
900                         }
901                         BLI_end_threads(&threads);
902                         tot= bkr.tot;
903                 }
904                 else /* no thread bake */ 
905                         tot= RE_bake_shade_all_selected(re, event);
906                 
907                 RE_Database_Free(re);
908                 waitcursor(0);
909                 
910                 if(tot==0) error("No Images found to bake to");
911                 else {
912                         Image *ima;
913                         /* force OpenGL reload */
914                         for(ima= G.main->image.first; ima; ima= ima->id.next)
915                                 if(ima->ibuf->userflags & IB_BITMAPDIRTY)
916                                         free_realtime_image(ima); 
917                 }
918                 
919                 allqueue(REDRAWIMAGE, 0);
920                 allqueue(REDRAWVIEW3D, 0);
921         }
922 }
923
924