converted more mixed tab/space indentations to tabs. only whitespace changes.
[blender.git] / source / blender / blenlib / intern / boxpack2d.c
1 /*
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * Contributor(s): Campbell Barton
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/blenlib/intern/boxpack2d.c
25  *  \ingroup bli
26  */
27
28
29 #include <stdlib.h> /* for qsort */
30
31 #include "MEM_guardedalloc.h"
32 #include "BLI_boxpack2d.h"
33  
34 /* BoxPacker for backing 2D rectangles into a square
35  * 
36  * The defined Below are for internal use only */
37
38 typedef struct boxVert {
39         float x;
40         float y;
41         short free;
42
43         struct boxPack *trb; /* top right box */
44         struct boxPack *blb; /* bottom left box */
45         struct boxPack *brb; /* bottom right box */
46         struct boxPack *tlb; /* top left box */
47
48         /* Store last intersecting boxes here
49          * speedup intersection testing */
50         struct boxPack *isect_cache[4];
51
52         int index;
53 } boxVert;
54
55 /* free vert flags */
56 #define eps 0.0000001f
57 #define BLF 1
58 #define TRF 2
59 #define TLF 4
60 #define BRF 8
61 #define CORNERFLAGS (BLF|TRF|TLF|BRF)
62
63 #define BL 0
64 #define TR 1
65 #define TL 2
66 #define BR 3
67
68 #define BOXLEFT(b)              b->v[BL]->x
69 #define BOXRIGHT(b)             b->v[TR]->x
70 #define BOXBOTTOM(b)    b->v[BL]->y
71 #define BOXTOP(b)               b->v[TR]->y
72 #define BOXAREA(b)              (b->w * b->h)
73
74 #define UPDATE_V34X(b)  b->v[TL]->x = b->v[BL]->x;\
75                                                 b->v[BR]->x = b->v[TR]->x
76 #define UPDATE_V34Y(b)  b->v[TL]->y = b->v[TR]->y;\
77                                                 b->v[BR]->y = b->v[BL]->y
78 #define UPDATE_V34(b) UPDATE_V34X(b); UPDATE_V34Y(b)  
79
80 #define SET_BOXLEFT(b, f)       b->v[TR]->x = f + b->w;\
81                                                         b->v[BL]->x = f;\
82                                                         UPDATE_V34X(b)
83 #define SET_BOXRIGHT(b, f)      b->v[BL]->x = f - b->w;\
84                                                         b->v[TR]->x = f;\
85                                                         UPDATE_V34X(b)
86 #define SET_BOXBOTTOM(b, f)     b->v[TR]->y = f + b->h;\
87                                                         b->v[BL]->y = f;\
88                                                         UPDATE_V34Y(b)
89 #define SET_BOXTOP(b, f)        b->v[BL]->y = f - b->h;\
90                                                         b->v[TR]->y = f;\
91                                                         UPDATE_V34Y(b)
92 #define BOXINTERSECT(b1, b2)\
93         (!( BOXLEFT(b1)+eps>=BOXRIGHT(b2) ||\
94                 BOXBOTTOM(b1)+eps>=BOXTOP(b2) ||\
95                 BOXRIGHT(b1)-eps<=BOXLEFT(b2) ||\
96                 BOXTOP(b1)-eps<=BOXBOTTOM(b2) ))
97
98 #define MIN2(x,y)               ( (x)<(y) ? (x) : (y) )
99 #define MAX2(x,y)               ( (x)>(y) ? (x) : (y) )
100
101 /* #define BOXDEBUG(b)\
102  *              printf("\tBox Debug i %i, w:%.3f h:%.3f x:%.3f y:%.3f\n",\
103  *              b->index, b->w, b->h, b->x, b->y) */
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 boxPack2D(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         
213         /* Pack the First box!
214          * then enter the main box-packing loop */
215         
216         box = boxarray; /* get the first box  */
217         /* First time, no boxes packed */
218         box->v[BL]->free = 0; /* Can't use any if these */
219         box->v[BR]->free &= ~(BLF|BRF);
220         box->v[TL]->free &= ~(BLF|TLF);
221         
222         *tot_width = box->w;
223         *tot_height = box->h; 
224         
225         /* This sets all the vertex locations */
226         SET_BOXLEFT(box, 0.0f);
227         SET_BOXBOTTOM(box, 0.0f);
228         box->x = box->y = 0.0f;
229         
230         for (i=0; i<3; i++)
231                 vertex_pack_indices[i] = box->v[i+1]->index; 
232         verts_pack_len = 3;
233         box++; /* next box, needed for the loop below */
234         /* ...done packing the first box */
235
236         /* Main boxpacking loop */
237         for (box_index=1; box_index < len; box_index++, box++) {
238                 
239                 /* These static floatds are used for sorting */
240                 box_width = box->w;
241                 box_height = box->h;
242                 
243                 qsort(vertex_pack_indices, verts_pack_len, sizeof(int), vertex_sort);
244                 
245                 /* Pack the box in with the others */
246                 /* sort the verts */
247                 isect = 1;
248                 
249                 for (i=0; i<verts_pack_len && isect; i++) {
250                         vert = vertarray + vertex_pack_indices[i];
251                         /* printf("\ttesting vert %i %i %i %f %f\n", i,
252                          *              vert->free, verts_pack_len, vert->x, vert->y); */
253                         
254                         /* This vert has a free quadrant
255                          * Test if we can place the box here
256                          * vert->free & quad_flags[j] - Checks 
257                          * */
258                                                 
259                         for (j=0; (j<4) && isect; j++) {
260                                 if (vert->free & quad_flags[j]) {
261                                         switch (j) {
262                                         case BL:
263                                                 SET_BOXRIGHT(box, vert->x);
264                                                 SET_BOXTOP(box, vert->y);
265                                                 break;
266                                         case TR:
267                                                 SET_BOXLEFT(box, vert->x);
268                                                 SET_BOXBOTTOM(box, vert->y);
269                                                 break;
270                                         case TL:
271                                                 SET_BOXRIGHT(box, vert->x);
272                                                 SET_BOXBOTTOM(box, vert->y);
273                                                 break;
274                                         case BR:
275                                                 SET_BOXLEFT(box, vert->x);
276                                                 SET_BOXTOP(box, vert->y);
277                                                 break;
278                                         }
279                                         
280                                         /* Now we need to check that the box intersects
281                                           * with any other boxes
282                                           * Assume no intersection... */
283                                         isect = 0;
284                                         
285                                         if (/* Constrain boxes to positive X/Y values */
286                                                 BOXLEFT(box)<0.0f || BOXBOTTOM(box) < 0.0f ||
287                                                 /* check for last intersected */
288                                                 (       vert->isect_cache[j] &&
289                                                         BOXINTERSECT(box, vert->isect_cache[j]) )
290                                            ) {
291                                                 /* Here we check that the last intersected
292                                                  * box will intersect with this one using
293                                                  * isect_cache that can store a pointer to a
294                                                  * box for each quadrant
295                                                  * big speedup */
296                                                 isect = 1;
297                                         } else {
298                                                 /* do a full search for colliding box
299                                                  * this is really slow, some spacialy 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                                                 } else if (BOXBOTTOM(box) <= 0) {
350                                                         box->v[BL]->free &= ~(BRF|BLF);
351                                                         box->v[BR]->free &= ~(BRF|BLF);
352                                                 }
353                                                 
354                                                 /* The following block of code does a logical
355                                                  * check with 2 adjacent boxes, its possible to
356                                                  * flag verts on one or both of the boxes 
357                                                  * as being used by checking the width or
358                                                  * height of both boxes */
359                                                 if (vert->tlb && vert->trb &&
360                                                                         (box == vert->tlb || box == vert->trb)) {
361                                                         if (vert->tlb->h > vert->trb->h) {
362                                                                 vert->trb->v[TL]->free &= ~(TLF|BLF);
363                                                         } else if (vert->tlb->h < vert->trb->h) {
364                                                                 vert->tlb->v[TR]->free &= ~(TRF|BRF);
365                                                         } else { /*same*/
366                                                                 vert->tlb->v[TR]->free &= ~BLF;
367                                                                 vert->trb->v[TL]->free &= ~BRF;
368                                                         }
369                                                 } else if (vert->blb && vert->brb &&
370                                                                         (box == vert->blb || box == vert->brb)) {
371                                                         if (vert->blb->h > vert->brb->h) {
372                                                                 vert->brb->v[BL]->free &= ~(TLF|BLF);
373                                                         } else if (vert->blb->h < vert->brb->h) {
374                                                                 vert->blb->v[BR]->free &= ~(TRF|BRF);
375                                                         } else { /*same*/
376                                                                 vert->blb->v[BR]->free &= ~TRF;
377                                                                 vert->brb->v[BL]->free &= ~TLF;
378                                                         }
379                                                 }
380                                                 /* Horizontal */
381                                                 if (vert->tlb && vert->blb &&
382                                                                         (box == vert->tlb || box == vert->blb) ) {
383                                                         if (vert->tlb->w > vert->blb->w) {
384                                                                 vert->blb->v[TL]->free &= ~(TLF|TRF);
385                                                         } else if (vert->tlb->w < vert->blb->w) {
386                                                                 vert->tlb->v[BL]->free &= ~(BLF|BRF);
387                                                         } else { /*same*/
388                                                                 vert->blb->v[TL]->free &= ~TRF;
389                                                                 vert->tlb->v[BL]->free &= ~BRF;
390                                                         }
391                                                 } else if (     vert->trb && vert->brb &&
392                                                                         (box == vert->trb || box == vert->brb) ) {
393                                                         if (vert->trb->w > vert->brb->w) {
394                                                                 vert->brb->v[TR]->free &= ~(TRF|TRF);
395                                                         } else if (vert->trb->w < vert->brb->w) {
396                                                                 vert->trb->v[BR]->free &= ~(BLF|BRF);
397                                                         } else { /*same*/
398                                                                 vert->brb->v[TR]->free &= ~TLF;
399                                                                 vert->trb->v[BR]->free &= ~BLF;
400                                                         }
401                                                 }
402                                                 /* End logical check */
403                                                 
404                                                 
405                                                 for (k=0; k<4; k++) {
406                                                         if (box->v[k] != vert) {
407                                                                 vertex_pack_indices[verts_pack_len] =
408                                                                                         box->v[k]->index; 
409                                                                 verts_pack_len++;
410                                                         }
411                                                 }
412                                                 /* The Box verts are only used internally
413                                                  * Update the box x and y since thats what external
414                                                  * functions will see */
415                                                 box->x = BOXLEFT(box);
416                                                 box->y = BOXBOTTOM(box);
417                                         }
418                                 }       
419                         }
420                 }
421         }
422
423         /* free all the verts, not really needed because they shouldn't be
424          * touched anymore but accessing the pointers would crash blender */
425         for (box_index=0; box_index < len; box_index++) {
426                 box = boxarray+box_index; 
427                 box->v[0] = box->v[1] = box->v[2] = box->v[3] = NULL; 
428         }
429         MEM_freeN(vertex_pack_indices);
430         MEM_freeN(vertarray);
431 }
432