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