Release 1.5.29.
[wine] / dlls / gdi32 / region.c
1 /*
2  * GDI region objects. Shamelessly ripped out from the X11 distribution
3  * Thanks for the nice license.
4  *
5  * Copyright 1993, 1994, 1995 Alexandre Julliard
6  * Modifications and additions: Copyright 1998 Huw Davies
7  *                                        1999 Alex Korobka
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 /************************************************************************
25
26 Copyright (c) 1987, 1988  X Consortium
27
28 Permission is hereby granted, free of charge, to any person obtaining a copy
29 of this software and associated documentation files (the "Software"), to deal
30 in the Software without restriction, including without limitation the rights
31 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
32 copies of the Software, and to permit persons to whom the Software is
33 furnished to do so, subject to the following conditions:
34
35 The above copyright notice and this permission notice shall be included in
36 all copies or substantial portions of the Software.
37
38 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
41 X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
42 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
43 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
44
45 Except as contained in this notice, the name of the X Consortium shall not be
46 used in advertising or otherwise to promote the sale, use or other dealings
47 in this Software without prior written authorization from the X Consortium.
48
49
50 Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts.
51
52                         All Rights Reserved
53
54 Permission to use, copy, modify, and distribute this software and its
55 documentation for any purpose and without fee is hereby granted,
56 provided that the above copyright notice appear in all copies and that
57 both that copyright notice and this permission notice appear in
58 supporting documentation, and that the name of Digital not be
59 used in advertising or publicity pertaining to distribution of the
60 software without specific, written prior permission.
61
62 DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
63 ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
64 DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
65 ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
66 WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
67 ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
68 SOFTWARE.
69
70 ************************************************************************/
71 /*
72  * The functions in this file implement the Region abstraction, similar to one
73  * used in the X11 sample server. A Region is simply an area, as the name
74  * implies, and is implemented as a "y-x-banded" array of rectangles. To
75  * explain: Each Region is made up of a certain number of rectangles sorted
76  * by y coordinate first, and then by x coordinate.
77  *
78  * Furthermore, the rectangles are banded such that every rectangle with a
79  * given upper-left y coordinate (y1) will have the same lower-right y
80  * coordinate (y2) and vice versa. If a rectangle has scanlines in a band, it
81  * will span the entire vertical distance of the band. This means that some
82  * areas that could be merged into a taller rectangle will be represented as
83  * several shorter rectangles to account for shorter rectangles to its left
84  * or right but within its "vertical scope".
85  *
86  * An added constraint on the rectangles is that they must cover as much
87  * horizontal area as possible. E.g. no two rectangles in a band are allowed
88  * to touch.
89  *
90  * Whenever possible, bands will be merged together to cover a greater vertical
91  * distance (and thus reduce the number of rectangles). Two bands can be merged
92  * only if the bottom of one touches the top of the other and they have
93  * rectangles in the same places (of the same width, of course). This maintains
94  * the y-x-banding that's so nice to have...
95  */
96
97 #include <stdarg.h>
98 #include <stdlib.h>
99 #include <string.h>
100 #include "windef.h"
101 #include "winbase.h"
102 #include "wingdi.h"
103 #include "gdi_private.h"
104 #include "wine/debug.h"
105
106 WINE_DEFAULT_DEBUG_CHANNEL(region);
107
108
109 static HGDIOBJ REGION_SelectObject( HGDIOBJ handle, HDC hdc );
110 static BOOL REGION_DeleteObject( HGDIOBJ handle );
111
112 static const struct gdi_obj_funcs region_funcs =
113 {
114     REGION_SelectObject,  /* pSelectObject */
115     NULL,                 /* pGetObjectA */
116     NULL,                 /* pGetObjectW */
117     NULL,                 /* pUnrealizeObject */
118     REGION_DeleteObject   /* pDeleteObject */
119 };
120
121 /* Check if two RECTs overlap. */
122 static inline BOOL overlapping( const RECT *r1, const RECT *r2 )
123 {
124     return (r1->right > r2->left && r1->left < r2->right &&
125             r1->bottom > r2->top && r1->top < r2->bottom);
126 }
127
128 static BOOL add_rect( WINEREGION *reg, INT left, INT top, INT right, INT bottom )
129 {
130     RECT *rect;
131     if (reg->numRects >= reg->size)
132     {
133         RECT *newrects = HeapReAlloc( GetProcessHeap(), 0, reg->rects, 2 * sizeof(RECT) * reg->size );
134         if (!newrects) return FALSE;
135         reg->rects = newrects;
136         reg->size *= 2;
137     }
138     rect = reg->rects + reg->numRects++;
139     rect->left = left;
140     rect->top = top;
141     rect->right = right;
142     rect->bottom = bottom;
143     return TRUE;
144 }
145
146 static inline void empty_region( WINEREGION *reg )
147 {
148     reg->numRects = 0;
149     reg->extents.left = reg->extents.top = reg->extents.right = reg->extents.bottom = 0;
150 }
151
152 static inline BOOL is_in_rect( const RECT *rect, int x, int y )
153 {
154     return (rect->right > x && rect->left <= x && rect->bottom > y && rect->top <= y);
155 }
156
157 /*
158  * number of points to buffer before sending them off
159  * to scanlines() :  Must be an even number
160  */
161 #define NUMPTSTOBUFFER 200
162
163 /*
164  * used to allocate buffers for points and link
165  * the buffers together
166  */
167
168 struct point_block
169 {
170     POINT pts[NUMPTSTOBUFFER];
171     int count;
172     struct point_block *next;
173 };
174
175 static struct point_block *add_point( struct point_block *block, int x, int y )
176 {
177     if (block->count == NUMPTSTOBUFFER)
178     {
179         struct point_block *new = HeapAlloc( GetProcessHeap(), 0, sizeof(*new) );
180         if (!new) return NULL;
181         block->next = new;
182         new->count = 0;
183         new->next = NULL;
184         block = new;
185     }
186     block->pts[block->count].x = x;
187     block->pts[block->count].y = y;
188     block->count++;
189     return block;
190 }
191
192 static void free_point_blocks( struct point_block *block )
193 {
194     while (block)
195     {
196         struct point_block *tmp = block->next;
197         HeapFree( GetProcessHeap(), 0, block );
198         block = tmp;
199     }
200 }
201
202
203 /*
204  *     This file contains a few macros to help track
205  *     the edge of a filled object.  The object is assumed
206  *     to be filled in scanline order, and thus the
207  *     algorithm used is an extension of Bresenham's line
208  *     drawing algorithm which assumes that y is always the
209  *     major axis.
210  *     Since these pieces of code are the same for any filled shape,
211  *     it is more convenient to gather the library in one
212  *     place, but since these pieces of code are also in
213  *     the inner loops of output primitives, procedure call
214  *     overhead is out of the question.
215  *     See the author for a derivation if needed.
216  */
217
218
219 /*
220  *     This structure contains all of the information needed
221  *     to run the bresenham algorithm.
222  *     The variables may be hardcoded into the declarations
223  *     instead of using this structure to make use of
224  *     register declarations.
225  */
226 struct bres_info
227 {
228     INT minor_axis;     /* minor axis        */
229     INT d;              /* decision variable */
230     INT m, m1;          /* slope and slope+1 */
231     INT incr1, incr2;   /* error increments */
232 };
233
234
235 /*
236  *  In scan converting polygons, we want to choose those pixels
237  *  which are inside the polygon.  Thus, we add .5 to the starting
238  *  x coordinate for both left and right edges.  Now we choose the
239  *  first pixel which is inside the pgon for the left edge and the
240  *  first pixel which is outside the pgon for the right edge.
241  *  Draw the left pixel, but not the right.
242  *
243  *  How to add .5 to the starting x coordinate:
244  *      If the edge is moving to the right, then subtract dy from the
245  *  error term from the general form of the algorithm.
246  *      If the edge is moving to the left, then add dy to the error term.
247  *
248  *  The reason for the difference between edges moving to the left
249  *  and edges moving to the right is simple:  If an edge is moving
250  *  to the right, then we want the algorithm to flip immediately.
251  *  If it is moving to the left, then we don't want it to flip until
252  *  we traverse an entire pixel.
253  */
254 static inline void bres_init_polygon( int dy, int x1, int x2, struct bres_info *bres )
255 {
256     int dx;
257
258     /*
259      *  if the edge is horizontal, then it is ignored
260      *  and assumed not to be processed.  Otherwise, do this stuff.
261      */
262     if (!dy) return;
263
264     bres->minor_axis = x1;
265     dx = x2 - x1;
266     if (dx < 0)
267     {
268         bres->m = dx / dy;
269         bres->m1 = bres->m - 1;
270         bres->incr1 = -2 * dx + 2 * dy * bres->m1;
271         bres->incr2 = -2 * dx + 2 * dy * bres->m;
272         bres->d = 2 * bres->m * dy - 2 * dx - 2 * dy;
273     }
274     else
275     {
276         bres->m = dx / (dy);
277         bres->m1 = bres->m + 1;
278         bres->incr1 = 2 * dx - 2 * dy * bres->m1;
279         bres->incr2 = 2 * dx - 2 * dy * bres->m;
280         bres->d = -2 * bres->m * dy + 2 * dx;
281     }
282 }
283
284 static inline void bres_incr_polygon( struct bres_info *bres )
285 {
286     if (bres->m1 > 0) {
287         if (bres->d > 0) {
288             bres->minor_axis += bres->m1;
289             bres->d += bres->incr1;
290         }
291         else {
292             bres->minor_axis += bres->m;
293             bres->d += bres->incr2;
294         }
295     } else {
296         if (bres->d >= 0) {
297             bres->minor_axis += bres->m1;
298             bres->d += bres->incr1;
299         }
300         else {
301             bres->minor_axis += bres->m;
302             bres->d += bres->incr2;
303         }
304     }
305 }
306
307
308 /*
309  *     These are the data structures needed to scan
310  *     convert regions.  Two different scan conversion
311  *     methods are available -- the even-odd method, and
312  *     the winding number method.
313  *     The even-odd rule states that a point is inside
314  *     the polygon if a ray drawn from that point in any
315  *     direction will pass through an odd number of
316  *     path segments.
317  *     By the winding number rule, a point is decided
318  *     to be inside the polygon if a ray drawn from that
319  *     point in any direction passes through a different
320  *     number of clockwise and counter-clockwise path
321  *     segments.
322  *
323  *     These data structures are adapted somewhat from
324  *     the algorithm in (Foley/Van Dam) for scan converting
325  *     polygons.
326  *     The basic algorithm is to start at the top (smallest y)
327  *     of the polygon, stepping down to the bottom of
328  *     the polygon by incrementing the y coordinate.  We
329  *     keep a list of edges which the current scanline crosses,
330  *     sorted by x.  This list is called the Active Edge Table (AET)
331  *     As we change the y-coordinate, we update each entry in
332  *     in the active edge table to reflect the edges new xcoord.
333  *     This list must be sorted at each scanline in case
334  *     two edges intersect.
335  *     We also keep a data structure known as the Edge Table (ET),
336  *     which keeps track of all the edges which the current
337  *     scanline has not yet reached.  The ET is basically a
338  *     list of ScanLineList structures containing a list of
339  *     edges which are entered at a given scanline.  There is one
340  *     ScanLineList per scanline at which an edge is entered.
341  *     When we enter a new edge, we move it from the ET to the AET.
342  *
343  *     From the AET, we can implement the even-odd rule as in
344  *     (Foley/Van Dam).
345  *     The winding number rule is a little trickier.  We also
346  *     keep the EdgeTableEntries in the AET linked by the
347  *     nextWETE (winding EdgeTableEntry) link.  This allows
348  *     the edges to be linked just as before for updating
349  *     purposes, but only uses the edges linked by the nextWETE
350  *     link as edges representing spans of the polygon to
351  *     drawn (as with the even-odd rule).
352  */
353
354 typedef struct edge_table_entry {
355     struct list entry;
356     struct list winding_entry;
357     INT ymax;                     /* ycoord at which we exit this edge. */
358     struct bres_info bres;        /* Bresenham info to run the edge     */
359     int ClockWise;                /* flag for winding number rule       */
360 } EdgeTableEntry;
361
362
363 typedef struct _ScanLineList{
364     struct list edgelist;
365     INT scanline;            /* the scanline represented */
366     struct _ScanLineList *next;  /* next in the list       */
367 } ScanLineList;
368
369
370 typedef struct {
371      INT ymax;               /* ymax for the polygon     */
372      INT ymin;               /* ymin for the polygon     */
373      ScanLineList scanlines;   /* header node              */
374 } EdgeTable;
375
376
377 /*
378  * Here is a struct to help with storage allocation
379  * so we can allocate a big chunk at a time, and then take
380  * pieces from this heap when we need to.
381  */
382 #define SLLSPERBLOCK 25
383
384 typedef struct _ScanLineListBlock {
385      ScanLineList SLLs[SLLSPERBLOCK];
386      struct _ScanLineListBlock *next;
387 } ScanLineListBlock;
388
389
390 /* Note the parameter order is different from the X11 equivalents */
391
392 static BOOL REGION_CopyRegion(WINEREGION *d, WINEREGION *s);
393 static BOOL REGION_OffsetRegion(WINEREGION *d, WINEREGION *s, INT x, INT y);
394 static BOOL REGION_IntersectRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
395 static BOOL REGION_UnionRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
396 static BOOL REGION_SubtractRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
397 static BOOL REGION_XorRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
398 static BOOL REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn);
399
400 #define RGN_DEFAULT_RECTS       2
401
402
403 /***********************************************************************
404  *            get_region_type
405  */
406 static inline INT get_region_type( const WINEREGION *obj )
407 {
408     switch(obj->numRects)
409     {
410     case 0:  return NULLREGION;
411     case 1:  return SIMPLEREGION;
412     default: return COMPLEXREGION;
413     }
414 }
415
416
417 /***********************************************************************
418  *            REGION_DumpRegion
419  *            Outputs the contents of a WINEREGION
420  */
421 static void REGION_DumpRegion(WINEREGION *pReg)
422 {
423     RECT *pRect, *pRectEnd = pReg->rects + pReg->numRects;
424
425     TRACE("Region %p: %d,%d - %d,%d %d rects\n", pReg,
426             pReg->extents.left, pReg->extents.top,
427             pReg->extents.right, pReg->extents.bottom, pReg->numRects);
428     for(pRect = pReg->rects; pRect < pRectEnd; pRect++)
429         TRACE("\t%d,%d - %d,%d\n", pRect->left, pRect->top,
430                        pRect->right, pRect->bottom);
431     return;
432 }
433
434
435 /***********************************************************************
436  *            init_region
437  *
438  * Initialize a new empty region.
439  */
440 static BOOL init_region( WINEREGION *pReg, INT n )
441 {
442     if (!(pReg->rects = HeapAlloc(GetProcessHeap(), 0, n * sizeof( RECT )))) return FALSE;
443     pReg->size = n;
444     empty_region(pReg);
445     return TRUE;
446 }
447
448 /***********************************************************************
449  *           destroy_region
450  */
451 static void destroy_region( WINEREGION *pReg )
452 {
453     HeapFree( GetProcessHeap(), 0, pReg->rects );
454 }
455
456 /***********************************************************************
457  *           REGION_DeleteObject
458  */
459 static BOOL REGION_DeleteObject( HGDIOBJ handle )
460 {
461     WINEREGION *rgn = free_gdi_handle( handle );
462
463     if (!rgn) return FALSE;
464     HeapFree( GetProcessHeap(), 0, rgn->rects );
465     HeapFree( GetProcessHeap(), 0, rgn );
466     return TRUE;
467 }
468
469 /***********************************************************************
470  *           REGION_SelectObject
471  */
472 static HGDIOBJ REGION_SelectObject( HGDIOBJ handle, HDC hdc )
473 {
474     return ULongToHandle(SelectClipRgn( hdc, handle ));
475 }
476
477
478 /***********************************************************************
479  *           REGION_OffsetRegion
480  *           Offset a WINEREGION by x,y
481  */
482 static BOOL REGION_OffsetRegion( WINEREGION *rgn, WINEREGION *srcrgn, INT x, INT y )
483 {
484     if( rgn != srcrgn)
485     {
486         if (!REGION_CopyRegion( rgn, srcrgn)) return FALSE;
487     }
488     if(x || y) {
489         int nbox = rgn->numRects;
490         RECT *pbox = rgn->rects;
491
492         if(nbox) {
493             while(nbox--) {
494                 pbox->left += x;
495                 pbox->right += x;
496                 pbox->top += y;
497                 pbox->bottom += y;
498                 pbox++;
499             }
500             rgn->extents.left += x;
501             rgn->extents.right += x;
502             rgn->extents.top += y;
503             rgn->extents.bottom += y;
504         }
505     }
506     return TRUE;
507 }
508
509 /***********************************************************************
510  *           OffsetRgn   (GDI32.@)
511  *
512  * Moves a region by the specified X- and Y-axis offsets.
513  *
514  * PARAMS
515  *   hrgn [I] Region to offset.
516  *   x    [I] Offset right if positive or left if negative.
517  *   y    [I] Offset down if positive or up if negative.
518  *
519  * RETURNS
520  *   Success:
521  *     NULLREGION - The new region is empty.
522  *     SIMPLEREGION - The new region can be represented by one rectangle.
523  *     COMPLEXREGION - The new region can only be represented by more than
524  *                     one rectangle.
525  *   Failure: ERROR
526  */
527 INT WINAPI OffsetRgn( HRGN hrgn, INT x, INT y )
528 {
529     WINEREGION *obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
530     INT ret;
531
532     TRACE("%p %d,%d\n", hrgn, x, y);
533
534     if (!obj)
535         return ERROR;
536
537     REGION_OffsetRegion( obj, obj, x, y);
538
539     ret = get_region_type( obj );
540     GDI_ReleaseObj( hrgn );
541     return ret;
542 }
543
544
545 /***********************************************************************
546  *           GetRgnBox    (GDI32.@)
547  *
548  * Retrieves the bounding rectangle of the region. The bounding rectangle
549  * is the smallest rectangle that contains the entire region.
550  *
551  * PARAMS
552  *   hrgn [I] Region to retrieve bounding rectangle from.
553  *   rect [O] Rectangle that will receive the coordinates of the bounding
554  *            rectangle.
555  *
556  * RETURNS
557  *     NULLREGION - The new region is empty.
558  *     SIMPLEREGION - The new region can be represented by one rectangle.
559  *     COMPLEXREGION - The new region can only be represented by more than
560  *                     one rectangle.
561  */
562 INT WINAPI GetRgnBox( HRGN hrgn, LPRECT rect )
563 {
564     WINEREGION *obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
565     if (obj)
566     {
567         INT ret;
568         rect->left = obj->extents.left;
569         rect->top = obj->extents.top;
570         rect->right = obj->extents.right;
571         rect->bottom = obj->extents.bottom;
572         TRACE("%p (%d,%d-%d,%d)\n", hrgn,
573                rect->left, rect->top, rect->right, rect->bottom);
574         ret = get_region_type( obj );
575         GDI_ReleaseObj(hrgn);
576         return ret;
577     }
578     return ERROR;
579 }
580
581
582 /***********************************************************************
583  *           CreateRectRgn   (GDI32.@)
584  *
585  * Creates a simple rectangular region.
586  *
587  * PARAMS
588  *   left   [I] Left coordinate of rectangle.
589  *   top    [I] Top coordinate of rectangle.
590  *   right  [I] Right coordinate of rectangle.
591  *   bottom [I] Bottom coordinate of rectangle.
592  *
593  * RETURNS
594  *   Success: Handle to region.
595  *   Failure: NULL.
596  */
597 HRGN WINAPI CreateRectRgn(INT left, INT top, INT right, INT bottom)
598 {
599     HRGN hrgn;
600     WINEREGION *obj;
601
602     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
603
604     /* Allocate 2 rects by default to reduce the number of reallocs */
605     if (!init_region( obj, RGN_DEFAULT_RECTS ))
606     {
607         HeapFree( GetProcessHeap(), 0, obj );
608         return 0;
609     }
610     if (!(hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs )))
611     {
612         HeapFree( GetProcessHeap(), 0, obj->rects );
613         HeapFree( GetProcessHeap(), 0, obj );
614         return 0;
615     }
616     TRACE( "%d,%d-%d,%d returning %p\n", left, top, right, bottom, hrgn );
617     SetRectRgn(hrgn, left, top, right, bottom);
618     return hrgn;
619 }
620
621
622 /***********************************************************************
623  *           CreateRectRgnIndirect    (GDI32.@)
624  *
625  * Creates a simple rectangular region.
626  *
627  * PARAMS
628  *   rect [I] Coordinates of rectangular region.
629  *
630  * RETURNS
631  *   Success: Handle to region.
632  *   Failure: NULL.
633  */
634 HRGN WINAPI CreateRectRgnIndirect( const RECT* rect )
635 {
636     return CreateRectRgn( rect->left, rect->top, rect->right, rect->bottom );
637 }
638
639
640 /***********************************************************************
641  *           SetRectRgn    (GDI32.@)
642  *
643  * Sets a region to a simple rectangular region.
644  *
645  * PARAMS
646  *   hrgn   [I] Region to convert.
647  *   left   [I] Left coordinate of rectangle.
648  *   top    [I] Top coordinate of rectangle.
649  *   right  [I] Right coordinate of rectangle.
650  *   bottom [I] Bottom coordinate of rectangle.
651  *
652  * RETURNS
653  *   Success: Non-zero.
654  *   Failure: Zero.
655  *
656  * NOTES
657  *   Allows either or both left and top to be greater than right or bottom.
658  */
659 BOOL WINAPI SetRectRgn( HRGN hrgn, INT left, INT top,
660                           INT right, INT bottom )
661 {
662     WINEREGION *obj;
663
664     TRACE("%p %d,%d-%d,%d\n", hrgn, left, top, right, bottom );
665
666     if (!(obj = GDI_GetObjPtr( hrgn, OBJ_REGION ))) return FALSE;
667
668     if (left > right) { INT tmp = left; left = right; right = tmp; }
669     if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
670
671     if((left != right) && (top != bottom))
672     {
673         obj->rects->left = obj->extents.left = left;
674         obj->rects->top = obj->extents.top = top;
675         obj->rects->right = obj->extents.right = right;
676         obj->rects->bottom = obj->extents.bottom = bottom;
677         obj->numRects = 1;
678     }
679     else
680         empty_region(obj);
681
682     GDI_ReleaseObj( hrgn );
683     return TRUE;
684 }
685
686
687 /***********************************************************************
688  *           CreateRoundRectRgn    (GDI32.@)
689  *
690  * Creates a rectangular region with rounded corners.
691  *
692  * PARAMS
693  *   left           [I] Left coordinate of rectangle.
694  *   top            [I] Top coordinate of rectangle.
695  *   right          [I] Right coordinate of rectangle.
696  *   bottom         [I] Bottom coordinate of rectangle.
697  *   ellipse_width  [I] Width of the ellipse at each corner.
698  *   ellipse_height [I] Height of the ellipse at each corner.
699  *
700  * RETURNS
701  *   Success: Handle to region.
702  *   Failure: NULL.
703  *
704  * NOTES
705  *   If ellipse_width or ellipse_height is less than 2 logical units then
706  *   it is treated as though CreateRectRgn() was called instead.
707  */
708 HRGN WINAPI CreateRoundRectRgn( INT left, INT top,
709                                     INT right, INT bottom,
710                                     INT ellipse_width, INT ellipse_height )
711 {
712     WINEREGION *obj;
713     HRGN hrgn = 0;
714     int a, b, i, x, y;
715     INT64 asq, bsq, dx, dy, err;
716     RECT *rects;
717
718       /* Make the dimensions sensible */
719
720     if (left > right) { INT tmp = left; left = right; right = tmp; }
721     if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
722     /* the region is for the rectangle interior, but only at right and bottom for some reason */
723     right--;
724     bottom--;
725
726     ellipse_width = min( right - left, abs( ellipse_width ));
727     ellipse_height = min( bottom - top, abs( ellipse_height ));
728
729       /* Check if we can do a normal rectangle instead */
730
731     if ((ellipse_width < 2) || (ellipse_height < 2))
732         return CreateRectRgn( left, top, right, bottom );
733
734     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
735     obj->size = ellipse_height;
736     obj->numRects = ellipse_height;
737     obj->extents.left   = left;
738     obj->extents.top    = top;
739     obj->extents.right  = right;
740     obj->extents.bottom = bottom;
741
742     obj->rects = rects = HeapAlloc( GetProcessHeap(), 0, obj->size * sizeof(RECT) );
743     if (!rects) goto done;
744
745     /* based on an algorithm by Alois Zingl */
746
747     a = ellipse_width - 1;
748     b = ellipse_height - 1;
749     asq = (INT64)8 * a * a;
750     bsq = (INT64)8 * b * b;
751     dx  = (INT64)4 * b * b * (1 - a);
752     dy  = (INT64)4 * a * a * (1 + (b % 2));
753     err = dx + dy + a * a * (b % 2);
754
755     x = 0;
756     y = ellipse_height / 2;
757
758     rects[y].left = left;
759     rects[y].right = right;
760
761     while (x <= ellipse_width / 2)
762     {
763         INT64 e2 = 2 * err;
764         if (e2 >= dx)
765         {
766             x++;
767             err += dx += bsq;
768         }
769         if (e2 <= dy)
770         {
771             y++;
772             err += dy += asq;
773             rects[y].left = left + x;
774             rects[y].right = right - x;
775         }
776     }
777     for (i = 0; i < ellipse_height / 2; i++)
778     {
779         rects[i].left = rects[b - i].left;
780         rects[i].right = rects[b - i].right;
781         rects[i].top = top + i;
782         rects[i].bottom = rects[i].top + 1;
783     }
784     for (; i < ellipse_height; i++)
785     {
786         rects[i].top = bottom - ellipse_height + i;
787         rects[i].bottom = rects[i].top + 1;
788     }
789     rects[ellipse_height / 2].top = top + ellipse_height / 2;  /* extend to top of rectangle */
790
791     hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs );
792
793     TRACE("(%d,%d-%d,%d %dx%d): ret=%p\n",
794           left, top, right, bottom, ellipse_width, ellipse_height, hrgn );
795 done:
796     if (!hrgn)
797     {
798         HeapFree( GetProcessHeap(), 0, obj->rects );
799         HeapFree( GetProcessHeap(), 0, obj );
800     }
801     return hrgn;
802 }
803
804
805 /***********************************************************************
806  *           CreateEllipticRgn    (GDI32.@)
807  *
808  * Creates an elliptical region.
809  *
810  * PARAMS
811  *   left   [I] Left coordinate of bounding rectangle.
812  *   top    [I] Top coordinate of bounding rectangle.
813  *   right  [I] Right coordinate of bounding rectangle.
814  *   bottom [I] Bottom coordinate of bounding rectangle.
815  *
816  * RETURNS
817  *   Success: Handle to region.
818  *   Failure: NULL.
819  *
820  * NOTES
821  *   This is a special case of CreateRoundRectRgn() where the width of the
822  *   ellipse at each corner is equal to the width the rectangle and
823  *   the same for the height.
824  */
825 HRGN WINAPI CreateEllipticRgn( INT left, INT top,
826                                    INT right, INT bottom )
827 {
828     return CreateRoundRectRgn( left, top, right, bottom,
829                                  right-left, bottom-top );
830 }
831
832
833 /***********************************************************************
834  *           CreateEllipticRgnIndirect    (GDI32.@)
835  *
836  * Creates an elliptical region.
837  *
838  * PARAMS
839  *   rect [I] Pointer to bounding rectangle of the ellipse.
840  *
841  * RETURNS
842  *   Success: Handle to region.
843  *   Failure: NULL.
844  *
845  * NOTES
846  *   This is a special case of CreateRoundRectRgn() where the width of the
847  *   ellipse at each corner is equal to the width the rectangle and
848  *   the same for the height.
849  */
850 HRGN WINAPI CreateEllipticRgnIndirect( const RECT *rect )
851 {
852     return CreateRoundRectRgn( rect->left, rect->top, rect->right,
853                                  rect->bottom, rect->right - rect->left,
854                                  rect->bottom - rect->top );
855 }
856
857 /***********************************************************************
858  *           GetRegionData   (GDI32.@)
859  *
860  * Retrieves the data that specifies the region.
861  *
862  * PARAMS
863  *   hrgn    [I] Region to retrieve the region data from.
864  *   count   [I] The size of the buffer pointed to by rgndata in bytes.
865  *   rgndata [I] The buffer to receive data about the region.
866  *
867  * RETURNS
868  *   Success: If rgndata is NULL then the required number of bytes. Otherwise,
869  *            the number of bytes copied to the output buffer.
870  *   Failure: 0.
871  *
872  * NOTES
873  *   The format of the Buffer member of RGNDATA is determined by the iType
874  *   member of the region data header.
875  *   Currently this is always RDH_RECTANGLES, which specifies that the format
876  *   is the array of RECT's that specify the region. The length of the array
877  *   is specified by the nCount member of the region data header.
878  */
879 DWORD WINAPI GetRegionData(HRGN hrgn, DWORD count, LPRGNDATA rgndata)
880 {
881     DWORD size;
882     WINEREGION *obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
883
884     TRACE(" %p count = %d, rgndata = %p\n", hrgn, count, rgndata);
885
886     if(!obj) return 0;
887
888     size = obj->numRects * sizeof(RECT);
889     if(count < (size + sizeof(RGNDATAHEADER)) || rgndata == NULL)
890     {
891         GDI_ReleaseObj( hrgn );
892         if (rgndata) /* buffer is too small, signal it by return 0 */
893             return 0;
894         else            /* user requested buffer size with rgndata NULL */
895             return size + sizeof(RGNDATAHEADER);
896     }
897
898     rgndata->rdh.dwSize = sizeof(RGNDATAHEADER);
899     rgndata->rdh.iType = RDH_RECTANGLES;
900     rgndata->rdh.nCount = obj->numRects;
901     rgndata->rdh.nRgnSize = size;
902     rgndata->rdh.rcBound.left = obj->extents.left;
903     rgndata->rdh.rcBound.top = obj->extents.top;
904     rgndata->rdh.rcBound.right = obj->extents.right;
905     rgndata->rdh.rcBound.bottom = obj->extents.bottom;
906
907     memcpy( rgndata->Buffer, obj->rects, size );
908
909     GDI_ReleaseObj( hrgn );
910     return size + sizeof(RGNDATAHEADER);
911 }
912
913
914 static void translate( POINT *pt, UINT count, const XFORM *xform )
915 {
916     while (count--)
917     {
918         double x = pt->x;
919         double y = pt->y;
920         pt->x = floor( x * xform->eM11 + y * xform->eM21 + xform->eDx + 0.5 );
921         pt->y = floor( x * xform->eM12 + y * xform->eM22 + xform->eDy + 0.5 );
922         pt++;
923     }
924 }
925
926
927 /***********************************************************************
928  *           ExtCreateRegion   (GDI32.@)
929  *
930  * Creates a region as specified by the transformation data and region data.
931  *
932  * PARAMS
933  *   lpXform [I] World-space to logical-space transformation data.
934  *   dwCount [I] Size of the data pointed to by rgndata, in bytes.
935  *   rgndata [I] Data that specifies the region.
936  *
937  * RETURNS
938  *   Success: Handle to region.
939  *   Failure: NULL.
940  *
941  * NOTES
942  *   See GetRegionData().
943  */
944 HRGN WINAPI ExtCreateRegion( const XFORM* lpXform, DWORD dwCount, const RGNDATA* rgndata)
945 {
946     HRGN hrgn = 0;
947     WINEREGION *obj;
948
949     if (!rgndata)
950     {
951         SetLastError( ERROR_INVALID_PARAMETER );
952         return 0;
953     }
954
955     if (rgndata->rdh.dwSize < sizeof(RGNDATAHEADER))
956         return 0;
957
958     /* XP doesn't care about the type */
959     if( rgndata->rdh.iType != RDH_RECTANGLES )
960         WARN("(Unsupported region data type: %u)\n", rgndata->rdh.iType);
961
962     if (lpXform)
963     {
964         const RECT *pCurRect, *pEndRect;
965
966         hrgn = CreateRectRgn( 0, 0, 0, 0 );
967
968         pEndRect = (const RECT *)rgndata->Buffer + rgndata->rdh.nCount;
969         for (pCurRect = (const RECT *)rgndata->Buffer; pCurRect < pEndRect; pCurRect++)
970         {
971             static const INT count = 4;
972             HRGN poly_hrgn;
973             POINT pt[4];
974
975             pt[0].x = pCurRect->left;
976             pt[0].y = pCurRect->top;
977             pt[1].x = pCurRect->right;
978             pt[1].y = pCurRect->top;
979             pt[2].x = pCurRect->right;
980             pt[2].y = pCurRect->bottom;
981             pt[3].x = pCurRect->left;
982             pt[3].y = pCurRect->bottom;
983
984             translate( pt, 4, lpXform );
985             poly_hrgn = CreatePolyPolygonRgn( pt, &count, 1, WINDING );
986             CombineRgn( hrgn, hrgn, poly_hrgn, RGN_OR );
987             DeleteObject( poly_hrgn );
988         }
989         return hrgn;
990     }
991
992     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
993
994     if (init_region( obj, rgndata->rdh.nCount ))
995     {
996         const RECT *pCurRect, *pEndRect;
997
998         pEndRect = (const RECT *)rgndata->Buffer + rgndata->rdh.nCount;
999         for(pCurRect = (const RECT *)rgndata->Buffer; pCurRect < pEndRect; pCurRect++)
1000         {
1001             if (pCurRect->left < pCurRect->right && pCurRect->top < pCurRect->bottom)
1002             {
1003                 if (!REGION_UnionRectWithRegion( pCurRect, obj )) goto done;
1004             }
1005         }
1006         hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs );
1007     }
1008     else
1009     {
1010         HeapFree( GetProcessHeap(), 0, obj );
1011         return 0;
1012     }
1013
1014 done:
1015     if (!hrgn)
1016     {
1017         HeapFree( GetProcessHeap(), 0, obj->rects );
1018         HeapFree( GetProcessHeap(), 0, obj );
1019     }
1020     TRACE("%p %d %p returning %p\n", lpXform, dwCount, rgndata, hrgn );
1021     return hrgn;
1022 }
1023
1024
1025 /***********************************************************************
1026  *           PtInRegion    (GDI32.@)
1027  *
1028  * Tests whether the specified point is inside a region.
1029  *
1030  * PARAMS
1031  *   hrgn [I] Region to test.
1032  *   x    [I] X-coordinate of point to test.
1033  *   y    [I] Y-coordinate of point to test.
1034  *
1035  * RETURNS
1036  *   Non-zero if the point is inside the region or zero otherwise.
1037  */
1038 BOOL WINAPI PtInRegion( HRGN hrgn, INT x, INT y )
1039 {
1040     WINEREGION *obj;
1041     BOOL ret = FALSE;
1042
1043     if ((obj = GDI_GetObjPtr( hrgn, OBJ_REGION )))
1044     {
1045         int i;
1046
1047         if (obj->numRects > 0 && is_in_rect(&obj->extents, x, y))
1048             for (i = 0; i < obj->numRects; i++)
1049                 if (is_in_rect(&obj->rects[i], x, y))
1050                 {
1051                     ret = TRUE;
1052                     break;
1053                 }
1054         GDI_ReleaseObj( hrgn );
1055     }
1056     return ret;
1057 }
1058
1059
1060 /***********************************************************************
1061  *           RectInRegion    (GDI32.@)
1062  *
1063  * Tests if a rectangle is at least partly inside the specified region.
1064  *
1065  * PARAMS
1066  *   hrgn [I] Region to test.
1067  *   rect [I] Rectangle to test.
1068  *
1069  * RETURNS
1070  *   Non-zero if the rectangle is partially inside the region or
1071  *   zero otherwise.
1072  */
1073 BOOL WINAPI RectInRegion( HRGN hrgn, const RECT *rect )
1074 {
1075     WINEREGION *obj;
1076     BOOL ret = FALSE;
1077     RECT rc;
1078
1079     /* swap the coordinates to make right >= left and bottom >= top */
1080     /* (region building rectangles are normalized the same way) */
1081     rc = *rect;
1082     order_rect( &rc );
1083
1084     if ((obj = GDI_GetObjPtr( hrgn, OBJ_REGION )))
1085     {
1086         RECT *pCurRect, *pRectEnd;
1087
1088     /* this is (just) a useful optimization */
1089         if ((obj->numRects > 0) && overlapping(&obj->extents, &rc))
1090         {
1091             for (pCurRect = obj->rects, pRectEnd = pCurRect +
1092              obj->numRects; pCurRect < pRectEnd; pCurRect++)
1093             {
1094                 if (pCurRect->bottom <= rc.top)
1095                     continue;             /* not far enough down yet */
1096
1097                 if (pCurRect->top >= rc.bottom)
1098                     break;                /* too far down */
1099
1100                 if (pCurRect->right <= rc.left)
1101                     continue;              /* not far enough over yet */
1102
1103                 if (pCurRect->left >= rc.right) {
1104                     continue;
1105                 }
1106
1107                 ret = TRUE;
1108                 break;
1109             }
1110         }
1111         GDI_ReleaseObj(hrgn);
1112     }
1113     return ret;
1114 }
1115
1116 /***********************************************************************
1117  *           EqualRgn    (GDI32.@)
1118  *
1119  * Tests whether one region is identical to another.
1120  *
1121  * PARAMS
1122  *   hrgn1 [I] The first region to compare.
1123  *   hrgn2 [I] The second region to compare.
1124  *
1125  * RETURNS
1126  *   Non-zero if both regions are identical or zero otherwise.
1127  */
1128 BOOL WINAPI EqualRgn( HRGN hrgn1, HRGN hrgn2 )
1129 {
1130     WINEREGION *obj1, *obj2;
1131     BOOL ret = FALSE;
1132
1133     if ((obj1 = GDI_GetObjPtr( hrgn1, OBJ_REGION )))
1134     {
1135         if ((obj2 = GDI_GetObjPtr( hrgn2, OBJ_REGION )))
1136         {
1137             int i;
1138
1139             if ( obj1->numRects != obj2->numRects ) goto done;
1140             if ( obj1->numRects == 0 )
1141             {
1142                 ret = TRUE;
1143                 goto done;
1144
1145             }
1146             if (obj1->extents.left   != obj2->extents.left) goto done;
1147             if (obj1->extents.right  != obj2->extents.right) goto done;
1148             if (obj1->extents.top    != obj2->extents.top) goto done;
1149             if (obj1->extents.bottom != obj2->extents.bottom) goto done;
1150             for( i = 0; i < obj1->numRects; i++ )
1151             {
1152                 if (obj1->rects[i].left   != obj2->rects[i].left) goto done;
1153                 if (obj1->rects[i].right  != obj2->rects[i].right) goto done;
1154                 if (obj1->rects[i].top    != obj2->rects[i].top) goto done;
1155                 if (obj1->rects[i].bottom != obj2->rects[i].bottom) goto done;
1156             }
1157             ret = TRUE;
1158         done:
1159             GDI_ReleaseObj(hrgn2);
1160         }
1161         GDI_ReleaseObj(hrgn1);
1162     }
1163     return ret;
1164 }
1165
1166 /***********************************************************************
1167  *           REGION_UnionRectWithRegion
1168  *           Adds a rectangle to a WINEREGION
1169  */
1170 static BOOL REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn)
1171 {
1172     WINEREGION region;
1173
1174     region.rects = &region.extents;
1175     region.numRects = 1;
1176     region.size = 1;
1177     region.extents = *rect;
1178     return REGION_UnionRegion(rgn, rgn, &region);
1179 }
1180
1181
1182 BOOL add_rect_to_region( HRGN rgn, const RECT *rect )
1183 {
1184     WINEREGION *obj = GDI_GetObjPtr( rgn, OBJ_REGION );
1185     BOOL ret;
1186
1187     if (!obj) return FALSE;
1188     ret = REGION_UnionRectWithRegion( rect, obj );
1189     GDI_ReleaseObj( rgn );
1190     return ret;
1191 }
1192
1193 /***********************************************************************
1194  *           REGION_CreateFrameRgn
1195  *
1196  * Create a region that is a frame around another region.
1197  * Compute the intersection of the region moved in all 4 directions
1198  * ( +x, -x, +y, -y) and subtract from the original.
1199  * The result looks slightly better than in Windows :)
1200  */
1201 BOOL REGION_FrameRgn( HRGN hDest, HRGN hSrc, INT x, INT y )
1202 {
1203     WINEREGION tmprgn;
1204     BOOL bRet = FALSE;
1205     WINEREGION* destObj = NULL;
1206     WINEREGION *srcObj = GDI_GetObjPtr( hSrc, OBJ_REGION );
1207
1208     tmprgn.rects = NULL;
1209     if (!srcObj) return FALSE;
1210     if (srcObj->numRects != 0)
1211     {
1212         if (!(destObj = GDI_GetObjPtr( hDest, OBJ_REGION ))) goto done;
1213         if (!init_region( &tmprgn, srcObj->numRects )) goto done;
1214
1215         if (!REGION_OffsetRegion( destObj, srcObj, -x, 0)) goto done;
1216         if (!REGION_OffsetRegion( &tmprgn, srcObj, x, 0)) goto done;
1217         if (!REGION_IntersectRegion( destObj, destObj, &tmprgn )) goto done;
1218         if (!REGION_OffsetRegion( &tmprgn, srcObj, 0, -y)) goto done;
1219         if (!REGION_IntersectRegion( destObj, destObj, &tmprgn )) goto done;
1220         if (!REGION_OffsetRegion( &tmprgn, srcObj, 0, y)) goto done;
1221         if (!REGION_IntersectRegion( destObj, destObj, &tmprgn )) goto done;
1222         if (!REGION_SubtractRegion( destObj, srcObj, destObj )) goto done;
1223         bRet = TRUE;
1224     }
1225 done:
1226     HeapFree( GetProcessHeap(), 0, tmprgn.rects );
1227     if (destObj) GDI_ReleaseObj ( hDest );
1228     GDI_ReleaseObj( hSrc );
1229     return bRet;
1230 }
1231
1232
1233 /***********************************************************************
1234  *           CombineRgn   (GDI32.@)
1235  *
1236  * Combines two regions with the specified operation and stores the result
1237  * in the specified destination region.
1238  *
1239  * PARAMS
1240  *   hDest [I] The region that receives the combined result.
1241  *   hSrc1 [I] The first source region.
1242  *   hSrc2 [I] The second source region.
1243  *   mode  [I] The way in which the source regions will be combined. See notes.
1244  *
1245  * RETURNS
1246  *   Success:
1247  *     NULLREGION - The new region is empty.
1248  *     SIMPLEREGION - The new region can be represented by one rectangle.
1249  *     COMPLEXREGION - The new region can only be represented by more than
1250  *                     one rectangle.
1251  *   Failure: ERROR
1252  *
1253  * NOTES
1254  *   The two source regions can be the same region.
1255  *   The mode can be one of the following:
1256  *|  RGN_AND - Intersection of the regions
1257  *|  RGN_OR - Union of the regions
1258  *|  RGN_XOR - Unions of the regions minus any intersection.
1259  *|  RGN_DIFF - Difference (subtraction) of the regions.
1260  */
1261 INT WINAPI CombineRgn(HRGN hDest, HRGN hSrc1, HRGN hSrc2, INT mode)
1262 {
1263     WINEREGION *destObj = GDI_GetObjPtr( hDest, OBJ_REGION );
1264     INT result = ERROR;
1265
1266     TRACE(" %p,%p -> %p mode=%x\n", hSrc1, hSrc2, hDest, mode );
1267     if (destObj)
1268     {
1269         WINEREGION *src1Obj = GDI_GetObjPtr( hSrc1, OBJ_REGION );
1270
1271         if (src1Obj)
1272         {
1273             TRACE("dump src1Obj:\n");
1274             if(TRACE_ON(region))
1275               REGION_DumpRegion(src1Obj);
1276             if (mode == RGN_COPY)
1277             {
1278                 if (REGION_CopyRegion( destObj, src1Obj ))
1279                     result = get_region_type( destObj );
1280             }
1281             else
1282             {
1283                 WINEREGION *src2Obj = GDI_GetObjPtr( hSrc2, OBJ_REGION );
1284
1285                 if (src2Obj)
1286                 {
1287                     TRACE("dump src2Obj:\n");
1288                     if(TRACE_ON(region))
1289                         REGION_DumpRegion(src2Obj);
1290                     switch (mode)
1291                     {
1292                     case RGN_AND:
1293                         if (REGION_IntersectRegion( destObj, src1Obj, src2Obj ))
1294                             result = get_region_type( destObj );
1295                         break;
1296                     case RGN_OR:
1297                         if (REGION_UnionRegion( destObj, src1Obj, src2Obj ))
1298                             result = get_region_type( destObj );
1299                         break;
1300                     case RGN_XOR:
1301                         if (REGION_XorRegion( destObj, src1Obj, src2Obj ))
1302                             result = get_region_type( destObj );
1303                         break;
1304                     case RGN_DIFF:
1305                         if (REGION_SubtractRegion( destObj, src1Obj, src2Obj ))
1306                             result = get_region_type( destObj );
1307                         break;
1308                     }
1309                     GDI_ReleaseObj( hSrc2 );
1310                 }
1311             }
1312             GDI_ReleaseObj( hSrc1 );
1313         }
1314         TRACE("dump destObj:\n");
1315         if(TRACE_ON(region))
1316           REGION_DumpRegion(destObj);
1317
1318         GDI_ReleaseObj( hDest );
1319     }
1320     return result;
1321 }
1322
1323 /***********************************************************************
1324  *           REGION_SetExtents
1325  *           Re-calculate the extents of a region
1326  */
1327 static void REGION_SetExtents (WINEREGION *pReg)
1328 {
1329     RECT *pRect, *pRectEnd, *pExtents;
1330
1331     if (pReg->numRects == 0)
1332     {
1333         pReg->extents.left = 0;
1334         pReg->extents.top = 0;
1335         pReg->extents.right = 0;
1336         pReg->extents.bottom = 0;
1337         return;
1338     }
1339
1340     pExtents = &pReg->extents;
1341     pRect = pReg->rects;
1342     pRectEnd = &pRect[pReg->numRects - 1];
1343
1344     /*
1345      * Since pRect is the first rectangle in the region, it must have the
1346      * smallest top and since pRectEnd is the last rectangle in the region,
1347      * it must have the largest bottom, because of banding. Initialize left and
1348      * right from pRect and pRectEnd, resp., as good things to initialize them
1349      * to...
1350      */
1351     pExtents->left = pRect->left;
1352     pExtents->top = pRect->top;
1353     pExtents->right = pRectEnd->right;
1354     pExtents->bottom = pRectEnd->bottom;
1355
1356     while (pRect <= pRectEnd)
1357     {
1358         if (pRect->left < pExtents->left)
1359             pExtents->left = pRect->left;
1360         if (pRect->right > pExtents->right)
1361             pExtents->right = pRect->right;
1362         pRect++;
1363     }
1364 }
1365
1366 /***********************************************************************
1367  *           REGION_CopyRegion
1368  */
1369 static BOOL REGION_CopyRegion(WINEREGION *dst, WINEREGION *src)
1370 {
1371     if (dst != src) /*  don't want to copy to itself */
1372     {
1373         if (dst->size < src->numRects)
1374         {
1375             RECT *rects = HeapReAlloc( GetProcessHeap(), 0, dst->rects, src->numRects * sizeof(RECT) );
1376             if (!rects) return FALSE;
1377             dst->rects = rects;
1378             dst->size = src->numRects;
1379         }
1380         dst->numRects = src->numRects;
1381         dst->extents.left = src->extents.left;
1382         dst->extents.top = src->extents.top;
1383         dst->extents.right = src->extents.right;
1384         dst->extents.bottom = src->extents.bottom;
1385         memcpy(dst->rects, src->rects, src->numRects * sizeof(RECT));
1386     }
1387     return TRUE;
1388 }
1389
1390 /***********************************************************************
1391  *           REGION_MirrorRegion
1392  */
1393 static BOOL REGION_MirrorRegion( WINEREGION *dst, WINEREGION *src, int width )
1394 {
1395     int i, start, end;
1396     RECT extents;
1397     RECT *rects = HeapAlloc( GetProcessHeap(), 0, src->numRects * sizeof(RECT) );
1398
1399     if (!rects) return FALSE;
1400
1401     extents.left   = width - src->extents.right;
1402     extents.right  = width - src->extents.left;
1403     extents.top    = src->extents.top;
1404     extents.bottom = src->extents.bottom;
1405
1406     for (start = 0; start < src->numRects; start = end)
1407     {
1408         /* find the end of the current band */
1409         for (end = start + 1; end < src->numRects; end++)
1410             if (src->rects[end].top != src->rects[end - 1].top) break;
1411
1412         for (i = 0; i < end - start; i++)
1413         {
1414             rects[start + i].left   = width - src->rects[end - i - 1].right;
1415             rects[start + i].right  = width - src->rects[end - i - 1].left;
1416             rects[start + i].top    = src->rects[end - i - 1].top;
1417             rects[start + i].bottom = src->rects[end - i - 1].bottom;
1418         }
1419     }
1420
1421     HeapFree( GetProcessHeap(), 0, dst->rects );
1422     dst->rects    = rects;
1423     dst->size     = src->numRects;
1424     dst->numRects = src->numRects;
1425     dst->extents  = extents;
1426     return TRUE;
1427 }
1428
1429 /***********************************************************************
1430  *           mirror_region
1431  */
1432 INT mirror_region( HRGN dst, HRGN src, INT width )
1433 {
1434     WINEREGION *src_rgn, *dst_rgn;
1435     INT ret = ERROR;
1436
1437     if (!(src_rgn = GDI_GetObjPtr( src, OBJ_REGION ))) return ERROR;
1438     if ((dst_rgn = GDI_GetObjPtr( dst, OBJ_REGION )))
1439     {
1440         if (REGION_MirrorRegion( dst_rgn, src_rgn, width )) ret = get_region_type( dst_rgn );
1441         GDI_ReleaseObj( dst_rgn );
1442     }
1443     GDI_ReleaseObj( src_rgn );
1444     return ret;
1445 }
1446
1447 /***********************************************************************
1448  *           MirrorRgn    (GDI32.@)
1449  */
1450 BOOL WINAPI MirrorRgn( HWND hwnd, HRGN hrgn )
1451 {
1452     static const WCHAR user32W[] = {'u','s','e','r','3','2','.','d','l','l',0};
1453     static BOOL (WINAPI *pGetWindowRect)( HWND hwnd, LPRECT rect );
1454     RECT rect;
1455
1456     /* yes, a HWND in gdi32, don't ask */
1457     if (!pGetWindowRect)
1458     {
1459         HMODULE user32 = GetModuleHandleW(user32W);
1460         if (!user32) return FALSE;
1461         if (!(pGetWindowRect = (void *)GetProcAddress( user32, "GetWindowRect" ))) return FALSE;
1462     }
1463     pGetWindowRect( hwnd, &rect );
1464     return mirror_region( hrgn, hrgn, rect.right - rect.left ) != ERROR;
1465 }
1466
1467
1468 /***********************************************************************
1469  *           REGION_Coalesce
1470  *
1471  *      Attempt to merge the rects in the current band with those in the
1472  *      previous one. Used only by REGION_RegionOp.
1473  *
1474  * Results:
1475  *      The new index for the previous band.
1476  *
1477  * Side Effects:
1478  *      If coalescing takes place:
1479  *          - rectangles in the previous band will have their bottom fields
1480  *            altered.
1481  *          - pReg->numRects will be decreased.
1482  *
1483  */
1484 static INT REGION_Coalesce (
1485              WINEREGION *pReg, /* Region to coalesce */
1486              INT prevStart,  /* Index of start of previous band */
1487              INT curStart    /* Index of start of current band */
1488 ) {
1489     RECT *pPrevRect;          /* Current rect in previous band */
1490     RECT *pCurRect;           /* Current rect in current band */
1491     RECT *pRegEnd;            /* End of region */
1492     INT curNumRects;          /* Number of rectangles in current band */
1493     INT prevNumRects;         /* Number of rectangles in previous band */
1494     INT bandtop;               /* top coordinate for current band */
1495
1496     pRegEnd = &pReg->rects[pReg->numRects];
1497
1498     pPrevRect = &pReg->rects[prevStart];
1499     prevNumRects = curStart - prevStart;
1500
1501     /*
1502      * Figure out how many rectangles are in the current band. Have to do
1503      * this because multiple bands could have been added in REGION_RegionOp
1504      * at the end when one region has been exhausted.
1505      */
1506     pCurRect = &pReg->rects[curStart];
1507     bandtop = pCurRect->top;
1508     for (curNumRects = 0;
1509          (pCurRect != pRegEnd) && (pCurRect->top == bandtop);
1510          curNumRects++)
1511     {
1512         pCurRect++;
1513     }
1514
1515     if (pCurRect != pRegEnd)
1516     {
1517         /*
1518          * If more than one band was added, we have to find the start
1519          * of the last band added so the next coalescing job can start
1520          * at the right place... (given when multiple bands are added,
1521          * this may be pointless -- see above).
1522          */
1523         pRegEnd--;
1524         while (pRegEnd[-1].top == pRegEnd->top)
1525         {
1526             pRegEnd--;
1527         }
1528         curStart = pRegEnd - pReg->rects;
1529         pRegEnd = pReg->rects + pReg->numRects;
1530     }
1531
1532     if ((curNumRects == prevNumRects) && (curNumRects != 0)) {
1533         pCurRect -= curNumRects;
1534         /*
1535          * The bands may only be coalesced if the bottom of the previous
1536          * matches the top scanline of the current.
1537          */
1538         if (pPrevRect->bottom == pCurRect->top)
1539         {
1540             /*
1541              * Make sure the bands have rects in the same places. This
1542              * assumes that rects have been added in such a way that they
1543              * cover the most area possible. I.e. two rects in a band must
1544              * have some horizontal space between them.
1545              */
1546             do
1547             {
1548                 if ((pPrevRect->left != pCurRect->left) ||
1549                     (pPrevRect->right != pCurRect->right))
1550                 {
1551                     /*
1552                      * The bands don't line up so they can't be coalesced.
1553                      */
1554                     return (curStart);
1555                 }
1556                 pPrevRect++;
1557                 pCurRect++;
1558                 prevNumRects -= 1;
1559             } while (prevNumRects != 0);
1560
1561             pReg->numRects -= curNumRects;
1562             pCurRect -= curNumRects;
1563             pPrevRect -= curNumRects;
1564
1565             /*
1566              * The bands may be merged, so set the bottom of each rect
1567              * in the previous band to that of the corresponding rect in
1568              * the current band.
1569              */
1570             do
1571             {
1572                 pPrevRect->bottom = pCurRect->bottom;
1573                 pPrevRect++;
1574                 pCurRect++;
1575                 curNumRects -= 1;
1576             } while (curNumRects != 0);
1577
1578             /*
1579              * If only one band was added to the region, we have to backup
1580              * curStart to the start of the previous band.
1581              *
1582              * If more than one band was added to the region, copy the
1583              * other bands down. The assumption here is that the other bands
1584              * came from the same region as the current one and no further
1585              * coalescing can be done on them since it's all been done
1586              * already... curStart is already in the right place.
1587              */
1588             if (pCurRect == pRegEnd)
1589             {
1590                 curStart = prevStart;
1591             }
1592             else
1593             {
1594                 do
1595                 {
1596                     *pPrevRect++ = *pCurRect++;
1597                 } while (pCurRect != pRegEnd);
1598             }
1599
1600         }
1601     }
1602     return (curStart);
1603 }
1604
1605 /***********************************************************************
1606  *           REGION_RegionOp
1607  *
1608  *      Apply an operation to two regions. Called by REGION_Union,
1609  *      REGION_Inverse, REGION_Subtract, REGION_Intersect...
1610  *
1611  * Results:
1612  *      None.
1613  *
1614  * Side Effects:
1615  *      The new region is overwritten.
1616  *
1617  * Notes:
1618  *      The idea behind this function is to view the two regions as sets.
1619  *      Together they cover a rectangle of area that this function divides
1620  *      into horizontal bands where points are covered only by one region
1621  *      or by both. For the first case, the nonOverlapFunc is called with
1622  *      each the band and the band's upper and lower extents. For the
1623  *      second, the overlapFunc is called to process the entire band. It
1624  *      is responsible for clipping the rectangles in the band, though
1625  *      this function provides the boundaries.
1626  *      At the end of each band, the new region is coalesced, if possible,
1627  *      to reduce the number of rectangles in the region.
1628  *
1629  */
1630 static BOOL REGION_RegionOp(
1631             WINEREGION *destReg, /* Place to store result */
1632             WINEREGION *reg1,   /* First region in operation */
1633             WINEREGION *reg2,   /* 2nd region in operation */
1634             BOOL (*overlapFunc)(WINEREGION*, RECT*, RECT*, RECT*, RECT*, INT, INT),     /* Function to call for over-lapping bands */
1635             BOOL (*nonOverlap1Func)(WINEREGION*, RECT*, RECT*, INT, INT), /* Function to call for non-overlapping bands in region 1 */
1636             BOOL (*nonOverlap2Func)(WINEREGION*, RECT*, RECT*, INT, INT)  /* Function to call for non-overlapping bands in region 2 */
1637 ) {
1638     WINEREGION newReg;
1639     RECT *r1;                         /* Pointer into first region */
1640     RECT *r2;                         /* Pointer into 2d region */
1641     RECT *r1End;                      /* End of 1st region */
1642     RECT *r2End;                      /* End of 2d region */
1643     INT ybot;                         /* Bottom of intersection */
1644     INT ytop;                         /* Top of intersection */
1645     INT prevBand;                     /* Index of start of
1646                                                  * previous band in newReg */
1647     INT curBand;                      /* Index of start of current
1648                                                  * band in newReg */
1649     RECT *r1BandEnd;                  /* End of current band in r1 */
1650     RECT *r2BandEnd;                  /* End of current band in r2 */
1651     INT top;                          /* Top of non-overlapping band */
1652     INT bot;                          /* Bottom of non-overlapping band */
1653
1654     /*
1655      * Initialization:
1656      *  set r1, r2, r1End and r2End appropriately, preserve the important
1657      * parts of the destination region until the end in case it's one of
1658      * the two source regions, then mark the "new" region empty, allocating
1659      * another array of rectangles for it to use.
1660      */
1661     r1 = reg1->rects;
1662     r2 = reg2->rects;
1663     r1End = r1 + reg1->numRects;
1664     r2End = r2 + reg2->numRects;
1665
1666     /*
1667      * Allocate a reasonable number of rectangles for the new region. The idea
1668      * is to allocate enough so the individual functions don't need to
1669      * reallocate and copy the array, which is time consuming, yet we don't
1670      * have to worry about using too much memory. I hope to be able to
1671      * nuke the Xrealloc() at the end of this function eventually.
1672      */
1673     if (!init_region( &newReg, max(reg1->numRects,reg2->numRects) * 2 )) return FALSE;
1674
1675     /*
1676      * Initialize ybot and ytop.
1677      * In the upcoming loop, ybot and ytop serve different functions depending
1678      * on whether the band being handled is an overlapping or non-overlapping
1679      * band.
1680      *  In the case of a non-overlapping band (only one of the regions
1681      * has points in the band), ybot is the bottom of the most recent
1682      * intersection and thus clips the top of the rectangles in that band.
1683      * ytop is the top of the next intersection between the two regions and
1684      * serves to clip the bottom of the rectangles in the current band.
1685      *  For an overlapping band (where the two regions intersect), ytop clips
1686      * the top of the rectangles of both regions and ybot clips the bottoms.
1687      */
1688     if (reg1->extents.top < reg2->extents.top)
1689         ybot = reg1->extents.top;
1690     else
1691         ybot = reg2->extents.top;
1692
1693     /*
1694      * prevBand serves to mark the start of the previous band so rectangles
1695      * can be coalesced into larger rectangles. qv. miCoalesce, above.
1696      * In the beginning, there is no previous band, so prevBand == curBand
1697      * (curBand is set later on, of course, but the first band will always
1698      * start at index 0). prevBand and curBand must be indices because of
1699      * the possible expansion, and resultant moving, of the new region's
1700      * array of rectangles.
1701      */
1702     prevBand = 0;
1703
1704     do
1705     {
1706         curBand = newReg.numRects;
1707
1708         /*
1709          * This algorithm proceeds one source-band (as opposed to a
1710          * destination band, which is determined by where the two regions
1711          * intersect) at a time. r1BandEnd and r2BandEnd serve to mark the
1712          * rectangle after the last one in the current band for their
1713          * respective regions.
1714          */
1715         r1BandEnd = r1;
1716         while ((r1BandEnd != r1End) && (r1BandEnd->top == r1->top))
1717         {
1718             r1BandEnd++;
1719         }
1720
1721         r2BandEnd = r2;
1722         while ((r2BandEnd != r2End) && (r2BandEnd->top == r2->top))
1723         {
1724             r2BandEnd++;
1725         }
1726
1727         /*
1728          * First handle the band that doesn't intersect, if any.
1729          *
1730          * Note that attention is restricted to one band in the
1731          * non-intersecting region at once, so if a region has n
1732          * bands between the current position and the next place it overlaps
1733          * the other, this entire loop will be passed through n times.
1734          */
1735         if (r1->top < r2->top)
1736         {
1737             top = max(r1->top,ybot);
1738             bot = min(r1->bottom,r2->top);
1739
1740             if ((top != bot) && (nonOverlap1Func != NULL))
1741             {
1742                 if (!nonOverlap1Func(&newReg, r1, r1BandEnd, top, bot)) return FALSE;
1743             }
1744
1745             ytop = r2->top;
1746         }
1747         else if (r2->top < r1->top)
1748         {
1749             top = max(r2->top,ybot);
1750             bot = min(r2->bottom,r1->top);
1751
1752             if ((top != bot) && (nonOverlap2Func != NULL))
1753             {
1754                 if (!nonOverlap2Func(&newReg, r2, r2BandEnd, top, bot)) return FALSE;
1755             }
1756
1757             ytop = r1->top;
1758         }
1759         else
1760         {
1761             ytop = r1->top;
1762         }
1763
1764         /*
1765          * If any rectangles got added to the region, try and coalesce them
1766          * with rectangles from the previous band. Note we could just do
1767          * this test in miCoalesce, but some machines incur a not
1768          * inconsiderable cost for function calls, so...
1769          */
1770         if (newReg.numRects != curBand)
1771         {
1772             prevBand = REGION_Coalesce (&newReg, prevBand, curBand);
1773         }
1774
1775         /*
1776          * Now see if we've hit an intersecting band. The two bands only
1777          * intersect if ybot > ytop
1778          */
1779         ybot = min(r1->bottom, r2->bottom);
1780         curBand = newReg.numRects;
1781         if (ybot > ytop)
1782         {
1783             if (!overlapFunc(&newReg, r1, r1BandEnd, r2, r2BandEnd, ytop, ybot)) return FALSE;
1784         }
1785
1786         if (newReg.numRects != curBand)
1787         {
1788             prevBand = REGION_Coalesce (&newReg, prevBand, curBand);
1789         }
1790
1791         /*
1792          * If we've finished with a band (bottom == ybot) we skip forward
1793          * in the region to the next band.
1794          */
1795         if (r1->bottom == ybot)
1796         {
1797             r1 = r1BandEnd;
1798         }
1799         if (r2->bottom == ybot)
1800         {
1801             r2 = r2BandEnd;
1802         }
1803     } while ((r1 != r1End) && (r2 != r2End));
1804
1805     /*
1806      * Deal with whichever region still has rectangles left.
1807      */
1808     curBand = newReg.numRects;
1809     if (r1 != r1End)
1810     {
1811         if (nonOverlap1Func != NULL)
1812         {
1813             do
1814             {
1815                 r1BandEnd = r1;
1816                 while ((r1BandEnd < r1End) && (r1BandEnd->top == r1->top))
1817                 {
1818                     r1BandEnd++;
1819                 }
1820                 if (!nonOverlap1Func(&newReg, r1, r1BandEnd, max(r1->top,ybot), r1->bottom))
1821                     return FALSE;
1822                 r1 = r1BandEnd;
1823             } while (r1 != r1End);
1824         }
1825     }
1826     else if ((r2 != r2End) && (nonOverlap2Func != NULL))
1827     {
1828         do
1829         {
1830             r2BandEnd = r2;
1831             while ((r2BandEnd < r2End) && (r2BandEnd->top == r2->top))
1832             {
1833                  r2BandEnd++;
1834             }
1835             if (!nonOverlap2Func(&newReg, r2, r2BandEnd, max(r2->top,ybot), r2->bottom))
1836                 return FALSE;
1837             r2 = r2BandEnd;
1838         } while (r2 != r2End);
1839     }
1840
1841     if (newReg.numRects != curBand)
1842     {
1843         REGION_Coalesce (&newReg, prevBand, curBand);
1844     }
1845
1846     /*
1847      * A bit of cleanup. To keep regions from growing without bound,
1848      * we shrink the array of rectangles to match the new number of
1849      * rectangles in the region. This never goes to 0, however...
1850      *
1851      * Only do this stuff if the number of rectangles allocated is more than
1852      * twice the number of rectangles in the region (a simple optimization...).
1853      */
1854     if ((newReg.numRects < (newReg.size >> 1)) && (newReg.numRects > 2))
1855     {
1856         RECT *new_rects = HeapReAlloc( GetProcessHeap(), 0, newReg.rects, newReg.numRects * sizeof(RECT) );
1857         if (new_rects)
1858         {
1859             newReg.rects = new_rects;
1860             newReg.size = newReg.numRects;
1861         }
1862     }
1863     HeapFree( GetProcessHeap(), 0, destReg->rects );
1864     destReg->rects    = newReg.rects;
1865     destReg->size     = newReg.size;
1866     destReg->numRects = newReg.numRects;
1867     return TRUE;
1868 }
1869
1870 /***********************************************************************
1871  *          Region Intersection
1872  ***********************************************************************/
1873
1874
1875 /***********************************************************************
1876  *           REGION_IntersectO
1877  *
1878  * Handle an overlapping band for REGION_Intersect.
1879  *
1880  * Results:
1881  *      None.
1882  *
1883  * Side Effects:
1884  *      Rectangles may be added to the region.
1885  *
1886  */
1887 static BOOL REGION_IntersectO(WINEREGION *pReg,  RECT *r1, RECT *r1End,
1888                               RECT *r2, RECT *r2End, INT top, INT bottom)
1889
1890 {
1891     INT       left, right;
1892
1893     while ((r1 != r1End) && (r2 != r2End))
1894     {
1895         left = max(r1->left, r2->left);
1896         right = min(r1->right, r2->right);
1897
1898         /*
1899          * If there's any overlap between the two rectangles, add that
1900          * overlap to the new region.
1901          * There's no need to check for subsumption because the only way
1902          * such a need could arise is if some region has two rectangles
1903          * right next to each other. Since that should never happen...
1904          */
1905         if (left < right)
1906         {
1907             if (!add_rect( pReg, left, top, right, bottom )) return FALSE;
1908         }
1909
1910         /*
1911          * Need to advance the pointers. Shift the one that extends
1912          * to the right the least, since the other still has a chance to
1913          * overlap with that region's next rectangle, if you see what I mean.
1914          */
1915         if (r1->right < r2->right)
1916         {
1917             r1++;
1918         }
1919         else if (r2->right < r1->right)
1920         {
1921             r2++;
1922         }
1923         else
1924         {
1925             r1++;
1926             r2++;
1927         }
1928     }
1929     return TRUE;
1930 }
1931
1932 /***********************************************************************
1933  *           REGION_IntersectRegion
1934  */
1935 static BOOL REGION_IntersectRegion(WINEREGION *newReg, WINEREGION *reg1,
1936                                    WINEREGION *reg2)
1937 {
1938    /* check for trivial reject */
1939     if ( (!(reg1->numRects)) || (!(reg2->numRects))  ||
1940         (!overlapping(&reg1->extents, &reg2->extents)))
1941         newReg->numRects = 0;
1942     else
1943         if (!REGION_RegionOp (newReg, reg1, reg2, REGION_IntersectO, NULL, NULL)) return FALSE;
1944
1945     /*
1946      * Can't alter newReg's extents before we call miRegionOp because
1947      * it might be one of the source regions and miRegionOp depends
1948      * on the extents of those regions being the same. Besides, this
1949      * way there's no checking against rectangles that will be nuked
1950      * due to coalescing, so we have to examine fewer rectangles.
1951      */
1952     REGION_SetExtents(newReg);
1953     return TRUE;
1954 }
1955
1956 /***********************************************************************
1957  *           Region Union
1958  ***********************************************************************/
1959
1960 /***********************************************************************
1961  *           REGION_UnionNonO
1962  *
1963  *      Handle a non-overlapping band for the union operation. Just
1964  *      Adds the rectangles into the region. Doesn't have to check for
1965  *      subsumption or anything.
1966  *
1967  * Results:
1968  *      None.
1969  *
1970  * Side Effects:
1971  *      pReg->numRects is incremented and the final rectangles overwritten
1972  *      with the rectangles we're passed.
1973  *
1974  */
1975 static BOOL REGION_UnionNonO(WINEREGION *pReg, RECT *r, RECT *rEnd, INT top, INT bottom)
1976 {
1977     while (r != rEnd)
1978     {
1979         if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE;
1980         r++;
1981     }
1982     return TRUE;
1983 }
1984
1985 /***********************************************************************
1986  *           REGION_UnionO
1987  *
1988  *      Handle an overlapping band for the union operation. Picks the
1989  *      left-most rectangle each time and merges it into the region.
1990  *
1991  * Results:
1992  *      None.
1993  *
1994  * Side Effects:
1995  *      Rectangles are overwritten in pReg->rects and pReg->numRects will
1996  *      be changed.
1997  *
1998  */
1999 static BOOL REGION_UnionO (WINEREGION *pReg, RECT *r1, RECT *r1End,
2000                            RECT *r2, RECT *r2End, INT top, INT bottom)
2001 {
2002 #define MERGERECT(r) \
2003     if ((pReg->numRects != 0) &&  \
2004         (pReg->rects[pReg->numRects-1].top == top) &&  \
2005         (pReg->rects[pReg->numRects-1].bottom == bottom) &&  \
2006         (pReg->rects[pReg->numRects-1].right >= r->left))  \
2007     {  \
2008         if (pReg->rects[pReg->numRects-1].right < r->right)  \
2009             pReg->rects[pReg->numRects-1].right = r->right;  \
2010     }  \
2011     else  \
2012     { \
2013         if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE; \
2014     } \
2015     r++;
2016
2017     while ((r1 != r1End) && (r2 != r2End))
2018     {
2019         if (r1->left < r2->left)
2020         {
2021             MERGERECT(r1);
2022         }
2023         else
2024         {
2025             MERGERECT(r2);
2026         }
2027     }
2028
2029     if (r1 != r1End)
2030     {
2031         do
2032         {
2033             MERGERECT(r1);
2034         } while (r1 != r1End);
2035     }
2036     else while (r2 != r2End)
2037     {
2038         MERGERECT(r2);
2039     }
2040     return TRUE;
2041 #undef MERGERECT
2042 }
2043
2044 /***********************************************************************
2045  *           REGION_UnionRegion
2046  */
2047 static BOOL REGION_UnionRegion(WINEREGION *newReg, WINEREGION *reg1, WINEREGION *reg2)
2048 {
2049     BOOL ret = TRUE;
2050
2051     /*  checks all the simple cases */
2052
2053     /*
2054      * Region 1 and 2 are the same or region 1 is empty
2055      */
2056     if ( (reg1 == reg2) || (!(reg1->numRects)) )
2057     {
2058         if (newReg != reg2)
2059             ret = REGION_CopyRegion(newReg, reg2);
2060         return ret;
2061     }
2062
2063     /*
2064      * if nothing to union (region 2 empty)
2065      */
2066     if (!(reg2->numRects))
2067     {
2068         if (newReg != reg1)
2069             ret = REGION_CopyRegion(newReg, reg1);
2070         return ret;
2071     }
2072
2073     /*
2074      * Region 1 completely subsumes region 2
2075      */
2076     if ((reg1->numRects == 1) &&
2077         (reg1->extents.left <= reg2->extents.left) &&
2078         (reg1->extents.top <= reg2->extents.top) &&
2079         (reg1->extents.right >= reg2->extents.right) &&
2080         (reg1->extents.bottom >= reg2->extents.bottom))
2081     {
2082         if (newReg != reg1)
2083             ret = REGION_CopyRegion(newReg, reg1);
2084         return ret;
2085     }
2086
2087     /*
2088      * Region 2 completely subsumes region 1
2089      */
2090     if ((reg2->numRects == 1) &&
2091         (reg2->extents.left <= reg1->extents.left) &&
2092         (reg2->extents.top <= reg1->extents.top) &&
2093         (reg2->extents.right >= reg1->extents.right) &&
2094         (reg2->extents.bottom >= reg1->extents.bottom))
2095     {
2096         if (newReg != reg2)
2097             ret = REGION_CopyRegion(newReg, reg2);
2098         return ret;
2099     }
2100
2101     if ((ret = REGION_RegionOp (newReg, reg1, reg2, REGION_UnionO, REGION_UnionNonO, REGION_UnionNonO)))
2102     {
2103         newReg->extents.left = min(reg1->extents.left, reg2->extents.left);
2104         newReg->extents.top = min(reg1->extents.top, reg2->extents.top);
2105         newReg->extents.right = max(reg1->extents.right, reg2->extents.right);
2106         newReg->extents.bottom = max(reg1->extents.bottom, reg2->extents.bottom);
2107     }
2108     return ret;
2109 }
2110
2111 /***********************************************************************
2112  *           Region Subtraction
2113  ***********************************************************************/
2114
2115 /***********************************************************************
2116  *           REGION_SubtractNonO1
2117  *
2118  *      Deal with non-overlapping band for subtraction. Any parts from
2119  *      region 2 we discard. Anything from region 1 we add to the region.
2120  *
2121  * Results:
2122  *      None.
2123  *
2124  * Side Effects:
2125  *      pReg may be affected.
2126  *
2127  */
2128 static BOOL REGION_SubtractNonO1 (WINEREGION *pReg, RECT *r, RECT *rEnd, INT top, INT bottom)
2129 {
2130     while (r != rEnd)
2131     {
2132         if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE;
2133         r++;
2134     }
2135     return TRUE;
2136 }
2137
2138
2139 /***********************************************************************
2140  *           REGION_SubtractO
2141  *
2142  *      Overlapping band subtraction. x1 is the left-most point not yet
2143  *      checked.
2144  *
2145  * Results:
2146  *      None.
2147  *
2148  * Side Effects:
2149  *      pReg may have rectangles added to it.
2150  *
2151  */
2152 static BOOL REGION_SubtractO (WINEREGION *pReg, RECT *r1, RECT *r1End,
2153                               RECT *r2, RECT *r2End, INT top, INT bottom)
2154 {
2155     INT left = r1->left;
2156
2157     while ((r1 != r1End) && (r2 != r2End))
2158     {
2159         if (r2->right <= left)
2160         {
2161             /*
2162              * Subtrahend missed the boat: go to next subtrahend.
2163              */
2164             r2++;
2165         }
2166         else if (r2->left <= left)
2167         {
2168             /*
2169              * Subtrahend precedes minuend: nuke left edge of minuend.
2170              */
2171             left = r2->right;
2172             if (left >= r1->right)
2173             {
2174                 /*
2175                  * Minuend completely covered: advance to next minuend and
2176                  * reset left fence to edge of new minuend.
2177                  */
2178                 r1++;
2179                 if (r1 != r1End)
2180                     left = r1->left;
2181             }
2182             else
2183             {
2184                 /*
2185                  * Subtrahend now used up since it doesn't extend beyond
2186                  * minuend
2187                  */
2188                 r2++;
2189             }
2190         }
2191         else if (r2->left < r1->right)
2192         {
2193             /*
2194              * Left part of subtrahend covers part of minuend: add uncovered
2195              * part of minuend to region and skip to next subtrahend.
2196              */
2197             if (!add_rect( pReg, left, top, r2->left, bottom )) return FALSE;
2198             left = r2->right;
2199             if (left >= r1->right)
2200             {
2201                 /*
2202                  * Minuend used up: advance to new...
2203                  */
2204                 r1++;
2205                 if (r1 != r1End)
2206                     left = r1->left;
2207             }
2208             else
2209             {
2210                 /*
2211                  * Subtrahend used up
2212                  */
2213                 r2++;
2214             }
2215         }
2216         else
2217         {
2218             /*
2219              * Minuend used up: add any remaining piece before advancing.
2220              */
2221             if (r1->right > left)
2222             {
2223                 if (!add_rect( pReg, left, top, r1->right, bottom )) return FALSE;
2224             }
2225             r1++;
2226             if (r1 != r1End)
2227                 left = r1->left;
2228         }
2229     }
2230
2231     /*
2232      * Add remaining minuend rectangles to region.
2233      */
2234     while (r1 != r1End)
2235     {
2236         if (!add_rect( pReg, left, top, r1->right, bottom )) return FALSE;
2237         r1++;
2238         if (r1 != r1End)
2239         {
2240             left = r1->left;
2241         }
2242     }
2243     return TRUE;
2244 }
2245
2246 /***********************************************************************
2247  *           REGION_SubtractRegion
2248  *
2249  *      Subtract regS from regM and leave the result in regD.
2250  *      S stands for subtrahend, M for minuend and D for difference.
2251  *
2252  * Results:
2253  *      TRUE.
2254  *
2255  * Side Effects:
2256  *      regD is overwritten.
2257  *
2258  */
2259 static BOOL REGION_SubtractRegion(WINEREGION *regD, WINEREGION *regM, WINEREGION *regS )
2260 {
2261    /* check for trivial reject */
2262     if ( (!(regM->numRects)) || (!(regS->numRects))  ||
2263         (!overlapping(&regM->extents, &regS->extents)) )
2264         return REGION_CopyRegion(regD, regM);
2265
2266     if (!REGION_RegionOp (regD, regM, regS, REGION_SubtractO, REGION_SubtractNonO1, NULL))
2267         return FALSE;
2268
2269     /*
2270      * Can't alter newReg's extents before we call miRegionOp because
2271      * it might be one of the source regions and miRegionOp depends
2272      * on the extents of those regions being the unaltered. Besides, this
2273      * way there's no checking against rectangles that will be nuked
2274      * due to coalescing, so we have to examine fewer rectangles.
2275      */
2276     REGION_SetExtents (regD);
2277     return TRUE;
2278 }
2279
2280 /***********************************************************************
2281  *           REGION_XorRegion
2282  */
2283 static BOOL REGION_XorRegion(WINEREGION *dr, WINEREGION *sra, WINEREGION *srb)
2284 {
2285     WINEREGION tra, trb;
2286     BOOL ret;
2287
2288     if (!init_region( &tra, sra->numRects + 1 )) return FALSE;
2289     if ((ret = init_region( &trb, srb->numRects + 1 )))
2290     {
2291         ret = REGION_SubtractRegion(&tra,sra,srb) &&
2292               REGION_SubtractRegion(&trb,srb,sra) &&
2293               REGION_UnionRegion(dr,&tra,&trb);
2294         destroy_region(&trb);
2295     }
2296     destroy_region(&tra);
2297     return ret;
2298 }
2299
2300 /**************************************************************************
2301  *
2302  *    Poly Regions
2303  *
2304  *************************************************************************/
2305
2306 #define LARGE_COORDINATE  0x7fffffff /* FIXME */
2307 #define SMALL_COORDINATE  0x80000000
2308
2309 /***********************************************************************
2310  *     REGION_InsertEdgeInET
2311  *
2312  *     Insert the given edge into the edge table.
2313  *     First we must find the correct bucket in the
2314  *     Edge table, then find the right slot in the
2315  *     bucket.  Finally, we can insert it.
2316  *
2317  */
2318 static void REGION_InsertEdgeInET(EdgeTable *ET, EdgeTableEntry *ETE,
2319                 INT scanline, ScanLineListBlock **SLLBlock, INT *iSLLBlock)
2320
2321 {
2322     struct list *ptr;
2323     ScanLineList *pSLL, *pPrevSLL;
2324     ScanLineListBlock *tmpSLLBlock;
2325
2326     /*
2327      * find the right bucket to put the edge into
2328      */
2329     pPrevSLL = &ET->scanlines;
2330     pSLL = pPrevSLL->next;
2331     while (pSLL && (pSLL->scanline < scanline))
2332     {
2333         pPrevSLL = pSLL;
2334         pSLL = pSLL->next;
2335     }
2336
2337     /*
2338      * reassign pSLL (pointer to ScanLineList) if necessary
2339      */
2340     if ((!pSLL) || (pSLL->scanline > scanline))
2341     {
2342         if (*iSLLBlock > SLLSPERBLOCK-1)
2343         {
2344             tmpSLLBlock = HeapAlloc( GetProcessHeap(), 0, sizeof(ScanLineListBlock));
2345             if(!tmpSLLBlock)
2346             {
2347                 WARN("Can't alloc SLLB\n");
2348                 return;
2349             }
2350             (*SLLBlock)->next = tmpSLLBlock;
2351             tmpSLLBlock->next = NULL;
2352             *SLLBlock = tmpSLLBlock;
2353             *iSLLBlock = 0;
2354         }
2355         pSLL = &((*SLLBlock)->SLLs[(*iSLLBlock)++]);
2356
2357         pSLL->next = pPrevSLL->next;
2358         list_init( &pSLL->edgelist );
2359         pPrevSLL->next = pSLL;
2360     }
2361     pSLL->scanline = scanline;
2362
2363     /*
2364      * now insert the edge in the right bucket
2365      */
2366     LIST_FOR_EACH( ptr, &pSLL->edgelist )
2367     {
2368         struct edge_table_entry *entry = LIST_ENTRY( ptr, struct edge_table_entry, entry );
2369         if (entry->bres.minor_axis >= ETE->bres.minor_axis) break;
2370     }
2371     list_add_before( ptr, &ETE->entry );
2372 }
2373
2374 /***********************************************************************
2375  *     REGION_CreateEdgeTable
2376  *
2377  *     This routine creates the edge table for
2378  *     scan converting polygons.
2379  *     The Edge Table (ET) looks like:
2380  *
2381  *    EdgeTable
2382  *     --------
2383  *    |  ymax  |        ScanLineLists
2384  *    |scanline|-->------------>-------------->...
2385  *     --------   |scanline|   |scanline|
2386  *                |edgelist|   |edgelist|
2387  *                ---------    ---------
2388  *                    |             |
2389  *                    |             |
2390  *                    V             V
2391  *              list of ETEs   list of ETEs
2392  *
2393  *     where ETE is an EdgeTableEntry data structure,
2394  *     and there is one ScanLineList per scanline at
2395  *     which an edge is initially entered.
2396  *
2397  */
2398 static void REGION_CreateEdgeTable(const INT *Count, INT nbpolygons,
2399             const POINT *pts, EdgeTable *ET,
2400             EdgeTableEntry *pETEs, ScanLineListBlock *pSLLBlock)
2401 {
2402     const POINT *top, *bottom;
2403     const POINT *PrevPt, *CurrPt, *EndPt;
2404     INT poly, count;
2405     int iSLLBlock = 0;
2406     int dy;
2407
2408     /*
2409      *  initialize the Edge Table.
2410      */
2411     ET->scanlines.next = NULL;
2412     ET->ymax = SMALL_COORDINATE;
2413     ET->ymin = LARGE_COORDINATE;
2414     pSLLBlock->next = NULL;
2415
2416     EndPt = pts - 1;
2417     for(poly = 0; poly < nbpolygons; poly++)
2418     {
2419         count = Count[poly];
2420         EndPt += count;
2421         if(count < 2)
2422             continue;
2423
2424         PrevPt = EndPt;
2425
2426     /*
2427      *  for each vertex in the array of points.
2428      *  In this loop we are dealing with two vertices at
2429      *  a time -- these make up one edge of the polygon.
2430      */
2431         while (count--)
2432         {
2433             CurrPt = pts++;
2434
2435         /*
2436          *  find out which point is above and which is below.
2437          */
2438             if (PrevPt->y > CurrPt->y)
2439             {
2440                 bottom = PrevPt, top = CurrPt;
2441                 pETEs->ClockWise = 0;
2442             }
2443             else
2444             {
2445                 bottom = CurrPt, top = PrevPt;
2446                 pETEs->ClockWise = 1;
2447             }
2448
2449         /*
2450          * don't add horizontal edges to the Edge table.
2451          */
2452             if (bottom->y != top->y)
2453             {
2454                 pETEs->ymax = bottom->y-1;
2455                                 /* -1 so we don't get last scanline */
2456
2457             /*
2458              *  initialize integer edge algorithm
2459              */
2460                 dy = bottom->y - top->y;
2461                 bres_init_polygon(dy, top->x, bottom->x, &pETEs->bres);
2462
2463                 REGION_InsertEdgeInET(ET, pETEs, top->y, &pSLLBlock,
2464                                                                 &iSLLBlock);
2465
2466                 if (PrevPt->y > ET->ymax)
2467                   ET->ymax = PrevPt->y;
2468                 if (PrevPt->y < ET->ymin)
2469                   ET->ymin = PrevPt->y;
2470                 pETEs++;
2471             }
2472
2473             PrevPt = CurrPt;
2474         }
2475     }
2476 }
2477
2478 /***********************************************************************
2479  *     REGION_loadAET
2480  *
2481  *     This routine moves EdgeTableEntries from the
2482  *     EdgeTable into the Active Edge Table,
2483  *     leaving them sorted by smaller x coordinate.
2484  *
2485  */
2486 static void REGION_loadAET( struct list *AET, struct list *ETEs )
2487 {
2488     struct edge_table_entry *ptr, *next, *entry;
2489     struct list *active;
2490
2491     LIST_FOR_EACH_ENTRY_SAFE( ptr, next, ETEs, struct edge_table_entry, entry )
2492     {
2493         LIST_FOR_EACH( active, AET )
2494         {
2495             entry = LIST_ENTRY( active, struct edge_table_entry, entry );
2496             if (entry->bres.minor_axis >= ptr->bres.minor_axis) break;
2497         }
2498         list_remove( &ptr->entry );
2499         list_add_before( active, &ptr->entry );
2500     }
2501 }
2502
2503 /***********************************************************************
2504  *     REGION_computeWAET
2505  *
2506  *     This routine links the AET by the
2507  *     nextWETE (winding EdgeTableEntry) link for
2508  *     use by the winding number rule.  The final
2509  *     Active Edge Table (AET) might look something
2510  *     like:
2511  *
2512  *     AET
2513  *     ----------  ---------   ---------
2514  *     |ymax    |  |ymax    |  |ymax    |
2515  *     | ...    |  |...     |  |...     |
2516  *     |next    |->|next    |->|next    |->...
2517  *     |nextWETE|  |nextWETE|  |nextWETE|
2518  *     ---------   ---------   ^--------
2519  *         |                   |       |
2520  *         V------------------->       V---> ...
2521  *
2522  */
2523 static void REGION_computeWAET( struct list *AET, struct list *WETE )
2524 {
2525     struct edge_table_entry *active;
2526     int inside = 1;
2527     int isInside = 0;
2528
2529     list_init( WETE );
2530     LIST_FOR_EACH_ENTRY( active, AET, struct edge_table_entry, entry )
2531     {
2532         if (active->ClockWise)
2533             isInside++;
2534         else
2535             isInside--;
2536
2537         if ((!inside && !isInside) || (inside && isInside))
2538         {
2539             list_add_tail( WETE, &active->winding_entry );
2540             inside = !inside;
2541         }
2542     }
2543 }
2544
2545 /***********************************************************************
2546  *     REGION_InsertionSort
2547  *
2548  *     Just a simple insertion sort to sort the Active Edge Table.
2549  *
2550  */
2551 static BOOL REGION_InsertionSort( struct list *AET )
2552 {
2553     struct edge_table_entry *active, *next, *insert;
2554     BOOL changed = FALSE;
2555
2556     LIST_FOR_EACH_ENTRY_SAFE( active, next, AET, struct edge_table_entry, entry )
2557     {
2558         LIST_FOR_EACH_ENTRY( insert, AET, struct edge_table_entry, entry )
2559         {
2560             if (insert == active) break;
2561             if (insert->bres.minor_axis > active->bres.minor_axis) break;
2562         }
2563         if (insert == active) continue;
2564         list_remove( &active->entry );
2565         list_add_before( &insert->entry, &active->entry );
2566         changed = TRUE;
2567     }
2568     return changed;
2569 }
2570
2571 /***********************************************************************
2572  *     REGION_FreeStorage
2573  *
2574  *     Clean up our act.
2575  */
2576 static void REGION_FreeStorage(ScanLineListBlock *pSLLBlock)
2577 {
2578     ScanLineListBlock   *tmpSLLBlock;
2579
2580     while (pSLLBlock)
2581     {
2582         tmpSLLBlock = pSLLBlock->next;
2583         HeapFree( GetProcessHeap(), 0, pSLLBlock );
2584         pSLLBlock = tmpSLLBlock;
2585     }
2586 }
2587
2588
2589 /***********************************************************************
2590  *     REGION_PtsToRegion
2591  *
2592  *     Create an array of rectangles from a list of points.
2593  */
2594 static BOOL REGION_PtsToRegion( struct point_block *FirstPtBlock, WINEREGION *reg )
2595 {
2596     RECT *rects;
2597     POINT *pts;
2598     struct point_block *pb;
2599     int i;
2600     RECT *extents;
2601     INT numRects;
2602
2603     extents = &reg->extents;
2604
2605     for (pb = FirstPtBlock, numRects = 0; pb; pb = pb->next) numRects += pb->count;
2606     if (!init_region( reg, numRects )) return FALSE;
2607
2608     reg->size = numRects;
2609     rects = reg->rects - 1;
2610     numRects = 0;
2611     extents->left = LARGE_COORDINATE,  extents->right = SMALL_COORDINATE;
2612
2613     for (pb = FirstPtBlock; pb; pb = pb->next)
2614     {
2615         /* the loop uses 2 points per iteration */
2616         i = pb->count / 2;
2617         for (pts = pb->pts; i--; pts += 2) {
2618             if (pts->x == pts[1].x)
2619                 continue;
2620             if (numRects && pts->x == rects->left && pts->y == rects->bottom &&
2621                 pts[1].x == rects->right &&
2622                 (numRects == 1 || rects[-1].top != rects->top) &&
2623                 (i && pts[2].y > pts[1].y)) {
2624                 rects->bottom = pts[1].y + 1;
2625                 continue;
2626             }
2627             numRects++;
2628             rects++;
2629             rects->left = pts->x;  rects->top = pts->y;
2630             rects->right = pts[1].x;  rects->bottom = pts[1].y + 1;
2631             if (rects->left < extents->left)
2632                 extents->left = rects->left;
2633             if (rects->right > extents->right)
2634                 extents->right = rects->right;
2635         }
2636     }
2637
2638     if (numRects) {
2639         extents->top = reg->rects->top;
2640         extents->bottom = rects->bottom;
2641     } else {
2642         extents->left = 0;
2643         extents->top = 0;
2644         extents->right = 0;
2645         extents->bottom = 0;
2646     }
2647     reg->numRects = numRects;
2648
2649     return(TRUE);
2650 }
2651
2652 /***********************************************************************
2653  *           CreatePolyPolygonRgn    (GDI32.@)
2654  */
2655 HRGN WINAPI CreatePolyPolygonRgn(const POINT *Pts, const INT *Count,
2656                       INT nbpolygons, INT mode)
2657 {
2658     HRGN hrgn = 0;
2659     WINEREGION *obj;
2660     INT y;                           /* current scanline        */
2661     struct list WETE, *pWETE;        /* Winding Edge Table */
2662     ScanLineList *pSLL;              /* current scanLineList    */
2663     EdgeTable ET;                    /* header node for ET      */
2664     struct list AET;                 /* header for AET     */
2665     EdgeTableEntry *pETEs;           /* EdgeTableEntries pool   */
2666     ScanLineListBlock SLLBlock;      /* header for scanlinelist */
2667     int fixWAET = FALSE;
2668     struct point_block FirstPtBlock, *block; /* PtBlock buffers    */
2669     struct edge_table_entry *active, *next;
2670     INT poly, total;
2671
2672     TRACE("%p, count %d, polygons %d, mode %d\n", Pts, *Count, nbpolygons, mode);
2673
2674     /* special case a rectangle */
2675
2676     if (((nbpolygons == 1) && ((*Count == 4) ||
2677        ((*Count == 5) && (Pts[4].x == Pts[0].x) && (Pts[4].y == Pts[0].y)))) &&
2678         (((Pts[0].y == Pts[1].y) &&
2679           (Pts[1].x == Pts[2].x) &&
2680           (Pts[2].y == Pts[3].y) &&
2681           (Pts[3].x == Pts[0].x)) ||
2682          ((Pts[0].x == Pts[1].x) &&
2683           (Pts[1].y == Pts[2].y) &&
2684           (Pts[2].x == Pts[3].x) &&
2685           (Pts[3].y == Pts[0].y))))
2686         return CreateRectRgn( min(Pts[0].x, Pts[2].x), min(Pts[0].y, Pts[2].y),
2687                               max(Pts[0].x, Pts[2].x), max(Pts[0].y, Pts[2].y) );
2688
2689     for(poly = total = 0; poly < nbpolygons; poly++)
2690         total += Count[poly];
2691     if (! (pETEs = HeapAlloc( GetProcessHeap(), 0, sizeof(EdgeTableEntry) * total )))
2692         return 0;
2693
2694     REGION_CreateEdgeTable(Count, nbpolygons, Pts, &ET, pETEs, &SLLBlock);
2695     list_init( &AET );
2696     pSLL = ET.scanlines.next;
2697     block = &FirstPtBlock;
2698     FirstPtBlock.count = 0;
2699     FirstPtBlock.next  = NULL;
2700
2701     if (mode != WINDING) {
2702         /*
2703          *  for each scanline
2704          */
2705         for (y = ET.ymin; y < ET.ymax; y++) {
2706             /*
2707              *  Add a new edge to the active edge table when we
2708              *  get to the next edge.
2709              */
2710             if (pSLL != NULL && y == pSLL->scanline) {
2711                 REGION_loadAET(&AET, &pSLL->edgelist);
2712                 pSLL = pSLL->next;
2713             }
2714
2715             LIST_FOR_EACH_ENTRY_SAFE( active, next, &AET, struct edge_table_entry, entry )
2716             {
2717                 block = add_point( block, active->bres.minor_axis, y );
2718                 if (!block) goto done;
2719
2720                 if (active->ymax == y)  /* leaving this edge */
2721                     list_remove( &active->entry );
2722                 else
2723                     bres_incr_polygon( &active->bres );
2724             }
2725             REGION_InsertionSort(&AET);
2726         }
2727     }
2728     else {
2729         /*
2730          *  for each scanline
2731          */
2732         for (y = ET.ymin; y < ET.ymax; y++) {
2733             /*
2734              *  Add a new edge to the active edge table when we
2735              *  get to the next edge.
2736              */
2737             if (pSLL != NULL && y == pSLL->scanline) {
2738                 REGION_loadAET(&AET, &pSLL->edgelist);
2739                 REGION_computeWAET( &AET, &WETE );
2740                 pSLL = pSLL->next;
2741             }
2742             pWETE = list_head( &WETE );
2743
2744             /*
2745              *  for each active edge
2746              */
2747             LIST_FOR_EACH_ENTRY_SAFE( active, next, &AET, struct edge_table_entry, entry )
2748             {
2749                 /*
2750                  *  add to the buffer only those edges that
2751                  *  are in the Winding active edge table.
2752                  */
2753                 if (pWETE == &active->winding_entry) {
2754                     block = add_point( block, active->bres.minor_axis, y );
2755                     if (!block) goto done;
2756                     pWETE = list_next( &WETE, pWETE );
2757                 }
2758                 if (active->ymax == y)  /* leaving this edge */
2759                 {
2760                     list_remove( &active->entry );
2761                     fixWAET = TRUE;
2762                 }
2763                 else
2764                     bres_incr_polygon( &active->bres );
2765             }
2766
2767             /*
2768              *  recompute the winding active edge table if
2769              *  we just resorted or have exited an edge.
2770              */
2771             if (REGION_InsertionSort(&AET) || fixWAET) {
2772                 REGION_computeWAET( &AET, &WETE );
2773                 fixWAET = FALSE;
2774             }
2775         }
2776     }
2777
2778     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) goto done;
2779
2780     if (!REGION_PtsToRegion(&FirstPtBlock, obj))
2781     {
2782         HeapFree( GetProcessHeap(), 0, obj );
2783         goto done;
2784     }
2785     if (!(hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs )))
2786     {
2787         HeapFree( GetProcessHeap(), 0, obj->rects );
2788         HeapFree( GetProcessHeap(), 0, obj );
2789     }
2790
2791 done:
2792     REGION_FreeStorage(SLLBlock.next);
2793     free_point_blocks( FirstPtBlock.next );
2794     HeapFree( GetProcessHeap(), 0, pETEs );
2795     return hrgn;
2796 }
2797
2798
2799 /***********************************************************************
2800  *           CreatePolygonRgn    (GDI32.@)
2801  */
2802 HRGN WINAPI CreatePolygonRgn( const POINT *points, INT count,
2803                                   INT mode )
2804 {
2805     return CreatePolyPolygonRgn( points, &count, 1, mode );
2806 }