Cycles: svn merge -r41225:41232 ^/trunk/blender
[blender.git] / source / blender / blenkernel / intern / mball.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Jiri Hnidek <jiri.hnidek@vslib.cz>.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  * MetaBalls are created from a single Object (with a name without number in it),
26  * here the DispList and BoundBox also is located.
27  * All objects with the same name (but with a number in it) are added to this.
28  *
29  * texture coordinates are patched within the displist
30  */
31
32 /** \file blender/blenkernel/intern/mball.c
33  *  \ingroup bke
34  */
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <math.h>
39 #include <stdlib.h>
40 #include <ctype.h>
41 #include <float.h>
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_material_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_meta_types.h"
47 #include "DNA_scene_types.h"
48
49
50 #include "BLI_blenlib.h"
51 #include "BLI_math.h"
52 #include "BLI_utildefines.h"
53
54
55
56 #include "BKE_global.h"
57 #include "BKE_main.h"
58
59 /*  #include "BKE_object.h" */
60 #include "BKE_animsys.h"
61 #include "BKE_scene.h"
62 #include "BKE_library.h"
63 #include "BKE_displist.h"
64 #include "BKE_mball.h"
65 #include "BKE_object.h"
66 #include "BKE_material.h"
67
68 /* Global variables */
69
70 static float thresh= 0.6f;
71 static int totelem=0;
72 static MetaElem **mainb;
73 static octal_tree *metaball_tree = NULL;
74 /* Functions */
75
76 void unlink_mball(MetaBall *mb)
77 {
78         int a;
79         
80         for(a=0; a<mb->totcol; a++) {
81                 if(mb->mat[a]) mb->mat[a]->id.us--;
82                 mb->mat[a]= NULL;
83         }
84 }
85
86
87 /* do not free mball itself */
88 void free_mball(MetaBall *mb)
89 {
90         unlink_mball(mb);       
91         
92         if(mb->adt) {
93                 BKE_free_animdata((ID *)mb);
94                 mb->adt = NULL;
95         }
96         if(mb->mat) MEM_freeN(mb->mat);
97         if(mb->bb) MEM_freeN(mb->bb);
98         BLI_freelistN(&mb->elems);
99         if(mb->disp.first) freedisplist(&mb->disp);
100 }
101
102 MetaBall *add_mball(const char *name)
103 {
104         MetaBall *mb;
105         
106         mb= alloc_libblock(&G.main->mball, ID_MB, name);
107         
108         mb->size[0]= mb->size[1]= mb->size[2]= 1.0;
109         mb->texflag= MB_AUTOSPACE;
110         
111         mb->wiresize= 0.4f;
112         mb->rendersize= 0.2f;
113         mb->thresh= 0.6f;
114         
115         return mb;
116 }
117
118 MetaBall *copy_mball(MetaBall *mb)
119 {
120         MetaBall *mbn;
121         int a;
122         
123         mbn= copy_libblock(mb);
124
125         BLI_duplicatelist(&mbn->elems, &mb->elems);
126         
127         mbn->mat= MEM_dupallocN(mb->mat);
128         for(a=0; a<mbn->totcol; a++) {
129                 id_us_plus((ID *)mbn->mat[a]);
130         }
131         mbn->bb= MEM_dupallocN(mb->bb);
132
133         mbn->editelems= NULL;
134         mbn->lastelem= NULL;
135         
136         return mbn;
137 }
138
139 static void extern_local_mball(MetaBall *mb)
140 {
141         if(mb->mat) {
142                 extern_local_matarar(mb->mat, mb->totcol);
143         }
144 }
145
146 void make_local_mball(MetaBall *mb)
147 {
148         Main *bmain= G.main;
149         Object *ob;
150         int local=0, lib=0;
151
152         /* - only lib users: do nothing
153          * - only local users: set flag
154          * - mixed: make copy
155          */
156         
157         if(mb->id.lib==NULL) return;
158         if(mb->id.us==1) {
159                 mb->id.lib= NULL;
160                 mb->id.flag= LIB_LOCAL;
161                 new_id(&bmain->mball, (ID *)mb, NULL);
162                 extern_local_mball(mb);
163                 
164                 return;
165         }
166
167         for(ob= G.main->object.first; ob && ELEM(0, lib, local); ob= ob->id.next) {
168                 if(ob->data == mb) {
169                         if(ob->id.lib) lib= 1;
170                         else local= 1;
171                 }
172         }
173         
174         if(local && lib==0) {
175                 mb->id.lib= NULL;
176                 mb->id.flag= LIB_LOCAL;
177
178                 new_id(&bmain->mball, (ID *)mb, NULL);
179                 extern_local_mball(mb);
180         }
181         else if(local && lib) {
182                 MetaBall *mbn= copy_mball(mb);
183                 mbn->id.us= 0;
184
185                 for(ob= G.main->object.first; ob; ob= ob->id.next) {
186                         if(ob->data == mb) {
187                                 if(ob->id.lib==NULL) {
188                                         ob->data= mbn;
189                                         mbn->id.us++;
190                                         mb->id.us--;
191                                 }
192                         }
193                 }
194         }
195 }
196
197 /* most simple meta-element adding function
198  * don't do context manipulation here (rna uses) */
199 MetaElem *add_metaball_element(MetaBall *mb, const int type)
200 {
201         MetaElem *ml= MEM_callocN(sizeof(MetaElem), "metaelem");
202
203         unit_qt(ml->quat);
204
205         ml->rad= 2.0;
206         ml->s= 2.0;
207         ml->flag= MB_SCALE_RAD;
208
209         switch(type) {
210         case MB_BALL:
211                 ml->type = MB_BALL;
212                 ml->expx= ml->expy= ml->expz= 1.0;
213
214                 break;
215         case MB_TUBE:
216                 ml->type = MB_TUBE;
217                 ml->expx= ml->expy= ml->expz= 1.0;
218
219                 break;
220         case MB_PLANE:
221                 ml->type = MB_PLANE;
222                 ml->expx= ml->expy= ml->expz= 1.0;
223
224                 break;
225         case MB_ELIPSOID:
226                 ml->type = MB_ELIPSOID;
227                 ml->expx= 1.2f;
228                 ml->expy= 0.8f;
229                 ml->expz= 1.0;
230                 
231                 break;
232         case MB_CUBE:
233                 ml->type = MB_CUBE;
234                 ml->expx= ml->expy= ml->expz= 1.0;
235
236                 break;
237         default:
238                 break;
239         }
240
241         BLI_addtail(&mb->elems, ml);
242
243         return ml;
244 }
245 /** Compute bounding box of all MetaElems/MetaBalls.
246  *
247  * Bounding box is computed from polygonized surface. Object *ob is
248  * basic MetaBall (usually with name Meta). All other MetaBalls (with
249  * names Meta.001, Meta.002, etc) are included in this Bounding Box.
250  */
251 void tex_space_mball(Object *ob)
252 {
253         DispList *dl;
254         BoundBox *bb;
255         float *data, min[3], max[3] /*, loc[3], size[3] */;
256         int tot, doit=0;
257
258         if(ob->bb==NULL) ob->bb= MEM_callocN(sizeof(BoundBox), "mb boundbox");
259         bb= ob->bb;
260         
261         /* Weird one, this. */
262 /*      INIT_MINMAX(min, max); */
263         (min)[0]= (min)[1]= (min)[2]= 1.0e30f;
264         (max)[0]= (max)[1]= (max)[2]= -1.0e30f;
265
266         dl= ob->disp.first;
267         while(dl) {
268                 tot= dl->nr;
269                 if(tot) doit= 1;
270                 data= dl->verts;
271                 while(tot--) {
272                         /* Also weird... but longer. From utildefines. */
273                         DO_MINMAX(data, min, max);
274                         data+= 3;
275                 }
276                 dl= dl->next;
277         }
278
279         if(!doit) {
280                 min[0] = min[1] = min[2] = -1.0f;
281                 max[0] = max[1] = max[2] = 1.0f;
282         }
283         /*
284         loc[0]= (min[0]+max[0])/2.0f;
285         loc[1]= (min[1]+max[1])/2.0f;
286         loc[2]= (min[2]+max[2])/2.0f;
287         
288         size[0]= (max[0]-min[0])/2.0f;
289         size[1]= (max[1]-min[1])/2.0f;
290         size[2]= (max[2]-min[2])/2.0f;
291         */
292         boundbox_set_from_min_max(bb, min, max);
293 }
294
295 float *make_orco_mball(Object *ob, ListBase *dispbase)
296 {
297         BoundBox *bb;
298         DispList *dl;
299         float *data, *orco, *orcodata;
300         float loc[3], size[3];
301         int a;
302
303         /* restore size and loc */
304         bb= ob->bb;
305         loc[0]= (bb->vec[0][0]+bb->vec[4][0])/2.0f;
306         size[0]= bb->vec[4][0]-loc[0];
307         loc[1]= (bb->vec[0][1]+bb->vec[2][1])/2.0f;
308         size[1]= bb->vec[2][1]-loc[1];
309         loc[2]= (bb->vec[0][2]+bb->vec[1][2])/2.0f;
310         size[2]= bb->vec[1][2]-loc[2];
311
312         dl= dispbase->first;
313         orcodata= MEM_mallocN(sizeof(float)*3*dl->nr, "MballOrco");
314
315         data= dl->verts;
316         orco= orcodata;
317         a= dl->nr;
318         while(a--) {
319                 orco[0]= (data[0]-loc[0])/size[0];
320                 orco[1]= (data[1]-loc[1])/size[1];
321                 orco[2]= (data[2]-loc[2])/size[2];
322
323                 data+= 3;
324                 orco+= 3;
325         }
326
327         return orcodata;
328 }
329
330 /* Note on mball basis stuff 2.5x (this is a can of worms)
331  * This really needs a rewrite/refactor its totally broken in anything other then basic cases
332  * Multiple Scenes + Set Scenes & mixing mball basis SHOULD work but fails to update the depsgraph on rename
333  * and linking into scenes or removal of basis mball. so take care when changing this code.
334  * 
335  * Main idiot thing here is that the system returns find_basis_mball() objects which fail a is_basis_mball() test.
336  *
337  * Not only that but the depsgraph and their areas depend on this behavior!, so making small fixes here isn't worth it.
338  * - Campbell
339  */
340
341
342 /** \brief Test, if Object *ob is basic MetaBall.
343  *
344  * It test last character of Object ID name. If last character
345  * is digit it return 0, else it return 1.
346  */
347 int is_basis_mball(Object *ob)
348 {
349         int len;
350         
351         /* just a quick test */
352         len= strlen(ob->id.name);
353         if( isdigit(ob->id.name[len-1]) ) return 0;
354         return 1;
355 }
356
357 /* return nonzero if ob1 is a basis mball for ob */
358 int is_mball_basis_for(Object *ob1, Object *ob2)
359 {
360         int basis1nr, basis2nr;
361         char basis1name[32], basis2name[32];
362
363         BLI_split_name_num(basis1name, &basis1nr, ob1->id.name+2, '.');
364         BLI_split_name_num(basis2name, &basis2nr, ob2->id.name+2, '.');
365
366         if(!strcmp(basis1name, basis2name)) return is_basis_mball(ob1);
367         else return 0;
368 }
369
370 /* \brief copy some properties from object to other metaball object with same base name
371  *
372  * When some properties (wiresize, threshold, update flags) of metaball are changed, then this properties
373  * are copied to all metaballs in same "group" (metaballs with same base name: MBall,
374  * MBall.001, MBall.002, etc). The most important is to copy properties to the base metaball,
375  * because this metaball influence polygonisation of metaballs. */
376 void copy_mball_properties(Scene *scene, Object *active_object)
377 {
378         Scene *sce_iter= scene;
379         Base *base;
380         Object *ob;
381         MetaBall *active_mball = (MetaBall*)active_object->data;
382         int basisnr, obnr;
383         char basisname[32], obname[32];
384         
385         BLI_split_name_num(basisname, &basisnr, active_object->id.name+2, '.');
386
387         /* XXX recursion check, see scene.c, just too simple code this next_object() */
388         if(F_ERROR==next_object(&sce_iter, 0, NULL, NULL))
389                 return;
390         
391         while(next_object(&sce_iter, 1, &base, &ob)) {
392                 if (ob->type==OB_MBALL) {
393                         if(ob!=active_object){
394                                 BLI_split_name_num(obname, &obnr, ob->id.name+2, '.');
395
396                                 /* Object ob has to be in same "group" ... it means, that it has to have
397                                  * same base of its name */
398                                 if(strcmp(obname, basisname)==0){
399                                         MetaBall *mb= ob->data;
400
401                                         /* Copy properties from selected/edited metaball */
402                                         mb->wiresize= active_mball->wiresize;
403                                         mb->rendersize= active_mball->rendersize;
404                                         mb->thresh= active_mball->thresh;
405                                         mb->flag= active_mball->flag;
406                                 }
407                         }
408                 }
409         }
410 }
411
412 /** \brief This function finds basic MetaBall.
413  *
414  * Basic MetaBall doesn't include any number at the end of
415  * its name. All MetaBalls with same base of name can be
416  * blended. MetaBalls with different basic name can't be
417  * blended.
418  *
419  * warning!, is_basis_mball() can fail on returned object, see long note above.
420  */
421 Object *find_basis_mball(Scene *scene, Object *basis)
422 {
423         Scene *sce_iter= scene;
424         Base *base;
425         Object *ob,*bob= basis;
426         MetaElem *ml=NULL;
427         int basisnr, obnr;
428         char basisname[32], obname[32];
429
430         BLI_split_name_num(basisname, &basisnr, basis->id.name+2, '.');
431         totelem= 0;
432
433         /* XXX recursion check, see scene.c, just too simple code this next_object() */
434         if(F_ERROR==next_object(&sce_iter, 0, NULL, NULL))
435                 return NULL;
436         
437         while(next_object(&sce_iter, 1, &base, &ob)) {
438                 
439                 if (ob->type==OB_MBALL) {
440                         if(ob==bob){
441                                 MetaBall *mb= ob->data;
442                                 
443                                 /* if bob object is in edit mode, then dynamic list of all MetaElems
444                                  * is stored in editelems */
445                                 if(mb->editelems) ml= mb->editelems->first;
446                                 /* if bob object is in object mode */
447                                 else ml= mb->elems.first;
448                         }
449                         else{
450                                 BLI_split_name_num(obname, &obnr, ob->id.name+2, '.');
451
452                                 /* object ob has to be in same "group" ... it means, that it has to have
453                                  * same base of its name */
454                                 if(strcmp(obname, basisname)==0){
455                                         MetaBall *mb= ob->data;
456                                         
457                                         /* if object is in edit mode, then dynamic list of all MetaElems
458                                          * is stored in editelems */
459                                         if(mb->editelems) ml= mb->editelems->first;
460                                         /* if bob object is in object mode */
461                                         else ml= mb->elems.first;
462                                         
463                                         if(obnr<basisnr){
464                                                 if(!(ob->flag & OB_FROMDUPLI)){
465                                                         basis= ob;
466                                                         basisnr= obnr;
467                                                 }
468                                         }       
469                                 }
470                         }
471                         
472                         while(ml){
473                                 if(!(ml->flag & MB_HIDE)) totelem++;
474                                 ml= ml->next;
475                         }
476                 }
477         }
478
479         return basis;
480 }
481
482
483 /* ******************** ARITH ************************* */
484
485 /* BASED AT CODE (but mostly rewritten) :
486  * C code from the article
487  * "An Implicit Surface Polygonizer"
488  * by Jules Bloomenthal, jbloom@beauty.gmu.edu
489  * in "Graphics Gems IV", Academic Press, 1994
490
491  * Authored by Jules Bloomenthal, Xerox PARC.
492  * Copyright (c) Xerox Corporation, 1991.  All rights reserved.
493  * Permission is granted to reproduce, use and distribute this code for
494  * any and all purposes, provided that this notice appears in all copies. */
495
496 #define RES     12 /* # converge iterations    */
497
498 #define L       0  /* left direction:   -x, -i */
499 #define R       1  /* right direction:  +x, +i */
500 #define B       2  /* bottom direction: -y, -j */
501 #define T       3  /* top direction:    +y, +j */
502 #define N       4  /* near direction:   -z, -k */
503 #define F       5  /* far direction:    +z, +k */
504 #define LBN     0  /* left bottom near corner  */
505 #define LBF     1  /* left bottom far corner   */
506 #define LTN     2  /* left top near corner     */
507 #define LTF     3  /* left top far corner      */
508 #define RBN     4  /* right bottom near corner */
509 #define RBF     5  /* right bottom far corner  */
510 #define RTN     6  /* right top near corner    */
511 #define RTF     7  /* right top far corner     */
512
513 /* the LBN corner of cube (i, j, k), corresponds with location
514  * (i-0.5)*size, (j-0.5)*size, (k-0.5)*size) */
515
516 #define HASHBIT     (5)
517 #define HASHSIZE    (size_t)(1<<(3*HASHBIT))   /*! < hash table size (32768) */
518
519 #define HASH(i,j,k) ((((( (i) & 31)<<5) | ( (j) & 31))<<5 ) | ( (k) & 31) )
520
521 #define MB_BIT(i, bit) (((i)>>(bit))&1)
522 #define FLIP(i,bit) ((i)^1<<(bit)) /* flip the given bit of i */
523
524
525 /* **************** POLYGONIZATION ************************ */
526
527 void calc_mballco(MetaElem *ml, float *vec)
528 {
529         if(ml->mat) {
530                 mul_m4_v3((float ( * )[4])ml->mat, vec);
531         }
532 }
533
534 float densfunc(MetaElem *ball, float x, float y, float z)
535 {
536         float dist2 = 0.0, dx, dy, dz;
537         float vec[3];
538
539         vec[0]= x;
540         vec[1]= y;
541         vec[2]= z;
542         mul_m4_v3((float ( * )[4])ball->imat, vec);
543         dx= vec[0];
544         dy= vec[1];
545         dz= vec[2];
546         
547         if(ball->type==MB_BALL) {
548         }
549         else if(ball->type==MB_TUBEX) {
550                 if( dx > ball->len) dx-= ball->len;
551                 else if(dx< -ball->len) dx+= ball->len;
552                 else dx= 0.0;
553         }
554         else if(ball->type==MB_TUBEY) {
555                 if( dy > ball->len) dy-= ball->len;
556                 else if(dy< -ball->len) dy+= ball->len;
557                 else dy= 0.0;
558         }
559         else if(ball->type==MB_TUBEZ) {
560                 if( dz > ball->len) dz-= ball->len;
561                 else if(dz< -ball->len) dz+= ball->len;
562                 else dz= 0.0;
563         }
564         else if(ball->type==MB_TUBE) {
565                 if( dx > ball->expx) dx-= ball->expx;
566                 else if(dx< -ball->expx) dx+= ball->expx;
567                 else dx= 0.0;
568         }
569         else if(ball->type==MB_PLANE) {
570                 if( dx > ball->expx) dx-= ball->expx;
571                 else if(dx< -ball->expx) dx+= ball->expx;
572                 else dx= 0.0;
573                 if( dy > ball->expy) dy-= ball->expy;
574                 else if(dy< -ball->expy) dy+= ball->expy;
575                 else dy= 0.0;
576         }
577         else if(ball->type==MB_ELIPSOID) {
578                 dx *= 1/ball->expx;
579                 dy *= 1/ball->expy;
580                 dz *= 1/ball->expz;
581         }
582         else if(ball->type==MB_CUBE) {
583                 if( dx > ball->expx) dx-= ball->expx;
584                 else if(dx< -ball->expx) dx+= ball->expx;
585                 else dx= 0.0;
586                 if( dy > ball->expy) dy-= ball->expy;
587                 else if(dy< -ball->expy) dy+= ball->expy;
588                 else dy= 0.0;
589                 if( dz > ball->expz) dz-= ball->expz;
590                 else if(dz< -ball->expz) dz+= ball->expz;
591                 else dz= 0.0;
592         }
593
594         dist2= (dx*dx + dy*dy + dz*dz);
595
596         if(ball->flag & MB_NEGATIVE) {
597                 dist2= 1.0f-(dist2/ball->rad2);
598                 if(dist2 < 0.0f) return 0.5f;
599
600                 return 0.5f-ball->s*dist2*dist2*dist2;
601         }
602         else {
603                 dist2= 1.0f-(dist2/ball->rad2);
604                 if(dist2 < 0.0f) return -0.5f;
605
606                 return ball->s*dist2*dist2*dist2 -0.5f;
607         }
608 }
609
610 octal_node* find_metaball_octal_node(octal_node *node, float x, float y, float z, short depth)
611 {
612         if(!depth) return node;
613         
614         if(z < node->z){
615                 if(y < node->y){
616                         if(x < node->x){
617                                 if(node->nodes[0])
618                                         return find_metaball_octal_node(node->nodes[0],x,y,z,depth--);
619                                 else
620                                         return node;
621                         }
622                         else{
623                                 if(node->nodes[1])
624                                         return find_metaball_octal_node(node->nodes[1],x,y,z,depth--);
625                                 else
626                                         return node;
627                         }
628                 }
629                 else{
630                         if(x < node->x){
631                                 if(node->nodes[3])
632                                         return find_metaball_octal_node(node->nodes[3],x,y,z,depth--);
633                                 else
634                                         return node;
635                         }
636                         else{
637                                 if(node->nodes[2])
638                                         return find_metaball_octal_node(node->nodes[2],x,y,z,depth--);
639                                 else
640                                         return node;
641                         }               
642                 }
643         }
644         else{
645                 if(y < node->y){
646                         if(x < node->x){
647                                 if(node->nodes[4])
648                                         return find_metaball_octal_node(node->nodes[4],x,y,z,depth--);
649                                 else
650                                         return node;
651                         }
652                         else{
653                                 if(node->nodes[5])
654                                         return find_metaball_octal_node(node->nodes[5],x,y,z,depth--);
655                                 else
656                                         return node;
657                         }
658                 }
659                 else{
660                         if(x < node->x){
661                                 if(node->nodes[7])
662                                         return find_metaball_octal_node(node->nodes[7],x,y,z,depth--);
663                                 else
664                                         return node;
665                         }
666                         else{
667                                 if(node->nodes[6])
668                                         return find_metaball_octal_node(node->nodes[6],x,y,z,depth--);
669                                 else
670                                         return node;
671                         }               
672                 }
673         }
674         
675         return node;
676 }
677
678 float metaball(float x, float y, float z)
679 /*  float x, y, z; */
680 {
681         struct octal_node *node;
682         struct ml_pointer *ml_p;
683         float dens=0;
684         int a;
685         
686         if(totelem > 1){
687                 node= find_metaball_octal_node(metaball_tree->first, x, y, z, metaball_tree->depth);
688                 if(node){
689                         ml_p= node->elems.first;
690
691                         while(ml_p){
692                                 dens+=densfunc(ml_p->ml, x, y, z);
693                                 ml_p= ml_p->next;
694                         }
695
696                         dens+= -0.5f*(metaball_tree->pos - node->pos);
697                         dens+= 0.5f*(metaball_tree->neg - node->neg);
698                 }
699                 else{
700                         for(a=0; a<totelem; a++) {
701                                 dens+= densfunc( mainb[a], x, y, z);
702                         }
703                 }
704         }
705         else{
706                 dens+= densfunc( mainb[0], x, y, z);
707         }
708
709         return thresh - dens;
710 }
711
712 /* ******************************************** */
713
714 static int *indices=NULL;
715 static int totindex, curindex;
716
717
718 void accum_mballfaces(int i1, int i2, int i3, int i4)
719 {
720         int *newi, *cur;
721         /* static int i=0; I would like to delete altogether, but I don't dare to, yet */
722
723         if(totindex==curindex) {
724                 totindex+= 256;
725                 newi= MEM_mallocN(4*sizeof(int)*totindex, "vertindex");
726                 
727                 if(indices) {
728                         memcpy(newi, indices, 4*sizeof(int)*(totindex-256));
729                         MEM_freeN(indices);
730                 }
731                 indices= newi;
732         }
733         
734         cur= indices+4*curindex;
735
736         /* displists now support array drawing, we treat tri's as fake quad */
737         
738         cur[0]= i1;
739         cur[1]= i2;
740         cur[2]= i3;
741         if(i4==0)
742                 cur[3]= i3;
743         else 
744                 cur[3]= i4;
745         
746         curindex++;
747
748 }
749
750 /* ******************* MEMORY MANAGEMENT *********************** */
751 void *new_pgn_element(int size)
752 {
753         /* during polygonize 1000s of elements are allocated
754          * and never freed in between. Freeing only done at the end.
755          */
756         int blocksize= 16384;
757         static int offs= 0;             /* the current free address */
758         static struct pgn_elements *cur= NULL;
759         static ListBase lb= {NULL, NULL};
760         void *adr;
761         
762         if(size>10000 || size==0) {
763                 printf("incorrect use of new_pgn_element\n");
764         }
765         else if(size== -1) {
766                 cur= lb.first;
767                 while(cur) {
768                         MEM_freeN(cur->data);
769                         cur= cur->next;
770                 }
771                 BLI_freelistN(&lb);
772                 
773                 return NULL;    
774         }
775         
776         size= 4*( (size+3)/4 );
777         
778         if(cur) {
779                 if(size+offs < blocksize) {
780                         adr= (void *) (cur->data+offs);
781                          offs+= size;
782                         return adr;
783                 }
784         }
785         
786         cur= MEM_callocN( sizeof(struct pgn_elements), "newpgn");
787         cur->data= MEM_callocN(blocksize, "newpgn");
788         BLI_addtail(&lb, cur);
789         
790         offs= size;
791         return cur->data;
792 }
793
794 void freepolygonize(PROCESS *p)
795 {
796         MEM_freeN(p->corners);
797         MEM_freeN(p->edges);
798         MEM_freeN(p->centers);
799
800         new_pgn_element(-1);
801         
802         if(p->vertices.ptr) MEM_freeN(p->vertices.ptr);
803 }
804
805 /**** Cubical Polygonization (optional) ****/
806
807 #define LB      0  /* left bottom edge  */
808 #define LT      1  /* left top edge     */
809 #define LN      2  /* left near edge    */
810 #define LF      3  /* left far edge     */
811 #define RB      4  /* right bottom edge */
812 #define RT      5  /* right top edge    */
813 #define RN      6  /* right near edge   */
814 #define RF      7  /* right far edge    */
815 #define BN      8  /* bottom near edge  */
816 #define BF      9  /* bottom far edge   */
817 #define TN      10 /* top near edge     */
818 #define TF      11 /* top far edge      */
819
820 static INTLISTS *cubetable[256];
821
822 /* edge: LB, LT, LN, LF, RB, RT, RN, RF, BN, BF, TN, TF */
823 static int corner1[12]     = {
824         LBN,LTN,LBN,LBF,RBN,RTN,RBN,RBF,LBN,LBF,LTN,LTF};
825 static int corner2[12]     = {
826         LBF,LTF,LTN,LTF,RBF,RTF,RTN,RTF,RBN,RBF,RTN,RTF};
827 static int leftface[12]    = {
828         B,  L,  L,  F,  R,  T,  N,  R,  N,  B,  T,  F};
829 /* face on left when going corner1 to corner2 */
830 static int rightface[12]   = {
831         L,  T,  N,  L,  B,  R,  R,  F,  B,  F,  N,  T};
832 /* face on right when going corner1 to corner2 */
833
834
835 /* docube: triangulate the cube directly, without decomposition */
836
837 void docube(CUBE *cube, PROCESS *p, MetaBall *mb)
838 {
839         INTLISTS *polys;
840         CORNER *c1, *c2;
841         int i, index = 0, count, indexar[8];
842         
843         for (i = 0; i < 8; i++) if (cube->corners[i]->value > 0.0f) index += (1<<i);
844         
845         for (polys = cubetable[index]; polys; polys = polys->next) {
846                 INTLIST *edges;
847                 
848                 count = 0;
849                 
850                 for (edges = polys->list; edges; edges = edges->next) {
851                         c1 = cube->corners[corner1[edges->i]];
852                         c2 = cube->corners[corner2[edges->i]];
853                         
854                         indexar[count] = vertid(c1, c2, p, mb);
855                         count++;
856                 }
857                 if(count>2) {
858                         switch(count) {
859                         case 3:
860                                 accum_mballfaces(indexar[2], indexar[1], indexar[0], 0);
861                                 break;
862                         case 4:
863                                 if(indexar[0]==0) accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
864                                 else accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
865                                 break;
866                         case 5:
867                                 if(indexar[0]==0) accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
868                                 else accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
869
870                                 accum_mballfaces(indexar[4], indexar[3], indexar[0], 0);
871                                 break;
872                         case 6:
873                                 if(indexar[0]==0) {
874                                         accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
875                                         accum_mballfaces(indexar[0], indexar[5], indexar[4], indexar[3]);
876                                 }
877                                 else {
878                                         accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
879                                         accum_mballfaces(indexar[5], indexar[4], indexar[3], indexar[0]);
880                                 }
881                                 break;
882                         case 7:
883                                 if(indexar[0]==0) {
884                                         accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
885                                         accum_mballfaces(indexar[0], indexar[5], indexar[4], indexar[3]);
886                                 }
887                                 else {
888                                         accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
889                                         accum_mballfaces(indexar[5], indexar[4], indexar[3], indexar[0]);
890                                 }
891                                 
892                                 accum_mballfaces(indexar[6], indexar[5], indexar[0], 0);
893                                 
894                                 break;
895                         }
896                 }
897         }
898 }
899
900
901 /* testface: given cube at lattice (i, j, k), and four corners of face,
902  * if surface crosses face, compute other four corners of adjacent cube
903  * and add new cube to cube stack */
904
905 void testface(int i, int j, int k, CUBE* old, int bit, int c1, int c2, int c3, int c4, PROCESS *p)
906 {
907         CUBE newc;
908         CUBES *oldcubes = p->cubes;
909         CORNER *corn1, *corn2, *corn3, *corn4;
910         int n, pos;
911
912         corn1= old->corners[c1];
913         corn2= old->corners[c2];
914         corn3= old->corners[c3];
915         corn4= old->corners[c4];
916         
917         pos = corn1->value > 0.0f ? 1 : 0;
918
919         /* test if no surface crossing */
920         if( (corn2->value > 0) == pos && (corn3->value > 0) == pos && (corn4->value > 0) == pos) return;
921         /* test if cube out of bounds */
922         /*if ( abs(i) > p->bounds || abs(j) > p->bounds || abs(k) > p->bounds) return;*/
923         /* test if already visited (always as last) */
924         if (setcenter(p->centers, i, j, k)) return;
925
926
927         /* create new cube and add cube to top of stack: */
928         p->cubes = (CUBES *) new_pgn_element(sizeof(CUBES));
929         p->cubes->next = oldcubes;
930         
931         newc.i = i;
932         newc.j = j;
933         newc.k = k;
934         for (n = 0; n < 8; n++) newc.corners[n] = NULL;
935         
936         newc.corners[FLIP(c1, bit)] = corn1;
937         newc.corners[FLIP(c2, bit)] = corn2;
938         newc.corners[FLIP(c3, bit)] = corn3;
939         newc.corners[FLIP(c4, bit)] = corn4;
940
941         if(newc.corners[0]==NULL) newc.corners[0] = setcorner(p, i, j, k);
942         if(newc.corners[1]==NULL) newc.corners[1] = setcorner(p, i, j, k+1);
943         if(newc.corners[2]==NULL) newc.corners[2] = setcorner(p, i, j+1, k);
944         if(newc.corners[3]==NULL) newc.corners[3] = setcorner(p, i, j+1, k+1);
945         if(newc.corners[4]==NULL) newc.corners[4] = setcorner(p, i+1, j, k);
946         if(newc.corners[5]==NULL) newc.corners[5] = setcorner(p, i+1, j, k+1);
947         if(newc.corners[6]==NULL) newc.corners[6] = setcorner(p, i+1, j+1, k);
948         if(newc.corners[7]==NULL) newc.corners[7] = setcorner(p, i+1, j+1, k+1);
949
950         p->cubes->cube= newc;   
951 }
952
953 /* setcorner: return corner with the given lattice location
954    set (and cache) its function value */
955
956 CORNER *setcorner (PROCESS* p, int i, int j, int k)
957 {
958         /* for speed, do corner value caching here */
959         CORNER *c;
960         int index;
961
962         /* does corner exist? */
963         index = HASH(i, j, k);
964         c = p->corners[index];
965         
966         for (; c != NULL; c = c->next) {
967                 if (c->i == i && c->j == j && c->k == k) {
968                         return c;
969                 }
970         }
971
972         c = (CORNER *) new_pgn_element(sizeof(CORNER));
973
974         c->i = i; 
975         c->x = ((float)i-0.5f)*p->size;
976         c->j = j; 
977         c->y = ((float)j-0.5f)*p->size;
978         c->k = k; 
979         c->z = ((float)k-0.5f)*p->size;
980         c->value = p->function(c->x, c->y, c->z);
981         
982         c->next = p->corners[index];
983         p->corners[index] = c;
984         
985         return c;
986 }
987
988
989 /* nextcwedge: return next clockwise edge from given edge around given face */
990
991 int nextcwedge (int edge, int face)
992 {
993         switch (edge) {
994         case LB: 
995                 return (face == L)? LF : BN;
996         case LT: 
997                 return (face == L)? LN : TF;
998         case LN: 
999                 return (face == L)? LB : TN;
1000         case LF: 
1001                 return (face == L)? LT : BF;
1002         case RB: 
1003                 return (face == R)? RN : BF;
1004         case RT: 
1005                 return (face == R)? RF : TN;
1006         case RN: 
1007                 return (face == R)? RT : BN;
1008         case RF: 
1009                 return (face == R)? RB : TF;
1010         case BN: 
1011                 return (face == B)? RB : LN;
1012         case BF: 
1013                 return (face == B)? LB : RF;
1014         case TN: 
1015                 return (face == T)? LT : RN;
1016         case TF: 
1017                 return (face == T)? RT : LF;
1018         }
1019         return 0;
1020 }
1021
1022
1023 /* otherface: return face adjoining edge that is not the given face */
1024
1025 int otherface (int edge, int face)
1026 {
1027         int other = leftface[edge];
1028         return face == other? rightface[edge] : other;
1029 }
1030
1031
1032 /* makecubetable: create the 256 entry table for cubical polygonization */
1033
1034 void makecubetable (void)
1035 {
1036         static int isdone= 0;
1037         int i, e, c, done[12], pos[8];
1038
1039         if(isdone) return;
1040         isdone= 1;
1041
1042         for (i = 0; i < 256; i++) {
1043                 for (e = 0; e < 12; e++) done[e] = 0;
1044                 for (c = 0; c < 8; c++) pos[c] = MB_BIT(i, c);
1045                 for (e = 0; e < 12; e++)
1046                         if (!done[e] && (pos[corner1[e]] != pos[corner2[e]])) {
1047                                 INTLIST *ints = NULL;
1048                                 INTLISTS *lists = (INTLISTS *) MEM_callocN(sizeof(INTLISTS), "mball_intlist");
1049                                 int start = e, edge = e;
1050                                 
1051                                 /* get face that is to right of edge from pos to neg corner: */
1052                                 int face = pos[corner1[e]]? rightface[e] : leftface[e];
1053                                 
1054                                 while (1) {
1055                                         edge = nextcwedge(edge, face);
1056                                         done[edge] = 1;
1057                                         if (pos[corner1[edge]] != pos[corner2[edge]]) {
1058                                                 INTLIST *tmp = ints;
1059                                                 
1060                                                 ints = (INTLIST *) MEM_callocN(sizeof(INTLIST), "mball_intlist");
1061                                                 ints->i = edge;
1062                                                 ints->next = tmp; /* add edge to head of list */
1063                                                 
1064                                                 if (edge == start) break;
1065                                                 face = otherface(edge, face);
1066                                         }
1067                                 }
1068                                 lists->list = ints; /* add ints to head of table entry */
1069                                 lists->next = cubetable[i];
1070                                 cubetable[i] = lists;
1071                         }
1072         }
1073 }
1074
1075 void BKE_freecubetable(void)
1076 {
1077         int i;
1078         INTLISTS *lists, *nlists;
1079         INTLIST *ints, *nints;
1080
1081         for (i = 0; i < 256; i++) {
1082                 lists= cubetable[i];
1083                 while(lists) {
1084                         nlists= lists->next;
1085                         
1086                         ints= lists->list;
1087                         while(ints) {
1088                                 nints= ints->next;
1089                                 MEM_freeN(ints);
1090                                 ints= nints;
1091                         }
1092                         
1093                         MEM_freeN(lists);
1094                         lists= nlists;
1095                 }
1096                 cubetable[i]= NULL;
1097         }
1098 }
1099
1100 /**** Storage ****/
1101
1102 /* setcenter: set (i,j,k) entry of table[]
1103  * return 1 if already set; otherwise, set and return 0 */
1104
1105 int setcenter(CENTERLIST *table[], int i, int j, int k)
1106 {
1107         int index;
1108         CENTERLIST *newc, *l, *q;
1109
1110         index= HASH(i, j, k);
1111         q= table[index];
1112
1113         for (l = q; l != NULL; l = l->next) {
1114                 if (l->i == i && l->j == j && l->k == k) return 1;
1115         }
1116         
1117         newc = (CENTERLIST *) new_pgn_element(sizeof(CENTERLIST));
1118         newc->i = i; 
1119         newc->j = j; 
1120         newc->k = k; 
1121         newc->next = q;
1122         table[index] = newc;
1123         
1124         return 0;
1125 }
1126
1127
1128 /* setedge: set vertex id for edge */
1129
1130 void setedge (EDGELIST *table[],
1131                           int i1, int j1,
1132                           int k1, int i2,
1133                           int j2, int k2,
1134                           int vid)
1135 {
1136         unsigned int index;
1137         EDGELIST *newe;
1138         
1139         if (i1>i2 || (i1==i2 && (j1>j2 || (j1==j2 && k1>k2)))) {
1140                 int t=i1; 
1141                 i1=i2; 
1142                 i2=t; 
1143                 t=j1; 
1144                 j1=j2; 
1145                 j2=t; 
1146                 t=k1; 
1147                 k1=k2; 
1148                 k2=t;
1149         }
1150         index = HASH(i1, j1, k1) + HASH(i2, j2, k2);
1151         newe = (EDGELIST *) new_pgn_element(sizeof(EDGELIST));
1152         newe->i1 = i1; 
1153         newe->j1 = j1; 
1154         newe->k1 = k1;
1155         newe->i2 = i2; 
1156         newe->j2 = j2; 
1157         newe->k2 = k2;
1158         newe->vid = vid;
1159         newe->next = table[index];
1160         table[index] = newe;
1161 }
1162
1163
1164 /* getedge: return vertex id for edge; return -1 if not set */
1165
1166 int getedge (EDGELIST *table[],
1167                          int i1, int j1, int k1,
1168                          int i2, int j2, int k2)
1169 {
1170         EDGELIST *q;
1171         
1172         if (i1>i2 || (i1==i2 && (j1>j2 || (j1==j2 && k1>k2)))) {
1173                 int t=i1; 
1174                 i1=i2; 
1175                 i2=t; 
1176                 t=j1; 
1177                 j1=j2; 
1178                 j2=t; 
1179                 t=k1; 
1180                 k1=k2; 
1181                 k2=t;
1182         }
1183         q = table[HASH(i1, j1, k1)+HASH(i2, j2, k2)];
1184         for (; q != NULL; q = q->next)
1185                 if (q->i1 == i1 && q->j1 == j1 && q->k1 == k1 &&
1186                         q->i2 == i2 && q->j2 == j2 && q->k2 == k2)
1187                         return q->vid;
1188         return -1;
1189 }
1190
1191
1192 /**** Vertices ****/
1193
1194 #undef R
1195
1196
1197
1198 /* vertid: return index for vertex on edge:
1199  * c1->value and c2->value are presumed of different sign
1200  * return saved index if any; else compute vertex and save */
1201
1202 /* addtovertices: add v to sequence of vertices */
1203
1204 void addtovertices (VERTICES *vertices, VERTEX v)
1205 {
1206         if (vertices->count == vertices->max) {
1207                 int i;
1208                 VERTEX *newv;
1209                 vertices->max = vertices->count == 0 ? 10 : 2*vertices->count;
1210                 newv = (VERTEX *) MEM_callocN(vertices->max * sizeof(VERTEX), "addtovertices");
1211                 
1212                 for (i = 0; i < vertices->count; i++) newv[i] = vertices->ptr[i];
1213                 
1214                 if (vertices->ptr != NULL) MEM_freeN(vertices->ptr);
1215                 vertices->ptr = newv;
1216         }
1217         vertices->ptr[vertices->count++] = v;
1218 }
1219
1220 /* vnormal: compute unit length surface normal at point */
1221
1222 void vnormal (MB_POINT *point, PROCESS *p, MB_POINT *v)
1223 {
1224         float delta= 0.2f*p->delta;
1225         float f = p->function(point->x, point->y, point->z);
1226
1227         v->x = p->function(point->x+delta, point->y, point->z)-f;
1228         v->y = p->function(point->x, point->y+delta, point->z)-f;
1229         v->z = p->function(point->x, point->y, point->z+delta)-f;
1230         f = sqrtf(v->x*v->x + v->y*v->y + v->z*v->z);
1231
1232         if (f != 0.0f) {
1233                 v->x /= f; 
1234                 v->y /= f; 
1235                 v->z /= f;
1236         }
1237         
1238         if(FALSE) {
1239                 MB_POINT temp;
1240                 
1241                 delta *= 2.0f;
1242                 
1243                 f = p->function(point->x, point->y, point->z);
1244         
1245                 temp.x = p->function(point->x+delta, point->y, point->z)-f;
1246                 temp.y = p->function(point->x, point->y+delta, point->z)-f;
1247                 temp.z = p->function(point->x, point->y, point->z+delta)-f;
1248                 f = sqrtf(temp.x*temp.x + temp.y*temp.y + temp.z*temp.z);
1249         
1250                 if (f != 0.0f) {
1251                         temp.x /= f; 
1252                         temp.y /= f; 
1253                         temp.z /= f;
1254                         
1255                         v->x+= temp.x;
1256                         v->y+= temp.y;
1257                         v->z+= temp.z;
1258                         
1259                         f = sqrtf(v->x*v->x + v->y*v->y + v->z*v->z);
1260                 
1261                         if (f != 0.0f) {
1262                                 v->x /= f; 
1263                                 v->y /= f; 
1264                                 v->z /= f;
1265                         }
1266                 }
1267         }
1268         
1269 }
1270
1271
1272 int vertid (CORNER *c1, CORNER *c2, PROCESS *p, MetaBall *mb)
1273 {
1274         VERTEX v;
1275         MB_POINT a, b;
1276         int vid = getedge(p->edges, c1->i, c1->j, c1->k, c2->i, c2->j, c2->k);
1277
1278         if (vid != -1) return vid;                           /* previously computed */
1279         a.x = c1->x; 
1280         a.y = c1->y; 
1281         a.z = c1->z;
1282         b.x = c2->x; 
1283         b.y = c2->y; 
1284         b.z = c2->z;
1285
1286         converge(&a, &b, c1->value, c2->value, p->function, &v.position, mb, 1); /* position */
1287         vnormal(&v.position, p, &v.normal);
1288
1289         addtovertices(&p->vertices, v);                    /* save vertex */
1290         vid = p->vertices.count-1;
1291         setedge(p->edges, c1->i, c1->j, c1->k, c2->i, c2->j, c2->k, vid);
1292         
1293         return vid;
1294 }
1295
1296
1297
1298
1299 /* converge: from two points of differing sign, converge to zero crossing */
1300 /* watch it: p1 and p2 are used to calculate */
1301 void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
1302                            float (*function)(float, float, float), MB_POINT *p, MetaBall *mb, int f)
1303 {
1304         int i = 0;
1305         MB_POINT pos, neg;
1306         float positive = 0.0f, negative = 0.0f;
1307         float dx = 0.0f ,dy = 0.0f ,dz = 0.0f;
1308         
1309         if (v1 < 0) {
1310                 pos= *p2;
1311                 neg= *p1;
1312                 positive = v2;
1313                 negative = v1;
1314         }
1315         else {
1316                 pos= *p1;
1317                 neg= *p2;
1318                 positive = v1;
1319                 negative = v2;
1320         }
1321
1322         dx = pos.x - neg.x;
1323         dy = pos.y - neg.y;
1324         dz = pos.z - neg.z;
1325
1326 /* Approximation by linear interpolation is faster then binary subdivision,
1327  * but it results sometimes (mb->thresh < 0.2) into the strange results */
1328         if((mb->thresh > 0.2f) && (f==1)){
1329         if((dy == 0.0f) && (dz == 0.0f)){
1330                 p->x = neg.x - negative*dx/(positive-negative);
1331                 p->y = neg.y;
1332                 p->z = neg.z;
1333                 return;
1334         }
1335           if((dx == 0.0f) && (dz == 0.0f)){
1336                 p->x = neg.x;
1337                 p->y = neg.y - negative*dy/(positive-negative);
1338                 p->z = neg.z;
1339                 return;
1340         }
1341         if((dx == 0.0f) && (dy == 0.0f)){
1342                 p->x = neg.x;
1343                 p->y = neg.y;
1344                 p->z = neg.z - negative*dz/(positive-negative);
1345                 return;
1346         }
1347         }
1348
1349         if((dy == 0.0f) && (dz == 0.0f)){
1350                 p->y = neg.y;
1351                 p->z = neg.z;
1352                 while (1) {
1353                         if (i++ == RES) return;
1354                         p->x = 0.5f*(pos.x + neg.x);
1355                         if ((function(p->x,p->y,p->z)) > 0.0f)  pos.x = p->x; else neg.x = p->x;
1356                 }
1357         }
1358
1359         if((dx == 0.0f) && (dz == 0.0f)){
1360                 p->x = neg.x;
1361                 p->z = neg.z;
1362                 while (1) {
1363                         if (i++ == RES) return;
1364                         p->y = 0.5f*(pos.y + neg.y);
1365                         if ((function(p->x,p->y,p->z)) > 0.0f)  pos.y = p->y; else neg.y = p->y;
1366                 }
1367           }
1368    
1369         if((dx == 0.0f) && (dy == 0.0f)){
1370                 p->x = neg.x;
1371                 p->y = neg.y;
1372                 while (1) {
1373                         if (i++ == RES) return;
1374                         p->z = 0.5f*(pos.z + neg.z);
1375                         if ((function(p->x,p->y,p->z)) > 0.0f)  pos.z = p->z; else neg.z = p->z;
1376                 }
1377         }
1378
1379         /* This is necessary to find start point */
1380         while (1) {
1381                 p->x = 0.5f*(pos.x + neg.x);
1382                 p->y = 0.5f*(pos.y + neg.y);
1383                 p->z = 0.5f*(pos.z + neg.z);
1384
1385                 if (i++ == RES) return;
1386    
1387                 if ((function(p->x, p->y, p->z)) > 0.0f){
1388                         pos.x = p->x;
1389                         pos.y = p->y;
1390                         pos.z = p->z;
1391                 }
1392                 else{
1393                         neg.x = p->x;
1394                         neg.y = p->y;
1395                         neg.z = p->z;
1396                 }
1397         }
1398 }
1399
1400 /* ************************************** */
1401 void add_cube(PROCESS *mbproc, int i, int j, int k, int count)
1402 {
1403         CUBES *ncube;
1404         int n;
1405         int a, b, c;
1406
1407         /* hmmm, not only one, but eight cube will be added on the stack 
1408          * ... */
1409         for(a=i-1; a<i+count; a++)
1410                 for(b=j-1; b<j+count; b++)
1411                         for(c=k-1; c<k+count; c++) {
1412                                 /* test if cube has been found before */
1413                                 if( setcenter(mbproc->centers, a, b, c)==0 ) {
1414                                         /* push cube on stack: */
1415                                         ncube= (CUBES *) new_pgn_element(sizeof(CUBES));
1416                                         ncube->next= mbproc->cubes;
1417                                         mbproc->cubes= ncube;
1418
1419                                         ncube->cube.i= a;
1420                                         ncube->cube.j= b;
1421                                         ncube->cube.k= c;
1422
1423                                         /* set corners of initial cube: */
1424                                         for (n = 0; n < 8; n++)
1425                                         ncube->cube.corners[n] = setcorner(mbproc, a+MB_BIT(n,2), b+MB_BIT(n,1), c+MB_BIT(n,0));
1426                                 }
1427                         }
1428 }
1429
1430
1431 void find_first_points(PROCESS *mbproc, MetaBall *mb, int a)
1432 {
1433         MB_POINT IN, in, OUT, out; /*point;*/
1434         MetaElem *ml;
1435         int i, j, k, c_i, c_j, c_k;
1436         int index[3]={1,0,-1};
1437         float f =0.0f;
1438         float in_v /*, out_v*/;
1439         MB_POINT workp;
1440         float tmp_v, workp_v, max_len, len, dx, dy, dz, nx, ny, nz, MAXN;
1441
1442         ml = mainb[a];
1443
1444         f = 1-(mb->thresh/ml->s);
1445
1446         /* Skip, when Stiffness of MetaElement is too small ... MetaElement can't be
1447          * visible alone ... but still can influence others MetaElements :-) */
1448         if(f > 0.0f) {
1449                 OUT.x = IN.x = in.x= 0.0;
1450                 OUT.y = IN.y = in.y= 0.0;
1451                 OUT.z = IN.z = in.z= 0.0;
1452
1453                 calc_mballco(ml, (float *)&in);
1454                 in_v = mbproc->function(in.x, in.y, in.z);
1455
1456                 for(i=0;i<3;i++){
1457                         switch (ml->type) {
1458                                 case MB_BALL:
1459                                         OUT.x = out.x= IN.x + index[i]*ml->rad;
1460                                         break;
1461                                 case MB_TUBE:
1462                                 case MB_PLANE:
1463                                 case MB_ELIPSOID:
1464                                 case MB_CUBE:
1465                                         OUT.x = out.x= IN.x + index[i]*(ml->expx + ml->rad);
1466                                         break;
1467                         }
1468
1469                         for(j=0;j<3;j++) {
1470                                 switch (ml->type) {
1471                                         case MB_BALL:
1472                                                 OUT.y = out.y= IN.y + index[j]*ml->rad;
1473                                                 break;
1474                                         case MB_TUBE:
1475                                         case MB_PLANE:
1476                                         case MB_ELIPSOID:
1477                                         case MB_CUBE:
1478                                                 OUT.y = out.y= IN.y + index[j]*(ml->expy + ml->rad);
1479                                                 break;
1480                                 }
1481                         
1482                                 for(k=0;k<3;k++) {
1483                                         out.x = OUT.x;
1484                                         out.y = OUT.y;
1485                                         switch (ml->type) {
1486                                                 case MB_BALL:
1487                                                 case MB_TUBE:
1488                                                 case MB_PLANE:
1489                                                         out.z= IN.z + index[k]*ml->rad;
1490                                                         break;
1491                                                 case MB_ELIPSOID:
1492                                                 case MB_CUBE:
1493                                                         out.z= IN.z + index[k]*(ml->expz + ml->rad);
1494                                                         break;
1495                                         }
1496
1497                                         calc_mballco(ml, (float *)&out);
1498
1499                                         /*out_v = mbproc->function(out.x, out.y, out.z);*/ /*UNUSED*/
1500
1501                                         /* find "first points" on Implicit Surface of MetaElemnt ml */
1502                                         workp.x = in.x;
1503                                         workp.y = in.y;
1504                                         workp.z = in.z;
1505                                         workp_v = in_v;
1506                                         max_len = sqrtf((out.x-in.x)*(out.x-in.x) + (out.y-in.y)*(out.y-in.y) + (out.z-in.z)*(out.z-in.z));
1507
1508                                         nx = abs((out.x - in.x)/mbproc->size);
1509                                         ny = abs((out.y - in.y)/mbproc->size);
1510                                         nz = abs((out.z - in.z)/mbproc->size);
1511                                         
1512                                         MAXN = MAX3(nx,ny,nz);
1513                                         if(MAXN!=0.0f) {
1514                                                 dx = (out.x - in.x)/MAXN;
1515                                                 dy = (out.y - in.y)/MAXN;
1516                                                 dz = (out.z - in.z)/MAXN;
1517
1518                                                 len = 0.0;
1519                                                 while(len<=max_len) {
1520                                                         workp.x += dx;
1521                                                         workp.y += dy;
1522                                                         workp.z += dz;
1523                                                         /* compute value of implicite function */
1524                                                         tmp_v = mbproc->function(workp.x, workp.y, workp.z);
1525                                                         /* add cube to the stack, when value of implicite function crosses zero value */
1526                                                         if((tmp_v<0.0f && workp_v>=0.0f)||(tmp_v>0.0f && workp_v<=0.0f)) {
1527
1528                                                                 /* indexes of CUBE, which includes "first point" */
1529                                                                 c_i= (int)floor(workp.x/mbproc->size);
1530                                                                 c_j= (int)floor(workp.y/mbproc->size);
1531                                                                 c_k= (int)floor(workp.z/mbproc->size);
1532                                                                 
1533                                                                 /* add CUBE (with indexes c_i, c_j, c_k) to the stack,
1534                                                                  * this cube includes found point of Implicit Surface */
1535                                                                 if (ml->flag & MB_NEGATIVE)
1536                                                                         add_cube(mbproc, c_i, c_j, c_k, 2);
1537                                                                 else
1538                                                                         add_cube(mbproc, c_i, c_j, c_k, 1);
1539                                                         }
1540                                                         len = sqrtf((workp.x-in.x)*(workp.x-in.x) + (workp.y-in.y)*(workp.y-in.y) + (workp.z-in.z)*(workp.z-in.z));
1541                                                         workp_v = tmp_v;
1542
1543                                                 }
1544                                         }
1545                                 }
1546                         }
1547                 }
1548         }
1549 }
1550
1551 void polygonize(PROCESS *mbproc, MetaBall *mb)
1552 {
1553         CUBE c;
1554         int a;
1555
1556         mbproc->vertices.count = mbproc->vertices.max = 0;
1557         mbproc->vertices.ptr = NULL;
1558
1559         /* allocate hash tables and build cube polygon table: */
1560         mbproc->centers = MEM_callocN(HASHSIZE * sizeof(CENTERLIST *), "mbproc->centers");
1561         mbproc->corners = MEM_callocN(HASHSIZE * sizeof(CORNER *), "mbproc->corners");
1562         mbproc->edges = MEM_callocN(2*HASHSIZE * sizeof(EDGELIST *), "mbproc->edges");
1563         makecubetable();
1564
1565         for(a=0; a<totelem; a++) {
1566
1567                 /* try to find 8 points on the surface for each MetaElem */
1568                 find_first_points(mbproc, mb, a);       
1569         }
1570
1571         /* polygonize all MetaElems of current MetaBall */
1572         while (mbproc->cubes != NULL) { /* process active cubes till none left */
1573                 c = mbproc->cubes->cube;
1574
1575                 /* polygonize the cube directly: */
1576                 docube(&c, mbproc, mb);
1577                 
1578                 /* pop current cube from stack */
1579                 mbproc->cubes = mbproc->cubes->next;
1580                 
1581                 /* test six face directions, maybe add to stack: */
1582                 testface(c.i-1, c.j, c.k, &c, 2, LBN, LBF, LTN, LTF, mbproc);
1583                 testface(c.i+1, c.j, c.k, &c, 2, RBN, RBF, RTN, RTF, mbproc);
1584                 testface(c.i, c.j-1, c.k, &c, 1, LBN, LBF, RBN, RBF, mbproc);
1585                 testface(c.i, c.j+1, c.k, &c, 1, LTN, LTF, RTN, RTF, mbproc);
1586                 testface(c.i, c.j, c.k-1, &c, 0, LBN, LTN, RBN, RTN, mbproc);
1587                 testface(c.i, c.j, c.k+1, &c, 0, LBF, LTF, RBF, RTF, mbproc);
1588         }
1589 }
1590
1591 float init_meta(Scene *scene, Object *ob)       /* return totsize */
1592 {
1593         Scene *sce_iter= scene;
1594         Base *base;
1595         Object *bob;
1596         MetaBall *mb;
1597         MetaElem *ml;
1598         float size, totsize, obinv[4][4], obmat[4][4], vec[3];
1599         //float max=0.0;
1600         int a, obnr, zero_size=0;
1601         char obname[32];
1602         
1603         copy_m4_m4(obmat, ob->obmat);   /* to cope with duplicators from next_object */
1604         invert_m4_m4(obinv, ob->obmat);
1605         a= 0;
1606         
1607         BLI_split_name_num(obname, &obnr, ob->id.name+2, '.');
1608         
1609         /* make main array */
1610         next_object(&sce_iter, 0, NULL, NULL);
1611         while(next_object(&sce_iter, 1, &base, &bob)) {
1612
1613                 if(bob->type==OB_MBALL) {
1614                         zero_size= 0;
1615                         ml= NULL;
1616
1617                         if(bob==ob && (base->flag & OB_FROMDUPLI)==0) {
1618                                 mb= ob->data;
1619         
1620                                 if(mb->editelems) ml= mb->editelems->first;
1621                                 else ml= mb->elems.first;
1622                         }
1623                         else {
1624                                 char name[32];
1625                                 int nr;
1626                                 
1627                                 BLI_split_name_num(name, &nr, bob->id.name+2, '.');
1628                                 if( strcmp(obname, name)==0 ) {
1629                                         mb= bob->data;
1630                                         
1631                                         if(mb->editelems) ml= mb->editelems->first;
1632                                         else ml= mb->elems.first;
1633                                 }
1634                         }
1635
1636                         /* when metaball object has zero scale, then MetaElem to this MetaBall
1637                          * will not be put to mainb array */
1638                         if(bob->size[0]==0.0f || bob->size[1]==0.0f || bob->size[2]==0.0f) {
1639                                 zero_size= 1;
1640                         }
1641                         else if(bob->parent) {
1642                                 struct Object *pob=bob->parent;
1643                                 while(pob) {
1644                                         if(pob->size[0]==0.0f || pob->size[1]==0.0f || pob->size[2]==0.0f) {
1645                                                 zero_size= 1;
1646                                                 break;
1647                                         }
1648                                         pob= pob->parent;
1649                                 }
1650                         }
1651
1652                         if (zero_size) {
1653                                 unsigned int ml_count=0;
1654                                 while(ml) {
1655                                         ml_count++;
1656                                         ml= ml->next;
1657                                 }
1658                                 totelem -= ml_count;
1659                         }
1660                         else {
1661                         while(ml) {
1662                                 if(!(ml->flag & MB_HIDE)) {
1663                                         int i;
1664                                         float temp1[4][4], temp2[4][4], temp3[4][4];
1665                                         float (*mat)[4] = NULL, (*imat)[4] = NULL;
1666                                         float max_x, max_y, max_z, min_x, min_y, min_z;
1667
1668                                         max_x = max_y = max_z = -3.4e38;
1669                                         min_x = min_y = min_z =  3.4e38;
1670
1671                                         /* too big stiffness seems only ugly due to linear interpolation
1672                                          * no need to have possibility for too big stiffness */
1673                                         if(ml->s > 10.0f) ml->s = 10.0f;
1674                                         
1675                                         /* Rotation of MetaElem is stored in quat */
1676                                          quat_to_mat4( temp3,ml->quat);
1677
1678                                         /* Translation of MetaElem */
1679                                         unit_m4(temp2);
1680                                         temp2[3][0]= ml->x;
1681                                         temp2[3][1]= ml->y;
1682                                         temp2[3][2]= ml->z;
1683
1684                                         mul_m4_m4m4(temp1, temp3, temp2);
1685                                 
1686                                         /* make a copy because of duplicates */
1687                                         mainb[a]= new_pgn_element(sizeof(MetaElem));
1688                                         *(mainb[a])= *ml;
1689                                         mainb[a]->bb = new_pgn_element(sizeof(BoundBox));
1690                                 
1691                                         mat= new_pgn_element(4*4*sizeof(float));
1692                                         imat= new_pgn_element(4*4*sizeof(float));
1693                                         
1694                                         /* mat is the matrix to transform from mball into the basis-mball */
1695                                         invert_m4_m4(obinv, obmat);
1696                                         mul_m4_m4m4(temp2, bob->obmat, obinv);
1697                                         /* MetaBall transformation */
1698                                         mul_m4_m4m4(mat, temp1, temp2);
1699
1700                                         invert_m4_m4(imat,mat);                         
1701
1702                                         mainb[a]->rad2= ml->rad*ml->rad;
1703
1704                                         mainb[a]->mat= (float*) mat;
1705                                         mainb[a]->imat= (float*) imat;
1706
1707                                         /* untransformed Bounding Box of MetaElem */
1708                                         /* 0 */
1709                                         mainb[a]->bb->vec[0][0]= -ml->expx;
1710                                         mainb[a]->bb->vec[0][1]= -ml->expy;
1711                                         mainb[a]->bb->vec[0][2]= -ml->expz;
1712                                         /* 1 */
1713                                         mainb[a]->bb->vec[1][0]=  ml->expx;
1714                                         mainb[a]->bb->vec[1][1]= -ml->expy;
1715                                         mainb[a]->bb->vec[1][2]= -ml->expz;
1716                                         /* 2 */
1717                                         mainb[a]->bb->vec[2][0]=  ml->expx;
1718                                         mainb[a]->bb->vec[2][1]=  ml->expy;
1719                                         mainb[a]->bb->vec[2][2]= -ml->expz;
1720                                         /* 3 */
1721                                         mainb[a]->bb->vec[3][0]= -ml->expx;
1722                                         mainb[a]->bb->vec[3][1]=  ml->expy;
1723                                         mainb[a]->bb->vec[3][2]= -ml->expz;
1724                                         /* 4 */
1725                                         mainb[a]->bb->vec[4][0]= -ml->expx;
1726                                         mainb[a]->bb->vec[4][1]= -ml->expy;
1727                                         mainb[a]->bb->vec[4][2]=  ml->expz;
1728                                         /* 5 */
1729                                         mainb[a]->bb->vec[5][0]=  ml->expx;
1730                                         mainb[a]->bb->vec[5][1]= -ml->expy;
1731                                         mainb[a]->bb->vec[5][2]=  ml->expz;
1732                                         /* 6 */
1733                                         mainb[a]->bb->vec[6][0]=  ml->expx;
1734                                         mainb[a]->bb->vec[6][1]=  ml->expy;
1735                                         mainb[a]->bb->vec[6][2]=  ml->expz;
1736                                         /* 7 */
1737                                         mainb[a]->bb->vec[7][0]= -ml->expx;
1738                                         mainb[a]->bb->vec[7][1]=  ml->expy;
1739                                         mainb[a]->bb->vec[7][2]=  ml->expz;
1740
1741                                         /* transformation of Metalem bb */
1742                                         for(i=0; i<8; i++)
1743                                                 mul_m4_v3((float ( * )[4])mat, mainb[a]->bb->vec[i]);
1744
1745                                         /* find max and min of transformed bb */
1746                                         for(i=0; i<8; i++){
1747                                                 /* find maximums */
1748                                                 if(mainb[a]->bb->vec[i][0] > max_x) max_x = mainb[a]->bb->vec[i][0];
1749                                                 if(mainb[a]->bb->vec[i][1] > max_y) max_y = mainb[a]->bb->vec[i][1];
1750                                                 if(mainb[a]->bb->vec[i][2] > max_z) max_z = mainb[a]->bb->vec[i][2];
1751                                                 /* find  minimums */
1752                                                 if(mainb[a]->bb->vec[i][0] < min_x) min_x = mainb[a]->bb->vec[i][0];
1753                                                 if(mainb[a]->bb->vec[i][1] < min_y) min_y = mainb[a]->bb->vec[i][1];
1754                                                 if(mainb[a]->bb->vec[i][2] < min_z) min_z = mainb[a]->bb->vec[i][2];
1755                                         }
1756
1757                                         /* create "new" bb, only point 0 and 6, which are
1758                                          * neccesary for octal tree filling */
1759                                         mainb[a]->bb->vec[0][0] = min_x - ml->rad;
1760                                         mainb[a]->bb->vec[0][1] = min_y - ml->rad;
1761                                         mainb[a]->bb->vec[0][2] = min_z - ml->rad;
1762
1763                                         mainb[a]->bb->vec[6][0] = max_x + ml->rad;
1764                                         mainb[a]->bb->vec[6][1] = max_y + ml->rad;
1765                                         mainb[a]->bb->vec[6][2] = max_z + ml->rad;
1766                                         
1767                                         a++;
1768                                 }
1769                                 ml= ml->next;
1770                         }
1771                         }
1772                 }
1773         }
1774
1775         
1776         /* totsize (= 'manhattan' radius) */
1777         totsize= 0.0;
1778         for(a=0; a<totelem; a++) {
1779                 
1780                 vec[0]= mainb[a]->x + mainb[a]->rad + mainb[a]->expx;
1781                 vec[1]= mainb[a]->y + mainb[a]->rad + mainb[a]->expy;
1782                 vec[2]= mainb[a]->z + mainb[a]->rad + mainb[a]->expz;
1783
1784                 calc_mballco(mainb[a], vec);
1785         
1786                 size= (float)fabs( vec[0] );
1787                 if( size > totsize ) totsize= size;
1788                 size= (float)fabs( vec[1] );
1789                 if( size > totsize ) totsize= size;
1790                 size= (float)fabs( vec[2] );
1791                 if( size > totsize ) totsize= size;
1792
1793                 vec[0]= mainb[a]->x - mainb[a]->rad;
1794                 vec[1]= mainb[a]->y - mainb[a]->rad;
1795                 vec[2]= mainb[a]->z - mainb[a]->rad;
1796                                 
1797                 calc_mballco(mainb[a], vec);
1798         
1799                 size= (float)fabs( vec[0] );
1800                 if( size > totsize ) totsize= size;
1801                 size= (float)fabs( vec[1] );
1802                 if( size > totsize ) totsize= size;
1803                 size= (float)fabs( vec[2] );
1804                 if( size > totsize ) totsize= size;
1805         }
1806
1807         for(a=0; a<totelem; a++) {
1808                 thresh+= densfunc( mainb[a], 2.0f*totsize, 2.0f*totsize, 2.0f*totsize);
1809         }
1810
1811         return totsize;
1812 }
1813
1814 /* if MetaElem lies in node, then node includes MetaElem pointer (ml_p)
1815  * pointing at MetaElem (ml)
1816  */
1817 void fill_metaball_octal_node(octal_node *node, MetaElem *ml, short i)
1818 {
1819         ml_pointer *ml_p;
1820
1821         ml_p= MEM_mallocN(sizeof(ml_pointer), "ml_pointer");
1822         ml_p->ml= ml;
1823         BLI_addtail(&(node->nodes[i]->elems), ml_p);
1824         node->count++;
1825         
1826         if(ml->flag & MB_NEGATIVE) {
1827                 node->nodes[i]->neg++;
1828         }
1829         else{
1830                 node->nodes[i]->pos++;
1831         }
1832 }
1833
1834 /* Node is subdivided as is ilustrated on the following figure:
1835  * 
1836  *      +------+------+
1837  *     /      /      /|
1838  *    +------+------+ |
1839  *   /      /      /| +
1840  *  +------+------+ |/|
1841  *  |      |      | + |
1842  *  |      |      |/| +
1843  *  +------+------+ |/
1844  *  |      |      | +
1845  *  |      |      |/
1846  *  +------+------+
1847  *  
1848  */
1849 void subdivide_metaball_octal_node(octal_node *node, float size_x, float size_y, float size_z, short depth)
1850 {
1851         MetaElem *ml;
1852         ml_pointer *ml_p;
1853         float x,y,z;
1854         int a,i;
1855
1856         /* create new nodes */
1857         for(a=0;a<8;a++){
1858                 node->nodes[a]= MEM_mallocN(sizeof(octal_node),"octal_node");
1859                 for(i=0;i<8;i++)
1860                         node->nodes[a]->nodes[i]= NULL;
1861                 node->nodes[a]->parent= node;
1862                 node->nodes[a]->elems.first= NULL;
1863                 node->nodes[a]->elems.last= NULL;
1864                 node->nodes[a]->count= 0;
1865                 node->nodes[a]->neg= 0;
1866                 node->nodes[a]->pos= 0;
1867         }
1868
1869         size_x /= 2;
1870         size_y /= 2;
1871         size_z /= 2;
1872         
1873         /* center of node */
1874         node->x = x = node->x_min + size_x;
1875         node->y = y = node->y_min + size_y;
1876         node->z = z = node->z_min + size_z;
1877
1878         /* setting up of border points of new nodes */
1879         node->nodes[0]->x_min = node->x_min;
1880         node->nodes[0]->y_min = node->y_min;
1881         node->nodes[0]->z_min = node->z_min;
1882         node->nodes[0]->x = node->nodes[0]->x_min + size_x/2;
1883         node->nodes[0]->y = node->nodes[0]->y_min + size_y/2;
1884         node->nodes[0]->z = node->nodes[0]->z_min + size_z/2;
1885         
1886         node->nodes[1]->x_min = x;
1887         node->nodes[1]->y_min = node->y_min;
1888         node->nodes[1]->z_min = node->z_min;
1889         node->nodes[1]->x = node->nodes[1]->x_min + size_x/2;
1890         node->nodes[1]->y = node->nodes[1]->y_min + size_y/2;
1891         node->nodes[1]->z = node->nodes[1]->z_min + size_z/2;
1892
1893         node->nodes[2]->x_min = x;
1894         node->nodes[2]->y_min = y;
1895         node->nodes[2]->z_min = node->z_min;
1896         node->nodes[2]->x = node->nodes[2]->x_min + size_x/2;
1897         node->nodes[2]->y = node->nodes[2]->y_min + size_y/2;
1898         node->nodes[2]->z = node->nodes[2]->z_min + size_z/2;
1899
1900         node->nodes[3]->x_min = node->x_min;
1901         node->nodes[3]->y_min = y;
1902         node->nodes[3]->z_min = node->z_min;
1903         node->nodes[3]->x = node->nodes[3]->x_min + size_x/2;
1904         node->nodes[3]->y = node->nodes[3]->y_min + size_y/2;
1905         node->nodes[3]->z = node->nodes[3]->z_min + size_z/2;
1906
1907         node->nodes[4]->x_min = node->x_min;
1908         node->nodes[4]->y_min = node->y_min;
1909         node->nodes[4]->z_min = z;
1910         node->nodes[4]->x = node->nodes[4]->x_min + size_x/2;
1911         node->nodes[4]->y = node->nodes[4]->y_min + size_y/2;
1912         node->nodes[4]->z = node->nodes[4]->z_min + size_z/2;
1913         
1914         node->nodes[5]->x_min = x;
1915         node->nodes[5]->y_min = node->y_min;
1916         node->nodes[5]->z_min = z;
1917         node->nodes[5]->x = node->nodes[5]->x_min + size_x/2;
1918         node->nodes[5]->y = node->nodes[5]->y_min + size_y/2;
1919         node->nodes[5]->z = node->nodes[5]->z_min + size_z/2;
1920
1921         node->nodes[6]->x_min = x;
1922         node->nodes[6]->y_min = y;
1923         node->nodes[6]->z_min = z;
1924         node->nodes[6]->x = node->nodes[6]->x_min + size_x/2;
1925         node->nodes[6]->y = node->nodes[6]->y_min + size_y/2;
1926         node->nodes[6]->z = node->nodes[6]->z_min + size_z/2;
1927
1928         node->nodes[7]->x_min = node->x_min;
1929         node->nodes[7]->y_min = y;
1930         node->nodes[7]->z_min = z;
1931         node->nodes[7]->x = node->nodes[7]->x_min + size_x/2;
1932         node->nodes[7]->y = node->nodes[7]->y_min + size_y/2;
1933         node->nodes[7]->z = node->nodes[7]->z_min + size_z/2;
1934
1935         ml_p= node->elems.first;
1936         
1937         /* setting up references of MetaElems for new nodes */
1938         while(ml_p){
1939                 ml= ml_p->ml;
1940                 if(ml->bb->vec[0][2] < z){
1941                         if(ml->bb->vec[0][1] < y){
1942                                 /* vec[0][0] lies in first octant */
1943                                 if(ml->bb->vec[0][0] < x){
1944                                         /* ml belongs to the (0)1st node */
1945                                         fill_metaball_octal_node(node, ml, 0);
1946
1947                                         /* ml belongs to the (3)4th node */
1948                                         if(ml->bb->vec[6][1] >= y){
1949                                                 fill_metaball_octal_node(node, ml, 3);
1950
1951                                                 /* ml belongs to the (7)8th node */
1952                                                 if(ml->bb->vec[6][2] >= z){
1953                                                         fill_metaball_octal_node(node, ml, 7);
1954                                                 }
1955                                         }
1956         
1957                                         /* ml belongs to the (1)2nd node */
1958                                         if(ml->bb->vec[6][0] >= x){
1959                                                 fill_metaball_octal_node(node, ml, 1);
1960
1961                                                 /* ml belongs to the (5)6th node */
1962                                                 if(ml->bb->vec[6][2] >= z){
1963                                                         fill_metaball_octal_node(node, ml, 5);
1964                                                 }
1965                                         }
1966
1967                                         /* ml belongs to the (2)3th node */
1968                                         if((ml->bb->vec[6][0] >= x) && (ml->bb->vec[6][1] >= y)){
1969                                                 fill_metaball_octal_node(node, ml, 2);
1970                                                 
1971                                                 /* ml belong to the (6)7th node */
1972                                                 if(ml->bb->vec[6][2] >= z){
1973                                                         fill_metaball_octal_node(node, ml, 6);
1974                                                 }
1975                                                 
1976                                         }
1977                         
1978                                         /* ml belongs to the (4)5th node too */ 
1979                                         if(ml->bb->vec[6][2] >= z){
1980                                                 fill_metaball_octal_node(node, ml, 4);
1981                                         }
1982
1983                                         
1984                                         
1985                                 }
1986                                 /* vec[0][0] is in the (1)second octant */
1987                                 else{
1988                                         /* ml belong to the (1)2nd node */
1989                                         fill_metaball_octal_node(node, ml, 1);
1990
1991                                         /* ml belongs to the (2)3th node */
1992                                         if(ml->bb->vec[6][1] >= y){
1993                                                 fill_metaball_octal_node(node, ml, 2);
1994
1995                                                 /* ml belongs to the (6)7th node */
1996                                                 if(ml->bb->vec[6][2] >= z){
1997                                                         fill_metaball_octal_node(node, ml, 6);
1998                                                 }
1999                                                 
2000                                         }
2001                                         
2002                                         /* ml belongs to the (5)6th node */
2003                                         if(ml->bb->vec[6][2] >= z){
2004                                                 fill_metaball_octal_node(node, ml, 5);
2005                                         }
2006                                 }
2007                         }
2008                         else{
2009                                 /* vec[0][0] is in the (3)4th octant */
2010                                 if(ml->bb->vec[0][0] < x){
2011                                         /* ml belongs to the (3)4nd node */
2012                                         fill_metaball_octal_node(node, ml, 3);
2013                                         
2014                                         /* ml belongs to the (7)8th node */
2015                                         if(ml->bb->vec[6][2] >= z){
2016                                                 fill_metaball_octal_node(node, ml, 7);
2017                                         }
2018                                 
2019
2020                                         /* ml belongs to the (2)3th node */
2021                                         if(ml->bb->vec[6][0] >= x){
2022                                                 fill_metaball_octal_node(node, ml, 2);
2023                                         
2024                                                 /* ml belongs to the (6)7th node */
2025                                                 if(ml->bb->vec[6][2] >= z){
2026                                                         fill_metaball_octal_node(node, ml, 6);
2027                                                 }
2028                                         }
2029                                 }
2030
2031                         }
2032
2033                         /* vec[0][0] is in the (2)3th octant */
2034                         if((ml->bb->vec[0][0] >= x) && (ml->bb->vec[0][1] >= y)){
2035                                 /* ml belongs to the (2)3th node */
2036                                 fill_metaball_octal_node(node, ml, 2);
2037                                 
2038                                 /* ml belongs to the (6)7th node */
2039                                 if(ml->bb->vec[6][2] >= z){
2040                                         fill_metaball_octal_node(node, ml, 6);
2041                                 }
2042                         }
2043                 }
2044                 else{
2045                         if(ml->bb->vec[0][1] < y){
2046                                 /* vec[0][0] lies in (4)5th octant */
2047                                 if(ml->bb->vec[0][0] < x){
2048                                         /* ml belongs to the (4)5th node */
2049                                         fill_metaball_octal_node(node, ml, 4);
2050
2051                                         if(ml->bb->vec[6][0] >= x){
2052                                                 fill_metaball_octal_node(node, ml, 5);
2053                                         }
2054
2055                                         if(ml->bb->vec[6][1] >= y){
2056                                                 fill_metaball_octal_node(node, ml, 7);
2057                                         }
2058                                         
2059                                         if((ml->bb->vec[6][0] >= x) && (ml->bb->vec[6][1] >= y)){
2060                                                 fill_metaball_octal_node(node, ml, 6);
2061                                         }
2062                                 }
2063                                 /* vec[0][0] lies in (5)6th octant */
2064                                 else{
2065                                         fill_metaball_octal_node(node, ml, 5);
2066
2067                                         if(ml->bb->vec[6][1] >= y){
2068                                                 fill_metaball_octal_node(node, ml, 6);
2069                                         }
2070                                 }
2071                         }
2072                         else{
2073                                 /* vec[0][0] lies in (7)8th octant */
2074                                 if(ml->bb->vec[0][0] < x){
2075                                         fill_metaball_octal_node(node, ml, 7);
2076
2077                                         if(ml->bb->vec[6][0] >= x){
2078                                                 fill_metaball_octal_node(node, ml, 6);
2079                                         }
2080                                 }
2081
2082                         }
2083                         
2084                         /* vec[0][0] lies in (6)7th octant */
2085                         if((ml->bb->vec[0][0] >= x) && (ml->bb->vec[0][1] >= y)){
2086                                 fill_metaball_octal_node(node, ml, 6);
2087                         }
2088                 }
2089                 ml_p= ml_p->next;
2090         }
2091
2092         /* free references of MetaElems for curent node (it is not needed anymore) */
2093         BLI_freelistN(&node->elems);
2094
2095         depth--;
2096         
2097         if(depth>0){
2098                 for(a=0;a<8;a++){
2099                         if(node->nodes[a]->count > 0) /* if node is not empty, then it is subdivided */
2100                                 subdivide_metaball_octal_node(node->nodes[a], size_x, size_y, size_z, depth);
2101                 }
2102         }
2103 }
2104
2105 /* free all octal nodes recursively */
2106 void free_metaball_octal_node(octal_node *node)
2107 {
2108         int a;
2109         for(a=0;a<8;a++){
2110                 if(node->nodes[a]!=NULL) free_metaball_octal_node(node->nodes[a]);
2111         }
2112         BLI_freelistN(&node->elems);
2113         MEM_freeN(node);
2114 }
2115
2116 /* If scene include more then one MetaElem, then octree is used */
2117 void init_metaball_octal_tree(int depth)
2118 {
2119         struct octal_node *node;
2120         ml_pointer *ml_p;
2121         float size[3];
2122         int a;
2123         
2124         metaball_tree= MEM_mallocN(sizeof(octal_tree), "metaball_octal_tree");
2125         metaball_tree->first= node= MEM_mallocN(sizeof(octal_node), "metaball_octal_node");
2126         /* maximal depth of octree */
2127         metaball_tree->depth= depth;
2128
2129         metaball_tree->neg= node->neg=0;
2130         metaball_tree->pos= node->pos=0;
2131         
2132         node->elems.first= NULL;
2133         node->elems.last= NULL;
2134         node->count=0;
2135
2136         for(a=0;a<8;a++)
2137                 node->nodes[a]=NULL;
2138
2139         node->x_min= node->y_min= node->z_min= FLT_MAX;
2140         node->x_max= node->y_max= node->z_max= -FLT_MAX;
2141
2142         /* size of octal tree scene */
2143         for(a=0;a<totelem;a++) {
2144                 if(mainb[a]->bb->vec[0][0] < node->x_min) node->x_min= mainb[a]->bb->vec[0][0];
2145                 if(mainb[a]->bb->vec[0][1] < node->y_min) node->y_min= mainb[a]->bb->vec[0][1];
2146                 if(mainb[a]->bb->vec[0][2] < node->z_min) node->z_min= mainb[a]->bb->vec[0][2];
2147                 
2148                 if(mainb[a]->bb->vec[6][0] > node->x_max) node->x_max= mainb[a]->bb->vec[6][0];
2149                 if(mainb[a]->bb->vec[6][1] > node->y_max) node->y_max= mainb[a]->bb->vec[6][1];
2150                 if(mainb[a]->bb->vec[6][2] > node->z_max) node->z_max= mainb[a]->bb->vec[6][2];
2151
2152                 ml_p= MEM_mallocN(sizeof(ml_pointer), "ml_pointer");
2153                 ml_p->ml= mainb[a];
2154                 BLI_addtail(&node->elems, ml_p);
2155
2156                 if(mainb[a]->flag & MB_NEGATIVE) {
2157                         /* number of negative MetaElem in scene */
2158                         metaball_tree->neg++;
2159                 }
2160                 else{
2161                         /* number of positive MetaElem in scene */
2162                         metaball_tree->pos++;
2163                 }
2164         }
2165
2166         /* size of first node */        
2167         size[0]= node->x_max - node->x_min;
2168         size[1]= node->y_max - node->y_min;
2169         size[2]= node->z_max - node->z_min;
2170
2171         /* first node is subdivided recursively */
2172         subdivide_metaball_octal_node(node, size[0], size[1], size[2], metaball_tree->depth);
2173 }
2174
2175 void metaball_polygonize(Scene *scene, Object *ob, ListBase *dispbase)
2176 {
2177         PROCESS mbproc;
2178         MetaBall *mb;
2179         DispList *dl;
2180         int a, nr_cubes;
2181         float *ve, *no, totsize, width;
2182
2183         mb= ob->data;
2184
2185         if(totelem==0) return;
2186         if(!(G.rendering) && (mb->flag==MB_UPDATE_NEVER)) return;
2187         if(G.moving && mb->flag==MB_UPDATE_FAST) return;
2188
2189         curindex= totindex= 0;
2190         indices= NULL;
2191         thresh= mb->thresh;
2192
2193         /* total number of MetaElems (totelem) is precomputed in find_basis_mball() function */
2194         mainb= MEM_mallocN(sizeof(void *)*totelem, "mainb");
2195         
2196         /* initialize all mainb (MetaElems) */
2197         totsize= init_meta(scene, ob);
2198
2199         if(metaball_tree){
2200                 free_metaball_octal_node(metaball_tree->first);
2201                 MEM_freeN(metaball_tree);
2202                 metaball_tree= NULL;
2203         }
2204
2205         /* if scene includes more then one MetaElem, then octal tree optimalisation is used */  
2206         if((totelem > 1) && (totelem <= 64)) init_metaball_octal_tree(1);
2207         if((totelem > 64) && (totelem <= 128)) init_metaball_octal_tree(2);
2208         if((totelem > 128) && (totelem <= 512)) init_metaball_octal_tree(3);
2209         if((totelem > 512) && (totelem <= 1024)) init_metaball_octal_tree(4);
2210         if(totelem > 1024) init_metaball_octal_tree(5);
2211
2212         /* don't polygonize metaballs with too high resolution (base mball to small)
2213          * note: Eps was 0.0001f but this was giving problems for blood animation for durian, using 0.00001f */
2214         if(metaball_tree) {
2215                 if(     ob->size[0] <= 0.00001f * (metaball_tree->first->x_max - metaball_tree->first->x_min) ||
2216                         ob->size[1] <= 0.00001f * (metaball_tree->first->y_max - metaball_tree->first->y_min) ||
2217                         ob->size[2] <= 0.00001f * (metaball_tree->first->z_max - metaball_tree->first->z_min))
2218                 {
2219                         new_pgn_element(-1); /* free values created by init_meta */
2220
2221                         MEM_freeN(mainb);
2222
2223                         /* free tree */
2224                         free_metaball_octal_node(metaball_tree->first);
2225                         MEM_freeN(metaball_tree);
2226                         metaball_tree= NULL;
2227
2228                         return;
2229                 }
2230         }
2231
2232         /* width is size per polygonize cube */
2233         if(G.rendering) width= mb->rendersize;
2234         else {
2235                 width= mb->wiresize;
2236                 if(G.moving && mb->flag==MB_UPDATE_HALFRES) width*= 2;
2237         }
2238         /* nr_cubes is just for safety, minimum is totsize */
2239         nr_cubes= (int)(0.5f+totsize/width);
2240
2241         /* init process */
2242         mbproc.function = metaball;
2243         mbproc.size = width;
2244         mbproc.bounds = nr_cubes;
2245         mbproc.cubes= NULL;
2246         mbproc.delta = width/(float)(RES*RES);
2247
2248         polygonize(&mbproc, mb);
2249         
2250         MEM_freeN(mainb);
2251
2252         /* free octal tree */
2253         if(totelem > 1){
2254                 free_metaball_octal_node(metaball_tree->first);
2255                 MEM_freeN(metaball_tree);
2256                 metaball_tree= NULL;
2257         }
2258
2259         if(curindex) {
2260                 dl= MEM_callocN(sizeof(DispList), "mbaldisp");
2261                 BLI_addtail(dispbase, dl);
2262                 dl->type= DL_INDEX4;
2263                 dl->nr= mbproc.vertices.count;
2264                 dl->parts= curindex;
2265
2266                 dl->index= indices;
2267                 indices= NULL;
2268                 
2269                 a= mbproc.vertices.count;
2270                 dl->verts= ve= MEM_mallocN(sizeof(float)*3*a, "mballverts");
2271                 dl->nors= no= MEM_mallocN(sizeof(float)*3*a, "mballnors");
2272
2273                 for(a=0; a<mbproc.vertices.count; a++, no+=3, ve+=3) {
2274                         ve[0]= mbproc.vertices.ptr[a].position.x;
2275                         ve[1]= mbproc.vertices.ptr[a].position.y;
2276                         ve[2]= mbproc.vertices.ptr[a].position.z;
2277
2278                         no[0]= mbproc.vertices.ptr[a].normal.x;
2279                         no[1]= mbproc.vertices.ptr[a].normal.y;
2280                         no[2]= mbproc.vertices.ptr[a].normal.z;
2281                 }
2282         }
2283
2284         freepolygonize(&mbproc);
2285 }
2286