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