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