style cleanyp
[blender.git] / source / blender / blenlib / intern / boxpack2d.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  * Contributor(s): Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/blenlib/intern/boxpack2d.c
24  *  \ingroup bli
25  */
26
27 #include <stdlib.h> /* for qsort */
28
29 #include "MEM_guardedalloc.h"
30 #include "BLI_boxpack2d.h"
31
32 /* BoxPacker for backing 2D rectangles into a square
33  * 
34  * The defined Below are for internal use only */
35
36 typedef struct BoxVert {
37         float x;
38         float y;
39         short free;
40
41         struct BoxPack *trb; /* top right box */
42         struct BoxPack *blb; /* bottom left box */
43         struct BoxPack *brb; /* bottom right box */
44         struct BoxPack *tlb; /* top left box */
45
46         /* Store last intersecting boxes here
47          * speedup intersection testing */
48         struct BoxPack *isect_cache[4];
49
50         int index;
51 } BoxVert;
52
53 /* free vert flags */
54 #define EPSILON 0.0000001f
55 #define BLF 1
56 #define TRF 2
57 #define TLF 4
58 #define BRF 8
59 #define CORNERFLAGS (BLF | TRF | TLF | BRF)
60
61 #define BL 0
62 #define TR 1
63 #define TL 2
64 #define BR 3
65
66 #define BOXLEFT(b)      ((b)->v[BL]->x)
67 #define BOXRIGHT(b)     ((b)->v[TR]->x)
68 #define BOXBOTTOM(b)    ((b)->v[BL]->y)
69 #define BOXTOP(b)       ((b)->v[TR]->y)
70 #define BOXAREA(b)      ((b)->w * (b)->h)
71
72 #define UPDATE_V34X(b)  ((b)->v[TL]->x = (b)->v[BL]->x); \
73                         ((b)->v[BR]->x = (b)->v[TR]->x)
74 #define UPDATE_V34Y(b)  ((b)->v[TL]->y = (b)->v[TR]->y); \
75                         ((b)->v[BR]->y = (b)->v[BL]->y)
76 #define UPDATE_V34(b) UPDATE_V34X(b); UPDATE_V34Y(b)
77
78 #define SET_BOXLEFT(b, f)   (b)->v[TR]->x = f + (b)->w; \
79                             (b)->v[BL]->x = f;          \
80                             UPDATE_V34X(b)
81 #define SET_BOXRIGHT(b, f)  (b)->v[BL]->x = f - (b)->w; \
82                             (b)->v[TR]->x = f;          \
83                             UPDATE_V34X(b)
84 #define SET_BOXBOTTOM(b, f) (b)->v[TR]->y = f + (b)->h; \
85                             (b)->v[BL]->y = f;          \
86                             UPDATE_V34Y(b)
87 #define SET_BOXTOP(b, f)    (b)->v[BL]->y = f - (b)->h; \
88                             (b)->v[TR]->y = f;          \
89                             UPDATE_V34Y(b)
90 #define BOXINTERSECT(b1, b2)                 \
91     !(BOXLEFT(b1)   + EPSILON >= BOXRIGHT(b2) || \
92       BOXBOTTOM(b1) + EPSILON >= BOXTOP(b2)   || \
93       BOXRIGHT(b1)  - EPSILON <= BOXLEFT(b2)  || \
94       BOXTOP(b1)    - EPSILON <= BOXBOTTOM(b2))
95
96 #define MIN2(x, y)              ((x) < (y) ? (x) : (y))
97 #define MAX2(x, y)              ((x) > (y) ? (x) : (y))
98
99 #if 0
100 #define BOXDEBUG(b) \
101         printf("\tBox Debug i %i, w:%.3f h:%.3f x:%.3f y:%.3f\n", \
102                b->index, b->w, b->h, b->x, b->y)
103 #endif
104
105 /* qsort function - sort largest to smallest */
106 static int box_areasort(const void *p1, const void *p2)
107 {
108         const BoxPack *b1 = p1, *b2 = p2;
109         const float a1 = BOXAREA(b1);
110         const float a2 = BOXAREA(b2);
111
112         if      (a1 < a2) return  1;
113         else if (a1 > a2) return -1;
114         return 0;
115 }
116
117 /* qsort vertex sorting function
118  * sorts from lower left to top right It uses the current box's width and height 
119  * as offsets when sorting, this has the result of not placing boxes outside
120  * the bounds of the existing backed area where possible
121  * */
122 static float box_width;
123 static float box_height;
124 static BoxVert *vertarray;
125
126 static int vertex_sort(const void *p1, const void *p2)
127 {
128         BoxVert *v1, *v2;
129         float a1, a2;
130
131         v1 = vertarray + ((int *)p1)[0];
132         v2 = vertarray + ((int *)p2)[0];
133
134         a1 = MAX2(v1->x + box_width, v1->y + box_height);
135         a2 = MAX2(v2->x + box_width, v2->y + box_height);
136
137         /* sort largest to smallest */
138         if      (a1 > a2) return 1;
139         else if (a1 < a2) return -1;
140         return 0;
141 }
142 /* Main boxpacking function accessed from other functions
143  * This sets boxes x,y to positive values, sorting from 0,0 outwards.
144  * There is no limit to the space boxes may take, only that they will be packed
145  * tightly into the lower left hand corner (0,0)
146  * 
147  * boxarray - a pre allocated array of boxes.
148  *      only the 'box->x' and 'box->y' are set, 'box->w' and 'box->h' are used,
149  *      'box->index' is not used at all, the only reason its there
150  *          is that the box array is sorted by area and programs need to be able
151  *          to have some way of writing the boxes back to the original data.
152  *  len - the number of boxes in the array.
153  *      tot_width and tot_height are set so you can normalize the data.
154  *  */
155 void BLI_box_pack_2D(BoxPack *boxarray, const int len, float *tot_width, float *tot_height)
156 {
157         BoxVert *vert; /* the current vert */
158         int box_index, verts_pack_len, i, j, k, isect;
159         int quad_flags[4] = {BLF, TRF, TLF, BRF}; /* use for looping */
160         BoxPack *box, *box_test; /*current box and another for intersection tests*/
161         int *vertex_pack_indices; /*an array of indices used for sorting verts*/
162
163         if (!len) {
164                 *tot_width = 0.0f;
165                 *tot_height = 0.0f;
166                 return;
167         }
168
169         /* Sort boxes, biggest first */
170         qsort(boxarray, len, sizeof(BoxPack), box_areasort);
171
172         /* add verts to the boxes, these are only used internally  */
173         vert = vertarray = MEM_mallocN(len * 4 * sizeof(BoxVert), "BoxPack Verts");
174         vertex_pack_indices = MEM_mallocN(len * 3 * sizeof(int), "BoxPack Indices");
175
176         for (box = boxarray, box_index = 0, i = 0; box_index < len; box_index++, box++) {
177
178                 vert->blb = vert->brb = vert->tlb =
179                             vert->isect_cache[0] = vert->isect_cache[1] =
180                             vert->isect_cache[2] = vert->isect_cache[3] = NULL;
181                 vert->free = CORNERFLAGS & ~TRF;
182                 vert->trb = box;
183                 vert->index = i; i++;
184                 box->v[BL] = vert; vert++;
185                 
186                 vert->trb = vert->brb = vert->tlb =
187                             vert->isect_cache[0] = vert->isect_cache[1] =
188                             vert->isect_cache[2] = vert->isect_cache[3] = NULL;
189                 vert->free = CORNERFLAGS & ~BLF;
190                 vert->blb = box;
191                 vert->index = i; i++;
192                 box->v[TR] = vert; vert++;
193                 
194                 vert->trb = vert->blb = vert->tlb =
195                             vert->isect_cache[0] = vert->isect_cache[1] =
196                             vert->isect_cache[2] = vert->isect_cache[3] = NULL;
197                 vert->free = CORNERFLAGS & ~BRF;
198                 vert->brb = box;
199                 vert->index = i; i++;
200                 box->v[TL] = vert; vert++;
201                 
202                 vert->trb = vert->blb = vert->brb =
203                             vert->isect_cache[0] = vert->isect_cache[1] =
204                             vert->isect_cache[2] = vert->isect_cache[3] = NULL;
205                 vert->free = CORNERFLAGS & ~TLF;
206                 vert->tlb = box; 
207                 vert->index = i; i++;
208                 box->v[BR] = vert; vert++;
209         }
210         vert = NULL;
211
212         /* Pack the First box!
213          * then enter the main box-packing loop */
214
215         box = boxarray; /* get the first box  */
216         /* First time, no boxes packed */
217         box->v[BL]->free = 0; /* Can't use any if these */
218         box->v[BR]->free &= ~(BLF | BRF);
219         box->v[TL]->free &= ~(BLF | TLF);
220
221         *tot_width = box->w;
222         *tot_height = box->h;
223
224         /* This sets all the vertex locations */
225         SET_BOXLEFT(box, 0.0f);
226         SET_BOXBOTTOM(box, 0.0f);
227         box->x = box->y = 0.0f;
228
229         for (i = 0; i < 3; i++)
230                 vertex_pack_indices[i] = box->v[i + 1]->index;
231         verts_pack_len = 3;
232         box++; /* next box, needed for the loop below */
233         /* ...done packing the first box */
234
235         /* Main boxpacking loop */
236         for (box_index = 1; box_index < len; box_index++, box++) {
237
238                 /* These static floatds are used for sorting */
239                 box_width = box->w;
240                 box_height = box->h;
241
242                 qsort(vertex_pack_indices, verts_pack_len, sizeof(int), vertex_sort);
243
244                 /* Pack the box in with the others */
245                 /* sort the verts */
246                 isect = 1;
247
248                 for (i = 0; i < verts_pack_len && isect; i++) {
249                         vert = vertarray + vertex_pack_indices[i];
250                         /* printf("\ttesting vert %i %i %i %f %f\n", i,
251                          *        vert->free, verts_pack_len, vert->x, vert->y); */
252
253                         /* This vert has a free quadrant
254                          * Test if we can place the box here
255                          * vert->free & quad_flags[j] - Checks 
256                          * */
257
258                         for (j = 0; (j < 4) && isect; j++) {
259                                 if (vert->free & quad_flags[j]) {
260                                         switch (j) {
261                                                 case BL:
262                                                         SET_BOXRIGHT(box, vert->x);
263                                                         SET_BOXTOP(box, vert->y);
264                                                         break;
265                                                 case TR:
266                                                         SET_BOXLEFT(box, vert->x);
267                                                         SET_BOXBOTTOM(box, vert->y);
268                                                         break;
269                                                 case TL:
270                                                         SET_BOXRIGHT(box, vert->x);
271                                                         SET_BOXBOTTOM(box, vert->y);
272                                                         break;
273                                                 case BR:
274                                                         SET_BOXLEFT(box, vert->x);
275                                                         SET_BOXTOP(box, vert->y);
276                                                         break;
277                                         }
278
279                                         /* Now we need to check that the box intersects
280                                          * with any other boxes
281                                          * Assume no intersection... */
282                                         isect = 0;
283                                         
284                                         if ( /* Constrain boxes to positive X/Y values */
285                                             BOXLEFT(box) < 0.0f || BOXBOTTOM(box) < 0.0f ||
286                                             /* check for last intersected */
287                                             (vert->isect_cache[j] &&
288                                              BOXINTERSECT(box, vert->isect_cache[j])))
289                                         {
290                                                 /* Here we check that the last intersected
291                                                  * box will intersect with this one using
292                                                  * isect_cache that can store a pointer to a
293                                                  * box for each quadrant
294                                                  * big speedup */
295                                                 isect = 1;
296                                         }
297                                         else {
298                                                 /* do a full search for colliding box
299                                                  * this is really slow, some spatially divided
300                                                  * data-structure would be better */
301                                                 for (box_test = boxarray; box_test != box; box_test++) {
302                                                         if (BOXINTERSECT(box, box_test)) {
303                                                                 /* Store the last intersecting here as cache
304                                                                  * for faster checking next time around */
305                                                                 vert->isect_cache[j] = box_test;
306                                                                 isect = 1;
307                                                                 break;
308                                                         }
309                                                 }
310                                         }
311
312                                         if (!isect) {
313
314                                                 /* maintain the total width and height */
315                                                 (*tot_width) = MAX2(BOXRIGHT(box), (*tot_width));
316                                                 (*tot_height) = MAX2(BOXTOP(box), (*tot_height));
317
318                                                 /* Place the box */
319                                                 vert->free &= ~quad_flags[j];
320
321                                                 switch (j) {
322                                                         case TR:
323                                                                 box->v[BL] = vert;
324                                                                 vert->trb = box;
325                                                                 break;
326                                                         case TL:
327                                                                 box->v[BR] = vert;
328                                                                 vert->tlb = box;
329                                                                 break;
330                                                         case BR:
331                                                                 box->v[TL] = vert;
332                                                                 vert->brb = box;
333                                                                 break;
334                                                         case BL:
335                                                                 box->v[TR] = vert;
336                                                                 vert->blb = box;
337                                                                 break;
338                                                 }
339
340                                                 /* Mask free flags for verts that are
341                                                  * on the bottom or side so we don't get
342                                                  * boxes outside the given rectangle ares
343                                                  * 
344                                                  * We can do an else/if here because only the first 
345                                                  * box can be at the very bottom left corner */
346                                                 if (BOXLEFT(box) <= 0) {
347                                                         box->v[TL]->free &= ~(TLF | BLF);
348                                                         box->v[BL]->free &= ~(TLF | BLF);
349                                                 }
350                                                 else if (BOXBOTTOM(box) <= 0) {
351                                                         box->v[BL]->free &= ~(BRF | BLF);
352                                                         box->v[BR]->free &= ~(BRF | BLF);
353                                                 }
354
355                                                 /* The following block of code does a logical
356                                                  * check with 2 adjacent boxes, its possible to
357                                                  * flag verts on one or both of the boxes 
358                                                  * as being used by checking the width or
359                                                  * height of both boxes */
360                                                 if (vert->tlb && vert->trb && (box == vert->tlb || box == vert->trb)) {
361                                                         if (vert->tlb->h > vert->trb->h) {
362                                                                 vert->trb->v[TL]->free &= ~(TLF | BLF);
363                                                         }
364                                                         else if (vert->tlb->h < vert->trb->h) {
365                                                                 vert->tlb->v[TR]->free &= ~(TRF | BRF);
366                                                         }
367                                                         else { /*same*/
368                                                                 vert->tlb->v[TR]->free &= ~BLF;
369                                                                 vert->trb->v[TL]->free &= ~BRF;
370                                                         }
371                                                 }
372                                                 else if (vert->blb && vert->brb && (box == vert->blb || box == vert->brb)) {
373                                                         if (vert->blb->h > vert->brb->h) {
374                                                                 vert->brb->v[BL]->free &= ~(TLF | BLF);
375                                                         }
376                                                         else if (vert->blb->h < vert->brb->h) {
377                                                                 vert->blb->v[BR]->free &= ~(TRF | BRF);
378                                                         }
379                                                         else { /*same*/
380                                                                 vert->blb->v[BR]->free &= ~TRF;
381                                                                 vert->brb->v[BL]->free &= ~TLF;
382                                                         }
383                                                 }
384                                                 /* Horizontal */
385                                                 if (vert->tlb && vert->blb && (box == vert->tlb || box == vert->blb)) {
386                                                         if (vert->tlb->w > vert->blb->w) {
387                                                                 vert->blb->v[TL]->free &= ~(TLF | TRF);
388                                                         }
389                                                         else if (vert->tlb->w < vert->blb->w) {
390                                                                 vert->tlb->v[BL]->free &= ~(BLF | BRF);
391                                                         }
392                                                         else { /*same*/
393                                                                 vert->blb->v[TL]->free &= ~TRF;
394                                                                 vert->tlb->v[BL]->free &= ~BRF;
395                                                         }
396                                                 }
397                                                 else if (vert->trb && vert->brb && (box == vert->trb || box == vert->brb)) {
398                                                         if (vert->trb->w > vert->brb->w) {
399                                                                 vert->brb->v[TR]->free &= ~(TLF | TRF);
400                                                         }
401                                                         else if (vert->trb->w < vert->brb->w) {
402                                                                 vert->trb->v[BR]->free &= ~(BLF | BRF);
403                                                         }
404                                                         else { /*same*/
405                                                                 vert->brb->v[TR]->free &= ~TLF;
406                                                                 vert->trb->v[BR]->free &= ~BLF;
407                                                         }
408                                                 }
409                                                 /* End logical check */
410
411                                                 for (k = 0; k < 4; k++) {
412                                                         if (box->v[k] != vert) {
413                                                                 vertex_pack_indices[verts_pack_len] = box->v[k]->index;
414                                                                 verts_pack_len++;
415                                                         }
416                                                 }
417                                                 /* The Box verts are only used internally
418                                                  * Update the box x and y since thats what external
419                                                  * functions will see */
420                                                 box->x = BOXLEFT(box);
421                                                 box->y = BOXBOTTOM(box);
422                                         }
423                                 }
424                         }
425                 }
426         }
427
428         /* free all the verts, not really needed because they shouldn't be
429          * touched anymore but accessing the pointers would crash blender */
430         for (box_index = 0; box_index < len; box_index++) {
431                 box = boxarray + box_index;
432                 box->v[0] = box->v[1] = box->v[2] = box->v[3] = NULL;
433         }
434         MEM_freeN(vertex_pack_indices);
435         MEM_freeN(vertarray);
436 }
437